public JsonResult Add(TransactionModel model)
        {
            //JourListDMContainer dm = new JourListDMContainer();

            //// Verify the member
            //Member member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);
            //if (!User.Identity.IsAuthenticated || member == null)
            return JsonError("This function has been deprecated");

            //model.ActionId = dm.InventoryActions.Single(z => z.Description == "ADD").Id;

            //try
            //{
            //    model.TransId = UpdateStock(model).Id;
            //}
            //catch (Exception e)
            //{
            //    return JsonError(e.Message);
            //    throw;
            //}

            //// get next shopping list item or default item model
            //var i = member.Inventories.FirstOrDefault(z => z.ShoppingList != null);
            //TransactionModel nmodel = new TransactionModel();
            //nmodel.InvId = i == null ? 0 : i.Id;
            //nmodel.Description = i == null ? "" : i.Item.Description;
            //nmodel.Quantity = i == null ? 0 : i.ShoppingList.QuantityNeeded;
            //nmodel.Size = i == null ? 0 : i.ShoppingList.SizeNeeded;
            //nmodel.sUnitId = i == null ? "-1" : i.Unit.Id.ToString();
            //nmodel.Cost = i == null ? 0 :
            //    i.InventoryLogs == null ? 0 : i.InventoryLogs.Last().Cost;

            //return JsonOk(new { NextItem = nmodel, Transaction = tmodel });
        }
        //(StockUpdateEnum action, double quantity, double size, long itemId, Unit units, double cost)
        /// <summary>
        /// Updates the inventory entry for the item
        /// Calls to update shopping list
        /// Creates a transaction log entry
        /// </summary>
        /// <param name="action">ADD/REMOVE/CURRENT</param>
        /// <param name="quantity">Count Multiplier</param>
        /// <param name="size">Size of each Item</param>
        /// <param name="itemId">ID of the item we're updating</param>
        /// <param name="units">Units of quantity coming in</param>
        /// <returns></returns>
        private InventoryLog UpdateStock(TransactionModel model)
        {
            #region Setup objects

            JourListDMContainer dm = new JourListDMContainer();
            InventoryLog log = new InventoryLog();

            var member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);
            if (member == null) return null;

            var inv = member.Inventories.FirstOrDefault(z => z.Id == model.InvId);
            if (inv == null) return null;

            // Update the inventory numbers
            var action = dm.InventoryActions.Single(z => z.Id == model.ActionId).Description;
            var uaction = (StockUpdateEnum)Enum.Parse(typeof(StockUpdateEnum), action);

            #endregion

            #region Update inventory values
            var units = dm.Units.Single(z => z.Id == model.UnitId);
            double size;
            try
            {
                size = Tools.Tools.ConvertUnits(model.Size, units, inv.Unit);
            }
            catch (Exception e)
            {
                throw e;
            }

            double total = size * model.Quantity;

            switch (uaction)
            {
                case StockUpdateEnum.ADD:
                    inv.OnHand += total;
                    log.Cost =  model.Cost;
                    break;
                case StockUpdateEnum.REMOVE:
                    model.Quantity *= -1;
                    inv.OnHand -= total;
                    model.Cost = 0;
                    break;
                case StockUpdateEnum.ADJUST:
                    if (inv.OnHand > total)
                    {
                        model.Quantity *= -1;
                        model.Size = -1 * (inv.OnHand - total);
                    }
                    else // if inv.onhand < total
                        model.Size = total - inv.OnHand;
                    inv.OnHand = total;
                    model.Cost = 0;
                    break;
                default:
                    break;
            }
            #endregion

            dm.SaveChanges();

            #region Make a transaction log

            // Create an inventory transaction
            log.Quantity = model.Quantity;
            log.Inventory = inv;
            log.TransactionDate = DateTime.Now;
            log.InventoryAction = dm.InventoryActions.Single(z => z.Id == model.ActionId);
            log.Size = model.Size;
            log.Quantity = model.Quantity;
            log.Unit = dm.Units.Single(z => z.Id == model.UnitId);
            log.Cost = model.Cost;
            dm.SaveChanges();

            model.TransId = log.Id;

            #endregion

            // With any inventory update, it's possible the item need to be included/excluded from the shopping list.
            UpdateShoppingList(inv);

            // Success
            return log;
        }
        public JsonResult UpdateItem(ItemModel model)
        {
            try
            {
                if (!ModelState.IsValid) return JsonError("Form is not valid! Please correct it and try again.");

                if (!User.Identity.IsAuthenticated) return JsonError("You need to log in to add modify personal items.");

                JourListDMContainer dm = new JourListDMContainer();

                Inventory inv = dm.Members.SingleOrDefault(z=>z.Name == User.Identity.Name)
                                  .Inventories.FirstOrDefault(z => z.Item.Id == model.Id);

                if (inv == null) return JsonError("The item was not modified since it does not exist in your inventory.");

                // Allow the update of fundamental properties if it's personal
                if (inv.Item is PersonalItem)
                {
                    inv.Item.Description = model.Description;
                    //if (model.Hyperlink != null) inv.Item.Hyperlink = model.Hyperlink;
                    //if (model.Barcode != null) inv.Item.Barcode = model.Barcode;
                    inv.Item.ItemCategory = dm.ItemCategories.Single(z => z.Id == model.CategoryId);
                    inv.Item.UnitType = dm.UnitTypes.Single(z => z.Id == model.UnitTypeId);
                    inv.Active = model.Active;
                }
                // Otherwise fix the model that will be resent and displayed
                else
                {
                    // TODO: Provide some message to the user that they can't update thse
                    model.Description = inv.Item.Description;
                    model.CategoryId = inv.Item.ItemCategory.Id;
                    model.UnitTypeId = inv.Item.UnitType.Id;
                    model.Active = inv.Active;
                }

                // TODO: Create unit test to ensure unit manipulation happens after we've confirmed Unit Type changes
                Unit unit = dm.Units.Single(z => z.Id == model.UnitId);

                // Ensure the new unit is of the correct type
                if (unit.UnitType.Id != inv.Unit.UnitType.Id)
                    return JsonError("The new unit must be of type " + inv.Unit.UnitType.Description + "!");

                // If the standard unit is changing, convert the stock level values.
                if (inv.Unit.Id != model.UnitId)
                {
                    try
                    {
                        inv.OnHand = Tools.Tools.ConvertUnits(inv.OnHand, inv.Unit, unit);
                        inv.RestockThreshold = Tools.Tools.ConvertUnits(inv.RestockThreshold, inv.Unit, unit);
                        inv.RequiredQuantity = Tools.Tools.ConvertUnits(inv.RequiredQuantity, inv.Unit, unit);
                    }
                    catch (Exception e)
                    {
                        return JsonError(e.Message);
                    }
                }

                // Assign converted values
                inv.RestockThreshold = model.RestockThreshold;
                inv.RequiredQuantity = model.RequiredQuantity;
                inv.Unit = unit;

                dm.SaveChanges();

                TransactionModel cm = new TransactionModel();
                cm.InvId = inv.Id;
                cm.ActionId = dm.InventoryActions.Single(z => z.Description == "ADJUST").Id;
                cm.UnitId = unit.Id;
                cm.Quantity = 1;
                cm.Size = model.OnHand;
                cm.Cost = 0;
            //                cm.IsTotalCost = true;

                if (UpdateStock(cm) == null)
                    return JsonError("Your inventory could not be updated.");

                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return JsonError(e.Message);
            }
        }
        public JsonResult Transact(TransactionModel model)
        {
            JourListDMContainer dm = new JourListDMContainer();

            Member member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);
            if (!User.Identity.IsAuthenticated || member == null)
                return JsonError("You need to log in to use the shopping cart.");

            try
            {
                var log = UpdateStock(model);
                model.TransId = log.Id;
                model.TimeStamp = log.TransactionDate;
            }
            catch (Exception e)
            {
                return JsonError(e.Message);
                throw;
            }

            TransactionModel nmodel = new TransactionModel(model.ActionId, member.Name);

            return JsonOk(new { NextItem = nmodel, Transaction = model });
        }
        public TransactionModel(int actionId = -1, string user = null, long invid = -1, bool allunits = false)
        {
            JourListDMContainer dm    = new JourListDMContainer();
            TransactionModel    model = this;
            Inventory           inv   = null;
            IEnumerable <Unit>  units = dm.Units;

            // Verify the member
            if (user != null)
            {
                Member member = dm.Members.SingleOrDefault(z => z.Name == user);
                if (member == null)
                {
                    throw new Exception("User not authenticated");
                }

                // Get the item if the jourId is specified
                inv = member.Inventories.FirstOrDefault(z => z.Id == invid);

                if (inv == null)
                {
                    inv = member.Inventories.FirstOrDefault(z => z.ShoppingList != null);
                }

                // If that didn't work just grab the first item from the inventory
                if (inv == null)
                {
                    inv = member.Inventories.FirstOrDefault();
                }

                // If that didn't work then they get nothing
                if (inv != null)
                {
                    model.InvId       = inv.Id;
                    model.Description = inv.Item.Description;
                    model.UnitId      = inv.Unit.Id;

                    InventoryLog log;
                    if ((log = inv.InventoryLogs.FirstOrDefault()) != null)
                    {
                        model.Cost = log.Cost;
                    }
                    else
                    {
                        model.Cost = 0;
                    }

                    if (allunits == false)
                    {
                        units = inv.Unit.UnitType.Units;
                    }

                    if (inv.ShoppingList != null)
                    {
                        model.Quantity = inv.ShoppingList.QuantityNeeded;
                        model.Size     = inv.ShoppingList.SizeNeeded;
                    }
                    else
                    {
                        model.Quantity = 0;
                        model.Size     = 0;
                    }
                }
            }
            if (inv == null)
            {
                model.InvId       = -1;
                model.Description = "";
                model.Quantity    = 0;
                model.Size        = 0;
                model.sUnitId     = "";
                model.Cost        = 0;
            }

            List <SelectListItem> list = new List <SelectListItem>();

            foreach (var item in units)
            {
                SelectListItem li = new SelectListItem();
                li.Text  = item.Description;
                li.Value = item.Id.ToString();
                if (inv != null && item.Id == inv.Unit.Id)
                {
                    li.Selected = true;
                }
                list.Add(li);
            }

            model.UnitOptions = new SelectList(list, "Value", "Text", model.sUnitId);

            if (actionId != -1)
            {
                model.ActionId = actionId;
            }
        }