1- import { getLongestDateRange } from '@crowd/common'
1+ import { getLongestDateRange , getMemberOrganizationSourceRank } from '@crowd/common'
22import { IMemberOrganization } from '@crowd/types'
33
44import { BLACKLISTED_MEMBER_TITLES } from '../members/base'
@@ -22,6 +22,7 @@ export interface IWorkExperienceResolution {
2222 isPrimaryWorkExperience : boolean
2323 memberCount : number
2424 segmentId : string | null
25+ source : string | null
2526}
2627
2728/**
@@ -58,7 +59,8 @@ export async function findWorkExperiencesBulk(
5859 mo."createdAt",
5960 COALESCE(ovr."isPrimaryWorkExperience", false) AS "isPrimaryWorkExperience",
6061 COALESCE(a.total_count, 0) AS "memberCount",
61- NULL::text AS "segmentId"
62+ NULL::text AS "segmentId",
63+ mo."source"
6264 FROM "memberOrganizations" mo
6365 JOIN organizations o ON mo."organizationId" = o.id
6466 LEFT JOIN "memberOrganizationAffiliationOverrides" ovr ON ovr."memberOrganizationId" = mo.id
@@ -92,7 +94,8 @@ export async function findManualAffiliationsBulk(
9294 NULL::timestamptz AS "createdAt",
9395 false AS "isPrimaryWorkExperience",
9496 0 AS "memberCount",
95- msa."segmentId"
97+ msa."segmentId",
98+ NULL AS "source"
9699 FROM "memberSegmentAffiliations" msa
97100 JOIN organizations o ON msa."organizationId" = o.id
98101 WHERE msa."memberId" IN ($(memberIds:csv))
@@ -121,13 +124,21 @@ export function selectPrimaryWorkExperience(orgs: IWorkExperienceResolution[]) {
121124 const withDates = orgs . filter ( ( r ) => r . dateStart )
122125 if ( withDates . length === 1 ) return withDates [ 0 ]
123126
124- // 4. Org with strictly more members wins; if tied, fall through
127+ // 4. Among dated rows, pick the best source tier (ui > email-domain > enrichment-*)
128+ if ( withDates . length > 1 ) {
129+ const bestRank = Math . min ( ...withDates . map ( ( r ) => getMemberOrganizationSourceRank ( r . source ) ) )
130+ const topSourceGroup = withDates . filter ( ( r ) => getMemberOrganizationSourceRank ( r . source ) === bestRank )
131+ if ( topSourceGroup . length === 1 ) return topSourceGroup [ 0 ]
132+ orgs = topSourceGroup
133+ }
134+
135+ // 5. Org with strictly more members wins; if tied, fall through
125136 const sorted = [ ...orgs ] . sort ( ( a , b ) => b . memberCount - a . memberCount )
126137 if ( sorted . length >= 2 && sorted [ 0 ] . memberCount > sorted [ 1 ] . memberCount ) {
127138 return sorted [ 0 ]
128139 }
129140
130- // 5 . Longest date range as final tiebreaker
141+ // 6 . Longest date range as final tiebreaker
131142 return getLongestDateRange (
132143 orgs as unknown as IMemberOrganization [ ] ,
133144 ) as unknown as IWorkExperienceResolution
0 commit comments