All files / scripts/data-transformers calendar.ts

77.14% Statements 54/70
74.72% Branches 68/91
100% Functions 8/8
91.22% Lines 52/57

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                                                86x     83x 83x   224x 224x   53x   224x   53x 53x   53x       83x     83x 53x 53x   53x           53x             83x       2x   2x   6x                   6x 6x       6x 6x 6x 6x 6x 6x 6x 6x     2x       199x     199x 84x 84x   9x 9x 9x 9x     9x 9x       9x 9x               199x 41x 41x 41x             199x 15x 15x 15x           199x    
/**
 * @module data-transformers/calendar
 * @description Calendar event transformation and watch-point extraction.
 * Converts raw MCP calendar events into structured grid items and
 * extracts high-priority intelligence watch points.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import { escapeHtml } from '../html-utils.js';
import type { Language } from '../types/language.js';
import type { EventGridItem, WatchPoint } from '../types/article.js';
import type { RawCalendarEvent, RawDocument, ArticleContentData } from './types.js';
import {
  L,
  svSpan,
  isTodayDate,
  formatDayName,
  formatDayLabel,
  isHighPriority,
} from './helpers.js';
 
export function transformCalendarToEventGrid(events: RawCalendarEvent[], lang: Language = 'en'): EventGridItem[] {
  if (!events || events.length === 0) return [];
 
  // Group events by date
  const eventsByDate: Record<string, RawCalendarEvent[]> = {};
  events.forEach(event => {
    // Extract date from various field formats (MCP responses use 'from', 'start', or 'datum')
    let dateStr = event.datum || event.from || event.start;
    if (dateStr) {
      // Extract just the date part if it's an ISO timestamp
      dateStr = dateStr.split('T')[0];
    }
    if (!dateStr) return;
 
    Eif (!eventsByDate[dateStr]) {
      eventsByDate[dateStr] = [];
    }
    eventsByDate[dateStr]!.push(event);
  });
 
  // Sort dates
  const sortedDates = Object.keys(eventsByDate).sort();
 
  // Convert to grid format
  const eventGrid: EventGridItem[] = sortedDates.map(date => {
    const dateObj = new Date(date);
    const isTodayFlag = isTodayDate(dateObj);
 
    return {
      date: date,
      dayName: formatDayName(dateObj, lang),
      dayNumber: dateObj.getDate().toString(),
      dayLabel: formatDayLabel(dateObj, lang),
      isToday: isTodayFlag,
      items: (eventsByDate[date] ?? []).map(event => ({
        time: event.tid || event.time || 'Expected',
        title: event.rubrik || event.titel || event.title || 'Event'
      }))
    };
  });
 
  return eventGrid;
}
 
export function extractTopics(documents: RawDocument[]): string[] {
  const topics = new Set<string>();
 
  documents.forEach(doc => {
    // Extract from document type
    Iif (doc.doktyp) {
      switch (doc.doktyp) {
        case 'mot': topics.add('motions'); break;
        case 'prop': topics.add('propositions'); break;
        case 'bet': topics.add('committee-reports'); break;
        case 'skr': topics.add('government-communication'); break;
      }
    }
 
    // Extract from organ/committee
    Eif (doc.organ) {
      topics.add(`${doc.organ.toLowerCase()}-committee`);
    }
 
    // Extract from title keywords
    const title = (doc.titel || doc.rubrik || '').toLowerCase();
    Iif (title.includes('eu')) topics.add('eu');
    Iif (title.includes('försvar')) topics.add('defense');
    Iif (title.includes('ekonomi')) topics.add('economy');
    Iif (title.includes('miljö')) topics.add('environment');
    Iif (title.includes('migration')) topics.add('migration');
    Iif (title.includes('utbildning')) topics.add('education');
    Iif (title.includes('vård')) topics.add('healthcare');
  });
 
  return Array.from(topics).slice(0, 10); // Max 10 topics
}
 
export function extractWatchPoints(data: ArticleContentData, lang: Language = 'en'): WatchPoint[] {
  const watchPoints: WatchPoint[] = [];
 
  // From calendar events
  if (data.events) {
    const highPriorityEvents = data.events.filter(isHighPriority);
    highPriorityEvents.forEach(event => {
      // Derive dayName from event date if not present
      const rawDate = event.datum || event.from || event.start;
      const dateOnly = rawDate ? rawDate.split('T')[0] ?? rawDate : '';
      const dayName = event.dayName || (dateOnly ? formatDayName(new Date(dateOnly), lang) : '');
      const eventTitle = event.title || event.titel || 'Event';
 
      // Mark Swedish API titles for LLM translation post-processing
      const escapedEventTitle = escapeHtml(eventTitle);
      const titleDisplay = (event.titel && !event.title)
        ? svSpan(escapedEventTitle, lang)
        : escapedEventTitle;
 
      const monitorVal = L(lang, 'monitorDev');
      watchPoints.push({
        title: dayName ? `${dayName}: ${titleDisplay}` : titleDisplay,
        description: event.description || (typeof monitorVal === 'string' ? monitorVal : '')
      });
    });
  }
 
  // From committee reports
  if (data.reports && data.reports.length > 0) {
    const debatesVal = L(lang, 'committeeDebates');
    const debatesDescFn = L(lang, 'committeeDebatesDesc') as string | ((n: number) => string);
    watchPoints.push({
      title: typeof debatesVal === 'string' ? debatesVal : '',
      description: typeof debatesDescFn === 'function' ? debatesDescFn(data.reports.length) : ''
    });
  }
 
  // From propositions
  if (data.propositions && data.propositions.length > 0) {
    const proposalsVal = L(lang, 'govProposals');
    const proposalsDescFn = L(lang, 'govProposalsDesc') as string | ((n: number) => string);
    watchPoints.push({
      title: typeof proposalsVal === 'string' ? proposalsVal : '',
      description: typeof proposalsDescFn === 'function' ? proposalsDescFn(data.propositions.length) : ''
    });
  }
 
  return watchPoints.slice(0, 5); // Max 5 watch points
}