# All files matcher.service.ts

97.61% Statements 123/126
93.42% Branches 71/76
93.75% Functions 15/16
99.12% Lines 113/114

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
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310

    2x

    2x

    2x

    2x

    2x

    56x
    2622x

    56x
    323x
    1950x
    1950x

    56x

    39x
    38x

    848x

    37x
    37x

    37x
    37x
    37x
    37x

    37x

    36x
    36x
    2x

    36x
    36x
    2x

    36x

    36x
    1x
    35x
    31x
    31x

    4x
    4x
    4x

    36x

    36x
    4x
    4x
    4x

    36x

    69x
    69x

    30x

    30x

    300x
    300x
    300x

    300x
    252x

    250x

    36x
    36x
    36x

    36x

    9x
    9x
    9x

    9x

    9x
    9x

    15x
    15x
    15x

    15x
    15x
    1x
    1x
    1x
    1x
    1x

    1x
    1x

    15x
    15x

    15x
    15x
    15x

    15x
    15x
    15x
    15x

    15x

    15x
    9x
    9x
    9x

    15x

    15x

    15x

    15x
    15x

    15x

    15x

    15x

    15x
    15x
    15x
    15x
    15x
    15x

    15x
    15x
    15x
    15x

    15x
    15x

    15x

    15x

    15x

    3x

     import {
      Address,
      MatchResult,
      MatchDetails,
      FieldMatch,
      MatchingConfig,
      NormalizedTokens,
      PropertyType,
    } from './types';

    const DEFAULT_CONFIG: MatchingConfig = {
      nameThreshold: 0.85,
      addressThreshold: 0.9,
      overallThreshold: 0.85,
      geocodingRadiusMeters: 100,
    };

    const COMMON_PREFIXES = new Set([
      'mr', 'mrs', 'ms', 'miss', 'dr', 'prof', 'jr', 'sr', 'junior', 'senior',
      'ii', 'iii', 'iv', 'rev', 'st', 'hon', 'esq',
    ]);

    const COMMON_SUFFIXES = new Set([
      'jr', 'sr', 'junior', 'senior', 'ii', 'iii', 'iv', 'v', 'esq',
      'phd', 'md', 'llm', 'cpa',
    ]);

    const STREET_TYPE_MAP: Record<string, string> = {
      'st': 'street', 'street': 'street',
      'ave': 'avenue', 'avenue': 'avenue',
      'blvd': 'boulevard', 'boulevard': 'boulevard',
      'dr': 'drive', 'drive': 'drive',
      'ln': 'lane', 'lane': 'lane',
      'ct': 'court', 'court': 'court',
      'pl': 'place', 'place': 'place',
      'rd': 'road', 'road': 'road',
      'way': 'way',
      'trl': 'trail', 'trail': 'trail',
      'hwy': 'highway', 'highway': 'highway',
      'pkwy': 'parkway', 'parkway': 'parkway',
      'cir': 'circle', 'circle': 'circle',
      'sq': 'square', 'square': 'square',
      'ter': 'terrace', 'terrace': 'terrace',
    };

    const PROPERTY_TYPE_CONFIGS: Record<PropertyType, Partial<MatchingConfig>> = {
      'residential': { nameThreshold: 0.85, addressThreshold: 0.9 },
      'commercial': { nameThreshold: 0.8, addressThreshold: 0.9 },
      'land': { nameThreshold: 0.8, addressThreshold: 0.85 },
      'multi-family': { nameThreshold: 0.8, addressThreshold: 0.9 },
    };

    function levenshteinDistance(a: string, b: string): number {
      const matrix: number[][] = Array.from({ length: b.length + 1 }, (_, i) =>
        Array.from({ length: a.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0))
      );

      for (let i = 1; i <= b.length; i++) {
        for (let j = 1; j <= a.length; j++) {
          const cost = a[j - 1] === b[i - 1] ? 0 : 1;
          matrix[i][j] = Math.min(
            matrix[i - 1][j] + 1,
            matrix[i][j - 1] + 1,
            matrix[i - 1][j - 1] + cost,
          );
        }
      }

      return matrix[b.length][a.length];
    }

    function similarityScore(distance: number, maxLen: number): number {
      if (maxLen === 0) return 1.0;
      return 1.0 - distance / maxLen;
    }

    function normalizeString(str: string): string {
      return str
        .toLowerCase()
        .replace(/[''']/g, '')
        .replace(/[^a-z0-9\s]/g, ' ')
        .replace(/\s+/g, ' ')
        .trim();
    }

    function parseName(name: string): NormalizedTokens {
      const clean = normalizeString(name);
      const parts = clean.split(' ').filter(Boolean);

      let firstName = '';
      let lastName = '';
      let middleName = '';
      const initials: string[] = [];

      if (parts.length === 0) return { firstName, lastName, middleName, initials };

      let startIdx = 0;
      while (startIdx < parts.length && COMMON_PREFIXES.has(parts[startIdx])) {
        startIdx++;
      }

      let endIdx = parts.length;
      while (endIdx > startIdx + 1 && COMMON_SUFFIXES.has(parts[endIdx - 1])) {
        endIdx--;
      }

      const coreParts = parts.slice(startIdx, endIdx);

      if (coreParts.length === 1) {
        lastName = coreParts[0];
      } else if (coreParts.length === 2) {
        firstName = coreParts[0];
        lastName = coreParts[1];
      } else {
        firstName = coreParts[0];
        lastName = coreParts[coreParts.length - 1];
        middleName = coreParts.slice(1, -1).join(' ');
      }

      Iif (firstName.length === 1) {
        initials.push(firstName);
      }
      if (middleName) {
        const middleParts = middleName.split(' ');
        for (const mp of middleParts) {
          if (mp.length === 1) initials.push(mp);
        }
      }

      return { firstName, lastName, middleName, initials };
    }

    function normalizeStreetType(type: string): string {
      const clean = normalizeString(type);
      return STREET_TYPE_MAP[clean] || clean;
    }

    function normalizeAddress(addr: Address): string {
      const parts = [
        addr.streetNumber,
        normalizeString(addr.streetName),
        addr.streetType ? normalizeStreetType(addr.streetType) : '',
        addr.unit ? normalizeString(addr.unit) : '',
        normalizeString(addr.city),
        addr.state.toLowerCase(),
        addr.zip,
      ].filter(Boolean);
      return parts.join(' ');
    }

    function computeFieldMatch(valueA: string, valueB: string, normalizeFn?: (v: string) => string): FieldMatch {
      const normFn = normalizeFn || normalizeString;
      const normalizedA = normFn(valueA);
      const normalizedB = normFn(valueB);

      if (!normalizedA && !normalizedB) return { valueA, valueB, normalizedA, normalizedB, score: 1.0 };
      if (!normalizedA || !normalizedB) return { valueA, valueB, normalizedA, normalizedB, score: 0.0 };

      if (normalizedA === normalizedB) return { valueA, valueB, normalizedA, normalizedB, score: 1.0 };

      const dist = levenshteinDistance(normalizedA, normalizedB);
      const maxLen = Math.max(normalizedA.length, normalizedB.length);
      const score = similarityScore(dist, maxLen);

      return { valueA, valueB, normalizedA, normalizedB, score: Math.round(score * 1000) / 1000 };
    }

    function haversineDistance(lat1: number, lon1: number, lat2: number, lon2: number): number {
      const R = 6371000;
      const dLat = ((lat2 - lat1) * Math.PI) / 180;
      const dLon = ((lon2 - lon1) * Math.PI) / 180;
      const a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos((lat1 * Math.PI) / 180) *
          Math.cos((lat2 * Math.PI) / 180) *
          Math.sin(dLon / 2) *
          Math.sin(dLon / 2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      return R * c;
    }

    function computeNameScore(tokensA: NormalizedTokens, tokensB: NormalizedTokens): number {
      const firstScore = computeFieldMatch(tokensA.firstName, tokensB.firstName).score;
      const lastScore = computeFieldMatch(tokensA.lastName, tokensB.lastName).score;
      const middleScore = computeFieldMatch(tokensA.middleName, tokensB.middleName).score;

      let initialMatchScore = 1.0;
      if (tokensA.initials.length > 0 || tokensB.initials.length > 0) {
        const allInitialsA = new Set(tokensA.initials.map(i => i.toLowerCase()));
        const allInitialsB = new Set(tokensB.initials.map(i => i.toLowerCase()));
        let matched = 0;
        for (const init of allInitialsA) {
          Iif (allInitialsB.has(init)) matched++;
        }
        const total = Math.max(allInitialsA.size, allInitialsB.size);
        initialMatchScore = total > 0 ? matched / total : 1.0;
      }

      const weighted = (lastScore * 0.45) + (firstScore * 0.35) + (middleScore * 0.1) + (initialMatchScore * 0.1);
      return Math.round(weighted * 1000) / 1000;
    }

    function computeAddressScore(addrA: Address, addrB: Address, config: MatchingConfig): { score: number; geocodingDistance?: number } {
      const numberMatch = computeFieldMatch(addrA.streetNumber, addrB.streetNumber).score;
      const streetMatch = computeFieldMatch(addrA.streetName, addrB.streetName, normalizeString).score;
      const typeMatch = computeFieldMatch(
        addrA.streetType ? normalizeStreetType(addrA.streetType) : '',
        addrB.streetType ? normalizeStreetType(addrB.streetType) : '',
      ).score;
      const unitMatch = computeFieldMatch(addrA.unit || '', addrB.unit || '').score;
      const cityMatch = computeFieldMatch(addrA.city, addrB.city).score;
      const stateMatch = computeFieldMatch(addrA.state, addrB.state).score;
      const zipMatch = computeFieldMatch(addrA.zip, addrB.zip).score;

      let geocodingDistance: number | undefined;
      let geoScore = 0.0;

      if (addrA.latitude && addrA.longitude && addrB.latitude && addrB.longitude) {
        geocodingDistance = haversineDistance(addrA.latitude, addrA.longitude, addrB.latitude, addrB.longitude);
        const maxDist = config.geocodingRadiusMeters;
        geoScore = geocodingDistance <= maxDist ? 1.0 : Math.max(0, 1.0 - (geocodingDistance - maxDist) / (maxDist * 5));
      }

      const weighted =
        (numberMatch * 0.2) +
        (streetMatch * 0.25) +
        (typeMatch * 0.1) +
        (unitMatch * 0.1) +
        (cityMatch * 0.1) +
        (stateMatch * 0.1) +
        (zipMatch * 0.1) +
        (geoScore * (geocodingDistance !== undefined ? 0.05 : 0));

      return { score: Math.round(weighted * 1000) / 1000, geocodingDistance };
    }

    export function matchRecords(
      nameA: string,
      addressA: Address,
      nameB: string,
      addressB: Address,
      config?: Partial<MatchingConfig>,
    ): MatchResult {
      const effectiveConfig = { ...DEFAULT_CONFIG, ...config };

      const tokensA = parseName(nameA);
      const tokensB = parseName(nameB);

      const nameScore = computeNameScore(tokensA, tokensB);

      const { score: addressScore, geocodingDistance } = computeAddressScore(addressA, addressB, effectiveConfig);

      const overallConfidence = Math.round((nameScore * 0.5 + addressScore * 0.5) * 1000) / 1000;

      const firstMatch = computeFieldMatch(tokensA.firstName, tokensB.firstName);
      const lastMatch = computeFieldMatch(tokensA.lastName, tokensB.lastName);
      const middleMatch = computeFieldMatch(tokensA.middleName, tokensB.middleName);
      const numberMatch = computeFieldMatch(addressA.streetNumber, addressB.streetNumber);
      const streetMatch = computeFieldMatch(addressA.streetName, addressB.streetName, normalizeString);
      const typeMatch = computeFieldMatch(
        addressA.streetType ? normalizeStreetType(addressA.streetType) : '',
        addressB.streetType ? normalizeStreetType(addressB.streetType) : '',
      );
      const unitMatch = computeFieldMatch(addressA.unit || '', addressB.unit || '');
      const cityMatch = computeFieldMatch(addressA.city, addressB.city);
      const stateMatch = computeFieldMatch(addressA.state, addressB.state);
      const zipMatch = computeFieldMatch(addressA.zip, addressB.zip);

      const normalizedA = normalizeAddress(addressA);
      const normalizedB = normalizeAddress(addressB);

      const dist = levenshteinDistance(
        normalizeString(nameA),
        normalizeString(nameB),
      );

      const details: MatchDetails = {
        nameNormalized: [normalizeString(nameA), normalizeString(nameB)],
        addressNormalized: [normalizedA, normalizedB],
        levenshteinDistance: dist,
        geocodingDistance,
        fields: {
          firstName: firstMatch,
          lastName: lastMatch,
          middleName: middleMatch,
          streetNumber: numberMatch,
          streetName: streetMatch,
          streetType: typeMatch,
          unit: unitMatch,
          city: cityMatch,
          state: stateMatch,
          zip: zipMatch,
        },
      };

      return {
        nameScore,
        addressScore,
        overallConfidence,
        isMatch: overallConfidence >= effectiveConfig.overallThreshold,
        details,
      };
    }

    export function getConfigForPropertyType(type: PropertyType): MatchingConfig {
      return { ...DEFAULT_CONFIG, ...PROPERTY_TYPE_CONFIGS[type] };
    }

    export { parseName, normalizeString, normalizeStreetType, levenshteinDistance, similarityScore };