name-similarity.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /**
  2. * Fuzzy name matching, used to line a name read off a scanned document up
  3. * against the customers a workshop already has.
  4. *
  5. * Papers write names in their own way: "Lücking, Manuel" for a customer saved
  6. * as "Manuel Lücking", an OCR pass that turns "ü" into "u", a middle initial
  7. * that never made it into the app. Sorting the words and measuring edit
  8. * distance absorbs all three without matching two genuinely different people.
  9. */
  10. /** Lowercases, strips punctuation and accents, and sorts the words. */
  11. export function normalizeName(value: string): string {
  12. return value
  13. .normalize('NFD')
  14. .replace(/[\u0300-\u036f]/g, '')
  15. .toLowerCase()
  16. .replace(/[^\p{L}\p{N}]+/gu, ' ')
  17. .trim()
  18. .split(' ')
  19. .filter(Boolean)
  20. .sort()
  21. .join(' ')
  22. }
  23. /**
  24. * Letters a name search treats as plain ones, as two strings of equal length
  25. * for SQL `translate()`: each accented Latin letter and each capital beside
  26. * the letter it becomes, plus the few that carry a stroke rather than an
  27. * accent (Ł, Ø, Đ...), which papers and OCR write plain just as often.
  28. *
  29. * `foldName` applies the same table in the browser or on the server, so a
  30. * word folded here is found in a column folded in the database: "Muller"
  31. * finds "Müller", and "Lukasz" finds "Łukasz", with no extension installed.
  32. */
  33. export const NAME_FOLD: { from: string; to: string } = (() => {
  34. let from = ''
  35. let to = ''
  36. const strokes: Record<string, string> = { ł: 'l', ø: 'o', đ: 'd', ħ: 'h', ı: 'i', ŧ: 't' }
  37. for (let code = 0xc0; code <= 0x24f; code++) {
  38. const letter = String.fromCharCode(code)
  39. const plain = letter
  40. .normalize('NFD')
  41. .replace(/[\u0300-\u036f]/g, '')
  42. .toLowerCase()
  43. const folded = strokes[plain] ?? plain
  44. if (folded !== letter && folded.length === 1) {
  45. from += letter
  46. to += folded
  47. }
  48. }
  49. return { from, to }
  50. })()
  51. /** Lowercases and folds letters with `NAME_FOLD`, as the database search does. */
  52. export function foldName(value: string): string {
  53. return [...value]
  54. .map((letter) => {
  55. const at = NAME_FOLD.from.indexOf(letter)
  56. return at === -1 ? letter : NAME_FOLD.to[at]
  57. })
  58. .join('')
  59. .toLowerCase()
  60. }
  61. /** Levenshtein distance, iterative with a single row of state. */
  62. function editDistance(a: string, b: string): number {
  63. if (a === b) return 0
  64. if (!a.length) return b.length
  65. if (!b.length) return a.length
  66. let previous = Array.from({ length: b.length + 1 }, (_, i) => i)
  67. for (let i = 1; i <= a.length; i++) {
  68. const current = [i]
  69. for (let j = 1; j <= b.length; j++) {
  70. const cost = a[i - 1] === b[j - 1] ? 0 : 1
  71. current[j] = Math.min(current[j - 1] + 1, previous[j] + 1, previous[j - 1] + cost)
  72. }
  73. previous = current
  74. }
  75. return previous[b.length]
  76. }
  77. /**
  78. * A name that is another name plus extra words scores just under an exact
  79. * match: "Autohaus Meyer" and "Autohaus Meyer GmbH" are almost always the same
  80. * customer, but the papers are not proof of it.
  81. */
  82. const SUBSET_SCORE = 0.95
  83. /**
  84. * Similarity of two names from 0 (nothing in common) to 1 (the same name once
  85. * spelling and word order are set aside).
  86. */
  87. export function nameSimilarity(a: string, b: string): number {
  88. const left = normalizeName(a)
  89. const right = normalizeName(b)
  90. if (!left || !right) return 0
  91. if (left === right) return 1
  92. const ratio = 1 - editDistance(left, right) / Math.max(left.length, right.length)
  93. // Edit distance alone punishes a legal form or a middle name harshly enough
  94. // to hide a real customer, so check whether one name simply contains the
  95. // other. Two words minimum: a lone surname matches far too much.
  96. const leftWords = left.split(' ')
  97. const rightWords = right.split(' ')
  98. const [shorter, longer] =
  99. leftWords.length <= rightWords.length ? [leftWords, rightWords] : [rightWords, leftWords]
  100. const contained = shorter.length >= 2 && shorter.every((word) => longer.includes(word))
  101. return contained ? Math.max(ratio, SUBSET_SCORE) : ratio
  102. }