diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 4995cf61..0d9f0ff8 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -46,6 +46,24 @@ class InstitutionsSearchClient: return institution + async def get_eu_organisation_id_by_oa_institution_id( + self, raw_institution_id: str + ) -> Optional[str]: + """Retrieves the corresponding EU organisation ID for a given OpenAlex institution ID, if available. + + Args: + raw_institution_id (str): The raw OpenAlex institution ID for which to retrieve the EU organisation ID. + + Returns: + Optional[str]: The corresponding EU organisation ID, or None if not found. + """ + raw_institution_id = raw_institution_id.upper() + cache = { + "I62318514": "999843312", + } + # TODO: Implement actual retrieval of RCN from Elasticsearch or another source instead of using a hardcoded cache. + return cache.get(raw_institution_id) + def get_institutions_by_name( self, name: str, @@ -190,55 +208,37 @@ class InstitutionsSearchClient: if query_text: stripped = query_text.strip() - must.append( - { - "bool": { - "should": [ - # Fast prefix matching via search_as_you_type shingles - { - "multi_match": { - "query": stripped, - "type": "bool_prefix", - "fields": [ - "display_name.search", - "display_name.search._2gram", - "display_name.search._3gram", - "display_name_alternatives.search", - "display_name_alternatives.search._2gram", - ], - "boost": 2, - } - }, - # Exact acronym match — high confidence signal - { - "term": { - "display_name_acronyms.keyword": { - "value": stripped.upper(), - "boost": 10, - } - } - }, - # Fuzzy fallback for typos (only worth it for longer input) - *( - [ - { - "match": { - "display_name": { - "query": stripped, - "fuzziness": "AUTO", - "boost": 1, - } - } - } - ] - if len(stripped) >= 4 - else [] - ), - ], - "minimum_should_match": 1, + must.append({ + "bool": { + "should": [ + { + "wildcard": { + "display_name.keyword": { + "value": f"*{stripped}*", + "boost": 2 + } + } + }, + { + "wildcard": { + "display_name_alternatives.keyword": { + "value": f"*{stripped}*", + "boost": 2 + } + } + }, + { + "wildcard": { + "display_name_acronyms.keyword": { + "value": f"*{stripped.upper()}*", + "boost": 10 + } + } } - } - ) + ], + "minimum_should_match": 1 + } + }) filter_queries = [] diff --git a/service/src/main/inse/institutions/router.py b/service/src/main/inse/institutions/router.py index c5ae252c..423281c0 100644 --- a/service/src/main/inse/institutions/router.py +++ b/service/src/main/inse/institutions/router.py @@ -81,28 +81,6 @@ async def search_institutions_by_name( ) -@router.get( - "/{id}", - summary="Returns a single institution by ID.", - description="Returns a single institution by its OpenAlex ID.", - operation_id="getInstitutionById", - responses={ - status.HTTP_200_OK: { - "description": "Successful Response", - "model": Institution, - }, - status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, - }, -) -async def get_institution( - id: str, - client: Annotated[ - InstitutionsSearchClient, Depends(get_institutions_search_client) - ], -) -> Institution: - return await logic.get_institution_by_id(raw_institution_id=id, client=client) - - @router.get( "/autocomplete", operation_id="autocompleteInstitutions", @@ -142,6 +120,28 @@ async def autocomplete_institutions( client=client, ) +@router.get( + "/{id}", + summary="Returns a single institution by ID.", + description="Returns a single institution by its OpenAlex ID.", + operation_id="getInstitutionById", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": Institution, + }, + status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + }, +) +async def get_institution( + id: str, + client: Annotated[ + InstitutionsSearchClient, Depends(get_institutions_search_client) + ], +) -> Institution: + return await logic.get_institution_by_id(raw_institution_id=id, client=client) + + @router.get( "", diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 93fed522..a91e13ad 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -16,15 +16,15 @@ from inse.collaboration_network.router import router as collaboration_network_ro from inse.company_connections.service import router as company_connections_router from inse.exceptions import NotFoundException from inse.funders.service import router as funders_service_router -from inse.institutions.router import router as institutions_router - +from inse.projects.router import router as projects_router +from inse.university_ranking.router import router as university_ranking_router # caching from inse.middleware.etag_cache import ETagCacheMiddleware from inse.persons.service import router as persons_service_router from inse.projects.router import router as projects_router from inse.topics.service import router as topics_service_router from inse.works.service import router as works_service_router - +from inse.institutions.router import router as institutions_router from . import config from .account.service import router as account_router from .service import router as service_router @@ -51,6 +51,7 @@ app.include_router(funders_service_router) app.include_router(company_connections_router) app.include_router(service_router) app.include_router(account_router) +app.include_router(university_ranking_router) app.include_router(projects_router) app.add_middleware( diff --git a/service/src/main/inse/models/bund_project_details.py b/service/src/main/inse/models/bund_project_details.py new file mode 100644 index 00000000..d7c4baf1 --- /dev/null +++ b/service/src/main/inse/models/bund_project_details.py @@ -0,0 +1,337 @@ +# coding: utf-8 + +""" + Bund Project Clean Model + + Summary model that consolidates scattered fields from the raw projects_bund index + into clean, semantic field names with proper native Python types. +""" + +from datetime import date, datetime +from typing import Optional, List, Set, Any + +from pydantic import BaseModel, ConfigDict, Field, field_validator + + +class BundProjectDetails(BaseModel): + """ + Clean summary model for a Bund (federal) project, consolidating all fields + into semantic English names with proper native types. + """ + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + ) + + # Core identifiers + id: str = Field(description="The ID of the Bund project") + funding_reference: Optional[str] = Field( + default=None, + + description="The funding reference number (Förderkennzeichen)", + ) + + # Project metadata + title: Optional[str] = Field( + default=None, + + description="The project topic/title", + ) + description: Optional[str] = Field( + default=None, + + description="Plain text description of the performance plan classification", + ) + joint_project: Optional[str] = Field( + default=None, + + description="Parent joint project if this is a sub-project", + ) + + # Funding information + funding_type: Optional[str] = Field( + default=None, + + description="Type of funding (Förderart)", + ) + funding_profile: Optional[str] = Field( + default=None, + + description="Funding profile (Förderprofil)", + ) + funding_amount: Optional[float] = Field( + default=None, + + description="Funding amount in EUR", + ) + funding_start_date: Optional[date] = Field( + default=None, + description="Funding start date", + ) + funding_end_date: Optional[date] = Field( + default=None, + description="Funding end date", + ) + duration: Optional[str] = Field( + default=None, + + description="Project duration (Laufzeit)", + ) + + # Classification + performance_plan_code: Optional[str] = Field( + default=None, + + description="Performance plan classification code", + ) + performance_plan_fullname: Optional[str] = Field( + default=None, + + description="Full name of the performance plan classification", + ) + + # Organizational + executing_agency: Optional[str] = Field( + default=None, + + description="Executing agency", + ) + funding_recipient: Optional[str] = Field( + default=None, + + description="Funding recipient", + ) + project_agency: Optional[str] = Field( + default=None, + + description="Project management agency", + ) + project_agency_fullname: Optional[str] = Field( + default=None, + + description="Full name of the project management agency", + ) + + # Government hierarchy + department: Optional[str] = Field( + default=None, + + description="Government department code", + ) + department_fullname: Optional[str] = Field( + default=None, + + description="Full name of the government department", + ) + division: Optional[str] = Field( + default=None, + + description="Division/unit reference", + ) + + # Location + location: Optional[str] = Field( + default=None, + + description="Location/city", + ) + municipality: Optional[str] = Field( + default=None, + + description="City/Municipality", + ) + state: Optional[str] = Field( + default=None, + + description="Federal state", + ) + country: Optional[str] = Field( + default=None, + + description="Country", + ) + municipality_code: Optional[str] = Field( + default=None, + + description="Municipality code", + ) + + # Publication + publication_date: Optional[str] = Field( + default=None, + + description="Publication date", + ) + + # Additional + is_new: Optional[bool] = Field( + default=None, + + description="Flag indicating if the project is new", + ) + record_date: Optional[str] = Field( + default=None, + + description="Record date", + ) + unix_timestamp: Optional[int] = Field( + default=None, + description="Unix timestamp of the record", + ) + + # Unified lists for aggregation + associated_persons: List[str] = Field( + default_factory=list, + description="All persons associated with the Bund project (from nested Arb object)", + ) + institutions: List[str] = Field( + default_factory=list, + description="All institutions associated with the Bund project", + ) + + # --- Validators for type coercion --- + + @field_validator("funding_amount", mode="before") + @classmethod + def parse_funding_amount(cls, v: Any) -> Optional[float]: + """Parse funding amount from string or number.""" + if v is None: + return None + if isinstance(v, (int, float)): + return float(v) + if isinstance(v, str): + # Remove thousands separators and trim + cleaned = v.replace(".", "").replace(",", ".").strip() + try: + return float(cleaned) + except ValueError: + return None + return None + + @field_validator("funding_start_date", "funding_end_date", mode="before") + @classmethod + def parse_german_date(cls, v: Any) -> Optional[date]: + """Parse date from German format (dd.MM.yyyy) or date/datetime object.""" + if v is None: + return None + if isinstance(v, datetime): + return v.date() + if isinstance(v, date): + return v + if isinstance(v, str): + v = v.strip() + # Try German format first: dd.MM.yyyy + try: + return datetime.strptime(v, "%d.%m.%Y").date() + except ValueError: + pass + # Try ISO format: yyyy-MM-dd + try: + return datetime.strptime(v, "%Y-%m-%d").date() + except ValueError: + pass + # Try with time component + try: + return datetime.fromisoformat(v).date() + except ValueError: + pass + return None + + @field_validator("is_new", mode="before") + @classmethod + def parse_is_new(cls, v: Any) -> Optional[bool]: + """Parse is_new from bool or string.""" + if v is None: + return None + if isinstance(v, bool): + return v + if isinstance(v, str): + return v.lower() in ("true", "1", "yes", "ja") + if isinstance(v, (int, float)): + return bool(v) + return None + + @field_validator("unix_timestamp", mode="before") + @classmethod + def parse_unix_timestamp(cls, v: Any) -> Optional[int]: + """Parse unix timestamp from int, float, or string.""" + if v is None: + return None + if isinstance(v, (int, float)): + return int(v) + if isinstance(v, str): + try: + return int(v) + except ValueError: + return None + return None + + @classmethod + def from_elastic_hit(cls, hit: dict) -> "BundProject": + """ + Create a BundProject from an Elasticsearch hit, consolidating all fields. + """ + source = hit.get("_source", {}) + + # --- Extract persons from nested Arb object --- + persons: Set[str] = set() + arb = source.get("Arb") + if arb and isinstance(arb, dict): + for key, value in arb.items(): + if isinstance(value, str) and value.strip(): + for person in value.split(";"): + person = person.strip() + if person: + persons.add(person) + + # --- Extract institutions --- + institutions: Set[str] = set() + inst_fields = [ + "Ausführende Stelle", + "Zuwendungsempfänger", + "Projektträger", + ] + for field in inst_fields: + if field in source and source[field]: + for inst in source[field].split(";"): + inst = inst.strip() + if inst: + institutions.add(inst) + + if source.get("PT_fullname"): + institutions.add(source["PT_fullname"].strip()) + + return cls( + id=hit["_id"], + funding_reference=source.get("Förderkennzeichen"), + title=source.get("Thema"), + description=source.get("Klartext Leistungsplansystematik"), + joint_project=source.get("Verbundprojekt"), + funding_type=source.get("Förderart"), + funding_profile=source.get("Förderprofil"), + funding_amount=source.get("Fördersumme"), + funding_start_date=source.get("funding_start"), + funding_end_date=source.get("funding_end"), + duration=source.get("Laufzeit"), + performance_plan_code=source.get("Leistungsplansystematik"), + performance_plan_fullname=source.get("Leistungsplansystematik_fullname"), + executing_agency=source.get("Ausführende Stelle"), + funding_recipient=source.get("Zuwendungsempfänger"), + project_agency=source.get("Projektträger"), + project_agency_fullname=source.get("PT_fullname"), + department=source.get("Ressort"), + department_fullname=source.get("Ressort_fullname"), + division=source.get("Referat"), + location=source.get("Ort"), + municipality=source.get("Stadt/Gemeinde"), + state=source.get("Bundesland"), + country=source.get("Staat"), + municipality_code=source.get("Gemeindekennziffer"), + publication_date=source.get("Publikationsdatum"), + is_new=source.get("new"), + record_date=source.get("datum"), + unix_timestamp=source.get("unix_timestamp"), + associated_persons=sorted(persons), + institutions=sorted(institutions), + ) \ No newline at end of file diff --git a/service/src/main/inse/models/cordis_eu_project.py b/service/src/main/inse/models/cordis_eu_project.py new file mode 100644 index 00000000..557dfd57 --- /dev/null +++ b/service/src/main/inse/models/cordis_eu_project.py @@ -0,0 +1,62 @@ +from datetime import datetime +from typing import Optional, List, Union +from pydantic import BaseModel, Field + + +class CordisEuProject(BaseModel): + id: str = Field( + description="Unique identifier for the project, typically the CORDIS ID" + ) + rcn: Optional[str] = Field( + None, description="Research and Innovation project number (CORDIS RCN)" + ) + acronym: Optional[str] = Field(None, description="Acronym for the project") + title: Optional[str] = Field(None, description="Title of the project") + objective: Optional[str] = Field(None, description="Objective of the project") + + frameworkProgramme: Optional[str] = Field( + None, description="Framework Programme under which the project was funded" + ) + fundingScheme: Optional[str] = Field( + None, description="Funding scheme of the project" + ) + legalBasis: Optional[str] = Field( + None, description="Legal basis for the project funding" + ) + masterCall: Optional[str] = Field( + None, description="Master call identifier if applicable" + ) + subCall: Optional[str] = Field( + None, description="Sub call identifier if applicable" + ) + topics: Optional[Union[str, List[str]]] = ( + None # Elastic keyword can map to a single string or list of strings + ) + nature: Optional[str] = Field(None, description="Nature of the project") + status: Optional[str] = Field(None, description="Status of the project") + + ecMaxContribution: Optional[float] = Field( + None, description="Maximum European Commission contribution" + ) + totalCost: Optional[float] = Field(None, description="Total cost of the project") + + startDate: Optional[datetime] = Field(None, description="Start date of the project") + endDate: Optional[datetime] = Field(None, description="End date of the project") + ecSignatureDate: Optional[datetime] = Field( + None, description="Date of the European Commission signature" + ) + contentUpdateDate: Optional[datetime] = Field( + None, description="Date when the project content was last updated" + ) + + grantDoi: Optional[str] = Field(None, description="DOI for the project grant") + humanValidated: Optional[bool] = Field( + None, + description="Indicates if the project information has been human validated", + ) + keywords: Optional[Union[str, List[str]]] = Field( + None, description="Keywords associated with the project" + ) + + class Config: + populate_by_name = True diff --git a/service/src/main/inse/models/dfg_project_details.py b/service/src/main/inse/models/dfg_project_details.py new file mode 100644 index 00000000..96ee5dc9 --- /dev/null +++ b/service/src/main/inse/models/dfg_project_details.py @@ -0,0 +1,275 @@ +# coding: utf-8 + +""" + DFG Project Clean Model + + Summary model that consolidates all scattered person and institution fields + from the raw projects_dfg_all index into clean, unified lists. +""" + +from typing import Optional, List, Set + +from pydantic import BaseModel, ConfigDict, Field + + +class DfgProjectDetails(BaseModel): + """ + Clean summary model for a DFG project, consolidating all person roles + and institution references into unified lists. + """ + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + ) + + id: str = Field(description="The ID of the DFG project") + link: Optional[str] = Field(default=None, description="The link to the DFG project") + title: Optional[str] = Field( + default=None, description="The title of the DFG project" + ) + description: Optional[str] = Field( + default=None, description="The description of the DFG project" + ) + + project_identifier: Optional[str] = Field( + default=None, + description="The project identifier of the DFG project", + ) + + funding_start_date: Optional[str] = Field( + default=None, description="The funding start date of the DFG project" + ) + funding_end_date: Optional[str] = Field( + default=None, description="The funding end date of the DFG project" + ) + + dfg_procedure: Optional[str] = Field( + default=None, description="The DFG procedure" + ) + subject_area: Optional[str] = Field( + default=None, + description="The subject area classification", + ) + funding_type: Optional[str] = Field( + default=None, description="The type of funding" + ) + international_reference: Optional[str] = Field( + default=None, + + description="International reference", + ) + + website: Optional[str] = Field( + default=None, description="The project website" + ) + + # Unified person list: all person names from any role + associated_persons: List[str] = Field( + default_factory=list, + description="All persons associated with the DFG project (any role)", + ) + + # Unified institution list: all institutions involved + institutions: List[str] = Field( + default_factory=list, + description="All institutions associated with the DFG project", + ) + + # Sub-project reference + subproject_of: Optional[str] = Field( + default=None, + description="Parent project this is a sub-project of", + ) + + @classmethod + def from_elastic_hit(cls, hit: dict) -> "DfgProjectDetails": + """ + Create a DfgProject from an Elasticsearch hit, consolidating all + person and institution fields into unified lists. + """ + + source = hit.get("_source", {}) + + associated_persons: Set[str] = set() + institutions: Set[str] = set() + + # --- Collect all persons from every person-related field --- + + # Applicant fields + _add_persons(source, associated_persons, "Antragsteller") # semicolon-separated + _add_person(source, associated_persons, "Antragstellerin") + _add_persons( + source, associated_persons, "Antragstellerinnen" + ) # semicolon-separated + _add_persons( + source, associated_persons, "Antragstellerinnen / Antragsteller" + ) # semicolon-separated + + # Co-applicant fields + _add_persons(source, associated_persons, "Mitantragsteller") + _add_person(source, associated_persons, "Mitantragstellerin") + _add_persons(source, associated_persons, "Mitantragstellerinnen") + _add_persons( + source, associated_persons, "Mitantragstellerinnen / Mitantragsteller" + ) + + # Former applicant fields + _add_persons(source, associated_persons, "Ehemalige Antragsteller") + _add_person(source, associated_persons, "Ehemalige Antragstellerin") + _add_persons(source, associated_persons, "Ehemalige Antragstellerinnen") + _add_persons( + source, + associated_persons, + "Ehemalige Antragstellerinnen / Ehemalige Antragsteller", + ) + _add_person(source, associated_persons, "Ehemaliger Antragsteller") + + # Speaker / coordinator fields + _add_person(source, associated_persons, "Sprecher") + _add_person(source, associated_persons, "Sprecherin") + _add_persons(source, associated_persons, "Sprecherinnen") + _add_persons(source, associated_persons, "Sprecherinnen / Sprecher") + _add_person(source, associated_persons, "Co-Sprecher") + _add_persons(source, associated_persons, "Co-Sprecherinnen / Co-Sprecher") + + # IGK partner speaker fields + _add_person(source, associated_persons, "Sprecher (IGK-Partner)") + _add_person(source, associated_persons, "Sprecherin (IGK-Partner)") + _add_persons( + source, + associated_persons, + "Sprecherinnen (IGK-Partner) / Sprecher (IGK-Partner)", + ) + + # Leader fields + _add_person(source, associated_persons, "Leiter") + _add_person(source, associated_persons, "Leiterin") + _add_persons(source, associated_persons, "Leiterinnen") + _add_persons(source, associated_persons, "Leiterinnen / Leiter") + + # Sub-project leader fields + _add_persons(source, associated_persons, "Teilprojektleiter") + _add_person(source, associated_persons, "Teilprojektleiterin") + _add_persons(source, associated_persons, "Teilprojektleiterinnen") + _add_persons( + source, associated_persons, "Teilprojektleiterinnen / Teilprojektleiter" + ) + + # Participating scientist fields + _add_persons(source, associated_persons, "beteiligte Wissenschaftler") + _add_person(source, associated_persons, "beteiligte Wissenschaftlerin") + _add_persons(source, associated_persons, "beteiligte Wissenschaftlerinnen") + _add_persons( + source, + associated_persons, + "beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler", + ) + _add_person(source, associated_persons, "beteiligter Wissenschaftler") + + # Participating person fields + _add_person(source, associated_persons, "Beteiligte Person") + _add_persons(source, associated_persons, "Beteiligte Personen") + + # Host fields (for guest researchers) + _add_person(source, associated_persons, "Gastgeber") + _add_person(source, associated_persons, "Gastgeberin") + _add_persons(source, associated_persons, "Gastgeberinnen") + _add_persons(source, associated_persons, "Gastgeberinnen / Gastgeber") + + # Cooperation partner fields + _add_person(source, associated_persons, "Kooperationspartner") + _add_person(source, associated_persons, "Kooperationspartnerin") + _add_persons(source, associated_persons, "Kooperationspartnerinnen") + _add_persons( + source, associated_persons, "Kooperationspartnerinnen / Kooperationspartner" + ) + + # Co-responsible fields + _add_person(source, associated_persons, "Mitverantwortlich") + _add_person(source, associated_persons, "Mitverantwortlich(e)") + _add_persons(source, associated_persons, "Mitverantwortliche") + + # Application partner + _add_person(source, associated_persons, "Anwendungspartner") + + # Foreign co-applicant fields + _add_persons(source, associated_persons, "ausländische Mitantragsteller") + _add_person(source, associated_persons, "ausländischer Mitantragsteller") + + # Person creator (from nested fields) + if "person_creater_name" in source and source["person_creater_name"]: + associated_persons.add(source["person_creater_name"].strip()) + + # Deputy (stellvertr) - nested object + stellvertr = source.get("stellvertr") + if stellvertr and isinstance(stellvertr, dict): + for field in ["stellvertreter", "stellvertreterin"]: + if field in stellvertr and stellvertr[field]: + associated_persons.add(stellvertr[field].strip()) + + # --- Collect all institutions --- + + _add_institution(source, institutions, "Antragstellende Institution") + _add_institution(source, institutions, "Mitantragstellende Institution") + _add_institution(source, institutions, "Beteiligte Einrichtung") + _add_institution(source, institutions, "Beteiligte Hochschule") + _add_institution(source, institutions, "Beteiligte Institution") + _add_institution(source, institutions, "IGK-Partnerinstitution") + _add_institution(source, institutions, "Partnerorganisation") + _add_institution(source, institutions, "Unternehmen") + + # Foreign institution (nested object) + auslaend = source.get("ausländ") + if auslaend and isinstance(auslaend, dict): + for field in [ + "auslaendischeInstitution", + "auslaendischeInstitution2", + "auslaendischesUnternehmen", + "auslaendischesUnternehmen2", + ]: + if field in auslaend and auslaend[field]: + institutions.add(auslaend[field].strip()) + return cls( + id=hit["_id"], + link=source.get("link"), + title=source.get("title"), + description=source.get("description"), + project_identifier=source.get("Projektkennung"), + funding_start_date=source.get("funding_start"), + funding_end_date=source.get("funding_end"), + dfg_procedure=source.get("DFG-Verfahren"), + subject_area=source.get("Fachliche Zuordnung"), + funding_type=source.get("Förderung"), + international_reference=source.get("Internationaler Bezug"), + website=source.get("Webseite"), + associated_persons=sorted(associated_persons), # sorted for consistency + institutions=sorted(institutions), + subproject_of=source.get("Teilprojekt zu"), + ) + + +# --- Helper functions for parsing source fields --- + +def _add_person(source: dict, persons: Set[str], field: str) -> None: + """Add a single person value from a field.""" + if field in source and source[field]: + value = source[field].strip() + if value: + persons.add(value) + + +def _add_persons(source: dict, persons: Set[str], field: str) -> None: + """Add persons from a semicolon-separated field.""" + if field in source and source[field]: + for person in source[field].split(";"): + cleaned = person.strip() + if cleaned: + persons.add(cleaned) + + +def _add_institution(source: dict, institutions: Set[str], field: str) -> None: + """Add a single institution value from a field.""" + if field in source and source[field]: + value = source[field].strip() + if value: + institutions.add(value) \ No newline at end of file diff --git a/service/src/main/inse/models/openalex/institution.py b/service/src/main/inse/models/openalex/institution.py index 6121af94..1d1062b5 100644 --- a/service/src/main/inse/models/openalex/institution.py +++ b/service/src/main/inse/models/openalex/institution.py @@ -33,7 +33,7 @@ class Institution(BaseModel): """ A university, research organization, or other affiliation """ # noqa: E501 - id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this institution.") + id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this institution.", json_schema_extra={"examples": ["https://openalex.org/I27837315"]}) ror: Optional[StrictStr] = Field(default=None, description="The ROR ID for this institution. This is the Canonical External ID for institutions.") display_name: Optional[StrictStr] = Field(default=None, description="The primary name of the institution.") country_code: Optional[StrictStr] = Field(default=None, description="ISO two-letter country code where this institution is located.") @@ -55,20 +55,13 @@ class Institution(BaseModel): updated_date: Optional[datetime] = Field(default=None, description="When this institution was last updated (ISO 8601 datetime).") __properties: ClassVar[List[str]] = ["id", "ror", "display_name", "country_code", "type", "homepage_url", "image_url", "image_thumbnail_url", "display_name_acronyms", "display_name_alternatives", "works_count", "cited_by_count", "summary_stats", "geo", "lineage", "ids", "counts_by_year", "works_api_url", "created_date", "updated_date"] - @field_validator('created_date', mode='before') - @classmethod - def normalize_created_date(cls, v: Any) -> Any: - if isinstance(v, str) and len(v) > 10: - return v[:10] - return v - @field_validator('type') def type_validate_enum(cls, value): """Validates the enum""" if value is None: return value - if value not in set(['education','funder', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']): + if value not in set(['education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']): raise ValueError("must be one of enum values ('education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other')") return value @@ -161,3 +154,5 @@ class Institution(BaseModel): "updated_date": obj.get("updated_date") }) return _obj + + diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index 8631a25a..ae05256b 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -1,9 +1,31 @@ -from typing import List, Literal, Optional +from datetime import date +import datetime +from enum import StrEnum +from typing import List, Optional -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, field_validator from inse.models.bund_project import BundProject from inse.models.eu_project import EuProject +from inse.models.cordis_eu_project import CordisEuProject + + +class ProjectType(StrEnum): + BUND = "bund" + EU = "eu" + DFG = "dfg" + + +class ProjectsSortBy(StrEnum): + TITLE = "title" + FUNDING_START = "funding_start" + FUNDING_END = "funding_end" + FUNDING_AMOUNT = "funding_amount" + + +class SortDirection(StrEnum): + ASC = "asc" + DESC = "desc" class Page(BaseModel): @@ -76,7 +98,7 @@ class DfgProjectPage(Page): class InstitutionFunderSummary(BaseModel): - type: Literal["bund", "eu", "dfg"] = Field( + type: ProjectType = Field( description="The type of funding data (e.g., 'bund', 'eu', 'dfg')." ) funding_per_year: dict = Field( @@ -87,3 +109,119 @@ class InstitutionFunderSummary(BaseModel): default=0.0, description="The average annual funding over the continuous period covered by the data.", ) + + +class ProjectsFilteringProperties(BaseModel): + project_type: ProjectType = Field(description="The type of projects to filter by.") + page: int = Field(description="The page number for pagination.") + size: int = Field(description="The page size for pagination.") + raw_oa_institution_id: Optional[str] = Field( + default=None, description="The raw OA institution ID to filter by." + ) + query: Optional[str] = Field( + default=None, description="The query string to filter projects by." + ) + sort_by: ProjectsSortBy = Field( + default=ProjectsSortBy.TITLE, description="The field to sort by." + ) + sort_direction: SortDirection = Field( + default=SortDirection.ASC, description="The sort direction (asc or desc)." + ) + + +class CordisEuProjectPage(Page): + elements: List[CordisEuProject] = Field( + default_factory=list, description="The CORDIS EU projects on this page." + ) + + +class FundingProject(BaseModel): + type: ProjectType = Field( + description="The type of the project.", + examples=[ProjectType.BUND, ProjectType.EU, ProjectType.DFG], + ) + id: str = Field(description="The unique identifier of the project.") + title: Optional[str] = Field(default=None, description="The title of the project.") + start_date: Optional[date] = Field( + default=None, description="The funding start date of the project." + ) + end_date: Optional[date] = Field( + default=None, description="The funding end date of the project." + ) + funding_amount: Optional[float] = Field( + default=None, description="The total funding amount for the project." + ) + + @field_validator("start_date", "end_date", mode="before") + @classmethod + def parse_all_date_formats(cls, value): + if isinstance(value, str): + value = value.strip() + + if len(value) == 4 and value.isdigit(): + return f"{value}-01-01" + + if "." in value: + return datetime.datetime.strptime(value, "%d.%m.%Y").date() + + return value + + return value + + @classmethod + def from_cordis_projects_hit(cls, hit: dict) -> "FundingProject": + if not hit.get("_index", "").startswith("cordis_eu_") and not hit.get( + "_index", "" + ).endswith("_projects"): + raise ValueError( + "The provided hit does not belong to an index starting with 'cordis_eu_' and ending with '_projects'." + ) + + source = hit.get("_source", {}) + return cls( + type=ProjectType.EU, + id=hit.get("_id", ""), + title=source.get("title"), + start_date=source.get("startDate"), + end_date=source.get("endDate"), + funding_amount=source.get("ecMacContribution"), + ) + + @classmethod + def from_bund_projects_hit(cls, hit: dict) -> "FundingProject": + if hit.get("_index") != "projects_bund_v1": + raise ValueError( + "The provided hit does not belong to the 'projects_bund_v1' index." + ) + + source = hit.get("_source", {}) + return cls( + type=ProjectType.BUND, + id=source.get("Förderkennzeichen", ""), + title=source.get("Thema"), + start_date=source.get("funding_start"), + end_date=source.get("funding_end"), + funding_amount=source.get("Fördersumme"), + ) + + @classmethod + def from_dfg_projects_hit(cls, hit: dict) -> "FundingProject": + if hit.get("_index") != "projects_dfg_all": + raise ValueError( + "The provided hit does not belong to the 'projects_dfg_all' index." + ) + + source = hit.get("_source", {}) + return cls( + type=ProjectType.DFG, + id=hit.get("_id", ""), + title=source.get("title"), + start_date=source.get("funding_start"), + end_date=source.get("funding_end"), + ) + + +class FundingProjectPage(Page): + elements: List[FundingProject] = Field( + default_factory=list, description="The funding projects on this page." + ) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index d38304d3..8f8c93cd 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -1,6 +1,6 @@ import json import logging -from typing import Any, Dict, List, Optional +from typing import Any, Dict, List, Literal, Optional, Set import httpx @@ -8,11 +8,21 @@ from inse.config import get_settings from inse.models.bund_project import BundProject from inse.projects.model import ( BundProjectPage, + CordisEuProjectPage, DfgProjectPage, DfgProjectSummary, EuProjectPage, + FundingProject, + FundingProjectPage, + ProjectType, + ProjectsFilteringProperties, + ProjectsSortBy, + SortDirection, ) from inse.models.eu_project import EuProject +from inse.models.dfg_project_details import DfgProjectDetails +from inse.models.bund_project_details import BundProjectDetails +from inse.models.cordis_eu_project import CordisEuProject settings = get_settings() @@ -97,10 +107,12 @@ class ProjectsSearchClient: "Authorization": f"ApiKey {self.api_key}", } - async def make_search_request(self, query: dict) -> dict: + async def make_search_request( + self, query: dict, index: Optional[str] = None + ) -> dict: async with httpx.AsyncClient() as client: response = await client.post( - f"{self.base_url}/{self.index}/_search", + f"{self.base_url}/{index or self.index}/_search", json=query, headers=self.headers, ) @@ -128,15 +140,25 @@ class BundProjectsSearchClient(ProjectsSearchClient): api_key=settings.elasticsearch_inse_api_key, ) - def bund_projects_query( + def _bund_projects_sort_by_field(self, sort_by: ProjectsSortBy) -> str: + if sort_by == ProjectsSortBy.TITLE: + return "Thema.keyword" + elif sort_by == ProjectsSortBy.FUNDING_START: + return "funding_start" + elif sort_by == ProjectsSortBy.FUNDING_END: + return "funding_end" + elif sort_by == ProjectsSortBy.FUNDING_AMOUNT: + return "Fördersumme" + + def _bund_projects_query( self, page: int, size: int, id: Optional[str] = None, institution_names: List[str] = [], topic: Optional[str] = None, - sort_by: str = "topic", - sort_direction: str = "asc", + sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, + sort_direction: SortDirection = SortDirection.ASC, ) -> dict: from_ = page * size query: Dict[str, Any] = {"size": size, "from": from_, "query": {}} @@ -182,19 +204,9 @@ class BundProjectsSearchClient(ProjectsSearchClient): else: query["query"] = {"match_all": {}} - sort_by = sort_by.strip() - if sort_by == "topic": - sort_by = "Thema.keyword" - elif sort_by == "department": - sort_by = "Ressort_fullname.keyword" - elif sort_by == "grant_amount": - sort_by = "Fördersumme" - - sort_direction = sort_direction.strip().lower() - if sort_direction not in ["asc", "desc"]: - sort_direction = "asc" - - query["sort"] = [{f"{sort_by}": {"order": sort_direction}}] + query["sort"] = [ + {self._bund_projects_sort_by_field(sort_by): {"order": sort_direction}} + ] query_str = json.dumps(query, indent=2) logger.debug(f"Constructed Bund project query: {query_str}") @@ -221,10 +233,10 @@ class BundProjectsSearchClient(ProjectsSearchClient): id: Optional[str] = None, institution_names: List[str] = [], topic: Optional[str] = None, - sort_by: str = "topic", - sort_direction: str = "asc", + sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, + sort_direction: SortDirection = SortDirection.ASC, ) -> BundProjectPage: - query = self.bund_projects_query( + query = self._bund_projects_query( page=page, size=size, id=id, @@ -236,6 +248,42 @@ class BundProjectsSearchClient(ProjectsSearchClient): response = await self.make_search_request(query) return self.response_to_bund_project_page(response, page, size) + async def get_bund_projects_by_institution_name( + self, + institution_names: List[str], + page: int, + size: int, + sort_by: str = "topic", + sort_direction: str = "asc", + ) -> BundProjectPage: + query = self.bund_projects_query( + page=page, + size=size, + institution_names=institution_names, + sort_by=sort_by, + sort_direction=sort_direction, + ) + response = await self.make_search_request(query) + return self.response_to_bund_project_page(response, page, size) + + async def get_bund_project_by_id( + self, project_id: str + ) -> Optional[BundProjectDetails]: + + query = { + "query": {"term": {"Förderkennzeichen.keyword": {"value": project_id}}}, + "_source": True, + } + + response = await self.make_search_request(query) + hits = response.get("hits", {}).get("hits", []) + if hits: + hit = hits[0] + print(hit) + details = BundProjectDetails.from_elastic_hit(hit=hit) + return details + return None + class EuProjectsSearchClient(ProjectsSearchClient): def __init__(self): @@ -338,8 +386,149 @@ class EuProjectsSearchClient(ProjectsSearchClient): return query + def _eu_projects_id_body(self, eu_organisation_id: str) -> Dict[str, Any]: + body: Dict[str, Any] = { + "size": 0, + "query": { + "bool": {"filter": [{"term": {"organisationID": eu_organisation_id}}]} + }, + "aggs": { + "associated_project_ids": { + "terms": {"field": "projectID", "size": 10000} + } + }, + } + + query_str = json.dumps(body, indent=2) + logger.debug(f"Constructed EU project ID query: {query_str}") + return body + + def _eu_projects_id_response_to_ids(self, response: Dict[str, Any]) -> List[str]: + """Converts the Elasticsearch aggregation response to a list of project IDs. + + Args: + response (Dict[str, Any]): The Elasticsearch aggregation response. + + Returns: + List[str]: A list of project IDs. + """ + buckets = ( + response.get("aggregations", {}) + .get("associated_project_ids", {}) + .get("buckets", []) + ) + ids = [bucket.get("key") for bucket in buckets if "key" in bucket] + logger.debug(f"Extracted project IDs from response: {ids}") + return ids + + def _eu_project_sort_by_field(self, sort_by: ProjectsSortBy) -> str: + if sort_by == ProjectsSortBy.TITLE: + return "title.keyword" + elif sort_by == ProjectsSortBy.FUNDING_START: + return "startDate" + elif sort_by == ProjectsSortBy.FUNDING_END: + return "endDate" + elif sort_by == ProjectsSortBy.FUNDING_AMOUNT: + return "totalCost" + else: + return "id.keyword" + + def _eu_projects_body( + self, + project_ids: List[str], + projects_filtering_properties: ProjectsFilteringProperties, + ) -> Dict[str, Any]: + bool_query: Dict[str, Any] = {"filter": [{"terms": {"id": project_ids}}]} + + if ( + projects_filtering_properties.query is not None + and projects_filtering_properties.query.strip() != "" + ): + bool_query["must"] = [ + { + "match_phrase_prefix": { + "title": { + "query": projects_filtering_properties.query, + "max_expansions": 50, + } + } + } + ] + + body: Dict[str, Any] = { + "from": projects_filtering_properties.page + * projects_filtering_properties.size, + "size": projects_filtering_properties.size, + "query": {"bool": bool_query}, + "sort": [ + { + self._eu_project_sort_by_field( + projects_filtering_properties.sort_by + ): { + "order": projects_filtering_properties.sort_direction, + } + } + ], + } + + query_str = json.dumps(body, indent=2) + logger.debug(f"Constructed EU project details query: {query_str}") + return body + + async def search_eu_projects2( + self, + eu_organisation_id: str, + projects_filtering_properties: ProjectsFilteringProperties, + ) -> CordisEuProjectPage: + projects_id_body = self._eu_projects_id_body(eu_organisation_id) + id_response = await self.make_search_request( + projects_id_body, index="cordis_eu_*_organizations" + ) + project_ids = self._eu_projects_id_response_to_ids(id_response) + logger.debug( + f"Found project IDs for organization ID {eu_organisation_id}: {project_ids}" + ) + if not project_ids: + logger.debug( + f"No project IDs found for organization ID {eu_organisation_id}" + ) + return CordisEuProjectPage( + elements=[], + total=0, + page=projects_filtering_properties.page, + size=projects_filtering_properties.size, + ) + projects_body = self._eu_projects_body( + project_ids=project_ids, + projects_filtering_properties=projects_filtering_properties, + ) + projects_response = await self.make_search_request( + projects_body, index="cordis_eu_*_projects" + ) + logger.debug( + f"Received projects response: {json.dumps(projects_response, indent=2)}" + ) + return self._response_to_cordis_eu_project_page( + projects_response, + projects_filtering_properties.page, + projects_filtering_properties.size, + ) + + def _response_to_cordis_eu_project_page( + self, response: Dict[str, Any], page: int, size: int + ) -> CordisEuProjectPage: + hits_block = response.get("hits", {}) + total_hits = hits_block.get("total", {}).get("value", 0) + elements = [ + CordisEuProject.model_validate(hit["_source"]) + for hit in hits_block.get("hits", []) + ] + return CordisEuProjectPage( + elements=elements, total=total_hits, page=page, size=size + ) + def response_to_eu_project_page( - self, response: dict, page: int, size: int + self, response: Dict[str, Any], page: int, size: int ) -> EuProjectPage: hits_block = response.get("hits", {}) total_hits = hits_block.get("total", {}).get("value", 0) @@ -605,3 +794,147 @@ class DfgProjectsSearchClient(ProjectsSearchClient): ) response = await self.make_search_request(query) return self.response_to_dfg_project_page(response, page, size) + + async def get_dfg_project_by_id( + self, project_id: str + ) -> Optional[DfgProjectDetails]: + query = {"query": {"ids": {"values": [project_id]}}, "_source": True} + + response = await self.make_search_request(query) + hits = response.get("hits", {}).get("hits", []) + + if hits: + hit = hits[0] + details = DfgProjectDetails.from_elastic_hit(hit=hit) + return details + return None + + +class CompleteProjectsSearchClient(ProjectsSearchClient): + def __init__(self): + if not settings.elasticsearch_inse_url: + raise ValueError("Elasticsearch INSE URL is missing in settings.") + if not settings.elasticsearch_inse_api_key: + raise ValueError("Elasticsearch INSE API key is missing in settings.") + super().__init__( + base_url=settings.elasticsearch_inse_url, + index="cordis_eu_*_projects,projects_bund_v1,projects_dfg_all", + api_key=settings.elasticsearch_inse_api_key, + ) + + def _build_projects_search_body( + self, + page: int, + size: int, + title: Optional[str] = None, + sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, + sort_direction: SortDirection = SortDirection.ASC, + ) -> Dict[str, Any]: + if sort_by != ProjectsSortBy.TITLE: + raise ValueError("Currently only sorting by title is supported.") + + query: Dict[str, Any] = { + "size": size, + "from": page * size, + "sort": [ + { + "title.keyword": { + "order": sort_direction, + "missing": "_last", + "unmapped_type": "keyword", + } + }, + { + "Thema.keyword": { + "order": sort_direction, + "missing": "_last", + "unmapped_type": "keyword", + } + }, + ], + } + + if title and len(title.strip()) > 0: + title = f"*{title.strip()}*" + query["query"] = { + "bool": { + "should": [ + { + "wildcard": { + "title.keyword": { + "value": title, + "case_insensitive": True, + } + } + }, + { + "wildcard": { + "Thema.keyword": { + "value": title, + "case_insensitive": True, + } + } + }, + ], + "minimum_should_match": 1, + } + } + + return query + + def _project_type_to_index(self, project_type: ProjectType) -> str: + if project_type == ProjectType.BUND: + return "projects_bund_v1" + elif project_type == ProjectType.EU: + return "cordis_eu_*_projects" + elif project_type == ProjectType.DFG: + return "projects_dfg_all" + else: + raise ValueError(f"Unsupported project type: {project_type}") + + def _hit_to_funding_project(self, hit: Dict[str, Any]) -> FundingProject: + if hit.get("_index", "").startswith("cordis_eu_") and hit.get( + "_index", "" + ).endswith("_projects"): + return FundingProject.from_cordis_projects_hit(hit=hit) + elif hit.get("_index") == "projects_bund_v1": + return FundingProject.from_bund_projects_hit(hit=hit) + elif hit.get("_index") == "projects_dfg_all": + return FundingProject.from_dfg_projects_hit(hit=hit) + else: + raise ValueError( + "The provided hit does not belong to a recognized project index." + ) + + def _response_to_funding_project_page( + self, response: Dict[str, Any], page: int, size: int + ) -> FundingProjectPage: + hits = response.get("hits", {}).get("hits", []) + projects = [self._hit_to_funding_project(hit=hit) for hit in hits] + total = response.get("hits", {}).get("total", {}).get("value", 0) + return FundingProjectPage(elements=projects, total=total, page=page, size=size) + + async def search_projects( + self, + page: int, + size: int, + selected_project_types: Optional[Set[ProjectType]] = None, + title: Optional[str] = None, + sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, + sort_direction: SortDirection = SortDirection.ASC, + ): + body = self._build_projects_search_body( + page=page, + size=size, + title=title, + sort_by=sort_by, + sort_direction=sort_direction, + ) + if not selected_project_types: + selected_project_types = {ProjectType.BUND, ProjectType.EU, ProjectType.DFG} + index = ",".join( + self._project_type_to_index(pt) for pt in selected_project_types + ) + + projects_response = await self.make_search_request(body, index=index) + return self._response_to_funding_project_page(projects_response, page, size) diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index c9baa58d..60beae82 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -1,19 +1,27 @@ from functools import lru_cache import logging -from typing import Annotated, Optional +from typing import Annotated, Optional, Set -from fastapi import APIRouter, Depends, Query, status +from fastapi import APIRouter, Body, Depends, Path, Query, status from inse.projects.model import ( BundProjectPage, + CordisEuProjectPage, DfgProjectPage, - EuProjectPage, + FundingProjectPage, InstitutionFunderSummary, + ProjectType, + ProjectsFilteringProperties, + ProjectsSortBy, + SortDirection, ) +from inse.models.dfg_project_details import DfgProjectDetails +from inse.models.bund_project_details import BundProjectDetails from inse.tags import Tags from inse.projects import service as projects_service from inse.projects.projects_search_client import ( BundProjectsSearchClient, + CompleteProjectsSearchClient, DfgProjectsSearchClient, EuProjectsSearchClient, ) @@ -42,11 +50,16 @@ def get_dfg_search_client() -> DfgProjectsSearchClient: return DfgProjectsSearchClient() -@router.get( +@lru_cache +def get_complete_projects_search_client() -> CompleteProjectsSearchClient: + return CompleteProjectsSearchClient() + + +@router.post( "/institution/bund/search", summary="Get bund projects.", description="Returns a page of bund projects based on the provided pagination parameters and optional institution filter.", - operation_id="getBundProjects", + operation_id="searchBundProjects", responses={ status.HTTP_200_OK: { "description": "Successful Response", @@ -56,35 +69,76 @@ def get_dfg_search_client() -> DfgProjectsSearchClient: }, response_model_by_alias=False, ) -async def get_bund_projects( +async def search_bund_projects( bund_search_client: Annotated[ BundProjectsSearchClient, Depends(get_bund_search_client) ], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], - institution_id: Annotated[ - str, Query(description="The institution ID to filter by.") + filtering_properties: Annotated[ + ProjectsFilteringProperties, + Body(description="The filtering properties for the projects search."), ], - topic: Annotated[ - Optional[str], Query(description="The topic to filter by.") - ] = None, - page: Annotated[int, Query(description="The page number.", ge=0)] = 0, - size: Annotated[int, Query(description="The page size.", ge=1)] = 20, - sort_by: Annotated[str, Query(description="The field to sort by.")] = "topic", - sort_direction: Annotated[ - str, Query(description="The sort direction (asc or desc).") - ] = "asc", ) -> BundProjectPage: - return await projects_service.get_bund_projects_by_institution_id( + return await projects_service.search_bund_projects( bund_search_client=bund_search_client, institutions_search_client=institutions_search_client, - institution_id=institution_id, - page=page, - size=size, - topic=topic, - sort_by=sort_by, - sort_direction=sort_direction, + filtering_properties=filtering_properties, + ) + + +@router.get( + "/dfg/{id}", + summary="Get a single DFG project.", + description="Returns a single DFG project based on its ID.", + operation_id="getSingleDfgProject", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": DfgProjectDetails, + }, + status.HTTP_404_NOT_FOUND: {"description": "Project not found"}, + }, + response_model_by_alias=False, +) +async def get_single_dfg_project( + dfg_search_client: Annotated[ + DfgProjectsSearchClient, Depends(get_dfg_search_client) + ], + id: Annotated[str, Path(description="The ID of the DFG project to retrieve.")], +) -> DfgProjectDetails: + logger.debug(f"Received request to get single DFG project for id={id}") + return await projects_service.get_single_dfg_project( + dfg_search_client=dfg_search_client, + project_id=id, + ) + + +@router.get( + "/bund/{id}", + summary="Get a single BUND project.", + description="Returns a single BUND project based on its ID.", + operation_id="getSingleBundProject", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": BundProjectDetails, + }, + status.HTTP_404_NOT_FOUND: {"description": "Project not found"}, + }, + response_model_by_alias=False, +) +async def get_single_bund_project( + bund_search_client: Annotated[ + BundProjectsSearchClient, Depends(get_bund_search_client) + ], + id: Annotated[str, Path(description="The ID of the BUND project to retrieve.")], +) -> BundProjectDetails: + logger.debug(f"Received request to get single BUND project for id={id}") + return await projects_service.get_single_bund_project( + bund_search_client=bund_search_client, + project_id=id, ) @@ -92,7 +146,7 @@ async def get_bund_projects( "/institution/bund/funding-over-time", summary="Get funding over time for bund projects.", description="Returns the funding over time for bund projects associated with the specified institution.", - operation_id="getBundFundingOverTime", + operation_id="getInstitutionBundProjectsFundingOverTime", responses={ status.HTTP_200_OK: { "description": "Successful Response", @@ -102,65 +156,82 @@ async def get_bund_projects( }, response_model_by_alias=False, ) -async def get_bund_funding_over_time( +async def get_institution_bund_projects_funding_over_time( bund_search_client: Annotated[ BundProjectsSearchClient, Depends(get_bund_search_client) ], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], - institution_id: Annotated[ + raw_oa_institution_id: Annotated[ str, Query(description="The institution ID to filter by.") ], ) -> InstitutionFunderSummary: - return await projects_service.get_institution_bund_funding_over_time( + return await projects_service.get_institution_bund_projects_funding_over_time( bund_search_client=bund_search_client, institutions_search_client=institutions_search_client, - institution_id=institution_id, + raw_oa_institution_id=raw_oa_institution_id, ) -@router.get( +@router.post( "/institution/eu/search", summary="Get EU projects.", description="Returns a page of EU projects based on the provided pagination parameters and optional institution filter.", - operation_id="getEuProjects", + operation_id="searchCordisEuProjects", responses={ status.HTTP_200_OK: { "description": "Successful Response", - "model": EuProjectPage, + "model": CordisEuProjectPage, }, status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, }, response_model_by_alias=False, ) -async def get_eu_projects( +async def search_cordis_eu_projects( eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], - institution_id: Annotated[ - str, Query(description="The institution ID to filter by.") + projects_filtering_properties: Annotated[ + ProjectsFilteringProperties, + Body(description="The filtering properties for the projects search."), ], - topic: Annotated[ - Optional[str], Query(description="The topic to filter by.") - ] = None, - page: Annotated[int, Query(description="The page number.", ge=0)] = 0, - size: Annotated[int, Query(description="The page size.", ge=1)] = 20, - sort_by: Annotated[str, Query(description="The field to sort by.")] = "topic", - sort_direction: Annotated[ - str, Query(description="The sort direction (asc or desc).") - ] = "asc", -) -> EuProjectPage: - return await projects_service.get_eu_projects_by_institution_id( +) -> CordisEuProjectPage: + return await projects_service.search_cordis_eu_projects( eu_search_client=eu_search_client, institutions_search_client=institutions_search_client, - institution_id=institution_id, - topic=topic, - page=page, - size=size, - sort_by=sort_by, - sort_direction=sort_direction, + projects_filtering_properties=projects_filtering_properties, + ) + + +@router.get( + "/institution/eu/funding-over-time", + summary="Get funding over time for EU projects.", + description="Returns the funding over time for EU projects associated with the specified institution.", + operation_id="getInstitutionCordisEuProjectsFundingOverTime", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": InstitutionFunderSummary, + }, + status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + }, + response_model_by_alias=False, +) +async def get_institution_cordis_eu_projects_funding_over_time( + eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)], + institutions_search_client: Annotated[ + InstitutionsSearchClient, Depends(get_institutions_search_client) + ], + raw_oa_institution_id: Annotated[ + str, Query(description="The institution ID to filter by.") + ], +) -> InstitutionFunderSummary: + return await projects_service.get_institution_cordis_eu_projects_funding_over_time( + eu_search_client=eu_search_client, + institutions_search_client=institutions_search_client, + raw_oa_institution_id=raw_oa_institution_id, ) @@ -211,3 +282,49 @@ async def get_dfg_projects( sort_by=sort_by, sort_direction=sort_direction, ) + + +@router.get( + "/search", + summary="Search projects across all funders.", + description="Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter.", + operation_id="searchProjects", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": FundingProjectPage, + }, + }, + response_model_by_alias=False, +) +async def search_projects( + complete_projects_search_client: Annotated[ + CompleteProjectsSearchClient, Depends(get_complete_projects_search_client) + ], + page: Annotated[int, Query(description="The page number.", ge=0)] = 0, + size: Annotated[int, Query(description="The page size.", ge=1)] = 10, + selected_project_types: Annotated[ + Optional[Set[ProjectType]], + Query( + description="The set of project types to filter by (e.g., 'bund', 'eu', 'dfg'). If not provided, projects of all types will be included." + ), + ] = None, + title: Annotated[ + Optional[str], Query(description="The title to filter by.") + ] = None, + sort_by: Annotated[ + ProjectsSortBy, Query(description="The field to sort by.") + ] = ProjectsSortBy.TITLE, + sort_direction: Annotated[ + SortDirection, Query(description="The sort direction (asc or desc).") + ] = SortDirection.ASC, +) -> FundingProjectPage: + return await projects_service.search_projects( + projects_search_client=complete_projects_search_client, + page=page, + size=size, + selected_project_types=selected_project_types, + title=title, + sort_by=sort_by, + sort_direction=sort_direction, + ) diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index fda7832e..83f55211 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -1,18 +1,27 @@ import datetime import logging -from typing import Dict, List, Optional +from typing import Any, Dict, List, Optional, Set from inse.projects.projects_search_client import ( BundProjectsSearchClient, + CompleteProjectsSearchClient, DfgProjectsSearchClient, EuProjectsSearchClient, ) from inse.projects.model import ( BundProjectPage, + CordisEuProjectPage, DfgProjectPage, EuProjectPage, + FundingProjectPage, InstitutionFunderSummary, + ProjectType, + ProjectsFilteringProperties, + ProjectsSortBy, + SortDirection, ) +from inse.models.dfg_project_details import DfgProjectDetails +from inse.models.bund_project_details import BundProjectDetails from inse.institutions.institutions_search_client import ( InstitutionsSearchClient, ) @@ -22,41 +31,133 @@ from inse.persons.logic import get_author_name_by_id logger = logging.getLogger(__name__) +async def search_projects( + projects_search_client: CompleteProjectsSearchClient, + page: int, + size: int, + sort_by: ProjectsSortBy, + sort_direction: SortDirection, + selected_project_types: Optional[Set[ProjectType]] = None, + title: Optional[str] = None, +) -> FundingProjectPage: + return await projects_search_client.search_projects( + page=page, + size=size, + selected_project_types=selected_project_types, + title=title, + sort_by=sort_by, + sort_direction=sort_direction, + ) + + +async def search_bund_projects( + bund_search_client: BundProjectsSearchClient, + institutions_search_client: InstitutionsSearchClient, + filtering_properties: ProjectsFilteringProperties, +) -> BundProjectPage: + if filtering_properties.project_type != "bund": + raise ValueError( + f"Invalid project type: {filtering_properties.project_type}. Expected 'bund'." + ) + + return await get_bund_projects_by_institution_id( + bund_search_client=bund_search_client, + institutions_search_client=institutions_search_client, + filtering_properties=filtering_properties, + ) + + async def get_bund_projects_by_institution_id( bund_search_client: BundProjectsSearchClient, institutions_search_client: InstitutionsSearchClient, - institution_id: str, - page: int, - size: int, - topic: Optional[str], - sort_by: str = "topic", - sort_direction: str = "asc", + filtering_properties: ProjectsFilteringProperties, ) -> BundProjectPage: + if filtering_properties.raw_oa_institution_id is None: + raise ValueError("raw_oa_institution_id must be provided") + logger.info( - f"Fetching bund projects for institution_id={institution_id}, page={page}, size={size}" + f"Fetching bund projects for institution_id={filtering_properties.raw_oa_institution_id}, page={filtering_properties.page}, size={filtering_properties.size}" ) institution_aliases = institutions_search_client.get_institution_aliases_by_id( - institution_id + filtering_properties.raw_oa_institution_id ) logger.debug( - f"Found institution aliases for institution_id={institution_id}: {institution_aliases}" + f"Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) response = await bund_search_client.search_bund_projects( - page=page, - size=size, + page=filtering_properties.page, + size=filtering_properties.size, institution_names=institution_aliases, - topic=topic, - sort_by=sort_by, - sort_direction=sort_direction, + topic=filtering_properties.query, + sort_by=filtering_properties.sort_by, + sort_direction=filtering_properties.sort_direction, ) logger.debug(f"get_bund_projects_by_institution_id response: {response}") return response +async def search_cordis_eu_projects( + eu_search_client: EuProjectsSearchClient, + institutions_search_client: InstitutionsSearchClient, + projects_filtering_properties: ProjectsFilteringProperties, +) -> CordisEuProjectPage: + if projects_filtering_properties.project_type != "eu": + raise ValueError( + f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'." + ) + + return await get_cordis_eu_projects_by_institution_id( + eu_search_client=eu_search_client, + institutions_search_client=institutions_search_client, + projects_filtering_properties=projects_filtering_properties, + ) + + +async def get_cordis_eu_projects_by_institution_id( + eu_search_client: EuProjectsSearchClient, + institutions_search_client: InstitutionsSearchClient, + projects_filtering_properties: ProjectsFilteringProperties, +) -> CordisEuProjectPage: + if not projects_filtering_properties.raw_oa_institution_id: + raise ValueError( + "raw_oa_institution_id must be provided to fetch CORDIS EU projects by institution ID" + ) + + logger.info( + f"Fetching CORDIS EU projects for institution_id={projects_filtering_properties.raw_oa_institution_id}, page={projects_filtering_properties.page}, size={projects_filtering_properties.size}" + ) + institution_aliases = institutions_search_client.get_institution_aliases_by_id( + projects_filtering_properties.raw_oa_institution_id + ) + logger.debug( + f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}" + ) + + institution_eu_organisation_id = await ( + institutions_search_client.get_eu_organisation_id_by_oa_institution_id( + projects_filtering_properties.raw_oa_institution_id + ) + ) + if not institution_eu_organisation_id: + logger.debug( + f"No EU organization ID found for institution_id={projects_filtering_properties.raw_oa_institution_id}" + ) + raise NotFoundException( + f"EU organization ID for institution with id {projects_filtering_properties.raw_oa_institution_id} not found" + ) + + cordis_eu_project_page = await eu_search_client.search_eu_projects2( + eu_organisation_id=institution_eu_organisation_id, + projects_filtering_properties=projects_filtering_properties, + ) + + return cordis_eu_project_page + + async def get_eu_projects_by_institution_id( eu_search_client: EuProjectsSearchClient, institutions_search_client: InstitutionsSearchClient, - institution_id: str, + raw_oa_institution_id: str, topic: Optional[str], page: int, size: int, @@ -64,14 +165,28 @@ async def get_eu_projects_by_institution_id( sort_direction: str = "asc", ) -> EuProjectPage: logger.info( - f"Fetching EU projects for institution_id={institution_id}, page={page}, size={size}" + f"Fetching EU projects for institution_id={raw_oa_institution_id}, page={page}, size={size}" ) institution_aliases = institutions_search_client.get_institution_aliases_by_id( - institution_id + raw_oa_institution_id ) logger.debug( - f"Found institution aliases for institution_id={institution_id}: {institution_aliases}" + f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" ) + + institution_eu_organisation_id = await ( + institutions_search_client.get_eu_organisation_id_by_oa_institution_id( + raw_oa_institution_id + ) + ) + if not institution_eu_organisation_id: + logger.debug( + f"No EU organization ID found for institution_id={raw_oa_institution_id}" + ) + raise NotFoundException( + f"EU organization ID for institution with id {raw_oa_institution_id} not found" + ) + response = await eu_search_client.search_eu_projects( page=page, size=size, @@ -115,17 +230,45 @@ async def get_dfg_projects_by_author_id( return response -async def get_institution_bund_funding_over_time( +async def get_institution_cordis_eu_projects_funding_over_time( + eu_search_client: EuProjectsSearchClient, + institutions_search_client: InstitutionsSearchClient, + raw_oa_institution_id: str, +) -> InstitutionFunderSummary: + + cordis_eu_project_page = await search_cordis_eu_projects( + eu_search_client, + institutions_search_client, + ProjectsFilteringProperties( + project_type=ProjectType.EU, + raw_oa_institution_id=raw_oa_institution_id, + page=0, + size=10000, + ), + ) + + return _calculate_funding_over_time( + project_type=ProjectType.EU, + projects=cordis_eu_project_page.elements, + funding_start_attr="startDate", + funding_end_attr="endDate", + funding_amount_attr="totalCost", + ) + + +async def get_institution_bund_projects_funding_over_time( bund_search_client: BundProjectsSearchClient, institutions_search_client: InstitutionsSearchClient, - institution_id: str, + raw_oa_institution_id: str, ) -> InstitutionFunderSummary: - logger.info(f"Fetching funding over time for institution_id={institution_id}") + logger.info( + f"Fetching funding over time for institution_id={raw_oa_institution_id}" + ) institution_aliases = institutions_search_client.get_institution_aliases_by_id( - institution_id + raw_oa_institution_id ) logger.debug( - f"Found institution aliases for institution_id={institution_id}: {institution_aliases}" + f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" ) response = await bund_search_client.search_bund_projects( page=0, @@ -133,14 +276,36 @@ async def get_institution_bund_funding_over_time( institution_names=institution_aliases, ) + return _calculate_funding_over_time( + project_type=ProjectType.BUND, + projects=response.elements, + funding_start_attr="funding_start", + funding_end_attr="funding_end", + funding_amount_attr="grant_amount", + ) + + +def _calculate_funding_over_time( + project_type: ProjectType, + projects: List[Any], + funding_start_attr: str, + funding_end_attr: str, + funding_amount_attr: str, +) -> InstitutionFunderSummary: funding_per_year: Dict[int, float] = {} - for project in response.elements: - funding_start = project.funding_start - funding_end = project.funding_end - funding_amount = project.grant_amount + + for project in projects: + funding_start = getattr(project, funding_start_attr) + funding_end = getattr(project, funding_end_attr) + funding_amount = getattr(project, funding_amount_attr) if not funding_start or not funding_end or not funding_amount: continue + if hasattr(funding_start, "date"): + funding_start = funding_start.date() + if hasattr(funding_end, "date"): + funding_end = funding_end.date() + delta = (funding_end - funding_start).days + 1 if delta <= 0: continue @@ -182,7 +347,31 @@ async def get_institution_bund_funding_over_time( annual_average_over_period = 0.0 return InstitutionFunderSummary( - type="bund", + type=project_type, funding_per_year=sorted_funding_per_year, annual_average_over_period=annual_average_over_period, ) + + +async def get_single_dfg_project( + dfg_search_client: DfgProjectsSearchClient, + project_id: str, +) -> DfgProjectDetails: + logger.debug(f"Fetching single DFG project for id={project_id}") + + project = await dfg_search_client.get_dfg_project_by_id(project_id) + if not project: + raise NotFoundException(f"DFG project with id {project_id} not found") + return project + + +async def get_single_bund_project( + bund_search_client: BundProjectsSearchClient, + project_id: str, +) -> BundProjectDetails: + logger.debug(f"Fetching single BUND project for id={project_id}") + + project = await bund_search_client.get_bund_project_by_id(project_id) + if not project: + raise NotFoundException(f"BUND project with id {project_id} not found") + return project diff --git a/service/src/main/inse/university_ranking/logic.py b/service/src/main/inse/university_ranking/logic.py new file mode 100644 index 00000000..bd1e58f9 --- /dev/null +++ b/service/src/main/inse/university_ranking/logic.py @@ -0,0 +1,113 @@ +import logging +from typing import List, Dict, Any +from .model import UniversityTopicData, YearlyData, UniversityRanking, ResearchTopic, DashboardMetric, RankingResponse +from inse.integrations import elasticsearch + +logger = logging.getLogger(__name__) + +START_YEAR = 2015 +END_YEAR = 2026 + +async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse: + """ + Fetches real data from Elasticsearch and computes metrics for the dashboard. + """ + query = { + "bool": { + "must": [ + { + "match_phrase": { + "topics.display_name": topic + } + }, + { + "term": { + "geo.country_code": "DE" + } + } + ] + } + } + + + # Fetch top institutions for the topic by works_count + res = elasticsearch.search( + index="openalex-institutions", + query=query, + size=10, + sort=[{"works_count": "desc"}], + cluster="nes" + ) + + hits = res.get("hits", {}).get("hits", []) + timeseries: List[UniversityTopicData] = [] + + for hit in hits: + source = hit["_source"] + # Map the counts_by_year from ES to our model + # We ensure every year from START_YEAR to END_YEAR is present, defaulting to 0 + es_counts = {c["year"]: c for c in source.get("counts_by_year", [])} + + yearly_data = [] + for year in range(START_YEAR, END_YEAR + 1): + count_item = es_counts.get(year, {}) + yearly_data.append(YearlyData( + year=year, + publications=count_item.get("works_count", 0), + citations=count_item.get("cited_by_count", 0) + )) + + timeseries.append(UniversityTopicData( + university=source.get("display_name", "Unknown"), + topic=topic, + yearly_data=yearly_data + )) + + rankings = _compute_rankings(timeseries, metric) + + return RankingResponse(timeseries=timeseries, rankings=rankings) + +def _compute_rankings(data: List[UniversityTopicData], metric: DashboardMetric) -> List[UniversityRanking]: + """Computes ranking metrics based on the timeseries data.""" + latest_year = END_YEAR + five_years_ago = latest_year - 5 + three_years_ago = latest_year - 3 + + processed: List[Dict[str, Any]] = [] + for item in data: + latest = next((d for d in item.yearly_data if d.year == latest_year), YearlyData(year=latest_year, publications=0, citations=0)) + prev = next((d for d in item.yearly_data if d.year == latest_year - 1), YearlyData(year=latest_year-1, publications=0, citations=0)) + start_range = next((d for d in item.yearly_data if d.year == five_years_ago), YearlyData(year=five_years_ago, publications=0, citations=0)) + mover_range = next((d for d in item.yearly_data if d.year == three_years_ago), YearlyData(year=three_years_ago, publications=0, citations=0)) + + curr_val = getattr(latest, metric) or 0 + prev_val = getattr(prev, metric) or 0 + old_val = getattr(start_range, metric) or 0 + mover_old_val = getattr(mover_range, metric) or 0 + + growth_rate = ((curr_val - old_val) / old_val * 100) if old_val > 0 else 0 + recent_growth = ((curr_val - mover_old_val) / mover_old_val * 100) if mover_old_val > 0 else 0 + + processed.append({ + "university": item.university, + "publications": latest.publications, + "citations": latest.citations, + "growth_rate": growth_rate, + "trend": 'up' if curr_val > prev_val else ('down' if curr_val < prev_val else 'stable'), + "recent_growth": recent_growth, + "sort_val": curr_val + }) + + processed.sort(key=lambda x: x["sort_val"], reverse=True) + # Top movers: top 2 by recent growth + growth_sorted = sorted([p["recent_growth"] for p in processed], reverse=True) + threshold = growth_sorted[1] if len(growth_sorted) > 1 else 0 + + return [ + UniversityRanking( + rank=i + 1, + is_top_mover=p["recent_growth"] >= threshold and p["recent_growth"] > 0, + **{k: v for k, v in p.items() if k != "sort_val" and k != "recent_growth"} + ) + for i, p in enumerate(processed) + ] \ No newline at end of file diff --git a/service/src/main/inse/university_ranking/model.py b/service/src/main/inse/university_ranking/model.py new file mode 100644 index 00000000..1b4b8605 --- /dev/null +++ b/service/src/main/inse/university_ranking/model.py @@ -0,0 +1,30 @@ +from pydantic import BaseModel +from typing import List, Literal + +ResearchTopic = Literal['Artificial Intelligence', 'Quantum Computing', 'Renewable Energy', 'Biotechnology'] +DashboardMetric = Literal['publications', 'citations'] + +class YearlyData(BaseModel): + year: int + publications: int + citations: int + +class UniversityTopicData(BaseModel): + university: str + topic: ResearchTopic + yearly_data: List[YearlyData] + +class UniversityRanking(BaseModel): + rank: int + university: str + publications: int + citations: int + growth_rate: float + trend: Literal['up', 'down', 'stable'] + is_top_mover: bool + +class RankingResponse(BaseModel): + # Raw timeseries data for the ECharts line race + timeseries: List[UniversityTopicData] + # Computed metrics for the ranking table + rankings: List[UniversityRanking] \ No newline at end of file diff --git a/service/src/main/inse/university_ranking/router.py b/service/src/main/inse/university_ranking/router.py new file mode 100644 index 00000000..60c52c9d --- /dev/null +++ b/service/src/main/inse/university_ranking/router.py @@ -0,0 +1,23 @@ +from fastapi import APIRouter, Query +from . import service +from .model import RankingResponse, ResearchTopic, DashboardMetric +from inse.tags import Tags + +router = APIRouter( + prefix="/api/inse-service/university-rankings", + tags=[Tags.INSTITUTIONS] +) + +@router.get( + "", + response_model=RankingResponse, + summary="Returns data for the University Ranking Dashboard." +) +async def get_rankings( + topic: ResearchTopic = Query( + ..., + description="Research topic (e.g., 'Artificial Intelligence')" + ), + metric: DashboardMetric = Query("publications", description="Metric to rank by") +): + return await service.get_university_dashboard_data(topic, metric) \ No newline at end of file diff --git a/service/src/main/inse/university_ranking/service.py b/service/src/main/inse/university_ranking/service.py new file mode 100644 index 00000000..4eac89e6 --- /dev/null +++ b/service/src/main/inse/university_ranking/service.py @@ -0,0 +1,6 @@ +from . import logic +from .model import RankingResponse, ResearchTopic, DashboardMetric + +async def get_university_dashboard_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse: + """Orchestrates data retrieval and computation for the dashboard.""" + return await logic.get_ranking_data(topic, metric) \ No newline at end of file diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 40e2c9f1..37540cda 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -6,7 +6,7 @@ Business logic for publication works. import logging from time import time -from typing import List +from typing import Any, List import httpx from fastapi import HTTPException @@ -328,6 +328,30 @@ async def get_topics_by_time_by_author( target_publications: int = 300, include_all: bool = False, client: OpenAlexWorksSearchClient | None = None, +) -> TopicsByTime: + if client is not None: + return await _get_topics_by_time_by_author_from_work_pages( + author_id, + max_topics_per_year=max_topics_per_year, + target_publications=target_publications, + include_all=include_all, + client=client, + ) + + return _get_topics_by_time_by_author_from_es( + author_id, + max_topics_per_year=max_topics_per_year, + target_publications=target_publications, + include_all=include_all, + ) + + +async def _get_topics_by_time_by_author_from_work_pages( + author_id: str, + max_topics_per_year: int = 3, + target_publications: int = 300, + include_all: bool = False, + client: OpenAlexWorksSearchClient | None = None, ) -> TopicsByTime: if include_all: works = await get_all_author_works(author_id, client=client) @@ -459,6 +483,304 @@ async def get_topics_by_time_by_author( ) +def _get_topics_by_time_by_author_from_es( + author_id: str, + max_topics_per_year: int = 3, + target_publications: int = 300, + include_all: bool = False, +) -> TopicsByTime: + year_buckets, total_publications = _get_publication_year_counts_from_es(author_id) + selected_years, is_limited = _select_complete_timeline_years( + year_buckets, + target_publications=target_publications, + include_all=include_all, + ) + + if not selected_years: + return TopicsByTime( + elements=[], + total=0, + is_limited=False, + used_publications=0, + total_publications=total_publications, + ) + + year_topic_buckets = _get_timeline_topic_counts_from_es( + author_id, + years=selected_years, + max_topics_per_year=max_topics_per_year, + ) + topic_ids = _collect_topic_ids_from_year_buckets(year_topic_buckets) + topic_details = _get_topic_details(list(topic_ids)) + + elements = _build_timeline_elements_from_aggregations( + year_topic_buckets, + topic_details=topic_details, + max_topics_per_year=max_topics_per_year, + ) + + return TopicsByTime( + elements=elements, + total=len(elements), + is_limited=is_limited, + used_publications=sum(element.publication_count for element in elements), + total_publications=total_publications, + ) + + +def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]: + body = { + "size": 0, + "track_total_hits": True, + "query": _author_works_query(author_id), + "aggs": { + "publication_years": { + "terms": { + "field": "publication_year", + "size": 300, + "order": {"_key": "desc"}, + }, + }, + }, + } + + try: + response = elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=body, + ) + except httpx.HTTPError as exc: + logger.exception("OpenAlex publication year aggregation request failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex works search request failed.", + ) from exc + + return _parse_year_count_buckets(response), _parse_total_hits(response) + + +def _get_timeline_topic_counts_from_es( + author_id: str, + years: list[int], + max_topics_per_year: int, +) -> list[dict]: + body = { + "size": 0, + "query": { + "bool": { + "must": [_author_works_query(author_id)], + "filter": [{"terms": {"publication_year": years}}], + }, + }, + "aggs": { + "by_year": { + "terms": { + "field": "publication_year", + "size": len(years), + "order": {"_key": "asc"}, + }, + "aggs": { + "primary_topics": { + "terms": { + "field": "primary_topic.id", + "size": max_topics_per_year, + "order": [ + {"_count": "desc"}, + {"_key": "asc"}, + ], + }, + }, + "topics_nested": { + "nested": {"path": "topics"}, + "aggs": { + "topics": { + "terms": { + "field": "topics.id", + "size": max_topics_per_year, + "order": [ + {"_count": "desc"}, + {"_key": "asc"}, + ], + }, + "aggs": { + "works": { + "reverse_nested": {}, + }, + }, + }, + }, + }, + }, + }, + }, + } + + try: + response = elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=body, + ) + except httpx.HTTPError as exc: + logger.exception("OpenAlex timeline topic aggregation request failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex works search request failed.", + ) from exc + + return response.get("aggregations", {}).get("by_year", {}).get("buckets", []) + + +def _author_works_query(author_id: str) -> dict[str, Any]: + indexed_author_id = f"https://openalex.org/{author_id.strip()}" + + return { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": [ + {"term": {"authorships.author.id": indexed_author_id}}, + ], + }, + }, + }, + } + + +def _parse_year_count_buckets(response: dict) -> list[dict]: + return ( + response.get("aggregations", {}) + .get("publication_years", {}) + .get("buckets", []) + ) + + +def _parse_total_hits(response: dict) -> int: + total = response.get("hits", {}).get("total", 0) + + if isinstance(total, dict): + return total.get("value", 0) + + return total + + +def _select_complete_timeline_years( + year_buckets: list[dict], + target_publications: int, + include_all: bool, +) -> tuple[list[int], bool]: + if include_all: + return [bucket["key"] for bucket in year_buckets], False + + selected_years: list[int] = [] + selected_publications = 0 + + for bucket in year_buckets: + selected_years.append(bucket["key"]) + selected_publications += bucket.get("doc_count", 0) + + if selected_publications >= target_publications: + break + + is_limited = len(selected_years) < len(year_buckets) + + return selected_years, is_limited + + +def _collect_topic_ids_from_year_buckets(year_buckets: list[dict]) -> set[str]: + topic_ids: set[str] = set() + + for year_bucket in year_buckets: + primary_buckets = ( + year_bucket.get("primary_topics", {}).get("buckets", []) + ) + topic_buckets = ( + year_bucket.get("topics_nested", {}) + .get("topics", {}) + .get("buckets", []) + ) + + for bucket in primary_buckets + topic_buckets: + topic_id = bucket.get("key") + + if topic_id: + topic_ids.add(topic_id) + + return topic_ids + + +def _build_timeline_elements_from_aggregations( + year_buckets: list[dict], + topic_details: dict[str, dict], + max_topics_per_year: int, +) -> list[TopicsByYear]: + elements: list[TopicsByYear] = [] + + for year_bucket in year_buckets: + year = year_bucket.get("key") + + if year is None: + continue + + topics = _build_topic_counts_from_buckets( + year_bucket.get("topics_nested", {}) + .get("topics", {}) + .get("buckets", []), + topic_details=topic_details, + max_topics_per_year=max_topics_per_year, + use_reverse_nested_count=True, + ) + primary_topics = _build_topic_counts_from_buckets( + year_bucket.get("primary_topics", {}).get("buckets", []), + topic_details=topic_details, + max_topics_per_year=max_topics_per_year, + use_reverse_nested_count=False, + ) + + elements.append( + TopicsByYear( + year=year, + publication_count=year_bucket.get("doc_count", 0), + topics=topics, + primary_topics=primary_topics, + ) + ) + + return elements + + +def _build_topic_counts_from_buckets( + buckets: list[dict], + topic_details: dict[str, dict], + max_topics_per_year: int, + use_reverse_nested_count: bool, +) -> list[TopicCount]: + topics: list[TopicCount] = [] + + for bucket in buckets[:max_topics_per_year]: + topic_id = bucket.get("key") + + if not topic_id: + continue + + info = topic_details.get(topic_id, {}) + display_name = info.get("display_name") or topic_id + count = bucket.get("doc_count", 0) + + if use_reverse_nested_count: + count = bucket.get("works", {}).get("doc_count", count) + + topics.append( + TopicCount( + id=topic_id, + name=display_name, + count=count, + description=info.get("description"), + ) + ) + + return topics + async def _search_author_works_data( search_client: OpenAlexWorksSearchClient, author_id: str, @@ -538,4 +860,4 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]: detail="OpenAlex works search response could not be parsed.", ) from exc - return elements, total + return elements, total \ No newline at end of file diff --git a/ude_person.http b/ude_person.http index 83b5a842..35ed2607 100644 --- a/ude_person.http +++ b/ude_person.http @@ -13,10 +13,192 @@ Content-Type: application/json } ### -GET https://inse.nes.uni-due.de/elastic/projects_dfg_all/_search +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== Content-Type: application/json +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_mapping +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_projects/_mapping +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_projects/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "size": 100, + "query": { + "bool": { + "filter": [ + { + "terms": { + "id": ["604123", "101003555"] + } + } + ] + } + } +} + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "size": 0, + "query": { + "bool": { + "filter": [ + { + "term": { + "organisationID": "999843312" + } + } + ] + } + }, + "aggs": { + "associated_project_ids": { + "terms": { + "field": "projectID" + } + } + } +} + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "size": 0, + "query": { + "bool": { + "filter": [ + { + "term": { + "name.keyword": "UNIVERSITAET DUISBURG-ESSEN" + } + } + ] + } + }, + "aggs": { + "associated_project_ids": { + "terms": { + "field": "projectID" + } + } + } +} + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "size": 10, + "query": { + "bool": { + "filter": [ + { + "term": { + "name.keyword": "UNIVERSITAET DUISBURG-ESSEN" + } + } + ] + } + } +} + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "size": 0, + "query": { + "bool": { + "filter": [ + { + "term": { + "name.keyword": "UNIVERSITAET DUISBURG-ESSEN" + } + } + ] + } + }, + "aggs": { + "specific_org_rcn_values": { + "terms": { + "field": "organisationID", + "size": 1000 + } + } + } +} + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_horizon_europe_organizations/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "size": 0, + "query": { + "match": { + "name": { + "query": "Essen", + "fuzziness": "AUTO" + } + } + }, + "aggs": { + "distinct_matched_names": { + "terms": { + "field": "name.keyword", + "size": 100 + } + } + } +} + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_fp7_organizations/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "size": 0, + "query": { + "match": { + "name": { + "query": "Essen", + "fuzziness": "AUTO" + } + } + }, + "aggs": { + "distinct_matched_names": { + "terms": { + "field": "name.keyword", + "size": 100 + } + } + } +} + ### GET https://inse.nes.uni-due.de/elastic/projects_dfg_all/_search Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== @@ -337,6 +519,37 @@ Content-Type: application/json # } # } +### +GET https://inse.nes.uni-due.de/elastic/projects_dfg_all/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "query": { + "bool": { + "should": [ + { + "wildcard": { + "title.keyword": { + "value": "*generic*", + "case_insensitive": true + } + } + }, + { + "wildcard": { + "Thema.keyword": { + "value": "*generic*", + "case_insensitive": true + } + } + } + ] + } + } +} + + ### GET https://inse.nes.uni-due.de/elastic/projects_dfg_all/_mapping Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 289630f9..a8e4f29f 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -4,6 +4,7 @@ README.md api.base.service.ts api.module.ts api/api.ts +api/companyConnections.service.ts api/funding.service.ts api/iNSEAccountService.service.ts api/iNSEService.service.ts @@ -38,12 +39,16 @@ model/autocompleteResponseResultsInner.ts model/award.ts model/bodyCreateUser.ts model/bundProject.ts +model/bundProjectDetails.ts model/bundProjectPage.ts model/careerMetrics.ts -model/categoryNested.ts model/collaborationNetwork.ts model/collaborationNetworkEdge.ts model/collaborationNetworkNodeType.ts +model/companyConnection.ts +model/companyConnectionsResponse.ts +model/cordisEuProject.ts +model/cordisEuProjectPage.ts model/costUsd.ts model/customAuthor.ts model/customAuthorsListResponse.ts @@ -51,15 +56,15 @@ model/dehydratedAuthor.ts model/dehydratedFunder.ts model/dehydratedInstitution.ts model/dehydratedSource.ts +model/dfgProjectDetails.ts model/dfgProjectPage.ts model/dfgProjectSummary.ts -model/displayCodeSplittedNested.ts -model/euProject.ts -model/euProjectPage.ts model/filterInformation.ts model/filterProperties.ts model/funderByAuthor.ts model/fundersByAuthorResponse.ts +model/fundingProject.ts +model/fundingProjectPage.ts model/fwci.ts model/groupByResult.ts model/hTTPValidationError.ts @@ -75,30 +80,37 @@ model/institutionsListResponse.ts model/item.ts model/itemCreate.ts model/itemPage.ts -model/keywordNested.ts +model/keywords.ts model/latitude.ts model/location.ts model/longitude.ts +model/matchedOfficer.ts model/meta.ts model/model2YrMeanCitedness.ts model/models.ts model/openAccess.ts -model/organizationNested.ts model/personBio.ts -model/programmeNested.ts +model/projectType.ts +model/projectsFilteringProperties.ts +model/projectsSortBy.ts model/publicationDetailByFunder.ts model/publicationIdsByAuthorPosition.ts model/publicationsByAuthorResponse.ts +model/rankingResponse.ts model/score.ts +model/sortDirection.ts model/topic.ts model/topicCount.ts model/topicDomain.ts model/topicField.ts model/topicIds.ts model/topicSubfield.ts +model/topics.ts model/topicsByTime.ts model/topicsByYear.ts model/topicsListResponse.ts +model/universityRanking.ts +model/universityTopicData.ts model/user.ts model/validationError.ts model/validationErrorLocInner.ts @@ -122,6 +134,7 @@ model/workTopicInformation.ts model/workTopicSubfield.ts model/worksFilterProperties.ts model/worksListResponse.ts +model/yearlyData.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 7a04a0b0..eb0b53f3 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -1,3 +1,5 @@ +export * from './companyConnections.service'; +import { CompanyConnectionsService } from './companyConnections.service'; export * from './funding.service'; import { FundingService } from './funding.service'; export * from './iNSEAccountService.service'; @@ -18,10 +20,8 @@ export * from './topics.service'; import { TopicsService } from './topics.service'; export * from './works.service'; import { WorksService } from './works.service'; -export * from './company-connections.service'; -import { CompanyConnectionsService } from './company-connections.service'; -export * from './company-connections.serviceInterface'; export const APIS = [ + CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, @@ -32,5 +32,4 @@ export const APIS = [ ProjectsService, TopicsService, WorksService, - CompanyConnectionsService, ]; diff --git a/webapp/src/app/api/api/company-connections.serviceInterface.ts b/webapp/src/app/api/api/company-connections.serviceInterface.ts deleted file mode 100644 index f5001758..00000000 --- a/webapp/src/app/api/api/company-connections.serviceInterface.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 { HttpHeaders } from '@angular/common/http'; - -import { Observable } from 'rxjs'; - -import { CompanyConnectionsResponse } from '../model/models'; -import { HTTPValidationError } from '../model/models'; - -import { Configuration } from '../configuration'; - -export interface CompanyConnectionsServiceInterface { - defaultHeaders: HttpHeaders; - configuration: Configuration; - - /** - * Get possible company connections by OpenAlex author ID. - * - * @endpoint get /api/inse-service/authors/{author_id}/company-connections - * @param authorId - */ - getCompanyConnectionsByAuthor( - authorId: string, - extraHttpRequestParams?: any, - ): Observable; -} diff --git a/webapp/src/app/api/api/company-connections.service.ts b/webapp/src/app/api/api/companyConnections.service.ts similarity index 92% rename from webapp/src/app/api/api/company-connections.service.ts rename to webapp/src/app/api/api/companyConnections.service.ts index b21e9556..6ad850ea 100644 --- a/webapp/src/app/api/api/company-connections.service.ts +++ b/webapp/src/app/api/api/companyConnections.service.ts @@ -23,23 +23,19 @@ import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; // @ts-ignore -import { CompanyConnectionsResponse } from '../model/company-connections-response'; +import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse'; // @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 { CompanyConnectionsServiceInterface } from './company-connections.serviceInterface'; @Injectable({ providedIn: 'root', }) -export class CompanyConnectionsService - extends BaseService - implements CompanyConnectionsServiceInterface -{ +export class CompanyConnectionsService extends BaseService { constructor( protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string | string[], diff --git a/webapp/src/app/api/api/institutions.service.ts b/webapp/src/app/api/api/institutions.service.ts index b837e00e..8b27a539 100644 --- a/webapp/src/app/api/api/institutions.service.ts +++ b/webapp/src/app/api/api/institutions.service.ts @@ -32,6 +32,8 @@ import { Institution } from '../model/institution'; import { InstitutionPage } from '../model/institutionPage'; // @ts-ignore import { InstitutionsListResponse } from '../model/institutionsListResponse'; +// @ts-ignore +import { RankingResponse } from '../model/rankingResponse'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -293,6 +295,142 @@ export class InstitutionsService extends BaseService { ); } + /** + * Returns data for the University Ranking Dashboard. + * @endpoint get /api/inse-service/university-rankings + * @param topic Research topic (e.g., \'Artificial Intelligence\') + * @param metric Metric to rank by + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getRankingsApiInseServiceUniversityRankingsGet( + topic: + | 'Artificial Intelligence' + | 'Quantum Computing' + | 'Renewable Energy' + | 'Biotechnology', + metric?: 'publications' | 'citations', + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getRankingsApiInseServiceUniversityRankingsGet( + topic: + | 'Artificial Intelligence' + | 'Quantum Computing' + | 'Renewable Energy' + | 'Biotechnology', + metric?: 'publications' | 'citations', + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getRankingsApiInseServiceUniversityRankingsGet( + topic: + | 'Artificial Intelligence' + | 'Quantum Computing' + | 'Renewable Energy' + | 'Biotechnology', + metric?: 'publications' | 'citations', + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getRankingsApiInseServiceUniversityRankingsGet( + topic: + | 'Artificial Intelligence' + | 'Quantum Computing' + | 'Renewable Energy' + | 'Biotechnology', + metric?: 'publications' | 'citations', + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (topic === null || topic === undefined) { + throw new Error( + 'Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + topic, + 'topic', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + metric, + 'metric', + ); + + 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/university-rankings`; + 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/inse-service/institutions diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 4c8af35e..1e359d7c 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -22,16 +22,30 @@ import { import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; +// @ts-ignore +import { BundProjectDetails } from '../model/bundProjectDetails'; // @ts-ignore import { BundProjectPage } from '../model/bundProjectPage'; // @ts-ignore +import { CordisEuProjectPage } from '../model/cordisEuProjectPage'; +// @ts-ignore +import { DfgProjectDetails } from '../model/dfgProjectDetails'; +// @ts-ignore import { DfgProjectPage } from '../model/dfgProjectPage'; // @ts-ignore -import { EuProjectPage } from '../model/euProjectPage'; +import { FundingProjectPage } from '../model/fundingProjectPage'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore import { InstitutionFunderSummary } from '../model/institutionFunderSummary'; +// @ts-ignore +import { ProjectType } from '../model/projectType'; +// @ts-ignore +import { ProjectsFilteringProperties } from '../model/projectsFilteringProperties'; +// @ts-ignore +import { ProjectsSortBy } from '../model/projectsSortBy'; +// @ts-ignore +import { SortDirection } from '../model/sortDirection'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -50,278 +64,6 @@ export class ProjectsService extends BaseService { super(basePath, configuration); } - /** - * Get funding over time for bund projects. - * Returns the funding over time for bund projects associated with the specified institution. - * @endpoint get /api/projects/institution/bund/funding-over-time - * @param institutionId The institution ID to filter by. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getBundFundingOverTime( - institutionId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getBundFundingOverTime( - institutionId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getBundFundingOverTime( - institutionId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getBundFundingOverTime( - institutionId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (institutionId === null || institutionId === undefined) { - throw new Error( - 'Required parameter institutionId was null or undefined when calling getBundFundingOverTime.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - institutionId, - 'institution_id', - ); - - 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/projects/institution/bund/funding-over-time`; - 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 bund projects. - * Returns a page of bund projects based on the provided pagination parameters and optional institution filter. - * @endpoint get /api/projects/institution/bund/search - * @param institutionId The institution ID to filter by. - * @param topic The topic to filter by. - * @param page The page number. - * @param size The page size. - * @param sortBy The field to sort by. - * @param sortDirection The sort direction (asc or desc). - * @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 getBundProjects( - institutionId: string, - topic?: string, - page?: number, - size?: number, - sortBy?: string, - sortDirection?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getBundProjects( - institutionId: string, - topic?: string, - page?: number, - size?: number, - sortBy?: string, - sortDirection?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getBundProjects( - institutionId: string, - topic?: string, - page?: number, - size?: number, - sortBy?: string, - sortDirection?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getBundProjects( - institutionId: string, - topic?: string, - page?: number, - size?: number, - sortBy?: string, - sortDirection?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (institutionId === null || institutionId === undefined) { - throw new Error( - 'Required parameter institutionId was null or undefined when calling getBundProjects.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - institutionId, - 'institution_id', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - topic, - 'topic', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - size, - 'size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortBy, - 'sort_by', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortDirection, - 'sort_direction', - ); - - 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/projects/institution/bund/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, - }, - ); - } - /** * Get DFG projects. * Returns a page of DFG projects based on the provided pagination parameters and optional institution filter. @@ -484,25 +226,15 @@ export class ProjectsService extends BaseService { } /** - * Get EU projects. - * Returns a page of EU projects based on the provided pagination parameters and optional institution filter. - * @endpoint get /api/projects/institution/eu/search - * @param institutionId The institution ID to filter by. - * @param topic The topic to filter by. - * @param page The page number. - * @param size The page size. - * @param sortBy The field to sort by. - * @param sortDirection The sort direction (asc or desc). + * Get funding over time for bund projects. + * Returns the funding over time for bund projects associated with the specified institution. + * @endpoint get /api/projects/institution/bund/funding-over-time + * @param rawOaInstitutionId The institution ID to filter by. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getEuProjects( - institutionId: string, - topic?: string, - page?: number, - size?: number, - sortBy?: string, - sortDirection?: string, + public getInstitutionBundProjectsFundingOverTime( + rawOaInstitutionId: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -510,14 +242,9 @@ export class ProjectsService extends BaseService { context?: HttpContext; transferCache?: boolean; }, - ): Observable; - public getEuProjects( - institutionId: string, - topic?: string, - page?: number, - size?: number, - sortBy?: string, - sortDirection?: string, + ): Observable; + public getInstitutionBundProjectsFundingOverTime( + rawOaInstitutionId: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -525,14 +252,9 @@ export class ProjectsService extends BaseService { context?: HttpContext; transferCache?: boolean; }, - ): Observable>; - public getEuProjects( - institutionId: string, - topic?: string, - page?: number, - size?: number, - sortBy?: string, - sortDirection?: string, + ): Observable>; + public getInstitutionBundProjectsFundingOverTime( + rawOaInstitutionId: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -540,14 +262,9 @@ export class ProjectsService extends BaseService { context?: HttpContext; transferCache?: boolean; }, - ): Observable>; - public getEuProjects( - institutionId: string, - topic?: string, - page?: number, - size?: number, - sortBy?: string, - sortDirection?: string, + ): Observable>; + public getInstitutionBundProjectsFundingOverTime( + rawOaInstitutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -556,23 +273,696 @@ export class ProjectsService extends BaseService { transferCache?: boolean; }, ): Observable { - if (institutionId === null || institutionId === undefined) { + if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) { throw new Error( - 'Required parameter institutionId was null or undefined when calling getEuProjects.', + 'Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionBundProjectsFundingOverTime.', ); } let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); localVarQueryParameters = this.addToHttpParams( localVarQueryParameters, - institutionId, - 'institution_id', + rawOaInstitutionId, + 'raw_oa_institution_id', ); + + 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/projects/institution/bund/funding-over-time`; + 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 over time for EU projects. + * Returns the funding over time for EU projects associated with the specified institution. + * @endpoint get /api/projects/institution/eu/funding-over-time + * @param rawOaInstitutionId The institution ID to filter by. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInstitutionCordisEuProjectsFundingOverTime( + rawOaInstitutionId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getInstitutionCordisEuProjectsFundingOverTime( + rawOaInstitutionId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getInstitutionCordisEuProjectsFundingOverTime( + rawOaInstitutionId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getInstitutionCordisEuProjectsFundingOverTime( + rawOaInstitutionId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) { + throw new Error( + 'Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionCordisEuProjectsFundingOverTime.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); localVarQueryParameters = this.addToHttpParams( localVarQueryParameters, - topic, - 'topic', + rawOaInstitutionId, + 'raw_oa_institution_id', ); + + 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/projects/institution/eu/funding-over-time`; + 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 a single BUND project. + * Returns a single BUND project based on its ID. + * @endpoint get /api/projects/bund/{id} + * @param id The ID of the BUND project to retrieve. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getSingleBundProject( + id: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getSingleBundProject( + id: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getSingleBundProject( + id: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getSingleBundProject( + id: 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 getSingleBundProject.', + ); + } + + 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/projects/bund/${this.configuration.encodeParam({ name: 'id', value: id, 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, + }, + ); + } + + /** + * Get a single DFG project. + * Returns a single DFG project based on its ID. + * @endpoint get /api/projects/dfg/{id} + * @param id The ID of the DFG project to retrieve. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getSingleDfgProject( + id: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getSingleDfgProject( + id: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getSingleDfgProject( + id: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getSingleDfgProject( + id: 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 getSingleDfgProject.', + ); + } + + 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/projects/dfg/${this.configuration.encodeParam({ name: 'id', value: id, 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, + }, + ); + } + + /** + * Get bund projects. + * Returns a page of bund projects based on the provided pagination parameters and optional institution filter. + * @endpoint post /api/projects/institution/bund/search + * @param projectsFilteringProperties + * @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 searchBundProjects( + projectsFilteringProperties: ProjectsFilteringProperties, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchBundProjects( + projectsFilteringProperties: ProjectsFilteringProperties, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchBundProjects( + projectsFilteringProperties: ProjectsFilteringProperties, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchBundProjects( + projectsFilteringProperties: ProjectsFilteringProperties, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if ( + projectsFilteringProperties === null || + projectsFilteringProperties === undefined + ) { + throw new Error( + 'Required parameter projectsFilteringProperties was null or undefined when calling searchBundProjects.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/projects/institution/bund/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: projectsFilteringProperties, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Get EU projects. + * Returns a page of EU projects based on the provided pagination parameters and optional institution filter. + * @endpoint post /api/projects/institution/eu/search + * @param projectsFilteringProperties + * @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 searchCordisEuProjects( + projectsFilteringProperties: ProjectsFilteringProperties, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchCordisEuProjects( + projectsFilteringProperties: ProjectsFilteringProperties, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchCordisEuProjects( + projectsFilteringProperties: ProjectsFilteringProperties, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchCordisEuProjects( + projectsFilteringProperties: ProjectsFilteringProperties, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if ( + projectsFilteringProperties === null || + projectsFilteringProperties === undefined + ) { + throw new Error( + 'Required parameter projectsFilteringProperties was null or undefined when calling searchCordisEuProjects.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/projects/institution/eu/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: projectsFilteringProperties, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Search projects across all funders. + * Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter. + * @endpoint get /api/projects/search + * @param page The page number. + * @param size The page size. + * @param selectedProjectTypes The set of project types to filter by (e.g., \'bund\', \'eu\', \'dfg\'). If not provided, projects of all types will be included. + * @param title The title to filter by. + * @param sortBy The field to sort by. + * @param sortDirection The sort direction (asc or desc). + * @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 searchProjects( + page?: number, + size?: number, + selectedProjectTypes?: Set, + title?: string, + sortBy?: ProjectsSortBy, + sortDirection?: SortDirection, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchProjects( + page?: number, + size?: number, + selectedProjectTypes?: Set, + title?: string, + sortBy?: ProjectsSortBy, + sortDirection?: SortDirection, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchProjects( + page?: number, + size?: number, + selectedProjectTypes?: Set, + title?: string, + sortBy?: ProjectsSortBy, + sortDirection?: SortDirection, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchProjects( + page?: number, + size?: number, + selectedProjectTypes?: Set, + title?: string, + sortBy?: ProjectsSortBy, + sortDirection?: SortDirection, + 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, page, @@ -583,6 +973,20 @@ export class ProjectsService extends BaseService { size, 'size', ); + if (selectedProjectTypes) { + selectedProjectTypes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'selected_project_types', + ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + title, + 'title', + ); localVarQueryParameters = this.addToHttpParams( localVarQueryParameters, sortBy, @@ -624,9 +1028,9 @@ export class ProjectsService extends BaseService { } } - let localVarPath = `/api/projects/institution/eu/search`; + let localVarPath = `/api/projects/search`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( + return this.httpClient.request( 'get', `${basePath}${localVarPath}`, { diff --git a/webapp/src/app/api/model/bundProjectDetails.ts b/webapp/src/app/api/model/bundProjectDetails.ts new file mode 100644 index 00000000..b61df06b --- /dev/null +++ b/webapp/src/app/api/model/bundProjectDetails.ts @@ -0,0 +1,55 @@ +/** + * 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. + */ + +/** + * Clean summary model for a Bund (federal) project, consolidating all fields into semantic English names with proper native types. + */ +export interface BundProjectDetails { + /** + * The ID of the Bund project + */ + id: string; + funding_reference?: string | null; + title?: string | null; + description?: string | null; + joint_project?: string | null; + funding_type?: string | null; + funding_profile?: string | null; + funding_amount?: number | null; + funding_start_date?: string | null; + funding_end_date?: string | null; + duration?: string | null; + performance_plan_code?: string | null; + performance_plan_fullname?: string | null; + executing_agency?: string | null; + funding_recipient?: string | null; + project_agency?: string | null; + project_agency_fullname?: string | null; + department?: string | null; + department_fullname?: string | null; + division?: string | null; + location?: string | null; + municipality?: string | null; + state?: string | null; + country?: string | null; + municipality_code?: string | null; + publication_date?: string | null; + is_new?: boolean | null; + record_date?: string | null; + unix_timestamp?: number | null; + /** + * All persons associated with the Bund project (from nested Arb object) + */ + associated_persons?: Array; + /** + * All institutions associated with the Bund project + */ + institutions?: Array; +} diff --git a/webapp/src/app/api/model/categoryNested.ts b/webapp/src/app/api/model/categoryNested.ts deleted file mode 100644 index 2e92a624..00000000 --- a/webapp/src/app/api/model/categoryNested.ts +++ /dev/null @@ -1,24 +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 { DisplayCodeSplittedNested } from './displayCodeSplittedNested'; - -export interface CategoryNested { - category?: string | null; - code?: string | null; - display_code?: string | null; - /** - * A tokenized hierarchy breakdown of the display code represented as an array of strings. - */ - display_code_splitted?: Array; - /** - * Granular, nested breakdowns of the split parts of the display code. - */ - display_code_splitted_nested?: Array; -} diff --git a/webapp/src/app/api/model/company-connection.ts b/webapp/src/app/api/model/companyConnection.ts similarity index 92% rename from webapp/src/app/api/model/company-connection.ts rename to webapp/src/app/api/model/companyConnection.ts index 0eb1fa5b..2824c543 100644 --- a/webapp/src/app/api/model/company-connection.ts +++ b/webapp/src/app/api/model/companyConnection.ts @@ -7,7 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { MatchedOfficer } from './matched-officer'; +import { MatchedOfficer } from './matchedOfficer'; export interface CompanyConnection { company_number?: string | null; diff --git a/webapp/src/app/api/model/company-connections-response.ts b/webapp/src/app/api/model/companyConnectionsResponse.ts similarity index 83% rename from webapp/src/app/api/model/company-connections-response.ts rename to webapp/src/app/api/model/companyConnectionsResponse.ts index 0af604f9..f4f5f42f 100644 --- a/webapp/src/app/api/model/company-connections-response.ts +++ b/webapp/src/app/api/model/companyConnectionsResponse.ts @@ -7,14 +7,14 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { CompanyConnection } from './company-connection'; +import { CompanyConnection } from './companyConnection'; export interface CompanyConnectionsResponse { author_id: string; display_name?: string | null; is_ude_author: boolean; institution_scope?: string | null; - matching_institutions?: Array; + matching_institutions?: Array; matching_method?: string | null; company_count: number; has_more_results: boolean; diff --git a/webapp/src/app/api/model/cordisEuProject.ts b/webapp/src/app/api/model/cordisEuProject.ts new file mode 100644 index 00000000..8d408ad6 --- /dev/null +++ b/webapp/src/app/api/model/cordisEuProject.ts @@ -0,0 +1,39 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Keywords } from './keywords'; +import { Topics } from './topics'; + +export interface CordisEuProject { + /** + * Unique identifier for the project, typically the CORDIS ID + */ + id: string; + rcn?: string | null; + acronym?: string | null; + title?: string | null; + objective?: string | null; + frameworkProgramme?: string | null; + fundingScheme?: string | null; + legalBasis?: string | null; + masterCall?: string | null; + subCall?: string | null; + topics?: Topics | null; + nature?: string | null; + status?: string | null; + ecMaxContribution?: number | null; + totalCost?: number | null; + startDate?: string | null; + endDate?: string | null; + ecSignatureDate?: string | null; + contentUpdateDate?: string | null; + grantDoi?: string | null; + humanValidated?: boolean | null; + keywords?: Keywords | null; +} diff --git a/webapp/src/app/api/model/cordisEuProjectPage.ts b/webapp/src/app/api/model/cordisEuProjectPage.ts new file mode 100644 index 00000000..8dc900f7 --- /dev/null +++ b/webapp/src/app/api/model/cordisEuProjectPage.ts @@ -0,0 +1,29 @@ +/** + * 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 { CordisEuProject } from './cordisEuProject'; + +export interface CordisEuProjectPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + /** + * The CORDIS EU projects on this page. + */ + elements?: Array; +} diff --git a/webapp/src/app/api/model/dfgProjectDetails.ts b/webapp/src/app/api/model/dfgProjectDetails.ts new file mode 100644 index 00000000..58ece5f7 --- /dev/null +++ b/webapp/src/app/api/model/dfgProjectDetails.ts @@ -0,0 +1,39 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Clean summary model for a DFG project, consolidating all person roles and institution references into unified lists. + */ +export interface DfgProjectDetails { + /** + * The ID of the DFG project + */ + id: string; + link?: string | null; + title?: string | null; + description?: string | null; + project_identifier?: string | null; + funding_start_date?: string | null; + funding_end_date?: string | null; + dfg_procedure?: string | null; + subject_area?: string | null; + funding_type?: string | null; + international_reference?: string | null; + website?: string | null; + /** + * All persons associated with the DFG project (any role) + */ + associated_persons?: Array; + /** + * All institutions associated with the DFG project + */ + institutions?: Array; + subproject_of?: string | null; +} diff --git a/webapp/src/app/api/model/euProject.ts b/webapp/src/app/api/model/euProject.ts deleted file mode 100644 index 66469d1f..00000000 --- a/webapp/src/app/api/model/euProject.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 { ProgrammeNested } from './programmeNested'; -import { KeywordNested } from './keywordNested'; -import { OrganizationNested } from './organizationNested'; -import { CategoryNested } from './categoryNested'; - -export interface EuProject { - acronym?: string | null; - /** - * Structured lists of classification categories and taxonomy mappings assigned to the project. - */ - categories_nested?: Array; - doc_number?: string | null; - doi?: string | null; - ec_max_contribution?: string | null; - end_date?: string | null; - funding_end?: string | null; - funding_start?: string | null; - id?: string | null; - keywords?: string | null; - /** - * Strictly tokenized and isolated keywords nested for targeted search engine aggregations. - */ - keywords_nested?: Array; - link?: string | null; - objective?: string | null; - /** - * The full roster of academic, public, or private organizations participating in the project consortium. - */ - organization_nested?: Array; - /** - * The nested historical line of EU funding frameworks and structural grants supporting this project. - */ - programme_nested?: Array; - source?: string | null; - start_date?: string | null; - status?: string | null; - teaser?: string | null; - title?: string | null; - total_cost?: string | null; -} diff --git a/webapp/src/app/api/model/fundingProject.ts b/webapp/src/app/api/model/fundingProject.ts new file mode 100644 index 00000000..a62bd06c --- /dev/null +++ b/webapp/src/app/api/model/fundingProject.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 { ProjectType } from './projectType'; + +export interface FundingProject { + /** + * The type of the project. + */ + type: ProjectType; + /** + * The unique identifier of the project. + */ + id: string; + title?: string | null; + start_date?: string | null; + end_date?: string | null; + funding_amount?: number | null; +} +export namespace FundingProject {} diff --git a/webapp/src/app/api/model/euProjectPage.ts b/webapp/src/app/api/model/fundingProjectPage.ts similarity index 71% rename from webapp/src/app/api/model/euProjectPage.ts rename to webapp/src/app/api/model/fundingProjectPage.ts index 276e0b06..e0996525 100644 --- a/webapp/src/app/api/model/euProjectPage.ts +++ b/webapp/src/app/api/model/fundingProjectPage.ts @@ -7,9 +7,9 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { EuProject } from './euProject'; +import { FundingProject } from './fundingProject'; -export interface EuProjectPage { +export interface FundingProjectPage { /** * The current page number. */ @@ -23,7 +23,7 @@ export interface EuProjectPage { */ total?: number; /** - * The EU projects on this page. + * The funding projects on this page. */ - elements?: Array; + elements?: Array; } diff --git a/webapp/src/app/api/model/institutionFunderSummary.ts b/webapp/src/app/api/model/institutionFunderSummary.ts index eb55e900..cf15754a 100644 --- a/webapp/src/app/api/model/institutionFunderSummary.ts +++ b/webapp/src/app/api/model/institutionFunderSummary.ts @@ -7,12 +7,13 @@ * https://openapi-generator.tech * Do not edit the class manually. */ +import { ProjectType } from './projectType'; export interface InstitutionFunderSummary { /** * The type of funding data (e.g., \'bund\', \'eu\', \'dfg\'). */ - type: InstitutionFunderSummary.TypeEnum; + type: ProjectType; /** * A dictionary mapping years to total funding amounts for that year. */ @@ -22,11 +23,4 @@ export interface InstitutionFunderSummary { */ annual_average_over_period?: number; } -export namespace InstitutionFunderSummary { - export const TypeEnum = { - Bund: 'bund', - Eu: 'eu', - Dfg: 'dfg', - } as const; - export type TypeEnum = (typeof TypeEnum)[keyof typeof TypeEnum]; -} +export namespace InstitutionFunderSummary {} diff --git a/webapp/src/app/api/model/displayCodeSplittedNested.ts b/webapp/src/app/api/model/keywords.ts similarity index 71% rename from webapp/src/app/api/model/displayCodeSplittedNested.ts rename to webapp/src/app/api/model/keywords.ts index 8d7317dc..d93b5fe0 100644 --- a/webapp/src/app/api/model/displayCodeSplittedNested.ts +++ b/webapp/src/app/api/model/keywords.ts @@ -8,6 +8,7 @@ * Do not edit the class manually. */ -export interface DisplayCodeSplittedNested { - single_display_code?: string | null; -} +/** + * Keywords associated with the project + */ +export interface Keywords {} diff --git a/webapp/src/app/api/model/matched-officer.ts b/webapp/src/app/api/model/matchedOfficer.ts similarity index 100% rename from webapp/src/app/api/model/matched-officer.ts rename to webapp/src/app/api/model/matchedOfficer.ts diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 7cbf91a8..60006d17 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -18,12 +18,16 @@ export * from './autocompleteResponseResultsInner'; export * from './award'; export * from './bodyCreateUser'; export * from './bundProject'; +export * from './bundProjectDetails'; export * from './bundProjectPage'; export * from './careerMetrics'; -export * from './categoryNested'; export * from './collaborationNetwork'; export * from './collaborationNetworkEdge'; export * from './collaborationNetworkNodeType'; +export * from './companyConnection'; +export * from './companyConnectionsResponse'; +export * from './cordisEuProject'; +export * from './cordisEuProjectPage'; export * from './costUsd'; export * from './customAuthor'; export * from './customAuthorsListResponse'; @@ -31,15 +35,15 @@ export * from './dehydratedAuthor'; export * from './dehydratedFunder'; export * from './dehydratedInstitution'; export * from './dehydratedSource'; +export * from './dfgProjectDetails'; export * from './dfgProjectPage'; export * from './dfgProjectSummary'; -export * from './displayCodeSplittedNested'; -export * from './euProject'; -export * from './euProjectPage'; export * from './filterInformation'; export * from './filterProperties'; export * from './funderByAuthor'; export * from './fundersByAuthorResponse'; +export * from './fundingProject'; +export * from './fundingProjectPage'; export * from './fwci'; export * from './groupByResult'; export * from './hTTPValidationError'; @@ -55,37 +59,41 @@ export * from './institutionsListResponse'; export * from './item'; export * from './itemCreate'; export * from './itemPage'; -export * from './keywordNested'; +export * from './keywords'; export * from './latitude'; export * from './location'; export * from './longitude'; +export * from './matchedOfficer'; export * from './meta'; export * from './model2YrMeanCitedness'; export * from './openAccess'; -export * from './organizationNested'; export * from './personBio'; -export * from './programmeNested'; +export * from './projectType'; +export * from './projectsFilteringProperties'; +export * from './projectsSortBy'; export * from './publicationDetailByFunder'; export * from './publicationIdsByAuthorPosition'; export * from './publicationsByAuthorResponse'; +export * from './rankingResponse'; export * from './score'; +export * from './sortDirection'; export * from './topic'; export * from './topicCount'; export * from './topicDomain'; export * from './topicField'; export * from './topicIds'; export * from './topicSubfield'; +export * from './topics'; export * from './topicsByTime'; export * from './topicsByYear'; export * from './topicsListResponse'; +export * from './universityRanking'; +export * from './universityTopicData'; export * from './user'; export * from './validationError'; export * from './validationErrorLocInner'; export * from './value'; export * from './work'; -export * from './company-connection'; -export * from './company-connections-response'; -export * from './matched-officer'; export * from './workBiblio'; export * from './workCitationNormalizedPercentile'; export * from './workCitedByPercentileYear'; @@ -104,3 +112,4 @@ export * from './workTopicInformation'; export * from './workTopicSubfield'; export * from './worksFilterProperties'; export * from './worksListResponse'; +export * from './yearlyData'; diff --git a/webapp/src/app/api/model/organizationNested.ts b/webapp/src/app/api/model/organizationNested.ts deleted file mode 100644 index 8c948d35..00000000 --- a/webapp/src/app/api/model/organizationNested.ts +++ /dev/null @@ -1,18 +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 OrganizationNested { - ec_contribution?: string | null; - id?: string | null; - name?: string | null; - net_ec_contribution?: string | null; - total_cost?: string | null; - organization_type?: string | null; -} diff --git a/webapp/src/app/api/model/projectType.ts b/webapp/src/app/api/model/projectType.ts new file mode 100644 index 00000000..08df30c4 --- /dev/null +++ b/webapp/src/app/api/model/projectType.ts @@ -0,0 +1,16 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export const ProjectType = { + Bund: 'bund', + Eu: 'eu', + Dfg: 'dfg', +} as const; +export type ProjectType = (typeof ProjectType)[keyof typeof ProjectType]; diff --git a/webapp/src/app/api/model/projectsFilteringProperties.ts b/webapp/src/app/api/model/projectsFilteringProperties.ts new file mode 100644 index 00000000..c0cebe63 --- /dev/null +++ b/webapp/src/app/api/model/projectsFilteringProperties.ts @@ -0,0 +1,38 @@ +/** + * 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 { SortDirection } from './sortDirection'; +import { ProjectsSortBy } from './projectsSortBy'; +import { ProjectType } from './projectType'; + +export interface ProjectsFilteringProperties { + /** + * The type of projects to filter by. + */ + project_type: ProjectType; + /** + * The page number for pagination. + */ + page: number; + /** + * The page size for pagination. + */ + size: number; + raw_oa_institution_id?: string | null; + query?: string | null; + /** + * The field to sort by. + */ + sort_by?: ProjectsSortBy; + /** + * The sort direction (asc or desc). + */ + sort_direction?: SortDirection; +} +export namespace ProjectsFilteringProperties {} diff --git a/webapp/src/app/api/model/projectsSortBy.ts b/webapp/src/app/api/model/projectsSortBy.ts new file mode 100644 index 00000000..26400b22 --- /dev/null +++ b/webapp/src/app/api/model/projectsSortBy.ts @@ -0,0 +1,18 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export const ProjectsSortBy = { + Title: 'title', + FundingStart: 'funding_start', + FundingEnd: 'funding_end', + FundingAmount: 'funding_amount', +} as const; +export type ProjectsSortBy = + (typeof ProjectsSortBy)[keyof typeof ProjectsSortBy]; diff --git a/webapp/src/app/api/model/rankingResponse.ts b/webapp/src/app/api/model/rankingResponse.ts new file mode 100644 index 00000000..5be090a2 --- /dev/null +++ b/webapp/src/app/api/model/rankingResponse.ts @@ -0,0 +1,16 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { UniversityRanking } from './universityRanking'; +import { UniversityTopicData } from './universityTopicData'; + +export interface RankingResponse { + timeseries: Array; + rankings: Array; +} diff --git a/webapp/src/app/api/model/sortDirection.ts b/webapp/src/app/api/model/sortDirection.ts new file mode 100644 index 00000000..49933995 --- /dev/null +++ b/webapp/src/app/api/model/sortDirection.ts @@ -0,0 +1,15 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export const SortDirection = { + Asc: 'asc', + Desc: 'desc', +} as const; +export type SortDirection = (typeof SortDirection)[keyof typeof SortDirection]; diff --git a/webapp/src/app/api/model/keywordNested.ts b/webapp/src/app/api/model/topics.ts similarity index 77% rename from webapp/src/app/api/model/keywordNested.ts rename to webapp/src/app/api/model/topics.ts index f52bb734..cf40ff1d 100644 --- a/webapp/src/app/api/model/keywordNested.ts +++ b/webapp/src/app/api/model/topics.ts @@ -8,6 +8,4 @@ * Do not edit the class manually. */ -export interface KeywordNested { - keyword?: string | null; -} +export interface Topics {} diff --git a/webapp/src/app/api/model/universityRanking.ts b/webapp/src/app/api/model/universityRanking.ts new file mode 100644 index 00000000..5c9d0d05 --- /dev/null +++ b/webapp/src/app/api/model/universityRanking.ts @@ -0,0 +1,27 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface UniversityRanking { + rank: number; + university: string; + publications: number; + citations: number; + growth_rate: number; + trend: UniversityRanking.TrendEnum; + is_top_mover: boolean; +} +export namespace UniversityRanking { + export const TrendEnum = { + Up: 'up', + Down: 'down', + Stable: 'stable', + } as const; + export type TrendEnum = (typeof TrendEnum)[keyof typeof TrendEnum]; +} diff --git a/webapp/src/app/api/model/universityTopicData.ts b/webapp/src/app/api/model/universityTopicData.ts new file mode 100644 index 00000000..f5436445 --- /dev/null +++ b/webapp/src/app/api/model/universityTopicData.ts @@ -0,0 +1,25 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { YearlyData } from './yearlyData'; + +export interface UniversityTopicData { + university: string; + topic: UniversityTopicData.TopicEnum; + yearly_data: Array; +} +export namespace UniversityTopicData { + export const TopicEnum = { + ArtificialIntelligence: 'Artificial Intelligence', + QuantumComputing: 'Quantum Computing', + RenewableEnergy: 'Renewable Energy', + Biotechnology: 'Biotechnology', + } as const; + export type TopicEnum = (typeof TopicEnum)[keyof typeof TopicEnum]; +} diff --git a/webapp/src/app/api/model/programmeNested.ts b/webapp/src/app/api/model/yearlyData.ts similarity index 66% rename from webapp/src/app/api/model/programmeNested.ts rename to webapp/src/app/api/model/yearlyData.ts index 98710fdb..d473f13e 100644 --- a/webapp/src/app/api/model/programmeNested.ts +++ b/webapp/src/app/api/model/yearlyData.ts @@ -8,8 +8,8 @@ * Do not edit the class manually. */ -export interface ProgrammeNested { - code?: string | null; - id?: string | null; - programme?: string | null; +export interface YearlyData { + year: number; + publications: number; + citations: number; } diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index e043f52a..32b49d9d 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -5,11 +5,15 @@ import { personListResolver } from './resolvers/person-list.resolver'; import { personBioResolver } from './resolvers/person-bio.resolver'; import { personResolver } from './resolvers/person.resolver'; import { institutionResolver } from './resolvers/institution.resolver'; -import { bundProjectsResolver } from './resolvers/bund-projects.resolver'; -import { euProjectsResolver } from './resolvers/eu-projects.resolver'; +import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver'; import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver'; import { institutionsResolver } from './resolvers/institutions.resolver'; import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.resolver'; +import { dfgSingleProjectResolver } from './resolvers/dfg-single-project-resolver'; +import { bundSingleProjectResolver } from './resolvers/bund-single-project-resolver'; +import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page.resolver'; +import { cordisEuProjectsFundingResolver } from './resolvers/cordis-eu-projects-funding.resolver'; +import { fundingProjectPageResolver } from './resolvers/funding-project-page.resolver'; export const routes: Routes = [ { @@ -86,6 +90,30 @@ export const routes: Routes = [ (mod) => mod.PublicationDetailComponent, ), }, + { + path: 'projects/dfg/:id', + canActivate: [userGuard], + pathMatch: 'full', + loadComponent: () => + import('./modules/person-projects/dfg-details/dfg-details.component').then( + (mod) => mod.DfgDetailsComponent, + ), + resolve: { + dfgSingleProject: dfgSingleProjectResolver, + }, + }, + { + path: 'projects/bund/:id', + canActivate: [userGuard], + pathMatch: 'full', + loadComponent: () => + import('./modules/person-projects/bund-details/bund-details.component').then( + (mod) => mod.BundDetailsComponent, + ), + resolve: { + bundSingleProject: bundSingleProjectResolver, + }, + }, { path: 'person/:id', canActivate: [userGuard], @@ -236,9 +264,10 @@ export const routes: Routes = [ ); }, resolve: { - bundProjectPage: bundProjectsResolver, - euProjectPage: euProjectsResolver, + bundProjectPage: bundProjectPageResolver, bundProjectsFunding: bundProjectsFundingResolver, + cordisEuProjectPage: cordisEuProjectPageResolver, + cordisEuProjectsFunding: cordisEuProjectsFundingResolver, }, runGuardsAndResolvers: (from, to) => { const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; @@ -250,6 +279,31 @@ export const routes: Routes = [ }, ], }, + { + path: 'projects', + canActivate: [userGuard], + loadComponent: () => + import('./modules/projects/projects.component').then( + (mod) => mod.ProjectsComponent, + ), + resolve: { + fundingProjectPage: fundingProjectPageResolver, + }, + runGuardsAndResolvers: (from, to) => { + const keys = [ + 'search', + 'page', + 'size', + 'selected_project_types', + 'sort_by', + 'sorting_order', + ]; + + return keys.some( + (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + ); + }, + }, { path: 'error', loadComponent: () => diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index e69de29b..fbd76a45 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -0,0 +1,39 @@ +
+
+

University Performance Dashboard

+
+ + +
+ + +
+
+
+ +
+
+ +
+ + +
+
diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index e69de29b..f9b4f56b 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -0,0 +1,95 @@ +// src/app/modules/university-ranking/dashboard.component.scss +.dashboard-wrapper { + padding: 2rem; + font-family: 'Inter', sans-serif; + color: #333; + + .dashboard-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 2rem; + border-bottom: 1px solid #eee; + padding-bottom: 1rem; + } + + .content-grid { + display: grid; + grid-template-columns: 2fr 1fr; + gap: 2rem; + + @media (max-width: 1024px) { + grid-template-columns: 1fr; + } + } + + .controls { + display: flex; + gap: 1rem; + + select { + padding: 0.5rem; + border-radius: 4px; + border: 1px solid #ccc; + } + + .toggle-group { + button { + padding: 0.5rem 1rem; + border: 1px solid #0056b3; + background: white; + color: #0056b3; + cursor: pointer; + &:first-child { + border-radius: 4px 0 0 4px; + } + &:last-child { + border-radius: 0 4px 4px 0; + } + &.active { + background: #0056b3; + color: white; + } + } + } + } +} + +// Table styling +.ranking-table { + width: 100%; + border-collapse: collapse; + font-size: 0.9rem; + + th, + td { + padding: 0.75rem; + text-align: left; + border-bottom: 1px solid #f0f0f0; + } + + .top-tier { + background-color: #f8fbff; + font-weight: 600; + } + .positive { + color: #28a745; + } + .negative { + color: #dc3545; + } + .mover-badge { + margin-left: 4px; + font-size: 0.8rem; + } + + .trend-col { + font-weight: bold; + &[data-trend='up'] { + color: #28a745; + } + &[data-trend='down'] { + color: #dc3545; + } + } +} diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 7d31c1db..ef967b09 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -1,10 +1,62 @@ -import { Component } from '@angular/core'; +import { Component, OnInit } from '@angular/core'; +import { UniversityRankingService } from '../university-ranking/services/uni-ranking-service'; +import { UniversityLineChartComponent } from '../university-ranking/uni-line-chart/uni-line-chart.component'; +import { UniversityRankingTableComponent } from '../university-ranking/uni-ranking-table/uni-ranking-table.component'; +import { UniversityTopicData, UniversityRanking } from '../../api'; +export type ResearchTopic = + | 'Artificial Intelligence' + | 'Quantum Computing' + | 'Renewable Energy' + | 'Biotechnology'; +export type DashboardMetric = 'publications' | 'citations'; @Component({ - selector: 'app-dashboard', - imports: [], + selector: 'dashboard', + imports: [UniversityLineChartComponent, UniversityRankingTableComponent], templateUrl: './dashboard.component.html', styleUrl: './dashboard.component.scss', - standalone: true, }) -export class DashboardComponent {} +export class DashboardComponent implements OnInit { + topics: ResearchTopic[] = [ + 'Artificial Intelligence', + 'Quantum Computing', + 'Renewable Energy', + 'Biotechnology', + ]; + selectedTopic: ResearchTopic = 'Artificial Intelligence'; + metric: DashboardMetric = 'publications'; + + rawDataSource: UniversityTopicData[] = []; + computedRankings: UniversityRanking[] = []; + isLoading = false; + + constructor(private dataService: UniversityRankingService) {} + + ngOnInit() { + this.loadData(); + } + + onTopicChange(topic: ResearchTopic) { + this.selectedTopic = topic; + this.loadData(); // Re-fetch as rankings depend on the topic + } + + setMetric(metric: DashboardMetric) { + this.metric = metric; + this.loadData(); // Re-fetch as ranking order changes based on metric + } + + private loadData() { + this.isLoading = true; + this.dataService + .getRankingData(this.selectedTopic, this.metric) + .subscribe((response) => { + // Map backend snake_case properties to frontend camelCase if necessary, + // though OpenAPI Generator usually handles this. + console.log(response); + this.rawDataSource = (response.timeseries as any) || []; + this.computedRankings = (response.rankings as any) || []; + this.isLoading = false; + }); + } +} diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.html b/webapp/src/app/modules/institution-projects/institution-projects.component.html index 609ec083..e4982ec6 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.html +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.html @@ -51,7 +51,7 @@ + [fundings]="[bundProjectsFunding(), cordisEuProjectsFunding()]" /> @@ -71,13 +71,14 @@ @@ -90,6 +91,6 @@ {{ row.funding_end | date: 'dd.MM.yyyy' }} - - {{ row.grant_amount | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} + + {{ row.funding_amount | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.ts b/webapp/src/app/modules/institution-projects/institution-projects.component.ts index 00189559..4f547c61 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.ts +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.ts @@ -12,8 +12,8 @@ import { ActivatedRoute, Router } from '@angular/router'; import { BundProject, BundProjectPage, - EuProject, - EuProjectPage, + CordisEuProject, + CordisEuProjectPage, InstitutionFunderSummary, } from '../../api'; import { MatCardModule } from '@angular/material/card'; @@ -39,7 +39,7 @@ type BundProjectRow = { topic: string; funding_start: Date; funding_end: Date; - grant_amount: number; + funding_amount: number; department: string; }; @@ -47,7 +47,7 @@ type EuProjectRow = { topic: string; funding_start: Date; funding_end: Date; - grant_amount: number; + funding_amount: number; }; @Component({ @@ -74,9 +74,9 @@ type EuProjectRow = { export class InstitutionProjectsComponent implements OnInit { fundingStartTmp = viewChild.required>('fundingStartTmp'); fundingEndTmp = viewChild.required>('fundingEndTmp'); - grantAmountTmp = viewChild.required>('grantAmountTmp'); + fundingAmountTmp = viewChild.required>('fundingAmountTmp'); - euProjectPage = input.required(); + cordisEuProjectPage = input.required(); euProjectColumns: GenericColumn[] = []; euProjectData: EuProjectRow[] = []; @@ -85,19 +85,29 @@ export class InstitutionProjectsComponent implements OnInit { bundProjectData: BundProjectRow[] = []; bundProjectsFunding = input.required(); - bundTotalFunding = computed(() => { const funding = this.bundProjectsFunding(); return Object.values( funding.funding_per_year as Record, ).reduce((sum, yearFunding) => sum + yearFunding, 0); }); - bundAverageAnnualFunding = computed(() => { const funding = this.bundProjectsFunding(); return funding.annual_average_over_period ?? 0; }); + cordisEuProjectsFunding = input.required(); + euTotalFunding = computed(() => { + const funding = this.cordisEuProjectsFunding(); + return Object.values( + funding.funding_per_year as Record, + ).reduce((sum, yearFunding) => sum + yearFunding, 0); + }); + euAverageAnnualFunding = computed(() => { + const funding = this.cordisEuProjectsFunding(); + return funding.annual_average_over_period ?? 0; + }); + urlSortKey = signal(''); urlSortDirection = signal(''); urlSearchTerm = signal(''); @@ -117,7 +127,7 @@ export class InstitutionProjectsComponent implements OnInit { }); effect(() => { - const euPage = this.euProjectPage(); + const euPage = this.cordisEuProjectPage(); if (euPage) { this.euProjectData = euPage.elements ? euPage.elements.map(this.transformEuRow.bind(this)) @@ -164,7 +174,7 @@ export class InstitutionProjectsComponent implements OnInit { readonly selectedPage = computed(() => { if (this.displayedProjects() === 'eu') { - return this.euProjectPage(); + return this.cordisEuProjectPage(); } else { return this.bundProjectPage(); } @@ -185,8 +195,8 @@ export class InstitutionProjectsComponent implements OnInit { ngOnInit(): void { this.euProjectColumns = [ { - id: 'topic', - header: 'Thema', + id: 'title', + header: 'Titel', type: 'accessor', accessorKey: 'topic', }, @@ -205,17 +215,17 @@ export class InstitutionProjectsComponent implements OnInit { cellTemplate: this.fundingEndTmp(), }, { - id: 'grant_amount', + id: 'funding_amount', header: 'Fördersumme', type: 'accessor', - accessorKey: 'grant_amount', - cellTemplate: this.grantAmountTmp(), + accessorKey: 'funding_amount', + cellTemplate: this.fundingAmountTmp(), }, ]; this.bundProjectColumns = [ { id: 'topic', - header: 'Thema', + header: 'Titel', type: 'accessor', accessorKey: 'topic', }, @@ -234,29 +244,23 @@ export class InstitutionProjectsComponent implements OnInit { cellTemplate: this.fundingEndTmp(), }, { - id: 'grant_amount', + id: 'funding_amount', header: 'Fördersumme', type: 'accessor', - accessorKey: 'grant_amount', - cellTemplate: this.grantAmountTmp(), - }, - { - id: 'department', - header: 'Abteilung', - type: 'accessor', - accessorKey: 'department', + accessorKey: 'funding_amount', + cellTemplate: this.fundingAmountTmp(), }, ]; } - transformEuRow(project: EuProject): EuProjectRow { + transformEuRow(project: CordisEuProject): EuProjectRow { return { topic: project.title || '', - funding_start: project.start_date - ? new Date(project.start_date) + funding_start: project.startDate + ? new Date(project.startDate) : new Date(0), - funding_end: project.end_date ? new Date(project.end_date) : new Date(0), - grant_amount: Number(project.total_cost) || 0, + funding_end: project.endDate ? new Date(project.endDate) : new Date(0), + funding_amount: Number(project.totalCost) || 0, }; } @@ -269,7 +273,7 @@ export class InstitutionProjectsComponent implements OnInit { funding_end: project.funding_end ? new Date(project.funding_end) : new Date(0), - grant_amount: project.grant_amount || 0, + funding_amount: project.grant_amount || 0, department: project.department_fullname || '', }; } @@ -288,7 +292,7 @@ export class InstitutionProjectsComponent implements OnInit { selectedTabChange(event: MatTabChangeEvent): void { const tab = ['eu', 'bund'][event.index]; this.router.navigate([], { - queryParams: { project_tab: tab, page: 1, size: 10 }, + queryParams: { project_tab: tab, page: 0, size: 10 }, queryParamsHandling: 'merge', }); } diff --git a/webapp/src/app/modules/institution/institution.component.ts b/webapp/src/app/modules/institution/institution.component.ts index 1a64f762..03ffd347 100644 --- a/webapp/src/app/modules/institution/institution.component.ts +++ b/webapp/src/app/modules/institution/institution.component.ts @@ -36,7 +36,7 @@ export class InstitutionComponent implements OnInit { page: 0, size: 10, search: '', - sort_by: 'topic', + sort_by: 'title', sort_direction: 'asc', }, }, diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index 1ce09684..03c91185 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -25,7 +25,7 @@ {{ person.display_name ?? '' }}

- {{ getDistinguishingId(person) ?? '' }} + {{ getDistinguishingId(person) }}

{{ getStatsString() }} diff --git a/webapp/src/app/modules/person-company-connections/person-company-connections.component.html b/webapp/src/app/modules/person-company-connections/person-company-connections.component.html index 7cb40edc..f4e9453b 100644 --- a/webapp/src/app/modules/person-company-connections/person-company-connections.component.html +++ b/webapp/src/app/modules/person-company-connections/person-company-connections.component.html @@ -40,24 +40,30 @@

@if (graphOptions) { -
-
- -
- +
+ +
} -
+ }

@@ -95,7 +101,7 @@

-
+
Unternehmen Rolle @@ -109,6 +115,7 @@
- + {{ - isCompanyOfficersExpanded(connection) ? '▲' : '▼' + isCompanyOfficersExpanded(connection) + ? 'expand_less' + : 'expand_more' }} - + @if (isCompanyOfficersExpanded(connection)) { - +
} }
@@ -253,7 +262,7 @@
}
-
+ diff --git a/webapp/src/app/modules/person-company-connections/person-company-connections.component.scss b/webapp/src/app/modules/person-company-connections/person-company-connections.component.scss index b051e2a2..91824dd7 100644 --- a/webapp/src/app/modules/person-company-connections/person-company-connections.component.scss +++ b/webapp/src/app/modules/person-company-connections/person-company-connections.component.scss @@ -1,10 +1,8 @@ -$author-color: #5470c6; +$marked-color: #5470c6; +$related-person-color: #4f8df5; $timeline-purple: #7255d9; $timeline-purple-bg: #f6f0ff; -$timeline-green-bg: #effaf3; -$timeline-green-border: #bdebcf; - $timeline-orange-bg: #fff7e8; $timeline-orange-border: #ffd796; $timeline-orange-text: #c67500; @@ -107,7 +105,6 @@ $text-muted: #64718f; .graph-card, .connection-list { - border: 1px solid $card-border; border-radius: 16px; background: #ffffff; box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04); @@ -121,70 +118,45 @@ $text-muted: #64718f; flex-direction: column; } -.graph-toolbar { - flex: 0 0 auto; - padding: 12px 18px 8px; - border-bottom: 1px solid #edf2fb; -} - -.related-toggle { - display: inline-flex; - align-items: center; - gap: 10px; - max-width: 100%; - padding: 0; - border: 0; - background: transparent; - color: $text-main; - cursor: pointer; -} - -.toggle-switch { - position: relative; - flex: 0 0 auto; - width: 44px; - height: 24px; - border-radius: 999px; - background: #dbe5f6; - transition: background 160ms ease; -} - -.toggle-knob { - position: absolute; - top: 3px; - left: 3px; - width: 18px; - height: 18px; - border-radius: 999px; - background: #ffffff; - box-shadow: 0 1px 4px rgba(15, 23, 42, 0.24); - transition: transform 160ms ease; -} - -.related-toggle.active .toggle-switch { - background: #e95590; -} - -.related-toggle.active .toggle-knob { - transform: translateX(20px); -} - -.toggle-text { - min-width: 0; - color: $text-main; - font-size: 13px; - font-weight: 600; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - .graph-stage { + position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; } +.graph-related-persons-button { + position: absolute; + top: 12px; + right: 12px; + z-index: 2; + + width: 50px; + height: 50px; + padding: 0; + + background: transparent; + color: $related-person-color; + box-shadow: none; +} + +.graph-related-persons-button:hover { + background: rgba(84, 112, 198, 0.08); +} + +.graph-related-persons-icon { + width: 51px; + height: 51px; + + font-size: 51px; + line-height: 51px; + font-variation-settings: + 'FILL' 1, + 'wght' 400, + 'GRAD' 0, + 'opsz' 48; +} + .graph { width: 100%; height: 100%; @@ -288,14 +260,6 @@ $text-muted: #64718f; .list-header span, .connection-row span { min-width: 0; -} - -.list-header span { - white-space: normal; -} - -.list-header span, -.connection-row span { justify-self: start; text-align: left; } @@ -322,7 +286,7 @@ $text-muted: #64718f; &.selected { background: #f0f6ff; - box-shadow: inset 3px 0 0 $author-color; + box-shadow: inset 3px 0 0 $marked-color; } &.removed { @@ -343,34 +307,10 @@ $text-muted: #64718f; white-space: nowrap; } -.company-name { - min-width: 0; -} - .company-name { font-weight: 700; } -.detail-value.detail-status { - display: block; - margin: 0; - padding: 0; - border: 0; - border-radius: 0; - background: transparent; - font-size: 13px; - font-weight: 700; - line-height: 1.35; -} - -.detail-value.detail-status--active { - color: #218354; -} - -.detail-value.detail-status--removed { - color: #6b7280; -} - .role-value { width: auto; padding-left: 8px; @@ -422,6 +362,26 @@ $text-muted: #64718f; line-height: 1.35; } +.detail-value.detail-status { + display: block; + margin: 0; + padding: 0; + border: 0; + border-radius: 0; + background: transparent; + font-size: 13px; + font-weight: 700; + line-height: 1.35; +} + +.detail-value.detail-status--active { + color: #218354; +} + +.detail-value.detail-status--removed { + color: #6b7280; +} + .officers-toggle { display: flex; justify-content: space-between; @@ -441,21 +401,23 @@ $text-muted: #64718f; cursor: pointer; } +.officers-toggle mat-icon { + color: $text-muted; +} + .related-officers { display: flex; flex-direction: column; gap: 6px; margin: 8px 0 0; padding: 0; - list-style: none; } .related-officer { display: grid; - grid-template-columns: minmax(0, 1fr) minmax(0, 0.72fr) 28px; + grid-template-columns: minmax(0, 1fr) minmax(0, 0.72fr) 40px; gap: 12px; align-items: center; - padding-right: 34px; color: $text-main; font-size: 13px; } @@ -466,49 +428,21 @@ $text-muted: #64718f; } .officer-role { - display: block; - max-width: 100%; - min-width: 0; padding-left: 10px; border-left: 4px solid #8a95b3; color: $text-main; font-weight: 600; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; } .officer-open-link { - --mdc-icon-button-state-layer-size: 28px; - --mat-icon-button-state-layer-size: 28px; - justify-self: center; - display: inline-flex; - align-items: center; - justify-content: center; - width: 28px; - height: 28px; - padding: 0; - border-radius: 6px; - color: $author-color; - line-height: 1; -} - -.officer-open-link:hover { - background: rgba(47, 76, 190, 0.08); -} - -.officer-open-link .mat-icon { - width: 20px; - height: 20px; - font-size: 20px; - line-height: 20px; + color: $marked-color; } .officer-open-placeholder { display: block; - width: 28px; - height: 28px; + width: 40px; + height: 40px; } @media (max-width: 1450px) { @@ -553,9 +487,8 @@ $text-muted: #64718f; } .related-officer { - grid-template-columns: minmax(0, 1fr) 28px; + grid-template-columns: minmax(0, 1fr) 40px; gap: 6px 10px; - padding-right: 0; } .officer-role { diff --git a/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts b/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts index 8e7b1c03..742349e8 100644 --- a/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts +++ b/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts @@ -1,7 +1,16 @@ import { CommonModule, LocationStrategy } from '@angular/common'; -import { Component, ElementRef, OnInit, inject } from '@angular/core'; +import { + Component, + ElementRef, + OnInit, + QueryList, + ViewChildren, + inject, +} from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; +import { MatTooltip, MatTooltipModule } from '@angular/material/tooltip'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { EChartsOption } from 'echarts'; @@ -26,7 +35,10 @@ interface RoleLegendItem { MatProgressSpinnerModule, NgxEchartsDirective, MatButtonModule, + MatCardModule, MatIconModule, + MatTooltipModule, + MatTooltip, RouterModule, ], templateUrl: './person-company-connections.component.html', @@ -36,11 +48,9 @@ export class PersonCompanyConnectionsComponent implements OnInit { private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); private readonly locationStrategy = inject(LocationStrategy); - private readonly host = inject(ElementRef); private readonly companyConnectionsApi = inject(CompanyConnectionsService); private readonly graphCompanyLimit = 10; - private readonly searchInstitutionName = 'University of Duisburg-Essen'; private readonly personCategoryIndex = 0; private readonly activeCompanyCategoryIndex = 1; @@ -58,6 +68,22 @@ export class PersonCompanyConnectionsComponent implements OnInit { private readonly relatedPersonColor = '#4f8df5'; private readonly fallbackRoleColor = '#8a95b3'; + private readonly personIconSymbol = this.createAccountCircleSymbol( + this.authorColor, + ); + + private readonly registerPersonIconSymbol = this.createAccountCircleSymbol( + this.relatedPersonColor, + ); + + private readonly activeCompanyIconSymbol = this.createApartmentSymbol( + this.companyActiveColor, + ); + + private readonly removedCompanyIconSymbol = this.createApartmentSymbol( + this.companyRemovedColor, + ); + private readonly roleColors: Record = { Geschäftsführer: '#2678e8', Prokurist: '#39a96b', @@ -81,6 +107,9 @@ export class PersonCompanyConnectionsComponent implements OnInit { expandedOfficersCompanyKey: string | null = null; showRelatedPersons = false; + @ViewChildren('connectionRow', { read: ElementRef }) + private connectionRows!: QueryList>; + get connections(): CompanyConnection[] { return this.data?.connections ?? []; } @@ -216,11 +245,6 @@ export class PersonCompanyConnectionsComponent implements OnInit { this.expandedOfficersCompanyKey = companyKey; } - toggleRelatedPersons(): void { - this.showRelatedPersons = !this.showRelatedPersons; - this.refreshGraph(); - } - onGraphClick(event: any): void { if (event.dataType !== 'node') { return; @@ -253,6 +277,17 @@ export class PersonCompanyConnectionsComponent implements OnInit { ); } + toggleRelatedPersons(tooltip?: MatTooltip): void { + this.showRelatedPersons = !this.showRelatedPersons; + this.refreshGraph(); + + tooltip?.hide(0); + + window.setTimeout(() => { + tooltip?.show(0); + }); + } + private loadCompanyConnections(authorId: string): void { this.loading = true; this.error = false; @@ -309,8 +344,9 @@ export class PersonCompanyConnectionsComponent implements OnInit { id: personNodeId, name: response.display_name || 'Person', category: this.personCategoryIndex, - symbol: 'circle', - symbolSize: 44, + symbol: this.personIconSymbol, + symbolSize: 42, + symbolKeepAspect: true, itemStyle: { color: this.authorColor, }, @@ -335,8 +371,11 @@ export class PersonCompanyConnectionsComponent implements OnInit { category: isRemoved ? this.removedCompanyCategoryIndex : this.activeCompanyCategoryIndex, - symbol: 'roundRect', - symbolSize: [48, 34], + symbol: isRemoved + ? this.removedCompanyIconSymbol + : this.activeCompanyIconSymbol, + symbolSize: 44, + symbolKeepAspect: true, itemStyle: { color: isRemoved ? this.companyRemovedColor : this.companyActiveColor, }, @@ -377,8 +416,9 @@ export class PersonCompanyConnectionsComponent implements OnInit { searchName: relatedOfficer.name, role: relatedRole, category: this.registerPersonCategoryIndex, - symbol: 'circle', - symbolSize: 28, + symbol: this.registerPersonIconSymbol, + symbolSize: 30, + symbolKeepAspect: true, itemStyle: { color: this.relatedPersonColor, }, @@ -412,7 +452,7 @@ export class PersonCompanyConnectionsComponent implements OnInit { roam: true, roamTrigger: 'global', animation: false, - top: 24, + top: 34, left: 20, right: 20, bottom: 64, @@ -444,8 +484,8 @@ export class PersonCompanyConnectionsComponent implements OnInit { left: 'center', orient: 'horizontal', itemGap: 18, - itemWidth: 18, - itemHeight: 14, + itemWidth: 20, + itemHeight: 20, selectedMode: false, textStyle: { color: '#3f4659', @@ -483,31 +523,19 @@ export class PersonCompanyConnectionsComponent implements OnInit { return [ { name: this.personCategoryName, - symbol: 'circle', - itemStyle: { - color: this.authorColor, - }, + symbol: this.personIconSymbol, }, { name: this.activeCompanyCategoryName, - symbol: 'roundRect', - itemStyle: { - color: this.companyActiveColor, - }, + symbol: this.activeCompanyIconSymbol, }, { name: this.removedCompanyCategoryName, - symbol: 'roundRect', - itemStyle: { - color: this.companyRemovedColor, - }, + symbol: this.removedCompanyIconSymbol, }, { name: this.registerPersonCategoryName, - symbol: 'circle', - itemStyle: { - color: this.relatedPersonColor, - }, + symbol: this.registerPersonIconSymbol, }, ]; } @@ -523,40 +551,28 @@ export class PersonCompanyConnectionsComponent implements OnInit { const legendData = [ { name: this.personCategoryName, - icon: 'circle', - itemStyle: { - color: this.authorColor, - }, + icon: this.personIconSymbol, }, ]; if (hasActiveCompany) { legendData.push({ name: this.activeCompanyCategoryName, - icon: 'roundRect', - itemStyle: { - color: this.companyActiveColor, - }, + icon: this.activeCompanyIconSymbol, }); } if (hasRemovedCompany) { legendData.push({ name: this.removedCompanyCategoryName, - icon: 'roundRect', - itemStyle: { - color: this.companyRemovedColor, - }, + icon: this.removedCompanyIconSymbol, }); } if (this.showRelatedPersons) { legendData.push({ name: this.registerPersonCategoryName, - icon: 'circle', - itemStyle: { - color: this.relatedPersonColor, - }, + icon: this.registerPersonIconSymbol, }); } @@ -619,12 +635,10 @@ export class PersonCompanyConnectionsComponent implements OnInit { } getPersonSearchQueryParams(name?: string | null): { - institutionName: string; query: string; page: number; } { return { - institutionName: this.searchInstitutionName, query: name?.trim() ?? '', page: 1, }; @@ -636,19 +650,53 @@ export class PersonCompanyConnectionsComponent implements OnInit { return; } - const rows = Array.from( - this.host.nativeElement.querySelectorAll('.connection-row'), - ) as HTMLElement[]; + const selectedRow = this.connectionRows.find((row) => { + return ( + row.nativeElement.dataset['companyKey'] === this.selectedCompanyKey + ); + }); - for (const row of rows) { - if (row.dataset['companyKey'] === this.selectedCompanyKey) { - row.scrollIntoView({ - block: 'nearest', - behavior: 'smooth', - }); - return; - } - } + selectedRow?.nativeElement.scrollIntoView({ + block: 'nearest', + behavior: 'smooth', + }); }); } + + private createAccountCircleSymbol(color: string): string { + const backgroundPath = + 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z'; + + const foregroundPath = + 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z'; + + const svg = ` + + + + + `; + + return this.toSvgImageSymbol(svg); + } + + private createApartmentSymbol(color: string): string { + const backgroundPath = 'M17 11V3H7v4H3v14h18V11h-4z'; + + const foregroundPath = + 'M17 11V3H7v4H3v14h18V11h-4zM7 19H5v-2h2v2zm0-4H5v-2h2v2zm0-4H5V9h2v2zm4 8H9v-2h2v2zm0-4H9v-2h2v2zm0-4H9V9h2v2zm0-4H9V5h2v2zm4 12h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V9h2v2zm0-4h-2V5h2v2zm4 12h-2v-2h2v2zm0-4h-2v-2h2v2z'; + + const svg = ` + + + + + `; + + return this.toSvgImageSymbol(svg); + } + + private toSvgImageSymbol(svg: string): string { + return `image://data:image/svg+xml;utf8,${encodeURIComponent(svg.trim())}`; + } } 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 65bf5eae..dc6026c8 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 @@ -59,7 +59,7 @@
@@ -110,13 +110,6 @@ {{ maxYear }}
- -
- -
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 e1b43d09..adf3af43 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 @@ -38,7 +38,7 @@ .timeline-header { display: grid; - grid-template-columns: minmax(260px, 1fr) auto minmax(260px, 1fr); + grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: flex-start; gap: 24px; margin-bottom: 28px; @@ -103,6 +103,7 @@ border: 1px solid #dbe5f6; border-radius: 10px; background: #fbfdff; + box-sizing: border-box; } .year-filter-top, 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 3d3ffa2d..31ac9ae8 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.html +++ b/webapp/src/app/modules/person-overview/person-overview.component.html @@ -14,26 +14,6 @@ (topicSelect)="onTimelineTopicSelect($event)" (yearSelect)="onTimelineYearSelect($event)" (loadEarlierYears)="onTimelineLoadEarlierYears()"> -
- @if (loadingWordCloud) { - Themen laden ... - } @else if (wordCloudOptions && sliderMax > 5) { - {{ topN }} Themen -
-
- -
- } @else { - Themen - } -
-
@if (loadingWordCloud) {
Forschungsthemen werden geladen ...
diff --git a/webapp/src/app/modules/person-overview/person-overview.component.scss b/webapp/src/app/modules/person-overview/person-overview.component.scss index 7b40485a..7e0732ce 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.scss +++ b/webapp/src/app/modules/person-overview/person-overview.component.scss @@ -5,91 +5,6 @@ box-sizing: border-box; } -.word-cloud-slider-wrapper { - display: flex; - align-items: center; - justify-content: center; - gap: 0.75rem; - min-height: 86px; -} - -.slider-label { - font-size: 13px; - color: var(--sg-text-muted); - white-space: nowrap; - min-width: 4.5rem; - text-align: right; -} - -.word-cloud-slider { - --accent: #0057ff; - --range-value: 50%; - - position: relative; - width: 160px; - height: 22px; - - .range-track { - position: absolute; - top: 50%; - left: 0; - right: 0; - height: 5px; - transform: translateY(-50%); - border-radius: 999px; - background: linear-gradient( - to right, - var(--accent) 0%, - var(--accent) var(--range-value), - #d8e2f4 var(--range-value), - #d8e2f4 100% - ); - } - - input[type='range'] { - position: absolute; - inset: 0; - width: 100%; - height: 22px; - margin: 0; - appearance: none; - background: transparent; - - &::-webkit-slider-runnable-track, - &::-moz-range-track { - height: 5px; - background: transparent; - border: none; - } - - &::-webkit-slider-thumb { - appearance: none; - width: 15px; - height: 15px; - margin-top: -5px; - border: 2px solid #ffffff; - border-radius: 50%; - background: var(--accent); - box-shadow: - 0 0 0 1px #9ab7ff, - 0 2px 6px rgba(0, 87, 255, 0.22); - cursor: pointer; - } - - &::-moz-range-thumb { - width: 15px; - height: 15px; - border: 2px solid #ffffff; - border-radius: 50%; - background: var(--accent); - box-shadow: - 0 0 0 1px #9ab7ff, - 0 2px 6px rgba(0, 87, 255, 0.22); - cursor: pointer; - } - } -} - .word-cloud-view { min-height: 420px; } 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 57d2275c..5c6c0420 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -54,32 +54,10 @@ export class PersonOverviewComponent implements OnInit { loadingWordCloud = false; wordCloudEmpty = false; - topN = 30; - sliderMax = 50; - - get sliderPercent(): string { - if (this.sliderMax <= 5) return '100%'; - return `${(((this.topN - 5) / (this.sliderMax - 5)) * 100).toFixed(1)}%`; - } - - onTopNChange(event: Event): void { - this.topN = Number((event.target as HTMLInputElement).value); - this.rebuildWordCloud(); - } - - private allTopicData: Array<{ + private rawTopicOccurrences: Array<{ name: string; - value: number; - topicId: string | undefined; - textStyle: { color: string; fontSize: number }; - emphasis: { - textStyle: { - fontSize: number; - color: string; - shadowBlur: number; - shadowColor: string; - }; - }; + topicId: string; + year: number | undefined; }> = []; ngOnInit(): void { @@ -123,6 +101,7 @@ export class PersonOverviewComponent implements OnInit { onTimelineYearRangeChange(range: TimelineYearRange): void { this.timelineStartYear = range.startYear; this.timelineEndYear = range.endYear; + this.rebuildWordCloud(); this.updateTimelineQueryParams( { @@ -308,30 +287,20 @@ export class PersonOverviewComponent implements OnInit { this.timelineEarlierYearsLoadFailed = false; } - private readonly blueShades = [ - '#0057ff', - '#1a6fff', - '#2952d9', - '#3d7cff', - '#1240cc', - '#5a90ff', - '#0044cc', - '#4d85ff', - '#0b4fe0', - '#2563eb', + private readonly timelineColors = [ + '#7255d9', + '#2678e8', + '#39a96b', + '#f59e0b', + '#e0527c', ]; - private topicColor(name: string): string { - const hash = name.split('').reduce((acc, c) => acc + c.charCodeAt(0), 0); - return this.blueShades[hash % this.blueShades.length]; - } - private loadWordCloud(authorId: string): void { if (!authorId || authorId === '0') { this.wordCloudOptions = null; this.wordCloudEmpty = false; this.loadingWordCloud = false; - this.allTopicData = []; + this.rawTopicOccurrences = []; return; } @@ -344,64 +313,28 @@ export class PersonOverviewComponent implements OnInit { .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe({ next: (page) => { - const counts = new Map(); - const nameToId = new Map(); - + this.rawTopicOccurrences = []; page.elements?.forEach((work) => { + const year = work.publication_year ?? undefined; work.topics?.forEach((topic) => { if (topic.display_name && topic.id) { - counts.set( - topic.display_name, - (counts.get(topic.display_name) ?? 0) + 1, - ); - if (!nameToId.has(topic.display_name)) { - nameToId.set(topic.display_name, topic.id); - } + this.rawTopicOccurrences.push({ + name: topic.display_name, + topicId: topic.id, + year, + }); } }); }); - const allValues = Array.from(counts.values()); - const minVal = Math.min(...allValues); - const maxVal = Math.max(...allValues); - const computeSize = (v: number): number => - maxVal === minVal - ? 22 - : Math.round(12 + ((v - minVal) / (maxVal - minVal)) * (32 - 12)); - - this.allTopicData = Array.from(counts.entries()) - .sort((a, b) => b[1] - a[1]) - .map(([name, value]) => { - const fontSize = computeSize(value); - return { - name, - value, - topicId: nameToId.get(name), - textStyle: { color: this.topicColor(name), fontSize }, - emphasis: { - textStyle: { - fontSize: Math.round(fontSize * 1.1), - color: '#101a3d', - shadowBlur: 16, - shadowColor: 'rgba(0, 87, 255, 0.35)', - }, - }, - }; - }); - this.loadingWordCloud = false; - if (this.allTopicData.length === 0) { + if (this.rawTopicOccurrences.length === 0) { this.wordCloudEmpty = true; return; } - this.sliderMax = Math.min(50, this.allTopicData.length); - this.topN = Math.min(30, this.sliderMax); - - setTimeout(() => { - this.rebuildWordCloud(); - }); + setTimeout(() => this.rebuildWordCloud()); }, error: (error) => { console.error('Word cloud could not be loaded.', error); @@ -412,8 +345,57 @@ export class PersonOverviewComponent implements OnInit { } private rebuildWordCloud(): void { - const data = this.allTopicData.slice(0, this.topN); - if (data.length === 0) return; + const start = this.timelineStartYear; + const end = this.timelineEndYear; + const counts = new Map(); + const nameToId = new Map(); + + for (const occ of this.rawTopicOccurrences) { + if (start !== undefined && (occ.year === undefined || occ.year < start)) + continue; + if (end !== undefined && (occ.year === undefined || occ.year > end)) + continue; + counts.set(occ.name, (counts.get(occ.name) ?? 0) + 1); + if (!nameToId.has(occ.name)) nameToId.set(occ.name, occ.topicId); + } + + if (counts.size === 0) { + this.wordCloudOptions = null; + this.wordCloudEmpty = true; + return; + } + + this.wordCloudEmpty = false; + + const allValues = Array.from(counts.values()); + const minVal = Math.min(...allValues); + const maxVal = Math.max(...allValues); + const computeSize = (v: number): number => + maxVal === minVal + ? 22 + : Math.round(12 + ((v - minVal) / (maxVal - minVal)) * (32 - 12)); + + const sorted = Array.from(counts.entries()).sort((a, b) => b[1] - a[1]); + + const data = sorted.slice(0, 30).map(([name, value], i) => { + const fontSize = computeSize(value); + const color = this.timelineColors[i % this.timelineColors.length]; + return { + name, + value, + topicId: nameToId.get(name), + textStyle: { color, fontSize }, + emphasis: { + textStyle: { + fontSize: Math.round(fontSize * 1.1), + color, + shadowBlur: 16, + shadowColor: 'rgba(0, 87, 255, 0.35)', + }, + }, + }; + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any this.wordCloudOptions = { series: [ diff --git a/webapp/src/app/modules/person-projects/bund-details/bund-details.component.html b/webapp/src/app/modules/person-projects/bund-details/bund-details.component.html new file mode 100644 index 00000000..9b0df147 --- /dev/null +++ b/webapp/src/app/modules/person-projects/bund-details/bund-details.component.html @@ -0,0 +1,385 @@ +
+ + + @if (bundProject) { +
+
+
+ Bund Projekt + ID: {{ bundProject.funding_reference }} + +
+

{{ bundProject.title || 'Ohne Titel' }}

+ @if (bundProject.funding_reference) { +

+ {{ bundProject.funding_type }} +

+ } +
+ + +
+
+ +
+
+ calendar_today +
+ {{ getStartDate() || 'N/A' }} + Startdatum +
+
+
+ event_busy +
+ {{ getFundingStatus(getEndDate()) }} + Enddatum +
+
+ @if (bundProject.funding_amount) { +
+ paid +
+ {{ getFundingAmountDisplay() }} + Fördersumme +
+
+ } + @if (bundProject.funding_profile) { +
+ assignment +
+ {{ bundProject.funding_profile }} + Förderprofil +
+
+ } +
+
+ + @if (bundProject.description) { + +
+ description +

Beschreibung

+
+

{{ bundProject.description }}

+
+ } + +
+
+ + @if (getAssociatedPersons().length > 0) { + +
+ people +

Beteiligte Personen

+ {{ + getAssociatedPersons().length + }} +
+
+ @for (person of getAssociatedPersons(); track person) { +
+
{{ getInitials(person) }}
+
{{ person }}
+
+ } +
+
+ } + + + @if (getInstitutions().length > 0) { + +
+ business +

Beteiligte Institutionen

+ {{ getInstitutions().length }} +
+
+ @for (institution of getInstitutions(); track institution) { +
+ apartment + {{ institution }} +
+ } +
+
+ } + + + + @if ( + bundProject.executing_agency || + bundProject.funding_recipient || + bundProject.project_agency || + bundProject.department || + bundProject.division + ) { + +
+ organization +

Organisation

+
+
+ @if (bundProject.executing_agency) { +
+
Ausführende Stelle
+
+ {{ bundProject.executing_agency }} +
+
+ } + @if (bundProject.funding_recipient) { +
+
Förderempfänger
+
{{ bundProject.funding_recipient }}
+
+ } + @if (bundProject.project_agency) { +
+
Projektagentur
+
+ {{ + bundProject.project_agency_fullname || + bundProject.project_agency + }} +
+
+ } + @if (bundProject.department) { +
+
Abteilung
+
+ {{ + bundProject.department_fullname || bundProject.department + }} +
+
+ } + @if (bundProject.division) { +
+
Division
+
{{ bundProject.division }}
+
+ } +
+
+ } + + + @if ( + bundProject.location || + bundProject.municipality || + bundProject.state || + bundProject.country + ) { + +
+ location_on +

Standort

+
+
+ @if (bundProject.location) { +
+
Standort
+
+ {{ bundProject.location }} +
+
+ } + @if (bundProject.municipality) { +
+
Gemeinde
+
{{ bundProject.municipality }}
+
+ } + @if (bundProject.state) { +
+
Bundesland
+
+ {{ bundProject.state }} +
+
+ } + @if (bundProject.country) { +
+
Land
+
{{ bundProject.country }}
+
+ } + @if (bundProject.municipality_code) { +
+
Gemeindeschlüssel
+
{{ bundProject.municipality_code }}
+
+ } +
+
+ } + + + @if ( + bundProject.performance_plan_code || + bundProject.performance_plan_fullname || + bundProject.publication_date || + bundProject.record_date + ) { + +
+ more_info +

Weitere Informationen

+
+
+ @if (bundProject.performance_plan_code) { +
+
Leistungsplancode
+
{{ bundProject.performance_plan_code }}
+
+ } + @if (bundProject.performance_plan_fullname) { +
+
Leistungsplan
+
{{ bundProject.performance_plan_fullname }}
+
+ } + @if (bundProject.publication_date) { +
+
Veröffentlichungsdatum
+
{{ bundProject.publication_date }}
+
+ } + @if (bundProject.record_date) { +
+
Datensatzdatum
+
{{ bundProject.record_date }}
+
+ } +
+
+ } +
+ + +
+ } @else { +
+
+ error_outline +

Bund Projekt nicht gefunden.

+
+
+ } +
diff --git a/webapp/src/app/modules/person-projects/bund-details/bund-details.component.scss b/webapp/src/app/modules/person-projects/bund-details/bund-details.component.scss new file mode 100644 index 00000000..839a4ea7 --- /dev/null +++ b/webapp/src/app/modules/person-projects/bund-details/bund-details.component.scss @@ -0,0 +1,527 @@ +// Complete SCSS with all styles including clickable elements + +.detail-page { + padding: 28px 32px 42px; + max-width: 100%; + margin: 0 auto; +} + +.page-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; + margin-bottom: 24px; +} + +.back-link { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 8px 16px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + cursor: pointer; + font-size: 14px; + transition: all 0.2s; +} + +.back-link:hover { + background: #f5f7fa; + border-color: #b8c5d6; +} + +.back-link mat-icon { + width: 20px; + height: 20px; + font-size: 20px; +} + +.breadcrumb { + display: flex; + align-items: center; + gap: 6px; + color: var(--sg-text-muted); + font-size: 13px; +} + +.breadcrumb mat-icon { + width: 18px; + height: 18px; + font-size: 18px; +} + +.breadcrumb span:last-child { + color: var(--sg-text); + font-weight: 500; +} + +.project-hero { + background: #f8fafc; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-md); + padding: 28px 32px; + margin-bottom: 28px; +} + +.hero-content { + margin-bottom: 24px; +} + +.eyebrow { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 12px; + flex-wrap: wrap; +} + +.project-badge { + display: inline-block; + padding: 4px 12px; + background: #e8edf5; + color: var(--sg-text); + border-radius: var(--sg-radius-sm); + font-size: 12px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.5px; +} + +.project-id { + color: var(--sg-text-muted); + font-size: 13px; +} + +.new-badge { + display: inline-block; + padding: 2px 10px; + background: #27ae60; + color: #fff; + border-radius: var(--sg-radius-sm); + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.5px; +} + +h1 { + margin: 0 0 8px; + font-size: 26px; + line-height: 1.3; + font-weight: 700; + color: var(--sg-text); +} + +.project-reference { + margin: 0 0 16px; + color: var(--sg-text-muted); + font-size: 14px; +} + +.hero-actions { + display: flex; + flex-wrap: wrap; + gap: 10px; +} + +.agency-info, +.funding-type-info { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 8px 16px; + background: #fff; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + color: var(--sg-text); + font-size: 14px; + cursor: pointer; + transition: all 0.2s; +} + +.agency-info:hover, +.funding-type-info:hover { + background: #f5f7fa; + border-color: #b8c5d6; +} + +.agency-info mat-icon, +.funding-type-info mat-icon { + color: var(--sg-text-muted); + width: 20px; + height: 20px; + font-size: 20px; +} + +.metrics-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 16px; + padding-top: 20px; + border-top: 1px solid #d9e2f0; +} + +.metric-item { + display: flex; + align-items: center; + gap: 12px; +} + +.metric-item mat-icon { + color: var(--sg-text-muted); + width: 24px; + height: 24px; + font-size: 24px; +} + +.metric-content { + display: flex; + flex-direction: column; +} + +.metric-content strong { + font-size: 15px; + color: var(--sg-text); + line-height: 1.3; +} + +.metric-content span { + font-size: 12px; + color: var(--sg-text-muted); +} + +.card { + margin-bottom: 24px; + border-color: #d9e2f0 !important; + border-radius: var(--sg-radius-md) !important; +} + +.card ::ng-deep .mat-mdc-card-content { + padding: 0; +} + +.section-header { + display: flex; + align-items: center; + gap: 10px; + padding: 16px 20px 12px; + border-bottom: 1px solid #f0f2f5; +} + +.section-header mat-icon { + color: var(--sg-text-muted); + width: 22px; + height: 22px; + font-size: 22px; +} + +.section-header h2 { + margin: 0; + font-size: 16px; + font-weight: 600; + color: var(--sg-text); +} + +.count-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 24px; + height: 24px; + padding: 0 8px; + margin-left: auto; + background: #e8edf5; + border-radius: 12px; + color: var(--sg-text-muted); + font-size: 12px; + font-weight: 500; +} + +.description-text { + padding: 16px 20px 20px; + margin: 0; + color: var(--sg-text); + font-size: 14px; + line-height: 1.6; +} + +.content-grid { + display: grid; + grid-template-columns: 2fr 1fr; + gap: 24px; +} + +.main-content { + display: flex; + flex-direction: column; + gap: 24px; +} + +.sidebar { + display: flex; + flex-direction: column; + gap: 24px; +} + +.person-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); + gap: 12px; + padding: 16px 20px 20px; +} + +.person-item { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 12px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + cursor: pointer; + transition: all 0.2s; +} + +.person-item:hover { + background: #f8fafc; + border-color: #b8c5d6; + transform: translateY(-1px); +} + +.avatar { + display: flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: 50%; + background: #e8edf5; + color: var(--sg-text); + font-size: 13px; + font-weight: 600; + flex-shrink: 0; +} + +.person-name { + font-size: 13px; + font-weight: 500; + color: var(--sg-text); +} + +.institution-grid { + display: grid; + grid-template-columns: 1fr; + gap: 8px; + padding: 16px 20px 20px; +} + +.institution-item { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 12px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + font-size: 13px; + color: var(--sg-text); + cursor: pointer; + transition: all 0.2s; +} + +.institution-item:hover { + background: #f8fafc; + border-color: #b8c5d6; +} + +.institution-item mat-icon { + color: var(--sg-text-muted); + width: 20px; + height: 20px; + font-size: 20px; + flex-shrink: 0; +} + +.joint-project-content { + display: flex; + align-items: center; + gap: 12px; + padding: 16px 20px 20px; + color: var(--sg-text); + font-size: 14px; +} + +.joint-project-content mat-icon { + color: var(--sg-text-muted); + width: 24px; + height: 24px; + font-size: 24px; + flex-shrink: 0; +} + +.details-list { + margin: 0; + padding: 16px 20px 20px; +} + +.detail-row { + display: grid; + grid-template-columns: 140px 1fr; + gap: 24px; + padding: 8px 0; + border-bottom: 1px solid #f0f2f5; +} + +.detail-row:last-child { + border-bottom: none; +} + +.detail-row dt { + color: var(--sg-text-muted); + font-size: 13px; + font-weight: 500; +} + +.detail-row dd { + margin: 0; + color: var(--sg-text); + font-size: 13px; + word-break: break-word; + display: flex; + align-items: center; + gap: 6px; +} + +.detail-row dd.clickable { + cursor: pointer; + transition: color 0.2s; +} + +.detail-row dd.clickable:hover { + color: var(--sg-primary, #0066cc); +} + +.detail-row dd.clickable:hover .search-icon { + opacity: 1; +} + +.search-icon { + width: 16px; + height: 16px; + font-size: 16px; + opacity: 0; + transition: opacity 0.2s; + color: var(--sg-text-muted); +} + +.detail-row dd:hover .search-icon { + opacity: 1; +} + +.empty-state { + padding: 20px; + text-align: center; + color: var(--sg-text-muted); + font-size: 14px; +} + +.error-container { + display: flex; + align-items: center; + justify-content: center; + min-height: 400px; +} + +.error-state { + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; + color: var(--sg-text-muted); +} + +.error-state mat-icon { + width: 48px; + height: 48px; + font-size: 48px; + color: #e74c3c; +} + +.error-state p { + margin: 0; + font-size: 16px; +} + +// Clickable external link styling +.external-link { + color: var(--sg-primary, #0066cc); + text-decoration: none; +} + +.external-link:hover { + text-decoration: underline; +} + +@media (max-width: 992px) { + .content-grid { + grid-template-columns: 1fr; + gap: 20px; + } +} + +@media (max-width: 768px) { + .detail-page { + padding: 16px; + } + + .page-header { + flex-direction: column; + align-items: flex-start; + gap: 12px; + } + + .project-hero { + padding: 20px; + } + + .metrics-grid { + grid-template-columns: 1fr 1fr; + gap: 12px; + } + + h1 { + font-size: 22px; + } + + .detail-row { + grid-template-columns: 1fr; + gap: 4px; + } + + .person-grid { + grid-template-columns: 1fr; + } + + .eyebrow { + gap: 8px; + } +} + +@media (max-width: 480px) { + .metrics-grid { + grid-template-columns: 1fr; + } + + .hero-actions { + flex-direction: column; + } + + .agency-info, + .funding-type-info { + width: 100%; + justify-content: center; + } +} diff --git a/webapp/src/app/modules/person-projects/bund-details/bund-details.component.ts b/webapp/src/app/modules/person-projects/bund-details/bund-details.component.ts new file mode 100644 index 00000000..5ad9007b --- /dev/null +++ b/webapp/src/app/modules/person-projects/bund-details/bund-details.component.ts @@ -0,0 +1,163 @@ +import { Component, OnInit, inject } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; +import { CommonModule } from '@angular/common'; +import { MatCardModule } from '@angular/material/card'; +import { MatIconModule } from '@angular/material/icon'; +import { BundProjectDetails } from '../../../api/model/bundProjectDetails'; +import { Router } from '@angular/router'; + +@Component({ + selector: 'app-bund-details', + standalone: true, + imports: [CommonModule, MatCardModule, MatIconModule], + templateUrl: './bund-details.component.html', + styleUrl: './bund-details.component.scss', +}) +export class BundDetailsComponent implements OnInit { + private route = inject(ActivatedRoute); + bundProject: BundProjectDetails | undefined; + + constructor(private router: Router) {} + + ngOnInit(): void { + this.route.data.subscribe(({ bundSingleProject }) => { + console.log('Bund Project:', bundSingleProject); + this.bundProject = bundSingleProject; + }); + } + + getInitials(name: string | null | undefined): string { + if (!name) return ''; + const parts = name.trim().split(/\s+/); + if (parts.length > 1) { + return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase(); + } + return parts[0][0].toUpperCase(); + } + + getFundingStatus(fundingEndDate: string | null | undefined): string { + if (!fundingEndDate) return 'N/A'; + if (fundingEndDate === '2999') return 'laufend'; + const year = parseInt(fundingEndDate, 10); + if (isNaN(year)) return fundingEndDate; + return year >= new Date().getFullYear() + ? `${fundingEndDate} (laufend)` + : `${fundingEndDate} (abgeschlossen)`; + } + + formatCurrency(amount: number | null | undefined): string { + if (amount === null || amount === undefined) return 'N/A'; + + // Format as Euro with thousands separators + return new Intl.NumberFormat('de-DE', { + style: 'currency', + currency: 'EUR', + minimumFractionDigits: 0, + maximumFractionDigits: 0, + }).format(amount); + } + + searchForPersonName(personName: string): void { + this.router.navigate(['/persons'], { + queryParams: { + query: personName, + }, + }); + } + + searchForInstitutionName(institutionName: string): void { + this.router.navigate(['/institutions'], { + queryParams: { + search: institutionName, + }, + }); + } + + // searchForLocation(location: string): void { + // this.router.navigate(['/bund-projects'], { + // queryParams: { + // location: location + // } + // }); + // } + + // searchForState(state: string): void { + // this.router.navigate(['/bund-projects'], { + // queryParams: { + // state: state + // } + // }); + // } + + // searchForFundingType(fundingType: string): void { + // this.router.navigate(['/bund-projects'], { + // queryParams: { + // fundingType: fundingType + // } + // }); + // } + + // searchForAgency(agency: string): void { + // this.router.navigate(['/bund-projects'], { + // queryParams: { + // agency: agency + // } + // }); + // } + private formatGermanDate(dateString: string): string { + if (!dateString) return ''; + + return new Intl.DateTimeFormat('de-DE', { + day: 'numeric', + month: 'long', + year: 'numeric', + }).format(new Date(dateString)); + } + /** + * All associated persons as a simple list. + */ + getAssociatedPersons(): string[] { + return this.bundProject?.associated_persons || []; + } + getStartDate(): string { + return this.formatGermanDate(this.bundProject?.funding_start_date ?? ''); + } + + getEndDate(): string { + return this.formatGermanDate(this.bundProject?.funding_end_date ?? ''); + } + + getDuration(): string { + const start = this.bundProject?.funding_start_date; + const end = this.bundProject?.funding_end_date; + + if (!start || !end) return ''; + + return `von ${this.formatGermanDate(start)} bis ${this.formatGermanDate(end)}`; + } + /** + * All institutions as a simple list. + */ + getInstitutions(): string[] { + return this.bundProject?.institutions || []; + } + + /** + * Check if project is new + */ + isNewProject(): boolean { + return this.bundProject?.is_new === true; + } + + /** + * Get display name for funding amount + */ + getFundingAmountDisplay(): string { + if (!this.bundProject?.funding_amount) return 'N/A'; + return this.formatCurrency(this.bundProject.funding_amount); + } + + goBack(): void { + window.history.back(); + } +} diff --git a/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.html b/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.html new file mode 100644 index 00000000..81947db7 --- /dev/null +++ b/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.html @@ -0,0 +1,245 @@ +
+ + + @if (dfgProject) { +
+
+
+ DFG Projekt + ID: {{ dfgProject.id }} +
+

{{ dfgProject.title }}

+ @if (dfgProject.project_identifier) { +

+ {{ dfgProject.project_identifier.split('-')[0] }} +

+ } +
+ @if (dfgProject.link) { + + open_in_new + Zum Projekt + + } + @if (dfgProject.website) { + + language + Webseite + + } +
+
+ +
+
+ calendar_today +
+ {{ dfgProject.funding_start_date || 'N/A' }} + Fördersbeginn +
+
+
+ event_busy +
+ {{ getFundingStatus(dfgProject.funding_end_date) }} + Fördersende +
+
+ + @if (dfgProject.dfg_procedure) { +
+ gavel +
+ {{ dfgProject.dfg_procedure }} + DFG Verfahren +
+
+ } + + @if (dfgProject.international_reference) { +
+ public +
+ {{ dfgProject.international_reference }} + Internationaler Bezug +
+
+ } +
+
+ + @if (dfgProject.description) { + +
+ description +

Beschreibung

+
+

{{ dfgProject.description }}

+
+ } + +
+
+ + +
+ people +

Beteiligte Personen

+ {{ getAssociatedPersons().length }} +
+ @if (getAssociatedPersons().length > 0) { +
+ @for (person of getAssociatedPersons(); track person) { +
+
{{ getInitials(person) }}
+
{{ person }}
+
+ } +
+ } @else { +
Keine Personen gefunden.
+ } +
+ + + +
+ business +

Beteiligte Institutionen

+ {{ getInstitutions().length }} +
+ @if (getInstitutions().length > 0) { +
+ @for (institution of getInstitutions(); track institution) { +
+ apartment + {{ institution }} +
+ } +
+ } @else { +
Keine Institutionen gefunden.
+ } +
+ + +
+ + +
+ } @else { +
+
+ error_outline +

DFG Projekt nicht gefunden.

+
+
+ } +
diff --git a/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.scss b/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.scss new file mode 100644 index 00000000..08fbf9e7 --- /dev/null +++ b/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.scss @@ -0,0 +1,467 @@ +.detail-page { + padding: 28px 32px 42px; + max-width: 100%; + margin: 0 auto; +} + +.page-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; + margin-bottom: 24px; +} + +.back-link { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 8px 16px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + cursor: pointer; + font-size: 14px; + transition: all 0.2s; +} + +.back-link:hover { + background: #f5f7fa; + border-color: #b8c5d6; +} + +.back-link mat-icon { + width: 20px; + height: 20px; + font-size: 20px; +} + +.breadcrumb { + display: flex; + align-items: center; + gap: 6px; + color: var(--sg-text-muted); + font-size: 13px; +} + +.breadcrumb mat-icon { + width: 18px; + height: 18px; + font-size: 18px; +} + +.breadcrumb span:last-child { + color: var(--sg-text); + font-weight: 500; +} + +.project-hero { + background: #f8fafc; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-md); + padding: 28px 32px; + margin-bottom: 28px; +} + +.hero-content { + margin-bottom: 24px; +} + +.eyebrow { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 12px; +} + +.project-badge { + display: inline-block; + padding: 4px 12px; + background: #e8edf5; + color: var(--sg-text); + border-radius: var(--sg-radius-sm); + font-size: 12px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.5px; +} + +.project-id { + color: var(--sg-text-muted); + font-size: 13px; +} + +h1 { + margin: 0 0 8px; + font-size: 26px; + line-height: 1.3; + font-weight: 700; + color: var(--sg-text); +} + +.project-identifier { + margin: 0 0 16px; + color: var(--sg-text-muted); + font-size: 14px; +} + +.hero-actions { + display: flex; + flex-wrap: wrap; + gap: 10px; +} + +.primary-action, +.secondary-action { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 10px 20px; + border-radius: var(--sg-radius-sm); + text-decoration: none; + font-size: 14px; + font-weight: 500; + transition: all 0.2s; +} + +.primary-action { + background: var(--sg-primary, #0066cc); + color: #fff; + border: none; +} + +.primary-action:hover { + background: var(--sg-primary-dark, #0052a3); +} + +.secondary-action { + background: #fff; + color: var(--sg-text); + border: 1px solid #d9e2f0; +} + +.secondary-action:hover { + background: #f5f7fa; + border-color: #b8c5d6; +} + +.primary-action mat-icon, +.secondary-action mat-icon { + width: 20px; + height: 20px; + font-size: 20px; +} + +.metrics-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 16px; + padding-top: 20px; + border-top: 1px solid #d9e2f0; +} + +.metric-item { + display: flex; + align-items: center; + gap: 12px; +} + +.metric-item mat-icon { + color: var(--sg-text-muted); + width: 24px; + height: 24px; + font-size: 24px; +} + +.metric-content { + display: flex; + flex-direction: column; +} + +.metric-content strong { + font-size: 15px; + color: var(--sg-text); + line-height: 1.3; +} + +.metric-content span { + font-size: 12px; + color: var(--sg-text-muted); +} + +.card { + margin-bottom: 24px; + border-color: #d9e2f0 !important; + border-radius: var(--sg-radius-md) !important; +} + +.card ::ng-deep .mat-mdc-card-content { + padding: 0; +} + +.section-header { + display: flex; + align-items: center; + gap: 10px; + padding: 16px 20px 12px; + border-bottom: 1px solid #f0f2f5; +} + +.section-header mat-icon { + color: var(--sg-text-muted); + width: 22px; + height: 22px; + font-size: 22px; +} + +.section-header h2 { + margin: 0; + font-size: 16px; + font-weight: 600; + color: var(--sg-text); +} + +.count-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 24px; + height: 24px; + padding: 0 8px; + margin-left: auto; + background: #e8edf5; + border-radius: 12px; + color: var(--sg-text-muted); + font-size: 12px; + font-weight: 500; +} + +.description-text { + padding: 16px 20px 20px; + margin: 0; + color: var(--sg-text); + font-size: 14px; + line-height: 1.6; +} + +.content-grid { + display: grid; + grid-template-columns: 2fr 1fr; + gap: 24px; +} + +.main-content { + display: flex; + flex-direction: column; + gap: 24px; +} + +.sidebar { + display: flex; + flex-direction: column; + gap: 24px; +} + +.person-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); + gap: 12px; + padding: 16px 20px 20px; +} + +.person-item { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 12px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + transition: all 0.2s; +} + +.person-item:hover { + cursor: pointer; + background: #f8fafc; + border-color: #b8c5d6; +} + +.avatar { + display: flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: 50%; + background: #e8edf5; + color: var(--sg-text); + font-size: 13px; + font-weight: 600; + flex-shrink: 0; +} + +.person-name { + cursor: pointer; + font-size: 13px; + font-weight: 500; + color: var(--sg-text); +} + +.institution-grid { + cursor: pointer; + display: grid; + grid-template-columns: 1fr; + gap: 8px; + padding: 16px 20px 20px; +} + +.institution-item { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 12px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + font-size: 13px; + color: var(--sg-text); +} + +.institution-item mat-icon { + color: var(--sg-text-muted); + width: 20px; + height: 20px; + font-size: 20px; + flex-shrink: 0; +} + +.details-list { + margin: 0; + padding: 16px 20px 20px; +} + +.detail-row { + display: grid; + grid-template-columns: 140px 1fr; + gap: 12px; + padding: 8px 0; + border-bottom: 1px solid #f0f2f5; +} + +.detail-row:last-child { + border-bottom: none; +} + +.detail-row dt { + color: var(--sg-text-muted); + font-size: 13px; + font-weight: 500; +} + +.detail-row dd { + margin: 0; + color: var(--sg-text); + font-size: 13px; + word-break: break-word; +} + +.external-link { + color: var(--sg-primary, #0066cc); + text-decoration: none; +} + +.external-link:hover { + text-decoration: underline; +} + +.empty-state { + padding: 20px; + text-align: center; + color: var(--sg-text-muted); + font-size: 14px; +} + +.error-container { + display: flex; + align-items: center; + justify-content: center; + min-height: 400px; +} + +.error-state { + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; + color: var(--sg-text-muted); +} + +.error-state mat-icon { + width: 48px; + height: 48px; + font-size: 48px; + color: #e74c3c; +} + +.error-state p { + margin: 0; + font-size: 16px; +} + +@media (max-width: 992px) { + .content-grid { + grid-template-columns: 1fr; + gap: 20px; + } +} + +@media (max-width: 768px) { + .detail-page { + padding: 16px; + } + + .page-header { + flex-direction: column; + align-items: flex-start; + gap: 12px; + } + + .project-hero { + padding: 20px; + } + + .metrics-grid { + grid-template-columns: 1fr 1fr; + gap: 12px; + } + + h1 { + font-size: 22px; + } + + .detail-row { + grid-template-columns: 1fr; + gap: 4px; + } + + .person-grid { + grid-template-columns: 1fr; + } +} + +@media (max-width: 480px) { + .metrics-grid { + grid-template-columns: 1fr; + } + + .hero-actions { + flex-direction: column; + } + + .primary-action, + .secondary-action { + width: 100%; + justify-content: center; + } +} diff --git a/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.ts b/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.ts new file mode 100644 index 00000000..ab8ca4ea --- /dev/null +++ b/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.ts @@ -0,0 +1,77 @@ +import { Component, OnInit, inject } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; +import { CommonModule } from '@angular/common'; +import { MatCardModule } from '@angular/material/card'; +import { MatIconModule } from '@angular/material/icon'; +import { DfgProjectDetails } from '../../../api'; +import { Router } from '@angular/router'; +@Component({ + selector: 'app-dfg-details', + standalone: true, + imports: [CommonModule, MatCardModule, MatIconModule], + templateUrl: './dfg-details.component.html', + styleUrl: './dfg-details.component.scss', +}) +export class DfgDetailsComponent implements OnInit { + private route = inject(ActivatedRoute); + dfgProject: DfgProjectDetails | undefined; + + constructor(private router: Router) {} + + ngOnInit(): void { + this.route.data.subscribe(({ dfgSingleProject }) => { + console.log('DFG Project:', dfgSingleProject); + this.dfgProject = dfgSingleProject; + }); + } + + getInitials(name: string | null | undefined): string { + if (!name) return ''; + const parts = name.trim().split(/\s+/); + if (parts.length > 1) { + return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase(); + } + return parts[0][0].toUpperCase(); + } + + getFundingStatus(fundingEndDate: string | null | undefined): string { + if (!fundingEndDate) return 'N/A'; + if (fundingEndDate === '2999') return 'laufend'; + const year = parseInt(fundingEndDate, 10); + if (isNaN(year)) return fundingEndDate; + return year >= new Date().getFullYear() + ? `${fundingEndDate} (laufend)` + : `${fundingEndDate} (abgeschlossen)`; + } + searchForPersonName(personName: string): void { + this.router.navigate(['/persons'], { + queryParams: { + query: personName, + }, + }); + } + searchForInstitutionName(institutionName: string): void { + this.router.navigate(['/institutions'], { + queryParams: { + search: institutionName, + }, + }); + } + /** + * All associated persons as a simple list (no role grouping). + */ + getAssociatedPersons(): string[] { + return this.dfgProject?.associated_persons || []; + } + + /** + * All institutions as a simple list. + */ + getInstitutions(): string[] { + return this.dfgProject?.institutions || []; + } + + goBack(): void { + window.history.back(); + } +} diff --git a/webapp/src/app/modules/person-projects/person-projects.component.html b/webapp/src/app/modules/person-projects/person-projects.component.html index b1f8bb43..90e01edf 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.html +++ b/webapp/src/app/modules/person-projects/person-projects.component.html @@ -39,7 +39,11 @@
- + open_in_new diff --git a/webapp/src/app/modules/person-projects/person-projects.component.ts b/webapp/src/app/modules/person-projects/person-projects.component.ts index 660576e3..6374de4f 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -20,7 +20,7 @@ import { MatTabsModule } from '@angular/material/tabs'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { DebounceDirective } from '../../directives/debounce.directive'; -import { ActivatedRoute, Router } from '@angular/router'; +import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; import { Sort, SortDirection } from '@angular/material/sort'; @@ -37,6 +37,7 @@ import { Sort, SortDirection } from '@angular/material/sort'; MatInputModule, DebounceDirective, MatPaginatorModule, + RouterModule, ], templateUrl: './person-projects.component.html', styleUrl: './person-projects.component.scss', diff --git a/webapp/src/app/modules/projects/projects.component.html b/webapp/src/app/modules/projects/projects.component.html new file mode 100644 index 00000000..8d2a3884 --- /dev/null +++ b/webapp/src/app/modules/projects/projects.component.html @@ -0,0 +1,112 @@ +
+

Passende Projekte finden

+ + + +
+ + Suche nach Namen + + search + + + +
+ + EU + BUND + DFG + + +
+ + + +
+
+
+ + + + @let fundingProjectPageValue = fundingProjectPage(); + + @if ( + fundingProjectPageValue.elements && + fundingProjectPageValue.elements.length > 0 + ) { +
+ @for (fundingProject of fundingProjectPageValue.elements; track $index) { + + + {{ fundingProject.title }} + {{ + fundingProject.type | uppercase + }} + + + + + + + + + + + + info + Übersicht + + + + + } +
+ } @else { +
+

Keine passenden Projekte gefunden.

+
+ } + + + + + +
diff --git a/webapp/src/app/modules/projects/projects.component.scss b/webapp/src/app/modules/projects/projects.component.scss new file mode 100644 index 00000000..e3d0edc0 --- /dev/null +++ b/webapp/src/app/modules/projects/projects.component.scss @@ -0,0 +1,99 @@ +.content { + display: flex; + flex-direction: column; + gap: 1rem; + padding: 1rem; +} + +.sorting { + display: flex; + justify-content: flex-end; + gap: 0.5rem; +} + +.sorting select { + padding: 0.75rem; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + font-size: 1rem; +} + +.sorting select:hover { + cursor: pointer; +} + +.cards { + display: grid; + gap: 1.5rem; + grid-template-columns: repeat(4, 1fr); + padding: 0 1rem; +} + +@media (max-width: 900px) { + .cards { + grid-template-columns: repeat(2, 1fr); + } +} + +@media (max-width: 600px) { + .cards { + grid-template-columns: 1fr; + } +} + +mat-paginator { + background-color: var(--sg-background); +} + +.card { + padding: 0.5rem; + background-color: var(--sg-background); + transition: transform 0.3s ease; + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.card:hover { + cursor: pointer; + transform: scale(1.05); +} + +.card-content { + display: flex; + flex-direction: column; + justify-content: flex-end; + gap: 0.5rem; + flex: 1; +} + +.card-metadata { + display: flex; + flex-direction: column; + gap: 0.2rem; + font-size: 0.9rem; + color: var(--sg-text-secondary); +} + +mat-card-actions { + padding-top: 0.5rem; + display: flex; + gap: 0.5rem; +} + +mat-card-actions a { + width: 100%; + text-decoration: none; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); +} + +.no-results { + text-align: center; + padding: 2rem; + color: var(--sg-text-secondary); +} + +.mat-mdc-standard-chip { + border-radius: var(--sg-radius-sm); +} diff --git a/webapp/src/app/modules/projects/projects.component.ts b/webapp/src/app/modules/projects/projects.component.ts new file mode 100644 index 00000000..3e68025a --- /dev/null +++ b/webapp/src/app/modules/projects/projects.component.ts @@ -0,0 +1,128 @@ +import { Component, effect, input, signal } from '@angular/core'; +import { FundingProject, FundingProjectPage, ProjectType } from '../../api'; +import { MatDividerModule } from '@angular/material/divider'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { DebounceDirective } from '../../directives/debounce.directive'; +import { MatIconModule } from '@angular/material/icon'; +import { MatCardModule } from '@angular/material/card'; +import { ActivatedRoute, Router, RouterModule } from '@angular/router'; +import { MatPaginator, PageEvent } from '@angular/material/paginator'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatInputModule } from '@angular/material/input'; +import { MatButtonModule } from '@angular/material/button'; +import { DatePipe, UpperCasePipe } from '@angular/common'; +import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips'; + +@Component({ + selector: 'app-projects', + imports: [ + MatDividerModule, + MatFormFieldModule, + DebounceDirective, + MatIconModule, + MatCardModule, + RouterModule, + MatPaginator, + MatInputModule, + MatButtonModule, + UpperCasePipe, + DatePipe, + MatChipsModule, + ], + templateUrl: './projects.component.html', + styleUrl: './projects.component.scss', +}) +export class ProjectsComponent { + fundingProjectPage = input.required(); + + urlSearchTerm = signal(''); + urlSortBy = signal('relevance'); + urlSortingOrder = signal('desc'); + urlChips = signal(['eu', 'bund', 'dfg']); + + constructor( + private readonly activatedRoute: ActivatedRoute, + private readonly router: Router, + ) { + this.activatedRoute.queryParams + .pipe(takeUntilDestroyed()) + .subscribe((params) => { + this.urlSearchTerm.set(params['search'] || ''); + this.urlSortBy.set(params['sort_by'] || 'relevance'); + this.urlSortingOrder.set(params['sorting_order'] || 'desc'); + this.urlChips.set( + (params['selected_project_types'] || 'eu,bund,dfg').split(','), + ); + }); + + effect(() => { + const searchTerm = this.urlSearchTerm(); + this.router.navigate([], { + queryParams: { search: searchTerm }, + queryParamsHandling: 'merge', + }); + }); + } + + handleSearchTermChange(newTerm: string): void { + this.router.navigate([], { + queryParams: { search: newTerm }, + queryParamsHandling: 'merge', + }); + } + + clearSearchTerm(): void { + this.router.navigate([], { + queryParams: { search: null }, + queryParamsHandling: 'merge', + }); + } + + handlePageChange(event: PageEvent): void { + this.router.navigate([], { + queryParams: { page: event.pageIndex, size: event.pageSize }, + queryParamsHandling: 'merge', + }); + } + + handleSortFieldChange(event: Event): void { + const selectElement = event.target as HTMLSelectElement; + const sortField = selectElement.value; + this.router.navigate([], { + queryParams: { sort_by: sortField }, + queryParamsHandling: 'merge', + }); + } + + handleSortOrderChange(event: Event): void { + const selectElement = event.target as HTMLSelectElement; + const sortOrder = selectElement.value; + this.router.navigate([], { + queryParams: { sorting_order: sortOrder }, + queryParamsHandling: 'merge', + }); + } + + handleChipBoxChange(change: MatChipListboxChange): void { + const selectedValues = change.value as string[]; + + this.router.navigate([], { + queryParams: { + selected_project_types: selectedValues.length + ? selectedValues.join(',') + : null, + }, + queryParamsHandling: 'merge', + }); + } + + getDetaiLink(fundingProject: FundingProject): string | null { + if (fundingProject.type === 'bund') { + return '/projects/bund/' + fundingProject.id; + } else if (fundingProject.type === 'dfg') { + return '/projects/dfg/' + fundingProject.id; + } else { + return null; + } + } +} diff --git a/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts b/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts new file mode 100644 index 00000000..ece71b78 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts @@ -0,0 +1,29 @@ +// src/app/modules/university-ranking/services/university-data.service.ts +import { inject, Injectable } from '@angular/core'; +import { Observable } from 'rxjs'; +import { InstitutionsService, RankingResponse } from '../../../api'; +export type ResearchTopic = + | 'Artificial Intelligence' + | 'Quantum Computing' + | 'Renewable Energy' + | 'Biotechnology'; +export type DashboardMetric = 'publications' | 'citations'; + +@Injectable({ providedIn: 'root' }) +export class UniversityRankingService { + private apiService = inject(InstitutionsService); + + /** + * Fetches ranking and timeseries data directly from the backend. + * Calculations for growth and trends are now handled server-side. + */ + getRankingData( + topic: ResearchTopic, + metric: DashboardMetric, + ): Observable { + return this.apiService.getRankingsApiInseServiceUniversityRankingsGet( + topic, + metric, + ); + } +} diff --git a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html new file mode 100644 index 00000000..41931384 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html @@ -0,0 +1,5 @@ +
diff --git a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.scss b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.scss new file mode 100644 index 00000000..f51d8c68 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.scss @@ -0,0 +1,4 @@ +.chart-container { + height: 500px; + width: 100%; +} diff --git a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.ts new file mode 100644 index 00000000..799ad08f --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.ts @@ -0,0 +1,64 @@ +// src/app/modules/university-ranking/components/line-chart/university-line-chart.component.ts +import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; +import { EChartsOption } from 'echarts'; +import { NgxEchartsDirective } from 'ngx-echarts'; +import { UniversityTopicData, YearlyData } from '../../../api'; +export type ResearchTopic = + | 'Artificial Intelligence' + | 'Quantum Computing' + | 'Renewable Energy' + | 'Biotechnology'; +export type DashboardMetric = 'publications' | 'citations'; + +@Component({ + selector: 'app-university-line-chart', + templateUrl: './uni-line-chart.component.html', + styleUrl: './uni-line-chart.component.scss', + imports: [NgxEchartsDirective], + standalone: true, +}) +export class UniversityLineChartComponent implements OnChanges { + @Input() data: UniversityTopicData[] = []; + @Input() metric: DashboardMetric = 'publications'; + + chartOption: EChartsOption = { + title: { + text: 'Research Output Over Time', + left: 'center', + textStyle: { fontWeight: 'lighter' }, + }, + tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, + legend: { bottom: 0 }, + grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true }, + xAxis: { type: 'category', boundaryGap: false, data: [] }, + yAxis: { type: 'value', name: 'Volume' }, + dataZoom: [{ type: 'slider', show: true, bottom: 40 }], + series: [], + }; + + mergeOption: EChartsOption = {}; + + ngOnChanges(changes: SimpleChanges): void { + if (this.data.length > 0) { + this.updateChart(); + console.log('CHANGES!'); + } + } + + private updateChart() { + const years = this.data[0].yearly_data.map((d) => d.year); + const series = this.data.map((uni) => ({ + name: uni.university, + type: 'line', + smooth: true, + emphasis: { focus: 'series' }, + animationDuration: 2000, + data: uni.yearly_data.map((d) => d[this.metric]), + })); + + this.mergeOption = { + xAxis: { data: years.map(String) }, + series: series as any, + }; + } +} diff --git a/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.html b/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.html new file mode 100644 index 00000000..99da5bcb --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.html @@ -0,0 +1,42 @@ +
+

Topic Rankings

+ @if (loading) { +
Loading rankings...
+ } @else { + + + + + + + + + + + + @for (row of rankings; track $index) { + + + + + + + + } + +
RankUniversityLatest5Y GrowthTrend
#{{ row.rank }} + {{ row.university }} + @if (row.is_top_mover) { + 🔥 + } + {{ row.publications | number }} + {{ row.growth_rate | number: '1.0-1' }}% + + {{ getTrendIcon(row.trend) }} +
+ } +
diff --git a/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.scss b/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.ts b/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.ts new file mode 100644 index 00000000..05db1334 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.ts @@ -0,0 +1,21 @@ +// src/app/modules/university-ranking/components/ranking-table/university-ranking-table.component.ts +import { Component, Input } from '@angular/core'; +import { UniversityRanking } from '../../../api'; +import { DecimalPipe } from '@angular/common'; + +@Component({ + selector: 'app-university-ranking-table', + templateUrl: './uni-ranking-table.component.html', + styleUrls: ['./uni-ranking-table.component.scss'], + imports: [DecimalPipe], +}) +export class UniversityRankingTableComponent { + @Input() rankings: UniversityRanking[] = []; + @Input() loading: boolean = false; + + getTrendIcon(trend: string): string { + if (trend === 'up') return '↑'; + if (trend === 'down') return '↓'; + return '→'; + } +} diff --git a/webapp/src/app/resolvers/bund-project-page.resolver.ts b/webapp/src/app/resolvers/bund-project-page.resolver.ts new file mode 100644 index 00000000..57657d8c --- /dev/null +++ b/webapp/src/app/resolvers/bund-project-page.resolver.ts @@ -0,0 +1,38 @@ +import { ResolveFn } from '@angular/router'; +import { + BundProjectPage, + ProjectsService, + ProjectsSortBy, + SortDirection, +} from '../api'; +import { inject } from '@angular/core'; + +export const bundProjectPageResolver: ResolveFn = ( + route, + state, +) => { + console.log('bundProjectPageResolver called with route:', route); + const page = route.queryParamMap.get('page') ?? '0'; + const size = route.queryParamMap.get('size') ?? '10'; + let institutionId = route.paramMap.get('institutionId'); + if (!institutionId) { + institutionId = route.parent?.paramMap.get('institutionId') ?? null; + } + + const sortBy = (route.queryParamMap.get('sort_by') ?? + 'title') as ProjectsSortBy; + const sortDirection = (route.queryParamMap.get('sort_direction') ?? + 'asc') as SortDirection; + + const search = route.queryParamMap.get('search'); + + return inject(ProjectsService).searchBundProjects({ + project_type: 'bund', + page: Number(page), + size: Number(size), + raw_oa_institution_id: institutionId, + query: search, + sort_by: sortBy, + sort_direction: sortDirection, + }); +}; diff --git a/webapp/src/app/resolvers/bund-projects-funding.resolver.ts b/webapp/src/app/resolvers/bund-projects-funding.resolver.ts index 61591e66..27f188c5 100644 --- a/webapp/src/app/resolvers/bund-projects-funding.resolver.ts +++ b/webapp/src/app/resolvers/bund-projects-funding.resolver.ts @@ -5,9 +5,11 @@ import { inject } from '@angular/core'; export const bundProjectsFundingResolver: ResolveFn< InstitutionFunderSummary > = (route, state) => { - let institutionId = route.paramMap.get('institutionId'); + let institutionId = route.parent?.paramMap.get('institutionId') ?? null; if (!institutionId) { institutionId = route.parent?.paramMap.get('institutionId') ?? null; } - return inject(ProjectsService).getBundFundingOverTime(institutionId || ''); + return inject(ProjectsService).getInstitutionBundProjectsFundingOverTime( + institutionId!, + ); }; diff --git a/webapp/src/app/resolvers/bund-projects.resolver.ts b/webapp/src/app/resolvers/bund-projects.resolver.ts deleted file mode 100644 index 88025139..00000000 --- a/webapp/src/app/resolvers/bund-projects.resolver.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { ResolveFn } from '@angular/router'; -import { BundProjectPage, ProjectsService } from '../api'; -import { inject } from '@angular/core'; - -export const bundProjectsResolver: ResolveFn = ( - route, - state, -) => { - console.log('bundProjectsResolver called with route:', route); - const page = route.queryParamMap.get('page') ?? '1'; - const size = route.queryParamMap.get('size') ?? '10'; - let institutionId = route.paramMap.get('institutionId'); - if (!institutionId) { - institutionId = route.parent?.paramMap.get('institutionId') ?? null; - } - - const sortBy = route.queryParamMap.get('sort_by') ?? 'topic'; - const sortDirection = route.queryParamMap.get('sort_direction') ?? 'asc'; - - const search = route.queryParamMap.get('search'); - - return inject(ProjectsService).getBundProjects( - institutionId || '', - search || undefined, - Number(page), - Number(size), - sortBy, - sortDirection, - ); -}; diff --git a/webapp/src/app/resolvers/bund-single-project-resolver.ts b/webapp/src/app/resolvers/bund-single-project-resolver.ts new file mode 100644 index 00000000..c41d0816 --- /dev/null +++ b/webapp/src/app/resolvers/bund-single-project-resolver.ts @@ -0,0 +1,16 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { ProjectsService } from '../api/api/projects.service'; +import { BundProjectDetails } from '../api/model/bundProjectDetails'; + +export const bundSingleProjectResolver: ResolveFn = ( + route, + state, +) => { + const projectsService = inject(ProjectsService); + const projectId = route.paramMap.get('id'); + if (!projectId) { + throw new Error('BUND Project ID is required'); + } + return projectsService.getSingleBundProject(projectId); +}; diff --git a/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts b/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts new file mode 100644 index 00000000..791a0423 --- /dev/null +++ b/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts @@ -0,0 +1,29 @@ +import { ResolveFn } from '@angular/router'; +import { CordisEuProjectPage, ProjectsService } from '../api'; +import { inject } from '@angular/core'; + +export const cordisEuProjectPageResolver: ResolveFn = ( + route, + state, +) => { + const page = route.queryParamMap.get('page') ?? '1'; + const size = route.queryParamMap.get('size') ?? '10'; + let institutionId = route.paramMap.get('institutionId'); + if (!institutionId) { + institutionId = route.parent?.paramMap.get('institutionId') ?? null; + } + + const sortBy = route.queryParamMap.get('sort_by') ?? 'title'; + const sortDirection = route.queryParamMap.get('sort_direction') ?? 'asc'; + const search = route.queryParamMap.get('search'); + + return inject(ProjectsService).searchCordisEuProjects({ + project_type: 'eu', + page: Number(page), + size: Number(size), + raw_oa_institution_id: institutionId, + query: search, + sort_by: sortBy as 'title' | 'funding_start' | 'funding_end', + sort_direction: sortDirection as 'asc' | 'desc', + }); +}; diff --git a/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts b/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts new file mode 100644 index 00000000..4b1e5385 --- /dev/null +++ b/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts @@ -0,0 +1,17 @@ +import { ResolveFn } from '@angular/router'; +import { InstitutionFunderSummary, ProjectsService } from '../api'; +import { inject } from '@angular/core'; + +export const cordisEuProjectsFundingResolver: ResolveFn< + InstitutionFunderSummary +> = (route, state) => { + let institutionId = route.parent?.paramMap.get('institutionId') ?? null; + if (!institutionId) { + throw new Error( + 'Institution ID is required to resolve Cordis EU projects funding', + ); + } + return inject(ProjectsService).getInstitutionCordisEuProjectsFundingOverTime( + institutionId, + ); +}; diff --git a/webapp/src/app/resolvers/dfg-single-project-resolver.ts b/webapp/src/app/resolvers/dfg-single-project-resolver.ts new file mode 100644 index 00000000..2d0ae08f --- /dev/null +++ b/webapp/src/app/resolvers/dfg-single-project-resolver.ts @@ -0,0 +1,16 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { ProjectsService } from '../api/api/projects.service'; +import { DfgProjectDetails } from '../api'; + +export const dfgSingleProjectResolver: ResolveFn = ( + route, + state, +) => { + const projectsService = inject(ProjectsService); + const projectId = route.paramMap.get('id'); + if (!projectId) { + throw new Error('DFG Project ID is required'); + } + return projectsService.getSingleDfgProject(projectId); +}; diff --git a/webapp/src/app/resolvers/eu-projects.resolver.ts b/webapp/src/app/resolvers/eu-projects.resolver.ts deleted file mode 100644 index 5ca019aa..00000000 --- a/webapp/src/app/resolvers/eu-projects.resolver.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { ResolveFn } from '@angular/router'; -import { EuProjectPage, ProjectsService } from '../api'; -import { inject } from '@angular/core'; - -export const euProjectsResolver: ResolveFn = (route, state) => { - const page = route.queryParamMap.get('page') ?? '1'; - const size = route.queryParamMap.get('size') ?? '10'; - let institutionId = route.paramMap.get('institutionId'); - if (!institutionId) { - institutionId = route.parent?.paramMap.get('institutionId') ?? null; - } - - const sortBy = route.queryParamMap.get('sort_by') ?? 'topic'; - const sortDirection = route.queryParamMap.get('sort_direction') ?? 'asc'; - const search = route.queryParamMap.get('search'); - - return inject(ProjectsService).getEuProjects( - institutionId || '', - search || undefined, - Number(page), - Number(size), - sortBy, - sortDirection, - ); -}; diff --git a/webapp/src/app/resolvers/funding-project-page.resolver.ts b/webapp/src/app/resolvers/funding-project-page.resolver.ts new file mode 100644 index 00000000..496e7958 --- /dev/null +++ b/webapp/src/app/resolvers/funding-project-page.resolver.ts @@ -0,0 +1,37 @@ +import { ResolveFn } from '@angular/router'; +import { + FundingProjectPage, + ProjectsService, + ProjectsSortBy, + ProjectType, + SortDirection, +} from '../api'; +import { inject } from '@angular/core'; + +export const fundingProjectPageResolver: ResolveFn = ( + route, + state, +) => { + const page = Number(route.queryParamMap.get('page') || '0'); + const size = Number(route.queryParamMap.get('size') || '10'); + const sortBy = (route.queryParamMap.get('sort_by') ?? + 'title') as ProjectsSortBy; + const sortOrder = (route.queryParamMap.get('sorting_order') ?? + 'asc') as SortDirection; + const title = route.queryParamMap.get('search') ?? undefined; + const selectedProjectTypes = route.queryParamMap.get('selected_project_types') + ? new Set( + route.queryParamMap + .get('selected_project_types')! + .split(',') as ProjectType[], + ) + : undefined; + return inject(ProjectsService).searchProjects( + page, + size, + selectedProjectTypes, + title, + sortBy, + sortOrder, + ); +}; diff --git a/webapp/src/app/resolvers/person.resolver.ts b/webapp/src/app/resolvers/person.resolver.ts index 64bde7da..1dc145ac 100644 --- a/webapp/src/app/resolvers/person.resolver.ts +++ b/webapp/src/app/resolvers/person.resolver.ts @@ -6,12 +6,16 @@ export const personResolver: ResolveFn = ( route, state, ) => { - const authorId = route.paramMap.get('id'); + const PERSON_INCLUDE_TAGS = + 'topics_full,topic_share,summary_stats,ids,last_known_institutions,' + + 'sources,counts_by_year,works_api_url,dates,cited_by_count_boost,career_metrics'; + + const authorId = route.paramMap.get('id') || undefined; const personsService = inject(PersonsService); if (!authorId) { return { results: [] }; } - return personsService.getPersonByID(authorId); + return personsService.getPersonByID(authorId, PERSON_INCLUDE_TAGS); }; diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index 6de5f1f4..7b479fe8 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -1,6 +1,8 @@
- + @if ( (credentialService.authenticated | async) && ((credentialService.superadmin | async) || @@ -8,10 +10,15 @@ ) { - + + } @@ -52,6 +59,12 @@ icon="person" [size]="200" [diameter]="200" /> + } @else if (resolverState.isResolvingFromOutside('/projects/')) { + } @else { } diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss index 5afa1f9c..adba06a1 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss @@ -84,6 +84,10 @@ mat-toolbar.main { box-shadow: none; } +.drawer--collapsed { + width: 76px; +} + .content { display: flex; flex-direction: column; diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index 7ac7e077..f0a1e6c1 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -45,7 +45,10 @@ export class AppLayoutComponent implements OnInit, OnDestroy { protected resolverState = inject(ResolverStateService); mediaQueryListener: () => void; + private readonly sidebarCollapsedStorageKey = 'inse.sidebar.collapsed'; sideNavOpen = false; + sideNavCollapsed = this.readSidebarCollapsedState(); + constructor( public credentialService: CredentialService, public router: Router, @@ -56,6 +59,11 @@ export class AppLayoutComponent implements OnInit, OnDestroy { this.mediaQuery = media.matchMedia('(max-width: 600px)'); this.mediaQueryListener = () => { this.sideNavOpen = !this.mediaQuery.matches; + + if (this.mediaQuery.matches) { + this.sideNavCollapsed = false; + } + changeDetector.detectChanges(); }; } @@ -66,6 +74,26 @@ export class AppLayoutComponent implements OnInit, OnDestroy { } } + private readSidebarCollapsedState(): boolean { + return localStorage.getItem(this.sidebarCollapsedStorageKey) === 'true'; + } + + isSidebarCollapsed(): boolean { + return this.sideNavCollapsed && !this.mediaQuery.matches; + } + + toggleSidebarCollapsed(): void { + if (this.mediaQuery.matches) { + return; + } + + this.sideNavCollapsed = !this.sideNavCollapsed; + localStorage.setItem( + this.sidebarCollapsedStorageKey, + String(this.sideNavCollapsed), + ); + } + ngOnInit() { this.sideNavOpen = !this.mediaQuery.matches; this.mediaQuery.addEventListener('change', this.mediaQueryListener); diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index 5c43bd85..f20b8878 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -1,30 +1,71 @@ -
-