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/funders/logic.py b/service/src/main/inse/funders/logic.py index a04eb6fd..95a7493e 100644 --- a/service/src/main/inse/funders/logic.py +++ b/service/src/main/inse/funders/logic.py @@ -290,6 +290,7 @@ def _collect_funders_from_publications( "unknown": [], }, "publication_urls": {}, + "publication_titles": {}, } entry = funder_counts[key] @@ -298,3 +299,7 @@ def _collect_funders_from_publications( entry["publication_ids"][author_position].append(publication_id) if publication_id and publication_url: entry["publication_urls"][publication_id] = publication_url + if publication_id: + title = publication.get("display_name") or publication.get("title") or publication_id + entry["publication_titles"][publication_id] = title + diff --git a/service/src/main/inse/funders/model.py b/service/src/main/inse/funders/model.py index d2207541..982737b3 100644 --- a/service/src/main/inse/funders/model.py +++ b/service/src/main/inse/funders/model.py @@ -34,6 +34,7 @@ class FunderByAuthor(BaseModel): author_position_count: AuthorPositionCount publication_ids: PublicationIdsByAuthorPosition publication_urls: dict[str, str] = {} + publication_titles: dict[str, str] = {} class FundersByAuthorResponse(BaseModel): 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 467410b7..27c15dac 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -11,6 +11,7 @@ import httpx from fastapi import HTTPException from pydantic import ValidationError from starlette.status import HTTP_502_BAD_GATEWAY +from starlette.status import HTTP_404_NOT_FOUND from starlette.status import HTTP_503_SERVICE_UNAVAILABLE from inse.models.work import Work @@ -33,6 +34,8 @@ async def get_author_works( publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, client: OpenAlexWorksSearchClient | None = None, ) -> WorkPage: search_client = client or OpenAlexWorksSearchClient() @@ -44,6 +47,8 @@ async def get_author_works( publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ) elements, total = _parse_full_work_search_response(data) @@ -116,16 +121,80 @@ async def get_primary_topic_counts( ] +async def get_work( + work_id: str, + client: OpenAlexWorksSearchClient | None = None, +) -> Work: + search_client = client or OpenAlexWorksSearchClient() + try: + data = await search_client.search_work(work_id) + except MissingApiKeyError as exc: + raise HTTPException( + status_code=HTTP_503_SERVICE_UNAVAILABLE, + detail="OpenAlex works search is not configured.", + ) from exc + except httpx.HTTPError as exc: + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex works search request failed.", + ) from exc + elements, _ = _parse_full_work_search_response(data) + if not elements: + raise HTTPException( + status_code=HTTP_404_NOT_FOUND, + detail="Publication not found.", + ) + return elements[0] + + +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 @@ -217,6 +286,8 @@ async def _search_author_works_data( publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, ) -> dict: try: return await search_client.search_author_works( @@ -226,6 +297,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 13d8ad8b..f5876c65 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -1,96 +1,109 @@ .gitignore +.openapi-generator-ignore README.md api.base.service.ts api.module.ts api/api.ts api/funding.service.ts -api/funding.serviceInterface.ts -api/inse-account-service.service.ts -api/inse-account-service.serviceInterface.ts -api/inse-service.service.ts -api/inse-service.serviceInterface.ts +api/iNSEAccountService.service.ts +api/iNSEService.service.ts +api/institutions.service.ts api/items.service.ts -api/items.serviceInterface.ts -api/person-network.service.ts -api/person-network.serviceInterface.ts +api/personNetwork.service.ts api/persons.service.ts -api/persons.serviceInterface.ts api/topics.service.ts -api/topics.serviceInterface.ts api/works.service.ts -api/works.serviceInterface.ts configuration.ts encoder.ts git_push.sh index.ts -model/access-grant.ts -model/auth-account.ts -model/auth-scope.ts -model/author-affiliations-inner.ts -model/author-counts-by-year-inner.ts -model/author-ids.ts -model/author-parsed-longest-name.ts -model/author-position-count.ts -model/author-summary-stats.ts +model/accessGrant.ts +model/authAccount.ts +model/authScope.ts model/author.ts -model/authors-list-response.ts +model/authorAffiliationsInner.ts +model/authorCountsByYearInner.ts +model/authorIds.ts +model/authorNetworkNode.ts +model/authorParsedLongestName.ts +model/authorPositionCount.ts +model/authorSummaryStats.ts +model/authorsFilterProperties.ts +model/authorsListResponse.ts model/authorship.ts +model/autocompleteResponse.ts +model/autocompleteResponseMeta.ts +model/autocompleteResponseResultsInner.ts model/award.ts -model/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 -model/dehydrated-institution.ts -model/dehydrated-source.ts -model/filter-information.ts -model/filter-properties.ts -model/funder-by-author.ts -model/funders-by-author-response.ts +model/collaborationNetwork.ts +model/collaborationNetworkEdge.ts +model/collaborationNetworkNodeType.ts +model/costUsd.ts +model/customAuthor.ts +model/customAuthorsListResponse.ts +model/dehydratedAuthor.ts +model/dehydratedFunder.ts +model/dehydratedInstitution.ts +model/dehydratedSource.ts +model/filterInformation.ts +model/filterProperties.ts +model/funderByAuthor.ts +model/fundersByAuthorResponse.ts model/fwci.ts -model/group-by-result.ts -model/http-validation-error.ts -model/identity-grant.ts -model/institution-information.ts -model/item-create.ts -model/item-page.ts +model/groupByResult.ts +model/hTTPValidationError.ts +model/identityGrant.ts +model/institution.ts +model/institutionGeo.ts +model/institutionIds.ts +model/institutionInformation.ts +model/institutionNetworkNode.ts +model/institutionsListResponse.ts model/item.ts +model/itemCreate.ts +model/itemPage.ts +model/latitude.ts model/location.ts +model/longitude.ts model/meta.ts -model/model2-yr-mean-citedness.ts +model/model2YrMeanCitedness.ts model/models.ts -model/open-access.ts -model/person-bio.ts -model/publication-ids-by-author-position.ts -model/publications-by-author-response.ts +model/openAccess.ts +model/personBio.ts +model/publicationIdsByAuthorPosition.ts +model/publicationsByAuthorResponse.ts model/score.ts -model/topic-count.ts -model/topics-by-time.ts -model/topics-by-year.ts -model/validation-error-loc-inner.ts -model/validation-error.ts +model/topic.ts +model/topicCount.ts +model/topicDomain.ts +model/topicField.ts +model/topicIds.ts +model/topicSubfield.ts +model/topicsByTime.ts +model/topicsByYear.ts +model/topicsListResponse.ts +model/validationError.ts +model/validationErrorLocInner.ts model/value.ts -model/work-biblio.ts -model/work-citation-normalized-percentile.ts -model/work-cited-by-percentile-year.ts -model/work-counts-by-year-inner.ts -model/work-has-content.ts -model/work-ids.ts -model/work-keyword.ts -model/work-mesh-inner.ts -model/work-page.ts -model/work-sustainable-development-goals-inner.ts -model/work-topic-domain.ts -model/work-topic-field.ts -model/work-topic-information.ts -model/work-topic-subfield.ts -model/work-topic.ts model/work.ts -model/works-list-response.ts +model/workBiblio.ts +model/workCitationNormalizedPercentile.ts +model/workCitedByPercentileYear.ts +model/workCountsByYearInner.ts +model/workHasContent.ts +model/workIds.ts +model/workKeyword.ts +model/workMeshInner.ts +model/workNetworkNode.ts +model/workPage.ts +model/workSustainableDevelopmentGoalsInner.ts +model/workTopic.ts +model/workTopicDomain.ts +model/workTopicField.ts +model/workTopicInformation.ts +model/workTopicSubfield.ts +model/worksFilterProperties.ts +model/worksListResponse.ts param.ts provide-api.ts variables.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index 27d4e254..ea1f3603 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -1,25 +1,19 @@ export * from './funding.service'; import { FundingService } from './funding.service'; -export * from './funding.serviceInterface'; -export * from './inse-account-service.service'; -import { INSEAccountServiceService } from './inse-account-service.service'; -export * from './inse-account-service.serviceInterface'; -export * from './inse-service.service'; -import { INSEServiceService } from './inse-service.service'; -export * from './inse-service.serviceInterface'; +export * from './iNSEAccountService.service'; +import { INSEAccountServiceService } from './iNSEAccountService.service'; +export * from './iNSEService.service'; +import { INSEServiceService } from './iNSEService.service'; +export * from './institutions.service'; +import { InstitutionsService } from './institutions.service'; export * from './items.service'; import { ItemsService } from './items.service'; -export * from './items.serviceInterface'; -export * from './person-network.service'; -import { PersonNetworkService } from './person-network.service'; -export * from './person-network.serviceInterface'; +export * from './personNetwork.service'; +import { PersonNetworkService } from './personNetwork.service'; export * from './persons.service'; import { PersonsService } from './persons.service'; -export * from './persons.serviceInterface'; export * from './topics.service'; import { TopicsService } from './topics.service'; -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/funding.service.ts b/webapp/src/app/api/api/funding.service.ts index 17619786..46772768 100644 --- a/webapp/src/app/api/api/funding.service.ts +++ b/webapp/src/app/api/api/funding.service.ts @@ -17,26 +17,23 @@ import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; // @ts-ignore -import { FundersByAuthorResponse } from '../model/funders-by-author-response'; +import { FundersByAuthorResponse } from '../model/fundersByAuthorResponse'; // @ts-ignore -import { HTTPValidationError } from '../model/http-validation-error'; +import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore -import { PublicationsByAuthorResponse } from '../model/publications-by-author-response'; +import { PublicationsByAuthorResponse } from '../model/publicationsByAuthorResponse'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; -import { - FundingServiceInterface -} from './funding.serviceInterface'; @Injectable({ providedIn: 'root' }) -export class FundingService extends BaseService implements FundingServiceInterface { +export class FundingService extends BaseService { constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { super(basePath, configuration); diff --git a/webapp/src/app/api/api/funding.serviceInterface.ts b/webapp/src/app/api/api/funding.serviceInterface.ts deleted file mode 100644 index 86b8b171..00000000 --- a/webapp/src/app/api/api/funding.serviceInterface.ts +++ /dev/null @@ -1,45 +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 { FundersByAuthorResponse } from '../model/models'; -import { HTTPValidationError } from '../model/models'; -import { PublicationsByAuthorResponse } from '../model/models'; - - -import { Configuration } from '../configuration'; - - - -export interface FundingServiceInterface { - defaultHeaders: HttpHeaders; - configuration: Configuration; - - /** - * Get funding organizations by author. - * - * @endpoint get /api/inse-service/authors/{author_id}/funders - * @param authorId - */ - getFundersByAuthor(authorId: string, extraHttpRequestParams?: any): Observable; - - /** - * Get funded publications by author. - * - * @endpoint get /api/inse-service/authors/{author_id}/publications - * @param authorId - * @param page - * @param pageSize - */ - getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, extraHttpRequestParams?: any): Observable; - -} diff --git a/webapp/src/app/api/api/inse-account-service.service.ts b/webapp/src/app/api/api/iNSEAccountService.service.ts similarity index 96% rename from webapp/src/app/api/api/inse-account-service.service.ts rename to webapp/src/app/api/api/iNSEAccountService.service.ts index ef79eace..7b43eaa5 100644 --- a/webapp/src/app/api/api/inse-account-service.service.ts +++ b/webapp/src/app/api/api/iNSEAccountService.service.ts @@ -17,26 +17,23 @@ import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; // @ts-ignore -import { AccessGrant } from '../model/access-grant'; +import { AccessGrant } from '../model/accessGrant'; // @ts-ignore -import { HTTPValidationError } from '../model/http-validation-error'; +import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore -import { IdentityGrant } from '../model/identity-grant'; +import { IdentityGrant } from '../model/identityGrant'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; -import { - INSEAccountServiceServiceInterface -} from './inse-account-service.serviceInterface'; @Injectable({ providedIn: 'root' }) -export class INSEAccountServiceService extends BaseService implements INSEAccountServiceServiceInterface { +export class INSEAccountServiceService extends BaseService { constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { super(basePath, configuration); diff --git a/webapp/src/app/api/api/inse-service.service.ts b/webapp/src/app/api/api/iNSEService.service.ts similarity index 51% rename from webapp/src/app/api/api/inse-service.service.ts rename to webapp/src/app/api/api/iNSEService.service.ts index dbca3805..cf95d68e 100644 --- a/webapp/src/app/api/api/inse-service.service.ts +++ b/webapp/src/app/api/api/iNSEService.service.ts @@ -17,36 +17,25 @@ import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; // @ts-ignore -import { AuthorsListResponse } from '../model/authors-list-response'; -// @ts-ignore -import { FundersByAuthorResponse } from '../model/funders-by-author-response'; -// @ts-ignore -import { HTTPValidationError } from '../model/http-validation-error'; +import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore import { Item } from '../model/item'; // @ts-ignore -import { ItemCreate } from '../model/item-create'; +import { ItemCreate } from '../model/itemCreate'; // @ts-ignore -import { ItemPage } from '../model/item-page'; -// @ts-ignore -import { PersonBio } from '../model/person-bio'; -// @ts-ignore -import { PublicationsByAuthorResponse } from '../model/publications-by-author-response'; +import { ItemPage } from '../model/itemPage'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; -import { - INSEServiceServiceInterface -} from './inse-service.serviceInterface'; @Injectable({ providedIn: 'root' }) -export class INSEServiceService extends BaseService implements INSEServiceServiceInterface { +export class INSEServiceService extends BaseService { constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { super(basePath, configuration); @@ -303,127 +292,6 @@ export class INSEServiceService extends BaseService implements INSEServiceServic } /** -<<<<<<< HEAD -======= - * Generates a bio for a person by author ID. - * @endpoint get /api/inse-service/persons/bio - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param include Comma-separated list to include tags - * @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 generatePersonBio(authorId: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public generatePersonBio(authorId: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public generatePersonBio(authorId: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public generatePersonBio(authorId: string, include?: string, 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 generatePersonBio.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorId, 'author_id'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - 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/bio`; - 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 - } - ); - } - - /** - * Get funding organizations by author. - * @endpoint get /api/inse-service/authors/{author_id}/funders - * @param authorId - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getFundersByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getFundersByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getFundersByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getFundersByAuthor(authorId: string, 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 getFundersByAuthor.'); - } - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/funders`; - 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 - } - ); - } - - /** ->>>>>>> 33f767dea36fe8a44c8249dbb74537d47c186c5d * Returns the item with the id. * @endpoint get /api/inse-service/items/{id} * @param id The item id. @@ -545,29 +413,15 @@ export class INSEServiceService extends BaseService implements INSEServiceServic } /** -<<<<<<< HEAD -======= - * Searches for person by ID. - * @endpoint get /api/inse-service/person/{id} - * @param id OpenAlex author ID - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * 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 getPersonByID(id: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getPersonByID(id: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID(id: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID(id: string, include: string, 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 getPersonByID.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling getPersonByID.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); + 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; @@ -594,12 +448,11 @@ export class INSEServiceService extends BaseService implements INSEServiceServic } } - let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + let localVarPath = `/api/inse-service/topics/hierarchy`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, + return this.httpClient.request('get', `${basePath}${localVarPath}`, { context: localVarHttpContext, - params: localVarQueryParameters, responseType: responseType_, ...(withCredentials ? { withCredentials } : {}), headers: localVarHeaders, @@ -611,266 +464,6 @@ export class INSEServiceService extends BaseService implements INSEServiceServic } /** - * Get funded publications by author. - * @endpoint get /api/inse-service/authors/{author_id}/publications - * @param authorId - * @param page - * @param pageSize - * @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 getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, 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 getPublicationsByAuthor.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'page_size'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/publications`; - 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 - } - ); - } - - /** - * Searches for persons by ID or name. - * @endpoint get /api/inse-service/persons/search - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param query Search query (e.g., Arman AND Arzani) - * @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost - * @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 searchPersons(authorId?: string, query?: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersons(authorId?: string, query?: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersons(authorId?: string, query?: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersons(authorId?: string, query?: string, include?: 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, - authorId, 'author_id'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - 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`; - 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 - } - ); - } - - /** - * Searches for persons by institution name. - * @endpoint get /api/inse-service/persons/searchByInstitution - * @param institutionName Institution name (e.g., MIT, Oxford University) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 searchPersonsByInstitution(institutionName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (institutionName === null || institutionName === undefined) { - throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsByInstitution.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - institutionName, 'institution_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - 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/searchByInstitution`; - 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 - } - ); - } - - /** - * Searches for person by name. - * @endpoint get /api/inse-service/persons/searchByName - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 searchPersonsByName(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByName(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorName === null || authorName === undefined) { - throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsByName.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorName, 'author_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - 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/searchByName`; - 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 - } - ); - } - - /** ->>>>>>> 33f767dea36fe8a44c8249dbb74537d47c186c5d * Updates the item with the id. * @endpoint put /api/inse-service/items/{id} * @param id The item id. diff --git a/webapp/src/app/api/api/inse-account-service.serviceInterface.ts b/webapp/src/app/api/api/inse-account-service.serviceInterface.ts deleted file mode 100644 index 2cb6b360..00000000 --- a/webapp/src/app/api/api/inse-account-service.serviceInterface.ts +++ /dev/null @@ -1,46 +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 { AccessGrant } from '../model/models'; -import { HTTPValidationError } from '../model/models'; -import { IdentityGrant } from '../model/models'; - - -import { Configuration } from '../configuration'; - - - -export interface INSEAccountServiceServiceInterface { - defaultHeaders: HttpHeaders; - configuration: Configuration; - - /** - * Get Access Grant - * - * @endpoint post /inse-account/auth/access - * @param secret - * @param account - * @param organization - */ - getAccessGrantInseAccountAuthAccessPost(secret: string, account: number, organization: number, extraHttpRequestParams?: any): Observable; - - /** - * Get Identity Grant - * - * @endpoint post /inse-account/auth/id - * @param username - * @param password - */ - getIdentityGrantInseAccountAuthIdPost(username: string, password: string, extraHttpRequestParams?: any): Observable; - -} diff --git a/webapp/src/app/api/api/inse-service.serviceInterface.ts b/webapp/src/app/api/api/inse-service.serviceInterface.ts deleted file mode 100644 index 979f6465..00000000 --- a/webapp/src/app/api/api/inse-service.serviceInterface.ts +++ /dev/null @@ -1,161 +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 { AuthorsListResponse } from '../model/models'; // -import { FundersByAuthorResponse } from '../model/models'; // -import { HTTPValidationError } from '../model/models'; -import { Item } from '../model/models'; -import { ItemCreate } from '../model/models'; -import { ItemPage } from '../model/models'; -import { PersonBio } from '../model/models'; // -import { PublicationsByAuthorResponse } from '../model/models'; // - - -import { Configuration } from '../configuration'; - - - -export interface INSEServiceServiceInterface { - defaultHeaders: HttpHeaders; - configuration: Configuration; - - /** - * Adds a new item. - * - * @endpoint post /api/inse-service/items - * @param itemCreate - */ - addItem(itemCreate: ItemCreate, extraHttpRequestParams?: any): Observable; - - /** - * 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. - */ - buildTopicCache(pageSize?: number, saveJson?: boolean, extraHttpRequestParams?: any): Observable; - - /** - * Counts topic hierarchy occurrences from cache. - * - * @endpoint get /api/inse-service/topics/count - * @param topic Topic names (repeat parameter). - */ - countTopicHierarchy(topic: Array, extraHttpRequestParams?: any): Observable; - - /** - * Deletes the item with the id. - * - * @endpoint delete /api/inse-service/items/{id} - * @param id The item id. - */ - deleteItem(id: number, extraHttpRequestParams?: any): Observable; - - /** -<<<<<<< HEAD -======= - * Generates a bio for a person by author ID. - * - * @endpoint get /api/inse-service/persons/bio - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param include Comma-separated list to include tags - */ - generatePersonBio(authorId: string, include?: string, extraHttpRequestParams?: any): Observable; - - /** - * Get funding organizations by author. - * - * @endpoint get /api/inse-service/authors/{author_id}/funders - * @param authorId - */ - getFundersByAuthor(authorId: string, extraHttpRequestParams?: any): Observable; - - /** ->>>>>>> 33f767dea36fe8a44c8249dbb74537d47c186c5d - * Returns the item with the id. - * - * @endpoint get /api/inse-service/items/{id} - * @param id The item id. - */ - getItem(id: number, extraHttpRequestParams?: any): Observable; - - /** - * Returns a page of items. - * - * @endpoint get /api/inse-service/items - * @param pageOffset The page offset. - * @param pageSize The page size. - */ - getItems(pageOffset?: number, pageSize?: number, extraHttpRequestParams?: any): Observable; - - /** -<<<<<<< HEAD -======= - * Searches for person by ID. - * - * @endpoint get /api/inse-service/person/{id} - * @param id OpenAlex author ID - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - */ - getPersonByID(id: string, include: string, extraHttpRequestParams?: any): Observable; - - /** - * Get funded publications by author. - * - * @endpoint get /api/inse-service/authors/{author_id}/publications - * @param authorId - * @param page - * @param pageSize - */ - getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, extraHttpRequestParams?: any): Observable; - - /** - * Searches for persons by ID or name. - * - * @endpoint get /api/inse-service/persons/search - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param query Search query (e.g., Arman AND Arzani) - * @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost - */ - searchPersons(authorId?: string, query?: string, include?: string, extraHttpRequestParams?: any): Observable; - - /** - * Searches for persons by institution name. - * - * @endpoint get /api/inse-service/persons/searchByInstitution - * @param institutionName Institution name (e.g., MIT, Oxford University) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - */ - searchPersonsByInstitution(institutionName: string, include: string, extraHttpRequestParams?: any): Observable; - - /** - * Searches for person by name. - * - * @endpoint get /api/inse-service/persons/searchByName - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - */ - searchPersonsByName(authorName: string, include: string, extraHttpRequestParams?: any): Observable; - - /** ->>>>>>> 33f767dea36fe8a44c8249dbb74537d47c186c5d - * Updates the item with the id. - * - * @endpoint put /api/inse-service/items/{id} - * @param id The item id. - * @param itemCreate - */ - updateItem(id: number, itemCreate: ItemCreate, extraHttpRequestParams?: any): Observable; - -} diff --git a/webapp/src/app/api/api/institutions.service.ts b/webapp/src/app/api/api/institutions.service.ts new file mode 100644 index 00000000..ff8895a9 --- /dev/null +++ b/webapp/src/app/api/api/institutions.service.ts @@ -0,0 +1,192 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { AutocompleteResponse } from '../model/autocompleteResponse'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { InstitutionsListResponse } from '../model/institutionsListResponse'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + + + +@Injectable({ + providedIn: 'root' +}) +export class InstitutionsService extends BaseService { + + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); + } + + /** + * Returns institution options for autocomplete inputs. + * @endpoint get /api/institutions/autocomplete + * @param query Institution search text, for example \'Duisburg Essen\'. + * @param countryCode Optional ISO country code filter. + * @param type Optional institution type filter. + * @param limit Maximum number of autocomplete options. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling autocompleteInstitutions.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + countryCode, 'countryCode'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + type, 'type'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/institutions/autocomplete`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Returns a list of OpenAlex institutions. + * @endpoint get /api/institutions + * @param search Full-text search, for example \'Duisburg Essen\'. + * @param filter OpenAlex filter, for example \'country_code:DE,type:education\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'country_code\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + search, 'search'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filter, 'filter'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sort, 'sort'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + groupBy, 'group_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + perPage, 'per_page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + cursor, 'cursor'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sample, 'sample'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + select, 'select'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/institutions`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + +} diff --git a/webapp/src/app/api/api/items.service.ts b/webapp/src/app/api/api/items.service.ts index 1d00c8c8..69cd8e54 100644 --- a/webapp/src/app/api/api/items.service.ts +++ b/webapp/src/app/api/api/items.service.ts @@ -17,28 +17,25 @@ import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; // @ts-ignore -import { HTTPValidationError } from '../model/http-validation-error'; +import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore import { Item } from '../model/item'; // @ts-ignore -import { ItemCreate } from '../model/item-create'; +import { ItemCreate } from '../model/itemCreate'; // @ts-ignore -import { ItemPage } from '../model/item-page'; +import { ItemPage } from '../model/itemPage'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; -import { - ItemsServiceInterface -} from './items.serviceInterface'; @Injectable({ providedIn: 'root' }) -export class ItemsService extends BaseService implements ItemsServiceInterface { +export class ItemsService extends BaseService { constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { super(basePath, configuration); diff --git a/webapp/src/app/api/api/items.serviceInterface.ts b/webapp/src/app/api/api/items.serviceInterface.ts deleted file mode 100644 index 140cbec0..00000000 --- a/webapp/src/app/api/api/items.serviceInterface.ts +++ /dev/null @@ -1,70 +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 { HTTPValidationError } from '../model/models'; -import { Item } from '../model/models'; -import { ItemCreate } from '../model/models'; -import { ItemPage } from '../model/models'; - - -import { Configuration } from '../configuration'; - - - -export interface ItemsServiceInterface { - defaultHeaders: HttpHeaders; - configuration: Configuration; - - /** - * Adds a new item. - * - * @endpoint post /api/inse-service/items - * @param itemCreate - */ - addItem(itemCreate: ItemCreate, extraHttpRequestParams?: any): Observable; - - /** - * Deletes the item with the id. - * - * @endpoint delete /api/inse-service/items/{id} - * @param id The item id. - */ - deleteItem(id: number, extraHttpRequestParams?: any): Observable; - - /** - * Returns the item with the id. - * - * @endpoint get /api/inse-service/items/{id} - * @param id The item id. - */ - getItem(id: number, extraHttpRequestParams?: any): Observable; - - /** - * Returns a page of items. - * - * @endpoint get /api/inse-service/items - * @param pageOffset The page offset. - * @param pageSize The page size. - */ - getItems(pageOffset?: number, pageSize?: number, extraHttpRequestParams?: any): Observable; - - /** - * Updates the item with the id. - * - * @endpoint put /api/inse-service/items/{id} - * @param id The item id. - * @param itemCreate - */ - updateItem(id: number, itemCreate: ItemCreate, extraHttpRequestParams?: any): Observable; - -} diff --git a/webapp/src/app/api/api/person-network.serviceInterface.ts b/webapp/src/app/api/api/person-network.serviceInterface.ts deleted file mode 100644 index 58e7a1fb..00000000 --- a/webapp/src/app/api/api/person-network.serviceInterface.ts +++ /dev/null @@ -1,36 +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 { CollaborationNetwork } from '../model/models'; -import { FilterProperties } from '../model/models'; -import { HTTPValidationError } from '../model/models'; - - -import { Configuration } from '../configuration'; - - - -export interface PersonNetworkServiceInterface { - defaultHeaders: HttpHeaders; - configuration: 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 - */ - getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, extraHttpRequestParams?: any): Observable; - -} diff --git a/webapp/src/app/api/api/person-network.service.ts b/webapp/src/app/api/api/personNetwork.service.ts similarity index 93% rename from webapp/src/app/api/api/person-network.service.ts rename to webapp/src/app/api/api/personNetwork.service.ts index 135a20d8..b1183ff6 100644 --- a/webapp/src/app/api/api/person-network.service.ts +++ b/webapp/src/app/api/api/personNetwork.service.ts @@ -17,26 +17,23 @@ import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; // @ts-ignore -import { CollaborationNetwork } from '../model/collaboration-network'; +import { CollaborationNetwork } from '../model/collaborationNetwork'; // @ts-ignore -import { FilterProperties } from '../model/filter-properties'; +import { FilterProperties } from '../model/filterProperties'; // @ts-ignore -import { HTTPValidationError } from '../model/http-validation-error'; +import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; -import { - PersonNetworkServiceInterface -} from './person-network.serviceInterface'; @Injectable({ providedIn: 'root' }) -export class PersonNetworkService extends BaseService implements PersonNetworkServiceInterface { +export class PersonNetworkService extends BaseService { constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { super(basePath, configuration); 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/persons.service.ts b/webapp/src/app/api/api/persons.service.ts index c80c7c64..a45848ef 100644 --- a/webapp/src/app/api/api/persons.service.ts +++ b/webapp/src/app/api/api/persons.service.ts @@ -17,28 +17,25 @@ import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; // @ts-ignore -import { AuthorsListResponse } from '../model/authors-list-response'; +import { AuthorsListResponse } from '../model/authorsListResponse'; // @ts-ignore -import { CustomAuthorsListResponse } from '../model/custom-authors-list-response'; +import { CustomAuthorsListResponse } from '../model/customAuthorsListResponse'; // @ts-ignore -import { HTTPValidationError } from '../model/http-validation-error'; +import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore -import { PersonBio } from '../model/person-bio'; +import { PersonBio } from '../model/personBio'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; -import { - PersonsServiceInterface -} from './persons.serviceInterface'; @Injectable({ providedIn: 'root' }) -export class PersonsService extends BaseService implements PersonsServiceInterface { +export class PersonsService extends BaseService { constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { super(basePath, configuration); @@ -728,6 +725,8 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa * @param pageSize Results per page * @param include Comma-separated include tags * @param strict Strict institution search by target year + * @param filterMode Filter mode: \'in\' or \'from\' + * @param filterYear Filter 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. */ @@ -811,6 +810,8 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa * @param pageSize Results per page * @param include Comma-separated include tags * @param strict Strict institution search by target year + * @param filterMode Filter mode: \'in\' or \'from\' + * @param filterYear Filter 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. */ diff --git a/webapp/src/app/api/api/persons.serviceInterface.ts b/webapp/src/app/api/api/persons.serviceInterface.ts deleted file mode 100644 index 22232b9b..00000000 --- a/webapp/src/app/api/api/persons.serviceInterface.ts +++ /dev/null @@ -1,143 +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 { AuthorsListResponse } from '../model/models'; -import { CustomAuthorsListResponse } from '../model/models'; -import { HTTPValidationError } from '../model/models'; -import { PersonBio } from '../model/models'; - - -import { Configuration } from '../configuration'; - - - -export interface PersonsServiceInterface { - defaultHeaders: HttpHeaders; - configuration: Configuration; - - /** - * Generates a bio for a person by author ID. - * - * @endpoint get /api/inse-service/persons/bio - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param include Comma-separated list to include tags - */ - generatePersonBio(authorId: string, include?: string, extraHttpRequestParams?: any): Observable; - - /** - * Searches for person by ID. - * - * @endpoint get /api/inse-service/person/{id} - * @param id OpenAlex author ID - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - */ - getPersonByID(id: string, include: string, extraHttpRequestParams?: any): Observable; - - /** - * Searches for person by ID. - * - * @endpoint get /api/inse-service/person/{id} - * @param id OpenAlex author ID - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - */ - getPersonByID_1(id: string, include: string, extraHttpRequestParams?: any): Observable; - - /** - * Searches for persons by ID or name. - * - * @endpoint get /api/inse-service/persons/search - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param query Search query (e.g., Arman AND Arzani) - * @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost - */ - searchPersons(authorId?: string, query?: string, include?: string, extraHttpRequestParams?: any): Observable; - - /** - * Searches for person by name. - * - * @endpoint get /api/inse-service/persons/autocomplete - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - */ - searchPersonsAutocomplete(authorName: string, include: string, extraHttpRequestParams?: any): Observable; - - /** - * Searches for person by name. - * - * @endpoint get /api/inse-service/persons/autocomplete - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - */ - searchPersonsAutocomplete_2(authorName: string, include: string, extraHttpRequestParams?: any): Observable; - - /** - * Searches for persons by institution name. - * - * @endpoint get /api/inse-service/persons/searchByInstitution - * @param institutionName Institution name (e.g., MIT, Oxford University) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - */ - searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, extraHttpRequestParams?: any): Observable; - - /** - * Searches for persons by institution name. - * - * @endpoint get /api/inse-service/persons/searchByInstitution - * @param institutionName Institution name (e.g., MIT, Oxford University) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - */ - searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, extraHttpRequestParams?: any): Observable; - - /** - * Searches for person by name. - * - * @endpoint get /api/inse-service/persons/searchByName - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - */ - searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, extraHttpRequestParams?: any): Observable; - - /** - * Searches for person by name. - * - * @endpoint get /api/inse-service/persons/searchByName - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - */ - searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, extraHttpRequestParams?: any): Observable; - - searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, extraHttpRequestParams?: any): Observable; - - /** - * 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_5(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, extraHttpRequestParams?: any): Observable; - -} diff --git a/webapp/src/app/api/api/topics.service.ts b/webapp/src/app/api/api/topics.service.ts index 8635bf04..2667546d 100644 --- a/webapp/src/app/api/api/topics.service.ts +++ b/webapp/src/app/api/api/topics.service.ts @@ -17,27 +17,100 @@ import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; // @ts-ignore -import { HTTPValidationError } from '../model/http-validation-error'; +import { AutocompleteResponse } from '../model/autocompleteResponse'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { TopicsListResponse } from '../model/topicsListResponse'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; -import { - TopicsServiceInterface -} from './topics.serviceInterface'; @Injectable({ providedIn: 'root' }) -export class TopicsService extends BaseService implements TopicsServiceInterface { +export class TopicsService extends BaseService { constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { 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 @@ -163,7 +236,7 @@ export class TopicsService extends BaseService implements TopicsServiceInterface } /** - * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). + * 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. @@ -173,7 +246,6 @@ export class TopicsService extends BaseService implements TopicsServiceInterface 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 localVarQueryParameters = new HttpParams({encoder: this.encoder}); let localVarHeaders = this.defaultHeaders; const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ @@ -184,8 +256,10 @@ export class TopicsService extends BaseService implements TopicsServiceInterface } 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')) { @@ -200,6 +274,86 @@ export class TopicsService extends BaseService implements TopicsServiceInterface 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 + } + ); + } + + /** + * 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, diff --git a/webapp/src/app/api/api/topics.serviceInterface.ts b/webapp/src/app/api/api/topics.serviceInterface.ts deleted file mode 100644 index baebd5f6..00000000 --- a/webapp/src/app/api/api/topics.serviceInterface.ts +++ /dev/null @@ -1,49 +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 { HTTPValidationError } from '../model/models'; - - -import { Configuration } from '../configuration'; - - - -export interface TopicsServiceInterface { - defaultHeaders: HttpHeaders; - configuration: Configuration; - - /** - * 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. - */ - buildTopicCache(pageSize?: number, saveJson?: boolean, extraHttpRequestParams?: any): Observable; - - /** - * Counts topic hierarchy occurrences from cache. - * - * @endpoint get /api/inse-service/topics/count - * @param topic Topic names (repeat parameter). - */ - countTopicHierarchy(topic: Array, extraHttpRequestParams?: any): Observable; - - /** - * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). - * - * @endpoint get /api/inse-service/topics/hierarchy - */ - getTopicHierarchy(extraHttpRequestParams?: any): Observable; - -} diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts index cd80c9ac..63355411 100644 --- a/webapp/src/app/api/api/works.service.ts +++ b/webapp/src/app/api/api/works.service.ts @@ -17,30 +17,29 @@ import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; // @ts-ignore -import { HTTPValidationError } from '../model/http-validation-error'; +import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore -import { TopicCount } from '../model/topic-count'; // +import { TopicCount } from '../model/topicCount'; // @ts-ignore -import { TopicsByTime } from '../model/topics-by-time'; +import { TopicsByTime } from '../model/topicsByTime'; // @ts-ignore -import { WorkPage } from '../model/work-page'; +import { Work } from '../model/work'; // @ts-ignore -import { WorksListResponse } from '../model/works-list-response'; +import { WorkPage } from '../model/workPage'; +// @ts-ignore +import { WorksListResponse } from '../model/worksListResponse'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; -import { - WorksServiceInterface -} from './works.serviceInterface'; @Injectable({ providedIn: 'root' }) -export class WorksService extends BaseService implements WorksServiceInterface { +export class WorksService extends BaseService { constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { super(basePath, configuration); @@ -113,13 +112,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 +148,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; @@ -314,4 +327,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 deleted file mode 100644 index 792f42f7..00000000 --- a/webapp/src/app/api/api/works.serviceInterface.ts +++ /dev/null @@ -1,59 +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 { HTTPValidationError } from '../model/models'; -import { TopicCount } from '../model/models'; // -import { TopicsByTime } from '../model/models'; -import { WorkPage } from '../model/models'; -import { WorksListResponse } from '../model/models'; - - -import { Configuration } from '../configuration'; - - - -export interface WorksServiceInterface { - defaultHeaders: HttpHeaders; - configuration: Configuration; - - /** - * Returns all works for an author. - * - * @endpoint get /api/works/{author_id}/all - * @param authorId The author id, for example A5023888391. - */ - getAllAuthorWorks(authorId: string, extraHttpRequestParams?: any): Observable; - - /** - * Returns a page of works for an author. - * - * @endpoint get /api/works/{author_id} - * @param authorId The author id, for example A5023888391. - * @param page The page number. - * @param size The page size. - * @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. - */ - getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, extraHttpRequestParams?: any): Observable; - - /** - * Returns topics grouped by publication year for an author. - * - * @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. - */ - getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, extraHttpRequestParams?: any): Observable; - -} diff --git a/webapp/src/app/api/model/access-grant.ts b/webapp/src/app/api/model/accessGrant.ts similarity index 89% rename from webapp/src/app/api/model/access-grant.ts rename to webapp/src/app/api/model/accessGrant.ts index 9de129ac..ad1f537a 100644 --- a/webapp/src/app/api/model/access-grant.ts +++ b/webapp/src/app/api/model/accessGrant.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { AuthScope } from './auth-scope'; +import { AuthScope } from './authScope'; export interface AccessGrant { diff --git a/webapp/src/app/api/model/auth-account.ts b/webapp/src/app/api/model/authAccount.ts similarity index 100% rename from webapp/src/app/api/model/auth-account.ts rename to webapp/src/app/api/model/authAccount.ts diff --git a/webapp/src/app/api/model/auth-scope.ts b/webapp/src/app/api/model/authScope.ts similarity index 87% rename from webapp/src/app/api/model/auth-scope.ts rename to webapp/src/app/api/model/authScope.ts index 0d9d325d..65ffa9b5 100644 --- a/webapp/src/app/api/model/auth-scope.ts +++ b/webapp/src/app/api/model/authScope.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { AuthAccount } from './auth-account'; +import { AuthAccount } from './authAccount'; export interface AuthScope { diff --git a/webapp/src/app/api/model/author.ts b/webapp/src/app/api/model/author.ts index 8d91fe5d..9ba12273 100644 --- a/webapp/src/app/api/model/author.ts +++ b/webapp/src/app/api/model/author.ts @@ -7,13 +7,13 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { AuthorAffiliationsInner } from './author-affiliations-inner'; -import { AuthorParsedLongestName } from './author-parsed-longest-name'; -import { DehydratedInstitution } from './dehydrated-institution'; -import { AuthorCountsByYearInner } from './author-counts-by-year-inner'; -import { AuthorIds } from './author-ids'; -import { AuthorSummaryStats } from './author-summary-stats'; -import { WorkTopic } from './work-topic'; +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'; /** diff --git a/webapp/src/app/api/model/author-affiliations-inner.ts b/webapp/src/app/api/model/authorAffiliationsInner.ts similarity index 85% rename from webapp/src/app/api/model/author-affiliations-inner.ts rename to webapp/src/app/api/model/authorAffiliationsInner.ts index 7d3ee92b..270443ff 100644 --- a/webapp/src/app/api/model/author-affiliations-inner.ts +++ b/webapp/src/app/api/model/authorAffiliationsInner.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { DehydratedInstitution } from './dehydrated-institution'; +import { DehydratedInstitution } from './dehydratedInstitution'; /** diff --git a/webapp/src/app/api/model/author-counts-by-year-inner.ts b/webapp/src/app/api/model/authorCountsByYearInner.ts similarity index 100% rename from webapp/src/app/api/model/author-counts-by-year-inner.ts rename to webapp/src/app/api/model/authorCountsByYearInner.ts diff --git a/webapp/src/app/api/model/author-ids.ts b/webapp/src/app/api/model/authorIds.ts similarity index 100% rename from webapp/src/app/api/model/author-ids.ts rename to webapp/src/app/api/model/authorIds.ts diff --git a/webapp/src/app/api/model/collaboration-network-node.ts b/webapp/src/app/api/model/authorNetworkNode.ts similarity index 79% rename from webapp/src/app/api/model/collaboration-network-node.ts rename to webapp/src/app/api/model/authorNetworkNode.ts index 3a4542d3..aee98d47 100644 --- a/webapp/src/app/api/model/collaboration-network-node.ts +++ b/webapp/src/app/api/model/authorNetworkNode.ts @@ -7,10 +7,10 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { CollaborationNetworkNodeType } from './collaboration-network-node-type'; +import { CollaborationNetworkNodeType } from './collaborationNetworkNodeType'; -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/author-parsed-longest-name.ts b/webapp/src/app/api/model/authorParsedLongestName.ts similarity index 100% rename from webapp/src/app/api/model/author-parsed-longest-name.ts rename to webapp/src/app/api/model/authorParsedLongestName.ts diff --git a/webapp/src/app/api/model/author-position-count.ts b/webapp/src/app/api/model/authorPositionCount.ts similarity index 100% rename from webapp/src/app/api/model/author-position-count.ts rename to webapp/src/app/api/model/authorPositionCount.ts diff --git a/webapp/src/app/api/model/author-summary-stats.ts b/webapp/src/app/api/model/authorSummaryStats.ts similarity index 85% rename from webapp/src/app/api/model/author-summary-stats.ts rename to webapp/src/app/api/model/authorSummaryStats.ts index 9bdb23e8..1cfc0bdb 100644 --- a/webapp/src/app/api/model/author-summary-stats.ts +++ b/webapp/src/app/api/model/authorSummaryStats.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { Model2YrMeanCitedness } from './model2-yr-mean-citedness'; +import { Model2YrMeanCitedness } from './model2YrMeanCitedness'; /** 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/authors-list-response.ts b/webapp/src/app/api/model/authorsListResponse.ts similarity index 89% rename from webapp/src/app/api/model/authors-list-response.ts rename to webapp/src/app/api/model/authorsListResponse.ts index 37a9fc2c..d309ae43 100644 --- a/webapp/src/app/api/model/authors-list-response.ts +++ b/webapp/src/app/api/model/authorsListResponse.ts @@ -9,7 +9,7 @@ */ import { Meta } from './meta'; import { Author } from './author'; -import { GroupByResult } from './group-by-result'; +import { GroupByResult } from './groupByResult'; /** diff --git a/webapp/src/app/api/model/authorship.ts b/webapp/src/app/api/model/authorship.ts index cd95a07b..db3a0bf0 100644 --- a/webapp/src/app/api/model/authorship.ts +++ b/webapp/src/app/api/model/authorship.ts @@ -7,8 +7,8 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { DehydratedInstitution } from './dehydrated-institution'; -import { DehydratedAuthor } from './dehydrated-author'; +import { DehydratedInstitution } from './dehydratedInstitution'; +import { DehydratedAuthor } from './dehydratedAuthor'; /** 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 deleted file mode 100644 index 9956ae19..00000000 --- a/webapp/src/app/api/model/collaboration-network.ts +++ /dev/null @@ -1,33 +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 { FilterInformation } from './filter-information'; -import { CollaborationNetworkEdge } from './collaboration-network-edge'; -import { CollaborationNetworkNode } from './collaboration-network-node'; - - -export interface CollaborationNetwork { - /** - * The raw person ID of the person whose collaboration network this is. - */ - raw_person_id: string; - /** - * The nodes in the collaboration network. - */ - nodes: Array; - /** - * The edges in the collaboration network. - */ - 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/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/collaboration-network-edge.ts b/webapp/src/app/api/model/collaborationNetworkEdge.ts similarity index 100% rename from webapp/src/app/api/model/collaboration-network-edge.ts rename to webapp/src/app/api/model/collaborationNetworkEdge.ts diff --git a/webapp/src/app/api/model/collaboration-network-node-type.ts b/webapp/src/app/api/model/collaborationNetworkNodeType.ts similarity index 84% rename from webapp/src/app/api/model/collaboration-network-node-type.ts rename to webapp/src/app/api/model/collaborationNetworkNodeType.ts index 1b3c0d84..752e35b0 100644 --- a/webapp/src/app/api/model/collaboration-network-node-type.ts +++ b/webapp/src/app/api/model/collaborationNetworkNodeType.ts @@ -10,9 +10,9 @@ export const CollaborationNetworkNodeType = { - author: 'author', - institution: 'institution', - work: 'work' + Author: 'author', + Institution: 'institution', + Work: 'work' } as const; export type CollaborationNetworkNodeType = typeof CollaborationNetworkNodeType[keyof typeof CollaborationNetworkNodeType]; diff --git a/webapp/src/app/api/model/cost-usd.ts b/webapp/src/app/api/model/costUsd.ts similarity index 100% rename from webapp/src/app/api/model/cost-usd.ts rename to webapp/src/app/api/model/costUsd.ts diff --git a/webapp/src/app/api/model/custom-author.ts b/webapp/src/app/api/model/customAuthor.ts similarity index 69% rename from webapp/src/app/api/model/custom-author.ts rename to webapp/src/app/api/model/customAuthor.ts index 07000ade..1117cd53 100644 --- a/webapp/src/app/api/model/custom-author.ts +++ b/webapp/src/app/api/model/customAuthor.ts @@ -7,13 +7,13 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { AuthorAffiliationsInner } from './author-affiliations-inner'; -import { AuthorParsedLongestName } from './author-parsed-longest-name'; -import { DehydratedInstitution } from './dehydrated-institution'; -import { AuthorCountsByYearInner } from './author-counts-by-year-inner'; -import { AuthorIds } from './author-ids'; -import { AuthorSummaryStats } from './author-summary-stats'; -import { WorkTopic } from './work-topic'; +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 { diff --git a/webapp/src/app/api/model/custom-authors-list-response.ts b/webapp/src/app/api/model/customAuthorsListResponse.ts similarity index 63% rename from webapp/src/app/api/model/custom-authors-list-response.ts rename to webapp/src/app/api/model/customAuthorsListResponse.ts index 45aeae54..f6eac14b 100644 --- a/webapp/src/app/api/model/custom-authors-list-response.ts +++ b/webapp/src/app/api/model/customAuthorsListResponse.ts @@ -8,13 +8,15 @@ * Do not edit the class manually. */ import { Meta } from './meta'; -import { CustomAuthor } from './custom-author'; -import { GroupByResult } from './group-by-result'; +import { CustomAuthor } from './customAuthor'; +import { Author } from './author'; +import { GroupByResult } from './groupByResult'; export interface CustomAuthorsListResponse { meta?: Meta | null; - results?: Array | null; + results?: Array | null; group_by?: Array | null; + placeholder?: CustomAuthor | null; } diff --git a/webapp/src/app/api/model/dehydrated-author.ts b/webapp/src/app/api/model/dehydratedAuthor.ts similarity index 100% rename from webapp/src/app/api/model/dehydrated-author.ts rename to webapp/src/app/api/model/dehydratedAuthor.ts diff --git a/webapp/src/app/api/model/dehydrated-funder.ts b/webapp/src/app/api/model/dehydratedFunder.ts similarity index 100% rename from webapp/src/app/api/model/dehydrated-funder.ts rename to webapp/src/app/api/model/dehydratedFunder.ts diff --git a/webapp/src/app/api/model/dehydrated-institution.ts b/webapp/src/app/api/model/dehydratedInstitution.ts similarity index 100% rename from webapp/src/app/api/model/dehydrated-institution.ts rename to webapp/src/app/api/model/dehydratedInstitution.ts diff --git a/webapp/src/app/api/model/dehydrated-source.ts b/webapp/src/app/api/model/dehydratedSource.ts similarity index 100% rename from webapp/src/app/api/model/dehydrated-source.ts rename to webapp/src/app/api/model/dehydratedSource.ts diff --git a/webapp/src/app/api/model/filter-properties.ts b/webapp/src/app/api/model/filter-properties.ts deleted file mode 100644 index daeb08ee..00000000 --- a/webapp/src/app/api/model/filter-properties.ts +++ /dev/null @@ -1,22 +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. - */ - - -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; -} - diff --git a/webapp/src/app/api/model/filter-information.ts b/webapp/src/app/api/model/filterInformation.ts similarity index 85% rename from webapp/src/app/api/model/filter-information.ts rename to webapp/src/app/api/model/filterInformation.ts index a8e9d5dd..b2078376 100644 --- a/webapp/src/app/api/model/filter-information.ts +++ b/webapp/src/app/api/model/filterInformation.ts @@ -7,8 +7,8 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { InstitutionInformation } from './institution-information'; -import { WorkTopicInformation } from './work-topic-information'; +import { InstitutionInformation } from './institutionInformation'; +import { WorkTopicInformation } from './workTopicInformation'; export interface FilterInformation { 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/funder-by-author.ts b/webapp/src/app/api/model/funderByAuthor.ts similarity index 71% rename from webapp/src/app/api/model/funder-by-author.ts rename to webapp/src/app/api/model/funderByAuthor.ts index 06fa85f0..fbcbf475 100644 --- a/webapp/src/app/api/model/funder-by-author.ts +++ b/webapp/src/app/api/model/funderByAuthor.ts @@ -7,8 +7,8 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { PublicationIdsByAuthorPosition } from './publication-ids-by-author-position'; -import { AuthorPositionCount } from './author-position-count'; +import { PublicationIdsByAuthorPosition } from './publicationIdsByAuthorPosition'; +import { AuthorPositionCount } from './authorPositionCount'; export interface FunderByAuthor { @@ -18,5 +18,6 @@ export interface FunderByAuthor { 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/funders-by-author-response.ts b/webapp/src/app/api/model/fundersByAuthorResponse.ts similarity index 87% rename from webapp/src/app/api/model/funders-by-author-response.ts rename to webapp/src/app/api/model/fundersByAuthorResponse.ts index 6949ed4b..1286429e 100644 --- a/webapp/src/app/api/model/funders-by-author-response.ts +++ b/webapp/src/app/api/model/fundersByAuthorResponse.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { FunderByAuthor } from './funder-by-author'; +import { FunderByAuthor } from './funderByAuthor'; export interface FundersByAuthorResponse { diff --git a/webapp/src/app/api/model/group-by-result.ts b/webapp/src/app/api/model/groupByResult.ts similarity index 100% rename from webapp/src/app/api/model/group-by-result.ts rename to webapp/src/app/api/model/groupByResult.ts diff --git a/webapp/src/app/api/model/http-validation-error.ts b/webapp/src/app/api/model/hTTPValidationError.ts similarity index 84% rename from webapp/src/app/api/model/http-validation-error.ts rename to webapp/src/app/api/model/hTTPValidationError.ts index a82a8f71..f624be37 100644 --- a/webapp/src/app/api/model/http-validation-error.ts +++ b/webapp/src/app/api/model/hTTPValidationError.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { ValidationError } from './validation-error'; +import { ValidationError } from './validationError'; export interface HTTPValidationError { diff --git a/webapp/src/app/api/model/identity-grant.ts b/webapp/src/app/api/model/identityGrant.ts similarity index 89% rename from webapp/src/app/api/model/identity-grant.ts rename to webapp/src/app/api/model/identityGrant.ts index fd48137c..9ec3fe50 100644 --- a/webapp/src/app/api/model/identity-grant.ts +++ b/webapp/src/app/api/model/identityGrant.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { AuthScope } from './auth-scope'; +import { AuthScope } from './authScope'; export interface IdentityGrant { diff --git a/webapp/src/app/api/model/institution.ts b/webapp/src/app/api/model/institution.ts new file mode 100644 index 00000000..6b1a5778 --- /dev/null +++ b/webapp/src/app/api/model/institution.ts @@ -0,0 +1,41 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { InstitutionIds } from './institutionIds'; +import { AuthorCountsByYearInner } from './authorCountsByYearInner'; +import { AuthorSummaryStats } from './authorSummaryStats'; +import { InstitutionGeo } from './institutionGeo'; + + +/** + * A university, research organization, or other affiliation + */ +export interface Institution { + id?: string | null; + ror?: string | null; + display_name?: string | null; + country_code?: string | null; + type?: string | null; + homepage_url?: string | null; + image_url?: string | null; + image_thumbnail_url?: string | null; + display_name_acronyms?: Array | null; + display_name_alternatives?: Array | null; + works_count?: number | null; + cited_by_count?: number | null; + summary_stats?: AuthorSummaryStats | null; + geo?: InstitutionGeo | null; + lineage?: Array | null; + ids?: InstitutionIds | null; + counts_by_year?: Array | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; +} + diff --git a/webapp/src/app/api/model/institutionGeo.ts b/webapp/src/app/api/model/institutionGeo.ts new file mode 100644 index 00000000..949b73f4 --- /dev/null +++ b/webapp/src/app/api/model/institutionGeo.ts @@ -0,0 +1,26 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Latitude } from './latitude'; +import { Longitude } from './longitude'; + + +/** + * Location information: + */ +export interface InstitutionGeo { + city?: string | null; + geonames_city_id?: string | null; + region?: string | null; + country_code?: string | null; + country?: string | null; + latitude?: Latitude | null; + longitude?: Longitude | null; +} + diff --git a/webapp/src/app/api/model/institutionIds.ts b/webapp/src/app/api/model/institutionIds.ts new file mode 100644 index 00000000..93d801e1 --- /dev/null +++ b/webapp/src/app/api/model/institutionIds.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * External identifiers: + */ +export interface InstitutionIds { + openalex?: string | null; + ror?: string | null; + mag?: number | null; + grid?: string | null; + wikipedia?: string | null; + wikidata?: string | null; +} + diff --git a/webapp/src/app/api/model/institution-information.ts b/webapp/src/app/api/model/institutionInformation.ts similarity index 100% rename from webapp/src/app/api/model/institution-information.ts rename to webapp/src/app/api/model/institutionInformation.ts 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/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/item-create.ts b/webapp/src/app/api/model/itemCreate.ts similarity index 100% rename from webapp/src/app/api/model/item-create.ts rename to webapp/src/app/api/model/itemCreate.ts diff --git a/webapp/src/app/api/model/item-page.ts b/webapp/src/app/api/model/itemPage.ts similarity index 100% rename from webapp/src/app/api/model/item-page.ts rename to webapp/src/app/api/model/itemPage.ts diff --git a/webapp/src/app/api/model/person-filters.ts b/webapp/src/app/api/model/latitude.ts similarity index 67% rename from webapp/src/app/api/model/person-filters.ts rename to webapp/src/app/api/model/latitude.ts index 625bc459..fe6b49aa 100644 --- a/webapp/src/app/api/model/person-filters.ts +++ b/webapp/src/app/api/model/latitude.ts @@ -9,8 +9,6 @@ */ -export interface PersonFilters { - institution?: string | null; - cited_by_count?: number | null; +export interface Latitude { } diff --git a/webapp/src/app/api/model/location.ts b/webapp/src/app/api/model/location.ts index ed2aa1e2..f207d751 100644 --- a/webapp/src/app/api/model/location.ts +++ b/webapp/src/app/api/model/location.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { DehydratedSource } from './dehydrated-source'; +import { DehydratedSource } from './dehydratedSource'; /** 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/meta.ts b/webapp/src/app/api/model/meta.ts index cf47d6d3..8481062a 100644 --- a/webapp/src/app/api/model/meta.ts +++ b/webapp/src/app/api/model/meta.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { CostUsd } from './cost-usd'; +import { CostUsd } from './costUsd'; /** diff --git a/webapp/src/app/api/model/model2-yr-mean-citedness.ts b/webapp/src/app/api/model/model2YrMeanCitedness.ts similarity index 100% rename from webapp/src/app/api/model/model2-yr-mean-citedness.ts rename to webapp/src/app/api/model/model2YrMeanCitedness.ts diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index c9938757..3c24b908 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -1,67 +1,86 @@ -export * from './access-grant'; -export * from './auth-account'; -export * from './auth-scope'; +export * from './accessGrant'; +export * from './authAccount'; +export * from './authScope'; export * from './author'; -export * from './author-affiliations-inner'; -export * from './author-counts-by-year-inner'; -export * from './author-ids'; -export * from './author-parsed-longest-name'; -export * from './author-position-count'; -export * from './author-summary-stats'; -export * from './authors-list-response'; +export * from './authorAffiliationsInner'; +export * from './authorCountsByYearInner'; +export * from './authorIds'; +export * from './authorNetworkNode'; +export * from './authorParsedLongestName'; +export * from './authorPositionCount'; +export * from './authorSummaryStats'; +export * from './authorsFilterProperties'; +export * from './authorsListResponse'; export * from './authorship'; +export * from './autocompleteResponse'; +export * from './autocompleteResponseMeta'; +export * from './autocompleteResponseResultsInner'; export * from './award'; -export * from './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'; -export * from './dehydrated-institution'; -export * from './dehydrated-source'; -export * from './filter-information'; -export * from './filter-properties'; -export * from './funder-by-author'; -export * from './funders-by-author-response'; +export * from './collaborationNetwork'; +export * from './collaborationNetworkEdge'; +export * from './collaborationNetworkNodeType'; +export * from './costUsd'; +export * from './customAuthor'; +export * from './customAuthorsListResponse'; +export * from './dehydratedAuthor'; +export * from './dehydratedFunder'; +export * from './dehydratedInstitution'; +export * from './dehydratedSource'; +export * from './filterInformation'; +export * from './filterProperties'; +export * from './funderByAuthor'; +export * from './fundersByAuthorResponse'; export * from './fwci'; -export * from './group-by-result'; -export * from './http-validation-error'; -export * from './identity-grant'; -export * from './institution-information'; +export * from './groupByResult'; +export * from './hTTPValidationError'; +export * from './identityGrant'; +export * from './institution'; +export * from './institutionGeo'; +export * from './institutionIds'; +export * from './institutionInformation'; +export * from './institutionNetworkNode'; +export * from './institutionsListResponse'; export * from './item'; -export * from './item-create'; -export * from './item-page'; +export * from './itemCreate'; +export * from './itemPage'; +export * from './latitude'; export * from './location'; +export * from './longitude'; export * from './meta'; -export * from './model2-yr-mean-citedness'; -export * from './open-access'; -export * from './person-bio'; -export * from './publication-ids-by-author-position'; -export * from './publications-by-author-response'; +export * from './model2YrMeanCitedness'; +export * from './openAccess'; +export * from './personBio'; +export * from './publicationIdsByAuthorPosition'; +export * from './publicationsByAuthorResponse'; export * from './score'; -export * from './topic-count'; -export * from './topics-by-time'; -export * from './topics-by-year'; -export * from './validation-error'; -export * from './validation-error-loc-inner'; +export * from './topic'; +export * from './topicCount'; +export * from './topicDomain'; +export * from './topicField'; +export * from './topicIds'; +export * from './topicSubfield'; +export * from './topicsByTime'; +export * from './topicsByYear'; +export * from './topicsListResponse'; +export * from './validationError'; +export * from './validationErrorLocInner'; export * from './value'; export * from './work'; -export * from './work-biblio'; -export * from './work-citation-normalized-percentile'; -export * from './work-cited-by-percentile-year'; -export * from './work-counts-by-year-inner'; -export * from './work-has-content'; -export * from './work-ids'; -export * from './work-keyword'; -export * from './work-mesh-inner'; -export * from './work-page'; -export * from './work-sustainable-development-goals-inner'; -export * from './work-topic'; -export * from './work-topic-domain'; -export * from './work-topic-field'; -export * from './work-topic-information'; -export * from './work-topic-subfield'; -export * from './works-list-response'; +export * from './workBiblio'; +export * from './workCitationNormalizedPercentile'; +export * from './workCitedByPercentileYear'; +export * from './workCountsByYearInner'; +export * from './workHasContent'; +export * from './workIds'; +export * from './workKeyword'; +export * from './workMeshInner'; +export * from './workNetworkNode'; +export * from './workPage'; +export * from './workSustainableDevelopmentGoalsInner'; +export * from './workTopic'; +export * from './workTopicDomain'; +export * from './workTopicField'; +export * from './workTopicInformation'; +export * from './workTopicSubfield'; +export * from './worksFilterProperties'; +export * from './worksListResponse'; diff --git a/webapp/src/app/api/model/open-access.ts b/webapp/src/app/api/model/openAccess.ts similarity index 100% rename from webapp/src/app/api/model/open-access.ts rename to webapp/src/app/api/model/openAccess.ts 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/person-bio.ts b/webapp/src/app/api/model/personBio.ts similarity index 100% rename from webapp/src/app/api/model/person-bio.ts rename to webapp/src/app/api/model/personBio.ts diff --git a/webapp/src/app/api/model/publication-ids-by-author-position.ts b/webapp/src/app/api/model/publicationIdsByAuthorPosition.ts similarity index 100% rename from webapp/src/app/api/model/publication-ids-by-author-position.ts rename to webapp/src/app/api/model/publicationIdsByAuthorPosition.ts diff --git a/webapp/src/app/api/model/publications-by-author-response.ts b/webapp/src/app/api/model/publicationsByAuthorResponse.ts similarity index 100% rename from webapp/src/app/api/model/publications-by-author-response.ts rename to webapp/src/app/api/model/publicationsByAuthorResponse.ts diff --git a/webapp/src/app/api/model/topic.ts b/webapp/src/app/api/model/topic.ts new file mode 100644 index 00000000..9fc0ee63 --- /dev/null +++ b/webapp/src/app/api/model/topic.ts @@ -0,0 +1,34 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { TopicDomain } from './topicDomain'; +import { TopicIds } from './topicIds'; +import { TopicSubfield } from './topicSubfield'; +import { TopicField } from './topicField'; + + +/** + * A research topic automatically assigned to works + */ +export interface Topic { + id?: string | null; + display_name?: string | null; + description?: string | null; + keywords?: Array | null; + subfield?: TopicSubfield | null; + field?: TopicField | null; + domain?: TopicDomain | null; + works_count?: number | null; + cited_by_count?: number | null; + ids?: TopicIds | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; +} + diff --git a/webapp/src/app/api/model/topic-count.ts b/webapp/src/app/api/model/topicCount.ts similarity index 100% rename from webapp/src/app/api/model/topic-count.ts rename to webapp/src/app/api/model/topicCount.ts 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-by-time.ts b/webapp/src/app/api/model/topicsByTime.ts similarity index 89% rename from webapp/src/app/api/model/topics-by-time.ts rename to webapp/src/app/api/model/topicsByTime.ts index d2ecf101..0dac04a7 100644 --- a/webapp/src/app/api/model/topics-by-time.ts +++ b/webapp/src/app/api/model/topicsByTime.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { TopicsByYear } from './topics-by-year'; +import { TopicsByYear } from './topicsByYear'; export interface TopicsByTime { diff --git a/webapp/src/app/api/model/topics-by-year.ts b/webapp/src/app/api/model/topicsByYear.ts similarity index 92% rename from webapp/src/app/api/model/topics-by-year.ts rename to webapp/src/app/api/model/topicsByYear.ts index 707cda16..fded8da0 100644 --- a/webapp/src/app/api/model/topics-by-year.ts +++ b/webapp/src/app/api/model/topicsByYear.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { TopicCount } from './topic-count'; +import { TopicCount } from './topicCount'; export interface TopicsByYear { 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/validation-error.ts b/webapp/src/app/api/model/validationError.ts similarity index 82% rename from webapp/src/app/api/model/validation-error.ts rename to webapp/src/app/api/model/validationError.ts index c71e7bfa..bdbd57ad 100644 --- a/webapp/src/app/api/model/validation-error.ts +++ b/webapp/src/app/api/model/validationError.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { ValidationErrorLocInner } from './validation-error-loc-inner'; +import { ValidationErrorLocInner } from './validationErrorLocInner'; export interface ValidationError { diff --git a/webapp/src/app/api/model/validation-error-loc-inner.ts b/webapp/src/app/api/model/validationErrorLocInner.ts similarity index 100% rename from webapp/src/app/api/model/validation-error-loc-inner.ts rename to webapp/src/app/api/model/validationErrorLocInner.ts diff --git a/webapp/src/app/api/model/work.ts b/webapp/src/app/api/model/work.ts index b84cc7b6..07d94a1c 100644 --- a/webapp/src/app/api/model/work.ts +++ b/webapp/src/app/api/model/work.ts @@ -7,22 +7,22 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { DehydratedFunder } from './dehydrated-funder'; +import { DehydratedFunder } from './dehydratedFunder'; import { Authorship } from './authorship'; -import { OpenAccess } from './open-access'; -import { WorkIds } from './work-ids'; -import { WorkSustainableDevelopmentGoalsInner } from './work-sustainable-development-goals-inner'; -import { WorkTopic } from './work-topic'; -import { WorkCountsByYearInner } from './work-counts-by-year-inner'; -import { WorkKeyword } from './work-keyword'; -import { WorkCitationNormalizedPercentile } from './work-citation-normalized-percentile'; +import { OpenAccess } from './openAccess'; +import { WorkIds } from './workIds'; +import { WorkSustainableDevelopmentGoalsInner } from './workSustainableDevelopmentGoalsInner'; +import { WorkTopic } from './workTopic'; +import { WorkCountsByYearInner } from './workCountsByYearInner'; +import { WorkKeyword } from './workKeyword'; +import { WorkCitationNormalizedPercentile } from './workCitationNormalizedPercentile'; import { Award } from './award'; import { Fwci } from './fwci'; -import { WorkMeshInner } from './work-mesh-inner'; -import { WorkCitedByPercentileYear } from './work-cited-by-percentile-year'; -import { WorkHasContent } from './work-has-content'; +import { WorkMeshInner } from './workMeshInner'; +import { WorkCitedByPercentileYear } from './workCitedByPercentileYear'; +import { WorkHasContent } from './workHasContent'; import { Location } from './location'; -import { WorkBiblio } from './work-biblio'; +import { WorkBiblio } from './workBiblio'; /** diff --git a/webapp/src/app/api/model/work-biblio.ts b/webapp/src/app/api/model/workBiblio.ts similarity index 100% rename from webapp/src/app/api/model/work-biblio.ts rename to webapp/src/app/api/model/workBiblio.ts diff --git a/webapp/src/app/api/model/work-citation-normalized-percentile.ts b/webapp/src/app/api/model/workCitationNormalizedPercentile.ts similarity index 100% rename from webapp/src/app/api/model/work-citation-normalized-percentile.ts rename to webapp/src/app/api/model/workCitationNormalizedPercentile.ts diff --git a/webapp/src/app/api/model/work-cited-by-percentile-year.ts b/webapp/src/app/api/model/workCitedByPercentileYear.ts similarity index 100% rename from webapp/src/app/api/model/work-cited-by-percentile-year.ts rename to webapp/src/app/api/model/workCitedByPercentileYear.ts diff --git a/webapp/src/app/api/model/work-counts-by-year-inner.ts b/webapp/src/app/api/model/workCountsByYearInner.ts similarity index 100% rename from webapp/src/app/api/model/work-counts-by-year-inner.ts rename to webapp/src/app/api/model/workCountsByYearInner.ts diff --git a/webapp/src/app/api/model/work-has-content.ts b/webapp/src/app/api/model/workHasContent.ts similarity index 100% rename from webapp/src/app/api/model/work-has-content.ts rename to webapp/src/app/api/model/workHasContent.ts diff --git a/webapp/src/app/api/model/work-ids.ts b/webapp/src/app/api/model/workIds.ts similarity index 100% rename from webapp/src/app/api/model/work-ids.ts rename to webapp/src/app/api/model/workIds.ts diff --git a/webapp/src/app/api/model/work-keyword.ts b/webapp/src/app/api/model/workKeyword.ts similarity index 100% rename from webapp/src/app/api/model/work-keyword.ts rename to webapp/src/app/api/model/workKeyword.ts diff --git a/webapp/src/app/api/model/work-mesh-inner.ts b/webapp/src/app/api/model/workMeshInner.ts similarity index 100% rename from webapp/src/app/api/model/work-mesh-inner.ts rename to webapp/src/app/api/model/workMeshInner.ts 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/work-page.ts b/webapp/src/app/api/model/workPage.ts similarity index 100% rename from webapp/src/app/api/model/work-page.ts rename to webapp/src/app/api/model/workPage.ts diff --git a/webapp/src/app/api/model/work-sustainable-development-goals-inner.ts b/webapp/src/app/api/model/workSustainableDevelopmentGoalsInner.ts similarity index 100% rename from webapp/src/app/api/model/work-sustainable-development-goals-inner.ts rename to webapp/src/app/api/model/workSustainableDevelopmentGoalsInner.ts diff --git a/webapp/src/app/api/model/work-topic.ts b/webapp/src/app/api/model/workTopic.ts similarity index 74% rename from webapp/src/app/api/model/work-topic.ts rename to webapp/src/app/api/model/workTopic.ts index 87f829f2..925ead4f 100644 --- a/webapp/src/app/api/model/work-topic.ts +++ b/webapp/src/app/api/model/workTopic.ts @@ -8,9 +8,9 @@ * Do not edit the class manually. */ import { Score } from './score'; -import { WorkTopicDomain } from './work-topic-domain'; -import { WorkTopicSubfield } from './work-topic-subfield'; -import { WorkTopicField } from './work-topic-field'; +import { WorkTopicDomain } from './workTopicDomain'; +import { WorkTopicSubfield } from './workTopicSubfield'; +import { WorkTopicField } from './workTopicField'; /** diff --git a/webapp/src/app/api/model/work-topic-domain.ts b/webapp/src/app/api/model/workTopicDomain.ts similarity index 100% rename from webapp/src/app/api/model/work-topic-domain.ts rename to webapp/src/app/api/model/workTopicDomain.ts diff --git a/webapp/src/app/api/model/work-topic-field.ts b/webapp/src/app/api/model/workTopicField.ts similarity index 100% rename from webapp/src/app/api/model/work-topic-field.ts rename to webapp/src/app/api/model/workTopicField.ts diff --git a/webapp/src/app/api/model/work-topic-information.ts b/webapp/src/app/api/model/workTopicInformation.ts similarity index 100% rename from webapp/src/app/api/model/work-topic-information.ts rename to webapp/src/app/api/model/workTopicInformation.ts diff --git a/webapp/src/app/api/model/work-topic-subfield.ts b/webapp/src/app/api/model/workTopicSubfield.ts similarity index 100% rename from webapp/src/app/api/model/work-topic-subfield.ts rename to webapp/src/app/api/model/workTopicSubfield.ts 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/works-list-response.ts b/webapp/src/app/api/model/worksListResponse.ts similarity index 89% rename from webapp/src/app/api/model/works-list-response.ts rename to webapp/src/app/api/model/worksListResponse.ts index cf03bd2e..a65d3849 100644 --- a/webapp/src/app/api/model/works-list-response.ts +++ b/webapp/src/app/api/model/worksListResponse.ts @@ -9,7 +9,7 @@ */ import { Meta } from './meta'; import { Work } from './work'; -import { GroupByResult } from './group-by-result'; +import { GroupByResult } from './groupByResult'; /** diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index c8fe99fe..006b1c65 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -26,6 +26,14 @@ export const routes: Routes = [ (mod) => mod.PersonListComponent, ), }, + { + path: 'publication/:publicationId', + canActivate: [userGuard], + loadComponent: () => + import('./modules/publication-detail/publication-detail.component').then( + (mod) => mod.PublicationDetailComponent, + ), + }, { path: 'person/:id', canActivate: [userGuard], @@ -58,12 +66,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 +98,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/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..9d07452e --- /dev/null +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -0,0 +1,59 @@ +
+ + +
+ {{ getInitials(person.display_name) }} +
+
+
+ @if (person.relevance_rating) { + + {{ person.relevance_rating }} + + } + +
+

{{ person.display_name }}

+

+ {{ institution(person)?.display_name }} + @if (institution(person)?.country_code) { + + } +

+

{{ getDistinguishingId(person) }}

+

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

+
+
+ +
+
+ @for (topic of topics(person); track topic) { + {{ topic }} + } +
+
+ + +
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..520008c2 --- /dev/null +++ b/webapp/src/app/modules/person-card/person-card.component.scss @@ -0,0 +1,212 @@ +: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: 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; +} + +.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..89ebf0e8 --- /dev/null +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -0,0 +1,62 @@ +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 } from '../../api'; + +@Component({ + selector: 'app-person-card', + standalone: true, + imports: [CommonModule, RouterLink, MatIconModule], + templateUrl: './person-card.component.html', + styleUrl: './person-card.component.scss', +}) +export class PersonCardComponent { + @Input({ required: true }) person!: CustomAuthor; + @Input() isBookmarked = false; + @Output() bookmarkToggle = new EventEmitter(); + @Output() topicClick = 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): string[] { + return (person.topics ?? []) + .map((t) => t.display_name) + .filter((name): name is string => !!name) + .slice(0, 3); + } + + 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-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index ff01f61e..6b2b0ce4 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -20,14 +20,33 @@
Filter nach Position: - - - - + + + +
-
@@ -51,11 +70,20 @@
@if (hasFunderListPagination()) {
- - Seite {{ selectedFunderListPage }} von {{ getFunderListPageCount() }} -
@@ -68,41 +96,75 @@

{{ selectedFunder.funder_name }}

- @if (shouldShowPosition('first')) { -
- Erstautor - {{ selectedFunder.author_position_count.first }} -
+ @if (shouldShowPosition("first")) { +
+ Erstautor + {{ + selectedFunder.author_position_count.first + }} +
} - @if (shouldShowPosition('middle')) { -
- Mitautor - {{ selectedFunder.author_position_count.middle }} -
+ @if (shouldShowPosition("middle")) { +
+ Mitautor + {{ + selectedFunder.author_position_count.middle + }} +
} - @if (shouldShowPosition('last')) { -
- Letztautor - {{ selectedFunder.author_position_count.last }} -
+ @if (shouldShowPosition("last")) { +
+ Letztautor + {{ + selectedFunder.author_position_count.last + }} +
}

Publikationen

    @for (id of getSelectedPublicationIdsPage(); track id) { -
  • - {{ id }} +
  • + {{ + getPublicationTitle(id) + }} + @if (expandedPublicationId === id) { +
    + Mehr Infos + + open_in_new + +
    + }
  • }
@if (hasPublicationPagination()) {
- - Seite {{ selectedPublicationPage }} von {{ getSelectedPublicationPageCount() }} -
@@ -113,7 +175,6 @@

Klicke auf einen Förderer für Details.

} -
} diff --git a/webapp/src/app/modules/person-funding/person-funding.component.scss b/webapp/src/app/modules/person-funding/person-funding.component.scss index b9f511c9..c1a80450 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.scss +++ b/webapp/src/app/modules/person-funding/person-funding.component.scss @@ -33,17 +33,30 @@ &:hover { background: #f0f0f0; } - - &.active { - background: - radial-gradient(circle at 50% 30%, rgba(255, 255, 255, 0.78), transparent 34%), - linear-gradient(145deg, #c8d9ff, #f7faff 48%, #88a9ee); - color: var(--sg-primary); - border-color: var(--sg-border); - font-weight: 600; - box-shadow: var(--sg-shadow-sm); - } } + button:nth-child(2) { + background: #f0f6ff; + color: #0b63ce; + border-color: #bdd4ff; +} + +button:nth-child(3) { + background: #effaf3; + color: #24834f; + border-color: #bdebcf; +} + +button:nth-child(4) { + background: #f6f0ff; + color: #7255d9; + border-color: #d8cafe; +} + +button:nth-child(5) { + background: #fff7e8; + color: #c67500; + border-color: #ffd796; +} } .funding-content { @@ -93,7 +106,7 @@ } .funding-detail { - width: 340px; + width: 440px; border: 1px solid #e0e0e0; border-radius: 8px; padding: 20px; @@ -124,9 +137,13 @@ display: flex; gap: 12px; margin-bottom: 16px; + width: fit-content; + margin-left: auto; + margin-right: auto; .stat { - flex: 1; + flex: 0.0 auto; + min-width: 100px; text-align: center; background: white; border: 1px solid #e0e0e0; @@ -147,6 +164,20 @@ color: #333; } } + .stat-first { + background: #effaf3; + border-color: #bdebcf; + } + + .stat-middle { + background: #f6f0ff; + border-color: #d8cafe; + } + + .stat-last { + background: #fff7e8; + border-color: #ffd796; + } } .publication-list { @@ -158,7 +189,7 @@ li { padding: 6px 0; - border-bottom: 1px solid #f0f0f0; + border-bottom: 1px solid #5b5555; font-size: 13px; a { @@ -219,3 +250,49 @@ color: #333; } } +.publication-item { + padding: 8px 0; + border-bottom: 2px solid #5b5555; + cursor: pointer; + + &:hover { + background: #f9f9f9; + } +} + +.publication-title { + font-size: 0.875rem; + color: #333; + white-space: normal; + word-break: break-word; + display: block; +} +.publication-more-info { + display: flex; + align-items: center; + flex-direction: row; + gap: 4px; + margin-top: 6px; +} + +.mehr-infos-label { + font-size: 0.8rem; + color: #1976d2; + font-weight: 500; +} + +.publication-link-icon { + display: flex; + align-items: center; + color: #1976d2; + text-decoration: none; + flex-shrink: 0; + + .material-icons { + font-size: 16px; + } + + &:hover { + color: #0d47a1; + } +} diff --git a/webapp/src/app/modules/person-funding/person-funding.component.ts b/webapp/src/app/modules/person-funding/person-funding.component.ts index 4e0a074d..72609509 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -28,6 +28,7 @@ export class PersonFundingComponent implements OnInit { activeFilter: 'all' | 'first' | 'middle' | 'last' = 'all'; loading = true; error = false; + expandedPublicationId: string | null = null; ngOnInit(): void { this.route.parent?.paramMap.subscribe(params => { @@ -257,4 +258,13 @@ export class PersonFundingComponent implements OnInit { } return parsed; } + getPublicationTitle(publicationId: string): string { + const title = this.selectedFunder?.publication_titles?.[publicationId]; + if (title) return title; + const parts = publicationId.split('/'); + return parts[parts.length - 1] ?? publicationId; + } + togglePublication(id: string): void { + this.expandedPublicationId = this.expandedPublicationId === id ? null : id; +} } 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..f516e3d9 100644 --- a/webapp/src/app/modules/person-list/person-list.component.html +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -73,61 +73,12 @@ } @else if (sortedPersons.length) {
@for (person of sortedPersons; track person.id) { -
-
- -
- {{ getInitials(person.display_name) }} -
-
-
- @if (person.relevance_rating) { - - {{ person.relevance_rating }} - - } - -
-

{{ 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 { 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..d8f2eb02 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; @@ -567,50 +353,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); 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 4c170319..141fd937 100644 --- a/webapp/src/app/modules/person-list/person-list.component.ts +++ b/webapp/src/app/modules/person-list/person-list.component.ts @@ -12,11 +12,11 @@ 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 } 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'; @@ -37,6 +37,7 @@ import { MatSnackBar } from '@angular/material/snack-bar'; MatCheckboxModule, MatRadioModule, TopicHierarchyComponent, + PersonCardComponent, ], templateUrl: './person-list.component.html', styleUrl: './person-list.component.scss', @@ -64,47 +65,59 @@ export class PersonListComponent { // Selected filter states selectedTopics = new Set(); - // 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' - ]; - // Forms sortControl = new FormControl('relevance', { 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() { + // Enable/disable the year filter checkbox based on the presence of an institution value + if (!this.institutionControl.value) { + this.yearFilterEnabledControl.disable(); + } + this.institutionControl.valueChanges + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((val) => { + if (!val) { + this.yearFilterEnabledControl.disable(); + this.yearFilterEnabledControl.setValue(false); + } else { + this.yearFilterEnabledControl.enable(); + } + }); + // Subscribe to route query parameters to trigger searches 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']); @@ -129,7 +142,16 @@ export class PersonListComponent { this.filterYearControl.setValue(filterYear); } - this.load(query, page, pageSize, topics, institutionName, yearFilterEnabled, filterMode, filterYear); + this.load( + query, + page, + pageSize, + topics, + institutionName, + yearFilterEnabled, + filterMode, + filterYear, + ); }); } @@ -141,24 +163,25 @@ export class PersonListComponent { institutionName?: string, yearFilterEnabled: boolean = false, filterMode: 'in' | 'from' = 'from', - filterYear?: number + 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 - ) + 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) + takeUntilDestroyed(this.destroyRef), ) .subscribe({ next: (response) => { @@ -167,7 +190,7 @@ export class PersonListComponent { }, error: (err) => { console.error('Error loading persons:', err); - } + }, }); } @@ -178,39 +201,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); @@ -226,9 +227,13 @@ 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 => { + 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 }); }); if (this.institutionControl.value) { @@ -240,13 +245,13 @@ export class PersonListComponent { list.push({ category: 'institutionName', value: this.institutionControl.value, - label: label + 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') { @@ -273,11 +278,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, }, @@ -287,7 +303,10 @@ export class PersonListComponent { // Pagination custom calculation get totalPages(): number { - return Math.max(1, Math.ceil(this.total / this.paginationService.selection)); + return Math.max( + 1, + Math.ceil(this.total / this.paginationService.selection), + ); } get pageList(): number[] { @@ -329,7 +348,7 @@ export class PersonListComponent { goToPage(p: number): void { this.router.navigate([], { queryParams: { page: p }, - queryParamsHandling: 'merge' + queryParamsHandling: 'merge', }); } @@ -340,36 +359,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 { @@ -386,6 +376,10 @@ export class PersonListComponent { this.applySidebarFilters(); } + onCardTopicClick(topic: string): void { + this.topicSearchControl.setValue(topic); + } + isBookmarked(person: CustomAuthor): boolean { return !!person.id && this.bookmarkedIds.has(person.id); } @@ -398,13 +392,7 @@ export class PersonListComponent { }); } - getDistinguishingId(person: CustomAuthor): string { - if (!person) return ''; - if (person.orcid) { - return person.orcid.replace('https://orcid.org/', ''); - } - return ''; - } + private parseQueryParamArray(val: any): string[] { if (!val) return []; 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..4867052f 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.ts +++ b/webapp/src/app/modules/person-publications/person-publications.component.ts @@ -1,6 +1,11 @@ -import { Component, OnInit, ViewChild } from '@angular/core'; +import { Component, DestroyRef, OnInit, ViewChild, inject } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; -import { ActivatedRoute } from '@angular/router'; +import { ActivatedRoute, ParamMap, Router, RouterLink } from '@angular/router'; +import { + MatAutocompleteModule, + MatAutocompleteSelectedEvent, +} from '@angular/material/autocomplete'; import { MatIconModule } from '@angular/material/icon'; import { MatPaginator, @@ -12,46 +17,113 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { MatTableModule } from '@angular/material/table'; import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { + catchError, + combineLatest, + debounceTime, + distinctUntilChanged, + finalize, + map, + of, + switchMap, +} from 'rxjs'; import { Work, WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; import { createLoadError } from '../../shared/utils/errorHandler'; import { ChipComponent } from '../../shared/ui/chip/chip.component'; +interface InstitutionAutocompleteOption { + id?: string | null; + display_name?: string | null; + hint?: string | null; + cited_by_count?: number | null; + works_count?: number | null; + entity_type?: string | null; + external_id?: string | null; +} + +interface InstitutionAutocompleteResponse { + results?: InstitutionAutocompleteOption[] | null; +} + +interface TopicAutocompleteOption { + id?: string | null; + display_name?: string | null; + hint?: string | null; + cited_by_count?: number | null; + works_count?: number | null; + entity_type?: string | null; + external_id?: string | null; +} + +interface TopicAutocompleteResponse { + results?: TopicAutocompleteOption[] | null; +} + +interface PublicationFilterQueryState { + pageIndex: number; + pageSize: number; + publicationYears: number[]; + types: string[]; + languages: string[]; + institutions: InstitutionAutocompleteOption[]; + topics: TopicAutocompleteOption[]; +} + @Component({ selector: 'app-person-publications', imports: [ MatButtonModule, + MatAutocompleteModule, ChipComponent, MatIconModule, MatFormFieldModule, + MatInputModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, MatSnackBarModule, MatTableModule, ReactiveFormsModule, + RouterLink, ], templateUrl: './person-publications.component.html', styleUrl: './person-publications.component.scss', }) export class PersonPublicationsComponent implements OnInit { @ViewChild(MatPaginator) paginator?: MatPaginator; + private readonly destroyRef = inject(DestroyRef); displayedColumns: string[] = [ 'title', 'type', 'year', 'language', + 'institutions', 'topics', 'citations', ]; publications: Work[] = []; total = 0; loading = false; + institutionLookupLoading = false; + topicLookupLoading = false; authorId = ''; currentPageIndex = 0; + institutionOptions: InstitutionAutocompleteOption[] = []; + selectedInstitutions: InstitutionAutocompleteOption[] = []; + topicOptions: TopicAutocompleteOption[] = []; + selectedTopics: TopicAutocompleteOption[] = []; + readonly institutionSearchControl = new FormControl< + string | InstitutionAutocompleteOption + >('', { nonNullable: true }); + readonly topicSearchControl = new FormControl('', { + nonNullable: true, + }); readonly filterForm = new FormGroup({ publicationYears: new FormControl([], { nonNullable: true }), @@ -61,6 +133,18 @@ export class PersonPublicationsComponent implements OnInit { readonly publicationYearOptions = this.createPublicationYearOptions(); + private readonly queryParamKeys = { + page: 'publicationPage', + pageSize: 'publicationPageSize', + years: 'publicationYear', + types: 'publicationType', + languages: 'publicationLanguage', + institutionIds: 'publicationInstitutionId', + institutionNames: 'publicationInstitutionName', + topicIds: 'publicationTopicId', + topicNames: 'publicationTopicName', + } as const; + readonly typeOptions = [ { value: 'article', label: 'article' }, { value: 'book', label: 'book' }, @@ -90,16 +174,28 @@ export class PersonPublicationsComponent implements OnInit { constructor( private readonly route: ActivatedRoute, + private readonly router: Router, private readonly workService: WorksService, + private readonly httpClient: HttpClient, public readonly paginationService: PaginationService, private readonly snackBar: MatSnackBar, ) {} ngOnInit(): void { - this.route.parent?.paramMap.subscribe((params) => { - this.authorId = params.get('id') ?? ''; - this.resetAndLoad(); - }); + this.setupInstitutionAutocomplete(); + this.setupTopicAutocomplete(); + + const parentParamMap = this.route.parent?.paramMap; + if (!parentParamMap) return; + + combineLatest([parentParamMap, this.route.queryParamMap]) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(([params, queryParams]) => { + this.authorId = params.get('id') ?? ''; + const queryState = this.parsePublicationFilterQueryParams(queryParams); + this.applyPublicationFilterQueryState(queryState); + this.load(queryState.pageIndex, queryState.pageSize); + }); } load(pageIndex = 0, pageSize = this.paginationService.selection): void { @@ -116,6 +212,8 @@ export class PersonPublicationsComponent implements OnInit { this.filters().publicationYears, this.filters().types, this.filters().languages, + this.selectedInstitutionIds(), + this.selectedTopicIds(), ) .subscribe({ next: (page) => { @@ -137,13 +235,19 @@ export class PersonPublicationsComponent implements OnInit { onPage(event: PageEvent): void { this.paginationService.selection = event.pageSize; this.currentPageIndex = event.pageIndex; - this.load(event.pageIndex, event.pageSize); + this.updatePublicationFilterQueryParams({ + [this.queryParamKeys.page]: event.pageIndex + 1, + [this.queryParamKeys.pageSize]: event.pageSize, + }); } - resetAndLoad(): void { + applyFilters(): void { this.currentPageIndex = 0; this.paginator?.firstPage(); - this.load(0, this.paginationService.selection); + this.updatePublicationFilterQueryParams({ + [this.queryParamKeys.page]: 1, + [this.queryParamKeys.pageSize]: this.paginationService.selection, + }); } clearFilters(): void { @@ -152,7 +256,65 @@ export class PersonPublicationsComponent implements OnInit { types: [], languages: [], }); - this.resetAndLoad(); + this.selectedInstitutions = []; + this.selectedTopics = []; + this.institutionOptions = []; + this.topicOptions = []; + this.institutionSearchControl.setValue('', { emitEvent: false }); + this.topicSearchControl.setValue('', { emitEvent: false }); + this.updatePublicationFilterQueryParams({ + [this.queryParamKeys.page]: 1, + [this.queryParamKeys.pageSize]: this.paginationService.selection, + [this.queryParamKeys.years]: null, + [this.queryParamKeys.types]: null, + [this.queryParamKeys.languages]: null, + [this.queryParamKeys.institutionIds]: null, + [this.queryParamKeys.institutionNames]: null, + [this.queryParamKeys.topicIds]: null, + [this.queryParamKeys.topicNames]: null, + }); + } + + displayInstitution(option: string | InstitutionAutocompleteOption): string { + return typeof option === 'string' ? option : (option.display_name ?? ''); + } + + selectInstitution(event: MatAutocompleteSelectedEvent): void { + const institution = event.option.value as InstitutionAutocompleteOption; + if (!institution.id) return; + if (!this.selectedInstitutions.some((item) => item.id === institution.id)) { + this.selectedInstitutions = [...this.selectedInstitutions, institution]; + this.applyFilters(); + } + this.institutionSearchControl.setValue('', { emitEvent: false }); + this.institutionOptions = []; + } + + removeInstitution(institution: InstitutionAutocompleteOption): void { + this.selectedInstitutions = this.selectedInstitutions.filter( + (item) => item.id !== institution.id, + ); + this.applyFilters(); + } + + displayTopic(option: string | TopicAutocompleteOption): string { + return typeof option === 'string' ? option : (option.display_name ?? ''); + } + + selectTopic(event: MatAutocompleteSelectedEvent): void { + const topic = event.option.value as TopicAutocompleteOption; + if (!topic.id) return; + if (!this.selectedTopics.some((item) => item.id === topic.id)) { + this.selectedTopics = [...this.selectedTopics, topic]; + this.applyFilters(); + } + this.topicSearchControl.setValue('', { emitEvent: false }); + this.topicOptions = []; + } + + removeTopic(topic: TopicAutocompleteOption): void { + this.selectedTopics = this.selectedTopics.filter((item) => item.id !== topic.id); + this.applyFilters(); } doiUrl(doi: string | null | undefined): string | null { @@ -160,6 +322,11 @@ export class PersonPublicationsComponent implements OnInit { return doi.startsWith('http') ? doi : `https://doi.org/${doi}`; } + publicationKey(publication: Work): string { + const id = publication.id ?? publication.ids?.openalex ?? publication.doi ?? ''; + return id.split('/').filter(Boolean).pop() ?? id; + } + publicationRange(): string { if (this.total === 0 || this.publications.length === 0) { return 'Keine Publikationen'; @@ -175,6 +342,24 @@ export class PersonPublicationsComponent implements OnInit { return 'info'; } + institutions(publication: Work): Array<{ id: string; name: string }> { + const institutionsById = new Map(); + + for (const authorship of publication.authorships ?? []) { + for (const institution of authorship.institutions ?? []) { + if (!institution.id || !institution.display_name) continue; + if (!institutionsById.has(institution.id)) { + institutionsById.set(institution.id, { + id: institution.id, + name: institution.display_name, + }); + } + } + } + + return Array.from(institutionsById.values()); + } + private filters() { return { publicationYears: this.filterForm.controls.publicationYears.value, @@ -183,6 +368,210 @@ export class PersonPublicationsComponent implements OnInit { }; } + private setupInstitutionAutocomplete(): void { + this.institutionSearchControl.valueChanges + .pipe( + debounceTime(250), + map((value) => (typeof value === 'string' ? value.trim() : '')), + distinctUntilChanged(), + switchMap((query) => { + if (query.length < 2) { + this.institutionOptions = []; + return of([]); + } + this.institutionLookupLoading = true; + return this.searchInstitutions(query).pipe( + catchError(() => of([])), + finalize(() => { + this.institutionLookupLoading = false; + }), + ); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((options) => { + const selectedIds = new Set(this.selectedInstitutionIds()); + this.institutionOptions = options.filter( + (option) => !!option.id && !selectedIds.has(option.id), + ); + }); + } + + private setupTopicAutocomplete(): void { + this.topicSearchControl.valueChanges + .pipe( + debounceTime(250), + map((value) => (typeof value === 'string' ? value.trim() : '')), + distinctUntilChanged(), + switchMap((query) => { + if (query.length < 2) { + this.topicOptions = []; + return of([]); + } + this.topicLookupLoading = true; + return this.searchTopics(query).pipe( + catchError(() => of([])), + finalize(() => { + this.topicLookupLoading = false; + }), + ); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((options) => { + const selectedIds = new Set(this.selectedTopicIds()); + this.topicOptions = options.filter( + (option) => !!option.id && !selectedIds.has(option.id), + ); + }); + } + + private searchInstitutions(query: string) { + const params = new HttpParams() + .set('query', query) + .set('limit', '10'); + + const basePath = this.workService.configuration.basePath ?? ''; + return this.httpClient + .get(`${basePath}/api/institutions/autocomplete`, { + params, + }) + .pipe(map((response) => response.results ?? [])); + } + + private searchTopics(query: string) { + const params = new HttpParams().set('query', query).set('limit', '10'); + + const basePath = this.workService.configuration.basePath ?? ''; + return this.httpClient + .get(`${basePath}/api/topics/autocomplete`, { + params, + }) + .pipe(map((response) => response.results ?? [])); + } + + private selectedInstitutionIds(): string[] { + return this.selectedInstitutions + .map((institution) => institution.id) + .filter((id): id is string => !!id); + } + + private selectedTopicIds(): string[] { + return this.selectedTopics + .map((topic) => topic.id) + .filter((id): id is string => !!id); + } + + private updatePublicationFilterQueryParams( + overrides: Record | null>, + ): void { + const filters = this.filters(); + const institutionIds = this.selectedInstitutionIds(); + const institutionNames = this.selectedInstitutions + .map((institution) => institution.display_name) + .filter((name): name is string => !!name); + const topicIds = this.selectedTopicIds(); + const topicNames = this.selectedTopics + .map((topic) => topic.display_name) + .filter((name): name is string => !!name); + + void this.router.navigate([], { + relativeTo: this.route, + queryParams: { + [this.queryParamKeys.years]: filters.publicationYears.length + ? filters.publicationYears + : null, + [this.queryParamKeys.types]: filters.types.length ? filters.types : null, + [this.queryParamKeys.languages]: filters.languages.length + ? filters.languages + : null, + [this.queryParamKeys.institutionIds]: institutionIds.length + ? institutionIds + : null, + [this.queryParamKeys.institutionNames]: institutionNames.length + ? institutionNames + : null, + [this.queryParamKeys.topicIds]: topicIds.length ? topicIds : null, + [this.queryParamKeys.topicNames]: topicNames.length ? topicNames : null, + ...overrides, + }, + queryParamsHandling: 'merge', + }); + } + + private parsePublicationFilterQueryParams( + queryParams: ParamMap, + ): PublicationFilterQueryState { + const institutionIds = queryParams.getAll(this.queryParamKeys.institutionIds); + const institutionNames = queryParams.getAll(this.queryParamKeys.institutionNames); + const topicIds = queryParams.getAll(this.queryParamKeys.topicIds); + const topicNames = queryParams.getAll(this.queryParamKeys.topicNames); + + return { + pageIndex: + this.parsePositiveInteger(queryParams.get(this.queryParamKeys.page), 1) - 1, + pageSize: this.parsePositiveInteger( + queryParams.get(this.queryParamKeys.pageSize), + this.paginationService.selection, + ), + publicationYears: this.parseNumberParams( + queryParams.getAll(this.queryParamKeys.years), + ), + types: this.parseStringParams(queryParams.getAll(this.queryParamKeys.types)), + languages: this.parseStringParams( + queryParams.getAll(this.queryParamKeys.languages), + ), + institutions: institutionIds + .filter(Boolean) + .map((id, index) => ({ + id, + display_name: institutionNames[index] || id, + })), + topics: topicIds + .filter(Boolean) + .map((id, index) => ({ + id, + display_name: topicNames[index] || id, + })), + }; + } + + private applyPublicationFilterQueryState( + queryState: PublicationFilterQueryState, + ): void { + this.currentPageIndex = queryState.pageIndex; + this.paginationService.selection = queryState.pageSize; + this.selectedInstitutions = queryState.institutions; + this.selectedTopics = queryState.topics; + this.filterForm.setValue( + { + publicationYears: queryState.publicationYears, + types: queryState.types, + languages: queryState.languages, + }, + { emitEvent: false }, + ); + } + + private parseStringParams(values: string[]): string[] { + return values.map((value) => value.trim()).filter(Boolean); + } + + private parseNumberParams(values: string[]): number[] { + return values + .map((value) => Number(value)) + .filter((value) => Number.isInteger(value)); + } + + private parsePositiveInteger(value: string | null, fallback: number): number { + const parsedValue = Number(value); + if (!Number.isInteger(parsedValue) || parsedValue < 1) { + return fallback; + } + + return parsedValue; + } + private createPublicationYearOptions(): number[] { const currentYear = new Date().getFullYear(); return Array.from({ length: 90 }, (_, index) => currentYear - index); diff --git a/webapp/src/app/modules/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/styles.scss b/webapp/src/styles.scss index 17b951de..271f28ac 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; } * {