public JsonResult UpdateItem(ItemModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "Form is not valid! " +
                          "Please correct it and try again."
                    });
                }

                if (!User.Identity.IsAuthenticated)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "You need to log in to add update an item."
                    });
                }

                if (!User.IsInRole("Officer"))
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "You do not have the authority to create a new inventory item."
                    });
                }

                JourListDMContainer dm = new JourListDMContainer();

                Item item = dm.Items.OfType<StandardItem>().Single(z => z.Id == model.Id);

                if (item == null)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "The item was not modified since it does not exist."
                    });
                }

                item.Description = model.Description;
                //if (model.Hyperlink != null) item.Hyperlink = model.Hyperlink;
                //if (model.Barcode != null) item.Barcode = model.Barcode;
                item.ItemCategory = dm.ItemCategories.Single(z => z.Id == model.CategoryId);
                item.UnitType = dm.UnitTypes.Single(z => z.Id == model.UnitTypeId);
                item.Active = model.Active;

                dm.SaveChanges(); dm.SaveChanges();

                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult CreateItem(ItemModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "Form is not valid! " +
                    "Please correct it and try again."
                });
            }

            if (!User.Identity.IsAuthenticated)
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You need to log in to add an item."
                });
            }

            if (!User.IsInRole("Officer"))
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You do not have the authority to create a new inventory item."
                });
            }
            try
            {
                JourListDMContainer dm = new JourListDMContainer();

                StandardItem item = new StandardItem();

                item.Description = model.Description;
                //if (model.Hyperlink != null) item.Hyperlink = model.Hyperlink;
                //if (model.Barcode != null) item.Barcode = model.Barcode;
                item.ItemCategory = dm.ItemCategories.Single(z => z.Id == model.CategoryId);
                item.UnitType = dm.UnitTypes.Single(z => z.Id == model.UnitTypeId);

                dm.AddToItems(item);
                dm.SaveChanges();

                model.Id = item.Id;

                return Json(new { Result = "OK", Record = model });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        // POST: /DataManagement/ItemList
        public JsonResult ItemList(FormCollection collection)
        {
            try
            {
                JourListDMContainer dm = new JourListDMContainer();
                List<ItemModel> list = new List<ItemModel>();

                foreach (var a in dm.Items.OfType<StandardItem>().Where(z => z.Active == true))
                {
                    ItemModel item = new ItemModel();
                    item.Id = a.Id;
                    item.Description = a.Description;
                    //item.Hyperlink = a.Hyperlink;
                    //item.Barcode = a.Barcode;
                    item.CategoryId = a.ItemCategory.Id;
                    item.UnitTypeId = a.UnitType.Id;
                    item.Active = a.Active;
                    list.Add(item);
                }

                return Json(new { Result = "OK", Records = list });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult AddStandardItemToInventory(FormCollection collection)
        {
            if (!User.Identity.IsAuthenticated)
                return JsonError("You need to log in to add personal items.");

            long itemID = -1;

            if ( long.TryParse(collection["ItemId"], out itemID) == false)
                return JsonError("Invalid ID data.");

            JourListDMContainer dm = new JourListDMContainer();

            try
            {
                // We don't want the member to access other people's items so limit
                // their access to standard items and their own.
                // Check standard items first
                Item item = dm.Items.OfType<StandardItem>().FirstOrDefault(z => z.Id == itemID);

                if (item == null)
                    // then check the member's personal items
                    item = dm.Members.First(z => z.Name == User.Identity.Name).PersonalItems.FirstOrDefault(z => z.Id == itemID);
                if (item == null)
                {
                    // So we have a more specific error message, either way we're ending this attempt.
                    item = dm.Items.OfType<PersonalItem>().FirstOrDefault(z => z.Member.Name != User.Identity.Name);
                    if (item != null)
                        return JsonError("That's not your item to add to your inventory.");
                    else return JsonError("Could not find the item.");
                }
                ItemModel model = new ItemModel();
                model.Id = item.Id;
                model.IsPersonal = item is PersonalItem;
                model.Description = item.Description;
                model.UnitTypeId = item.UnitType.Id;
                model.CategoryId = item.ItemCategory.Id;

                Unit dUnit;
                if ((dUnit = item.UnitType.DefaultUnit) != null)
                    model.UnitId = item.UnitType.DefaultUnit.Id;
                else
                    model.UnitId = dm.Units.First(z => z.UnitType.Id == item.UnitType.Id).Id;

                Inventory inv;
                if ( (inv = AddToInventory(model)) == null)
                        return JsonError("Could not add this item to your inventory");

                model.OnHand = inv.OnHand;
                model.RestockThreshold = inv.RestockThreshold;
                model.RequiredQuantity = inv.RequiredQuantity;
                model.Active = inv.Active;

                return Json(new { Result = "OK", Record = model });
            }
            catch (Exception e)
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = e.Message
                });
            }
        }
        // Get Generic Items
        private JsonResult CreateItemModelList( IEnumerable<Item> items)
        {
            try
            {
                List<ItemModel> list = new List<ItemModel>();
                JourListDMContainer dm = new JourListDMContainer();
                var member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);

                foreach (var a in items)
                {
                    ItemModel item = new ItemModel();
                    item.Id = a.Id;
                    item.Description = a.Description;
                    //item.Hyperlink = a.Hyperlink;
                    //item.Barcode = a.Barcode;
                    item.CategoryId = a.ItemCategory.Id;
                    item.UnitTypeId = a.UnitType.Id;
                    item.Active = member.Inventories.First(z => z.Item.Id == a.Id).Active;//a.Inventories.First(.Active;
                    item.IsPersonal = a is PersonalItem;
                    Inventory inv;
                    if (member != null && (inv = member.Inventories.FirstOrDefault(z => z.Item.Id == a.Id)) != null)
                    {
                        item.InvId = inv.Id;
                        item.UnitId = inv.Unit.Id;
                        item.OnHand = inv.OnHand;
                        item.RequiredQuantity = inv.RequiredQuantity;
                        item.RestockThreshold = inv.RestockThreshold;
                    }
                    list.Add(item);
                }

                return Json(new { Result = "OK", Records = list });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        /// <summary>
        /// Add an inventory item given an item model if it doesn't exist
        /// Reactivates it if deactivated
        /// </summary>
        /// <param name="model"></param>
        /// <returns>The manipulated/created inventory entry</returns>
        private Inventory AddToInventory(ItemModel model)
        {
            JourListDMContainer dm = new JourListDMContainer();
            var member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);

            if (member == null) return null;

            // If inventory already exists but is inactive, reactivate
            // If it exists and is active, then just return the inventory item, do nothing
            Inventory inv;
            if ((inv = member.Inventories.FirstOrDefault(z=>z.Item.Id == model.Id)) != null)
            {
                if (inv.Active == false)
                    inv.Active = true;
                else return inv;
            }

            // Add an inventory listing if it doesn't exist.
            else
            {
                inv = new Inventory();
                inv.Item = dm.Items.Single(z=>z.Id == model.Id);
                inv.RestockThreshold = model.RestockThreshold;
                inv.OnHand = model.OnHand;
                inv.RequiredQuantity = model.RequiredQuantity;
                inv.Unit = dm.Units.Single(z => z.Id == model.UnitId);
                inv.Member = member;
                dm.AddToInventories(inv);
            }

            dm.SaveChanges();

            return inv;
        }
        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 CreateItem(ItemModel model)
        {
            if (!ModelState.IsValid)
                return Json(new
                {
                    Result = "ERROR",
                    Message = "Form is not valid! " +
                    "Please correct it and try again."
                });

            if (!User.Identity.IsAuthenticated)
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You need to log in to add personal items."
                });

            try
            {
                JourListDMContainer dm = new JourListDMContainer();
                var member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);

                // If the item exists but is inactive, just reactivate it.
                PersonalItem item;
                if ( (item = member.PersonalItems.SingleOrDefault(z => z.Description == model.Description)) != null)
                {
                    if (item.Active == false)
                        item.Active = true;
                    else
                        return Json(new
                        {
                            Result = "ERROR",
                            Message = "An active item by this description already exists"
                        });
                }
                // Otherwie create a new personal item
                else
                {
                    item = new PersonalItem();
                    item.Description = model.Description;
                    //if (model.Hyperlink != null) item.Hyperlink = model.Hyperlink;
                    //if (model.Barcode != null) item.Barcode = model.Barcode;
                    item.ItemCategory = dm.ItemCategories.Single(z => z.Id == model.CategoryId);
                    item.UnitType = dm.UnitTypes.Single(z => z.Id == model.UnitTypeId);
                    item.Member = member;
                    dm.AddToItems(item);
                    dm.SaveChanges();
                    // Hookup our model with the new jourId number
                    model.Id = item.Id;
                }

                Inventory inv;
                if ((inv = this.AddToInventory(model)) == null)
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "An active inventory for this item already exists"
                    });

                // Relevant inventory for jTable's purposes
            //                model.Id = item.Id;
                model.IsPersonal = item is PersonalItem;

                return Json(new { Result = "OK", Record = model });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }