Untitled

mail@pastecode.io avatar
unknown
csharp
a year ago
2.9 kB
1
Indexable
Never
private void ProcessVariableStatusForOneSurveyIterationRespondent(int surveyIterationRespondentId)
{
    var ruleResultRespondents = _db.RuleResultRespondent
        .Where(r => r.SurveyIterationRespondentId == surveyIterationRespondentId)
        .ToList();

    var ruleIdsInQuestion = ruleResultRespondents.Select(x => x.RuleId).ToList();

    var ruleVariableAssociations = _db.RuleVariableAssociation
        .Where(x => ruleIdsInQuestion.Contains(x.RuleId))
        .ToList();

    // Use a dictionary to group rule variables by name for faster access
    var variableGroups = ruleVariableAssociations
        .GroupBy(x => x.VariableName)
        .ToDictionary(g => g.Key, g => g.ToList());

    foreach (var variableEntry in variableGroups)
    {
        var variableName = variableEntry.Key;
        var ruleVariables = variableEntry.Value;

        // Get rules associated with the variable
        var ruleIdsToCheckVariableAgainst = ruleVariables.Select(x => x.RuleId).ToList();

        var ruleStatusesForThisVariable = ruleResultRespondents
            .Where(x => ruleIdsToCheckVariableAgainst.Contains(x.RuleId))
            .ToList();

        var ruleCountForThisVariable = ruleStatusesForThisVariable.Count;

        if (ruleCountForThisVariable > 0)
        {
            var varStatus = "Fail";
            var offPathCount = ruleStatusesForThisVariable.Count(x => x.ValidityStatus == "Off Path");
            var invalidCount = ruleStatusesForThisVariable.Count(x => x.ValidityStatus == "Invalid");

            if (invalidCount == 0)
            {
                varStatus = "Pass"; // no errors
            }

            if (offPathCount == ruleCountForThisVariable)
            {
                varStatus = "Off Path"; // all rules are off path
            }

            var errorCount = invalidCount; // this many rules failed for the variable

            // Update variable in response table
            var resp = _db.Response
                .FirstOrDefault(x => x.VariableName == variableName && x.SurveyIterationRespondentId == surveyIterationRespondentId);

            if (resp != null)
            {
                resp.ErrorsCount = errorCount;
                resp.VariableStatus = varStatus;
            }
        }
    }

    // Batch update the responses
    _db.SaveChanges(1);

    // Determine response status for the survey iteration respondent
    var failedList = _db.Response
        .Where(x => x.SurveyIterationRespondentId == surveyIterationRespondentId && x.VariableStatus == "Fail")
        .ToList();

    var respStatus = failedList.Any() ? $"Dirty ({failedList.Sum(x => x.ErrorsCount)})" : "Clean";

    var sirToUpdate = _db.SurveyIterationRespondent.Find(surveyIterationRespondentId);
    sirToUpdate.ResponseStatus = respStatus;

    // Batch update the survey iteration respondent
    _db.SaveChanges(1);
}