Merge pull request 'feature/keywords-analysis' (#247) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good

Reviewed-on: #247
This commit was merged in pull request #247.
This commit is contained in:
2026-07-26 22:49:24 +02:00
35 changed files with 1776 additions and 749 deletions
+1 -1
View File
@@ -137,7 +137,7 @@ app.include_router(background_jobs_router)
app.include_router(eu_organizations_router)
app.add_middleware(
ETagCacheMiddleware,
ttl=120, # 2 minutes expiration time
ttl=600, # 10 minutes expiration time
)
app.add_middleware(
CORSMiddleware,
@@ -8,8 +8,8 @@
"""
from datetime import date, datetime
from typing import Optional, List, Set, Any
from typing import Optional, List, Set, Any, Dict
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
from pydantic import BaseModel, ConfigDict, Field, field_validator
@@ -189,6 +189,10 @@ class BundProjectDetails(BaseModel):
default_factory=list,
description="All institutions associated with the Bund project",
)
oa_topics: Optional[List[Topic]] = Field(
default_factory=list,
description="OpenAlex topics associated with the Bund project",
)
# --- Validators for type coercion ---
@@ -301,7 +305,17 @@ class BundProjectDetails(BaseModel):
if source.get("PT_fullname"):
institutions.add(source["PT_fullname"].strip())
topics_raw = source.get("oa_topics") or []
if not isinstance(source, dict):
return cls.model_validate(source)
oa_topics = None
if isinstance(topics_raw, list) and topics_raw:
sorted_topics_raw = sorted(
(t for t in topics_raw if isinstance(t, dict)),
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
oa_topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
return cls(
id=hit["_id"],
funding_reference=source.get("Förderkennzeichen"),
@@ -334,4 +348,24 @@ class BundProjectDetails(BaseModel):
unix_timestamp=source.get("unix_timestamp"),
associated_persons=sorted(persons),
institutions=sorted(institutions),
oa_topics=oa_topics
)
@staticmethod
def _topic_from_match(match: Dict[str, Any]) -> Topic:
"""Builds a Topic model from a flattened topic_match dict.
"""
domain_name = match.get("domain")
field_name = match.get("field")
subfield_name = match.get("subfield")
domain = TopicDomain(display_name=domain_name) if domain_name else None
field = TopicField(display_name=field_name) if field_name else None
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
return Topic(
id=match.get("topic_id"),
display_name=match.get("topic_display_name"),
domain=domain,
field=field,
subfield=subfield,
)
@@ -1,293 +1,435 @@
# coding: utf-8
"""
DFG Project Clean Model
DFG Project Clean Model (v2)
Summary model that consolidates all scattered person and institution fields
from the raw projects_dfg_all index into clean, unified lists.
Enriched, consolidated model built on top of the structured
projects_dfg_v2 API models (DFGProject / DFGPerson / DFGInstitute),
rather than the old flat projects_dfg_all Elasticsearch index.
"""
from typing import Optional, List, Set
from typing import List, Optional
from pydantic import BaseModel, ConfigDict, Field
from inse.models.projects_dfg_v2.project.dfg_project import DFGProject
from inse.models.projects_dfg_v2.project.dfg_project_persons_inner import (
DFGProjectPersonsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_institutions_inner import (
DFGProjectInstitutionsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_subprojects_inner import (
DFGProjectSubprojectsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_publications_inner import (
DFGProjectPublicationsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import (
DFGProjectFachgebieteInner,
)
from inse.topics.model import Topic
class DfgProjectPersonRole(BaseModel):
"""A person associated with the project, together with their role."""
model_config = ConfigDict(populate_by_name=True)
person_id: Optional[int] = Field(default=None, description="DFG person ID")
full_name: Optional[str] = Field(default=None, description="Full name of the person")
orcid_id: Optional[str] = Field(
default=None,
description=(
"ORCID iD, if known. Not present on the project's embedded person "
"record (DFGProjectPersonsInner) -- only populated if the caller "
"cross-references the full DFGPerson record via person_id and "
"calls DfgProjectDetails.enrich_orcids afterwards."
),
)
role_key: Optional[str] = Field(
default=None, description="Machine-readable role key (e.g. 'antragsteller')"
)
role_label_de: Optional[str] = Field(default=None, description="Role label (German)")
role_label_en: Optional[str] = Field(default=None, description="Role label (English)")
affiliation_de: Optional[str] = Field(
default=None, description="Person's affiliation at time of project (German)"
)
affiliation_en: Optional[str] = Field(
default=None, description="Person's affiliation at time of project (English)"
)
is_deceased: Optional[bool] = Field(default=None, description="Whether the person is deceased")
is_head: Optional[bool] = Field(
default=None, description="Whether this person is highlighted as the project head"
)
@classmethod
def from_inner(cls, p: DFGProjectPersonsInner) -> "DfgProjectPersonRole":
return cls(
person_id=p.person_id,
full_name=p.full_name,
role_key=p.role_key,
role_label_de=p.role_label_de,
role_label_en=p.role_label_en,
affiliation_de=p.affiliation_de,
affiliation_en=p.affiliation_en,
is_deceased=p.is_deceased,
is_head=p.is_head_display,
)
class DfgProjectInstitutionRole(BaseModel):
"""An institution associated with the project, together with its role."""
model_config = ConfigDict(populate_by_name=True)
institute_id: Optional[int] = Field(default=None, description="DFG institute ID")
name_de: Optional[str] = Field(default=None, description="Institution name (German)")
name_en: Optional[str] = Field(default=None, description="Institution name (English)")
role_key: Optional[str] = Field(default=None, description="Machine-readable role key")
role_label_de: Optional[str] = Field(default=None, description="Role label (German)")
role_label_en: Optional[str] = Field(default=None, description="Role label (English)")
is_dissolved: Optional[bool] = Field(
default=None, description="Whether the institution has since been dissolved"
)
is_head: Optional[bool] = Field(
default=None, description="Whether this institution is highlighted as the lead institution"
)
@classmethod
def from_inner(cls, i: DFGProjectInstitutionsInner) -> "DfgProjectInstitutionRole":
return cls(
institute_id=i.institute_id,
name_de=i.institute_name_de,
name_en=i.institute_name_en,
role_key=i.role_key,
role_label_de=i.role_label_de,
role_label_en=i.role_label_en,
is_dissolved=i.is_dissolved,
is_head=i.is_head_display,
)
class DfgProjectSubprojectSummary(BaseModel):
"""A lightweight reference to a sub-project of this project."""
model_config = ConfigDict(populate_by_name=True)
subproject_id: Optional[int] = None
title_de: Optional[str] = None
title_en: Optional[str] = None
short_title: Optional[str] = None
role_label_de: Optional[str] = Field(
default=None, description="Role of the sub-project lead within the sub-project"
)
person_full_name: Optional[str] = Field(
default=None, description="Sub-project lead, derived from first/last name fields"
)
status_de: Optional[str] = None
funding_start: Optional[int] = None
funding_end: Optional[int] = None
@classmethod
def from_inner(cls, s: DFGProjectSubprojectsInner) -> "DfgProjectSubprojectSummary":
person_full_name = None
if s.person_first_names or s.person_last_name:
person_full_name = " ".join(
part for part in [s.person_first_names, s.person_last_name] if part
).strip() or None
return cls(
subproject_id=s.subproject_id,
title_de=s.title_de,
title_en=s.title_en,
short_title=s.short_title,
role_label_de=s.role_label_de,
person_full_name=person_full_name,
status_de=s.status_de,
funding_start=s.funding_start,
funding_end=s.funding_end,
)
class DfgProjectPublicationSummary(BaseModel):
"""A lightweight reference to a publication resulting from the project."""
model_config = ConfigDict(populate_by_name=True)
publication_id: Optional[int] = None
title: Optional[str] = None
authors_editors: Optional[str] = None
doi: Optional[str] = None
publication_year: Optional[int] = None
@classmethod
def from_inner(cls, p: DFGProjectPublicationsInner) -> "DfgProjectPublicationSummary":
return cls(
publication_id=p.publication_id,
title=p.title,
authors_editors=p.authors_editors,
doi=p.doi,
publication_year=p.publication_year,
)
class DfgProjectSubjectArea(BaseModel):
"""A single subject-area classification entry (DFG 'Fachsystematik')."""
model_config = ConfigDict(populate_by_name=True)
fach: Optional[str] = None
fachgebiet: Optional[str] = None
fachkollegium: Optional[str] = None
wissenschaftsbereich: Optional[str] = None
@classmethod
def from_inner(cls, f: DFGProjectFachgebieteInner) -> "DfgProjectSubjectArea":
return cls(
fach=f.fach,
fachgebiet=f.fachgebiet,
fachkollegium=f.fachkollegium,
wissenschaftsbereich=f.wissenschaftsbereich,
)
class DfgProjectDetails(BaseModel):
"""
Clean summary model for a DFG project, consolidating all person roles
and institution references into unified lists.
Clean, enriched summary model for a DFG project.
"""
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
model_config = ConfigDict(populate_by_name=True, validate_assignment=True)
id: Optional[int] = Field(default=None, description="The DFG project ID")
link: Optional[str] = Field(default=None, description="Canonical DFG link to the project")
page_url: Optional[str] = Field(default=None, description="DFG GEPRIS page URL")
external_link: Optional[str] = Field(
default=None, description="External project website/link, if provided"
)
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"
title_de: Optional[str] = Field(default=None, description="Project title (German)")
title_en: Optional[str] = Field(default=None, description="Project title (English)")
description_de: Optional[str] = Field(default=None, description="Project abstract (German)")
description_en: Optional[str] = Field(default=None, description="Project abstract (English)")
final_report_abstract_de: Optional[str] = Field(
default=None, description="Final report abstract (German), if the project has concluded"
)
description: Optional[str] = Field(
default=None, description="The description of the DFG project"
final_report_abstract_en: Optional[str] = Field(
default=None, description="Final report abstract (English), if the project has concluded"
)
project_identifier: Optional[str] = Field(
default=None,
description="The project identifier of the DFG project",
)
project_identifier_de: Optional[str] = Field(default=None, description="DFG project identifier (German)")
project_identifier_en: Optional[str] = Field(default=None, description="DFG project identifier (English)")
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"
)
funding_start: Optional[int] = Field(default=None, description="Funding start year")
funding_end: Optional[int] = Field(default=None, description="Funding end year")
funding_period_de: Optional[str] = Field(default=None, description="Human-readable funding period (German)")
funding_period_en: Optional[str] = Field(default=None, description="Human-readable funding period (English)")
funding_type_de: Optional[str] = Field(default=None, description="Funding type / programme (German)")
funding_type_en: Optional[str] = Field(default=None, description="Funding type / programme (English)")
funding_type_key: Optional[str] = Field(default=None, description="Machine-readable funding type key")
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",
default=None, description="DFG procedure / template type (e.g. Sachbeihilfe, SFB, GRK)"
)
website: Optional[str] = Field(
default=None, description="The project website"
is_transfer_project: Optional[bool] = Field(
default=None, description="Whether this is a transfer project"
)
# Unified person list: all person names from any role
website_html_de: Optional[str] = Field(
default=None, description="Raw project website HTML content (German), as served by DFG"
)
website_html_en: Optional[str] = Field(
default=None, description="Raw project website HTML content (English), as served by DFG"
)
equipment_group: Optional[str] = Field(
default=None,
description="Large-equipment (Großgerät) group, for equipment-funding projects",
)
equipment_name: Optional[str] = Field(
default=None,
description="Large-equipment (Großgerät) name, for equipment-funding projects",
)
subject_area_de: Optional[str] = Field(default=None, description="Subject area, summary text (German)")
subject_area_en: Optional[str] = Field(default=None, description="Subject area, summary text (English)")
subject_classifications: List[DfgProjectSubjectArea] = Field(
default_factory=list,
description="Detailed DFG subject-area classification entries (Fachsystematik)",
)
international_relation_de: Optional[str] = Field(
default=None, description="International reference/cooperation (German)"
)
international_relation_en: Optional[str] = Field(
default=None, description="International reference/cooperation (English)"
)
# Structured, role-aware person and institution lists
persons: List[DfgProjectPersonRole] = Field(
default_factory=list,
description="All persons associated with the project, each with their role",
)
institutions: List[DfgProjectInstitutionRole] = Field(
default_factory=list,
description="All institutions associated with the project, each with their role",
)
# Convenience flat views, derived from the structured lists above
associated_persons: List[str] = Field(
default_factory=list,
description="All persons associated with the DFG project (any role)",
description="Flat, de-duplicated list of all person full names (convenience view)",
)
# Unified institution list: all institutions involved
institutions: List[str] = Field(
associated_institutions: List[str] = Field(
default_factory=list,
description="All institutions associated with the DFG project",
description="Flat, de-duplicated list of all institution names (convenience view)",
)
# Sub-project reference
subproject_of: Optional[str] = Field(
default=None,
description="Parent project this is a sub-project of",
# Parent / sub-project structure
parent_project_id: Optional[int] = Field(default=None, description="Parent project ID, if this is a sub-project")
parent_title_de: Optional[str] = Field(default=None, description="Parent project title (German)")
parent_title_en: Optional[str] = Field(default=None, description="Parent project title (English)")
subprojects: List[DfgProjectSubprojectSummary] = Field(
default_factory=list, description="Sub-projects of this project, if any"
)
publications: List[DfgProjectPublicationSummary] = Field(
default_factory=list, description="Publications resulting from the project"
)
topics: Optional[List[Topic]] = Field(
default_factory=list, description="OpenAlex topics associated with the project ID"
)
@classmethod
def from_dfg_project(cls, project: DFGProject) -> "DfgProjectDetails":
"""
Build a DfgProjectDetails from a fully-typed DFGProject instance
(e.g. as returned by the projects_dfg_v2 API client).
"""
persons = [DfgProjectPersonRole.from_inner(p) for p in (project.persons or [])]
institutions = [
DfgProjectInstitutionRole.from_inner(i) for i in (project.institutions or [])
]
subprojects = [
DfgProjectSubprojectSummary.from_inner(s) for s in (project.subprojects or [])
]
publications = [
DfgProjectPublicationSummary.from_inner(p) for p in (project.publications or [])
]
subject_classifications = [
DfgProjectSubjectArea.from_inner(f) for f in (project.fachgebiete or [])
]
# De-duplicated flat views, order-preserving
seen_persons = set()
associated_persons = []
for p in persons:
if p.full_name and p.full_name not in seen_persons:
seen_persons.add(p.full_name)
associated_persons.append(p.full_name)
seen_institutions = set()
associated_institutions = []
for i in institutions:
name = i.name_de or i.name_en
if name and name not in seen_institutions:
seen_institutions.add(name)
associated_institutions.append(name)
return cls(
id=project.id or project.project_id,
link=project.link,
page_url=project.page_url,
external_link=project.external_link,
title_de=project.title_de,
title_en=project.title_en,
description_de=project.abstract_de,
description_en=project.abstract_en,
final_report_abstract_de=project.final_report_abstract_de,
final_report_abstract_en=project.final_report_abstract_en,
project_identifier_de=project.project_identifier_de,
project_identifier_en=project.project_identifier_en,
funding_start=project.funding_start,
funding_end=project.funding_end,
funding_period_de=project.funding_period_de,
funding_period_en=project.funding_period_en,
funding_type_de=project.funding_type_de,
funding_type_en=project.funding_type_en,
funding_type_key=project.funding_type_key,
dfg_procedure=project.template_type,
is_transfer_project=project.is_transfer_project,
website_html_de=project.website_html_de,
website_html_en=project.website_html_en,
equipment_group=project.equipment_group,
equipment_name=project.equipment_name,
subject_area_de=project.subject_area_de,
subject_area_en=project.subject_area_en,
subject_classifications=subject_classifications,
international_relation_de=project.international_relation_de,
international_relation_en=project.international_relation_en,
persons=persons,
institutions=institutions,
associated_persons=associated_persons,
associated_institutions=associated_institutions,
parent_project_id=project.parent_project_id,
parent_title_de=project.parent_title_de,
parent_title_en=project.parent_title_en,
subprojects=subprojects,
publications=publications,
topics=project.topics,
)
@classmethod
def from_dict(cls, obj: dict) -> "DfgProjectDetails":
"""Convenience constructor from a raw dict (e.g. a JSON API response body)."""
obj = cls._sanitize_raw_project_dict(obj)
return cls.from_dfg_project(DFGProject.from_dict(obj))
@staticmethod
def _sanitize_raw_project_dict(obj: dict) -> dict:
"""
Work around known mismatches between the generated DFGProject model
and the actual shape of API/index data, before handing off to
DFGProject.from_dict (which would otherwise raise a ValidationError
and abort the whole parse).
"""
if isinstance(obj.get("subject_classifications"), list):
obj = dict(obj)
obj.pop("subject_classifications", None)
return obj
@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.
Compatibility constructor for callers still reading from an
Elasticsearch hit (e.g. `{"_id": ..., "_source": {...}}`), matching
the old model's from_elastic_hit signature.
"""
source = dict(hit.get("_source", {}))
source = hit.get("_source", {})
if source.get("id") is None and source.get("project_id") is None:
raw_id = hit.get("_id")
if raw_id is not None:
try:
source["id"] = int(raw_id)
except (TypeError, ValueError):
# Non-numeric _id (e.g. a composite/legacy key) - leave
# id unset rather than fail the whole parse.
pass
associated_persons: Set[str] = set()
institutions: Set[str] = set()
return cls.from_dict(source)
# --- Collect all persons and institutions from nested persons array ---
persons_list = source.get("persons", [])
if isinstance(persons_list, list):
for p in persons_list:
if isinstance(p, dict):
full_name = p.get("full_name")
if full_name:
associated_persons.add(full_name.strip())
aff_de = p.get("affiliation_de")
if aff_de:
institutions.add(aff_de.strip())
aff_en = p.get("affiliation_en")
if aff_en:
institutions.add(aff_en.strip())
# --- 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") or source.get("page_url"),
title=source.get("title") or source.get("title_de") or source.get("title_en"),
description=source.get("description") or source.get("abstract_de") or source.get("abstract_en"),
project_identifier=source.get("Projektkennung") or source.get("project_identifier_de") or source.get("project_identifier_en"),
funding_start_date=str(source.get("funding_start")) if source.get("funding_start") is not None else None,
funding_end_date=str(source.get("funding_end")) if source.get("funding_end") is not None else None,
dfg_procedure=source.get("DFG-Verfahren") or source.get("template_type"),
subject_area=source.get("Fachliche Zuordnung") or source.get("subject_area_de") or source.get("subject_area_en"),
funding_type=source.get("Förderung") or source.get("funding_type_sort"),
international_reference=source.get("Internationaler Bezug") or source.get("international_relation_de") or source.get("international_relation_en"),
website=source.get("Webseite"),
associated_persons=sorted(associated_persons), # sorted for consistency
institutions=sorted(institutions),
subproject_of=source.get("Teilprojekt zu") or source.get("parent_project_id"),
)
# --- 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)
def enrich_orcids(self, persons_by_id: dict) -> None:
"""
Fill in orcid_id on each entry in `self.persons`, given a mapping of
person_id -> DFGPersonPerson (or DFGPerson) for the persons involved
in this project
"""
for person in self.persons:
record = persons_by_id.get(person.person_id)
if record is not None:
person.orcid_id = getattr(record, "orcid_id", None)
@@ -29,6 +29,7 @@ from inse.models.projects_dfg_v2.project.dfg_project_subprojects_inner import DF
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
class DFGProject(BaseModel):
"""
@@ -52,7 +53,7 @@ class DFGProject(BaseModel):
funding_type_key: Optional[StrictStr] = None
funding_type_sort: Optional[StrictStr] = None
id: Optional[StrictInt] = None
institution_roles_order: Optional[StrictStr] = None
institution_roles_order: Optional[list[StrictStr]] = None
institutions: Optional[List[DFGProjectInstitutionsInner]] = None
international_relation_de: Optional[StrictStr] = None
international_relation_en: Optional[StrictStr] = None
@@ -62,7 +63,7 @@ class DFGProject(BaseModel):
parent_project_id: Optional[StrictInt] = None
parent_title_de: Optional[StrictStr] = None
parent_title_en: Optional[StrictStr] = None
person_roles_order: Optional[StrictStr] = None
person_roles_order: Optional[list[StrictStr]] = None
persons: Optional[List[DFGProjectPersonsInner]] = None
project: Optional[DFGProjectProject] = None
project_id: Optional[StrictInt] = None
@@ -72,13 +73,14 @@ class DFGProject(BaseModel):
subject_area_de: Optional[StrictStr] = None
subject_area_en: Optional[StrictStr] = None
subject_classifications: Optional[DFGProjectFachgebieteInner] = None
subproject_order: Optional[StrictStr] = None
subproject_order: Optional[list[StrictStr]] = None
subprojects: Optional[List[DFGProjectSubprojectsInner]] = None
template_type: Optional[StrictStr] = None
title_de: Optional[StrictStr] = None
title_en: Optional[StrictStr] = None
website_html_de: Optional[StrictStr] = None
website_html_en: Optional[StrictStr] = None
topics: Optional[List[Topic]] = None
__properties: ClassVar[List[str]] = ["abstract_de", "abstract_en", "equipment_group", "equipment_name", "external_link", "fachgebiete", "fetched_at", "final_report_abstract_de", "final_report_abstract_en", "funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "id", "institution_roles_order", "institutions", "international_relation_de", "international_relation_en", "is_transfer_project", "link", "page_url", "parent_project_id", "parent_title_de", "parent_title_en", "person_roles_order", "persons", "project", "project_id", "project_identifier_de", "project_identifier_en", "publications", "subject_area_de", "subject_area_en", "subject_classifications", "subproject_order", "subprojects", "template_type", "title_de", "title_en", "website_html_de", "website_html_en"]
model_config = ConfigDict(
@@ -168,9 +170,18 @@ class DFGProject(BaseModel):
"""Create an instance of DFGProject from a dict"""
if obj is None:
return None
topics_raw = obj.get("topics") or []
if not isinstance(obj, dict):
return cls.model_validate(obj)
topics = None
if isinstance(topics_raw, list) and topics_raw:
sorted_topics_raw = sorted(
(t for t in topics_raw if isinstance(t, dict)),
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
_obj = cls.model_validate({
"abstract_de": obj.get("abstract_de"),
@@ -217,8 +228,29 @@ class DFGProject(BaseModel):
"title_de": obj.get("title_de"),
"title_en": obj.get("title_en"),
"website_html_de": obj.get("website_html_de"),
"website_html_en": obj.get("website_html_en")
"website_html_en": obj.get("website_html_en"),
"topics": topics,
})
return _obj
@staticmethod
def _topic_from_match(match: Dict[str, Any]) -> Topic:
"""Builds a Topic model from a flattened topic_match dict.
"""
domain_name = match.get("domain")
field_name = match.get("field")
subfield_name = match.get("subfield")
domain = TopicDomain(display_name=domain_name) if domain_name else None
field = TopicField(display_name=field_name) if field_name else None
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
return Topic(
id=match.get("topic_id"),
display_name=match.get("topic_display_name"),
domain=domain,
field=field,
subfield=subfield,
)
@@ -25,7 +25,8 @@ from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic
from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink
from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc
from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis
from inse.authors.v2.model import AuthorPage
from inse.models.openalex.topic import Topic
class Fp7ProjectDetails(BaseModel):
"""
@@ -70,6 +71,9 @@ class Fp7ProjectDetails(BaseModel):
organization_count: Optional[int] = Field(default=None, alias="organizationCount")
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
ipr_count: Optional[int] = Field(default=None, alias="iprCount")
# OpenAlex related fields
oa_topics: Optional[List[Topic]] = Field(default=None, alias="oaTopics", description="OpenAlex topics associated with the project")
oa_authors: Optional[AuthorPage] = Field(default=None, alias="oaAuthors", description="OpenAlex authors associated with the project")
__properties: ClassVar[List[str]] = [
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
@@ -79,7 +83,7 @@ class Fp7ProjectDetails(BaseModel):
"title", "topics", "totalCost",
"organizations", "publications", "iprs", "reportSummaries",
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
"organizationCount", "publicationCount", "iprCount"
"organizationCount", "publicationCount", "iprCount","oaTopics", "oaAuthors"
]
model_config = ConfigDict(
@@ -163,6 +167,10 @@ class Fp7ProjectDetails(BaseModel):
"organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0,
"publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0,
"iprCount": len(obj.get("iprs", [])) if obj.get("iprs") else 0,
# # OpenAlex related fields
# "oaTopics": [Topic.from_dict(topic) for topic in obj.get("oaTopics", [])] if obj.get("oaTopics") else None,
# "oaAuthors": AuthorPage.from_dict(obj.get("oaAuthors")) if obj.get("oaAuthors") else None,
})
return _obj
@@ -178,6 +186,8 @@ class Fp7ProjectDetails(BaseModel):
web_links: Optional[List[Fp7WebLink]] = None,
eurosci_voc: Optional[List[Fp7EurosciVoc]] = None,
legal_basis_list: Optional[List[Fp7LegalBasis]] = None,
oa_topics: Optional[List[Topic]] = None,
oa_authors: Optional[AuthorPage] = None,
) -> Self:
"""
Factory method to create a detailed project from a base project and its relations.
@@ -211,4 +221,6 @@ class Fp7ProjectDetails(BaseModel):
organizationCount=len(organizations) if organizations else 0,
publicationCount=len(publications) if publications else 0,
iprCount=len(iprs) if iprs else 0,
oa_authors=oa_authors,
oa_topics=oa_topics or [],
)
@@ -26,7 +26,8 @@ from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLi
from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc
from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis
from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI
from inse.authors.v2.model import AuthorPage
from inse.models.openalex.topic import Topic
class H2020ProjectDetails(BaseModel):
"""
@@ -73,7 +74,10 @@ class H2020ProjectDetails(BaseModel):
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount")
erc_pi_count: Optional[int] = Field(default=None, alias="ercPiCount")
# OpenAlex related fields
oa_topics: Optional[List[Topic]] = Field(default=None, alias="oaTopics", description="OpenAlex topics associated with the project")
oa_authors: Optional[AuthorPage] = Field(default=None, alias="oaAuthors", description="OpenAlex authors associated with the project")
__properties: ClassVar[List[str]] = [
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
"endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
@@ -84,6 +88,7 @@ class H2020ProjectDetails(BaseModel):
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
"ercPrincipalInvestigators",
"organizationCount", "publicationCount", "deliverableCount", "ercPiCount"
,"oaTopics", "oaAuthors"
]
model_config = ConfigDict(
@@ -185,6 +190,8 @@ class H2020ProjectDetails(BaseModel):
eurosci_voc: Optional[List[H2020EurosciVoc]] = None,
legal_basis_list: Optional[List[H2020LegalBasis]] = None,
erc_principal_investigators: Optional[List[H2020ErcPI]] = None,
oa_topics: Optional[List[Topic]] = None,
oa_authors: Optional[AuthorPage] = None,
) -> Self:
"""
Factory method to create a detailed project from a base project and its relations.
@@ -221,4 +228,6 @@ class H2020ProjectDetails(BaseModel):
publicationCount=len(publications) if publications else 0,
deliverableCount=len(deliverables) if deliverables else 0,
ercPiCount=len(erc_principal_investigators) if erc_principal_investigators else 0,
oa_authors=oa_authors,
oa_topics=oa_topics or [],
)
@@ -25,7 +25,8 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic
from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink
from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
from inse.authors.v2.model import AuthorPage
from inse.models.openalex.topic import Topic
class HEUProjectDetails(BaseModel):
"""
@@ -70,7 +71,9 @@ class HEUProjectDetails(BaseModel):
organization_count: Optional[int] = Field(default=None, alias="organizationCount")
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount")
# OpenAlex related fields
oa_topics: Optional[List[Topic]] = Field(default=None, alias="oaTopics", description="OpenAlex topics associated with the project")
oa_authors: Optional[AuthorPage] = Field(default=None, alias="oaAuthors", description="OpenAlex authors associated with the project")
__properties: ClassVar[List[str]] = [
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
"endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
@@ -79,7 +82,7 @@ class HEUProjectDetails(BaseModel):
"title", "topics", "totalCost",
"organizations", "publications", "deliverables", "reportSummaries",
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
"organizationCount", "publicationCount", "deliverableCount"
"organizationCount", "publicationCount", "deliverableCount","oaTopics", "oaAuthors"
]
model_config = ConfigDict(
@@ -178,6 +181,8 @@ class HEUProjectDetails(BaseModel):
web_links: Optional[List[HEUWebLink]] = None,
eurosci_voc: Optional[List[HEUEurosciVoc]] = None,
legal_basis_list: Optional[List[HEULegalBasis]] = None,
oa_topics: Optional[List[Topic]] = None,
oa_authors: Optional[AuthorPage] = None,
) -> Self:
"""
Factory method to create a detailed project from a base project and its relations.
@@ -211,4 +216,6 @@ class HEUProjectDetails(BaseModel):
organizationCount=len(organizations) if organizations else 0,
publicationCount=len(publications) if publications else 0,
deliverableCount=len(deliverables) if deliverables else 0,
oa_authors=oa_authors,
oa_topics=oa_topics or [],
)
@@ -46,7 +46,7 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLin
from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
from inse.projects.model import EuCordisProjectType, EuCordisProjectSummary
from inse.projects.model import (
EuCordisProjectType,
EuCordisProjectSearchPage,
@@ -56,7 +56,7 @@ from inse.projects.model import (
EuCordisEurosciVocSummary,
)
from inse.projects.logic import get_eu_project_ids_by_openalex_topic_ids, get_openalex_topics_for_eu_projects
from inse.models.openalex.topic import Topic
settings = get_settings()
logger = logging.getLogger(__name__)
@@ -96,24 +96,13 @@ _HEU_ENTITY_CONFIGS = [
{"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc},
{"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis},
]
async def get_enriched_cordis_project_by_id(
project_id: str,
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
"""
Fetches and enriches a single Cordis EU project by its ID across all programme types.
Args:
project_id: The project ID to fetch.
Returns:
The enriched detailed project model, or None if not found.
"""
if not project_id:
return None
query = {"bool": {"filter": [{"term": {"id": project_id}}]}}
response = await elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
@@ -130,33 +119,46 @@ async def get_enriched_cordis_project_by_id(
index = hit.get("_index", "")
source = hit.get("_source", {})
program_type = _determine_program_type_from_index(index)
project_type = EuCordisProjectType.from_index_name(index)
enrichers = {
"fp7": _enrich_fp7_project,
"h2020": _enrich_h2020_project,
"heu": _enrich_heu_project,
EuCordisProjectType.FP7: _enrich_fp7_project,
EuCordisProjectType.H2020: _enrich_h2020_project,
EuCordisProjectType.HEU: _enrich_heu_project,
}
enricher = enrichers.get(program_type)
enricher = enrichers.get(project_type)
if enricher is None:
logger.warning(f"Unknown programme type for index: {index}")
return CordisEuProject.model_validate(source)
return await enricher(project_id, source)
return await enricher(project_id, source, project_type)
# helpers
def _determine_program_type_from_index(index: str) -> str:
"""Determines the programme type from the Elasticsearch index name."""
index_lower = index.lower()
if "fp7" in index_lower:
return "fp7"
if "horizon_2020" in index_lower:
return "h2020"
if "heu" in index_lower or "horizon_europe" in index_lower:
return "heu"
return "unknown"
async def _fetch_authors_and_topics_for_project(
project_id: str,
project_type: EuCordisProjectType,
) -> Tuple[Optional[AuthorPage], List[Topic]]:
"""Fetches OpenAlex authors and mapped topics for a single project."""
authors_lookup, topics_lookup = await asyncio.gather(
get_openalex_authors_for_projects_ids({project_type: [project_id]}),
get_openalex_topics_for_eu_projects({project_type: [project_id]}),
)
author_page = authors_lookup.get((project_type, project_id))
raw_topic_matches = sorted(
topics_lookup.get((project_type, project_id), []),
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
topics = [
EuCordisProjectSummary.topic_from_match(match)
for match in raw_topic_matches
if isinstance(match, dict)
]
return author_page, topics
async def _fetch_related_entities_parallel(
project_id: str,
@@ -244,10 +246,10 @@ async def _fetch_related_entities(
return grouped
async def _enrich_fp7_project(
project_id: str,
project_source: Dict[str, Any],
project_type: EuCordisProjectType,
) -> Optional[Fp7ProjectDetails]:
"""Enriches a single FP7 project with all related data."""
try:
@@ -256,41 +258,97 @@ async def _enrich_fp7_project(
logger.error(f"Failed to validate FP7 project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
related, (authors, topics) = await asyncio.gather(
_fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS),
_fetch_authors_and_topics_for_project(project_id, project_type),
)
return Fp7ProjectDetails.from_project_with_relations(project=project, **related)
return Fp7ProjectDetails.from_project_with_relations(
project=project, oa_authors=authors, oa_topics=topics, **related
)
async def _enrich_h2020_project(
project_id: str,
project_source: Dict[str, Any],
project_type: EuCordisProjectType,
) -> Optional[H2020ProjectDetails]:
"""Enriches a single H2020 project with all related data."""
try:
project = H2020Project.model_validate(project_source)
except Exception as e:
logger.error(f"Failed to validate H2020 project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
related, (authors, topics) = await asyncio.gather(
_fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS),
_fetch_authors_and_topics_for_project(project_id, project_type),
)
return H2020ProjectDetails.from_project_with_relations(project=project, **related)
return H2020ProjectDetails.from_project_with_relations(
project=project, oa_authors=authors, oa_topics=topics, **related
)
async def _enrich_heu_project(
project_id: str,
project_source: Dict[str, Any],
project_type: EuCordisProjectType,
) -> Optional[HEUProjectDetails]:
"""Enriches a single Horizon Europe project with all related data."""
try:
project = HEUProject.model_validate(project_source)
except Exception as e:
logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
related, (authors, topics) = await asyncio.gather(
_fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS),
_fetch_authors_and_topics_for_project(project_id, project_type),
)
return HEUProjectDetails.from_project_with_relations(project=project, **related)
return HEUProjectDetails.from_project_with_relations(
project=project, oa_authors=authors, oa_topics=topics, **related
)
async def _enrich_h2020_project(
project_id: str,
project_source: Dict[str, Any],
project_type: EuCordisProjectType,
) -> Optional[H2020ProjectDetails]:
try:
project = H2020Project.model_validate(project_source)
except Exception as e:
logger.error(f"Failed to validate H2020 project {project_id}: {e}")
return None
related, (authors, topics) = await asyncio.gather(
_fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS),
_fetch_authors_and_topics_for_project(project_id, project_type),
)
return H2020ProjectDetails.from_project_with_relations(
project=project, oa_authors=authors, oa_topics=topics, **related
)
async def _enrich_heu_project(
project_id: str,
project_source: Dict[str, Any],
project_type: EuCordisProjectType,
) -> Optional[HEUProjectDetails]:
try:
project = HEUProject.model_validate(project_source)
except Exception as e:
logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}")
return None
related, (authors, topics) = await asyncio.gather(
_fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS),
_fetch_authors_and_topics_for_project(project_id, project_type),
)
return HEUProjectDetails.from_project_with_relations(
project=project, oa_authors=authors, oa_topics=topics, **related
)
+56 -46
View File
@@ -137,63 +137,73 @@ async def get_dfg_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
async def get_openalex_topics_for_dfg_projects(
project_ids: List[str],
) -> Dict[int, List[Dict[str, Any]]]:
"""Fetches OpenAlex topic matches for the given DFG project IDs.
Args:
project_ids (List[str]): The DFG project IDs to fetch topics for.
Returns:
Dict[int, List[Dict[str, Any]]]: Mapping of project_id -> list of topic match dicts,
each containing topic_id, topic_display_name, domain, field, subfield, rank.
async def get_openalex_topics_for_bund_projects(project_ids: List[str]) -> Dict[str, List[Dict]]:
"""
Retrieve OpenAlex topic details for a list of BUND project IDs.
Returns a dict mapping `project_id` -> list of topic_match objects.
"""
if not project_ids:
return {}
topic_lookup: Dict[int, List[Dict[str, Any]]] = {}
body: Dict[str, Any] = {
"size": 10000,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
"_source": ["project_id", "topic_matches"]
}
page_size = 1000
from_ = 0
# print(f"Fetching topics for {len(project_ids)} DFG projects in batches of {page_size}...{project_ids}")
while True:
response = await elasticsearch.search(
index=ESIndex.PROJECTS_DFG_TOPICS,
cluster=ESCluster.INSE,
body={
"size": page_size,
"from": from_,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
},
)
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
body=body,
cluster=ESCluster.INSE
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
lookup: Dict[str, List[Dict]] = {}
for hit in response.get("hits", {}).get("hits", []):
src = hit["_source"]
pid = src.get("project_id")
if pid:
lookup[pid] = src.get("topic_matches", [])
return lookup
async def get_openalex_topics_for_dfg_projects(
project_ids: List[str],
) -> Dict[str, List[Dict]]:
"""
Retrieve OpenAlex topic details for a list of DFG project IDs.
Returns a dict mapping `project_id` -> list of topic_match objects.
"""
if not project_ids:
return {}
for hit in hits:
source = hit["_source"]
project_id = int(source.get("project_id"))
if project_id is None:
continue
body: Dict[str, Any] = {
"size": 10000,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
"_source": ["project_id", "topic_matches"]
}
topic_matches = source.get("topic_matches") or []
if isinstance(topic_matches, dict):
topic_matches = [topic_matches]
response = await elasticsearch.search(
index=ESIndex.PROJECTS_DFG_TOPICS,
body=body,
cluster=ESCluster.INSE
)
topic_lookup.setdefault(project_id, []).extend(topic_matches)
lookup: Dict[str, List[Dict]] = {}
for hit in response.get("hits", {}).get("hits", []):
src = hit["_source"]
pid = src.get("project_id")
if pid:
lookup[str(pid)] = src.get("topic_matches", [])
if len(hits) < page_size:
break
from_ += page_size
#logger.info(f"Fetched topics for {len(topic_lookup)} DFG projects.")
return topic_lookup
return lookup
async def get_person_institutes(
person_ids: list[int],
-1
View File
@@ -91,7 +91,6 @@ class BundProjectSummary(BundProject):
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
oa_topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
print(f"oa_topics: {oa_topics}")
return cls(
funding_code=source.get("Förderkennzeichen"),
department=source.get("Ressort"),
@@ -21,7 +21,7 @@ from inse.models.dfg_project_details import DfgProjectDetails
from inse.models.bund_project_details import BundProjectDetails
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes
from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes, get_openalex_topics_for_bund_projects
settings = get_settings()
@@ -204,10 +204,13 @@ async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails
query=query,
size=1,
)
hits = response.get("hits", {}).get("hits", [])
if hits:
hit = hits[0]
elastic_id = hit["_id"]
topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=[elastic_id])
hit["_source"]["oa_topics"] = topic_lookup.get(elastic_id, [])
details = BundProjectDetails.from_elastic_hit(hit=hit)
return details
return None
@@ -679,6 +682,7 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
Returns:
Optional[DfgProjectDetails]: The project details or None if not found.
"""
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=[project_id])
query = {"ids": {"values": [project_id]}}
response = await elasticsearch.search(
@@ -690,6 +694,7 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
if hits:
hit = hits[0]
hit["_source"]["topics"] = topic_lookup.get(project_id, [])
details = DfgProjectDetails.from_elastic_hit(hit=hit)
return details
return None
@@ -723,43 +728,10 @@ async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
body=body,
cluster=ESCluster.INSE
)
print(f"Received response for topic_ids {topic_ids}: {json.dumps(response, indent=2)}")
buckets = response.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
return [bucket["key"] for bucket in buckets]
async def get_openalex_topics_for_bund_projects(project_ids: List[str]) -> Dict[str, List[Dict]]:
"""
Retrieve OpenAlex topic details for a list of BUND project IDs.
Returns a dict mapping `project_id` -> list of topic_match objects.
"""
if not project_ids:
return {}
body: Dict[str, Any] = {
"size": 10000,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
"_source": ["project_id", "topic_matches"]
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
body=body,
cluster=ESCluster.INSE
)
lookup: Dict[str, List[Dict]] = {}
for hit in response.get("hits", {}).get("hits", []):
src = hit["_source"]
pid = src.get("project_id")
if pid:
lookup[pid] = src.get("topic_matches", [])
return lookup
async def search_bund_projects_with_filters(
executing_agency: Optional[List[str]] = None,
institution_ids: Optional[List[int]] = None,
@@ -914,7 +886,6 @@ async def search_bund_projects_with_filters(
# Enrich with OpenAlex topics
project_ids = [hit["_id"] for hit in hits]
topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=project_ids)
print(f"Enriched BUND projects with topics: {json.dumps(topic_lookup, indent=2)}")
for hit in hits:
hit["_source"]["oa_topics"] = topic_lookup.get(hit["_id"], [])
@@ -7,7 +7,7 @@ async def test_search_dfg_projects():
res = await projects_search_client.search_dfg_projects(
page=0,
size=5,
names=["Wolfgang Ahrens"],
names=["Bovensiepen"],
)
assert res is not None
assert res.total > 0
@@ -15,23 +15,19 @@ async def test_search_dfg_projects():
for element in res.elements:
assert element.id is not None
assert any(
all(part.lower() in name.lower() for part in "Wolfgang Ahrens".split())
all(part.lower() in name.lower() for part in "Bovensiepen".split())
for name in element.names
)
@pytest.mark.anyio
async def test_get_dfg_project_by_id():
# Get by ID of the project we found or a known one
known_id = "164008977"
known_id = 164008977
project = await projects_search_client.get_dfg_project_by_id(known_id)
assert project is not None
assert project.id == known_id
assert project.title is not None
assert project.title_de is not None
assert any(
all(part.lower() in person.lower() for part in "Wolfgang Ahrens".split())
for person in project.associated_persons
)
assert any(
"Leibniz" in inst
for inst in project.institutions
all(part.lower() in person.full_name.lower() for part in "Wolfgang Ahrens".split())
for person in project.persons
)
@@ -96,7 +96,12 @@ model/dfgInstitutionSummaryPage.ts
model/dfgPersonSummary.ts
model/dfgPersonSummaryPage.ts
model/dfgProjectDetails.ts
model/dfgProjectInstitutionRole.ts
model/dfgProjectPage.ts
model/dfgProjectPersonRole.ts
model/dfgProjectPublicationSummary.ts
model/dfgProjectSubjectArea.ts
model/dfgProjectSubprojectSummary.ts
model/dfgProjectSummary.ts
model/dfgProjectTopic.ts
model/dfgProjectTopics.ts
+44 -44
View File
@@ -1,57 +1,57 @@
/**
* 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 { Topic } from './topic';
/**
* 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<string>;
/**
* All institutions associated with the Bund project
*/
institutions?: Array<string>;
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<string>;
/**
* All institutions associated with the Bund project
*/
institutions?: Array<string>;
oa_topics?: Array<Topic> | null;
}
+70 -29
View File
@@ -1,41 +1,82 @@
/**
* 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 { DfgProjectPersonRole } from './dfgProjectPersonRole';
import { DfgProjectSubprojectSummary } from './dfgProjectSubprojectSummary';
import { DfgProjectInstitutionRole } from './dfgProjectInstitutionRole';
import { DfgProjectSubjectArea } from './dfgProjectSubjectArea';
import { Topic } from './topic';
import { DfgProjectPublicationSummary } from './dfgProjectPublicationSummary';
/**
* Clean summary model for a DFG project, consolidating all person roles and institution references into unified lists.
* Clean, enriched summary model for a DFG project.
*/
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<string>;
/**
* All institutions associated with the DFG project
*/
institutions?: Array<string>;
subproject_of?: string | null;
export interface DfgProjectDetails {
id?: number | null;
link?: string | null;
page_url?: string | null;
external_link?: string | null;
title_de?: string | null;
title_en?: string | null;
description_de?: string | null;
description_en?: string | null;
final_report_abstract_de?: string | null;
final_report_abstract_en?: string | null;
project_identifier_de?: string | null;
project_identifier_en?: string | null;
funding_start?: number | null;
funding_end?: number | null;
funding_period_de?: string | null;
funding_period_en?: string | null;
funding_type_de?: string | null;
funding_type_en?: string | null;
funding_type_key?: string | null;
dfg_procedure?: string | null;
is_transfer_project?: boolean | null;
website_html_de?: string | null;
website_html_en?: string | null;
equipment_group?: string | null;
equipment_name?: string | null;
subject_area_de?: string | null;
subject_area_en?: string | null;
/**
* Detailed DFG subject-area classification entries (Fachsystematik)
*/
subject_classifications?: Array<DfgProjectSubjectArea>;
international_relation_de?: string | null;
international_relation_en?: string | null;
/**
* All persons associated with the project, each with their role
*/
persons?: Array<DfgProjectPersonRole>;
/**
* All institutions associated with the project, each with their role
*/
institutions?: Array<DfgProjectInstitutionRole>;
/**
* Flat, de-duplicated list of all person full names (convenience view)
*/
associated_persons?: Array<string>;
/**
* Flat, de-duplicated list of all institution names (convenience view)
*/
associated_institutions?: Array<string>;
parent_project_id?: number | null;
parent_title_de?: string | null;
parent_title_en?: string | null;
/**
* Sub-projects of this project, if any
*/
subprojects?: Array<DfgProjectSubprojectSummary>;
/**
* Publications resulting from the project
*/
publications?: Array<DfgProjectPublicationSummary>;
topics?: Array<Topic> | null;
}
@@ -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.
*/
/**
* An institution associated with the project, together with its role.
*/
export interface DfgProjectInstitutionRole {
institute_id?: number | null;
name_de?: string | null;
name_en?: string | null;
role_key?: string | null;
role_label_de?: string | null;
role_label_en?: string | null;
is_dissolved?: boolean | null;
is_head?: boolean | null;
}
@@ -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.
*/
/**
* A person associated with the project, together with their role.
*/
export interface DfgProjectPersonRole {
person_id?: number | null;
full_name?: string | null;
orcid_id?: string | null;
role_key?: string | null;
role_label_de?: string | null;
role_label_en?: string | null;
affiliation_de?: string | null;
affiliation_en?: string | null;
is_deceased?: boolean | null;
is_head?: boolean | null;
}
@@ -0,0 +1,22 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A lightweight reference to a publication resulting from the project.
*/
export interface DfgProjectPublicationSummary {
publication_id?: number | null;
title?: string | null;
authors_editors?: string | null;
doi?: string | null;
publication_year?: number | null;
}
@@ -0,0 +1,21 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A single subject-area classification entry (DFG \'Fachsystematik\').
*/
export interface DfgProjectSubjectArea {
fach?: string | null;
fachgebiet?: string | null;
fachkollegium?: string | null;
wissenschaftsbereich?: string | null;
}
@@ -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.
*/
/**
* A lightweight reference to a sub-project of this project.
*/
export interface DfgProjectSubprojectSummary {
subproject_id?: number | null;
title_de?: string | null;
title_en?: string | null;
short_title?: string | null;
role_label_de?: string | null;
person_full_name?: string | null;
status_de?: string | null;
funding_start?: number | null;
funding_end?: number | null;
}
+45 -43
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -13,6 +13,7 @@ import { HEUOrganization } from './hEUOrganization';
import { HEUPublication } from './hEUPublication';
import { Fp7WebLink } from './fp7WebLink';
import { HEUWebLink } from './hEUWebLink';
import { AuthorPage } from './authorPage';
import { HEUDeliverable } from './hEUDeliverable';
import { Fp7ProjectIPR } from './fp7ProjectIPR';
import { HEUEurosciVoc } from './hEUEurosciVoc';
@@ -21,51 +22,52 @@ import { HEULegalBasis } from './hEULegalBasis';
import { HEUTopic } from './hEUTopic';
import { Fp7ReportSummary } from './fp7ReportSummary';
import { HEUReportSummary } from './hEUReportSummary';
import { Topic } from './topic';
import { HEUProjectDetails } from './hEUProjectDetails';
/**
* The project data
*/
export interface EuProjectData {
acronym?: string;
contentUpdateDate?: string;
ecMaxContribution?: number;
ecSignatureDate?: string;
endDate?: string;
frameworkProgramme?: string;
fundingScheme?: string;
grantDoi?: string;
humanValidated?: boolean;
id?: string;
keywords?: string;
legalBasis?: string;
masterCall?: string;
nature?: string;
objective?: string;
rcn?: string;
startDate?: string;
status?: string;
subCall?: string;
title?: string;
topics?: string;
totalCost?: number;
organizations?: Array<HEUOrganization>;
publications?: Array<HEUPublication>;
iprs?: Array<Fp7ProjectIPR>;
report_summaries?: Array<Fp7ReportSummary>;
topicsList?: Array<HEUTopic>;
web_links?: Array<Fp7WebLink>;
eurosciVoc?: Array<HEUEurosciVoc>;
legalBasisList?: Array<HEULegalBasis>;
organizationCount?: number;
publicationCount?: number;
iprCount?: number;
deliverables?: Array<HEUDeliverable>;
reportSummaries?: Array<HEUReportSummary>;
webLinks?: Array<HEUWebLink>;
ercPrincipalInvestigators?: Array<H2020ErcPI>;
deliverableCount?: number;
ercPiCount?: number;
export interface EuProjectData {
acronym?: string;
contentUpdateDate?: string;
ecMaxContribution?: number;
ecSignatureDate?: string;
endDate?: string;
frameworkProgramme?: string;
fundingScheme?: string;
grantDoi?: string;
humanValidated?: boolean;
id?: string;
keywords?: string;
legalBasis?: string;
masterCall?: string;
nature?: string;
objective?: string;
rcn?: string;
startDate?: string;
status?: string;
subCall?: string;
title?: string;
topics?: string;
totalCost?: number;
organizations?: Array<HEUOrganization>;
publications?: Array<HEUPublication>;
iprs?: Array<Fp7ProjectIPR>;
report_summaries?: Array<Fp7ReportSummary>;
topicsList?: Array<HEUTopic>;
web_links?: Array<Fp7WebLink>;
eurosciVoc?: Array<HEUEurosciVoc>;
legalBasisList?: Array<HEULegalBasis>;
organizationCount?: number;
publicationCount?: number;
iprCount?: number;
oaTopics?: Array<Topic>;
oaAuthors?: AuthorPage;
deliverables?: Array<HEUDeliverable>;
reportSummaries?: Array<HEUReportSummary>;
webLinks?: Array<HEUWebLink>;
ercPrincipalInvestigators?: Array<H2020ErcPI>;
deliverableCount?: number;
ercPiCount?: number;
}
+39 -37
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -12,47 +12,49 @@ import { Fp7WebLink } from './fp7WebLink';
import { Fp7Publication } from './fp7Publication';
import { Fp7ReportSummary } from './fp7ReportSummary';
import { Fp7Topic } from './fp7Topic';
import { AuthorPage } from './authorPage';
import { Fp7ProjectIPR } from './fp7ProjectIPR';
import { Topic } from './topic';
import { Fp7Organization } from './fp7Organization';
import { Fp7LegalBasis } from './fp7LegalBasis';
/**
* Comprehensive FP7 Project model combining all related entities. This model extends the base Fp7Project with all associated data.
*/
export interface Fp7ProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<Fp7Organization> | null;
publications?: Array<Fp7Publication> | null;
iprs?: Array<Fp7ProjectIPR> | null;
report_summaries?: Array<Fp7ReportSummary> | null;
topicsList?: Array<Fp7Topic> | null;
web_links?: Array<Fp7WebLink> | null;
eurosciVoc?: Array<Fp7EurosciVoc> | null;
legalBasisList?: Array<Fp7LegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
iprCount?: number | null;
export interface Fp7ProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<Fp7Organization> | null;
publications?: Array<Fp7Publication> | null;
iprs?: Array<Fp7ProjectIPR> | null;
report_summaries?: Array<Fp7ReportSummary> | null;
topicsList?: Array<Fp7Topic> | null;
web_links?: Array<Fp7WebLink> | null;
eurosciVoc?: Array<Fp7EurosciVoc> | null;
legalBasisList?: Array<Fp7LegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
iprCount?: number | null;
oaTopics?: Array<Topic> | null;
oaAuthors?: AuthorPage | null;
}
+41 -39
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -11,51 +11,53 @@ import { H2020LegalBasis } from './h2020LegalBasis';
import { H2020ErcPI } from './h2020ErcPI';
import { H2020Deliverable } from './h2020Deliverable';
import { H2020WebLink } from './h2020WebLink';
import { AuthorPage } from './authorPage';
import { H2020Publication } from './h2020Publication';
import { H2020ReportSummary } from './h2020ReportSummary';
import { H2020Topic } from './h2020Topic';
import { H2020EurosciVoc } from './h2020EurosciVoc';
import { Topic } from './topic';
import { H2020Organization } from './h2020Organization';
/**
* Comprehensive Horizon 2020 Project model combining all related entities. This model extends the base H2020Project with all associated data.
*/
export interface H2020ProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<H2020Organization> | null;
publications?: Array<H2020Publication> | null;
deliverables?: Array<H2020Deliverable> | null;
reportSummaries?: Array<H2020ReportSummary> | null;
topicsList?: Array<H2020Topic> | null;
webLinks?: Array<H2020WebLink> | null;
eurosciVoc?: Array<H2020EurosciVoc> | null;
legalBasisList?: Array<H2020LegalBasis> | null;
ercPrincipalInvestigators?: Array<H2020ErcPI> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
ercPiCount?: number | null;
export interface H2020ProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<H2020Organization> | null;
publications?: Array<H2020Publication> | null;
deliverables?: Array<H2020Deliverable> | null;
reportSummaries?: Array<H2020ReportSummary> | null;
topicsList?: Array<H2020Topic> | null;
webLinks?: Array<H2020WebLink> | null;
eurosciVoc?: Array<H2020EurosciVoc> | null;
legalBasisList?: Array<H2020LegalBasis> | null;
ercPrincipalInvestigators?: Array<H2020ErcPI> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
ercPiCount?: number | null;
oaTopics?: Array<Topic> | null;
oaAuthors?: AuthorPage | null;
}
+39 -37
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -12,47 +12,49 @@ import { HEUOrganization } from './hEUOrganization';
import { HEUTopic } from './hEUTopic';
import { HEUPublication } from './hEUPublication';
import { HEUWebLink } from './hEUWebLink';
import { AuthorPage } from './authorPage';
import { HEUReportSummary } from './hEUReportSummary';
import { HEUDeliverable } from './hEUDeliverable';
import { Topic } from './topic';
import { HEUEurosciVoc } from './hEUEurosciVoc';
/**
* Comprehensive Horizon Europe Project model combining all related entities. This model extends the base HEUProject with all associated data.
*/
export interface HEUProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<HEUOrganization> | null;
publications?: Array<HEUPublication> | null;
deliverables?: Array<HEUDeliverable> | null;
reportSummaries?: Array<HEUReportSummary> | null;
topicsList?: Array<HEUTopic> | null;
webLinks?: Array<HEUWebLink> | null;
eurosciVoc?: Array<HEUEurosciVoc> | null;
legalBasisList?: Array<HEULegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
export interface HEUProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<HEUOrganization> | null;
publications?: Array<HEUPublication> | null;
deliverables?: Array<HEUDeliverable> | null;
reportSummaries?: Array<HEUReportSummary> | null;
topicsList?: Array<HEUTopic> | null;
webLinks?: Array<HEUWebLink> | null;
eurosciVoc?: Array<HEUEurosciVoc> | null;
legalBasisList?: Array<HEULegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
oaTopics?: Array<Topic> | null;
oaAuthors?: AuthorPage | null;
}
+5
View File
@@ -62,7 +62,12 @@ export * from './dfgInstitutionSummaryPage';
export * from './dfgPersonSummary';
export * from './dfgPersonSummaryPage';
export * from './dfgProjectDetails';
export * from './dfgProjectInstitutionRole';
export * from './dfgProjectPage';
export * from './dfgProjectPersonRole';
export * from './dfgProjectPublicationSummary';
export * from './dfgProjectSubjectArea';
export * from './dfgProjectSubprojectSummary';
export * from './dfgProjectSummary';
export * from './dfgProjectTopic';
export * from './dfgProjectTopics';
@@ -112,6 +112,11 @@
<p class="description-text">{{ bundProject.description }}</p>
</mat-card>
}
<!-- OpenAlex Topics -->
@if (bundProject.oa_topics && bundProject.oa_topics.length > 0) {
<app-project-oa-topics
[topics]="bundProject.oa_topics"></app-project-oa-topics>
}
<!-- Beteiligte Personen -->
@if (getAssociatedPersons().length > 0) {
<mat-card appearance="outlined" class="card">
@@ -4,11 +4,16 @@ import { CommonModule } from '@angular/common';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { BundProjectDetails } from '../../../api/model/bundProjectDetails';
import { ProjectOaTopicsComponent } from '../../../shared/ui/project-oa-topics/project-oa-topics.component';
@Component({
selector: 'app-bund-details',
standalone: true,
imports: [CommonModule, MatCardModule, MatIconModule],
imports: [
CommonModule,
MatCardModule,
MatIconModule,
ProjectOaTopicsComponent,
],
templateUrl: './bund-details.component.html',
styleUrl: './bund-details.component.scss',
})
@@ -14,20 +14,28 @@
<span class="project-badge">DFG Projekt</span>
<span class="project-id">ID: {{ dfgProject.id }}</span>
</div>
<h1>{{ dfgProject.title }}</h1>
@if (dfgProject.project_identifier) {
<h1>{{ getTitle() }}</h1>
@if (getProjectIdentifier()) {
<p class="project-identifier">
<strong>{{ dfgProject.project_identifier.split('-')[0] }}</strong>
<strong>{{ getProjectIdentifier().split('-')[0] }}</strong>
</p>
}
@if (dfgProject.parent_project_id) {
<p class="project-identifier">
Teilprojekt von
<a (click)="goToParentProject()" class="external-link">{{
getParentTitle() || dfgProject.parent_project_id
}}</a>
</p>
}
<div class="hero-actions">
<div
class="status-badge"
[style.background-color]="
getStatusColor(getStatusDisplay(dfgProject.funding_end_date))
getStatusColor(getStatusDisplay(dfgProject.funding_end))
">
<mat-icon>circle</mat-icon>
<span>{{ getStatusDisplay(dfgProject.funding_end_date) }}</span>
<span>{{ getStatusDisplay(dfgProject.funding_end) }}</span>
</div>
@if (dfgProject.link) {
<a [href]="dfgProject.link" target="_blank" class="primary-action">
@@ -35,9 +43,9 @@
<span>Zum Projekt</span>
</a>
}
@if (dfgProject.website) {
@if (dfgProject.external_link) {
<a
[href]="dfgProject.website"
[href]="dfgProject.external_link"
target="_blank"
class="secondary-action">
<mat-icon>language</mat-icon>
@@ -51,33 +59,33 @@
<div class="metric-item">
<mat-icon>calendar_today</mat-icon>
<div class="metric-content">
<strong>{{ dfgProject.funding_start_date || 'N/A' }}</strong>
<strong>{{ dfgProject.funding_start || 'N/A' }}</strong>
<span>Förderbeginn</span>
</div>
</div>
<div class="metric-item">
<mat-icon>event_busy</mat-icon>
<div class="metric-content">
<strong>{{ getFundingStatus(dfgProject.funding_end_date) }}</strong>
<strong>{{ getFundingEndDisplay(dfgProject.funding_end) }}</strong>
<span>Förderende</span>
</div>
</div>
<div class="metric-item">
<mat-icon>access_time</mat-icon>
<div class="metric-content">
<strong>{{ getStatusDisplay(dfgProject.funding_end_date) }}</strong>
<strong>{{ getStatusDisplay(dfgProject.funding_end) }}</strong>
<span>Status</span>
</div>
</div>
<!-- @if (dfgProject.subject_area) {
@if (getSubjectArea()) {
<div class="metric-item">
<mat-icon>category</mat-icon>
<div class="metric-content">
<strong>{{ dfgProject.subject_area }}</strong>
<strong>{{ getSubjectArea() }}</strong>
<span>Fachliche Zuordnung</span>
</div>
</div>
} -->
}
@if (dfgProject.dfg_procedure) {
<div class="metric-item">
<mat-icon>gavel</mat-icon>
@@ -87,20 +95,20 @@
</div>
</div>
}
<!-- @if (dfgProject.funding_type) {
@if (getFundingType()) {
<div class="metric-item">
<mat-icon>paid</mat-icon>
<div class="metric-content">
<strong>{{ dfgProject.funding_type }}</strong>
<strong>{{ getFundingType() }}</strong>
<span>Förderung</span>
</div>
</div>
} -->
@if (dfgProject.international_reference) {
}
@if (getInternationalRelation()) {
<div class="metric-item">
<mat-icon>public</mat-icon>
<div class="metric-content">
<strong>{{ dfgProject.international_reference }}</strong>
<strong>{{ getInternationalRelation() }}</strong>
<span>Internationaler Bezug</span>
</div>
</div>
@@ -110,28 +118,56 @@
<div class="content-grid">
<main class="main-content">
@if (dfgProject.description) {
@if (getDescription()) {
<mat-card appearance="outlined" class="card">
<div class="section-header">
<mat-icon>description</mat-icon>
<h2>Beschreibung</h2>
</div>
<p class="description-text">{{ dfgProject.description }}</p>
<p class="description-text">{{ getDescription() }}</p>
</mat-card>
}
@if (getFinalReportAbstract()) {
<mat-card appearance="outlined" class="card">
<div class="section-header">
<mat-icon>fact_check</mat-icon>
<h2>Abschlussbericht</h2>
</div>
<p class="description-text">{{ getFinalReportAbstract() }}</p>
</mat-card>
}
<!-- Beteiligte Personen -->
<mat-card appearance="outlined" class="card">
<div class="section-header">
<mat-icon>people</mat-icon>
<h2>Beteiligte Personen</h2>
<span class="count-badge">{{ getAssociatedPersons().length }}</span>
<span class="count-badge">{{ getPersonCount() }}</span>
</div>
@if (getAssociatedPersons().length > 0) {
@if (getPersons().length > 0) {
<div class="person-grid">
@for (person of getAssociatedPersons(); track person) {
<div (click)="searchForPersonName(person)" class="person-item">
<div class="avatar">{{ getInitials(person) }}</div>
<div class="person-name">{{ person }}</div>
@for (
person of getPersons();
track person.person_id + (person.role_key || '')
) {
<div
(click)="searchForPersonName(person.full_name)"
class="person-item">
<div class="avatar">{{ getInitials(person.full_name) }}</div>
<div class="person-details">
<div class="person-name">{{ person.full_name }}</div>
@if (getPersonRoleLabel(person)) {
<div class="person-role">
{{ getPersonRoleLabel(person) }}
</div>
}
@if (getPersonAffiliation(person)) {
<div class="person-affiliation">
{{ getPersonAffiliation(person) }}
</div>
}
</div>
</div>
}
</div>
@@ -139,22 +175,42 @@
<div class="empty-state">Keine Personen gefunden.</div>
}
</mat-card>
<!-- OpenAlex Topics -->
@if (dfgProject.topics && dfgProject.topics.length > 0) {
<app-project-oa-topics
[topics]="dfgProject.topics"></app-project-oa-topics>
}
<!-- Beteiligte Institutionen -->
<mat-card appearance="outlined" class="card">
<div class="section-header">
<mat-icon>business</mat-icon>
<h2>Beteiligte Institutionen</h2>
<span class="count-badge">{{ getInstitutions().length }}</span>
<span class="count-badge">{{ getInstitutionCount() }}</span>
</div>
@if (getInstitutions().length > 0) {
@if (getInstitutionsList().length > 0) {
<div class="institution-grid">
@for (institution of getInstitutions(); track institution) {
@for (
institution of getInstitutionsList();
track institution.institute_id + (institution.role_key || '')
) {
<div
(click)="searchForInstitutionName(institution)"
(click)="
searchForInstitutionName(getInstitutionName(institution))
"
class="institution-item">
<mat-icon>apartment</mat-icon>
<span>{{ institution }}</span>
<div class="institution-details">
<span>{{ getInstitutionName(institution) }}</span>
@if (getInstitutionRoleLabel(institution)) {
<span class="institution-role">{{
getInstitutionRoleLabel(institution)
}}</span>
}
</div>
@if (institution.is_dissolved) {
<span class="dissolved-tag">aufgelöst</span>
}
</div>
}
</div>
@@ -162,21 +218,98 @@
<div class="empty-state">Keine Institutionen gefunden.</div>
}
</mat-card>
<!-- Teilprojekt -->
<!-- @if (dfgProject.subproject_of) {
<!-- Teilprojekte -->
@if (getSubprojects().length > 0) {
<mat-card appearance="outlined" class="card">
<div class="section-header">
<mat-icon>account_tree</mat-icon>
<h2>Teilprojekt</h2>
<h2>Teilprojekte</h2>
<span class="count-badge">{{ getSubprojects().length }}</span>
</div>
<div class="subproject-list">
@for (
subproject of getSubprojects();
track subproject.subproject_id
) {
<div
(click)="goToSubproject(subproject.subproject_id)"
class="subproject-item">
<div class="subproject-main">
<span class="subproject-title">{{
subproject.title_de ||
subproject.title_en ||
subproject.short_title
}}</span>
@if (subproject.status_de) {
<span class="subproject-status">{{
subproject.status_de
}}</span>
}
</div>
@if (
subproject.person_full_name || subproject.role_label_de
) {
<div class="subproject-lead">
{{ subproject.person_full_name }}
@if (subproject.role_label_de) {
<span>· {{ subproject.role_label_de }}</span>
}
</div>
}
</div>
}
</div>
<dl class="details-list">
<div class="detail-row">
<dt>Teilprojekt zu</dt>
<dd>{{ dfgProject.subproject_of }}</dd>
</div>
</dl>
</mat-card>
} -->
}
<!-- Publikationen -->
@if (getPublications().length > 0) {
<mat-card appearance="outlined" class="card">
<div class="section-header">
<mat-icon>menu_book</mat-icon>
<h2>Publikationen</h2>
<span class="count-badge">{{ getPublications().length }}</span>
</div>
<div class="publication-list">
@for (
publication of getPublications();
track publication.publication_id
) {
<div class="publication-item">
<div class="publication-title">{{ publication.title }}</div>
<div class="publication-meta">
@if (publication.authors_editors) {
<span>{{ publication.authors_editors }}</span>
}
@if (publication.publication_year) {
<span>{{ publication.publication_year }}</span>
}
@if (publication.doi) {
<a
[href]="'https://doi.org/' + publication.doi"
target="_blank"
class="external-link"
>DOI: {{ publication.doi }}</a
>
}
</div>
</div>
}
</div>
</mat-card>
}
<!-- Projekt-Webseite (DFG-gehostete HTML-Inhalte) -->
@if (getWebsiteHtml()) {
<mat-card appearance="outlined" class="card">
<div class="section-header">
<mat-icon>language</mat-icon>
<h2>Projektwebseite</h2>
</div>
<div class="website-html" [innerHTML]="getWebsiteHtml()"></div>
</mat-card>
}
</main>
<aside class="sidebar">
@@ -193,49 +326,78 @@
</div>
<div class="detail-row">
<dt>Titel</dt>
<dd>{{ dfgProject.title || 'N/A' }}</dd>
<dd>{{ getTitle() }}</dd>
</div>
<div class="detail-row">
<dt>Projektkennung</dt>
<dd>{{ dfgProject.project_identifier || 'N/A' }}</dd>
<dd>{{ getProjectIdentifier() || 'N/A' }}</dd>
</div>
<div class="detail-row">
<dt>Fachliche Zuordnung</dt>
<dd>{{ dfgProject.subject_area || 'N/A' }}</dd>
<dd>{{ getSubjectArea() || 'N/A' }}</dd>
</div>
@if (getSubjectClassifications().length > 0) {
<div class="detail-row">
<dt>Fachsystematik</dt>
<dd>
@for (entry of getSubjectClassifications(); track $index) {
<div class="classification-path">
{{ formatSubjectClassification(entry) }}
</div>
}
</dd>
</div>
}
<div class="detail-row">
<dt>DFG-Verfahren</dt>
<dd>{{ dfgProject.dfg_procedure || 'N/A' }}</dd>
</div>
<!-- <div class="detail-row">
<dt>Förderung</dt>
<dd>{{ dfgProject.funding_type || 'N/A' }}</dd>
</div> -->
@if (getFundingType()) {
<div class="detail-row">
<dt>Förderung</dt>
<dd>{{ getFundingType() }}</dd>
</div>
}
<div class="detail-row">
<dt>Laufzeit</dt>
<dd>{{ getDuration() }}</dd>
<dd>{{ getFundingPeriod() || getDuration() }}</dd>
</div>
@if (dfgProject.subproject_of) {
@if (hasEquipmentInfo()) {
<div class="detail-row">
<dt>Großgerät</dt>
<dd>
{{ dfgProject.equipment_name }}
@if (dfgProject.equipment_group) {
<span>({{ dfgProject.equipment_group }})</span>
}
</dd>
</div>
}
@if (dfgProject.parent_project_id) {
<div class="detail-row">
<dt>Teilprojekt von</dt>
<dd>{{ dfgProject.subproject_of }}</dd>
<dd>
<a (click)="goToParentProject()" class="external-link">{{
getParentTitle() || dfgProject.parent_project_id
}}</a>
</dd>
</div>
}
@if (dfgProject.international_reference) {
@if (getInternationalRelation()) {
<div class="detail-row">
<dt>Internationaler Bezug</dt>
<dd>{{ dfgProject.international_reference }}</dd>
<dd>{{ getInternationalRelation() }}</dd>
</div>
}
@if (dfgProject.website) {
@if (dfgProject.external_link) {
<div class="detail-row">
<dt>Webseite</dt>
<dd>
<a
[href]="dfgProject.website"
[href]="dfgProject.external_link"
target="_blank"
class="external-link"
>{{ dfgProject.website }}</a
>{{ dfgProject.external_link }}</a
>
</dd>
</div>
@@ -11,7 +11,6 @@
gap: 18px;
margin-bottom: 24px;
}
.back-link {
display: inline-flex;
align-items: center;
@@ -323,6 +322,12 @@ h1 {
flex-shrink: 0;
}
.person-details {
display: flex;
flex-direction: column;
min-width: 0;
}
.person-name {
cursor: pointer;
font-size: 13px;
@@ -330,6 +335,20 @@ h1 {
color: var(--sg-text);
}
.person-role {
font-size: 11px;
color: var(--sg-primary, #0066cc);
font-weight: 500;
}
.person-affiliation {
font-size: 11px;
color: var(--sg-text-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.institution-grid {
cursor: pointer;
display: grid;
@@ -358,6 +377,120 @@ h1 {
flex-shrink: 0;
}
.institution-details {
display: flex;
flex-direction: column;
min-width: 0;
flex: 1;
}
.institution-role {
font-size: 11px;
color: var(--sg-text-muted);
}
.dissolved-tag {
flex-shrink: 0;
padding: 2px 8px;
border-radius: 10px;
background: #fbeaea;
color: #c0392b;
font-size: 11px;
font-weight: 500;
}
.subproject-list,
.publication-list {
display: flex;
flex-direction: column;
gap: 10px;
padding: 16px 20px 20px;
}
.subproject-item {
padding: 10px 14px;
border: 1px solid #d9e2f0;
border-radius: var(--sg-radius-sm);
background: #fff;
cursor: pointer;
transition: all 0.2s;
}
.subproject-item:hover {
background: #f8fafc;
border-color: #b8c5d6;
}
.subproject-main {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.subproject-title {
font-size: 13px;
font-weight: 500;
color: var(--sg-text);
}
.subproject-status {
flex-shrink: 0;
padding: 2px 8px;
border-radius: 10px;
background: #e8edf5;
color: var(--sg-text-muted);
font-size: 11px;
font-weight: 500;
}
.subproject-lead {
margin-top: 4px;
font-size: 12px;
color: var(--sg-text-muted);
}
.publication-item {
padding: 10px 14px;
border: 1px solid #d9e2f0;
border-radius: var(--sg-radius-sm);
background: #fff;
}
.publication-title {
font-size: 13px;
font-weight: 500;
color: var(--sg-text);
margin-bottom: 4px;
}
.publication-meta {
display: flex;
flex-wrap: wrap;
gap: 10px;
font-size: 12px;
color: var(--sg-text-muted);
}
.classification-path {
font-size: 13px;
color: var(--sg-text);
line-height: 1.5;
}
.website-html {
padding: 16px 20px 20px;
font-size: 14px;
line-height: 1.6;
color: var(--sg-text);
overflow-wrap: break-word;
}
.website-html img {
max-width: 100%;
height: auto;
}
.details-list {
margin: 0;
padding: 16px 20px 20px;
@@ -1,14 +1,29 @@
import { Component, OnInit, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ActivatedRoute, Router } 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';
import { DfgProjectPublicationSummary } from '../../../api/model/dfgProjectPublicationSummary';
import { DfgProjectSubprojectSummary } from '../../../api/model/dfgProjectSubprojectSummary';
import { DfgProjectInstitutionRole } from '../../../api/model/dfgProjectInstitutionRole';
import { DfgProjectPersonRole } from '../../../api/model/dfgProjectPersonRole';
import { DfgProjectSubjectArea } from '../../../api/model/dfgProjectSubjectArea';
import { ProjectOaTopicsComponent } from '../../../shared/ui/project-oa-topics/project-oa-topics.component';
import { Topic } from '../../../api';
import {
topicHierarchyColor,
TopicHierarchyColorInput,
} from '../../../resolvers/utils/topic-colors';
@Component({
selector: 'app-dfg-details',
standalone: true,
imports: [CommonModule, MatCardModule, MatIconModule],
imports: [
CommonModule,
MatCardModule,
MatIconModule,
ProjectOaTopicsComponent,
],
templateUrl: './dfg-details.component.html',
styleUrl: './dfg-details.component.scss',
})
@@ -25,30 +40,174 @@ export class DfgDetailsComponent implements OnInit {
});
}
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();
private pick(de?: string | null, en?: string | null): string {
return de || en || '';
}
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}`
: `${fundingEndDate}`;
getTitle(): string {
return (
this.pick(this.dfgProject?.title_de, this.dfgProject?.title_en) || 'N/A'
);
}
getStatusDisplay(fundingEndDate: string | null | undefined): string {
if (!fundingEndDate) return 'N/A';
if (fundingEndDate === '2999') return 'Laufend';
const year = parseInt(fundingEndDate, 10);
return year >= new Date().getFullYear() ? `Laufend` : `Abgeschlossen`;
getDescription(): string {
return this.pick(
this.dfgProject?.description_de,
this.dfgProject?.description_en,
);
}
getFinalReportAbstract(): string {
return this.pick(
this.dfgProject?.final_report_abstract_de,
this.dfgProject?.final_report_abstract_en,
);
}
getProjectIdentifier(): string {
return this.pick(
this.dfgProject?.project_identifier_de,
this.dfgProject?.project_identifier_en,
);
}
getSubjectArea(): string {
return this.pick(
this.dfgProject?.subject_area_de,
this.dfgProject?.subject_area_en,
);
}
getFundingType(): string {
return this.pick(
this.dfgProject?.funding_type_de,
this.dfgProject?.funding_type_en,
);
}
getFundingPeriod(): string {
return this.pick(
this.dfgProject?.funding_period_de,
this.dfgProject?.funding_period_en,
);
}
getInternationalRelation(): string {
return this.pick(
this.dfgProject?.international_relation_de,
this.dfgProject?.international_relation_en,
);
}
getParentTitle(): string {
return this.pick(
this.dfgProject?.parent_title_de,
this.dfgProject?.parent_title_en,
);
}
getWebsiteHtml(): string {
return this.pick(
this.dfgProject?.website_html_de,
this.dfgProject?.website_html_en,
);
}
hasEquipmentInfo(): boolean {
return !!(
this.dfgProject?.equipment_group || this.dfgProject?.equipment_name
);
}
// --- Persons & institutions (now role-aware, not just names) ---
getPersons(): DfgProjectPersonRole[] {
return this.dfgProject?.persons ?? [];
}
getPersonRoleLabel(person: DfgProjectPersonRole): string {
return this.pick(person.role_label_de, person.role_label_en);
}
getPersonAffiliation(person: DfgProjectPersonRole): string {
return this.pick(person.affiliation_de, person.affiliation_en);
}
/** Unique person count for the section badge (persons[] may list one person more than once if they hold multiple roles). */
getPersonCount(): number {
return (
this.dfgProject?.associated_persons?.length ?? this.getPersons().length
);
}
getInstitutionsList(): DfgProjectInstitutionRole[] {
return this.dfgProject?.institutions ?? [];
}
getInstitutionName(institution: DfgProjectInstitutionRole): string {
return this.pick(institution.name_de, institution.name_en);
}
getInstitutionRoleLabel(institution: DfgProjectInstitutionRole): string {
return this.pick(institution.role_label_de, institution.role_label_en);
}
getInstitutionCount(): number {
return (
this.dfgProject?.associated_institutions?.length ??
this.getInstitutionsList().length
);
}
// --- Subject classification (DFG Fachsystematik) ---
getSubjectClassifications(): DfgProjectSubjectArea[] {
return this.dfgProject?.subject_classifications ?? [];
}
/** Renders one classification entry as a breadcrumb-like path. */
formatSubjectClassification(entry: DfgProjectSubjectArea): string {
return [
entry.wissenschaftsbereich,
entry.fachkollegium,
entry.fachgebiet,
entry.fach,
]
.filter((part) => !!part)
.join(' › ');
}
// --- Subprojects & publications ---
getSubprojects(): DfgProjectSubprojectSummary[] {
return this.dfgProject?.subprojects ?? [];
}
getPublications(): DfgProjectPublicationSummary[] {
return this.dfgProject?.publications ?? [];
}
goToSubproject(subprojectId: number | null | undefined): void {
if (!subprojectId) return;
// Adjust this route to match your app's actual DFG project detail route.
this.router.navigate(['/dfg-projects', subprojectId]);
}
goToParentProject(): void {
if (!this.dfgProject?.parent_project_id) return;
this.router.navigate(['/dfg-projects', this.dfgProject.parent_project_id]);
}
// --- Funding status / duration (funding_start/funding_end are now year numbers, not date strings) ---
getStatusDisplay(fundingEnd: number | null | undefined): string {
if (fundingEnd == null || fundingEnd >= 2999) return 'Laufend';
return fundingEnd >= new Date().getFullYear() ? 'Laufend' : 'Abgeschlossen';
}
getFundingEndDisplay(fundingEnd: number | null | undefined): string {
if (fundingEnd == null || fundingEnd >= 2999) return 'Laufend';
return `${fundingEnd}`;
}
getStatusColor(status: string | null | undefined): string {
@@ -63,44 +222,39 @@ export class DfgDetailsComponent implements OnInit {
}
}
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 || [];
}
getDuration(): string {
const start = this.dfgProject?.funding_start_date;
const end =
this.dfgProject?.funding_end_date === '2999'
? 'Heute'
: this.dfgProject?.funding_end_date;
if (!start || !end) return '';
return `von ${start} bis ${end}`;
const start = this.dfgProject?.funding_start;
const end = this.dfgProject?.funding_end;
if (start == null) return '';
const endLabel = end == null || end >= 2999 ? 'Heute' : `${end}`;
return `von ${start} bis ${endLabel}`;
}
// --- Navigation helpers ---
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();
}
searchForPersonName(personName: string | null | undefined): void {
if (!personName) return;
this.router.navigate(['/persons'], {
queryParams: { query: personName },
});
}
searchForInstitutionName(institutionName: string | null | undefined): void {
if (!institutionName) return;
this.router.navigate(['/institutions'], {
queryParams: { search: institutionName },
});
}
goBack(): void {
window.history.back();
}
@@ -224,6 +224,11 @@
</div>
</mat-card>
}
<!-- OpenAlex Topics -->
@if (euProject.oaTopics && euProject.oaTopics.length > 0) {
<app-project-oa-topics
[topics]="euProject.oaTopics"></app-project-oa-topics>
}
@if (getKeywordChips().length > 0) {
<mat-card appearance="outlined" class="card">
@@ -10,12 +10,13 @@ import { MatDividerModule } from '@angular/material/divider';
import { MatTooltipModule } from '@angular/material/tooltip';
import { Subscription } from 'rxjs';
import { EuProjectData } from '../../../api/model/euProjectData';
import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component';
import { OrganizationsTableComponent } from './organizations-table/organizations-table.component';
import { PublicationsTableComponent } from './publications-table/publications-table.component';
import { PatentsCardsComponent } from './patents-cards/patents-cards.component';
import { DeliverablesCardsComponent } from './deliverables-cards/deliverables-cards.component';
import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component';
import { ProjectOaTopicsComponent } from '../../../shared/ui/project-oa-topics/project-oa-topics.component';
export type TabType =
| 'overview'
| 'organizations'
@@ -35,6 +36,7 @@ export type TabType =
MatDividerModule,
MatTooltipModule,
TopicChipComponent,
ProjectOaTopicsComponent,
OrganizationsTableComponent,
PublicationsTableComponent,
PatentsCardsComponent,
@@ -468,6 +470,5 @@ export class EuDetailsComponent implements OnInit, OnDestroy {
);
return Array.from(countries);
}
// ============= SEARCH / NAVIGATION METHODS =============
}
@@ -0,0 +1,20 @@
<mat-card appearance="outlined" class="card">
<div class="section-header">
<mat-icon>label</mat-icon>
<h2>OpenAlex Themen</h2>
<span class="count-badge">{{ getUniqueOATopics().length }}</span>
</div>
<div class="keyword-stack">
@for (topic of getUniqueOATopics(); track $index) {
<app-topic-chip
[label]="topic.display_name || ''"
[subfieldName]="topic.subfield?.display_name || ''"
[fieldName]="topic.field?.display_name || ''"
[domainName]="topic.domain?.display_name || ''"
[color]="getTopicColor(topic)"
[active]="true"
countIcon="article"
descriptionTooltipTarget="button" />
}
</div>
</mat-card>
@@ -0,0 +1,48 @@
.keyword-stack {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.6rem;
padding: 16px 20px 20px;
::ng-deep app-topic-chip .topic-chip__count {
display: none;
}
}
.card {
margin-bottom: 24px;
border-color: #d9e2f0 !important;
border-radius: var(--sg-radius-md) !important;
}
.section-header {
display: flex;
align-items: center;
gap: 12px;
padding: 16px 20px;
border-bottom: 1px solid #e6e9ed;
}
.section-header mat-icon {
color: var(--sg-text-muted);
width: 22px;
height: 22px;
font-size: 22px;
}
.section-header h2 {
margin: 0;
font-size: 18px;
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;
}
@@ -0,0 +1,44 @@
import { Component, Input } from '@angular/core';
import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component';
import { Topic } from '../../../api';
import {
topicHierarchyColor,
TopicHierarchyColorInput,
} from '../../../resolvers/utils/topic-colors';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';
@Component({
selector: 'app-project-oa-topics',
imports: [TopicChipComponent, MatCardModule, MatIconModule, MatChipsModule],
templateUrl: './project-oa-topics.component.html',
styleUrl: './project-oa-topics.component.scss',
})
export class ProjectOaTopicsComponent {
@Input() topics: Topic[] | undefined;
//Topics
getUniqueOATopics(): Topic[] {
if (!this.topics) return [];
const uniqueTopicsMap = new Map<string, Topic>();
this.topics.forEach((topic) => {
if (topic.id && !uniqueTopicsMap.has(topic.id)) {
uniqueTopicsMap.set(topic.id, topic);
}
});
return Array.from(uniqueTopicsMap.values());
}
getTopicColor(topic: Topic | undefined | null): string {
const topicInput: TopicHierarchyColorInput = {
id: topic?.id ?? null,
name: topic?.display_name ?? null,
field_id: topic?.field?.id ?? null,
field_name: topic?.field?.display_name ?? null,
domain_id: topic?.domain?.id ?? null,
domain_name: topic?.domain?.display_name ?? null,
};
return topicHierarchyColor(topicInput);
}
}