diff --git a/service/Dockerfile b/service/Dockerfile
index 90d1a619..1c1f95a2 100644
--- a/service/Dockerfile
+++ b/service/Dockerfile
@@ -13,7 +13,6 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
"pytest~=8.1.0" \
"httpx~=0.27.0" \
"python-multipart~=0.0.19"\
- "elasticsearch~=9.4.0" \
"openai~=2.41.0"
COPY [ "src/main", "/home" ]
diff --git a/service/pyproject.toml b/service/pyproject.toml
index 9e45ebc4..7a21303c 100644
--- a/service/pyproject.toml
+++ b/service/pyproject.toml
@@ -7,7 +7,6 @@ requires-python = ">=3.12"
dependencies = [
"cryptography~=42.0.0",
"dotenv>=0.9.9",
- "elasticsearch~=9.4.0",
"fastapi~=0.115.0",
"httpx~=0.27.0",
"openai~=2.41.0",
diff --git a/service/src/main/inse/company_connections/logic.py b/service/src/main/inse/company_connections/logic.py
index 1ffea295..fa96a1f4 100644
--- a/service/src/main/inse/company_connections/logic.py
+++ b/service/src/main/inse/company_connections/logic.py
@@ -1,12 +1,9 @@
import logging
from typing import Any
-import httpx
-from fastapi import HTTPException
-from starlette.status import HTTP_502_BAD_GATEWAY, HTTP_503_SERVICE_UNAVAILABLE
-
from . import model
-from .search_client import CompanyConnectionsSearchClient, MissingApiKeyError
+from inse.exceptions import MissingApiKeyError, ElasticsearchException, NotFoundException
+from .search_client import CompanyConnectionsSearchClient
logger = logging.getLogger(__name__)
@@ -23,22 +20,10 @@ async def get_company_connections_by_author_id(
) -> model.CompanyConnectionsResponse:
search_client = client or CompanyConnectionsSearchClient()
- try:
- author_hit = await search_client.get_openalex_author(author_id)
- except MissingApiKeyError as exc:
- raise HTTPException(
- status_code=HTTP_503_SERVICE_UNAVAILABLE,
- detail="Elasticsearch is not configured.",
- ) from exc
- except httpx.HTTPError as exc:
- logger.exception("OpenAlex author lookup failed for %s.", author_id)
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="OpenAlex author lookup failed.",
- ) from exc
+ author_hit = await search_client.get_openalex_author(author_id)
if author_hit is None:
- raise HTTPException(status_code=404, detail=f"Author {author_id} not found.")
+ raise NotFoundException(f"Author {author_id} not found.")
source = author_hit.get("_source", {})
display_name = _clean(source.get("display_name"))
@@ -59,21 +44,9 @@ async def get_company_connections_by_author_id(
connections=[],
)
- try:
- hr_response = await search_client.search_handelsregister_by_officer_name(
- display_name
- )
- except MissingApiKeyError as exc:
- raise HTTPException(
- status_code=HTTP_503_SERVICE_UNAVAILABLE,
- detail="Elasticsearch is not configured.",
- ) from exc
- except httpx.HTTPError as exc:
- logger.exception("Handelsregister lookup failed for %s.", display_name)
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="Handelsregister lookup failed.",
- ) from exc
+ hr_response = await search_client.search_handelsregister_by_officer_name(
+ display_name
+ )
company_count, company_count_relation = _parse_total(hr_response)
connections = _parse_company_connections(
diff --git a/service/src/main/inse/company_connections/search_client.py b/service/src/main/inse/company_connections/search_client.py
index 4516f4f7..b4fe2d1e 100644
--- a/service/src/main/inse/company_connections/search_client.py
+++ b/service/src/main/inse/company_connections/search_client.py
@@ -5,8 +5,12 @@ import httpx
from .. import config
-class MissingApiKeyError(Exception):
- pass
+from inse.integrations import elasticsearch
+from inse.model import ESCluster
+from inse.exceptions import ElasticsearchNotFoundException
+
+
+from inse.exceptions import MissingApiKeyError
class CompanyConnectionsSearchClient:
@@ -28,7 +32,7 @@ class CompanyConnectionsSearchClient:
api_key
if api_key is not None
else config.settings.elasticsearch_api_key
-)
+ )
self.openalex_index = openalex_index
self.handelsregister_index = handelsregister_index
self.timeout = timeout
@@ -39,26 +43,15 @@ class CompanyConnectionsSearchClient:
return author_id.strip().removeprefix("https://openalex.org/")
async def get_openalex_author(self, author_id: str) -> dict[str, Any] | None:
- if not self.api_key:
- raise MissingApiKeyError("Elasticsearch API key is not configured.")
-
doc_id = self.openalex_doc_id(author_id)
-
- async with httpx.AsyncClient(
- base_url=self.base_url,
- timeout=self.timeout,
- transport=self.transport,
- ) as client:
- response = await client.get(
- f"/{self.openalex_index}/_doc/{doc_id}",
- headers={"Authorization": f"ApiKey {self.api_key}"},
+ try:
+ return await elasticsearch.get(
+ index=self.openalex_index,
+ doc_id=doc_id,
+ cluster=ESCluster.NES,
)
-
- if response.status_code == 404:
- return None
-
- response.raise_for_status()
- return response.json()
+ except ElasticsearchNotFoundException:
+ return None
async def search_handelsregister_by_officer_name(
self,
@@ -66,27 +59,16 @@ class CompanyConnectionsSearchClient:
size: int = 10000,
track_total_hits: bool = True,
) -> dict[str, Any]:
- if not self.api_key:
- raise MissingApiKeyError("Elasticsearch API key is not configured.")
-
payload = self.handelsregister_officer_name_query(
officer_name=officer_name,
size=size,
track_total_hits=track_total_hits,
)
-
- async with httpx.AsyncClient(
- base_url=self.base_url,
- timeout=self.timeout,
- transport=self.transport,
- ) as client:
- response = await client.post(
- f"/{self.handelsregister_index}/_search",
- headers={"Authorization": f"ApiKey {self.api_key}"},
- json=payload,
- )
- response.raise_for_status()
- return response.json()
+ return await elasticsearch.search(
+ index=self.handelsregister_index,
+ body=payload,
+ cluster=ESCluster.NES,
+ )
@staticmethod
def handelsregister_officer_name_query(
diff --git a/service/src/main/inse/exceptions.py b/service/src/main/inse/exceptions.py
index 772a9607..c642bca5 100644
--- a/service/src/main/inse/exceptions.py
+++ b/service/src/main/inse/exceptions.py
@@ -1,3 +1,36 @@
class NotFoundException(Exception):
def __init__(self, message: str):
super().__init__(message)
+
+
+class ElasticsearchException(Exception):
+ """Base exception for all Elasticsearch integrations."""
+ pass
+
+
+class ElasticsearchNotFoundException(NotFoundException, ElasticsearchException):
+ """Raised when an Elasticsearch document or index is not found."""
+ pass
+
+
+class ElasticsearchConnectionException(ElasticsearchException):
+ """Raised when connecting to Elasticsearch fails."""
+ pass
+
+
+class MissingApiKeyError(Exception):
+ """Raised when a required API key is missing."""
+ pass
+
+
+class UpstreamAPIException(Exception):
+ """Raised when an upstream third-party service (e.g. REST API) fails."""
+ def __init__(self, message: str, status_code: int = 502):
+ self.message = message
+ self.status_code = status_code
+ super().__init__(message)
+
+
+class BadRequestException(Exception):
+ """Raised when request parameters are invalid or validation fails."""
+ pass
diff --git a/service/src/main/inse/funders/elastic_search_client.py b/service/src/main/inse/funders/elastic_search_client.py
index a411cb0a..08dc6bde 100644
--- a/service/src/main/inse/funders/elastic_search_client.py
+++ b/service/src/main/inse/funders/elastic_search_client.py
@@ -8,10 +8,11 @@ from typing import Any
import httpx
from .. import config
+from inse.integrations import elasticsearch
+from inse.model import ESCluster
-class MissingApiKeyError(Exception):
- pass
+from inse.exceptions import MissingApiKeyError
class FundedPublicationsSearchClient:
@@ -177,15 +178,8 @@ class FundedPublicationsSearchClient:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
- async with httpx.AsyncClient(
- base_url=self.base_url,
- timeout=self.timeout,
- transport=self.transport,
- ) as client:
- response = await client.post(
- f"/{self.index}/_search",
- headers={"Authorization": f"ApiKey {self.api_key}"},
- json=payload,
- )
- response.raise_for_status()
- return response.json()
+ return await elasticsearch.search(
+ index=self.index,
+ body=payload,
+ cluster=ESCluster.NES,
+ )
diff --git a/service/src/main/inse/funders/logic.py b/service/src/main/inse/funders/logic.py
index 1976a9c8..bad9e46e 100644
--- a/service/src/main/inse/funders/logic.py
+++ b/service/src/main/inse/funders/logic.py
@@ -6,16 +6,11 @@
import logging
from typing import Any
-import httpx
-from fastapi import HTTPException
from pydantic import ValidationError
-from starlette.status import HTTP_502_BAD_GATEWAY
-from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
-
from ..persons import logic as person_logic
from . import model
from .elastic_search_client import FundedPublicationsSearchClient
-from .elastic_search_client import MissingApiKeyError
+from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
logger = logging.getLogger(__name__)
@@ -62,7 +57,7 @@ async def get_funders_by_author_id(
funder_counts: dict[str, dict[str, Any]] = {}
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
- author_name = _get_author_name(author_id)
+ author_name = await _get_author_name(author_id)
try:
_, all_hits = await _fetch_all_author_work_hits(
@@ -92,9 +87,9 @@ async def get_funders_by_author_id(
)
except ValidationError as exc:
logger.exception("Funders response could not be validated for author %s.", author_id)
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="Funders response could not be parsed.",
+ raise UpstreamAPIException(
+ message="Funders response could not be parsed.",
+ status_code=502,
) from exc
@@ -144,26 +139,13 @@ async def _search_funded_publications(
*,
funded_only: bool = False,
) -> dict:
- try:
- payload = search_client.publications_by_author_query(
- author_id,
- page,
- page_size,
- funded_only=funded_only,
- )
- return await search_client.search(payload)
- except MissingApiKeyError as exc:
- logger.error("OpenAlex works Elasticsearch API key is not configured.")
- raise HTTPException(
- status_code=HTTP_503_SERVICE_UNAVAILABLE,
- detail="OpenAlex works search is not configured.",
- ) from exc
- except httpx.HTTPError as exc:
- logger.exception("OpenAlex works search request failed.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="OpenAlex works search request failed.",
- ) from exc
+ payload = search_client.publications_by_author_query(
+ author_id,
+ page,
+ page_size,
+ funded_only=funded_only,
+ )
+ return await search_client.search(payload)
def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
@@ -180,9 +162,9 @@ def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
return total, results
-def _get_author_name(author_id: str) -> str | None:
+async def _get_author_name(author_id: str) -> str | None:
short_author_id = author_id.replace("https://openalex.org/", "")
- search_result = person_logic.search_persons(author_id=short_author_id)
+ search_result = await person_logic.search_persons(author_id=short_author_id)
if not search_result.results:
return None
diff --git a/service/src/main/inse/funders/test_logic.py b/service/src/main/inse/funders/test_logic.py
index 234ffdcf..52ff0fdb 100644
--- a/service/src/main/inse/funders/test_logic.py
+++ b/service/src/main/inse/funders/test_logic.py
@@ -1,8 +1,6 @@
-import json
-
-import httpx
import pytest
-from fastapi import HTTPException
+from unittest.mock import AsyncMock, patch
+from inse.exceptions import MissingApiKeyError
from inse.funders import logic
from inse.funders.elastic_search_client import FundedPublicationsSearchClient
@@ -68,201 +66,177 @@ def _funded_publication_hit(
@pytest.mark.anyio
-async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch):
- def handler(request: httpx.Request) -> httpx.Response:
- payload = json.loads(request.content.decode("utf-8"))
- assert payload["from"] == 0
- return httpx.Response(
- 200,
- json={
- "hits": {
- "total": {"value": 2},
- "hits": [
- _funded_publication_hit(
- "https://openalex.org/W1",
- funder_id="https://openalex.org/F123",
- funder_name="Funder A",
- author_position="first",
- pdf_url="https://example.org/w1.pdf",
- abstract_inverted_index={
- "This": [0],
- "is": [1],
- "an": [2],
- "abstract.": [3],
+async def test_get_funders_by_author_id_aggregates_funders_and_awards():
+ mock_es_response = {
+ "hits": {
+ "total": {"value": 2},
+ "hits": [
+ _funded_publication_hit(
+ "https://openalex.org/W1",
+ funder_id="https://openalex.org/F123",
+ funder_name="Funder A",
+ author_position="first",
+ pdf_url="https://example.org/w1.pdf",
+ abstract_inverted_index={
+ "This": [0],
+ "is": [1],
+ "an": [2],
+ "abstract.": [3],
+ },
+ extra_source={
+ "title": "Example publication: full detail",
+ "funders": [
+ {
+ "id": "https://openalex.org/F456",
+ "display_name": "Funder B",
+ }
+ ],
+ "publication_year": 2020,
+ "publication_date": "2020-05-10",
+ "type": "article",
+ "language": "en",
+ "cited_by_count": 12,
+ "is_retracted": False,
+ "primary_location": {
+ "pdf_url": "https://example.org/w1.pdf",
+ "is_oa": True,
+ "license": "cc-by",
+ "source": {
+ "display_name": "Example Journal",
+ "type": "journal",
},
- extra_source={
- "title": "Example publication: full detail",
- "funders": [
- {
- "id": "https://openalex.org/F456",
- "display_name": "Funder B",
- }
- ],
- "publication_year": 2020,
- "publication_date": "2020-05-10",
- "type": "article",
- "language": "en",
- "cited_by_count": 12,
- "is_retracted": False,
- "primary_location": {
- "pdf_url": "https://example.org/w1.pdf",
- "is_oa": True,
- "license": "cc-by",
- "source": {
- "display_name": "Example Journal",
- "type": "journal",
- },
- },
- "open_access": {
- "is_oa": True,
- "oa_status": "gold",
- "any_repository_has_fulltext": True,
- },
- "primary_topic": {
- "display_name": "Clinical Trials",
- "subfield": {"display_name": "Medicine"},
- "field": {"display_name": "Health Sciences"},
- "domain": {"display_name": "Life Sciences"},
- },
- "topics": [
- {"display_name": "Trials", "score": 0.8},
- {"display_name": "Guidelines", "score": 0.6},
- ],
- "keywords": [
- {"display_name": "randomised trials", "score": 0.9},
- {"display_name": "reporting guideline", "score": 0.7},
- ],
- "counts_by_year": [
- {"year": 2024, "cited_by_count": 3},
- {"year": 2023, "cited_by_count": 2},
- ],
- },
- ),
- _funded_publication_hit(
- "https://openalex.org/W2",
- funder_id=None,
- funder_name=None,
- award_funder_id="https://openalex.org/F123",
- award_funder_name="Funder A",
- award_display_name="Project Grant",
- award_number="PG-42",
- author_position="last",
- ),
- ],
- },
- },
- )
+ },
+ "open_access": {
+ "is_oa": True,
+ "oa_status": "gold",
+ "any_repository_has_fulltext": True,
+ },
+ "primary_topic": {
+ "display_name": "Clinical Trials",
+ "subfield": {"display_name": "Medicine"},
+ "field": {"display_name": "Health Sciences"},
+ "domain": {"display_name": "Life Sciences"},
+ },
+ "topics": [
+ {"display_name": "Trials", "score": 0.8},
+ {"display_name": "Guidelines", "score": 0.6},
+ ],
+ "keywords": [
+ {"display_name": "randomised trials", "score": 0.9},
+ {"display_name": "reporting guideline", "score": 0.7},
+ ],
+ "counts_by_year": [
+ {"year": 2024, "cited_by_count": 3},
+ {"year": 2023, "cited_by_count": 2},
+ ],
+ },
+ ),
+ _funded_publication_hit(
+ "https://openalex.org/W2",
+ funder_id=None,
+ funder_name=None,
+ award_funder_id="https://openalex.org/F123",
+ award_funder_name="Funder A",
+ award_display_name="Project Grant",
+ award_number="PG-42",
+ author_position="last",
+ ),
+ ],
+ },
+ }
- monkeypatch.setattr(
- logic.person_logic,
- "search_persons",
- lambda author_id: type(
- "Result",
- (),
- {"results": [type("Author", (), {"display_name": "Example Author"})()]},
- )(),
- )
+ mock_author_result = type(
+ "Result",
+ (),
+ {"results": [type("Author", (), {"display_name": "Example Author"})()]}
+ )()
- client = FundedPublicationsSearchClient(
- base_url="https://project.nes.uni-due.de/elastic",
- api_key="test-key",
- transport=httpx.MockTransport(handler),
- )
+ with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
+ patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
+ mock_search.return_value = mock_es_response
+ mock_search_persons.return_value = mock_author_result
- response = await logic.get_funders_by_author_id("A5023888391", client=client)
+ client = FundedPublicationsSearchClient(api_key="test-key")
+ response = await logic.get_funders_by_author_id("A5023888391", client=client)
- assert response.author_id == "https://openalex.org/A5023888391"
- assert response.author_name == "Example Author"
- assert response.funder_count == 2
- assert response.funders[0].funder_id == "https://openalex.org/F123"
- assert response.funders[0].funder_name == "Funder A"
- assert response.funders[0].publication_count == 2
- assert response.funders[0].author_position_count.first == 1
- assert response.funders[0].author_position_count.last == 1
- assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"]
- assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"]
- assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
- assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
- publication_detail = response.funders[0].publication_details["https://openalex.org/W1"]
- assert publication_detail.title == "Example publication: full detail"
- assert publication_detail.funder_names == ["Funder A", "Funder B"]
- assert publication_detail.abstract == "This is an abstract."
- assert publication_detail.publication_date == "2020-05-10"
- assert publication_detail.publication_type == "article"
- assert publication_detail.source_name == "Example Journal"
- assert publication_detail.source_type == "journal"
- assert publication_detail.is_open_access is True
- assert publication_detail.open_access_status == "gold"
- assert publication_detail.has_fulltext is True
- assert publication_detail.license == "cc-by"
- assert publication_detail.cited_by_count == 12
- assert publication_detail.primary_topic == "Clinical Trials"
- assert publication_detail.topic_field == "Health Sciences"
- assert publication_detail.topic_subfield == "Medicine"
- assert publication_detail.topic_domain == "Life Sciences"
- assert publication_detail.topics == ["Trials", "Guidelines"]
- assert publication_detail.keywords == ["randomised trials", "reporting guideline"]
- assert publication_detail.counts_by_year == [
- {"year": 2024, "cited_by_count": 3},
- {"year": 2023, "cited_by_count": 2},
- ]
- assert response.funders[0].publication_details["https://openalex.org/W2"].grant_labels == [
- "Project Grant"
- ]
+ assert response.author_id == "https://openalex.org/A5023888391"
+ assert response.author_name == "Example Author"
+ assert response.funder_count == 2
+
+ funder_a = next(f for f in response.funders if f.funder_id == "https://openalex.org/F123")
+ assert funder_a.funder_name == "Funder A"
+ assert funder_a.publication_count == 2
+ assert funder_a.author_position_count.first == 1
+ assert funder_a.author_position_count.last == 1
+ assert funder_a.publication_ids.first == ["https://openalex.org/W1"]
+ assert funder_a.publication_ids.last == ["https://openalex.org/W2"]
+ assert funder_a.publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
+ assert funder_a.publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
+
+ pub1_detail = funder_a.publication_details["https://openalex.org/W1"]
+ assert pub1_detail.title == "Example publication: full detail"
+ assert pub1_detail.funder_names == ["Funder A", "Funder B"]
+ assert pub1_detail.abstract == "This is an abstract."
+ assert pub1_detail.publication_date == "2020-05-10"
+ assert pub1_detail.publication_type == "article"
+ assert pub1_detail.source_name == "Example Journal"
+ assert pub1_detail.source_type == "journal"
+ assert pub1_detail.is_open_access is True
+ assert pub1_detail.open_access_status == "gold"
+ assert pub1_detail.has_fulltext is True
+ assert pub1_detail.license == "cc-by"
+ assert pub1_detail.cited_by_count == 12
+ assert pub1_detail.primary_topic == "Clinical Trials"
+ assert pub1_detail.topic_field == "Health Sciences"
+ assert pub1_detail.topic_subfield == "Medicine"
+ assert pub1_detail.topic_domain == "Life Sciences"
+ assert pub1_detail.topics == ["Trials", "Guidelines"]
+ assert pub1_detail.keywords == ["randomised trials", "reporting guideline"]
+ assert pub1_detail.counts_by_year == [
+ {"year": 2024, "cited_by_count": 3},
+ {"year": 2023, "cited_by_count": 2},
+ ]
+ assert funder_a.publication_details["https://openalex.org/W2"].grant_labels == ["Project Grant"]
@pytest.mark.anyio
-async def test_publication_grant_labels_ignore_funder_award_id_without_display_name(monkeypatch):
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 200,
- json={
- "hits": {
- "total": {"value": 1},
- "hits": [
- _funded_publication_hit(
- "https://openalex.org/W3",
- funder_id="https://openalex.org/F123",
- funder_name="Funder A",
- award_funder_id="https://openalex.org/F123",
- award_funder_name="Funder A",
- award_display_name=None,
- award_number="ANR-12-1234",
- ),
- ],
- },
- },
- )
+async def test_publication_grant_labels_ignore_funder_award_id_without_display_name():
+ mock_es_response = {
+ "hits": {
+ "total": {"value": 1},
+ "hits": [
+ _funded_publication_hit(
+ "https://openalex.org/W3",
+ funder_id="https://openalex.org/F123",
+ funder_name="Funder A",
+ award_funder_id="https://openalex.org/F123",
+ award_funder_name="Funder A",
+ award_display_name=None,
+ award_number="ANR-12-1234",
+ ),
+ ],
+ },
+ }
+ mock_author_result = type("Result", (), {"results": [type("Author", (), {"display_name": "Example Author"})()]})()
- monkeypatch.setattr(
- logic.person_logic,
- "search_persons",
- lambda author_id: type(
- "Result",
- (),
- {"results": [type("Author", (), {"display_name": "Example Author"})()]},
- )(),
- )
+ with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
+ patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
+ mock_search.return_value = mock_es_response
+ mock_search_persons.return_value = mock_author_result
- client = FundedPublicationsSearchClient(
- base_url="https://project.nes.uni-due.de/elastic",
- api_key="test-key",
- transport=httpx.MockTransport(handler),
- )
+ client = FundedPublicationsSearchClient(api_key="test-key")
+ response = await logic.get_funders_by_author_id("A5023888391", client=client)
- response = await logic.get_funders_by_author_id("A5023888391", client=client)
-
- assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == []
+ assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == []
@pytest.mark.anyio
-async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch):
+async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded():
requested_pages: list[int] = []
- def handler(request: httpx.Request) -> httpx.Response:
- payload = json.loads(request.content.decode("utf-8"))
- size = payload["size"]
- offset = payload["from"]
+ async def mock_search_func(index, body, cluster=None):
+ size = body["size"]
+ offset = body["from"]
page = offset // size + 1
requested_pages.append(page)
total = size + 1
@@ -284,115 +258,87 @@ async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(m
)
]
- return httpx.Response(
- 200,
- json={
- "hits": {
- "total": {"value": total},
- "hits": hits,
- },
+ return {
+ "hits": {
+ "total": {"value": total},
+ "hits": hits,
},
- )
+ }
- monkeypatch.setattr(
- logic.person_logic,
- "search_persons",
- lambda author_id: type("Result", (), {"results": []})(),
- )
+ mock_author_result = type("Result", (), {"results": []})()
- client = FundedPublicationsSearchClient(
- base_url="https://project.nes.uni-due.de/elastic",
- api_key="test-key",
- transport=httpx.MockTransport(handler),
- )
+ with patch("inse.integrations.elasticsearch.search", side_effect=mock_search_func) as mock_search, \
+ patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
+ mock_search_persons.return_value = mock_author_result
- response = await logic.get_funders_by_author_id("A5023888391", client=client)
+ client = FundedPublicationsSearchClient(api_key="test-key")
+ response = await logic.get_funders_by_author_id("A5023888391", client=client)
- assert requested_pages == [1, 2]
- assert response.funder_count > 1
- funder_names = {funder.funder_name for funder in response.funders}
- assert "Funder 1" in funder_names
+ assert requested_pages == [1, 2]
+ assert response.funder_count > 1
+ funder_names = {funder.funder_name for funder in response.funders}
+ assert "Funder 1" in funder_names
@pytest.mark.anyio
-async def test_get_funders_by_author_id_ignores_publications_without_funders(monkeypatch):
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 200,
- json={
- "hits": {
- "total": {"value": 2},
- "hits": [
- _funded_publication_hit(
- "https://openalex.org/W1",
- funder_id="https://openalex.org/F123",
- funder_name="Bundesministerium",
- ),
- _funded_publication_hit(
- "https://openalex.org/W2",
- funder_id=None,
- funder_name=None,
- ),
- ],
- },
- },
- )
+async def test_get_funders_by_author_id_ignores_publications_without_funders():
+ mock_es_response = {
+ "hits": {
+ "total": {"value": 2},
+ "hits": [
+ _funded_publication_hit(
+ "https://openalex.org/W1",
+ funder_id="https://openalex.org/F123",
+ funder_name="Bundesministerium",
+ ),
+ _funded_publication_hit(
+ "https://openalex.org/W2",
+ funder_id=None,
+ funder_name=None,
+ ),
+ ],
+ },
+ }
+ mock_author_result = type("Result", (), {"results": []})()
- monkeypatch.setattr(
- logic.person_logic,
- "search_persons",
- lambda author_id: type("Result", (), {"results": []})(),
- )
+ with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
+ patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
+ mock_search.return_value = mock_es_response
+ mock_search_persons.return_value = mock_author_result
- client = FundedPublicationsSearchClient(
- base_url="https://project.nes.uni-due.de/elastic",
- api_key="test-key",
- transport=httpx.MockTransport(handler),
- )
+ client = FundedPublicationsSearchClient(api_key="test-key")
+ response = await logic.get_funders_by_author_id("A5093075883", client=client)
- response = await logic.get_funders_by_author_id("A5093075883", client=client)
-
- assert response.funder_count == 1
- assert response.funders[0].funder_name == "Bundesministerium"
- assert response.funders[0].publication_count == 1
+ assert response.funder_count == 1
+ assert response.funders[0].funder_name == "Bundesministerium"
+ assert response.funders[0].publication_count == 1
@pytest.mark.anyio
-async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(monkeypatch):
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 200,
- json={"hits": {"total": {"value": 0}, "hits": []}},
- )
+async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders():
+ mock_es_response = {"hits": {"total": {"value": 0}, "hits": []}}
+ mock_author_result = type("Result", (), {"results": []})()
- monkeypatch.setattr(
- logic.person_logic,
- "search_persons",
- lambda author_id: type("Result", (), {"results": []})(),
- )
+ with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
+ patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
+ mock_search.return_value = mock_es_response
+ mock_search_persons.return_value = mock_author_result
- client = FundedPublicationsSearchClient(
- base_url="https://project.nes.uni-due.de/elastic",
- api_key="test-key",
- transport=httpx.MockTransport(handler),
- )
+ client = FundedPublicationsSearchClient(api_key="test-key")
+ response = await logic.get_funders_by_author_id("A5093075883", client=client)
- response = await logic.get_funders_by_author_id("A5093075883", client=client)
-
- assert response.funder_count == 0
- assert response.funders == []
+ assert response.funder_count == 0
+ assert response.funders == []
@pytest.mark.anyio
-async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(monkeypatch):
- monkeypatch.setattr(
- logic.person_logic,
- "search_persons",
- lambda author_id: type("Result", (), {"results": []})(),
- )
- client = FundedPublicationsSearchClient(api_key="")
+async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable():
+ mock_author_result = type("Result", (), {"results": []})()
- with pytest.raises(HTTPException) as exc:
- await logic.get_funders_by_author_id("A5023888391", client=client)
+ with patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
+ mock_search_persons.return_value = mock_author_result
- assert exc.value.status_code == 503
+ client = FundedPublicationsSearchClient(api_key="")
+
+ with pytest.raises(MissingApiKeyError):
+ await logic.get_funders_by_author_id("A5023888391", client=client)
diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py
index 0e86c8de..975d6c4d 100644
--- a/service/src/main/inse/institutions/institutions_search_client.py
+++ b/service/src/main/inse/institutions/institutions_search_client.py
@@ -20,7 +20,7 @@ class InstitutionsSearchClient:
"""
pass
- def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
+ async def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
"""Retrieves an institution by its raw OpenAlex institution ID.
Args:
@@ -38,7 +38,7 @@ class InstitutionsSearchClient:
}
}
- res = elasticsearch.search(index="openalex-institutions", query=query, size=1)
+ res = await elasticsearch.search(index="openalex-institutions", query=query, size=1)
hits = res.get("hits", {}).get("hits", [])
if not hits:
@@ -72,7 +72,7 @@ class InstitutionsSearchClient:
# TODO: Implement actual retrieval of RCN from Elasticsearch or another source instead of using a hardcoded cache.
return cache.get(raw_institution_id)
- def get_institutions_by_name(
+ async def get_institutions_by_name(
self,
name: str,
page: int = 0,
@@ -122,7 +122,7 @@ class InstitutionsSearchClient:
query,
)
try:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index="openalex-institutions",
offset=page * size,
size=size,
@@ -189,7 +189,7 @@ class InstitutionsSearchClient:
query,
)
- res = elasticsearch.search(index="openalex-authors", query=query)
+ res = await elasticsearch.search(index="openalex-authors", query=query)
hits = res.get("hits", {}).get("hits", [])
# Extracting display_name directly from the author document source
@@ -200,7 +200,7 @@ class InstitutionsSearchClient:
}
return list(authors)
- def search_institutions(
+ async def search_institutions(
self,
query_text: str,
country_code: str | None = None,
@@ -265,7 +265,7 @@ class InstitutionsSearchClient:
}
}
- res = elasticsearch.search(
+ res = await elasticsearch.search(
index="openalex-institutions",
query=query,
size=limit,
@@ -288,7 +288,7 @@ class InstitutionsSearchClient:
return [Institution.from_dict(hit["_source"]) for hit in hits]
- def get_institution_aliases_by_oa_institution_id(
+ async 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.
@@ -299,7 +299,7 @@ class InstitutionsSearchClient:
Returns:
List[str]: A list of aliases for the given institution ID.
"""
- institution = self.get_institution_by_id(raw_oa_institution_id)
+ institution = await 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_oa_institution_id)
@@ -426,7 +426,7 @@ class InstitutionsSearchClient:
)
return None
- def get_cordis_eu_organisation_ids_by_oa_institution_id(
+ async 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.
@@ -439,7 +439,7 @@ class InstitutionsSearchClient:
"""
institution_aliases = set(
- self.get_institution_aliases_by_oa_institution_id(
+ await self.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id=raw_oa_institution_id
)
)
@@ -476,7 +476,7 @@ class InstitutionsSearchClient:
try:
# IMPORTANT: The indices are named organizations and not organisations. + 15 Minutes debugging why the search returns 0 results
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index="cordis_eu_*_organizations", body=body, cluster="inse"
)
except Exception as e:
diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py
index 10f53cc6..d001c646 100644
--- a/service/src/main/inse/institutions/logic.py
+++ b/service/src/main/inse/institutions/logic.py
@@ -9,10 +9,8 @@ from copy import deepcopy
from typing import Any, Optional
import httpx
-from fastapi import HTTPException
from pydantic import ValidationError
-from starlette.status import HTTP_400_BAD_REQUEST
-from starlette.status import HTTP_502_BAD_GATEWAY
+from inse.exceptions import UpstreamAPIException, BadRequestException
from inse.models.openalex.autocomplete_response import AutocompleteResponse
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
@@ -41,7 +39,7 @@ _VALID_INSTITUTION_TYPES = {
async def get_institution_by_id(
raw_institution_id: str, client: InstitutionsSearchClient
) -> Institution:
- return client.get_institution_by_id(raw_institution_id)
+ return await client.get_institution_by_id(raw_institution_id)
async def list_institutions(
@@ -58,10 +56,7 @@ async def list_institutions(
client: OpenAlexInstitutionsClient | None = None,
) -> InstitutionsListResponse:
if sample is not None and (sort or page not in (None, 1)):
- raise HTTPException(
- status_code=HTTP_400_BAD_REQUEST,
- detail="sample cannot be combined with sort or page.",
- )
+ raise BadRequestException("sample cannot be combined with sort or page.")
openalex_client = client or OpenAlexInstitutionsClient()
@@ -86,12 +81,12 @@ async def list_institutions(
except ValueError:
if exc.response.text:
detail = exc.response.text
- raise HTTPException(status_code=status_code, detail=detail) from exc
+ raise UpstreamAPIException(message=detail, status_code=status_code) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex institutions request failed.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="OpenAlex institutions request failed.",
+ raise UpstreamAPIException(
+ message="OpenAlex institutions request failed.",
+ status_code=502,
) from exc
try:
@@ -102,9 +97,9 @@ async def list_institutions(
)
except ValidationError as exc:
logger.exception("OpenAlex institutions response could not be parsed.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="OpenAlex institutions response could not be parsed.",
+ raise UpstreamAPIException(
+ message="OpenAlex institutions response could not be parsed.",
+ status_code=502,
) from exc
@@ -120,7 +115,7 @@ async def autocomplete_institutions(
Returns institution options for autocomplete inputs using the local
Elasticsearch cluster via the provided client.
"""
- institutions = client.search_institutions(
+ institutions = await client.search_institutions(
query_text=query,
country_code=country_code,
institution_type=institution_type,
diff --git a/service/src/main/inse/institutions/router.py b/service/src/main/inse/institutions/router.py
index 423281c0..2709e4d9 100644
--- a/service/src/main/inse/institutions/router.py
+++ b/service/src/main/inse/institutions/router.py
@@ -72,7 +72,7 @@ async def search_institutions_by_name(
),
] = "asc",
) -> InstitutionPage:
- return client.get_institutions_by_name(
+ return await client.get_institutions_by_name(
name=name,
page=page,
size=size,
diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py
index bebf52c0..11544b19 100644
--- a/service/src/main/inse/institutions/test_logic.py
+++ b/service/src/main/inse/institutions/test_logic.py
@@ -1,6 +1,6 @@
import httpx
import pytest
-from fastapi import HTTPException
+from inse.exceptions import BadRequestException
from inse.institutions import logic
from inse.institutions.search_client import OpenAlexInstitutionsClient
@@ -96,11 +96,9 @@ async def test_list_institutions_maps_openalex_response_to_model():
@pytest.mark.anyio
async def test_list_institutions_rejects_sample_with_sort():
- with pytest.raises(HTTPException) as exc_info:
+ with pytest.raises(BadRequestException) as exc_info:
await logic.list_institutions(sample=10, sort="works_count:desc")
- assert exc_info.value.status_code == 400
-
@pytest.mark.anyio
async def test_list_institutions_accepts_practical_openalex_type_variants():
diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py
index 6c6164be..803aa212 100644
--- a/service/src/main/inse/integrations/elasticsearch.py
+++ b/service/src/main/inse/integrations/elasticsearch.py
@@ -1,13 +1,37 @@
import json
import logging
-from typing import Any, Dict, List, Optional, Tuple
+from typing import Any, Dict, AsyncIterator, List, Optional, Tuple
+
import httpx
+from inse.exceptions import (
+ ElasticsearchException,
+ ElasticsearchNotFoundException,
+ ElasticsearchConnectionException,
+ MissingApiKeyError,
+)
from inse.model import ESCluster, ESIndex
from .. import config
logger = logging.getLogger(__name__)
+_client: Optional[httpx.AsyncClient] = None
+_loop = None
+
+
+def get_client() -> httpx.AsyncClient:
+ global _client, _loop
+ try:
+ import asyncio
+ current_loop = asyncio.get_running_loop()
+ except RuntimeError:
+ current_loop = None
+
+ if _client is None or _loop is not current_loop:
+ _client = httpx.AsyncClient(timeout=httpx.Timeout(30.0))
+ _loop = current_loop
+ return _client
+
def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
"""Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration.
@@ -21,22 +45,23 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
Returns:
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
"""
-
+
if cluster == ESCluster.NES:
if (
not config.settings.elasticsearch_url
or not config.settings.elasticsearch_api_key
):
- raise ValueError(
+ raise MissingApiKeyError(
"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 == ESCluster.INSE:
if (
not config.settings.elasticsearch_inse_url
or not config.settings.elasticsearch_inse_api_key
):
- raise ValueError(
+ raise MissingApiKeyError(
"Elasticsearch INSE URL and API key must be set in the configuration for cluster 'inse'"
)
@@ -80,8 +105,18 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
return None
-def search(
- index: ESIndex | List[ESIndex],
+def _wrap_exception(e: Exception) -> Exception:
+ if isinstance(e, httpx.HTTPStatusError):
+ if e.response.status_code == 404:
+ return ElasticsearchNotFoundException(f"Elasticsearch resource not found: {e}")
+ return ElasticsearchException(f"Elasticsearch returned status {e.response.status_code}: {e}")
+ elif isinstance(e, httpx.RequestError):
+ return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}")
+ return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
+
+
+async def search(
+ index: ESIndex | List[ESIndex] | str | List[str],
query: Optional[Dict] = None,
source: Optional[List] = None,
size: Optional[int] = None,
@@ -112,10 +147,11 @@ def search(
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:
+ if isinstance(idx, ESIndex):
+ cluster_for_index = _index_to_cluster(idx)
+ if cluster_for_index is not None:
+ clusters.add(cluster_for_index)
+ elif isinstance(index, ESIndex):
cluster_for_index = _index_to_cluster(index)
if cluster_for_index is not None:
clusters.add(cluster_for_index)
@@ -156,24 +192,125 @@ def search(
"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} for {index} with payload: {json.dumps(payload)}"
- )
- if isinstance(index, list):
- index_str = ",".join(index)
- else:
- index_str = index
+ client = get_client()
+ logger.debug(
+ 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(str(idx) for idx in index)
+ else:
+ index_str = str(index)
- response = client.post(
+ try:
+ response = await client.post(
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
)
response.raise_for_status()
return response.json()
+ except Exception as exc:
+ raise _wrap_exception(exc) from exc
-def get(
- index: ESIndex,
+async def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str:
+ """Opens a point-in-time on the given index and returns its id."""
+ elasticsearch_url, api_key = _cluster_credentials(cluster)
+ headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
+
+ client = get_client()
+ try:
+ response = await client.post(
+ f"{elasticsearch_url}/{index}/_pit",
+ params={"keep_alive": keep_alive},
+ headers=headers,
+ )
+ response.raise_for_status()
+ return response.json()["id"]
+ except Exception as exc:
+ raise _wrap_exception(exc) from exc
+
+
+async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
+ """Closes a previously opened point-in-time."""
+ elasticsearch_url, api_key = _cluster_credentials(cluster)
+ headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
+
+ client = get_client()
+ try:
+ response = await client.request(
+ "DELETE",
+ f"{elasticsearch_url}/_pit",
+ json={"id": pit_id},
+ headers=headers,
+ )
+ response.raise_for_status()
+ except Exception as exc:
+ raise _wrap_exception(exc) from exc
+
+
+async def scan(
+ index: str,
+ query: Dict,
+ source: Optional[List] = None,
+ page_size: int = 1000,
+ keep_alive: str = "1m",
+ cluster: str = "nes",
+) -> AsyncIterator[Dict[str, Any]]:
+ """Yields every hit matching ``query`` using a point-in-time + ``search_after``.
+
+ Unlike ``from``/``size`` pagination, this is not bounded by
+ ``index.max_result_window``, so it can stream result sets larger than 10k.
+ """
+ elasticsearch_url, api_key = _cluster_credentials(cluster)
+ headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
+
+ pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster)
+ search_after: Optional[List] = None
+ try:
+ client = get_client()
+ while True:
+ payload: Dict[str, Any] = {
+ "size": page_size,
+ "query": query,
+ "pit": {"id": pit_id, "keep_alive": keep_alive},
+ "sort": [{"_shard_doc": "asc"}],
+ "track_total_hits": False,
+ }
+ if source is not None:
+ payload["_source"] = source
+ if search_after is not None:
+ payload["search_after"] = search_after
+
+ try:
+ response = await client.post(
+ f"{elasticsearch_url}/_search", json=payload, headers=headers
+ )
+ response.raise_for_status()
+ except Exception as exc:
+ raise _wrap_exception(exc) from exc
+
+ result = response.json()
+
+ hits = result.get("hits", {}).get("hits", [])
+ if not hits:
+ break
+
+ for hit in hits:
+ yield hit
+
+ # The pit id can be refreshed between requests; keep the latest.
+ pit_id = result.get("pit_id", pit_id)
+ search_after = hits[-1].get("sort")
+ if search_after is None or len(hits) < page_size:
+ break
+ finally:
+ try:
+ await close_point_in_time(pit_id, cluster=cluster)
+ except Exception:
+ logger.exception("Failed to close Elasticsearch point-in-time.")
+
+
+async def get(
+ index: ESIndex | str,
doc_id: str,
source: Optional[list] = None,
cluster: ESCluster = ESCluster.NES,
@@ -187,9 +324,56 @@ def get(
if source is not None:
params["_source_includes"] = ",".join(source)
- with httpx.Client() as client:
- response = client.get(
+ client = get_client()
+ try:
+ response = await client.get(
f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers
)
response.raise_for_status()
return response.json()
+ except Exception as exc:
+ raise _wrap_exception(exc) from exc
+
+
+async def update(
+ index: str,
+ doc_id: str,
+ doc: Dict[str, Any],
+ cluster: ESCluster = ESCluster.NES,
+) -> Dict[str, Any]:
+ elasticsearch_url, api_key = _cluster_credentials(cluster)
+ headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
+
+ client = get_client()
+ try:
+ response = await client.post(
+ f"{elasticsearch_url}/{index}/_update/{doc_id}",
+ json={"doc": doc},
+ headers=headers,
+ )
+ response.raise_for_status()
+ return response.json()
+ except Exception as exc:
+ raise _wrap_exception(exc) from exc
+
+
+async def index_doc(
+ index: str,
+ doc_id: str,
+ document: Dict[str, Any],
+ cluster: ESCluster = ESCluster.NES,
+) -> Dict[str, Any]:
+ elasticsearch_url, api_key = _cluster_credentials(cluster)
+ headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
+
+ client = get_client()
+ try:
+ response = await client.put(
+ f"{elasticsearch_url}/{index}/_doc/{doc_id}",
+ json=document,
+ headers=headers,
+ )
+ response.raise_for_status()
+ return response.json()
+ except Exception as exc:
+ raise _wrap_exception(exc) from exc
diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py
index 19e9dda3..bc3edcf6 100644
--- a/service/src/main/inse/logic.py
+++ b/service/src/main/inse/logic.py
@@ -18,6 +18,7 @@ import json
from . import schema
from . import model
from . import config
+from inse.integrations import elasticsearch
from inse.models.openalex.topic import Topic
@@ -103,56 +104,42 @@ def _load_topic_cache() -> dict:
return {}
-def build_topic_cache(page_size: int = 200, save_json: bool = True) -> dict:
+async def build_topic_cache(save_json: bool = True) -> dict:
"""
Fetch topics from the hosted OpenAlex topics index and build a lookup cache (scheduled task).
Arguments:
- page_size (int): Number of topics to fetch per request (default: 200)
save_json (bool): Whether to save the cache as a JSON file (default: True)
Returns:
taxonomy_cache (dict): The topic hierarchy dictionary.
"""
output_filename: str = "topic_hierarchy_cache.json"
- headers = {
- "Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
- "Content-Type": "application/json",
- }
taxonomy_cache = {}
- offset = 0
- with httpx.Client(timeout=30.0) as client:
- while True:
- payload = {"query": {"match_all": {}}, "from": offset, "size": page_size}
- response = client.post(
- config.settings.elasticsearch_url + "/openalex-topics/_search",
- json=payload,
- headers=headers,
- )
- response.raise_for_status()
- data = response.json()
+ try:
+ async for hit in elasticsearch.scan(
+ index="openalex-topics",
+ query={"match_all": {}},
+ source=["display_name", "name", "id", "subfield", "field", "domain"],
+ cluster="nes",
+ ):
+ source = hit.get("_source", {})
+ topic_name = source.get("display_name") or source.get("name")
+ if not topic_name:
+ continue
- hits = data.get("hits", {}).get("hits", [])
- if not hits:
- break
+ taxonomy_cache[topic_name] = {
+ "topic_id": source.get("id") or hit.get("_id", ""),
+ "subfield": source.get("subfield", {}).get("display_name", ""),
+ "field": source.get("field", {}).get("display_name", ""),
+ "domain": source.get("domain", {}).get("display_name", ""),
+ }
+ except Exception as exc:
+ logger.error("Failed to scan topics from Elasticsearch: %s", exc)
- for hit in hits:
- source = hit.get("_source", {})
- topic_name = source.get("display_name") or source.get("name")
- if not topic_name:
- continue
-
- taxonomy_cache[topic_name] = {
- "topic_id": source.get("id") or hit.get("_id", ""),
- "subfield": source.get("subfield", {}).get("display_name", ""),
- "field": source.get("field", {}).get("display_name", ""),
- "domain": source.get("domain", {}).get("display_name", ""),
- }
-
- offset += len(hits)
- logger.info("Processed %s topics total", len(taxonomy_cache))
+ logger.info("Processed %s topics total", len(taxonomy_cache))
if save_json:
data_json = json.dumps(taxonomy_cache, indent=2, ensure_ascii=True)
diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py
index 24c763de..3af016e5 100644
--- a/service/src/main/inse/main.py
+++ b/service/src/main/inse/main.py
@@ -14,7 +14,13 @@ from fastapi.responses import JSONResponse, RedirectResponse
from inse.collaboration_network.router import router as collaboration_network_router
from inse.company_connections.service import router as company_connections_router
-from inse.exceptions import NotFoundException
+from inse.exceptions import (
+ NotFoundException,
+ ElasticsearchException,
+ MissingApiKeyError,
+ UpstreamAPIException,
+ BadRequestException,
+)
from inse.funders.service import router as funders_service_router
from inse.projects.router import router as projects_router
from inse.university_ranking.router import router as university_ranking_router
@@ -34,6 +40,7 @@ from inse.institutions.router import router as institutions_router
from . import config
from .account.service import router as account_router
from .service import router as service_router
+from inse.patents.service import router as patents_service_router, patents_router as patents_all_router
logger = logging.getLogger(__name__)
@@ -61,6 +68,7 @@ app.include_router(account_router)
app.include_router(patents_service_router)
app.include_router(university_ranking_router)
app.include_router(projects_router)
+app.include_router(patents_all_router)
app.add_middleware(
ETagCacheMiddleware,
@@ -76,11 +84,37 @@ app.add_middleware(
)
+# exception handlers
+
@app.exception_handler(NotFoundException)
async def handle_not_found(request: Request, exc: NotFoundException):
return JSONResponse(status_code=404, content={"message": str(exc)})
+@app.exception_handler(ElasticsearchException)
+async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException):
+ logger.error("Elasticsearch integration error: %s", str(exc))
+ return JSONResponse(status_code=502, content={"message": "Search service temporarily unavailable"})
+
+
+@app.exception_handler(MissingApiKeyError)
+async def handle_missing_api_key(request: Request, exc: MissingApiKeyError):
+ logger.error("Configuration error: %s", str(exc))
+ return JSONResponse(status_code=503, content={"message": str(exc) or "Search service is not configured"})
+
+
+@app.exception_handler(UpstreamAPIException)
+async def handle_upstream_api_error(request: Request, exc: UpstreamAPIException):
+ logger.error("Upstream API error: %s", str(exc))
+ return JSONResponse(status_code=exc.status_code, content={"message": exc.message})
+
+
+@app.exception_handler(BadRequestException)
+async def handle_bad_request(request: Request, exc: BadRequestException):
+ logger.error("Bad Request: %s", str(exc))
+ return JSONResponse(status_code=400, content={"message": str(exc)})
+
+
@app.exception_handler(404)
async def redirect(_, __):
return RedirectResponse(url="/inse-webapp/")
diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py
index 98aaf28c..028d5eb7 100644
--- a/service/src/main/inse/model.py
+++ b/service/src/main/inse/model.py
@@ -55,10 +55,44 @@ class ESIndex(StrEnum):
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"
+
+ EPO_INDEX = "epo_index_1.0"
+ USPTO_INDEX = "uspto_patents_3.0"
PROJECTS_BUND_V1 = "projects_bund_v1"
- PROJECTS_DFG_ALL = "projects_dfg_all"
\ No newline at end of file
+ PROJECTS_DFG_ALL = "projects_dfg_all"
+
+ CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
+ CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
+ CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
+ CORDIS_EU_FP7_OGANIZATIONS = "cordis_eu_fp7_organizations"
+ # FP7
+ CORDIS_EU_FP7_ORGANIZATIONS = "cordis_eu_fp7_organizations"
+ CORDIS_EU_FP7_PUBLICATIONS = "cordis_eu_fp7_publications"
+ CORDIS_EU_FP7_PROJECT_IPRS = "cordis_eu_fp7_project_iprs"
+ CORDIS_EU_FP7_REPORT_SUMMARIES = "cordis_eu_fp7_report_summaries"
+ CORDIS_EU_FP7_TOPICS = "cordis_eu_fp7_topics"
+ CORDIS_EU_FP7_WEB_LINKS = "cordis_eu_fp7_web_links"
+ CORDIS_EU_FP7_EUROSCIVOC = "cordis_eu_fp7_euroscivoc"
+ CORDIS_EU_FP7_LEGAL_BASIS = "cordis_eu_fp7_legal_basis"
+
+ # Horizon 2020
+ CORDIS_EU_HORIZON_2020_ORGANIZATIONS = "cordis_eu_horizon_2020_organizations"
+ CORDIS_EU_HORIZON_2020_PUBLICATIONS = "cordis_eu_horizon_2020_publications"
+ CORDIS_EU_HORIZON_2020_DELIVERABLES = "cordis_eu_horizon_2020_deliverables"
+ CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES = "cordis_eu_horizon_2020_report_summaries"
+ CORDIS_EU_HORIZON_2020_TOPICS = "cordis_eu_horizon_2020_topics"
+ CORDIS_EU_HORIZON_2020_WEB_LINKS = "cordis_eu_horizon_2020_web_links"
+ CORDIS_EU_HORIZON_2020_EUROSCIVOC = "cordis_eu_horizon_2020_euroscivoc"
+ CORDIS_EU_HORIZON_2020_LEGAL_BASIS = "cordis_eu_horizon_2020_legal_basis"
+ CORDIS_EU_HORIZON_2020_ERC_PIS = "cordis_eu_horizon_2020_erc_pis"
+
+ # Horizon Europe
+ CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS = "cordis_eu_horizon_europe_organizations"
+ CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS = "cordis_eu_horizon_europe_publications"
+ CORDIS_EU_HORIZON_EUROPE_DELIVERABLES = "cordis_eu_horizon_europe_deliverables"
+ CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES = "cordis_eu_horizon_europe_report_summaries"
+ CORDIS_EU_HORIZON_EUROPE_TOPICS = "cordis_eu_horizon_europe_topics"
+ CORDIS_EU_HORIZON_EUROPE_WEB_LINKS = "cordis_eu_horizon_europe_web_links"
+ CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC = "cordis_eu_horizon_europe_euroscivoc"
+ CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS = "cordis_eu_horizon_europe_legal_basis"
\ No newline at end of file
diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_eurosci_voc.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_eurosci_voc.py
new file mode 100644
index 00000000..27e2cec2
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_eurosci_voc.py
@@ -0,0 +1,98 @@
+# coding: utf-8
+
+"""
+ CORDIS FP7 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class Fp7EurosciVoc(BaseModel):
+ """
+ Fp7EurosciVoc
+ """ # noqa: E501
+ code: Optional[StrictStr] = None
+ description: Optional[StrictStr] = None
+ id: Optional[StrictStr] = None
+ path: Optional[StrictStr] = None
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ title: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["code", "description", "id", "path", "projectID", "title"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of Fp7EurosciVoc from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of Fp7EurosciVoc from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "code": obj.get("code"),
+ "description": obj.get("description"),
+ "id": obj.get("id"),
+ "path": obj.get("path"),
+ "projectID": obj.get("projectID"),
+ "title": obj.get("title")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_legal_basis.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_legal_basis.py
new file mode 100644
index 00000000..b4868f44
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_legal_basis.py
@@ -0,0 +1,96 @@
+# coding: utf-8
+
+"""
+ CORDIS FP7 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class Fp7LegalBasis(BaseModel):
+ """
+ Fp7LegalBasis
+ """ # noqa: E501
+ id: Optional[StrictStr] = None
+ legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ title: Optional[StrictStr] = None
+ unique_programme_part: Optional[StrictStr] = Field(default=None, alias="uniqueProgrammePart")
+ __properties: ClassVar[List[str]] = ["id", "legalBasis", "projectID", "title", "uniqueProgrammePart"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of Fp7LegalBasis from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of Fp7LegalBasis from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "id": obj.get("id"),
+ "legalBasis": obj.get("legalBasis"),
+ "projectID": obj.get("projectID"),
+ "title": obj.get("title"),
+ "uniqueProgrammePart": obj.get("uniqueProgrammePart")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_organization.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_organization.py
new file mode 100644
index 00000000..07814631
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_organization.py
@@ -0,0 +1,139 @@
+# coding: utf-8
+
+"""
+ CORDIS FP7 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class Fp7Organization(BaseModel):
+ """
+ Fp7Organization
+ """ # noqa: E501
+ sme: Optional[StrictBool] = Field(default=None, alias="SME")
+ active: Optional[StrictBool] = None
+ activity_type: Optional[StrictStr] = Field(default=None, alias="activityType")
+ city: Optional[StrictStr] = None
+ contact_form: Optional[StrictStr] = Field(default=None, alias="contactForm")
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ country: Optional[StrictStr] = None
+ ec_contribution: Optional[StrictFloat] = Field(default=None, alias="ecContribution")
+ end_of_participation: Optional[StrictBool] = Field(default=None, alias="endOfParticipation")
+ geolocation: Optional[StrictStr] = None
+ id: Optional[StrictStr] = None
+ name: Optional[StrictStr] = None
+ net_ec_contribution: Optional[StrictFloat] = Field(default=None, alias="netEcContribution")
+ nuts_code: Optional[StrictStr] = Field(default=None, alias="nutsCode")
+ order: Optional[StrictInt] = None
+ organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID")
+ organization_url: Optional[StrictStr] = Field(default=None, alias="organizationURL")
+ post_code: Optional[StrictStr] = Field(default=None, alias="postCode")
+ project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ rcn: Optional[StrictStr] = None
+ role: Optional[StrictStr] = None
+ short_name: Optional[StrictStr] = Field(default=None, alias="shortName")
+ street: Optional[StrictStr] = None
+ total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
+ vat_number: Optional[StrictStr] = Field(default=None, alias="vatNumber")
+ __properties: ClassVar[List[str]] = ["SME", "active", "activityType", "city", "contactForm", "contentUpdateDate", "country", "ecContribution", "endOfParticipation", "geolocation", "id", "name", "netEcContribution", "nutsCode", "order", "organisationID", "organizationURL", "postCode", "projectAcronym", "projectID", "rcn", "role", "shortName", "street", "totalCost", "vatNumber"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of Fp7Organization from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of Fp7Organization from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "SME": obj.get("SME"),
+ "active": obj.get("active"),
+ "activityType": obj.get("activityType"),
+ "city": obj.get("city"),
+ "contactForm": obj.get("contactForm"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "country": obj.get("country"),
+ "ecContribution": obj.get("ecContribution"),
+ "endOfParticipation": obj.get("endOfParticipation"),
+ "geolocation": obj.get("geolocation"),
+ "id": obj.get("id"),
+ "name": obj.get("name"),
+ "netEcContribution": obj.get("netEcContribution"),
+ "nutsCode": obj.get("nutsCode"),
+ "order": obj.get("order"),
+ "organisationID": obj.get("organisationID"),
+ "organizationURL": obj.get("organizationURL"),
+ "postCode": obj.get("postCode"),
+ "projectAcronym": obj.get("projectAcronym"),
+ "projectID": obj.get("projectID"),
+ "rcn": obj.get("rcn"),
+ "role": obj.get("role"),
+ "shortName": obj.get("shortName"),
+ "street": obj.get("street"),
+ "totalCost": obj.get("totalCost"),
+ "vatNumber": obj.get("vatNumber")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project.py
new file mode 100644
index 00000000..ca53bf13
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project.py
@@ -0,0 +1,131 @@
+# coding: utf-8
+
+"""
+ CORDIS FP7 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import date, datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class Fp7Project(BaseModel):
+ """
+ Fp7Project
+ """ # noqa: E501
+ acronym: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ ec_max_contribution: Optional[StrictFloat] = Field(default=None, alias="ecMaxContribution")
+ ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate")
+ end_date: Optional[date] = Field(default=None, alias="endDate")
+ framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme")
+ funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
+ grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi")
+ human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated")
+ id: Optional[StrictStr] = None
+ keywords: Optional[StrictStr] = None
+ legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
+ master_call: Optional[StrictStr] = Field(default=None, alias="masterCall")
+ nature: Optional[StrictStr] = None
+ objective: Optional[StrictStr] = None
+ rcn: Optional[StrictStr] = None
+ start_date: Optional[date] = Field(default=None, alias="startDate")
+ status: Optional[StrictStr] = None
+ sub_call: Optional[StrictStr] = Field(default=None, alias="subCall")
+ title: Optional[StrictStr] = None
+ topics: Optional[StrictStr] = None
+ total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
+ __properties: ClassVar[List[str]] = ["acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate", "endDate", "frameworkProgramme", "fundingScheme", "grantDoi", "humanValidated", "id", "keywords", "legalBasis", "masterCall", "nature", "objective", "rcn", "startDate", "status", "subCall", "title", "topics", "totalCost"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of Fp7Project from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of Fp7Project from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "acronym": obj.get("acronym"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "ecMaxContribution": obj.get("ecMaxContribution"),
+ "ecSignatureDate": obj.get("ecSignatureDate"),
+ "endDate": obj.get("endDate"),
+ "frameworkProgramme": obj.get("frameworkProgramme"),
+ "fundingScheme": obj.get("fundingScheme"),
+ "grantDoi": obj.get("grantDoi"),
+ "humanValidated": obj.get("humanValidated"),
+ "id": obj.get("id"),
+ "keywords": obj.get("keywords"),
+ "legalBasis": obj.get("legalBasis"),
+ "masterCall": obj.get("masterCall"),
+ "nature": obj.get("nature"),
+ "objective": obj.get("objective"),
+ "rcn": obj.get("rcn"),
+ "startDate": obj.get("startDate"),
+ "status": obj.get("status"),
+ "subCall": obj.get("subCall"),
+ "title": obj.get("title"),
+ "topics": obj.get("topics"),
+ "totalCost": obj.get("totalCost")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_details.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_details.py
new file mode 100644
index 00000000..0f3864f2
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_details.py
@@ -0,0 +1,214 @@
+# coding: utf-8
+
+"""
+ CORDIS FP7 Multi-Index API - Extended Models
+""" # noqa: E501
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+from datetime import date, datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+# Import all the base models
+from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project
+from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization
+from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication
+from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR
+from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary
+from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic
+from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink
+from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc
+from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis
+
+
+class Fp7ProjectDetails(BaseModel):
+ """
+ Comprehensive FP7 Project model combining all related entities.
+ This model extends the base Fp7Project with all associated data.
+ """
+ # Project core information (flattened from Fp7Project)
+ acronym: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ ec_max_contribution: Optional[StrictFloat] = Field(default=None, alias="ecMaxContribution")
+ ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate")
+ end_date: Optional[date] = Field(default=None, alias="endDate")
+ framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme")
+ funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
+ grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi")
+ human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated")
+ id: Optional[StrictStr] = None
+ keywords: Optional[StrictStr] = None
+ legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
+ master_call: Optional[StrictStr] = Field(default=None, alias="masterCall")
+ nature: Optional[StrictStr] = None
+ objective: Optional[StrictStr] = None
+ rcn: Optional[StrictStr] = None
+ start_date: Optional[date] = Field(default=None, alias="startDate")
+ status: Optional[StrictStr] = None
+ sub_call: Optional[StrictStr] = Field(default=None, alias="subCall")
+ title: Optional[StrictStr] = None
+ topics: Optional[StrictStr] = None
+ total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
+
+ # Related entities (collections)
+ organizations: Optional[List[Fp7Organization]] = Field(default=None, description="Organizations participating in the project")
+ publications: Optional[List[Fp7Publication]] = Field(default=None, description="Publications related to the project")
+ iprs: Optional[List[Fp7ProjectIPR]] = Field(default=None, description="Intellectual Property Rights related to the project")
+ report_summaries: Optional[List[Fp7ReportSummary]] = Field(default=None, description="Report summaries for the project")
+ topics_list: Optional[List[Fp7Topic]] = Field(default=None, alias="topicsList", description="Topics associated with the project")
+ web_links: Optional[List[Fp7WebLink]] = Field(default=None, description="Web links related to the project")
+ eurosci_voc: Optional[List[Fp7EurosciVoc]] = Field(default=None, alias="eurosciVoc", description="EuroSciVoc classifications")
+ legal_basis_list: Optional[List[Fp7LegalBasis]] = Field(default=None, alias="legalBasisList", description="Legal basis information")
+
+ # Project statistics (aggregated)
+ organization_count: Optional[int] = Field(default=None, alias="organizationCount")
+ publication_count: Optional[int] = Field(default=None, alias="publicationCount")
+ ipr_count: Optional[int] = Field(default=None, alias="iprCount")
+
+ __properties: ClassVar[List[str]] = [
+ "acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
+ "endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
+ "humanValidated", "id", "keywords", "legalBasis", "masterCall",
+ "nature", "objective", "rcn", "startDate", "status", "subCall",
+ "title", "topics", "totalCost",
+ "organizations", "publications", "iprs", "reportSummaries",
+ "topicsList", "webLinks", "eurosciVoc", "legalBasisList",
+ "organizationCount", "publicationCount", "iprCount"
+ ]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ populate_by_name=True,
+ )
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of Fp7ProjectDetailed from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias."""
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of Fp7ProjectDetailed from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ # Project core fields
+ "acronym": obj.get("acronym"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "ecMaxContribution": obj.get("ecMaxContribution"),
+ "ecSignatureDate": obj.get("ecSignatureDate"),
+ "endDate": obj.get("endDate"),
+ "frameworkProgramme": obj.get("frameworkProgramme"),
+ "fundingScheme": obj.get("fundingScheme"),
+ "grantDoi": obj.get("grantDoi"),
+ "humanValidated": obj.get("humanValidated"),
+ "id": obj.get("id"),
+ "keywords": obj.get("keywords"),
+ "legalBasis": obj.get("legalBasis"),
+ "masterCall": obj.get("masterCall"),
+ "nature": obj.get("nature"),
+ "objective": obj.get("objective"),
+ "rcn": obj.get("rcn"),
+ "startDate": obj.get("startDate"),
+ "status": obj.get("status"),
+ "subCall": obj.get("subCall"),
+ "title": obj.get("title"),
+ "topics": obj.get("topics"),
+ "totalCost": obj.get("totalCost"),
+
+ # Related entities
+ "organizations": [Fp7Organization.from_dict(org) for org in obj.get("organizations", [])] if obj.get("organizations") else None,
+ "publications": [Fp7Publication.from_dict(pub) for pub in obj.get("publications", [])] if obj.get("publications") else None,
+ "iprs": [Fp7ProjectIPR.from_dict(ipr) for ipr in obj.get("iprs", [])] if obj.get("iprs") else None,
+ "reportSummaries": [Fp7ReportSummary.from_dict(report) for report in obj.get("reportSummaries", [])] if obj.get("reportSummaries") else None,
+ "topicsList": [Fp7Topic.from_dict(topic) for topic in obj.get("topicsList", [])] if obj.get("topicsList") else None,
+ "webLinks": [Fp7WebLink.from_dict(link) for link in obj.get("webLinks", [])] if obj.get("webLinks") else None,
+ "eurosciVoc": [Fp7EurosciVoc.from_dict(voc) for voc in obj.get("eurosciVoc", [])] if obj.get("eurosciVoc") else None,
+ "legalBasisList": [Fp7LegalBasis.from_dict(lb) for lb in obj.get("legalBasisList", [])] if obj.get("legalBasisList") else None,
+
+ # Statistics
+ "organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0,
+ "publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0,
+ "iprCount": len(obj.get("iprs", [])) if obj.get("iprs") else 0,
+ })
+ return _obj
+
+ @classmethod
+ def from_project_with_relations(
+ cls,
+ project: Fp7Project,
+ organizations: Optional[List[Fp7Organization]] = None,
+ publications: Optional[List[Fp7Publication]] = None,
+ iprs: Optional[List[Fp7ProjectIPR]] = None,
+ report_summaries: Optional[List[Fp7ReportSummary]] = None,
+ topics_list: Optional[List[Fp7Topic]] = None,
+ web_links: Optional[List[Fp7WebLink]] = None,
+ eurosci_voc: Optional[List[Fp7EurosciVoc]] = None,
+ legal_basis_list: Optional[List[Fp7LegalBasis]] = None,
+ ) -> Self:
+ """
+ Factory method to create a detailed project from a base project and its relations.
+
+ Args:
+ project: The base Fp7Project object
+ organizations: List of organizations participating in the project
+ publications: List of publications related to the project
+ iprs: List of IPRs related to the project
+ report_summaries: List of report summaries
+ topics_list: List of topics associated with the project
+ web_links: List of web links
+ eurosci_voc: List of EuroSciVoc classifications
+ legal_basis_list: List of legal basis information
+
+ Returns:
+ Fp7ProjectDetailed instance
+ """
+ project_dict = project.to_dict() if project else {}
+
+ return cls(
+ **project_dict,
+ organizations=organizations or [],
+ publications=publications or [],
+ iprs=iprs or [],
+ reportSummaries=report_summaries or [],
+ topicsList=topics_list or [],
+ webLinks=web_links or [],
+ eurosciVoc=eurosci_voc or [],
+ legalBasisList=legal_basis_list or [],
+ organizationCount=len(organizations) if organizations else 0,
+ publicationCount=len(publications) if publications else 0,
+ iprCount=len(iprs) if iprs else 0,
+ )
\ No newline at end of file
diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_ipr.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_ipr.py
new file mode 100644
index 00000000..cfbdd89b
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_ipr.py
@@ -0,0 +1,125 @@
+# coding: utf-8
+
+"""
+ CORDIS FP7 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import date
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class Fp7ProjectIPR(BaseModel):
+ """
+ Fp7ProjectIPR
+ """ # noqa: E501
+ applicant_name: Optional[StrictStr] = Field(default=None, alias="applicantName")
+ application_date: Optional[date] = Field(default=None, alias="applicationDate")
+ application_identifier: Optional[StrictStr] = Field(default=None, alias="applicationIdentifier")
+ application_kind: Optional[StrictStr] = Field(default=None, alias="applicationKind")
+ application_prefix: Optional[StrictStr] = Field(default=None, alias="applicationPrefix")
+ award_date: Optional[date] = Field(default=None, alias="awardDate")
+ award_identifier: Optional[StrictStr] = Field(default=None, alias="awardIdentifier")
+ award_kind: Optional[StrictStr] = Field(default=None, alias="awardKind")
+ award_prefix: Optional[StrictStr] = Field(default=None, alias="awardPrefix")
+ epo_app_url: Optional[StrictStr] = Field(default=None, alias="epoAppUrl")
+ epo_pub_url: Optional[StrictStr] = Field(default=None, alias="epoPubUrl")
+ id: Optional[StrictStr] = None
+ organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID")
+ patent_family_identifier: Optional[StrictStr] = Field(default=None, alias="patentFamilyIdentifier")
+ patent_type: Optional[StrictStr] = Field(default=None, alias="patentType")
+ priority_date: Optional[date] = Field(default=None, alias="priorityDate")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ title: Optional[StrictStr] = None
+ type: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["applicantName", "applicationDate", "applicationIdentifier", "applicationKind", "applicationPrefix", "awardDate", "awardIdentifier", "awardKind", "awardPrefix", "epoAppUrl", "epoPubUrl", "id", "organisationID", "patentFamilyIdentifier", "patentType", "priorityDate", "projectID", "title", "type"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of Fp7ProjectIPR from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of Fp7ProjectIPR from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "applicantName": obj.get("applicantName"),
+ "applicationDate": obj.get("applicationDate"),
+ "applicationIdentifier": obj.get("applicationIdentifier"),
+ "applicationKind": obj.get("applicationKind"),
+ "applicationPrefix": obj.get("applicationPrefix"),
+ "awardDate": obj.get("awardDate"),
+ "awardIdentifier": obj.get("awardIdentifier"),
+ "awardKind": obj.get("awardKind"),
+ "awardPrefix": obj.get("awardPrefix"),
+ "epoAppUrl": obj.get("epoAppUrl"),
+ "epoPubUrl": obj.get("epoPubUrl"),
+ "id": obj.get("id"),
+ "organisationID": obj.get("organisationID"),
+ "patentFamilyIdentifier": obj.get("patentFamilyIdentifier"),
+ "patentType": obj.get("patentType"),
+ "priorityDate": obj.get("priorityDate"),
+ "projectID": obj.get("projectID"),
+ "title": obj.get("title"),
+ "type": obj.get("type")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_publication.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_publication.py
new file mode 100644
index 00000000..2e9ab1ff
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_publication.py
@@ -0,0 +1,123 @@
+# coding: utf-8
+
+"""
+ CORDIS FP7 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class Fp7Publication(BaseModel):
+ """
+ Fp7Publication
+ """ # noqa: E501
+ authors: Optional[StrictStr] = None
+ collection: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ doi: Optional[StrictStr] = None
+ id: Optional[StrictStr] = None
+ is_published_as: Optional[StrictStr] = Field(default=None, alias="isPublishedAs")
+ journal_number: Optional[StrictStr] = Field(default=None, alias="journalNumber")
+ journal_title: Optional[StrictStr] = Field(default=None, alias="journalTitle")
+ project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ published_pages: Optional[StrictStr] = Field(default=None, alias="publishedPages")
+ published_year: Optional[StrictInt] = Field(default=None, alias="publishedYear")
+ publisher: Optional[StrictStr] = None
+ qa_processed_doi: Optional[StrictStr] = Field(default=None, alias="qaProcessedDoi")
+ rcn: Optional[StrictStr] = None
+ repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl")
+ title: Optional[StrictStr] = None
+ volume: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of Fp7Publication from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of Fp7Publication from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "authors": obj.get("authors"),
+ "collection": obj.get("collection"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "doi": obj.get("doi"),
+ "id": obj.get("id"),
+ "isPublishedAs": obj.get("isPublishedAs"),
+ "journalNumber": obj.get("journalNumber"),
+ "journalTitle": obj.get("journalTitle"),
+ "projectAcronym": obj.get("projectAcronym"),
+ "projectID": obj.get("projectID"),
+ "publishedPages": obj.get("publishedPages"),
+ "publishedYear": obj.get("publishedYear"),
+ "publisher": obj.get("publisher"),
+ "qaProcessedDoi": obj.get("qaProcessedDoi"),
+ "rcn": obj.get("rcn"),
+ "repositoryUrl": obj.get("repositoryUrl"),
+ "title": obj.get("title"),
+ "volume": obj.get("volume")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_report_summary.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_report_summary.py
new file mode 100644
index 00000000..43ce8910
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_report_summary.py
@@ -0,0 +1,101 @@
+# coding: utf-8
+
+"""
+ CORDIS FP7 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class Fp7ReportSummary(BaseModel):
+ """
+ Fp7ReportSummary
+ """ # noqa: E501
+ attachments: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ id: Optional[StrictStr] = None
+ project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ rcn: Optional[StrictStr] = None
+ title: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["attachments", "contentUpdateDate", "id", "projectAcronym", "projectID", "rcn", "title"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of Fp7ReportSummary from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of Fp7ReportSummary from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "attachments": obj.get("attachments"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "id": obj.get("id"),
+ "projectAcronym": obj.get("projectAcronym"),
+ "projectID": obj.get("projectID"),
+ "rcn": obj.get("rcn"),
+ "title": obj.get("title")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_topic.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_topic.py
new file mode 100644
index 00000000..27a59a47
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_topic.py
@@ -0,0 +1,94 @@
+# coding: utf-8
+
+"""
+ CORDIS FP7 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class Fp7Topic(BaseModel):
+ """
+ Fp7Topic
+ """ # noqa: E501
+ id: Optional[StrictStr] = None
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ title: Optional[StrictStr] = None
+ topic: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["id", "projectID", "title", "topic"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of Fp7Topic from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of Fp7Topic from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "id": obj.get("id"),
+ "projectID": obj.get("projectID"),
+ "title": obj.get("title"),
+ "topic": obj.get("topic")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_web_link.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_web_link.py
new file mode 100644
index 00000000..6898b07f
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_web_link.py
@@ -0,0 +1,107 @@
+# coding: utf-8
+
+"""
+ CORDIS FP7 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class Fp7WebLink(BaseModel):
+ """
+ Fp7WebLink
+ """ # noqa: E501
+ archived_date: Optional[datetime] = Field(default=None, alias="archivedDate")
+ available_languages: Optional[StrictStr] = Field(default=None, alias="availableLanguages")
+ id: Optional[StrictStr] = None
+ link_id: Optional[StrictStr] = Field(default=None, alias="linkId")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ represents: Optional[StrictStr] = None
+ source: Optional[StrictStr] = None
+ status: Optional[StrictStr] = None
+ type: Optional[StrictStr] = None
+ url: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["archivedDate", "availableLanguages", "id", "linkId", "projectID", "represents", "source", "status", "type", "url"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of Fp7WebLink from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of Fp7WebLink from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "archivedDate": obj.get("archivedDate"),
+ "availableLanguages": obj.get("availableLanguages"),
+ "id": obj.get("id"),
+ "linkId": obj.get("linkId"),
+ "projectID": obj.get("projectID"),
+ "represents": obj.get("represents"),
+ "source": obj.get("source"),
+ "status": obj.get("status"),
+ "type": obj.get("type"),
+ "url": obj.get("url")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_deliverable.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_deliverable.py
new file mode 100644
index 00000000..29166ca3
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_deliverable.py
@@ -0,0 +1,103 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon 2020 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class H2020Deliverable(BaseModel):
+ """
+ H2020Deliverable
+ """ # noqa: E501
+ collection: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ deliverable_type: Optional[StrictStr] = Field(default=None, alias="deliverableType")
+ description: Optional[StrictStr] = None
+ project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ rcn: Optional[StrictStr] = None
+ url: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["collection", "contentUpdateDate", "deliverableType", "description", "projectAcronym", "projectID", "rcn", "url"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of H2020Deliverable from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of H2020Deliverable from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "collection": obj.get("collection"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "deliverableType": obj.get("deliverableType"),
+ "description": obj.get("description"),
+ "projectAcronym": obj.get("projectAcronym"),
+ "projectID": obj.get("projectID"),
+ "rcn": obj.get("rcn"),
+ "url": obj.get("url")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_erc_pi.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_erc_pi.py
new file mode 100644
index 00000000..b16ed4d0
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_erc_pi.py
@@ -0,0 +1,102 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon 2020 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class H2020ErcPI(BaseModel):
+ """
+ H2020ErcPI
+ """ # noqa: E501
+ first_name: Optional[StrictStr] = Field(default=None, alias="firstName")
+ funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
+ id: Optional[StrictStr] = None
+ last_name: Optional[StrictStr] = Field(default=None, alias="lastName")
+ organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID")
+ project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ title: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["firstName", "fundingScheme", "id", "lastName", "organisationID", "projectAcronym", "projectID", "title"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of H2020ErcPI from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of H2020ErcPI from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "firstName": obj.get("firstName"),
+ "fundingScheme": obj.get("fundingScheme"),
+ "id": obj.get("id"),
+ "lastName": obj.get("lastName"),
+ "organisationID": obj.get("organisationID"),
+ "projectAcronym": obj.get("projectAcronym"),
+ "projectID": obj.get("projectID"),
+ "title": obj.get("title")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_eurosci_voc.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_eurosci_voc.py
new file mode 100644
index 00000000..f6227b6c
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_eurosci_voc.py
@@ -0,0 +1,98 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon 2020 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class H2020EurosciVoc(BaseModel):
+ """
+ H2020EurosciVoc
+ """ # noqa: E501
+ code: Optional[StrictStr] = None
+ description: Optional[StrictStr] = None
+ id: Optional[StrictStr] = None
+ path: Optional[StrictStr] = None
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ title: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["code", "description", "id", "path", "projectID", "title"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of H2020EurosciVoc from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of H2020EurosciVoc from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "code": obj.get("code"),
+ "description": obj.get("description"),
+ "id": obj.get("id"),
+ "path": obj.get("path"),
+ "projectID": obj.get("projectID"),
+ "title": obj.get("title")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_legal_basis.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_legal_basis.py
new file mode 100644
index 00000000..43327f68
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_legal_basis.py
@@ -0,0 +1,96 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon 2020 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class H2020LegalBasis(BaseModel):
+ """
+ H2020LegalBasis
+ """ # noqa: E501
+ id: Optional[StrictStr] = None
+ legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ title: Optional[StrictStr] = None
+ unique_programme_part: Optional[StrictStr] = Field(default=None, alias="uniqueProgrammePart")
+ __properties: ClassVar[List[str]] = ["id", "legalBasis", "projectID", "title", "uniqueProgrammePart"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of H2020LegalBasis from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of H2020LegalBasis from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "id": obj.get("id"),
+ "legalBasis": obj.get("legalBasis"),
+ "projectID": obj.get("projectID"),
+ "title": obj.get("title"),
+ "uniqueProgrammePart": obj.get("uniqueProgrammePart")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_organization.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_organization.py
new file mode 100644
index 00000000..ed63c1a0
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_organization.py
@@ -0,0 +1,139 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon 2020 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class H2020Organization(BaseModel):
+ """
+ H2020Organization
+ """ # noqa: E501
+ sme: Optional[StrictBool] = Field(default=None, alias="SME")
+ active: Optional[StrictBool] = None
+ activity_type: Optional[StrictStr] = Field(default=None, alias="activityType")
+ city: Optional[StrictStr] = None
+ contact_form: Optional[StrictStr] = Field(default=None, alias="contactForm")
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ country: Optional[StrictStr] = None
+ ec_contribution: Optional[StrictFloat] = Field(default=None, alias="ecContribution")
+ end_of_participation: Optional[StrictBool] = Field(default=None, alias="endOfParticipation")
+ geolocation: Optional[StrictStr] = None
+ id: Optional[StrictStr] = None
+ name: Optional[StrictStr] = None
+ net_ec_contribution: Optional[StrictFloat] = Field(default=None, alias="netEcContribution")
+ nuts_code: Optional[StrictStr] = Field(default=None, alias="nutsCode")
+ order: Optional[StrictInt] = None
+ organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID")
+ organization_url: Optional[StrictStr] = Field(default=None, alias="organizationURL")
+ post_code: Optional[StrictStr] = Field(default=None, alias="postCode")
+ project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ rcn: Optional[StrictStr] = None
+ role: Optional[StrictStr] = None
+ short_name: Optional[StrictStr] = Field(default=None, alias="shortName")
+ street: Optional[StrictStr] = None
+ total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
+ vat_number: Optional[StrictStr] = Field(default=None, alias="vatNumber")
+ __properties: ClassVar[List[str]] = ["SME", "active", "activityType", "city", "contactForm", "contentUpdateDate", "country", "ecContribution", "endOfParticipation", "geolocation", "id", "name", "netEcContribution", "nutsCode", "order", "organisationID", "organizationURL", "postCode", "projectAcronym", "projectID", "rcn", "role", "shortName", "street", "totalCost", "vatNumber"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of H2020Organization from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of H2020Organization from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "SME": obj.get("SME"),
+ "active": obj.get("active"),
+ "activityType": obj.get("activityType"),
+ "city": obj.get("city"),
+ "contactForm": obj.get("contactForm"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "country": obj.get("country"),
+ "ecContribution": obj.get("ecContribution"),
+ "endOfParticipation": obj.get("endOfParticipation"),
+ "geolocation": obj.get("geolocation"),
+ "id": obj.get("id"),
+ "name": obj.get("name"),
+ "netEcContribution": obj.get("netEcContribution"),
+ "nutsCode": obj.get("nutsCode"),
+ "order": obj.get("order"),
+ "organisationID": obj.get("organisationID"),
+ "organizationURL": obj.get("organizationURL"),
+ "postCode": obj.get("postCode"),
+ "projectAcronym": obj.get("projectAcronym"),
+ "projectID": obj.get("projectID"),
+ "rcn": obj.get("rcn"),
+ "role": obj.get("role"),
+ "shortName": obj.get("shortName"),
+ "street": obj.get("street"),
+ "totalCost": obj.get("totalCost"),
+ "vatNumber": obj.get("vatNumber")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project.py
new file mode 100644
index 00000000..c12b16ec
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project.py
@@ -0,0 +1,131 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon 2020 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import date, datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class H2020Project(BaseModel):
+ """
+ H2020Project
+ """ # noqa: E501
+ acronym: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ ec_max_contribution: Optional[StrictFloat] = Field(default=None, alias="ecMaxContribution")
+ ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate")
+ end_date: Optional[date] = Field(default=None, alias="endDate")
+ framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme")
+ funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
+ grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi")
+ human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated")
+ id: Optional[StrictStr] = None
+ keywords: Optional[StrictStr] = None
+ legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
+ master_call: Optional[StrictStr] = Field(default=None, alias="masterCall")
+ nature: Optional[StrictStr] = None
+ objective: Optional[StrictStr] = None
+ rcn: Optional[StrictStr] = None
+ start_date: Optional[date] = Field(default=None, alias="startDate")
+ status: Optional[StrictStr] = None
+ sub_call: Optional[StrictStr] = Field(default=None, alias="subCall")
+ title: Optional[StrictStr] = None
+ topics: Optional[StrictStr] = None
+ total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
+ __properties: ClassVar[List[str]] = ["acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate", "endDate", "frameworkProgramme", "fundingScheme", "grantDoi", "humanValidated", "id", "keywords", "legalBasis", "masterCall", "nature", "objective", "rcn", "startDate", "status", "subCall", "title", "topics", "totalCost"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of H2020Project from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of H2020Project from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "acronym": obj.get("acronym"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "ecMaxContribution": obj.get("ecMaxContribution"),
+ "ecSignatureDate": obj.get("ecSignatureDate"),
+ "endDate": obj.get("endDate"),
+ "frameworkProgramme": obj.get("frameworkProgramme"),
+ "fundingScheme": obj.get("fundingScheme"),
+ "grantDoi": obj.get("grantDoi"),
+ "humanValidated": obj.get("humanValidated"),
+ "id": obj.get("id"),
+ "keywords": obj.get("keywords"),
+ "legalBasis": obj.get("legalBasis"),
+ "masterCall": obj.get("masterCall"),
+ "nature": obj.get("nature"),
+ "objective": obj.get("objective"),
+ "rcn": obj.get("rcn"),
+ "startDate": obj.get("startDate"),
+ "status": obj.get("status"),
+ "subCall": obj.get("subCall"),
+ "title": obj.get("title"),
+ "topics": obj.get("topics"),
+ "totalCost": obj.get("totalCost")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project_details.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project_details.py
new file mode 100644
index 00000000..0c57f008
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project_details.py
@@ -0,0 +1,224 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon 2020 Multi-Index API - Extended Models
+""" # noqa: E501
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+from datetime import date, datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+# Import all the base models
+from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project
+from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization
+from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication
+from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable
+from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary
+from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic
+from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink
+from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc
+from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis
+from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI
+
+
+class H2020ProjectDetails(BaseModel):
+ """
+ Comprehensive Horizon 2020 Project model combining all related entities.
+ This model extends the base H2020Project with all associated data.
+ """
+ # Project core information (flattened from H2020Project)
+ acronym: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ ec_max_contribution: Optional[StrictFloat] = Field(default=None, alias="ecMaxContribution")
+ ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate")
+ end_date: Optional[date] = Field(default=None, alias="endDate")
+ framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme")
+ funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
+ grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi")
+ human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated")
+ id: Optional[StrictStr] = None
+ keywords: Optional[StrictStr] = None
+ legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
+ master_call: Optional[StrictStr] = Field(default=None, alias="masterCall")
+ nature: Optional[StrictStr] = None
+ objective: Optional[StrictStr] = None
+ rcn: Optional[StrictStr] = None
+ start_date: Optional[date] = Field(default=None, alias="startDate")
+ status: Optional[StrictStr] = None
+ sub_call: Optional[StrictStr] = Field(default=None, alias="subCall")
+ title: Optional[StrictStr] = None
+ topics: Optional[StrictStr] = None
+ total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
+
+ # Related entities (collections)
+ organizations: Optional[List[H2020Organization]] = Field(default=None, description="Organizations participating in the project")
+ publications: Optional[List[H2020Publication]] = Field(default=None, description="Publications related to the project")
+ deliverables: Optional[List[H2020Deliverable]] = Field(default=None, description="Deliverables of the project")
+ report_summaries: Optional[List[H2020ReportSummary]] = Field(default=None, alias="reportSummaries", description="Report summaries for the project")
+ topics_list: Optional[List[H2020Topic]] = Field(default=None, alias="topicsList", description="Topics associated with the project")
+ web_links: Optional[List[H2020WebLink]] = Field(default=None, alias="webLinks", description="Web links related to the project")
+ eurosci_voc: Optional[List[H2020EurosciVoc]] = Field(default=None, alias="eurosciVoc", description="EuroSciVoc classifications")
+ legal_basis_list: Optional[List[H2020LegalBasis]] = Field(default=None, alias="legalBasisList", description="Legal basis information")
+ erc_principal_investigators: Optional[List[H2020ErcPI]] = Field(default=None, alias="ercPrincipalInvestigators", description="ERC Principal Investigators (specific to H2020)")
+
+ # Project statistics (aggregated)
+ organization_count: Optional[int] = Field(default=None, alias="organizationCount")
+ publication_count: Optional[int] = Field(default=None, alias="publicationCount")
+ deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount")
+ erc_pi_count: Optional[int] = Field(default=None, alias="ercPiCount")
+
+ __properties: ClassVar[List[str]] = [
+ "acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
+ "endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
+ "humanValidated", "id", "keywords", "legalBasis", "masterCall",
+ "nature", "objective", "rcn", "startDate", "status", "subCall",
+ "title", "topics", "totalCost",
+ "organizations", "publications", "deliverables", "reportSummaries",
+ "topicsList", "webLinks", "eurosciVoc", "legalBasisList",
+ "ercPrincipalInvestigators",
+ "organizationCount", "publicationCount", "deliverableCount", "ercPiCount"
+ ]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ populate_by_name=True,
+ )
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of H2020ProjectDetailed from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias."""
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of H2020ProjectDetailed from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ # Project core fields
+ "acronym": obj.get("acronym"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "ecMaxContribution": obj.get("ecMaxContribution"),
+ "ecSignatureDate": obj.get("ecSignatureDate"),
+ "endDate": obj.get("endDate"),
+ "frameworkProgramme": obj.get("frameworkProgramme"),
+ "fundingScheme": obj.get("fundingScheme"),
+ "grantDoi": obj.get("grantDoi"),
+ "humanValidated": obj.get("humanValidated"),
+ "id": obj.get("id"),
+ "keywords": obj.get("keywords"),
+ "legalBasis": obj.get("legalBasis"),
+ "masterCall": obj.get("masterCall"),
+ "nature": obj.get("nature"),
+ "objective": obj.get("objective"),
+ "rcn": obj.get("rcn"),
+ "startDate": obj.get("startDate"),
+ "status": obj.get("status"),
+ "subCall": obj.get("subCall"),
+ "title": obj.get("title"),
+ "topics": obj.get("topics"),
+ "totalCost": obj.get("totalCost"),
+
+ # Related entities
+ "organizations": [H2020Organization.from_dict(org) for org in obj.get("organizations", [])] if obj.get("organizations") else None,
+ "publications": [H2020Publication.from_dict(pub) for pub in obj.get("publications", [])] if obj.get("publications") else None,
+ "deliverables": [H2020Deliverable.from_dict(deliv) for deliv in obj.get("deliverables", [])] if obj.get("deliverables") else None,
+ "reportSummaries": [H2020ReportSummary.from_dict(report) for report in obj.get("reportSummaries", [])] if obj.get("reportSummaries") else None,
+ "topicsList": [H2020Topic.from_dict(topic) for topic in obj.get("topicsList", [])] if obj.get("topicsList") else None,
+ "webLinks": [H2020WebLink.from_dict(link) for link in obj.get("webLinks", [])] if obj.get("webLinks") else None,
+ "eurosciVoc": [H2020EurosciVoc.from_dict(voc) for voc in obj.get("eurosciVoc", [])] if obj.get("eurosciVoc") else None,
+ "legalBasisList": [H2020LegalBasis.from_dict(lb) for lb in obj.get("legalBasisList", [])] if obj.get("legalBasisList") else None,
+ "ercPrincipalInvestigators": [H2020ErcPI.from_dict(pi) for pi in obj.get("ercPrincipalInvestigators", [])] if obj.get("ercPrincipalInvestigators") else None,
+
+ # Statistics
+ "organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0,
+ "publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0,
+ "deliverableCount": len(obj.get("deliverables", [])) if obj.get("deliverables") else 0,
+ "ercPiCount": len(obj.get("ercPrincipalInvestigators", [])) if obj.get("ercPrincipalInvestigators") else 0,
+ })
+ return _obj
+
+ @classmethod
+ def from_project_with_relations(
+ cls,
+ project: H2020Project,
+ organizations: Optional[List[H2020Organization]] = None,
+ publications: Optional[List[H2020Publication]] = None,
+ deliverables: Optional[List[H2020Deliverable]] = None,
+ report_summaries: Optional[List[H2020ReportSummary]] = None,
+ topics_list: Optional[List[H2020Topic]] = None,
+ web_links: Optional[List[H2020WebLink]] = None,
+ eurosci_voc: Optional[List[H2020EurosciVoc]] = None,
+ legal_basis_list: Optional[List[H2020LegalBasis]] = None,
+ erc_principal_investigators: Optional[List[H2020ErcPI]] = None,
+ ) -> Self:
+ """
+ Factory method to create a detailed project from a base project and its relations.
+
+ Args:
+ project: The base H2020Project object
+ organizations: List of organizations participating in the project
+ publications: List of publications related to the project
+ deliverables: List of deliverables of the project
+ report_summaries: List of report summaries
+ topics_list: List of topics associated with the project
+ web_links: List of web links
+ eurosci_voc: List of EuroSciVoc classifications
+ legal_basis_list: List of legal basis information
+ erc_principal_investigators: List of ERC Principal Investigators
+
+ Returns:
+ H2020ProjectDetailed instance
+ """
+ project_dict = project.to_dict() if project else {}
+
+ return cls(
+ **project_dict,
+ organizations=organizations or [],
+ publications=publications or [],
+ deliverables=deliverables or [],
+ reportSummaries=report_summaries or [],
+ topicsList=topics_list or [],
+ webLinks=web_links or [],
+ eurosciVoc=eurosci_voc or [],
+ legalBasisList=legal_basis_list or [],
+ ercPrincipalInvestigators=erc_principal_investigators or [],
+ organizationCount=len(organizations) if organizations else 0,
+ publicationCount=len(publications) if publications else 0,
+ deliverableCount=len(deliverables) if deliverables else 0,
+ ercPiCount=len(erc_principal_investigators) if erc_principal_investigators else 0,
+ )
\ No newline at end of file
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_publication.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_publication.py
new file mode 100644
index 00000000..ffe9a440
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_publication.py
@@ -0,0 +1,123 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon 2020 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class H2020Publication(BaseModel):
+ """
+ H2020Publication
+ """ # noqa: E501
+ authors: Optional[StrictStr] = None
+ collection: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ doi: Optional[StrictStr] = None
+ id: Optional[StrictStr] = None
+ is_published_as: Optional[StrictStr] = Field(default=None, alias="isPublishedAs")
+ journal_number: Optional[StrictStr] = Field(default=None, alias="journalNumber")
+ journal_title: Optional[StrictStr] = Field(default=None, alias="journalTitle")
+ project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ published_pages: Optional[StrictStr] = Field(default=None, alias="publishedPages")
+ published_year: Optional[StrictInt] = Field(default=None, alias="publishedYear")
+ publisher: Optional[StrictStr] = None
+ qa_processed_doi: Optional[StrictStr] = Field(default=None, alias="qaProcessedDoi")
+ rcn: Optional[StrictStr] = None
+ repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl")
+ title: Optional[StrictStr] = None
+ volume: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of H2020Publication from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of H2020Publication from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "authors": obj.get("authors"),
+ "collection": obj.get("collection"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "doi": obj.get("doi"),
+ "id": obj.get("id"),
+ "isPublishedAs": obj.get("isPublishedAs"),
+ "journalNumber": obj.get("journalNumber"),
+ "journalTitle": obj.get("journalTitle"),
+ "projectAcronym": obj.get("projectAcronym"),
+ "projectID": obj.get("projectID"),
+ "publishedPages": obj.get("publishedPages"),
+ "publishedYear": obj.get("publishedYear"),
+ "publisher": obj.get("publisher"),
+ "qaProcessedDoi": obj.get("qaProcessedDoi"),
+ "rcn": obj.get("rcn"),
+ "repositoryUrl": obj.get("repositoryUrl"),
+ "title": obj.get("title"),
+ "volume": obj.get("volume")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_report_summary.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_report_summary.py
new file mode 100644
index 00000000..e1f7e49f
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_report_summary.py
@@ -0,0 +1,101 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon 2020 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class H2020ReportSummary(BaseModel):
+ """
+ H2020ReportSummary
+ """ # noqa: E501
+ attachments: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ id: Optional[StrictStr] = None
+ project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ rcn: Optional[StrictStr] = None
+ title: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["attachments", "contentUpdateDate", "id", "projectAcronym", "projectID", "rcn", "title"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of H2020ReportSummary from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of H2020ReportSummary from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "attachments": obj.get("attachments"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "id": obj.get("id"),
+ "projectAcronym": obj.get("projectAcronym"),
+ "projectID": obj.get("projectID"),
+ "rcn": obj.get("rcn"),
+ "title": obj.get("title")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_topic.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_topic.py
new file mode 100644
index 00000000..0c6bedbb
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_topic.py
@@ -0,0 +1,94 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon 2020 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class H2020Topic(BaseModel):
+ """
+ H2020Topic
+ """ # noqa: E501
+ id: Optional[StrictStr] = None
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ title: Optional[StrictStr] = None
+ topic: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["id", "projectID", "title", "topic"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of H2020Topic from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of H2020Topic from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "id": obj.get("id"),
+ "projectID": obj.get("projectID"),
+ "title": obj.get("title"),
+ "topic": obj.get("topic")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_web_link.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_web_link.py
new file mode 100644
index 00000000..a8e45638
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_web_link.py
@@ -0,0 +1,107 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon 2020 Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class H2020WebLink(BaseModel):
+ """
+ H2020WebLink
+ """ # noqa: E501
+ archived_date: Optional[datetime] = Field(default=None, alias="archivedDate")
+ available_languages: Optional[StrictStr] = Field(default=None, alias="availableLanguages")
+ id: Optional[StrictStr] = None
+ link_id: Optional[StrictStr] = Field(default=None, alias="linkId")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ represents: Optional[StrictStr] = None
+ source: Optional[StrictStr] = None
+ status: Optional[StrictStr] = None
+ type: Optional[StrictStr] = None
+ url: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["archivedDate", "availableLanguages", "id", "linkId", "projectID", "represents", "source", "status", "type", "url"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of H2020WebLink from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of H2020WebLink from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "archivedDate": obj.get("archivedDate"),
+ "availableLanguages": obj.get("availableLanguages"),
+ "id": obj.get("id"),
+ "linkId": obj.get("linkId"),
+ "projectID": obj.get("projectID"),
+ "represents": obj.get("represents"),
+ "source": obj.get("source"),
+ "status": obj.get("status"),
+ "type": obj.get("type"),
+ "url": obj.get("url")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_deliverable.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_deliverable.py
new file mode 100644
index 00000000..ba858158
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_deliverable.py
@@ -0,0 +1,103 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon Europe Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class HEUDeliverable(BaseModel):
+ """
+ HEUDeliverable
+ """ # noqa: E501
+ collection: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ deliverable_type: Optional[StrictStr] = Field(default=None, alias="deliverableType")
+ description: Optional[StrictStr] = None
+ project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ rcn: Optional[StrictStr] = None
+ url: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["collection", "contentUpdateDate", "deliverableType", "description", "projectAcronym", "projectID", "rcn", "url"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of HEUDeliverable from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of HEUDeliverable from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "collection": obj.get("collection"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "deliverableType": obj.get("deliverableType"),
+ "description": obj.get("description"),
+ "projectAcronym": obj.get("projectAcronym"),
+ "projectID": obj.get("projectID"),
+ "rcn": obj.get("rcn"),
+ "url": obj.get("url")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_eurosci_voc.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_eurosci_voc.py
new file mode 100644
index 00000000..586f3777
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_eurosci_voc.py
@@ -0,0 +1,98 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon Europe Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class HEUEurosciVoc(BaseModel):
+ """
+ HEUEurosciVoc
+ """ # noqa: E501
+ code: Optional[StrictStr] = None
+ description: Optional[StrictStr] = None
+ id: Optional[StrictStr] = None
+ path: Optional[StrictStr] = None
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ title: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["code", "description", "id", "path", "projectID", "title"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of HEUEurosciVoc from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of HEUEurosciVoc from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "code": obj.get("code"),
+ "description": obj.get("description"),
+ "id": obj.get("id"),
+ "path": obj.get("path"),
+ "projectID": obj.get("projectID"),
+ "title": obj.get("title")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_legal_basis.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_legal_basis.py
new file mode 100644
index 00000000..0c4e288e
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_legal_basis.py
@@ -0,0 +1,96 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon Europe Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class HEULegalBasis(BaseModel):
+ """
+ HEULegalBasis
+ """ # noqa: E501
+ id: Optional[StrictStr] = None
+ legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ title: Optional[StrictStr] = None
+ unique_programme_part: Optional[StrictStr] = Field(default=None, alias="uniqueProgrammePart")
+ __properties: ClassVar[List[str]] = ["id", "legalBasis", "projectID", "title", "uniqueProgrammePart"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of HEULegalBasis from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of HEULegalBasis from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "id": obj.get("id"),
+ "legalBasis": obj.get("legalBasis"),
+ "projectID": obj.get("projectID"),
+ "title": obj.get("title"),
+ "uniqueProgrammePart": obj.get("uniqueProgrammePart")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_organization.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_organization.py
new file mode 100644
index 00000000..069ee71a
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_organization.py
@@ -0,0 +1,139 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon Europe Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class HEUOrganization(BaseModel):
+ """
+ HEUOrganization
+ """ # noqa: E501
+ sme: Optional[StrictBool] = Field(default=None, alias="SME")
+ active: Optional[StrictBool] = None
+ activity_type: Optional[StrictStr] = Field(default=None, alias="activityType")
+ city: Optional[StrictStr] = None
+ contact_form: Optional[StrictStr] = Field(default=None, alias="contactForm")
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ country: Optional[StrictStr] = None
+ ec_contribution: Optional[StrictFloat] = Field(default=None, alias="ecContribution")
+ end_of_participation: Optional[StrictBool] = Field(default=None, alias="endOfParticipation")
+ geolocation: Optional[StrictStr] = None
+ id: Optional[StrictStr] = None
+ name: Optional[StrictStr] = None
+ net_ec_contribution: Optional[StrictFloat] = Field(default=None, alias="netEcContribution")
+ nuts_code: Optional[StrictStr] = Field(default=None, alias="nutsCode")
+ order: Optional[StrictInt] = None
+ organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID")
+ organization_url: Optional[StrictStr] = Field(default=None, alias="organizationURL")
+ post_code: Optional[StrictStr] = Field(default=None, alias="postCode")
+ project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ rcn: Optional[StrictStr] = None
+ role: Optional[StrictStr] = None
+ short_name: Optional[StrictStr] = Field(default=None, alias="shortName")
+ street: Optional[StrictStr] = None
+ total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
+ vat_number: Optional[StrictStr] = Field(default=None, alias="vatNumber")
+ __properties: ClassVar[List[str]] = ["SME", "active", "activityType", "city", "contactForm", "contentUpdateDate", "country", "ecContribution", "endOfParticipation", "geolocation", "id", "name", "netEcContribution", "nutsCode", "order", "organisationID", "organizationURL", "postCode", "projectAcronym", "projectID", "rcn", "role", "shortName", "street", "totalCost", "vatNumber"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of HEUOrganization from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of HEUOrganization from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "SME": obj.get("SME"),
+ "active": obj.get("active"),
+ "activityType": obj.get("activityType"),
+ "city": obj.get("city"),
+ "contactForm": obj.get("contactForm"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "country": obj.get("country"),
+ "ecContribution": obj.get("ecContribution"),
+ "endOfParticipation": obj.get("endOfParticipation"),
+ "geolocation": obj.get("geolocation"),
+ "id": obj.get("id"),
+ "name": obj.get("name"),
+ "netEcContribution": obj.get("netEcContribution"),
+ "nutsCode": obj.get("nutsCode"),
+ "order": obj.get("order"),
+ "organisationID": obj.get("organisationID"),
+ "organizationURL": obj.get("organizationURL"),
+ "postCode": obj.get("postCode"),
+ "projectAcronym": obj.get("projectAcronym"),
+ "projectID": obj.get("projectID"),
+ "rcn": obj.get("rcn"),
+ "role": obj.get("role"),
+ "shortName": obj.get("shortName"),
+ "street": obj.get("street"),
+ "totalCost": obj.get("totalCost"),
+ "vatNumber": obj.get("vatNumber")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project.py
new file mode 100644
index 00000000..77607832
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project.py
@@ -0,0 +1,131 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon Europe Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import date, datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class HEUProject(BaseModel):
+ """
+ HEUProject
+ """ # noqa: E501
+ acronym: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ ec_max_contribution: Optional[StrictFloat] = Field(default=None, alias="ecMaxContribution")
+ ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate")
+ end_date: Optional[date] = Field(default=None, alias="endDate")
+ framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme")
+ funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
+ grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi")
+ human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated")
+ id: Optional[StrictStr] = None
+ keywords: Optional[StrictStr] = None
+ legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
+ master_call: Optional[StrictStr] = Field(default=None, alias="masterCall")
+ nature: Optional[StrictStr] = None
+ objective: Optional[StrictStr] = None
+ rcn: Optional[StrictStr] = None
+ start_date: Optional[date] = Field(default=None, alias="startDate")
+ status: Optional[StrictStr] = None
+ sub_call: Optional[StrictStr] = Field(default=None, alias="subCall")
+ title: Optional[StrictStr] = None
+ topics: Optional[StrictStr] = None
+ total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
+ __properties: ClassVar[List[str]] = ["acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate", "endDate", "frameworkProgramme", "fundingScheme", "grantDoi", "humanValidated", "id", "keywords", "legalBasis", "masterCall", "nature", "objective", "rcn", "startDate", "status", "subCall", "title", "topics", "totalCost"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of HEUProject from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of HEUProject from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "acronym": obj.get("acronym"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "ecMaxContribution": obj.get("ecMaxContribution"),
+ "ecSignatureDate": obj.get("ecSignatureDate"),
+ "endDate": obj.get("endDate"),
+ "frameworkProgramme": obj.get("frameworkProgramme"),
+ "fundingScheme": obj.get("fundingScheme"),
+ "grantDoi": obj.get("grantDoi"),
+ "humanValidated": obj.get("humanValidated"),
+ "id": obj.get("id"),
+ "keywords": obj.get("keywords"),
+ "legalBasis": obj.get("legalBasis"),
+ "masterCall": obj.get("masterCall"),
+ "nature": obj.get("nature"),
+ "objective": obj.get("objective"),
+ "rcn": obj.get("rcn"),
+ "startDate": obj.get("startDate"),
+ "status": obj.get("status"),
+ "subCall": obj.get("subCall"),
+ "title": obj.get("title"),
+ "topics": obj.get("topics"),
+ "totalCost": obj.get("totalCost")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project_details.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project_details.py
new file mode 100644
index 00000000..48f69a7f
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project_details.py
@@ -0,0 +1,214 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon Europe Multi-Index API - Extended Models
+""" # noqa: E501
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+from datetime import date, datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+# Import all the base models
+from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject
+from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization
+from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication
+from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable
+from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary
+from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic
+from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink
+from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
+from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
+
+
+class HEUProjectDetails(BaseModel):
+ """
+ Comprehensive Horizon Europe Project model combining all related entities.
+ This model extends the base HEUProject with all associated data.
+ """
+ # Project core information (flattened from HEUProject)
+ acronym: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ ec_max_contribution: Optional[StrictFloat] = Field(default=None, alias="ecMaxContribution")
+ ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate")
+ end_date: Optional[date] = Field(default=None, alias="endDate")
+ framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme")
+ funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
+ grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi")
+ human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated")
+ id: Optional[StrictStr] = None
+ keywords: Optional[StrictStr] = None
+ legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
+ master_call: Optional[StrictStr] = Field(default=None, alias="masterCall")
+ nature: Optional[StrictStr] = None
+ objective: Optional[StrictStr] = None
+ rcn: Optional[StrictStr] = None
+ start_date: Optional[date] = Field(default=None, alias="startDate")
+ status: Optional[StrictStr] = None
+ sub_call: Optional[StrictStr] = Field(default=None, alias="subCall")
+ title: Optional[StrictStr] = None
+ topics: Optional[StrictStr] = None
+ total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
+
+ # Related entities (collections)
+ organizations: Optional[List[HEUOrganization]] = Field(default=None, description="Organizations participating in the project")
+ publications: Optional[List[HEUPublication]] = Field(default=None, description="Publications related to the project")
+ deliverables: Optional[List[HEUDeliverable]] = Field(default=None, description="Deliverables of the project")
+ report_summaries: Optional[List[HEUReportSummary]] = Field(default=None, alias="reportSummaries", description="Report summaries for the project")
+ topics_list: Optional[List[HEUTopic]] = Field(default=None, alias="topicsList", description="Topics associated with the project")
+ web_links: Optional[List[HEUWebLink]] = Field(default=None, alias="webLinks", description="Web links related to the project")
+ eurosci_voc: Optional[List[HEUEurosciVoc]] = Field(default=None, alias="eurosciVoc", description="EuroSciVoc classifications")
+ legal_basis_list: Optional[List[HEULegalBasis]] = Field(default=None, alias="legalBasisList", description="Legal basis information")
+
+ # Project statistics (aggregated)
+ organization_count: Optional[int] = Field(default=None, alias="organizationCount")
+ publication_count: Optional[int] = Field(default=None, alias="publicationCount")
+ deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount")
+
+ __properties: ClassVar[List[str]] = [
+ "acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
+ "endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
+ "humanValidated", "id", "keywords", "legalBasis", "masterCall",
+ "nature", "objective", "rcn", "startDate", "status", "subCall",
+ "title", "topics", "totalCost",
+ "organizations", "publications", "deliverables", "reportSummaries",
+ "topicsList", "webLinks", "eurosciVoc", "legalBasisList",
+ "organizationCount", "publicationCount", "deliverableCount"
+ ]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ populate_by_name=True,
+ )
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of HEUProjectDetailed from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias."""
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of HEUProjectDetailed from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ # Project core fields
+ "acronym": obj.get("acronym"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "ecMaxContribution": obj.get("ecMaxContribution"),
+ "ecSignatureDate": obj.get("ecSignatureDate"),
+ "endDate": obj.get("endDate"),
+ "frameworkProgramme": obj.get("frameworkProgramme"),
+ "fundingScheme": obj.get("fundingScheme"),
+ "grantDoi": obj.get("grantDoi"),
+ "humanValidated": obj.get("humanValidated"),
+ "id": obj.get("id"),
+ "keywords": obj.get("keywords"),
+ "legalBasis": obj.get("legalBasis"),
+ "masterCall": obj.get("masterCall"),
+ "nature": obj.get("nature"),
+ "objective": obj.get("objective"),
+ "rcn": obj.get("rcn"),
+ "startDate": obj.get("startDate"),
+ "status": obj.get("status"),
+ "subCall": obj.get("subCall"),
+ "title": obj.get("title"),
+ "topics": obj.get("topics"),
+ "totalCost": obj.get("totalCost"),
+
+ # Related entities
+ "organizations": [HEUOrganization.from_dict(org) for org in obj.get("organizations", [])] if obj.get("organizations") else None,
+ "publications": [HEUPublication.from_dict(pub) for pub in obj.get("publications", [])] if obj.get("publications") else None,
+ "deliverables": [HEUDeliverable.from_dict(deliv) for deliv in obj.get("deliverables", [])] if obj.get("deliverables") else None,
+ "reportSummaries": [HEUReportSummary.from_dict(report) for report in obj.get("reportSummaries", [])] if obj.get("reportSummaries") else None,
+ "topicsList": [HEUTopic.from_dict(topic) for topic in obj.get("topicsList", [])] if obj.get("topicsList") else None,
+ "webLinks": [HEUWebLink.from_dict(link) for link in obj.get("webLinks", [])] if obj.get("webLinks") else None,
+ "eurosciVoc": [HEUEurosciVoc.from_dict(voc) for voc in obj.get("eurosciVoc", [])] if obj.get("eurosciVoc") else None,
+ "legalBasisList": [HEULegalBasis.from_dict(lb) for lb in obj.get("legalBasisList", [])] if obj.get("legalBasisList") else None,
+
+ # Statistics
+ "organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0,
+ "publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0,
+ "deliverableCount": len(obj.get("deliverables", [])) if obj.get("deliverables") else 0,
+ })
+ return _obj
+
+ @classmethod
+ def from_project_with_relations(
+ cls,
+ project: HEUProject,
+ organizations: Optional[List[HEUOrganization]] = None,
+ publications: Optional[List[HEUPublication]] = None,
+ deliverables: Optional[List[HEUDeliverable]] = None,
+ report_summaries: Optional[List[HEUReportSummary]] = None,
+ topics_list: Optional[List[HEUTopic]] = None,
+ web_links: Optional[List[HEUWebLink]] = None,
+ eurosci_voc: Optional[List[HEUEurosciVoc]] = None,
+ legal_basis_list: Optional[List[HEULegalBasis]] = None,
+ ) -> Self:
+ """
+ Factory method to create a detailed project from a base project and its relations.
+
+ Args:
+ project: The base HEUProject object
+ organizations: List of organizations participating in the project
+ publications: List of publications related to the project
+ deliverables: List of deliverables of the project
+ report_summaries: List of report summaries
+ topics_list: List of topics associated with the project
+ web_links: List of web links
+ eurosci_voc: List of EuroSciVoc classifications
+ legal_basis_list: List of legal basis information
+
+ Returns:
+ HEUProjectDetailed instance
+ """
+ project_dict = project.to_dict() if project else {}
+
+ return cls(
+ **project_dict,
+ organizations=organizations or [],
+ publications=publications or [],
+ deliverables=deliverables or [],
+ reportSummaries=report_summaries or [],
+ topicsList=topics_list or [],
+ webLinks=web_links or [],
+ eurosciVoc=eurosci_voc or [],
+ legalBasisList=legal_basis_list or [],
+ organizationCount=len(organizations) if organizations else 0,
+ publicationCount=len(publications) if publications else 0,
+ deliverableCount=len(deliverables) if deliverables else 0,
+ )
\ No newline at end of file
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_publication.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_publication.py
new file mode 100644
index 00000000..9d3424df
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_publication.py
@@ -0,0 +1,123 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon Europe Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class HEUPublication(BaseModel):
+ """
+ HEUPublication
+ """ # noqa: E501
+ authors: Optional[StrictStr] = None
+ collection: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ doi: Optional[StrictStr] = None
+ id: Optional[StrictStr] = None
+ is_published_as: Optional[StrictStr] = Field(default=None, alias="isPublishedAs")
+ journal_number: Optional[StrictStr] = Field(default=None, alias="journalNumber")
+ journal_title: Optional[StrictStr] = Field(default=None, alias="journalTitle")
+ project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ published_pages: Optional[StrictStr] = Field(default=None, alias="publishedPages")
+ published_year: Optional[StrictInt] = Field(default=None, alias="publishedYear")
+ publisher: Optional[StrictStr] = None
+ qa_processed_doi: Optional[StrictStr] = Field(default=None, alias="qaProcessedDoi")
+ rcn: Optional[StrictStr] = None
+ repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl")
+ title: Optional[StrictStr] = None
+ volume: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of HEUPublication from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of HEUPublication from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "authors": obj.get("authors"),
+ "collection": obj.get("collection"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "doi": obj.get("doi"),
+ "id": obj.get("id"),
+ "isPublishedAs": obj.get("isPublishedAs"),
+ "journalNumber": obj.get("journalNumber"),
+ "journalTitle": obj.get("journalTitle"),
+ "projectAcronym": obj.get("projectAcronym"),
+ "projectID": obj.get("projectID"),
+ "publishedPages": obj.get("publishedPages"),
+ "publishedYear": obj.get("publishedYear"),
+ "publisher": obj.get("publisher"),
+ "qaProcessedDoi": obj.get("qaProcessedDoi"),
+ "rcn": obj.get("rcn"),
+ "repositoryUrl": obj.get("repositoryUrl"),
+ "title": obj.get("title"),
+ "volume": obj.get("volume")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_report_summary.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_report_summary.py
new file mode 100644
index 00000000..bf5850fc
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_report_summary.py
@@ -0,0 +1,101 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon Europe Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class HEUReportSummary(BaseModel):
+ """
+ HEUReportSummary
+ """ # noqa: E501
+ attachments: Optional[StrictStr] = None
+ content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
+ id: Optional[StrictStr] = None
+ project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ rcn: Optional[StrictStr] = None
+ title: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["attachments", "contentUpdateDate", "id", "projectAcronym", "projectID", "rcn", "title"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of HEUReportSummary from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of HEUReportSummary from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "attachments": obj.get("attachments"),
+ "contentUpdateDate": obj.get("contentUpdateDate"),
+ "id": obj.get("id"),
+ "projectAcronym": obj.get("projectAcronym"),
+ "projectID": obj.get("projectID"),
+ "rcn": obj.get("rcn"),
+ "title": obj.get("title")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_topic.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_topic.py
new file mode 100644
index 00000000..4aa58787
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_topic.py
@@ -0,0 +1,94 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon Europe Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class HEUTopic(BaseModel):
+ """
+ HEUTopic
+ """ # noqa: E501
+ id: Optional[StrictStr] = None
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ title: Optional[StrictStr] = None
+ topic: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["id", "projectID", "title", "topic"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of HEUTopic from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of HEUTopic from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "id": obj.get("id"),
+ "projectID": obj.get("projectID"),
+ "title": obj.get("title"),
+ "topic": obj.get("topic")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_web_link.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_web_link.py
new file mode 100644
index 00000000..50797815
--- /dev/null
+++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_web_link.py
@@ -0,0 +1,107 @@
+# coding: utf-8
+
+"""
+ CORDIS Horizon Europe Multi-Index API
+
+ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
+
+ The version of the OpenAPI document: 1.0.0
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
+
+ Do not edit the class manually.
+""" # noqa: E501
+
+
+from __future__ import annotations
+import pprint
+import re # noqa: F401
+import json
+
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, Field, StrictStr
+from typing import Any, ClassVar, Dict, List, Optional
+from typing import Optional, Set
+from typing_extensions import Self
+from pydantic_core import to_jsonable_python
+
+class HEUWebLink(BaseModel):
+ """
+ HEUWebLink
+ """ # noqa: E501
+ archived_date: Optional[datetime] = Field(default=None, alias="archivedDate")
+ available_languages: Optional[StrictStr] = Field(default=None, alias="availableLanguages")
+ id: Optional[StrictStr] = None
+ link_id: Optional[StrictStr] = Field(default=None, alias="linkId")
+ project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
+ represents: Optional[StrictStr] = None
+ source: Optional[StrictStr] = None
+ status: Optional[StrictStr] = None
+ type: Optional[StrictStr] = None
+ url: Optional[StrictStr] = None
+ __properties: ClassVar[List[str]] = ["archivedDate", "availableLanguages", "id", "linkId", "projectID", "represents", "source", "status", "type", "url"]
+
+ model_config = ConfigDict(
+ validate_by_name=True,
+ validate_by_alias=True,
+ validate_assignment=True,
+ protected_namespaces=(),
+ )
+
+
+ def to_str(self) -> str:
+ """Returns the string representation of the model using alias"""
+ return pprint.pformat(self.model_dump(by_alias=True))
+
+ def to_json(self) -> str:
+ """Returns the JSON representation of the model using alias"""
+ return json.dumps(to_jsonable_python(self.to_dict()))
+
+ @classmethod
+ def from_json(cls, json_str: str) -> Optional[Self]:
+ """Create an instance of HEUWebLink from a JSON string"""
+ return cls.from_dict(json.loads(json_str))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return the dictionary representation of the model using alias.
+
+ This has the following differences from calling pydantic's
+ `self.model_dump(by_alias=True)`:
+
+ * `None` is only added to the output dict for nullable fields that
+ were set at model initialization. Other fields with value `None`
+ are ignored.
+ """
+ excluded_fields: Set[str] = set([
+ ])
+
+ _dict = self.model_dump(
+ by_alias=True,
+ exclude=excluded_fields,
+ exclude_none=True,
+ )
+ return _dict
+
+ @classmethod
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
+ """Create an instance of HEUWebLink from a dict"""
+ if obj is None:
+ return None
+
+ if not isinstance(obj, dict):
+ return cls.model_validate(obj)
+
+ _obj = cls.model_validate({
+ "archivedDate": obj.get("archivedDate"),
+ "availableLanguages": obj.get("availableLanguages"),
+ "id": obj.get("id"),
+ "linkId": obj.get("linkId"),
+ "projectID": obj.get("projectID"),
+ "represents": obj.get("represents"),
+ "source": obj.get("source"),
+ "status": obj.get("status"),
+ "type": obj.get("type"),
+ "url": obj.get("url")
+ })
+ return _obj
+
+
diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py
index b02aafd2..77cf31a0 100644
--- a/service/src/main/inse/news/logic.py
+++ b/service/src/main/inse/news/logic.py
@@ -4,33 +4,69 @@
Business logic for the "aktuell" news index on the INSE cluster.
"""
+import json
import logging
+import re
-from fastapi import HTTPException
-from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
+from inse.exceptions import ElasticsearchException
-from ..integrations import elasticsearch
+from ..integrations import elasticsearch, llm
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__)
+TOPIC_LIMIT = 4
+TOPIC_QUERY_CONTENT_CHARS = 300
+TOPIC_NUM_CANDIDATES = 100
+TOPIC_SIMILARITY = 0.5
-def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPage:
+KEYWORD_LIMIT = 6
+KEYWORD_CONTENT_CHARS = 4000
+KEYWORD_SYSTEM_PROMPT = """\
+ Extrahiere aus dem folgenden Nachrichtenartikel die wichtigsten Schlagwörter (Keywords).
+ Gib maximal sechs prägnante Begriffe oder kurze Phrasen zurück, die den inhaltlichen Kern
+ des Artikels erfassen. Antworte ausschließlich mit einem JSON-Array von Strings, ohne
+ weiteren Text, zum Beispiel ["Künstliche Intelligenz", "Klimaforschung"].
+"""
+
+RELATED_BLOCK_SIZE = 5
+RELATED_TOPIC_K = 1
+EXACT_ID_CAP = 1000
+
+
+async def get_news_page(
+ page: int,
+ page_size: int,
+ sort_order: str = "desc",
+ year_from: int | None = None,
+ year_to: int | None = None,
+ relevance_values: list | None = None,
+) -> NewsPage:
offset = (page - 1) * page_size
- response = _run_search(
- query={"match_all": {}},
- source=["date", "maintitle", "author", "url"],
+ clauses = await _filter_clauses(year_from, year_to, relevance_values)
+ query = {"bool": {"filter": clauses}} if clauses else {"match_all": {}}
+
+ response = await _run_search(
+ query=query,
+ source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
size=page_size,
offset=offset,
sort=[{"date_full": sort_order}],
)
- return _build_page(response, page, page_size)
+ return await _build_page(response, page, page_size)
-def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
+async def search_news(
+ query_text: str,
+ page: int,
+ page_size: int,
+ year_from: int | None = None,
+ year_to: int | None = None,
+ relevance_values: list | None = None,
+) -> NewsPage:
offset = (page - 1) * page_size
highlight = {
@@ -40,8 +76,16 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
"encoder": "html",
}
- response = _run_search(
- query={"match": {"full_content": query_text}},
+ # Filter einmal berechnen (der Relevanz-Filter macht eine ES-Abfrage).
+ clauses = await _filter_clauses(year_from, year_to, relevance_values)
+ exact_query = {
+ "bool": {
+ "must": [{"match": {"full_content": query_text}}],
+ "filter": clauses,
+ }
+ }
+ response = await _run_search(
+ query=exact_query,
source=["date", "maintitle", "author", "url"],
size=page_size,
offset=offset,
@@ -49,9 +93,20 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
highlight=highlight,
)
- return _build_page(response, page, page_size)
+ news_page = await _build_page(response, page, page_size)
-def get_news_by_author(
+ if _is_last_page(page, page_size, news_page.total):
+ exclude_ids = await _exact_match_ids(exact_query)
+ news_page.results.extend(
+ await _related_articles(
+ query_text, exclude_ids=exclude_ids, extra_filters=clauses
+ )
+ )
+
+ return news_page
+
+
+async def get_news_by_author(
author_id: str,
page: int = 1,
page_size: int = 10,
@@ -59,11 +114,11 @@ def get_news_by_author(
query_text: str | None = None,
) -> NewsPage:
- author_name = get_author_name_by_id(author_id)
+ author_name = await 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)
+ news_ids = await _find_news_ids_for_author(author_name)
if not news_ids:
return _empty_page(page, page_size)
@@ -74,7 +129,7 @@ def get_news_by_author(
]
offset = (page - 1) * page_size
- response = _run_search(
+ response = await _run_search(
query=es_query,
source=["date", "maintitle", "author", "url"],
size=page_size,
@@ -82,13 +137,71 @@ def get_news_by_author(
sort=[{"date_full": sort_order}],
)
- return _build_page(response, page, page_size)
+ news_page = await _build_page(response, page, page_size)
+
+ if query_text and _is_last_page(page, page_size, news_page.total):
+ exclude_ids = await _exact_match_ids(es_query)
+ news_page.results.extend(
+ await _related_articles(
+ query_text, exclude_ids=exclude_ids, filter_news_ids=news_ids
+ )
+ )
+
+ return news_page
-def _find_news_ids_for_author(author_name: str) -> list:
+async def _filter_clauses(
+ year_from: int | None,
+ year_to: int | None,
+ relevance_values: list | None,
+) -> list:
+ clauses = []
+
+ if year_from is not None or year_to is not None:
+ date_range = {}
+ if year_from is not None:
+ date_range["gte"] = year_from
+ if year_to is not None:
+ date_range["lte"] = year_to
+ clauses.append({"range": {"date_year": date_range}})
+
+ relevant_ids = await _relevance_news_ids(relevance_values)
+ if relevant_ids is not None:
+ clauses.append({"ids": {"values": relevant_ids}})
+
+ return clauses
+
+
+async def _relevance_news_ids(relevance_values: list | None) -> list | None:
+ selected = set(relevance_values or [])
+
+ if not selected or {"relevant", "not_relevant"} <= selected:
+ return None
+
+ relevant_value = 1 if "relevant" in selected else 0
+
+ news_ids = []
+ try:
+ async for hit in elasticsearch.scan(
+ index="aktuell_postproc",
+ query={"term": {"relevant": relevant_value}},
+ source=["news_id"],
+ cluster="inse",
+ ):
+ news_id = hit.get("_source", {}).get("news_id")
+ if news_id:
+ news_ids.append(news_id)
+ except Exception:
+ logger.exception("Relevanz-IDs aus aktuell_postproc konnten nicht geladen werden.")
+ return []
+
+ return news_ids
+
+
+async def _find_news_ids_for_author(author_name: str) -> list:
try:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index="aktuell_postproc",
query={"term": {"authors.keyword": author_name}},
source=["news_id"],
@@ -112,24 +225,29 @@ 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:
+async def get_news_by_id(news_id: str) -> NewsArticleDetail:
try:
- response = elasticsearch.get(
+ response = await elasticsearch.get(
index="aktuell",
doc_id=news_id,
source=["date", "maintitle", "author", "url", "full_content"],
cluster="inse",
)
- except Exception as exc:
+ except ElasticsearchException as exc:
logger.exception("Abruf des News-Artikels fehlgeschlagen.")
- raise HTTPException(
- status_code=HTTP_500_INTERNAL_SERVER_ERROR,
- detail="Etwas ist schiefgelaufen.",
- ) from exc
+ raise
source = response.get("_source", {})
- relevant, authors = _get_postproc_labels(news_id)
+ relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
+ topics = await _get_article_topics(source.get("maintitle"), source.get("full_content"))
+ keywords = await _get_article_keywords(
+ news_id,
+ postproc_id,
+ cached_keywords,
+ source.get("maintitle"),
+ source.get("full_content"),
+ )
return NewsArticleDetail(
id=response.get("_id"),
@@ -139,17 +257,131 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail:
url=source.get("url"),
full_content=source.get("full_content"),
relevant=relevant,
- authors=_build_mentioned_persons(authors),
+ authors=await _build_mentioned_persons(authors),
+ topics=topics,
+ keywords=keywords,
)
-def _build_mentioned_persons(author_names: list) -> list:
+async def _get_article_topics(maintitle: str | None, full_content: str | None) -> list:
+ query = " ".join(
+ part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part
+ ).strip()
+ if not query:
+ return []
+
+ topics = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
+ return [topic["display_name"] for topic in topics if topic.get("display_name")]
+
+
+async def _get_article_keywords(
+ news_id: str,
+ postproc_id: str | None,
+ cached_keywords: list,
+ maintitle: str | None,
+ full_content: str | None,
+) -> list:
+ if cached_keywords:
+ return cached_keywords
+
+ text = " ".join(
+ part for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS]) if part
+ ).strip()
+ if not text:
+ return []
+
+ raw = llm.call(
+ system_prompt=KEYWORD_SYSTEM_PROMPT,
+ user_prompt=f"Artikel:\n{text}",
+ temperature=0.3,
+ )
+ keywords = _parse_keywords(raw)
+
+ if keywords:
+ await _store_keywords(news_id, postproc_id, keywords)
+
+ return keywords
+
+
+def _parse_keywords(raw: str) -> list:
+ raw = (raw or "").strip()
+
+ try:
+ parsed = json.loads(raw)
+ candidates = parsed if isinstance(parsed, list) else []
+ except (json.JSONDecodeError, TypeError):
+ candidates = re.split(r"[,\n]", raw)
+
+ seen = set()
+ keywords = []
+ for item in candidates:
+ term = str(item).strip().strip('"').strip()
+ if term and term.lower() not in seen:
+ seen.add(term.lower())
+ keywords.append(term)
+
+ return keywords[:KEYWORD_LIMIT]
+
+
+async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None:
+ try:
+ if postproc_id:
+ await elasticsearch.update(
+ index="aktuell_postproc",
+ doc_id=postproc_id,
+ doc={"keywords": keywords},
+ cluster="inse",
+ )
+ else:
+ await elasticsearch.index_doc(
+ index="aktuell_postproc",
+ doc_id=news_id,
+ document={"news_id": news_id, "keywords": keywords},
+ cluster="inse",
+ )
+ except Exception:
+ logger.exception(f"Failed to cache keywords for {news_id}.")
+
+
+async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
+ try:
+ from ..util import get_model
+
+ query_vector = get_model().encode(query_text).tolist()
+ except Exception:
+ logger.exception("Failed to encode text for topic vector search.")
+ return []
+
+ try:
+ response = await elasticsearch.search(
+ index="topicvectors",
+ body={
+ "knn": {
+ "field": "display_name_vector",
+ "query_vector": query_vector,
+ "k": k,
+ "num_candidates": TOPIC_NUM_CANDIDATES,
+ "similarity": TOPIC_SIMILARITY,
+ },
+ "_source": source_fields,
+ "size": k,
+ },
+ cluster="nes",
+ )
+ except Exception:
+ logger.exception("Topic vector search failed.")
+ return []
+
+ return [hit.get("_source", {}) for hit in response.get("hits", {}).get("hits", [])]
+
+
+async def _build_mentioned_persons(author_names: list) -> list:
ude_persons = []
other_persons = []
for name in author_names:
- match = find_ude_author_by_name(name)
+ match = await find_ude_author_by_name(name)
if match:
ude_persons.append(
MentionedPerson(name=name, is_ude=True, person_id=match["id"])
@@ -160,33 +392,35 @@ def _build_mentioned_persons(author_names: list) -> list:
return ude_persons + other_persons
-def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]:
+async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]:
try:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index="aktuell_postproc",
query={"term": {"news_id.keyword": news_id}},
- source=["relevant", "authors"],
+ source=["relevant", "authors", "keywords"],
size=1,
cluster="inse",
)
except Exception:
logger.exception(f"Postproc-Lookup for {news_id} failed.")
- return None, []
+ return None, [], [], None
hits = response.get("hits", {}).get("hits", [])
if not hits:
- return None, []
+ return None, [], [], None
- postproc_source = hits[0].get("_source", {})
+ hit = hits[0]
+ postproc_source = hit.get("_source", {})
relevant = bool(postproc_source.get("relevant", 0))
authors = postproc_source.get("authors") or []
+ keywords = postproc_source.get("keywords") or []
- return relevant, authors
+ return relevant, authors, keywords, hit.get("_id")
-def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
+async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
try:
- return elasticsearch.search(
+ return await elasticsearch.search(
index="aktuell",
query=query,
source=source,
@@ -197,15 +431,12 @@ def _run_search(query: dict, source: list, size: int, offset: int, sort, highlig
highlight=highlight,
cluster="inse",
)
- except Exception as exc:
+ except ElasticsearchException 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
+ raise
-def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
+async 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", [])
@@ -216,7 +447,7 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
if news_id:
news_ids.append(news_id)
- relevance_map = _get_relevance_map(news_ids)
+ relevance_map = await _get_relevance_map(news_ids)
articles = []
for hit in hits:
@@ -232,12 +463,12 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
)
-def _get_relevance_map(news_ids: list) -> dict:
+async def _get_relevance_map(news_ids: list) -> dict:
if not news_ids:
return {}
try:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index="aktuell_postproc",
query={"terms": {"news_id.keyword": news_ids}},
source=["news_id", "relevant"],
@@ -262,7 +493,11 @@ def _parse_hit(hit: dict) -> NewsArticle:
source = hit.get("_source", {})
fragments = hit.get("highlight", {}).get("full_content")
- snippet = fragments[0] if fragments else None
+
+ if fragments:
+ snippet = fragments[0]
+ else:
+ snippet = _make_preview(source)
return NewsArticle(
id=hit.get("_id"),
@@ -272,3 +507,104 @@ def _parse_hit(hit: dict) -> NewsArticle:
url=source.get("url"),
snippet=snippet,
)
+
+
+def _make_preview(source: dict) -> str | None:
+ text = source.get("intro_content") or source.get("full_content")
+
+ if not text:
+ return None
+
+ words = text.split()
+
+ PREVIEW_WORD_COUNT = 10
+ preview = " ".join(words[:PREVIEW_WORD_COUNT])
+ if len(words) > PREVIEW_WORD_COUNT:
+ preview = preview + " …"
+ return preview
+
+
+def _is_last_page(page: int, page_size: int, total: int) -> bool:
+ return page * page_size >= total
+
+
+async def _exact_match_ids(query: dict) -> list:
+ try:
+ response = await _run_search(
+ query=query,
+ source=[],
+ size=EXACT_ID_CAP,
+ offset=0,
+ sort=None,
+ )
+ except Exception:
+ logger.exception("Failed to collect exact-match ids for dedup.")
+ return []
+
+ return [
+ hit.get("_id")
+ for hit in response.get("hits", {}).get("hits", [])
+ if hit.get("_id")
+ ]
+
+
+async def _related_articles(
+ query_text: str,
+ exclude_ids: list | None = None,
+ filter_news_ids: list | None = None,
+ extra_filters: list | None = None,
+ k: int = RELATED_BLOCK_SIZE,
+) -> list:
+ related_terms = await _related_search_terms(query_text)
+ if not related_terms:
+ return []
+
+ bool_query = {
+ "should": [{"match": {"full_content": term}} for term in related_terms],
+ "minimum_should_match": 1,
+ }
+ if exclude_ids:
+ bool_query["must_not"] = [{"ids": {"values": exclude_ids}}]
+ if filter_news_ids is not None:
+ bool_query["filter"] = [{"ids": {"values": filter_news_ids}}]
+ if extra_filters:
+ bool_query.setdefault("filter", []).extend(extra_filters)
+
+ try:
+ response = await elasticsearch.search(
+ index="aktuell",
+ query={"bool": bool_query},
+ source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
+ size=k,
+ offset=0,
+ cluster="inse",
+ )
+ except Exception:
+ logger.exception("Related-articles search failed.")
+ return []
+
+ articles = []
+ for hit in response.get("hits", {}).get("hits", []):
+ article = _parse_hit(hit)
+ article.related = True
+ articles.append(article)
+
+ relevance_map = await _get_relevance_map([article.id for article in articles])
+ for article in articles:
+ article.relevant = relevance_map.get(article.id)
+
+ return articles
+
+
+async def _related_search_terms(query_text: str) -> list:
+ topics = await _topic_vector_search(query_text, RELATED_TOPIC_K, ["display_name", "keywords"])
+
+ seen = {query_text.lower()}
+ terms = []
+ for topic in topics:
+ for term in [topic.get("display_name"), *(topic.get("keywords") or [])]:
+ if term and term.lower() not in seen:
+ seen.add(term.lower())
+ terms.append(term)
+
+ return terms
diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py
index 723e9b49..b63c2bc0 100644
--- a/service/src/main/inse/news/model.py
+++ b/service/src/main/inse/news/model.py
@@ -14,6 +14,7 @@ class NewsArticle(BaseModel):
url: Optional[str] = None
relevant: Optional[bool] = None
snippet: Optional[str] = None
+ related: Optional[bool] = None
class MentionedPerson(BaseModel):
@@ -26,6 +27,8 @@ class NewsArticleDetail(NewsArticle):
full_content: Optional[str] = None
relevant: Optional[bool] = None
authors: List[MentionedPerson] = []
+ topics: List[str] = []
+ keywords: List[str] = []
class NewsPage(BaseModel):
diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py
index 5bb5dc03..b183d6fa 100644
--- a/service/src/main/inse/news/service.py
+++ b/service/src/main/inse/news/service.py
@@ -16,6 +16,15 @@ from .model import NewsArticleDetail, NewsPage
router = APIRouter(prefix="/api/news", tags=[Tags.NEWS])
+ALLOWED_RELEVANCE_VALUES = {"relevant", "not_relevant"}
+
+
+def _parse_relevance(relevance: str | None) -> list:
+ if not relevance:
+ return []
+ values = [entry.strip() for entry in relevance.split(",")]
+ return [value for value in values if value in ALLOWED_RELEVANCE_VALUES]
+
@router.get(
"",
@@ -25,7 +34,7 @@ router = APIRouter(prefix="/api/news", tags=[Tags.NEWS])
summary="Returns a page of news articles, newest first.",
tags=[Tags.NEWS],
)
-def list_news(
+async def list_news(
page: Annotated[
int, Query(description="Page number (1-based).", ge=1)
] = 1,
@@ -35,8 +44,24 @@ def list_news(
sort_order: Annotated[
str, Query(alias="sortOrder", description="Sort order: 'desc' (newest first) or 'asc' (oldest first).", pattern="^(asc|desc)$")
] = "desc",
+ relevance: Annotated[
+ str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.")
+ ] = None,
+ year_from: Annotated[
+ int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0)
+ ] = None,
+ year_to: Annotated[
+ int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
+ ] = None,
):
- return logic.get_news_page(page, page_size, sort_order)
+ return await logic.get_news_page(
+ page,
+ page_size,
+ sort_order,
+ year_from=year_from,
+ year_to=year_to,
+ relevance_values=_parse_relevance(relevance),
+ )
@router.get(
@@ -47,7 +72,7 @@ def list_news(
summary="Searches news articles by full text (full_content).",
tags=[Tags.NEWS],
)
-def search_news(
+async def search_news(
query: Annotated[
str, Query(description="Search term, matched against the full text (full_content).", min_length=1)
],
@@ -57,8 +82,24 @@ def search_news(
page_size: Annotated[
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
] = 10,
+ relevance: Annotated[
+ str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.")
+ ] = None,
+ year_from: Annotated[
+ int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0)
+ ] = None,
+ year_to: Annotated[
+ int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
+ ] = None,
):
- return logic.search_news(query, page, page_size)
+ return await logic.search_news(
+ query,
+ page,
+ page_size,
+ year_from=year_from,
+ year_to=year_to,
+ relevance_values=_parse_relevance(relevance),
+ )
@router.get(
@@ -69,7 +110,7 @@ def search_news(
summary="Returns news articles in which the given person is mentioned.",
tags=[Tags.NEWS],
)
-def get_news_by_author(
+async def get_news_by_author(
author_id: Annotated[
str, Query(alias="authorId", description="OpenAlex author id, e.g. A5034365278.")
],
@@ -86,7 +127,7 @@ def get_news_by_author(
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)
+ return await logic.get_news_by_author(author_id, page, page_size, sort_order, query)
@router.get(
@@ -97,9 +138,9 @@ def get_news_by_author(
summary="Returns a single news article including its full content.",
tags=[Tags.NEWS],
)
-def get_news_by_id(
+async 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)
+ return await logic.get_news_by_id(news_id)
diff --git a/service/src/main/inse/patents/elastic_search_all_patents_client.py b/service/src/main/inse/patents/elastic_search_all_patents_client.py
new file mode 100644
index 00000000..bdca70f5
--- /dev/null
+++ b/service/src/main/inse/patents/elastic_search_all_patents_client.py
@@ -0,0 +1,125 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+ HTTP client for fetching all patents from EPO and USPTO Elasticsearch indices.
+"""
+from typing import Any
+
+import httpx
+
+from .. import config
+from inse.exceptions import MissingApiKeyError
+
+from inse.integrations import elasticsearch
+from inse.model import ESCluster
+
+EPO_INDEX = "epo_index_1.0"
+USPTO_INDEX = "uspto_patents_3.0"
+
+
+class AllPatentsSearchClient:
+ def __init__(
+ self,
+ base_url: str | None = None,
+ api_key: str | None = None,
+ timeout: float = 30.0,
+ transport: httpx.AsyncBaseTransport | None = None,
+ ):
+ self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
+ self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
+ self.timeout = timeout
+ self.transport = transport
+
+ def _headers(self) -> dict[str, str]:
+ if not self.api_key:
+ raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
+ return {
+ "Authorization": f"ApiKey {self.api_key}",
+ "Content-Type": "application/json",
+ }
+
+ def epo_query(
+ self,
+ page: int = 0,
+ size: int = 10,
+ search: str | None = None,
+ sort_direction: str = "desc",
+ ) -> dict[str, Any]:
+ sort = [{"date_publication": {"order": sort_direction, "missing": "_last"}}, "_doc"]
+
+ if search and search.strip():
+ term = search.strip()
+ doc_number = term.upper().removeprefix("EP")
+ query: dict[str, Any] = {
+ "bool": {
+ "should": [
+ {"match_phrase": {"title_en": {"query": term}}},
+ {"match_phrase": {"title_de": {"query": term}}},
+ {"term": {"doc_number": doc_number}},
+ ],
+ "minimum_should_match": 1,
+ }
+ }
+ else:
+ query = {"match_all": {}}
+
+ return {
+ "from": page * size,
+ "size": size,
+ "track_total_hits": True,
+ "sort": sort,
+ "_source": [
+ "doc_number", "country", "kind", "date_publication",
+ "date_publication_year", "application_number",
+ "application_filing_date", "title_en", "title_de",
+ "abstract", "inventors_name", "applicants_name", "ipc", "cpc",
+ ],
+ "query": query,
+ }
+
+ def uspto_query(
+ self,
+ page: int = 0,
+ size: int = 10,
+ search: str | None = None,
+ sort_direction: str = "desc",
+ ) -> dict[str, Any]:
+ sort = [{"publication_date": {"order": sort_direction, "missing": "_last"}}, "_doc"]
+
+ if search and search.strip():
+ term = search.strip()
+ pub_number = term.upper().removeprefix("US")
+ query: dict[str, Any] = {
+ "bool": {
+ "should": [
+ {"match_phrase": {"title": {"query": term}}},
+ {"term": {"publication_number": pub_number}},
+ ],
+ "minimum_should_match": 1,
+ }
+ }
+ else:
+ query = {"match_all": {}}
+
+ return {
+ "from": page * size,
+ "size": size,
+ "track_total_hits": True,
+ "sort": sort,
+ "_source": [
+ "publication_number", "country", "publication_date",
+ "publication_year", "application_number", "application_date",
+ "application_type", "title", "abstract", "inventors_names",
+ "assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
+ ],
+ "query": query,
+ }
+
+ async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
+ return await self._search(EPO_INDEX, payload)
+
+ async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
+ return await self._search(USPTO_INDEX, payload)
+
+ async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
+ return await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE)
\ No newline at end of file
diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py
index 64d5865e..a7860f4d 100644
--- a/service/src/main/inse/patents/elastic_search_client.py
+++ b/service/src/main/inse/patents/elastic_search_client.py
@@ -4,15 +4,13 @@
HTTP client for patent searches in EPO and USPTO Elasticsearch indices.
"""
from typing import Any
-
+from inse.integrations import elasticsearch
+from inse.model import ESCluster, ESIndex
import httpx
-
+import asyncio
from .. import config
from .name_matching import search_name_variants
-EPO_INDEX = "epo_index_1.0"
-USPTO_INDEX = "uspto_patents_3.0"
-
DEFAULT_SEARCH_SIZE = 100
@@ -29,8 +27,7 @@ def _match_name_field(field: str, name: str) -> dict[str, Any]:
}
-class MissingApiKeyError(Exception):
- pass
+from inse.exceptions import MissingApiKeyError
class PatentSearchClient:
@@ -97,13 +94,15 @@ class PatentSearchClient:
"kind",
"date_publication",
"date_publication_year",
+ "application_number",
+ "application_filing_date",
"title_en",
"title_de",
"abstract",
"inventors_name",
"applicants_name",
"ipc",
- "ipc_text",
+ "cpc",
],
"query": query,
}
@@ -150,33 +149,133 @@ class PatentSearchClient:
"country",
"publication_date",
"publication_year",
+ "application_number",
+ "application_date",
+ "application_type",
"title",
"abstract",
"inventors_names",
- "inventors_names_text",
"assignees_orgs",
"ipcr",
- "ipcr_text",
+ "cpc",
+ "number_of_claims",
+ "status",
],
"query": query,
}
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
- return await self._search(EPO_INDEX, payload)
+ return await self._search(ESIndex.EPO_INDEX, payload)
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
- return await self._search(USPTO_INDEX, payload)
+ return await self._search(ESIndex.USPTO_INDEX, payload)
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
- async with httpx.AsyncClient(
- base_url=self.base_url,
- timeout=self.timeout,
- transport=self.transport,
- ) as client:
- response = await client.post(
- f"/{index}/_search",
- headers=self._headers(),
- json=payload,
- )
- response.raise_for_status()
- return response.json()
+ response = await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE)
+ return response
+
+ async def get_by_id_or_title(
+ self,
+ patent_id: str,
+ prefix: str,
+ title: str,
+ size: int = 1,
+ ) -> dict[str, Any]:
+ """Search EPO and USPTO by ID; fall back to match_phrase on title if no hits.
+
+ Args:
+ patent_id: The raw document/publication number (e.g. "1234567", "US1234567A").
+ prefix: "EP" routes the title fallback to EPO; "US" routes it to USPTO.
+ Both indices are always queried for the ID lookup.
+ title: Used only when the ID lookup returns zero hits.
+ size: Maximum number of results to return.
+ """
+ epo_id_payload = self._epo_query_by_id(patent_id, size)
+ uspto_id_payload = self._uspto_query_by_id(patent_id, size)
+
+ epo_result, uspto_result = await asyncio.gather(
+ self.search_epo(epo_id_payload),
+ self.search_uspto(uspto_id_payload),
+ )
+
+ epo_hits = epo_result.get("hits", {}).get("total", {}).get("value", 0)
+ uspto_hits = uspto_result.get("hits", {}).get("total", {}).get("value", 0)
+
+ if epo_hits > 0 or uspto_hits > 0:
+ if prefix.upper() == "EP" and epo_hits > 0:
+ return epo_result
+ if prefix.upper() == "US" and uspto_hits > 0:
+ return uspto_result
+ return epo_result if epo_hits > 0 else uspto_result
+
+ if prefix.upper() == "US":
+ payload = self._uspto_query_by_title(title, size)
+ return await self.search_uspto(payload)
+
+ payload = self._epo_query_by_title(title, size)
+ return await self.search_epo(payload)
+ #query builders
+
+ def _epo_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
+ """Term query against doc_number; strips a leading 'EP' prefix if present."""
+ raw_id = patent_id.upper().removeprefix("EP")
+ return {
+ "size": size,
+ "_source": [
+ "doc_number", "country", "kind", "date_publication",
+ "date_publication_year", "application_number",
+ "application_filing_date", "title_en", "title_de", "abstract",
+ "inventors_name", "applicants_name", "ipc", "cpc",
+ ],
+ "query": {"term": {"doc_number": raw_id}},
+ }
+
+ def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
+ """Term query against publication_number; tries the ID as-is."""
+ return {
+ "size": size,
+ "track_total_hits": True,
+ "sort": [{"publication_date": {"order": "desc", "missing": "_last"}}, "_doc"],
+ "_source": [
+ "publication_number", "country", "publication_date",
+ "publication_year", "application_number", "application_date",
+ "application_type", "title", "abstract", "inventors_names",
+ "assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
+ ],
+ "query": {"term": {"publication_number": patent_id}},
+ }
+
+ def _epo_query_by_title(self, title: str, size: int) -> dict[str, Any]:
+ """match_phrase fallback on title_en (and title_de as a should clause)."""
+ return {
+ "size": size,
+ "_source": [
+ "doc_number", "country", "kind", "date_publication",
+ "date_publication_year", "application_number",
+ "application_filing_date", "title_en", "title_de", "abstract",
+ "inventors_name", "applicants_name", "ipc", "cpc",
+ ],
+ "query": {
+ "bool": {
+ "should": [
+ {"match_phrase": {"title_en": title}},
+ {"match_phrase": {"title_de": title}},
+ {"match_phrase": {"title_fr": title}},
+ ],
+ "minimum_should_match": 1,
+ }
+ },
+ }
+
+ def _uspto_query_by_title(self, title: str, size: int) -> dict[str, Any]:
+ """match_phrase fallback on title."""
+ return {
+ "size": size,
+ "_source": [
+ "publication_number", "country", "publication_date",
+ "publication_year", "application_number", "application_date",
+ "application_type", "title", "abstract", "inventors_names",
+ "assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
+ ],
+ "query": {"match_phrase": {"title": title}},
+ }
\ No newline at end of file
diff --git a/service/src/main/inse/patents/ipc_lookup.py b/service/src/main/inse/patents/ipc_lookup.py
new file mode 100644
index 00000000..9581ffe6
--- /dev/null
+++ b/service/src/main/inse/patents/ipc_lookup.py
@@ -0,0 +1,221 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+ Parse IPC/CPC symbols and assemble enriched classification objects.
+"""
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+from . import model
+
+IPC_SYMBOL_RE = re.compile(
+ r"^(?P[A-HY])"
+ r"(?P\d{2})"
+ r"(?P[A-Z])"
+ r"\s*"
+ r"(?:(?P\d+))?"
+ r"(?:/(?P\d+))?"
+ r"\s*$",
+ re.IGNORECASE,
+)
+
+# EPO strings append metadata after the symbol, e.g.
+# "G01S 5/02 20100101AFI20140127BHEP"
+IPC_CODE_EXTRACT_RE = re.compile(
+ r"^([A-HY]\d{2}[A-Z]\s*\d+(?:/\d+)?)",
+ re.IGNORECASE,
+)
+# Legacy EPO spacing and trailing classification value, e.g.
+# "C 07C 405/00 A" or "C 07D 317/20 B"
+EPO_LEGACY_IPC_RE = re.compile(
+ r"^(?P[A-HY])\s+"
+ r"(?P\d{2})\s*"
+ r"(?P[A-Z])\s+"
+ r"(?P\d+)"
+ r"(?:/(?P\d+))?"
+ r"(?:\s+(?P[A-Z]))?"
+ r"(?:\s|$)",
+ re.IGNORECASE,
+)
+IPC_SUBCLASS_ONLY_RE = re.compile(
+ r"^([A-HY]\d{2}[A-Z])(?:\s|$)",
+ re.IGNORECASE,
+)
+
+
+@dataclass(frozen=True)
+class IpcHierarchyKeys:
+ symbol: str
+ normalized: str
+ section: str | None
+ ipc_class: str | None
+ subclass: str | None
+ main_group: str | None
+ subgroup: str | None
+
+
+def extract_ipc_symbol(raw: str) -> str:
+ """
+ Extract the classification code from a raw patent IPC string.
+
+ Supports:
+ - 'G01S 5/02 20100101AFI20140127BHEP'
+ - 'C 07C 405/00 A' (legacy EPO spacing)
+ """
+ cleaned = raw.strip()
+ if not cleaned:
+ return cleaned
+
+ legacy = EPO_LEGACY_IPC_RE.match(cleaned)
+ if legacy:
+ section = legacy.group("section").upper()
+ class_num = legacy.group("class_num")
+ subclass_letter = legacy.group("subclass_letter").upper()
+ prefix = f"{section}{class_num}{subclass_letter}"
+ main_group = legacy.group("main_group")
+ subgroup = legacy.group("subgroup")
+ if subgroup is not None:
+ normalized = f"{prefix}{main_group}/{subgroup}"
+ else:
+ normalized = f"{prefix}{main_group}"
+ return display_ipc_symbol(normalized)
+
+ match = IPC_CODE_EXTRACT_RE.match(cleaned)
+ if match:
+ return display_ipc_symbol(normalize_ipc_symbol(match.group(1)))
+
+ match = IPC_SUBCLASS_ONLY_RE.match(cleaned)
+ if match:
+ return match.group(1).upper()
+
+ return cleaned
+
+
+def normalize_ipc_symbol(symbol: str) -> str:
+ """Remove whitespace, e.g. 'H01L 21/02' -> 'H01L21/02'."""
+ return re.sub(r"\s+", "", symbol.strip().upper())
+
+
+def display_ipc_symbol(normalized: str) -> str:
+ """Format for display, e.g. 'H01L21/02' -> 'H01L 21/02'."""
+ match = re.match(r"^([A-HY]\d{2}[A-Z])(\d+)(/\d+)$", normalized, re.IGNORECASE)
+ if match:
+ return f"{match.group(1)} {match.group(2)}{match.group(3)}"
+ match = re.match(r"^([A-HY]\d{2}[A-Z])$", normalized, re.IGNORECASE)
+ if match:
+ return match.group(1)
+ return normalized
+
+
+def parse_ipc_symbol(symbol: str) -> IpcHierarchyKeys:
+ """Derive lookup keys for each hierarchy level from a patent IPC symbol."""
+ cleaned = extract_ipc_symbol(symbol.strip())
+ normalized = normalize_ipc_symbol(cleaned)
+ match = IPC_SYMBOL_RE.match(cleaned) or IPC_SYMBOL_RE.match(normalized)
+
+ if not match:
+ return IpcHierarchyKeys(
+ symbol=cleaned,
+ normalized=normalized,
+ section=None,
+ ipc_class=None,
+ subclass=None,
+ main_group=None,
+ subgroup=None,
+ )
+
+ section = match.group("section").upper()
+ class_num = match.group("class_num")
+ subclass_letter = match.group("subclass_letter").upper()
+ subclass = f"{section}{class_num}{subclass_letter}"
+ ipc_class = f"{section}{class_num}"
+
+ main_group_digits = match.group("main_group")
+ subgroup_digits = match.group("subgroup")
+
+ main_group = None
+ subgroup = None
+ if main_group_digits:
+ base = f"{subclass}{main_group_digits}"
+ if subgroup_digits:
+ full = f"{base}/{subgroup_digits}"
+ if len(subgroup_digits) > 2:
+ subgroup = full
+ main_group = f"{base}/{subgroup_digits[:2]}"
+ else:
+ main_group = full
+ else:
+ main_group = base
+
+ return IpcHierarchyKeys(
+ symbol=cleaned,
+ normalized=normalized,
+ section=section,
+ ipc_class=ipc_class,
+ subclass=subclass,
+ main_group=main_group,
+ subgroup=subgroup,
+ )
+
+
+def _format_level(number: str | None, name: str | None) -> str | None:
+ if not number or not name:
+ return None
+ label = display_ipc_symbol(number)
+ return f"{label} - {name.strip()}"
+
+
+def _lookup_name(level_names: dict[str, str | None], *keys: str | None) -> str | None:
+ for key in keys:
+ if not key:
+ continue
+ if key in level_names and level_names[key]:
+ return level_names[key]
+ normalized = normalize_ipc_symbol(key)
+ if normalized in level_names and level_names[normalized]:
+ return level_names[normalized]
+ return None
+
+
+def build_ipc_classification(
+ keys: IpcHierarchyKeys,
+ names: dict[str, dict[str, str | None]],
+) -> model.IpcClassification:
+ """Combine parsed keys with lookup results from the ipc index."""
+ section_name = _lookup_name(names.get("section", {}), keys.section)
+ class_name = _lookup_name(names.get("class", {}), keys.ipc_class)
+ subclass_name = _lookup_name(names.get("class", {}), keys.subclass)
+ group_name = _lookup_name(
+ names.get("group", {}),
+ keys.main_group,
+ keys.normalized,
+ )
+ subgroup_name = _lookup_name(
+ names.get("subgroup", {}),
+ keys.subgroup,
+ keys.normalized,
+ )
+
+ if not subgroup_name and group_name and keys.subgroup:
+ subgroup_name = group_name
+
+ main_group = None
+ if group_name:
+ main_group = _format_level(keys.main_group or keys.normalized, group_name)
+
+ subgroup = None
+ if subgroup_name:
+ subgroup = _format_level(keys.subgroup or keys.normalized, subgroup_name)
+
+ return model.IpcClassification(
+ symbol=keys.symbol,
+ section=_format_level(keys.section, section_name),
+ ipc_class=_format_level(keys.ipc_class, class_name)
+ if class_name
+ else (display_ipc_symbol(keys.ipc_class) if keys.ipc_class else None),
+ subclass=_format_level(keys.subclass, subclass_name),
+ main_group=main_group,
+ subgroup=subgroup,
+ )
diff --git a/service/src/main/inse/patents/ipc_search_client.py b/service/src/main/inse/patents/ipc_search_client.py
new file mode 100644
index 00000000..834b82af
--- /dev/null
+++ b/service/src/main/inse/patents/ipc_search_client.py
@@ -0,0 +1,142 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+ HTTP client for IPC/CPC classification lookups in the ipc Elasticsearch index.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import httpx
+
+from .. import config
+from . import model
+from inse.exceptions import MissingApiKeyError
+from .ipc_lookup import IpcHierarchyKeys
+from .ipc_lookup import build_ipc_classification
+from .ipc_lookup import parse_ipc_symbol
+
+from inse.integrations import elasticsearch
+from inse.model import ESCluster
+
+IPC_INDEX = "ipc"
+
+_LEVELS: tuple[tuple[str, str, str], ...] = (
+ ("section", "cpc_section_number", "cpc_section_name"),
+ ("class", "cpc_class_number", "cpc_class_name"),
+ ("group", "cpc_group_number", "cpc_group_name"),
+ ("subgroup", "cpc_subgroup_number", "cpc_subgroup_name"),
+)
+
+
+class IpcSearchClient:
+ def __init__(
+ self,
+ base_url: str | None = None,
+ api_key: str | None = None,
+ timeout: float = 30.0,
+ transport: httpx.AsyncBaseTransport | None = None,
+ ):
+ self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
+ self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
+ self.timeout = timeout
+ self.transport = transport
+
+ def _headers(self) -> dict[str, str]:
+ if not self.api_key:
+ raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
+ return {
+ "Authorization": f"ApiKey {self.api_key}",
+ "Content-Type": "application/json",
+ }
+
+ async def resolve_symbols(self, symbols: list[str]) -> dict[str, model.IpcClassification]:
+ """Resolve patent IPC symbols to enriched classification objects."""
+ unique_symbols = list(dict.fromkeys(s.strip() for s in symbols if s and s.strip()))
+ if not unique_symbols:
+ return {}
+
+ parsed = {symbol: parse_ipc_symbol(symbol) for symbol in unique_symbols}
+ names = await self._lookup_all_levels(parsed.values())
+
+ return {
+ symbol: build_ipc_classification(keys, names)
+ for symbol, keys in parsed.items()
+ }
+
+ async def _lookup_all_levels(
+ self,
+ keys_list: list[IpcHierarchyKeys],
+ ) -> dict[str, dict[str, str | None]]:
+ symbols_by_level: dict[str, set[str]] = {
+ "section": set(),
+ "class": set(),
+ "group": set(),
+ "subgroup": set(),
+ }
+
+ for keys in keys_list:
+ if keys.section:
+ symbols_by_level["section"].add(keys.section)
+ if keys.ipc_class:
+ symbols_by_level["class"].add(keys.ipc_class)
+ if keys.subclass:
+ symbols_by_level["class"].add(keys.subclass)
+ if keys.main_group:
+ symbols_by_level["group"].add(keys.main_group)
+ if keys.subgroup:
+ symbols_by_level["subgroup"].add(keys.subgroup)
+ if "/" in keys.normalized:
+ symbols_by_level["group"].add(keys.normalized)
+ symbols_by_level["subgroup"].add(keys.normalized)
+
+ results: dict[str, dict[str, str | None]] = {
+ level: {} for level in symbols_by_level
+ }
+
+ for level, number_field, name_field in _LEVELS:
+ level_symbols = {s for s in symbols_by_level[level] if s}
+ if level_symbols:
+ results[level] = await self._lookup_level(number_field, name_field, level_symbols)
+
+ return results
+
+ async def _lookup_level(
+ self,
+ number_field: str,
+ name_field: str,
+ symbols: set[str],
+ ) -> dict[str, str | None]:
+ if not symbols:
+ return {}
+
+ payload: dict[str, Any] = {
+ "size": min(len(symbols), 100),
+ "query": {
+ "bool": {
+ "should": [
+ {"bool": {"filter": [{"match_phrase": {number_field: symbol}}]}}
+ for symbol in sorted(symbols)
+ ],
+ "minimum_should_match": 1,
+ }
+ },
+ "_source": [number_field, name_field],
+ }
+
+ data = await self._search(payload)
+ found: dict[str, str | None] = {}
+
+ for hit in data.get("hits", {}).get("hits", []):
+ source = hit.get("_source", {})
+ number = source.get(number_field)
+ if not number:
+ continue
+ normalized_number = number.strip().upper()
+ found[normalized_number] = source.get(name_field)
+ found[number.strip()] = source.get(name_field)
+
+ return found
+
+ async def _search(self, payload: dict[str, Any]) -> dict[str, Any]:
+ return await elasticsearch.search(index=IPC_INDEX, body=payload, cluster=ESCluster.INSE)
diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py
index 7e82cc31..9ff5b490 100644
--- a/service/src/main/inse/patents/logic.py
+++ b/service/src/main/inse/patents/logic.py
@@ -1,156 +1,313 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-"""
- Business logic for patent matching by author name.
-"""
-import logging
-
-import httpx
-from fastapi import HTTPException
-from starlette.status import HTTP_502_BAD_GATEWAY
-from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
-
-from ..persons import logic as person_logic
-from ..models.openalex.author import Author
-from . import model
-from .elastic_search_client import MissingApiKeyError
-from .elastic_search_client import PatentSearchClient
-from .name_matching import name_matches
-
-logger = logging.getLogger(__name__)
-
-
-async def get_patents_by_author_id(
- author_id: str,
- client: PatentSearchClient | None = None,
-) -> model.PatentsByAuthorResponse:
- search_client = client or PatentSearchClient()
-
- author = _get_author(author_id)
- if not author:
- return model.PatentsByAuthorResponse(
- author_id=author_id,
- author_name=None,
- patent_count=0,
- patents=[],
- )
-
- author_name = author.display_name
- last_name = _extract_last_name(author_name)
- first_name = _extract_first_name(author_name)
-
- if not last_name:
- return model.PatentsByAuthorResponse(
- author_id=author_id,
- author_name=author_name,
- patent_count=0,
- patents=[],
- )
-
- try:
- epo_data, uspto_data = await _search_both_indices(
- search_client, last_name, first_name
- )
- except MissingApiKeyError as exc:
- raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE,
- detail="Patent search is not configured.") from exc
- except httpx.HTTPError as exc:
- raise HTTPException(status_code=HTTP_502_BAD_GATEWAY,
- detail="Patent search request failed.") from exc
-
- all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
-
- if first_name and last_name:
- all_patents = _filter_patents_by_name(all_patents, first_name, last_name)
-
- return model.PatentsByAuthorResponse(
- author_id=author_id,
- author_name=author_name,
- patent_count=len(all_patents),
- patents=all_patents,
- )
-
-
-async def _search_both_indices(client, last_name, first_name):
- import asyncio
- epo_result, uspto_result = await asyncio.gather(
- client.search_epo(client.epo_query_by_inventor(last_name, first_name)),
- client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)),
- )
- return epo_result, uspto_result
-
-
-def _parse_epo_hits(data: dict) -> list[model.PatentEntry]:
- patents = []
- for hit in data.get("hits", {}).get("hits", []):
- src = hit.get("_source", {})
- inventors = src.get("inventors_name") or []
- applicants = src.get("applicants_name") or []
- ipc = src.get("ipc") or []
- patents.append(model.PatentEntry(
- patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
- source="EPO",
- title=src.get("title_en") or src.get("title_de"),
- abstract=src.get("abstract"),
- publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
- publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
- inventors=inventors if isinstance(inventors, list) else [inventors],
- assignees=applicants if isinstance(applicants, list) else [applicants],
- ipc=ipc if isinstance(ipc, list) else [ipc],
- country=src.get("country", "EP"),
- ))
- return patents
-
-
-def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
- patents = []
- for hit in data.get("hits", {}).get("hits", []):
- src = hit.get("_source", {})
- inventors = src.get("inventors_names") or []
- assignees = src.get("assignees_orgs") or []
- ipc = src.get("ipcr") or []
- patents.append(model.PatentEntry(
- patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
- source="USPTO",
- title=src.get("title"),
- abstract=src.get("abstract"),
- publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
- publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
- inventors=inventors if isinstance(inventors, list) else [inventors],
- assignees=assignees if isinstance(assignees, list) else [assignees],
- ipc=ipc if isinstance(ipc, list) else [ipc],
- country=src.get("country", "US"),
- ))
- return patents
-
-
-def _filter_patents_by_name(
- patents: list[model.PatentEntry],
- first_name: str,
- last_name: str,
-) -> list[model.PatentEntry]:
- """Keep patents where at least one inventor matches the author name."""
- return [
- patent for patent in patents
- if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors)
- ]
-
-
-def _get_author(author_id: str) -> Author | None:
- short_id = author_id.replace("https://openalex.org/", "")
- result = person_logic.search_persons(author_id=short_id)
- return result.results[0] if result.results else None
-
-
-def _extract_last_name(name: str | None) -> str | None:
- if not name:
- return None
- parts = name.strip().split()
- return parts[-1] if parts else None
-
-
-def _extract_first_name(name: str | None) -> str | None:
- if not name:
- return None
- parts = name.strip().split()
- return parts[0] if len(parts) > 1 else None
\ No newline at end of file
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+ Business logic for patent matching by author name.
+"""
+import logging
+import asyncio
+
+import httpx
+
+from ..persons import logic as person_logic
+from ..models.openalex.author import Author
+from . import model
+from inse.exceptions import MissingApiKeyError, ElasticsearchException
+from .elastic_search_client import PatentSearchClient
+from .elastic_search_all_patents_client import AllPatentsSearchClient
+from .ipc_search_client import IpcSearchClient
+from .ipc_lookup import extract_ipc_symbol
+from .name_matching import name_matches
+
+logger = logging.getLogger(__name__)
+
+
+async def get_patent(
+ patent_id: str,
+ title: str,
+ prefix: str,
+ client: PatentSearchClient | None = None,
+) -> model.PatentEntry:
+ search_client = client or PatentSearchClient()
+
+ data = await search_client.get_by_id_or_title(
+ patent_id=patent_id,
+ prefix=prefix,
+ title=title,
+ )
+
+ parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits
+ elements = parse(data)
+
+ if not elements:
+ return None
+ return elements[0]
+
+
+async def get_patents_by_author_id(
+ author_id: str,
+ client: PatentSearchClient | None = None,
+ ipc_client: IpcSearchClient | None = None,
+) -> model.PatentsByAuthorResponse:
+ search_client = client or PatentSearchClient()
+ ipc_search_client = ipc_client or IpcSearchClient()
+
+ author = await _get_author(author_id)
+ if not author:
+ return model.PatentsByAuthorResponse(
+ author_id=author_id,
+ author_name=None,
+ patent_count=0,
+ patents=[],
+ )
+
+ author_name = author.display_name
+ last_name = _extract_last_name(author_name)
+ first_name = _extract_first_name(author_name)
+
+ if not last_name:
+ return model.PatentsByAuthorResponse(
+ author_id=author_id,
+ author_name=author_name,
+ patent_count=0,
+ patents=[],
+ )
+
+ epo_data, uspto_data = await _search_both_indices(
+ search_client, last_name, first_name
+ )
+
+ all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
+
+ if first_name and last_name:
+ all_patents = _filter_patents_by_name(all_patents, first_name, last_name)
+
+ all_patents = _deduplicate_patents(all_patents)
+
+ await _enrich_patents_classifications(all_patents, ipc_search_client)
+
+ return model.PatentsByAuthorResponse(
+ author_id=author_id,
+ author_name=author_name,
+ patent_count=len(all_patents),
+ patents=all_patents,
+ )
+
+
+async def _search_both_indices(client, last_name, first_name):
+ epo_result, uspto_result = await asyncio.gather(
+ client.search_epo(client.epo_query_by_inventor(last_name, first_name)),
+ client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)),
+ )
+ return epo_result, uspto_result
+
+
+def _parse_epo_hits(data: dict) -> list[model.PatentEntry]:
+ patents = []
+ for hit in data.get("hits", {}).get("hits", []):
+ src = hit.get("_source", {})
+ inventors = src.get("inventors_name") or []
+ applicants = src.get("applicants_name") or []
+ ipc = src.get("ipc") or []
+ cpc = src.get("cpc") or []
+ patents.append(model.PatentEntry(
+ patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
+ source="EPO",
+ title=src.get("title_en") or src.get("title_de"),
+ abstract=src.get("abstract"),
+ publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
+ publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
+ application_number=src.get("application_number"),
+ application_date=src.get("application_filing_date"),
+ kind=src.get("kind"),
+ inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
+ assignees=[a for a in (applicants if isinstance(applicants, list) else [applicants]) if a is not None],
+ ipc=_to_classification_strings(ipc),
+ cpc=_to_classification_strings(cpc),
+ country=src.get("country", "EP"),
+ ))
+ return patents
+
+
+def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
+ patents = []
+ for hit in data.get("hits", {}).get("hits", []):
+ src = hit.get("_source", {})
+ inventors = src.get("inventors_names") or []
+ assignees = src.get("assignees_orgs") or []
+ ipc = src.get("ipcr") or []
+ cpc = src.get("cpc") or []
+ patents.append(model.PatentEntry(
+ patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
+ source="USPTO",
+ title=src.get("title"),
+ abstract=src.get("abstract"),
+ publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
+ publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
+ application_number=src.get("application_number"),
+ application_date=str(src.get("application_date")) if src.get("application_date") else None,
+ application_type=src.get("application_type"),
+ number_of_claims=src.get("number_of_claims"),
+ status=src.get("status"),
+ inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
+ assignees=[a for a in (assignees if isinstance(assignees, list) else [assignees]) if a is not None],
+ ipc=_to_classification_strings(ipc),
+ cpc=_to_classification_strings(cpc),
+ country=src.get("country", "US"),
+ ))
+ return patents
+
+
+def _to_classification_strings(value) -> list[str]:
+ if not value:
+ return []
+ items = value if isinstance(value, list) else [value]
+ return [str(item).strip() for item in items if item and str(item).strip()]
+
+
+def _descriptions_for_raw_codes(
+ raw_codes: list[str],
+ resolved: dict[str, model.IpcClassification],
+) -> list[model.IpcClassification]:
+ return [
+ resolved[extract_ipc_symbol(raw)]
+ for raw in raw_codes
+ if extract_ipc_symbol(raw) in resolved
+ ]
+
+
+async def _enrich_patents_classifications(
+ patents: list[model.PatentEntry],
+ ipc_client: IpcSearchClient,
+) -> None:
+ symbols = list(dict.fromkeys(
+ extract_ipc_symbol(raw)
+ for patent in patents
+ for raw in (*patent.ipc, *patent.cpc)
+ ))
+ if not symbols:
+ return
+
+ try:
+ resolved = await ipc_client.resolve_symbols(symbols)
+ except MissingApiKeyError:
+ logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.")
+ return
+ except ElasticsearchException as exc:
+ logger.warning("Classification enrichment failed: %s", exc)
+ return
+ except Exception as exc:
+ logger.exception("Classification enrichment failed unexpectedly: %s", exc)
+ return
+
+ for patent in patents:
+ patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved)
+ patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved)
+
+
+def _filter_patents_by_name(
+ patents: list[model.PatentEntry],
+ first_name: str,
+ last_name: str,
+) -> list[model.PatentEntry]:
+ return [
+ patent for patent in patents
+ if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors)
+ ]
+
+
+def _deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]:
+ seen: set[tuple[str, str, str, str]] = set()
+ deduplicated: list[model.PatentEntry] = []
+
+ for patent in patents:
+ key = _patent_dedup_key(patent)
+ if key in seen:
+ continue
+ seen.add(key)
+ deduplicated.append(patent)
+
+ return deduplicated
+
+
+def _patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]:
+ stage = patent.kind or patent.application_type or ""
+ return (
+ patent.source,
+ patent.patent_id,
+ patent.publication_date or "",
+ stage,
+ )
+
+
+async def _get_author(author_id: str) -> Author | None:
+ short_id = author_id.replace("https://openalex.org/", "")
+ result = await person_logic.search_persons(author_id=short_id)
+ return result.results[0] if result.results else None
+
+
+def _extract_last_name(name: str | None) -> str | None:
+ if not name:
+ return None
+ parts = name.strip().split()
+ return parts[-1] if parts else None
+
+
+def _extract_first_name(name: str | None) -> str | None:
+ if not name:
+ return None
+ parts = name.strip().split()
+ return parts[0] if len(parts) > 1 else None
+
+
+async def get_all_patents(
+ page: int = 0,
+ size: int = 10,
+ search: str | None = None,
+ source: str | None = None,
+ sort_by: str = "date",
+ sort_direction: str = "desc",
+ client: PatentSearchClient | None = None,
+ ipc_client: IpcSearchClient | None = None,
+) -> model.AllPatentsResponse:
+ all_patents_client = AllPatentsSearchClient()
+ ipc_search_client = ipc_client or IpcSearchClient()
+
+ if source == "EPO":
+ epo_data = await all_patents_client.search_epo(
+ all_patents_client.epo_query(page, size, search, sort_direction)
+ )
+ patents = _parse_epo_hits(epo_data)
+ total = epo_data.get("hits", {}).get("total", {}).get("value", 0)
+
+ elif source == "USPTO":
+ uspto_data = await all_patents_client.search_uspto(
+ all_patents_client.uspto_query(page, size, search, sort_direction)
+ )
+ patents = _parse_uspto_hits(uspto_data)
+ total = uspto_data.get("hits", {}).get("total", {}).get("value", 0)
+
+ else:
+ half = size // 2
+ epo_data, uspto_data = await asyncio.gather(
+ all_patents_client.search_epo(
+ all_patents_client.epo_query(page, half, search, sort_direction)
+ ),
+ all_patents_client.search_uspto(
+ all_patents_client.uspto_query(page, half, search, sort_direction)
+ ),
+ )
+ patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
+ total = (
+ epo_data.get("hits", {}).get("total", {}).get("value", 0) +
+ uspto_data.get("hits", {}).get("total", {}).get("value", 0)
+ )
+
+
+ await _enrich_patents_classifications(patents, ipc_search_client)
+
+ return model.AllPatentsResponse(
+ total=total,
+ page=page,
+ size=size,
+ patents=patents,
+ )
\ No newline at end of file
diff --git a/service/src/main/inse/patents/model.py b/service/src/main/inse/patents/model.py
index 31ebc18c..ad26f939 100644
--- a/service/src/main/inse/patents/model.py
+++ b/service/src/main/inse/patents/model.py
@@ -1,4 +1,15 @@
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, ConfigDict, Field
+
+
+class IpcClassification(BaseModel):
+ symbol: str
+ section: str | None = None
+ ipc_class: str | None = Field(default=None, serialization_alias="class")
+ subclass: str | None = None
+ main_group: str | None = None
+ subgroup: str | None = None
+
+ model_config = ConfigDict(populate_by_name=True)
class PatentEntry(BaseModel):
@@ -8,13 +19,29 @@ class PatentEntry(BaseModel):
abstract: str | None = None
publication_date: str | None = None
publication_year: str | None = None
+ application_number: str | None = None
+ application_date: str | None = None
+ kind: str | None = None # EPO only
+ application_type: str | None = None # USPTO only
+ number_of_claims: int | None = None # USPTO only
+ status: str | None = None # USPTO only
inventors: list[str] = Field(default_factory=list)
assignees: list[str] = Field(default_factory=list)
ipc: list[str] = Field(default_factory=list)
+ ipc_descriptions: list[IpcClassification] = Field(default_factory=list)
+ cpc: list[str] = Field(default_factory=list)
+ cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
country: str | None = None
+
class PatentsByAuthorResponse(BaseModel):
author_id: str
author_name: str | None = None
patent_count: int
patents: list[PatentEntry]
+
+class AllPatentsResponse(BaseModel):
+ total: int
+ page: int
+ size: int
+ patents: list[PatentEntry]
\ No newline at end of file
diff --git a/service/src/main/inse/patents/service.py b/service/src/main/inse/patents/service.py
index 53a27446..059fe0d8 100644
--- a/service/src/main/inse/patents/service.py
+++ b/service/src/main/inse/patents/service.py
@@ -1,14 +1,15 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-"""
- REST API for patent matching by author.
-"""
from fastapi import APIRouter
from . import logic
from . import model
-
+from typing import Annotated, Optional
+from fastapi import Path
+from fastapi import Query
router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
+patents_router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
+
@router.get(
"/{author_id}/patents",
@@ -18,3 +19,46 @@ router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
)
async def get_patents_by_author(author_id: str):
return await logic.get_patents_by_author_id(author_id)
+
+@patents_router.get(
+ "/patents/{identifier}",
+ operation_id="getPatentByIdOrTitle",
+ response_model=model.PatentEntry | None,
+ summary="Returns one publication by OpenAlex ID or DOI.",
+)
+async def get_patent_by_identifier(
+ identifier: Annotated[
+ str, Path(description="")
+ ],
+ prefix: Annotated[
+ Optional[str], Query(description="Application Prefix (EP or US)")
+ ] = "",
+ title: Annotated[
+ Optional[str], Query(description="Do we want to fallback to title search if ID and DOI dont work?")
+ ] = "",
+):
+ return await logic.get_patent(patent_id=identifier,prefix=prefix,title=title)
+
+
+@patents_router.get(
+ "/patents",
+ operation_id="getAllPatents",
+ response_model=model.AllPatentsResponse,
+ summary="Get all patents with pagination and search.",
+)
+async def get_all_patents(
+ page: int = 0,
+ size: int = 10,
+ search: str | None = None,
+ source: str | None = None,
+ sort_by: str = "date",
+ sort_direction: str = "desc",
+):
+ return await logic.get_all_patents(
+ page=page,
+ size=size,
+ search=search,
+ source=source,
+ sort_by=sort_by,
+ sort_direction=sort_direction,
+ )
diff --git a/service/src/main/inse/patents/test_elastic_search_client.py b/service/src/main/inse/patents/test_elastic_search_client.py
index 08729ea6..6aea4c7c 100644
--- a/service/src/main/inse/patents/test_elastic_search_client.py
+++ b/service/src/main/inse/patents/test_elastic_search_client.py
@@ -1,11 +1,9 @@
-import httpx
import pytest
-
+from unittest.mock import patch, MagicMock
+from inse.model import ESIndex
from inse.patents.elastic_search_client import (
DEFAULT_SEARCH_SIZE,
- EPO_INDEX,
PatentSearchClient,
- USPTO_INDEX,
)
@@ -28,22 +26,21 @@ def test_epo_query_uses_nested_search_and_name_variants():
def test_uspto_index_is_3_0():
- assert USPTO_INDEX == "uspto_patents_3.0"
- assert EPO_INDEX == "epo_index_1.0"
+ assert ESIndex.USPTO_INDEX == "uspto_patents_3.0"
+ assert ESIndex.EPO_INDEX == "epo_index_1.0"
@pytest.mark.anyio
async def test_search_epo_posts_to_correct_index():
- requests: list[str] = []
+ captured: list[dict] = []
- def handler(request: httpx.Request) -> httpx.Response:
- requests.append(request.url.path)
- return httpx.Response(200, json={"hits": {"hits": []}})
+ def fake_search(index: str, body: dict, cluster=None):
+ captured.append({"index": index, "body": body})
+ return {"hits": {"hits": []}}
- transport = httpx.MockTransport(handler)
- client = PatentSearchClient(api_key="test-key", transport=transport)
+ with patch("inse.integrations.elasticsearch.search", side_effect=fake_search):
+ client = PatentSearchClient(api_key="test-key")
+ await client.search_epo(client.epo_query_by_inventor("Weber", "Christian"))
- await client.search_epo(client.epo_query_by_inventor("Weber", "Christian"))
-
- assert len(requests) == 1
- assert requests[0].endswith(f"/{EPO_INDEX}/_search")
+ assert len(captured) == 1
+ assert captured[0]["index"] == ESIndex.EPO_INDEX
\ No newline at end of file
diff --git a/service/src/main/inse/patents/test_ipc_lookup.py b/service/src/main/inse/patents/test_ipc_lookup.py
new file mode 100644
index 00000000..941ff03b
--- /dev/null
+++ b/service/src/main/inse/patents/test_ipc_lookup.py
@@ -0,0 +1,129 @@
+import pytest
+
+from inse.patents.ipc_lookup import (
+ build_ipc_classification,
+ display_ipc_symbol,
+ extract_ipc_symbol,
+ normalize_ipc_symbol,
+ parse_ipc_symbol,
+)
+from inse.patents.model import IpcClassification
+
+
+@pytest.mark.parametrize(
+ ("raw", "normalized"),
+ [
+ ("H01L 21/02", "H01L21/02"),
+ ("h01l21/02", "H01L21/02"),
+ ("H04L 29/08", "H04L29/08"),
+ ],
+)
+def test_normalize_ipc_symbol(raw: str, normalized: str) -> None:
+ assert normalize_ipc_symbol(raw) == normalized
+
+
+def test_display_ipc_symbol() -> None:
+ assert display_ipc_symbol("H01L21/02") == "H01L 21/02"
+
+
+def test_parse_ipc_symbol_main_group() -> None:
+ keys = parse_ipc_symbol("H01L 21/02")
+ assert keys.section == "H"
+ assert keys.ipc_class == "H01"
+ assert keys.subclass == "H01L"
+ assert keys.main_group == "H01L21/02"
+ assert keys.subgroup is None
+
+
+def test_parse_ipc_symbol_subgroup() -> None:
+ keys = parse_ipc_symbol("H01L 21/0262")
+ assert keys.main_group == "H01L21/02"
+ assert keys.subgroup == "H01L21/0262"
+
+
+def test_extract_ipc_symbol_from_epo_string() -> None:
+ raw = "G01S 5/02 20100101AFI20140127BHEP"
+ assert extract_ipc_symbol(raw) == "G01S 5/02"
+
+
+def test_extract_ipc_symbol_from_cpc_string() -> None:
+ raw = "A61B 5/0713 20130101AFI20140127BHEP"
+ assert extract_ipc_symbol(raw) == "A61B 5/0713"
+
+
+def test_parse_ipc_symbol_from_epo_string() -> None:
+ keys = parse_ipc_symbol("G01S 5/02 20100101AFI20140127BHEP")
+ assert keys.symbol == "G01S 5/02"
+ assert keys.section == "G"
+ assert keys.subclass == "G01S"
+ assert keys.main_group == "G01S5/02"
+
+
+def test_extract_ipc_symbol_subclass_only() -> None:
+ assert extract_ipc_symbol("H01L extra") == "H01L"
+
+
+def test_build_ipc_classification_uses_index_names() -> None:
+ keys = parse_ipc_symbol("H01L 21/02")
+ names = {
+ "section": {"H": "ELECTRICITY"},
+ "class": {"H01L": "SEMICONDUCTOR DEVICES"},
+ "group": {"H01L21/02": "Manufacture or treatment of semiconductor devices"},
+ "subgroup": {},
+ }
+
+ result = build_ipc_classification(keys, names)
+
+ assert result.symbol == "H01L 21/02"
+ assert result.section == "H - ELECTRICITY"
+ assert result.subclass == "H01L - SEMICONDUCTOR DEVICES"
+ assert result.main_group == "H01L 21/02 - Manufacture or treatment of semiconductor devices"
+
+
+def test_extract_ipc_symbol_from_legacy_epo_string() -> None:
+ assert extract_ipc_symbol("C 07C 405/00 A") == "C07C 405/00"
+ assert extract_ipc_symbol("C 07D 317/20 B") == "C07D 317/20"
+
+
+def test_parse_ipc_symbol_from_legacy_epo_string() -> None:
+ keys = parse_ipc_symbol("C 07D 319/06 B")
+ assert keys.symbol == "C07D 319/06"
+ assert keys.section == "C"
+ assert keys.subclass == "C07D"
+ assert keys.main_group == "C07D319/06"
+
+
+def test_build_ipc_classification_uses_subgroup_when_only_subgroup_indexed() -> None:
+ keys = parse_ipc_symbol("G02B 6/42")
+ names = {
+ "section": {"G": "PHYSICS"},
+ "class": {"G02B": "OPTICAL ELEMENTS, SYSTEMS OR APPARATUS"},
+ "group": {},
+ "subgroup": {
+ "G02B6/42": "Coupling light guides with opto-electronic elements",
+ },
+ }
+
+ result = build_ipc_classification(keys, names)
+
+ assert result.main_group is None
+ assert result.subgroup == (
+ "G02B 6/42 - Coupling light guides with opto-electronic elements"
+ )
+
+
+def test_build_ipc_classification_omits_levels_without_index_names() -> None:
+ keys = parse_ipc_symbol("G02B 6/44")
+ result = build_ipc_classification(keys, {})
+
+ assert result.symbol == "G02B 6/44"
+ assert result.section is None
+ assert result.main_group is None
+ assert result.subgroup is None
+
+
+def test_build_ipc_classification_falls_back_to_symbol_only() -> None:
+ keys = parse_ipc_symbol("INVALID")
+ result = build_ipc_classification(keys, {})
+
+ assert result == IpcClassification(symbol="INVALID")
diff --git a/service/src/main/inse/patents/test_ipc_model.py b/service/src/main/inse/patents/test_ipc_model.py
new file mode 100644
index 00000000..5b942cba
--- /dev/null
+++ b/service/src/main/inse/patents/test_ipc_model.py
@@ -0,0 +1,50 @@
+import pytest
+
+from inse.patents import model
+
+
+def test_patent_entry_keeps_raw_ipc_and_separate_descriptions() -> None:
+ entry = model.PatentEntry(
+ patent_id="US123456",
+ source="USPTO",
+ ipc=["H01L 21/02 20100101AFI20140127BHEP"],
+ ipc_descriptions=[
+ model.IpcClassification(
+ symbol="H01L 21/02",
+ section="H - ELECTRICITY",
+ subclass="H01L - SEMICONDUCTOR DEVICES",
+ )
+ ],
+ )
+
+ assert entry.ipc == ["H01L 21/02 20100101AFI20140127BHEP"]
+ assert len(entry.ipc_descriptions) == 1
+ assert entry.ipc_descriptions[0].symbol == "H01L 21/02"
+
+
+def test_patent_entry_ipc_defaults_to_empty_lists() -> None:
+ entry = model.PatentEntry(patent_id="EP1", source="EPO")
+
+ assert entry.ipc == []
+ assert entry.ipc_descriptions == []
+ assert entry.cpc == []
+ assert entry.cpc_descriptions == []
+
+
+def test_patent_entry_keeps_raw_cpc_and_separate_descriptions() -> None:
+ entry = model.PatentEntry(
+ patent_id="US123456",
+ source="USPTO",
+ cpc=["A61B 5/0713 20130101AFI20140127BHEP"],
+ cpc_descriptions=[
+ model.IpcClassification(
+ symbol="A61B 5/0713",
+ section="A - HUMAN NECESSITIES",
+ subclass="A61B - DIAGNOSIS",
+ )
+ ],
+ )
+
+ assert entry.cpc == ["A61B 5/0713 20130101AFI20140127BHEP"]
+ assert len(entry.cpc_descriptions) == 1
+ assert entry.cpc_descriptions[0].symbol == "A61B 5/0713"
diff --git a/service/src/main/inse/patents/test_ipc_search_client.py b/service/src/main/inse/patents/test_ipc_search_client.py
new file mode 100644
index 00000000..78df758e
--- /dev/null
+++ b/service/src/main/inse/patents/test_ipc_search_client.py
@@ -0,0 +1,61 @@
+from unittest.mock import AsyncMock, patch
+import pytest
+
+from inse.patents.ipc_search_client import IPC_INDEX, IpcSearchClient
+
+
+@pytest.fixture
+def anyio_backend():
+ return "asyncio"
+
+
+@pytest.mark.anyio
+async def test_resolve_symbols_posts_to_ipc_index():
+ mock_response = {
+ "hits": {
+ "hits": [
+ {
+ "_source": {
+ "cpc_section_number": "H",
+ "cpc_section_name": "ELECTRICITY",
+ }
+ },
+ {
+ "_source": {
+ "cpc_class_number": "H01L",
+ "cpc_class_name": "SEMICONDUCTOR DEVICES",
+ }
+ },
+ {
+ "_source": {
+ "cpc_group_number": "H01L21/02",
+ "cpc_group_name": "Manufacture or treatment of semiconductor devices",
+ }
+ },
+ ]
+ }
+ }
+
+ with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
+ mock_search.return_value = mock_response
+ client = IpcSearchClient()
+
+ result = await client.resolve_symbols(["H01L 21/02"])
+
+ assert mock_search.call_count >= 1
+ _, kwargs = mock_search.call_args
+ assert kwargs.get("index") == IPC_INDEX
+ assert "H01L 21/02" in result
+ assert result["H01L 21/02"].section == "H - ELECTRICITY"
+ assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES"
+
+
+@pytest.mark.anyio
+async def test_resolve_symbols_does_not_crash_for_subclass_codes():
+ with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
+ mock_search.return_value = {"hits": {"hits": []}}
+ client = IpcSearchClient()
+ result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"])
+
+ assert "A61J 1/14" in result
+ assert "C07D 319/06" in result
diff --git a/service/src/main/inse/patents/test_logic.py b/service/src/main/inse/patents/test_logic.py
new file mode 100644
index 00000000..6c81e218
--- /dev/null
+++ b/service/src/main/inse/patents/test_logic.py
@@ -0,0 +1,91 @@
+from inse.patents import logic, model
+
+
+def _uspto_patent(
+ patent_id: str = "US12508845",
+ publication_date: str = "20251230",
+ application_type: str | None = None,
+) -> model.PatentEntry:
+ return model.PatentEntry(
+ patent_id=patent_id,
+ source="USPTO",
+ title="Vehicle pneumatic tyre and rubber mixture for a tread",
+ publication_date=publication_date,
+ publication_year="2025",
+ application_type=application_type,
+ )
+
+
+def _epo_patent(
+ patent_id: str = "EP2867692",
+ publication_date: str = "20180411",
+ kind: str | None = None,
+) -> model.PatentEntry:
+ return model.PatentEntry(
+ patent_id=patent_id,
+ source="EPO",
+ title="METHOD FOR GENERATING AND USING A MAP",
+ publication_date=publication_date,
+ publication_year="2018",
+ kind=kind,
+ )
+
+
+def test_deduplicate_patents_removes_exact_duplicates() -> None:
+ patents = [_uspto_patent(), _uspto_patent(), _uspto_patent()]
+
+ result = logic._deduplicate_patents(patents)
+
+ assert len(result) == 1
+ assert result[0].patent_id == "US12508845"
+
+
+def test_deduplicate_patents_keeps_distinct_publication_numbers() -> None:
+ patents = [_uspto_patent("US12508845"), _uspto_patent("US12303461")]
+
+ result = logic._deduplicate_patents(patents)
+
+ assert len(result) == 2
+ assert [patent.patent_id for patent in result] == ["US12508845", "US12303461"]
+
+
+def test_deduplicate_patents_keeps_first_occurrence_of_exact_duplicate() -> None:
+ first = _uspto_patent()
+ first.abstract = "First abstract"
+ duplicate = _uspto_patent()
+ duplicate.abstract = "Second abstract"
+
+ result = logic._deduplicate_patents([first, duplicate])
+
+ assert len(result) == 1
+ assert result[0].abstract == "First abstract"
+
+
+def test_deduplicate_patents_keeps_epo_application_and_grant_stages() -> None:
+ application = _epo_patent(publication_date="20161005", kind="A1")
+ grant = _epo_patent(publication_date="20180411", kind="B1")
+
+ result = logic._deduplicate_patents([application, grant])
+
+ assert len(result) == 2
+ assert [patent.kind for patent in result] == ["A1", "B1"]
+
+
+def test_deduplicate_patents_keeps_same_patent_number_with_different_dates() -> None:
+ earlier = _uspto_patent(publication_date="20241230")
+ later = _uspto_patent(publication_date="20251230")
+
+ result = logic._deduplicate_patents([earlier, later])
+
+ assert len(result) == 2
+ assert [patent.publication_date for patent in result] == ["20241230", "20251230"]
+
+
+def test_deduplicate_patents_keeps_same_patent_number_with_different_uspto_types() -> None:
+ utility = _uspto_patent(application_type="utility")
+ reissue = _uspto_patent(application_type="reissue")
+
+ result = logic._deduplicate_patents([utility, reissue])
+
+ assert len(result) == 2
+ assert [patent.application_type for patent in result] == ["utility", "reissue"]
diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py
index 8c5238f9..a7d74fde 100644
--- a/service/src/main/inse/persons/logic.py
+++ b/service/src/main/inse/persons/logic.py
@@ -9,10 +9,15 @@ import logging
import time
from datetime import datetime
from typing import Optional, Callable, Any, List
-from elasticsearch import ApiError, NotFoundError
import hashlib
import httpx
-from fastapi import HTTPException
+from inse.exceptions import (
+ NotFoundException,
+ ElasticsearchException,
+ ElasticsearchNotFoundException,
+ ElasticsearchConnectionException,
+ BadRequestException,
+)
from inse.model import ESIndex
from .. import config
@@ -35,7 +40,7 @@ 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]:
+async def find_ude_author_by_name(display_name: str) -> Optional[dict]:
query = {
"_source": ["display_name"],
"query": {
@@ -63,7 +68,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]:
}
try:
- data = elasticsearch.search(index=INDEX_NAME, body=query)
+ data = await elasticsearch.search(index=INDEX_NAME, body=query)
except Exception:
logger.exception(f"UDE-Lookup für '{display_name}' fehlgeschlagen.")
return None
@@ -89,7 +94,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]:
}
-def get_author_name_by_id(author_id: str) -> Optional[str]:
+async def get_author_name_by_id(author_id: str) -> Optional[str]:
try:
query = {
"_source": ["id", "display_name"],
@@ -99,7 +104,7 @@ def get_author_name_by_id(author_id: str) -> Optional[str]:
"size": 1,
}
- data = elasticsearch.search(index=INDEX_NAME, body=query)
+ data = await elasticsearch.search(index=INDEX_NAME, body=query)
hits = data.get("hits", {}).get("hits", [])
if not hits:
return None
@@ -109,7 +114,7 @@ def get_author_name_by_id(author_id: str) -> Optional[str]:
return None
-def search_persons(
+async def search_persons(
author_id: Optional[str] = None,
query: Optional[str] = None,
) -> AuthorsListResponse:
@@ -131,7 +136,7 @@ def search_persons(
else:
return AuthorsListResponse(results=[], meta=Meta(count=0))
- data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
+ data = await elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
authors = []
for hit in data.get("hits", {}).get("hits", []):
@@ -155,7 +160,7 @@ def search_persons(
return AuthorsListResponse(results=authors, meta=Meta(count=len(authors)))
-def _fetch_author_display_name(author_id: str) -> Optional[str]:
+async def _fetch_author_display_name(author_id: str) -> Optional[str]:
query = {
"query_string": {
@@ -164,7 +169,7 @@ def _fetch_author_display_name(author_id: str) -> Optional[str]:
}
}
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=INDEX_NAME,
query=query,
source=["display_name"],
@@ -178,7 +183,7 @@ def _fetch_author_display_name(author_id: str) -> Optional[str]:
return hits[0].get("_source", {}).get("display_name")
-def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
+async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
WORK_SOURCE_FIELDS = [
"title",
@@ -221,7 +226,7 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
},
}
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
@@ -251,7 +256,7 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
return works, topics
-def _get_publication_years_for_author(author_id: str) -> list[int]:
+async def _get_publication_years_for_author(author_id: str) -> list[int]:
author_url = f"https://openalex.org/{author_id.strip()}"
body = {
@@ -278,7 +283,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]:
},
}
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
@@ -359,8 +364,8 @@ def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics:
)
-def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
- publication_years = _get_publication_years_for_author(author_id)
+async def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
+ publication_years = await _get_publication_years_for_author(author_id)
return _compute_career_metrics(publication_years)
@@ -382,13 +387,13 @@ def _build_papers(works: list) -> list:
return papers
-def get_data_for_bio(author_id: str) -> Optional[dict]:
+async def get_data_for_bio(author_id: str) -> Optional[dict]:
- display_name = _fetch_author_display_name(author_id)
+ display_name = await _fetch_author_display_name(author_id)
if display_name is None:
return None
- works, top_topics = _fetch_works_and_topics(author_id)
+ works, top_topics = await _fetch_works_and_topics(author_id)
papers = _build_papers(works)
author_data = {
@@ -399,9 +404,9 @@ def get_data_for_bio(author_id: str) -> Optional[dict]:
return author_data
-def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
+async def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
start_time = time.time()
- author_data = get_data_for_bio(author_id)
+ author_data = await get_data_for_bio(author_id)
if author_data is None:
return "No person found."
@@ -430,27 +435,23 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s
return bio
-def get_person_by_id(
+async def get_person_by_id(
author_id: str, include: Optional[str] = None
) -> CustomAuthorsListResponse:
source = include.split(",") if include else None
try:
- hit = elasticsearch.get(
+ hit = await elasticsearch.get(
index="openalex-authors",
doc_id=author_id,
source=source,
)
- except NotFoundError:
- raise HTTPException(
- status_code=404, detail=f"Person with id {author_id} not found"
- )
- except ApiError as e:
- raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}")
+ except NotFoundException as e:
+ raise NotFoundException(f"Person with id {author_id} not found") from e
author = util.get_persons_data(hit)
start_time = time.time()
- career_metrics = get_career_metrics_for_author(author_id)
+ career_metrics = await get_career_metrics_for_author(author_id)
elapsed_time = time.time() - start_time
logger.info(
@@ -465,14 +466,14 @@ def get_person_by_id(
return CustomAuthorsListResponse(results=[custom_author])
-def search_persons_by_name(
+async def search_persons_by_name(
author_name: str,
limit: Optional[int] = 10,
page_offset: Optional[int] = 0,
include: Optional[str] = None,
) -> AuthorsListResponse:
if not author_name:
- raise HTTPException(status_code=400, detail="name must be provided")
+ raise BadRequestException("name must be provided")
search_query = {
"bool": {
"should": [
@@ -495,7 +496,7 @@ def search_persons_by_name(
}
}
try:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index="openalex-authors",
query=search_query,
offset=page_offset,
@@ -504,10 +505,8 @@ def search_persons_by_name(
track_total_hits=True,
)
- except Exception as e:
- raise HTTPException(
- status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
- )
+ except ElasticsearchException as e:
+ raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
hits = response.get("hits", {}).get("hits", [])
@@ -518,11 +517,11 @@ def search_persons_by_name(
)
-def search_persons_autocomplete(
+async def search_persons_autocomplete(
author_name: str, limit: Optional[int] = 5, include: Optional[str] = None
) -> AuthorsListResponse:
if not author_name:
- raise HTTPException(status_code=400, detail="name must be provided")
+ raise BadRequestException("name must be provided")
search_query = {
"function_score": {
"query": {
@@ -555,11 +554,9 @@ def search_persons_autocomplete(
"collapse": collapse,
}
try:
- response = elasticsearch.search(index="openalex-authors", body=body)
- except Exception as e:
- raise HTTPException(
- status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
- )
+ response = await elasticsearch.search(index="openalex-authors", body=body)
+ except ElasticsearchException as e:
+ raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
hits = response.get("hits", {}).get("hits", [])
@@ -587,7 +584,7 @@ def search_persons_autocomplete(
return AuthorsListResponse(results=persons)
-def search_persons_by_institution(
+async def search_persons_by_institution(
institution_name: str,
limit: Optional[int] = 10,
page_offset: Optional[int] = 0,
@@ -595,7 +592,7 @@ def search_persons_by_institution(
) -> AuthorsListResponse:
if not institution_name:
- raise HTTPException(status_code=400, detail="institution_name must be provided")
+ raise BadRequestException("institution_name must be provided")
search_query = {
"nested": {
@@ -614,7 +611,7 @@ def search_persons_by_institution(
}
}
try:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index="openalex-authors",
query=search_query,
source=include.split(",") if include else True,
@@ -624,10 +621,8 @@ def search_persons_by_institution(
track_total_hits=True,
)
- except Exception as e:
- raise HTTPException(
- status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
- )
+ except ElasticsearchException as e:
+ raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
hits = response.get("hits", {}).get("hits", [])
persons = [util.get_persons_data(hit) for hit in hits]
@@ -679,7 +674,7 @@ def _enrich_author_data(author_data) -> Optional[CustomAuthor]:
return author
-def advanced_search_persons(
+async def advanced_search_persons(
query: Optional[str] = None,
institution_name: Optional[str] = None,
sort_by: Optional[str] = None,
@@ -707,39 +702,20 @@ def advanced_search_persons(
filter_mode=filter_mode,
filter_year=filter_year,
)
- response_dict = elasticsearch.search(
+ response_dict = await elasticsearch.search(
index=INDEX_NAME,
body=query_body,
)
- except httpx.HTTPStatusError as e:
- if e.response.status_code == 404:
- logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.")
- return CustomAuthorsListResponse(
- results=[], meta=Meta(count=0, page=page, per_page=page_size)
- )
- elif e.response.status_code == 400:
- logger.error(f"Elasticsearch request error: {str(e)}")
- raise HTTPException(
- status_code=400, detail=f"Elasticsearch request error: {str(e)}"
- )
- else:
- logger.error(f"Elasticsearch API error: {str(e)}")
- raise HTTPException(
- status_code=500, detail=f"Elasticsearch API error: {str(e)}"
- )
- except httpx.RequestError as e:
- logger.error(f"Elasticsearch connection/request error: {str(e)}")
- raise HTTPException(
- status_code=500, detail=f"Elasticsearch connection/request error: {str(e)}"
+ except ElasticsearchNotFoundException:
+ logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.")
+ return CustomAuthorsListResponse(
+ results=[], meta=Meta(count=0, page=page, per_page=page_size)
)
- except Exception as e:
+ except ElasticsearchException as e:
logger.error(f"Elasticsearch search failed: {str(e)}")
- raise HTTPException(
- status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
- )
+ raise
total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
hits = response_dict.get("hits", {}).get("hits", [])
- total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
include_career_metrics = include is None or "career_metrics" in include
results = []
@@ -749,7 +725,7 @@ def advanced_search_persons(
if custom_author:
if include_career_metrics:
start_time = time.time()
- custom_author.career_metrics = get_career_metrics_for_author(
+ custom_author.career_metrics = await get_career_metrics_for_author(
custom_author.id
)
elapsed_time = time.time() - start_time
diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py
index a1e08f62..dfdf7fd7 100644
--- a/service/src/main/inse/persons/service.py
+++ b/service/src/main/inse/persons/service.py
@@ -29,7 +29,7 @@ router = APIRouter(
summary="Searches for persons by ID or name.",
response_model_exclude_none=True,
)
-def search_persons(
+async def search_persons(
author_id: Annotated[
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
] = None,
@@ -53,7 +53,7 @@ def search_persons(
if include
else None
)
- return logic.search_persons(author_id, query)
+ return await logic.search_persons(author_id, query)
@router.get(
@@ -62,7 +62,7 @@ def search_persons(
response_model=model.PersonBio,
summary="Generates a bio for a person by author ID.",
)
-def generate_person_bio(
+async def generate_person_bio(
author_id: Annotated[
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
],
@@ -79,7 +79,7 @@ def generate_person_bio(
if include
else None
)
- bio = logic.generate_person_bio(author_id, include_set)
+ bio = await logic.generate_person_bio(author_id, include_set)
return model.PersonBio(bio=bio)
@router.get(
@@ -89,7 +89,7 @@ def generate_person_bio(
summary="Searches for person by ID.",
tags=["Persons"],
)
-def get_person_by_id(
+async def get_person_by_id(
id: Annotated[
str, Path(description="OpenAlex author ID", examples=["A5093075883"])
],
@@ -104,7 +104,7 @@ def get_person_by_id(
),
] = None,
):
- return logic.get_person_by_id(author_id=id, include=include)
+ return await logic.get_person_by_id(author_id=id, include=include)
@router.get(
@@ -114,7 +114,7 @@ def get_person_by_id(
summary="Searches for person by name.",
tags=["Persons"],
)
-def search_persons_by_name(
+async def search_persons_by_name(
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
include: Annotated[
Optional[str],
@@ -129,24 +129,25 @@ def search_persons_by_name(
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
):
- return logic.search_persons_by_name(author_name=author_name, include=include,page_offset=page_offset,limit=limit)
+ return await logic.search_persons_by_name(author_name=author_name, include=include, page_offset=page_offset, limit=limit)
+
@router.get(
'/persons/autocomplete',
operation_id='searchPersonsAutocomplete',
response_model=AuthorsListResponse,
summary='Searches for person by name.',
- tags=[ 'Persons' ])
-def search_persons_autocomplete(
+ tags=['Persons'])
+async def search_persons_autocomplete(
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
include : Annotated[Optional[str], Query(
- description=(
- "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
- "last_known_institutions, ..."
- ),
- example="topics_full,topic_share"
- )]):
- return logic.search_persons_autocomplete(author_name=author_name,include=include)
+ description=(
+ "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
+ "last_known_institutions, ..."
+ ),
+ example="topics_full,topic_share"
+ )]):
+ return await logic.search_persons_autocomplete(author_name=author_name, include=include)
@router.get(
@@ -156,7 +157,7 @@ def search_persons_autocomplete(
summary="Searches for persons by institution name.",
tags=["Persons"],
)
-def search_persons_by_institution(
+async def search_persons_by_institution(
institution_name: Annotated[
str, Query(description="Institution name (e.g., MIT, Oxford University)")
],
@@ -173,7 +174,8 @@ def search_persons_by_institution(
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
):
- return logic.search_persons_by_institution(institution_name, include=include,page_offset=page_offset,limit=limit)
+ return await logic.search_persons_by_institution(institution_name, include=include, page_offset=page_offset, limit=limit)
+
@router.get(
"/persons/search-list",
@@ -183,7 +185,7 @@ def search_persons_by_institution(
response_model_exclude_none=True,
tags=["Persons"],
)
-def search_persons_list(
+async def search_persons_list(
query: Annotated[
Optional[str], Query(description="Search query (e.g., Arman AND Arzani)")
] = None,
@@ -227,7 +229,7 @@ def search_persons_list(
if include
else None
)
- return logic.advanced_search_persons(
+ return await logic.advanced_search_persons(
query=query,
institution_name=institution_name,
sort_by=sort_by,
diff --git a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py
new file mode 100644
index 00000000..cb120418
--- /dev/null
+++ b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py
@@ -0,0 +1,281 @@
+import logging
+import asyncio
+from typing import Any, Dict, List, Optional, Union
+
+from inse.config import get_settings
+from inse.integrations import elasticsearch
+from inse.model import ESCluster, ESIndex
+
+# Import base models
+from inse.models.cordis_eu_project import CordisEuProject
+
+# Import FP7 models
+from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project
+from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization
+from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication
+from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR
+from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary
+from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic
+from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink
+from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc
+from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis
+from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
+
+# Import H2020 models
+from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project
+from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization
+from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication
+from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable
+from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary
+from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic
+from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink
+from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc
+from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis
+from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI
+from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
+
+# Import Horizon Europe models
+from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject
+from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization
+from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication
+from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable
+from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary
+from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic
+from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink
+from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
+from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
+from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
+
+settings = get_settings()
+logger = logging.getLogger(__name__)
+logger.setLevel(settings.logging_level)
+
+# Entity config
+_FP7_ENTITY_CONFIGS = [
+ {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, "model_class": Fp7Organization},
+ {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_FP7_PUBLICATIONS, "model_class": Fp7Publication},
+ {"key": "iprs", "index_pattern": ESIndex.CORDIS_EU_FP7_PROJECT_IPRS, "model_class": Fp7ProjectIPR},
+ {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_FP7_REPORT_SUMMARIES, "model_class": Fp7ReportSummary},
+ {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_FP7_TOPICS, "model_class": Fp7Topic},
+ {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_FP7_WEB_LINKS, "model_class": Fp7WebLink},
+ {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_FP7_EUROSCIVOC, "model_class": Fp7EurosciVoc},
+ {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_FP7_LEGAL_BASIS, "model_class": Fp7LegalBasis},
+]
+
+_H2020_ENTITY_CONFIGS = [
+ {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, "model_class": H2020Organization},
+ {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, "model_class": H2020Publication},
+ {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_DELIVERABLES, "model_class": H2020Deliverable},
+ {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES, "model_class": H2020ReportSummary},
+ {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, "model_class": H2020Topic},
+ {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_WEB_LINKS, "model_class": H2020WebLink},
+ {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, "model_class": H2020EurosciVoc},
+ {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_LEGAL_BASIS, "model_class": H2020LegalBasis},
+ {"key": "erc_principal_investigators", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ERC_PIS, "model_class": H2020ErcPI},
+]
+
+_HEU_ENTITY_CONFIGS = [
+ {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, "model_class": HEUOrganization},
+ {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, "model_class": HEUPublication},
+ {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_DELIVERABLES, "model_class": HEUDeliverable},
+ {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES, "model_class": HEUReportSummary},
+ {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, "model_class": HEUTopic},
+ {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_WEB_LINKS, "model_class": HEUWebLink},
+ {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc},
+ {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis},
+]
+
+async def get_enriched_cordis_project_by_id(
+ project_id: str,
+) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
+ """
+ Fetches and enriches a single Cordis EU project by its ID across all programme types.
+
+ Args:
+ project_id: The project ID to fetch.
+
+ Returns:
+ The enriched detailed project model, or None if not found.
+ """
+ if not project_id:
+ return None
+
+ query = {"bool": {"filter": [{"term": {"id": project_id}}]}}
+
+ response = await elasticsearch.search(
+ query=query,
+ index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
+ cluster=ESCluster.INSE,
+ size=1,
+ )
+
+ hits = response.get("hits", {}).get("hits", [])
+ if not hits:
+ logger.info(f"No project found with ID: {project_id}")
+ return None
+
+ hit = hits[0]
+ index = hit.get("_index", "")
+ source = hit.get("_source", {})
+
+ program_type = _determine_program_type_from_index(index)
+
+ enrichers = {
+ "fp7": _enrich_fp7_project,
+ "h2020": _enrich_h2020_project,
+ "heu": _enrich_heu_project,
+ }
+
+ enricher = enrichers.get(program_type)
+ if enricher is None:
+ logger.warning(f"Unknown programme type for index: {index}")
+ return CordisEuProject.model_validate(source)
+
+ return await enricher(project_id, source)
+
+# helpers
+def _determine_program_type_from_index(index: str) -> str:
+ """Determines the programme type from the Elasticsearch index name."""
+ index_lower = index.lower()
+ if "fp7" in index_lower:
+ return "fp7"
+ if "horizon_2020" in index_lower:
+ return "h2020"
+ if "heu" in index_lower or "horizon_europe" in index_lower:
+ return "heu"
+ return "unknown"
+
+
+async def _fetch_related_entities_parallel(
+ project_id: str,
+ entity_configs: List[Dict[str, Any]],
+) -> Dict[str, List[Any]]:
+ """
+ Fetches all related entity types for a project in parallel.
+
+ Args:
+ project_id: The project ID to fetch entities for.
+ entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'.
+
+ Returns:
+ Dictionary mapping each config 'key' to a list of validated entities.
+ """
+ async def _fetch_one(config: Dict[str, Any]):
+ entities = await _fetch_related_entities(
+ project_ids=[project_id],
+ index_pattern=config["index_pattern"],
+ model_class=config["model_class"],
+ )
+ return config["key"], entities.get(project_id, [])
+
+ tasks = [_fetch_one(cfg) for cfg in entity_configs]
+ completed = await asyncio.gather(*tasks, return_exceptions=True)
+
+ results: Dict[str, List[Any]] = {}
+ for cfg, res in zip(entity_configs, completed):
+ key = cfg["key"]
+ if isinstance(res, Exception):
+ logger.error(f"Parallel fetch failed for '{key}': {res}")
+ results[key] = []
+ else:
+ key_name, data = res
+ results[key_name] = data
+
+ return results
+
+
+async def _fetch_related_entities(
+ project_ids: List[str],
+ index_pattern: str,
+ model_class: Any,
+) -> Dict[str, List[Any]]:
+ """
+ Fetches and groups related entities from Elasticsearch by project ID.
+
+ Args:
+ project_ids: List of project IDs to fetch entities for.
+ index_pattern: The index pattern to search (supports wildcards).
+ model_class: The Pydantic model class to validate against.
+
+ Returns:
+ Dictionary mapping project IDs to lists of validated entities.
+ """
+ query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}}
+
+ try:
+ response = await elasticsearch.search(
+ query=query,
+ index=index_pattern,
+ cluster=ESCluster.INSE,
+ size=10000,
+ )
+ except Exception as e:
+ logger.warning(f"Failed to fetch from {index_pattern}: {e}")
+ return {}
+
+ grouped: Dict[str, List[Any]] = {}
+
+ for hit in response.get("hits", {}).get("hits", []):
+ source = hit.get("_source", {})
+ project_id = source.get("projectID")
+
+ if not project_id:
+ continue
+
+ grouped.setdefault(project_id, [])
+
+ try:
+ entity = model_class.model_validate(source)
+ grouped[project_id].append(entity)
+ except Exception as e:
+ logger.warning(f"Failed to validate {model_class.__name__} for project {project_id}: {e}")
+
+ return grouped
+
+
+async def _enrich_fp7_project(
+ project_id: str,
+ project_source: Dict[str, Any],
+) -> Optional[Fp7ProjectDetails]:
+ """Enriches a single FP7 project with all related data."""
+ try:
+ project = Fp7Project.model_validate(project_source)
+ except Exception as e:
+ logger.error(f"Failed to validate FP7 project {project_id}: {e}")
+ return None
+
+ related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
+
+ return Fp7ProjectDetails.from_project_with_relations(project=project, **related)
+
+
+async def _enrich_h2020_project(
+ project_id: str,
+ project_source: Dict[str, Any],
+) -> Optional[H2020ProjectDetails]:
+ """Enriches a single H2020 project with all related data."""
+ try:
+ project = H2020Project.model_validate(project_source)
+ except Exception as e:
+ logger.error(f"Failed to validate H2020 project {project_id}: {e}")
+ return None
+
+ related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
+
+ return H2020ProjectDetails.from_project_with_relations(project=project, **related)
+
+
+async def _enrich_heu_project(
+ project_id: str,
+ project_source: Dict[str, Any],
+) -> Optional[HEUProjectDetails]:
+ """Enriches a single Horizon Europe project with all related data."""
+ try:
+ project = HEUProject.model_validate(project_source)
+ except Exception as e:
+ logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}")
+ return None
+
+ related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
+
+ return HEUProjectDetails.from_project_with_relations(project=project, **related)
\ No newline at end of file
diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py
index d0957d4d..c95ada07 100644
--- a/service/src/main/inse/projects/model.py
+++ b/service/src/main/inse/projects/model.py
@@ -9,7 +9,10 @@ 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
-
+from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
+from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
+from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
+from typing import Union
class ProjectType(StrEnum):
BUND = "bund"
@@ -164,7 +167,25 @@ class CordisEuProjectPage(Page):
default_factory=list, description="The CORDIS EU projects on this page."
)
-
+class EuCordisProjectResponse(BaseModel):
+ """
+ Response model for EU Cordis project endpoints.
+ """
+ success: bool = Field(description="Indicates if the request was successful")
+ project_type: Optional[str] = Field(
+ default=None,
+ description="The type of project: 'fp7', 'h2020', or 'heu'"
+ )
+ eu_project_data: Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]] = Field(
+ default=None,
+ description="The project data"
+ )
+ error: Optional[str] = Field(
+ default=None,
+ description="Error message if the request failed"
+ )
+
+
class FundingProject(BaseModel):
type: ProjectType = Field(
description="The type of the project.",
diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py
index a53c2f1f..bbb09625 100644
--- a/service/src/main/inse/projects/projects_search_client.py
+++ b/service/src/main/inse/projects/projects_search_client.py
@@ -3,7 +3,7 @@ import logging
from typing import Any, Dict, List, Optional, Set, Tuple
import httpx
-
+import urllib
from inse.config import get_settings
from inse.models.bund_project import BundProject
from inse.projects.model import (
@@ -22,14 +22,16 @@ from inse.projects.model import (
ProjectsSortBy,
SortDirection,
)
-
+from inse.projects.eu_cordis_projects_enrichment_client import get_enriched_cordis_project_by_id
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
-
-
+from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
+from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
+from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
+from typing import Union
settings = get_settings()
logger = logging.getLogger(__name__)
@@ -99,7 +101,7 @@ DFG_PERSON_FIELDS: List[str] = [
# BUND
-def search_bund_projects(
+async def search_bund_projects(
filter_properties: ProjectsFilteringProperties,
institution_names: List[str] = [],
) -> BundProjectPage:
@@ -158,7 +160,7 @@ def search_bund_projects(
}
]
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
query=query,
sort=sort,
@@ -192,8 +194,8 @@ def _complete_response_to_bund_project_page(
return BundProjectPage(elements=elements, total=total_hits, page=page, size=size)
-def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
- """Fetches the details of a single Bund project based on its project ID.
+async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
+ """Decodes project_id and fetches the details of a single Bund project based on its project ID.
Args:
project_id (str): The ID of the project to fetch.
@@ -201,9 +203,11 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
Returns:
Optional[BundProjectDetails]: The details of the project if found, otherwise None.
"""
- query = {"term": {"Förderkennzeichen.keyword": {"value": project_id}}}
+
+ decoded_id = urllib.parse.unquote(project_id)
+ query = {"term": {"Förderkennzeichen.keyword": {"value": decoded_id}}}
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
query=query,
size=1,
@@ -220,7 +224,7 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
# EU
-def get_eu_organization_project_contributions(
+async def get_eu_organization_project_contributions(
organization_names: List[str],
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
@@ -237,11 +241,11 @@ def get_eu_organization_project_contributions(
# 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_project_contributions = await get_eu_organization_contributions(
organization_names=organization_names,
)
- total_projects, projects = get_eu_organization_projects(
+ total_projects, projects = await get_eu_organization_projects(
project_contributions=list(organization_project_contributions.values()),
projects_filtering_properties=projects_filtering_properties,
)
@@ -267,7 +271,7 @@ def get_eu_organization_project_contributions(
)
-def get_eu_organization_contributions(
+async 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.
@@ -289,7 +293,7 @@ def get_eu_organization_contributions(
}
}
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
@@ -339,7 +343,7 @@ def _process_organization_project_contributions(
return project_contributions
-def get_eu_organization_projects(
+async def get_eu_organization_projects(
project_contributions: List[EuOrganizationShort],
projects_filtering_properties: ProjectsFilteringProperties,
) -> Tuple[int, Dict[str, EuProjectShort]]:
@@ -384,7 +388,7 @@ def get_eu_organization_projects(
# Project contributions have been filtered before based on ecContribution
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
@@ -392,7 +396,7 @@ def get_eu_organization_projects(
size=10000,
)
else:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
@@ -492,7 +496,7 @@ def _get_raw_doi(doi: str) -> str:
return doi
-def get_cordis_eu_publications_by_dois(dois: List[str]):
+async def get_cordis_eu_publications_by_dois(dois: List[str]):
"""Retrieves Cordis EU publications associated with the given list of DOIs.
Args:
@@ -504,7 +508,7 @@ def get_cordis_eu_publications_by_dois(dois: List[str]):
raw_dois = [_get_raw_doi(doi) for doi in dois]
query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}}
- response = elasticsearch.search(
+ response = await elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
cluster=ESCluster.INSE,
@@ -515,7 +519,7 @@ def get_cordis_eu_publications_by_dois(dois: List[str]):
return response
-def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
+async 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:
@@ -524,7 +528,7 @@ def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
Returns:
List[str]: The list of project IDs.
"""
- response = get_cordis_eu_publications_by_dois(dois=dois)
+ response = await get_cordis_eu_publications_by_dois(dois=dois)
hits_block = response.get("hits", {})
project_ids = set()
for hit in hits_block.get("hits", []):
@@ -535,12 +539,12 @@ def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
return list(project_ids)
-def get_cordis_eu_projects_by_project_ids(
+async def get_cordis_eu_projects_by_project_ids(
project_ids: List[str],
) -> CordisEuProjectPage:
query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}}
- response = elasticsearch.search(
+ response = await elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
@@ -557,10 +561,26 @@ def get_cordis_eu_projects_by_project_ids(
)
+async def get_eu_cordis_projects_by_id(
+ project_id: str,
+) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
+ """
+ Fetches and enriches a single Cordis EU project by its ID.
+
+ Args:
+ project_id: The project ID to fetch
+
+ Returns:
+ The enriched project details, or None if not found
+ """
+ enriched_project = await get_enriched_cordis_project_by_id(
+ project_id=project_id
+ )
+ return enriched_project
# DFG
-def search_dfg_projects(
+async def search_dfg_projects(
page: int,
size: int,
names: Optional[List[str]] = None,
@@ -730,7 +750,7 @@ def search_dfg_projects(
body["sort"] = [sort_config]
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=ESIndex.PROJECTS_DFG_ALL,
body=body,
)
@@ -756,7 +776,7 @@ def _complete_response_to_dfg_project_page(
return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size)
-def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
+async 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:
@@ -767,7 +787,7 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
"""
query = {"ids": {"values": [project_id]}}
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=ESIndex.PROJECTS_DFG_ALL,
query=query,
size=1,
@@ -784,7 +804,7 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
# All
-def search_all_projects(
+async def search_all_projects(
projects_filtering_properties: ProjectsFilteringProperties,
selected_project_types: Optional[Set[ProjectType]] = None,
) -> FundingProjectPage:
@@ -862,7 +882,7 @@ def search_all_projects(
size = projects_filtering_properties.size
page = projects_filtering_properties.page
offset = page * size
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=index,
size=size,
offset=offset,
diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py
index 509f5d8b..fcd91844 100644
--- a/service/src/main/inse/projects/router.py
+++ b/service/src/main/inse/projects/router.py
@@ -15,6 +15,7 @@ from inse.projects.model import (
ProjectsFilteringProperties,
ProjectsSortBy,
SortDirection,
+ EuCordisProjectResponse
)
from inse.models.dfg_project_details import DfgProjectDetails
from inse.models.bund_project_details import BundProjectDetails
@@ -26,6 +27,11 @@ from inse.institutions.institutions_search_client import (
)
from inse.institutions.router import get_institutions_search_client
+from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
+from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
+from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
+from typing import Union
+
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
@@ -45,13 +51,13 @@ router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
},
response_model_by_alias=False,
)
-def get_eu_projects_for_author(
+async def get_eu_projects_for_author(
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(
+ return await projects_service.search_cordis_eu_projects_for_author_id(
raw_oa_author_id=raw_oa_author_id,
)
@@ -79,7 +85,7 @@ async def search_bund_projects(
Body(description="The filtering properties for the projects search."),
],
) -> BundProjectPage:
- return projects_service.search_bund_projects(
+ return await projects_service.search_bund_projects(
institutions_search_client=institutions_search_client,
filtering_properties=filtering_properties,
)
@@ -99,11 +105,11 @@ async def search_bund_projects(
},
response_model_by_alias=False,
)
-def get_single_dfg_project(
+async 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 projects_service.get_single_dfg_project(
+ return await projects_service.get_single_dfg_project(
project_id=id,
)
@@ -122,15 +128,93 @@ def get_single_dfg_project(
},
response_model_by_alias=False,
)
-def get_single_bund_project(
+async 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 projects_service.get_single_bund_project(
+ return await projects_service.get_single_bund_project(
project_id=id,
)
+@router.get(
+ "/eu/{id}",
+ summary="Get a single EU Cordis project.",
+ description="Returns a single EU Cordis project based on its ID.",
+ operation_id="getSingleEuCordisProject",
+ responses={
+ status.HTTP_200_OK: {
+ "description": "Successful Response",
+ "model": EuCordisProjectResponse,
+ },
+ status.HTTP_404_NOT_FOUND: {
+ "description": "Project not found",
+ "model": EuCordisProjectResponse
+ },
+ status.HTTP_500_INTERNAL_SERVER_ERROR: {
+ "description": "Internal server error",
+ "model": EuCordisProjectResponse
+ }
+ },
+)
+async def get_single_eu_cordis_project(
+ id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")],
+) -> EuCordisProjectResponse:
+ """
+ Get a single EU Cordis project by ID.
+ Returns a wrapper response containing the project data or error information.
+ """
+ logger.debug(f"Received request to get single EU Cordis project for id={id}")
+
+ try:
+ # Get the project from the service
+ project = await projects_service.get_single_eu_cordis_project(project_id=id)
+
+ # Check if project exists
+ if project is None:
+ logger.warning(f"Project with ID {id} not found")
+ return EuCordisProjectResponse(
+ success=False,
+ project_type=None,
+ eu_project_data=None,
+ error=f"Project with ID {id} not found"
+ )
+
+ # Determine the project type
+ if isinstance(project, Fp7ProjectDetails):
+ project_type = "fp7"
+ elif isinstance(project, H2020ProjectDetails):
+ project_type = "h2020"
+ elif isinstance(project, HEUProjectDetails):
+ project_type = "heu"
+ else:
+ # Unknown project type - maybe it's the base CordisEuProject
+ logger.warning(f"Unknown project type for ID {id}: {type(project)}")
+ return EuCordisProjectResponse(
+ success=False,
+ project_type=None,
+ eu_project_data=None,
+ error=f"Unknown project type for ID {id}"
+ )
+
+ # Return success with the project data
+ return EuCordisProjectResponse(
+ success=True,
+ project_type=project_type,
+ eu_project_data=project,
+ error=None
+ )
+
+ except Exception as e:
+ logger.error(f"Error retrieving project with ID {id}: {str(e)}", exc_info=True)
+ return EuCordisProjectResponse(
+ success=False,
+ project_type=None,
+ data=None,
+ error=f"Internal server error: {str(e)}"
+ )
+
+
@router.get(
"/institution/bund/funding-over-time",
summary="Get funding over time for bund projects.",
@@ -145,7 +229,7 @@ def get_single_bund_project(
},
response_model_by_alias=False,
)
-def get_institution_bund_projects_funding_over_time(
+async def get_institution_bund_projects_funding_over_time(
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -153,7 +237,7 @@ def get_institution_bund_projects_funding_over_time(
str, Query(description="The institution ID to filter by.")
],
) -> InstitutionFunderSummary:
- return projects_service.get_institution_bund_projects_funding_over_time(
+ return await projects_service.get_institution_bund_projects_funding_over_time(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
)
@@ -182,7 +266,7 @@ async def search_cordis_eu_projects(
Body(description="The filtering properties for the projects search."),
],
) -> EuOrganizationProjectSummaryPage:
- return projects_service.search_cordis_eu_projects(
+ return await projects_service.search_cordis_eu_projects(
institutions_search_client=institutions_search_client,
projects_filtering_properties=projects_filtering_properties,
)
@@ -274,7 +358,7 @@ async def get_dfg_projects(
},
response_model_by_alias=False,
)
-def search_projects(
+async 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[
@@ -293,7 +377,7 @@ def search_projects(
SortDirection, Query(description="The sort direction (asc or desc).")
] = SortDirection.ASC,
) -> FundingProjectPage:
- return projects_service.search_all_projects(
+ return await 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 75c72e0e..e8d83281 100644
--- a/service/src/main/inse/projects/service.py
+++ b/service/src/main/inse/projects/service.py
@@ -17,6 +17,7 @@ from inse.projects.model import (
ProjectsFilteringProperties,
ProjectsSortBy,
SortDirection,
+ CordisEuProject
)
from inse.models.dfg_project_details import DfgProjectDetails
from inse.models.bund_project_details import BundProjectDetails
@@ -26,12 +27,15 @@ 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
-
+from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
+from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
+from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
+from typing import Union
logger = logging.getLogger(__name__)
-def search_all_projects(
+async def search_all_projects(
page: int,
size: int,
sort_by: ProjectsSortBy,
@@ -39,7 +43,7 @@ def search_all_projects(
selected_project_types: Optional[Set[ProjectType]] = None,
title: Optional[str] = None,
) -> FundingProjectPage:
- return projects_search_client.search_all_projects(
+ return await projects_search_client.search_all_projects(
projects_filtering_properties=ProjectsFilteringProperties(
project_type=ProjectType.EU, # placeholder, shall be ignored in search_all_projects
page=page,
@@ -52,7 +56,7 @@ def search_all_projects(
)
-def search_bund_projects(
+async def search_bund_projects(
institutions_search_client: InstitutionsSearchClient,
filtering_properties: ProjectsFilteringProperties,
) -> BundProjectPage:
@@ -65,13 +69,13 @@ def search_bund_projects(
f"search_bund_projects called with filtering_properties: {filtering_properties}"
)
- return get_bund_projects_by_institution_id(
+ return await get_bund_projects_by_institution_id(
institutions_search_client=institutions_search_client,
filtering_properties=filtering_properties,
)
-def get_bund_projects_by_institution_id(
+async def get_bund_projects_by_institution_id(
institutions_search_client: InstitutionsSearchClient,
filtering_properties: ProjectsFilteringProperties,
) -> BundProjectPage:
@@ -89,7 +93,7 @@ def get_bund_projects_by_institution_id(
logger.debug(
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(
+ response = await projects_search_client.search_bund_projects(
institution_names=institution_aliases,
filter_properties=filtering_properties,
)
@@ -97,7 +101,7 @@ def get_bund_projects_by_institution_id(
return response
-def search_cordis_eu_projects(
+async def search_cordis_eu_projects(
institutions_search_client: InstitutionsSearchClient,
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
@@ -106,13 +110,13 @@ def search_cordis_eu_projects(
f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'."
)
- return get_cordis_eu_projects_by_institution_id(
+ return await get_cordis_eu_projects_by_institution_id(
institutions_search_client=institutions_search_client,
projects_filtering_properties=projects_filtering_properties,
)
-def get_cordis_eu_projects_by_institution_id(
+async def get_cordis_eu_projects_by_institution_id(
institutions_search_client: InstitutionsSearchClient,
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
@@ -133,7 +137,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_eu_organization_project_contributions(
+ page = await get_eu_organization_project_contributions(
organization_names=institution_aliases,
projects_filtering_properties=projects_filtering_properties,
)
@@ -154,7 +158,7 @@ async def get_dfg_projects_by_author_id(
logger.debug(
f"Fetching DFG projects for author_id={author_id}, topic={topic}, page={page}, size={size}, sort_by={sort_by}, sort_direction={sort_direction}"
)
- name = get_author_name_by_id(author_id)
+ name = await get_author_name_by_id(author_id)
if not name:
logger.debug(f"No author name found for author_id={author_id}")
raise NotFoundException(
@@ -162,7 +166,7 @@ async def get_dfg_projects_by_author_id(
)
logger.debug(f"Found author name for author_id={author_id}: {name}")
- response = projects_search_client.search_dfg_projects(
+ response = await projects_search_client.search_dfg_projects(
page=page,
size=size,
names=[name],
@@ -182,7 +186,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
raw_oa_institution_id
)
)
- page = get_eu_organization_project_contributions(
+ page = await get_eu_organization_project_contributions(
organization_names=institution_aliases,
projects_filtering_properties=ProjectsFilteringProperties(
project_type=ProjectType.EU,
@@ -200,7 +204,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
)
-def get_institution_bund_projects_funding_over_time(
+async def get_institution_bund_projects_funding_over_time(
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
) -> InstitutionFunderSummary:
@@ -215,7 +219,7 @@ def get_institution_bund_projects_funding_over_time(
logger.debug(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
- response = projects_search_client.search_bund_projects(
+ response = await projects_search_client.search_bund_projects(
filter_properties=ProjectsFilteringProperties(
project_type=ProjectType.BUND,
page=0,
@@ -301,29 +305,40 @@ def _calculate_funding_over_time(
)
-def get_single_dfg_project(
+async def get_single_dfg_project(
project_id: str,
) -> DfgProjectDetails:
logger.debug(f"Fetching single DFG project for id={project_id}")
- project = projects_search_client.get_dfg_project_by_id(project_id)
+ project = await 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
-def get_single_bund_project(
+async def get_single_bund_project(
project_id: str,
) -> BundProjectDetails:
logger.debug(f"Fetching single BUND project for id={project_id}")
- project = projects_search_client.get_bund_project_by_id(project_id)
+ project = await 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(
+async def get_single_eu_cordis_project(
+ project_id: str,
+) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
+ logger.debug(f"Fetching single EU Cordis project for id={project_id}")
+
+ project = await projects_search_client.get_eu_cordis_projects_by_id(project_id)
+ if not project:
+ raise NotFoundException(f"EU project with id {project_id} not found")
+ return project
+
+
+async def search_cordis_eu_projects_for_author_id(
raw_oa_author_id: str,
) -> CordisEuProjectPage:
@@ -332,18 +347,19 @@ def search_cordis_eu_projects_for_author_id(
# 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)
+ dois = await 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 = projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois)
+ project_ids = await 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 = projects_search_client.get_cordis_eu_projects_by_project_ids(
+ funding_project_page = await 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/topics/logic.py b/service/src/main/inse/topics/logic.py
index 244f70c8..1d718ecf 100644
--- a/service/src/main/inse/topics/logic.py
+++ b/service/src/main/inse/topics/logic.py
@@ -8,10 +8,8 @@ from copy import deepcopy
from typing import Any
import httpx
-from fastapi import HTTPException
from pydantic import ValidationError
-from starlette.status import HTTP_400_BAD_REQUEST
-from starlette.status import HTTP_502_BAD_GATEWAY
+from inse.exceptions import UpstreamAPIException, BadRequestException, ElasticsearchException
from inse.models.openalex.autocomplete_response import AutocompleteResponse
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
@@ -38,10 +36,7 @@ async def list_topics(
client: OpenAlexTopicsClient | None = None,
) -> TopicsListResponse:
if sample is not None and (sort or page not in (None, 1)):
- raise HTTPException(
- status_code=HTTP_400_BAD_REQUEST,
- detail="sample cannot be combined with sort or page.",
- )
+ raise BadRequestException("sample cannot be combined with sort or page.")
openalex_client = client or OpenAlexTopicsClient()
@@ -66,12 +61,12 @@ async def list_topics(
except ValueError:
if exc.response.text:
detail = exc.response.text
- raise HTTPException(status_code=status_code, detail=detail) from exc
+ raise UpstreamAPIException(message=detail, status_code=status_code) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex topics request failed.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="OpenAlex topics request failed.",
+ raise UpstreamAPIException(
+ message="OpenAlex topics request failed.",
+ status_code=502,
) from exc
try:
@@ -79,9 +74,9 @@ async def list_topics(
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
except ValidationError as exc:
logger.exception("OpenAlex topics response could not be parsed.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="OpenAlex topics response could not be parsed.",
+ raise UpstreamAPIException(
+ message="OpenAlex topics response could not be parsed.",
+ status_code=502,
) from exc
@@ -282,10 +277,7 @@ async def vector_search_topics(
except Exception as exc:
logger.exception("Failed to load elasticsearch integration.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail=f"Failed to load elasticsearch integration: {exc}"
- )
+ raise ElasticsearchException(f"Failed to load elasticsearch integration: {exc}") from exc
# 1. Vectorize query
try:
@@ -293,10 +285,7 @@ async def vector_search_topics(
query_vector = model.encode(query).tolist()
except Exception as exc:
logger.exception("Failed to encode query text.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail=f"Failed to encode query text: {exc}"
- )
+ raise ElasticsearchException(f"Failed to encode query text: {exc}") from exc
# 2. Query Elasticsearch using standard Bool Should hybrid search
should_clauses = []
@@ -357,17 +346,14 @@ async def vector_search_topics(
}
try:
- raw_results = elasticsearch.search(
+ raw_results = await elasticsearch.search(
index="topicvectors",
body=body,
cluster="nes"
)
except Exception as exc:
- logger.exception("Elasticsearch vector search failed.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail=f"Elasticsearch vector search failed: {exc}"
- )
+ logger.exception("Elasticsearch vector search failed with unexpected error.")
+ raise ElasticsearchException(f"Unexpected vector search failure: {exc}") from exc
# 3. Format result
hits = raw_results.get("hits", {}).get("hits", [])
@@ -389,8 +375,5 @@ async def vector_search_topics(
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
except ValidationError as exc:
logger.exception("Vector search response could not be parsed.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="Vector search response could not be parsed.",
- ) from exc
+ raise ElasticsearchException(f"Vector search response could not be parsed: {exc}") from exc
diff --git a/service/src/main/inse/topics/test_logic.py b/service/src/main/inse/topics/test_logic.py
index e6f9a3a4..5e88a461 100644
--- a/service/src/main/inse/topics/test_logic.py
+++ b/service/src/main/inse/topics/test_logic.py
@@ -1,6 +1,6 @@
import httpx
import pytest
-from fastapi import HTTPException
+from inse.exceptions import BadRequestException
from inse.topics import logic
from inse.topics.search_client import OpenAlexTopicsClient
@@ -76,11 +76,9 @@ async def test_list_topics_maps_openalex_response_to_model():
@pytest.mark.anyio
async def test_list_topics_rejects_sample_with_sort():
- with pytest.raises(HTTPException) as exc_info:
+ with pytest.raises(BadRequestException) as exc_info:
await logic.list_topics(sample=10, sort="works_count:desc")
- assert exc_info.value.status_code == 400
-
@pytest.mark.anyio
async def test_list_topics_accepts_practical_openalex_type_variants():
diff --git a/service/src/main/inse/university_ranking/logic.py b/service/src/main/inse/university_ranking/logic.py
index bd1e58f9..10d926ff 100644
--- a/service/src/main/inse/university_ranking/logic.py
+++ b/service/src/main/inse/university_ranking/logic.py
@@ -31,7 +31,7 @@ async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> Ran
# Fetch top institutions for the topic by works_count
- res = elasticsearch.search(
+ res = await elasticsearch.search(
index="openalex-institutions",
query=query,
size=10,
diff --git a/service/src/main/inse/util.py b/service/src/main/inse/util.py
index dc47d976..5848c92e 100644
--- a/service/src/main/inse/util.py
+++ b/service/src/main/inse/util.py
@@ -8,15 +8,14 @@ from typing import Optional
from typing import TypeVar
from inse.models.openalex import Author
from . import model
-from fastapi import HTTPException
-from starlette.status import HTTP_404_NOT_FOUND
+from inse.exceptions import NotFoundException
T = TypeVar('T')
def raise_not_found_if_none(value: Optional[T]) -> T:
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
if value == None:
- raise HTTPException(HTTP_404_NOT_FOUND)
+ raise NotFoundException("Not found.")
else:
return value
diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py
index 9d5918cf..2ffb73e4 100644
--- a/service/src/main/inse/works/logic.py
+++ b/service/src/main/inse/works/logic.py
@@ -9,11 +9,8 @@ from time import time
from typing import Any, List
import httpx
-from fastapi import HTTPException
from pydantic import ValidationError
-from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_404_NOT_FOUND
-from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from inse import config
from inse.integrations import elasticsearch
@@ -24,7 +21,7 @@ from inse.models.openalex.meta import Meta
from inse.models.openalex.topic_count import TopicCount
from inse.models.openalex.topics_by_year import TopicsByYear
from inse.models.openalex.topics_by_time import TopicsByTime
-from .search_client import MissingApiKeyError
+from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
from .search_client import OpenAlexWorksSearchClient
logger = logging.getLogger(__name__)
@@ -122,10 +119,10 @@ async def get_primary_topic_counts(
author_id: str,
client: OpenAlexWorksSearchClient | None = None,
) -> List[TopicCount]:
- topic_counts = _get_primary_topic_counts_from_es(author_id)
+ topic_counts = await _get_primary_topic_counts_from_es(author_id)
topic_ids = [item["id"] for item in topic_counts if item["id"]]
- details = _get_topic_details(topic_ids)
+ details = await _get_topic_details(topic_ids)
result = []
@@ -148,7 +145,7 @@ async def get_primary_topic_counts(
return result
-def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
+async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
@@ -174,16 +171,13 @@ def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
}
try:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
- except httpx.HTTPError as exc:
+ except ElasticsearchException as exc:
logger.exception("OpenAlex primary topic aggregation request failed.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="OpenAlex works search request failed.",
- ) from exc
+ raise
aggregations = response.get("aggregations", {})
buckets = aggregations.get("primary_topics", {}).get("buckets", [])
@@ -197,42 +191,33 @@ def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
async def get_work(
work_id: str,
+ title:str,
client: OpenAlexWorksSearchClient | None = None,
-) -> Work:
+) -> Work | None:
search_client = client or OpenAlexWorksSearchClient()
- try:
- data = await search_client.search_work(work_id)
- except MissingApiKeyError as exc:
- raise HTTPException(
- status_code=HTTP_503_SERVICE_UNAVAILABLE,
- detail="OpenAlex works search is not configured.",
- ) from exc
- except httpx.HTTPError as exc:
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="OpenAlex works search request failed.",
- ) from exc
+
+ data = await search_client.search_work(work_id)
elements, _ = _parse_full_work_search_response(data)
+ if (not elements) and title:
+ response_by_title = await search_client.search_for_work_by_title(title=title)
+ elements, _ = _parse_full_work_search_response(response_by_title)
if not elements:
- raise HTTPException(
- status_code=HTTP_404_NOT_FOUND,
- detail="Publication not found.",
- )
+ return None
return elements[0]
-def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
+async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
if not topic_ids:
return {}
try:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index="openalex-topics",
query={"terms": {"id": topic_ids}},
source=TOPIC_DETAIL_SOURCE_FIELDS,
size=len(topic_ids),
)
- except httpx.HTTPError:
+ except Exception:
logger.exception("Could not load topic details from Elasticsearch.")
return {}
@@ -251,7 +236,7 @@ def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
"domain": _extract_topic_hierarchy_item(source, "domain"),
}
- _enrich_topic_hierarchy_descriptions(details)
+ await _enrich_topic_hierarchy_descriptions(details)
return details
@@ -269,7 +254,7 @@ def _extract_topic_hierarchy_item(source: dict, key: str) -> dict[str, str | Non
}
-def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
+async def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
for hierarchy_key, index in TOPIC_HIERARCHY_DESCRIPTION_INDICES.items():
hierarchy_ids = {
item.get(hierarchy_key, {}).get("id")
@@ -277,7 +262,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
if item.get(hierarchy_key, {}).get("id")
}
- descriptions = _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
+ descriptions = await _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
for item in details.values():
hierarchy_item = item.get(hierarchy_key) or {}
@@ -287,7 +272,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
hierarchy_item["description"] = descriptions[hierarchy_id]
-def _get_topic_hierarchy_descriptions(
+async def _get_topic_hierarchy_descriptions(
index: str,
hierarchy_ids: list[str],
) -> dict[str, str | None]:
@@ -295,13 +280,13 @@ def _get_topic_hierarchy_descriptions(
return {}
try:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=index,
query={"terms": {"id": hierarchy_ids}},
source=TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS,
size=len(hierarchy_ids),
)
- except httpx.HTTPError:
+ except Exception:
logger.exception("Could not load topic hierarchy details from %s.", index)
return {}
@@ -442,7 +427,7 @@ async def get_topics_by_time_by_author(
client=client,
)
- return _get_topics_by_time_by_author_from_es(
+ return await _get_topics_by_time_by_author_from_es(
author_id,
max_topics_per_year=max_topics_per_year,
target_publications=target_publications,
@@ -530,7 +515,7 @@ async def _get_topics_by_time_by_author_from_work_pages(
if topic["id"]:
topic_ids.add(topic["id"])
- topic_details = _get_topic_details(list(topic_ids))
+ topic_details = await _get_topic_details(list(topic_ids))
elements = []
@@ -589,13 +574,13 @@ async def _get_topics_by_time_by_author_from_work_pages(
)
-def _get_topics_by_time_by_author_from_es(
+async def _get_topics_by_time_by_author_from_es(
author_id: str,
max_topics_per_year: int = 3,
target_publications: int = 300,
include_all: bool = False,
) -> TopicsByTime:
- year_buckets, total_publications = _get_publication_year_counts_from_es(author_id)
+ year_buckets, total_publications = await _get_publication_year_counts_from_es(author_id)
selected_years, is_limited = _select_complete_timeline_years(
year_buckets,
target_publications=target_publications,
@@ -611,13 +596,13 @@ def _get_topics_by_time_by_author_from_es(
total_publications=total_publications,
)
- year_topic_buckets = _get_timeline_topic_counts_from_es(
+ year_topic_buckets = await _get_timeline_topic_counts_from_es(
author_id,
years=selected_years,
max_topics_per_year=max_topics_per_year,
)
topic_ids = _collect_topic_ids_from_year_buckets(year_topic_buckets)
- topic_details = _get_topic_details(list(topic_ids))
+ topic_details = await _get_topic_details(list(topic_ids))
elements = _build_timeline_elements_from_aggregations(
year_topic_buckets,
@@ -634,7 +619,7 @@ def _get_topics_by_time_by_author_from_es(
)
-def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
+async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
body = {
"size": 0,
"track_total_hits": True,
@@ -651,21 +636,18 @@ def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], in
}
try:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
- except httpx.HTTPError as exc:
+ except ElasticsearchException as exc:
logger.exception("OpenAlex publication year aggregation request failed.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="OpenAlex works search request failed.",
- ) from exc
+ raise
return _parse_year_count_buckets(response), _parse_total_hits(response)
-def _get_timeline_topic_counts_from_es(
+async def _get_timeline_topic_counts_from_es(
author_id: str,
years: list[int],
max_topics_per_year: int,
@@ -722,16 +704,13 @@ def _get_timeline_topic_counts_from_es(
}
try:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
- except httpx.HTTPError as exc:
+ except ElasticsearchException as exc:
logger.exception("OpenAlex timeline topic aggregation request failed.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="OpenAlex works search request failed.",
- ) from exc
+ raise
return response.get("aggregations", {}).get("by_year", {}).get("buckets", [])
@@ -892,29 +871,16 @@ async def _search_author_works_data(
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
) -> dict:
- try:
- return await search_client.search_author_works(
- author_id,
- page,
- size,
- publication_year=publication_year,
- work_type=work_type,
- language=language,
- institution_id=institution_id,
- topic_id=topic_id,
- )
- except MissingApiKeyError as exc:
- logger.error("OpenAlex works Elasticsearch API key is not configured.")
- raise HTTPException(
- status_code=HTTP_503_SERVICE_UNAVAILABLE,
- detail="OpenAlex works search is not configured.",
- ) from exc
- except httpx.HTTPError as exc:
- logger.exception("OpenAlex works search request failed.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="OpenAlex works search request failed.",
- ) from exc
+ return await search_client.search_author_works(
+ author_id,
+ page,
+ size,
+ publication_year=publication_year,
+ work_type=work_type,
+ language=language,
+ institution_id=institution_id,
+ topic_id=topic_id,
+ )
def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
@@ -955,15 +921,15 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
elements.append(work)
except ValidationError as exc:
logger.exception("OpenAlex works search response could not be parsed.")
- raise HTTPException(
- status_code=HTTP_502_BAD_GATEWAY,
- detail="OpenAlex works search response could not be parsed.",
+ raise UpstreamAPIException(
+ message="OpenAlex works search response could not be parsed.",
+ status_code=502,
) from exc
return elements, total
-def get_publication_dois_of_author(
+async def get_publication_dois_of_author(
raw_oa_author_id: str,
) -> List[str]:
query = {
@@ -985,19 +951,16 @@ def get_publication_dois_of_author(
}
try:
- response = elasticsearch.search(
+ response = await elasticsearch.search(
index="openalex-works",
source=["doi"],
size=10000,
query=query,
cluster="nes",
)
- except httpx.HTTPError as exc:
+ except ElasticsearchException 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
+ raise
dois = []
for hit in response.get("hits", {}).get("hits", []):
diff --git a/service/src/main/inse/works/search_client.py b/service/src/main/inse/works/search_client.py
index fe60c665..41e6cb1e 100644
--- a/service/src/main/inse/works/search_client.py
+++ b/service/src/main/inse/works/search_client.py
@@ -7,12 +7,11 @@ import logging
from typing import Any
import httpx
-
+import urllib
from .. import config
-
-
-class MissingApiKeyError(Exception):
- pass
+from inse.integrations import elasticsearch
+from inse.model import ESCluster, ESIndex
+from inse.exceptions import MissingApiKeyError
logger = logging.getLogger(__name__)
@@ -141,46 +140,72 @@ class OpenAlexWorksSearchClient:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
- async with httpx.AsyncClient(
- base_url=self.base_url,
- timeout=self.timeout,
- transport=self.transport,
- ) as client:
- response = await client.post(
- f"/{self.index}/_search",
- headers={"Authorization": f"ApiKey {self.api_key}"},
- json=self.author_works_query(
- author_id,
- page,
- size,
- publication_year=publication_year,
- work_type=work_type,
- language=language,
- institution_id=institution_id,
- topic_id=topic_id,
- ),
- )
- # logging.debug(f"Response: {response.text}")
- response.raise_for_status()
- return response.json()
+ body = self.author_works_query(
+ author_id,
+ page,
+ size,
+ publication_year=publication_year,
+ work_type=work_type,
+ language=language,
+ institution_id=institution_id,
+ topic_id=topic_id,
+ )
+ return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,)
- async def search_work(self, work_id: str) -> dict[str, Any]:
+ async def search_work(self, identifier: str) -> dict[str, Any]:
+ if not self.api_key:
+ raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
+ decoded_id = urllib.parse.unquote(identifier)
+ body = {
+ "query": {
+ "bool": {
+ "should": [
+ {
+ "term": {
+ "_id": {
+ "value": decoded_id,
+ "boost": 5
+ }
+ }
+ },
+ {
+ "term": {
+ "doi": {
+ "value": "https://doi.org/" + decoded_id.lower(),
+ "boost": 3
+ }
+ }
+ }
+ ],
+ "minimum_should_match": 1
+ }
+ }
+ }
+ response = await elasticsearch.search(index=f"{ESIndex.OPENALEX_WORKS}*",body=body,cluster=ESCluster.NES,size=1)
+ return response
+
+ async def search_for_work_by_title(
+ self,
+ title: str,
+ ) -> dict[str, Any]:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
- indexed_work_id = f"https://openalex.org/{work_id.strip().split('/')[-1]}"
- async with httpx.AsyncClient(
- base_url=self.base_url,
- timeout=self.timeout,
- transport=self.transport,
- ) as client:
- response = await client.post(
- f"/{self.index}/_search",
- headers={"Authorization": f"ApiKey {self.api_key}"},
- json={
- "size": 1,
- "query": {"term": {"id": indexed_work_id}},
+ query_clauses = [
+ {"match_phrase": {"title": title}},
+ ]
+
+ body = {
+ "query": {
+ "bool": {
+ "must": query_clauses,
},
- )
- response.raise_for_status()
- return response.json()
+ },
+ "sort": [
+ {"publication_year": {"order": "desc", "missing": "_last"}},
+ {"cited_by_count": {"order": "desc", "missing": "_last"}},
+ ],
+ }
+ response = await elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1)
+
+ return response
\ No newline at end of file
diff --git a/service/src/main/inse/works/service.py b/service/src/main/inse/works/service.py
index e0d84c57..a474d262 100644
--- a/service/src/main/inse/works/service.py
+++ b/service/src/main/inse/works/service.py
@@ -4,7 +4,7 @@
REST API for publication works.
"""
-from typing import Annotated
+from typing import Annotated, Optional
from fastapi import APIRouter
from fastapi import Depends
@@ -123,17 +123,20 @@ async def get_topics_by_time_by_author(
@router.get(
- "/detail/{work_id}",
+ "/detail/{identifier}",
operation_id="getWork",
- response_model=Work,
- summary="Returns one publication.",
+ response_model=Work | None,
+ summary="Returns one publication by OpenAlex ID or DOI.",
)
-async def get_work(
- work_id: Annotated[
- str, Path(description="The OpenAlex work id, for example W2741809807.")
+async def get_work_by_identifier(
+ identifier: Annotated[
+ str, Path(description="The OpenAlex work id (e.g., W2741809807) or DOI number of the publication.")
],
+ title: Annotated[
+ Optional[str], Query(description="Do we want to fallback to title search if ID and DOI dont work?")
+ ] = "",
principal: security.Principal = Depends(
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
),
):
- return await logic.get_work(work_id)
+ return await logic.get_work(identifier,title=title)
\ No newline at end of file
diff --git a/service/src/main/inse/works/test_search_client.py b/service/src/main/inse/works/test_search_client.py
index 0bfe1a44..39dbf091 100644
--- a/service/src/main/inse/works/test_search_client.py
+++ b/service/src/main/inse/works/test_search_client.py
@@ -3,7 +3,7 @@ import json
import httpx
import pytest
-from inse.works.search_client import MissingApiKeyError
+from inse.exceptions import MissingApiKeyError
from inse.works.search_client import OpenAlexWorksSearchClient
@@ -152,37 +152,47 @@ def test_author_works_query_adds_topic_filter():
]
+from unittest.mock import AsyncMock, patch
+
+
@pytest.mark.anyio
async def test_search_author_works_passes_institution_filter_to_query():
- def handler(request: httpx.Request) -> httpx.Response:
- body = json.loads(request.content)
- assert body["query"]["bool"]["must"][1]["nested"]["path"] == (
- "authorships.institutions"
+ with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
+ mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
+ client = OpenAlexWorksSearchClient(index="openalex-works")
+
+ await client.search_author_works(
+ "A5023888391",
+ page=1,
+ size=20,
+ institution_id=["https://openalex.org/I205640436"],
)
+
+ assert mock_search.call_count == 1
+ _, kwargs = mock_search.call_args
+ body = kwargs.get("body")
+ assert body["query"]["bool"]["must"][1]["nested"]["path"] == "authorships.institutions"
assert body["query"]["bool"]["must"][1]["nested"]["query"]["terms"] == {
"authorships.institutions.id": ["https://openalex.org/I205640436"],
}
- return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
-
- client = OpenAlexWorksSearchClient(
- base_url="https://project.nes.uni-due.de/elastic",
- index="openalex-works",
- api_key="test-key",
- transport=httpx.MockTransport(handler),
- )
-
- await client.search_author_works(
- "A5023888391",
- page=1,
- size=20,
- institution_id=["https://openalex.org/I205640436"],
- )
@pytest.mark.anyio
async def test_search_author_works_passes_topic_filter_to_query():
- def handler(request: httpx.Request) -> httpx.Response:
- body = json.loads(request.content)
+ with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
+ mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
+ client = OpenAlexWorksSearchClient(index="openalex-works")
+
+ await client.search_author_works(
+ "A5023888391",
+ page=1,
+ size=20,
+ topic_id=["https://openalex.org/T12419"],
+ )
+
+ assert mock_search.call_count == 1
+ _, kwargs = mock_search.call_args
+ body = kwargs.get("body")
assert body["query"]["bool"]["filter"] == [
{
"bool": {
@@ -207,61 +217,55 @@ async def test_search_author_works_passes_topic_filter_to_query():
},
},
]
- return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
-
- client = OpenAlexWorksSearchClient(
- base_url="https://project.nes.uni-due.de/elastic",
- index="openalex-works",
- api_key="test-key",
- transport=httpx.MockTransport(handler),
- )
-
- await client.search_author_works(
- "A5023888391",
- page=1,
- size=20,
- topic_id=["https://openalex.org/T12419"],
- )
@pytest.mark.anyio
async def test_search_author_works_calls_elasticsearch_index_with_api_key():
- def handler(request: httpx.Request) -> httpx.Response:
- assert request.method == "POST"
- assert request.url.path == "/elastic/openalex-works/_search"
- assert request.headers["Authorization"] == "ApiKey test-key"
- return httpx.Response(200, json={"hits": {"total": {"value": 0}, "hits": []}})
+ with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
+ mock_search.return_value = {"hits": {"total": {"value": 0}, "hits": []}}
+ client = OpenAlexWorksSearchClient(index="openalex-works")
- client = OpenAlexWorksSearchClient(
- base_url="https://project.nes.uni-due.de/elastic",
- index="openalex-works",
- api_key="test-key",
- transport=httpx.MockTransport(handler),
- )
+ result = await client.search_author_works("A5023888391", page=1, size=20)
- result = await client.search_author_works("A5023888391", page=1, size=20)
-
- assert result == {"hits": {"total": {"value": 0}, "hits": []}}
+ assert result == {"hits": {"total": {"value": 0}, "hits": []}}
@pytest.mark.anyio
async def test_search_work_filters_by_work_id():
- def handler(request: httpx.Request) -> httpx.Response:
- body = json.loads(request.content)
+ with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
+ mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
+ client = OpenAlexWorksSearchClient(index="openalex-works")
+
+ await client.search_work("W2741809807")
+
+ assert mock_search.call_count == 1
+ _, kwargs = mock_search.call_args
+ body = kwargs.get("body")
assert body == {
- "size": 1,
- "query": {"term": {"id": "https://openalex.org/W2741809807"}},
+ "query": {
+ "bool": {
+ "should": [
+ {
+ "term": {
+ "_id": {
+ "value": "W2741809807",
+ "boost": 5
+ }
+ }
+ },
+ {
+ "term": {
+ "doi": {
+ "value": "https://doi.org/w2741809807",
+ "boost": 3
+ }
+ }
+ }
+ ],
+ "minimum_should_match": 1
+ }
+ }
}
- return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
-
- client = OpenAlexWorksSearchClient(
- base_url="https://project.nes.uni-due.de/elastic",
- index="openalex-works",
- api_key="test-key",
- transport=httpx.MockTransport(handler),
- )
-
- await client.search_work("W2741809807")
@pytest.mark.anyio
diff --git a/service/uv.lock b/service/uv.lock
index d4016c83..4a7e9873 100644
--- a/service/uv.lock
+++ b/service/uv.lock
@@ -178,36 +178,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b2/b7/545d2c10c1fc15e48653c91efde329a790f2eecfbbf2bd16003b5db2bab0/dotenv-0.9.9-py2.py3-none-any.whl", hash = "sha256:29cf74a087b31dafdb5a446b6d7e11cbce8ed2741540e2339c69fbef92c94ce9", size = 1892, upload-time = "2025-02-19T22:15:01.647Z" },
]
-[[package]]
-name = "elastic-transport"
-version = "9.4.1"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "certifi" },
- { name = "sniffio" },
- { name = "urllib3" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/0f/a8/dd1431b95daa54d4859c1d250362433df6df9cfaab7bfac3eafd410d019a/elastic_transport-9.4.1.tar.gz", hash = "sha256:d12c86ea73528690ebf63a488d9ae323292e6aa5ee55e1e29f14293472f4197f", size = 79170, upload-time = "2026-05-25T14:16:47.416Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/5c/f6/508c1e541b840b6eaf60a46a8994ba55affd07bf6a311cffc860781ae06a/elastic_transport-9.4.1-py3-none-any.whl", hash = "sha256:186a29e6c66ff269487e33f7b17176316e18b6061702c25eb0bb15681302e91d", size = 66229, upload-time = "2026-05-25T14:16:45.882Z" },
-]
-
-[[package]]
-name = "elasticsearch"
-version = "9.4.1"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "anyio" },
- { name = "elastic-transport" },
- { name = "python-dateutil" },
- { name = "sniffio" },
- { name = "typing-extensions" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/e0/4b/9b753f0a8f56ae508dced2f7ac87bef7a27ce8f890e349e16812e9f7f4fa/elasticsearch-9.4.1.tar.gz", hash = "sha256:1d78fdfba97a903ec35a5eb5808a74e33392b7c620bd5f742d465a3a26c27d75", size = 908138, upload-time = "2026-05-26T16:28:40.132Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/cf/8e/2c93805e93e724a90156004a9212572ec86473974deede4605a33b8b169a/elasticsearch-9.4.1-py3-none-any.whl", hash = "sha256:71ab71c3d1b20fd88c2922fb82c3277cce7ea03c160686e7b9368b265c2b4cac", size = 993647, upload-time = "2026-05-26T16:28:36.556Z" },
-]
-
[[package]]
name = "fastapi"
version = "0.115.14"
@@ -799,18 +769,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" },
]
-[[package]]
-name = "python-dateutil"
-version = "2.9.0.post0"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "six" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
-]
-
[[package]]
name = "python-dotenv"
version = "1.2.2"
@@ -1127,7 +1085,6 @@ source = { virtual = "." }
dependencies = [
{ name = "cryptography" },
{ name = "dotenv" },
- { name = "elasticsearch" },
{ name = "fastapi" },
{ name = "httpx" },
{ name = "openai" },
@@ -1148,7 +1105,6 @@ dependencies = [
requires-dist = [
{ name = "cryptography", specifier = "~=42.0.0" },
{ name = "dotenv", specifier = ">=0.9.9" },
- { name = "elasticsearch", specifier = "~=9.4.0" },
{ name = "fastapi", specifier = "~=0.115.0" },
{ name = "httpx", specifier = "~=0.27.0" },
{ name = "openai", specifier = "~=2.41.0" },
@@ -1182,15 +1138,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
]
-[[package]]
-name = "six"
-version = "1.17.0"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
-]
-
[[package]]
name = "sniffio"
version = "1.3.1"
@@ -1421,15 +1368,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" },
]
-[[package]]
-name = "urllib3"
-version = "2.7.0"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },
-]
-
[[package]]
name = "uvicorn"
version = "0.29.0"
diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES
index 0a468ed3..9a1f5c93 100644
--- a/webapp/src/app/api/.openapi-generator/FILES
+++ b/webapp/src/app/api/.openapi-generator/FILES
@@ -22,6 +22,7 @@ encoder.ts
git_push.sh
index.ts
model/accessGrant.ts
+model/allPatentsResponse.ts
model/authAccount.ts
model/authScope.ts
model/author.ts
@@ -61,16 +62,46 @@ model/dehydratedSource.ts
model/dfgProjectDetails.ts
model/dfgProjectPage.ts
model/dfgProjectSummary.ts
+model/euCordisProjectResponse.ts
model/euOrganizationProjectSummary.ts
model/euOrganizationProjectSummaryPage.ts
+model/euProjectData.ts
model/filterInformation.ts
model/filterProperties.ts
+model/fp7EurosciVoc.ts
+model/fp7LegalBasis.ts
+model/fp7Organization.ts
+model/fp7ProjectDetails.ts
+model/fp7ProjectIPR.ts
+model/fp7Publication.ts
+model/fp7ReportSummary.ts
+model/fp7Topic.ts
+model/fp7WebLink.ts
model/funderByAuthor.ts
model/fundersByAuthorResponse.ts
model/fundingProject.ts
model/fundingProjectPage.ts
model/fwci.ts
model/groupByResult.ts
+model/h2020Deliverable.ts
+model/h2020ErcPI.ts
+model/h2020EurosciVoc.ts
+model/h2020LegalBasis.ts
+model/h2020Organization.ts
+model/h2020ProjectDetails.ts
+model/h2020Publication.ts
+model/h2020ReportSummary.ts
+model/h2020Topic.ts
+model/h2020WebLink.ts
+model/hEUDeliverable.ts
+model/hEUEurosciVoc.ts
+model/hEULegalBasis.ts
+model/hEUOrganization.ts
+model/hEUProjectDetails.ts
+model/hEUPublication.ts
+model/hEUReportSummary.ts
+model/hEUTopic.ts
+model/hEUWebLink.ts
model/hTTPValidationError.ts
model/identityGrant.ts
model/institution.ts
@@ -81,6 +112,7 @@ model/institutionInformation.ts
model/institutionNetworkNode.ts
model/institutionPage.ts
model/institutionsListResponse.ts
+model/ipcClassification.ts
model/item.ts
model/itemCreate.ts
model/itemPage.ts
diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts
index d8715dc1..d08ec699 100644
--- a/webapp/src/app/api/api/patents.service.ts
+++ b/webapp/src/app/api/api/patents.service.ts
@@ -22,9 +22,13 @@ import {
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
+// @ts-ignore
+import { AllPatentsResponse } from '../model/allPatentsResponse';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
+import { PatentEntry } from '../model/patentEntry';
+// @ts-ignore
import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
// @ts-ignore
@@ -44,6 +48,285 @@ export class PatentsService extends BaseService {
super(basePath, configuration);
}
+ /**
+ * Get all patents with pagination and search.
+ * @endpoint get /api/inse-service/patents
+ * @param page
+ * @param size
+ * @param search
+ * @param source
+ * @param sortBy
+ * @param sortDirection
+ * @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 getAllPatents(
+ page?: number,
+ size?: number,
+ search?: string,
+ source?: string,
+ sortBy?: string,
+ sortDirection?: string,
+ observe?: 'body',
+ reportProgress?: boolean,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable;
+ public getAllPatents(
+ page?: number,
+ size?: number,
+ search?: string,
+ source?: string,
+ sortBy?: string,
+ sortDirection?: string,
+ observe?: 'response',
+ reportProgress?: boolean,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable>;
+ public getAllPatents(
+ page?: number,
+ size?: number,
+ search?: string,
+ source?: string,
+ sortBy?: string,
+ sortDirection?: string,
+ observe?: 'events',
+ reportProgress?: boolean,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable>;
+ public getAllPatents(
+ page?: number,
+ size?: number,
+ search?: string,
+ source?: string,
+ sortBy?: string,
+ sortDirection?: string,
+ observe: any = 'body',
+ reportProgress: boolean = false,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable {
+ let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
+ localVarQueryParameters = this.addToHttpParams(
+ localVarQueryParameters,
+ page,
+ 'page',
+ );
+ localVarQueryParameters = this.addToHttpParams(
+ localVarQueryParameters,
+ size,
+ 'size',
+ );
+ localVarQueryParameters = this.addToHttpParams(
+ localVarQueryParameters,
+ search,
+ 'search',
+ );
+ localVarQueryParameters = this.addToHttpParams(
+ localVarQueryParameters,
+ source,
+ 'source',
+ );
+ localVarQueryParameters = this.addToHttpParams(
+ localVarQueryParameters,
+ sortBy,
+ 'sort_by',
+ );
+ localVarQueryParameters = this.addToHttpParams(
+ localVarQueryParameters,
+ sortDirection,
+ 'sort_direction',
+ );
+
+ 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/inse-service/patents`;
+ const { basePath, withCredentials } = this.configuration;
+ return this.httpClient.request(
+ 'get',
+ `${basePath}${localVarPath}`,
+ {
+ context: localVarHttpContext,
+ params: localVarQueryParameters,
+ responseType: responseType_,
+ ...(withCredentials ? { withCredentials } : {}),
+ headers: localVarHeaders,
+ observe: observe,
+ ...(localVarTransferCache !== undefined
+ ? { transferCache: localVarTransferCache }
+ : {}),
+ reportProgress: reportProgress,
+ },
+ );
+ }
+
+ /**
+ * Returns one publication by OpenAlex ID or DOI.
+ * @endpoint get /api/inse-service/patents/{identifier}
+ * @param identifier
+ * @param prefix Application Prefix (EP or US)
+ * @param title Do we want to fallback to title search if ID and DOI dont work?
+ * @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 getPatentByIdOrTitle(
+ identifier: string,
+ prefix?: string,
+ title?: string,
+ observe?: 'body',
+ reportProgress?: boolean,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable;
+ public getPatentByIdOrTitle(
+ identifier: string,
+ prefix?: string,
+ title?: string,
+ observe?: 'response',
+ reportProgress?: boolean,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable>;
+ public getPatentByIdOrTitle(
+ identifier: string,
+ prefix?: string,
+ title?: string,
+ observe?: 'events',
+ reportProgress?: boolean,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable>;
+ public getPatentByIdOrTitle(
+ identifier: string,
+ prefix?: string,
+ title?: string,
+ observe: any = 'body',
+ reportProgress: boolean = false,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable {
+ if (identifier === null || identifier === undefined) {
+ throw new Error(
+ 'Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.',
+ );
+ }
+
+ let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
+ localVarQueryParameters = this.addToHttpParams(
+ localVarQueryParameters,
+ prefix,
+ 'prefix',
+ );
+ localVarQueryParameters = this.addToHttpParams(
+ localVarQueryParameters,
+ title,
+ 'title',
+ );
+
+ 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/inse-service/patents/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
+ const { basePath, withCredentials } = this.configuration;
+ return this.httpClient.request(
+ 'get',
+ `${basePath}${localVarPath}`,
+ {
+ context: localVarHttpContext,
+ params: localVarQueryParameters,
+ responseType: responseType_,
+ ...(withCredentials ? { withCredentials } : {}),
+ headers: localVarHeaders,
+ observe: observe,
+ ...(localVarTransferCache !== undefined
+ ? { transferCache: localVarTransferCache }
+ : {}),
+ reportProgress: reportProgress,
+ },
+ );
+ }
+
/**
* Get patents matched to an author by name.
* @endpoint get /api/inse-service/authors/{author_id}/patents
diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts
index 35cdba8a..c69e39c9 100644
--- a/webapp/src/app/api/api/projects.service.ts
+++ b/webapp/src/app/api/api/projects.service.ts
@@ -33,6 +33,8 @@ import { DfgProjectDetails } from '../model/dfgProjectDetails';
// @ts-ignore
import { DfgProjectPage } from '../model/dfgProjectPage';
// @ts-ignore
+import { EuCordisProjectResponse } from '../model/euCordisProjectResponse';
+// @ts-ignore
import { EuOrganizationProjectSummaryPage } from '../model/euOrganizationProjectSummaryPage';
// @ts-ignore
import { FundingProjectPage } from '../model/fundingProjectPage';
@@ -758,6 +760,109 @@ export class ProjectsService extends BaseService {
);
}
+ /**
+ * Get a single EU Cordis project.
+ * Returns a single EU Cordis project based on its ID.
+ * @endpoint get /api/projects/eu/{id}
+ * @param id The ID of the EU Cordis project to retrieve.
+ * @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 getSingleEuCordisProject(
+ id: string,
+ observe?: 'body',
+ reportProgress?: boolean,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable;
+ public getSingleEuCordisProject(
+ id: string,
+ observe?: 'response',
+ reportProgress?: boolean,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable>;
+ public getSingleEuCordisProject(
+ id: string,
+ observe?: 'events',
+ reportProgress?: boolean,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable>;
+ public getSingleEuCordisProject(
+ id: string,
+ observe: any = 'body',
+ reportProgress: boolean = false,
+ options?: {
+ httpHeaderAccept?: 'application/json';
+ context?: HttpContext;
+ transferCache?: boolean;
+ },
+ ): Observable {
+ if (id === null || id === undefined) {
+ throw new Error(
+ 'Required parameter id was null or undefined when calling getSingleEuCordisProject.',
+ );
+ }
+
+ 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/eu/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
+ 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 bund projects.
* Returns a page of bund projects based on the provided pagination parameters and optional institution filter.
diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts
index 20d855a3..82f38cbe 100644
--- a/webapp/src/app/api/api/works.service.ts
+++ b/webapp/src/app/api/api/works.service.ts
@@ -619,14 +619,16 @@ export class WorksService extends BaseService {
}
/**
- * Returns one publication.
- * @endpoint get /api/works/detail/{work_id}
- * @param workId The OpenAlex work id, for example W2741809807.
+ * Returns one publication by OpenAlex ID or DOI.
+ * @endpoint get /api/works/detail/{identifier}
+ * @param identifier The OpenAlex work id (e.g., W2741809807) or DOI number of the publication.
+ * @param title Do we want to fallback to title search if ID and DOI dont work?
* @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 getWork(
- workId: string,
+ identifier: string,
+ title?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
@@ -636,7 +638,8 @@ export class WorksService extends BaseService {
},
): Observable;
public getWork(
- workId: string,
+ identifier: string,
+ title?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
@@ -646,7 +649,8 @@ export class WorksService extends BaseService {
},
): Observable>;
public getWork(
- workId: string,
+ identifier: string,
+ title?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
@@ -656,7 +660,8 @@ export class WorksService extends BaseService {
},
): Observable>;
public getWork(
- workId: string,
+ identifier: string,
+ title?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
@@ -665,12 +670,19 @@ export class WorksService extends BaseService {
transferCache?: boolean;
},
): Observable {
- if (workId === null || workId === undefined) {
+ if (identifier === null || identifier === undefined) {
throw new Error(
- 'Required parameter workId was null or undefined when calling getWork.',
+ 'Required parameter identifier was null or undefined when calling getWork.',
);
}
+ let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
+ localVarQueryParameters = this.addToHttpParams(
+ localVarQueryParameters,
+ title,
+ 'title',
+ );
+
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
@@ -709,10 +721,11 @@ export class WorksService extends BaseService {
}
}
- let localVarPath = `/api/works/detail/${this.configuration.encodeParam({ name: 'workId', value: workId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
+ let localVarPath = `/api/works/detail/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request('get', `${basePath}${localVarPath}`, {
context: localVarHttpContext,
+ params: localVarQueryParameters,
responseType: responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
diff --git a/webapp/src/app/api/model/allPatentsResponse.ts b/webapp/src/app/api/model/allPatentsResponse.ts
new file mode 100644
index 00000000..dfe6fb24
--- /dev/null
+++ b/webapp/src/app/api/model/allPatentsResponse.ts
@@ -0,0 +1,19 @@
+/**
+ * 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 { PatentEntry } from './patentEntry';
+
+
+export interface AllPatentsResponse {
+ total: number;
+ page: number;
+ size: number;
+ patents: Array;
+}
+
diff --git a/webapp/src/app/api/model/euCordisProjectResponse.ts b/webapp/src/app/api/model/euCordisProjectResponse.ts
new file mode 100644
index 00000000..63e9084d
--- /dev/null
+++ b/webapp/src/app/api/model/euCordisProjectResponse.ts
@@ -0,0 +1,25 @@
+/**
+ * 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 { EuProjectData } from './euProjectData';
+
+
+/**
+ * Response model for EU Cordis project endpoints.
+ */
+export interface EuCordisProjectResponse {
+ /**
+ * Indicates if the request was successful
+ */
+ success: boolean;
+ project_type?: string | null;
+ eu_project_data?: EuProjectData | null;
+ error?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/euProjectData.ts b/webapp/src/app/api/model/euProjectData.ts
new file mode 100644
index 00000000..6acedaf5
--- /dev/null
+++ b/webapp/src/app/api/model/euProjectData.ts
@@ -0,0 +1,71 @@
+/**
+ * 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 { H2020ProjectDetails } from './h2020ProjectDetails';
+import { Fp7ProjectDetails } from './fp7ProjectDetails';
+import { HEUOrganization } from './hEUOrganization';
+import { HEUPublication } from './hEUPublication';
+import { Fp7WebLink } from './fp7WebLink';
+import { HEUWebLink } from './hEUWebLink';
+import { HEUDeliverable } from './hEUDeliverable';
+import { Fp7ProjectIPR } from './fp7ProjectIPR';
+import { HEUEurosciVoc } from './hEUEurosciVoc';
+import { H2020ErcPI } from './h2020ErcPI';
+import { HEULegalBasis } from './hEULegalBasis';
+import { HEUTopic } from './hEUTopic';
+import { Fp7ReportSummary } from './fp7ReportSummary';
+import { HEUReportSummary } from './hEUReportSummary';
+import { HEUProjectDetails } from './hEUProjectDetails';
+
+
+/**
+ * The project data
+ */
+export interface EuProjectData {
+ acronym?: string;
+ contentUpdateDate?: string;
+ ecMaxContribution?: number;
+ ecSignatureDate?: string;
+ endDate?: string;
+ frameworkProgramme?: string;
+ fundingScheme?: string;
+ grantDoi?: string;
+ humanValidated?: boolean;
+ id?: string;
+ keywords?: string;
+ legalBasis?: string;
+ masterCall?: string;
+ nature?: string;
+ objective?: string;
+ rcn?: string;
+ startDate?: string;
+ status?: string;
+ subCall?: string;
+ title?: string;
+ topics?: string;
+ totalCost?: number;
+ organizations?: Array;
+ publications?: Array;
+ iprs?: Array;
+ report_summaries?: Array;
+ topicsList?: Array;
+ web_links?: Array;
+ eurosciVoc?: Array;
+ legalBasisList?: Array;
+ organizationCount?: number;
+ publicationCount?: number;
+ iprCount?: number;
+ deliverables?: Array;
+ reportSummaries?: Array;
+ webLinks?: Array;
+ ercPrincipalInvestigators?: Array;
+ deliverableCount?: number;
+ ercPiCount?: number;
+}
+
diff --git a/webapp/src/app/api/model/fp7EurosciVoc.ts b/webapp/src/app/api/model/fp7EurosciVoc.ts
new file mode 100644
index 00000000..fb7e8deb
--- /dev/null
+++ b/webapp/src/app/api/model/fp7EurosciVoc.ts
@@ -0,0 +1,23 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * Fp7EurosciVoc
+ */
+export interface Fp7EurosciVoc {
+ code?: string | null;
+ description?: string | null;
+ id?: string | null;
+ path?: string | null;
+ projectID?: string | null;
+ title?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/fp7LegalBasis.ts b/webapp/src/app/api/model/fp7LegalBasis.ts
new file mode 100644
index 00000000..89a05742
--- /dev/null
+++ b/webapp/src/app/api/model/fp7LegalBasis.ts
@@ -0,0 +1,22 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * Fp7LegalBasis
+ */
+export interface Fp7LegalBasis {
+ id?: string | null;
+ legalBasis?: string | null;
+ projectID?: string | null;
+ title?: string | null;
+ uniqueProgrammePart?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/fp7Organization.ts b/webapp/src/app/api/model/fp7Organization.ts
new file mode 100644
index 00000000..2989a873
--- /dev/null
+++ b/webapp/src/app/api/model/fp7Organization.ts
@@ -0,0 +1,43 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * Fp7Organization
+ */
+export interface Fp7Organization {
+ SME?: boolean | null;
+ active?: boolean | null;
+ activityType?: string | null;
+ city?: string | null;
+ contactForm?: string | null;
+ contentUpdateDate?: string | null;
+ country?: string | null;
+ ecContribution?: number | null;
+ endOfParticipation?: boolean | null;
+ geolocation?: string | null;
+ id?: string | null;
+ name?: string | null;
+ netEcContribution?: number | null;
+ nutsCode?: string | null;
+ order?: number | null;
+ organisationID?: string | null;
+ organizationURL?: string | null;
+ postCode?: string | null;
+ projectAcronym?: string | null;
+ projectID?: string | null;
+ rcn?: string | null;
+ role?: string | null;
+ shortName?: string | null;
+ street?: string | null;
+ totalCost?: number | null;
+ vatNumber?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/fp7ProjectDetails.ts b/webapp/src/app/api/model/fp7ProjectDetails.ts
new file mode 100644
index 00000000..a7dce634
--- /dev/null
+++ b/webapp/src/app/api/model/fp7ProjectDetails.ts
@@ -0,0 +1,58 @@
+/**
+ * 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 { Fp7EurosciVoc } from './fp7EurosciVoc';
+import { Fp7WebLink } from './fp7WebLink';
+import { Fp7Publication } from './fp7Publication';
+import { Fp7ReportSummary } from './fp7ReportSummary';
+import { Fp7Topic } from './fp7Topic';
+import { Fp7ProjectIPR } from './fp7ProjectIPR';
+import { Fp7Organization } from './fp7Organization';
+import { Fp7LegalBasis } from './fp7LegalBasis';
+
+
+/**
+ * Comprehensive FP7 Project model combining all related entities. This model extends the base Fp7Project with all associated data.
+ */
+export interface Fp7ProjectDetails {
+ acronym?: string | null;
+ contentUpdateDate?: string | null;
+ ecMaxContribution?: number | null;
+ ecSignatureDate?: string | null;
+ endDate?: string | null;
+ frameworkProgramme?: string | null;
+ fundingScheme?: string | null;
+ grantDoi?: string | null;
+ humanValidated?: boolean | null;
+ id?: string | null;
+ keywords?: string | null;
+ legalBasis?: string | null;
+ masterCall?: string | null;
+ nature?: string | null;
+ objective?: string | null;
+ rcn?: string | null;
+ startDate?: string | null;
+ status?: string | null;
+ subCall?: string | null;
+ title?: string | null;
+ topics?: string | null;
+ totalCost?: number | null;
+ organizations?: Array | null;
+ publications?: Array | null;
+ iprs?: Array | null;
+ report_summaries?: Array | null;
+ topicsList?: Array | null;
+ web_links?: Array | null;
+ eurosciVoc?: Array | null;
+ legalBasisList?: Array | null;
+ organizationCount?: number | null;
+ publicationCount?: number | null;
+ iprCount?: number | null;
+}
+
diff --git a/webapp/src/app/api/model/fp7ProjectIPR.ts b/webapp/src/app/api/model/fp7ProjectIPR.ts
new file mode 100644
index 00000000..f35487c4
--- /dev/null
+++ b/webapp/src/app/api/model/fp7ProjectIPR.ts
@@ -0,0 +1,36 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * Fp7ProjectIPR
+ */
+export interface Fp7ProjectIPR {
+ applicantName?: string | null;
+ applicationDate?: string | null;
+ applicationIdentifier?: string | null;
+ applicationKind?: string | null;
+ applicationPrefix?: string | null;
+ awardDate?: string | null;
+ awardIdentifier?: string | null;
+ awardKind?: string | null;
+ awardPrefix?: string | null;
+ epoAppUrl?: string | null;
+ epoPubUrl?: string | null;
+ id?: string | null;
+ organisationID?: string | null;
+ patentFamilyIdentifier?: string | null;
+ patentType?: string | null;
+ priorityDate?: string | null;
+ projectID?: string | null;
+ title?: string | null;
+ type?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/fp7Publication.ts b/webapp/src/app/api/model/fp7Publication.ts
new file mode 100644
index 00000000..fd0e2491
--- /dev/null
+++ b/webapp/src/app/api/model/fp7Publication.ts
@@ -0,0 +1,35 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * Fp7Publication
+ */
+export interface Fp7Publication {
+ authors?: string | null;
+ collection?: string | null;
+ contentUpdateDate?: string | null;
+ doi?: string | null;
+ id?: string | null;
+ isPublishedAs?: string | null;
+ journalNumber?: string | null;
+ journalTitle?: string | null;
+ projectAcronym?: string | null;
+ projectID?: string | null;
+ publishedPages?: string | null;
+ publishedYear?: number | null;
+ publisher?: string | null;
+ qaProcessedDoi?: string | null;
+ rcn?: string | null;
+ repositoryUrl?: string | null;
+ title?: string | null;
+ volume?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/fp7ReportSummary.ts b/webapp/src/app/api/model/fp7ReportSummary.ts
new file mode 100644
index 00000000..f0413439
--- /dev/null
+++ b/webapp/src/app/api/model/fp7ReportSummary.ts
@@ -0,0 +1,24 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * Fp7ReportSummary
+ */
+export interface Fp7ReportSummary {
+ attachments?: string | null;
+ contentUpdateDate?: string | null;
+ id?: string | null;
+ projectAcronym?: string | null;
+ projectID?: string | null;
+ rcn?: string | null;
+ title?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/fp7Topic.ts b/webapp/src/app/api/model/fp7Topic.ts
new file mode 100644
index 00000000..f39a021e
--- /dev/null
+++ b/webapp/src/app/api/model/fp7Topic.ts
@@ -0,0 +1,21 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * Fp7Topic
+ */
+export interface Fp7Topic {
+ id?: string | null;
+ projectID?: string | null;
+ title?: string | null;
+ topic?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/fp7WebLink.ts b/webapp/src/app/api/model/fp7WebLink.ts
new file mode 100644
index 00000000..eeaff7ab
--- /dev/null
+++ b/webapp/src/app/api/model/fp7WebLink.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.
+ */
+
+
+/**
+ * Fp7WebLink
+ */
+export interface Fp7WebLink {
+ archivedDate?: string | null;
+ availableLanguages?: string | null;
+ id?: string | null;
+ linkId?: string | null;
+ projectID?: string | null;
+ represents?: string | null;
+ source?: string | null;
+ status?: string | null;
+ type?: string | null;
+ url?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/h2020Deliverable.ts b/webapp/src/app/api/model/h2020Deliverable.ts
new file mode 100644
index 00000000..390d2c7a
--- /dev/null
+++ b/webapp/src/app/api/model/h2020Deliverable.ts
@@ -0,0 +1,25 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * H2020Deliverable
+ */
+export interface H2020Deliverable {
+ collection?: string | null;
+ contentUpdateDate?: string | null;
+ deliverableType?: string | null;
+ description?: string | null;
+ projectAcronym?: string | null;
+ projectID?: string | null;
+ rcn?: string | null;
+ url?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/h2020ErcPI.ts b/webapp/src/app/api/model/h2020ErcPI.ts
new file mode 100644
index 00000000..48ae3ff0
--- /dev/null
+++ b/webapp/src/app/api/model/h2020ErcPI.ts
@@ -0,0 +1,25 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * H2020ErcPI
+ */
+export interface H2020ErcPI {
+ firstName?: string | null;
+ fundingScheme?: string | null;
+ id?: string | null;
+ lastName?: string | null;
+ organisationID?: string | null;
+ projectAcronym?: string | null;
+ projectID?: string | null;
+ title?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/h2020EurosciVoc.ts b/webapp/src/app/api/model/h2020EurosciVoc.ts
new file mode 100644
index 00000000..7d1ea931
--- /dev/null
+++ b/webapp/src/app/api/model/h2020EurosciVoc.ts
@@ -0,0 +1,23 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * H2020EurosciVoc
+ */
+export interface H2020EurosciVoc {
+ code?: string | null;
+ description?: string | null;
+ id?: string | null;
+ path?: string | null;
+ projectID?: string | null;
+ title?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/h2020LegalBasis.ts b/webapp/src/app/api/model/h2020LegalBasis.ts
new file mode 100644
index 00000000..d247488d
--- /dev/null
+++ b/webapp/src/app/api/model/h2020LegalBasis.ts
@@ -0,0 +1,22 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * H2020LegalBasis
+ */
+export interface H2020LegalBasis {
+ id?: string | null;
+ legalBasis?: string | null;
+ projectID?: string | null;
+ title?: string | null;
+ uniqueProgrammePart?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/h2020Organization.ts b/webapp/src/app/api/model/h2020Organization.ts
new file mode 100644
index 00000000..003a00ed
--- /dev/null
+++ b/webapp/src/app/api/model/h2020Organization.ts
@@ -0,0 +1,43 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * H2020Organization
+ */
+export interface H2020Organization {
+ SME?: boolean | null;
+ active?: boolean | null;
+ activityType?: string | null;
+ city?: string | null;
+ contactForm?: string | null;
+ contentUpdateDate?: string | null;
+ country?: string | null;
+ ecContribution?: number | null;
+ endOfParticipation?: boolean | null;
+ geolocation?: string | null;
+ id?: string | null;
+ name?: string | null;
+ netEcContribution?: number | null;
+ nutsCode?: string | null;
+ order?: number | null;
+ organisationID?: string | null;
+ organizationURL?: string | null;
+ postCode?: string | null;
+ projectAcronym?: string | null;
+ projectID?: string | null;
+ rcn?: string | null;
+ role?: string | null;
+ shortName?: string | null;
+ street?: string | null;
+ totalCost?: number | null;
+ vatNumber?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/h2020ProjectDetails.ts b/webapp/src/app/api/model/h2020ProjectDetails.ts
new file mode 100644
index 00000000..7d08134e
--- /dev/null
+++ b/webapp/src/app/api/model/h2020ProjectDetails.ts
@@ -0,0 +1,61 @@
+/**
+ * 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 { H2020LegalBasis } from './h2020LegalBasis';
+import { H2020ErcPI } from './h2020ErcPI';
+import { H2020Deliverable } from './h2020Deliverable';
+import { H2020WebLink } from './h2020WebLink';
+import { H2020Publication } from './h2020Publication';
+import { H2020ReportSummary } from './h2020ReportSummary';
+import { H2020Topic } from './h2020Topic';
+import { H2020EurosciVoc } from './h2020EurosciVoc';
+import { H2020Organization } from './h2020Organization';
+
+
+/**
+ * Comprehensive Horizon 2020 Project model combining all related entities. This model extends the base H2020Project with all associated data.
+ */
+export interface H2020ProjectDetails {
+ acronym?: string | null;
+ contentUpdateDate?: string | null;
+ ecMaxContribution?: number | null;
+ ecSignatureDate?: string | null;
+ endDate?: string | null;
+ frameworkProgramme?: string | null;
+ fundingScheme?: string | null;
+ grantDoi?: string | null;
+ humanValidated?: boolean | null;
+ id?: string | null;
+ keywords?: string | null;
+ legalBasis?: string | null;
+ masterCall?: string | null;
+ nature?: string | null;
+ objective?: string | null;
+ rcn?: string | null;
+ startDate?: string | null;
+ status?: string | null;
+ subCall?: string | null;
+ title?: string | null;
+ topics?: string | null;
+ totalCost?: number | null;
+ organizations?: Array | null;
+ publications?: Array | null;
+ deliverables?: Array | null;
+ reportSummaries?: Array | null;
+ topicsList?: Array | null;
+ webLinks?: Array | null;
+ eurosciVoc?: Array | null;
+ legalBasisList?: Array | null;
+ ercPrincipalInvestigators?: Array | null;
+ organizationCount?: number | null;
+ publicationCount?: number | null;
+ deliverableCount?: number | null;
+ ercPiCount?: number | null;
+}
+
diff --git a/webapp/src/app/api/model/h2020Publication.ts b/webapp/src/app/api/model/h2020Publication.ts
new file mode 100644
index 00000000..945e22d2
--- /dev/null
+++ b/webapp/src/app/api/model/h2020Publication.ts
@@ -0,0 +1,35 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * H2020Publication
+ */
+export interface H2020Publication {
+ authors?: string | null;
+ collection?: string | null;
+ contentUpdateDate?: string | null;
+ doi?: string | null;
+ id?: string | null;
+ isPublishedAs?: string | null;
+ journalNumber?: string | null;
+ journalTitle?: string | null;
+ projectAcronym?: string | null;
+ projectID?: string | null;
+ publishedPages?: string | null;
+ publishedYear?: number | null;
+ publisher?: string | null;
+ qaProcessedDoi?: string | null;
+ rcn?: string | null;
+ repositoryUrl?: string | null;
+ title?: string | null;
+ volume?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/h2020ReportSummary.ts b/webapp/src/app/api/model/h2020ReportSummary.ts
new file mode 100644
index 00000000..a5975ffb
--- /dev/null
+++ b/webapp/src/app/api/model/h2020ReportSummary.ts
@@ -0,0 +1,24 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * H2020ReportSummary
+ */
+export interface H2020ReportSummary {
+ attachments?: string | null;
+ contentUpdateDate?: string | null;
+ id?: string | null;
+ projectAcronym?: string | null;
+ projectID?: string | null;
+ rcn?: string | null;
+ title?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/h2020Topic.ts b/webapp/src/app/api/model/h2020Topic.ts
new file mode 100644
index 00000000..8ddb1991
--- /dev/null
+++ b/webapp/src/app/api/model/h2020Topic.ts
@@ -0,0 +1,21 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * H2020Topic
+ */
+export interface H2020Topic {
+ id?: string | null;
+ projectID?: string | null;
+ title?: string | null;
+ topic?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/h2020WebLink.ts b/webapp/src/app/api/model/h2020WebLink.ts
new file mode 100644
index 00000000..26d54599
--- /dev/null
+++ b/webapp/src/app/api/model/h2020WebLink.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.
+ */
+
+
+/**
+ * H2020WebLink
+ */
+export interface H2020WebLink {
+ archivedDate?: string | null;
+ availableLanguages?: string | null;
+ id?: string | null;
+ linkId?: string | null;
+ projectID?: string | null;
+ represents?: string | null;
+ source?: string | null;
+ status?: string | null;
+ type?: string | null;
+ url?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/hEUDeliverable.ts b/webapp/src/app/api/model/hEUDeliverable.ts
new file mode 100644
index 00000000..05d8c5ba
--- /dev/null
+++ b/webapp/src/app/api/model/hEUDeliverable.ts
@@ -0,0 +1,25 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * HEUDeliverable
+ */
+export interface HEUDeliverable {
+ collection?: string | null;
+ contentUpdateDate?: string | null;
+ deliverableType?: string | null;
+ description?: string | null;
+ projectAcronym?: string | null;
+ projectID?: string | null;
+ rcn?: string | null;
+ url?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/hEUEurosciVoc.ts b/webapp/src/app/api/model/hEUEurosciVoc.ts
new file mode 100644
index 00000000..93921ab7
--- /dev/null
+++ b/webapp/src/app/api/model/hEUEurosciVoc.ts
@@ -0,0 +1,23 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * HEUEurosciVoc
+ */
+export interface HEUEurosciVoc {
+ code?: string | null;
+ description?: string | null;
+ id?: string | null;
+ path?: string | null;
+ projectID?: string | null;
+ title?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/hEULegalBasis.ts b/webapp/src/app/api/model/hEULegalBasis.ts
new file mode 100644
index 00000000..e3cb66ca
--- /dev/null
+++ b/webapp/src/app/api/model/hEULegalBasis.ts
@@ -0,0 +1,22 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * HEULegalBasis
+ */
+export interface HEULegalBasis {
+ id?: string | null;
+ legalBasis?: string | null;
+ projectID?: string | null;
+ title?: string | null;
+ uniqueProgrammePart?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/hEUOrganization.ts b/webapp/src/app/api/model/hEUOrganization.ts
new file mode 100644
index 00000000..6bb193ef
--- /dev/null
+++ b/webapp/src/app/api/model/hEUOrganization.ts
@@ -0,0 +1,43 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * HEUOrganization
+ */
+export interface HEUOrganization {
+ SME?: boolean | null;
+ active?: boolean | null;
+ activityType?: string | null;
+ city?: string | null;
+ contactForm?: string | null;
+ contentUpdateDate?: string | null;
+ country?: string | null;
+ ecContribution?: number | null;
+ endOfParticipation?: boolean | null;
+ geolocation?: string | null;
+ id?: string | null;
+ name?: string | null;
+ netEcContribution?: number | null;
+ nutsCode?: string | null;
+ order?: number | null;
+ organisationID?: string | null;
+ organizationURL?: string | null;
+ postCode?: string | null;
+ projectAcronym?: string | null;
+ projectID?: string | null;
+ rcn?: string | null;
+ role?: string | null;
+ shortName?: string | null;
+ street?: string | null;
+ totalCost?: number | null;
+ vatNumber?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/hEUProjectDetails.ts b/webapp/src/app/api/model/hEUProjectDetails.ts
new file mode 100644
index 00000000..8a897435
--- /dev/null
+++ b/webapp/src/app/api/model/hEUProjectDetails.ts
@@ -0,0 +1,58 @@
+/**
+ * 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 { HEULegalBasis } from './hEULegalBasis';
+import { HEUOrganization } from './hEUOrganization';
+import { HEUTopic } from './hEUTopic';
+import { HEUPublication } from './hEUPublication';
+import { HEUWebLink } from './hEUWebLink';
+import { HEUReportSummary } from './hEUReportSummary';
+import { HEUDeliverable } from './hEUDeliverable';
+import { HEUEurosciVoc } from './hEUEurosciVoc';
+
+
+/**
+ * Comprehensive Horizon Europe Project model combining all related entities. This model extends the base HEUProject with all associated data.
+ */
+export interface HEUProjectDetails {
+ acronym?: string | null;
+ contentUpdateDate?: string | null;
+ ecMaxContribution?: number | null;
+ ecSignatureDate?: string | null;
+ endDate?: string | null;
+ frameworkProgramme?: string | null;
+ fundingScheme?: string | null;
+ grantDoi?: string | null;
+ humanValidated?: boolean | null;
+ id?: string | null;
+ keywords?: string | null;
+ legalBasis?: string | null;
+ masterCall?: string | null;
+ nature?: string | null;
+ objective?: string | null;
+ rcn?: string | null;
+ startDate?: string | null;
+ status?: string | null;
+ subCall?: string | null;
+ title?: string | null;
+ topics?: string | null;
+ totalCost?: number | null;
+ organizations?: Array | null;
+ publications?: Array | null;
+ deliverables?: Array | null;
+ reportSummaries?: Array | null;
+ topicsList?: Array | null;
+ webLinks?: Array | null;
+ eurosciVoc?: Array | null;
+ legalBasisList?: Array | null;
+ organizationCount?: number | null;
+ publicationCount?: number | null;
+ deliverableCount?: number | null;
+}
+
diff --git a/webapp/src/app/api/model/hEUPublication.ts b/webapp/src/app/api/model/hEUPublication.ts
new file mode 100644
index 00000000..4d067177
--- /dev/null
+++ b/webapp/src/app/api/model/hEUPublication.ts
@@ -0,0 +1,35 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * HEUPublication
+ */
+export interface HEUPublication {
+ authors?: string | null;
+ collection?: string | null;
+ contentUpdateDate?: string | null;
+ doi?: string | null;
+ id?: string | null;
+ isPublishedAs?: string | null;
+ journalNumber?: string | null;
+ journalTitle?: string | null;
+ projectAcronym?: string | null;
+ projectID?: string | null;
+ publishedPages?: string | null;
+ publishedYear?: number | null;
+ publisher?: string | null;
+ qaProcessedDoi?: string | null;
+ rcn?: string | null;
+ repositoryUrl?: string | null;
+ title?: string | null;
+ volume?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/hEUReportSummary.ts b/webapp/src/app/api/model/hEUReportSummary.ts
new file mode 100644
index 00000000..b9e1a299
--- /dev/null
+++ b/webapp/src/app/api/model/hEUReportSummary.ts
@@ -0,0 +1,24 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * HEUReportSummary
+ */
+export interface HEUReportSummary {
+ attachments?: string | null;
+ contentUpdateDate?: string | null;
+ id?: string | null;
+ projectAcronym?: string | null;
+ projectID?: string | null;
+ rcn?: string | null;
+ title?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/hEUTopic.ts b/webapp/src/app/api/model/hEUTopic.ts
new file mode 100644
index 00000000..a0a5e764
--- /dev/null
+++ b/webapp/src/app/api/model/hEUTopic.ts
@@ -0,0 +1,21 @@
+/**
+ * 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.
+ */
+
+
+/**
+ * HEUTopic
+ */
+export interface HEUTopic {
+ id?: string | null;
+ projectID?: string | null;
+ title?: string | null;
+ topic?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/hEUWebLink.ts b/webapp/src/app/api/model/hEUWebLink.ts
new file mode 100644
index 00000000..81c5d60f
--- /dev/null
+++ b/webapp/src/app/api/model/hEUWebLink.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.
+ */
+
+
+/**
+ * HEUWebLink
+ */
+export interface HEUWebLink {
+ archivedDate?: string | null;
+ availableLanguages?: string | null;
+ id?: string | null;
+ linkId?: string | null;
+ projectID?: string | null;
+ represents?: string | null;
+ source?: string | null;
+ status?: string | null;
+ type?: string | null;
+ url?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/ipcClassification.ts b/webapp/src/app/api/model/ipcClassification.ts
new file mode 100644
index 00000000..74805329
--- /dev/null
+++ b/webapp/src/app/api/model/ipcClassification.ts
@@ -0,0 +1,20 @@
+/**
+ * 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 IpcClassification {
+ symbol: string;
+ section?: string | null;
+ 'class'?: string | null;
+ subclass?: string | null;
+ main_group?: string | null;
+ subgroup?: string | null;
+}
+
diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts
index 89f601cc..c91170db 100644
--- a/webapp/src/app/api/model/models.ts
+++ b/webapp/src/app/api/model/models.ts
@@ -38,16 +38,45 @@ export * from './dehydratedSource';
export * from './dfgProjectDetails';
export * from './dfgProjectPage';
export * from './dfgProjectSummary';
+export * from './euCordisProjectResponse';
export * from './euOrganizationProjectSummary';
export * from './euOrganizationProjectSummaryPage';
export * from './filterInformation';
export * from './filterProperties';
+export * from './fp7EurosciVoc';
+export * from './fp7LegalBasis';
+export * from './fp7Organization';
+export * from './fp7ProjectDetails';
+export * from './fp7ProjectIPR';
+export * from './fp7Publication';
+export * from './fp7ReportSummary';
+export * from './fp7Topic';
+export * from './fp7WebLink';
export * from './funderByAuthor';
export * from './fundersByAuthorResponse';
export * from './fundingProject';
export * from './fundingProjectPage';
export * from './fwci';
export * from './groupByResult';
+export * from './h2020Deliverable';
+export * from './h2020ErcPI';
+export * from './h2020EurosciVoc';
+export * from './h2020LegalBasis';
+export * from './h2020Organization';
+export * from './h2020ProjectDetails';
+export * from './h2020Publication';
+export * from './h2020ReportSummary';
+export * from './h2020Topic';
+export * from './h2020WebLink';
+export * from './hEUDeliverable';
+export * from './hEUEurosciVoc';
+export * from './hEULegalBasis';
+export * from './hEUOrganization';
+export * from './hEUProjectDetails';
+export * from './hEUPublication';
+export * from './hEUReportSummary';
+export * from './hEUTopic';
+export * from './hEUWebLink';
export * from './hTTPValidationError';
export * from './identityGrant';
export * from './institution';
@@ -69,6 +98,7 @@ export * from './matchedOfficer';
export * from './mentionedPerson';
export * from './meta';
export * from './model2YrMeanCitedness';
+export * from './neteccontribution';
export * from './newsArticle';
export * from './newsArticleDetail';
export * from './newsPage';
diff --git a/webapp/src/app/api/model/neteccontribution.ts b/webapp/src/app/api/model/neteccontribution.ts
new file mode 100644
index 00000000..925189cf
--- /dev/null
+++ b/webapp/src/app/api/model/neteccontribution.ts
@@ -0,0 +1,14 @@
+/**
+ * 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 Neteccontribution {
+}
+
diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts
index a6a3619c..96c3842d 100644
--- a/webapp/src/app/api/model/patentEntry.ts
+++ b/webapp/src/app/api/model/patentEntry.ts
@@ -1,22 +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.
- */
+export interface IpcClassification {
+ symbol: string;
+ section: string | null;
+ class: string | null;
+ subclass: string | null;
+ main_group: string | null;
+ subgroup: string | null;
+}
export interface PatentEntry {
patent_id: string;
source: string;
- title?: string | null;
- abstract?: string | null;
- publication_date?: string | null;
- publication_year?: string | null;
- inventors?: Array;
- assignees?: Array;
- ipc?: Array;
- country?: string | null;
+ title: string | null;
+ abstract: string | null;
+ publication_date: string | null;
+ publication_year: string | null;
+ application_number: string | null;
+ application_date: string | null;
+ kind: string | null;
+ application_type: string | null;
+ number_of_claims: number | null;
+ status: string | null;
+ inventors: string[];
+ assignees: string[];
+ ipc: string[];
+ ipc_descriptions: IpcClassification[];
+ cpc: string[];
+ cpc_descriptions: IpcClassification[];
+ country: string | null;
}
+
diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts
index a7d8b279..db7e24ac 100644
--- a/webapp/src/app/app.routes.ts
+++ b/webapp/src/app/app.routes.ts
@@ -16,7 +16,8 @@ import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page.
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';
-
+import { euSingleProjectResolver } from './resolvers/eu-single-project-resolver';
+import { publicationResolver } from './resolvers/publication-resolver';
export const routes: Routes = [
{
path: '',
@@ -67,20 +68,14 @@ export const routes: Routes = [
'filterMode',
'filterYear',
];
-
- // scalar params
const scalarChanged = keys.some(
(key) => to.queryParamMap.get(key) !== from.queryParamMap.get(key),
);
-
- // multi-value param: topics
const toTopics = to.queryParamMap.getAll('topic');
const fromTopics = from.queryParamMap.getAll('topic');
-
const topicsChanged =
toTopics.length !== fromTopics.length ||
toTopics.some((t, i) => t !== fromTopics[i]);
-
return scalarChanged || topicsChanged;
},
},
@@ -105,29 +100,40 @@ export const routes: Routes = [
import('./modules/publication-detail/publication-detail.component').then(
(mod) => mod.PublicationDetailComponent,
),
+ resolve: {
+ publication: publicationResolver,
+ },
},
{
path: 'projects/dfg/:id',
canActivate: [userGuard],
pathMatch: 'full',
loadComponent: () =>
- import('./modules/person-projects/dfg-details/dfg-details.component').then(
+ import('./modules/projects/dfg-details/dfg-details.component').then(
(mod) => mod.DfgDetailsComponent,
),
- resolve: {
- dfgSingleProject: dfgSingleProjectResolver,
- },
+ resolve: { dfgSingleProject: dfgSingleProjectResolver },
},
{
path: 'projects/bund/:id',
canActivate: [userGuard],
pathMatch: 'full',
loadComponent: () =>
- import('./modules/person-projects/bund-details/bund-details.component').then(
+ import('./modules/projects/bund-details/bund-details.component').then(
(mod) => mod.BundDetailsComponent,
),
+ resolve: { bundSingleProject: bundSingleProjectResolver },
+ },
+ {
+ path: 'projects/eu/:id',
+ canActivate: [userGuard],
+ pathMatch: 'full',
+ loadComponent: () =>
+ import('./modules/projects/eu-cordis-details/eu-details.component').then(
+ (mod) => mod.EuDetailsComponent,
+ ),
resolve: {
- bundSingleProject: bundSingleProjectResolver,
+ euSingleProject: euSingleProjectResolver,
},
},
{
@@ -143,11 +149,7 @@ export const routes: Routes = [
},
runGuardsAndResolvers: (from, to) => from.params['id'] !== to.params['id'],
children: [
- {
- path: '',
- pathMatch: 'full',
- redirectTo: 'overview',
- },
+ { path: '', pathMatch: 'full', redirectTo: 'overview' },
{
path: 'overview',
loadComponent: () =>
@@ -167,7 +169,6 @@ export const routes: Routes = [
},
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
-
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
@@ -186,37 +187,8 @@ export const routes: Routes = [
import('./modules/person-network/person-network.component').then(
(mod) => mod.PersonNetworkComponent,
),
- resolve: {
- collaborationNetwork: collaborationNetworkResolver,
- },
+ resolve: { collaborationNetwork: collaborationNetworkResolver },
runGuardsAndResolvers: (from, to) => {
- const network = from.data['collaborationNetwork'] as
- | {
- filter_information?: {
- min_possible_year?: number;
- max_possible_year?: number;
- };
- }
- | undefined;
-
- const filterInformation = network?.filter_information;
-
- const defaultQueryParams: Record = {
- filter_by: 'works',
- start_year: filterInformation?.min_possible_year
- ? String(filterInformation.min_possible_year)
- : '',
- end_year: filterInformation?.max_possible_year
- ? String(filterInformation.max_possible_year)
- : '',
- min_contributors: '2',
- max_contributors: '10',
- min_collaborations: '1',
- max_collaborations: '100',
- institutions: '',
- topics: '',
- };
-
const keys = [
'filter_by',
'start_year',
@@ -228,26 +200,11 @@ export const routes: Routes = [
'institutions',
'topics',
];
-
- return keys.some((key) => {
- const fromRawValue = from.queryParamMap.get(key);
- const toRawValue = to.queryParamMap.get(key);
-
- const fromValue =
- fromRawValue === null || fromRawValue === ''
- ? defaultQueryParams[key]
- : fromRawValue;
-
- const toValue =
- toRawValue === null || toRawValue === ''
- ? defaultQueryParams[key]
- : toRawValue;
-
- return fromValue !== toValue;
- });
+ return keys.some(
+ (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
+ );
},
},
-
{
path: 'funding',
loadComponent: () =>
@@ -255,23 +212,6 @@ export const routes: Routes = [
(mod) => mod.PersonFundingComponent,
),
},
- {
- path: 'news',
- loadComponent: () =>
- 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),
- );
- },
- },
{
path: 'patents',
loadComponent: () =>
@@ -295,12 +235,9 @@ export const routes: Routes = [
import('./modules/institutions/institutions.component').then(
(mod) => mod.InstitutionsComponent,
),
- resolve: {
- institutionPage: institutionsResolver,
- },
+ resolve: { institutionPage: institutionsResolver },
runGuardsAndResolvers: (from, to) => {
const keys = ['search', 'page', 'size', 'sort_by', 'sorting_order'];
-
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
@@ -313,15 +250,9 @@ export const routes: Routes = [
import('./modules/institution/institution.component').then(
(mod) => mod.InstitutionComponent,
),
- resolve: {
- institution: institutionResolver,
- },
+ resolve: { institution: institutionResolver },
children: [
- {
- path: '',
- pathMatch: 'full',
- redirectTo: 'overview',
- },
+ { path: '', pathMatch: 'full', redirectTo: 'overview' },
{
path: 'overview',
loadComponent: () =>
@@ -338,11 +269,10 @@ export const routes: Routes = [
},
{
path: 'projects',
- loadComponent: () => {
- return import('./modules/institution-projects/institution-projects.component').then(
+ loadComponent: () =>
+ import('./modules/institution-projects/institution-projects.component').then(
(mod) => mod.InstitutionProjectsComponent,
- );
- },
+ ),
resolve: {
bundProjectPage: bundProjectPageResolver,
bundProjectsFunding: bundProjectsFundingResolver,
@@ -351,7 +281,6 @@ export const routes: Routes = [
},
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
-
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
@@ -366,9 +295,7 @@ export const routes: Routes = [
import('./modules/projects/projects.component').then(
(mod) => mod.ProjectsComponent,
),
- resolve: {
- fundingProjectPage: fundingProjectPageResolver,
- },
+ resolve: { fundingProjectPage: fundingProjectPageResolver },
runGuardsAndResolvers: (from, to) => {
const keys = [
'search',
@@ -378,12 +305,19 @@ export const routes: Routes = [
'sort_by',
'sorting_order',
];
-
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
},
+ {
+ path: 'patents',
+ canActivate: [userGuard],
+ loadComponent: () =>
+ import('./modules/patents/patents.component').then(
+ (mod) => mod.PatentsComponent,
+ ),
+ },
{
path: 'error',
loadComponent: () =>
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 dc1a3fc0..cdb886cf 100644
--- a/webapp/src/app/modules/news-detail/news-detail.component.html
+++ b/webapp/src/app/modules/news-detail/news-detail.component.html
@@ -107,13 +107,21 @@
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 82f7b1ac..17d325bb 100644
--- a/webapp/src/app/modules/news-detail/news-detail.component.scss
+++ b/webapp/src/app/modules/news-detail/news-detail.component.scss
@@ -180,6 +180,9 @@ main {
display: flex;
flex-direction: column;
gap: 8px;
+ max-height: 375px;
+ overflow-y: auto;
+ padding-right: 4px;
}
.person-item {
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 bd75dc3c..e93ec298 100644
--- a/webapp/src/app/modules/news-detail/news-detail.component.ts
+++ b/webapp/src/app/modules/news-detail/news-detail.component.ts
@@ -24,6 +24,7 @@ interface NewsArticleDetail {
full_content?: string | null;
relevant?: boolean;
authors?: MentionedPerson[];
+ keywords?: string[];
}
@Component({
@@ -49,13 +50,6 @@ export class NewsDetailComponent implements OnInit {
loading = false;
notFound = false;
- readonly relevantTopics = [
- 'Künstliche Intelligenz',
- 'Maschinelles Lernen',
- 'Digitalisierung',
- 'Datenwissenschaft',
- ];
-
private readonly chipColors = ['purple', 'blue', 'green', 'orange', 'pink'];
chipColor(index: number): string {
diff --git a/webapp/src/app/modules/news/news.component.html b/webapp/src/app/modules/news/news.component.html
index aff9aadc..c77377f2 100644
--- a/webapp/src/app/modules/news/news.component.html
+++ b/webapp/src/app/modules/news/news.component.html
@@ -4,107 +4,31 @@
Aktuelle Nachrichten aus Campus-Aktuell.
-
-
- search
-
-
-
- @if (!isSearching) {
-
-
- Neueste zuerst
- Älteste zuerst
-
-
+
+ @if (article.snippet) {
+
+ } @else {
+ —
}
-
+
-
- @if (loading) {
-
-
-
- }
-
-
-
- | Titel |
-
- {{
- article.maintitle || 'Kein Titel'
- }}
- |
-
-
-
- Fundstelle |
-
- @if (article.snippet) {
-
- } @else {
- —
- }
- |
-
-
-
- Relevanz |
-
- @if (article.relevant === true) {
-
- check_circle
- Relevant
-
- } @else if (article.relevant === false) {
-
- cancel
- Nicht relevant
-
- } @else {
-
- help
- Nicht bestimmt
-
- }
- |
-
-
-
- Datum |
-
- {{ formatDate(article.date) }}
- |
-
-
-
-
-
-
- @if (!loading && articles.length === 0) {
-
- @if (isSearching) {
- Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden.
- } @else {
- Keine Nachrichten gefunden.
- }
-
- }
-
-
-
+
+
diff --git a/webapp/src/app/modules/news/news.component.scss b/webapp/src/app/modules/news/news.component.scss
index 100dead9..3ed0d40d 100644
--- a/webapp/src/app/modules/news/news.component.scss
+++ b/webapp/src/app/modules/news/news.component.scss
@@ -17,107 +17,14 @@ h6 {
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;
-}
-
.snippet {
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
color: var(--sg-text-muted);
font-size: 13px;
- line-height: 1.4;
+ line-height: 1.45;
}
::ng-deep .snippet em {
@@ -131,79 +38,8 @@ table {
color: var(--sg-text-muted);
}
-.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;
- 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
index 3c1ff74c..c75cf38f 100644
--- a/webapp/src/app/modules/news/news.component.ts
+++ b/webapp/src/app/modules/news/news.component.ts
@@ -1,27 +1,23 @@
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 { ActivatedRoute, Router } from '@angular/router';
+import { PageEvent } from '@angular/material/paginator';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged } from 'rxjs';
import { WorksService } from '../../api';
import { PaginationService } from '../../shared/services/pagination.service';
+import {
+ NewsArticleBase,
+ NewsFilterState,
+ NewsListComponent,
+ NEWS_MIN_YEAR,
+ SortOrder,
+} from '../../shared/ui/news-list/news-list.component';
-interface NewsArticle {
- id: string;
- date?: string | null;
- maintitle?: string | null;
+interface NewsArticle extends NewsArticleBase {
author?: string | null;
- url?: string | null;
- relevant?: boolean | null;
snippet?: string | null;
}
@@ -32,22 +28,11 @@ interface NewsPage {
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,
- ],
+ imports: [ReactiveFormsModule, NewsListComponent],
templateUrl: './news.component.html',
styleUrl: './news.component.scss',
})
@@ -61,12 +46,12 @@ export class NewsComponent implements OnInit {
readonly searchControl = new FormControl('', { nonNullable: true });
- get displayedColumns(): string[] {
- if (this.isSearching) {
- return ['maintitle', 'snippet', 'relevance', 'date'];
- }
- return ['maintitle', 'relevance', 'date'];
- }
+ readonly displayedColumns: string[] = [
+ 'maintitle',
+ 'snippet',
+ 'relevance',
+ 'date',
+ ];
articles: NewsArticle[] = [];
total = 0;
@@ -75,9 +60,12 @@ export class NewsComponent implements OnInit {
currentPage = 1;
sortOrder: SortOrder = DEFAULT_SORT_ORDER;
- get isSearching(): boolean {
- return this.searchControl.value.trim().length > 0;
- }
+ relevanceValues: string[] = [];
+ yearFrom: number | null = null;
+ yearTo: number | null = null;
+
+ private readonly minYear = NEWS_MIN_YEAR;
+ private readonly maxYear = new Date().getFullYear();
ngOnInit(): void {
this.route.queryParamMap
@@ -88,6 +76,9 @@ export class NewsComponent implements OnInit {
params.get('pageSize'),
);
this.sortOrder = this.parseSortOrder(params.get('sortOrder'));
+ this.relevanceValues = this.parseRelevance(params.get('relevance'));
+ this.yearFrom = this.parseYear(params.get('yearFrom'));
+ this.yearTo = this.parseYear(params.get('yearTo'));
this.searchControl.setValue(params.get('q') ?? '', {
emitEvent: false,
});
@@ -115,10 +106,11 @@ export class NewsComponent implements OnInit {
const basePath = this.worksService.configuration.basePath ?? '';
if (query) {
- const params = new HttpParams()
+ let params = new HttpParams()
.set('query', query)
.set('page', this.currentPage)
.set('pageSize', this.paginationService.selection);
+ params = this.appendFilters(params);
this.httpClient
.get(`${basePath}/api/news/search`, { params })
@@ -135,10 +127,11 @@ export class NewsComponent implements OnInit {
},
});
} else {
- const params = new HttpParams()
+ let params = new HttpParams()
.set('page', this.currentPage)
.set('pageSize', this.paginationService.selection)
.set('sortOrder', this.sortOrder);
+ params = this.appendFilters(params);
this.httpClient
.get(`${basePath}/api/news`, { params })
@@ -157,6 +150,19 @@ export class NewsComponent implements OnInit {
}
}
+ private appendFilters(params: HttpParams): HttpParams {
+ if (this.relevanceValues.length > 0) {
+ params = params.set('relevance', this.relevanceValues.join(','));
+ }
+ if (this.yearFrom !== null) {
+ params = params.set('yearFrom', this.yearFrom);
+ }
+ if (this.yearTo !== null) {
+ params = params.set('yearTo', this.yearTo);
+ }
+ return params;
+ }
+
onPage(event: PageEvent): void {
this.router.navigate([], {
relativeTo: this.route,
@@ -179,19 +185,22 @@ export class NewsComponent implements OnInit {
});
}
- 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);
- }
+ onFiltersChange(state: NewsFilterState): void {
+ const relevance =
+ state.relevance.length > 0 ? state.relevance.join(',') : null;
+ const yearFrom = state.yearFrom > this.minYear ? state.yearFrom : null;
+ const yearTo = state.yearTo < this.maxYear ? state.yearTo : null;
- 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`;
+ this.router.navigate([], {
+ relativeTo: this.route,
+ queryParams: {
+ relevance,
+ yearFrom,
+ yearTo,
+ page: 1,
+ },
+ queryParamsHandling: 'merge',
+ });
}
private parsePage(value: string | null): number {
@@ -216,4 +225,23 @@ export class NewsComponent implements OnInit {
}
return DEFAULT_SORT_ORDER;
}
+
+ private parseRelevance(value: string | null): string[] {
+ if (!value) {
+ return [];
+ }
+ const allowed = ['relevant', 'not_relevant'];
+ return value
+ .split(',')
+ .map((entry) => entry.trim())
+ .filter((entry) => allowed.includes(entry));
+ }
+
+ private parseYear(value: string | null): number | null {
+ const year = Number.parseInt(value ?? '', 10);
+ if (Number.isNaN(year)) {
+ return null;
+ }
+ return year;
+ }
}
diff --git a/webapp/src/app/modules/patents/patents.component.html b/webapp/src/app/modules/patents/patents.component.html
new file mode 100644
index 00000000..76c7df46
--- /dev/null
+++ b/webapp/src/app/modules/patents/patents.component.html
@@ -0,0 +1,248 @@
+
+
Patente
+
+
+
+
+
+ Suche nach Titel oder Patent-Nr.
+
+ search
+
+
+
+
+
+ Alle
+ EPO
+ USPTO
+
+
+
+
+
+
+
+
+
+
+ @if (loading) {
+
+
+ Lade Patente...
+
+ } @else if (error) {
+
Fehler beim Laden der Patente.
+ } @else if (showDetail && selectedPatent) {
+
+
+
+
{{ selectedPatent.title ?? selectedPatent.patent_id }}
+
+
+
+ @if (selectedPatent.abstract) {
+
+
Abstract
+
{{ selectedPatent.abstract }}
+
+ }
+
+
+
Erfinder
+
+ @for (inv of selectedPatent.inventors; track inv) {
+ - {{ inv }}
+ }
+
+
+
+ @if (selectedPatent.assignees.length > 0) {
+
+
Anmelder
+
+ @for (a of selectedPatent.assignees; track a) {
+ - {{ a }}
+ }
+
+
+ }
+
+ @if (selectedPatent.ipc_descriptions.length > 0) {
+
+
Klassifikation (IPC)
+
+ @for (card of getClassificationCards(selectedPatent.ipc_descriptions, 'IPC'); track card.key) {
+
+
+ @if (card.primaryDescription) {
+
+ {{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }}
+
+ @if (isLongDescription(card.primaryDescription)) {
+
+ }
+ }
+ @if (card.hierarchy.length > 0) {
+
+ @for (row of card.hierarchy; track row.label) {
+
+
- {{ row.label }}
+ - {{ row.value }}
+
+ }
+
+ }
+
+ }
+
+
+ } @else if (selectedPatent.ipc.length > 0) {
+
+
Klassifikation (IPC)
+
+ @for (ipc of selectedPatent.ipc; track ipc) {
+ - {{ ipc }}
+ }
+
+
+ }
+
+ @if (selectedPatent.cpc_descriptions.length > 0) {
+
+
Klassifikation (CPC)
+
+ @for (card of getClassificationCards(selectedPatent.cpc_descriptions, 'CPC'); track card.key) {
+
+
+ @if (card.primaryDescription) {
+
+ {{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }}
+
+ @if (isLongDescription(card.primaryDescription)) {
+
+ }
+ }
+ @if (card.hierarchy.length > 0) {
+
+ @for (row of card.hierarchy; track row.label) {
+
+
- {{ row.label }}
+ - {{ row.value }}
+
+ }
+
+ }
+
+ }
+
+
+ } @else if (selectedPatent.cpc.length > 0) {
+
+
Klassifikation (CPC)
+
+ @for (cpc of selectedPatent.cpc; track cpc) {
+ - {{ cpc }}
+ }
+
+
+ }
+
+ } @else if (patents.length === 0) {
+
+
Keine Patente gefunden.
+
+ } @else {
+
+ @for (patent of patents; track patent.patent_id + (patent.publication_date ?? '')) {
+
+
+ {{ patent.title ?? patent.patent_id }}
+
+ {{ patent.source }}
+
+
+
+
+
+ {{ patent.patent_id }}
+ {{ formatDate(patent.publication_date) }}
+
+
+
+
+
+
+
+
+
+ }
+
+ }
+
+
+
+ @if (!showDetail) {
+
+ }
+
diff --git a/webapp/src/app/modules/patents/patents.component.scss b/webapp/src/app/modules/patents/patents.component.scss
new file mode 100644
index 00000000..e19ca6e1
--- /dev/null
+++ b/webapp/src/app/modules/patents/patents.component.scss
@@ -0,0 +1,280 @@
+.content {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ padding: 1rem;
+}
+
+h1 {
+ margin: 0;
+ font-size: 2rem;
+ font-weight: 700;
+ padding: 1rem 0 0;
+}
+
+.sorting {
+ display: flex;
+ justify-content: flex-end;
+ gap: 0.5rem;
+
+ select {
+ padding: 0.75rem;
+ border: 1px solid var(--sg-border);
+ border-radius: var(--sg-radius-sm);
+ font-size: 1rem;
+ cursor: pointer;
+ }
+}
+
+.search-and-filter {
+ padding: 0 1rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+
+.filter-row {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.state-message {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 24px 1rem;
+ color: #666;
+ font-size: 14px;
+
+ &.error { color: #c0392b; }
+}
+
+.cards {
+ display: grid;
+ gap: 1.5rem;
+ grid-template-columns: repeat(4, 1fr);
+ padding: 0 1rem;
+}
+
+@media (max-width: 900px) {
+ .cards {
+ grid-template-columns: repeat(2, 1fr);
+ }
+}
+
+@media (max-width: 600px) {
+ .cards {
+ grid-template-columns: 1fr;
+ }
+}
+
+mat-paginator {
+ background-color: var(--sg-background);
+}
+
+.card {
+ padding: 0.5rem;
+ background-color: var(--sg-background);
+ transition: transform 0.3s ease;
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+
+ &:hover {
+ cursor: pointer;
+ transform: scale(1.05);
+ }
+
+ mat-card-title {
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 1.4;
+ }
+}
+
+.card-content {
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-end;
+ gap: 0.5rem;
+ flex: 1;
+}
+
+.card-metadata {
+ display: flex;
+ flex-direction: column;
+ gap: 0.2rem;
+ font-size: 0.9rem;
+ color: var(--sg-text-secondary);
+}
+
+mat-card-actions {
+ padding-top: 0.5rem;
+ display: flex;
+ gap: 0.5rem;
+
+ button {
+ width: 100%;
+ border: 1px solid var(--sg-border);
+ border-radius: var(--sg-radius-sm);
+ }
+}
+
+.source-badge {
+ display: inline-flex;
+ align-items: center;
+ padding: 3px 10px;
+ border-radius: 999px;
+ font-size: 0.75rem;
+ font-weight: 700;
+
+ &--epo { background: #effaf3; color: #24834f; border: 1px solid #bdebcf; }
+ &--uspto { background: #f0f6ff; color: #0b63ce; border: 1px solid #bdd4ff; }
+}
+
+.no-results {
+ text-align: center;
+ padding: 2rem;
+ color: var(--sg-text-secondary);
+}
+
+.detail-view {
+ padding: 1rem;
+
+ h2 { margin: 0 0 1rem; font-size: 1.4rem; color: #333; line-height: 1.4; }
+ h4 { margin: 16px 0 8px; font-size: 14px; color: #555; font-weight: 600; }
+ p { font-size: 13px; color: #444; line-height: 1.6; margin: 0; }
+}
+
+.back-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ margin-bottom: 1rem;
+ padding: 0.5rem 0.85rem;
+ border: 1px solid #d6e3f8;
+ border-radius: 999px;
+ background: #f8fbff;
+ color: #2563eb;
+ font-size: 0.9rem;
+ font-weight: 600;
+ cursor: pointer;
+
+ &:hover { background: #eef5ff; border-color: #bcd3f7; }
+}
+
+.patent-meta__list {
+ margin: 12px 0 20px;
+ border: 1px solid #e2e8f4;
+ border-radius: 12px;
+ background: linear-gradient(180deg, #fff 0%, #f8faff 100%);
+ overflow: hidden;
+}
+
+.patent-meta__row {
+ display: grid;
+ grid-template-columns: minmax(130px, 38%) 1fr;
+ gap: 12px 16px;
+ align-items: center;
+ padding: 11px 16px;
+ border-top: 1px solid #eef2f8;
+
+ &:first-child { border-top: 0; }
+
+ dt { margin: 0; font-size: 12px; font-weight: 500; color: #64748b; }
+ dd { margin: 0; font-size: 14px; font-weight: 600; color: #1e293b; word-break: break-word; }
+}
+
+.detail-section {
+ margin-top: 12px;
+ padding-top: 12px;
+ border-top: 1px solid #eee;
+}
+
+.tag-list {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+
+ &--compact .tag { font-size: 0.75rem; padding: 3px 8px; }
+}
+
+.tag {
+ padding: 4px 10px;
+ border-radius: 999px;
+ background: #f0f6ff;
+ border: 1px solid #dbeafe;
+ color: #1e40af;
+ font-size: 0.8rem;
+}
+
+.classification-section {
+ &--ipc .classification-card { background: #f0f6ff; border-color: #bfdbfe; }
+ &--ipc .classification-badge--system { background: #dbeafe; color: #1d4ed8; }
+ &--cpc .classification-card { background: #f0fdf4; border-color: #bbf7d0; }
+ &--cpc .classification-badge--system { background: #dcfce7; color: #15803d; }
+}
+
+.classification-cards { display: flex; flex-direction: column; gap: 10px; }
+
+.classification-card {
+ padding: 12px 14px;
+ border-radius: 10px;
+ border: 1px solid #dbeafe;
+}
+
+.classification-card__header {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+}
+
+.classification-card__codes { display: flex; flex-wrap: wrap; gap: 6px; }
+.classification-card__badges { display: flex; flex-wrap: wrap; gap: 6px; }
+.classification-code { font-size: 0.9rem; font-weight: 700; color: #0f172a; }
+
+.classification-badge {
+ display: inline-flex;
+ align-items: center;
+ padding: 2px 8px;
+ border-radius: 999px;
+ font-size: 0.68rem;
+ font-weight: 700;
+ text-transform: uppercase;
+}
+
+.classification-badge--level { background: #e2e8f0; color: #475569; }
+.classification-summary { margin: 10px 0 0; font-size: 0.84rem; line-height: 1.5; color: #334155; }
+
+.classification-toggle {
+ margin-top: 6px;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: #2563eb;
+ font-size: 0.78rem;
+ cursor: pointer;
+ &:hover { text-decoration: underline; }
+}
+
+.classification-hierarchy {
+ margin: 10px 0 0;
+ padding-top: 10px;
+ border-top: 1px solid rgba(15, 23, 42, 0.08);
+}
+
+.classification-hierarchy__row {
+ display: grid;
+ grid-template-columns: 88px 1fr;
+ gap: 8px;
+ margin-bottom: 6px;
+
+ dt { margin: 0; font-size: 0.72rem; font-weight: 700; color: #64748b; text-transform: uppercase; }
+ dd { margin: 0; font-size: 0.8rem; line-height: 1.45; color: #334155; }
+}
diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts
new file mode 100644
index 00000000..d946a0e5
--- /dev/null
+++ b/webapp/src/app/modules/patents/patents.component.ts
@@ -0,0 +1,307 @@
+import { Component, OnInit, inject } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { ActivatedRoute, Router, RouterModule } from '@angular/router';
+import { MatIconModule } from '@angular/material/icon';
+import { MatButtonModule } from '@angular/material/button';
+import { MatCardModule } from '@angular/material/card';
+import { MatFormFieldModule } from '@angular/material/form-field';
+import { MatInputModule } from '@angular/material/input';
+import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
+import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
+import { MatChipsModule } from '@angular/material/chips';
+import { MatDividerModule } from '@angular/material/divider';
+import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
+import { debounceTime, distinctUntilChanged, Subject } from 'rxjs';
+import { PatentsService } from '../../api/api/patents.service';
+import { PatentEntry, IpcClassification } from '../../api/model/patentEntry';
+
+type SourceFilter = 'all' | 'EPO' | 'USPTO';
+type ClassificationSystem = 'IPC' | 'CPC';
+
+interface ClassificationCard {
+ key: string;
+ symbols: string[];
+ system: ClassificationSystem;
+ levelLabel: string;
+ primaryDescription: string | null;
+ hierarchy: { label: string; value: string }[];
+}
+
+const DESCRIPTION_PREVIEW_LENGTH = 140;
+
+@Component({
+ selector: 'app-patents',
+ imports: [
+ CommonModule,
+ RouterModule,
+ MatIconModule,
+ MatButtonModule,
+ MatCardModule,
+ MatFormFieldModule,
+ MatInputModule,
+ MatPaginatorModule,
+ MatProgressSpinnerModule,
+ MatChipsModule,
+ MatDividerModule,
+ ],
+ templateUrl: './patents.component.html',
+ styleUrl: './patents.component.scss',
+})
+export class PatentsComponent implements OnInit {
+ private router = inject(Router);
+ private route = inject(ActivatedRoute);
+ private patentsApi = inject(PatentsService);
+
+ patents: PatentEntry[] = [];
+ total = 0;
+ page = 0;
+ pageSize = 10;
+
+ loading = true;
+ error = false;
+
+ searchTerm = '';
+ activeFilter: SourceFilter = 'all';
+ sortDirection: string = 'desc';
+
+ selectedPatent: PatentEntry | null = null;
+ showDetail = false;
+ private expandedClassificationKeys = new Set();
+
+ private searchSubject = new Subject();
+
+ constructor() {
+ this.searchSubject
+ .pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed())
+ .subscribe((term) => {
+ this.searchTerm = term;
+ this.page = 0;
+ this.selectedPatent = null;
+ this.showDetail = false;
+ this.loadPatents();
+ this.updateQueryParams();
+ });
+ }
+
+ ngOnInit(): void {
+ const qp = this.route.snapshot.queryParamMap;
+ this.searchTerm = qp.get('search') ?? '';
+ this.page = parseInt(qp.get('page') ?? '0', 10);
+ this.pageSize = parseInt(qp.get('size') ?? '10', 10);
+ const f = qp.get('source');
+ if (f === 'EPO' || f === 'USPTO') this.activeFilter = f;
+ const d = qp.get('sort_direction');
+ if (d === 'asc' || d === 'desc') this.sortDirection = d;
+
+ this.loadPatents();
+ }
+
+ private loadPatents(): void {
+ this.loading = true;
+ this.error = false;
+ const source = this.activeFilter === 'all' ? undefined : this.activeFilter;
+
+ this.patentsApi
+ .getAllPatents(this.page, this.pageSize, this.searchTerm || undefined, source, 'date', this.sortDirection)
+ .subscribe({
+ next: (res) => {
+ this.patents = res.patents;
+ this.total = res.total;
+ this.loading = false;
+ },
+ error: () => {
+ this.error = true;
+ this.loading = false;
+ },
+ });
+ }
+
+ onSearchInput(event: Event): void {
+ this.searchSubject.next((event.target as HTMLInputElement).value);
+ }
+
+ clearSearch(): void {
+ this.searchTerm = '';
+ this.page = 0;
+ this.selectedPatent = null;
+ this.showDetail = false;
+ this.loadPatents();
+ this.updateQueryParams();
+ }
+
+ setFilterFromChip(event: any): void {
+ const val = event.value;
+ this.activeFilter = val === 'EPO' || val === 'USPTO' ? val : 'all';
+ this.page = 0;
+ this.selectedPatent = null;
+ this.showDetail = false;
+ this.loadPatents();
+ this.updateQueryParams();
+ }
+
+ setSortDirection(direction: string): void {
+ this.sortDirection = direction;
+ this.loadPatents();
+ this.updateQueryParams();
+ }
+
+ handlePageChange(event: PageEvent): void {
+ this.page = event.pageIndex;
+ this.pageSize = event.pageSize;
+ this.selectedPatent = null;
+ this.showDetail = false;
+ this.loadPatents();
+ this.updateQueryParams();
+ }
+
+ selectPatent(patent: PatentEntry): void {
+ this.selectedPatent = patent;
+ this.showDetail = true;
+ this.expandedClassificationKeys.clear();
+ }
+
+ closeDetail(): void {
+ this.showDetail = false;
+ this.selectedPatent = null;
+ this.expandedClassificationKeys.clear();
+ }
+
+ private updateQueryParams(): void {
+ this.router.navigate([], {
+ relativeTo: this.route,
+ queryParams: {
+ search: this.searchTerm || null,
+ page: this.page,
+ size: this.pageSize,
+ source: this.activeFilter === 'all' ? null : this.activeFilter,
+ sort_direction: this.sortDirection,
+ },
+ queryParamsHandling: 'merge',
+ replaceUrl: true,
+ });
+ }
+
+ formatDate(date: string | null): string {
+ if (!date) return '-';
+ const d = date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
+ const parsed = new Date(d);
+ if (isNaN(parsed.getTime())) return date;
+ return new Intl.DateTimeFormat('de-DE').format(parsed);
+ }
+
+ getPublicationStageLabel(patent: PatentEntry): string | null {
+ return patent.kind ?? patent.application_type ?? null;
+ }
+
+ getPatentMetadataRows(patent: PatentEntry) {
+ const rows: { label: string; value: string; variant?: 'source' }[] = [];
+ rows.push({ label: 'Quelle', value: patent.source, variant: 'source' });
+ rows.push({ label: 'Patent-Nr.', value: patent.patent_id });
+ if (patent.publication_date)
+ rows.push({ label: 'Veröffentlichungsdatum', value: this.formatDate(patent.publication_date) });
+ if (patent.application_number)
+ rows.push({ label: 'Anmeldungsnummer', value: patent.application_number });
+ if (patent.application_date)
+ rows.push({ label: 'Anmeldedatum', value: this.formatDate(patent.application_date) });
+ const stage = this.getPublicationStageLabel(patent);
+ if (stage)
+ rows.push({ label: patent.kind ? 'Publikationsstufe' : 'Anmeldungstyp', value: this.formatMetadataLabel(stage) });
+ if (patent.number_of_claims != null)
+ rows.push({ label: 'Ansprüche', value: String(patent.number_of_claims) });
+ if (patent.status)
+ rows.push({ label: 'Status', value: this.formatMetadataLabel(patent.status) });
+ return rows;
+ }
+
+ private formatMetadataLabel(value: string): string {
+ return value.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase());
+ }
+
+ getClassificationCards(
+ entries: IpcClassification[] | undefined,
+ system: ClassificationSystem,
+ ): ClassificationCard[] {
+ if (!entries?.length) return [];
+ const merged = new Map();
+ for (const entry of entries) {
+ const card = this.buildClassificationCard(entry, system);
+ const mergeKey = card.primaryDescription?.toLocaleLowerCase('en') ?? card.symbols[0] ?? card.key;
+ const existing = merged.get(mergeKey);
+ if (existing) {
+ for (const s of card.symbols) {
+ if (!existing.symbols.includes(s)) existing.symbols.push(s);
+ }
+ continue;
+ }
+ merged.set(mergeKey, card);
+ }
+ return [...merged.values()];
+ }
+
+ toggleClassificationExpanded(key: string): void {
+ this.expandedClassificationKeys.has(key)
+ ? this.expandedClassificationKeys.delete(key)
+ : this.expandedClassificationKeys.add(key);
+ }
+
+ isClassificationExpanded(key: string): boolean {
+ return this.expandedClassificationKeys.has(key);
+ }
+
+ isLongDescription(text: string | null): boolean {
+ return !!text && text.length > DESCRIPTION_PREVIEW_LENGTH;
+ }
+
+ getDescriptionPreview(text: string | null): string {
+ if (!text) return '';
+ return text.length <= DESCRIPTION_PREVIEW_LENGTH
+ ? text
+ : `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`;
+ }
+
+ private buildClassificationCard(entry: IpcClassification, system: ClassificationSystem): ClassificationCard {
+ const level = this.getClassificationLevel(entry);
+ const primaryDescription = this.extractDescriptionText(entry[level.field]);
+ return {
+ key: `${system}-${entry.symbol}`,
+ symbols: [entry.symbol],
+ system,
+ levelLabel: level.label,
+ primaryDescription,
+ hierarchy: this.buildHierarchyRows(entry, primaryDescription),
+ };
+ }
+
+ private getClassificationLevel(entry: IpcClassification): { label: string; field: keyof IpcClassification } {
+ if (entry.subgroup) return { label: 'Untergruppe', field: 'subgroup' };
+ if (entry.main_group) return { label: 'Hauptgruppe', field: 'main_group' };
+ if (entry.subclass) return { label: 'Unterklasse', field: 'subclass' };
+ if (entry.section) return { label: 'Sektion', field: 'section' };
+ return { label: 'Code', field: 'symbol' };
+ }
+
+ private buildHierarchyRows(entry: IpcClassification, primaryDescription: string | null) {
+ const rows: { label: string; value: string }[] = [];
+ const seen = new Set();
+ const addRow = (label: string, raw: string | null) => {
+ const value = this.extractDescriptionText(raw);
+ if (!value) return;
+ const norm = value.toLocaleLowerCase('en');
+ if (seen.has(norm) || norm === primaryDescription?.toLocaleLowerCase('en')) return;
+ seen.add(norm);
+ rows.push({ label, value });
+ };
+ addRow('Sektion', entry.section);
+ addRow('Klasse', entry.class);
+ addRow('Unterklasse', entry.subclass);
+ return rows;
+ }
+
+ private extractDescriptionText(value: string | null | undefined): string | null {
+ if (!value?.trim()) return null;
+ const text = value.includes(' - ') ? value.split(' - ').slice(1).join(' - ').trim() : value.trim();
+ if (!text) return null;
+ const first = text.split(/[;|]/)[0]?.trim() ?? text;
+ return first === first.toUpperCase() ? first.charAt(0) + first.slice(1).toLowerCase() : first;
+ }
+}
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 b4f717db..651e39d4 100644
--- a/webapp/src/app/modules/person-news/person-news.component.html
+++ b/webapp/src/app/modules/person-news/person-news.component.html
@@ -4,79 +4,15 @@
Aktuelle Nachrichten zu dieser Person.
-
-
- search
-
-
-
-
-
- Neueste zuerst
- Älteste zuerst
-
-
-
-
-
- @if (loading) {
-
-
-
- }
-
-
-
- @if (!loading && articles.length === 0) {
-
- @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.scss b/webapp/src/app/modules/person-news/person-news.component.scss
index 68a1899f..6cad4cdb 100644
--- a/webapp/src/app/modules/person-news/person-news.component.scss
+++ b/webapp/src/app/modules/person-news/person-news.component.scss
@@ -17,140 +17,8 @@ h6 {
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
index b0e6356b..f05391e9 100644
--- a/webapp/src/app/modules/person-news/person-news.component.ts
+++ b/webapp/src/app/modules/person-news/person-news.component.ts
@@ -1,33 +1,21 @@
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
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 { ActivatedRoute, Router } from '@angular/router';
+import { PageEvent } from '@angular/material/paginator';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged } from 'rxjs';
import { PaginationService } from '../../shared/services/pagination.service';
import { ResolverStateService } from '../../shared/services/resolver-state.service';
import { NewsArticle, NewsPage } from '../../resolvers/person-news.resolver';
+import {
+ NewsListComponent,
+ SortOrder,
+} from '../../shared/ui/news-list/news-list.component';
@Component({
selector: 'app-person-news',
- imports: [
- MatIconModule,
- MatSelectModule,
- MatFormFieldModule,
- MatInputModule,
- MatPaginatorModule,
- MatProgressSpinnerModule,
- MatTableModule,
- ReactiveFormsModule,
- RouterLink,
- ],
+ imports: [ReactiveFormsModule, NewsListComponent],
templateUrl: './person-news.component.html',
styleUrl: './person-news.component.scss',
})
@@ -40,11 +28,11 @@ export class PersonNewsComponent implements OnInit {
readonly searchControl = new FormControl('', { nonNullable: true });
- displayedColumns = ['maintitle', 'author', 'date'];
+ displayedColumns = ['maintitle', 'relevance', 'date'];
articles: NewsArticle[] = [];
total = 0;
- currentPageIndex = 0;
- sortOrder: 'desc' | 'asc' = 'desc';
+ currentPage = 1;
+ sortOrder: SortOrder = 'desc';
get loading(): boolean {
return this.resolverStateService.isResolving();
@@ -75,7 +63,7 @@ export class PersonNewsComponent implements OnInit {
const sortOrder = params.get('sortOrder');
const query = params.get('query') ?? '';
- this.currentPageIndex = page - 1;
+ this.currentPage = page;
this.paginationService.selection = pageSize;
this.sortOrder = sortOrder === 'asc' ? 'asc' : 'desc';
this.searchControl.setValue(query, { emitEvent: false });
@@ -103,30 +91,13 @@ export class PersonNewsComponent implements OnInit {
});
}
- onSortChange(order: 'desc' | 'asc'): void {
+ onSortChange(order: SortOrder): void {
this.updateQueryParams({
sortOrder: order,
page: 1,
});
}
- 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`;
- }
-
private updateQueryParams(
overrides: Record,
): void {
diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html
index 054163c2..dc376937 100644
--- a/webapp/src/app/modules/person-patents/person-patents.component.html
+++ b/webapp/src/app/modules/person-patents/person-patents.component.html
@@ -1,179 +1,291 @@
-@if (loading) {
- Lade Patente...
-} @else if (error) {
- Fehler beim Laden der Patente.
-} @else if (patents.length === 0) {
- Keine Patente gefunden.
-} @else {
-
-
-
- {{ filteredPatents.length }}
- Patente
-
-
- {{ getEpoCount() }}
- EPO
-
-
- {{ getUsptoCount() }}
- USPTO
-
-
-
- @if (showDetail && selectedPatent) {
-
- }
-
-
- @if (showDetail && selectedPatent) {
-
-
{{ selectedPatent.title ?? selectedPatent.patent_id }}
-
- @if (selectedPatent.abstract) {
-
-
Abstract
-
{{ selectedPatent.abstract }}
-
- }
-
-
-
Erfinder
-
- @for (inventor of selectedPatent.inventors; track inventor) {
- - {{ inventor }}
- }
-
-
-
- @if (hasAsignees(selectedPatent)) {
-
-
Anmelder
-
- @for (assignee of selectedPatent.assignees; track assignee) {
- - {{ assignee }}
- }
-
-
- }
-
- @if (hasIpcs(selectedPatent)) {
-
-
Klassifikation (IPC)
-
- @for (ipc of selectedPatent.ipc; track ipc) {
- - {{ ipc }}
- }
-
-
- }
-
- }
-
-
-
-
-
-
-
-
-
-
- | Patent |
- Quelle |
- Jahr |
-
-
-
- @for (patent of getPagedPatents(); track patent.patent_id) {
-
- |
- {{ patent.title ?? patent.patent_id }}
- |
-
-
- {{ patent.source }}
-
- |
- {{ patent.publication_year ?? '-' }} |
-
- }
-
-
-
- @if (hasPagination()) {
-
- }
-
-
- @if (selectedPatent) {
-
-
{{ selectedPatent.title ?? selectedPatent.patent_id }}
-
-
- Quelle
-
-
- {{ selectedPatent.source }}
-
-
-
-
- Patent-Nr.
- {{ selectedPatent.patent_id }}
-
-
- Datum
- {{
- formatDate(selectedPatent.publication_date || '')
- }}
-
-
-
- } @else {
-
-
Klicke auf ein Patent für Details.
-
- }
-
-
-}
+@if (loading) {
+ Lade Patente...
+} @else if (error) {
+ Fehler beim Laden der Patente.
+} @else if (patents.length === 0) {
+ Keine Patente gefunden.
+} @else {
+
+
+
+ @if (showDetail && selectedPatent) {
+
+
+
+
{{ selectedPatent.title ?? selectedPatent.patent_id }}
+
+ @if (hasPatentMetadata(selectedPatent)) {
+
+ }
+
+ @if (selectedPatent.abstract) {
+
+
Abstract
+
{{ selectedPatent.abstract }}
+
+ }
+
+
+
Erfinder
+
+ @for (inventor of selectedPatent.inventors; track inventor) {
+ - {{ inventor }}
+ }
+
+
+
+ @if (selectedPatent.assignees && selectedPatent.assignees.length > 0) {
+
+
Anmelder
+
+ @for (assignee of selectedPatent.assignees; track assignee) {
+ - {{ assignee }}
+ }
+
+
+ }
+
+ @if (selectedPatent.ipc_descriptions && selectedPatent.ipc_descriptions.length > 0) {
+
+
Klassifikation (IPC)
+
+ @for (card of getClassificationCards(selectedPatent.ipc_descriptions, 'IPC'); track card.key) {
+
+
+
+ @if (card.primaryDescription) {
+
+ {{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }}
+
+ @if (isLongDescription(card.primaryDescription)) {
+
+ }
+ }
+
+ @if (card.hierarchy.length > 0) {
+
+ @for (row of card.hierarchy; track row.label) {
+
+
- {{ row.label }}
+ - {{ row.value }}
+
+ }
+
+ }
+
+ }
+
+
+ } @else if (selectedPatent.ipc && selectedPatent.ipc.length > 0) {
+
+
Klassifikation (IPC)
+
+ @for (ipc of selectedPatent.ipc; track ipc) {
+ - {{ ipc }}
+ }
+
+
+ }
+
+ @if (selectedPatent.cpc_descriptions && selectedPatent.cpc_descriptions.length > 0) {
+
+
Klassifikation (CPC)
+
+ @for (card of getClassificationCards(selectedPatent.cpc_descriptions, 'CPC'); track card.key) {
+
+
+
+ @if (card.primaryDescription) {
+
+ {{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }}
+
+ @if (isLongDescription(card.primaryDescription)) {
+
+ }
+ }
+
+ @if (card.hierarchy.length > 0) {
+
+ @for (row of card.hierarchy; track row.label) {
+
+
- {{ row.label }}
+ - {{ row.value }}
+
+ }
+
+ }
+
+ }
+
+
+ }
+
+
+ }
+
+
+
+
+
+
+
+
+
+
+ | Patent |
+ Quelle |
+ Jahr |
+
+
+
+ @for (patent of getPagedPatents(); track trackPatent($index, patent)) {
+
+ | {{ patent.title ?? patent.patent_id }} |
+
+
+ {{ patent.source }}
+
+ |
+ {{ patent.publication_year ?? '-' }} |
+
+ }
+
+
+
+ @if (hasPagination()) {
+
+ }
+
+
+ @if (selectedPatent && !showDetail) {
+
+
{{ selectedPatent.title ?? selectedPatent.patent_id }}
+
+
+ Quelle
+
+
+ {{ selectedPatent.source }}
+
+
+
+
+ Patent-Nr.
+ {{ selectedPatent.patent_id }}
+
+
+ Datum
+ {{ formatDate(selectedPatent.publication_date) }}
+
+ @if (getPublicationStageLabel(selectedPatent); as stageLabel) {
+
+ Publikationsstufe
+ {{ stageLabel }}
+
+ }
+
+
+ @if (getAbstractPreview(selectedPatent.abstract); as abstractPreview) {
+
{{ abstractPreview }}
+ }
+
+
+
+ Abstract, Erfinder, Anmelder und IPC/CPC-Klassifikation
+
+
+ } @else {
+
+
Patentübersicht
+
Alle Patente dieser Person im Überblick.
+
+
+ {{ patents.length }}
+ Patente
+
+
+ {{ getEpoCount() }}
+ EPO
+
+
+ {{ getUsptoCount() }}
+ USPTO
+
+
+
Wähle links ein Patent aus, um Kurzinfos und Details zu sehen.
+
+ }
+
+
+}
diff --git a/webapp/src/app/modules/person-patents/person-patents.component.scss b/webapp/src/app/modules/person-patents/person-patents.component.scss
index 59079610..37cac10f 100644
--- a/webapp/src/app/modules/person-patents/person-patents.component.scss
+++ b/webapp/src/app/modules/person-patents/person-patents.component.scss
@@ -1,306 +1,564 @@
-.message {
- padding: 16px;
- color: #666;
-}
-
-.patents-container {
- padding: 16px;
- display: flex;
- flex-direction: column;
- gap: 16px;
-}
-
-.patents-summary {
- margin-bottom: 8px;
- display: flex;
- gap: 24px;
-
- .summary-line {
- margin: 0;
- font-size: 14px;
- color: #333;
- }
-
- .summary-label {
- color: #333;
- }
-
- .summary-value {
- font-weight: 600;
- color: #333;
- }
-}
-
-.sort-control {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- width: fit-content;
- padding: 10px 14px;
- border-radius: 20px;
- background: #f2f2f2;
- color: #333;
- font-size: 14px;
-
- span {
- color: #555;
- }
-
- select {
- border: 0;
- background: transparent;
- color: #111827;
- font: inherit;
- cursor: pointer;
- outline: none;
- }
-}
-
-.patents-content {
- display: flex;
- gap: 24px;
- align-items: flex-start;
-}
-
-.patents-list {
- flex: 1;
-
- &.hidden {
- display: none;
- }
-
- .patents-list-toolbar {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 16px;
- margin-bottom: 18px;
- flex-wrap: wrap;
- }
-
- table {
- width: 100%;
- border-collapse: collapse;
-
- th {
- text-align: left;
- padding: 10px 12px;
- border-bottom: 2px solid #e0e0e0;
- font-weight: 600;
- color: #333;
- }
-
- tr {
- cursor: pointer;
-
- &:hover {
- background: #f5f5f5;
- }
-
- &.selected {
- background: #f0f0f0;
- }
- }
-
- td {
- padding: 10px 12px;
- border-bottom: 1px solid #f0f0f0;
- }
-
- .patent-title {
- color: #333;
- font-weight: 500;
- max-width: 400px;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
- }
-}
-
-.source-badge {
- display: inline-flex;
- align-items: center;
- padding: 3px 10px;
- border-radius: 999px;
- font-size: 0.75rem;
- font-weight: 700;
-
- &--epo {
- background: #effaf3;
- color: #24834f;
- border: 1px solid #bdebcf;
- }
-
- &--uspto {
- background: #f0f6ff;
- color: #0b63ce;
- border: 1px solid #bdd4ff;
- }
-}
-
-.patent-detail {
- width: 440px;
- border: 1px solid #e0e0e0;
- border-radius: 8px;
- padding: 20px;
- background: #fafafa;
-
- &.empty {
- display: flex;
- align-items: center;
- justify-content: center;
- color: #999;
- min-height: 200px;
- }
-
- h3 {
- margin: 0 0 16px 0;
- font-size: 16px;
- color: #333;
- line-height: 1.4;
- }
-}
-
-.detail-stats {
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 10px;
-
- .stat {
- background: white;
- border: 1px solid #e0e0e0;
- border-radius: 8px;
- padding: 10px;
- text-align: center;
-
- .stat-label {
- display: block;
- font-size: 11px;
- color: #666;
- margin-bottom: 4px;
- text-transform: uppercase;
- letter-spacing: 0.03em;
- }
-
- .stat-value {
- display: block;
- font-size: 15px;
- font-weight: bold;
- color: #333;
- }
- }
-}
-
-.stat--clickable {
- cursor: pointer;
- transition:
- border-color 0.15s,
- background 0.15s;
-
- &:hover {
- border-color: #0b63ce;
- background: #f0f6ff;
- }
-}
-
-.patent-full-detail {
- flex: 1;
- border: 1px solid #e0e0e0;
- border-radius: 8px;
- padding: 20px;
- background: #fafafa;
-
- h3 {
- margin: 0 0 16px 0;
- font-size: 16px;
- color: #333;
- line-height: 1.4;
- }
-
- h4 {
- margin: 16px 0 8px 0;
- font-size: 14px;
- color: #555;
- font-weight: 600;
- }
-
- p {
- font-size: 13px;
- color: #444;
- line-height: 1.6;
- margin: 0;
- }
-}
-
-.back-btn {
- border: none;
- background: none;
- color: #333;
- cursor: pointer;
- font-size: 14px;
- font-weight: 400;
- padding: 0;
- align-self: flex-start; // NEU
-
- &:hover {
- text-decoration: underline;
- }
-}
-
-.detail-section {
- margin-top: 12px;
- padding-top: 12px;
- border-top: 1px solid #eee;
-}
-
-.tag-list {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- margin: 0;
- padding: 0;
- list-style: none;
-
- &--compact .tag {
- font-size: 0.75rem;
- padding: 3px 8px;
- }
-}
-
-.tag {
- padding: 4px 10px;
- border-radius: 999px;
- background: #f0f6ff;
- border: 1px solid #dbeafe;
- color: #1e40af;
- font-size: 0.8rem;
- line-height: 1.3;
-}
-
-.pagination {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 8px;
- margin-top: 12px;
-
- button {
- padding: 4px 10px;
- border: 1px solid #d0d0d0;
- border-radius: 6px;
- background: white;
- cursor: pointer;
- font-size: 12px;
-
- &:disabled {
- opacity: 0.5;
- cursor: default;
- }
- }
-
- span {
- font-size: 12px;
- color: #666;
- }
-}
+.message {
+ padding: 16px;
+ color: #666;
+}
+
+.patents-container {
+ padding: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+}
+
+.sort-control {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ width: fit-content;
+ padding: 10px 14px;
+ border-radius: 20px;
+ background: #f2f2f2;
+ color: #333;
+ font-size: 14px;
+
+ span {
+ color: #555;
+ }
+
+ select {
+ border: 0;
+ background: transparent;
+ color: #111827;
+ font: inherit;
+ cursor: pointer;
+ outline: none;
+ }
+}
+
+.patents-content {
+ display: flex;
+ gap: 24px;
+ align-items: flex-start;
+}
+
+.patents-list {
+ flex: 1;
+
+ &.hidden {
+ display: none;
+ }
+
+ .patents-list-toolbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ margin-bottom: 18px;
+ flex-wrap: wrap;
+ }
+
+ table {
+ width: 100%;
+ border-collapse: collapse;
+
+ th {
+ text-align: left;
+ padding: 10px 12px;
+ border-bottom: 2px solid #e0e0e0;
+ font-weight: 600;
+ color: #333;
+ }
+
+ tr {
+ cursor: pointer;
+
+ &:hover {
+ background: #f5f5f5;
+ }
+
+ &.selected {
+ background: #f0f0f0;
+ }
+ }
+
+ td {
+ padding: 10px 12px;
+ border-bottom: 1px solid #f0f0f0;
+ }
+
+ .patent-title {
+ color: #333;
+ font-weight: 500;
+ max-width: 400px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ }
+}
+
+.source-badge {
+ display: inline-flex;
+ align-items: center;
+ padding: 3px 10px;
+ border-radius: 999px;
+ font-size: 0.75rem;
+ font-weight: 700;
+
+ &--epo {
+ background: #effaf3;
+ color: #24834f;
+ border: 1px solid #bdebcf;
+ }
+
+ &--uspto {
+ background: #f0f6ff;
+ color: #0b63ce;
+ border: 1px solid #bdd4ff;
+ }
+}
+
+.patent-detail {
+ width: 440px;
+ border: 1px solid #e0e0e0;
+ border-radius: 8px;
+ padding: 20px;
+ background: #fafafa;
+
+ &.empty {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: #999;
+ min-height: 200px;
+ }
+
+ &.overview {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+
+ .overview-title {
+ font-size: 15px;
+ font-weight: 600;
+ color: #333;
+ margin: 0;
+ }
+
+ .overview-subtitle {
+ font-size: 13px;
+ color: #888;
+ margin: 0;
+ }
+
+ .overview-stats {
+ display: grid;
+ grid-template-columns: 1fr 1fr 1fr;
+ gap: 10px;
+ margin-top: 4px;
+ }
+
+ .overview-stat {
+ background: white;
+ border: 1px solid #e0e0e0;
+ border-radius: 8px;
+ padding: 12px 8px;
+ text-align: center;
+
+ .overview-value {
+ display: block;
+ font-size: 22px;
+ font-weight: 700;
+ color: #333;
+ }
+
+ .overview-label {
+ display: block;
+ font-size: 12px;
+ color: #888;
+ margin-top: 4px;
+ }
+ }
+
+ .overview-hint {
+ font-size: 12px;
+ color: #aaa;
+ margin: 0;
+ }
+ }
+
+ h3 {
+ margin: 0 0 16px 0;
+ font-size: 16px;
+ color: #333;
+ line-height: 1.4;
+ }
+}
+
+.detail-stats {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 10px;
+
+ .stat {
+ background: white;
+ border: 1px solid #e0e0e0;
+ border-radius: 8px;
+ padding: 10px;
+ text-align: center;
+
+ .stat-label {
+ display: block;
+ font-size: 11px;
+ color: #666;
+ margin-bottom: 4px;
+ text-transform: uppercase;
+ letter-spacing: 0.03em;
+ }
+
+ .stat-value {
+ display: block;
+ font-size: 15px;
+ font-weight: bold;
+ color: #333;
+ }
+ }
+}
+
+.patent-detail-preview {
+ margin: 14px 0 0;
+ font-size: 13px;
+ line-height: 1.55;
+ color: #555;
+}
+
+.patent-detail-action {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ width: 100%;
+ margin-top: 16px;
+ padding: 12px 14px;
+ border: 1px solid #bdd4ff;
+ border-radius: 10px;
+ background: linear-gradient(180deg, #f8fbff 0%, #eef4ff 100%);
+ color: #0b63ce;
+ font-size: 14px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: border-color 0.15s, background 0.15s, box-shadow 0.15s;
+
+ &:hover {
+ border-color: #0b63ce;
+ background: #f0f6ff;
+ box-shadow: 0 2px 8px rgba(11, 99, 206, 0.12);
+ }
+
+ .material-icons {
+ font-size: 20px;
+ }
+}
+
+.patent-detail-hint {
+ margin: 8px 0 0;
+ font-size: 12px;
+ line-height: 1.4;
+ color: #888;
+ text-align: center;
+}
+
+.patent-full-detail {
+ flex: 1;
+ border: 1px solid #e0e0e0;
+ border-radius: 8px;
+ padding: 20px;
+ background: #fafafa;
+
+ h3 {
+ margin: 0 0 4px 0;
+ font-size: 16px;
+ color: #333;
+ line-height: 1.4;
+ }
+
+ h4 {
+ margin: 16px 0 8px 0;
+ font-size: 14px;
+ color: #555;
+ font-weight: 600;
+ }
+
+ p {
+ font-size: 13px;
+ color: #444;
+ line-height: 1.6;
+ margin: 0;
+ }
+}
+
+.back-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+
+ width: auto;
+ margin-bottom: 1rem;
+ padding: 0.5rem 0.85rem;
+
+ border: 1px solid #d6e3f8;
+ border-radius: 999px;
+
+ background: #f8fbff;
+ color: #2563eb;
+
+ font-size: 0.9rem;
+ font-weight: 600;
+
+ cursor: pointer;
+ transition:
+ background-color 0.15s ease,
+ border-color 0.15s ease,
+ color 0.15s ease,
+ box-shadow 0.15s ease;
+
+ &:hover {
+ background: #eef5ff;
+ border-color: #bcd3f7;
+ color: #1d4ed8;
+ box-shadow: 0 1px 4px rgba(37, 99, 235, 0.12);
+ }
+
+ &:focus-visible {
+ outline: 2px solid #93c5fd;
+ outline-offset: 2px;
+ }
+}
+
+.detail-section {
+ margin-top: 12px;
+ padding-top: 12px;
+ border-top: 1px solid #eee;
+}
+
+.patent-meta {
+ &--inline {
+ margin: 12px 0 20px;
+ }
+
+ &__list {
+ margin: 0;
+ border: 1px solid #e2e8f4;
+ border-radius: 12px;
+ background: linear-gradient(180deg, #fff 0%, #f8faff 100%);
+ box-shadow: 0 1px 3px rgba(15, 23, 42, 0.04);
+ overflow: hidden;
+ }
+
+ &__row {
+ display: grid;
+ grid-template-columns: minmax(130px, 38%) 1fr;
+ gap: 12px 16px;
+ align-items: center;
+ padding: 11px 16px;
+ border-top: 1px solid #eef2f8;
+
+ &:first-child {
+ border-top: 0;
+ }
+
+ dt {
+ margin: 0;
+ font-size: 12px;
+ font-weight: 500;
+ color: #64748b;
+ line-height: 1.35;
+ }
+
+ dd {
+ margin: 0;
+ font-size: 14px;
+ font-weight: 600;
+ color: #1e293b;
+ line-height: 1.35;
+ word-break: break-word;
+ }
+ }
+}
+
+.tag-list {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+
+ &--compact .tag {
+ font-size: 0.75rem;
+ padding: 3px 8px;
+ }
+}
+
+.tag {
+ padding: 4px 10px;
+ border-radius: 999px;
+ background: #f0f6ff;
+ border: 1px solid #dbeafe;
+ color: #1e40af;
+ font-size: 0.8rem;
+ line-height: 1.3;
+}
+
+.classification-section {
+ &--ipc .classification-card {
+ background: #f0f6ff;
+ border-color: #bfdbfe;
+ }
+
+ &--ipc .classification-badge--system {
+ background: #dbeafe;
+ color: #1d4ed8;
+ }
+
+ &--cpc .classification-card {
+ background: #f0fdf4;
+ border-color: #bbf7d0;
+ }
+
+ &--cpc .classification-badge--system {
+ background: #dcfce7;
+ color: #15803d;
+ }
+}
+
+.classification-cards {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.classification-card {
+ padding: 12px 14px;
+ border-radius: 10px;
+ border: 1px solid #dbeafe;
+}
+
+.classification-card__header {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+}
+
+.classification-card__codes {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.classification-card__badges {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.classification-code {
+ font-size: 0.9rem;
+ font-weight: 700;
+ color: #0f172a;
+}
+
+.classification-badge {
+ display: inline-flex;
+ align-items: center;
+ padding: 2px 8px;
+ border-radius: 999px;
+ font-size: 0.68rem;
+ font-weight: 700;
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
+}
+
+.classification-badge--level {
+ background: #e2e8f0;
+ color: #475569;
+}
+
+.classification-summary {
+ margin: 10px 0 0;
+ font-size: 0.84rem;
+ line-height: 1.5;
+ color: #334155;
+}
+
+.classification-toggle {
+ margin-top: 6px;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: #2563eb;
+ font-size: 0.78rem;
+ cursor: pointer;
+
+ &:hover {
+ text-decoration: underline;
+ }
+}
+
+.classification-hierarchy {
+ margin: 10px 0 0;
+ padding-top: 10px;
+ border-top: 1px solid rgba(15, 23, 42, 0.08);
+}
+
+.classification-hierarchy__row {
+ display: grid;
+ grid-template-columns: 88px 1fr;
+ gap: 8px;
+ margin-bottom: 6px;
+
+ dt {
+ margin: 0;
+ font-size: 0.72rem;
+ font-weight: 700;
+ color: #64748b;
+ text-transform: uppercase;
+ letter-spacing: 0.03em;
+ }
+
+ dd {
+ margin: 0;
+ font-size: 0.8rem;
+ line-height: 1.45;
+ color: #334155;
+ }
+}
+
+.pagination {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ margin-top: 12px;
+
+ button {
+ padding: 4px 10px;
+ border: 1px solid #d0d0d0;
+ border-radius: 6px;
+ background: white;
+ cursor: pointer;
+ font-size: 12px;
+
+ &:disabled {
+ opacity: 0.5;
+ cursor: default;
+ }
+ }
+
+ span {
+ font-size: 12px;
+ color: #666;
+ }
+}
diff --git a/webapp/src/app/modules/person-patents/person-patents.component.ts b/webapp/src/app/modules/person-patents/person-patents.component.ts
index f0c80153..6d195a3e 100644
--- a/webapp/src/app/modules/person-patents/person-patents.component.ts
+++ b/webapp/src/app/modules/person-patents/person-patents.component.ts
@@ -1,174 +1,412 @@
-import { Component, OnInit, inject } from '@angular/core';
-import { CommonModule } from '@angular/common';
-import { ActivatedRoute, Router } from '@angular/router';
-import { PatentsService } from '../../api/api/patents.service';
-import { PatentEntry } from '../../api';
-
-type SortMode = 'date' | 'title';
-type SourceFilter = 'all' | 'EPO' | 'USPTO';
-
-@Component({
- selector: 'app-person-patents',
- imports: [CommonModule],
- templateUrl: './person-patents.component.html',
- styleUrl: './person-patents.component.scss',
-})
-export class PersonPatentsComponent implements OnInit {
- private route = inject(ActivatedRoute);
- private router = inject(Router);
- private patentsApi = inject(PatentsService);
-
- patents: PatentEntry[] = [];
- filteredPatents: PatentEntry[] = [];
- authorName: string | null = null;
- selectedPatent: PatentEntry | null = null;
- showDetail = false;
-
- loading = true;
- error = false;
-
- activeFilter: SourceFilter = 'all';
- sortMode: SortMode = 'date';
-
- selectedPage = 1;
- readonly pageSize = 10;
-
- hasAsignees(selectedPatent: PatentEntry | null): boolean {
- return !!selectedPatent?.assignees && selectedPatent.assignees.length > 0;
- }
-
- hasIpcs(selectedPatent: PatentEntry | null): boolean {
- return !!selectedPatent?.ipc && selectedPatent.ipc.length > 0;
- }
-
- ngOnInit(): void {
- this.route.parent?.paramMap.subscribe((params) => {
- const authorId = params.get('id') ?? '';
-
- const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
- const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
-
- if (this.isValidFilter(filterFromUrl)) {
- this.activeFilter = filterFromUrl;
- }
- if (this.isValidSortMode(sortFromUrl)) {
- this.sortMode = sortFromUrl;
- }
-
- if (authorId) {
- this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({
- next: (result) => {
- this.patents = result.patents ?? [];
- this.authorName = result.author_name ?? null;
- this.applyFilter();
- this.loading = false;
- },
- error: () => {
- this.error = true;
- this.loading = false;
- },
- });
- }
- });
- }
-
- setFilter(filter: SourceFilter): void {
- this.activeFilter = filter;
- this.selectedPage = 1;
- this.selectedPatent = null;
- this.showDetail = false;
- this.applyFilter();
- this.updateQueryParams();
- }
-
- setSortMode(sortMode: SortMode): void {
- this.sortMode = sortMode;
- this.applyFilter();
- this.updateQueryParams();
- }
-
- selectPatent(patent: PatentEntry): void {
- this.selectedPatent = patent;
- this.showDetail = false;
- this.updateQueryParams();
- }
-
- openDetail(): void {
- this.showDetail = true;
- }
-
- private applyFilter(): void {
- let patents = this.patents;
-
- if (this.activeFilter !== 'all') {
- patents = patents.filter((p) => p.source === this.activeFilter);
- }
-
- this.filteredPatents = this.sortPatents(patents);
- }
-
- private sortPatents(patents: PatentEntry[]): PatentEntry[] {
- return [...patents].sort((a, b) => {
- if (this.sortMode === 'date') {
- return (b.publication_date ?? '').localeCompare(
- a.publication_date ?? '',
- );
- }
- return (a.title ?? '').localeCompare(b.title ?? '', 'de', {
- sensitivity: 'base',
- });
- });
- }
-
- private updateQueryParams(): void {
- this.router.navigate([], {
- relativeTo: this.route,
- queryParams: {
- filter: this.activeFilter,
- sortBy: this.sortMode,
- },
- queryParamsHandling: 'merge',
- replaceUrl: true,
- });
- }
-
- private isValidFilter(value: string | null): value is SourceFilter {
- return value === 'all' || value === 'EPO' || value === 'USPTO';
- }
-
- private isValidSortMode(value: string | null): value is SortMode {
- return value === 'date' || value === 'title';
- }
-
- getPagedPatents(): PatentEntry[] {
- const start = (this.selectedPage - 1) * this.pageSize;
- return this.filteredPatents.slice(start, start + this.pageSize);
- }
-
- getPageCount(): number {
- return Math.max(1, Math.ceil(this.filteredPatents.length / this.pageSize));
- }
-
- hasPagination(): boolean {
- return this.getPageCount() > 1;
- }
-
- setPage(page: number): void {
- this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount());
- this.updateQueryParams();
- }
-
- formatDate(date: string | null): string {
- if (!date) return '-';
- const d = date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
- return new Intl.DateTimeFormat('de-DE').format(new Date(d));
- }
-
- getEpoCount(): number {
- return this.patents.filter((p) => p.source === 'EPO').length;
- }
-
- getUsptoCount(): number {
- return this.patents.filter((p) => p.source === 'USPTO').length;
- }
-}
+import { Component, OnInit, inject } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { ActivatedRoute, Router } from '@angular/router';
+import { PatentsService } from '../../api/api/patents.service';
+import { PatentEntry, IpcClassification } from '../../api/model/patentEntry';
+
+type SortMode = 'date' | 'title';
+type SourceFilter = 'all' | 'EPO' | 'USPTO';
+type ClassificationSystem = 'IPC' | 'CPC';
+
+interface ClassificationCard {
+ key: string;
+ symbols: string[];
+ system: ClassificationSystem;
+ levelLabel: string;
+ primaryDescription: string | null;
+ hierarchy: { label: string; value: string }[];
+}
+
+interface PatentMetadataRow {
+ label: string;
+ value: string;
+ variant?: 'source';
+}
+
+const DESCRIPTION_PREVIEW_LENGTH = 140;
+
+@Component({
+ selector: 'app-person-patents',
+ imports: [CommonModule],
+ templateUrl: './person-patents.component.html',
+ styleUrl: './person-patents.component.scss',
+})
+export class PersonPatentsComponent implements OnInit {
+ private route = inject(ActivatedRoute);
+ private router = inject(Router);
+ private patentsApi = inject(PatentsService);
+
+ patents: PatentEntry[] = [];
+ filteredPatents: PatentEntry[] = [];
+ authorName: string | null = null;
+ selectedPatent: PatentEntry | null = null;
+ showDetail = false;
+
+ loading = true;
+ error = false;
+
+ activeFilter: SourceFilter = 'all';
+ sortMode: SortMode = 'date';
+
+ selectedPage = 1;
+ readonly pageSize = 10;
+ private expandedClassificationKeys = new Set();
+
+ ngOnInit(): void {
+ this.route.parent?.paramMap.subscribe((params) => {
+ const authorId = params.get('id') ?? '';
+
+ const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
+ const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
+
+ if (this.isValidFilter(filterFromUrl)) {
+ this.activeFilter = filterFromUrl;
+ }
+ if (this.isValidSortMode(sortFromUrl)) {
+ this.sortMode = sortFromUrl;
+ }
+
+ if (authorId) {
+ this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({
+ next: (result) => {
+ this.patents = result.patents ?? [];
+ this.authorName = result.author_name ?? null;
+ this.applyFilter();
+ this.loading = false;
+ },
+ error: () => {
+ this.error = true;
+ this.loading = false;
+ },
+ });
+ }
+ });
+ }
+
+ setFilter(filter: SourceFilter): void {
+ this.activeFilter = filter;
+ this.selectedPage = 1;
+ this.selectedPatent = null;
+ this.showDetail = false;
+ this.applyFilter();
+ this.updateQueryParams();
+ }
+
+ setSortMode(sortMode: SortMode): void {
+ this.sortMode = sortMode;
+ this.applyFilter();
+ this.updateQueryParams();
+ }
+
+ selectPatent(patent: PatentEntry): void {
+ this.selectedPatent = patent;
+ this.showDetail = false;
+ this.expandedClassificationKeys.clear();
+ this.updateQueryParams();
+ }
+
+ openDetail(): void {
+ this.showDetail = true;
+ this.expandedClassificationKeys.clear();
+ }
+
+ closeDetail(): void {
+ this.showDetail = false;
+ this.expandedClassificationKeys.clear();
+ }
+
+ private applyFilter(): void {
+ let patents = this.patents;
+
+ if (this.activeFilter !== 'all') {
+ patents = patents.filter((p) => p.source === this.activeFilter);
+ }
+
+ this.filteredPatents = this.sortPatents(patents);
+ }
+
+ private sortPatents(patents: PatentEntry[]): PatentEntry[] {
+ return [...patents].sort((a, b) => {
+ if (this.sortMode === 'date') {
+ return (b.publication_date ?? '').localeCompare(a.publication_date ?? '');
+ }
+ return (a.title ?? '').localeCompare(b.title ?? '', 'de', { sensitivity: 'base' });
+ });
+ }
+
+ private updateQueryParams(): void {
+ this.router.navigate([], {
+ relativeTo: this.route,
+ queryParams: {
+ filter: this.activeFilter,
+ sortBy: this.sortMode,
+ },
+ queryParamsHandling: 'merge',
+ replaceUrl: true,
+ });
+ }
+
+ private isValidFilter(value: string | null): value is SourceFilter {
+ return value === 'all' || value === 'EPO' || value === 'USPTO';
+ }
+
+ private isValidSortMode(value: string | null): value is SortMode {
+ return value === 'date' || value === 'title';
+ }
+
+ getPagedPatents(): PatentEntry[] {
+ const start = (this.selectedPage - 1) * this.pageSize;
+ return this.filteredPatents.slice(start, start + this.pageSize);
+ }
+
+ getPageCount(): number {
+ return Math.max(1, Math.ceil(this.filteredPatents.length / this.pageSize));
+ }
+
+ hasPagination(): boolean {
+ return this.getPageCount() > 1;
+ }
+
+ setPage(page: number): void {
+ this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount());
+ this.updateQueryParams();
+ }
+
+ formatDate(date: string | null | undefined): string {
+ if (!date) return '-';
+ const d = date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
+ return new Intl.DateTimeFormat('de-DE').format(new Date(d));
+ }
+
+ getEpoCount(): number {
+ return this.patents.filter((p) => p.source === 'EPO').length;
+ }
+
+ getUsptoCount(): number {
+ return this.patents.filter((p) => p.source === 'USPTO').length;
+ }
+
+ trackPatent(_index: number, patent: PatentEntry): string {
+ return [
+ patent.source,
+ patent.patent_id,
+ patent.publication_date ?? '',
+ patent.kind ?? patent.application_type ?? '',
+ ].join('|');
+ }
+
+ getAbstractPreview(abstract: string | null | undefined): string | null {
+ if (!abstract?.trim()) {
+ return null;
+ }
+ const text = abstract.trim();
+ if (text.length <= 160) {
+ return text;
+ }
+ return `${text.slice(0, 160).trimEnd()}…`;
+ }
+
+ getPublicationStageLabel(patent: PatentEntry): string | null {
+ if (patent.kind) {
+ return patent.kind;
+ }
+ if (patent.application_type) {
+ return patent.application_type;
+ }
+ return null;
+ }
+
+ hasPatentMetadata(_patent: PatentEntry): boolean {
+ return true;
+ }
+
+ getPatentMetadataRows(patent: PatentEntry): PatentMetadataRow[] {
+ const rows: PatentMetadataRow[] = [];
+
+ rows.push({ label: 'Quelle', value: patent.source, variant: 'source' });
+ rows.push({ label: 'Patent-Nr.', value: patent.patent_id });
+
+ if (patent.publication_date) {
+ rows.push({
+ label: 'Veröffentlichungsdatum',
+ value: this.formatDate(patent.publication_date),
+ });
+ }
+ if (patent.application_number) {
+ rows.push({ label: 'Anmeldungsnummer', value: patent.application_number });
+ }
+ if (patent.application_date) {
+ rows.push({ label: 'Anmeldedatum', value: this.formatDate(patent.application_date) });
+ }
+
+ const stageLabel = this.getPublicationStageLabel(patent);
+ if (stageLabel) {
+ rows.push({
+ label: patent.kind ? 'Publikationsstufe' : 'Anmeldungstyp',
+ value: patent.kind ? stageLabel : this.formatMetadataLabel(stageLabel),
+ });
+ }
+ if (patent.number_of_claims != null) {
+ rows.push({ label: 'Ansprüche', value: String(patent.number_of_claims) });
+ }
+ if (patent.status) {
+ rows.push({ label: 'Status', value: this.formatMetadataLabel(patent.status) });
+ }
+
+ return rows;
+ }
+
+ private formatMetadataLabel(value: string): string {
+ return value
+ .replace(/_/g, ' ')
+ .toLowerCase()
+ .replace(/\b\w/g, (char) => char.toUpperCase());
+ }
+
+ getClassificationCards(
+ entries: IpcClassification[] | undefined,
+ system: ClassificationSystem,
+ ): ClassificationCard[] {
+ if (!entries?.length) {
+ return [];
+ }
+
+ const merged = new Map();
+
+ for (const entry of entries) {
+ const card = this.buildClassificationCard(entry, system);
+ const mergeKey =
+ card.primaryDescription?.toLocaleLowerCase('en') ?? card.symbols[0] ?? card.key;
+
+ const existing = merged.get(mergeKey);
+ if (existing) {
+ for (const symbol of card.symbols) {
+ if (!existing.symbols.includes(symbol)) {
+ existing.symbols.push(symbol);
+ }
+ }
+ continue;
+ }
+
+ merged.set(mergeKey, card);
+ }
+
+ return [...merged.values()];
+ }
+
+ toggleClassificationExpanded(key: string): void {
+ if (this.expandedClassificationKeys.has(key)) {
+ this.expandedClassificationKeys.delete(key);
+ return;
+ }
+ this.expandedClassificationKeys.add(key);
+ }
+
+ isClassificationExpanded(key: string): boolean {
+ return this.expandedClassificationKeys.has(key);
+ }
+
+ isLongDescription(text: string | null): boolean {
+ return !!text && text.length > DESCRIPTION_PREVIEW_LENGTH;
+ }
+
+ getDescriptionPreview(text: string | null): string {
+ if (!text) {
+ return '';
+ }
+ if (text.length <= DESCRIPTION_PREVIEW_LENGTH) {
+ return text;
+ }
+ return `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`;
+ }
+
+ private buildClassificationCard(
+ entry: IpcClassification,
+ system: ClassificationSystem,
+ ): ClassificationCard {
+ const level = this.getClassificationLevel(entry);
+ const primaryDescription = this.extractDescriptionText(entry[level.field]);
+
+ return {
+ key: `${system}-${entry.symbol}`,
+ symbols: [entry.symbol],
+ system,
+ levelLabel: level.label,
+ primaryDescription,
+ hierarchy: this.buildHierarchyRows(entry, primaryDescription),
+ };
+ }
+
+ private getClassificationLevel(entry: IpcClassification): {
+ label: string;
+ field: keyof IpcClassification;
+ } {
+ if (entry.subgroup) {
+ return { label: 'Untergruppe', field: 'subgroup' };
+ }
+ if (entry.main_group) {
+ return { label: 'Hauptgruppe', field: 'main_group' };
+ }
+ if (entry.subclass) {
+ return { label: 'Unterklasse', field: 'subclass' };
+ }
+ if (entry.section) {
+ return { label: 'Sektion', field: 'section' };
+ }
+ return { label: 'Code', field: 'symbol' };
+ }
+
+ private buildHierarchyRows(
+ entry: IpcClassification,
+ primaryDescription: string | null,
+ ): { label: string; value: string }[] {
+ const rows: { label: string; value: string }[] = [];
+ const seen = new Set();
+
+ const addRow = (label: string, raw: string | null) => {
+ const value = this.extractDescriptionText(raw);
+ if (!value) {
+ return;
+ }
+ const normalized = value.toLocaleLowerCase('en');
+ if (seen.has(normalized) || normalized === primaryDescription?.toLocaleLowerCase('en')) {
+ return;
+ }
+ seen.add(normalized);
+ rows.push({ label, value });
+ };
+ if (entry.section){
+ addRow('Sektion', entry.section);
+ }
+ if (entry.class){
+ addRow('Klasse', entry.class);
+ }
+ if (entry.subclass){
+ addRow('Unterklasse', entry.subclass);
+ }
+
+
+ return rows;
+ }
+
+ private extractDescriptionText(value: string | null | undefined): string | null {
+ if (!value?.trim()) {
+ return null;
+ }
+
+ const text = value.includes(' - ') ? value.split(' - ').slice(1).join(' - ').trim() : value.trim();
+ if (!text) {
+ return null;
+ }
+
+ const firstSentence = text.split(/[;|]/)[0]?.trim() ?? text;
+ return this.normalizeDescriptionCase(firstSentence);
+ }
+
+ private normalizeDescriptionCase(text: string): string {
+ if (text !== text.toUpperCase()) {
+ return text;
+ }
+ return text.charAt(0) + text.slice(1).toLowerCase();
+ }
+}
diff --git a/webapp/src/app/modules/person-projects/bund-details/bund-details.component.html b/webapp/src/app/modules/projects/bund-details/bund-details.component.html
similarity index 92%
rename from webapp/src/app/modules/person-projects/bund-details/bund-details.component.html
rename to webapp/src/app/modules/projects/bund-details/bund-details.component.html
index 9b0df147..fcceb4bd 100644
--- a/webapp/src/app/modules/person-projects/bund-details/bund-details.component.html
+++ b/webapp/src/app/modules/projects/bund-details/bund-details.component.html
@@ -26,6 +26,14 @@
}
+
+ circle
+ {{ getStatusDisplay(bundProject.funding_end_date) }}
+
@if (getAssociatedPersons().length > 0) {
@@ -351,11 +367,11 @@
}
@if (getDuration()) {
diff --git a/webapp/src/app/modules/person-projects/bund-details/bund-details.component.scss b/webapp/src/app/modules/projects/bund-details/bund-details.component.scss
similarity index 95%
rename from webapp/src/app/modules/person-projects/bund-details/bund-details.component.scss
rename to webapp/src/app/modules/projects/bund-details/bund-details.component.scss
index 839a4ea7..d70ac5ff 100644
--- a/webapp/src/app/modules/person-projects/bund-details/bund-details.component.scss
+++ b/webapp/src/app/modules/projects/bund-details/bund-details.component.scss
@@ -13,7 +13,29 @@
gap: 18px;
margin-bottom: 24px;
}
+.status-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 14px;
+ border-radius: var(--sg-radius-sm);
+ color: #fff;
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: all 0.2s;
+}
+.status-badge:hover {
+ transform: translateY(-1px);
+ box-shadow: 0 2px 8px rgba(0,0,0,0.15);
+}
+
+.status-badge mat-icon {
+ width: 16px;
+ height: 16px;
+ font-size: 16px;
+}
.back-link {
display: inline-flex;
align-items: center;
diff --git a/webapp/src/app/modules/person-projects/bund-details/bund-details.component.ts b/webapp/src/app/modules/projects/bund-details/bund-details.component.ts
similarity index 80%
rename from webapp/src/app/modules/person-projects/bund-details/bund-details.component.ts
rename to webapp/src/app/modules/projects/bund-details/bund-details.component.ts
index 5ad9007b..2415da37 100644
--- a/webapp/src/app/modules/person-projects/bund-details/bund-details.component.ts
+++ b/webapp/src/app/modules/projects/bund-details/bund-details.component.ts
@@ -5,7 +5,7 @@ import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { BundProjectDetails } from '../../../api/model/bundProjectDetails';
import { Router } from '@angular/router';
-
+import { formatGermanDate } from '../../../shared/utils/formatters';
@Component({
selector: 'app-bund-details',
standalone: true,
@@ -41,8 +41,8 @@ export class BundDetailsComponent implements OnInit {
const year = parseInt(fundingEndDate, 10);
if (isNaN(year)) return fundingEndDate;
return year >= new Date().getFullYear()
- ? `${fundingEndDate} (laufend)`
- : `${fundingEndDate} (abgeschlossen)`;
+ ? `${fundingEndDate}`
+ : `${fundingEndDate}`;
}
formatCurrency(amount: number | null | undefined): string {
@@ -104,15 +104,6 @@ export class BundDetailsComponent implements OnInit {
// }
// });
// }
- private formatGermanDate(dateString: string): string {
- if (!dateString) return '';
-
- return new Intl.DateTimeFormat('de-DE', {
- day: 'numeric',
- month: 'long',
- year: 'numeric',
- }).format(new Date(dateString));
- }
/**
* All associated persons as a simple list.
*/
@@ -120,11 +111,11 @@ export class BundDetailsComponent implements OnInit {
return this.bundProject?.associated_persons || [];
}
getStartDate(): string {
- return this.formatGermanDate(this.bundProject?.funding_start_date ?? '');
+ return formatGermanDate(this.bundProject?.funding_start_date ?? '');
}
getEndDate(): string {
- return this.formatGermanDate(this.bundProject?.funding_end_date ?? '');
+ return formatGermanDate(this.bundProject?.funding_end_date ?? '');
}
getDuration(): string {
@@ -133,7 +124,7 @@ export class BundDetailsComponent implements OnInit {
if (!start || !end) return '';
- return `von ${this.formatGermanDate(start)} bis ${this.formatGermanDate(end)}`;
+ return `von ${formatGermanDate(start)} bis ${formatGermanDate(end)}`;
}
/**
* All institutions as a simple list.
@@ -156,7 +147,23 @@ export class BundDetailsComponent implements OnInit {
if (!this.bundProject?.funding_amount) return 'N/A';
return this.formatCurrency(this.bundProject.funding_amount);
}
-
+ getStatusDisplay(fundingEndDate: string | null | undefined): string {
+ if (!fundingEndDate) return 'N/A';
+ if (fundingEndDate === '2999') return 'Laufend';
+ const year = parseInt(fundingEndDate, 10);
+ return year >= new Date().getFullYear() ? `Laufend` : `Abgeschlossen`;
+ }
+ getStatusColor(status: string | null | undefined): string {
+ if (!status) return '#95a5a6';
+ const statusUpper = status.toUpperCase();
+ if (statusUpper.includes('ABGESCHLOSSEN')) {
+ return '#27ae60';
+ } else if (statusUpper.includes('LAUFEND')) {
+ return '#f39c12';
+ } else {
+ return '#95a5a6';
+ }
+ }
goBack(): void {
window.history.back();
}
diff --git a/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.html b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.html
similarity index 88%
rename from webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.html
rename to webapp/src/app/modules/projects/dfg-details/dfg-details.component.html
index 81947db7..e335b614 100644
--- a/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.html
+++ b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.html
@@ -21,6 +21,12 @@
}
event_busy
{{ getFundingStatus(dfgProject.funding_end_date) }}
- Fördersende
+ Förderende
+
+
+
+
access_time
+
+ {{ getStatusDisplay(dfgProject.funding_end_date) }}
+ Status
-->
-
Fördersbeginn
- {{ dfgProject.funding_start_date || 'N/A' }}
-
-
-
Fördersende
- {{ getFundingStatus(dfgProject.funding_end_date) }}
+ Laufzeit
+ {{ getDuration() }}
@if (dfgProject.subproject_of) {
diff --git a/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.scss b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.scss
similarity index 94%
rename from webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.scss
rename to webapp/src/app/modules/projects/dfg-details/dfg-details.component.scss
index 08fbf9e7..b49f8eda 100644
--- a/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.scss
+++ b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.scss
@@ -236,7 +236,29 @@ h1 {
font-size: 12px;
font-weight: 500;
}
+.status-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 14px;
+ border-radius: var(--sg-radius-sm);
+ color: #fff;
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: all 0.2s;
+}
+.status-badge:hover {
+ transform: translateY(-1px);
+ box-shadow: 0 2px 8px rgba(0,0,0,0.15);
+}
+
+.status-badge mat-icon {
+ width: 16px;
+ height: 16px;
+ font-size: 16px;
+}
.description-text {
padding: 16px 20px 20px;
margin: 0;
diff --git a/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.ts b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts
similarity index 68%
rename from webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.ts
rename to webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts
index ab8ca4ea..f102f76d 100644
--- a/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.ts
+++ b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts
@@ -36,13 +36,33 @@ export class DfgDetailsComponent implements OnInit {
getFundingStatus(fundingEndDate: string | null | undefined): string {
if (!fundingEndDate) return 'N/A';
- if (fundingEndDate === '2999') return 'laufend';
+ if (fundingEndDate === '2999') return 'Laufend';
const year = parseInt(fundingEndDate, 10);
if (isNaN(year)) return fundingEndDate;
return year >= new Date().getFullYear()
- ? `${fundingEndDate} (laufend)`
- : `${fundingEndDate} (abgeschlossen)`;
+ ? `${fundingEndDate}`
+ : `${fundingEndDate}`;
}
+
+ getStatusDisplay(fundingEndDate: string | null | undefined): string {
+ if (!fundingEndDate) return 'N/A';
+ if (fundingEndDate === '2999') return 'Laufend';
+ const year = parseInt(fundingEndDate, 10);
+ return year >= new Date().getFullYear() ? `Laufend` : `Abgeschlossen`;
+ }
+
+ getStatusColor(status: string | null | undefined): string {
+ if (!status) return '#95a5a6';
+ const statusUpper = status.toUpperCase();
+ if (statusUpper.includes('ABGESCHLOSSEN')) {
+ return '#27ae60';
+ } else if (statusUpper.includes('LAUFEND')) {
+ return '#f39c12';
+ } else {
+ return '#95a5a6';
+ }
+ }
+
searchForPersonName(personName: string): void {
this.router.navigate(['/persons'], {
queryParams: {
@@ -70,7 +90,14 @@ export class DfgDetailsComponent implements OnInit {
getInstitutions(): string[] {
return this.dfgProject?.institutions || [];
}
+ getDuration(): string {
+ const start = this.dfgProject?.funding_start_date;
+ const end = this.dfgProject?.funding_end_date === "2999" ? "Heute" : this.dfgProject?.funding_end_date ;
+ if (!start || !end) return '';
+
+ return `von ${start} bis ${end}`;
+ }
goBack(): void {
window.history.back();
}
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.html b/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.html
new file mode 100644
index 00000000..5a399ecb
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.html
@@ -0,0 +1,33 @@
+
+
+
+
+ @for (deliv of deliverables; track deliv.url) {
+
+
+ file_present
+
+
+
+ {{ deliv.description || 'Ohne Beschreibung' }}
+
+
+
+
+ }
+
+
+
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.scss
new file mode 100644
index 00000000..a729cc21
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.scss
@@ -0,0 +1,109 @@
+// Deliverables
+.deliverables-list {
+ padding: 16px 20px 20px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.deliverable-item {
+ display: flex;
+ align-items: flex-start;
+ gap: 16px;
+ padding: 14px 16px;
+ border: 1px solid #d9e2f0;
+ border-radius: var(--sg-radius-sm);
+ background: #fff;
+ transition: all 0.2s;
+
+ &:hover {
+ background: #f8fafc;
+ }
+}
+
+.deliv-icon {
+ flex-shrink: 0;
+ color: #7b1fa2;
+
+ mat-icon {
+ width: 24px;
+ height: 24px;
+ font-size: 24px;
+ }
+}
+
+.deliv-info {
+ flex: 1;
+ min-width: 0;
+}
+
+.deliv-description {
+ font-weight: 500;
+ color: var(--sg-text);
+ font-size: 14px;
+}
+
+.deliv-meta {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-top: 4px;
+ font-size: 12px;
+ align-items: center;
+
+ .deliv-type {
+ padding: 1px 8px;
+ background: #f3e5f5;
+ border-radius: var(--sg-radius-sm);
+ color: #7b1fa2;
+ }
+
+ .deliv-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ color: var(--sg-primary, #0066cc);
+ text-decoration: none;
+
+ &:hover {
+ text-decoration: underline;
+ }
+
+ mat-icon {
+ width: 16px;
+ height: 16px;
+ font-size: 16px;
+ }
+ }
+}
+.deliverable-item {
+ flex-wrap: wrap;
+}
+
+.card {
+ margin-bottom: 24px;
+ border-color: #d9e2f0 !important;
+ border-radius: var(--sg-radius-md) !important;
+}
+
+.section-header {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 16px 20px;
+ border-bottom: 1px solid #e6e9ed;
+}
+
+.section-header mat-icon {
+ color: var(--sg-text-muted);
+ width: 22px;
+ height: 22px;
+ font-size: 22px;
+}
+
+.section-header h2 {
+ margin: 0;
+ font-size: 18px;
+ font-weight: 600;
+ color: var(--sg-text);
+}
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.ts
new file mode 100644
index 00000000..99fbd049
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.ts
@@ -0,0 +1,17 @@
+import { Component, inject } from '@angular/core';
+import { HEUDeliverable } from '../../../../api';
+import { Router } from '@angular/router';
+import { Input } from '@angular/core';
+import { MatIcon } from '@angular/material/icon';
+import { MatCard } from '@angular/material/card';
+@Component({
+ selector: 'app-deliverables-cards',
+ imports: [MatIcon, MatCard],
+ templateUrl: './deliverables-cards.component.html',
+ styleUrl: './deliverables-cards.component.scss',
+})
+export class DeliverablesCardsComponent {
+ @Input() deliverables: HEUDeliverable[] = [];
+ @Input() showHeader: boolean = true;
+ @Input() headerTitle: string = 'Deliverables';
+}
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html
new file mode 100644
index 00000000..1aa56279
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html
@@ -0,0 +1,502 @@
+
+
+
+ @if (euProject) {
+
+
+
+ EU Projekt
+ @if (programType) {
+
+ {{
+ programType === 'fp7'
+ ? 'FP7'
+ : programType === 'h2020'
+ ? 'H2020'
+ : programType === 'heu'
+ ? 'Horizon Europe'
+ : ''
+ }}
+
+ }
+ ID: {{ euProject.id }}
+
+
{{ euProject.title || 'Ohne Titel' }}
+ @if (euProject.frameworkProgramme) {
+
+ {{
+ getFrameworkDisplay(euProject.frameworkProgramme)
+ }}
+
+ }
+
+ @if (euProject.status) {
+
+ circle
+ {{ getStatusDisplay(euProject.status) }}
+
+ }
+ @if (euProject.fundingScheme) {
+
+ assignment
+ {{
+ getFundingSchemeDisplay(euProject.fundingScheme)
+ }}
+
+ }
+ @if (euProject.grantDoi) {
+
+ link
+ DOI: {{ euProject.grantDoi }}
+
+ }
+
+
+
+
+
+
calendar_today
+
+ {{ formatDate(euProject.startDate) || 'N/A' }}
+ Förderbeginn
+
+
+
+
event_busy
+
+ {{ formatDate(euProject.endDate) || 'N/A' }}
+ Förderende
+
+
+
+
access_time
+
+ {{ getFundingStatus(euProject.endDate) }}
+ Status
+
+
+ @if (euProject.ecMaxContribution) {
+
+
euro_symbol
+
+ {{ formatCurr(euProject.ecMaxContribution) }}
+ EU-Beitrag
+
+
+ }
+ @if (euProject.totalCost) {
+
+
attach_money
+
+ {{ formatCurr(euProject.totalCost) }}
+ Gesamtkosten
+
+
+ }
+ @if (euProject.organizationCount !== undefined) {
+
+
business
+
+ {{ euProject.organizationCount }}
+ Organisationen
+
+
+ }
+ @if (euProject.publicationCount !== undefined) {
+
+
description
+
+ {{ euProject.publicationCount }}
+ Publikationen
+
+
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ @if (activeTab === 'overview') {
+
+
+
+ @if (euProject.objective) {
+
+
+ {{ euProject.objective }}
+
+ }
+
+ @if (getFormattedTopics(euProject.topics).length > 0) {
+
+
+
+ @for (
+ topic of getFormattedTopics(euProject.topics);
+ track topic
+ ) {
+
+ {{ topic }}
+
+ }
+
+
+ }
+
+ @if (getKeywordChips().length > 0) {
+
+
+
+
+ }
+
+
+ @if (euProject.eurosciVoc && euProject.eurosciVoc.length > 0) {
+
+
+
+ @for (voc of euProject.eurosciVoc; track voc.id) {
+
+
+ @if (voc.path) {
+ @for (
+ segment of getPathSegments(voc.path);
+ track segment
+ ) {
+ {{ segment }}
+ @if (!$last) {
+ chevron_right
+ }
+ }
+ } @else {
+ {{
+ voc.code || 'N/A'
+ }}
+ }
+
+ @if (voc.code) {
+
{{ voc.code }}
+ }
+ @if (voc.description) {
+
{{
+ voc.description
+ }}
+ }
+ @if (voc.path) {
+
search
+ }
+
+ }
+
+
+ }
+
+
+
+
+
+ }
+
+
+ @if (activeTab === 'organizations' && euProject.organizations) {
+
+ }
+ @if (activeTab === 'publications' && euProject.publications) {
+
+ }
+
+
+ @if (activeTab === 'iprs' && euProject.iprs) {
+
+ }
+
+
+ @if (activeTab === 'deliverables' && euProject.deliverables) {
+
+ }
+
+ } @else {
+
+
+
error_outline
+
EU Projekt nicht gefunden.
+
+
+ }
+
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss
new file mode 100644
index 00000000..6559f75a
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss
@@ -0,0 +1,643 @@
+.detail-page {
+ padding: 28px 32px 42px;
+ max-width: 100%;
+ margin: 0 auto;
+}
+.page-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 18px;
+ margin-bottom: 24px;
+}
+.breadcrumb {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--sg-text-muted);
+ font-size: 13px;
+}
+.breadcrumb mat-icon {
+ width: 18px;
+ height: 18px;
+ font-size: 18px;
+}
+.breadcrumb span:last-child {
+ color: var(--sg-text);
+ font-weight: 500;
+}
+.project-hero {
+ background: #f8fafc;
+ border: 1px solid #d9e2f0;
+ border-radius: var(--sg-radius-md);
+ padding: 28px 32px;
+ margin-bottom: 28px;
+}
+.hero-content {
+ margin-bottom: 24px;
+}
+.eyebrow {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ margin-bottom: 12px;
+ flex-wrap: wrap;
+}
+.project-badge {
+ display: inline-block;
+ padding: 4px 12px;
+ background: #e8edf5;
+ color: var(--sg-text);
+ border-radius: var(--sg-radius-sm);
+ font-size: 12px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+}
+.project-id {
+ color: var(--sg-text-muted);
+ font-size: 13px;
+}
+h1 {
+ margin: 0 0 8px;
+ font-size: 26px;
+ line-height: 1.3;
+ font-weight: 700;
+ color: var(--sg-text);
+}
+.project-framework {
+ margin: 0 0 16px;
+ color: var(--sg-text-muted);
+ font-size: 14px;
+}
+.hero-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 10px;
+}
+.status-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 14px;
+ border-radius: var(--sg-radius-sm);
+ color: #fff;
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: all 0.2s;
+}
+.status-badge:hover {
+ transform: translateY(-1px);
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
+}
+.status-badge mat-icon {
+ width: 16px;
+ height: 16px;
+ font-size: 16px;
+}
+.scheme-info {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 14px;
+ background: #fff;
+ border: 1px solid #d9e2f0;
+ border-radius: var(--sg-radius-sm);
+ color: var(--sg-text);
+ font-size: 13px;
+ cursor: pointer;
+ transition: all 0.2s;
+}
+.scheme-info:hover {
+ background: #f5f7fa;
+ border-color: #b8c5d6;
+}
+.scheme-info mat-icon {
+ color: var(--sg-text-muted);
+ width: 18px;
+ height: 18px;
+ font-size: 18px;
+}
+.doi-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 14px;
+ background: #e8f0fe;
+ border: 1px solid #c5d8f0;
+ border-radius: var(--sg-radius-sm);
+ color: #1a73e8;
+ text-decoration: none;
+ font-size: 13px;
+ transition: all 0.2s;
+}
+.doi-link:hover {
+ background: #d5e3fa;
+}
+.doi-link mat-icon {
+ width: 18px;
+ height: 18px;
+ font-size: 18px;
+}
+.metrics-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+ gap: 16px;
+ padding-top: 20px;
+ border-top: 1px solid #d9e2f0;
+}
+.metric-item {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+.metric-item mat-icon {
+ color: var(--sg-text-muted);
+ width: 24px;
+ height: 24px;
+ font-size: 24px;
+}
+.metric-content {
+ display: flex;
+ flex-direction: column;
+}
+.metric-content strong {
+ font-size: 15px;
+ color: var(--sg-text);
+ line-height: 1.3;
+}
+.metric-content span {
+ font-size: 12px;
+ color: var(--sg-text-muted);
+}
+.card {
+ margin-bottom: 24px;
+ border-color: #d9e2f0 !important;
+ border-radius: var(--sg-radius-md) !important;
+}
+.section-header {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 16px 20px;
+ border-bottom: 1px solid #e6e9ed;
+}
+.section-header mat-icon {
+ color: var(--sg-text-muted);
+ width: 22px;
+ height: 22px;
+ font-size: 22px;
+}
+.section-header h2 {
+ margin: 0;
+ font-size: 18px;
+ font-weight: 600;
+ color: var(--sg-text);
+}
+.count-badge {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 24px;
+ height: 24px;
+ padding: 0 8px;
+ margin-left: auto;
+ background: #e8edf5;
+ border-radius: 12px;
+ color: var(--sg-text-muted);
+ font-size: 12px;
+ font-weight: 500;
+}
+.description-text {
+ padding: 16px 20px 20px;
+ margin: 0;
+ color: var(--sg-text);
+ font-size: 14px;
+ line-height: 1.6;
+}
+.content-grid {
+ display: grid;
+ grid-template-columns: 2fr 1fr;
+ gap: 24px;
+}
+.main-content,
+.sidebar {
+ display: flex;
+ flex-direction: column;
+ gap: 24px;
+}
+.topics-grid {
+ display: grid;
+ grid-template-columns: 1fr;
+ gap: 10px;
+ padding: 16px 20px 20px;
+}
+.topic-item {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 14px;
+ border: 1px solid #d9e2f0;
+ border-radius: var(--sg-radius-sm);
+ background: #fff;
+ cursor: pointer;
+ transition: all 0.2s;
+}
+.topic-item:hover {
+ background: #f8fafc;
+ border-color: #b8c5d6;
+ transform: translateY(-1px);
+}
+.topic-value {
+ color: var(--sg-text);
+ font-size: 13px;
+ word-break: break-word;
+}
+.topic-item .search-icon {
+ color: var(--sg-text-muted);
+ width: 18px;
+ height: 18px;
+ font-size: 18px;
+ opacity: 0;
+ transition: opacity 0.2s;
+}
+.topic-item:hover .search-icon {
+ opacity: 1;
+}
+.interest-tags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 12px;
+ padding: 16px 20px 12px;
+}
+.details-list {
+ margin: 0;
+ padding: 16px 20px 20px;
+}
+.detail-row {
+ display: grid;
+ grid-template-columns: 140px 1fr;
+ gap: 12px;
+ padding: 8px 0;
+ border-bottom: 1px solid #f0f2f5;
+}
+.detail-row:last-child {
+ border-bottom: 0;
+}
+.detail-row dt {
+ color: var(--sg-text-muted);
+ font-size: 13px;
+ font-weight: 500;
+}
+.detail-row dd {
+ margin: 0;
+ color: var(--sg-text);
+ font-size: 13px;
+ word-break: break-word;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+.detail-row dd.clickable {
+ cursor: pointer;
+ transition: color 0.2s;
+}
+.detail-row dd.clickable:hover {
+ color: var(--sg-primary, #0066cc);
+}
+.detail-row dd.clickable:hover .search-icon,
+.detail-row dd:hover .search-icon {
+ opacity: 1;
+}
+.search-icon {
+ width: 16px;
+ height: 16px;
+ font-size: 16px;
+ opacity: 0;
+ transition: opacity 0.2s;
+ color: var(--sg-text-muted);
+}
+.status-indicator {
+ display: inline-block;
+ padding: 2px 10px;
+ border-radius: var(--sg-radius-sm);
+ color: #fff;
+ font-size: 12px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: all 0.2s;
+}
+.status-indicator:hover {
+ transform: scale(1.05);
+}
+.external-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ color: var(--sg-primary, #0066cc);
+ text-decoration: none;
+ word-break: break-all;
+}
+.external-link:hover {
+ text-decoration: underline;
+}
+.error-container {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 400px;
+}
+.error-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 12px;
+ color: var(--sg-text-muted);
+}
+.error-state mat-icon {
+ width: 48px;
+ height: 48px;
+ font-size: 48px;
+ color: #e74c3c;
+}
+.error-state p {
+ margin: 0;
+ font-size: 16px;
+}
+@media (max-width: 1116px) {
+ .content-grid {
+ grid-template-columns: 1fr;
+ gap: 20px;
+ }
+}
+@media (max-width: 768px) {
+ .detail-page {
+ padding: 16px;
+ }
+ .page-header {
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 12px;
+ }
+ .project-hero {
+ padding: 20px;
+ }
+ .metrics-grid {
+ grid-template-columns: 1fr 1fr;
+ gap: 12px;
+ }
+ h1 {
+ font-size: 22px;
+ }
+ .detail-row {
+ grid-template-columns: 1fr;
+ gap: 4px;
+ }
+ .eyebrow {
+ gap: 8px;
+ }
+ .topics-grid,
+ .interest-tags {
+ grid-template-columns: 1fr;
+ }
+}
+@media (max-width: 480px) {
+ .metrics-grid {
+ grid-template-columns: 1fr;
+ }
+ .hero-actions {
+ flex-direction: column;
+ }
+ .status-badge,
+ .scheme-info,
+ .doi-link {
+ width: 100%;
+ justify-content: center;
+ }
+}
+
+.program-badge {
+ display: inline-block;
+ padding: 4px 12px;
+ border-radius: var(--sg-radius-sm);
+ font-size: 11px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+}
+.program-badge.fp7 {
+ background: #e8eaf6;
+ color: #283593;
+}
+.program-badge.h2020 {
+ background: #e3f2fd;
+ color: #0d47a1;
+}
+.program-badge.heu {
+ background: #e8f5e9;
+ color: #1b5e20;
+}
+
+.tabs-container {
+ display: flex;
+ gap: 4px;
+ padding: 0 4px;
+ margin-bottom: 24px;
+ background: #f8fafc;
+ border-radius: var(--sg-radius-md);
+ border: 1px solid #d9e2f0;
+ overflow-x: auto;
+}
+.tab-btn {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 12px 20px;
+ background: 0 0;
+ border: 0;
+ border-radius: var(--sg-radius-sm);
+ color: var(--sg-text-muted);
+ font-size: 14px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: all 0.2s;
+ white-space: nowrap;
+}
+.tab-btn:hover {
+ background: rgba(0, 0, 0, 0.04);
+ color: var(--sg-text);
+}
+.tab-btn.active {
+ background: #fff;
+ color: var(--sg-primary, #0066cc);
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
+}
+.tab-btn mat-icon {
+ width: 20px;
+ height: 20px;
+ font-size: 20px;
+}
+.tab-badge {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 20px;
+ height: 20px;
+ padding: 0 6px;
+ background: #e8edf5;
+ border-radius: 10px;
+ color: var(--sg-text-muted);
+ font-size: 11px;
+ font-weight: 600;
+}
+.tab-content {
+ animation: fadeIn 0.3s ease;
+}
+@keyframes fadeIn {
+ from {
+ opacity: 0;
+ transform: translateY(8px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+.eurosci-voc-grid {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ padding: 16px 20px 20px;
+}
+.eurosci-voc-item {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 12px 16px;
+ background: #f8fafc;
+ border: 1px solid #e6e9ed;
+ border-radius: 8px;
+ flex-wrap: wrap;
+}
+.eurosci-voc-item.clickable:hover {
+ background: #f0f3f7;
+ border-color: #b8c5d6;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
+}
+.eurosci-voc-item .voc-path {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 4px;
+ flex: 1;
+ min-width: 200px;
+}
+.eurosci-voc-item .path-segment {
+ font-size: 13px;
+ font-weight: 500;
+ color: #1a1a1a;
+ padding: 2px 8px;
+ border-radius: 4px;
+ background: #fff;
+ border: 1px solid #e6e9ed;
+}
+.eurosci-voc-item .path-segment:last-child {
+ background: #e8f0fe;
+ border-color: #c5d8f0;
+ color: #005a9c;
+ font-weight: 600;
+}
+.eurosci-voc-item .path-separator {
+ width: 16px;
+ height: 16px;
+ font-size: 16px;
+ color: #6b7a8a;
+}
+.eurosci-voc-item .voc-code {
+ font-size: 12px;
+ color: #6b7a8a;
+ font-family: monospace;
+ background: #eef2f7;
+ padding: 2px 8px;
+ border-radius: 4px;
+ white-space: nowrap;
+}
+.eurosci-voc-item .voc-description {
+ font-size: 13px;
+ color: #6b7a8a;
+ font-style: italic;
+}
+
+.erc-pi-list {
+ padding: 16px 20px 20px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+.erc-pi-item {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 10px 14px;
+ background: #f8fafc;
+ border-radius: var(--sg-radius-sm);
+ border: 1px solid #d9e2f0;
+}
+.erc-pi-item .pi-name {
+ font-weight: 500;
+ color: var(--sg-text);
+ font-size: 14px;
+}
+.erc-pi-item .pi-title {
+ color: var(--sg-text-muted);
+ font-size: 13px;
+}
+
+@media (max-width: 992px) {
+ .eurosci-voc-grid {
+ grid-template-columns: 1fr;
+ }
+}
+@media (max-width: 768px) {
+ .tabs-container {
+ gap: 2px;
+ padding: 0 2px;
+ }
+ .tab-btn {
+ padding: 8px 12px;
+ font-size: 12px;
+ }
+ .tab-btn mat-icon {
+ width: 16px;
+ height: 16px;
+ font-size: 16px;
+ }
+ .eurosci-voc-item {
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 8px;
+ }
+ .eurosci-voc-item .voc-path {
+ min-width: 100%;
+ }
+ .eurosci-voc-item .search-icon {
+ opacity: 1;
+ align-self: flex-end;
+ }
+ .eurosci-voc-item .path-segment {
+ font-size: 12px;
+ }
+}
+@media (max-width: 480px) {
+ .eurosci-voc-item {
+ padding: 10px 12px;
+ }
+ .eurosci-voc-item .path-segment {
+ font-size: 11px;
+ padding: 1px 6px;
+ }
+ .eurosci-voc-item .voc-code {
+ font-size: 10px;
+ }
+}
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts
new file mode 100644
index 00000000..dc584171
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts
@@ -0,0 +1,494 @@
+// eu-details.component.ts (refactored)
+import { Component, OnInit, inject, OnDestroy } from '@angular/core';
+import { ActivatedRoute, Router } from '@angular/router';
+import { CommonModule } from '@angular/common';
+import { MatCardModule } from '@angular/material/card';
+import { MatIconModule } from '@angular/material/icon';
+import { MatChipsModule } from '@angular/material/chips';
+import { MatButtonModule } from '@angular/material/button';
+import { MatDividerModule } from '@angular/material/divider';
+import { MatTooltipModule } from '@angular/material/tooltip';
+import { Subscription } from 'rxjs';
+import {
+ formatGermanDate,
+ formatCurrency,
+} from '../../../shared/utils/formatters';
+import { EuProjectData } from '../../../api/model/euProjectData';
+import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component';
+import { OrganizationsTableComponent } from './organizations-table/organizations-table/organizations-table.component';
+import { PublicationsTableComponent } from './publications-table/publications-table.component';
+import { PatentsCardsComponent } from './patents-cards/patents-cards.component';
+import { DeliverablesCardsComponent } from './deliverables-cards/deliverables-cards.component';
+export type TabType =
+ | 'overview'
+ | 'organizations'
+ | 'publications'
+ | 'iprs'
+ | 'deliverables';
+
+@Component({
+ selector: 'app-eu-details',
+ standalone: true,
+ imports: [
+ CommonModule,
+ MatCardModule,
+ MatIconModule,
+ MatChipsModule,
+ MatButtonModule,
+ MatDividerModule,
+ MatTooltipModule,
+ TopicChipComponent,
+ OrganizationsTableComponent,
+ PublicationsTableComponent,
+ PatentsCardsComponent,
+ DeliverablesCardsComponent,
+ ],
+ templateUrl: './eu-details.component.html',
+ styleUrl: './eu-details.component.scss',
+})
+export class EuDetailsComponent implements OnInit, OnDestroy {
+ private route = inject(ActivatedRoute);
+ private router = inject(Router);
+
+ // Data
+ euProject: EuProjectData | undefined;
+ programType: string = '';
+
+ // UI State
+ activeTab: TabType = 'overview';
+ isLoading = true;
+
+ // Tab content flags
+ hasOrganizations = false;
+ hasPublications = false;
+ hasIprs = false;
+ hasDeliverables = false;
+
+ // Subscriptions
+ private subscriptions: Subscription = new Subscription();
+
+ // Tab configuration
+ private readonly tabConfig: Record<
+ TabType,
+ { label: string; icon: string; order: number }
+ > = {
+ overview: { label: 'Übersicht', icon: 'info', order: 0 },
+ organizations: { label: 'Organisationen', icon: 'business', order: 1 },
+ publications: { label: 'Publikationen', icon: 'article', order: 2 },
+ iprs: { label: 'IPRs', icon: 'gavel', order: 3 },
+ deliverables: { label: 'Ergebnisse', icon: 'assignment', order: 4 },
+ };
+
+ ngOnInit(): void {
+ // Subscribe to route data
+ this.subscriptions.add(
+ this.route.data.subscribe(({ euSingleProject }) => {
+ console.log('EU Project:', euSingleProject);
+ this.euProject = euSingleProject.eu_project_data;
+ this.isLoading = false;
+
+ if (this.euProject) {
+ this.determineProgramType(euSingleProject);
+ this.updateTabContentFlags();
+ this.handleTabFromQueryParams();
+ }
+ }),
+ );
+
+ // Subscribe to query params changes
+ this.subscriptions.add(
+ this.route.queryParams.subscribe((params) => {
+ // Only handle if data is already loaded
+ if (this.euProject) {
+ this.handleTabFromQueryParams(params);
+ }
+ }),
+ );
+ }
+
+ ngOnDestroy(): void {
+ this.subscriptions.unsubscribe();
+ }
+
+ // ============= PRIVATE METHODS =============
+
+ /**
+ * Determine program type based on available data
+ */
+ private determineProgramType(euSingleProject: any): void {
+ if (euSingleProject.iprs !== undefined) {
+ this.programType = 'fp7';
+ } else if (euSingleProject.ercPrincipalInvestigators !== undefined) {
+ this.programType = 'h2020';
+ } else if (euSingleProject.deliverables !== undefined) {
+ this.programType = 'heu';
+ }
+ }
+
+ /**
+ * Update flags for which tabs have content
+ */
+ private updateTabContentFlags(): void {
+ this.hasOrganizations =
+ (this.euProject?.organizations &&
+ this.euProject.organizations.length > 0) ||
+ false;
+ this.hasPublications =
+ (this.euProject?.publications &&
+ this.euProject.publications.length > 0) ||
+ false;
+ this.hasIprs =
+ (this.euProject?.iprs && this.euProject.iprs.length > 0) || false;
+ this.hasDeliverables =
+ (this.euProject?.deliverables &&
+ this.euProject.deliverables.length > 0) ||
+ false;
+ }
+
+ /**
+ * Handle tab selection from query params
+ */
+ private handleTabFromQueryParams(params?: any): void {
+ const queryParams = params || this.route.snapshot.queryParams;
+ const tabParam = queryParams['tab'] as TabType;
+
+ if (!tabParam) {
+ this.activeTab = 'overview'; // silent default, no navigation
+ return;
+ }
+
+ if (this.isValidTab(tabParam) && this.tabHasContent(tabParam)) {
+ this.activeTab = tabParam;
+ } else {
+ // tab param exists but is invalid/empty — correct it
+ this.activeTab = 'overview';
+ this.updateTabQueryParam('overview');
+ }
+ }
+
+ /**
+ * Check if a tab value is valid
+ */
+ private isValidTab(tab: string): tab is TabType {
+ return [
+ 'overview',
+ 'organizations',
+ 'publications',
+ 'iprs',
+ 'deliverables',
+ ].includes(tab);
+ }
+
+ /**
+ * Check if a tab has content to display
+ */
+ private tabHasContent(tab: TabType): boolean {
+ switch (tab) {
+ case 'overview':
+ return true;
+ case 'organizations':
+ return this.hasOrganizations;
+ case 'publications':
+ return this.hasPublications;
+ case 'iprs':
+ return this.hasIprs;
+ case 'deliverables':
+ return this.hasDeliverables;
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * Update URL query param for tab
+ */
+ private updateTabQueryParam(tab: TabType): void {
+ const currentTab = this.route.snapshot.queryParams['tab'];
+ if (currentTab === tab) return;
+
+ this.router
+ .navigate([], {
+ relativeTo: this.route,
+ queryParams: { tab },
+ queryParamsHandling: 'merge',
+ replaceUrl: true,
+ })
+ .catch((err) => console.error('Tab navigation failed:', err));
+ }
+
+ /**
+ * Get color for keyword based on index
+ */
+ private getKeywordColor(index: number): string {
+ const colors = [
+ '#3498db', // Blue
+ '#e67e22', // Orange
+ '#27ae60', // Green
+ '#8e44ad', // Purple
+ '#e74c3c', // Red
+ '#1abc9c', // Teal
+ '#f39c12', // Gold
+ '#2c3e50', // Navy
+ ];
+ return colors[index % colors.length];
+ }
+
+ // ============= PUBLIC METHODS =============
+
+ /**
+ * Set active tab and update URL
+ */
+ setTab(tab: TabType): void {
+ if (this.activeTab === tab) return;
+
+ // Check if tab has content
+ if (!this.tabHasContent(tab)) {
+ return;
+ }
+
+ this.activeTab = tab;
+ this.updateTabQueryParam(tab);
+ }
+
+ /**
+ * Check if a tab is active
+ */
+ isTabActive(tab: TabType): boolean {
+ return this.activeTab === tab;
+ }
+
+ /**
+ * Check if tab is visible (has content)
+ */
+ isTabVisible(tab: TabType): boolean {
+ return this.tabHasContent(tab);
+ }
+
+ /**
+ * Get tab label with count
+ */
+ getTabLabel(tab: TabType): string {
+ return this.tabConfig[tab].label;
+ }
+
+ /**
+ * Get tab icon
+ */
+ getTabIcon(tab: TabType): string {
+ return this.tabConfig[tab].icon;
+ }
+
+ /**
+ * Get tab count badge
+ */
+ getTabCount(tab: TabType): number | null {
+ switch (tab) {
+ case 'organizations':
+ return this.euProject?.organizations?.length || null;
+ case 'publications':
+ return this.euProject?.publications?.length || null;
+ case 'iprs':
+ return this.euProject?.iprs?.length || null;
+ case 'deliverables':
+ return this.euProject?.deliverables?.length || null;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get sorted tabs that have content
+ */
+ getVisibleTabs(): TabType[] {
+ return (
+ [
+ 'overview',
+ 'organizations',
+ 'publications',
+ 'iprs',
+ 'deliverables',
+ ] as TabType[]
+ )
+ .filter((tab) => this.tabHasContent(tab))
+ .sort((a, b) => this.tabConfig[a].order - this.tabConfig[b].order);
+ }
+
+ // ============= FORMATTING METHODS =============
+
+ getFundingStatus(endDate: string | null | undefined): string {
+ if (!endDate) return 'N/A';
+ const end = new Date(endDate);
+ const now = new Date();
+
+ if (isNaN(end.getTime())) return endDate;
+
+ return end >= now ? 'Laufend' : 'Abgeschlossen';
+ }
+
+ getDuration(start: string | undefined, end: string | undefined): string {
+ if (!start || !end) return '';
+ return `von ${formatGermanDate(start)} bis ${formatGermanDate(end)}`;
+ }
+
+ formatDate(date: string | undefined): string | undefined {
+ if (date) {
+ return formatGermanDate(date);
+ }
+ return date;
+ }
+
+ formatCurr(value: number | undefined | null): string | null | undefined {
+ if (value) {
+ return formatCurrency(value);
+ }
+ return String(value);
+ }
+
+ getStatusColor(status: string | null | undefined): string {
+ if (!status) return '#95a5a6';
+
+ const statusUpper = status.toUpperCase();
+ if (statusUpper.includes('CLOSED') || statusUpper.includes('COMPLETED')) {
+ return '#27ae60';
+ } else if (
+ statusUpper.includes('ONGOING') ||
+ statusUpper.includes('ACTIVE')
+ ) {
+ return '#f39c12';
+ } else if (statusUpper.includes('SIGNED')) {
+ return '#3498db';
+ } else if (statusUpper.includes('CANCELLED')) {
+ return '#e74c3c';
+ } else {
+ return '#95a5a6';
+ }
+ }
+
+ getStatusDisplay(status: string | null | undefined): string {
+ if (!status) return 'N/A';
+
+ const statusMap: { [key: string]: string } = {
+ CLOSED: 'Abgeschlossen',
+ COMPLETED: 'Abgeschlossen',
+ ONGOING: 'Laufend',
+ ACTIVE: 'Aktiv',
+ SIGNED: 'Unterzeichnet',
+ CANCELLED: 'Abgebrochen',
+ SUSPENDED: 'Unterbrochen',
+ };
+
+ const statusUpper = status.toUpperCase();
+ return statusMap[statusUpper] || status;
+ }
+
+ getFrameworkDisplay(framework: string | null | undefined): string {
+ if (!framework) return 'N/A';
+
+ const frameworkMap: { [key: string]: string } = {
+ HORIZON: ' Horizon Europe',
+ H2020: 'Horizon 2020',
+ FP7: '7. Rahmenprogramm',
+ FP6: '6. Rahmenprogramm',
+ HE: 'Horizon Europe',
+ };
+
+ return frameworkMap[framework] || framework;
+ }
+
+ getFundingSchemeDisplay(scheme: string | null | undefined): string {
+ if (!scheme) return 'N/A';
+
+ const schemeMap: { [key: string]: string } = {
+ 'MSCA-IF-EF-SE':
+ 'MSCA Individual Fellowship - European Fellowship - Standard',
+ 'MSCA-IF-EF': 'MSCA Individual Fellowship - European Fellowship',
+ 'MSCA-IF-GF': 'MSCA Individual Fellowship - Global Fellowship',
+ 'MSCA-IF': 'MSCA Individual Fellowship',
+ 'MSCA-ITN': 'MSCA Innovative Training Networks',
+ 'MSCA-RISE': 'MSCA Research and Innovation Staff Exchange',
+ 'MSCA-COFUND':
+ 'MSCA Co-funding of Regional, National and International Programmes',
+ };
+
+ return schemeMap[scheme] || scheme;
+ }
+ notEmpty(array: any): boolean {
+ if (array === undefined) return false;
+ return Array.isArray(array) && array.length > 0;
+ }
+
+ getFormattedTopics(topics: string | null | undefined): string[] {
+ if (!topics) return [];
+ return topics
+ .split(',')
+ .map((t) => t.trim())
+ .filter((t) => t);
+ }
+
+ getKeywords(keywords: string | null | undefined): string[] {
+ if (!keywords) return [];
+ if (keywords === 'false') return [];
+ if (typeof keywords === 'string') {
+ return keywords
+ .split(',')
+ .map((k) => k.trim())
+ .filter((k) => k && k !== 'false');
+ }
+ return [];
+ }
+
+ /**
+ * Get keywords mapped to topic chip format
+ */
+ getKeywordChips(): {
+ label: string;
+ count?: number;
+ description?: string;
+ subfieldName?: string;
+ fieldName?: string;
+ domainName?: string;
+ color?: string;
+ id?: string;
+ }[] {
+ const keywords = this.getKeywords(this.euProject?.keywords);
+ if (keywords.length === 0) return [];
+
+ return keywords.map((keyword, index) => ({
+ label: keyword,
+ count: 1,
+ description: `Schlüsselwort: ${keyword}`,
+ subfieldName: '',
+ fieldName: '',
+ domainName: '',
+ color: this.getKeywordColor(index),
+ id: keyword,
+ }));
+ }
+
+ /**
+ * Get path segments from a path string
+ */
+ getPathSegments(path: string | undefined): string[] {
+ if (!path) return [];
+ return path.split('/').filter((segment) => segment.trim());
+ }
+
+ getTotalEcContribution(): number {
+ if (!this.euProject?.organizations) return 0;
+ return this.euProject.organizations
+ .filter((org) => org.ecContribution !== undefined)
+ .reduce((sum, org) => sum + (org.ecContribution || 0), 0);
+ }
+
+ getOrganizationCountries(): string[] {
+ if (!this.euProject?.organizations) return [];
+ const countries = new Set(
+ this.euProject.organizations
+ .filter((org) => org.country)
+ .map((org) => org.country as string),
+ );
+ return Array.from(countries);
+ }
+
+ // ============= SEARCH / NAVIGATION METHODS =============
+}
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html
new file mode 100644
index 00000000..1e5bfd19
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html
@@ -0,0 +1,121 @@
+
+
+
+
+
+
+
+ | Name |
+
+
+ {{
+ org.name || org.shortName || 'Unbekannte Organisation'
+ }}
+
+ |
+
+
+
+
+ Rolle |
+
+ @if (org.role) {
+ {{ org.role }}
+ } @else {
+ —
+ }
+ |
+
+
+
+
+ Stadt |
+
+ @if (org.city) {
+
+ {{ org.city }}
+
+
+
+ } @else {
+ —
+ }
+ |
+
+
+
+
+ EU-Beitrag |
+
+ @if (org.ecContribution) {
+ {{
+ formatCurr(org.ecContribution)
+ }}
+ } @else {
+ —
+ }
+ |
+
+
+
+
+ Aktivitätstyp |
+
+ @if (org.activityType) {
+ {{ org.activityType }}
+ } @else {
+ —
+ }
+ |
+
+
+
+
+ SME |
+
+ @if (org.sme) {
+ SME
+ } @else {
+ —
+ }
+ |
+
+
+
+
+ URL |
+
+
+ |
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.scss
new file mode 100644
index 00000000..0ed8015c
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.scss
@@ -0,0 +1,266 @@
+// Organizations
+
+.organizations-tab {
+ .card {
+ margin-bottom: 24px;
+ }
+
+ .section-header {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 16px 20px;
+ border-bottom: 1px solid #e6e9ed;
+
+ mat-icon {
+ color: #6b7a8a;
+ font-size: 24px;
+ width: 24px;
+ height: 24px;
+ }
+
+ h2 {
+ margin: 0;
+ font-size: 18px;
+ font-weight: 600;
+ color: #1a1a1a;
+ }
+ }
+
+ .organizations-table-wrapper {
+
+ table {
+ width: 100%;
+ border-radius: 8px;
+ overflow: hidden;
+ }
+
+ .mat-mdc-header-cell {
+ font-weight: 600;
+ color: #6b7a8a;
+ font-size: 12px;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ background: #f8fafc;
+ border-bottom: 2px solid #e6e9ed;
+ padding: 12px 16px;
+ }
+
+ .mat-mdc-cell {
+ padding: 12px 16px;
+ border-bottom: 1px solid #f0f2f5;
+ font-size: 13px;
+ }
+
+ .mat-mdc-row {
+ transition: background 0.2s ease;
+ }
+
+ .mat-mdc-row:hover {
+ background: #f8fafc;
+ }
+ }
+
+ .org-name-cell {
+ display: flex;
+ align-items: center;
+ gap: 24px;
+ cursor: pointer;
+ }
+
+ .org-name-text {
+ font-weight: 500;
+ color: #1a1a1a;
+ }
+
+ .org-name-cell:hover .org-name-text {
+ color: #005a9c;
+ text-decoration: underline;
+ }
+
+ .role-chip {
+ display: inline-block;
+ padding: 2px 10px;
+ background: #e8edf5;
+ border-radius: 12px;
+ font-size: 12px;
+ color: #6b7a8a;
+ }
+
+ .country-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 10px;
+ font-size: 13px;
+ }
+
+ .country-flag {
+ width: auto;
+ height: 10px;
+ }
+
+ .currency-value {
+ font-weight: 500;
+ color: #1a1a1a;
+ }
+
+ .empty-value {
+ color: #6b7a8a;
+ }
+
+ .activity-chip {
+ display: inline-block;
+ padding: 2px 10px;
+ background: #f0f3f7;
+ border-radius: 12px;
+ font-size: 12px;
+ color: #6b7a8a;
+ }
+
+ .sme-badge {
+ display: inline-block;
+ padding: 2px 8px;
+ background: #e8f5e9;
+ color: #2e7d32;
+ border-radius: 4px;
+ font-weight: 500;
+ font-size: 12px;
+ }
+
+ .links-container {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ }
+
+ .link-button {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 2px 8px;
+ background: #f0f3f7;
+ border-radius: 4px;
+ color: #4a5a6a;
+ text-decoration: none;
+ font-size: 12px;
+ transition: all 0.2s ease;
+
+ &:hover {
+ background: #e8edf5;
+ color: #005a9c;
+ }
+
+ .link-icon {
+ font-size: 16px;
+ width: 16px;
+ height: 16px;
+ color: #6b7a8a;
+ }
+
+ .link-label {
+ font-size: 11px;
+ font-weight: 500;
+ }
+ }
+}
+
+@media (max-width: 768px) {
+ .organizations-tab {
+ .section-header {
+ padding: 12px 16px;
+
+ h2 {
+ font-size: 16px;
+ }
+ }
+
+ .organizations-table-wrapper {
+ padding: 0 12px 12px;
+ }
+
+ .mat-mdc-header-cell,
+ .mat-mdc-cell {
+ padding: 8px 10px;
+ font-size: 12px;
+ }
+
+ .country-flag {
+ height: 8px;
+ }
+
+ .role-chip,
+ .activity-chip {
+ font-size: 11px;
+ padding: 2px 8px;
+ }
+
+ .sme-badge {
+ font-size: 11px;
+ padding: 2px 6px;
+ }
+
+ .link-button {
+ padding: 2px 6px;
+ font-size: 11px;
+
+ .link-label {
+ font-size: 10px;
+ }
+
+ .link-icon {
+ font-size: 14px;
+ width: 14px;
+ height: 14px;
+ }
+ }
+
+ .org-name-text {
+ font-size: 13px;
+ }
+ }
+}
+
+@media (max-width: 480px) {
+ .organizations-tab {
+ .mat-column-role {
+ display: none;
+ }
+
+ .mat-column-activityType {
+ display: none;
+ }
+
+ .mat-mdc-cell {
+ padding: 6px 8px;
+ font-size: 11px;
+ }
+
+ .country-chip {
+ font-size: 11px;
+ gap: 6px;
+ }
+
+ .currency-value {
+ font-size: 12px;
+ }
+
+ .links-container {
+ gap: 4px;
+ }
+
+ .link-button {
+ padding: 2px 4px;
+ font-size: 10px;
+
+ .link-label {
+ display: none;
+ }
+
+ .link-icon {
+ font-size: 16px;
+ width: 16px;
+ height: 16px;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts
new file mode 100644
index 00000000..c5f61a8d
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts
@@ -0,0 +1,55 @@
+import { Component, inject,Input } from '@angular/core';
+import { MatTableModule } from '@angular/material/table';
+import { Router } from '@angular/router';
+import { formatCurrency } from '../../../../../shared/utils/formatters';
+import { MatIcon } from '@angular/material/icon';
+import { MatCard } from '@angular/material/card';
+import { HEUOrganization } from '../../../../../api';
+@Component({
+ selector: 'app-organizations-table',
+ imports: [MatTableModule,MatIcon,MatCard],
+ templateUrl: './organizations-table.component.html',
+ styleUrl: './organizations-table.component.scss',
+})
+export class OrganizationsTableComponent {
+ private router = inject(Router);
+
+ @Input() orgs!: HEUOrganization[];
+ @Input() showHeader: boolean = true;
+ @Input() headerTitle: string = 'Organizationen';
+
+ // Displayed columns for the organizations table
+ organizationDisplayedColumns: string[] = [
+ 'name',
+ 'role',
+ 'country',
+ 'ecContribution',
+ 'activityType',
+ 'sme',
+ 'organizationURL',
+ ];
+
+ searchForInstitutionName(institutionName: string): void {
+ this.router.navigate(['/institutions'], {
+ queryParams: {
+ search: institutionName,
+ },
+ });
+ }
+ getSvgByCountryCode(code: string) {
+ const codeLower = code.toLowerCase();
+ if (codeLower === 'uk') {
+ return 'gb';
+ }
+ return codeLower;
+ }
+ getOrgsCount(): number {
+ return this.orgs?.length || 0;
+ }
+ formatCurr(value: number | undefined | null) {
+ if (value) {
+ return formatCurrency(value);
+ }
+ return value;
+ }
+}
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.html b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.html
new file mode 100644
index 00000000..8da21925
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.html
@@ -0,0 +1,49 @@
+
+
+
+
+ @for (ipr of patents; track ipr.title) {
+
+
+ @if (ipr.type === 'PATENT') {
+ emoji_events
+ } @else {
+ copyright
+ }
+
+
+
{{ ipr.title || 'Ohne Titel' }}
+
+ @if (ipr.type) {
+ {{ ipr.type }}
+ }
+ @if (ipr.patentType) {
+ {{ ipr.patentType }}
+ }
+ @if (ipr.applicantName) {
+ Applicant: {{ ipr.applicantName }}
+ }
+
+
+ @if (ipr.applicationIdentifier) {
+ App: {{ ipr.applicationIdentifier }}
+ }
+ @if (ipr.awardIdentifier) {
+ Award: {{ ipr.awardIdentifier }}
+ }
+
+
+
+ }
+
+
+
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.scss
new file mode 100644
index 00000000..43846f9a
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.scss
@@ -0,0 +1,113 @@
+.section-header {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 16px 20px;
+ border-bottom: 1px solid #e6e9ed;
+}
+
+.section-header mat-icon {
+ color: var(--sg-text-muted);
+ width: 22px;
+ height: 22px;
+ font-size: 22px;
+}
+
+.section-header h2 {
+ margin: 0;
+ font-size: 18px;
+ font-weight: 600;
+ color: var(--sg-text);
+}
+// IPRs
+.iprs-list {
+ padding: 16px 20px 20px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.ipr-item {
+ cursor: pointer;
+ display: flex;
+ align-items: flex-start;
+ gap: 16px;
+ padding: 14px 16px;
+ border: 1px solid #d9e2f0;
+ border-radius: var(--sg-radius-sm);
+ background: #fff;
+ transition: all 0.2s;
+
+ &:hover {
+ background: #f8fafc;
+ }
+}
+
+.ipr-icon {
+ flex-shrink: 0;
+ color: #f39c12;
+
+ mat-icon {
+ width: 24px;
+ height: 24px;
+ font-size: 24px;
+ }
+}
+
+.ipr-info {
+ flex: 1;
+ min-width: 0;
+}
+
+.ipr-title {
+ font-weight: 500;
+ color: var(--sg-text);
+ font-size: 14px;
+}
+
+.ipr-details {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-top: 4px;
+ font-size: 12px;
+
+ .ipr-type {
+ padding: 1px 8px;
+ background: #fff3e0;
+ border-radius: var(--sg-radius-sm);
+ color: #e65100;
+ font-weight: 500;
+ }
+
+ .ipr-patent-type {
+ padding: 1px 8px;
+ background: #e8eaf6;
+ border-radius: var(--sg-radius-sm);
+ color: #283593;
+ }
+
+ .ipr-applicant {
+ color: var(--sg-text-muted);
+ }
+}
+
+.ipr-identifiers {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-top: 4px;
+ font-size: 11px;
+ color: var(--sg-text-muted);
+
+ .ipr-app-id,
+ .ipr-award-id {
+ padding: 1px 8px;
+ background: #f5f7fa;
+ border-radius: var(--sg-radius-sm);
+ }
+}
+
+.ipr-item {
+ flex-wrap: wrap;
+}
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.ts
new file mode 100644
index 00000000..1d8f46ac
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.ts
@@ -0,0 +1,25 @@
+import { Component, inject } from '@angular/core';
+import { Fp7ProjectIPR } from '../../../../api';
+import { Router } from '@angular/router';
+import { Input } from '@angular/core';
+import { MatIcon } from '@angular/material/icon';
+import { MatCard } from '@angular/material/card';
+@Component({
+ selector: 'app-patents-cards',
+ imports: [MatIcon, MatCard],
+ templateUrl: './patents-cards.component.html',
+ styleUrl: './patents-cards.component.scss',
+})
+export class PatentsCardsComponent {
+ @Input() patents: Fp7ProjectIPR[] = [];
+ @Input() showHeader: boolean = true;
+ @Input() headerTitle: string = 'IPRs';
+ private router = inject(Router);
+ searchForPatent(patent: Fp7ProjectIPR): void {
+ this.router.navigate(['/patents'], {
+ queryParams: {
+ search: patent.title,
+ },
+ });
+ }
+}
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html
new file mode 100644
index 00000000..0b921f55
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html
@@ -0,0 +1,141 @@
+
+
+ @if (showHeader) {
+
+ }
+
+
+
+
+ | Titel |
+
+
+
+ {{ pub.title || 'Kein Titel' }}
+
+
+ |
+
+
+
+
+ Autoren |
+
+ @if (pub.authors) {
+ @let authorList = parseAuthors(pub.authors);
+ @if (authorList.length > 0) {
+
+ @for (author of authorList; track author; let last = $last) {
+
+
+ {{ author }}
+
+ @if (!last) {
+ ,
+ }
+
+ }
+
+ } @else {
+ —
+ }
+ } @else {
+ —
+ }
+ |
+
+
+
+
+ Zeitschrift |
+
+ @if (pub.journalNumber) {
+ {{ pub.journalNumber }}
+ } @else {
+ —
+ }
+ |
+
+
+
+
+ Jahr |
+
+ @if (pub.publishedYear) {
+ {{ pub.publishedYear }}
+ } @else {
+ —
+ }
+ |
+
+
+
+
+ Verlag |
+
+ @if (pub.publisher) {
+ {{ pub.publisher }}
+ } @else {
+ —
+ }
+ |
+
+
+
+
+ Links |
+
+
+ |
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss
new file mode 100644
index 00000000..cc50153b
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss
@@ -0,0 +1,236 @@
+// Publications Table
+
+.publications-tab {
+ .card {
+ margin-bottom: 24px;
+ }
+
+ .section-header {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 16px 20px;
+ border-bottom: 1px solid #e6e9ed;
+
+ mat-icon {
+ color: #6b7a8a;
+ font-size: 24px;
+ width: 24px;
+ height: 24px;
+ }
+
+ h2 {
+ margin: 0;
+ font-size: 18px;
+ font-weight: 600;
+ color: #1a1a1a;
+ }
+ }
+
+ table {
+ width: 100%;
+ border-radius: 8px;
+ overflow: hidden;
+ }
+
+ .mat-mdc-header-cell {
+ font-weight: 600;
+ color: #6b7a8a;
+ font-size: 12px;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ background: #f8fafc;
+ border-bottom: 2px solid #e6e9ed;
+ padding: 12px 16px;
+ }
+
+ .mat-mdc-cell {
+ padding: 12px 16px;
+ border-bottom: 1px solid #f0f2f5;
+ font-size: 13px;
+ }
+
+ .mat-mdc-row {
+ transition: background 0.2s ease;
+ cursor: pointer;
+ }
+
+ .mat-mdc-row:hover {
+ background: #f8fafc;
+ }
+
+ .pub-title-cell {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ cursor: pointer;
+ }
+
+ .pub-title-text {
+ font-weight: 500;
+ color: #1a1a1a;
+ line-height: 1.4;
+ }
+
+ .pub-title-cell:hover .pub-title-text {
+ color: #005a9c;
+ text-decoration: underline;
+ }
+
+ .authors-text {
+ color: #4a5a6a;
+ font-size: 13px;
+ color: #1a1a1a;
+ line-height: 1.4;
+ }
+ .author-name:hover {
+ color: #005a9c;
+ text-decoration: underline;
+ }
+
+ .journal-chip {
+ display: inline-block;
+ padding: 2px 10px;
+ background: #e8edf5;
+ border-radius: 12px;
+ font-size: 12px;
+ color: #6b7a8a;
+ max-width: 200px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ .year-value {
+ font-weight: 500;
+ color: #1a1a1a;
+ }
+
+ .publisher-text {
+ color: #4a5a6a;
+ font-size: 13px;
+ }
+
+ .empty-value {
+ color: #6b7a8a;
+ font-size: 13px;
+ }
+
+ .links-container {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
+ }
+
+ .link-button {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 10px;
+ background: #f0f3f7;
+ border-radius: 12px;
+ color: #4a5a6a;
+ text-decoration: none;
+ font-size: 11px;
+ font-weight: 500;
+ transition: all 0.2s ease;
+
+ &:hover {
+ background: #e8edf5;
+ color: #005a9c;
+ transform: translateY(-1px);
+ }
+
+ .link-icon {
+ font-size: 14px;
+ width: 14px;
+ height: 14px;
+ color: #6b7a8a;
+ }
+
+ .link-label {
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: 0.3px;
+ }
+ }
+
+ // Responsive styles
+ @media (max-width: 768px) {
+ .section-header {
+ padding: 12px 16px;
+
+ h2 {
+ font-size: 16px;
+ }
+ }
+
+ .mat-mdc-header-cell,
+ .mat-mdc-cell {
+ padding: 8px 10px;
+ font-size: 12px;
+ }
+
+ .publicationDisplayedColumns {
+ // Hide less important columns on mobile
+ .mat-column-publisher {
+ display: none;
+ }
+ }
+
+ .journal-chip {
+ max-width: 120px;
+ font-size: 11px;
+ }
+
+ .link-button {
+ padding: 2px 8px;
+ font-size: 10px;
+
+ .link-label {
+ display: none;
+ }
+ }
+
+ .pub-title-text {
+ font-size: 13px;
+ }
+ }
+
+ @media (max-width: 480px) {
+ .mat-column-journal {
+ display: none;
+ }
+
+ .mat-column-publisher {
+ display: none;
+ }
+
+ .mat-mdc-cell {
+ padding: 6px 8px;
+ font-size: 11px;
+ }
+
+ .authors-text {
+ font-size: 11px;
+ max-width: 100px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ display: inline-block;
+ }
+
+ .links-container {
+ gap: 4px;
+ }
+
+ .link-button {
+ padding: 2px 6px;
+ font-size: 9px;
+ }
+ }
+}
+.deliverable-item {
+ flex-wrap: wrap;
+}
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts
new file mode 100644
index 00000000..44f5af5e
--- /dev/null
+++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts
@@ -0,0 +1,87 @@
+import { Component, computed, inject, Input } from '@angular/core';
+import { MatTableModule } from '@angular/material/table';
+import { Router } from '@angular/router';
+import { MatIcon } from '@angular/material/icon';
+import { MatCard } from '@angular/material/card';
+import { MatTooltipModule } from '@angular/material/tooltip';
+import { CommonModule } from '@angular/common';
+import { HEUPublication } from '../../../../api';
+
+@Component({
+ selector: 'app-publications-table',
+ imports: [CommonModule, MatTableModule, MatIcon, MatCard, MatTooltipModule],
+ templateUrl: './publications-table.component.html',
+ styleUrl: './publications-table.component.scss',
+})
+export class PublicationsTableComponent {
+ private router = inject(Router);
+
+ @Input() publications: HEUPublication[] = [];
+ @Input() showHeader: boolean = true;
+ @Input() headerTitle: string = 'Publikationen';
+
+ // Displayed columns for the publications table
+ publicationDisplayedColumns: string[] = [
+ 'title',
+ 'authors',
+ 'journal',
+ 'year',
+ 'publisher',
+ 'links',
+ ];
+ author_names = computed(() => 'keka');
+ /**
+ * Navigate to publication details
+ */
+ searchForPublication(pub: HEUPublication): void {
+ if (!pub) {
+ console.warn('Cannot navigate with empty publication');
+ return;
+ }
+
+ const doi = pub.doi?.trim() ?? 'unknown';
+
+ // Encode DOI and navigate
+ const encodedDoi = encodeURIComponent(doi);
+
+ this.router
+ .navigate(['/publication', encodedDoi], {
+ queryParams: {
+ title: pub.title || '',
+ },
+ })
+ .catch((err) => console.error('Navigation to publication failed:', err));
+ }
+
+ getPublicationCount(): number {
+ return this.publications?.length || 0;
+ }
+ searchForPersonName(personName: string): void {
+ this.router.navigate(['/persons'], {
+ queryParams: {
+ query: personName,
+ },
+ });
+ }
+ // Parse authors string into array of individual authors
+ parseAuthors(authorsString: string | undefined): string[] {
+ if (!authorsString) return [];
+
+ // Common separators: 'and', ',', ';', '&'
+ // Also handle cases like "Author1, Author2 and Author3"
+ let authors = authorsString;
+
+ // Replace ' and ' with ', ' for consistent splitting
+ authors = authors.replace(/\s+and\s+/g, ', ');
+
+ // Split by common separators
+ let authorList = authors.split(/[,;]\s*/);
+
+ // Clean up each author name
+ authorList = authorList
+ .map((author) => author.trim())
+ .filter((author) => author.length > 0);
+
+ return authorList;
+ }
+}
diff --git a/webapp/src/app/modules/projects/projects.component.ts b/webapp/src/app/modules/projects/projects.component.ts
index effdc3f4..4361c9bb 100644
--- a/webapp/src/app/modules/projects/projects.component.ts
+++ b/webapp/src/app/modules/projects/projects.component.ts
@@ -72,11 +72,13 @@ export class ProjectsComponent {
getDetaiLink(fundingProject: FundingProject): string | null {
if (fundingProject.type === 'bund') {
- return '/projects/bund/' + fundingProject.id;
+ const encodedId = encodeURIComponent(fundingProject.id)
+ return '/projects/bund/' + encodedId;
} else if (fundingProject.type === 'dfg') {
return '/projects/dfg/' + fundingProject.id;
- } else {
+ } else if (fundingProject.type === 'eu') {
+ return '/projects/eu/' + fundingProject.id;
+ } else
return null;
}
- }
}
diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts
index 2eeb7feb..c2850656 100644
--- a/webapp/src/app/modules/publication-detail/publication-detail.component.ts
+++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts
@@ -8,7 +8,6 @@ import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { finalize } from 'rxjs';
-
import {
Authorship,
Location as ApiLocation,
@@ -54,18 +53,18 @@ export class PublicationDetailComponent implements OnInit {
notFound = false;
ngOnInit(): void {
- this.route.paramMap
- .pipe(takeUntilDestroyed(this.destroyRef))
- .subscribe((params) => {
- const publicationId = params.get('publicationId');
- if (!publicationId) {
- this.loading = false;
- this.notFound = true;
- return;
- }
+ this.loading = true;
- this.loadPublication(publicationId);
- });
+ this.route.data.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
+ next: ({ publication }) => {
+ this.publication = publication;
+ this.loading = false;
+ },
+ error: () => {
+ this.notFound = true;
+ this.loading = false;
+ },
+ });
}
navigateBack(): void {
@@ -157,27 +156,6 @@ export class PublicationDetailComponent implements OnInit {
return 'Kein Open Access';
}
- private loadPublication(publicationId: string): void {
- this.loading = true;
- this.notFound = false;
- this.publication = null;
-
- const basePath = this.worksService.configuration.basePath ?? '';
- this.httpClient
- .get
(
- `${basePath}/api/works/detail/${encodeURIComponent(publicationId)}`,
- )
- .pipe(finalize(() => (this.loading = false)))
- .subscribe({
- next: (publication) => {
- this.publication = publication;
- },
- error: () => {
- this.notFound = true;
- },
- });
- }
-
private doiUrl(doi: string | null | undefined): string | null {
if (!doi) return null;
return doi.startsWith('http') ? doi : `https://doi.org/${doi}`;
diff --git a/webapp/src/app/resolvers/eu-single-project-resolver.ts b/webapp/src/app/resolvers/eu-single-project-resolver.ts
new file mode 100644
index 00000000..032ba63e
--- /dev/null
+++ b/webapp/src/app/resolvers/eu-single-project-resolver.ts
@@ -0,0 +1,16 @@
+import { inject } from '@angular/core';
+import { ResolveFn } from '@angular/router';
+import { ProjectsService } from '../api/api/projects.service';
+import { EuCordisProjectResponse } from '../api';
+
+export const euSingleProjectResolver: ResolveFn = (
+ route,
+ state,
+) => {
+ const projectsService = inject(ProjectsService);
+ const projectId = route.paramMap.get('id');
+ if (!projectId) {
+ throw new Error('EU Cordis Project ID is required');
+ }
+ return projectsService.getSingleEuCordisProject(projectId);
+};
diff --git a/webapp/src/app/resolvers/person-news.resolver.ts b/webapp/src/app/resolvers/person-news.resolver.ts
index 9d361534..6c4bde29 100644
--- a/webapp/src/app/resolvers/person-news.resolver.ts
+++ b/webapp/src/app/resolvers/person-news.resolver.ts
@@ -11,6 +11,7 @@ export interface NewsArticle {
maintitle?: string | null;
author?: string | null;
url?: string | null;
+ relevant?: boolean | null;
}
export interface NewsPage {
diff --git a/webapp/src/app/resolvers/publication-resolver.ts b/webapp/src/app/resolvers/publication-resolver.ts
new file mode 100644
index 00000000..d0e1111e
--- /dev/null
+++ b/webapp/src/app/resolvers/publication-resolver.ts
@@ -0,0 +1,16 @@
+import { ResolveFn } from '@angular/router';
+import { inject } from '@angular/core';
+import { WorksService,Work } from '../api';
+
+export const publicationResolver: ResolveFn = (route) => {
+
+ const id = route.paramMap.get('publicationId');
+ const title = route.queryParamMap.get('title') ?? '';
+ const worksService = inject(WorksService);
+
+ if (!id) {
+ throw new Error('Publication id is required');
+ }
+
+ return worksService.getWork(id, title);
+};
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 3386701a..295aae4c 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
@@ -90,6 +90,12 @@ export class AppMenuComponent {
sorting_order: 'asc',
},
},
+ {
+ label: 'Patente',
+ icon: 'workspace_premium',
+ route: '/patents',
+ disabled: false,
+ },
];
constructor(
diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.html b/webapp/src/app/shared/ui/news-list/news-list.component.html
new file mode 100644
index 00000000..e42d1783
--- /dev/null
+++ b/webapp/src/app/shared/ui/news-list/news-list.component.html
@@ -0,0 +1,156 @@
+
+
+
+ @if (loading) {
+
+
+
+ }
+
+
+
+ | Titel |
+
+ {{
+ article.maintitle || 'Kein Titel'
+ }}
+ @if (article.related) {
+ Ähnlich zu deiner Suche
+ }
+ |
+
+
+
+
+
+ |
+
+ @if (article.relevant === true) {
+
+ check_circle
+ Relevant
+
+ } @else if (article.relevant === false) {
+
+ cancel
+ Nicht relevant
+
+ } @else {
+
+ help
+ Nicht bestimmt
+
+ }
+ |
+
+
+
+ Datum |
+
+ {{ formatDate(article.date) }}
+ |
+
+
+ @if (extraColumnId && extraColumnTemplate) {
+
+ {{ extraColumnHeader }} |
+
+
+ |
+
+ }
+
+
+
+
+
+ @if (!loading && articles.length === 0) {
+
+ @if (isSearching) {
+ Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden.
+ } @else {
+ Keine Nachrichten gefunden.
+ }
+
+ }
+
+
+
diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.scss b/webapp/src/app/shared/ui/news-list/news-list.component.scss
new file mode 100644
index 00000000..df6a9592
--- /dev/null
+++ b/webapp/src/app/shared/ui/news-list/news-list.component.scss
@@ -0,0 +1,279 @@
+.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;
+}
+
+.relevance-field {
+ width: 180px;
+}
+
+.year-field {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ min-width: 220px;
+ padding: 0 6px;
+}
+
+.year-field__head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 10px;
+ font-size: 12px;
+}
+
+.year-field__label {
+ color: var(--sg-text-muted);
+ font-weight: 600;
+}
+
+.year-field__range {
+ color: var(--sg-text);
+ font-weight: 600;
+ white-space: nowrap;
+}
+
+.year-field mat-slider {
+ width: 100%;
+ margin: 0;
+}
+
+.reset-filter-btn {
+ min-width: 132px;
+ height: 42px;
+ padding: 0 14px;
+ border-color: #d9e2f0;
+ border-radius: var(--sg-radius-sm);
+ color: var(--sg-text);
+ background: #fff;
+
+ mat-icon {
+ margin-right: 6px;
+ width: 20px;
+ height: 20px;
+ font-size: 20px;
+ }
+}
+
+.table-wrap {
+ position: relative;
+ overflow-x: auto;
+}
+
+table {
+ width: 100%;
+ min-width: 600px;
+ table-layout: fixed;
+ border-collapse: separate;
+ border-spacing: 0 10px;
+ background: transparent;
+ box-shadow: none;
+}
+
+::ng-deep .mat-column-maintitle {
+ width: 30%;
+}
+
+::ng-deep .mat-column-relevance {
+ width: 160px;
+}
+
+::ng-deep .mat-column-date {
+ width: 110px;
+}
+
+.article-title {
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ line-height: 1.45;
+ color: var(--sg-text);
+ font-size: 14px;
+ font-weight: 700;
+ text-decoration: none;
+
+ &:hover {
+ color: var(--sg-text);
+ text-decoration: underline;
+ }
+}
+
+.related-badge {
+ display: flex;
+ width: fit-content;
+ align-items: center;
+ margin-top: 6px;
+ padding: 3px 10px;
+ border-radius: 999px;
+ font-size: 12px;
+ font-weight: 600;
+ line-height: 1;
+ white-space: nowrap;
+ background: #eef3fe;
+ border: 1px solid #c5d6f7;
+ color: #2f5bd0;
+}
+
+.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;
+}
+
+.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;
+ font-weight: 700;
+}
+
+.relevance-header {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.relevance-info {
+ font-size: 15px;
+ width: 15px;
+ height: 15px;
+ color: var(--sg-text-muted);
+ cursor: help;
+
+ &:hover,
+ &:focus {
+ color: var(--sg-text);
+ }
+}
+
+::ng-deep .relevance-tooltip.mdc-tooltip .mdc-tooltip__surface {
+ max-width: 260px;
+ font-size: 12.5px;
+ line-height: 1.5;
+ padding: 8px 12px;
+}
+
+::ng-deep .mat-mdc-cell {
+ padding-top: 18px;
+ padding-bottom: 18px;
+ vertical-align: top;
+ color: var(--sg-text);
+ border-bottom-color: var(--sg-border);
+ font-size: 13px;
+ overflow-wrap: anywhere;
+}
+
+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) {
+ .table-footer {
+ align-items: stretch;
+ flex-direction: column;
+ }
+}
diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.ts b/webapp/src/app/shared/ui/news-list/news-list.component.ts
new file mode 100644
index 00000000..d0c760a0
--- /dev/null
+++ b/webapp/src/app/shared/ui/news-list/news-list.component.ts
@@ -0,0 +1,206 @@
+import {
+ Component,
+ EventEmitter,
+ Input,
+ Output,
+ TemplateRef,
+ inject,
+} from '@angular/core';
+import { NgTemplateOutlet } from '@angular/common';
+import { FormControl, ReactiveFormsModule } from '@angular/forms';
+import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
+import { RouterLink } from '@angular/router';
+import { merge, debounceTime } from 'rxjs';
+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 { MatTooltipModule } from '@angular/material/tooltip';
+import { MatSliderModule } from '@angular/material/slider';
+import { MatButtonModule } from '@angular/material/button';
+
+import { PaginationService } from '../../services/pagination.service';
+
+export interface NewsArticleBase {
+ id: string;
+ date?: string | null;
+ maintitle?: string | null;
+ url?: string | null;
+ relevant?: boolean | null;
+ related?: boolean | null;
+}
+
+export type SortOrder = 'desc' | 'asc';
+
+export const NEWS_MIN_YEAR = 2000;
+
+export interface NewsFilterState {
+ relevance: string[];
+ yearFrom: number;
+ yearTo: number;
+}
+
+@Component({
+ selector: 'app-news-list',
+ imports: [
+ MatIconModule,
+ MatSelectModule,
+ MatFormFieldModule,
+ MatInputModule,
+ MatPaginatorModule,
+ MatProgressSpinnerModule,
+ MatTableModule,
+ MatTooltipModule,
+ MatSliderModule,
+ MatButtonModule,
+ NgTemplateOutlet,
+ ReactiveFormsModule,
+ RouterLink,
+ ],
+ templateUrl: './news-list.component.html',
+ styleUrl: './news-list.component.scss',
+})
+export class NewsListComponent {
+ readonly paginationService = inject(PaginationService);
+
+ readonly relevanceHelp =
+ 'Zeigt, ob ein Artikel inhaltlich über eine konkrete Person berichtet ' +
+ '(Relevant) oder eine allgemeine Mitteilung ohne Personenbezug ist ' +
+ '(Nicht relevant).';
+
+ @Input({ required: true }) articles: NewsArticleBase[] = [];
+ @Input({ required: true }) displayedColumns: string[] = [];
+ @Input() total = 0;
+ @Input() loading = false;
+ @Input() currentPage = 1;
+ @Input() sortOrder: SortOrder = 'desc';
+ @Input({ required: true }) searchControl!: FormControl;
+ @Input() showFilters = false;
+
+ readonly minYear = NEWS_MIN_YEAR;
+ readonly maxYear = new Date().getFullYear();
+
+ readonly relevanceFilter = new FormControl([], {
+ nonNullable: true,
+ });
+ readonly yearFrom = new FormControl(this.minYear, {
+ nonNullable: true,
+ });
+ readonly yearTo = new FormControl(this.maxYear, {
+ nonNullable: true,
+ });
+
+ @Input() set initialRelevance(values: string[] | null) {
+ this.relevanceFilter.setValue(values ?? [], { emitEvent: false });
+ }
+ @Input() set initialYearFrom(year: number | null) {
+ this.yearFrom.setValue(year ?? this.minYear, { emitEvent: false });
+ }
+ @Input() set initialYearTo(year: number | null) {
+ this.yearTo.setValue(year ?? this.maxYear, { emitEvent: false });
+ }
+
+ @Input() extraColumnId: string | null = null;
+ @Input() extraColumnHeader = '';
+ @Input() extraColumnTemplate: TemplateRef<{
+ $implicit: NewsArticleBase;
+ }> | null = null;
+
+ @Output() sortChange = new EventEmitter();
+ @Output() pageChange = new EventEmitter();
+ @Output() filtersChange = new EventEmitter();
+
+ constructor() {
+ merge(
+ this.relevanceFilter.valueChanges,
+ this.yearFrom.valueChanges,
+ this.yearTo.valueChanges,
+ )
+ .pipe(debounceTime(300), takeUntilDestroyed())
+ .subscribe(() => {
+ this.filtersChange.emit({
+ relevance: this.relevanceFilter.value,
+ yearFrom: this.yearFrom.value,
+ yearTo: this.yearTo.value,
+ });
+ });
+ }
+
+ get isSearching(): boolean {
+ return this.searchControl.value.trim().length > 0;
+ }
+
+ onSortChange(order: SortOrder): void {
+ this.sortChange.emit(order);
+ }
+
+ onPage(event: PageEvent): void {
+ this.pageChange.emit(event);
+ }
+
+ resetFilters(): void {
+ this.relevanceFilter.setValue([]);
+ this.yearFrom.setValue(this.minYear);
+ this.yearTo.setValue(this.maxYear);
+ }
+
+ formatDate(dateStr?: string | null): string {
+ if (!dateStr) {
+ return '-';
+ }
+
+ const parts = dateStr.split('.');
+
+ if (parts.length === 3) {
+ const day = parts[0].trim().padStart(2, '0');
+ const month = parts[1].trim().padStart(2, '0');
+ const year = parts[2].trim();
+ return `${day}.${month}.${year}`;
+ }
+
+ const date = new Date(dateStr);
+
+ if (isNaN(date.getTime())) {
+ return dateStr;
+ }
+
+ return new Intl.DateTimeFormat('de-DE', {
+ day: '2-digit',
+ month: '2-digit',
+ year: 'numeric',
+ }).format(date);
+ }
+
+ articleRange(): string {
+ const relatedCount = this.articles.filter(
+ (article) => article.related,
+ ).length;
+ const matchCount = this.articles.length - relatedCount;
+
+ if (this.total === 0 && relatedCount === 0) {
+ return 'Keine Nachrichten gefunden';
+ }
+
+ const pageSize = this.paginationService.selection;
+ const start = matchCount > 0 ? (this.currentPage - 1) * pageSize + 1 : 0;
+ const end = Math.min(start + matchCount - 1, this.total);
+
+ const base =
+ matchCount > 0
+ ? `Zeige ${start} bis ${end} von ${this.total} Nachrichten`
+ : 'Keine direkten Treffer';
+
+ if (relatedCount > 0) {
+ const suffix =
+ relatedCount === 1
+ ? '1 ähnlicher Vorschlag'
+ : `${relatedCount} ähnliche Vorschläge`;
+ return `${base} · ${suffix}`;
+ }
+
+ return base;
+ }
+}
diff --git a/webapp/src/app/shared/utils/formatters.ts b/webapp/src/app/shared/utils/formatters.ts
new file mode 100644
index 00000000..3131672a
--- /dev/null
+++ b/webapp/src/app/shared/utils/formatters.ts
@@ -0,0 +1,20 @@
+export function formatGermanDate(dateString: string): string {
+ if (!dateString) return '';
+
+ return new Intl.DateTimeFormat('de-DE', {
+ day: 'numeric',
+ month: 'long',
+ year: 'numeric',
+ }).format(new Date(dateString));
+}
+
+export function formatCurrency(amount: number | null | undefined): string {
+ if (amount === null || amount === undefined) return 'N/A';
+
+ return new Intl.NumberFormat('de-DE', {
+ style: 'currency',
+ currency: 'EUR',
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 0,
+ }).format(amount);
+}