private void tryPrintSingleLineLabel(def_Sections sct, int indentLevel, double sectionLabelIndent, double itemLabelIndent, double responseIndent)
        {
            Dictionary <string, string> responses        = GetResponsesByItemVariableIdentifier(sct);
            List <string> positiveResponsesItemVariables = responses.Where(pair => pair.Value.Equals("Yes")).Select(pair => pair.Key).ToList();

            //if there is exactly one response for this section, print it on the same line as the section header
            if (positiveResponsesItemVariables.Count == 1)
            {
                string            ivIdent = positiveResponsesItemVariables.First();
                def_ItemVariables iv      = formsRepo.GetItemVariableByIdentifier(ivIdent);
                def_Items         itm     = formsRepo.GetItemById(iv.itemId);
                string            label   = itm.label;
                double            drawY   = output.drawY;
                printGenericSectionHeader(sct, sectionLabelIndent);
                output.drawY = drawY;
                output.appendWrappedText(label, responseIndent, 8 - responseIndent);
                output.drawY -= .1;
            }

            //otherewise, delegate to the standard section printing
            else
            {
                base.PrintGenericSection(output, sct, indentLevel, responses);
            }
        }
        /// <summary>
        /// Used to display responses to radiobuttons or dropdowns.
        ///
        /// Retrieve a numerical response for the given def_FormResult and deF_ItemVariable from the ResponseVariables table,
        /// Then lookup the display text associated with the numerical response, for the current UI language.
        /// </summary>
        /// <param name="formResultId"></param>
        /// <param name="itm"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        private string GetResponseThroughLookupTables(int formResultId, def_Items itm, def_ItemVariables iv)
        {
            string           rsp = GetResponse(formResultId, itm, iv);
            def_LookupMaster lm  = formsRepo.GetLookupMastersByLookupCode(iv.identifier);

            if (lm == null)
            {
                return(rsp);
            }

            def_LookupDetail ld = formsRepo.GetLookupDetailByEnterpriseMasterAndDataValue(SessionHelper.LoginStatus.EnterpriseID, lm.lookupMasterId, rsp);

            if (ld != null)
            {
                CultureInfo    ci     = Thread.CurrentThread.CurrentUICulture;
                string         region = (ci == null) ? "en" : ci.TwoLetterISOLanguageName.ToLower();
                int            langId = formsRepo.GetLanguageByTwoLetterISOName(region).langId;
                def_LookupText lt     = formsRepo.GetLookupTextsByLookupDetailLanguage(ld.lookupDetailId, langId).FirstOrDefault();
                if (lt != null)
                {
                    return(lt.displayText);
                }
            }
            return(rsp);
        }
        private void printD5AndD6(def_Sections sct, int indentLevel, double sectionLabelIndent, double itemLabelIndent, double responseIndent)
        {
            Dictionary <string, string> responses = GetResponsesByItemVariableIdentifier(sct);

            List <string> yesLabels = new List <string>();

            foreach (string ivIdent in responses.Keys)
            {
                if (responses[ivIdent].Equals("Yes"))
                {
                    def_ItemVariables iv  = formsRepo.GetItemVariableByIdentifier(ivIdent);
                    def_Items         itm = formsRepo.GetItemById(iv.itemId);
                    yesLabels.Add(itm.label);
                }
            }
            if (yesLabels.Count > 0)
            {
                string rsp = yesLabels[0];
                for (int i = 1; i < yesLabels.Count; i++)
                {
                    rsp += ", " + yesLabels[i];
                }

                printGenericSectionHeader(sct, sectionLabelIndent);
                output.appendWrappedText(rsp, responseIndent, 8 - responseIndent);
                output.drawY -= .1;
            }
        }
        protected void buildTableWithItems(PdfOutput output, def_Parts part, int nColumns, string[] headers, params string[] identifiers)
        {
            int nRows = identifiers.Length / nColumns;

            string[][] vals = new string[nRows][];
            for (int row = 0; row < nRows; row++)
            {
                vals[row] = new string[nColumns];
                for (int col = 0; col < nColumns; col++)
                {
                    string    ident = identifiers[row * nColumns + col];
                    def_Items itm   = formsRepo.GetItemByIdentifier(/*formResults,*/ ident);                  //formsRepo.GetAllItems().First(t => t.identifier.Equals(ident));//getItemByIdentifier(part,ident);
                    if (itm == null)
                    {
                        throw new Exception("could not find item with identifer " + ident);
                    }
                    formsRepo.GetItemVariables(itm);
                    def_ItemVariables iv = itm.def_ItemVariables.FirstOrDefault();
                    if (iv == null)
                    {
                        throw new Exception("could not find any itemVariables for item with identifer " + ident);
                    }
                    def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(formResultId, iv.itemVariableId);                    //iv.def_ResponseVariables.FirstOrDefault();
                    vals[row][col] = ((rv == null) ? "" : rv.rspValue);
                }
            }
            output.appendSimpleTable(headers, vals);
        }
        //                BuildItemResults(output, part, "SIS-Prof1_PageNotes_item");

        protected void BuildItemResults(PdfOutput output, def_Parts part, params object[] identifiersOrPairs)
        {
            foreach (object identOrPair in identifiersOrPairs)
            {
                if (identOrPair is string)
                {
                    string    ident = (string)identOrPair;
                    def_Items itm   = formsRepo.GetItemByIdentifier(ident);
                    formsRepo.GetEnterpriseItems(new def_Items[] { itm }.ToList(), formResults.EnterpriseID.Value);
                    if (itm == null)
                    {
                        throw new Exception("could not find item with identifier " + ident);
                    }
                    string rv = GetSingleResponse(itm);
                    output.appendItem(itm.label.Replace("*", ""), (rv == null) ? "" : rv.Replace("@", "@    "));
                }
                else if (identOrPair is LabelValuePair)
                {
                    LabelValuePair p = (LabelValuePair)identOrPair;
                    output.appendItem(p.label, p.value);
                }
                else
                {
                    throw new Exception("unrecognized object type in parameter \"identifieresOrPairs\", objects must be of type string or pair");
                }
            }
        }
        protected string GetResponse(int formResultId, def_Items itm, def_ItemVariables iv)
        {
            def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(formResultId, iv.itemVariableId);
            string response          = (rv == null) ? String.Empty : rv.rspValue;

            // special case for drop-downs/radiolists with options in meta-data
            if ((itm != null) && (iv.baseTypeId == 8) && !String.IsNullOrWhiteSpace(itm.prompt) && itm.prompt.Contains(";"))
            {
                try {
                    return(itm.prompt.Split(';')[Convert.ToInt16(response) - 1]);
                }
                catch (Exception e) {
                    Debug.WriteLine(" *** FormResultPdfReport.cs failed to retrieve selected option for ItemVariable "
                                    + iv.itemVariableId + ", response string \"" + response + "\"");
                }
            }

            //special case for YES/NO items
            else if ((response != null) && (iv.baseTypeId == 1))
            {
                if (response.Equals("1"))
                {
                    return("Yes");
                }

                if (response.Equals("0"))
                {
                    return("No");
                }
            }

            return(response);
        }
        //ADAP_F3
        protected void printF3(def_Sections sct, int indentLevel, double sectionLabelIndent, double itemLabelIndent, double responseIndent)
        {
            printGenericSectionHeader(sct, sectionLabelIndent);
            Dictionary <string, string> responses = GetResponsesByItemVariableIdentifierThroughLookupTables(sct);

            foreach (string ivIdent in responses.Keys)
            {
                if (String.IsNullOrWhiteSpace(responses[ivIdent]))
                {
                    continue;
                }
                def_Items itm = formsRepo.GetItemByIdentifier(ivIdent + "_item");

                itm = formsRepo.GetItemById(itm.itemId);    //Get the version of the item as it appears on the form.

                if (ivIdent.EndsWith("IncomeProof") || ivIdent.EndsWith("EmployerForm"))
                {
                    appendAdapAttachmentLink(itm.label, ivIdent, itemLabelIndent, responseIndent);
                }
                else
                {
                    appendItemLabelAndResponses(itm, itemLabelIndent, responseIndent, responses);
                }
            }
        }
示例#8
0
        private void PrintGenericSection(PdfOutput output, def_Sections section, int indentLevel)
        {
            output.appendSectionBreak();
            double indent = .5 + labelIndent * (indentLevel - 1);

            output.appendWrappedText(section.identifier, indent, 8 - indent, 12);
            output.drawY -= .2;
            formsRepo.GetSectionItems(section);
            foreach (def_SectionItems si in section.def_SectionItems)
            {
                if (si.subSectionId.HasValue)
                {
                    PrintGenericSection(output, formsRepo.GetSubSectionById(si.subSectionId.Value), indentLevel + 1);
                }
                else
                {
                    def_Items itm = formsRepo.GetItemById(si.itemId);//si.def_Items;
                    indent = labelIndent * indentLevel;
                    output.appendWrappedText(itm.label, indent, 8 - indent, output.boldFont);
                    foreach (def_ItemVariables iv in itm.def_ItemVariables)
                    {
                        def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(formResultId, iv.itemVariableId);
                        string s = (rv == null) ? "N/A" : rv.rspValue;
                        indent = valueIndent + labelIndent * (indentLevel - 1);
                        output.appendWrappedText(iv.identifier + ": " + s, indent, 8 - indent);
                    }
                    output.drawY -= .1;
                }
            }
        }
        private void printD8(def_Sections sct, int indentLevel, double sectionLabelIndent, double itemLabelIndent, double responseIndent)
        {
            //append the "current gender" response in the same line as the section header
            double drawY = output.drawY;

            printGenericSectionHeader(sct, sectionLabelIndent);
            def_ItemVariables ivCurrGender  = formsRepo.GetItemVariableByIdentifier("ADAP_D8_CurrGenderDrop");
            string            rspCurrGender = GetResponseThroughLookupTables(formResultId, ivCurrGender.def_Items, ivCurrGender);

            if (!String.IsNullOrWhiteSpace(rspCurrGender))
            {
                output.drawY = drawY;
                output.appendWrappedText(rspCurrGender, responseIndent, 8 - responseIndent);
                output.drawY -= .1;
            }

            //if applicable, append the "gender at birth" label and response on one line
            def_Items         itmBirthGenderLabel = formsRepo.GetItemByIdentifier("ADAP_D8_BirthGenderLabel_item");
            def_ItemVariables ivBirthGender       = formsRepo.GetItemVariableByIdentifier("ADAP_D8_BirthGenderDrop");
            string            rspBirthGender      = GetResponseThroughLookupTables(formResultId, ivBirthGender.def_Items, ivBirthGender);

            if (!String.IsNullOrWhiteSpace(rspBirthGender))
            {
                double itemLabelHeight = itmBirthGenderLabel == null ? 0 :
                                         output.appendWrappedText(itmBirthGenderLabel.label, itemLabelIndent, responseIndent - itemLabelIndent, output.boldFont);
                double drawYBelowItemLabel = output.drawY;
                output.drawY += itemLabelHeight;
                output.appendWrappedText(rspBirthGender, responseIndent, 8 - responseIndent);
                output.drawY = Math.Min(drawYBelowItemLabel, output.drawY - .05);
            }

            //Dictionary<string, string> responses = GetResponsesByItemVariableIdentifierThroughLookupTables(sct);

            //foreach (string prefix in new string[] { "ADAP_D8_CurrGender", "ADAP_D8_BirthGender" })
            //{

            //    string ivIdent = prefix + "Drop";
            //    string labelItemIdent = prefix + "Label_item";

            //    def_Items labelItm = formsRepo.GetItemByIdentifier(labelItemIdent);
            //    string rsp = responses.ContainsKey( ivIdent ) ? responses[ivIdent] : "";

            //    //append item label (if applicable), without actually moving drawY down the page
            //    double itemLabelHeight =  labelItm == null ? 0 :
            //        output.appendWrappedText(labelItm.label, itemLabelIndent, responseIndent - itemLabelIndent, output.boldFont);
            //    double drawYBelowItemLabel = output.drawY;
            //    output.drawY += itemLabelHeight;
            //    output.appendWrappedText(rsp, responseIndent, 8 - responseIndent);
            //    output.drawY = Math.Min(drawYBelowItemLabel, output.drawY - .05);

            //}
        }
        protected string GetSingleResponse(def_Items itm)
        {
            def_ItemResults ir = formsRepo.GetItemResultByFormResItem(formResultId, itm.itemId);

            if (ir == null)
            {
                return(String.Empty);
            }

            formsRepo.GetItemResultsResponseVariables(ir);
            def_ResponseVariables rv = ir.def_ResponseVariables.FirstOrDefault();

            return((rv == null) ? String.Empty : rv.rspValue);
        }
 protected void buildTableWithItems(PdfOutput output, def_Parts part, int nColumns, params string[] identifiers)
 {
     string[] headers = new string[nColumns];
     for (int i = 0; i < nColumns; i++)
     {
         string    ident = identifiers[i];
         def_Items itm   = formsRepo.GetItemByIdentifier(/*formResults,*/ ident);              //formsRepo.GetAllItems().First(t => t.identifier.Equals(ident));//getItemByIdentifier(part,ident);
         if (itm == null)
         {
             throw new Exception("could not find item with identifer " + ident);
         }
         headers[i] = itm.label.Replace("*", "");
     }
     buildTableWithItems(output, part, nColumns, headers, identifiers);
 }
示例#12
0
        public void CreateEligibilityField(string identifier)
        {
            //  Get the FormResult to get the subject of the current Application
            def_FormResults fr = formsRepo.GetFormResultById(SessionHelper.SessionForm.formResultId);

            // Get the Eligibility Form for the subject
            IEnumerable <def_FormResults> frElgList = formsRepo.GetFormResultsByFormSubject(18, fr.subject);
            var frmRes = frElgList.First <def_FormResults>();
            Dictionary <string, string> DataToPopulate = new Dictionary <string, string>();

            DataToPopulate.Add(identifier, string.Empty);

            foreach (String s in DataToPopulate.Keys)
            {
                def_Items       item = formsRepo.GetItemByIdentifier(s + "_item");
                def_ItemResults ir   = new def_ItemResults()
                {
                    itemId        = item.itemId,
                    sessionStatus = 0,
                    dateUpdated   = DateTime.Now
                };

                var itemResult = formsRepo.GetItemResultByFormResItem(frmRes.formResultId, item.itemId);
                if (itemResult == null)
                {
                    frmRes.def_ItemResults.Add(ir);
                }
                else
                {
                    ir = itemResult;
                }

                foreach (var iv in formsRepo.GetItemVariablesByItemId(item.itemId))
                {
                    // Note for General forms like ADAP there should only be 1 ItemVariable per Item
                    def_ResponseVariables rv = new def_ResponseVariables();
                    rv.itemVariableId = iv.itemVariableId;
                    // rv.rspDate = DateTime.Now;    // RRB 11/11/15 The date, fp, and int fields are for the native data conversion.
                    rv.rspValue = DataToPopulate[s];

                    formsRepo.ConvertValueToNativeType(iv, rv);
                    ir.def_ResponseVariables.Add(rv);
                }
            }

            formsRepo.Save();
        }
        //if responsesByItemVariable is supplied, responses will be pulled from there rather than db
        protected void appendItemLabelAndResponses(
            def_Items itm,
            double itemLabelIndent,
            double responseIndent,
            Dictionary <string, string> responsesByItemVariableIdentifier = null)
        {
            List <string>            responses     = new List <string>();
            List <def_ItemVariables> itemVariables = formsRepo.GetItemVariablesByItemId(itm.itemId);

            foreach (def_ItemVariables iv in itemVariables)
            {
                //if this itemvariable has been explicitely removed from responsesByItemVariableIdentifier, skip it
                if ((responsesByItemVariableIdentifier != null) && !responsesByItemVariableIdentifier.ContainsKey(iv.identifier))
                {
                    continue;
                }

                string rsp = (responsesByItemVariableIdentifier == null) ? GetSingleResponse(iv.identifier) : responsesByItemVariableIdentifier[iv.identifier];
                if (rsp != null)
                {
                    responses.Add(rsp);
                }
            }

            //if there are no responses, terminate without even printing the item label
            if (responses.Count == 0)
            {
                return;
            }

            //append item label, without actually moving drawY down the page
            double itemLabelHeight     = output.appendWrappedText(itm.label, itemLabelIndent, responseIndent - itemLabelIndent, output.boldFont);
            double drawYBelowItemLabel = output.drawY;

            output.drawY += itemLabelHeight;

            //append responses to the right of the item label
            foreach (string rsp in responses)
            {
                output.appendWrappedText(rsp, responseIndent, 8 - responseIndent);
            }

            output.drawY = Math.Min(drawYBelowItemLabel, output.drawY - .05);
        }
        //ADAP_C3
        private void printC3(def_Sections sct, int indentLevel, double sectionLabelIndent, double itemLabelIndent, double responseIndent)
        {
            printGenericSectionHeader(sct, sectionLabelIndent);

            Dictionary <string, string> responses = GetResponsesByItemVariableIdentifierThroughLookupTables(sct);

            for (int i = 1; i <= 2; i++)
            {
                string prefix = "ADAP_C3_Phone" + i + "_";
                if (responses.ContainsKey(prefix + "Num") && !String.IsNullOrWhiteSpace(responses[prefix + "Num"]))
                {
                    foreach (string shortIdent in new string[] { "Num", "Type", "MayMsgYN" })
                    {
                        def_Items itm = formsRepo.GetItemByIdentifier(prefix + shortIdent + "_item");
                        itm = formsRepo.GetItemById(itm.itemId);    //Get the version of the item as it appears on the form.
                        appendItemLabelAndResponses(itm, itemLabelIndent, responseIndent, responses);
                    }
                }
            }
        }
        //Public instance methods

        /// <summary>
        /// Used by the create application method to populate the application with data from UAS.
        /// Creates a new forms result object for the application.
        /// </summary>
        /// <param name="subjectUserId">Numerical Identifier of the user creating a new application.</param>
        /// <param name="formId">Numerical Identifier of the form to use for the new application</param>
        /// <param name="DataToPopulate">Dictionary object listing the items to be pulled from UAS.</param>
        /// <returns>Returns the forms result object created by this method.</returns>
        public def_FormResults CreateFormResultPopulatedFromUAS(int entId, int groupId, int subjectUserId, int formId, Dictionary <string, string> DataToPopulate)
        {
            Debug.WriteLine("*** populateFromUAS ***");
            def_FormResults frmRes = Assmnts.Models.FormResults.CreateNewFormResultModel(formId.ToString());

            frmRes.EnterpriseID = entId;
            frmRes.GroupID      = groupId;
            frmRes.subject      = subjectUserId;
            frmRes.interviewer  = subjectUserId;
            frmRes.assigned     = subjectUserId;
            frmRes.reviewStatus = 0;

            foreach (String s in DataToPopulate.Keys)
            {
                def_Items       item = formsRepo.GetItemByIdentifier(s);
                def_ItemResults ir   = new def_ItemResults()
                {
                    itemId        = item.itemId,
                    sessionStatus = 0,
                    dateUpdated   = DateTime.Now
                };

                frmRes.def_ItemResults.Add(ir);

                foreach (var iv in formsRepo.GetItemVariablesByItemId(item.itemId))
                {
                    // Note for General forms like ADAP there should only be 1 ItemVariable per Item
                    def_ResponseVariables rv = new def_ResponseVariables();
                    rv.itemVariableId = iv.itemVariableId;
                    // rv.rspDate = DateTime.Now;    // RRB 11/11/15 The date, fp, and int fields are for the native data conversion.
                    rv.rspValue = DataToPopulate[s];

                    formsRepo.ConvertValueToNativeType(iv, rv);
                    ir.def_ResponseVariables.Add(rv);
                }
            }

            Debug.WriteLine("PopulateFromUAS FormResults populated.");
            return(frmRes);
        }
        //ADAP_I3
        protected void printI3(def_Sections sct, int indentLevel, double sectionLabelIndent, double itemLabelIndent, double responseIndent)
        {
            printGenericSectionHeader(sct, sectionLabelIndent);
            Dictionary <string, string> responses = GetResponsesByItemVariableIdentifier(sct);

            foreach (string ivIdent in responses.Keys)
            {
                if (String.IsNullOrWhiteSpace(responses[ivIdent]))
                {
                    continue;
                }
                def_Items itm = formsRepo.GetItemByIdentifier(ivIdent + "_item");

                if (ivIdent == "ADAP_I3_Invoice")
                {
                    appendAdapAttachmentLink(itm.label, ivIdent, itemLabelIndent, responseIndent);
                }
                else
                {
                    appendItemLabelAndResponses(itm, itemLabelIndent, responseIndent, responses);
                }
            }
        }
示例#17
0
        protected void PrintSupportNeedsGraph(PdfOutput output, int ageInYears)
        {
            Debug.WriteLine("PrintSupportNeedsGraph() method.");

            new Assessments(formsRepo).UpdateAssessmentScores(formResults);

            def_Parts prt = formsRepo.GetPartByFormAndIdentifier(form, "Section 2. Supports Needs Index");

            formsRepo.GetPartSections(prt);
            int row = 0, nRows = prt.def_PartSections.Count();

            double[]      percentiles       = new double[nRows];
            string[][]    supNeedsTableVals = new string[nRows][];
            List <string> subscaleLabels    = new List <string>();

            Debug.WriteLine("     Print Part 3");
            foreach (def_PartSections ps in prt.def_PartSections)
            {
                // Debug.WriteLine("     ps.sectionId: " + ps.sectionId.ToString());
                def_Sections sct = formsRepo.GetSectionById(ps.sectionId);
                subscaleLabels.Add(sct.title);
                Debug.WriteLine("     sct.sectionId: " + sct.sectionId.ToString());


                //pull subscale scores from database
                string sctNumberLetter = sct.title.Substring(0, sct.title.IndexOf('.'));
                double totalRawScore   = getScoreResponse("scr_" + sctNumberLetter + "_raw");
                double standardScore   = getScoreResponse("scr_" + sctNumberLetter + "_std");
                double rawScoreAvg     = getScoreResponse("scr_" + sctNumberLetter + "_avg");
                double percentile      = getScoreResponse("scr_" + sctNumberLetter + "_pct");
                double confidenceLow   = Math.Max(0, standardScore - 1);
                double confidenceHigh  = standardScore + 1;

                percentiles[row] = percentile;
                string rowLabel = sct.title.Replace("ActivitiesHI", "");
                rowLabel = rowLabel.Replace("and Neighborhood", "...");
                supNeedsTableVals[row] = new string[] {
                    rowLabel,
                    (form.formId == 1) ? totalRawScore.ToString() : String.Format("{0:0.##}", rawScoreAvg),
                    standardScore.ToString(),
                    percentile.ToString(),
                    confidenceLow + "-" + confidenceHigh
                };

                row++;
            }

            //pull overall scores from database
            double totalRawScoreTotal       = getScoreResponse("scr_total_rawscores_all_SIS_sections");
            double standardScoreTotal       = getScoreResponse("scr_standard_score_total");
            double compositeIndex           = getScoreResponse("scr_support_needs_index");
            double compositePercentile      = getScoreResponse("scr_sni_percentile_rank");
            double totalRating              = getScoreResponse("scr_total_rating");
            double meanRating               = Math.Round((double)totalRating / 7, 2); //usd only for SIS-C reports

            AppendPartHeader(output, "Support Needs Profile - Graph");

            output.appendWrappedText("The graph provides a visual presentation of the six life activity areas from section 2. ", .5, 7.5);

            output.drawY -= .1;
            output.appendWrappedText("The graph reflects the pattern and intensity of the individual’s level of support. "
                                     + "The intent of the graph is to provide an easy means to prioritize the life activity areas in consideration "
                                     + "of setting goals and developing the Individual Support Plan. ", .5, 7.5);

            output.drawY -= .15;

            if (options[OptionKey.includeScores])
            {
                output.appendSimpleTable(
                    new string[] { "Activities Subscale", (form.formId == 1) ? "Total Raw Score" : "Average Raw Score",
                                   "Standard Score", "Percentile", "Confidence Interval (95%)" },
                    supNeedsTableVals,
                    new double[] { 0, .35, .35, .3, .35 });
                output.drawY -= PdfOutput.itemSpacing;

                if (form.identifier.Equals("SIS-A"))
                {
                    //for SIS-A, add a row to the bottom of the table, with totals
                    output.DrawLine(.75, output.drawY + .05, 7.75, output.drawY + .05, .01);
                    output.appendSimpleTable(
                        new string[] { "Total:",
                                       totalRawScoreTotal.ToString(),
                                       standardScoreTotal.ToString(), "", "" },
                        new string[0][],
                        new double[] { 0, .35, .35, .3, .35 },
                        new double[] { .08, .35, .35, .3, .35 }
                        );

                    output.drawY -= .2;
                }
                else
                {
                    //for SIS-C
                    output.appendItem("Overall Mean Rating", String.Format("{0:0.##}", meanRating), 2);
                }

                output.appendItem("SIS Support Needs Index", compositeIndex.ToString(), 2);
                output.appendItem("Percentile", compositePercentile.ToString(), 2);
                output.drawY -= PdfOutput.itemSpacing;
            }

            //AppendPartHeader(output, "Support Needs Profile");
            AppendReportChart(output, subscaleLabels.ToArray(), percentiles, compositePercentile);

            if (!options[OptionKey.includeScores])
            {
                return;
            }

            if (form.identifier.Equals("SIS-A"))
            {
                Debug.WriteLine("     Print Part 4");
                prt = formsRepo.GetPartByFormAndIdentifier(form, "Section 3. Supplemental Protection and Advocacy Scale");
                formsRepo.GetPartSections(prt);
                List <def_Sections> scts   = formsRepo.GetSectionsInPart(prt);
                def_Sections        proSct = scts[0];
                if (proSct == null)
                {
                    throw new Exception("could not find any sections in part \"Section 3. Supplemental Protection and Advocacy Scale\"");
                }

                List <def_Items> proItms = formsRepo.GetSectionItems(proSct);  // getItemsInSection(proSct);
                // RRB 3/17/15 - this is hokey, but not sure how else to do it at this point w/o the SectionItems.
                //                  should be checking SectionItems.subSectionId != null
                // Prune out the subSections (this is
                for (int i = 0; i < proItms.Count; i++)
                {
                    if (proItms[i].itemId == 1)
                    {
                        proItms.Remove(proItms[i]);
                    }
                }

                int        nProItms        = proItms.Count();
                string[][] supProTableVals = new string[nProItms][];
                for (int i = 0; i < nProItms; i++)
                {
                    def_Items itm      = proItms[i];
                    int       rawScore = 0;
                    // def_ItemResults itmResults = itm.def_ItemResults.SingleOrDefault(ir => ir.formResultId == formResultId);
                    def_ItemResults itmResults = formsRepo.GetItemResultByFormResItem(formResultId, itm.itemId);
                    for (int j = 0; j < 3; j++)
                    {
                        string suffix   = SupportNeedsColumnSuffixes[j];
                        string rspValue = null;

                        try
                        {
                            rspValue = itmResults.def_ResponseVariables.SingleOrDefault(rv => rv.def_ItemVariables.identifier.EndsWith(suffix)).rspValue;
                        }
                        catch (System.NullReferenceException ex)
                        {
                            Debug.Print("for itemId " + itm.itemId + ", could not find responseVariable linked to itemVariableIdentifier with suffix \"" + suffix + "\"");
                        }

                        try
                        {
                            rawScore += Int16.Parse(rspValue);
                        }
                        catch (Exception ex)
                        {
                            Debug.Print("could not parse integer from response value \"" + rspValue + "\"");
                        }
                    }

                    supProTableVals[i]    = new string[2];
                    supProTableVals[i][0] = itm.label;
                    supProTableVals[i][1] = rawScore.ToString();
                }

                output.drawY -= PdfOutput.itemSpacing;
                AppendPartHeader(output, "Section 3: Supplemental Protection and Advocacy Scale");
                output.appendSimpleTable(new string[] { "Protection and Advocacy Activities", "Raw Score" }, supProTableVals, new double[] { 0, .2 });

                output.drawY -= .2;
                output.appendWrappedText("The support needs profile reflects the pattern and intensity of the "
                                         + "individual’s support. The information provided in sections 1, 2, and 3, can be beneficial "
                                         + "in the development of the individual’s support plan.", .5, 7.5);
            }
        }
示例#18
0
        public void CreateElgibility(int formResultId)
        {
            string     formIdent = "CA-ADAP-DASHBOARD", entName = "California";
            def_Forms  frm = formsRepo.GetFormByIdentifier(formIdent);
            Enterprise ent = new AuthenticationClient().GetEnterpriseByName(entName);

            //  Get the FormResult to get the subject of the current Application
            def_FormResults fr = formsRepo.GetFormResultById(formResultId);

            // Get the Eligibility Form for the subject
            IEnumerable <def_FormResults> frElgList = formsRepo.GetFormResultsByFormSubject(frm.formId, fr.subject);
            def_FormResults frmRes = null;

            if ((frElgList == null) || frElgList.Count <def_FormResults>() == 0)
            {
                mLogger.Debug("Couldn't find a current FormResult for Eligibility.  Create one.");
                frmRes = new def_FormResults()
                {
                    formId               = frm.formId,
                    formStatus           = 0,
                    sessionStatus        = 0,
                    dateUpdated          = DateTime.Now,
                    deleted              = false,
                    locked               = false,
                    archived             = false,
                    EnterpriseID         = ent.EnterpriseID,
                    GroupID              = fr.GroupID, // User the same Enrollment Center
                    subject              = fr.subject,
                    interviewer          = fr.interviewer,
                    assigned             = fr.assigned,
                    training             = false,
                    reviewStatus         = 0,
                    statusChangeDate     = DateTime.Now,
                    LastModifiedByUserId = fr.LastModifiedByUserId
                };

                int newFrmRsltId = formsRepo.AddFormResult(frmRes);
                mLogger.Debug("New Eligibility FormResult created: {0}", newFrmRsltId);
            }
            else
            {
                frmRes = frElgList.First <def_FormResults>();
            }

            // make sure item responses exist for the form
            Dictionary <string, string> DataToPopulate = new Dictionary <string, string>();
            var sectionItems = formsRepo.GetSectionItemsBySectionId(756);

            AuthenticationClient authClient = new AuthenticationClient();
            var uasData = authClient.GetUser(fr.subject.Value);
            var adapId  = authClient.GetADAPIdentifier(uasData.UserID, uasData.EnterpriseID);

            foreach (var item in sectionItems)
            {
                var defItem = formsRepo.GetItemById(item.itemId);

                if (defItem.identifier == "C1_MemberIdentifier_item")
                {
                    DataToPopulate.Add(defItem.identifier, adapId);
                }
                else if (defItem.identifier == "C1_MemberFirstName_item")
                {
                    def_ResponseVariables firstName = formsRepo.GetResponseVariablesBySubjectForm(fr.subject.Value, 15, "C1_MemberFirstName");
                    DataToPopulate.Add(defItem.identifier, firstName != null ? firstName.rspValue : string.Empty);
                }
                else if (defItem.identifier == "C1_MemberLastName_item")
                {
                    def_ResponseVariables lastName = formsRepo.GetResponseVariablesBySubjectForm(fr.subject.Value, 15, "C1_MemberLastName");
                    DataToPopulate.Add(defItem.identifier, lastName != null ? lastName.rspValue : string.Empty);
                }
                else if (defItem.identifier == "C1_MemberDateOfBirth_item")
                {
                    def_ResponseVariables dob = formsRepo.GetResponseVariablesBySubjectForm(fr.subject.Value, 15, "C1_MemberDateOfBirth");
                    DataToPopulate.Add(defItem.identifier, dob != null ? dob.rspValue : string.Empty);
                }
                else
                {
                    DataToPopulate.Add(defItem.identifier, string.Empty);
                }
            }

            foreach (String s in DataToPopulate.Keys)
            {
                def_Items       item = formsRepo.GetItemByIdentifier(s);
                def_ItemResults ir   = new def_ItemResults()
                {
                    itemId        = item.itemId,
                    sessionStatus = 0,
                    dateUpdated   = DateTime.Now
                };

                // check if the key already exist
                var itemResult = formsRepo.GetItemResultByFormResItem(frmRes.formResultId, item.itemId);
                if (itemResult == null)
                {
                    frmRes.def_ItemResults.Add(ir);

                    foreach (var iv in formsRepo.GetItemVariablesByItemId(item.itemId))
                    {
                        // Note for General forms like ADAP there should only be 1 ItemVariable per Item
                        def_ResponseVariables rv = new def_ResponseVariables();
                        rv.itemVariableId = iv.itemVariableId;
                        // rv.rspDate = DateTime.Now;    // RRB 11/11/15 The date, fp, and int fields are for the native data conversion.
                        rv.rspValue = DataToPopulate[s];

                        formsRepo.ConvertValueToNativeType(iv, rv);
                        ir.def_ResponseVariables.Add(rv);
                    }
                }
                else
                {
                    ir = itemResult;
                }
            }

            formsRepo.Save();
        }
示例#19
0
        public FileStreamResult ExportFormJSON()
        {
            //use session variables to pick a FormResults object from the database
            string formId = Request["formId"] as string;

            Debug.WriteLine("* * *  GetFormResultsJSON formId: " + formId);

            int iFormId = Convert.ToInt32(formId);

            formsEntities db = DataContext.GetDbContext();

            db.Configuration.LazyLoadingEnabled = false;

            // def_Forms form = db.def_Forms
            //     .Include(fr => fr.def_FormParts
            //         .Select(fp => fp.def_Parts)
            //         .Select(pa => pa.def_PartSections
            //             .Select(p => p.def_Sections)
            //             .Select(s => s.def_SectionItems
            //             .Select(si => si.def_SubSections))))
            //     .Include(fr => fr.def_FormParts
            //         .Select(fp => fp.def_Parts)
            //         .Select(pa => pa.def_PartSections
            //             .Select(p => p.def_Sections)
            //             .Select(s => s.def_SectionItems
            //                 .Select(si => si.def_Items)
            //                 .Select(i => i.def_ItemVariables))))
            //     .Single(f => f.formId == iFormId);



            def_Forms            form      = db.def_Forms.Where(f => f.formId == iFormId).FirstOrDefault();
            List <def_FormParts> formParts = db.def_FormParts.Where(fp => fp.formId == iFormId).ToList();
            List <int>           partIds   = formParts.Select(fp => fp.partId).ToList();
            List <def_Parts>     parts     = db.def_Parts.Where(p => partIds.Contains(p.partId)).ToList();

            partIds = parts.Select(p => p.partId).ToList();
            List <def_PartSections> partSections = db.def_PartSections.Where(ps => partIds.Contains(ps.partId)).ToList();
            List <int>          sectionIds       = partSections.Select(ps => ps.sectionId).ToList();
            List <def_Sections> sections         = db.def_Sections.Where(s => sectionIds.Contains(s.sectionId)).ToList();

            List <def_SectionItems>  sectionItems  = new List <def_SectionItems>();
            List <def_SubSections>   subSections   = new List <def_SubSections>();
            List <def_Items>         items         = new List <def_Items>();
            List <def_ItemVariables> itemVariables = new List <def_ItemVariables>();

            foreach (def_Sections section in sections)
            {
                GetSectionItemsAndSubSectionsRecursive(section.sectionId, sectionItems, subSections);
            }

            foreach (def_SectionItems si in sectionItems)
            {
                if (si.subSectionId == null)
                {
                    def_Items item = db.def_Items.Where(i => i.itemId == si.itemId).FirstOrDefault();

                    items.Add(item);

                    List <def_ItemVariables> newItemVariables = db.def_ItemVariables.Where(iv => iv.itemId == item.itemId).ToList();

                    itemVariables.AddRange(newItemVariables);
                }
            }


            string jsonString = "{\"data\":[" + fastJSON.JSON.ToJSON(form);

            jsonString += "," + fastJSON.JSON.ToJSON(formParts);
            jsonString += "," + fastJSON.JSON.ToJSON(parts);
            jsonString += "," + fastJSON.JSON.ToJSON(partSections);
            jsonString += "," + fastJSON.JSON.ToJSON(sections);
            jsonString += "," + fastJSON.JSON.ToJSON(sectionItems);
            jsonString += "," + fastJSON.JSON.ToJSON(subSections);
            jsonString += "," + fastJSON.JSON.ToJSON(items);
            jsonString += "," + fastJSON.JSON.ToJSON(itemVariables);
            jsonString += "]}";

            MemoryStream stream = new MemoryStream();

            //write json string to file, then stream it out
            //DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(FormResultJSON));

            StreamWriter streamWriter = new StreamWriter(stream);

            streamWriter.Write(jsonString);
            //streamWriter.Close();
            //stream.Close();

            FileStreamResult fsr = null;

            streamWriter.Flush();
            stream.Position = 0;

            try
            {
                fsr = new FileStreamResult(stream, "application/json")
                {
                    FileDownloadName = form.identifier + " " + DateTime.Now + ".json"
                };
            }
            catch (Exception exp)
            {
                Debug.WriteLine("File write exception: " + exp.Message);
                string errMsg = "File write exception: " + exp.Message;
                return(ProcessError(errMsg));
            }


            return(fsr);
        }
示例#20
0
        // This is for the sets of items that have 3 numerical response values
        private void BuildDetailedResponseTable(def_Parts part, PdfOutput output, def_Sections sct)
        {
            int nCols = 6;

            string[] headers = { sct.title, "", "Freq", "Time", "Type", "Important \"To\" or \"For\"" };
            double[] indents = { .5, .75, 5.3, 5.6, 5.95, 6.75 };

            //headers
            output.drawY -= .1;
            for (int i = 0; i < nCols; i++)
            {
                output.DrawText(output.boldFont, output.fontSize, indents[i], output.drawY, headers[i]);
            }
            output.drawY += .13; output.appendSectionBreak();
            output.drawY -= PdfOutput.itemSpacing;

            indents = new double[] { .5, .75, 5.38, 5.73, 6.05, 6.75 };
            List <def_Items> itms = formsRepo.GetSectionItems(sct);

            // Values
            for (int row = 0; row < itms.Count; row++)
            {
                def_Items       itm        = itms[row];
                def_ItemResults itmResults = formsRepo.GetItemResultByFormResItem(formResultId, itm.itemId);
                formsRepo.GetItemResultsResponseVariables(itmResults);
                foreach (def_ResponseVariables rv in itmResults.def_ResponseVariables)
                {
                    rv.def_ItemVariables = formsRepo.GetItemVariableById(rv.itemVariableId);
                }

                output.drawY -= .1;
                for (int col = 0; col < nCols; col++)
                {
                    string s = "ERROR";
                    switch (col)
                    {
                    case 0:
                        s = (row + 1).ToString();
                        break;

                    case 1:
                        s = itm.label;
                        break;

                    case 2:
                    case 3:
                    case 4:
                        s = null;
                        string suffix = SupportNeedsColumnSuffixes[col - 2];
                        try
                        {
                            //Debug.WriteLine("\titemvariableId= " + ivEnum.Current.itemVariableId);
                            s = itmResults.def_ResponseVariables.SingleOrDefault(rv => rv.def_ItemVariables.identifier.EndsWith(suffix)).rspValue;
                        }
                        catch (System.NullReferenceException ex)
                        {
                            Debug.Print("for itemId " + itm.itemId + ", could not find responseVariable linked to itemVariableIdentifier with suffix \"" + suffix + "\"");
                            Debug.Print("   NullReferenceException: " + ex.Message);
                        }
                        s = String.IsNullOrEmpty(s) ? "N/A" : s;
                        break;

                    case 5:
                        s = String.Empty;
                        break;
                    }
                    output.DrawText(output.contentFont, output.fontSize, indents[col], output.drawY, s);
                }
                output.drawY -= PdfOutput.itemSpacing * 2.5;
                if (output.drawY < 1)
                {
                    output.appendPageBreak();
                }
            }

            output.drawY -= .1;
            output.DrawText(output.boldFont, output.fontSize, indents[1], output.drawY, "Page Notes:");
            output.drawY -= PdfOutput.itemSpacing * 4;
            if (output.drawY < 1)
            {
                output.appendPageBreak();
            }
        }
示例#21
0
        //this is for the sections in the "Exceptional medical... needs" part
        private void PrintExceptMedNeedsTable(def_Parts part, PdfOutput output, def_Sections sct)
        {
            int nCols = 4;

            string[] headers = { sct.title, "", "Score", "Important \"To\" or \"For\"" };
            double[] indents = { .5, .75, 5.6, 6.75 };

            //headers
            output.drawY -= .1;
            for (int i = 0; i < nCols; i++)
            {
                output.DrawText(output.boldFont, output.fontSize, indents[i], output.drawY, headers[i]);
            }
            output.drawY += .13; output.appendSectionBreak();
            output.drawY -= PdfOutput.itemSpacing;

            indents = new double[] { .5, .75, 5.73, 6.75 };
            List <def_Items> itms = new List <def_Items>();

            formsRepo.SortSectionItems(sct);
            foreach (def_SectionItems si in sct.def_SectionItems)
            {
                if (si.subSectionId == null)    // NOTE: this case probably never occurs for this Part
                {
                    itms.Add(formsRepo.GetItemById(si.itemId));
                }
                else
                {
                    def_Sections sctn = formsRepo.GetSubSectionById(si.subSectionId);
                    formsRepo.SortSectionItems(sctn);
                    foreach (def_SectionItems ssi in sctn.def_SectionItems)
                    {
                        if (ssi.subSectionId == null)
                        {
                            itms.Add(formsRepo.GetItemById(ssi.itemId));
                        }
                    }
                }
            }
            int nRows = itms.Count() + 1;

            // Load the Values
            for (int row = 0; row < itms.Count; row++)
            {
                def_Items itm = itms[row];
                formsRepo.GetItemResultByFormResItem(formResultId, itm.itemId);
                def_ItemResults itmResults = itm.def_ItemResults.SingleOrDefault(ir => (ir.formResultId == formResultId));
                formsRepo.GetItemResultsResponseVariables(itmResults);
                foreach (def_ResponseVariables rv in itmResults.def_ResponseVariables)
                {
                    rv.def_ItemVariables = formsRepo.GetItemVariableById(rv.itemVariableId);
                }

                output.drawY -= .1;
                for (int col = 0; col < nCols; col++)
                {
                    string s = "ERROR";
                    switch (col)
                    {
                    case 0:
                        s = (row + 1).ToString();
                        break;

                    case 1:
                        s = itm.label;
                        break;

                    case 2:
                        def_ResponseVariables rv = itmResults.def_ResponseVariables.SingleOrDefault(r => r.def_ItemVariables.identifier.EndsWith("_ExMedSupport"));
                        s = ((rv == null) ? "" : rv.rspValue);
                        break;

                    case 3:
                        s = String.Empty;
                        break;
                    }
                    output.DrawText(output.contentFont, output.fontSize, indents[col], output.drawY, s);
                }
                output.drawY -= PdfOutput.itemSpacing * 2.5;
                if (output.drawY < 1)
                {
                    output.appendPageBreak();
                }
            }

            output.drawY -= .1;
            output.DrawText(output.boldFont, output.fontSize, indents[1], output.drawY, "Page Notes:");
            output.drawY -= PdfOutput.itemSpacing * 4;
            if (output.drawY < 1)
            {
                output.appendPageBreak();
            }
        }
示例#22
0
        public static void updateSection3ScoresNoSave(
            IFormsRepository formsRepo,
            def_Forms frm,
            int formResultId)
        {
            if (frm.identifier == "SIS-C")
            {
                return;
            }

            string       sectionIdentifier = "SIS-A 3";
            def_Sections sct = formsRepo.GetSectionByIdentifier(sectionIdentifier);

            if (sct == null)
            {
                throw new Exception("Could not find section with identifier \"" + sectionIdentifier + "\"");
            }
            int rawTotal = 0;

            foreach (def_SectionItems si in sct.def_SectionItems)
            {
                if (si.subSectionId != null)        // skip the Subsections
                {
                    continue;
                }
                def_Items itm = formsRepo.GetItemById(si.itemId);
                // def_ItemResults itmResults = itm.def_ItemResults.SingleOrDefault(ir => ir.formResultId == formResultId);
                def_ItemResults itmResults = formsRepo.GetItemResultByFormResItem(formResultId, itm.itemId);
                if (itmResults == null)
                {
                    continue;
                }
                formsRepo.GetItemResultsResponseVariables(itmResults);
                foreach (def_ResponseVariables rv in itmResults.def_ResponseVariables)
                {
                    rv.def_ItemVariables = formsRepo.GetItemVariableById(rv.itemVariableId);
                }
                for (int i = 0; i < 3; i++)
                {
                    string suffix   = SupportNeedsColumnSuffixes[i];
                    string rspValue = null;

                    def_ResponseVariables rv = itmResults.def_ResponseVariables.SingleOrDefault(trv => trv.def_ItemVariables.identifier.EndsWith(suffix));
                    if (rv != null)
                    {
                        rspValue = rv.rspValue;
                    }

                    if (!String.IsNullOrWhiteSpace(rspValue))
                    {
                        int rawScore;
                        if (Int32.TryParse(rv.rspValue, out rawScore))
                        {
                            rawTotal += rawScore;
                        }
                        else
                        {
                            Debug.WriteLine("* * * Skipping item on updating section 1 scores: " +
                                            "Could not parse integer from response value \"{0}\" for itemVariable \"{1}\". (formResultID {2})",
                                            rv.rspValue, rv.def_ItemVariables.identifier, formResultId);
                        }
                    }
                }
            }

            UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_3_raw_total", rawTotal);
        }
示例#23
0
        public static int UpdateSisScoresNoSave(
            IFormsRepository formsRepo,
            def_Forms frm,
            int formResultId,
            SubscaleCatagory[] subscales,
            Func <int, double, SubscaleCatagory, double> GetSubscaleStandardScore,
            Func <int, double, SubscaleCatagory, double> GetSubscalePercentile)
        {
            DateTime startTime = DateTime.Now;

            updateSection1ScoresNoSave(formsRepo, frm, formResultId);
            if (frm.identifier == "SIS-A")
            {
                updateSection3ScoresNoSave(formsRepo, frm, formResultId);
            }

            double standardScoreTotal = 0, totalRating = 0;
            int    totalRawScoreTotal = 0;
            int    standardScoreCount = 0;

            foreach (SubscaleCatagory cat in subscales)
            {
                def_Sections sct = GetSectionForSubscaleCatagory(frm, cat);
                formsRepo.SortSectionItems(sct);

                int totalRawScore = 0, countRawScore = 0;


                foreach (def_SectionItems si in sct.def_SectionItems)
                {
                    if (si.subSectionId != null)        // skip the Subsections
                    {
                        continue;
                    }
                    def_Items itm = formsRepo.GetItemById(si.itemId);
                    // def_ItemResults itmResults = itm.def_ItemResults.SingleOrDefault(ir => ir.formResultId == formResultId);
                    def_ItemResults itmResults = formsRepo.GetItemResultByFormResItem(formResultId, itm.itemId);
                    if (itmResults == null)
                    {
                        continue;
                    }
                    formsRepo.GetItemResultsResponseVariables(itmResults);
                    foreach (def_ResponseVariables rv in itmResults.def_ResponseVariables)
                    {
                        rv.def_ItemVariables = formsRepo.GetItemVariableById(rv.itemVariableId);
                    }
                    for (int i = 0; i < 3; i++)
                    {
                        string suffix   = SupportNeedsColumnSuffixes[i];
                        string rspValue = null;

                        def_ResponseVariables rv = itmResults.def_ResponseVariables.SingleOrDefault(trv => trv.def_ItemVariables.identifier.EndsWith(suffix));
                        if (rv != null)
                        {
                            rspValue = rv.rspValue;
                        }

                        if (!String.IsNullOrWhiteSpace(rspValue))
                        {
                            int rspInt;
                            if (Int32.TryParse(rspValue, out rspInt))
                            {
                                totalRawScore += rspInt;
                                countRawScore++;
                            }
                            else
                            {
                                Debug.WriteLine("* * * Skipping item on updating scores: " +
                                                "Could not parse integer from response value \"{0}\" for itemVariable \"{1}\". (formResultID {2})",
                                                rv.rspValue, rv.def_ItemVariables.identifier, formResultId);
                                Debug.Print("could not parse integer from response value \"" + rspValue + "\"");
                            }
                        }
                    }
                }

                double rawScoreAvg   = Math.Round((double)totalRawScore / countRawScore, 2);
                double standardScore = GetSubscaleStandardScore(totalRawScore, rawScoreAvg, cat); //totalRawScore / 5;
                double percentile    = GetSubscalePercentile(totalRawScore, rawScoreAvg, cat);    //totalRawScore;

                //save subscale scores to database
                string sctNumberLetter = sct.title.Substring(0, sct.title.IndexOf('.'));
                UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_" + sctNumberLetter + "_raw", totalRawScore);
                UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_" + sctNumberLetter + "_std", standardScore);
                UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_" + sctNumberLetter + "_avg", rawScoreAvg);
                UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_" + sctNumberLetter + "_pct", percentile);

                standardScoreTotal += standardScore;
                totalRawScoreTotal += totalRawScore;
                totalRating        += rawScoreAvg;
                standardScoreCount++;
            }

            //save overall scores to database
            //int compositeIndex = GetSupportNeedsIndex((int)standardScoreTotal);//19;
            //int compositePercentile = GetSupportNeedsPercentile((int)standardScoreTotal);
            UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_total_rawscores_all_SIS_sections", totalRawScoreTotal);
            UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_standard_score_total", standardScoreTotal);
            //saveResponse(formsRepo, formResultId, "scr_support_needs_index", compositeIndex);
            //saveResponse(formsRepo, formResultId, "scr_sni_percentile_rank", compositePercentile);
            UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_total_rating", totalRating);

            TimeSpan duration = DateTime.Now - startTime;

            Debug.WriteLine("* * *  SharedScoring:UpdateSisScores COMPLETED IN " + duration.ToString());
            return((int)standardScoreTotal);
        }
示例#24
0
        /// <summary>
        /// Used by ResultsController.ValidateFormResult()
        ///
        /// Runs the hard-coded validation rules, which can't be encoded into meta-data, for SIS-A and SIS-C forms.
        ///
        /// adds to the model's validation messages for any validation errors or warnings.
        /// </summary>
        /// <param name="sv"></param>
        /// <param name="model"></param>
        /// <returns>true if any validation ERRORS where found, false if nothin (or only wanrings) found</returns>
        public static bool RunOneOffValidation(IFormsRepository formsRepo, def_Forms frm, int entId, List <ValuePair> allResponses, TemplateItems model)
        {
            bool invalid          = false;
            bool isSisCAssessment = frm.identifier.Equals("SIS-C");

            #region if any section 1 "other" text fields are populated, make sure they have a positive numerical response. (and vice-versa)
            string itemsToCheck = isSisCAssessment ?
                                  "A19,A20,A21,B14,B15,B16" // <- check these section 1 items if SIS-C
                : "A19,B13";                                // <- check these if SIS-A
            foreach (string shortIdentifier in itemsToCheck.Split(','))
            {
                string textIdentifier;
                string numIdentifier;

                if (isSisCAssessment)
                {
                    textIdentifier = "SIS-C_Q1" + shortIdentifier + "_Other";
                    numIdentifier  = "SIS-C_Q1" + shortIdentifier + "_Ex" + (shortIdentifier.StartsWith("A") ? "Med" : "Beh") + "Support";
                }
                else // Assumes that if it isn't SIS-C,it must be a SIS-A assessment
                {
                    textIdentifier = "Q1" + shortIdentifier + "_Other";
                    numIdentifier  = "Q1" + shortIdentifier + "_Ex" + (shortIdentifier.StartsWith("A") ? "Med" : "Beh") + "Support";
                }

                ValuePair textVp = allResponses.SingleOrDefault(vpt => vpt.identifier == textIdentifier); //formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, textIdentifier);
                ValuePair numVp  = allResponses.SingleOrDefault(vpt => vpt.identifier == numIdentifier);  //def_ResponseVariables numRv = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, numIdentifier);

                bool textBlank = textVp == null || String.IsNullOrWhiteSpace(textVp.rspValue);            //isNullEmptyOrBlank(textRv);
                bool numBlank  = numVp == null || String.IsNullOrWhiteSpace(numVp.rspValue);              //isNullEmptyOrBlank(numRv);

                if (numBlank)
                {
                    invalid = true;
                    model.validationMessages.Add("Section 1: \"other\" item " + shortIdentifier + " has no numerical response");
                }
                else if ((Int32.Parse(numVp.rspValue) > 0) && textBlank)
                {
                    invalid = true;
                    model.validationMessages.Add("Section 1: \"other\" item " + shortIdentifier + " has positive numerical response, but no text explaination");
                }
            }
            #endregion

            #region check interviewee age / interview date
            ValuePair vpBirthDate = allResponses.SingleOrDefault(vpt => vpt.identifier == "sis_cl_dob_dt");
            ValuePair vpIntDate   = allResponses.SingleOrDefault(vpt => vpt.identifier == "sis_completed_dt");
            DateTime  dtDob;
            DateTime  dtInt;
            //def_ResponseVariables rvBirthDate = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "sis_cl_dob_dt");
            //def_ResponseVariables rvIntDate = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "sis_completed_dt");
            if (vpBirthDate != null && DateTime.TryParse(vpBirthDate.rspValue, out dtDob) &&
                vpIntDate != null && DateTime.TryParse(vpIntDate.rspValue, out dtInt))
            {
                int age = dtInt.Year - dtDob.Year;
                if (dtInt.Month < dtDob.Month)
                {
                    age--;
                }
                if ((dtInt.Month == dtDob.Month) && (dtInt.Day < dtDob.Day))
                {
                    age--;
                }

                //for SIS-C assessments, age must fall between 5 and 16 inclusive, and interview date must be 2009 at earliest
                if (isSisCAssessment)
                {
                    if (age < 5)
                    {
                        invalid = true;
                        model.validationMessages.Add("Profile: interviewee age is " + age + " years, should be at least 5 years");
                    }
                    if (age > 16)
                    {
                        invalid = true;
                        model.validationMessages.Add("Profile: interviewee age is " + age + " years, should be at most 16 years");
                    }
                    if (dtInt.Year < 2009)
                    {
                        invalid = true;
                        model.validationMessages.Add("Profile: interview date is in the year " + dtInt.Year + ", should be 2009 at the earliest");
                    }
                }

                //for SIS-A assessments, age must be at least 15, and interview date must be 2004 at earliest
                else
                {
                    if (dtInt.Year < 2004)
                    {
                        invalid = true;
                        model.validationMessages.Add("Profile: interview date is in the year " + dtInt.Year + ", should be 2004 at the earliest");
                    }
                    if (age < 15)
                    {
                        invalid = true;
                        model.validationMessages.Add("Profile: interviewee age is " + age + " years, should be at least 15 years");
                    }
                }
            }
            #endregion

            #region if "SEVERE MEDICAL RISK" under supplementl questions is marked "yes"...

            ValuePair vpSup = allResponses.SingleOrDefault(vpt => vpt.identifier == "Q4A1v1");
            //def_ResponseVariables rvSup = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "Q4A1v1");
            if (vpSup != null && vpSup.rspValue != null && (vpSup.rspValue.Equals("1") || vpSup.rspValue.ToLower().Equals("true")))
            {
                int rspInt;

                //make sure at least one of the items under section 1A has a rsponse value "2"
                bool      anyTwosInOtherItems = false;
                ValuePair vp;

                for (int i = 1; i <= 21; i++)
                {
                    if (isSisCAssessment) // Accomodating for different identifiers (SIS-A vs SIS-C)
                    {
                        vp = allResponses.SingleOrDefault(vpt => vpt.identifier == "SIS-C_Q1A" + i + "_ExMedSupport");
                    }
                    else
                    {
                        vp = allResponses.SingleOrDefault(vpt => vpt.identifier == "Q1A" + i + "_ExMedSupport");
                    }
                    //def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "Q1A" + i + "_ExMedSupport");
                    if ((vp != null) && Int32.TryParse(vp.rspValue, out rspInt) && (rspInt == 2))
                    {
                        anyTwosInOtherItems = true;
                        break;
                    }
                }

                ValuePair vpExMedSup = allResponses.SingleOrDefault(vpt => vpt.identifier == "Q1A_ed_ExMedSupport");
                //def_ResponseVariables edRv = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "Q1A_ed_ExMedSupport");

                if ((vpExMedSup != null) && Int32.TryParse(vpExMedSup.rspValue, out rspInt) && (rspInt == 2))
                {
                    anyTwosInOtherItems = true;
                }

                if (!anyTwosInOtherItems)
                {
                    invalid = true;
                    model.validationMessages.Add("Marked \"yes\" under SEVERE MEDICAL RISK in supplemental questions, but no scores of 2 in section 1A");
                }
            }
            #endregion

            #region Custom validation for supplemental questions 2-4, depending on section 1B responses
            Dictionary <string, string[]> specs;
            if (isSisCAssessment)
            {
                specs = new Dictionary <string, string[]>
                {
                    { "Q4A2v1", new string[] {
                          //if Q4A2v1 has response "yes", at least one
                          //of these item variables must have response "2"
                          "SIS-C_Q1B2", //question 2 in SIS-C
                          "SIS-C_Q1B3", //question 3 in SIS-C
                          "SIS-C_Q1B8", //question 8 in SIS-C
                      } },
                    { "Q4A3v1", new string[] {
                          "SIS-C_Q1B2", //question 2 in SIS-C
                          "SIS-C_Q1B3", //question 3 in SIS-C
                          "SIS-C_Q1B8", //question 8 in SIS-C
                      } },
                    { "Q4A4v1", new string[] {
                          "SIS-C_Q1B5", //question 5 in SIS-C
                          "SIS-C_Q1B6", //question 6 in SIS-C
                          "SIS-C_Q1B7", //question 7 in SIS-C
                      } },
                };
            }
            else
            {
                specs = new Dictionary <string, string[]>
                {
                    { "Q4A2v1", new string[] {
                          //if Q4A2v1 has response "yes", at least one
                          //of these item variables must have response "2"
                          "Q1B2", //question 2 in SIS-C
                          "Q1B3", //question 3 in SIS-C
                          "Q1B9", //question 8 in SIS-C
                      } },
                    { "Q4A3v1", new string[] {
                          "Q1B2", //question 2 in SIS-C
                          "Q1B3", //question 3 in SIS-C
                          "Q1B9", //question 8 in SIS-C
                      } },
                    { "Q4A4v1", new string[] {
                          "Q1B5", //question 5 in SIS-C
                          "Q1B6", //question 6 in SIS-C
                          "Q1B7", //question 7 in SIS-C
                      } },
                };
            }
            foreach (string supIvIdent in specs.Keys)
            {
                def_ItemVariables supIv = formsRepo.GetItemVariableByIdentifier(supIvIdent);
                if (supIv == null)
                {
                    throw new Exception("Could not find item variable with identifier \"" + supIvIdent + "\"");
                }
                def_Items supItm   = formsRepo.GetItemById(supIv.itemId);
                string    supIndex = supIvIdent.Substring(3, 1);

                //rvSup = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, supIv.itemVariableId);
                vpSup = allResponses.SingleOrDefault(vpt => vpt.identifier == supIv.identifier);

                if (vpSup != null && vpSup.rspValue != null && (vpSup.rspValue.Equals("1") || vpSup.rspValue.ToLower().Equals("true")))
                {
                    List <string> checkedItemLabels   = new List <string>();
                    bool          anyTwosInOtherItems = false;
                    foreach (string ivPrefix in specs[supIvIdent])
                    {
                        def_ItemVariables iv  = formsRepo.GetItemVariableByIdentifier(ivPrefix + "_ExBehSupport");
                        def_Items         itm = formsRepo.GetItemById(iv.itemId);
                        checkedItemLabels.Add("\"" + itm.label + "\"");

                        ValuePair vp = allResponses.SingleOrDefault(vpt => vpt.identifier == iv.identifier);
                        //def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, iv.itemVariableId);
                        if ((vp != null) && (vp.rspValue != null) && (vp.rspValue == "2"))
                        {
                            anyTwosInOtherItems = true;
                            break;
                        }
                    }

                    if (!anyTwosInOtherItems)
                    {
                        invalid = true;
                        model.validationMessages.Add("Marked \"yes\" under supplemental question " + supIndex + ", but no scores of 2 in any of these section 1B items: "
                                                     + String.Join(", ", checkedItemLabels));
                    }
                }
            }
            #endregion

            #region Require notes for Section 1A or 1B where the item is flagged as Important For/To
            foreach (def_FormParts fp in frm.def_FormParts)
            {
                //This is currently hardcodoed for Enterprise 44: Virginia.  This should probably be added to a lookup Table so the feature can be switched on/off for any enterprise.
                //if (fr.EnterpriseID == 44)
                //{
                if (fp.def_Parts.identifier.StartsWith("Section 1"))
                {
                    foreach (def_PartSections ps in fp.def_Parts.def_PartSections)
                    {
                        foreach (def_SectionItems si in ps.def_Sections.def_SectionItems)
                        {
                            // Configured in def_SectionItemsEnt, some Enterprises require validation on these sections.  Currently checks for a 1 for Enterprise 44.
                            // Empty lists should return false.
                            if (si.def_SectionItemsEnt.Any(r => r.validation == 1 && r.EnterpriseID == entId) && si.subSectionId != null)
                            {
                                foreach (def_SectionItems subsi in si.def_SubSections.def_Sections.def_SectionItems)
                                {
                                    List <def_ItemVariables> ivImportant = subsi.def_Items.def_ItemVariables.Where(iv => iv.identifier.EndsWith("_ImportantFor") || iv.identifier.EndsWith("_ImportantTo")).ToList();
                                    if (ivImportant.Count() == 0)
                                    {
                                        Debug.WriteLine("ResultsController:ValidateFormResult method  * * * Could not find Important For/To itemVariable for item \"" + subsi.def_Items.identifier + "\"");
                                    }
                                    else
                                    {
                                        List <bool> rvImpBools = new List <bool>();
                                        foreach (def_ItemVariables iv in ivImportant)
                                        {
                                            ValuePair vp = allResponses.SingleOrDefault(vpt => vpt.identifier == iv.identifier);
                                            //def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, iv.itemVariableId);
                                            rvImpBools.Add((vp != null && vp.rspValue != null && vp.rspValue.Equals("1")));
                                        }
                                        // Test true if any value is true.  Empty lists should return false.
                                        if (rvImpBools.Any(r => r))
                                        {
                                            List <def_ItemVariables> ivNote = subsi.def_Items.def_ItemVariables.Where(iv => iv.identifier.EndsWith("_Notes")).ToList();
                                            foreach (def_ItemVariables iv in ivNote)
                                            {
                                                ValuePair vp = allResponses.SingleOrDefault(vpt => vpt.identifier == iv.identifier);
                                                //def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, iv.itemVariableId);
                                                if (vp == null || String.IsNullOrEmpty(vp.rspValue))
                                                {
                                                    invalid = true;
                                                    model.validationMessages.Add(subsi.def_Sections.title + ", " + subsi.def_Items.label +
                                                                                 ": Notes are required for items flagged as Important.");
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //}
            }
            #endregion

            #region For all supplemental questions, require sub-questions if top-level response is "Yes" (Bug 13132, #2 in description)

            //iterate through all the sub-sections in the Supplemental Questions section
            def_Sections sqSection = formsRepo.GetSectionByIdentifier("SQ");
            formsRepo.SortSectionItems(sqSection);
            foreach (def_SectionItems si in sqSection.def_SectionItems.Where(si => si.subSectionId != null))
            {
                bool         validationRequired = false;
                def_Sections subSct             = formsRepo.GetSubSectionById(si.subSectionId);

                //exclude "S4aPageNotes" subsection
                if (subSct.identifier == "S4aPageNotes")
                {
                    continue;
                }

                //iterate through all the sectionitems in this subsection, in order
                formsRepo.SortSectionItems(subSct);
                foreach (def_SectionItems subSi in subSct.def_SectionItems)
                {
                    //if the sectionitem points to an item, that item must represent a top-level yes.no Supplemental Question
                    //and it should have exactly one itemVariable, with basetype 1
                    if (subSi.itemId > 1)
                    {
                        def_ItemVariables ivTopQuestion = subSi.def_Items.def_ItemVariables.FirstOrDefault();

                        ValuePair vpTopQuestion = allResponses.SingleOrDefault(vpt => vpt.identifier == ivTopQuestion.identifier);
                        //def_ResponseVariables rvTopQuestion = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, ivTopQuestion.itemVariableId);

                        //check if the response is "yes" for this top-level yes/no
                        if (vpTopQuestion != null && !String.IsNullOrWhiteSpace(vpTopQuestion.rspValue) && vpTopQuestion.rspValue == "1")
                        {
                            validationRequired = true;
                        }
                    }

                    //if the sectionitem points to a sub-subsection, that sub-subsection contains lower-level items
                    //that should be checked only if the previous top-level question was answered "yes"
                    else if (subSi.subSectionId.HasValue && validationRequired)
                    {
                        def_Sections subSubSct = formsRepo.GetSubSectionById(subSi.subSectionId);

                        //iterate through the item variables in this sub-subsection and require responses for some of them,
                        //if their identifier ends with a, b, c, d, or d2
                        formsRepo.SortSectionItems(subSubSct);
                        foreach (def_SectionItems subSubSi in subSubSct.def_SectionItems.Where(subSubSi => subSubSi.subSectionId == null))
                        {
                            foreach (def_ItemVariables bottomLevelIv in subSubSi.def_Items.def_ItemVariables)
                            {
                                if ("a,b,c,d,d2".Split(',').Where(suffix => bottomLevelIv.identifier.EndsWith(suffix)).Any())
                                {
                                    ValuePair vp = allResponses.SingleOrDefault(vpt => vpt.identifier == bottomLevelIv.identifier);
                                    //def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, bottomLevelIv.itemVariableId);
                                    if (vp == null || String.IsNullOrWhiteSpace(vp.rspValue) ||
                                        (bottomLevelIv.baseTypeId == 1 && vp.rspValue.ToLower() == "unanswered"))
                                    //^ ^ ^ OT 3-24-16 consider "unanswered" the same as blank for yes/nos ("unanswered" responses may exist in DB as a result of a bug: Bug 13132, #1 in description)
                                    {
                                        invalid = true;
                                        model.validationMessages.Add(sqSection.title + ": since you marked \"yes\" under \"" + subSct.title + "\", you must provide a response for \"" + subSubSi.def_Items.label + "\"");
                                    }
                                }
                            }
                        }

                        //reset the flag so the following subsection is not validated unless we hit another top-level "yes"
                        validationRequired = false;
                    }
                }
            }

            #endregion

            return(invalid);
        }
        protected void PrintGenericSection(
            PdfOutput output,
            def_Sections section,
            int indentLevel,
            Dictionary <string, string> responsesByItemVariable)
        {
            if (output.drawY < 1.5)
            {
                output.appendPageBreak();
            }

            if (indentLevel < 2)
            {
                output.appendSectionBreak();
            }

            //print section title + identifier
            double sectionLabelIndent = .5 + labelIndent * (indentLevel - 1);
            double itemLabelIndent    = labelIndent * indentLevel;
            double responseIndent     = valueIndent + labelIndent * (indentLevel - 1);

            output.appendWrappedText(buildSectionHeaderText(section),
                                     sectionLabelIndent, 8 - sectionLabelIndent, output.sectionHeaderFontSize);
            output.drawY -= .1;

            List <def_Items> ignoreList = new List <def_Items>();
            int singleBoolCount         = 0;

            formsRepo.GetSectionItems(section);

            //add items wtihout responses to the ignore list, count the number of single-boolean items
            Debug.WriteLine("FormResultPdfReport.PrintGenericSection section: " + section.identifier);
            foreach (def_SectionItems si in section.def_SectionItems.Where(si => !si.subSectionId.HasValue))
            {
                def_Items itm = formsRepo.GetItemById(si.itemId);
                Debug.WriteLine("   itm: " + itm.identifier);
                ICollection <def_ItemVariables> ivs = formsRepo.GetItemVariablesByItemId(itm.itemId);
                if (ivs.Any(iv => !responsesByItemVariable.ContainsKey(iv.identifier) || String.IsNullOrWhiteSpace(responsesByItemVariable[iv.identifier])))
                {
                    ignoreList.Add(itm);
                }

                if ((ivs.Count == 1) && (ivs.First().baseTypeId == 1))
                {
                    singleBoolCount++;
                }
            }

            //if there at least 4 boolean items in this section, ignore all labeled items with single negative boolean responses
            if (singleBoolCount >= 4)
            {
                foreach (def_SectionItems si in section.def_SectionItems.Where(si => !si.subSectionId.HasValue))
                {
                    def_Items itm = formsRepo.GetItemById(si.itemId);
                    ICollection <def_ItemVariables> ivs = formsRepo.GetItemVariablesByItemId(itm.itemId);
                    if (ignoreList.Contains(itm) || itm.label.Trim().Length == 0)
                    {
                        continue;
                    }

                    if (ivs.Count == 1)
                    {
                        def_ItemVariables iv = ivs.First();
                        if ((iv.baseTypeId == 1) && (!responsesByItemVariable.ContainsKey(iv.identifier) || responsesByItemVariable[iv.identifier].Equals("No")))
                        {
                            ignoreList.Add(itm);
                        }
                    }
                }
            }

            //iterate through section items, printing to pdf output
            foreach (def_SectionItems si in section.def_SectionItems)
            {
                if (si.subSectionId.HasValue)
                {
                    PrintGenericSection(output, formsRepo.GetSubSectionById(si.subSectionId.Value), indentLevel + 1);
                }
                else
                {
                    def_Items itm = formsRepo.GetItemById(si.itemId);
                    if (ignoreList.Where(x => x.itemId == itm.itemId).Any())
                    {
                        continue;
                    }

                    formsRepo.GetEnterpriseItems(new def_Items[] { itm }.ToList(), formResults.EnterpriseID.Value);
                    appendItemLabelAndResponses(itm, itemLabelIndent, responseIndent, responsesByItemVariable);
                }
            }
        }
示例#26
0
        protected void PrintProfilePage(PdfOutput output, int ageInYears)
        {
            List <def_Parts> prts = formsRepo.GetFormParts(form);
            def_Parts        part = prts[0];

            PdfOutput secondCol = output.getSecondColumnBranch();

            output.drawY -= .3;
            if (SessionHelper.LoginStatus.EnterpriseID == 44)
            {
                buildSubheaderWithResults(output, part, "Person Being Assessed",
                                          "itmNmeLst", "nmeFrst", "nmeMdl", "sis_cl_lang_item", "itmGender", "adrlne", "adrcty",
                                          "sis_cl_st1", "sis_cl_zip1", "sis_cl_phone_item",
                                          "sis_cl_dob_dt1", new LabelValuePair("Age", ageInYears.ToString()), "trkNum", new LabelValuePair("Medicaid Number", MaskMedicaidNumber(GetSingleResponse(formsRepo.GetItemByIdentifier("sis_cl_medicaidNum1")))),
                                          new LabelValuePair("SSN", MaskSSN(GetSingleResponse(formsRepo.GetItemByIdentifier("itmSsn")))));
            }
            else
            {
                buildSubheaderWithResults(output, part, "Person Being Assessed",
                                          "itmNmeLst", "nmeFrst", "nmeMdl", "sis_cl_lang_item", "itmGender", "adrlne", "adrcty",
                                          "sis_cl_st1", "sis_cl_zip1", "sis_cl_phone_item",
                                          "sis_cl_dob_dt1", new LabelValuePair("Age", ageInYears.ToString()), "trkNum", "sis_cl_medicaidNum1",
                                          new LabelValuePair("SSN", MaskSSN(GetSingleResponse(formsRepo.GetItemByIdentifier("itmSsn")))));
            }

            buildSubheaderWithResults(output, part, "Assessment Data", "intvwDate", "isp_begin_date_item", new LabelValuePair("SIS ID", formResults.formResultId.ToString()));
            secondCol.drawY -= .6;
            buildSubheaderWithResults(secondCol, part, "Interviewer Data",
                                      "sis_int_full_nm1", "sis_int_agency_nm1", "sis_int_addr_line11", "sis_int_city1",
                                      "sis_int_st1", "sis_int_zip", "sis_int_position_cd1", "sis_int_phone_num1",
                                      "sis_int_phone_num_ext1", "sis_int_email1");
            output.drawY -= .3;
            output.appendSectionBreak();
            output.appendSubHeader("Support Providers", "Essential supports for this individual are being provided by the following");
            buildTableWithItems(output, part, 4,
                                "sis_sup1_name_item", "sis_sup1_reln_item", "sis_sup1_phone_item", "sis_sup1_ext_item",
                                "sis_sup2_name_item", "sis_sup2_reln_item", "sis_sup2_phone_item", "sis_sup2_ext_item",
                                "sis_sup3_name_item", "sis_sup3_reln_item", "sis_sup3_phone_item", "sis_sup3_ext_item",
                                "sis_sup4_name_item", "sis_sup4_reln_item", "sis_sup4_phone_item", "sis_sup4_ext_item",
                                "sis_sup5_name_item", "sis_sup5_reln_item", "sis_sup5_phone_item", "sis_sup5_ext_item",
                                "sis_sup6_name_item", "sis_sup6_reln_item", "sis_sup6_phone_item", "sis_sup6_ext_item");
            output.drawY -= .3;
            output.appendSectionBreak();
            output.appendSubHeader("Respondent Data", "Information for the SIS ratings was provided by the following respondents:");
            //buildTableWithItems(output, part, 5,
            //    new string[] { "First Name", "Last Name", "Agency", "Email", "Language", },
            //    "sis_res1_firstn_item", "sis_res1_lastn_item", "sis_res1_agen_item", "sis_res1_email_item", "sis_res1_lang_item",
            //    "sis_res2_firstn_item", "sis_res2_lastn_item", "sis_res2_agen_item", "sis_res2_email_item", "sis_res2_lang_item",
            //    "sis_res3_firstn_item", "sis_res3_lastn_item", "sis_res3_agen_item", "sis_res3_email_item", "sis_res3_lang_item",
            //    "sis_res4_firstn_item", "sis_res4_lastn_item", "sis_res4_agen_item", "sis_res4_email_item", "sis_res4_lang_item",
            //    "sis_res5_firstn_item", "sis_res5_lastn_item", "sis_res5_agen_item", "sis_res5_email_item", "sis_res5_lang_item",
            //    "sis_res6_firstn_item", "sis_res6_lastn_item", "sis_res6_agen_item", "sis_res6_email_item", "sis_res6_lang_item",
            //    "sis_res7_firstn_item", "sis_res7_lastn_item", "sis_res7_agen_item", "sis_res7_email_item", "sis_res7_lang_item",
            //    "sis_res8_firstn_item", "sis_res8_lastn_item", "sis_res8_agen_item", "sis_res8_email_item", "sis_res8_lang_item",
            //    "sis_res9_firstn_item", "sis_res9_lastn_item", "sis_res9_agen_item", "sis_res9_email_item", "sis_res9_lang_item",
            //    "sis_res10_firstn_item", "sis_res10_lastn_item", "sis_res10_agen_item", "sis_res10_email_item", "sis_res10_lang_item");

            buildTableWithItems(output, part, 6,
                                new string[] { "First Name", "Last Name", "Relationship", "Agency", "Email", "Language", },
                                "sis_res1_firstn_item", "sis_res1_lastn_item", "sis_res1_reln_item", "sis_res1_agen_item", "sis_res1_email_item", "sis_res1_lang_item",
                                "sis_res2_firstn_item", "sis_res2_lastn_item", "sis_res2_reln_item", "sis_res2_agen_item", "sis_res2_email_item", "sis_res2_lang_item",
                                "sis_res3_firstn_item", "sis_res3_lastn_item", "sis_res3_reln_item", "sis_res3_agen_item", "sis_res3_email_item", "sis_res3_lang_item",
                                "sis_res4_firstn_item", "sis_res4_lastn_item", "sis_res4_reln_item", "sis_res4_agen_item", "sis_res4_email_item", "sis_res4_lang_item",
                                "sis_res5_firstn_item", "sis_res5_lastn_item", "sis_res5_reln_item", "sis_res5_agen_item", "sis_res5_email_item", "sis_res5_lang_item",
                                "sis_res6_firstn_item", "sis_res6_lastn_item", "sis_res6_reln_item", "sis_res6_agen_item", "sis_res6_email_item", "sis_res6_lang_item",
                                "sis_res7_firstn_item", "sis_res7_lastn_item", "sis_res7_reln_item", "sis_res7_agen_item", "sis_res7_email_item", "sis_res7_lang_item",
                                "sis_res8_firstn_item", "sis_res8_lastn_item", "sis_res8_reln_item", "sis_res8_agen_item", "sis_res8_email_item", "sis_res8_lang_item",
                                "sis_res9_firstn_item", "sis_res9_lastn_item", "sis_res9_reln_item", "sis_res9_agen_item", "sis_res9_email_item", "sis_res9_lang_item",
                                "sis_res10_firstn_item", "sis_res10_lastn_item", "sis_res10_reln_item", "sis_res10_agen_item", "sis_res10_email_item", "sis_res10_lang_item");


            output.drawY -= .3;

            output.appendSectionBreak();
            buildSubheaderWithResults(output, part, "Person who entered this information",
                                      "sis_entry_firstn_item", "sis_entry_lastn_item");

            if (options[OptionKey.includeComments])
            {
                output.appendSectionBreak();

                def_Items itm = formsRepo.GetItemByIdentifier("SIS-Prof1_PageNotes_item");
                if (itm == null)
                {
                    throw new Exception("could not find item with identifier " + "SIS-Prof1_PageNotes_item");
                }
                string rv = GetSingleResponse(itm);

                output.appendSubHeaderOnNewPageIfNecessary("Other Pertinent Information", rv);

                //BuildItemResults(output, part, "SIS-Prof1_PageNotes_item");
                output.drawY -= .3;
            }

            //output.appendWrappedText("Introduction to the SIS Report:", .36, 7.9, output.boldFont);
        }
示例#27
0
        /// <summary>
        /// Creates the the Report Chart
        /// </summary>
        /// <param name="chartFileName">File name to save chart to</param>
        /// <returns>output path if chart was successfully created, null otherwise</returns>
        private string CreateReportChart(string chartFileName, string[] xLabels, double[] percentiles, double supportIndex, bool relSIS = false)
        {
            string outpath     = null;
            Chart  crtSection1 = new Chart();

            Bitmap img;

            def_Items itm            = formsRepo.GetItemByIdentifier("trkNum");
            string    trackingNumber = GetSingleResponse(itm);

            try
            {
                // set overlap footer on to make chart the same size
                // if there is a valid license or not
                crtSection1.OverlapFooter = true;
                crtSection1.ChartArea.XAxis.Label.Text = "Life Activity Subscale"; // set the xaxis title
                crtSection1.ChartArea.YAxis.Label.Text = "Percentile";             // set the yaxis title
                crtSection1.TempDirectory = System.IO.Path.GetTempPath();          //System.Configuration.ConfigurationManager.AppSettings["ChartPath"];         // set the temp directory
                crtSection1.Debug         = true;                                  // do not show debug info on chart
                crtSection1.FileName      = chartFileName;                         // set the file name

                if (relSIS)
                {
                    crtSection1.Title = "Activity Subscale and Composite Score Profile";
                    crtSection1.Size  = "600x400";                                                 // set the chart size
                }
                else
                {
                    crtSection1.Title = "Tracking Number: " + trackingNumber; //+
                    //ds.Tables["ReportData"].Rows[0]["sis_track_num"].ToString();
                    crtSection1.Size = "575x442";                             // set the chart size
                }

                // set the chart title
                crtSection1.DefaultSeries.DefaultElement.ShowValue = true;
                crtSection1.Mentor = false;
                crtSection1.Use3D  = false;
                crtSection1.DefaultSeries.DefaultElement.Transparency = 15;
                crtSection1.TitleBox.Visible                 = true;                           // show the title box
                crtSection1.LegendBox.Visible                = true;                           // show the legend
                crtSection1.LegendBox.Orientation            = dotnetCHARTING.Orientation.Top; // show the legend at the top
                crtSection1.YAxis.Interval                   = 10;                             // set the chart inverval
                crtSection1.YAxis.Minimum                    = 0;                              // set the min value the chart shows
                crtSection1.YAxis.Maximum                    = 100;                            // set the max value the chart shows
                crtSection1.LegendBox.Background.Color       = Color.FromArgb(240, 234, 202);  // set the legend box color
                crtSection1.LegendBox.Background.GlassEffect = true;
                crtSection1.ChartArea.Background             = new Background(Color.Ivory);    // set the chart background color
                crtSection1.ImageFormat = ImageFormat.Png;
                string bgImagePath = String.Format("/Content/Images/SuppNeedOverlay.jpg", crtSection1.TempDirectory);
                crtSection1.ChartArea.Background = new Background(bgImagePath, BackgroundMode.ImageTile);
                // add the values to the chart
                Series sr = new Series();
                sr      = new Series();
                sr.Name = "Activity Subscale Percentile";
                sr.Type = SeriesType.Bar;

                for (int i = 0; i < xLabels.Length; i++)
                {
                    int headerColorIndex = i % (section2HeaderColors.Length / 3);
                    sr.Elements.Add(new Element(xLabels[i], percentiles[i])
                    {
                        Color = Color.FromArgb(
                            section2HeaderColors[headerColorIndex, 0],
                            section2HeaderColors[headerColorIndex, 1],
                            section2HeaderColors[headerColorIndex, 2])
                    });
                }
                sr.DefaultElement.Color = Color.FromArgb(190, 65, 30);
                sr.LegendEntry.Value    = "";
                crtSection1.SeriesCollection.Add(sr);

                sr      = new Series();
                sr.Name = "SIS Support Index Percentile";
                sr.Type = SeriesType.Bar;
                sr.Elements.Add(new Element("SIS Support Index", supportIndex));
                sr.DefaultElement.Color = Color.FromArgb(215, 195, 93);

                // bind the data to the chart
                crtSection1.SeriesCollection.Add(sr);

                // save the chart image
                img = crtSection1.GetChartBitmap();
                crtSection1.FileManager.SaveImage(img);
            }
            finally
            {
                outpath = crtSection1.TempDirectory + crtSection1.FileName + ".png";
                // clean up
                crtSection1.Dispose();
                crtSection1 = null;
            }

            return(outpath);
        }
示例#28
0
        public ActionResult Validate(FormCollection frmCllctn, TemplateItems ti)
        {
            //save response from formCollection into the DB
            ResultsController rc = new ResultsController(formsRepo);

            rc.ControllerContext = ControllerContext;
            rc.Save(frmCllctn, ti);

            int formResultId = SessionHelper.SessionForm.formResultId;

            SessionHelper.SessionForm.sectionId = -1;

            //Run generic validation
            AdapValidationErrorsModel model = new AdapValidationErrorsModel();

            model.navMenuModel       = AJBoggs.Adap.Templates.TemplateMenus.getAdapNavMenuModel(SessionHelper.SessionForm, formsRepo);
            model.validationMessages = new List <string>();
            model.missingItemVariablesBySectionByPart = new Dictionary <int, Dictionary <int, List <string> > >();
            def_Forms        frm          = formsRepo.GetFormById(SessionHelper.SessionForm.formId);
            List <ValuePair> allResponses = CommonExport.GetDataByFormResultId(formResultId);
            SharedValidation sv           = new SharedValidation(allResponses);
            bool             invalid      = sv.DoGenericValidation(formsRepo, model, frm);

            //transfer generic validation results to an ADAP-specific model
            model.titlesOfMissingSubsectionsBySectionByPart = new Dictionary <int, Dictionary <int, List <string> > >();
            foreach (int prtId in model.missingItemVariablesBySectionByPart.Keys)
            {
                model.titlesOfMissingSubsectionsBySectionByPart.Add(prtId, new Dictionary <int, List <string> >());
                foreach (int sctId in model.missingItemVariablesBySectionByPart[prtId].Keys)
                {
                    def_Sections sct = formsRepo.GetSectionById(sctId);
                    formsRepo.SortSectionItems(sct);
                    List <int> ssSectionIds = new List <int>();
                    foreach (def_SectionItems si in sct.def_SectionItems.Where(si => si.subSectionId.HasValue))
                    {
                        ssSectionIds.Add(formsRepo.GetSubSectionById(si.subSectionId.Value).sectionId);
                    }

                    model.titlesOfMissingSubsectionsBySectionByPart[prtId].Add(sctId, new List <string>());
                    foreach (string itemVariableIdent in model.missingItemVariablesBySectionByPart[prtId][sctId])
                    {
                        //for each item variable identifier returned by generic validation,
                        //lookup the corresponding subsection's title for display on the ADAP "validation errors" screen
                        def_ItemVariables iv  = formsRepo.GetItemVariableByIdentifier(itemVariableIdent);
                        def_Items         itm = iv == null ? null : iv.def_Items;
                        def_SectionItems  si  = itm == null ? null : formsRepo.getSectionItemsForItem(itm).Where(sit => ssSectionIds.Contains(sit.sectionId)).FirstOrDefault();
                        def_Sections      sub = si == null ? null : si.def_Sections;
                        if (sub != null && !model.titlesOfMissingSubsectionsBySectionByPart[prtId][sctId].Contains(sub.title))
                        {
                            model.titlesOfMissingSubsectionsBySectionByPart[prtId][sctId].Add(sub.title);
                        }
                    }
                }
            }

            //run CO-ADAP one-off validation
            if (AdapCOOneOffValidation.RunOneOffValidation(sv, model))
            {
                invalid = true;
            }

            //return the validation errors screen if any errors were found
            //model.validationMessages could have some warnings even if no errors were found, in which case "invalid" would be false here
            if (invalid)
            {
                return(View("~/Views/COADAP/ValidationErrors.cshtml", model));
            }

            //if no problems were found, or if warnings were found but no errors, return the next section in the application
            if (model.validationMessages.Count == 0)
            {
                model.validationMessages.Add("No errors were found");
            }
            int sectionId = Convert.ToInt16(frmCllctn["navSectionId"]);

            return(rc.Template(sectionId, model.validationMessages));
        }
示例#29
0
        protected void PrintSupplementalQuestions(PdfOutput output)
        {
            def_Parts part = formsRepo.GetPartByFormAndIdentifier(form, "Supplemental Questions");

            AppendPartHeader(output, part.identifier);

            def_Sections topSct = formsRepo.GetSectionsInPart(part).FirstOrDefault();

            if (topSct == null)
            {
                throw new Exception("not sections found in part with partId " + part.partId);
            }

            List <def_Sections> sectionList = new List <def_Sections>();

            formsRepo.SortSectionItems(topSct);
            foreach (def_SectionItems sctnItm in topSct.def_SectionItems)
            {
                if (sctnItm.display == false)
                {
                    continue;
                }
                def_Sections subSctns = formsRepo.GetSubSectionById(sctnItm.subSectionId);// sctnItm.def_SubSections.def_Sections;
                sectionList.Add(subSctns);
            }

            int  grayCount          = 0;
            bool showWhiteQuestions = true;

            foreach (def_Sections sct in sectionList)
            {
                formsRepo.SortSectionItems(sct);
                foreach (def_SectionItems si in sct.def_SectionItems)
                {
                    if (si.display == false)
                    {
                        continue;
                    }

                    //if this is a "gray" question... (high-level questions pertaining to a set of "white" questions)
                    if (si.subSectionId == null)
                    {
                        grayCount++;
                        if (grayCount > 1)
                        {
                            output.drawY -= .5;
                        }
                        def_Items         itm = si.def_Items;
                        def_ItemVariables iv  = itm.def_ItemVariables.FirstOrDefault();
                        if (iv == null)
                        {
                            throw new Exception("no item variable for question with itemId " + si.itemId);
                        }
                        def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(formResultId, iv.itemVariableId);//iv.def_ResponseVariables.FirstOrDefault();
                        if (rv == null)
                        {
                            continue;
                        }

                        //don't show the white questions if the response value is false
                        if (iv.baseTypeId == 1 && (rv.rspValue.ToLower().Equals("false") || rv.rspValue.Equals("0")))
                        {
                            showWhiteQuestions = false;
                        }
                        else
                        {
                            showWhiteQuestions = true;
                        }

                        if (output.drawY < .5)
                        {
                            output.appendPageBreak();
                        }

                        if (!itm.label.Equals("Page Notes"))
                        {
                            double y = output.drawY;
                            output.appendWrappedText(grayCount + ".", .8, 6, output.boldFont);
                            output.drawY = y;
                        }
                        output.appendWrappedText(itm.label, 1, 7, output.boldFont);
                        output.appendWrappedText(GetSupplementalResponseText(iv, rv), 1.5, 6, output.boldFont);
                        output.drawY -= PdfOutput.itemSpacing;
                    }

                    // if this is a "white" question-set
                    else
                    {
                        if (!showWhiteQuestions)
                        {
                            continue;
                        }
                        foreach (def_SectionItems ssi in si.def_SubSections.def_Sections.def_SectionItems)
                        {
                            def_Items itm = ssi.def_Items;
                            if (itm == null)
                            {
                                throw new Exception("no item for setionItems with sectionItemId " + ssi.sectionItemId);
                            }
                            def_ItemVariables iv = itm.def_ItemVariables.FirstOrDefault();
                            if (iv == null)
                            {
                                throw new Exception("no item variable for item with itemId " + itm.itemId);
                            }
                            def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(formResultId, iv.itemVariableId);

                            try
                            {
                                output.appendWrappedText(itm.label, 1.1, 6);
                            }
                            catch (ApplicationException e)
                            {
                                string msg = "Exception appending label \"" +
                                             itm.label + "\" for item with itemId " + itm.itemId + "\nchars:";
                                foreach (char c in itm.label.ToCharArray())
                                {
                                    msg += " " + c + "(" + ((int)c) + ")";
                                }
                                throw new Exception(msg, e);
                            }

                            output.appendWrappedText(GetSupplementalResponseText(iv, rv), 1.5, 6);
                            output.drawY -= PdfOutput.itemSpacing;
                        }
                    }
                }
            }
        }
        //Private instance methods

        private void PopulateItems(def_FormResults formResult, def_FormResults previousFormResult, List <ItemToPrepopulate> itemsToPrepopulate)
        {
            List <Tuple <def_Items, ItemToPrepopulate> > itemTuples = new List <Tuple <def_Items, ItemToPrepopulate> >();

            foreach (ItemToPrepopulate itemToPrepopulate in itemsToPrepopulate)
            {
                def_Items item = formsRepo.GetItemByIdentifier(itemToPrepopulate.Title + Constants.CAADAP.IDENTIFIER_SUFFIX);                 //This is coming from cache
                if (item != null)
                {
                    item = new def_Items(item);                     //We can't modify an item from the cache
                    itemTuples.Add(new Tuple <def_Items, ItemToPrepopulate>(item, itemToPrepopulate));
                }
            }
            if (itemTuples.Count == 0)
            {
                return;
            }

            formsRepo.GetItemLabelsResponses(previousFormResult.formResultId, itemTuples.Select(x => x.Item1).ToList());

            foreach (var itemTuple in itemTuples)
            {
                def_Items         item = itemTuple.Item1;
                ItemToPrepopulate itemToPrepopulate  = itemTuple.Item2;
                def_ItemResults   itemResult         = formResult.def_ItemResults.Where(x => x.itemId == item.itemId).FirstOrDefault();
                def_ItemResults   previousItemResult = item.def_ItemResults.FirstOrDefault();
                def_ItemVariables itemVariable       = item.def_ItemVariables.FirstOrDefault();
                if (previousItemResult == null || itemVariable == null)
                {
                    continue;
                }
                def_ResponseVariables previousResponseVariable = itemVariable.def_ResponseVariables.FirstOrDefault();
                if (previousResponseVariable != null && !String.IsNullOrWhiteSpace(previousResponseVariable.rspValue))
                {
                    bool addItemResult       = false;
                    bool addResponseVariable = false;
                    if (itemResult == null)
                    {
                        itemResult = new def_ItemResults()
                        {
                            itemId        = item.itemId,
                            sessionStatus = 0,
                            dateUpdated   = DateTime.Now
                        };
                        addItemResult = true;
                    }
                    def_ResponseVariables responseVariable = itemResult.def_ResponseVariables.FirstOrDefault();
                    if (responseVariable == null)
                    {
                        responseVariable = new def_ResponseVariables {
                            itemVariableId = itemVariable.itemVariableId
                        };
                        addResponseVariable = true;
                    }
                    if (String.IsNullOrWhiteSpace(responseVariable.rspValue))
                    {
                        bool documentCopyFailed = false;
                        if (itemToPrepopulate.Document.HasValue && itemToPrepopulate.Document.Value)
                        {
                            string newSaveDirectoryPath = Assmnts.Business.Uploads.FileUploads.GetSaveDirectoryPath(formResult.formResultId, itemToPrepopulate.Title);
                            string newDocumentPath;
                            if (TryCopyDocument(previousResponseVariable.rspValue, newSaveDirectoryPath, out newDocumentPath))
                            {
                                responseVariable.rspValue = newDocumentPath;
                            }
                            else
                            {
                                documentCopyFailed = true;
                            }
                        }
                        else
                        {
                            //The item is not a document, just copy the value
                            responseVariable.rspValue = previousResponseVariable.rspValue;
                            try {
                                formsRepo.ConvertValueToNativeType(itemVariable, responseVariable);
                            }
                            catch (Exception ex) {
                                Debug.WriteLine("error converting response to native type for itemvariable \""
                                                + itemVariable.identifier + "\": " + ex.Message);
                            }
                        }
                        if (!documentCopyFailed)
                        {
                            if (addResponseVariable)
                            {
                                itemResult.def_ResponseVariables.Add(responseVariable);
                            }
                            if (addItemResult)
                            {
                                itemResult.dateUpdated = DateTime.Now;
                                formResult.def_ItemResults.Add(itemResult);
                            }
                        }
                    }
                }
            }
        }