Name

sn_risk_advanced.FactorUtilsBase

Description

No description available

Script

var FactorUtilsBase = Class.create();
FactorUtilsBase.prototype = {
  initialize: function() {},
  
  updateGroupFactorMandatoryFlag: function(groupFactor) {
  	this._updateGroupFactorMandatoryFlag(groupFactor);
  },

  deleteTransformationCriterias: function(factorID) {
      this._deleteTransformationCriterias(factorID);
  },

  deleteChoices: function(factorID) {
      this._deleteChoices(factorID);
  },
  
  publishFactor: function(factorID) {
      this._publishFactor(factorID);
  },

  isRecordExists: function(tableName, factorID) {
      return this._isRecordExists(tableName, factorID);
  },

  canFactorBePublished: function(factorRec) {
      return this._canFactorBePublished(factorRec);
  },

  checkifChoiceConfiguredCorrectly: function(factorRec, result) {
      return this._checkifChoiceConfiguredCorrectly(factorRec, result);
  },

  checkifTransformScoreConfiguredCorrectly: function(factorRec, result) {
      return this._checkifTransformScoreConfiguredCorrectly(factorRec, result);
  },

  isValidRecord: function(record, fieldName) {
      return this._isValidRecord(record, fieldName);
  },

  getFactorsWithSameFactorContribution: function(groupFactorRec) {
      return this._getFactorsWithSameFactorContribution(groupFactorRec);
  },

  clearParentFieldInChildFactors: function(groupFactorRec, factorContri, context) {
      this._clearParentFieldInChildFactors(groupFactorRec, factorContri, context);
  },

  checkFactorCanBeDraft: function(factorRecord, errorMesg) {
      return this._checkFactorCanBeDraft(factorRecord, errorMesg);
  },

  deleteManualFactorFromGroup: function(factorRecord) {
      return this._deleteManualFactorFromGroup(factorRecord);
  },

  deleteAsmtFactorMapping: function(factorRecord) {
      return this._deleteAsmtFactorMapping(factorRecord);
  },

  // To validate group factor scripts
  validateBothScripts: function(groupFactor, result) {
      return this._validateBothScripts(groupFactor, result);
  },
  

  canDeleteTransformationCriteria: function(factorID) {
      return this._canDeleteTransformationCriteria(factorID);
  },
  
  copySubfactor: function(factor) {
      return this._copySubfactor(factor);
  },
  
  updateFactorDisplayValueReferences: function(factorChoice){
  	this._updateFactorDisplayValueReferences(factorChoice);
  },
  
  _updateFactorDisplayValueReferences: function(factorChoice){
  	new sn_risk_advanced.GrcARAIntegrationUtils().updateMitigationEffectiveness(factorChoice);
  },

  copyGroupfactor: function(factor) {
      return this._copyGroupfactor(factor);
  },
  
  copyRecord: function(originalRecord, columnsToExclude, predefValues) {
  	return this._copyRecord(originalRecord, columnsToExclude, predefValues);
  },
  
  copyData: function(oldFactor,newFactorID,tables) {
  	return this._copyData(oldFactor,newFactorID,tables);
  },
  
  copyFactor: function(factorId) {
  	return this._copyFactor(factorId);
  },
  
  checkScriptContainsFactor: function(record, mapRecord) {
  	return this._checkScriptContainsFactor(record, mapRecord);
  },
  
  _copyFactor: function(factorId) {
  	var factor = new GlideRecord("sn_risk_advanced_factor");
  	factor.get(factorId);
  	var result = '';
  		
  	if (factor.sys_class_name == "sn_risk_advanced_group_factor") {
      	var groupFactor = new GlideRecord("sn_risk_advanced_group_factor");
      	groupFactor.get(factor.getUniqueValue());
      	result = new sn_risk_advanced.FactorUtils().copyGroupfactor(groupFactor);
      } else if (factor.sys_class_name == "sn_risk_advanced_manual_factor") {
      	var manualFactor = new GlideRecord("sn_risk_advanced_manual_factor");
      	manualFactor.get(factor.getUniqueValue());
      	result = new sn_risk_advanced.FactorUtils().copySubfactor(manualFactor);
      } else if (factor.sys_class_name == "sn_risk_advanced_automated_query_factor") {
      	var autoFactor = new GlideRecord("sn_risk_advanced_automated_query_factor");
      	autoFactor.get(factor.getUniqueValue());
      	result = new sn_risk_advanced.FactorUtils().copySubfactor(autoFactor);
      } else if (factor.sys_class_name == "sn_risk_advanced_automated_scripted_factor") {
      	var scriptedFactor = new GlideRecord("sn_risk_advanced_automated_scripted_factor");
      	scriptedFactor.get(factor.getUniqueValue());
      	result = new sn_risk_advanced.FactorUtils().copySubfactor(scriptedFactor);
      }
  	
  	return result;
  },
  
  _copyGroupfactor: function(factor) {
  	var resultObj = {'error': false, 'errorMsg' : ''};
  	var factorDataCopySuccess = false;
  	var columns_to_exclude = 'state,risk_assessment_methodology,number';
  	var predefObj = {};
  	predefObj['name'] = factor.name;
  	var newFactorID = this._copyRecord(factor,columns_to_exclude,predefObj);
  	resultObj.newFactorID = newFactorID;
  	if(newFactorID != null)
  		factorDataCopySuccess = this._copyGroupFactorRelevantData(factor,newFactorID);
  	if(factorDataCopySuccess == false){
  		this._deleteGroupFactorWithRelevantData(newFactorID);
  		resultObj.error = true;
  		resultObj.errorMsg = gs.getMessage('Error while copying factor');
  		resultObj.newFactorID = null;
  	}
  	return resultObj;
  },
  
  _deleteGroupFactorWithRelevantData: function(factorId){
  	var gr= new GlideRecord("sn_risk_advanced_sub_factor");
  	gr.addQuery("parent", factorId);
  	gr.query();
  	gr.deleteMultiple();
  	
  	var gr1 = new GlideRecord("sn_risk_advanced_group_factor");
  	gr.get(factorId);
  	gr.deleteRecord();
  },
  
  _publishFactor: function(factorId){
  	var gr= new GlideRecord("sn_risk_advanced_factor");
  	gr.get(factorId);
  	gr.setValue("state", "2");
  	gr.update();
  },
  
  _copyGroupFactorRelevantData: function(factor, newFactorID) {
  	var factorDataCopySuccess = false;
  	//copy of transformation critera.
  	factorDataCopySuccess = this._copyRelevantData(factor,newFactorID);
  	//copy of factor
  	factorDataCopySuccess = this._copyFactorsofGroupfactor(factor, newFactorID, "sn_risk_advanced_manual_factor");
  	factorDataCopySuccess = this._copyFactorsofGroupfactor(factor, newFactorID, "sn_risk_advanced_automated_query_factor");
  	factorDataCopySuccess = this._copyFactorsofGroupfactor(factor, newFactorID, "sn_risk_advanced_automated_scripted_factor");
  	
  	return factorDataCopySuccess;
  },
  
  _correctScriptwithValidFactor: function(factor, newFactorID, factorRecord, mapFactor) {
  		if(this._checkScriptContainsFactor(factor, mapFactor)){			
  			var newFactor = new GlideRecord("sn_risk_advanced_group_factor");
  			newFactor.get(newFactorID);
  			newFactor.setValue("qualitative_script",newFactor.getValue("qualitative_script").replace(new RegExp(mapFactor.getValue("number"), 'g'), factorRecord.getValue("number")));
  			newFactor.setValue("quantitative_script",newFactor.getValue("quantitative_script").replace(new RegExp(mapFactor.getValue("number"), 'g'), factorRecord.getValue("number")));
  			newFactor.update();
  		}
  },
  
  _checkScriptContainsFactor: function(factor, mapFactor) {
  	return factor.getValue("qualitative_script").includes(mapFactor.getValue("number")) || factor.getValue("quantitative_script").includes(mapFactor.getValue("number"));
  },
  
  _copyFactorsofGroupfactor: function(factor, newFactorID, tableName) {
  	
  	var factorDataCopySuccess = true;
  	//copy of factor
  	var gr = new GlideRecord(tableName);
  	gr.addQuery('parent', factor.getUniqueValue());
  	gr.query();
  	
  	while(gr.next()) {
  		var resultObj = this.copySubfactor(gr);
  		if(resultObj.error) {
  			factorDataCopySuccess = false;
  			return factorDataCopySuccess;
  		} else {
  			var factorRecord = new GlideRecord("sn_risk_advanced_sub_factor");
  			factorRecord.get(resultObj.newFactorID+'');
  			factorRecord.setValue('parent', newFactorID);
  			factorRecord.setValue('state', '2');
  			factorRecord.update();
  			factorDataCopySuccess = true;
  			
  			if(factor.getValue("qualitative_formula") == "SCRIPT" || factor.getValue("quantitative_formula") == "SCRIPT") {
  				this._correctScriptwithValidFactor(factor, newFactorID, factorRecord, gr);
  	}
  			
  		}
  	}	
  	return factorDataCopySuccess;
  },

  _copySubfactor: function(factor) {
  	var resultObj = {'error': false, 'errorMsg' : ''};
  	var factorDataCopySuccess = false;
  	var columns_to_exclude = 'state,risk_assessment_methodology,number,parent, next_run_date';
  	var predefObj = {};
  	predefObj['name'] = factor.name;
  	var newFactorID = this._copyRecord(factor,columns_to_exclude,predefObj);
  	resultObj.newFactorID = newFactorID;
  	if(newFactorID != null)
  		factorDataCopySuccess = this._copyRelevantData(factor,newFactorID);
  	if(factorDataCopySuccess == false){
  		resultObj.error = true;
  		resultObj.errorMsg = gs.getMessage('Error while copying factor');
  		this._deleteNewFactor(newFactorID);
  		resultObj.newFactorID = null;
  	}
  	return resultObj;
  },
  
  _deleteNewFactor: function(newFactorID){
  	if(newFactorID != null){
  		var factor = new GlideRecord('sn_risk_advanced_factor');
  		factor.get(newFactorID);
  		factor.deleteRecord();
  	}
  },
  
  _copyRecord: function(originalRecord, columnsToExclude, predefValues) {
  	// predefValues - The values which have a known value and should not be copied from original record
  	//example in choice table, F2->C1 if copied from F1->C1
  	var newRec = new GlideRecord(originalRecord.sys_class_name);
  	var fields = originalRecord.getElements();
  	for (var i = 0; i < fields.length; i++) {
  		var glideElement = fields[i];
  		if(!columnsToExclude.contains(glideElement.getName()) && glideElement.getTableName() != 'sys_metadata'){
  			newRec.setValue(glideElement.getName(),originalRecord.getValue(glideElement.getName()));
  		}
  	}
  	
  	for(var key in predefValues){
  		newRec.setValue(key,predefValues[key]);
  	}
  	
  	var newFactorID = newRec.insert();
  	return newFactorID;
  },
  
  _copyRelevantData: function(oldFactor, newFactorID){
  	//tables object key--> tablename to copy data, value--> factor column name
  	//In one table factor reference can be factor, in other it can be sn_risk_advanced_factor
  	var tables = {};
  	if(oldFactor.user_response == '1') {
  		tables['sn_risk_advanced_factor_choice'] = 'factor';
  	}
  	if(oldFactor.transform_score == true){
  		tables['sn_risk_advanced_transformation_criteria'] = 'factor';
  	}
  	return this._copyData(oldFactor,newFactorID,tables);
  },
  
  _copyData: function(oldFactor,newFactorID,tables){
  	var result = true;
  	for(var key in tables){
  		var predefObj = {};
  		var columnName = tables[key];
  		predefObj[columnName] = newFactorID;
  		var table = new GlideRecord(key);
  		table.addQuery(columnName,oldFactor.getUniqueValue());
  		table.query();
  		while(table.next()){
  			result = result && (this._copyRecord(table,'',predefObj) == null ? false : true);
  		}
  	}
  	return result;
  },

  retireFactors: function(ramID) {
  	return this._retireFactors(ramID);
  },
  
  publishFactorsFromRetire: function(ramID) {
  	return this._publishFactorsFromRetire(ramID);
  },
  
  _canDeleteTransformationCriteria: function(factorID) {
      var criteria = new GlideAggregate('sn_risk_advanced_transformation_criteria');
      criteria.addQuery('factor', factorID);
      criteria.addAggregate('count');
      criteria.query();
      criteria.next();
      if (criteria.getAggregate('count') > 1) {
          return true;
      } else {
          return false;
      }
  },

  _validateBothScripts: function(groupFactor, result) {
      var returnedFlag;
      if (groupFactor.qualitative_formula == 'SCRIPT') {
          returnedFlag = this.validateScript(groupFactor, 'qualitative_script', '2');
          result.qualitative = {};
          result.qualitative.error = returnedFlag;
      }
      if (groupFactor.quantitative_formula == 'SCRIPT') {
          returnedFlag = this.validateScript(groupFactor, 'quantitative_script', '1');
          result.quantitative = {};
          result.quantitative.error = returnedFlag;
      }

      if (result.qualitative && !result.qualitative.error && result.quantitative && !result.quantitative.error) {
          result.error = gs.getMessage("Qualitative script and quantitative script validation failed. ");
      } else if (result.qualitative && !result.qualitative.error) {
          result.error = gs.getMessage("Qualitative script validation failed.");
      } else if (result.quantitative && !result.quantitative.error) {
          result.error = gs.getMessage("Quantitative script validation failed.");
      }
  },


  // To validate if script written has any reference error
  validateScript: function(groupFactor, variableName, qualOrQuant) {
      return this._validateScript(groupFactor, variableName, qualOrQuant);
  },

  _validateScript: function(groupFactor, variableName, qualOrQuant) {
      var evaluator = new GlideScopedEvaluator();
      // Get all child factor numbers and put into script to check for errors
      var childFactors = new GlideRecord('sn_risk_advanced_sub_factor');
      childFactors.addQuery('parent', groupFactor.getUniqueValue());
      childFactors.addEncodedQuery('factor_contributionIN3,' + qualOrQuant);
      childFactors.query();
      while (childFactors.next()) {
          evaluator.putVariable(childFactors.number + '', 0);
      }
      evaluator.putVariable('result', {});
      evaluator.evaluateScript(groupFactor, variableName, null);

      var result = evaluator.getVariable('result');
      // If error exists and is reference error, then return false
      if (result.error && (result.error + '').contains('ReferenceError')) {
          return false;
      } else {
          return true;
      }
  },


  // To validate assessment type scripts
  validateBothAsmtTypeScripts: function(asmtType, result) {
      this._validateBothAsmtTypeScripts(asmtType, result);
  },

  _validateBothAsmtTypeScripts: function(asmtType, result) {
      var returnedFlag;
      if (asmtType.qualitative_scoring_logic == 'SCRIPT') {
          returnedFlag = this._validateAsmtTypeScript(asmtType, 'qualitative_script', '2');
          result.qualitative = {};
          result.qualitative.error = returnedFlag;
      }
      if (asmtType.quantitative_scoring_logic == 'SCRIPT') {
          returnedFlag = this._validateAsmtTypeScript(asmtType, 'quantitative_script', '1');
          result.quantitative = {};
          result.quantitative.error = returnedFlag;
      }

      if (result.qualitative && !result.qualitative.error && result.quantitative && !result.quantitative.error) {
          result.error = gs.getMessage("Qualitative script and quantitative script validation failed. ");
      } else if (result.qualitative && !result.qualitative.error) {
          result.error = gs.getMessage("Qualitative script validation failed.");
      } else if (result.quantitative && !result.quantitative.error) {
          result.error = gs.getMessage("Quantitative script validation failed.");
      }
  },

  // To validate assessment type scripts
  validateAsmtTypeScript: function(asmtType, variableName, qualOrQuant) {
      return this._validateAsmtTypeScript(asmtType, variableName, qualOrQuant);
  },

  _validateAsmtTypeScript: function(asmtType, variableName, qualOrQuant) {
      var evaluator = new GlideScopedEvaluator();
      // Get all child factor numbers and put into script to check for errors
      var asmtTypeToFactor = new GlideRecord('sn_risk_advanced_asmt_type_m2m_factor');
      asmtTypeToFactor.addQuery('sn_risk_advanced_assessment_type', asmtType.getUniqueValue());
      asmtTypeToFactor.addEncodedQuery('sn_risk_advanced_factor.factor_contributionIN3,' + qualOrQuant);
      asmtTypeToFactor.query();
      while (asmtTypeToFactor.next()) {
          evaluator.putVariable(asmtTypeToFactor.sn_risk_advanced_factor.number + '', 0);
      }
  	evaluator.putVariable('asmtId', '');
      evaluator.putVariable('result', {});
      evaluator.evaluateScript(asmtType, variableName, null);

      var result = evaluator.getVariable('result');
      // If error exists and is reference error, then return false
      if (result.error && (result.error + '').contains('ReferenceError')) {
          return false;
      } else {
          return true;
      }
  },

  // To calculate script variables for previous and current parent factor
  recalculateScriptVariablesForParents: function(previousGroupFactor, currentGroupFactor, factorContribution) {
      this._recalculateScriptVariablesForParents(previousGroupFactor, currentGroupFactor, factorContribution);
  },

  _recalculateScriptVariablesForParents: function(previousGroupFactor, currentGroupFactor, factorContribution) {
      this._recalculateScriptVariablesForParent(previousGroupFactor, factorContribution);
      this._recalculateScriptVariablesForParent(currentGroupFactor, factorContribution);
  },

  // To calculate script variable field value for parent factor
  recalculateScriptVariablesForParent: function(parentGroupFactor, factorContribution) {
      this._recalculateScriptVariablesForParent(parentGroupFactor, factorContribution);
  },

  _recalculateScriptVariablesForParent: function(parentGroupFactor, factorContribution) {
      // If there is no parent factor, do not calculate
      if (parentGroupFactor) {
          // If factor contribution is Quantitative for factor, recalculate quantitative script variables for parent
          if (factorContribution == '1') {
              this._generateScriptVariables(parentGroupFactor + '', '1');
          } else if (factorContribution == '2') {
              // If factor contribution is qualitative, recalculate only qualitative script variable for parent
              this._generateScriptVariables(parentGroupFactor + '', '2');
          } else if (factorContribution == '3') {
              // If factor contribution is Both, recalculate qualitative and quantitative script variables for parent
              this._generateScriptVariables(parentGroupFactor + '', '2');
              this._generateScriptVariables(parentGroupFactor + '', '1');
          }

      }
  },

  // To calculate script variables for a group factor
  _generateScriptVariables: function(groupFactorId, qualOrQuant) {
      var scriptVariablesString = gs.getMessage('The format of the values in this field is <variable> : <factor name>. For example, FACxxxxxxx: Impact');
      scriptVariablesString += '\n \n';
      // Get all child factors of given factor contribution and Both type
      var childFactors = new GlideRecord('sn_risk_advanced_sub_factor');
      childFactors.addQuery('parent', groupFactorId);
      childFactors.addEncodedQuery('factor_contributionIN3,' + qualOrQuant);
      childFactors.query();
      while (childFactors.next()) {
          scriptVariablesString += childFactors.number + ": " + childFactors.name + "\n";
      }
      var groupFactor = new GlideRecord('sn_risk_advanced_group_factor');
      groupFactor.get(groupFactorId);

      if (qualOrQuant == '2') {
          groupFactor.qualitative_script_variables = scriptVariablesString;
      } else {
          groupFactor.quantitative_script_variables = scriptVariablesString;
      }
      groupFactor.update();
  },


  // To calculate script variables for assessment type
  recalculateScriptVariablesForAssessmentType: function(asmtTypem2mfactor) {
      this._recalculateScriptVariablesForAssessmentType(asmtTypem2mfactor);
  },

  _recalculateScriptVariablesForAssessmentType: function(asmtTypem2mfactor) {
      var factorContribution = asmtTypem2mfactor.sn_risk_advanced_factor.factor_contribution;
      // If factor contribution of factor is quantitative, calculate quantitative script variables. 
      if (factorContribution == '1') {
          this._generateScriptVariablesForAsmtType(asmtTypem2mfactor.sn_risk_advanced_assessment_type + '', '1');
      } else if (factorContribution == '2') {
          // If factor contribution of factor is qualitative, calculate qualitative script variables. 
          this._generateScriptVariablesForAsmtType(asmtTypem2mfactor.sn_risk_advanced_assessment_type + '', '2');
      } else if (factorContribution == '3') {
          // If factor contribution of factor is Both, calculate both qualitative and quantitative script variables
          this._generateScriptVariablesForAsmtType(asmtTypem2mfactor.sn_risk_advanced_assessment_type + '', '1');
          this._generateScriptVariablesForAsmtType(asmtTypem2mfactor.sn_risk_advanced_assessment_type + '', '2');
      }
  },

  // To calculate script variable field for assessment type
  _generateScriptVariablesForAsmtType: function(asmtTypeId, qualOrQuant) {
      var scriptVariablesString = gs.getMessage('The format of the values in this field is <variable> : <factor name>. For example, FACxxxxxxx: Impact');
      scriptVariablesString += '\n \n';
  	scriptVariablesString += 'asmtId: Assessment sys_id' + '\n';
      // Get all factors linked to asmt type of BOTH type and given factor contribution
      var asmtTypeToFactor = new GlideRecord('sn_risk_advanced_asmt_type_m2m_factor');
      asmtTypeToFactor.addQuery('sn_risk_advanced_assessment_type', asmtTypeId);
      asmtTypeToFactor.addEncodedQuery('sn_risk_advanced_factor.factor_contributionIN3,' + qualOrQuant);
      asmtTypeToFactor.query();
      while (asmtTypeToFactor.next()) {
          scriptVariablesString += asmtTypeToFactor.sn_risk_advanced_factor.number + ": " + asmtTypeToFactor.sn_risk_advanced_factor.name + "\n";
      }

      var asmtType = new GlideRecord('sn_risk_advanced_assessment_type');
      if (asmtType.get(asmtTypeId)) {
          if (qualOrQuant == '2') {
              asmtType.qualitative_script_variables = scriptVariablesString;
          } else {
              asmtType.quantitative_script_variables = scriptVariablesString;
          }
          asmtType.update();
      }
  },

  _deleteTransformationCriterias: function(factorID) {
      var gr = new GlideRecord('sn_risk_advanced_transformation_criteria');
      gr.addQuery('factor', factorID);
      gr.query();
      gr.deleteMultiple();
  },

  _deleteChoices: function(factorID) {
      var gr = new GlideRecord('sn_risk_advanced_factor_choice');
      gr.addQuery('factor', factorID);
      gr.query();
      gr.deleteMultiple();
  },

  _isRecordExists: function(tableName, factorID) {
      var gr = new GlideRecord(tableName);
      gr.addQuery('factor', factorID);
      gr.query();
      return gr.hasNext();
  },

  _canFactorBePublished: function(factorRec) {
      var result = {};
      if ((factorRec.getValue('sys_class_name') == 'sn_risk_advanced_manual_factor') && factorRec.getValue('user_response') == '1') {
          return this._checkifChoiceConfiguredCorrectly(factorRec, result);
      } else if (factorRec.getValue('sys_class_name') == 'sn_risk_advanced_group_factor') {
          this._validateBothScripts(factorRec, result);
          if (result.error) {
              return result;
          }
          this._setGroupFactorMandatoryFlag(factorRec);
          return this._checkIfGroupFactorCanBePublished(factorRec, result);
  	} else if (factorRec.getValue('sys_class_name') == 'sn_risk_advanced_automated_scripted_factor'){
  		return this._checkIfScriptedFactorBePublished(factorRec);
  	}
  	else if (factorRec.getValue('transform_score') == true) {
          return this._checkifTransformScoreConfiguredCorrectly(factorRec, result);
      }
      return result;

  },
  
  _checkIfScriptedFactorBePublished: function(factorRec){
  	var result={};
  	result=(new ScriptFactorUtils().validateScript(factorRec));
  	
  	if(result.error){
  		var errMsg = result.error+'';
  		result.error= gs.getMessage("Script validation failed with the error: {0}" , errMsg);			
  	}		
  	if (!result.error && factorRec.getValue('transform_score') == true)
  		this._checkifTransformScoreConfiguredCorrectly(factorRec, result);
  	return result;
  },

  _checkifChoiceConfiguredCorrectly: function(factorRec, result) {
      if (factorRec.getValue('transform_score') == true) {
          var checkChoiceRecordsExist = this._isRecordExists('sn_risk_advanced_factor_choice', factorRec.getUniqueValue());
          var checkTransformationCriteriaRecordsExist = this._isRecordExists('sn_risk_advanced_transformation_criteria', factorRec.getUniqueValue());

          if (!checkChoiceRecordsExist && !checkTransformationCriteriaRecordsExist) {
              result.error = gs.getMessage('Add entries to the Qualitative Transformation Criteria and Choice related lists to publish the factor');
          } else if (!checkChoiceRecordsExist) {
              result.error = gs.getMessage('Add entries to the Choices related list to publish the factor');
          } else if (!checkTransformationCriteriaRecordsExist) {
              result.error = gs.getMessage('Add entries to the Qualitative Transformation Criteria related list to publish the factor');
          }
      } else {
          if (!this._isRecordExists('sn_risk_advanced_factor_choice', factorRec.getUniqueValue())) {
              result.error = gs.getMessage('Add entries to the Choices related list to publish the factor');
          }
      }
      return result;
  },

  _checkifTransformScoreConfiguredCorrectly: function(factorRec, result) {
      if (!this._isRecordExists('sn_risk_advanced_transformation_criteria', factorRec.getUniqueValue())) {

          result.error = gs.getMessage('Add entries to the Qualitative Transformation Criteria related list to publish the factor');
      }
      return result;
  },

  _checkIfGroupFactorCanBePublished: function(factorRec, result) {
      var resultObj = this._checkifChildFactorsConfiguredCorrectly(factorRec, result);
      if (factorRec.getValue('transform_score') == true) {
          var checkTransformationCriteriaRecordsExist = this._isRecordExists('sn_risk_advanced_transformation_criteria', factorRec.getUniqueValue());
          if (resultObj.error) {
              return resultObj;
          } else if (!checkTransformationCriteriaRecordsExist) {
              result.error = gs.getMessage('Add entries to the Qualitative Transformation Criteria related list to publish the factor');
          }
      } else {
          return resultObj;
      }
      return result;
  },

  _checkifChildFactorsConfiguredCorrectly: function(factorRec, result) {
      var gr = new GlideAggregate('sn_risk_advanced_sub_factor');
      gr.addQuery('parent', factorRec.getUniqueValue());
      gr.addAggregate('COUNT');
      gr.groupBy('factor_contribution');
      gr.query();
      var factorContributionCount = {};
      var quant = 1;
      var qual = 2;
      var both = 3;
      if (!gr.hasNext()) {
          result.error = gs.getMessage('Add at least one factor to publish the group factor.');
          return result;
      } else {
          while (gr.next()) {
              factorContributionCount[gr.getValue('factor_contribution')] = gr.getAggregate('COUNT');
          }
      }
      if (factorRec.getValue('factor_contribution') == '1') {
          if (!factorContributionCount[quant] && !factorContributionCount[both]) {
              result.error = gs.getMessage('Add at least one quantitative factor to publish the group factor.');
          }
      } else if (factorRec.getValue('factor_contribution') == '2') {
          if (!factorContributionCount[qual] && !factorContributionCount[both]) {
              result.error = gs.getMessage('Add at least one qualitative factor to publish the group factor.');
          }
      } else if (factorRec.getValue('factor_contribution') == '3') {
          if ((factorContributionCount[quant] && !factorContributionCount[qual]) && !factorContributionCount[both]) {
              result.error = gs.getMessage('Add at least one qualitative factor to publish the group factor.');
          } else if ((factorContributionCount[qual] && !factorContributionCount[quant]) && !factorContributionCount[both]) {
              result.error = gs.getMessage('Add at least one quantitative factor to publish the group factor.');
          } else if ((!factorContributionCount[quant] && !factorContributionCount[qual]) && !factorContributionCount[both]) {
              result.error = gs.getMessage('Add at least one quantitative factor and one qualitative factor to publish the group factor.');
          }
      }
      return result;
  },

  _isValidRecord: function(record, fieldName) {
      var gr = new GlideRecord(record.sys_class_name);
      gr.addQuery('factor', record.factor);
      gr.addQuery('sys_id', '!=', record.getUniqueValue());
      gr.addQuery(fieldName, record.getValue(fieldName));
      gr.query();
      return gr.hasNext();
  },

  _getFactorsWithSameFactorContribution: function(groupFactorRec) {
      var listOfFactorIds = [];
      var childFactors = new GlideRecord('sn_risk_advanced_sub_factor');
      var groupFactorContribution = groupFactorRec.factor_contribution;
      if (groupFactorContribution == '1' || groupFactorContribution == '2') {
          var query = childFactors.addQuery('factor_contribution', groupFactorContribution);
          query.addOrCondition('factor_contribution', '3');
          query.addOrCondition('factor_contribution', '4');
      }
      childFactors.addQuery('state', '2');
      childFactors.addNullQuery('risk_assessment_methodology');
      childFactors.addNullQuery('parent');
      childFactors.query();
      while (childFactors.next()) {
  		var className = childFactors.sys_class_name;
  		if((className=='sn_risk_advanced_automated_query_factor' || className=='sn_risk_advanced_automated_scripted_factor') ){
  			var automatedFactor = new GlideRecord(className);
  			automatedFactor.get(childFactors.getUniqueValue());
  			if(automatedFactor.factor_usage!= groupFactorRec.factor_usage)
  				continue;				
  		}				
          listOfFactorIds.push(childFactors.getUniqueValue() + '');
      }
      return listOfFactorIds.join(',');
  },

  _clearParentFieldInChildFactors: function(groupFactorRec, factorContri, context) {
  	if(factorContri){
  		var childFactors = new GlideRecord('sn_risk_advanced_sub_factor');
  		childFactors.addQuery('parent', groupFactorRec.getUniqueValue());
  		childFactors.addQuery('factor_contribution', 'NOT IN', groupFactorRec.factor_contribution + ',3,4');
  		childFactors.query();
  		while (childFactors.next()) {
  			childFactors.setValue('parent', '');
  			childFactors.update();
  		}
  	}
  	if(context){
  		var automatedChildFactors = new GlideRecord('sn_risk_advanced_base_automated_factor');
  		automatedChildFactors.addQuery('parent', groupFactorRec.getUniqueValue());
  		automatedChildFactors.addQuery('factor_usage', '!=', groupFactorRec.factor_usage);
  		automatedChildFactors.query();
  		while (automatedChildFactors.next()) {
  			automatedChildFactors.setValue('parent', '');
  			automatedChildFactors.update();
  		}
  	}
  },

  _checkFactorCanBeDraft: function(factorRecord, errorMesg) {
      if (factorRecord.sys_class_name != 'sn_risk_advanced_group_factor' && factorRecord.parent != '') {
          if (this._checkIfGroupFactorDraft(factorRecord, errorMesg))
              return this._checkIfAsmtTypesDraft(factorRecord, errorMesg);
          else
              return false;
      } else {
          return this._checkIfAsmtTypesDraft(factorRecord, errorMesg);
      }
  },

  _checkIfGroupFactorDraft: function(factorRecord, errorMesg) {
      if (factorRecord.parent.state == '2') {
          if (errorMesg)
              gs.addErrorMessage(gs.getMessage("This factor cannot be moved back to the draft state because it is a part of a published group factor. "));
          return false;
      }
      return true;
  },

  _checkIfAsmtTypesDraft: function(factorRecord, errorMesg) {
      var isAsmtPublished = false;
      var factorAsmtTypem2m = new GlideRecord('sn_risk_advanced_asmt_type_m2m_factor');
      factorAsmtTypem2m.addQuery('sn_risk_advanced_factor', factorRecord.getUniqueValue());
      factorAsmtTypem2m.addQuery('sn_risk_advanced_assessment_type.state', '2');
      factorAsmtTypem2m.query();

      if (!factorAsmtTypem2m.hasNext()) {
          var control_asmt = new GlideRecord('sn_risk_advanced_control_assessment');
          control_asmt.addQuery('overall_effectiveness_factor', factorRecord.getUniqueValue());
          control_asmt.addQuery('state', '2');
          control_asmt.query();
          isAsmtPublished = control_asmt.hasNext();
      } else {
          isAsmtPublished = true;
      }

      if (isAsmtPublished) {
          if (errorMesg)
              gs.addErrorMessage(gs.getMessage("This factor cannot be moved back to the draft state because it is a part of a published assessment"));
      }
      return !isAsmtPublished;

  },

  _deleteManualFactorFromGroup: function(factorRecord) {
      factorRecord.parent = 'NULL';
  },

  _deleteAsmtFactorMapping: function(factorRecord) {
      var factorAsmtTypem2m = new GlideRecord('sn_risk_advanced_asmt_type_m2m_factor');
      factorAsmtTypem2m.addQuery('sn_risk_advanced_factor', factorRecord.getUniqueValue());
      factorAsmtTypem2m.query();
      if (factorAsmtTypem2m.hasNext())
          factorAsmtTypem2m.deleteMultiple();

      var control_asmt = new GlideRecord('sn_risk_advanced_control_assessment');
      control_asmt.addQuery('overall_effectiveness_factor', factorRecord.getUniqueValue());
      control_asmt.query();
      if (control_asmt.next()) {
          control_asmt.overall_effectiveness_factor = '';
          control_asmt.update();
      }
  },
  
  _retireFactors: function(ramID) {
  	var factors = new GlideRecord('sn_risk_advanced_factor');
  	factors.addQuery('risk_assessment_methodology', ramID);
  	factors.query();
  	factors.setValue('state', '3');
  	factors.updateMultiple();
  },
  
  _publishFactorsFromRetire: function(ramID) {
  	var factors = new GlideRecord('sn_risk_advanced_factor');
  	factors.addQuery('risk_assessment_methodology', ramID);
  	factors.query();
  	factors.setValue('state', '2');
  	factors.updateMultiple();
  },
  
  _setGroupFactorMandatoryFlag: function(groupFactor) {
      //Verify if any child factor is mandatory or not.
  	//As this is called from before br, not updating the record directly
      var childFactors = new GlideRecord('sn_risk_advanced_sub_factor');
      childFactors.addQuery('parent', groupFactor.getUniqueValue());
      childFactors.addQuery('state', 2);
      childFactors.addQuery('mandatory_response', true);
      childFactors.setLimit(1);
      childFactors.query();
      if(childFactors.next()){
  		//If any mandatory child factor found, set group factor as mandatory
  		groupFactor.setValue("mandatory_response", true);
  	}else{
  		groupFactor.setValue("mandatory_response", false);
  	}
  	
  },
  
  _updateGroupFactorMandatoryFlag: function(groupFactor) {
  	var childFactors = new GlideRecord('sn_risk_advanced_sub_factor');
      childFactors.addQuery('parent', groupFactor.getUniqueValue());
      childFactors.addQuery('state', 2);
      childFactors.addQuery('mandatory_response', true);
      childFactors.setLimit(1);
      childFactors.query();
      if(childFactors.next()){
  		//If any mandatory child factor found, set group factor as mandatory
  		groupFactor.setValue("mandatory_response", true);
  	}else{
  		groupFactor.setValue("mandatory_response", false);
  	}
  	groupFactor.update();
  	
  },
  
  type: 'FactorUtilsBase'
};

Sys ID

479c4910539100101be2ddeeff7b12ff

Offical Documentation

Official Docs: