private string PostEntryWarehouseInventory()
 {
     try
     {
         var model = new WarehouseInventory()
         {
             AllowBackorder            = true,
             AllowPreorder             = true,
             BackorderAvailabilityDate = DateTime.UtcNow,
             BackorderQuantity         = 2,
             CatalogEntryCode          = "Accessories-Electronics-200WattsAMFMCDReciever-sku",
             InStockQuantity           = 23,
             InventoryStatus           = "Enabled",
             PreorderAvailabilityDate  = DateTime.UtcNow,
             PreorderQuantity          = 3,
             ReorderMinQuantity        = 1,
             ReservedQuantity          = 1,
             WarehouseCode             = "WELLINGTON"
         };
         var json   = JsonConvert.SerializeObject(model);
         var xml    = SerializeObjectToXml(typeof(WarehouseInventory), model);
         var result = Post("/episerverapi/commerce/entries/Accessories-Electronics-200WattsAMFMCDReciever-sku/inventories", new StringContent(json, Encoding.UTF8, "application/json")).Result.Content.ReadAsStringAsync().Result;
         WriteTextFile(Path.Combine(_warehouseInventoryOutputPath, "PostJson.txt"), result);
         result = Post("/episerverapi/commerce/entries/Accessories-Electronics-200WattsAMFMCDReciever-sku/inventories", new StringContent(xml, Encoding.UTF8, "text/xml")).Result.Content.ReadAsStringAsync().Result;
         WriteTextFile(Path.Combine(_warehouseInventoryOutputPath, "PostXml.xml"), result);
         return("Post entry warehouse inventory complete.....");
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
Esempio n. 2
0
    /// <summary>
    /// Executes a purchase for the specified items. Validation will check if there is enough money AND inventory space. If both are true, deducts money and adds item to inventory.
    /// </summary>
    /// <param name="item">The item(s) to purchase.</param>
    /// <param name="discount">The discount percentage on the price of the item(s).</param>
    /// <param name="performValidation">Set to false only if money AND inventory space has already been validated.</param>
    /// <param name="result"></param>
    /// <returns></returns>
    public bool PurchaseItem(OrderItem item, float discount, bool performValidation, out string result)
    {
        bool successful = false;

        result = GameMaster.MSG_ERR_DEFAULT;

        float totalCost      = GameMaster.DiscountPrice(item.TotalValue(), discount);
        float totalSpaceUsed = item.TotalSpaceUsed();

        bool valid = true;

        if (performValidation)
        {
            valid = ValidatePurchaseItem(totalCost, out result);

            if (valid)
            {
                valid = WarehouseInventory.ValidateAddItem(totalSpaceUsed, out result);
            }
        }

        if (valid)
        {
            DecreaseMoney(totalCost);
            WarehouseInventory.AddItem(item, false, out result);

            successful = true;
            result     = string.Format("Purchase successful: {0}", result);
        }

        return(successful);
    }
Esempio n. 3
0
        /// <summary>
        /// Determines whether the specific inventory has enough quantity for the line item.
        /// </summary>
        /// <param name="inventory">The inventory.</param>
        /// <param name="lineItem">The line item.</param>
        /// <returns>
        ///   <c>true</c> if has enough quantity; otherwise, <c>false</c>.
        /// </returns>
        private bool IsEnoughQuantity(IWarehouseInventory inventory, LineItem lineItem)
        {
            //TODO: Consolidate with CheckInventoryActivity
            decimal quantity = lineItem.Quantity;

            if (lineItem.InventoryStatus == (int)InventoryTrackingStatus.Enabled)
            {
                var entry = CatalogContext.Current.GetCatalogEntry(lineItem.CatalogEntryId, CatalogEntryResponseGroup_InfoWithVariations);
                if (inventory == null)
                {
                    // Treat missing as zeroes
                    inventory = new WarehouseInventory();
                    ((WarehouseInventory)inventory).InventoryStatus = InventoryTrackingStatus.Enabled;
                }
                if (entry.StartDate > FrameworkContext.Current.CurrentDateTime)
                {
                    //not allow preorder or preorder is not available
                    if (!inventory.AllowPreorder || inventory.PreorderAvailabilityDate > FrameworkContext.Current.CurrentDateTime)
                    {
                        return(false);
                    }
                    //allow preorder but quantity is not enough
                    if (quantity > inventory.PreorderQuantity)
                    {
                        return(false);
                    }
                }
                if (inventory.InStockQuantity > 0 && inventory.InStockQuantity >= inventory.ReservedQuantity + quantity)
                {
                    return(true);
                }

                //Not enough quantity in stock, check for backorder
                if (!inventory.AllowBackorder)
                {
                    return(false);
                }
                //Backorder is not available
                if (inventory.BackorderAvailabilityDate > FrameworkContext.Current.CurrentDateTime)
                {
                    return(false);
                }
                //Backorder quantity is not enough
                if (quantity > inventory.InStockQuantity -
                    inventory.ReservedQuantity + inventory.BackorderQuantity)
                {
                    return(false);
                }
            }
            return(true);
        }
        private ShoppingCartRuleResult PerformRules(ShoppingCart_V02 cart,
                                                    ShoppingCartRuleReason reason,
                                                    ShoppingCartRuleResult Result)
        {
            if (reason == ShoppingCartRuleReason.CartItemsBeingAdded)
            {
                bool bEventTicket = isEventTicket(cart.DistributorID, Locale);
                var  thisCart     = cart as MyHLShoppingCart;
                if (null != thisCart)
                {
                    //Kiosk items must have inventory
                    string             sku                = thisCart.CurrentItems[0].SKU;
                    var                catItem            = CatalogProvider.GetCatalogItem(sku, Country);
                    WarehouseInventory warehouseInventory = null;

                    var isSplitted = false;

                    if (thisCart.DeliveryInfo != null && thisCart.DeliveryInfo.Option == ServiceProvider.ShippingSvc.DeliveryOptionType.Shipping &&
                        HLConfigManager.Configurations.DOConfiguration.WhCodesForSplit.Contains(thisCart.DeliveryInfo.WarehouseCode))
                    {
                        //split order scenario
                        ShoppingCartProvider.CheckInventory(catItem, thisCart.CurrentItems[0].Quantity, thisCart.DeliveryInfo.WarehouseCode, thisCart.DeliveryInfo.FreightCode, ref isSplitted);
                    }


                    if (!isSplitted && null != thisCart.DeliveryInfo && !string.IsNullOrEmpty(thisCart.DeliveryInfo.WarehouseCode) && !bEventTicket && !isNonInventoryItem(sku))
                    {
                        catItem.InventoryList.TryGetValue(thisCart.DeliveryInfo.WarehouseCode, out warehouseInventory);
                        if ((warehouseInventory != null && (warehouseInventory as WarehouseInventory_V01).QuantityAvailable <= 0) || warehouseInventory == null)
                        {
                            Result.AddMessage(string.Format(HttpContext.GetGlobalResourceObject(string.Format("{0}_ErrorMessage", HLConfigManager.Platform), "BackOrderItem").ToString(), sku));
                            Result.Result = RulesResult.Failure;
                            cart.RuleResults.Add(Result);
                        }
                        else
                        {
                            int availQuantity = InventoryHelper.CheckInventory(thisCart, thisCart.CurrentItems[0].Quantity, catItem, thisCart.DeliveryInfo.WarehouseCode);
                            if (availQuantity - thisCart.CurrentItems[0].Quantity < 0)
                            {
                                Result.AddMessage(string.Format(HttpContext.GetGlobalResourceObject(string.Format("{0}_ErrorMessage", HLConfigManager.Platform), "OutOfInventory").ToString(), sku));
                                Result.Result = RulesResult.Failure;
                                cart.RuleResults.Add(Result);
                            }
                        }
                    }
                }
            }

            return(Result);
        }
        protected void AdjustOrderInventoryFromWarehouse(PurchaseOrderModel order)
        {
            var warehouseRepository = ServiceLocator.Current.GetInstance<IWarehouseRepository>();
            var warehousesCache = warehouseRepository.List();
            var warehouseInventory = ServiceLocator.Current.GetInstance<IWarehouseInventoryService>();

            var expirationCandidates = new HashSet<ProductContent>();

            var referenceConverter = ServiceLocator.Current.GetInstance<ReferenceConverter>();
            var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();

            // Adjust inventory
            foreach (var f in order.OrderForms)
            {
                foreach (var i in f.LineItems)
                {
                    try
                    {
                        var warehouse = warehousesCache.First(w => w.Code == i.WarehouseCode);
                        var catalogEntry = CatalogContext.Current.GetCatalogEntry((string) i.CatalogEntryId);
                        var catalogKey = new CatalogKey(catalogEntry);
                        var inventory = new WarehouseInventory(warehouseInventory.Get(catalogKey, warehouse));

                        inventory.InStockQuantity = inventory.InStockQuantity - i.Quantity;
                        if (inventory.InStockQuantity <= 0)
                        {
                            var contentLink = referenceConverter.GetContentLink(i.CatalogEntryId);
                            var variant = contentRepository.Get<VariationContent>(contentLink);

                            expirationCandidates.Add((ProductContent) variant.GetParent());
                        }

                        // NOTE! Default implementation is to NOT save the inventory here,
                        // as it will subtract double if the workflows also do this.
                        // warehouseInventory.Save(inventory);
                    }
                    catch (Exception ex)
                    {
                        Log.Error("Unable to adjust inventory.", ex);
                    }
                }
            }

            // TODO: Determine if you want to unpublish products with no sellable variants
            ExpireProductsWithNoInventory(expirationCandidates, contentRepository);
            // Alterntive approach is to notify the commerce admin about the products without inventory
        }
Esempio n. 6
0
        protected void AdjustOrderInventoryFromWarehouse(PurchaseOrderModel order)
        {
            var warehouseRepository = ServiceLocator.Current.GetInstance <IWarehouseRepository>();
            var warehousesCache     = warehouseRepository.List();
            var warehouseInventory  = ServiceLocator.Current.GetInstance <IWarehouseInventoryService>();

            var expirationCandidates = new HashSet <ProductContent>();

            var referenceConverter = ServiceLocator.Current.GetInstance <ReferenceConverter>();
            var contentRepository  = ServiceLocator.Current.GetInstance <IContentRepository>();

            // Adjust inventory
            foreach (var f in order.OrderForms)
            {
                foreach (var i in f.LineItems)
                {
                    try
                    {
                        var warehouse    = warehousesCache.First(w => w.Code == i.WarehouseCode);
                        var catalogEntry = CatalogContext.Current.GetCatalogEntry((string)i.CatalogEntryId);
                        var catalogKey   = new CatalogKey(catalogEntry);
                        var inventory    = new WarehouseInventory(warehouseInventory.Get(catalogKey, warehouse));

                        inventory.InStockQuantity = inventory.InStockQuantity - i.Quantity;
                        if (inventory.InStockQuantity <= 0)
                        {
                            var contentLink = referenceConverter.GetContentLink(i.CatalogEntryId);
                            var variant     = contentRepository.Get <VariationContent>(contentLink);

                            expirationCandidates.Add((ProductContent)variant.GetParent());
                        }

                        // NOTE! Default implementation is to NOT save the inventory here,
                        // as it will subtract double if the workflows also do this.
                        // warehouseInventory.Save(inventory);
                    }
                    catch (Exception ex)
                    {
                        Log.Error("Unable to adjust inventory.", ex);
                    }
                }
            }

            // TODO: Determine if you want to unpublish products with no sellable variants
            ExpireProductsWithNoInventory(expirationCandidates, contentRepository);
            // Alterntive approach is to notify the commerce admin about the products without inventory
        }
        private ShoppingCartRuleResult AddToCart(MyHLShoppingCart cart,
                                                 ShoppingCartRuleResult Result,
                                                 string SkuToBeAdded)
        {
            var allSkus = CatalogProvider.GetAllSKU(Locale);

            if (!allSkus.Keys.Contains(SkuToBeAdded))
            {
                if (Environment.MachineName.IndexOf("PROD") < 0)
                {
                    var    country = new RegionInfo(new CultureInfo(Locale, false).LCID);
                    string message =
                        string.Format(
                            HttpContext.GetGlobalResourceObject(string.Format("{0}_Rules", HLConfigManager.Platform),
                                                                "NoPromoSku").ToString(), country.DisplayName,
                            SkuToBeAdded);
                    LoggerHelper.Error(message);
                    Result.Result = RulesResult.Feedback;
                    Result.AddMessage(message);
                    cart.RuleResults.Add(Result);
                    return(Result);
                }

                return(Result);
            }

            //Promo items must have inventory
            var catItem = CatalogProvider.GetCatalogItem(SkuToBeAdded, Country);
            WarehouseInventory warehouseInventory = null;

            if (null != cart.DeliveryInfo && !string.IsNullOrEmpty(cart.DeliveryInfo.WarehouseCode))
            {
                if (catItem.InventoryList.TryGetValue(cart.DeliveryInfo.WarehouseCode, out warehouseInventory))
                {
                    if ((warehouseInventory as WarehouseInventory_V01).QuantityAvailable > 0)
                    {
                        cart.AddItemsToCart(
                            new List <ShoppingCartItem_V01>(new[]
                                                            { new ShoppingCartItem_V01(0, SkuToBeAdded, quantity, DateTime.Now) }), true);
                        Result.Result = RulesResult.Success;
                        cart.RuleResults.Add(Result);
                    }
                }
            }

            return(Result);
        }
Esempio n. 8
0
    public void MoveItemsToInventory(int iSlot)
    {
        string temp = GameMaster.MSG_GEN_NA;

        OrderItem item = new OrderItem(Shop.ItemsOnDisplay[iSlot].ItemID, 1);

        bool itemMoved = WarehouseInventory.AddItem(item, false, out temp);

        if (itemMoved)
        {
            Shop.RemoveItem(iSlot);
        }
        else
        {
            Debug.Log("***Moving items to Inventory fail: " + temp);
        }
    }
        public void AdjustStocks(PurchaseOrderModel order)
        {
            var warehouseRepository = ServiceLocator.Current.GetInstance<IWarehouseRepository>();
            var warehousesCache = warehouseRepository.List();
            var warehouseInventory = ServiceLocator.Current.GetInstance<IWarehouseInventoryService>();

            var expirationCandidates = new HashSet<ProductContent>();

            var referenceConverter = ServiceLocator.Current.GetInstance<ReferenceConverter>();
            var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();

            // Adjust inventory
            foreach (var f in order.OrderForms)
            {
                foreach (var i in f.LineItems)
                {
                    try
                    {
                        var warehouse = warehousesCache.First(w => w.Code == i.WarehouseCode);
                        var catalogEntry = CatalogContext.Current.GetCatalogEntry(i.CatalogEntryId);
                        var catalogKey = new CatalogKey(catalogEntry);
                        var inventory = new WarehouseInventory(warehouseInventory.Get(catalogKey, warehouse));

                        if ((inventory.InStockQuantity -= i.Quantity) <= 0)
                        {
                            var contentLink = referenceConverter.GetContentLink(i.CatalogEntryId);
                            var variant = contentRepository.Get<VariationContent>(contentLink);

                            expirationCandidates.Add((ProductContent)variant.GetParent());
                        }

                        warehouseInventory.Save(inventory);
                    }
                    catch (Exception ex)
                    {
                        LoggerExtensions.Error((ILogger) Log, "Unable to adjust inventory.", ex);
                    }

                }
            }

            // TODO: Determine if you want to unpublish products with no sellable variants
            // ExpireProductsWithNoInventory(expirationCandidates, contentRepository);
            // Alterntive approach is to notify the commerce admin about the products without inventory
        }
Esempio n. 10
0
        protected void AdjustStocks(PurchaseOrder order)
        {
            var warehouseRepository = ServiceLocator.Current.GetInstance <IWarehouseRepository>();
            var warehousesCache     = warehouseRepository.List();
            var warehouseInventory  = ServiceLocator.Current.GetInstance <IWarehouseInventoryService>();

            var expirationCandidates = new HashSet <ProductContent>();

            var referenceConverter = ServiceLocator.Current.GetInstance <ReferenceConverter>();
            var contentRepository  = ServiceLocator.Current.GetInstance <IContentRepository>();

            // Adjust inventory
            foreach (OrderForm f in order.OrderForms)
            {
                foreach (LineItem i in f.LineItems)
                {
                    try
                    {
                        var warehouse    = warehousesCache.Where(w => w.Code == i.WarehouseCode).First();
                        var catalogEntry = CatalogContext.Current.GetCatalogEntry(i.CatalogEntryId);
                        var catalogKey   = new CatalogKey(catalogEntry);
                        var inventory    = new WarehouseInventory(warehouseInventory.Get(catalogKey, warehouse));

                        //inventory.ReservedQuantity += i.Quantity;
                        if ((inventory.InStockQuantity -= i.Quantity) <= 0)
                        {
                            var contentLink = referenceConverter.GetContentLink(i.CatalogEntryId);
                            var variant     = contentRepository.Get <VariationContent>(contentLink);

                            expirationCandidates.Add((ProductContent)variant.GetParent());
                        }

                        warehouseInventory.Save(inventory);
                    }
                    catch (Exception ex)
                    {
                        _log.Error("Unable to adjust inventory.", ex);
                    }
                }
            }

            // TODO: Determine if you want to unpublish products with no sellable variants
            // ExpireProductsWithNoInventory(expirationCandidates, contentRepository);
            // Alterntive approach is to notify the commerce admin about the products without inventory
        }
        private bool IsBlocked(CatalogItem_V01 catItem)
        {
            MyHLShoppingCart cart = (ProductsBase).ShoppingCart;

            if (null != cart && null != cart.DeliveryInfo && catItem.InventoryList != null && catItem.InventoryList.ContainsKey(cart.DeliveryInfo.WarehouseCode))
            {
                WarehouseInventory warehouseInventory = catItem.InventoryList[cart.DeliveryInfo.WarehouseCode];
                if (null != warehouseInventory)
                {
                    WarehouseInventory_V01 inventory = warehouseInventory as WarehouseInventory_V01;
                    if (inventory != null)
                    {
                        return(inventory.IsBlocked);
                    }
                }
            }
            return(true);
        }
Esempio n. 12
0
    /// <summary>
    /// Moves some or all of the specified Items to the Shop.
    /// </summary>
    /// <param name="iInventoryItem">The index of the OrderItem in the Player Inventory to be moved to the shop.</param>
    /// <param name="quantity"></param>
    /// <param name="iSlot"></param>
    /// <returns></returns>
    public void MoveItemsToShop(int iInventoryItem, int iSlot)
    {
        string temp = GameMaster.MSG_GEN_NA;

        bool itemMoved = Shop.AddItem(WarehouseInventory.Items[iInventoryItem].ItemID, iSlot);

        if (itemMoved)
        {
            if (WarehouseInventory.Items[iInventoryItem].Quantity > 1)
            {
                WarehouseInventory.Items[iInventoryItem].ReduceQuantity(1, false, out temp);
            }
            else
            {
                WarehouseInventory.RemoveItem(iInventoryItem, out temp);
            }
        }
        else
        {
            Debug.Log("***The specified Shop Item slot is already in use.");
        }
    }
        /// <summary>
        /// Gets all item in stock.
        /// </summary>
        /// <param name="inventories"> The WarehouseInventory.</param>
        /// <returns></returns>
        public static IWarehouseInventory SumInventories(IEnumerable <IWarehouseInventory> inventories)
        {
            WarehouseInventory result = new WarehouseInventory()
            {
                InStockQuantity           = 0,
                ReservedQuantity          = 0,
                ReorderMinQuantity        = 0,
                PreorderQuantity          = 0,
                BackorderQuantity         = 0,
                AllowBackorder            = false,
                AllowPreorder             = false,
                PreorderAvailabilityDate  = DateTime.MaxValue,
                BackorderAvailabilityDate = DateTime.MaxValue
            };
            IWarehouseRepository warehouseRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance <IWarehouseRepository>();

            foreach (IWarehouseInventory inventory in inventories)
            {
                if (warehouseRepository.Get(inventory.WarehouseCode).IsActive)
                {
                    // Sum up quantity fields
                    result.BackorderQuantity  += inventory.BackorderQuantity;
                    result.InStockQuantity    += inventory.InStockQuantity;
                    result.PreorderQuantity   += inventory.PreorderQuantity;
                    result.ReorderMinQuantity += inventory.ReorderMinQuantity;
                    result.ReservedQuantity   += inventory.ReservedQuantity;

                    // Check flags that should be global when aggregating warehouse inventories
                    result.AllowBackorder = inventory.AllowBackorder ? inventory.AllowBackorder : result.AllowBackorder;
                    result.AllowPreorder  = inventory.AllowPreorder ? inventory.AllowPreorder : result.AllowPreorder;

                    result.BackorderAvailabilityDate = GetAvailabilityDate(result.BackorderAvailabilityDate, inventory.BackorderAvailabilityDate);
                    result.PreorderAvailabilityDate  = GetAvailabilityDate(result.PreorderAvailabilityDate, inventory.PreorderAvailabilityDate);
                }
            }

            return(result);
        }
        protected void SetDefaultInventory(string code, decimal inStockQuantity, string warehouseCode = "default")
        {
            _log.Debug("Setting stock for {0} to {1}", code, inStockQuantity);
            var warehouse = _warehouseRepository.Get(warehouseCode);

            if (warehouse == null)
            {
                throw new ArgumentNullException("warehouse");
            }

            if (inStockQuantity == 0)
            {
                throw new ArgumentNullException("inStockQuantity", "InStockQuantity is required");
            }

            CatalogKey key = new CatalogKey(Mediachase.Commerce.Core.AppContext.Current.ApplicationId, code);



            var existingInventory = _inventoryService.Get(key, warehouse);

            WarehouseInventory inv;

            if (existingInventory != null)
            {
                inv = new WarehouseInventory(existingInventory);
            }
            else
            {
                inv = new WarehouseInventory();
                inv.WarehouseCode = warehouse.Code;
                inv.CatalogKey    = key;
            }
            inv.InStockQuantity = inStockQuantity;

            _inventoryService.Save(inv);
        }
Esempio n. 15
0
        protected void SetDefaultInventory(string code, decimal inStockQuantity, string warehouseCode = "default")
        {
            _log.Debug("Setting stock for {0} to {1}", code, inStockQuantity);
            var warehouse = _warehouseRepository.Get(warehouseCode);
            if (warehouse == null)
                throw new ArgumentNullException("warehouse");

            if (inStockQuantity == 0)
            {
                throw new ArgumentNullException("inStockQuantity", "InStockQuantity is required");
            }

            CatalogKey key = new CatalogKey(AppContext.Current.ApplicationId, code);

            var existingInventory = _inventoryService.Get(key, warehouse);

            WarehouseInventory inv;
            if (existingInventory != null)
            {
                inv = new WarehouseInventory(existingInventory);
            }
            else
            {
                inv = new WarehouseInventory();
                inv.WarehouseCode = warehouse.Code;
                inv.CatalogKey = key;
            }
            inv.InStockQuantity = inStockQuantity;

            _inventoryService.Save(inv);
        }
Esempio n. 16
0
        /// <summary>
        ///     Adds to cart.
        /// </summary>
        /// <param name="cart">The cart.</param>
        /// <param name="Result">The result.</param>
        /// <returns></returns>
        private ShoppingCartRuleResult AddToCart(MyHLShoppingCart cart, ShoppingCartRuleResult Result, int quantity, ShoppingCartRuleReason reason, bool displayMessage)
        {
            cart.IsPromoDiscarted = false;
            var allSkus = CatalogProvider.GetAllSKU(Locale);

            if (!allSkus.Keys.Contains(promoSku))
            {
                if (Environment.MachineName.IndexOf("PROD") < 0)
                {
                    var    country = new RegionInfo(new CultureInfo(Locale, false).LCID);
                    string message =
                        string.Format(
                            HttpContext.GetGlobalResourceObject(string.Format("{0}_Rules", HLConfigManager.Platform),
                                                                "NoPromoSku").ToString(), country.DisplayName, promoSku);
                    LoggerHelper.Error(message);
                    Result.Result = RulesResult.Failure;
                    Result.AddMessage(message);
                    cart.RuleResults.Add(Result);
                    return(Result);
                }

                return(Result);
            }

            //Promo items must have inventory
            var catItem = CatalogProvider.GetCatalogItem(promoSku, Country);
            WarehouseInventory warehouseInventory = null;

            if (null != cart.DeliveryInfo && !string.IsNullOrEmpty(cart.DeliveryInfo.WarehouseCode))
            {
                if (catItem.InventoryList.TryGetValue(cart.DeliveryInfo.WarehouseCode, out warehouseInventory))
                {
                    if ((warehouseInventory as WarehouseInventory_V01).QuantityAvailable > 0)
                    {
                        cart.AddItemsToCart(
                            new List <ShoppingCartItem_V01>(new[]
                                                            { new ShoppingCartItem_V01(0, promoSku, quantity, DateTime.Now) }), true);

                        string message = string.Empty;
                        if (reason == ShoppingCartRuleReason.CartItemsAdded)
                        {
                            if (displayMessage)
                            {
                                message =
                                    string.Format(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_Rules", HLConfigManager.Platform),
                                            "PromotionalSkuAdded").ToString());
                                Result.Result = RulesResult.Feedback;
                            }
                            else if (cart.CurrentItems.Count > 0 && cart.CurrentItems[0].SKU == promoSku)
                            {
                                message       = string.Format(HttpContext.GetGlobalResourceObject(string.Format("{0}_Rules", HLConfigManager.Platform), "NoModifyPromoSku").ToString());
                                Result.Result = RulesResult.Failure;
                            }
                            else
                            {
                                Result.Result = RulesResult.Success;
                            }
                        }
                        Result.AddMessage(message);
                        cart.IsPromoNotified = true;
                        cart.RuleResults.Add(Result);
                    }
                }
            }

            return(Result);
        }
        /// <summary>
        /// Determines whether the specific inventory has enough quantity for the line item.
        /// </summary>
        /// <param name="inventory">The inventory.</param>
        /// <param name="lineItem">The line item.</param>
        /// <returns>
        ///   <c>true</c> if has enough quantity; otherwise, <c>false</c>.
        /// </returns>
        private bool IsEnoughQuantity(IWarehouseInventory inventory, LineItem lineItem)
        {
            //TODO: Consolidate with CheckInventoryActivity
            decimal quantity = lineItem.Quantity;
            if (lineItem.InventoryStatus == (int)InventoryTrackingStatus.Enabled)
            {
                var entry = CatalogContext.Current.GetCatalogEntry(lineItem.CatalogEntryId, CatalogEntryResponseGroup_InfoWithVariations);
                if (inventory == null)
                {
                    // Treat missing as zeroes
                    inventory = new WarehouseInventory();
                    ((WarehouseInventory)inventory).InventoryStatus = InventoryTrackingStatus.Enabled;
                }
                if (entry.StartDate > FrameworkContext.Current.CurrentDateTime)
                {
                    //not allow preorder or preorder is not available
                    if (!inventory.AllowPreorder || inventory.PreorderAvailabilityDate > FrameworkContext.Current.CurrentDateTime)
                    {
                        return false;
                    }
                    //allow preorder but quantity is not enough
                    if (quantity > inventory.PreorderQuantity)
                    {
                        return false;
                    }
                }
                if (inventory.InStockQuantity > 0 && inventory.InStockQuantity >= inventory.ReservedQuantity + quantity)
                {
                    return true;
                }

                //Not enough quantity in stock, check for backorder
                if (!inventory.AllowBackorder)
                {
                    return false;
                }
                //Backorder is not available
                if (inventory.BackorderAvailabilityDate > FrameworkContext.Current.CurrentDateTime)
                {
                    return false;
                }
                //Backorder quantity is not enough
                if (quantity > inventory.InStockQuantity -
                    inventory.ReservedQuantity + inventory.BackorderQuantity)
                {
                    return false;
                }
            }
            return true;
        }
Esempio n. 18
0
        public object Post(JObject inventory)
        {
            // Need the catalog code
            string code = inventory["CatalogEntryCode"].Value <string>();

            if (string.IsNullOrWhiteSpace(code))
            {
                throw new ArgumentNullException("CatalogEntryCode", "CatalogEntryCode is required");
            }

            string warehouseCode = "default";

            if (string.IsNullOrEmpty(inventory["WarehouseCode"].Value <string>()) == false)
            {
                warehouseCode = inventory["WarehouseCode"].Value <string>();
            }
            IWarehouseRepository warehouseRepository = ServiceLocator.Current.GetInstance <IWarehouseRepository>();
            var warehouse = warehouseRepository.Get(warehouseCode);

            if (warehouse == null)
            {
                throw new ArgumentNullException("warehouse");
            }

            decimal inStockQuantity = inventory["InStockQuantity"].Value <decimal>();

            if (inStockQuantity == 0)
            {
                throw new ArgumentNullException("InStockQuantity", "InStockQuantity is required");
            }

            CatalogKey key = new CatalogKey(AppContext.Current.ApplicationId, code);

            var inventoryService = ServiceLocator.Current.GetInstance <IWarehouseInventoryService>();

            var existingInventory = inventoryService.Get(key, warehouse);

            WarehouseInventory inv;

            if (existingInventory != null)
            {
                inv = new WarehouseInventory(existingInventory);
            }
            else
            {
                inv = new WarehouseInventory();
                inv.WarehouseCode = warehouse.Code;
                inv.CatalogKey    = key;
            }
            inv.InStockQuantity = inStockQuantity;

            // Set tracking status, if passed in, if not, ignore it
            string status = inventory["InventoryStatus"].Value <string>();

            if (string.IsNullOrEmpty(status) == false)
            {
                InventoryTrackingStatus inventoryTrackingStatus;
                if (Enum.TryParse(status, true, out inventoryTrackingStatus))
                {
                    inv.InventoryStatus = inventoryTrackingStatus;
                }
            }

            inventoryService.Save(inv);

            return(Get(key.CatalogEntryCode));
        }
Esempio n. 19
0
        /// <summary>
        /// Adjusts the stock inventory quantities. Method assumes only inventory TRACKING is enabled.
        /// </summary>
        /// <param name="lineItem">Line item object in cart.</param>
        /// <param name="inventory">Inventory associated with the line item's catalog entry.</param>
        /// <param name="delta">The change in inventory.</param>
        private static void AdjustStockInventoryQuantity(LineItem lineItem, IWarehouseInventory inventory, decimal delta)
        {
            if (inventory == null)
            {
                if (delta != 0)
                {
                    //throw new Exception("Inventory cannot be null with non-zero delta.");
                    return;
                }
                return;
            }

            WarehouseInventory editedInventory = new WarehouseInventory(inventory);

            //arrival
            if (delta > 0)
            {
                // need distribute delta between InStock, Backorder, Preorder.
                if (lineItem.InStockQuantity > 0)
                {
                    var backorderDelta = Math.Min(delta, lineItem.BackorderQuantity - inventory.BackorderQuantity);
                    var preorderdelta  = Math.Min(delta, lineItem.PreorderQuantity - inventory.PreorderQuantity);
                    editedInventory.PreorderQuantity  += preorderdelta;
                    editedInventory.BackorderQuantity += backorderDelta;
                    editedInventory.InStockQuantity   += delta - backorderDelta - preorderdelta;
                }                 //need distribute delta between Preorder and Backorder
                else if (lineItem.InStockQuantity == 0)
                {
                    if (lineItem.PreorderQuantity > 0)
                    {
                        editedInventory.PreorderQuantity += delta;
                    }
                    else if (lineItem.BackorderQuantity > 0)
                    {
                        editedInventory.BackorderQuantity += delta;
                    }
                }
            }            //consumption
            else
            {
                delta = Math.Abs(delta);
                bool inventoryEnabled = inventory.InventoryStatus == InventoryTrackingStatus.Enabled;
                //Instock quantity is larger than delta plus reserved quantity
                if (inventory.InStockQuantity >= delta + inventory.ReservedQuantity) // Adjust the main inventory
                {
                    //just simply subtract from Instock quantity
                    editedInventory.InStockQuantity -= delta;
                }
                //Instock quantity is larger than delta but smaller than delta and reserved quantity
                else if (inventory.InStockQuantity >= inventory.ReservedQuantity)
                {
                    if (inventoryEnabled)
                    {
                        if (editedInventory.AllowPreorder && editedInventory.PreorderAvailabilityDate <= FrameworkContext.Current.CurrentDateTime)
                        {
                            editedInventory.PreorderQuantity -= delta;
                        }

                        if (editedInventory.AllowBackorder && editedInventory.BackorderAvailabilityDate <= FrameworkContext.Current.CurrentDateTime)
                        {
                            editedInventory.BackorderQuantity -= delta - (editedInventory.InStockQuantity - inventory.ReservedQuantity);
                            editedInventory.InStockQuantity    = inventory.ReservedQuantity;
                        }
                    }
                    else
                    {
                        editedInventory.InStockQuantity -= delta;
                    }
                }
                else if (inventory.InStockQuantity > 0) // there still exist items in stock
                {
                    // Calculate difference between currently available and backorder
                    var backorderDelta = delta - (inventory.InStockQuantity - (inventoryEnabled ? inventory.ReservedQuantity : 0));

                    // Update inventory
                    if (inventoryEnabled)
                    {
                        editedInventory.InStockQuantity    = inventory.ReservedQuantity;
                        editedInventory.BackorderQuantity -= backorderDelta;
                    }
                    else
                    {
                        editedInventory.InStockQuantity -= delta;
                    }
                }
                else if (inventory.InStockQuantity == 0)
                {
                    if (inventoryEnabled)
                    {
                        if (inventory.PreorderQuantity == 0)
                        {
                            editedInventory.BackorderQuantity -= delta;
                        }
                        else
                        {
                            editedInventory.PreorderQuantity -= delta;
                        }
                    }
                    else
                    {
                        editedInventory.InStockQuantity = -delta;
                    }
                }
            }

            ServiceLocator.Current.GetInstance <IWarehouseInventoryService>().Save(editedInventory);
        }
        /// <summary>
        /// Adjusts the stock inventory quantities. Method assumes only inventory TRACKING is enabled.
        /// </summary>
        /// <param name="lineItem">Line item object in cart.</param>
        /// <param name="inventory">Inventory associated with the line item's catalog entry.</param>
        /// <param name="delta">The change in inventory.</param>
        private static void AdjustStockInventoryQuantity(LineItem lineItem, IWarehouseInventory inventory, decimal delta)
        {
            if (inventory == null)
            {
                if (delta != 0)
                {
                    //throw new Exception("Inventory cannot be null with non-zero delta.");
                    return;
                }
                return;
            }

            WarehouseInventory editedInventory = new WarehouseInventory(inventory);

            //arrival
            if (delta > 0)
            {
                // need distribute delta between InStock, Backorder, Preorder.
                if (lineItem.InStockQuantity > 0)
                {
                    var backorderDelta = Math.Min(delta, lineItem.BackorderQuantity - inventory.BackorderQuantity);
                    var preorderdelta = Math.Min(delta, lineItem.PreorderQuantity - inventory.PreorderQuantity);
                    editedInventory.PreorderQuantity += preorderdelta;
                    editedInventory.BackorderQuantity += backorderDelta;
                    editedInventory.InStockQuantity += delta - backorderDelta - preorderdelta;
                } //need distribute delta between Preorder and Backorder
                else if (lineItem.InStockQuantity == 0)
                {
                    if (lineItem.PreorderQuantity > 0)
                    {
                        editedInventory.PreorderQuantity += delta;
                    }
                    else if (lineItem.BackorderQuantity > 0)
                    {
                        editedInventory.BackorderQuantity += delta;
                    }
                }
            }//consumption
            else
            {
                delta = Math.Abs(delta);
                bool inventoryEnabled = inventory.InventoryStatus == InventoryTrackingStatus.Enabled;
                if (inventory.InStockQuantity >= delta + inventory.ReservedQuantity) // Adjust the main inventory
                {
                    //just simply subtract from Instock quantity
                    editedInventory.InStockQuantity -= delta;
                }
                //Instock quantity is larger than delta but smaller than delta and reserved quantity
                else if (inventory.InStockQuantity >= inventory.ReservedQuantity)
                {
                    if (inventoryEnabled)
                    {
                        editedInventory.BackorderQuantity -= delta - (editedInventory.InStockQuantity - inventory.ReservedQuantity);
                        editedInventory.InStockQuantity = inventory.ReservedQuantity;
                    }
                    else
                    {
                        editedInventory.InStockQuantity -= delta;
                    }
                }
                else if (inventory.InStockQuantity > 0) // there still exist items in stock
                {
                    // Calculate difference between currently availbe and backorder
                    var backorderDelta = delta - (inventory.InStockQuantity - (inventoryEnabled ? inventory.ReservedQuantity : 0));

                    // Update inventory
                    if (inventoryEnabled)
                    {
                        editedInventory.InStockQuantity = inventory.ReservedQuantity;
                        editedInventory.BackorderQuantity -= backorderDelta;
                    }
                    else
                    {
                        editedInventory.InStockQuantity -= delta;
                    }
                }
                else if (inventory.InStockQuantity <= 0)
                {
                    // Update inventory
                    editedInventory.InStockQuantity = -delta;

                    if (inventoryEnabled)
                    {
                        if (inventory.PreorderQuantity == 0)
                            editedInventory.BackorderQuantity -= delta;
                        else
                            editedInventory.PreorderQuantity -= delta;
                    }
                }
            }

            ServiceLocator.Current.GetInstance<IWarehouseInventoryService>().Save(editedInventory);
        }
        /// <summary>
        /// Validates if the promo should be in cart.
        /// </summary>
        /// <param name="cart">The cart.</param>
        /// <param name="result">The promo rule result.</param>
        /// <param name="requiredSkus">The required sku list.</param>
        /// <param name="promoSku">The promo sku.</param>
        /// <returns></returns>
        private ShoppingCartRuleResult CheckPromoIncart(MyHLShoppingCart cart, ShoppingCartRuleResult result, List <string> requiredSkus, string promoSku)
        {
            // Check if promo sku should be in cart
            var quantityToAdd = cart.CartItems.Where(i => requiredSkus.Contains(i.SKU)).Sum(i => i.Quantity);
            var promoInCart   = cart.CartItems.FirstOrDefault(i => i.SKU.Equals(promoSku));

            // If not elegibe for promo then nothing to do
            if (quantityToAdd == 0)
            {
                if (promoInCart != null)
                {
                    cart.DeleteItemsFromCart(new List <string> {
                        promoSku
                    }, true);
                }

                // Nothing to do
                result.Result = RulesResult.Success;
                cart.RuleResults.Add(result);
                return(result);
            }

            // Define the quantity to add
            if (promoInCart != null)
            {
                if (promoInCart.Quantity == quantityToAdd)
                {
                    // Check if nothing to do
                    result.Result = RulesResult.Success;
                    cart.RuleResults.Add(result);
                    return(result);
                }
                if (promoInCart.Quantity > quantityToAdd)
                {
                    // Remove the promo sku if quantity to add is minor than the quantity in cart
                    cart.DeleteItemsFromCart(new List <string> {
                        promoSku
                    }, true);
                }
                else
                {
                    // Change item quantity adding the excess to the existent sku
                    quantityToAdd -= promoInCart.Quantity;
                }
            }

            // Check promo items in catalog
            var allSkus = CatalogProvider.GetAllSKU(Locale);

            if (!allSkus.Keys.Contains(promoSku))
            {
                if (Environment.MachineName.IndexOf("PROD", StringComparison.Ordinal) < 0)
                {
                    var    country = new RegionInfo(new CultureInfo(Locale, false).LCID);
                    string message = "NoPromoSku";
                    var    globalResourceObject =
                        HttpContext.GetGlobalResourceObject(string.Format("{0}_Rules", HLConfigManager.Platform),
                                                            "NoPromoSku");
                    if (globalResourceObject != null)
                    {
                        message = string.Format(globalResourceObject.ToString(), country.DisplayName, promoSku);
                    }
                    result.Result = RulesResult.Feedback;
                    result.AddMessage(message);
                    cart.RuleResults.Add(result);
                }
                return(result);
            }

            //Promo items must have inventory
            var catItem = CatalogProvider.GetCatalogItem(promoSku, Country);

            if (cart.DeliveryInfo != null && !string.IsNullOrEmpty(cart.DeliveryInfo.WarehouseCode))
            {
                WarehouseInventory warehouseInventory = null;
                if (catItem.InventoryList.TryGetValue(cart.DeliveryInfo.WarehouseCode, out warehouseInventory))
                {
                    if (warehouseInventory != null)
                    {
                        var warehouseInventory01 = warehouseInventory as WarehouseInventory_V01;
                        if (warehouseInventory01 != null && warehouseInventory01.QuantityAvailable > 0)
                        {
                            cart.AddItemsToCart(
                                new List <ShoppingCartItem_V01>(new[]
                                                                { new ShoppingCartItem_V01(0, promoSku, quantityToAdd, DateTime.Now) }), true);
                            result.Result = RulesResult.Success;
                            cart.RuleResults.Add(result);
                        }
                    }
                }
            }

            return(result);
        }