コード例 #1
0
        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);
        }
コード例 #2
0
        public void DeleteStatusMaster(def_StatusMaster statusMaster)
        {
            db.def_StatusMaster.Remove(statusMaster);

            db.SaveChanges();
        }
コード例 #3
0
        public void SaveStatusMaster(def_StatusMaster statusMaster)
        {
            db.Entry(statusMaster).State = EntityState.Modified;

            db.SaveChanges();
        }
コード例 #4
0
        public void AddStatusMaster(def_StatusMaster statusMaster)
        {
            db.def_StatusMaster.Add(statusMaster);

            db.SaveChanges();
        }
コード例 #5
0
        public string GetHtmlForColumn(int columnIndex)
        {
            switch (columnIndex)
            {
            case 0:     //ramsellId / MemberId
                def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultIdentifier(vfru.formResultId, "C1_MemberIdentifier") ?? formsRepo.GetResponseVariablesByFormResultIdentifier(vfru.formResultId, "ADAP_D9_Ramsell");
                string ramsellId         = (rv == null) ? null : rv.rspValue;
                string ramsellIdDisplayText;
                if ((ramsellId == null) || String.IsNullOrWhiteSpace(ramsellId))
                {
                    if (vfru.EnterpriseID == 8)
                    {
                        ramsellIdDisplayText = @Resources.AdapPortal.NoId;
                    }
                    else
                    {
                        ramsellIdDisplayText = @Resources.AdapPortal.NoRamsellId;
                    }
                }
                else
                {
                    ramsellIdDisplayText = ramsellId;
                }
                if (UAS_Business_Functions.hasPermission(PermissionConstants.EDIT, PermissionConstants.ASSMNTS))
                {
                    return(isHistorical ? ramsellIdDisplayText : "<a href=\"/ADAP/ToTemplate?formResultId=" + Convert.ToString(vfru.formResultId) + "&Update=Y\">" + ramsellIdDisplayText + "</a>");
                }
                else
                {
                    return(ramsellIdDisplayText);
                }

            case 1:     //FirstName
                return(vfru.FirstName);

            case 2:     //Last name
                return(vfru.LastName);

            case 3:     //DOB
                return(vfru.DOB.HasValue ? vfru.DOB.Value.ToString("MM/dd/yyyy") : String.Empty);

            case 4:     //Status
                def_StatusMaster statusMaster = formsRepo.GetStatusMasterByFormId(vfru.formId);
                int statusMasterId            = statusMaster == null ? 1 : statusMaster.statusMasterId;

                string statusDisplayText = formsRepo.GetStatusTextByDetailSortOrder(statusMasterId, vfru.formStatus).displayText;
                return(isHistorical ? statusDisplayText : "<a href=\"/ADAP/UpdateStatus?formResultId=" + Convert.ToString(vfru.formResultId) + "\">" + statusDisplayText + "</a>");

            case 5:     //Status changed
                return(statusChangeDate == null ? String.Empty : statusChangeDate.ToString());

            case 6:     //Next Recert
                DateTime?nextRecertDate = GetRecert(formsRepo, vfru, allVfrus);
                return(nextRecertDate.HasValue ? nextRecertDate.Value.ToString("MMMM yyyy") : "None Pending");

            case 7:     //type
                var form = formsRepo.GetFormByIdentifier(formIdentifier).title;
                return("<div class=\"form-type-text\" data-formIdentifier=\"" + formIdentifier + "\">" + form + "</div>");

            case 8:     //group
                if (vfru.EnterpriseID == 8)
                {
                    string groupDesc = string.Empty;
                    var    context   = DataContext.getUasDbContext();
                    var    group     = (from g in context.uas_Group
                                        where g.GroupID == vfru.GroupID
                                        select g).FirstOrDefault();
                    groupDesc = group.GroupDescription;
                    return(isHistorical ? vfru.GroupName + " - " + groupDesc : "<a href=\"/ADAP/UpdateTeam?formId=" + Convert.ToString(vfru.formResultId) + "\">" + vfru.GroupName + " - " + groupDesc + "</a>");
                }
                else
                {
                    return(isHistorical ? vfru.GroupName : "<a href=\"/ADAP/UpdateTeam?formId=" + Convert.ToString(vfru.formResultId) + "\">" + vfru.GroupName + "</a>");
                }

            case 9:     //contact info
                return
                    ("<div class=\"row\">" +
                     "<div class=\"col-md-12 text-center\">" +
                     "<a href=\"#\" data-toggle=\"modal\" data-target=\"#contactsModal\" data-formresultid=\"" + Convert.ToString(vfru.formResultId) + "\">" +
                     "Contact" +
                     "</a>" +
                     "<span class=\"text-divider\">|</span>" +
                     "<a href=\"#\" data-toggle=\"modal\" data-target=\"#cmmtModal\" data-userid=\"" + vfru.subject.ToString() + "\" data-formresultid=\"" + Convert.ToString(vfru.formResultId) + "\">" +
                     "Comments" +
                     "</a>" +
                     "<span class=\"text-divider\">|</span>" +
                     "<a href=\"/ADAP/StatusHistory?formResultId=" + Convert.ToString(vfru.formResultId) + "\">" +
                     "History" +
                     "</a>" +
                     "</div>" +
                     "</div>");

            case 10:     //print button
                if (isHistorical)
                {
                    if (historicalSnapshot != null)
                    {
                        return("<a class=\"glyphicon glyphicon-print text-primary\" href=\"/Search/DownloadFile?fileId=" + historicalSnapshot.FileId + "&fileDownloadName=snapshot.pdf\"></a>");
                    }
                    else
                    {
                        return("N/A");
                    }
                }
                else
                {
                    return("<a class=\"glyphicon glyphicon-print text-primary\" href=\"../COADAP/BuildPDFReport?formResultId=" + Convert.ToString(vfru.formResultId) + "\"></a>");
                }

            case 11:     //subject (user id number for applicant)
                return(Convert.ToString(vfru.subject));

            case 12:     //upload and download attachments
                if (isHistorical)
                {
                    return(String.Empty);
                }
                else
                {
                    int frId = vfru.formResultId;
                    return("<div>"
                           + "<div id=\"attachment1" + frId + "\">"
                           + "<form class=\"uploadForm\" action=\"/Search/UploadFile\" method=\"post\" enctype=\"multipart/form-data\">"
                           + "<input type=\"hidden\" name=\"formResultId\" value=\"" + frId + "\" />"
                           + "<input type=\"file\" id=\"file" + frId + "\" name=\"file" + frId + "\">"
                           + "<a href=\"#\" onclick=\"$('#Upload" + frId + "').click()\">Upload</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" class=\"viewFiles\" id=\"view" + frId + "\" onclick=\"downloadAttach(" + frId + ")\" hidden=\"hidden\">View Files</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<input type=\"submit\" id=\"Upload" + frId + "\" value=\"Upload\" hidden=\"hidden\" />"
                           + "</form>"
                           + "</div>"
                           + "<div id=\"attachment2" + frId + "\" hidden=\"hidden\">"
                           + "<span id=\"dwnldDDL" + frId + "\" class=\"AttachDDL" + frId + "\" style=\"min-width:10px\"></span> "
                           + "<a href=\"#\" onclick=\"downloadFile(" + frId + ")\">Download</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" onclick=\"deleteAttach(" + frId + ")\">Delete Files</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" onclick=\"cancelAttach(" + frId + ")\">Cancel</a>"
                           + "</div>"
                           + "<div id=\"attachment3" + frId + "\" hidden=\"hidden\">"
                           + "<span id=\"dltDDL" + frId + "\" class=\"AttachDDL" + frId + "\"></span> "
                           + "<a href=\"#\" onclick=\"deleteFile(" + frId + ")\">Delete</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" onclick=\"downloadAttach(" + frId + ")\">Cancel</a>"
                           + "</div>"
                           + "</div>");
                }

            default:
                throw new Exception("invalid column index: " + columnIndex);
            }
        }
コード例 #6
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
        }
コード例 #7
0
        public string GetHtmlForColumn(int columnIndex)
        {
            Uri userAdminUri = new Uri(System.Configuration.ConfigurationManager.AppSettings["UASAdminURL"]);

            switch (columnIndex)
            {
            case 0:     //ramsellId / MemberId
                var    ramsellId = vfru.adap_id;
                string ramsellIdDisplayText;
                if ((ramsellId == null) || String.IsNullOrWhiteSpace(ramsellId))
                {
                    ramsellIdDisplayText = @Resources.AdapPortal.NoId;
                }
                else
                {
                    ramsellIdDisplayText = ramsellId;
                }
                if (UAS_Business_Functions.hasPermission(PermissionConstants.EDIT, PermissionConstants.ASSMNTS))
                {
                    return(isHistorical ? ramsellIdDisplayText : "<a href=\"/ADAP/ToTemplate?formResultId=" + Convert.ToString(vfru.formResultId) + "&Update=Y\">" + ramsellIdDisplayText + "</a>");
                }
                else
                {
                    return(ramsellIdDisplayText);
                }

            case 1:     //FirstName

                string url          = new Uri(userAdminUri, String.Format("Site/Limited/simple_User?UserID={0}", vfru.subject)).ToString();
                string uasEditFirst = "<a target='_blank' href='" + url + "' >" + vfru.FirstName + "  </a>";
                return(uasEditFirst);

            case 2:     //Last name

                string urlEdit     = new Uri(userAdminUri, String.Format("Site/Limited/simple_User?UserID={0}", vfru.subject)).ToString();
                string uasEditLast = "<a target='_blank' href='" + urlEdit + "' >" + vfru.LastName + "  </a>";
                return(uasEditLast);


            case 3:     //Status
                def_StatusMaster statusMaster = formsRepo.GetStatusMasterByFormId(vfru.formId);
                int    statusMasterId         = statusMaster == null ? 1 : statusMaster.statusMasterId;
                var    status            = formsRepo.GetStatusTextByDetailSortOrder(statusMasterId, vfru.formStatus);
                var    permChangeStatus  = UAS_Business_Functions.hasPermission(PermissionConstants.CNGE_STATUS, PermissionConstants.ASSMNTS);
                string statusDisplayText = status != null ? status.displayText : "In Progress";
                return((isHistorical || !permChangeStatus) ? statusDisplayText : "<a href=\"Javascript:StatusRedirect('/AdapCa/UpdateStatus'," + Convert.ToString(vfru.formResultId) + ")\">" + statusDisplayText + "</a>");

            case 4:     //Status changed
                return(statusChangeDate == null ? String.Empty : statusChangeDate.ToString());

            case 5:     // Elibility End Date
                DateTime?eligibilityEndDate = vfru.EligibilityEndDate;
                string   endDate            = "None Pending";
                if (eligibilityEndDate.HasValue)
                {
                    endDate = eligibilityEndDate.Value.ToShortDateString();
                }

                IEnumerable <def_FormResults> frElgList = formsRepo.GetFormResultsByFormSubject(18, vfru.subject);

                if (!frElgList.Any())
                {
                    // create an Eligibility Dashboard
                    AdapCaController adapCa = new AdapCaController(formsRepo);
                    adapCa.CreateElgibility(vfru.formResultId);
                    frElgList = formsRepo.GetFormResultsByFormSubject(18, vfru.subject);
                }

                var frmElgResultId = frElgList.FirstOrDefault().formResultId;
                var endDateLink    = "<a href=\"/ADAP/ToTemplate?formResultId=" + Convert.ToString(frmElgResultId) + "&Update=Y\">"
                                     + endDate + "</a>";

                return(endDateLink);

            case 6:     //Next Recert
                def_ResponseVariables rvSixMonth = formsRepo.GetResponseVariablesBySubjectForm(vfru.subject.Value, 18, "C1_Next6MonthRecertDate");
                DateTime nextRecertDate;
                string   recertDate = "None Pending";
                if (rvSixMonth != null && DateTime.TryParse(rvSixMonth.rspValue, out nextRecertDate))
                {
                    recertDate = nextRecertDate.ToString("MMMM yyyy");
                }
                return(recertDate);

            case 7:
                def_ResponseVariables rvAnuual = formsRepo.GetResponseVariablesBySubjectForm(vfru.subject.Value, 18, "C1_NextAnnualRecertDate");
                DateTime annualDate;
                string   annualDateStr = "None Pending";
                if (rvAnuual != null && DateTime.TryParse(rvAnuual.rspValue, out annualDate))
                {
                    annualDateStr = annualDate.ToString("MMMM yyyy");
                }
                return(annualDateStr);

            case 8:     //type
                var form        = formsRepo.GetFormByIdentifier(formIdentifier).title;
                var formVariant = vfru.formVariant;
                if (!string.IsNullOrWhiteSpace(formVariant))
                {
                    form = formVariant;
                }
                return("<div class=\"form-type-text\" data-formIdentifier=\"" + formIdentifier + "\">" + form + "</div>");

            case 9:     //group
                var permMove = UAS_Business_Functions.hasPermission(PermissionConstants.MOVE, PermissionConstants.ASSMNTS);
                if (vfru.EnterpriseID == 8)
                {
                    string groupDesc = string.Empty;
                    var    context   = DataContext.getUasDbContext();
                    var    group     = (from g in context.uas_Group
                                        where g.GroupID == vfru.GroupID
                                        select g).FirstOrDefault();
                    groupDesc = group.GroupDescription;
                    return((isHistorical || !permMove) ? vfru.GroupName + " - " + groupDesc : "<a href=\"/ADAP/UpdateTeam?formId=" + Convert.ToString(vfru.formResultId) + "\">" + vfru.GroupName + " - " + groupDesc + "</a>");
                }
                else
                {
                    return(isHistorical ? vfru.GroupName : "<a href=\"/ADAP/UpdateTeam?formId=" + Convert.ToString(vfru.formResultId) + "\">" + vfru.GroupName + "</a>");
                }

            case 10:     //contact info
                return
                    ("<div class=\"row\">" +
                     "<div class=\"col-md-12 text-center\">" +
                     "<a href=\"#\" data-toggle=\"modal\" data-target=\"#contactsModal\" data-formresultid=\"" + Convert.ToString(vfru.formResultId) + "\">" +
                     "Contact" +
                     "</a>" +
                     "<span class=\"text-divider\">|</span>" +
                     "<a href=\"#\" data-toggle=\"modal\" data-target=\"#cmmtModal\" data-userid=\"" + vfru.subject.ToString() + "\" data-formresultid=\"" + Convert.ToString(vfru.formResultId) + "\">" +
                     "Comments" +
                     "</a>" +
                     "<span class=\"text-divider\">|</span>" +
                     "<a href=\"Javascript:StatusRedirect('/AdapCa/StatusHistory'," + Convert.ToString(vfru.formResultId) + ")\">" +
                     "History" +
                     "</a>" +
                     "<br/><br/>" +
                     "<a href=\"Javascript:clientHandoutRedirect('/Results/ClientHandout'," + Convert.ToString(vfru.formResultId) + ")\">" +
                     "Client Handout" +
                     "</a>" +
                     "</div>" +
                     "</div>");

            case 11:     //DOB
                return(vfru.DOB.HasValue ? vfru.DOB.Value.ToString("MM/dd/yyyy") : String.Empty);

            case 12:     //print button
                if (isHistorical)
                {
                    if (historicalSnapshot != null)
                    {
                        return("<a class=\"glyphicon glyphicon-print text-primary\" href=\"/Search/DownloadFile?fileId=" + historicalSnapshot.FileId + "&fileDownloadName=snapshot.pdf\"></a>");
                    }
                    else
                    {
                        return("N/A");
                    }
                }
                else
                {
                    return("<a class=\"glyphicon glyphicon-print text-primary\" href=\"../COADAP/BuildPDFReport?formResultId=" + Convert.ToString(vfru.formResultId) + "\"></a>");
                }

            case 13:     //subject (user id number for applicant)
                return(Convert.ToString(vfru.subject));

            case 14:     //upload and download attachments
                if (isHistorical)
                {
                    return(String.Empty);
                }
                else
                {
                    int frId = vfru.formResultId;
                    return("<div>"
                           + "<div id=\"attachment1" + frId + "\">"
                           + "<form class=\"uploadForm\" action=\"/Search/UploadFile\" method=\"post\" enctype=\"multipart/form-data\">"
                           + "<input type=\"hidden\" name=\"formResultId\" value=\"" + frId + "\" />"
                           + "<input type=\"file\" id=\"file" + frId + "\" name=\"file" + frId + "\">"
                           + "<a href=\"#\" onclick=\"$('#Upload" + frId + "').click()\">Upload</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" class=\"viewFiles\" id=\"view" + frId + "\" onclick=\"downloadAttach(" + frId + ")\" hidden=\"hidden\">View Files</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<input type=\"submit\" id=\"Upload" + frId + "\" value=\"Upload\" hidden=\"hidden\" />"
                           + "</form>"
                           + "</div>"
                           + "<div id=\"attachment2" + frId + "\" hidden=\"hidden\">"
                           + "<span id=\"dwnldDDL" + frId + "\" class=\"AttachDDL" + frId + "\" style=\"min-width:10px\"></span> "
                           + "<a href=\"#\" onclick=\"downloadFile(" + frId + ")\">Download</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" onclick=\"deleteAttach(" + frId + ")\">Delete Files</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" onclick=\"cancelAttach(" + frId + ")\">Cancel</a>"
                           + "</div>"
                           + "<div id=\"attachment3" + frId + "\" hidden=\"hidden\">"
                           + "<span id=\"dltDDL" + frId + "\" class=\"AttachDDL" + frId + "\"></span> "
                           + "<a href=\"#\" onclick=\"deleteFile(" + frId + ")\">Delete</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" onclick=\"downloadAttach(" + frId + ")\">Cancel</a>"
                           + "</div>"
                           + "</div>");
                }

            default:
                throw new Exception("invalid column index: " + columnIndex);
            }
        }
コード例 #8
0
        /// <summary>
        /// Primary method for processing database queries posted to DataTables.  Intended to be universal for all ADAP Applicant and Dashboard Reports.
        /// </summary>
        /// <param name="query">The query initialized by the DataTable Web Service calling this method.</param>
        /// <param name="sFName">String of the applicant's first name</param>
        /// <param name="sLName">String of the applicant's last name</param>
        /// <param name="sTeam">String of the Team associated with the application.</param>
        /// <param name="sStat">String of the Status of the application.  Some reports use a specialized key word to add additional parameters to the query.</param>
        /// <param name="sDate">String of the Date of the application.  Some reports use specialized key words to add additional parameters to the query.</param>
        /// <returns>IQueryable<vFormResultUsers> with additional parameters added for the DataTable.</returns>
        public IQueryable <vFormResultUser> SetVfruQueryParams(IQueryable <vFormResultUser> query, String sFName, String sLName, String sTeam, String sStat, String sDate, String sDob, String ssn, string adapId,
                                                               string siteNum, string enrollmentSite, String formType, String elgEndFrom, String elgEndTo, int statusMasterId = 1)
        {
            query = query.Where(q => q.StatusFlag.Equals("A"));
            if (!String.IsNullOrEmpty(sFName))
            {
                query = query.Where(q => q.FirstName.Contains(sFName));
            }

            if (!String.IsNullOrEmpty(sLName))
            {
                query = query.Where(q => q.LastName.Contains(sLName));
            }

            if (!string.IsNullOrWhiteSpace(siteNum))
            {
                query = query.Where(q => q.GroupName.StartsWith(siteNum));
            }

            int formId = 15;

            if (!string.IsNullOrWhiteSpace(formType))
            {
                var parts      = formType.Split('|');
                var formIdPart = parts[0];
                if (int.TryParse(formIdPart, out formId))
                {
                    query = query.Where(q => q.formId == formId);
                }

                if (formId == 15)
                {
                    var formVariant = parts[1];
                    if (formVariant != "Initial Enrollment Application")
                    {
                        query = query.Where(q => q.formVariant == formVariant);
                    }
                    else
                    {
                        query = query.Where(q => q.formVariant == null || q.formVariant == formVariant);
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(elgEndFrom))
            {
                DateTime elgEndFromDate;
                if (DateTime.TryParse(elgEndFrom, out elgEndFromDate))
                {
                    query = query.Where(q => q.EligibilityEndDate >= elgEndFromDate);
                }
            }

            if (!string.IsNullOrWhiteSpace(elgEndTo))
            {
                DateTime elgEndToDate;
                if (DateTime.TryParse(elgEndTo, out elgEndToDate))
                {
                    query = query.Where(q => q.EligibilityEndDate <= elgEndToDate);
                }
            }

            if (!String.IsNullOrWhiteSpace(enrollmentSite))
            {
                var context  = DataContext.getUasDbContext();
                var groupIds = (from g in context.uas_Group
                                where g.GroupDescription.Contains(enrollmentSite) &&
                                g.GroupTypeID == 193
                                select g.GroupID).ToList();
                query = query.Where(q => groupIds.Contains(q.GroupID.Value));
            }

            if (!String.IsNullOrEmpty(sTeam) && !sTeam.Equals("All"))
            {
                // serach by unit
                // get child groups of unit
                var context = DataContext.getUasDbContext();
                int groupId;
                int.TryParse(sTeam, out groupId);
                List <int> groupIds = (from g in context.uas_Group
                                       where g.ParentGroupId == groupId ||
                                       g.GroupID == groupId
                                       select g.GroupID).ToList();

                query = query.Where(q => groupIds.Contains(q.GroupID.Value));
            }

            if (!String.IsNullOrEmpty(sStat) && !sStat.Equals("All"))
            {
                if (sStat.Equals("Pending") || sStat.Equals("All Pending"))
                {
                    // In Process = 0, Needs Review = 1, Needs Information = 2
                    int inProcess        = Convert.ToInt32(formsRepo.GetStatusDetailByMasterIdentifier(1, "IN_PROCESS").sortOrder);
                    int needsReview      = Convert.ToInt32(formsRepo.GetStatusDetailByMasterIdentifier(1, "NEEDS_REVIEW").sortOrder);
                    int needsInformation = Convert.ToInt32(formsRepo.GetStatusDetailByMasterIdentifier(1, "NEEDS_INFORMATION").sortOrder);
                    query = query.Where(q => q.formStatus == inProcess || q.formStatus == needsReview || q.formStatus == needsInformation);
                }
                else
                {
                    if (sStat.Contains(" Pending"))
                    {
                        sStat = sStat.Substring(0, sStat.IndexOf(" Pending"));
                    }

                    // In Process = 0, Needs Review = 1, Needs Information = 2, Denied = 3, Approved = 4, Cancelled = 5
                    if (!string.IsNullOrWhiteSpace(formType))
                    {
                        def_StatusMaster statusMaster = formsRepo.GetStatusMasterByFormId(formId);
                        statusMasterId = statusMaster == null ? 1 : statusMaster.statusMasterId;
                        var statusDisplay = formsRepo.GetStatusDetailByDisplayText(statusMasterId, sStat);
                        int index         = statusDisplay != null ? statusDisplay.sortOrder.Value : -1;
                        query = query.Where(q => q.formStatus == index);
                    }
                    else
                    {
                        // all form types
                        // form enrollment
                        int formIdStandard            = 15;
                        int formIdMoop                = 17;
                        int formIdSvf                 = 19;
                        def_StatusMaster statusMaster = formsRepo.GetStatusMasterByFormId(formIdStandard);
                        statusMasterId = statusMaster == null ? 1 : statusMaster.statusMasterId;
                        var statusDisplay = formsRepo.GetStatusDetailByDisplayText(statusMasterId, sStat);
                        int index         = statusDisplay != null ? statusDisplay.sortOrder.Value : -1;

                        // form moop
                        def_StatusMaster statusMasterMoop = formsRepo.GetStatusMasterByFormId(formIdMoop);
                        var statusMasterIdMoop            = statusMasterMoop == null ? 1 : statusMasterMoop.statusMasterId;
                        var statusDisplayMoop             = formsRepo.GetStatusDetailByDisplayText(statusMasterIdMoop, sStat);
                        int indexMoop = statusDisplayMoop != null ? statusDisplayMoop.sortOrder.Value : -1;

                        // form svf
                        def_StatusMaster statusMasterSvf = formsRepo.GetStatusMasterByFormId(formIdSvf);
                        var statusMasterIdSvf            = statusMasterSvf == null ? 1 : statusMasterSvf.statusMasterId;
                        var statusDisplaySvf             = formsRepo.GetStatusDetailByDisplayText(statusMasterIdSvf, sStat);
                        int indexSvf = statusDisplaySvf != null ? statusDisplaySvf.sortOrder.Value : -1;

                        query = query.Where(q => (q.formStatus == index && q.formId == formIdStandard) ||
                                            (q.formStatus == indexSvf && q.formId == formIdSvf) ||
                                            (q.formStatus == indexMoop && q.formId == formIdMoop));
                    }
                }
            }

            if (!String.IsNullOrWhiteSpace(sDob))
            {
                DateTime dob;
                if (DateTime.TryParse(sDob, out dob))
                {
                    query = query.Where(q => q.DOB == dob);
                }
            }

            if (!string.IsNullOrWhiteSpace(ssn))
            {
                formsEntities context       = new formsEntities();
                var           formResultIds = (from iv in context.def_ItemVariables
                                               join rv in context.def_ResponseVariables on iv.itemVariableId equals rv.itemVariableId
                                               join ir in context.def_ItemResults on rv.itemResultId equals ir.itemResultId
                                               where iv.identifier == "C1_MemberSocSecNumber" && rv.rspValue == ssn
                                               select ir.formResultId);
                query = from q in query
                        join fr in formResultIds.ToList() on q.formResultId equals fr
                        select q;
            }

            if (!string.IsNullOrWhiteSpace(adapId))
            {
                query = query.Where(x => x.adap_id == adapId);
            }

            if (!String.IsNullOrEmpty(sDate) && !sDate.Equals("All"))
            {
                //int formId = formsRepo.GetFormByIdentifier("ADAP").formId;
                // "Re-Certs Late" still needs to be added.
                // Current calculation does not account for Late re-certifications.
                if (sDate.Contains("Last Modified within"))
                {
                    try {
                        int      span    = Convert.ToInt32(sDate.Substring(21, 1));
                        DateTime compare = DateTime.Now.AddDays(span * -30);
                        query = query.Where(q => q.dateUpdated >= compare);
                    }
                    catch (FormatException ex) {
                        Debug.WriteLine("Adap Applications sDate span: " + ex.Message);
                    }
                }
                if (sDate.Contains("Re-Certs"))
                {
                    /// 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.

                    int approved = Convert.ToInt32(formsRepo.GetStatusDetailByMasterIdentifier(1, "APPROVED").sortOrder);
                    IQueryable <vFormResultUser> subQuery = formsRepo.GetFormResultsWithSubjects(SessionHelper.LoginStatus.EnterpriseID, formId)
                                                            .Where(sq => sq.formStatus == approved && sq.StatusFlag.Equals("A")).OrderByDescending(sq => sq.statusChangeDate);

                    // Duplicated variable to prevent InvalidOperationException: "A cycle was detected in a LINQ expression."
                    IQueryable <vFormResultUser> accepted = formsRepo.GetFormResultsWithSubjects(SessionHelper.LoginStatus.EnterpriseID, formId)
                                                            .Where(sq => sq.formStatus == approved && sq.StatusFlag.Equals("A")).OrderByDescending(sq => sq.statusChangeDate);

                    // DbFunctions formula:  AddDays(AddMonths(CreateDatetime()))
                    // CreateDateTime() to assemble the birthdate of the current year on the first of the month.
                    // AddMonths() to either advance the birthdate to 7 months in the future, or a single month in the future.
                    // AddDays() to subtract a single day, resulting in either the last day of the month 6 months after the birthdate, or the last day of the birth month.

                    // Logic used below should reflect the logic used in the getRecert method.
                    // nextRecert pseudocode: create new IQueryable<RecertObject>
                    // Test if the current time falls between the birth month and 6 months from the birth month ( DOB < Today < DOB + 6 Months )
                    //      if true: use DbFunctions formula to find the last day of the month 6 months after the birthdate
                    //      if false: Test if the current time is later than 6 months from teh birth month.  ( DOB + 6 Months < Today )
                    //          if true: use DbFunctions formula to find the last day of the birth month in the following year.
                    //          if false: use DbFunctions formula to find the last day of the birth month
                    IQueryable <RecertObject> nextRecert = formsRepo.GetFormResultsWithSubjects(SessionHelper.LoginStatus.EnterpriseID, formId)
                                                           .Select(nr => new RecertObject {
                        formResultId = nr.formResultId,
                        subject      = nr.subject,
                        recert       = (nr.DOB.Value.Month < DateTime.Now.Month && DateTime.Now.Month <= nr.DOB.Value.Month + 6)
                                                                        ? DbFunctions.AddDays(DbFunctions.AddMonths(DbFunctions.CreateDateTime(DateTime.Now.Year, nr.DOB.Value.Month, 1, 0, 0, 0), 7), -1)
                                                                        : (nr.DOB.Value.Month + 6 < DateTime.Now.Month)
                                                                        ? DbFunctions.AddDays(DbFunctions.AddMonths(DbFunctions.CreateDateTime(DateTime.Now.Year + 1, nr.DOB.Value.Month, 1, 0, 0, 0), 1), -1)
                                                                        : DbFunctions.AddDays(DbFunctions.AddMonths(DbFunctions.CreateDateTime(DateTime.Now.Year, nr.DOB.Value.Month, 1, 0, 0, 0), 1), -1)
                    });

                    // applyExcep pseudocode: edit nextRecert object to apply the 3 month exception.
                    // Ensure there is only one accepted application, then
                    // Test if the absolute value of the most recent statusChangeDate for the subject minus the nextRecert.recert is LESS THAN 3 ( statusChangeDate - recert < 3 )
                    //      if true: Find the last day of the month 6 months from the recert with recert.AddDays(+1) -> AddMonths(+6) -> AddDays(-1)
                    //      if false: Use the established recert date.
                    IQueryable <RecertObject> applyExcep = nextRecert.Where(nr => accepted.Where(sq => sq.subject == nr.subject).Count() > 0)
                                                           .Select(nr => new RecertObject {
                        formResultId = nr.formResultId,
                        subject      = nr.subject,
                        recert       = (accepted.Where(sq => sq.subject == nr.subject).Count() == 1 &&
                                        Math.Abs(accepted.Select(sq => sq.statusChangeDate).FirstOrDefault().Value.Month - nr.recert.Value.Month) < 3)
                                                                                        ? DbFunctions.AddDays(DbFunctions.AddMonths(DbFunctions.AddDays(nr.recert, 1), 6), -1)
                                                                                        : nr.recert
                    });

                    //// Data check for validation.
                    //List<RecertObject> recertCheck = new List<RecertObject>();
                    //foreach (var v in applyExcep)
                    //{
                    //    recertCheck.Add(v);
                    //}

                    DateTime deadline = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                    deadline = deadline.AddMonths(1).AddDays(-1);
                    if (sDate.Contains("Re-Certs Late"))
                    {
                        // Adjust the deadline to 6 months prior to the current deadline.
                        deadline = deadline.AddDays(1).AddMonths(-6).AddDays(-1);

                        // Take the most recently accepted application and check if the statusChangeDate falls before the deadline.
                        subQuery = subQuery.Where(sq => accepted.Where(ac => ac.subject == sq.subject).Select(ac => ac.statusChangeDate).FirstOrDefault() < deadline);
                    }
                    else if (sDate.Contains("Re-Certs Due within 7 Days"))
                    {
                        // Adjust deadline to the current date so recerts due will only show when the due date is within 7 days.
                        deadline = DateTime.Now;
                        DateTime range = deadline.AddDays(7);

                        subQuery = subQuery.Where(sq => deadline <= applyExcep.Where(nr => nr.subject == sq.subject).Select(nr => nr.recert).FirstOrDefault() &&
                                                  applyExcep.Where(nr => nr.subject == sq.subject).Select(nr => nr.recert).FirstOrDefault() <= range);

                        //// Data check for validation
                        //List<string[]> dataCheck = new List<string[]>();
                        //foreach (var v in subQuery)
                        //{
                        //    dataCheck.Add(new string[] { v.subject.ToString() });
                        //}
                    }
                    else if (sDate.Contains("Re-Certs Due within"))
                    {
                        try {
                            // This block begins by parsing the month multiplier from the selection string.
                            int      span  = Convert.ToInt32(sDate.Substring(20, 1));
                            DateTime range = deadline.AddDays(1).AddMonths(span).AddDays(-1);
                            subQuery = subQuery.Where(sq => deadline <= applyExcep.Where(nr => nr.subject == sq.subject).Select(nr => nr.recert).FirstOrDefault() &&
                                                      applyExcep.Where(nr => nr.subject == sq.subject).Select(nr => nr.recert).FirstOrDefault() <= range);
                        }
                        catch (FormatException ex) {
                            Debug.WriteLine("Adap Reports Controller sDate span: " + ex.Message);
                        }
                    }

                    query = query.Where(q => subQuery.Where(sq => sq.subject == q.subject).Select(sq => sq.subject).FirstOrDefault() == q.subject);
                    query = query.OrderByDescending(q => q.dateUpdated);
                }
                else if (sDate.Contains("&"))
                {
                    string[] dates = sDate.Split('&');
                    DateTime from;
                    bool     fromBool = true;
                    DateTime to;
                    bool     toBool = true;
                    if (!String.IsNullOrEmpty(dates[0]))
                    {
                        try {
                            from = Convert.ToDateTime(dates[0]);
                        }
                        catch (FormatException ex) {
                            Debug.WriteLine("Adap Reports Controller sDate from date conversation: " + ex.Message);
                            from = new DateTime(2000, 1, 1);
                        }
                    }
                    else
                    {
                        from     = new DateTime(2000, 1, 1);
                        fromBool = false;
                    }

                    if (!String.IsNullOrEmpty(dates[1]))
                    {
                        try {
                            to = Convert.ToDateTime(dates[1]);
                        }
                        catch (FormatException ex) {
                            Debug.WriteLine("Adap Reports Controller sDate to date conversation: " + ex.Message);
                            to = DateTime.Now.AddDays(1);
                        }
                    }
                    else
                    {
                        to     = DateTime.Now.AddDays(1);
                        toBool = false;
                    }

                    IQueryable <vFormResultUser> subQuery = formsRepo.GetFormResultsWithSubjects(SessionHelper.LoginStatus.EnterpriseID, formId);
                    int needsReview = Convert.ToInt32(formsRepo.GetStatusDetailByMasterIdentifier(1, "NEEDS_REVIEW").sortOrder);
                    subQuery = subQuery.Where(sq => /*sq.formStatus == needsReview &&*/ sq.StatusFlag.Equals("A"));
                    if (dates[2].Contains("Overview"))
                    {
                        subQuery = subQuery.Where(sq => (sq.formStatus == needsReview) &&
                                                  ((fromBool) ? sq.statusChangeDate >= from : true) && ((toBool) ? sq.statusChangeDate <= to : true)).OrderByDescending(sq => sq.statusChangeDate);
                    }
                    else if (dates[2].Contains("Summary"))
                    {
                        subQuery = subQuery.Where(sq => ((fromBool) ? sq.statusChangeDate >= from : true) && ((toBool) ? sq.statusChangeDate <= to : true))
                                   .OrderByDescending(sq => sq.statusChangeDate);
                    }
                    //List<string[]> dataCheck = new List<string[]>();
                    //foreach (var v in subQuery)
                    //{
                    //    dataCheck.Add(new string[] { v.subject.ToString(), v.formStatus.ToString(), v.GroupName, v.statusChangeDate.ToString() });
                    //}

                    if (dates[2].Contains("Overview"))
                    {
                        query = query.Where(q => q.subject == subQuery.Where(sq => sq.subject == q.subject).Select(sq => sq.subject).FirstOrDefault());
                    }
                    else if (dates[2].Contains("Summary"))
                    {
                        query = query.Where(q => q.formResultId == subQuery.Where(sq => sq.subject == q.subject)
                                            .OrderByDescending(sq => sq.statusChangeDate).Select(sq => sq.formResultId).FirstOrDefault());
                    }
                }
            }

            return(query);
        }
コード例 #9
0
        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));
        }