All files / src/clients/ep documentClient.ts

94.54% Statements 104/110
84.26% Branches 75/89
95.83% Functions 23/24
94.62% Lines 88/93

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                                                                        295x           83x                             13x 13x 13x 13x 4x           4x     13x 1x   13x                     13x 13x 13x 13x   49x         13x 1x 1x 2x     13x       13x                                             13x 13x 13x     13x 13x   13x         13x 13x 13x 13x   49x 13x   13x                       13x 13x                                       4x 4x 4x         4x   4x 3x 5x 4x                       4x 4x 4x         4x   4x 3x 5x 4x                     3x 3x   3x           2x 4x 3x                     4x 4x   4x         3x 5x 4x                       5x 5x 5x         5x   5x 4x 5x 5x               4x 2x       2x               4x 2x       2x               4x 2x       2x               4x 2x       2x               4x 2x       2x      
/**
 * @fileoverview Document sub-client for European Parliament API
 *
 * Handles all document-related API calls: plenary documents,
 * committee documents, plenary session documents, external documents,
 * and the generic documents search endpoint.
 *
 * @module clients/ep/documentClient
 */
 
import { auditLogger } from '../../utils/auditLogger.js';
import type {
  LegislativeDocument,
  PaginatedResponse,
} from '../../types/europeanParliament.js';
import {
  transformDocument as _transformDocument,
} from './transformers.js';
import {
  BaseEPClient,
  APIError,
  type EPClientConfig,
  type EPSharedResources,
  type JSONLDResponse,
} from './baseClient.js';
 
// ─── Document Client ──────────────────────────────────────────────────────────
 
/**
 * Sub-client for document EP API endpoints.
 *
 * @extends BaseEPClient
 * @public
 */
export class DocumentClient extends BaseEPClient {
  constructor(config: EPClientConfig = {}, shared?: EPSharedResources) {
    super(config, shared);
  }
 
  // ─── Transform helpers ────────────────────────────────────────────────────
 
  private transformDocument(apiData: Record<string, unknown>): LegislativeDocument {
    return _transformDocument(apiData);
  }
 
  // ─── Private helpers ──────────────────────────────────────────────────────
 
  /**
   * Builds EP API parameters for document search.
   * @private
   */
  private buildDocumentSearchParams(params: {
    documentType?: string;
    dateFrom?: string;
    limit?: number;
    offset?: number;
  }): Record<string, unknown> {
    const apiParams: Record<string, unknown> = {};
    Eif (params.limit !== undefined) apiParams['limit'] = params.limit;
    if (params.offset !== undefined) apiParams['offset'] = params.offset;
    if (params.documentType !== undefined && params.documentType !== '') {
      const typeMap: Record<string, string> = {
        REPORT: 'REPORT_PLENARY',
        AMENDMENT: 'AMENDMENT_LIST',
        RESOLUTION: 'RESOLUTION_MOTION',
        ADOPTED: 'TEXT_ADOPTED',
      };
      apiParams['work-type'] =
        typeMap[params.documentType.toUpperCase()] ?? params.documentType;
    }
    if (params.dateFrom !== undefined && params.dateFrom !== '') {
      apiParams['year'] = params.dateFrom.substring(0, 4);
    }
    return apiParams;
  }
 
  /**
   * Applies client-side keyword, committee, and date-range filters to documents.
   * @private
   */
  private filterDocuments(
    documents: LegislativeDocument[],
    params: { keyword?: string; committee?: string; dateTo?: string }
  ): LegislativeDocument[] {
    let filtered = documents;
    Eif (params.keyword !== undefined && params.keyword !== '') {
      const keywordLower = params.keyword.toLowerCase();
      filtered = filtered.filter(
        (d) =>
          d.title.toLowerCase().includes(keywordLower) ||
          d.summary?.toLowerCase().includes(keywordLower) === true ||
          d.id.toLowerCase().includes(keywordLower)
      );
    }
    if (params.committee !== undefined && params.committee !== '') {
      const committeeLower = params.committee.toLowerCase();
      filtered = filtered.filter(
        (d) => d.committee?.toLowerCase().includes(committeeLower) === true
      );
    }
    Iif (params.dateTo !== undefined && params.dateTo !== '') {
      const dateTo = params.dateTo;
      filtered = filtered.filter((d) => d.date <= dateTo);
    }
    return filtered;
  }
 
  // ─── Public methods ───────────────────────────────────────────────────────
 
  /**
   * Searches legislative documents by keyword, type, date, and committee.
   *
   * **EP API Endpoint:** `GET /documents`
   *
   * @param params - keyword, documentType, dateFrom, dateTo, committee, limit, offset
   * @returns Paginated legislative documents list
   * @security Audit logged per GDPR Article 30
   */
  async searchDocuments(params: {
    keyword: string;
    documentType?: string;
    dateFrom?: string;
    dateTo?: string;
    committee?: string;
    limit?: number;
    offset?: number;
  }): Promise<PaginatedResponse<LegislativeDocument>> {
    const action = 'search_documents';
    try {
      Iif (params.keyword.trim() === '') {
        throw new APIError('keyword is required and must not be empty', 400);
      }
      const requestedLimit = params.limit ?? 20;
      const currentOffset = params.offset ?? 0;
 
      const apiParams = this.buildDocumentSearchParams(params);
      // Always apply the resolved limit/offset so the server page size matches
      // the pagination metadata we return (callers may omit them, in which case
      // buildDocumentSearchParams would leave them unset and the server default
      // could differ from our requestedLimit/currentOffset defaults).
      apiParams['limit'] = requestedLimit;
      apiParams['offset'] = currentOffset;
      const response = await this.get<JSONLDResponse>('documents', apiParams);
      const pageSize = response.data.length;
 
      let documents = response.data.map((item) => this.transformDocument(item));
      documents = this.filterDocuments(documents, params);
 
      const result: PaginatedResponse<LegislativeDocument> = {
        data: documents,
        // total/hasMore are derived from the unfiltered server page size, not from
        // `documents.length` after client-side filtering.  This means `hasMore` can
        // be true even when the filtered result set is empty — callers should
        // continue paginating until `data` is empty or `hasMore` is false.
        total: currentOffset + pageSize,
        limit: requestedLimit,
        offset: currentOffset,
        hasMore: pageSize === requestedLimit,
      };
 
      auditLogger.logDataAccess(action, params, result.data.length);
      return result;
    } catch (error) {
      auditLogger.logError(
        action,
        params,
        error instanceof Error ? error.message : 'Unknown error'
      );
      throw error;
    }
  }
 
  /**
   * Returns plenary documents.
   * **EP API Endpoint:** `GET /plenary-documents`
   */
  async getPlenaryDocuments(params: {
    year?: number;
    limit?: number;
    offset?: number;
  } = {}): Promise<PaginatedResponse<LegislativeDocument>> {
    const limit = params.limit ?? 50;
    const offset = params.offset ?? 0;
    const apiParams: Record<string, unknown> = {
      format: 'application/ld+json',
      offset,
      limit,
    };
    if (params.year !== undefined) apiParams['year'] = params.year;
 
    const response = await this.get<JSONLDResponse>('plenary-documents', apiParams);
    const items = Array.isArray(response.data) ? response.data : [];
    const docs = items.map((item) => this.transformDocument(item));
    return { data: docs, total: docs.length + offset, limit, offset, hasMore: docs.length === limit };
  }
 
  /**
   * Returns committee documents.
   * **EP API Endpoint:** `GET /committee-documents`
   */
  async getCommitteeDocuments(params: {
    year?: number;
    limit?: number;
    offset?: number;
  } = {}): Promise<PaginatedResponse<LegislativeDocument>> {
    const limit = params.limit ?? 50;
    const offset = params.offset ?? 0;
    const apiParams: Record<string, unknown> = {
      format: 'application/ld+json',
      offset,
      limit,
    };
    if (params.year !== undefined) apiParams['year'] = params.year;
 
    const response = await this.get<JSONLDResponse>('committee-documents', apiParams);
    const items = Array.isArray(response.data) ? response.data : [];
    const docs = items.map((item) => this.transformDocument(item));
    return { data: docs, total: docs.length + offset, limit, offset, hasMore: docs.length === limit };
  }
 
  /**
   * Returns plenary session documents.
   * **EP API Endpoint:** `GET /plenary-session-documents`
   */
  async getPlenarySessionDocuments(params: {
    limit?: number;
    offset?: number;
  } = {}): Promise<PaginatedResponse<LegislativeDocument>> {
    const limit = params.limit ?? 50;
    const offset = params.offset ?? 0;
 
    const response = await this.get<JSONLDResponse>('plenary-session-documents', {
      format: 'application/ld+json',
      offset,
      limit,
    });
 
    const items = Array.isArray(response.data) ? response.data : [];
    const docs = items.map((item) => this.transformDocument(item));
    return { data: docs, total: docs.length + offset, limit, offset, hasMore: docs.length === limit };
  }
 
  /**
   * Returns all Plenary Session Document Items.
   * **EP API Endpoint:** `GET /plenary-session-documents-items`
   */
  async getPlenarySessionDocumentItems(params: {
    limit?: number;
    offset?: number;
  } = {}): Promise<PaginatedResponse<LegislativeDocument>> {
    const limit = params.limit ?? 50;
    const offset = params.offset ?? 0;
 
    const response = await this.get<JSONLDResponse>(
      'plenary-session-documents-items',
      { format: 'application/ld+json', offset, limit }
    );
 
    const items = Array.isArray(response.data) ? response.data : [];
    const docs = items.map((item) => this.transformDocument(item));
    return { data: docs, total: docs.length + offset, limit, offset, hasMore: docs.length === limit };
  }
 
  /**
   * Returns all External Documents.
   * **EP API Endpoint:** `GET /external-documents`
   */
  async getExternalDocuments(params: {
    year?: number;
    limit?: number;
    offset?: number;
  } = {}): Promise<PaginatedResponse<LegislativeDocument>> {
    const limit = params.limit ?? 50;
    const offset = params.offset ?? 0;
    const apiParams: Record<string, unknown> = {
      format: 'application/ld+json',
      offset,
      limit,
    };
    if (params.year !== undefined) apiParams['year'] = params.year;
 
    const response = await this.get<JSONLDResponse>('external-documents', apiParams);
    const items = Array.isArray(response.data) ? response.data : [];
    const docs = items.map((item) => this.transformDocument(item));
    return { data: docs, total: docs.length + offset, limit, offset, hasMore: docs.length === limit };
  }
 
  /**
   * Returns a single document by ID.
   * **EP API Endpoint:** `GET /documents/{doc-id}`
   */
  async getDocumentById(docId: string): Promise<LegislativeDocument> {
    if (docId.trim() === '') throw new APIError('Document ID is required', 400);
    const response = await this.get<Record<string, unknown>>(
      `documents/${docId}`,
      { format: 'application/ld+json' }
    );
    return this.transformDocument(response);
  }
 
  /**
   * Returns a single plenary document by ID.
   * **EP API Endpoint:** `GET /plenary-documents/{doc-id}`
   */
  async getPlenaryDocumentById(docId: string): Promise<LegislativeDocument> {
    if (docId.trim() === '') throw new APIError('Document ID is required', 400);
    const response = await this.get<Record<string, unknown>>(
      `plenary-documents/${docId}`,
      { format: 'application/ld+json' }
    );
    return this.transformDocument(response);
  }
 
  /**
   * Returns a single plenary session document by ID.
   * **EP API Endpoint:** `GET /plenary-session-documents/{doc-id}`
   */
  async getPlenarySessionDocumentById(docId: string): Promise<LegislativeDocument> {
    if (docId.trim() === '') throw new APIError('Document ID is required', 400);
    const response = await this.get<Record<string, unknown>>(
      `plenary-session-documents/${docId}`,
      { format: 'application/ld+json' }
    );
    return this.transformDocument(response);
  }
 
  /**
   * Returns a single committee document by ID.
   * **EP API Endpoint:** `GET /committee-documents/{doc-id}`
   */
  async getCommitteeDocumentById(docId: string): Promise<LegislativeDocument> {
    if (docId.trim() === '') throw new APIError('Document ID is required', 400);
    const response = await this.get<Record<string, unknown>>(
      `committee-documents/${docId}`,
      { format: 'application/ld+json' }
    );
    return this.transformDocument(response);
  }
 
  /**
   * Returns a single external document by ID.
   * **EP API Endpoint:** `GET /external-documents/{doc-id}`
   */
  async getExternalDocumentById(docId: string): Promise<LegislativeDocument> {
    if (docId.trim() === '') throw new APIError('Document ID is required', 400);
    const response = await this.get<Record<string, unknown>>(
      `external-documents/${docId}`,
      { format: 'application/ld+json' }
    );
    return this.transformDocument(response);
  }
}