All files / platform/core/src/services/HangingProtocolService HPMatcher.js

82.22% Statements 37/45
65.38% Branches 17/26
100% Functions 4/4
82.22% Lines 37/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174                      166x 32643x       32643x         32643x   32643x 32643x     32643x 32643x 32643x 32621x                 32621x 44853x   44853x 27413x           17440x       44853x               44853x           44853x           44853x 44853x                           44853x       27154x   27154x               17699x 5241x         17699x               32621x 5133x     32621x               166x           44853x       44853x 44853x 44853x                                         44853x       44853x     166x          
import validate from './lib/validator';
 
/**
 * Match a Metadata instance against rules using Validate.js for validation.
 * @param  {InstanceMetadata} metadataInstance Metadata instance object
 * @param  {Array} rules Array of MatchingRules instances (StudyMatchingRule|SeriesMatchingRule|ImageMatchingRule) for the match
 * @param {object} options is an object containing additional information
 * @param {object[]} options.studies is a list of all the studies
 * @param {object[]} options.displaySets is a list of the display sets
 * @return {Object}      Matching Object with score and details (which rule passed or failed)
 */
const match = (metadataInstance, rules = [], customAttributeRetrievalCallbacks, options) => {
  const validateOptions = {
    format: 'grouped',
  };
 
  const details = {
    passed: [],
    failed: [],
  };
 
  const readValues = {};
 
  let requiredFailed = false;
  let score = 0;
 
  // Allow for matching against current or prior specifically
  const prior = options?.studies?.[1];
  const current = options?.studies?.[0];
  const instance = metadataInstance.instances?.[0];
  const fromSrc = {
    prior,
    current,
    instance,
    ...options,
    options,
    metadataInstance,
  };
 
  rules.forEach(rule => {
    const { attribute, from = 'metadataInstance' } = rule;
    // Do not use the custom attribute from the metadataInstance since it is subject to change
    if (customAttributeRetrievalCallbacks.hasOwnProperty(attribute)) {
      readValues[attribute] = customAttributeRetrievalCallbacks[attribute].callback.call(
        rule,
        metadataInstance,
        options
      );
    } else {
      readValues[attribute] = fromSrc[from]?.[attribute] ?? instance?.[attribute];
    }
 
    // handle cases where the constraint is also a custom attribute
    const resolvedConstraint = resolveConstraintAttributes(
      readValues,
      rule.constraint,
      customAttributeRetrievalCallbacks,
      fromSrc
    );
 
    // Format the constraint as required by Validate.js
    const testConstraint = {
      [attribute]: resolvedConstraint,
    };
 
    // Create a single attribute object to be validated, since metadataInstance is an
    // instance of Metadata (StudyMetadata, SeriesMetadata or InstanceMetadata)
    const attributeMap = {
      [attribute]: readValues[attribute],
    };
 
    // Use Validate.js to evaluate the constraints on the specified metadataInstance
    let errorMessages;
    try {
      errorMessages = validate(attributeMap, testConstraint, [validateOptions]);
    } catch (e) {
      errorMessages = ['Something went wrong during validation.', e];
    }
 
    // TODO: move to a logger
    // console.log(
    //   'Test',
    //   `${from}.${attribute}`,
    //   readValues[attribute],
    //   JSON.stringify(rule.constraint),
    //   !errorMessages
    // );
 
    if (!errorMessages) {
      // If no errorMessages were returned, then validation passed.
 
      // Add the rule's weight to the total score
      score += parseInt(rule.weight || 1, 10);
      // Log that this rule passed in the matching details object
      details.passed.push({
        rule,
      });
    } else {
      // If errorMessages were present, then validation failed
 
      // If the rule that failed validation was Required, then
      // mark that a required Rule has failed
      if (rule.required) {
        requiredFailed = true;
      }
 
      // Log that this rule failed in the matching details object
      // and include any error messages
      details.failed.push({
        rule,
        errorMessages,
      });
    }
  });
 
  // If a required Rule has failed Validation, set the matching score to zero
  if (requiredFailed) {
    score = 0;
  }
 
  return {
    score,
    details,
    requiredFailed,
  };
};
 
// New helper function to resolve constraint attributes
const resolveConstraintAttributes = (
  readValues,
  constraint,
  customAttributeRetrievalCallbacks,
  fromSrc
) => {
  Iif (typeof constraint !== 'object' || constraint === null) {
    return constraint;
  }
 
  const resolvedConstraint = {};
  Object.entries(constraint).forEach(([key, value]) => {
    Iif (typeof value === 'object' && Object.keys(value).length > 0 && 'attribute' in value) {
      const attributeName = value.attribute;
      const attributeFrom = value.from ?? 'metadataInstance';
 
      if (customAttributeRetrievalCallbacks.hasOwnProperty(attributeName)) {
        const value = customAttributeRetrievalCallbacks[attributeName].callback.call(
          null,
          fromSrc[attributeFrom],
          fromSrc.options
        );
 
        resolvedConstraint[key] = {
          value,
        };
      } else {
        resolvedConstraint[key] = {
          value:
            fromSrc[attributeFrom]?.[attributeName] ?? fromSrc.metadataInstance?.[attributeName],
        };
      }
    } else {
      resolvedConstraint[key] = value;
    }
  }, {});
 
  return resolvedConstraint;
};
 
const HPMatcher = {
  match,
};
 
export { HPMatcher };