From a5664e01fe5d2767bb99c1939d5433d88bf8e514 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Mon, 20 Jul 2026 21:11:17 +0200 Subject: [PATCH] feat(work-classifications): optimized aggregation retrieval, moved chart to own component, and added chart for institution publications --- service/src/main/inse/authors/v2/service.py | 48 +++ .../main/inse/integrations/elasticsearch.py | 6 +- service/src/main/inse/works/v2/model.py | 13 +- service/src/main/inse/works/v2/router.py | 175 +++++++--- service/src/main/inse/works/v2/service.py | 326 +++++++++++------- ude_person.http | 14 + webapp/src/app/api/.openapi-generator/FILES | 4 +- webapp/src/app/api/api/worksV2.service.ts | 199 +++++++---- webapp/src/app/api/model/authorPage.ts | 3 + .../app/api/model/dfgInstitutionSummary.ts | 22 +- webapp/src/app/api/model/dfgPersonSummary.ts | 20 +- webapp/src/app/api/model/dfgProjectSummary.ts | 50 +-- webapp/src/app/api/model/institutionPageV2.ts | 3 + webapp/src/app/api/model/models.ts | 4 +- .../model/primaryCategoryYearAggregation.ts | 22 ++ ... => primaryCategoryYearAggregationPage.ts} | 6 +- .../app/api/model/workClassificationMerge.ts | 21 -- webapp/src/app/app.routes.ts | 8 +- .../institution-publications.component.html | 33 +- .../institution-publications.component.scss | 22 ++ .../institution-publications.component.ts | 20 +- .../person-publications.component.html | 110 +++--- .../person-publications.component.ts | 264 +------------- ...uthor-work-classification-page.resolver.ts | 16 - ...category-year-aggregation-page.resolver.ts | 26 ++ .../app/shared/services/credential.service.ts | 3 + ...gory-year-aggregation-chart.component.html | 18 + ...gory-year-aggregation-chart.component.scss | 7 + ...tegory-year-aggregation-chart.component.ts | 184 ++++++++++ 29 files changed, 980 insertions(+), 667 deletions(-) create mode 100644 webapp/src/app/api/model/primaryCategoryYearAggregation.ts rename webapp/src/app/api/model/{workClassificationMergePage.ts => primaryCategoryYearAggregationPage.ts} (71%) delete mode 100644 webapp/src/app/api/model/workClassificationMerge.ts delete mode 100644 webapp/src/app/resolvers/author-work-classification-page.resolver.ts create mode 100644 webapp/src/app/resolvers/primary-category-year-aggregation-page.resolver.ts create mode 100644 webapp/src/app/shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component.html create mode 100644 webapp/src/app/shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component.scss create mode 100644 webapp/src/app/shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component.ts diff --git a/service/src/main/inse/authors/v2/service.py b/service/src/main/inse/authors/v2/service.py index 428d7fed..777daa39 100644 --- a/service/src/main/inse/authors/v2/service.py +++ b/service/src/main/inse/authors/v2/service.py @@ -47,6 +47,21 @@ async def search_authors( return AuthorPage(elements=authors, total=len(authors), page=page, size=size) +async def get_author_by_id(author_id: str) -> Optional[Author]: + """Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID. + + Args: + author_id (str): The ID of the author to retrieve. + + Returns: + Optional[Author]: The retrieved author, or None if not found. + """ + response = await elasticsearch.get(index=ESIndex.OPENALEX_AUTHORS, doc_id=author_id) + if not response.get("found"): + return None + return Author.from_dict(response.get("_source", {})) # type: ignore + + async def autocomplete_authors_for_selector(query: str) -> AuthorPage: """Autocompletes authors based on a search term for use in a selector component. @@ -95,3 +110,36 @@ async def get_authors_by_ids(author_ids: List[str]) -> AuthorPage: "works_count", ], ) + + +async def author_currently_belongs_to_institution( + raw_oa_author_id: str, + raw_oa_institution_id: str, + current_years: List[int] = [2025, 2026], +) -> bool: + """Checks if an author currently belongs to a specific institution based on their affiliations and the provided years. + + Args: + raw_oa_author_id (str): The ID of the author to check. + raw_oa_institution_id (str): The ID of the institution to check. + current_years (List[int], optional): The years to check for affiliation. Defaults to [2025, 2026]. + + Returns: + bool: True if the author belongs to the institution in any of the specified years, False otherwise. + """ + + author = await get_author_by_id(raw_oa_author_id) + if not author: + return False + + for affiliation in author.affiliations or []: + institution = affiliation.institution + if not institution: + continue + + if institution.id == f"https://openalex.org/{raw_oa_institution_id}" and any( + year in (affiliation.years or []) for year in current_years + ): + return True + + return False diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index b58065cf..3777d6fc 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -129,6 +129,7 @@ async def search( size: Optional[int] = None, offset: Optional[int] = None, sort: Optional[List] = None, + aggs: Optional[Dict] = None, body: Optional[Dict] = None, track_total_hits=False, highlight: Optional[Dict] = None, @@ -143,6 +144,7 @@ async def search( size (Optional[int], optional): The maximum number of results to return. Defaults to None. offset (Optional[int], optional): The number of results to skip. Defaults to None. sort (Optional[List], optional): The fields to sort by. Defaults to None. + aggs (Optional[Dict], optional): The aggregations to include in the response. Defaults to None. body (Optional[Dict], optional): The full query body. Defaults to None. track_total_hits (bool, optional): Whether to track the total number of hits. Defaults to False. cluster (ElasticsearchCluster, optional): The Elasticsearch cluster to search. Defaults to ElasticsearchCluster.NES. @@ -189,6 +191,8 @@ async def search( payload["from"] = offset if sort is not None: payload["sort"] = sort + if aggs is not None: + payload["aggs"] = aggs if track_total_hits: payload["track_total_hits"] = True if highlight is not None: @@ -196,7 +200,7 @@ async def search( if len(payload) == 0: raise ValueError( - "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided" + "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided" ) client = get_client() diff --git a/service/src/main/inse/works/v2/model.py b/service/src/main/inse/works/v2/model.py index f1d732d1..5cde6e77 100644 --- a/service/src/main/inse/works/v2/model.py +++ b/service/src/main/inse/works/v2/model.py @@ -1,6 +1,6 @@ from datetime import datetime from enum import StrEnum -from typing import Optional, List +from typing import Dict, Optional, List from pydantic import BaseModel, Field @@ -179,12 +179,13 @@ class WorkClassificationPage(Page[WorkClassification]): pass -class WorkClassificationMerge(BaseModel): - work: Work = Field(description="The OpenAlex work object.") - classification: Optional[WorkClassification] = Field( - default=None, description="The classification result for the work." +class PrimaryCategoryYearAggregation(BaseModel): + publication_year: int = Field(description="The publication year.") + categories: Dict[WorkPrimaryCategory, int] = Field( + default_factory=dict, + description="A mapping of primary categories to their counts for the given year.", ) -class WorkClassificationMergePage(Page[WorkClassificationMerge]): +class PrimaryCategoryYearAggregationPage(Page[PrimaryCategoryYearAggregation]): pass diff --git a/service/src/main/inse/works/v2/router.py b/service/src/main/inse/works/v2/router.py index 1d741428..76ae238c 100644 --- a/service/src/main/inse/works/v2/router.py +++ b/service/src/main/inse/works/v2/router.py @@ -6,15 +6,16 @@ from fastapi import APIRouter, Path, Query from inse.tags import Tags from inse.model import SortDirection from inse.works.v2.model import ( + PrimaryCategoryYearAggregationPage, WorkClassification, - WorkClassificationMergePage, WorkClassificationPage, WorkPageV2, WorkSortBy, ) from inse.auth.model import AccessTokenMetadata from inse.auth.service import CurrentUserAccessTokenPayloadDep -from inse.works.v2.service import get_works_by_keywords +import inse.works.v2.service as works_service + WORKS_v2_PREFIX = "/api/v2/works" logger = logging.getLogger(__name__) @@ -67,9 +68,7 @@ async def get_author_works( SortDirection, Query(description="The order to sort by.") ] = SortDirection.DESCENDING, ) -> WorkPageV2: - from inse.works.v2.service import get_author_works - - return await get_author_works( + return await works_service.get_author_works( raw_oa_author_id=raw_oa_author_id, page=page, size=size, @@ -83,33 +82,65 @@ async def get_author_works( sort_order=sort_order, ) + @router.get( "/keyword/search", operation_id="getWorksByKeywords", - response_model=WorkPageV2, - summary="Search works by topics or raw keywords with filters." + summary="Search works by topics or raw keywords with filters.", ) async def search_works_by_keywords( - topics: Annotated[list[str] | None, Query(description="List of topics to match.")] = None, - topic_ids: Annotated[list[str] | None, Query(description="List of topic IDs to match.")] = None, + topics: Annotated[ + list[str] | None, Query(description="List of topics to match.") + ] = None, + topic_ids: Annotated[ + list[str] | None, Query(description="List of topic IDs to match.") + ] = None, filter_topic_ids: Annotated[ list[str] | None, - Query(description="Additional topic IDs to filter results by, independent of search mode."), + Query( + description="Additional topic IDs to filter results by, independent of search mode." + ), ] = None, - keywords: Annotated[list[str] | None, Query(description="Raw keywords to search in title/abstract.")] = None, - fuzzy: Annotated[bool, Query(description="Use topic resolution if True, otherwise use raw keywords.")] = True, - publication_year: Annotated[list[int] | None, Query(description="A list of publication years to filter by.")] = None, - publication_type: Annotated[list[str] | None, Query(description="A list of publication types to filter by.")] = None, - institution_ids: Annotated[list[str] | None, Query(description="A list of institution IDs to filter by.")] = None, - author_ids: Annotated[list[str] | None, Query(description="A list of author IDs to filter by.")] = None, - language: Annotated[list[str] | None, Query(description="A list of language codes to filter by.")] = None, - title: Annotated[str | None, Query(description="Title to search for in works.")] = None, - 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, - 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, + keywords: Annotated[ + list[str] | None, Query(description="Raw keywords to search in title/abstract.") + ] = None, + fuzzy: Annotated[ + bool, + Query(description="Use topic resolution if True, otherwise use raw keywords."), + ] = True, + publication_year: Annotated[ + list[int] | None, Query(description="A list of publication years to filter by.") + ] = None, + publication_type: Annotated[ + list[str] | None, Query(description="A list of publication types to filter by.") + ] = None, + institution_ids: Annotated[ + list[str] | None, Query(description="A list of institution IDs to filter by.") + ] = None, + author_ids: Annotated[ + list[str] | None, Query(description="A list of author IDs to filter by.") + ] = None, + language: Annotated[ + list[str] | None, Query(description="A list of language codes to filter by.") + ] = None, + title: Annotated[ + str | None, Query(description="Title to search for in works.") + ] = None, + 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, + 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, ) -> WorkPageV2: - return await get_works_by_keywords( + return await works_service.get_works_by_keywords( topics=topics or [], keywords=keywords or [], fuzzy=fuzzy, @@ -126,7 +157,8 @@ async def search_works_by_keywords( sort_by=sort_by, sort_order=sort_order, ) - + + @router.get( "/institution/{raw_oa_institution_id}", operation_id="getInstitutionWorkPage", @@ -173,9 +205,7 @@ async def get_institution_works( SortDirection, Query(description="The order to sort by.") ] = SortDirection.DESCENDING, ) -> WorkPageV2: - from inse.works.v2.service import get_institution_works - - return await get_institution_works( + return await works_service.get_institution_works( raw_oa_institution_id=raw_oa_institution_id, page=page, size=size, @@ -190,24 +220,6 @@ async def get_institution_works( ) -@router.get( - "/classification/author/{raw_oa_author_id}", - operation_id="getWorkClassificationsByAuthorId", - summary="Returns the classifications of an author's works based on their ID.", -) -async def get_work_classifications_by_author_id( - access_token_metadata: Annotated[ - AccessTokenMetadata, CurrentUserAccessTokenPayloadDep - ], - raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")], -) -> WorkClassificationMergePage: - from inse.works.v2.service import get_work_classifications_by_author_id - - return await get_work_classifications_by_author_id( - access_token_metadata=access_token_metadata, raw_oa_author_id=raw_oa_author_id - ) - - @router.get( "/classification/work/{raw_oa_work_id}", operation_id="getWorkClassificationByWorkId", @@ -219,9 +231,7 @@ async def get_work_classification_by_work_id( ], raw_oa_work_id: Annotated[str, Path(description="The raw OpenAlex work id.")], ) -> WorkClassification | None: - from inse.works.v2.service import get_work_classification_by_work_id - - return await get_work_classification_by_work_id( + return await works_service.get_work_classification_by_work_id( access_token_metadata=access_token_metadata, raw_oa_work_id=raw_oa_work_id ) @@ -253,15 +263,70 @@ async def get_work_classifications_by_work_ids( ), ] = 10, ) -> WorkClassificationPage: - from inse.works.v2.service import get_work_classifications_by_work_ids - - logger.debug( - f"Fetching work classifications for work IDs: {work_ids}, page: {page}, size: {size}" - ) - - return await get_work_classifications_by_work_ids( + return await works_service.get_work_classifications_by_work_ids( access_token_metadata=access_token_metadata, work_ids=work_ids or [], page=page, size=size, ) + + +@router.get( + "/institution/{raw_oa_institution_id}/primary-category-aggregations", + operation_id="getPrimaryCategoryAggregationsByInstitutionId", + summary="Returns the primary category aggregations of works for a given institution based on their ID.", +) +async def get_primary_category_aggregations_by_institution_id( + access_token_metadata: Annotated[ + AccessTokenMetadata, CurrentUserAccessTokenPayloadDep + ], + raw_oa_institution_id: Annotated[ + str, Path(description="The raw OpenAlex institution id.") + ], + year_size: Annotated[ + int, + Query(description="The number of years to retrieve aggregations for.", ge=1), + ] = 100, + category_size: Annotated[ + int, + Query( + description="The number of categories to retrieve aggregations for.", ge=1 + ), + ] = 50, +) -> PrimaryCategoryYearAggregationPage: + + return await works_service.get_primary_category_aggregations_by_institution_id( + access_token_metadata=access_token_metadata, + raw_oa_institution_id=raw_oa_institution_id, + year_size=year_size, + category_size=category_size, + ) + + +@router.get( + "/author/{raw_oa_author_id}/primary-category-aggregations", + operation_id="getPrimaryCategoryAggregationsByAuthorId", + summary="Returns the primary category aggregations of works for a given author based on their ID", +) +async def get_primary_category_aggregations_by_author_id( + access_token_metadata: Annotated[ + AccessTokenMetadata, CurrentUserAccessTokenPayloadDep + ], + raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")], + year_size: Annotated[ + int, + Query(description="The number of years to retrieve aggregations for.", ge=1), + ] = 100, + category_size: Annotated[ + int, + Query( + description="The number of categories to retrieve aggregations for.", ge=1 + ), + ] = 50, +) -> PrimaryCategoryYearAggregationPage: + return await works_service.get_primary_category_aggregations_by_author_id( + access_token_metadata=access_token_metadata, + raw_oa_author_id=raw_oa_author_id, + year_size=year_size, + category_size=category_size, + ) diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index 80e7bada..b6626478 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -4,15 +4,17 @@ from fastapi import Query from inse.integrations import elasticsearch from inse.model import ESIndex, SortDirection, ESCluster from inse.works.v2.model import ( + PrimaryCategoryYearAggregation, + PrimaryCategoryYearAggregationPage, WorkClassification, WorkClassificationPage, - WorkClassificationMerge, - WorkClassificationMergePage, WorkPageV2, WorkSortBy, ) from inse.models.openalex.work import Work from inse.auth.model import AccessTokenMetadata +import inse.authors.v2.service as author_service + logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) @@ -229,17 +231,24 @@ async def get_works( return await _execute_works_search(must, page, size, sort_by, sort_order) + async def get_works_by_keywords( topics: Optional[List[str]] = Query(None, description="List of topics to match."), - topic_ids: Optional[List[str]] = Query(None, description="List of topic IDs to match."), + topic_ids: Optional[List[str]] = Query( + None, description="List of topic IDs to match." + ), filter_topic_ids: Optional[List[str]] = Query( None, description="Additional topic IDs to filter results by (OR semantics), " - "applied independently of the fuzzy/keyword search mode.", + "applied independently of the fuzzy/keyword search mode.", + ), + keywords: Optional[List[str]] = Query( + None, description="Raw keywords to search in title/abstract." ), - keywords: Optional[List[str]] = Query(None, description="Raw keywords to search in title/abstract."), title: Optional[str] = None, - fuzzy: bool = Query(True, description="Use topic resolution if True, otherwise use raw keywords."), + fuzzy: bool = Query( + True, description="Use topic resolution if True, otherwise use raw keywords." + ), publication_year: Optional[List[int]] = Query(None), publication_type: Optional[List[str]] = Query(None, alias="type"), language: Optional[List[str]] = Query(None), @@ -250,7 +259,7 @@ async def get_works_by_keywords( sort_by: WorkSortBy = Query(WorkSortBy.PUBLICATION_YEAR), sort_order: SortDirection = Query(SortDirection.DESCENDING), ) -> WorkPageV2: - #print(f"get_works_by_keywords called with topics={topics}, topic_ids={topic_ids}, filter_topic_ids={filter_topic_ids}, keywords={keywords}, fuzzy={fuzzy}, publication_year={publication_year}, publication_type={publication_type}, language={language},title={title}, institution_ids={institution_ids}, page={page}, size={size}, sort_by={sort_by}, sort_order={sort_order}") + # print(f"get_works_by_keywords called with topics={topics}, topic_ids={topic_ids}, filter_topic_ids={filter_topic_ids}, keywords={keywords}, fuzzy={fuzzy}, publication_year={publication_year}, publication_type={publication_type}, language={language},title={title}, institution_ids={institution_ids}, page={page}, size={size}, sort_by={sort_by}, sort_order={sort_order}") def _topics_nested_clause(should_clauses: List[Dict]) -> Dict: return { "nested": { @@ -286,32 +295,50 @@ async def get_works_by_keywords( elif keywords: keyword_clauses = [] for kw in keywords: - keyword_clauses.append({ - "bool": { - "should": [ - {"nested": {"path": "keywords", "query": {"match_phrase": {"keywords.display_name": kw}}}}, - {"match_phrase": {"primary_topic.display_name": kw}}, - {"match_phrase": {"title": kw}}, - {"match_phrase": {"abstract": kw}}, - _topics_nested_clause([ - {"match_phrase": {"topics.display_name": kw}}, - {"match_phrase": {"topics.field.display_name": kw}}, - {"match_phrase": {"topics.subfield.display_name": kw}}, - {"match_phrase": {"topics.domain.display_name": kw}}, - ]), - ], - "minimum_should_match": 1, + keyword_clauses.append( + { + "bool": { + "should": [ + { + "nested": { + "path": "keywords", + "query": { + "match_phrase": {"keywords.display_name": kw} + }, + } + }, + {"match_phrase": {"primary_topic.display_name": kw}}, + {"match_phrase": {"title": kw}}, + {"match_phrase": {"abstract": kw}}, + _topics_nested_clause( + [ + {"match_phrase": {"topics.display_name": kw}}, + {"match_phrase": {"topics.field.display_name": kw}}, + { + "match_phrase": { + "topics.subfield.display_name": kw + } + }, + { + "match_phrase": { + "topics.domain.display_name": kw + } + }, + ] + ), + ], + "minimum_should_match": 1, + } } - }) + ) topic_clause = {"bool": {"must": keyword_clauses}} if not topic_clause: return WorkPageV2(elements=[], total=0, page=page, size=size) - #filters + # filters must = [topic_clause] - if title: must.append(_title_query(title)) if publication_year: @@ -325,13 +352,13 @@ async def get_works_by_keywords( if author_ids: must.append(_authors_nested_query(author_ids)) - #sorting + # sorting if sort_by == WorkSortBy.TITLE: sort = [{"title.keyword": sort_order.value}] else: sort = [{sort_by.value: sort_order.value}] - print(f"Final query:",must) - #search + print(f"Final query:", must) + # search response = await elasticsearch.search( index=ESIndex.OPENALEX_WORKS_WILDCARD, source=[ @@ -359,7 +386,7 @@ async def get_works_by_keywords( ) print(f"Elasticsearch response: {response}") logger.debug(f"Query: {{'bool': {{'must': {must}}}}}") - #model mapping + # model mapping hits_block = response.get("hits", {}) total = hits_block.get("total", {}).get("value", 0) hits = hits_block.get("hits", []) @@ -375,6 +402,7 @@ async def get_works_by_keywords( return WorkPageV2(elements=elements, total=total, page=page, size=size) + async def get_author_works( raw_oa_author_id: str, page: int, @@ -469,80 +497,6 @@ async def get_institution_works( ) -async def get_work_classifications_by_author_id( - access_token_metadata: AccessTokenMetadata, raw_oa_author_id: str -) -> WorkClassificationMergePage: - """Retrieves work classifications for a specific author, filtered by the effective institution ID from the access token metadata. - - Args: - access_token_metadata (AccessTokenMetadata): The access token metadata containing the effective institution ID. - raw_oa_author_id (str): The ID of the author for whom to retrieve work classifications. - - Returns: - WorkClassificationMergePage: The page of work classifications matching the criteria. - """ - raw_account_institution_id = access_token_metadata.effective_institution_id - - work_page = await _get_work_ids_with_publication_year_for_author_id( - raw_oa_author_id=raw_oa_author_id - ) - logger.debug( - f"Fetched {len(work_page.elements)} works for author {raw_oa_author_id} with publication year and institution {raw_account_institution_id}" - ) - - works_dict: Dict[str, Work] = { - work.id: work - for work in work_page.elements - if work.id is not None and work.publication_year is not None - } - work_ids = list(works_dict.keys()) - logger.debug( - f"Filtered to {len(work_ids)} works for author {raw_oa_author_id} with publication year and institution {raw_account_institution_id}" - ) - - allowed_work_ids: List[str] = [] - for work in works_dict.values(): - if work.id and _work_has_authorship_with_institution_id( - work, raw_account_institution_id - ): - allowed_work_ids.append(work.id) - - logger.debug( - f"Filtered to {len(allowed_work_ids)} works for author {raw_oa_author_id} that are associated with institution {raw_account_institution_id}" - ) - - # all works considered here are associated with the account institution, so we can fetch their classifications without further filtering - work_classification_page = await _get_work_classifications_by_work_ids( - work_ids=allowed_work_ids, page=0, size=len(allowed_work_ids) - ) - works_classifications_dict: Dict[str, WorkClassification] = { - work.work_id: work for work in work_classification_page.elements - } - logger.debug( - f"Fetched {len(works_classifications_dict)} work classifications for author {raw_oa_author_id} and institution {raw_account_institution_id}" - ) - - work_classification_merges: List[WorkClassificationMerge] = [ - WorkClassificationMerge( - work=works_dict[work_id], - classification=works_classifications_dict.get( - work_id, None - ), # None, if no classification exists for this work -> work is from another institution, or has not been classified yet - ) - for work_id in work_ids - ] - logger.debug( - f"Created {len(work_classification_merges)} work classification merges for author {raw_oa_author_id} and institution {raw_account_institution_id}" - ) - - return WorkClassificationMergePage( - elements=work_classification_merges, - total=len(work_classification_merges), - page=0, - size=len(work_classification_merges), - ) - - async def get_work( raw_oa_work_id: str, source: Optional[List[str]] = None ) -> Work | None: @@ -556,6 +510,7 @@ async def get_work( Work | None: The retrieved work, or None if not found. """ + # search instead of get, because multiple indices are used for works work_page = await search_works( query={"term": {"id": _prefix_id(raw_oa_work_id)}}, source=source, @@ -607,32 +562,6 @@ async def search_works( return WorkPageV2(elements=works, total=total, page=page, size=size) -async def _get_work_ids_with_publication_year_for_author_id( - raw_oa_author_id: str, -) -> WorkPageV2: - """Retrieves works for a specific author, including only those works that have a publication year and are associated with the specified author ID. - - Args: - raw_oa_author_id (str): The ID of the author for which to retrieve works. - - Returns: - WorkPageV2: The page of works matching the criteria. - """ - - return await search_works( - query={ - "nested": { - "path": "authorships", - "query": { - "term": {"authorships.author.id": _prefix_id(raw_oa_author_id)} - }, - } - }, - source=["id", "publication_year", "authorships.institutions.id"], - size=10000, - ) - - async def _get_works_by_work_ids_and_institution_id( work_ids: List[str], raw_oa_institution_id: str | None ) -> WorkPageV2: @@ -889,3 +818,142 @@ def _prefix_id(raw_id: str) -> str: if not raw_id.startswith("https://openalex.org/"): return f"https://openalex.org/{raw_id}" return raw_id + + +async def _get_primary_category_year_aggregations( + nested_path: str, + term_field: str, + term_value: str, + year_size: int = 100, + category_size: int = 50, +) -> PrimaryCategoryYearAggregationPage: + """Gets primary category aggregations by year for works that match a specific term in a nested field. + + Args: + nested_path (str): The path to the nested field in the Elasticsearch index. + term_field (str): The field within the nested path to filter by. + term_value (str): The value to filter the term field by. + year_size (int, optional): The maximum number of years to include in the aggregation. Defaults to 100. + category_size (int, optional): The maximum number of categories to include in the aggregation. Defaults to 50. + + Returns: + PrimaryCategoryYearAggregationPage: A page of primary category aggregations by year for the matching works. + """ + + response = await elasticsearch.search( + ESIndex.WORK_CLASSIFICATIONS, + query={ + "nested": { + "path": nested_path, + "query": {"term": {term_field: term_value}}, + } + }, + size=0, + aggs={ + "by_year": { + "terms": { + "field": "publication_year", + "size": year_size, + "order": {"_key": "asc"}, + }, + "aggs": { + "by_category": { + "terms": { + "field": "classification.primary_category", + "size": category_size, + } + } + }, + } + }, + ) + + year_buckets = ( + response.get("aggregations", {}).get("by_year", {}).get("buckets", []) + ) + + results: List[PrimaryCategoryYearAggregation] = [] + for year_bucket in year_buckets: + category_buckets = year_bucket.get("by_category", {}).get("buckets", []) + categories = {cb["key"]: cb["doc_count"] for cb in category_buckets} + + results.append( + PrimaryCategoryYearAggregation( + publication_year=year_bucket["key"], + categories=categories, + ) + ) + + return PrimaryCategoryYearAggregationPage( + elements=results, total=len(results), page=0, size=len(results) + ) + + +async def get_primary_category_aggregations_by_institution_id( + access_token_metadata: AccessTokenMetadata, + raw_oa_institution_id: str, + year_size: int = 100, + category_size: int = 50, +) -> PrimaryCategoryYearAggregationPage: + """Gets primary category aggregations by year for works associated with a specific institution ID, filtered by the effective institution ID from the access token metadata. + + Args: + access_token_metadata (AccessTokenMetadata): The access token metadata containing the effective institution ID. + raw_oa_institution_id (str): The raw OpenAlex institution ID. + year_size (int, optional): The maximum number of years to include in the aggregation. Defaults to 100. + category_size (int, optional): The maximum number of categories to include in the aggregation. Defaults to 50. + + Returns: + PrimaryCategoryYearAggregationPage: A page of primary category aggregations by year for the matching works. + """ + + account_raw_oa_institution_id = access_token_metadata.effective_institution_id + if account_raw_oa_institution_id != raw_oa_institution_id: + return PrimaryCategoryYearAggregationPage(elements=[]) + + prefixed_institution_id = _prefix_id(raw_oa_institution_id) + + return await _get_primary_category_year_aggregations( + nested_path="institutions", + term_field="institutions.id", + term_value=prefixed_institution_id, + year_size=year_size, + category_size=category_size, + ) + + +async def get_primary_category_aggregations_by_author_id( + access_token_metadata: AccessTokenMetadata, + raw_oa_author_id: str, + year_size: int = 100, + category_size: int = 50, +) -> PrimaryCategoryYearAggregationPage: + """Gets primary category aggregations by year for works associated with a specific author ID, filtered by the effective institution ID from the access token metadata. + + Args: + access_token_metadata (AccessTokenMetadata): The access token metadata containing the effective institution ID. + raw_oa_author_id (str): The raw OpenAlex author ID. + year_size (int, optional): The maximum number of years to include in the aggregation. Defaults to 100. + category_size (int, optional): The maximum number of categories to include in the aggregation. Defaults to 50. + + Returns: + PrimaryCategoryYearAggregationPage: A page of primary category aggregations by year for the matching works. + """ + + account_institution_id = access_token_metadata.effective_institution_id + if not account_institution_id: + return PrimaryCategoryYearAggregationPage(elements=[]) + if not await author_service.author_currently_belongs_to_institution( + raw_oa_author_id, account_institution_id + ): + return PrimaryCategoryYearAggregationPage(elements=[]) + + prefixed_author_id = _prefix_id(raw_oa_author_id) + + return await _get_primary_category_year_aggregations( + nested_path="authors", + term_field="authors.id", + term_value=prefixed_author_id, + year_size=year_size, + category_size=category_size, + ) diff --git a/ude_person.http b/ude_person.http index e139e498..32eea3dc 100644 --- a/ude_person.http +++ b/ude_person.http @@ -1151,6 +1151,20 @@ GET https://project.nes.uni-due.de/elastic/work-classifications/_search Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ== Content-Type: application/json +{ + "query": { + "nested": { + "path": "authors", + "query": { + "term": { + "authors.id": "https://openalex.org/A5007170803" + } + } + } + }, + "size": 100 +} + ### GET https://project.nes.uni-due.de/elastic/work-classifications/_search diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 86676070..bcaf568d 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -188,6 +188,8 @@ model/patentsByKeywordsRequest.ts model/patentsByKeywordsResponse.ts model/personBio.ts model/personBookmarkResponse.ts +model/primaryCategoryYearAggregation.ts +model/primaryCategoryYearAggregationPage.ts model/projectType.ts model/projectsFilteringProperties.ts model/projectsSortBy.ts @@ -238,8 +240,6 @@ model/workClassification.ts model/workClassificationAuthor.ts model/workClassificationDetails.ts model/workClassificationInstitution.ts -model/workClassificationMerge.ts -model/workClassificationMergePage.ts model/workClassificationMeta.ts model/workClassificationPage.ts model/workClassificationTopic.ts diff --git a/webapp/src/app/api/api/worksV2.service.ts b/webapp/src/app/api/api/worksV2.service.ts index 78013c2d..50f05609 100644 --- a/webapp/src/app/api/api/worksV2.service.ts +++ b/webapp/src/app/api/api/worksV2.service.ts @@ -19,12 +19,12 @@ import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore +import { PrimaryCategoryYearAggregationPage } from '../model/primaryCategoryYearAggregationPage'; +// @ts-ignore import { SortDirection } from '../model/sortDirection'; // @ts-ignore import { WorkClassification } from '../model/workClassification'; // @ts-ignore -import { WorkClassificationMergePage } from '../model/workClassificationMergePage'; -// @ts-ignore import { WorkClassificationPage } from '../model/workClassificationPage'; // @ts-ignore import { WorkPageV2 } from '../model/workPageV2'; @@ -263,6 +263,142 @@ export class WorksV2Service extends BaseService { ); } + /** + * Returns the primary category aggregations of works for a given author based on their ID + * @endpoint get /api/v2/works/author/{raw_oa_author_id}/primary-category-aggregations + * @param rawOaAuthorId The raw OpenAlex author id. + * @param yearSize The number of years to retrieve aggregations for. + * @param categorySize The number of categories to retrieve aggregations for. + * @param secureFgpAcc + * @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 getPrimaryCategoryAggregationsByAuthorId(rawOaAuthorId: string, yearSize?: number, categorySize?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPrimaryCategoryAggregationsByAuthorId(rawOaAuthorId: string, yearSize?: number, categorySize?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPrimaryCategoryAggregationsByAuthorId(rawOaAuthorId: string, yearSize?: number, categorySize?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPrimaryCategoryAggregationsByAuthorId(rawOaAuthorId: string, yearSize?: number, categorySize?: number, secureFgpAcc?: string, 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 getPrimaryCategoryAggregationsByAuthorId.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + yearSize, 'year_size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + categorySize, 'category_size'); + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', '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/v2/works/author/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/primary-category-aggregations`; + 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 the primary category aggregations of works for a given institution based on their ID. + * @endpoint get /api/v2/works/institution/{raw_oa_institution_id}/primary-category-aggregations + * @param rawOaInstitutionId The raw OpenAlex institution id. + * @param yearSize The number of years to retrieve aggregations for. + * @param categorySize The number of categories to retrieve aggregations for. + * @param secureFgpAcc + * @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 getPrimaryCategoryAggregationsByInstitutionId(rawOaInstitutionId: string, yearSize?: number, categorySize?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPrimaryCategoryAggregationsByInstitutionId(rawOaInstitutionId: string, yearSize?: number, categorySize?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPrimaryCategoryAggregationsByInstitutionId(rawOaInstitutionId: string, yearSize?: number, categorySize?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPrimaryCategoryAggregationsByInstitutionId(rawOaInstitutionId: string, yearSize?: number, categorySize?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) { + throw new Error('Required parameter rawOaInstitutionId was null or undefined when calling getPrimaryCategoryAggregationsByInstitutionId.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + yearSize, 'year_size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + categorySize, 'category_size'); + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', '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/v2/works/institution/${this.configuration.encodeParam({name: "rawOaInstitutionId", value: rawOaInstitutionId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/primary-category-aggregations`; + 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 the classifications of a work based on its ID. * @endpoint get /api/v2/works/classification/work/{raw_oa_work_id} @@ -322,65 +458,6 @@ export class WorksV2Service extends BaseService { ); } - /** - * Returns the classifications of an author\'s works based on their ID. - * @endpoint get /api/v2/works/classification/author/{raw_oa_author_id} - * @param rawOaAuthorId The raw OpenAlex author id. - * @param secureFgpAcc - * @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 getWorkClassificationsByAuthorId(rawOaAuthorId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getWorkClassificationsByAuthorId(rawOaAuthorId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getWorkClassificationsByAuthorId(rawOaAuthorId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getWorkClassificationsByAuthorId(rawOaAuthorId: string, secureFgpAcc?: string, 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 getWorkClassificationsByAuthorId.'); - } - - let localVarHeaders = this.defaultHeaders; - - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', '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/v2/works/classification/author/${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, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - /** * Returns the classifications of works based on their IDs. * @endpoint get /api/v2/works/classification/works/search diff --git a/webapp/src/app/api/model/authorPage.ts b/webapp/src/app/api/model/authorPage.ts index 456cadbc..ce0a58ed 100644 --- a/webapp/src/app/api/model/authorPage.ts +++ b/webapp/src/app/api/model/authorPage.ts @@ -10,6 +10,9 @@ import { Author } from './author'; +/** + * A paginated response containing a list of authors. + */ export interface AuthorPage { /** * The elements of the page. diff --git a/webapp/src/app/api/model/dfgInstitutionSummary.ts b/webapp/src/app/api/model/dfgInstitutionSummary.ts index f2134a2f..e3da7abf 100644 --- a/webapp/src/app/api/model/dfgInstitutionSummary.ts +++ b/webapp/src/app/api/model/dfgInstitutionSummary.ts @@ -1,23 +1,25 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + /** * A summary of a DFG institution. */ -export interface DfgInstitutionSummary { - id: number; - institute_name_de?: string | null; - institute_name_en?: string | null; - root_id?: number | null; - root_name_de?: string | null; - root_name_en?: string | null; - address_country_de?: string | null; - address_country_en?: string | null; +export interface DfgInstitutionSummary { + id: number; + institute_name_de?: string | null; + institute_name_en?: string | null; + root_id?: number | null; + root_name_de?: string | null; + root_name_en?: string | null; + address_country_de?: string | null; + address_country_en?: string | null; } + diff --git a/webapp/src/app/api/model/dfgPersonSummary.ts b/webapp/src/app/api/model/dfgPersonSummary.ts index 5c525ca5..ebd441ee 100644 --- a/webapp/src/app/api/model/dfgPersonSummary.ts +++ b/webapp/src/app/api/model/dfgPersonSummary.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,12 +9,14 @@ */ import { DfgInstitutionSummary } from './dfgInstitutionSummary'; -export interface DfgPersonSummary { - person_id: number; - orcid_id?: string | null; - project_ref_id?: number | null; - full_name?: string | null; - role_label_en?: string | null; - role_label_de?: string | null; - institution?: DfgInstitutionSummary | null; + +export interface DfgPersonSummary { + person_id: number; + orcid_id?: string | null; + project_ref_id?: number | null; + full_name?: string | null; + role_label_en?: string | null; + role_label_de?: string | null; + institution?: DfgInstitutionSummary | null; } + diff --git a/webapp/src/app/api/model/dfgProjectSummary.ts b/webapp/src/app/api/model/dfgProjectSummary.ts index cd52e073..f3e80b4a 100644 --- a/webapp/src/app/api/model/dfgProjectSummary.ts +++ b/webapp/src/app/api/model/dfgProjectSummary.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -11,27 +11,29 @@ import { DfgInstitutionSummary } from './dfgInstitutionSummary'; import { DFGProjectFachgebieteInner } from './dFGProjectFachgebieteInner'; import { DfgPersonSummary } from './dfgPersonSummary'; -export interface DfgProjectSummary { - /** - * The unique identifier of the DFG project. - */ - id: string; - link?: string | null; - title?: string | null; - professional_classification?: string | null; - funding_start?: string | null; - funding_end?: string | null; - /** - * Institutions associated with the project. - */ - institutions?: Array; - /** - * The names of the persons involved in the DFG project. - */ - names?: Array; - /** - * The persons involved in the DFG project. - */ - persons?: Array; - subject_classifications?: Array | null; + +export interface DfgProjectSummary { + /** + * The unique identifier of the DFG project. + */ + id: string; + link?: string | null; + title?: string | null; + professional_classification?: string | null; + funding_start?: string | null; + funding_end?: string | null; + /** + * Institutions associated with the project. + */ + institutions?: Array; + /** + * The names of the persons involved in the DFG project. + */ + names?: Array; + /** + * The persons involved in the DFG project. + */ + persons?: Array; + subject_classifications?: Array | null; } + diff --git a/webapp/src/app/api/model/institutionPageV2.ts b/webapp/src/app/api/model/institutionPageV2.ts index 8fe4ca78..15f481f6 100644 --- a/webapp/src/app/api/model/institutionPageV2.ts +++ b/webapp/src/app/api/model/institutionPageV2.ts @@ -10,6 +10,9 @@ import { Institution } from './institution'; +/** + * A paginated response containing a list of institutions. + */ export interface InstitutionPageV2 { /** * The elements of the page. diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index fae1f5af..7be7ffb2 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -154,6 +154,8 @@ export * from './patentsByKeywordsRequest'; export * from './patentsByKeywordsResponse'; export * from './personBio'; export * from './personBookmarkResponse'; +export * from './primaryCategoryYearAggregation'; +export * from './primaryCategoryYearAggregationPage'; export * from './projectType'; export * from './projectsFilteringProperties'; export * from './projectsSortBy'; @@ -204,8 +206,6 @@ export * from './workClassification'; export * from './workClassificationAuthor'; export * from './workClassificationDetails'; export * from './workClassificationInstitution'; -export * from './workClassificationMerge'; -export * from './workClassificationMergePage'; export * from './workClassificationMeta'; export * from './workClassificationPage'; export * from './workClassificationTopic'; diff --git a/webapp/src/app/api/model/primaryCategoryYearAggregation.ts b/webapp/src/app/api/model/primaryCategoryYearAggregation.ts new file mode 100644 index 00000000..bc146f8d --- /dev/null +++ b/webapp/src/app/api/model/primaryCategoryYearAggregation.ts @@ -0,0 +1,22 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface PrimaryCategoryYearAggregation { + /** + * The publication year. + */ + publication_year: number; + /** + * A mapping of primary categories to their counts for the given year. + */ + categories?: { [key: string]: number; }; +} + diff --git a/webapp/src/app/api/model/workClassificationMergePage.ts b/webapp/src/app/api/model/primaryCategoryYearAggregationPage.ts similarity index 71% rename from webapp/src/app/api/model/workClassificationMergePage.ts rename to webapp/src/app/api/model/primaryCategoryYearAggregationPage.ts index b32d7e95..e191b225 100644 --- a/webapp/src/app/api/model/workClassificationMergePage.ts +++ b/webapp/src/app/api/model/primaryCategoryYearAggregationPage.ts @@ -7,14 +7,14 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { WorkClassificationMerge } from './workClassificationMerge'; +import { PrimaryCategoryYearAggregation } from './primaryCategoryYearAggregation'; -export interface WorkClassificationMergePage { +export interface PrimaryCategoryYearAggregationPage { /** * The elements of the page. */ - elements?: Array; + elements?: Array; /** * The page number. (0-based) */ diff --git a/webapp/src/app/api/model/workClassificationMerge.ts b/webapp/src/app/api/model/workClassificationMerge.ts deleted file mode 100644 index e47a5880..00000000 --- a/webapp/src/app/api/model/workClassificationMerge.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ -import { WorkClassification } from './workClassification'; -import { Work } from './work'; - - -export interface WorkClassificationMerge { - /** - * The OpenAlex work object. - */ - work: Work; - classification?: WorkClassification | null; -} - diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 5368cc05..d633eecf 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -39,10 +39,10 @@ import { roleGuard } from './shared/guards/role.guard'; import { UserRole } from './api'; import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver'; import { selectedAuthorsResolver } from './resolvers/selected-authors.resolver'; -import { authorWorkClassificationPageResolver } from './resolvers/author-work-classification-page.resolver'; import { workClassificationResolver } from './resolvers/work-classification.resolver'; import { selectedDfgAuthorsResolver } from './resolvers/selected-dfg-authors.resolver'; import { selectedDfgInstitutionsResolver } from './resolvers/selected-dfg-institutions.resolver'; +import { primaryCategoryYearAggregationPageResolver } from './resolvers/primary-category-year-aggregation-page.resolver'; export const routes: Routes = [ { path: '', @@ -400,8 +400,8 @@ export const routes: Routes = [ selectedTopicsPage: selectedTopicsResolver, selectedInstitutionsPage: selectedInstitutionsResolver, authorWorkPage: workPageResolver, - authorWorkClassificationMergePage: - authorWorkClassificationPageResolver, + primaryCategoryYearAggregationPage: + primaryCategoryYearAggregationPageResolver, }, data: { resolvingFor: RESOLVING_WORK_PAGE_FOR.PERSON, @@ -527,6 +527,8 @@ export const routes: Routes = [ selectedAuthorsPage: selectedAuthorsResolver, selectedTopicsPage: selectedTopicsResolver, institutionWorkPage: workPageResolver, + primaryCategoryYearAggregationPage: + primaryCategoryYearAggregationPageResolver, }, data: { resolvingFor: RESOLVING_WORK_PAGE_FOR.INSTITUTION, diff --git a/webapp/src/app/modules/institution-publications/institution-publications.component.html b/webapp/src/app/modules/institution-publications/institution-publications.component.html index a3c99e51..46d6a00d 100644 --- a/webapp/src/app/modules/institution-publications/institution-publications.component.html +++ b/webapp/src/app/modules/institution-publications/institution-publications.component.html @@ -1,4 +1,35 @@
+
+
Publikationen
+

Übersicht der wissenschaftlichen Veröffentlichungen.

+
+ @if (canViewClassificationChart()) { + + + + Forschungszwecke + + + + + + + Publikationsliste + {{ total() >= 10000 ? 'mehr als' : '' }} + {{ total() }} Publikationen + + + + + } @else { + + } +
+ + - + diff --git a/webapp/src/app/modules/institution-publications/institution-publications.component.scss b/webapp/src/app/modules/institution-publications/institution-publications.component.scss index e1076aec..55442f6c 100644 --- a/webapp/src/app/modules/institution-publications/institution-publications.component.scss +++ b/webapp/src/app/modules/institution-publications/institution-publications.component.scss @@ -4,3 +4,25 @@ gap: 1rem; padding: 2rem; } + +mat-expansion-panel { + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: var(--sg-none); + box-shadow: none; +} + +mat-expansion-panel-header { + padding: 0 16px; + min-height: 48px; +} + +mat-panel-title { + font-size: 16px; + font-weight: 700; +} + +mat-panel-description { + font-size: 14px; + color: var(--sg-text-muted); +} diff --git a/webapp/src/app/modules/institution-publications/institution-publications.component.ts b/webapp/src/app/modules/institution-publications/institution-publications.component.ts index c827389c..ae554f93 100644 --- a/webapp/src/app/modules/institution-publications/institution-publications.component.ts +++ b/webapp/src/app/modules/institution-publications/institution-publications.component.ts @@ -1,8 +1,16 @@ import { Component, computed, input } from '@angular/core'; import { PublicationTableComponent } from '../../shared/ui/publication-table/publication-table.component'; -import { Author, AuthorPage, TopicPageV2, WorkPageV2, WorkTopic } from '../../api'; +import { + AuthorPage, + PrimaryCategoryYearAggregationPage, + TopicPageV2, + WorkPageV2, +} from '../../api'; import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; import { PublicationFilterComponent } from '../../shared/ui/publication-filters/publication-filters.component'; +import { PrimaryCategoryYearAggregationChartComponent } from '../../shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component'; +import { MatExpansionModule } from '@angular/material/expansion'; +import { CommonModule } from '@angular/common'; @Component({ selector: 'app-institution-publications', @@ -10,6 +18,9 @@ import { PublicationFilterComponent } from '../../shared/ui/publication-filters/ PublicationTableComponent, QueryParamPaginatorComponent, PublicationFilterComponent, + PrimaryCategoryYearAggregationChartComponent, + MatExpansionModule, + CommonModule, ], templateUrl: './institution-publications.component.html', styleUrl: './institution-publications.component.scss', @@ -18,6 +29,13 @@ export class InstitutionPublicationsComponent { institutionWorkPage = input.required(); selectedAuthorsPage = input.required(); selectedTopicsPage = input.required(); + primaryCategoryYearAggregationPage = + input.required(); total = computed(() => this.institutionWorkPage().total ?? 0); + + canViewClassificationChart = computed(() => { + const page = this.primaryCategoryYearAggregationPage(); + return (page?.elements?.length ?? 0) > 0; + }); } 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 f601cc07..ff65a8b5 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.html +++ b/webapp/src/app/modules/person-publications/person-publications.component.html @@ -3,75 +3,45 @@
Publikationen

Übersicht der wissenschaftlichen Veröffentlichungen.

- - - - Forschungszwecke - - @if (this.authorWorkClassificationsMerges().length === 0) { -
Keine Publikationen gefunden.
- } @else { -
- } -
- - - - - -
-
- - Im Diagramm sind ausschließlich klassifizierte Publikationen - deiner Institution enthalten. -
-
-
-
+ @if (canViewClassificationChart()) { + + + + Forschungszwecke + + + - - - Publikationsliste - {{ total() }} Publikationen - - -
- - - - - -
-
-
+ + + Publikationsliste + {{ total() >= 10000 ? 'mehr als' : '' }} + {{ total() }} Publikationen + + + +
+ } @else { + + } + + + + + + + + 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 6f690e88..29bd1c0a 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.ts +++ b/webapp/src/app/modules/person-publications/person-publications.component.ts @@ -1,62 +1,27 @@ -import { Component, computed, effect, input } from '@angular/core'; +import { Component, computed, input } from '@angular/core'; import { WorkPageV2, - Author, - WorkTopic, - WorkPrimaryCategory, - WorkClassificationMerge, - WorkClassificationMergePage, InstitutionPageV2, TopicPageV2, + PrimaryCategoryYearAggregationPage, } from '../../api'; -import { NgxEchartsDirective } from 'ngx-echarts'; -import * as echarts from 'echarts/core'; -import { - GridComponent, - LegendComponent, - TitleComponent, -} from 'echarts/components'; -import { CanvasRenderer } from 'echarts/renderers'; -import { GraphChart } from 'echarts/charts'; import { MatExpansionModule } from '@angular/material/expansion'; import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; -import { AppInfoCardComponent } from '../../shared/ui/app-info-card/app-info-card.component'; import { PublicationTableComponent } from '../../shared/ui/publication-table/publication-table.component'; import { PublicationFilterComponent } from '../../shared/ui/publication-filters/publication-filters.component'; -import { transformWorkPrimaryCategory } from '../../shared/pipes/work-primary-category.pipe'; -import { MatIconModule } from '@angular/material/icon'; -import { MatButtonModule } from '@angular/material/button'; -import { MatTooltipModule } from '@angular/material/tooltip'; -echarts.use([ - GridComponent, - CanvasRenderer, - GraphChart, - TitleComponent, - LegendComponent, -]); - -interface YearlyPurposeCounts { - year: number; - basicResearch: number; - appliedResearch: number; - nonResearch: number; - experimentalDevelopment: number; - notClassified: number; -} +import { PrimaryCategoryYearAggregationChartComponent } from '../../shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component'; +import { CommonModule } from '@angular/common'; @Component({ selector: 'app-person-publications', imports: [ - MatIconModule, - MatButtonModule, MatExpansionModule, - MatTooltipModule, - NgxEchartsDirective, - AppInfoCardComponent, PublicationTableComponent, PublicationFilterComponent, QueryParamPaginatorComponent, + PrimaryCategoryYearAggregationChartComponent, + CommonModule, ], templateUrl: './person-publications.component.html', styleUrl: './person-publications.component.scss', @@ -69,218 +34,11 @@ export class PersonPublicationsComponent { selectedInstitutionsPage = input.required(); selectedTopicsPage = input.required(); - authorWorkClassificationMergePage = - input.required(); - authorWorkClassificationsMerges = computed( - () => this.authorWorkClassificationMergePage().elements ?? [], - ); + primaryCategoryYearAggregationPage = + input.required(); - specificWorkPurposesByYear = computed(() => { - const authorWorkClassificationMerges = - this.authorWorkClassificationsMerges(); - return this.getAuthorWorkClassificationByYear( - authorWorkClassificationMerges, - ); + canViewClassificationChart = computed(() => { + const page = this.primaryCategoryYearAggregationPage(); + return (page?.elements?.length ?? 0) > 0; }); - basicResearchAmount = computed(() => { - return this.countPurpose( - this.authorWorkClassificationsMerges(), - WorkPrimaryCategory.BasicResearch, - ); - }); - basicResearchLabel = transformWorkPrimaryCategory( - WorkPrimaryCategory.BasicResearch, - ); - - appliedResearchAmount = computed(() => { - return this.countPurpose( - this.authorWorkClassificationsMerges(), - WorkPrimaryCategory.AppliedResearch, - ); - }); - appliedResearchLabel = transformWorkPrimaryCategory( - WorkPrimaryCategory.AppliedResearch, - ); - - nonResearchAmount = computed(() => { - return this.countPurpose( - this.authorWorkClassificationsMerges(), - WorkPrimaryCategory.NonResearch, - ); - }); - nonResearchLabel = transformWorkPrimaryCategory( - WorkPrimaryCategory.NonResearch, - ); - - experimentalDevelopmentAmount = computed(() => { - return this.countPurpose( - this.authorWorkClassificationsMerges(), - WorkPrimaryCategory.ExperimentalDevelopment, - ); - }); - experimentalDevelopmentLabel = transformWorkPrimaryCategory( - WorkPrimaryCategory.ExperimentalDevelopment, - ); - - notClassifiedAmount = computed(() => { - return this.authorWorkClassificationsMerges().filter( - (workClassification) => - !workClassification.classification?.classification?.primary_category, - ).length; - }); - notClassifiedLabel = transformWorkPrimaryCategory( - WorkPrimaryCategory.NotClassified, - ); - - countPurpose = ( - workClassifications: WorkClassificationMerge[], - primaryCategory: WorkPrimaryCategory, - ) => { - let count = 0; - for (const workClassification of workClassifications) { - if ( - workClassification.classification?.classification?.primary_category == - primaryCategory - ) { - count++; - } - } - return count; - }; - - chartOption!: echarts.EChartsCoreOption; - - constructor() { - effect(() => { - const yearlyCounts = this.buildYearlyCounts( - this.specificWorkPurposesByYear(), - ); - this.chartOption = this.buildChartOption(yearlyCounts); - }); - } - - getAuthorWorkClassificationByYear( - authorWorkClassificationMerges: WorkClassificationMerge[], - ): Record> { - const workClassificationsByYear: Record< - number, - Array - > = {}; - for (const classificationMerge of authorWorkClassificationMerges) { - const year = classificationMerge.work.publication_year; - if (!year) continue; - - if (!workClassificationsByYear[year]) { - workClassificationsByYear[year] = []; - } - - workClassificationsByYear[year].push(classificationMerge); - } - return workClassificationsByYear; - } - - buildYearlyCounts( - workClassificationsByYear: Record>, - ): YearlyPurposeCounts[] { - return Object.entries(workClassificationsByYear) - .map(([year, classificiationMerges]) => { - const counts: YearlyPurposeCounts = { - year: Number(year), - basicResearch: 0, - appliedResearch: 0, - nonResearch: 0, - experimentalDevelopment: 0, - notClassified: 0, - }; - for (const classificationMerge of classificiationMerges) { - const primaryCategory = - classificationMerge.classification?.classification - ?.primary_category; - if (!primaryCategory) { - counts.notClassified++; - continue; - } - - if (primaryCategory == WorkPrimaryCategory.BasicResearch) { - counts.basicResearch++; - } else if (primaryCategory == WorkPrimaryCategory.AppliedResearch) { - counts.appliedResearch++; - } else if (primaryCategory == WorkPrimaryCategory.NonResearch) { - counts.nonResearch++; - } else if ( - primaryCategory == WorkPrimaryCategory.ExperimentalDevelopment - ) { - counts.experimentalDevelopment++; - } - } - return counts; - }) - .sort((a, b) => a.year - b.year); - } - - buildChartOption(data: YearlyPurposeCounts[]): echarts.EChartsCoreOption { - return { - tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, - legend: { - data: [ - this.basicResearchLabel, - this.appliedResearchLabel, - this.nonResearchLabel, - this.experimentalDevelopmentLabel, - this.notClassifiedLabel, - ], - bottom: 0, - itemGap: 40, - }, - grid: { - left: '3%', - right: '4%', - bottom: '10%', - top: '3%', - containLabel: true, - }, - xAxis: { - type: 'category', - data: data.map((d) => d.year.toString()), - }, - yAxis: { type: 'value' }, - series: [ - { - name: this.basicResearchLabel, - type: 'bar', - stack: 'total', - emphasis: { focus: 'series' }, - data: data.map((d) => d.basicResearch), - }, - { - name: this.appliedResearchLabel, - type: 'bar', - stack: 'total', - emphasis: { focus: 'series' }, - data: data.map((d) => d.appliedResearch), - }, - { - name: this.nonResearchLabel, - type: 'bar', - stack: 'total', - emphasis: { focus: 'series' }, - data: data.map((d) => d.nonResearch), - }, - { - name: this.experimentalDevelopmentLabel, - type: 'bar', - stack: 'total', - emphasis: { focus: 'series' }, - data: data.map((d) => d.experimentalDevelopment), - }, - { - name: this.notClassifiedLabel, - type: 'bar', - stack: 'total', - emphasis: { focus: 'series' }, - data: data.map((d) => d.notClassified), - }, - ], - }; - } } diff --git a/webapp/src/app/resolvers/author-work-classification-page.resolver.ts b/webapp/src/app/resolvers/author-work-classification-page.resolver.ts deleted file mode 100644 index 59158b13..00000000 --- a/webapp/src/app/resolvers/author-work-classification-page.resolver.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { ResolveFn } from '@angular/router'; -import { WorkClassificationMergePage, WorksV2Service } from '../api'; -import { inject } from '@angular/core'; - -export const authorWorkClassificationPageResolver: ResolveFn< - WorkClassificationMergePage -> = (route, state) => { - const id = route.parent?.paramMap.get('id') || route.paramMap.get('id'); - if (!id) { - throw new Error( - 'Author ID is required to resolve author work classification page.', - ); - } - - return inject(WorksV2Service).getWorkClassificationsByAuthorId(id); -}; diff --git a/webapp/src/app/resolvers/primary-category-year-aggregation-page.resolver.ts b/webapp/src/app/resolvers/primary-category-year-aggregation-page.resolver.ts new file mode 100644 index 00000000..43ebb91c --- /dev/null +++ b/webapp/src/app/resolvers/primary-category-year-aggregation-page.resolver.ts @@ -0,0 +1,26 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { PrimaryCategoryYearAggregationPage, WorksV2Service } from '../api'; + +export const primaryCategoryYearAggregationPageResolver: ResolveFn< + PrimaryCategoryYearAggregationPage +> = (route, state) => { + const institutionId = route.parent?.paramMap.get('institutionId'); + const authorId = route.parent?.paramMap.get('id'); + console.log(route.parent?.paramMap); + if (!institutionId && !authorId) { + throw new Error('Institution ID or Author ID is required'); + } + + if (institutionId) { + return inject(WorksV2Service).getPrimaryCategoryAggregationsByInstitutionId( + institutionId, + ); + } else if (authorId) { + return inject(WorksV2Service).getPrimaryCategoryAggregationsByAuthorId( + authorId, + ); + } else { + throw new Error('Institution ID or Author ID is required'); + } +}; diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index 6b81fc90..9007b7bd 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -103,6 +103,9 @@ export class CredentialService { public readonly effectiveAccountId = computed( () => this.accessToken()?.effective_account_id ?? '', ); + public readonly effectiveInstitutionId = computed( + () => this.accessToken()?.effective_institution_id ?? '', + ); public readonly isImpersonating = computed( () => this.realAccountId() !== this.effectiveAccountId(), ); diff --git a/webapp/src/app/shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component.html b/webapp/src/app/shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component.html new file mode 100644 index 00000000..bf3c9e7d --- /dev/null +++ b/webapp/src/app/shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component.html @@ -0,0 +1,18 @@ +
+
+
+ @for (cardInput of this.cardInputs(); track $index) { + + } + +
+
diff --git a/webapp/src/app/shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component.scss b/webapp/src/app/shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component.scss new file mode 100644 index 00000000..5c106e61 --- /dev/null +++ b/webapp/src/app/shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component.scss @@ -0,0 +1,7 @@ +.info-cards { + width: 100%; + display: flex; + gap: 1rem; + flex-wrap: wrap; + margin-top: 1rem; +} \ No newline at end of file diff --git a/webapp/src/app/shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component.ts b/webapp/src/app/shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component.ts new file mode 100644 index 00000000..09ad9ccf --- /dev/null +++ b/webapp/src/app/shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component.ts @@ -0,0 +1,184 @@ +import { Component, computed, input } from '@angular/core'; +import { + PrimaryCategoryYearAggregation, + PrimaryCategoryYearAggregationPage, + WorkPrimaryCategory, +} from '../../../api'; +import { transformWorkPrimaryCategory } from '../../pipes/work-primary-category.pipe'; +import { AppInfoCardComponent } from '../app-info-card/app-info-card.component'; +import { EChartsCoreOption } from 'echarts'; +import { NgxEchartsDirective } from 'ngx-echarts'; + +type CardInput = { + value: string; + description: string; + icon: string; +}; + +@Component({ + selector: 'app-primary-category-year-aggregation-chart', + imports: [AppInfoCardComponent, NgxEchartsDirective], + templateUrl: './primary-category-year-aggregation-chart.component.html', + styleUrl: './primary-category-year-aggregation-chart.component.scss', +}) +export class PrimaryCategoryYearAggregationChartComponent { + page = input.required(); + + countPrimaryCategoryForAllYears( + page: PrimaryCategoryYearAggregationPage, + primaryCategory: WorkPrimaryCategory, + ): number { + if (!page?.elements) { + return 0; + } + return page.elements.reduce((acc, element) => { + const count = element.categories?.[primaryCategory] || 0; + return acc + count; + }, 0); + } + + basicResearchCount = computed(() => { + return this.countPrimaryCategoryForAllYears( + this.page(), + WorkPrimaryCategory.BasicResearch, + ); + }); + basicResearchLabel = transformWorkPrimaryCategory( + WorkPrimaryCategory.BasicResearch, + ); + + appliedResearchCount = computed(() => { + return this.countPrimaryCategoryForAllYears( + this.page(), + WorkPrimaryCategory.AppliedResearch, + ); + }); + appliedResearchLabel = transformWorkPrimaryCategory( + WorkPrimaryCategory.AppliedResearch, + ); + + nonResearchCount = computed(() => { + return this.countPrimaryCategoryForAllYears( + this.page(), + WorkPrimaryCategory.NonResearch, + ); + }); + nonResearchLabel = transformWorkPrimaryCategory( + WorkPrimaryCategory.NonResearch, + ); + + experimentalDevelopmentCount = computed(() => { + return this.countPrimaryCategoryForAllYears( + this.page(), + WorkPrimaryCategory.ExperimentalDevelopment, + ); + }); + experimentalDevelopmentLabel = transformWorkPrimaryCategory( + WorkPrimaryCategory.ExperimentalDevelopment, + ); + + totalCount = computed(() => { + return ( + this.basicResearchCount() + + this.appliedResearchCount() + + this.nonResearchCount() + + this.experimentalDevelopmentCount() + ); + }); + + cardInputs = computed(() => { + return [ + { + value: this.basicResearchCount().toString(), + description: this.basicResearchLabel, + icon: 'science', + }, + { + value: this.appliedResearchCount().toString(), + description: this.appliedResearchLabel, + icon: 'biotech', + }, + { + value: this.nonResearchCount().toString(), + description: this.nonResearchLabel, + icon: 'work_outline', + }, + { + value: this.experimentalDevelopmentCount().toString(), + description: this.experimentalDevelopmentLabel, + icon: 'build', + }, + ]; + }); + + chartOption = computed(() => { + return this.buildChartOptions(this.page().elements ?? []); + }); + + buildChartOptions(data: PrimaryCategoryYearAggregation[]): EChartsCoreOption { + return { + tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, + legend: { + data: [ + this.basicResearchLabel, + this.appliedResearchLabel, + this.nonResearchLabel, + this.experimentalDevelopmentLabel, + ], + bottom: 0, + itemGap: 40, + }, + grid: { + left: '3%', + right: '4%', + bottom: '10%', + top: '3%', + containLabel: true, + }, + xAxis: { + type: 'category', + data: data.map((d) => d.publication_year.toString()), + }, + yAxis: { type: 'value' }, + series: [ + { + name: this.basicResearchLabel, + type: 'bar', + stack: 'total', + emphasis: { focus: 'series' }, + data: data.map( + (d) => d.categories?.[WorkPrimaryCategory.BasicResearch] || 0, + ), + }, + { + name: this.appliedResearchLabel, + type: 'bar', + stack: 'total', + emphasis: { focus: 'series' }, + data: data.map( + (d) => d.categories?.[WorkPrimaryCategory.AppliedResearch] || 0, + ), + }, + { + name: this.nonResearchLabel, + type: 'bar', + stack: 'total', + emphasis: { focus: 'series' }, + data: data.map( + (d) => d.categories?.[WorkPrimaryCategory.NonResearch] || 0, + ), + }, + { + name: this.experimentalDevelopmentLabel, + type: 'bar', + stack: 'total', + emphasis: { focus: 'series' }, + data: data.map( + (d) => + d.categories?.[WorkPrimaryCategory.ExperimentalDevelopment] || 0, + ), + }, + ], + }; + } +}