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

81.63% Statements 40/49
67.64% Branches 23/34
100% Functions 5/5
81.63% Lines 40/49

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 175 176 177 178 179 180 181 182 183 184 185                        276x 50320x       50320x         50320x   50320x 50320x     50320x 50320x 50320x 50319x                 50319x 80025x   80025x 41721x           38304x       80025x               80025x           80025x           80025x 80025x         80025x                   80025x       50591x   50591x               29434x 11108x         29434x               50319x 8662x     50319x               276x           80025x       80025x 80025x 80025x                                         80025x       80025x                 276x 80025x   276x          
import validate, { isOhifValidator } from './lib/validator';
import { hpLog } from '../../logging';
 
/**
 * 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];
    }
 
    Iif (hpLog.getLevel() <= hpLog.levels.DEBUG) {
      hpLog.debug(
        '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 (value && typeof value === 'object' && '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] = isOhifValidator(key) ? wrapFalsyOperand(value) : value;
    }
  }, {});
 
  return resolvedConstraint;
};
 
/**
 * Validate.js does not run a validator whose operand is falsy, so
 * `{ greaterThan: 0 }` would always pass. `{ value: 0 }` is truthy, and the
 * validators read the operand from `value`. Only the OHIF validators get the
 * wrapper: for a validate.js built-in such as `presence`, `false` means "off".
 */
const wrapFalsyOperand = operand =>
  operand === 0 || operand === false || operand === '' ? { value: operand } : operand;
 
const HPMatcher = {
  match,
};
 
export { HPMatcher };