Exemplo n.º 1
0
        /// <summary>
        /// New function to handle a uploading an assessment in the JSON format created in the FormsSql CreateFormResultJSON.
        ///
        /// Reads in a form result record first and updates it.
        ///
        /// Adds/modifies item results and response variables for this form result.
        ///
        /// Item result and response variable data is in the following order:
        ///
        /// responseVariableId, itemId, itemVariableId, rspValue
        ///
        /// The data is sorted by itemId
        ///
        /// responseVariableId is only included so that the data table on the client side has a primary key
        /// (we may find a better way to do this later)
        /// </summary>
        /// <param name="json"></param>
        /// <returns>string - Exception message if any.</returns>

        public static string UpdateAssessmentJSONVenture(IFormsRepository formsRepo, string json)
        {
            string result = String.Empty;

            try
            {
                var dResults = fastJSON.JSON.Parse(json);
                Dictionary <string, Object> resDict = (Dictionary <string, Object>)dResults;

                Dictionary <string, object> formResultDict = (Dictionary <string, object>)resDict["FormResult"];

                // Find the form result we are updating.
                def_FormResults formResult = formsRepo.GetFormResultById(Int32.Parse(formResultDict["newFormResultId"].ToString()));

                // Update the form result's data (More values can be added here as needed to fill in other def_FormResults table fields)
                if (formResult != null)
                {
                    // 4/4/2016 Bug #13143 LK All uploaded assessments should have completed status; some were being set to uploaded somehow. Sets to completed.
                    formResult.formStatus  = 2; // Hard code status "2" for "Complete" (all uploaded assessments must be Complete). To see other formStatus, visit: AJBoggs.Sis.Domain.FormResults_formStatus. OLD code: //Byte.Parse(formResultDict["formStatus"].ToString());
                    formResult.dateUpdated = DateTime.Parse(formResultDict["dateUpdated"].ToString());
                    formResult.interviewer = Int32.Parse(formResultDict["interviewer"].ToString());
                }

                // Get a list of all the data

                List <object> data = (List <object>)resDict["Data"];

                def_ItemResults itemResult = null;

                bool newItemResult = false;


                // Loop over the data items and process them, adding/modifying item results and response variables as needed
                foreach (object dataValue in data)
                {
                    // Order of data in this list is: responseVariableId, itemId, itemVariableId, rspValue
                    Dictionary <string, object> dataValueDict = (Dictionary <string, object>)dataValue;

                    int itemId = Int32.Parse(dataValueDict["itemId"].ToString());


                    // Find the item result corresponding to the form result and item
                    if (itemResult == null)
                    {
                        itemResult = formsRepo.GetItemResultByFormResItem(formResult.formResultId, itemId);
                    }
                    else if (itemResult.itemId != itemId) // we have moved on to the next item
                    {
                        // if the item result was new, and it has response variables, it is added to the item result list of the form result
                        // (this will be saved later)
                        if (newItemResult == true && itemResult.def_ResponseVariables.Count > 0)
                        {
                            formResult.def_ItemResults.Add(itemResult);
                            newItemResult = false;
                        }

                        // Attempt to get the next item result
                        itemResult = formsRepo.GetItemResultByFormResItem(formResult.formResultId, itemId);
                    }

                    // Create a new item result if it doesn't already exist
                    if (itemResult == null)
                    {
                        itemResult               = new def_ItemResults();
                        itemResult.itemId        = itemId;
                        itemResult.formResultId  = formResult.formResultId;
                        itemResult.sessionStatus = 0;
                        newItemResult            = true;
                    }

                    // Set the date updated for the item result (new or old) to now
                    itemResult.dateUpdated = DateTime.Now;


                    int itemVariableId = Int32.Parse(dataValueDict["itemVariableId"].ToString());

                    string rspValue = String.Empty;
                    if (dataValueDict["rspValue"] != null)
                    {
                        rspValue = dataValueDict["rspValue"].ToString();
                    }

                    // Attempt to find a response variable corresponding to the item variable id and form result
                    def_ResponseVariables responseVariable = formsRepo.GetResponseVariablesByFormResultItemVarId(formResult.formResultId, itemVariableId);

                    def_ItemVariables itemVariable = formsRepo.GetItemVariableById(itemVariableId);

                    // If no response variable is found, create one, convert it, and add it to the item result's response variable collection
                    if (responseVariable == null)
                    {
                        responseVariable = new def_ResponseVariables();
                        responseVariable.itemVariableId = itemVariableId;
                        responseVariable.rspValue       = rspValue;

                        formsRepo.ConvertValueToNativeType(itemVariable, responseVariable);

                        itemResult.def_ResponseVariables.Add(responseVariable);
                    }
                    else // A response variable was found. Change the value and convert it.
                    {
                        responseVariable.rspValue = rspValue;

                        formsRepo.ConvertValueToNativeType(itemVariable, responseVariable);
                    }
                }

                // After all changes are made, save everything.
                formsRepo.Save();

                // check is this assessment has been scored.  If not, update the scores.
                def_ItemVariables     iv = formsRepo.GetItemVariableByIdentifier("scr_total_rawscores_all_SIS_sections");
                def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(formResult.formResultId, iv.itemVariableId);
                if (rv == null || String.IsNullOrEmpty(rv.rspValue))
                {
                    new Assessments(formsRepo).UpdateAssessmentScores(formResult);
                }

                try
                {
                    // Add access log record for check in.
                    AccessLogging.InsertAccessLogRecord(formsRepo, formResult.formResultId, (int)AccessLogging.accessLogFunctions.CHECK_IN, "Check in of assessment from Venture by " + SessionHelper.LoginInfo.LoginID);

                    // Add status log record for check in.
                    ReviewStatus.ChangeStatus(formsRepo, formResult, ReviewStatus.CHECKED_IN, "Checked in from Venture by " + SessionHelper.LoginInfo.LoginID);

                    // Change assessment status to completed (multiple workflows determined by enterprise; has separate method from ChangeStatus)
                    ReviewStatus.AssessmentIsCompleted(formsRepo, formResult);

                    // If webservice is enabled, add record to webservice activity table
                    if (WebServiceActivity.IsWebServiceEnabled())
                    {
                        WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.UPLOAD, "formResultId=" + formResult.formResultId.ToString());
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.StackTrace);
                }
            }
            catch (Exception excptn)
            {
                // If any exception is thrown, put the messages from it into the result returned to the client for troubleshooting purposes.

                Debug.WriteLine("JsonImports UpdateAssessmentJSON exception:" + excptn.Message);
                Debug.WriteLine(excptn.StackTrace);
                result = excptn.Message + "\n" + excptn.StackTrace;
                if ((excptn.InnerException != null) && (excptn.InnerException.Message != null))
                {
                    result = result + "\n " + excptn.InnerException.Message;
                }
                Debug.WriteLine("JsonImports UpdateAssessmentJSONVenture exception json:" + json);
            }


            return(result);
        }
        public ActionResult GoAction(FormCollection formCollection)
        {
            string      recId             = formCollection["recId"];
            string      paramFormResultId = formCollection["sisId"];
            string      paramFormId       = formCollection["formId"];
            string      category          = formCollection["CategoryID"];
            SearchModel model             = new SearchModel();

            if (SessionHelper.SessionForm == null)
            {
                // return RedirectToAction("Index", "Search", null);
                SessionHelper.SessionForm = new SessionForm();
            }
            SessionForm sf = SessionHelper.SessionForm;

            if (String.IsNullOrWhiteSpace(category))
            {
                return(RedirectToAction("Index", "Search"));
            }
            else if (category.ToLower().Equals("edit") && model.edit)
            {
                // retrieve and set SessionForm params
                sf.formId       = Convert.ToInt32(paramFormId);
                sf.formResultId = Convert.ToInt32(paramFormResultId);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);

                if (!formResult.locked || (formResult.locked && model.editLocked))
                {
                    // get the sectionId of the first section of the first part based on the formId
                    def_Forms frm = formsRepo.GetFormById(sf.formId);
                    def_Parts prt = formsRepo.GetFormParts(frm)[0];
                    sf.partId       = prt.partId;
                    Session["part"] = prt.partId;
                    def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, sf.formResultId, (int)AccessLogging.accessLogFunctions.EDIT, "Initiate editing of assessment.");
                    }
                    return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
                }
            }
            else if (category.ToLower().Equals("review"))
            {
                // retrieve and set SessionForm params
                sf.formId       = Convert.ToInt32(paramFormId);
                sf.formResultId = Convert.ToInt32(paramFormResultId);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);

                if (model.editLocked)
                {
                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, sf.formResultId, (int)AccessLogging.accessLogFunctions.REVIEW, "Assessment accessed for review.");
                    }

                    if (model.unlock == true)
                    {
                        formsRepo.LockFormResult(formResult.formResultId);
                    }

                    if (formResult.reviewStatus != (int)ReviewStatus.REVIEWED && formResult.reviewStatus != (int)ReviewStatus.APPROVED && formResult.reviewStatus != (int)ReviewStatus.PRE_QA)
                    {
                        def_FormResults preQAcopy = AssessmentCopy.CopyAssessment(formsRepo, formResult.formResultId);

                        if (WebServiceActivity.IsWebServiceEnabled())
                        {
                            WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.REVIEW, "formResultId=" + preQAcopy.formResultId.ToString());
                        }
                    }

                    ReviewStatus.ChangeStatus(formsRepo, formResult, ReviewStatus.REVIEWED, "Initiate review of assessment");

                    // get the sectionId of the first section of the first part based on the formId
                    def_Forms frm = formsRepo.GetFormById(sf.formId);
                    def_Parts prt = formsRepo.GetFormParts(frm)[0];
                    sf.partId       = prt.partId;
                    Session["part"] = prt.partId;
                    def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];


                    return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
                }
            }
            else if (category.ToLower().Equals("approve"))
            {
                // retrieve and set SessionForm params
                sf.formId       = Convert.ToInt32(paramFormId);
                sf.formResultId = Convert.ToInt32(paramFormResultId);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);

                if (model.editLocked)
                {
                    ReviewStatus.ChangeStatus(formsRepo, formResult, ReviewStatus.APPROVED, "Approve review of assessment");

                    if (WebServiceActivity.IsWebServiceEnabled())
                    {
                        WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.APPROVE, "formResultId=" + formResult.formResultId.ToString());
                    }
                }
            }
            else if (category.ToLower().Equals("create"))
            {
                if (model.create == true)
                {
                    string          formId = String.IsNullOrEmpty(paramFormId) ? "1" : paramFormId;
                    def_FormResults frmRes = FormResults.CreateNewFormResultFull(formId,
                                                                                 SessionHelper.LoginStatus.EnterpriseID.ToString(),
                                                                                 SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].GroupID.ToString(),
                                                                                 recId,
                                                                                 SessionHelper.LoginStatus.UserID.ToString()
                                                                                 );
                    string strFormResultId = String.Empty;
                    try
                    {
                        int formRsltId = formsRepo.AddFormResult(frmRes);
                        strFormResultId = formRsltId.ToString();
                        Debug.WriteLine("GoAction create FormResultId strFormResultId:" + strFormResultId);
                    }
                    catch (Exception excptn)
                    {
                        Debug.WriteLine("GoAction Defws.CreateNewFormResultFull formsRepo.AddFormResult  exception:" + excptn.Message);
                        Debug.WriteLine("   GoAction formId:" + formId
                                        + "   entId: " + SessionHelper.LoginStatus.EnterpriseID.ToString()
                                        + "   GroupId: " + SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].GroupID.ToString()
                                        + "   recId: " + recId.ToString()
                                        + "   UserId: " + SessionHelper.LoginStatus.UserID.ToString()
                                        );
                    }

                    if ((!String.IsNullOrEmpty(strFormResultId)) && !String.IsNullOrEmpty(recId))
                    {
                        int intRecId;

                        if (int.TryParse(recId, out intRecId))
                        {
                            using (var context = DataContext.getSisDbContext())
                            {
                                // Contact tempContact = new Contact();
                                Contact tempContact = (from c in context.Contacts
                                                       where c.ContactID == intRecId
                                                       select c).FirstOrDefault();

                                // Address tempAddress = new Address();
                                Address tempAddress = (from a in context.Addresses
                                                       where (a.ContactID == tempContact.ContactID) &&
                                                       (a.AddressType == "R")
                                                       select a).FirstOrDefault();

                                Dictionary <string, string> responsesByIdentifier = new Dictionary <string, string>();
                                responsesByIdentifier.Add("sis_cl_first_nm", tempContact.FirstName);
                                responsesByIdentifier.Add("sis_cl_last_nm", tempContact.LastName);

                                if (tempAddress != null)
                                {
                                    responsesByIdentifier.Add("sis_cl_addr_line1", tempAddress.Address1);
                                    responsesByIdentifier.Add("sis_cl_city", tempAddress.City);
                                    responsesByIdentifier.Add("sis_cl_st", tempAddress.StateCode);
                                    responsesByIdentifier.Add("sis_cl_zip", tempAddress.Zip);
                                }

                                string msg = formsRepo.CreateNewResponseValues(strFormResultId, responsesByIdentifier);
                                Debug.WriteLine("GoAction CreateNewResponseValues strFormResultId: " + strFormResultId + "    msg: " + msg);
                            }
                        }

                        // Retrieve and set SessionForm params
                        sf.formId       = 1; // Temporary
                        sf.formResultId = Convert.ToInt32(strFormResultId);

                        // Get the sectionId of the first section of the first part based on the formId
                        def_Forms frm = formsRepo.GetFormById(sf.formId);
                        def_Parts prt = formsRepo.GetFormParts(frm)[0];
                        sf.partId       = prt.partId;
                        Session["part"] = prt.partId;
                        def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

                        return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
                    }
                }
            }
            else if (category.ToLower().Equals("delete"))
            {
                if (model.delete == true)
                {
                    formsRepo.FormResultDeleteLogically(Convert.ToInt32(paramFormResultId));

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, Convert.ToInt32(paramFormResultId), (int)AccessLogging.accessLogFunctions.DELETE, "Delete assessment.");
                    }


                    if (ventureMode == false && WebServiceActivity.IsWebServiceEnabled())
                    {
                        WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.DELETE, "formResultId=" + paramFormResultId);
                        def_FormResults preQAcopy = ReviewStatus.GetLatestPreQACopy(formsRepo, Convert.ToInt32(paramFormResultId));

                        if (preQAcopy != null)
                        {
                            formsRepo.FormResultDeleteLogically(preQAcopy.formResultId);
                            WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.DELETE, "formResultId=" + preQAcopy.formResultId.ToString());
                        }
                    }
                }
            }
            else if (category.ToLower().Equals("lock"))
            {
                if (model.unlock == true)
                {
                    formsRepo.LockFormResult(Convert.ToInt32(paramFormResultId));
                }
            }
            else if (category.ToLower().Equals("unlock"))
            {
                if (model.unlock == true)
                {
                    formsRepo.UnlockFormResult(Convert.ToInt32(paramFormResultId));
                }
            }
            else if (category.ToLower().Equals("archive"))
            {
                if (model.archive == true)
                {
                    formsRepo.ArchiveFormResult(Convert.ToInt32(paramFormResultId));

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, Convert.ToInt32(paramFormResultId), (int)AccessLogging.accessLogFunctions.ARCHIVE, "Archive assessment.");
                    }
                }
            }
            else if (category.ToLower().Equals("unarchive"))
            {
                if (model.archive == true)
                {
                    formsRepo.UnarchiveFormResult(Convert.ToInt32(paramFormResultId));

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, Convert.ToInt32(paramFormResultId), (int)AccessLogging.accessLogFunctions.UNARCHIVE, "Unarchive assessment.");
                    }
                }
            }
            else if (category.ToLower().Equals("upload"))
            {
                def_FormResults fr = formsRepo.GetFormResultById(Convert.ToInt32(paramFormResultId));

                if (fr.formStatus == (byte)FormResults_formStatus.COMPLETED)
                {
                    SessionHelper.Write("uploadFormResultId", Convert.ToInt32(paramFormResultId));
                    return(RedirectToAction("UploadSingle", "DataSync"));
                }
            }
            else if (category.ToLower().Equals("undelete"))
            {
                if (model.undelete == true)
                {
                    formsRepo.FormResultUndelete(Convert.ToInt32(paramFormResultId));

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, Convert.ToInt32(paramFormResultId), (int)AccessLogging.accessLogFunctions.UNDELETE, "Undelete assessment.");
                    }
                }
            }
            else if (category.ToLower().Equals("planning") && model.edit)
            {
                // retrieve and set SessionForm params
                sf.formId       = Convert.ToInt32(paramFormId);
                sf.formResultId = Convert.ToInt32(paramFormResultId);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);

                if (!formResult.locked || (formResult.locked && model.editLocked))
                {
                    // get the sectionId of the first section of the first part based on the formId
                    def_Forms frm = formsRepo.GetFormById(sf.formId);
                    def_Parts prt = formsRepo.GetPartByFormAndIdentifier(frm, "Other");
                    sf.partId       = prt.partId;
                    Session["part"] = prt.partId;
                    def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, sf.formResultId, (int)AccessLogging.accessLogFunctions.EDIT, "Initiate editing of interview planning.");
                    }
                    return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
                }
            }

            return(RedirectToAction("Index", "Search"));
        }
        /*  This method validates the SIS templates in Views/Templates/SIS
         *
         *
         */
        private bool ValidateFormResult(def_FormResults fr, TemplateItems amt = null)
        {
            // * * * OT 3-15-16 completed form results need to be validated on every save (Bug 13110)
            //// * * * OT 1-4-16   form results that are already marked as completed get to skip validation
            //if (fr.formStatus == (byte)FormResults_formStatus.COMPLETED)
            //    return true;

            if (amt == null)
            {
                amt = new GeneralForm();
            }

            //retrieve all responses for this formResult, by def_ItemVariable identifier
            List <ValuePair> allResponses = CommonExport.GetDataByFormResultId(fr.formResultId);

            //pass the response data through generic validation (meta-data driven validation)
            def_Forms frm = formsRepo.GetFormById(fr.formId);

            string[]         ItemVariableSuffixesToSkip = { "Notes", "portantTo", "portantFor", "cl_age", "int_id" };
            SharedValidation sv      = new SharedValidation(allResponses);
            bool             invalid = sv.DoGenericValidation(formsRepo, amt, frm, ItemVariableSuffixesToSkip);

            //pass the response data through one-off validation (rules that can't be encoded into meta-data)
            //populate amt.valdiationMessages in the process
            amt.validationMessages = new List <string>();
            if (SisOneOffValidation.RunOneOffValidation(formsRepo, frm, fr.EnterpriseID.Value, allResponses, amt))
            {
                invalid = true;
            }

            if (invalid)
            {
                return(false);
            }

            //  Mark the FormResult as Complete
            new Assessments(formsRepo).AssessmentComplete(fr);// formsRepo.FormResultComplete(fr);

            // Insert status log indicating assessment has been marked complete
            if (SessionHelper.IsVentureMode == false)
            {
                ReviewStatus.AssessmentIsCompleted(formsRepo, fr);

                if (WebServiceActivity.IsWebServiceEnabled())
                {
                    WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.COMPLETE, "formResultId=" + fr.formResultId.ToString());
                }
            }

            // Populate the hidden Venture Version field upon validation

            if (SessionHelper.IsVentureMode == true)
            {
                string ventureVersion = SessionHelper.Read <string>("venture_version");

                if (ventureVersion != null)
                {
                    Updates.AddField(formsRepo, Updates.SIS_HIDDEN, fr, Updates.VENTURE_VERSION, ventureVersion);
                }
            }

            return(true);
        }