Compare commits

..
Author SHA1 Message Date
farajollahi 7e3559432b Merge branch 'dev' into publidher-for-publications
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-20 20:14:33 +02:00
farajollahi cae7e4299b add publisher to publications
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-20 20:01:56 +02:00
90 changed files with 2359 additions and 5591 deletions
@@ -22,13 +22,14 @@ class CompanyConnectionsSearchClient:
self.base_url = (
base_url
or config.settings.elasticsearch_url
or ""
or config.settings.openalex_works_search_base_url
).rstrip("/")
self.api_key = (
api_key
if api_key is not None
else config.settings.elasticsearch_api_key
)
or config.settings.openalex_works_api_key
)
self.openalex_index = openalex_index
self.handelsregister_index = handelsregister_index
self.timeout = timeout
+12 -5
View File
@@ -26,18 +26,22 @@ class Settings(BaseSettings):
auth_disabled: bool = False
auth_standalone: bool = True
auth_secret: str = "change-me-to-a-secure-secret-key"
# OpenAlex works search config
openalex_works_search_base_url: str = "https://project.nes.uni-due.de/elastic"
# IMPORTANT: wildcard * needed to query all work indices
openalex_works_search_index: str = "openalex-works*"
openalex_works_api_key: str = (
"am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
)
openalex_works_search_timeout_seconds: float = 30.0
# OpenAlex public API config
openalex_api_base_url: str = "https://api.openalex.org"
openalex_api_key: Optional[str] = None
openalex_api_timeout_seconds: float = 30.0
# Patent Elasticsearch config
# Patent elasticsearch config
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
patent_elasticsearch_api_key: Optional[str] = None
patent_elasticsearch_api_key: str = ""
# LLM config
@@ -45,8 +49,8 @@ class Settings(BaseSettings):
llm_api_key: Optional[str] = None
llm_model: Optional[str] = None
# Elasticsearch config
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
# elasticsearch config
elasticsearch_url: Optional[str] = None
elasticsearch_api_key: Optional[str] = None
elasticsearch_inse_url: Optional[str] = None
elasticsearch_inse_api_key: Optional[str] = None
@@ -59,6 +63,9 @@ class Settings(BaseSettings):
{"url": "http://localhost:8000", "description": "Local development server"},
]
elasticsearch_inse_url: Optional[str] = None
elasticsearch_inse_api_key: Optional[str] = None
logging_level: str = "DEBUG"
@@ -23,9 +23,9 @@ class FundedPublicationsSearchClient:
timeout: float | None = None,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.elasticsearch_url or "").rstrip("/")
self.base_url = (base_url or config.settings.openalex_works_search_base_url).rstrip("/")
self.index = index or config.settings.openalex_works_search_index
self.api_key = api_key if api_key is not None else config.settings.elasticsearch_api_key
self.api_key = api_key if api_key is not None else config.settings.openalex_works_api_key
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
self.transport = transport
@@ -20,21 +20,13 @@ class InstitutionsSearchClient:
"""
pass
def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
"""Retrieves an institution by its raw OpenAlex institution ID.
Args:
raw_oa_institution_id (str): The raw OpenAlex institution ID to search for.
Raises:
NotFoundException: If no institution is found with the given ID or if the institution data cannot be parsed.
Returns:
Institution: The institution corresponding to the given raw OpenAlex institution ID.
def get_institution_by_id(self, raw_institution_id: str) -> Institution:
"""
Retrieves a single institution by its OpenAlex ID from the local Elasticsearch cluster.
"""
query = {
"match": {
"id": f"https://openalex.org/{raw_oa_institution_id.upper()}",
"id": f"https://openalex.org/{raw_institution_id.upper()}",
}
}
@@ -43,13 +35,13 @@ class InstitutionsSearchClient:
hits = res.get("hits", {}).get("hits", [])
if not hits:
raise NotFoundException(
f"Institution with ID '{raw_oa_institution_id}' not found."
f"Institution with ID '{raw_institution_id}' not found."
)
institution = self._convert_hit_to_institution(hits[0])
if not institution:
raise NotFoundException(
f"Institution with ID '{raw_oa_institution_id}' could not be parsed."
f"Institution with ID '{raw_institution_id}' could not be parsed."
)
return institution
@@ -216,39 +208,37 @@ class InstitutionsSearchClient:
if query_text:
stripped = query_text.strip()
must.append(
{
"bool": {
"should": [
{
"wildcard": {
"display_name.keyword": {
"value": f"*{stripped}*",
"boost": 2,
}
}
},
{
"wildcard": {
"display_name_alternatives.keyword": {
"value": f"*{stripped}*",
"boost": 2,
}
}
},
{
"wildcard": {
"display_name_acronyms.keyword": {
"value": f"*{stripped.upper()}*",
"boost": 10,
}
}
},
],
"minimum_should_match": 1,
must.append({
"bool": {
"should": [
{
"wildcard": {
"display_name.keyword": {
"value": f"*{stripped}*",
"boost": 2
}
}
},
{
"wildcard": {
"display_name_alternatives.keyword": {
"value": f"*{stripped}*",
"boost": 2
}
}
},
{
"wildcard": {
"display_name_acronyms.keyword": {
"value": f"*{stripped.upper()}*",
"boost": 10
}
}
}
}
)
],
"minimum_should_match": 1
}
})
filter_queries = []
@@ -288,41 +278,35 @@ class InstitutionsSearchClient:
return [Institution.from_dict(hit["_source"]) for hit in hits]
def get_institution_aliases_by_oa_institution_id(
self, raw_oa_institution_id: str
) -> List[str]:
def get_institution_aliases_by_id(self, raw_institution_id: str) -> List[str]:
"""Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases.
Args:
raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve aliases.
raw_institution_id (str): The raw institution ID for which to retrieve aliases.
Returns:
List[str]: A list of aliases for the given institution ID.
"""
institution = self.get_institution_by_id(raw_oa_institution_id)
institution = self.get_institution_by_id(raw_institution_id)
aliases = list(
self.augment_aliases(set(institution.display_name_alternatives or []))
| self.get_predefined_institution_aliases(raw_oa_institution_id)
| self.get_predefined_institution_aliases(raw_institution_id)
)
logger.debug(
"Retrieved aliases for institution_id=%s: %s",
raw_oa_institution_id,
aliases,
"Retrieved aliases for institution_id=%s: %s", raw_institution_id, aliases
)
return aliases
def get_predefined_institution_aliases(
self, raw_oa_institution_id: str
) -> Set[str]:
def get_predefined_institution_aliases(self, raw_institution_id: str) -> Set[str]:
"""Get predefined aliases for a given institution ID.
Args:
raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve predefined aliases.
raw_institution_id (str): The raw institution ID for which to retrieve predefined aliases.
Returns:
Set[str]: A set of predefined aliases for the given institution ID.
"""
raw_oa_institution_id = raw_oa_institution_id.upper()
raw_institution_id = raw_institution_id.upper()
predefined_aliases = {
"I62318514": [
"universität duisburg-essen",
@@ -333,9 +317,7 @@ class InstitutionsSearchClient:
],
}
return self.augment_aliases(
set(predefined_aliases.get(raw_oa_institution_id, []))
)
return self.augment_aliases(set(predefined_aliases.get(raw_institution_id, [])))
def augment_aliases(self, aliases: Set[str]) -> Set[str]:
"""Augment a set of aliases by applying the augment_alias function to each alias.
@@ -425,80 +407,3 @@ class InstitutionsSearchClient:
"Failed to validate institution hit ID %s: %s", hit.get("_id"), e
)
return None
def get_cordis_eu_organisation_ids_by_oa_institution_id(
self, raw_oa_institution_id: str
) -> Optional[List[str]]:
"""Retrieves the corresponding EU organisation IDs for a given OpenAlex institution ID by searching for institution aliases and matching them against the Cordis EU organisations indices.
Args:
raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve the corresponding EU organisation IDs.
Returns:
Optional[List[str]]: A list of corresponding EU organisation IDs or None if the search fails.
"""
institution_aliases = set(
self.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id=raw_oa_institution_id
)
)
body = {
"size": 0,
"query": {
"bool": {
"filter": [
{
"terms": {
"name.keyword": [
institution_alias.upper()
for institution_alias in institution_aliases
]
}
}
]
}
},
"aggs": {
"organisation_ids": {
"terms": {"field": "organisationID", "size": 10000}
}
},
}
logger.debug(
"Searching for EU organisation IDs for raw_oa_institution_id=%s with aliases=%s and query: %s",
raw_oa_institution_id,
institution_aliases,
body,
)
try:
# IMPORTANT: The indices are named organizations and not organisations. + 15 Minutes debugging why the search returns 0 results
response = elasticsearch.search(
index="cordis_eu_*_organizations", body=body, cluster="inse"
)
except Exception as e:
logger.exception("Error while searching for EU organisation IDs: %s", e)
return None
logger.debug(
"Received response for EU organisation ID search for raw_oa_institution_id=%s: %s",
raw_oa_institution_id,
response,
)
aggregations = response.get("aggregations", {})
organisation_ids_buckets = aggregations.get("organisation_ids", {}).get(
"buckets", []
)
organisation_ids = [bucket.get("key") for bucket in organisation_ids_buckets]
logger.debug(
"Extracted EU organisation IDs for raw_oa_institution_id=%s: %s",
raw_oa_institution_id,
organisation_ids,
)
return organisation_ids
@@ -1,19 +1,16 @@
import json
import logging
from typing import Any, Dict, List, Optional, Tuple
import httpx
from inse.model import ESCluster, ESIndex
from .. import config
logger = logging.getLogger(__name__)
def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
def _cluster_credentials(cluster: str) -> Tuple[str, str]:
"""Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration.
Args:
cluster (ElasticsearchCluster): The cluster for which to retrieve credentials. Allowed values are "nes" and "inse".
cluster (str): The cluster for which to retrieve credentials. Allowed values are "nes" and "inse".
Raises:
ValueError: If the cluster is unknown or the credentials are not set in the configuration.
@@ -22,7 +19,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
"""
if cluster == ESCluster.NES:
if cluster == "nes":
if (
not config.settings.elasticsearch_url
or not config.settings.elasticsearch_api_key
@@ -31,7 +28,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
"Elasticsearch URL and API key must be set in the configuration for cluster 'nes'"
)
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
elif cluster == ESCluster.INSE:
elif cluster == "inse":
if (
not config.settings.elasticsearch_inse_url
or not config.settings.elasticsearch_inse_api_key
@@ -48,40 +45,10 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
raise ValueError(f"Unknown cluster: {cluster!r} (allowed: 'nes', 'inse')")
def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
"""Determines the Elasticsearch cluster to use based on the specified index.
Args:
index (ESIndex): The Elasticsearch index for which to determine the cluster. Allowed values are defined in the ESIndex enum.
Raises:
ValueError: If the index is unknown.
Returns:
ESCluster: The Elasticsearch cluster to use for the specified index.
"""
if index in {
ESIndex.OPENALEX_WORKS,
ESIndex.OPENALEX_AUTHORS,
ESIndex.OPENALEX_INSTITUTIONS,
ESIndex.OPENALEX_PUBLICATIONS,
}:
return ESCluster.NES
elif index in {
ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
ESIndex.PROJECTS_BUND_V1,
ESIndex.PROJECTS_DFG_ALL,
}:
return ESCluster.INSE
else:
return None
def search(
index: ESIndex | List[ESIndex],
index: str,
query_field: Optional[str] = None,
query_value: Optional[str] = None,
query: Optional[Dict] = None,
source: Optional[List] = None,
size: Optional[int] = None,
@@ -89,13 +56,14 @@ def search(
sort: Optional[List] = None,
body: Optional[Dict] = None,
track_total_hits=False,
highlight: Optional[Dict] = None,
cluster: ESCluster = ESCluster.NES,
cluster: str = "nes",
) -> Dict[str, Any]:
"""Searches the specified Elasticsearch index using either a simple query string or a full query body.
Args:
index (ElasticsearchIndex): The Elasticsearch index to search.
index (str): The name of the Elasticsearch index to search.
query_field (Optional[str], optional): The field to search in. Defaults to None.
query_value (Optional[str], optional): The value to search for. Defaults to None.
query (Optional[Dict], optional): The full query body. Defaults to None.
source (Optional[List], optional): The fields to include in the response. Defaults to None.
size (Optional[int], optional): The maximum number of results to return. Defaults to None.
@@ -103,41 +71,22 @@ def search(
sort (Optional[List], optional): The fields to sort by. Defaults to None.
body (Optional[Dict], optional): The full query body. Defaults to None.
track_total_hits (bool, optional): Whether to track the total number of hits. Defaults to False.
cluster (ElasticsearchCluster, optional): The Elasticsearch cluster to search. Defaults to ElasticsearchCluster.NES.
cluster (str, optional): The Elasticsearch cluster to search. Defaults to "nes".
Returns:
Dict[str, Any]: The search results.
"""
clusters = set()
if isinstance(index, list):
for idx in index:
cluster_for_index = _index_to_cluster(idx)
if cluster_for_index is not None:
clusters.add(cluster_for_index)
else:
cluster_for_index = _index_to_cluster(index)
if cluster_for_index is not None:
clusters.add(cluster_for_index)
if len(clusters) > 1:
raise ValueError(
f"All indices in the search request must belong to the same cluster, but found clusters: {clusters}"
)
elif len(clusters) == 1:
cluster = clusters.pop()
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
payload: Dict[str, Any] = {}
payload: Dict[str, Any]
if body is not None:
payload = body
else:
if query is not None:
payload["query"] = query
elif query is not None:
payload = {"query": query}
if source is not None:
payload["_source"] = source
if size is not None:
@@ -148,35 +97,29 @@ def search(
payload["sort"] = sort
if track_total_hits:
payload["track_total_hits"] = True
if highlight is not None:
payload["highlight"] = highlight
if len(payload) == 0:
raise ValueError(
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided"
)
else:
payload = {
"query": {
"query_string": {"default_field": query_field, "query": query_value}
}
}
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)}"
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} with payload: {payload}"
)
if isinstance(index, list):
index_str = ",".join(index)
else:
index_str = index
response = client.post(
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
f"{elasticsearch_url}/{index}/_search", json=payload, headers=headers
)
response.raise_for_status()
return response.json()
def get(
index: ESIndex,
index: str,
doc_id: str,
source: Optional[list] = None,
cluster: ESCluster = ESCluster.NES,
cluster: str = "nes",
) -> dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
-3
View File
@@ -26,8 +26,6 @@ from inse.topics.service import router as topics_service_router
from inse.works.service import router as works_service_router
from inse.persons.service import router as persons_service_router
from inse.funders.service import router as funders_service_router
from inse.news.service import router as news_service_router
from inse.projects.router import router as projects_router
from inse.patents.service import router as patents_service_router
from inse.institutions.router import router as institutions_router
@@ -54,7 +52,6 @@ app.include_router(topics_service_router)
app.include_router(works_service_router)
app.include_router(persons_service_router)
app.include_router(funders_service_router)
app.include_router(news_service_router)
app.include_router(company_connections_router)
app.include_router(service_router)
app.include_router(account_router)
+3 -27
View File
@@ -1,12 +1,9 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines the model classes returned from
our api using pydantic.
This module defines the model classes returned from
our api using pydantic.
"""
from enum import StrEnum
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field
@@ -16,49 +13,28 @@ from typing import Generic
from typing import Optional
T = TypeVar("T", bound=BaseModel)
T = TypeVar('T', bound=BaseModel)
class Entity(BaseModel):
id: int = Field(description="The id of the entity.")
class Item(Entity):
model_config = ConfigDict(from_attributes=True)
name: str = Field(description="The name of the item.")
description: str = Field(description="The description of the item.")
class ItemCreate(BaseModel):
name: str = Field(description="The name of the item.")
description: str = Field(description="The description of the item.")
class Page(BaseModel, Generic[T]):
elements: List[T] = Field(default=[], description="The elements of the page.")
offset: int = Field(default=0, description="The page offset in elements.")
total: int = Field(default=0, description="The total number of elements.")
size: int = Field(default=20, description="The page size in elements.")
class ItemPage(Page[Item]):
pass
class ESCluster(StrEnum):
NES = "nes"
INSE = "inse"
class ESIndex(StrEnum):
OPENALEX_WORKS = "openalex-works"
OPENALEX_AUTHORS = "openalex-authors"
OPENALEX_INSTITUTIONS = "openalex-institutions"
OPENALEX_PUBLICATIONS = "openalex-publications"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
PROJECTS_BUND_V1 = "projects_bund_v1"
PROJECTS_DFG_ALL = "projects_dfg_all"
-274
View File
@@ -1,274 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for the "aktuell" news index on the INSE cluster.
"""
import logging
from fastapi import HTTPException
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
from ..integrations import elasticsearch
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
logger = logging.getLogger(__name__)
def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPage:
offset = (page - 1) * page_size
response = _run_search(
query={"match_all": {}},
source=["date", "maintitle", "author", "url"],
size=page_size,
offset=offset,
sort=[{"date_full": sort_order}],
)
return _build_page(response, page, page_size)
def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
offset = (page - 1) * page_size
highlight = {
"fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}},
"pre_tags": ["<em>"],
"post_tags": ["</em>"],
"encoder": "html",
}
response = _run_search(
query={"match": {"full_content": query_text}},
source=["date", "maintitle", "author", "url"],
size=page_size,
offset=offset,
sort=None,
highlight=highlight,
)
return _build_page(response, page, page_size)
def get_news_by_author(
author_id: str,
page: int = 1,
page_size: int = 10,
sort_order: str = "desc",
query_text: str | None = None,
) -> NewsPage:
author_name = get_author_name_by_id(author_id)
if not author_name:
return _empty_page(page, page_size)
news_ids = _find_news_ids_for_author(author_name)
if not news_ids:
return _empty_page(page, page_size)
es_query = {"bool": {"filter": [{"ids": {"values": news_ids}}]}}
if query_text:
es_query["bool"]["must"] = [
{"multi_match": {"query": query_text, "fields": ["maintitle", "author"]}}
]
offset = (page - 1) * page_size
response = _run_search(
query=es_query,
source=["date", "maintitle", "author", "url"],
size=page_size,
offset=offset,
sort=[{"date_full": sort_order}],
)
return _build_page(response, page, page_size)
def _find_news_ids_for_author(author_name: str) -> list:
try:
response = elasticsearch.search(
index="aktuell_postproc",
query={"term": {"authors.keyword": author_name}},
source=["news_id"],
size=1000,
cluster="inse",
)
except Exception:
logger.exception(f"Postproc-search: Finding news IDs for author '{author_name}' failed.")
return []
news_ids = []
for hit in response.get("hits", {}).get("hits", []):
news_id = hit.get("_source", {}).get("news_id")
if news_id:
news_ids.append(news_id)
return news_ids
def _empty_page(page: int = 1, page_size: int = 0) -> NewsPage:
return NewsPage(total=0, page=page, page_size=page_size, results=[])
def get_news_by_id(news_id: str) -> NewsArticleDetail:
try:
response = elasticsearch.get(
index="aktuell",
doc_id=news_id,
source=["date", "maintitle", "author", "url", "full_content"],
cluster="inse",
)
except Exception as exc:
logger.exception("Abruf des News-Artikels fehlgeschlagen.")
raise HTTPException(
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
detail="Etwas ist schiefgelaufen.",
) from exc
source = response.get("_source", {})
relevant, authors = _get_postproc_labels(news_id)
return NewsArticleDetail(
id=response.get("_id"),
date=source.get("date"),
maintitle=source.get("maintitle"),
author=source.get("author"),
url=source.get("url"),
full_content=source.get("full_content"),
relevant=relevant,
authors=_build_mentioned_persons(authors),
)
def _build_mentioned_persons(author_names: list) -> list:
ude_persons = []
other_persons = []
for name in author_names:
match = find_ude_author_by_name(name)
if match:
ude_persons.append(
MentionedPerson(name=name, is_ude=True, person_id=match["id"])
)
else:
other_persons.append(MentionedPerson(name=name))
return ude_persons + other_persons
def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]:
try:
response = elasticsearch.search(
index="aktuell_postproc",
query={"term": {"news_id.keyword": news_id}},
source=["relevant", "authors"],
size=1,
cluster="inse",
)
except Exception:
logger.exception(f"Postproc-Lookup for {news_id} failed.")
return None, []
hits = response.get("hits", {}).get("hits", [])
if not hits:
return None, []
postproc_source = hits[0].get("_source", {})
relevant = bool(postproc_source.get("relevant", 0))
authors = postproc_source.get("authors") or []
return relevant, authors
def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
try:
return elasticsearch.search(
index="aktuell",
query=query,
source=source,
size=size,
offset=offset,
sort=sort,
track_total_hits=True,
highlight=highlight,
cluster="inse",
)
except Exception as exc:
logger.exception("Elasticsearch-Anfrage an Index 'aktuell' fehlgeschlagen.")
raise HTTPException(
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
detail="Etwas ist schiefgelaufen.",
) from exc
def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
hits_section = response.get("hits", {})
total = hits_section.get("total", {}).get("value", 0)
hits = hits_section.get("hits", [])
news_ids = []
for hit in hits:
news_id = hit.get("_id")
if news_id:
news_ids.append(news_id)
relevance_map = _get_relevance_map(news_ids)
articles = []
for hit in hits:
article = _parse_hit(hit)
article.relevant = relevance_map.get(article.id)
articles.append(article)
return NewsPage(
total=total,
page=page,
page_size=page_size,
results=articles,
)
def _get_relevance_map(news_ids: list) -> dict:
if not news_ids:
return {}
try:
response = elasticsearch.search(
index="aktuell_postproc",
query={"terms": {"news_id.keyword": news_ids}},
source=["news_id", "relevant"],
size=len(news_ids),
cluster="inse",
)
except Exception:
logger.exception("Postproc-Relevanz-Lookup fehlgeschlagen.")
return {}
relevance_map = {}
for hit in response.get("hits", {}).get("hits", []):
postproc_source = hit.get("_source", {})
news_id = postproc_source.get("news_id")
if news_id is not None:
relevance_map[news_id] = bool(postproc_source.get("relevant", 0))
return relevance_map
def _parse_hit(hit: dict) -> NewsArticle:
source = hit.get("_source", {})
fragments = hit.get("highlight", {}).get("full_content")
snippet = fragments[0] if fragments else None
return NewsArticle(
id=hit.get("_id"),
date=source.get("date"),
maintitle=source.get("maintitle"),
author=source.get("author"),
url=source.get("url"),
snippet=snippet,
)
-35
View File
@@ -1,35 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import List, Optional
from pydantic import BaseModel
class NewsArticle(BaseModel):
id: str
date: Optional[str] = None
maintitle: Optional[str] = None
author: Optional[str] = None
url: Optional[str] = None
relevant: Optional[bool] = None
snippet: Optional[str] = None
class MentionedPerson(BaseModel):
name: str
is_ude: bool = False
person_id: Optional[str] = None
class NewsArticleDetail(NewsArticle):
full_content: Optional[str] = None
relevant: Optional[bool] = None
authors: List[MentionedPerson] = []
class NewsPage(BaseModel):
total: int
page: int
page_size: int
results: List[NewsArticle]
-105
View File
@@ -1,105 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for the "aktuell" news index.
"""
from typing import Annotated
from fastapi import APIRouter
from fastapi import Path
from fastapi import Query
from inse.tags import Tags
from . import logic
from .model import NewsArticleDetail, NewsPage
router = APIRouter(prefix="/api/news", tags=[Tags.NEWS])
@router.get(
"",
operation_id="listNews",
response_model=NewsPage,
response_model_exclude_none=True,
summary="Returns a page of news articles, newest first.",
tags=[Tags.NEWS],
)
def list_news(
page: Annotated[
int, Query(description="Page number (1-based).", ge=1)
] = 1,
page_size: Annotated[
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
] = 10,
sort_order: Annotated[
str, Query(alias="sortOrder", description="Sort order: 'desc' (newest first) or 'asc' (oldest first).", pattern="^(asc|desc)$")
] = "desc",
):
return logic.get_news_page(page, page_size, sort_order)
@router.get(
"/search",
operation_id="searchNews",
response_model=NewsPage,
response_model_exclude_none=True,
summary="Searches news articles by full text (full_content).",
tags=[Tags.NEWS],
)
def search_news(
query: Annotated[
str, Query(description="Search term, matched against the full text (full_content).", min_length=1)
],
page: Annotated[
int, Query(description="Page number (1-based).", ge=1)
] = 1,
page_size: Annotated[
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
] = 10,
):
return logic.search_news(query, page, page_size)
@router.get(
"/by-author",
operation_id="getNewsByAuthor",
response_model=NewsPage,
response_model_exclude_none=True,
summary="Returns news articles in which the given person is mentioned.",
tags=[Tags.NEWS],
)
def get_news_by_author(
author_id: Annotated[
str, Query(alias="authorId", description="OpenAlex author id, e.g. A5034365278.")
],
page: Annotated[
int, Query(description="Page number (1-based).", ge=1)
] = 1,
page_size: Annotated[
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
] = 10,
sort_order: Annotated[
str, Query(alias="sortOrder", description="Sort order: 'desc' (newest first) or 'asc' (oldest first).", pattern="^(asc|desc)$")
] = "desc",
query: Annotated[
str | None, Query(description="Optional search term, matched against title/author.")
] = None,
):
return logic.get_news_by_author(author_id, page, page_size, sort_order, query)
@router.get(
"/{news_id}",
operation_id="getNewsById",
response_model=NewsArticleDetail,
response_model_exclude_none=True,
summary="Returns a single news article including its full content.",
tags=[Tags.NEWS],
)
def get_news_by_id(
news_id: Annotated[
str, Path(description="The unique id of the news article (Elasticsearch _id).")
],
):
return logic.get_news_by_id(news_id)
+12 -73
View File
@@ -13,8 +13,6 @@ from elasticsearch import ApiError, NotFoundError
import hashlib
import httpx
from fastapi import HTTPException
from inse.model import ESIndex
from .. import config
from .. import util
from ..integrations import llm
@@ -30,63 +28,8 @@ from inse.persons.model import (
PersonSearchRequest,
CareerMetrics,
)
logger = logging.getLogger(__name__)
INDEX_NAME = "openalex-authors"
UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen
def find_ude_author_by_name(display_name: str) -> Optional[dict]:
query = {
"_source": ["display_name"],
"query": {
"bool": {
"must": [
{
"match_phrase": {
"display_name": display_name
}
},
{
"nested": {
"path": "affiliations",
"query": {
"term": {
"affiliations.institution.id": UDE_INSTITUTION_ID
}
},
}
},
]
}
},
"size": 10,
}
try:
data = elasticsearch.search(index=INDEX_NAME, body=query)
except Exception:
logger.exception(f"UDE-Lookup für '{display_name}' fehlgeschlagen.")
return None
hits = data.get("hits", {}).get("hits", [])
display_name = display_name.strip().lower()
exact_matches = []
for hit in hits:
hit_display_name = hit.get("_source", {}).get("display_name", "")
if hit_display_name.strip().lower() == display_name:
exact_matches.append(hit)
if not exact_matches:
return None
hit = exact_matches[0]
return {
"id": hit.get("_id"),
"display_name": hit.get("_source", {}).get("display_name"),
}
def get_author_name_by_id(author_id: str) -> Optional[str]:
@@ -112,26 +55,20 @@ def get_author_name_by_id(author_id: str) -> Optional[str]:
def search_persons(
author_id: Optional[str] = None,
query: Optional[str] = None,
include: Optional[set[str]] = None,
) -> AuthorsListResponse:
if author_id:
query_ = {
"query_string": {
"default_field": "_id",
"query": author_id,
}
}
query_field = "_id"
query_value = author_id
elif query:
query_ = {
"query_string": {
"default_field": "display_name",
"query": query,
}
}
query_field = "display_name"
query_value = query
else:
return AuthorsListResponse(results=[], meta=Meta(count=0))
data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
data = elasticsearch.search(
index="openalex-authors", query_field=query_field, query_value=query_value
)
authors = []
for hit in data.get("hits", {}).get("hits", []):
@@ -284,7 +221,9 @@ def _get_publication_years_for_author(author_id: str) -> list[int]:
)
buckets = (
response.get("aggregations", {}).get("publication_years", {}).get("buckets", [])
response.get("aggregations", {})
.get("publication_years", {})
.get("buckets", [])
)
publication_years: list[int] = []
@@ -298,7 +237,6 @@ def _get_publication_years_for_author(author_id: str) -> list[int]:
return publication_years
def _classify_career_stage(active_years: int) -> str:
if active_years <= 0:
return "unknown"
@@ -461,6 +399,7 @@ def get_person_by_id(
return CustomAuthorsListResponse(results=[custom_author])
def search_persons_by_name(
author_name: str,
limit: Optional[int] = 10,
+1 -1
View File
@@ -53,7 +53,7 @@ def search_persons(
if include
else None
)
return logic.search_persons(author_id, query)
return logic.search_persons(author_id, query, include_set)
@router.get(
+1 -90
View File
@@ -8,7 +8,6 @@ from pydantic import BaseModel, Field, field_validator
from inse.models.bund_project import BundProject
from inse.models.eu_project import EuProject
from inse.models.cordis_eu_project import CordisEuProject
from inse.model import ESIndex
class ProjectType(StrEnum):
@@ -16,17 +15,6 @@ class ProjectType(StrEnum):
EU = "eu"
DFG = "dfg"
def to_es_index(self) -> ESIndex:
mapping = {
self.BUND: ESIndex.PROJECTS_BUND_V1,
self.EU: ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
self.DFG: ESIndex.PROJECTS_DFG_ALL,
}
index = mapping.get(self)
if index is None:
raise ValueError(f"Unsupported project type: {self}")
return index
class ProjectsSortBy(StrEnum):
TITLE = "title"
@@ -34,24 +22,6 @@ class ProjectsSortBy(StrEnum):
FUNDING_END = "funding_end"
FUNDING_AMOUNT = "funding_amount"
def to_cordis_eu_project_sort_field(self) -> str:
mapping = {
self.TITLE: "title.keyword",
self.FUNDING_START: "startDate",
self.FUNDING_END: "endDate",
self.FUNDING_AMOUNT: "ecMaxContribution",
}
return mapping.get(self, "title.keyword")
def to_bund_project_sort_field(self) -> str:
mapping = {
self.TITLE: "Thema.keyword",
self.FUNDING_START: "funding_start",
self.FUNDING_END: "funding_end",
self.FUNDING_AMOUNT: "Fördersumme",
}
return mapping.get(self, "Thema.keyword")
class SortDirection(StrEnum):
ASC = "asc"
@@ -172,9 +142,6 @@ class FundingProject(BaseModel):
)
id: str = Field(description="The unique identifier of the project.")
title: Optional[str] = Field(default=None, description="The title of the project.")
acronym: Optional[str] = Field(
default=None, description="The acronym of the project (if available)."
)
start_date: Optional[date] = Field(
default=None, description="The funding start date of the project."
)
@@ -217,7 +184,7 @@ class FundingProject(BaseModel):
title=source.get("title"),
start_date=source.get("startDate"),
end_date=source.get("endDate"),
funding_amount=source.get("ecMaxContribution"),
funding_amount=source.get("ecMacContribution"),
)
@classmethod
@@ -251,7 +218,6 @@ class FundingProject(BaseModel):
title=source.get("title"),
start_date=source.get("funding_start"),
end_date=source.get("funding_end"),
acronym=source.get("acronym"),
)
@@ -259,58 +225,3 @@ class FundingProjectPage(Page):
elements: List[FundingProject] = Field(
default_factory=list, description="The funding projects on this page."
)
class EuOrganizationShort(BaseModel):
project_id: str = Field(description="The unique identifier of the project.")
organization_id: str = Field(
description="The unique identifier of the organization."
)
ec_contribution: Optional[float] = Field(
default=None,
description="The EC contribution amount for the organization in the project.",
)
class EuProjectShort(BaseModel):
id: str = Field(description="The unique identifier of the EU project.")
title: Optional[str] = Field(
default=None, description="The title of the EU project."
)
start_date: Optional[date] = Field(
default=None, description="The funding start date of the EU project."
)
end_date: Optional[date] = Field(
default=None, description="The funding end date of the EU project."
)
acronym: Optional[str] = Field(
default=None, description="The acronym of the EU project."
)
class EuOrganizationProjectSummary(BaseModel):
organization_id: str = Field(
description="The unique identifier of the organization."
)
project_id: str = Field(description="The unique identifier of the project.")
title: Optional[str] = Field(default=None, description="The title of the project.")
start_date: Optional[date] = Field(
default=None, description="The funding start date of the project."
)
end_date: Optional[date] = Field(
default=None, description="The funding end date of the project."
)
acronym: Optional[str] = Field(
default=None, description="The acronym of the project."
)
ec_contribution: Optional[float] = Field(
default=None,
description="The EC contribution amount for the organization in the project.",
)
class EuOrganizationProjectSummaryPage(Page):
elements: List[EuOrganizationProjectSummary] = Field(
default_factory=list,
description="The organization project summaries on this page.",
)
File diff suppressed because it is too large Load Diff
+64 -37
View File
@@ -8,7 +8,6 @@ from inse.projects.model import (
BundProjectPage,
CordisEuProjectPage,
DfgProjectPage,
EuOrganizationProjectSummaryPage,
FundingProjectPage,
InstitutionFunderSummary,
ProjectType,
@@ -20,7 +19,12 @@ from inse.models.dfg_project_details import DfgProjectDetails
from inse.models.bund_project_details import BundProjectDetails
from inse.tags import Tags
from inse.projects import service as projects_service
from inse.projects.projects_search_client import (
BundProjectsSearchClient,
CompleteProjectsSearchClient,
DfgProjectsSearchClient,
EuProjectsSearchClient,
)
from inse.institutions.institutions_search_client import (
InstitutionsSearchClient,
)
@@ -31,29 +35,24 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
@router.get(
"/author/{raw_oa_author_id}/eu",
summary="Get EU projects for an author.",
description="Returns a list of EU projects associated with the specified author ID.",
operation_id="getEuProjectsForAuthor",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": CordisEuProjectPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Author not found"},
},
response_model_by_alias=False,
)
def get_eu_projects_for_author(
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(
raw_oa_author_id=raw_oa_author_id,
)
@lru_cache
def get_bund_search_client() -> BundProjectsSearchClient:
return BundProjectsSearchClient()
@lru_cache
def get_eu_search_client() -> EuProjectsSearchClient:
return EuProjectsSearchClient()
@lru_cache
def get_dfg_search_client() -> DfgProjectsSearchClient:
return DfgProjectsSearchClient()
@lru_cache
def get_complete_projects_search_client() -> CompleteProjectsSearchClient:
return CompleteProjectsSearchClient()
@router.post(
@@ -71,6 +70,9 @@ def get_eu_projects_for_author(
response_model_by_alias=False,
)
async def search_bund_projects(
bund_search_client: Annotated[
BundProjectsSearchClient, Depends(get_bund_search_client)
],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -79,7 +81,8 @@ 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(
bund_search_client=bund_search_client,
institutions_search_client=institutions_search_client,
filtering_properties=filtering_properties,
)
@@ -99,11 +102,15 @@ async def search_bund_projects(
},
response_model_by_alias=False,
)
def get_single_dfg_project(
async def get_single_dfg_project(
dfg_search_client: Annotated[
DfgProjectsSearchClient, Depends(get_dfg_search_client)
],
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(
dfg_search_client=dfg_search_client,
project_id=id,
)
@@ -122,11 +129,15 @@ def get_single_dfg_project(
},
response_model_by_alias=False,
)
def get_single_bund_project(
async def get_single_bund_project(
bund_search_client: Annotated[
BundProjectsSearchClient, Depends(get_bund_search_client)
],
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(
bund_search_client=bund_search_client,
project_id=id,
)
@@ -145,7 +156,10 @@ 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(
bund_search_client: Annotated[
BundProjectsSearchClient, Depends(get_bund_search_client)
],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -153,7 +167,8 @@ 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(
bund_search_client=bund_search_client,
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
)
@@ -167,13 +182,14 @@ def get_institution_bund_projects_funding_over_time(
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": EuOrganizationProjectSummaryPage,
"model": CordisEuProjectPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
},
response_model_by_alias=False,
)
async def search_cordis_eu_projects(
eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -181,8 +197,9 @@ async def search_cordis_eu_projects(
ProjectsFilteringProperties,
Body(description="The filtering properties for the projects search."),
],
) -> EuOrganizationProjectSummaryPage:
return projects_service.search_cordis_eu_projects(
) -> CordisEuProjectPage:
return await projects_service.search_cordis_eu_projects(
eu_search_client=eu_search_client,
institutions_search_client=institutions_search_client,
projects_filtering_properties=projects_filtering_properties,
)
@@ -203,6 +220,7 @@ async def search_cordis_eu_projects(
response_model_by_alias=False,
)
async def get_institution_cordis_eu_projects_funding_over_time(
eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -211,6 +229,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
],
) -> InstitutionFunderSummary:
return await projects_service.get_institution_cordis_eu_projects_funding_over_time(
eu_search_client=eu_search_client,
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
)
@@ -231,6 +250,9 @@ async def get_institution_cordis_eu_projects_funding_over_time(
response_model_by_alias=False,
)
async def get_dfg_projects(
dfg_search_client: Annotated[
DfgProjectsSearchClient, Depends(get_dfg_search_client)
],
author_id: Annotated[str, Query(description="The author ID to filter by.")],
topic: Annotated[
Optional[str], Query(description="The topic to filter by.")
@@ -252,6 +274,7 @@ async def get_dfg_projects(
sort_direction,
)
return await projects_service.get_dfg_projects_by_author_id(
dfg_search_client=dfg_search_client,
author_id=author_id,
topic=topic,
page=page,
@@ -274,7 +297,10 @@ async def get_dfg_projects(
},
response_model_by_alias=False,
)
def search_projects(
async def search_projects(
complete_projects_search_client: Annotated[
CompleteProjectsSearchClient, Depends(get_complete_projects_search_client)
],
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 +319,8 @@ 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_projects(
projects_search_client=complete_projects_search_client,
page=page,
size=size,
selected_project_types=selected_project_types,
+124 -96
View File
@@ -2,15 +2,17 @@ import datetime
import logging
from typing import Any, Dict, List, Optional, Set
from inse.projects import projects_search_client
from inse.projects.projects_search_client import (
get_eu_organization_project_contributions,
BundProjectsSearchClient,
CompleteProjectsSearchClient,
DfgProjectsSearchClient,
EuProjectsSearchClient,
)
from inse.projects.model import (
BundProjectPage,
CordisEuProjectPage,
DfgProjectPage,
EuOrganizationProjectSummaryPage,
EuProjectPage,
FundingProjectPage,
InstitutionFunderSummary,
ProjectType,
@@ -25,13 +27,12 @@ from inse.institutions.institutions_search_client import (
)
from inse.exceptions import NotFoundException
from inse.persons.logic import get_author_name_by_id
from inse.works.logic import get_publication_dois_of_author
logger = logging.getLogger(__name__)
def search_all_projects(
async def search_projects(
projects_search_client: CompleteProjectsSearchClient,
page: int,
size: int,
sort_by: ProjectsSortBy,
@@ -39,20 +40,18 @@ def search_all_projects(
selected_project_types: Optional[Set[ProjectType]] = None,
title: Optional[str] = None,
) -> FundingProjectPage:
return projects_search_client.search_all_projects(
projects_filtering_properties=ProjectsFilteringProperties(
project_type=ProjectType.EU, # placeholder, shall be ignored in search_all_projects
page=page,
size=size,
sort_by=sort_by,
sort_direction=sort_direction,
query=title,
),
return await projects_search_client.search_projects(
page=page,
size=size,
selected_project_types=selected_project_types,
title=title,
sort_by=sort_by,
sort_direction=sort_direction,
)
def search_bund_projects(
async def search_bund_projects(
bund_search_client: BundProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
filtering_properties: ProjectsFilteringProperties,
) -> BundProjectPage:
@@ -61,17 +60,15 @@ def search_bund_projects(
f"Invalid project type: {filtering_properties.project_type}. Expected 'bund'."
)
logger.debug(
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(
bund_search_client=bund_search_client,
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(
bund_search_client: BundProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
filtering_properties: ProjectsFilteringProperties,
) -> BundProjectPage:
@@ -81,41 +78,46 @@ def get_bund_projects_by_institution_id(
logger.info(
f"Fetching bund projects for institution_id={filtering_properties.raw_oa_institution_id}, page={filtering_properties.page}, size={filtering_properties.size}"
)
institution_aliases = (
institutions_search_client.get_institution_aliases_by_oa_institution_id(
filtering_properties.raw_oa_institution_id
)
institution_aliases = institutions_search_client.get_institution_aliases_by_id(
filtering_properties.raw_oa_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}"
f"Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}"
)
response = projects_search_client.search_bund_projects(
response = await bund_search_client.search_bund_projects(
page=filtering_properties.page,
size=filtering_properties.size,
institution_names=institution_aliases,
filter_properties=filtering_properties,
topic=filtering_properties.query,
sort_by=filtering_properties.sort_by,
sort_direction=filtering_properties.sort_direction,
)
logger.debug(f"get_bund_projects_by_institution_id response: {response}")
return response
def search_cordis_eu_projects(
async def search_cordis_eu_projects(
eu_search_client: EuProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
) -> CordisEuProjectPage:
if projects_filtering_properties.project_type != "eu":
raise ValueError(
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(
eu_search_client=eu_search_client,
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(
eu_search_client: EuProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
) -> CordisEuProjectPage:
if not projects_filtering_properties.raw_oa_institution_id:
raise ValueError(
"raw_oa_institution_id must be provided to fetch CORDIS EU projects by institution ID"
@@ -124,26 +126,81 @@ def get_cordis_eu_projects_by_institution_id(
logger.info(
f"Fetching CORDIS EU projects for institution_id={projects_filtering_properties.raw_oa_institution_id}, page={projects_filtering_properties.page}, size={projects_filtering_properties.size}"
)
institution_aliases = (
institutions_search_client.get_institution_aliases_by_oa_institution_id(
projects_filtering_properties.raw_oa_institution_id
)
institution_aliases = institutions_search_client.get_institution_aliases_by_id(
projects_filtering_properties.raw_oa_institution_id
)
logger.debug(
f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}"
)
page = get_eu_organization_project_contributions(
organization_names=institution_aliases,
institution_eu_organisation_id = await (
institutions_search_client.get_eu_organisation_id_by_oa_institution_id(
projects_filtering_properties.raw_oa_institution_id
)
)
if not institution_eu_organisation_id:
logger.debug(
f"No EU organization ID found for institution_id={projects_filtering_properties.raw_oa_institution_id}"
)
raise NotFoundException(
f"EU organization ID for institution with id {projects_filtering_properties.raw_oa_institution_id} not found"
)
cordis_eu_project_page = await eu_search_client.search_eu_projects2(
eu_organisation_id=institution_eu_organisation_id,
projects_filtering_properties=projects_filtering_properties,
)
logger.debug(f"get_cordis_eu_projects_by_institution_id response: {page}")
return cordis_eu_project_page
return page
async def get_eu_projects_by_institution_id(
eu_search_client: EuProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
topic: Optional[str],
page: int,
size: int,
sort_by: str = "topic",
sort_direction: str = "asc",
) -> EuProjectPage:
logger.info(
f"Fetching EU projects for institution_id={raw_oa_institution_id}, page={page}, size={size}"
)
institution_aliases = institutions_search_client.get_institution_aliases_by_id(
raw_oa_institution_id
)
logger.debug(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
institution_eu_organisation_id = await (
institutions_search_client.get_eu_organisation_id_by_oa_institution_id(
raw_oa_institution_id
)
)
if not institution_eu_organisation_id:
logger.debug(
f"No EU organization ID found for institution_id={raw_oa_institution_id}"
)
raise NotFoundException(
f"EU organization ID for institution with id {raw_oa_institution_id} not found"
)
response = await eu_search_client.search_eu_projects(
page=page,
size=size,
institution_names=institution_aliases,
topic=topic,
sort_by=sort_by,
sort_direction=sort_direction,
)
logger.debug(f"get_eu_projects_by_institution_id response: {response}")
return response
async def get_dfg_projects_by_author_id(
dfg_search_client: DfgProjectsSearchClient,
author_id: str,
topic: Optional[str],
page: int,
@@ -162,7 +219,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 dfg_search_client.search_dfg_projects(
page=page,
size=size,
names=[name],
@@ -174,18 +231,17 @@ async def get_dfg_projects_by_author_id(
async def get_institution_cordis_eu_projects_funding_over_time(
eu_search_client: EuProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
) -> InstitutionFunderSummary:
institution_aliases = (
institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
)
page = get_eu_organization_project_contributions(
organization_names=institution_aliases,
projects_filtering_properties=ProjectsFilteringProperties(
cordis_eu_project_page = await search_cordis_eu_projects(
eu_search_client,
institutions_search_client,
ProjectsFilteringProperties(
project_type=ProjectType.EU,
raw_oa_institution_id=raw_oa_institution_id,
page=0,
size=10000,
),
@@ -193,34 +249,30 @@ async def get_institution_cordis_eu_projects_funding_over_time(
return _calculate_funding_over_time(
project_type=ProjectType.EU,
projects=page.elements,
funding_start_attr="start_date",
funding_end_attr="end_date",
funding_amount_attr="ec_contribution",
projects=cordis_eu_project_page.elements,
funding_start_attr="startDate",
funding_end_attr="endDate",
funding_amount_attr="totalCost",
)
def get_institution_bund_projects_funding_over_time(
async def get_institution_bund_projects_funding_over_time(
bund_search_client: BundProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
) -> InstitutionFunderSummary:
logger.info(
f"Fetching funding over time for institution_id={raw_oa_institution_id}"
)
institution_aliases = (
institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
institution_aliases = institutions_search_client.get_institution_aliases_by_id(
raw_oa_institution_id
)
logger.debug(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
response = projects_search_client.search_bund_projects(
filter_properties=ProjectsFilteringProperties(
project_type=ProjectType.BUND,
page=0,
size=10000,
),
response = await bund_search_client.search_bund_projects(
page=0,
size=10000,
institution_names=institution_aliases,
)
@@ -301,49 +353,25 @@ def _calculate_funding_over_time(
)
def get_single_dfg_project(
async def get_single_dfg_project(
dfg_search_client: DfgProjectsSearchClient,
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 dfg_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(
bund_search_client: BundProjectsSearchClient,
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 bund_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(
raw_oa_author_id: str,
) -> CordisEuProjectPage:
# Direct search not possible -> multi stage search
# 1. Exisiting author has publications with DOIs
# 2. CORDIS EU projects have associated publications with DOIs
# 3. Matching DOIs of author publications with DOIs of CORDIS EU project publications -> projects with associated publications of the author
dois = get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id)
logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}")
project_ids = 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(
project_ids=project_ids
)
return funding_project_page
-1
View File
@@ -7,5 +7,4 @@ class Tags(Enum):
INSTITUTIONS = "Institutions"
TOPICS = "Topics"
WORKS = "Works"
NEWS = "News"
PROJECTS = "Projects"
+17 -52
View File
@@ -39,6 +39,7 @@ async def get_author_works(
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
search: str | None = None,
client: OpenAlexWorksSearchClient | None = None,
) -> WorkPage:
search_client = client or OpenAlexWorksSearchClient()
@@ -52,6 +53,7 @@ async def get_author_works(
language=language,
institution_id=institution_id,
topic_id=topic_id,
search=search,
)
elements, total = _parse_full_work_search_response(data)
@@ -649,7 +651,9 @@ def _author_works_query(author_id: str) -> dict[str, Any]:
def _parse_year_count_buckets(response: dict) -> list[dict]:
return (
response.get("aggregations", {}).get("publication_years", {}).get("buckets", [])
response.get("aggregations", {})
.get("publication_years", {})
.get("buckets", [])
)
@@ -689,9 +693,13 @@ def _collect_topic_ids_from_year_buckets(year_buckets: list[dict]) -> set[str]:
topic_ids: set[str] = set()
for year_bucket in year_buckets:
primary_buckets = year_bucket.get("primary_topics", {}).get("buckets", [])
primary_buckets = (
year_bucket.get("primary_topics", {}).get("buckets", [])
)
topic_buckets = (
year_bucket.get("topics_nested", {}).get("topics", {}).get("buckets", [])
year_bucket.get("topics_nested", {})
.get("topics", {})
.get("buckets", [])
)
for bucket in primary_buckets + topic_buckets:
@@ -717,7 +725,9 @@ def _build_timeline_elements_from_aggregations(
continue
topics = _build_topic_counts_from_buckets(
year_bucket.get("topics_nested", {}).get("topics", {}).get("buckets", []),
year_bucket.get("topics_nested", {})
.get("topics", {})
.get("buckets", []),
topic_details=topic_details,
max_topics_per_year=max_topics_per_year,
use_reverse_nested_count=True,
@@ -773,7 +783,6 @@ def _build_topic_counts_from_buckets(
return topics
async def _search_author_works_data(
search_client: OpenAlexWorksSearchClient,
author_id: str,
@@ -784,6 +793,7 @@ async def _search_author_works_data(
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
search: str | None = None,
) -> dict:
try:
return await search_client.search_author_works(
@@ -795,6 +805,7 @@ async def _search_author_works_data(
language=language,
institution_id=institution_id,
topic_id=topic_id,
search=search,
)
except MissingApiKeyError as exc:
logger.error("OpenAlex works Elasticsearch API key is not configured.")
@@ -853,50 +864,4 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
detail="OpenAlex works search response could not be parsed.",
) from exc
return elements, total
def get_publication_dois_of_author(
raw_oa_author_id: str,
) -> List[str]:
query = {
"bool": {
"must": [
{
"nested": {
"path": "authorships",
"query": {
"term": {
"authorships.author.id": f"https://openalex.org/{raw_oa_author_id.strip().upper()}"
}
},
}
}
],
"filter": [{"exists": {"field": "doi"}}],
}
}
try:
response = elasticsearch.search(
index="openalex-works",
source=["doi"],
size=10000,
query=query,
cluster="nes",
)
except httpx.HTTPError as exc:
logger.exception("Request for publication DOIs of author failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Request for publication DOIs of author failed.",
) from exc
dois = []
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
doi = source.get("doi")
if doi:
dois.append(doi)
return dois
return elements, total
+14 -3
View File
@@ -26,13 +26,12 @@ class OpenAlexWorksSearchClient:
timeout: float | None = None,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.elasticsearch_url or "").rstrip("/")
self.base_url = (base_url or config.settings.openalex_works_search_base_url).rstrip("/")
self.index = index or config.settings.openalex_works_search_index
self.api_key = api_key if api_key is not None else config.settings.elasticsearch_api_key
self.api_key = api_key if api_key is not None else config.settings.openalex_works_api_key
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
self.transport = transport
def author_works_query(
self,
author_id: str,
@@ -43,6 +42,7 @@ class OpenAlexWorksSearchClient:
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
search: str | None = None,
) -> dict[str, Any]:
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
filters = self._work_filters(
@@ -81,6 +81,15 @@ class OpenAlexWorksSearchClient:
},
},
})
if search and search.strip():
must_clauses.append({
"match": {
"title": {
"query": search.strip(),
"operator": "and",
},
},
})
return {
"from": (page - 1) * size,
"size": size,
@@ -137,6 +146,7 @@ class OpenAlexWorksSearchClient:
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
search: str | None = None,
) -> dict[str, Any]:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
@@ -158,6 +168,7 @@ class OpenAlexWorksSearchClient:
language=language,
institution_id=institution_id,
topic_id=topic_id,
search=search,
),
)
# logging.debug(f"Response: {response.text}")
+5
View File
@@ -56,6 +56,10 @@ async def get_author_works(
list[str] | None,
Query(description="Filter by OpenAlex topic id. Can be repeated."),
] = None,
search: Annotated[
str | None,
Query(description="Search publication titles."),
] = None,
principal: security.Principal = Depends(
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
),
@@ -69,6 +73,7 @@ async def get_author_works(
language=language,
institution_id=institution_id,
topic_id=topic_id,
search=search,
)
@@ -152,6 +152,26 @@ def test_author_works_query_adds_topic_filter():
]
def test_author_works_query_adds_title_search():
client = OpenAlexWorksSearchClient(api_key="test-key")
query = client.author_works_query(
"A5023888391",
page=1,
size=20,
search="machine learning",
)
assert query["query"]["bool"]["must"][1] == {
"match": {
"title": {
"query": "machine learning",
"operator": "and",
},
},
}
@pytest.mark.anyio
async def test_search_author_works_passes_institution_filter_to_query():
def handler(request: httpx.Request) -> httpx.Response:
+4 -187
View File
@@ -17,21 +17,6 @@ GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
Content-Type: application/json
{
"size": 100,
"query": {
"bool": {
"filter": [
{
"terms": {
"projectID": ["287661"]
}
}
]
}
}
}
###
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_mapping
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
@@ -62,73 +47,6 @@ Content-Type: application/json
}
}
# 10.1371/journal.pone.0018216
###
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_mapping
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
Content-Type: application/json
###
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
Content-Type: application/json
###
GET https://inse.nes.uni-due.de/elastic/cordis_eu_fp7_project_iprs/_search
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
Content-Type: application/json
###
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
Content-Type: application/json
{
"query": {
"bool": {
"filter": [
{
"terms": {
"qaProcessedDoi": [
"10.5555/3234847.3234861",
"10.1145/1858367.1858373",
"10.1145/3583120.3586961",
"10.1109/ipin.2017.8115906",
"10.1145/3274783.3275217",
"10.1007/978-3-031-20716-7_7",
"10.1109/percomw.2012.6197554",
"10.1016/j.pmcj.2012.12.002",
"10.1007/978-3-658-32266-3_30",
"10.1109/percomw.2013.6529502",
"10.1109/ie.2010.40",
"10.18419/opus-2650",
"10.1007/s00138-024-01553-z",
"10.1007/978-3-030-90439-5_15",
"10.1201/9781003338659-4",
"10.1016/j.pmcj.2013.10.013",
"10.1109/percom.2009.4912852",
"10.1109/icra55743.2025.11128432",
"10.1145/2494091.2497327",
"10.1007/978-3-658-46485-1_31",
"10.1109/ie.2017.22",
"10.1109/jiot.2016.2554146",
"10.1145/2493432.2493459",
"10.3233/ais-160416",
"10.1109/percomw.2007.111",
"10.5194/asr-17-183-2020",
"10.1007/978-3-658-36430-4_37",
"10.1007/978-3-030-64559-5_50"
]
}
}
]
}
}
}
###
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
@@ -161,26 +79,6 @@ GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
Content-Type: application/json
{
"size": 1000,
"query": {
"bool": {
"filter": [
{
"term": {
"name.keyword": "UNIVERSITAET DUISBURG-ESSEN"
}
}
]
}
}
}
###
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
Content-Type: application/json
{
"size": 0,
"query": {
@@ -203,38 +101,6 @@ Content-Type: application/json
}
}
###
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_projects/_mapping
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
Content-Type: application/json
###
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
Content-Type: application/json
{
"query": {
"terms": {
"name": [
"UNIVERSITÄT DUISBURG-ESSEN",
"UNIVERSITY OF DUISBURG-ESSEN",
"UNIVERSITAT DUISBURG-ESSEN",
"UNIVERSITY OF DUISBURG ESSEN",
"UNIVERSITAT DUISBURG-ESSEN",
"UNIVERSITAET DUISBURG ESSEN",
"UNIVERSITÄT DUISBURG ESSEN",
"UNIVERSITAT DUISBURG ESSEN",
"UNIVERSITÄT DUISBURG-ESSEN",
"UNIVERSITAET DUISBURG-ESSEN",
"UNIVERSITY OF DUISBURG-ESSEN"
]
}
},
"_source": ["projectID", "organisationID", "ecContribution"]
}
###
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
@@ -266,27 +132,18 @@ Content-Type: application/json
"bool": {
"filter": [
{
"terms": {
"name.keyword": [
"UNIVERSITAET DUISBURG-ESSEN",
"UNIVERSITY OF DUISBURG-ESSEN",
"UNIVERSITÄT DUISBURG-ESSEN",
"UNIVERSITAT DUISBURG ESSEN",
"UNIVERSITÄT DUISBURG ESSEN",
"UNIVERSITY OF DUISBURG ESSEN",
"UNIVERSITAET DUISBURG ESSEN",
"UNIVERSITAT DUISBURG-ESSEN"
]
"term": {
"name.keyword": "UNIVERSITAET DUISBURG-ESSEN"
}
}
]
}
},
"aggs": {
"organisation_ids": {
"specific_org_rcn_values": {
"terms": {
"field": "organisationID",
"size": 10000
"size": 1000
}
}
}
@@ -1195,46 +1052,6 @@ Content-Type: application/json
###
GET https://project.nes.uni-due.de/elastic/openalex-works/_search
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
Content-Type: application/json
###
GET https://project.nes.uni-due.de/elastic/openalex-works/_search
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
Content-Type: application/json
{
"_source": ["title", "doi"],
"size": 100,
"query": {
"bool": {
"must": [
{
"nested": {
"path": "authorships",
"query": {
"term": {
"authorships.author.id": "https://openalex.org/A5007170803"
}
}
}
}
],
"filter": [
{
"exists": {
"field": "doi"
}
}
]
}
}
}
###
GET https://project.nes.uni-due.de/elastic/openalex-authors/_search
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
Content-Type: application/json
@@ -10,8 +10,6 @@ api/iNSEAccountService.service.ts
api/iNSEService.service.ts
api/institutions.service.ts
api/items.service.ts
api/news.service.ts
api/patents.service.ts
api/personNetwork.service.ts
api/persons.service.ts
api/projects.service.ts
@@ -61,8 +59,6 @@ model/dehydratedSource.ts
model/dfgProjectDetails.ts
model/dfgProjectPage.ts
model/dfgProjectSummary.ts
model/euOrganizationProjectSummary.ts
model/euOrganizationProjectSummaryPage.ts
model/filterInformation.ts
model/filterProperties.ts
model/funderByAuthor.ts
@@ -89,16 +85,10 @@ model/latitude.ts
model/location.ts
model/longitude.ts
model/matchedOfficer.ts
model/mentionedPerson.ts
model/meta.ts
model/model2YrMeanCitedness.ts
model/models.ts
model/newsArticle.ts
model/newsArticleDetail.ts
model/newsPage.ts
model/openAccess.ts
model/patentEntry.ts
model/patentsByAuthorResponse.ts
model/personBio.ts
model/projectType.ts
model/projectsFilteringProperties.ts
+1 -5
View File
@@ -10,10 +10,6 @@ export * from './institutions.service';
import { InstitutionsService } from './institutions.service';
export * from './items.service';
import { ItemsService } from './items.service';
export * from './news.service';
import { NewsService } from './news.service';
export * from './patents.service';
import { PatentsService } from './patents.service';
export * from './personNetwork.service';
import { PersonNetworkService } from './personNetwork.service';
export * from './persons.service';
@@ -24,4 +20,4 @@ export * from './topics.service';
import { TopicsService } from './topics.service';
export * from './works.service';
import { WorksService } from './works.service';
export const APIS = [CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, ItemsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
export const APIS = [CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, ItemsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
-554
View File
@@ -1,554 +0,0 @@
/**
* 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.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { NewsArticleDetail } from '../model/newsArticleDetail';
// @ts-ignore
import { NewsPage } from '../model/newsPage';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
})
export class NewsService extends BaseService {
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
/**
* Returns news articles in which the given person is mentioned.
* @endpoint get /api/news/by-author
* @param authorId OpenAlex author id, e.g. A5034365278.
* @param page Page number (1-based).
* @param pageSize Articles per page.
* @param sortOrder Sort order: \&#39;desc\&#39; (newest first) or \&#39;asc\&#39; (oldest first).
* @param query Optional search term, matched against title/author.
* @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 getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsPage>;
public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsPage>>;
public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsPage>>;
public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getNewsByAuthor.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>authorId, 'authorId');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'pageSize');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortOrder, 'sortOrder');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>query, 'query');
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/news/by-author`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<NewsPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns news articles in which the given person is mentioned.
* @endpoint get /api/news/by-author
* @param authorId OpenAlex author id, e.g. A5034365278.
* @param page Page number (1-based).
* @param pageSize Articles per page.
* @param sortOrder Sort order: \&#39;desc\&#39; (newest first) or \&#39;asc\&#39; (oldest first).
* @param query Optional search term, matched against title/author.
* @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 getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsPage>;
public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsPage>>;
public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsPage>>;
public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getNewsByAuthor_1.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>authorId, 'authorId');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'pageSize');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortOrder, 'sortOrder');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>query, 'query');
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/news/by-author`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<NewsPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a single news article including its full content.
* @endpoint get /api/news/{news_id}
* @param newsId The unique id of the news article (Elasticsearch _id).
* @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 getNewsById(newsId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsArticleDetail>;
public getNewsById(newsId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsArticleDetail>>;
public getNewsById(newsId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsArticleDetail>>;
public getNewsById(newsId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (newsId === null || newsId === undefined) {
throw new Error('Required parameter newsId was null or undefined when calling getNewsById.');
}
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/news/${this.configuration.encodeParam({name: "newsId", value: newsId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<NewsArticleDetail>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a single news article including its full content.
* @endpoint get /api/news/{news_id}
* @param newsId The unique id of the news article (Elasticsearch _id).
* @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 getNewsById_2(newsId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsArticleDetail>;
public getNewsById_2(newsId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsArticleDetail>>;
public getNewsById_2(newsId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsArticleDetail>>;
public getNewsById_2(newsId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (newsId === null || newsId === undefined) {
throw new Error('Required parameter newsId was null or undefined when calling getNewsById_2.');
}
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/news/${this.configuration.encodeParam({name: "newsId", value: newsId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<NewsArticleDetail>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a page of news articles, newest first.
* @endpoint get /api/news
* @param page Page number (1-based).
* @param pageSize Articles per page.
* @param sortOrder Sort order: \&#39;desc\&#39; (newest first) or \&#39;asc\&#39; (oldest first).
* @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 listNews(page?: number, pageSize?: number, sortOrder?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsPage>;
public listNews(page?: number, pageSize?: number, sortOrder?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsPage>>;
public listNews(page?: number, pageSize?: number, sortOrder?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsPage>>;
public listNews(page?: number, pageSize?: number, sortOrder?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'pageSize');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortOrder, 'sortOrder');
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/news`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<NewsPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a page of news articles, newest first.
* @endpoint get /api/news
* @param page Page number (1-based).
* @param pageSize Articles per page.
* @param sortOrder Sort order: \&#39;desc\&#39; (newest first) or \&#39;asc\&#39; (oldest first).
* @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 listNews_3(page?: number, pageSize?: number, sortOrder?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsPage>;
public listNews_3(page?: number, pageSize?: number, sortOrder?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsPage>>;
public listNews_3(page?: number, pageSize?: number, sortOrder?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsPage>>;
public listNews_3(page?: number, pageSize?: number, sortOrder?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'pageSize');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortOrder, 'sortOrder');
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/news`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<NewsPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Searches news articles by full text (full_content).
* @endpoint get /api/news/search
* @param query Search term, matched against the full text (full_content).
* @param page Page number (1-based).
* @param pageSize Articles per page.
* @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 searchNews(query: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsPage>;
public searchNews(query: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsPage>>;
public searchNews(query: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsPage>>;
public searchNews(query: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (query === null || query === undefined) {
throw new Error('Required parameter query was null or undefined when calling searchNews.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>query, 'query');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'pageSize');
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/news/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<NewsPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Searches news articles by full text (full_content).
* @endpoint get /api/news/search
* @param query Search term, matched against the full text (full_content).
* @param page Page number (1-based).
* @param pageSize Articles per page.
* @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 searchNews_4(query: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsPage>;
public searchNews_4(query: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsPage>>;
public searchNews_4(query: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsPage>>;
public searchNews_4(query: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (query === null || query === undefined) {
throw new Error('Required parameter query was null or undefined when calling searchNews_4.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>query, 'query');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'pageSize');
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/news/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<NewsPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
+158 -95
View File
@@ -1,95 +1,158 @@
/**
* 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.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
})
export class PatentsService extends BaseService {
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
/**
* Get patents matched to an author by name.
* @endpoint get /api/inse-service/authors/{author_id}/patents
* @param authorId
* @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 getPatentsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentsByAuthorResponse>;
public getPatentsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentsByAuthorResponse>>;
public getPatentsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentsByAuthorResponse>>;
public getPatentsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getPatentsByAuthor.');
}
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/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentsByAuthorResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
/**
* Innovation Search Engine API
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
export interface PatentEntry {
patent_id: string;
source: string;
title: string | null;
abstract: string | null;
publication_date: string | null;
publication_year: string | null;
inventors: string[];
assignees: string[];
ipc: string[];
country: string | null;
confidence_score: number;
}
export interface PatentsByAuthorResponse {
author_id: string;
author_name: string | null;
patent_count: number;
patents: PatentEntry[];
}
type GetPatentsByAuthorOptions = {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
};
@Injectable({
providedIn: 'root',
})
export class PatentsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
/**
* Get patents by author.
* @endpoint get /api/inse-service/authors/{author_id}/patents
* @param authorId
* @param observe
* @param reportProgress
*/
public getPatentsByAuthor(
authorId: string,
observe?: 'body',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<PatentsByAuthorResponse>;
public getPatentsByAuthor(
authorId: string,
observe?: 'response',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<HttpResponse<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe?: 'events',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<HttpEvent<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: GetPatentsByAuthorOptions,
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getPatentsByAuthor.',
);
}
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/authors/${this.configuration.encodeParam({
name: 'authorId',
value: authorId,
in: 'path',
style: 'simple',
explode: false,
dataType: 'string',
dataFormat: undefined,
})}/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentsByAuthorResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
+4 -62
View File
@@ -27,8 +27,6 @@ import { DfgProjectDetails } from '../model/dfgProjectDetails';
// @ts-ignore
import { DfgProjectPage } from '../model/dfgProjectPage';
// @ts-ignore
import { EuOrganizationProjectSummaryPage } from '../model/euOrganizationProjectSummaryPage';
// @ts-ignore
import { FundingProjectPage } from '../model/fundingProjectPage';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
@@ -135,62 +133,6 @@ export class ProjectsService extends BaseService {
);
}
/**
* Get EU projects for an author.
* Returns a list of EU projects associated with the specified author ID.
* @endpoint get /api/projects/author/{raw_oa_author_id}/eu
* @param rawOaAuthorId The author ID to filter by.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CordisEuProjectPage>;
public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CordisEuProjectPage>>;
public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CordisEuProjectPage>>;
public getEuProjectsForAuthor(rawOaAuthorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (rawOaAuthorId === null || rawOaAuthorId === undefined) {
throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getEuProjectsForAuthor.');
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/projects/author/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/eu`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CordisEuProjectPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Get funding over time for bund projects.
* Returns the funding over time for bund projects associated with the specified institution.
@@ -499,9 +441,9 @@ export class ProjectsService extends BaseService {
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<EuOrganizationProjectSummaryPage>;
public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<EuOrganizationProjectSummaryPage>>;
public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<EuOrganizationProjectSummaryPage>>;
public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CordisEuProjectPage>;
public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CordisEuProjectPage>>;
public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CordisEuProjectPage>>;
public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (projectsFilteringProperties === null || projectsFilteringProperties === undefined) {
throw new Error('Required parameter projectsFilteringProperties was null or undefined when calling searchCordisEuProjects.');
@@ -543,7 +485,7 @@ export class ProjectsService extends BaseService {
let localVarPath = `/api/projects/institution/eu/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<EuOrganizationProjectSummaryPage>('post', `${basePath}${localVarPath}`,
return this.httpClient.request<CordisEuProjectPage>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: projectsFilteringProperties,
+97 -21
View File
@@ -103,27 +103,98 @@ export class WorksService extends BaseService {
);
}
/**
* Returns a page of works for an author.
* @endpoint get /api/works/{author_id}
* @param authorId The author id, for example A5023888391.
* @param page The page number.
* @param size The page size.
* @param publicationYear Filter by publication year. Can be repeated.
* @param type Filter by publication type. Can be repeated.
* @param language Filter by language code. Can be repeated.
* @param institutionId Filter by OpenAlex institution id. Can be repeated.
* @param topicId Filter by OpenAlex topic id. Can be repeated.
* @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 getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorkPage>;
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorkPage>>;
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorkPage>>;
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.');
}
/**
* Returns a page of works for an author.
* @endpoint get /api/works/{author_id}
* @param authorId The author id, for example A5023888391.
* @param page The page number.
* @param size The page size.
* @param publicationYear Filter by publication year. Can be repeated.
* @param type Filter by publication type. Can be repeated.
* @param language Filter by language code. Can be repeated.
* @param institutionId Filter by OpenAlex institution id. Can be repeated.
* @param topicId Filter by OpenAlex topic id. Can be repeated.
* @param search Search publication titles.
* @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 getAuthorWorks(
authorId: string,
page?: number,
size?: number,
publicationYear?: Array<number>,
type?: Array<string>,
language?: Array<string>,
institutionId?: Array<string>,
topicId?: Array<string>,
search?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<WorkPage>;
public getAuthorWorks(
authorId: string,
page?: number,
size?: number,
publicationYear?: Array<number>,
type?: Array<string>,
language?: Array<string>,
institutionId?: Array<string>,
topicId?: Array<string>,
search?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<WorkPage>>;
public getAuthorWorks(
authorId: string,
page?: number,
size?: number,
publicationYear?: Array<number>,
type?: Array<string>,
language?: Array<string>,
institutionId?: Array<string>,
topicId?: Array<string>,
search?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<WorkPage>>;
public getAuthorWorks(
authorId: string,
page?: number,
size?: number,
publicationYear?: Array<number>,
type?: Array<string>,
language?: Array<string>,
institutionId?: Array<string>,
topicId?: Array<string>,
search?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getAuthorWorks.',
);
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -160,6 +231,11 @@ export class WorksService extends BaseService {
<any>element, 'topic_id');
})
}
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>search,
'search',
);
let localVarHeaders = this.defaultHeaders;
@@ -1,27 +0,0 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface EuOrganizationProjectSummary {
/**
* The unique identifier of the organization.
*/
organization_id: string;
/**
* The unique identifier of the project.
*/
project_id: string;
title?: string | null;
start_date?: string | null;
end_date?: string | null;
acronym?: string | null;
ec_contribution?: number | null;
}
@@ -1,31 +0,0 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { EuOrganizationProjectSummary } from './euOrganizationProjectSummary';
export interface EuOrganizationProjectSummaryPage {
/**
* The current page number.
*/
page?: number;
/**
* The requested page size.
*/
size?: number;
/**
* The total number of items.
*/
total?: number;
/**
* The organization project summaries on this page.
*/
elements?: Array<EuOrganizationProjectSummary>;
}
@@ -20,7 +20,6 @@ export interface FundingProject {
*/
id: string;
title?: string | null;
acronym?: string | null;
start_date?: string | null;
end_date?: string | null;
funding_amount?: number | null;
@@ -1,17 +0,0 @@
/**
* 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 MentionedPerson {
name: string;
is_ude?: boolean;
person_id?: string | null;
}
-8
View File
@@ -38,8 +38,6 @@ export * from './dehydratedSource';
export * from './dfgProjectDetails';
export * from './dfgProjectPage';
export * from './dfgProjectSummary';
export * from './euOrganizationProjectSummary';
export * from './euOrganizationProjectSummaryPage';
export * from './filterInformation';
export * from './filterProperties';
export * from './funderByAuthor';
@@ -66,15 +64,9 @@ export * from './latitude';
export * from './location';
export * from './longitude';
export * from './matchedOfficer';
export * from './mentionedPerson';
export * from './meta';
export * from './model2YrMeanCitedness';
export * from './newsArticle';
export * from './newsArticleDetail';
export * from './newsPage';
export * from './openAccess';
export * from './patentEntry';
export * from './patentsByAuthorResponse';
export * from './personBio';
export * from './projectType';
export * from './projectsFilteringProperties';
-21
View File
@@ -1,21 +0,0 @@
/**
* 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 NewsArticle {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
}
@@ -1,24 +0,0 @@
/**
* 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 { MentionedPerson } from './mentionedPerson';
export interface NewsArticleDetail {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
full_content?: string | null;
authors?: Array<MentionedPerson>;
}
-19
View File
@@ -1,19 +0,0 @@
/**
* 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 { NewsArticle } from './newsArticle';
export interface NewsPage {
total: number;
page: number;
page_size: number;
results: Array<NewsArticle>;
}
-24
View File
@@ -1,24 +0,0 @@
/**
* 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 PatentEntry {
patent_id: string;
source: string;
title?: string | null;
'abstract'?: string | null;
publication_date?: string | null;
publication_year?: string | null;
inventors?: Array<string>;
assignees?: Array<string>;
ipc?: Array<string>;
country?: string | null;
}
@@ -1,19 +0,0 @@
/**
* 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 PatentsByAuthorResponse {
author_id: string;
author_name?: string | null;
patent_count: number;
patents: Array<PatentEntry>;
}
+22 -34
View File
@@ -7,7 +7,6 @@ import { personResolver } from './resolvers/person.resolver';
import { institutionResolver } from './resolvers/institution.resolver';
import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
import { personNewsResolver } from './resolvers/person-news.resolver';
import { institutionsResolver } from './resolvers/institutions.resolver';
import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.resolver';
import { dfgSingleProjectResolver } from './resolvers/dfg-single-project-resolver';
@@ -15,7 +14,7 @@ import { bundSingleProjectResolver } from './resolvers/bund-single-project-resol
import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page.resolver';
import { cordisEuProjectsFundingResolver } from './resolvers/cordis-eu-projects-funding.resolver';
import { fundingProjectPageResolver } from './resolvers/funding-project-page.resolver';
import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver';
import { publicationsResolver } from './resolvers/publications.resolver';
export const routes: Routes = [
{
@@ -84,20 +83,6 @@ export const routes: Routes = [
return scalarChanged || topicsChanged;
},
},
{
path: 'news',
canActivate: [userGuard],
loadComponent: () =>
import('./modules/news/news.component').then((mod) => mod.NewsComponent),
},
{
path: 'news/:id',
canActivate: [userGuard],
loadComponent: () =>
import('./modules/news-detail/news-detail.component').then(
(mod) => mod.NewsDetailComponent,
),
},
{
path: 'publication/:publicationId',
canActivate: [userGuard],
@@ -163,7 +148,6 @@ export const routes: Routes = [
),
resolve: {
dfgProjectPage: dfgProjectsResolver,
personCordisEuProjectPage: personCordisEuProjectPageResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
@@ -179,6 +163,27 @@ export const routes: Routes = [
import('./modules/person-publications/person-publications.component').then(
(mod) => mod.PersonPublicationsComponent,
),
resolve: {
publicationPage: publicationsResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = [
'publicationPage',
'publicationPageSize',
'publicationYear',
'publicationType',
'publicationLanguage',
'publicationInstitutionId',
'publicationTopicId',
'publicationSearch',
];
return keys.some(
(key) =>
from.queryParamMap.getAll(key).join(',') !==
to.queryParamMap.getAll(key).join(','),
);
},
},
{
path: 'network',
@@ -216,23 +221,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: () =>
@@ -1,39 +1,28 @@
<div class="dashboard-wrapper">
<header class="dashboard-header">
<h2>University Performance Dashboard</h2>
<div class="controls">
<select (change)="onTopicChange($any($event.target).value)">
@for (t of topics; track t) {
<option [value]="t">{{ t }}</option>
}
</select>
<header class="dashboard-header">
<h2>University Performance Dashboard</h2>
<div class="controls">
<select (change)="onTopicChange($any($event.target).value)">
@for (t of topics; track t){
<option [value]="t">{{t}}</option>
}
</select>
<div class="toggle-group">
<button [class.active]="metric === 'publications'" (click)="setMetric('publications')">Publications</button>
<button [class.active]="metric === 'citations'" (click)="setMetric('citations')">Citations</button>
</div>
</div>
</header>
<div class="toggle-group">
<button
[class.active]="metric === 'publications'"
(click)="setMetric('publications')">
Publications
</button>
<button
[class.active]="metric === 'citations'"
(click)="setMetric('citations')">
Citations
</button>
<div class="content-grid">
<section class="chart-section">
<app-university-line-chart [data]="rawDataSource" [metric]="metric"></app-university-line-chart>
</section>
<aside class="table-section">
<app-university-ranking-table [rankings]="computedRankings" [loading]="isLoading"></app-university-ranking-table>
</aside>
</div>
</div>
</header>
<div class="content-grid">
<section class="chart-section">
<app-university-line-chart
[data]="rawDataSource"
[metric]="metric"></app-university-line-chart>
</section>
<aside class="table-section">
<app-university-ranking-table
[rankings]="computedRankings"
[loading]="isLoading"></app-university-ranking-table>
</aside>
</div>
</div>
</div>
@@ -26,7 +26,7 @@
.controls {
display: flex;
gap: 1rem;
select {
padding: 0.5rem;
border-radius: 4px;
@@ -40,16 +40,9 @@
background: white;
color: #0056b3;
cursor: pointer;
&:first-child {
border-radius: 4px 0 0 4px;
}
&:last-child {
border-radius: 0 4px 4px 0;
}
&.active {
background: #0056b3;
color: white;
}
&:first-child { border-radius: 4px 0 0 4px; }
&:last-child { border-radius: 0 4px 4px 0; }
&.active { background: #0056b3; color: white; }
}
}
}
@@ -61,35 +54,20 @@
border-collapse: collapse;
font-size: 0.9rem;
th,
td {
th, td {
padding: 0.75rem;
text-align: left;
border-bottom: 1px solid #f0f0f0;
}
.top-tier {
background-color: #f8fbff;
font-weight: 600;
}
.positive {
color: #28a745;
}
.negative {
color: #dc3545;
}
.mover-badge {
margin-left: 4px;
font-size: 0.8rem;
}
.top-tier { background-color: #f8fbff; font-weight: 600; }
.positive { color: #28a745; }
.negative { color: #dc3545; }
.mover-badge { margin-left: 4px; font-size: 0.8rem; }
.trend-col {
font-weight: bold;
&[data-trend='up'] {
color: #28a745;
}
&[data-trend='down'] {
color: #dc3545;
}
&[data-trend="up"] { color: #28a745; }
&[data-trend="down"] { color: #dc3545; }
}
}
@@ -1,31 +1,24 @@
import { Component, OnInit } from '@angular/core';
import { UniversityRankingService } from '../university-ranking/services/uni-ranking-service';
import { UniversityLineChartComponent } from '../university-ranking/uni-line-chart/uni-line-chart.component';
import {UniversityLineChartComponent} from '../university-ranking/uni-line-chart/uni-line-chart.component';
import { UniversityRankingTableComponent } from '../university-ranking/uni-ranking-table/uni-ranking-table.component';
import { UniversityTopicData, UniversityRanking } from '../../api';
export type ResearchTopic =
| 'Artificial Intelligence'
| 'Quantum Computing'
| 'Renewable Energy'
| 'Biotechnology';
export type ResearchTopic = 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology';
export type DashboardMetric = 'publications' | 'citations';
@Component({
selector: 'dashboard',
imports: [UniversityLineChartComponent, UniversityRankingTableComponent],
imports: [UniversityLineChartComponent,UniversityRankingTableComponent],
templateUrl: './dashboard.component.html',
styleUrl: './dashboard.component.scss',
})
export class DashboardComponent implements OnInit {
topics: ResearchTopic[] = [
'Artificial Intelligence',
'Quantum Computing',
'Renewable Energy',
'Biotechnology',
];
topics: ResearchTopic[] = ['Artificial Intelligence', 'Quantum Computing', 'Renewable Energy', 'Biotechnology'];
selectedTopic: ResearchTopic = 'Artificial Intelligence';
metric: DashboardMetric = 'publications';
rawDataSource: UniversityTopicData[] = [];
computedRankings: UniversityRanking[] = [];
isLoading = false;
@@ -48,15 +41,13 @@ export class DashboardComponent implements OnInit {
private loadData() {
this.isLoading = true;
this.dataService
.getRankingData(this.selectedTopic, this.metric)
.subscribe((response) => {
// Map backend snake_case properties to frontend camelCase if necessary,
// though OpenAPI Generator usually handles this.
console.log(response);
this.rawDataSource = (response.timeseries as any) || [];
this.computedRankings = (response.rankings as any) || [];
this.isLoading = false;
});
this.dataService.getRankingData(this.selectedTopic, this.metric).subscribe(response => {
// Map backend snake_case properties to frontend camelCase if necessary,
// though OpenAPI Generator usually handles this.
console.log(response);
this.rawDataSource = (response.timeseries as any) || [];
this.computedRankings = (response.rankings as any) || [];
this.isLoading = false;
});
}
}
@@ -75,9 +75,7 @@
undefined
" />
<app-person-network-info-card
[description]="
'Durchschnittliche jährliche Förderung durch die Europäische Union'
"
[description]="'Durchschnittliche jährliche Förderung durch die Europäische Union'"
[value]="
(euAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
@@ -96,15 +94,3 @@
<ng-template #fundingAmountTmp let-row>
{{ row.funding_amount | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }}
</ng-template>
<ng-template #euProjectActionsTmp let-row>
<a mat-icon-button color="primary" [routerLink]="['/projects/eu', row.id]">
<mat-icon>open_in_new</mat-icon>
</a></ng-template
>
<ng-template #bundProjectActionsTmp let-row>
<a mat-icon-button color="primary" [routerLink]="['/projects/bund', row.id]">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
@@ -8,12 +8,12 @@ import {
TemplateRef,
viewChild,
} from '@angular/core';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { ActivatedRoute, Router } from '@angular/router';
import {
BundProject,
BundProjectPage,
EuOrganizationProjectSummary,
EuOrganizationProjectSummaryPage,
CordisEuProject,
CordisEuProjectPage,
InstitutionFunderSummary,
} from '../../api';
import { MatCardModule } from '@angular/material/card';
@@ -36,7 +36,6 @@ import { InstitutionProjectsFundingGraphComponent } from '../institution-project
import { PersonNetworkInfoCardComponent } from '../person-network-info-card/person-network-info-card.component';
type BundProjectRow = {
id: string;
topic: string;
funding_start: Date;
funding_end: Date;
@@ -45,7 +44,6 @@ type BundProjectRow = {
};
type EuProjectRow = {
id: string;
topic: string;
funding_start: Date;
funding_end: Date;
@@ -69,7 +67,6 @@ type EuProjectRow = {
MatButtonModule,
InstitutionProjectsFundingGraphComponent,
PersonNetworkInfoCardComponent,
RouterModule,
],
templateUrl: './institution-projects.component.html',
styleUrl: './institution-projects.component.scss',
@@ -79,19 +76,13 @@ export class InstitutionProjectsComponent implements OnInit {
fundingEndTmp = viewChild.required<TemplateRef<any>>('fundingEndTmp');
fundingAmountTmp = viewChild.required<TemplateRef<any>>('fundingAmountTmp');
cordisEuProjectPage = input.required<EuOrganizationProjectSummaryPage>();
cordisEuProjectPage = input.required<CordisEuProjectPage>();
euProjectColumns: GenericColumn<EuProjectRow>[] = [];
euProjectData: EuProjectRow[] = [];
euProjectActionsTmp = viewChild.required<TemplateRef<any>>(
'euProjectActionsTmp',
);
bundProjectPage = input.required<BundProjectPage>();
bundProjectColumns: GenericColumn<BundProjectRow>[] = [];
bundProjectData: BundProjectRow[] = [];
bundProjectActionsTmp = viewChild.required<TemplateRef<any>>(
'bundProjectActionsTmp',
);
bundProjectsFunding = input.required<InstitutionFunderSummary>();
bundTotalFunding = computed(() => {
@@ -230,16 +221,10 @@ export class InstitutionProjectsComponent implements OnInit {
accessorKey: 'funding_amount',
cellTemplate: this.fundingAmountTmp(),
},
{
id: 'actions',
header: '',
type: 'display',
cellTemplate: this.euProjectActionsTmp(),
},
];
this.bundProjectColumns = [
{
id: 'title',
id: 'topic',
header: 'Titel',
type: 'accessor',
accessorKey: 'topic',
@@ -265,30 +250,22 @@ export class InstitutionProjectsComponent implements OnInit {
accessorKey: 'funding_amount',
cellTemplate: this.fundingAmountTmp(),
},
{
id: 'actions',
header: '',
type: 'display',
cellTemplate: this.bundProjectActionsTmp(),
},
];
}
transformEuRow(project: EuOrganizationProjectSummary): EuProjectRow {
transformEuRow(project: CordisEuProject): EuProjectRow {
return {
id: project.project_id,
topic: project.title || '',
funding_start: project.start_date
? new Date(project.start_date)
funding_start: project.startDate
? new Date(project.startDate)
: new Date(0),
funding_end: project.end_date ? new Date(project.end_date) : new Date(0),
funding_amount: Number(project.ec_contribution) || 0,
funding_end: project.endDate ? new Date(project.endDate) : new Date(0),
funding_amount: Number(project.totalCost) || 0,
};
}
transformBundRow(project: BundProject): BundProjectRow {
return {
id: project.funding_code || '',
topic: project.topic || '',
funding_start: project.funding_start
? new Date(project.funding_start)
@@ -1,123 +0,0 @@
<div class="detail-page">
<button
type="button"
class="back-link"
(click)="navigateBack()"
aria-label="Zurück zu den Nachrichten">
<mat-icon>arrow_back</mat-icon>
Alle Nachrichten
</button>
@if (loading) {
<div class="state">
<mat-spinner diameter="42"></mat-spinner>
<p>Nachricht wird geladen...</p>
</div>
} @else if (notFound || !article) {
<div class="state error-state">
<mat-icon>search_off</mat-icon>
<h2>Nachricht nicht gefunden</h2>
<p>Der Artikel konnte nicht geladen werden.</p>
<a mat-stroked-button routerLink="/persons">Zur Personensuche</a>
</div>
} @else {
<div class="detail-layout">
<main>
<header class="hero">
<div class="eyebrow">
@if (article.author) {
<span>{{ article.author }}</span>
}
@if (article.date) {
<span>{{ formatDate(article.date) }}</span>
}
</div>
<p class="article-heading">{{ article.maintitle || 'Kein Titel' }}</p>
@if (article.relevant === true) {
<span class="relevance-badge is-relevant">
<mat-icon>check_circle</mat-icon>
Relevant
</span>
} @else if (article.relevant === false) {
<span class="relevance-badge not-relevant">
<mat-icon>cancel</mat-icon>
Nicht relevant
</span>
} @else {
<span class="relevance-badge undetermined">
<mat-icon>help</mat-icon>
Relevanz nicht bestimmt
</span>
}
</header>
<div class="article-body">
@if (article.full_content) {
<p class="content">{{ article.full_content }}</p>
} @else {
<p class="placeholder">Kein Inhalt verfügbar.</p>
}
</div>
@if (article.url) {
<div class="article-actions">
<a
mat-stroked-button
[href]="article.url"
target="_blank"
rel="noopener">
<mat-icon>open_in_new</mat-icon>
Originalartikel öffnen
</a>
</div>
}
</main>
<aside class="sidebar">
<div class="sidebar-card">
<h3>
<mat-icon>group</mat-icon>
Erwähnte Personen
</h3>
<div class="person-list">
@if (article.authors && article.authors.length) {
@for (person of article.authors; track person.name) {
@if (person.is_ude && person.person_id) {
<a
class="person-item is-link"
[routerLink]="['/person', person.person_id, 'overview']">
<div class="avatar">{{ person.name.charAt(0) }}</div>
<span class="person-name">{{ person.name }}</span>
<span class="ude-badge">UDE</span>
</a>
} @else {
<article class="person-item is-muted">
<div class="avatar">{{ person.name.charAt(0) }}</div>
<span class="person-name">{{ person.name }}</span>
</article>
}
}
} @else {
<p class="placeholder">Keine erwähnten Personen gefunden.</p>
}
</div>
</div>
<div class="sidebar-card">
<h3>
<mat-icon>label</mat-icon>
Relevante Themen
</h3>
<div class="chip-list">
@for (topic of relevantTopics; track topic; let i = $index) {
<span class="topic-chip" [ngClass]="chipColor(i)">{{
topic
}}</span>
}
</div>
</div>
</aside>
</div>
}
</div>
@@ -1,295 +0,0 @@
.detail-page {
max-width: 1200px;
margin: 0 auto;
padding: 28px 32px 64px;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 6px;
background: none;
border: none;
cursor: pointer;
font-size: 14px;
color: var(--sg-text-muted);
padding: 0;
margin-bottom: 32px;
&:hover {
color: var(--sg-text);
}
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
}
.state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 16px;
padding: 80px 0;
text-align: center;
color: var(--sg-text-muted);
mat-icon {
font-size: 48px;
width: 48px;
height: 48px;
}
p {
margin: 0;
}
}
.error-state h2 {
margin: 0;
}
.detail-layout {
display: grid;
grid-template-columns: 1fr 280px;
gap: 40px;
align-items: start;
}
main {
min-width: 0;
}
.hero {
margin-bottom: 32px;
}
.eyebrow {
display: flex;
gap: 12px;
font-size: 13px;
color: var(--sg-text-muted);
margin-bottom: 12px;
span + span::before {
content: '·';
margin-right: 12px;
}
}
.article-heading {
margin: 0;
font-size: 28px;
font-weight: 700;
line-height: 1.3;
}
.relevance-badge {
display: inline-flex;
align-items: center;
gap: 6px;
margin-top: 14px;
padding: 5px 12px;
border-radius: 999px;
font-size: 13px;
font-weight: 600;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
}
&.is-relevant {
background: #effaf3;
border: 1px solid #bdebcf;
color: #24834f;
}
&.not-relevant {
background: var(--sg-surface-muted);
border: 1px solid #e2e2e2;
color: var(--sg-text-muted);
}
&.undetermined {
background: #fff7e8;
border: 1px solid #ffd796;
color: #c67500;
}
}
.article-body {
font-size: 15px;
line-height: 1.7;
color: var(--sg-text);
}
.content {
margin: 0;
white-space: pre-wrap;
}
.placeholder {
margin: 0;
color: var(--sg-text-muted);
font-style: italic;
}
.article-actions {
margin-top: 32px;
}
.sidebar {
display: flex;
flex-direction: column;
gap: 16px;
position: sticky;
top: 24px;
}
.sidebar-card {
padding: 20px;
border: 1px solid #d7e4ff;
border-radius: 16px;
background: #ffffff;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
h3 {
display: flex;
align-items: center;
gap: 8px;
margin: 0 0 14px;
font-size: 14px;
font-weight: 600;
color: var(--sg-text);
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
color: var(--sg-text-muted);
}
}
}
.person-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.person-item {
display: grid;
grid-template-columns: 38px minmax(0, 1fr) auto;
gap: 11px;
align-items: center;
padding: 12px;
border-radius: var(--sg-radius-sm);
background: var(--sg-surface-muted);
}
.person-item.is-link {
cursor: pointer;
text-decoration: none;
color: inherit;
transition: background 0.15s ease;
}
.person-item.is-link:hover {
background: #e5ecfb;
}
.person-item.is-muted {
.avatar {
background: #ececef;
color: var(--sg-text-muted);
}
.person-name {
color: var(--sg-text-muted);
}
}
.ude-badge {
justify-self: end;
padding: 3px 9px;
border-radius: 999px;
background: #effaf3;
border: 1px solid #bdebcf;
color: #24834f;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.03em;
}
.avatar {
display: grid;
place-items: center;
width: 38px;
height: 38px;
border-radius: 50%;
background: #e5ecfb;
color: var(--sg-text);
font-size: 15px;
font-weight: 700;
text-transform: uppercase;
}
.person-name {
color: var(--sg-text);
font-size: 13px;
font-weight: 700;
}
.chip-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.topic-chip {
display: inline-flex;
align-items: center;
padding: 6px 12px;
border: 1px solid var(--topic-border);
border-radius: 8px;
background: var(--topic-bg);
color: var(--topic-color);
font-size: 12px;
font-weight: 500;
line-height: 1.25;
}
.purple {
--topic-border: #d8cafe;
--topic-bg: #f6f0ff;
--topic-color: #7255d9;
}
.blue {
--topic-border: #bdd4ff;
--topic-bg: #f0f6ff;
--topic-color: #0b63ce;
}
.green {
--topic-border: #bdebcf;
--topic-bg: #effaf3;
--topic-color: #24834f;
}
.orange {
--topic-border: #ffd796;
--topic-bg: #fff7e8;
--topic-color: #c67500;
}
.pink {
--topic-border: #ffc7d7;
--topic-bg: #fff1f5;
--topic-color: #d12f61;
}
@@ -1,109 +0,0 @@
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { Location, NgClass } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { WorksService } from '../../api';
interface MentionedPerson {
name: string;
is_ude?: boolean;
person_id?: string | null;
}
interface NewsArticleDetail {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
full_content?: string | null;
relevant?: boolean;
authors?: MentionedPerson[];
}
@Component({
selector: 'app-news-detail',
imports: [
MatButtonModule,
MatIconModule,
MatProgressSpinnerModule,
RouterLink,
NgClass,
],
templateUrl: './news-detail.component.html',
styleUrl: './news-detail.component.scss',
})
export class NewsDetailComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute);
private readonly httpClient = inject(HttpClient);
private readonly worksService = inject(WorksService);
private readonly location = inject(Location);
article: NewsArticleDetail | null = null;
loading = false;
notFound = false;
readonly relevantTopics = [
'Künstliche Intelligenz',
'Maschinelles Lernen',
'Digitalisierung',
'Datenwissenschaft',
];
private readonly chipColors = ['purple', 'blue', 'green', 'orange', 'pink'];
chipColor(index: number): string {
return this.chipColors[index % this.chipColors.length];
}
ngOnInit(): void {
this.route.paramMap
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((params) => {
const id = params.get('id');
if (id) {
this.fetchArticle(id);
}
});
}
navigateBack(): void {
this.location.back();
}
formatDate(dateStr?: string | null): string {
if (!dateStr) return '-';
const date = new Date(dateStr);
if (isNaN(date.getTime())) return dateStr;
return new Intl.DateTimeFormat('de-DE', {
day: '2-digit',
month: 'long',
year: 'numeric',
}).format(date);
}
private fetchArticle(id: string): void {
this.loading = true;
this.notFound = false;
const basePath = this.worksService.configuration.basePath ?? '';
this.httpClient
.get<NewsArticleDetail>(`${basePath}/api/news/${encodeURIComponent(id)}`)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: (article) => {
this.article = article;
this.loading = false;
},
error: () => {
this.notFound = true;
this.loading = false;
},
});
}
}
@@ -1,110 +0,0 @@
<div class="page">
<div>
<h6>Nachrichten</h6>
<p>Aktuelle Nachrichten aus Campus-Aktuell.</p>
</div>
<div class="news-toolbar">
<mat-form-field appearance="outline" class="search-field">
<mat-icon matPrefix>search</mat-icon>
<input
matInput
[formControl]="searchControl"
placeholder="Nachrichten durchsuchen..." />
</mat-form-field>
@if (!isSearching) {
<mat-form-field appearance="outline" class="sort-field">
<mat-select
[value]="sortOrder"
(selectionChange)="onSortChange($event.value)">
<mat-option value="desc">Neueste zuerst</mat-option>
<mat-option value="asc">Älteste zuerst</mat-option>
</mat-select>
</mat-form-field>
}
</div>
<div class="table-wrap">
@if (loading) {
<div class="loading">
<mat-spinner diameter="36"></mat-spinner>
</div>
}
<table mat-table [dataSource]="articles" class="mat-elevation-z2">
<ng-container matColumnDef="maintitle">
<th mat-header-cell *matHeaderCellDef>Titel</th>
<td mat-cell *matCellDef="let article">
<a class="article-title" [routerLink]="['/news', article.id]">{{
article.maintitle || 'Kein Titel'
}}</a>
</td>
</ng-container>
<ng-container matColumnDef="snippet">
<th mat-header-cell *matHeaderCellDef>Fundstelle</th>
<td mat-cell *matCellDef="let article">
@if (article.snippet) {
<span class="snippet" [innerHTML]="article.snippet"></span>
} @else {
<span class="snippet-empty">—</span>
}
</td>
</ng-container>
<ng-container matColumnDef="relevance">
<th mat-header-cell *matHeaderCellDef>Relevanz</th>
<td mat-cell *matCellDef="let article">
@if (article.relevant === true) {
<span class="relevance-badge is-relevant">
<mat-icon>check_circle</mat-icon>
Relevant
</span>
} @else if (article.relevant === false) {
<span class="relevance-badge not-relevant">
<mat-icon>cancel</mat-icon>
Nicht relevant
</span>
} @else {
<span class="relevance-badge undetermined">
<mat-icon>help</mat-icon>
Nicht bestimmt
</span>
}
</td>
</ng-container>
<ng-container matColumnDef="date">
<th mat-header-cell *matHeaderCellDef>Datum</th>
<td mat-cell *matCellDef="let article">
{{ formatDate(article.date) }}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
@if (!loading && articles.length === 0) {
<div class="empty-state">
@if (isSearching) {
Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden.
} @else {
Keine Nachrichten gefunden.
}
</div>
}
</div>
<div class="table-footer">
<span>{{ articleRange() }}</span>
<mat-paginator
[length]="total"
[pageIndex]="currentPage - 1"
[pageSize]="paginationService.selection"
[pageSizeOptions]="paginationService.options"
(page)="onPage($event)">
</mat-paginator>
</div>
</div>
@@ -1,209 +0,0 @@
.page {
padding: 28px 32px 42px;
max-width: 100%;
margin: 0 auto;
}
h6 {
margin: 0 0 6px;
font-size: 22px;
line-height: 1.2;
font-weight: 700;
}
.page > div:first-child p {
margin: 0;
color: var(--sg-text-muted);
font-size: 14px;
}
.news-toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
padding-top: 10px;
padding-bottom: 25px;
}
.search-field {
max-width: 480px;
}
::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper {
display: none;
}
::ng-deep .news-toolbar .mat-mdc-text-field-wrapper {
height: 42px;
background: #fff;
border-radius: var(--sg-radius-sm);
}
::ng-deep .news-toolbar .mat-mdc-form-field-infix {
min-height: unset;
height: 42px;
padding: 0;
display: flex;
align-items: center;
}
::ng-deep .news-toolbar .mdc-notched-outline__leading,
::ng-deep .news-toolbar .mdc-notched-outline__notch,
::ng-deep .news-toolbar .mdc-notched-outline__trailing {
border-color: #d9e2f0;
}
::ng-deep .news-toolbar input.mat-mdc-input-element {
color: var(--sg-text);
font-size: 14px;
}
::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder {
color: var(--sg-text-muted);
opacity: 1;
font-size: 14px;
}
.sort-field {
width: 180px;
}
.table-wrap {
position: relative;
overflow-x: auto;
}
table {
width: 100%;
min-width: 600px;
border-collapse: separate;
border-spacing: 0 10px;
background: transparent;
box-shadow: none;
}
.article-title {
display: inline-block;
max-width: 520px;
line-height: 1.35;
color: var(--sg-text);
font-size: 14px;
font-weight: 700;
text-decoration: none;
&:hover {
color: var(--sg-text);
text-decoration: underline;
}
}
.loading {
position: absolute;
inset: 0;
z-index: 1;
display: grid;
place-items: center;
background: rgba(255, 255, 255, 0.65);
}
.empty-state {
padding: 28px;
text-align: center;
color: rgba(0, 0, 0, 0.6);
background: transparent;
}
.snippet {
color: var(--sg-text-muted);
font-size: 13px;
line-height: 1.4;
}
::ng-deep .snippet em {
font-style: normal;
background: #fff48d;
padding: 0 3px;
border-radius: 3px;
}
.snippet-empty {
color: var(--sg-text-muted);
}
.relevance-badge {
display: inline-flex;
align-items: center;
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;
}
}
@@ -1,219 +0,0 @@
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatSelectModule } from '@angular/material/select';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTableModule } from '@angular/material/table';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged } from 'rxjs';
import { WorksService } from '../../api';
import { PaginationService } from '../../shared/services/pagination.service';
interface NewsArticle {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
}
interface NewsPage {
total: number;
page: number;
page_size: number;
results: NewsArticle[];
}
type SortOrder = 'desc' | 'asc';
const DEFAULT_SORT_ORDER: SortOrder = 'desc';
@Component({
selector: 'app-news',
imports: [
MatIconModule,
MatSelectModule,
MatFormFieldModule,
MatInputModule,
MatPaginatorModule,
MatProgressSpinnerModule,
MatTableModule,
ReactiveFormsModule,
RouterLink,
],
templateUrl: './news.component.html',
styleUrl: './news.component.scss',
})
export class NewsComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly httpClient = inject(HttpClient);
private readonly worksService = inject(WorksService);
readonly paginationService = inject(PaginationService);
readonly searchControl = new FormControl('', { nonNullable: true });
get displayedColumns(): string[] {
if (this.isSearching) {
return ['maintitle', 'snippet', 'relevance', 'date'];
}
return ['maintitle', 'relevance', 'date'];
}
articles: NewsArticle[] = [];
total = 0;
loading = false;
currentPage = 1;
sortOrder: SortOrder = DEFAULT_SORT_ORDER;
get isSearching(): boolean {
return this.searchControl.value.trim().length > 0;
}
ngOnInit(): void {
this.route.queryParamMap
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((params) => {
this.currentPage = this.parsePage(params.get('page'));
this.paginationService.selection = this.parsePageSize(
params.get('pageSize'),
);
this.sortOrder = this.parseSortOrder(params.get('sortOrder'));
this.searchControl.setValue(params.get('q') ?? '', {
emitEvent: false,
});
this.load();
});
this.searchControl.valueChanges
.pipe(
debounceTime(300),
distinctUntilChanged(),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((query) => {
this.router.navigate([], {
relativeTo: this.route,
queryParams: { q: query.trim() || null, page: 1 },
queryParamsHandling: 'merge',
});
});
}
load(): void {
this.loading = true;
const query = this.searchControl.value.trim();
const basePath = this.worksService.configuration.basePath ?? '';
if (query) {
const params = new HttpParams()
.set('query', query)
.set('page', this.currentPage)
.set('pageSize', this.paginationService.selection);
this.httpClient
.get<NewsPage>(`${basePath}/api/news/search`, { params })
.subscribe({
next: (page) => {
this.articles = page.results ?? [];
this.total = page.total ?? 0;
this.loading = false;
},
error: () => {
this.articles = [];
this.total = 0;
this.loading = false;
},
});
} else {
const params = new HttpParams()
.set('page', this.currentPage)
.set('pageSize', this.paginationService.selection)
.set('sortOrder', this.sortOrder);
this.httpClient
.get<NewsPage>(`${basePath}/api/news`, { params })
.subscribe({
next: (page) => {
this.articles = page.results ?? [];
this.total = page.total ?? 0;
this.loading = false;
},
error: () => {
this.articles = [];
this.total = 0;
this.loading = false;
},
});
}
}
onPage(event: PageEvent): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
page: event.pageIndex + 1,
pageSize: event.pageSize,
},
queryParamsHandling: 'merge',
});
}
onSortChange(order: SortOrder): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
sortOrder: order,
page: 1,
},
queryParamsHandling: 'merge',
});
}
formatDate(dateStr?: string | null): string {
if (!dateStr) return '-';
const date = new Date(dateStr);
if (isNaN(date.getTime())) return dateStr;
return new Intl.DateTimeFormat('de-DE').format(date);
}
articleRange(): string {
if (this.total === 0) return 'Keine Nachrichten gefunden';
const pageSize = this.paginationService.selection;
const start = (this.currentPage - 1) * pageSize + 1;
const end = Math.min(start + this.articles.length - 1, this.total);
return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`;
}
private parsePage(value: string | null): number {
const page = Number.parseInt(value ?? '', 10);
if (Number.isNaN(page) || page < 1) {
return 1;
}
return page;
}
private parsePageSize(value: string | null): number {
const pageSize = Number.parseInt(value ?? '', 10);
if (this.paginationService.options.includes(pageSize)) {
return pageSize;
}
return 10;
}
private parseSortOrder(value: string | null): SortOrder {
if (value === 'asc' || value === 'desc') {
return value;
}
return DEFAULT_SORT_ORDER;
}
}
@@ -36,25 +36,11 @@ export class PersonCardComponent {
}
institution(person: CustomAuthor): DehydratedInstitution | undefined {
if (person.last_known_institutions?.[0]) {
return person.last_known_institutions[0];
}
const affiliations = person.affiliations ?? [];
let newestInstitution: DehydratedInstitution | undefined =
affiliations[0]?.institution ?? undefined;
let newestYear = -1;
for (const affiliation of affiliations) {
for (const jahr of affiliation.years ?? []) {
if (jahr > newestYear) {
newestYear = jahr;
newestInstitution = affiliation.institution ?? undefined;
}
}
}
return newestInstitution;
return (
person.last_known_institutions?.[0] ||
person.affiliations?.[person.affiliations.length - 1]?.institution ||
undefined
);
}
topics(person: CustomAuthor): WorkTopic[] {
@@ -62,7 +62,7 @@
<option value="cited_by_count">Zitierungen</option>
<option value="summary_stats.h_index">h_index</option>
</select>
<select [formControl]="sortOrderControl">
<option value="desc">Absteigend</option>
<option value="asc">Aufsteigend</option>
@@ -13,7 +13,11 @@ import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatRadioModule } from '@angular/material/radio';
import { ResolverStateService } from '../../shared/services/resolver-state.service';
import { CustomAuthor, PersonsService, InstitutionsService } from '../../api';
import {
CustomAuthor,
PersonsService,
InstitutionsService,
} from '../../api';
import { TopicsService } from '../../api/api/topics.service';
import { TopicHierarchyComponent } from '../topic-hierarchy/topic-hierarchy.component';
import { PersonCardComponent } from '../person-card/person-card.component';
@@ -1,82 +0,0 @@
<div class="page">
<div>
<h6>Nachrichten</h6>
<p>Aktuelle Nachrichten zu dieser Person.</p>
</div>
<div class="news-toolbar">
<mat-form-field appearance="outline" class="search-field">
<mat-icon matPrefix>search</mat-icon>
<input
matInput
[formControl]="searchControl"
placeholder="Nachrichten durchsuchen..." />
</mat-form-field>
<mat-form-field appearance="outline" class="sort-field">
<mat-select
[value]="sortOrder"
(selectionChange)="onSortChange($event.value)">
<mat-option value="desc">Neueste zuerst</mat-option>
<mat-option value="asc">Älteste zuerst</mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="table-wrap">
@if (loading) {
<div class="loading">
<mat-spinner diameter="36"></mat-spinner>
</div>
}
<table mat-table [dataSource]="articles" class="mat-elevation-z2">
<ng-container matColumnDef="maintitle">
<th mat-header-cell *matHeaderCellDef>Titel</th>
<td mat-cell *matCellDef="let article">
<a class="article-title" [routerLink]="['/news', article.id]">{{
article.maintitle || 'Kein Titel'
}}</a>
</td>
</ng-container>
<ng-container matColumnDef="author">
<th mat-header-cell *matHeaderCellDef>Autor</th>
<td mat-cell *matCellDef="let article">
{{ article.author || '-' }}
</td>
</ng-container>
<ng-container matColumnDef="date">
<th mat-header-cell *matHeaderCellDef>Datum</th>
<td mat-cell *matCellDef="let article">
{{ formatDate(article.date) }}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
@if (!loading && articles.length === 0) {
<div class="empty-state">
@if (isSearching) {
Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden.
} @else {
Keine Nachrichten gefunden.
}
</div>
}
</div>
<div class="table-footer">
<span>{{ articleRange() }}</span>
<mat-paginator
[length]="total"
[pageIndex]="currentPageIndex"
[pageSize]="paginationService.selection"
[pageSizeOptions]="paginationService.options"
(page)="onPage($event)">
</mat-paginator>
</div>
</div>
@@ -1,156 +0,0 @@
.page {
padding: 28px 32px 42px;
max-width: 100%;
margin: 0 auto;
}
h6 {
margin: 0 0 6px;
font-size: 22px;
line-height: 1.2;
font-weight: 700;
}
.page > div:first-child p {
margin: 0;
color: var(--sg-text-muted);
font-size: 14px;
}
.news-toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
padding-top: 10px;
padding-bottom: 25px;
}
.search-field {
max-width: 480px;
}
::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper {
display: none;
}
::ng-deep .news-toolbar .mat-mdc-text-field-wrapper {
height: 42px;
background: #fff;
border-radius: var(--sg-radius-sm);
}
::ng-deep .news-toolbar .mat-mdc-form-field-infix {
min-height: unset;
height: 42px;
padding: 0;
display: flex;
align-items: center;
}
::ng-deep .news-toolbar .mdc-notched-outline__leading,
::ng-deep .news-toolbar .mdc-notched-outline__notch,
::ng-deep .news-toolbar .mdc-notched-outline__trailing {
border-color: #d9e2f0;
}
::ng-deep .news-toolbar input.mat-mdc-input-element {
color: var(--sg-text);
font-size: 14px;
}
::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder {
color: var(--sg-text-muted);
opacity: 1;
font-size: 14px;
}
.sort-field {
width: 180px;
}
.table-wrap {
position: relative;
overflow-x: auto;
}
table {
width: 100%;
min-width: 600px;
border-collapse: separate;
border-spacing: 0 10px;
background: transparent;
box-shadow: none;
}
.article-title {
display: inline-block;
max-width: 520px;
line-height: 1.35;
color: var(--sg-text);
font-size: 14px;
font-weight: 700;
text-decoration: none;
&:hover {
color: var(--sg-text);
text-decoration: underline;
}
}
.loading {
position: absolute;
inset: 0;
z-index: 1;
display: grid;
place-items: center;
background: rgba(255, 255, 255, 0.65);
}
.empty-state {
padding: 28px;
text-align: center;
color: rgba(0, 0, 0, 0.6);
background: transparent;
}
::ng-deep .mat-mdc-header-cell {
color: var(--sg-text-muted);
font-size: 12px;
font-weight: 700;
}
::ng-deep .mat-mdc-row {
height: 72px;
}
::ng-deep .mat-mdc-cell {
color: var(--sg-text);
border-bottom-color: var(--sg-border);
font-size: 13px;
}
mat-paginator {
background: transparent;
}
.table-footer {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 66px;
padding: 0 22px 0 28px;
color: var(--sg-text-muted);
font-size: 13px;
}
@media (max-width: 600px) {
.page {
padding: 16px;
}
.table-footer {
align-items: stretch;
flex-direction: column;
}
}
@@ -1,139 +0,0 @@
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 { 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';
@Component({
selector: 'app-person-news',
imports: [
MatIconModule,
MatSelectModule,
MatFormFieldModule,
MatInputModule,
MatPaginatorModule,
MatProgressSpinnerModule,
MatTableModule,
ReactiveFormsModule,
RouterLink,
],
templateUrl: './person-news.component.html',
styleUrl: './person-news.component.scss',
})
export class PersonNewsComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
readonly paginationService = inject(PaginationService);
private readonly resolverStateService = inject(ResolverStateService);
readonly searchControl = new FormControl('', { nonNullable: true });
displayedColumns = ['maintitle', 'author', 'date'];
articles: NewsArticle[] = [];
total = 0;
currentPageIndex = 0;
sortOrder: 'desc' | 'asc' = 'desc';
get loading(): boolean {
return this.resolverStateService.isResolving();
}
get isSearching(): boolean {
return this.searchControl.value.trim().length > 0;
}
ngOnInit(): void {
this.route.data
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(({ newsPage }) => {
const page = newsPage as NewsPage;
this.articles = page.results ?? [];
this.total = page.total ?? 0;
});
this.route.queryParamMap
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((params) => {
const page = params.get('page')
? Number.parseInt(params.get('page')!, 10)
: 1;
const pageSize = params.get('pageSize')
? Number.parseInt(params.get('pageSize')!, 10)
: 10;
const sortOrder = params.get('sortOrder');
const query = params.get('query') ?? '';
this.currentPageIndex = page - 1;
this.paginationService.selection = pageSize;
this.sortOrder = sortOrder === 'asc' ? 'asc' : 'desc';
this.searchControl.setValue(query, { emitEvent: false });
});
this.searchControl.valueChanges
.pipe(
debounceTime(300),
distinctUntilChanged(),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((value) => {
this.updateQueryParams({
query: value.trim() || null,
page: 1,
});
});
}
onPage(event: PageEvent): void {
this.paginationService.selection = event.pageSize;
this.updateQueryParams({
page: event.pageIndex + 1,
pageSize: event.pageSize,
});
}
onSortChange(order: 'desc' | 'asc'): 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<string, string | number | null>,
): void {
void this.router.navigate([], {
relativeTo: this.route,
queryParams: overrides,
queryParamsHandling: 'merge',
});
}
}
@@ -1,179 +1,157 @@
@if (loading) {
<p class="message">Lade Patente...</p>
} @else if (error) {
<p class="message">Fehler beim Laden der Patente.</p>
} @else if (patents.length === 0) {
<p class="message">Keine Patente gefunden.</p>
} @else {
<div class="patents-container">
<div class="patents-summary">
<p class="summary-line">
<span class="summary-value">{{ filteredPatents.length }}</span>
<span class="summary-label"> Patente</span>
</p>
<p class="summary-line">
<span class="summary-value">{{ getEpoCount() }}</span>
<span class="summary-label"> EPO</span>
</p>
<p class="summary-line">
<span class="summary-value">{{ getUsptoCount() }}</span>
<span class="summary-label"> USPTO</span>
</p>
</div>
@if (showDetail && selectedPatent) {
<button class="back-btn" (click)="showDetail = false">
← Zurück zu den Patenten
</button>
}
<div class="patents-content">
@if (showDetail && selectedPatent) {
<div class="patent-full-detail">
<h3>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h3>
@if (selectedPatent.abstract) {
<div class="detail-section">
<h4>Abstract</h4>
<p>{{ selectedPatent.abstract }}</p>
</div>
}
<div class="detail-section">
<h4>Erfinder</h4>
<ul class="tag-list">
@for (inventor of selectedPatent.inventors; track inventor) {
<li class="tag">{{ inventor }}</li>
}
</ul>
</div>
@if (hasAsignees(selectedPatent)) {
<div class="detail-section">
<h4>Anmelder</h4>
<ul class="tag-list">
@for (assignee of selectedPatent.assignees; track assignee) {
<li class="tag">{{ assignee }}</li>
}
</ul>
</div>
}
@if (hasIpcs(selectedPatent)) {
<div class="detail-section">
<h4>Klassifikation (IPC)</h4>
<ul class="tag-list tag-list--compact">
@for (ipc of selectedPatent.ipc; track ipc) {
<li class="tag">{{ ipc }}</li>
}
</ul>
</div>
}
</div>
}
<div class="patents-list" [class.hidden]="showDetail">
<div class="patents-list-toolbar">
<label class="sort-control">
<span>Filter nach Quelle:</span>
<select
[value]="activeFilter"
(change)="setFilter($any($event.target).value)">
<option value="all">Alle</option>
<option value="EPO">EPO</option>
<option value="USPTO">USPTO</option>
</select>
</label>
<label class="sort-control">
<span>Sortieren nach:</span>
<select
[value]="sortMode"
(change)="setSortMode($any($event.target).value)">
<option value="date">Datum</option>
<option value="title">Titel</option>
</select>
</label>
</div>
<table>
<thead>
<tr>
<th>Patent</th>
<th>Quelle</th>
<th>Jahr</th>
</tr>
</thead>
<tbody>
@for (patent of getPagedPatents(); track patent.patent_id) {
<tr
[class.selected]="selectedPatent === patent"
(click)="selectPatent(patent)">
<td class="patent-title">
{{ patent.title ?? patent.patent_id }}
</td>
<td>
<span
class="source-badge source-badge--{{
patent.source.toLowerCase()
}}">
{{ patent.source }}
</span>
</td>
<td>{{ patent.publication_year ?? '-' }}</td>
</tr>
}
</tbody>
</table>
@if (hasPagination()) {
<div class="pagination">
<button
[disabled]="selectedPage === 1"
(click)="setPage(selectedPage - 1)">
Zurück
</button>
<span>Seite {{ selectedPage }} von {{ getPageCount() }}</span>
<button
[disabled]="selectedPage === getPageCount()"
(click)="setPage(selectedPage + 1)">
Weiter
</button>
</div>
}
</div>
@if (selectedPatent) {
<div class="patent-detail">
<h3>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h3>
<div class="detail-stats">
<div class="stat stat--clickable" (click)="openDetail()">
<span class="stat-label">Quelle</span>
<span class="stat-value">
<span
class="source-badge source-badge--{{
selectedPatent.source.toLowerCase()
}}">
{{ selectedPatent.source }}
</span>
</span>
</div>
<div class="stat">
<span class="stat-label">Patent-Nr.</span>
<span class="stat-value">{{ selectedPatent.patent_id }}</span>
</div>
<div class="stat">
<span class="stat-label">Datum</span>
<span class="stat-value">{{
formatDate(selectedPatent.publication_date || '')
}}</span>
</div>
</div>
</div>
} @else {
<div class="patent-detail empty">
<p>Klicke auf ein Patent für Details.</p>
</div>
}
</div>
</div>
}
@if (loading) {
<p class="message">Lade Patente...</p>
} @else if (error) {
<p class="message">Fehler beim Laden der Patente.</p>
} @else if (patents.length === 0) {
<p class="message">Keine Patente gefunden.</p>
} @else {
<div class="patents-container">
<div class="patents-summary">
<p class="summary-line">
<span class="summary-value">{{ filteredPatents.length }}</span>
<span class="summary-label"> Patente</span>
</p>
<p class="summary-line">
<span class="summary-value">{{ getEpoCount() }}</span>
<span class="summary-label"> EPO</span>
</p>
<p class="summary-line">
<span class="summary-value">{{ getUsptoCount() }}</span>
<span class="summary-label"> USPTO</span>
</p>
</div>
@if (showDetail && selectedPatent) {
<button class="back-btn" (click)="showDetail = false">
← Zurück zu den Patenten
</button>
}
<div class="patents-content">
@if (showDetail && selectedPatent) {
<div class="patent-full-detail">
<h3>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h3>
@if (selectedPatent.abstract) {
<div class="detail-section">
<h4>Abstract</h4>
<p>{{ selectedPatent.abstract }}</p>
</div>
}
<div class="detail-section">
<h4>Erfinder</h4>
<ul class="tag-list">
@for (inventor of selectedPatent.inventors; track inventor) {
<li class="tag">{{ inventor }}</li>
}
</ul>
</div>
@if (selectedPatent.assignees.length > 0) {
<div class="detail-section">
<h4>Anmelder</h4>
<ul class="tag-list">
@for (assignee of selectedPatent.assignees; track assignee) {
<li class="tag">{{ assignee }}</li>
}
</ul>
</div>
}
@if (selectedPatent.ipc.length > 0) {
<div class="detail-section">
<h4>Klassifikation (IPC)</h4>
<ul class="tag-list tag-list--compact">
@for (ipc of selectedPatent.ipc; track ipc) {
<li class="tag">{{ ipc }}</li>
}
</ul>
</div>
}
</div>
}
<div class="patents-list" [class.hidden]="showDetail">
<div class="patents-list-toolbar">
<label class="sort-control">
<span>Filter nach Quelle:</span>
<select [value]="activeFilter" (change)="setFilter($any($event.target).value)">
<option value="all">Alle</option>
<option value="EPO">EPO</option>
<option value="USPTO">USPTO</option>
</select>
</label>
<label class="sort-control">
<span>Sortieren nach:</span>
<select [value]="sortMode" (change)="setSortMode($any($event.target).value)">
<option value="date">Datum</option>
<option value="title">Titel</option>
</select>
</label>
</div>
<table>
<thead>
<tr>
<th>Patent</th>
<th>Quelle</th>
<th>Jahr</th>
</tr>
</thead>
<tbody>
@for (patent of getPagedPatents(); track patent.patent_id) {
<tr
[class.selected]="selectedPatent === patent"
(click)="selectPatent(patent)">
<td class="patent-title">{{ patent.title ?? patent.patent_id }}</td>
<td>
<span class="source-badge source-badge--{{ patent.source.toLowerCase() }}">
{{ patent.source }}
</span>
</td>
<td>{{ patent.publication_year ?? '-' }}</td>
</tr>
}
</tbody>
</table>
@if (hasPagination()) {
<div class="pagination">
<button [disabled]="selectedPage === 1" (click)="setPage(selectedPage - 1)">Zurück</button>
<span>Seite {{ selectedPage }} von {{ getPageCount() }}</span>
<button [disabled]="selectedPage === getPageCount()" (click)="setPage(selectedPage + 1)">Weiter</button>
</div>
}
</div>
@if (selectedPatent) {
<div class="patent-detail">
<h3>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h3>
<div class="detail-stats">
<div class="stat stat--clickable" (click)="openDetail()">
<span class="stat-label">Quelle</span>
<span class="stat-value">
<span class="source-badge source-badge--{{ selectedPatent.source.toLowerCase() }}">
{{ selectedPatent.source }}
</span>
</span>
</div>
<div class="stat">
<span class="stat-label">Patent-Nr.</span>
<span class="stat-value">{{ selectedPatent.patent_id }}</span>
</div>
<div class="stat">
<span class="stat-label">Datum</span>
<span class="stat-value">{{ formatDate(selectedPatent.publication_date) }}</span>
</div>
</div>
</div>
} @else {
<div class="patent-detail empty">
<p>Klicke auf ein Patent für Details.</p>
</div>
}
</div>
</div>
}
@@ -1,306 +1,304 @@
.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;
}
.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;
}
}
@@ -1,174 +1,161 @@
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, PatentEntry } from '../../api/api/patents.service';
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;
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;
}
}
@@ -52,7 +52,9 @@
<div class="metric-item">
<mat-icon>event_busy</mat-icon>
<div class="metric-content">
<strong>{{ getFundingStatus(getEndDate()) }}</strong>
<strong>{{
getFundingStatus(getEndDate())
}}</strong>
<span>Enddatum</span>
</div>
</div>
@@ -163,6 +165,7 @@
<dt>Ausführende Stelle</dt>
<dd>
{{ bundProject.executing_agency }}
</dd>
</div>
}
@@ -175,11 +178,12 @@
@if (bundProject.project_agency) {
<div class="detail-row">
<dt>Projektagentur</dt>
<dd>
<dd>
{{
bundProject.project_agency_fullname ||
bundProject.project_agency
}}
</dd>
</div>
}
@@ -221,6 +225,7 @@
<dt>Standort</dt>
<dd>
{{ bundProject.location }}
</dd>
</div>
}
@@ -323,6 +328,7 @@
<dt>Förderart</dt>
<dd>
{{ bundProject.funding_type }}
</dd>
</div>
}
@@ -504,7 +504,7 @@ h1 {
.person-grid {
grid-template-columns: 1fr;
}
.eyebrow {
gap: 8px;
}
@@ -524,4 +524,4 @@ h1 {
width: 100%;
justify-content: center;
}
}
}
@@ -136,9 +136,7 @@
@if (getInstitutions().length > 0) {
<div class="institution-grid">
@for (institution of getInstitutions(); track institution) {
<div
(click)="searchForInstitutionName(institution)"
class="institution-item">
<div (click)="searchForInstitutionName(institution)" class="institution-item">
<mat-icon>apartment</mat-icon>
<span>{{ institution }}</span>
</div>
@@ -205,7 +203,7 @@
<dt>Fördersende</dt>
<dd>{{ getFundingStatus(dfgProject.funding_end_date) }}</dd>
</div>
@if (dfgProject.subproject_of) {
@if (dfgProject.subproject_of ) {
<div class="detail-row">
<dt>Teilprojekt von</dt>
<dd>{{ dfgProject.subproject_of }}</dd>
@@ -282,7 +282,7 @@ h1 {
}
.person-item:hover {
cursor: pointer;
cursor:pointer;
background: #f8fafc;
border-color: #b8c5d6;
}
@@ -302,14 +302,14 @@ h1 {
}
.person-name {
cursor: pointer;
cursor:pointer;
font-size: 13px;
font-weight: 500;
color: var(--sg-text);
}
.institution-grid {
cursor: pointer;
cursor:pointer;
display: grid;
grid-template-columns: 1fr;
gap: 8px;
@@ -464,4 +464,4 @@ h1 {
width: 100%;
justify-content: center;
}
}
}
@@ -16,7 +16,7 @@ export class DfgDetailsComponent implements OnInit {
private route = inject(ActivatedRoute);
dfgProject: DfgProjectDetails | undefined;
constructor(private router: Router) {}
constructor (private router:Router){}
ngOnInit(): void {
this.route.data.subscribe(({ dfgSingleProject }) => {
@@ -46,15 +46,15 @@ export class DfgDetailsComponent implements OnInit {
searchForPersonName(personName: string): void {
this.router.navigate(['/persons'], {
queryParams: {
query: personName,
},
query: personName
}
});
}
searchForInstitutionName(institutionName: string): void {
searchForInstitutionName(institutionName: string): void {
this.router.navigate(['/institutions'], {
queryParams: {
search: institutionName,
},
search: institutionName
}
});
}
/**
@@ -28,11 +28,6 @@
[sortDirection]="urlSortDirection()"
(sortChange)="handleSortChange($event)" />
</mat-tab>
<mat-tab label="EU">
<app-data-table
[columns]="personCordisEuProjectColumns"
[data]="personCordisEuProjectData" />
</mat-tab>
</mat-tab-group>
<mat-paginator
[length]="this.pageTotal()"
@@ -71,25 +66,3 @@
</ul>
</div>
</ng-template>
<ng-template #euProjectsFundingStartTmp let-element>
{{ element.startDate | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #euProjectsFundingEndTmp let-element>
{{ element.endDate | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #euProjectsFundingAmountTmp let-element>
{{ element.ecMaxContribution | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }}
</ng-template>
<ng-template #euProjectsActionsTmp let-element>
<a
[routerLink]="['/projects/eu', element.id]"
target="_blank"
mat-icon-button
color="primary">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
@@ -8,12 +8,7 @@ import {
TemplateRef,
viewChild,
} from '@angular/core';
import {
CordisEuProject,
CordisEuProjectPage,
DfgProjectPage,
DfgProjectSummary,
} from '../../api';
import { DfgProjectPage, DfgProjectSummary } from '../../api';
import {
DataTableComponent,
GenericColumn,
@@ -29,7 +24,6 @@ import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { Sort, SortDirection } from '@angular/material/sort';
import { CurrencyPipe, DatePipe } from '@angular/common';
@Component({
selector: 'app-person-projects',
@@ -44,8 +38,6 @@ import { CurrencyPipe, DatePipe } from '@angular/common';
DebounceDirective,
MatPaginatorModule,
RouterModule,
DatePipe,
CurrencyPipe,
],
templateUrl: './person-projects.component.html',
styleUrl: './person-projects.component.scss',
@@ -65,23 +57,6 @@ export class PersonProjectsComponent implements OnInit {
'dfgProjectDetailRowTmp',
);
personCordisEuProjectPage = input.required<CordisEuProjectPage>();
personCordisEuProjectColumns: GenericColumn<CordisEuProject>[] = [];
personCordisEuProjectData: CordisEuProject[] = [];
euProjectsFundingStartTmp = viewChild.required<TemplateRef<any>>(
'euProjectsFundingStartTmp',
);
euProjectsFundingEndTmp = viewChild.required<TemplateRef<any>>(
'euProjectsFundingEndTmp',
);
euProjectsFundingAmountTmp = viewChild.required<TemplateRef<any>>(
'euProjectsFundingAmountTmp',
);
euProjectsActionsTmp = viewChild.required<TemplateRef<any>>(
'euProjectsActionsTmp',
);
urlSearchTerm = signal<string>('');
urlSortKey = signal<string>('');
urlSortDirection = signal<SortDirection>('');
@@ -108,25 +83,19 @@ export class PersonProjectsComponent implements OnInit {
this.urlSearchTerm.set(params.get('search') || '');
});
effect(() => {
this.dfgProjectData = this.dfgProjectPage().elements || [];
});
effect(() => {
console.log(
'Updating personCordisEuProjectData with',
this.personCordisEuProjectPage(),
'PersonProjectsComponent: dfgProjectPage changed',
this.dfgProjectPage(),
);
this.personCordisEuProjectData =
this.personCordisEuProjectPage().elements || [];
this.dfgProjectData = this.dfgProjectPage().elements || [];
});
effect(() => {
const searchTerm = this.urlSearchTerm();
if (searchTerm) {
this.router.navigate([], {
queryParams: { search: searchTerm, page: 0, size: this.pageSize() },
queryParams: { search: searchTerm },
queryParamsHandling: 'merge',
});
}
@@ -162,39 +131,6 @@ export class PersonProjectsComponent implements OnInit {
cellTemplate: this.dfgProjectActionsTmp(),
},
];
this.personCordisEuProjectColumns = [
{
id: 'title',
header: 'Titel',
type: 'accessor',
accessorKey: 'title',
},
{
id: 'startDate',
header: 'Startdatum',
type: 'display',
cellTemplate: this.euProjectsFundingStartTmp(),
},
{
id: 'endDate',
header: 'Enddatum',
type: 'display',
cellTemplate: this.euProjectsFundingEndTmp(),
},
{
id: 'ecMaxContribution',
header: 'Förderbetrag (EU)',
type: 'display',
cellTemplate: this.euProjectsFundingAmountTmp(),
},
{
id: 'actions',
header: '',
type: 'display',
cellTemplate: this.euProjectsActionsTmp(),
},
];
}
handleSearchTermChange(newTerm: string): void {
@@ -5,6 +5,16 @@
</div>
<div class="publication-filter-stack">
<form class="publication-filters" [formGroup]="filterForm">
<mat-form-field class="publication-search">
<mat-icon matPrefix>search</mat-icon>
<input
type="search"
matInput
[formControl]="publicationSearchControl"
placeholder="Publikationen suchen"
aria-label="Publikationen suchen" />
</mat-form-field>
<mat-form-field>
<mat-select
placeholder="Jahr"
@@ -141,12 +151,6 @@
</div>
<div class="table-wrap">
@if (loading) {
<div class="loading">
<mat-spinner diameter="36"></mat-spinner>
</div>
}
<table mat-table [dataSource]="publications" class="mat-elevation-z2">
<ng-container matColumnDef="title">
<th mat-header-cell *matHeaderCellDef>Titel</th>
@@ -180,12 +184,27 @@
</ng-container>
<ng-container matColumnDef="language">
<th mat-header-cell *matHeaderCellDef>Sprache / Quelle</th>
<th mat-header-cell *matHeaderCellDef>Sprache</th>
<td mat-cell *matCellDef="let publication">
{{ publication.language || '-' }}
</td>
</ng-container>
<ng-container matColumnDef="publisher">
<th mat-header-cell *matHeaderCellDef>Publisher</th>
<td mat-cell *matCellDef="let publication">
@if (publication.primary_location?.source?.display_name) {
<span
class="publication-source"
[title]="publication.primary_location.source.display_name">
{{ publication.primary_location.source.display_name }}
</span>
} @else {
<span class="empty-text">-</span>
}
</td>
</ng-container>
<ng-container matColumnDef="institutions">
<th mat-header-cell *matHeaderCellDef>Institutionen</th>
<td mat-cell *matCellDef="let publication">
@@ -244,7 +263,7 @@
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
@if (!loading && publications.length === 0) {
@if (publications.length === 0) {
<div class="empty-state">Keine Publikationen gefunden.</div>
}
</div>
@@ -46,6 +46,10 @@ h2 {
width: 150px;
}
.publication-filters .publication-search {
width: 320px;
}
.publication-filters .institution-filter,
.publication-filters .topic-filter {
width: 320px;
@@ -164,7 +168,7 @@ h2 {
table {
width: 100%;
min-width: 1120px;
min-width: 1240px;
border-collapse: separate;
border-spacing: 0 10px;
overflow: hidden;
@@ -193,15 +197,6 @@ a.title:hover {
font-size: 12px;
}
.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;
@@ -213,6 +208,14 @@ a.title:hover {
color: rgba(0, 0, 0, 0.54);
}
.publication-source {
display: inline-block;
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.topic-chips {
display: flex;
flex-wrap: wrap;
@@ -336,7 +339,8 @@ mat-paginator {
}
.publication-filters .institution-filter,
.publication-filters .topic-filter {
.publication-filters .topic-filter,
.publication-filters .publication-search {
width: 100%;
}
@@ -18,8 +18,6 @@ import {
MatPaginatorModule,
PageEvent,
} from '@angular/material/paginator';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
@@ -37,9 +35,8 @@ import {
switchMap,
} from 'rxjs';
import { Work, WorksService } from '../../api';
import { Work, WorkPage, WorksService } from '../../api';
import { PaginationService } from '../../shared/services/pagination.service';
import { createLoadError } from '../../shared/utils/errorHandler';
import { ChipComponent } from '../../shared/ui/chip/chip.component';
interface InstitutionAutocompleteOption {
@@ -73,6 +70,7 @@ interface TopicAutocompleteResponse {
interface PublicationFilterQueryState {
pageIndex: number;
pageSize: number;
search: string;
publicationYears: number[];
types: string[];
languages: string[];
@@ -90,9 +88,7 @@ interface PublicationFilterQueryState {
MatFormFieldModule,
MatInputModule,
MatPaginatorModule,
MatProgressSpinnerModule,
MatSelectModule,
MatSnackBarModule,
MatTableModule,
ReactiveFormsModule,
RouterLink,
@@ -109,21 +105,21 @@ export class PersonPublicationsComponent implements OnInit {
'type',
'year',
'language',
'publisher',
'institutions',
'topics',
'citations',
];
publications: Work[] = [];
total = 0;
loading = false;
institutionLookupLoading = false;
topicLookupLoading = false;
authorId = '';
currentPageIndex = 0;
institutionOptions: InstitutionAutocompleteOption[] = [];
selectedInstitutions: InstitutionAutocompleteOption[] = [];
topicOptions: TopicAutocompleteOption[] = [];
selectedTopics: TopicAutocompleteOption[] = [];
readonly publicationSearchControl = new FormControl('', { nonNullable: true });
readonly institutionSearchControl = new FormControl<
string | InstitutionAutocompleteOption
>('', { nonNullable: true });
@@ -151,6 +147,7 @@ export class PersonPublicationsComponent implements OnInit {
institutionNames: 'publicationInstitutionName',
topicIds: 'publicationTopicId',
topicNames: 'publicationTopicName',
search: 'publicationSearch',
} as const;
readonly typeOptions = [
@@ -186,57 +183,19 @@ export class PersonPublicationsComponent implements OnInit {
private readonly workService: WorksService,
private readonly httpClient: HttpClient,
public readonly paginationService: PaginationService,
private readonly snackBar: MatSnackBar,
) {}
ngOnInit(): void {
this.setupPublicationSearch();
this.setupInstitutionAutocomplete();
this.setupTopicAutocomplete();
const parentParamMap = this.route.parent?.paramMap;
if (!parentParamMap) return;
combineLatest([parentParamMap, this.route.queryParamMap])
combineLatest([this.route.data, this.route.queryParamMap])
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(([params, queryParams]) => {
this.authorId = params.get('id') ?? '';
.subscribe(([data, queryParams]) => {
const queryState = this.parsePublicationFilterQueryParams(queryParams);
this.applyPublicationFilterQueryState(queryState);
this.load(queryState.pageIndex, queryState.pageSize);
});
}
load(pageIndex = 0, pageSize = this.paginationService.selection): void {
console.log('Loading publications for author ID:', this.authorId);
if (!this.authorId) return;
this.loading = true;
this.workService
.getAuthorWorks(
this.authorId,
pageIndex + 1,
pageSize,
this.filters().publicationYears,
this.filters().types,
this.filters().languages,
this.selectedInstitutionIds(),
this.selectedTopicIds(),
)
.subscribe({
next: (page) => {
this.publications = page.elements ?? [];
this.total = page.total ?? 0;
this.loading = false;
},
error: (error) => {
this.loading = false;
createLoadError(
this.snackBar,
() => this.load(pageIndex, pageSize),
'Publikationen konnten nicht geladen werden',
)(error);
},
this.applyPublicationPage(data['publicationPage'] as WorkPage);
});
}
@@ -266,6 +225,7 @@ export class PersonPublicationsComponent implements OnInit {
});
this.selectedInstitutions = [];
this.selectedTopics = [];
this.publicationSearchControl.setValue('', { emitEvent: false });
this.institutionOptions = [];
this.topicOptions = [];
this.institutionSearchControl.setValue('', { emitEvent: false });
@@ -280,6 +240,7 @@ export class PersonPublicationsComponent implements OnInit {
[this.queryParamKeys.institutionNames]: null,
[this.queryParamKeys.topicIds]: null,
[this.queryParamKeys.topicNames]: null,
[this.queryParamKeys.search]: null,
});
}
@@ -379,6 +340,27 @@ export class PersonPublicationsComponent implements OnInit {
};
}
private applyPublicationPage(page: WorkPage): void {
this.publications = page.elements ?? [];
this.total = page.total ?? 0;
}
private setupPublicationSearch(): void {
this.publicationSearchControl.valueChanges
.pipe(
map((value) => value.trim()),
debounceTime(350),
distinctUntilChanged(),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((search) => {
this.updatePublicationFilterQueryParams({
[this.queryParamKeys.page]: 1,
[this.queryParamKeys.search]: search || null,
});
});
}
private setupInstitutionAutocomplete(): void {
this.institutionSearchControl.valueChanges
.pipe(
@@ -535,6 +517,7 @@ export class PersonPublicationsComponent implements OnInit {
queryParams.get(this.queryParamKeys.pageSize),
this.paginationService.selection,
),
search: queryParams.get(this.queryParamKeys.search)?.trim() ?? '',
publicationYears: this.parseNumberParams(
queryParams.getAll(this.queryParamKeys.years),
),
@@ -562,6 +545,9 @@ export class PersonPublicationsComponent implements OnInit {
this.paginationService.selection = queryState.pageSize;
this.selectedInstitutions = queryState.institutions;
this.selectedTopics = queryState.topics;
this.publicationSearchControl.setValue(queryState.search, {
emitEvent: false,
});
this.filterForm.setValue(
{
publicationYears: queryState.publicationYears,
@@ -119,20 +119,15 @@ export class PersonComponent {
() => this.person()?.affiliations?.[0] ?? null,
);
readonly lastAffiliation = computed(() => {
const affiliations = this.person()?.affiliations ?? [];
let newestAffiliation = affiliations[0] ?? null;
let newestYear = -1;
for (const affiliation of affiliations) {
for (const jahr of affiliation.years ?? []) {
if (jahr > newestYear) {
newestYear = jahr;
newestAffiliation = affiliation;
}
}
let lastAffiliation: number | undefined = 0;
if (this.person()?.affiliations?.length != undefined) {
lastAffiliation = this.person()?.affiliations?.length;
}
return newestAffiliation;
return (
(lastAffiliation
? this.person()?.affiliations?.[lastAffiliation - 1]
: this.person()?.affiliations?.[0]) ?? null
);
});
readonly institution = computed(
() =>
@@ -191,7 +186,6 @@ export class PersonComponent {
{ label: 'Netzwerk', path: 'network', disabled: false },
{ label: 'Unternehmen', path: 'company-connections', disabled: false },
{ label: 'Förderungen', path: 'funding', disabled: false },
{ label: 'Nachrichten', path: 'news', disabled: false },
{ label: 'Patente', path: 'patents', disabled: false },
];
@@ -66,7 +66,7 @@ export class ProjectsComponent {
handleSearchTermChange(newTerm: string): void {
this.router.navigate([], {
queryParams: { search: newTerm, page: 0, size: 10 },
queryParams: { search: newTerm },
queryParamsHandling: 'merge',
});
}
@@ -107,15 +107,17 @@
<div class="content-grid">
<main>
@if (abstractText(); as abstract) {
<section class="card abstract-card">
<div class="section-title">
<mat-icon>subject</mat-icon>
<h2>Abstract</h2>
</div>
<section class="card abstract-card">
<div class="section-title">
<mat-icon>subject</mat-icon>
<h2>Abstract</h2>
</div>
@if (abstractText(); as abstract) {
<p>{{ abstract }}</p>
</section>
}
} @else {
<p class="empty">Kein Abstract verfügbar.</p>
}
</section>
<section class="card">
<div class="section-title">
@@ -261,6 +263,12 @@
<dt>Sprache</dt>
<dd>{{ publication.language || '-' }}</dd>
</div>
<div>
<dt>Publisher</dt>
<dd>
{{ publication.primary_location?.source?.display_name || '-' }}
</dd>
</div>
<div>
<dt>Open Access</dt>
<dd>{{ openAccessLabel() }}</dd>
@@ -73,6 +73,11 @@ export class PublicationDetailComponent implements OnInit {
}
abstractText(): string | null {
const plainAbstract = (
this.publication as (Work & { abstract?: string | null }) | null
)?.abstract?.trim();
if (plainAbstract) return plainAbstract;
const index = this.publication?.abstract_inverted_index;
if (!index || typeof index !== 'object') return null;
@@ -2,13 +2,10 @@
import { inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { InstitutionsService, RankingResponse } from '../../../api';
export type ResearchTopic =
| 'Artificial Intelligence'
| 'Quantum Computing'
| 'Renewable Energy'
| 'Biotechnology';
export type ResearchTopic = 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology';
export type DashboardMetric = 'publications' | 'citations';
@Injectable({ providedIn: 'root' })
export class UniversityRankingService {
private apiService = inject(InstitutionsService);
@@ -17,13 +14,7 @@ export class UniversityRankingService {
* Fetches ranking and timeseries data directly from the backend.
* Calculations for growth and trends are now handled server-side.
*/
getRankingData(
topic: ResearchTopic,
metric: DashboardMetric,
): Observable<RankingResponse> {
return this.apiService.getRankingsApiInseServiceUniversityRankingsGet(
topic,
metric,
);
getRankingData(topic: ResearchTopic, metric: DashboardMetric): Observable<RankingResponse> {
return this.apiService.getRankingsApiInseServiceUniversityRankingsGet(topic, metric);
}
}
@@ -2,4 +2,5 @@
echarts
[options]="chartOption"
[merge]="mergeOption"
class="chart-container"></div>
class="chart-container">
</div>
@@ -1,4 +1 @@
.chart-container {
height: 500px;
width: 100%;
}
.chart-container { height: 500px; width: 100%; }
@@ -1,13 +1,9 @@
// src/app/modules/university-ranking/components/line-chart/university-line-chart.component.ts
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { NgxEchartsDirective} from 'ngx-echarts';
import { UniversityTopicData, YearlyData } from '../../../api';
export type ResearchTopic =
| 'Artificial Intelligence'
| 'Quantum Computing'
| 'Renewable Energy'
| 'Biotechnology';
export type ResearchTopic = 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology';
export type DashboardMetric = 'publications' | 'citations';
@Component({
@@ -16,24 +12,21 @@ export type DashboardMetric = 'publications' | 'citations';
styleUrl: './uni-line-chart.component.scss',
imports: [NgxEchartsDirective],
standalone: true,
})
export class UniversityLineChartComponent implements OnChanges {
@Input() data: UniversityTopicData[] = [];
@Input() metric: DashboardMetric = 'publications';
chartOption: EChartsOption = {
title: {
text: 'Research Output Over Time',
left: 'center',
textStyle: { fontWeight: 'lighter' },
},
title: { text: 'Research Output Over Time', left: 'center', textStyle: { fontWeight: 'lighter' } },
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
legend: { bottom: 0 },
grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true },
xAxis: { type: 'category', boundaryGap: false, data: [] },
yAxis: { type: 'value', name: 'Volume' },
dataZoom: [{ type: 'slider', show: true, bottom: 40 }],
series: [],
series: []
};
mergeOption: EChartsOption = {};
@@ -41,24 +34,24 @@ export class UniversityLineChartComponent implements OnChanges {
ngOnChanges(changes: SimpleChanges): void {
if (this.data.length > 0) {
this.updateChart();
console.log('CHANGES!');
console.log("CHANGES!")
}
}
private updateChart() {
const years = this.data[0].yearly_data.map((d) => d.year);
const series = this.data.map((uni) => ({
const years = this.data[0].yearly_data.map(d => d.year);
const series = this.data.map(uni => ({
name: uni.university,
type: 'line',
smooth: true,
emphasis: { focus: 'series' },
animationDuration: 2000,
data: uni.yearly_data.map((d) => d[this.metric]),
data: uni.yearly_data.map(d => d[this.metric])
}));
this.mergeOption = {
xAxis: { data: years.map(String) },
series: series as any,
series: series as any
};
}
}
@@ -2,7 +2,7 @@
<h4>Topic Rankings</h4>
@if (loading) {
<div class="skeleton-loader">Loading rankings...</div>
} @else {
} @else{
<table class="ranking-table">
<thead>
<tr>
@@ -7,7 +7,8 @@ import { DecimalPipe } from '@angular/common';
selector: 'app-university-ranking-table',
templateUrl: './uni-ranking-table.component.html',
styleUrls: ['./uni-ranking-table.component.scss'],
imports: [DecimalPipe],
imports:[DecimalPipe],
})
export class UniversityRankingTableComponent {
@Input() rankings: UniversityRanking[] = [];
@@ -19,9 +19,9 @@ export const bundProjectPageResolver: ResolveFn<BundProjectPage> = (
institutionId = route.parent?.paramMap.get('institutionId') ?? null;
}
const sortBy = (route.queryParamMap.get('sort_by') ||
const sortBy = (route.queryParamMap.get('sort_by') ??
'title') as ProjectsSortBy;
const sortDirection = (route.queryParamMap.get('sort_direction') ||
const sortDirection = (route.queryParamMap.get('sort_direction') ??
'asc') as SortDirection;
const search = route.queryParamMap.get('search');
@@ -13,4 +13,4 @@ export const bundSingleProjectResolver: ResolveFn<BundProjectDetails> = (
throw new Error('BUND Project ID is required');
}
return projectsService.getSingleBundProject(projectId);
};
};
@@ -1,13 +1,8 @@
import { ResolveFn } from '@angular/router';
import {
EuOrganizationProjectSummaryPage,
ProjectsService,
ProjectsSortBy,
SortDirection,
} from '../api';
import { CordisEuProjectPage, ProjectsService } from '../api';
import { inject } from '@angular/core';
export const cordisEuProjectPageResolver: ResolveFn<EuOrganizationProjectSummaryPage> = (
export const cordisEuProjectPageResolver: ResolveFn<CordisEuProjectPage> = (
route,
state,
) => {
@@ -18,10 +13,8 @@ export const cordisEuProjectPageResolver: ResolveFn<EuOrganizationProjectSummary
institutionId = route.parent?.paramMap.get('institutionId') ?? null;
}
const sortBy = (route.queryParamMap.get('sort_by') ||
'title') as ProjectsSortBy;
const sortDirection = (route.queryParamMap.get('sort_direction') ||
'asc') as SortDirection;
const sortBy = route.queryParamMap.get('sort_by') ?? 'title';
const sortDirection = route.queryParamMap.get('sort_direction') ?? 'asc';
const search = route.queryParamMap.get('search');
return inject(ProjectsService).searchCordisEuProjects({
@@ -30,7 +23,7 @@ export const cordisEuProjectPageResolver: ResolveFn<EuOrganizationProjectSummary
size: Number(size),
raw_oa_institution_id: institutionId,
query: search,
sort_by: sortBy,
sort_direction: sortDirection,
sort_by: sortBy as 'title' | 'funding_start' | 'funding_end',
sort_direction: sortDirection as 'asc' | 'desc',
});
};
@@ -13,4 +13,4 @@ export const dfgSingleProjectResolver: ResolveFn<DfgProjectDetails> = (
throw new Error('DFG Project ID is required');
}
return projectsService.getSingleDfgProject(projectId);
};
};
@@ -1,13 +0,0 @@
import { ResolveFn } from '@angular/router';
import { CordisEuProjectPage, ProjectsService } from '../api';
import { inject } from '@angular/core';
export const personCordisEuProjectPageResolver: ResolveFn<
CordisEuProjectPage
> = (route, state) => {
const rawAuthorId = route.parent?.params['id'];
if (!rawAuthorId) {
throw new Error('Author ID is required to resolve collaboration network');
}
return inject(ProjectsService).getEuProjectsForAuthor(rawAuthorId);
};
@@ -1,57 +0,0 @@
import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { of } from 'rxjs';
import { WorksService } from '../api';
export interface NewsArticle {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
}
export interface NewsPage {
total: number;
page: number;
page_size: number;
results: NewsArticle[];
}
export const personNewsResolver: ResolveFn<NewsPage> = (route) => {
const httpClient = inject(HttpClient);
const worksService = inject(WorksService);
const authorId = route.parent?.paramMap.get('id');
if (!authorId) {
return of({ total: 0, page: 1, page_size: 0, results: [] });
}
const queryParams = route.queryParamMap;
const page = queryParams.get('page')
? Number.parseInt(queryParams.get('page')!, 10)
: 1;
const pageSize = queryParams.get('pageSize')
? Number.parseInt(queryParams.get('pageSize')!, 10)
: 10;
const sortOrder = queryParams.get('sortOrder') || 'desc';
const query = queryParams.get('query') || '';
let params = new HttpParams()
.set('authorId', authorId)
.set('page', page)
.set('pageSize', pageSize)
.set('sortOrder', sortOrder);
if (query) {
params = params.set('query', query);
}
const basePath = worksService.configuration.basePath ?? '';
return httpClient.get<NewsPage>(`${basePath}/api/news/by-author`, { params });
};
@@ -6,6 +6,7 @@ export const personResolver: ResolveFn<AuthorsListResponse> = (
route,
state,
) => {
const PERSON_INCLUDE_TAGS =
'topics_full,topic_share,summary_stats,ids,last_known_institutions,' +
'sources,counts_by_year,works_api_url,dates,cited_by_count_boost';
@@ -0,0 +1,36 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { WorkPage, WorksService } from '../api';
import { PaginationService } from '../shared/services/pagination.service';
export const publicationsResolver: ResolveFn<WorkPage> = (route) => {
const authorId = route.parent?.paramMap.get('id');
if (!authorId) {
throw new Error('Author ID is required to resolve publications');
}
const params = route.queryParamMap;
const pageSize = inject(PaginationService).selection;
return inject(WorksService).getAuthorWorks(
authorId,
parsePositiveInteger(params.get('publicationPage'), 1),
parsePositiveInteger(params.get('publicationPageSize'), pageSize),
params
.getAll('publicationYear')
.map(Number)
.filter(Number.isInteger),
params.getAll('publicationType').filter(Boolean),
params.getAll('publicationLanguage').filter(Boolean),
params.getAll('publicationInstitutionId').filter(Boolean),
params.getAll('publicationTopicId').filter(Boolean),
params.get('publicationSearch')?.trim() || undefined,
);
};
function parsePositiveInteger(value: string | null, fallback: number): number {
const parsedValue = Number(value);
return Number.isInteger(parsedValue) && parsedValue > 0
? parsedValue
: fallback;
}
@@ -59,7 +59,7 @@
icon="person"
[size]="200"
[diameter]="200" />
} @else if (resolverState.isResolvingFromOutside('/projects/')) {
} @else if (resolverState.isResolvingFromOutside('/projects/')){
<app-loading
text="Projektdaten werden geladen..."
icon="article"
@@ -46,12 +46,6 @@ export class AppMenuComponent {
},
disabled: false,
},
{
label: 'News',
icon: 'newspaper',
route: '/news',
disabled: false,
},
{
label: 'Institutionen',
icon: 'apartment',