//Validates and set goals and sets inequality
        public bool ValidateSetGoalsInequality(int inequality, ref Goal goal, string meetsValue, string meetsPlusValue, string exceedsValue)
        {
            bool error = false;
            bool meetsIsDecimal = false, meetsPlusIsDecimal = false, exceedsIsDecimal = false;

            //This allows for goals to be null. Convert to decimal only if the goal is not an empty string
            if (meetsValue.Trim().Equals(""))
            {
                goal.Meets_Val = null;
            }
            else
            {
                decimal meetsDec;
                meetsIsDecimal = decimal.TryParse(meetsValue, out meetsDec);
                if (meetsIsDecimal)
                    goal.Meets_Val = meetsDec;
                else
                {
                    TempData["Error"] += "Meets goal must be numbers!\n";
                    error = true;
                }
            }
            if (meetsPlusValue.Trim().Equals(""))
            {
                goal.Meets_Plus_Val = null;
            }
            else
            {
                decimal meetsPlusDec;
                meetsPlusIsDecimal = decimal.TryParse(meetsPlusValue, out meetsPlusDec);
                if (meetsPlusIsDecimal)
                    goal.Meets_Plus_Val = meetsPlusDec;
                else
                {
                    TempData["Error"] += "Meets Plus goal must be numbers!\n";
                    error = true;
                }
            }

            if (exceedsValue.Trim().Equals(""))
            {
                goal.Exceeds_Val = null;
            }
            else
            {
                decimal exceedsDec;
                exceedsIsDecimal = decimal.TryParse(exceedsValue, out exceedsDec);
                if (exceedsIsDecimal)
                    goal.Exceeds_Val = exceedsDec;
                else
                {
                    TempData["Error"] += "Exceeds goal must be numbers!\n";
                    error = true;
                }
            }

            //less-than or equal to
            switch (inequality)
            {
                case 0:
                    goal.Typ = "<=";
                    if (meetsPlusIsDecimal && exceedsIsDecimal && goal.Meets_Plus_Val <= goal.Exceeds_Val)
                    {
                        TempData["Error"] += "For a <= goal, the Meets+ goal should be greater than the Exceeds goal!\n";
                        error = true;
                    }
                    if (meetsIsDecimal && meetsPlusIsDecimal && goal.Meets_Val <= goal.Meets_Plus_Val)
                    {
                        TempData["Error"] += "For a <= goal, the Meets goal should be greater than the Meets+ goal!\n";
                        error = true;
                    }
                    if (meetsIsDecimal && exceedsIsDecimal && goal.Meets_Val <= goal.Exceeds_Val)
                    {
                        TempData["Error"] += "For a <= goal, the Meets goal should be greater than the Exceeds goal!\n";
                        error = true;
                    }
                    break;
                case 1:
                    goal.Typ = ">=";
                    if (meetsIsDecimal && meetsPlusIsDecimal && goal.Meets_Val >= goal.Meets_Plus_Val)
                    {
                        TempData["Error"] += "For a >= goal, the Meets goal should be less than the Meets+ goal!\n";
                        error = true;
                    }
                    if (meetsIsDecimal && exceedsIsDecimal && goal.Meets_Val >= goal.Exceeds_Val)
                    {
                        TempData["Error"] += "For a >= goal, the Meets goal should be less than the Exceeds goal!\n";
                        error = true;
                    }
                    if (meetsPlusIsDecimal && exceedsIsDecimal && goal.Meets_Plus_Val >= goal.Exceeds_Val)
                    {
                        TempData["Error"] += "For a >= goal, the Meets+ goal should be less than the Exceeds goal!\n";
                        error = true;
                    }
                    break;
            }
            return !error;
        }
        public ActionResult NewGoal()
        {
            Goal goal = new Goal();
            string user = User.Identity.Name;
            string measureIdString = Request["hiddenGoalMeasurementId"];
            string inequalityString = Request["Inequality"];
            string meetsString = Request["newGoalMeets"].Replace(",", "").Replace("$", "").Replace("%", "");
            string meetsPlusString = Request["newGoalMeetsPlus"].Replace(",", "").Replace("$", "").Replace("%", "");
            string exceedsString = Request["newGoalExceeds"].Replace(",", "").Replace("$", "").Replace("%", "");
            string weightString = Request["newGoalWeight"];
            string appliesAfterDateString = Request["newGoalAppliesAfter"];
            string goalCategoryString = Request["GoalCategory"];
            string goalComment = Request["newGoalComment"];
            GoalAudit goalAudit = new GoalAudit();

            //Validates Measure ID
            if (!ValidateMeasureId(measureIdString))
                return RedirectToAction("Index");
            int measureId = Convert.ToInt32(measureIdString);

            TempData["OldMeasureId"] = measureId;

            if (meetsString.Length == 0 && meetsPlusString.Length == 0 && exceedsString.Length == 0)
            {
                TempData["Error"] = "Did not save, Must have at least one goal!";
                return RedirectToAction("Index");
            }

            //User identity checking
            if (!ValidateUserName(user))
                return RedirectToAction("Index");
            goal.Sbmt_By = User.Identity.Name.Substring(0,3);

            Measurement measure = _repository.GetMeasurementFromId(measureId);

            if (measure == null)
            {
                TempData["Error"] = "Invalid Measurement, Not Found in Database!";
                return RedirectToAction("Index");
            }
            goal.Measurement_ID = measureId;

            //inequality Validation
            if (!ValidateInequalityId(inequalityString))
                return RedirectToAction("Index");
            int inequality = Convert.ToInt32(inequalityString[0]) - 48;

            //Validation for goals and sets the values
            if (!ValidateSetGoalsInequality(inequality, ref goal, meetsString, meetsPlusString, exceedsString))
                return RedirectToAction("Index");

            measure.Has_Goal_IN = 1;

            //Validates Weight
            if (!ValidateWeight(weightString))
                return RedirectToAction("Index");
            decimal weight = Convert.ToDecimal(weightString);
            if (weight > 0 && weight <= 1)
                weight *= 100;
            goal.Wgt = (int)weight;

            //Validates Applies After Date
            if (!ValidateAppliesAfterDate(appliesAfterDateString))
                return RedirectToAction("Index");
            try
            {
                DateTime date = Convert.ToDateTime(appliesAfterDateString + " 12:00:00 AM");
                goal.Applies_After_Tmstp = date;
            }
            catch (FormatException ex)
            {
                TempData["Error"] = "Date is improperly formatted! Error: " + ex.Message + "\n";
                return RedirectToAction("Index");
            }

            //Validates Goal Category
            if (!ValidateGoalCategoryId(goalCategoryString))
                return RedirectToAction("Index");
            int goalCategory = Convert.ToInt32(goalCategoryString);
            goal.GoalCategory_ID = goalCategory;

            try
            {
                _db.Measurements.AddOrUpdate(measure);
                _db.Goals.Add(goal);

                if(!ValidateComment(goalComment))
                    return RedirectToAction(("Index"));
                //Create a new entry in goalAudit table
                goalAudit.Goal = goal;
                goalAudit.Description_TXT = "A new goal was created.";
                goalAudit.Changed_DT = DateTime.Now;
                goalAudit.Reason_TXT = goalComment;
                _db.GoalAudits.Add(goalAudit);

                _db.SaveChanges();
                TempData["Success"] = "You've added a new goal to " + measure.NM + "!";

            }
            catch (DbEntityValidationException)
            {
                TempData["Error"] = "Database error, please try again later!";
            }
            catch (DbException)
            {
                TempData["Error"] = "Database error, please try again later!";
            }

            return RedirectToAction("Index");
        }
        public ActionResult AddMeasure()
        {
            try
            {
                Measurement measurement = new Measurement();
                measurement.Measurement_ID = measurement.Measurement_ID = (int)(DateTime.UtcNow.Ticks / 1000000);
                Goal goal = new Goal();
                CalculatedMeasurement calculatedMeasurement = new CalculatedMeasurement();

                string user = User.Identity.Name.Substring(0,3);

                //Basic Measurement Information
                string measurementName = Request["txtMeasurementName"].Trim();
                string measurementDescription = Request["txtDescription"].Trim();
                string dept = Request["Depts"];
                string typeString = Request["Type_ID"];
                string categoryString = Request["Category_ID"];
                string checkboxIsSla = Request["checkSLA"];
                string checkboxIsUnitCost = Request["checkUnitCost"];
                string decimalPlaces = Request["Decimal"];
                string ytdCalc = Request["YtdCalc"] ?? "2";

                //Goal Input Items
                string meetsValue = Request["txtMeets"].Replace(",", "").Replace("$", "").Replace("%", "");
                string meetsPlusValue = Request["txtMeetsPlus"].Replace(",", "").Replace("$", "").Replace("%", "");
                string exceedsValue = Request["txtExceeds"].Replace(",", "").Replace("$", "").Replace("%", "");
                string inequalityString = Request["Inequality"];
                string appliesAfterD = Request["dpAppliesAfter"];
                string weightString = Request["txtWeight"];
                string goalCategoryString = Request["GoalCategory"];

                //IDs from calculated measurement
                string checkboxCalculated = Request["checkCalculated"];
                string equation = Request["calculatedFormula"];

                //Department information
                if (!ValidateDeptId(dept))
                    return RedirectToAction("Index");
                measurement.Department_ID = int.Parse(dept);

                //Start Basic Information
                measurement.Activated_IN = 1;

                if (!(ValidateMeasurementName(measurementName)))
                    return RedirectToAction("Index");
                measurement.NM = measurementName;

                if (!ValidateMeasurementDescription(measurementDescription))
                    return RedirectToAction("Index");
                measurement.Description_TXT = measurementDescription;

                //set create date
                measurement.Created_DT = DateTime.Today;

                //validate measurement type
                if (!ValidateTypeId(typeString))
                    return RedirectToAction("Index");
                int type = Convert.ToInt32(typeString);
                measurement.Type_ID = type;

                //validate measure category
                if (!ValidateCategoryId(categoryString))
                    return RedirectToAction("Index");
                int category = Convert.ToInt32(categoryString);
                measurement.Category_ID = category;

                //SLA checkbox validation
                short isSla = 0;
                if (checkboxIsSla.Contains("true"))
                    isSla = 1;
                measurement.SLA_IN = isSla;

                //Unit Cost checkbox validation
                short isUnitCost = 0;
                if (checkboxIsUnitCost.Contains("true"))
                    isUnitCost = 1;
                measurement.Is_UnitCost_IN = isUnitCost;

                if (!ValidateDecimalPlaces(decimalPlaces))
                    return RedirectToAction("Index");
                measurement.Decimal_Points_SZ = Convert.ToInt32(decimalPlaces);

                if (!ValidateYtdCalc(ytdCalc))
                    return RedirectToAction("Index");
                measurement.YTD_Calc = Convert.ToInt32(ytdCalc);

                //Start of Goal infomation
                measurement.Has_Goal_IN = 0;
                if (meetsValue.Length != 0 || meetsPlusValue.Length != 0 || exceedsValue.Length != 0)
                    measurement.Has_Goal_IN = 1;

                //Goal checking. if one goal is entered, all must be entered.
                if (measurement.Has_Goal_IN != 0)
                {
                    if (!ValidateAppliesAfterDate(appliesAfterD))
                        return RedirectToAction("Index");

                    try
                    {
                        DateTime date = Convert.ToDateTime(appliesAfterD + " 12:00:00 AM");
                        goal.Applies_After_Tmstp = date;
                    }
                    catch (FormatException ex)
                    {
                        TempData["Error"] = "Date is improperly formatted! Error: " + ex.Message + "\n";
                        return RedirectToAction("Index");
                    }

                    //User identity checking
                    if (!ValidateUserName(user))
                        return RedirectToAction("Index");
                    goal.Sbmt_By = User.Identity.Name.Substring(0, 3);

                    //inequality Validation
                    if (!ValidateInequalityId(inequalityString))
                        return RedirectToAction("Index");
                    int inequality = Convert.ToInt32(inequalityString[0]) - 48;

                    //Validation for goals and sets the values
                    if (!ValidateSetGoalsInequality(inequality, ref goal, meetsValue, meetsPlusValue, exceedsValue))
                        return RedirectToAction("Index");

                    //weight valiation
                    if (!ValidateWeight(weightString))
                        return RedirectToAction("Index");
                    decimal weight = Convert.ToDecimal(weightString);
                    if (weight > 0 && weight <= 1)
                        weight *= 100;
                    goal.Wgt = (int)weight;

                    //Goal Category validation
                    if (!ValidateGoalCategoryId(goalCategoryString))
                        return RedirectToAction("Index");
                    int goalCategory = Convert.ToInt32(goalCategoryString);
                    goal.GoalCategory_ID = goalCategory;

                    goal.Measurement = measurement;
                }

                //Start of Calculated Information
                //Get Calc Measurement formula and convert it to an int array
                short isCalculated = 0;
                if (checkboxCalculated.Contains("true"))
                {
                    isCalculated = 1;
                    // If valid, store
                    // (this includes the generic exception handler)
                    if (!ValidateCalculation(equation))
                        return RedirectToAction("Index");

                    calculatedMeasurement.Measurement = measurement;
                    calculatedMeasurement.Formula = equation;

                    measurement.YTD_Calc = 2;

                }
                measurement.Is_Calculated = isCalculated;

                Submit(measurement, goal, calculatedMeasurement);
                TempData["OldMeasureId"] = measurement.Measurement_ID;
            }
            catch (HttpRequestValidationException)
            {
                TempData["Error"] = "Markup is not allowed in any fields!";
            }
            catch (DbException)
            {
                TempData["Error"] = "Something went wrong in the database, please try again later!";
            }
            return RedirectToAction("Index");
        }
        //submit to database
        private void Submit(Measurement measurement, Goal goal, CalculatedMeasurement calculatedMeasurement)
        {
            if (!ModelState.IsValid) return;

            _db.Measurements.Add(measurement);

            if (measurement.Has_Goal_IN != 0)
                _db.Goals.Add(goal);

            if (measurement.Is_Calculated == 1)
                _db.CalculatedMeasurements.Add(calculatedMeasurement);
            try
            {
                _db.SaveChanges();
                TempData["Success"] = "You have successfully added a measurement!";
            }
            catch (DbException)
            {
                TempData["Error"] = "Database error!  Try again later!";
            }
            catch (DbUpdateException)
            {
                TempData["Error"] = "Database error, data may have been invalid, please try again!";
            }
        }
 public void ValidateSetGoalsInequalitySuccessWithOneGoal()
 {
     const bool expected = true;
     int inequality = 0;
     Goal goal = new Goal();
     string meetsValue = "";
     string meetsPlusValue = "";
     string exceedsValue = "1";
     var result = controller.ValidateSetGoalsInequality(inequality, ref goal, meetsValue, meetsPlusValue,
         exceedsValue);
     Assert.That(result.Equals(expected));
 }
 public void ValidateSetGoalsInequalityFailMeetsPlusNotInt()
 {
     const bool expected = false;
     int inequality = 0;
     Goal goal = new Goal();
     string meetsValue = "3";
     string meetsPlusValue = "Not Int";
     string exceedsValue = "1";
     var result = controller.ValidateSetGoalsInequality(inequality, ref goal, meetsValue, meetsPlusValue,
         exceedsValue);
     Assert.That(result.Equals(expected));
 }