All files / src/generators/strategies weekly-review-strategy.ts

97.36% Statements 74/76
82.14% Branches 46/56
100% Functions 7/7
97.22% Lines 70/72

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                                                                                                                                8x                           13x   13x 12x   13x 12x   13x 12x   13x 12x 12x       13x                   7x   7x 6x 7x 6x 7x 6x 7x 7x 6x   7x 1x     6x 7x 7x 6x 6x                       7x 7x 6x   7x 6x   7x 7x 6x   7x                       3x 3x 3x   3x 3x   3x       3x                           17x   17x                                         3x 3x     3x               3x                                       11x                 11x               11x       11x       11x           11x 11x 11x 11x           11x 11x                           13x 13x       13x 13x 13x 13x 13x                     8x  
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Generators/Strategies/WeeklyReviewStrategy
 * @description Article strategy for the Week In Review article type.
 * Fetches voting records, voting patterns, voting anomalies, and parliamentary
 * questions from the past 7 days, then renders a retrospective analysis article.
 */
 
import type { EuropeanParliamentMCPClient } from '../../mcp/ep-mcp-client.js';
import { ArticleCategory } from '../../types/index.js';
import type {
  LanguageCode,
  DateRange,
  VotingRecord,
  VotingPattern,
  VotingAnomaly,
  MotionsQuestion,
  EPFeedData,
} from '../../types/index.js';
import { WEEKLY_REVIEW_TITLES, getLocalizedString } from '../../constants/languages.js';
import {
  fetchVotingRecords,
  fetchVotingPatterns,
  fetchMotionsAnomalies,
  fetchParliamentaryQuestionsForMotions,
  fetchEPFeedData,
} from '../pipeline/fetch-stage.js';
import { generateMotionsContent, buildAdoptedTextsSection } from '../motions-content.js';
import { buildDeepAnalysisSection } from '../deep-analysis-content.js';
import {
  buildVotingAnalysis,
  buildVotingSwot,
  buildVotingDashboard,
  buildVotingMindmap,
} from '../analysis-builders.js';
import { buildSwotSection } from '../swot-content.js';
import { buildDashboardSection } from '../dashboard-content.js';
import { buildIntelligenceMindmapSection } from '../mindmap-content.js';
import type { ArticleStrategy, ArticleData, ArticleMetadata } from './article-strategy.js';
import { pl } from '../../utils/metadata-utils.js';
 
// ─── Data payload ─────────────────────────────────────────────────────────────
 
/** Data fetched and pre-processed by {@link WeeklyReviewStrategy} */
export interface WeeklyReviewArticleData extends ArticleData {
  /** Review period date range */
  readonly dateRange: DateRange;
  /** Voting records from the review period */
  readonly votingRecords: readonly VotingRecord[];
  /** Voting patterns analysis */
  readonly votingPatterns: readonly VotingPattern[];
  /** Detected voting anomalies */
  readonly anomalies: readonly VotingAnomaly[];
  /** Parliamentary questions from the period */
  readonly questions: readonly MotionsQuestion[];
  /** Start date string for display */
  readonly dateFromStr: string;
  /** EP feed data for enrichment (when available) */
  readonly feedData?: EPFeedData | undefined;
}
 
/** Base keywords shared by all Weekly Review articles */
const WEEKLY_REVIEW_BASE_KEYWORDS = [
  'European Parliament',
  'weekly review',
  'voting records',
  'parliamentary activity',
] as const;
 
/**
 * Extract content-aware keywords from weekly review data.
 *
 * @param data - Weekly review article data payload
 * @returns Deduplicated keyword array
 */
function buildWeeklyReviewKeywords(data: WeeklyReviewArticleData): string[] {
  const keywords: string[] = [...WEEKLY_REVIEW_BASE_KEYWORDS];
 
  for (const r of data.votingRecords.slice(0, 5)) {
    Eif (r.title) keywords.push(r.title.slice(0, 60));
  }
  for (const a of data.anomalies.slice(0, 3)) {
    Eif (a.type) keywords.push(a.type);
  }
  for (const q of data.questions.slice(0, 3)) {
    Eif (q.topic) keywords.push(q.topic);
  }
  if (data.feedData?.adoptedTexts) {
    for (const text of data.feedData.adoptedTexts.slice(0, 3)) {
      Eif (text.title) keywords.push(text.title.slice(0, 60));
    }
  }
 
  return [...new Set(keywords)];
}
 
/**
 * Build a content-aware description from weekly review data.
 *
 * @param data - Weekly review article data payload
 * @returns SEO-friendly description (≤ 200 chars)
 */
function buildWeeklyReviewDescription(data: WeeklyReviewArticleData): string {
  const parts: string[] = [];
 
  if (data.votingRecords.length > 0)
    parts.push(`${pl(data.votingRecords.length, 'vote', 'votes')} analysed`);
  if (data.anomalies.length > 0)
    parts.push(pl(data.anomalies.length, 'voting anomaly', 'voting anomalies'));
  if (data.questions.length > 0)
    parts.push(`${pl(data.questions.length, 'question', 'questions')} tabled`);
  const adoptedCount = data.feedData?.adoptedTexts?.length ?? 0;
  if (adoptedCount > 0)
    parts.push(`${adoptedCount} adopted ${adoptedCount === 1 ? 'text' : 'texts'}`);
 
  if (parts.length === 0) {
    return `European Parliament weekly review for ${data.dateRange.start} to ${data.dateRange.end}.`;
  }
 
  const highlight = data.votingRecords[0]?.title ?? '';
  const base = `EP week in review (${data.dateRange.start}–${data.dateRange.end}): ${parts.join(', ')}`;
  if (highlight) {
    const full = `${base}. Key: ${highlight}`;
    return full.length > 200 ? full.slice(0, 197) + '...' : full;
  }
  return base.length > 200 ? base.slice(0, 197) + '...' : base;
}
 
/**
 * Build a content-aware title suffix from weekly review data counts.
 *
 * @param data - Weekly review article data payload
 * @returns Short suffix for the title, or empty string
 */
function buildWeeklyReviewTitleSuffix(data: WeeklyReviewArticleData): string {
  const parts: string[] = [];
  if (data.votingRecords.length > 0) {
    parts.push(pl(data.votingRecords.length, 'Vote', 'Votes'));
  }
  if (data.anomalies.length > 0) {
    parts.push(pl(data.anomalies.length, 'Anomaly', 'Anomalies'));
  }
  const adoptedCount = data.feedData?.adoptedTexts?.length ?? 0;
  if (adoptedCount > 0) {
    parts.push(pl(adoptedCount, 'Text', 'Texts'));
  }
  return parts.join(', ');
}
 
// ─── Date-range helper ────────────────────────────────────────────────────────
 
/**
 * Compute the review period covering the 7 days ending on `baseDate`.
 *
 * @param baseDate - ISO 8601 publication date (YYYY-MM-DD)
 * @returns Date range covering the past 7 days
 */
function computeWeeklyReviewDateRange(baseDate: string): DateRange {
  const end = new Date(`${baseDate}T00:00:00Z`);
  const start = new Date(end);
  start.setUTCDate(end.getUTCDate() - 7);
 
  const startParts = start.toISOString().split('T');
  const endParts = end.toISOString().split('T');
 
  Iif (!startParts[0] || !endParts[0]) {
    throw new Error('Invalid date format generated in computeWeeklyReviewDateRange');
  }
 
  return {
    start: startParts[0],
    end: endParts[0],
  };
}
 
// ─── Strategy implementation ──────────────────────────────────────────────────
 
/**
 * Article strategy for {@link ArticleCategory.WEEK_IN_REVIEW}.
 * Fetches voting records, anomalies, patterns, and questions for the
 * past 7 days and builds a retrospective analysis article.
 */
export class WeeklyReviewStrategy implements ArticleStrategy<WeeklyReviewArticleData> {
  readonly type = ArticleCategory.WEEK_IN_REVIEW;
 
  readonly requiredMCPTools = [
    'get_voting_records',
    'analyze_voting_patterns',
    'detect_voting_anomalies',
    'get_parliamentary_questions',
    'get_adopted_texts_feed',
    'get_procedures_feed',
    'get_events_feed',
  ] as const;
 
  /**
   * Fetch weekly review data from MCP.
   *
   * @param client - MCP client or null
   * @param date - ISO 8601 publication date
   * @returns Populated weekly review data payload
   */
  async fetchData(
    client: EuropeanParliamentMCPClient | null,
    date: string
  ): Promise<WeeklyReviewArticleData> {
    const dateRange = computeWeeklyReviewDateRange(date);
    console.log(`  📊 Weekly review range: ${dateRange.start} to ${dateRange.end}`);
 
    // Fetch voting data and EP feed data in parallel
    const [votingRecords, votingPatterns, anomalies, questions, feedData] = await Promise.all([
      fetchVotingRecords(client, dateRange.start, dateRange.end),
      fetchVotingPatterns(client, dateRange.start, dateRange.end),
      fetchMotionsAnomalies(client, dateRange.start, dateRange.end),
      fetchParliamentaryQuestionsForMotions(client, dateRange.start, dateRange.end),
      fetchEPFeedData(client, 'one-week', dateRange),
    ]);
 
    return {
      date,
      dateRange,
      dateFromStr: dateRange.start,
      votingRecords,
      votingPatterns,
      anomalies,
      questions,
      feedData,
    };
  }
 
  /**
   * Build the weekly review HTML body for the specified language.
   *
   * @param data - Weekly review data payload
   * @param lang - Target language code used for editorial strings
   * @returns Article HTML body
   */
  buildContent(data: WeeklyReviewArticleData, lang: LanguageCode): string {
    const base = generateMotionsContent(
      data.dateRange.start,
      data.dateRange.end,
      [...data.votingRecords],
      [...data.votingPatterns],
      [...data.anomalies],
      [...data.questions],
      lang
    );
    const analysis = buildVotingAnalysis(
      data.dateRange.start,
      data.dateRange.end,
      data.votingRecords,
      data.votingPatterns,
      data.anomalies,
      data.questions
    );
    const deepSection = buildDeepAnalysisSection(analysis, lang, 'en');
 
    // Enrich with adopted texts from feed data when available
    const adoptedTextsHtml =
      data.feedData && data.feedData.adoptedTexts.length > 0
        ? buildAdoptedTextsSection(data.feedData.adoptedTexts, lang)
        : '';
 
    const mindmapData = buildVotingMindmap(
      data.votingRecords,
      data.votingPatterns,
      data.anomalies,
      lang
    );
    const mindmapSection = buildIntelligenceMindmapSection(mindmapData, lang);
    const swotData = buildVotingSwot(data.votingRecords, data.votingPatterns, data.anomalies, lang);
    const swotSection = buildSwotSection(swotData, lang);
    const dashboardData = buildVotingDashboard(
      data.votingRecords,
      data.votingPatterns,
      data.anomalies,
      lang
    );
    const dashboardSection = buildDashboardSection(dashboardData, lang);
    return base.replace(
      '<!-- /article-content -->',
      adoptedTextsHtml + deepSection + mindmapSection + swotSection + dashboardSection
    );
  }
 
  /**
   * Return language-specific metadata for the weekly review article.
   *
   * @param data - Weekly review data payload
   * @param lang - Target language code
   * @returns Localised metadata
   */
  getMetadata(data: WeeklyReviewArticleData, lang: LanguageCode): ArticleMetadata {
    const titleFn = getLocalizedString(WEEKLY_REVIEW_TITLES, lang);
    const { title: baseTitle, subtitle: baseSubtitle } = titleFn(
      data.dateRange.start,
      data.dateRange.end
    );
    const suffix = lang === 'en' ? buildWeeklyReviewTitleSuffix(data) : '';
    const title = suffix ? `${baseTitle} — ${suffix}` : baseTitle;
    const description = lang === 'en' ? buildWeeklyReviewDescription(data) : '';
    const subtitle = description || baseSubtitle;
    return {
      title,
      subtitle,
      keywords: buildWeeklyReviewKeywords(data),
      category: ArticleCategory.WEEK_IN_REVIEW,
      sources: [],
    };
  }
}
 
/** Singleton instance for use by the strategy registry */
export const weeklyReviewStrategy = new WeeklyReviewStrategy();