Compare commits

..
Author SHA1 Message Date
farajollahi 6e4742206f Merge branch 'dev' into dfg-status-dashboard
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 10:45:41 +02:00
farajollahi a28ecc9d02 implement keyword select and dfg status diagramm
LocationBasedServices/smartguide/pipeline/head Build started...
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-28 10:43:42 +02:00
genja 53397f844e Merge pull request 'feature/keywords-analysis' (#249) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #249
2026-07-28 10:09:56 +02:00
genja 818398ccda Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 10:08:48 +02:00
spsaefan a6c7068ca6 Merge branch 'global-time-filter' into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
# Please enter a commit message to explain why this merge is necessary,
:wq
2026-07-28 09:31:03 +02:00
genja 4785bb4d40 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 09:19:31 +02:00
genja 1a9f9496fd date formatting for BUND details page fixed 2026-07-28 09:18:56 +02:00
genja 78f35daa58 fixed pagination options for project tables 2026-07-28 09:17:51 +02:00
Kazgatari b2e70c2bb3 fix: institution visisbility button & refactor ID type (full OpenAlex link vs ID) into parent component
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 09:11:40 +02:00
genja 3d8ceeb5b6 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 00:40:19 +02:00
genja 0b8540d70b regenerated services and models 2026-07-28 00:35:34 +02:00
genja e9ccfe6796 added BUND institutions resolver, BUND projects desolver adjusted for the new logic 2026-07-28 00:35:20 +02:00
genja e20f2732b3 minor UI fixes 2026-07-28 00:34:35 +02:00
genja 4da4ea1bff moved BUND projects out from person component to keywords search 2026-07-28 00:32:21 +02:00
genja 93ba39f9b0 fixed filters for BUND projects 2026-07-28 00:31:51 +02:00
genja 0642a3704d added new func for retrievingbund project by topic_ids 2026-07-28 00:31:30 +02:00
genja 57e1bafa8b added BUND institutions endpoint with autocomplete 2026-07-28 00:30:20 +02:00
genja 3d5eb524aa added Institutions filter and funding-type filter for BUND 2026-07-28 00:24:52 +02:00
genja c15afed0aa added funding type selector for BUND projects 2026-07-28 00:18:24 +02:00
genja b133ce80c9 added BUND institutions selector 2026-07-28 00:17:36 +02:00
Roman ae8332dc3d (dashboard) fix pytest
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-27 23:10:01 +02:00
Roman 026a35dd90 (work-classifications): show orientation scores for limited publication samples
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-27 21:58:55 +02:00
Roman 5fdc1cdce3 refactor(dashboard): use shared active institution membership query for person count
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-27 21:40:35 +02:00
Roman 02bb8b8fb8 (work-classifications): add research profiles to author comparison (ranking) 2026-07-27 21:23:53 +02:00
Kazgatari 4fe78c2b88 made pie chart bigger and seperated header to properly resize
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-27 09:22:16 +02:00
genja 2e8dd00aa6 Merge pull request 'feature/keywords-analysis' (#247) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #247
2026-07-26 22:49:24 +02:00
genja 127eed5c49 regenerated services
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-07-26 22:41:38 +02:00
genja 7a84fc2b12 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis 2026-07-26 22:39:48 +02:00
genja 96e0925054 dfg tests adjusted 2026-07-26 22:36:36 +02:00
genja 730ee7f89a applied the new OpenAlex topics component for EU detail page 2026-07-26 21:55:48 +02:00
genja e62d1ca458 new ui component for displaying OpenAlex topics on project pages 2026-07-26 21:55:02 +02:00
genja 6bca5643ee added openalex topics and authors to EU details project page 2026-07-26 21:54:25 +02:00
genja db20b23ff3 reworked the dfg detail page for the new DFG data 2026-07-26 21:53:21 +02:00
genja 66f34668a9 added openalex topics to dfg detail page 2026-07-26 21:52:53 +02:00
genja ceadc26741 added openalex topics to bund detail page 2026-07-26 21:51:23 +02:00
genja 3a74dc9b7b created new DfgProjectsDetails model from the new DFG data models 2026-07-26 18:38:32 +02:00
genja 4a47d752cb removed unused components from uni-trend-parent component 2026-07-26 18:31:43 +02:00
genja 46aee46ea3 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-26 10:59:40 +02:00
genja 3a78519655 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-24 16:36:54 +02:00
genja c6de85d4a0 cache time increased up to 10 minutes 2026-07-24 16:35:26 +02:00
109 changed files with 5751 additions and 1677 deletions
+8
View File
@@ -34,6 +34,14 @@ class BmbfProjectStatusStatistics(BaseModel):
completed: int
class DfgProjectStatusStatistics(BaseModel):
institution_id: str
organization_name: str
ongoing: int
upcoming: int
completed: int
class DfgProjectTopic(BaseModel):
id: str
name: str
+22
View File
@@ -12,6 +12,7 @@ from .model import (
BmbfProjectStatusStatistics,
DashboardStatisticValue,
DashboardStatistics,
DfgProjectStatusStatistics,
DfgProjectTopics,
EuProjectStatusStatistics,
TopAuthorStatistics,
@@ -22,6 +23,7 @@ from .service import (
get_dashboard_bmbf_project_statuses,
get_dashboard_bmbf_projects,
get_dashboard_dfg_projects,
get_dashboard_dfg_project_statuses,
get_dashboard_dfg_topics,
get_dashboard_eu_projects,
get_dashboard_eu_project_statuses,
@@ -210,6 +212,26 @@ async def dashboard_dfg_projects(
)
@router.get(
"/projects/dfg/status",
operation_id="getDashboardDfgProjectStatuses",
response_model=DfgProjectStatusStatistics,
)
async def dashboard_dfg_project_statuses(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DfgProjectStatusStatistics:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_dfg_project_statuses(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@router.get(
"/projects/dfg/topics",
operation_id="getDashboardDfgProjectTopics",
+107 -66
View File
@@ -9,6 +9,9 @@ from sqlmodel import Session
from inse import config
from inse.auth.model import AccessToken, Organization
from inse.authors.institution_membership_query import (
build_active_institution_membership_query,
)
from inse.integrations import elasticsearch
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.model import ESCluster, ESIndex
@@ -22,6 +25,7 @@ from .model import (
DashboardStatisticValue,
DashboardStatistics,
DfgProjectTopic,
DfgProjectStatusStatistics,
DfgProjectTopics,
EuProjectStatusStatistics,
TopAuthor,
@@ -221,74 +225,9 @@ async def get_dashboard_persons(
organization_name: str,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
target_year = datetime.now().year - 1
recent_affiliation_query = {
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{
"match_phrase": {
"affiliations.institution.id": normalized_id
}
},
{"range": {"affiliations.years": {"gte": target_year}}},
]
}
},
}
}
matching_last_known_institution_query = {
"nested": {
"path": "last_known_institutions",
"query": {
"match_phrase": {
"last_known_institutions.id": normalized_id
}
},
}
}
missing_last_known_institutions_query = {
"bool": {
"must_not": [
{
"nested": {
"path": "last_known_institutions",
"query": {"exists": {"field": "last_known_institutions.id"}},
}
}
]
}
}
search_query = {
"bool": {
"should": [
{
"bool": {
"filter": [
matching_last_known_institution_query,
recent_affiliation_query,
]
}
},
{
"bool": {
"filter": [
missing_last_known_institutions_query,
recent_affiliation_query,
]
}
},
],
"minimum_should_match": 1,
}
}
response = await elasticsearch.search(
index=ESIndex.OPENALEX_AUTHORS,
query=search_query,
query=build_active_institution_membership_query(normalized_id),
size=0,
track_total_hits=True,
cluster=ESCluster.NES,
@@ -557,6 +496,108 @@ async def get_dashboard_dfg_projects(
)
async def get_dashboard_dfg_project_statuses(
institution_id: str,
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DfgProjectStatusStatistics:
normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
project_ids = await _get_dfg_project_ids_for_institution(
normalized_id,
)
if not project_ids:
return DfgProjectStatusStatistics(
institution_id=normalized_id,
organization_name=organization_name,
ongoing=0,
upcoming=0,
completed=0,
)
selected_project_filters: list[dict[str, Any]] = [
{
"terms": {
"projects.project_id": [
int(project_id) for project_id in project_ids
]
}
}
]
if period_filter := _project_overlap_filter(
"projects.funding_start",
"projects.funding_end",
period,
missing_end_is_ongoing=True,
):
selected_project_filters.append(period_filter)
response = await elasticsearch.search(
index=ESIndex.DFG_INSTITUTES_V2,
body={
"size": 0,
"aggs": {
"projects_nested": {
"nested": {"path": "projects"},
"aggs": {
"selected_projects": {
"filter": (
selected_project_filters[0]
if len(selected_project_filters) == 1
else {"bool": {"filter": selected_project_filters}}
),
"aggs": {
"ongoing": {
"filter": {
"match_phrase": {
"projects.status_de": "laufend"
}
},
"aggs": {
"projects": {
"cardinality": {
"field": "projects.project_id"
}
}
},
},
"completed": {
"filter": {
"match_phrase": {
"projects.status_de": "abgeschlossen"
}
},
"aggs": {
"projects": {
"cardinality": {
"field": "projects.project_id"
}
}
},
},
},
}
},
}
},
},
cluster=ESCluster.INSE,
)
aggregations = (
response.get("aggregations", {})
.get("projects_nested", {})
.get("selected_projects", {})
)
return DfgProjectStatusStatistics(
institution_id=normalized_id,
organization_name=organization_name,
ongoing=_project_status_count(aggregations, "ongoing"),
upcoming=0,
completed=_project_status_count(aggregations, "completed"),
)
async def get_dashboard_dfg_topics(
institution_id: str,
organization_name: str,
+103 -5
View File
@@ -8,9 +8,13 @@ from sqlmodel import Session, SQLModel, create_engine
from inse import config
from inse.auth.model import AccessToken, Organization, UserRole
from inse.authors.institution_membership_query import (
build_active_institution_membership_query,
)
from inse.dashboard.service import (
get_dashboard_bmbf_project_statuses,
get_dashboard_organization,
get_dashboard_dfg_project_statuses,
get_dashboard_dfg_topics,
get_dashboard_eu_project_statuses,
get_dashboard_patents,
@@ -224,6 +228,102 @@ async def test_dashboard_bmbf_project_statuses_uses_funding_dates():
}
@pytest.mark.anyio
async def test_dashboard_dfg_project_statuses_uses_nested_status_de():
with patch(
"inse.dashboard.service._get_dfg_project_ids_for_institution",
new=AsyncMock(return_value=["123", "456"]),
) as project_ids, patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(
return_value={
"aggregations": {
"projects_nested": {
"selected_projects": {
"ongoing": {"projects": {"value": 1}},
"completed": {"projects": {"value": 1}},
}
}
}
}
),
) as search:
result = await get_dashboard_dfg_project_statuses(
ORG_INSTITUTION_ID,
"Example Org",
from_year=2020,
to_year=2024,
)
project_ids.assert_awaited_once_with(
ORG_INSTITUTION_ID,
)
assert result.model_dump() == {
"institution_id": ORG_INSTITUTION_ID,
"organization_name": "Example Org",
"ongoing": 1,
"upcoming": 0,
"completed": 1,
}
call = search.await_args
assert call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2
selected = call.kwargs["body"]["aggs"]["projects_nested"]["aggs"][
"selected_projects"
]
assert selected["filter"] == {
"bool": {
"filter": [
{"terms": {"projects.project_id": [123, 456]}},
{
"bool": {
"filter": [
{
"range": {
"projects.funding_start": {"lte": 2024}
}
},
{
"bool": {
"should": [
{
"range": {
"projects.funding_end": {
"gte": 2020
}
}
},
{
"bool": {
"must_not": {
"exists": {
"field": "projects.funding_end"
}
}
}
},
],
"minimum_should_match": 1,
}
},
]
}
},
]
}
}
assert selected["aggs"]["ongoing"]["filter"] == {
"match_phrase": {"projects.status_de": "laufend"}
}
assert selected["aggs"]["completed"]["filter"] == {
"match_phrase": {"projects.status_de": "abgeschlossen"}
}
assert all(
selected["aggs"][status]["aggs"]["projects"]["cardinality"]["field"]
== "projects.project_id"
for status in ("ongoing", "completed")
)
@pytest.mark.anyio
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
async def search(**kwargs):
@@ -307,11 +407,9 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
assert works_call.kwargs["query"]["nested"]["query"]["term"] == {
"authorships.institutions.id": ORG_INSTITUTION_ID
}
assert authors_call.kwargs["query"]["bool"]["should"][0]["bool"]["filter"][
0
]["nested"]["query"]["match_phrase"] == {
"last_known_institutions.id": ORG_INSTITUTION_ID
}
assert authors_call.kwargs["query"] == build_active_institution_membership_query(
ORG_INSTITUTION_ID
)
assert all(
call.kwargs["cluster"] == ESCluster.INSE
for call in [eu_call, bmbf_call, *dfg_calls]
+3 -1
View File
@@ -52,6 +52,7 @@ from inse.patents.service import (
)
from inse.persons.service import router as persons_service_router
from inse.projects.dfg_institutions.router import router as dfg_institutions_router
from inse.projects.bund_institutions.router import router as bund_institutions_router
from inse.projects.dfg_persons.router import router as dfg_persons_router
from inse.projects.eu_organizations.router import router as eu_organizations_router
from inse.projects.router import router as projects_router
@@ -103,6 +104,7 @@ app = FastAPI(
app.include_router(institution_patents_router)
app.include_router(org_patents_router)
app.include_router(institutions_router)
app.include_router(bund_institutions_router)
app.include_router(topics_service_router)
app.include_router(works_service_router)
app.include_router(persons_service_router)
@@ -137,7 +139,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,
@@ -16,10 +16,11 @@ NO_STORE_PATH_PREFIXES = (
"/api/background-jobs",
"/api/bookmarks",
"/api/organizations",
"/api/dashboard",
"/api/rank/rank-author",
"/api/works/v2/classification/",
)
"/api/dashboard",
"/api/rank/rank-author",
"/api/rank/orientation-profiles",
"/api/works/v2/classification/",
)
NO_STORE_PATH_FRAGMENTS = (
"/company-connections",
@@ -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 [],
)
@@ -0,0 +1,42 @@
from typing import Optional
from inse.model import Page
from pydantic import BaseModel
class BundInstitutionSummary(BaseModel):
"""A single institution entry derived from a BUND project record.
Note: this index has no dedicated institution entity — each entry is
reconstructed from the agency/recipient fields on a single project hit,
so the same institution may appear multiple times (once per project).
"""
department: Optional[str] = None
department_fullname: Optional[str] = None
name: Optional[str] = None
recepient: Optional[str] = None
municipality: Optional[str] = None
place: Optional[str] = None
state: Optional[str] = None
country: Optional[str] = None
@classmethod
def from_source(cls, source: dict) -> "BundInstitutionSummary":
"""Build a BundInstitutionSummary from a raw Elasticsearch _source dict."""
return cls(
department=source.get("Ressort"),
department_fullname=source.get("Ressort_fullname"),
name=source.get("Ausführende Stelle"),
recepient=source.get("Zuwendungsempfänger"),
municipality=source.get("Stadt/Gemeinde"),
place=source.get("Ort"),
state=source.get("Bundesland"),
country=source.get("Staat"),
)
class BundInstitutionSummaryPage(Page[BundInstitutionSummary]):
"""A paginated response containing a list of institutions."""
pass
@@ -0,0 +1,47 @@
import logging
from typing import Annotated
from fastapi import APIRouter, Query
from inse.projects.bund_institutions.model import BundInstitutionSummaryPage
from inse.tags import Tags
from inse.projects.bund_institutions.service import autocomplete_institutions_for_selector, get_institutions_by_names
logger = logging.getLogger(__name__)
INSTITUTIONS_BUND_PREFIX = "/api/bund/institutions"
router = APIRouter(prefix=INSTITUTIONS_BUND_PREFIX, tags=[Tags.BUND_INSTITUTIONS])
@router.get(
"/names",
operation_id="getBundInstitutionsByName",
summary="Returns a list of institutions based on their names.",
)
async def get_bund_institutions(
institution_names: Annotated[
list[str],
Query(description="A list of institution names to retrieve."),
] = [],
) -> BundInstitutionSummaryPage:
return await get_institutions_by_names(institution_names=institution_names or [])
@router.get(
"/autocomplete/selector",
operation_id="getBundInstitutionAutocompleteForSelector",
summary="Returns a list of institutions based on a search term for autocomplete functionality.",
)
async def get_bund_institution_autocomplete(
query: Annotated[
str,
Query(
description="A search term to filter institutions by (partial matches allowed)."
),
] = "",
) -> BundInstitutionSummaryPage:
return await autocomplete_institutions_for_selector(query=query)
@@ -0,0 +1,169 @@
import logging
from typing import Dict, List, Optional
from inse.integrations import elasticsearch
from inse.model import ESIndex, ESCluster
from inse.projects.bund_institutions.model import BundInstitutionSummary
from inse.projects.bund_institutions.model import BundInstitutionSummaryPage
logger = logging.getLogger(__name__)
# Fields on the BUND project index that describe the institution/agency involved,
# used consistently across all lookup functions below.
_INSTITUTION_SOURCE_FIELDS = [
"Ressort",
"Ressort_fullname",
"Ausführende Stelle",
"Zuwendungsempfänger",
"Stadt/Gemeinde",
"Ort",
"Bundesland",
"Staat",
]
async def search_institutions(
page: int = 0,
size: int = 10,
query: Optional[Dict] = None,
source: Optional[List[str]] = None,
sort: Optional[List[Dict]] = None,
body: Optional[Dict] = None,
) -> BundInstitutionSummaryPage:
"""Searches for institutions in the BUND Projects Elasticsearch index based on the provided parameters.
Note: PROJECTS_BUND_V1 indexes projects, not institutions directly, so each
matching project hit is reshaped into a BundInstitutionSummary. The same
institution may therefore appear multiple times if it's tied to multiple projects.
Args:
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
query (Optional[Dict], optional): The search query to filter institutions by. Defaults to None.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
sort (Optional[List[Dict]], optional): A list of sorting criteria. Defaults to None.
body (Optional[Dict], optional): The request body for the Elasticsearch search query. Defaults to None.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the search criteria.
"""
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
cluster=ESCluster.INSE,
query=query,
source=source or _INSTITUTION_SOURCE_FIELDS,
size=size,
offset=size * page,
sort=sort,
body=body,
)
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
institutions: List[BundInstitutionSummary] = [
BundInstitutionSummary.from_source(hit.get("_source", {})) for hit in hits
]
return BundInstitutionSummaryPage(
elements=institutions,
total=hits_block.get("total", {}).get("value", len(institutions)),
page=page,
size=size,
)
async def get_institutions_by_names(institution_names: List[str]) -> BundInstitutionSummaryPage:
"""Retrieves institutions based on a list of institution (Ausführende Stelle) names.
Args:
institution_names (List[str]): A list of institution names to retrieve.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the provided names.
"""
logger.debug(f"Fetching institutions for names: {institution_names}")
if not institution_names:
return BundInstitutionSummaryPage(elements=[], total=0, page=0, size=0)
return await search_institutions(
page=0,
size=len(institution_names),
query={
"terms": {
"Ausführende Stelle.keyword": institution_names,
}
},
source=_INSTITUTION_SOURCE_FIELDS,
)
async def autocomplete_institutions(
query: str, page: int = 0, size: int = 10, source: Optional[List[str]] = None
) -> BundInstitutionSummaryPage:
"""Autocompletes institutions based on a search term, matching against both the
executing agency (Ausführende Stelle) and recipient (Zuwendungsempfänger) fields.
Args:
query (str): The search term to autocomplete institutions with.
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the autocomplete criteria.
"""
logger.debug(f"Autocomplete institutions for query: {query}")
if not query:
return BundInstitutionSummaryPage(elements=[], total=0, page=0, size=0)
return await search_institutions(
page=page,
size=size,
query={
"bool": {
"should": [
{
"match_phrase_prefix": {
"Ausführende Stelle": {
"query": query,
"max_expansions": 50,
"boost": 2,
}
}
},
{
"match_phrase_prefix": {
"Zuwendungsempfänger": {
"query": query,
"max_expansions": 50,
}
}
},
],
"minimum_should_match": 1,
}
},
source=source or _INSTITUTION_SOURCE_FIELDS,
)
async def autocomplete_institutions_for_selector(
query: str, page: int = 0, size: int = 10
) -> BundInstitutionSummaryPage:
"""Autocompletes institutions based on a search term for use in a selector component.
Args:
query (str): The search term to filter institutions by (partial matches allowed).
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the autocomplete criteria.
"""
return await autocomplete_institutions(
query=query,
page=page,
size=size,
source=_INSTITUTION_SOURCE_FIELDS,
)
@@ -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
)
+123 -46
View File
@@ -74,6 +74,73 @@ async def get_person_ids_by_institution_ids(
if hit.get("_source", {}).get("person_id") is not None
}
)
async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""
Query the `projects_bund_openalex_topics` index to find BUND project IDs
that match any of the given OpenAlex topic IDs.
"""
if not topic_ids:
return []
required_topics = set(topic_ids)
project_topics: dict[str, Set[str]] = defaultdict(set)
page_size = 1000
from_ = 0
while True:
body = {
"size": page_size,
"from": from_,
"_source": ["project_id", "topic_matches"],
"query": {
"terms": {
"topic_matches.topic_id.keyword": topic_ids
}
},
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
cluster=ESCluster.INSE,
body=body,
)
print(f"Response from Elasticsearch: {json.dumps(response, indent=2)}") # Debugging line
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
for hit in hits:
source = hit["_source"]
project_id = source.get("project_id")
if not project_id:
continue
topic_matches = source.get("topic_matches") or []
if isinstance(topic_matches, dict):
topic_matches = [topic_matches]
for match in topic_matches:
topic_id = match.get("topic_id")
if topic_id in required_topics:
project_topics[project_id].add(topic_id)
if len(hits) < page_size:
break
from_ += page_size
return [
project_id
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
async def get_dfg_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""Fetches project IDs whose topic_matches contain EVERY given topic ID,
even if the topics are distributed across multiple documents for the same project.
@@ -137,63 +204,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],
+9 -3
View File
@@ -14,6 +14,7 @@ from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDet
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
from inse.authors.v2.model import AuthorPage
from inse.projects.bund_institutions.model import BundInstitutionSummary
from typing import Union
class ProjectType(StrEnum):
@@ -75,6 +76,11 @@ class BundProjectSummary(BundProject):
description="The OpenAlex topics of the project",
examples=[["Artificial Intelligence", "Machine Learning"]],
)
institution: Optional[BundInstitutionSummary] = Field(
default=None,
description="The executing agency / recipient institution for this project, "
"derived from the project's own agency fields.",
)
@classmethod
def from_hit(cls, hit: dict) -> "BundProjectSummary":
@@ -91,7 +97,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"),
@@ -110,8 +115,8 @@ class BundProjectSummary(BundProject):
topic=source.get("Thema"),
performance_plan_system=source.get("Leistungsplansystematik"),
performance_plan_system_text=source.get("Klartext Leistungsplansystematik"),
funding_start=source.get("Förderbeginn"),
funding_end=source.get("Förderende"),
funding_start=source.get("funding_start"),
funding_end=source.get("funding_end"),
grant_amount=source.get("Fördersumme"),
funding_profile=source.get("Förderprofil"),
joint_project=source.get("Verbundprojekt"),
@@ -122,6 +127,7 @@ class BundProjectSummary(BundProject):
new=source.get("neu"),
duration=source.get("Laufzeit"),
oa_topics=oa_topics,
institution=BundInstitutionSummary.from_source(source),
)
@staticmethod
@@ -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_bund_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes, get_openalex_topics_for_bund_projects
settings = get_settings()
@@ -29,66 +29,6 @@ logger = logging.getLogger(__name__)
logger.setLevel(settings.logging_level)
DFG_PERSON_FIELDS: List[str] = [
"Antragsteller",
"Antragstellerin",
"Antragstellerinnen",
"Antragstellerinnen / Antragsteller",
"Beteiligte Person",
"Beteiligte Personen",
"Co-Sprecher",
"Co-Sprecherinnen / Co-Sprecher",
"Ehemalige Antragsteller",
"Ehemalige Antragstellerin",
"Ehemalige Antragstellerinnen",
"Ehemalige Antragstellerinnen / Ehemalige Antragsteller",
"Ehemaliger Antragsteller",
"Gastgeber",
"Gastgeberin",
"Gastgeberinnen",
"Gastgeberinnen / Gastgeber",
"Kooperationspartner",
"Kooperationspartnerin",
"Kooperationspartnerinnen",
"Kooperationspartnerinnen / Kooperationspartner",
"Leiter",
"Leiterin",
"Leiterinnen",
"Leiterinnen / Leiter",
"Mitantragsteller",
"Mitantragstellerin",
"Mitantragstellerinnen",
"Mitantragstellerinnen / Mitantragsteller",
"Mitverantwortlich",
"Mitverantwortlich(e)",
"Mitverantwortliche",
"Sprecher",
"Sprecher (IGK-Partner)",
"Sprecherin",
"Sprecherin (IGK-Partner)",
"Sprecherinnen",
"Sprecherinnen (IGK-Partner) / Sprecher (IGK-Partner)",
"Sprecherinnen / Sprecher",
"Teilprojektleiter",
"Teilprojektleiterin",
"Teilprojektleiterinnen",
"Teilprojektleiterinnen / Teilprojektleiter",
"ausländ. Mitantragstellerin",
"ausländ. Mitantragstellerinnen",
"ausländ. Mitantragstellerinnen / ausländische Mitantragsteller",
"ausländische Mitantragsteller",
"ausländischer Mitantragsteller",
"beteiligte Wissenschaftler",
"beteiligte Wissenschaftlerin",
"beteiligte Wissenschaftlerinnen",
"beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler",
"beteiligter Wissenschaftler",
"person_creater_name",
"stellvertr. Sprecher",
"stellvertr. Sprecherin",
"stellvertr. Sprecherinnen / stellvertr. Sprecher",
]
# BUND
@@ -204,10 +144,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 +622,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,79 +634,42 @@ 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
#BUND
async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""
Query the `projects_bund_openalex_topics` index to find BUND project IDs
that match any of the given OpenAlex topic IDs.
"""
body: Dict[str, Any] = {
"size": 0,
"query": {
"terms": {
"topic_matches.topic_id": topic_ids
}
},
"aggs": {
"project_ids": {
"terms": {
"field": "project_id.keyword",
"size": 10000
def _bund_year_filters(field: str, years: List[str]) -> Dict[str, Any]:
should = []
for year in years:
year = str(year).strip()
if not year:
continue
should.append(
{
"range": {
field: {
"gte": f"01.01.{year}",
"lte": f"31.12.{year}",
}
}
}
)
return {
"bool": {
"should": should,
"minimum_should_match": 1,
}
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
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,
institution_ids: Optional[List[str]] = None,
funding_arts: Optional[List[str]] = None, # actually EuCordisProjectType, but treated as strings
title: Optional[str] = None,
keywords: Optional[List[str]] = None,
@@ -781,7 +688,7 @@ async def search_bund_projects_with_filters(
Main search function for BUND projects, analogous to the DFG search.
"""
from_ = page * size
#institution_ids = ["I62318514"]
# Fields we need to build BundProject objects (validation aliases match these exact names)
source_fields = [
"Förderkennzeichen",
@@ -812,7 +719,6 @@ async def search_bund_projects_with_filters(
"datum",
"neu",
"Laufzeit",
# Also include funding_start/end for sorting and filtering (they may also be needed)
"funding_start",
"funding_end",
]
@@ -825,13 +731,12 @@ async def search_bund_projects_with_filters(
}
must_clauses: List[Dict[str, Any]] = []
# === Primary search clause: fuzzy(topic_ids) vs keyword phrase search ===
if fuzzy and topic_ids:
matching_project_ids = await get_bund_project_ids_by_topic_ids(topic_ids=topic_ids)
if not matching_project_ids:
return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_project_ids}})
must_clauses.append({"terms": {"_id": matching_project_ids}})
elif keywords:
keyword_clauses = []
@@ -841,7 +746,7 @@ async def search_bund_projects_with_filters(
keyword_clauses.append({
"multi_match": {
"query": kw,
"fields": ["Verbundprojekt"], # searching title/acronym field
"fields": ["Verbundprojekt","Thema"], # searching title/acronym field
"type": "phrase_prefix",
"max_expansions": 100,
}
@@ -854,21 +759,38 @@ async def search_bund_projects_with_filters(
matching_filter_ids = await get_bund_project_ids_by_topic_ids(topic_ids=filter_topic_ids)
if not matching_filter_ids:
return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_filter_ids}})
must_clauses.append({"terms": {"_id": matching_filter_ids}})
if title:
must_clauses.append({
"multi_match": {
"query": title,
"fields": ["Verbundprojekt"],
"fields": ["Verbundprojekt","Thema"], # searching title field
"type": "phrase_prefix",
"max_expansions": 100,
}
})
# print(f"Executing BUND project search with institution_ids: {institution_ids}, executing_agency: {executing_agency}, funding_arts: {funding_arts}, countries: {countries}, funding_start_years: {funding_start_years}, funding_end_years: {funding_end_years}")
if executing_agency:
must_clauses.append({"terms": {"Ausführende Stelle.keyword": executing_agency}})
# institution_names = await institutions_search_client.get_institution_aliases_by_oa_institution_id(executing_agency[0].split("/")[-1])
# institution_page = await institutions_search_client.get_institutions_by_alias(alias=institution_names[0])
# print(f"Retrieved institution names for IDs {executing_agency}: {institution_names}")
# print(f"Retrieved institution page for names {institution_names}: {institution_page}")
# if not institution_names:
# return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({
"bool": {
"should": [
clause
for name in executing_agency
for clause in (
{"match": {"Zuwendungsempfänger": {"query": name, "operator": "and"}}},
{"match": {"Ausführende Stelle": {"query": name, "operator": "and"}}},
)
],
"minimum_should_match": 1,
}
})
if funding_arts:
must_clauses.append({"terms": {"Förderart.keyword": funding_arts}})
@@ -876,10 +798,10 @@ async def search_bund_projects_with_filters(
must_clauses.append({"terms": {"Staat.keyword": countries}})
if funding_start_years:
must_clauses.append({"terms": {"funding_start": funding_start_years}})
must_clauses.append(_bund_year_filters("funding_start", funding_start_years))
if funding_end_years:
must_clauses.append({"terms": {"funding_end": funding_end_years}})
must_clauses.append(_bund_year_filters("funding_end", funding_end_years))
body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
@@ -914,7 +836,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
)
@@ -0,0 +1,241 @@
from decimal import Decimal, ROUND_HALF_UP
from typing import Any
from inse.authors.v2.service import authors_currently_belong_to_institution
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.works.v2.model import WorkPrimaryCategory
from .model import PublicationType, Timespan
from .orientation_profile_model import (
AuthorOrientationProfile,
AuthorOrientationProfileStatus,
)
_SCORE_FIELD = "classification.applied_orientation_score"
_PRIMARY_CATEGORY_VALUES = {
category.value for category in WorkPrimaryCategory
}
def _author_filter(author_ids: list[str]) -> dict[str, Any]:
return {
"nested": {
"path": "authors",
"query": {"terms": {"authors.id": author_ids}},
}
}
def _orientation_profile_query(
author_ids: list[str],
publication_types: list[PublicationType],
timespan: Timespan | None,
) -> dict[str, Any]:
filters: list[dict[str, Any]] = [_author_filter(author_ids)]
if publication_types:
filters.append(
{
"terms": {
"publication_type": [
publication_type.value
for publication_type in publication_types
]
}
}
)
if timespan:
filters.append(
{
"range": {
"publication_year": {
"gte": timespan.from_year,
"lte": timespan.to_year,
}
}
}
)
return {
"size": 0,
"query": {"bool": {"filter": filters}},
"aggs": {
"authors": {
"nested": {"path": "authors"},
"aggs": {
"selected": {
"filter": {"terms": {"authors.id": author_ids}},
"aggs": {
"by_author": {
"terms": {
"field": "authors.id",
"size": len(author_ids),
"execution_hint": "map",
},
"aggs": {
"works": {
"reverse_nested": {},
"aggs": {
"classified": {
"filter": {
"exists": {
"field": (
"classification."
"primary_category"
)
}
},
"aggs": {
"by_primary_category": {
"terms": {
"field": (
"classification."
"primary_category"
),
"size": len(
WorkPrimaryCategory
),
}
}
},
},
"scored": {
"filter": {
"exists": {
"field": _SCORE_FIELD
}
},
"aggs": {
"average_score": {
"avg": {
"field": _SCORE_FIELD
}
}
},
},
},
}
},
}
},
}
},
}
},
}
def _rounded_score(value: float) -> int:
return int(Decimal(str(value)).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
def _profile_from_bucket(
author_id: str,
bucket: dict[str, Any] | None,
) -> AuthorOrientationProfile:
works = (bucket or {}).get("works", {})
classified_count = works.get("classified", {}).get("doc_count", 0)
category_buckets = (
works.get("classified", {})
.get("by_primary_category", {})
.get("buckets", [])
)
category_counts = {
WorkPrimaryCategory(category_bucket["key"]): category_bucket["doc_count"]
for category_bucket in category_buckets
if category_bucket.get("key") in _PRIMARY_CATEGORY_VALUES
}
scored = works.get("scored", {})
scored_count = scored.get("doc_count", 0)
average_score = scored.get("average_score", {}).get("value")
if classified_count == 0:
status = AuthorOrientationProfileStatus.NO_CLASSIFIED_PUBLICATIONS
elif scored_count == 0 or average_score is None:
status = AuthorOrientationProfileStatus.NO_ORIENTATION_SCORE
else:
score = _rounded_score(average_score)
return AuthorOrientationProfile(
author_id=author_id,
status=AuthorOrientationProfileStatus.AVAILABLE,
orientation_score=score,
primary_category_counts=category_counts,
classified_work_count=classified_count,
scored_work_count=scored_count,
)
return AuthorOrientationProfile(
author_id=author_id,
status=status,
primary_category_counts=category_counts,
classified_work_count=classified_count,
scored_work_count=scored_count,
)
async def orientation_profiles_for_authors(
author_ids: list[str],
institution_id: str | None,
publication_types: list[PublicationType],
timespan: Timespan | None,
) -> list[AuthorOrientationProfile]:
"""Return protected orientation profiles in the requested author order.
Institution membership is checked for all authors in one query. Only
matching active members are included in the work-classification
aggregation, so restricted classification data is never retrieved.
"""
if not institution_id:
allowed_author_ids: set[str] = set()
else:
allowed_author_ids = await authors_currently_belong_to_institution(
author_ids,
institution_id,
)
restricted_profiles = {
author_id: AuthorOrientationProfile(
author_id=author_id,
status=AuthorOrientationProfileStatus.RESTRICTED,
)
for author_id in author_ids
if author_id not in allowed_author_ids
}
allowed_in_request_order = [
author_id for author_id in author_ids if author_id in allowed_author_ids
]
profiles_by_id: dict[str, AuthorOrientationProfile] = restricted_profiles
if allowed_in_request_order:
response = await elasticsearch.search(
index=ESIndex.WORK_CLASSIFICATIONS,
body=_orientation_profile_query(
allowed_in_request_order,
publication_types,
timespan,
),
)
buckets = (
response.get("aggregations", {})
.get("authors", {})
.get("selected", {})
.get("by_author", {})
.get("buckets", [])
)
buckets_by_author = {
bucket.get("key"): bucket
for bucket in buckets
if isinstance(bucket.get("key"), str)
}
for author_id in allowed_in_request_order:
profiles_by_id[author_id] = _profile_from_bucket(
author_id,
buckets_by_author.get(author_id),
)
return [profiles_by_id[author_id] for author_id in author_ids]
@@ -0,0 +1,78 @@
from enum import StrEnum
from pydantic import BaseModel, Field, field_validator
from inse.works.v2.model import WorkPrimaryCategory
from .model import PublicationType, Timespan
class AuthorOrientationProfileStatus(StrEnum):
AVAILABLE = "available"
INSUFFICIENT_SCORED_PUBLICATIONS = "insufficient_scored_publications"
NO_CLASSIFIED_PUBLICATIONS = "no_classified_publications"
NO_ORIENTATION_SCORE = "no_orientation_score"
RESTRICTED = "restricted"
class AuthorOrientationProfilesRequest(BaseModel):
"""Filters used to compare the research orientation of selected authors."""
author_ids: list[str] = Field(
min_length=1,
max_length=4,
description="One to four unique OpenAlex author IDs.",
)
publication_types: list[PublicationType] = Field(
default_factory=list,
description="Optional publication-type filter. Empty means all types.",
)
timespan: Timespan | None = Field(
default=None,
description="Optional inclusive publication-year filter.",
)
@field_validator("author_ids")
@classmethod
def normalize_author_ids(cls, values: list[str]) -> list[str]:
normalized: list[str] = []
for value in values:
author_id = value.strip()
if not author_id:
raise ValueError("author IDs must not be empty")
if not author_id.startswith("https://openalex.org/"):
author_id = f"https://openalex.org/{author_id}"
if author_id in normalized:
raise ValueError("author IDs must be unique")
normalized.append(author_id)
return normalized
class AuthorOrientationProfile(BaseModel):
"""Aggregated research-orientation result for one selected author."""
author_id: str = Field(description="The full OpenAlex author ID.")
status: AuthorOrientationProfileStatus
orientation_score: int | None = Field(
default=None,
ge=0,
le=100,
description="Rounded mean score, available when at least one work has a score.",
)
primary_category_counts: dict[WorkPrimaryCategory, int] | None = Field(
default=None,
description=(
"Matching work counts grouped by primary category; hidden when "
"access is restricted."
),
)
classified_work_count: int | None = Field(
default=None,
ge=0,
description="Matching classified works; hidden when access is restricted.",
)
scored_work_count: int | None = Field(
default=None,
ge=0,
description="Matching works with an orientation score; hidden when restricted.",
)
+25
View File
@@ -7,6 +7,11 @@ from inse.auth.model import AccessTokenMetadata
from inse.auth.service import CurrentUserAccessTokenPayloadDep
from inse.tags import Tags
from . import logic
from .orientation_profile_logic import orientation_profiles_for_authors
from .orientation_profile_model import (
AuthorOrientationProfile,
AuthorOrientationProfilesRequest,
)
from .model import (
AuthorMetricsRequest,
AuthorStaticStats,
@@ -117,3 +122,23 @@ async def static_stats(request: AuthorMetricsRequest):
request.author_ids,
request.company_status,
)
@router.post(
"/orientation-profiles",
response_model=List[AuthorOrientationProfile],
)
async def orientation_profiles(
request: AuthorOrientationProfilesRequest,
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
):
"""Compare orientation scores for active members of the account institution."""
return await orientation_profiles_for_authors(
author_ids=request.author_ids,
institution_id=access_token_metadata.effective_institution_id,
publication_types=request.publication_types,
timespan=request.timespan,
)
+2
View File
@@ -24,3 +24,5 @@ class Tags(StrEnum):
DFG_INSTITUTIONS = "DFG Institutions"
DFG_PERSONS = "DFG Persons"
BACKGROUND_JOBS = "Background Jobs"
BUND_INSTITUTIONS = "BUND Institutions"
+21 -1
View File
@@ -74,7 +74,27 @@ async def search_topics(
query = None
if search_term:
query = {"match_phrase_prefix": {"display_name": search_term}}
search_terms = [
term.strip() for term in search_term.split(",") if term.strip()
]
if len(search_terms) == 1:
query = {
"match_phrase_prefix": {"display_name": search_terms[0]}
}
elif search_terms:
query = {
"bool": {
"should": [
{
"match_phrase_prefix": {
"display_name": search_term
}
}
for search_term in search_terms
],
"minimum_should_match": 1,
}
}
return await _search_topics(
page=page,
@@ -0,0 +1,41 @@
from unittest.mock import AsyncMock, patch
import pytest
from inse.topics.v2.service import search_topics
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_search_topics_treats_comma_separated_terms_as_alternatives():
with patch(
"inse.topics.v2.service.elasticsearch.search",
new=AsyncMock(
return_value={
"hits": {"hits": [], "total": {"value": 0}}
}
),
) as search:
await search_topics("Artificial Intelligence, Machine Learning")
assert search.await_args.kwargs["query"] == {
"bool": {
"should": [
{
"match_phrase_prefix": {
"display_name": "Artificial Intelligence"
}
},
{
"match_phrase_prefix": {
"display_name": "Machine Learning"
}
},
],
"minimum_should_match": 1,
}
}
@@ -6,6 +6,7 @@ api.module.ts
api/api.ts
api/auth.service.ts
api/authorsV2.service.ts
api/bUNDInstitutions.service.ts
api/backgroundJobs.service.ts
api/bookmarks.service.ts
api/companyConnections.service.ts
@@ -43,6 +44,9 @@ model/authorCountsByYearInner.ts
model/authorIds.ts
model/authorMetricsRequest.ts
model/authorNode.ts
model/authorOrientationProfile.ts
model/authorOrientationProfileStatus.ts
model/authorOrientationProfilesRequest.ts
model/authorPage.ts
model/authorParsedLongestName.ts
model/authorPositionCount.ts
@@ -66,6 +70,8 @@ model/bodyLogin.ts
model/bodyRequestOtk.ts
model/bodyRequestPasswordReset.ts
model/bodyResetPassword.ts
model/bundInstitutionSummary.ts
model/bundInstitutionSummaryPage.ts
model/bundProjectDetails.ts
model/bundProjectPage.ts
model/bundProjectSummary.ts
@@ -96,7 +102,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
+29 -1
View File
@@ -2,6 +2,8 @@ export * from './auth.service';
import { AuthService } from './auth.service';
export * from './authorsV2.service';
import { AuthorsV2Service } from './authorsV2.service';
export * from './bUNDInstitutions.service';
import { BUNDInstitutionsService } from './bUNDInstitutions.service';
export * from './backgroundJobs.service';
import { BackgroundJobsService } from './backgroundJobs.service';
export * from './bookmarks.service';
@@ -46,4 +48,30 @@ export * from './works.service';
import { WorksService } from './works.service';
export * from './worksV2.service';
import { WorksV2Service } from './worksV2.service';
export const APIS = [AuthService, AuthorsV2Service, BackgroundJobsService, BookmarksService, CompanyConnectionsService, DFGInstitutionsService, DFGPersonsService, DashboardService, FundingService, INSEServiceService, InstitutionsService, InstitutionsV2Service, KeywordsService, NewsService, OrganizationService, PatentsService, PersonsService, ProjectsService, RankingService, TopicsService, TopicsV2Service, UniversityRankingsService, WorksService, WorksV2Service];
export const APIS = [
AuthService,
AuthorsV2Service,
BUNDInstitutionsService,
BackgroundJobsService,
BookmarksService,
CompanyConnectionsService,
DFGInstitutionsService,
DFGPersonsService,
DashboardService,
FundingService,
INSEServiceService,
InstitutionsService,
InstitutionsV2Service,
KeywordsService,
NewsService,
OrganizationService,
PatentsService,
PersonsService,
ProjectsService,
RankingService,
TopicsService,
TopicsV2Service,
UniversityRankingsService,
WorksService,
WorksV2Service,
];
@@ -0,0 +1,258 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { BundInstitutionSummaryPage } from '../model/bundInstitutionSummaryPage';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root',
})
export class BUNDInstitutionsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
/**
* Returns a list of institutions based on a search term for autocomplete functionality.
* @endpoint get /api/bund/institutions/autocomplete/selector
* @param query A search term to filter institutions by (partial matches allowed).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<BundInstitutionSummaryPage>;
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<BundInstitutionSummaryPage>>;
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<BundInstitutionSummaryPage>>;
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>query,
'query',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/bund/institutions/autocomplete/selector`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<BundInstitutionSummaryPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Returns a list of institutions based on their names.
* @endpoint get /api/bund/institutions/names
* @param institutionNames A list of institution names to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<BundInstitutionSummaryPage>;
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<BundInstitutionSummaryPage>>;
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<BundInstitutionSummaryPage>>;
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (institutionNames) {
institutionNames.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'institution_names',
);
});
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/bund/institutions/names`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<BundInstitutionSummaryPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
+620 -265
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
@@ -9,16 +9,26 @@
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { AuthorMetricsRequest } from '../model/authorMetricsRequest';
// @ts-ignore
import { AuthorOrientationProfile } from '../model/authorOrientationProfile';
// @ts-ignore
import { AuthorOrientationProfilesRequest } from '../model/authorOrientationProfilesRequest';
// @ts-ignore
import { AuthorStaticStats } from '../model/authorStaticStats';
// @ts-ignore
import { AuthorTopicProfile } from '../model/authorTopicProfile';
@@ -34,283 +44,628 @@ import { RankedAuthor } from '../model/rankedAuthor';
import { SelectedAuthorsRequest } from '../model/selectedAuthorsRequest';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class RankingService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
/**
* Orientation Profiles
* Compare orientation scores for active members of the account institution.
* @endpoint post /api/rank/orientation-profiles
* @param authorOrientationProfilesRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public orientationProfilesApiRankOrientationProfilesPost(
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorOrientationProfile>>;
public orientationProfilesApiRankOrientationProfilesPost(
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorOrientationProfile>>>;
public orientationProfilesApiRankOrientationProfilesPost(
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorOrientationProfile>>>;
public orientationProfilesApiRankOrientationProfilesPost(
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
authorOrientationProfilesRequest === null ||
authorOrientationProfilesRequest === undefined
) {
throw new Error(
'Required parameter authorOrientationProfilesRequest was null or undefined when calling orientationProfilesApiRankOrientationProfilesPost.',
);
}
/**
* Rank Author
* @endpoint post /api/rank/rank-author
* @param keywordToAuthorRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<RankedAuthor>>;
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (keywordToAuthorRequest === null || keywordToAuthorRequest === undefined) {
throw new Error('Required parameter keywordToAuthorRequest was null or undefined when calling rankAuthorApiRankRankAuthorPost.');
}
let localVarHeaders = this.defaultHeaders;
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/rank-author`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<RankedAuthor>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: keywordToAuthorRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
/**
* Static Stats
* @endpoint post /api/rank/static-stats
* @param authorMetricsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AuthorStaticStats>>;
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorMetricsRequest === null || authorMetricsRequest === undefined) {
throw new Error('Required parameter authorMetricsRequest was null or undefined when calling staticStatsApiRankStaticStatsPost.');
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
let localVarHeaders = this.defaultHeaders;
const localVarTransferCache: boolean = options?.transferCache ?? true;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/static-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorStaticStats>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: authorMetricsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
/**
* Topic Profile
* @endpoint post /api/rank/topic-profile
* @param selectedAuthorsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AuthorTopicProfile>>;
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (selectedAuthorsRequest === null || selectedAuthorsRequest === undefined) {
throw new Error('Required parameter selectedAuthorsRequest was null or undefined when calling topicProfileApiRankTopicProfilePost.');
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/topic-profile`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicProfile>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
/**
* Topic Stats
* @endpoint post /api/rank/topic-stats
* @param selectedAuthorsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AuthorTopicStats>>;
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (selectedAuthorsRequest === null || selectedAuthorsRequest === undefined) {
throw new Error('Required parameter selectedAuthorsRequest was null or undefined when calling topicStatsApiRankTopicStatsPost.');
}
let localVarPath = `/api/rank/orientation-profiles`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorOrientationProfile>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: authorOrientationProfilesRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/topic-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicStats>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
/**
* Rank Author
* @endpoint post /api/rank/rank-author
* @param keywordToAuthorRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<RankedAuthor>>;
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
keywordToAuthorRequest === null ||
keywordToAuthorRequest === undefined
) {
throw new Error(
'Required parameter keywordToAuthorRequest was null or undefined when calling rankAuthorApiRankRankAuthorPost.',
);
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/rank-author`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<RankedAuthor>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: keywordToAuthorRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Static Stats
* @endpoint post /api/rank/static-stats
* @param authorMetricsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorStaticStats>>;
public staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorMetricsRequest === null || authorMetricsRequest === undefined) {
throw new Error(
'Required parameter authorMetricsRequest was null or undefined when calling staticStatsApiRankStaticStatsPost.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/static-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorStaticStats>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: authorMetricsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Topic Profile
* @endpoint post /api/rank/topic-profile
* @param selectedAuthorsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorTopicProfile>>;
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
selectedAuthorsRequest === null ||
selectedAuthorsRequest === undefined
) {
throw new Error(
'Required parameter selectedAuthorsRequest was null or undefined when calling topicProfileApiRankTopicProfilePost.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/topic-profile`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicProfile>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Topic Stats
* @endpoint post /api/rank/topic-stats
* @param selectedAuthorsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorTopicStats>>;
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
selectedAuthorsRequest === null ||
selectedAuthorsRequest === undefined
) {
throw new Error(
'Required parameter selectedAuthorsRequest was null or undefined when calling topicStatsApiRankTopicStatsPost.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/topic-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicStats>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
@@ -0,0 +1,27 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { AuthorOrientationProfileStatus } from './authorOrientationProfileStatus';
import { WorkPrimaryCategory } from './workPrimaryCategory';
/**
* Aggregated research-orientation result for one selected author.
*/
export interface AuthorOrientationProfile {
/**
* The full OpenAlex author ID.
*/
author_id: string;
status: AuthorOrientationProfileStatus;
orientation_score?: number | null;
primary_category_counts?: Partial<Record<WorkPrimaryCategory, number>> | null;
classified_work_count?: number | null;
scored_work_count?: number | null;
}
export namespace AuthorOrientationProfile {}
@@ -0,0 +1,19 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export const AuthorOrientationProfileStatus = {
available: 'available',
insufficient_scored_publications: 'insufficient_scored_publications',
no_classified_publications: 'no_classified_publications',
no_orientation_score: 'no_orientation_score',
restricted: 'restricted',
} as const;
export type AuthorOrientationProfileStatus =
(typeof AuthorOrientationProfileStatus)[keyof typeof AuthorOrientationProfileStatus];
@@ -0,0 +1,26 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Timespan } from './timespan';
import { PublicationType } from './publicationType';
/**
* Filters used to compare the research orientation of selected authors.
*/
export interface AuthorOrientationProfilesRequest {
/**
* One to four unique OpenAlex author IDs.
*/
author_ids: Array<string>;
/**
* Optional publication-type filter. Empty means all types.
*/
publication_types?: Array<PublicationType>;
timespan?: Timespan | null;
}
@@ -0,0 +1,23 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A single institution entry derived from a BUND project record. Note: this index has no dedicated institution entity — each entry is reconstructed from the agency/recipient fields on a single project hit, so the same institution may appear multiple times (once per project).
*/
export interface BundInstitutionSummary {
department?: string | null;
department_fullname?: string | null;
name?: string | null;
recepient?: string | null;
municipality?: string | null;
place?: string | null;
state?: string | null;
country?: string | null;
}
@@ -0,0 +1,32 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { BundInstitutionSummary } from './bundInstitutionSummary';
/**
* A paginated response containing a list of institutions.
*/
export interface BundInstitutionSummaryPage {
/**
* The elements of the page.
*/
elements?: Array<BundInstitutionSummary>;
/**
* The page number. (0-based)
*/
page?: number;
/**
* The page size in elements.
*/
size?: number;
/**
* The total number of elements.
*/
total?: number;
}
+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;
}
+33 -33
View File
@@ -1,44 +1,44 @@
/**
* 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';
import { BundInstitutionSummary } from './bundInstitutionSummary';
export interface BundProjectSummary {
funding_code?: string | null;
department?: string | null;
department_fullname?: string | null;
referat?: string | null;
project_sponsor?: string | null;
project_sponsor_fullname?: string | null;
work_unit?: string | null;
recipient?: string | null;
municipal_code?: string | null;
municipality?: string | null;
place?: string | null;
state?: string | null;
country?: string | null;
implementing_agency?: string | null;
topic?: string | null;
performance_plan_system?: string | null;
performance_plan_system_text?: string | null;
funding_start?: string | null;
funding_end?: string | null;
grant_amount?: number | null;
funding_profile?: string | null;
joint_project?: string | null;
funding_type?: string | null;
publication_date?: string | null;
unix_timestamp?: number | null;
date?: string | null;
'new'?: boolean | null;
duration?: string | null;
oa_topics?: Array<Topic> | null;
export interface BundProjectSummary {
funding_code?: string | null;
department?: string | null;
department_fullname?: string | null;
referat?: string | null;
project_sponsor?: string | null;
project_sponsor_fullname?: string | null;
work_unit?: string | null;
recipient?: string | null;
municipal_code?: string | null;
municipality?: string | null;
place?: string | null;
state?: string | null;
country?: string | null;
implementing_agency?: string | null;
topic?: string | null;
performance_plan_system?: string | null;
performance_plan_system_text?: string | null;
funding_start?: string | null;
funding_end?: string | null;
grant_amount?: number | null;
funding_profile?: string | null;
joint_project?: string | null;
funding_type?: string | null;
publication_date?: string | null;
unix_timestamp?: number | null;
date?: string | null;
new?: boolean | null;
duration?: string | null;
oa_topics?: Array<Topic> | null;
institution?: BundInstitutionSummary | 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;
}
+10
View File
@@ -9,6 +9,9 @@ export * from './authorCountsByYearInner';
export * from './authorIds';
export * from './authorMetricsRequest';
export * from './authorNode';
export * from './authorOrientationProfile';
export * from './authorOrientationProfileStatus';
export * from './authorOrientationProfilesRequest';
export * from './authorPage';
export * from './authorParsedLongestName';
export * from './authorPositionCount';
@@ -32,6 +35,8 @@ export * from './bodyLogin';
export * from './bodyRequestOtk';
export * from './bodyRequestPasswordReset';
export * from './bodyResetPassword';
export * from './bundInstitutionSummary';
export * from './bundInstitutionSummaryPage';
export * from './bundProjectDetails';
export * from './bundProjectPage';
export * from './bundProjectSummary';
@@ -62,7 +67,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';
+23 -17
View File
@@ -39,6 +39,7 @@ import {
} from './resolvers/work-page.resolver';
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
import { selectedBundInstitutionsResolver } from './resolvers/selected-bund-institutions.resolver';
import { SearchResultsStateService } from './modules/keywords-search/search-results/search-results-state.service';
import { roleGuard } from './shared/guards/role.guard';
import { UserRole } from './api';
@@ -241,6 +242,20 @@ export const routes: Routes = [
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
{
path: 'bund',
component: BundProjectsComponent,
resolve: {
bundProjectPage: bundProjectsResolver,
selectedBundInstitutionsPage: selectedBundInstitutionsResolver,
selectedBundAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
],
},
{ path: 'patents', component: KeywordsToPatentsResultsComponent },
@@ -526,20 +541,6 @@ export const routes: Routes = [
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON,
},
},
{
path: 'bund',
component: BundProjectsComponent,
resolve: {
bundProjectPage: bundProjectsResolver,
selectedBundInstitutionsPage: selectedInstitutionsResolver,
selectedBundAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
],
},
{
@@ -757,9 +758,14 @@ export const routes: Routes = [
topicPage: topicPageResolver,
},
runGuardsAndResolvers: (from, to) => {
return Object.values(topicQueryParamKeys).some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
return Object.values(topicQueryParamKeys).some((key) => {
const fromValues = from.queryParamMap.getAll(key);
const toValues = to.queryParamMap.getAll(key);
return (
fromValues.length !== toValues.length ||
fromValues.some((value, index) => value !== toValues[index])
);
});
},
},
{
@@ -0,0 +1,156 @@
import { Component, computed, input } from '@angular/core';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { WorkPrimaryCategory } from '../../../api';
import { SUBFIELD_COLORS } from '../compare-authors-colors';
export interface AuthorCategoryLegendItem {
category: WorkPrimaryCategory;
label: string;
color: string;
}
const categoryLegendItem = (
category: WorkPrimaryCategory,
label: string,
color: string,
): AuthorCategoryLegendItem => ({
category,
label,
color,
});
export const AUTHOR_CATEGORY_LEGEND: readonly AuthorCategoryLegendItem[] = [
categoryLegendItem(
WorkPrimaryCategory.BasicResearch,
'Grundlagenforschung',
SUBFIELD_COLORS[0],
),
categoryLegendItem(
WorkPrimaryCategory.AppliedResearch,
'Anwendungsbasierte Forschung',
SUBFIELD_COLORS[1],
),
categoryLegendItem(
WorkPrimaryCategory.ExperimentalDevelopment,
'Experimentelle Entwicklung',
SUBFIELD_COLORS[2],
),
categoryLegendItem(
WorkPrimaryCategory.NonResearch,
'Nicht-forschende Tätigkeit',
SUBFIELD_COLORS[3],
),
categoryLegendItem(
WorkPrimaryCategory.NotClassified,
'Nicht klassifiziert',
SUBFIELD_COLORS[4],
),
];
@Component({
selector: 'app-author-category-pie',
standalone: true,
imports: [NgxEchartsDirective],
template: '<div echarts class="category-chart" [options]="options()"></div>',
styles: `
:host {
display: block;
width: 100%;
max-width: 240px;
}
.category-chart {
width: 100%;
height: 220px;
}
`,
})
export class AuthorCategoryPieComponent {
counts = input<Partial<Record<WorkPrimaryCategory, number>> | null>(null);
readonly total = computed(() =>
Object.values(this.counts() ?? {}).reduce(
(sum, count) => sum + Math.max(0, count),
0,
),
);
readonly options = computed<EChartsOption>(() => {
const counts = this.counts() ?? {};
const total = this.total();
const textColor = this.cssColor('--sg-text', '#0f172a');
const mutedColor = this.cssColor('--sg-text-muted', '#64748b');
return {
animation: false,
tooltip: {
trigger: 'item',
formatter: '{b}: {c} Publikationen ({d} %)',
},
graphic: {
type: 'text',
left: 'center',
top: 'middle',
silent: true,
style: {
text: `{value|${total}}\n{label|klassifiziert}`,
textAlign: 'center',
textVerticalAlign: 'middle',
rich: {
value: {
fill: textColor,
fontSize: 22,
fontWeight: 700,
lineHeight: 23,
},
label: {
fill: mutedColor,
fontSize: 11,
fontWeight: 600,
lineHeight: 12,
},
},
},
},
series: [
{
type: 'pie',
radius: ['40%', '70%'],
center: ['50%', '50%'],
avoidLabelOverlap: true,
silent: false,
selectedMode: false,
padAngle: 1,
itemStyle: {
borderRadius: 2,
},
label: {
show: false,
},
labelLine: { show: false },
emphasis: {
scale: true,
scaleSize: 6,
},
data: AUTHOR_CATEGORY_LEGEND.map((item) => ({
name: item.label,
value: Math.max(0, counts[item.category] ?? 0),
itemStyle: { color: item.color },
})).filter((item) => item.value > 0),
},
],
};
});
private cssColor(variable: string, fallback: string): string {
if (typeof getComputedStyle !== 'function') {
return fallback;
}
return (
getComputedStyle(document.documentElement)
.getPropertyValue(variable)
.trim() || fallback
);
}
}
@@ -0,0 +1,106 @@
@if (visible()) {
<mat-card appearance="outlined" class="research-profile-card">
<mat-card-header class="profile-header">
<mat-icon class="profile-icon">science</mat-icon>
<div class="profile-heading">
<mat-card-title>Forschungsprofil</mat-card-title>
<mat-card-subtitle>
Vergleich der Forschungsorientierung
</mat-card-subtitle>
</div>
</mat-card-header>
<mat-card-content>
<section aria-labelledby="category-distribution-title">
<h3 id="category-distribution-title" class="section-title">
Verteilung der Forschungskategorien
</h3>
<div class="author-grid">
@for (view of views(); track view.author.authorId) {
<mat-card appearance="outlined" class="author-card">
<mat-card-header class="author-header">
<div class="author-heading">
<span
class="author-color"
[style.background]="view.author.color"></span>
<mat-card-title>{{ view.author.name }}</mat-card-title>
</div>
</mat-card-header>
<mat-card-content class="distribution-content">
@if (hasCategoryData(view.profile)) {
<app-author-category-pie
[counts]="view.profile.primary_category_counts ?? null" />
} @else {
<p class="status-label distribution-status">
{{ categoryStatusLabel(view.profile) }}
</p>
}
</mat-card-content>
</mat-card>
}
</div>
<mat-chip-set class="category-legend" aria-label="Forschungskategorien">
@for (item of categoryLegend; track item.category) {
<mat-chip class="legend-chip" [style.--legend-color]="item.color">
<span class="legend-color" [style.background]="item.color"></span>
{{ item.label }}
</mat-chip>
}
</mat-chip-set>
</section>
<mat-divider class="section-divider"></mat-divider>
<section aria-labelledby="average-score-title">
<h3 id="average-score-title" class="section-title">
Durchschnittlicher Orientierungsscore
</h3>
<div class="author-grid">
@for (view of views(); track view.author.authorId) {
<mat-card appearance="outlined" class="author-card">
<mat-card-header class="author-header">
<div class="author-heading">
<span
class="author-color"
[style.background]="view.author.color"></span>
<mat-card-title>{{ view.author.name }}</mat-card-title>
</div>
</mat-card-header>
<mat-card-content class="score-content">
<app-orientation-gauge
[score]="view.profile.orientation_score ?? null" />
@if (hasLowScoreSample(view.profile)) {
<mat-card
appearance="outlined"
class="warning-note"
[style.--warning-border]="lowSampleTokens.border"
[style.--warning-background]="lowSampleTokens.background"
[style.--warning-text]="lowSampleTokens.color">
<span>Geringe Datengrundlage</span>
<mat-icon
class="info-icon"
[matTooltip]="lowScoreSampleTooltip(view.profile)"
matTooltipPosition="above"
aria-label="Erläuterung zur Datengrundlage">
info_outline
</mat-icon>
</mat-card>
} @else if (!isAvailable(view.profile)) {
<p class="status-label">
{{ statusLabel(view.profile.status) }}
</p>
}
</mat-card-content>
</mat-card>
}
</div>
</section>
</mat-card-content>
</mat-card>
}
@@ -0,0 +1,214 @@
:host {
display: block;
}
.research-profile-card {
border-color: var(--sg-border);
border-radius: 16px;
box-shadow: 0 8px 24px rgb(15 23 42 / 4%);
}
.profile-header {
align-items: center;
padding: 20px 22px 16px;
}
.profile-icon {
flex: 0 0 30px;
width: 30px;
height: 30px;
margin: 0 12px 0 0;
color: var(--sg-text-muted);
font-size: 30px;
line-height: 30px;
}
.profile-heading {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
}
mat-card-title {
color: var(--sg-text);
font-size: 16px;
font-weight: 700;
line-height: 1.25;
}
mat-card-subtitle {
margin: 0;
color: var(--sg-text-muted);
font-size: 13px;
line-height: 1.3;
}
.research-profile-card > mat-card-content {
padding: 10px 22px 22px;
}
section {
min-width: 0;
}
.section-title {
margin: 8px 0 12px;
color: var(--sg-text);
font-size: 15px;
font-weight: 700;
line-height: 1.3;
}
.author-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
gap: 14px;
}
.author-card {
min-width: 0;
border-color: var(--sg-border);
background: var(--sg-surface);
}
.author-header {
align-items: center;
min-height: 52px;
padding: 14px 16px 4px;
}
.author-heading {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.author-heading mat-card-title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.author-color {
flex: 0 0 auto;
width: 12px;
height: 12px;
border-radius: 3px;
}
.distribution-content,
.score-content {
display: flex;
flex-direction: column;
align-items: center;
padding: 0 16px 16px;
}
.distribution-content {
justify-content: center;
min-height: 232px;
}
.score-content {
min-height: 220px;
}
.score-content app-orientation-gauge {
margin-top: -4px;
}
.category-legend {
display: flex;
justify-content: center;
margin-top: 14px;
}
.legend-chip {
--mdc-chip-elevated-container-color: color-mix(
in srgb,
var(--legend-color) 10%,
var(--sg-surface)
);
--mdc-chip-label-text-color: var(--legend-color);
--mdc-chip-outline-color: color-mix(
in srgb,
var(--legend-color) 28%,
transparent
);
border: 1px solid color-mix(in srgb, var(--legend-color) 28%, transparent);
}
.legend-color {
display: inline-block;
width: 9px;
height: 9px;
margin-right: 6px;
border-radius: 50%;
}
.section-divider {
margin: 22px 0 18px;
}
.status-label {
display: flex;
align-items: center;
justify-content: center;
min-height: 34px;
margin: 20px 0 0;
color: var(--sg-text-muted);
font-size: 13px;
font-weight: 600;
text-align: center;
}
.warning-note {
display: flex;
flex-direction: row;
align-items: center;
gap: 10px;
min-height: 42px;
margin-top: 12px;
padding: 9px 12px;
border-color: var(--warning-border);
border-radius: 12px;
background: var(--warning-background);
color: var(--warning-text);
box-shadow: none;
font-size: 13px;
line-height: 1.4;
}
.warning-note .info-icon {
flex: 0 0 auto;
width: 16px;
height: 16px;
color: inherit;
font-size: 16px;
line-height: 16px;
opacity: 0.7;
cursor: default;
&:hover {
opacity: 1;
}
}
.distribution-status {
margin: 0;
}
@media (max-width: 720px) {
.research-profile-card > mat-card-header,
.research-profile-card > mat-card-content {
padding-right: 16px;
padding-left: 16px;
}
.author-grid {
grid-template-columns: 1fr;
}
}
@@ -0,0 +1,134 @@
import { Component, computed, input } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { MatChipsModule } from '@angular/material/chips';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import {
AuthorOrientationProfile,
AuthorOrientationProfileStatus,
} from '../../../api';
import { OrientationGaugeComponent } from '../../../shared/ui/orientation-gauge/orientation-gauge.component';
import { topicChipColorTokens } from '../../../shared/ui/topic-chip/topic-chip.component';
import {
AUTHOR_CATEGORY_LEGEND,
AuthorCategoryPieComponent,
} from './author-category-pie.component';
export interface ResearchProfileAuthor {
authorId: string;
name: string;
color: string;
}
interface AuthorOrientationView {
author: ResearchProfileAuthor;
profile: AuthorOrientationProfile;
}
const LOW_SAMPLE_MAX_WORKS = 4;
const LOW_SAMPLE_TOKENS = topicChipColorTokens('orange');
@Component({
selector: 'app-author-research-profile',
standalone: true,
imports: [
MatCardModule,
MatChipsModule,
MatDividerModule,
MatIconModule,
MatTooltipModule,
AuthorCategoryPieComponent,
OrientationGaugeComponent,
],
templateUrl: './author-research-profile.component.html',
styleUrl: './author-research-profile.component.scss',
})
export class AuthorResearchProfileComponent {
authors = input.required<ResearchProfileAuthor[]>();
profiles = input.required<AuthorOrientationProfile[]>();
loading = input(false);
readonly categoryLegend = AUTHOR_CATEGORY_LEGEND;
readonly lowSampleTokens = LOW_SAMPLE_TOKENS;
readonly views = computed<AuthorOrientationView[]>(() => {
const profilesById = new Map(
this.profiles().map((profile) => [profile.author_id, profile]),
);
return this.authors()
.map((author) => {
const profile = profilesById.get(author.authorId);
return profile ? { author, profile } : null;
})
.filter((view): view is AuthorOrientationView => view !== null);
});
readonly visible = computed(() => {
const profiles = this.profiles();
const profilesWithoutClassifiedWorks = profiles.filter(
(profile) => (profile.classified_work_count ?? 0) === 0,
).length;
return (
!this.loading() &&
profiles.length >= 2 &&
profilesWithoutClassifiedWorks < 3
);
});
statusLabel(status: AuthorOrientationProfileStatus): string {
switch (status) {
case AuthorOrientationProfileStatus.insufficient_scored_publications:
return 'Zu wenige Publikationen für einen Orientierungsscore';
case AuthorOrientationProfileStatus.no_classified_publications:
return 'Keine klassifizierten Publikationen';
case AuthorOrientationProfileStatus.no_orientation_score:
return 'Kein Orientierungsscore verfügbar';
case AuthorOrientationProfileStatus.restricted:
return 'Orientierungsscore nicht verfügbar';
default:
return '';
}
}
isAvailable(profile: AuthorOrientationProfile): boolean {
return profile.status === AuthorOrientationProfileStatus.available;
}
hasLowScoreSample(profile: AuthorOrientationProfile): boolean {
const scoredWorkCount = profile.scored_work_count ?? 0;
return (
profile.orientation_score != null &&
scoredWorkCount > 0 &&
scoredWorkCount <= LOW_SAMPLE_MAX_WORKS
);
}
lowScoreSampleTooltip(profile: AuthorOrientationProfile): string {
const scoredWorkCount = profile.scored_work_count ?? 0;
const publicationLabel =
scoredWorkCount === 1
? 'einer Publikation'
: `${scoredWorkCount} Publikationen`;
return `Der Orientierungsscore basiert auf nur ${publicationLabel} und ist daher nur eingeschränkt aussagekräftig.`;
}
hasCategoryData(profile: AuthorOrientationProfile): boolean {
return Object.values(profile.primary_category_counts ?? {}).some(
(count) => count > 0,
);
}
categoryStatusLabel(profile: AuthorOrientationProfile): string {
if (profile.status === AuthorOrientationProfileStatus.restricted) {
return 'Forschungsprofil nicht verfügbar';
}
if (
profile.status ===
AuthorOrientationProfileStatus.no_classified_publications
) {
return 'Keine klassifizierten Publikationen';
}
return 'Keine Kategoriedaten verfügbar';
}
}
@@ -0,0 +1,14 @@
export const AUTHOR_COLORS = ['#1565c0', '#e6550d', '#2ca02c', '#9467bd'];
export const SUBFIELD_COLORS = [
'#2563eb',
'#16a34a',
'#d97706',
'#7c3aed',
'#0891b2',
'#db2777',
'#65a30d',
'#b45309',
];
export const OTHER_COLOR = '#9ca3af';
@@ -97,6 +97,11 @@
<p class="compare-hint">Keine Daten für das Themenprofil.</p>
}
</section>
<app-author-research-profile
[authors]="researchProfileAuthors()"
[profiles]="orientationProfiles()"
[loading]="orientationProfilesLoading()" />
}
</div>
@@ -6,6 +6,8 @@ import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import {
AuthorOrientationProfile,
AuthorOrientationProfilesRequest,
AuthorStaticStats,
AuthorTopicProfile,
AuthorTopicStats,
@@ -13,19 +15,16 @@ import {
RankingService,
SelectedAuthorsRequest,
} from '../../api';
import {
AuthorResearchProfileComponent,
ResearchProfileAuthor,
} from './author-research-profile/author-research-profile.component';
import {
AUTHOR_COLORS,
OTHER_COLOR,
SUBFIELD_COLORS,
} from './compare-authors-colors';
const AUTHOR_COLORS = ['#1565c0', '#e6550d', '#2ca02c', '#9467bd'];
const SUBFIELD_COLORS = [
'#2563eb',
'#16a34a',
'#d97706',
'#7c3aed',
'#0891b2',
'#db2777',
'#65a30d',
'#b45309',
];
const OTHER_COLOR = '#9ca3af';
const SUBFIELD_LIMIT = 5;
interface AuthorSummary {
@@ -110,7 +109,13 @@ interface SegmentDef {
@Component({
selector: 'app-compare-authors',
standalone: true,
imports: [DecimalPipe, NgTemplateOutlet, MatIconModule, NgxEchartsDirective],
imports: [
DecimalPipe,
NgTemplateOutlet,
MatIconModule,
NgxEchartsDirective,
AuthorResearchProfileComponent,
],
templateUrl: './compare-authors.component.html',
styleUrl: './compare-authors.component.scss',
})
@@ -129,7 +134,9 @@ export class CompareAuthorsComponent implements OnInit {
readonly staticStats = signal<AuthorStaticStats[]>([]);
// section 3: topic profile over ALL works of each author
readonly profile = signal<AuthorTopicProfile[]>([]);
readonly orientationProfiles = signal<AuthorOrientationProfile[]>([]);
readonly profileLoading = signal(false);
readonly orientationProfilesLoading = signal(false);
readonly loading = signal(false);
// maps both sections onto one row per author, in the requested order
@@ -357,6 +364,14 @@ export class CompareAuthorsComponent implements OnInit {
.filter((p): p is AuthorTopicProfile => p !== undefined);
});
readonly researchProfileAuthors = computed<ResearchProfileAuthor[]>(() => {
return this.summary().map((author) => ({
authorId: author.authorId,
name: author.name,
color: author.color,
}));
});
// colours the author names on the chart axes like the legend chips
private authorAxisLabel(profiles: AuthorTopicProfile[]) {
const rich: Record<string, { color: string; fontWeight: number }> = {};
@@ -657,6 +672,11 @@ export class CompareAuthorsComponent implements OnInit {
publication_types: publication_types,
timespan: timespan,
};
const orientationRequest: AuthorOrientationProfilesRequest = {
author_ids: fullIds,
publication_types: publication_types,
timespan: timespan,
};
// section 1: topic-filtered works stats
this.loading.set(true);
@@ -698,6 +718,23 @@ export class CompareAuthorsComponent implements OnInit {
this.staticStats.set([]);
},
});
if (fullIds.length >= 2) {
this.orientationProfilesLoading.set(true);
this.rankingService
.orientationProfilesApiRankOrientationProfilesPost(orientationRequest)
.subscribe({
next: (results) => {
this.orientationProfiles.set(results);
this.orientationProfilesLoading.set(false);
},
error: (error) => {
console.error(error);
this.orientationProfiles.set([]);
this.orientationProfilesLoading.set(false);
},
});
}
}
private parseList(raw: string): string[] {
@@ -44,6 +44,14 @@ export interface BmbfProjectStatusStatistics {
completed: number;
}
export interface DfgProjectStatusStatistics {
institution_id: string;
organization_name: string;
ongoing: number;
upcoming: number;
completed: number;
}
export interface DfgProjectTopic {
id: string;
name: string;
@@ -149,6 +157,15 @@ export class DashboardStatisticsService {
);
}
getDfgProjectStatuses(
period: DashboardPeriodBounds = {},
): Observable<DfgProjectStatusStatistics> {
return this.httpClient.get<DfgProjectStatusStatistics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/status`,
{ params: this.periodParams(period) },
);
}
getBmbfProjectCount(
period: DashboardPeriodBounds = {},
): Observable<DashboardStatisticValue> {
@@ -165,20 +165,22 @@
@if (
euProjectStatusesLoading ||
bmbfProjectStatusesLoading ||
dfgProjectStatusesLoading ||
euProjectStatusesError ||
bmbfProjectStatusesError ||
(euProjectStatuses && bmbfProjectStatuses)
dfgProjectStatusesError ||
(euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses)
) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>Projektstatus nach Fördergeber</h2>
<p>
Laufende, kommende und abgeschlossene EU- und Bund-Projekte Ihrer
Organisation.
Laufende, kommende und abgeschlossene EU-, Bund- und DFG-Projekte
Ihrer Organisation.
</p>
</div>
@if (euProjectStatuses && bmbfProjectStatuses) {
@if (euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses) {
<div class="project-status-summary">
<span>
EU:
@@ -196,11 +198,23 @@
bmbfProjectStatuses.completed | number
}}
</span>
<span>
DFG:
{{
dfgProjectStatuses.ongoing +
dfgProjectStatuses.upcoming +
dfgProjectStatuses.completed | number
}}
</span>
</div>
}
</header>
@if (euProjectStatusesLoading || bmbfProjectStatusesLoading) {
@if (
euProjectStatusesLoading ||
bmbfProjectStatusesLoading ||
dfgProjectStatusesLoading
) {
<div class="project-status-loading" role="status" aria-live="polite">
<app-loading
text="Projektstatus wird geladen …"
@@ -208,14 +222,22 @@
size="64"
diameter="64"></app-loading>
</div>
} @else if (euProjectStatusesError || bmbfProjectStatusesError) {
} @else if (
euProjectStatusesError ||
bmbfProjectStatusesError ||
dfgProjectStatusesError
) {
<p class="statistics-error">
Der Status der EU- und Bund-Projekte konnte nicht geladen werden.
Der Status der EU-, Bund- und DFG-Projekte konnte nicht geladen
werden.
</p>
} @else if (euProjectStatuses && bmbfProjectStatuses) {
} @else if (
euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses
) {
<app-eu-project-status-chart
[statuses]="euProjectStatuses"
[bmbfStatuses]="bmbfProjectStatuses"></app-eu-project-status-chart>
[bmbfStatuses]="bmbfProjectStatuses"
[dfgStatuses]="dfgProjectStatuses"></app-eu-project-status-chart>
}
</section>
}
@@ -23,6 +23,7 @@ import {
DashboardStatisticValue,
DashboardStatistics,
DashboardStatisticsService,
DfgProjectStatusStatistics,
DfgProjectTopics,
EuProjectStatusStatistics,
TopAuthor,
@@ -101,6 +102,9 @@ export class DashboardComponent implements OnInit {
bmbfProjectStatuses?: BmbfProjectStatusStatistics;
bmbfProjectStatusesLoading = false;
bmbfProjectStatusesError = false;
dfgProjectStatuses?: DfgProjectStatusStatistics;
dfgProjectStatusesLoading = false;
dfgProjectStatusesError = false;
readonly topicTreemapMinYear = 1900;
readonly topicTreemapMaxYear = new Date().getFullYear();
dashboardPeriodMode: DashboardPeriodMode = 'all_time';
@@ -125,6 +129,7 @@ export class DashboardComponent implements OnInit {
this.loadDfgProjectTopics();
this.loadEuProjectStatuses();
this.loadBmbfProjectStatuses();
this.loadDfgProjectStatuses();
}
private loadStatistics(): void {
@@ -281,12 +286,17 @@ export class DashboardComponent implements OnInit {
}
onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
const period = this.selectedPeriodBounds();
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
TopicWordCloudDialogComponent,
{
width: '85vw',
maxWidth: '92vw',
data: topic,
data: {
...topic,
fromYear: period.fromYear,
toYear: period.toYear,
},
},
);
}
@@ -368,6 +378,7 @@ export class DashboardComponent implements OnInit {
this.loadDfgProjectTopics();
this.loadEuProjectStatuses();
this.loadBmbfProjectStatuses();
this.loadDfgProjectStatuses();
}
private loadStatistic(
@@ -479,6 +490,22 @@ export class DashboardComponent implements OnInit {
});
}
private loadDfgProjectStatuses(): void {
this.dfgProjectStatusesLoading = true;
this.dfgProjectStatusesError = false;
this.statisticsService
.getDfgProjectStatuses(this.selectedPeriodBounds())
.pipe(finalize(() => (this.dfgProjectStatusesLoading = false)))
.subscribe({
next: (statuses) => {
this.dfgProjectStatuses = statuses;
},
error: () => {
this.dfgProjectStatusesError = true;
},
});
}
private loadTopicTreemap(): void {
if (this.dashboardFromYear > this.dashboardToYear) {
this.topicTreemapLoading = false;
@@ -4,6 +4,7 @@ import { NgxEchartsDirective } from 'ngx-echarts';
import {
BmbfProjectStatusStatistics,
DfgProjectStatusStatistics,
EuProjectStatusStatistics,
} from '../dashboard-statistics.service';
@@ -16,6 +17,7 @@ import {
export class EuProjectStatusChartComponent implements OnChanges {
@Input({ required: true }) statuses!: EuProjectStatusStatistics;
@Input({ required: true }) bmbfStatuses!: BmbfProjectStatusStatistics;
@Input({ required: true }) dfgStatuses!: DfgProjectStatusStatistics;
options: EChartsOption = {};
@@ -23,12 +25,20 @@ export class EuProjectStatusChartComponent implements OnChanges {
const values = [
{
name: 'Laufend',
data: [this.statuses?.ongoing ?? 0, this.bmbfStatuses?.ongoing ?? 0],
data: [
this.statuses?.ongoing ?? 0,
this.bmbfStatuses?.ongoing ?? 0,
this.dfgStatuses?.ongoing ?? 0,
],
color: '#2563eb',
},
{
name: 'Kommend',
data: [this.statuses?.upcoming ?? 0, this.bmbfStatuses?.upcoming ?? 0],
data: [
this.statuses?.upcoming ?? 0,
this.bmbfStatuses?.upcoming ?? 0,
this.dfgStatuses?.upcoming ?? 0,
],
color: '#f59e0b',
},
{
@@ -36,6 +46,7 @@ export class EuProjectStatusChartComponent implements OnChanges {
data: [
this.statuses?.completed ?? 0,
this.bmbfStatuses?.completed ?? 0,
this.dfgStatuses?.completed ?? 0,
],
color: '#64748b',
},
@@ -69,7 +80,7 @@ export class EuProjectStatusChartComponent implements OnChanges {
},
yAxis: {
type: 'category',
data: ['EU-Projekte', 'Bund-Projekte'],
data: ['EU-Projekte', 'Bund-Projekte', 'DFG-Projekte'],
axisTick: { show: false },
axisLine: { show: false },
axisLabel: { color: '#334155', fontWeight: 600 },
@@ -91,16 +91,100 @@
<span>Die Keywords konnten nicht geladen werden.</span>
</div>
} @else if (words.length) {
<div class="keyword-toolbar" aria-label="Ausgewählte Keywords">
<div class="keyword-toolbar-label">
<mat-icon aria-hidden="true">tune</mat-icon>
<span>
<strong>Keyword-Auswahl</strong>
<small
>Klicken Sie auf Begriffe in der Wordcloud, um sie
auszuwählen.</small
>
</span>
</div>
<div class="keyword-selection" aria-live="polite">
@for (word of selectedWords(); track word.id) {
<button
type="button"
class="keyword-chip"
[attr.aria-label]="word.name + ' aus Auswahl entfernen'"
(click)="toggleWord(word)">
{{ word.name }}
<mat-icon aria-hidden="true">close</mat-icon>
</button>
} @empty {
<span class="keyword-selection-empty">Noch nichts ausgewählt</span>
}
</div>
<div class="keyword-toolbar-actions">
@if (selectedWordIds.size) {
<button
mat-button
type="button"
class="keyword-clear"
(click)="clearSelection()">
Auswahl löschen
</button>
}
<a
mat-stroked-button
class="keyword-search keyword-search--secondary"
routerLink="/keywords"
[queryParams]="{
manual: selectedWordsQuery(),
selected: selectedWordsQuery(),
}"
[class.keyword-search--disabled]="!selectedWordIds.size"
[attr.aria-disabled]="!selectedWordIds.size"
[attr.tabindex]="selectedWordIds.size ? 0 : -1"
(click)="
!selectedWordIds.size
? $event.preventDefault()
: closeForSearchNavigation()
">
<mat-icon aria-hidden="true">manage_search</mat-icon>
Suche in Keywords
</a>
<a
mat-flat-button
class="keyword-search"
routerLink="/topics"
[queryParams]="{
query: selectedWordNames(),
page: 0,
sortBy: 'works_count',
sortDirection: 'desc',
}"
[class.keyword-search--disabled]="!selectedWordIds.size"
[attr.aria-disabled]="!selectedWordIds.size"
[attr.tabindex]="selectedWordIds.size ? 0 : -1"
(click)="
!selectedWordIds.size
? $event.preventDefault()
: closeForSearchNavigation()
">
<mat-icon aria-hidden="true">search</mat-icon>
Suche in Themen
</a>
</div>
</div>
<div class="word-cloud-chart" aria-label="Wordcloud verwandter Themen">
@for (word of words; track word.id) {
<span
<button
type="button"
class="word-cloud-word"
[class.word-cloud-word--selected]="isWordSelected(word)"
[attr.aria-pressed]="isWordSelected(word)"
[style.color]="word.color"
[style.fontSize.px]="word.fontSize"
[style.fontWeight]="word.fontWeight"
[title]="word.name + ': ' + word.count + ' Publikationen'">
[title]="word.name + ': ' + word.count + ' Publikationen'"
(click)="toggleWord(word)">
{{ word.name }}
</span>
</button>
}
</div>
} @else {
@@ -187,6 +187,113 @@ mat-dialog-content {
font-weight: 700;
}
.keyword-toolbar {
display: grid;
grid-template-columns: auto minmax(160px, 1fr) auto;
align-items: center;
gap: 14px;
padding: 10px 14px;
border-bottom: 1px solid #e8edf5;
background: #f8faff;
}
.keyword-toolbar-label {
display: flex;
align-items: center;
gap: 8px;
color: #334155;
> mat-icon {
width: 19px;
height: 19px;
color: #7255d9;
font-size: 19px;
}
> span {
display: flex;
flex-direction: column;
gap: 1px;
}
strong {
font-size: 0.75rem;
}
small {
color: var(--sg-text-muted, #64708f);
font-size: 0.6875rem;
}
}
.keyword-selection {
display: flex;
min-width: 0;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.keyword-chip {
display: inline-flex;
min-height: 28px;
align-items: center;
gap: 4px;
padding: 4px 7px 4px 9px;
border: 1px solid #c9bafa;
border-radius: 999px;
background: #f6f0ff;
color: #6347c8;
cursor: pointer;
font: inherit;
font-size: 0.6875rem;
font-weight: 600;
mat-icon {
width: 14px;
height: 14px;
font-size: 14px;
}
&:hover {
border-color: #a992ef;
background: #eee7ff;
}
}
.keyword-selection-empty {
color: var(--sg-text-soft, #8a95b3);
font-size: 0.75rem;
font-style: italic;
}
.keyword-clear {
white-space: nowrap;
}
.keyword-toolbar-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 4px;
white-space: nowrap;
}
.keyword-search {
mat-icon {
margin-right: 5px;
}
}
.keyword-search--secondary {
background: #ffffff;
}
.keyword-search--disabled {
pointer-events: none;
opacity: 0.45;
}
.word-cloud-chart {
display: flex;
min-height: 280px;
@@ -211,9 +318,13 @@ mat-dialog-content {
}
.word-cloud-word {
appearance: none;
padding: 3px 5px;
border: 1px solid transparent;
border-radius: 6px;
cursor: help;
background: transparent;
cursor: pointer;
font-family: inherit;
line-height: 1.1;
text-align: center;
transition:
@@ -224,6 +335,18 @@ mat-dialog-content {
background: rgba(241, 243, 247, 0.9);
transform: translateY(-2px);
}
&:focus-visible {
outline: 3px solid rgba(114, 85, 217, 0.25);
outline-offset: 2px;
}
}
.word-cloud-word--selected {
border-color: currentColor;
background: #ffffff;
box-shadow: 0 2px 8px rgba(51, 65, 85, 0.16);
transform: translateY(-2px);
}
.word-cloud-state {
@@ -303,6 +426,20 @@ mat-dialog-content {
gap: 10px 14px;
padding: 24px 18px;
}
.keyword-toolbar {
grid-template-columns: 1fr auto;
}
.keyword-toolbar-actions {
grid-column: 2;
grid-row: 1;
}
.keyword-selection {
grid-column: 1 / -1;
grid-row: 2;
}
}
@media (prefers-reduced-motion: reduce) {
@@ -1,9 +1,14 @@
import { CommonModule } from '@angular/common';
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { RouterLink } from '@angular/router';
import {
DashboardStatisticsService,
@@ -28,16 +33,26 @@ interface DisplayWord extends TopicWordCloudWord {
@Component({
selector: 'app-topic-wordcloud-dialog',
standalone: true,
imports: [CommonModule, MatButtonModule, MatDialogModule, MatIconModule],
imports: [
CommonModule,
MatButtonModule,
MatDialogModule,
MatIconModule,
RouterLink,
],
templateUrl: './topic-wordcloud-dialog.component.html',
styleUrl: './topic-wordcloud-dialog.component.scss',
})
export class TopicWordCloudDialogComponent {
readonly data = inject<TopicWordCloudDialogData>(MAT_DIALOG_DATA);
private readonly dialogRef = inject(
MatDialogRef<TopicWordCloudDialogComponent>,
);
private readonly statisticsService = inject(DashboardStatisticsService);
private readonly destroyRef = inject(DestroyRef);
words: DisplayWord[] = [];
selectedWordIds = new Set<string>();
loading = true;
loadFailed = false;
@@ -74,6 +89,42 @@ export class TopicWordCloudDialogComponent {
});
}
toggleWord(word: DisplayWord): void {
const selected = new Set(this.selectedWordIds);
if (selected.has(word.id)) {
selected.delete(word.id);
} else {
selected.add(word.id);
}
this.selectedWordIds = selected;
}
isWordSelected(word: DisplayWord): boolean {
return this.selectedWordIds.has(word.id);
}
selectedWords(): DisplayWord[] {
return this.words.filter((word) => this.selectedWordIds.has(word.id));
}
selectedWordsQuery(): string {
return this.selectedWordNames().join(', ');
}
selectedWordNames(): string[] {
return this.selectedWords().map((word) => word.name);
}
clearSelection(): void {
this.selectedWordIds = new Set<string>();
}
closeForSearchNavigation(): void {
if (this.selectedWordIds.size) {
this.dialogRef.close();
}
}
private buildWords(words: TopicWordCloudWord[]): DisplayWord[] {
if (!words.length) return [];
const values = words.map((word) => word.count);
@@ -41,5 +41,9 @@ export class KeywordsToProjectsResultsComponent {
path: 'eu',
label: 'EU-Projekte',
},
{
path: 'bund',
label: 'BUND-Projekte',
},
];
}
@@ -69,6 +69,7 @@
keywords: state.payload()?.keywords?.join(','),
fuzzy: state.payload()?.options?.fuzzy,
topics: state.payload()?.options?.fuzzy ? state.topicIds() : null,
topicId: null,
}"
queryParamsHandling="replace">
<mat-icon>{{ route.icon }}</mat-icon>
@@ -27,9 +27,5 @@ export class PersonProjectsComponent {
path: 'eu',
label: 'EU-Projekte',
},
{
path: 'bund',
label: 'Bund-Projekte',
},
];
}
@@ -64,6 +64,7 @@
<div class="metric-content">
<strong>{{
getFundingStatus(bundProject.funding_end_date)
| date: 'dd.MM.yyyy'
}}</strong>
<span>Förderende</span>
</div>
@@ -112,6 +113,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 =============
}
@@ -32,11 +32,8 @@
Orientierungsscore
</h3>
<div class="score-content">
<div echarts class="score-chart" [options]="scoreOptions()"></div>
<div class="score-labels" aria-hidden="true">
<span>Grundlagenorientiert</span>
<span>Anwendungsorientiert</span>
</div>
<app-orientation-gauge
[score]="profile.applied_orientation_score ?? null" />
@if (profile.primary_category; as category) {
<app-topic-chip
[label]="category | workPrimaryCategory"
@@ -10,18 +10,18 @@
}
.profile-header {
align-items: flex-start;
align-items: center;
padding: 22px 24px 12px;
}
.profile-icon {
flex: 0 0 24px;
width: 24px;
height: 24px;
margin: 1px 12px 0 0;
flex: 0 0 30px;
width: 30px;
height: 30px;
margin: 0 12px 0 0;
color: var(--sg-text-muted);
font-size: 24px;
line-height: 24px;
font-size: 30px;
line-height: 30px;
}
.profile-heading {
@@ -97,22 +97,6 @@ mat-card-content {
padding-bottom: 22px;
}
.score-chart {
width: 100%;
max-width: 280px;
height: 180px;
}
.score-labels {
display: flex;
justify-content: space-between;
width: min(100%, 280px);
margin-top: -36px;
color: var(--sg-text-muted);
font-size: 11px;
font-weight: 600;
}
.score-content app-topic-chip {
margin-top: 24px;
max-width: 100%;
@@ -18,6 +18,7 @@ import {
WorkPrimaryCategory,
} from '../../../api';
import { WorkPrimaryCategoryPipe } from '../../../shared/pipes/work-primary-category.pipe';
import { OrientationGaugeComponent } from '../../../shared/ui/orientation-gauge/orientation-gauge.component';
import {
TopicChipComponent,
TopicChipPaletteColor,
@@ -81,6 +82,7 @@ const LOW_CONFIDENCE_TOKENS = topicChipColorTokens('pink');
MatIconModule,
MatTooltipModule,
NgxEchartsDirective,
OrientationGaugeComponent,
TopicChipComponent,
WorkPrimaryCategoryPipe,
],
@@ -110,10 +112,6 @@ export class ResearchProfileComponent {
this.buildQuadrantOptions(this.details()?.pasteur_quadrant),
);
scoreOptions = computed<EChartsOption>(() =>
this.buildScoreOptions(this.details()?.applied_orientation_score ?? 0),
);
primaryCategoryChipColor = computed<TopicChipPaletteColor>(() => {
switch (this.details()?.primary_category) {
case WorkPrimaryCategory.BasicResearch:
@@ -367,48 +365,6 @@ export class ResearchProfileComponent {
};
}
private buildScoreOptions(score: number): EChartsOption {
const boundedScore = Math.max(0, Math.min(100, score));
const textColor = this.cssColor('--sg-text', BLUE_TOKENS.color);
return {
animation: false,
series: [
{
type: 'gauge',
min: 0,
max: 100,
startAngle: 180,
endAngle: 0,
center: ['50%', '70%'],
radius: '92%',
progress: {
show: true,
width: 13,
itemStyle: { color: BLUE_TOKENS.color },
},
axisLine: {
lineStyle: { width: 13, color: [[1, BLUE_TOKENS.background]] },
},
pointer: { show: false },
axisTick: { show: false },
splitLine: { show: false },
axisLabel: { show: false },
anchor: { show: false },
title: { show: false },
detail: {
valueAnimation: false,
offsetCenter: [0, '-8%'],
color: textColor,
fontSize: 25,
fontWeight: 700,
formatter: '{value}',
},
data: [{ value: boundedScore }],
},
],
};
}
private cssColor(variable: string, fallback: string): string {
if (typeof getComputedStyle !== 'function') {
return fallback;
@@ -24,6 +24,7 @@ export class TopicsComponent {
id: 'query',
queryParamKey: topicQueryParamKeys.query,
icon: 'search',
removable: true,
},
];
@@ -1,9 +1,19 @@
<div class="pie-chart-holder">
@if (chartTitle()) {
<div class="pie-chart-header">
<h4 class="pie-chart-title">{{ chartTitle() }}</h4>
<span class="pie-chart-subtext">{{ chartSubtext() }}</span>
</div>
}
@if (loading()) {
<div class="pie-loader-overlay">
<mat-spinner diameter="35"></mat-spinner>
<span class="pie-loader-text">Lade Daten...</span>
</div>
}
<div echarts [options]="chartOptions()" class="pie-chart-container"></div>
<div
echarts
[options]="chartOptions()"
[autoResize]="true"
class="pie-chart-container"></div>
</div>
@@ -4,17 +4,40 @@
background: white;
border: 1px solid #d7e4ff;
border-radius: 16px;
padding: 16px;
padding: 1.25rem;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
box-sizing: border-box;
width: 100%;
height: 380px;
min-height: clamp(420px, 48vh, 580px);
position: relative;
}
.pie-chart-header {
text-align: center;
margin-bottom: 0.25rem;
z-index: 1;
.pie-chart-title {
font-size: 0.95rem;
font-weight: 600;
color: #1f2937;
margin: 0;
line-height: 1.3;
}
.pie-chart-subtext {
display: block;
font-size: 0.75rem;
color: #6b7280;
margin-top: 2px;
}
}
.pie-chart-container {
flex: 1;
width: 100%;
height: 100%;
min-height: 0;
}
.pie-loader-overlay {
@@ -36,6 +36,21 @@ export class UniPieChartComponent {
readonly pieData = input<{ value: number; name: string }[] | null>(null);
readonly loading = input<boolean>(false);
readonly error = input<boolean>(false);
readonly chartTitle = computed<string>(() => {
if (this.pieData() !== null) {
return this.titleText() ?? 'Themenverteilung';
}
return (
this.titleText() ??
(this.entityName()
? `Verteilung: ${this.entityName()}`
: 'Themenverteilung')
);
});
readonly chartSubtext = computed<string>(() => {
return `Zeitraum: ${this.startYear()} - ${this.endYear()}`;
});
private resolveTopicColorTokens(topic: string) {
if (topic === 'Andere Themen') {
@@ -80,8 +95,6 @@ export class UniPieChartComponent {
const endYr = this.endYear();
let pieDataList: any[] = [];
let title = '';
let subtext = `Zeitraum: ${startYr} - ${endYr}`;
// 3. If direct pieData input is provided, use it
const directData = this.pieData();
@@ -99,7 +112,6 @@ export class UniPieChartComponent {
},
};
});
title = this.titleText() ?? 'Themenverteilung';
} else {
// Otherwise, filter and extract from TrendResponse
const trendData = this.data();
@@ -151,8 +163,6 @@ export class UniPieChartComponent {
});
}
});
title = this.titleText() ?? `Verteilung: ${this.entityName()}`;
}
if (pieDataList.length === 0) {
@@ -167,21 +177,6 @@ export class UniPieChartComponent {
}
return {
title: {
text: title,
subtext: subtext,
left: 'center',
top: 10,
textStyle: {
fontSize: 13,
fontWeight: 600,
color: '#1f2937',
},
subtextStyle: {
fontSize: 10,
color: '#6b7280',
},
},
tooltip: {
trigger: 'item',
formatter: '{b}: <strong>{c}</strong> ({d}%)',
@@ -193,10 +188,9 @@ export class UniPieChartComponent {
{
name: 'Themenverteilung',
type: 'pie',
radius: ['45%', '75%'],
radius: ['38%', '76%'],
center: ['50%', '50%'],
avoidLabelOverlap: true,
top: 40,
bottom: 10,
itemStyle: {
borderRadius: 6,
borderColor: '#fff',
@@ -205,14 +199,15 @@ export class UniPieChartComponent {
label: {
show: true,
position: 'outside',
fontSize: 9,
fontSize: 10,
fontWeight: 500,
formatter: '{b}: {d}%',
color: '#374151',
},
labelLine: {
show: true,
length: 8,
length2: 5,
length: 12,
length2: 8,
smooth: true,
},
emphasis: {
@@ -225,7 +220,7 @@ export class UniPieChartComponent {
},
label: {
show: true,
fontSize: 10,
fontSize: 11,
fontWeight: 'bold',
},
},
@@ -77,6 +77,11 @@ export class UniTrendChartComponent {
];
const getFn = this.getEntityColor();
// Find index of first visible series for markLine zero baseline attachment
const firstVisibleIdx = trendData.series.findIndex(
(s) => (s as any).visible !== false,
);
// Build series: Line in top grid, growth volume bars and S-Curve in bottom grid
trendData.series.forEach((entity, entityIdx) => {
const rawColor = getFn
@@ -146,7 +151,7 @@ export class UniTrendChartComponent {
color: color,
},
markLine:
entityIdx === 0
entityIdx === firstVisibleIdx
? {
silent: true,
symbol: 'none',
@@ -421,7 +426,11 @@ export class UniTrendChartComponent {
return value > 0 ? `+${value}` : `${value}`;
},
},
axisLine: { show: false },
axisLine: {
show: true,
onZero: true,
lineStyle: { color: '#9ca3af', width: 1 },
},
axisTick: { show: false },
splitLine: {
show: true,
@@ -195,8 +195,8 @@
.pie-charts-row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 1.25rem;
grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
gap: 1.5rem;
width: 100%;
box-sizing: border-box;
}
@@ -8,7 +8,9 @@ import {
untracked,
inject,
OnInit,
DestroyRef,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import {
@@ -202,6 +204,8 @@ export class UniTrendParentComponent implements OnInit {
]);
readonly comparisonRegions = signal<CompareItem[]>([]);
readonly comparisonAuthors = signal<CompareItem[]>([]);
readonly hasUserClearedInstitutions = signal<boolean>(false);
readonly hasUserClearedAuthors = signal<boolean>(false);
readonly startYear = signal<number>(2010);
readonly endYear = signal<number>(2025);
readonly chartMode = signal<'normalized' | 'total' | 'cumulative'>(
@@ -583,14 +587,16 @@ export class UniTrendParentComponent implements OnInit {
}
isVisible(id: string): boolean {
return this.entityVisibilityMap().get(id) !== false;
const clean = this.cleanEntityId(id);
return this.entityVisibilityMap().get(clean) !== false;
}
toggleVisibility(id: string): void {
const clean = this.cleanEntityId(id);
this.entityVisibilityMap.update((map) => {
const newMap = new Map(map);
const current = newMap.get(id) !== false;
newMap.set(id, !current);
const current = newMap.get(clean) !== false;
newMap.set(clean, !current);
return newMap;
});
}
@@ -791,13 +797,26 @@ export class UniTrendParentComponent implements OnInit {
topics.forEach((topicName, idx) => {
const mappedName = this.getMappedTopic(topicName);
let matchKey = rawTopicKeys.find(
(rk) =>
rk.toLowerCase() === topicName.toLowerCase() ||
rk.toLowerCase() === mappedName.toLowerCase() ||
rk.toLowerCase().includes(topicName.toLowerCase()) ||
rk.toLowerCase().includes(mappedName.toLowerCase()),
);
const topicLower = topicName.toLowerCase().trim();
const mappedLower = mappedName.toLowerCase().trim();
let matchKey = rawTopicKeys.find((rk) => {
const rkLower = rk.toLowerCase().trim();
const rkClean = rkLower.includes('/')
? rkLower.split('/').pop()!
: rkLower.startsWith('news_topic_')
? rkLower.slice('news_topic_'.length)
: rkLower;
return (
rkLower === topicLower ||
rkLower === mappedLower ||
rkClean === topicLower ||
rkClean === mappedLower ||
rkLower.includes(topicLower) ||
rkLower.includes(mappedLower)
);
});
if (!matchKey && rawTopicKeys[idx]) {
matchKey = rawTopicKeys[idx];
@@ -912,7 +931,7 @@ export class UniTrendParentComponent implements OnInit {
this.availableYears.push(y);
}
this.router.events.subscribe((event) => {
this.router.events.pipe(takeUntilDestroyed()).subscribe((event) => {
if (event instanceof ResolveStart) {
this.isPageResolving.set(true);
} else if (event instanceof ResolveEnd) {
@@ -921,7 +940,7 @@ export class UniTrendParentComponent implements OnInit {
});
// Subscribe to route resolver data
this.route.data.subscribe((data) => {
this.route.data.pipe(takeUntilDestroyed()).subscribe((data) => {
if (data['trendData']) {
const resolved = data['trendData'];
const res = resolved.trendResponse ?? resolved;
@@ -1041,15 +1060,21 @@ export class UniTrendParentComponent implements OnInit {
);
}
// If comparison list is empty, initialize default institutions/authors dynamically
// If comparison list is empty, initialize default institutions/authors dynamically (unless explicitly cleared by user)
if (searchType === 'authors') {
const currentAuthors = untracked(() => this.comparisonAuthors());
if (currentAuthors.length === 0) {
if (
currentAuthors.length === 0 &&
!untracked(() => this.hasUserClearedAuthors())
) {
untracked(() => this.initializeDefaultAuthors());
}
} else {
const currentInsts = untracked(() => this.comparisonInstitutions());
if (currentInsts.length === 0) {
if (
currentInsts.length === 0 &&
!untracked(() => this.hasUserClearedInstitutions())
) {
untracked(() => this.initializeDefaultInstitutions());
}
}
@@ -1150,7 +1175,7 @@ export class UniTrendParentComponent implements OnInit {
});
// Handle initialization and synchronization of URL state
this.route.queryParams.subscribe((params) => {
this.route.queryParams.pipe(takeUntilDestroyed()).subscribe((params) => {
let hasInstsFromUrl = false;
if (params['search_type']) {
this.selectedSearchType.set(params['search_type'] as any);
@@ -1183,8 +1208,12 @@ export class UniTrendParentComponent implements OnInit {
}
}
// If URL didn't specify institutions and list is currently empty, initialize defaults
if (!hasInstsFromUrl && this.comparisonInstitutions().length === 0) {
// If URL didn't specify institutions and list is currently empty, initialize defaults (unless user explicitly cleared them)
if (
!hasInstsFromUrl &&
this.comparisonInstitutions().length === 0 &&
!this.hasUserClearedInstitutions()
) {
this.initializeDefaultInstitutions();
}
@@ -1798,15 +1827,14 @@ export class UniTrendParentComponent implements OnInit {
// Add comparison institution
addInstitution(id: string, name: string) {
const cleanId = id.includes('/') ? id.split('/').pop() || id : id;
const cleanId = this.cleanEntityId(id);
const current = this.comparisonInstitutions();
const exists = current.some((i: CompareItem) => {
const itemClean = i.id.includes('/')
? i.id.split('/').pop() || i.id
: i.id;
const itemClean = this.cleanEntityId(i.id);
return itemClean.toLowerCase() === cleanId.toLowerCase();
});
if (!exists) {
this.hasUserClearedInstitutions.set(false);
this.comparisonInstitutions.set([...current, { id: cleanId, name }]);
this.updateUrlParams();
}
@@ -1815,10 +1843,15 @@ export class UniTrendParentComponent implements OnInit {
}
removeInstitution(id: string) {
const cleanTarget = this.cleanEntityId(id);
const current = this.comparisonInstitutions();
this.comparisonInstitutions.set(
current.filter((i: CompareItem) => i.id !== id),
const updated = current.filter(
(i: CompareItem) => this.cleanEntityId(i.id) !== cleanTarget,
);
if (updated.length === 0) {
this.hasUserClearedInstitutions.set(true);
}
this.comparisonInstitutions.set(updated);
this.updateUrlParams();
}
@@ -1888,17 +1921,20 @@ export class UniTrendParentComponent implements OnInit {
const current = this.comparisonAuthors();
const updated = [...current];
(res.results || []).forEach((author: any) => {
const shortId =
author.id && author.id.includes('/')
? author.id.split('/').pop() || author.id
: author.id;
if (shortId && !updated.some((a) => a.id === shortId)) {
const shortId = this.cleanEntityId(author.id);
if (
shortId &&
!updated.some((a) => this.cleanEntityId(a.id) === shortId)
) {
updated.push({
id: shortId,
name: author.display_name || 'Unbekannt',
});
}
});
if (updated.length > 0) {
this.hasUserClearedAuthors.set(false);
}
this.comparisonAuthors.set(updated);
this.isSuggestionsLoading.set(false);
this.updateUrlParams();
@@ -1914,17 +1950,25 @@ export class UniTrendParentComponent implements OnInit {
}
addAuthor(id: string, name: string) {
const shortId = id.includes('/') ? id.split('/').pop() || id : id;
const shortId = this.cleanEntityId(id);
const current = this.comparisonAuthors();
if (!current.some((a) => a.id === shortId)) {
if (!current.some((a) => this.cleanEntityId(a.id) === shortId)) {
this.hasUserClearedAuthors.set(false);
this.comparisonAuthors.set([...current, { id: shortId, name }]);
this.updateUrlParams();
}
}
removeAuthor(id: string) {
const cleanTarget = this.cleanEntityId(id);
const current = this.comparisonAuthors();
this.comparisonAuthors.set(current.filter((a: CompareItem) => a.id !== id));
const updated = current.filter(
(a: CompareItem) => this.cleanEntityId(a.id) !== cleanTarget,
);
if (updated.length === 0) {
this.hasUserClearedAuthors.set(true);
}
this.comparisonAuthors.set(updated);
this.updateUrlParams();
}
@@ -11,7 +11,7 @@ export const bundProjectQueryParamKeys = {
size: 'size',
title: 'title',
authorId: 'authorId',
funding_art: 'funding_art',
funding_type: 'funding_type',
institutionId: 'institutionId',
funding_start: 'funding_start',
funding_end: 'funding_end',
@@ -20,13 +20,15 @@ export const bundProjectQueryParamKeys = {
sortDirection: 'sort_direction',
legend: 'legend',
legend_expanded: 'legend_expanded',
keywords: 'keywords',
topics: 'topics',
agency: 'agency',
} as const;
export const bundProjectsResolver: ResolveFn<BundProjectPage> = (
route,
state,
) => {
console.log('bundProjectsResolver called with route:', route);
const page = route.queryParamMap.get(bundProjectQueryParamKeys.page) ?? '0';
const size = route.queryParamMap.get(bundProjectQueryParamKeys.size) ?? '10';
const institutionIds = route.queryParamMap.getAll(
@@ -38,34 +40,43 @@ export const bundProjectsResolver: ResolveFn<BundProjectPage> = (
const fundingEndYears = route.queryParamMap.getAll(
bundProjectQueryParamKeys.funding_end,
);
const topicIds = route.queryParamMap.get(bundProjectQueryParamKeys.topicId);
const fundingArts = route.queryParamMap.getAll(
bundProjectQueryParamKeys.funding_art,
const keywords =
route.queryParamMap.get(bundProjectQueryParamKeys.keywords)?.split(',') ||
[];
const topicIds = route.queryParamMap.getAll(
bundProjectQueryParamKeys.topicId,
);
const topics = route.queryParamMap.getAll(bundProjectQueryParamKeys.topics);
const fundingType = route.queryParamMap.getAll(
bundProjectQueryParamKeys.funding_type,
);
const sortBy = (route.queryParamMap.get(bundProjectQueryParamKeys.sortBy) ||
'title') as ProjectsSortBy;
const sortDirection = (route.queryParamMap.get(
bundProjectQueryParamKeys.sortDirection,
) || 'asc') as SortDirection;
const fuzzySearch = route.queryParamMap.get('fuzzy') === 'true';
const search =
route.queryParamMap.get(bundProjectQueryParamKeys.title) || undefined;
const executingAgency = route.queryParamMap.getAll(
bundProjectQueryParamKeys.agency,
);
return inject(ProjectsService).searchBundProjectsWithFilters(
institutionIds,
fundingArts,
executingAgency,
fundingType,
search,
[],
[],
[],
keywords,
topics,
topicIds,
fundingStartYears,
fundingEndYears,
[],
[],
institutionIds,
Number(page),
Number(size),
sortBy,
sortDirection,
false,
fuzzySearch,
);
};
@@ -0,0 +1,15 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { BUNDInstitutionsService } from '../api';
import { BundInstitutionSummaryPage } from '../api/model/bundInstitutionSummaryPage';
export const selectedBundInstitutionsResolver: ResolveFn<
BundInstitutionSummaryPage
> = (route, state) => {
const agencyNameQueryParamKey =
(route.data['institutionIdQueryParamKey'] as string) || 'agency';
const agencies = route.queryParamMap.getAll(agencyNameQueryParamKey);
return inject(BUNDInstitutionsService).getBundInstitutionsByName(agencies);
};
@@ -16,7 +16,13 @@ export const topicQueryParamKeys = {
} as const;
export const topicPageResolver: ResolveFn<TopicPageV2> = (route, state) => {
const query = route.queryParamMap.get(topicQueryParamKeys.query) || undefined;
const query =
route.queryParamMap
.getAll(topicQueryParamKeys.query)
.flatMap((value) => value.split(','))
.map((value) => value.trim())
.filter(Boolean)
.join(', ') || undefined;
const page = Number(route.queryParamMap.get(topicQueryParamKeys.page) ?? '0');
const size = Number(
route.queryParamMap.get(topicQueryParamKeys.size) ?? '10',
@@ -109,8 +109,17 @@ export class AuthorSelectorComponent {
this.toggleVisibility.emit(id);
}
private cleanId(id: string | undefined): string {
if (!id) return '';
const lower = id.toLowerCase().trim();
return lower.includes('/') ? lower.split('/').pop()! : lower;
}
isAlreadyAdded(id: string | undefined): boolean {
if (!id) return false;
return this.comparisonAuthors().some((i) => i.id === id);
const cleanTarget = this.cleanId(id);
return this.comparisonAuthors().some(
(i) => this.cleanId(i.id) === cleanTarget,
);
}
}
@@ -6,21 +6,25 @@
<app-query-param-paginator
[total]="total()"
[queryParamPageKey]="queryParamKeys.page"
[queryParamSizeKey]="queryParamKeys.size"
[pageSizeOptions]="[10]" />
queryParamPageKey="page"
queryParamSizeKey="size"
[pageSizeOptions]="[10, 25, 50]" />
<ng-template #fundingStartTmp let-element>
{{ getStartDate(element) | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #fundingEndTmp let-element>
{{
element.funding_end == '2999' || element.funding_end == null
? 'laufend'
: element.funding_end
}}
{{ getEndDate(element) | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #fundingAmountTmp let-element>
{{ getFundingAmount(element) | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }}
</ng-template>
<ng-template #actionsTmp let-element>
<a
[routerLink]="['/projects/dfg', element.id]"
[routerLink]="['/projects/bund', element.funding_code]"
target="_blank"
mat-icon-button
color="primary">
@@ -42,43 +46,6 @@
</div>
</ng-template>
<!-- <ng-template #authorsTmp let-project>
@let projectAuthors = getProjectAuthors(project);
@let isProjectAuthorsExpanded = isProjectPersonsExpanded(project);
@let visibleAuthors =
isProjectAuthorsExpanded ? projectAuthors : projectAuthors.slice(0, 3); -->
<!-- <div class="author-tags" aria-label="Autoren" style="padding: 0.5rem 0">
@for (author of visibleAuthors; track author.person_id) {
<button
type="button"
class="publication-institution-tag"
[class.active]="isAuthorActive(author.person_id!)"
[matTooltip]="getAuthorTooltipText(author)"
matTooltipPosition="above"
[attr.aria-label]="getAuthorTooltipText(author)"
(click)="filterByAuthor(author.person_id!)">
<mat-icon class="institution-icon">person</mat-icon>
<span class="institution-name">{{ author.full_name }}</span>
</button>
} @empty {
<span class="empty-text">-</span>
} -->
<!-- @if (projectAuthors.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isProjectAuthorsExpanded"
(click)="toggleProjectAuthorsExpansion(project)">
{{
isProjectAuthorsExpanded
? 'weniger'
: '+' + (projectAuthors.length - 3)
}}
</button>
} -->
<!-- </div>
</ng-template> -->
<ng-template #institutionsTmp let-project>
@let institutions = getProjectInstitutions(project);
@@ -86,45 +53,42 @@
class="institution-tags"
aria-label="Institutionen"
style="padding: 0.5rem 0">
@for (
institution of isProjectInstitutionsExpanded(project)
? institutions
: institutions.slice(0, 3);
track getProjectInstitutionId(institution)
) {
<button
type="button"
class="publication-institution-tag"
[class.active]="isInstitutionActive(institution.id!)"
[matTooltip]="getInstitutionTooltipText(institution)"
matTooltipPosition="above"
[attr.aria-label]="getInstitutionTooltipText(institution)"
(click)="filterByInstitution(institution)">
<mat-icon class="institution-icon">apartment</mat-icon>
<span class="institution-name">{{
institution.institute_name_de || institution.institute_name_en
}}</span>
</button>
} @empty {
<span class="empty-text">-</span>
}
@if (institutions.length > 3) {
<button
type="button"
class="publication-institution-more"
(click)="toggleProjectInstitutionsExpansion(project)">
@if (isProjectInstitutionsExpanded(project)) {
Weniger anzeigen
} @else {
+{{ institutions.length - 3 }} weitere
}
</button>
}
<button
type="button"
class="publication-institution-tag"
[class.active]="isInstitutionActive(institutions[0].name!)"
[matTooltip]="getInstitutionTooltipText(institutions[0])"
matTooltipPosition="above"
[attr.aria-label]="getInstitutionTooltipText(institutions[0])"
(click)="filterByInstitution(institutions[0])">
<mat-icon class="institution-icon">apartment</mat-icon>
<span class="institution-name">{{
institutions[0].name || institutions[0].recepient || '-'
}}</span>
</button>
</div>
</ng-template>
<ng-template #fundingTypeTmp let-project>
@if (project.funding_type) {
<button
type="button"
class="type-filter-btn"
[class.active]="isFundingTypeActive(project.funding_type)"
matTooltip="Nach Typ filtern"
matTooltipPosition="above"
(click)="toggleFundingTypeFilter(project.funding_type)">
<app-chip [color]="getFundingTypeColor(project.funding_type)">
{{ project.funding_type }}
</app-chip>
</button>
} @else {
<span class="empty-text">-</span>
}
</ng-template>
<ng-template #topicsTmp let-project>
@let projectTopics = project.topics ?? [];
@let projectTopics = project.oa_topics ?? [];
@let isTopicsExpanded = isProjectTopicsExpanded(project);
@let visibleTopics =
isTopicsExpanded ? projectTopics : projectTopics.slice(0, 3);
@@ -7,7 +7,28 @@
// ------------------------
// Shared tags & chips
// ------------------------
.type-filter-btn {
display: inline-flex;
margin: 0;
padding: 0;
border: 0;
border-radius: 7px;
background: transparent;
cursor: pointer;
transition: box-shadow 0.2s ease;
&:hover,
&:focus-visible {
outline: none;
box-shadow: 0 0 0 1px var(--sg-primary);
}
&.active {
box-shadow:
0 0 0 1px #ffffff,
0 0 0 3px var(--sg-primary);
}
}
.publication-institution-tag {
display: inline-flex;
align-items: center;
@@ -7,12 +7,8 @@ import {
viewChild,
inject,
} from '@angular/core';
import {
BundProjectPage,
DfgProjectPage,
DfgProjectSummary,
Topic,
} from '../../../api';
import { CurrencyPipe, DatePipe } from '@angular/common';
import { BundProjectPage, Topic } from '../../../api';
import { BundProjectSummary } from '../../../api/model/bundProjectSummary';
import { TopicChipComponent } from '../topic-chip/topic-chip.component';
import {
@@ -23,12 +19,12 @@ import { RouterModule } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { QueryParamPaginatorComponent } from '../query-param-paginator/query-param-paginator.component';
import { dfgProjectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute, Router } from '@angular/router';
import { DfgPersonSummary } from '../../../api/model/dfgPersonSummary';
import { ChipComponent } from '../chip/chip.component';
import { MatTooltip } from '@angular/material/tooltip';
import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors';
import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.resolver';
@Component({
selector: 'app-bund-project-table',
imports: [
@@ -39,6 +35,9 @@ import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors';
QueryParamPaginatorComponent,
MatTooltip,
TopicChipComponent,
CurrencyPipe,
DatePipe,
ChipComponent,
],
templateUrl: './bund-project-table.component.html',
styleUrl: './bund-project-table.component.scss',
@@ -58,17 +57,18 @@ export class BundProjectTableComponent implements OnInit {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
queryParamKeys = dfgProjectQueryParamKeys;
queryParamKeys = bundProjectQueryParamKeys;
total = computed(() => this.page().total ?? 0);
columns: GenericColumn<BundProjectSummary>[] = [];
titleTmp = viewChild.required<TemplateRef<any>>('titleTmp');
authorsTmp = viewChild.required<TemplateRef<any>>('authorsTmp');
fundingTypeTmp = viewChild.required<TemplateRef<any>>('fundingTypeTmp');
institutionsTmp = viewChild.required<TemplateRef<any>>('institutionsTmp');
fundingStartTmp = viewChild.required<TemplateRef<any>>('fundingStartTmp');
fundingEndTmp = viewChild.required<TemplateRef<any>>('fundingEndTmp');
actionsTmp = viewChild.required<TemplateRef<any>>('actionsTmp');
detailRowTmp = viewChild.required<TemplateRef<any>>('detailRowTmp');
fundingAmountTmp =
viewChild.required<TemplateRef<unknown>>('fundingAmountTmp');
topicsTmp = viewChild.required<TemplateRef<any>>('topicsTmp');
expandedProjectAuthorsId: string[] = [];
@@ -92,21 +92,32 @@ export class BundProjectTableComponent implements OnInit {
});
selectedInstitutionIdsQueryParams = computed(() => {
return this.queryParamMap().getAll(this.queryParamKeys.institutionId);
return this.queryParamMap().getAll(this.queryParamKeys.agency);
});
selectedTopicIdsQueryParams = computed(() => {
return this.queryParamMap().getAll(this.queryParamKeys.topicId);
});
selectedFundingTypesQueryParams = computed(() => {
return this.queryParamMap().getAll(this.queryParamKeys.funding_type);
});
ngOnInit(): void {
this.columns = [
{ id: 'title', header: 'Titel', type: 'accessor', accessorKey: 'topic' },
{
id: 'funding_type',
header: 'Förderart',
type: 'accessor',
accessorKey: 'funding_type',
cellTemplate: this.fundingTypeTmp(),
},
{
id: 'funding_start',
header: 'Förderbeginn',
type: 'accessor',
accessorKey: 'funding_start',
cellTemplate: this.fundingStartTmp(),
},
{
id: 'funding_end',
@@ -115,13 +126,6 @@ export class BundProjectTableComponent implements OnInit {
accessorKey: 'funding_end',
cellTemplate: this.fundingEndTmp(),
},
// {
// id: 'names',
// header: 'Autoren',
// type: 'accessor',
// accessorKey: 'names',
// cellTemplate: this.authorsTmp(),
// },
{
id: 'institutions',
header: 'Institutionen',
@@ -129,10 +133,11 @@ export class BundProjectTableComponent implements OnInit {
cellTemplate: this.institutionsTmp(),
},
{
id: 'professional_classification',
header: 'Fachliche Zuordnung',
type: 'display',
cellTemplate: this.detailRowTmp(),
id: 'grant_amount',
header: 'Förderbetrag',
type: 'accessor',
accessorKey: 'grant_amount',
cellTemplate: this.fundingAmountTmp(),
},
{
@@ -160,125 +165,23 @@ export class BundProjectTableComponent implements OnInit {
this.selectedAuthorIdsQueryParams().includes(String(authorId))
);
}
// getProjectAuthors(project: DfgProjectSummary): DfgPersonSummary[] {
// return project.persons?.filter((a): a is DfgPersonSummary => !!a) || [];
// }
// toggleProjectAuthorsExpansion(project: DfgProjectSummary): void {
// if (!project.id) return;
// if (this.expandedProjectAuthorsId.includes(project.id)) {
// this.expandedProjectAuthorsId = this.expandedProjectAuthorsId.filter(
// (id) => id !== project.id,
// );
// } else {
// this.expandedProjectAuthorsId.push(project.id);
// }
// }
isProjectPersonsExpanded(project: DfgProjectSummary): boolean {
if (!project.id) return false;
return this.expandedProjectAuthorsId.includes(project.id);
isFundingTypeActive(type: string): boolean {
return this.selectedFundingTypesQueryParams().includes(type);
}
// getAuthorTooltipText(author: DfgPersonSummary): string {
// if (this.authorFilterEnabled() && author.person_id) {
// return `Nach Autor filtern: ${author.full_name}`;
// }
// return `Autor: ${author.full_name}`;
// }
// filterByAuthor(authorId: number): void {
// if (!authorId || !this.authorFilterEnabled()) return;
// const selectedAuthorIds = this.selectedAuthorIdsQueryParams();
// if (selectedAuthorIds.includes(String(authorId))) {
// this.router.navigate([], {
// queryParams: {
// [this.queryParamKeys.authorId]: selectedAuthorIds.filter(
// (id) => id !== String(authorId),
// ),
// [this.queryParamKeys.page]: 0,
// },
// queryParamsHandling: 'merge',
// });
// } else {
// this.router.navigate([], {
// queryParams: {
// [this.queryParamKeys.authorId]: [
// ...selectedAuthorIds,
// String(authorId),
// ],
// [this.queryParamKeys.page]: 0,
// },
// queryParamsHandling: 'merge',
// });
// }
// }
isProjectInstitutionsExpanded(project: DfgProjectSummary): boolean {
if (!project.id) return false;
return this.expandedProjectInstitutionsId.includes(project.id);
getFundingTypeColor(type: string | null | undefined): string {
const normalized = (type ?? '').toLowerCase();
if (normalized == 'direkte projektförderung') return 'success';
if (normalized == 'indirekte projektförderung') return 'warning';
if (normalized == 'übrige indirekte projektförderung') return 'help';
return 'info';
}
toggleProjectInstitutionsExpansion(project: DfgProjectSummary): void {
if (!project.id) return;
if (this.expandedProjectInstitutionsId.includes(project.id)) {
this.expandedProjectInstitutionsId =
this.expandedProjectInstitutionsId.filter((id) => id !== project.id);
} else {
this.expandedProjectInstitutionsId.push(project.id);
}
}
getProjectInstitutions(project: DfgProjectSummary): any[] {
const institutions = new Map<string, any>();
for (const institution of project.institutions ?? []) {
const id = this.getProjectInstitutionId(institution);
if (!id) continue;
institutions.set(id, institution);
}
return Array.from(institutions.values()).sort((a, b) =>
this.getProjectInstitutionName(a).localeCompare(
this.getProjectInstitutionName(b),
),
);
}
getProjectInstitutionId(institution: any): string | null {
const id = institution.id;
return id == null ? null : String(id);
}
getProjectInstitutionName(institution: any): string {
return institution.institute_name_de ?? institution.institute_name_en;
}
isInstitutionActive(
institutionId: string | number | null | undefined,
): boolean {
return (
!!institutionId &&
this.institutionFilterEnabled() &&
this.selectedInstitutionIdsQueryParams().includes(String(institutionId))
);
}
filterByInstitution(institution: any): void {
const institutionId = this.getProjectInstitutionId(institution);
if (!institutionId || !this.institutionFilterEnabled()) return;
const selectedInstitutionIds = this.selectedInstitutionIdsQueryParams();
if (selectedInstitutionIds.includes(institutionId)) {
toggleFundingTypeFilter(type: string): void {
const selectedTypes = this.selectedFundingTypesQueryParams();
if (selectedTypes.includes(type)) {
this.router.navigate([], {
queryParams: {
[this.queryParamKeys.institutionId]: selectedInstitutionIds.filter(
(id) => id !== institutionId,
[this.queryParamKeys.funding_type]: selectedTypes.filter(
(t) => t !== type,
),
[this.queryParamKeys.page]: 0,
},
@@ -287,9 +190,70 @@ export class BundProjectTableComponent implements OnInit {
} else {
this.router.navigate([], {
queryParams: {
[this.queryParamKeys.institutionId]: [
[this.queryParamKeys.funding_type]: [...selectedTypes, type],
[this.queryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
}
}
isProjectPersonsExpanded(project: BundProjectSummary): boolean {
if (!project.institution?.name) return false;
return this.expandedProjectAuthorsId.includes(project.institution.name);
}
getStartDate(element: BundProjectSummary): string | Date | undefined {
return (element as any).funding_start;
}
getEndDate(element: BundProjectSummary): string | Date | undefined {
return (element as any).funding_end;
}
getFundingAmount(element: BundProjectSummary): number | undefined {
return (element as any).grant_amount;
}
getProjectInstitutions(project: BundProjectSummary): any[] {
return project.institution ? [project.institution] : [];
}
isInstitutionActive(
institution_name: string | number | null | undefined,
): boolean {
return (
!!institution_name &&
this.institutionFilterEnabled() &&
this.selectedInstitutionIdsQueryParams().includes(
String(institution_name),
)
);
}
filterByInstitution(institution: any): void {
const institutionName = institution.name ?? institution.recepient;
if (!institutionName || !this.institutionFilterEnabled()) return;
const selectedInstitutionIds = this.selectedInstitutionIdsQueryParams();
if (selectedInstitutionIds.includes(institutionName)) {
this.router.navigate([], {
queryParams: {
[this.queryParamKeys.agency]: selectedInstitutionIds.filter(
(id) => id !== institutionName,
),
[this.queryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
} else {
this.router.navigate([], {
queryParams: {
[this.queryParamKeys.agency]: [
...selectedInstitutionIds,
institutionId,
institutionName,
],
[this.queryParamKeys.page]: 0,
},
@@ -299,7 +263,7 @@ export class BundProjectTableComponent implements OnInit {
}
getInstitutionTooltipText(institution: any): string {
const name = this.getProjectInstitutionName(institution);
const name = institution.name ?? institution.recepient ?? 'Unbekannt';
if (this.institutionFilterEnabled()) {
return `Nach Institution filtern: ${name}`;
@@ -350,20 +314,20 @@ export class BundProjectTableComponent implements OnInit {
});
}
}
toggleProjectTopicsExpansion(project: DfgProjectSummary): void {
if (!project.id) return;
toggleProjectTopicsExpansion(project: BundProjectSummary): void {
if (!project.funding_code) return;
if (this.expandedProjectTopicsId.includes(project.id)) {
if (this.expandedProjectTopicsId.includes(project.funding_code)) {
this.expandedProjectTopicsId = this.expandedProjectTopicsId.filter(
(id) => id !== project.id,
(id) => id !== project.funding_code,
);
} else {
this.expandedProjectTopicsId.push(project.id);
this.expandedProjectTopicsId.push(project.funding_code);
}
}
isProjectTopicsExpanded(project: DfgProjectSummary): boolean {
if (!project.id) return false;
isProjectTopicsExpanded(project: BundProjectSummary): boolean {
if (!project.funding_code) return false;
return this.expandedProjectTopicsId.includes(project.id);
return this.expandedProjectTopicsId.includes(project.funding_code);
}
}
@@ -6,6 +6,7 @@
[selectedTopicsPage]="selectedTopicsPage()"
[showFundingStartFilter]="true"
[showTopicFilter]="topicFilterEnabled()"
[showBundFundingTypeFilter]="true"
[showFundingEndFilter]="true"
[showAuthorFilter]="true"
[showInstitutionFilter]="true"
@@ -6,7 +6,7 @@ import {
DfgPersonSummaryPage,
TopicPageV2,
} from '../../../api';
import { DfgInstitutionSummaryPage } from '../../../api/model/dfgInstitutionSummaryPage';
import { BundInstitutionSummaryPage } from '../../../api/model/bundInstitutionSummaryPage';
import { MatCardModule } from '@angular/material/card';
import { MatTabsModule } from '@angular/material/tabs';
import { ProjectFilterComponent } from '../project-filters/project-filters.component';
@@ -26,8 +26,7 @@ import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.reso
export class BundProjectsComponent {
bundProjectPage = input.required<BundProjectPage>();
selectedBundInstitutionsPage = input.required<DfgInstitutionSummaryPage>();
selectedBundAuthorsPage = input.required<DfgPersonSummaryPage>();
selectedBundInstitutionsPage = input.required<BundInstitutionSummaryPage>();
selectedTopicsPage = input.required<TopicPageV2>();
@@ -6,9 +6,9 @@
<app-query-param-paginator
[total]="total()"
[queryParamPageKey]="queryParamKeys.page"
[queryParamSizeKey]="queryParamKeys.size"
[pageSizeOptions]="[10]" />
queryParamPageKey="page"
queryParamSizeKey="size"
[pageSizeOptions]="[10, 25, 50]" />
<ng-template #fundingEndTmp let-element>
{{
@@ -6,9 +6,9 @@
<app-query-param-paginator
[total]="total()"
[queryParamPageKey]="queryParamKeys.page"
[queryParamSizeKey]="queryParamKeys.size"
[pageSizeOptions]="[10]" />
queryParamPageKey="page"
queryParamSizeKey="size"
[pageSizeOptions]="[10, 25, 50]" />
<ng-template #projectTypeTmp let-project>
@if (project.project_type) {
@@ -120,14 +120,14 @@ export class EuProjectTableComponent {
},
{
id: 'startDate',
header: 'Startdatum',
header: 'Förderbeginn',
type: 'accessor',
accessorKey: 'start_date',
cellTemplate: this.fundingStartTmp(),
},
{
id: 'endDate',
header: 'Enddatum',
header: 'Förderende',
type: 'accessor',
accessorKey: 'end_date',
cellTemplate: this.fundingEndTmp(),
@@ -0,0 +1,6 @@
<div echarts class="gauge-chart" [options]="options()"></div>
<div class="gauge-labels" aria-hidden="true">
<span>Grundlagenorientiert</span>
<span class="gauge-label-divider"></span>
<span>Anwendungsorientiert</span>
</div>
@@ -0,0 +1,36 @@
:host {
display: block;
width: 100%;
max-width: 280px;
}
.gauge-chart {
width: 100%;
height: 180px;
}
.gauge-labels {
display: grid;
grid-template-columns: minmax(0, 1fr) 1px minmax(0, 1fr);
align-items: center;
gap: 9px;
width: 100%;
margin-top: -36px;
color: var(--sg-text-muted);
font-size: 11px;
font-weight: 600;
}
.gauge-labels > span:first-child {
text-align: left;
}
.gauge-labels > span:last-child {
text-align: right;
}
.gauge-label-divider {
width: 1px;
height: 13px;
background: var(--sg-border);
}
@@ -0,0 +1,76 @@
import { Component, computed, input } from '@angular/core';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { topicChipColorTokens } from '../topic-chip/topic-chip.component';
const BLUE_TOKENS = topicChipColorTokens('blue');
@Component({
selector: 'app-orientation-gauge',
standalone: true,
imports: [NgxEchartsDirective],
templateUrl: './orientation-gauge.component.html',
styleUrl: './orientation-gauge.component.scss',
})
export class OrientationGaugeComponent {
score = input<number | null>(null);
readonly options = computed<EChartsOption>(() => {
const score = this.score();
const boundedScore = score === null ? 0 : Math.max(0, Math.min(100, score));
const textColor = this.cssColor('--sg-text', BLUE_TOKENS.color);
const trackColor =
score === null
? this.cssColor('--sg-surface-muted', BLUE_TOKENS.background)
: BLUE_TOKENS.background;
return {
animation: false,
series: [
{
type: 'gauge',
min: 0,
max: 100,
startAngle: 180,
endAngle: 0,
center: ['50%', '70%'],
radius: '92%',
progress: {
show: score !== null,
width: 13,
itemStyle: { color: BLUE_TOKENS.color },
},
axisLine: {
lineStyle: { width: 13, color: [[1, trackColor]] },
},
pointer: { show: false },
axisTick: { show: false },
splitLine: { show: false },
axisLabel: { show: false },
anchor: { show: false },
title: { show: false },
detail: {
valueAnimation: false,
offsetCenter: [0, '-8%'],
color: textColor,
fontSize: 25,
fontWeight: 700,
formatter: score === null ? '–' : '{value}',
},
data: [{ value: boundedScore }],
},
],
};
});
private cssColor(variable: string, fallback: string): string {
if (typeof getComputedStyle !== 'function') {
return fallback;
}
return (
getComputedStyle(document.documentElement)
.getPropertyValue(variable)
.trim() || fallback
);
}
}
@@ -22,6 +22,14 @@
[selectedYears]="selectedFundingEndYears()"
(handleYearSelectChange)="handleFundingEndSelectChange($event)" />
}
@if (showBundFundingTypeFilter() && filterMode() === 'bund') {
<app-searchable-bund-funding-type-select
[label]="bundFundingTypeLabel()"
[selectedBundFundingTypes]="selectedBundFundingTypes()"
(handleBundFundingTypeSelectChange)="
handleBundFundingTypeSelectChange($event)
" />
}
@if (showEuProjectTypeFilter() && filterMode() === 'eu') {
<app-searchable-eu-project-type-select
[label]="euProjectTypeLabel()"
@@ -48,6 +56,14 @@
handleEuInstitutionSelectChange($event)
" />
}
@if (showInstitutionFilter() && filterMode() === 'bund') {
<app-searchable-bund-institution-select
[label]="bundInstitutionLabel()"
[selectedInstitutions]="selectedBundInstitutions()"
(handleInstitutionSelectChange)="
handleBundInstitutionSelectChange($event)
" />
}
@if (showAuthorFilter() && filterMode() === 'dfg') {
<app-searchable-dfg-author-select
@@ -9,6 +9,8 @@ import { MatSelectModule } from '@angular/material/select';
import { DfgInstitutionSummaryPage } from '../../../api/model/dfgInstitutionSummaryPage';
import { DfgInstitutionSummary } from '../../../api/model/dfgInstitutionSummary';
import { BundInstitutionSummary } from '../../../api/model/bundInstitutionSummary';
import { BundInstitutionSummaryPage } from '../../../api/model/bundInstitutionSummaryPage';
import {
Author,
@@ -32,9 +34,15 @@ import { TopicLegendComponent } from '../topic-legend/topic-legend.component';
import { QueryParamInputComponent } from '../query-param-input/query-param-input.component';
import { SearchableDfgInstitutionSelectComponent } from '../searchable-dfg-institution-select/searchable-dfg-institution-select.component';
import { SearchableEuInstitutionSelectComponent } from '../searchable-eu-institution-select/searchable-eu-institution-select.component';
import { SearchableBundInstitutionSelectComponent } from '../searchable-bund-institution-select/searchable-bund-institution-select.component';
import { SearchableYearSelectComponent } from '../searchable-year-select/searchable-year-select.component';
import { SearchableDfgAuthorSelectComponent } from '../searchable-dfg-author-select/searchable-dfg-author-select.component';
import { SearchableTopicSelectComponent } from '../searchable-topic-select/searchable-topic-select.component';
import {
SearchableBundFundingTypeSelectComponent,
FundingType,
findFundingTypeById,
} from '../searchable-bund-funding-type-select/searchable-bund-funding-type-select.component';
import {
SearchableEuProjectTypeSelectComponent,
ProjectType,
@@ -74,6 +82,8 @@ type ProjectQueryParamKeys =
SearchableTopicSelectComponent,
TopicLegendComponent,
SearchableEuProjectTypeSelectComponent,
SearchableBundFundingTypeSelectComponent,
SearchableBundInstitutionSelectComponent,
],
templateUrl: './project-filters.component.html',
styleUrl: './project-filters.component.scss',
@@ -87,7 +97,7 @@ export class ProjectFilterComponent {
selectedDfgInstitutionsPage = input<DfgInstitutionSummaryPage>();
selectedEuInstitutionsPage = input<EuCordisOrganizationSelectorPage>();
selectedBundInstitutionsPage = input<DfgInstitutionSummaryPage>();
selectedBundInstitutionsPage = input<BundInstitutionSummaryPage>();
selectedDfgAuthorsPage = input<DfgPersonSummaryPage>();
selectedEuAuthorsPage = input<AuthorPage>();
@@ -100,6 +110,7 @@ export class ProjectFilterComponent {
showFundingEndFilter = input<boolean>(false);
showTopicFilter = input<boolean>(true);
showEuProjectTypeFilter = input<boolean>(false);
showBundFundingTypeFilter = input<boolean>(false);
selectedDfgAuthors = computed<DfgPersonSummary[]>(
() => this.selectedDfgAuthorsPage()?.elements || [],
@@ -116,7 +127,9 @@ export class ProjectFilterComponent {
selectedEuInstitutions = computed<EuCordisOrganizationSelectorSummary[]>(
() => this.selectedEuInstitutionsPage()?.elements || [],
);
selectedBundInstitutions = computed<BundInstitutionSummary[]>(
() => this.selectedBundInstitutionsPage()?.elements || [],
);
selectedTopics = computed<Topic[]>(
() => this.selectedTopicsPage()?.elements || [],
);
@@ -228,6 +241,19 @@ export class ProjectFilterComponent {
return `${selected.length} Institutionen`;
});
bundInstitutionLabel = computed(() => {
const selected = this.selectedBundInstitutions().filter((i) =>
this.selectedInstitutionIds().includes(String(i.name!)),
);
if (selected.length === 0) return 'Institution';
if (selected.length === 1) {
return selected[0].name ?? 'Institution';
}
return `${selected.length} Institutionen`;
});
dfgAuthorLabel = computed(() => {
const selected = this.selectedDfgAuthors().filter((a) =>
this.dfgSelectedAuthorIds().includes(String(a.person_id!)),
@@ -362,6 +388,30 @@ export class ProjectFilterComponent {
},
});
}
if (this.filterMode() === 'bund') {
const bundKeys = keys as typeof bundProjectQueryParamKeys;
observers.push({
id: 'fundingTypes',
queryParamKey: bundKeys.funding_type,
icon: 'category',
valueFormatter: (value: string) => {
const fundingType = findFundingTypeById(value);
return fundingType ? fundingType.name : value;
},
});
observers.push({
id: 'agencies',
queryParamKey: bundKeys.agency,
icon: 'apartment',
valueFormatter: (value: string) => {
const institution = this.selectedBundInstitutions().find(
(i) => String(i.name) === value,
);
return institution ? institution.name : value;
},
});
}
return observers;
});
@@ -465,7 +515,28 @@ export class ProjectFilterComponent {
queryParamsHandling: 'merge',
});
};
handleBundInstitutionSelectChange = (
institution: BundInstitutionSummary,
): void => {
if (!institution.name) return;
const keys = this.queryParamKeys() as typeof bundProjectQueryParamKeys;
const selectedIds = this.selectedInstitutionIds();
const agency_name = String(institution.name);
const nextIds = selectedIds.includes(agency_name)
? selectedIds.filter((id) => id !== agency_name)
: [...selectedIds, agency_name];
this.router.navigate([], {
queryParams: {
[keys.agency]: nextIds,
[keys.page]: 0,
},
queryParamsHandling: 'merge',
});
};
handleDfgAuthorSelectChange = (author: DfgPersonSummary): void => {
if (!author.person_id) return;
@@ -539,6 +610,19 @@ export class ProjectFilterComponent {
queryParamsHandling: 'merge',
});
};
handleBundFundingTypeSelectChange = (
selectedFundingTypes: FundingType,
): void => {
const keys = this.queryParamKeys() as typeof bundProjectQueryParamKeys;
this.router.navigate([], {
queryParams: {
[keys.funding_type]: selectedFundingTypes.id,
[keys.page]: 0,
},
queryParamsHandling: 'merge',
});
};
get topicLegendGroups(): TopicLegendGroup[] {
const topics = this.selectedTopics().map((topic) =>
@@ -563,4 +647,23 @@ export class ProjectFilterComponent {
subfield_description: null,
};
}
selectedBundFundingTypes = computed(() => {
const projectTypeIds = this.queryParamMap().getAll(
(this.queryParamKeys() as any).project_type,
);
return projectTypeIds
.map((id) => findFundingTypeById(id))
.filter((type) => type !== undefined) as FundingType[];
});
bundFundingTypeLabel = computed(() => {
const selected = this.selectedBundFundingTypes();
if (selected.length === 0) return 'Förderungstyp';
if (selected.length === 1) {
return selected[0].name ?? 'Förderungstyp';
}
return `${selected.length} Förderungstypen`;
});
}

Some files were not shown because too many files have changed in this diff Show More