From 9432d01135e3c4396bf2a2d7d76a7913e2c4c513 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 10 Jun 2026 19:17:20 +0200 Subject: [PATCH 01/22] add news module with business logic and models --- service/src/main/inse/main.py | 2 + service/src/main/inse/news/__init__.py | 0 service/src/main/inse/news/logic.py | 118 +++++++++++++++++++++++++ service/src/main/inse/news/model.py | 25 ++++++ service/src/main/inse/news/service.py | 74 ++++++++++++++++ service/src/main/inse/tags.py | 1 + 6 files changed, 220 insertions(+) create mode 100644 service/src/main/inse/news/__init__.py create mode 100644 service/src/main/inse/news/logic.py create mode 100644 service/src/main/inse/news/model.py create mode 100644 service/src/main/inse/news/service.py diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index a1e4614e..0ec0a2a4 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -16,6 +16,7 @@ from inse.topics.service import router as topics_service_router from inse.works.service import router as works_service_router from inse.persons.service import router as persons_service_router from inse.funders.service import router as funders_service_router +from inse.news.service import router as news_service_router from . import config from .service import router as service_router @@ -40,6 +41,7 @@ app.include_router(topics_service_router) app.include_router(works_service_router) app.include_router(persons_service_router) app.include_router(funders_service_router) +app.include_router(news_service_router) app.include_router(service_router) app.include_router(account_router) diff --git a/service/src/main/inse/news/__init__.py b/service/src/main/inse/news/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py new file mode 100644 index 00000000..4171ab96 --- /dev/null +++ b/service/src/main/inse/news/logic.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Business logic for the "aktuell" news index on the INSE cluster. +""" + +import logging + +from fastapi import HTTPException +from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR + +from ..integrations import elasticsearch +from .model import NewsArticle, NewsArticleDetail, NewsPage + +logger = logging.getLogger(__name__) + + +def get_news_page(page: int, page_size: int) -> NewsPage: + offset = (page - 1) * page_size + + response = _run_search( + query={"match_all": {}}, + source=["date", "maintitle", "author", "url"], + size=page_size, + offset=offset, + sort=[{"date_full": "desc"}], + ) + + return _build_page(response, page, page_size) + + +def search_news(query_text: str, page: int, page_size: int) -> NewsPage: + offset = (page - 1) * page_size + + response = _run_search( + query={"match": {"full_content": query_text}}, + source=["date", "maintitle", "author", "url"], + size=page_size, + offset=offset, + sort=None, + ) + + return _build_page(response, page, page_size) + + +def get_news_by_id(news_id: str) -> NewsArticleDetail: + try: + response = elasticsearch.get( + index="aktuell", + doc_id=news_id, + source=["date", "maintitle", "author", "url", "full_content"], + cluster="inse", + ) + except Exception as exc: + logger.exception("Abruf des News-Artikels fehlgeschlagen.") + raise HTTPException( + status_code=HTTP_500_INTERNAL_SERVER_ERROR, + detail="Etwas ist schiefgelaufen.", + ) from exc + + source = response.get("_source", {}) + + return NewsArticleDetail( + id=response.get("_id"), + date=source.get("date"), + maintitle=source.get("maintitle"), + author=source.get("author"), + url=source.get("url"), + full_content=source.get("full_content"), + ) + + +def _run_search(query: dict, source: list, size: int, offset: int, sort) -> dict: + try: + return elasticsearch.search( + index="aktuell", + query=query, + source=source, + size=size, + offset=offset, + sort=sort, + track_total_hits=True, + cluster="inse", + ) + except Exception as exc: + logger.exception("Elasticsearch-Anfrage an Index 'aktuell' fehlgeschlagen.") + raise HTTPException( + status_code=HTTP_500_INTERNAL_SERVER_ERROR, + detail="Etwas ist schiefgelaufen.", + ) from exc + + +def _build_page(response: dict, page: int, page_size: int) -> NewsPage: + hits_section = response.get("hits", {}) + total = hits_section.get("total", {}).get("value", 0) + + articles = [] + for hit in hits_section.get("hits", []): + articles.append(_parse_hit(hit)) + + return NewsPage( + total=total, + page=page, + page_size=page_size, + results=articles, + ) + + +def _parse_hit(hit: dict) -> NewsArticle: + source = hit.get("_source", {}) + + return NewsArticle( + id=hit.get("_id"), + date=source.get("date"), + maintitle=source.get("maintitle"), + author=source.get("author"), + url=source.get("url"), + ) diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py new file mode 100644 index 00000000..1fee0b8f --- /dev/null +++ b/service/src/main/inse/news/model.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from typing import List, Optional + +from pydantic import BaseModel + + +class NewsArticle(BaseModel): + id: str + date: Optional[str] = None + maintitle: Optional[str] = None + author: Optional[str] = None + url: Optional[str] = None + + +class NewsArticleDetail(NewsArticle): + full_content: Optional[str] = None + + +class NewsPage(BaseModel): + total: int + page: int + page_size: int + results: List[NewsArticle] diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py new file mode 100644 index 00000000..d93a10a8 --- /dev/null +++ b/service/src/main/inse/news/service.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +REST API for the "aktuell" news index. +""" + +from typing import Annotated + +from fastapi import APIRouter +from fastapi import Path +from fastapi import Query + +from inse.tags import Tags +from . import logic +from .model import NewsArticleDetail, NewsPage + +router = APIRouter(prefix="/api/news", tags=[Tags.NEWS]) + + +@router.get( + "", + operation_id="listNews", + response_model=NewsPage, + response_model_exclude_none=True, + summary="Returns a page of news articles, newest first.", + tags=[Tags.NEWS], +) +def list_news( + page: Annotated[ + int, Query(description="Page number (1-based).", ge=1) + ] = 1, + page_size: Annotated[ + int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100) + ] = 10, +): + return logic.get_news_page(page, page_size) + + +@router.get( + "/search", + operation_id="searchNews", + response_model=NewsPage, + response_model_exclude_none=True, + summary="Searches news articles by full text (full_content).", + tags=[Tags.NEWS], +) +def search_news( + query: Annotated[ + str, Query(description="Search term, matched against the full text (full_content).", min_length=1) + ], + page: Annotated[ + int, Query(description="Page number (1-based).", ge=1) + ] = 1, + page_size: Annotated[ + int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100) + ] = 10, +): + return logic.search_news(query, page, page_size) + + +@router.get( + "/{news_id}", + operation_id="getNewsById", + response_model=NewsArticleDetail, + response_model_exclude_none=True, + summary="Returns a single news article including its full content.", + tags=[Tags.NEWS], +) +def get_news_by_id( + news_id: Annotated[ + str, Path(description="The unique id of the news article (Elasticsearch _id).") + ], +): + return logic.get_news_by_id(news_id) diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index 21c6b03c..9142f3eb 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -7,3 +7,4 @@ class Tags(Enum): INSTITUTIONS = "Institutions" TOPICS = "Topics" WORKS = "Works" + NEWS = "News" From 7442a56b0a9061b6770b547fbffdd6a102eab7df Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Thu, 11 Jun 2026 21:40:26 +0200 Subject: [PATCH 02/22] feat(news-tab): add news tab and details page to person overview --- service/src/main/inse/news/logic.py | 4 +- service/src/main/inse/news/service.py | 5 +- webapp/src/app/app.routes.ts | 15 ++ .../news-detail/news-detail.component.html | 92 +++++++ .../news-detail/news-detail.component.scss | 226 ++++++++++++++++++ .../news-detail/news-detail.component.ts | 107 +++++++++ .../person-news/person-news.component.html | 76 ++++++ .../person-news/person-news.component.scss | 156 ++++++++++++ .../person-news/person-news.component.ts | 145 +++++++++++ .../app/modules/person/person.component.ts | 1 + 10 files changed, 824 insertions(+), 3 deletions(-) create mode 100644 webapp/src/app/modules/news-detail/news-detail.component.html create mode 100644 webapp/src/app/modules/news-detail/news-detail.component.scss create mode 100644 webapp/src/app/modules/news-detail/news-detail.component.ts create mode 100644 webapp/src/app/modules/person-news/person-news.component.html create mode 100644 webapp/src/app/modules/person-news/person-news.component.scss create mode 100644 webapp/src/app/modules/person-news/person-news.component.ts diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 4171ab96..46866d0b 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -15,7 +15,7 @@ from .model import NewsArticle, NewsArticleDetail, NewsPage logger = logging.getLogger(__name__) -def get_news_page(page: int, page_size: int) -> NewsPage: +def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPage: offset = (page - 1) * page_size response = _run_search( @@ -23,7 +23,7 @@ def get_news_page(page: int, page_size: int) -> NewsPage: source=["date", "maintitle", "author", "url"], size=page_size, offset=offset, - sort=[{"date_full": "desc"}], + sort=[{"date_full": sort_order}], ) return _build_page(response, page, page_size) diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py index d93a10a8..0ed5fe6d 100644 --- a/service/src/main/inse/news/service.py +++ b/service/src/main/inse/news/service.py @@ -32,8 +32,11 @@ def list_news( page_size: Annotated[ int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100) ] = 10, + sort_order: Annotated[ + str, Query(alias="sortOrder", description="Sort order: 'desc' (newest first) or 'asc' (oldest first).", pattern="^(asc|desc)$") + ] = "desc", ): - return logic.get_news_page(page, page_size) + return logic.get_news_page(page, page_size, sort_order) @router.get( diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index c19c5b60..def295c4 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -60,6 +60,14 @@ export const routes: Routes = [ return scalarChanged || topicsChanged; }, }, + { + path: 'news/:id', + canActivate: [userGuard], + loadComponent: () => + import('./modules/news-detail/news-detail.component').then( + (mod) => mod.NewsDetailComponent, + ), + }, { path: 'publication/:publicationId', canActivate: [userGuard], @@ -135,6 +143,13 @@ export const routes: Routes = [ (mod) => mod.PersonFundingComponent, ), }, + { + path: 'news', + loadComponent: () => + import('./modules/person-news/person-news.component').then( + (mod) => mod.PersonNewsComponent, + ), + }, ], }, { diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html new file mode 100644 index 00000000..6e930151 --- /dev/null +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -0,0 +1,92 @@ +
+ + + @if (loading) { +
+ +

Nachricht wird geladen...

+
+ } @else if (notFound || !article) { +
+ search_off +

Nachricht nicht gefunden

+

Der Artikel konnte nicht geladen werden.

+ Zur Personensuche +
+ } @else { +
+
+
+
+ @if (article.author) { + {{ article.author }} + } + @if (article.date) { + {{ formatDate(article.date) }} + } +
+

{{ article.maintitle || 'Kein Titel' }}

+
+ +
+ @if (article.full_content) { +

{{ article.full_content }}

+ } @else { +

Kein Inhalt verfügbar.

+ } +
+ + @if (article.url) { +
+ + open_in_new + Originalartikel öffnen + +
+ } +
+ + +
+ } +
diff --git a/webapp/src/app/modules/news-detail/news-detail.component.scss b/webapp/src/app/modules/news-detail/news-detail.component.scss new file mode 100644 index 00000000..71b7519e --- /dev/null +++ b/webapp/src/app/modules/news-detail/news-detail.component.scss @@ -0,0 +1,226 @@ +.detail-page { + max-width: 1200px; + margin: 0 auto; + padding: 28px 32px 64px; +} + +.back-link { + display: inline-flex; + align-items: center; + gap: 6px; + background: none; + border: none; + cursor: pointer; + font-size: 14px; + color: var(--sg-text-muted); + padding: 0; + margin-bottom: 32px; + + &:hover { + color: var(--sg-text); + } + + mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } +} + +.state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 16px; + padding: 80px 0; + text-align: center; + color: var(--sg-text-muted); + + mat-icon { + font-size: 48px; + width: 48px; + height: 48px; + } + + p { + margin: 0; + } +} + +.error-state h2 { + margin: 0; +} + +.detail-layout { + display: grid; + grid-template-columns: 1fr 280px; + gap: 40px; + align-items: start; +} + +main { + min-width: 0; +} + +.hero { + margin-bottom: 32px; +} + +.eyebrow { + display: flex; + gap: 12px; + font-size: 13px; + color: var(--sg-text-muted); + margin-bottom: 12px; + + span + span::before { + content: '·'; + margin-right: 12px; + } +} + +.article-heading { + margin: 0; + font-size: 28px; + font-weight: 700; + line-height: 1.3; +} + +.article-body { + font-size: 15px; + line-height: 1.7; + color: var(--sg-text); +} + +.content { + margin: 0; + white-space: pre-wrap; +} + +.placeholder { + margin: 0; + color: var(--sg-text-muted); + font-style: italic; +} + +.article-actions { + margin-top: 32px; +} + +.sidebar { + display: flex; + flex-direction: column; + gap: 16px; + position: sticky; + top: 24px; +} + +.sidebar-card { + padding: 20px; + border: 1px solid #d7e4ff; + border-radius: 16px; + background: #ffffff; + box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04); + + h3 { + display: flex; + align-items: center; + gap: 8px; + margin: 0 0 14px; + font-size: 14px; + font-weight: 600; + color: var(--sg-text); + + mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + color: var(--sg-text-muted); + } + } +} + +.person-list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.person-item { + display: grid; + grid-template-columns: 38px minmax(0, 1fr); + gap: 11px; + align-items: center; + padding: 12px; + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-muted); +} + +.avatar { + display: grid; + place-items: center; + width: 38px; + height: 38px; + border-radius: 50%; + background: #e5ecfb; + color: var(--sg-text); + font-size: 15px; + font-weight: 700; + text-transform: uppercase; +} + +.person-name { + color: var(--sg-text); + font-size: 13px; + font-weight: 700; +} + +.chip-list { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.topic-chip { + display: inline-flex; + align-items: center; + padding: 6px 12px; + border: 1px solid var(--topic-border); + border-radius: 8px; + background: var(--topic-bg); + color: var(--topic-color); + font-size: 12px; + font-weight: 500; + line-height: 1.25; +} + +.purple { + --topic-border: #d8cafe; + --topic-bg: #f6f0ff; + --topic-color: #7255d9; +} + +.blue { + --topic-border: #bdd4ff; + --topic-bg: #f0f6ff; + --topic-color: #0b63ce; +} + +.green { + --topic-border: #bdebcf; + --topic-bg: #effaf3; + --topic-color: #24834f; +} + +.orange { + --topic-border: #ffd796; + --topic-bg: #fff7e8; + --topic-color: #c67500; +} + +.pink { + --topic-border: #ffc7d7; + --topic-bg: #fff1f5; + --topic-color: #d12f61; +} diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts new file mode 100644 index 00000000..3bbca4d1 --- /dev/null +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -0,0 +1,107 @@ +import { Component, DestroyRef, OnInit, inject } from '@angular/core'; +import { Location, NgClass } from '@angular/common'; +import { HttpClient } from '@angular/common/http'; +import { ActivatedRoute, RouterLink } from '@angular/router'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; + +import { WorksService } from '../../api'; + +interface NewsArticleDetail { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; + full_content?: string | null; +} + +@Component({ + selector: 'app-news-detail', + imports: [ + MatButtonModule, + MatIconModule, + MatProgressSpinnerModule, + RouterLink, + NgClass, + ], + templateUrl: './news-detail.component.html', + styleUrl: './news-detail.component.scss', +}) +export class NewsDetailComponent implements OnInit { + private readonly destroyRef = inject(DestroyRef); + private readonly route = inject(ActivatedRoute); + private readonly httpClient = inject(HttpClient); + private readonly worksService = inject(WorksService); + private readonly location = inject(Location); + + article: NewsArticleDetail | null = null; + loading = false; + notFound = false; + + readonly mentionedPersons = [ + 'Prof. Dr. Anna Müller', + 'Dr. Hans Schmidt', + 'Dr. Lena Weber', + ]; + + readonly relevantTopics = [ + 'Künstliche Intelligenz', + 'Maschinelles Lernen', + 'Digitalisierung', + 'Datenwissenschaft', + ]; + + private readonly chipColors = ['purple', 'blue', 'green', 'orange', 'pink']; + + chipColor(index: number): string { + return this.chipColors[index % this.chipColors.length]; + } + + ngOnInit(): void { + this.route.paramMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + const id = params.get('id'); + if (id) { + this.fetchArticle(id); + } + }); + } + + navigateBack(): void { + this.location.back(); + } + + formatDate(dateStr?: string | null): string { + if (!dateStr) return '-'; + const date = new Date(dateStr); + if (isNaN(date.getTime())) return dateStr; + return new Intl.DateTimeFormat('de-DE', { + day: '2-digit', + month: 'long', + year: 'numeric', + }).format(date); + } + + private fetchArticle(id: string): void { + this.loading = true; + this.notFound = false; + const basePath = this.worksService.configuration.basePath ?? ''; + this.httpClient + .get(`${basePath}/api/news/${encodeURIComponent(id)}`) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: (article) => { + this.article = article; + this.loading = false; + }, + error: () => { + this.notFound = true; + this.loading = false; + }, + }); + } +} diff --git a/webapp/src/app/modules/person-news/person-news.component.html b/webapp/src/app/modules/person-news/person-news.component.html new file mode 100644 index 00000000..d5477d07 --- /dev/null +++ b/webapp/src/app/modules/person-news/person-news.component.html @@ -0,0 +1,76 @@ +
+
+
Nachrichten
+

Aktuelle Nachrichten zu dieser Person.

+
+ +
+ + search + + + + + + Neueste zuerst + Älteste zuerst + + +
+ +
+ @if (loading) { +
+ +
+ } + + + + + + + + + + + + + + + + + + + +
Titel + {{ + article.maintitle || 'Kein Titel' + }} + Autor + {{ article.author || '-' }} + Datum + {{ formatDate(article.date) }} +
+ + @if (!loading && articles.length === 0) { +
Keine Nachrichten gefunden.
+ } +
+ + +
diff --git a/webapp/src/app/modules/person-news/person-news.component.scss b/webapp/src/app/modules/person-news/person-news.component.scss new file mode 100644 index 00000000..68a1899f --- /dev/null +++ b/webapp/src/app/modules/person-news/person-news.component.scss @@ -0,0 +1,156 @@ +.page { + padding: 28px 32px 42px; + max-width: 100%; + margin: 0 auto; +} + +h6 { + margin: 0 0 6px; + font-size: 22px; + line-height: 1.2; + font-weight: 700; +} + +.page > div:first-child p { + margin: 0; + color: var(--sg-text-muted); + font-size: 14px; +} + +.news-toolbar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 12px; + padding-top: 10px; + padding-bottom: 25px; +} + +.search-field { + max-width: 480px; +} + +::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper { + display: none; +} + +::ng-deep .news-toolbar .mat-mdc-text-field-wrapper { + height: 42px; + background: #fff; + border-radius: var(--sg-radius-sm); +} + +::ng-deep .news-toolbar .mat-mdc-form-field-infix { + min-height: unset; + height: 42px; + padding: 0; + display: flex; + align-items: center; +} + +::ng-deep .news-toolbar .mdc-notched-outline__leading, +::ng-deep .news-toolbar .mdc-notched-outline__notch, +::ng-deep .news-toolbar .mdc-notched-outline__trailing { + border-color: #d9e2f0; +} + +::ng-deep .news-toolbar input.mat-mdc-input-element { + color: var(--sg-text); + font-size: 14px; +} + +::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder { + color: var(--sg-text-muted); + opacity: 1; + font-size: 14px; +} + +.sort-field { + width: 180px; +} + +.table-wrap { + position: relative; + overflow-x: auto; +} + +table { + width: 100%; + min-width: 600px; + border-collapse: separate; + border-spacing: 0 10px; + background: transparent; + box-shadow: none; +} + +.article-title { + display: inline-block; + max-width: 520px; + line-height: 1.35; + color: var(--sg-text); + font-size: 14px; + font-weight: 700; + text-decoration: none; + + &:hover { + color: var(--sg-text); + text-decoration: underline; + } +} + +.loading { + position: absolute; + inset: 0; + z-index: 1; + display: grid; + place-items: center; + background: rgba(255, 255, 255, 0.65); +} + +.empty-state { + padding: 28px; + text-align: center; + color: rgba(0, 0, 0, 0.6); + background: transparent; +} + +::ng-deep .mat-mdc-header-cell { + color: var(--sg-text-muted); + font-size: 12px; + font-weight: 700; +} + +::ng-deep .mat-mdc-row { + height: 72px; +} + +::ng-deep .mat-mdc-cell { + color: var(--sg-text); + border-bottom-color: var(--sg-border); + font-size: 13px; +} + +mat-paginator { + background: transparent; +} + +.table-footer { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 66px; + padding: 0 22px 0 28px; + color: var(--sg-text-muted); + font-size: 13px; +} + +@media (max-width: 600px) { + .page { + padding: 16px; + } + + .table-footer { + align-items: stretch; + flex-direction: column; + } +} diff --git a/webapp/src/app/modules/person-news/person-news.component.ts b/webapp/src/app/modules/person-news/person-news.component.ts new file mode 100644 index 00000000..7c69ef2c --- /dev/null +++ b/webapp/src/app/modules/person-news/person-news.component.ts @@ -0,0 +1,145 @@ +import { + Component, + DestroyRef, + OnInit, + ViewChild, + inject, +} from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { ActivatedRoute, RouterLink } from '@angular/router'; +import { MatIconModule } from '@angular/material/icon'; +import { MatSelectModule } from '@angular/material/select'; +import { + MatPaginator, + MatPaginatorModule, + PageEvent, +} from '@angular/material/paginator'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatTableModule } from '@angular/material/table'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; + +import { WorksService } from '../../api'; +import { PaginationService } from '../../shared/services/pagination.service'; + +interface NewsArticle { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; +} + +interface NewsPage { + total: number; + page: number; + page_size: number; + results: NewsArticle[]; +} + +const ARTICLE_CAP = 100; + +@Component({ + selector: 'app-person-news', + imports: [ + MatIconModule, + MatSelectModule, + MatFormFieldModule, + MatInputModule, + MatPaginatorModule, + MatProgressSpinnerModule, + MatTableModule, + ReactiveFormsModule, + RouterLink, + ], + templateUrl: './person-news.component.html', + styleUrl: './person-news.component.scss', +}) +export class PersonNewsComponent implements OnInit { + @ViewChild(MatPaginator) paginator?: MatPaginator; + private readonly destroyRef = inject(DestroyRef); + private readonly route = inject(ActivatedRoute); + private readonly httpClient = inject(HttpClient); + private readonly worksService = inject(WorksService); + readonly paginationService = inject(PaginationService); + + readonly searchControl = new FormControl('', { nonNullable: true }); + + displayedColumns = ['maintitle', 'author', 'date']; + private allArticles: NewsArticle[] = []; + articles: NewsArticle[] = []; + total = 0; + loading = false; + currentPageIndex = 0; + sortOrder: 'desc' | 'asc' = 'desc'; + + ngOnInit(): void { + this.route.parent?.paramMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { + this.load(); + }); + } + + load(): void { + this.loading = true; + const params = new HttpParams() + .set('page', 1) + .set('pageSize', ARTICLE_CAP) + .set('sortOrder', this.sortOrder); + + const basePath = this.worksService.configuration.basePath ?? ''; + this.httpClient + .get(`${basePath}/api/news`, { params }) + .subscribe({ + next: (page) => { + this.allArticles = page.results ?? []; + this.total = this.allArticles.length; + this.currentPageIndex = 0; + this.updatePage(); + this.loading = false; + }, + error: () => { + this.loading = false; + }, + }); + } + + onPage(event: PageEvent): void { + this.paginationService.selection = event.pageSize; + this.currentPageIndex = event.pageIndex; + this.updatePage(); + } + + formatDate(dateStr?: string | null): string { + if (!dateStr) return '-'; + const date = new Date(dateStr); + if (isNaN(date.getTime())) return dateStr; + return new Intl.DateTimeFormat('de-DE').format(date); + } + + articleRange(): string { + if (this.total === 0) return 'Keine Nachrichten gefunden'; + const start = this.currentPageIndex * this.paginationService.selection + 1; + const end = Math.min( + start + this.paginationService.selection - 1, + this.total, + ); + return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`; + } + + onSortChange(order: 'desc' | 'asc'): void { + this.sortOrder = order; + this.load(); + } + + private updatePage(): void { + const start = this.currentPageIndex * this.paginationService.selection; + this.articles = this.allArticles.slice( + start, + start + this.paginationService.selection, + ); + } +} diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 2dd189ec..46a8c068 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -176,6 +176,7 @@ export class PersonComponent { { label: 'Netzwerk', path: 'network', disabled: false }, { label: 'Gründungen', path: 'foundings', disabled: true }, { label: 'Förderungen', path: 'funding', disabled: false }, + { label: 'Nachrichten', path: 'news', disabled: false }, ]; onInterestingTagClick(selection: { id: string; name: string }): void { From 977ac97241d7b57d0e04388b57316ed97695852d Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Mon, 15 Jun 2026 17:46:20 +0200 Subject: [PATCH 03/22] add page news --- webapp/src/app/app.routes.ts | 6 + .../src/app/modules/news/news.component.html | 76 ++++++++ .../src/app/modules/news/news.component.scss | 156 +++++++++++++++++ webapp/src/app/modules/news/news.component.ts | 165 ++++++++++++++++++ .../shared/ui/app-menu/app-menu.component.ts | 6 + 5 files changed, 409 insertions(+) create mode 100644 webapp/src/app/modules/news/news.component.html create mode 100644 webapp/src/app/modules/news/news.component.scss create mode 100644 webapp/src/app/modules/news/news.component.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index c6c2707c..0dd9d706 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -64,6 +64,12 @@ export const routes: Routes = [ return scalarChanged || topicsChanged; }, }, + { + path: 'news', + canActivate: [userGuard], + loadComponent: () => + import('./modules/news/news.component').then((mod) => mod.NewsComponent), + }, { path: 'news/:id', canActivate: [userGuard], diff --git a/webapp/src/app/modules/news/news.component.html b/webapp/src/app/modules/news/news.component.html new file mode 100644 index 00000000..5004b3e5 --- /dev/null +++ b/webapp/src/app/modules/news/news.component.html @@ -0,0 +1,76 @@ +
+
+
Nachrichten
+

Aktuelle Nachrichten aus Campus-Aktuell.

+
+ +
+ + search + + + + + + Neueste zuerst + Älteste zuerst + + +
+ +
+ @if (loading) { +
+ +
+ } + + + + + + + + + + + + + + + + + + + +
Titel + {{ + article.maintitle || 'Kein Titel' + }} + Autor + {{ article.author || '-' }} + Datum + {{ formatDate(article.date) }} +
+ + @if (!loading && articles.length === 0) { +
Keine Nachrichten gefunden.
+ } +
+ + +
diff --git a/webapp/src/app/modules/news/news.component.scss b/webapp/src/app/modules/news/news.component.scss new file mode 100644 index 00000000..68a1899f --- /dev/null +++ b/webapp/src/app/modules/news/news.component.scss @@ -0,0 +1,156 @@ +.page { + padding: 28px 32px 42px; + max-width: 100%; + margin: 0 auto; +} + +h6 { + margin: 0 0 6px; + font-size: 22px; + line-height: 1.2; + font-weight: 700; +} + +.page > div:first-child p { + margin: 0; + color: var(--sg-text-muted); + font-size: 14px; +} + +.news-toolbar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 12px; + padding-top: 10px; + padding-bottom: 25px; +} + +.search-field { + max-width: 480px; +} + +::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper { + display: none; +} + +::ng-deep .news-toolbar .mat-mdc-text-field-wrapper { + height: 42px; + background: #fff; + border-radius: var(--sg-radius-sm); +} + +::ng-deep .news-toolbar .mat-mdc-form-field-infix { + min-height: unset; + height: 42px; + padding: 0; + display: flex; + align-items: center; +} + +::ng-deep .news-toolbar .mdc-notched-outline__leading, +::ng-deep .news-toolbar .mdc-notched-outline__notch, +::ng-deep .news-toolbar .mdc-notched-outline__trailing { + border-color: #d9e2f0; +} + +::ng-deep .news-toolbar input.mat-mdc-input-element { + color: var(--sg-text); + font-size: 14px; +} + +::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder { + color: var(--sg-text-muted); + opacity: 1; + font-size: 14px; +} + +.sort-field { + width: 180px; +} + +.table-wrap { + position: relative; + overflow-x: auto; +} + +table { + width: 100%; + min-width: 600px; + border-collapse: separate; + border-spacing: 0 10px; + background: transparent; + box-shadow: none; +} + +.article-title { + display: inline-block; + max-width: 520px; + line-height: 1.35; + color: var(--sg-text); + font-size: 14px; + font-weight: 700; + text-decoration: none; + + &:hover { + color: var(--sg-text); + text-decoration: underline; + } +} + +.loading { + position: absolute; + inset: 0; + z-index: 1; + display: grid; + place-items: center; + background: rgba(255, 255, 255, 0.65); +} + +.empty-state { + padding: 28px; + text-align: center; + color: rgba(0, 0, 0, 0.6); + background: transparent; +} + +::ng-deep .mat-mdc-header-cell { + color: var(--sg-text-muted); + font-size: 12px; + font-weight: 700; +} + +::ng-deep .mat-mdc-row { + height: 72px; +} + +::ng-deep .mat-mdc-cell { + color: var(--sg-text); + border-bottom-color: var(--sg-border); + font-size: 13px; +} + +mat-paginator { + background: transparent; +} + +.table-footer { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 66px; + padding: 0 22px 0 28px; + color: var(--sg-text-muted); + font-size: 13px; +} + +@media (max-width: 600px) { + .page { + padding: 16px; + } + + .table-footer { + align-items: stretch; + flex-direction: column; + } +} diff --git a/webapp/src/app/modules/news/news.component.ts b/webapp/src/app/modules/news/news.component.ts new file mode 100644 index 00000000..a6df56f2 --- /dev/null +++ b/webapp/src/app/modules/news/news.component.ts @@ -0,0 +1,165 @@ +import { Component, DestroyRef, OnInit, inject } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; +import { MatIconModule } from '@angular/material/icon'; +import { MatSelectModule } from '@angular/material/select'; +import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatTableModule } from '@angular/material/table'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; + +import { WorksService } from '../../api'; +import { PaginationService } from '../../shared/services/pagination.service'; + +interface NewsArticle { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; +} + +interface NewsPage { + total: number; + page: number; + page_size: number; + results: NewsArticle[]; +} + +type SortOrder = 'desc' | 'asc'; +const DEFAULT_SORT_ORDER: SortOrder = 'desc'; + +@Component({ + selector: 'app-news', + imports: [ + MatIconModule, + MatSelectModule, + MatFormFieldModule, + MatInputModule, + MatPaginatorModule, + MatProgressSpinnerModule, + MatTableModule, + ReactiveFormsModule, + RouterLink, + ], + templateUrl: './news.component.html', + styleUrl: './news.component.scss', +}) +export class NewsComponent implements OnInit { + private readonly destroyRef = inject(DestroyRef); + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + private readonly httpClient = inject(HttpClient); + private readonly worksService = inject(WorksService); + readonly paginationService = inject(PaginationService); + + readonly searchControl = new FormControl('', { nonNullable: true }); + + displayedColumns = ['maintitle', 'author', 'date']; + articles: NewsArticle[] = []; + total = 0; + loading = false; + + currentPage = 1; + sortOrder: SortOrder = DEFAULT_SORT_ORDER; + + ngOnInit(): void { + this.route.queryParamMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + this.currentPage = this.parsePage(params.get('page')); + this.paginationService.selection = this.parsePageSize( + params.get('pageSize'), + ); + this.sortOrder = this.parseSortOrder(params.get('sortOrder')); + this.load(); + }); + } + + load(): void { + this.loading = true; + const params = new HttpParams() + .set('page', this.currentPage) + .set('pageSize', this.paginationService.selection) + .set('sortOrder', this.sortOrder); + + const basePath = this.worksService.configuration.basePath ?? ''; + this.httpClient + .get(`${basePath}/api/news`, { params }) + .subscribe({ + next: (page) => { + this.articles = page.results ?? []; + this.total = page.total ?? 0; + this.loading = false; + }, + error: () => { + this.articles = []; + this.total = 0; + this.loading = false; + }, + }); + } + + onPage(event: PageEvent): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + page: event.pageIndex + 1, + pageSize: event.pageSize, + }, + queryParamsHandling: 'merge', + }); + } + + onSortChange(order: SortOrder): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + sortOrder: order, + page: 1, + }, + queryParamsHandling: 'merge', + }); + } + + formatDate(dateStr?: string | null): string { + if (!dateStr) return '-'; + const date = new Date(dateStr); + if (isNaN(date.getTime())) return dateStr; + return new Intl.DateTimeFormat('de-DE').format(date); + } + + articleRange(): string { + if (this.total === 0) return 'Keine Nachrichten gefunden'; + const pageSize = this.paginationService.selection; + const start = (this.currentPage - 1) * pageSize + 1; + const end = Math.min(start + this.articles.length - 1, this.total); + return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`; + } + + private parsePage(value: string | null): number { + const page = Number.parseInt(value ?? '', 10); + if (Number.isNaN(page) || page < 1) { + return 1; + } + return page; + } + + private parsePageSize(value: string | null): number { + const pageSize = Number.parseInt(value ?? '', 10); + if (this.paginationService.options.includes(pageSize)) { + return pageSize; + } + return 10; + } + + private parseSortOrder(value: string | null): SortOrder { + if (value === 'asc' || value === 'desc') { + return value; + } + return DEFAULT_SORT_ORDER; + } +} diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 371cedb4..7e63b2a3 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -35,6 +35,12 @@ export class AppMenuComponent { queryParams: { institutionName: 'University of Duisburg-Essen' }, disabled: false, }, + { + label: 'News', + icon: 'newspaper', + route: '/news', + disabled: false, + }, ]; constructor( From bd39e16d9bcaa62ca8d3d6b4c633a701e64367dc Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 15 Jun 2026 22:35:38 +0200 Subject: [PATCH 04/22] feat(news): wire full-text search to global news page and client-side filter to person news tab --- .../src/app/modules/news/news.component.html | 26 ++++-- webapp/src/app/modules/news/news.component.ts | 84 ++++++++++++++----- .../person-news/person-news.component.html | 8 +- .../person-news/person-news.component.ts | 37 +++++++- 4 files changed, 122 insertions(+), 33 deletions(-) diff --git a/webapp/src/app/modules/news/news.component.html b/webapp/src/app/modules/news/news.component.html index 5004b3e5..05ca40a8 100644 --- a/webapp/src/app/modules/news/news.component.html +++ b/webapp/src/app/modules/news/news.component.html @@ -13,14 +13,16 @@ placeholder="Nachrichten durchsuchen..." /> - - - Neueste zuerst - Älteste zuerst - - + @if (!isSearching) { + + + Neueste zuerst + Älteste zuerst + + + }
@@ -59,7 +61,13 @@ @if (!loading && articles.length === 0) { -
Keine Nachrichten gefunden.
+
+ @if (isSearching) { + Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden. + } @else { + Keine Nachrichten gefunden. + } +
}
diff --git a/webapp/src/app/modules/news/news.component.ts b/webapp/src/app/modules/news/news.component.ts index a6df56f2..e6990dbb 100644 --- a/webapp/src/app/modules/news/news.component.ts +++ b/webapp/src/app/modules/news/news.component.ts @@ -10,6 +10,7 @@ import { MatTableModule } from '@angular/material/table'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { debounceTime, distinctUntilChanged } from 'rxjs'; import { WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; @@ -66,6 +67,10 @@ export class NewsComponent implements OnInit { currentPage = 1; sortOrder: SortOrder = DEFAULT_SORT_ORDER; + get isSearching(): boolean { + return this.searchControl.value.trim().length > 0; + } + ngOnInit(): void { this.route.queryParamMap .pipe(takeUntilDestroyed(this.destroyRef)) @@ -75,32 +80,73 @@ export class NewsComponent implements OnInit { params.get('pageSize'), ); this.sortOrder = this.parseSortOrder(params.get('sortOrder')); + this.searchControl.setValue(params.get('q') ?? '', { + emitEvent: false, + }); this.load(); }); + + this.searchControl.valueChanges + .pipe( + debounceTime(300), + distinctUntilChanged(), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((query) => { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { q: query.trim() || null, page: 1 }, + queryParamsHandling: 'merge', + }); + }); } load(): void { this.loading = true; - const params = new HttpParams() - .set('page', this.currentPage) - .set('pageSize', this.paginationService.selection) - .set('sortOrder', this.sortOrder); - + const query = this.searchControl.value.trim(); const basePath = this.worksService.configuration.basePath ?? ''; - this.httpClient - .get(`${basePath}/api/news`, { params }) - .subscribe({ - next: (page) => { - this.articles = page.results ?? []; - this.total = page.total ?? 0; - this.loading = false; - }, - error: () => { - this.articles = []; - this.total = 0; - this.loading = false; - }, - }); + + if (query) { + const params = new HttpParams() + .set('query', query) + .set('page', this.currentPage) + .set('pageSize', this.paginationService.selection); + + this.httpClient + .get(`${basePath}/api/news/search`, { params }) + .subscribe({ + next: (page) => { + this.articles = page.results ?? []; + this.total = page.total ?? 0; + this.loading = false; + }, + error: () => { + this.articles = []; + this.total = 0; + this.loading = false; + }, + }); + } else { + const params = new HttpParams() + .set('page', this.currentPage) + .set('pageSize', this.paginationService.selection) + .set('sortOrder', this.sortOrder); + + this.httpClient + .get(`${basePath}/api/news`, { params }) + .subscribe({ + next: (page) => { + this.articles = page.results ?? []; + this.total = page.total ?? 0; + this.loading = false; + }, + error: () => { + this.articles = []; + this.total = 0; + this.loading = false; + }, + }); + } } onPage(event: PageEvent): void { diff --git a/webapp/src/app/modules/person-news/person-news.component.html b/webapp/src/app/modules/person-news/person-news.component.html index d5477d07..b4f717db 100644 --- a/webapp/src/app/modules/person-news/person-news.component.html +++ b/webapp/src/app/modules/person-news/person-news.component.html @@ -59,7 +59,13 @@ @if (!loading && articles.length === 0) { -
Keine Nachrichten gefunden.
+
+ @if (isSearching) { + Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden. + } @else { + Keine Nachrichten gefunden. + } +
} diff --git a/webapp/src/app/modules/person-news/person-news.component.ts b/webapp/src/app/modules/person-news/person-news.component.ts index 7c69ef2c..230f51a2 100644 --- a/webapp/src/app/modules/person-news/person-news.component.ts +++ b/webapp/src/app/modules/person-news/person-news.component.ts @@ -20,6 +20,7 @@ import { MatTableModule } from '@angular/material/table'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { debounceTime, distinctUntilChanged } from 'rxjs'; import { WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; @@ -69,18 +70,33 @@ export class PersonNewsComponent implements OnInit { displayedColumns = ['maintitle', 'author', 'date']; private allArticles: NewsArticle[] = []; + private filteredArticles: NewsArticle[] = []; articles: NewsArticle[] = []; total = 0; loading = false; currentPageIndex = 0; sortOrder: 'desc' | 'asc' = 'desc'; + get isSearching(): boolean { + return this.searchControl.value.trim().length > 0; + } + ngOnInit(): void { this.route.parent?.paramMap .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe(() => { this.load(); }); + + this.searchControl.valueChanges + .pipe( + debounceTime(300), + distinctUntilChanged(), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe(() => { + this.applyFilter(); + }); } load(): void { @@ -96,9 +112,7 @@ export class PersonNewsComponent implements OnInit { .subscribe({ next: (page) => { this.allArticles = page.results ?? []; - this.total = this.allArticles.length; - this.currentPageIndex = 0; - this.updatePage(); + this.applyFilter(); this.loading = false; }, error: () => { @@ -135,9 +149,24 @@ export class PersonNewsComponent implements OnInit { this.load(); } + private applyFilter(): void { + const query = this.searchControl.value.trim().toLowerCase(); + this.filteredArticles = query + ? this.allArticles.filter( + (a) => + a.maintitle?.toLowerCase().includes(query) || + a.author?.toLowerCase().includes(query), + ) + : this.allArticles; + this.total = this.filteredArticles.length; + this.currentPageIndex = 0; + this.paginator?.firstPage(); + this.updatePage(); + } + private updatePage(): void { const start = this.currentPageIndex * this.paginationService.selection; - this.articles = this.allArticles.slice( + this.articles = this.filteredArticles.slice( start, start + this.paginationService.selection, ); From 379f94ddc7d81b684d9b3920d0d213685b1f5a09 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 17 Jun 2026 13:06:41 +0200 Subject: [PATCH 05/22] feat(backend/news): combine data from aktuell_postproc with news model --- service/src/main/inse/news/logic.py | 28 ++++++++++++++++++++++++++++ service/src/main/inse/news/model.py | 2 ++ 2 files changed, 30 insertions(+) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 46866d0b..aad2e896 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -60,6 +60,8 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: source = response.get("_source", {}) + relevant, authors = _get_postproc_labels(news_id) + return NewsArticleDetail( id=response.get("_id"), date=source.get("date"), @@ -67,9 +69,35 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: author=source.get("author"), url=source.get("url"), full_content=source.get("full_content"), + relevant=relevant, + authors=authors, ) +def _get_postproc_labels(news_id: str) -> tuple[bool, list]: + try: + response = elasticsearch.search( + index="aktuell_postproc", + query={"term": {"news_id.keyword": news_id}}, + source=["relevant", "authors"], + size=1, + cluster="inse", + ) + except Exception: + logger.exception(f"Postproc-Lookup for {news_id} failed.") + return False, [] + + hits = response.get("hits", {}).get("hits", []) + if not hits: + return False, [] + + postproc_source = hits[0].get("_source", {}) + relevant = bool(postproc_source.get("relevant", 0)) + authors = postproc_source.get("authors") or [] + + return relevant, authors + + def _run_search(query: dict, source: list, size: int, offset: int, sort) -> dict: try: return elasticsearch.search( diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index 1fee0b8f..74a37542 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -16,6 +16,8 @@ class NewsArticle(BaseModel): class NewsArticleDetail(NewsArticle): full_content: Optional[str] = None + relevant: bool = False + authors: List[str] = [] class NewsPage(BaseModel): From 23da3e44ba8b4b876d8df02682c70ef722b2d4c3 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 17 Jun 2026 13:08:46 +0200 Subject: [PATCH 06/22] feat(frontend/news_aritcle): show extracted authors --- .../modules/news-detail/news-detail.component.html | 14 +++++++++----- .../modules/news-detail/news-detail.component.ts | 8 ++------ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index 6e930151..38ece59d 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -64,11 +64,15 @@ Erwähnte Personen
- @for (person of mentionedPersons; track person) { -
-
{{ person.charAt(0) }}
- {{ person }} -
+ @if (article.authors && article.authors.length) { + @for (person of article.authors; track person) { +
+
{{ person.charAt(0) }}
+ {{ person }} +
+ } + } @else { +

Keine erwähnten Personen gefunden.

}
diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts index 3bbca4d1..5c51b52c 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.ts +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -16,6 +16,8 @@ interface NewsArticleDetail { author?: string | null; url?: string | null; full_content?: string | null; + relevant?: boolean; + authors?: string[]; } @Component({ @@ -41,12 +43,6 @@ export class NewsDetailComponent implements OnInit { loading = false; notFound = false; - readonly mentionedPersons = [ - 'Prof. Dr. Anna Müller', - 'Dr. Hans Schmidt', - 'Dr. Lena Weber', - ]; - readonly relevantTopics = [ 'Künstliche Intelligenz', 'Maschinelles Lernen', From b6618e030e3e77ab3023def950ddee34ee2bc1b7 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 17 Jun 2026 13:18:08 +0200 Subject: [PATCH 07/22] feat: add info about article relevance to the news page --- service/src/main/inse/news/logic.py | 6 ++-- service/src/main/inse/news/model.py | 2 +- .../news-detail/news-detail.component.html | 17 +++++++++ .../news-detail/news-detail.component.scss | 35 +++++++++++++++++++ 4 files changed, 56 insertions(+), 4 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index aad2e896..06334728 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -74,7 +74,7 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: ) -def _get_postproc_labels(news_id: str) -> tuple[bool, list]: +def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]: try: response = elasticsearch.search( index="aktuell_postproc", @@ -85,11 +85,11 @@ def _get_postproc_labels(news_id: str) -> tuple[bool, list]: ) except Exception: logger.exception(f"Postproc-Lookup for {news_id} failed.") - return False, [] + return None, [] hits = response.get("hits", {}).get("hits", []) if not hits: - return False, [] + return None, [] postproc_source = hits[0].get("_source", {}) relevant = bool(postproc_source.get("relevant", 0)) diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index 74a37542..ad34577f 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -16,7 +16,7 @@ class NewsArticle(BaseModel): class NewsArticleDetail(NewsArticle): full_content: Optional[str] = None - relevant: bool = False + relevant: Optional[bool] = None authors: List[str] = [] diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index 38ece59d..ce499e8d 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -33,6 +33,23 @@ }

{{ article.maintitle || 'Kein Titel' }}

+ + @if (article.relevant === true) { + + check_circle + Relevant + + } @else if (article.relevant === false) { + + cancel + Nicht relevant + + } @else { + + help + Relevanz nicht bestimmt + + }
diff --git a/webapp/src/app/modules/news-detail/news-detail.component.scss b/webapp/src/app/modules/news-detail/news-detail.component.scss index 71b7519e..02101fda 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.scss +++ b/webapp/src/app/modules/news-detail/news-detail.component.scss @@ -87,6 +87,41 @@ main { line-height: 1.3; } +.relevance-badge { + display: inline-flex; + align-items: center; + gap: 6px; + margin-top: 14px; + padding: 5px 12px; + border-radius: 999px; + font-size: 13px; + font-weight: 600; + + mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + + &.is-relevant { + background: #effaf3; + border: 1px solid #bdebcf; + color: #24834f; + } + + &.not-relevant { + background: var(--sg-surface-muted); + border: 1px solid #e2e2e2; + color: var(--sg-text-muted); + } + + &.undetermined { + background: #fff7e8; + border: 1px solid #ffd796; + color: #c67500; + } +} + .article-body { font-size: 15px; line-height: 1.7; From 11d20546b1631a506511634926c1df21d922abf2 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 17 Jun 2026 20:15:16 +0200 Subject: [PATCH 08/22] WIP: show news in author overview --- service/src/main/inse/news/logic.py | 61 ++++++++ service/src/main/inse/news/service.py | 28 ++++ .../person-news/person-news.component.ts | 142 ++++++++++++------ 3 files changed, 189 insertions(+), 42 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 06334728..526510de 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -10,6 +10,7 @@ from fastapi import HTTPException from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR from ..integrations import elasticsearch +from ..persons.logic import get_author_name_by_id from .model import NewsArticle, NewsArticleDetail, NewsPage logger = logging.getLogger(__name__) @@ -42,6 +43,66 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage: return _build_page(response, page, page_size) +def get_news_by_author( + author_id: str, + page: int = 1, + page_size: int = 10, + sort_order: str = "desc", + query_text: str | None = None, +) -> NewsPage: + + author_name = get_author_name_by_id(author_id) + if not author_name: + return _empty_page(page, page_size) + + news_ids = _find_news_ids_for_author(author_name) + if not news_ids: + return _empty_page(page, page_size) + + es_query = {"bool": {"filter": [{"ids": {"values": news_ids}}]}} + if query_text: + es_query["bool"]["must"] = [ + {"multi_match": {"query": query_text, "fields": ["maintitle", "author"]}} + ] + + offset = (page - 1) * page_size + response = _run_search( + query=es_query, + source=["date", "maintitle", "author", "url"], + size=page_size, + offset=offset, + sort=[{"date_full": sort_order}], + ) + + return _build_page(response, page, page_size) + + +def _find_news_ids_for_author(author_name: str) -> list: + + try: + response = elasticsearch.search( + index="aktuell_postproc", + query={"term": {"authors.keyword": author_name}}, + source=["news_id"], + size=1000, + cluster="inse", + ) + except Exception: + logger.exception(f"Postproc-search: Finding news IDs for author '{author_name}' failed.") + return [] + + news_ids = [] + for hit in response.get("hits", {}).get("hits", []): + news_id = hit.get("_source", {}).get("news_id") + if news_id: + news_ids.append(news_id) + + return news_ids + + +def _empty_page(page: int = 1, page_size: int = 0) -> NewsPage: + return NewsPage(total=0, page=page, page_size=page_size, results=[]) + def get_news_by_id(news_id: str) -> NewsArticleDetail: try: diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py index 0ed5fe6d..5bb5dc03 100644 --- a/service/src/main/inse/news/service.py +++ b/service/src/main/inse/news/service.py @@ -61,6 +61,34 @@ def search_news( return logic.search_news(query, page, page_size) +@router.get( + "/by-author", + operation_id="getNewsByAuthor", + response_model=NewsPage, + response_model_exclude_none=True, + summary="Returns news articles in which the given person is mentioned.", + tags=[Tags.NEWS], +) +def get_news_by_author( + author_id: Annotated[ + str, Query(alias="authorId", description="OpenAlex author id, e.g. A5034365278.") + ], + page: Annotated[ + int, Query(description="Page number (1-based).", ge=1) + ] = 1, + page_size: Annotated[ + int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100) + ] = 10, + sort_order: Annotated[ + str, Query(alias="sortOrder", description="Sort order: 'desc' (newest first) or 'asc' (oldest first).", pattern="^(asc|desc)$") + ] = "desc", + query: Annotated[ + str | None, Query(description="Optional search term, matched against title/author.") + ] = None, +): + return logic.get_news_by_author(author_id, page, page_size, sort_order, query) + + @router.get( "/{news_id}", operation_id="getNewsById", diff --git a/webapp/src/app/modules/person-news/person-news.component.ts b/webapp/src/app/modules/person-news/person-news.component.ts index 230f51a2..f33bf1e8 100644 --- a/webapp/src/app/modules/person-news/person-news.component.ts +++ b/webapp/src/app/modules/person-news/person-news.component.ts @@ -7,7 +7,7 @@ import { } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { ActivatedRoute, RouterLink } from '@angular/router'; +import { ActivatedRoute, ParamMap, Router, RouterLink } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; import { MatSelectModule } from '@angular/material/select'; import { @@ -20,7 +20,7 @@ import { MatTableModule } from '@angular/material/table'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { debounceTime, distinctUntilChanged } from 'rxjs'; +import { combineLatest, debounceTime, distinctUntilChanged } from 'rxjs'; import { WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; @@ -40,7 +40,12 @@ interface NewsPage { results: NewsArticle[]; } -const ARTICLE_CAP = 100; +interface NewsQueryState { + pageIndex: number; + pageSize: number; + sortOrder: 'desc' | 'asc'; + query: string; +} @Component({ selector: 'app-person-news', @@ -62,6 +67,7 @@ export class PersonNewsComponent implements OnInit { @ViewChild(MatPaginator) paginator?: MatPaginator; private readonly destroyRef = inject(DestroyRef); private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); private readonly httpClient = inject(HttpClient); private readonly worksService = inject(WorksService); readonly paginationService = inject(PaginationService); @@ -69,23 +75,35 @@ export class PersonNewsComponent implements OnInit { readonly searchControl = new FormControl('', { nonNullable: true }); displayedColumns = ['maintitle', 'author', 'date']; - private allArticles: NewsArticle[] = []; - private filteredArticles: NewsArticle[] = []; + private authorId: string | null = null; articles: NewsArticle[] = []; total = 0; loading = false; currentPageIndex = 0; sortOrder: 'desc' | 'asc' = 'desc'; + private readonly queryParamKeys = { + page: 'newsPage', + pageSize: 'newsPageSize', + sort: 'newsSort', + query: 'newsQuery', + } as const; + get isSearching(): boolean { return this.searchControl.value.trim().length > 0; } ngOnInit(): void { - this.route.parent?.paramMap + const parentParamMap = this.route.parent?.paramMap; + if (!parentParamMap) return; + + combineLatest([parentParamMap, this.route.queryParamMap]) .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(() => { - this.load(); + .subscribe(([params, queryParams]) => { + this.authorId = params.get('id'); + const state = this.parseQueryParams(queryParams); + this.applyState(state); + this.load(state); }); this.searchControl.valueChanges @@ -94,28 +112,42 @@ export class PersonNewsComponent implements OnInit { distinctUntilChanged(), takeUntilDestroyed(this.destroyRef), ) - .subscribe(() => { - this.applyFilter(); + .subscribe((value) => { + this.updateQueryParams({ + [this.queryParamKeys.query]: value.trim() || null, + [this.queryParamKeys.page]: 1, + }); }); } - load(): void { + load(state: NewsQueryState): void { + if (!this.authorId) { + return; + } + this.loading = true; - const params = new HttpParams() - .set('page', 1) - .set('pageSize', ARTICLE_CAP) - .set('sortOrder', this.sortOrder); + let params = new HttpParams() + .set('authorId', this.authorId) + .set('page', state.pageIndex + 1) + .set('pageSize', state.pageSize) + .set('sortOrder', state.sortOrder); + + if (state.query) { + params = params.set('query', state.query); + } const basePath = this.worksService.configuration.basePath ?? ''; this.httpClient - .get(`${basePath}/api/news`, { params }) + .get(`${basePath}/api/news/by-author`, { params }) .subscribe({ next: (page) => { - this.allArticles = page.results ?? []; - this.applyFilter(); + this.articles = page.results ?? []; + this.total = page.total ?? 0; this.loading = false; }, error: () => { + this.articles = []; + this.total = 0; this.loading = false; }, }); @@ -123,8 +155,17 @@ export class PersonNewsComponent implements OnInit { onPage(event: PageEvent): void { this.paginationService.selection = event.pageSize; - this.currentPageIndex = event.pageIndex; - this.updatePage(); + this.updateQueryParams({ + [this.queryParamKeys.page]: event.pageIndex + 1, + [this.queryParamKeys.pageSize]: event.pageSize, + }); + } + + onSortChange(order: 'desc' | 'asc'): void { + this.updateQueryParams({ + [this.queryParamKeys.sort]: order, + [this.queryParamKeys.page]: 1, + }); } formatDate(dateStr?: string | null): string { @@ -144,31 +185,48 @@ export class PersonNewsComponent implements OnInit { return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`; } - onSortChange(order: 'desc' | 'asc'): void { - this.sortOrder = order; - this.load(); + private updateQueryParams( + overrides: Record, + ): void { + void this.router.navigate([], { + relativeTo: this.route, + queryParams: overrides, + queryParamsHandling: 'merge', + }); } - private applyFilter(): void { - const query = this.searchControl.value.trim().toLowerCase(); - this.filteredArticles = query - ? this.allArticles.filter( - (a) => - a.maintitle?.toLowerCase().includes(query) || - a.author?.toLowerCase().includes(query), - ) - : this.allArticles; - this.total = this.filteredArticles.length; - this.currentPageIndex = 0; - this.paginator?.firstPage(); - this.updatePage(); + private parseQueryParams(queryParams: ParamMap): NewsQueryState { + const sortParam = queryParams.get(this.queryParamKeys.sort); + const sortOrder: 'desc' | 'asc' = sortParam === 'asc' ? 'asc' : 'desc'; + + return { + pageIndex: + this.parsePositiveInteger( + queryParams.get(this.queryParamKeys.page), + 1, + ) - 1, + pageSize: this.parsePositiveInteger( + queryParams.get(this.queryParamKeys.pageSize), + this.paginationService.selection, + ), + sortOrder, + query: (queryParams.get(this.queryParamKeys.query) ?? '').trim(), + }; } - private updatePage(): void { - const start = this.currentPageIndex * this.paginationService.selection; - this.articles = this.filteredArticles.slice( - start, - start + this.paginationService.selection, - ); + private applyState(state: NewsQueryState): void { + this.currentPageIndex = state.pageIndex; + this.paginationService.selection = state.pageSize; + this.sortOrder = state.sortOrder; + this.searchControl.setValue(state.query, { emitEvent: false }); + } + + private parsePositiveInteger(value: string | null, fallback: number): number { + const parsedValue = Number(value); + if (!Number.isInteger(parsedValue) || parsedValue < 1) { + return fallback; + } + + return parsedValue; } } From dc2ef6fd203aff0438cc5a15eff3f76d54c36344 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 17 Jun 2026 20:26:51 +0200 Subject: [PATCH 09/22] refactor person news to load via resolver --- webapp/src/app/app.routes.ts | 11 ++ .../person-news/person-news.component.ts | 171 ++++-------------- .../src/app/resolvers/person-news.resolver.ts | 57 ++++++ 3 files changed, 107 insertions(+), 132 deletions(-) create mode 100644 webapp/src/app/resolvers/person-news.resolver.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 068e2080..56278534 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -8,6 +8,7 @@ import { institutionResolver } from './resolvers/institution.resolver'; import { bundProjectsResolver } from './resolvers/bund-projects.resolver'; import { euProjectsResolver } from './resolvers/eu-projects.resolver'; import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver'; +import { personNewsResolver } from './resolvers/person-news.resolver'; export const routes: Routes = [ { path: '', @@ -188,6 +189,16 @@ export const routes: Routes = [ import('./modules/person-news/person-news.component').then( (mod) => mod.PersonNewsComponent, ), + resolve: { + newsPage: personNewsResolver, + }, + runGuardsAndResolvers: (from, to) => { + const keys = ['page', 'pageSize', 'sortOrder', 'query']; + + return keys.some( + (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + ); + }, }, ], }, diff --git a/webapp/src/app/modules/person-news/person-news.component.ts b/webapp/src/app/modules/person-news/person-news.component.ts index f33bf1e8..b0e6356b 100644 --- a/webapp/src/app/modules/person-news/person-news.component.ts +++ b/webapp/src/app/modules/person-news/person-news.component.ts @@ -1,51 +1,19 @@ -import { - Component, - DestroyRef, - OnInit, - ViewChild, - inject, -} from '@angular/core'; -import { HttpClient, HttpParams } from '@angular/common/http'; +import { Component, DestroyRef, OnInit, inject } from '@angular/core'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { ActivatedRoute, ParamMap, Router, RouterLink } from '@angular/router'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; import { MatSelectModule } from '@angular/material/select'; -import { - MatPaginator, - MatPaginatorModule, - PageEvent, -} from '@angular/material/paginator'; +import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatTableModule } from '@angular/material/table'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { combineLatest, debounceTime, distinctUntilChanged } from 'rxjs'; +import { debounceTime, distinctUntilChanged } from 'rxjs'; -import { WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; - -interface NewsArticle { - id: string; - date?: string | null; - maintitle?: string | null; - author?: string | null; - url?: string | null; -} - -interface NewsPage { - total: number; - page: number; - page_size: number; - results: NewsArticle[]; -} - -interface NewsQueryState { - pageIndex: number; - pageSize: number; - sortOrder: 'desc' | 'asc'; - query: string; -} +import { ResolverStateService } from '../../shared/services/resolver-state.service'; +import { NewsArticle, NewsPage } from '../../resolvers/person-news.resolver'; @Component({ selector: 'app-person-news', @@ -64,46 +32,53 @@ interface NewsQueryState { styleUrl: './person-news.component.scss', }) export class PersonNewsComponent implements OnInit { - @ViewChild(MatPaginator) paginator?: MatPaginator; private readonly destroyRef = inject(DestroyRef); private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); - private readonly httpClient = inject(HttpClient); - private readonly worksService = inject(WorksService); readonly paginationService = inject(PaginationService); + private readonly resolverStateService = inject(ResolverStateService); readonly searchControl = new FormControl('', { nonNullable: true }); displayedColumns = ['maintitle', 'author', 'date']; - private authorId: string | null = null; articles: NewsArticle[] = []; total = 0; - loading = false; currentPageIndex = 0; sortOrder: 'desc' | 'asc' = 'desc'; - private readonly queryParamKeys = { - page: 'newsPage', - pageSize: 'newsPageSize', - sort: 'newsSort', - query: 'newsQuery', - } as const; + get loading(): boolean { + return this.resolverStateService.isResolving(); + } get isSearching(): boolean { return this.searchControl.value.trim().length > 0; } ngOnInit(): void { - const parentParamMap = this.route.parent?.paramMap; - if (!parentParamMap) return; - - combineLatest([parentParamMap, this.route.queryParamMap]) + this.route.data .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(([params, queryParams]) => { - this.authorId = params.get('id'); - const state = this.parseQueryParams(queryParams); - this.applyState(state); - this.load(state); + .subscribe(({ newsPage }) => { + const page = newsPage as NewsPage; + this.articles = page.results ?? []; + this.total = page.total ?? 0; + }); + + this.route.queryParamMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + const page = params.get('page') + ? Number.parseInt(params.get('page')!, 10) + : 1; + const pageSize = params.get('pageSize') + ? Number.parseInt(params.get('pageSize')!, 10) + : 10; + const sortOrder = params.get('sortOrder'); + const query = params.get('query') ?? ''; + + this.currentPageIndex = page - 1; + this.paginationService.selection = pageSize; + this.sortOrder = sortOrder === 'asc' ? 'asc' : 'desc'; + this.searchControl.setValue(query, { emitEvent: false }); }); this.searchControl.valueChanges @@ -114,57 +89,24 @@ export class PersonNewsComponent implements OnInit { ) .subscribe((value) => { this.updateQueryParams({ - [this.queryParamKeys.query]: value.trim() || null, - [this.queryParamKeys.page]: 1, + query: value.trim() || null, + page: 1, }); }); } - load(state: NewsQueryState): void { - if (!this.authorId) { - return; - } - - this.loading = true; - let params = new HttpParams() - .set('authorId', this.authorId) - .set('page', state.pageIndex + 1) - .set('pageSize', state.pageSize) - .set('sortOrder', state.sortOrder); - - if (state.query) { - params = params.set('query', state.query); - } - - const basePath = this.worksService.configuration.basePath ?? ''; - this.httpClient - .get(`${basePath}/api/news/by-author`, { params }) - .subscribe({ - next: (page) => { - this.articles = page.results ?? []; - this.total = page.total ?? 0; - this.loading = false; - }, - error: () => { - this.articles = []; - this.total = 0; - this.loading = false; - }, - }); - } - onPage(event: PageEvent): void { this.paginationService.selection = event.pageSize; this.updateQueryParams({ - [this.queryParamKeys.page]: event.pageIndex + 1, - [this.queryParamKeys.pageSize]: event.pageSize, + page: event.pageIndex + 1, + pageSize: event.pageSize, }); } onSortChange(order: 'desc' | 'asc'): void { this.updateQueryParams({ - [this.queryParamKeys.sort]: order, - [this.queryParamKeys.page]: 1, + sortOrder: order, + page: 1, }); } @@ -194,39 +136,4 @@ export class PersonNewsComponent implements OnInit { queryParamsHandling: 'merge', }); } - - private parseQueryParams(queryParams: ParamMap): NewsQueryState { - const sortParam = queryParams.get(this.queryParamKeys.sort); - const sortOrder: 'desc' | 'asc' = sortParam === 'asc' ? 'asc' : 'desc'; - - return { - pageIndex: - this.parsePositiveInteger( - queryParams.get(this.queryParamKeys.page), - 1, - ) - 1, - pageSize: this.parsePositiveInteger( - queryParams.get(this.queryParamKeys.pageSize), - this.paginationService.selection, - ), - sortOrder, - query: (queryParams.get(this.queryParamKeys.query) ?? '').trim(), - }; - } - - private applyState(state: NewsQueryState): void { - this.currentPageIndex = state.pageIndex; - this.paginationService.selection = state.pageSize; - this.sortOrder = state.sortOrder; - this.searchControl.setValue(state.query, { emitEvent: false }); - } - - private parsePositiveInteger(value: string | null, fallback: number): number { - const parsedValue = Number(value); - if (!Number.isInteger(parsedValue) || parsedValue < 1) { - return fallback; - } - - return parsedValue; - } } diff --git a/webapp/src/app/resolvers/person-news.resolver.ts b/webapp/src/app/resolvers/person-news.resolver.ts new file mode 100644 index 00000000..9d361534 --- /dev/null +++ b/webapp/src/app/resolvers/person-news.resolver.ts @@ -0,0 +1,57 @@ +import { ResolveFn } from '@angular/router'; +import { inject } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { of } from 'rxjs'; + +import { WorksService } from '../api'; + +export interface NewsArticle { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; +} + +export interface NewsPage { + total: number; + page: number; + page_size: number; + results: NewsArticle[]; +} + +export const personNewsResolver: ResolveFn = (route) => { + const httpClient = inject(HttpClient); + const worksService = inject(WorksService); + + const authorId = route.parent?.paramMap.get('id'); + if (!authorId) { + return of({ total: 0, page: 1, page_size: 0, results: [] }); + } + + const queryParams = route.queryParamMap; + + const page = queryParams.get('page') + ? Number.parseInt(queryParams.get('page')!, 10) + : 1; + + const pageSize = queryParams.get('pageSize') + ? Number.parseInt(queryParams.get('pageSize')!, 10) + : 10; + + const sortOrder = queryParams.get('sortOrder') || 'desc'; + const query = queryParams.get('query') || ''; + + let params = new HttpParams() + .set('authorId', authorId) + .set('page', page) + .set('pageSize', pageSize) + .set('sortOrder', sortOrder); + + if (query) { + params = params.set('query', query); + } + + const basePath = worksService.configuration.basePath ?? ''; + return httpClient.get(`${basePath}/api/news/by-author`, { params }); +}; From 28b57059b7d5879865f9f5d11f5eb3207c081fbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sat, 20 Jun 2026 15:12:33 +0200 Subject: [PATCH 10/22] Added support for eu projects for other institutions than UDE --- .../institutions_search_client.py | 185 ++++++++--- service/src/main/inse/projects/model.py | 2 +- .../inse/projects/projects_search_client.py | 291 ++++++++---------- service/src/main/inse/projects/router.py | 29 ++ service/src/main/inse/projects/service.py | 111 ++++--- service/src/main/inse/works/logic.py | 65 +++- ude_person.http | 157 +++++++++- webapp/src/app/api/api/projects.service.ts | 56 ++++ webapp/src/app/app.routes.ts | 2 + .../person-projects.component.ts | 8 +- .../modules/projects/projects.component.ts | 2 +- .../resolvers/bund-project-page.resolver.ts | 4 +- .../cordis-eu-project-page.resolver.ts | 17 +- .../person-cordis-eu-project-page.resolver.ts | 24 ++ 14 files changed, 660 insertions(+), 293 deletions(-) create mode 100644 webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 0d9f0ff8..0e86c8de 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -20,13 +20,21 @@ class InstitutionsSearchClient: """ pass - def get_institution_by_id(self, raw_institution_id: str) -> Institution: - """ - Retrieves a single institution by its OpenAlex ID from the local Elasticsearch cluster. + def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution: + """Retrieves an institution by its raw OpenAlex institution ID. + + Args: + raw_oa_institution_id (str): The raw OpenAlex institution ID to search for. + + Raises: + NotFoundException: If no institution is found with the given ID or if the institution data cannot be parsed. + + Returns: + Institution: The institution corresponding to the given raw OpenAlex institution ID. """ query = { "match": { - "id": f"https://openalex.org/{raw_institution_id.upper()}", + "id": f"https://openalex.org/{raw_oa_institution_id.upper()}", } } @@ -35,13 +43,13 @@ class InstitutionsSearchClient: hits = res.get("hits", {}).get("hits", []) if not hits: raise NotFoundException( - f"Institution with ID '{raw_institution_id}' not found." + f"Institution with ID '{raw_oa_institution_id}' not found." ) institution = self._convert_hit_to_institution(hits[0]) if not institution: raise NotFoundException( - f"Institution with ID '{raw_institution_id}' could not be parsed." + f"Institution with ID '{raw_oa_institution_id}' could not be parsed." ) return institution @@ -208,37 +216,39 @@ class InstitutionsSearchClient: if query_text: stripped = query_text.strip() - must.append({ - "bool": { - "should": [ - { - "wildcard": { - "display_name.keyword": { - "value": f"*{stripped}*", - "boost": 2 - } - } - }, - { - "wildcard": { - "display_name_alternatives.keyword": { - "value": f"*{stripped}*", - "boost": 2 - } - } - }, - { - "wildcard": { - "display_name_acronyms.keyword": { - "value": f"*{stripped.upper()}*", - "boost": 10 - } - } + must.append( + { + "bool": { + "should": [ + { + "wildcard": { + "display_name.keyword": { + "value": f"*{stripped}*", + "boost": 2, + } + } + }, + { + "wildcard": { + "display_name_alternatives.keyword": { + "value": f"*{stripped}*", + "boost": 2, + } + } + }, + { + "wildcard": { + "display_name_acronyms.keyword": { + "value": f"*{stripped.upper()}*", + "boost": 10, + } + } + }, + ], + "minimum_should_match": 1, } - ], - "minimum_should_match": 1 - } - }) + } + ) filter_queries = [] @@ -278,35 +288,41 @@ class InstitutionsSearchClient: return [Institution.from_dict(hit["_source"]) for hit in hits] - def get_institution_aliases_by_id(self, raw_institution_id: str) -> List[str]: + def get_institution_aliases_by_oa_institution_id( + self, raw_oa_institution_id: str + ) -> List[str]: """Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases. Args: - raw_institution_id (str): The raw institution ID for which to retrieve aliases. + raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve aliases. Returns: List[str]: A list of aliases for the given institution ID. """ - institution = self.get_institution_by_id(raw_institution_id) + institution = self.get_institution_by_id(raw_oa_institution_id) aliases = list( self.augment_aliases(set(institution.display_name_alternatives or [])) - | self.get_predefined_institution_aliases(raw_institution_id) + | self.get_predefined_institution_aliases(raw_oa_institution_id) ) logger.debug( - "Retrieved aliases for institution_id=%s: %s", raw_institution_id, aliases + "Retrieved aliases for institution_id=%s: %s", + raw_oa_institution_id, + aliases, ) return aliases - def get_predefined_institution_aliases(self, raw_institution_id: str) -> Set[str]: + def get_predefined_institution_aliases( + self, raw_oa_institution_id: str + ) -> Set[str]: """Get predefined aliases for a given institution ID. Args: - raw_institution_id (str): The raw institution ID for which to retrieve predefined aliases. + raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve predefined aliases. Returns: Set[str]: A set of predefined aliases for the given institution ID. """ - raw_institution_id = raw_institution_id.upper() + raw_oa_institution_id = raw_oa_institution_id.upper() predefined_aliases = { "I62318514": [ "universität duisburg-essen", @@ -317,7 +333,9 @@ class InstitutionsSearchClient: ], } - return self.augment_aliases(set(predefined_aliases.get(raw_institution_id, []))) + return self.augment_aliases( + set(predefined_aliases.get(raw_oa_institution_id, [])) + ) def augment_aliases(self, aliases: Set[str]) -> Set[str]: """Augment a set of aliases by applying the augment_alias function to each alias. @@ -407,3 +425,80 @@ class InstitutionsSearchClient: "Failed to validate institution hit ID %s: %s", hit.get("_id"), e ) return None + + def get_cordis_eu_organisation_ids_by_oa_institution_id( + self, raw_oa_institution_id: str + ) -> Optional[List[str]]: + """Retrieves the corresponding EU organisation IDs for a given OpenAlex institution ID by searching for institution aliases and matching them against the Cordis EU organisations indices. + + Args: + raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve the corresponding EU organisation IDs. + + Returns: + Optional[List[str]]: A list of corresponding EU organisation IDs or None if the search fails. + """ + + institution_aliases = set( + self.get_institution_aliases_by_oa_institution_id( + raw_oa_institution_id=raw_oa_institution_id + ) + ) + + body = { + "size": 0, + "query": { + "bool": { + "filter": [ + { + "terms": { + "name.keyword": [ + institution_alias.upper() + for institution_alias in institution_aliases + ] + } + } + ] + } + }, + "aggs": { + "organisation_ids": { + "terms": {"field": "organisationID", "size": 10000} + } + }, + } + + logger.debug( + "Searching for EU organisation IDs for raw_oa_institution_id=%s with aliases=%s and query: %s", + raw_oa_institution_id, + institution_aliases, + body, + ) + + try: + # IMPORTANT: The indices are named organizations and not organisations. + 15 Minutes debugging why the search returns 0 results + response = elasticsearch.search( + index="cordis_eu_*_organizations", body=body, cluster="inse" + ) + except Exception as e: + logger.exception("Error while searching for EU organisation IDs: %s", e) + return None + + logger.debug( + "Received response for EU organisation ID search for raw_oa_institution_id=%s: %s", + raw_oa_institution_id, + response, + ) + + aggregations = response.get("aggregations", {}) + organisation_ids_buckets = aggregations.get("organisation_ids", {}).get( + "buckets", [] + ) + organisation_ids = [bucket.get("key") for bucket in organisation_ids_buckets] + + logger.debug( + "Extracted EU organisation IDs for raw_oa_institution_id=%s: %s", + raw_oa_institution_id, + organisation_ids, + ) + + return organisation_ids diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index ae05256b..dd75726f 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -184,7 +184,7 @@ class FundingProject(BaseModel): title=source.get("title"), start_date=source.get("startDate"), end_date=source.get("endDate"), - funding_amount=source.get("ecMacContribution"), + funding_amount=source.get("ecMaxContribution"), ) @classmethod diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 8f8c93cd..3347fc3c 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -1,6 +1,6 @@ import json import logging -from typing import Any, Dict, List, Literal, Optional, Set +from typing import Any, Dict, List, Optional, Set import httpx @@ -23,6 +23,7 @@ from inse.models.eu_project import EuProject from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails from inse.models.cordis_eu_project import CordisEuProject +from inse.integrations import elasticsearch settings = get_settings() @@ -256,7 +257,7 @@ class BundProjectsSearchClient(ProjectsSearchClient): sort_by: str = "topic", sort_direction: str = "asc", ) -> BundProjectPage: - query = self.bund_projects_query( + query = self._bund_projects_query( page=page, size=size, institution_names=institution_names, @@ -297,100 +298,19 @@ class EuProjectsSearchClient(ProjectsSearchClient): api_key=settings.elasticsearch_inse_api_key, ) - def eu_projects_query( - self, - page: int, - size: int, - id: Optional[str] = None, - institution_names: List[str] = [], - topic: Optional[str] = "Network", - sort_by: str = "topic", - sort_direction: str = "asc", - ) -> dict: - from_ = page * size - query: Dict[str, Any] = {"size": size, "from": from_, "query": {}} + def _eu_projects_id_body(self, eu_organisation_ids: List[str]) -> Dict[str, Any]: + """Constructs the Elasticsearch query body to retrieve project IDs associated with the given list of EU organisation IDs. - must_clauses: List[Dict[str, Any]] = [] - if id: - must_clauses.append({"match": {"id": id}}) + Args: + eu_organisation_ids (List[str]): A list of EU organisation IDs for which to retrieve associated project IDs. - if topic is not None and topic.strip() != "": - must_clauses.append( - { - "match_phrase_prefix": { - "title": { - "query": topic, - "max_expansions": 50, - } - } - } - ) - - if institution_names: - must_clauses.append( - { - "nested": { - "path": "organization_nested", - "query": { - "bool": { - "should": [ - { - "match": { - "organization_nested.name": { - "query": name, - "operator": "and", - } - } - } - for name in institution_names - ], - "minimum_should_match": 1, - } - }, - } - } - ) - - if must_clauses: - query["query"] = {"bool": {"must": must_clauses}} - else: - query["query"] = {"match_all": {}} - - sort_by = sort_by.strip().lower() - sort_direction = sort_direction.strip().lower() - if sort_direction not in ["asc", "desc"]: - sort_direction = "asc" - - sort_config: Dict[str, Any] = {} - - if sort_by == "topic": - sort_config = {"title.keyword": {"order": sort_direction}} - - elif sort_by == "grant_amount": - sort_config = {"totalCost.keyword": {"order": sort_direction}} - - elif sort_by == "department": - sort_config = { - "programme_nested.programme.keyword": { - "order": sort_direction, - "nested": {"path": "programme_nested"}, - } - } - else: - sort_config = {"id.keyword": {"order": sort_direction}} - - query["sort"] = [sort_config] - - query_str = json.dumps(query, indent=2) - logger.debug(f"Constructed EU project query: {query_str}") - - return query - - def _eu_projects_id_body(self, eu_organisation_id: str) -> Dict[str, Any]: + Returns: + Dict[str, Any]: The Elasticsearch query body. + """ body: Dict[str, Any] = { "size": 0, "query": { - "bool": {"filter": [{"term": {"organisationID": eu_organisation_id}}]} + "bool": {"filter": [{"terms": {"organisationID": eu_organisation_ids}}]} }, "aggs": { "associated_project_ids": { @@ -422,6 +342,14 @@ class EuProjectsSearchClient(ProjectsSearchClient): return ids def _eu_project_sort_by_field(self, sort_by: ProjectsSortBy) -> str: + """Maps the ProjectsSortBy enum to the corresponding Elasticsearch field for sorting EU projects. + + Args: + sort_by (ProjectsSortBy): The sorting criterion specified as a ProjectsSortBy enum value. + + Returns: + str: The corresponding Elasticsearch field for sorting. + """ if sort_by == ProjectsSortBy.TITLE: return "title.keyword" elif sort_by == ProjectsSortBy.FUNDING_START: @@ -475,22 +403,22 @@ class EuProjectsSearchClient(ProjectsSearchClient): logger.debug(f"Constructed EU project details query: {query_str}") return body - async def search_eu_projects2( + async def search_eu_projects( self, - eu_organisation_id: str, + eu_organisation_ids: List[str], projects_filtering_properties: ProjectsFilteringProperties, ) -> CordisEuProjectPage: - projects_id_body = self._eu_projects_id_body(eu_organisation_id) + projects_id_body = self._eu_projects_id_body(eu_organisation_ids) id_response = await self.make_search_request( projects_id_body, index="cordis_eu_*_organizations" ) project_ids = self._eu_projects_id_response_to_ids(id_response) logger.debug( - f"Found project IDs for organization ID {eu_organisation_id}: {project_ids}" + f"Found project IDs for organization IDs {eu_organisation_ids}: {project_ids}" ) if not project_ids: logger.debug( - f"No project IDs found for organization ID {eu_organisation_id}" + f"No project IDs found for organization IDs {eu_organisation_ids}" ) return CordisEuProjectPage( elements=[], @@ -517,6 +445,16 @@ class EuProjectsSearchClient(ProjectsSearchClient): def _response_to_cordis_eu_project_page( self, response: Dict[str, Any], page: int, size: int ) -> CordisEuProjectPage: + """Converts the Elasticsearch response to a CordisEuProjectPage containing CordisEuProject elements. + + Args: + response (Dict[str, Any]): The Elasticsearch response. + page (int): The page number. + size (int): The number of items per page. + + Returns: + CordisEuProjectPage: The converted project page. + """ hits_block = response.get("hits", {}) total_hits = hits_block.get("total", {}).get("value", 0) elements = [ @@ -527,56 +465,81 @@ class EuProjectsSearchClient(ProjectsSearchClient): elements=elements, total=total_hits, page=page, size=size ) - def response_to_eu_project_page( - self, response: Dict[str, Any], page: int, size: int - ) -> EuProjectPage: + def _get_raw_doi(self, doi: str) -> str: + """Extracts the raw DOI from a given DOI string, removing any URL prefixes if present. + + Args: + doi (str): The DOI string to process. + + Returns: + str: The raw DOI string. + """ + if doi.startswith("https://doi.org/"): + return doi[len("https://doi.org/") :] + elif doi.startswith("http://dx.doi.org/"): + return doi[len("http://dx.doi.org/") :] + else: + return doi + + def get_cordis_eu_publications_by_dois(self, dois: List[str]): + """Retrieves Cordis EU publications associated with the given list of DOIs. + + Args: + dois (List[str]): The list of DOIs for which to retrieve publications. + + Returns: + _type_: The retrieved publications. + """ + raw_dois = [self._get_raw_doi(doi) for doi in dois] + query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} + + response = elasticsearch.search( + query=query, index="cordis_eu_*_publications", cluster="inse" + ) + + logger.debug( + f"Received publications response: {json.dumps(response, indent=2)}" + ) + + return response + + def get_cordis_eu_project_ids_by_dois(self, dois: List[str]) -> List[str]: + """Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs. + + Args: + dois (List[str]): The list of DOIs for which to retrieve project IDs. + + Returns: + List[str]: The list of project IDs. + """ + response = self.get_cordis_eu_publications_by_dois(dois=dois) + hits_block = response.get("hits", {}) + project_ids = set() + for hit in hits_block.get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if project_id: + project_ids.add(project_id) + return list(project_ids) + + def get_cordis_eu_projects_by_project_ids( + self, project_ids: List[str] + ) -> CordisEuProjectPage: + query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}} + + response = elasticsearch.search( + query=query, index="cordis_eu_*_projects", cluster="inse" + ) + hits_block = response.get("hits", {}) total_hits = hits_block.get("total", {}).get("value", 0) elements = [ - EuProject.model_validate(hit["_source"]) + CordisEuProject.model_validate(hit["_source"]) for hit in hits_block.get("hits", []) ] - return EuProjectPage(elements=elements, total=total_hits, page=page, size=size) - - async def search_eu_projects( - self, - page: int, - size: int, - id: Optional[str] = None, - institution_names: List[str] = [], - topic: Optional[str] = None, - sort_by: str = "topic", - sort_direction: str = "asc", - ) -> EuProjectPage: - query = self.eu_projects_query( - page=page, - size=size, - id=id, - institution_names=institution_names, - topic=topic, - sort_by=sort_by, - sort_direction=sort_direction, + return CordisEuProjectPage( + elements=elements, total=total_hits, page=0, size=len(elements) ) - response = await self.make_search_request(query) - return self.response_to_eu_project_page(response, page, size) - - async def get_eu_projects_by_institution_name( - self, - institution_names: List[str], - page: int, - size: int, - sort_by: str = "topic", - sort_direction: str = "asc", - ) -> EuProjectPage: - query = self.eu_projects_query( - page=page, - size=size, - institution_names=institution_names, - sort_by=sort_by, - sort_direction=sort_direction, - ) - response = await self.make_search_request(query) - return self.response_to_eu_project_page(response, page, size) class DfgProjectsSearchClient(ProjectsSearchClient): @@ -892,28 +855,6 @@ class CompleteProjectsSearchClient(ProjectsSearchClient): else: raise ValueError(f"Unsupported project type: {project_type}") - def _hit_to_funding_project(self, hit: Dict[str, Any]) -> FundingProject: - if hit.get("_index", "").startswith("cordis_eu_") and hit.get( - "_index", "" - ).endswith("_projects"): - return FundingProject.from_cordis_projects_hit(hit=hit) - elif hit.get("_index") == "projects_bund_v1": - return FundingProject.from_bund_projects_hit(hit=hit) - elif hit.get("_index") == "projects_dfg_all": - return FundingProject.from_dfg_projects_hit(hit=hit) - else: - raise ValueError( - "The provided hit does not belong to a recognized project index." - ) - - def _response_to_funding_project_page( - self, response: Dict[str, Any], page: int, size: int - ) -> FundingProjectPage: - hits = response.get("hits", {}).get("hits", []) - projects = [self._hit_to_funding_project(hit=hit) for hit in hits] - total = response.get("hits", {}).get("total", {}).get("value", 0) - return FundingProjectPage(elements=projects, total=total, page=page, size=size) - async def search_projects( self, page: int, @@ -937,4 +878,28 @@ class CompleteProjectsSearchClient(ProjectsSearchClient): ) projects_response = await self.make_search_request(body, index=index) - return self._response_to_funding_project_page(projects_response, page, size) + return _response_to_funding_project_page(projects_response, page, size) + + +def _response_to_funding_project_page( + response: Dict[str, Any], page: int, size: int +) -> FundingProjectPage: + hits = response.get("hits", {}).get("hits", []) + projects = [_hit_to_funding_project(hit=hit) for hit in hits] + total = response.get("hits", {}).get("total", {}).get("value", 0) + return FundingProjectPage(elements=projects, total=total, page=page, size=size) + + +def _hit_to_funding_project(hit: Dict[str, Any]) -> FundingProject: + if hit.get("_index", "").startswith("cordis_eu_") and hit.get( + "_index", "" + ).endswith("_projects"): + return FundingProject.from_cordis_projects_hit(hit=hit) + elif hit.get("_index") == "projects_bund_v1": + return FundingProject.from_bund_projects_hit(hit=hit) + elif hit.get("_index") == "projects_dfg_all": + return FundingProject.from_dfg_projects_hit(hit=hit) + else: + raise ValueError( + "The provided hit does not belong to a recognized project index." + ) diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 60beae82..7d6e45f9 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -55,6 +55,35 @@ def get_complete_projects_search_client() -> CompleteProjectsSearchClient: return CompleteProjectsSearchClient() +@router.get( + "/author/{raw_oa_author_id}/eu", + summary="Get EU projects for an author.", + description="Returns a list of EU projects associated with the specified author ID.", + operation_id="getEuProjectsForAuthor", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": CordisEuProjectPage, + }, + status.HTTP_404_NOT_FOUND: {"description": "Author not found"}, + }, + response_model_by_alias=False, +) +def get_eu_projects_for_author( + eu_projects_search_client: Annotated[ + EuProjectsSearchClient, Depends(get_eu_search_client) + ], + raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")], +) -> CordisEuProjectPage: + logger.debug( + f"Received request to get EU projects for author_id={raw_oa_author_id}" + ) + return projects_service.search_cordis_eu_projects_for_author_id( + eu_projects_search_client=eu_projects_search_client, + raw_oa_author_id=raw_oa_author_id, + ) + + @router.post( "/institution/bund/search", summary="Get bund projects.", diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 83f55211..9dde9e87 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -27,6 +27,7 @@ from inse.institutions.institutions_search_client import ( ) from inse.exceptions import NotFoundException from inse.persons.logic import get_author_name_by_id +from inse.works.logic import get_publication_dois_of_author logger = logging.getLogger(__name__) @@ -78,8 +79,10 @@ async def get_bund_projects_by_institution_id( logger.info( f"Fetching bund projects for institution_id={filtering_properties.raw_oa_institution_id}, page={filtering_properties.page}, size={filtering_properties.size}" ) - institution_aliases = institutions_search_client.get_institution_aliases_by_id( - filtering_properties.raw_oa_institution_id + institution_aliases = ( + institutions_search_client.get_institution_aliases_by_oa_institution_id( + filtering_properties.raw_oa_institution_id + ) ) logger.debug( f"Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}" @@ -126,79 +129,39 @@ async def get_cordis_eu_projects_by_institution_id( logger.info( f"Fetching CORDIS EU projects for institution_id={projects_filtering_properties.raw_oa_institution_id}, page={projects_filtering_properties.page}, size={projects_filtering_properties.size}" ) - institution_aliases = institutions_search_client.get_institution_aliases_by_id( - projects_filtering_properties.raw_oa_institution_id + institution_aliases = ( + institutions_search_client.get_institution_aliases_by_oa_institution_id( + projects_filtering_properties.raw_oa_institution_id + ) ) logger.debug( f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) - institution_eu_organisation_id = await ( - institutions_search_client.get_eu_organisation_id_by_oa_institution_id( + institution_eu_organisation_ids = ( + institutions_search_client.get_cordis_eu_organisation_ids_by_oa_institution_id( projects_filtering_properties.raw_oa_institution_id ) ) - if not institution_eu_organisation_id: + if not institution_eu_organisation_ids: logger.debug( - f"No EU organization ID found for institution_id={projects_filtering_properties.raw_oa_institution_id}" + f"No EU organization IDs found for institution_id={projects_filtering_properties.raw_oa_institution_id}" ) - raise NotFoundException( - f"EU organization ID for institution with id {projects_filtering_properties.raw_oa_institution_id} not found" + return CordisEuProjectPage( + elements=[], + total=0, + page=projects_filtering_properties.page, + size=projects_filtering_properties.size, ) - cordis_eu_project_page = await eu_search_client.search_eu_projects2( - eu_organisation_id=institution_eu_organisation_id, + cordis_eu_project_page = await eu_search_client.search_eu_projects( + eu_organisation_ids=institution_eu_organisation_ids, projects_filtering_properties=projects_filtering_properties, ) return cordis_eu_project_page -async def get_eu_projects_by_institution_id( - eu_search_client: EuProjectsSearchClient, - institutions_search_client: InstitutionsSearchClient, - raw_oa_institution_id: str, - topic: Optional[str], - page: int, - size: int, - sort_by: str = "topic", - sort_direction: str = "asc", -) -> EuProjectPage: - logger.info( - f"Fetching EU projects for institution_id={raw_oa_institution_id}, page={page}, size={size}" - ) - institution_aliases = institutions_search_client.get_institution_aliases_by_id( - raw_oa_institution_id - ) - logger.debug( - f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" - ) - - institution_eu_organisation_id = await ( - institutions_search_client.get_eu_organisation_id_by_oa_institution_id( - raw_oa_institution_id - ) - ) - if not institution_eu_organisation_id: - logger.debug( - f"No EU organization ID found for institution_id={raw_oa_institution_id}" - ) - raise NotFoundException( - f"EU organization ID for institution with id {raw_oa_institution_id} not found" - ) - - response = await eu_search_client.search_eu_projects( - page=page, - size=size, - institution_names=institution_aliases, - topic=topic, - sort_by=sort_by, - sort_direction=sort_direction, - ) - logger.debug(f"get_eu_projects_by_institution_id response: {response}") - return response - - async def get_dfg_projects_by_author_id( dfg_search_client: DfgProjectsSearchClient, author_id: str, @@ -264,8 +227,10 @@ async def get_institution_bund_projects_funding_over_time( logger.info( f"Fetching funding over time for institution_id={raw_oa_institution_id}" ) - institution_aliases = institutions_search_client.get_institution_aliases_by_id( - raw_oa_institution_id + institution_aliases = ( + institutions_search_client.get_institution_aliases_by_oa_institution_id( + raw_oa_institution_id + ) ) logger.debug( f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" @@ -375,3 +340,31 @@ async def get_single_bund_project( if not project: raise NotFoundException(f"BUND project with id {project_id} not found") return project + + +def search_cordis_eu_projects_for_author_id( + eu_projects_search_client: EuProjectsSearchClient, raw_oa_author_id: str +) -> CordisEuProjectPage: + + # Direct search not possible -> multi stage search + # 1. Exisiting author has publications with DOIs + # 2. CORDIS EU projects have associated publications with DOIs + # 3. Matching DOIs of author publications with DOIs of CORDIS EU project publications -> projects with associated publications of the author + + dois = get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id) + + logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}") + + project_ids = eu_projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois) + + logger.debug( + f"Found project IDs {project_ids} for author_id={raw_oa_author_id} and dois={dois}" + ) + + funding_project_page = ( + eu_projects_search_client.get_cordis_eu_projects_by_project_ids( + project_ids=project_ids + ) + ) + + return funding_project_page diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 37540cda..26528505 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -649,9 +649,7 @@ def _author_works_query(author_id: str) -> dict[str, Any]: def _parse_year_count_buckets(response: dict) -> list[dict]: return ( - response.get("aggregations", {}) - .get("publication_years", {}) - .get("buckets", []) + response.get("aggregations", {}).get("publication_years", {}).get("buckets", []) ) @@ -691,13 +689,9 @@ def _collect_topic_ids_from_year_buckets(year_buckets: list[dict]) -> set[str]: topic_ids: set[str] = set() for year_bucket in year_buckets: - primary_buckets = ( - year_bucket.get("primary_topics", {}).get("buckets", []) - ) + primary_buckets = year_bucket.get("primary_topics", {}).get("buckets", []) topic_buckets = ( - year_bucket.get("topics_nested", {}) - .get("topics", {}) - .get("buckets", []) + year_bucket.get("topics_nested", {}).get("topics", {}).get("buckets", []) ) for bucket in primary_buckets + topic_buckets: @@ -723,9 +717,7 @@ def _build_timeline_elements_from_aggregations( continue topics = _build_topic_counts_from_buckets( - year_bucket.get("topics_nested", {}) - .get("topics", {}) - .get("buckets", []), + year_bucket.get("topics_nested", {}).get("topics", {}).get("buckets", []), topic_details=topic_details, max_topics_per_year=max_topics_per_year, use_reverse_nested_count=True, @@ -781,6 +773,7 @@ def _build_topic_counts_from_buckets( return topics + async def _search_author_works_data( search_client: OpenAlexWorksSearchClient, author_id: str, @@ -860,4 +853,50 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]: detail="OpenAlex works search response could not be parsed.", ) from exc - return elements, total \ No newline at end of file + return elements, total + + +def get_publication_dois_of_author( + raw_oa_author_id: str, +) -> List[str]: + query = { + "bool": { + "must": [ + { + "nested": { + "path": "authorships", + "query": { + "term": { + "authorships.author.id": f"https://openalex.org/{raw_oa_author_id.strip().upper()}" + } + }, + } + } + ], + "filter": [{"exists": {"field": "doi"}}], + } + } + + try: + response = elasticsearch.search( + index="openalex-works", + source=["doi"], + size=10000, + query=query, + cluster="nes", + ) + except httpx.HTTPError as exc: + logger.exception("Request for publication DOIs of author failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="Request for publication DOIs of author failed.", + ) from exc + + dois = [] + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + doi = source.get("doi") + if doi: + dois.append(doi) + + return dois diff --git a/ude_person.http b/ude_person.http index 35ed2607..f4691a10 100644 --- a/ude_person.http +++ b/ude_person.http @@ -17,6 +17,21 @@ GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== Content-Type: application/json +{ + "size": 100, + "query": { + "bool": { + "filter": [ + { + "terms": { + "projectID": ["287661"] + } + } + ] + } + } +} + ### GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_mapping Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== @@ -47,6 +62,73 @@ Content-Type: application/json } } +# 10.1371/journal.pone.0018216 + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_mapping +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_fp7_project_iprs/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "query": { + "bool": { + "filter": [ + { + "terms": { + "qaProcessedDoi": [ + "10.5555/3234847.3234861", + "10.1145/1858367.1858373", + "10.1145/3583120.3586961", + "10.1109/ipin.2017.8115906", + "10.1145/3274783.3275217", + "10.1007/978-3-031-20716-7_7", + "10.1109/percomw.2012.6197554", + "10.1016/j.pmcj.2012.12.002", + "10.1007/978-3-658-32266-3_30", + "10.1109/percomw.2013.6529502", + "10.1109/ie.2010.40", + "10.18419/opus-2650", + "10.1007/s00138-024-01553-z", + "10.1007/978-3-030-90439-5_15", + "10.1201/9781003338659-4", + "10.1016/j.pmcj.2013.10.013", + "10.1109/percom.2009.4912852", + "10.1109/icra55743.2025.11128432", + "10.1145/2494091.2497327", + "10.1007/978-3-658-46485-1_31", + "10.1109/ie.2017.22", + "10.1109/jiot.2016.2554146", + "10.1145/2493432.2493459", + "10.3233/ais-160416", + "10.1109/percomw.2007.111", + "10.5194/asr-17-183-2020", + "10.1007/978-3-658-36430-4_37", + "10.1007/978-3-030-64559-5_50" + ] + } + } + ] + } + } +} + + + ### GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== @@ -127,7 +209,7 @@ Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw Content-Type: application/json { - "size": 0, + "size": 10, "query": { "bool": { "filter": [ @@ -138,12 +220,41 @@ Content-Type: application/json } ] } + } +} + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "size": 0, + "query": { + "bool": { + "filter": [ + { + "terms": { + "name.keyword": [ + "UNIVERSITAET DUISBURG-ESSEN", + "UNIVERSITY OF DUISBURG-ESSEN", + "UNIVERSITÄT DUISBURG-ESSEN", + "UNIVERSITAT DUISBURG ESSEN", + "UNIVERSITÄT DUISBURG ESSEN", + "UNIVERSITY OF DUISBURG ESSEN", + "UNIVERSITAET DUISBURG ESSEN", + "UNIVERSITAT DUISBURG-ESSEN" + ] + } + } + ] + } }, "aggs": { - "specific_org_rcn_values": { + "organisation_ids": { "terms": { "field": "organisationID", - "size": 1000 + "size": 10000 } } } @@ -1052,6 +1163,46 @@ Content-Type: application/json ### +GET https://project.nes.uni-due.de/elastic/openalex-works/_search +Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ== +Content-Type: application/json + +### + +GET https://project.nes.uni-due.de/elastic/openalex-works/_search +Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ== +Content-Type: application/json + +{ + "_source": ["title", "doi"], + "size": 100, + "query": { + "bool": { + "must": [ + { + "nested": { + "path": "authorships", + "query": { + "term": { + "authorships.author.id": "https://openalex.org/A5007170803" + } + } + } + } + ], + "filter": [ + { + "exists": { + "field": "doi" + } + } + ] + } + } +} + +### + GET https://project.nes.uni-due.de/elastic/openalex-authors/_search Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ== Content-Type: application/json diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 584633f1..b3b91911 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -133,6 +133,62 @@ export class ProjectsService extends BaseService { ); } + /** + * Get EU projects for an author. + * Returns a list of EU projects associated with the specified author ID. + * @endpoint get /api/projects/author/{raw_oa_author_id}/eu + * @param rawOaAuthorId The author ID to filter by. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getEuProjectsForAuthor(rawOaAuthorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawOaAuthorId === null || rawOaAuthorId === undefined) { + throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getEuProjectsForAuthor.'); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/projects/author/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/eu`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Get funding over time for bund projects. * Returns the funding over time for bund projects associated with the specified institution. diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 32b49d9d..a0f72fbb 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -14,6 +14,7 @@ import { bundSingleProjectResolver } from './resolvers/bund-single-project-resol import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page.resolver'; import { cordisEuProjectsFundingResolver } from './resolvers/cordis-eu-projects-funding.resolver'; import { fundingProjectPageResolver } from './resolvers/funding-project-page.resolver'; +import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver'; export const routes: Routes = [ { @@ -147,6 +148,7 @@ export const routes: Routes = [ ), resolve: { dfgProjectPage: dfgProjectsResolver, + personCordisEuProjectPage: personCordisEuProjectPageResolver, }, runGuardsAndResolvers: (from, to) => { const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; diff --git a/webapp/src/app/modules/person-projects/person-projects.component.ts b/webapp/src/app/modules/person-projects/person-projects.component.ts index 6374de4f..3b7ad95e 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -8,7 +8,11 @@ import { TemplateRef, viewChild, } from '@angular/core'; -import { DfgProjectPage, DfgProjectSummary } from '../../api'; +import { + CordisEuProjectPage, + DfgProjectPage, + DfgProjectSummary, +} from '../../api'; import { DataTableComponent, GenericColumn, @@ -47,6 +51,8 @@ export class PersonProjectsComponent implements OnInit { dfgProjectColumns: GenericColumn[] = []; dfgProjectData: DfgProjectSummary[] = []; + personCordisEuProjectPage = input.required(); + dfgProjectFundingEndTmp = viewChild.required>( 'dfgProjectFundingEndTmp', ); diff --git a/webapp/src/app/modules/projects/projects.component.ts b/webapp/src/app/modules/projects/projects.component.ts index 3e68025a..4fc6f46d 100644 --- a/webapp/src/app/modules/projects/projects.component.ts +++ b/webapp/src/app/modules/projects/projects.component.ts @@ -66,7 +66,7 @@ export class ProjectsComponent { handleSearchTermChange(newTerm: string): void { this.router.navigate([], { - queryParams: { search: newTerm }, + queryParams: { search: newTerm, page: 0, size: 10 }, queryParamsHandling: 'merge', }); } diff --git a/webapp/src/app/resolvers/bund-project-page.resolver.ts b/webapp/src/app/resolvers/bund-project-page.resolver.ts index 57657d8c..548cbb34 100644 --- a/webapp/src/app/resolvers/bund-project-page.resolver.ts +++ b/webapp/src/app/resolvers/bund-project-page.resolver.ts @@ -19,9 +19,9 @@ export const bundProjectPageResolver: ResolveFn = ( institutionId = route.parent?.paramMap.get('institutionId') ?? null; } - const sortBy = (route.queryParamMap.get('sort_by') ?? + const sortBy = (route.queryParamMap.get('sort_by') || 'title') as ProjectsSortBy; - const sortDirection = (route.queryParamMap.get('sort_direction') ?? + const sortDirection = (route.queryParamMap.get('sort_direction') || 'asc') as SortDirection; const search = route.queryParamMap.get('search'); diff --git a/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts b/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts index 791a0423..2508fa68 100644 --- a/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts +++ b/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts @@ -1,5 +1,10 @@ import { ResolveFn } from '@angular/router'; -import { CordisEuProjectPage, ProjectsService } from '../api'; +import { + CordisEuProjectPage, + ProjectsService, + ProjectsSortBy, + SortDirection, +} from '../api'; import { inject } from '@angular/core'; export const cordisEuProjectPageResolver: ResolveFn = ( @@ -13,8 +18,10 @@ export const cordisEuProjectPageResolver: ResolveFn = ( institutionId = route.parent?.paramMap.get('institutionId') ?? null; } - const sortBy = route.queryParamMap.get('sort_by') ?? 'title'; - const sortDirection = route.queryParamMap.get('sort_direction') ?? 'asc'; + const sortBy = (route.queryParamMap.get('sort_by') || + 'title') as ProjectsSortBy; + const sortDirection = (route.queryParamMap.get('sort_direction') || + 'asc') as SortDirection; const search = route.queryParamMap.get('search'); return inject(ProjectsService).searchCordisEuProjects({ @@ -23,7 +30,7 @@ export const cordisEuProjectPageResolver: ResolveFn = ( size: Number(size), raw_oa_institution_id: institutionId, query: search, - sort_by: sortBy as 'title' | 'funding_start' | 'funding_end', - sort_direction: sortDirection as 'asc' | 'desc', + sort_by: sortBy, + sort_direction: sortDirection, }); }; diff --git a/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts b/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts new file mode 100644 index 00000000..fa15f0d1 --- /dev/null +++ b/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts @@ -0,0 +1,24 @@ +import { ResolveFn } from '@angular/router'; +import { CordisEuProjectPage, ProjectsService } from '../api'; +import { inject } from '@angular/core'; + +export const personCordisEuProjectPageResolver: ResolveFn< + CordisEuProjectPage +> = (route, state) => { + const rawAuthorId = route.parent?.params['id']; + if (!rawAuthorId) { + throw new Error('Author ID is required to resolve collaboration network'); + } + + console.log('Before calling getEuProjectsForAuthor'); + inject(ProjectsService) + .getEuProjectsForAuthor(rawAuthorId) + .subscribe({ + next: (data) => { + console.log('Received data from getEuProjectsForAuthor:', data); + }, + }); + console.log('After calling getEuProjectsForAuthor'); + + return { elements: [], total: 0, page: 1, page_size: 10 }; +}; From 08cfec6be018da900b1de98ef93e9a3b8d51b0b3 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 15:15:23 +0200 Subject: [PATCH 11/22] Replace author with "Relevant" label in news list --- service/src/main/inse/news/logic.py | 41 ++++++++++++++++++- service/src/main/inse/news/model.py | 1 + .../src/app/modules/news/news.component.html | 21 ++++++++-- .../src/app/modules/news/news.component.scss | 36 ++++++++++++++++ webapp/src/app/modules/news/news.component.ts | 3 +- 5 files changed, 96 insertions(+), 6 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 526510de..f5599ddf 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -182,10 +182,21 @@ def _run_search(query: dict, source: list, size: int, offset: int, sort) -> dict def _build_page(response: dict, page: int, page_size: int) -> NewsPage: hits_section = response.get("hits", {}) total = hits_section.get("total", {}).get("value", 0) + hits = hits_section.get("hits", []) + + news_ids = [] + for hit in hits: + news_id = hit.get("_id") + if news_id: + news_ids.append(news_id) + + relevance_map = _get_relevance_map(news_ids) articles = [] - for hit in hits_section.get("hits", []): - articles.append(_parse_hit(hit)) + for hit in hits: + article = _parse_hit(hit) + article.relevant = relevance_map.get(article.id) + articles.append(article) return NewsPage( total=total, @@ -195,6 +206,32 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage: ) +def _get_relevance_map(news_ids: list) -> dict: + if not news_ids: + return {} + + try: + response = elasticsearch.search( + index="aktuell_postproc", + query={"terms": {"news_id.keyword": news_ids}}, + source=["news_id", "relevant"], + size=len(news_ids), + cluster="inse", + ) + except Exception: + logger.exception("Postproc-Relevanz-Lookup fehlgeschlagen.") + return {} + + relevance_map = {} + for hit in response.get("hits", {}).get("hits", []): + postproc_source = hit.get("_source", {}) + news_id = postproc_source.get("news_id") + if news_id is not None: + relevance_map[news_id] = bool(postproc_source.get("relevant", 0)) + + return relevance_map + + def _parse_hit(hit: dict) -> NewsArticle: source = hit.get("_source", {}) diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index ad34577f..83b593b3 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -12,6 +12,7 @@ class NewsArticle(BaseModel): maintitle: Optional[str] = None author: Optional[str] = None url: Optional[str] = None + relevant: Optional[bool] = None class NewsArticleDetail(NewsArticle): diff --git a/webapp/src/app/modules/news/news.component.html b/webapp/src/app/modules/news/news.component.html index 05ca40a8..bfd8cba1 100644 --- a/webapp/src/app/modules/news/news.component.html +++ b/webapp/src/app/modules/news/news.component.html @@ -42,10 +42,25 @@ - - Autor + + Relevanz - {{ article.author || '-' }} + @if (article.relevant === true) { + + check_circle + Relevant + + } @else if (article.relevant === false) { + + cancel + Nicht relevant + + } @else { + + help + Nicht bestimmt + + } diff --git a/webapp/src/app/modules/news/news.component.scss b/webapp/src/app/modules/news/news.component.scss index 68a1899f..def9857d 100644 --- a/webapp/src/app/modules/news/news.component.scss +++ b/webapp/src/app/modules/news/news.component.scss @@ -114,6 +114,42 @@ table { background: transparent; } +.relevance-badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 5px 12px; + border-radius: 999px; + font-size: 13px; + font-weight: 600; + line-height: 1; + white-space: nowrap; + + mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + + &.is-relevant { + background: #effaf3; + border: 1px solid #bdebcf; + color: #24834f; + } + + &.not-relevant { + background: var(--sg-surface-muted); + border: 1px solid #e2e2e2; + color: var(--sg-text-muted); + } + + &.undetermined { + background: #fff7e8; + border: 1px solid #ffd796; + color: #c67500; + } +} + ::ng-deep .mat-mdc-header-cell { color: var(--sg-text-muted); font-size: 12px; diff --git a/webapp/src/app/modules/news/news.component.ts b/webapp/src/app/modules/news/news.component.ts index e6990dbb..89a3d1e4 100644 --- a/webapp/src/app/modules/news/news.component.ts +++ b/webapp/src/app/modules/news/news.component.ts @@ -21,6 +21,7 @@ interface NewsArticle { maintitle?: string | null; author?: string | null; url?: string | null; + relevant?: boolean | null; } interface NewsPage { @@ -59,7 +60,7 @@ export class NewsComponent implements OnInit { readonly searchControl = new FormControl('', { nonNullable: true }); - displayedColumns = ['maintitle', 'author', 'date']; + displayedColumns = ['maintitle', 'relevance', 'date']; articles: NewsArticle[] = []; total = 0; loading = false; From 9dadc1f12f3b923ae103b27890a93f45ea2f3671 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 15:33:16 +0200 Subject: [PATCH 12/22] extends es-client with highlighting --- service/src/main/inse/integrations/elasticsearch.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 870d833f..f1b405ba 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -24,6 +24,7 @@ def search( sort: list = None, body: dict = None, track_total_hits = False, + highlight: dict = None, cluster: str = "nes", ) -> dict[str, Any]: @@ -48,6 +49,8 @@ def search( payload["sort"] = sort if track_total_hits: payload["track_total_hits"] = True + if highlight is not None: + payload["highlight"] = highlight else: payload = { "query": { From db5156a02d91eb3618398063f7c304f42784bb97 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 15:39:06 +0200 Subject: [PATCH 13/22] feat: display search findings directly in news --- service/src/main/inse/news/logic.py | 17 +++++++++++++++-- service/src/main/inse/news/model.py | 1 + webapp/src/app/modules/news/news.component.html | 11 +++++++++++ webapp/src/app/modules/news/news.component.scss | 17 +++++++++++++++++ webapp/src/app/modules/news/news.component.ts | 9 ++++++++- 5 files changed, 52 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index f5599ddf..82847a96 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -33,12 +33,20 @@ def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPa def search_news(query_text: str, page: int, page_size: int) -> NewsPage: offset = (page - 1) * page_size + highlight = { + "fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}}, + "pre_tags": [""], + "post_tags": [""], + "encoder": "html", + } + response = _run_search( query={"match": {"full_content": query_text}}, source=["date", "maintitle", "author", "url"], size=page_size, offset=offset, sort=None, + highlight=highlight, ) return _build_page(response, page, page_size) @@ -159,7 +167,7 @@ def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]: return relevant, authors -def _run_search(query: dict, source: list, size: int, offset: int, sort) -> dict: +def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict: try: return elasticsearch.search( index="aktuell", @@ -169,6 +177,7 @@ def _run_search(query: dict, source: list, size: int, offset: int, sort) -> dict offset=offset, sort=sort, track_total_hits=True, + highlight=highlight, cluster="inse", ) except Exception as exc: @@ -234,11 +243,15 @@ def _get_relevance_map(news_ids: list) -> dict: def _parse_hit(hit: dict) -> NewsArticle: source = hit.get("_source", {}) - + + fragments = hit.get("highlight", {}).get("full_content") + snippet = fragments[0] if fragments else None + return NewsArticle( id=hit.get("_id"), date=source.get("date"), maintitle=source.get("maintitle"), author=source.get("author"), url=source.get("url"), + snippet=snippet, ) diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index 83b593b3..be32ee80 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -13,6 +13,7 @@ class NewsArticle(BaseModel): author: Optional[str] = None url: Optional[str] = None relevant: Optional[bool] = None + snippet: Optional[str] = None class NewsArticleDetail(NewsArticle): diff --git a/webapp/src/app/modules/news/news.component.html b/webapp/src/app/modules/news/news.component.html index bfd8cba1..aff9aadc 100644 --- a/webapp/src/app/modules/news/news.component.html +++ b/webapp/src/app/modules/news/news.component.html @@ -42,6 +42,17 @@ + + Fundstelle + + @if (article.snippet) { + + } @else { + — + } + + + Relevanz diff --git a/webapp/src/app/modules/news/news.component.scss b/webapp/src/app/modules/news/news.component.scss index def9857d..100dead9 100644 --- a/webapp/src/app/modules/news/news.component.scss +++ b/webapp/src/app/modules/news/news.component.scss @@ -114,6 +114,23 @@ table { background: transparent; } +.snippet { + color: var(--sg-text-muted); + font-size: 13px; + line-height: 1.4; +} + +::ng-deep .snippet em { + font-style: normal; + background: #fff48d; + padding: 0 3px; + border-radius: 3px; +} + +.snippet-empty { + color: var(--sg-text-muted); +} + .relevance-badge { display: inline-flex; align-items: center; diff --git a/webapp/src/app/modules/news/news.component.ts b/webapp/src/app/modules/news/news.component.ts index 89a3d1e4..3c1ff74c 100644 --- a/webapp/src/app/modules/news/news.component.ts +++ b/webapp/src/app/modules/news/news.component.ts @@ -22,6 +22,7 @@ interface NewsArticle { author?: string | null; url?: string | null; relevant?: boolean | null; + snippet?: string | null; } interface NewsPage { @@ -60,7 +61,13 @@ export class NewsComponent implements OnInit { readonly searchControl = new FormControl('', { nonNullable: true }); - displayedColumns = ['maintitle', 'relevance', 'date']; + get displayedColumns(): string[] { + if (this.isSearching) { + return ['maintitle', 'snippet', 'relevance', 'date']; + } + return ['maintitle', 'relevance', 'date']; + } + articles: NewsArticle[] = []; total = 0; loading = false; From 124d65f8c9bdd671d9081a8894d9e62695135306 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sat, 20 Jun 2026 15:50:55 +0200 Subject: [PATCH 14/22] Added eu projects for single persons by DOI publication mapping --- .../person-projects.component.html | 27 +++++++ .../person-projects.component.ts | 72 +++++++++++++++++-- .../person-cordis-eu-project-page.resolver.ts | 13 +--- 3 files changed, 93 insertions(+), 19 deletions(-) diff --git a/webapp/src/app/modules/person-projects/person-projects.component.html b/webapp/src/app/modules/person-projects/person-projects.component.html index 90e01edf..e33bdee6 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.html +++ b/webapp/src/app/modules/person-projects/person-projects.component.html @@ -28,6 +28,11 @@ [sortDirection]="urlSortDirection()" (sortChange)="handleSortChange($event)" /> + + +
+ + + {{ element.startDate | date: 'dd.MM.yyyy' }} + + + + {{ element.endDate | date: 'dd.MM.yyyy' }} + + + + {{ element.ecMaxContribution | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} + + + + + open_in_new + + diff --git a/webapp/src/app/modules/person-projects/person-projects.component.ts b/webapp/src/app/modules/person-projects/person-projects.component.ts index 3b7ad95e..9e208870 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -9,6 +9,7 @@ import { viewChild, } from '@angular/core'; import { + CordisEuProject, CordisEuProjectPage, DfgProjectPage, DfgProjectSummary, @@ -28,6 +29,7 @@ import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; import { Sort, SortDirection } from '@angular/material/sort'; +import { CurrencyPipe, DatePipe } from '@angular/common'; @Component({ selector: 'app-person-projects', @@ -42,6 +44,8 @@ import { Sort, SortDirection } from '@angular/material/sort'; DebounceDirective, MatPaginatorModule, RouterModule, + DatePipe, + CurrencyPipe, ], templateUrl: './person-projects.component.html', styleUrl: './person-projects.component.scss', @@ -51,8 +55,6 @@ export class PersonProjectsComponent implements OnInit { dfgProjectColumns: GenericColumn[] = []; dfgProjectData: DfgProjectSummary[] = []; - personCordisEuProjectPage = input.required(); - dfgProjectFundingEndTmp = viewChild.required>( 'dfgProjectFundingEndTmp', ); @@ -63,6 +65,23 @@ export class PersonProjectsComponent implements OnInit { 'dfgProjectDetailRowTmp', ); + personCordisEuProjectPage = input.required(); + personCordisEuProjectColumns: GenericColumn[] = []; + personCordisEuProjectData: CordisEuProject[] = []; + + euProjectsFundingStartTmp = viewChild.required>( + 'euProjectsFundingStartTmp', + ); + euProjectsFundingEndTmp = viewChild.required>( + 'euProjectsFundingEndTmp', + ); + euProjectsFundingAmountTmp = viewChild.required>( + 'euProjectsFundingAmountTmp', + ); + euProjectsActionsTmp = viewChild.required>( + 'euProjectsActionsTmp', + ); + urlSearchTerm = signal(''); urlSortKey = signal(''); urlSortDirection = signal(''); @@ -90,18 +109,24 @@ export class PersonProjectsComponent implements OnInit { }); effect(() => { - console.log( - 'PersonProjectsComponent: dfgProjectPage changed', - this.dfgProjectPage(), - ); this.dfgProjectData = this.dfgProjectPage().elements || []; }); + effect(() => { + console.log( + 'Updating personCordisEuProjectData with', + this.personCordisEuProjectPage(), + ); + + this.personCordisEuProjectData = + this.personCordisEuProjectPage().elements || []; + }); + effect(() => { const searchTerm = this.urlSearchTerm(); if (searchTerm) { this.router.navigate([], { - queryParams: { search: searchTerm }, + queryParams: { search: searchTerm, page: 0, size: this.pageSize() }, queryParamsHandling: 'merge', }); } @@ -137,6 +162,39 @@ export class PersonProjectsComponent implements OnInit { cellTemplate: this.dfgProjectActionsTmp(), }, ]; + + this.personCordisEuProjectColumns = [ + { + id: 'title', + header: 'Titel', + type: 'accessor', + accessorKey: 'title', + }, + { + id: 'startDate', + header: 'Startdatum', + type: 'display', + cellTemplate: this.euProjectsFundingStartTmp(), + }, + { + id: 'endDate', + header: 'Enddatum', + type: 'display', + cellTemplate: this.euProjectsFundingEndTmp(), + }, + { + id: 'ecMaxContribution', + header: 'Förderbetrag (EU)', + type: 'display', + cellTemplate: this.euProjectsFundingAmountTmp(), + }, + { + id: 'actions', + header: '', + type: 'display', + cellTemplate: this.euProjectsActionsTmp(), + }, + ]; } handleSearchTermChange(newTerm: string): void { diff --git a/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts b/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts index fa15f0d1..90427263 100644 --- a/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts +++ b/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts @@ -9,16 +9,5 @@ export const personCordisEuProjectPageResolver: ResolveFn< if (!rawAuthorId) { throw new Error('Author ID is required to resolve collaboration network'); } - - console.log('Before calling getEuProjectsForAuthor'); - inject(ProjectsService) - .getEuProjectsForAuthor(rawAuthorId) - .subscribe({ - next: (data) => { - console.log('Received data from getEuProjectsForAuthor:', data); - }, - }); - console.log('After calling getEuProjectsForAuthor'); - - return { elements: [], total: 0, page: 1, page_size: 10 }; + return inject(ProjectsService).getEuProjectsForAuthor(rawAuthorId); }; From c8b055902fb431e08f6ed7c8e94a7dc1993f1db5 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 17:03:45 +0200 Subject: [PATCH 15/22] Add badge with link to author profile in news --- service/src/main/inse/news/logic.py | 20 +++++-- service/src/main/inse/news/model.py | 8 ++- service/src/main/inse/persons/logic.py | 54 +++++++++++++++++++ .../news-detail/news-detail.component.html | 20 +++++-- .../news-detail/news-detail.component.scss | 25 ++++++++- .../news-detail/news-detail.component.ts | 8 ++- 6 files changed, 124 insertions(+), 11 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 82847a96..5f22b9eb 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -10,8 +10,8 @@ from fastapi import HTTPException from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR from ..integrations import elasticsearch -from ..persons.logic import get_author_name_by_id -from .model import NewsArticle, NewsArticleDetail, NewsPage +from ..persons.logic import find_ude_author_by_name, get_author_name_by_id +from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage logger = logging.getLogger(__name__) @@ -139,10 +139,24 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: url=source.get("url"), full_content=source.get("full_content"), relevant=relevant, - authors=authors, + authors=_build_mentioned_persons(authors), ) +def _build_mentioned_persons(author_names: list) -> list: + + persons = [] + for name in author_names: + match = find_ude_author_by_name(name) + if match: + persons.append( + MentionedPerson(name=name, is_ude=True, person_id=match["id"]) + ) + else: + persons.append(MentionedPerson(name=name)) + return persons + + def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]: try: response = elasticsearch.search( diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index be32ee80..723e9b49 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -16,10 +16,16 @@ class NewsArticle(BaseModel): snippet: Optional[str] = None +class MentionedPerson(BaseModel): + name: str + is_ude: bool = False + person_id: Optional[str] = None + + class NewsArticleDetail(NewsArticle): full_content: Optional[str] = None relevant: Optional[bool] = None - authors: List[str] = [] + authors: List[MentionedPerson] = [] class NewsPage(BaseModel): diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 76db43c7..458ecc23 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -30,6 +30,60 @@ from inse.persons.model import ( ) logger = logging.getLogger(__name__) INDEX_NAME = "openalex-authors" +UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen + +def find_ude_author_by_name(display_name: str) -> Optional[dict]: + query = { + "_source": ["display_name"], + "query": { + "bool": { + "must": [ + { + "match_phrase": { + "display_name": display_name + } + }, + { + "nested": { + "path": "affiliations", + "query": { + "term": { + "affiliations.institution.id": UDE_INSTITUTION_ID + } + }, + } + }, + ] + } + }, + "size": 10, + } + + try: + data = elasticsearch.search(index=INDEX_NAME, body=query) + except Exception: + logger.exception(f"UDE-Lookup für '{display_name}' fehlgeschlagen.") + return None + + hits = data.get("hits", {}).get("hits", []) + + display_name = display_name.strip().lower() + exact_matches = [] + + for hit in hits: + hit_display_name = hit.get("_source", {}).get("display_name", "") + if hit_display_name.strip().lower() == display_name: + exact_matches.append(hit) + + if not exact_matches: + return None + + hit = exact_matches[0] + + return { + "id": hit.get("_id"), + "display_name": hit.get("_source", {}).get("display_name"), + } def get_author_name_by_id(author_id: str) -> Optional[str]: diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index ce499e8d..1bc97e7c 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -82,11 +82,21 @@
@if (article.authors && article.authors.length) { - @for (person of article.authors; track person) { -
-
{{ person.charAt(0) }}
- {{ person }} -
+ @for (person of article.authors; track person.name) { + @if (person.is_ude && person.person_id) { + +
{{ person.name.charAt(0) }}
+ {{ person.name }} + UDE +
+ } @else { +
+
{{ person.name.charAt(0) }}
+ {{ person.name }} +
+ } } } @else {

Keine erwähnten Personen gefunden.

diff --git a/webapp/src/app/modules/news-detail/news-detail.component.scss b/webapp/src/app/modules/news-detail/news-detail.component.scss index 02101fda..e1669060 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.scss +++ b/webapp/src/app/modules/news-detail/news-detail.component.scss @@ -184,7 +184,7 @@ main { .person-item { display: grid; - grid-template-columns: 38px minmax(0, 1fr); + grid-template-columns: 38px minmax(0, 1fr) auto; gap: 11px; align-items: center; padding: 12px; @@ -192,6 +192,29 @@ main { background: var(--sg-surface-muted); } +.person-item.is-link { + cursor: pointer; + text-decoration: none; + color: inherit; + transition: background 0.15s ease; +} + +.person-item.is-link:hover { + background: #e5ecfb; +} + +.ude-badge { + justify-self: end; + padding: 3px 9px; + border-radius: 999px; + background: #effaf3; + border: 1px solid #bdebcf; + color: #24834f; + font-size: 11px; + font-weight: 700; + letter-spacing: 0.03em; +} + .avatar { display: grid; place-items: center; diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts index 5c51b52c..bd75dc3c 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.ts +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -9,6 +9,12 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { WorksService } from '../../api'; +interface MentionedPerson { + name: string; + is_ude?: boolean; + person_id?: string | null; +} + interface NewsArticleDetail { id: string; date?: string | null; @@ -17,7 +23,7 @@ interface NewsArticleDetail { url?: string | null; full_content?: string | null; relevant?: boolean; - authors?: string[]; + authors?: MentionedPerson[]; } @Component({ From be74063a5171b693c74124154313e5c124163f15 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 17:10:30 +0200 Subject: [PATCH 16/22] order person list in news to show ude authors on top --- service/src/main/inse/news/logic.py | 11 +++++++---- .../modules/news-detail/news-detail.component.html | 2 +- .../modules/news-detail/news-detail.component.scss | 11 +++++++++++ 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 5f22b9eb..48e7f5ff 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -145,16 +145,19 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: def _build_mentioned_persons(author_names: list) -> list: - persons = [] + ude_persons = [] + other_persons = [] + for name in author_names: match = find_ude_author_by_name(name) if match: - persons.append( + ude_persons.append( MentionedPerson(name=name, is_ude=True, person_id=match["id"]) ) else: - persons.append(MentionedPerson(name=name)) - return persons + other_persons.append(MentionedPerson(name=name)) + + return ude_persons + other_persons def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]: diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index 1bc97e7c..dc1a3fc0 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -92,7 +92,7 @@ UDE } @else { -
+
{{ person.name.charAt(0) }}
{{ person.name }}
diff --git a/webapp/src/app/modules/news-detail/news-detail.component.scss b/webapp/src/app/modules/news-detail/news-detail.component.scss index e1669060..82f7b1ac 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.scss +++ b/webapp/src/app/modules/news-detail/news-detail.component.scss @@ -203,6 +203,17 @@ main { background: #e5ecfb; } +.person-item.is-muted { + .avatar { + background: #ececef; + color: var(--sg-text-muted); + } + + .person-name { + color: var(--sg-text-muted); + } +} + .ude-badge { justify-self: end; padding: 3px 9px; From 3b16f8d8fc36bcd18ee144f57547c921d1b14c96 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 20:31:13 +0200 Subject: [PATCH 17/22] extract latest institution from affiliations if last_known_institutions is null --- .../person-card/person-card.component.ts | 24 +++++++++++++++---- .../app/modules/person/person.component.ts | 21 +++++++++------- 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts index 89f0440c..6502b9c5 100644 --- a/webapp/src/app/modules/person-card/person-card.component.ts +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -36,11 +36,25 @@ export class PersonCardComponent { } institution(person: CustomAuthor): DehydratedInstitution | undefined { - return ( - person.last_known_institutions?.[0] || - person.affiliations?.[person.affiliations.length - 1]?.institution || - undefined - ); + if (person.last_known_institutions?.[0]) { + return person.last_known_institutions[0]; + } + + const affiliations = person.affiliations ?? []; + let newestInstitution: DehydratedInstitution | undefined = + affiliations[0]?.institution ?? undefined; + let newestYear = -1; + + for (const affiliation of affiliations) { + for (const jahr of affiliation.years ?? []) { + if (jahr > newestYear) { + newestYear = jahr; + newestInstitution = affiliation.institution ?? undefined; + } + } + } + + return newestInstitution; } topics(person: CustomAuthor): WorkTopic[] { diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index a74be3fe..13b866bd 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -119,15 +119,20 @@ export class PersonComponent { () => this.person()?.affiliations?.[0] ?? null, ); readonly lastAffiliation = computed(() => { - let lastAffiliation: number | undefined = 0; - if (this.person()?.affiliations?.length != undefined) { - lastAffiliation = this.person()?.affiliations?.length; + const affiliations = this.person()?.affiliations ?? []; + let newestAffiliation = affiliations[0] ?? null; + let newestYear = -1; + + for (const affiliation of affiliations) { + for (const jahr of affiliation.years ?? []) { + if (jahr > newestYear) { + newestYear = jahr; + newestAffiliation = affiliation; + } + } } - return ( - (lastAffiliation - ? this.person()?.affiliations?.[lastAffiliation - 1] - : this.person()?.affiliations?.[0]) ?? null - ); + + return newestAffiliation; }); readonly institution = computed( () => From d1588ac5c1d9c4264a99d84522dd8aaf8c47647a Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 21:14:17 +0200 Subject: [PATCH 18/22] Resolve conflicts in generated OpenAPI client by regenerating from dev --- webapp/src/app/api/model/fundingProjectPage.ts | 18 ------------------ webapp/src/app/api/model/keywords.ts | 3 --- webapp/src/app/api/model/topics.ts | 4 ---- webapp/src/app/api/model/yearlyData.ts | 6 ------ 4 files changed, 31 deletions(-) diff --git a/webapp/src/app/api/model/fundingProjectPage.ts b/webapp/src/app/api/model/fundingProjectPage.ts index 6641656a..e0996525 100644 --- a/webapp/src/app/api/model/fundingProjectPage.ts +++ b/webapp/src/app/api/model/fundingProjectPage.ts @@ -9,24 +9,6 @@ */ import { FundingProject } from './fundingProject'; -export interface EuProjectPage { - /** - * The current page number. - */ - page?: number; - /** - * The requested page size. - */ - size?: number; - /** - * The total number of items. - */ - total?: number; - /** - * The EU projects on this page. - */ - elements?: Array; -} export interface FundingProjectPage { /** * The current page number. diff --git a/webapp/src/app/api/model/keywords.ts b/webapp/src/app/api/model/keywords.ts index 51be69db..d93b5fe0 100644 --- a/webapp/src/app/api/model/keywords.ts +++ b/webapp/src/app/api/model/keywords.ts @@ -8,9 +8,6 @@ * Do not edit the class manually. */ -export interface DisplayCodeSplittedNested { - single_display_code?: string | null; -} /** * Keywords associated with the project */ diff --git a/webapp/src/app/api/model/topics.ts b/webapp/src/app/api/model/topics.ts index ff61fde6..cf40ff1d 100644 --- a/webapp/src/app/api/model/topics.ts +++ b/webapp/src/app/api/model/topics.ts @@ -8,8 +8,4 @@ * Do not edit the class manually. */ -export interface KeywordNested { - keyword?: string | null; -} - export interface Topics {} diff --git a/webapp/src/app/api/model/yearlyData.ts b/webapp/src/app/api/model/yearlyData.ts index c6920fac..d473f13e 100644 --- a/webapp/src/app/api/model/yearlyData.ts +++ b/webapp/src/app/api/model/yearlyData.ts @@ -8,12 +8,6 @@ * Do not edit the class manually. */ -export interface ProgrammeNested { - code?: string | null; - id?: string | null; - programme?: string | null; -} - export interface YearlyData { year: number; publications: number; From 84f3314b60305f827f80dae21c44d33accc275e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 21 Jun 2026 14:07:39 +0200 Subject: [PATCH 19/22] Fixed institution cordis eu funding amount to show the amount actually received not total for project --- .../main/inse/integrations/elasticsearch.py | 51 +++- service/src/main/inse/model.py | 27 ++- service/src/main/inse/projects/model.py | 64 +++++ .../inse/projects/projects_search_client.py | 222 +++++++++++++++++- service/src/main/inse/projects/router.py | 8 +- service/src/main/inse/projects/service.py | 72 +++--- ude_person.http | 50 +++- webapp/src/app/api/.openapi-generator/FILES | 2 + webapp/src/app/api/api/projects.service.ts | 10 +- .../api/model/euOrganizationProjectSummary.ts | 27 +++ .../model/euOrganizationProjectSummaryPage.ts | 31 +++ webapp/src/app/api/model/models.ts | 2 + .../institution-projects.component.html | 16 +- .../institution-projects.component.ts | 41 +++- .../cordis-eu-project-page.resolver.ts | 4 +- 15 files changed, 543 insertions(+), 84 deletions(-) create mode 100644 webapp/src/app/api/model/euOrganizationProjectSummary.ts create mode 100644 webapp/src/app/api/model/euOrganizationProjectSummaryPage.ts diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 449b748f..bd32501a 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -1,16 +1,18 @@ import logging from typing import Any, Dict, List, Optional, Tuple import httpx + +from inse.model import ESCluster, ESIndex from .. import config logger = logging.getLogger(__name__) -def _cluster_credentials(cluster: str) -> Tuple[str, str]: +def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]: """Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration. Args: - cluster (str): The cluster for which to retrieve credentials. Allowed values are "nes" and "inse". + cluster (ElasticsearchCluster): The cluster for which to retrieve credentials. Allowed values are "nes" and "inse". Raises: ValueError: If the cluster is unknown or the credentials are not set in the configuration. @@ -19,7 +21,7 @@ def _cluster_credentials(cluster: str) -> Tuple[str, str]: Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster. """ - if cluster == "nes": + if cluster == ESCluster.NES: if ( not config.settings.elasticsearch_url or not config.settings.elasticsearch_api_key @@ -28,7 +30,7 @@ def _cluster_credentials(cluster: str) -> Tuple[str, str]: "Elasticsearch URL and API key must be set in the configuration for cluster 'nes'" ) return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key - elif cluster == "inse": + elif cluster == ESCluster.INSE: if ( not config.settings.elasticsearch_inse_url or not config.settings.elasticsearch_inse_api_key @@ -45,8 +47,37 @@ def _cluster_credentials(cluster: str) -> Tuple[str, str]: raise ValueError(f"Unknown cluster: {cluster!r} (allowed: 'nes', 'inse')") +def _index_to_cluster(index: ESIndex) -> ESCluster: + """Determines the Elasticsearch cluster to use based on the specified index. + + Args: + index (ESIndex): The Elasticsearch index for which to determine the cluster. Allowed values are defined in the ESIndex enum. + + Raises: + ValueError: If the index is unknown. + + Returns: + ESCluster: The Elasticsearch cluster to use for the specified index. + """ + + if index in { + ESIndex.OPENALEX_WORKS, + ESIndex.OPENALEX_AUTHORS, + ESIndex.OPENALEX_INSTITUTIONS, + ESIndex.OPENALEX_PUBLICATIONS, + }: + return ESCluster.NES + elif index in { + ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + }: + return ESCluster.INSE + else: + raise ValueError(f"Unknown index: {index!r}") + + def search( - index: str, + index: ESIndex, query_field: Optional[str] = None, query_value: Optional[str] = None, query: Optional[Dict] = None, @@ -56,12 +87,12 @@ def search( sort: Optional[List] = None, body: Optional[Dict] = None, track_total_hits=False, - cluster: str = "nes", + cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: """Searches the specified Elasticsearch index using either a simple query string or a full query body. Args: - index (str): The name of the Elasticsearch index to search. + index (ElasticsearchIndex): The Elasticsearch index to search. query_field (Optional[str], optional): The field to search in. Defaults to None. query_value (Optional[str], optional): The value to search for. Defaults to None. query (Optional[Dict], optional): The full query body. Defaults to None. @@ -71,7 +102,7 @@ def search( sort (Optional[List], optional): The fields to sort by. Defaults to None. body (Optional[Dict], optional): The full query body. Defaults to None. track_total_hits (bool, optional): Whether to track the total number of hits. Defaults to False. - cluster (str, optional): The Elasticsearch cluster to search. Defaults to "nes". + cluster (ElasticsearchCluster, optional): The Elasticsearch cluster to search. Defaults to ElasticsearchCluster.NES. Returns: Dict[str, Any]: The search results. @@ -116,10 +147,10 @@ def search( def get( - index: str, + index: ESIndex, doc_id: str, source: Optional[list] = None, - cluster: str = "nes", + cluster: ESCluster = ESCluster.NES, ) -> dict[str, Any]: elasticsearch_url, api_key = _cluster_credentials(cluster) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 669f049f..55d556eb 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -1,9 +1,12 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- """ - This module defines the model classes returned from - our api using pydantic. +This module defines the model classes returned from +our api using pydantic. """ + +from enum import StrEnum + from pydantic import BaseModel from pydantic import ConfigDict from pydantic import Field @@ -13,28 +16,46 @@ from typing import Generic from typing import Optional -T = TypeVar('T', bound=BaseModel) +T = TypeVar("T", bound=BaseModel) + class Entity(BaseModel): id: int = Field(description="The id of the entity.") + class Item(Entity): model_config = ConfigDict(from_attributes=True) name: str = Field(description="The name of the item.") description: str = Field(description="The description of the item.") + class ItemCreate(BaseModel): name: str = Field(description="The name of the item.") description: str = Field(description="The description of the item.") + class Page(BaseModel, Generic[T]): elements: List[T] = Field(default=[], description="The elements of the page.") offset: int = Field(default=0, description="The page offset in elements.") total: int = Field(default=0, description="The total number of elements.") size: int = Field(default=20, description="The page size in elements.") + class ItemPage(Page[Item]): pass +class ESCluster(StrEnum): + NES = "nes" + INSE = "inse" + +class ESIndex(StrEnum): + OPENALEX_WORKS = "openalex-works" + OPENALEX_AUTHORS = "openalex-authors" + OPENALEX_INSTITUTIONS = "openalex-institutions" + OPENALEX_PUBLICATIONS = "openalex-publications" + + CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" + CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects" + CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications" diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index dd75726f..ed58fe8e 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -22,6 +22,15 @@ class ProjectsSortBy(StrEnum): FUNDING_END = "funding_end" FUNDING_AMOUNT = "funding_amount" + def to_cordis_eu_project_sort_field(self) -> str: + mapping = { + self.TITLE: "title.keyword", + self.FUNDING_START: "startDate", + self.FUNDING_END: "endDate", + self.FUNDING_AMOUNT: "ecMaxContribution", + } + return mapping.get(self, "title.keyword") + class SortDirection(StrEnum): ASC = "asc" @@ -225,3 +234,58 @@ class FundingProjectPage(Page): elements: List[FundingProject] = Field( default_factory=list, description="The funding projects on this page." ) + + +class EuOrganizationShort(BaseModel): + project_id: str = Field(description="The unique identifier of the project.") + organization_id: str = Field( + description="The unique identifier of the organization." + ) + ec_contribution: Optional[float] = Field( + default=None, + description="The EC contribution amount for the organization in the project.", + ) + + +class EuProjectShort(BaseModel): + id: str = Field(description="The unique identifier of the EU project.") + title: Optional[str] = Field( + default=None, description="The title of the EU project." + ) + start_date: Optional[date] = Field( + default=None, description="The funding start date of the EU project." + ) + end_date: Optional[date] = Field( + default=None, description="The funding end date of the EU project." + ) + acronym: Optional[str] = Field( + default=None, description="The acronym of the EU project." + ) + + +class EuOrganizationProjectSummary(BaseModel): + organization_id: str = Field( + description="The unique identifier of the organization." + ) + project_id: str = Field(description="The unique identifier of the project.") + title: Optional[str] = Field(default=None, description="The title of the project.") + start_date: Optional[date] = Field( + default=None, description="The funding start date of the project." + ) + end_date: Optional[date] = Field( + default=None, description="The funding end date of the project." + ) + acronym: Optional[str] = Field( + default=None, description="The acronym of the project." + ) + ec_contribution: Optional[float] = Field( + default=None, + description="The EC contribution amount for the organization in the project.", + ) + + +class EuOrganizationProjectSummaryPage(Page): + elements: List[EuOrganizationProjectSummary] = Field( + default_factory=list, + description="The organization project summaries on this page.", + ) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 3347fc3c..d11dd659 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -1,6 +1,6 @@ import json import logging -from typing import Any, Dict, List, Optional, Set +from typing import Any, Dict, List, Optional, Set, Tuple import httpx @@ -11,7 +11,10 @@ from inse.projects.model import ( CordisEuProjectPage, DfgProjectPage, DfgProjectSummary, - EuProjectPage, + EuOrganizationProjectSummary, + EuOrganizationProjectSummaryPage, + EuOrganizationShort, + EuProjectShort, FundingProject, FundingProjectPage, ProjectType, @@ -19,11 +22,12 @@ from inse.projects.model import ( ProjectsSortBy, SortDirection, ) -from inse.models.eu_project import EuProject + from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails from inse.models.cordis_eu_project import CordisEuProject from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex settings = get_settings() @@ -494,7 +498,9 @@ class EuProjectsSearchClient(ProjectsSearchClient): query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} response = elasticsearch.search( - query=query, index="cordis_eu_*_publications", cluster="inse" + query=query, + index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + cluster=ESCluster.INSE, ) logger.debug( @@ -528,7 +534,9 @@ class EuProjectsSearchClient(ProjectsSearchClient): query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}} response = elasticsearch.search( - query=query, index="cordis_eu_*_projects", cluster="inse" + query=query, + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, ) hits_block = response.get("hits", {}) @@ -903,3 +911,207 @@ def _hit_to_funding_project(hit: Dict[str, Any]) -> FundingProject: raise ValueError( "The provided hit does not belong to a recognized project index." ) + + +def get_organization_project_contributions_foo( + organization_names: List[str], + projects_filtering_properties: ProjectsFilteringProperties, +) -> EuOrganizationProjectSummaryPage: + # Pagination depending on sorting criteria + # For FUNDING_AMOUNT before on the organization project contributions + # For the rest after the contributions are known on the real projects + + organization_project_contributions = get_organization_project_contributions( + organization_names=organization_names, + ) + + total_projects, projects = get_projects( + project_contributions=list(organization_project_contributions.values()), + projects_filtering_properties=projects_filtering_properties, + ) + + elements: List[EuOrganizationProjectSummary] = _merge_project_data( + projects=projects, contributions=organization_project_contributions + ) + + if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: + elements.sort( + key=lambda x: x.ec_contribution or 0, + reverse=projects_filtering_properties.sort_direction == SortDirection.DESC, + ) + start = projects_filtering_properties.page * projects_filtering_properties.size + end = start + projects_filtering_properties.size + elements = elements[start:end] + + return EuOrganizationProjectSummaryPage( + elements=elements, + total=total_projects, + page=projects_filtering_properties.page, + size=projects_filtering_properties.size, + ) + + +def get_organization_project_contributions( + organization_names: List[str], +) -> Dict[str, EuOrganizationShort]: + + source = ["projectID", "organisationID", "ecContribution"] + + query = { + "terms": { + "name.keyword": [ + name.upper() for name in organization_names if name.strip() + ], + } + } + + response = elasticsearch.search( + index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, + cluster=ESCluster.INSE, + source=source, + size=10000, + query=query, + ) + + logger.debug( + f"Received organization project contributions response: {json.dumps(response, indent=2)}" + ) + + organization_project_contributions = _process_organization_project_contributions( + response + ) + + logger.debug( + f"Found organization project contributions for organization names {organization_names}: {organization_project_contributions}" + ) + + return organization_project_contributions + + +def _process_organization_project_contributions( + response: Dict[str, Any], +) -> Dict[str, EuOrganizationShort]: + hits_block = response.get("hits", {}) + project_contributions: Dict[str, EuOrganizationShort] = {} + for hit in hits_block.get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + organization_id = source.get("organisationID") + ec_contribution = source.get("ecContribution") + if project_id and organization_id: + project_contributions[project_id] = EuOrganizationShort( + project_id=project_id, + organization_id=organization_id, + ec_contribution=ec_contribution, + ) + return project_contributions + + +def get_projects( + project_contributions: List[EuOrganizationShort], + projects_filtering_properties: ProjectsFilteringProperties, +) -> Tuple[int, Dict[str, EuProjectShort]]: + project_ids = [contribution.project_id for contribution in project_contributions] + + source = ["id", "title", "startDate", "endDate", "acronym"] + + query = { + "terms": { + "id": project_ids, + } + } + + if ( + projects_filtering_properties.query + and projects_filtering_properties.query.strip() + ): + query = { + "bool": { + "must": [ + { + "match_phrase_prefix": { + "title": { + "query": projects_filtering_properties.query, + "max_expansions": 50, + } + } + } + ], + "filter": query, + } + } + + # Project contributions have been filtered before based on ecContribution + if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: + response = elasticsearch.search( + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + source=source, + query=query, + size=10000, + ) + else: + response = elasticsearch.search( + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + source=source, + query=query, + size=projects_filtering_properties.size, + offset=projects_filtering_properties.page + * projects_filtering_properties.size, + sort=[ + { + projects_filtering_properties.sort_by.to_cordis_eu_project_sort_field(): { + "order": projects_filtering_properties.sort_direction + } + } + ], + ) + + return _process_projects_response(response) + + +def _process_projects_response( + response: Dict[str, Any], +) -> Tuple[int, Dict[str, EuProjectShort]]: + hits_block = response.get("hits", {}) + total = hits_block.get("total", {}).get("value", 0) + projects: Dict[str, EuProjectShort] = {} + for hit in hits_block.get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("id") + title = source.get("title") + start_date = source.get("startDate") + end_date = source.get("endDate") + acronym = source.get("acronym") + if not project_id: + continue + projects[project_id] = EuProjectShort( + id=project_id, + title=title, + start_date=start_date, + end_date=end_date, + acronym=acronym, + ) + + return total, projects + + +def _merge_project_data( + projects: Dict[str, EuProjectShort], contributions: Dict[str, EuOrganizationShort] +) -> List[EuOrganizationProjectSummary]: + merged_data = [] + for project_id, project_info in projects.items(): + contribution_info = contributions.get(project_id) + if contribution_info: + merged_entry = EuOrganizationProjectSummary( + project_id=project_id, + title=project_info.title, + start_date=project_info.start_date, + end_date=project_info.end_date, + acronym=project_info.acronym, + organization_id=contribution_info.organization_id, + ec_contribution=contribution_info.ec_contribution, + ) + merged_data.append(merged_entry) + return merged_data diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 7d6e45f9..568abeae 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -8,6 +8,7 @@ from inse.projects.model import ( BundProjectPage, CordisEuProjectPage, DfgProjectPage, + EuOrganizationProjectSummaryPage, FundingProjectPage, InstitutionFunderSummary, ProjectType, @@ -211,7 +212,7 @@ async def get_institution_bund_projects_funding_over_time( responses={ status.HTTP_200_OK: { "description": "Successful Response", - "model": CordisEuProjectPage, + "model": EuOrganizationProjectSummaryPage, }, status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, }, @@ -226,9 +227,8 @@ async def search_cordis_eu_projects( ProjectsFilteringProperties, Body(description="The filtering properties for the projects search."), ], -) -> CordisEuProjectPage: - return await projects_service.search_cordis_eu_projects( - eu_search_client=eu_search_client, +) -> EuOrganizationProjectSummaryPage: + return projects_service.search_cordis_eu_projects( institutions_search_client=institutions_search_client, projects_filtering_properties=projects_filtering_properties, ) diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 9dde9e87..a725f0fa 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -7,12 +7,13 @@ from inse.projects.projects_search_client import ( CompleteProjectsSearchClient, DfgProjectsSearchClient, EuProjectsSearchClient, + get_organization_project_contributions_foo, ) from inse.projects.model import ( BundProjectPage, CordisEuProjectPage, DfgProjectPage, - EuProjectPage, + EuOrganizationProjectSummaryPage, FundingProjectPage, InstitutionFunderSummary, ProjectType, @@ -99,28 +100,25 @@ async def get_bund_projects_by_institution_id( return response -async def search_cordis_eu_projects( - eu_search_client: EuProjectsSearchClient, +def search_cordis_eu_projects( institutions_search_client: InstitutionsSearchClient, projects_filtering_properties: ProjectsFilteringProperties, -) -> CordisEuProjectPage: +) -> EuOrganizationProjectSummaryPage: if projects_filtering_properties.project_type != "eu": raise ValueError( f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'." ) - return await get_cordis_eu_projects_by_institution_id( - eu_search_client=eu_search_client, + return get_cordis_eu_projects_by_institution_id( institutions_search_client=institutions_search_client, projects_filtering_properties=projects_filtering_properties, ) -async def get_cordis_eu_projects_by_institution_id( - eu_search_client: EuProjectsSearchClient, +def get_cordis_eu_projects_by_institution_id( institutions_search_client: InstitutionsSearchClient, projects_filtering_properties: ProjectsFilteringProperties, -) -> CordisEuProjectPage: +) -> EuOrganizationProjectSummaryPage: if not projects_filtering_properties.raw_oa_institution_id: raise ValueError( "raw_oa_institution_id must be provided to fetch CORDIS EU projects by institution ID" @@ -138,28 +136,14 @@ async def get_cordis_eu_projects_by_institution_id( f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) - institution_eu_organisation_ids = ( - institutions_search_client.get_cordis_eu_organisation_ids_by_oa_institution_id( - projects_filtering_properties.raw_oa_institution_id - ) - ) - if not institution_eu_organisation_ids: - logger.debug( - f"No EU organization IDs found for institution_id={projects_filtering_properties.raw_oa_institution_id}" - ) - return CordisEuProjectPage( - elements=[], - total=0, - page=projects_filtering_properties.page, - size=projects_filtering_properties.size, - ) - - cordis_eu_project_page = await eu_search_client.search_eu_projects( - eu_organisation_ids=institution_eu_organisation_ids, + page = get_organization_project_contributions_foo( + organization_names=institution_aliases, projects_filtering_properties=projects_filtering_properties, ) - return cordis_eu_project_page + logger.debug(f"get_cordis_eu_projects_by_institution_id response: {page}") + + return page async def get_dfg_projects_by_author_id( @@ -199,12 +183,26 @@ async def get_institution_cordis_eu_projects_funding_over_time( raw_oa_institution_id: str, ) -> InstitutionFunderSummary: - cordis_eu_project_page = await search_cordis_eu_projects( - eu_search_client, - institutions_search_client, - ProjectsFilteringProperties( + # cordis_eu_project_page = await search_cordis_eu_projects( + # eu_search_client, + # institutions_search_client, + # ProjectsFilteringProperties( + # project_type=ProjectType.EU, + # raw_oa_institution_id=raw_oa_institution_id, + # page=0, + # size=10000, + # ), + # ) + + institution_aliases = ( + institutions_search_client.get_institution_aliases_by_oa_institution_id( + raw_oa_institution_id + ) + ) + page = get_organization_project_contributions_foo( + organization_names=institution_aliases, + projects_filtering_properties=ProjectsFilteringProperties( project_type=ProjectType.EU, - raw_oa_institution_id=raw_oa_institution_id, page=0, size=10000, ), @@ -212,10 +210,10 @@ async def get_institution_cordis_eu_projects_funding_over_time( return _calculate_funding_over_time( project_type=ProjectType.EU, - projects=cordis_eu_project_page.elements, - funding_start_attr="startDate", - funding_end_attr="endDate", - funding_amount_attr="totalCost", + projects=page.elements, + funding_start_attr="start_date", + funding_end_attr="end_date", + funding_amount_attr="ec_contribution", ) diff --git a/ude_person.http b/ude_person.http index f4691a10..9354020f 100644 --- a/ude_person.http +++ b/ude_person.http @@ -161,6 +161,26 @@ GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== Content-Type: application/json +{ + "size": 1000, + "query": { + "bool": { + "filter": [ + { + "term": { + "name.keyword": "UNIVERSITAET DUISBURG-ESSEN" + } + } + ] + } + } +} + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + { "size": 0, "query": { @@ -183,26 +203,38 @@ Content-Type: application/json } } +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_projects/_mapping +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + ### GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== Content-Type: application/json { - "size": 10, "query": { - "bool": { - "filter": [ - { - "term": { - "name.keyword": "UNIVERSITAET DUISBURG-ESSEN" - } - } + "terms": { + "name": [ + "UNIVERSITÄT DUISBURG-ESSEN", + "UNIVERSITY OF DUISBURG-ESSEN", + "UNIVERSITAT DUISBURG-ESSEN", + "UNIVERSITY OF DUISBURG ESSEN", + "UNIVERSITAT DUISBURG-ESSEN", + "UNIVERSITAET DUISBURG ESSEN", + "UNIVERSITÄT DUISBURG ESSEN", + "UNIVERSITAT DUISBURG ESSEN", + "UNIVERSITÄT DUISBURG-ESSEN", + "UNIVERSITAET DUISBURG-ESSEN", + "UNIVERSITY OF DUISBURG-ESSEN" ] } - } + }, + "_source": ["projectID", "organisationID", "ecContribution"] } + ### GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index a8e4f29f..d188cd69 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -59,6 +59,8 @@ model/dehydratedSource.ts model/dfgProjectDetails.ts model/dfgProjectPage.ts model/dfgProjectSummary.ts +model/euOrganizationProjectSummary.ts +model/euOrganizationProjectSummaryPage.ts model/filterInformation.ts model/filterProperties.ts model/funderByAuthor.ts diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index b3b91911..9edfb7fe 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -27,6 +27,8 @@ import { DfgProjectDetails } from '../model/dfgProjectDetails'; // @ts-ignore import { DfgProjectPage } from '../model/dfgProjectPage'; // @ts-ignore +import { EuOrganizationProjectSummaryPage } from '../model/euOrganizationProjectSummaryPage'; +// @ts-ignore import { FundingProjectPage } from '../model/fundingProjectPage'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; @@ -497,9 +499,9 @@ export class ProjectsService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (projectsFilteringProperties === null || projectsFilteringProperties === undefined) { throw new Error('Required parameter projectsFilteringProperties was null or undefined when calling searchCordisEuProjects.'); @@ -541,7 +543,7 @@ export class ProjectsService extends BaseService { let localVarPath = `/api/projects/institution/eu/search`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, + return this.httpClient.request('post', `${basePath}${localVarPath}`, { context: localVarHttpContext, body: projectsFilteringProperties, diff --git a/webapp/src/app/api/model/euOrganizationProjectSummary.ts b/webapp/src/app/api/model/euOrganizationProjectSummary.ts new file mode 100644 index 00000000..3cc10f0a --- /dev/null +++ b/webapp/src/app/api/model/euOrganizationProjectSummary.ts @@ -0,0 +1,27 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface EuOrganizationProjectSummary { + /** + * The unique identifier of the organization. + */ + organization_id: string; + /** + * The unique identifier of the project. + */ + project_id: string; + title?: string | null; + start_date?: string | null; + end_date?: string | null; + acronym?: string | null; + ec_contribution?: number | null; +} + diff --git a/webapp/src/app/api/model/euOrganizationProjectSummaryPage.ts b/webapp/src/app/api/model/euOrganizationProjectSummaryPage.ts new file mode 100644 index 00000000..9d57d5b4 --- /dev/null +++ b/webapp/src/app/api/model/euOrganizationProjectSummaryPage.ts @@ -0,0 +1,31 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { EuOrganizationProjectSummary } from './euOrganizationProjectSummary'; + + +export interface EuOrganizationProjectSummaryPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + /** + * The organization project summaries on this page. + */ + elements?: Array; +} + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 60006d17..0dd39ede 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -38,6 +38,8 @@ export * from './dehydratedSource'; export * from './dfgProjectDetails'; export * from './dfgProjectPage'; export * from './dfgProjectSummary'; +export * from './euOrganizationProjectSummary'; +export * from './euOrganizationProjectSummaryPage'; export * from './filterInformation'; export * from './filterProperties'; export * from './funderByAuthor'; diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.html b/webapp/src/app/modules/institution-projects/institution-projects.component.html index e4982ec6..ce7c7648 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.html +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.html @@ -75,7 +75,9 @@ undefined " /> + open_in_new + + + + + open_in_new + + diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.ts b/webapp/src/app/modules/institution-projects/institution-projects.component.ts index 4f547c61..42631284 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.ts +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.ts @@ -8,12 +8,12 @@ import { TemplateRef, viewChild, } from '@angular/core'; -import { ActivatedRoute, Router } from '@angular/router'; +import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { BundProject, BundProjectPage, - CordisEuProject, - CordisEuProjectPage, + EuOrganizationProjectSummary, + EuOrganizationProjectSummaryPage, InstitutionFunderSummary, } from '../../api'; import { MatCardModule } from '@angular/material/card'; @@ -36,6 +36,7 @@ import { InstitutionProjectsFundingGraphComponent } from '../institution-project import { PersonNetworkInfoCardComponent } from '../person-network-info-card/person-network-info-card.component'; type BundProjectRow = { + id: string; topic: string; funding_start: Date; funding_end: Date; @@ -44,6 +45,7 @@ type BundProjectRow = { }; type EuProjectRow = { + id: string; topic: string; funding_start: Date; funding_end: Date; @@ -67,6 +69,7 @@ type EuProjectRow = { MatButtonModule, InstitutionProjectsFundingGraphComponent, PersonNetworkInfoCardComponent, + RouterModule, ], templateUrl: './institution-projects.component.html', styleUrl: './institution-projects.component.scss', @@ -76,13 +79,19 @@ export class InstitutionProjectsComponent implements OnInit { fundingEndTmp = viewChild.required>('fundingEndTmp'); fundingAmountTmp = viewChild.required>('fundingAmountTmp'); - cordisEuProjectPage = input.required(); + cordisEuProjectPage = input.required(); euProjectColumns: GenericColumn[] = []; euProjectData: EuProjectRow[] = []; + euProjectActionsTmp = viewChild.required>( + 'euProjectActionsTmp', + ); bundProjectPage = input.required(); bundProjectColumns: GenericColumn[] = []; bundProjectData: BundProjectRow[] = []; + bundProjectActionsTmp = viewChild.required>( + 'bundProjectActionsTmp', + ); bundProjectsFunding = input.required(); bundTotalFunding = computed(() => { @@ -221,6 +230,12 @@ export class InstitutionProjectsComponent implements OnInit { accessorKey: 'funding_amount', cellTemplate: this.fundingAmountTmp(), }, + { + id: 'actions', + header: '', + type: 'display', + cellTemplate: this.euProjectActionsTmp(), + }, ]; this.bundProjectColumns = [ { @@ -250,22 +265,30 @@ export class InstitutionProjectsComponent implements OnInit { accessorKey: 'funding_amount', cellTemplate: this.fundingAmountTmp(), }, + { + id: 'actions', + header: '', + type: 'display', + cellTemplate: this.bundProjectActionsTmp(), + }, ]; } - transformEuRow(project: CordisEuProject): EuProjectRow { + transformEuRow(project: EuOrganizationProjectSummary): EuProjectRow { return { + id: project.project_id, topic: project.title || '', - funding_start: project.startDate - ? new Date(project.startDate) + funding_start: project.start_date + ? new Date(project.start_date) : new Date(0), - funding_end: project.endDate ? new Date(project.endDate) : new Date(0), - funding_amount: Number(project.totalCost) || 0, + funding_end: project.end_date ? new Date(project.end_date) : new Date(0), + funding_amount: Number(project.ec_contribution) || 0, }; } transformBundRow(project: BundProject): BundProjectRow { return { + id: project.funding_code || '', topic: project.topic || '', funding_start: project.funding_start ? new Date(project.funding_start) diff --git a/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts b/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts index 2508fa68..b6a9cfb5 100644 --- a/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts +++ b/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts @@ -1,13 +1,13 @@ import { ResolveFn } from '@angular/router'; import { - CordisEuProjectPage, + EuOrganizationProjectSummaryPage, ProjectsService, ProjectsSortBy, SortDirection, } from '../api'; import { inject } from '@angular/core'; -export const cordisEuProjectPageResolver: ResolveFn = ( +export const cordisEuProjectPageResolver: ResolveFn = ( route, state, ) => { From 9cd109fc1717aeeed968940096a727dea2ce08e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 21 Jun 2026 14:44:21 +0200 Subject: [PATCH 20/22] Moved all projects search client out of class --- .../main/inse/integrations/elasticsearch.py | 58 ++++-- service/src/main/inse/model.py | 3 + service/src/main/inse/persons/logic.py | 31 +-- service/src/main/inse/projects/model.py | 25 +++ .../inse/projects/projects_search_client.py | 182 +++++++----------- service/src/main/inse/projects/router.py | 14 +- service/src/main/inse/projects/service.py | 21 +- 7 files changed, 171 insertions(+), 163 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index bd32501a..00f9d241 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -47,7 +47,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]: raise ValueError(f"Unknown cluster: {cluster!r} (allowed: 'nes', 'inse')") -def _index_to_cluster(index: ESIndex) -> ESCluster: +def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]: """Determines the Elasticsearch cluster to use based on the specified index. Args: @@ -68,18 +68,19 @@ def _index_to_cluster(index: ESIndex) -> ESCluster: }: return ESCluster.NES elif index in { + ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, ESIndex.CORDIS_EU_PROJECTS_WILDCARD, ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + ESIndex.PROJECTS_BUND_V1, + ESIndex.PROJECTS_DFG_ALL, }: return ESCluster.INSE else: - raise ValueError(f"Unknown index: {index!r}") + return None def search( - index: ESIndex, - query_field: Optional[str] = None, - query_value: Optional[str] = None, + index: ESIndex | List[ESIndex], query: Optional[Dict] = None, source: Optional[List] = None, size: Optional[int] = None, @@ -93,8 +94,6 @@ def search( Args: index (ElasticsearchIndex): The Elasticsearch index to search. - query_field (Optional[str], optional): The field to search in. Defaults to None. - query_value (Optional[str], optional): The value to search for. Defaults to None. query (Optional[Dict], optional): The full query body. Defaults to None. source (Optional[List], optional): The fields to include in the response. Defaults to None. size (Optional[int], optional): The maximum number of results to return. Defaults to None. @@ -108,16 +107,35 @@ def search( Dict[str, Any]: The search results. """ + clusters = set() + if isinstance(index, list): + for idx in index: + cluster_for_index = _index_to_cluster(idx) + if cluster_for_index is not None: + clusters.add(cluster_for_index) + else: + cluster_for_index = _index_to_cluster(index) + if cluster_for_index is not None: + clusters.add(cluster_for_index) + + if len(clusters) > 1: + raise ValueError( + f"All indices in the search request must belong to the same cluster, but found clusters: {clusters}" + ) + elif len(clusters) == 1: + cluster = clusters.pop() + elasticsearch_url, api_key = _cluster_credentials(cluster) headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - payload: Dict[str, Any] + payload: Dict[str, Any] = {} if body is not None: payload = body - elif query is not None: - payload = {"query": query} + else: + if query is not None: + payload["query"] = query if source is not None: payload["_source"] = source if size is not None: @@ -128,19 +146,23 @@ def search( payload["sort"] = sort if track_total_hits: payload["track_total_hits"] = True - else: - payload = { - "query": { - "query_string": {"default_field": query_field, "query": query_value} - } - } + + if len(payload) == 0: + raise ValueError( + "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided" + ) with httpx.Client(timeout=httpx.Timeout(30.0)) as client: logger.debug( - f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} with payload: {payload}" + f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {payload}" ) + if isinstance(index, list): + index_str = ",".join(index) + else: + index_str = index + response = client.post( - f"{elasticsearch_url}/{index}/_search", json=payload, headers=headers + f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers ) response.raise_for_status() return response.json() diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 55d556eb..fd06db11 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -59,3 +59,6 @@ class ESIndex(StrEnum): CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects" CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications" + + PROJECTS_BUND_V1 = "projects_bund_v1" + PROJECTS_DFG_ALL = "projects_dfg_all" \ No newline at end of file diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 76db43c7..ca1e09e5 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -13,6 +13,8 @@ from elasticsearch import ApiError, NotFoundError import hashlib import httpx from fastapi import HTTPException + +from inse.model import ESIndex from .. import config from .. import util from ..integrations import llm @@ -28,6 +30,7 @@ from inse.persons.model import ( PersonSearchRequest, CareerMetrics, ) + logger = logging.getLogger(__name__) INDEX_NAME = "openalex-authors" @@ -55,20 +58,26 @@ def get_author_name_by_id(author_id: str) -> Optional[str]: def search_persons( author_id: Optional[str] = None, query: Optional[str] = None, - include: Optional[set[str]] = None, ) -> AuthorsListResponse: if author_id: - query_field = "_id" - query_value = author_id + query_ = { + "query_string": { + "default_field": "_id", + "query": author_id, + } + } + elif query: - query_field = "display_name" - query_value = query + query_ = { + "query_string": { + "default_field": "display_name", + "query": query, + } + } else: return AuthorsListResponse(results=[], meta=Meta(count=0)) - data = elasticsearch.search( - index="openalex-authors", query_field=query_field, query_value=query_value - ) + data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_) authors = [] for hit in data.get("hits", {}).get("hits", []): @@ -221,9 +230,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]: ) buckets = ( - response.get("aggregations", {}) - .get("publication_years", {}) - .get("buckets", []) + response.get("aggregations", {}).get("publication_years", {}).get("buckets", []) ) publication_years: list[int] = [] @@ -237,6 +244,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]: return publication_years + def _classify_career_stage(active_years: int) -> str: if active_years <= 0: return "unknown" @@ -399,7 +407,6 @@ def get_person_by_id( return CustomAuthorsListResponse(results=[custom_author]) - def search_persons_by_name( author_name: str, limit: Optional[int] = 10, diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index ed58fe8e..d0957d4d 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -8,6 +8,7 @@ from pydantic import BaseModel, Field, field_validator from inse.models.bund_project import BundProject from inse.models.eu_project import EuProject from inse.models.cordis_eu_project import CordisEuProject +from inse.model import ESIndex class ProjectType(StrEnum): @@ -15,6 +16,17 @@ class ProjectType(StrEnum): EU = "eu" DFG = "dfg" + def to_es_index(self) -> ESIndex: + mapping = { + self.BUND: ESIndex.PROJECTS_BUND_V1, + self.EU: ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + self.DFG: ESIndex.PROJECTS_DFG_ALL, + } + index = mapping.get(self) + if index is None: + raise ValueError(f"Unsupported project type: {self}") + return index + class ProjectsSortBy(StrEnum): TITLE = "title" @@ -31,6 +43,15 @@ class ProjectsSortBy(StrEnum): } return mapping.get(self, "title.keyword") + def to_bund_project_sort_field(self) -> str: + mapping = { + self.TITLE: "Thema.keyword", + self.FUNDING_START: "funding_start", + self.FUNDING_END: "funding_end", + self.FUNDING_AMOUNT: "Fördersumme", + } + return mapping.get(self, "Thema.keyword") + class SortDirection(StrEnum): ASC = "asc" @@ -151,6 +172,9 @@ class FundingProject(BaseModel): ) id: str = Field(description="The unique identifier of the project.") title: Optional[str] = Field(default=None, description="The title of the project.") + acronym: Optional[str] = Field( + default=None, description="The acronym of the project (if available)." + ) start_date: Optional[date] = Field( default=None, description="The funding start date of the project." ) @@ -227,6 +251,7 @@ class FundingProject(BaseModel): title=source.get("title"), start_date=source.get("funding_start"), end_date=source.get("funding_end"), + acronym=source.get("acronym"), ) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index d11dd659..ed62e84b 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -145,16 +145,6 @@ class BundProjectsSearchClient(ProjectsSearchClient): api_key=settings.elasticsearch_inse_api_key, ) - def _bund_projects_sort_by_field(self, sort_by: ProjectsSortBy) -> str: - if sort_by == ProjectsSortBy.TITLE: - return "Thema.keyword" - elif sort_by == ProjectsSortBy.FUNDING_START: - return "funding_start" - elif sort_by == ProjectsSortBy.FUNDING_END: - return "funding_end" - elif sort_by == ProjectsSortBy.FUNDING_AMOUNT: - return "Fördersumme" - def _bund_projects_query( self, page: int, @@ -210,7 +200,7 @@ class BundProjectsSearchClient(ProjectsSearchClient): query["query"] = {"match_all": {}} query["sort"] = [ - {self._bund_projects_sort_by_field(sort_by): {"order": sort_direction}} + {sort_by.to_bund_project_sort_field(): {"order": sort_direction}} ] query_str = json.dumps(query, indent=2) @@ -781,112 +771,80 @@ class DfgProjectsSearchClient(ProjectsSearchClient): return None -class CompleteProjectsSearchClient(ProjectsSearchClient): - def __init__(self): - if not settings.elasticsearch_inse_url: - raise ValueError("Elasticsearch INSE URL is missing in settings.") - if not settings.elasticsearch_inse_api_key: - raise ValueError("Elasticsearch INSE API key is missing in settings.") - super().__init__( - base_url=settings.elasticsearch_inse_url, - index="cordis_eu_*_projects,projects_bund_v1,projects_dfg_all", - api_key=settings.elasticsearch_inse_api_key, +def search_all_projects( + projects_filtering_properties: ProjectsFilteringProperties, + selected_project_types: Optional[Set[ProjectType]] = None, +): + sort_by = projects_filtering_properties.sort_by + if sort_by != ProjectsSortBy.TITLE: + raise ValueError( + "Currently only sorting by title is supported across all project types." ) - def _build_projects_search_body( - self, - page: int, - size: int, - title: Optional[str] = None, - sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, - sort_direction: SortDirection = SortDirection.ASC, - ) -> Dict[str, Any]: - if sort_by != ProjectsSortBy.TITLE: - raise ValueError("Currently only sorting by title is supported.") + sort_direction = projects_filtering_properties.sort_direction + sort = [ + { + "title.keyword": { + "order": sort_direction, + "missing": "_last", + "unmapped_type": "keyword", + } + }, + { + "Thema.keyword": { + "order": sort_direction, + "missing": "_last", + "unmapped_type": "keyword", + } + }, + ] - query: Dict[str, Any] = { - "size": size, - "from": page * size, - "sort": [ - { - "title.keyword": { - "order": sort_direction, - "missing": "_last", - "unmapped_type": "keyword", - } - }, - { - "Thema.keyword": { - "order": sort_direction, - "missing": "_last", - "unmapped_type": "keyword", - } - }, - ], + query = None + + if ( + projects_filtering_properties.query + and projects_filtering_properties.query.strip() != "" + ): + title_query = projects_filtering_properties.query.strip() + wildcard_title = f"*{title_query}*" + query = { + "bool": { + "should": [ + { + "wildcard": { + "title.keyword": { + "value": wildcard_title, + "case_insensitive": True, + } + } + }, + { + "wildcard": { + "Thema.keyword": { + "value": wildcard_title, + "case_insensitive": True, + } + } + }, + ], + "minimum_should_match": 1, + } } - if title and len(title.strip()) > 0: - title = f"*{title.strip()}*" - query["query"] = { - "bool": { - "should": [ - { - "wildcard": { - "title.keyword": { - "value": title, - "case_insensitive": True, - } - } - }, - { - "wildcard": { - "Thema.keyword": { - "value": title, - "case_insensitive": True, - } - } - }, - ], - "minimum_should_match": 1, - } - } - - return query - - def _project_type_to_index(self, project_type: ProjectType) -> str: - if project_type == ProjectType.BUND: - return "projects_bund_v1" - elif project_type == ProjectType.EU: - return "cordis_eu_*_projects" - elif project_type == ProjectType.DFG: - return "projects_dfg_all" - else: - raise ValueError(f"Unsupported project type: {project_type}") - - async def search_projects( - self, - page: int, - size: int, - selected_project_types: Optional[Set[ProjectType]] = None, - title: Optional[str] = None, - sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, - sort_direction: SortDirection = SortDirection.ASC, - ): - body = self._build_projects_search_body( - page=page, - size=size, - title=title, - sort_by=sort_by, - sort_direction=sort_direction, - ) - if not selected_project_types: - selected_project_types = {ProjectType.BUND, ProjectType.EU, ProjectType.DFG} - index = ",".join( - self._project_type_to_index(pt) for pt in selected_project_types - ) - - projects_response = await self.make_search_request(body, index=index) - return _response_to_funding_project_page(projects_response, page, size) + if not selected_project_types: + selected_project_types = {ProjectType.BUND, ProjectType.EU, ProjectType.DFG} + index = [project_type.to_es_index() for project_type in selected_project_types] + size = projects_filtering_properties.size + page = projects_filtering_properties.page + offset = page * size + response = elasticsearch.search( + index=index, + size=size, + offset=offset, + query=query, + sort=sort, + ) + return _response_to_funding_project_page(response=response, page=page, size=size) def _response_to_funding_project_page( diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 568abeae..8cc1f11e 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -22,7 +22,6 @@ from inse.tags import Tags from inse.projects import service as projects_service from inse.projects.projects_search_client import ( BundProjectsSearchClient, - CompleteProjectsSearchClient, DfgProjectsSearchClient, EuProjectsSearchClient, ) @@ -51,11 +50,6 @@ def get_dfg_search_client() -> DfgProjectsSearchClient: return DfgProjectsSearchClient() -@lru_cache -def get_complete_projects_search_client() -> CompleteProjectsSearchClient: - return CompleteProjectsSearchClient() - - @router.get( "/author/{raw_oa_author_id}/eu", summary="Get EU projects for an author.", @@ -326,10 +320,7 @@ async def get_dfg_projects( }, response_model_by_alias=False, ) -async def search_projects( - complete_projects_search_client: Annotated[ - CompleteProjectsSearchClient, Depends(get_complete_projects_search_client) - ], +def search_projects( page: Annotated[int, Query(description="The page number.", ge=0)] = 0, size: Annotated[int, Query(description="The page size.", ge=1)] = 10, selected_project_types: Annotated[ @@ -348,8 +339,7 @@ async def search_projects( SortDirection, Query(description="The sort direction (asc or desc).") ] = SortDirection.ASC, ) -> FundingProjectPage: - return await projects_service.search_projects( - projects_search_client=complete_projects_search_client, + return projects_service.search_all_projects( page=page, size=size, selected_project_types=selected_project_types, diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index a725f0fa..0e1e58e2 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -2,9 +2,9 @@ import datetime import logging from typing import Any, Dict, List, Optional, Set +from inse.projects import projects_search_client from inse.projects.projects_search_client import ( BundProjectsSearchClient, - CompleteProjectsSearchClient, DfgProjectsSearchClient, EuProjectsSearchClient, get_organization_project_contributions_foo, @@ -30,11 +30,11 @@ from inse.exceptions import NotFoundException from inse.persons.logic import get_author_name_by_id from inse.works.logic import get_publication_dois_of_author + logger = logging.getLogger(__name__) -async def search_projects( - projects_search_client: CompleteProjectsSearchClient, +def search_all_projects( page: int, size: int, sort_by: ProjectsSortBy, @@ -42,13 +42,16 @@ async def search_projects( selected_project_types: Optional[Set[ProjectType]] = None, title: Optional[str] = None, ) -> FundingProjectPage: - return await projects_search_client.search_projects( - page=page, - size=size, + return projects_search_client.search_all_projects( + projects_filtering_properties=ProjectsFilteringProperties( + project_type=ProjectType.EU, # placeholder, shall be ignored in search_all_projects + page=page, + size=size, + sort_by=sort_by, + sort_direction=sort_direction, + query=title, + ), selected_project_types=selected_project_types, - title=title, - sort_by=sort_by, - sort_direction=sort_direction, ) From f3539e4210cfce0060bc712f7368cb476d40613f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 21 Jun 2026 15:35:56 +0200 Subject: [PATCH 21/22] Moved dfg projects search client out of class --- .../main/inse/integrations/elasticsearch.py | 3 +- service/src/main/inse/persons/service.py | 2 +- .../inse/projects/projects_search_client.py | 923 ++++++------------ service/src/main/inse/projects/router.py | 62 +- service/src/main/inse/projects/service.py | 61 +- 5 files changed, 354 insertions(+), 697 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 00f9d241..da34ed82 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -1,3 +1,4 @@ +import json import logging from typing import Any, Dict, List, Optional, Tuple import httpx @@ -154,7 +155,7 @@ def search( with httpx.Client(timeout=httpx.Timeout(30.0)) as client: logger.debug( - f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {payload}" + f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}" ) if isinstance(index, list): index_str = ",".join(index) diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index c6cae176..a1e08f62 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -53,7 +53,7 @@ def search_persons( if include else None ) - return logic.search_persons(author_id, query, include_set) + return logic.search_persons(author_id, query) @router.get( diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index ed62e84b..72620407 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -133,642 +133,365 @@ class ProjectsSearchClient: return response.json() -class BundProjectsSearchClient(ProjectsSearchClient): - def __init__(self): - if not settings.elasticsearch_inse_url: - raise ValueError("Elasticsearch INSE URL is missing in settings.") - if not settings.elasticsearch_inse_api_key: - raise ValueError("Elasticsearch INSE API key is missing in settings.") - super().__init__( - base_url=settings.elasticsearch_inse_url, - index="projects_bund_v1", - api_key=settings.elasticsearch_inse_api_key, - ) +def search_bund_projects( + page: int, + size: int, + institution_names: List[str] = [], + topic: Optional[str] = None, + sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, + sort_direction: SortDirection = SortDirection.ASC, +) -> BundProjectPage: - def _bund_projects_query( - self, - page: int, - size: int, - id: Optional[str] = None, - institution_names: List[str] = [], - topic: Optional[str] = None, - sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, - sort_direction: SortDirection = SortDirection.ASC, - ) -> dict: - from_ = page * size - query: Dict[str, Any] = {"size": size, "from": from_, "query": {}} - - must_clauses: List[Dict[str, Any]] = [] - if id: - must_clauses.append({"match": {"id": id}}) - - if len(institution_names) > 0: - must_clauses.append( - { - "bool": { - "should": [ - { - "match": { - "Zuwendungsempfänger": { - "query": name, - "operator": "and", - } + must_clauses: List[Dict[str, Any]] = [] + if len(institution_names) > 0: + must_clauses.append( + { + "bool": { + "should": [ + { + "match": { + "Zuwendungsempfänger": { + "query": name, + "operator": "and", } } - for name in institution_names - ], - "minimum_should_match": 1, - } - } - ) - - if topic is not None and topic.strip() != "": - must_clauses.append( - { - "match_phrase_prefix": { - "Thema": { - "query": topic, - "max_expansions": 50, } + for name in institution_names + ], + "minimum_should_match": 1, + } + } + ) + + if topic is not None and topic.strip() != "": + must_clauses.append( + { + "match_phrase_prefix": { + "Thema": { + "query": topic, + "max_expansions": 50, } } - ) - - if must_clauses: - query["query"] = {"bool": {"must": must_clauses}} - else: - query["query"] = {"match_all": {}} - - query["sort"] = [ - {sort_by.to_bund_project_sort_field(): {"order": sort_direction}} - ] - - query_str = json.dumps(query, indent=2) - logger.debug(f"Constructed Bund project query: {query_str}") - - return query - - def response_to_bund_project_page( - self, response: dict, page: int, size: int - ) -> BundProjectPage: - hits_block = response.get("hits", {}) - total_hits = hits_block.get("total", {}).get("value", 0) - elements = [ - BundProject.model_validate(hit["_source"]) - for hit in hits_block.get("hits", []) - ] - return BundProjectPage( - elements=elements, total=total_hits, page=page, size=size + } ) - async def search_bund_projects( - self, - page: int, - size: int, - id: Optional[str] = None, - institution_names: List[str] = [], - topic: Optional[str] = None, - sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, - sort_direction: SortDirection = SortDirection.ASC, - ) -> BundProjectPage: - query = self._bund_projects_query( - page=page, - size=size, - id=id, - institution_names=institution_names, - topic=topic, - sort_by=sort_by, - sort_direction=sort_direction, - ) - response = await self.make_search_request(query) - return self.response_to_bund_project_page(response, page, size) + query: Optional[Dict[str, Any]] = None + if must_clauses: + query = {"bool": {"must": must_clauses}} - async def get_bund_projects_by_institution_name( - self, - institution_names: List[str], - page: int, - size: int, - sort_by: str = "topic", - sort_direction: str = "asc", - ) -> BundProjectPage: - query = self._bund_projects_query( - page=page, - size=size, - institution_names=institution_names, - sort_by=sort_by, - sort_direction=sort_direction, - ) - response = await self.make_search_request(query) - return self.response_to_bund_project_page(response, page, size) + sort = [{sort_by.to_bund_project_sort_field(): {"order": sort_direction.value}}] - async def get_bund_project_by_id( - self, project_id: str - ) -> Optional[BundProjectDetails]: + response = elasticsearch.search( + index=ESIndex.PROJECTS_BUND_V1, + query=query, + sort=sort, + size=size, + offset=page * size, + ) - query = { - "query": {"term": {"Förderkennzeichen.keyword": {"value": project_id}}}, - "_source": True, - } - - response = await self.make_search_request(query) - hits = response.get("hits", {}).get("hits", []) - if hits: - hit = hits[0] - print(hit) - details = BundProjectDetails.from_elastic_hit(hit=hit) - return details - return None + return _complete_response_to_bund_project_page( + response=response, page=page, size=size + ) -class EuProjectsSearchClient(ProjectsSearchClient): - def __init__(self): - if not settings.elasticsearch_inse_url: - raise ValueError("Elasticsearch INSE URL is missing in settings.") - if not settings.elasticsearch_inse_api_key: - raise ValueError("Elasticsearch INSE API key is missing in settings.") - super().__init__( - base_url=settings.elasticsearch_inse_url, - index="projects_eu_all", - api_key=settings.elasticsearch_inse_api_key, - ) +def _complete_response_to_bund_project_page( + response: Dict[str, Any], page: int, size: int +) -> BundProjectPage: + hits_block = response.get("hits", {}) + total_hits = hits_block.get("total", {}).get("value", 0) + elements = [ + BundProject.model_validate(hit["_source"]) for hit in hits_block.get("hits", []) + ] + return BundProjectPage(elements=elements, total=total_hits, page=page, size=size) - def _eu_projects_id_body(self, eu_organisation_ids: List[str]) -> Dict[str, Any]: - """Constructs the Elasticsearch query body to retrieve project IDs associated with the given list of EU organisation IDs. - Args: - eu_organisation_ids (List[str]): A list of EU organisation IDs for which to retrieve associated project IDs. +def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: + query = {"term": {"Förderkennzeichen.keyword": {"value": project_id}}} - Returns: - Dict[str, Any]: The Elasticsearch query body. - """ - body: Dict[str, Any] = { - "size": 0, - "query": { - "bool": {"filter": [{"terms": {"organisationID": eu_organisation_ids}}]} - }, - "aggs": { - "associated_project_ids": { - "terms": {"field": "projectID", "size": 10000} + response = elasticsearch.search( + index=ESIndex.PROJECTS_BUND_V1, + query=query, + size=1, + ) + + hits = response.get("hits", {}).get("hits", []) + if hits: + hit = hits[0] + details = BundProjectDetails.from_elastic_hit(hit=hit) + return details + return None + + +def _get_raw_doi(doi: str) -> str: + """Extracts the raw DOI from a given DOI string, removing any URL prefixes if present. + + Args: + doi (str): The DOI string to process. + + Returns: + str: The raw DOI string. + """ + if doi.startswith("https://doi.org/"): + return doi[len("https://doi.org/") :] + elif doi.startswith("http://dx.doi.org/"): + return doi[len("http://dx.doi.org/") :] + else: + return doi + + +def get_cordis_eu_publications_by_dois(dois: List[str]): + """Retrieves Cordis EU publications associated with the given list of DOIs. + + Args: + dois (List[str]): The list of DOIs for which to retrieve publications. + + Returns: + _type_: The retrieved publications. + """ + raw_dois = [_get_raw_doi(doi) for doi in dois] + query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} + + response = elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + cluster=ESCluster.INSE, + ) + + logger.debug(f"Received publications response: {json.dumps(response, indent=2)}") + + return response + + +def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]: + """Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs. + + Args: + dois (List[str]): The list of DOIs for which to retrieve project IDs. + + Returns: + List[str]: The list of project IDs. + """ + response = get_cordis_eu_publications_by_dois(dois=dois) + hits_block = response.get("hits", {}) + project_ids = set() + for hit in hits_block.get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if project_id: + project_ids.add(project_id) + return list(project_ids) + + +def get_cordis_eu_projects_by_project_ids( + project_ids: List[str], +) -> CordisEuProjectPage: + query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}} + + response = elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + ) + + hits_block = response.get("hits", {}) + total_hits = hits_block.get("total", {}).get("value", 0) + elements = [ + CordisEuProject.model_validate(hit["_source"]) + for hit in hits_block.get("hits", []) + ] + return CordisEuProjectPage( + elements=elements, total=total_hits, page=0, size=len(elements) + ) + + +def search_dfg_projects( + page: int, + size: int, + names: Optional[List[str]] = None, + topic: Optional[str] = None, + sort_by: str = "id", + sort_direction: str = "asc", +): + from_ = page * size + + painless_fields_string = ", ".join([f"'{f}.keyword'" for f in DFG_PERSON_FIELDS]) + + body: Dict[str, Any] = { + "size": size, + "from": from_, + "_source": [ + "id", + "link", + "title", + "funding_start", + "funding_end", + "Fachliche Zuordnung", + ], + "query": {}, + "script_fields": { + "all_found_names": { + "script": { + "lang": "painless", + "source": ( + f"def names = new HashSet(); " + f"def fields = [{painless_fields_string}]; " + f"for (field in fields) {{ " + f" if (doc.containsKey(field) && !doc[field].empty) {{ " + f" for (value in doc[field]) {{ " + f" if (value.contains(';')) {{ " + f" def splitNames = value.splitOnToken(';'); " + f" for (sn in splitNames) {{ names.add(sn.trim()); }} " + f" }} else {{ " + f" names.add(value.trim()); " + f" }} " + f" }} " + f" }} " + f"}} " + f"return new ArrayList(names);" + ), } - }, - } + } + }, + } - query_str = json.dumps(body, indent=2) - logger.debug(f"Constructed EU project ID query: {query_str}") - return body + must_clauses: List[Dict[str, Any]] = [] + filter_clauses: List[Dict[str, Any]] = [] - def _eu_projects_id_response_to_ids(self, response: Dict[str, Any]) -> List[str]: - """Converts the Elasticsearch aggregation response to a list of project IDs. - - Args: - response (Dict[str, Any]): The Elasticsearch aggregation response. - - Returns: - List[str]: A list of project IDs. - """ - buckets = ( - response.get("aggregations", {}) - .get("associated_project_ids", {}) - .get("buckets", []) - ) - ids = [bucket.get("key") for bucket in buckets if "key" in bucket] - logger.debug(f"Extracted project IDs from response: {ids}") - return ids - - def _eu_project_sort_by_field(self, sort_by: ProjectsSortBy) -> str: - """Maps the ProjectsSortBy enum to the corresponding Elasticsearch field for sorting EU projects. - - Args: - sort_by (ProjectsSortBy): The sorting criterion specified as a ProjectsSortBy enum value. - - Returns: - str: The corresponding Elasticsearch field for sorting. - """ - if sort_by == ProjectsSortBy.TITLE: - return "title.keyword" - elif sort_by == ProjectsSortBy.FUNDING_START: - return "startDate" - elif sort_by == ProjectsSortBy.FUNDING_END: - return "endDate" - elif sort_by == ProjectsSortBy.FUNDING_AMOUNT: - return "totalCost" - else: - return "id.keyword" - - def _eu_projects_body( - self, - project_ids: List[str], - projects_filtering_properties: ProjectsFilteringProperties, - ) -> Dict[str, Any]: - bool_query: Dict[str, Any] = {"filter": [{"terms": {"id": project_ids}}]} - - if ( - projects_filtering_properties.query is not None - and projects_filtering_properties.query.strip() != "" - ): - bool_query["must"] = [ - { - "match_phrase_prefix": { - "title": { - "query": projects_filtering_properties.query, - "max_expansions": 50, - } + if topic is not None and topic.strip() != "": + must_clauses.append( + { + "match_phrase_prefix": { + "title": { + "query": topic, + "max_expansions": 100, } } + } + ) + + if names: + name_should_clauses = [] + script_conditions = [] + + for full_name in names: + name_parts = full_name.strip().split() + if not name_parts: + continue + + match_musts = [] + for part in name_parts: + match_musts.append( + {"multi_match": {"query": part, "fields": DFG_PERSON_FIELDS}} + ) + + name_should_clauses.append({"bool": {"must": match_musts}}) + + script_parts = [ + f"singlePerson.contains('{part.lower()}')" for part in name_parts ] + script_conditions.append(f"({' && '.join(script_parts)})") - body: Dict[str, Any] = { - "from": projects_filtering_properties.page - * projects_filtering_properties.size, - "size": projects_filtering_properties.size, - "query": {"bool": bool_query}, - "sort": [ - { - self._eu_project_sort_by_field( - projects_filtering_properties.sort_by - ): { - "order": projects_filtering_properties.sort_direction, - } - } - ], - } - - query_str = json.dumps(body, indent=2) - logger.debug(f"Constructed EU project details query: {query_str}") - return body - - async def search_eu_projects( - self, - eu_organisation_ids: List[str], - projects_filtering_properties: ProjectsFilteringProperties, - ) -> CordisEuProjectPage: - projects_id_body = self._eu_projects_id_body(eu_organisation_ids) - id_response = await self.make_search_request( - projects_id_body, index="cordis_eu_*_organizations" - ) - project_ids = self._eu_projects_id_response_to_ids(id_response) - logger.debug( - f"Found project IDs for organization IDs {eu_organisation_ids}: {project_ids}" - ) - if not project_ids: - logger.debug( - f"No project IDs found for organization IDs {eu_organisation_ids}" - ) - return CordisEuProjectPage( - elements=[], - total=0, - page=projects_filtering_properties.page, - size=projects_filtering_properties.size, - ) - projects_body = self._eu_projects_body( - project_ids=project_ids, - projects_filtering_properties=projects_filtering_properties, - ) - projects_response = await self.make_search_request( - projects_body, index="cordis_eu_*_projects" - ) - logger.debug( - f"Received projects response: {json.dumps(projects_response, indent=2)}" - ) - return self._response_to_cordis_eu_project_page( - projects_response, - projects_filtering_properties.page, - projects_filtering_properties.size, - ) - - def _response_to_cordis_eu_project_page( - self, response: Dict[str, Any], page: int, size: int - ) -> CordisEuProjectPage: - """Converts the Elasticsearch response to a CordisEuProjectPage containing CordisEuProject elements. - - Args: - response (Dict[str, Any]): The Elasticsearch response. - page (int): The page number. - size (int): The number of items per page. - - Returns: - CordisEuProjectPage: The converted project page. - """ - hits_block = response.get("hits", {}) - total_hits = hits_block.get("total", {}).get("value", 0) - elements = [ - CordisEuProject.model_validate(hit["_source"]) - for hit in hits_block.get("hits", []) - ] - return CordisEuProjectPage( - elements=elements, total=total_hits, page=page, size=size - ) - - def _get_raw_doi(self, doi: str) -> str: - """Extracts the raw DOI from a given DOI string, removing any URL prefixes if present. - - Args: - doi (str): The DOI string to process. - - Returns: - str: The raw DOI string. - """ - if doi.startswith("https://doi.org/"): - return doi[len("https://doi.org/") :] - elif doi.startswith("http://dx.doi.org/"): - return doi[len("http://dx.doi.org/") :] - else: - return doi - - def get_cordis_eu_publications_by_dois(self, dois: List[str]): - """Retrieves Cordis EU publications associated with the given list of DOIs. - - Args: - dois (List[str]): The list of DOIs for which to retrieve publications. - - Returns: - _type_: The retrieved publications. - """ - raw_dois = [self._get_raw_doi(doi) for doi in dois] - query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} - - response = elasticsearch.search( - query=query, - index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, - cluster=ESCluster.INSE, - ) - - logger.debug( - f"Received publications response: {json.dumps(response, indent=2)}" - ) - - return response - - def get_cordis_eu_project_ids_by_dois(self, dois: List[str]) -> List[str]: - """Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs. - - Args: - dois (List[str]): The list of DOIs for which to retrieve project IDs. - - Returns: - List[str]: The list of project IDs. - """ - response = self.get_cordis_eu_publications_by_dois(dois=dois) - hits_block = response.get("hits", {}) - project_ids = set() - for hit in hits_block.get("hits", []): - source = hit.get("_source", {}) - project_id = source.get("projectID") - if project_id: - project_ids.add(project_id) - return list(project_ids) - - def get_cordis_eu_projects_by_project_ids( - self, project_ids: List[str] - ) -> CordisEuProjectPage: - query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}} - - response = elasticsearch.search( - query=query, - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - cluster=ESCluster.INSE, - ) - - hits_block = response.get("hits", {}) - total_hits = hits_block.get("total", {}).get("value", 0) - elements = [ - CordisEuProject.model_validate(hit["_source"]) - for hit in hits_block.get("hits", []) - ] - return CordisEuProjectPage( - elements=elements, total=total_hits, page=0, size=len(elements) - ) - - -class DfgProjectsSearchClient(ProjectsSearchClient): - def __init__(self): - if not settings.elasticsearch_inse_url: - raise ValueError("Elasticsearch INSE URL is missing in settings.") - if not settings.elasticsearch_inse_api_key: - raise ValueError("Elasticsearch INSE API key is missing in settings.") - super().__init__( - base_url=settings.elasticsearch_inse_url, - index="projects_dfg_all", - api_key=settings.elasticsearch_inse_api_key, - ) - - def dfg_projects_query( - self, - page: int, - size: int, - names: Optional[List[str]] = None, - topic: Optional[str] = None, - sort_by: str = "id", - sort_direction: str = "asc", - ) -> dict: - - from_ = page * size - - painless_fields_string = ", ".join( - [f"'{f}.keyword'" for f in DFG_PERSON_FIELDS] - ) - - query: Dict[str, Any] = { - "size": size, - "from": from_, - "_source": [ - "id", - "link", - "title", - "funding_start", - "funding_end", - "Fachliche Zuordnung", - ], - "query": {}, - "script_fields": { - "all_found_names": { - "script": { - "lang": "painless", - "source": ( - f"def names = new HashSet(); " - f"def fields = [{painless_fields_string}]; " - f"for (field in fields) {{ " - f" if (doc.containsKey(field) && !doc[field].empty) {{ " - f" for (value in doc[field]) {{ " - f" if (value.contains(';')) {{ " - f" def splitNames = value.splitOnToken(';'); " - f" for (sn in splitNames) {{ names.add(sn.trim()); }} " - f" }} else {{ " - f" names.add(value.trim()); " - f" }} " - f" }} " - f" }} " - f"}} " - f"return new ArrayList(names);" - ), - } - } - }, - } - - must_clauses: List[Dict[str, Any]] = [] - filter_clauses: List[Dict[str, Any]] = [] - - if topic is not None and topic.strip() != "": + if name_should_clauses: must_clauses.append( - { - "match_phrase_prefix": { - "title": { - "query": topic, - "max_expansions": 100, - } - } - } + {"bool": {"should": name_should_clauses, "minimum_should_match": 1}} ) - if names: - name_should_clauses = [] - script_conditions = [] + combined_script_condition = " || ".join(script_conditions) + painless_source = ( + f"def fields = [{painless_fields_string}]; " + f"for (field in fields) {{ " + f" if (doc.containsKey(field) && !doc[field].empty) {{ " + f" for (value in doc[field]) {{ " + f" if (value.contains(';')) {{ " + f" def splitValues = value.splitOnToken(';'); " + f" for (singlePersonRaw in splitValues) {{ " + f" def singlePerson = singlePersonRaw.toLowerCase(); " + f" if ({combined_script_condition}) {{ return true; }} " + f" }} " + f" }} else {{ " + f" def singlePerson = value.toLowerCase(); " + f" if ({combined_script_condition}) {{ return true; }} " + f" }} " + f" }} " + f" }} " + f"}} " + f"return false;" + ) - for full_name in names: - name_parts = full_name.strip().split() - if not name_parts: - continue + filter_clauses.append( + {"script": {"script": {"lang": "painless", "source": painless_source}}} + ) - match_musts = [] - for part in name_parts: - match_musts.append( - {"multi_match": {"query": part, "fields": DFG_PERSON_FIELDS}} - ) + if must_clauses or filter_clauses: + body["query"] = {"bool": {}} + if must_clauses: + body["query"]["bool"]["must"] = must_clauses + if filter_clauses: + body["query"]["bool"]["filter"] = filter_clauses + else: + body["query"] = {"match_all": {}} - name_should_clauses.append({"bool": {"must": match_musts}}) + sort_by = sort_by.strip().lower() + sort_direction = sort_direction.strip().lower() + if sort_direction not in ["asc", "desc"]: + sort_direction = "asc" + logger.debug(f"Sorting DFG projects by {sort_by} with direction {sort_direction}") - script_parts = [ - f"singlePerson.contains('{part.lower()}')" for part in name_parts - ] - script_conditions.append(f"({' && '.join(script_parts)})") - - if name_should_clauses: - must_clauses.append( - {"bool": {"should": name_should_clauses, "minimum_should_match": 1}} - ) - - combined_script_condition = " || ".join(script_conditions) - painless_source = ( - f"def fields = [{painless_fields_string}]; " - f"for (field in fields) {{ " - f" if (doc.containsKey(field) && !doc[field].empty) {{ " - f" for (value in doc[field]) {{ " - f" if (value.contains(';')) {{ " - f" def splitValues = value.splitOnToken(';'); " - f" for (singlePersonRaw in splitValues) {{ " - f" def singlePerson = singlePersonRaw.toLowerCase(); " - f" if ({combined_script_condition}) {{ return true; }} " - f" }} " - f" }} else {{ " - f" def singlePerson = value.toLowerCase(); " - f" if ({combined_script_condition}) {{ return true; }} " - f" }} " - f" }} " - f" }} " - f"}} " - f"return false;" - ) - - filter_clauses.append( - { - "script": { - "script": {"lang": "painless", "source": painless_source} - } - } - ) - - if must_clauses or filter_clauses: - query["query"] = {"bool": {}} - if must_clauses: - query["query"]["bool"]["must"] = must_clauses - if filter_clauses: - query["query"]["bool"]["filter"] = filter_clauses - else: - query["query"] = {"match_all": {}} - - sort_by = sort_by.strip().lower() - sort_direction = sort_direction.strip().lower() - if sort_direction not in ["asc", "desc"]: - sort_direction = "asc" + if sort_by in ["topic", "title"]: + logger.debug(f"Sorting DFG projects by title with direction {sort_direction}") + sort_config = {"title.keyword": {"order": sort_direction}} + elif sort_by == "funding_start": logger.debug( - f"Sorting DFG projects by {sort_by} with direction {sort_direction}" + f"Sorting DFG projects by funding_start with direction {sort_direction}" ) - - if sort_by in ["topic", "title"]: - logger.debug( - f"Sorting DFG projects by title with direction {sort_direction}" - ) - sort_config = {"title.keyword": {"order": sort_direction}} - elif sort_by == "funding_start": - logger.debug( - f"Sorting DFG projects by funding_start with direction {sort_direction}" - ) - sort_config = {"funding_start.keyword": {"order": sort_direction}} - elif sort_by == "funding_end": - logger.debug( - f"Sorting DFG projects by funding_end with direction {sort_direction}" - ) - sort_config = {"funding_end.keyword": {"order": sort_direction}} - elif sort_by == "professional_classification": - logger.debug( - f"Sorting DFG projects by Fachliche Zuordnung with direction {sort_direction}" - ) - sort_config = {"Fachliche Zuordnung.keyword": {"order": sort_direction}} - else: - logger.debug(f"Sorting DFG projects by id with direction {sort_direction}") - sort_config = {"id.keyword": {"order": sort_direction}} - - query["sort"] = [sort_config] - - query_str = json.dumps(query, indent=2) - logger.debug(f"Constructed DFG project query: {query_str}") - - return query - - def response_to_dfg_project_page( - self, response: dict, page: int, size: int - ) -> DfgProjectPage: - hits_block = response.get("hits", {}) - total_hits = hits_block.get("total", {}).get("value", 0) - elements = [ - DfgProjectSummary.from_hit(hit) for hit in hits_block.get("hits", []) - ] - return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size) - - async def search_dfg_projects( - self, - page: int, - size: int, - names: Optional[List[str]] = None, - topic: Optional[str] = None, - sort_by: str = "id", - sort_direction: str = "asc", - ) -> DfgProjectPage: - query = self.dfg_projects_query( - page=page, - size=size, - names=names, - topic=topic, - sort_by=sort_by, - sort_direction=sort_direction, + sort_config = {"funding_start.keyword": {"order": sort_direction}} + elif sort_by == "funding_end": + logger.debug( + f"Sorting DFG projects by funding_end with direction {sort_direction}" ) - response = await self.make_search_request(query) - return self.response_to_dfg_project_page(response, page, size) + sort_config = {"funding_end.keyword": {"order": sort_direction}} + elif sort_by == "professional_classification": + logger.debug( + f"Sorting DFG projects by Fachliche Zuordnung with direction {sort_direction}" + ) + sort_config = {"Fachliche Zuordnung.keyword": {"order": sort_direction}} + else: + logger.debug(f"Sorting DFG projects by id with direction {sort_direction}") + sort_config = {"id.keyword": {"order": sort_direction}} - async def get_dfg_project_by_id( - self, project_id: str - ) -> Optional[DfgProjectDetails]: - query = {"query": {"ids": {"values": [project_id]}}, "_source": True} + body["sort"] = [sort_config] - response = await self.make_search_request(query) - hits = response.get("hits", {}).get("hits", []) + response = elasticsearch.search( + index=ESIndex.PROJECTS_DFG_ALL, + body=body, + ) + return _complete_response_to_dfg_project_page(response, page, size) - if hits: - hit = hits[0] - details = DfgProjectDetails.from_elastic_hit(hit=hit) - return details - return None + +def _complete_response_to_dfg_project_page( + response: dict, page: int, size: int +) -> DfgProjectPage: + hits_block = response.get("hits", {}) + total_hits = hits_block.get("total", {}).get("value", 0) + elements = [DfgProjectSummary.from_hit(hit) for hit in hits_block.get("hits", [])] + return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size) + + +def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: + query = {"ids": {"values": [project_id]}} + + response = elasticsearch.search( + index=ESIndex.PROJECTS_DFG_ALL, + query=query, + size=1, + ) + hits = response.get("hits", {}).get("hits", []) + + if hits: + hit = hits[0] + details = DfgProjectDetails.from_elastic_hit(hit=hit) + return details + return None def search_all_projects( diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 8cc1f11e..509f5d8b 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -20,11 +20,7 @@ from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails from inse.tags import Tags from inse.projects import service as projects_service -from inse.projects.projects_search_client import ( - BundProjectsSearchClient, - DfgProjectsSearchClient, - EuProjectsSearchClient, -) + from inse.institutions.institutions_search_client import ( InstitutionsSearchClient, ) @@ -35,21 +31,6 @@ logger = logging.getLogger(__name__) router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS]) -@lru_cache -def get_bund_search_client() -> BundProjectsSearchClient: - return BundProjectsSearchClient() - - -@lru_cache -def get_eu_search_client() -> EuProjectsSearchClient: - return EuProjectsSearchClient() - - -@lru_cache -def get_dfg_search_client() -> DfgProjectsSearchClient: - return DfgProjectsSearchClient() - - @router.get( "/author/{raw_oa_author_id}/eu", summary="Get EU projects for an author.", @@ -65,16 +46,12 @@ def get_dfg_search_client() -> DfgProjectsSearchClient: response_model_by_alias=False, ) def get_eu_projects_for_author( - eu_projects_search_client: Annotated[ - EuProjectsSearchClient, Depends(get_eu_search_client) - ], raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")], ) -> CordisEuProjectPage: logger.debug( f"Received request to get EU projects for author_id={raw_oa_author_id}" ) return projects_service.search_cordis_eu_projects_for_author_id( - eu_projects_search_client=eu_projects_search_client, raw_oa_author_id=raw_oa_author_id, ) @@ -94,9 +71,6 @@ def get_eu_projects_for_author( response_model_by_alias=False, ) async def search_bund_projects( - bund_search_client: Annotated[ - BundProjectsSearchClient, Depends(get_bund_search_client) - ], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -105,8 +79,7 @@ async def search_bund_projects( Body(description="The filtering properties for the projects search."), ], ) -> BundProjectPage: - return await projects_service.search_bund_projects( - bund_search_client=bund_search_client, + return projects_service.search_bund_projects( institutions_search_client=institutions_search_client, filtering_properties=filtering_properties, ) @@ -126,15 +99,11 @@ async def search_bund_projects( }, response_model_by_alias=False, ) -async def get_single_dfg_project( - dfg_search_client: Annotated[ - DfgProjectsSearchClient, Depends(get_dfg_search_client) - ], +def get_single_dfg_project( id: Annotated[str, Path(description="The ID of the DFG project to retrieve.")], ) -> DfgProjectDetails: logger.debug(f"Received request to get single DFG project for id={id}") - return await projects_service.get_single_dfg_project( - dfg_search_client=dfg_search_client, + return projects_service.get_single_dfg_project( project_id=id, ) @@ -153,15 +122,11 @@ async def get_single_dfg_project( }, response_model_by_alias=False, ) -async def get_single_bund_project( - bund_search_client: Annotated[ - BundProjectsSearchClient, Depends(get_bund_search_client) - ], +def get_single_bund_project( id: Annotated[str, Path(description="The ID of the BUND project to retrieve.")], ) -> BundProjectDetails: logger.debug(f"Received request to get single BUND project for id={id}") - return await projects_service.get_single_bund_project( - bund_search_client=bund_search_client, + return projects_service.get_single_bund_project( project_id=id, ) @@ -180,10 +145,7 @@ async def get_single_bund_project( }, response_model_by_alias=False, ) -async def get_institution_bund_projects_funding_over_time( - bund_search_client: Annotated[ - BundProjectsSearchClient, Depends(get_bund_search_client) - ], +def get_institution_bund_projects_funding_over_time( institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -191,8 +153,7 @@ async def get_institution_bund_projects_funding_over_time( str, Query(description="The institution ID to filter by.") ], ) -> InstitutionFunderSummary: - return await projects_service.get_institution_bund_projects_funding_over_time( - bund_search_client=bund_search_client, + return projects_service.get_institution_bund_projects_funding_over_time( institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, ) @@ -213,7 +174,6 @@ async def get_institution_bund_projects_funding_over_time( response_model_by_alias=False, ) async def search_cordis_eu_projects( - eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -243,7 +203,6 @@ async def search_cordis_eu_projects( response_model_by_alias=False, ) async def get_institution_cordis_eu_projects_funding_over_time( - eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -252,7 +211,6 @@ async def get_institution_cordis_eu_projects_funding_over_time( ], ) -> InstitutionFunderSummary: return await projects_service.get_institution_cordis_eu_projects_funding_over_time( - eu_search_client=eu_search_client, institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, ) @@ -273,9 +231,6 @@ async def get_institution_cordis_eu_projects_funding_over_time( response_model_by_alias=False, ) async def get_dfg_projects( - dfg_search_client: Annotated[ - DfgProjectsSearchClient, Depends(get_dfg_search_client) - ], author_id: Annotated[str, Query(description="The author ID to filter by.")], topic: Annotated[ Optional[str], Query(description="The topic to filter by.") @@ -297,7 +252,6 @@ async def get_dfg_projects( sort_direction, ) return await projects_service.get_dfg_projects_by_author_id( - dfg_search_client=dfg_search_client, author_id=author_id, topic=topic, page=page, diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 0e1e58e2..4f35c69b 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -4,9 +4,6 @@ from typing import Any, Dict, List, Optional, Set from inse.projects import projects_search_client from inse.projects.projects_search_client import ( - BundProjectsSearchClient, - DfgProjectsSearchClient, - EuProjectsSearchClient, get_organization_project_contributions_foo, ) from inse.projects.model import ( @@ -55,8 +52,7 @@ def search_all_projects( ) -async def search_bund_projects( - bund_search_client: BundProjectsSearchClient, +def search_bund_projects( institutions_search_client: InstitutionsSearchClient, filtering_properties: ProjectsFilteringProperties, ) -> BundProjectPage: @@ -65,15 +61,17 @@ async def search_bund_projects( f"Invalid project type: {filtering_properties.project_type}. Expected 'bund'." ) - return await get_bund_projects_by_institution_id( - bund_search_client=bund_search_client, + logger.debug( + f"search_bund_projects called with filtering_properties: {filtering_properties}" + ) + + return get_bund_projects_by_institution_id( institutions_search_client=institutions_search_client, filtering_properties=filtering_properties, ) -async def get_bund_projects_by_institution_id( - bund_search_client: BundProjectsSearchClient, +def get_bund_projects_by_institution_id( institutions_search_client: InstitutionsSearchClient, filtering_properties: ProjectsFilteringProperties, ) -> BundProjectPage: @@ -89,9 +87,9 @@ async def get_bund_projects_by_institution_id( ) ) logger.debug( - f"Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}" + f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) - response = await bund_search_client.search_bund_projects( + response = projects_search_client.search_bund_projects( page=filtering_properties.page, size=filtering_properties.size, institution_names=institution_aliases, @@ -150,7 +148,6 @@ def get_cordis_eu_projects_by_institution_id( async def get_dfg_projects_by_author_id( - dfg_search_client: DfgProjectsSearchClient, author_id: str, topic: Optional[str], page: int, @@ -169,7 +166,7 @@ async def get_dfg_projects_by_author_id( ) logger.debug(f"Found author name for author_id={author_id}: {name}") - response = await dfg_search_client.search_dfg_projects( + response = projects_search_client.search_dfg_projects( page=page, size=size, names=[name], @@ -181,22 +178,9 @@ async def get_dfg_projects_by_author_id( async def get_institution_cordis_eu_projects_funding_over_time( - eu_search_client: EuProjectsSearchClient, institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str, ) -> InstitutionFunderSummary: - - # cordis_eu_project_page = await search_cordis_eu_projects( - # eu_search_client, - # institutions_search_client, - # ProjectsFilteringProperties( - # project_type=ProjectType.EU, - # raw_oa_institution_id=raw_oa_institution_id, - # page=0, - # size=10000, - # ), - # ) - institution_aliases = ( institutions_search_client.get_institution_aliases_by_oa_institution_id( raw_oa_institution_id @@ -220,8 +204,7 @@ async def get_institution_cordis_eu_projects_funding_over_time( ) -async def get_institution_bund_projects_funding_over_time( - bund_search_client: BundProjectsSearchClient, +def get_institution_bund_projects_funding_over_time( institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str, ) -> InstitutionFunderSummary: @@ -236,7 +219,7 @@ async def get_institution_bund_projects_funding_over_time( logger.debug( f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" ) - response = await bund_search_client.search_bund_projects( + response = projects_search_client.search_bund_projects( page=0, size=10000, institution_names=institution_aliases, @@ -319,32 +302,30 @@ def _calculate_funding_over_time( ) -async def get_single_dfg_project( - dfg_search_client: DfgProjectsSearchClient, +def get_single_dfg_project( project_id: str, ) -> DfgProjectDetails: logger.debug(f"Fetching single DFG project for id={project_id}") - project = await dfg_search_client.get_dfg_project_by_id(project_id) + project = projects_search_client.get_dfg_project_by_id(project_id) if not project: raise NotFoundException(f"DFG project with id {project_id} not found") return project -async def get_single_bund_project( - bund_search_client: BundProjectsSearchClient, +def get_single_bund_project( project_id: str, ) -> BundProjectDetails: logger.debug(f"Fetching single BUND project for id={project_id}") - project = await bund_search_client.get_bund_project_by_id(project_id) + project = projects_search_client.get_bund_project_by_id(project_id) if not project: raise NotFoundException(f"BUND project with id {project_id} not found") return project def search_cordis_eu_projects_for_author_id( - eu_projects_search_client: EuProjectsSearchClient, raw_oa_author_id: str + raw_oa_author_id: str, ) -> CordisEuProjectPage: # Direct search not possible -> multi stage search @@ -356,16 +337,14 @@ def search_cordis_eu_projects_for_author_id( logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}") - project_ids = eu_projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois) + project_ids = projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois) logger.debug( f"Found project IDs {project_ids} for author_id={raw_oa_author_id} and dois={dois}" ) - funding_project_page = ( - eu_projects_search_client.get_cordis_eu_projects_by_project_ids( - project_ids=project_ids - ) + funding_project_page = projects_search_client.get_cordis_eu_projects_by_project_ids( + project_ids=project_ids ) return funding_project_page From a0477fcdb153f86c7eddc8b4f59e477fab1d0cfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 21 Jun 2026 15:50:54 +0200 Subject: [PATCH 22/22] Added documentation for projects search client --- .../inse/projects/projects_search_client.py | 627 +++++++++++------- service/src/main/inse/projects/service.py | 19 +- 2 files changed, 382 insertions(+), 264 deletions(-) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 72620407..a53c2f1f 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -96,51 +96,22 @@ DFG_PERSON_FIELDS: List[str] = [ "stellvertr. Sprecherinnen / stellvertr. Sprecher", ] - -class ProjectsSearchClient: - def __init__( - self, - base_url: str, - index: str, - api_key: str, - ): - self.base_url = base_url - self.index = index - self.api_key = api_key - self.headers = { - "Content-Type": "application/json", - "Authorization": f"ApiKey {self.api_key}", - } - - async def make_search_request( - self, query: dict, index: Optional[str] = None - ) -> dict: - async with httpx.AsyncClient() as client: - response = await client.post( - f"{self.base_url}/{index or self.index}/_search", - json=query, - headers=self.headers, - ) - - try: - response.raise_for_status() - except httpx.HTTPStatusError as e: - logger.exception( - f"HTTP error occurred: {e.response.status_code} - {e.response.text}" - ) - raise - - return response.json() +# BUND def search_bund_projects( - page: int, - size: int, + filter_properties: ProjectsFilteringProperties, institution_names: List[str] = [], - topic: Optional[str] = None, - sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, - sort_direction: SortDirection = SortDirection.ASC, ) -> BundProjectPage: + """Searches for Bund projects based on the provided filtering properties and institution names. + + Args: + filter_properties (ProjectsFilteringProperties): The properties to filter the projects by. + institution_names (List[str], optional): The names of the institutions to filter by. Defaults to []. + + Returns: + BundProjectPage: The page of Bund projects that match the filtering criteria. + """ must_clauses: List[Dict[str, Any]] = [] if len(institution_names) > 0: @@ -163,12 +134,12 @@ def search_bund_projects( } ) - if topic is not None and topic.strip() != "": + if filter_properties.query is not None and filter_properties.query.strip() != "": must_clauses.append( { "match_phrase_prefix": { "Thema": { - "query": topic, + "query": filter_properties.query, "max_expansions": 50, } } @@ -179,24 +150,40 @@ def search_bund_projects( if must_clauses: query = {"bool": {"must": must_clauses}} - sort = [{sort_by.to_bund_project_sort_field(): {"order": sort_direction.value}}] + sort = [ + { + filter_properties.sort_by.to_bund_project_sort_field(): { + "order": filter_properties.sort_direction.value + } + } + ] response = elasticsearch.search( index=ESIndex.PROJECTS_BUND_V1, query=query, sort=sort, - size=size, - offset=page * size, + size=filter_properties.size, + offset=filter_properties.page * filter_properties.size, ) return _complete_response_to_bund_project_page( - response=response, page=page, size=size + response=response, page=filter_properties.page, size=filter_properties.size ) def _complete_response_to_bund_project_page( response: Dict[str, Any], page: int, size: int ) -> BundProjectPage: + """Converts the raw Elasticsearch response into a BundProjectPage object. + + Args: + response (Dict[str, Any]): The raw Elasticsearch response. + page (int): The page number. + size (int): The number of items per page. + + Returns: + BundProjectPage: The converted BundProjectPage object. + """ hits_block = response.get("hits", {}) total_hits = hits_block.get("total", {}).get("value", 0) elements = [ @@ -206,6 +193,14 @@ def _complete_response_to_bund_project_page( def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: + """Fetches the details of a single Bund project based on its project ID. + + Args: + project_id (str): The ID of the project to fetch. + + Returns: + Optional[BundProjectDetails]: The details of the project if found, otherwise None. + """ query = {"term": {"Förderkennzeichen.keyword": {"value": project_id}}} response = elasticsearch.search( @@ -222,6 +217,264 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: return None +# EU + + +def get_eu_organization_project_contributions( + organization_names: List[str], + projects_filtering_properties: ProjectsFilteringProperties, +) -> EuOrganizationProjectSummaryPage: + """Fetches the contributions of EU organizations to projects based on the provided organization names and filtering properties, and returns a paginated summary of the projects. + + Args: + organization_names (List[str]): The list of organization names to fetch contributions for. + projects_filtering_properties (ProjectsFilteringProperties): The filtering properties for the projects. + + Returns: + EuOrganizationProjectSummaryPage: The paginated summary of the projects. + """ + # Pagination depending on sorting criteria + # For FUNDING_AMOUNT before on the organization project contributions + # For the rest after the contributions are known on the real projects + + organization_project_contributions = get_eu_organization_contributions( + organization_names=organization_names, + ) + + total_projects, projects = get_eu_organization_projects( + project_contributions=list(organization_project_contributions.values()), + projects_filtering_properties=projects_filtering_properties, + ) + + elements: List[EuOrganizationProjectSummary] = _merge_project_data( + projects=projects, contributions=organization_project_contributions + ) + + if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: + elements.sort( + key=lambda x: x.ec_contribution or 0, + reverse=projects_filtering_properties.sort_direction == SortDirection.DESC, + ) + start = projects_filtering_properties.page * projects_filtering_properties.size + end = start + projects_filtering_properties.size + elements = elements[start:end] + + return EuOrganizationProjectSummaryPage( + elements=elements, + total=total_projects, + page=projects_filtering_properties.page, + size=projects_filtering_properties.size, + ) + + +def get_eu_organization_contributions( + organization_names: List[str], +) -> Dict[str, EuOrganizationShort]: + """Fetches the contributions of EU organizations to projects based on the provided organization names. + + Args: + organization_names (List[str]): The list of organization names to fetch contributions for. + + Returns: + Dict[str, EuOrganizationShort]: A dictionary mapping project IDs to their corresponding organization contributions. + """ + + source = ["projectID", "organisationID", "ecContribution"] + + query = { + "terms": { + "name.keyword": [ + name.upper() for name in organization_names if name.strip() + ], + } + } + + response = elasticsearch.search( + index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, + cluster=ESCluster.INSE, + source=source, + size=10000, + query=query, + ) + + logger.debug( + f"Received organization project contributions response: {json.dumps(response, indent=2)}" + ) + + organization_project_contributions = _process_organization_project_contributions( + response + ) + + logger.debug( + f"Found organization project contributions for organization names {organization_names}: {organization_project_contributions}" + ) + + return organization_project_contributions + + +def _process_organization_project_contributions( + response: Dict[str, Any], +) -> Dict[str, EuOrganizationShort]: + """Processes the raw Elasticsearch response to extract the contributions of EU organizations to projects. + + Args: + response (Dict[str, Any]): The raw Elasticsearch response. + + Returns: + Dict[str, EuOrganizationShort]: A dictionary mapping project IDs to their corresponding organization contributions. + """ + hits_block = response.get("hits", {}) + project_contributions: Dict[str, EuOrganizationShort] = {} + for hit in hits_block.get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + organization_id = source.get("organisationID") + ec_contribution = source.get("ecContribution") + if project_id and organization_id: + project_contributions[project_id] = EuOrganizationShort( + project_id=project_id, + organization_id=organization_id, + ec_contribution=ec_contribution, + ) + return project_contributions + + +def get_eu_organization_projects( + project_contributions: List[EuOrganizationShort], + projects_filtering_properties: ProjectsFilteringProperties, +) -> Tuple[int, Dict[str, EuProjectShort]]: + """Fetches the projects associated with the given list of organization contributions, applying the specified filtering properties. + + Args: + project_contributions (List[EuOrganizationShort]): The list of organization contributions to fetch projects for. + projects_filtering_properties (ProjectsFilteringProperties): The filtering properties to apply to the project search. + + Returns: + Tuple[int, Dict[str, EuProjectShort]]: A tuple containing the total number of projects and a dictionary mapping project IDs to their corresponding project details. + """ + project_ids = [contribution.project_id for contribution in project_contributions] + + source = ["id", "title", "startDate", "endDate", "acronym"] + + query = { + "terms": { + "id": project_ids, + } + } + + if ( + projects_filtering_properties.query + and projects_filtering_properties.query.strip() + ): + query = { + "bool": { + "must": [ + { + "match_phrase_prefix": { + "title": { + "query": projects_filtering_properties.query, + "max_expansions": 50, + } + } + } + ], + "filter": query, + } + } + + # Project contributions have been filtered before based on ecContribution + if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: + response = elasticsearch.search( + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + source=source, + query=query, + size=10000, + ) + else: + response = elasticsearch.search( + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + source=source, + query=query, + size=projects_filtering_properties.size, + offset=projects_filtering_properties.page + * projects_filtering_properties.size, + sort=[ + { + projects_filtering_properties.sort_by.to_cordis_eu_project_sort_field(): { + "order": projects_filtering_properties.sort_direction + } + } + ], + ) + + return _process_projects_response(response) + + +def _process_projects_response( + response: Dict[str, Any], +) -> Tuple[int, Dict[str, EuProjectShort]]: + """Processes the raw Elasticsearch response to extract the project details and total count. + + Args: + response (Dict[str, Any]): The raw Elasticsearch response. + + Returns: + Tuple[int, Dict[str, EuProjectShort]]: A tuple containing the total number of projects and a dictionary mapping project IDs to their corresponding project details. + """ + hits_block = response.get("hits", {}) + total = hits_block.get("total", {}).get("value", 0) + projects: Dict[str, EuProjectShort] = {} + for hit in hits_block.get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("id") + title = source.get("title") + start_date = source.get("startDate") + end_date = source.get("endDate") + acronym = source.get("acronym") + if not project_id: + continue + projects[project_id] = EuProjectShort( + id=project_id, + title=title, + start_date=start_date, + end_date=end_date, + acronym=acronym, + ) + + return total, projects + + +def _merge_project_data( + projects: Dict[str, EuProjectShort], contributions: Dict[str, EuOrganizationShort] +) -> List[EuOrganizationProjectSummary]: + """Merges the project details with the organization contributions to create a list of EuOrganizationProjectSummary objects. + + Args: + projects (Dict[str, EuProjectShort]): The dictionary of project details. + contributions (Dict[str, EuOrganizationShort]): The dictionary of organization contributions. + + Returns: + List[EuOrganizationProjectSummary]: The list of merged project-summary objects. + """ + merged_data = [] + for project_id, project_info in projects.items(): + contribution_info = contributions.get(project_id) + if contribution_info: + merged_entry = EuOrganizationProjectSummary( + project_id=project_id, + title=project_info.title, + start_date=project_info.start_date, + end_date=project_info.end_date, + acronym=project_info.acronym, + organization_id=contribution_info.organization_id, + ec_contribution=contribution_info.ec_contribution, + ) + merged_data.append(merged_entry) + return merged_data + + def _get_raw_doi(doi: str) -> str: """Extracts the raw DOI from a given DOI string, removing any URL prefixes if present. @@ -304,6 +557,9 @@ def get_cordis_eu_projects_by_project_ids( ) +# DFG + + def search_dfg_projects( page: int, size: int, @@ -311,7 +567,20 @@ def search_dfg_projects( topic: Optional[str] = None, sort_by: str = "id", sort_direction: str = "asc", -): +) -> DfgProjectPage: + """Searches for DFG projects based on the provided filtering and sorting criteria. + + Args: + page (int): The page number. + size (int): The number of items per page. + names (Optional[List[str]], optional): The list of names to search for. Defaults to None. + topic (Optional[str], optional): The topic to search for. Defaults to None. + sort_by (str, optional): The field to sort by. Defaults to "id". + sort_direction (str, optional): The direction to sort. Defaults to "asc". + + Returns: + DfgProjectPage: The search results. + """ from_ = page * size painless_fields_string = ", ".join([f"'{f}.keyword'" for f in DFG_PERSON_FIELDS]) @@ -471,6 +740,16 @@ def search_dfg_projects( def _complete_response_to_dfg_project_page( response: dict, page: int, size: int ) -> DfgProjectPage: + """Converts the raw Elasticsearch response into a DfgProjectPage object. + + Args: + response (dict): The raw Elasticsearch response. + page (int): The page number. + size (int): The number of items per page. + + Returns: + DfgProjectPage: The converted project page object. + """ hits_block = response.get("hits", {}) total_hits = hits_block.get("total", {}).get("value", 0) elements = [DfgProjectSummary.from_hit(hit) for hit in hits_block.get("hits", [])] @@ -478,6 +757,14 @@ def _complete_response_to_dfg_project_page( def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: + """Fetches the details of a single DFG project based on its project ID. + + Args: + project_id (str): The project ID to fetch. + + Returns: + Optional[DfgProjectDetails]: The project details or None if not found. + """ query = {"ids": {"values": [project_id]}} response = elasticsearch.search( @@ -494,10 +781,25 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: return None +# All + + def search_all_projects( projects_filtering_properties: ProjectsFilteringProperties, selected_project_types: Optional[Set[ProjectType]] = None, -): +) -> FundingProjectPage: + """Searches for projects across all project types based on the provided filtering properties and selected project types. + + Args: + projects_filtering_properties (ProjectsFilteringProperties): The filtering properties for the search. + selected_project_types (Optional[Set[ProjectType]], optional): The set of project types to include in the search. Defaults to None -> includes all project types. + + Raises: + ValueError: If the sorting property is not supported across all project types. + + Returns: + FundingProjectPage: The converted project page object. + """ sort_by = projects_filtering_properties.sort_by if sort_by != ProjectsSortBy.TITLE: raise ValueError( @@ -573,6 +875,16 @@ def search_all_projects( def _response_to_funding_project_page( response: Dict[str, Any], page: int, size: int ) -> FundingProjectPage: + """Converts the raw Elasticsearch response into a FundingProjectPage object. + + Args: + response (Dict[str, Any]): The raw Elasticsearch response. + page (int): The current page number. + size (int): The number of projects per page. + + Returns: + FundingProjectPage: The converted project page object. + """ hits = response.get("hits", {}).get("hits", []) projects = [_hit_to_funding_project(hit=hit) for hit in hits] total = response.get("hits", {}).get("total", {}).get("value", 0) @@ -580,219 +892,26 @@ def _response_to_funding_project_page( def _hit_to_funding_project(hit: Dict[str, Any]) -> FundingProject: + """Converts a single Elasticsearch hit into a FundingProject object based on the index it belongs to. + + Args: + hit (Dict[str, Any]): The Elasticsearch hit to convert. + + Raises: + ValueError: If the hit does not belong to a recognized project index. + + Returns: + FundingProject: The converted funding project object. + """ if hit.get("_index", "").startswith("cordis_eu_") and hit.get( "_index", "" ).endswith("_projects"): return FundingProject.from_cordis_projects_hit(hit=hit) - elif hit.get("_index") == "projects_bund_v1": + elif hit.get("_index") == ESIndex.PROJECTS_BUND_V1.value: return FundingProject.from_bund_projects_hit(hit=hit) - elif hit.get("_index") == "projects_dfg_all": + elif hit.get("_index") == ESIndex.PROJECTS_DFG_ALL.value: return FundingProject.from_dfg_projects_hit(hit=hit) else: raise ValueError( "The provided hit does not belong to a recognized project index." ) - - -def get_organization_project_contributions_foo( - organization_names: List[str], - projects_filtering_properties: ProjectsFilteringProperties, -) -> EuOrganizationProjectSummaryPage: - # Pagination depending on sorting criteria - # For FUNDING_AMOUNT before on the organization project contributions - # For the rest after the contributions are known on the real projects - - organization_project_contributions = get_organization_project_contributions( - organization_names=organization_names, - ) - - total_projects, projects = get_projects( - project_contributions=list(organization_project_contributions.values()), - projects_filtering_properties=projects_filtering_properties, - ) - - elements: List[EuOrganizationProjectSummary] = _merge_project_data( - projects=projects, contributions=organization_project_contributions - ) - - if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: - elements.sort( - key=lambda x: x.ec_contribution or 0, - reverse=projects_filtering_properties.sort_direction == SortDirection.DESC, - ) - start = projects_filtering_properties.page * projects_filtering_properties.size - end = start + projects_filtering_properties.size - elements = elements[start:end] - - return EuOrganizationProjectSummaryPage( - elements=elements, - total=total_projects, - page=projects_filtering_properties.page, - size=projects_filtering_properties.size, - ) - - -def get_organization_project_contributions( - organization_names: List[str], -) -> Dict[str, EuOrganizationShort]: - - source = ["projectID", "organisationID", "ecContribution"] - - query = { - "terms": { - "name.keyword": [ - name.upper() for name in organization_names if name.strip() - ], - } - } - - response = elasticsearch.search( - index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, - cluster=ESCluster.INSE, - source=source, - size=10000, - query=query, - ) - - logger.debug( - f"Received organization project contributions response: {json.dumps(response, indent=2)}" - ) - - organization_project_contributions = _process_organization_project_contributions( - response - ) - - logger.debug( - f"Found organization project contributions for organization names {organization_names}: {organization_project_contributions}" - ) - - return organization_project_contributions - - -def _process_organization_project_contributions( - response: Dict[str, Any], -) -> Dict[str, EuOrganizationShort]: - hits_block = response.get("hits", {}) - project_contributions: Dict[str, EuOrganizationShort] = {} - for hit in hits_block.get("hits", []): - source = hit.get("_source", {}) - project_id = source.get("projectID") - organization_id = source.get("organisationID") - ec_contribution = source.get("ecContribution") - if project_id and organization_id: - project_contributions[project_id] = EuOrganizationShort( - project_id=project_id, - organization_id=organization_id, - ec_contribution=ec_contribution, - ) - return project_contributions - - -def get_projects( - project_contributions: List[EuOrganizationShort], - projects_filtering_properties: ProjectsFilteringProperties, -) -> Tuple[int, Dict[str, EuProjectShort]]: - project_ids = [contribution.project_id for contribution in project_contributions] - - source = ["id", "title", "startDate", "endDate", "acronym"] - - query = { - "terms": { - "id": project_ids, - } - } - - if ( - projects_filtering_properties.query - and projects_filtering_properties.query.strip() - ): - query = { - "bool": { - "must": [ - { - "match_phrase_prefix": { - "title": { - "query": projects_filtering_properties.query, - "max_expansions": 50, - } - } - } - ], - "filter": query, - } - } - - # Project contributions have been filtered before based on ecContribution - if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: - response = elasticsearch.search( - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - cluster=ESCluster.INSE, - source=source, - query=query, - size=10000, - ) - else: - response = elasticsearch.search( - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - cluster=ESCluster.INSE, - source=source, - query=query, - size=projects_filtering_properties.size, - offset=projects_filtering_properties.page - * projects_filtering_properties.size, - sort=[ - { - projects_filtering_properties.sort_by.to_cordis_eu_project_sort_field(): { - "order": projects_filtering_properties.sort_direction - } - } - ], - ) - - return _process_projects_response(response) - - -def _process_projects_response( - response: Dict[str, Any], -) -> Tuple[int, Dict[str, EuProjectShort]]: - hits_block = response.get("hits", {}) - total = hits_block.get("total", {}).get("value", 0) - projects: Dict[str, EuProjectShort] = {} - for hit in hits_block.get("hits", []): - source = hit.get("_source", {}) - project_id = source.get("id") - title = source.get("title") - start_date = source.get("startDate") - end_date = source.get("endDate") - acronym = source.get("acronym") - if not project_id: - continue - projects[project_id] = EuProjectShort( - id=project_id, - title=title, - start_date=start_date, - end_date=end_date, - acronym=acronym, - ) - - return total, projects - - -def _merge_project_data( - projects: Dict[str, EuProjectShort], contributions: Dict[str, EuOrganizationShort] -) -> List[EuOrganizationProjectSummary]: - merged_data = [] - for project_id, project_info in projects.items(): - contribution_info = contributions.get(project_id) - if contribution_info: - merged_entry = EuOrganizationProjectSummary( - project_id=project_id, - title=project_info.title, - start_date=project_info.start_date, - end_date=project_info.end_date, - acronym=project_info.acronym, - organization_id=contribution_info.organization_id, - ec_contribution=contribution_info.ec_contribution, - ) - merged_data.append(merged_entry) - return merged_data diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 4f35c69b..75c72e0e 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -4,7 +4,7 @@ from typing import Any, Dict, List, Optional, Set from inse.projects import projects_search_client from inse.projects.projects_search_client import ( - get_organization_project_contributions_foo, + get_eu_organization_project_contributions, ) from inse.projects.model import ( BundProjectPage, @@ -90,12 +90,8 @@ def get_bund_projects_by_institution_id( f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) response = projects_search_client.search_bund_projects( - page=filtering_properties.page, - size=filtering_properties.size, institution_names=institution_aliases, - topic=filtering_properties.query, - sort_by=filtering_properties.sort_by, - sort_direction=filtering_properties.sort_direction, + filter_properties=filtering_properties, ) logger.debug(f"get_bund_projects_by_institution_id response: {response}") return response @@ -137,7 +133,7 @@ def get_cordis_eu_projects_by_institution_id( f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) - page = get_organization_project_contributions_foo( + page = get_eu_organization_project_contributions( organization_names=institution_aliases, projects_filtering_properties=projects_filtering_properties, ) @@ -186,7 +182,7 @@ async def get_institution_cordis_eu_projects_funding_over_time( raw_oa_institution_id ) ) - page = get_organization_project_contributions_foo( + page = get_eu_organization_project_contributions( organization_names=institution_aliases, projects_filtering_properties=ProjectsFilteringProperties( project_type=ProjectType.EU, @@ -220,8 +216,11 @@ def get_institution_bund_projects_funding_over_time( f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" ) response = projects_search_client.search_bund_projects( - page=0, - size=10000, + filter_properties=ProjectsFilteringProperties( + project_type=ProjectType.BUND, + page=0, + size=10000, + ), institution_names=institution_aliases, )