Merge branch 'dev' into researchers-to-projects
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit

This commit is contained in:
Mats Paul Tončik
2026-06-21 16:07:03 +02:00
68 changed files with 4478 additions and 120 deletions
+11 -1
View File
@@ -1,3 +1,13 @@
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
LLM_MODEL=gemma4-e4b
# Patent search (EPO + USPTO)
PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic
PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
@@ -6,4 +16,4 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
LLM_MODEL=gemma4-e4b
LLM_MODEL=gemma4-e4b
+5
View File
@@ -39,6 +39,11 @@ class Settings(BaseSettings):
openalex_api_key: Optional[str] = None
openalex_api_timeout_seconds: float = 30.0
# Patent elasticsearch config
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
patent_elasticsearch_api_key: str = ""
# LLM config
llm_api_url: Optional[str] = None
llm_api_key: Optional[str] = None
@@ -89,6 +89,7 @@ def search(
sort: Optional[List] = None,
body: Optional[Dict] = None,
track_total_hits=False,
highlight: Optional[Dict] = None,
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
"""Searches the specified Elasticsearch index using either a simple query string or a full query body.
@@ -147,6 +148,8 @@ 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(
+8
View File
@@ -24,6 +24,12 @@ from inse.persons.service import router as persons_service_router
from inse.projects.router import router as projects_router
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
from . import config
from .account.service import router as account_router
@@ -48,9 +54,11 @@ 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)
app.include_router(patents_service_router)
app.include_router(university_ranking_router)
app.include_router(projects_router)
+274
View File
@@ -0,0 +1,274 @@
#!/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
@@ -0,0 +1,35 @@
#!/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
@@ -0,0 +1,105 @@
#!/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)
@@ -0,0 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Patents domain package.
"""
@@ -0,0 +1,182 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP client for patent searches in EPO and USPTO Elasticsearch indices.
"""
from typing import Any
import httpx
from .. import config
from .name_matching import search_name_variants
EPO_INDEX = "epo_index_1.0"
USPTO_INDEX = "uspto_patents_3.0"
DEFAULT_SEARCH_SIZE = 100
def _match_name_field(field: str, name: str) -> dict[str, Any]:
"""Match a name field, including transliterated variants (Müller/Mueller)."""
variants = search_name_variants(name)
if len(variants) <= 1:
return {"match": {field: variants[0] if variants else name}}
return {
"bool": {
"should": [{"match": {field: variant}} for variant in variants],
"minimum_should_match": 1,
}
}
class MissingApiKeyError(Exception):
pass
class PatentSearchClient:
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout: float = 30.0,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
self.timeout = timeout
self.transport = transport
def _headers(self) -> dict[str, str]:
if not self.api_key:
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
return {
"Authorization": f"ApiKey {self.api_key}",
"Content-Type": "application/json",
}
def epo_query_by_inventor(
self,
last_name: str,
first_name: str | None = None,
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
"""Search EPO index: first AND last name in the SAME inventor entry."""
if first_name:
query = {
"nested": {
"path": "inventors_name_nested",
"query": {
"bool": {
"must": [
_match_name_field("inventors_name_nested.inventor", last_name),
_match_name_field("inventors_name_nested.inventor", first_name),
]
}
},
}
}
else:
query = {
"nested": {
"path": "inventors_name_nested",
"query": _match_name_field("inventors_name_nested.inventor", last_name),
}
}
return {
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"date_publication": {"order": "desc", "missing": "_last"}},
"_doc",
],
"_source": [
"doc_number",
"country",
"kind",
"date_publication",
"date_publication_year",
"title_en",
"title_de",
"abstract",
"inventors_name",
"applicants_name",
"ipc",
"ipc_text",
],
"query": query,
}
def uspto_query_by_inventor(
self,
last_name: str,
first_name: str | None = None,
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
"""Search USPTO index: first AND last name in the SAME inventor entry."""
if first_name:
query = {
"nested": {
"path": "inventors",
"query": {
"bool": {
"must": [
_match_name_field("inventors.name", last_name),
_match_name_field("inventors.name", first_name),
]
}
},
}
}
else:
query = {
"nested": {
"path": "inventors",
"query": _match_name_field("inventors.name", last_name),
}
}
return {
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"publication_date": {"order": "desc", "missing": "_last"}},
"_doc",
],
"_source": [
"publication_number",
"country",
"publication_date",
"publication_year",
"title",
"abstract",
"inventors_names",
"inventors_names_text",
"assignees_orgs",
"ipcr",
"ipcr_text",
],
"query": query,
}
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
return await self._search(EPO_INDEX, payload)
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
return await self._search(USPTO_INDEX, payload)
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{index}/_search",
headers=self._headers(),
json=payload,
)
response.raise_for_status()
return response.json()
+156
View File
@@ -0,0 +1,156 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for patent matching by author name.
"""
import logging
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from ..persons import logic as person_logic
from ..models.openalex.author import Author
from . import model
from .elastic_search_client import MissingApiKeyError
from .elastic_search_client import PatentSearchClient
from .name_matching import name_matches
logger = logging.getLogger(__name__)
async def get_patents_by_author_id(
author_id: str,
client: PatentSearchClient | None = None,
) -> model.PatentsByAuthorResponse:
search_client = client or PatentSearchClient()
author = _get_author(author_id)
if not author:
return model.PatentsByAuthorResponse(
author_id=author_id,
author_name=None,
patent_count=0,
patents=[],
)
author_name = author.display_name
last_name = _extract_last_name(author_name)
first_name = _extract_first_name(author_name)
if not last_name:
return model.PatentsByAuthorResponse(
author_id=author_id,
author_name=author_name,
patent_count=0,
patents=[],
)
try:
epo_data, uspto_data = await _search_both_indices(
search_client, last_name, first_name
)
except MissingApiKeyError as exc:
raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.") from exc
except httpx.HTTPError as exc:
raise HTTPException(status_code=HTTP_502_BAD_GATEWAY,
detail="Patent search request failed.") from exc
all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
if first_name and last_name:
all_patents = _filter_patents_by_name(all_patents, first_name, last_name)
return model.PatentsByAuthorResponse(
author_id=author_id,
author_name=author_name,
patent_count=len(all_patents),
patents=all_patents,
)
async def _search_both_indices(client, last_name, first_name):
import asyncio
epo_result, uspto_result = await asyncio.gather(
client.search_epo(client.epo_query_by_inventor(last_name, first_name)),
client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)),
)
return epo_result, uspto_result
def _parse_epo_hits(data: dict) -> list[model.PatentEntry]:
patents = []
for hit in data.get("hits", {}).get("hits", []):
src = hit.get("_source", {})
inventors = src.get("inventors_name") or []
applicants = src.get("applicants_name") or []
ipc = src.get("ipc") or []
patents.append(model.PatentEntry(
patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
source="EPO",
title=src.get("title_en") or src.get("title_de"),
abstract=src.get("abstract"),
publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
inventors=inventors if isinstance(inventors, list) else [inventors],
assignees=applicants if isinstance(applicants, list) else [applicants],
ipc=ipc if isinstance(ipc, list) else [ipc],
country=src.get("country", "EP"),
))
return patents
def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
patents = []
for hit in data.get("hits", {}).get("hits", []):
src = hit.get("_source", {})
inventors = src.get("inventors_names") or []
assignees = src.get("assignees_orgs") or []
ipc = src.get("ipcr") or []
patents.append(model.PatentEntry(
patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
source="USPTO",
title=src.get("title"),
abstract=src.get("abstract"),
publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
inventors=inventors if isinstance(inventors, list) else [inventors],
assignees=assignees if isinstance(assignees, list) else [assignees],
ipc=ipc if isinstance(ipc, list) else [ipc],
country=src.get("country", "US"),
))
return patents
def _filter_patents_by_name(
patents: list[model.PatentEntry],
first_name: str,
last_name: str,
) -> list[model.PatentEntry]:
"""Keep patents where at least one inventor matches the author name."""
return [
patent for patent in patents
if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors)
]
def _get_author(author_id: str) -> Author | None:
short_id = author_id.replace("https://openalex.org/", "")
result = person_logic.search_persons(author_id=short_id)
return result.results[0] if result.results else None
def _extract_last_name(name: str | None) -> str | None:
if not name:
return None
parts = name.strip().split()
return parts[-1] if parts else None
def _extract_first_name(name: str | None) -> str | None:
if not name:
return None
parts = name.strip().split()
return parts[0] if len(parts) > 1 else None
+20
View File
@@ -0,0 +1,20 @@
from pydantic import BaseModel, Field
class PatentEntry(BaseModel):
patent_id: str
source: str # "EPO" or "USPTO"
title: str | None = None
abstract: str | None = None
publication_date: str | None = None
publication_year: str | None = None
inventors: list[str] = Field(default_factory=list)
assignees: list[str] = Field(default_factory=list)
ipc: list[str] = Field(default_factory=list)
country: str | None = None
class PatentsByAuthorResponse(BaseModel):
author_id: str
author_name: str | None = None
patent_count: int
patents: list[PatentEntry]
@@ -0,0 +1,242 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Name normalization and matching for patent inventor lookup.
Handles umlauts, diacritics, and common Latin transliterations so that
e.g. 'Müller' matches 'Mueller' and 'Muller'.
"""
import re
import unicodedata
# Characters that NFKD does not map to ASCII-friendly forms.
_CHAR_REPLACEMENTS: dict[str, str] = {
"ß": "ss",
"ẞ": "ss",
"æ": "ae",
"Æ": "ae",
"œ": "oe",
"Œ": "oe",
"ø": "o",
"Ø": "o",
"đ": "d",
"Đ": "d",
"ð": "d",
"Ð": "d",
"þ": "th",
"Þ": "th",
"ł": "l",
"Ł": "l",
"ı": "i",
"ſ": "s",
}
# German patent transliterations: ae/oe/ue often stand in for ä/ö/ü.
_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = (
("ae", "a"),
("oe", "o"),
("ue", "u"),
)
# Common ASCII spellings in patent records for umlaut-derived vowels.
_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = (
(r"u([lmnrt])", r"ue\1"),
(r"o([lmnrt])", r"oe\1"),
(r"a([lmnrt])", r"ae\1"),
)
def normalize_name_part(value: str | None) -> str:
"""
Normalize a single name token for comparison.
Steps: transliteration map -> NFKD -> strip diacritics -> lowercase
-> remove apostrophes/punctuation -> collapse whitespace.
"""
if not value:
return ""
text = value.strip()
for src, dst in _CHAR_REPLACEMENTS.items():
text = text.replace(src, dst)
text = unicodedata.normalize("NFKD", text)
text = "".join(c for c in text if not unicodedata.combining(c))
text = text.lower()
text = re.sub(r"[''`´]", "", text)
text = re.sub(r"[^\w\s-]", "", text)
text = re.sub(r"\s+", " ", text).strip()
return text
def name_token_variants(value: str | None) -> set[str]:
"""
Return equivalent forms of a name token.
Includes the normalized base plus German digraph collapses
(Mueller -> muller) and hyphen Relaxed forms (Jean-Pierre -> jean pierre).
"""
base = normalize_name_part(value)
if not base:
return set()
variants = {base}
for src, dst in _DIGRAPH_COLLAPSES:
if src in base:
variants.add(base.replace(src, dst))
if "-" in base:
variants.add(base.replace("-", ""))
variants.add(base.replace("-", " "))
return {v for v in variants if v}
def _patent_transliteration_expansions(normalized: str) -> set[str]:
"""
ASCII spellings used in patent records (e.g. Müller indexed as Mueller).
Used for Elasticsearch recall only; post-filter applies stricter matching.
"""
expanded = {normalized}
for pattern, repl in _PATENT_VOWEL_EXPANSIONS:
if re.search(pattern, normalized):
expanded.add(re.sub(pattern, repl, normalized))
return expanded
def tokens_equal(
left: str | None,
right: str | None,
*,
allow_initial: bool = True,
) -> bool:
"""True when two name tokens are equivalent after normalization."""
left_variants = name_token_variants(left)
right_variants = name_token_variants(right)
if not left_variants or not right_variants:
return False
if left_variants & right_variants:
return True
if not allow_initial:
return False
return _initial_tokens_match(left, right)
def _initial_letter(token: str | None) -> str | None:
normalized = normalize_name_part(token)
if len(normalized) == 1 and normalized.isalpha():
return normalized
return None
def _initial_tokens_match(left: str | None, right: str | None) -> bool:
"""True when one token is a single-letter initial matching the other token."""
left_initial = _initial_letter(left)
right_initial = _initial_letter(right)
left_full = normalize_name_part(left)
right_full = normalize_name_part(right)
if left_initial and right_full and len(right_full) > 1:
return right_full.startswith(left_initial)
if right_initial and left_full and len(left_full) > 1:
return left_full.startswith(right_initial)
if left_initial and right_initial:
return left_initial == right_initial
return False
def _inventor_first_token(inventor_name: str) -> str:
if "," in inventor_name:
_, first_part = [p.strip() for p in inventor_name.split(",", 1)]
return first_part.split()[0] if first_part else ""
parts = inventor_name.split()
return parts[0] if parts else ""
def first_name_match_kind(
inventor_name: str,
first_name: str,
last_name: str,
) -> str:
"""
Match quality for the inventor first name: 'full', 'initial', or 'none'.
"""
if not name_matches(inventor_name, first_name, last_name):
return "none"
inventor_first = _inventor_first_token(inventor_name)
if tokens_equal(inventor_first, first_name, allow_initial=False):
return "full"
return "initial"
def search_name_variants(value: str | None) -> list[str]:
"""
Distinct search strings for Elasticsearch, preserving original casing
where useful but including normalized and transliterated forms.
"""
if not value or not value.strip():
return []
seen: set[str] = set()
ordered: list[str] = []
def _add(candidate: str) -> None:
key = candidate.casefold()
if candidate.strip() and key not in seen:
seen.add(key)
ordered.append(candidate.strip())
_add(value.strip())
normalized = normalize_name_part(value)
if normalized:
_add(normalized.title())
for variant in name_token_variants(value):
_add(variant.title())
for variant in _patent_transliteration_expansions(normalized):
_add(variant.title())
if normalized and len(normalized) > 1:
_add(normalized[0].upper())
return ordered
def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool:
"""
True when an inventor entry matches first_name + last_name.
Supports:
- USPTO: 'Christian Weber', 'Christian Hans Weber'
- EPO: 'Weber, Christian', 'Weber, Christian Hans'
"""
if not inventor_name or not last_name:
return False
name = inventor_name.strip()
if "," in name:
last_part, first_part = [p.strip() for p in name.split(",", 1)]
first_token = first_part.split()[0] if first_part else ""
return (
tokens_equal(last_part, last_name, allow_initial=False)
and bool(first_name)
and tokens_equal(first_token, first_name)
)
parts = name.split()
if len(parts) < 2:
return False
return (
tokens_equal(parts[-1], last_name, allow_initial=False)
and bool(first_name)
and tokens_equal(parts[0], first_name)
)
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for patent matching by author.
"""
from fastapi import APIRouter
from . import logic
from . import model
router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
@router.get(
"/{author_id}/patents",
operation_id="getPatentsByAuthor",
response_model=model.PatentsByAuthorResponse,
summary="Get patents matched to an author by name.",
)
async def get_patents_by_author(author_id: str):
return await logic.get_patents_by_author_id(author_id)
@@ -0,0 +1,49 @@
import httpx
import pytest
from inse.patents.elastic_search_client import (
DEFAULT_SEARCH_SIZE,
EPO_INDEX,
PatentSearchClient,
USPTO_INDEX,
)
@pytest.fixture
def anyio_backend():
return "asyncio"
def test_epo_query_uses_nested_search_and_name_variants():
client = PatentSearchClient(api_key="test-key")
payload = client.epo_query_by_inventor("Müller", "Christian")
assert payload["size"] == DEFAULT_SEARCH_SIZE
assert payload["sort"][0] == {"_score": {"order": "desc"}}
nested = payload["query"]["nested"]
assert nested["path"] == "inventors_name_nested"
must = nested["query"]["bool"]["must"]
assert len(must) == 2
assert "should" in must[0]["bool"]
def test_uspto_index_is_3_0():
assert USPTO_INDEX == "uspto_patents_3.0"
assert EPO_INDEX == "epo_index_1.0"
@pytest.mark.anyio
async def test_search_epo_posts_to_correct_index():
requests: list[str] = []
def handler(request: httpx.Request) -> httpx.Response:
requests.append(request.url.path)
return httpx.Response(200, json={"hits": {"hits": []}})
transport = httpx.MockTransport(handler)
client = PatentSearchClient(api_key="test-key", transport=transport)
await client.search_epo(client.epo_query_by_inventor("Weber", "Christian"))
assert len(requests) == 1
assert requests[0].endswith(f"/{EPO_INDEX}/_search")
@@ -0,0 +1,123 @@
import pytest
from inse.patents.name_matching import (
first_name_match_kind,
name_matches,
name_token_variants,
normalize_name_part,
search_name_variants,
tokens_equal,
)
@pytest.mark.parametrize(
("left", "right"),
[
("Müller", "Mueller"),
("Müller", "Muller"),
("Schöning", "Schoening"),
("François", "Francois"),
("José", "Jose"),
("García", "Garcia"),
("Bräun", "Braun"),
("Straß", "Strass"),
("Grøn", "Gron"),
("Małgorzata", "Malgorzata"),
("Øystein", "Oystein"),
],
)
def test_tokens_equal_transliteration(left: str, right: str) -> None:
assert tokens_equal(left, right)
@pytest.mark.parametrize(
("left", "right"),
[
("Christian", "Marc"),
("Weber", "Wagner"),
("Müller", "Meier"),
],
)
def test_tokens_equal_rejects_different_names(left: str, right: str) -> None:
assert not tokens_equal(left, right)
def test_hyphenated_first_name() -> None:
assert tokens_equal("Jean-Pierre", "Jean Pierre")
assert tokens_equal("Jean-Pierre", "JeanPierre")
@pytest.mark.parametrize(
("inventor", "first", "last", "expected"),
[
("Christian Weber", "Christian", "Weber", True),
("Weber, Christian", "Christian", "Weber", True),
("Marc Christian Weber", "Christian", "Weber", False),
("Müller, Hans", "Hans", "Müller", True),
("Mueller, Hans", "Hans", "Müller", True),
("Hans Mueller", "Hans", "Müller", True),
("Weber, Christian Hans", "Christian", "Weber", True),
("Schoening, Klaus", "Klaus", "Schöning", True),
],
)
def test_name_matches(inventor: str, first: str, last: str, expected: bool) -> None:
assert name_matches(inventor, first, last) is expected
def test_normalize_name_part_strips_diacritics() -> None:
assert normalize_name_part("François") == "francois"
assert normalize_name_part(" O'Brien ") == "obrien"
def test_search_name_variants_includes_transliterations() -> None:
variants = search_name_variants("Müller")
folded = {v.casefold() for v in variants}
assert "müller" in folded or "Müller".casefold() in folded
assert "mueller" in folded
assert "muller" in folded
def test_name_token_variants_mueller() -> None:
variants = name_token_variants("Mueller")
assert "mueller" in variants
assert "muller" in variants
@pytest.mark.parametrize(
("left", "right"),
[
("C", "Christian"),
("C.", "Christian"),
("Christian", "C"),
],
)
def test_tokens_equal_initials(left: str, right: str) -> None:
assert tokens_equal(left, right)
def test_tokens_equal_initials_not_for_last_names_by_default() -> None:
assert not tokens_equal("W", "Weber", allow_initial=False)
@pytest.mark.parametrize(
("inventor", "first", "last", "expected"),
[
("C. Weber", "Christian", "Weber", True),
("Weber, C.", "Christian", "Weber", True),
("Weber, C", "Christian", "Weber", True),
],
)
def test_name_matches_initials(inventor: str, first: str, last: str, expected: bool) -> None:
assert name_matches(inventor, first, last) is expected
def test_first_name_match_kind() -> None:
assert first_name_match_kind("Christian Weber", "Christian", "Weber") == "full"
assert first_name_match_kind("C. Weber", "Christian", "Weber") == "initial"
assert first_name_match_kind("Marc Christian Weber", "Christian", "Weber") == "none"
def test_search_name_variants_includes_initial() -> None:
variants = search_name_variants("Christian")
assert "C" in variants
+54
View File
@@ -33,6 +33,60 @@ from inse.persons.model import (
logger = logging.getLogger(__name__)
INDEX_NAME = "openalex-authors"
UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen
def find_ude_author_by_name(display_name: str) -> Optional[dict]:
query = {
"_source": ["display_name"],
"query": {
"bool": {
"must": [
{
"match_phrase": {
"display_name": display_name
}
},
{
"nested": {
"path": "affiliations",
"query": {
"term": {
"affiliations.institution.id": UDE_INSTITUTION_ID
}
},
}
},
]
}
},
"size": 10,
}
try:
data = elasticsearch.search(index=INDEX_NAME, body=query)
except Exception:
logger.exception(f"UDE-Lookup für '{display_name}' fehlgeschlagen.")
return None
hits = data.get("hits", {}).get("hits", [])
display_name = display_name.strip().lower()
exact_matches = []
for hit in hits:
hit_display_name = hit.get("_source", {}).get("display_name", "")
if hit_display_name.strip().lower() == display_name:
exact_matches.append(hit)
if not exact_matches:
return None
hit = exact_matches[0]
return {
"id": hit.get("_id"),
"display_name": hit.get("_source", {}).get("display_name"),
}
def get_author_name_by_id(author_id: str) -> Optional[str]:
+1
View File
@@ -7,4 +7,5 @@ class Tags(Enum):
INSTITUTIONS = "Institutions"
TOPICS = "Topics"
WORKS = "Works"
NEWS = "News"
PROJECTS = "Projects"
@@ -10,6 +10,8 @@ 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
@@ -87,10 +89,16 @@ 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
+5 -1
View File
@@ -10,6 +10,10 @@ 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';
@@ -20,4 +24,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, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
export const APIS = [CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, ItemsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
+554
View File
@@ -0,0 +1,554 @@
/**
* 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
}
);
}
}
+95
View File
@@ -0,0 +1,95 @@
/**
* 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
}
);
}
}
@@ -20,6 +20,7 @@ export interface FundingProject {
*/
id: string;
title?: string | null;
acronym?: string | null;
start_date?: string | null;
end_date?: string | null;
funding_amount?: number | null;
@@ -0,0 +1,17 @@
/**
* 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;
}
+6
View File
@@ -66,9 +66,15 @@ 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
@@ -0,0 +1,21 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface NewsArticle {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
}
@@ -0,0 +1,24 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
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
@@ -0,0 +1,19 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { NewsArticle } from './newsArticle';
export interface NewsPage {
total: number;
page: number;
page_size: number;
results: Array<NewsArticle>;
}
+24
View File
@@ -0,0 +1,24 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
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;
}
@@ -0,0 +1,19 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { PatentEntry } from './patentEntry';
export interface PatentsByAuthorResponse {
author_id: string;
author_name?: string | null;
patent_count: number;
patents: Array<PatentEntry>;
}
+39
View File
@@ -7,6 +7,7 @@ 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';
@@ -83,6 +84,20 @@ 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],
@@ -201,6 +216,30 @@ 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: () =>
import('./modules/person-patents/person-patents.component').then(
(mod) => mod.PersonPatentsComponent,
),
},
{
path: 'company-connections',
loadComponent: () =>
@@ -1,28 +1,39 @@
<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>
<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>
<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="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 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>
</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>
@@ -26,7 +26,7 @@
.controls {
display: flex;
gap: 1rem;
select {
padding: 0.5rem;
border-radius: 4px;
@@ -40,9 +40,16 @@
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;
}
}
}
}
@@ -54,20 +61,35 @@
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,24 +1,31 @@
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;
@@ -41,13 +48,15 @@ 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;
});
}
}
@@ -239,7 +239,7 @@ export class InstitutionProjectsComponent implements OnInit {
];
this.bundProjectColumns = [
{
id: 'topic',
id: 'title',
header: 'Titel',
type: 'accessor',
accessorKey: 'topic',
@@ -0,0 +1,123 @@
<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>
@@ -0,0 +1,295 @@
.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;
}
@@ -0,0 +1,109 @@
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;
},
});
}
}
@@ -0,0 +1,110 @@
<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>
@@ -0,0 +1,209 @@
.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;
}
}
@@ -0,0 +1,219 @@
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,11 +36,25 @@ export class PersonCardComponent {
}
institution(person: CustomAuthor): DehydratedInstitution | undefined {
return (
person.last_known_institutions?.[0] ||
person.affiliations?.[person.affiliations.length - 1]?.institution ||
undefined
);
if (person.last_known_institutions?.[0]) {
return person.last_known_institutions[0];
}
const affiliations = person.affiliations ?? [];
let newestInstitution: DehydratedInstitution | undefined =
affiliations[0]?.institution ?? undefined;
let newestYear = -1;
for (const affiliation of affiliations) {
for (const jahr of affiliation.years ?? []) {
if (jahr > newestYear) {
newestYear = jahr;
newestInstitution = affiliation.institution ?? undefined;
}
}
}
return newestInstitution;
}
topics(person: CustomAuthor): WorkTopic[] {
@@ -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,11 +13,7 @@ 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';
@@ -0,0 +1,82 @@
<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>
@@ -0,0 +1,156 @@
.page {
padding: 28px 32px 42px;
max-width: 100%;
margin: 0 auto;
}
h6 {
margin: 0 0 6px;
font-size: 22px;
line-height: 1.2;
font-weight: 700;
}
.page > div:first-child p {
margin: 0;
color: var(--sg-text-muted);
font-size: 14px;
}
.news-toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
padding-top: 10px;
padding-bottom: 25px;
}
.search-field {
max-width: 480px;
}
::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper {
display: none;
}
::ng-deep .news-toolbar .mat-mdc-text-field-wrapper {
height: 42px;
background: #fff;
border-radius: var(--sg-radius-sm);
}
::ng-deep .news-toolbar .mat-mdc-form-field-infix {
min-height: unset;
height: 42px;
padding: 0;
display: flex;
align-items: center;
}
::ng-deep .news-toolbar .mdc-notched-outline__leading,
::ng-deep .news-toolbar .mdc-notched-outline__notch,
::ng-deep .news-toolbar .mdc-notched-outline__trailing {
border-color: #d9e2f0;
}
::ng-deep .news-toolbar input.mat-mdc-input-element {
color: var(--sg-text);
font-size: 14px;
}
::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder {
color: var(--sg-text-muted);
opacity: 1;
font-size: 14px;
}
.sort-field {
width: 180px;
}
.table-wrap {
position: relative;
overflow-x: auto;
}
table {
width: 100%;
min-width: 600px;
border-collapse: separate;
border-spacing: 0 10px;
background: transparent;
box-shadow: none;
}
.article-title {
display: inline-block;
max-width: 520px;
line-height: 1.35;
color: var(--sg-text);
font-size: 14px;
font-weight: 700;
text-decoration: none;
&:hover {
color: var(--sg-text);
text-decoration: underline;
}
}
.loading {
position: absolute;
inset: 0;
z-index: 1;
display: grid;
place-items: center;
background: rgba(255, 255, 255, 0.65);
}
.empty-state {
padding: 28px;
text-align: center;
color: rgba(0, 0, 0, 0.6);
background: transparent;
}
::ng-deep .mat-mdc-header-cell {
color: var(--sg-text-muted);
font-size: 12px;
font-weight: 700;
}
::ng-deep .mat-mdc-row {
height: 72px;
}
::ng-deep .mat-mdc-cell {
color: var(--sg-text);
border-bottom-color: var(--sg-border);
font-size: 13px;
}
mat-paginator {
background: transparent;
}
.table-footer {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 66px;
padding: 0 22px 0 28px;
color: var(--sg-text-muted);
font-size: 13px;
}
@media (max-width: 600px) {
.page {
padding: 16px;
}
.table-footer {
align-items: stretch;
flex-direction: column;
}
}
@@ -0,0 +1,139 @@
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',
});
}
}
@@ -0,0 +1,179 @@
@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>
}
@@ -0,0 +1,306 @@
.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;
}
}
@@ -0,0 +1,174 @@
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;
}
}
@@ -52,9 +52,7 @@
<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>
@@ -165,7 +163,6 @@
<dt>Ausführende Stelle</dt>
<dd>
{{ bundProject.executing_agency }}
</dd>
</div>
}
@@ -178,12 +175,11 @@
@if (bundProject.project_agency) {
<div class="detail-row">
<dt>Projektagentur</dt>
<dd>
<dd>
{{
bundProject.project_agency_fullname ||
bundProject.project_agency
}}
</dd>
</div>
}
@@ -225,7 +221,6 @@
<dt>Standort</dt>
<dd>
{{ bundProject.location }}
</dd>
</div>
}
@@ -328,7 +323,6 @@
<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,7 +136,9 @@
@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>
@@ -203,7 +205,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,
},
});
}
/**
@@ -119,15 +119,20 @@ export class PersonComponent {
() => this.person()?.affiliations?.[0] ?? null,
);
readonly lastAffiliation = computed(() => {
let lastAffiliation: number | undefined = 0;
if (this.person()?.affiliations?.length != undefined) {
lastAffiliation = this.person()?.affiliations?.length;
const affiliations = this.person()?.affiliations ?? [];
let newestAffiliation = affiliations[0] ?? null;
let newestYear = -1;
for (const affiliation of affiliations) {
for (const jahr of affiliation.years ?? []) {
if (jahr > newestYear) {
newestYear = jahr;
newestAffiliation = affiliation;
}
}
}
return (
(lastAffiliation
? this.person()?.affiliations?.[lastAffiliation - 1]
: this.person()?.affiliations?.[0]) ?? null
);
return newestAffiliation;
});
readonly institution = computed(
() =>
@@ -186,6 +191,8 @@ 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 },
];
onInterestingTagClick(selection: { id: string; name: string }): void {
@@ -2,10 +2,13 @@
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);
@@ -14,7 +17,13 @@ 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,5 +2,4 @@
echarts
[options]="chartOption"
[merge]="mergeOption"
class="chart-container">
</div>
class="chart-container"></div>
@@ -1 +1,4 @@
.chart-container { height: 500px; width: 100%; }
.chart-container {
height: 500px;
width: 100%;
}
@@ -1,9 +1,13 @@
// 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({
@@ -12,21 +16,24 @@ 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 = {};
@@ -34,24 +41,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,8 +7,7 @@ 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[] = [];
@@ -13,4 +13,4 @@ export const bundSingleProjectResolver: ResolveFn<BundProjectDetails> = (
throw new Error('BUND Project ID is required');
}
return projectsService.getSingleBundProject(projectId);
};
};
@@ -13,4 +13,4 @@ export const dfgSingleProjectResolver: ResolveFn<DfgProjectDetails> = (
throw new Error('DFG Project ID is required');
}
return projectsService.getSingleDfgProject(projectId);
};
};
@@ -0,0 +1,57 @@
import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { of } from 'rxjs';
import { WorksService } from '../api';
export interface NewsArticle {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
}
export interface NewsPage {
total: number;
page: number;
page_size: number;
results: NewsArticle[];
}
export const personNewsResolver: ResolveFn<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,7 +6,6 @@ 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';
@@ -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,6 +46,12 @@ export class AppMenuComponent {
},
disabled: false,
},
{
label: 'News',
icon: 'newspaper',
route: '/news',
disabled: false,
},
{
label: 'Institutionen',
icon: 'apartment',