diff --git a/app/api/0pt/internal/er/candidates/route.ts b/app/api/0pt/internal/er/candidates/route.ts index f6a55ea..20ddf64 100644 --- a/app/api/0pt/internal/er/candidates/route.ts +++ b/app/api/0pt/internal/er/candidates/route.ts @@ -15,31 +15,54 @@ const er = new EntityResolutionService(); /** * Company identity hard rule. * - * Negative identity evidence dominates positive evidence: if two records both - * carry the same identifier type and the values conflict, they MUST NOT be - * merged even if another identifier happens to match. Only when every shared - * stable identifier agrees may one matching identifier force a match. + * LEI is globally scoped. National registration numbers are not: they may only + * force a decision when both records also carry the same registration country. + * Negative identity evidence dominates positive evidence within the same + * identifier scope. Formatting punctuation is ignored for stable identifiers. */ er.registerHardRule({ - rule_id: "0pt.company.stable-identifiers.v2", + rule_id: "0pt.company.stable-identifiers.v3", decide(a, b) { - const fields = ["lei", "org_nr"] as const; let sharedMatch = false; - for (const field of fields) { - const av = stringField(a, field); - const bv = stringField(b, field); - if (!av || !bv) continue; - if (av !== bv) return "force_non_match"; + + const aLei = stableIdentifier(a, "lei"); + const bLei = stableIdentifier(b, "lei"); + if (aLei && bLei) { + if (aLei !== bLei) return "force_non_match"; sharedMatch = true; } + + const aCountry = countryIdentifier(a); + const bCountry = countryIdentifier(b); + const aOrg = stableIdentifier(a, "org_nr"); + const bOrg = stableIdentifier(b, "org_nr"); + if (aOrg && bOrg && aCountry && bCountry && aCountry === bCountry) { + if (aOrg !== bOrg) return "force_non_match"; + sharedMatch = true; + } + return sharedMatch ? "force_match" : "abstain"; }, }); -function stringField(record: ErRecord, field: string): string | undefined { +function rawStringField(record: ErRecord, field: string): string | undefined { const value = record.fields[field]; if (value === null || value === undefined) return undefined; - const normalized = String(value).trim().toUpperCase(); + const normalized = String(value).trim(); + return normalized || undefined; +} + +function stableIdentifier(record: ErRecord, field: string): string | undefined { + const value = rawStringField(record, field); + if (!value) return undefined; + const normalized = value.toUpperCase().replace(/[^A-Z0-9]/g, ""); + return normalized || undefined; +} + +function countryIdentifier(record: ErRecord): string | undefined { + const value = rawStringField(record, "registration_country") ?? rawStringField(record, "country"); + if (!value) return undefined; + const normalized = value.toUpperCase().replace(/[^A-Z0-9]/g, ""); return normalized || undefined; }