Example #1
0
        /// <summary>
        /// Retrieves the StatusDetail by StatusDetailMaster Id and StatusDetail identifier
        /// </summary>
        /// <param name="statusMasterId"></param>
        /// <param name="identifier"></param>
        /// <returns></returns>
        public def_StatusDetail GetStatusDetailByMasterIdentifier(int statusMasterId, string identifier)
        {
            def_StatusDetail statusDetail = db.def_StatusDetail.Where(d => (d.statusMasterId == statusMasterId) && (d.identifier == identifier)).FirstOrDefault();

            if (statusDetail == null)
            {
                // Most queries only using sortOrder, populated some fields to prevent exceptions
                statusDetail = new def_StatusDetail()
                {
                    identifier = string.Empty,
                    sortOrder  = 0,
                    Active     = "I"
                };
            }
            return(statusDetail);
        }
Example #2
0
        internal static void ChangeStatus(IFormsRepository formsRepo, def_FormResults formResult, int newStatus, string note = "")
        {
            def_StatusDetail statusFrom = formsRepo.GetStatusDetailBySortOrder(STATUS_MASTER_ID, formResult.reviewStatus);

            def_StatusDetail statusTo = formsRepo.GetStatusDetailBySortOrder(STATUS_MASTER_ID, newStatus);

            if (statusTo != null)
            {
                formResult.reviewStatus = (byte)statusTo.sortOrder.Value;
            }
            else
            {
                formResult.reviewStatus = (byte)BLANK;
            }

            LogStatusChange(formsRepo, formResult.formResultId, statusFrom, statusTo, note);
        }
        private string GetAllStatusComments(int formResultId, string newLine, string tab)
        {
            string result = "";

            def_FormResults            fr            = formsRepo.GetFormResultById(formResultId);
            def_StatusMaster           statusMaster  = formsRepo.GetStatusMasterByFormId(fr.formId);
            List <def_StatusDetail>    statusDetails = formsRepo.GetStatusDetails(statusMaster.statusMasterId);
            List <def_StatusText>      statusTexts   = statusDetails.Select(sd => formsRepo.GetStatusTextByDetailSortOrder(statusMaster.statusMasterId, sd.sortOrder.Value)).ToList();
            IQueryable <def_StatusLog> statusLogs    = formsRepo.GetStatusLogsForFormResultId(fr.formResultId).OrderByDescending(sl => sl.statusLogDate);

            foreach (def_StatusLog sl in statusLogs)
            {
                def_StatusDetail sdFrom = statusDetails.Where(sd => sd.statusDetailId == sl.statusDetailIdFrom).FirstOrDefault();
                def_StatusDetail sdTo   = statusDetails.Where(sd => sd.statusDetailId == sl.statusDetailIdTo).FirstOrDefault();
                if (sdFrom == null)
                {
                    throw new Exception("could not find def_StatusDetail for statusDetailIdFrom " + sl.statusDetailIdFrom + " in def_StatusLog " + sl.statusLogId);
                }
                if (sdTo == null)
                {
                    throw new Exception("could not find def_StatusDetail for statusDetailIdTo " + sl.statusDetailIdTo + " in def_StatusLog " + sl.statusLogId);
                }

                def_StatusText stFrom = statusTexts.Where(st => st.statusDetailId == sdFrom.statusDetailId).FirstOrDefault();
                def_StatusText stTo   = statusTexts.Where(st => st.statusDetailId == sdTo.statusDetailId).FirstOrDefault();
                if (stFrom == null)
                {
                    throw new Exception("could not find def_StatusText for statusDetailId " + sdFrom.statusDetailId);
                }
                if (stTo == null)
                {
                    throw new Exception("could not find def_StatusText for statusDetailId " + sdTo.statusDetailId);
                }

                result += "<span style='color:Red'>" + sl.statusLogDate + "</span> - " + stFrom.displayText + " -> " + stTo.displayText + newLine;
                result += tab + sl.statusNote + newLine + "<hr>";
            }
            //statusLog.statusDetailIdFrom = formsRepo.GetStatusDetailBySortOrder(statusMasterId, oldStatus).statusDetailId;
            //statusLog.statusDetailIdTo = formsRepo.GetStatusDetailBySortOrder(statusMasterId, status).statusDetailId;
            //statusLog.formResultId = result.formResultId;
            //statusLog.UserID = SessionHelper.LoginStatus.UserID;
            //statusLog.statusLogDate = DateTime.Now;

            return(result);
        }
Example #4
0
        /// <summary>
        /// Get the list of possible Application Status based on the method parameters
        ///         rolePermission [Applicant 0, Staff 1, Mgt 2])
        /// </summary>
        /// <param name="formsRepo">FormsRepository interface</param>
        /// <param name="currentStatus">current application status code</param>
        /// <param name="rolePermission">Role Permission of User</param>
        /// <returns></returns>
        public static Dictionary <int, string> PossibleWorkflow(IFormsRepository formsRepo, int statusMasterId, int currentStatus, int rolePermission)
        {
            Dictionary <int, string> possibleStatus = new Dictionary <int, string>();

            string currentStatusIdentifier = formsRepo.GetStatusDetailBySortOrder(statusMasterId, currentStatus).identifier;
            int    enterpriseId            = SessionHelper.LoginStatus.EnterpriseID;

            string[] nextWorkflowStatuses = GetNextWorkflowStatusIdentifiers(currentStatusIdentifier, statusMasterId);
            foreach (string statusIdentifier in nextWorkflowStatuses)
            {
                def_StatusDetail sd = formsRepo.GetStatusDetailByMasterIdentifier(statusMasterId, statusIdentifier);
                def_StatusText   st = formsRepo.GetStatusText(sd.statusDetailId, enterpriseId, 1);
                int    sortOrder    = sd.sortOrder.Value;
                string text         = st.displayText;
                possibleStatus.Add(sortOrder, text);
            }

            return(possibleStatus);
        }
        /// <summary>
        /// Determines the next schedualed recertification date for a given applicant.
        /// This method shouldn't be called when the count of approved applications is 0, returns 1/1/0001 if it is.
        ///
        /// Base Rule: END of birth month, END of birth month +6.
        ///
        /// Upon first approval, if base rule results in less than 3 months, advance to the next 6 month date.  E.g. birth month March,
        /// initially approved July.  Instead of recert due Sept 30, due next March 31.  Exception applies for initial approval.
        /// After that, even if a recert is late, it doesn't delay the next recert due from the Base Rule.
        /// </summary>
        ///
        /// <param name="formResultUser">a formResultUser view record for the fiven applicant</param>
        ///
        /// <param name="query">the full set of formResultUsers to consider in computing the recertification date.
        /// Any records that aren't approved or that have a "subject" that does not match the given applicant will be ignored.</param>
        ///
        /// <returns>DateTime of the next Recertification date, defaults to null if calculation does not apply.</returns>
        private DateTime?GetRecert(IFormsRepository formsRepo, vFormResultUser formResultUser, IEnumerable <vFormResultUser> query)
        {
            if (!sortOrderForApprovedStatusDetail.HasValue)
            {
                def_StatusDetail sd = formsRepo.GetStatusDetailByMasterIdentifier(1, "APPROVED");
                sortOrderForApprovedStatusDetail = Convert.ToInt32(sd.sortOrder);
            }
            // Get applications for the applicant so Recertification can be determined.
            IEnumerable <vFormResultUser> apprRcrd = query.Where(fr => fr.formStatus == sortOrderForApprovedStatusDetail && fr.subject == formResultUser.subject).OrderByDescending(fr => fr.statusChangeDate);
            int acceptCount = apprRcrd.Count();

            if (acceptCount == 0)
            {
                return(null);
            }

            DateTime recentRecert = Convert.ToDateTime(apprRcrd.Select(fr => fr.statusChangeDate).FirstOrDefault());

            return(new Applications(formsRepo).GetRecert(formResultUser.DOB, acceptCount, recentRecert));
        }
Example #6
0
        public void DeleteStatusDetail(def_StatusDetail statusDetail)
        {
            db.def_StatusDetail.Remove(statusDetail);

            db.SaveChanges();
        }
Example #7
0
        public void SaveStatusDetail(def_StatusDetail statusDetail)
        {
            db.Entry(statusDetail).State = EntityState.Modified;

            db.SaveChanges();
        }
Example #8
0
        public void AddStatusDetail(def_StatusDetail statusDetail)
        {
            db.def_StatusDetail.Add(statusDetail);

            db.SaveChanges();
        }
Example #9
0
        public static void TransformAndAppendResponseNodesToXML(
            XmlNode appendTo, XmlDocument doc, DefResponseElement rspElement, int formResultId, IFormsRepository formsRepo)
        {
            string elementContent = null;

            //super-special case for Enrollment_Type, which is based on the formStatus, rather than responses
            if (rspElement.tagName == "Enrollment_Type")
            {
                #region check the formResult.formStatus field to determin enrollment type

                def_FormResults  fr           = formsRepo.GetFormResultById(formResultId);
                def_StatusMaster statusMaster = formsRepo.GetStatusMasterByFormId(fr.formId);
                def_StatusDetail statusDetail = formsRepo.GetStatusDetailBySortOrder(statusMaster.statusMasterId, fr.formStatus);
                switch (statusDetail.identifier)
                {
                case "NEEDS_INFORMATION":
                    elementContent = "2";
                    break;

                case "APPROVED":
                    elementContent = "2";
                    break;

                default:
                    elementContent = "1";
                    break;
                }

                #endregion
            }

            if (rspElement.tagName == "Email")
            {
                #region check uas tables for email
                using (UASEntities context = Data.Concrete.DataContext.getUasDbContext())
                {
                    def_FormResults fr   = formsRepo.GetFormResultById(formResultId);
                    var             data = from ue in context.uas_UserEmail
                                           where ue.UserID == fr.subject &&
                                           ue.EmailAddress != null &&
                                           ue.MayContact
                                           orderby ue.SortOrder
                                           select ue.EmailAddress;
                    elementContent = data.FirstOrDefault();
                }
                #endregion
            }

            if (rspElement.tagName == "Mailing_Address" || rspElement.tagName == "Mailing_City" ||
                rspElement.tagName == "Mailing_State" || rspElement.tagName == "Mailing_Zip")
            {
                def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultIdentifier(formResultId, "ADAP_C2_SameAsMailing");
                if (rv.rspInt != null && rv.rspInt == 1)
                {
                    return;
                }
            }

            //assign a special-case transformation value if applicable
            if (elementContent == null)
            {
                elementContent = RamsellTransformations.GetExportValueForRamsellTag(rspElement.tagName, formResultId, formsRepo);
            }

            //if elementContent has been assigned a non-null value,
            //it must have been assigned to handle a one-off special case (above),
            //so append one node with elementContent and terminate this function
            if (elementContent != null)
            {
                AppendContentNodeToXML(appendTo, doc, rspElement.tagName, elementContent);
                return;
            }

            #region normal case: append an xml node for each associated itemvariable identifier in ramsellIdentifierMap

            List <string> ivIdentList = GetItemVariableIdentifiersForRamsellTagName(rspElement.tagName);
            foreach (string ivIdent in ivIdentList)
            {
                def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultIdentifier(formResultId, ivIdent);
                if ((rv != null) && !String.IsNullOrWhiteSpace(rv.rspValue))
                {
                    elementContent = GetFormattedResponse(rv, rspElement.xmlType, formsRepo);
                }
                else
                {
                    GetDefaultValue(rspElement.xmlType);  // to pass validation
                }

                //if there are multiple itemVariables, assume this is one out of a set of checkboxes
                //in which case zeroes represent unchecked checkboxes which should be ignored
                if ((elementContent == "0") && (ivIdentList.Count > 1))
                {
                    continue;
                }

                // if no output and the tag is optional, don't write it out
                //   *** For some reason Ramsell system doesn't seem process empty tags or recognize as valid
                //   *** Even though they pass XML / XSD validation
                if (String.IsNullOrWhiteSpace(elementContent) && rspElement.minOccurs.Equals(0.0m))
                {
                    continue;
                }

                AppendContentNodeToXML(appendTo, doc, rspElement.tagName, elementContent);
            }

            #endregion
        }
Example #10
0
        public static void LogStatusChange(IFormsRepository formsRepo, int formResultId, def_StatusDetail from, def_StatusDetail to, string note)
        {
            def_StatusLog statusChangeLog = new def_StatusLog();

            statusChangeLog.formResultId = formResultId;
            if (from != null)
            {
                statusChangeLog.statusDetailIdFrom = from.statusDetailId;
            }
            if (to != null)
            {
                statusChangeLog.statusDetailIdTo = to.statusDetailId;
            }
            statusChangeLog.statusLogDate = DateTime.Now;
            statusChangeLog.UserID        = SessionHelper.LoginStatus.UserID;
            statusChangeLog.statusNote    = note;
            try
            {
                formsRepo.AddStatusLog(statusChangeLog);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error adding status log: " + ex.Message);
            }
        }
        public ActionResult Template(int?sectionIdOverride = null, List <string> validationMessages = null)
        {
            mLogger.Debug("* * *  ResultsController:Template method  * * *");

            if (!SessionHelper.IsUserLoggedIn)
            {
                return(RedirectToAction("Index", "Account", null));
            }

            if (SessionHelper.SessionForm == null)
            {
                SessionHelper.SessionForm = new SessionForm();
            }

            if (Session["form"] != null && !string.IsNullOrWhiteSpace(Session["form"].ToString()))
            {
                int formId = SessionHelper.SessionForm.formId;
                formId = int.Parse(Session["form"].ToString());
                def_Forms frm = formsRepo.GetFormById(formId);
                SessionHelper.SessionForm.formId         = formId;
                SessionHelper.SessionForm.formIdentifier = frm.identifier;
                var oldFrmResult = formsRepo.GetFormResultById(SessionHelper.SessionForm.formResultId);
                var newFrmResult = formsRepo.GetFormResultsByFormSubject(formId, oldFrmResult.subject).OrderByDescending(f => f.dateUpdated);
                if (newFrmResult.Any())
                {
                    // use most recent form result
                    SessionHelper.SessionForm.formResultId = newFrmResult.FirstOrDefault().formResultId;
                }

                Session["form"] = null;
                int part = int.Parse(Session["part"].ToString());
                SessionHelper.SessionForm.partId = part;
            }

            SessionForm sessionForm = SessionHelper.SessionForm;

            // set language ID in session based on meta-data (default to English) + other session vars
            CultureInfo   ci      = Thread.CurrentThread.CurrentUICulture;
            string        isoName = (ci == null) ? "en" : ci.TwoLetterISOLanguageName.ToLower();
            def_Languages lang    = formsRepo.GetLanguageByTwoLetterISOName(isoName);

            if (lang == null)
            {
                throw new Exception("could not find def_Language entry for iso code \"" + isoName + "\"");
            }
            else
            {
                sessionForm.langId = lang.langId;
            }



            // This is the master or top level sectionId, there can be mulitple subSections below this section.
            // The subSections will be in the SectionItems
            string sectionId = (sectionIdOverride == null) ? Request["sectionId"] as string : sectionIdOverride.ToString();

            mLogger.Debug("* * *  Results Template sectionId: {0}", sectionId);
            Session["section"] = sectionId;
            def_Sections sctn = formsRepo.GetSectionById(Convert.ToInt32(sectionId));

            sessionForm.sectionId = sctn.sectionId;

            // Create a new Assessments Model Template (AMT) that is used by the .cshtml template (Razor code)
            TemplateItems amt;

            if (sctn.href != null && (sctn.href.EndsWith("spprtNeedsScale.cshtml") || sctn.href.EndsWith("excptnlMedSpprtNeed.cshtml")))
            {
                amt = new QuestionListForm();
            }
            else
            {
                amt = new GeneralForm();
            }


            amt.thisSection   = sctn;
            amt.thisSectionId = sctn.sectionId;
            amt.formsRepo     = formsRepo;
            amt.formResultId  = sessionForm.formResultId;
            amt.currentUser   = SessionHelper.LoginInfo.LoginID;

            //amt.items = new List<def_Items>();
            amt.subSections = new List <def_Sections>();
            amt.fldLabels   = new Dictionary <string, string>();
            amt.itmPrompts  = new Dictionary <string, string>();
            amt.rspValues   = new Dictionary <string, string>();
            mLogger.Debug("* * *  ResultsController:Template sessionForm.formResultId: {0}", sessionForm.formResultId);
            def_FormResults fr = formsRepo.GetFormResultById(sessionForm.formResultId);

            mLogger.Debug("* * *  ResultsController:Template fr.formResultId: {0}", fr.formResultId);

            if (fr != null)
            {
                if (fr.formStatus == (byte)FormResults_formStatus.IN_PROGRESS)
                {
                    amt.inProgress = true;
                }
                if (fr.formStatus == (byte)FormResults_formStatus.NEW)
                {
                    amt.newAssmnt = true;
                }
            }



            //Start: added for enhancement Bug 13663 to be refactored

            amt.updatedDate = fr.dateUpdated;

            amt.formStatus = fr.formStatus;

            int statusMasterId = 0;

            def_StatusMaster statusMaster = formsRepo.GetStatusMasterByFormId(fr.formId);

            if (statusMaster != null)
            {
                statusMasterId = statusMaster.statusMasterId;

                def_StatusDetail statusdetails = formsRepo.GetStatusDetailBySortOrder(statusMasterId, fr.formStatus);

                amt.formSatusText = statusdetails.def_StatusText
                                    .Where(sd => sd.EnterpriseID == 8 && sd.langId == 1)
                                    .Select(z => z.displayText)
                                    .FirstOrDefault();
            }
            else
            {
                //This is used as currently we are showing In Progress for all items which do not have status
                amt.formSatusText = "In Progress";
            }

            amt.CanUserChangeStatus = true;

            if (UAS_Business_Functions.hasPermission(PermissionConstants.ASSIGNED, PermissionConstants.ASSMNTS))
            {
                amt.CanUserChangeStatus = false;
            }
            else if (amt.formSatusText.ToLower() == "needs review" || amt.formSatusText.ToLower().Contains("approved"))
            {
                if (!UAS_Business_Functions.hasPermission(PermissionConstants.APPROVE, PermissionConstants.ASSMNTS))
                {
                    amt.CanUserChangeStatus = false;
                }
            }
            else if (amt.formId == 18)
            {
                amt.CanUserChangeStatus = false;
            }



            var    formType    = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "C1_FormType");
            string formVariant = string.Empty;

            if (formType != null && formType.rspValue != null && formType.rspValue != String.Empty)
            {
                formVariant          = formType.rspValue;
                amt.FormVariantTitle = formVariant;
            }
            else
            {
                formsEntities context = new Assmnts.formsEntities();

                amt.FormVariantTitle = context.def_FormVariants
                                       .Where(fv => fv.formID == fr.formId)
                                       .Select(fv => fv.title)
                                       .FirstOrDefault();
            }

            //get the subject id from form result id
            if (fr.subject != null)
            {
                int subject = (int)fr.subject;

                var elgEndDate = formsRepo.GetResponseVariablesBySubjectForm(subject, 18, "C1_ProgramEligibleEndDate");

                string endDate = elgEndDate != null ? elgEndDate.rspValue : string.Empty;

                amt.EligibilityEnddate = endDate;

                amt.formResultUser = authClient.GetUserDisplay(subject);

                amt.clientId = authClient.GetExistingAdapIdentifier(amt.formResultUser.UserID, 8);
            }



            //End: added for enhancement Bug 13663 to be refactored


            amt.formId = sessionForm.formId;

            formsRepo.SortSectionItems(sctn);                   // This is both loading and sorting the SectionItems.

            // Get the Items in the SubSections *** NOTE: this only goes ONE level deep ***  Should be made recursive for unlimited levels !!!
            // amt.sections = new List<def_Sections>();
            foreach (def_SectionItems sctnItm in sctn.def_SectionItems.OrderBy(si => si.order))
            {
                if (sctnItm.subSectionId.GetValueOrDefault(0) == 0 || sctnItm.display == false)
                {
                    continue;
                }
                // def_Sections subSctns = sctnItm.def_SubSections.def_Sections;
                def_Sections subSctns = formsRepo.GetSubSectionById(sctnItm.subSectionId);

                //do not add notes section to the section list, (if there is a notes item, it will later be set as amt.notesItem)
                if (subSctns.multipleItemsPerPage == false)
                {
                    continue;
                }

                formsRepo.SortSectionItems(subSctns);                       // Load and sort the SectionItems
                amt.subSections.Add(subSctns);
                // GetItemLabelsResponses(fr.formResultId, amt, formsRepo.GetSectionItems(sctnItm.def_SubSections.def_Sections));
            }

            // RRB 5/28/15 *** This is only necessary for the Profile screens
            //             *** Getting and sorting the SectionItems above is only necessary for Question forms
            //             ***   In fact, it may duplicate what is being done in the templates
            formsRepo.GetItemListIncludingSubSections(sctn, amt);
            //GetItemListIncludingSubSections(sctn, amt);

            // Get the Notes items
            formsRepo.GetItemListForNotes(sctn, amt);

            formsRepo.GetItemLabelsResponses(fr.formResultId, amt, amt.items);

            //determine whether or not this user will be shown itemvariable identifiers as tooltips
            //TODO this is a DEV mode only thing
            amt.showItemVariableIdentifiersAsTooltips = Convert.ToBoolean(ConfigurationManager.AppSettings["showItemVariableIdentifiersAsTooltips"]);            // true;//new UAS.Business.UAS_Business_Functions().hasPermission(7,"assmnts");

            //save response values in session variable to later determine which ones were modified
            ////List<string> keysToClear = new List<string>();
            ////foreach (string key in Session.Keys)
            ////    if (key.StartsWith("frmOriginal___"))
            ////        keysToClear.Add(key);
            ////foreach (string key in keysToClear)
            ////    Session.Remove(key);
            //DateTime oneHourFromNow = DateTime.Now.AddHours(1);
            //foreach (string key in amt.rspValues.Keys)
            //{
            //Response.Cookies["frmOriginal___" + key].Value = amt.rspValues[key];
            //Response.Cookies["frmOriginal___" + key].Expires = oneHourFromNow;
            //}

            mLogger.Debug("* * *  AFTER GetItemLabelsResponses amt.items.Count: {0}", amt.items.Count);

            mLogger.Debug("* * *  amt.rspValues.Count (Total): {0}", amt.rspValues.Count);

            //populate required and readonly dictionaries
            amt.fldRequired = new Dictionary <string, bool>();
            amt.fldReadOnly = new Dictionary <string, bool>();
            List <def_SectionItems> siList = formsRepo.GetSectionItemsBySectionIdEnt(sctn.sectionId, SessionHelper.LoginStatus.EnterpriseID);

            if (amt.items != null)
            {
                foreach (def_Items itm in amt.items)
                {
                    if (amt.fldRequired.ContainsKey(itm.identifier))
                    {
                        throw new Exception("Found duplicate item identifier \"" + itm.identifier + "\"");
                    }
                    def_SectionItems si = siList.FirstOrDefault(s => (!s.subSectionId.HasValue && s.itemId == itm.itemId));

                    amt.fldRequired.Add(itm.identifier, (si == null) ? false : si.requiredForm);
                    amt.fldReadOnly.Add(itm.identifier, (si == null) ? false : si.readOnly);
                }
            }

            amt.isProfile = false;

            string[] uriSegments      = sctn.href.Split('/');
            string   templateFileName = uriSegments[uriSegments.Count() - 1];

            switch (templateFileName)
            {
            case "idprof1.cshtml":
            case "idprof2.cshtml":
            case "idprof2_Child.cshtml":
                if (mLogger.IsDebugEnabled)
                {
                    mLogger.Debug("showing section item identifiers:");
                    foreach (def_SectionItems si in siList)
                    {
                        mLogger.Debug("\t{0}", si.def_Items.identifier);
                    }
                }
                amt.notesItem            = siList.Single(si => si.def_Items.identifier.EndsWith("PageNotes_item")).def_Items;
                sessionForm.templateType = TemplateType.StdSectionItems;
                amt.isProfile            = true;
                break;

            default:                                // "SIS/section1a":     Default to the item list
                sessionForm.templateType = TemplateType.MultipleCommonItems;
                break;
            }

            // Setup the Previous / Next screens
            amt.prevScreenTitle = amt.prevScreenHref = String.Empty;
            amt.nextScreenTitle = amt.nextScreenHref = String.Empty;

            def_Parts prt = formsRepo.GetPartById(Convert.ToInt32(Session["part"]));



            List <def_Sections> partSections = formsRepo.GetSectionsInPart(prt);

            mLogger.Debug("* * *  ResultsController:Template method  * * * partSections.Count: {0}", partSections.Count);

            //get a list of parts in the current form

            def_Forms        form          = formsRepo.GetFormById(amt.formId);
            List <def_Parts> partsInForm   = formsRepo.GetFormParts(form);
            List <int>       partIdsInForm = partsInForm.Select(p => p.partId).ToList();
            // List<def_Parts> partsInForm = formsRepo.getFormParts(fr.def_Forms);



            //these variables will be assigned int he loop below
            int currentSectionIndex = 0;
            int prevSectionIndex    = 0;
            int nextSectionIndex    = 0;

            //start by assuming the previous and next section will be in the same part
            int currentPartId = (prt == null) ? sessionForm.partId : prt.partId;

            amt.thisPartId = currentPartId;

            amt.navPartId = currentPartId.ToString();
            int prevPartId = currentPartId;
            int nextPartId = currentPartId;

            //in a special cases one of these will be set to true
            bool veryFirst = false;
            bool veryLast  = false;

            bool foundSectionId = false;

            //iterate through possible section ids
            for (int idx = 0; idx < partSections.Count; idx++)
            {
                if (partSections[idx].sectionId == sessionForm.sectionId)
                {
                    //found the current section id, start with some assumptions about previous and next section ids
                    foundSectionId      = true;
                    currentSectionIndex = idx;
                    prevSectionIndex    = idx - 1;
                    nextSectionIndex    = idx + 1;

                    //we may have to link to the last section of the previous part
                    if (prevSectionIndex < 0)
                    {
                        //special case where we're on the first section of the first part
                        if (partIdsInForm.IndexOf(prt.partId) == 0)                        //currentPartId == 1)
                        {
                            //veryFirst = true;
                            int partIndexInForm = partsInForm.Count();
                            List <def_Sections> prevPartSections = formsRepo.GetSectionsInPart(partsInForm[partIndexInForm - 1]);
                            prevPartId       = partsInForm[partIndexInForm - 1].partId;
                            prevSectionIndex = prevPartSections.Count - 1;
                        }
                        else
                        {
                            int partIndexInForm = partIdsInForm.IndexOf(prt.partId);
                            // occasionally a part with no sections may need to be skipped, which can happen with PartSectionsEnt records.
                            int listIndex = 0;
                            for (int i = 1; i < partIndexInForm; i++)
                            {
                                if (formsRepo.GetSectionsInPart(partsInForm[partIndexInForm - i]).Count() > 0)
                                {
                                    listIndex = partIndexInForm - i;
                                    break;
                                }
                            }

                            List <def_Sections> prevPartSections = formsRepo.GetSectionsInPart(partsInForm[listIndex]);
                            prevPartId       = partsInForm[listIndex].partId;
                            prevSectionIndex = prevPartSections.Count - 1;
                        }
                    }

                    // Oliver - same here the PartSections are ordered - just use the first one in the List.
                    // you can press F12 in Visual Studio and it will take you to the method.
                    // Data/Concrete/FormsRepository line 200
                    // The defined Interfaces are in Data/Abstract/IFormsRepository.cs

                    //we may have to link to he first section of the next part
                    if (nextSectionIndex > (partSections.Count - 1))
                    {
                        int partIndexInForm = partIdsInForm.IndexOf(prt.partId);
                        if (partIndexInForm == (partsInForm.Count() - 1))                          //formsRepo.GetPartById(nextPartId) == null)
                        {
                            //veryLast = true;
                            nextPartId       = partsInForm[0].partId;
                            nextSectionIndex = 0;
                        }
                        else
                        {
                            // occasionally a part with no sections may need to be skipped, which can happen with PartSectionsEnt records.
                            int listIndex = 0;
                            for (int i = 1; i < partsInForm.Count() - 1 - partIndexInForm; i++)
                            {
                                if (formsRepo.GetSectionsInPart(partsInForm[partIndexInForm + i]).Count() > 0)
                                {
                                    listIndex = partIndexInForm + i;
                                    break;
                                }
                            }

                            nextPartId       = partsInForm[listIndex].partId;
                            nextSectionIndex = 0;
                        }
                    }

                    break;
                }
            }

            if (!foundSectionId)
            {
                string msg = "current section id (" + sessionForm.sectionId + ") could not be found.\r\nListing candidates: (identifier / sectionId)";
                foreach (def_Sections sct in partSections)
                {
                    msg += (sct == null) ? "null" : ("\r\n" + sct.identifier + " / " + sct.sectionId);
                }
                throw new Exception(msg);
            }

            //print some debugging info
            if (mLogger.IsDebugEnabled)
            {
                mLogger.Debug("* * *  ResultsController:Template method  * * * " +
                              (veryFirst ? "this is the very first part/section" : "prevPartId: " + prevPartId.ToString() +
                               ", prevSectionIndex: " + prevSectionIndex.ToString()));
                mLogger.Debug("* * *  ResultsController:Template method  * * * " +
                              (veryLast ? "this is the very last part/section" : "nextPartId: " + nextPartId.ToString() +
                               ", nextSectionIndex: " + nextSectionIndex.ToString()));
            }
            if (partSections.Count > 0)
            {
                int    idxPeriod      = prt.identifier.IndexOf('.');
                string partShortTitle = (idxPeriod < 0) ? prt.identifier : prt.identifier.Substring(0, idxPeriod);
                // amt.thisScreenCaption = partShortTitle + " - " + partSections[thisIdx].identifier;
                amt.thisScreenCaption = partShortTitle + " - " + partSections[currentSectionIndex].identifier;
                amt.thisScreenTitle   = partSections[currentSectionIndex].title;

                if (!veryFirst)
                {
                    List <def_Sections> prevPartSections = formsRepo.GetSectionsInPart(formsRepo.GetPartById(prevPartId));
                    amt.prevScreenTitle     = prevPartSections[prevSectionIndex].title;
                    amt.prevScreenPartId    = prevPartId.ToString();
                    amt.prevScreenSectionId = prevPartSections[prevSectionIndex].sectionId.ToString();
                    amt.prevScreenHref      = "Template?partId=" + nextPartId + "&sectionId=" + amt.prevScreenSectionId;
                    //if (prevPartId != currentPartId)
                    //    amt.previousScreenHref = "Parts?formResultId=" + formsRepo.GetPartById(prevPartId).partId.ToString() + amt.previousScreenHref;
                }

                if (!veryLast)
                {
                    def_Parts tempPart = formsRepo.GetPartById(nextPartId);
                    if (tempPart != null)
                    {
                        List <def_Sections> tempPartSections = formsRepo.GetSectionsInPart(tempPart);
                        amt.nextScreenTitle     = tempPartSections[nextSectionIndex].title;
                        amt.nextScreenPartId    = nextPartId.ToString();
                        amt.nextScreenSectionId = tempPartSections[nextSectionIndex].sectionId.ToString();
                        amt.nextScreenHref      = "Template?partId=" + nextPartId + "&sectionId=" + amt.nextScreenSectionId;
                    }
                }
            }

            //pass a NavMenu model as a field in this items Model
            sessionForm.formIdentifier = form.identifier;
            amt.navMenuModel           = getNavMenuModel(sessionForm, amt);


            //Start: added for enhancement Bug 13663 to be refactored
            amt.navMenuModel.formResultUser      = amt.formResultUser;
            amt.navMenuModel.clientId            = amt.clientId;
            amt.navMenuModel.formSatusText       = amt.formSatusText;
            amt.navMenuModel.EligibilityEnddate  = amt.EligibilityEnddate;
            amt.navMenuModel.FormVariantTitle    = amt.FormVariantTitle;
            amt.navMenuModel.updatedDate         = amt.updatedDate;
            amt.navMenuModel.CanUserChangeStatus = amt.CanUserChangeStatus;
            amt.navMenuModel.formResultId        = amt.formResultId;
            //End: added for enhancement Bug 13663 to be refactored



            amt.ventureMode = SessionHelper.IsVentureMode;

            //special case for reports sections
            if ((sctn.identifier.EndsWith("Report") /*&& (Request["ignoreValidation"] as string) == null*/) ||
                sctn.href.Equals("~/Views/Templates/SIS/reportErrors.cshtml")
                )
            {
                if (!ValidateFormResult(fr, amt))
                {
                    return(View("~/Views/Templates/SIS/reportErrors.cshtml", amt));
                }
            }

            //add messages to the mdoel if necessary
            amt.validationMessages = validationMessages;             //validationMessages from method params, normally null

            //add a message to the model if necessary
            string message = Request["message"] as string;

            if (message != null)
            {
                if (amt.validationMessages == null)
                {
                    amt.validationMessages = new List <string>();
                }
                amt.validationMessages.Add(message);
            }

            // *** RRB 10/27/15 - added to fix problems with Venture and to be more efficient.
            if (!SessionHelper.IsVentureMode)
            {
                if (templateFileName.Equals("reportOptions.cshtml"))
                {
                    amt.reportOptions = AJBoggs.Sis.Reports.SisReportOptions.BuildPdfReportOptions(fr.EnterpriseID);
                }
            }

            // * * * OT 3/24/16 - for SIS supplemental questions, pre-populate sis_s41f with some item prompts from section 1A
            //  Don't do anything if there is already a response for sis_s41f
            //  (Bug 13132, #4 in description)
            if (sctn.identifier == "SQ" && amt.rspValues.ContainsKey("sis_s41f") && String.IsNullOrWhiteSpace(amt.rspValues["sis_s41f"]))
            {
                amt.rspValues["sis_s41f"] = String.Empty;

                //iterate through all section 1A items
                int          itmCount         = 0;
                bool         isSisCAssessment = fr.def_Forms.identifier.Equals("SIS-C");
                def_Sections sct1A            = formsRepo.GetSectionByIdentifier(isSisCAssessment ? "SIS-C 1A" : "SIS-A 1A");
                formsRepo.SortSectionItems(sct1A);
                foreach (def_SectionItems si in sct1A.def_SectionItems)
                {
                    def_Sections subSct = formsRepo.GetSubSectionById(si.subSectionId);
                    formsRepo.SortSectionItems(subSct);
                    foreach (def_SectionItems subSi in subSct.def_SectionItems)
                    {
                        //for items that have an itemVariable with suffix "_ExMedSupport", check if that itemVariable have a response of "2"
                        def_Items itm = subSi.def_Items;
                        itmCount++;
                        def_ItemVariables exMedSupIv = itm.def_ItemVariables.Where(iv => iv.identifier.EndsWith("_ExMedSupport")).FirstOrDefault();
                        if (exMedSupIv != null)
                        {
                            def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, exMedSupIv.itemVariableId);
                            if (rv != null && !String.IsNullOrWhiteSpace(rv.rspValue) && rv.rspValue == "2")
                            {
                                //append the item prompt to the pre-populated response for sis_s41f
                                amt.rspValues["sis_s41f"] += itmCount + ". " + itm.prompt + "\n";
                            }
                        }
                    }
                }
            }

            // *** OT 11/23/15 - added as test for Bug 12910 - Comparison: what changed from last approved application?
            //if we're on the ADAP form...
            if (form.identifier.Contains("ADAP"))
            {
                //get the previous formresult
                int?sortOrder = formsRepo.GetStatusDetailByMasterIdentifier(1, "CANCELLED").sortOrder;
                int userId    = fr.subject.HasValue ? fr.subject.Value : -1;
                if (userId < 1)
                {
                    mLogger.Warn("subject < 1 for form result having formResultId = {0}.", fr.formResultId);
                }
                // * * * OT 1-19-16 added stipulation that "prevRes" is not the current formResult "fr"
                def_FormResults prevRes = null;
                if (sortOrder.HasValue && userId > 0)
                {
                    prevRes = formsRepo.GetEntities <def_FormResults>(
                        x => x.formId == fr.formId &&
                        x.formResultId != fr.formResultId &&
                        x.subject == userId &&
                        x.formStatus != sortOrder)
                              .OrderByDescending(x => x.dateUpdated)
                              .FirstOrDefault();
                }
                // * * * OT 1-19-16 in order to duplicate existing behavior and avoid crashes,
                // default to using the current formResult as the previous if no others are applicable
                if (prevRes == null)
                {
                    prevRes = fr;
                }

                List <string> remainingIdentifiers = amt.rspValues.Keys.ToList();

                IList <def_ItemResults> previousItemResults = formsRepo.GetItemResults(prevRes.formResultId);
                foreach (def_ItemResults ir in previousItemResults)
                {
                    foreach (def_ResponseVariables rv in ir.def_ResponseVariables)
                    {
                        if (rv.def_ItemVariables == null)
                        {
                            continue;
                        }

                        remainingIdentifiers.Remove(rv.def_ItemVariables.identifier);
                        string rspValue = HttpUtility.HtmlDecode(rv.rspValue);

                        amt.rspValues.Add("PREVIOUS_" + rv.def_ItemVariables.identifier, rspValue);
                    }
                }

                //populate amt with empty responses for fields Bmissing from previous formResult
                foreach (string ident in remainingIdentifiers)
                {
                    amt.rspValues.Add("PREVIOUS_" + ident, "");
                }
            }

            SessionHelper.ResponseValues = amt.rspValues;

            //Displays save message
            ViewBag.Notify        = "";
            ViewBag.NotifyMessage = "";
            if (Session["IsPageLoad"] != null)
            {
                if (!(bool)Session["IsPageLoad"])
                {
                    if (TempData["Savemsg"] != null && TempData["SavemsgHeader"] != null)
                    {
                        if (TempData["Savemsg"].ToString() != "" && TempData["SavemsgHeader"].ToString() != "")
                        {
                            ViewBag.Notify        = TempData["SavemsgHeader"].ToString();
                            ViewBag.NotifyMessage = TempData["Savemsg"].ToString();
                        }
                    }
                }
            }


            TempData["SavemsgHeader"] = "";
            TempData["Savemsg"]       = "";
            return(View(sctn.href, amt));
        }