Beispiel #1
0
 public ActionResult AddClass(AddClassModel m)
 {
     if (ModelState.IsValid)
     {
         itemClass newItemClass = new itemClass();
         using (var db = new CopiosisEntities())
         {
             itemClass conflictingItemClass = db.itemClasses.Where(ic => ic.name == m.name).FirstOrDefault();
             if (conflictingItemClass != null)
             {
                 ModelState.AddModelError("name", "There is already a class of this name");
                 return View(m);
             }
             else
             {
                 newItemClass.name = m.name;
                 newItemClass.suggestedGateway = m.suggestedGateway;
                 newItemClass.cPdb = m.cPdb;
                 newItemClass.a = m.a;
                 newItemClass.aMax = m.aMax;
                 newItemClass.d = m.d;
                 newItemClass.aPrime = m.aPrime;
                 newItemClass.cCb = m.cCb;
                 newItemClass.m1 = m.m1;
                 newItemClass.pO = m.pO;
                 newItemClass.m2 = m.m2;
                 newItemClass.cEb = m.cEb;
                 newItemClass.s = m.s;
                 newItemClass.m3 = m.m3;
                 newItemClass.sE = m.sE;
                 newItemClass.m4 = m.m4;
                 newItemClass.sH = m.sH;
                 newItemClass.m5 = m.m5;
                 //save changes
                 db.itemClasses.Add(newItemClass);
                 db.SaveChanges();
                 TempData["AddClass"] = newItemClass.name;
                 return RedirectToAction("ViewClasses");
             }
         }
     }
     else
     {
         return View(m);
     }
 }
Beispiel #2
0
        public ActionResult View(string act, TransactionModel model)
        {
            ACCOUNTERROR.ErrorSubject = "Error while trying to add a transaction";
            if (model.transactionID == null)
            {
                throw new ArgumentNullException("Transaction GUID must be specified");
            }

            if (!(model.result == "Confirmed" || model.result == "Rejected"))
            {
                throw new ArgumentNullException("A transaction must be specified as Confirmed or Rejected");
            }

            using (var db = new CopiosisEntities())
            {
                // Get transaction data
                var transaction = db.transactions.Where(t => t.transactionID == model.transactionID).FirstOrDefault();

                // Make sure a transaction was found.
                if(transaction == null)
                {
                    throw new ArgumentNullException(string.Format("Transaction with ID does not exist", model.transactionID));
                }

                /////////////////////////////////////////////////
                // Check permissions to update this transaction.
                /////////////////////////////////////////////////
                bool update = false;

                // User is the provider and the transaction is waiting on their confirmation.
                if (WebSecurity.CurrentUserId == transaction.providerID && transaction.dateClosed == null)
                {
                    // These are the only things being updated. Anything else sent along in the POST (even if it's in the model)
                    // will be ignored.
                    transaction.providerNotes   = model.providerNotes;
                    transaction.dateClosed      = DateTime.Now;
                    transaction.status          = model.result;

                    // Make sure the DB gets updated below
                    update = true;
                }

                // User is the receiver and the transaction is waiting on their confirmation.
                else if (WebSecurity.CurrentUserId == transaction.receiverID && transaction.dateClosed == null)
                {
                    // Satisfaction must be specified!
                    if (model.satisfaction == null)
                    {
                        this.ModelState.AddModelError("Satisfaction", "Your satisfaction with this transaction must be specified.");
                        return View(model.transactionID);
                    }

                    transaction.receiverNotes   = model.receiverNotes;
                    transaction.satisfaction    = (short)model.satisfaction;
                    transaction.dateClosed      = DateTime.Now;
                    transaction.status          = model.result;

                    // Make sure DB gets updated below.
                    update = true;
                }

                if (update)
                {
                    // Only modify NBRs if the transaction was actually confirmed, and not rejected.
                    if (model.result == "Confirmed")
                    {
                        // Deduct product cost (NBR) from receiver.
                        transaction.receiver.nbr -= transaction.productGateway;
                        transaction.receiver.nbr += 2;

                        // Credit provider with NBR. Bind the NBR to the transaction for records purposes.
                        float providerReward  = CalculateNBR((int)transaction.satisfaction, transaction.productID, transaction.providerID);
                        transaction.provider.nbr += providerReward;
                        transaction.nbr = providerReward;
                    }
                    db.SaveChanges();
                }
            }

            return RedirectToAction("View", new { tranId = model.transactionID });
        }
Beispiel #3
0
        public ActionResult AddItem(AddItemModel m)
        {
            if (ModelState.IsValid)
            {
                //ValidateItemModel(model);
                if (!m.ItemType.Equals("Product", StringComparison.OrdinalIgnoreCase) && !m.ItemType.Equals("Service", StringComparison.OrdinalIgnoreCase))
                {
                    ACCOUNTERROR.ErrorSubject = "Error while trying to add an item";
                    throw new ArgumentException("Items can only be of type Product or Service");
                }
                product p = new product();
                using (var db = new CopiosisEntities())
                {
                    int? itemClassId = db.itemClasses.Where(ic => ic.name == m.ItemClass).Select(i => i.classID).FirstOrDefault();
                    if (itemClassId == null)
                    {
                        ACCOUNTERROR.ErrorSubject = "Error while trying to add an item";
                        throw new ArgumentException("Product item class not found");
                    }

                    int existing = db.products.Where(i => i.name == m.Name && i.ownerID == WebSecurity.CurrentUserId).Count();
                    if (existing > 0)
                    {
                        m.ItemClassTemplates = FetchItemClassTemplates(db);
                        ModelState.AddModelError("name", "There is already an item of this name. Please try again.");
                        return View(m);
                    }

                    p.name = m.Name;
                    p.ownerID = WebSecurity.CurrentUserId;
                    p.guid = Guid.NewGuid();
                    p.gateway = m.Gateway;
                    p.description = m.Description;
                    p.createdDate = DateTime.Now;
                    p.itemClass = (int)itemClassId;
                    p.type = m.ItemType;
                    db.products.Add(p);
                    db.SaveChanges();
                    TempData["currentItem"] = p.name;
                    TempData["addSuccess"] = true;
                }
                return RedirectToAction("Items");
            }
            else
            {
                return View(m);
            }
        }
Beispiel #4
0
        public ActionResult Manage(AccountManagerModel model)
        {
            if (ModelState.IsValid)
            {
                using (var db = new CopiosisEntities())
                {
                    var dbCurrentUser = db.users.Where(p => p.userID == WebSecurity.CurrentUserId).FirstOrDefault();
                    if (dbCurrentUser == null)
                    {
                        ACCOUNTERROR.ErrorSubject = "Error while trying to retrieve your user account";
                        throw new Exception(string.Format("No match for the current user with user name {0}", WebSecurity.CurrentUserId));
                    }
                    ViewBag.isValidatedUser = true;
                    string passwordTemp;
                    bool changePassword;
                    bool noPwProvided;
                    validateManageAccountForm(model, db, dbCurrentUser, out passwordTemp, out changePassword, out noPwProvided);

                    if (ModelState.IsValid == true)
                    {
                        if (changePassword == true)
                        {
                            // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                            bool changePasswordSucceeded = true;
                            try
                            {
                                changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, passwordTemp, model.newPassword);
                            }
                            catch (Exception)
                            {
                                changePasswordSucceeded = false;
                            }

                            if (changePasswordSucceeded == false)
                            {
                                ACCOUNTERROR.ErrorSubject = "Error while trying to update your account";
                                throw new Exception("Could not change your password");
                            }
                            else
                            {
                                try
                                {
                                    WebSecurity.Login(dbCurrentUser.username, passwordTemp);
                                    passwordTemp = model.newPassword;
                                }
                                catch (Exception e)
                                {
                                    ACCOUNTERROR.ErrorSubject = "Error when logging you in";
                                    throw new Exception(e.Message);
                                }
                            }
                        }
                        db.SaveChanges();
                        ViewBag.changesSaved = true;
                        return RedirectToAction("Manage", new { Message = ManageMessageId.AccountChangesSaved });
                    }
                    else
                    {
                        //there was at least one error:
                        ViewBag.changesSaved = false;
                        return View(model);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.changesSaved = false;
            return View(model);
        }
Beispiel #5
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            string sanitizedun = Regex.Replace(model.UserName, @"\s+", "");
            if (ModelState.IsValid && WebSecurity.Login(sanitizedun, model.Password, persistCookie: model.RememberMe))
            {
                using (var db = new CopiosisEntities())
                {
                    var x = db.users.Where(u => u.username == model.UserName).First();
                    x.prevLastLogin = x.lastLogin.HasValue ? x.lastLogin.Value : (DateTime?)null;
                    x.lastLogin = DateTime.Now;
                    db.SaveChanges();
                }
                return RedirectToAction("Overview");
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }
Beispiel #6
0
        public ActionResult EditItem(AddItemModel model, Guid itemId)
        {
            using (var db = new CopiosisEntities())
            {
                var item = db.products.Where(p => p.guid == itemId && p.ownerID == WebSecurity.CurrentUserId).FirstOrDefault();
                int itemClassId = db.itemClasses.Where(ic => ic.name == model.ItemClass).Select(i => i.classID).First();
                int existing = db.products.Where(i => i.name == model.Name && i.ownerID == WebSecurity.CurrentUserId).Count();
                if (item == null)
                {
                    ACCOUNTERROR.ErrorSubject = "Error while trying to edit an item";
                    throw new ArgumentException(string.Format("Product with ID {0} not found", itemId));
                }
                else if (existing > 0 && model.Name != item.name)
                {
                    model.ItemClassTemplates = FetchItemClassTemplates(db);
                    ModelState.AddModelError("name", "There is already an item of this name. Please try again.");
                    return View(model);
                }
                else
                {
                    item.name = model.Name;
                    item.description = model.Description;
                    item.gateway = model.Gateway;
                    item.itemClass = itemClassId;
                    item.type = model.ItemType;
                    db.SaveChanges();
                    TempData["currentItem"] = item.name;
                    TempData["editSuccessful"] = true;

                }
            }
            return RedirectToAction("Items");
        }
Beispiel #7
0
        // POST: /Account/DeleteItem
        // Deactivate an item. Take the GUID of the item as a parameter
        public ActionResult DeleteItem(Guid itemId)
        {
            bool result = true;
            using(var db = new CopiosisEntities())
            {
                var item = db.products.Where(p => p.guid == itemId && p.ownerID == WebSecurity.CurrentUserId && p.deletedDate == null).FirstOrDefault();
                if(item == null)
                {
                    result = false;
                }
                else
                {
                    item.deletedDate = DateTime.Now;
                    db.SaveChanges();
                    TempData["itemDeleted"] = item.name;
                }
            }

            if(result)
            {
                return RedirectToAction("Items");
            }
            else
            {
                ModelState.AddModelError("DeletionError", "Unable to delete item");
                return View("Items", CurrenUserItems());
            }
        }
Beispiel #8
0
        public ActionResult Create(string type, NewTransactionModel model)
        {
            ACCOUNTERROR.ErrorSubject = "Error while trying create a transaction";
            if (type == null)
            {
                throw new ArgumentNullException("Type of transaction must be specified");
            }

            string typeLower = type.ToLower();
            if(type == "consumer")
            {
                string[] producerName = model.Producer.Split('|');
                string producerUN = producerName != null ? producerName[1].Trim() : "";

                string[] productName = model.ProductProvided.Split('|');
                string productUN = productName[0] != null ? productName[0].TrimEnd() : "";
                using(var db = new CopiosisEntities())
                {
                    var producer = db.users.Where(u => u.username == producerUN && u.status == 1).FirstOrDefault();
                    string producerFirstLast = db.users.Where(m => m.username == producerUN).Select(u => u.firstName).FirstOrDefault()
                        + " " + db.users.Where(m => m.username == producerUN).Select(u => u.lastName).FirstOrDefault();
                    if (producer == null)
                    {
                        throw new ArgumentException(string.Format("Producer {0} not found", producerUN));
                    }

                    var product = db.products.Where(p => p.ownerID == producer.userID && p.name == productUN && p.deletedDate == null).FirstOrDefault();
                    if(product == null)
                    {
                        throw new ArgumentException(string.Format("Product {0} not found", productUN));
                    }
                    double? currentUserNBR = db.users.Where(u => u.userID == WebSecurity.CurrentUserId).Select(u => u.nbr).FirstOrDefault();
                    if(!currentUserNBR.HasValue || currentUserNBR.Value < product.gateway)
                    {
                        ModelState.AddModelError("Producer", "You do not have enough NBR for this good or service");
                        PopulateNewTransactionModel(type, model);
                        return View(model);
                    }

                    if (model.SatisfactionRating < -2 || model.SatisfactionRating > 2)
                    {
                        ModelState.AddModelError("Satisfaction", "You must select a satisfaction rating by selecting an icon.");
                        PopulateNewTransactionModel(type, model);
                        return View(model);
                    }

                    transaction consumerTran = new transaction();
                    consumerTran.transactionID = Guid.NewGuid();
                    consumerTran.createdBy = WebSecurity.CurrentUserId;
                    consumerTran.dateAdded = DateTime.Now;
                    consumerTran.providerID = producer.userID;
                    consumerTran.productID = product.productID;
                    consumerTran.productDesc = product.description;
                    consumerTran.receiverID = WebSecurity.CurrentUserId;
                    consumerTran.status = "PENDING";
                    consumerTran.receiverNotes = model.Notes;
                    consumerTran.satisfaction = (short)model.SatisfactionRating;
                    consumerTran.productGateway = product.gateway;
                    db.transactions.Add(consumerTran);
                    db.SaveChanges();
                    TempData["consumerAdd"] = true;
                    TempData["producerIs"] = producerFirstLast;
                }
            }
            else if(type == "producer")
            {
                string[] consumerName = model.Consumer.Split('|');
                string consumerUN = consumerName[1] != null ? consumerName[1].Trim(): "";
                string[] productName = model.ProductProvided.Split('|');
                string productUN = productName[0] != null ? productName[0].TrimEnd() : "";
                using(var db = new CopiosisEntities())
                {
                    var consumer = db.users.Where(u => u.username == consumerUN && u.status == 1).FirstOrDefault();
                    TempData["consumerIs"] = db.users.Where(m => m.username == consumerUN).Select(u => u.firstName).FirstOrDefault()
                        + " " + db.users.Where(m => m.username == consumerUN).Select(u => u.lastName).FirstOrDefault();
                    if(consumer == null)
                    {
                        throw new ArgumentException(string.Format("Consumer {0} not found", consumerUN));
                    }

                    var product = db.products.Where(p => p.ownerID == WebSecurity.CurrentUserId && p.name == productUN && p.deletedDate == null).FirstOrDefault();
                    if(product == null)
                    {
                        throw new ArgumentException(string.Format("Product {0} not found", productUN));
                    }

                    double? consumerNBR = db.users.Where(u => u.userID == consumer.userID).Select(u => u.nbr).FirstOrDefault();
                    if (!consumerNBR.HasValue || consumerNBR.Value < product.gateway)
                    {
                        ModelState.AddModelError("Consumer", "The consumer " + TempData["consumerIs"] + " does not have enough NBR for this good or service");
                        PopulateNewTransactionModel(type, model);
                        return View(model);
                    }

                    transaction producerTran = new transaction();
                    producerTran.transactionID = Guid.NewGuid();
                    producerTran.createdBy = WebSecurity.CurrentUserId;
                    producerTran.dateAdded = DateTime.Now;
                    producerTran.providerID = WebSecurity.CurrentUserId;
                    producerTran.productID = product.productID;
                    producerTran.productDesc = product.description;
                    producerTran.receiverID = consumer.userID;
                    producerTran.status = "PENDING";
                    producerTran.providerNotes = model.Notes;
                    producerTran.productGateway = product.gateway;

                    db.transactions.Add(producerTran);
                    db.SaveChanges();
                    TempData["producerAdd"] = true;

                }
            }
            else
            {
                throw new ArgumentException("Transaction type not recognized");
            }
            return RedirectToAction("Overview");
        }
Beispiel #9
0
        public ActionResult AddNotes(string participant, string notes, Guid tranId, short? newSatisfaction)
        {
            using (var db = new CopiosisEntities())
            {
                int userId = WebSecurity.CurrentUserId;
                var trans = db.transactions.Where(a => a.transactionID == tranId).FirstOrDefault();
                if(participant == null)
                {
                    return Json(new { success = false });
                }

                if(participant.Equals("producer", StringComparison.OrdinalIgnoreCase))
                {
                    if(trans.providerID == userId)
                    {
                        trans.providerNotes = notes;
                    }
                    else
                    {
                        return Json(new { success = false });
                    }
                }
                else if (participant.Equals("consumer", StringComparison.OrdinalIgnoreCase))
                {
                    if (trans.receiverID == userId)
                    {
                        if (newSatisfaction != null)
                        {
                            trans.satisfaction = newSatisfaction;
                        }
                        trans.receiverNotes = notes;
                    }
                    else
                    {
                        return Json(new { success = false });
                    }
                }
                else
                {
                    return Json(new { success = false });
                }
                db.SaveChanges();
            }
            return Json(new { success = true });
        }
Beispiel #10
0
        public ActionResult EditClass(AddClassModel model, string className)
        {
            if (ModelState.IsValid)
            {
                using (var db = new CopiosisEntities())
                {
                    var currentItemClass = db.itemClasses.Where(p => p.name == className).FirstOrDefault();
                    if (currentItemClass == null)
                    {
                        ADMINERROR.ErrorSubject = "Error while trying to edit an item";
                        throw new ArgumentException(string.Format("ItemClass with Name {0} not found", className));
                    }
                    else
                    {
                        if (model.name.Equals(currentItemClass.name) == false)
                        {
                            itemClass conflictingItemClass = db.itemClasses.Where(ic => ic.name == model.name).FirstOrDefault();
                            if (conflictingItemClass != null)
                            {
                                ModelState.AddModelError("name", "There is already a class of this name");
                                return View(model);
                            }
                        }
                        //Case when the are no changes to the current class
                        else if (model.Equals(currentItemClass) == true)
                        {
                            TempData["NoEdit"] = currentItemClass.name;
                            return RedirectToAction("ViewClasses");
                        }
                        currentItemClass.name = model.name;
                        currentItemClass.suggestedGateway = model.suggestedGateway;
                        currentItemClass.cPdb = model.cPdb;
                        currentItemClass.a = model.a;
                        currentItemClass.aMax = model.aMax;
                        currentItemClass.d = model.d;
                        currentItemClass.aPrime = model.aPrime;
                        currentItemClass.cCb = model.cCb;
                        currentItemClass.m1 = model.m1;
                        currentItemClass.pO = model.pO;
                        currentItemClass.m2 = model.m2;
                        currentItemClass.cEb = model.cEb;
                        currentItemClass.s = model.s;
                        currentItemClass.m3 = model.m3;
                        currentItemClass.sE = model.sE;
                        currentItemClass.m4 = model.m4;
                        currentItemClass.sH = model.sH;
                        currentItemClass.m5 = model.m5;
                        db.SaveChanges();
                        TempData["EditClass"] = currentItemClass.name;
                        return RedirectToAction("ViewClasses");

                    }
                }
            }
            else
            {
                return View(model);
            }
        }
Beispiel #11
0
        public ActionResult ChangeUserIsAdmin(string roleAction, string userName)
        {
            using (var db = new CopiosisEntities())
            {
                var user = db.users.Where(p => p.username == userName).FirstOrDefault();
                var roles = db.webpages_Roles.Where(r => r.RoleName == "ADMIN").FirstOrDefault();

                if (user == null)
                    throw new ArgumentException(string.Format("No user found with that username: {0}", userName));

                if (user.userID == WebSecurity.CurrentUserId)
                    throw new ArgumentException(string.Format("Sorry, you can't demote yourself!: {0}", userName));

                if(roles == null)
                    throw new ArgumentException(string.Format("The role: {0} does not exist", "ADMIN"));

                //we are adding
                if (roleAction.ToLower() == "promote")
                {
                    if (!roles.users.Contains(user))
                        roles.users.Add(user);
                }
                else
                {
                    if (roles.users.Contains(user))
                        roles.users.Remove(user);
                    else
                        throw new ArgumentException(string.Format("{0} is not currently an admin.", user.username));
                }
                db.SaveChanges();
            }
            return Json(new { success = true });
        }
Beispiel #12
0
        public ActionResult ChangeClass(string newClass, Guid itemGuid)
        {
            using (var db = new CopiosisEntities())
            {
                var item = db.products.Where(p => p.guid == itemGuid).FirstOrDefault();
                var classID = db.itemClasses.Where(ic => ic.name == newClass).Select(ic => ic.classID).FirstOrDefault();
                ADMINERROR.ErrorSubject = "Error while trying to change an item's class";
                if (item == null)
                {
                    throw new ArgumentException(string.Format("No product found with GUID: {0}", itemGuid));
                }
                if (classID == null)
                {
                    throw new ArgumentException(string.Format("No matching item class with name: {0}", itemGuid));
                }

                item.itemClass = classID;
                db.SaveChanges();
            }
            return Json(new { success = true });
        }