From fa5e42a5ebdf7e68fb232e9ca6c99669b02aa5d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 12 Jul 2026 23:39:25 +0200 Subject: [PATCH] fix(person/publications): made URL stateful and moved retrieval logic to resolvers --- .../main/inse/integrations/elasticsearch.py | 1 + service/src/main/inse/main.py | 2 + service/src/main/inse/model.py | 25 +- service/src/main/inse/tags.py | 1 + service/src/main/inse/works/purpose_router.py | 6 +- .../src/main/inse/works/purpose_service.py | 6 +- service/src/main/inse/works/v2/model.py | 48 ++ service/src/main/inse/works/v2/router.py | 101 +++ service/src/main/inse/works/v2/service.py | 188 +++++ ude_person.http | 6 + webapp/src/app/api/.openapi-generator/FILES | 5 + webapp/src/app/api/api/api.ts | 4 +- webapp/src/app/api/api/worksV2.service.ts | 275 +++++++ webapp/src/app/api/model/authorWork.ts | 48 ++ .../app/api/model/authorWorkInstitution.ts | 26 + webapp/src/app/api/model/authorWorkPage.ts | 31 + webapp/src/app/api/model/models.ts | 4 + webapp/src/app/api/model/workSortBy.ts | 20 + webapp/src/app/app.routes.ts | 7 + .../person-publications.component.html | 136 ++-- .../person-publications.component.ts | 745 +++++++----------- .../selected-institutions.resolver.ts | 18 + .../app/resolvers/selected-topics.resolver.ts | 18 + .../src/app/resolvers/work-page.resolver.ts | 53 +- 24 files changed, 1211 insertions(+), 563 deletions(-) create mode 100644 service/src/main/inse/works/v2/model.py create mode 100644 service/src/main/inse/works/v2/router.py create mode 100644 service/src/main/inse/works/v2/service.py create mode 100644 webapp/src/app/api/api/worksV2.service.ts create mode 100644 webapp/src/app/api/model/authorWork.ts create mode 100644 webapp/src/app/api/model/authorWorkInstitution.ts create mode 100644 webapp/src/app/api/model/authorWorkPage.ts create mode 100644 webapp/src/app/api/model/workSortBy.ts create mode 100644 webapp/src/app/resolvers/selected-institutions.resolver.ts create mode 100644 webapp/src/app/resolvers/selected-topics.resolver.ts diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 3ff5dc53..be4bcb17 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -107,6 +107,7 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]: def _wrap_exception(e: Exception) -> Exception: + logger.exception(f"Elasticsearch raised an exception: {e}") if isinstance(e, httpx.HTTPStatusError): if e.response.status_code == 404: return ElasticsearchNotFoundException( diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 690f2e01..006855d5 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -52,6 +52,7 @@ from inse.patents.service import ( ) from inse.works.purpose_router import router as works_purpose_router +from inse.works.v2.router import router as works_v2_router logger = logging.getLogger(__name__) @@ -101,6 +102,7 @@ app.include_router(service_router) app.include_router(auth_router) app.include_router(account_management_router) app.include_router(organization_management_router) +app.include_router(works_v2_router) app.add_middleware( diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 72a27008..4b129cb9 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -16,6 +16,7 @@ else: def __str__(self) -> str: return self.value + from pydantic import BaseModel from pydantic import Field from typing import List @@ -28,11 +29,16 @@ T = TypeVar("T", bound=BaseModel) class Page(BaseModel, Generic[T]): elements: List[T] = Field(default=[], description="The elements of the page.") - offset: int = Field(default=0, description="The page number. (0-based)") + page: int = Field(default=0, description="The page number. (0-based)") size: int = Field(default=20, description="The page size in elements.") total: int = Field(default=0, description="The total number of elements.") +class SortDirection(StrEnum): + ASCENDING = "asc" + DESCENDING = "desc" + + class ESCluster(StrEnum): NES = "nes" INSE = "inse" @@ -40,6 +46,7 @@ class ESCluster(StrEnum): class ESIndex(StrEnum): OPENALEX_WORKS = "openalex-works" + OPENALEX_WORKS_WILDCARD = "openalex-works*" OPENALEX_AUTHORS = "openalex-authors" OPENALEX_INSTITUTIONS = "openalex-institutions" OPENALEX_PUBLICATIONS = "openalex-publications" @@ -47,17 +54,17 @@ class ESIndex(StrEnum): OPENALEX_CONTINENTS = "openalex-continents" OPENALEX_TOPICS = "openalex-topics" OPENALEX_TOPIC_VECTORS = "topicvectors" - + EPO_INDEX = "epo_index_1.0" USPTO_INDEX = "uspto_patents_3.0" ORG_PATENTS = "org_patents" PROJECTS_BUND_V1 = "projects_bund_v1" PROJECTS_DFG_ALL = "projects_dfg_all" - - CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" - CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects" - CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications" + + CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" + CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects" + CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications" CORDIS_EU_FP7_OGANIZATIONS = "cordis_eu_fp7_organizations" # FP7 CORDIS_EU_FP7_ORGANIZATIONS = "cordis_eu_fp7_organizations" @@ -84,8 +91,10 @@ class ESIndex(StrEnum): CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS = "cordis_eu_horizon_europe_organizations" CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS = "cordis_eu_horizon_europe_publications" CORDIS_EU_HORIZON_EUROPE_DELIVERABLES = "cordis_eu_horizon_europe_deliverables" - CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES = "cordis_eu_horizon_europe_report_summaries" + CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES = ( + "cordis_eu_horizon_europe_report_summaries" + ) CORDIS_EU_HORIZON_EUROPE_TOPICS = "cordis_eu_horizon_europe_topics" CORDIS_EU_HORIZON_EUROPE_WEB_LINKS = "cordis_eu_horizon_europe_web_links" CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC = "cordis_eu_horizon_europe_euroscivoc" - CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS = "cordis_eu_horizon_europe_legal_basis" \ No newline at end of file + CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS = "cordis_eu_horizon_europe_legal_basis" diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index 1b25c312..194552df 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -7,6 +7,7 @@ class Tags(StrEnum): INSTITUTIONS = "Institutions" TOPICS = "Topics" WORKS = "Works" + WORKS_V2 = "Works V2" NEWS = "News" PROJECTS = "Projects" AUTH = "Auth" diff --git a/service/src/main/inse/works/purpose_router.py b/service/src/main/inse/works/purpose_router.py index b641e008..2d2beeaf 100644 --- a/service/src/main/inse/works/purpose_router.py +++ b/service/src/main/inse/works/purpose_router.py @@ -20,7 +20,7 @@ router = APIRouter(prefix=WORKS_PREFIX, tags=[Tags.WORKS]) async def get_work_purpose( raw_oa_work_id: Annotated[str, Path(description="The raw OpenAlex work id.")], ) -> SpecificWorkPurpose: - return await purpose_service.get_work_purpose(raw_oa_work_id) + return await purpose_service.get_work_purpose(raw_oa_work_id=raw_oa_work_id) @router.get( @@ -31,4 +31,6 @@ async def get_work_purpose( async def get_author_work_purposes( raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")], ) -> AuthorWorkPurposes: - return await purpose_service.get_author_work_purposes(raw_oa_author_id) + return await purpose_service.get_author_work_purposes( + raw_oa_author_id=raw_oa_author_id + ) diff --git a/service/src/main/inse/works/purpose_service.py b/service/src/main/inse/works/purpose_service.py index 9003f4c4..a5fe5031 100644 --- a/service/src/main/inse/works/purpose_service.py +++ b/service/src/main/inse/works/purpose_service.py @@ -2,7 +2,6 @@ import logging import random from typing import List -from fastapi import HTTPException, status from inse.exceptions import NotFoundException from inse.integrations import elasticsearch @@ -10,13 +9,14 @@ from inse.model import ESIndex from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose, WorkPurpose logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) async def get_work_purpose(raw_oa_work_id: str) -> SpecificWorkPurpose: raw_oa_work_id = raw_oa_work_id.strip().upper() response = await elasticsearch.get( - index=ESIndex.OPENALEX_WORKS, + index=ESIndex.OPENALEX_WORKS_WILDCARD, doc_id=raw_oa_work_id, source=["title", "abstract"], ) @@ -41,7 +41,7 @@ async def get_author_work_purposes(raw_oa_author_id: str) -> AuthorWorkPurposes: raw_oa_author_id = raw_oa_author_id.strip().upper() response = await elasticsearch.search( - index=ESIndex.OPENALEX_WORKS, + index=ESIndex.OPENALEX_WORKS_WILDCARD, source=["id", "publication_year"], query={ "nested": { diff --git a/service/src/main/inse/works/v2/model.py b/service/src/main/inse/works/v2/model.py new file mode 100644 index 00000000..bd440b8f --- /dev/null +++ b/service/src/main/inse/works/v2/model.py @@ -0,0 +1,48 @@ +from enum import StrEnum +from typing import List + +from pydantic import BaseModel, Field + +from inse.model import Page +from inse.models.openalex.work_topic import WorkTopic + + +class WorkSortBy(StrEnum): + TITLE = "title" + TYPE = "type" + PUBLICATION_YEAR = "publication_year" + LANGUAGE = "language" + CITED_BY_COUNT = "cited_by_count" + + +class AuthorWorkInstitution(BaseModel): + institution_id: str = Field( + description="The ID of the institution associated with the work" + ) + institution_name: str = Field( + description="The name of the institution associated with the work" + ) + institution_country_code: str = Field( + description="The country code of the institution associated with the work" + ) + + +class AuthorWork(BaseModel): + id: str = Field(description="The ID of the work") + title: str = Field(description="The title of the work") + type: str = Field(description="The type of the work") + publication_year: int = Field(description="The year the work was published") + language_code: str = Field(description="The language code of the work") + institutions: List[AuthorWorkInstitution] = Field( + description="A list of institutions associated with the work" + ) + topics: List[WorkTopic] = Field( + description="A list of topics associated with the work" + ) + cited_by_count: int = Field( + description="The number of citations the work has received" + ) + + +class AuthorWorkPage(Page[AuthorWork]): + pass diff --git a/service/src/main/inse/works/v2/router.py b/service/src/main/inse/works/v2/router.py new file mode 100644 index 00000000..5ad09882 --- /dev/null +++ b/service/src/main/inse/works/v2/router.py @@ -0,0 +1,101 @@ +from typing import Annotated, List + +from fastapi import APIRouter, Path, Query + +from inse.tags import Tags +from inse.model import SortDirection +from inse.works.v2.model import AuthorWorkPage, WorkSortBy +from inse.models.openalex.work_topic import WorkTopic +from inse.models.openalex.institution import Institution + + +router = APIRouter(prefix="/api/v2/works", tags=[Tags.WORKS_V2]) + + +@router.get( + "/{raw_oa_author_id}", + operation_id="getAuthorWorkPage", + summary="Returns a paginated list of works for a given author based on their ID.", +) +async def get_author_works( + raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")], + page: Annotated[ + int, Query(description="The page number to retrieve. (0-based)", ge=0) + ] = 0, + size: Annotated[ + int, + Query(description="The number of works to retrieve per page.", ge=1, le=100), + ] = 10, + publication_years: Annotated[ + list[int], + Query(description="A list of publication years to filter by."), + ] = [], + publication_types: Annotated[ + list[str], + Query(description="A list of publication types to filter by."), + ] = [], + institution_ids: Annotated[ + list[str], + Query(description="A list of institution IDs to filter by."), + ] = [], + topic_ids: Annotated[ + list[str], + Query(description="A list of topic IDs to filter by."), + ] = [], + language_codes: Annotated[ + list[str], + Query(description="A list of language codes to filter by."), + ] = [], + sort_by: Annotated[ + WorkSortBy, Query(description="The field to sort by.") + ] = WorkSortBy.PUBLICATION_YEAR, + sort_order: Annotated[ + SortDirection, Query(description="The order to sort by.") + ] = SortDirection.DESCENDING, +) -> AuthorWorkPage: + from inse.works.v2.service import get_author_works + + return await get_author_works( + raw_oa_author_id=raw_oa_author_id, + page=page, + size=size, + publication_years=publication_years or [], + publication_types=publication_types or [], + institution_ids=institution_ids or [], + topic_ids=topic_ids or [], + language_codes=language_codes or [], + sort_by=sort_by, + sort_order=sort_order, + ) + + +@router.get( + "/topics/search", + operation_id="getWorkTopicsByIds", + summary="Returns a list of work topics based on their IDs.", +) +async def get_work_topics_by_ids( + topic_ids: Annotated[ + list[str], + Query(description="A list of topic IDs to retrieve."), + ] = [], +) -> List[WorkTopic]: + from inse.works.v2.service import get_work_topics_by_ids + + return await get_work_topics_by_ids(topic_ids=topic_ids or []) + + +@router.get( + "/institutions/search", + operation_id="getInstitutionsByIds", + summary="Returns a list of institutions based on their IDs.", +) +async def get_institutions_by_ids( + institution_ids: Annotated[ + list[str], + Query(description="A list of institution IDs to retrieve."), + ] = [], +) -> List[Institution]: + from inse.works.v2.service import get_work_institutions_by_ids + + return await get_work_institutions_by_ids(institution_ids=institution_ids or []) diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py new file mode 100644 index 00000000..3761d73d --- /dev/null +++ b/service/src/main/inse/works/v2/service.py @@ -0,0 +1,188 @@ +import logging +from typing import List, Optional, Dict + +from inse.integrations import elasticsearch +from inse.model import ESIndex, SortDirection +from inse.works.v2.model import ( + AuthorWork, + AuthorWorkInstitution, + AuthorWorkPage, + WorkSortBy, +) +from inse.models.openalex.work_topic import WorkTopic +from inse.models.openalex.institution import Institution + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +async def get_author_works( + raw_oa_author_id: str, + page: int, + size: int, + publication_years: Optional[List[int]] = None, + publication_types: Optional[List[str]] = None, + institution_ids: Optional[List[str]] = None, + topic_ids: Optional[List[str]] = None, + language_codes: Optional[List[str]] = None, + sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR, + sort_order: SortDirection = SortDirection.DESCENDING, +) -> AuthorWorkPage: + + must = [ + { + "nested": { + "path": "authorships", + "query": { + "term": { + "authorships.author.id": f"https://openalex.org/{raw_oa_author_id}" + } + }, + } + } + ] + if publication_years: + must.append({"terms": {"publication_year": publication_years}}) + if publication_types: + must.append({"terms": {"type": publication_types}}) + if language_codes: + must.append({"terms": {"language": language_codes}}) + if institution_ids: + must.append( + { + "nested": { + "path": "authorships", + "query": { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": institution_ids + } + }, + } + }, + } + } + ) + if topic_ids: + must.append( + {"nested": {"path": "topics", "query": {"terms": {"topics.id": topic_ids}}}} + ) + + if sort_by == WorkSortBy.TITLE: + sort = [{"title.keyword": sort_order.value}] + else: + sort = [{sort_by.value: sort_order.value}] + + response = await elasticsearch.search( + ESIndex.OPENALEX_WORKS_WILDCARD, + source=[ + "id", + "title", + "type", + "publication_year", + "language", + "cited_by_count", + "authorships.institutions.id", + "authorships.institutions.display_name", + "authorships.institutions.country_code", + "topics", + ], + query={"bool": {"must": must}}, + size=size, + offset=page * size, + sort=sort, + ) + + logger.debug(f"Elasticsearch response for author {raw_oa_author_id} v2: {response}") + hits_block = response.get("hits", {}) + total = hits_block.get("total", {}).get("value", 0) + hits = hits_block.get("hits", []) + elements: List[AuthorWork] = [] + for hit in hits: + source = hit.get("_source", {}) + logger.debug(f"Hit source for author {raw_oa_author_id} v2: {source}") + institutions: Dict[str, AuthorWorkInstitution] = {} + for authorship in source.get("authorships", []): + for institution in authorship.get("institutions", []): + institution_id = institution.get("id", "") + if institution_id not in institutions: + institutions[institution_id] = AuthorWorkInstitution( + institution_id=institution.get("id", ""), + institution_name=institution.get("display_name", ""), + institution_country_code=institution.get("country_code", ""), + ) + topics: List[WorkTopic] = [ + WorkTopic.from_dict(topic) for topic in source.get("topics", []) + ] # type: ignore + elements.append( + AuthorWork( + id=source.get("id", ""), + title=source.get("title", ""), + type=source.get("type", ""), + publication_year=source.get("publication_year", 0), + language_code=source.get("language") or "", + institutions=list(institutions.values()), + topics=topics, + cited_by_count=source.get("cited_by_count", 0), + ) + ) + return AuthorWorkPage( + elements=elements, + total=total, + page=page, + size=size, + ) + + +async def get_work_topics_by_ids(topic_ids: List[str]) -> List[WorkTopic]: + logger.debug(f"Fetching work topics for IDs: {topic_ids}") + if not topic_ids: + return [] + + must = [{"terms": {"id": topic_ids}}] + + response = await elasticsearch.search( + ESIndex.OPENALEX_TOPICS, + source=["id", "display_name", "field", "domain"], + query={"bool": {"must": must}}, + size=len(topic_ids), + ) + + logger.debug(f"Elasticsearch response for work topics {topic_ids}: {response}") + hits_block = response.get("hits", {}) + hits = hits_block.get("hits", []) + topics: List[WorkTopic] = [] + for hit in hits: + source = hit.get("_source", {}) + logger.debug(f"Hit source for work topic {source.get('id', '')}: {source}") + topics.append(WorkTopic.from_dict(source)) # type: ignore + return topics + + +async def get_work_institutions_by_ids(institution_ids: List[str]) -> List[Institution]: + logger.debug(f"Fetching institutions for IDs: {institution_ids}") + if not institution_ids: + return [] + + must = [{"terms": {"id": institution_ids}}] + + response = await elasticsearch.search( + ESIndex.OPENALEX_INSTITUTIONS, + source=["id", "display_name", "country_code"], + query={"bool": {"must": must}}, + size=len(institution_ids), + ) + + logger.debug( + f"Elasticsearch response for institutions {institution_ids}: {response}" + ) + hits_block = response.get("hits", {}) + hits = hits_block.get("hits", []) + institutions: List[Institution] = [] + for hit in hits: + source = hit.get("_source", {}) + logger.debug(f"Hit source for institution {source.get('id', '')}: {source}") + institutions.append(Institution.from_dict(source)) # type: ignore + return institutions diff --git a/ude_person.http b/ude_person.http index 94a219fb..b95414f9 100644 --- a/ude_person.http +++ b/ude_person.http @@ -1147,6 +1147,12 @@ Content-Type: application/json ### +GET https://project.nes.uni-due.de/elastic/openalex-topics/_search +Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ== +Content-Type: application/json + +### + GET https://project.nes.uni-due.de/elastic/openalex-authors/_search Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ== Content-Type: application/json diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index d1311b2f..27e92b2a 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -19,6 +19,7 @@ api/projects.service.ts api/topics.service.ts api/universityRankings.service.ts api/works.service.ts +api/worksV2.service.ts configuration.ts encoder.ts git_push.sh @@ -36,6 +37,9 @@ model/authorNetworkNode.ts model/authorParsedLongestName.ts model/authorPositionCount.ts model/authorSummaryStats.ts +model/authorWork.ts +model/authorWorkInstitution.ts +model/authorWorkPage.ts model/authorWorkPurposes.ts model/authorsFilterProperties.ts model/authorsListResponse.ts @@ -211,6 +215,7 @@ model/workMeshInner.ts model/workNetworkNode.ts model/workPage.ts model/workPurpose.ts +model/workSortBy.ts model/workSustainableDevelopmentGoalsInner.ts model/workTopic.ts model/workTopicDomain.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index 64e95400..43555caf 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -28,4 +28,6 @@ export * from './universityRankings.service'; import { UniversityRankingsService } from './universityRankings.service'; export * from './works.service'; import { WorksService } from './works.service'; -export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, UniversityRankingsService, WorksService]; +export * from './worksV2.service'; +import { WorksV2Service } from './worksV2.service'; +export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, UniversityRankingsService, WorksService, WorksV2Service]; diff --git a/webapp/src/app/api/api/worksV2.service.ts b/webapp/src/app/api/api/worksV2.service.ts new file mode 100644 index 00000000..f8bbee8f --- /dev/null +++ b/webapp/src/app/api/api/worksV2.service.ts @@ -0,0 +1,275 @@ +/** + * 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 { AuthorWorkPage } from '../model/authorWorkPage'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { Institution } from '../model/institution'; +// @ts-ignore +import { SortDirection } from '../model/sortDirection'; +// @ts-ignore +import { WorkSortBy } from '../model/workSortBy'; +// @ts-ignore +import { WorkTopic } from '../model/workTopic'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + + + +@Injectable({ + providedIn: 'root' +}) +export class WorksV2Service extends BaseService { + + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); + } + + /** + * Returns a paginated list of works for a given author based on their ID. + * @endpoint get /api/v2/works/{raw_oa_author_id} + * @param rawOaAuthorId The raw OpenAlex author id. + * @param page The page number to retrieve. (0-based) + * @param size The number of works to retrieve per page. + * @param publicationYears A list of publication years to filter by. + * @param publicationTypes A list of publication types to filter by. + * @param institutionIds A list of institution IDs to filter by. + * @param topicIds A list of topic IDs to filter by. + * @param languageCodes A list of language codes to filter by. + * @param sortBy The field to sort by. + * @param sortOrder The order to sort by. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getAuthorWorkPage(rawOaAuthorId: string, page?: number, size?: number, publicationYears?: Array, publicationTypes?: Array, institutionIds?: Array, topicIds?: Array, languageCodes?: Array, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAuthorWorkPage(rawOaAuthorId: string, page?: number, size?: number, publicationYears?: Array, publicationTypes?: Array, institutionIds?: Array, topicIds?: Array, languageCodes?: Array, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorWorkPage(rawOaAuthorId: string, page?: number, size?: number, publicationYears?: Array, publicationTypes?: Array, institutionIds?: Array, topicIds?: Array, languageCodes?: Array, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorWorkPage(rawOaAuthorId: string, page?: number, size?: number, publicationYears?: Array, publicationTypes?: Array, institutionIds?: Array, topicIds?: Array, languageCodes?: Array, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawOaAuthorId === null || rawOaAuthorId === undefined) { + throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getAuthorWorkPage.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + if (publicationYears) { + publicationYears.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'publication_years'); + }) + } + if (publicationTypes) { + publicationTypes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'publication_types'); + }) + } + if (institutionIds) { + institutionIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'institution_ids'); + }) + } + if (topicIds) { + topicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic_ids'); + }) + } + if (languageCodes) { + languageCodes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'language_codes'); + }) + } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortBy, 'sort_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortOrder, 'sort_order'); + + 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/v2/works/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Returns a list of institutions based on their IDs. + * @endpoint get /api/v2/works/institutions/search + * @param institutionIds A list of institution IDs to retrieve. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInstitutionsByIds(institutionIds?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionsByIds(institutionIds?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public getInstitutionsByIds(institutionIds?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public getInstitutionsByIds(institutionIds?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (institutionIds) { + institutionIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'institution_ids'); + }) + } + + 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/v2/works/institutions/search`; + 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 work topics based on their IDs. + * @endpoint get /api/v2/works/topics/search + * @param topicIds A list of topic IDs to retrieve. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getWorkTopicsByIds(topicIds?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWorkTopicsByIds(topicIds?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public getWorkTopicsByIds(topicIds?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public getWorkTopicsByIds(topicIds?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (topicIds) { + topicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic_ids'); + }) + } + + 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/v2/works/topics/search`; + 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/model/authorWork.ts b/webapp/src/app/api/model/authorWork.ts new file mode 100644 index 00000000..8e301863 --- /dev/null +++ b/webapp/src/app/api/model/authorWork.ts @@ -0,0 +1,48 @@ +/** + * 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 { AuthorWorkInstitution } from './authorWorkInstitution'; +import { WorkTopic } from './workTopic'; + + +export interface AuthorWork { + /** + * The ID of the work + */ + id: string; + /** + * The title of the work + */ + title: string; + /** + * The type of the work + */ + type: string; + /** + * The year the work was published + */ + publication_year: number; + /** + * The language code of the work + */ + language_code: string; + /** + * A list of institutions associated with the work + */ + institutions: Array; + /** + * A list of topics associated with the work + */ + topics: Array; + /** + * The number of citations the work has received + */ + cited_by_count: number; +} + diff --git a/webapp/src/app/api/model/authorWorkInstitution.ts b/webapp/src/app/api/model/authorWorkInstitution.ts new file mode 100644 index 00000000..5656b1cb --- /dev/null +++ b/webapp/src/app/api/model/authorWorkInstitution.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. + */ + + +export interface AuthorWorkInstitution { + /** + * The ID of the institution associated with the work + */ + institution_id: string; + /** + * The name of the institution associated with the work + */ + institution_name: string; + /** + * The country code of the institution associated with the work + */ + institution_country_code: string; +} + diff --git a/webapp/src/app/api/model/authorWorkPage.ts b/webapp/src/app/api/model/authorWorkPage.ts new file mode 100644 index 00000000..561bc421 --- /dev/null +++ b/webapp/src/app/api/model/authorWorkPage.ts @@ -0,0 +1,31 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { AuthorWork } from './authorWork'; + + +export interface AuthorWorkPage { + /** + * The elements of the page. + */ + elements?: Array; + /** + * The page number. (0-based) + */ + page?: number; + /** + * The page size in elements. + */ + size?: number; + /** + * The total number of elements. + */ + total?: number; +} + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 91abe3c5..3077033f 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -11,6 +11,9 @@ export * from './authorNetworkNode'; export * from './authorParsedLongestName'; export * from './authorPositionCount'; export * from './authorSummaryStats'; +export * from './authorWork'; +export * from './authorWorkInstitution'; +export * from './authorWorkPage'; export * from './authorWorkPurposes'; export * from './authorsFilterProperties'; export * from './authorsListResponse'; @@ -185,6 +188,7 @@ export * from './workMeshInner'; export * from './workNetworkNode'; export * from './workPage'; export * from './workPurpose'; +export * from './workSortBy'; export * from './workSustainableDevelopmentGoalsInner'; export * from './workTopic'; export * from './workTopicDomain'; diff --git a/webapp/src/app/api/model/workSortBy.ts b/webapp/src/app/api/model/workSortBy.ts new file mode 100644 index 00000000..7580ac82 --- /dev/null +++ b/webapp/src/app/api/model/workSortBy.ts @@ -0,0 +1,20 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const WorkSortBy = { + Title: 'title', + Type: 'type', + PublicationYear: 'publication_year', + Language: 'language', + CitedByCount: 'cited_by_count' +} as const; +export type WorkSortBy = typeof WorkSortBy[keyof typeof WorkSortBy]; + diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 21a8b833..9a4cc6ca 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -31,6 +31,9 @@ import { KeywordsToPatentsResultsComponent } from './modules/keywords-search/sea import { KeywordsToNewsResultsComponent } from './modules/keywords-search/search-results/news-results/news-results.component'; import { KeywordsToWorksResultsComponent } from './modules/keywords-search/search-results/works-results/works-results.component'; import { authorWorkPurposesResolver } from './resolvers/author-work-purposes.resolver'; +import { workPageResolver } from './resolvers/work-page.resolver'; +import { selectedTopicsResolver } from './resolvers/selected-topics.resolver'; +import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver'; export const routes: Routes = [ { path: '', @@ -271,7 +274,11 @@ export const routes: Routes = [ import('./modules/person-publications/person-publications.component').then( (mod) => mod.PersonPublicationsComponent, ), + runGuardsAndResolvers: 'always', resolve: { + selectedTopics: selectedTopicsResolver, + selectedInstitutions: selectedInstitutionsResolver, + authorWorkPage: workPageResolver, authorWorkPurposes: authorWorkPurposesResolver, }, }, 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 5fa58797..56dca982 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.html +++ b/webapp/src/app/modules/person-publications/person-publications.component.html @@ -21,22 +21,23 @@ Publikationsliste - {{ total }} Publikationen + {{ totalElements() }} Publikationen
-
+ calendar_today + [value]="this.selectedYearsQueryParams()"> {{ yearSelectionSummary() }} @@ -46,7 +47,6 @@ #yearSearchInput type="text" class="select-search__input" - [formControl]="yearSearchControl" placeholder="Jahr suchen…" (keydown)="$event.stopPropagation()" />
@@ -62,12 +62,11 @@ category + [value]="this.selectedTypesQueryParams()"> {{ typeSelectionSummary() }} @@ -93,12 +92,11 @@ translate + [value]="this.selectedLanguagesQueryParams()"> {{ languageSelectionSummary() }} @@ -185,21 +183,6 @@ - - sort - - @for (option of sortOptions; track option.value) { - {{ - option.label - }} - } - - - } - @for (language of selectedLanguages; track language) { + @for ( + language of selectedLanguagesQueryParams(); + track language + ) { translate {{ - languageLabel(language) + language | languageCode }} } - @for (topic of selectedTopics; track topic.id) { + @for (topic of selectedTopics(); track topic.id) { + [matTooltipDisabled]="!getSelectedWorkTopicTooltip(topic)"> label {{ topic.display_name @@ -301,7 +284,10 @@ } - @for (institution of selectedInstitutions; track institution.id) { + @for ( + institution of selectedInstitutions(); + track institution.id + ) { @let instCountry = selectedInstitutionCountry(institution); @@ -325,7 +311,10 @@ } open_in_new @@ -344,13 +333,16 @@ } - + + [total]="totalElements()" + queryParamPageKey="page" + queryParamSizeKey="size" + [pageSizeOptions]="paginationService.options" />
@@ -398,11 +390,11 @@ } @else { - @@ -410,43 +402,49 @@ - @let publicationInstitutions = getInstitutions(work); + @let publicationInstitutions = work.institutions ?? []; @let institutionsExpanded = true; @let visibleInstitutions = institutionsExpanded ? publicationInstitutions : publicationInstitutions.slice(0, 3); -
- @for (institution of visibleInstitutions; track institution.id) { +
+ @for ( + institution of visibleInstitutions; + track institution.institution_id + ) { @@ -483,7 +481,7 @@ [subfieldName]="topic.subfield?.display_name" [fieldName]="topic.field?.display_name" [domainName]="topic.domain?.display_name" - [color]="getTopicColor(topic)" + [color]="getWorkTopicColor(topic)" [disabled]="!topic.id" [active]="isTopicActive(topic)" (chipClick)="filterByTopic(topic)"> @@ -511,7 +509,7 @@ open_in_new 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 d000f46d..19c83518 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.ts +++ b/webapp/src/app/modules/person-publications/person-publications.component.ts @@ -29,9 +29,9 @@ 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 { MatSelectChange, MatSelectModule } from '@angular/material/select'; import { MatTooltipModule } from '@angular/material/tooltip'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; import { catchError, combineLatest, @@ -44,17 +44,18 @@ import { } from 'rxjs'; import { + AuthorWork, + AuthorWorkInstitution, + AuthorWorkPage, AuthorWorkPurposes, Institution, InstitutionsService, SpecificWorkPurpose, - Work, WorkPurpose, WorksService, WorkTopic, } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; -import { createLoadError } from '../../resolvers/utils/errorHandler'; import { ChipComponent } from '../../shared/ui/chip/chip.component'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; @@ -115,17 +116,6 @@ interface TopicAutocompleteResponse { type PublicationSort = 'year' | 'citations'; -interface PublicationFilterQueryState { - pageIndex: number; - pageSize: number; - publicationYears: number[]; - types: string[]; - languages: string[]; - institutions: InstitutionAutocompleteOption[]; - topics: TopicAutocompleteOption[]; - sort: PublicationSort; -} - interface YearlyPurposeCounts { year: number; FOUNDATION: number; @@ -169,6 +159,15 @@ export class PersonPublicationsComponent implements OnInit { @ViewChild(MatPaginator) paginator?: MatPaginator; private readonly destroyRef = inject(DestroyRef); + private readonly worksService = inject(WorksService); + + authorWorkPage = input.required(); + totalElements = computed(() => this.authorWorkPage().total ?? 0); + elements = computed(() => this.authorWorkPage().elements ?? []); + + selectedInstitutions = input.required>(); + selectedTopics = input.required>(); + authorWorkPurposes = input.required(); specificWorkPurposesByYear = computed(() => { const authorWorkPurposes = this.authorWorkPurposes(); @@ -197,7 +196,7 @@ export class PersonPublicationsComponent implements OnInit { chartOption!: echarts.EChartsCoreOption; - workColumns: GenericColumn[] = []; + workColumns: GenericColumn[] = []; titleTmp = viewChild.required>('titleTmp'); typeTmp = viewChild.required>('typeTmp'); yearTmp = viewChild.required>('yearTmp'); @@ -207,26 +206,10 @@ export class PersonPublicationsComponent implements OnInit { citationsTmp = viewChild.required>('citationsTmp'); actionsTmp = viewChild.required>('actionsTmp'); - 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[] = []; private readonly expandedInstitutions = new Set(); private readonly expandedTopics = new Set(); readonly institutionSearchControl = new FormControl< @@ -244,22 +227,11 @@ export class PersonPublicationsComponent implements OnInit { nonNullable: true, }); - readonly sortOptions: { value: PublicationSort; label: string }[] = [ - { value: 'year', label: 'Neueste zuerst' }, - { value: 'citations', label: 'Meistzitiert zuerst' }, - ]; - - readonly filterForm = new FormGroup({ - publicationYears: new FormControl([], { nonNullable: true }), - types: new FormControl([], { nonNullable: true }), - languages: new FormControl([], { nonNullable: true }), - }); - readonly publicationYearOptions = this.createPublicationYearOptions(); private readonly queryParamKeys = { - page: 'publicationPage', - pageSize: 'publicationPageSize', + page: 'page', + pageSize: 'size', years: 'publicationYear', types: 'publicationType', languages: 'publicationLanguage', @@ -300,9 +272,8 @@ export class PersonPublicationsComponent implements OnInit { ]; constructor( - private readonly route: ActivatedRoute, + private readonly activatedRoute: ActivatedRoute, private readonly router: Router, - private readonly workService: WorksService, private readonly httpClient: HttpClient, public readonly paginationService: PaginationService, private readonly snackBar: MatSnackBar, @@ -316,6 +287,74 @@ export class PersonPublicationsComponent implements OnInit { }); } + queryParamMap = toSignal(this.activatedRoute.queryParamMap, { + initialValue: this.activatedRoute.snapshot.queryParamMap, + }); + + selectedYearsQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.years).map(Number); + }); + + handleYearSelectionChange(event: MatSelectChange): void { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.years]: event.value, + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } + + selectedTypesQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.types); + }); + + handleTypeSelectionChange(event: MatSelectChange): void { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.types]: event.value, + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + console.log('Type selection changed:', event.value); + } + + selectedLanguagesQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.languages); + }); + + resolvedInstitutions = computed(() => { + const institutionMap = new Map(); + for (const work of this.elements()) { + for (const institution of work.institutions ?? []) { + if (!institutionMap.has(institution.institution_id)) { + institutionMap.set(institution.institution_id, institution); + } + } + } + return institutionMap; + }); + + handleLanguageSelectionChange(event: MatSelectChange): void { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.languages]: event.value, + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + console.log('Language selection changed:', event.value); + } + + selectedInstitutionIdsQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.institutionIds); + }); + + selectedTopicIdsQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.topicIds); + }); + getAuthorSpecificWorkPurposesByYear( authorWorkPurposes: AuthorWorkPurposes, ): Record> { @@ -402,19 +441,22 @@ export class PersonPublicationsComponent implements OnInit { { id: 'title', header: 'Titel', - type: 'display', + type: 'accessor', + accessorKey: 'title', cellTemplate: this.titleTmp(), }, { id: 'type', header: 'Typ', - type: 'display', + type: 'accessor', + accessorKey: 'type', cellTemplate: this.typeTmp(), }, { id: 'publication_year', header: 'Jahr', - type: 'display', + type: 'accessor', + accessorKey: 'publication_year', cellTemplate: this.yearTmp(), }, { @@ -438,7 +480,8 @@ export class PersonPublicationsComponent implements OnInit { { id: 'cited_by_count', header: 'Zitiert von', - type: 'display', + type: 'accessor', + accessorKey: 'cited_by_count', cellTemplate: this.citationsTmp(), }, { @@ -448,101 +491,16 @@ export class PersonPublicationsComponent implements OnInit { cellTemplate: this.actionsTmp(), }, ]; - - 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 { - console.log('Loading publications for author ID:', this.authorId); - - if (!this.authorId) return; - - this.loading = true; - this.workService - .getAuthorWorks( - this.authorId, - pageIndex + 1, - pageSize, - this.filters().publicationYears, - this.filters().types, - this.filters().languages, - this.selectedInstitutionIds(), - this.selectedTopicIds(), - this.sortControl.value, - ) - .subscribe({ - next: (page) => { - this.publications = page.elements ?? []; - this.total = page.total ?? 0; - this.loading = false; - }, - error: (error) => { - this.loading = false; - createLoadError( - this.snackBar, - () => this.load(pageIndex, pageSize), - 'Publikationen konnten nicht geladen werden', - )(error); - }, - }); - } - - onPage(event: PageEvent): void { - this.paginationService.selection = event.pageSize; - this.currentPageIndex = event.pageIndex; - this.updatePublicationFilterQueryParams({ - [this.queryParamKeys.page]: event.pageIndex + 1, - [this.queryParamKeys.pageSize]: event.pageSize, - }); - } - - applyFilters(): void { - this.currentPageIndex = 0; - this.paginator?.firstPage(); - this.updatePublicationFilterQueryParams({ - [this.queryParamKeys.page]: 1, - [this.queryParamKeys.pageSize]: this.paginationService.selection, - }); - } - - onSortChange(): void { - this.applyFilters(); } clearFilters(): void { - this.filterForm.reset({ - publicationYears: [], - types: [], - languages: [], - }); - 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, - [this.queryParamKeys.topicFields]: null, - [this.queryParamKeys.topicDomains]: null, + this.router.navigate([], { + queryParams: { + page: 0, + size: 10, + sort_by: 'publication_year', + sort_direction: 'desc', + }, }); } @@ -553,47 +511,77 @@ export class PersonPublicationsComponent implements OnInit { 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(); + if (!this.selectedInstitutionIdsQueryParams().includes(institution.id)) { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.institutionIds]: [ + ...this.selectedInstitutionIdsQueryParams(), + institution.id, + ], + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); } - this.institutionSearchControl.setValue('', { emitEvent: false }); - this.institutionOptions = []; } removeInstitution(institution: InstitutionAutocompleteOption): void { - this.selectedInstitutions = this.selectedInstitutions.filter( - (item) => item.id !== institution.id, - ); - this.applyFilters(); + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.institutionIds]: + this.selectedInstitutionIdsQueryParams().filter( + (id) => id !== institution.id, + ), + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); } filterByInstitution(institution: { id: string; name: string }): void { if (!institution.id) return; - if (this.selectedInstitutions.some((item) => item.id === institution.id)) { - return; + const selectedInstitutionIds = this.selectedInstitutionIdsQueryParams(); + if (selectedInstitutionIds.includes(institution.id)) { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.institutionIds]: selectedInstitutionIds.filter( + (id) => id !== institution.id, + ), + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } else { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.institutionIds]: [ + ...selectedInstitutionIds, + institution.id, + ], + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); } - this.selectedInstitutions = [ - ...this.selectedInstitutions, - { id: institution.id, display_name: institution.name }, - ]; - this.applyFilters(); } isInstitutionActive(id: string): boolean { - return !!id && this.selectedInstitutions.some((item) => item.id === id); + return !!id && this.selectedInstitutionIdsQueryParams().includes(id); } selectedInstitutionCountry( institution: InstitutionAutocompleteOption, ): string | null { if (!institution.id) return null; - for (const publication of this.publications) { - for (const authorship of publication.authorships ?? []) { - for (const inst of authorship.institutions ?? []) { - if (inst.id === institution.id && inst.country_code) { - return inst.country_code; - } + const authorWorkPage = this.authorWorkPage(); + if (!authorWorkPage?.elements) return null; + for (const publication of authorWorkPage.elements) { + for (const inst of publication.institutions ?? []) { + if ( + institution.id === inst.institution_id && + inst.institution_country_code + ) { + return inst.institution_country_code; } } } @@ -601,48 +589,80 @@ export class PersonPublicationsComponent implements OnInit { } toggleYearFilter(year: number): void { - const control = this.filterForm.controls.publicationYears; - const current = control.value; - control.setValue( - current.includes(year) - ? current.filter((value) => value !== year) - : [...current, year], - ); - this.applyFilters(); + const selectedYears = this.selectedYearsQueryParams(); + if (selectedYears.includes(year)) { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.years]: selectedYears.filter((y) => y !== year), + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } else { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.years]: [...selectedYears, year], + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } } toggleTypeFilter(type: string): void { - const control = this.filterForm.controls.types; - const current = control.value; - control.setValue( - current.includes(type) - ? current.filter((value) => value !== type) - : [...current, type], - ); - this.applyFilters(); + const selectedTopics = this.selectedTypesQueryParams(); + if (selectedTopics.includes(type)) { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.types]: selectedTopics.filter((t) => t !== type), + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } else { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.types]: [...selectedTopics, type], + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } } toggleLanguageFilter(language: string): void { - const control = this.filterForm.controls.languages; - const current = control.value; - control.setValue( - current.includes(language) - ? current.filter((value) => value !== language) - : [...current, language], - ); - this.applyFilters(); + const selectedLanguages = this.selectedLanguagesQueryParams(); + if (selectedLanguages.includes(language)) { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.languages]: selectedLanguages.filter( + (l) => l !== language, + ), + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } else { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.languages]: [...selectedLanguages, language], + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } } isYearActive(year: number): boolean { - return this.filterForm.controls.publicationYears.value.includes(year); + return this.selectedYearsQueryParams().includes(year); } isTypeActive(type: string): boolean { - return this.filterForm.controls.types.value.includes(type); + return this.selectedTypesQueryParams().includes(type); } isLanguageActive(language: string): boolean { - return this.filterForm.controls.languages.value.includes(language); + return this.selectedLanguagesQueryParams().includes(language); } displayTopic(option: string | TopicAutocompleteOption): string { @@ -652,16 +672,18 @@ export class PersonPublicationsComponent implements OnInit { selectTopic(event: MatAutocompleteSelectedEvent): void { const topic = event.option.value as TopicAutocompleteOption; if (!topic.id) return; - if (!this.selectedTopics.some((item) => item.id === topic.id)) { - const enrichedTopic: TopicAutocompleteOption = { - ...topic, - field_name: topic.field_name ?? this.fieldNameFromHint(topic.hint), - }; - this.selectedTopics = [...this.selectedTopics, enrichedTopic]; - this.applyFilters(); + if (!this.selectedTopicIdsQueryParams().includes(topic.id)) { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.topicIds]: [ + ...this.selectedTopicIdsQueryParams(), + topic.id, + ], + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); } - this.topicSearchControl.setValue('', { emitEvent: false }); - this.topicOptions = []; } private fieldNameFromHint( @@ -672,10 +694,14 @@ export class PersonPublicationsComponent implements OnInit { } removeTopic(topic: TopicAutocompleteOption): void { - this.selectedTopics = this.selectedTopics.filter( - (item) => item.id !== topic.id, - ); - this.applyFilters(); + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.topicIds]: + this.selectedTopicIdsQueryParams().filter((id) => id !== topic.id), + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); } doiUrl(doi: string | null | undefined): string | null { @@ -683,23 +709,23 @@ export class PersonPublicationsComponent implements OnInit { return doi.startsWith('http') ? doi : `https://doi.org/${doi}`; } - toggleInstitutions(publication: Work): void { + toggleInstitutions(publication: AuthorWork): void { this.toggleExpanded(this.expandedInstitutions, publication); } - isInstitutionsExpanded(publication: Work): boolean { + isInstitutionsExpanded(publication: AuthorWork): boolean { return this.expandedInstitutions.has(this.publicationKey(publication)); } - toggleTopics(publication: Work): void { + toggleTopics(publication: AuthorWork): void { this.toggleExpanded(this.expandedTopics, publication); } - isTopicsExpanded(publication: Work): boolean { + isTopicsExpanded(publication: AuthorWork): boolean { return this.expandedTopics.has(this.publicationKey(publication)); } - private toggleExpanded(set: Set, publication: Work): void { + private toggleExpanded(set: Set, publication: AuthorWork): void { const key = this.publicationKey(publication); if (set.has(key)) { set.delete(key); @@ -708,21 +734,17 @@ export class PersonPublicationsComponent implements OnInit { } } - publicationKey(publication: Work): string { - const id = - publication.id ?? publication.ids?.openalex ?? publication.doi ?? ''; + publicationKey(publication: AuthorWork): string { + const id = publication.id; return id.split('/').filter(Boolean).pop() ?? id; } - publicationRange(): string { - if (this.total === 0 || this.publications.length === 0) { - return 'Keine Publikationen'; - } - - return `Zeige 1 bis ${this.publications.length} von ${this.total} Publikationen`; + extractRawId(id: string | null | undefined): string | null { + if (!id) return null; + return id.split('/').filter(Boolean).pop() ?? null; } - getTopicColor(topic: WorkTopic): string { + getWorkTopicColor(topic: WorkTopic): string { return topicHierarchyColor({ id: topic.id, name: topic.display_name, @@ -733,17 +755,14 @@ export class PersonPublicationsComponent implements OnInit { }); } - openInstitutionPage( - institutionId: string | null | undefined, - event: Event, - ): void { - event.stopPropagation(); - event.preventDefault(); - - const id = institutionId?.split('/').pop(); - if (!id) return; - - void this.router.navigate(['/institution', id]); + getSelectedWorkTopicTooltip(topic: WorkTopic): string { + return buildTopicHierarchyTooltip({ + topicName: topic.display_name, + description: topic.description, + subfieldName: topic.subfield?.display_name, + fieldName: topic.field?.display_name, + domainName: topic.domain?.display_name, + }); } getSelectedTopicTooltip(topic: TopicAutocompleteOption): string { @@ -763,7 +782,10 @@ export class PersonPublicationsComponent implements OnInit { ): WorkTopic | undefined { if (!topicId) return undefined; - for (const publication of this.publications) { + const authorWorkPage = this.authorWorkPage(); + if (!authorWorkPage?.elements) return undefined; + + for (const publication of authorWorkPage.elements) { const topic = publication.topics?.find((item) => item.id === topicId); if (topic) return topic; } @@ -783,26 +805,31 @@ export class PersonPublicationsComponent implements OnInit { } isTopicActive(topic: WorkTopic): boolean { - return ( - !!topic.id && this.selectedTopics.some((item) => item.id === topic.id) - ); + return !!topic.id && this.selectedTopicIdsQueryParams().includes(topic.id); } filterByTopic(topic: WorkTopic): void { if (!topic.id) return; - if (this.selectedTopics.some((item) => item.id === topic.id)) return; - this.selectedTopics = [ - ...this.selectedTopics, - { - id: topic.id, - display_name: topic.display_name ?? topic.id, - field_id: topic.field?.id, - field_name: topic.field?.display_name, - domain_id: topic.domain?.id, - domain_name: topic.domain?.display_name, - }, - ]; - this.applyFilters(); + const selectedTopicIds = this.selectedTopicIdsQueryParams(); + if (selectedTopicIds.includes(topic.id)) { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.topicIds]: selectedTopicIds.filter( + (id) => id !== topic.id, + ), + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } else { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.topicIds]: [...selectedTopicIds, topic.id], + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } } typeColor(type: string | null | undefined): string { @@ -812,62 +839,18 @@ export class PersonPublicationsComponent implements OnInit { return 'info'; } - getInstitutions(work: Work): Array { - const institutions: Array = []; - for (const authorship of work.authorships ?? []) { - for (const institution of authorship.institutions ?? []) { - if (!institution.id || !institution.display_name) continue; - if (!institutions.some((inst) => inst.id === institution.id)) { - institutions.push(institution); - } - } - } - return institutions; - } - - institutions( - publication: Work, - ): Array<{ id: string; name: string; country: string | null }> { - const institutionsById = new Map< - string, - { id: string; name: string; country: string | null } - >(); - - 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, - country: institution.country_code ?? null, - }); - } - } - } - - return Array.from(institutionsById.values()); - } - yearSelectionSummary(): string { - return this.summarizeSelection( - this.filterForm.controls.publicationYears.value.map((year) => - String(year), - ), - ); + return this.summarizeSelection(this.selectedYearsQueryParams().map(String)); } typeSelectionSummary(): string { - return this.summarizeSelection(this.filterForm.controls.types.value); + return this.summarizeSelection(this.selectedTypesQueryParams()); } languageSelectionSummary(): string { - const labels = this.filterForm.controls.languages.value.map( - (value) => - this.languageOptions.find((option) => option.value === value)?.label ?? - value, + return this.summarizeSelection( + this.selectedLanguagesQueryParams().map(String), ); - return this.summarizeSelection(labels); } private summarizeSelection(labels: string[]): string { @@ -911,14 +894,6 @@ export class PersonPublicationsComponent implements OnInit { setTimeout(() => input.focus()); } - private filters() { - return { - publicationYears: this.filterForm.controls.publicationYears.value, - types: this.filterForm.controls.types.value, - languages: this.filterForm.controls.languages.value, - }; - } - private setupInstitutionAutocomplete(): void { this.institutionSearchControl.valueChanges .pipe( @@ -941,7 +916,7 @@ export class PersonPublicationsComponent implements OnInit { takeUntilDestroyed(this.destroyRef), ) .subscribe((options) => { - const selectedIds = new Set(this.selectedInstitutionIds()); + const selectedIds = new Set(this.selectedInstitutionIdsQueryParams()); this.institutionOptions = options.filter( (option) => !!option.id && !selectedIds.has(option.id), ); @@ -970,7 +945,7 @@ export class PersonPublicationsComponent implements OnInit { takeUntilDestroyed(this.destroyRef), ) .subscribe((options) => { - const selectedIds = new Set(this.selectedTopicIds()); + const selectedIds = new Set(this.selectedTopicIdsQueryParams()); this.topicOptions = options.filter( (option) => !!option.id && !selectedIds.has(option.id), ); @@ -991,7 +966,7 @@ export class PersonPublicationsComponent implements OnInit { private searchTopics(query: string) { const params = new HttpParams().set('query', query).set('limit', '10'); - const basePath = this.workService.configuration.basePath ?? ''; + const basePath = this.worksService.configuration.basePath ?? ''; return this.httpClient .get(`${basePath}/api/topics/autocomplete`, { params, @@ -999,160 +974,6 @@ export class PersonPublicationsComponent implements OnInit { .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); - const topicFields = this.selectedTopics.map( - (topic) => topic.field_name ?? '', - ); - const topicDomains = this.selectedTopics.map( - (topic) => topic.domain_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, - [this.queryParamKeys.topicFields]: topicFields.some((field) => field) - ? topicFields - : null, - [this.queryParamKeys.topicDomains]: topicDomains.some( - (domain) => domain, - ) - ? topicDomains - : null, - [this.queryParamKeys.sort]: - this.sortControl.value !== 'year' ? this.sortControl.value : 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); - const topicFields = queryParams.getAll(this.queryParamKeys.topicFields); - const topicDomains = queryParams.getAll(this.queryParamKeys.topicDomains); - - 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, - field_name: topicFields[index] || undefined, - domain_name: topicDomains[index] || undefined, - })), - sort: - queryParams.get(this.queryParamKeys.sort) === 'citations' - ? 'citations' - : 'year', - }; - } - - private applyPublicationFilterQueryState( - queryState: PublicationFilterQueryState, - ): void { - this.currentPageIndex = queryState.pageIndex; - this.paginationService.selection = queryState.pageSize; - this.selectedInstitutions = queryState.institutions; - this.selectedTopics = queryState.topics; - this.sortControl.setValue(queryState.sort, { emitEvent: false }); - 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/resolvers/selected-institutions.resolver.ts b/webapp/src/app/resolvers/selected-institutions.resolver.ts new file mode 100644 index 00000000..d5a7cbb2 --- /dev/null +++ b/webapp/src/app/resolvers/selected-institutions.resolver.ts @@ -0,0 +1,18 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { Institution, WorksV2Service } from '../api'; + +export const selectedInstitutionsResolver: ResolveFn> = ( + route, + state, +) => { + const institutionIds = route.queryParamMap.getAll('publicationInstitutionId'); + if (institutionIds.length === 0) { + return []; + } + console.log('Resolving selected institutions for IDs:', institutionIds); + + return inject(WorksV2Service).getInstitutionsByIds( + institutionIds.map((id) => id.trim()).filter((id) => id.length > 0), + ); +}; diff --git a/webapp/src/app/resolvers/selected-topics.resolver.ts b/webapp/src/app/resolvers/selected-topics.resolver.ts new file mode 100644 index 00000000..f538d122 --- /dev/null +++ b/webapp/src/app/resolvers/selected-topics.resolver.ts @@ -0,0 +1,18 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { WorksV2Service, WorkTopic } from '../api'; + +export const selectedTopicsResolver: ResolveFn> = ( + route, + state, +) => { + const topicIds = route.queryParamMap.getAll('publicationTopicId'); + if (topicIds.length === 0) { + return []; + } + console.log('Resolving selected topics for IDs:', topicIds); + + return inject(WorksV2Service).getWorkTopicsByIds( + topicIds.map((id) => id.trim()).filter((id) => id.length > 0), + ); +}; diff --git a/webapp/src/app/resolvers/work-page.resolver.ts b/webapp/src/app/resolvers/work-page.resolver.ts index 5c69230a..bf1a0d8d 100644 --- a/webapp/src/app/resolvers/work-page.resolver.ts +++ b/webapp/src/app/resolvers/work-page.resolver.ts @@ -1,27 +1,44 @@ import { ResolveFn } from '@angular/router'; -import { WorkPage, WorksService } from '../api'; +import { + AuthorWorkPage, + SortDirection, + WorkSortBy, + WorksV2Service, +} from '../api'; import { inject } from '@angular/core'; -export const workPageResolver: ResolveFn = (route, state) => { - const authorId = route.paramMap.get('authorId'); - const page = Number(route.queryParamMap.get('page') || 0); - const pageSize = Number(route.queryParamMap.get('pageSize') || 10); - const publicationYears = route.queryParamMap - .getAll('publicationYears') - .map(Number); - const type = route.queryParamMap.getAll('types'); - const languages = route.queryParamMap.getAll('languages'); - const institutionIds = route.queryParamMap.getAll('institutionIds'); - const topicsIds = route.queryParamMap.getAll('topicsIds'); +export const workPageResolver: ResolveFn = (route, state) => { + const rawOaAuthorId = + route.parent?.paramMap.get('id') || route.paramMap.get('id'); + if (!rawOaAuthorId) { + throw new Error('Author ID is required to resolve author work purposes.'); + } - return inject(WorksService).getAuthorWorks( - authorId!, + const page = Number(route.queryParamMap.get('page')) || 0; + const size = Number(route.queryParamMap.get('size')) || 10; + const publicationYears = route.queryParamMap + .getAll('publicationYear') + .map(Number); + const publicationTypes = route.queryParamMap.getAll('publicationType'); + const institutionIds = route.queryParamMap.getAll('publicationInstitutionId'); + const topicIds = route.queryParamMap.getAll('publicationTopicId'); + + const sortBy: WorkSortBy = (route.queryParamMap.get('sort_by') || + 'publication_year') as WorkSortBy; + const sortDirection: SortDirection = (route.queryParamMap.get( + 'sort_direction', + ) || 'desc') as SortDirection; + + return inject(WorksV2Service).getAuthorWorkPage( + rawOaAuthorId, page, - pageSize, + size, publicationYears, - type, - languages, + publicationTypes, institutionIds, - topicsIds, + topicIds, + undefined, + sortBy, + sortDirection, ); };