All files change-detector.ts

98.83% Statements 85/86
91.07% Branches 51/56
100% Functions 11/11
98.73% Lines 78/79

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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203                      1x                 11x   5x           5x   2x 2x   2x 2x   1x 1x   1x 1x         11x       5x               5x 5x       15x   15x               15x   15x 14x 14x 14x     10x 9x 9x     5x       15x   13x 13x 16x   6x 6x   3x 3x   3x 3x 3x 3x 3x     2x 2x   2x       13x               11x 11x   11x                 11x 66x 66x   66x 11x       11x 11x   11x 11x   11x 11x 4x 7x 2x 5x 1x 4x 1x     11x                         11x   11x   11x 77x 77x 77x 1x                 11x       5x 5x 5x 5x        
import {
  PropertySnapshot,
  ChangeDetectionResult,
  ChangeType,
  Severity,
  PropertyChange,
  DetectionConfig,
  Address,
} from './types';
import { matchRecords } from './matcher.service';
 
const DEFAULT_DETECTION_CONFIG: DetectionConfig = {
  ownershipNameThreshold: 0.7,
  deedDateSensitivity: 0.9,
  taxAmountChangePercent: 15,
};
 
function classifyFieldChange(field: string, oldValue: unknown, newValue: unknown, config: DetectionConfig): PropertyChange {
  let changeType: ChangeType;
 
  switch (field) {
    case 'ownerName':
      changeType =
        typeof oldValue === 'string' && typeof newValue === 'string'
          ? isSignificantNameChange(oldValue, newValue, config)
            ? 'ownership_transfer'
            : 'metadata_change'
          : 'ownership_transfer';
      break;
    case 'deedDate':
      changeType = 'deed_change';
      break;
    case 'taxAmount':
      changeType = 'tax_change';
      break;
    case 'lienCount':
      changeType = (newValue as number) > (oldValue as number) ? 'lien_filing' : 'metadata_change';
      break;
    case 'taxId':
      changeType = 'deed_change';
      break;
    default:
      changeType = 'metadata_change';
  }
 
  return { field, oldValue, newValue, changeType };
}
 
function isSignificantNameChange(oldName: string, newName: string, config: DetectionConfig): boolean {
  const dummyAddress: Address = {
    streetNumber: '0',
    streetName: 'dummy',
    city: 'dummy',
    state: 'XX',
    zip: '00000',
  };
 
  const result = matchRecords(oldName, dummyAddress, newName, dummyAddress);
  return result.nameScore < config.ownershipNameThreshold;
}
 
function determineSeverity(changes: PropertyChange[], config: DetectionConfig): Severity {
  const severityOverrides = config.severityOverrides || {};
 
  const typeToSeverity: Record<ChangeType, Severity> = {
    ownership_transfer: severityOverrides['ownership_transfer'] || 'major',
    deed_change: severityOverrides['deed_change'] || 'moderate',
    lien_filing: severityOverrides['lien_filing'] || 'moderate',
    tax_change: severityOverrides['tax_change'] || 'minor',
    metadata_change: severityOverrides['metadata_change'] || 'minor',
  };
 
  const severityOrder: Severity[] = ['major', 'moderate', 'minor'];
 
  for (const change of changes) {
    const sev = typeToSeverity[change.changeType];
    const idx = severityOrder.indexOf(sev);
    if (idx === 0) return 'major';
  }
 
  for (const change of changes) {
    const sev = typeToSeverity[change.changeType];
    if (sev === 'moderate') return 'moderate';
  }
 
  return 'minor';
}
 
function computeChangeConfidence(changes: PropertyChange[], config: DetectionConfig): number {
  if (changes.length === 0) return 0;
 
  let totalConfidence = 0;
  for (const change of changes) {
    switch (change.changeType) {
      case 'ownership_transfer':
        totalConfidence += 0.95;
        break;
      case 'deed_change':
        totalConfidence += config.deedDateSensitivity;
        break;
      case 'tax_change': {
        const oldVal = change.oldValue as number;
        const newVal = change.newValue as number;
        const pctChange = oldVal ? Math.abs(newVal - oldVal) / oldVal * 100 : 100;
        totalConfidence += pctChange >= config.taxAmountChangePercent ? 0.85 : 0.5;
        break;
      }
      case 'lien_filing':
        totalConfidence += 0.9;
        break;
      default:
        totalConfidence += 0.4;
    }
  }
 
  return Math.round((totalConfidence / changes.length) * 1000) / 1000;
}
 
export function detectChanges(
  previous: PropertySnapshot,
  current: PropertySnapshot,
  config?: Partial<DetectionConfig>,
): ChangeDetectionResult {
  const effectiveConfig = { ...DEFAULT_DETECTION_CONFIG, ...config };
  const changes: PropertyChange[] = [];
 
  const fieldsToCompare: (keyof Omit<PropertySnapshot, 'id' | 'capturedAt' | 'propertyId'>)[] = [
    'ownerName',
    'deedDate',
    'taxId',
    'taxAmount',
    'lienCount',
    'propertyType',
  ];
 
  for (const field of fieldsToCompare) {
    const oldValue = previous[field];
    const newValue = current[field];
 
    if (oldValue !== newValue) {
      changes.push(classifyFieldChange(field, oldValue, newValue, effectiveConfig));
    }
  }
 
  const addressChanges = detectAddressChanges(previous.address, current.address);
  changes.push(...addressChanges);
 
  const severity = determineSeverity(changes, effectiveConfig);
  const confidence = computeChangeConfidence(changes, effectiveConfig);
 
  let changeType: ChangeType = 'metadata_change';
  if (changes.some(c => c.changeType === 'ownership_transfer')) {
    changeType = 'ownership_transfer';
  } else if (changes.some(c => c.changeType === 'deed_change')) {
    changeType = 'deed_change';
  } else if (changes.some(c => c.changeType === 'lien_filing')) {
    changeType = 'lien_filing';
  } else if (changes.some(c => c.changeType === 'tax_change')) {
    changeType = 'tax_change';
  }
 
  return {
    propertyId: previous.propertyId,
    changeType,
    severity,
    confidence,
    changes,
    previousSnapshot: previous,
    currentSnapshot: current,
    detectedAt: new Date().toISOString(),
  };
}
 
function detectAddressChanges(oldAddr: Address, newAddr: Address): PropertyChange[] {
  const changes: PropertyChange[] = [];
 
  const addressFields: (keyof Address)[] = ['streetNumber', 'streetName', 'streetType', 'unit', 'city', 'state', 'zip'];
 
  for (const field of addressFields) {
    const oldVal = oldAddr[field];
    const newVal = newAddr[field];
    if (oldVal !== newVal) {
      changes.push({
        field: `address.${field}`,
        oldValue: oldVal,
        newValue: newVal,
        changeType: 'metadata_change',
      });
    }
  }
 
  return changes;
}
 
export function shouldTriggerAlert(result: ChangeDetectionResult, minSeverity: Severity = 'moderate'): boolean {
  const severityOrder: Severity[] = ['minor', 'moderate', 'major'];
  const resultIdx = severityOrder.indexOf(result.severity);
  const minIdx = severityOrder.indexOf(minSeverity);
  return resultIdx >= minIdx && result.confidence >= 0.7;
}
 
export { classifyFieldChange, determineSeverity, computeChangeConfidence };