diff --git a/service/src/main/inse/collaboration_network/schemas.py b/service/src/main/inse/collaboration_network/schemas.py index 421c7b4d..b68d3547 100644 --- a/service/src/main/inse/collaboration_network/schemas.py +++ b/service/src/main/inse/collaboration_network/schemas.py @@ -1,5 +1,5 @@ from enum import Enum -from typing import List, Optional +from typing import List, Optional, Set from pydantic import BaseModel, Field @@ -84,38 +84,65 @@ class FilterInformation(BaseModel): ) -class FilterProperties(BaseModel): - start_year: Optional[int] = Field( +class WorksFilterProperties(BaseModel): + start_year: int = Field( + default=0, title="Start Year", description="The start publication year for the works to include in the collaboration network.", ) - end_year: Optional[int] = Field( + end_year: int = Field( + default=9999, title="End Year", description="The end publication year for the works to include in the collaboration network.", ) - allowed_institutions: Optional[List[str]] = Field( - title="Allowed Institutions", - description="The list of raw institution IDs to include in the collaboration network. If not provided, all institutions will be included.", - ) - allowed_topics: Optional[List[str]] = Field( + allowed_topics: List[str] = Field( + default_factory=list, title="Allowed Topics", - description="The list of raw topic IDs to include in the collaboration network. If not provided, all topics will be included.", + description="The list of raw topic IDs to include in the collaboration network. If empty, all topics will be included.", ) - min_collaborators: Optional[int] = Field( - title="Minimum Collaborators", - description="The minimum number of collaborators required for a work to be included in the collaboration network. If not provided, all works will be included regardless of the number of collaborators.", + min_contributors: int = Field( + default=1, + title="Minimum Contributors", + description="The minimum number of contributors required for a work to be included in the collaboration network.", ) - max_collaborators: Optional[int] = Field( - title="Maximum Collaborators", - description="The maximum number of collaborators allowed for a work to be included in the collaboration network. If not provided, all works will be included regardless of the number of collaborators.", + max_contributors: int = Field( + default=100, + title="Maximum Contributors", + description="The maximum number of contributors allowed for a work to be included in the collaboration network.", ) - min_collaborations: Optional[int] = Field( + + +class AuthorsFilterProperties(BaseModel): + allowed_institutions: List[str] = Field( + default_factory=list, + title="Allowed Institutions", + description="The list of raw institution IDs to include in the collaboration network. If empty, all institutions will be included.", + ) + min_collaborations: int = Field( + default=1, title="Minimum Collaborations", - description="The minimum number of collaborations required for a collaboration edge to be included in the collaboration network. If not provided, all collaboration edges will be included regardless of the number of collaborations.", + description="The minimum number of collaborations required for an author to be included in the collaboration network.", ) - max_collaborations: Optional[int] = Field( + max_collaborations: int = Field( + default=1000, title="Maximum Collaborations", - description="The maximum number of collaborations allowed for a collaboration edge to be included in the collaboration network. If not provided, all collaboration edges will be included regardless of the number of collaborations.", + description="The maximum number of collaborations allowed for an author to be included in the collaboration network.", + ) + + +class FilterProperties(BaseModel): + filter_by: str = Field( + default="works", + title="Filter By", + description="The type of filter to apply when generating the collaboration network. Can be either 'works' or 'authors'. If 'works', the filter properties in the 'works_filter_properties' field will be used. If 'authors', the filter properties in the 'authors_filter_properties' field will be used.", + ) + works_filter_properties: Optional[WorksFilterProperties] = Field( + title="Works Filter Properties", + description="The filter properties to apply when filtering works for the collaboration network. This field is only applicable if the 'filter_by' field is set to 'works'.", + ) + authors_filter_properties: Optional[AuthorsFilterProperties] = Field( + title="Authors Filter Properties", + description="The filter properties to apply when filtering authors for the collaboration network. This field is only applicable if the 'filter_by' field is set to 'authors'.", ) @@ -141,6 +168,45 @@ class CollaborationNetworkNode(BaseModel): return hash(self.raw_id) +class WorkNetworkNode(CollaborationNetworkNode): + publication_year: Optional[int] = Field( + title="Publication Year", + description="The publication year of the work represented by this node. This field is only applicable if the category of the node is 'work'.", + ) + work_topics_information: Optional[Set[WorkTopicInformation]] = Field( + title="Work Topics Information", + description="The list of topic information associated with the work represented by this node. This field is only applicable if the category of the node is 'work'.", + ) + + def __eq__(self, value: object) -> bool: + if isinstance(value, WorkNetworkNode): + return self.raw_id == value.raw_id + return False + + def __hash__(self) -> int: + return hash(self.raw_id) + + +class AuthorNetworkNode(CollaborationNetworkNode): + def __eq__(self, value: object) -> bool: + if isinstance(value, AuthorNetworkNode): + return self.raw_id == value.raw_id + return False + + def __hash__(self) -> int: + return hash(self.raw_id) + + +class InstitutionNetworkNode(CollaborationNetworkNode): + def __eq__(self, value: object) -> bool: + if isinstance(value, InstitutionNetworkNode): + return self.raw_id == value.raw_id + return False + + def __hash__(self) -> int: + return hash(self.raw_id) + + class CollaborationNetworkEdge(BaseModel): raw_source_id: str = Field( title="Source Raw ID", @@ -185,13 +251,21 @@ class CollaborationNetwork(BaseModel): title="Raw Person ID", description="The raw person ID of the person whose collaboration network this is.", ) - nodes: List[CollaborationNetworkNode] = Field( - title="Collaboration Network Nodes", - description="The nodes in the collaboration network.", + work_nodes: List[WorkNetworkNode] = Field( + title="Collaboration Network Work Nodes", + description="The work nodes in the collaboration network.", ) - edges: List[CollaborationNetworkEdge] = Field( + author_nodes: List[AuthorNetworkNode] = Field( + title="Collaboration Network Author Nodes", + description="The author nodes in the collaboration network.", + ) + institution_nodes: List[InstitutionNetworkNode] = Field( + title="Collaboration Network Institution Nodes", + description="The institution nodes in the collaboration network.", + ) + collaboration_edges: List[CollaborationNetworkEdge] = Field( title="Collaboration Network Edges", - description="The edges in the collaboration network.", + description="The collaboration edges in the collaboration network. A collaboration edge represents a collaboration between two nodes. A -> W and A -> I", ) filter_information: FilterInformation = Field( title="Filter Information", diff --git a/service/src/main/inse/collaboration_network/service.py b/service/src/main/inse/collaboration_network/service.py index 19c18e45..2f4dedfd 100644 --- a/service/src/main/inse/collaboration_network/service.py +++ b/service/src/main/inse/collaboration_network/service.py @@ -3,14 +3,18 @@ import logging from typing import List, Optional, Set, Tuple from inse.collaboration_network.schemas import ( + AuthorNetworkNode, + AuthorsFilterProperties, CollaborationNetwork, CollaborationNetworkEdge, - CollaborationNetworkNode, CollaborationNetworkNodeType, FilterInformation, FilterProperties, InstitutionInformation, + InstitutionNetworkNode, + WorkNetworkNode, WorkTopicInformation, + WorksFilterProperties, ) from inse.works import logic as work_logic @@ -31,16 +35,19 @@ from inse.models.institution import Institution logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + async def get_collaboration_network( raw_user_id: str, - filter_properties: Optional[FilterProperties] = None, + filter_properties: FilterProperties, ) -> CollaborationNetwork: - """Gets the collaboration network for a given user ID. + """Generates a collaboration network for a given user ID based on the works associated with that user, and applies filtering to the network based on the specified filter properties, which may include criteria such as publication year range, allowed topics, minimum/maximum number of contributors, and minimum/maximum number of collaborations. + The function returns a collaboration network that includes the works, authors, and institutions that are relevant to the specified user and meet the filtering criteria defined in the filter properties. Args: - raw_user_id (str): The raw user ID for whom to get the collaboration network. - filter_properties (Optional[FilterProperties]): The filter properties for the collaboration network. + raw_user_id (str): The raw user ID for whom to generate the collaboration network. + filter_properties (FilterProperties): The filter properties for the collaboration network. Returns: CollaborationNetwork: The collaboration network for the given user. @@ -51,8 +58,476 @@ async def get_collaboration_network( work_page = await work_logic.get_all_author_works(author_id=raw_user_id) works: List[Work] = work_page.results or [] - return build_collaboration_network( - raw_user_id=raw_user_id, works=works, filter_properties=filter_properties + collaboration_network = build_collaboration_network( + raw_user_id=raw_user_id, works=works + ) + if filter_properties.filter_by == "works": + if not filter_properties.works_filter_properties: + filter_properties.works_filter_properties = WorksFilterProperties() + return filter_collaboration_network_by_works( + raw_user_id=raw_user_id, + collaboration_network=collaboration_network, + works_filter_properties=filter_properties.works_filter_properties, + ) + elif filter_properties.filter_by == "authors": + if not filter_properties.authors_filter_properties: + filter_properties.authors_filter_properties = AuthorsFilterProperties() + return filter_collaboration_network_by_authors( + raw_user_id=raw_user_id, + collaboration_network=collaboration_network, + filter_properties=filter_properties.authors_filter_properties, + ) + else: + logger.warning( + f"Invalid filter_by value in filter properties: {filter_properties.filter_by}. Expected 'works' or 'authors'. No additional filtering will be applied." + ) + return collaboration_network + + +def filter_collaboration_network_by_authors( + raw_user_id: str, + collaboration_network: CollaborationNetwork, + filter_properties: AuthorsFilterProperties, +) -> CollaborationNetwork: + """Filters the given collaboration network based on the specified author filter properties, which may include criteria such as allowed institutions and minimum/maximum number of collaborations. + The function returns a new collaboration network that only includes authors that meet the specified criteria, along with their associated works and institutions. + + Args: + raw_user_id (str): The raw user ID for whom to filter the collaboration network. + collaboration_network (CollaborationNetwork): The collaboration network to filter. + filter_properties (AuthorsFilterProperties): The filter properties for the author filtering. + + Returns: + CollaborationNetwork: The filtered collaboration network. + """ + logger.debug( + f"Filtering collaboration network for user {raw_user_id} with author filter properties: {filter_properties}" + ) + + all_author_nodes = set(collaboration_network.author_nodes) + remaining_author_ids = {node.raw_id for node in all_author_nodes} + remaining_institution_nodes = set(collaboration_network.institution_nodes) + + logger.debug(f"Remaining author IDs before filtering: {remaining_author_ids}") + # 1. Filter author nodes based on allowed institutions in filter properties + if len(filter_properties.allowed_institutions) > 0: + logger.debug( + f"Filtering author nodes based on allowed institutions: {filter_properties.allowed_institutions}" + ) + remaining_author_ids = { + edge.raw_source_id + for edge in collaboration_network.collaboration_edges + if edge.raw_target_id in filter_properties.allowed_institutions + } + remaining_institution_nodes = { + node + for node in collaboration_network.institution_nodes + if node.raw_id in filter_properties.allowed_institutions + } + logger.debug( + f"Remaining author IDs after filtering by allowed institutions: {remaining_author_ids}" + ) + + # 2. Filter out collaboration edges that are associated with author nodes that have been filtered out + remaining_work_edges = { + edge + for edge in collaboration_network.collaboration_edges + if edge.raw_source_id in remaining_author_ids + and edge.raw_target_id.lower().startswith("w") + } + logger.debug( + f"Remaining work edges after filtering by allowed institutions: {len(remaining_work_edges)}" + ) + + works_per_author = defaultdict(set) + for edge in remaining_work_edges: + if ( + edge.raw_source_id in remaining_author_ids + and edge.raw_target_id.lower().startswith("w") + ): + works_per_author[edge.raw_source_id].add(edge.raw_target_id) + + logger.debug( + f"Works per author after filtering by allowed institutions: {dict(works_per_author)}" + ) + + # 3. Filter out author that do not have enough collaborations based on the filter properties + remaining_author_ids = { + author_id + for author_id, work_ids in works_per_author.items() + if filter_properties.min_collaborations + <= len(work_ids) + <= filter_properties.max_collaborations + } + remaining_author_ids.add(raw_user_id) # main author always included + remaining_author_nodes = { + node + for node in collaboration_network.author_nodes + if node.raw_id in remaining_author_ids + } + + remaining_institutions_edges = { + edge + for edge in collaboration_network.collaboration_edges + if edge.raw_source_id in remaining_author_ids + and edge.raw_target_id.lower().startswith("i") + } + + # 4. Remove institution nodes that are not connected to any of the remaining author nodes + institution_ids_with_remaining_authors = { + edge.raw_target_id + for edge in remaining_institutions_edges + if edge.raw_source_id in remaining_author_ids + } + remaining_institution_nodes = { + node + for node in remaining_institution_nodes + if node.raw_id in institution_ids_with_remaining_authors + } + + return CollaborationNetwork( + raw_person_id=raw_user_id, + work_nodes=collaboration_network.work_nodes, + author_nodes=list(remaining_author_nodes), + institution_nodes=list(remaining_institution_nodes), + collaboration_edges=list(remaining_work_edges) + + list(remaining_institutions_edges), + filter_information=collaboration_network.filter_information, + ) + + +def filter_collaboration_network_by_works( + raw_user_id: str, + collaboration_network: CollaborationNetwork, + works_filter_properties: WorksFilterProperties, +) -> CollaborationNetwork: + """Filters the given collaboration network based on the specified works filter properties, which may include criteria such as publication year range, allowed topics, and minimum/maximum number of contributors. + The function returns a new collaboration network that only includes works that meet the specified criteria, along with their associated authors and institutions. + + Args: + raw_user_id (str): _description_ + collaboration_network (CollaborationNetwork): _description_ + works_filter_properties (WorksFilterProperties): _description_ + + Returns: + CollaborationNetwork: The filtered collaboration network. + """ + if not works_filter_properties: + return collaboration_network + + all_work_nodes = set(collaboration_network.work_nodes) + valid_work_ids = {node.raw_id for node in all_work_nodes} + + # 1. Filter out works that are not in the specified year range or do not have allowed topics, and update valid_work_ids accordingly + valid_work_ids = filter_works_by_year_and_topic( + works=all_work_nodes, + filter_properties=works_filter_properties, + valid_work_ids=valid_work_ids, + ) + + # 2. Filter out works that do not have enough collaborators based on the filter properties, and update valid_work_ids accordingly + if ( + works_filter_properties.min_contributors + or works_filter_properties.max_contributors + ): + contributors_per_work = defaultdict(set) + for edge in collaboration_network.collaboration_edges: + if ( + edge.raw_target_id.lower().startswith("w") + and edge.raw_target_id in valid_work_ids + ): + contributors_per_work[edge.raw_target_id].add(edge.raw_source_id) + + valid_work_ids = set() + for work_id, contributors in contributors_per_work.items(): + contributors_count = len(contributors) + if has_enough_contributors( + contributors_count=contributors_count, + filter_properties=works_filter_properties, + ): + valid_work_ids.add(work_id) + + # 3. Filter out collaboration edges that are associated with works that have been filtered out + remaining_work_edges = { + edge + for edge in collaboration_network.collaboration_edges + if edge.raw_target_id in valid_work_ids + and edge.raw_target_id.lower().startswith("w") + } + + # 4. Identify author nodes that are still valid based on their association with the remaining valid works + author_ids_with_valid_works = {edge.raw_source_id for edge in remaining_work_edges} + + # 5. Identify institution nodes that are still valid based on their association with the remaining valid author nodes + institution_ids_with_valid_authors = { + edge.raw_target_id + for edge in collaboration_network.collaboration_edges + if edge.raw_source_id in author_ids_with_valid_works + and edge.raw_target_id.lower().startswith("i") + } + + remaining_collaboration_edges = { + edge + for edge in collaboration_network.collaboration_edges + if ( + edge.raw_target_id in valid_work_ids + and edge.raw_target_id.lower().startswith("w") + ) + or ( + edge.raw_source_id in author_ids_with_valid_works + and edge.raw_target_id.lower().startswith("i") + ) + or ( + edge.raw_source_id in author_ids_with_valid_works + and edge.raw_target_id in institution_ids_with_valid_authors + ) + } + remaining_work_nodes = { + node + for node in collaboration_network.work_nodes + if node.raw_id in valid_work_ids + } + remaining_author_nodes = { + node + for node in collaboration_network.author_nodes + if node.raw_id in author_ids_with_valid_works + } + remaining_institution_nodes = { + node + for node in collaboration_network.institution_nodes + if node.raw_id in institution_ids_with_valid_authors + } + + return CollaborationNetwork( + raw_person_id=raw_user_id, + work_nodes=list(remaining_work_nodes), + author_nodes=list(remaining_author_nodes), + institution_nodes=list(remaining_institution_nodes), + collaboration_edges=list(remaining_collaboration_edges), + filter_information=collaboration_network.filter_information, + ) + + +def filter_works_by_year_and_topic( + works: Set[WorkNetworkNode], + filter_properties: WorksFilterProperties, + valid_work_ids: Set[str], +): + """Determines the set of valid work IDs by filtering the given set of works based on the specified year range and allowed topics defined in the filter properties. + + Args: + works (Set[WorkNetworkNode]): The set of works to filter. + filter_properties (WorksFilterProperties): The filter properties containing the year range and allowed topics. + valid_work_ids (Set[str]): The set of valid work IDs to update. + + Returns: + Set[str]: The updated set of valid work IDs. + """ + if not any( + [ + filter_properties.start_year, + filter_properties.end_year, + filter_properties.allowed_topics, + ] + ): + return valid_work_ids + + for work in works: + if not is_in_year_range( + year=work.publication_year or -1, + works_filter_properties=filter_properties, + ) or not has_allowed_topic(work, filter_properties): + valid_work_ids.discard(work.raw_id) + + return valid_work_ids + + +def is_in_year_range(year: int, works_filter_properties: WorksFilterProperties) -> bool: + """Determines whether a given year falls within the specified year range defined in the filter properties. + + Args: + year (int): The year to check. + works_filter_properties (WorksFilterProperties): The filter properties containing the year range. + + Returns: + bool: True if the year falls within the specified range, False otherwise. + """ + # no year extracted, excluding work by default + if year == -1: + return False + + if works_filter_properties.start_year and year < works_filter_properties.start_year: + return False + + if works_filter_properties.end_year and year > works_filter_properties.end_year: + return False + + return True + + +def has_allowed_topic( + work: WorkNetworkNode, filter_properties: WorksFilterProperties +) -> bool: + """Determines whether a given work has at least one topic that is included in the allowed topics specified in the filter properties. + + Args: + work (WorkNetworkNode): The work for which to check the topics. + filter_properties (WorksFilterProperties): The filter properties containing the allowed topics. + + Returns: + bool: True if the work has at least one allowed topic, False otherwise. + """ + if len(filter_properties.allowed_topics) == 0: + return True + return any( + topic.raw_topic_id in filter_properties.allowed_topics + for topic in work.work_topics_information or set() + ) + + +def has_enough_contributors( + contributors_count: int, filter_properties: WorksFilterProperties +) -> bool: + """Determines whether a given number of contributors meets the specified minimum and maximum contributor requirements defined in the filter properties. + + Args: + contributors_count (int): The number of contributors to check. + filter_properties (WorksFilterProperties): The filter properties containing the contributor requirements. + + Returns: + bool: True if the contributor count meets the requirements, False otherwise. + """ + if filter_properties and contributors_count < filter_properties.min_contributors: + return False + if ( + filter_properties.max_contributors + and contributors_count > filter_properties.max_contributors + ): + return False + return True + + +def build_collaboration_network( + raw_user_id: str, + works: List[Work], +) -> CollaborationNetwork: + """Builds a collaboration network for a given user ID based on the provided list of works. + + Args: + raw_user_id (str): The raw ID of the user for whom to build the collaboration network. + works (List[Work]): The list of works for which to build the collaboration network. + + Returns: + CollaborationNetwork: The built collaboration network. + """ + min_possible_year = float("inf") + max_possible_year = float("-inf") + + work_nodes: Set[WorkNetworkNode] = set() + all_author_nodes: Set[AuthorNetworkNode] = set() + all_institution_nodes: Set[InstitutionNetworkNode] = set() + all_collaboration_edges: Set[CollaborationNetworkEdge] = set() + + work_topics_information: Set[WorkTopicInformation] = set() + for work in works: + work_node, author_nodes, institution_nodes, collaboration_edges = process_work( + work=work + ) + if not work_node: + continue + + min_possible_year = min( + min_possible_year, work_node.publication_year or float("inf") + ) + max_possible_year = max( + max_possible_year, work_node.publication_year or float("-inf") + ) + work_topics_information.update(work_node.work_topics_information or set()) + work_nodes.add(work_node) + all_author_nodes.update(author_nodes) + all_institution_nodes.update(institution_nodes) + all_collaboration_edges.update(collaboration_edges) + + return CollaborationNetwork( + raw_person_id=raw_user_id, + work_nodes=list(work_nodes), + author_nodes=list(all_author_nodes), + institution_nodes=list(all_institution_nodes), + collaboration_edges=list(all_collaboration_edges), + filter_information=FilterInformation( + min_possible_year=int(min_possible_year), + max_possible_year=int(max_possible_year), + institutions=sorted( + { + InstitutionInformation( + raw_id=institution.raw_id, display_name=institution.display_name + ) + for institution in all_institution_nodes + }, + key=lambda inst: inst.display_name, + ), + topics=sorted( + work_topics_information, key=lambda topic: topic.display_name + ), + ), + ) + + +def process_work( + work: Work, +) -> Tuple[ + Optional[WorkNetworkNode], + Set[AuthorNetworkNode], + Set[InstitutionNetworkNode], + Set[CollaborationNetworkEdge], +]: + """Processes a given work to extract the associated work node, author nodes, institution nodes, and collaboration edges for the collaboration network. + + Args: + work (Work): The work to process. + + Returns: + Tuple[ Optional[WorkNetworkNode], Set[AuthorNetworkNode], Set[InstitutionNetworkNode], Set[CollaborationNetworkEdge], ]: A tuple containing the associated work node, author nodes, institution nodes, and collaboration edges. + """ + year = get_work_year(work) + topics_information = extract_topics_information(work=work) + + work_node = create_work_node( + work=work, year=year, work_topics_information=topics_information + ) + if not work_node: + return None, set(), set(), set() + + authorships = work.authorships + if not authorships: + return work_node, set(), set(), set() + + author_nodes: Set[AuthorNetworkNode] = set() + institution_nodes: Set[InstitutionNetworkNode] = set() + collaboration_edges: Set[CollaborationNetworkEdge] = set() + + for authorship in authorships: + author_node, institution_nodes, associated_institution_edges = ( + process_authorship(authorship=authorship) + ) + if not author_node: + continue + + work_author_edge = CollaborationNetworkEdge( + raw_source_id=author_node.raw_id, + raw_target_id=work_node.raw_id, + ) + + author_nodes.add(author_node) + collaboration_edges.add(work_author_edge) + institution_nodes.update(institution_nodes) + collaboration_edges.update(associated_institution_edges) + + return ( + work_node, + author_nodes, + institution_nodes, + collaboration_edges, ) @@ -73,236 +548,110 @@ def get_work_year(work: Work) -> int: return -1 -def filter_works( - min_year: Optional[int], - max_year: Optional[int], - works: List[Work], -) -> List[Work]: - """Filters a list of works based on a given year range. +def create_work_node( + work: Work, year: int, work_topics_information: Set[WorkTopicInformation] +) -> Optional[WorkNetworkNode]: + """Creates a collaboration network node representing a work based on the provided work data, publication year, and topic information. Args: - min_year (Optional[int]): The minimum publication year for the works to include. - max_year (Optional[int]): The maximum publication year for the works to include. - works (List[Work]): The list of works to filter. + work (Work): The work from which to create the collaboration network node. + year (int): The publication year of the work. + work_topics_information (Set[WorkTopicInformation]): The topic information of the work. Returns: - List[Work]: A list of works that fall within the specified year range. + Optional[WorkNetworkNode]: The collaboration network node representing the work, or None if the work data is invalid. """ - filtered_works = [] - for work in works: - work_year = get_work_year(work) - if min_year is not None and work_year < min_year: + if not work or not work.id or not work.display_name: + return None + + work_id = extract_raw_work_id(work.id) + display_name = work.display_name + + return WorkNetworkNode( + raw_id=work_id, + display_name=display_name, + category=CollaborationNetworkNodeType.WORK, + publication_year=year, + work_topics_information=work_topics_information, + ) + + +def extract_topics_information(work: Work) -> Set[WorkTopicInformation]: + """Extracts the topic information from a given work and returns it as a set of WorkTopicInformation objects. + + Args: + work (Work): The work from which to extract topic information. + + Returns: + Set[WorkTopicInformation]: A set of WorkTopicInformation objects representing the topics of the work. + """ + topics_information: Set[WorkTopicInformation] = set() + for topic in work.topics or []: + if not topic.id or not topic.display_name: continue - if max_year is not None and work_year > max_year: - continue - filtered_works.append(work) - return filtered_works - - -def get_year_range(works: List[Work]) -> Tuple[int, int]: - """Determines the minimum and maximum publication years from a list of works. - - Args: - works (List[Work]): The list of works from which to determine the year range. - - Returns: - Tuple[int, int]: A tuple containing the minimum and maximum publication years, respectively. - """ - min_year = float("inf") - max_year = float("-inf") - - for work in works: - work_year = get_work_year(work) - if work_year != -1: # Only consider valid years - min_year = min(min_year, work_year) - max_year = max(max_year, work_year) - - return int(min_year), int(max_year) - - -def build_collaboration_network( - raw_user_id: str, - works: List[Work], - filter_properties: Optional[FilterProperties] = None, -) -> CollaborationNetwork: - """Builds a collaboration network for a given user based on their works. - - Args: - raw_user_id (str): The raw user ID for whom the collaboration network is being built. - works (List[Work]): A list of works for which to build the collaboration network. - filter_properties (Optional[FilterProperties]): The filter properties for the collaboration network. - - Returns: - CollaborationNetwork: The built collaboration network. - """ - collaboration_nodes: Set[CollaborationNetworkNode] = set() - collaboration_edges: Set[CollaborationNetworkEdge] = set() - - min_possible_year, max_possible_year = get_year_range(works) - - min_year = ( - filter_properties.start_year - if filter_properties - and filter_properties.start_year is not None - and filter_properties.start_year >= min_possible_year - else min_possible_year - ) - max_year = ( - filter_properties.end_year - if filter_properties - and filter_properties.end_year is not None - and filter_properties.end_year <= max_possible_year - else max_possible_year - ) - - filtered_works = filter_works( - min_year=min_year, - max_year=max_year, - works=works, - ) - - for work in filtered_works: - nodes, edges = process_work(work=work, filter_properties=filter_properties) - - work_year = get_work_year(work) - min_possible_year = min(min_possible_year, work_year) - max_possible_year = max(max_possible_year, work_year) - - collaboration_nodes.update(nodes) - collaboration_edges.update(edges) - - filter_information = FilterInformation( - min_possible_year=int(min_possible_year), - max_possible_year=int(max_possible_year), - institutions=sorted( - extract_institutions(works=works), key=lambda inst: inst.display_name - ), - topics=sorted( - extract_topics(works=works), key=lambda topic: topic.display_name - ), - ) - - collaboration_nodes, collaboration_edges = reduce_collaboration_network( - collaboration_nodes=collaboration_nodes, - collaboration_edges=collaboration_edges, - filter_properties=filter_properties, - ) - - return CollaborationNetwork( - raw_person_id=raw_user_id, - nodes=list(collaboration_nodes), - edges=list(collaboration_edges), - filter_information=filter_information, - ) - - -def reduce_collaboration_network( - collaboration_nodes: Set[CollaborationNetworkNode], - collaboration_edges: Set[CollaborationNetworkEdge], - filter_properties: Optional[FilterProperties], -) -> Tuple[Set[CollaborationNetworkNode], Set[CollaborationNetworkEdge]]: - if not filter_properties or ( - filter_properties.min_collaborations is None - and filter_properties.max_collaborations is None - ): - return collaboration_nodes, collaboration_edges - - collaboration_counts = defaultdict(int) - for collaboration_edge in collaboration_edges: - # only count works as collaborations, not institution affiliations - if collaboration_edge.raw_target_id.lower().startswith("w"): - collaboration_counts[collaboration_edge.raw_source_id] += 1 - - min_collaborations = filter_properties.min_collaborations or 0 - max_collaborations = filter_properties.max_collaborations or float("inf") - valid_node_ids = { - node_id - for node_id, count in collaboration_counts.items() - if min_collaborations <= count <= max_collaborations - } - - collaboration_nodes = { - node - for node in collaboration_nodes - if node.raw_id.startswith("W") - or node.raw_id.startswith("I") - or node.raw_id in valid_node_ids - } - - return collaboration_nodes, {edge for edge in collaboration_edges if edge.raw_source_id in valid_node_ids} - - -def extract_institutions(works: List[Work]) -> Set[InstitutionInformation]: - """Extracts a set of unique institutions from a list of works. - - Args: - works (List[Work]): The list of works from which to extract institutions. - - Returns: - Set[InstitutionInformation]: A set of unique institution information associated with the works. - """ - institutions: Set[InstitutionInformation] = set() - for work in works: - if work.authorships: - for authorship in work.authorships: - if authorship.institutions: - for institution in authorship.institutions: - if not institution.id or not institution.display_name: - continue - institution_id = extract_raw_institution_id(institution.id) - institution_info = InstitutionInformation( - raw_id=institution_id, - display_name=str(institution.display_name), - ) - institutions.add(institution_info) - return institutions - - -def extract_topics(works: List[Work]) -> Set[WorkTopicInformation]: - """Extracts a set of unique topics from a list of works. - - Args: - works (List[Work]): The list of works from which to extract topics. - - Returns: - Set[WorkTopicInformation]: A set of unique topic information associated with the works. - """ - topics: Set[WorkTopicInformation] = set() - for work in works: - if work.topics: - for topic in work.topics: - if not topic.id or not topic.display_name: - continue - topic_info = WorkTopicInformation.from_topic(topic) - topics.add(topic_info) - return topics + raw_topic_id = extract_raw_topic_id(topic.id) + topics_information.add( + WorkTopicInformation( + raw_topic_id=raw_topic_id, display_name=topic.display_name + ) + ) + return topics_information def process_authorship( authorship: Authorship, ) -> Tuple[ - Optional[CollaborationNetworkNode], - Set[CollaborationNetworkNode], + Optional[AuthorNetworkNode], + Set[InstitutionNetworkNode], Set[CollaborationNetworkEdge], ]: - """Processes an authorship to extract the corresponding collaboration network node and associated institutions. + """Processes a given authorship to extract the associated author node, institution nodes, and collaboration edges. Args: - authorship (Authorship): The authorship to process. + authorship (Authorship): The authorship data to process. + Returns: - Tuple[CollaborationNetworkNode, List[CollaborationNetworkNode]]: A tuple containing the collaboration network node and a list of associated institution nodes. + Tuple[ Optional[AuthorNetworkNode], Set[InstitutionNetworkNode], Set[CollaborationNetworkEdge], ]: A tuple containing the associated author node, institution nodes, and collaboration edges. """ author = authorship.author if not author or not author.id or not author.display_name: return None, set(), set() - author_node = get_author_node(author) + author_node = create_author_node(author) if not author_node: return None, set(), set() - institution_nodes = get_institution_nodes(authorship.institutions or []) + institution_nodes: Set[InstitutionNetworkNode] = set() + for institution in authorship.institutions or []: + institution_id = extract_raw_institution_id(institution.id or "") + if not institution_id or not institution.display_name: + continue - associated_institution_edges = { + institution_node = create_institution_node(institution) + if institution_node: + institution_nodes.add(institution_node) + + associated_institution_edges = create_associated_institution_edges( + author_node=author_node, institution_nodes=institution_nodes + ) + + return author_node, institution_nodes, associated_institution_edges + + +def create_associated_institution_edges( + author_node: AuthorNetworkNode, + institution_nodes: Set[InstitutionNetworkNode], +) -> Set[CollaborationNetworkEdge]: + """Creates a set of collaboration network edges representing the associations between an author and their affiliated institutions. + + Args: + author_node (AuthorNetworkNode): The collaboration network node representing the author. + institution_nodes (Set[InstitutionNetworkNode]): A set of collaboration network nodes representing the institutions affiliated with the author. + + Returns: + Set[CollaborationNetworkEdge]: A set of collaboration network edges representing the associations between the author and their affiliated institutions. + """ + return { CollaborationNetworkEdge( raw_source_id=author_node.raw_id, raw_target_id=institution_node.raw_id, @@ -310,90 +659,17 @@ def process_authorship( for institution_node in institution_nodes } - return author_node, institution_nodes, associated_institution_edges - -def get_institution_nodes( - institutions: List[Institution] | List[DehydratedInstitution], -) -> Set[CollaborationNetworkNode]: - """Processes a list of institutions to extract the corresponding collaboration network nodes. - - Args: - institutions (List[Institution]): The list of institutions to process. - - Returns: - Set[CollaborationNetworkNode]: A set of collaboration network nodes corresponding to the institutions. - """ - institution_nodes: Set[CollaborationNetworkNode] = set() - for institution in institutions: - institution_node = get_institution_node(institution) - if institution_node: - institution_nodes.add(institution_node) - return institution_nodes - - -def get_institution_node( - institution: Institution | DehydratedInstitution, -) -> Optional[CollaborationNetworkNode]: - """Processes an institution to extract the corresponding collaboration network node. - - Args: - institution (Institution): The institution to process. - - Returns: - CollaborationNetworkNode: The collaboration network node corresponding to the institution, or None if the institution is invalid. - """ - if not institution or not institution.id or not institution.display_name: - return None - - institution_id = extract_raw_institution_id(institution.id) - display_name = institution.display_name - - return CollaborationNetworkNode( - raw_id=institution_id, - display_name=display_name, - category=CollaborationNetworkNodeType.INSTITUTION, - ) - - -def get_work_node( - work: Work, filter_properties: Optional[FilterProperties] -) -> Optional[CollaborationNetworkNode]: - """Processes a work to extract the corresponding collaboration network node. - - Args: - work (Work): The work to process. - filter_properties (Optional[FilterProperties]): The filter properties containing the list of allowed topics. Defaults to None. - - Returns: - Optional[CollaborationNetworkNode]: The collaboration network node corresponding to the work, or None if the work is invalid. - """ - if not work or not work.id or not work.display_name: - return None - - if not has_allowed_topic(work=work, filter_properties=filter_properties): - return None - - work_id = extract_raw_work_id(work.id) - display_name = work.display_name - - return CollaborationNetworkNode( - raw_id=work_id, - display_name=display_name, - category=CollaborationNetworkNodeType.WORK, - ) - - -def get_author_node( +def create_author_node( author: Author | DehydratedAuthor, -) -> Optional[CollaborationNetworkNode]: - """Processes an author to extract the corresponding collaboration network node. +) -> Optional[AuthorNetworkNode]: + """Creates a collaboration network node representing an author based on the provided author data. Args: - author (Author): The author to process. + author (Author | DehydratedAuthor): The author data from which to create the collaboration network node. Returns: - CollaborationNetworkNode: The collaboration network node corresponding to the author, or None if the author is invalid. + Optional[AuthorNetworkNode]: The collaboration network node representing the author, or None if the author data is invalid. """ if not author or not author.id or not author.display_name: return None @@ -401,150 +677,32 @@ def get_author_node( author_id = extract_raw_author_id(author.id) display_name = author.display_name - return CollaborationNetworkNode( + return AuthorNetworkNode( raw_id=author_id, display_name=display_name, category=CollaborationNetworkNodeType.AUTHOR, ) -def process_work( - work: Work, - filter_properties: Optional[FilterProperties] = None, -) -> Tuple[Set[CollaborationNetworkNode], Set[CollaborationNetworkEdge]]: - """Processes a work to extract the corresponding collaboration network nodes and edges. +def create_institution_node( + institution: Institution | DehydratedInstitution, +) -> Optional[InstitutionNetworkNode]: + """Creates a collaboration network node representing an institution based on the provided institution data. Args: - work (Work): The work to process. + institution (Institution | DehydratedInstitution): The institution data from which to create the collaboration network node. Returns: - Tuple[Set[CollaborationNetworkNode], Set[CollaborationNetworkEdge]]: A tuple containing a set of collaboration network nodes and edges. + Optional[InstitutionNetworkNode]: The collaboration network node representing the institution, or None if the institution data is invalid. """ - work_node = get_work_node(work=work, filter_properties=filter_properties) - if not work_node: - return set(), set() + if not institution or not institution.id or not institution.display_name: + return None - authorships = work.authorships - if not authorships: - return set(), set() + institution_id = extract_raw_institution_id(institution.id) + display_name = institution.display_name - collaboration_nodes: Set[CollaborationNetworkNode] = {work_node} - collaboration_edges: Set[CollaborationNetworkEdge] = set() - - for authorship in authorships: - author_node, institution_nodes, associated_institution_edges = ( - process_authorship(authorship) - ) - if not author_node: - continue - - if not is_member_of_allowed_institution( - institution_nodes=institution_nodes, filter_properties=filter_properties - ): - continue - - work_author_edge = CollaborationNetworkEdge( - raw_source_id=author_node.raw_id, - raw_target_id=work_node.raw_id, - ) - - collaboration_nodes.add(author_node) - collaboration_edges.add(work_author_edge) - collaboration_nodes.update(institution_nodes) - collaboration_edges.update(associated_institution_edges) - - author_nodes = { - node - for node in collaboration_nodes - if node.category == CollaborationNetworkNodeType.AUTHOR - } - - if not has_enough_contributors( - contributors=author_nodes, filter_properties=filter_properties - ): - return set(), set() - - return collaboration_nodes, collaboration_edges - - -def has_enough_contributors( - contributors: Set[CollaborationNetworkNode], - filter_properties: Optional[FilterProperties], -) -> bool: - """Determines whether a work has enough contributors to be included in the collaboration network based on the provided filter properties. - - Args: - contributors (Set[CollaborationNetworkNode]): The set of contributor nodes. - filter_properties (Optional[FilterProperties]): The filter properties containing the minimum and maximum collaborator thresholds. - - Returns: - bool: True if the work has enough contributors to be included in the collaboration network, False otherwise. - """ - if not filter_properties: - return True - - num_contributors = len(contributors) - - if ( - filter_properties.min_collaborators - and num_contributors < filter_properties.min_collaborators - ): - return False - - if ( - filter_properties.max_collaborators - and num_contributors > filter_properties.max_collaborators - ): - return False - - return True - - -def has_allowed_topic( - work: Work, filter_properties: Optional[FilterProperties] -) -> bool: - """Determines whether a work is associated with at least one topic that is in the list of allowed topics specified in the filter properties. - - Args: - work (Work): The work for which to check the topics. - filter_properties (Optional[FilterProperties]): The filter properties containing the list of allowed topics. Defaults to None. - - Returns: - bool: True if at least one of the work's topics is in the list of allowed topics, False otherwise. - """ - if not filter_properties or not filter_properties.allowed_topics: - return True - - if not work.topics: - return False - - for topic in work.topics: - if not topic.id: - continue - topic_id = extract_raw_topic_id(topic.id) - if topic_id in filter_properties.allowed_topics: - return True - return False - - -def is_member_of_allowed_institution( - institution_nodes: Set[CollaborationNetworkNode], - filter_properties: Optional[FilterProperties] = None, -) -> bool: - """Determines whether an author is affiliated with at least one institution that is in the list of allowed institutions specified in the filter properties. - - Args: - institution_nodes (Set[CollaborationNetworkNode]): The set of institution nodes associated with a work. - filter_properties (Optional[FilterProperties], optional): The filter properties containing the list of allowed institutions. Defaults to None. - - Returns: - bool: True if at least one of the institution nodes is in the list of allowed institutions, False otherwise. - """ - - if not filter_properties or not filter_properties.allowed_institutions: - return True - - for institution_node in institution_nodes: - if institution_node.raw_id in filter_properties.allowed_institutions: - return True - return False + return InstitutionNetworkNode( + raw_id=institution_id, + display_name=display_name, + category=CollaborationNetworkNodeType.INSTITUTION, + ) diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index ad171904..4d83fe03 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -34,6 +34,10 @@ class Settings(BaseSettings): "am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==" ) openalex_works_search_timeout_seconds: float = 30.0 + # OpenAlex public API config + openalex_api_base_url: str = "https://api.openalex.org" + openalex_api_key: Optional[str] = None + openalex_api_timeout_seconds: float = 30.0 # LLM config llm_api_url: Optional[str] = None diff --git a/service/src/main/inse/institutions/__init__.py b/service/src/main/inse/institutions/__init__.py new file mode 100644 index 00000000..9be5f207 --- /dev/null +++ b/service/src/main/inse/institutions/__init__.py @@ -0,0 +1 @@ +"""Institution lookup module.""" diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py new file mode 100644 index 00000000..34504553 --- /dev/null +++ b/service/src/main/inse/institutions/logic.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Business logic for OpenAlex institutions. +""" +import logging +from copy import deepcopy +from typing import Any + +import httpx +from fastapi import HTTPException +from pydantic import ValidationError +from starlette.status import HTTP_400_BAD_REQUEST +from starlette.status import HTTP_502_BAD_GATEWAY + +from inse.models.autocomplete_response import AutocompleteResponse +from inse.models.autocomplete_response_meta import AutocompleteResponseMeta +from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner +from inse.models.institutions_list_response import InstitutionsListResponse +from .search_client import OpenAlexInstitutionsClient + +logger = logging.getLogger(__name__) + +_VALID_INSTITUTION_TYPES = { + "education", + "healthcare", + "company", + "archive", + "nonprofit", + "government", + "facility", + "other", +} + + +async def list_institutions( + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + client: OpenAlexInstitutionsClient | None = None, +) -> InstitutionsListResponse: + if sample is not None and (sort or page not in (None, 1)): + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail="sample cannot be combined with sort or page.", + ) + + openalex_client = client or OpenAlexInstitutionsClient() + + try: + data = await openalex_client.list_institutions( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) + except httpx.HTTPStatusError as exc: + status_code = exc.response.status_code + detail = "OpenAlex institutions request failed." + try: + error_body = exc.response.json() + detail = error_body.get("message") or error_body.get("error") or detail + except ValueError: + if exc.response.text: + detail = exc.response.text + raise HTTPException(status_code=status_code, detail=detail) from exc + except httpx.HTTPError as exc: + logger.exception("OpenAlex institutions request failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex institutions request failed.", + ) from exc + + try: + normalized_data = _normalize_institutions_response(data) + return InstitutionsListResponse.from_dict(normalized_data) or InstitutionsListResponse() + except ValidationError as exc: + logger.exception("OpenAlex institutions response could not be parsed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex institutions response could not be parsed.", + ) from exc + + +async def autocomplete_institutions( + *, + query: str, + country_code: str | None = None, + institution_type: str | None = None, + limit: int = 10, + client: OpenAlexInstitutionsClient | None = None, +) -> AutocompleteResponse: + filters = [] + if country_code: + filters.append(f"country_code:{country_code}") + if institution_type: + filters.append(f"type:{institution_type}") + + response = await list_institutions( + search=query, + filter=",".join(filters) if filters else None, + sort="works_count:desc", + per_page=limit, + page=1, + select=( + "id,ror,display_name,country_code,type,works_count," + "cited_by_count,geo" + ), + client=client, + ) + + results = [] + for institution in response.results or []: + if not institution.id or not institution.display_name: + continue + + hint_parts = [] + if institution.geo: + if institution.geo.city: + hint_parts.append(institution.geo.city) + if institution.geo.country: + hint_parts.append(institution.geo.country) + elif institution.country_code: + hint_parts.append(institution.country_code) + if institution.type: + hint_parts.append(institution.type) + + results.append( + AutocompleteResponseResultsInner( + id=institution.id, + display_name=institution.display_name, + hint=" · ".join(hint_parts) if hint_parts else None, + cited_by_count=institution.cited_by_count, + works_count=institution.works_count, + entity_type="institution", + external_id=institution.ror, + ) + ) + + return AutocompleteResponse( + meta=AutocompleteResponseMeta( + count=response.meta.count if response.meta else len(results), + db_response_time_ms=( + response.meta.db_response_time_ms if response.meta else None + ), + ), + results=results, + ) + + +def _normalize_institutions_response(data: dict[str, Any]) -> dict[str, Any]: + normalized = deepcopy(data) + + meta = normalized.get("meta") + if isinstance(meta, dict): + for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]: + meta[field] = _int_or_none(meta.get(field)) + meta["next_cursor"] = _str_or_none(meta.get("next_cursor")) + meta["cost_usd"] = _number_or_none(meta.get("cost_usd")) + + for institution in normalized.get("results") or []: + if not isinstance(institution, dict): + continue + + for field in [ + "id", + "ror", + "display_name", + "country_code", + "homepage_url", + "image_url", + "image_thumbnail_url", + "works_api_url", + ]: + institution[field] = _str_or_none(institution.get(field)) + + institution_type = institution.get("type") + if institution_type is not None and institution_type not in _VALID_INSTITUTION_TYPES: + institution["type"] = None + else: + institution["type"] = _str_or_none(institution_type) + + institution["display_name_acronyms"] = _str_list_or_none( + institution.get("display_name_acronyms") + ) + institution["display_name_alternatives"] = _str_list_or_none( + institution.get("display_name_alternatives") + ) + institution["lineage"] = _str_list_or_none(institution.get("lineage")) + institution["works_count"] = _int_or_none(institution.get("works_count")) + institution["cited_by_count"] = _int_or_none(institution.get("cited_by_count")) + institution["created_date"] = _date_str_or_none(institution.get("created_date")) + institution["updated_date"] = _datetime_str_or_none(institution.get("updated_date")) + + summary_stats = institution.get("summary_stats") + if isinstance(summary_stats, dict): + summary_stats["2yr_mean_citedness"] = _number_or_none( + summary_stats.get("2yr_mean_citedness") + ) + summary_stats["h_index"] = _int_or_none(summary_stats.get("h_index")) + summary_stats["i10_index"] = _int_or_none(summary_stats.get("i10_index")) + + geo = institution.get("geo") + if isinstance(geo, dict): + for field in [ + "city", + "geonames_city_id", + "region", + "country_code", + "country", + ]: + geo[field] = _str_or_none(geo.get(field)) + geo["latitude"] = _number_or_none(geo.get("latitude")) + geo["longitude"] = _number_or_none(geo.get("longitude")) + + ids = institution.get("ids") + if isinstance(ids, dict): + for field in ["openalex", "ror", "grid", "wikipedia", "wikidata"]: + ids[field] = _str_or_none(ids.get(field)) + ids["mag"] = _int_or_none(ids.get("mag")) + + for counts_by_year in institution.get("counts_by_year") or []: + if not isinstance(counts_by_year, dict): + continue + for field in ["year", "works_count", "cited_by_count"]: + counts_by_year[field] = _int_or_none(counts_by_year.get(field)) + + for group in normalized.get("group_by") or []: + if not isinstance(group, dict): + continue + + group["key"] = _str_or_none(group.get("key")) + group["key_display_name"] = _str_or_none(group.get("key_display_name")) + group["count"] = _int_or_none(group.get("count")) + + return normalized + + +def _str_or_none(value: Any) -> str | None: + if value is None: + return None + if isinstance(value, bool): + return str(value).lower() + return str(value) + + +def _str_list_or_none(value: Any) -> list[str] | None: + if value is None: + return None + if not isinstance(value, list): + return None + return [_str_or_none(item) for item in value if item is not None] + + +def _int_or_none(value: Any) -> int | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, float): + return int(value) + if isinstance(value, str): + try: + return int(float(value)) + except ValueError: + return None + return None + + +def _number_or_none(value: Any) -> int | float | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, (int, float)): + return value + if isinstance(value, str): + try: + number = float(value) + except ValueError: + return None + return int(number) if number.is_integer() else number + return None + + +def _date_str_or_none(value: Any) -> str | None: + text = _str_or_none(value) + if not text: + return None + return text[:10] + + +def _datetime_str_or_none(value: Any) -> str | None: + text = _str_or_none(value) + if not text: + return None + if len(text) == 10: + return f"{text}T00:00:00Z" + return text diff --git a/service/src/main/inse/institutions/search_client.py b/service/src/main/inse/institutions/search_client.py new file mode 100644 index 00000000..3db5e1dd --- /dev/null +++ b/service/src/main/inse/institutions/search_client.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +HTTP client for OpenAlex institutions. +""" +from typing import Any + +import httpx + +from .. import config + + +class OpenAlexInstitutionsClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + timeout: float | None = None, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/") + self.api_key = api_key if api_key is not None else config.settings.openalex_api_key + self.timeout = timeout if timeout is not None else config.settings.openalex_api_timeout_seconds + self.transport = transport + + def list_institutions_params( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + params: dict[str, Any] = {"per_page": per_page} + + if search: + params["search"] = search + if filter: + params["filter"] = filter + if sort: + params["sort"] = sort + if group_by: + params["group_by"] = group_by + if cursor: + params["cursor"] = cursor + elif page is not None: + params["page"] = page + if sample is not None: + params["sample"] = sample + if select: + params["select"] = select + if self.api_key: + params["api_key"] = self.api_key + + return params + + async def list_institutions( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.get( + "/institutions", + params=self.list_institutions_params( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ), + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/institutions/service.py b/service/src/main/inse/institutions/service.py new file mode 100644 index 00000000..69d6911e --- /dev/null +++ b/service/src/main/inse/institutions/service.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +REST API for OpenAlex institutions. +""" +from typing import Annotated + +from fastapi import APIRouter +from fastapi import Query + +from inse.models.autocomplete_response import AutocompleteResponse +from inse.models.institutions_list_response import InstitutionsListResponse +from inse.tags import Tags +from . import logic + + +router = APIRouter(prefix="/api/institutions", tags=[Tags.INSTITUTIONS]) + + +@router.get( + "/autocomplete", + operation_id="autocompleteInstitutions", + response_model=AutocompleteResponse, + response_model_exclude_none=True, + summary="Returns institution options for autocomplete inputs.", +) +async def autocomplete_institutions( + query: Annotated[ + str, + Query(description="Institution search text, for example 'Duisburg Essen'.", min_length=1), + ], + country_code: Annotated[ + str | None, + Query(alias="countryCode", description="Optional ISO country code filter."), + ] = None, + institution_type: Annotated[ + str | None, + Query(alias="type", description="Optional institution type filter."), + ] = None, + limit: Annotated[ + int, + Query(description="Maximum number of autocomplete options.", ge=1, le=25), + ] = 10, +): + return await logic.autocomplete_institutions( + query=query, + country_code=country_code, + institution_type=institution_type, + limit=limit, + ) + + +@router.get( + "", + operation_id="listInstitutions", + response_model=InstitutionsListResponse, + response_model_exclude_none=True, + summary="Returns a list of OpenAlex institutions.", +) +async def list_institutions( + search: Annotated[ + str | None, + Query(description="Full-text search, for example 'Duisburg Essen'."), + ] = None, + filter: Annotated[ + str | None, + Query(description="OpenAlex filter, for example 'country_code:DE,type:education'."), + ] = None, + sort: Annotated[ + str | None, + Query(description="Sort field, for example 'works_count:desc'."), + ] = "works_count:desc", + group_by: Annotated[ + str | None, + Query(description="OpenAlex group_by field, for example 'country_code'."), + ] = None, + per_page: Annotated[ + int, + Query(description="Results per page.", ge=1, le=100), + ] = 25, + page: Annotated[ + int | None, + Query(description="Page number. Use cursor for deep pagination.", ge=1), + ] = 1, + cursor: Annotated[ + str | None, + Query(description="Cursor pagination token. Use '*' to start."), + ] = None, + sample: Annotated[ + int | None, + Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000), + ] = None, + select: Annotated[ + str | None, + Query(description="Comma-separated fields to return."), + ] = None, +): + return await logic.list_institutions( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py new file mode 100644 index 00000000..e079ff8e --- /dev/null +++ b/service/src/main/inse/institutions/test_logic.py @@ -0,0 +1,236 @@ +import httpx +import pytest +from fastapi import HTTPException + +from inse.institutions import logic +from inse.institutions.search_client import OpenAlexInstitutionsClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@pytest.mark.anyio +async def test_list_institutions_maps_openalex_response_to_model(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/I123", + "ror": "https://ror.org/04mz5ra38", + "display_name": "University of Duisburg-Essen", + "country_code": "DE", + "type": "education", + "homepage_url": "https://www.uni-due.de", + "image_url": "https://example.org/image.jpg", + "image_thumbnail_url": "https://example.org/thumb.jpg", + "display_name_acronyms": ["UDE"], + "display_name_alternatives": ["Universitaet Duisburg-Essen"], + "works_count": 123, + "cited_by_count": 456, + "summary_stats": { + "2yr_mean_citedness": 1.5, + "h_index": 42, + "i10_index": 99, + }, + "geo": { + "city": "Duisburg", + "geonames_city_id": "2934691", + "region": "North Rhine-Westphalia", + "country_code": "DE", + "country": "Germany", + "latitude": 51.4344, + "longitude": 6.7623, + }, + "lineage": ["https://openalex.org/I123"], + "ids": { + "openalex": "https://openalex.org/I123", + "ror": "https://ror.org/04mz5ra38", + "mag": 123, + "grid": "grid.12345.6", + "wikipedia": "https://en.wikipedia.org/wiki/University_of_Duisburg-Essen", + "wikidata": "https://www.wikidata.org/wiki/Q317070", + }, + "counts_by_year": [ + { + "year": 2024, + "works_count": 12, + "cited_by_count": 34, + } + ], + "works_api_url": "https://api.openalex.org/works?filter=institutions.id:I123", + "created_date": "2023-12-25", + "updated_date": "2023-11-07T05:31:56Z", + } + ], + "group_by": [ + { + "key": "DE", + "key_display_name": "Germany", + "count": 1, + } + ], + }, + ) + + client = OpenAlexInstitutionsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_institutions(search="Duisburg Essen", client=client) + + assert result.meta.count == 1 + institution = result.results[0] + assert institution.display_name == "University of Duisburg-Essen" + assert institution.summary_stats.h_index == 42 + assert institution.geo.country == "Germany" + assert institution.ids.mag == 123 + assert institution.counts_by_year[0].year == 2024 + assert result.group_by[0].key_display_name == "Germany" + + +@pytest.mark.anyio +async def test_list_institutions_rejects_sample_with_sort(): + with pytest.raises(HTTPException) as exc_info: + await logic.list_institutions(sample=10, sort="works_count:desc") + + assert exc_info.value.status_code == 400 + + +@pytest.mark.anyio +async def test_list_institutions_accepts_practical_openalex_type_variants(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": 123, + "ror": 456, + "display_name": "Example Institute", + "country_code": 789, + "type": "unknown-openalex-type", + "display_name_acronyms": ["EI", 123], + "display_name_alternatives": "not-a-list", + "works_count": "12", + "cited_by_count": "34.0", + "summary_stats": { + "2yr_mean_citedness": "1.25", + "h_index": "10.0", + "i10_index": True, + }, + "geo": { + "city": 123, + "geonames_city_id": 12345, + "latitude": "51.4", + "longitude": "6", + }, + "ids": {"openalex": 123, "mag": "123"}, + "counts_by_year": [ + { + "year": "2024", + "works_count": "12.0", + "cited_by_count": False, + } + ], + "created_date": "2023-12-25T10:11:12Z", + "updated_date": "2023-12-25", + } + ], + "group_by": [{"key": True, "count": 1}], + }, + ) + + client = OpenAlexInstitutionsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_institutions(client=client) + + assert result.results[0].id == "123" + assert result.results[0].ror == "456" + assert result.results[0].country_code == "789" + assert result.results[0].type is None + assert result.results[0].display_name_acronyms == ["EI", "123"] + assert result.results[0].display_name_alternatives is None + assert result.results[0].works_count == 12 + assert result.results[0].cited_by_count == 34 + assert result.results[0].summary_stats.var_2yr_mean_citedness == 1.25 + assert result.results[0].summary_stats.h_index == 10 + assert result.results[0].summary_stats.i10_index is None + assert result.results[0].geo.city == "123" + assert result.results[0].geo.geonames_city_id == "12345" + assert result.results[0].geo.latitude == 51.4 + assert result.results[0].geo.longitude == 6 + assert result.results[0].ids.openalex == "123" + assert result.results[0].ids.mag == 123 + assert result.results[0].counts_by_year[0].year == 2024 + assert result.results[0].counts_by_year[0].works_count == 12 + assert result.results[0].counts_by_year[0].cited_by_count is None + assert result.group_by[0].key == "true" + + +@pytest.mark.anyio +async def test_autocomplete_institutions_returns_frontend_options(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.params["search"] == "Duisburg Essen" + assert request.url.params["filter"] == "country_code:DE,type:education" + assert request.url.params["sort"] == "works_count:desc" + assert request.url.params["per_page"] == "5" + assert request.url.params["select"] == ( + "id,ror,display_name,country_code,type,works_count," + "cited_by_count,geo" + ) + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "db_response_time_ms": 12}, + "results": [ + { + "id": "https://openalex.org/I123", + "ror": "https://ror.org/04mz5ra38", + "display_name": "University of Duisburg-Essen", + "country_code": "DE", + "type": "education", + "works_count": 123, + "cited_by_count": 456, + "geo": { + "city": "Duisburg", + "country": "Germany", + }, + } + ], + }, + ) + + client = OpenAlexInstitutionsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.autocomplete_institutions( + query="Duisburg Essen", + country_code="DE", + institution_type="education", + limit=5, + client=client, + ) + + assert result.meta.count == 1 + assert result.meta.db_response_time_ms == 12 + assert len(result.results) == 1 + option = result.results[0] + assert option.id == "https://openalex.org/I123" + assert option.display_name == "University of Duisburg-Essen" + assert option.hint == "Duisburg · Germany · education" + assert option.works_count == 123 + assert option.cited_by_count == 456 + assert option.entity_type == "institution" + assert option.external_id == "https://ror.org/04mz5ra38" diff --git a/service/src/main/inse/institutions/test_search_client.py b/service/src/main/inse/institutions/test_search_client.py new file mode 100644 index 00000000..0051b8cf --- /dev/null +++ b/service/src/main/inse/institutions/test_search_client.py @@ -0,0 +1,77 @@ +import httpx +import pytest + +from inse.institutions.search_client import OpenAlexInstitutionsClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def test_list_institutions_params_include_openalex_query_parameters(): + client = OpenAlexInstitutionsClient(api_key="test-key") + + params = client.list_institutions_params( + search="Duisburg Essen", + filter="country_code:DE,type:education", + sort="works_count:desc", + group_by="country_code", + per_page=10, + page=2, + select="id,display_name", + ) + + assert params == { + "search": "Duisburg Essen", + "filter": "country_code:DE,type:education", + "sort": "works_count:desc", + "group_by": "country_code", + "per_page": 10, + "page": 2, + "select": "id,display_name", + "api_key": "test-key", + } + + +def test_list_institutions_params_prefers_cursor_over_page(): + client = OpenAlexInstitutionsClient(api_key="test-key") + + params = client.list_institutions_params(cursor="*", page=3) + + assert params["cursor"] == "*" + assert "page" not in params + + +@pytest.mark.anyio +async def test_list_institutions_calls_openalex_institutions_endpoint(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.method == "GET" + assert request.url.path == "/institutions" + assert request.url.params["search"] == "Duisburg Essen" + assert request.url.params["api_key"] == "test-key" + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/I123", + "display_name": "University of Duisburg-Essen", + "country_code": "DE", + "type": "education", + } + ], + }, + ) + + client = OpenAlexInstitutionsClient( + base_url="https://api.openalex.org", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await client.list_institutions(search="Duisburg Essen") + + assert result["meta"]["count"] == 1 + assert result["results"][0]["display_name"] == "University of Duisburg-Essen" diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 4e0e62d2..a1e4614e 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -11,6 +11,8 @@ from fastapi import FastAPI from fastapi.responses import RedirectResponse from fastapi.middleware.cors import CORSMiddleware from inse.collaboration_network.router import router as collaboration_network_router +from inse.institutions.service import router as institutions_service_router +from inse.topics.service import router as topics_service_router from inse.works.service import router as works_service_router from inse.persons.service import router as persons_service_router from inse.funders.service import router as funders_service_router @@ -33,6 +35,8 @@ app = FastAPI( servers=settings.servers, ) app.include_router(collaboration_network_router) +app.include_router(institutions_service_router) +app.include_router(topics_service_router) app.include_router(works_service_router) app.include_router(persons_service_router) app.include_router(funders_service_router) diff --git a/service/src/main/inse/models/__init__.py b/service/src/main/inse/models/__init__.py index 046bf20e..90e05096 100644 --- a/service/src/main/inse/models/__init__.py +++ b/service/src/main/inse/models/__init__.py @@ -125,4 +125,4 @@ from inse.models.work_types_list_response import WorkTypesListResponse from inse.models.works_list_response import WorksListResponse from inse.models.work_page import WorkPage - +from inse.models.lsf_person import LsfPerson diff --git a/service/src/main/inse/models/lsf_person.py b/service/src/main/inse/models/lsf_person.py new file mode 100644 index 00000000..2820d56c --- /dev/null +++ b/service/src/main/inse/models/lsf_person.py @@ -0,0 +1,72 @@ +from typing import List, Optional + +from pydantic import BaseModel, Field, StrictStr + + +class Function(BaseModel): + facility: StrictStr = Field(description="The facility of the function.") + function: StrictStr = Field(description="The name of the function.") + + +class LsfPerson(BaseModel): + lsf_id: StrictStr = Field(description="The LSF ID of the person.") + name: StrictStr = Field(description="The name of the person.") + firstname: StrictStr = Field(description="The first name of the person.") + surname: StrictStr = Field(description="The last name of the person.") + title: Optional[StrictStr] = Field( + default=None, description="The title of the person." + ) + location: Optional[StrictStr] = Field( + default=None, description="The location of the person." + ) + room: Optional[StrictStr] = Field( + default=None, description="The room of the person." + ) + telefon: Optional[StrictStr] = Field( + default=None, description="The telephone number of the person." + ) + telefax: Optional[StrictStr] = Field( + default=None, description="The telefax number of the person." + ) + mail: Optional[StrictStr] = Field( + default=None, description="The email address of the person." + ) + website: Optional[StrictStr] = Field( + default=None, description="The website of the person." + ) + affiliation_university: Optional[StrictStr] = Field( + default=None, description="The university affiliation of the person." + ) + affiliation_faculty: Optional[StrictStr] = Field( + default=None, description="The faculty affiliation of the person." + ) + affiliation_institute: Optional[StrictStr] = Field( + default=None, description="The institute affiliation of the person." + ) + affiliation_chair: Optional[StrictStr] = Field( + default=None, description="The chair affiliation of the person." + ) + functions: List[Function] = Field(description="The functions of the person.") + + @classmethod + def from_dict(cls, data: dict) -> "LsfPerson": + functions_data = data.get("functions", []) + functions = [Function(**func) for func in functions_data] + return cls( + lsf_id=data.get("lsf_id", ""), + name=data.get("name", ""), + firstname=data.get("firstname", ""), + surname=data.get("surname", ""), + title=data.get("title"), + location=data.get("location"), + room=data.get("room"), + telefon=data.get("telefon"), + telefax=data.get("telefax"), + mail=data.get("mail"), + website=data.get("website"), + affiliation_university=data.get("affiliation_university"), + affiliation_faculty=data.get("affiliation_faculty"), + affiliation_institute=data.get("affiliation_institute"), + affiliation_chair=data.get("affiliation_chair"), + functions=functions, + ) diff --git a/service/src/main/inse/models/ude_organization.py b/service/src/main/inse/models/ude_organization.py new file mode 100644 index 00000000..33b3ddcb --- /dev/null +++ b/service/src/main/inse/models/ude_organization.py @@ -0,0 +1,105 @@ +from typing import List, Optional, Union + +from pydantic import BaseModel, Field, StrictStr + + +class UdeStaff(BaseModel): + research_interests: Union[List[StrictStr], StrictStr] = Field( + description="Research interests of the staff member" + ) + keywords: List[StrictStr] = Field( + description="Keywords associated with the staff member" + ) + telefon: StrictStr = Field(description="Phone number of the staff member") + name: StrictStr = Field(description="Name of the staff member") + links: List[StrictStr] = Field(description="Links associated with the staff member") + email: StrictStr = Field(description="Email address of the staff member") + + @classmethod + def from_dict(cls, data: dict) -> "UdeStaff": + return cls( + research_interests=data.get("research_interests", ""), + keywords=data.get("keywords", []), + telefon=data.get("telefon", ""), + name=data.get("name", ""), + links=data.get("links", []), + email=data.get("email", ""), + ) + + +class UdeProject(BaseModel): + project_type: StrictStr = Field(description="Type of the project") + names: StrictStr = Field(description="Names associated with the project") + keywords: List[StrictStr] = Field( + description="Keywords associated with the project" + ) + topic: StrictStr = Field(description="Topic of the project") + links: List[StrictStr] = Field(description="Links associated with the project") + title: StrictStr = Field(description="Title of the project") + + @classmethod + def from_dict(cls, data: dict) -> "UdeProject": + return cls( + project_type=data.get("project_type", ""), + names=data.get("names", ""), + keywords=data.get("keywords", []), + topic=data.get("topic", ""), + links=data.get("links", []), + title=data.get("title", ""), + ) + + +class UdeNews(BaseModel): + date: Optional[StrictStr] = Field(description="Date of the news") + keywords: List[StrictStr] = Field(description="Keywords associated with the news") + topic: StrictStr = Field(description="Topic of the news") + links: List[StrictStr] = Field(description="Links associated with the news") + title: StrictStr = Field(description="Title of the news") + + @classmethod + def from_dict(cls, data: dict) -> "UdeNews": + return cls( + date=data.get("date"), + keywords=data.get("keywords", []), + topic=data.get("topic", ""), + links=data.get("links", []), + title=data.get("title", ""), + ) + + +class UdeKeyword(BaseModel): + value: StrictStr = Field(description="Value of the keyword") + score: float = Field(description="Relevance score of the keyword") + + @classmethod + def from_dict(cls, data: dict) -> "UdeKeyword": + return cls( + value=data.get("value", ""), + score=data.get("score", 0.0), + ) + + +class UdeOrganization(BaseModel): + uri: StrictStr = Field(description="URI of the organization") + staff: List[UdeStaff] = Field( + description="List of staff members in the organization" + ) + projects: List[UdeProject] = Field( + description="List of projects associated with the organization" + ) + news: List[UdeNews] = Field( + description="List of news items associated with the organization" + ) + keywords: List[UdeKeyword] = Field( + description="List of keywords associated with the organization" + ) + + @classmethod + def from_dict(cls, data: dict) -> "UdeOrganization": + return cls( + uri=data.get("uri", ""), + staff=[UdeStaff.from_dict(s) for s in data.get("staff", [])], + projects=[UdeProject.from_dict(p) for p in data.get("projects", [])], + news=[UdeNews.from_dict(n) for n in data.get("news", [])], + keywords=[UdeKeyword.from_dict(k) for k in data.get("keywords", [])], + ) diff --git a/service/src/main/inse/persons/model.py b/service/src/main/inse/persons/model.py index 49fc03bc..900d91d5 100644 --- a/service/src/main/inse/persons/model.py +++ b/service/src/main/inse/persons/model.py @@ -13,27 +13,35 @@ from inse.models.authors_list_response import AuthorsListResponse from inse.models.group_by_result import GroupByResult + class CustomAuthor(Author): - relevance_rating: Optional[str] = Field(default=None, description="The relevance suitability rating.") + relevance_rating: Optional[str] = Field( + default=None, description="The relevance suitability rating." + ) + class CustomAuthorsListResponse(AuthorsListResponse): - pass - #meta: Optional[Meta] = None - #results: Optional[List[CustomAuthor]] = None - #group_by: Optional[List[GroupByResult]] = None + placeholder: Optional[CustomAuthor] = Field( + default=None, description="A placeholder field for generation." + ) + # meta: Optional[Meta] = None + # results: Optional[List[CustomAuthor]] = None + # group_by: Optional[List[GroupByResult]] = None class PersonBio(BaseModel): bio: str = Field(description="The generated biography.") - + + class PersonFilters(BaseModel): institution: Optional[str] = None cited_by_count: Optional[int] = None # more filters + class PersonSearchRequest(BaseModel): name: Optional[str] = None filters: PersonFilters = PersonFilters() include: Optional[str] = None limit: Optional[int] = 10 - page_offset: Optional[int] = 0 \ No newline at end of file + page_offset: Optional[int] = 0 diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index 219152ad..21c6b03c 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -4,4 +4,6 @@ from enum import Enum class Tags(Enum): PERSON = "Person" PERSON_NETWORK = "Person Network" - WORKS = "Works" \ No newline at end of file + INSTITUTIONS = "Institutions" + TOPICS = "Topics" + WORKS = "Works" diff --git a/service/src/main/inse/topics/__init__.py b/service/src/main/inse/topics/__init__.py new file mode 100644 index 00000000..6909a227 --- /dev/null +++ b/service/src/main/inse/topics/__init__.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +OpenAlex topics module. +""" diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py new file mode 100644 index 00000000..5d4bdef7 --- /dev/null +++ b/service/src/main/inse/topics/logic.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Business logic for OpenAlex topics. +""" +import logging +from copy import deepcopy +from typing import Any + +import httpx +from fastapi import HTTPException +from pydantic import ValidationError +from starlette.status import HTTP_400_BAD_REQUEST +from starlette.status import HTTP_502_BAD_GATEWAY + +from inse.models.autocomplete_response import AutocompleteResponse +from inse.models.autocomplete_response_meta import AutocompleteResponseMeta +from inse.models.autocomplete_response_results_inner import ( + AutocompleteResponseResultsInner, +) +from inse.models.topics_list_response import TopicsListResponse +from .search_client import OpenAlexTopicsClient + +logger = logging.getLogger(__name__) + + +async def list_topics( + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + client: OpenAlexTopicsClient | None = None, +) -> TopicsListResponse: + if sample is not None and (sort or page not in (None, 1)): + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail="sample cannot be combined with sort or page.", + ) + + openalex_client = client or OpenAlexTopicsClient() + + try: + data = await openalex_client.list_topics( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) + except httpx.HTTPStatusError as exc: + status_code = exc.response.status_code + detail = "OpenAlex topics request failed." + try: + error_body = exc.response.json() + detail = error_body.get("message") or error_body.get("error") or detail + except ValueError: + if exc.response.text: + detail = exc.response.text + raise HTTPException(status_code=status_code, detail=detail) from exc + except httpx.HTTPError as exc: + logger.exception("OpenAlex topics request failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex topics request failed.", + ) from exc + + try: + normalized_data = _normalize_topics_response(data) + return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse() + except ValidationError as exc: + logger.exception("OpenAlex topics response could not be parsed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex topics response could not be parsed.", + ) from exc + + +async def autocomplete_topics( + *, + query: str, + domain_id: str | None = None, + field_id: str | None = None, + subfield_id: str | None = None, + limit: int = 10, + client: OpenAlexTopicsClient | None = None, +) -> AutocompleteResponse: + filters = [] + if domain_id: + filters.append(f"domain.id:{domain_id}") + if field_id: + filters.append(f"field.id:{field_id}") + if subfield_id: + filters.append(f"subfield.id:{subfield_id}") + + response = await list_topics( + search=query, + filter=",".join(filters) if filters else None, + sort="works_count:desc", + per_page=limit, + page=1, + select=( + "id,display_name,description,keywords,subfield,field,domain," + "works_count,cited_by_count,ids" + ), + client=client, + ) + + results = [] + for topic in response.results or []: + if not topic.id or not topic.display_name: + continue + + hint_parts = [] + if topic.var_field and topic.var_field.display_name: + hint_parts.append(topic.var_field.display_name) + if topic.subfield and topic.subfield.display_name: + hint_parts.append(topic.subfield.display_name) + if topic.domain and topic.domain.display_name: + hint_parts.append(topic.domain.display_name) + + results.append( + AutocompleteResponseResultsInner( + id=topic.id, + display_name=topic.display_name, + hint=" · ".join(hint_parts) if hint_parts else topic.description, + cited_by_count=topic.cited_by_count, + works_count=topic.works_count, + entity_type="topic", + external_id=topic.ids.openalex if topic.ids else None, + ) + ) + + return AutocompleteResponse( + meta=AutocompleteResponseMeta( + count=response.meta.count if response.meta else len(results), + db_response_time_ms=( + response.meta.db_response_time_ms if response.meta else None + ), + ), + results=results, + ) + + +def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]: + normalized = deepcopy(data) + + meta = normalized.get("meta") + if isinstance(meta, dict): + for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]: + meta[field] = _int_or_none(meta.get(field)) + meta["next_cursor"] = _str_or_none(meta.get("next_cursor")) + meta["cost_usd"] = _number_or_none(meta.get("cost_usd")) + + for topic in normalized.get("results") or []: + if not isinstance(topic, dict): + continue + + for field in ["id", "display_name", "description", "works_api_url"]: + topic[field] = _str_or_none(topic.get(field)) + topic["keywords"] = _str_list_or_none(topic.get("keywords")) + topic["works_count"] = _int_or_none(topic.get("works_count")) + topic["cited_by_count"] = _int_or_none(topic.get("cited_by_count")) + topic["created_date"] = _date_str_or_none(topic.get("created_date")) + topic["updated_date"] = _datetime_str_or_none(topic.get("updated_date")) + + for relation_field in ["subfield", "field", "domain"]: + relation = topic.get(relation_field) + if not isinstance(relation, dict): + continue + relation["id"] = _str_or_none(relation.get("id")) + relation["display_name"] = _str_or_none(relation.get("display_name")) + + ids = topic.get("ids") + if isinstance(ids, dict): + for field in ["openalex", "wikipedia"]: + ids[field] = _str_or_none(ids.get(field)) + + for group in normalized.get("group_by") or []: + if not isinstance(group, dict): + continue + + group["key"] = _str_or_none(group.get("key")) + group["key_display_name"] = _str_or_none(group.get("key_display_name")) + group["count"] = _int_or_none(group.get("count")) + + return normalized + + +def _str_or_none(value: Any) -> str | None: + if value is None: + return None + if isinstance(value, bool): + return str(value).lower() + return str(value) + + +def _str_list_or_none(value: Any) -> list[str] | None: + if value is None: + return None + if not isinstance(value, list): + return None + return [_str_or_none(item) for item in value if item is not None] + + +def _int_or_none(value: Any) -> int | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, float): + return int(value) + if isinstance(value, str): + try: + return int(float(value)) + except ValueError: + return None + return None + + +def _number_or_none(value: Any) -> int | float | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, (int, float)): + return value + if isinstance(value, str): + try: + number = float(value) + except ValueError: + return None + return int(number) if number.is_integer() else number + return None + + +def _date_str_or_none(value: Any) -> str | None: + text = _str_or_none(value) + if not text: + return None + return text[:10] + + +def _datetime_str_or_none(value: Any) -> str | None: + text = _str_or_none(value) + if not text: + return None + if len(text) == 10: + return f"{text}T00:00:00Z" + return text diff --git a/service/src/main/inse/topics/search_client.py b/service/src/main/inse/topics/search_client.py new file mode 100644 index 00000000..7c70afa0 --- /dev/null +++ b/service/src/main/inse/topics/search_client.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +HTTP client for OpenAlex topics. +""" +from typing import Any + +import httpx + +from .. import config + + +class OpenAlexTopicsClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + timeout: float | None = None, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/") + self.api_key = api_key if api_key is not None else config.settings.openalex_api_key + self.timeout = ( + timeout + if timeout is not None + else config.settings.openalex_api_timeout_seconds + ) + self.transport = transport + + def list_topics_params( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + params: dict[str, Any] = {"per_page": per_page} + + if search: + params["search"] = search + if filter: + params["filter"] = filter + if sort: + params["sort"] = sort + if group_by: + params["group_by"] = group_by + if cursor: + params["cursor"] = cursor + elif page is not None: + params["page"] = page + if sample is not None: + params["sample"] = sample + if select: + params["select"] = select + if self.api_key: + params["api_key"] = self.api_key + + return params + + async def list_topics( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.get( + "/topics", + params=self.list_topics_params( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ), + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/topics/service.py b/service/src/main/inse/topics/service.py new file mode 100644 index 00000000..70252254 --- /dev/null +++ b/service/src/main/inse/topics/service.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +REST API for OpenAlex topics. +""" +from typing import Annotated + +from fastapi import APIRouter +from fastapi import Query + +from inse.models.autocomplete_response import AutocompleteResponse +from inse.models.topics_list_response import TopicsListResponse +from inse.tags import Tags +from . import logic + + +router = APIRouter(prefix="/api/topics", tags=[Tags.TOPICS]) + + +@router.get( + "/autocomplete", + operation_id="autocompleteTopics", + response_model=AutocompleteResponse, + response_model_exclude_none=True, + summary="Returns topic options for autocomplete inputs.", +) +async def autocomplete_topics( + query: Annotated[ + str, + Query(description="Topic search text, for example 'machine learning'.", min_length=1), + ], + domain_id: Annotated[ + str | None, + Query(alias="domainId", description="Optional OpenAlex domain id filter."), + ] = None, + field_id: Annotated[ + str | None, + Query(alias="fieldId", description="Optional OpenAlex field id filter."), + ] = None, + subfield_id: Annotated[ + str | None, + Query(alias="subfieldId", description="Optional OpenAlex subfield id filter."), + ] = None, + limit: Annotated[ + int, + Query(description="Maximum number of autocomplete options.", ge=1, le=25), + ] = 10, +): + return await logic.autocomplete_topics( + query=query, + domain_id=domain_id, + field_id=field_id, + subfield_id=subfield_id, + limit=limit, + ) + + +@router.get( + "", + operation_id="listTopics", + response_model=TopicsListResponse, + response_model_exclude_none=True, + summary="Returns a list of OpenAlex topics.", +) +async def list_topics( + search: Annotated[ + str | None, + Query(description="Full-text search, for example 'machine learning'."), + ] = None, + filter: Annotated[ + str | None, + Query(description="OpenAlex filter, for example 'domain.id:1,works_count:>1000'."), + ] = None, + sort: Annotated[ + str | None, + Query(description="Sort field, for example 'works_count:desc'."), + ] = "works_count:desc", + group_by: Annotated[ + str | None, + Query(description="OpenAlex group_by field, for example 'domain.id'."), + ] = None, + per_page: Annotated[ + int, + Query(description="Results per page.", ge=1, le=100), + ] = 25, + page: Annotated[ + int | None, + Query(description="Page number. Use cursor for deep pagination.", ge=1), + ] = 1, + cursor: Annotated[ + str | None, + Query(description="Cursor pagination token. Use '*' to start."), + ] = None, + sample: Annotated[ + int | None, + Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000), + ] = None, + select: Annotated[ + str | None, + Query(description="Comma-separated fields to return."), + ] = None, +): + return await logic.list_topics( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) diff --git a/service/src/main/inse/topics/test_logic.py b/service/src/main/inse/topics/test_logic.py new file mode 100644 index 00000000..e6f9a3a4 --- /dev/null +++ b/service/src/main/inse/topics/test_logic.py @@ -0,0 +1,195 @@ +import httpx +import pytest +from fastapi import HTTPException + +from inse.topics import logic +from inse.topics.search_client import OpenAlexTopicsClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@pytest.mark.anyio +async def test_list_topics_maps_openalex_response_to_model(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + "description": "Methods that learn from data.", + "keywords": ["machine learning", "classification"], + "subfield": { + "id": "https://openalex.org/subfields/1702", + "display_name": "Artificial Intelligence", + }, + "field": { + "id": "https://openalex.org/fields/17", + "display_name": "Computer Science", + }, + "domain": { + "id": "https://openalex.org/domains/4", + "display_name": "Physical Sciences", + }, + "works_count": 123, + "cited_by_count": 456, + "ids": { + "openalex": "https://openalex.org/T12419", + "wikipedia": "https://en.wikipedia.org/wiki/Machine_learning", + }, + "works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419", + "created_date": "2023-12-25", + "updated_date": "2023-11-07T05:31:56Z", + } + ], + "group_by": [ + { + "key": "https://openalex.org/domains/4", + "key_display_name": "Physical Sciences", + "count": 1, + } + ], + }, + ) + + client = OpenAlexTopicsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_topics(search="machine learning", client=client) + + assert result.meta.count == 1 + topic = result.results[0] + assert topic.display_name == "Machine learning" + assert topic.var_field.display_name == "Computer Science" + assert topic.subfield.display_name == "Artificial Intelligence" + assert topic.domain.display_name == "Physical Sciences" + assert topic.ids.openalex == "https://openalex.org/T12419" + assert result.group_by[0].key_display_name == "Physical Sciences" + + +@pytest.mark.anyio +async def test_list_topics_rejects_sample_with_sort(): + with pytest.raises(HTTPException) as exc_info: + await logic.list_topics(sample=10, sort="works_count:desc") + + assert exc_info.value.status_code == 400 + + +@pytest.mark.anyio +async def test_list_topics_accepts_practical_openalex_type_variants(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": "1", "page": "1", "per_page": "25"}, + "results": [ + { + "id": 123, + "display_name": 456, + "description": True, + "keywords": ["topic", 123], + "subfield": {"id": 1, "display_name": 2}, + "field": {"id": 3, "display_name": 4}, + "domain": {"id": 5, "display_name": 6}, + "works_count": "12.0", + "cited_by_count": False, + "ids": {"openalex": 123, "wikipedia": 456}, + "created_date": "2023-12-25T10:11:12Z", + "updated_date": "2023-12-25", + } + ], + "group_by": [{"key": True, "count": "1"}], + }, + ) + + client = OpenAlexTopicsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_topics(client=client) + + topic = result.results[0] + assert topic.id == "123" + assert topic.display_name == "456" + assert topic.description == "true" + assert topic.keywords == ["topic", "123"] + assert topic.works_count == 12 + assert topic.cited_by_count is None + assert topic.var_field.id == "3" + assert topic.domain.display_name == "6" + assert topic.ids.wikipedia == "456" + assert topic.created_date.isoformat() == "2023-12-25" + assert topic.updated_date.isoformat() == "2023-12-25T00:00:00+00:00" + assert result.group_by[0].key == "true" + + +@pytest.mark.anyio +async def test_autocomplete_topics_returns_frontend_options(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.params["search"] == "machine learning" + assert request.url.params["filter"] == ( + "domain.id:https://openalex.org/domains/4," + "field.id:https://openalex.org/fields/17," + "subfield.id:https://openalex.org/subfields/1702" + ) + assert request.url.params["sort"] == "works_count:desc" + assert request.url.params["per_page"] == "5" + assert request.url.params["select"] == ( + "id,display_name,description,keywords,subfield,field,domain," + "works_count,cited_by_count,ids" + ) + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "db_response_time_ms": 12}, + "results": [ + { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + "description": "Methods that learn from data.", + "field": {"display_name": "Computer Science"}, + "subfield": {"display_name": "Artificial Intelligence"}, + "domain": {"display_name": "Physical Sciences"}, + "works_count": 123, + "cited_by_count": 456, + "ids": {"openalex": "https://openalex.org/T12419"}, + } + ], + }, + ) + + client = OpenAlexTopicsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.autocomplete_topics( + query="machine learning", + domain_id="https://openalex.org/domains/4", + field_id="https://openalex.org/fields/17", + subfield_id="https://openalex.org/subfields/1702", + limit=5, + client=client, + ) + + assert result.meta.count == 1 + assert result.meta.db_response_time_ms == 12 + assert len(result.results) == 1 + option = result.results[0] + assert option.id == "https://openalex.org/T12419" + assert option.display_name == "Machine learning" + assert option.hint == ( + "Computer Science · Artificial Intelligence · Physical Sciences" + ) + assert option.works_count == 123 + assert option.cited_by_count == 456 + assert option.entity_type == "topic" + assert option.external_id == "https://openalex.org/T12419" diff --git a/service/src/main/inse/topics/test_search_client.py b/service/src/main/inse/topics/test_search_client.py new file mode 100644 index 00000000..69c16a82 --- /dev/null +++ b/service/src/main/inse/topics/test_search_client.py @@ -0,0 +1,75 @@ +import httpx +import pytest + +from inse.topics.search_client import OpenAlexTopicsClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def test_list_topics_params_include_openalex_query_parameters(): + client = OpenAlexTopicsClient(api_key="test-key") + + params = client.list_topics_params( + search="machine learning", + filter="domain.id:4,works_count:>1000", + sort="works_count:desc", + group_by="domain.id", + per_page=10, + page=2, + select="id,display_name", + ) + + assert params == { + "search": "machine learning", + "filter": "domain.id:4,works_count:>1000", + "sort": "works_count:desc", + "group_by": "domain.id", + "per_page": 10, + "page": 2, + "select": "id,display_name", + "api_key": "test-key", + } + + +def test_list_topics_params_prefers_cursor_over_page(): + client = OpenAlexTopicsClient(api_key="test-key") + + params = client.list_topics_params(cursor="*", page=3) + + assert params["cursor"] == "*" + assert "page" not in params + + +@pytest.mark.anyio +async def test_list_topics_calls_openalex_topics_endpoint(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.method == "GET" + assert request.url.path == "/topics" + assert request.url.params["search"] == "machine learning" + assert request.url.params["api_key"] == "test-key" + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + } + ], + }, + ) + + client = OpenAlexTopicsClient( + base_url="https://api.openalex.org", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await client.list_topics(search="machine learning") + + assert result["meta"]["count"] == 1 + assert result["results"][0]["display_name"] == "Machine learning" diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 73120011..642f05d0 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -11,6 +11,7 @@ import httpx from fastapi import HTTPException from pydantic import ValidationError from starlette.status import HTTP_502_BAD_GATEWAY +from starlette.status import HTTP_404_NOT_FOUND from starlette.status import HTTP_503_SERVICE_UNAVAILABLE from inse.integrations import elasticsearch @@ -34,6 +35,8 @@ async def get_author_works( publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, client: OpenAlexWorksSearchClient | None = None, ) -> WorkPage: search_client = client or OpenAlexWorksSearchClient() @@ -45,6 +48,8 @@ async def get_author_works( publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ) elements, total = _parse_full_work_search_response(data) @@ -124,7 +129,6 @@ async def get_primary_topic_counts( for item in items ] - def _get_topic_descriptions(topic_ids: List[str]) -> dict[str, str]: if not topic_ids: return {} @@ -151,16 +155,54 @@ def _get_topic_descriptions(topic_ids: List[str]) -> dict[str, str]: return descriptions +def _limit_works_by_complete_years( + work_results: list[Work], + target_publications: int, +) -> list[Work]: + works_by_year: dict[int, list[Work]] = {} + + for work in work_results: + if work.publication_year is None: + continue + + year = work.publication_year + + if year not in works_by_year: + works_by_year[year] = [] + + works_by_year[year].append(work) + + selected_works: list[Work] = [] + + for year in sorted(works_by_year.keys(), reverse=True): + selected_works.extend(works_by_year[year]) + + if len(selected_works) >= target_publications: + break + + return selected_works + + async def get_topics_by_time_by_author( author_id: str, max_topics_per_year: int = 3, + target_publications: int = 300, + include_all: bool = False, client: OpenAlexWorksSearchClient | None = None, ) -> TopicsByTime: works = await get_all_author_works(author_id, client=client) + work_results = works.results or [] + + if not include_all: + work_results = _limit_works_by_complete_years( + work_results, + target_publications=target_publications, + ) + years = {} - for work in works.results or []: + for work in work_results: if work.publication_year is None: continue @@ -252,6 +294,8 @@ async def _search_author_works_data( publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, ) -> dict: try: return await search_client.search_author_works( @@ -261,6 +305,8 @@ async def _search_author_works_data( publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ) except MissingApiKeyError as exc: logger.error("OpenAlex works Elasticsearch API key is not configured.") diff --git a/service/src/main/inse/works/model.py b/service/src/main/inse/works/model.py index db5baf59..8c0a8eee 100644 --- a/service/src/main/inse/works/model.py +++ b/service/src/main/inse/works/model.py @@ -8,333 +8,11 @@ from typing import List from typing import Optional from pydantic import BaseModel -from pydantic import ConfigDict from pydantic import Field from inse.models.work import Work -class OpenAlexModel(BaseModel): - model_config = ConfigDict(extra="allow") - - -class Source(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The source id.") - display_name: Optional[str] = Field( - default=None, description="The source display name." - ) - issn_l: Optional[str] = Field(default=None, description="The linking ISSN.") - issn: Optional[List[str]] = Field( - default=None, description="The ISSNs of the source." - ) - is_oa: Optional[bool] = Field( - default=None, description="Whether the source is open access." - ) - is_in_doaj: Optional[bool] = Field( - default=None, description="Whether the source is in DOAJ." - ) - is_core: Optional[bool] = Field( - default=None, description="Whether the source is a core source." - ) - host_organization: Optional[str] = Field( - default=None, description="The host organization id." - ) - host_organization_name: Optional[str] = Field( - default=None, description="The host organization name." - ) - host_organization_lineage: Optional[List[str]] = Field( - default=None, description="The host organization lineage." - ) - type: Optional[str] = Field(default=None, description="The source type.") - - -class Location(OpenAlexModel): - is_oa: Optional[bool] = Field( - default=None, description="Whether this location is open access." - ) - landing_page_url: Optional[str] = Field( - default=None, description="The landing page URL." - ) - pdf_url: Optional[str] = Field(default=None, description="The PDF URL.") - source: Optional[Source] = Field( - default=None, description="The publication source." - ) - license: Optional[str] = Field(default=None, description="The license label.") - license_id: Optional[str] = Field(default=None, description="The license id.") - is_accepted: Optional[bool] = Field( - default=None, description="Whether this manuscript is accepted." - ) - is_published: Optional[bool] = Field( - default=None, description="Whether this manuscript is published." - ) - - -class OpenAccess(OpenAlexModel): - is_oa: Optional[bool] = Field( - default=None, description="Whether the work is open access." - ) - oa_url: Optional[str] = Field(default=None, description="The open access URL.") - any_repository_has_fulltext: Optional[bool] = Field( - default=None, description="Whether a repository has full text." - ) - - -class Author(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The author id.") - display_name: Optional[str] = Field( - default=None, description="The display name of the author." - ) - orcid: Optional[str] = Field( - default=None, description="The optional ORCID of the author." - ) - - -class Institution(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The institution id.") - display_name: Optional[str] = Field( - default=None, description="The institution display name." - ) - ror: Optional[str] = Field(default=None, description="The ROR id.") - country_code: Optional[str] = Field(default=None, description="The country code.") - type: Optional[str] = Field(default=None, description="The institution type.") - lineage: Optional[List[str]] = Field( - default=None, description="The institution lineage." - ) - - -class Authorship(OpenAlexModel): - author: Optional[Author] = Field(default=None, description="The author.") - institutions: List[Institution] = Field( - default_factory=list, description="The author's institutions." - ) - countries: List[str] = Field( - default_factory=list, description="The author's countries." - ) - is_corresponding: Optional[bool] = Field( - default=None, description="Whether this author is corresponding." - ) - raw_author_name: Optional[str] = Field( - default=None, description="The raw author name." - ) - raw_affiliation_strings: List[str] = Field( - default_factory=list, description="The raw affiliation strings." - ) - - -class WorkIds(OpenAlexModel): - openalex: Optional[str] = Field(default=None, description="The OpenAlex id.") - doi: Optional[str] = Field(default=None, description="The DOI.") - mag: Optional[int] = Field(default=None, description="The MAG id.") - pmid: Optional[str] = Field(default=None, description="The PubMed id.") - pmcid: Optional[str] = Field(default=None, description="The PubMed Central id.") - - -class Biblio(OpenAlexModel): - volume: Optional[str] = Field(default=None, description="The volume.") - issue: Optional[str] = Field(default=None, description="The issue.") - first_page: Optional[str] = Field(default=None, description="The first page.") - last_page: Optional[str] = Field(default=None, description="The last page.") - - -class TopicLevel(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The topic level id.") - display_name: Optional[str] = Field( - default=None, description="The topic level display name." - ) - - -class Topic(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The topic id.") - display_name: Optional[str] = Field( - default=None, description="The topic display name." - ) - score: Optional[float] = Field(default=None, description="The topic score.") - subfield: Optional[TopicLevel] = Field( - default=None, description="The topic subfield." - ) - field: Optional[TopicLevel] = Field(default=None, description="The topic field.") - domain: Optional[TopicLevel] = Field(default=None, description="The topic domain.") - - -class Keyword(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The keyword id.") - display_name: Optional[str] = Field( - default=None, description="The keyword display name." - ) - score: Optional[float] = Field(default=None, description="The keyword score.") - - -class Funder(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The funder id.") - display_name: Optional[str] = Field( - default=None, description="The funder display name." - ) - ror: Optional[str] = Field(default=None, description="The ROR id.") - - -class Award(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The award id.") - display_name: Optional[str] = Field( - default=None, description="The award display name." - ) - funder_award_id: Optional[str] = Field( - default=None, description="The funder award id." - ) - funder_id: Optional[str] = Field(default=None, description="The funder id.") - funder_display_name: Optional[str] = Field( - default=None, description="The funder display name." - ) - doi: Optional[str] = Field(default=None, description="The award DOI.") - - -class CitationNormalizedPercentile(OpenAlexModel): - value: Optional[float] = Field( - default=None, description="The normalized citation percentile." - ) - is_in_top_1_percent: Optional[bool] = Field( - default=None, description="Whether the work is in the top 1 percent." - ) - is_in_top_10_percent: Optional[bool] = Field( - default=None, description="Whether the work is in the top 10 percent." - ) - - -class CitedByPercentileYear(OpenAlexModel): - min: Optional[int] = Field(default=None, description="The minimum percentile year.") - max: Optional[int] = Field(default=None, description="The maximum percentile year.") - - -class CountByYear(OpenAlexModel): - year: Optional[int] = Field(default=None, description="The year.") - cited_by_count: int = Field( - default=0, description="The citation count for the year." - ) - - -class SustainableDevelopmentGoal(OpenAlexModel): - id: Optional[str] = Field( - default=None, description="The sustainable development goal id." - ) - display_name: Optional[str] = Field( - default=None, description="The sustainable development goal display name." - ) - score: Optional[float] = Field( - default=None, description="The sustainable development goal score." - ) - - -class Mesh(OpenAlexModel): - descriptor_ui: Optional[str] = Field(default=None, description="The descriptor UI.") - descriptor_name: Optional[str] = Field( - default=None, description="The descriptor name." - ) - qualifier_ui: Optional[str] = Field(default=None, description="The qualifier UI.") - qualifier_name: Optional[str] = Field( - default=None, description="The qualifier name." - ) - is_major_topic: Optional[bool] = Field( - default=None, description="Whether this is a major topic." - ) - - -class HasContent(OpenAlexModel): - pdf: Optional[bool] = Field(default=None, description="Whether PDF content exists.") - grobid_xml: Optional[bool] = Field( - default=None, description="Whether GROBID XML content exists." - ) - - -# class Work(OpenAlexModel): -# id: str = Field(description="The external id of the work.") -# doi: Optional[str] = Field( -# default=None, description="The optional DOI of the work." -# ) -# title: Optional[str] = Field(default=None, description="The title of the work.") -# display_name: Optional[str] = Field( -# default=None, description="The display name of the work." -# ) -# publication_year: Optional[int] = Field( -# default=None, description="The publication year." -# ) -# publication_date: Optional[str] = Field( -# default=None, description="The publication date." -# ) -# type: Optional[str] = Field(default=None, description="The work type.") -# language: Optional[str] = Field(default=None, description="The work language.") -# cited_by_count: int = Field(default=0, description="The number of citations.") -# is_retracted: Optional[bool] = Field( -# default=None, description="Whether the work is retracted." -# ) -# is_paratext: Optional[bool] = Field( -# default=None, description="Whether the work is paratext." -# ) -# primary_location: Optional[Location] = Field( -# default=None, description="The primary location." -# ) -# locations: List[Location] = Field( -# default_factory=list, description="The work locations." -# ) -# best_oa_location: Optional[Location] = Field( -# default=None, description="The best open access location." -# ) -# open_access: Optional[OpenAccess] = Field( -# default=None, description="Open access information." -# ) -# authorships: List[Authorship] = Field( -# default_factory=list, description="The authorships." -# ) -# ids: Optional[WorkIds] = Field(default=None, description="External ids.") -# biblio: Optional[Biblio] = Field( -# default=None, description="Bibliographic information." -# ) -# abstract_inverted_index: dict[str, List[int]] = Field( -# default_factory=dict, description="The inverted abstract index." -# ) -# referenced_works: List[str] = Field( -# default_factory=list, description="Referenced work ids." -# ) -# referenced_works_count: int = Field( -# default=0, description="The number of referenced works." -# ) -# related_works: List[str] = Field( -# default_factory=list, description="Related work ids." -# ) -# topics: List[Topic] = Field(default_factory=list, description="The topics.") -# primary_topic: Optional[Topic] = Field( -# default=None, description="The primary topic." -# ) -# keywords: List[Keyword] = Field(default_factory=list, description="The keywords.") -# funders: List[Funder] = Field(default_factory=list, description="The funders.") -# awards: List[Award] = Field(default_factory=list, description="The awards.") -# fwci: Optional[float] = Field( -# default=None, description="The field weighted citation impact." -# ) -# citation_normalized_percentile: Optional[CitationNormalizedPercentile] = Field( -# default=None, description="The normalized citation percentile." -# ) -# cited_by_percentile_year: Optional[CitedByPercentileYear] = Field( -# default=None, description="The cited by percentile year." -# ) -# counts_by_year: List[CountByYear] = Field( -# default_factory=list, description="Citation counts by year." -# ) -# sustainable_development_goals: List[SustainableDevelopmentGoal] = Field( -# default_factory=list, description="Sustainable development goals." -# ) -# mesh: List[Mesh] = Field(default_factory=list, description="MeSH terms.") -# indexed_in: List[str] = Field( -# default_factory=list, description="Indexes containing the work." -# ) -# has_content: Optional[HasContent] = Field( -# default=None, description="Available content flags." -# ) -# content_url: Optional[str] = Field(default=None, description="The content URL.") -# created_date: Optional[str] = Field(default=None, description="The creation date.") -# updated_date: Optional[str] = Field( -# default=None, description="The last update timestamp." -# ) - - class WorkSummary(BaseModel): doi: Optional[str] = Field( default=None, description="The optional DOI of the work." diff --git a/service/src/main/inse/works/search_client.py b/service/src/main/inse/works/search_client.py index 8f44a776..36b1b3bb 100644 --- a/service/src/main/inse/works/search_client.py +++ b/service/src/main/inse/works/search_client.py @@ -40,26 +40,52 @@ class OpenAlexWorksSearchClient: publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, ) -> dict[str, Any]: indexed_author_id = f"https://openalex.org/{author_id.strip()}" - filters = self._work_filters(publication_year, work_type, language) + filters = self._work_filters( + publication_year, + work_type, + language, + topic_id, + ) + author_filters: list[dict[str, Any]] = [ + { + "term": { + "authorships.author.id": indexed_author_id, + }, + }, + ] + must_clauses: list[dict[str, Any]] = [ + { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": author_filters, + }, + }, + }, + }, + ] + if institution_id: + must_clauses.append({ + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": institution_id, + }, + }, + }, + }) return { "from": (page - 1) * size, "size": size, "query": { "bool": { - "must": [ - { - "nested": { - "path": "authorships", - "query": { - "term": { - "authorships.author.id": indexed_author_id, - }, - }, - }, - }, - ], + "must": must_clauses, "filter": filters, }, }, @@ -74,6 +100,7 @@ class OpenAlexWorksSearchClient: publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + topic_id: list[str] | None = None, ) -> list[dict[str, Any]]: filters: list[dict[str, Any]] = [] if publication_year: @@ -82,6 +109,21 @@ class OpenAlexWorksSearchClient: filters.append({"terms": {"type": work_type}}) if language: filters.append({"terms": {"language": language}}) + if topic_id: + filters.append({ + "bool": { + "should": [ + { + "nested": { + "path": "topics", + "query": {"terms": {"topics.id": topic_id}}, + }, + }, + {"terms": {"primary_topic.id": topic_id}}, + ], + "minimum_should_match": 1, + }, + }) return filters async def search_author_works( @@ -92,6 +134,8 @@ class OpenAlexWorksSearchClient: publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, ) -> dict[str, Any]: if not self.api_key: raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") @@ -111,8 +155,31 @@ class OpenAlexWorksSearchClient: publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ), ) # logging.debug(f"Response: {response.text}") response.raise_for_status() return response.json() + + async def search_work(self, work_id: str) -> dict[str, Any]: + if not self.api_key: + raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") + + indexed_work_id = f"https://openalex.org/{work_id.strip().split('/')[-1]}" + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.post( + f"/{self.index}/_search", + headers={"Authorization": f"ApiKey {self.api_key}"}, + json={ + "size": 1, + "query": {"term": {"id": indexed_work_id}}, + }, + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/works/service.py b/service/src/main/inse/works/service.py index 127b69a5..8f6c20b6 100644 --- a/service/src/main/inse/works/service.py +++ b/service/src/main/inse/works/service.py @@ -16,6 +16,7 @@ from inse.tags import Tags from .. import security from . import logic from inse.models.work_page import WorkPage +from inse.models.work import Work from inse.models.works_list_response import WorksListResponse from inse.models.topic_count import TopicCount from inse.models.topics_by_time import TopicsByTime @@ -47,6 +48,14 @@ async def get_author_works( language: Annotated[ list[str] | None, Query(description="Filter by language code. Can be repeated.") ] = None, + institution_id: Annotated[ + list[str] | None, + Query(description="Filter by OpenAlex institution id. Can be repeated."), + ] = None, + topic_id: Annotated[ + list[str] | None, + Query(description="Filter by OpenAlex topic id. Can be repeated."), + ] = None, principal: security.Principal = Depends( security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) ), @@ -58,6 +67,8 @@ async def get_author_works( publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ) @@ -90,9 +101,39 @@ async def get_primary_topic_counts( async def get_topics_by_time_by_author( author_id: Annotated[str, Path(description="The author id, for example A5023888391.")], max_topics_per_year: Annotated[int, Query(description="The maximum number of topics per year.", ge=1, le=20)] = 3, + target_publications: Annotated[ + int, + Query( + description="Target number of publications used for the timeline. Complete years are always included.", + ge=1, + ), + ] = 300, + include_all: Annotated[ + bool, + Query(description="If true, all publications are used for the timeline."), + ] = False, principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])), ): return await logic.get_topics_by_time_by_author( author_id, max_topics_per_year=max_topics_per_year, + target_publications=target_publications, + include_all=include_all, ) + + +@router.get( + "/detail/{work_id}", + operation_id="getWork", + response_model=Work, + summary="Returns one publication.", +) +async def get_work( + work_id: Annotated[ + str, Path(description="The OpenAlex work id, for example W2741809807.") + ], + principal: security.Principal = Depends( + security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) + ), +): + return await logic.get_work(work_id) diff --git a/service/src/main/inse/works/test_search_client.py b/service/src/main/inse/works/test_search_client.py index 5a376f26..0bfe1a44 100644 --- a/service/src/main/inse/works/test_search_client.py +++ b/service/src/main/inse/works/test_search_client.py @@ -1,3 +1,5 @@ +import json + import httpx import pytest @@ -19,7 +21,9 @@ def test_author_works_query_searches_authorship_author_id(): assert query["size"] == 25 author_query = query["query"]["bool"]["must"][0]["nested"] assert author_query["path"] == "authorships" - assert author_query["query"]["term"]["authorships.author.id"] == "https://openalex.org/A5023888391" + assert author_query["query"]["bool"]["filter"] == [ + {"term": {"authorships.author.id": "https://openalex.org/A5023888391"}}, + ] assert query["query"]["bool"]["filter"] == [] @@ -33,13 +37,191 @@ def test_author_works_query_adds_publication_filters(): publication_year=[2023, 2024], work_type=["article", "book-chapter"], language=["en", "de"], + institution_id=["https://openalex.org/I123"], + topic_id=["https://openalex.org/T12419"], ) assert query["query"]["bool"]["filter"] == [ {"terms": {"publication_year": [2023, 2024]}}, {"terms": {"type": ["article", "book-chapter"]}}, {"terms": {"language": ["en", "de"]}}, + { + "bool": { + "should": [ + { + "nested": { + "path": "topics", + "query": { + "terms": { + "topics.id": ["https://openalex.org/T12419"], + }, + }, + }, + }, + {"terms": {"primary_topic.id": ["https://openalex.org/T12419"]}}, + ], + "minimum_should_match": 1, + }, + }, ] + assert query["query"]["bool"]["must"] == [ + { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": [ + { + "term": { + "authorships.author.id": "https://openalex.org/A5023888391" + } + }, + ], + }, + }, + }, + }, + { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [ + "https://openalex.org/I123", + ], + }, + }, + }, + }, + ] + + +def test_author_works_query_uses_nested_institution_path(): + client = OpenAlexWorksSearchClient(api_key="test-key") + + query = client.author_works_query( + "A5023888391", + page=1, + size=20, + institution_id=["https://openalex.org/I205640436"], + ) + + assert query["query"]["bool"]["must"][1] == { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [ + "https://openalex.org/I205640436", + ], + }, + }, + }, + } + + +def test_author_works_query_adds_topic_filter(): + client = OpenAlexWorksSearchClient(api_key="test-key") + + query = client.author_works_query( + "A5023888391", + page=1, + size=20, + topic_id=["https://openalex.org/T12419"], + ) + + assert query["query"]["bool"]["filter"] == [ + { + "bool": { + "should": [ + { + "nested": { + "path": "topics", + "query": { + "terms": { + "topics.id": ["https://openalex.org/T12419"], + }, + }, + }, + }, + {"terms": {"primary_topic.id": ["https://openalex.org/T12419"]}}, + ], + "minimum_should_match": 1, + }, + }, + ] + + +@pytest.mark.anyio +async def test_search_author_works_passes_institution_filter_to_query(): + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + assert body["query"]["bool"]["must"][1]["nested"]["path"] == ( + "authorships.institutions" + ) + assert body["query"]["bool"]["must"][1]["nested"]["query"]["terms"] == { + "authorships.institutions.id": ["https://openalex.org/I205640436"], + } + return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) + + client = OpenAlexWorksSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + index="openalex-works", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + await client.search_author_works( + "A5023888391", + page=1, + size=20, + institution_id=["https://openalex.org/I205640436"], + ) + + +@pytest.mark.anyio +async def test_search_author_works_passes_topic_filter_to_query(): + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + assert body["query"]["bool"]["filter"] == [ + { + "bool": { + "should": [ + { + "nested": { + "path": "topics", + "query": { + "terms": { + "topics.id": ["https://openalex.org/T12419"], + }, + }, + }, + }, + { + "terms": { + "primary_topic.id": ["https://openalex.org/T12419"], + }, + }, + ], + "minimum_should_match": 1, + }, + }, + ] + return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) + + client = OpenAlexWorksSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + index="openalex-works", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + await client.search_author_works( + "A5023888391", + page=1, + size=20, + topic_id=["https://openalex.org/T12419"], + ) @pytest.mark.anyio @@ -62,6 +244,26 @@ async def test_search_author_works_calls_elasticsearch_index_with_api_key(): assert result == {"hits": {"total": {"value": 0}, "hits": []}} +@pytest.mark.anyio +async def test_search_work_filters_by_work_id(): + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + assert body == { + "size": 1, + "query": {"term": {"id": "https://openalex.org/W2741809807"}}, + } + return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) + + client = OpenAlexWorksSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + index="openalex-works", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + await client.search_work("W2741809807") + + @pytest.mark.anyio async def test_search_author_works_requires_api_key(): client = OpenAlexWorksSearchClient(api_key="") diff --git a/ude_person.http b/ude_person.http new file mode 100644 index 00000000..0eef0048 --- /dev/null +++ b/ude_person.http @@ -0,0 +1,104 @@ +GET https://inse.nes.uni-due.de/elastic/ude_persons_1.0/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "query": { + "query_string": { + "default_field": "name", + "query": "Tobias Janelt" + } + } + +} + +### + +GET https://inse.nes.uni-due.de/elastic/ude_organization_content_august_2025/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +# { +# "query": {"match": {"staff.name": {"query": "Peter Roch", "operator": "and"}}} +# } + +### + +GET https://project.nes.uni-due.de/elastic/openalex-authors/_search +Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ== +Content-Type: application/json + + +# { +# "query": { +# "query_string": { +# "default_field": "display_name", +# "query": "Tobias Janelt" +# } +# } + +# } + +### + +GET https://project.nes.uni-due.de/elastic/openalex-authors/_search +Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ== +Content-Type: application/json + +{ + "query": { + "bool": { + "must": [ + { + "nested": { + "path": "affiliations", + "query": { + "match_phrase": { + "affiliations.institution.display_name": "University of Duisburg-Essen" + } + } + } + }, + { + "nested": { + "path": "counts_by_year", + "query": { + "range": { + "counts_by_year.year": { + "gte": 2020 + } + } + } + } + } + ], + "must_not": [ + + { + + "nested": { + + "path": "counts_by_year", + + "query": { + + "range": { + + "counts_by_year.year": { + + "lt": 2020 + + } + + } + + } + + } + + } + + ] + } + } +} \ No newline at end of file diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index f03f62ef..9779c964 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -9,6 +9,8 @@ api/inse-account-service.service.ts api/inse-account-service.serviceInterface.ts api/inse-service.service.ts api/inse-service.serviceInterface.ts +api/institutions.service.ts +api/institutions.serviceInterface.ts api/items.service.ts api/items.serviceInterface.ts api/person-network.service.ts @@ -29,18 +31,23 @@ model/auth-scope.ts model/author-affiliations-inner.ts model/author-counts-by-year-inner.ts model/author-ids.ts +model/author-network-node.ts model/author-parsed-longest-name.ts model/author-position-count.ts model/author-summary-stats.ts model/author.ts +model/authors-filter-properties.ts model/authors-list-response.ts model/authorship.ts +model/autocomplete-response-meta.ts +model/autocomplete-response-results-inner.ts +model/autocomplete-response.ts model/award.ts model/collaboration-network-edge.ts model/collaboration-network-node-type.ts -model/collaboration-network-node.ts model/collaboration-network.ts model/cost-usd.ts +model/custom-author.ts model/custom-authors-list-response.ts model/dehydrated-author.ts model/dehydrated-funder.ts @@ -54,11 +61,18 @@ model/fwci.ts model/group-by-result.ts model/http-validation-error.ts model/identity-grant.ts +model/institution-geo.ts +model/institution-ids.ts model/institution-information.ts +model/institution-network-node.ts +model/institution.ts +model/institutions-list-response.ts model/item-create.ts model/item-page.ts model/item.ts +model/latitude.ts model/location.ts +model/longitude.ts model/meta.ts model/model2-yr-mean-citedness.ts model/models.ts @@ -68,8 +82,14 @@ model/publication-ids-by-author-position.ts model/publications-by-author-response.ts model/score.ts model/topic-count.ts +model/topic-domain.ts +model/topic-field.ts +model/topic-ids.ts +model/topic-subfield.ts +model/topic.ts model/topics-by-time.ts model/topics-by-year.ts +model/topics-list-response.ts model/validation-error-loc-inner.ts model/validation-error.ts model/value.ts @@ -81,6 +101,7 @@ model/work-has-content.ts model/work-ids.ts model/work-keyword.ts model/work-mesh-inner.ts +model/work-network-node.ts model/work-page.ts model/work-sustainable-development-goals-inner.ts model/work-topic-domain.ts @@ -89,6 +110,7 @@ model/work-topic-information.ts model/work-topic-subfield.ts model/work-topic.ts model/work.ts +model/works-filter-properties.ts model/works-list-response.ts param.ts provide-api.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index 27d4e254..4227c79f 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -7,6 +7,9 @@ export * from './inse-account-service.serviceInterface'; export * from './inse-service.service'; import { INSEServiceService } from './inse-service.service'; export * from './inse-service.serviceInterface'; +export * from './institutions.service'; +import { InstitutionsService } from './institutions.service'; +export * from './institutions.serviceInterface'; export * from './items.service'; import { ItemsService } from './items.service'; export * from './items.serviceInterface'; @@ -22,4 +25,4 @@ export * from './topics.serviceInterface'; export * from './works.service'; import { WorksService } from './works.service'; export * from './works.serviceInterface'; -export const APIS = [FundingService, INSEAccountServiceService, INSEServiceService, ItemsService, PersonNetworkService, PersonsService, TopicsService, WorksService]; +export const APIS = [FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, ItemsService, PersonNetworkService, PersonsService, TopicsService, WorksService]; diff --git a/webapp/src/app/api/api/iNSEAccountService.service.ts b/webapp/src/app/api/api/iNSEAccountService.service.ts new file mode 100644 index 00000000..7b43eaa5 --- /dev/null +++ b/webapp/src/app/api/api/iNSEAccountService.service.ts @@ -0,0 +1,213 @@ +/** + * 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 { AccessGrant } from '../model/accessGrant'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { IdentityGrant } from '../model/identityGrant'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + + + +@Injectable({ + providedIn: 'root' +}) +export class INSEAccountServiceService extends BaseService { + + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); + } + + /** + * Get Access Grant + * @endpoint post /inse-account/auth/access + * @param secret + * @param account + * @param organization + * @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 getAccessGrantInseAccountAuthAccessPost(secret: string, account: number, organization: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAccessGrantInseAccountAuthAccessPost(secret: string, account: number, organization: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessGrantInseAccountAuthAccessPost(secret: string, account: number, organization: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessGrantInseAccountAuthAccessPost(secret: string, account: number, organization: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (secret === null || secret === undefined) { + throw new Error('Required parameter secret was null or undefined when calling getAccessGrantInseAccountAuthAccessPost.'); + } + if (account === null || account === undefined) { + throw new Error('Required parameter account was null or undefined when calling getAccessGrantInseAccountAuthAccessPost.'); + } + if (organization === null || organization === undefined) { + throw new Error('Required parameter organization was null or undefined when calling getAccessGrantInseAccountAuthAccessPost.'); + } + + 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; + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (secret !== undefined) { + localVarFormParams = localVarFormParams.append('secret', secret) as any || localVarFormParams; + } + if (account !== undefined) { + localVarFormParams = localVarFormParams.append('account', account) as any || localVarFormParams; + } + if (organization !== undefined) { + localVarFormParams = localVarFormParams.append('organization', organization) as any || localVarFormParams; + } + + 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 = `/inse-account/auth/access`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Get Identity Grant + * @endpoint post /inse-account/auth/id + * @param username + * @param password + * @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 getIdentityGrantInseAccountAuthIdPost(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getIdentityGrantInseAccountAuthIdPost(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getIdentityGrantInseAccountAuthIdPost(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getIdentityGrantInseAccountAuthIdPost(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getIdentityGrantInseAccountAuthIdPost.'); + } + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling getIdentityGrantInseAccountAuthIdPost.'); + } + + 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; + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (username !== undefined) { + localVarFormParams = localVarFormParams.append('username', username) as any || localVarFormParams; + } + if (password !== undefined) { + localVarFormParams = localVarFormParams.append('password', password) as any || localVarFormParams; + } + + 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 = `/inse-account/auth/id`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + +} diff --git a/webapp/src/app/api/api/iNSEService.service.ts b/webapp/src/app/api/api/iNSEService.service.ts new file mode 100644 index 00000000..cf95d68e --- /dev/null +++ b/webapp/src/app/api/api/iNSEService.service.ts @@ -0,0 +1,538 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { Item } from '../model/item'; +// @ts-ignore +import { ItemCreate } from '../model/itemCreate'; +// @ts-ignore +import { ItemPage } from '../model/itemPage'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + + + +@Injectable({ + providedIn: 'root' +}) +export class INSEServiceService extends BaseService { + + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); + } + + /** + * Adds a new item. + * @endpoint post /api/inse-service/items + * @param itemCreate + * @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 addItem(itemCreate: ItemCreate, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public addItem(itemCreate: ItemCreate, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public addItem(itemCreate: ItemCreate, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public addItem(itemCreate: ItemCreate, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (itemCreate === null || itemCreate === undefined) { + throw new Error('Required parameter itemCreate was null or undefined when calling addItem.'); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (bearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer '); + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/items`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: itemCreate, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Builds the topic hierarchy cache. + * @endpoint get /api/inse-service/topics/cache + * @param pageSize Page size for each search page. + * @param saveJson Persist cache JSON to data folder. + * @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 buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'page_size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + saveJson, 'save_json'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/cache`; + 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 + } + ); + } + + /** + * Counts topic hierarchy occurrences from cache. + * @endpoint get /api/inse-service/topics/count + * @param topic Topic names (repeat parameter). + * @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 countTopicHierarchy(topic: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public countTopicHierarchy(topic: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (topic === null || topic === undefined) { + throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic'); + }) + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/count`; + 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 + } + ); + } + + /** + * Deletes the item with the id. + * @endpoint delete /api/inse-service/items/{id} + * @param id The item id. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteItem(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public deleteItem(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteItem(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteItem(id: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling deleteItem.'); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (bearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer '); + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('delete', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Returns the item with the id. + * @endpoint get /api/inse-service/items/{id} + * @param id The item id. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getItem(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getItem(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getItem(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getItem(id: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling getItem.'); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (bearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer '); + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", 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 a page of items. + * @endpoint get /api/inse-service/items + * @param pageOffset The page offset. + * @param pageSize The page size. + * @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 getItems(pageOffset?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getItems(pageOffset?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getItems(pageOffset?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getItems(pageOffset?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageOffset, 'pageOffset'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'pageSize'); + + let localVarHeaders = this.defaultHeaders; + + // authentication (bearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer '); + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/items`; + 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 nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). + * @endpoint get /api/inse-service/topics/hierarchy + * @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 getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/hierarchy`; + 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 + } + ); + } + + /** + * Updates the item with the id. + * @endpoint put /api/inse-service/items/{id} + * @param id The item id. + * @param itemCreate + * @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 updateItem(id: number, itemCreate: ItemCreate, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public updateItem(id: number, itemCreate: ItemCreate, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateItem(id: number, itemCreate: ItemCreate, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateItem(id: number, itemCreate: ItemCreate, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling updateItem.'); + } + if (itemCreate === null || itemCreate === undefined) { + throw new Error('Required parameter itemCreate was null or undefined when calling updateItem.'); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (bearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer '); + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('put', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: itemCreate, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + +} diff --git a/webapp/src/app/api/api/institutions.service.ts b/webapp/src/app/api/api/institutions.service.ts new file mode 100644 index 00000000..23739da2 --- /dev/null +++ b/webapp/src/app/api/api/institutions.service.ts @@ -0,0 +1,195 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { AutocompleteResponse } from '../model/autocomplete-response'; +// @ts-ignore +import { HTTPValidationError } from '../model/http-validation-error'; +// @ts-ignore +import { InstitutionsListResponse } from '../model/institutions-list-response'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; +import { + InstitutionsServiceInterface +} from './institutions.serviceInterface'; + + + +@Injectable({ + providedIn: 'root' +}) +export class InstitutionsService extends BaseService implements InstitutionsServiceInterface { + + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); + } + + /** + * Returns institution options for autocomplete inputs. + * @endpoint get /api/institutions/autocomplete + * @param query Institution search text, for example \'Duisburg Essen\'. + * @param countryCode Optional ISO country code filter. + * @param type Optional institution type filter. + * @param limit Maximum number of autocomplete options. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling autocompleteInstitutions.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + countryCode, 'countryCode'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + type, 'type'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/institutions/autocomplete`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Returns a list of OpenAlex institutions. + * @endpoint get /api/institutions + * @param search Full-text search, for example \'Duisburg Essen\'. + * @param filter OpenAlex filter, for example \'country_code:DE,type:education\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'country_code\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + search, 'search'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filter, 'filter'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sort, 'sort'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + groupBy, 'group_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + perPage, 'per_page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + cursor, 'cursor'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sample, 'sample'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + select, 'select'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/institutions`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + +} diff --git a/webapp/src/app/api/api/institutions.serviceInterface.ts b/webapp/src/app/api/api/institutions.serviceInterface.ts new file mode 100644 index 00000000..7dc7be7d --- /dev/null +++ b/webapp/src/app/api/api/institutions.serviceInterface.ts @@ -0,0 +1,54 @@ +/** + * 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 { HttpHeaders } from '@angular/common/http'; + +import { Observable } from 'rxjs'; + +import { AutocompleteResponse } from '../model/models'; +import { HTTPValidationError } from '../model/models'; +import { InstitutionsListResponse } from '../model/models'; + + +import { Configuration } from '../configuration'; + + + +export interface InstitutionsServiceInterface { + defaultHeaders: HttpHeaders; + configuration: Configuration; + + /** + * Returns institution options for autocomplete inputs. + * + * @endpoint get /api/institutions/autocomplete + * @param query Institution search text, for example \'Duisburg Essen\'. + * @param countryCode Optional ISO country code filter. + * @param type Optional institution type filter. + * @param limit Maximum number of autocomplete options. + */ + autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, extraHttpRequestParams?: any): Observable; + + /** + * Returns a list of OpenAlex institutions. + * + * @endpoint get /api/institutions + * @param search Full-text search, for example \'Duisburg Essen\'. + * @param filter OpenAlex filter, for example \'country_code:DE,type:education\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'country_code\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + */ + listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, extraHttpRequestParams?: any): Observable; + +} diff --git a/webapp/src/app/api/api/personNetwork.service.ts b/webapp/src/app/api/api/personNetwork.service.ts new file mode 100644 index 00000000..b1183ff6 --- /dev/null +++ b/webapp/src/app/api/api/personNetwork.service.ts @@ -0,0 +1,109 @@ +/** + * 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 { CollaborationNetwork } from '../model/collaborationNetwork'; +// @ts-ignore +import { FilterProperties } from '../model/filterProperties'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + + + +@Injectable({ + providedIn: 'root' +}) +export class PersonNetworkService extends BaseService { + + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); + } + + /** + * Get a person\'s collaboration network. + * Returns a person\'s collaboration network based on their works and co-authors. + * @endpoint post /api/person/network/{raw_user_id} + * @param rawUserId The raw user ID of the person. + * @param filterProperties + * @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 getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawUserId === null || rawUserId === undefined) { + throw new Error('Required parameter rawUserId was null or undefined when calling getCollaborationNetwork.'); + } + + 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; + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + 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/person/network/${this.configuration.encodeParam({name: "rawUserId", value: rawUserId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: filterProperties, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + +} diff --git a/webapp/src/app/api/api/persons-search.service.ts b/webapp/src/app/api/api/persons-search.service.ts deleted file mode 100644 index a92a1b26..00000000 --- a/webapp/src/app/api/api/persons-search.service.ts +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ -/* tslint:disable:no-unused-variable member-ordering */ - -import { Inject, Injectable, Optional } from '@angular/core'; -import { HttpClient, HttpHeaders, HttpParams, - HttpResponse, HttpEvent, HttpParameterCodec, HttpContext - } from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; - -// @ts-ignore -import { CustomAuthorsListResponse } from '../model/custom-authors-list-response'; -// @ts-ignore -import { HTTPValidationError } from '../model/http-validation-error'; - -// @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; -import { BaseService } from '../api.base.service'; -import { - PersonsSearchServiceInterface -} from './persons-search.serviceInterface'; - - - -@Injectable({ - providedIn: 'root' -}) -export class PersonsSearchService extends BaseService implements PersonsSearchServiceInterface { - - constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { - super(basePath, configuration); - } - - /** - * Searches for persons with advanced filters (Topic & Institution) and pagination. - * @endpoint get /api/inse-service/persons/search-list - * @param query Search query (e.g., Arman AND Arzani) - * @param institutionName Filter by institution name - * @param topic Filter by topic display names - * @param page Page number (1-indexed) - * @param pageSize Results per page - * @param include Comma-separated include tags - * @param strict Strict institution search by target year - * @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 searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - institutionName, 'institutionName'); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'topic'); - }) - } - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - strict, 'strict'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/persons/search-list`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - -} diff --git a/webapp/src/app/api/api/persons-search.serviceInterface.ts b/webapp/src/app/api/api/persons-search.serviceInterface.ts deleted file mode 100644 index 23155580..00000000 --- a/webapp/src/app/api/api/persons-search.serviceInterface.ts +++ /dev/null @@ -1,40 +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 { HttpHeaders } from '@angular/common/http'; - -import { Observable } from 'rxjs'; - -import { CustomAuthorsListResponse } from '../model/custom-authors-list-response'; -import { HTTPValidationError } from '../model/models'; - - -import { Configuration } from '../configuration'; - - - -export interface PersonsSearchServiceInterface { - defaultHeaders: HttpHeaders; - configuration: Configuration; - - /** - * Searches for persons with advanced filters (Topic & Institution) and pagination. - * - * @endpoint get /api/inse-service/persons/search-list - * @param query Search query (e.g., Arman AND Arzani) - * @param institutionName Filter by institution name - * @param topic Filter by topic display names - * @param page Page number (1-indexed) - * @param pageSize Results per page - * @param include Comma-separated include tags - * @param strict Strict institution search by target year - */ - searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, extraHttpRequestParams?: any): Observable; - -} diff --git a/webapp/src/app/api/api/topics.service.ts b/webapp/src/app/api/api/topics.service.ts index 59da64d8..d0874989 100644 --- a/webapp/src/app/api/api/topics.service.ts +++ b/webapp/src/app/api/api/topics.service.ts @@ -16,8 +16,12 @@ import { HttpClient, HttpHeaders, HttpParams, import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; +// @ts-ignore +import { AutocompleteResponse } from '../model/autocomplete-response'; // @ts-ignore import { HTTPValidationError } from '../model/http-validation-error'; +// @ts-ignore +import { TopicsListResponse } from '../model/topics-list-response'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -38,6 +42,78 @@ export class TopicsService extends BaseService implements TopicsServiceInterface super(basePath, configuration); } + /** + * Returns topic options for autocomplete inputs. + * @endpoint get /api/topics/autocomplete + * @param query Topic search text, for example \'machine learning\'. + * @param domainId Optional OpenAlex domain id filter. + * @param fieldId Optional OpenAlex field id filter. + * @param subfieldId Optional OpenAlex subfield id filter. + * @param limit Maximum number of autocomplete options. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling autocompleteTopics.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + domainId, 'domainId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + fieldId, 'fieldId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + subfieldId, 'subfieldId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/topics/autocomplete`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Builds the topic hierarchy cache. * @endpoint get /api/inse-service/topics/cache @@ -213,4 +289,85 @@ export class TopicsService extends BaseService implements TopicsServiceInterface ); } + /** + * Returns a list of OpenAlex topics. + * @endpoint get /api/topics + * @param search Full-text search, for example \'machine learning\'. + * @param filter OpenAlex filter, for example \'domain.id:1,works_count:>1000\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'domain.id\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + search, 'search'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filter, 'filter'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sort, 'sort'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + groupBy, 'group_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + perPage, 'per_page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + cursor, 'cursor'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sample, 'sample'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + select, 'select'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/topics`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + } diff --git a/webapp/src/app/api/api/topics.serviceInterface.ts b/webapp/src/app/api/api/topics.serviceInterface.ts index 80100ed1..f17e7433 100644 --- a/webapp/src/app/api/api/topics.serviceInterface.ts +++ b/webapp/src/app/api/api/topics.serviceInterface.ts @@ -11,7 +11,9 @@ import { HttpHeaders } from '@angular/comm import { Observable } from 'rxjs'; +import { AutocompleteResponse } from '../model/models'; import { HTTPValidationError } from '../model/models'; +import { TopicsListResponse } from '../model/models'; import { Configuration } from '../configuration'; @@ -22,6 +24,18 @@ export interface TopicsServiceInterface { defaultHeaders: HttpHeaders; configuration: Configuration; + /** + * Returns topic options for autocomplete inputs. + * + * @endpoint get /api/topics/autocomplete + * @param query Topic search text, for example \'machine learning\'. + * @param domainId Optional OpenAlex domain id filter. + * @param fieldId Optional OpenAlex field id filter. + * @param subfieldId Optional OpenAlex subfield id filter. + * @param limit Maximum number of autocomplete options. + */ + autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, extraHttpRequestParams?: any): Observable; + /** * Builds the topic hierarchy cache. * @@ -46,4 +60,20 @@ export interface TopicsServiceInterface { */ getTopicHierarchy(extraHttpRequestParams?: any): Observable; + /** + * Returns a list of OpenAlex topics. + * + * @endpoint get /api/topics + * @param search Full-text search, for example \'machine learning\'. + * @param filter OpenAlex filter, for example \'domain.id:1,works_count:>1000\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'domain.id\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + */ + listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, extraHttpRequestParams?: any): Observable; + } diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts index 7121b4a2..958dbae1 100644 --- a/webapp/src/app/api/api/works.service.ts +++ b/webapp/src/app/api/api/works.service.ts @@ -23,6 +23,8 @@ import { TopicCount } from '../model/topic-count'; // @ts-ignore import { TopicsByTime } from '../model/topics-by-time'; // @ts-ignore +import { Work } from '../model/work'; +// @ts-ignore import { WorkPage } from '../model/work-page'; // @ts-ignore import { WorksListResponse } from '../model/works-list-response'; @@ -113,13 +115,15 @@ export class WorksService extends BaseService implements WorksServiceInterface { * @param publicationYear Filter by publication year. Can be repeated. * @param type Filter by publication type. Can be repeated. * @param language Filter by language code. Can be repeated. + * @param institutionId Filter by OpenAlex institution id. Can be repeated. + * @param topicId Filter by OpenAlex topic id. Can be repeated. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (authorId === null || authorId === undefined) { throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.'); } @@ -147,6 +151,18 @@ export class WorksService extends BaseService implements WorksServiceInterface { element, 'language'); }) } + if (institutionId) { + institutionId.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'institution_id'); + }) + } + if (topicId) { + topicId.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic_id'); + }) + } let localVarHeaders = this.defaultHeaders; @@ -255,13 +271,15 @@ export class WorksService extends BaseService implements WorksServiceInterface { * @endpoint get /api/works/{author_id}/topics-by-time * @param authorId The author id, for example A5023888391. * @param maxTopicsPerYear The maximum number of topics per year. + * @param targetPublications Target number of publications used for the timeline. Complete years are always included. + * @param includeAll If true, all publications are used for the timeline. * @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 getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (authorId === null || authorId === undefined) { throw new Error('Required parameter authorId was null or undefined when calling getTopicsByTimeByAuthor.'); } @@ -269,6 +287,10 @@ export class WorksService extends BaseService implements WorksServiceInterface { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, maxTopicsPerYear, 'max_topics_per_year'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + targetPublications, 'target_publications'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + includeAll, 'include_all'); let localVarHeaders = this.defaultHeaders; @@ -314,4 +336,62 @@ export class WorksService extends BaseService implements WorksServiceInterface { ); } + /** + * Returns one publication. + * @endpoint get /api/works/detail/{work_id} + * @param workId The OpenAlex work id, for example W2741809807. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getWork(workId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getWork(workId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWork(workId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWork(workId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (workId === null || workId === undefined) { + throw new Error('Required parameter workId was null or undefined when calling getWork.'); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (bearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer '); + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/works/detail/${this.configuration.encodeParam({name: "workId", value: workId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + } diff --git a/webapp/src/app/api/api/works.serviceInterface.ts b/webapp/src/app/api/api/works.serviceInterface.ts index ed81c297..750853b0 100644 --- a/webapp/src/app/api/api/works.serviceInterface.ts +++ b/webapp/src/app/api/api/works.serviceInterface.ts @@ -14,6 +14,7 @@ import { Observable } from 'rxjs'; import { HTTPValidationError } from '../model/models'; import { TopicCount } from '../model/models'; import { TopicsByTime } from '../model/models'; +import { Work } from '../model/models'; import { WorkPage } from '../model/models'; import { WorksListResponse } from '../model/models'; @@ -44,8 +45,10 @@ export interface WorksServiceInterface { * @param publicationYear Filter by publication year. Can be repeated. * @param type Filter by publication type. Can be repeated. * @param language Filter by language code. Can be repeated. + * @param institutionId Filter by OpenAlex institution id. Can be repeated. + * @param topicId Filter by OpenAlex topic id. Can be repeated. */ - getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, extraHttpRequestParams?: any): Observable; + getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, extraHttpRequestParams?: any): Observable; /** * Returns work counts per primary topic for an author. @@ -61,7 +64,17 @@ export interface WorksServiceInterface { * @endpoint get /api/works/{author_id}/topics-by-time * @param authorId The author id, for example A5023888391. * @param maxTopicsPerYear The maximum number of topics per year. + * @param targetPublications Target number of publications used for the timeline. Complete years are always included. + * @param includeAll If true, all publications are used for the timeline. */ - getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, extraHttpRequestParams?: any): Observable; + getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, extraHttpRequestParams?: any): Observable; + + /** + * Returns one publication. + * + * @endpoint get /api/works/detail/{work_id} + * @param workId The OpenAlex work id, for example W2741809807. + */ + getWork(workId: string, extraHttpRequestParams?: any): Observable; } diff --git a/webapp/src/app/api/model/accessGrant.ts b/webapp/src/app/api/model/accessGrant.ts new file mode 100644 index 00000000..ad1f537a --- /dev/null +++ b/webapp/src/app/api/model/accessGrant.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. + */ +import { AuthScope } from './authScope'; + + +export interface AccessGrant { + token_type: string; + access_token: string; + expires_in: number; + scope: AuthScope; + refresh_token: string; +} + diff --git a/webapp/src/app/api/model/authAccount.ts b/webapp/src/app/api/model/authAccount.ts new file mode 100644 index 00000000..0c76d8dc --- /dev/null +++ b/webapp/src/app/api/model/authAccount.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface AuthAccount { + i: number; + l: string; + o: number; +} + diff --git a/webapp/src/app/api/model/authScope.ts b/webapp/src/app/api/model/authScope.ts new file mode 100644 index 00000000..65ffa9b5 --- /dev/null +++ b/webapp/src/app/api/model/authScope.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { AuthAccount } from './authAccount'; + + +export interface AuthScope { + t: string; + a: AuthAccount; + d?: number | null; + r?: Array; +} + diff --git a/webapp/src/app/api/model/collaboration-network-node.ts b/webapp/src/app/api/model/author-network-node.ts similarity index 89% rename from webapp/src/app/api/model/collaboration-network-node.ts rename to webapp/src/app/api/model/author-network-node.ts index 3a4542d3..e9d71c5a 100644 --- a/webapp/src/app/api/model/collaboration-network-node.ts +++ b/webapp/src/app/api/model/author-network-node.ts @@ -10,7 +10,7 @@ import { CollaborationNetworkNodeType } from './collaboration-network-node-type'; -export interface CollaborationNetworkNode { +export interface AuthorNetworkNode { /** * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. */ @@ -24,7 +24,7 @@ export interface CollaborationNetworkNode { */ category: CollaborationNetworkNodeType; } -export namespace CollaborationNetworkNode { +export namespace AuthorNetworkNode { } diff --git a/webapp/src/app/api/model/authorAffiliationsInner.ts b/webapp/src/app/api/model/authorAffiliationsInner.ts new file mode 100644 index 00000000..270443ff --- /dev/null +++ b/webapp/src/app/api/model/authorAffiliationsInner.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. + */ +import { DehydratedInstitution } from './dehydratedInstitution'; + + +/** + * AuthorAffiliationsInner + */ +export interface AuthorAffiliationsInner { + institution?: DehydratedInstitution | null; + years?: Array | null; +} + diff --git a/webapp/src/app/api/model/authorCountsByYearInner.ts b/webapp/src/app/api/model/authorCountsByYearInner.ts new file mode 100644 index 00000000..d16c7c21 --- /dev/null +++ b/webapp/src/app/api/model/authorCountsByYearInner.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. + */ + + +/** + * AuthorCountsByYearInner + */ +export interface AuthorCountsByYearInner { + year?: number | null; + works_count?: number | null; + cited_by_count?: number | null; +} + diff --git a/webapp/src/app/api/model/authorIds.ts b/webapp/src/app/api/model/authorIds.ts new file mode 100644 index 00000000..9235a207 --- /dev/null +++ b/webapp/src/app/api/model/authorIds.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. + */ + + +/** + * External identifiers: + */ +export interface AuthorIds { + openalex?: string | null; + orcid?: string | null; + scopus?: string | null; +} + diff --git a/webapp/src/app/api/model/authorNetworkNode.ts b/webapp/src/app/api/model/authorNetworkNode.ts new file mode 100644 index 00000000..aee98d47 --- /dev/null +++ b/webapp/src/app/api/model/authorNetworkNode.ts @@ -0,0 +1,30 @@ +/** + * 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 { CollaborationNetworkNodeType } from './collaborationNetworkNodeType'; + + +export interface AuthorNetworkNode { + /** + * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. + */ + raw_id: string; + /** + * The display name of the node. + */ + display_name: string; + /** + * The category of the node, either \'author\', \'institution\', or \'work\'. + */ + category: CollaborationNetworkNodeType; +} +export namespace AuthorNetworkNode { +} + + diff --git a/webapp/src/app/api/model/authorParsedLongestName.ts b/webapp/src/app/api/model/authorParsedLongestName.ts new file mode 100644 index 00000000..f49e04be --- /dev/null +++ b/webapp/src/app/api/model/authorParsedLongestName.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. + */ + + +/** + * The longest name parsed into its component parts. + */ +export interface AuthorParsedLongestName { + first?: string | null; + middle?: string | null; + last?: string | null; + suffix?: string | null; + nickname?: string | null; +} + diff --git a/webapp/src/app/api/model/authorPositionCount.ts b/webapp/src/app/api/model/authorPositionCount.ts new file mode 100644 index 00000000..a02e3749 --- /dev/null +++ b/webapp/src/app/api/model/authorPositionCount.ts @@ -0,0 +1,18 @@ +/** + * 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 AuthorPositionCount { + first?: number; + middle?: number; + last?: number; + unknown?: number; +} + diff --git a/webapp/src/app/api/model/authorSummaryStats.ts b/webapp/src/app/api/model/authorSummaryStats.ts new file mode 100644 index 00000000..1cfc0bdb --- /dev/null +++ b/webapp/src/app/api/model/authorSummaryStats.ts @@ -0,0 +1,21 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Model2YrMeanCitedness } from './model2YrMeanCitedness'; + + +/** + * Citation metrics: + */ +export interface AuthorSummaryStats { + '2yr_mean_citedness'?: Model2YrMeanCitedness | null; + h_index?: number | null; + i10_index?: number | null; +} + diff --git a/webapp/src/app/api/model/authors-filter-properties.ts b/webapp/src/app/api/model/authors-filter-properties.ts new file mode 100644 index 00000000..7312558f --- /dev/null +++ b/webapp/src/app/api/model/authors-filter-properties.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 AuthorsFilterProperties { + /** + * The list of raw institution IDs to include in the collaboration network. If empty, all institutions will be included. + */ + allowed_institutions?: Array; + /** + * The minimum number of collaborations required for an author to be included in the collaboration network. + */ + min_collaborations?: number; + /** + * The maximum number of collaborations allowed for an author to be included in the collaboration network. + */ + max_collaborations?: number; +} + diff --git a/webapp/src/app/api/model/authorsFilterProperties.ts b/webapp/src/app/api/model/authorsFilterProperties.ts new file mode 100644 index 00000000..7312558f --- /dev/null +++ b/webapp/src/app/api/model/authorsFilterProperties.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 AuthorsFilterProperties { + /** + * The list of raw institution IDs to include in the collaboration network. If empty, all institutions will be included. + */ + allowed_institutions?: Array; + /** + * The minimum number of collaborations required for an author to be included in the collaboration network. + */ + min_collaborations?: number; + /** + * The maximum number of collaborations allowed for an author to be included in the collaboration network. + */ + max_collaborations?: number; +} + diff --git a/webapp/src/app/api/model/authorsListResponse.ts b/webapp/src/app/api/model/authorsListResponse.ts new file mode 100644 index 00000000..d309ae43 --- /dev/null +++ b/webapp/src/app/api/model/authorsListResponse.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Meta } from './meta'; +import { Author } from './author'; +import { GroupByResult } from './groupByResult'; + + +/** + * AuthorsListResponse + */ +export interface AuthorsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; +} + diff --git a/webapp/src/app/api/model/autocomplete-response-meta.ts b/webapp/src/app/api/model/autocomplete-response-meta.ts new file mode 100644 index 00000000..2e080d39 --- /dev/null +++ b/webapp/src/app/api/model/autocomplete-response-meta.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * AutocompleteResponseMeta + */ +export interface AutocompleteResponseMeta { + count?: number | null; + db_response_time_ms?: number | null; +} + diff --git a/webapp/src/app/api/model/autocomplete-response-results-inner.ts b/webapp/src/app/api/model/autocomplete-response-results-inner.ts new file mode 100644 index 00000000..99ba71fe --- /dev/null +++ b/webapp/src/app/api/model/autocomplete-response-results-inner.ts @@ -0,0 +1,24 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * AutocompleteResponseResultsInner + */ +export interface AutocompleteResponseResultsInner { + id?: string | null; + display_name?: string | null; + hint?: string | null; + cited_by_count?: number | null; + works_count?: number | null; + entity_type?: string | null; + external_id?: string | null; +} + diff --git a/webapp/src/app/api/model/autocomplete-response.ts b/webapp/src/app/api/model/autocomplete-response.ts new file mode 100644 index 00000000..131fb559 --- /dev/null +++ b/webapp/src/app/api/model/autocomplete-response.ts @@ -0,0 +1,21 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { AutocompleteResponseMeta } from './autocomplete-response-meta'; +import { AutocompleteResponseResultsInner } from './autocomplete-response-results-inner'; + + +/** + * AutocompleteResponse + */ +export interface AutocompleteResponse { + meta?: AutocompleteResponseMeta | null; + results?: Array | null; +} + diff --git a/webapp/src/app/api/model/autocompleteResponse.ts b/webapp/src/app/api/model/autocompleteResponse.ts new file mode 100644 index 00000000..e220f57b --- /dev/null +++ b/webapp/src/app/api/model/autocompleteResponse.ts @@ -0,0 +1,21 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { AutocompleteResponseMeta } from './autocompleteResponseMeta'; +import { AutocompleteResponseResultsInner } from './autocompleteResponseResultsInner'; + + +/** + * AutocompleteResponse + */ +export interface AutocompleteResponse { + meta?: AutocompleteResponseMeta | null; + results?: Array | null; +} + diff --git a/webapp/src/app/api/model/autocompleteResponseMeta.ts b/webapp/src/app/api/model/autocompleteResponseMeta.ts new file mode 100644 index 00000000..2e080d39 --- /dev/null +++ b/webapp/src/app/api/model/autocompleteResponseMeta.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * AutocompleteResponseMeta + */ +export interface AutocompleteResponseMeta { + count?: number | null; + db_response_time_ms?: number | null; +} + diff --git a/webapp/src/app/api/model/autocompleteResponseResultsInner.ts b/webapp/src/app/api/model/autocompleteResponseResultsInner.ts new file mode 100644 index 00000000..99ba71fe --- /dev/null +++ b/webapp/src/app/api/model/autocompleteResponseResultsInner.ts @@ -0,0 +1,24 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * AutocompleteResponseResultsInner + */ +export interface AutocompleteResponseResultsInner { + id?: string | null; + display_name?: string | null; + hint?: string | null; + cited_by_count?: number | null; + works_count?: number | null; + entity_type?: string | null; + external_id?: string | null; +} + diff --git a/webapp/src/app/api/model/collaboration-network.ts b/webapp/src/app/api/model/collaboration-network.ts index 9956ae19..93788a02 100644 --- a/webapp/src/app/api/model/collaboration-network.ts +++ b/webapp/src/app/api/model/collaboration-network.ts @@ -8,8 +8,10 @@ * Do not edit the class manually. */ import { FilterInformation } from './filter-information'; +import { WorkNetworkNode } from './work-network-node'; import { CollaborationNetworkEdge } from './collaboration-network-edge'; -import { CollaborationNetworkNode } from './collaboration-network-node'; +import { InstitutionNetworkNode } from './institution-network-node'; +import { AuthorNetworkNode } from './author-network-node'; export interface CollaborationNetwork { @@ -18,13 +20,21 @@ export interface CollaborationNetwork { */ raw_person_id: string; /** - * The nodes in the collaboration network. + * The work nodes in the collaboration network. */ - nodes: Array; + work_nodes: Array; /** - * The edges in the collaboration network. + * The author nodes in the collaboration network. */ - edges: Array; + author_nodes: Array; + /** + * The institution nodes in the collaboration network. + */ + institution_nodes: Array; + /** + * The collaboration edges in the collaboration network. A collaboration edge represents a collaboration between two nodes. A -> W and A -> I + */ + collaboration_edges: Array; /** * The filter information for the collaboration network, including the minimum and maximum publication years of the works in the collaboration network. */ diff --git a/webapp/src/app/api/model/collaborationNetwork.ts b/webapp/src/app/api/model/collaborationNetwork.ts new file mode 100644 index 00000000..e439c061 --- /dev/null +++ b/webapp/src/app/api/model/collaborationNetwork.ts @@ -0,0 +1,43 @@ +/** + * 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 { FilterInformation } from './filterInformation'; +import { WorkNetworkNode } from './workNetworkNode'; +import { CollaborationNetworkEdge } from './collaborationNetworkEdge'; +import { InstitutionNetworkNode } from './institutionNetworkNode'; +import { AuthorNetworkNode } from './authorNetworkNode'; + + +export interface CollaborationNetwork { + /** + * The raw person ID of the person whose collaboration network this is. + */ + raw_person_id: string; + /** + * The work nodes in the collaboration network. + */ + work_nodes: Array; + /** + * The author nodes in the collaboration network. + */ + author_nodes: Array; + /** + * The institution nodes in the collaboration network. + */ + institution_nodes: Array; + /** + * The collaboration edges in the collaboration network. A collaboration edge represents a collaboration between two nodes. A -> W and A -> I + */ + collaboration_edges: Array; + /** + * The filter information for the collaboration network, including the minimum and maximum publication years of the works in the collaboration network. + */ + filter_information: FilterInformation; +} + diff --git a/webapp/src/app/api/model/collaborationNetworkEdge.ts b/webapp/src/app/api/model/collaborationNetworkEdge.ts new file mode 100644 index 00000000..16fb5fc6 --- /dev/null +++ b/webapp/src/app/api/model/collaborationNetworkEdge.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 CollaborationNetworkEdge { + /** + * The raw ID of the source node. + */ + raw_source_id: string; + /** + * The raw ID of the target node. + */ + raw_target_id: string; +} + diff --git a/webapp/src/app/api/model/collaborationNetworkNodeType.ts b/webapp/src/app/api/model/collaborationNetworkNodeType.ts new file mode 100644 index 00000000..752e35b0 --- /dev/null +++ b/webapp/src/app/api/model/collaborationNetworkNodeType.ts @@ -0,0 +1,18 @@ +/** + * 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 CollaborationNetworkNodeType = { + Author: 'author', + Institution: 'institution', + Work: 'work' +} as const; +export type CollaborationNetworkNodeType = typeof CollaborationNetworkNodeType[keyof typeof CollaborationNetworkNodeType]; + diff --git a/webapp/src/app/api/model/costUsd.ts b/webapp/src/app/api/model/costUsd.ts new file mode 100644 index 00000000..c7bcbee8 --- /dev/null +++ b/webapp/src/app/api/model/costUsd.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Cost of this request in USD + */ +export interface CostUsd { +} + diff --git a/webapp/src/app/api/model/custom-authors-list-response.ts b/webapp/src/app/api/model/custom-authors-list-response.ts index c82298d0..f6dc8f0b 100644 --- a/webapp/src/app/api/model/custom-authors-list-response.ts +++ b/webapp/src/app/api/model/custom-authors-list-response.ts @@ -8,6 +8,7 @@ * Do not edit the class manually. */ import { Meta } from './meta'; +import { CustomAuthor } from './custom-author'; import { Author } from './author'; import { GroupByResult } from './group-by-result'; @@ -16,5 +17,6 @@ export interface CustomAuthorsListResponse { meta?: Meta | null; results?: Array | null; group_by?: Array | null; + placeholder?: CustomAuthor | null; } diff --git a/webapp/src/app/api/model/customAuthor.ts b/webapp/src/app/api/model/customAuthor.ts new file mode 100644 index 00000000..1117cd53 --- /dev/null +++ b/webapp/src/app/api/model/customAuthor.ts @@ -0,0 +1,39 @@ +/** + * 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 { AuthorAffiliationsInner } from './authorAffiliationsInner'; +import { AuthorParsedLongestName } from './authorParsedLongestName'; +import { DehydratedInstitution } from './dehydratedInstitution'; +import { AuthorCountsByYearInner } from './authorCountsByYearInner'; +import { AuthorIds } from './authorIds'; +import { AuthorSummaryStats } from './authorSummaryStats'; +import { WorkTopic } from './workTopic'; + + +export interface CustomAuthor { + id?: string | null; + orcid?: string | null; + display_name?: string | null; + display_name_alternatives?: Array | null; + longest_name?: string | null; + parsed_longest_name?: AuthorParsedLongestName | null; + works_count?: number | null; + cited_by_count?: number | null; + summary_stats?: AuthorSummaryStats | null; + affiliations?: Array | null; + last_known_institutions?: Array | null; + topics?: Array | null; + counts_by_year?: Array | null; + ids?: AuthorIds | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; + relevance_rating?: string | null; +} + diff --git a/webapp/src/app/api/model/customAuthorsListResponse.ts b/webapp/src/app/api/model/customAuthorsListResponse.ts new file mode 100644 index 00000000..f6eac14b --- /dev/null +++ b/webapp/src/app/api/model/customAuthorsListResponse.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. + */ +import { Meta } from './meta'; +import { CustomAuthor } from './customAuthor'; +import { Author } from './author'; +import { GroupByResult } from './groupByResult'; + + +export interface CustomAuthorsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; + placeholder?: CustomAuthor | null; +} + diff --git a/webapp/src/app/api/model/dehydratedAuthor.ts b/webapp/src/app/api/model/dehydratedAuthor.ts new file mode 100644 index 00000000..4d3817f1 --- /dev/null +++ b/webapp/src/app/api/model/dehydratedAuthor.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. + */ + + +/** + * [Dehydrated Author](/api-reference/authors#the-dehydratedauthor-object) — reduced-field version used in nested contexts + */ +export interface DehydratedAuthor { + id?: string | null; + display_name?: string | null; + orcid?: string | null; +} + diff --git a/webapp/src/app/api/model/dehydratedFunder.ts b/webapp/src/app/api/model/dehydratedFunder.ts new file mode 100644 index 00000000..b134bbb1 --- /dev/null +++ b/webapp/src/app/api/model/dehydratedFunder.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. + */ + + +/** + * [Dehydrated Funder](/api-reference/funders) — reduced-field version used in nested contexts + */ +export interface DehydratedFunder { + id?: string | null; + display_name?: string | null; + ror?: string | null; +} + diff --git a/webapp/src/app/api/model/dehydratedInstitution.ts b/webapp/src/app/api/model/dehydratedInstitution.ts new file mode 100644 index 00000000..7b6c9824 --- /dev/null +++ b/webapp/src/app/api/model/dehydratedInstitution.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * [Dehydrated Institution](/api-reference/institutions#the-dehydratedinstitution-object) — reduced-field version used in nested contexts + */ +export interface DehydratedInstitution { + id?: string | null; + display_name?: string | null; + ror?: string | null; + country_code?: string | null; + type?: string | null; + lineage?: Array | null; +} + diff --git a/webapp/src/app/api/model/dehydratedSource.ts b/webapp/src/app/api/model/dehydratedSource.ts new file mode 100644 index 00000000..ae714846 --- /dev/null +++ b/webapp/src/app/api/model/dehydratedSource.ts @@ -0,0 +1,28 @@ +/** + * 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. + */ + + +/** + * [Dehydrated Source](/api-reference/sources#the-dehydratedsource-object) — reduced-field version used in nested contexts + */ +export interface DehydratedSource { + id?: string | null; + display_name?: string | null; + issn_l?: string | null; + issn?: Array | null; + is_oa?: boolean | null; + is_in_doaj?: boolean | null; + is_core?: boolean | null; + host_organization?: string | null; + host_organization_name?: string | null; + host_organization_lineage?: Array | null; + type?: string | null; +} + diff --git a/webapp/src/app/api/model/filter-properties.ts b/webapp/src/app/api/model/filter-properties.ts index daeb08ee..bb3cc934 100644 --- a/webapp/src/app/api/model/filter-properties.ts +++ b/webapp/src/app/api/model/filter-properties.ts @@ -7,16 +7,16 @@ * https://openapi-generator.tech * Do not edit the class manually. */ +import { WorksFilterProperties } from './works-filter-properties'; +import { AuthorsFilterProperties } from './authors-filter-properties'; export interface FilterProperties { - start_year: number | null; - end_year: number | null; - allowed_institutions: Array | null; - allowed_topics: Array | null; - min_collaborators: number | null; - max_collaborators: number | null; - min_collaborations: number | null; - max_collaborations: number | null; + /** + * The type of filter to apply when generating the collaboration network. Can be either \'works\' or \'authors\'. If \'works\', the filter properties in the \'works_filter_properties\' field will be used. If \'authors\', the filter properties in the \'authors_filter_properties\' field will be used. + */ + filter_by?: string; + works_filter_properties: WorksFilterProperties | null; + authors_filter_properties: AuthorsFilterProperties | null; } diff --git a/webapp/src/app/api/model/filterInformation.ts b/webapp/src/app/api/model/filterInformation.ts new file mode 100644 index 00000000..b2078376 --- /dev/null +++ b/webapp/src/app/api/model/filterInformation.ts @@ -0,0 +1,32 @@ +/** + * 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 { InstitutionInformation } from './institutionInformation'; +import { WorkTopicInformation } from './workTopicInformation'; + + +export interface FilterInformation { + /** + * The minimum publication year of the works in the collaboration network. + */ + min_possible_year: number; + /** + * The maximum publication year of the works in the collaboration network. + */ + max_possible_year: number; + /** + * The list of institutions associated with the works in the collaboration network. + */ + institutions: Array; + /** + * The list of topics associated with the works in the collaboration network. + */ + topics: Array; +} + diff --git a/webapp/src/app/api/model/filterProperties.ts b/webapp/src/app/api/model/filterProperties.ts new file mode 100644 index 00000000..608acab4 --- /dev/null +++ b/webapp/src/app/api/model/filterProperties.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. + */ +import { WorksFilterProperties } from './worksFilterProperties'; +import { AuthorsFilterProperties } from './authorsFilterProperties'; + + +export interface FilterProperties { + /** + * The type of filter to apply when generating the collaboration network. Can be either \'works\' or \'authors\'. If \'works\', the filter properties in the \'works_filter_properties\' field will be used. If \'authors\', the filter properties in the \'authors_filter_properties\' field will be used. + */ + filter_by?: string; + works_filter_properties: WorksFilterProperties | null; + authors_filter_properties: AuthorsFilterProperties | null; +} + diff --git a/webapp/src/app/api/model/funderByAuthor.ts b/webapp/src/app/api/model/funderByAuthor.ts new file mode 100644 index 00000000..fbcbf475 --- /dev/null +++ b/webapp/src/app/api/model/funderByAuthor.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { PublicationIdsByAuthorPosition } from './publicationIdsByAuthorPosition'; +import { AuthorPositionCount } from './authorPositionCount'; + + +export interface FunderByAuthor { + funder_id?: string | null; + funder_name?: string | null; + publication_count: number; + author_position_count: AuthorPositionCount; + publication_ids: PublicationIdsByAuthorPosition; + publication_urls?: { [key: string]: string; }; + publication_titles?: { [key: string]: string; }; +} + diff --git a/webapp/src/app/api/model/fundersByAuthorResponse.ts b/webapp/src/app/api/model/fundersByAuthorResponse.ts new file mode 100644 index 00000000..1286429e --- /dev/null +++ b/webapp/src/app/api/model/fundersByAuthorResponse.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { FunderByAuthor } from './funderByAuthor'; + + +export interface FundersByAuthorResponse { + author_id: string; + author_name?: string | null; + funder_count: number; + funders: Array; +} + diff --git a/webapp/src/app/api/model/groupByResult.ts b/webapp/src/app/api/model/groupByResult.ts new file mode 100644 index 00000000..68c51855 --- /dev/null +++ b/webapp/src/app/api/model/groupByResult.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. + */ + + +/** + * GroupByResult + */ +export interface GroupByResult { + key?: string | null; + key_display_name?: string | null; + count?: number | null; +} + diff --git a/webapp/src/app/api/model/hTTPValidationError.ts b/webapp/src/app/api/model/hTTPValidationError.ts new file mode 100644 index 00000000..f624be37 --- /dev/null +++ b/webapp/src/app/api/model/hTTPValidationError.ts @@ -0,0 +1,16 @@ +/** + * 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 { ValidationError } from './validationError'; + + +export interface HTTPValidationError { + detail?: Array; +} + diff --git a/webapp/src/app/api/model/identityGrant.ts b/webapp/src/app/api/model/identityGrant.ts new file mode 100644 index 00000000..9ec3fe50 --- /dev/null +++ b/webapp/src/app/api/model/identityGrant.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { AuthScope } from './authScope'; + + +export interface IdentityGrant { + token_type: string; + access_token: string; + expires_in: number; + scope: AuthScope; +} + diff --git a/webapp/src/app/api/model/institution-geo.ts b/webapp/src/app/api/model/institution-geo.ts new file mode 100644 index 00000000..949b73f4 --- /dev/null +++ b/webapp/src/app/api/model/institution-geo.ts @@ -0,0 +1,26 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Latitude } from './latitude'; +import { Longitude } from './longitude'; + + +/** + * Location information: + */ +export interface InstitutionGeo { + city?: string | null; + geonames_city_id?: string | null; + region?: string | null; + country_code?: string | null; + country?: string | null; + latitude?: Latitude | null; + longitude?: Longitude | null; +} + diff --git a/webapp/src/app/api/model/institution-ids.ts b/webapp/src/app/api/model/institution-ids.ts new file mode 100644 index 00000000..93d801e1 --- /dev/null +++ b/webapp/src/app/api/model/institution-ids.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * External identifiers: + */ +export interface InstitutionIds { + openalex?: string | null; + ror?: string | null; + mag?: number | null; + grid?: string | null; + wikipedia?: string | null; + wikidata?: string | null; +} + diff --git a/webapp/src/app/api/model/institution-network-node.ts b/webapp/src/app/api/model/institution-network-node.ts new file mode 100644 index 00000000..e1c85a17 --- /dev/null +++ b/webapp/src/app/api/model/institution-network-node.ts @@ -0,0 +1,30 @@ +/** + * 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 { CollaborationNetworkNodeType } from './collaboration-network-node-type'; + + +export interface InstitutionNetworkNode { + /** + * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. + */ + raw_id: string; + /** + * The display name of the node. + */ + display_name: string; + /** + * The category of the node, either \'author\', \'institution\', or \'work\'. + */ + category: CollaborationNetworkNodeType; +} +export namespace InstitutionNetworkNode { +} + + diff --git a/webapp/src/app/api/model/institution.ts b/webapp/src/app/api/model/institution.ts new file mode 100644 index 00000000..3c6b9d4c --- /dev/null +++ b/webapp/src/app/api/model/institution.ts @@ -0,0 +1,41 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { InstitutionIds } from './institution-ids'; +import { AuthorCountsByYearInner } from './author-counts-by-year-inner'; +import { AuthorSummaryStats } from './author-summary-stats'; +import { InstitutionGeo } from './institution-geo'; + + +/** + * A university, research organization, or other affiliation + */ +export interface Institution { + id?: string | null; + ror?: string | null; + display_name?: string | null; + country_code?: string | null; + type?: string | null; + homepage_url?: string | null; + image_url?: string | null; + image_thumbnail_url?: string | null; + display_name_acronyms?: Array | null; + display_name_alternatives?: Array | null; + works_count?: number | null; + cited_by_count?: number | null; + summary_stats?: AuthorSummaryStats | null; + geo?: InstitutionGeo | null; + lineage?: Array | null; + ids?: InstitutionIds | null; + counts_by_year?: Array | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; +} + diff --git a/webapp/src/app/api/model/institutionGeo.ts b/webapp/src/app/api/model/institutionGeo.ts new file mode 100644 index 00000000..949b73f4 --- /dev/null +++ b/webapp/src/app/api/model/institutionGeo.ts @@ -0,0 +1,26 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Latitude } from './latitude'; +import { Longitude } from './longitude'; + + +/** + * Location information: + */ +export interface InstitutionGeo { + city?: string | null; + geonames_city_id?: string | null; + region?: string | null; + country_code?: string | null; + country?: string | null; + latitude?: Latitude | null; + longitude?: Longitude | null; +} + diff --git a/webapp/src/app/api/model/institutionIds.ts b/webapp/src/app/api/model/institutionIds.ts new file mode 100644 index 00000000..93d801e1 --- /dev/null +++ b/webapp/src/app/api/model/institutionIds.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * External identifiers: + */ +export interface InstitutionIds { + openalex?: string | null; + ror?: string | null; + mag?: number | null; + grid?: string | null; + wikipedia?: string | null; + wikidata?: string | null; +} + diff --git a/webapp/src/app/api/model/institutionInformation.ts b/webapp/src/app/api/model/institutionInformation.ts new file mode 100644 index 00000000..e287b0fa --- /dev/null +++ b/webapp/src/app/api/model/institutionInformation.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 InstitutionInformation { + /** + * The raw institution ID of the institution. + */ + raw_id: string; + /** + * The display name of the institution. + */ + display_name: string; +} + diff --git a/webapp/src/app/api/model/institutionNetworkNode.ts b/webapp/src/app/api/model/institutionNetworkNode.ts new file mode 100644 index 00000000..a558a8cf --- /dev/null +++ b/webapp/src/app/api/model/institutionNetworkNode.ts @@ -0,0 +1,30 @@ +/** + * 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 { CollaborationNetworkNodeType } from './collaborationNetworkNodeType'; + + +export interface InstitutionNetworkNode { + /** + * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. + */ + raw_id: string; + /** + * The display name of the node. + */ + display_name: string; + /** + * The category of the node, either \'author\', \'institution\', or \'work\'. + */ + category: CollaborationNetworkNodeType; +} +export namespace InstitutionNetworkNode { +} + + diff --git a/webapp/src/app/api/model/institutions-list-response.ts b/webapp/src/app/api/model/institutions-list-response.ts new file mode 100644 index 00000000..747faa03 --- /dev/null +++ b/webapp/src/app/api/model/institutions-list-response.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Meta } from './meta'; +import { Institution } from './institution'; +import { GroupByResult } from './group-by-result'; + + +/** + * InstitutionsListResponse + */ +export interface InstitutionsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; +} + diff --git a/webapp/src/app/api/model/institutionsListResponse.ts b/webapp/src/app/api/model/institutionsListResponse.ts new file mode 100644 index 00000000..908d72fe --- /dev/null +++ b/webapp/src/app/api/model/institutionsListResponse.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Meta } from './meta'; +import { Institution } from './institution'; +import { GroupByResult } from './groupByResult'; + + +/** + * InstitutionsListResponse + */ +export interface InstitutionsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; +} + diff --git a/webapp/src/app/api/model/itemCreate.ts b/webapp/src/app/api/model/itemCreate.ts new file mode 100644 index 00000000..608d6910 --- /dev/null +++ b/webapp/src/app/api/model/itemCreate.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 ItemCreate { + /** + * The name of the item. + */ + name: string; + /** + * The description of the item. + */ + description: string; +} + diff --git a/webapp/src/app/api/model/itemPage.ts b/webapp/src/app/api/model/itemPage.ts new file mode 100644 index 00000000..56595b8a --- /dev/null +++ b/webapp/src/app/api/model/itemPage.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 { Item } from './item'; + + +export interface ItemPage { + /** + * The elements of the page. + */ + elements?: Array; + /** + * The page offset in elements. + */ + offset?: number; + /** + * The total number of elements. + */ + total?: number; + /** + * The page size in elements. + */ + size?: number; +} + diff --git a/webapp/src/app/api/model/latitude.ts b/webapp/src/app/api/model/latitude.ts new file mode 100644 index 00000000..fe6b49aa --- /dev/null +++ b/webapp/src/app/api/model/latitude.ts @@ -0,0 +1,14 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface Latitude { +} + diff --git a/webapp/src/app/api/model/longitude.ts b/webapp/src/app/api/model/longitude.ts new file mode 100644 index 00000000..b0d39fce --- /dev/null +++ b/webapp/src/app/api/model/longitude.ts @@ -0,0 +1,14 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface Longitude { +} + diff --git a/webapp/src/app/api/model/model2YrMeanCitedness.ts b/webapp/src/app/api/model/model2YrMeanCitedness.ts new file mode 100644 index 00000000..67ec623c --- /dev/null +++ b/webapp/src/app/api/model/model2YrMeanCitedness.ts @@ -0,0 +1,14 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface Model2YrMeanCitedness { +} + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 9aad2ee6..cd44ec17 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -5,17 +5,22 @@ export * from './author'; export * from './author-affiliations-inner'; export * from './author-counts-by-year-inner'; export * from './author-ids'; +export * from './author-network-node'; export * from './author-parsed-longest-name'; export * from './author-position-count'; export * from './author-summary-stats'; +export * from './authors-filter-properties'; export * from './authors-list-response'; export * from './authorship'; +export * from './autocomplete-response'; +export * from './autocomplete-response-meta'; +export * from './autocomplete-response-results-inner'; export * from './award'; export * from './collaboration-network'; export * from './collaboration-network-edge'; -export * from './collaboration-network-node'; export * from './collaboration-network-node-type'; export * from './cost-usd'; +export * from './custom-author'; export * from './custom-authors-list-response'; export * from './dehydrated-author'; export * from './dehydrated-funder'; @@ -29,11 +34,18 @@ export * from './fwci'; export * from './group-by-result'; export * from './http-validation-error'; export * from './identity-grant'; +export * from './institution'; +export * from './institution-geo'; +export * from './institution-ids'; export * from './institution-information'; +export * from './institution-network-node'; +export * from './institutions-list-response'; export * from './item'; export * from './item-create'; export * from './item-page'; +export * from './latitude'; export * from './location'; +export * from './longitude'; export * from './meta'; export * from './model2-yr-mean-citedness'; export * from './open-access'; @@ -41,9 +53,15 @@ export * from './person-bio'; export * from './publication-ids-by-author-position'; export * from './publications-by-author-response'; export * from './score'; +export * from './topic'; export * from './topic-count'; +export * from './topic-domain'; +export * from './topic-field'; +export * from './topic-ids'; +export * from './topic-subfield'; export * from './topics-by-time'; export * from './topics-by-year'; +export * from './topics-list-response'; export * from './validation-error'; export * from './validation-error-loc-inner'; export * from './value'; @@ -56,6 +74,7 @@ export * from './work-has-content'; export * from './work-ids'; export * from './work-keyword'; export * from './work-mesh-inner'; +export * from './work-network-node'; export * from './work-page'; export * from './work-sustainable-development-goals-inner'; export * from './work-topic'; @@ -63,4 +82,5 @@ export * from './work-topic-domain'; export * from './work-topic-field'; export * from './work-topic-information'; export * from './work-topic-subfield'; +export * from './works-filter-properties'; export * from './works-list-response'; diff --git a/webapp/src/app/api/model/openAccess.ts b/webapp/src/app/api/model/openAccess.ts new file mode 100644 index 00000000..32a4ddd9 --- /dev/null +++ b/webapp/src/app/api/model/openAccess.ts @@ -0,0 +1,21 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Open access information + */ +export interface OpenAccess { + is_oa?: boolean | null; + oa_status?: string | null; + oa_url?: string | null; + any_repository_has_fulltext?: boolean | null; +} + diff --git a/webapp/src/app/api/model/person-search-request.ts b/webapp/src/app/api/model/person-search-request.ts deleted file mode 100644 index 9ed6e5bc..00000000 --- a/webapp/src/app/api/model/person-search-request.ts +++ /dev/null @@ -1,20 +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 { PersonFilters } from './person-filters'; - - -export interface PersonSearchRequest { - name?: string | null; - filters?: PersonFilters; - include?: string | null; - limit?: number | null; - page_offset?: number | null; -} - diff --git a/webapp/src/app/api/model/personBio.ts b/webapp/src/app/api/model/personBio.ts new file mode 100644 index 00000000..f7291e6f --- /dev/null +++ b/webapp/src/app/api/model/personBio.ts @@ -0,0 +1,18 @@ +/** + * 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 PersonBio { + /** + * The generated biography. + */ + bio: string; +} + diff --git a/webapp/src/app/api/model/publicationIdsByAuthorPosition.ts b/webapp/src/app/api/model/publicationIdsByAuthorPosition.ts new file mode 100644 index 00000000..c35050ef --- /dev/null +++ b/webapp/src/app/api/model/publicationIdsByAuthorPosition.ts @@ -0,0 +1,18 @@ +/** + * 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 PublicationIdsByAuthorPosition { + first?: Array; + middle?: Array; + last?: Array; + unknown?: Array; +} + diff --git a/webapp/src/app/api/model/publicationsByAuthorResponse.ts b/webapp/src/app/api/model/publicationsByAuthorResponse.ts new file mode 100644 index 00000000..5176fe39 --- /dev/null +++ b/webapp/src/app/api/model/publicationsByAuthorResponse.ts @@ -0,0 +1,21 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface PublicationsByAuthorResponse { + author_id: string; + page: number; + page_size: number; + total_works: number; + total: number; + results_count: number; + results: Array; +} + diff --git a/webapp/src/app/api/model/topic-domain.ts b/webapp/src/app/api/model/topic-domain.ts new file mode 100644 index 00000000..652b1bca --- /dev/null +++ b/webapp/src/app/api/model/topic-domain.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * The domain (highest level) containing this topic: + */ +export interface TopicDomain { + id?: string | null; + display_name?: string | null; +} + diff --git a/webapp/src/app/api/model/topic-field.ts b/webapp/src/app/api/model/topic-field.ts new file mode 100644 index 00000000..c7351675 --- /dev/null +++ b/webapp/src/app/api/model/topic-field.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * The field (second level) containing this topic: + */ +export interface TopicField { + id?: string | null; + display_name?: string | null; +} + diff --git a/webapp/src/app/api/model/topic-ids.ts b/webapp/src/app/api/model/topic-ids.ts new file mode 100644 index 00000000..4aa6738f --- /dev/null +++ b/webapp/src/app/api/model/topic-ids.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * External identifiers: + */ +export interface TopicIds { + openalex?: string | null; + wikipedia?: string | null; +} + diff --git a/webapp/src/app/api/model/topic-subfield.ts b/webapp/src/app/api/model/topic-subfield.ts new file mode 100644 index 00000000..53d37842 --- /dev/null +++ b/webapp/src/app/api/model/topic-subfield.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * The subfield (third level) containing this topic: + */ +export interface TopicSubfield { + id?: string | null; + display_name?: string | null; +} + diff --git a/webapp/src/app/api/model/topic.ts b/webapp/src/app/api/model/topic.ts new file mode 100644 index 00000000..cb66621f --- /dev/null +++ b/webapp/src/app/api/model/topic.ts @@ -0,0 +1,34 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { TopicDomain } from './topic-domain'; +import { TopicIds } from './topic-ids'; +import { TopicSubfield } from './topic-subfield'; +import { TopicField } from './topic-field'; + + +/** + * A research topic automatically assigned to works + */ +export interface Topic { + id?: string | null; + display_name?: string | null; + description?: string | null; + keywords?: Array | null; + subfield?: TopicSubfield | null; + field?: TopicField | null; + domain?: TopicDomain | null; + works_count?: number | null; + cited_by_count?: number | null; + ids?: TopicIds | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; +} + diff --git a/webapp/src/app/api/model/topicCount.ts b/webapp/src/app/api/model/topicCount.ts new file mode 100644 index 00000000..520042ec --- /dev/null +++ b/webapp/src/app/api/model/topicCount.ts @@ -0,0 +1,24 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface TopicCount { + id?: string | null; + /** + * The topic display name. + */ + name: string; + /** + * The number of occurrences. + */ + count?: number; + description?: string | null; +} + diff --git a/webapp/src/app/api/model/topicDomain.ts b/webapp/src/app/api/model/topicDomain.ts new file mode 100644 index 00000000..652b1bca --- /dev/null +++ b/webapp/src/app/api/model/topicDomain.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * The domain (highest level) containing this topic: + */ +export interface TopicDomain { + id?: string | null; + display_name?: string | null; +} + diff --git a/webapp/src/app/api/model/topicField.ts b/webapp/src/app/api/model/topicField.ts new file mode 100644 index 00000000..c7351675 --- /dev/null +++ b/webapp/src/app/api/model/topicField.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * The field (second level) containing this topic: + */ +export interface TopicField { + id?: string | null; + display_name?: string | null; +} + diff --git a/webapp/src/app/api/model/topicIds.ts b/webapp/src/app/api/model/topicIds.ts new file mode 100644 index 00000000..4aa6738f --- /dev/null +++ b/webapp/src/app/api/model/topicIds.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * External identifiers: + */ +export interface TopicIds { + openalex?: string | null; + wikipedia?: string | null; +} + diff --git a/webapp/src/app/api/model/topicSubfield.ts b/webapp/src/app/api/model/topicSubfield.ts new file mode 100644 index 00000000..53d37842 --- /dev/null +++ b/webapp/src/app/api/model/topicSubfield.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * The subfield (third level) containing this topic: + */ +export interface TopicSubfield { + id?: string | null; + display_name?: string | null; +} + diff --git a/webapp/src/app/api/model/topics-list-response.ts b/webapp/src/app/api/model/topics-list-response.ts new file mode 100644 index 00000000..f6974837 --- /dev/null +++ b/webapp/src/app/api/model/topics-list-response.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Meta } from './meta'; +import { GroupByResult } from './group-by-result'; +import { Topic } from './topic'; + + +/** + * TopicsListResponse + */ +export interface TopicsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; +} + diff --git a/webapp/src/app/api/model/topicsByTime.ts b/webapp/src/app/api/model/topicsByTime.ts new file mode 100644 index 00000000..0dac04a7 --- /dev/null +++ b/webapp/src/app/api/model/topicsByTime.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { TopicsByYear } from './topicsByYear'; + + +export interface TopicsByTime { + /** + * Topics grouped by year. + */ + elements?: Array; + /** + * The number of years. + */ + total?: number; +} + diff --git a/webapp/src/app/api/model/topicsByYear.ts b/webapp/src/app/api/model/topicsByYear.ts new file mode 100644 index 00000000..fded8da0 --- /dev/null +++ b/webapp/src/app/api/model/topicsByYear.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 { TopicCount } from './topicCount'; + + +export interface TopicsByYear { + /** + * The publication year. + */ + year: number; + /** + * The number of works in this year. + */ + publication_count?: number; + /** + * The topics in this year. + */ + topics?: Array; + /** + * The primary topics in this year. + */ + primary_topics?: Array; +} + diff --git a/webapp/src/app/api/model/topicsListResponse.ts b/webapp/src/app/api/model/topicsListResponse.ts new file mode 100644 index 00000000..43f21226 --- /dev/null +++ b/webapp/src/app/api/model/topicsListResponse.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Meta } from './meta'; +import { GroupByResult } from './groupByResult'; +import { Topic } from './topic'; + + +/** + * TopicsListResponse + */ +export interface TopicsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; +} + diff --git a/webapp/src/app/api/model/validationError.ts b/webapp/src/app/api/model/validationError.ts new file mode 100644 index 00000000..bdbd57ad --- /dev/null +++ b/webapp/src/app/api/model/validationError.ts @@ -0,0 +1,18 @@ +/** + * 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 { ValidationErrorLocInner } from './validationErrorLocInner'; + + +export interface ValidationError { + loc: Array; + msg: string; + type: string; +} + diff --git a/webapp/src/app/api/model/validationErrorLocInner.ts b/webapp/src/app/api/model/validationErrorLocInner.ts new file mode 100644 index 00000000..d248a9b7 --- /dev/null +++ b/webapp/src/app/api/model/validationErrorLocInner.ts @@ -0,0 +1,14 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface ValidationErrorLocInner { +} + diff --git a/webapp/src/app/api/model/work-network-node.ts b/webapp/src/app/api/model/work-network-node.ts new file mode 100644 index 00000000..58b7ab07 --- /dev/null +++ b/webapp/src/app/api/model/work-network-node.ts @@ -0,0 +1,33 @@ +/** + * 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 { WorkTopicInformation } from './work-topic-information'; +import { CollaborationNetworkNodeType } from './collaboration-network-node-type'; + + +export interface WorkNetworkNode { + /** + * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. + */ + raw_id: string; + /** + * The display name of the node. + */ + display_name: string; + /** + * The category of the node, either \'author\', \'institution\', or \'work\'. + */ + category: CollaborationNetworkNodeType; + publication_year: number | null; + work_topics_information: Set | null; +} +export namespace WorkNetworkNode { +} + + diff --git a/webapp/src/app/api/model/workBiblio.ts b/webapp/src/app/api/model/workBiblio.ts new file mode 100644 index 00000000..f6d7079b --- /dev/null +++ b/webapp/src/app/api/model/workBiblio.ts @@ -0,0 +1,21 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Bibliographic info: `volume`, `issue`, `first_page`, `last_page`. + */ +export interface WorkBiblio { + volume?: string | null; + issue?: string | null; + first_page?: string | null; + last_page?: string | null; +} + diff --git a/webapp/src/app/api/model/workCitationNormalizedPercentile.ts b/webapp/src/app/api/model/workCitationNormalizedPercentile.ts new file mode 100644 index 00000000..a587ddf6 --- /dev/null +++ b/webapp/src/app/api/model/workCitationNormalizedPercentile.ts @@ -0,0 +1,21 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Value } from './value'; + + +/** + * Percentile of citation count normalized by work type, year, and subfield. Includes `value`, `is_in_top_1_percent`, `is_in_top_10_percent`. + */ +export interface WorkCitationNormalizedPercentile { + value?: Value | null; + is_in_top_1_percent?: boolean | null; + is_in_top_10_percent?: boolean | null; +} + diff --git a/webapp/src/app/api/model/workCitedByPercentileYear.ts b/webapp/src/app/api/model/workCitedByPercentileYear.ts new file mode 100644 index 00000000..5257eb3b --- /dev/null +++ b/webapp/src/app/api/model/workCitedByPercentileYear.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Percentile rank compared to other works published in the same year. Contains `min` and `max`. + */ +export interface WorkCitedByPercentileYear { + min?: number | null; + max?: number | null; +} + diff --git a/webapp/src/app/api/model/person-filters.ts b/webapp/src/app/api/model/workCountsByYearInner.ts similarity index 71% rename from webapp/src/app/api/model/person-filters.ts rename to webapp/src/app/api/model/workCountsByYearInner.ts index 625bc459..76d97d77 100644 --- a/webapp/src/app/api/model/person-filters.ts +++ b/webapp/src/app/api/model/workCountsByYearInner.ts @@ -9,8 +9,11 @@ */ -export interface PersonFilters { - institution?: string | null; +/** + * WorkCountsByYearInner + */ +export interface WorkCountsByYearInner { + year?: number | null; cited_by_count?: number | null; } diff --git a/webapp/src/app/api/model/workHasContent.ts b/webapp/src/app/api/model/workHasContent.ts new file mode 100644 index 00000000..44fbe446 --- /dev/null +++ b/webapp/src/app/api/model/workHasContent.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Information about downloadable full-text content: + */ +export interface WorkHasContent { + pdf?: boolean | null; + grobid_xml?: boolean | null; +} + diff --git a/webapp/src/app/api/model/workIds.ts b/webapp/src/app/api/model/workIds.ts new file mode 100644 index 00000000..e8315250 --- /dev/null +++ b/webapp/src/app/api/model/workIds.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. + */ + + +/** + * External identifiers: `openalex`, `doi`, `mag`, `pmid`, `pmcid`. + */ +export interface WorkIds { + openalex?: string | null; + doi?: string | null; + mag?: number | null; + pmid?: string | null; + pmcid?: string | null; +} + diff --git a/webapp/src/app/api/model/workKeyword.ts b/webapp/src/app/api/model/workKeyword.ts new file mode 100644 index 00000000..c9c99afb --- /dev/null +++ b/webapp/src/app/api/model/workKeyword.ts @@ -0,0 +1,21 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Score } from './score'; + + +/** + * WorkKeyword + */ +export interface WorkKeyword { + id?: string | null; + display_name?: string | null; + score?: Score | null; +} + diff --git a/webapp/src/app/api/model/workMeshInner.ts b/webapp/src/app/api/model/workMeshInner.ts new file mode 100644 index 00000000..40633524 --- /dev/null +++ b/webapp/src/app/api/model/workMeshInner.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. + */ + + +/** + * WorkMeshInner + */ +export interface WorkMeshInner { + descriptor_ui?: string | null; + descriptor_name?: string | null; + qualifier_ui?: string | null; + qualifier_name?: string | null; + is_major_topic?: boolean | null; +} + diff --git a/webapp/src/app/api/model/workNetworkNode.ts b/webapp/src/app/api/model/workNetworkNode.ts new file mode 100644 index 00000000..abc04a69 --- /dev/null +++ b/webapp/src/app/api/model/workNetworkNode.ts @@ -0,0 +1,33 @@ +/** + * 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 { WorkTopicInformation } from './workTopicInformation'; +import { CollaborationNetworkNodeType } from './collaborationNetworkNodeType'; + + +export interface WorkNetworkNode { + /** + * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. + */ + raw_id: string; + /** + * The display name of the node. + */ + display_name: string; + /** + * The category of the node, either \'author\', \'institution\', or \'work\'. + */ + category: CollaborationNetworkNodeType; + publication_year: number | null; + work_topics_information: Set | null; +} +export namespace WorkNetworkNode { +} + + diff --git a/webapp/src/app/api/model/workPage.ts b/webapp/src/app/api/model/workPage.ts new file mode 100644 index 00000000..8490c3ab --- /dev/null +++ b/webapp/src/app/api/model/workPage.ts @@ -0,0 +1,35 @@ +/** + * 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 { Work } from './work'; + + +export interface WorkPage { + /** + * Total number of works matching the query + */ + total: number; + /** + * List of works on the current page + */ + elements: Array; + /** + * Offset of the current page + */ + offset: number; + /** + * Size of the current page + */ + size: number; + /** + * Indicates if the current page is the last page + */ + last_page: boolean; +} + diff --git a/webapp/src/app/api/model/workSustainableDevelopmentGoalsInner.ts b/webapp/src/app/api/model/workSustainableDevelopmentGoalsInner.ts new file mode 100644 index 00000000..c9ecd00f --- /dev/null +++ b/webapp/src/app/api/model/workSustainableDevelopmentGoalsInner.ts @@ -0,0 +1,21 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Score } from './score'; + + +/** + * WorkSustainableDevelopmentGoalsInner + */ +export interface WorkSustainableDevelopmentGoalsInner { + id?: string | null; + display_name?: string | null; + score?: Score | null; +} + diff --git a/webapp/src/app/api/model/workTopic.ts b/webapp/src/app/api/model/workTopic.ts new file mode 100644 index 00000000..925ead4f --- /dev/null +++ b/webapp/src/app/api/model/workTopic.ts @@ -0,0 +1,27 @@ +/** + * 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 { Score } from './score'; +import { WorkTopicDomain } from './workTopicDomain'; +import { WorkTopicSubfield } from './workTopicSubfield'; +import { WorkTopicField } from './workTopicField'; + + +/** + * WorkTopic + */ +export interface WorkTopic { + id?: string | null; + display_name?: string | null; + score?: Score | null; + subfield?: WorkTopicSubfield | null; + field?: WorkTopicField | null; + domain?: WorkTopicDomain | null; +} + diff --git a/webapp/src/app/api/model/workTopicDomain.ts b/webapp/src/app/api/model/workTopicDomain.ts new file mode 100644 index 00000000..1a9879d4 --- /dev/null +++ b/webapp/src/app/api/model/workTopicDomain.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * The parent [domain](/api-reference/domains) + */ +export interface WorkTopicDomain { + id?: string | null; + display_name?: string | null; +} + diff --git a/webapp/src/app/api/model/workTopicField.ts b/webapp/src/app/api/model/workTopicField.ts new file mode 100644 index 00000000..1807cfc1 --- /dev/null +++ b/webapp/src/app/api/model/workTopicField.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * The parent [field](/api-reference/fields) + */ +export interface WorkTopicField { + id?: string | null; + display_name?: string | null; +} + diff --git a/webapp/src/app/api/model/workTopicInformation.ts b/webapp/src/app/api/model/workTopicInformation.ts new file mode 100644 index 00000000..ca3b9454 --- /dev/null +++ b/webapp/src/app/api/model/workTopicInformation.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 WorkTopicInformation { + /** + * The ID of the topic. + */ + raw_topic_id: string; + /** + * The name of the topic. + */ + display_name: string; +} + diff --git a/webapp/src/app/api/model/workTopicSubfield.ts b/webapp/src/app/api/model/workTopicSubfield.ts new file mode 100644 index 00000000..b6e7278a --- /dev/null +++ b/webapp/src/app/api/model/workTopicSubfield.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * The parent [subfield](/api-reference/subfields) + */ +export interface WorkTopicSubfield { + id?: string | null; + display_name?: string | null; +} + diff --git a/webapp/src/app/api/model/works-filter-properties.ts b/webapp/src/app/api/model/works-filter-properties.ts new file mode 100644 index 00000000..bd6cc9a4 --- /dev/null +++ b/webapp/src/app/api/model/works-filter-properties.ts @@ -0,0 +1,34 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface WorksFilterProperties { + /** + * The start publication year for the works to include in the collaboration network. + */ + start_year?: number; + /** + * The end publication year for the works to include in the collaboration network. + */ + end_year?: number; + /** + * The list of raw topic IDs to include in the collaboration network. If empty, all topics will be included. + */ + allowed_topics?: Array; + /** + * The minimum number of contributors required for a work to be included in the collaboration network. + */ + min_contributors?: number; + /** + * The maximum number of contributors allowed for a work to be included in the collaboration network. + */ + max_contributors?: number; +} + diff --git a/webapp/src/app/api/model/worksFilterProperties.ts b/webapp/src/app/api/model/worksFilterProperties.ts new file mode 100644 index 00000000..bd6cc9a4 --- /dev/null +++ b/webapp/src/app/api/model/worksFilterProperties.ts @@ -0,0 +1,34 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface WorksFilterProperties { + /** + * The start publication year for the works to include in the collaboration network. + */ + start_year?: number; + /** + * The end publication year for the works to include in the collaboration network. + */ + end_year?: number; + /** + * The list of raw topic IDs to include in the collaboration network. If empty, all topics will be included. + */ + allowed_topics?: Array; + /** + * The minimum number of contributors required for a work to be included in the collaboration network. + */ + min_contributors?: number; + /** + * The maximum number of contributors allowed for a work to be included in the collaboration network. + */ + max_contributors?: number; +} + diff --git a/webapp/src/app/api/model/worksListResponse.ts b/webapp/src/app/api/model/worksListResponse.ts new file mode 100644 index 00000000..a65d3849 --- /dev/null +++ b/webapp/src/app/api/model/worksListResponse.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Meta } from './meta'; +import { Work } from './work'; +import { GroupByResult } from './groupByResult'; + + +/** + * WorksListResponse + */ +export interface WorksListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; +} + diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index c8fe99fe..19a5df19 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -1,6 +1,7 @@ import { Routes } from '@angular/router'; import { userGuard } from './shared/guards/user.guard'; import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver'; +import { personListResolver } from './resolvers/person-list.resolver'; export const routes: Routes = [ { @@ -25,6 +26,43 @@ export const routes: Routes = [ import('./modules/person-list/person-list.component').then( (mod) => mod.PersonListComponent, ), + resolve: { + persons: personListResolver, + }, + runGuardsAndResolvers: (to, from) => { + const keys = [ + 'query', + 'page', + 'pageSize', + 'institutionName', + 'yearFilterEnabled', + 'filterMode', + 'filterYear', + ]; + + // scalar params + const scalarChanged = keys.some( + (key) => to.queryParamMap.get(key) !== from.queryParamMap.get(key), + ); + + // multi-value param: topics + const toTopics = to.queryParamMap.getAll('topic'); + const fromTopics = from.queryParamMap.getAll('topic'); + + const topicsChanged = + toTopics.length !== fromTopics.length || + toTopics.some((t, i) => t !== fromTopics[i]); + + return scalarChanged || topicsChanged; + } + }, + { + path: 'publication/:publicationId', + canActivate: [userGuard], + loadComponent: () => + import('./modules/publication-detail/publication-detail.component').then( + (mod) => mod.PublicationDetailComponent, + ), }, { path: 'person/:id', @@ -58,12 +96,13 @@ export const routes: Routes = [ runGuardsAndResolvers: (to, from) => { // No need to re-run for different table view or search term const keys = [ + 'filter_by', 'start_year', 'end_year', - 'minimum_collaborators', - 'maximum_collaborators', - 'minimum_collaborations', - 'maximum_collaborations', + 'min_contributors', + 'max_contributors', + 'min_collaborations', + 'max_collaborations', 'institutions', 'topics', ]; @@ -89,6 +128,14 @@ export const routes: Routes = [ }, ], }, + { + path: 'institution/:id', + canActivate: [userGuard], + loadComponent: () => + import('./modules/institution/institution.component').then( + (mod) => mod.InstitutionComponent, + ), + }, { path: '**', redirectTo: 'login', diff --git a/webapp/src/app/custom-directives/sk-text.directive.ts b/webapp/src/app/custom-directives/sk-text.directive.ts new file mode 100644 index 00000000..4884dde1 --- /dev/null +++ b/webapp/src/app/custom-directives/sk-text.directive.ts @@ -0,0 +1,51 @@ +import { Directive, OnChanges,Input,ElementRef,Renderer2 } from "@angular/core"; +import { SimpleChanges } from "@angular/core"; +@Directive({ selector: '[skText]', standalone: true }) +export class SkTextDirective implements OnChanges { + @Input() skText = false; + + private originalText = ''; + private originalColor = ''; + + constructor(private el: ElementRef, private renderer: Renderer2) {} + + ngOnChanges(changes: SimpleChanges) { + const change = changes['skText']; + + // skip if value didn't actually change, or is undefined + if (!change) return; + + this.skText ? this.showSkeleton() : this.hideSkeleton(); +} + + private showSkeleton() { + const el: HTMLElement = this.el.nativeElement; + this.originalText = el.textContent ?? ''; + this.originalColor = el.style.color; + + // measure natural width before blanking text + const width = Math.min(Math.max(this.originalText.length * 7.5, 48), 280); + const height = 20; + this.renderer.setStyle(el, 'color', 'transparent'); + this.renderer.setStyle(el, 'background', 'linear-gradient(90deg, #e2e8f0 25%, #f8fafc 50%, #e2e8f0 75%)'); + this.renderer.setStyle(el, 'background-size', '600px 100%'); + this.renderer.setStyle(el, 'animation', 'sk-shimmer 1.6s infinite linear'); + this.renderer.setStyle(el, 'border-radius', '4px'); + this.renderer.setStyle(el, 'min-width', `${width}px`); + this.renderer.setStyle(el, 'max-height', `${height}px`); + this.renderer.setStyle(el, 'display', 'inline-block'); + } + + private hideSkeleton() { + const el: HTMLElement = this.el.nativeElement; + this.renderer.removeStyle(el, 'color'); + this.renderer.removeStyle(el, 'background'); + this.renderer.removeStyle(el, 'background-size'); + this.renderer.removeStyle(el, 'animation'); + this.renderer.removeStyle(el, 'border-radius'); + this.renderer.removeStyle(el, 'min-width'); + this.renderer.removeStyle(el, 'max-height'); + this.renderer.removeStyle(el, 'display'); + + } +} \ No newline at end of file diff --git a/webapp/src/app/modules/institution/institution.component.html b/webapp/src/app/modules/institution/institution.component.html new file mode 100644 index 00000000..06cbe4a2 --- /dev/null +++ b/webapp/src/app/modules/institution/institution.component.html @@ -0,0 +1 @@ +

institution works!

diff --git a/webapp/src/app/modules/institution/institution.component.scss b/webapp/src/app/modules/institution/institution.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/modules/institution/institution.component.ts b/webapp/src/app/modules/institution/institution.component.ts new file mode 100644 index 00000000..0cdeb3de --- /dev/null +++ b/webapp/src/app/modules/institution/institution.component.ts @@ -0,0 +1,11 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-institution', + imports: [], + templateUrl: './institution.component.html', + styleUrl: './institution.component.scss', +}) +export class InstitutionComponent { + +} diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html new file mode 100644 index 00000000..5107366d --- /dev/null +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -0,0 +1,70 @@ +
+ + +
+ {{ getInitials(person.display_name) }} +
+
+
+ @if (person.relevance_rating) { + + {{ person.relevance_rating }} + + } + +
+

{{ person.display_name }}

+

{{ getDistinguishingId(person) }}

+

+ Publikationen: {{ person.works_count }} · + Zitationen: {{ person.cited_by_count }} +

+
+
+ +
+ @if (institution(person); as inst) { +
+ + apartment + {{ (inst.display_name ?? '') | truncate: 30 }} + @if (inst.country_code && !loading) { + + {{ inst.country_code.toUpperCase() + }} + } + +
+ } + +
+ @for (topic of topics(person); track topic.id) { + {{ topic.display_name }} + } +
+
+ + +
\ No newline at end of file diff --git a/webapp/src/app/modules/person-card/person-card.component.scss b/webapp/src/app/modules/person-card/person-card.component.scss new file mode 100644 index 00000000..cb82fcb0 --- /dev/null +++ b/webapp/src/app/modules/person-card/person-card.component.scss @@ -0,0 +1,231 @@ +:host { + display: flex; + flex-direction: column; + height: 100%; +} + +.person-card { + background: var(--sg-surface); + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + box-shadow: var(--sg-shadow-sm); + display: flex; + flex-direction: column; + height: 100%; + transition: transform 0.15s ease, box-shadow 0.15s ease; + + &:hover { + transform: translateY(-2px); + box-shadow: var(--sg-shadow-md); + } +} + +.card-header { + padding: 16px; + display: flex; + gap: 12px; + border-bottom: 1px solid var(--sg-surface-soft); + text-decoration: none; + color: inherit; + cursor: pointer; + + .avatar { + width: 40px; + height: 40px; + border-radius: 50%; + background: var(--sg-primary-soft); + color: var(--sg-primary); + font-size: 14px; + font-weight: 700; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + border: 1px solid var(--sg-border); + } + + .header-main { + flex-grow: 1; + min-width: 0; + } +} + +.rating-and-bookmark { + display: flex; + justify-content: space-between; + align-items: center; +} + +.suitability-badge { + font-size: 10px; + font-weight: 700; + padding: 2px 6px; + border-radius: 8px; + text-transform: uppercase; + + &.very-suitable { + background: var(--sg-success-soft); + color: var(--sg-success); + } + + &.suitable { + background: var(--sg-warning-soft); + color: var(--sg-warning); + } + + &.possible { + background: var(--sg-primary-soft); + color: var(--sg-text-muted); + } +} + +.bookmark-btn { + border: none; + background: transparent; + cursor: pointer; + padding: 2px; + color: var(--sg-text-soft); + + &:hover { + color: var(--sg-primary); + } + + &.bookmarked { + color: #e53935; + } + + mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } +} + +.person-name { + margin: 6px 0 2px; + font-size: 16px; + font-weight: 600; + color: var(--sg-text); +} +.institution { + display: flex; + align-items: center; + gap: 6px; + margin: 0; + font-size: 12px; + color: var(--sg-text-muted); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.institution-tag { + background: var(--sg-primary-soft); + border: 1px solid var(--sg-primary-border, var(--sg-border)); + color: var(--sg-primary); + font-size: 10px; + font-weight: 600; + padding: 2px 6px; + border-radius: 4px; + cursor: pointer; + display: inline-flex; + align-items: center; + transition: all 0.2s ease; + + &:hover { + background: var(--sg-primary); + color: #fff; + border-color: var(--sg-primary); + } +} + +.flag-img { + border: 1px solid; + vertical-align: -10px; +} + +.person-id { + margin: 2px 0 0; + font-size: 10px; + color: var(--sg-text-soft); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.stats { + margin: 4px 0 0; + font-size: 10px; + color: var(--sg-text-muted); +} + +.card-body { + padding: 16px; + flex-grow: 1; + display: flex; + flex-direction: column; + gap: 12px; + justify-content: space-between; +} + +.topic-row { + display: flex; + flex-wrap: wrap; + gap: 4px; +} + +.topic-tag { + background: var(--sg-surface-soft); + border: 1px solid var(--sg-border); + color: var(--sg-text-muted); + font-size: 10px; + font-weight: 600; + padding: 2px 6px; + border-radius: 4px; + cursor: pointer; + transition: all 0.2s ease; + + &:hover { + background: var(--sg-primary-soft); + border-color: var(--sg-primary); + color: var(--sg-primary); + } +} + +.card-footer { + padding: 10px 12px; + border-top: 1px solid var(--sg-border); + background: var(--sg-surface-muted); +} + +.action-buttons { + display: flex; + gap: 6px; +} + +.action-btn { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + gap: 4px; + padding: 6px; + background: var(--sg-surface); + border: 1px solid var(--sg-border-strong); + border-radius: var(--sg-radius-sm); + color: var(--sg-text-muted); + font-size: 10px; + font-weight: 600; + text-decoration: none; + + mat-icon { + font-size: 12px; + width: 12px; + height: 12px; + } + + &:hover { + background: var(--sg-primary-soft); + color: var(--sg-primary); + } +} diff --git a/webapp/src/app/modules/person-card/person-card.component.spec.ts b/webapp/src/app/modules/person-card/person-card.component.spec.ts new file mode 100644 index 00000000..ae9e9037 --- /dev/null +++ b/webapp/src/app/modules/person-card/person-card.component.spec.ts @@ -0,0 +1,30 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { PersonCardComponent } from './person-card.component'; + +describe('PersonCardComponent', () => { + let component: PersonCardComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [PersonCardComponent] + }) + .compileComponents(); + + fixture = TestBed.createComponent(PersonCardComponent); + component = fixture.componentInstance; + component.person = { + id: 'mock-id', + display_name: 'Test Author', + works_count: 5, + cited_by_count: 10, + topics: [] + } as any; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts new file mode 100644 index 00000000..a384b76a --- /dev/null +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -0,0 +1,74 @@ +import { Component, Input, Output, EventEmitter } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { RouterLink } from '@angular/router'; +import { MatIconModule } from '@angular/material/icon'; +import { CustomAuthor, DehydratedInstitution, WorkTopic } from '../../api'; +import { TruncatePipe } from '../../shared/pipes/truncate.pipe'; +import { SkTextDirective } from '../../custom-directives/sk-text.directive'; +@Component({ + selector: 'app-person-card', + standalone: true, + imports: [CommonModule, RouterLink, MatIconModule, TruncatePipe,SkTextDirective], + templateUrl: './person-card.component.html', + styleUrl: './person-card.component.scss', +}) +export class PersonCardComponent { + @Input({ required: true }) person!: CustomAuthor; + @Input() isBookmarked = false; + @Input() loading = false; + @Output() bookmarkToggle = new EventEmitter(); + @Output() topicClick = new EventEmitter(); + @Output() institutionClick = new EventEmitter(); + + getInitials(name: string | null | undefined): string { + if (!name) return 'U'; + const cleanName = name.replace(/Prof\.|Dr\.|M\.Sc\./g, '').trim(); + const parts = cleanName.split(' '); + const first = parts[0]?.[0] || ''; + const last = parts[parts.length - 1]?.[0] || ''; + return (first + last).toUpperCase(); + } + + getRatingClass(rating: string | null | undefined): string { + const r = (rating || '').toLowerCase(); + if (r === 'sehr geeignet') return 'very-suitable'; + if (r === 'geeignet') return 'suitable'; + return 'possible'; + } + + institution(person: CustomAuthor): DehydratedInstitution | undefined { + return ( + person.last_known_institutions?.[0] || + person.affiliations?.[person.affiliations.length - 1]?.institution || + undefined + ); + } + + topics(person: CustomAuthor): WorkTopic[] { + return (person.topics ?? []) + .filter((t): t is WorkTopic => !!t.display_name) + .slice(0, 3); + } + + getTopicTooltip(topic: WorkTopic): string { + const parts: string[] = []; + if (topic.domain?.display_name) parts.push(topic.domain.display_name); + if (topic.field?.display_name) parts.push(topic.field.display_name); + if (topic.subfield?.display_name) parts.push(topic.subfield.display_name); + + if (parts.length === 0) return topic.display_name || ''; + return parts.join(' - '); + } + + getDistinguishingId(person: CustomAuthor): string { + if (!person) return ''; + if (person.orcid) { + return person.orcid.replace('https://orcid.org/', ''); + } + return ''; + } + + toggleBookmark(): void { + this.bookmarkToggle.emit(this.person); + } +} diff --git a/webapp/src/app/modules/person-list/person-list.component.html b/webapp/src/app/modules/person-list/person-list.component.html index 2b9d5f40..789862a8 100644 --- a/webapp/src/app/modules/person-list/person-list.component.html +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -10,11 +10,11 @@ Durchsuchen Sie OpenAlex-Autorinnen und -Autoren nach Namen, Themen oder Kennungen.

- @if (state.searchValue()) { + @if (searchValue()) {
Aktive Suche - „{{ state.searchValue() }}“ + „{{ searchValue() }}“
-
-

{{ person.display_name }}

-

{{ institution(person)?.display_name }} -

-

{{ getDistinguishingId(person) }}

-

- Publikationen: {{ person.works_count }} · - Zitationen: {{ person.cited_by_count }} -

- - - -
-
- @for (topic of topics(person); track topic) { - {{ topic }} - } -
-
- - - + + } } @else { @@ -138,28 +83,11 @@ } - - @if (totalPages > 1) { -
- - -
- @for (p of pageList; track p) { - - } -
- - -
- } + + + @@ -193,11 +121,25 @@

Institution

- business - + apartment + + + @for (institution of institutionOptions(); track institution.id) { + + {{ institution.display_name }} + @if (institution.hint) { + {{ institution.hint }} + } + + } + @if (!institutionLookupLoading() && institutionOptions().length === 0 && institutionControl.value && + institutionControl.value.trim().length >= 2) { + Keine Institution gefunden + } + @if (institutionControl.value) { - } @@ -236,8 +178,8 @@ diff --git a/webapp/src/app/modules/person-list/person-list.component.scss b/webapp/src/app/modules/person-list/person-list.component.scss index 2c0c5e8f..a605117a 100644 --- a/webapp/src/app/modules/person-list/person-list.component.scss +++ b/webapp/src/app/modules/person-list/person-list.component.scss @@ -168,221 +168,7 @@ gap: 20px; } -.person-card { - background: var(--sg-surface); - border: 1px solid var(--sg-border); - border-radius: var(--sg-radius-sm); - box-shadow: var(--sg-shadow-sm); - display: flex; - flex-direction: column; - transition: transform 0.15s ease, box-shadow 0.15s ease; - &:hover { - transform: translateY(-2px); - box-shadow: var(--sg-shadow-md); - } -} - -.card-header { - padding: 16px; - display: flex; - gap: 12px; - border-bottom: 1px solid var(--sg-surface-soft); - - .avatar { - width: 40px; - height: 40px; - border-radius: 50%; - background: var(--sg-primary-soft); - color: var(--sg-primary); - font-size: 14px; - font-weight: 700; - display: flex; - align-items: center; - justify-content: center; - flex-shrink: 0; - border: 1px solid var(--sg-border); - } - - .header-main { - flex-grow: 1; - min-width: 0; - } -} - -.rating-and-bookmark { - display: flex; - justify-content: space-between; - align-items: center; -} - -.suitability-badge { - font-size: 10px; - font-weight: 700; - padding: 2px 6px; - border-radius: 8px; - text-transform: uppercase; - - &.very-suitable { - background: var(--sg-success-soft); - color: var(--sg-success); - } - - &.suitable { - background: var(--sg-warning-soft); - color: var(--sg-warning); - } - - &.possible { - background: var(--sg-primary-soft); - color: var(--sg-text-muted); - } -} - -.bookmark-btn { - border: none; - background: transparent; - cursor: pointer; - padding: 2px; - color: var(--sg-text-soft); - - &:hover { - color: var(--sg-primary); - } - - &.bookmarked { - color: #e53935; - } - - mat-icon { - font-size: 18px; - width: 18px; - height: 18px; - } -} - -.person-name { - margin: 6px 0 2px; - font-size: 16px; - font-weight: 600; - color: var(--sg-text); -} - -.institution { - display: flex; - align-items: center; - gap: 15px; - margin: 0; - font-size: 12px; - color: var(--sg-text-muted); - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.flag-img { - border: 1px solid; - vertical-align: -10px; -} - -.person-id { - margin: 2px 0 0; - font-size: 10px; - color: var(--sg-text-soft); - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.stats { - margin: 4px 0 0; - font-size: 10px; - color: var(--sg-text-muted); -} - -.card-body { - padding: 16px; - flex-grow: 1; - display: flex; - flex-direction: column; - gap: 12px; - justify-content: space-between; -} - -.experience-list { - list-style: none; - padding: 0; - margin: 0; - - li { - font-size: 12px; - color: var(--sg-text-muted); - position: relative; - padding-left: 12px; - margin-bottom: 4px; - - &::before { - content: "•"; - position: absolute; - left: 0; - color: var(--sg-text-soft); - } - } -} - -.topic-row { - display: flex; - flex-wrap: wrap; - gap: 4px; -} - -.topic-tag { - background: var(--sg-surface-soft); - border: 1px solid var(--sg-border); - color: var(--sg-text-muted); - font-size: 10px; - font-weight: 600; - padding: 2px 6px; - border-radius: 4px; -} - -.card-footer { - padding: 10px 12px; - border-top: 1px solid var(--sg-border); - background: var(--sg-surface-muted); -} - -.action-buttons { - display: flex; - gap: 6px; -} - -.action-btn { - flex: 1; - display: flex; - align-items: center; - justify-content: center; - gap: 4px; - padding: 6px; - background: var(--sg-surface); - border: 1px solid var(--sg-border-strong); - border-radius: var(--sg-radius-sm); - color: var(--sg-text-muted); - font-size: 10px; - font-weight: 600; - text-decoration: none; - - mat-icon { - font-size: 12px; - width: 12px; - height: 12px; - } - - &:hover { - background: var(--sg-primary-soft); - color: var(--sg-primary); - } -} .empty-state { display: flex; @@ -412,70 +198,11 @@ } } -.custom-pagination { - display: flex; - align-items: center; - justify-content: center; - gap: 12px; - padding-top: 16px; -} - -.paginator-btn { - display: flex; - align-items: center; - gap: 4px; - padding: 6px 12px; - background: var(--sg-surface); - border: 1px solid var(--sg-border); - border-radius: var(--sg-radius-sm); +mat-paginator { + background: transparent !important; + border-top: 1px solid var(--sg-border); + margin-top: 16px; color: var(--sg-text); - font-size: 12px; - font-weight: 600; - cursor: pointer; - - mat-icon { - font-size: 16px; - width: 16px; - height: 16px; - } - - &:hover:not(:disabled) { - background: var(--sg-surface-soft); - } - - &:disabled { - opacity: 0.5; - cursor: not-allowed; - } -} - -.page-numbers { - display: flex; - gap: 4px; -} - -.page-number-btn { - width: 32px; - height: 32px; - border-radius: 50%; - border: none; - background: transparent; - color: var(--sg-text-muted); - font-size: 12px; - font-weight: 600; - cursor: pointer; - display: flex; - align-items: center; - justify-content: center; - - &:hover { - background: var(--sg-surface-soft); - } - - &.active { - background: var(--sg-primary); - color: #fff; - } } .filters-sidebar { @@ -567,50 +294,6 @@ } } -.checkbox-list { - display: flex; - flex-direction: column; - gap: 8px; -} - -.checkbox-label { - display: flex; - align-items: center; - gap: 8px; - cursor: pointer; - - input[type="checkbox"] { - accent-color: var(--sg-primary); - width: 15px; - height: 15px; - cursor: pointer; - } - - .checkbox-text { - font-size: 12px; - color: var(--sg-text); - } -} - -.show-more-btn { - display: flex; - align-items: center; - gap: 2px; - background: transparent; - border: none; - cursor: pointer; - color: var(--sg-text-muted); - font-size: 11px; - font-weight: 700; - padding: 2px 0; - - mat-icon { - font-size: 14px; - width: 14px; - height: 14px; - } -} - .sidebar-footer { padding-top: 12px; border-top: 1px solid var(--sg-border); @@ -638,6 +321,13 @@ } } +::ng-deep .mat-mdc-option small { + display: block; + color: var(--sg-text-muted); + font-size: 11px; + line-height: 1.2; +} + @media (max-width: 1024px) { .layout-container { grid-template-columns: 1fr; diff --git a/webapp/src/app/modules/person-list/person-list.component.ts b/webapp/src/app/modules/person-list/person-list.component.ts index 6be52be4..b1afc0f0 100644 --- a/webapp/src/app/modules/person-list/person-list.component.ts +++ b/webapp/src/app/modules/person-list/person-list.component.ts @@ -1,32 +1,39 @@ -import { Component, inject, signal, DestroyRef } from '@angular/core'; +import { Component, inject, signal, DestroyRef, Signal } from '@angular/core'; import { Router, RouterLink, ActivatedRoute } from '@angular/router'; import { CommonModule } from '@angular/common'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; - import { MatIconModule } from '@angular/material/icon'; -import { MatPaginatorModule } from '@angular/material/paginator'; +import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatButtonModule } from '@angular/material/button'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatRadioModule } from '@angular/material/radio'; -import { CustomAuthor } from '../../api/model/custom-author'; -// import { PersonsSearchService } from '../../api/api/persons-search.service'; -import { DehydratedInstitution, PersonsService } from '../../api'; + +import { CustomAuthor, DehydratedInstitution, PersonsService, InstitutionsService } from '../../api'; import { TopicsService } from '../../api/api/topics.service'; import { TopicHierarchyComponent } from '../topic-hierarchy/topic-hierarchy.component'; +import { PersonCardComponent } from '../person-card/person-card.component'; import { SharedStateService } from '../../shared/services/shared-state.service'; import { PaginationService } from '../../shared/services/pagination.service'; -import { finalize } from 'rxjs'; +import { finalize, debounceTime, distinctUntilChanged, switchMap, map, of, catchError } from 'rxjs'; +import { MatAutocompleteModule, MatAutocompleteSelectedEvent } from '@angular/material/autocomplete'; import { MatSnackBar } from '@angular/material/snack-bar'; +import { SkTextDirective } from '../../custom-directives/sk-text.directive'; +import { + NavigationError, + NavigationEnd, + NavigationStart, + NavigationCancel, +} from '@angular/router'; +import { createLoadError } from '../../shared/utils/errorHandler'; @Component({ selector: 'app-person-list', imports: [ CommonModule, - RouterLink, ReactiveFormsModule, MatIconModule, MatPaginatorModule, @@ -37,6 +44,9 @@ import { MatSnackBar } from '@angular/material/snack-bar'; MatCheckboxModule, MatRadioModule, TopicHierarchyComponent, + PersonCardComponent, + SkTextDirective, + MatAutocompleteModule, ], templateUrl: './person-list.component.html', styleUrl: './person-list.component.scss', @@ -47,11 +57,10 @@ export class PersonListComponent { private readonly route = inject(ActivatedRoute); private readonly personsService = inject(PersonsService); private readonly topicsService = inject(TopicsService); + private readonly institutionsService = inject(InstitutionsService); private readonly destroyRef = inject(DestroyRef); - private readonly snackBar = inject(MatSnackBar); public readonly state = inject(SharedStateService); public readonly paginationService = inject(PaginationService); - private readonly defaultIncludes = 'display_name,works_count,cited_by_count,topics,orcid,relevance_rating,last_known_institutions,affiliations'; @@ -59,51 +68,84 @@ export class PersonListComponent { persons: CustomAuthor[] = []; total = 0; currentPage = 1; + readonly institutionOptions = signal([]); + readonly institutionLookupLoading = signal(false); // Selected filter states selectedTopics = new Set(); + searchValue = signal(null); - // Filter checklists - readonly defaultTopics = [ - 'Artificial Intelligence', - 'Big Data and Business Intelligence', - 'Topic Modeling', - 'Entrepreneurship Studies and Influences', - 'Complex Network Analysis Techniques', - 'Semantic Web and Ontologies', - 'Machine Learning', - 'Data Science', - 'Nachhaltigkeit', - 'Entrepreneurship' - ]; + // Applied filter states (reflecting actual URL query params) + appliedInstitutionName = ''; + appliedYearFilterEnabled = false; + appliedFilterMode: 'in' | 'from' = 'from'; + appliedFilterYear = new Date().getFullYear() - 1; // Forms - sortControl = new FormControl('relevance', { nonNullable: true }); + sortControl = new FormControl('works', { nonNullable: true }); topicSearchControl = new FormControl('', { nonNullable: true }); institutionControl = new FormControl('', { nonNullable: true }); yearFilterEnabledControl = new FormControl(false, { nonNullable: true }); - filterModeControl = new FormControl<'in' | 'from'>('from', { nonNullable: true }); + filterModeControl = new FormControl<'in' | 'from'>('from', { + nonNullable: true, + }); filterYearControl = new FormControl(new Date().getFullYear() - 1, { nonNullable: true, - validators: [Validators.min(1900), Validators.max(new Date().getFullYear())] + validators: [ + Validators.min(1900), + Validators.max(new Date().getFullYear()), + ], }); - showAllTopics = false; // Bookmarking bookmarkedIds = new Set(); - constructor() { - // Subscribe to route query parameters to trigger searches + this.router.events + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((event) => { + if (event instanceof NavigationStart) { + this.loadingState.set(true); + } + + if ( + event instanceof NavigationEnd || + event instanceof NavigationCancel || + event instanceof NavigationError + ) { + this.loadingState.set(false); + } + }); + + if (!this.institutionControl.value) { + this.yearFilterEnabledControl.disable(); + } + + this.setupInstitutionAutocomplete(); + // Enable/disable the year filter checkbox based on the presence of an institution value + this.updateYearFilterState(this.institutionControl.value); + this.institutionControl.valueChanges + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((val) => { + this.updateYearFilterState(val); + }); + this.route.queryParams .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((params) => { const query = params['query'] || ''; const page = params['page'] ? Number.parseInt(params['page'], 10) : 1; - const pageSize = params['pageSize'] ? Number.parseInt(params['pageSize'], 10) : 10; + const pageSize = params['pageSize'] + ? Number.parseInt(params['pageSize'], 10) + : 10; const institutionName = params['institutionName'] || ''; const yearFilterEnabled = params['yearFilterEnabled'] === 'true'; - const filterMode = (params['filterMode'] === 'in' || params['filterMode'] === 'from') ? params['filterMode'] : 'from'; - const filterYear = params['filterYear'] ? Number.parseInt(params['filterYear'], 10) : (new Date().getFullYear() - 1); + const filterMode = + params['filterMode'] === 'in' || params['filterMode'] === 'from' + ? params['filterMode'] + : 'from'; + const filterYear = params['filterYear'] + ? Number.parseInt(params['filterYear'], 10) + : new Date().getFullYear() - 1; const topics = this.parseQueryParamArray(params['topic']); @@ -112,11 +154,12 @@ export class PersonListComponent { this.paginationService.selection = pageSize; // Sync search box & institution input - if (this.state.searchValue() !== query) { - this.state.searchValue.set(query || null); + if (this.searchValue() !== query) { + this.searchValue.set(query || null); } if (this.institutionControl.value !== institutionName) { - this.institutionControl.setValue(institutionName); + this.institutionControl.setValue(institutionName, { emitEvent: false }); + this.updateYearFilterState(institutionName); } if (this.yearFilterEnabledControl.value !== yearFilterEnabled) { this.yearFilterEnabledControl.setValue(yearFilterEnabled); @@ -128,45 +171,20 @@ export class PersonListComponent { this.filterYearControl.setValue(filterYear); } - this.load(query, page, pageSize, topics, institutionName, yearFilterEnabled, filterMode, filterYear); + // Update applied filter states + this.appliedInstitutionName = institutionName; + this.appliedYearFilterEnabled = yearFilterEnabled; + this.appliedFilterMode = filterMode; + this.appliedFilterYear = filterYear; }); - } - load( - query?: string, - page: number = 1, - pageSize: number = 10, - topics?: string[], - institutionName?: string, - yearFilterEnabled: boolean = false, - filterMode: 'in' | 'from' = 'from', - filterYear?: number - ): void { - this.loadingState.set(true); - - this.personsService.searchPersonsList( - query || undefined, - institutionName || undefined, - topics?.length ? topics : undefined, - page, - pageSize, - this.defaultIncludes, - yearFilterEnabled ? true : undefined, - yearFilterEnabled ? filterMode : undefined, - yearFilterEnabled ? filterYear : undefined - ) - .pipe( - finalize(() => this.loadingState.set(false)), - takeUntilDestroyed(this.destroyRef) - ) - .subscribe({ - next: (response) => { - this.persons = (response.results ?? []) as CustomAuthor[]; - this.total = response.meta?.count ?? 0; - }, - error: (err) => { - console.error('Error loading persons:', err); - } + // Use resolver value + this.route.data + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(({ persons }) => { + this.persons = (persons.results ?? []) as CustomAuthor[]; + this.total = persons.meta?.count; + this.loadingState.set(false); }); } @@ -177,39 +195,17 @@ export class PersonListComponent { if (val === 'works') { return sorted.sort((a, b) => (b.works_count ?? 0) - (a.works_count ?? 0)); } else if (val === 'citations') { - return sorted.sort((a, b) => (b.cited_by_count ?? 0) - (a.cited_by_count ?? 0)); + return sorted.sort( + (a, b) => (b.cited_by_count ?? 0) - (a.cited_by_count ?? 0), + ); } - return sorted; // relevance (Elasticsearch default order) + return sorted; } get loading(): boolean { return this.loadingState(); } - // Topics checklist processing - get topicsList(): string[] { - const set = new Set(this.defaultTopics); - this.persons.forEach(p => { - p.topics?.forEach(t => { - if (t.display_name) set.add(t.display_name); - }); - }); - return Array.from(set); - } - - get filteredTopicsList(): string[] { - const filter = this.topicSearchControl.value.toLowerCase().trim(); - let list = this.topicsList; - if (filter) { - list = list.filter(t => t.toLowerCase().includes(filter)); - } - return this.showAllTopics ? list : list.slice(0, 5); - } - - toggleShowAllTopics(): void { - this.showAllTopics = !this.showAllTopics; - } - // Filter selection checks isTopicSelected(topic: string): boolean { return this.selectedTopics.has(topic); @@ -225,31 +221,37 @@ export class PersonListComponent { } // Active filters tags row - get activeFilters(): Array<{ category: string, value: string, label: string }> { - const list: Array<{ category: string, value: string, label: string }> = []; - this.selectedTopics.forEach(t => { - list.push({ category: 'topic', value: t, label: t }); + get activeFilters(): Array<{ + category: string; + value: string; + label: string; + }> { + const list: Array<{ category: string; value: string; label: string }> = []; + this.selectedTopics.forEach((t) => { + list.push({ category: 'topic', value: t, label: `Thema: ${t}` }); }); - if (this.institutionControl.value) { - let label = `Institution: ${this.institutionControl.value}`; - if (this.yearFilterEnabledControl.value) { - const modeLabel = this.filterModeControl.value === 'in' ? 'in' : 'from'; - label += ` (${modeLabel} ${this.filterYearControl.value})`; + if (this.appliedInstitutionName) { + let label = `Institution: ${this.appliedInstitutionName}`; + if (this.appliedYearFilterEnabled) { + const modeLabel = this.appliedFilterMode === 'in' ? 'in' : 'from'; + label += ` (${modeLabel} ${this.appliedFilterYear})`; } list.push({ category: 'institutionName', - value: this.institutionControl.value, - label: label + value: this.appliedInstitutionName, + label: label, }); } return list; } - removeFilter(filter: { category: string, value: string }): void { + removeFilter(filter: { category: string; value: string }): void { if (filter.category === 'topic') { this.selectedTopics.delete(filter.value); } else if (filter.category === 'institutionName') { - this.institutionControl.setValue(''); + this.institutionControl.setValue('', { emitEvent: false }); + this.updateYearFilterState(''); + this.institutionOptions.set([]); this.yearFilterEnabledControl.setValue(false); this.filterModeControl.setValue('from'); this.filterYearControl.setValue(new Date().getFullYear() - 1); @@ -259,7 +261,9 @@ export class PersonListComponent { clearAllFilters(): void { this.selectedTopics.clear(); - this.institutionControl.setValue(''); + this.institutionControl.setValue('', { emitEvent: false }); + this.updateYearFilterState(''); + this.institutionOptions.set([]); this.yearFilterEnabledControl.setValue(false); this.filterModeControl.setValue('from'); this.filterYearControl.setValue(new Date().getFullYear() - 1); @@ -272,11 +276,22 @@ export class PersonListComponent { } this.router.navigate([], { queryParams: { - topic: this.selectedTopics.size ? Array.from(this.selectedTopics) : null, + topic: this.selectedTopics.size + ? Array.from(this.selectedTopics) + : null, institutionName: this.institutionControl.value || null, - yearFilterEnabled: this.institutionControl.value && this.yearFilterEnabledControl.value ? 'true' : null, - filterMode: this.institutionControl.value && this.yearFilterEnabledControl.value ? this.filterModeControl.value : null, - filterYear: this.institutionControl.value && this.yearFilterEnabledControl.value ? this.filterYearControl.value : null, + yearFilterEnabled: + this.institutionControl.value && this.yearFilterEnabledControl.value + ? 'true' + : null, + filterMode: + this.institutionControl.value && this.yearFilterEnabledControl.value + ? this.filterModeControl.value + : null, + filterYear: + this.institutionControl.value && this.yearFilterEnabledControl.value + ? this.filterYearControl.value + : null, strict: null, page: 1, }, @@ -284,51 +299,14 @@ export class PersonListComponent { }); } - // Pagination custom calculation - get totalPages(): number { - return Math.max(1, Math.ceil(this.total / this.paginationService.selection)); - } - - get pageList(): number[] { - const list: number[] = []; - const maxPagesToShow = 5; - let start = Math.max(1, this.currentPage - 2); - let end = Math.min(this.totalPages, start + maxPagesToShow - 1); - - if (end - start + 1 < maxPagesToShow) { - start = Math.max(1, end - maxPagesToShow + 1); - } - - for (let i = start; i <= end; i++) { - list.push(i); - } - return list; - } - - isFirstPage(): boolean { - return this.currentPage === 1; - } - - isLastPage(): boolean { - return this.currentPage >= this.totalPages; - } - - prevPage(): void { - if (!this.isFirstPage()) { - this.goToPage(this.currentPage - 1); - } - } - - nextPage(): void { - if (!this.isLastPage()) { - this.goToPage(this.currentPage + 1); - } - } - - goToPage(p: number): void { + onPageChange(event: PageEvent): void { + this.paginationService.selection = event.pageSize; this.router.navigate([], { - queryParams: { page: p }, - queryParamsHandling: 'merge' + queryParams: { + page: event.pageIndex + 1, + pageSize: event.pageSize, + }, + queryParamsHandling: 'merge', }); } @@ -339,36 +317,7 @@ export class PersonListComponent { return `${start}-${end} von ${this.total} Personen`; } - institution(person: CustomAuthor): DehydratedInstitution | undefined { - return ( - person.last_known_institutions?.[0] || - person.affiliations?.[person.affiliations.length - 1]?.institution || - undefined - ); - } - topics(person: CustomAuthor): string[] { - return (person.topics ?? []) - .map((t) => t.display_name) - .filter((name): name is string => !!name) - .slice(0, 3); - } - - getInitials(name: string | null | undefined): string { - if (!name) return 'U'; - const cleanName = name.replace(/Prof\.|Dr\.|M\.Sc\./g, '').trim(); - const parts = cleanName.split(' '); - const first = parts[0]?.[0] || ''; - const last = parts[parts.length - 1]?.[0] || ''; - return (first + last).toUpperCase(); - } - - getRatingClass(rating: string | null | undefined): string { - const r = (rating || '').toLowerCase(); - if (r === 'sehr geeignet') return 'very-suitable'; - if (r === 'geeignet') return 'suitable'; - return 'possible'; - } // Bookmarks toggleBookmark(person: CustomAuthor): void { @@ -385,24 +334,84 @@ export class PersonListComponent { this.applySidebarFilters(); } + onCardTopicClick(topic: string): void { + this.topicSearchControl.setValue(topic); + } + + onCardInstitutionClick(institutionName: string): void { + this.institutionControl.setValue(institutionName, { emitEvent: false }); + this.updateYearFilterState(institutionName); + this.institutionOptions.set([]); + this.applySidebarFilters(); + } + isBookmarked(person: CustomAuthor): boolean { return !!person.id && this.bookmarkedIds.has(person.id); } clearSearch(): void { - this.state.searchValue.set(null); + this.searchValue.set(null); this.router.navigate([], { queryParams: { query: null, page: 1 }, - queryParamsHandling: 'merge', + queryParamsHandling:"merge", }); } - getDistinguishingId(person: CustomAuthor): string { - if (!person) return ''; - if (person.orcid) { - return person.orcid.replace('https://orcid.org/', ''); + + + private setupInstitutionAutocomplete(): void { + this.institutionControl.valueChanges + .pipe( + debounceTime(250), + map((value) => (typeof value === 'string' ? value.trim() : '')), + distinctUntilChanged(), + switchMap((query) => { + if (query.length < 2) { + this.institutionOptions.set([]); + return of([]); + } + this.institutionLookupLoading.set(true); + return this.searchInstitutions(query).pipe( + catchError(() => of([])), + finalize(() => { + this.institutionLookupLoading.set(false); + }), + ); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((options) => { + this.institutionOptions.set(options); + }); + } + + private searchInstitutions(query: string) { + return this.institutionsService.autocompleteInstitutions(query, undefined, undefined, 10) + .pipe(map((response) => response.results ?? [])); + } + + updateYearFilterState(val: string): void { + if (!val) { + this.yearFilterEnabledControl.disable(); + this.yearFilterEnabledControl.setValue(false); + } else { + this.yearFilterEnabledControl.enable(); } - return ''; + } + + clearInstitutionFilter(): void { + this.institutionControl.setValue('', { emitEvent: false }); + this.updateYearFilterState(''); + this.institutionOptions.set([]); + this.applySidebarFilters(); + } + + onInstitutionSelected(event: MatAutocompleteSelectedEvent): void { + const val = event.option.value; + this.institutionControl.setValue(val, { emitEvent: false }); + this.updateYearFilterState(val); + this.institutionOptions.set([]); + this.applySidebarFilters(); } private parseQueryParamArray(val: any): string[] { diff --git a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.html b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.html index 174e3857..c01f8cec 100644 --- a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.html +++ b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.html @@ -1,9 +1,5 @@
- - - - @@ -39,15 +35,18 @@ >
ID{{ element.id }} Name @@ -19,13 +15,13 @@ - +
+@if (dataSource.filteredData.length === 0) { +

Keine Kollaborierenden gefunden.

+}
diff --git a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.scss b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.scss index efec585e..4dfb4f9e 100644 --- a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.scss +++ b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.scss @@ -1,60 +1,11 @@ -.content { - display: flex; - flex-direction: row; - padding: 40px; - gap: 20px; - max-height: 1000px; -} - -.graph { - width: 75vh; - height: 75vh; -} - .table { overflow: auto; width: 100%; - max-height: 1000px; - height: 1200px; + max-height: 100%; } -.table table { - width: 100%; -} - -.table-area { - width: 100%; - height: 100%; - display: flex; - flex-direction: column; -} - -.scroll-viewport-container { - width: 100%; - height: 100%; -} - -.form-controls { - display: flex; - flex-direction: row; - align-items: flex-start; - gap: 10px; -} - -.form-field-full { - width: 100%; -} - -.right-card { - width: 100%; -} - -.toggle-group { - margin-bottom: 20px; -} - -.toggle-group .mat-button-toggle { - text-transform: none; +.mat-mdc-table { + background-color: var(--sg-background); } .element-row { @@ -75,5 +26,13 @@ .detail-row { width: 100%; +} -} \ No newline at end of file +.work-link { + color: var(--sg-primary); + text-decoration: none; + + &:hover { + text-decoration: underline; + } +} diff --git a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.ts b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.ts index 6138705f..f86545d4 100644 --- a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.ts +++ b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.ts @@ -43,7 +43,7 @@ export class PersonNetworkCollaboratorsComponent implements AfterViewInit { collaborationNetwork = input.required(); searchTerm = input.required(); - displayedColumns: string[] = ['id', 'name', 'count', 'actions']; + displayedColumns: string[] = ['name', 'count', 'actions']; dataSource = new MatTableDataSource(); @@ -101,8 +101,7 @@ export class PersonNetworkCollaboratorsComponent implements AfterViewInit { // key: work id, value: work const works: Record = {}; - const allWorks: Record = collaborationNetwork.nodes - .filter((node) => node.category === 'work') + const allWorks: Record = collaborationNetwork.work_nodes .map((node) => ({ id: node.raw_id, title: node.display_name, @@ -115,23 +114,23 @@ export class PersonNetworkCollaboratorsComponent implements AfterViewInit { {} as Record, ); - const allAuthors: Record = collaborationNetwork.nodes - .filter((node) => node.category === 'author') - .map((node) => ({ - id: node.raw_id, - name: node.display_name, - category: node.category, - works: [], - })) - .reduce( - (acc, author) => { - acc[author.id] = author; - return acc; - }, - {} as Record, - ); + const allAuthors: Record = + collaborationNetwork.author_nodes + .map((node) => ({ + id: node.raw_id, + name: node.display_name, + category: node.category, + works: [], + })) + .reduce( + (acc, author) => { + acc[author.id] = author; + return acc; + }, + {} as Record, + ); - collaborationNetwork.edges.forEach((edge) => { + collaborationNetwork.collaboration_edges.forEach((edge) => { if ( edge.raw_source_id.toUpperCase().startsWith('A') && edge.raw_target_id.toUpperCase().startsWith('W') @@ -142,6 +141,10 @@ export class PersonNetworkCollaboratorsComponent implements AfterViewInit { } }); + Object.values(allAuthors).forEach((author) => { + author.works.sort((a, b) => a.title.localeCompare(b.title)); + }); + return new MatTableDataSource( Object.values(allAuthors).filter( (author) => diff --git a/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.html b/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.html new file mode 100644 index 00000000..c2157d74 --- /dev/null +++ b/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.html @@ -0,0 +1,114 @@ +

Netzwerkfilter

+ + + + +
+
+ + Startjahr (inklusive) + + + + Endjahr (inklusive) + + +
+ + Minimale Anzahl von Kollaborierenden (inklusiv) + + + + Maximale Anzahl von Kollaborierenden (exklusiv) + + + + Themen + + @for ( + topic of collaborationNetwork.filter_information.topics; + track topic.raw_topic_id + ) { + + {{ topic.display_name }} + + } + + +
+
+ +
+ + Minimale Anzahl von Kollaborationen (inklusiv) + + + + Maximale Anzahl von Kollaborationen (inklusiv) + + + + + Institutionen + + @for ( + institution of collaborationNetwork.filter_information + .institutions; + track institution.raw_id + ) { + + {{ institution.display_name }} + + } + + +
+
+
+
+ + + + diff --git a/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.scss b/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.scss new file mode 100644 index 00000000..1bc86176 --- /dev/null +++ b/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.scss @@ -0,0 +1,29 @@ +form { + padding-top: 20px; + display: flex; + flex-direction: column; + min-width: 500px; + min-height: 350px; +} + +.form-field-full { + width: 100%; +} + +.toggle-group { + margin-bottom: 20px; +} + +.toggle-group .mat-button-toggle { + text-transform: none; + width: 100%; +} + +.pair-field { + display: flex; + gap: 20px; +} + +.pair-field > mat-form-field { + width: 100%; +} diff --git a/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.ts b/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.ts new file mode 100644 index 00000000..c11ecf73 --- /dev/null +++ b/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.ts @@ -0,0 +1,121 @@ +import { Component, inject, OnInit, signal } from '@angular/core'; +import { + FormControl, + FormGroup, + FormsModule, + ReactiveFormsModule, +} from '@angular/forms'; +import { + MAT_DIALOG_DATA, + MatDialogModule, + MatDialogRef, +} from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { CollaborationNetwork } from '../../api'; +import { MatSelectModule } from '@angular/material/select'; +import { MatInputModule } from '@angular/material/input'; +import { MatButtonModule } from '@angular/material/button'; +import { MatTabsModule } from '@angular/material/tabs'; + +export interface PersonNetworkFilterDialogData { + collaborationNetwork: CollaborationNetwork; + filterBy: 'works' | 'authors'; + + startYear: number; + endYear: number; + topics: string[]; + minContributors: number; + maxContributors: number; + + minCollaborations: number; + maxCollaborations: number; + institutions: string[]; +} + +@Component({ + selector: 'app-person-network-filter-dialog', + imports: [ + FormsModule, + ReactiveFormsModule, + MatFormFieldModule, + MatSelectModule, + MatDialogModule, + MatInputModule, + MatButtonModule, + MatTabsModule, + ], + templateUrl: './person-network-filter-dialog.component.html', + styleUrl: './person-network-filter-dialog.component.scss', +}) +export class PersonNetworkFilterDialogComponent implements OnInit { + readonly dialogRef = inject(MatDialogRef); + readonly data = inject(MAT_DIALOG_DATA); + + readonly collaborationNetwork = this.data.collaborationNetwork; + + worksFilterForm = new FormGroup({ + startYear: new FormControl(this.data.startYear), + endYear: new FormControl(this.data.endYear), + topics: new FormControl(this.data.topics), + minContributors: new FormControl(this.data.minContributors), + maxContributors: new FormControl(this.data.maxContributors), + }); + + authorsFilterForm = new FormGroup({ + minCollaborations: new FormControl(this.data.minCollaborations), + maxCollaborations: new FormControl(this.data.maxCollaborations), + institutions: new FormControl(this.data.institutions), + }); + + selectedTabIndex = signal(0); + + ngOnInit() { + console.log('Received data:', this.data); + + if (this.data.filterBy === 'works') { + this.selectedTabIndex.set(0); + } else if (this.data.filterBy === 'authors') { + this.selectedTabIndex.set(1); + } + + this.authorsFilterForm.patchValue({ + minCollaborations: this.data.minCollaborations, + maxCollaborations: this.data.maxCollaborations, + institutions: this.data.institutions, + }); + + this.worksFilterForm.patchValue({ + startYear: this.data.startYear, + endYear: this.data.endYear, + topics: this.data.topics, + minContributors: this.data.minContributors, + maxContributors: this.data.maxContributors, + }); + } + + onCancel() { + this.dialogRef.close(); + } + + onApply() { + const filterData = { + filterBy: this.filterBy(), + worksFilterProperties: this.worksFilterForm.value, + authorsFilterProperties: this.authorsFilterForm.value, + }; + this.dialogRef.close(filterData); + } + + filterBy() { + return this.selectedTabIndex() === 0 ? 'works' : 'authors'; + } + + onTabChange(event: any) { + this.selectedTabIndex.set(event.index); + if (event.index === 0) { + console.log('Switched to Works tab'); + } else if (event.index === 1) { + console.log('Switched to Authors tab'); + } + } +} diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.html b/webapp/src/app/modules/person-network-graph/person-network-graph.component.html index 8a37053e..d3452f05 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.html +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.html @@ -1,16 +1,24 @@ - - Kollaborations Netzwerk von {{ authorDisplayName }} - -
+ @if (isEmptyGraph()) { +
+ warning +

Das Netzwerk ist leer.

+
+ } @else if (!isValidGraph()) { +
+ warning +

Das Netzwerk ist zu groß für eine detaillierte Darstellung.

+
+ } @else { +
+ }
diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.scss b/webapp/src/app/modules/person-network-graph/person-network-graph.component.scss index ebdd5e69..f1ae7054 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.scss +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.scss @@ -7,12 +7,14 @@ mat-card { display: flex; flex-direction: column; width: 100%; - background: transparent; + background-color: var(--sg-background); } -mat-card-content { +mat-card > mat-card-content { flex: 1 1 auto; min-height: 0; + align-items: center; + padding: 0px; } .graph { @@ -24,3 +26,12 @@ mat-card-content { user-select: none; cursor: grab; } + +.warning-container { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 16px; + padding: 24px; +} diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts index c31f74d2..ae82076c 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts @@ -1,28 +1,68 @@ -import { Component, effect, input } from '@angular/core'; +import { Component, computed, effect, input, output } from '@angular/core'; import { MatCardModule } from '@angular/material/card'; import { CollaborationNetwork } from '../../api'; import { NgxEchartsDirective } from 'ngx-echarts'; import { EChartsCoreOption } from 'echarts/types/dist/core'; import * as echarts from 'echarts/core'; -import { GridComponent, TitleComponent } from 'echarts/components'; +import { + GridComponent, + LegendComponent, + TitleComponent, +} from 'echarts/components'; import { CanvasRenderer } from 'echarts/renderers'; import { GraphChart } from 'echarts/charts'; -echarts.use([GridComponent, CanvasRenderer, GraphChart, TitleComponent]); +import { MatIconModule } from '@angular/material/icon'; +echarts.use([ + GridComponent, + CanvasRenderer, + GraphChart, + TitleComponent, + LegendComponent, +]); + +export type NodeCategory = 'author' | 'collaborator' | 'work' | 'institution'; + +export interface NodeClickEvent { + id: string; + name: string; + category: NodeCategory; +} @Component({ selector: 'app-person-network-graph', - imports: [MatCardModule, NgxEchartsDirective], + imports: [MatCardModule, MatIconModule, NgxEchartsDirective], templateUrl: './person-network-graph.component.html', - styleUrl: './person-network-graph.component.scss', + styleUrls: ['./person-network-graph.component.scss'], }) export class PersonNetworkGraphComponent { collaborationNetwork = input(); + handleNodeClick = output(); + authorDisplayName: string = ''; options!: EChartsCoreOption; + readonly isEmptyGraph = computed(() => { + const network = this.collaborationNetwork(); + return ( + network === undefined || + network.author_nodes.length === 0 || + network.collaboration_edges.length === 0 + ); + }); + + readonly isValidGraph = computed(() => { + const network = this.collaborationNetwork(); + return ( + network !== undefined && + network.author_nodes.length > 0 && + network.author_nodes.length < 1000 && + network.collaboration_edges.length > 0 + ); + }); + constructor() { effect(() => { const network = this.collaborationNetwork(); @@ -37,45 +77,85 @@ export class PersonNetworkGraphComponent { event.preventDefault(); } + categoryLabels: Record = { + author: 'Autor', + collaborator: 'Kollaborierender', + institution: 'Institution', + work: 'Publikation', + }; + + onChartEvent(event: any, type: string) { + if (type !== 'chartClick') { + return; + } + const id = event?.data?.id; + const name = event?.data?.name; + const category = event?.data?.category; + if (!id || !name || !category) { + return; + } + this.handleNodeClick.emit({ id, name, category }); + } + private updateGraphOptions(collaborationNetwork: CollaborationNetwork): void { if (!collaborationNetwork) { return; } + const frequencies = + this.calculateOccurenceFrequencies(collaborationNetwork); + + const freqValues = Object.values(frequencies); + const minFrequency = freqValues.length ? Math.min(...freqValues) : 0; + const maxFrequency = freqValues.length ? Math.max(...freqValues) : 0; + const freqDenominator = + maxFrequency === minFrequency ? 1 : maxFrequency - minFrequency; + const datas = [ { - nodes: collaborationNetwork.nodes.map((node) => { - const category = (() => { - if (node.category === 'institution') { - return 'institution'; - } - if (node.category === 'work') { - return 'work'; - } - if (node.raw_id === collaborationNetwork.raw_person_id) { - return 'author'; - } - return 'collaborator'; - })(); + nodes: [ + collaborationNetwork.work_nodes, + collaborationNetwork.author_nodes, + collaborationNetwork.institution_nodes, + ] + .flat() + .map((node) => { + const category = (() => { + if (node.category === 'institution') { + return 'institution'; + } + if (node.category === 'work') { + return 'work'; + } + if (node.raw_id === collaborationNetwork.raw_person_id) { + return 'author'; + } + return 'collaborator'; + })(); + + const baseId = node.raw_id + ''; + const nodeFreq = frequencies[node.raw_id] || 0; + const computedSymbolSize = + 25 + ((nodeFreq - minFrequency) / freqDenominator) * 30; - if (node.category === 'work') { return { - id: node.raw_id + '', + id: baseId, name: node.display_name, category, + label: { + show: node.category !== 'work', + formatter: '{b}', + }, + emphasis: { + label: { + show: true, + formatter: '{b}', + }, + }, + symbolSize: node.category === 'work' ? 15 : computedSymbolSize, }; - } - - return { - id: node.raw_id + '', - name: node.display_name, - category, - label: { - show: true, - }, - }; - }), - links: collaborationNetwork.edges.map((edge) => { + }), + links: collaborationNetwork.collaboration_edges.map((edge) => { return [edge.raw_source_id + '', edge.raw_target_id + '']; }), categories: [ @@ -95,26 +175,32 @@ export class PersonNetworkGraphComponent { }, ]; - this.authorDisplayName = - collaborationNetwork.nodes.find( - (node) => node.raw_id === collaborationNetwork.raw_person_id, - )?.display_name || 'Unknown Author'; + const legendData = datas.length + ? datas[0].categories.map((c) => c.name) + : []; this.options = { + legend: { + data: legendData, + bottom: 0, + orient: 'horizontal', + formatter: (name: string) => this.categoryLabels[name] || name, + itemGap: 20, + }, series: datas.map((item) => { return { - name: this.authorDisplayName, type: 'graph', layout: 'force', - symbolSize: 20, + symbolSize: 15, animation: false, data: item.nodes, roam: true, force: { repulsion: 10000, - edgeLength: 125, + friction: 0.9, gravity: 0.2, }, + zoom: 0.1, links: item.links.map((e) => { return { source: e[0] + '', @@ -133,4 +219,16 @@ export class PersonNetworkGraphComponent { }), }; } + calculateOccurenceFrequencies( + network: CollaborationNetwork, + ): Record { + const frequencies: Record = {}; + network.collaboration_edges.forEach((edge) => { + frequencies[edge.raw_source_id] = + (frequencies[edge.raw_source_id] || 0) + 1; + frequencies[edge.raw_target_id] = + (frequencies[edge.raw_target_id] || 0) + 1; + }); + return frequencies; + } } diff --git a/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.html b/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.html new file mode 100644 index 00000000..29c0ea8b --- /dev/null +++ b/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.html @@ -0,0 +1,9 @@ + + + {{ icon() }} +
+ {{ value() }} + {{ description() }} +
+
+
diff --git a/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.scss b/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.scss new file mode 100644 index 00000000..13a84cc6 --- /dev/null +++ b/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.scss @@ -0,0 +1,34 @@ +.info-card { + --info-card-icon-size: 40px; + + background-color: var(--sg-background); + padding: 10px 20px; +} +.info-card mat-card-content { + display: flex; + align-items: start; + gap: 10px; +} + +.info-card mat-icon { + width: var(--info-card-icon-size); + height: var(--info-card-icon-size); + font-size: var(--info-card-icon-size); + color: var(--sg-blue-highlight); +} + +.info-card div { + display: flex; + flex-direction: column; + gap: 4px; +} + +.info-card .number { + font-weight: var(--sg-default-bold-weight); + font-size: 1.5em; +} + +.info-card .description { + color: var(--sg-text-muted); + font-size: 0.9em; +} diff --git a/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.ts b/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.ts new file mode 100644 index 00000000..fe5c3913 --- /dev/null +++ b/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.ts @@ -0,0 +1,15 @@ +import { Component, input } from '@angular/core'; +import { MatCardModule } from '@angular/material/card'; +import { MatIconModule } from '@angular/material/icon'; + +@Component({ + selector: 'app-person-network-info-card', + imports: [MatIconModule, MatCardModule], + templateUrl: './person-network-info-card.component.html', + styleUrl: './person-network-info-card.component.scss', +}) +export class PersonNetworkInfoCardComponent { + readonly icon = input(); + readonly value = input(); + readonly description = input(); +} diff --git a/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.html b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.html new file mode 100644 index 00000000..22621d39 --- /dev/null +++ b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.html @@ -0,0 +1,58 @@ +
+ + + + + + + + + + + + + + + + +
Name + {{ element.name }} + Mitwirkende + {{ element.collaborators.length }} + + + open_in_new + +
+
+@if (dataSource.filteredData.length === 0) { +

Keine Institutionen gefunden.

+} + + + + + + + + diff --git a/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.scss b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.scss new file mode 100644 index 00000000..7cb09d57 --- /dev/null +++ b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.scss @@ -0,0 +1,38 @@ +.table { + overflow: auto; + width: 100%; + max-height: 100%; +} + +.mat-mdc-table { + background-color: var(--sg-background); +} + +.element-row { + position: relative; +} + +.element-row:not(.expanded) { + cursor: pointer; +} + +.element-row:not(.expanded):hover { + background: #f5f5f5; +} + +.element-row.expanded { + border-bottom-color: transparent; +} + +.detail-row { + width: 100%; +} + +.person-link { + color: var(--sg-primary); + text-decoration: none; + + &:hover { + text-decoration: underline; + } +} diff --git a/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.ts b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.ts new file mode 100644 index 00000000..e4b827e4 --- /dev/null +++ b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.ts @@ -0,0 +1,124 @@ +import { + AfterViewInit, + Component, + effect, + input, + ViewChild, +} from '@angular/core'; +import { CollaborationNetwork } from '../../api'; +import { MatTableDataSource, MatTableModule } from '@angular/material/table'; +import { MatSort, MatSortModule } from '@angular/material/sort'; +import { MatIconModule } from '@angular/material/icon'; +import { RouterModule } from '@angular/router'; +import { CdkDetailRowDirective } from '../../directives/cdk-detail-row.directive'; +import { MatButtonModule } from '@angular/material/button'; + +type Collaborator = { + id: string; + name: string; +}; + +type Institution = { + id: string; + name: string; + collaborators: Collaborator[]; +}; + +@Component({ + selector: 'app-person-network-institutions', + imports: [ + MatTableModule, + MatIconModule, + MatSortModule, + RouterModule, + CdkDetailRowDirective, + MatButtonModule, + ], + templateUrl: './person-network-institutions.component.html', + styleUrl: './person-network-institutions.component.scss', +}) +export class PersonNetworkInstitutionsComponent implements AfterViewInit { + collaborationNetwork = input.required(); + searchTerm = input.required(); + + displayedColumns: string[] = ['name', 'collaborators', 'actions']; + + dataSource = new MatTableDataSource(); + + trackBy = (index: number, item: Institution) => item.id; + + @ViewChild(MatSort) sort!: MatSort; + + constructor() { + effect(() => { + const collaborationNetwork = this.collaborationNetwork(); + if (!collaborationNetwork) { + return; + } + + this.dataSource = this.buildInstitutionsDataSource(collaborationNetwork); + this.dataSource.sortingDataAccessor = (item, property) => { + if (property === 'collaborators') { + return item.collaborators.length; + } + return (item as any)[property]; + }; + if (this.sort) { + this.dataSource.sort = this.sort; + this.setDefaultSort(); + } + }); + + effect(() => { + const searchTerm = this.searchTerm().toLowerCase(); + this.dataSource.filter = searchTerm; + }); + } + + ngAfterViewInit() { + if (this.sort) { + this.dataSource.sort = this.sort; + } + } + + private setDefaultSort(): void { + this.sort.active = 'name'; + this.sort.direction = 'asc'; + this.sort.sortChange.emit({ active: 'name', direction: 'asc' }); + } + + buildInstitutionsDataSource( + collaborationNetwork: CollaborationNetwork, + ): MatTableDataSource { + const institutionsMap: Record = {}; + + for (const node of collaborationNetwork.institution_nodes) { + institutionsMap[node.raw_id] = { + id: node.raw_id, + name: node.display_name, + collaborators: [], + }; + } + + for (const edge of collaborationNetwork.collaboration_edges) { + if (edge.raw_target_id in institutionsMap) { + const institution = institutionsMap[edge.raw_target_id]; + institution.collaborators.push({ + id: edge.raw_source_id, + name: + collaborationNetwork.author_nodes.find( + (node) => node.raw_id === edge.raw_source_id, + )?.display_name || 'Unbekannt', + }); + } + } + + for (const institution of Object.values(institutionsMap)) { + institution.collaborators.sort((a, b) => + a.name.localeCompare(b.name, 'de', { sensitivity: 'base' }), + ); + } + + return new MatTableDataSource(Object.values(institutionsMap)); + } +} diff --git a/webapp/src/app/modules/person-network-publications/person-network-publications.component.html b/webapp/src/app/modules/person-network-publications/person-network-publications.component.html index a8c4c24b..10a5c436 100644 --- a/webapp/src/app/modules/person-network-publications/person-network-publications.component.html +++ b/webapp/src/app/modules/person-network-publications/person-network-publications.component.html @@ -1,9 +1,5 @@
- - - - @@ -39,19 +31,22 @@ >
ID{{ element.id }} Titel @@ -19,13 +15,9 @@ - +
+@if (dataSource.filteredData.length === 0) { +

Keine Publikationen gefunden.

+} -
-
    - @for (collaborator of element.collaborators; track $index) { -
  • - {{ collaborator.name }} - ({{ - collaborator.id - }}) -
  • - } -
-
+ + + + +
diff --git a/webapp/src/app/modules/person-network-publications/person-network-publications.component.scss b/webapp/src/app/modules/person-network-publications/person-network-publications.component.scss index b6462c61..7cb09d57 100644 --- a/webapp/src/app/modules/person-network-publications/person-network-publications.component.scss +++ b/webapp/src/app/modules/person-network-publications/person-network-publications.component.scss @@ -1,60 +1,11 @@ -.content { - display: flex; - flex-direction: row; - padding: 40px; - gap: 20px; - max-height: 1000px; -} - -.graph { - width: 75vh; - height: 75vh; -} - .table { overflow: auto; width: 100%; - max-height: 1000px; - height: 1200px; + max-height: 100%; } -.table table { - width: 100%; -} - -.table-area { - width: 100%; - height: 100%; - display: flex; - flex-direction: column; -} - -.scroll-viewport-container { - width: 100%; - height: 100%; -} - -.form-controls { - display: flex; - flex-direction: row; - align-items: flex-start; - gap: 10px; -} - -.form-field-full { - width: 100%; -} - -.right-card { - width: 100%; -} - -.toggle-group { - margin-bottom: 20px; -} - -.toggle-group .mat-button-toggle { - text-transform: none; +.mat-mdc-table { + background-color: var(--sg-background); } .element-row { @@ -76,3 +27,12 @@ .detail-row { width: 100%; } + +.person-link { + color: var(--sg-primary); + text-decoration: none; + + &:hover { + text-decoration: underline; + } +} diff --git a/webapp/src/app/modules/person-network-publications/person-network-publications.component.ts b/webapp/src/app/modules/person-network-publications/person-network-publications.component.ts index 271906b9..c4c08016 100644 --- a/webapp/src/app/modules/person-network-publications/person-network-publications.component.ts +++ b/webapp/src/app/modules/person-network-publications/person-network-publications.component.ts @@ -43,7 +43,7 @@ export class PersonNetworkPublicationsComponent implements AfterViewInit { collaborationNetwork = input.required(); searchTerm = input.required(); - displayedColumns: string[] = ['id', 'title', 'contributors', 'actions']; + displayedColumns: string[] = ['title', 'contributors', 'actions']; dataSource = new MatTableDataSource(); @@ -90,8 +90,7 @@ export class PersonNetworkPublicationsComponent implements AfterViewInit { buildWorksDataSource( collaborationNetwork: CollaborationNetwork, ): MatTableDataSource { - const allWorks: Record = collaborationNetwork.nodes - .filter((node) => node.category === 'work') + const allWorks: Record = collaborationNetwork.work_nodes .map((node) => ({ id: node.raw_id, title: node.display_name, @@ -105,25 +104,25 @@ export class PersonNetworkPublicationsComponent implements AfterViewInit { {} as Record, ); - const allAuthors: Record = collaborationNetwork.nodes - .filter((node) => node.category === 'author') - .map((node) => ({ - id: node.raw_id, - name: node.display_name, - category: - node.raw_id === collaborationNetwork.raw_person_id - ? 'author' - : 'collaborator', - })) - .reduce( - (acc, person) => { - acc[person.id] = person; - return acc; - }, - {} as Record, - ); + const allAuthors: Record = + collaborationNetwork.author_nodes + .map((node) => ({ + id: node.raw_id, + name: node.display_name, + category: + node.raw_id === collaborationNetwork.raw_person_id + ? 'author' + : 'collaborator', + })) + .reduce( + (acc, person) => { + acc[person.id] = person; + return acc; + }, + {} as Record, + ); - collaborationNetwork.edges.forEach((edge) => { + collaborationNetwork.collaboration_edges.forEach((edge) => { if ( edge.raw_source_id.toUpperCase().startsWith('A') && edge.raw_target_id.toUpperCase().startsWith('W') @@ -134,6 +133,10 @@ export class PersonNetworkPublicationsComponent implements AfterViewInit { } }); + Object.values(allWorks).forEach((work) => { + work.collaborators.sort((a, b) => a.name.localeCompare(b.name)); + }); + return new MatTableDataSource( Object.values(allWorks).filter((work) => work.collaborators.length > 0), ); diff --git a/webapp/src/app/modules/person-network/person-network.component.html b/webapp/src/app/modules/person-network/person-network.component.html index 33475766..6883dce7 100644 --- a/webapp/src/app/modules/person-network/person-network.component.html +++ b/webapp/src/app/modules/person-network/person-network.component.html @@ -1,170 +1,86 @@
- +
+
Netzwerk
+

Zusammenarbeit und Verbindungen im wissenschaftlichen Netzwerk.

+
-
-
- - - Filter - -
- - Startjahr (inklusive) - - - - Endjahr (inklusive) - - -
-
- - Minimale Anzahl von Kollaborierenden (inklusiv) - - - - Maximale Anzahl von Kollaborierenden (exklusiv) - - -
-
- - Minimale Anzahl von Kollaborationen (inklusiv) - - - - Maximale Anzahl von Kollaborationen (inklusiv) - - -
+
+ -
- - Institutionen - + +
+ + + Kollaborierende + + Publikationen - @for ( - institution of collaborationNetwork.filter_information - .institutions; - track institution.raw_id - ) { - - {{ institution.display_name }} - - } - - - - Themen - - @for ( - topic of collaborationNetwork.filter_information.topics; - track topic.raw_topic_id - ) { - - {{ topic.display_name }} - - } - - + + Institutionen + + +
- + + {{ this.searchTermLabel() }} + + search + + + - - - Kollaborierende - - Publikationen - - - {{ - this.displayedTable() === "collaborators" - ? "Suche Kollaborierende nach Name oder ID" - : "Suche Publikationen nach Titel oder ID" - }} - - search - - - -
- -
- @if (this.displayedTable() === "collaborators") { - - } @else if (this.displayedTable() === "publications") { - - } -
+ + @if (this.displayedTable() === "collaborators") { + + } @else if (this.displayedTable() === "publications") { + + } @else if (this.displayedTable() === "institutions") { + + }
+ +
+ @for (summary of this.summaryCards(); track $index) { + + } +
diff --git a/webapp/src/app/modules/person-network/person-network.component.scss b/webapp/src/app/modules/person-network/person-network.component.scss index 234fc412..36506868 100644 --- a/webapp/src/app/modules/person-network/person-network.component.scss +++ b/webapp/src/app/modules/person-network/person-network.component.scss @@ -1,57 +1,39 @@ .content { display: flex; - flex-direction: row; - padding: 40px; + flex-direction: column; + padding: 30px; gap: 20px; - align-items: stretch; +} + +.description-container { + display: flex; + flex-direction: column; +} + +.cards { + display: flex; + flex-direction: row; + gap: 20px; + max-height: 80vh; +} + +form > div { + display: flex; + flex-direction: row; + gap: 20px; +} + +form > div > button, +form > div > mat-button-toggle-group { + margin-top: 20px; + margin-bottom: 20px; + border-radius: var(--sg-radius-sm); + color: var(--sg-text); } .content > app-person-network-graph, .right-card { flex: 1 1 0; - min-width: 0; -} - -.table { - overflow: auto; - width: 100%; - max-height: 70vh; - height: 100%; -} - -.table table { - width: 100%; -} - -.table-area { - width: 100%; - height: 100%; - display: flex; - flex-direction: column; -} - -.scroll-viewport-container { - width: 100%; - height: 100%; -} - -.form-controls { - display: flex; - flex-direction: row; - align-items: flex-start; - gap: 10px; -} - -.form-field-full { - width: 100%; -} - -.right-card { - width: 100%; -} - -.toggle-group { - margin-bottom: 20px; } .toggle-group .mat-button-toggle { @@ -59,11 +41,21 @@ width: 100%; } -.pair-field { +.summary-container { display: flex; + flex-direction: row; gap: 20px; } -.pair-field > mat-form-field { - width: 100%; +.summary-container app-person-network-info-card { + flex: 1 1 0; +} + +.scroll-viewport-container { + height: 50vh; + max-height: 50vh; +} + +mat-card { + background-color: var(--sg-background); } diff --git a/webapp/src/app/modules/person-network/person-network.component.ts b/webapp/src/app/modules/person-network/person-network.component.ts index 45986862..647f2939 100644 --- a/webapp/src/app/modules/person-network/person-network.component.ts +++ b/webapp/src/app/modules/person-network/person-network.component.ts @@ -1,6 +1,6 @@ import { toSignal } from '@angular/core/rxjs-interop'; -import { Component, computed, OnInit } from '@angular/core'; +import { Component, computed, OnInit, signal } from '@angular/core'; import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { MatCardModule } from '@angular/material/card'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; @@ -26,9 +26,17 @@ import { CollaborationNetwork } from '../../api'; import { PersonNetworkCollaboratorsComponent } from '../person-network-collaborators/person-network-collaborators.component'; import { PersonNetworkPublicationsComponent } from '../person-network-publications/person-network-publications.component'; import { debounceTime } from 'rxjs'; -import { PersonNetworkGraphComponent } from '../person-network-graph/person-network-graph.component'; +import { + NodeCategory, + NodeClickEvent, + PersonNetworkGraphComponent, +} from '../person-network-graph/person-network-graph.component'; import { MatSelectModule } from '@angular/material/select'; import { MatExpansionModule } from '@angular/material/expansion'; +import { MatDialog, MatDialogModule } from '@angular/material/dialog'; +import { PersonNetworkFilterDialogComponent } from '../person-network-filter-dialog/person-network-filter-dialog.component'; +import { PersonNetworkInfoCardComponent } from '../person-network-info-card/person-network-info-card.component'; +import { PersonNetworkInstitutionsComponent } from '../person-network-institutions/person-network-institutions.component'; @Component({ selector: 'app-person-network', @@ -53,6 +61,9 @@ import { MatExpansionModule } from '@angular/material/expansion'; PersonNetworkGraphComponent, MatSelectModule, MatExpansionModule, + MatDialogModule, + PersonNetworkInfoCardComponent, + PersonNetworkInstitutionsComponent, ], templateUrl: './person-network.component.html', styleUrl: './person-network.component.scss', @@ -63,17 +74,94 @@ export class PersonNetworkComponent implements OnInit { filterForm = new FormGroup({ searchTerm: new FormControl(''), + filterBy: new FormControl<'works' | 'authors'>('works'), + displayedTable: new FormControl('collaborators'), + startYear: new FormControl(2000), endYear: new FormControl(2025), - minimumCollaborators: new FormControl(2), - maximumCollaborators: new FormControl(10), - minimumCollaborations: new FormControl(1), - maximumCollaborations: new FormControl(100), - institutions: new FormControl([]), topics: new FormControl([]), - displayedTable: new FormControl('collaborators'), + minContributors: new FormControl(2), + maxContributors: new FormControl(10), + + minCollaborations: new FormControl(1), + maxCollaborations: new FormControl(100), + institutions: new FormControl([]), }); + persons = signal(0); + institutions = signal(0); + publications = signal(0); + + connections = signal(0); + + searchTermLabel = computed(() => { + const displayedTable = this.displayedTable(); + switch (displayedTable) { + case 'collaborators': + return 'Suche Kollaborierende nach Name'; + case 'publications': + return 'Suche Publikationen nach Titel'; + case 'institutions': + return 'Suche Institutionen nach Name'; + default: + return 'Suchbegriff'; + } + }); + + private readonly categoryTableMap: Record = { + author: 'collaborators', + collaborator: 'collaborators', + work: 'publications', + institution: 'institutions', + }; + + latestNodeId = signal(null); + + handleNodeClick = ({ id, name, category }: NodeClickEvent): void => { + if (this.latestNodeId() === id) { + this.clearSearch(); + return; + } + + this.latestNodeId.set(id); + if (category === 'author') { + return; + } + + this.filterForm.patchValue({ + displayedTable: this.categoryTableMap[category], + searchTerm: name, + }); + }; + + clearSearch() { + this.latestNodeId.set(null); + this.filterForm.patchValue({ searchTerm: '' }); + } + + readonly summaryCards = computed(() => [ + { + icon: 'person', + value: this.persons(), + description: 'Personen', + }, + { + icon: 'apartment', + value: this.institutions(), + description: 'Institutionen', + }, + { + icon: 'menu_book', + value: this.publications(), + description: 'Gemeinsame Publikationen', + }, + { + icon: 'share', + value: this.connections(), + description: 'Verbindungen im Netzwerk', + }, + ]); + readonly formValue = toSignal(this.filterForm.valueChanges); readonly debouncedFormValue = toSignal( this.filterForm.valueChanges.pipe(debounceTime(300)), @@ -84,65 +172,114 @@ export class PersonNetworkComponent implements OnInit { }); readonly searchTerm = computed(() => { - console.log('Search term computed:', this.debouncedFormValue()?.searchTerm); return this.debouncedFormValue()?.searchTerm || ''; }); readonly activatedRouteData = toSignal(this.activatedRoute.data); - formatYearLabel = (value: number) => `${value}`; - constructor( private readonly activatedRoute: ActivatedRoute, private readonly router: Router, + private readonly dialog: MatDialog, ) {} + openFilterDialog() { + console.log('Form value when opening dialog:', this.filterForm.value); + const dialogRef = this.dialog.open(PersonNetworkFilterDialogComponent, { + data: { + collaborationNetwork: this.collaborationNetwork, + filterBy: this.filterForm.get('filterBy')?.value || 'works', + startYear: this.filterForm.get('startYear')?.value, + + endYear: this.filterForm.get('endYear')?.value, + topics: this.filterForm.get('topics')?.value, + minContributors: this.filterForm.get('minContributors')!.value, + maxContributors: this.filterForm.get('maxContributors')?.value, + + minCollaborations: this.filterForm.get('minCollaborations')?.value, + maxCollaborations: this.filterForm.get('maxCollaborations')?.value, + institutions: this.filterForm.get('institutions')?.value, + }, + }); + + dialogRef.afterClosed().subscribe((result) => { + console.log('Dialog closed with result:', result); + console.log(result.filterBy); + console.log(result.worksFilterProperties); + console.log(result.authorsFilterProperties); + if (result) { + this.filterForm.patchValue({ + filterBy: result.filterBy, + + startYear: result.worksFilterProperties.startYear, + endYear: result.worksFilterProperties.endYear, + topics: result.worksFilterProperties.topics, + minContributors: result.worksFilterProperties.minContributors, + maxContributors: result.worksFilterProperties.maxContributors, + + minCollaborations: result.authorsFilterProperties.minCollaborations, + maxCollaborations: result.authorsFilterProperties.maxCollaborations, + institutions: result.authorsFilterProperties.institutions, + }); + } + }); + } + + calculateSummary(collaborationNetwork: CollaborationNetwork) { + this.persons.set(collaborationNetwork.author_nodes.length); + this.institutions.set(collaborationNetwork.institution_nodes.length); + this.publications.set(collaborationNetwork.work_nodes.length); + this.connections.set(collaborationNetwork.collaboration_edges.length); + } + ngOnInit(): void { this.activatedRoute.data.subscribe(({ collaborationNetwork }) => { this.collaborationNetwork = collaborationNetwork; + this.calculateSummary(collaborationNetwork); + const currentParams = this.activatedRoute.snapshot.queryParams; - const initialStartYear = - Number(currentParams['start_year']) || - this.collaborationNetwork.filter_information.min_possible_year; - const initialEndYear = - Number(currentParams['end_year']) || - this.collaborationNetwork.filter_information.max_possible_year; this.filterForm.setValue({ searchTerm: currentParams['search_term'] || '', - startYear: initialStartYear, - endYear: initialEndYear, - minimumCollaborators: - Number(currentParams['minimum_collaborators']) || 2, - maximumCollaborators: - Number(currentParams['maximum_collaborators']) || 10, - minimumCollaborations: - this.filterForm.get('minimumCollaborations')?.value ?? 1, - maximumCollaborations: - this.filterForm.get('maximumCollaborations')?.value ?? 100, + filterBy: currentParams['filter_by'] || 'works', displayedTable: currentParams['table'] || 'collaborators', - institutions: currentParams['institutions'] - ? currentParams['institutions'].split(',') - : [], + + startYear: + Number(currentParams['start_year']) || + this.collaborationNetwork.filter_information.min_possible_year, + endYear: + Number(currentParams['end_year']) || + this.collaborationNetwork.filter_information.max_possible_year, topics: currentParams['topics'] ? currentParams['topics'].split(',') : [], + minContributors: Number(currentParams['min_contributors']) || 2, + maxContributors: Number(currentParams['max_contributors']) || 10, + + minCollaborations: Number(currentParams['min_collaborations']) || 1, + maxCollaborations: Number(currentParams['max_collaborations']) || 100, + + institutions: currentParams['institutions'] + ? currentParams['institutions'].split(',') + : [], }); }); this.filterForm.valueChanges.pipe(debounceTime(300)).subscribe((value) => { + console.log('Form value changed:', value); this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: { table: value.displayedTable, search_term: value.searchTerm, + filter_by: value.filterBy, start_year: value.startYear, end_year: value.endYear, - minimum_collaborators: value.minimumCollaborators, - maximum_collaborators: value.maximumCollaborators, - minimum_collaborations: value.minimumCollaborations, - maximum_collaborations: value.maximumCollaborations, + min_contributors: value.minContributors, + max_contributors: value.maxContributors, + min_collaborations: value.minCollaborations, + max_collaborations: value.maxCollaborations, institutions: value.institutions?.join(','), topics: value.topics?.join(','), }, diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html index cfd25c2e..fe7d4515 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html @@ -102,7 +102,14 @@ class="timeline-point" [ngClass]="getColorClass(index)" > - {{ item.year }} +
@@ -112,23 +119,39 @@ *ngFor="let item of timelineItems; let index = index; trackBy: trackByYear" class="timeline-item" > -

{{ getMainTopic(item) }}

+

+ +

- +
- {{ topic.name }} {{ topic.count }} - + @@ -154,25 +177,52 @@
- {{ getPhaseYearLabel(phase) }} -

{{ phase.primaryTopicName }}

- - {{ phase.publication_count }} - {{ phase.publication_count === 1 ? 'Publikation' : 'Publikationen' }} - +
+ + + +
+ +

+ +

- {{ topic.name }} {{ topic.count }} - + @@ -194,11 +244,23 @@
- {{ year.year }} - + + +
@@ -208,16 +270,19 @@ else noPhaseYearTopics " > - {{ topic.name }} {{ topic.count }} - + diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss index 16ca7935..1bac000d 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss @@ -1,4 +1,6 @@ .research-timeline-card { + --accent: #0057ff; + width: 100%; padding: 24px 28px; border: 1px solid #d7e4ff; @@ -6,6 +8,32 @@ background: #ffffff; box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04); box-sizing: border-box; + + button { + font-family: inherit; + } + + button:not(:where(.topic-chip, .mini-topic-chip)) { + border: 0; + background: transparent; + padding: 0; + cursor: pointer; + } + + button:hover:not(:disabled) { + color: var(--accent); + text-decoration: underline; + } + + button:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; + border-radius: 3px; + } + + button:disabled { + cursor: default; + } } .timeline-header { @@ -39,6 +67,35 @@ } } +.view-toggle { + justify-self: center; + display: flex; + gap: 4px; + padding: 4px; + border: 1px solid #dbe5f6; + border-radius: 10px; + background: #ffffff; + + button { + border-radius: 8px; + padding: 9px 18px; + color: #3f4b66; + font-size: 14px; + transition: all 0.2s ease; + + &:hover { + background: #f2f6ff; + text-decoration: none; + } + + &.active { + background: #eef4ff; + color: var(--accent); + box-shadow: inset 0 0 0 1px #3d7cff; + } + } +} + .year-filter { justify-self: end; width: min(285px, 100%); @@ -48,11 +105,21 @@ background: #fbfdff; } -.year-filter-top { +.year-filter-top, +.year-filter-values, +.year-filter-bounds, +.phase-meta-row { display: flex; align-items: center; +} + +.year-filter-top, +.phase-meta-row { justify-content: space-between; gap: 10px; +} + +.year-filter-top { margin-bottom: 4px; } @@ -63,22 +130,15 @@ } .reset-range-button { - border: none; - background: transparent; - color: #0057ff; + color: var(--accent); font-size: 11px; - cursor: pointer; - padding: 0; &:disabled { color: #9aa5bc; - cursor: default; } } .year-filter-values { - display: flex; - align-items: center; justify-content: center; gap: 7px; margin-bottom: 5px; @@ -87,13 +147,19 @@ font-weight: 600; } +.year-filter-bounds { + justify-content: space-between; + margin-top: 1px; + color: #7c88a3; + font-size: 10px; +} + .year-range-slider { --range-start: 0%; --range-end: 100%; position: relative; height: 22px; - margin: 0; } .range-track { @@ -109,8 +175,8 @@ to right, #d8e2f4 0%, #d8e2f4 var(--range-start), - #0057ff var(--range-start), - #0057ff var(--range-end), + var(--accent) var(--range-start), + var(--accent) var(--range-end), #d8e2f4 var(--range-end), #d8e2f4 100% ); @@ -118,22 +184,16 @@ .range-input { position: absolute; - top: 0; - left: 0; + inset: 0; width: 100%; - margin: 0; height: 22px; + margin: 0; appearance: none; background: transparent; pointer-events: none; } -.range-input::-webkit-slider-runnable-track { - height: 5px; - background: transparent; - border: none; -} - +.range-input::-webkit-slider-runnable-track, .range-input::-moz-range-track { height: 5px; background: transparent; @@ -147,7 +207,7 @@ margin-top: -5px; border: 2px solid #ffffff; border-radius: 50%; - background: #0057ff; + background: var(--accent); box-shadow: 0 0 0 1px #9ab7ff, 0 2px 6px rgba(0, 87, 255, 0.22); cursor: pointer; pointer-events: auto; @@ -158,22 +218,12 @@ height: 15px; border: 2px solid #ffffff; border-radius: 50%; - background: #0057ff; + background: var(--accent); box-shadow: 0 0 0 1px #9ab7ff, 0 2px 6px rgba(0, 87, 255, 0.22); cursor: pointer; pointer-events: auto; } -.range-input:focus-visible::-webkit-slider-thumb { - outline: 2px solid #07163d; - outline-offset: 2px; -} - -.range-input:focus-visible::-moz-range-thumb { - outline: 2px solid #07163d; - outline-offset: 2px; -} - .range-input-start { z-index: 2; } @@ -182,45 +232,6 @@ z-index: 3; } -.year-filter-bounds { - display: flex; - justify-content: space-between; - margin-top: 1px; - color: #7c88a3; - font-size: 10px; -} - -.view-toggle { - justify-self: center; - display: flex; - gap: 4px; - padding: 4px; - border: 1px solid #dbe5f6; - border-radius: 10px; - background: #ffffff; - - button { - border: none; - border-radius: 8px; - padding: 9px 18px; - background: transparent; - color: #3f4b66; - font-size: 14px; - cursor: pointer; - transition: all 0.2s ease; - - &:hover { - background: #f2f6ff; - } - - &.active { - background: #eef4ff; - color: #0057ff; - box-shadow: inset 0 0 0 1px #3d7cff; - } - } -} - .timeline-wrapper { width: 100%; overflow-x: auto; @@ -240,18 +251,16 @@ right: 34px; height: 2px; background: #23395d; -} -.timeline-axis::after { - content: ""; - position: absolute; - top: -5px; - right: -10px; - width: 0; - height: 0; - border-top: 6px solid transparent; - border-bottom: 6px solid transparent; - border-left: 12px solid #23395d; + &::after { + content: ""; + position: absolute; + top: -5px; + right: -10px; + border-top: 6px solid transparent; + border-bottom: 6px solid transparent; + border-left: 12px solid #23395d; + } } .timeline-points { @@ -268,7 +277,7 @@ align-items: center; min-width: 0; - .year { + .year-button { margin-bottom: 9px; color: #15213f; font-size: 14px; @@ -282,13 +291,13 @@ height: 13px; border: 3px solid #ffffff; border-radius: 50%; + background: var(--timeline-color); box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.16); } } .timeline-content { display: grid; - gap: 0; margin-top: 8px; } @@ -315,6 +324,18 @@ font-size: 12px; } +.publication-count-button { + width: fit-content; + margin: 0 auto 14px; +} + +.main-topic-button { + color: inherit; + font: inherit; + font-weight: inherit; + line-height: inherit; +} + .topic-list { display: flex; flex-direction: column; @@ -323,22 +344,42 @@ } .topic-chip { - display: inline-flex; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; align-items: center; - justify-content: center; - gap: 7px; - width: fit-content; + justify-items: center; + column-gap: 8px; + width: 100%; max-width: 210px; + box-sizing: border-box; min-height: 34px; padding: 6px 10px; + border: 1px solid var(--topic-border); border-radius: 8px; + background: var(--topic-bg); + color: var(--topic-color); + font-family: inherit; font-size: 12px; font-weight: 500; line-height: 1.25; + cursor: pointer; + transition: transform 0.15s ease, box-shadow 0.15s ease; + + &:hover:not(:disabled) { + transform: translateY(-1px); + box-shadow: 0 4px 10px rgba(15, 23, 42, 0.12); + text-decoration: none; + } + + &:disabled { + cursor: default; + } } -.topic-name { +.topic-name, +.mini-topic-chip span { min-width: 0; + text-align: center; overflow-wrap: anywhere; } @@ -376,7 +417,7 @@ box-sizing: border-box; padding: 15px 16px; border: 1px solid #dbe5f6; - border-left-width: 4px; + border-left: 4px solid var(--timeline-color); border-radius: 14px; background: #fbfdff; } @@ -394,14 +435,16 @@ margin-top: 5px; border: 3px solid #ffffff; border-radius: 50%; + background: var(--timeline-color); box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.14); } .phase-title-block { + flex: 1; min-width: 0; h3 { - margin: 3px 0 4px; + margin: 10px 0 0; color: #07163d; font-size: 15px; font-weight: 700; @@ -415,14 +458,23 @@ padding: 2px 8px; border-radius: 999px; background: #eef4ff; - color: #0057ff; + color: var(--accent); font-size: 12px; font-weight: 700; } -.phase-publications { +.phase-years-button:hover { + background: #dfeaff; +} + +.phase-publications-button { + display: inline-flex; + flex: 0 0 auto; + width: fit-content; color: #68748f; font-size: 12px; + font-weight: 600; + text-align: left; } .phase-topics { @@ -430,44 +482,31 @@ flex-wrap: wrap; gap: 7px; margin-top: 14px; + + .topic-chip { + flex: 0 0 calc((100% - 7px) / 2); + width: calc((100% - 7px) / 2); + max-width: none; + } } .phase-toggle { margin-top: 13px; - border: none; - background: transparent; - color: #0057ff; + color: var(--accent); font-size: 12px; font-weight: 700; - cursor: pointer; - padding: 0; } .phase-year-details { display: flex; flex-direction: column; + max-height: 320px; margin-top: 13px; padding-top: 4px; padding-right: 6px; border-top: 1px solid #dbe5f6; - max-height: 320px; overflow-y: auto; overflow-x: hidden; - scrollbar-gutter: stable; - overscroll-behavior: contain; -} - -.phase-year-details::-webkit-scrollbar { - width: 8px; -} - -.phase-year-details::-webkit-scrollbar-thumb { - border-radius: 999px; - background: #c8d4e8; -} - -.phase-year-details::-webkit-scrollbar-track { - background: transparent; } .phase-year-row { @@ -476,10 +515,10 @@ gap: 10px; align-items: start; padding: 10px 0; -} -.phase-year-row + .phase-year-row { - border-top: 1px solid #e4ebf7; + & + & { + border-top: 1px solid #e4ebf7; + } } .phase-year-meta { @@ -487,15 +526,24 @@ flex-direction: column; gap: 2px; - strong { + .phase-year-button { + width: fit-content; color: #07163d; font-size: 13px; + font-weight: 700; + text-align: left; } - span { + span, + .phase-year-publication-button { color: #68748f; font-size: 11px; } + + .phase-year-publication-button { + width: fit-content; + text-align: left; + } } .phase-year-topics { @@ -505,110 +553,69 @@ } .mini-topic-chip { - display: inline-flex; + display: inline-grid; + grid-template-columns: minmax(0, 1fr) auto; align-items: center; - gap: 5px; + column-gap: 5px; max-width: 100%; padding: 4px 7px; + border: 0; border-radius: 7px; background: #f2f6ff; color: #40506f; + font-family: inherit; font-size: 11px; line-height: 1.25; + cursor: pointer; - span { - overflow-wrap: anywhere; + &:hover:not(:disabled) { + color: var(--accent); + text-decoration: none; + } + + &:disabled { + cursor: default; } strong { - color: #0057ff; + color: var(--accent); font-size: 10px; } } .purple { - .dot, - .phase-marker { - background: #7255d9; - } + --timeline-color: #7255d9; + --topic-border: #d8cafe; + --topic-bg: #f6f0ff; + --topic-color: #7255d9; } .blue { - .dot, - .phase-marker { - background: #2678e8; - } + --timeline-color: #2678e8; + --topic-border: #bdd4ff; + --topic-bg: #f0f6ff; + --topic-color: #0b63ce; } .green { - .dot, - .phase-marker { - background: #39a96b; - } + --timeline-color: #39a96b; + --topic-border: #bdebcf; + --topic-bg: #effaf3; + --topic-color: #24834f; } .orange { - .dot, - .phase-marker { - background: #f59e0b; - } + --timeline-color: #f59e0b; + --topic-border: #ffd796; + --topic-bg: #fff7e8; + --topic-color: #c67500; } .pink { - .dot, - .phase-marker { - background: #e0527c; - } -} - -.phase-card.purple { - border-left-color: #7255d9; -} - -.phase-card.blue { - border-left-color: #2678e8; -} - -.phase-card.green { - border-left-color: #39a96b; -} - -.phase-card.orange { - border-left-color: #f59e0b; -} - -.phase-card.pink { - border-left-color: #e0527c; -} - -.topic-chip.purple { - border: 1px solid #d8cafe; - background: #f6f0ff; - color: #7255d9; -} - -.topic-chip.blue { - border: 1px solid #bdd4ff; - background: #f0f6ff; - color: #0b63ce; -} - -.topic-chip.green { - border: 1px solid #bdebcf; - background: #effaf3; - color: #24834f; -} - -.topic-chip.orange { - border: 1px solid #ffd796; - background: #fff7e8; - color: #c67500; -} - -.topic-chip.pink { - border: 1px solid #ffc7d7; - background: #fff1f5; - color: #d12f61; + --timeline-color: #e0527c; + --topic-border: #ffc7d7; + --topic-bg: #fff1f5; + --topic-color: #d12f61; } .timeline-note { diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts index 56ec4486..41193edc 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts @@ -9,6 +9,7 @@ import { } from '@angular/core'; export interface TopicTimelineTopic { + id?: string; name: string; count: number; } @@ -27,11 +28,17 @@ export interface TimelineYearRange { endYear: number; } +export interface TimelineTopicSelection { + topic: TopicTimelineTopic; + years: number[]; +} + interface ResearchTimelinePhase { id: string; startYear: number; endYear: number; publication_count: number; + primaryTopic: TopicTimelineTopic; primaryTopicName: string; years: TopicTimelineElement[]; topics: TopicTimelineTopic[]; @@ -41,6 +48,7 @@ interface WorkingResearchTimelinePhase { startYear: number; endYear: number; publication_count: number; + primaryTopic: TopicTimelineTopic; primaryTopicName: string; years: TopicTimelineElement[]; } @@ -62,6 +70,8 @@ export class ResearchTimelineComponent implements OnChanges { @Output() viewModeChange = new EventEmitter(); @Output() yearRangeChange = new EventEmitter(); + @Output() topicSelect = new EventEmitter(); + @Output() yearSelect = new EventEmitter(); timelineViewMode: TimelineViewMode = 'years'; @@ -167,12 +177,37 @@ export class ResearchTimelineComponent implements OnChanges { this.emitYearRangeChange(); } + selectTopic(topic: TopicTimelineTopic | undefined, years: number[]): void { + if (!topic?.id || years.length === 0) { + return; + } + + this.topicSelect.emit({ + topic, + years: this.normalizeSelectedYears(years), + }); + } + + selectYears(years: number[]): void { + const selectedYears = this.normalizeSelectedYears(years); + + if (selectedYears.length === 0) { + return; + } + + this.yearSelect.emit(selectedYears); + } + getPrimaryTopic(item: TopicTimelineElement): TopicTimelineTopic | undefined { return (item.primary_topics ?? [])[0]; } getMainTopic(item: TopicTimelineElement): string { - return this.getPrimaryTopic(item)?.name ?? this.getFirstTopic(item)?.name ?? 'Keine Topics'; + return this.getMainTopicItem(item)?.name ?? 'Keine Topics'; + } + + getMainTopicItem(item: TopicTimelineElement): TopicTimelineTopic | undefined { + return this.getPrimaryTopic(item) ?? this.getFirstTopic(item); } getDisplayedTopics(item: TopicTimelineElement): TopicTimelineTopic[] { @@ -198,6 +233,10 @@ export class ResearchTimelineComponent implements OnChanges { return `${phase.startYear}–${phase.endYear}`; } + getPhaseYears(phase: ResearchTimelinePhase): number[] { + return phase.years.map((year) => year.year); + } + togglePhase(phase: ResearchTimelinePhase): void { if (this.expandedPhaseIds.has(phase.id)) { this.expandedPhaseIds.delete(phase.id); @@ -276,7 +315,10 @@ export class ResearchTimelineComponent implements OnChanges { if (candidates.length === 0) { this.pushWorkingPhase(phases, currentPhase); - currentPhase = this.createWorkingPhase(item, this.getMainTopic(item)); + currentPhase = this.createWorkingPhase( + item, + this.getMainTopicItem(item) ?? { name: 'Keine Topics', count: 0 }, + ); continue; } @@ -299,7 +341,7 @@ export class ResearchTimelineComponent implements OnChanges { } this.pushWorkingPhase(phases, currentPhase); - currentPhase = this.createWorkingPhase(item, candidates[0].name); + currentPhase = this.createWorkingPhase(item, candidates[0]); } this.pushWorkingPhase(phases, currentPhase); @@ -309,13 +351,14 @@ export class ResearchTimelineComponent implements OnChanges { private createWorkingPhase( item: TopicTimelineElement, - primaryTopicName: string, + primaryTopic: TopicTimelineTopic, ): WorkingResearchTimelinePhase { return { startYear: item.year, endYear: item.year, publication_count: item.publication_count, - primaryTopicName, + primaryTopic, + primaryTopicName: primaryTopic.name, years: [item], }; } @@ -328,21 +371,58 @@ export class ResearchTimelineComponent implements OnChanges { return; } + const primaryTopic = this.aggregatePhasePrimaryTopic( + workingPhase.years, + workingPhase.primaryTopic, + ); + phases.push({ ...workingPhase, + primaryTopic, + primaryTopicName: primaryTopic.name, id: `${workingPhase.startYear}-${workingPhase.endYear}-${this.normalizeTopicName( - workingPhase.primaryTopicName, + primaryTopic.name, )}`, - topics: this.aggregatePhaseTopics(workingPhase.years, workingPhase.primaryTopicName), + topics: this.aggregatePhaseTopics(workingPhase.years, primaryTopic.name), }); } + private aggregatePhasePrimaryTopic( + years: TopicTimelineElement[], + primaryTopic: TopicTimelineTopic, + ): TopicTimelineTopic { + const primaryTopicName = primaryTopic.name; + let count = 0; + let id = primaryTopic.id; + + for (const year of years) { + for (const topic of year.primary_topics ?? []) { + if (!this.isSameTopic(topic.name, primaryTopicName)) { + continue; + } + + count += topic.count; + + if (!id && topic.id) { + id = topic.id; + } + } + } + + return { + id, + name: primaryTopicName, + count: count > 0 ? count : primaryTopic.count, + }; + } + private aggregatePhaseTopics( years: TopicTimelineElement[], primaryTopicName: string, ): TopicTimelineTopic[] { const counts = new Map(); const originalNames = new Map(); + const ids = new Map(); for (const year of years) { for (const topic of year.topics ?? []) { @@ -353,12 +433,18 @@ export class ResearchTimelineComponent implements OnChanges { const normalizedName = this.normalizeTopicName(topic.name); originalNames.set(normalizedName, topic.name); + + if (topic.id) { + ids.set(normalizedName, topic.id); + } + counts.set(normalizedName, (counts.get(normalizedName) ?? 0) + topic.count); } } return Array.from(counts.entries()) .map(([normalizedName, count]) => ({ + id: ids.get(normalizedName), name: originalNames.get(normalizedName) ?? normalizedName, count, })) @@ -372,6 +458,12 @@ export class ResearchTimelineComponent implements OnChanges { .slice(0, this.displayedPhaseTopicLimit); } + private normalizeSelectedYears(years: number[]): number[] { + return Array.from(new Set(years)) + .filter((year) => Number.isFinite(year)) + .sort((left, right) => left - right); + } + private getDominantPrimaryTopicCandidates(item: TopicTimelineElement): TopicTimelineTopic[] { const primaryTopics = item.primary_topics ?? []; diff --git a/webapp/src/app/modules/person-overview/person-overview.component.html b/webapp/src/app/modules/person-overview/person-overview.component.html index 363ee7f6..67f93c9d 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.html +++ b/webapp/src/app/modules/person-overview/person-overview.component.html @@ -8,5 +8,7 @@ [endYear]="timelineEndYear" (viewModeChange)="onTimelineViewModeChange($event)" (yearRangeChange)="onTimelineYearRangeChange($event)" + (topicSelect)="onTimelineTopicSelect($event)" + (yearSelect)="onTimelineYearSelect($event)" > - \ No newline at end of file + diff --git a/webapp/src/app/modules/person-overview/person-overview.component.ts b/webapp/src/app/modules/person-overview/person-overview.component.ts index e3c31b4a..a6f20d55 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -10,6 +10,7 @@ import { ResearchTimelineComponent, TimelineViewMode, TimelineYearRange, + TimelineTopicSelection, TopicTimelineElement, TopicTimelineTopic, } from './components/research-timeline/research-timeline.component'; @@ -89,6 +90,36 @@ export class PersonOverviewComponent implements OnInit { ); } + onTimelineTopicSelect(selection: TimelineTopicSelection): void { + if (!selection.topic.id) { + return; + } + + void this.router.navigate(['../publications'], { + relativeTo: this.route, + queryParams: { + publicationPage: 1, + publicationYear: selection.years, + publicationTopicId: selection.topic.id, + publicationTopicName: selection.topic.name, + }, + }); + } + + onTimelineYearSelect(years: number[]): void { + if (years.length === 0) { + return; + } + + void this.router.navigate(['../publications'], { + relativeTo: this.route, + queryParams: { + publicationPage: 1, + publicationYear: years, + }, + }); + } + private findAuthorId(paramMaps: readonly ParamMap[]): string { return ( paramMaps @@ -140,7 +171,8 @@ export class PersonOverviewComponent implements OnInit { } private mapTopicCounts(topics: TopicCount[] | undefined): TopicTimelineTopic[] { - return (topics ?? []).map((topic) => ({ + return (topics ?? []).map((topic: TopicCount & { id?: string | null }) => ({ + id: topic.id ?? undefined, name: topic.name, count: topic.count ?? 0, })); @@ -175,4 +207,4 @@ export class PersonOverviewComponent implements OnInit { replaceUrl, }); } -} \ No newline at end of file +} diff --git a/webapp/src/app/modules/person-publications/person-publications.component.html b/webapp/src/app/modules/person-publications/person-publications.component.html index 96c5df8d..a34b24ef 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.html +++ b/webapp/src/app/modules/person-publications/person-publications.component.html @@ -1,16 +1,16 @@
-
-
-
Publikationen
-

Übersicht der wissenschaftlichen Veröffentlichungen.

-
+
+
Publikationen
+

Übersicht der wissenschaftlichen Veröffentlichungen.

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

{{ displayName() }}

-
-

{{ institution() }}

- @if (countryCode()) { - {{ countryCode() }} - } - @if (worksCount() !== null || citedByCount() !== null) { - - @if (worksCount() !== null) { - {{ worksCount() }} Publikationen +@if (!isPersonLoading()) { +
+
+
{{ initials() }}
+
+
+ Person +

{{ displayName() }}

+
+

{{ institution() }}

+ @if (countryCode()) { + {{ countryCode() }} } - @if (worksCount() !== null && citedByCount() !== null) { - · + @if (worksCount() !== null || citedByCount() !== null) { + + @if (worksCount() !== null) { + {{ worksCount() }} Publikationen + } + @if (worksCount() !== null && citedByCount() !== null) { + · + } + @if (citedByCount() !== null) { + {{ citedByCount() }} Zitationen + } + } - @if (citedByCount() !== null) { - {{ citedByCount() }} Zitationen +
+
+
+ mail + uni-email@uni-due.de +
+ @if (orcid()) { +
+ verified + {{ + orcid() + }} +
} - - } -
-
-
- mail - uni-email@uni-due.de -
- @if (orcid()) { -
- verified - {{ orcid() }} -
- } -
-
- - -
- + + +
+ } @else { -
- -
+
+ + Person wird geladen... + +
} - - \ No newline at end of file + @if (isNetworkResolving()) { +
+
+ + + graph_3 + +
+ Das Netzwerk wird gebaut, kleinen Moment... +
+ } @else { + + } + diff --git a/webapp/src/app/modules/person/person.component.scss b/webapp/src/app/modules/person/person.component.scss index 2e5d744b..82751b4f 100644 --- a/webapp/src/app/modules/person/person.component.scss +++ b/webapp/src/app/modules/person/person.component.scss @@ -35,12 +35,16 @@ height: 112px; border-radius: 50%; background: - radial-gradient(circle at 50% 30%, rgba(255, 255, 255, 0.78), transparent 34%), + radial-gradient( + circle at 50% 30%, + rgba(255, 255, 255, 0.78), + transparent 34% + ), linear-gradient(145deg, #c8d9ff, #f7faff 48%, #88a9ee); border: 1px solid var(--sg-border); box-shadow: var(--sg-shadow-sm); color: var(--sg-primary); - font-family: 'Montserrat', 'Open Sans', Arial, sans-serif; + font-family: "Montserrat", "Open Sans", Arial, sans-serif; font-size: 28px; font-weight: 700; } @@ -220,3 +224,44 @@ overflow-x: auto; } } + +.loading-container { + display: flex; + flex-direction: column; + align-items: center; + gap: 16px; + padding: 48px 0; +} + +.spinner-container { + --spinner-size: 60px; + + position: relative; + width: var(--spinner-size); + height: var(--spinner-size); +} + +.spinner-icon { + position: absolute; + inset: 0; + margin: auto; + + font-size: calc(var(--spinner-size) * 0.4); + width: calc(var(--spinner-size) * 0.4); + height: calc(var(--spinner-size) * 0.4); + + animation: pulse 1.2s ease-in-out infinite; +} + +@keyframes pulse { + 0%, + 100% { + transform: scale(1); + opacity: 1; + } + + 50% { + transform: scale(1.2); + opacity: 0.7; + } +} diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 5aef3001..717aacf1 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -1,10 +1,21 @@ import { Component, computed, inject, signal, DestroyRef } from '@angular/core'; -import { toSignal, toObservable } from '@angular/core/rxjs-interop'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { + toSignal, + toObservable, + takeUntilDestroyed, +} from '@angular/core/rxjs-interop'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinner } from '@angular/material/progress-spinner'; import { MatTabsModule } from '@angular/material/tabs'; -import { ActivatedRoute, RouterModule, RouterOutlet } from '@angular/router'; +import { + ActivatedRoute, + ResolveEnd, + ResolveStart, + Router, + RouterEvent, + RouterModule, + RouterOutlet, +} from '@angular/router'; import { of, switchMap, finalize, map, catchError } from 'rxjs'; import { PersonInterestingComponent } from '../person-interesting/person-interesting.component'; @@ -28,20 +39,52 @@ const PERSON_INCLUDE_TAGS = styleUrl: './person.component.scss', }) export class PersonComponent { - private route = inject(ActivatedRoute); + private readonly router = inject(Router); + private readonly activatedRoute = inject(ActivatedRoute); + private readonly personsApi = inject(PersonsService); private readonly worksApi = inject(WorksService); private readonly destroyRef = inject(DestroyRef); - + readonly params = toSignal(this.activatedRoute.paramMap); + readonly routerEvents = toSignal(this.router.events); + + readonly currentUrl = computed(() => this.router.url); + // derive authorID directly from route private readonly authorId = toSignal( - this.route.paramMap.pipe( + this.activatedRoute.paramMap.pipe( map((params) => params.get('id') ?? null), - takeUntilDestroyed(this.destroyRef) - ) + takeUntilDestroyed(this.destroyRef), + ), ); + readonly isNetworkResolving = computed(() => { + const event = this.routerEvents(); + + if ( + !(event instanceof RouterEvent) || // not a router event + !this.isResolverEvent(event) || // not a resolver event + !this.isNetworkRouterEvent(event) // not navigating to network route + ) { + return false; + } + + if (event instanceof ResolveStart) { + return true; + } + + return false; + }); + + isResolverEvent(event: RouterEvent): boolean { + return event instanceof ResolveStart || event instanceof ResolveEnd; + } + + isNetworkRouterEvent(event: RouterEvent): boolean { + return event.url.startsWith(`/person/${this.authorId()}/network`); + } + // loading states readonly isPersonLoading = signal(false); readonly isBioLoading = signal(false); @@ -51,42 +94,44 @@ export class PersonComponent { switchMap((id) => { if (!id) return of(null); this.isPersonLoading.set(true); - return this.personsApi.searchPersons(id, undefined, PERSON_INCLUDE_TAGS).pipe( - map((result) => result.results?.[0] ?? null), - catchError((err) => { - console.error('Failed to load person:', err); - return of(null); - }), - finalize(() => this.isPersonLoading.set(false)) - ); - }) + return this.personsApi + .searchPersons(id, undefined, PERSON_INCLUDE_TAGS) + .pipe( + map((result) => result.results?.[0] ?? null), + catchError((err) => { + console.error('Failed to load person:', err); + return of(null); + }), + finalize(() => this.isPersonLoading.set(false)), + ); + }), ), - { initialValue: null } + { initialValue: null }, ); // bio data -readonly personBio = toSignal( - toObservable(this.authorId).pipe( - switchMap((id) => { - if (!id) { - this.isBioLoading.set(false); - return of(null); - } - this.isBioLoading.set(true); - return this.personsApi.generatePersonBio(id).pipe( - map((result) => { - this.isBioLoading.set(false); - return result.bio ?? null; - }), - catchError((err) => { - console.error('Failed to load bio:', err); + readonly personBio = toSignal( + toObservable(this.authorId).pipe( + switchMap((id) => { + if (!id) { this.isBioLoading.set(false); return of(null); - }) - ); - }) - ), - { initialValue: null } -); + } + this.isBioLoading.set(true); + return this.personsApi.generatePersonBio(id).pipe( + map((result) => { + this.isBioLoading.set(false); + return result.bio ?? null; + }), + catchError((err) => { + console.error('Failed to load bio:', err); + this.isBioLoading.set(false); + return of(null); + }), + ); + }), + ), + { initialValue: null }, + ); readonly displayName = computed( () => this.person()?.display_name ?? 'Unbekannte Person', ); @@ -94,17 +139,21 @@ readonly personBio = toSignal( readonly primaryAffiliation = computed( () => this.person()?.affiliations?.[0] ?? null, ); - readonly lastAffiliation = computed( - ()=> { - let lastAffiliation: number | undefined = 0 - if (this.person()?.affiliations?.length != undefined){ - lastAffiliation = this.person()?.affiliations?.length - } - return (lastAffiliation ? this.person()?.affiliations?.[lastAffiliation - 1] : this.person()?.affiliations?.[0]) ?? null + readonly lastAffiliation = computed(() => { + let lastAffiliation: number | undefined = 0; + if (this.person()?.affiliations?.length != undefined) { + lastAffiliation = this.person()?.affiliations?.length; } - ) + return ( + (lastAffiliation + ? this.person()?.affiliations?.[lastAffiliation - 1] + : this.person()?.affiliations?.[0]) ?? null + ); + }); readonly institution = computed( - () => this.lastAffiliation()?.institution?.display_name ?? 'Unbekannte Institution', + () => + this.lastAffiliation()?.institution?.display_name ?? + 'Unbekannte Institution', ); readonly countryCode = computed( () => this.lastAffiliation()?.institution?.country_code ?? null, @@ -131,11 +180,11 @@ readonly personBio = toSignal( catchError((err) => { console.error('Failed to load primary topic counts:', err); return of([]); - }) + }), ); - }) + }), ), - { initialValue: [] } + { initialValue: [] }, ); links = [ { label: 'Übersicht', path: 'overview', disabled: false }, diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.html b/webapp/src/app/modules/publication-detail/publication-detail.component.html new file mode 100644 index 00000000..58179d64 --- /dev/null +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.html @@ -0,0 +1,256 @@ +
+ + + @if (loading) { +
+ +

Publikation wird geladen...

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

Publikation nicht gefunden

+

Die Publikation konnte nicht geladen werden.

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

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

+

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

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

Abstract

+
+

{{ abstract }}

+
+ } + +
+
+ group +

Autorinnen und Autoren

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

Keine Angaben vorhanden.

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

Themen und Keywords

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

Quellen und Versionen

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

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

+
+
+ @if (location.is_oa) { + Open Access + } + @if (location.pdf_url || location.landing_page_url; as sourceUrl) { + + open_in_new + + } +
+
+ } +
+
+ } +
+ + +
+ } +
diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.scss b/webapp/src/app/modules/publication-detail/publication-detail.component.scss new file mode 100644 index 00000000..9e183808 --- /dev/null +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.scss @@ -0,0 +1,436 @@ +:host { + display: block; + background: var(--sg-background); +} + +.detail-page { + max-width: 1500px; + margin: 0 auto; + padding: 26px 32px 56px; +} + +.back-link { + display: inline-flex; + align-items: center; + gap: 7px; + margin-bottom: 22px; + padding: 0; + border: 0; + background: transparent; + color: var(--sg-text-muted); + font-size: 13px; + font-weight: 600; + text-decoration: none; + cursor: pointer; +} + +.back-link mat-icon { + width: 18px; + height: 18px; + font-size: 18px; +} + +.hero { + display: grid; + grid-template-columns: minmax(0, 1fr) 420px; + gap: 42px; + padding: 38px 42px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-lg); + background: + radial-gradient(circle at 90% 10%, rgba(200, 217, 255, 0.75), transparent 35%), + linear-gradient(140deg, #fff 0%, #f8faff 100%); + box-shadow: var(--sg-shadow-sm); +} + +.eyebrow, +.tags, +.hero-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.eyebrow span { + padding: 5px 10px; + border: 1px solid var(--sg-border); + border-radius: 999px; + background: rgba(255, 255, 255, 0.85); + color: var(--sg-text-muted); + font-size: 11px; + font-weight: 700; + text-transform: uppercase; +} + +h1 { + max-width: 920px; + margin: 20px 0 13px; + font-size: clamp(27px, 3vw, 42px); + line-height: 1.13; +} + +.author-line { + max-width: 900px; + margin: 0; + color: var(--sg-text-muted); + font-size: 14px; + line-height: 1.7; +} + +.hero-actions { + margin-top: 26px; +} + +.hero-actions a { + display: inline-flex; + align-items: center; + gap: 8px; + min-height: 42px; + padding: 9px 16px; + border: 1px solid var(--sg-border-strong); + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + font-weight: 700; + text-decoration: none; +} + +.hero-actions a.primary-action { + border-color: var(--sg-primary); + background: var(--sg-primary); + color: #fff; +} + +.hero-actions mat-icon { + width: 17px; + height: 17px; + font-size: 17px; +} + +.metrics { + display: grid; + grid-template-columns: repeat(3, 1fr); + align-self: center; + overflow: hidden; + border: 1px solid rgba(199, 211, 232, 0.8); + border-radius: var(--sg-radius-md); + background: rgba(255, 255, 255, 0.8); +} + +.metrics div { + display: flex; + align-items: center; + flex-direction: column; + gap: 5px; + padding: 22px 10px; + text-align: center; +} + +.metrics div + div { + border-left: 1px solid var(--sg-border); +} + +.metrics mat-icon { + color: var(--sg-text-soft); +} + +.metrics .positive mat-icon { + color: var(--sg-success); +} + +.metrics strong { + color: var(--sg-text); + font-family: "Montserrat", "Open Sans", sans-serif; + font-size: 22px; +} + +.metrics span { + color: var(--sg-text-muted); + font-size: 11px; +} + +.warning { + display: flex; + align-items: center; + gap: 10px; + margin-top: 20px; + padding: 14px 18px; + border: 1px solid #f1c6cc; + border-radius: var(--sg-radius-sm); + background: #fff4f5; + color: #9c2637; + font-weight: 700; +} + +.content-grid { + display: grid; + grid-template-columns: minmax(0, 1fr) 380px; + gap: 24px; + margin-top: 24px; +} + +main, +aside { + display: flex; + flex-direction: column; + gap: 24px; +} + +.card { + padding: 26px 28px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-md); + background: var(--sg-surface); + box-shadow: var(--sg-shadow-sm); +} + +.section-title { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 20px; +} + +.section-title mat-icon { + color: var(--sg-text-muted); +} + +.section-title h2 { + margin: 0; + font-size: 16px; +} + +.section-title span { + margin-left: auto; + color: var(--sg-text-muted); + font-size: 12px; +} + +.abstract-card p { + margin: 0; + color: var(--sg-text); + font-size: 14px; + line-height: 1.8; +} + +.author-list { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; +} + +.author-list article { + display: grid; + grid-template-columns: 38px minmax(0, 1fr); + gap: 11px; + align-items: center; + padding: 12px; + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-muted); +} + +.avatar { + display: grid; + place-items: center; + width: 38px; + height: 38px; + border-radius: 50%; + background: #e5ecfb; + color: var(--sg-text); + font-weight: 700; + text-transform: uppercase; +} + +.author-list a, +.author-list strong { + color: var(--sg-text); + font-size: 13px; + font-weight: 700; + text-decoration: none; +} + +.author-list p, +.source-list p { + margin: 3px 0 0; + color: var(--sg-text-muted); + font-size: 11px; +} + +.tags span { + padding: 7px 10px; + border: 1px solid var(--sg-border); + border-radius: 999px; + color: var(--sg-text-muted); + font-size: 11px; +} + +.tags .topic-tag { + border-color: #cbd8f1; + background: #f5f8ff; + color: var(--sg-text); +} + +.source-list, +.compact-list, +.link-list { + display: grid; + gap: 10px; +} + +.source-list article, +.compact-list div { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 13px 0; + border-bottom: 1px solid var(--sg-border); +} + +.source-list article:last-child, +.compact-list div:last-child { + border-bottom: 0; +} + +.source-actions { + display: flex; + align-items: center; + gap: 10px; +} + +.source-actions a { + height: 24px; +} + +.source-actions mat-icon { + width: 20px; + height: 20px; + font-size: 20px; +} + +.oa-badge { + padding: 4px 8px; + border-radius: 999px; + background: var(--sg-success-soft); + color: var(--sg-success); + font-size: 10px; + font-weight: 700; +} + +dl { + margin: 0; +} + +dl div { + display: grid; + grid-template-columns: 115px minmax(0, 1fr); + gap: 12px; + padding: 10px 0; + border-bottom: 1px solid var(--sg-border); +} + +dl div:last-child { + border-bottom: 0; +} + +dt { + color: var(--sg-text-muted); + font-size: 12px; +} + +dd { + margin: 0; + overflow-wrap: anywhere; + color: var(--sg-text); + font-size: 12px; + font-weight: 600; + text-align: right; +} + +.compact-list div { + align-items: flex-start; + flex-direction: column; + gap: 3px; +} + +.compact-list strong { + font-size: 12px; +} + +.compact-list span { + color: var(--sg-text-muted); + font-size: 11px; +} + +.link-list a { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 0; + border-bottom: 1px solid var(--sg-border); + color: var(--sg-text); + font-size: 12px; + font-weight: 700; + text-decoration: none; +} + +.link-list a:last-child { + border-bottom: 0; +} + +.link-list mat-icon { + width: 16px; + height: 16px; + color: var(--sg-text-muted); + font-size: 16px; +} + +.state { + display: grid; + place-items: center; + min-height: 380px; + color: var(--sg-text-muted); + text-align: center; +} + +.error-state mat-icon { + width: 46px; + height: 46px; + font-size: 46px; +} + +.empty { + color: var(--sg-text-muted); +} + +@media (max-width: 1150px) { + .hero, + .content-grid { + grid-template-columns: 1fr; + } + + .metrics { + width: 100%; + } +} + +@media (max-width: 700px) { + .detail-page { + padding: 18px 16px 40px; + } + + .hero, + .card { + padding: 22px 20px; + } + + .metrics, + .author-list { + grid-template-columns: 1fr; + } + + .metrics div + div { + border-top: 1px solid var(--sg-border); + border-left: 0; + } +} diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts new file mode 100644 index 00000000..e4c0b56f --- /dev/null +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -0,0 +1,182 @@ +import { DatePipe, DecimalPipe, UpperCasePipe } from '@angular/common'; +import { Location } from '@angular/common'; +import { Component, DestroyRef, OnInit, inject } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { HttpClient } from '@angular/common/http'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { ActivatedRoute, RouterLink } from '@angular/router'; +import { finalize } from 'rxjs'; + +import { Authorship, Location as ApiLocation, Work, WorksService } from '../../api'; + +interface DetailLink { + label: string; + url: string; +} + +interface InstitutionDetail { + id: string; + name: string; + country?: string | null; + type?: string | null; +} + +@Component({ + selector: 'app-publication-detail', + imports: [ + DatePipe, + DecimalPipe, + MatButtonModule, + MatIconModule, + MatProgressSpinnerModule, + RouterLink, + UpperCasePipe, + ], + templateUrl: './publication-detail.component.html', + styleUrl: './publication-detail.component.scss', +}) +export class PublicationDetailComponent implements OnInit { + private readonly destroyRef = inject(DestroyRef); + private readonly route = inject(ActivatedRoute); + private readonly httpClient = inject(HttpClient); + private readonly location = inject(Location); + private readonly worksService = inject(WorksService); + + publication: Work | null = null; + loading = true; + notFound = false; + + ngOnInit(): void { + this.route.paramMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + const publicationId = params.get('publicationId'); + if (!publicationId) { + this.loading = false; + this.notFound = true; + return; + } + + this.loadPublication(publicationId); + }); + } + + navigateBack(): void { + this.location.back(); + } + + abstractText(): string | null { + const index = this.publication?.abstract_inverted_index; + if (!index || typeof index !== 'object') return null; + + const words: Array<{ word: string; position: number }> = []; + for (const [word, rawPositions] of Object.entries(index)) { + if (!Array.isArray(rawPositions)) continue; + for (const position of rawPositions) { + if (typeof position === 'number') words.push({ word, position }); + } + } + + return words + .sort((first, second) => first.position - second.position) + .map(({ word }) => word) + .join(' ') || null; + } + + authors(): Authorship[] { + return this.publication?.authorships ?? []; + } + + institutions(): InstitutionDetail[] { + const institutions = new Map(); + for (const authorship of this.authors()) { + for (const institution of authorship.institutions ?? []) { + if (!institution.id || !institution.display_name) continue; + institutions.set(institution.id, { + id: institution.id, + name: institution.display_name, + country: institution.country_code, + type: institution.type, + }); + } + } + return Array.from(institutions.values()); + } + + sources(): ApiLocation[] { + const locations = [ + this.publication?.primary_location, + this.publication?.best_oa_location, + ...(this.publication?.locations ?? []), + ].filter((location): location is ApiLocation => !!location); + const unique = new Map(); + for (const location of locations) { + const key = + location.source?.id ?? + location.landing_page_url ?? + location.pdf_url ?? + JSON.stringify(location); + unique.set(key, location); + } + return Array.from(unique.values()); + } + + externalLinks(): DetailLink[] { + if (!this.publication) return []; + const links: DetailLink[] = []; + this.addLink(links, 'Open Access', this.publication.open_access?.oa_url); + this.addLink(links, 'DOI', this.doiUrl(this.publication.doi)); + return links.filter( + (link, index) => links.findIndex((candidate) => candidate.url === link.url) === index, + ); + } + + pages(): string | null { + const first = this.publication?.biblio?.first_page; + const last = this.publication?.biblio?.last_page; + if (first && last) return `${first}-${last}`; + return first ?? last ?? null; + } + + openAccessLabel(): string { + if (this.publication?.open_access?.is_oa) { + return this.publication.open_access.oa_status + ? `Open Access (${this.publication.open_access.oa_status})` + : 'Open Access'; + } + return 'Kein Open Access'; + } + + private loadPublication(publicationId: string): void { + this.loading = true; + this.notFound = false; + this.publication = null; + + const basePath = this.worksService.configuration.basePath ?? ''; + this.httpClient + .get( + `${basePath}/api/works/detail/${encodeURIComponent(publicationId)}`, + ) + .pipe(finalize(() => (this.loading = false))) + .subscribe({ + next: (publication) => { + this.publication = publication; + }, + error: () => { + this.notFound = true; + }, + }); + } + + private doiUrl(doi: string | null | undefined): string | null { + if (!doi) return null; + return doi.startsWith('http') ? doi : `https://doi.org/${doi}`; + } + + private addLink(links: DetailLink[], label: string, value: string | null | undefined) { + if (!value) return; + links.push({ label, url: value.startsWith('http') ? value : `https://${value}` }); + } +} diff --git a/webapp/src/app/resolvers/collaboration-network.resolver.ts b/webapp/src/app/resolvers/collaboration-network.resolver.ts index e09b8747..f15ac150 100644 --- a/webapp/src/app/resolvers/collaboration-network.resolver.ts +++ b/webapp/src/app/resolvers/collaboration-network.resolver.ts @@ -1,9 +1,11 @@ import { ResolveFn } from '@angular/router'; import { inject } from '@angular/core'; import { + AuthorsFilterProperties, CollaborationNetwork, FilterProperties, PersonNetworkService, + WorksFilterProperties, } from '../api'; export const collaborationNetworkResolver: ResolveFn = ( @@ -16,37 +18,50 @@ export const collaborationNetworkResolver: ResolveFn = ( } const startYear = route.queryParamMap.get('start_year'); const endYear = route.queryParamMap.get('end_year'); - const minimumCollaborators = route.queryParamMap.get('minimum_collaborators'); - const maximumCollaborators = route.queryParamMap.get('maximum_collaborators'); - const minimumCollaborations = route.queryParamMap.get( - 'minimum_collaborations', - ); - const maximumCollaborations = route.queryParamMap.get( - 'maximum_collaborations', - ); + const minContributors = route.queryParamMap.get('min_contributors'); + const maxContributors = route.queryParamMap.get('max_contributors'); + const minCollaborations = route.queryParamMap.get('min_collaborations'); + const maxCollaborations = route.queryParamMap.get('max_collaborations'); const institutions = route.queryParamMap.get('institutions'); const topics = route.queryParamMap.get('topics'); + const filterBy = route.queryParamMap.get('filter_by') || 'works'; + + if (filterBy !== 'works' && filterBy !== 'authors') { + throw new Error("Invalid filter_by value. Expected 'works' or 'authors'."); + } + + let worksFilterProperties: WorksFilterProperties | null = null; + let authorsFilterProperties: AuthorsFilterProperties | null = null; + if (filterBy === 'works') { + worksFilterProperties = { + start_year: startYear ? Number.parseInt(startYear, 10) : undefined, + end_year: endYear ? Number.parseInt(endYear, 10) : undefined, + min_contributors: minContributors + ? Number.parseInt(minContributors, 10) + : undefined, + max_contributors: maxContributors + ? Number.parseInt(maxContributors, 10) + : undefined, + allowed_topics: topics ? topics.split(',') : undefined, + }; + } + if (filterBy === 'authors') { + authorsFilterProperties = { + min_collaborations: minCollaborations + ? Number.parseInt(minCollaborations, 10) + : undefined, + max_collaborations: maxCollaborations + ? Number.parseInt(maxCollaborations, 10) + : undefined, + allowed_institutions: institutions ? institutions.split(',') : undefined, + }; + } - console.log('Resolving collaboration network for author ID:', rawAuthorId); const filterProperties: FilterProperties = { - start_year: startYear ? Number.parseInt(startYear, 10) : null, - end_year: endYear ? Number.parseInt(endYear, 10) : null, - min_collaborators: minimumCollaborators - ? Number.parseInt(minimumCollaborators, 10) - : 2, - max_collaborators: maximumCollaborators - ? Number.parseInt(maximumCollaborators, 10) - : 10, - min_collaborations: minimumCollaborations - ? Number.parseInt(minimumCollaborations, 10) - : 1, - max_collaborations: maximumCollaborations - ? Number.parseInt(maximumCollaborations, 10) - : null, - allowed_institutions: institutions ? institutions.split(',') : null, - allowed_topics: topics ? topics.split(',') : null, + filter_by: filterBy, + works_filter_properties: worksFilterProperties, + authors_filter_properties: authorsFilterProperties, }; - console.log('Using filter properties:', filterProperties); return inject(PersonNetworkService).getCollaborationNetwork( rawAuthorId, diff --git a/webapp/src/app/resolvers/person-list.resolver.ts b/webapp/src/app/resolvers/person-list.resolver.ts new file mode 100644 index 00000000..a5503d67 --- /dev/null +++ b/webapp/src/app/resolvers/person-list.resolver.ts @@ -0,0 +1,58 @@ +import { ResolveFn } from '@angular/router'; +import { inject } from '@angular/core'; +import { PersonsService, CustomAuthorsListResponse } from '../api'; + +export const personListResolver: ResolveFn = ( + route, + state, +) => { + const parseQueryParamArray = (val: any): string[] => { + if (!val) return []; + if (Array.isArray(val)) return val; + return [val]; + }; + const defaultIncludes = + 'display_name,works_count,cited_by_count,topics,orcid,relevance_rating,last_known_institutions,affiliations'; + const params = route.queryParamMap; + + const query = params.get('query') || undefined; + + const page = params.get('page') + ? Number.parseInt(params.get('page')!, 10) + : 1; + + const pageSize = params.get('pageSize') + ? Number.parseInt(params.get('pageSize')!, 10) + : 10; + + const institutionName = params.get('institutionName') || undefined; + + const topicsParam = params.getAll('topic'); + + const topics = parseQueryParamArray(topicsParam) + const yearFilterEnabled = params.get('yearFilterEnabled') === 'true'; + + const filterModeRaw = params.get('filterMode'); + const filterMode = + filterModeRaw === 'in' || filterModeRaw === 'from' + ? filterModeRaw + : undefined; + + const filterYear = params.get('filterYear') + ? Number.parseInt(params.get('filterYear')!, 10) + : undefined; + + const personsService = inject(PersonsService); + + return personsService.searchPersonsList( + query, + institutionName, + topics, + page, + pageSize, + defaultIncludes, + yearFilterEnabled ? true : undefined, + yearFilterEnabled ? filterMode : undefined, + yearFilterEnabled ? filterYear : undefined, + ); +}; diff --git a/webapp/src/app/shared/services/shared-state.service.ts b/webapp/src/app/shared/services/shared-state.service.ts index e03428ba..4dda1383 100644 --- a/webapp/src/app/shared/services/shared-state.service.ts +++ b/webapp/src/app/shared/services/shared-state.service.ts @@ -3,7 +3,6 @@ import { AuthorsListResponse } from '../../api'; @Injectable({ providedIn: 'root' }) export class SharedStateService { - searchValue = signal(null); persons = signal({ meta: null, results: [], diff --git a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts index 711c0211..3196c3b5 100644 --- a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts +++ b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts @@ -1,4 +1,4 @@ -import { Component, inject, ViewChild, DestroyRef} from '@angular/core'; +import { Component, inject, ViewChild, DestroyRef } from '@angular/core'; import { MatIcon } from '@angular/material/icon'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { Router, ActivatedRoute } from '@angular/router'; @@ -43,11 +43,19 @@ export class AppSearchbarComponent { private readonly router = inject(Router); private readonly route = inject(ActivatedRoute); private readonly personService = inject(PersonsService); - constructor() { - const params = new URLSearchParams(window.location.search); - const currentSearch = params.get('query') ?? ''; - this.searchControl.setValue(currentSearch, { emitEvent: false }); + const route = inject(ActivatedRoute); + const router = inject(Router); + + // Sync searchControl from query param on every URL change + route.queryParams + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + const query = params['query'] ?? ''; + if (this.searchControl.value !== query) { + this.searchControl.setValue(query, { emitEvent: false }); + } + }); // Autocomplete suggestions this.searchControl.valueChanges diff --git a/webapp/src/styles.scss b/webapp/src/styles.scss index 17b951de..0a3a5f8d 100644 --- a/webapp/src/styles.scss +++ b/webapp/src/styles.scss @@ -6,6 +6,8 @@ @include mat.elevation-classes(); @include mat.app-background(); +@import url("https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,200..700,0..1,-50..200"); + @font-face { font-display: swap; font-family: "Montserrat"; @@ -58,6 +60,22 @@ -webkit-font-smoothing: antialiased; } +.material-symbols-outlined { + font-family: "Material Symbols Outlined"; + font-weight: normal; + font-style: normal; + font-size: 24px; + line-height: 1; + letter-spacing: normal; + text-transform: none; + display: inline-block; + white-space: nowrap; + word-wrap: normal; + direction: ltr; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; +} + html { padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left); @@ -100,6 +118,9 @@ body { --sg-radius-sm: 8px; --sg-radius-md: 12px; --sg-radius-lg: 18px; + + --sg-blue-highlight: #3d7cff; + --sg-default-bold-weight: 900; } * { @@ -165,3 +186,8 @@ h3 { --mat-icon-button-disabled-icon-color: rgba(255, 255, 255, 0.35); --mat-icon-button-icon-color: #ffffff; } + +@keyframes sk-shimmer { + 0% { background-position: -600px 0; } + 100% { background-position: 600px 0; } +} \ No newline at end of file