feature/keywords-analysis #265
@@ -11,13 +11,13 @@ from sqlmodel import Session
|
||||
|
||||
from inse import config
|
||||
from inse.auth.model import AccessToken, Organization
|
||||
from inse.authors.institution_membership_query import (
|
||||
build_institution_membership_query,
|
||||
)
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.institutions.v2 import service as institutions_v2_service
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
|
||||
from inse.persons import service as persons_service
|
||||
from inse.projects import service as projects_service
|
||||
from inse.projects.dfg_institutions.service import (
|
||||
autocomplete_institutions_for_selector,
|
||||
)
|
||||
@@ -241,20 +241,26 @@ async def get_dashboard_publications(
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
filters = []
|
||||
if year_filter := _publication_year_filter(period):
|
||||
filters.append(year_filter)
|
||||
query = _institution_works_query(normalized_id)
|
||||
if filters:
|
||||
query = {"bool": {"must": [query], "filter": filters}}
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
query=query,
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.NES,
|
||||
institution = await institutions_v2_service.get_institution_by_id_or_raise(
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
source=["id", "works_count", "counts_by_year"],
|
||||
)
|
||||
if period == (None, None):
|
||||
value = int(institution.works_count or 0)
|
||||
else:
|
||||
value = sum(
|
||||
int(entry.works_count or 0)
|
||||
for entry in institution.counts_by_year or []
|
||||
if (
|
||||
(period[0] is None or int(entry.year or 0) >= period[0])
|
||||
and (period[1] is None or int(entry.year or 0) <= period[1])
|
||||
)
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=value,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_persons(
|
||||
@@ -270,20 +276,25 @@ async def get_dashboard_persons(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="from_year and to_year must either both be provided or both omitted.",
|
||||
)
|
||||
membership_query = build_institution_membership_query(
|
||||
persons = await persons_service.search_persons_list(
|
||||
query=None,
|
||||
institution_id=normalized_id,
|
||||
year_mode="between" if period[0] is not None else "all",
|
||||
year=period[0],
|
||||
year_to=period[1],
|
||||
sort_by=None,
|
||||
sort_order=None,
|
||||
topic=None,
|
||||
page=1,
|
||||
page_size=1,
|
||||
include="",
|
||||
year_filter_enabled=period[0] is not None,
|
||||
filter_mode="between" if period[0] is not None else None,
|
||||
filter_year=period[0],
|
||||
filter_year_to=period[1],
|
||||
)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_AUTHORS,
|
||||
query=membership_query,
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.NES,
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=int(persons.meta.count or 0) if persons.meta else 0,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_patents(
|
||||
@@ -315,45 +326,43 @@ async def get_dashboard_eu_projects(
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
period_filter = _project_overlap_filter(
|
||||
"startDate",
|
||||
"endDate",
|
||||
_date_period(period, "iso"),
|
||||
)
|
||||
if period_filter:
|
||||
project_ids = await _eu_project_ids_for_aliases(aliases)
|
||||
value = await _count_eu_projects_in_period(project_ids, period_filter)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=value,
|
||||
)
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": _eu_organization_query(aliases),
|
||||
"aggs": {
|
||||
"projects": {
|
||||
"cardinality": {
|
||||
"field": "projectID",
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
projects = await projects_service.search_eu_cordis_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
author_id=None,
|
||||
author_ids=None,
|
||||
organization_ids=None,
|
||||
organization_names=None,
|
||||
project_types=list(EuCordisProjectType),
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
countries=None,
|
||||
framework_programmes=None,
|
||||
funding_schemes=None,
|
||||
statuses=None,
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=int(
|
||||
response.get("aggregations", {})
|
||||
.get("projects", {})
|
||||
.get("value", 0)
|
||||
),
|
||||
value=projects.total,
|
||||
)
|
||||
|
||||
|
||||
@@ -368,10 +377,18 @@ async def get_dashboard_eu_project_statuses(
|
||||
project_ids = await _eu_project_ids_for_aliases(aliases)
|
||||
|
||||
if not project_ids:
|
||||
total = (
|
||||
await get_dashboard_eu_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=0,
|
||||
ongoing=total,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
@@ -426,12 +443,26 @@ async def get_dashboard_eu_project_statuses(
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = response.get("aggregations", {})
|
||||
total = (
|
||||
await get_dashboard_eu_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
ongoing, upcoming, completed = _reconcile_project_status_counts(
|
||||
total,
|
||||
_project_status_count(aggregations, "ongoing"),
|
||||
_project_status_count(aggregations, "upcoming"),
|
||||
_project_status_count(aggregations, "completed"),
|
||||
)
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=_project_status_count(aggregations, "ongoing"),
|
||||
upcoming=_project_status_count(aggregations, "upcoming"),
|
||||
completed=_project_status_count(aggregations, "completed"),
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
@@ -441,6 +472,32 @@ def _project_status_count(aggregations: dict[str, Any], status_name: str) -> int
|
||||
)
|
||||
|
||||
|
||||
def _reconcile_project_status_counts(
|
||||
total: int,
|
||||
ongoing: int,
|
||||
upcoming: int,
|
||||
completed: int,
|
||||
) -> tuple[int, int, int]:
|
||||
"""Makes status buckets add up to the authoritative project-service total."""
|
||||
counts = [max(0, ongoing), max(0, upcoming), max(0, completed)]
|
||||
difference = total - sum(counts)
|
||||
if difference >= 0:
|
||||
counts[0] += difference
|
||||
return counts[0], counts[1], counts[2]
|
||||
|
||||
# Defensive fallback for stale/duplicated status documents: reduce buckets
|
||||
# without ever returning negative values, preferring the inferred ongoing
|
||||
# bucket before changing explicit upcoming/completed classifications.
|
||||
excess = -difference
|
||||
for index in (0, 1, 2):
|
||||
reduction = min(counts[index], excess)
|
||||
counts[index] -= reduction
|
||||
excess -= reduction
|
||||
if excess == 0:
|
||||
break
|
||||
return counts[0], counts[1], counts[2]
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
@@ -448,23 +505,38 @@ async def get_dashboard_bmbf_projects(
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
filters = [_alias_match_query("Zuwendungsempfänger", aliases)]
|
||||
if period_filter := _project_overlap_filter(
|
||||
"funding_start",
|
||||
"funding_end",
|
||||
_date_period(period, "de"),
|
||||
):
|
||||
filters.append(period_filter)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
query=filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.INSE,
|
||||
projects = await projects_service.search_bund_projects_with_filters(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
executing_agency=None,
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
title=None,
|
||||
keywords=None,
|
||||
funding_arts=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
countries=None,
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=projects.total,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_project_statuses(
|
||||
@@ -498,12 +570,26 @@ async def get_dashboard_bmbf_project_statuses(
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = response.get("aggregations", {})
|
||||
total = (
|
||||
await get_dashboard_bmbf_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
ongoing, upcoming, completed = _reconcile_project_status_counts(
|
||||
total,
|
||||
int(aggregations.get("ongoing", {}).get("doc_count", 0)),
|
||||
int(aggregations.get("upcoming", {}).get("doc_count", 0)),
|
||||
int(aggregations.get("completed", {}).get("doc_count", 0)),
|
||||
)
|
||||
return BmbfProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=int(aggregations.get("ongoing", {}).get("doc_count", 0)),
|
||||
upcoming=int(aggregations.get("upcoming", {}).get("doc_count", 0)),
|
||||
completed=int(aggregations.get("completed", {}).get("doc_count", 0)),
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
@@ -535,15 +621,37 @@ async def get_dashboard_dfg_projects(
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
project_ids = await _get_dfg_project_ids_for_institution(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
projects = await projects_service.get_dfg_projects_by_author_id(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
author_id=None,
|
||||
author_filter_ids=None,
|
||||
institution_ids=None,
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=len(project_ids),
|
||||
value=projects.total,
|
||||
)
|
||||
|
||||
|
||||
@@ -559,10 +667,18 @@ async def get_dashboard_dfg_project_statuses(
|
||||
normalized_id,
|
||||
)
|
||||
if not project_ids:
|
||||
total = (
|
||||
await get_dashboard_dfg_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=0,
|
||||
ongoing=total,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
@@ -640,12 +756,26 @@ async def get_dashboard_dfg_project_statuses(
|
||||
.get("projects_nested", {})
|
||||
.get("selected_projects", {})
|
||||
)
|
||||
total = (
|
||||
await get_dashboard_dfg_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
ongoing, upcoming, completed = _reconcile_project_status_counts(
|
||||
total,
|
||||
_project_status_count(aggregations, "ongoing"),
|
||||
0,
|
||||
_project_status_count(aggregations, "completed"),
|
||||
)
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=_project_status_count(aggregations, "ongoing"),
|
||||
upcoming=0,
|
||||
completed=_project_status_count(aggregations, "completed"),
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
@@ -656,17 +786,11 @@ async def get_dashboard_dfg_topics(
|
||||
to_year: int | None = None,
|
||||
) -> DfgProjectTopics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
project_ids = await _get_dfg_project_ids_for_institution(
|
||||
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
print(
|
||||
"Dashboard DFG project topics "
|
||||
f"for institution {normalized_id}: "
|
||||
f"{len(project_ids)} project IDs={project_ids}",
|
||||
flush=True,
|
||||
)
|
||||
topics: dict[str, dict[str, Any]] = {}
|
||||
matched_project_ids: set[str] = set()
|
||||
|
||||
@@ -735,6 +859,53 @@ async def get_dashboard_dfg_topics(
|
||||
)
|
||||
|
||||
|
||||
async def _get_dfg_project_ids_from_projects_service(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
"""Returns every matching DFG project ID through the canonical project service."""
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
projects = await projects_service.get_dfg_projects_by_author_id(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(institution_id),
|
||||
author_id=None,
|
||||
author_filter_ids=None,
|
||||
institution_ids=None,
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
project_ids.update(project.id for project in projects.elements if project.id)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
return sorted(project_ids)
|
||||
|
||||
|
||||
async def _get_dfg_project_ids_for_institution(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
@@ -1011,7 +1182,6 @@ async def get_top_authors(
|
||||
from_year = datetime.now().year - 4
|
||||
to_year = datetime.now().year
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
authors = await _safe_institution_authors(normalized_id)
|
||||
works = _top_work_authors(authors, period)
|
||||
projects = await _safe_top_authors(
|
||||
@@ -1025,7 +1195,12 @@ async def get_top_authors(
|
||||
)
|
||||
eu_projects = await _safe_top_authors(
|
||||
"eu_projects",
|
||||
_top_eu_project_publication_authors(normalized_id, aliases, authors),
|
||||
_top_eu_project_publication_authors(
|
||||
normalized_id,
|
||||
authors,
|
||||
from_year=period[0],
|
||||
to_year=period[1],
|
||||
),
|
||||
)
|
||||
|
||||
patents = await _safe_top_authors(
|
||||
@@ -1998,8 +2173,9 @@ async def _top_patent_authors(
|
||||
|
||||
async def _top_eu_project_publication_authors(
|
||||
institution_id: str,
|
||||
organization_names: list[str],
|
||||
institution_authors: list[dict[str, Any]],
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[TopAuthor]:
|
||||
institution_author_ids = {
|
||||
author_id
|
||||
@@ -2009,17 +2185,12 @@ async def _top_eu_project_publication_authors(
|
||||
if not institution_author_ids:
|
||||
return []
|
||||
|
||||
project_page = await get_eu_organization_project_contributions(
|
||||
organization_names=organization_names,
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU,
|
||||
page=0,
|
||||
size=10000,
|
||||
),
|
||||
project_ids = await _get_eu_project_ids_from_projects_service(
|
||||
institution_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
project_ids = [project.project_id for project in project_page.elements]
|
||||
|
||||
if not project_ids:
|
||||
return []
|
||||
|
||||
@@ -2028,11 +2199,7 @@ async def _top_eu_project_publication_authors(
|
||||
body={
|
||||
"size": 10000,
|
||||
"_source": ["projectID", "qaProcessedDoi"],
|
||||
"query": {
|
||||
"terms": {
|
||||
"projectID": project_ids,
|
||||
}
|
||||
},
|
||||
"query": {"terms": {"projectID": project_ids}},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
@@ -2066,12 +2233,83 @@ async def _top_eu_project_publication_authors(
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
return _openalex_work_authors_by_eu_projects(
|
||||
candidates = _openalex_work_authors_by_eu_projects(
|
||||
works_response,
|
||||
doi_project_ids,
|
||||
institution_id,
|
||||
institution_author_ids,
|
||||
limit=None,
|
||||
)
|
||||
counts = await asyncio.gather(
|
||||
*(
|
||||
_person_eu_project_count(
|
||||
candidate.id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
for candidate in candidates
|
||||
if candidate.id
|
||||
)
|
||||
)
|
||||
ranked = [
|
||||
TopAuthor(id=candidate.id, name=candidate.name, count=count)
|
||||
for candidate, count in zip(candidates, counts, strict=True)
|
||||
]
|
||||
ranked.sort(key=lambda author: (-author.count, author.name, author.id or ""))
|
||||
return ranked[:TOP_AUTHOR_LIMIT]
|
||||
|
||||
|
||||
async def _get_eu_project_ids_from_projects_service(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
"""Loads all organization EU project IDs from the canonical project service."""
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
projects = await projects_service.search_eu_cordis_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(institution_id),
|
||||
author_id=None,
|
||||
author_ids=None,
|
||||
organization_ids=None,
|
||||
organization_names=None,
|
||||
project_types=list(EuCordisProjectType),
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
countries=None,
|
||||
framework_programmes=None,
|
||||
funding_schemes=None,
|
||||
statuses=None,
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
project_ids.update(project.id for project in projects.elements if project.id)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
return sorted(project_ids)
|
||||
|
||||
|
||||
def _cordis_publication_doi_project_ids(
|
||||
@@ -2108,6 +2346,7 @@ def _openalex_work_authors_by_eu_projects(
|
||||
doi_project_ids: dict[str, set[str]],
|
||||
institution_id: str,
|
||||
institution_author_ids: set[str],
|
||||
limit: int | None = TOP_AUTHOR_LIMIT,
|
||||
) -> list[TopAuthor]:
|
||||
# Count unique CORDIS projects per author, not publications. Multiple works
|
||||
# (and therefore multiple DOIs) can belong to the same project ID.
|
||||
@@ -2143,14 +2382,58 @@ def _openalex_work_authors_by_eu_projects(
|
||||
key=lambda item: (-len(item[1]), author_names.get(item[0], ""), item[0]),
|
||||
)
|
||||
|
||||
return [
|
||||
authors = [
|
||||
TopAuthor(
|
||||
id=_short_author_id(author_id),
|
||||
name=author_names[author_id],
|
||||
count=len(project_ids),
|
||||
)
|
||||
for author_id, project_ids in ranked_authors[:TOP_AUTHOR_LIMIT]
|
||||
for author_id, project_ids in ranked_authors
|
||||
]
|
||||
return authors[:limit] if limit is not None else authors
|
||||
|
||||
|
||||
async def _person_eu_project_count(
|
||||
author_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> int:
|
||||
"""Uses the same author-only EU project search as the person detail page."""
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
projects = await projects_service.search_eu_cordis_projects(
|
||||
page=0,
|
||||
size=1,
|
||||
project_types=None,
|
||||
raw_oa_institution_id=None,
|
||||
institutions_search_client=None,
|
||||
author_id=_short_author_id(author_id),
|
||||
author_ids=None,
|
||||
organization_ids=None,
|
||||
organization_names=None,
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
countries=None,
|
||||
framework_programmes=None,
|
||||
funding_schemes=None,
|
||||
statuses=None,
|
||||
sort_by="title",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
return projects.total
|
||||
|
||||
|
||||
def _normalize_author_id(value: Any) -> str | None:
|
||||
|
||||
@@ -10,14 +10,32 @@ from inse import config
|
||||
from inse.auth.model import AccessToken, Organization, UserRole
|
||||
from inse.dashboard.service import (
|
||||
_openalex_work_authors_by_eu_projects,
|
||||
_get_dfg_project_ids_from_projects_service,
|
||||
_reconcile_project_status_counts,
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_persons,
|
||||
get_dashboard_publications,
|
||||
get_dashboard_statistics,
|
||||
get_top_authors,
|
||||
get_topic_heatmap,
|
||||
get_topic_word_cloud,
|
||||
)
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.models.openalex.meta import Meta
|
||||
from inse.persons.model import CustomAuthorsListResponse
|
||||
from inse.projects.model import (
|
||||
BundProjectPage,
|
||||
DfgProjectPage,
|
||||
DfgProjectSummary,
|
||||
EuCordisProjectSearchPage,
|
||||
EuCordisProjectSummary,
|
||||
EuCordisProjectType,
|
||||
)
|
||||
|
||||
ORG_INSTITUTION_ID = "https://openalex.org/I123"
|
||||
|
||||
@@ -27,6 +45,47 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_project_status_counts_match_authoritative_total():
|
||||
assert _reconcile_project_status_counts(12, 4, 1, 5) == (6, 1, 5)
|
||||
assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dfg_topic_project_ids_use_paginated_projects_service():
|
||||
pages = [
|
||||
DfgProjectPage(
|
||||
elements=[DfgProjectSummary(id="101"), DfgProjectSummary(id="102")],
|
||||
total=3,
|
||||
page=0,
|
||||
size=1000,
|
||||
),
|
||||
DfgProjectPage(
|
||||
elements=[DfgProjectSummary(id="103")],
|
||||
total=3,
|
||||
page=1,
|
||||
size=1000,
|
||||
),
|
||||
]
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.get_dfg_projects_by_author_id",
|
||||
new=AsyncMock(side_effect=pages),
|
||||
) as mocked_get_projects:
|
||||
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||
ORG_INSTITUTION_ID,
|
||||
from_year=2020,
|
||||
to_year=2022,
|
||||
)
|
||||
|
||||
assert project_ids == ["101", "102", "103"]
|
||||
assert mocked_get_projects.await_count == 2
|
||||
first_call = mocked_get_projects.await_args_list[0]
|
||||
assert first_call.kwargs["raw_oa_institution_id"] == "I123"
|
||||
assert first_call.kwargs["skip_enrichment"] is True
|
||||
assert first_call.kwargs["funding_start_years"][-1] == "2022"
|
||||
assert first_call.kwargs["funding_end_years"][0] == "2020"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
async def search(**kwargs):
|
||||
@@ -84,6 +143,33 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
display_name_alternatives=["Example Universität"],
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.projects_service.get_dfg_projects_by_author_id",
|
||||
new=AsyncMock(
|
||||
return_value=DfgProjectPage(elements=[], total=3, page=0, size=1)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(
|
||||
return_value=EuCordisProjectSearchPage(
|
||||
elements=[], total=10, page=0, size=1
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.projects_service.search_bund_projects_with_filters",
|
||||
new=AsyncMock(
|
||||
return_value=BundProjectPage(elements=[], total=5, page=0, size=1)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.persons_service.search_persons_list",
|
||||
new=AsyncMock(
|
||||
return_value=CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=35, page=1, per_page=1)
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
|
||||
new=AsyncMock(return_value=Institution(id=ORG_INSTITUTION_ID, works_count=120)),
|
||||
):
|
||||
result = await get_dashboard_statistics(
|
||||
ORG_INSTITUTION_ID,
|
||||
@@ -101,64 +187,144 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
"bmbf_projects": 5,
|
||||
}
|
||||
|
||||
publication_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == config.settings.openalex_works_search_index
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_publications_uses_institutions_v2_counts():
|
||||
institution = Institution(
|
||||
id=ORG_INSTITUTION_ID,
|
||||
works_count=250,
|
||||
counts_by_year=[
|
||||
AuthorCountsByYearInner(year=2021, works_count=10),
|
||||
AuthorCountsByYearInner(year=2022, works_count=12),
|
||||
AuthorCountsByYearInner(year=2023, works_count=14),
|
||||
],
|
||||
)
|
||||
assert publication_call.kwargs["query"]["nested"]["query"]["term"] == {
|
||||
"authorships.institutions.id": ORG_INSTITUTION_ID
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
|
||||
new=AsyncMock(return_value=institution),
|
||||
) as mocked_get_institution:
|
||||
all_time = await get_dashboard_publications(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
)
|
||||
selected_period = await get_dashboard_publications(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2021,
|
||||
to_year=2022,
|
||||
)
|
||||
|
||||
assert all_time.value == 250
|
||||
assert selected_period.value == 22
|
||||
assert mocked_get_institution.await_args_list[0].kwargs == {
|
||||
"raw_oa_institution_id": "I123",
|
||||
"source": ["id", "works_count", "counts_by_year"],
|
||||
}
|
||||
|
||||
person_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS
|
||||
)
|
||||
person_query = person_call.kwargs["query"]
|
||||
affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1]
|
||||
|
||||
assert affiliation["nested"]["path"] == "affiliations"
|
||||
assert affiliation["nested"]["query"]["bool"]["filter"][0] == {
|
||||
"term": {"affiliations.institution.id": ORG_INSTITUTION_ID}
|
||||
}
|
||||
eu_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_persons_uses_persons_service_for_organization():
|
||||
response = CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=64, page=1, per_page=1)
|
||||
)
|
||||
assert eu_call.kwargs["cluster"] == ESCluster.INSE
|
||||
assert eu_call.kwargs["body"]["query"] == {
|
||||
"terms": {
|
||||
"name.keyword": [
|
||||
"EXAMPLE ORG",
|
||||
"EXAMPLE UNI",
|
||||
"EXAMPLE UNIVERSITY",
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
bund_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1
|
||||
with patch(
|
||||
"inse.dashboard.service.persons_service.search_persons_list",
|
||||
new=AsyncMock(return_value=response),
|
||||
) as mocked_search_persons:
|
||||
result = await get_dashboard_persons(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2020,
|
||||
to_year=2023,
|
||||
)
|
||||
|
||||
assert result.value == 64
|
||||
call = mocked_search_persons.await_args
|
||||
assert call.kwargs["institution_id"] == ORG_INSTITUTION_ID
|
||||
assert call.kwargs["filter_mode"] == "between"
|
||||
assert call.kwargs["filter_year"] == 2020
|
||||
assert call.kwargs["filter_year_to"] == 2023
|
||||
assert call.kwargs["page"] == 1
|
||||
assert call.kwargs["page_size"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_dfg_projects_uses_projects_service_total():
|
||||
project_page = DfgProjectPage(elements=[], total=42, page=0, size=1)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.get_dfg_projects_by_author_id",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_get_projects:
|
||||
result = await get_dashboard_dfg_projects(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2020,
|
||||
to_year=2022,
|
||||
)
|
||||
|
||||
assert result.value == 42
|
||||
mocked_get_projects.assert_awaited_once()
|
||||
call = mocked_get_projects.await_args
|
||||
assert call.kwargs["raw_oa_institution_id"] == "I123"
|
||||
assert call.kwargs["funding_start_years"][-1] == "2022"
|
||||
assert call.kwargs["funding_end_years"][0] == "2020"
|
||||
assert call.kwargs["page"] == 0
|
||||
assert call.kwargs["size"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_bmbf_projects_uses_projects_service_total():
|
||||
project_page = BundProjectPage(elements=[], total=29, page=0, size=1)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.search_bund_projects_with_filters",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_get_projects:
|
||||
result = await get_dashboard_bmbf_projects(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2018,
|
||||
to_year=2020,
|
||||
)
|
||||
|
||||
assert result.value == 29
|
||||
mocked_get_projects.assert_awaited_once()
|
||||
call = mocked_get_projects.await_args
|
||||
assert call.kwargs["raw_oa_institution_id"] == "I123"
|
||||
assert call.kwargs["funding_start_years"][-1] == "2020"
|
||||
assert call.kwargs["funding_end_years"][0] == "2018"
|
||||
assert call.kwargs["page"] == 0
|
||||
assert call.kwargs["size"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_eu_projects_uses_projects_service_total():
|
||||
project_page = EuCordisProjectSearchPage(
|
||||
elements=[], total=37, page=0, size=1
|
||||
)
|
||||
assert bund_call.kwargs["cluster"] == ESCluster.INSE
|
||||
assert bund_call.kwargs["query"]["bool"]["minimum_should_match"] == 1
|
||||
assert bund_call.kwargs["query"]["bool"]["should"][0]["match"] == {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "Example Org",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
|
||||
dfg_calls = [
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2
|
||||
]
|
||||
assert len(dfg_calls) == 2
|
||||
assert all(call.kwargs["cluster"] == ESCluster.INSE for call in dfg_calls)
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_get_projects:
|
||||
result = await get_dashboard_eu_projects(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2019,
|
||||
to_year=2021,
|
||||
)
|
||||
|
||||
assert result.value == 37
|
||||
mocked_get_projects.assert_awaited_once()
|
||||
call = mocked_get_projects.await_args
|
||||
assert call.kwargs["raw_oa_institution_id"] == "I123"
|
||||
assert call.kwargs["funding_start_years"][-1] == "2021"
|
||||
assert call.kwargs["funding_end_years"][0] == "2019"
|
||||
assert call.kwargs["project_types"] == list(EuCordisProjectType)
|
||||
assert call.kwargs["page"] == 0
|
||||
assert call.kwargs["size"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -272,6 +438,25 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
|
||||
return {"aggregations": {"people": {"buckets": []}}}
|
||||
|
||||
async def eu_projects(**kwargs):
|
||||
if kwargs.get("raw_oa_institution_id"):
|
||||
return EuCordisProjectSearchPage(
|
||||
elements=[
|
||||
EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7),
|
||||
EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020),
|
||||
EuCordisProjectSummary(id="P3", project_type=EuCordisProjectType.HEU),
|
||||
],
|
||||
total=3,
|
||||
page=0,
|
||||
size=1000,
|
||||
)
|
||||
return EuCordisProjectSearchPage(
|
||||
elements=[],
|
||||
total={"A1": 3, "A2": 4}[kwargs["author_id"]],
|
||||
page=0,
|
||||
size=1,
|
||||
)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
@@ -279,16 +464,8 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.get_eu_organization_project_contributions",
|
||||
new=AsyncMock(
|
||||
return_value=SimpleNamespace(
|
||||
elements=[
|
||||
SimpleNamespace(project_id="P1"),
|
||||
SimpleNamespace(project_id="P2"),
|
||||
SimpleNamespace(project_id="P3"),
|
||||
],
|
||||
)
|
||||
),
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(side_effect=eu_projects),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(
|
||||
@@ -313,8 +490,8 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
"count": 4,
|
||||
}
|
||||
assert [author.model_dump() for author in result.eu_projects] == [
|
||||
{"id": "A2", "name": "Grace Example", "count": 2},
|
||||
{"id": "A1", "name": "Ada Example", "count": 1},
|
||||
{"id": "A2", "name": "Grace Example", "count": 4},
|
||||
{"id": "A1", "name": "Ada Example", "count": 3},
|
||||
]
|
||||
assert result.news[0].model_dump() == {
|
||||
"id": "A1",
|
||||
@@ -573,6 +750,24 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
||||
}
|
||||
return {"aggregations": {"authors": {"buckets": []}}}
|
||||
|
||||
async def eu_projects(**kwargs):
|
||||
if kwargs.get("raw_oa_institution_id"):
|
||||
return EuCordisProjectSearchPage(
|
||||
elements=[
|
||||
EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7),
|
||||
EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020),
|
||||
],
|
||||
total=2,
|
||||
page=0,
|
||||
size=1000,
|
||||
)
|
||||
return EuCordisProjectSearchPage(
|
||||
elements=[],
|
||||
total={"A1": 4, "A2": 1}[kwargs["author_id"]],
|
||||
page=0,
|
||||
size=1,
|
||||
)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
@@ -580,15 +775,8 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.get_eu_organization_project_contributions",
|
||||
new=AsyncMock(
|
||||
return_value=SimpleNamespace(
|
||||
elements=[
|
||||
SimpleNamespace(project_id="P1"),
|
||||
SimpleNamespace(project_id="P2"),
|
||||
],
|
||||
)
|
||||
),
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(side_effect=eu_projects),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
@@ -599,7 +787,7 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
||||
)
|
||||
|
||||
assert [author.model_dump() for author in result.eu_projects] == [
|
||||
{"id": "A1", "name": "Ada Example", "count": 2},
|
||||
{"id": "A1", "name": "Ada Example", "count": 4},
|
||||
{"id": "A2", "name": "Grace Example", "count": 1},
|
||||
]
|
||||
|
||||
|
||||
@@ -944,6 +944,7 @@ async def search_eu_cordis_projects(
|
||||
sort_by: str = "title",
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
skip_enrichment: bool = False,
|
||||
) -> EuCordisProjectSearchPage:
|
||||
"""
|
||||
Generic EU CORDIS project search across FP7, H2020 and Horizon Europe.
|
||||
@@ -1015,6 +1016,14 @@ async def search_eu_cordis_projects(
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
total = response.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
if skip_enrichment:
|
||||
return EuCordisProjectSearchPage(
|
||||
elements=[EuCordisProjectSummary.from_hit(hit) for hit in hits],
|
||||
total=total,
|
||||
page=page,
|
||||
size=size,
|
||||
)
|
||||
|
||||
project_ids_by_type: dict[EuCordisProjectType, list[str]] = defaultdict(list)
|
||||
|
||||
for hit in hits:
|
||||
@@ -1124,10 +1133,6 @@ async def get_eu_cordis_projects_funding_data(
|
||||
"track_total_hits": False,
|
||||
"_source": ["id", "startDate", "endDate", "ecMaxContribution"],
|
||||
"query": query,
|
||||
# "id" is unique per project and used elsewhere as a term-filter
|
||||
# field, so it's mapped as keyword - safe + deterministic sort
|
||||
# key for search_after pagination across an arbitrarily large
|
||||
# result set.
|
||||
"sort": [{"id": {"order": "asc", "unmapped_type": "keyword"}}],
|
||||
}
|
||||
if search_after is not None:
|
||||
@@ -1247,68 +1252,6 @@ async def get_openalex_author_ids_by_dois(
|
||||
return result
|
||||
|
||||
|
||||
async def get_openalex_authors_for_cordis_project_ids(
|
||||
project_ids: list[str],
|
||||
) -> dict[str, AuthorPage]:
|
||||
"""Returns a mapping of project_id -> AuthorPage for a batch of projects."""
|
||||
if not project_ids:
|
||||
return {}
|
||||
|
||||
query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}}
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=["projectID", "doi","qaProcessedDoi"],
|
||||
size=10000,
|
||||
)
|
||||
dois_by_project: dict[str, set[str]] = {}
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
pid = source.get("projectID")
|
||||
doi = source.get("doi")
|
||||
qa_processed_doi = source.get("qaProcessedDoi")
|
||||
if pid:
|
||||
dois_by_project.setdefault(pid, set())
|
||||
if doi:
|
||||
dois_by_project[pid].add(doi)
|
||||
elif qa_processed_doi:
|
||||
dois_by_project[pid].add(qa_processed_doi)
|
||||
|
||||
all_dois = list({doi for dois in dois_by_project.values() for doi in dois})
|
||||
|
||||
# single ES call for the whole batch, keyed by raw DOI
|
||||
author_ids_by_doi = await get_openalex_author_ids_by_dois(dois=all_dois)
|
||||
|
||||
# aggregate per project, dedupe author_ids within a project
|
||||
author_ids_by_project: dict[str, list[str]] = {}
|
||||
for pid, dois in dois_by_project.items():
|
||||
project_author_ids: set[str] = set()
|
||||
for doi in dois:
|
||||
project_author_ids.update(author_ids_by_doi.get(doi, []))
|
||||
author_ids_by_project[pid] = list(project_author_ids)
|
||||
|
||||
# single ES call to fetch all Author objects across every project
|
||||
all_author_ids = list({aid for ids in author_ids_by_project.values() for aid in ids})
|
||||
|
||||
author_page = await get_authors_by_ids(author_ids=all_author_ids)
|
||||
authors_by_id = {author.id: author for author in author_page.elements}
|
||||
|
||||
# split the fetched authors back out per project
|
||||
result: dict[str, AuthorPage] = {}
|
||||
for pid in project_ids:
|
||||
ids_for_project = author_ids_by_project.get(pid, [])
|
||||
authors_for_project = [
|
||||
authors_by_id[aid] for aid in ids_for_project if aid in authors_by_id
|
||||
]
|
||||
result[pid] = AuthorPage(
|
||||
elements=authors_for_project,
|
||||
total=len(authors_for_project),
|
||||
page=0,
|
||||
size=len(authors_for_project),
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
async def get_openalex_authors_for_projects_ids(
|
||||
project_ids_by_type: dict[EuCordisProjectType, list[str]],
|
||||
@@ -1333,4 +1276,4 @@ async def get_openalex_authors_for_projects_ids(
|
||||
result[(project_type, pid)] = author_pages_by_project_id.get(
|
||||
pid, AuthorPage(elements=[], total=0, page=0, size=0)
|
||||
)
|
||||
return result
|
||||
return result
|
||||
|
||||
@@ -1,13 +1,49 @@
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
import inse.authors.v2.service as author_service
|
||||
from inse.auth.model import AccessTokenMetadata
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.projects.model import EuCordisProjectType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def is_projects_access_forbidden(
|
||||
access_token_metadata: AccessTokenMetadata,
|
||||
raw_oa_institution_id: str | None,
|
||||
raw_oa_author_id: str | None,
|
||||
) -> bool:
|
||||
"""
|
||||
Determines if access to projects is forbidden based on the provided access token metadata
|
||||
and the raw OpenAlex institution and author IDs.
|
||||
|
||||
Args:
|
||||
access_token_metadata (AccessTokenMetadata): Metadata from the access token.
|
||||
raw_oa_institution_id (str | None): The raw OpenAlex institution ID.
|
||||
raw_oa_author_id (str | None): The raw OpenAlex author ID.
|
||||
|
||||
Returns:
|
||||
bool: True if access is forbidden, False otherwise.
|
||||
"""
|
||||
effective_institution_id = access_token_metadata.effective_institution_id
|
||||
|
||||
if raw_oa_institution_id and effective_institution_id != raw_oa_institution_id:
|
||||
return True
|
||||
|
||||
if raw_oa_author_id:
|
||||
authors_profile = await author_service.get_author_by_id(raw_oa_author_id)
|
||||
if not authors_profile:
|
||||
return True # Author not found, access forbidden
|
||||
|
||||
authors_last_known_institution_ids = [inst.id.split("/")[-1] for inst in authors_profile.last_known_institutions]
|
||||
print(f"Author's last known institution IDs: {authors_last_known_institution_ids}")
|
||||
if effective_institution_id not in authors_last_known_institution_ids:
|
||||
return True # Effective institution ID does not match any of the author's last known institutions
|
||||
|
||||
return False
|
||||
|
||||
async def get_dfg_author_names_by_ids(author_ids: list[int]) -> list[str] | None:
|
||||
try:
|
||||
body = {
|
||||
|
||||
@@ -195,7 +195,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]):
|
||||
_type_: The retrieved publications.
|
||||
"""
|
||||
|
||||
query_dois = list({
|
||||
query_dois = set({
|
||||
variant
|
||||
for doi in dois
|
||||
for variant in (
|
||||
@@ -211,8 +211,8 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]):
|
||||
{
|
||||
"bool": {
|
||||
"should": [
|
||||
{"terms": {"doi": query_dois}},
|
||||
{"terms": {"qaProcessedDoi": query_dois}},
|
||||
{"terms": {"doi": list(query_dois)}},
|
||||
{"terms": {"qaProcessedDoi": list(query_dois)}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
@@ -223,6 +223,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]):
|
||||
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
size=10000,
|
||||
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
@@ -264,7 +265,7 @@ async def get_dfg_publications_by_dois(dois: list[str]):
|
||||
_type_: The retrieved publications.
|
||||
"""
|
||||
|
||||
query_dois = list({
|
||||
query_dois = set({
|
||||
variant
|
||||
for doi in dois
|
||||
for variant in (
|
||||
@@ -281,7 +282,7 @@ async def get_dfg_publications_by_dois(dois: list[str]):
|
||||
"query": {
|
||||
"terms": {
|
||||
"publications.doi":
|
||||
query_dois
|
||||
list(query_dois)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -291,7 +292,7 @@ async def get_dfg_publications_by_dois(dois: list[str]):
|
||||
}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
size=1000,
|
||||
size=10000,
|
||||
query=query,
|
||||
index=ESIndex.DFG_PROJECTS,
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -318,7 +319,7 @@ async def get_dfg_project_ids_by_names(names: list[str]) -> list[str]:
|
||||
|
||||
response = await elasticsearch.search(
|
||||
source=["projects.project_id"],
|
||||
size=1000,
|
||||
size=10000,
|
||||
query=query,
|
||||
index=ESIndex.DFG_PERSONS,
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -367,6 +368,7 @@ async def search_dfg_projects(
|
||||
sort_by: str = "id",
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
skip_enrichment: bool = False,
|
||||
) -> DfgProjectPage:
|
||||
"""Searches for DFG projects based on the provided filtering and sorting criteria.
|
||||
|
||||
@@ -607,6 +609,9 @@ async def search_dfg_projects(
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
if skip_enrichment:
|
||||
return _complete_response_to_dfg_project_page(response, page, size)
|
||||
|
||||
project_ids = [hit["_source"]["id"] for hit in hits]
|
||||
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids)
|
||||
|
||||
@@ -1197,4 +1202,4 @@ def _hit_to_funding_project(hit: dict[str, Any]) -> FundingProject:
|
||||
else:
|
||||
raise ValueError(
|
||||
"The provided hit does not belong to a recognized project index."
|
||||
)
|
||||
)
|
||||
|
||||
@@ -2,6 +2,8 @@ import logging
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Path, Query, status
|
||||
from inse.auth.model import AccessTokenMetadata
|
||||
from inse.auth.service import CurrentUserAccessTokenPayloadDep
|
||||
from inse.institutions.institutions_search_client import (
|
||||
InstitutionsSearchClient,
|
||||
)
|
||||
@@ -63,6 +65,105 @@ async def search_bund_projects(
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/dfg/search",
|
||||
summary="Get DFG projects.",
|
||||
description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.",
|
||||
operation_id="getDfgProjects",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": DfgProjectPage,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||
status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def get_dfg_projects(
|
||||
access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep],
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
raw_oa_institution_id: Annotated[
|
||||
str | None, Query(description="The openalex institution ID to filter by.")
|
||||
] = None,
|
||||
author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None,
|
||||
author_filter_ids: Annotated[list[int] | None, Query(description="The dfg author IDs to filter by.")] = None,
|
||||
institution_ids: Annotated[
|
||||
list[int] | None, Query(description="The institution IDs to filter by.")
|
||||
] = None,
|
||||
title: Annotated[
|
||||
str | None, Query(description="The title to filter by.")
|
||||
] = None,
|
||||
keywords: Annotated[
|
||||
list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.")
|
||||
] = None,
|
||||
topic_ids: Annotated[
|
||||
list[str] | None, Query(description="The openalex topic IDs to filter by.")
|
||||
] = None,
|
||||
filter_topic_ids: Annotated[
|
||||
list[str] | None,
|
||||
Query(
|
||||
description="Additional topic IDs to merge into the fuzzy topic-id resolution "
|
||||
"(union with topic_ids). Only used when fuzzy=True."
|
||||
),
|
||||
] = None,
|
||||
funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None,
|
||||
funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None,
|
||||
|
||||
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
||||
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
|
||||
sort_by: Annotated[str, Query(description="The field to sort by.")] = "title",
|
||||
sort_direction: Annotated[
|
||||
str, Query(description="The sort direction (asc or desc).")
|
||||
] = "asc",
|
||||
fuzzy: Annotated[
|
||||
bool,
|
||||
Query(description="Use topic_id resolution if True, otherwise use raw keyword search."),
|
||||
] = False,
|
||||
|
||||
) -> DfgProjectPage:
|
||||
logger.debug(
|
||||
"Received request to get DFG projects for author_id=%s, author_filter_ids=%s, "
|
||||
"institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, "
|
||||
"funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, "
|
||||
"sort_direction=%s, fuzzy=%s",
|
||||
author_id,
|
||||
author_filter_ids,
|
||||
institution_ids,
|
||||
keywords,
|
||||
topic_ids,
|
||||
filter_topic_ids,
|
||||
title,
|
||||
funding_start_years,
|
||||
funding_end_years,
|
||||
page,
|
||||
size,
|
||||
sort_by,
|
||||
sort_direction,
|
||||
fuzzy,
|
||||
)
|
||||
return await projects_service.get_dfg_projects_by_author_id(
|
||||
access_token_metadata=access_token_metadata,
|
||||
institutions_search_client=institutions_search_client,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
author_id=author_id,
|
||||
author_filter_ids=author_filter_ids,
|
||||
institution_ids=institution_ids,
|
||||
funding_start_years=funding_start_years,
|
||||
funding_end_years=funding_end_years,
|
||||
title=title,
|
||||
keywords=keywords,
|
||||
topic_ids=topic_ids,
|
||||
filter_topic_ids=filter_topic_ids,
|
||||
page=page,
|
||||
size=size,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
fuzzy=fuzzy,
|
||||
)
|
||||
|
||||
@router.get(
|
||||
"/dfg/{id}",
|
||||
summary="Get a single DFG project.",
|
||||
@@ -96,10 +197,13 @@ async def get_single_dfg_project(
|
||||
"description": "Successful Response",
|
||||
"model": BundProjectPage,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||
status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def search_bund_projects(
|
||||
access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep],
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
@@ -156,6 +260,7 @@ async def search_bund_projects(
|
||||
] = False,
|
||||
) -> BundProjectPage:
|
||||
return await projects_service.search_bund_projects_with_filters(
|
||||
access_token_metadata=access_token_metadata,
|
||||
institutions_search_client=institutions_search_client,
|
||||
executing_agency=executing_agency,
|
||||
funding_arts=funding_arts,
|
||||
@@ -217,10 +322,12 @@ from inse.projects.service import search_eu_cordis_projects
|
||||
"model": EuCordisProjectSearchPage,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||
status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def search_eu_cordis_projects_endpoint(
|
||||
access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep],
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
@@ -299,6 +406,7 @@ async def search_eu_cordis_projects_endpoint(
|
||||
bool,
|
||||
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
|
||||
] = False,
|
||||
|
||||
) -> EuCordisProjectSearchPage:
|
||||
logger.debug(
|
||||
"Received EU CORDIS search request: raw_oa_institution_id=%s, "
|
||||
@@ -332,6 +440,7 @@ async def search_eu_cordis_projects_endpoint(
|
||||
)
|
||||
|
||||
return await search_eu_cordis_projects(
|
||||
access_token_metadata=access_token_metadata,
|
||||
institutions_search_client=institutions_search_client,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
author_id=author_id,
|
||||
@@ -629,102 +738,6 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/person/dfg/search",
|
||||
summary="Get DFG projects.",
|
||||
description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.",
|
||||
operation_id="getDfgProjects",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": DfgProjectPage,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def get_dfg_projects(
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
raw_oa_institution_id: Annotated[
|
||||
str | None, Query(description="The openalex institution ID to filter by.")
|
||||
] = None,
|
||||
author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None,
|
||||
author_filter_ids: Annotated[list[int] | None, Query(description="The dfg author IDs to filter by.")] = None,
|
||||
institution_ids: Annotated[
|
||||
list[int] | None, Query(description="The institution IDs to filter by.")
|
||||
] = None,
|
||||
title: Annotated[
|
||||
str | None, Query(description="The title to filter by.")
|
||||
] = None,
|
||||
keywords: Annotated[
|
||||
list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.")
|
||||
] = None,
|
||||
topic_ids: Annotated[
|
||||
list[str] | None, Query(description="The openalex topic IDs to filter by.")
|
||||
] = None,
|
||||
filter_topic_ids: Annotated[
|
||||
list[str] | None,
|
||||
Query(
|
||||
description="Additional topic IDs to merge into the fuzzy topic-id resolution "
|
||||
"(union with topic_ids). Only used when fuzzy=True."
|
||||
),
|
||||
] = None,
|
||||
funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None,
|
||||
funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None,
|
||||
|
||||
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
||||
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
|
||||
sort_by: Annotated[str, Query(description="The field to sort by.")] = "title",
|
||||
sort_direction: Annotated[
|
||||
str, Query(description="The sort direction (asc or desc).")
|
||||
] = "asc",
|
||||
fuzzy: Annotated[
|
||||
bool,
|
||||
Query(description="Use topic_id resolution if True, otherwise use raw keyword search."),
|
||||
] = False,
|
||||
|
||||
) -> DfgProjectPage:
|
||||
logger.debug(
|
||||
"Received request to get DFG projects for author_id=%s, author_filter_ids=%s, "
|
||||
"institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, "
|
||||
"funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, "
|
||||
"sort_direction=%s, fuzzy=%s",
|
||||
author_id,
|
||||
author_filter_ids,
|
||||
institution_ids,
|
||||
keywords,
|
||||
topic_ids,
|
||||
filter_topic_ids,
|
||||
title,
|
||||
funding_start_years,
|
||||
funding_end_years,
|
||||
page,
|
||||
size,
|
||||
sort_by,
|
||||
sort_direction,
|
||||
fuzzy,
|
||||
)
|
||||
return await projects_service.get_dfg_projects_by_author_id(
|
||||
institutions_search_client=institutions_search_client,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
author_id=author_id,
|
||||
author_filter_ids=author_filter_ids,
|
||||
institution_ids=institution_ids,
|
||||
funding_start_years=funding_start_years,
|
||||
funding_end_years=funding_end_years,
|
||||
title=title,
|
||||
keywords=keywords,
|
||||
topic_ids=topic_ids,
|
||||
filter_topic_ids=filter_topic_ids,
|
||||
page=page,
|
||||
size=size,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
fuzzy=fuzzy,
|
||||
)
|
||||
|
||||
@router.get(
|
||||
"/search",
|
||||
summary="Search projects across all funders.",
|
||||
|
||||
@@ -3,6 +3,7 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.auth.model import AccessTokenMetadata
|
||||
from inse.institutions.institutions_search_client import (
|
||||
InstitutionsSearchClient,
|
||||
)
|
||||
@@ -27,7 +28,7 @@ from inse.projects.eu_cordis_projects_client import (
|
||||
search_eu_cordis_projects as _search_eu_cordis_projects_es,
|
||||
)
|
||||
from inse.projects.logic import (
|
||||
get_dfg_author_names_by_ids,
|
||||
get_dfg_author_names_by_ids, is_projects_access_forbidden
|
||||
)
|
||||
from inse.projects.model import (
|
||||
BundProjectPage,
|
||||
@@ -42,7 +43,7 @@ from inse.projects.model import (
|
||||
SortDirection,
|
||||
)
|
||||
from inse.works.logic import get_publication_dois_of_author
|
||||
|
||||
from fastapi import HTTPException as HttpException
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -158,6 +159,7 @@ async def _get_dfg_project_ids_for_openalex_authors(
|
||||
return list(set.intersection(*project_sets))
|
||||
|
||||
async def get_dfg_projects_by_author_id(
|
||||
access_token_metadata: AccessTokenMetadata,
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
raw_oa_institution_id: str | None,
|
||||
author_id: str | None,
|
||||
@@ -174,6 +176,7 @@ async def get_dfg_projects_by_author_id(
|
||||
sort_by: str = "topic",
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
skip_enrichment: bool = False,
|
||||
) -> DfgProjectPage:
|
||||
logger.debug(
|
||||
"Fetching DFG projects for author_id=%s, author_filter_ids=%s, "
|
||||
@@ -197,6 +200,12 @@ async def get_dfg_projects_by_author_id(
|
||||
)
|
||||
filter_names = []
|
||||
author_project_ids = []
|
||||
is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id)
|
||||
if is_forbidden:
|
||||
raise HttpException(
|
||||
status_code=403,
|
||||
detail="Access denied for the provided author ID or institution ID",
|
||||
)
|
||||
if author_id:
|
||||
author_project_ids = await _get_dfg_project_ids_for_openalex_authors([author_id])
|
||||
logger.info("Author project IDs for author_id:%s: %s", author_id, author_project_ids)
|
||||
@@ -220,6 +229,10 @@ async def get_dfg_projects_by_author_id(
|
||||
)
|
||||
institution_aliases = []
|
||||
if raw_oa_institution_id:
|
||||
if institutions_search_client is None:
|
||||
raise ValueError(
|
||||
"institutions_search_client must be provided when raw_oa_institution_id is set"
|
||||
)
|
||||
institution_aliases = (
|
||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
raw_oa_institution_id
|
||||
@@ -248,6 +261,7 @@ async def get_dfg_projects_by_author_id(
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
fuzzy=fuzzy,
|
||||
skip_enrichment=skip_enrichment,
|
||||
)
|
||||
|
||||
async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
@@ -407,6 +421,7 @@ async def get_institution_bund_projects_funding_over_time(
|
||||
|
||||
#Bund
|
||||
async def search_bund_projects_with_filters(
|
||||
access_token_metadata: AccessTokenMetadata,
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
executing_agency: str | None,
|
||||
raw_oa_institution_id: str | None,
|
||||
@@ -424,8 +439,18 @@ async def search_bund_projects_with_filters(
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
) -> BundProjectPage:
|
||||
is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, None)
|
||||
if is_forbidden:
|
||||
raise HttpException(
|
||||
status_code=403,
|
||||
detail="Access denied for the provided author ID or institution ID",
|
||||
)
|
||||
institution_aliases = []
|
||||
if raw_oa_institution_id:
|
||||
if institutions_search_client is None:
|
||||
raise ValueError(
|
||||
"institutions_search_client must be provided when raw_oa_institution_id is set"
|
||||
)
|
||||
institution_aliases = (
|
||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
raw_oa_institution_id
|
||||
@@ -601,6 +626,7 @@ async def _get_eu_project_ids_for_openalex_authors(
|
||||
|
||||
|
||||
async def search_eu_cordis_projects(
|
||||
access_token_metadata: AccessTokenMetadata,
|
||||
page: int,
|
||||
size: int,
|
||||
project_types: list[EuCordisProjectType] | None = None,
|
||||
@@ -623,6 +649,7 @@ async def search_eu_cordis_projects(
|
||||
sort_by: str = "title",
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
skip_enrichment: bool = False,
|
||||
) -> EuCordisProjectSearchPage:
|
||||
"""Single entry point for EU CORDIS project search.
|
||||
|
||||
@@ -638,8 +665,13 @@ async def search_eu_cordis_projects(
|
||||
funding scheme, status, funding years, country) are ANDed together as in
|
||||
eu_cordis_projects_client.search_eu_cordis_projects.
|
||||
"""
|
||||
is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id)
|
||||
if is_forbidden:
|
||||
raise HttpException(
|
||||
status_code=403,
|
||||
detail="Access denied for the provided author ID or institution ID",
|
||||
)
|
||||
resolved_organization_names: list[str] = list(organization_names or [])
|
||||
|
||||
if raw_oa_institution_id:
|
||||
if institutions_search_client is None:
|
||||
raise ValueError(
|
||||
@@ -683,4 +715,5 @@ async def search_eu_cordis_projects(
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
fuzzy=fuzzy,
|
||||
)
|
||||
skip_enrichment=skip_enrichment,
|
||||
)
|
||||
|
||||
@@ -3,11 +3,10 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from math import floor
|
||||
from time import time
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from inse.authors.institution_membership_query import (
|
||||
build_active_institution_membership_query,
|
||||
)
|
||||
@@ -746,15 +745,29 @@ def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor:
|
||||
)
|
||||
|
||||
|
||||
def _min_max_normalize(values: pd.Series) -> pd.Series:
|
||||
def _quantile(values: list[float], quantile: float) -> float:
|
||||
"""Returns a linearly interpolated quantile (the former pandas default)."""
|
||||
ordered = sorted(values)
|
||||
if not ordered:
|
||||
return 0.0
|
||||
position = (len(ordered) - 1) * quantile
|
||||
lower_index = floor(position)
|
||||
upper_index = min(lower_index + 1, len(ordered) - 1)
|
||||
fraction = position - lower_index
|
||||
return ordered[lower_index] + (
|
||||
ordered[upper_index] - ordered[lower_index]
|
||||
) * fraction
|
||||
|
||||
|
||||
def _min_max_normalize(values: list[float]) -> list[float]:
|
||||
"""Scales a numeric column to the range [0, 1] via min-max normalization."""
|
||||
minimum = values.min()
|
||||
maximum = values.max()
|
||||
minimum = min(values)
|
||||
maximum = max(values)
|
||||
# if all values are the same, return a series of 1.0 to avoid division by zero.
|
||||
if maximum == minimum:
|
||||
return pd.Series([1.0] * len(values))
|
||||
return [1.0] * len(values)
|
||||
|
||||
return (values - minimum) / (maximum - minimum)
|
||||
return [(value - minimum) / (maximum - minimum) for value in values]
|
||||
|
||||
|
||||
def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None:
|
||||
@@ -775,38 +788,29 @@ def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None:
|
||||
news_counts.append(author.news_count)
|
||||
patents_counts.append(author.patents_count)
|
||||
|
||||
frame = pd.DataFrame({
|
||||
"works": works_counts,
|
||||
"citations": citations_counts,
|
||||
"companies": companies_counts,
|
||||
"news": news_counts,
|
||||
"patents": patents_counts,
|
||||
})
|
||||
|
||||
quantile_value = 0.95
|
||||
|
||||
frame["works"] = frame["works"].clip(upper=frame["works"].quantile(quantile_value))
|
||||
frame["citations"] = frame["citations"].clip(upper=frame["citations"].quantile(quantile_value))
|
||||
frame["companies"] = frame["companies"].clip(upper=frame["companies"].quantile(quantile_value))
|
||||
frame["news"] = frame["news"].clip(upper=frame["news"].quantile(quantile_value))
|
||||
frame["patents"] = frame["patents"].clip(upper=frame["patents"].quantile(quantile_value))
|
||||
|
||||
works_normalized = _min_max_normalize(frame["works"])
|
||||
citations_normalized = _min_max_normalize(frame["citations"])
|
||||
companies_normalized = _min_max_normalize(frame["companies"])
|
||||
news_normalized = _min_max_normalize(frame["news"])
|
||||
patents_normalized = _min_max_normalize(frame["patents"])
|
||||
|
||||
scores = (
|
||||
works_normalized * weights.works
|
||||
+ citations_normalized * weights.citation
|
||||
+ companies_normalized * weights.companies
|
||||
+ news_normalized * weights.news
|
||||
+ patents_normalized * weights.patents
|
||||
)
|
||||
metrics = [
|
||||
works_counts,
|
||||
citations_counts,
|
||||
companies_counts,
|
||||
news_counts,
|
||||
patents_counts,
|
||||
]
|
||||
normalized_metrics = [
|
||||
_min_max_normalize(
|
||||
[min(value, _quantile(values, quantile_value)) for value in values]
|
||||
)
|
||||
for values in metrics
|
||||
]
|
||||
|
||||
for index, author in enumerate(authors):
|
||||
author.score = float(scores.iloc[index])
|
||||
author.score = float(
|
||||
normalized_metrics[0][index] * weights.works
|
||||
+ normalized_metrics[1][index] * weights.citation
|
||||
+ normalized_metrics[2][index] * weights.companies
|
||||
+ normalized_metrics[3][index] * weights.news
|
||||
+ normalized_metrics[4][index] * weights.patents
|
||||
)
|
||||
|
||||
|
||||
def _author_score(author: RankedAuthor) -> float:
|
||||
|
||||
@@ -654,6 +654,7 @@ async def _search_works(
|
||||
size=size,
|
||||
offset=page * size,
|
||||
sort=sort,
|
||||
track_total_hits=True
|
||||
)
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
|
||||
@@ -66,7 +66,7 @@ export class ProjectsService extends BaseService {
|
||||
/**
|
||||
* Get DFG projects.
|
||||
* Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.
|
||||
* @endpoint get /api/projects/person/dfg/search
|
||||
* @endpoint get /api/projects/dfg/search
|
||||
* @param rawOaInstitutionId The openalex institution ID to filter by.
|
||||
* @param authorId The openalex author ID to filter by.
|
||||
* @param authorFilterIds The dfg author IDs to filter by.
|
||||
@@ -82,13 +82,14 @@ export class ProjectsService extends BaseService {
|
||||
* @param sortBy The field to sort by.
|
||||
* @param sortDirection The sort direction (asc or desc).
|
||||
* @param fuzzy Use topic_id resolution if True, otherwise use raw keyword search.
|
||||
* @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 getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgProjectPage>;
|
||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgProjectPage>>;
|
||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgProjectPage>>;
|
||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgProjectPage>;
|
||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgProjectPage>>;
|
||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgProjectPage>>;
|
||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: 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,
|
||||
@@ -152,6 +153,9 @@ export class ProjectsService extends BaseService {
|
||||
|
||||
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'
|
||||
]);
|
||||
@@ -175,7 +179,7 @@ export class ProjectsService extends BaseService {
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/projects/person/dfg/search`;
|
||||
let localVarPath = `/api/projects/dfg/search`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<DfgProjectPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
@@ -846,13 +850,14 @@ export class ProjectsService extends BaseService {
|
||||
* @param sortBy Sort field.
|
||||
* @param sortDirection Sort direction: asc or desc.
|
||||
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
|
||||
* @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 searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<BundProjectPage>;
|
||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<BundProjectPage>>;
|
||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<BundProjectPage>>;
|
||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<BundProjectPage>;
|
||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<BundProjectPage>>;
|
||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<BundProjectPage>>;
|
||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: 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 (executingAgency) {
|
||||
@@ -920,6 +925,9 @@ export class ProjectsService extends BaseService {
|
||||
|
||||
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'
|
||||
]);
|
||||
@@ -984,13 +992,14 @@ export class ProjectsService extends BaseService {
|
||||
* @param sortBy Sort field.
|
||||
* @param sortDirection Sort direction: asc or desc.
|
||||
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
|
||||
* @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 searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<EuCordisProjectSearchPage>;
|
||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<EuCordisProjectSearchPage>>;
|
||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<EuCordisProjectSearchPage>>;
|
||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<EuCordisProjectSearchPage>;
|
||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<EuCordisProjectSearchPage>>;
|
||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<EuCordisProjectSearchPage>>;
|
||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: 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,
|
||||
@@ -1090,6 +1099,9 @@ export class ProjectsService extends BaseService {
|
||||
|
||||
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'
|
||||
]);
|
||||
|
||||
@@ -693,7 +693,9 @@ export const routes: Routes = [
|
||||
bundProjectsFunding: bundProjectsFundingResolver,
|
||||
cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
|
||||
},
|
||||
runGuardsAndResolvers: 'always',
|
||||
data: {
|
||||
enableFilters: false,
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: '',
|
||||
@@ -743,18 +745,6 @@ export const routes: Routes = [
|
||||
},
|
||||
},
|
||||
],
|
||||
// resolve: {
|
||||
// bundProjectPage: bundProjectPageResolver,
|
||||
// bundProjectsFunding: bundProjectsFundingResolver,
|
||||
// cordisEuProjectPage: euCordisProjectsResolver,
|
||||
// cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
|
||||
// },
|
||||
// runGuardsAndResolvers: (from, to) => {
|
||||
// const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
|
||||
// return keys.some(
|
||||
// (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
|
||||
// );
|
||||
// },
|
||||
},
|
||||
{
|
||||
path: 'patents',
|
||||
|
||||
@@ -1,30 +1,15 @@
|
||||
<div class="content">
|
||||
<h3>Projekte</h3>
|
||||
<div>
|
||||
<h6>Projekte</h6>
|
||||
<p>Übersicht der Projekte, die von der Institution durchgeführt werden.</p>
|
||||
</div>
|
||||
|
||||
<div class="funding-area">
|
||||
<div class="person-projects">
|
||||
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
|
||||
@for (route of childRoutes; track route.path) {
|
||||
<a
|
||||
matTabLink
|
||||
[routerLink]="[route.path]"
|
||||
[queryParams]="{
|
||||
authorId: null,
|
||||
institutionId: null,
|
||||
agency: null,
|
||||
}"
|
||||
queryParamsHandling="merge"
|
||||
routerLinkActive
|
||||
#rla="routerLinkActive"
|
||||
[active]="rla.isActive">
|
||||
{{ route.label }}
|
||||
</a>
|
||||
}
|
||||
</nav>
|
||||
<mat-accordion multi>
|
||||
<mat-expansion-panel class="mat-elevation-z1">
|
||||
<mat-expansion-panel-header>
|
||||
<mat-panel-title>Förderung über Zeit</mat-panel-title>
|
||||
</mat-expansion-panel-header>
|
||||
|
||||
<mat-tab-nav-panel #resultTabPanel>
|
||||
<router-outlet />
|
||||
</mat-tab-nav-panel>
|
||||
<div class="funding-info-section">
|
||||
<mat-card appearance="outlined">
|
||||
<mat-card-header>
|
||||
@@ -56,15 +41,35 @@
|
||||
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
|
||||
" />
|
||||
<app-info-card
|
||||
[description]="'Durchschnittliche jährliche Förderung durch die Europäische Union'"
|
||||
[description]="
|
||||
'Durchschnittliche jährliche Förderung durch die Europäische Union'
|
||||
"
|
||||
[value]="
|
||||
(euAverageAnnualFunding()
|
||||
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
|
||||
" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</mat-expansion-panel>
|
||||
|
||||
<mat-expansion-panel class="mat-elevation-z1" [expanded]="true">
|
||||
<mat-expansion-panel-header>
|
||||
<mat-panel-title>Projektliste</mat-panel-title>
|
||||
</mat-expansion-panel-header>
|
||||
|
||||
<div class="person-projects">
|
||||
@if (resultTabPanel) {
|
||||
<app-link-tab-nav-bar
|
||||
[links]="_links()"
|
||||
[tabPanel]="resultTabPanel" />
|
||||
}
|
||||
|
||||
<mat-tab-nav-panel #resultTabPanel>
|
||||
<router-outlet />
|
||||
</mat-tab-nav-panel>
|
||||
</div>
|
||||
</mat-expansion-panel>
|
||||
</mat-accordion>
|
||||
|
||||
<ng-template #fundingStartTmp let-row>
|
||||
{{ row.funding_start | date: 'dd.MM.yyyy' }}
|
||||
@@ -79,8 +84,8 @@
|
||||
<ng-template #euProjectActionsTmp let-row>
|
||||
<a mat-icon-button color="primary" [routerLink]="['/projects/eu', row.id]">
|
||||
<mat-icon>open_in_new</mat-icon>
|
||||
</a></ng-template
|
||||
>
|
||||
</a>
|
||||
</ng-template>
|
||||
|
||||
<ng-template #bundProjectActionsTmp let-row>
|
||||
<a
|
||||
|
||||
@@ -1,22 +1,30 @@
|
||||
.content {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
mat-card,
|
||||
mat-paginator {
|
||||
background-color: var(--sg-background);
|
||||
}
|
||||
|
||||
.funding-area {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.funding-info-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
mat-expansion-panel {
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: var(--sg-radius-sm);
|
||||
background: var(--sg-none);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
mat-expansion-panel-header {
|
||||
padding: 0 16px;
|
||||
min-height: 48px;
|
||||
}
|
||||
|
||||
mat-panel-title {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
mat-panel-description {
|
||||
font-size: 14px;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
.funding-info-cards {
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import { BundProjectSummary } from '../../api/model/bundProjectSummary';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatExpansionModule } from '@angular/material/expansion';
|
||||
import { MatTabChangeEvent, MatTabsModule } from '@angular/material/tabs';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
@@ -27,7 +28,10 @@ import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { InstitutionProjectsFundingGraphComponent } from '../institution-projects-funding-graph/institution-projects-funding-graph.component';
|
||||
import { AppInfoCardComponent } from '../../shared/ui/app-info-card/app-info-card.component';
|
||||
|
||||
import {
|
||||
LinkTabNavBarComponent,
|
||||
LinkTabNavBarItem,
|
||||
} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
|
||||
type BundProjectRow = {
|
||||
id: string;
|
||||
topic: string;
|
||||
@@ -51,6 +55,7 @@ type EuProjectRow = {
|
||||
MatCardModule,
|
||||
MatFormFieldModule,
|
||||
MatTabsModule,
|
||||
MatExpansionModule,
|
||||
FormsModule,
|
||||
MatInputModule,
|
||||
DatePipe,
|
||||
@@ -59,6 +64,7 @@ type EuProjectRow = {
|
||||
MatButtonModule,
|
||||
InstitutionProjectsFundingGraphComponent,
|
||||
AppInfoCardComponent,
|
||||
LinkTabNavBarComponent,
|
||||
RouterModule,
|
||||
],
|
||||
templateUrl: './institution-projects.component.html',
|
||||
@@ -122,6 +128,27 @@ export class InstitutionProjectsComponent implements OnInit {
|
||||
label: 'BUND-Projekte',
|
||||
},
|
||||
];
|
||||
|
||||
_links = computed<LinkTabNavBarItem[]>(() => {
|
||||
const links: LinkTabNavBarItem[] = [
|
||||
{
|
||||
label: 'DFG-Projekte',
|
||||
path: 'dfg',
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: 'EU-Projekte',
|
||||
path: 'eu',
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: 'BUND-Projekte',
|
||||
path: 'bund',
|
||||
disabled: false,
|
||||
},
|
||||
];
|
||||
return links;
|
||||
});
|
||||
constructor(
|
||||
private readonly activatedRoute: ActivatedRoute,
|
||||
private readonly router: Router,
|
||||
@@ -275,12 +302,4 @@ export class InstitutionProjectsComponent implements OnInit {
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
|
||||
selectedTabChange(event: MatTabChangeEvent): void {
|
||||
const tab = ['eu', 'bund'][event.index];
|
||||
this.router.navigate([], {
|
||||
queryParams: { project_tab: tab, page: 0, size: 10 },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+1
-2
@@ -16,8 +16,7 @@
|
||||
<mat-expansion-panel class="mat-elevation-z1" [expanded]="true">
|
||||
<mat-expansion-panel-header>
|
||||
<mat-panel-title>Publikationsliste</mat-panel-title>
|
||||
<mat-panel-description
|
||||
>{{ total() >= 10000 ? 'mehr als' : '' }}
|
||||
<mat-panel-description>
|
||||
{{ total() }} Publikationen</mat-panel-description
|
||||
>
|
||||
</mat-expansion-panel-header>
|
||||
|
||||
+3
-18
@@ -4,24 +4,9 @@
|
||||
<p>Übersicht der durchgeführten Projekte.</p>
|
||||
</div>
|
||||
|
||||
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
|
||||
@for (route of childRoutes; track route.path) {
|
||||
<a
|
||||
matTabLink
|
||||
[routerLink]="[route.path]"
|
||||
[queryParams]="{
|
||||
authorId: null,
|
||||
institutionId: null,
|
||||
agency: null,
|
||||
}"
|
||||
queryParamsHandling="merge"
|
||||
routerLinkActive
|
||||
#rla="routerLinkActive"
|
||||
[active]="rla.isActive">
|
||||
{{ route.label }}
|
||||
</a>
|
||||
}
|
||||
</nav>
|
||||
@if (resultTabPanel) {
|
||||
<app-link-tab-nav-bar [links]="_links()" [tabPanel]="resultTabPanel" />
|
||||
}
|
||||
|
||||
<mat-tab-nav-panel #resultTabPanel>
|
||||
<router-outlet />
|
||||
|
||||
+31
-22
@@ -6,16 +6,13 @@ import { MatTabsModule } from '@angular/material/tabs';
|
||||
import { OnInit, computed } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
|
||||
import {
|
||||
LinkTabNavBarComponent,
|
||||
LinkTabNavBarItem,
|
||||
} from '../../../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
|
||||
@Component({
|
||||
selector: 'app-projects-results',
|
||||
imports: [
|
||||
MatCardModule,
|
||||
MatTabsModule,
|
||||
RouterLink,
|
||||
RouterLinkActive,
|
||||
RouterOutlet,
|
||||
],
|
||||
imports: [MatCardModule, MatTabsModule, RouterOutlet, LinkTabNavBarComponent],
|
||||
templateUrl: './projects-results.component.html',
|
||||
styleUrl: './projects-results.component.scss',
|
||||
})
|
||||
@@ -32,18 +29,30 @@ export class KeywordsToProjectsResultsComponent {
|
||||
() => this.queryParamMap().get('fuzzy') === 'true',
|
||||
);
|
||||
|
||||
readonly childRoutes = [
|
||||
{
|
||||
path: 'dfg',
|
||||
label: 'DFG-Projekte',
|
||||
},
|
||||
{
|
||||
path: 'eu',
|
||||
label: 'EU-Projekte',
|
||||
},
|
||||
{
|
||||
path: 'bund',
|
||||
label: 'BUND-Projekte',
|
||||
},
|
||||
];
|
||||
_links = computed<LinkTabNavBarItem[]>(() => {
|
||||
const links: LinkTabNavBarItem[] = [
|
||||
{
|
||||
label: 'DFG-Projekte',
|
||||
path: 'dfg',
|
||||
queryParams: { authorId: null, institutionId: null, agency: null },
|
||||
queryParamsHandling: 'merge',
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: 'EU-Projekte',
|
||||
path: 'eu',
|
||||
queryParams: { authorId: null, institutionId: null, agency: null },
|
||||
queryParamsHandling: 'merge',
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: 'BUND-Projekte',
|
||||
path: 'bund',
|
||||
queryParams: { authorId: null, institutionId: null, agency: null },
|
||||
queryParamsHandling: 'merge',
|
||||
disabled: false,
|
||||
},
|
||||
];
|
||||
return links;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,22 +1,7 @@
|
||||
<div class="person-projects">
|
||||
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
|
||||
@for (route of childRoutes; track route.path) {
|
||||
<a
|
||||
matTabLink
|
||||
[routerLink]="[route.path]"
|
||||
[queryParams]="{
|
||||
authorId: null,
|
||||
institutionId: null,
|
||||
agency: null,
|
||||
}"
|
||||
queryParamsHandling="merge"
|
||||
routerLinkActive
|
||||
#rla="routerLinkActive"
|
||||
[active]="rla.isActive">
|
||||
{{ route.label }}
|
||||
</a>
|
||||
}
|
||||
</nav>
|
||||
@if (resultTabPanel) {
|
||||
<app-link-tab-nav-bar [links]="_links()" [tabPanel]="resultTabPanel" />
|
||||
}
|
||||
|
||||
<mat-tab-nav-panel #resultTabPanel>
|
||||
<router-outlet />
|
||||
|
||||
@@ -1,31 +1,33 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { Component, computed } from '@angular/core';
|
||||
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
|
||||
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatTabsModule } from '@angular/material/tabs';
|
||||
|
||||
import {
|
||||
LinkTabNavBarComponent,
|
||||
LinkTabNavBarItem,
|
||||
} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
|
||||
@Component({
|
||||
selector: 'app-person-projects',
|
||||
standalone: true,
|
||||
imports: [
|
||||
MatCardModule,
|
||||
MatTabsModule,
|
||||
RouterOutlet,
|
||||
RouterLink,
|
||||
RouterLinkActive,
|
||||
],
|
||||
imports: [MatCardModule, MatTabsModule, RouterOutlet, LinkTabNavBarComponent],
|
||||
templateUrl: './person-projects.component.html',
|
||||
styleUrl: './person-projects.component.scss',
|
||||
})
|
||||
export class PersonProjectsComponent {
|
||||
readonly childRoutes = [
|
||||
{
|
||||
path: 'dfg',
|
||||
label: 'DFG-Projekte',
|
||||
},
|
||||
{
|
||||
path: 'eu',
|
||||
label: 'EU-Projekte',
|
||||
},
|
||||
];
|
||||
_links = computed<LinkTabNavBarItem[]>(() => {
|
||||
const links: LinkTabNavBarItem[] = [
|
||||
{
|
||||
label: 'DFG-Projekte',
|
||||
path: 'dfg',
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: 'EU-Projekte',
|
||||
path: 'eu',
|
||||
disabled: false,
|
||||
},
|
||||
];
|
||||
return links;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -15,7 +15,22 @@ export const bundProjectsFundingResolver: ResolveFn<
|
||||
'Institution ID is required to resolve BUND projects funding',
|
||||
);
|
||||
}
|
||||
const filtersEnabled = route.data['enableFilters'] ?? false;
|
||||
|
||||
if (!filtersEnabled) {
|
||||
return inject(ProjectsService).getInstitutionBundProjectsFundingOverTime(
|
||||
institutionId,
|
||||
[],
|
||||
[],
|
||||
undefined,
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
undefined,
|
||||
);
|
||||
}
|
||||
const fundingStartYears = route.queryParamMap.getAll(
|
||||
bundProjectQueryParamKeys.funding_start,
|
||||
);
|
||||
|
||||
@@ -15,62 +15,90 @@ export const cordisEuProjectsFundingResolver: ResolveFn<
|
||||
'Institution ID is required to resolve Cordis EU projects funding',
|
||||
);
|
||||
}
|
||||
const filtersEnabled = route.data['enableFilters'] ?? false;
|
||||
if (!filtersEnabled) {
|
||||
return inject(
|
||||
ProjectsService,
|
||||
).getInstitutionCordisEuProjectsFundingOverTime(
|
||||
institutionId,
|
||||
undefined, // authorId (single) - institution view doesn't use this
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
undefined,
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
undefined,
|
||||
);
|
||||
} else {
|
||||
const searchTerm =
|
||||
route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined;
|
||||
|
||||
const searchTerm =
|
||||
route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined;
|
||||
const fundingStart = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.funding_start,
|
||||
);
|
||||
const fundingEnd = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.funding_end,
|
||||
);
|
||||
|
||||
const fundingStart = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.funding_start,
|
||||
);
|
||||
const fundingEnd = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.funding_end,
|
||||
);
|
||||
const filteredTopicIds = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.topicId,
|
||||
);
|
||||
|
||||
const filteredTopicIds = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.topicId,
|
||||
);
|
||||
const projectTypes = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.projectType,
|
||||
);
|
||||
|
||||
const projectTypes = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.projectType,
|
||||
);
|
||||
const organizationIds = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.institutionId,
|
||||
);
|
||||
|
||||
const organizationIds = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.institutionId,
|
||||
);
|
||||
const authorIds = route.queryParamMap
|
||||
.getAll(euProjectQueryParamKeys.authorId)
|
||||
.map((id) => id.split('/').pop() || id);
|
||||
|
||||
const authorIds = route.queryParamMap
|
||||
.getAll(euProjectQueryParamKeys.authorId)
|
||||
.map((id) => id.split('/').pop() || id);
|
||||
const countries = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.country,
|
||||
);
|
||||
|
||||
const countries = route.queryParamMap.getAll(euProjectQueryParamKeys.country);
|
||||
const frameworkProgrammes = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.frameworkProgramme,
|
||||
);
|
||||
|
||||
const frameworkProgrammes = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.frameworkProgramme,
|
||||
);
|
||||
const fundingSchemes = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.fundingScheme,
|
||||
);
|
||||
|
||||
const fundingSchemes = route.queryParamMap.getAll(
|
||||
euProjectQueryParamKeys.fundingScheme,
|
||||
);
|
||||
const statuses = route.queryParamMap.getAll(euProjectQueryParamKeys.status);
|
||||
|
||||
const statuses = route.queryParamMap.getAll(euProjectQueryParamKeys.status);
|
||||
|
||||
return inject(ProjectsService).getInstitutionCordisEuProjectsFundingOverTime(
|
||||
institutionId,
|
||||
undefined, // authorId (single) - institution view doesn't use this
|
||||
authorIds,
|
||||
organizationIds,
|
||||
[], // organizationNames
|
||||
projectTypes as any,
|
||||
searchTerm,
|
||||
[], // keywords - institution view doesn't use free-text keywords
|
||||
[], // topicIds (fuzzy) - institution view doesn't use fuzzy topic search
|
||||
filteredTopicIds,
|
||||
fundingStart,
|
||||
fundingEnd,
|
||||
countries,
|
||||
frameworkProgrammes,
|
||||
fundingSchemes,
|
||||
statuses,
|
||||
false, // fuzzy
|
||||
);
|
||||
return inject(
|
||||
ProjectsService,
|
||||
).getInstitutionCordisEuProjectsFundingOverTime(
|
||||
institutionId,
|
||||
undefined, // authorId (single) - institution view doesn't use this
|
||||
authorIds,
|
||||
organizationIds,
|
||||
[], // organizationNames
|
||||
projectTypes as any,
|
||||
searchTerm,
|
||||
[], // keywords - institution view doesn't use free-text keywords
|
||||
[], // topicIds (fuzzy) - institution view doesn't use fuzzy topic search
|
||||
filteredTopicIds,
|
||||
fundingStart,
|
||||
fundingEnd,
|
||||
countries,
|
||||
frameworkProgrammes,
|
||||
fundingSchemes,
|
||||
statuses,
|
||||
false, // fuzzy
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { ResolveFn } from '@angular/router';
|
||||
import { of } from 'rxjs';
|
||||
import { DfgProjectPage, ProjectsService } from '../api';
|
||||
|
||||
export const dfgProjectQueryParamKeys = {
|
||||
@@ -24,6 +25,34 @@ export const RESOLVING_PROJECT_PAGE_FOR = {
|
||||
KEYWORDS_SEARCH: 'KEYWORDS_SEARCH',
|
||||
} as const;
|
||||
|
||||
// Empty page returned whenever a required numeric param fails to parse.
|
||||
const EMPTY_DFG_PROJECT_PAGE: DfgProjectPage = {
|
||||
page: 0,
|
||||
size: 0,
|
||||
total: 0,
|
||||
elements: [],
|
||||
} as DfgProjectPage;
|
||||
|
||||
function toNumberOrNull(value: unknown): number | null {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return null;
|
||||
}
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
function toNumberArrayOrNull(values: string[]): number[] | null {
|
||||
const result: number[] = [];
|
||||
for (const value of values) {
|
||||
const parsed = toNumberOrNull(value);
|
||||
if (parsed === null) {
|
||||
return null;
|
||||
}
|
||||
result.push(parsed);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export const dfgProjectsResolver: ResolveFn<DfgProjectPage> = (
|
||||
route,
|
||||
state,
|
||||
@@ -40,9 +69,12 @@ export const dfgProjectsResolver: ResolveFn<DfgProjectPage> = (
|
||||
);
|
||||
|
||||
const page =
|
||||
Number(route.queryParamMap.get(dfgProjectQueryParamKeys.page)) || 0;
|
||||
toNumberOrNull(route.queryParamMap.get(dfgProjectQueryParamKeys.page)) ?? 0;
|
||||
|
||||
const size =
|
||||
Number(route.queryParamMap.get(dfgProjectQueryParamKeys.size)) || 10;
|
||||
toNumberOrNull(route.queryParamMap.get(dfgProjectQueryParamKeys.size)) ??
|
||||
10;
|
||||
|
||||
const searchTerm =
|
||||
route.queryParamMap.get(dfgProjectQueryParamKeys.title) ?? undefined;
|
||||
const sortBy =
|
||||
@@ -59,12 +91,16 @@ export const dfgProjectsResolver: ResolveFn<DfgProjectPage> = (
|
||||
const filteredTopicIds = route.queryParamMap.getAll(
|
||||
dfgProjectQueryParamKeys.topicId,
|
||||
);
|
||||
const institutionIds = route.queryParamMap
|
||||
.getAll(dfgProjectQueryParamKeys.institutionId)
|
||||
.map((id) => Number(id));
|
||||
const authorIds = route.queryParamMap
|
||||
.getAll(dfgProjectQueryParamKeys.authorId)
|
||||
.map((id) => Number(id));
|
||||
|
||||
const institutionIds = toNumberArrayOrNull(
|
||||
route.queryParamMap.getAll(dfgProjectQueryParamKeys.institutionId),
|
||||
);
|
||||
const authorIds = toNumberArrayOrNull(
|
||||
route.queryParamMap.getAll(dfgProjectQueryParamKeys.authorId),
|
||||
);
|
||||
if (institutionIds === null || authorIds === null) {
|
||||
return of(EMPTY_DFG_PROJECT_PAGE);
|
||||
}
|
||||
|
||||
if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) {
|
||||
const rawAuthorId = route.parent?.parent?.params['id'];
|
||||
@@ -108,6 +144,7 @@ export const dfgProjectsResolver: ResolveFn<DfgProjectPage> = (
|
||||
);
|
||||
} else if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.INSTITUTION) {
|
||||
const oaInstitutionId = route.parent?.parent?.params['institutionId'];
|
||||
|
||||
console.log(
|
||||
'Resolving project page for institution',
|
||||
oaInstitutionId,
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
mat-tab-link
|
||||
[routerLink]="link.path"
|
||||
[queryParams]="link.queryParams"
|
||||
[queryParamsHandling]="link.queryParamsHandling"
|
||||
routerLinkActive
|
||||
#rla="routerLinkActive"
|
||||
[active]="rla.isActive"
|
||||
|
||||
@@ -14,6 +14,7 @@ export type LinkTabNavBarItem = {
|
||||
icon?: string;
|
||||
description?: string;
|
||||
queryParams?: Record<string, any>;
|
||||
queryParamsHandling?: 'merge' | 'preserve' | 'replace';
|
||||
disabled?: boolean;
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user