All files / src/generators/builders shared-builders.ts

65.27% Statements 47/72
44.44% Branches 32/72
75% Functions 21/28
66.66% Lines 34/51

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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371                                                            12x   12x   12x                               168x                       83x                                     42x 37x   42x 36x     42x 42x 36x   36x   37x   42x                             23x 23x 23x 23x   23x                                                                                                                 42x 42x               37x 36x           37x                       13x 11x                                                           50x 47x   100x                                                                                                                                                                                 70x 56x         165x                                                                           115x    
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Generators/Builders/SharedBuilders
 * @description Shared helper functions used across multiple analysis builder
 * domains. Includes outcome matrix construction, AI marker impact assessments,
 * coalition metrics, pipeline builders, trend analytics, and SWOT dimension helpers.
 */
 
import type {
  DeepAnalysis,
  StakeholderOutcomeMatrix,
  AnalysisStakeholderType,
  CoalitionMetrics,
  LegislativePipeline,
  TrendAnalytics,
  DashboardPanel,
  DashboardBuilderStrings,
  WeekAheadData,
  VotingPattern,
  SwotDimension,
  SwotItem,
  StakeholderMetric,
} from '../../types/index.js';
import { buildStakeholderOutcomeMatrix } from '../../utils/intelligence-analysis.js';
import { AI_MARKER } from '../../constants/analysis-constants.js';
 
// ─── Style constants ─────────────────────────────────────────────────────────
 
export const EP_BLUE_TRANSPARENT = 'rgba(0,51,153,0.1)';
 
export const EP_BLUE_BORDER = '#003399';
 
export const CIVIL_SOCIETY = 'Civil Society';
 
/**
 * Build the stakeholder outcome matrix for a list of key actions.
 * Used by all 5 analysis builders to populate the outcome matrix.
 *
 * @param actions - Readonly array of (action, scores) pairs to include in the matrix
 * @returns Stakeholder outcome matrix rows
 */
export function buildOutcomeMatrix(
  actions: readonly {
    readonly action: string;
    readonly scores: Readonly<Partial<Record<AnalysisStakeholderType, number>>>;
    readonly confidence: 'high' | 'medium' | 'low';
  }[]
): StakeholderOutcomeMatrix[] {
  return actions.map(({ action, scores, confidence }) =>
    buildStakeholderOutcomeMatrix(action, scores, confidence)
  );
}
 
/**
 * Build an AI_MARKER impact assessment placeholder.
 * All five dimensions are marked for AI completion.
 *
 * @returns Impact assessment with AI_MARKER placeholders
 */
export function buildAiMarkerImpactAssessment(): DeepAnalysis['impactAssessment'] {
  return {
    political: AI_MARKER,
    economic: AI_MARKER,
    social: AI_MARKER,
    legal: AI_MARKER,
    geopolitical: AI_MARKER,
  };
}
 
/**
 * Build coalition metrics from voting patterns data.
 * Derives alignment scores and shift indicators for the coalition radar chart.
 *
 * @param patterns - Voting pattern data
 * @returns Coalition metrics object or null if no real patterns
 */
export function buildCoalitionMetricsFromPatterns(
  patterns: readonly VotingPattern[]
): CoalitionMetrics | null {
  const realPatterns = patterns.filter((p) => !/placeholder/i.test(p.group));
  if (realPatterns.length === 0) return null;
 
  const avgCohesion = realPatterns.reduce((sum, p) => sum + p.cohesion, 0) / realPatterns.length;
  const alignmentScore = Math.round(avgCohesion * 100);
 
  // Detect shift from cohesion spread
  const maxCohesion = Math.max(...realPatterns.map((p) => p.cohesion));
  const minCohesion = Math.min(...realPatterns.map((p) => p.cohesion));
  const spread = maxCohesion - minCohesion;
  const shiftIndicator: CoalitionMetrics['shiftIndicator'] =
    spread > 0.3 ? 'weakening' : avgCohesion > 0.7 ? 'strengthening' : 'stable';
 
  return {
    alignmentScore,
    votingBlocs: realPatterns.slice(0, 6).map((p) => ({
      group: p.group,
      alignmentScore: Math.round(p.cohesion * 100),
    })),
    shiftIndicator,
  };
}
 
/**
 * Build legislative pipeline data from WeekAheadData.
 *
 * @param weekData - Aggregated week/month data
 * @returns Legislative pipeline object
 */
export function buildPipelineFromWeekData(weekData: WeekAheadData): LegislativePipeline {
  const bottlenecked = weekData.pipeline.filter((p) => p.bottleneck === true).length;
  const total = weekData.pipeline.length;
  const onTrack = total - bottlenecked;
  const healthScore = total > 0 ? Math.round((onTrack / total) * 100) : 100;
 
  return {
    healthScore,
    onTrack,
    delayed: bottlenecked,
    blocked: 0,
    fastTracked: 0,
    total,
  };
}
 
/**
 * Build trend analytics from feed data counts using the provided periods as-is.
 *
 * @param counts - Array of activity counts per period in chronological order
 * @param period - Trend period label
 * @returns Trend analytics object or null if no data
 */
export function buildTrendFromCounts(
  counts: readonly number[],
  period: TrendAnalytics['period']
): TrendAnalytics | null {
  if (counts.length === 0 || counts.every((c) => c === 0)) return null;
 
  const periodLabels = counts.map((_, i) => {
    if (period === 'weekly') return `W${i + 1}`;
    if (period === 'monthly') return `M${i + 1}`;
    return `Q${i + 1}`;
  });
 
  const metrics = counts.map((value, i) => ({ period: periodLabels[i] ?? `${i + 1}`, value }));
 
  const last = counts.at(-1) ?? 0;
  const prev = counts.at(-2) ?? last;
  const change = prev > 0 ? ((last - prev) / prev) * 100 : 0;
  const direction: TrendAnalytics['direction'] =
    change > 5 ? 'improving' : change < -5 ? 'declining' : 'stable';
 
  return {
    period,
    metrics,
    direction,
    weekOverWeekChange: period === 'weekly' ? Math.round(change * 10) / 10 : undefined,
    monthOverMonthChange: period === 'monthly' ? Math.round(change * 10) / 10 : undefined,
  };
}
 
/**
 * Build stakeholder metrics from voting patterns.
 *
 * @param patterns - Voting patterns
 * @param anomalyCount - Number of anomalies
 * @returns Stakeholder metric array
 */
export function buildStakeholderMetricsFromVoting(
  patterns: readonly VotingPattern[],
  anomalyCount: number
): StakeholderMetric[] {
  const realPatterns = patterns.filter((p) => !/placeholder/i.test(p.group));
  const metrics: StakeholderMetric[] = realPatterns.slice(0, 4).map((p) => ({
    stakeholder: p.group,
    impactScore: Math.round(p.cohesion * 100),
    impactDirection: (p.cohesion > 0.7 ? 'positive' : p.cohesion < 0.4 ? 'negative' : 'neutral') as
      | 'positive'
      | 'negative'
      | 'neutral',
  }));
  if (anomalyCount > 0) {
    metrics.push({
      stakeholder: 'Coalition stability',
      impactScore: Math.max(0, 100 - anomalyCount * 15),
      impactDirection: anomalyCount > 3 ? 'negative' : 'neutral',
    });
  }
  return metrics;
}
 
/**
 * Build stakeholder metrics for legislative pipeline actors.
 *
 * @param pipeline - Legislative pipeline data
 * @returns Stakeholder metric array
 */
export function buildStakeholderMetricsFromPipeline(
  pipeline: LegislativePipeline | null
): StakeholderMetric[] {
  if (!pipeline || pipeline.total === 0) return [];
  return [
    {
      stakeholder: 'Legislators',
      impactScore: pipeline.healthScore,
      impactDirection:
        pipeline.healthScore > 70 ? 'positive' : pipeline.healthScore < 40 ? 'negative' : 'neutral',
    },
    {
      stakeholder: 'Pending proposals',
      impactScore: pipeline.total > 0 ? Math.round((pipeline.blocked / pipeline.total) * 100) : 0,
      impactDirection: pipeline.blocked > 0 ? 'negative' : 'neutral',
      description:
        pipeline.blocked > 0
          ? `${pipeline.blocked} blocked procedure${pipeline.blocked > 1 ? 's' : ''}`
          : undefined,
    },
  ];
}
 
/**
 * Build a stakeholder panel from stakeholder metric array.
 *
 * @param d - Localized strings
 * @param stakeholderMetrics - Stakeholder metric data
 * @returns Panel object or null
 */
export function buildStakeholderPanel(
  d: DashboardBuilderStrings,
  stakeholderMetrics: readonly StakeholderMetric[]
): DashboardPanel | null {
  if (stakeholderMetrics.length === 0) return null;
  return {
    title: d.stakeholderImpact,
    metrics: stakeholderMetrics.map((s) => ({
      label: s.stakeholder,
      value: `${s.impactScore}/100`,
      trend: (s.impactDirection === 'positive'
        ? 'up'
        : s.impactDirection === 'negative'
          ? 'down'
          : 'stable') as 'up' | 'down' | 'stable',
    })),
  };
}
 
/**
 * Resolve a direction label from trend direction.
 *
 * @param d - Localized strings
 * @param direction - Trend direction
 * @returns Localized direction label
 */
export function resolveTrendDirectionLabel(
  d: DashboardBuilderStrings,
  direction: TrendAnalytics['direction']
): string {
  if (direction === 'improving') return d.trendImproving;
  if (direction === 'declining') return d.trendDeclining;
  return d.trendStableLabel;
}
 
/**
 * Build a generic trend panel from a trend object.
 *
 * @param d - Localized strings
 * @param trend - Trend analytics
 * @param labels - Labels for x-axis
 * @param datasetLabel - Label for the dataset
 * @returns Panel object or null
 */
export function buildGenericTrendPanel(
  d: DashboardBuilderStrings,
  trend: TrendAnalytics | null,
  labels: string[],
  datasetLabel: string
): DashboardPanel | null {
  if (!trend) return null;
  return {
    title: d.trendAnalysis,
    metrics: [
      {
        label: d.trendAnalysis,
        value: resolveTrendDirectionLabel(d, trend.direction),
      },
    ],
    chart: {
      type: 'line' as const,
      title: d.activityTrendChart,
      data: {
        labels,
        datasets: [
          {
            label: datasetLabel,
            data: trend.metrics.map((m) => m.value),
            borderColor: EP_BLUE_BORDER,
            backgroundColor: EP_BLUE_TRANSPARENT,
          },
        ],
      },
    },
  };
}
 
/**
 * Build a category distribution panel showing counts per category as a bar chart.
 * Unlike `buildGenericTrendPanel`, this does not compute direction or week-over-week
 * change metrics, which are only meaningful for chronological time-series data.
 *
 * @param d - Localized strings
 * @param labels - Category labels for x-axis
 * @param counts - Counts per category (must align with labels)
 * @param datasetLabel - Label for the dataset
 * @param title - Panel title
 * @returns Panel object or null if all counts are zero
 */
export function buildCategoryDistributionPanel(
  d: DashboardBuilderStrings,
  labels: readonly string[],
  counts: readonly number[],
  datasetLabel: string,
  title: string
): DashboardPanel | null {
  if (counts.length === 0 || counts.every((c) => c === 0)) return null;
  return {
    title,
    metrics: [
      {
        label: d.trendAnalysis,
        value: `${counts.reduce((a, b) => a + b, 0)} total`,
      },
    ],
    chart: {
      type: 'bar' as const,
      title,
      data: {
        labels: [...labels],
        datasets: [
          {
            label: datasetLabel,
            data: [...counts],
            borderColor: EP_BLUE_BORDER,
            backgroundColor: EP_BLUE_TRANSPARENT,
          },
        ],
      },
    },
  };
}
 
/**
 * Build a dimension object from sets of pre-computed SWOT items.
 *
 * @param name - Dimension name
 * @param strengths - Strength items for this dimension
 * @param weaknesses - Weakness items for this dimension
 * @param opportunities - Opportunity items for this dimension
 * @param threats - Threat items for this dimension
 * @returns Typed SwotDimension
 */
export function makeDimension(
  name: SwotDimension['name'],
  strengths: readonly SwotItem[],
  weaknesses: readonly SwotItem[],
  opportunities: readonly SwotItem[],
  threats: readonly SwotItem[]
): SwotDimension {
  return { name, strengths, weaknesses, opportunities, threats };
}