diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index ad171904..4d83fe03 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -34,6 +34,10 @@ class Settings(BaseSettings): "am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==" ) openalex_works_search_timeout_seconds: float = 30.0 + # OpenAlex public API config + openalex_api_base_url: str = "https://api.openalex.org" + openalex_api_key: Optional[str] = None + openalex_api_timeout_seconds: float = 30.0 # LLM config llm_api_url: Optional[str] = None diff --git a/service/src/main/inse/institutions/__init__.py b/service/src/main/inse/institutions/__init__.py new file mode 100644 index 00000000..9be5f207 --- /dev/null +++ b/service/src/main/inse/institutions/__init__.py @@ -0,0 +1 @@ +"""Institution lookup module.""" diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py new file mode 100644 index 00000000..34504553 --- /dev/null +++ b/service/src/main/inse/institutions/logic.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Business logic for OpenAlex institutions. +""" +import logging +from copy import deepcopy +from typing import Any + +import httpx +from fastapi import HTTPException +from pydantic import ValidationError +from starlette.status import HTTP_400_BAD_REQUEST +from starlette.status import HTTP_502_BAD_GATEWAY + +from inse.models.autocomplete_response import AutocompleteResponse +from inse.models.autocomplete_response_meta import AutocompleteResponseMeta +from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner +from inse.models.institutions_list_response import InstitutionsListResponse +from .search_client import OpenAlexInstitutionsClient + +logger = logging.getLogger(__name__) + +_VALID_INSTITUTION_TYPES = { + "education", + "healthcare", + "company", + "archive", + "nonprofit", + "government", + "facility", + "other", +} + + +async def list_institutions( + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + client: OpenAlexInstitutionsClient | None = None, +) -> InstitutionsListResponse: + if sample is not None and (sort or page not in (None, 1)): + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail="sample cannot be combined with sort or page.", + ) + + openalex_client = client or OpenAlexInstitutionsClient() + + try: + data = await openalex_client.list_institutions( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) + except httpx.HTTPStatusError as exc: + status_code = exc.response.status_code + detail = "OpenAlex institutions request failed." + try: + error_body = exc.response.json() + detail = error_body.get("message") or error_body.get("error") or detail + except ValueError: + if exc.response.text: + detail = exc.response.text + raise HTTPException(status_code=status_code, detail=detail) from exc + except httpx.HTTPError as exc: + logger.exception("OpenAlex institutions request failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex institutions request failed.", + ) from exc + + try: + normalized_data = _normalize_institutions_response(data) + return InstitutionsListResponse.from_dict(normalized_data) or InstitutionsListResponse() + except ValidationError as exc: + logger.exception("OpenAlex institutions response could not be parsed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex institutions response could not be parsed.", + ) from exc + + +async def autocomplete_institutions( + *, + query: str, + country_code: str | None = None, + institution_type: str | None = None, + limit: int = 10, + client: OpenAlexInstitutionsClient | None = None, +) -> AutocompleteResponse: + filters = [] + if country_code: + filters.append(f"country_code:{country_code}") + if institution_type: + filters.append(f"type:{institution_type}") + + response = await list_institutions( + search=query, + filter=",".join(filters) if filters else None, + sort="works_count:desc", + per_page=limit, + page=1, + select=( + "id,ror,display_name,country_code,type,works_count," + "cited_by_count,geo" + ), + client=client, + ) + + results = [] + for institution in response.results or []: + if not institution.id or not institution.display_name: + continue + + hint_parts = [] + if institution.geo: + if institution.geo.city: + hint_parts.append(institution.geo.city) + if institution.geo.country: + hint_parts.append(institution.geo.country) + elif institution.country_code: + hint_parts.append(institution.country_code) + if institution.type: + hint_parts.append(institution.type) + + results.append( + AutocompleteResponseResultsInner( + id=institution.id, + display_name=institution.display_name, + hint=" · ".join(hint_parts) if hint_parts else None, + cited_by_count=institution.cited_by_count, + works_count=institution.works_count, + entity_type="institution", + external_id=institution.ror, + ) + ) + + return AutocompleteResponse( + meta=AutocompleteResponseMeta( + count=response.meta.count if response.meta else len(results), + db_response_time_ms=( + response.meta.db_response_time_ms if response.meta else None + ), + ), + results=results, + ) + + +def _normalize_institutions_response(data: dict[str, Any]) -> dict[str, Any]: + normalized = deepcopy(data) + + meta = normalized.get("meta") + if isinstance(meta, dict): + for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]: + meta[field] = _int_or_none(meta.get(field)) + meta["next_cursor"] = _str_or_none(meta.get("next_cursor")) + meta["cost_usd"] = _number_or_none(meta.get("cost_usd")) + + for institution in normalized.get("results") or []: + if not isinstance(institution, dict): + continue + + for field in [ + "id", + "ror", + "display_name", + "country_code", + "homepage_url", + "image_url", + "image_thumbnail_url", + "works_api_url", + ]: + institution[field] = _str_or_none(institution.get(field)) + + institution_type = institution.get("type") + if institution_type is not None and institution_type not in _VALID_INSTITUTION_TYPES: + institution["type"] = None + else: + institution["type"] = _str_or_none(institution_type) + + institution["display_name_acronyms"] = _str_list_or_none( + institution.get("display_name_acronyms") + ) + institution["display_name_alternatives"] = _str_list_or_none( + institution.get("display_name_alternatives") + ) + institution["lineage"] = _str_list_or_none(institution.get("lineage")) + institution["works_count"] = _int_or_none(institution.get("works_count")) + institution["cited_by_count"] = _int_or_none(institution.get("cited_by_count")) + institution["created_date"] = _date_str_or_none(institution.get("created_date")) + institution["updated_date"] = _datetime_str_or_none(institution.get("updated_date")) + + summary_stats = institution.get("summary_stats") + if isinstance(summary_stats, dict): + summary_stats["2yr_mean_citedness"] = _number_or_none( + summary_stats.get("2yr_mean_citedness") + ) + summary_stats["h_index"] = _int_or_none(summary_stats.get("h_index")) + summary_stats["i10_index"] = _int_or_none(summary_stats.get("i10_index")) + + geo = institution.get("geo") + if isinstance(geo, dict): + for field in [ + "city", + "geonames_city_id", + "region", + "country_code", + "country", + ]: + geo[field] = _str_or_none(geo.get(field)) + geo["latitude"] = _number_or_none(geo.get("latitude")) + geo["longitude"] = _number_or_none(geo.get("longitude")) + + ids = institution.get("ids") + if isinstance(ids, dict): + for field in ["openalex", "ror", "grid", "wikipedia", "wikidata"]: + ids[field] = _str_or_none(ids.get(field)) + ids["mag"] = _int_or_none(ids.get("mag")) + + for counts_by_year in institution.get("counts_by_year") or []: + if not isinstance(counts_by_year, dict): + continue + for field in ["year", "works_count", "cited_by_count"]: + counts_by_year[field] = _int_or_none(counts_by_year.get(field)) + + for group in normalized.get("group_by") or []: + if not isinstance(group, dict): + continue + + group["key"] = _str_or_none(group.get("key")) + group["key_display_name"] = _str_or_none(group.get("key_display_name")) + group["count"] = _int_or_none(group.get("count")) + + return normalized + + +def _str_or_none(value: Any) -> str | None: + if value is None: + return None + if isinstance(value, bool): + return str(value).lower() + return str(value) + + +def _str_list_or_none(value: Any) -> list[str] | None: + if value is None: + return None + if not isinstance(value, list): + return None + return [_str_or_none(item) for item in value if item is not None] + + +def _int_or_none(value: Any) -> int | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, float): + return int(value) + if isinstance(value, str): + try: + return int(float(value)) + except ValueError: + return None + return None + + +def _number_or_none(value: Any) -> int | float | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, (int, float)): + return value + if isinstance(value, str): + try: + number = float(value) + except ValueError: + return None + return int(number) if number.is_integer() else number + return None + + +def _date_str_or_none(value: Any) -> str | None: + text = _str_or_none(value) + if not text: + return None + return text[:10] + + +def _datetime_str_or_none(value: Any) -> str | None: + text = _str_or_none(value) + if not text: + return None + if len(text) == 10: + return f"{text}T00:00:00Z" + return text diff --git a/service/src/main/inse/institutions/search_client.py b/service/src/main/inse/institutions/search_client.py new file mode 100644 index 00000000..3db5e1dd --- /dev/null +++ b/service/src/main/inse/institutions/search_client.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +HTTP client for OpenAlex institutions. +""" +from typing import Any + +import httpx + +from .. import config + + +class OpenAlexInstitutionsClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + timeout: float | None = None, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/") + self.api_key = api_key if api_key is not None else config.settings.openalex_api_key + self.timeout = timeout if timeout is not None else config.settings.openalex_api_timeout_seconds + self.transport = transport + + def list_institutions_params( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + params: dict[str, Any] = {"per_page": per_page} + + if search: + params["search"] = search + if filter: + params["filter"] = filter + if sort: + params["sort"] = sort + if group_by: + params["group_by"] = group_by + if cursor: + params["cursor"] = cursor + elif page is not None: + params["page"] = page + if sample is not None: + params["sample"] = sample + if select: + params["select"] = select + if self.api_key: + params["api_key"] = self.api_key + + return params + + async def list_institutions( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.get( + "/institutions", + params=self.list_institutions_params( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ), + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/institutions/service.py b/service/src/main/inse/institutions/service.py new file mode 100644 index 00000000..69d6911e --- /dev/null +++ b/service/src/main/inse/institutions/service.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +REST API for OpenAlex institutions. +""" +from typing import Annotated + +from fastapi import APIRouter +from fastapi import Query + +from inse.models.autocomplete_response import AutocompleteResponse +from inse.models.institutions_list_response import InstitutionsListResponse +from inse.tags import Tags +from . import logic + + +router = APIRouter(prefix="/api/institutions", tags=[Tags.INSTITUTIONS]) + + +@router.get( + "/autocomplete", + operation_id="autocompleteInstitutions", + response_model=AutocompleteResponse, + response_model_exclude_none=True, + summary="Returns institution options for autocomplete inputs.", +) +async def autocomplete_institutions( + query: Annotated[ + str, + Query(description="Institution search text, for example 'Duisburg Essen'.", min_length=1), + ], + country_code: Annotated[ + str | None, + Query(alias="countryCode", description="Optional ISO country code filter."), + ] = None, + institution_type: Annotated[ + str | None, + Query(alias="type", description="Optional institution type filter."), + ] = None, + limit: Annotated[ + int, + Query(description="Maximum number of autocomplete options.", ge=1, le=25), + ] = 10, +): + return await logic.autocomplete_institutions( + query=query, + country_code=country_code, + institution_type=institution_type, + limit=limit, + ) + + +@router.get( + "", + operation_id="listInstitutions", + response_model=InstitutionsListResponse, + response_model_exclude_none=True, + summary="Returns a list of OpenAlex institutions.", +) +async def list_institutions( + search: Annotated[ + str | None, + Query(description="Full-text search, for example 'Duisburg Essen'."), + ] = None, + filter: Annotated[ + str | None, + Query(description="OpenAlex filter, for example 'country_code:DE,type:education'."), + ] = None, + sort: Annotated[ + str | None, + Query(description="Sort field, for example 'works_count:desc'."), + ] = "works_count:desc", + group_by: Annotated[ + str | None, + Query(description="OpenAlex group_by field, for example 'country_code'."), + ] = None, + per_page: Annotated[ + int, + Query(description="Results per page.", ge=1, le=100), + ] = 25, + page: Annotated[ + int | None, + Query(description="Page number. Use cursor for deep pagination.", ge=1), + ] = 1, + cursor: Annotated[ + str | None, + Query(description="Cursor pagination token. Use '*' to start."), + ] = None, + sample: Annotated[ + int | None, + Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000), + ] = None, + select: Annotated[ + str | None, + Query(description="Comma-separated fields to return."), + ] = None, +): + return await logic.list_institutions( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py new file mode 100644 index 00000000..e079ff8e --- /dev/null +++ b/service/src/main/inse/institutions/test_logic.py @@ -0,0 +1,236 @@ +import httpx +import pytest +from fastapi import HTTPException + +from inse.institutions import logic +from inse.institutions.search_client import OpenAlexInstitutionsClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@pytest.mark.anyio +async def test_list_institutions_maps_openalex_response_to_model(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/I123", + "ror": "https://ror.org/04mz5ra38", + "display_name": "University of Duisburg-Essen", + "country_code": "DE", + "type": "education", + "homepage_url": "https://www.uni-due.de", + "image_url": "https://example.org/image.jpg", + "image_thumbnail_url": "https://example.org/thumb.jpg", + "display_name_acronyms": ["UDE"], + "display_name_alternatives": ["Universitaet Duisburg-Essen"], + "works_count": 123, + "cited_by_count": 456, + "summary_stats": { + "2yr_mean_citedness": 1.5, + "h_index": 42, + "i10_index": 99, + }, + "geo": { + "city": "Duisburg", + "geonames_city_id": "2934691", + "region": "North Rhine-Westphalia", + "country_code": "DE", + "country": "Germany", + "latitude": 51.4344, + "longitude": 6.7623, + }, + "lineage": ["https://openalex.org/I123"], + "ids": { + "openalex": "https://openalex.org/I123", + "ror": "https://ror.org/04mz5ra38", + "mag": 123, + "grid": "grid.12345.6", + "wikipedia": "https://en.wikipedia.org/wiki/University_of_Duisburg-Essen", + "wikidata": "https://www.wikidata.org/wiki/Q317070", + }, + "counts_by_year": [ + { + "year": 2024, + "works_count": 12, + "cited_by_count": 34, + } + ], + "works_api_url": "https://api.openalex.org/works?filter=institutions.id:I123", + "created_date": "2023-12-25", + "updated_date": "2023-11-07T05:31:56Z", + } + ], + "group_by": [ + { + "key": "DE", + "key_display_name": "Germany", + "count": 1, + } + ], + }, + ) + + client = OpenAlexInstitutionsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_institutions(search="Duisburg Essen", client=client) + + assert result.meta.count == 1 + institution = result.results[0] + assert institution.display_name == "University of Duisburg-Essen" + assert institution.summary_stats.h_index == 42 + assert institution.geo.country == "Germany" + assert institution.ids.mag == 123 + assert institution.counts_by_year[0].year == 2024 + assert result.group_by[0].key_display_name == "Germany" + + +@pytest.mark.anyio +async def test_list_institutions_rejects_sample_with_sort(): + with pytest.raises(HTTPException) as exc_info: + await logic.list_institutions(sample=10, sort="works_count:desc") + + assert exc_info.value.status_code == 400 + + +@pytest.mark.anyio +async def test_list_institutions_accepts_practical_openalex_type_variants(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": 123, + "ror": 456, + "display_name": "Example Institute", + "country_code": 789, + "type": "unknown-openalex-type", + "display_name_acronyms": ["EI", 123], + "display_name_alternatives": "not-a-list", + "works_count": "12", + "cited_by_count": "34.0", + "summary_stats": { + "2yr_mean_citedness": "1.25", + "h_index": "10.0", + "i10_index": True, + }, + "geo": { + "city": 123, + "geonames_city_id": 12345, + "latitude": "51.4", + "longitude": "6", + }, + "ids": {"openalex": 123, "mag": "123"}, + "counts_by_year": [ + { + "year": "2024", + "works_count": "12.0", + "cited_by_count": False, + } + ], + "created_date": "2023-12-25T10:11:12Z", + "updated_date": "2023-12-25", + } + ], + "group_by": [{"key": True, "count": 1}], + }, + ) + + client = OpenAlexInstitutionsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_institutions(client=client) + + assert result.results[0].id == "123" + assert result.results[0].ror == "456" + assert result.results[0].country_code == "789" + assert result.results[0].type is None + assert result.results[0].display_name_acronyms == ["EI", "123"] + assert result.results[0].display_name_alternatives is None + assert result.results[0].works_count == 12 + assert result.results[0].cited_by_count == 34 + assert result.results[0].summary_stats.var_2yr_mean_citedness == 1.25 + assert result.results[0].summary_stats.h_index == 10 + assert result.results[0].summary_stats.i10_index is None + assert result.results[0].geo.city == "123" + assert result.results[0].geo.geonames_city_id == "12345" + assert result.results[0].geo.latitude == 51.4 + assert result.results[0].geo.longitude == 6 + assert result.results[0].ids.openalex == "123" + assert result.results[0].ids.mag == 123 + assert result.results[0].counts_by_year[0].year == 2024 + assert result.results[0].counts_by_year[0].works_count == 12 + assert result.results[0].counts_by_year[0].cited_by_count is None + assert result.group_by[0].key == "true" + + +@pytest.mark.anyio +async def test_autocomplete_institutions_returns_frontend_options(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.params["search"] == "Duisburg Essen" + assert request.url.params["filter"] == "country_code:DE,type:education" + assert request.url.params["sort"] == "works_count:desc" + assert request.url.params["per_page"] == "5" + assert request.url.params["select"] == ( + "id,ror,display_name,country_code,type,works_count," + "cited_by_count,geo" + ) + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "db_response_time_ms": 12}, + "results": [ + { + "id": "https://openalex.org/I123", + "ror": "https://ror.org/04mz5ra38", + "display_name": "University of Duisburg-Essen", + "country_code": "DE", + "type": "education", + "works_count": 123, + "cited_by_count": 456, + "geo": { + "city": "Duisburg", + "country": "Germany", + }, + } + ], + }, + ) + + client = OpenAlexInstitutionsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.autocomplete_institutions( + query="Duisburg Essen", + country_code="DE", + institution_type="education", + limit=5, + client=client, + ) + + assert result.meta.count == 1 + assert result.meta.db_response_time_ms == 12 + assert len(result.results) == 1 + option = result.results[0] + assert option.id == "https://openalex.org/I123" + assert option.display_name == "University of Duisburg-Essen" + assert option.hint == "Duisburg · Germany · education" + assert option.works_count == 123 + assert option.cited_by_count == 456 + assert option.entity_type == "institution" + assert option.external_id == "https://ror.org/04mz5ra38" diff --git a/service/src/main/inse/institutions/test_search_client.py b/service/src/main/inse/institutions/test_search_client.py new file mode 100644 index 00000000..0051b8cf --- /dev/null +++ b/service/src/main/inse/institutions/test_search_client.py @@ -0,0 +1,77 @@ +import httpx +import pytest + +from inse.institutions.search_client import OpenAlexInstitutionsClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def test_list_institutions_params_include_openalex_query_parameters(): + client = OpenAlexInstitutionsClient(api_key="test-key") + + params = client.list_institutions_params( + search="Duisburg Essen", + filter="country_code:DE,type:education", + sort="works_count:desc", + group_by="country_code", + per_page=10, + page=2, + select="id,display_name", + ) + + assert params == { + "search": "Duisburg Essen", + "filter": "country_code:DE,type:education", + "sort": "works_count:desc", + "group_by": "country_code", + "per_page": 10, + "page": 2, + "select": "id,display_name", + "api_key": "test-key", + } + + +def test_list_institutions_params_prefers_cursor_over_page(): + client = OpenAlexInstitutionsClient(api_key="test-key") + + params = client.list_institutions_params(cursor="*", page=3) + + assert params["cursor"] == "*" + assert "page" not in params + + +@pytest.mark.anyio +async def test_list_institutions_calls_openalex_institutions_endpoint(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.method == "GET" + assert request.url.path == "/institutions" + assert request.url.params["search"] == "Duisburg Essen" + assert request.url.params["api_key"] == "test-key" + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/I123", + "display_name": "University of Duisburg-Essen", + "country_code": "DE", + "type": "education", + } + ], + }, + ) + + client = OpenAlexInstitutionsClient( + base_url="https://api.openalex.org", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await client.list_institutions(search="Duisburg Essen") + + assert result["meta"]["count"] == 1 + assert result["results"][0]["display_name"] == "University of Duisburg-Essen" diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 4e0e62d2..a1e4614e 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -11,6 +11,8 @@ from fastapi import FastAPI from fastapi.responses import RedirectResponse from fastapi.middleware.cors import CORSMiddleware from inse.collaboration_network.router import router as collaboration_network_router +from inse.institutions.service import router as institutions_service_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 @@ -33,6 +35,8 @@ app = FastAPI( servers=settings.servers, ) app.include_router(collaboration_network_router) +app.include_router(institutions_service_router) +app.include_router(topics_service_router) app.include_router(works_service_router) app.include_router(persons_service_router) app.include_router(funders_service_router) diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index 219152ad..21c6b03c 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -4,4 +4,6 @@ from enum import Enum class Tags(Enum): PERSON = "Person" PERSON_NETWORK = "Person Network" - WORKS = "Works" \ No newline at end of file + INSTITUTIONS = "Institutions" + TOPICS = "Topics" + WORKS = "Works" diff --git a/service/src/main/inse/topics/__init__.py b/service/src/main/inse/topics/__init__.py new file mode 100644 index 00000000..6909a227 --- /dev/null +++ b/service/src/main/inse/topics/__init__.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +OpenAlex topics module. +""" diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py new file mode 100644 index 00000000..5d4bdef7 --- /dev/null +++ b/service/src/main/inse/topics/logic.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Business logic for OpenAlex topics. +""" +import logging +from copy import deepcopy +from typing import Any + +import httpx +from fastapi import HTTPException +from pydantic import ValidationError +from starlette.status import HTTP_400_BAD_REQUEST +from starlette.status import HTTP_502_BAD_GATEWAY + +from inse.models.autocomplete_response import AutocompleteResponse +from inse.models.autocomplete_response_meta import AutocompleteResponseMeta +from inse.models.autocomplete_response_results_inner import ( + AutocompleteResponseResultsInner, +) +from inse.models.topics_list_response import TopicsListResponse +from .search_client import OpenAlexTopicsClient + +logger = logging.getLogger(__name__) + + +async def list_topics( + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + client: OpenAlexTopicsClient | None = None, +) -> TopicsListResponse: + if sample is not None and (sort or page not in (None, 1)): + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail="sample cannot be combined with sort or page.", + ) + + openalex_client = client or OpenAlexTopicsClient() + + try: + data = await openalex_client.list_topics( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) + except httpx.HTTPStatusError as exc: + status_code = exc.response.status_code + detail = "OpenAlex topics request failed." + try: + error_body = exc.response.json() + detail = error_body.get("message") or error_body.get("error") or detail + except ValueError: + if exc.response.text: + detail = exc.response.text + raise HTTPException(status_code=status_code, detail=detail) from exc + except httpx.HTTPError as exc: + logger.exception("OpenAlex topics request failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex topics request failed.", + ) from exc + + try: + normalized_data = _normalize_topics_response(data) + return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse() + except ValidationError as exc: + logger.exception("OpenAlex topics response could not be parsed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex topics response could not be parsed.", + ) from exc + + +async def autocomplete_topics( + *, + query: str, + domain_id: str | None = None, + field_id: str | None = None, + subfield_id: str | None = None, + limit: int = 10, + client: OpenAlexTopicsClient | None = None, +) -> AutocompleteResponse: + filters = [] + if domain_id: + filters.append(f"domain.id:{domain_id}") + if field_id: + filters.append(f"field.id:{field_id}") + if subfield_id: + filters.append(f"subfield.id:{subfield_id}") + + response = await list_topics( + search=query, + filter=",".join(filters) if filters else None, + sort="works_count:desc", + per_page=limit, + page=1, + select=( + "id,display_name,description,keywords,subfield,field,domain," + "works_count,cited_by_count,ids" + ), + client=client, + ) + + results = [] + for topic in response.results or []: + if not topic.id or not topic.display_name: + continue + + hint_parts = [] + if topic.var_field and topic.var_field.display_name: + hint_parts.append(topic.var_field.display_name) + if topic.subfield and topic.subfield.display_name: + hint_parts.append(topic.subfield.display_name) + if topic.domain and topic.domain.display_name: + hint_parts.append(topic.domain.display_name) + + results.append( + AutocompleteResponseResultsInner( + id=topic.id, + display_name=topic.display_name, + hint=" · ".join(hint_parts) if hint_parts else topic.description, + cited_by_count=topic.cited_by_count, + works_count=topic.works_count, + entity_type="topic", + external_id=topic.ids.openalex if topic.ids else None, + ) + ) + + return AutocompleteResponse( + meta=AutocompleteResponseMeta( + count=response.meta.count if response.meta else len(results), + db_response_time_ms=( + response.meta.db_response_time_ms if response.meta else None + ), + ), + results=results, + ) + + +def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]: + normalized = deepcopy(data) + + meta = normalized.get("meta") + if isinstance(meta, dict): + for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]: + meta[field] = _int_or_none(meta.get(field)) + meta["next_cursor"] = _str_or_none(meta.get("next_cursor")) + meta["cost_usd"] = _number_or_none(meta.get("cost_usd")) + + for topic in normalized.get("results") or []: + if not isinstance(topic, dict): + continue + + for field in ["id", "display_name", "description", "works_api_url"]: + topic[field] = _str_or_none(topic.get(field)) + topic["keywords"] = _str_list_or_none(topic.get("keywords")) + topic["works_count"] = _int_or_none(topic.get("works_count")) + topic["cited_by_count"] = _int_or_none(topic.get("cited_by_count")) + topic["created_date"] = _date_str_or_none(topic.get("created_date")) + topic["updated_date"] = _datetime_str_or_none(topic.get("updated_date")) + + for relation_field in ["subfield", "field", "domain"]: + relation = topic.get(relation_field) + if not isinstance(relation, dict): + continue + relation["id"] = _str_or_none(relation.get("id")) + relation["display_name"] = _str_or_none(relation.get("display_name")) + + ids = topic.get("ids") + if isinstance(ids, dict): + for field in ["openalex", "wikipedia"]: + ids[field] = _str_or_none(ids.get(field)) + + for group in normalized.get("group_by") or []: + if not isinstance(group, dict): + continue + + group["key"] = _str_or_none(group.get("key")) + group["key_display_name"] = _str_or_none(group.get("key_display_name")) + group["count"] = _int_or_none(group.get("count")) + + return normalized + + +def _str_or_none(value: Any) -> str | None: + if value is None: + return None + if isinstance(value, bool): + return str(value).lower() + return str(value) + + +def _str_list_or_none(value: Any) -> list[str] | None: + if value is None: + return None + if not isinstance(value, list): + return None + return [_str_or_none(item) for item in value if item is not None] + + +def _int_or_none(value: Any) -> int | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, float): + return int(value) + if isinstance(value, str): + try: + return int(float(value)) + except ValueError: + return None + return None + + +def _number_or_none(value: Any) -> int | float | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, (int, float)): + return value + if isinstance(value, str): + try: + number = float(value) + except ValueError: + return None + return int(number) if number.is_integer() else number + return None + + +def _date_str_or_none(value: Any) -> str | None: + text = _str_or_none(value) + if not text: + return None + return text[:10] + + +def _datetime_str_or_none(value: Any) -> str | None: + text = _str_or_none(value) + if not text: + return None + if len(text) == 10: + return f"{text}T00:00:00Z" + return text diff --git a/service/src/main/inse/topics/search_client.py b/service/src/main/inse/topics/search_client.py new file mode 100644 index 00000000..7c70afa0 --- /dev/null +++ b/service/src/main/inse/topics/search_client.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +HTTP client for OpenAlex topics. +""" +from typing import Any + +import httpx + +from .. import config + + +class OpenAlexTopicsClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + timeout: float | None = None, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/") + self.api_key = api_key if api_key is not None else config.settings.openalex_api_key + self.timeout = ( + timeout + if timeout is not None + else config.settings.openalex_api_timeout_seconds + ) + self.transport = transport + + def list_topics_params( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + params: dict[str, Any] = {"per_page": per_page} + + if search: + params["search"] = search + if filter: + params["filter"] = filter + if sort: + params["sort"] = sort + if group_by: + params["group_by"] = group_by + if cursor: + params["cursor"] = cursor + elif page is not None: + params["page"] = page + if sample is not None: + params["sample"] = sample + if select: + params["select"] = select + if self.api_key: + params["api_key"] = self.api_key + + return params + + async def list_topics( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.get( + "/topics", + params=self.list_topics_params( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ), + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/topics/service.py b/service/src/main/inse/topics/service.py new file mode 100644 index 00000000..70252254 --- /dev/null +++ b/service/src/main/inse/topics/service.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +REST API for OpenAlex topics. +""" +from typing import Annotated + +from fastapi import APIRouter +from fastapi import Query + +from inse.models.autocomplete_response import AutocompleteResponse +from inse.models.topics_list_response import TopicsListResponse +from inse.tags import Tags +from . import logic + + +router = APIRouter(prefix="/api/topics", tags=[Tags.TOPICS]) + + +@router.get( + "/autocomplete", + operation_id="autocompleteTopics", + response_model=AutocompleteResponse, + response_model_exclude_none=True, + summary="Returns topic options for autocomplete inputs.", +) +async def autocomplete_topics( + query: Annotated[ + str, + Query(description="Topic search text, for example 'machine learning'.", min_length=1), + ], + domain_id: Annotated[ + str | None, + Query(alias="domainId", description="Optional OpenAlex domain id filter."), + ] = None, + field_id: Annotated[ + str | None, + Query(alias="fieldId", description="Optional OpenAlex field id filter."), + ] = None, + subfield_id: Annotated[ + str | None, + Query(alias="subfieldId", description="Optional OpenAlex subfield id filter."), + ] = None, + limit: Annotated[ + int, + Query(description="Maximum number of autocomplete options.", ge=1, le=25), + ] = 10, +): + return await logic.autocomplete_topics( + query=query, + domain_id=domain_id, + field_id=field_id, + subfield_id=subfield_id, + limit=limit, + ) + + +@router.get( + "", + operation_id="listTopics", + response_model=TopicsListResponse, + response_model_exclude_none=True, + summary="Returns a list of OpenAlex topics.", +) +async def list_topics( + search: Annotated[ + str | None, + Query(description="Full-text search, for example 'machine learning'."), + ] = None, + filter: Annotated[ + str | None, + Query(description="OpenAlex filter, for example 'domain.id:1,works_count:>1000'."), + ] = None, + sort: Annotated[ + str | None, + Query(description="Sort field, for example 'works_count:desc'."), + ] = "works_count:desc", + group_by: Annotated[ + str | None, + Query(description="OpenAlex group_by field, for example 'domain.id'."), + ] = None, + per_page: Annotated[ + int, + Query(description="Results per page.", ge=1, le=100), + ] = 25, + page: Annotated[ + int | None, + Query(description="Page number. Use cursor for deep pagination.", ge=1), + ] = 1, + cursor: Annotated[ + str | None, + Query(description="Cursor pagination token. Use '*' to start."), + ] = None, + sample: Annotated[ + int | None, + Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000), + ] = None, + select: Annotated[ + str | None, + Query(description="Comma-separated fields to return."), + ] = None, +): + return await logic.list_topics( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) diff --git a/service/src/main/inse/topics/test_logic.py b/service/src/main/inse/topics/test_logic.py new file mode 100644 index 00000000..e6f9a3a4 --- /dev/null +++ b/service/src/main/inse/topics/test_logic.py @@ -0,0 +1,195 @@ +import httpx +import pytest +from fastapi import HTTPException + +from inse.topics import logic +from inse.topics.search_client import OpenAlexTopicsClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@pytest.mark.anyio +async def test_list_topics_maps_openalex_response_to_model(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + "description": "Methods that learn from data.", + "keywords": ["machine learning", "classification"], + "subfield": { + "id": "https://openalex.org/subfields/1702", + "display_name": "Artificial Intelligence", + }, + "field": { + "id": "https://openalex.org/fields/17", + "display_name": "Computer Science", + }, + "domain": { + "id": "https://openalex.org/domains/4", + "display_name": "Physical Sciences", + }, + "works_count": 123, + "cited_by_count": 456, + "ids": { + "openalex": "https://openalex.org/T12419", + "wikipedia": "https://en.wikipedia.org/wiki/Machine_learning", + }, + "works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419", + "created_date": "2023-12-25", + "updated_date": "2023-11-07T05:31:56Z", + } + ], + "group_by": [ + { + "key": "https://openalex.org/domains/4", + "key_display_name": "Physical Sciences", + "count": 1, + } + ], + }, + ) + + client = OpenAlexTopicsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_topics(search="machine learning", client=client) + + assert result.meta.count == 1 + topic = result.results[0] + assert topic.display_name == "Machine learning" + assert topic.var_field.display_name == "Computer Science" + assert topic.subfield.display_name == "Artificial Intelligence" + assert topic.domain.display_name == "Physical Sciences" + assert topic.ids.openalex == "https://openalex.org/T12419" + assert result.group_by[0].key_display_name == "Physical Sciences" + + +@pytest.mark.anyio +async def test_list_topics_rejects_sample_with_sort(): + with pytest.raises(HTTPException) as exc_info: + await logic.list_topics(sample=10, sort="works_count:desc") + + assert exc_info.value.status_code == 400 + + +@pytest.mark.anyio +async def test_list_topics_accepts_practical_openalex_type_variants(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": "1", "page": "1", "per_page": "25"}, + "results": [ + { + "id": 123, + "display_name": 456, + "description": True, + "keywords": ["topic", 123], + "subfield": {"id": 1, "display_name": 2}, + "field": {"id": 3, "display_name": 4}, + "domain": {"id": 5, "display_name": 6}, + "works_count": "12.0", + "cited_by_count": False, + "ids": {"openalex": 123, "wikipedia": 456}, + "created_date": "2023-12-25T10:11:12Z", + "updated_date": "2023-12-25", + } + ], + "group_by": [{"key": True, "count": "1"}], + }, + ) + + client = OpenAlexTopicsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_topics(client=client) + + topic = result.results[0] + assert topic.id == "123" + assert topic.display_name == "456" + assert topic.description == "true" + assert topic.keywords == ["topic", "123"] + assert topic.works_count == 12 + assert topic.cited_by_count is None + assert topic.var_field.id == "3" + assert topic.domain.display_name == "6" + assert topic.ids.wikipedia == "456" + assert topic.created_date.isoformat() == "2023-12-25" + assert topic.updated_date.isoformat() == "2023-12-25T00:00:00+00:00" + assert result.group_by[0].key == "true" + + +@pytest.mark.anyio +async def test_autocomplete_topics_returns_frontend_options(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.params["search"] == "machine learning" + assert request.url.params["filter"] == ( + "domain.id:https://openalex.org/domains/4," + "field.id:https://openalex.org/fields/17," + "subfield.id:https://openalex.org/subfields/1702" + ) + assert request.url.params["sort"] == "works_count:desc" + assert request.url.params["per_page"] == "5" + assert request.url.params["select"] == ( + "id,display_name,description,keywords,subfield,field,domain," + "works_count,cited_by_count,ids" + ) + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "db_response_time_ms": 12}, + "results": [ + { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + "description": "Methods that learn from data.", + "field": {"display_name": "Computer Science"}, + "subfield": {"display_name": "Artificial Intelligence"}, + "domain": {"display_name": "Physical Sciences"}, + "works_count": 123, + "cited_by_count": 456, + "ids": {"openalex": "https://openalex.org/T12419"}, + } + ], + }, + ) + + client = OpenAlexTopicsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.autocomplete_topics( + query="machine learning", + domain_id="https://openalex.org/domains/4", + field_id="https://openalex.org/fields/17", + subfield_id="https://openalex.org/subfields/1702", + limit=5, + client=client, + ) + + assert result.meta.count == 1 + assert result.meta.db_response_time_ms == 12 + assert len(result.results) == 1 + option = result.results[0] + assert option.id == "https://openalex.org/T12419" + assert option.display_name == "Machine learning" + assert option.hint == ( + "Computer Science · Artificial Intelligence · Physical Sciences" + ) + assert option.works_count == 123 + assert option.cited_by_count == 456 + assert option.entity_type == "topic" + assert option.external_id == "https://openalex.org/T12419" diff --git a/service/src/main/inse/topics/test_search_client.py b/service/src/main/inse/topics/test_search_client.py new file mode 100644 index 00000000..69c16a82 --- /dev/null +++ b/service/src/main/inse/topics/test_search_client.py @@ -0,0 +1,75 @@ +import httpx +import pytest + +from inse.topics.search_client import OpenAlexTopicsClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def test_list_topics_params_include_openalex_query_parameters(): + client = OpenAlexTopicsClient(api_key="test-key") + + params = client.list_topics_params( + search="machine learning", + filter="domain.id:4,works_count:>1000", + sort="works_count:desc", + group_by="domain.id", + per_page=10, + page=2, + select="id,display_name", + ) + + assert params == { + "search": "machine learning", + "filter": "domain.id:4,works_count:>1000", + "sort": "works_count:desc", + "group_by": "domain.id", + "per_page": 10, + "page": 2, + "select": "id,display_name", + "api_key": "test-key", + } + + +def test_list_topics_params_prefers_cursor_over_page(): + client = OpenAlexTopicsClient(api_key="test-key") + + params = client.list_topics_params(cursor="*", page=3) + + assert params["cursor"] == "*" + assert "page" not in params + + +@pytest.mark.anyio +async def test_list_topics_calls_openalex_topics_endpoint(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.method == "GET" + assert request.url.path == "/topics" + assert request.url.params["search"] == "machine learning" + assert request.url.params["api_key"] == "test-key" + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + } + ], + }, + ) + + client = OpenAlexTopicsClient( + base_url="https://api.openalex.org", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await client.list_topics(search="machine learning") + + assert result["meta"]["count"] == 1 + assert result["results"][0]["display_name"] == "Machine learning" diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 467410b7..d2196a8e 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -11,6 +11,7 @@ import httpx from fastapi import HTTPException from pydantic import ValidationError from starlette.status import HTTP_502_BAD_GATEWAY +from starlette.status import HTTP_404_NOT_FOUND from starlette.status import HTTP_503_SERVICE_UNAVAILABLE from inse.models.work import Work @@ -33,6 +34,8 @@ async def get_author_works( publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, client: OpenAlexWorksSearchClient | None = None, ) -> WorkPage: search_client = client or OpenAlexWorksSearchClient() @@ -44,6 +47,8 @@ async def get_author_works( publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ) elements, total = _parse_full_work_search_response(data) @@ -116,6 +121,32 @@ async def get_primary_topic_counts( ] +async def get_work( + work_id: str, + client: OpenAlexWorksSearchClient | None = None, +) -> Work: + search_client = client or OpenAlexWorksSearchClient() + try: + data = await search_client.search_work(work_id) + except MissingApiKeyError as exc: + raise HTTPException( + status_code=HTTP_503_SERVICE_UNAVAILABLE, + detail="OpenAlex works search is not configured.", + ) from exc + except httpx.HTTPError as exc: + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex works search request failed.", + ) from exc + elements, _ = _parse_full_work_search_response(data) + if not elements: + raise HTTPException( + status_code=HTTP_404_NOT_FOUND, + detail="Publication not found.", + ) + return elements[0] + + async def get_topics_by_time_by_author( author_id: str, max_topics_per_year: int = 3, @@ -217,6 +248,8 @@ async def _search_author_works_data( publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, ) -> dict: try: return await search_client.search_author_works( @@ -226,6 +259,8 @@ async def _search_author_works_data( publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ) except MissingApiKeyError as exc: logger.error("OpenAlex works Elasticsearch API key is not configured.") diff --git a/service/src/main/inse/works/search_client.py b/service/src/main/inse/works/search_client.py index 8f44a776..36b1b3bb 100644 --- a/service/src/main/inse/works/search_client.py +++ b/service/src/main/inse/works/search_client.py @@ -40,26 +40,52 @@ class OpenAlexWorksSearchClient: publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, ) -> dict[str, Any]: indexed_author_id = f"https://openalex.org/{author_id.strip()}" - filters = self._work_filters(publication_year, work_type, language) + filters = self._work_filters( + publication_year, + work_type, + language, + topic_id, + ) + author_filters: list[dict[str, Any]] = [ + { + "term": { + "authorships.author.id": indexed_author_id, + }, + }, + ] + must_clauses: list[dict[str, Any]] = [ + { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": author_filters, + }, + }, + }, + }, + ] + if institution_id: + must_clauses.append({ + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": institution_id, + }, + }, + }, + }) return { "from": (page - 1) * size, "size": size, "query": { "bool": { - "must": [ - { - "nested": { - "path": "authorships", - "query": { - "term": { - "authorships.author.id": indexed_author_id, - }, - }, - }, - }, - ], + "must": must_clauses, "filter": filters, }, }, @@ -74,6 +100,7 @@ class OpenAlexWorksSearchClient: publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + topic_id: list[str] | None = None, ) -> list[dict[str, Any]]: filters: list[dict[str, Any]] = [] if publication_year: @@ -82,6 +109,21 @@ class OpenAlexWorksSearchClient: filters.append({"terms": {"type": work_type}}) if language: filters.append({"terms": {"language": language}}) + if topic_id: + filters.append({ + "bool": { + "should": [ + { + "nested": { + "path": "topics", + "query": {"terms": {"topics.id": topic_id}}, + }, + }, + {"terms": {"primary_topic.id": topic_id}}, + ], + "minimum_should_match": 1, + }, + }) return filters async def search_author_works( @@ -92,6 +134,8 @@ class OpenAlexWorksSearchClient: publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, ) -> dict[str, Any]: if not self.api_key: raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") @@ -111,8 +155,31 @@ class OpenAlexWorksSearchClient: publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ), ) # logging.debug(f"Response: {response.text}") response.raise_for_status() return response.json() + + async def search_work(self, work_id: str) -> dict[str, Any]: + if not self.api_key: + raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") + + indexed_work_id = f"https://openalex.org/{work_id.strip().split('/')[-1]}" + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.post( + f"/{self.index}/_search", + headers={"Authorization": f"ApiKey {self.api_key}"}, + json={ + "size": 1, + "query": {"term": {"id": indexed_work_id}}, + }, + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/works/service.py b/service/src/main/inse/works/service.py index 127b69a5..12ed15f3 100644 --- a/service/src/main/inse/works/service.py +++ b/service/src/main/inse/works/service.py @@ -16,6 +16,7 @@ from inse.tags import Tags from .. import security from . import logic from inse.models.work_page import WorkPage +from inse.models.work import Work from inse.models.works_list_response import WorksListResponse from inse.models.topic_count import TopicCount from inse.models.topics_by_time import TopicsByTime @@ -47,6 +48,14 @@ async def get_author_works( language: Annotated[ list[str] | None, Query(description="Filter by language code. Can be repeated.") ] = None, + institution_id: Annotated[ + list[str] | None, + Query(description="Filter by OpenAlex institution id. Can be repeated."), + ] = None, + topic_id: Annotated[ + list[str] | None, + Query(description="Filter by OpenAlex topic id. Can be repeated."), + ] = None, principal: security.Principal = Depends( security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) ), @@ -58,6 +67,8 @@ async def get_author_works( publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ) @@ -96,3 +107,20 @@ async def get_topics_by_time_by_author( author_id, max_topics_per_year=max_topics_per_year, ) + + +@router.get( + "/detail/{work_id}", + operation_id="getWork", + response_model=Work, + summary="Returns one publication.", +) +async def get_work( + work_id: Annotated[ + str, Path(description="The OpenAlex work id, for example W2741809807.") + ], + principal: security.Principal = Depends( + security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) + ), +): + return await logic.get_work(work_id) diff --git a/service/src/main/inse/works/test_search_client.py b/service/src/main/inse/works/test_search_client.py index 5a376f26..0bfe1a44 100644 --- a/service/src/main/inse/works/test_search_client.py +++ b/service/src/main/inse/works/test_search_client.py @@ -1,3 +1,5 @@ +import json + import httpx import pytest @@ -19,7 +21,9 @@ def test_author_works_query_searches_authorship_author_id(): assert query["size"] == 25 author_query = query["query"]["bool"]["must"][0]["nested"] assert author_query["path"] == "authorships" - assert author_query["query"]["term"]["authorships.author.id"] == "https://openalex.org/A5023888391" + assert author_query["query"]["bool"]["filter"] == [ + {"term": {"authorships.author.id": "https://openalex.org/A5023888391"}}, + ] assert query["query"]["bool"]["filter"] == [] @@ -33,13 +37,191 @@ def test_author_works_query_adds_publication_filters(): publication_year=[2023, 2024], work_type=["article", "book-chapter"], language=["en", "de"], + institution_id=["https://openalex.org/I123"], + topic_id=["https://openalex.org/T12419"], ) assert query["query"]["bool"]["filter"] == [ {"terms": {"publication_year": [2023, 2024]}}, {"terms": {"type": ["article", "book-chapter"]}}, {"terms": {"language": ["en", "de"]}}, + { + "bool": { + "should": [ + { + "nested": { + "path": "topics", + "query": { + "terms": { + "topics.id": ["https://openalex.org/T12419"], + }, + }, + }, + }, + {"terms": {"primary_topic.id": ["https://openalex.org/T12419"]}}, + ], + "minimum_should_match": 1, + }, + }, ] + assert query["query"]["bool"]["must"] == [ + { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": [ + { + "term": { + "authorships.author.id": "https://openalex.org/A5023888391" + } + }, + ], + }, + }, + }, + }, + { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [ + "https://openalex.org/I123", + ], + }, + }, + }, + }, + ] + + +def test_author_works_query_uses_nested_institution_path(): + client = OpenAlexWorksSearchClient(api_key="test-key") + + query = client.author_works_query( + "A5023888391", + page=1, + size=20, + institution_id=["https://openalex.org/I205640436"], + ) + + assert query["query"]["bool"]["must"][1] == { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [ + "https://openalex.org/I205640436", + ], + }, + }, + }, + } + + +def test_author_works_query_adds_topic_filter(): + client = OpenAlexWorksSearchClient(api_key="test-key") + + query = client.author_works_query( + "A5023888391", + page=1, + size=20, + topic_id=["https://openalex.org/T12419"], + ) + + assert query["query"]["bool"]["filter"] == [ + { + "bool": { + "should": [ + { + "nested": { + "path": "topics", + "query": { + "terms": { + "topics.id": ["https://openalex.org/T12419"], + }, + }, + }, + }, + {"terms": {"primary_topic.id": ["https://openalex.org/T12419"]}}, + ], + "minimum_should_match": 1, + }, + }, + ] + + +@pytest.mark.anyio +async def test_search_author_works_passes_institution_filter_to_query(): + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + assert body["query"]["bool"]["must"][1]["nested"]["path"] == ( + "authorships.institutions" + ) + assert body["query"]["bool"]["must"][1]["nested"]["query"]["terms"] == { + "authorships.institutions.id": ["https://openalex.org/I205640436"], + } + return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) + + client = OpenAlexWorksSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + index="openalex-works", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + await client.search_author_works( + "A5023888391", + page=1, + size=20, + institution_id=["https://openalex.org/I205640436"], + ) + + +@pytest.mark.anyio +async def test_search_author_works_passes_topic_filter_to_query(): + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + assert body["query"]["bool"]["filter"] == [ + { + "bool": { + "should": [ + { + "nested": { + "path": "topics", + "query": { + "terms": { + "topics.id": ["https://openalex.org/T12419"], + }, + }, + }, + }, + { + "terms": { + "primary_topic.id": ["https://openalex.org/T12419"], + }, + }, + ], + "minimum_should_match": 1, + }, + }, + ] + return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) + + client = OpenAlexWorksSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + index="openalex-works", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + await client.search_author_works( + "A5023888391", + page=1, + size=20, + topic_id=["https://openalex.org/T12419"], + ) @pytest.mark.anyio @@ -62,6 +244,26 @@ async def test_search_author_works_calls_elasticsearch_index_with_api_key(): assert result == {"hits": {"total": {"value": 0}, "hits": []}} +@pytest.mark.anyio +async def test_search_work_filters_by_work_id(): + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + assert body == { + "size": 1, + "query": {"term": {"id": "https://openalex.org/W2741809807"}}, + } + return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) + + client = OpenAlexWorksSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + index="openalex-works", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + await client.search_work("W2741809807") + + @pytest.mark.anyio async def test_search_author_works_requires_api_key(): client = OpenAlexWorksSearchClient(api_key="") diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index b5bdf063..f5876c65 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -7,6 +7,7 @@ api/api.ts api/funding.service.ts api/iNSEAccountService.service.ts api/iNSEService.service.ts +api/institutions.service.ts api/items.service.ts api/personNetwork.service.ts api/persons.service.ts @@ -30,6 +31,9 @@ model/authorSummaryStats.ts model/authorsFilterProperties.ts model/authorsListResponse.ts model/authorship.ts +model/autocompleteResponse.ts +model/autocompleteResponseMeta.ts +model/autocompleteResponseResultsInner.ts model/award.ts model/collaborationNetwork.ts model/collaborationNetworkEdge.ts @@ -49,12 +53,18 @@ model/fwci.ts model/groupByResult.ts model/hTTPValidationError.ts model/identityGrant.ts +model/institution.ts +model/institutionGeo.ts +model/institutionIds.ts model/institutionInformation.ts model/institutionNetworkNode.ts +model/institutionsListResponse.ts model/item.ts model/itemCreate.ts model/itemPage.ts +model/latitude.ts model/location.ts +model/longitude.ts model/meta.ts model/model2YrMeanCitedness.ts model/models.ts @@ -63,9 +73,15 @@ model/personBio.ts model/publicationIdsByAuthorPosition.ts model/publicationsByAuthorResponse.ts model/score.ts +model/topic.ts model/topicCount.ts +model/topicDomain.ts +model/topicField.ts +model/topicIds.ts +model/topicSubfield.ts model/topicsByTime.ts model/topicsByYear.ts +model/topicsListResponse.ts model/validationError.ts model/validationErrorLocInner.ts model/value.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index eae43798..ea1f3603 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -4,6 +4,8 @@ export * from './iNSEAccountService.service'; import { INSEAccountServiceService } from './iNSEAccountService.service'; export * from './iNSEService.service'; import { INSEServiceService } from './iNSEService.service'; +export * from './institutions.service'; +import { InstitutionsService } from './institutions.service'; export * from './items.service'; import { ItemsService } from './items.service'; export * from './personNetwork.service'; @@ -14,4 +16,4 @@ export * from './topics.service'; import { TopicsService } from './topics.service'; export * from './works.service'; import { WorksService } from './works.service'; -export const APIS = [FundingService, INSEAccountServiceService, INSEServiceService, ItemsService, PersonNetworkService, PersonsService, TopicsService, WorksService]; +export const APIS = [FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, ItemsService, PersonNetworkService, PersonsService, TopicsService, WorksService]; diff --git a/webapp/src/app/api/api/institutions.service.ts b/webapp/src/app/api/api/institutions.service.ts new file mode 100644 index 00000000..ff8895a9 --- /dev/null +++ b/webapp/src/app/api/api/institutions.service.ts @@ -0,0 +1,192 @@ +/** + * 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 { AutocompleteResponse } from '../model/autocompleteResponse'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { InstitutionsListResponse } from '../model/institutionsListResponse'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + + + +@Injectable({ + providedIn: 'root' +}) +export class InstitutionsService extends BaseService { + + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); + } + + /** + * Returns institution options for autocomplete inputs. + * @endpoint get /api/institutions/autocomplete + * @param query Institution search text, for example \'Duisburg Essen\'. + * @param countryCode Optional ISO country code filter. + * @param type Optional institution type filter. + * @param limit Maximum number of autocomplete options. + * @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 autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling autocompleteInstitutions.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + countryCode, 'countryCode'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + type, 'type'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + + 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/institutions/autocomplete`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Returns a list of OpenAlex institutions. + * @endpoint get /api/institutions + * @param search Full-text search, for example \'Duisburg Essen\'. + * @param filter OpenAlex filter, for example \'country_code:DE,type:education\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'country_code\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + * @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 listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + search, 'search'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filter, 'filter'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sort, 'sort'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + groupBy, 'group_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + perPage, 'per_page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + cursor, 'cursor'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sample, 'sample'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + select, 'select'); + + 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/institutions`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + +} diff --git a/webapp/src/app/api/api/topics.service.ts b/webapp/src/app/api/api/topics.service.ts index fdd4b44c..2667546d 100644 --- a/webapp/src/app/api/api/topics.service.ts +++ b/webapp/src/app/api/api/topics.service.ts @@ -16,8 +16,12 @@ import { HttpClient, HttpHeaders, HttpParams, import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; +// @ts-ignore +import { AutocompleteResponse } from '../model/autocompleteResponse'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { TopicsListResponse } from '../model/topicsListResponse'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -35,6 +39,78 @@ export class TopicsService extends BaseService { super(basePath, configuration); } + /** + * Returns topic options for autocomplete inputs. + * @endpoint get /api/topics/autocomplete + * @param query Topic search text, for example \'machine learning\'. + * @param domainId Optional OpenAlex domain id filter. + * @param fieldId Optional OpenAlex field id filter. + * @param subfieldId Optional OpenAlex subfield id filter. + * @param limit Maximum number of autocomplete options. + * @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 autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling autocompleteTopics.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + domainId, 'domainId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + fieldId, 'fieldId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + subfieldId, 'subfieldId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + + 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/topics/autocomplete`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Builds the topic hierarchy cache. * @endpoint get /api/inse-service/topics/cache @@ -210,4 +286,85 @@ export class TopicsService extends BaseService { ); } + /** + * Returns a list of OpenAlex topics. + * @endpoint get /api/topics + * @param search Full-text search, for example \'machine learning\'. + * @param filter OpenAlex filter, for example \'domain.id:1,works_count:>1000\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'domain.id\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + * @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 listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + search, 'search'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filter, 'filter'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sort, 'sort'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + groupBy, 'group_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + perPage, 'per_page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + cursor, 'cursor'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sample, 'sample'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + select, 'select'); + + 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/topics`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + } diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts index 62474a83..63355411 100644 --- a/webapp/src/app/api/api/works.service.ts +++ b/webapp/src/app/api/api/works.service.ts @@ -23,6 +23,8 @@ import { TopicCount } from '../model/topicCount'; // @ts-ignore import { TopicsByTime } from '../model/topicsByTime'; // @ts-ignore +import { Work } from '../model/work'; +// @ts-ignore import { WorkPage } from '../model/workPage'; // @ts-ignore import { WorksListResponse } from '../model/worksListResponse'; @@ -110,13 +112,15 @@ export class WorksService extends BaseService { * @param publicationYear Filter by publication year. Can be repeated. * @param type Filter by publication type. Can be repeated. * @param language Filter by language code. Can be repeated. + * @param institutionId Filter by OpenAlex institution id. Can be repeated. + * @param topicId Filter by OpenAlex topic id. Can be repeated. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (authorId === null || authorId === undefined) { throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.'); } @@ -144,6 +148,18 @@ export class WorksService extends BaseService { element, 'language'); }) } + if (institutionId) { + institutionId.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'institution_id'); + }) + } + if (topicId) { + topicId.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic_id'); + }) + } let localVarHeaders = this.defaultHeaders; @@ -311,4 +327,62 @@ export class WorksService extends BaseService { ); } + /** + * Returns one publication. + * @endpoint get /api/works/detail/{work_id} + * @param workId The OpenAlex work id, for example W2741809807. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getWork(workId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getWork(workId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWork(workId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWork(workId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (workId === null || workId === undefined) { + throw new Error('Required parameter workId was null or undefined when calling getWork.'); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (bearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer '); + + 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/works/detail/${this.configuration.encodeParam({name: "workId", value: workId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + } diff --git a/webapp/src/app/api/model/autocompleteResponse.ts b/webapp/src/app/api/model/autocompleteResponse.ts new file mode 100644 index 00000000..e220f57b --- /dev/null +++ b/webapp/src/app/api/model/autocompleteResponse.ts @@ -0,0 +1,21 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { AutocompleteResponseMeta } from './autocompleteResponseMeta'; +import { AutocompleteResponseResultsInner } from './autocompleteResponseResultsInner'; + + +/** + * AutocompleteResponse + */ +export interface AutocompleteResponse { + meta?: AutocompleteResponseMeta | null; + results?: Array | null; +} + diff --git a/webapp/src/app/api/model/autocompleteResponseMeta.ts b/webapp/src/app/api/model/autocompleteResponseMeta.ts new file mode 100644 index 00000000..2e080d39 --- /dev/null +++ b/webapp/src/app/api/model/autocompleteResponseMeta.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * AutocompleteResponseMeta + */ +export interface AutocompleteResponseMeta { + count?: number | null; + db_response_time_ms?: number | null; +} + diff --git a/webapp/src/app/api/model/autocompleteResponseResultsInner.ts b/webapp/src/app/api/model/autocompleteResponseResultsInner.ts new file mode 100644 index 00000000..99ba71fe --- /dev/null +++ b/webapp/src/app/api/model/autocompleteResponseResultsInner.ts @@ -0,0 +1,24 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * AutocompleteResponseResultsInner + */ +export interface AutocompleteResponseResultsInner { + id?: string | null; + display_name?: string | null; + hint?: string | null; + cited_by_count?: number | null; + works_count?: number | null; + entity_type?: string | null; + external_id?: string | null; +} + diff --git a/webapp/src/app/api/model/institution.ts b/webapp/src/app/api/model/institution.ts new file mode 100644 index 00000000..6b1a5778 --- /dev/null +++ b/webapp/src/app/api/model/institution.ts @@ -0,0 +1,41 @@ +/** + * 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 { InstitutionIds } from './institutionIds'; +import { AuthorCountsByYearInner } from './authorCountsByYearInner'; +import { AuthorSummaryStats } from './authorSummaryStats'; +import { InstitutionGeo } from './institutionGeo'; + + +/** + * A university, research organization, or other affiliation + */ +export interface Institution { + id?: string | null; + ror?: string | null; + display_name?: string | null; + country_code?: string | null; + type?: string | null; + homepage_url?: string | null; + image_url?: string | null; + image_thumbnail_url?: string | null; + display_name_acronyms?: Array | null; + display_name_alternatives?: Array | null; + works_count?: number | null; + cited_by_count?: number | null; + summary_stats?: AuthorSummaryStats | null; + geo?: InstitutionGeo | null; + lineage?: Array | null; + ids?: InstitutionIds | null; + counts_by_year?: Array | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; +} + diff --git a/webapp/src/app/api/model/institutionGeo.ts b/webapp/src/app/api/model/institutionGeo.ts new file mode 100644 index 00000000..949b73f4 --- /dev/null +++ b/webapp/src/app/api/model/institutionGeo.ts @@ -0,0 +1,26 @@ +/** + * 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 { Latitude } from './latitude'; +import { Longitude } from './longitude'; + + +/** + * Location information: + */ +export interface InstitutionGeo { + city?: string | null; + geonames_city_id?: string | null; + region?: string | null; + country_code?: string | null; + country?: string | null; + latitude?: Latitude | null; + longitude?: Longitude | null; +} + diff --git a/webapp/src/app/api/model/institutionIds.ts b/webapp/src/app/api/model/institutionIds.ts new file mode 100644 index 00000000..93d801e1 --- /dev/null +++ b/webapp/src/app/api/model/institutionIds.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * External identifiers: + */ +export interface InstitutionIds { + openalex?: string | null; + ror?: string | null; + mag?: number | null; + grid?: string | null; + wikipedia?: string | null; + wikidata?: string | null; +} + diff --git a/webapp/src/app/api/model/institutionsListResponse.ts b/webapp/src/app/api/model/institutionsListResponse.ts new file mode 100644 index 00000000..908d72fe --- /dev/null +++ b/webapp/src/app/api/model/institutionsListResponse.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Meta } from './meta'; +import { Institution } from './institution'; +import { GroupByResult } from './groupByResult'; + + +/** + * InstitutionsListResponse + */ +export interface InstitutionsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; +} + diff --git a/webapp/src/app/api/model/latitude.ts b/webapp/src/app/api/model/latitude.ts new file mode 100644 index 00000000..fe6b49aa --- /dev/null +++ b/webapp/src/app/api/model/latitude.ts @@ -0,0 +1,14 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface Latitude { +} + diff --git a/webapp/src/app/api/model/longitude.ts b/webapp/src/app/api/model/longitude.ts new file mode 100644 index 00000000..b0d39fce --- /dev/null +++ b/webapp/src/app/api/model/longitude.ts @@ -0,0 +1,14 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface Longitude { +} + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index c8862064..3c24b908 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -12,6 +12,9 @@ export * from './authorSummaryStats'; export * from './authorsFilterProperties'; export * from './authorsListResponse'; export * from './authorship'; +export * from './autocompleteResponse'; +export * from './autocompleteResponseMeta'; +export * from './autocompleteResponseResultsInner'; export * from './award'; export * from './collaborationNetwork'; export * from './collaborationNetworkEdge'; @@ -31,12 +34,18 @@ export * from './fwci'; export * from './groupByResult'; export * from './hTTPValidationError'; export * from './identityGrant'; +export * from './institution'; +export * from './institutionGeo'; +export * from './institutionIds'; export * from './institutionInformation'; export * from './institutionNetworkNode'; +export * from './institutionsListResponse'; export * from './item'; export * from './itemCreate'; export * from './itemPage'; +export * from './latitude'; export * from './location'; +export * from './longitude'; export * from './meta'; export * from './model2YrMeanCitedness'; export * from './openAccess'; @@ -44,9 +53,15 @@ export * from './personBio'; export * from './publicationIdsByAuthorPosition'; export * from './publicationsByAuthorResponse'; export * from './score'; +export * from './topic'; export * from './topicCount'; +export * from './topicDomain'; +export * from './topicField'; +export * from './topicIds'; +export * from './topicSubfield'; export * from './topicsByTime'; export * from './topicsByYear'; +export * from './topicsListResponse'; export * from './validationError'; export * from './validationErrorLocInner'; export * from './value'; diff --git a/webapp/src/app/api/model/topic.ts b/webapp/src/app/api/model/topic.ts new file mode 100644 index 00000000..9fc0ee63 --- /dev/null +++ b/webapp/src/app/api/model/topic.ts @@ -0,0 +1,34 @@ +/** + * 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 { TopicDomain } from './topicDomain'; +import { TopicIds } from './topicIds'; +import { TopicSubfield } from './topicSubfield'; +import { TopicField } from './topicField'; + + +/** + * A research topic automatically assigned to works + */ +export interface Topic { + id?: string | null; + display_name?: string | null; + description?: string | null; + keywords?: Array | null; + subfield?: TopicSubfield | null; + field?: TopicField | null; + domain?: TopicDomain | null; + works_count?: number | null; + cited_by_count?: number | null; + ids?: TopicIds | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; +} + diff --git a/webapp/src/app/api/model/topicDomain.ts b/webapp/src/app/api/model/topicDomain.ts new file mode 100644 index 00000000..652b1bca --- /dev/null +++ b/webapp/src/app/api/model/topicDomain.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * The domain (highest level) containing this topic: + */ +export interface TopicDomain { + id?: string | null; + display_name?: string | null; +} + diff --git a/webapp/src/app/api/model/topicField.ts b/webapp/src/app/api/model/topicField.ts new file mode 100644 index 00000000..c7351675 --- /dev/null +++ b/webapp/src/app/api/model/topicField.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * The field (second level) containing this topic: + */ +export interface TopicField { + id?: string | null; + display_name?: string | null; +} + diff --git a/webapp/src/app/api/model/topicIds.ts b/webapp/src/app/api/model/topicIds.ts new file mode 100644 index 00000000..4aa6738f --- /dev/null +++ b/webapp/src/app/api/model/topicIds.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * External identifiers: + */ +export interface TopicIds { + openalex?: string | null; + wikipedia?: string | null; +} + diff --git a/webapp/src/app/api/model/topicSubfield.ts b/webapp/src/app/api/model/topicSubfield.ts new file mode 100644 index 00000000..53d37842 --- /dev/null +++ b/webapp/src/app/api/model/topicSubfield.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * The subfield (third level) containing this topic: + */ +export interface TopicSubfield { + id?: string | null; + display_name?: string | null; +} + diff --git a/webapp/src/app/api/model/topicsListResponse.ts b/webapp/src/app/api/model/topicsListResponse.ts new file mode 100644 index 00000000..43f21226 --- /dev/null +++ b/webapp/src/app/api/model/topicsListResponse.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Meta } from './meta'; +import { GroupByResult } from './groupByResult'; +import { Topic } from './topic'; + + +/** + * TopicsListResponse + */ +export interface TopicsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; +} + diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 8abb6893..006b1c65 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -26,6 +26,14 @@ export const routes: Routes = [ (mod) => mod.PersonListComponent, ), }, + { + path: 'publication/:publicationId', + canActivate: [userGuard], + loadComponent: () => + import('./modules/publication-detail/publication-detail.component').then( + (mod) => mod.PublicationDetailComponent, + ), + }, { path: 'person/:id', canActivate: [userGuard], @@ -98,12 +106,6 @@ export const routes: Routes = [ (mod) => mod.InstitutionComponent, ), }, - { - path: 'work/:id', - canActivate: [userGuard], - loadComponent: () => - import('./modules/work/work.component').then((mod) => mod.WorkComponent), - }, { path: '**', redirectTo: 'login', diff --git a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.html b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.html index cee55b3c..c01f8cec 100644 --- a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.html +++ b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.html @@ -44,7 +44,7 @@
    @for (work of element.works; track $index) {
  • - + {{ work.title }}
  • diff --git a/webapp/src/app/modules/person-network-publications/person-network-publications.component.html b/webapp/src/app/modules/person-network-publications/person-network-publications.component.html index 80a737c9..10a5c436 100644 --- a/webapp/src/app/modules/person-network-publications/person-network-publications.component.html +++ b/webapp/src/app/modules/person-network-publications/person-network-publications.component.html @@ -15,7 +15,7 @@ - + open_in_new diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html index cfd25c2e..799f618a 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html @@ -112,7 +112,16 @@ *ngFor="let item of timelineItems; let index = index; trackBy: trackByYear" class="timeline-item" > -

    {{ getMainTopic(item) }}

    +

    + +

    {{ item.publication_count }} @@ -121,14 +130,17 @@
    - {{ topic.name }} {{ topic.count }} - + @@ -155,7 +167,16 @@
    {{ getPhaseYearLabel(phase) }} -

    {{ phase.primaryTopicName }}

    +

    + +

    {{ phase.publication_count }} {{ phase.publication_count === 1 ? 'Publikation' : 'Publikationen' }} @@ -165,14 +186,17 @@
    - {{ topic.name }} {{ topic.count }} - + @@ -208,16 +232,19 @@ else noPhaseYearTopics " > - {{ topic.name }} {{ topic.count }} - + @@ -246,4 +273,4 @@ Keine Timeline-Daten vorhanden.
    - \ No newline at end of file + diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss index 16ca7935..4088f182 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss @@ -315,6 +315,32 @@ font-size: 12px; } +.main-topic-button { + padding: 0; + border: 0; + background: transparent; + color: inherit; + font: inherit; + font-weight: inherit; + line-height: inherit; + cursor: pointer; + + &:hover:not(:disabled) { + color: #0057ff; + text-decoration: underline; + } + + &:focus-visible { + outline: 2px solid #0057ff; + outline-offset: 3px; + border-radius: 3px; + } + + &:disabled { + cursor: default; + } +} + .topic-list { display: flex; flex-direction: column; @@ -335,6 +361,24 @@ font-size: 12px; font-weight: 500; line-height: 1.25; + border: 0; + font-family: inherit; + cursor: pointer; + transition: transform 0.15s ease, box-shadow 0.15s ease; + + &:hover:not(:disabled) { + transform: translateY(-1px); + box-shadow: 0 4px 10px rgba(15, 23, 42, 0.12); + } + + &:focus-visible { + outline: 2px solid #0057ff; + outline-offset: 2px; + } + + &:disabled { + cursor: default; + } } .topic-name { @@ -515,6 +559,22 @@ color: #40506f; font-size: 11px; line-height: 1.25; + border: 0; + font-family: inherit; + cursor: pointer; + + &:hover:not(:disabled) { + color: #0057ff; + } + + &:focus-visible { + outline: 2px solid #0057ff; + outline-offset: 2px; + } + + &:disabled { + cursor: default; + } span { overflow-wrap: anywhere; @@ -686,4 +746,4 @@ .phase-year-row { grid-template-columns: 1fr; } -} \ No newline at end of file +} diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts index 56ec4486..5ca333ef 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts @@ -9,6 +9,7 @@ import { } from '@angular/core'; export interface TopicTimelineTopic { + id?: string; name: string; count: number; } @@ -27,11 +28,17 @@ export interface TimelineYearRange { endYear: number; } +export interface TimelineTopicSelection { + topic: TopicTimelineTopic; + years: number[]; +} + interface ResearchTimelinePhase { id: string; startYear: number; endYear: number; publication_count: number; + primaryTopic: TopicTimelineTopic; primaryTopicName: string; years: TopicTimelineElement[]; topics: TopicTimelineTopic[]; @@ -41,6 +48,7 @@ interface WorkingResearchTimelinePhase { startYear: number; endYear: number; publication_count: number; + primaryTopic: TopicTimelineTopic; primaryTopicName: string; years: TopicTimelineElement[]; } @@ -62,6 +70,7 @@ export class ResearchTimelineComponent implements OnChanges { @Output() viewModeChange = new EventEmitter(); @Output() yearRangeChange = new EventEmitter(); + @Output() topicSelect = new EventEmitter(); timelineViewMode: TimelineViewMode = 'years'; @@ -167,12 +176,27 @@ export class ResearchTimelineComponent implements OnChanges { this.emitYearRangeChange(); } + selectTopic(topic: TopicTimelineTopic): void { + if (!topic.id) { + return; + } + + this.topicSelect.emit({ + topic, + years: this.createSelectedYears(), + }); + } + getPrimaryTopic(item: TopicTimelineElement): TopicTimelineTopic | undefined { return (item.primary_topics ?? [])[0]; } getMainTopic(item: TopicTimelineElement): string { - return this.getPrimaryTopic(item)?.name ?? this.getFirstTopic(item)?.name ?? 'Keine Topics'; + return this.getMainTopicItem(item)?.name ?? 'Keine Topics'; + } + + getMainTopicItem(item: TopicTimelineElement): TopicTimelineTopic | undefined { + return this.getPrimaryTopic(item) ?? this.getFirstTopic(item); } getDisplayedTopics(item: TopicTimelineElement): TopicTimelineTopic[] { @@ -276,7 +300,10 @@ export class ResearchTimelineComponent implements OnChanges { if (candidates.length === 0) { this.pushWorkingPhase(phases, currentPhase); - currentPhase = this.createWorkingPhase(item, this.getMainTopic(item)); + currentPhase = this.createWorkingPhase( + item, + this.getMainTopicItem(item) ?? { name: 'Keine Topics', count: 0 }, + ); continue; } @@ -299,7 +326,7 @@ export class ResearchTimelineComponent implements OnChanges { } this.pushWorkingPhase(phases, currentPhase); - currentPhase = this.createWorkingPhase(item, candidates[0].name); + currentPhase = this.createWorkingPhase(item, candidates[0]); } this.pushWorkingPhase(phases, currentPhase); @@ -309,13 +336,14 @@ export class ResearchTimelineComponent implements OnChanges { private createWorkingPhase( item: TopicTimelineElement, - primaryTopicName: string, + primaryTopic: TopicTimelineTopic, ): WorkingResearchTimelinePhase { return { startYear: item.year, endYear: item.year, publication_count: item.publication_count, - primaryTopicName, + primaryTopic, + primaryTopicName: primaryTopic.name, years: [item], }; } @@ -343,6 +371,7 @@ export class ResearchTimelineComponent implements OnChanges { ): TopicTimelineTopic[] { const counts = new Map(); const originalNames = new Map(); + const ids = new Map(); for (const year of years) { for (const topic of year.topics ?? []) { @@ -353,12 +382,16 @@ export class ResearchTimelineComponent implements OnChanges { const normalizedName = this.normalizeTopicName(topic.name); originalNames.set(normalizedName, topic.name); + if (topic.id) { + ids.set(normalizedName, topic.id); + } counts.set(normalizedName, (counts.get(normalizedName) ?? 0) + topic.count); } } return Array.from(counts.entries()) .map(([normalizedName, count]) => ({ + id: ids.get(normalizedName), name: originalNames.get(normalizedName) ?? normalizedName, count, })) @@ -372,6 +405,13 @@ export class ResearchTimelineComponent implements OnChanges { .slice(0, this.displayedPhaseTopicLimit); } + private createSelectedYears(): number[] { + return Array.from( + { length: this.selectedEndYear - this.selectedStartYear + 1 }, + (_, index) => this.selectedStartYear + index, + ); + } + private getDominantPrimaryTopicCandidates(item: TopicTimelineElement): TopicTimelineTopic[] { const primaryTopics = item.primary_topics ?? []; @@ -443,4 +483,4 @@ export class ResearchTimelineComponent implements OnChanges { endYear: this.selectedEndYear, }); } -} \ No newline at end of file +} diff --git a/webapp/src/app/modules/person-overview/person-overview.component.html b/webapp/src/app/modules/person-overview/person-overview.component.html index 363ee7f6..9faf2002 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.html +++ b/webapp/src/app/modules/person-overview/person-overview.component.html @@ -8,5 +8,6 @@ [endYear]="timelineEndYear" (viewModeChange)="onTimelineViewModeChange($event)" (yearRangeChange)="onTimelineYearRangeChange($event)" + (topicSelect)="onTimelineTopicSelect($event)" > - \ No newline at end of file + diff --git a/webapp/src/app/modules/person-overview/person-overview.component.ts b/webapp/src/app/modules/person-overview/person-overview.component.ts index e3c31b4a..bb30949f 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -10,6 +10,7 @@ import { ResearchTimelineComponent, TimelineViewMode, TimelineYearRange, + TimelineTopicSelection, TopicTimelineElement, TopicTimelineTopic, } from './components/research-timeline/research-timeline.component'; @@ -89,6 +90,22 @@ export class PersonOverviewComponent implements OnInit { ); } + onTimelineTopicSelect(selection: TimelineTopicSelection): void { + if (!selection.topic.id) { + return; + } + + void this.router.navigate(['../publications'], { + relativeTo: this.route, + queryParams: { + publicationPage: 1, + publicationYear: selection.years, + publicationTopicId: selection.topic.id, + publicationTopicName: selection.topic.name, + }, + }); + } + private findAuthorId(paramMaps: readonly ParamMap[]): string { return ( paramMaps @@ -140,7 +157,8 @@ export class PersonOverviewComponent implements OnInit { } private mapTopicCounts(topics: TopicCount[] | undefined): TopicTimelineTopic[] { - return (topics ?? []).map((topic) => ({ + return (topics ?? []).map((topic: TopicCount & { id?: string | null }) => ({ + id: topic.id ?? undefined, name: topic.name, count: topic.count ?? 0, })); @@ -175,4 +193,4 @@ export class PersonOverviewComponent implements OnInit { replaceUrl, }); } -} \ No newline at end of file +} diff --git a/webapp/src/app/modules/person-publications/person-publications.component.html b/webapp/src/app/modules/person-publications/person-publications.component.html index 96c5df8d..a34b24ef 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.html +++ b/webapp/src/app/modules/person-publications/person-publications.component.html @@ -1,16 +1,16 @@
    -
    -
    -
    Publikationen
    -

    Übersicht der wissenschaftlichen Veröffentlichungen.

    -
    +
    +
    Publikationen
    +

    Übersicht der wissenschaftlichen Veröffentlichungen.

    +
    +
    - Jahr @for (year of publicationYearOptions; track year) { {{ year }} @@ -19,11 +19,11 @@ - Typ @for (type of typeOptions; track type.value) { {{ type.label }} @@ -32,11 +32,11 @@ - Sprache @for (language of languageOptions; track language.value) { {{ @@ -46,11 +46,108 @@ -
    + + @if (selectedInstitutions.length || selectedTopics.length) { +
    + @for (institution of selectedInstitutions; track institution.id) { + + {{ institution.display_name }} + + + } + @for (topic of selectedTopics; track topic.id) { + + {{ topic.display_name }} + + + } +
    + }
    @@ -64,14 +161,12 @@ Titel - @if (doiUrl(publication.doi); as url) { - - {{ publication.title || "Ohne Titel" }} - - } @else { -
    {{ publication.title || "Ohne Titel" }}
    - } -
    Becker, A.; Müller, T.; Zhang, L.
    + + {{ publication.title || "Ohne Titel" }} +
    @@ -102,6 +197,33 @@ + + Institutionen + + @let publicationInstitutions = institutions(publication); +
    + @for ( + institution of publicationInstitutions.slice(0, 3); + track institution.id + ) { + + {{ institution.name }} + + } @empty { + - + } + @if (publicationInstitutions.length > 3) { + + +{{ publicationInstitutions.length - 3 }} + + } +
    + +
    + Zitationen @@ -112,14 +234,20 @@ Themen + @let publicationTopics = publication.topics ?? [];
    - @for (topic of (publication.topics ?? []).slice(0, 3); track topic.id) { - + @for (topic of publicationTopics.slice(0, 3); track topic.id) { + {{ topic.display_name }} - + } @empty { - } + @if (publicationTopics.length > 3) { + + +{{ publicationTopics.length - 3 }} + + }
    diff --git a/webapp/src/app/modules/person-publications/person-publications.component.scss b/webapp/src/app/modules/person-publications/person-publications.component.scss index 0f05c502..e6d4fe76 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.scss +++ b/webapp/src/app/modules/person-publications/person-publications.component.scss @@ -6,10 +6,10 @@ .section-heading { display: flex; - align-items: flex-start; + align-items: center; justify-content: space-between; - gap: 24px; - margin-bottom: 22px; + gap: 18px; + margin-bottom: 18px; } h2 { @@ -25,11 +25,20 @@ h2 { font-size: 14px; } +.publication-filter-stack { + display: flex; + align-items: flex-start; + flex-direction: column; + gap: 8px; + padding-top: 10px; + padding-bottom: 25px; +} + .publication-filters { display: flex; flex-wrap: wrap; justify-content: flex-end; - align-items: flex-start; + align-items: center; gap: 10px; } @@ -37,17 +46,117 @@ h2 { width: 150px; } -.publication-filters button { +.publication-filters .institution-filter, +.publication-filters .topic-filter { + width: 320px; +} + +.publication-filters .reset-filter-btn { + min-width: 132px; height: 42px; - border-color: var(--sg-border); + padding: 0 14px; + border-color: #d9e2f0; border-radius: var(--sg-radius-sm); color: var(--sg-text); + background: #fff; +} + +.publication-filters .reset-filter-btn mat-icon { + margin-right: 6px; + width: 20px; + height: 20px; + font-size: 20px; } ::ng-deep .publication-filters .mat-mdc-form-field-subscript-wrapper { display: none; } +::ng-deep .publication-filters .mat-mdc-text-field-wrapper { + height: 42px; + background: #fff; + border-radius: var(--sg-radius-sm); +} + +::ng-deep .publication-filters .mat-mdc-form-field-infix { + min-height: 42px; + padding-top: 11px; + padding-bottom: 9px; +} + +::ng-deep .publication-filters .mdc-notched-outline__leading, +::ng-deep .publication-filters .mdc-notched-outline__notch, +::ng-deep .publication-filters .mdc-notched-outline__trailing { + border-color: #d9e2f0; +} + +::ng-deep .publication-filters .mat-mdc-select-value, +::ng-deep .publication-filters input.mat-mdc-input-element { + color: var(--sg-text); + font-size: 14px; +} + +::ng-deep .publication-filters .mat-mdc-select-placeholder, +::ng-deep .publication-filters input.mat-mdc-input-element::placeholder { + color: var(--sg-text-muted); + opacity: 1; + font-size: 14px; +} + +::ng-deep .publication-filters .mat-mdc-form-field-icon-suffix, +::ng-deep .publication-filters .mat-mdc-select-arrow-wrapper { + transform: none; +} + +::ng-deep .mat-mdc-option small { + display: block; + color: var(--sg-text-muted); + font-size: 11px; + line-height: 1.2; +} + +.selected-filter-chips { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 6px; + max-width: 900px; + margin: 0; +} + +.selected-filter-chip { + display: inline-flex; + align-items: center; + max-width: 320px; + min-height: 26px; + padding: 3px 4px 3px 9px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + font-size: 11px; + line-height: 1.2; +} + +.selected-filter-chip button { + display: inline-grid; + place-items: center; + width: 20px; + height: 20px; + margin-left: 3px; + padding: 0; + border: 0; + background: transparent; + color: var(--sg-text-muted); + cursor: pointer; +} + +.selected-filter-chip mat-icon { + width: 14px; + height: 14px; + font-size: 14px; +} + .table-wrap { position: relative; overflow-x: auto; @@ -55,7 +164,7 @@ h2 { table { width: 100%; - min-width: 980px; + min-width: 1120px; border-collapse: separate; border-spacing: 0 10px; overflow: hidden; @@ -111,6 +220,63 @@ a.title:hover { max-width: 320px; } +.publication-topic-tag, +.publication-topic-more { + display: inline-flex; + align-items: center; + max-width: 180px; + min-height: 24px; + padding: 3px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + font-size: 11px; + line-height: 1.2; +} + +.publication-topic-tag { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.publication-topic-more { + color: var(--sg-text-muted); +} + +.institution-tags { + display: flex; + flex-wrap: wrap; + gap: 6px; + max-width: 280px; +} + +.publication-institution-tag, +.publication-institution-more { + display: inline-flex; + align-items: center; + max-width: 180px; + min-height: 24px; + padding: 3px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + font-size: 11px; + line-height: 1.2; +} + +.publication-institution-tag { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.publication-institution-more { + color: var(--sg-text-muted); +} + ::ng-deep .mat-mdc-header-cell { color: var(--sg-text-muted); font-size: 12px; @@ -155,12 +321,27 @@ mat-paginator { flex-direction: column; } + .publication-filter-stack { + align-items: stretch; + } + .publication-filters { justify-content: stretch; + max-width: none; } .publication-filters mat-form-field, .publication-filters button { width: 100%; } + + .publication-filters .institution-filter, + .publication-filters .topic-filter { + width: 100%; + } + + .selected-filter-chips { + justify-content: flex-start; + max-width: none; + } } diff --git a/webapp/src/app/modules/person-publications/person-publications.component.ts b/webapp/src/app/modules/person-publications/person-publications.component.ts index 1350a65b..4867052f 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.ts +++ b/webapp/src/app/modules/person-publications/person-publications.component.ts @@ -1,6 +1,11 @@ -import { Component, OnInit, ViewChild } from '@angular/core'; +import { Component, DestroyRef, OnInit, ViewChild, inject } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; -import { ActivatedRoute } from '@angular/router'; +import { ActivatedRoute, ParamMap, Router, RouterLink } from '@angular/router'; +import { + MatAutocompleteModule, + MatAutocompleteSelectedEvent, +} from '@angular/material/autocomplete'; import { MatIconModule } from '@angular/material/icon'; import { MatPaginator, @@ -12,46 +17,113 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { MatTableModule } from '@angular/material/table'; import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { + catchError, + combineLatest, + debounceTime, + distinctUntilChanged, + finalize, + map, + of, + switchMap, +} from 'rxjs'; import { Work, WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; import { createLoadError } from '../../shared/utils/errorHandler'; import { ChipComponent } from '../../shared/ui/chip/chip.component'; +interface InstitutionAutocompleteOption { + id?: string | null; + display_name?: string | null; + hint?: string | null; + cited_by_count?: number | null; + works_count?: number | null; + entity_type?: string | null; + external_id?: string | null; +} + +interface InstitutionAutocompleteResponse { + results?: InstitutionAutocompleteOption[] | null; +} + +interface TopicAutocompleteOption { + id?: string | null; + display_name?: string | null; + hint?: string | null; + cited_by_count?: number | null; + works_count?: number | null; + entity_type?: string | null; + external_id?: string | null; +} + +interface TopicAutocompleteResponse { + results?: TopicAutocompleteOption[] | null; +} + +interface PublicationFilterQueryState { + pageIndex: number; + pageSize: number; + publicationYears: number[]; + types: string[]; + languages: string[]; + institutions: InstitutionAutocompleteOption[]; + topics: TopicAutocompleteOption[]; +} + @Component({ selector: 'app-person-publications', imports: [ MatButtonModule, + MatAutocompleteModule, ChipComponent, MatIconModule, MatFormFieldModule, + MatInputModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSnackBarModule, MatTableModule, ReactiveFormsModule, + RouterLink, ], templateUrl: './person-publications.component.html', styleUrl: './person-publications.component.scss', }) export class PersonPublicationsComponent implements OnInit { @ViewChild(MatPaginator) paginator?: MatPaginator; + private readonly destroyRef = inject(DestroyRef); displayedColumns: string[] = [ 'title', 'type', 'year', 'language', + 'institutions', 'topics', 'citations', ]; publications: Work[] = []; total = 0; loading = false; + institutionLookupLoading = false; + topicLookupLoading = false; authorId = ''; currentPageIndex = 0; + institutionOptions: InstitutionAutocompleteOption[] = []; + selectedInstitutions: InstitutionAutocompleteOption[] = []; + topicOptions: TopicAutocompleteOption[] = []; + selectedTopics: TopicAutocompleteOption[] = []; + readonly institutionSearchControl = new FormControl< + string | InstitutionAutocompleteOption + >('', { nonNullable: true }); + readonly topicSearchControl = new FormControl('', { + nonNullable: true, + }); readonly filterForm = new FormGroup({ publicationYears: new FormControl([], { nonNullable: true }), @@ -61,6 +133,18 @@ export class PersonPublicationsComponent implements OnInit { readonly publicationYearOptions = this.createPublicationYearOptions(); + private readonly queryParamKeys = { + page: 'publicationPage', + pageSize: 'publicationPageSize', + years: 'publicationYear', + types: 'publicationType', + languages: 'publicationLanguage', + institutionIds: 'publicationInstitutionId', + institutionNames: 'publicationInstitutionName', + topicIds: 'publicationTopicId', + topicNames: 'publicationTopicName', + } as const; + readonly typeOptions = [ { value: 'article', label: 'article' }, { value: 'book', label: 'book' }, @@ -90,16 +174,28 @@ export class PersonPublicationsComponent implements OnInit { constructor( private readonly route: ActivatedRoute, + private readonly router: Router, private readonly workService: WorksService, + private readonly httpClient: HttpClient, public readonly paginationService: PaginationService, private readonly snackBar: MatSnackBar, ) {} ngOnInit(): void { - this.route.parent?.paramMap.subscribe((params) => { - this.authorId = params.get('id') ?? ''; - this.resetAndLoad(); - }); + this.setupInstitutionAutocomplete(); + this.setupTopicAutocomplete(); + + const parentParamMap = this.route.parent?.paramMap; + if (!parentParamMap) return; + + combineLatest([parentParamMap, this.route.queryParamMap]) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(([params, queryParams]) => { + this.authorId = params.get('id') ?? ''; + const queryState = this.parsePublicationFilterQueryParams(queryParams); + this.applyPublicationFilterQueryState(queryState); + this.load(queryState.pageIndex, queryState.pageSize); + }); } load(pageIndex = 0, pageSize = this.paginationService.selection): void { @@ -116,6 +212,8 @@ export class PersonPublicationsComponent implements OnInit { this.filters().publicationYears, this.filters().types, this.filters().languages, + this.selectedInstitutionIds(), + this.selectedTopicIds(), ) .subscribe({ next: (page) => { @@ -137,13 +235,19 @@ export class PersonPublicationsComponent implements OnInit { onPage(event: PageEvent): void { this.paginationService.selection = event.pageSize; this.currentPageIndex = event.pageIndex; - this.load(event.pageIndex, event.pageSize); + this.updatePublicationFilterQueryParams({ + [this.queryParamKeys.page]: event.pageIndex + 1, + [this.queryParamKeys.pageSize]: event.pageSize, + }); } - resetAndLoad(): void { + applyFilters(): void { this.currentPageIndex = 0; this.paginator?.firstPage(); - this.load(0, this.paginationService.selection); + this.updatePublicationFilterQueryParams({ + [this.queryParamKeys.page]: 1, + [this.queryParamKeys.pageSize]: this.paginationService.selection, + }); } clearFilters(): void { @@ -152,7 +256,65 @@ export class PersonPublicationsComponent implements OnInit { types: [], languages: [], }); - this.resetAndLoad(); + this.selectedInstitutions = []; + this.selectedTopics = []; + this.institutionOptions = []; + this.topicOptions = []; + this.institutionSearchControl.setValue('', { emitEvent: false }); + this.topicSearchControl.setValue('', { emitEvent: false }); + this.updatePublicationFilterQueryParams({ + [this.queryParamKeys.page]: 1, + [this.queryParamKeys.pageSize]: this.paginationService.selection, + [this.queryParamKeys.years]: null, + [this.queryParamKeys.types]: null, + [this.queryParamKeys.languages]: null, + [this.queryParamKeys.institutionIds]: null, + [this.queryParamKeys.institutionNames]: null, + [this.queryParamKeys.topicIds]: null, + [this.queryParamKeys.topicNames]: null, + }); + } + + displayInstitution(option: string | InstitutionAutocompleteOption): string { + return typeof option === 'string' ? option : (option.display_name ?? ''); + } + + selectInstitution(event: MatAutocompleteSelectedEvent): void { + const institution = event.option.value as InstitutionAutocompleteOption; + if (!institution.id) return; + if (!this.selectedInstitutions.some((item) => item.id === institution.id)) { + this.selectedInstitutions = [...this.selectedInstitutions, institution]; + this.applyFilters(); + } + this.institutionSearchControl.setValue('', { emitEvent: false }); + this.institutionOptions = []; + } + + removeInstitution(institution: InstitutionAutocompleteOption): void { + this.selectedInstitutions = this.selectedInstitutions.filter( + (item) => item.id !== institution.id, + ); + this.applyFilters(); + } + + displayTopic(option: string | TopicAutocompleteOption): string { + return typeof option === 'string' ? option : (option.display_name ?? ''); + } + + selectTopic(event: MatAutocompleteSelectedEvent): void { + const topic = event.option.value as TopicAutocompleteOption; + if (!topic.id) return; + if (!this.selectedTopics.some((item) => item.id === topic.id)) { + this.selectedTopics = [...this.selectedTopics, topic]; + this.applyFilters(); + } + this.topicSearchControl.setValue('', { emitEvent: false }); + this.topicOptions = []; + } + + removeTopic(topic: TopicAutocompleteOption): void { + this.selectedTopics = this.selectedTopics.filter((item) => item.id !== topic.id); + this.applyFilters(); } doiUrl(doi: string | null | undefined): string | null { @@ -160,6 +322,11 @@ export class PersonPublicationsComponent implements OnInit { return doi.startsWith('http') ? doi : `https://doi.org/${doi}`; } + publicationKey(publication: Work): string { + const id = publication.id ?? publication.ids?.openalex ?? publication.doi ?? ''; + return id.split('/').filter(Boolean).pop() ?? id; + } + publicationRange(): string { if (this.total === 0 || this.publications.length === 0) { return 'Keine Publikationen'; @@ -175,6 +342,24 @@ export class PersonPublicationsComponent implements OnInit { return 'info'; } + institutions(publication: Work): Array<{ id: string; name: string }> { + const institutionsById = new Map(); + + for (const authorship of publication.authorships ?? []) { + for (const institution of authorship.institutions ?? []) { + if (!institution.id || !institution.display_name) continue; + if (!institutionsById.has(institution.id)) { + institutionsById.set(institution.id, { + id: institution.id, + name: institution.display_name, + }); + } + } + } + + return Array.from(institutionsById.values()); + } + private filters() { return { publicationYears: this.filterForm.controls.publicationYears.value, @@ -183,6 +368,210 @@ export class PersonPublicationsComponent implements OnInit { }; } + private setupInstitutionAutocomplete(): void { + this.institutionSearchControl.valueChanges + .pipe( + debounceTime(250), + map((value) => (typeof value === 'string' ? value.trim() : '')), + distinctUntilChanged(), + switchMap((query) => { + if (query.length < 2) { + this.institutionOptions = []; + return of([]); + } + this.institutionLookupLoading = true; + return this.searchInstitutions(query).pipe( + catchError(() => of([])), + finalize(() => { + this.institutionLookupLoading = false; + }), + ); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((options) => { + const selectedIds = new Set(this.selectedInstitutionIds()); + this.institutionOptions = options.filter( + (option) => !!option.id && !selectedIds.has(option.id), + ); + }); + } + + private setupTopicAutocomplete(): void { + this.topicSearchControl.valueChanges + .pipe( + debounceTime(250), + map((value) => (typeof value === 'string' ? value.trim() : '')), + distinctUntilChanged(), + switchMap((query) => { + if (query.length < 2) { + this.topicOptions = []; + return of([]); + } + this.topicLookupLoading = true; + return this.searchTopics(query).pipe( + catchError(() => of([])), + finalize(() => { + this.topicLookupLoading = false; + }), + ); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((options) => { + const selectedIds = new Set(this.selectedTopicIds()); + this.topicOptions = options.filter( + (option) => !!option.id && !selectedIds.has(option.id), + ); + }); + } + + private searchInstitutions(query: string) { + const params = new HttpParams() + .set('query', query) + .set('limit', '10'); + + const basePath = this.workService.configuration.basePath ?? ''; + return this.httpClient + .get(`${basePath}/api/institutions/autocomplete`, { + params, + }) + .pipe(map((response) => response.results ?? [])); + } + + private searchTopics(query: string) { + const params = new HttpParams().set('query', query).set('limit', '10'); + + const basePath = this.workService.configuration.basePath ?? ''; + return this.httpClient + .get(`${basePath}/api/topics/autocomplete`, { + params, + }) + .pipe(map((response) => response.results ?? [])); + } + + private selectedInstitutionIds(): string[] { + return this.selectedInstitutions + .map((institution) => institution.id) + .filter((id): id is string => !!id); + } + + private selectedTopicIds(): string[] { + return this.selectedTopics + .map((topic) => topic.id) + .filter((id): id is string => !!id); + } + + private updatePublicationFilterQueryParams( + overrides: Record | null>, + ): void { + const filters = this.filters(); + const institutionIds = this.selectedInstitutionIds(); + const institutionNames = this.selectedInstitutions + .map((institution) => institution.display_name) + .filter((name): name is string => !!name); + const topicIds = this.selectedTopicIds(); + const topicNames = this.selectedTopics + .map((topic) => topic.display_name) + .filter((name): name is string => !!name); + + void this.router.navigate([], { + relativeTo: this.route, + queryParams: { + [this.queryParamKeys.years]: filters.publicationYears.length + ? filters.publicationYears + : null, + [this.queryParamKeys.types]: filters.types.length ? filters.types : null, + [this.queryParamKeys.languages]: filters.languages.length + ? filters.languages + : null, + [this.queryParamKeys.institutionIds]: institutionIds.length + ? institutionIds + : null, + [this.queryParamKeys.institutionNames]: institutionNames.length + ? institutionNames + : null, + [this.queryParamKeys.topicIds]: topicIds.length ? topicIds : null, + [this.queryParamKeys.topicNames]: topicNames.length ? topicNames : null, + ...overrides, + }, + queryParamsHandling: 'merge', + }); + } + + private parsePublicationFilterQueryParams( + queryParams: ParamMap, + ): PublicationFilterQueryState { + const institutionIds = queryParams.getAll(this.queryParamKeys.institutionIds); + const institutionNames = queryParams.getAll(this.queryParamKeys.institutionNames); + const topicIds = queryParams.getAll(this.queryParamKeys.topicIds); + const topicNames = queryParams.getAll(this.queryParamKeys.topicNames); + + return { + pageIndex: + this.parsePositiveInteger(queryParams.get(this.queryParamKeys.page), 1) - 1, + pageSize: this.parsePositiveInteger( + queryParams.get(this.queryParamKeys.pageSize), + this.paginationService.selection, + ), + publicationYears: this.parseNumberParams( + queryParams.getAll(this.queryParamKeys.years), + ), + types: this.parseStringParams(queryParams.getAll(this.queryParamKeys.types)), + languages: this.parseStringParams( + queryParams.getAll(this.queryParamKeys.languages), + ), + institutions: institutionIds + .filter(Boolean) + .map((id, index) => ({ + id, + display_name: institutionNames[index] || id, + })), + topics: topicIds + .filter(Boolean) + .map((id, index) => ({ + id, + display_name: topicNames[index] || id, + })), + }; + } + + private applyPublicationFilterQueryState( + queryState: PublicationFilterQueryState, + ): void { + this.currentPageIndex = queryState.pageIndex; + this.paginationService.selection = queryState.pageSize; + this.selectedInstitutions = queryState.institutions; + this.selectedTopics = queryState.topics; + this.filterForm.setValue( + { + publicationYears: queryState.publicationYears, + types: queryState.types, + languages: queryState.languages, + }, + { emitEvent: false }, + ); + } + + private parseStringParams(values: string[]): string[] { + return values.map((value) => value.trim()).filter(Boolean); + } + + private parseNumberParams(values: string[]): number[] { + return values + .map((value) => Number(value)) + .filter((value) => Number.isInteger(value)); + } + + private parsePositiveInteger(value: string | null, fallback: number): number { + const parsedValue = Number(value); + if (!Number.isInteger(parsedValue) || parsedValue < 1) { + return fallback; + } + + return parsedValue; + } + private createPublicationYearOptions(): number[] { const currentYear = new Date().getFullYear(); return Array.from({ length: 90 }, (_, index) => currentYear - index); diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.html b/webapp/src/app/modules/publication-detail/publication-detail.component.html new file mode 100644 index 00000000..58179d64 --- /dev/null +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.html @@ -0,0 +1,256 @@ +
    + + + @if (loading) { +
    + +

    Publikation wird geladen...

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

    Publikation nicht gefunden

    +

    Die Publikation konnte nicht geladen werden.

    + + Zur Personensuche + +
    + } @else { +
    +
    +
    + @if (publication.type) { + {{ publication.type }} + } + @if (publication.publication_year) { + {{ publication.publication_year }} + } + @if (publication.language) { + {{ publication.language | uppercase }} + } +
    +

    {{ publication.title || publication.display_name || "Ohne Titel" }}

    +

    + @for (authorship of authors(); track authorship.author?.id; let last = $last) { + {{ authorship.author?.display_name || authorship.raw_author_name || "Unbekannt" }}@if (!last) {, } + } @empty { + Autorinnen und Autoren nicht angegeben + } +

    +
    + @for (link of externalLinks().slice(0, 3); track link.url; let first = $first) { + + {{ link.label }} + open_in_new + + } +
    +
    + +
    +
    + format_quote + {{ publication.cited_by_count ?? 0 | number }} + Zitationen +
    +
    + menu_book + {{ publication.referenced_works_count ?? 0 | number }} + Referenzen +
    +
    + {{ publication.open_access?.is_oa ? "lock_open" : "lock" }} + {{ publication.open_access?.is_oa ? "Ja" : "Nein" }} + Open Access +
    +
    +
    + + @if (publication.is_retracted) { +
    + warning + Diese Publikation wurde zurückgezogen. +
    + } + +
    +
    + @if (abstractText(); as abstract) { +
    +
    + subject +

    Abstract

    +
    +

    {{ abstract }}

    +
    + } + +
    +
    + group +

    Autorinnen und Autoren

    + {{ authors().length }} +
    +
    + @for (authorship of authors(); track authorship.author?.id) { + + } @empty { +

    Keine Angaben vorhanden.

    + } +
    +
    + + @if (publication.topics?.length || publication.keywords?.length) { +
    +
    + interests +

    Themen und Keywords

    +
    +
    + @for (topic of publication.topics ?? []; track topic.id) { + + {{ topic.display_name }} + + } + @for (keyword of publication.keywords ?? []; track keyword.id) { + {{ keyword.display_name }} + } +
    +
    + } + + @if (sources().length) { +
    +
    + library_books +

    Quellen und Versionen

    +
    +
    + @for (location of sources(); track location.source?.id || location.landing_page_url) { +
    +
    + {{ location.source?.display_name || "Externe Quelle" }} +

    + {{ location.version || location.source?.type || "Veröffentlichte Version" }} + @if (location.license) { · {{ location.license }} } +

    +
    +
    + @if (location.is_oa) { + Open Access + } + @if (location.pdf_url || location.landing_page_url; as sourceUrl) { + + open_in_new + + } +
    +
    + } +
    +
    + } +
    + + +
    + } +
    diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.scss b/webapp/src/app/modules/publication-detail/publication-detail.component.scss new file mode 100644 index 00000000..9e183808 --- /dev/null +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.scss @@ -0,0 +1,436 @@ +:host { + display: block; + background: var(--sg-background); +} + +.detail-page { + max-width: 1500px; + margin: 0 auto; + padding: 26px 32px 56px; +} + +.back-link { + display: inline-flex; + align-items: center; + gap: 7px; + margin-bottom: 22px; + padding: 0; + border: 0; + background: transparent; + color: var(--sg-text-muted); + font-size: 13px; + font-weight: 600; + text-decoration: none; + cursor: pointer; +} + +.back-link mat-icon { + width: 18px; + height: 18px; + font-size: 18px; +} + +.hero { + display: grid; + grid-template-columns: minmax(0, 1fr) 420px; + gap: 42px; + padding: 38px 42px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-lg); + background: + radial-gradient(circle at 90% 10%, rgba(200, 217, 255, 0.75), transparent 35%), + linear-gradient(140deg, #fff 0%, #f8faff 100%); + box-shadow: var(--sg-shadow-sm); +} + +.eyebrow, +.tags, +.hero-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.eyebrow span { + padding: 5px 10px; + border: 1px solid var(--sg-border); + border-radius: 999px; + background: rgba(255, 255, 255, 0.85); + color: var(--sg-text-muted); + font-size: 11px; + font-weight: 700; + text-transform: uppercase; +} + +h1 { + max-width: 920px; + margin: 20px 0 13px; + font-size: clamp(27px, 3vw, 42px); + line-height: 1.13; +} + +.author-line { + max-width: 900px; + margin: 0; + color: var(--sg-text-muted); + font-size: 14px; + line-height: 1.7; +} + +.hero-actions { + margin-top: 26px; +} + +.hero-actions a { + display: inline-flex; + align-items: center; + gap: 8px; + min-height: 42px; + padding: 9px 16px; + border: 1px solid var(--sg-border-strong); + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + font-weight: 700; + text-decoration: none; +} + +.hero-actions a.primary-action { + border-color: var(--sg-primary); + background: var(--sg-primary); + color: #fff; +} + +.hero-actions mat-icon { + width: 17px; + height: 17px; + font-size: 17px; +} + +.metrics { + display: grid; + grid-template-columns: repeat(3, 1fr); + align-self: center; + overflow: hidden; + border: 1px solid rgba(199, 211, 232, 0.8); + border-radius: var(--sg-radius-md); + background: rgba(255, 255, 255, 0.8); +} + +.metrics div { + display: flex; + align-items: center; + flex-direction: column; + gap: 5px; + padding: 22px 10px; + text-align: center; +} + +.metrics div + div { + border-left: 1px solid var(--sg-border); +} + +.metrics mat-icon { + color: var(--sg-text-soft); +} + +.metrics .positive mat-icon { + color: var(--sg-success); +} + +.metrics strong { + color: var(--sg-text); + font-family: "Montserrat", "Open Sans", sans-serif; + font-size: 22px; +} + +.metrics span { + color: var(--sg-text-muted); + font-size: 11px; +} + +.warning { + display: flex; + align-items: center; + gap: 10px; + margin-top: 20px; + padding: 14px 18px; + border: 1px solid #f1c6cc; + border-radius: var(--sg-radius-sm); + background: #fff4f5; + color: #9c2637; + font-weight: 700; +} + +.content-grid { + display: grid; + grid-template-columns: minmax(0, 1fr) 380px; + gap: 24px; + margin-top: 24px; +} + +main, +aside { + display: flex; + flex-direction: column; + gap: 24px; +} + +.card { + padding: 26px 28px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-md); + background: var(--sg-surface); + box-shadow: var(--sg-shadow-sm); +} + +.section-title { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 20px; +} + +.section-title mat-icon { + color: var(--sg-text-muted); +} + +.section-title h2 { + margin: 0; + font-size: 16px; +} + +.section-title span { + margin-left: auto; + color: var(--sg-text-muted); + font-size: 12px; +} + +.abstract-card p { + margin: 0; + color: var(--sg-text); + font-size: 14px; + line-height: 1.8; +} + +.author-list { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; +} + +.author-list article { + display: grid; + grid-template-columns: 38px minmax(0, 1fr); + gap: 11px; + align-items: center; + padding: 12px; + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-muted); +} + +.avatar { + display: grid; + place-items: center; + width: 38px; + height: 38px; + border-radius: 50%; + background: #e5ecfb; + color: var(--sg-text); + font-weight: 700; + text-transform: uppercase; +} + +.author-list a, +.author-list strong { + color: var(--sg-text); + font-size: 13px; + font-weight: 700; + text-decoration: none; +} + +.author-list p, +.source-list p { + margin: 3px 0 0; + color: var(--sg-text-muted); + font-size: 11px; +} + +.tags span { + padding: 7px 10px; + border: 1px solid var(--sg-border); + border-radius: 999px; + color: var(--sg-text-muted); + font-size: 11px; +} + +.tags .topic-tag { + border-color: #cbd8f1; + background: #f5f8ff; + color: var(--sg-text); +} + +.source-list, +.compact-list, +.link-list { + display: grid; + gap: 10px; +} + +.source-list article, +.compact-list div { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 13px 0; + border-bottom: 1px solid var(--sg-border); +} + +.source-list article:last-child, +.compact-list div:last-child { + border-bottom: 0; +} + +.source-actions { + display: flex; + align-items: center; + gap: 10px; +} + +.source-actions a { + height: 24px; +} + +.source-actions mat-icon { + width: 20px; + height: 20px; + font-size: 20px; +} + +.oa-badge { + padding: 4px 8px; + border-radius: 999px; + background: var(--sg-success-soft); + color: var(--sg-success); + font-size: 10px; + font-weight: 700; +} + +dl { + margin: 0; +} + +dl div { + display: grid; + grid-template-columns: 115px minmax(0, 1fr); + gap: 12px; + padding: 10px 0; + border-bottom: 1px solid var(--sg-border); +} + +dl div:last-child { + border-bottom: 0; +} + +dt { + color: var(--sg-text-muted); + font-size: 12px; +} + +dd { + margin: 0; + overflow-wrap: anywhere; + color: var(--sg-text); + font-size: 12px; + font-weight: 600; + text-align: right; +} + +.compact-list div { + align-items: flex-start; + flex-direction: column; + gap: 3px; +} + +.compact-list strong { + font-size: 12px; +} + +.compact-list span { + color: var(--sg-text-muted); + font-size: 11px; +} + +.link-list a { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 0; + border-bottom: 1px solid var(--sg-border); + color: var(--sg-text); + font-size: 12px; + font-weight: 700; + text-decoration: none; +} + +.link-list a:last-child { + border-bottom: 0; +} + +.link-list mat-icon { + width: 16px; + height: 16px; + color: var(--sg-text-muted); + font-size: 16px; +} + +.state { + display: grid; + place-items: center; + min-height: 380px; + color: var(--sg-text-muted); + text-align: center; +} + +.error-state mat-icon { + width: 46px; + height: 46px; + font-size: 46px; +} + +.empty { + color: var(--sg-text-muted); +} + +@media (max-width: 1150px) { + .hero, + .content-grid { + grid-template-columns: 1fr; + } + + .metrics { + width: 100%; + } +} + +@media (max-width: 700px) { + .detail-page { + padding: 18px 16px 40px; + } + + .hero, + .card { + padding: 22px 20px; + } + + .metrics, + .author-list { + grid-template-columns: 1fr; + } + + .metrics div + div { + border-top: 1px solid var(--sg-border); + border-left: 0; + } +} diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts new file mode 100644 index 00000000..e4c0b56f --- /dev/null +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -0,0 +1,182 @@ +import { DatePipe, DecimalPipe, UpperCasePipe } from '@angular/common'; +import { Location } from '@angular/common'; +import { Component, DestroyRef, OnInit, inject } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { HttpClient } from '@angular/common/http'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { ActivatedRoute, RouterLink } from '@angular/router'; +import { finalize } from 'rxjs'; + +import { Authorship, Location as ApiLocation, Work, WorksService } from '../../api'; + +interface DetailLink { + label: string; + url: string; +} + +interface InstitutionDetail { + id: string; + name: string; + country?: string | null; + type?: string | null; +} + +@Component({ + selector: 'app-publication-detail', + imports: [ + DatePipe, + DecimalPipe, + MatButtonModule, + MatIconModule, + MatProgressSpinnerModule, + RouterLink, + UpperCasePipe, + ], + templateUrl: './publication-detail.component.html', + styleUrl: './publication-detail.component.scss', +}) +export class PublicationDetailComponent implements OnInit { + private readonly destroyRef = inject(DestroyRef); + private readonly route = inject(ActivatedRoute); + private readonly httpClient = inject(HttpClient); + private readonly location = inject(Location); + private readonly worksService = inject(WorksService); + + publication: Work | null = null; + loading = true; + notFound = false; + + ngOnInit(): void { + this.route.paramMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + const publicationId = params.get('publicationId'); + if (!publicationId) { + this.loading = false; + this.notFound = true; + return; + } + + this.loadPublication(publicationId); + }); + } + + navigateBack(): void { + this.location.back(); + } + + abstractText(): string | null { + const index = this.publication?.abstract_inverted_index; + if (!index || typeof index !== 'object') return null; + + const words: Array<{ word: string; position: number }> = []; + for (const [word, rawPositions] of Object.entries(index)) { + if (!Array.isArray(rawPositions)) continue; + for (const position of rawPositions) { + if (typeof position === 'number') words.push({ word, position }); + } + } + + return words + .sort((first, second) => first.position - second.position) + .map(({ word }) => word) + .join(' ') || null; + } + + authors(): Authorship[] { + return this.publication?.authorships ?? []; + } + + institutions(): InstitutionDetail[] { + const institutions = new Map(); + for (const authorship of this.authors()) { + for (const institution of authorship.institutions ?? []) { + if (!institution.id || !institution.display_name) continue; + institutions.set(institution.id, { + id: institution.id, + name: institution.display_name, + country: institution.country_code, + type: institution.type, + }); + } + } + return Array.from(institutions.values()); + } + + sources(): ApiLocation[] { + const locations = [ + this.publication?.primary_location, + this.publication?.best_oa_location, + ...(this.publication?.locations ?? []), + ].filter((location): location is ApiLocation => !!location); + const unique = new Map(); + for (const location of locations) { + const key = + location.source?.id ?? + location.landing_page_url ?? + location.pdf_url ?? + JSON.stringify(location); + unique.set(key, location); + } + return Array.from(unique.values()); + } + + externalLinks(): DetailLink[] { + if (!this.publication) return []; + const links: DetailLink[] = []; + this.addLink(links, 'Open Access', this.publication.open_access?.oa_url); + this.addLink(links, 'DOI', this.doiUrl(this.publication.doi)); + return links.filter( + (link, index) => links.findIndex((candidate) => candidate.url === link.url) === index, + ); + } + + pages(): string | null { + const first = this.publication?.biblio?.first_page; + const last = this.publication?.biblio?.last_page; + if (first && last) return `${first}-${last}`; + return first ?? last ?? null; + } + + openAccessLabel(): string { + if (this.publication?.open_access?.is_oa) { + return this.publication.open_access.oa_status + ? `Open Access (${this.publication.open_access.oa_status})` + : 'Open Access'; + } + return 'Kein Open Access'; + } + + private loadPublication(publicationId: string): void { + this.loading = true; + this.notFound = false; + this.publication = null; + + const basePath = this.worksService.configuration.basePath ?? ''; + this.httpClient + .get( + `${basePath}/api/works/detail/${encodeURIComponent(publicationId)}`, + ) + .pipe(finalize(() => (this.loading = false))) + .subscribe({ + next: (publication) => { + this.publication = publication; + }, + error: () => { + this.notFound = true; + }, + }); + } + + private doiUrl(doi: string | null | undefined): string | null { + if (!doi) return null; + return doi.startsWith('http') ? doi : `https://doi.org/${doi}`; + } + + private addLink(links: DetailLink[], label: string, value: string | null | undefined) { + if (!value) return; + links.push({ label, url: value.startsWith('http') ? value : `https://${value}` }); + } +} diff --git a/webapp/src/app/modules/work/work.component.html b/webapp/src/app/modules/work/work.component.html deleted file mode 100644 index e8187ec0..00000000 --- a/webapp/src/app/modules/work/work.component.html +++ /dev/null @@ -1 +0,0 @@ -

    work works!

    diff --git a/webapp/src/app/modules/work/work.component.scss b/webapp/src/app/modules/work/work.component.scss deleted file mode 100644 index e69de29b..00000000 diff --git a/webapp/src/app/modules/work/work.component.ts b/webapp/src/app/modules/work/work.component.ts deleted file mode 100644 index f4fda054..00000000 --- a/webapp/src/app/modules/work/work.component.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Component } from '@angular/core'; - -@Component({ - selector: 'app-work', - imports: [], - templateUrl: './work.component.html', - styleUrl: './work.component.scss', -}) -export class WorkComponent { - -}