All files / src/utils cacheGeneration.ts

100% Statements 29/29
91.3% Branches 21/23
100% Functions 8/8
100% Lines 23/23

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              7x       3x             3x 3x 3x                 4x 4x 3x 2x 2x                         1x 2x   1x 1x 1x   1x 2x 2x 1x   1x 4x 4x       1x  
import type { WeeklyMEPCache } from './weeklyDataCache.js';
 
type CachedMembership = NonNullable<
  WeeklyMEPCache['mepDetails'][string]['hasMembership']
>[number];
 
function referenceCode(value: string | undefined): string {
  return value?.split('/').filter(Boolean).pop()?.toUpperCase() ?? '';
}
 
function normalizeMepIdentifier(id: string): string {
  return id.replace(/^MEP-/u, '').replace(/^person\//u, '');
}
 
function isCurrentPeriod(
  period: { startDate?: string | undefined; endDate?: string | undefined } | undefined,
  today: string,
): boolean {
  const startDate = period?.startDate;
  const endDate = period?.endDate;
  return (startDate === undefined || startDate <= today)
    && (endDate === undefined || endDate >= today);
}
 
function missingCommitteeId(
  membership: CachedMembership,
  existingIds: ReadonlySet<string>,
  today: string,
): string | null {
  const classification = referenceCode(membership.membershipClassification);
  if (!classification.startsWith('COMMITTEE_PARLIAMENTARY_')) return null;
  if (!isCurrentPeriod(membership.memberDuring, today)) return null;
  const organizationId = referenceCode(membership.organization);
  return organizationId === '' || existingIds.has(organizationId) ? null : organizationId;
}
 
/**
 * Finds current committee organization IDs referenced by active MEPs but absent
 * from the corporate-body listing. The result is normalized and sorted so the
 * cache generator performs deterministic direct-detail supplementation.
 */
export function findMissingCurrentCommitteeIds(
  cache: WeeklyMEPCache,
  existingBodyIds: ReadonlySet<string>,
  today = new Date().toISOString().slice(0, 10),
): string[] {
  const currentMEPIds = new Set(
    cache.meps.filter((mep) => mep.active).map((mep) => normalizeMepIdentifier(mep.id)),
  );
  const existingIds = new Set([...existingBodyIds].map((id) => referenceCode(id)));
  const visitedMEPs = new Set<string>();
  const missingIds = new Set<string>();
 
  for (const detail of Object.values(cache.mepDetails)) {
    const mepId = normalizeMepIdentifier(detail.id);
    if (!currentMEPIds.has(mepId) || visitedMEPs.has(mepId)) continue;
    visitedMEPs.add(mepId);
 
    for (const membership of detail.hasMembership ?? []) {
      const organizationId = missingCommitteeId(membership, existingIds, today);
      if (organizationId !== null) missingIds.add(organizationId);
    }
  }
 
  return [...missingIds].sort();
}