@@ -19,6 +19,13 @@ const logger = getServiceChildLogger('member-affiliations')
1919
2020type AffiliationItem = MemberOrganizationWithOverrides | IManualAffiliationData
2121
22+ const isManualAffiliation = ( row : AffiliationItem ) : row is IManualAffiliationData =>
23+ 'segmentId' in row && ! ! row . segmentId
24+
25+ const isMemberOrganizationWithOverrides = (
26+ row : AffiliationItem ,
27+ ) : row is MemberOrganizationWithOverrides => ! isManualAffiliation ( row )
28+
2229async function prepareMemberOrganizationAffiliationTimeline (
2330 qx : QueryExecutor ,
2431 memberId : string ,
@@ -53,7 +60,7 @@ async function prepareMemberOrganizationAffiliationTimeline(
5360 }
5461
5562 // manual affiliations (identified by segmentId) always take highest precedence
56- const manualAffiliations = orgs . filter ( ( row ) => 'segmentId' in row && ! ! row . segmentId )
63+ const manualAffiliations = orgs . filter ( isManualAffiliation )
5764 if ( manualAffiliations . length > 0 ) {
5865 if ( manualAffiliations . length === 1 ) return manualAffiliations [ 0 ]
5966 // if multiple manual affiliations, pick the one with the longest date range
@@ -83,18 +90,20 @@ async function prepareMemberOrganizationAffiliationTimeline(
8390
8491 // 2. among dated rows, pick the best source tier (ui > email-domain > enrichment-*)
8592 if ( withDates . length > 1 ) {
86- const sourceRank = ( row : AffiliationItem ) =>
87- getMemberOrganizationSourceRank ( ( row as MemberOrganizationWithOverrides ) . source )
88- const bestRank = Math . min ( ...withDates . map ( sourceRank ) )
89- orgs = withDates . filter ( ( row ) => sourceRank ( row ) === bestRank )
93+ const ranked = withDates . map ( ( row ) => ( {
94+ row,
95+ rank : getMemberOrganizationSourceRank (
96+ isMemberOrganizationWithOverrides ( row ) ? row . source : undefined ,
97+ ) ,
98+ } ) )
99+ const bestRank = Math . min ( ...ranked . map ( ( r ) => r . rank ) )
100+ orgs = ranked . filter ( ( r ) => r . rank === bestRank ) . map ( ( r ) => r . row )
90101 if ( orgs . length === 1 ) return orgs [ 0 ]
91102 }
92103
93104 // 3. get the two orgs with the most members, and return the one with the most members if there's no draw
94105 // only compare member orgs (manual affiliations don't have memberCount)
95- const memberOrgsOnly = orgs . filter (
96- ( row : AffiliationItem ) => 'segmentId' in row && ! ! row . segmentId ,
97- ) as MemberOrganizationWithOverrides [ ]
106+ const memberOrgsOnly = orgs . filter ( isMemberOrganizationWithOverrides )
98107 if ( memberOrgsOnly . length >= 2 ) {
99108 const sortedByMembers = memberOrgsOnly . sort ( ( a , b ) => b . memberCount - a . memberCount )
100109 if ( sortedByMembers [ 0 ] . memberCount > sortedByMembers [ 1 ] . memberCount ) {
0 commit comments