Compare commits

...
Author SHA1 Message Date
farajollahi 15f55af4c4 fix count
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-11 13:41:57 +02:00
farajollahi 934c49bf49 Merge branch 'dev' into check-dashboard
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-11 12:00:19 +02:00
Roman 70d6b3d698 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-11 11:48:39 +02:00
Roman e6e9628837 organization-feature 2026-08-11 11:48:18 +02:00
farajollahi e1b3318e68 fix eu
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-11 11:37:30 +02:00
Louis 4d8a7405ca Merge pull request 'fix: prevent undefined hierarchy and missing metrics in topic tooltip' (#274) from refactor/topic-chips into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #274
2026-08-11 11:18:22 +02:00
Louis f1a6c32e0c fix: prevent undefined hierarchy and missing metrics in topic tooltip
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-08-11 11:12:48 +02:00
Louis cf5a3e7d3d Merge remote-tracking branch 'origin/dev' into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-11 10:51:09 +02:00
Louis 89f45082fb fetch field/subfield descriptions on hover in legend tooltip 2026-08-11 10:48:05 +02:00
genja 0ad6ac70ff Merge pull request 'feature/keywords-analysis' (#273) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #273
2026-08-11 10:47:49 +02:00
Louis e8e0decc6c add domain/field/subfield lookup endpoints 2026-08-11 10:47:38 +02:00
genja 57aaf77162 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-11 10:43:57 +02:00
farajollahi a3eebedb02 Merge branch 'dev' into check-dashboard
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-11 10:38:21 +02:00
farajollahi f8e5cd90a5 feat(dashboard): improve filters, tooltips and treemap state
LocationBasedServices/smartguide/pipeline/head This commit looks good
- add detailed tooltips to dashboard statistic cards
- show author details on hover in top-10 person analyses
- align patent icon with the sidebar
- resize and right-align the dashboard period slider
- persist DFG, EU and Bund treemap selections in URL parameters
2026-08-11 10:37:24 +02:00
genja 07ce24143b 500 bug fix
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-11 10:23:57 +02:00
farajollahi 3d092b02f3 refactor(dashboard): split dashboard logic into dedicated services
LocationBasedServices/smartguide/pipeline/head This commit looks good
- add separate services for top authors, project statuses and topic treemaps
- extract shared project ID and statistics logic
- move common period and institution helpers into common module
- add individual top-author API routes
- load top-author analyses independently in the frontend
- remove unused dashboard code and helper functions
- reduce the main dashboard service to general statistics and topic visualizations
2026-08-11 10:16:25 +02:00
genja bf5e065520 Merge pull request 'feature/keywords-analysis' (#272) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #272
2026-08-11 09:20:50 +02:00
genja 08178e74d2 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-11 09:14:48 +02:00
genja c66fcff906 hot-fix: check for 403 only if author or institution id is persistent 2026-08-11 09:14:33 +02:00
Louis b0dd0e509d add legend tooltip component 2026-08-11 09:03:54 +02:00
genja 719da6e921 Merge pull request 'feature/keywords-analysis' (#271) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #271
2026-08-11 08:57:51 +02:00
genja e4b3d0a9a9 replaced the is_forbidden function with check function from auth
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-11 08:53:25 +02:00
genja c0e231a32b Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-11 08:22:05 +02:00
Kazgatari af9f9a25da added screen padding
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-10 23:21:42 +02:00
Kazgatari 0a465bc7e1 changed author and institution chips as well 2026-08-10 23:18:39 +02:00
Kazgatari aec735e09e fix: topic tooltip clipping 2026-08-10 23:01:20 +02:00
Kazgatari 9ce6d5f26e adapted shared topic chip to accept already fetched topics instead of making another seperate call (+ error handling for possible null and undifined types as specified in the openapi generated model). Hopefully found all instances of regular material tooltip and changed to use new chip
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-10 21:18:58 +02:00
Kazgatari f4b4fb0562 changed deprecated topic-chip component code to use signals. 2026-08-10 21:11:08 +02:00
genja aa22fad67d added external link button
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-10 20:43:17 +02:00
kallweit 548bb4ce70 Merge pull request 'refactor/wordcloud' (#270) from refactor/wordcloud into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #270
2026-08-10 18:44:06 +02:00
kallweit b6871b3618 refactor(wordcloud): use shared tooltip component
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-10 18:38:40 +02:00
kallweit fe5e816551 refactor(wordcloud): extract wordcloud into its own component 2026-08-10 18:22:48 +02:00
kallweit 20d2a281b1 Merge pull request 'fix/news-details-ui' (#269) from fix/news-details-ui into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #269
2026-08-10 17:58:25 +02:00
kallweit e2ae0c660a refactor(news-list): re-style search bar and filters to improve alignment
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-10 17:50:11 +02:00
kallweit 9e8ae16597 feat(sidebar): change 'News' to 'Nachrichten'
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-10 16:51:07 +02:00
kallweit e5284a79c9 fix(news-details): prevent keyword acronyms from highlighting unrelated words 2026-08-10 16:50:23 +02:00
kallweit 79dad5dfb0 fix(news-details): change navigation to always go back to news list 2026-08-10 16:50:23 +02:00
kallweit a511c16fb1 fix(news-details): change topic highlight text 2026-08-10 16:50:23 +02:00
kallweit 98a1214a4d feat(news-details): remove highlighting of orphaned keywords 2026-08-10 16:50:23 +02:00
kallweit be459c45cf Merge pull request 'feature/news-in-keywords' (#268) from feature/news-in-keywords into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #268
2026-08-10 16:44:06 +02:00
kallweit 328ef2938c feat(keyword-search): add wrapper to news filters
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-08-10 16:32:27 +02:00
kallweit 21f3f49078 refactor(keyword-search, news, accounts): use shared selector for news relevance filter and reset to first page on filter change 2026-08-10 16:32:27 +02:00
kallweit 882ad3b8cf refactor(news): deduplicate topic reading logic 2026-08-10 16:32:27 +02:00
kallweit d8b7d8bc2e fix(keyword-search): add fuzzy search fallback for news 2026-08-10 16:32:27 +02:00
kallweit c1692535a5 refactor(keyword-search): extract 'more' toggle into a shared component 2026-08-10 16:32:27 +02:00
kallweit af0e326747 feat(keyword-search): fill news tab 2026-08-10 16:32:27 +02:00
genja 6cdaa9738a Merge pull request 'feature/keywords-analysis' (#267) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #267
2026-08-10 16:29:04 +02:00
genja 1e5d0c4517 enabled ALWAYS tracking total hits to avoid 10000 cuts on data count in elastic client 2026-08-10 13:59:34 +02:00
genja 127f5ca287 added skeleton loading for projects data table 2026-08-10 13:45:59 +02:00
genja f51b775fd9 fixed skeleton for persons list while resolving
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-10 13:43:02 +02:00
genja 0015b92591 added all affiliations for 403 check at projects component 2026-08-10 13:41:51 +02:00
genja 37e1f1811f fixed wrong projects number displaying 2026-08-10 13:41:21 +02:00
farajollahi deb6448739 Merge branch 'dev' into check-dashboard
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-06 19:19:02 +02:00
farajollahi bfb3224684 Revert "fix bug"
LocationBasedServices/smartguide/pipeline/head This commit looks good
This reverts commit d48435b948.
2026-08-06 18:38:35 +02:00
farajollahi aed1f33935 Keep check-dashboard publication count after timeline merge 2026-08-06 18:31:52 +02:00
farajollahi 33192efa33 Merge branch 'check-final-timeline' into check-dashboard
# Conflicts:
#	service/src/main/inse/dashboard/service.py
#	service/src/main/inse/dashboard/test_service.py
2026-08-06 18:26:33 +02:00
farajollahi d48435b948 fix bug
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-06 18:12:38 +02:00
Kazgatari daa4f79ea0 fix: author prefetch did not work (moved away from excessive effect() usage, implemented additional methods to avoid missmatches)
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-06 16:30:28 +02:00
farajollahi 567b5ecd4f implement Eu and Bund topics treemap
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-06 12:16:49 +02:00
farajollahi b21d8d3e88 revert period filters on dashboard
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-06 11:32:05 +02:00
farajollahi 727c3fde67 fix counts
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-08-05 10:44:09 +02:00
farajollahi de880fb9f0 fix publications 2026-08-05 10:17:28 +02:00
spsaefan c054cf99fe Fix all time slider
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-04 23:19:50 +02:00
spsaefan 98a742f024 Match dashboard publications with publications page
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-04 22:59:36 +02:00
farajollahi bb791138cd fix news bug
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-04 14:41:26 +02:00
148 changed files with 10781 additions and 4703 deletions
+19
View File
@@ -88,6 +88,25 @@ class Organization(Durable, table=True):
accounts: list["Account"] = Relationship(back_populates="organization")
class OrganizationInstitution(SQLModel, table=True):
__tablename__ = "organization_institution"
__table_args__ = (
UniqueConstraint(
"organization_id",
"position",
name="uq_organization_institution_position",
),
)
organization_id: uuid.UUID = Field(
foreign_key="organization.id",
primary_key=True,
index=True,
)
openalex_institution_id: str = Field(primary_key=True, index=True)
position: int = Field(nullable=False)
class Account(Durable, table=True):
@model_validator(mode="before")
@classmethod
+15 -3
View File
@@ -22,6 +22,7 @@ from inse.auth.model import (
IdTokenMetadata,
LoginResponse,
Organization,
OrganizationInstitution,
OtkResponse,
RefreshTokenMetadata,
Secret,
@@ -98,9 +99,12 @@ def create_predefined_accounts(session: Session, file_path: str):
with open(file_path, "r") as file:
data: dict[str, Any] = json.loads(file.read())
for organization_data in data.get("organizations", []):
organization_id = organization_data.get("id")
if organization_id is not None:
organization_id = uuid.UUID(organization_id)
organization_id_value = organization_data.get("id")
organization_id = (
uuid.UUID(organization_id_value)
if organization_id_value is not None
else uuid.uuid4()
)
organization_name = organization_data["name"]
openalex_institution_id = organization_data.get(
"openalex_institution_id"
@@ -113,6 +117,14 @@ def create_predefined_accounts(session: Session, file_path: str):
openalex_institution_id=openalex_institution_id,
)
session.add(organization)
if openalex_institution_id:
session.add(
OrganizationInstitution(
organization_id=organization.id,
openalex_institution_id=openalex_institution_id,
position=0,
)
)
for account_data in data.get("accounts", []):
organization_id = uuid.UUID(account_data["organization_id"])
roles = normalize_roles(
@@ -0,0 +1,142 @@
import hashlib
from collections import defaultdict
from typing import Any
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.projects import service as projects_service
from .model import BundProjectTopics, DfgProjectKeyword, DfgProjectTopic
from .common import (
dashboard_period as _dashboard_period,
normalize_institution_id as _normalize_institution_id,
raw_institution_id as _raw_institution_id,
)
async def get_dashboard_bund_topics(
institution_id: str,
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> BundProjectTopics:
normalized_id = _normalize_institution_id(institution_id)
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_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=None,
funding_end_years=None,
active_from_year=period[0],
active_to_year=period[1],
countries=None,
page=page_number,
size=page_size,
sort_by="id",
sort_direction="asc",
fuzzy=False,
)
project_ids.update(
project.funding_code
for project in projects.elements
if project.funding_code
)
if len(project_ids) >= projects.total or not projects.elements:
break
page_number += 1
topics: dict[str, dict[str, Any]] = {}
matched_project_ids: set[str] = set()
if project_ids:
mapping_project_ids = sorted(
hashlib.sha256(project_id.encode("utf-8")).hexdigest()
for project_id in project_ids
)
async for hit in elasticsearch.scan(
index=str(ESIndex.PROJECTS_BUND_TOPICS),
query={"terms": {"project_id": mapping_project_ids}},
source=["project_id", "keyword", "topic_matches"],
page_size=1000,
cluster=ESCluster.INSE,
):
source = hit.get("_source", {})
project_id = str(source.get("project_id") or "")
if not project_id:
continue
keyword = str(source.get("keyword") or "").strip()
matched_project_ids.add(project_id)
for match in source.get("topic_matches", []):
topic_id = str(match.get("topic_id") or "")
if not topic_id:
continue
topic = topics.setdefault(
topic_id,
{
"id": topic_id,
"name": str(match.get("topic_display_name") or topic_id),
"subfield": match.get("subfield"),
"field": match.get("field"),
"domain": match.get("domain"),
"project_ids": set(),
"keywords": {},
},
)
topic["project_ids"].add(project_id)
if keyword:
topic["keywords"].setdefault(keyword, set()).add(project_id)
field_project_ids: dict[str, set[str]] = defaultdict(set)
subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
for topic in topics.values():
field_name = str(topic["field"] or "")
subfield_name = str(topic["subfield"] or "")
field_project_ids[field_name].update(topic["project_ids"])
subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
topic_list = [
DfgProjectTopic(
id=topic["id"],
name=topic["name"],
subfield=topic["subfield"],
field=topic["field"],
domain=topic["domain"],
project_count=len(topic["project_ids"]),
field_project_count=len(field_project_ids[str(topic["field"] or "")]),
subfield_project_count=len(
subfield_project_ids[
(str(topic["field"] or ""), str(topic["subfield"] or ""))
]
),
keywords=sorted(
[
DfgProjectKeyword(
name=keyword,
project_count=len(keyword_project_ids),
)
for keyword, keyword_project_ids in topic["keywords"].items()
],
key=lambda entry: (-entry.project_count, entry.name),
),
)
for topic in topics.values()
]
topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
return BundProjectTopics(
institution_id=normalized_id,
organization_name=organization_name,
project_count=len(project_ids),
matched_project_count=len(matched_project_ids),
topics=topic_list,
)
+92
View File
@@ -0,0 +1,92 @@
from typing import Any, Literal
from fastapi import HTTPException, status
DashboardPeriod = tuple[int | None, int | None]
def dashboard_period(
from_year: int | None = None,
to_year: int | None = None,
) -> DashboardPeriod:
if from_year is not None and to_year is not None and from_year > to_year:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="from_year must be less than or equal to to_year.",
)
return from_year, to_year
def project_overlap_filter(
start_field: str,
end_field: str,
period: DashboardPeriod,
*,
missing_end_is_ongoing: bool = False,
) -> dict[str, Any] | None:
from_year, to_year = period
filters: list[dict[str, Any]] = []
if to_year is not None:
filters.append({"range": {start_field: {"lte": to_year}}})
if from_year is not None:
end_filter: dict[str, Any] = {"range": {end_field: {"gte": from_year}}}
if missing_end_is_ongoing:
end_filter = {
"bool": {
"should": [
end_filter,
{"bool": {"must_not": {"exists": {"field": end_field}}}},
],
"minimum_should_match": 1,
}
}
filters.append(end_filter)
return {"bool": {"filter": filters}} if filters else None
def project_boundary_year_filter(
start_field: str,
end_field: str,
period: DashboardPeriod,
date_format: Literal["iso", "de", "year"],
) -> dict[str, Any] | None:
from_year, to_year = period
filters: list[dict[str, Any]] = []
if to_year is not None:
if date_format == "year":
filters.append({"range": {start_field: {"lte": to_year}}})
else:
last_day = (
f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}"
)
filters.append({"range": {start_field: {"lte": last_day}}})
if from_year is not None:
if date_format == "year":
filters.append({"range": {end_field: {"gte": from_year}}})
else:
first_day = (
f"{from_year}-01-01" if date_format == "iso" else f"01.01.{from_year}"
)
filters.append({"range": {end_field: {"gte": first_day}}})
return {"bool": {"filter": filters}} if filters else None
def normalize_institution_id(value: str) -> str:
return (
value
if value.startswith("https://openalex.org/")
else f"https://openalex.org/{value}"
)
def raw_institution_id(value: str) -> str:
return normalize_institution_id(value).removeprefix("https://openalex.org/")
def institution_works_query(institution_id: str) -> dict[str, Any]:
return {
"nested": {
"path": "authorships.institutions",
"query": {"term": {"authorships.institutions.id": institution_id}},
}
}
@@ -0,0 +1,103 @@
from collections import defaultdict
from typing import Any
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from .model import DfgProjectKeyword, DfgProjectTopic, DfgProjectTopics
from .common import normalize_institution_id as _normalize_institution_id
from .project_ids_service import _get_dfg_project_ids_from_projects_service
async def get_dashboard_dfg_topics(
institution_id: str,
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DfgProjectTopics:
normalized_id = _normalize_institution_id(institution_id)
project_ids = await _get_dfg_project_ids_from_projects_service(
normalized_id,
from_year=from_year,
to_year=to_year,
)
topics: dict[str, dict[str, Any]] = {}
matched_project_ids: set[str] = set()
if project_ids:
async for hit in elasticsearch.scan(
index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS),
query={"terms": {"project_id": project_ids}},
source=["project_id", "keyword", "topic_matches"],
page_size=1000,
cluster=ESCluster.INSE,
):
source = hit.get("_source", {})
project_id = str(source.get("project_id") or "")
if not project_id:
continue
keyword = str(source.get("keyword") or "").strip()
matched_project_ids.add(project_id)
for match in source.get("topic_matches", []):
topic_id = str(match.get("topic_id") or "")
if not topic_id:
continue
topic = topics.setdefault(
topic_id,
{
"id": topic_id,
"name": str(match.get("topic_display_name") or topic_id),
"subfield": match.get("subfield"),
"field": match.get("field"),
"domain": match.get("domain"),
"project_ids": set(),
"keywords": {},
},
)
topic["project_ids"].add(project_id)
if keyword:
topic["keywords"].setdefault(keyword, set()).add(project_id)
field_project_ids: dict[str, set[str]] = defaultdict(set)
subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
for topic in topics.values():
field_name = str(topic["field"] or "")
subfield_name = str(topic["subfield"] or "")
field_project_ids[field_name].update(topic["project_ids"])
subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
topic_list = [
DfgProjectTopic(
id=topic["id"],
name=topic["name"],
subfield=topic["subfield"],
field=topic["field"],
domain=topic["domain"],
project_count=len(topic["project_ids"]),
field_project_count=len(field_project_ids[str(topic["field"] or "")]),
subfield_project_count=len(
subfield_project_ids[
(str(topic["field"] or ""), str(topic["subfield"] or ""))
]
),
keywords=sorted(
[
DfgProjectKeyword(
name=keyword,
project_count=len(keyword_project_ids),
)
for keyword, keyword_project_ids in topic["keywords"].items()
],
key=lambda entry: (-entry.project_count, entry.name),
),
)
for topic in topics.values()
]
topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
return DfgProjectTopics(
institution_id=normalized_id,
organization_name=organization_name,
project_count=len(project_ids),
matched_project_count=len(matched_project_ids),
topics=topic_list,
)
@@ -0,0 +1,109 @@
from collections import defaultdict
from typing import Any
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from .model import DfgProjectKeyword, DfgProjectTopic, EuProjectTopics
from .common import normalize_institution_id as _normalize_institution_id
from .project_ids_service import _get_eu_project_ids_from_projects_service
async def get_dashboard_eu_topics(
institution_id: str,
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> EuProjectTopics:
normalized_id = _normalize_institution_id(institution_id)
project_ids = await _get_eu_project_ids_from_projects_service(
normalized_id,
from_year=from_year,
to_year=to_year,
)
topics: dict[str, dict[str, Any]] = {}
matched_project_ids: set[str] = set()
if project_ids:
mapping_indices = (
ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING,
ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS,
ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS,
)
for mapping_index in mapping_indices:
async for hit in elasticsearch.scan(
index=str(mapping_index),
query={"terms": {"project_id": project_ids}},
source=["project_id", "keyword", "topic_matches"],
page_size=1000,
cluster=ESCluster.INSE,
):
source = hit.get("_source", {})
project_id = str(source.get("project_id") or "")
if not project_id:
continue
keyword = str(source.get("keyword") or "").strip()
matched_project_ids.add(project_id)
for match in source.get("topic_matches", []):
topic_id = str(match.get("topic_id") or "")
if not topic_id:
continue
topic = topics.setdefault(
topic_id,
{
"id": topic_id,
"name": str(match.get("topic_display_name") or topic_id),
"subfield": match.get("subfield"),
"field": match.get("field"),
"domain": match.get("domain"),
"project_ids": set(),
"keywords": {},
},
)
topic["project_ids"].add(project_id)
if keyword:
topic["keywords"].setdefault(keyword, set()).add(project_id)
field_project_ids: dict[str, set[str]] = defaultdict(set)
subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
for topic in topics.values():
field_name = str(topic["field"] or "")
subfield_name = str(topic["subfield"] or "")
field_project_ids[field_name].update(topic["project_ids"])
subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
topic_list = [
DfgProjectTopic(
id=topic["id"],
name=topic["name"],
subfield=topic["subfield"],
field=topic["field"],
domain=topic["domain"],
project_count=len(topic["project_ids"]),
field_project_count=len(field_project_ids[str(topic["field"] or "")]),
subfield_project_count=len(
subfield_project_ids[
(str(topic["field"] or ""), str(topic["subfield"] or ""))
]
),
keywords=sorted(
[
DfgProjectKeyword(
name=keyword,
project_count=len(keyword_project_ids),
)
for keyword, keyword_project_ids in topic["keywords"].items()
],
key=lambda entry: (-entry.project_count, entry.name),
),
)
for topic in topics.values()
]
topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
return EuProjectTopics(
institution_id=normalized_id,
organization_name=organization_name,
project_count=len(project_ids),
matched_project_count=len(matched_project_ids),
topics=topic_list,
)
+23
View File
@@ -54,6 +54,8 @@ class DfgProjectTopic(BaseModel):
field: str | None = None
domain: str | None = None
project_count: int
field_project_count: int
subfield_project_count: int
keywords: list[DfgProjectKeyword]
@@ -65,6 +67,22 @@ class DfgProjectTopics(BaseModel):
topics: list[DfgProjectTopic]
class EuProjectTopics(BaseModel):
institution_id: str
organization_name: str
project_count: int
matched_project_count: int
topics: list[DfgProjectTopic]
class BundProjectTopics(BaseModel):
institution_id: str
organization_name: str
project_count: int
matched_project_count: int
topics: list[DfgProjectTopic]
class TopAuthor(BaseModel):
id: str | None = None
name: str
@@ -80,6 +98,11 @@ class TopAuthorStatistics(BaseModel):
news: list[TopAuthor]
class TopAuthorAnalysis(BaseModel):
institution_id: str
authors: list[TopAuthor]
class TopicHeatmapValue(BaseModel):
year: int
count: int
@@ -0,0 +1,102 @@
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.projects import service as projects_service
from inse.projects.model import EuCordisProjectType
from .common import (
dashboard_period as _dashboard_period,
raw_institution_id as _raw_institution_id,
)
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(
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_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=None,
funding_end_years=None,
active_from_year=period[0],
active_to_year=period[1],
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)
@@ -0,0 +1,122 @@
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.projects import service as projects_service
from inse.projects.model import EuCordisProjectType
from .common import (
dashboard_period as _dashboard_period,
normalize_institution_id as _normalize_institution_id,
raw_institution_id as _raw_institution_id,
)
from .model import DashboardStatisticValue
async def get_dashboard_eu_projects(
institution_id: str,
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
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=None,
funding_end_years=None,
active_from_year=period[0],
active_to_year=period[1],
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=projects.total,
)
async def get_dashboard_bmbf_projects(
institution_id: str,
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
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=None,
funding_end_years=None,
active_from_year=period[0],
active_to_year=period[1],
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,
)
async def get_dashboard_dfg_projects(
institution_id: str,
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
projects = await projects_service.get_dfg_projects(
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=None,
funding_end_years=None,
active_from_year=period[0],
active_to_year=period[1],
page=0,
size=1,
sort_by="id",
sort_direction="asc",
fuzzy=False,
skip_enrichment=True,
)
return DashboardStatisticValue(
institution_id=normalized_id,
organization_name=organization_name,
value=projects.total,
)
@@ -0,0 +1,513 @@
from datetime import datetime
from typing import Any
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from .common import (
DashboardPeriod,
dashboard_period as _dashboard_period,
normalize_institution_id as _normalize_institution_id,
project_boundary_year_filter as _project_boundary_year_filter,
project_overlap_filter as _project_overlap_filter,
raw_institution_id as _raw_institution_id,
)
from .institute_helper import get_openalex_institution
from .model import (
BmbfProjectStatusStatistics,
DfgProjectStatusStatistics,
EuProjectStatusStatistics,
)
from .project_statistics_service import (
get_dashboard_bmbf_projects,
get_dashboard_dfg_projects,
get_dashboard_eu_projects,
)
def _status_count(aggregations: dict[str, Any], status_name: str) -> int:
return int(aggregations.get(status_name, {}).get("projects", {}).get("value", 0))
def reconcile_status_counts(
total: int, ongoing: int, upcoming: int, completed: int
) -> tuple[int, int, int]:
"""Make 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]
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]
def _status_filter_aggregations(
start_field: str, end_field: str, today: str
) -> dict[str, Any]:
return {
"ongoing": {
"filter": {
"bool": {
"filter": [
{"range": {start_field: {"lte": today}}},
{"range": {end_field: {"gte": today}}},
]
}
}
},
"upcoming": {"filter": {"range": {start_field: {"gt": today}}}},
"completed": {"filter": {"range": {end_field: {"lt": today}}}},
}
async def get_dashboard_eu_project_statuses(
institution_id: str,
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> EuProjectStatusStatistics:
normalized_id = _normalize_institution_id(institution_id)
aliases = await _institution_aliases(normalized_id, organization_name)
project_ids = await _eu_project_ids_for_aliases(aliases)
total = (
await get_dashboard_eu_projects(
normalized_id, organization_name, from_year=from_year, to_year=to_year
)
).value
if not project_ids:
return EuProjectStatusStatistics(
institution_id=normalized_id,
organization_name=organization_name,
ongoing=total,
upcoming=0,
completed=0,
)
today = datetime.now().date().isoformat()
period = _dashboard_period(from_year, to_year)
filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}]
if period_filter := _project_boundary_year_filter(
"startDate", "endDate", period, "iso"
):
filters.append(period_filter)
response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
body={
"size": 0,
"query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
"aggs": {
"ongoing": {
"filter": {
"bool": {
"filter": [
{"range": {"startDate": {"lte": today}}},
{"range": {"endDate": {"gte": today}}},
]
}
},
"aggs": {"projects": {"cardinality": {"field": "id"}}},
},
"upcoming": {
"filter": {"range": {"startDate": {"gt": today}}},
"aggs": {"projects": {"cardinality": {"field": "id"}}},
},
"completed": {
"filter": {"range": {"endDate": {"lt": today}}},
"aggs": {"projects": {"cardinality": {"field": "id"}}},
},
},
},
cluster=ESCluster.INSE,
)
aggregations = response.get("aggregations", {})
ongoing, upcoming, completed = reconcile_status_counts(
total,
_status_count(aggregations, "ongoing"),
_status_count(aggregations, "upcoming"),
_status_count(aggregations, "completed"),
)
return EuProjectStatusStatistics(
institution_id=normalized_id,
organization_name=organization_name,
ongoing=ongoing,
upcoming=upcoming,
completed=completed,
)
async def get_dashboard_bmbf_project_statuses(
institution_id: str,
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> BmbfProjectStatusStatistics:
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_boundary_year_filter(
"funding_start", "funding_end", period, "de"
):
filters.append(period_filter)
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
body={
"size": 0,
"query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
"aggs": _status_filter_aggregations(
"funding_start", "funding_end", datetime.now().strftime("%d.%m.%Y")
),
},
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_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=ongoing,
upcoming=upcoming,
completed=completed,
)
async def get_dashboard_dfg_project_statuses(
institution_id: str,
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DfgProjectStatusStatistics:
normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
project_ids = await _get_dfg_project_ids_for_institution(normalized_id)
total = (
await get_dashboard_dfg_projects(
normalized_id, organization_name, from_year=from_year, to_year=to_year
)
).value
if not project_ids:
return DfgProjectStatusStatistics(
institution_id=normalized_id,
organization_name=organization_name,
ongoing=total,
upcoming=0,
completed=0,
)
filters: list[dict[str, Any]] = [
{
"terms": {
"projects.project_id": [int(project_id) for project_id in project_ids]
}
}
]
if period_filter := _project_boundary_year_filter(
"projects.funding_start", "projects.funding_end", period, "year"
):
filters.append(period_filter)
response = await elasticsearch.search(
index=ESIndex.DFG_INSTITUTES_V2,
body={
"size": 0,
"aggs": {
"projects_nested": {
"nested": {"path": "projects"},
"aggs": {
"selected_projects": {
"filter": filters[0]
if len(filters) == 1
else {"bool": {"filter": filters}},
"aggs": {
"ongoing": {
"filter": {
"match_phrase": {
"projects.status_de": "laufend"
}
},
"aggs": {
"projects": {
"cardinality": {
"field": "projects.project_id"
}
}
},
},
"completed": {
"filter": {
"match_phrase": {
"projects.status_de": "abgeschlossen"
}
},
"aggs": {
"projects": {
"cardinality": {
"field": "projects.project_id"
}
}
},
},
},
}
},
}
},
},
cluster=ESCluster.INSE,
)
aggregations = (
response.get("aggregations", {})
.get("projects_nested", {})
.get("selected_projects", {})
)
ongoing, upcoming, completed = reconcile_status_counts(
total,
_status_count(aggregations, "ongoing"),
0,
_status_count(aggregations, "completed"),
)
return DfgProjectStatusStatistics(
institution_id=normalized_id,
organization_name=organization_name,
ongoing=ongoing,
upcoming=upcoming,
completed=completed,
)
async def _get_dfg_project_ids_for_institution(
institution_id: str,
from_year: int | None = None,
to_year: int | None = None,
) -> list[str]:
period = _dashboard_period(from_year, to_year)
institution = await get_openalex_institution(institution_id)
institution_names = _openalex_institution_names(institution)
institutes_response = await elasticsearch.search(
index=ESIndex.DFG_INSTITUTES_V2,
body={
"size": 0,
"query": _dfg_institute_name_query(institution_names),
"aggs": {
"institute_ids": {"terms": {"field": "institute_id", "size": 1000}}
},
},
cluster=ESCluster.INSE,
)
institute_ids = [
bucket["key"]
for bucket in (
institutes_response.get("aggregations", {})
.get("institute_ids", {})
.get("buckets", [])
)
if bucket.get("key") is not None
]
if not institute_ids:
return []
projects_response = await elasticsearch.search(
index=ESIndex.DFG_INSTITUTES_V2,
body={
"size": 0,
"query": {"terms": {"institute_id": institute_ids}},
"aggs": {
"projects_nested": {
"nested": {"path": "projects"},
"aggs": {
"project_ids": {
"filter": {
"terms": {"projects.institute_ref_id": institute_ids}
},
"aggs": {
"values": {
"terms": {
"field": "projects.project_id",
"size": 10000,
}
}
},
}
},
}
},
},
cluster=ESCluster.INSE,
)
project_ids = [
str(bucket["key"])
for bucket in (
projects_response.get("aggregations", {})
.get("projects_nested", {})
.get("project_ids", {})
.get("values", {})
.get("buckets", [])
)
if bucket.get("key") is not None
]
return await _filter_dfg_project_ids_by_period(project_ids, period)
async def _eu_project_ids_for_aliases(aliases: list[str]) -> set[str]:
project_ids: set[str] = set()
async for hit in elasticsearch.scan(
index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD),
query=_eu_organization_query(aliases),
source=["projectID"],
page_size=1000,
cluster=ESCluster.INSE,
):
project_id = hit.get("_source", {}).get("projectID")
if project_id is not None:
project_ids.add(str(project_id))
return project_ids
async def _filter_dfg_project_ids_by_period(
project_ids: list[str],
period: DashboardPeriod,
) -> list[str]:
period_filter = _project_overlap_filter(
"funding_start",
"funding_end",
period,
missing_end_is_ongoing=True,
)
if not project_ids or not period_filter:
return project_ids
numeric_project_ids = [
int(project_id) for project_id in project_ids if str(project_id).isdigit()
]
if not numeric_project_ids:
return []
response = await elasticsearch.search(
index=ESIndex.DFG_PROJECTS,
body={
"size": 0,
"query": {
"bool": {
"filter": [
{"terms": {"id": numeric_project_ids}},
period_filter,
]
}
},
"aggs": {
"project_ids": {
"terms": {
"field": "id",
"size": len(numeric_project_ids),
}
}
},
},
cluster=ESCluster.INSE,
)
return [
str(bucket["key"])
for bucket in (
response.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
)
if bucket.get("key") is not None
]
async def _institution_aliases(
institution_id: str,
organization_name: str,
) -> list[str]:
aliases = (
await InstitutionsSearchClient().get_institution_aliases_by_oa_institution_id(
_raw_institution_id(institution_id)
)
)
return sorted(
{
alias.strip()
for alias in [organization_name, *aliases]
if alias and alias.strip()
}
)
def _eu_organization_query(aliases: list[str]) -> dict[str, Any]:
return {
"terms": {
"name.keyword": [alias.upper() for alias in aliases],
}
}
def _alias_match_query(field: str, aliases: list[str]) -> dict[str, Any]:
return {
"bool": {
"should": [
{
"match": {
field: {
"query": alias,
"operator": "and",
}
}
}
for alias in aliases
],
"minimum_should_match": 1,
}
}
def _openalex_institution_names(institution: Any) -> list[str]:
return sorted(
{
name.strip()
for name in [
institution.display_name,
*(institution.display_name_alternatives or []),
*(institution.display_name_acronyms or []),
]
if name and name.strip()
}
)
def _dfg_institute_name_query(institution_names: list[str]) -> dict[str, Any]:
return {
"bool": {
"should": [
{
"terms": {
"institute_name_de.keyword": institution_names,
}
},
{
"terms": {
"institute_name_en.keyword": institution_names,
}
},
],
"minimum_should_match": 1,
}
}
+152 -8
View File
@@ -10,32 +10,48 @@ from inse.tags import Tags
from .model import (
BmbfProjectStatusStatistics,
BundProjectTopics,
DashboardStatistics,
DashboardStatisticValue,
DfgProjectStatusStatistics,
DfgProjectTopics,
EuProjectTopics,
EuProjectStatusStatistics,
TopAuthorStatistics,
TopAuthorAnalysis,
TopicHeatmap,
TopicWordCloud,
)
from .service import (
get_dashboard_bmbf_project_statuses,
get_dashboard_bmbf_projects,
get_dashboard_dfg_project_statuses,
get_dashboard_dfg_projects,
get_dashboard_dfg_topics,
get_dashboard_eu_project_statuses,
get_dashboard_eu_projects,
get_dashboard_organization,
get_dashboard_patents,
get_dashboard_persons,
get_dashboard_publications,
get_dashboard_statistics,
get_top_authors,
get_topic_heatmap,
get_topic_word_cloud,
)
from .project_statistics_service import (
get_dashboard_bmbf_projects,
get_dashboard_dfg_projects,
get_dashboard_eu_projects,
)
from .bund_topics_service import get_dashboard_bund_topics
from .dfg_topics_service import get_dashboard_dfg_topics
from .eu_topics_service import get_dashboard_eu_topics
from .project_status_service import (
get_dashboard_bmbf_project_statuses,
get_dashboard_dfg_project_statuses,
get_dashboard_eu_project_statuses,
)
from .top_authors_service import (
get_top_authors,
get_top_eu_project_authors,
get_top_news_authors,
get_top_patent_authors,
get_top_project_authors,
get_top_work_authors,
)
router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD])
@@ -256,6 +272,46 @@ async def dashboard_dfg_project_topics(
)
@router.get(
"/projects/eu/topics",
operation_id="getDashboardEuProjectTopics",
response_model=EuProjectTopics,
)
async def dashboard_eu_project_topics(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> EuProjectTopics:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_eu_topics(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@router.get(
"/projects/bund/topics",
operation_id="getDashboardBundProjectTopics",
response_model=BundProjectTopics,
)
async def dashboard_bund_project_topics(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> BundProjectTopics:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_bund_topics(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@router.get(
"/top-authors",
operation_id="getDashboardTopAuthors",
@@ -281,6 +337,94 @@ async def dashboard_top_authors(
)
@router.get(
"/top-authors/works",
operation_id="getDashboardTopWorkAuthors",
response_model=TopAuthorAnalysis,
)
async def dashboard_top_work_authors(
works_period: Literal["all_time", "last_5_years"] = Query(
default="all_time", pattern="^(all_time|last_5_years)$"
),
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> TopAuthorAnalysis:
organization = get_dashboard_organization(session, access_token)
return await get_top_work_authors(
organization.openalex_institution_id, works_period, from_year, to_year
)
@router.get(
"/top-authors/projects",
operation_id="getDashboardTopProjectAuthors",
response_model=TopAuthorAnalysis,
)
async def dashboard_top_project_authors(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> TopAuthorAnalysis:
organization = get_dashboard_organization(session, access_token)
return await get_top_project_authors(
organization.openalex_institution_id, organization.name, from_year, to_year
)
@router.get(
"/top-authors/eu-projects",
operation_id="getDashboardTopEuProjectAuthors",
response_model=TopAuthorAnalysis,
)
async def dashboard_top_eu_project_authors(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> TopAuthorAnalysis:
organization = get_dashboard_organization(session, access_token)
return await get_top_eu_project_authors(
organization.openalex_institution_id, from_year, to_year
)
@router.get(
"/top-authors/patents",
operation_id="getDashboardTopPatentAuthors",
response_model=TopAuthorAnalysis,
)
async def dashboard_top_patent_authors(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> TopAuthorAnalysis:
organization = get_dashboard_organization(session, access_token)
return await get_top_patent_authors(
organization.openalex_institution_id, from_year, to_year
)
@router.get(
"/top-authors/news",
operation_id="getDashboardTopNewsAuthors",
response_model=TopAuthorAnalysis,
)
async def dashboard_top_news_authors(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> TopAuthorAnalysis:
organization = get_dashboard_organization(session, access_token)
return await get_top_news_authors(
organization.openalex_institution_id, from_year, to_year
)
@router.get(
"/topic-heatmap",
operation_id="getDashboardTopicHeatmap",
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+24
View File
@@ -107,6 +107,30 @@ def create_db_and_tables():
)
)
# Preserve the former single institution as the first manually selected
# institution.
# The legacy column remains synchronized for portal sections that have not yet
# been migrated to organization-wide institution lists.
with engine.begin() as connection:
connection.execute(
text(
"""
INSERT INTO organization_institution (
organization_id, openalex_institution_id, position
)
SELECT id, openalex_institution_id, 0
FROM organization
WHERE openalex_institution_id IS NOT NULL
AND TRIM(openalex_institution_id) != ''
AND NOT EXISTS (
SELECT 1
FROM organization_institution oi
WHERE oi.organization_id = organization.id
)
"""
)
)
def get_session():
"""Yields a database session for use in FastAPI endpoints.
@@ -261,11 +261,10 @@ async def search(
payload["sort"] = sort
if aggs is not None:
payload["aggs"] = aggs
if track_total_hits:
payload["track_total_hits"] = True
if highlight is not None:
payload["highlight"] = highlight
payload["track_total_hits"] = True # always track total hits for accurate pagination and counts
if len(payload) == 0:
raise ValueError(
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided"
+3
View File
@@ -52,6 +52,9 @@ class ESIndex(StrEnum):
OPENALEX_CONTINENTS = "openalex-continents"
OPENALEX_TOPICS = "openalex-topics"
OPENALEX_TOPIC_VECTORS = "topicvectors"
OPENALEX_DOMAINS = "openalex-domains"
OPENALEX_FIELDS = "openalex-fields"
OPENALEX_SUBFIELDS = "openalex-subfields"
EPO_INDEX = "epo_index_1.0"
USPTO_INDEX = "uspto_patents_3.0"
+207 -39
View File
@@ -27,7 +27,6 @@ TOPIC_NUM_CANDIDATES = 100
TOPIC_SIMILARITY = 0.5
TOPICS_INDEX = "aktuell_openalex_topics"
TOPICS_INDEX_MAX_PAIRS = 100
_SESSION_TOPIC_CACHE: dict[str, list] = {}
@@ -48,6 +47,11 @@ RELATED_BLOCK_SIZE = 5
RELATED_TOPIC_K = 1
EXACT_ID_CAP = 1000
KEYWORD_SEARCH_FIELDS = ["maintitle^3", "intro_content^2", "tags^2", "full_content"]
KEYWORD_SEARCH_SCAN_CAP = 50000
KEYWORD_SEARCH_ID_CAP = 2000
TOPIC_DOCS_PER_ARTICLE = 25
async def get_news_page(
page: int,
@@ -127,6 +131,206 @@ async def search_news(
return news_page
async def search_news_by_keywords(
keywords: list | None = None,
topic_ids: list | None = None,
filter_topic_ids: list | None = None,
fuzzy: bool = False,
page: int = 1,
page_size: int = 10,
year_from: int | None = None,
year_to: int | None = None,
relevance_values: list | None = None,
sort_order: str | None = None,
) -> NewsPage:
"""Searches the news for the keywords of a keywords-search run.
`fuzzy` resolves the keywords to OpenAlex topics (via the aktuell_openalex_topics index),
otherwise the raw keywords are matched as phrases against the article
text. The individual keywords are OR-ed rather than AND-ed.
An article carries at most KEYWORD_LIMIT keywords, so requiring all of them
would leave every multi-keyword search empty.
Articles matching more of them simply rank higher.
A fuzzy search without any resolved topic ids falls back to the raw
keywords. Once there are topic ids the fallback is off: a topic search that matches no article
stays empty instead of silently returning keyword hits.
By default results stay ranked by match strength (Elasticsearch's
`_score`). Passing `sort_order` ('asc'/'desc') overrides that with a
plain date sort, same as the plain news list.
"""
wanted_topic_ids: set = set()
if fuzzy:
wanted_topic_ids = {
topic_id
for topic_id in (topic_ids or []) + (filter_topic_ids or [])
if topic_id
}
if wanted_topic_ids:
should = await _topic_id_should_clauses(wanted_topic_ids)
else:
should = _keyword_should_clauses(keywords)
if not should:
return _empty_page(page, page_size)
clauses = await _filter_clauses(year_from, year_to, relevance_values)
query = {
"bool": {
"should": should,
"minimum_should_match": 1,
"filter": clauses,
}
}
highlight = {
"fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}},
"pre_tags": ["<em>"],
"post_tags": ["</em>"],
"encoder": "html",
}
sort = [{"date_full": sort_order}] if sort_order in ("asc", "desc") else None
response = await _run_search(
query=query,
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
size=page_size,
offset=(page - 1) * page_size,
sort=sort,
highlight=None if wanted_topic_ids else highlight,
)
news_page = await _build_page(response, page, page_size)
await _attach_topics(news_page.results)
return news_page
def _keyword_should_clauses(keywords: list | None) -> list:
return [
{
"multi_match": {
"query": keyword.strip(),
"fields": KEYWORD_SEARCH_FIELDS,
"type": "phrase",
}
}
for keyword in (keywords or [])
if keyword and keyword.strip()
]
async def _topic_id_should_clauses(topic_ids: set) -> list:
"""Turns matched OpenAlex topics into id clauses, boosted by hit count.
Articles that match several of the searched topics get a higher boost, so
Elasticsearch ranks them above articles that only match one.
"""
topics_per_article = await _news_ids_by_topic_ids(topic_ids)
if not topics_per_article:
return []
ranked = sorted(topics_per_article.items(), key=lambda item: -len(item[1]))
ids_by_hit_count: dict[int, list] = {}
for news_id, matched_topics in ranked[:KEYWORD_SEARCH_ID_CAP]:
ids_by_hit_count.setdefault(len(matched_topics), []).append(news_id)
return [
{"ids": {"values": news_ids, "boost": float(hit_count)}}
for hit_count, news_ids in ids_by_hit_count.items()
]
async def _news_ids_by_topic_ids(topic_ids: set) -> dict:
"""Returns news_id -> set of searched topic ids the article was mapped to."""
query = {"terms": {"topic_matches.topic_id.keyword": sorted(topic_ids)}}
topics_per_article: dict[str, set] = {}
scanned = 0
try:
async for hit in elasticsearch.scan(
index=TOPICS_INDEX,
query=query,
source=["news_id", "topic_matches.topic_id"],
cluster="inse",
):
scanned += 1
source = hit.get("_source", {})
news_id = source.get("news_id")
if news_id:
matched = topics_per_article.setdefault(news_id, set())
for match in source.get("topic_matches") or []:
topic_id = match.get("topic_id")
if topic_id in topic_ids:
matched.add(topic_id)
if scanned >= KEYWORD_SEARCH_SCAN_CAP:
logger.warning(
f"Topic lookup hit the scan cap of {KEYWORD_SEARCH_SCAN_CAP} documents."
)
break
except Exception:
logger.exception("Topic lookup for the keyword news search failed.")
return {}
return {news_id: matched for news_id, matched in topics_per_article.items() if matched}
async def _attach_topics(articles: list) -> None:
news_ids = [article.id for article in articles if article.id]
if not news_ids:
return
topics_per_article = await _topics_for_news_ids(news_ids)
for article in articles:
article.topics = topics_per_article.get(article.id, [])
async def _topics_for_news_ids(news_ids: list) -> dict[str, list[MatchedTopic]]:
"""Reads the indexed OpenAlex topic matches for the given articles."""
try:
response = await elasticsearch.search(
index=TOPICS_INDEX,
query={"terms": {"news_id.keyword": news_ids}},
source=["news_id", "keyword", "topic_matches"],
size=min(len(news_ids) * TOPIC_DOCS_PER_ARTICLE, 10000),
cluster="inse",
)
except Exception:
logger.exception("Batched topic lookup for the news result page failed.")
return {}
topics_per_article: dict[str, list[MatchedTopic]] = {}
seen_per_article: dict[str, set] = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
news_id = source.get("news_id")
if not news_id:
continue
keyword = source.get("keyword")
matched = topics_per_article.setdefault(news_id, [])
seen_ids = seen_per_article.setdefault(news_id, set())
for match in source.get("topic_matches") or []:
topic_id = match.get("topic_id")
if not topic_id or topic_id in seen_ids:
continue
seen_ids.add(topic_id)
matched.append(
MatchedTopic(
id=topic_id,
display_name=match.get("topic_display_name"),
subfield_name=match.get("subfield"),
field_name=match.get("field"),
domain_name=match.get("domain"),
source_keyword=keyword,
)
)
return topics_per_article
async def get_news_by_author(
author_id: str,
page: int = 1,
@@ -321,7 +525,7 @@ async def _get_article_keywords(
async def _get_article_topics(news_id: str, keywords: list) -> list:
indexed = await get_article_topics_from_index(news_id)
indexed = (await _topics_for_news_ids([news_id])).get(news_id, [])
if indexed:
return indexed
@@ -336,42 +540,6 @@ async def _get_article_topics(news_id: str, keywords: list) -> list:
return topics
async def get_article_topics_from_index(news_id: str) -> list:
try:
response = await elasticsearch.search(
index=TOPICS_INDEX,
query={"term": {"news_id.keyword": news_id}},
source=["keyword", "topic_matches"],
size=TOPICS_INDEX_MAX_PAIRS,
cluster="inse",
)
except Exception:
logger.exception(f"Topic-index lookup for {news_id} failed.")
return []
matched = []
seen_ids = set()
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
keyword = source.get("keyword")
for match in source.get("topic_matches") or []:
topic_id = match.get("topic_id")
if not topic_id or topic_id in seen_ids:
continue
seen_ids.add(topic_id)
matched.append(
MatchedTopic(
id=topic_id,
display_name=match.get("topic_display_name"),
subfield_name=match.get("subfield"),
field_name=match.get("field"),
domain_name=match.get("domain"),
source_keyword=keyword,
)
)
return matched
def _normalize_keywords(candidates: list) -> list:
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
seen = set()
@@ -516,7 +684,7 @@ async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, s
return relevant, authors, keywords, hit.get("_id")
async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict | None = None) -> dict:
try:
return await elasticsearch.search(
index="aktuell",
+12 -11
View File
@@ -8,17 +8,6 @@ class NewsKeywords(BaseModel):
keywords: list[str] = Field(description="The extracted keywords from the article.")
class NewsArticle(BaseModel):
id: str
date: str | None = None
maintitle: str | None = None
author: str | None = None
url: str | None = None
relevant: bool | None = None
snippet: str | None = None
related: bool | None = None
class MentionedPerson(BaseModel):
name: str
is_ude: bool = False
@@ -34,6 +23,18 @@ class MatchedTopic(BaseModel):
source_keyword: str | None = None
class NewsArticle(BaseModel):
id: str
date: str | None = None
maintitle: str | None = None
author: str | None = None
url: str | None = None
relevant: bool | None = None
snippet: str | None = None
related: bool | None = None
topics: list[MatchedTopic] | None = None
class NewsArticleDetail(NewsArticle):
full_content: str | None = None
relevant: bool | None = None
+62
View File
@@ -100,6 +100,68 @@ async def search_news(
)
@router.get(
"/keyword/search",
operation_id="getNewsByKeywords",
response_model=NewsPage,
response_model_exclude_none=True,
summary="Searches news articles by the keywords or matched topics of a keywords search.",
tags=[Tags.NEWS],
)
async def search_news_by_keywords(
keywords: Annotated[
list[str] | None, Query(description="Raw keywords to match against title/content.")
] = None,
topic_ids: Annotated[
list[str] | None,
Query(alias="topicIds", description="OpenAlex topic ids the keywords resolved to."),
] = None,
filter_topic_ids: Annotated[
list[str] | None,
Query(alias="filterTopicIds", description="Additional topic ids to narrow the results by."),
] = None,
fuzzy: Annotated[
bool,
Query(description="Search by resolved topics if True, otherwise by raw keywords."),
] = False,
page: Annotated[
int, Query(description="Page number (1-based).", ge=1)
] = 1,
page_size: Annotated[
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
] = 10,
relevance: Annotated[
str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.")
] = None,
year_from: Annotated[
int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0)
] = None,
year_to: Annotated[
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
] = None,
sort_order: Annotated[
str | None,
Query(
alias="sortOrder",
description="Overrides relevance ranking with a date sort: 'desc' (newest first) or 'asc' (oldest first).",
pattern="^(asc|desc)$",
),
] = None,
):
return await logic.search_news_by_keywords(
keywords=keywords or [],
topic_ids=topic_ids or [],
filter_topic_ids=filter_topic_ids or [],
fuzzy=fuzzy,
page=page,
page_size=page_size,
sort_order=sort_order,
year_from=year_from,
year_to=year_to,
relevance_values=_parse_relevance(relevance),
)
@router.get(
"/by-author",
operation_id="getNewsByAuthor",
@@ -1,4 +1,5 @@
import uuid
from typing import Literal
from pydantic import BaseModel, Field
@@ -7,6 +8,7 @@ class OrganizationProfile(BaseModel):
id: uuid.UUID
name: str
other_inst_id: str | None = None
selected_openalex_institution_ids: list[str] = Field(default_factory=list)
deleted: bool
member_count: int
@@ -21,9 +23,25 @@ class OrganizationPage(BaseModel):
class CreateOrganizationRequest(BaseModel):
name: str = Field(min_length=1)
other_inst_id: str | None = None
selected_openalex_institution_ids: list[str] | None = None
class UpdateOrganizationRequest(BaseModel):
name: str | None = Field(default=None, min_length=1)
other_inst_id: str | None = None
selected_openalex_institution_ids: list[str] | None = None
deleted: bool | None = None
class InstitutionAssociation(BaseModel):
id: str
display_name: str
relationship: Literal["child", "related"]
class InstitutionAssociationsResponse(BaseModel):
id: str
display_name: str
associated_institutions: list[InstitutionAssociation] = Field(
default_factory=list
)
@@ -11,6 +11,7 @@ from inse.tags import Tags
from . import service
from .model import (
CreateOrganizationRequest,
InstitutionAssociationsResponse,
OrganizationPage,
OrganizationProfile,
UpdateOrganizationRequest,
@@ -19,6 +20,18 @@ from .model import (
router = APIRouter(prefix="/api/organizations", tags=[Tags.ORGANIZATION])
@router.get(
"/institutions/associations",
operation_id="getOrganizationInstitutionAssociations",
response_model=list[InstitutionAssociationsResponse],
)
async def get_organization_institution_associations(
institution_ids: list[str] = Query(),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[InstitutionAssociationsResponse]:
return await service.get_institution_associations(access_token, institution_ids)
@router.get("", operation_id="getOrganisations", response_model=OrganizationPage)
async def get_organizations(
page: int = Query(default=0, ge=0),
@@ -1,18 +1,43 @@
import logging
import re
import uuid
from fastapi import HTTPException, status
from sqlmodel import Session, func, select
from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
from inse.auth.model import (
AccessTokenMetadata,
Account,
Organization,
OrganizationInstitution,
UserRole,
)
from inse.integrations import elasticsearch
from inse.model import ESIndex
from .model import (
CreateOrganizationRequest,
InstitutionAssociation,
InstitutionAssociationsResponse,
OrganizationPage,
OrganizationProfile,
UpdateOrganizationRequest,
)
logger = logging.getLogger(__name__)
OPENALEX_INSTITUTION_ID_PATTERN = re.compile(
r"^(?:https?://openalex\.org/)?(I\d+)/?$", re.IGNORECASE
)
KNOWN_ASSOCIATION_TYPES = {
"parent",
"child",
"related",
"predecessor",
"successor",
}
def _require_super_admin(access_token: AccessTokenMetadata) -> None:
if access_token.effective_role != UserRole.SUPER_ADMIN:
raise HTTPException(
@@ -31,6 +56,27 @@ def _normalize_name(name: str) -> str:
return normalized_name
def _normalize_institution_id(institution_id: str) -> str:
match = OPENALEX_INSTITUTION_ID_PATTERN.fullmatch(institution_id.strip())
if match is None:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Invalid OpenAlex institution ID: {institution_id}",
)
return f"I{match.group(1)[1:]}"
def _normalize_institution_ids(institution_ids: list[str]) -> list[str]:
normalized: list[str] = []
seen: set[str] = set()
for institution_id in institution_ids:
clean_id = _normalize_institution_id(institution_id)
if clean_id not in seen:
normalized.append(clean_id)
seen.add(clean_id)
return normalized
def _ensure_name_available(
session: Session,
name: str,
@@ -79,18 +125,76 @@ def _member_counts(
return {organization_id: count for organization_id, count in rows}
def _institution_data(
session: Session, organization_ids: list[uuid.UUID]
) -> dict[uuid.UUID, list[str]]:
ids_by_organization: dict[uuid.UUID, list[str]] = {
organization_id: [] for organization_id in organization_ids
}
if not organization_ids:
return ids_by_organization
institution_rows = session.exec(
select(OrganizationInstitution)
.where(OrganizationInstitution.organization_id.in_(organization_ids))
.order_by(
OrganizationInstitution.organization_id,
OrganizationInstitution.position,
)
).all()
for row in institution_rows:
ids_by_organization[row.organization_id].append(
row.openalex_institution_id
)
return ids_by_organization
def _to_profile(
organization: Organization, member_count: int
organization: Organization,
member_count: int,
institution_ids: list[str],
) -> OrganizationProfile:
if not institution_ids and organization.openalex_institution_id:
legacy_id = _normalize_institution_id(organization.openalex_institution_id)
institution_ids = [legacy_id]
return OrganizationProfile(
id=organization.id,
name=organization.name,
other_inst_id=organization.openalex_institution_id,
other_inst_id=institution_ids[0] if institution_ids else None,
selected_openalex_institution_ids=institution_ids,
deleted=organization.deleted,
member_count=member_count,
)
def _replace_organization_institutions(
session: Session,
organization: Organization,
institution_ids: list[str],
) -> None:
normalized_ids = _normalize_institution_ids(institution_ids)
for row in session.exec(
select(OrganizationInstitution).where(
OrganizationInstitution.organization_id == organization.id
)
).all():
session.delete(row)
session.flush()
for position, institution_id in enumerate(normalized_ids):
session.add(
OrganizationInstitution(
organization_id=organization.id,
openalex_institution_id=institution_id,
position=position,
)
)
organization.openalex_institution_id = (
normalized_ids[0] if normalized_ids else None
)
def _deactivate_organization_accounts(
session: Session, organization_id: uuid.UUID
) -> None:
@@ -106,6 +210,27 @@ def _deactivate_organization_accounts(
session.add(account)
def _ensure_not_current_organization(
session: Session,
access_token: AccessTokenMetadata,
organization_id: uuid.UUID,
) -> None:
protected_organization_ids = {access_token.effective_organization_id}
if access_token.real_account_id is not None:
real_account = session.get(Account, access_token.real_account_id)
if real_account is not None:
protected_organization_ids.add(real_account.organization_id)
if organization_id in protected_organization_ids:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=(
"The organization of the real or effective account "
"cannot be deleted."
),
)
def get_organizations(
session: Session,
access_token: AccessTokenMetadata,
@@ -130,10 +255,15 @@ def get_organizations(
).all()
organization_ids = [organization.id for organization in organizations]
counts = _member_counts(session, organization_ids)
institution_ids = _institution_data(session, organization_ids)
return OrganizationPage(
items=[
_to_profile(organization, counts.get(organization.id, 0))
_to_profile(
organization,
counts.get(organization.id, 0),
institution_ids.get(organization.id, []),
)
for organization in organizations
],
total=total,
@@ -153,12 +283,25 @@ def create_organization(
organization = Organization(
name=name,
openalex_institution_id=(payload.other_inst_id or '').strip() or None,
)
session.add(organization)
session.flush()
requested_ids = payload.selected_openalex_institution_ids
if requested_ids is None:
requested_ids = [payload.other_inst_id] if payload.other_inst_id else []
_replace_organization_institutions(
session,
organization,
requested_ids,
)
session.commit()
session.refresh(organization)
return _to_profile(organization, 0)
institution_ids = _institution_data(session, [organization.id])
return _to_profile(
organization,
0,
institution_ids[organization.id],
)
def update_organization(
@@ -174,10 +317,21 @@ def update_organization(
name = _normalize_name(payload.name)
_ensure_name_available(session, name, organization.id)
organization.name = name
if payload.other_inst_id is not None:
organization.openalex_institution_id = payload.other_inst_id.strip() or None
if payload.selected_openalex_institution_ids is not None:
_replace_organization_institutions(
session,
organization,
payload.selected_openalex_institution_ids,
)
elif payload.other_inst_id is not None:
_replace_organization_institutions(
session,
organization,
[payload.other_inst_id] if payload.other_inst_id.strip() else [],
)
if payload.deleted is not None:
if payload.deleted and not organization.deleted:
_ensure_not_current_organization(session, access_token, organization.id)
_deactivate_organization_accounts(session, organization.id)
organization.deleted = payload.deleted
@@ -185,7 +339,107 @@ def update_organization(
session.commit()
session.refresh(organization)
counts = _member_counts(session, [organization.id])
return _to_profile(organization, counts.get(organization.id, 0))
institution_ids = _institution_data(session, [organization.id])
return _to_profile(
organization,
counts.get(organization.id, 0),
institution_ids[organization.id],
)
async def get_institution_associations(
access_token: AccessTokenMetadata,
institution_ids: list[str],
) -> list[InstitutionAssociationsResponse]:
_require_super_admin(access_token)
clean_ids = _normalize_institution_ids(institution_ids)
if not clean_ids:
return []
response = await elasticsearch.search(
index=ESIndex.OPENALEX_INSTITUTIONS,
query={
"terms": {
"id": [
f"https://openalex.org/{institution_id}"
for institution_id in clean_ids
]
}
},
source=["id", "display_name", "associated_institutions"],
size=len(clean_ids),
)
sources_by_id: dict[str, dict] = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source") or {}
raw_id = source.get("id")
if isinstance(raw_id, str):
sources_by_id[_normalize_institution_id(raw_id)] = source
missing_id = next(
(
institution_id
for institution_id in clean_ids
if institution_id not in sources_by_id
),
None,
)
if missing_id is not None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"OpenAlex institution {missing_id} not found.",
)
results: list[InstitutionAssociationsResponse] = []
for clean_id in clean_ids:
source = sources_by_id[clean_id]
display_name = source.get("display_name")
if not isinstance(display_name, str) or not display_name.strip():
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"OpenAlex institution {clean_id} has no display name.",
)
associations_by_id: dict[str, InstitutionAssociation] = {}
for association in source.get("associated_institutions") or []:
if not isinstance(association, dict):
continue
relationship = str(association.get("relationship") or "").lower()
if relationship not in KNOWN_ASSOCIATION_TYPES:
logger.warning(
"Ignoring unknown OpenAlex institution relationship %r for %s",
relationship,
clean_id,
)
continue
if relationship not in {"child", "related"}:
continue
raw_association_id = association.get("id")
association_name = association.get("display_name")
if not isinstance(raw_association_id, str) or not isinstance(
association_name, str
):
continue
associated_id = _normalize_institution_id(raw_association_id)
candidate = InstitutionAssociation(
id=associated_id,
display_name=association_name,
relationship=relationship,
)
existing = associations_by_id.get(associated_id)
if existing is None or (
existing.relationship == "related" and relationship == "child"
):
associations_by_id[associated_id] = candidate
results.append(
InstitutionAssociationsResponse(
id=clean_id,
display_name=display_name,
associated_institutions=list(associations_by_id.values()),
)
)
return results
def delete_organization(
@@ -196,6 +450,7 @@ def delete_organization(
_require_super_admin(access_token)
organization = _get_organization_or_404(session, organization_id)
if not organization.deleted:
_ensure_not_current_organization(session, access_token, organization.id)
_deactivate_organization_accounts(session, organization.id)
organization.deleted = True
session.add(organization)
@@ -1,10 +1,16 @@
import asyncio
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
from sqlmodel import Session, SQLModel, create_engine
from sqlmodel import Session, SQLModel, create_engine, select
from inse.auth.model import Account, Organization, UserRole
from inse.auth.model import (
Account,
Organization,
OrganizationInstitution,
UserRole,
)
from inse.organization_management import service
from inse.organization_management.model import (
CreateOrganizationRequest,
@@ -22,10 +28,11 @@ def session():
yield database_session
def token(role: UserRole, organization_id):
def token(role: UserRole, organization_id, real_account_id=None):
return SimpleNamespace(
effective_role=role,
effective_organization_id=organization_id,
real_account_id=real_account_id,
)
@@ -105,8 +112,115 @@ def test_superadmin_can_create_update_and_soft_delete(session):
assert session.get(Organization, created.id).deleted is True
def test_organization_stores_ordered_selected_institution_ids(session):
scope = Organization(name="Scope")
session.add(scope)
session.commit()
created = service.create_organization(
session,
token(UserRole.SUPER_ADMIN, scope.id),
CreateOrganizationRequest(
name="Institution list",
selected_openalex_institution_ids=[
"https://openalex.org/I123",
"I456",
"I123",
],
),
)
assert created.selected_openalex_institution_ids == ["I123", "I456"]
assert created.other_inst_id == "I123"
assert session.get(Organization, created.id).openalex_institution_id == "I123"
rows = session.exec(
select(OrganizationInstitution)
.where(OrganizationInstitution.organization_id == created.id)
.order_by(OrganizationInstitution.position)
).all()
assert [row.openalex_institution_id for row in rows] == ["I123", "I456"]
def test_empty_institution_list_clears_legacy_primary_institution(session):
organization = Organization(name="Organization", openalex_institution_id="I123")
session.add(organization)
session.commit()
updated = service.update_organization(
session,
token(UserRole.SUPER_ADMIN, organization.id),
organization.id,
UpdateOrganizationRequest(selected_openalex_institution_ids=[]),
)
assert updated.selected_openalex_institution_ids == []
assert updated.other_inst_id is None
assert session.get(Organization, organization.id).openalex_institution_id is None
def test_association_expansion_adds_only_child_and_related_with_child_priority(
monkeypatch,
):
async def fake_search(**kwargs):
return {
"hits": {
"hits": [
{
"_source": {
"id": "https://openalex.org/I100",
"display_name": "Selected institution",
"associated_institutions": [
{
"id": "https://openalex.org/I200",
"display_name": "Duplicate",
"relationship": "related",
},
{
"id": "https://openalex.org/I200",
"display_name": "Duplicate",
"relationship": "child",
},
{
"id": "https://openalex.org/I300",
"display_name": "Related",
"relationship": "related",
},
{
"id": "https://openalex.org/I400",
"display_name": "Parent",
"relationship": "parent",
},
{
"id": "https://openalex.org/I500",
"display_name": "Successor",
"relationship": "successor",
},
],
},
}
],
},
}
monkeypatch.setattr(service.elasticsearch, "search", fake_search)
result = asyncio.run(
service.get_institution_associations(
token(UserRole.SUPER_ADMIN, None), ["https://openalex.org/I100"]
)
)
assert result[0].id == "I100"
assert [
(association.id, association.relationship)
for association in result[0].associated_institutions
] == [("I200", "child"), ("I300", "related")]
def test_deleting_organization_deactivates_all_its_accounts(session):
admin_scope = Organization(name="Admin scope for delete")
organization = Organization(name="Organization to delete")
session.add(admin_scope)
session.add(organization)
session.flush()
active_account = Account(
@@ -129,7 +243,7 @@ def test_deleting_organization_deactivates_all_its_accounts(session):
session.commit()
service.delete_organization(
session, token(UserRole.SUPER_ADMIN, organization.id), organization.id
session, token(UserRole.SUPER_ADMIN, admin_scope.id), organization.id
)
session.refresh(active_account)
@@ -141,7 +255,9 @@ def test_deleting_organization_deactivates_all_its_accounts(session):
def test_marking_organization_deleted_deactivates_its_accounts(session):
admin_scope = Organization(name="Admin scope for update")
organization = Organization(name="Organization to update")
session.add(admin_scope)
session.add(organization)
session.flush()
account = Account(
@@ -155,7 +271,7 @@ def test_marking_organization_deleted_deactivates_its_accounts(session):
service.update_organization(
session,
token(UserRole.SUPER_ADMIN, organization.id),
token(UserRole.SUPER_ADMIN, admin_scope.id),
organization.id,
UpdateOrganizationRequest(deleted=True),
)
@@ -165,6 +281,61 @@ def test_marking_organization_deleted_deactivates_its_accounts(session):
assert account.epoch == 1
@pytest.mark.parametrize("delete_via_update", [False, True])
def test_current_organization_cannot_be_deleted(session, delete_via_update):
organization = Organization(name="Current organization")
session.add(organization)
session.commit()
access_token = token(UserRole.SUPER_ADMIN, organization.id)
with pytest.raises(HTTPException) as error:
if delete_via_update:
service.update_organization(
session,
access_token,
organization.id,
UpdateOrganizationRequest(deleted=True),
)
else:
service.delete_organization(session, access_token, organization.id)
assert error.value.status_code == 409
assert session.get(Organization, organization.id).deleted is False
def test_real_account_organization_cannot_be_deleted_while_impersonating(session):
real_organization = Organization(name="Real organization")
effective_organization = Organization(name="Effective organization")
session.add(real_organization)
session.add(effective_organization)
session.flush()
real_account = Account(
email="real-superadmin@example.org",
name="Real superadmin",
password_hash="hash",
organization_id=real_organization.id,
roles=[UserRole.SUPER_ADMIN],
)
session.add(real_account)
session.commit()
access_token = token(
UserRole.SUPER_ADMIN,
effective_organization.id,
real_account.id,
)
with pytest.raises(HTTPException) as error:
service.delete_organization(
session,
access_token,
real_organization.id,
)
assert error.value.status_code == 409
assert session.get(Organization, real_organization.id).deleted is False
assert session.get(Account, real_account.id).activated is True
@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER])
def test_only_superadmin_can_create_organizations(session, role):
organization = Organization(name="Scope")
@@ -741,6 +741,8 @@ async def _build_eu_cordis_search_query(
title: str | None = None,
funding_start_years: list[str] | None = None,
funding_end_years: list[str] | None = None,
active_from_year: int | None = None,
active_to_year: int | None = None,
countries: list[str] | None = None,
framework_programmes: list[str] | None = None,
funding_schemes: list[str] | None = None,
@@ -876,6 +878,18 @@ async def _build_eu_cordis_search_query(
if funding_end_years:
must_clauses.append(_eu_year_filters("endDate", funding_end_years))
# Period-overlap filter: a project was active in the selected interval when
# it started no later than the interval end and ended no earlier than the
# interval start. This is intentionally separate from exact-year filters.
if active_to_year is not None:
must_clauses.append(
{"range": {"startDate": {"lte": f"{active_to_year}-12-31"}}}
)
if active_from_year is not None:
must_clauses.append(
{"range": {"endDate": {"gte": f"{active_from_year}-01-01"}}}
)
# === Project core filters ===
if framework_programmes:
must_clauses.append({"terms": {"frameworkProgramme": framework_programmes}})
@@ -937,6 +951,8 @@ async def search_eu_cordis_projects(
title: str | None = None,
funding_start_years: list[str] | None = None,
funding_end_years: list[str] | None = None,
active_from_year: int | None = None,
active_to_year: int | None = None,
countries: list[str] | None = None,
framework_programmes: list[str] | None = None,
funding_schemes: list[str] | None = None,
@@ -965,6 +981,8 @@ async def search_eu_cordis_projects(
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
active_from_year=active_from_year,
active_to_year=active_to_year,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
-35
View File
@@ -9,41 +9,6 @@ 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 = {
@@ -369,6 +369,8 @@ async def search_dfg_projects(
sort_direction: str = "asc",
fuzzy: bool = False,
skip_enrichment: bool = False,
active_from_year: int | None = None,
active_to_year: int | None = None,
) -> DfgProjectPage:
"""Searches for DFG projects based on the provided filtering and sorting criteria.
@@ -489,6 +491,11 @@ async def search_dfg_projects(
if funding_end_years:
must_clauses.append({"terms": {"funding_end": funding_end_years}})
if active_to_year is not None:
must_clauses.append({"range": {"funding_start": {"lte": str(active_to_year)}}})
if active_from_year is not None:
must_clauses.append({"range": {"funding_end": {"gte": str(active_from_year)}}})
if names:
name_must_clauses = []
for full_name in names:
@@ -600,7 +607,6 @@ async def search_dfg_projects(
body["sort"] = [sort_config]
# print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
# === Execute Search ===
print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
response = await elasticsearch.search(
index=ESIndex.DFG_PROJECTS,
body=body,
@@ -612,6 +618,9 @@ async def search_dfg_projects(
if skip_enrichment:
return _complete_response_to_dfg_project_page(response, page, size)
if not hits:
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)
@@ -648,7 +657,7 @@ async def search_dfg_projects(
# person["institute_name_en"] = institute.get("institute_name_en")
# person["address_country_de"] = institute.get("address_country_de")
# person["address_country_en"] = institute.get("address_country_en")
print("ENRIECHED",source.get("institutions", []))
return _complete_response_to_dfg_project_page(response, page, size)
def _complete_response_to_dfg_project_page(
@@ -858,6 +867,8 @@ async def search_bund_projects_with_filters(
sort_direction: str = "asc",
fuzzy: bool = False,
skip_topic_enrichment: bool = False,
active_from_year: int | None = None,
active_to_year: int | None = None,
) -> BundProjectPage:
"""
Main search function for BUND projects, analogous to the DFG search.
@@ -999,6 +1010,15 @@ async def search_bund_projects_with_filters(
if funding_end_years:
must_clauses.append(_bund_year_filters("funding_end", funding_end_years))
if active_to_year is not None:
must_clauses.append(
{"range": {"funding_start": {"lte": f"31.12.{active_to_year}"}}}
)
if active_from_year is not None:
must_clauses.append(
{"range": {"funding_end": {"gte": f"01.01.{active_from_year}"}}}
)
body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
# === Sorting ===
sort_by = sort_by.strip().lower()
@@ -1151,11 +1171,13 @@ async def search_all_projects(
page = projects_filtering_properties.page
offset = page * size
response = await elasticsearch.search(
index=index,
size=size,
offset=offset,
query=query,
sort=sort,
track_total_hits=True,
)
return _response_to_funding_project_page(response=response, page=page, size=size)
+22 -22
View File
@@ -7,9 +7,6 @@ from inse.auth.service import CurrentUserAccessTokenPayloadDep
from inse.institutions.institutions_search_client import (
InstitutionsSearchClient,
)
from inse.projects.logic import (
is_projects_access_forbidden
)
from inse.institutions.router import get_institutions_search_client
from inse.models.bund_project_details import BundProjectDetails
from inse.models.dfg_project_details import DfgProjectDetails
@@ -33,6 +30,7 @@ from inse.projects.model import (
SortDirection,
)
from inse.tags import Tags
from inse.auth.service import can_fetch_gdpr_relevant_data
from fastapi import HTTPException as HttpException
logger = logging.getLogger(__name__)
@@ -146,12 +144,13 @@ async def get_dfg_projects(
sort_direction,
fuzzy,
)
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 or raw_oa_institution_id):
is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id)
if not is_allowed:
raise HttpException(
status_code=403,
detail="Access denied for the provided author ID or institution ID",
)
return await projects_service.get_dfg_projects(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
@@ -266,14 +265,14 @@ async def search_bund_projects(
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
] = 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",
)
if (raw_oa_institution_id):
is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = None, raw_oa_institution_id = raw_oa_institution_id)
if not is_allowed:
raise HttpException(
status_code=403,
detail="Access denied for the provided author ID or institution ID",
)
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,
@@ -451,12 +450,13 @@ async def search_eu_cordis_projects_endpoint(
sort_direction,
fuzzy,
)
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 or raw_oa_institution_id):
is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id)
if not is_allowed:
raise HttpException(
status_code=403,
detail="Access denied for the provided author ID or institution ID",
)
return await search_eu_cordis_projects(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
+13 -1
View File
@@ -188,6 +188,8 @@ async def get_dfg_projects(
sort_direction: str = "asc",
fuzzy: bool = False,
skip_enrichment: bool = False,
active_from_year: int | None = None,
active_to_year: int | None = None,
) -> DfgProjectPage:
logger.debug(
"Fetching DFG projects for author_id=%s, author_filter_ids=%s, "
@@ -284,6 +286,8 @@ async def get_dfg_projects(
sort_direction=sort_direction,
fuzzy=fuzzy,
skip_enrichment=skip_enrichment,
active_from_year=active_from_year,
active_to_year=active_to_year,
)
async def get_institution_cordis_eu_projects_funding_over_time(
@@ -459,6 +463,8 @@ async def search_bund_projects_with_filters(
sort_by: str = "title",
sort_direction: str = "asc",
fuzzy: bool = False,
active_from_year: int | None = None,
active_to_year: int | None = None,
) -> BundProjectPage:
institution_aliases = []
if raw_oa_institution_id:
@@ -494,7 +500,9 @@ async def search_bund_projects_with_filters(
size=size,
sort_by=sort_by,
sort_direction=sort_direction,
fuzzy=fuzzy
fuzzy=fuzzy,
active_from_year=active_from_year,
active_to_year=active_to_year,
)
def _calculate_funding_over_time(
@@ -656,6 +664,8 @@ async def search_eu_cordis_projects(
title: str | None = None,
funding_start_years: list[str] | None = None,
funding_end_years: list[str] | None = None,
active_from_year: int | None = None,
active_to_year: int | None = None,
countries: list[str] | None = None,
framework_programmes: list[str] | None = None,
funding_schemes: list[str] | None = None,
@@ -716,6 +726,8 @@ async def search_eu_cordis_projects(
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
active_from_year=active_from_year,
active_to_year=active_to_year,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
@@ -2,6 +2,21 @@ import pytest
from inse.projects import eu_cordis_projects_client as eu_cordis_search_client
@pytest.mark.anyio
async def test_active_period_filter_matches_projects_overlapping_interval():
query, _, _ = await eu_cordis_search_client._build_eu_cordis_search_query(
active_from_year=2022,
active_to_year=2026,
)
assert {"range": {"startDate": {"lte": "2026-12-31"}}} in query["bool"][
"must"
]
assert {"range": {"endDate": {"gte": "2022-01-01"}}} in query["bool"][
"must"
]
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_title():
"""Test searching EU CORDIS projects by title."""
@@ -362,4 +377,4 @@ async def test_search_eu_cordis_projects_with_fuzzy_topic_search():
# Note: This may return 0 results if the topic ID doesn't exist
# The important thing is that it doesn't crash
assert isinstance(res.total, int)
assert isinstance(res.elements, list)
assert isinstance(res.elements, list)
@@ -1,4 +1,7 @@
from unittest.mock import AsyncMock, patch
import pytest
from inse.projects import projects_search_client
@@ -20,6 +23,33 @@ async def test_search_dfg_projects():
for name in element.names
)
@pytest.mark.anyio
async def test_search_dfg_projects_returns_empty_page_without_enrichment_crash():
response = {
"hits": {
"total": {"value": 0},
"hits": [],
}
}
with patch(
"inse.projects.projects_search_client.elasticsearch.search",
new=AsyncMock(return_value=response),
) as mocked_search:
result = await projects_search_client.search_dfg_projects(
page=0,
size=1,
funding_start_years=["2022"],
funding_end_years=["2026"],
)
assert result.total == 0
assert result.elements == []
query = mocked_search.await_args.kwargs["body"]["query"]
assert {"terms": {"funding_start": ["2022"]}} in query["bool"]["must"]
assert {"terms": {"funding_end": ["2026"]}} in query["bool"]["must"]
@pytest.mark.anyio
async def test_get_dfg_project_by_id():
# Get by ID of the project we found or a known one
+45
View File
@@ -4,6 +4,9 @@ from typing import Annotated
import inse.topics.v2.service as topics_service
from fastapi import APIRouter, Path, Query
from inse.model import SortDirection
from inse.models.openalex.domain import Domain
from inse.models.openalex.model_field import ModelField
from inse.models.openalex.subfield import Subfield
from inse.models.openalex.topic import Topic
from inse.router_prefixes import RouterPrefixes
from inse.tags import Tags
@@ -78,6 +81,48 @@ async def get_topic_by_id(
)
@router.get(
"/domains/single/{domain_id}",
operation_id="getDomainById",
summary="Returns a domain for a given domain ID.",
)
async def get_domain_by_id(
domain_id: Annotated[
str,
Path(description="The ID of the domain to retrieve."),
],
) -> Domain:
return await topics_service.get_domain_by_id_or_raise(domain_id=domain_id)
@router.get(
"/fields/single/{field_id}",
operation_id="getFieldById",
summary="Returns a field for a given field ID.",
)
async def get_field_by_id(
field_id: Annotated[
str,
Path(description="The ID of the field to retrieve."),
],
) -> ModelField:
return await topics_service.get_field_by_id_or_raise(field_id=field_id)
@router.get(
"/subfields/single/{subfield_id}",
operation_id="getSubfieldById",
summary="Returns a subfield for a given subfield ID.",
)
async def get_subfield_by_id(
subfield_id: Annotated[
str,
Path(description="The ID of the subfield to retrieve."),
],
) -> Subfield:
return await topics_service.get_subfield_by_id_or_raise(subfield_id=subfield_id)
@router.get(
"/topics/id",
operation_id="getTopicsByIds",
+114
View File
@@ -1,6 +1,9 @@
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
from inse.model import ESIndex, SortDirection
from inse.models.openalex.domain import Domain
from inse.models.openalex.model_field import ModelField
from inse.models.openalex.subfield import Subfield
from inse.models.openalex.topic import Topic
from inse.topics.v2.model import TopicPageV2, TopicSortBy
@@ -184,6 +187,117 @@ async def get_topic_by_id_or_raise(raw_oa_topic_id: str) -> Topic:
return topic
async def get_domain_by_id(domain_id: str) -> Domain | None:
"""Retrieves a domain based on its ID.
Args:
domain_id (str): The numeric OpenAlex ID of the domain to retrieve (e.g. "4").
Returns:
Domain | None: The domain matching the provided ID, or None if not found.
"""
response = await elasticsearch.get(
index=ESIndex.OPENALEX_DOMAINS,
doc_id=domain_id,
source=["id", "display_name", "description"],
)
if response.get("found"):
return Domain.from_dict(response.get("_source", {}))
return None
async def get_domain_by_id_or_raise(domain_id: str) -> Domain:
"""Retrieves a domain based on its ID, raising an exception if not found.
Args:
domain_id (str): The ID of the domain to retrieve.
Raises:
NotFoundException: If the domain with the specified ID is not found.
Returns:
Domain: The domain matching the provided ID.
"""
domain = await get_domain_by_id(domain_id)
if domain is None:
raise NotFoundException(f"Domain with ID {domain_id} not found.")
return domain
async def get_field_by_id(field_id: str) -> ModelField | None:
"""Retrieves a field based on its ID.
Args:
field_id (str): The numeric OpenAlex ID of the field to retrieve (e.g. "27").
Returns:
ModelField | None: The field matching the provided ID, or None if not found.
"""
response = await elasticsearch.get(
index=ESIndex.OPENALEX_FIELDS,
doc_id=field_id,
source=["id", "display_name", "description"],
)
if response.get("found"):
return ModelField.from_dict(response.get("_source", {}))
return None
async def get_field_by_id_or_raise(field_id: str) -> ModelField:
"""Retrieves a field based on its ID, raising an exception if not found.
Args:
field_id (str): The ID of the field to retrieve.
Raises:
NotFoundException: If the field with the specified ID is not found.
Returns:
ModelField: The field matching the provided ID.
"""
field = await get_field_by_id(field_id)
if field is None:
raise NotFoundException(f"Field with ID {field_id} not found.")
return field
async def get_subfield_by_id(subfield_id: str) -> Subfield | None:
"""Retrieves a subfield based on its ID.
Args:
subfield_id (str): The numeric OpenAlex ID of the subfield to retrieve (e.g. "2743").
Returns:
Subfield | None: The subfield matching the provided ID, or None if not found.
"""
response = await elasticsearch.get(
index=ESIndex.OPENALEX_SUBFIELDS,
doc_id=subfield_id,
source=["id", "display_name", "description"],
)
if response.get("found"):
return Subfield.from_dict(response.get("_source", {}))
return None
async def get_subfield_by_id_or_raise(subfield_id: str) -> Subfield:
"""Retrieves a subfield based on its ID, raising an exception if not found.
Args:
subfield_id (str): The ID of the subfield to retrieve.
Raises:
NotFoundException: If the subfield with the specified ID is not found.
Returns:
Subfield: The subfield matching the provided ID.
"""
subfield = await get_subfield_by_id(subfield_id)
if subfield is None:
raise NotFoundException(f"Subfield with ID {subfield_id} not found.")
return subfield
async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2:
"""Retrieves topics based on a list of topic IDs.
@@ -169,6 +169,8 @@ model/idTokenMetadata.ts
model/inseAccountManagementModelOrganizationProfile.ts
model/inseOrganizationManagementModelOrganizationProfile.ts
model/institution.ts
model/institutionAssociation.ts
model/institutionAssociationsResponse.ts
model/institutionFunderSummary.ts
model/institutionGeo.ts
model/institutionIds.ts
File diff suppressed because it is too large Load Diff
+652 -259
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -9,12 +9,18 @@
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { CreateOrganizationRequest } from '../model/createOrganizationRequest';
@@ -23,292 +29,679 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { InseOrganizationManagementModelOrganizationProfile } from '../model/inseOrganizationManagementModelOrganizationProfile';
// @ts-ignore
import { InstitutionAssociationsResponse } from '../model/institutionAssociationsResponse';
// @ts-ignore
import { OrganizationPage } from '../model/organizationPage';
// @ts-ignore
import { UpdateOrganizationRequest } from '../model/updateOrganizationRequest';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class OrganizationService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
/**
* Create Organization
* @endpoint post /api/organizations
* @param createOrganizationRequest
* @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 createOrganisation(
createOrganizationRequest: CreateOrganizationRequest,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<InseOrganizationManagementModelOrganizationProfile>;
public createOrganisation(
createOrganizationRequest: CreateOrganizationRequest,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<
HttpResponse<InseOrganizationManagementModelOrganizationProfile>
>;
public createOrganisation(
createOrganizationRequest: CreateOrganizationRequest,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
public createOrganisation(
createOrganizationRequest: CreateOrganizationRequest,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
createOrganizationRequest === null ||
createOrganizationRequest === undefined
) {
throw new Error(
'Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.',
);
}
/**
* Create Organization
* @endpoint post /api/organizations
* @param createOrganizationRequest
* @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 createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (createOrganizationRequest === null || createOrganizationRequest === undefined) {
throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.');
}
let localVarHeaders = this.defaultHeaders;
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let localVarPath = `/api/organizations`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: createOrganizationRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
/**
* Delete Organization
* @endpoint delete /api/organizations/{organization_id}
* @param organizationId
* @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 deleteOrganisation(
organizationId: string,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any>;
public deleteOrganisation(
organizationId: string,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<any>>;
public deleteOrganisation(
organizationId: string,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<any>>;
public deleteOrganisation(
organizationId: string,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (organizationId === null || organizationId === undefined) {
throw new Error(
'Required parameter organizationId was null or undefined when calling deleteOrganisation.',
);
}
let localVarPath = `/api/organizations`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: createOrganizationRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/organizations/${this.configuration.encodeParam({ name: 'organizationId', value: organizationId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: 'uuid' })}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>(
'delete',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Get Organizations
* @endpoint get /api/organizations
* @param page
* @param pageSize
* @param offset
* @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 getOrganisations(
page?: number,
pageSize?: number,
offset?: number,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<OrganizationPage>;
public getOrganisations(
page?: number,
pageSize?: number,
offset?: number,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<OrganizationPage>>;
public getOrganisations(
page?: number,
pageSize?: number,
offset?: number,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<OrganizationPage>>;
public getOrganisations(
page?: number,
pageSize?: number,
offset?: number,
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,
<any>page,
'page',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>pageSize,
'page_size',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>offset,
'offset',
);
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/organizations`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<OrganizationPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Get Organization Institution Associations
* @endpoint get /api/organizations/institutions/associations
* @param institutionIds
* @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 getOrganizationInstitutionAssociations(
institutionIds: Array<string>,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<InstitutionAssociationsResponse>>;
public getOrganizationInstitutionAssociations(
institutionIds: Array<string>,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<InstitutionAssociationsResponse>>>;
public getOrganizationInstitutionAssociations(
institutionIds: Array<string>,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<InstitutionAssociationsResponse>>>;
public getOrganizationInstitutionAssociations(
institutionIds: Array<string>,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (institutionIds === null || institutionIds === undefined) {
throw new Error(
'Required parameter institutionIds was null or undefined when calling getOrganizationInstitutionAssociations.',
);
}
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (institutionIds) {
institutionIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'institution_ids',
);
});
}
/**
* Delete Organization
* @endpoint delete /api/organizations/{organization_id}
* @param organizationId
* @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 deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (organizationId === null || organizationId === undefined) {
throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.');
}
let localVarHeaders = this.defaultHeaders;
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
/**
* Get Organizations
* @endpoint get /api/organizations
* @param page
* @param pageSize
* @param offset
* @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 getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OrganizationPage>;
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrganizationPage>>;
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrganizationPage>>;
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'page_size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>offset, 'offset');
const localVarTransferCache: boolean = options?.transferCache ?? true;
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/organizations`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<OrganizationPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
/**
* Update Organization
* @endpoint put /api/organizations/{organization_id}
* @param organizationId
* @param updateOrganizationRequest
* @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 updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (organizationId === null || organizationId === undefined) {
throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.');
}
if (updateOrganizationRequest === null || updateOrganizationRequest === undefined) {
throw new Error('Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.');
}
let localVarPath = `/api/organizations/institutions/associations`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<InstitutionAssociationsResponse>>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>('put', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: updateOrganizationRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
/**
* Update Organization
* @endpoint put /api/organizations/{organization_id}
* @param organizationId
* @param updateOrganizationRequest
* @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 updateOrganisation(
organizationId: string,
updateOrganizationRequest: UpdateOrganizationRequest,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<InseOrganizationManagementModelOrganizationProfile>;
public updateOrganisation(
organizationId: string,
updateOrganizationRequest: UpdateOrganizationRequest,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<
HttpResponse<InseOrganizationManagementModelOrganizationProfile>
>;
public updateOrganisation(
organizationId: string,
updateOrganizationRequest: UpdateOrganizationRequest,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
public updateOrganisation(
organizationId: string,
updateOrganizationRequest: UpdateOrganizationRequest,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (organizationId === null || organizationId === undefined) {
throw new Error(
'Required parameter organizationId was null or undefined when calling updateOrganisation.',
);
}
if (
updateOrganizationRequest === null ||
updateOrganizationRequest === undefined
) {
throw new Error(
'Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.',
);
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/organizations/${this.configuration.encodeParam({ name: 'organizationId', value: organizationId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: 'uuid' })}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>(
'put',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: updateOrganizationRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
File diff suppressed because it is too large Load Diff
@@ -1,16 +1,15 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface CreateOrganizationRequest {
name: string;
other_inst_id?: string | null;
export interface CreateOrganizationRequest {
name: string;
other_inst_id?: string | null;
selected_openalex_institution_ids?: Array<string> | null;
}
+1 -2
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -19,4 +19,3 @@ export interface DfgProjectTopic {
project_count: number;
keywords: Array<DfgProjectKeyword>;
}
+29
View File
@@ -0,0 +1,29 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { DomainFieldsInner } from './domainFieldsInner';
import { DomainIds } from './domainIds';
/**
* Top-level category in the topic hierarchy (4 total)
*/
export interface Domain {
id?: string | null;
display_name?: string | null;
description?: string | null;
display_name_alternatives?: Array<string> | null;
fields?: Array<DomainFieldsInner> | null;
siblings?: Array<DomainFieldsInner> | null;
ids?: DomainIds | null;
works_count?: number | null;
cited_by_count?: number | null;
works_api_url?: string | null;
created_date?: string | null;
updated_date?: string | null;
}
@@ -0,0 +1,17 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* DomainFieldsInner
*/
export interface DomainFieldsInner {
id?: string | null;
display_name?: string | null;
}
+18
View File
@@ -0,0 +1,18 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* External identifiers:
*/
export interface DomainIds {
openalex?: string | null;
wikidata?: string | null;
wikipedia?: string | null;
}
@@ -1,19 +1,18 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface InseOrganizationManagementModelOrganizationProfile {
id: string;
name: string;
other_inst_id?: string | null;
deleted: boolean;
member_count: number;
export interface InseOrganizationManagementModelOrganizationProfile {
id: string;
name: string;
other_inst_id?: string | null;
selected_openalex_institution_ids?: Array<string>;
deleted: boolean;
member_count: number;
}
@@ -0,0 +1,23 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface InstitutionAssociation {
id: string;
display_name: string;
relationship: InstitutionAssociation.RelationshipEnum;
}
export namespace InstitutionAssociation {
export const RelationshipEnum = {
Child: 'child',
Related: 'related',
} as const;
export type RelationshipEnum =
(typeof RelationshipEnum)[keyof typeof RelationshipEnum];
}
@@ -0,0 +1,16 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { InstitutionAssociation } from './institutionAssociation';
export interface InstitutionAssociationsResponse {
id: string;
display_name: string;
associated_institutions?: Array<InstitutionAssociation>;
}
+31
View File
@@ -0,0 +1,31 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { DomainFieldsInner } from './domainFieldsInner';
import { DomainIds } from './domainIds';
import { WorkTopicDomain } from './workTopicDomain';
/**
* Second-level category in the topic hierarchy (26 total)
*/
export interface ModelField {
id?: string | null;
display_name?: string | null;
description?: string | null;
display_name_alternatives?: Array<string> | null;
domain?: WorkTopicDomain | null;
subfields?: Array<DomainFieldsInner> | null;
siblings?: Array<DomainFieldsInner> | null;
ids?: DomainIds | null;
works_count?: number | null;
cited_by_count?: number | null;
works_api_url?: string | null;
created_date?: string | null;
updated_date?: string | null;
}
+9
View File
@@ -78,6 +78,9 @@ export * from './dfgProjectSummary';
export * from './dfgProjectTopic';
export * from './dfgProjectTopics';
export * from './dockerHealth';
export * from './domain';
export * from './domainFieldsInner';
export * from './domainIds';
export * from './edge';
export * from './euCordisEurosciVocSummary';
export * from './euCordisOrganizationSelectorPage';
@@ -134,6 +137,8 @@ export * from './idTokenMetadata';
export * from './inseAccountManagementModelOrganizationProfile';
export * from './inseOrganizationManagementModelOrganizationProfile';
export * from './institution';
export * from './institutionAssociation';
export * from './institutionAssociationsResponse';
export * from './institutionFunderSummary';
export * from './institutionGeo';
export * from './institutionIds';
@@ -172,6 +177,7 @@ export * from './matchedTopic';
export * from './mentionedPerson';
export * from './meta';
export * from './model2YrMeanCitedness';
export * from './modelField';
export * from './newsArticle';
export * from './newsArticleDetail';
export * from './newsPage';
@@ -206,6 +212,9 @@ export * from './score';
export * from './selectedAuthorsRequest';
export * from './sortDirection';
export * from './startCollaborationGraphResponse';
export * from './subfield';
export * from './subfieldDomain';
export * from './subfieldField';
export * from './subfieldShare';
export * from './timespan';
export * from './tokenType';
+12 -12
View File
@@ -1,22 +1,22 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { MatchedTopic } from './matchedTopic';
export interface NewsArticle {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
related?: boolean | null;
export interface NewsArticle {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
related?: boolean | null;
topics?: Array<MatchedTopic> | null;
}
+14 -16
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -10,19 +10,17 @@
import { MatchedTopic } from './matchedTopic';
import { MentionedPerson } from './mentionedPerson';
export interface NewsArticleDetail {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
related?: boolean | null;
full_content?: string | null;
authors?: Array<MentionedPerson>;
keywords?: Array<string>;
topics?: Array<MatchedTopic>;
export interface NewsArticleDetail {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
related?: boolean | null;
topics?: Array<MatchedTopic>;
full_content?: string | null;
authors?: Array<MentionedPerson>;
keywords?: Array<string>;
}
+33
View File
@@ -0,0 +1,33 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { DomainFieldsInner } from './domainFieldsInner';
import { DomainIds } from './domainIds';
import { SubfieldDomain } from './subfieldDomain';
import { SubfieldField } from './subfieldField';
/**
* Third-level category in the topic hierarchy (254 total)
*/
export interface Subfield {
id?: string | null;
display_name?: string | null;
description?: string | null;
display_name_alternatives?: Array<string> | null;
field?: SubfieldField | null;
domain?: SubfieldDomain | null;
topics?: Array<DomainFieldsInner> | null;
siblings?: Array<DomainFieldsInner> | null;
ids?: DomainIds | null;
works_count?: number | null;
cited_by_count?: number | null;
works_api_url?: string | null;
created_date?: string | null;
updated_date?: string | null;
}
@@ -0,0 +1,17 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* The domain containing this subfield (top level of hierarchy).
*/
export interface SubfieldDomain {
id?: string | null;
display_name?: string | null;
}
+17
View File
@@ -0,0 +1,17 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* The field containing this subfield (parent level).
*/
export interface SubfieldField {
id?: string | null;
display_name?: string | null;
}
@@ -1,17 +1,16 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface UpdateOrganizationRequest {
name?: string | null;
other_inst_id?: string | null;
deleted?: boolean | null;
export interface UpdateOrganizationRequest {
name?: string | null;
other_inst_id?: string | null;
selected_openalex_institution_ids?: Array<string> | null;
deleted?: boolean | null;
}
+9 -1
View File
@@ -36,6 +36,7 @@ import {
workPageResolver,
workQueryParamKeys,
} from './resolvers/work-page.resolver';
import { keywordsNewsPageResolver } from './resolvers/keywords-news-page.resolver';
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
import { selectedBundInstitutionsResolver } from './resolvers/selected-bund-institutions.resolver';
@@ -273,7 +274,14 @@ export const routes: Routes = [
resolvingFor: RESOLVING_WORK_PAGE_FOR.KEYWORDS_SEARCH,
},
},
{ path: 'news', component: KeywordsToNewsResultsComponent },
{
path: 'news',
component: KeywordsToNewsResultsComponent,
runGuardsAndResolvers: 'always',
resolve: {
newsPage: keywordsNewsPageResolver,
},
},
{
path: 'trends',
component: UniTrendParentComponent,
@@ -1,76 +1,80 @@
import {
Directive,
OnChanges,
Input,
ElementRef,
Input,
OnChanges,
Renderer2,
SimpleChanges,
effect,
inject,
} from '@angular/core';
import { SimpleChanges } from '@angular/core';
@Directive({ selector: '[skText]', standalone: true })
import { ResolverStateService } from '../../app/shared/services/resolver-state.service';
@Directive({
selector: 'span, [skText]',
standalone: true,
})
export class SkTextDirective implements OnChanges {
@Input() skText = false;
private originalText = '';
private originalColor = '';
private readonly el = inject(ElementRef<HTMLElement>);
private readonly renderer = inject(Renderer2);
private readonly resolverStateService = inject(ResolverStateService);
constructor(
private el: ElementRef,
private renderer: Renderer2,
) {}
constructor() {
effect(() => {
const loading = this.skText || this.resolverStateService.isResolving();
ngOnChanges(changes: SimpleChanges) {
const change = changes['skText'];
// skip if value didn't actually change, or is undefined
if (!change) return;
this.skText ? this.showSkeleton() : this.hideSkeleton();
if (loading) {
this.showSkeleton();
} else {
this.hideSkeleton();
}
});
}
private showSkeleton() {
const el: HTMLElement = this.el.nativeElement;
this.originalText = el.textContent ?? '';
this.originalColor = el.style.color;
ngOnChanges(changes: SimpleChanges): void {
if (!changes['skText']) {
return;
}
// measure natural width before blanking text
const width = Math.min(Math.max(this.originalText.length * 7.5, 48), 60);
const height = 20;
this.renderer.addClass(el, 'sk-text-loading');
this.renderer.setStyle(el, 'color', 'transparent');
this.renderer.setStyle(
el,
'background',
'linear-gradient(90deg, #e2e8f0 25%, #f8fafc 50%, #e2e8f0 75%)',
);
this.renderer.setStyle(el, 'background-size', '600px 100%');
this.renderer.setStyle(el, 'animation', 'sk-shimmer 1.6s infinite linear');
this.renderer.setStyle(el, 'border-radius', '4px');
this.renderer.setStyle(el, 'min-width', `${width}px`);
this.renderer.setStyle(el, 'max-height', `${height}px`);
this.renderer.setStyle(el, 'display', 'inline-block');
this.renderer.setStyle(el, 'overflow', 'hidden');
this.renderer.setStyle(el, 'pointer-events', 'none');
if (this.skText || this.resolverStateService.isResolving()) {
this.showSkeleton();
} else {
this.hideSkeleton();
}
}
Array.from(el.children).forEach((child) => {
private showSkeleton(): void {
const element = this.el.nativeElement;
if (element.classList.contains('sk-text-loading')) {
return;
}
const text = element.textContent?.trim() ?? '';
// For ordinary text elements only. Table cells use CSS width naturally.
if (element.tagName.toLowerCase() !== 'td') {
this.renderer.setStyle(element, 'min-width', `${20}px`);
this.renderer.setStyle(element, 'height', '20px');
}
this.renderer.addClass(element, 'sk-text-loading');
Array.from(element.children).forEach((child) => {
this.renderer.setStyle(child, 'visibility', 'hidden');
});
}
private hideSkeleton() {
const el: HTMLElement = this.el.nativeElement;
this.renderer.removeClass(el, 'sk-text-loading');
this.renderer.removeStyle(el, 'color');
this.renderer.removeStyle(el, 'background');
this.renderer.removeStyle(el, 'background-size');
this.renderer.removeStyle(el, 'animation');
this.renderer.removeStyle(el, 'border-radius');
this.renderer.removeStyle(el, 'min-width');
this.renderer.removeStyle(el, 'max-height');
this.renderer.removeStyle(el, 'display');
this.renderer.removeStyle(el, 'overflow');
this.renderer.removeStyle(el, 'pointer-events');
private hideSkeleton(): void {
const element = this.el.nativeElement;
Array.from(el.children).forEach((child) => {
this.renderer.removeClass(element, 'sk-text-loading');
this.renderer.removeStyle(element, 'min-width');
this.renderer.removeStyle(element, 'height');
Array.from(element.children).forEach((child) => {
this.renderer.removeStyle(child, 'visibility');
});
}
@@ -130,12 +130,14 @@ export class ComponentTooltipDirective<T extends object> implements OnDestroy {
.flexibleConnectedTo(this.elementRef)
.withPositions(positions)
.withFlexibleDimensions(false)
.withViewportMargin(12)
.withPush(true);
this.overlayRef = this.overlay.create({
positionStrategy,
scrollStrategy: this.overlay.scrollStrategies.reposition(),
panelClass: 'app-tooltip-panel',
maxWidth: this.tooltipMaxWidth() ?? 'calc(100vw - 24px)',
});
const portal = new ComponentPortal(this.component(), null, this.injector);
@@ -10,8 +10,22 @@
}}
</p>
</div>
</header>
<section class="account-toolbar">
<app-query-param-input
class="account-search"
queryParamKey="search"
label="Nach Name oder E-Mail suchen" />
<app-query-param-selector
class="account-organization"
queryParamKey="organization_id"
[options]="selectorOptions()"
label="Organisation"
[allowEmptyValue]="true" />
@if (!isReadOnly) {
<button
class="create-account-button"
mat-flat-button
color="primary"
type="button"
@@ -21,19 +35,6 @@
Neuer Account
</button>
}
</header>
<section style="display: flex; gap: 1rem; align-items: center">
<app-query-param-input
queryParamKey="search"
label="Nach Name oder E-Mail suchen"
style="width: 35%" />
<app-query-param-selector
queryParamKey="organization_id"
[options]="selectorOptions()"
label="Organisation"
[allowEmptyValue]="true"
style="width: 25%" />
</section>
<mat-card appearance="outlined">
<mat-card-content>
@@ -19,6 +19,25 @@
gap: 16px;
}
.account-toolbar {
display: flex;
align-items: center;
gap: 16px;
}
.account-search {
flex: 0 1 35%;
}
.account-organization {
flex: 0 1 25%;
}
.create-account-button {
flex: 0 0 auto;
margin-left: auto;
}
h1,
h2,
p {
@@ -155,6 +174,22 @@ tr.deactivated:not(.deleted) {
align-items: flex-start;
flex-direction: column;
}
.account-toolbar {
align-items: stretch;
flex-direction: column;
}
.account-search,
.account-organization {
flex-basis: auto;
width: 100%;
}
.create-account-button {
align-self: flex-start;
margin-left: 0;
}
}
mat-card,
@@ -1,6 +1,6 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { Observable, catchError, forkJoin, map, of } from 'rxjs';
import { Configuration } from '../../api';
import { TopicTreemapData } from '../../shared/ui/topic-treemap/topic-treemap.models';
@@ -59,6 +59,8 @@ export interface DfgProjectTopic {
field?: string | null;
domain?: string | null;
project_count: number;
field_project_count: number;
subfield_project_count: number;
keywords: DfgProjectKeyword[];
}
@@ -75,6 +77,9 @@ export interface DfgProjectTopics {
topics: DfgProjectTopic[];
}
export interface EuProjectTopics extends DfgProjectTopics {}
export interface BundProjectTopics extends DfgProjectTopics {}
export interface TopAuthor {
id?: string | null;
name: string;
@@ -90,6 +95,11 @@ export interface TopAuthorStatistics {
news: TopAuthor[];
}
export interface TopAuthorAnalysis {
institution_id: string;
authors: TopAuthor[];
}
export interface TopicWordCloudWord {
id: string;
name: string;
@@ -202,12 +212,59 @@ export class DashboardStatisticsService {
);
}
getEuProjectTopics(
period: DashboardPeriodBounds = {},
): Observable<EuProjectTopics> {
return this.httpClient.get<EuProjectTopics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/topics`,
{ params: this.periodParams(period) },
);
}
getBundProjectTopics(
period: DashboardPeriodBounds = {},
): Observable<BundProjectTopics> {
return this.httpClient.get<BundProjectTopics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bund/topics`,
{ params: this.periodParams(period) },
);
}
getTopAuthors(
period: DashboardPeriodBounds = {},
): Observable<TopAuthorStatistics> {
return this.httpClient.get<TopAuthorStatistics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors`,
{ params: this.periodParams(period) },
const analysis = (source: string) =>
this.httpClient
.get<TopAuthorAnalysis>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors/${source}`,
{ params: this.periodParams(period) },
)
.pipe(catchError(() => of(null)));
return forkJoin({
works: analysis('works'),
projects: analysis('projects'),
euProjects: analysis('eu-projects'),
patents: analysis('patents'),
news: analysis('news'),
}).pipe(
map((responses) => {
const successfulResponse = Object.values(responses).find(
(response) => response !== null,
);
if (!successfulResponse) {
throw new Error('All top-author analyses failed.');
}
return {
institution_id: successfulResponse.institution_id,
works: responses.works?.authors ?? [],
projects: responses.projects?.authors ?? [],
eu_projects: responses.euProjects?.authors ?? [],
patents: responses.patents?.authors ?? [],
news: responses.news?.authors ?? [],
};
}),
);
}
@@ -40,7 +40,9 @@
[attr.aria-disabled]="!institutionRouteId()"
[attr.aria-label]="
'Publikationen von ' + organizationName() + ' anzeigen'
">
"
matTooltip="Anzahl der Publikationen im ausgewählten Zeitraum"
matTooltipPosition="above">
<div class="statistics-icon statistics-icon--publications">
<mat-icon>menu_book</mat-icon>
</div>
@@ -60,7 +62,9 @@
class="statistics-card"
routerLink="/persons"
[queryParams]="personListQueryParams()"
[attr.aria-label]="'Personen von ' + organizationName() + ' anzeigen'">
[attr.aria-label]="'Personen von ' + organizationName() + ' anzeigen'"
matTooltip="Anzahl der Personen im ausgewählten Zeitraum"
matTooltipPosition="above">
<div class="statistics-icon statistics-icon--persons">
<mat-icon>groups</mat-icon>
</div>
@@ -81,9 +85,11 @@
[routerLink]="['/institution', institutionRouteId(), 'patents']"
[class.disabled]="!institutionRouteId()"
[attr.aria-disabled]="!institutionRouteId()"
[attr.aria-label]="'Patente von ' + organizationName() + ' anzeigen'">
[attr.aria-label]="'Patente von ' + organizationName() + ' anzeigen'"
matTooltip="Anzahl der Patente im ausgewählten Zeitraum"
matTooltipPosition="above">
<div class="statistics-icon statistics-icon--patents">
<mat-icon>description</mat-icon>
<mat-icon>{{ patentIcon }}</mat-icon>
</div>
<div>
<span>Patente</span>
@@ -101,7 +107,9 @@
class="statistics-card"
routerLink="/projects"
[queryParams]="{ selected_project_types: 'eu' }"
aria-label="EU-Projekte anzeigen">
aria-label="EU-Projekte anzeigen"
matTooltip="Anzahl der laufenden, abgeschlossenen und kommenden EU-Projekte im ausgewählten Zeitraum"
matTooltipPosition="above">
<div class="statistics-icon statistics-icon--eu-projects">
<mat-icon>public</mat-icon>
</div>
@@ -121,7 +129,9 @@
class="statistics-card"
routerLink="/projects"
[queryParams]="{ selected_project_types: 'bund' }"
aria-label="Bund-Projekte anzeigen">
aria-label="Bund-Projekte anzeigen"
matTooltip="Anzahl der laufenden, abgeschlossenen und kommenden Bund-Projekte im ausgewählten Zeitraum"
matTooltipPosition="above">
<div class="statistics-icon statistics-icon--bund-projects">
<mat-icon>account_balance</mat-icon>
</div>
@@ -141,7 +151,9 @@
class="statistics-card"
routerLink="/projects"
[queryParams]="{ selected_project_types: 'dfg' }"
aria-label="DFG-Projekte anzeigen">
aria-label="DFG-Projekte anzeigen"
matTooltip="Anzahl der laufenden, abgeschlossenen und kommenden DFG-Projekte im ausgewählten Zeitraum"
matTooltipPosition="above">
<div class="statistics-icon statistics-icon--dfg-projects">
<mat-icon>science</mat-icon>
</div>
@@ -317,6 +329,92 @@
</section>
}
@if (euTopicsLoading || euTopicsError || euProjectTopics) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>EU-Projekt-Topics</h2>
<p>
Gematchte EU-Projekte nach Field, Subfield und Topic. Ein Klick
auf ein Topic zeigt die zugehörigen Keywords.
</p>
</div>
@if (euProjectTopics) {
<p class="dfg-topic-summary">
{{ euProjectTopics.matched_project_count | number }} von
{{ euProjectTopics.project_count | number }} Projekten gematcht
</p>
}
</header>
@if (euTopicsLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="EU-Topics werden geladen …"
icon="account_tree"
size="72"
diameter="72"></app-loading>
</div>
} @else if (euTopicsError) {
<p class="statistics-error">
Die EU-Topic-Treemap konnte nicht geladen werden.
</p>
} @else {
<app-topic-treemap
[data]="euTopicTreemap"
[selectedNodeId]="selectedEuTopicTreemapNode"
countLabel="EU-Projekte"
[showCountInTooltip]="false"
(selectedNodeIdChange)="onEuTopicTreemapNodeChange($event)"
(topicSelect)="onEuTopicTreemapTopicSelect($event)">
</app-topic-treemap>
}
</section>
}
@if (bundTopicsLoading || bundTopicsError || bundProjectTopics) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>BUND-Projekt-Topics</h2>
<p>
Gematchte BUND-Projekte nach Field, Subfield und Topic. Ein Klick
auf ein Topic zeigt die zugehörigen Keywords.
</p>
</div>
@if (bundProjectTopics) {
<p class="dfg-topic-summary">
{{ bundProjectTopics.matched_project_count | number }} von
{{ bundProjectTopics.project_count | number }} Projekten gematcht
</p>
}
</header>
@if (bundTopicsLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="BUND-Topics werden geladen …"
icon="account_tree"
size="72"
diameter="72"></app-loading>
</div>
} @else if (bundTopicsError) {
<p class="statistics-error">
Die BUND-Topic-Treemap konnte nicht geladen werden.
</p>
} @else {
<app-topic-treemap
[data]="bundTopicTreemap"
[selectedNodeId]="selectedBundTopicTreemapNode"
countLabel="BUND-Projekte"
[showCountInTooltip]="false"
(selectedNodeIdChange)="onBundTopicTreemapNodeChange($event)"
(topicSelect)="onBundTopicTreemapTopicSelect($event)">
</app-topic-treemap>
}
</section>
}
@if (topAuthorsLoading || topAuthorsError || hasTopAuthorData()) {
<section class="top-authors-section">
<header class="top-authors-header">
@@ -355,6 +453,8 @@
class="author-name author-link"
[routerLink]="authorLink(dataset, entry)"
[queryParams]="authorQueryParams(dataset, entry)"
[appComponentTooltip]="AuthorTooltipComponent"
[tooltipInputs]="{ authorId: entry.id }"
[title]="authorDisplayName(dataset, entry)">
{{ authorDisplayName(dataset, entry) }}
</a>
@@ -39,7 +39,16 @@
}
.dashboard-period-slider {
width: min(100%, 34rem);
width: 280px;
max-width: 100%;
margin-left: auto;
}
@media (max-width: 720px) {
.dashboard-period-slider {
width: 100%;
margin-left: 0;
}
}
.statistics-grid {
@@ -1,9 +1,13 @@
import { Component, OnInit } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { Observable, finalize } from 'rxjs';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
import { AppAuthorTooltipComponent } from '../../shared/ui/app-author-tooltip/app-author-tooltip.component';
import { PATENT_ICON } from '../../shared/ui/icons';
import { EuProjectStatusChartComponent } from './eu-project-status-chart/eu-project-status-chart.component';
import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
@@ -18,6 +22,7 @@ import {
} from './topic-wordcloud-dialog/topic-wordcloud-dialog.component';
import {
BmbfProjectStatusStatistics,
BundProjectTopics,
DashboardPeriodBounds,
DashboardStatisticValue,
DashboardStatistics,
@@ -26,6 +31,7 @@ import {
DfgProjectTopic,
DfgProjectTopics,
EuProjectStatusStatistics,
EuProjectTopics,
TopAuthor,
TopAuthorStatistics,
} from './dashboard-statistics.service';
@@ -56,6 +62,8 @@ type DashboardPeriodMode =
imports: [
DecimalPipe,
MatIconModule,
MatTooltipModule,
ComponentTooltipDirective,
RouterLink,
LoadingComponent,
EuProjectStatusChartComponent,
@@ -66,6 +74,8 @@ type DashboardPeriodMode =
styleUrl: './dashboard.component.scss',
})
export class DashboardComponent implements OnInit {
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
readonly patentIcon = PATENT_ICON;
statistics?: Partial<DashboardStatistics>;
statisticsLoading = false;
statisticsError = false;
@@ -96,6 +106,14 @@ export class DashboardComponent implements OnInit {
dfgTopicTreemap?: TopicTreemapData;
dfgTopicsLoading = false;
dfgTopicsError = false;
euProjectTopics?: EuProjectTopics;
euTopicTreemap?: TopicTreemapData;
euTopicsLoading = false;
euTopicsError = false;
bundProjectTopics?: BundProjectTopics;
bundTopicTreemap?: TopicTreemapData;
bundTopicsLoading = false;
bundTopicsError = false;
euProjectStatuses?: EuProjectStatusStatistics;
euProjectStatusesLoading = false;
euProjectStatusesError = false;
@@ -108,10 +126,12 @@ export class DashboardComponent implements OnInit {
readonly topicTreemapMinYear = 1900;
readonly topicTreemapMaxYear = new Date().getFullYear();
dashboardPeriodMode: DashboardPeriodMode = 'all_time';
dashboardFromYear = this.topicTreemapMaxYear - 4;
dashboardFromYear = this.topicTreemapMinYear;
dashboardToYear = this.topicTreemapMaxYear;
selectedTopicTreemapNode?: string;
selectedDfgTopicTreemapNode?: string;
selectedEuTopicTreemapNode?: string;
selectedBundTopicTreemapNode?: string;
private topicTreemapReloadQueued = false;
private topicTreemapRequestId = 0;
@@ -128,6 +148,8 @@ export class DashboardComponent implements OnInit {
this.loadTopAuthors();
this.loadTopicTreemap();
this.loadDfgProjectTopics();
this.loadEuProjectTopics();
this.loadBundProjectTopics();
this.loadEuProjectStatuses();
this.loadBmbfProjectStatuses();
this.loadDfgProjectStatuses();
@@ -245,10 +267,12 @@ export class DashboardComponent implements OnInit {
([subfieldName, group]) => ({
id: `${fieldName}::${subfieldName}`,
name: subfieldName,
total: group.topics.reduce(
(sum, topic) => sum + topic.project_count,
0,
),
total:
group.topics[0]?.subfield_project_count ??
group.topics.reduce(
(sum, topic) => sum + topic.project_count,
0,
),
values: [],
topics: group.topics.map((topic) => ({
id: topic.id,
@@ -261,10 +285,12 @@ export class DashboardComponent implements OnInit {
return {
id: fieldName,
name: fieldName,
total: mappedSubfields.reduce(
(sum, subfield) => sum + subfield.total,
0,
),
total:
[...subfields.values()][0]?.topics[0]?.field_project_count ??
mappedSubfields.reduce(
(sum, subfield) => sum + subfield.total,
0,
),
values: [],
subfields: mappedSubfields,
};
@@ -352,6 +378,7 @@ export class DashboardComponent implements OnInit {
onDfgTopicTreemapNodeChange(nodeId: string | undefined): void {
this.selectedDfgTopicTreemapNode = nodeId;
this.updateDashboardPeriodUrl();
}
onDfgTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
@@ -378,6 +405,64 @@ export class DashboardComponent implements OnInit {
);
}
onEuTopicTreemapNodeChange(nodeId: string | undefined): void {
this.selectedEuTopicTreemapNode = nodeId;
this.updateDashboardPeriodUrl();
}
onEuTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
const euTopic = this.euProjectTopics?.topics.find(
(entry) => entry.id === topic.topicId,
);
if (!euTopic) return;
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
TopicWordCloudDialogComponent,
{
width: '85vw',
maxWidth: '92vw',
data: {
...topic,
source: 'eu',
words: euTopic.keywords.map((keyword) => ({
id: keyword.name,
name: keyword.name,
count: keyword.project_count,
})),
},
},
);
}
onBundTopicTreemapNodeChange(nodeId: string | undefined): void {
this.selectedBundTopicTreemapNode = nodeId;
this.updateDashboardPeriodUrl();
}
onBundTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
const bundTopic = this.bundProjectTopics?.topics.find(
(entry) => entry.id === topic.topicId,
);
if (!bundTopic) return;
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
TopicWordCloudDialogComponent,
{
width: '85vw',
maxWidth: '92vw',
data: {
...topic,
source: 'bund',
words: bundTopic.keywords.map((keyword) => ({
id: keyword.name,
name: keyword.name,
count: keyword.project_count,
})),
},
},
);
}
onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
const period = this.selectedPeriodBounds();
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
@@ -406,23 +491,34 @@ export class DashboardComponent implements OnInit {
this.dashboardPeriodMode = mode;
}
this.applyPresetPeriod();
this.dashboardFromYear = this.parseDashboardYear(
params.get('fromYear'),
this.dashboardFromYear,
);
this.dashboardToYear = this.parseDashboardYear(
params.get('toYear'),
this.dashboardToYear,
);
if (this.dashboardPeriodMode !== 'all_time') {
this.dashboardFromYear = this.parseDashboardYear(
params.get('fromYear'),
this.dashboardFromYear,
);
this.dashboardToYear = this.parseDashboardYear(
params.get('toYear'),
this.dashboardToYear,
);
}
if (this.dashboardFromYear > this.dashboardToYear) {
this.dashboardFromYear = this.dashboardToYear;
}
this.selectedTopicTreemapNode = params.get('treemapNode') ?? undefined;
this.selectedDfgTopicTreemapNode =
params.get('dfgTreemapNode') ?? undefined;
this.selectedEuTopicTreemapNode =
params.get('euTreemapNode') ?? undefined;
this.selectedBundTopicTreemapNode =
params.get('bundTreemapNode') ?? undefined;
}
private applyPresetPeriod(): void {
const currentYear = this.topicTreemapMaxYear;
if (this.dashboardPeriodMode === 'last_10_years') {
if (this.dashboardPeriodMode === 'all_time') {
this.dashboardFromYear = this.topicTreemapMinYear;
this.dashboardToYear = currentYear;
} else if (this.dashboardPeriodMode === 'last_10_years') {
this.dashboardFromYear = currentYear - 9;
this.dashboardToYear = currentYear;
} else if (this.dashboardPeriodMode === 'last_5_years') {
@@ -440,6 +536,9 @@ export class DashboardComponent implements OnInit {
fromYear: period.fromYear ?? null,
toYear: period.toYear ?? null,
treemapNode: this.selectedTopicTreemapNode ?? null,
dfgTreemapNode: this.selectedDfgTopicTreemapNode ?? null,
euTreemapNode: this.selectedEuTopicTreemapNode ?? null,
bundTreemapNode: this.selectedBundTopicTreemapNode ?? null,
},
queryParamsHandling: 'merge',
replaceUrl: true,
@@ -469,6 +568,8 @@ export class DashboardComponent implements OnInit {
this.loadTopAuthors();
this.loadTopicTreemap();
this.loadDfgProjectTopics();
this.loadEuProjectTopics();
this.loadBundProjectTopics();
this.loadEuProjectStatuses();
this.loadBmbfProjectStatuses();
this.loadDfgProjectStatuses();
@@ -552,6 +653,40 @@ export class DashboardComponent implements OnInit {
});
}
private loadEuProjectTopics(): void {
this.euTopicsLoading = true;
this.euTopicsError = false;
this.statisticsService
.getEuProjectTopics(this.selectedPeriodBounds())
.pipe(finalize(() => (this.euTopicsLoading = false)))
.subscribe({
next: (topics) => {
this.euProjectTopics = topics;
this.euTopicTreemap = this.buildDfgTopicTreemapData(topics);
},
error: () => {
this.euTopicsError = true;
},
});
}
private loadBundProjectTopics(): void {
this.bundTopicsLoading = true;
this.bundTopicsError = false;
this.statisticsService
.getBundProjectTopics(this.selectedPeriodBounds())
.pipe(finalize(() => (this.bundTopicsLoading = false)))
.subscribe({
next: (topics) => {
this.bundProjectTopics = topics;
this.bundTopicTreemap = this.buildDfgTopicTreemapData(topics);
},
error: () => {
this.bundTopicsError = true;
},
});
}
private loadEuProjectStatuses(): void {
this.euProjectStatusesLoading = true;
this.euProjectStatusesError = false;
@@ -23,7 +23,7 @@ export interface TopicWordCloudDialogData {
fromYear?: number;
toYear?: number;
words?: TopicWordCloudWord[];
source?: 'publications' | 'dfg';
source?: 'publications' | 'dfg' | 'eu' | 'bund';
}
interface DisplayWord extends TopicWordCloudWord {
@@ -179,6 +179,8 @@
<div class="keyword-chip-stack">
@for (keyword of keywords; track keyword.llm_keyword.keyword) {
<app-topic-chip
[topic]="keyword.topic_mapping?.topic"
[topicId]="keyword.topic_mapping?.topic?.id"
[label]="getChipLabel(keyword)"
[count]="
keywordView() === 'topic' ? getChipCount(keyword) : null
@@ -209,6 +211,8 @@
) {
<div class="manual-chip-row">
<app-topic-chip
[topic]="keyword.topic_mapping?.topic"
[topicId]="keyword.topic_mapping?.topic?.id"
[label]="getChipLabel(keyword)"
[count]="
keywordView() === 'topic' ? getChipCount(keyword) : null
@@ -1,31 +1,152 @@
<div class="result-layout">
<mat-card class="results-card">
<mat-card-content class="results-placeholder">
<mat-icon>groups</mat-icon>
<h2>Newsliste</h2>
<p>
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
</p>
</mat-card-content>
</mat-card>
<div class="content">
<div class="filters">
<app-filter-card>
<app-query-param-selector
class="relevance-field"
[options]="relevanceOptions"
[queryParamKey]="keywordsNewsQueryParamKeys.relevance"
label="Relevanz"
icon="check_circle"
[multiple]="true" />
<mat-card class="weights-card">
<mat-card-content>
<app-weights-sliders
[options]="weightOptions"
[initialWeights]="defaultWeights"
title="News-Gewichtung"
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
resetLabel="Ausgewogen"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="newsW_"
[persistInQueryParams]="true"
[showApplyButton]="true"
[showResetButton]="true"
[showNormalizedPreview]="true"
(weightsChange)="onWeightsChange($event)"
(applyWeights)="onApplyWeights($event)" />
</mat-card-content>
</mat-card>
<app-query-param-selector
class="sort-order-field"
[options]="sortOrderOptions"
[queryParamKey]="keywordsNewsQueryParamKeys.sortOrder"
label="Sortierung"
icon="sort" />
</app-filter-card>
<app-year-range-slider
[minYear]="minYear"
[maxYear]="maxYear"
[(startYear)]="yearFrom"
[(endYear)]="yearTo"
(startYearChange)="applyYearFilter()"
(endYearChange)="applyYearFilter()">
</app-year-range-slider>
@if (hasActiveFilters()) {
<button
class="reset-filter-btn"
mat-stroked-button
type="button"
(click)="resetFilters()"
aria-label="Filter zurücksetzen">
<mat-icon>filter_alt_off</mat-icon>
<span>Zurücksetzen</span>
</button>
}
</div>
<ng-template #titleTmp let-article>
<div class="title-cell">
<a class="title" [routerLink]="['/news', article.id]">
{{ article.maintitle || 'Kein Titel' }}
</a>
@if (article.snippet) {
<span class="snippet" [innerHTML]="article.snippet"></span>
}
</div>
</ng-template>
<ng-template #dateTmp let-article>
@if (article.date) {
<span class="date-text">{{ article.date }}</span>
} @else {
<span class="empty-text">-</span>
}
</ng-template>
<ng-template #relevanceTmp let-article>
@if (article.relevant === true) {
<span class="relevance-badge is-relevant">
<mat-icon>check_circle</mat-icon>
Relevant
</span>
} @else if (article.relevant === false) {
<span class="relevance-badge not-relevant">
<mat-icon>cancel</mat-icon>
Nicht relevant
</span>
} @else {
<span
class="relevance-badge undetermined"
[matTooltip]="relevanceHelp"
matTooltipPosition="above">
<mat-icon>help</mat-icon>
Nicht bestimmt
</span>
}
</ng-template>
<ng-template #topicsTmp let-article>
@let topics = article.topics ?? [];
@let topicsExpanded = isTopicsExpanded(article);
@let visibleTopics =
topicsExpanded ? topics : topics.slice(0, topicPreviewCount);
<div class="topic-chips" aria-label="Themen">
@for (topic of visibleTopics; track topic.id ?? topic.display_name) {
<app-topic-chip-2
size="mini"
[topic]="toTopic(topic)"
[showIcon]="false"
[isSelected]="isTopicActive(topic)"
[isClickable]="fuzzySearch()"
(handleChipClick)="toggleTopicFilter($event)" />
} @empty {
<span class="empty-text">-</span>
}
@if (topics.length > topicPreviewCount) {
<app-chip-overflow-toggle
[expanded]="topicsExpanded"
[hiddenCount]="topics.length - topicPreviewCount"
(toggle)="toggleTopicsExpansion(article)" />
}
</div>
</ng-template>
<ng-template #actionsTmp let-article>
<a
mat-icon-button
color="primary"
[routerLink]="['/news', article.id]"
matTooltip="Details anzeigen">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
@if (!hasSearchInput()) {
<div class="no-results">
<span>Keine Keywords ausgewählt.</span>
</div>
} @else if (total() === 0) {
<div class="no-results">
@if (hasNarrowingFilters()) {
<span>Keine Nachrichten für die aktuellen Filter.</span>
<span class="no-results__hint">
Setzen Sie die Filter zurück, um mehr Ergebnisse zu sehen.
</span>
} @else if (searchedByTopics()) {
<span>Zu diesen Themen gibt es keine Nachrichten.</span>
<span class="no-results__hint">
Campus Aktuell deckt nicht jedes Forschungsthema ab. Schalten Sie die
Fuzzy Search aus, um direkt nach den Keywords zu suchen.
</span>
} @else {
<span>Keine Nachrichten zu diesen Keywords gefunden.</span>
}
</div>
} @else {
<div class="table-wrap">
<app-data-table [columns]="columns()" [data]="elements()" />
</div>
<app-query-param-paginator
[total]="total()"
queryParamPageKey="page"
queryParamSizeKey="size" />
}
</div>
@@ -1,29 +1,199 @@
.content {
display: flex;
flex-direction: column;
gap: 1rem;
}
/* ============================================================
RESULT LAYOUT
FILTERS
============================================================ */
.result-layout {
display: grid;
grid-template-columns: minmax(300px, 420px) 1fr;
grid-template-areas: 'summary results';
.filters {
display: flex;
flex-wrap: wrap;
align-items: stretch;
gap: 0.75rem;
align-items: start;
}
.search-summary-card {
grid-area: summary;
}
.relevance-field,
.sort-order-field {
min-width: 200px;
}
.results-card {
grid-area: results;
}
app-year-range-slider {
display: flex;
}
.search-summary-card,
.results-card {
background: var(--sg-surface);
border: 1px solid var(--sg-border);
box-shadow: none;
::ng-deep app-year-range-slider .year-filter {
height: 100%;
}
.mat-mdc-card-content {
padding: 0.75rem;
::ng-deep .mat-mdc-form-field-subscript-wrapper {
display: none;
}
::ng-deep .mat-mdc-form-field-icon-prefix {
padding: 0 4px 0 10px;
}
}
.reset-filter-btn {
display: flex;
align-self: center;
align-items: center;
gap: 0.25rem;
height: 40px;
}
/* ============================================================
TABLE
============================================================ */
.table-wrap {
position: relative;
overflow-x: auto;
}
::ng-deep .table-wrap table {
width: 100%;
min-width: 960px;
border-collapse: separate;
border-spacing: 0 10px;
box-shadow: none;
background: transparent;
}
::ng-deep .table-wrap .mat-mdc-header-cell {
color: var(--sg-text-muted);
font-size: 12px;
font-weight: 700;
}
::ng-deep .table-wrap .mat-mdc-row {
height: 86px;
}
::ng-deep .table-wrap .mat-mdc-cell {
color: var(--sg-text);
border-bottom-color: var(--sg-border);
font-size: 13px;
}
::ng-deep .table-wrap {
.mat-column-date,
.mat-column-relevant,
.mat-mdc-header-cell {
text-align: center;
}
.mat-column-topics {
overflow: visible;
}
}
/* ============================================================
TABLE CELLS
============================================================ */
.title-cell {
display: flex;
flex-direction: column;
gap: 0.25rem;
padding: 0.5rem 0;
max-width: 32rem;
}
.title {
display: inline-block;
max-width: 520px;
line-height: 1.35;
color: var(--sg-text);
font-size: 14px;
font-weight: 700;
text-decoration: none;
&:hover {
color: var(--sg-text);
text-decoration: underline;
}
}
.snippet {
font-size: 12.5px;
line-height: 1.5;
color: var(--sg-text-secondary);
overflow-wrap: anywhere;
::ng-deep em {
font-style: normal;
font-weight: 700;
color: var(--sg-blue-highlight);
}
}
.date-text {
white-space: nowrap;
}
.empty-text {
color: var(--sg-text-muted);
}
.relevance-badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 12px;
border-radius: 999px;
font-size: 13px;
font-weight: 600;
line-height: 1;
white-space: nowrap;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
}
&.is-relevant {
background: var(--sg-success-soft);
border: 1px solid var(--sg-success);
color: var(--sg-success);
}
&.not-relevant {
background: var(--sg-surface-muted);
border: 1px solid var(--sg-border);
color: var(--sg-text-muted);
}
&.undetermined {
background: var(--sg-warning-soft);
border: 1px solid var(--sg-warning);
color: var(--sg-warning);
cursor: help;
}
}
.topic-chips {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
align-items: flex-start;
padding: 0.5rem 0;
max-width: 350px;
}
.no-results {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
padding: 2rem;
color: var(--sg-text-muted);
text-align: center;
&__hint {
max-width: 34rem;
color: var(--sg-text-soft);
font-size: 0.8125rem;
line-height: 1.5;
}
}
@@ -1,115 +1,284 @@
import { Component, inject, signal } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import {
WeightMap,
WeightSliderOption,
WeightsSlidersComponent,
WeightsSlidersValue,
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
Component,
DestroyRef,
computed,
inject,
input,
signal,
TemplateRef,
viewChild,
} from '@angular/core';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatchedTopic, NewsPage, Topic } from '../../../../api';
import {
DataTableComponent,
GenericColumn,
} from '../../../../shared/ui/data-table/data-table.component';
import { QueryParamPaginatorComponent } from '../../../../shared/ui/query-param-paginator/query-param-paginator.component';
import { AppTopicChipComponent } from '../../../../shared/ui/app-topic-chip/app-topic-chip.component';
import { ChipOverflowToggleComponent } from '../../../../shared/ui/chip-overflow-toggle/chip-overflow-toggle.component';
import { FilterCardComponent } from '../../../../shared/ui/filter-card/filter-card.component';
import {
QueryParamSelectorComponent,
SelectorOption,
} from '../../../../shared/ui/query-param-selector/query-param-selector.component';
import { NEWS_MIN_YEAR } from '../../../../shared/ui/news-card/news-card.component';
import { keywordsNewsQueryParamKeys } from '../../../../resolvers/keywords-news-page.resolver';
import { SearchResultsStateService } from '../search-results-state.service';
import { YearRangeSliderComponent } from '../../../../shared/ui/year-range-slider/year-range-slider.component';
type NewsResult = NewsPage['results'][number];
@Component({
selector: 'app-news-results',
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
imports: [
RouterModule,
MatButtonModule,
MatIconModule,
MatTooltipModule,
DataTableComponent,
AppTopicChipComponent,
ChipOverflowToggleComponent,
FilterCardComponent,
QueryParamPaginatorComponent,
QueryParamSelectorComponent,
YearRangeSliderComponent,
],
templateUrl: './news-results.component.html',
styleUrl: './news-results.component.scss',
})
export class KeywordsToNewsResultsComponent {
// injects the state set by the parent route — no duplicate parsing here
protected readonly keywordsNewsQueryParamKeys = keywordsNewsQueryParamKeys;
private readonly state = inject(SearchResultsStateService);
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly destroyRef = inject(DestroyRef);
readonly defaultWeights: WeightMap = {
param1: 0.33,
param2: 0.33,
param3: 0.34,
};
newsPage = input.required<NewsPage>();
readonly weightOptions: WeightSliderOption[] = [
{
key: 'param1',
label: 'Parameter 1',
icon: 'workspace_premium',
description: 'Gewichtet Parameter 1.',
defaultValue: 0.5,
queryParamName: 'wParam1',
},
{
key: 'param2',
label: 'Parameter 2',
icon: 'workspace_premium',
description: 'Gewichtet Parameter 2.',
defaultValue: 0.5,
queryParamName: 'wParam2',
},
{
key: 'param3',
label: 'Parameter 3',
icon: 'workspace_premium',
description: 'Gewichtet Parameter 3.',
defaultValue: 0.5,
queryParamName: 'wParam3',
},
readonly minYear = NEWS_MIN_YEAR;
readonly maxYear = new Date().getFullYear();
readonly relevanceHelp =
'Ein Artikel gilt als relevant, wenn er für Gründungsforschende interessante Inhalte enthält.';
readonly sortOrderOptions: SelectorOption[] = [
{ value: 'desc', display_name: 'Neueste zuerst' },
{ value: 'asc', display_name: 'Älteste zuerst' },
];
readonly currentWeights = signal<WeightsSlidersValue>({
raw: this.defaultWeights,
normalized: {
param1: 0.33,
param2: 0.33,
param3: 0.34,
},
rawSum: 2.5,
normalizedSum: 1,
valid: true,
readonly relevanceOptions: SelectorOption[] = [
{ value: 'relevant', display_name: 'Relevant' },
{ value: 'not_relevant', display_name: 'Nicht relevant' },
];
readonly yearFrom = signal<number>(this.minYear);
readonly yearTo = signal<number>(this.maxYear);
protected readonly topicPreviewCount = 3;
private readonly expandedTopicsIds = signal<ReadonlySet<string>>(new Set());
private readonly queryParamMap = toSignal(this.route.queryParamMap, {
initialValue: this.route.snapshot.queryParamMap,
});
readonly projects = signal<unknown[]>([]); // placeholder until the results service lands
readonly total = computed(() => this.newsPage().total ?? 0);
readonly elements = computed(() => this.newsPage().results ?? []);
readonly fuzzySearch = computed(
() => this.queryParamMap().get('fuzzy') === 'true',
);
private hasLoadedInitial = false;
constructor() {
console.log('check', this.state.payload());
}
onWeightsChange(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
readonly hasSearchInput = computed(() =>
this.fuzzySearch()
? this.state.topicIds().length > 0 || this.state.keywords().length > 0
: this.state.keywords().length > 0,
);
// fires once with the query-param-aware initial state — use it to load
if (!this.hasLoadedInitial) {
this.hasLoadedInitial = true;
this.loadprojects();
readonly selectedTopicIds = computed(() =>
this.queryParamMap().getAll(keywordsNewsQueryParamKeys.topicId),
);
readonly hasActiveFilters = computed(() => {
const params = this.queryParamMap();
return (
!!params.get(keywordsNewsQueryParamKeys.relevance) ||
!!params.get(keywordsNewsQueryParamKeys.yearFrom) ||
!!params.get(keywordsNewsQueryParamKeys.yearTo) ||
!!params.get(keywordsNewsQueryParamKeys.sortOrder) ||
this.selectedTopicIds().length > 0
);
});
readonly hasNarrowingFilters = computed(() => {
const params = this.queryParamMap();
return (
!!params.get(keywordsNewsQueryParamKeys.relevance) ||
!!params.get(keywordsNewsQueryParamKeys.yearFrom) ||
!!params.get(keywordsNewsQueryParamKeys.yearTo) ||
this.selectedTopicIds().length > 0
);
});
readonly searchedByTopics = computed(() => {
if (!this.fuzzySearch()) {
return false;
}
const baseTopicIds = (this.queryParamMap().get('topics') ?? '')
.split(',')
.filter((value) => value.trim());
return baseTopicIds.length > 0 || this.selectedTopicIds().length > 0;
});
titleTmp = viewChild.required<TemplateRef<any>>('titleTmp');
dateTmp = viewChild.required<TemplateRef<any>>('dateTmp');
relevanceTmp = viewChild.required<TemplateRef<any>>('relevanceTmp');
topicsTmp = viewChild.required<TemplateRef<any>>('topicsTmp');
actionsTmp = viewChild.required<TemplateRef<any>>('actionsTmp');
readonly columns = computed<GenericColumn<NewsResult>[]>(() => [
{
id: 'maintitle',
header: 'Titel',
type: 'display',
cellTemplate: this.titleTmp(),
},
{
id: 'date',
header: 'Datum',
type: 'display',
cellTemplate: this.dateTmp(),
},
{
id: 'relevant',
header: 'Relevanz',
type: 'display',
cellTemplate: this.relevanceTmp(),
},
{
id: 'topics',
header: 'Themen',
type: 'display',
cellTemplate: this.topicsTmp(),
},
{
id: 'actions',
header: 'Aktionen',
type: 'display',
cellTemplate: this.actionsTmp(),
},
]);
constructor() {
this.route.queryParamMap
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((params) => {
this.yearFrom.set(
this.parseYear(params.get(keywordsNewsQueryParamKeys.yearFrom)) ??
this.minYear,
);
this.yearTo.set(
this.parseYear(params.get(keywordsNewsQueryParamKeys.yearTo)) ??
this.maxYear,
);
});
}
onApplyWeights(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
this.loadprojects();
}
private loadprojects(): void {
const weights = this.currentWeights();
const requestPayload = {
manualKeywords: this.state.manualKeywords(),
extractedKeywords: this.state.extractedKeywords(),
keywords: this.state.keywords(),
fuzzy: this.state.fuzzySearch(),
weights: {
raw: weights.raw,
normalized: weights.normalized,
applyYearFilter(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
[keywordsNewsQueryParamKeys.yearFrom]:
this.yearFrom() > this.minYear ? this.yearFrom() : null,
[keywordsNewsQueryParamKeys.yearTo]:
this.yearTo() < this.maxYear ? this.yearTo() : null,
[keywordsNewsQueryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
}
toTopic(matched: MatchedTopic): Topic {
return {
id: matched.id,
display_name: matched.display_name,
subfield: matched.subfield_name
? { display_name: matched.subfield_name }
: null,
field: matched.field_name ? { display_name: matched.field_name } : null,
domain: matched.domain_name
? { display_name: matched.domain_name }
: null,
};
}
console.log(requestPayload);
isTopicActive(topic: MatchedTopic): boolean {
return !!topic.id && this.selectedTopicIds().includes(topic.id);
}
/**
* TODO:
* this.projectsService.searchprojects(requestPayload).subscribe({
* next: results => this.projects.set(results),
* error: error => console.error(error),
* });
*/
isTopicsExpanded(article: NewsResult): boolean {
return this.expandedTopicsIds().has(article.id);
}
toggleTopicsExpansion(article: NewsResult): void {
if (!article.id) {
return;
}
this.expandedTopicsIds.update((ids) => {
const next = new Set(ids);
if (next.has(article.id)) {
next.delete(article.id);
} else {
next.add(article.id);
}
return next;
});
}
toggleTopicFilter(topic: Topic): void {
if (!topic.id || !this.fuzzySearch()) {
return;
}
const selected = this.selectedTopicIds();
const next = selected.includes(topic.id)
? selected.filter((id) => id !== topic.id)
: [...selected, topic.id];
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
[keywordsNewsQueryParamKeys.topicId]: next.length ? next : null,
[keywordsNewsQueryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
}
resetFilters(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
[keywordsNewsQueryParamKeys.relevance]: null,
[keywordsNewsQueryParamKeys.yearFrom]: null,
[keywordsNewsQueryParamKeys.yearTo]: null,
[keywordsNewsQueryParamKeys.topicId]: null,
[keywordsNewsQueryParamKeys.sortOrder]: null,
[keywordsNewsQueryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
}
private parseYear(raw: string | null): number | null {
const year = Number.parseInt(raw ?? '', 10);
return Number.isNaN(year) ? null : year;
}
}
@@ -36,6 +36,8 @@
track getEntryTrack(entry)
) {
<app-topic-chip
[topic]="entry.topic_mapping?.topic"
[topicId]="entry.topic_mapping?.topic?.id"
[label]="getChipLabel(entry)"
[count]="getChipCount(entry)"
[description]="getChipDescription(entry)"
@@ -230,8 +230,8 @@
»{{ topic.source_keyword }}«
</button>
<p class="kw-hint">
Im Artikel hervorgehoben · klicken zum Suche zu
öffnen
Im Artikel hervorgehoben - klicken, um zum
ersten Vorkommen zu springen.
</p>
} @else {
<p class="placeholder">
@@ -6,7 +6,6 @@ import {
ViewChild,
inject,
} from '@angular/core';
import { Location } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
@@ -66,7 +65,6 @@ export class NewsDetailComponent implements OnInit {
private readonly route = inject(ActivatedRoute);
private readonly httpClient = inject(HttpClient);
private readonly worksService = inject(WorksService);
private readonly location = inject(Location);
private readonly sanitizer = inject(DomSanitizer);
article: NewsArticleDetail | null = null;
@@ -150,7 +148,7 @@ export class NewsDetailComponent implements OnInit {
}
navigateBack(): void {
this.location.back();
this.router.navigate(['/news']);
}
formatDate(dateStr?: string | null): string {
@@ -200,36 +198,30 @@ export class NewsDetailComponent implements OnInit {
);
}
}
const orphanColors = [
'var(--sg-primary)',
'var(--sg-blue-highlight)',
'var(--sg-success)',
'var(--sg-warning)',
'var(--sg-error)',
];
let orphanIdx = 0;
let html = this.escapeHtml(text);
if (keywords.length) {
[...keywords]
.sort((a, b) => b.length - a.length)
.forEach((kw) => {
let color = keywordColorMap.get(kw.toLowerCase());
if (!color) {
color = orphanColors[orphanIdx % orphanColors.length];
orphanIdx++;
}
const kwHtml = this.escapeHtml(kw);
const re = new RegExp(
`(${this.escapeRegex(kwHtml)}[\\w\\u00C0-\\u024F]*)`,
'gi',
);
html = html.replace(
re,
`<mark class="kw-mark" style="--t:${color}" data-kw="${kwHtml}">$1</mark>`,
);
});
}
[...keywords]
.sort((a, b) => b.length - a.length)
.forEach((kw) => {
const color = keywordColorMap.get(kw.toLowerCase());
if (!color) return;
const kwHtml = this.escapeHtml(kw);
const escaped = this.escapeRegex(kwHtml);
const before = '(?<![\\w\\u00C0-\\u024F])';
const acronymLike =
kw.length <= 3 ||
(kw === kw.toUpperCase() && kw !== kw.toLowerCase());
const re = new RegExp(
acronymLike
? `${before}(${escaped})(?![\\w\\u00C0-\\u024F])`
: `${before}(${escaped}[\\w\\u00C0-\\u024F]*)`,
'gi',
);
html = html.replace(
re,
`<mark class="kw-mark" style="--t:${color}" data-kw="${kwHtml}">$1</mark>`,
);
});
return this.sanitizer.bypassSecurityTrustHtml(html);
}
+18 -14
View File
@@ -18,18 +18,24 @@
<ng-template #additionalFiltersTmp>
<div class="additional-filters">
<mat-form-field
appearance="outline"
subscriptSizing="dynamic"
class="relevance-field">
<mat-select
[formControl]="relevanceFilter"
placeholder="Relevanz"
multiple>
<mat-option value="relevant">Relevant</mat-option>
<mat-option value="not_relevant">Nicht relevant</mat-option>
</mat-select>
</mat-form-field>
<app-filter-card>
<app-query-param-selector
class="relevance-field"
[options]="relevanceOptions"
queryParamKey="relevance"
label="Relevanz"
icon="check_circle"
[multiple]="true" />
@if (!isSearching()) {
<app-query-param-selector
class="sort-order-field"
[options]="sortingDirectionOptionsAll"
queryParamKey="sorting_order"
label="Sortierung"
icon="sort" />
}
</app-filter-card>
<app-year-range-slider
class="year-field"
@@ -59,7 +65,5 @@
[additionalFiltersTmp]="additionalFiltersTmp"
[noResultsTmp]="noResultsTmp"
[cardMinWidth]="380"
[sortingDirectionOptions]="sortingDirectionOptions()"
sortingDirectionLabel="Sortierung"
searchLabel="Nachrichten durchsuchen" />
</div>
+26 -10
View File
@@ -44,20 +44,36 @@
color: var(--sg-text-muted);
}
$card-min-width: 380px;
.additional-filters {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 40px;
display: grid;
grid-template-columns: repeat(auto-fill, minmax($card-min-width, 1fr));
align-items: stretch;
gap: 1.5rem;
padding: 0 1rem 1rem;
app-year-range-slider {
display: flex;
}
::ng-deep app-year-range-slider .year-filter {
height: 100%;
}
::ng-deep .mat-mdc-form-field-subscript-wrapper {
display: none;
}
::ng-deep .mat-mdc-form-field-icon-prefix {
padding: 0 4px 0 10px;
}
}
.relevance-field {
width: 180px;
}
.year-field {
min-width: 280px;
.relevance-field,
.sort-order-field {
flex: 1;
min-width: 0;
}
@media (max-width: 600px) {
+14 -11
View File
@@ -7,12 +7,10 @@ import {
signal,
} from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { FormControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounceTime, merge } from 'rxjs';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { WorksService } from '../../api';
import {
@@ -24,7 +22,11 @@ import {
NewsCardComponent,
NEWS_MIN_YEAR,
} from '../../shared/ui/news-card/news-card.component';
import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component';
import {
QueryParamSelectorComponent,
SelectorOption,
} from '../../shared/ui/query-param-selector/query-param-selector.component';
import { FilterCardComponent } from '../../shared/ui/filter-card/filter-card.component';
import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component';
interface NewsArticle extends NewsArticleBase {
@@ -44,11 +46,10 @@ type SortOrder = 'desc' | 'asc';
@Component({
selector: 'app-news',
imports: [
ReactiveFormsModule,
MatFormFieldModule,
MatSelectModule,
CardSearchComponent,
NewsCardComponent,
FilterCardComponent,
QueryParamSelectorComponent,
YearRangeSliderComponent,
],
templateUrl: './news.component.html',
@@ -64,11 +65,16 @@ export class NewsComponent implements OnInit {
readonly minYear = NEWS_MIN_YEAR;
readonly maxYear = new Date().getFullYear();
private readonly sortingDirectionOptionsAll: SelectorOption[] = [
readonly sortingDirectionOptionsAll: SelectorOption[] = [
{ value: 'desc', display_name: 'Neueste zuerst' },
{ value: 'asc', display_name: 'Älteste zuerst' },
];
readonly relevanceOptions: SelectorOption[] = [
{ value: 'relevant', display_name: 'Relevant' },
{ value: 'not_relevant', display_name: 'Nicht relevant' },
];
readonly relevanceFilter = new FormControl<string[]>([], {
nonNullable: true,
});
@@ -85,9 +91,6 @@ export class NewsComponent implements OnInit {
readonly searchQuery = signal('');
readonly isSearching = computed(() => this.searchQuery().trim().length > 0);
readonly sortingDirectionOptions = computed<SelectorOption[]>(() =>
this.isSearching() ? [] : this.sortingDirectionOptionsAll,
);
readonly page = computed<Page>(() => ({
page: this.currentPage,
@@ -0,0 +1,65 @@
import { Component, inject } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import {
MAT_DIALOG_DATA,
MatDialogActions,
MatDialogContent,
MatDialogRef,
MatDialogTitle,
} from '@angular/material/dialog';
@Component({
selector: 'app-institution-removal-dialog',
standalone: true,
imports: [
MatButtonModule,
MatDialogActions,
MatDialogContent,
MatDialogTitle,
],
template: `
<h3 mat-dialog-title>Manuelle Auswahl entfernen</h3>
<mat-dialog-content>
<p>
Möchtest du die manuelle Auswahl der Institution „{{
data.institutionName
}}“ wirklich entfernen?
</p>
@if (data.dependentCount === 1) {
<p>
Dadurch wird außerdem 1 automatisch zugeordnete Institution aus der
Organisation entfernt.
</p>
} @else if (data.dependentCount > 1) {
<p>
Dadurch werden außerdem {{ data.dependentCount }} automatisch
zugeordnete Institutionen aus der Organisation entfernt.
</p>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" (click)="close()">Abbrechen</button>
<button mat-flat-button color="primary" type="button" (click)="confirm()">
Entfernen
</button>
</mat-dialog-actions>
`,
})
export class InstitutionRemovalDialogComponent {
private readonly dialogRef =
inject<MatDialogRef<InstitutionRemovalDialogComponent, boolean>>(
MatDialogRef,
);
protected readonly data = inject<{
institutionName: string;
dependentCount: number;
}>(MAT_DIALOG_DATA);
protected close(): void {
this.dialogRef.close(false);
}
protected confirm(): void {
this.dialogRef.close(true);
}
}
@@ -16,10 +16,85 @@
}
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Externe Institutions-ID</mat-label>
<input matInput formControlName="otherInstId" />
</mat-form-field>
<section class="institution-section">
<div class="section-heading">
<div>
<h3>OpenAlex-Institutionen</h3>
<p>
Bei der Auswahl werden untergeordnete und verbundene Institutionen
automatisch ergänzt.
</p>
</div>
@if (isLoadingAssociations()) {
<mat-spinner diameter="24" />
}
</div>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Institution hinzufügen</mat-label>
<mat-icon matPrefix>search</mat-icon>
<input
matInput
type="text"
placeholder="Name der Institution eingeben"
[formControl]="institutionSearch"
[matAutocomplete]="institutionAutocomplete"
[readonly]="isLoadingAssociations()" />
@if (isSearchingInstitutions()) {
<mat-spinner matSuffix diameter="20" />
}
<mat-autocomplete
#institutionAutocomplete="matAutocomplete"
[displayWith]="displayInstitution"
(optionSelected)="selectAutocompleteInstitution($event)">
@for (
institution of institutionSearchResults();
track institution.id
) {
<mat-option [value]="institution">
<span>{{ institution.display_name }}</span>
<small class="autocomplete-description">
{{ institution.country_code }} · {{ institution.type }}
</small>
</mat-option>
}
</mat-autocomplete>
</mat-form-field>
<div class="institution-list" aria-live="polite">
@for (entry of institutions(); track entry.id) {
<article class="institution-item">
<mat-icon class="institution-icon">apartment</mat-icon>
<div class="institution-details">
<strong>{{ entry.institution.display_name }}</strong>
<span class="institution-id">{{ entry.id }}</span>
<div class="origin-labels">
@for (label of originLabels(entry); track label.relationship) {
<span
class="origin-label"
[matTooltip]="label.tooltip ?? ''"
[matTooltipDisabled]="!label.tooltip"
matTooltipClass="institution-origin-tooltip">
{{ label.label }}
</span>
}
</div>
</div>
@if (entry.manuallySelected) {
<button
mat-icon-button
type="button"
aria-label="Manuelle Auswahl entfernen"
(click)="removeInstitution(entry)">
<mat-icon>close</mat-icon>
</button>
}
</article>
} @empty {
<p class="empty-institutions">Noch keine Institution ausgewählt.</p>
}
</div>
</section>
@if (data.mode === 'edit') {
<mat-checkbox formControlName="deleted">
@@ -31,7 +106,12 @@
<mat-dialog-actions align="end">
<button mat-button type="button" (click)="close()">Abbrechen</button>
<button mat-flat-button color="primary" type="button" (click)="submit()">
<button
mat-flat-button
color="primary"
type="button"
[disabled]="isLoadingAssociations()"
(click)="submit()">
<mat-icon>save</mat-icon>
Speichern
</button>
@@ -1,7 +1,7 @@
.organization-form {
display: grid;
gap: 12px;
min-width: min(540px, calc(100vw - 64px));
gap: 18px;
min-width: min(680px, calc(100vw - 64px));
padding-top: 4px;
}
@@ -9,11 +9,101 @@
width: 100%;
}
.institution-section {
display: grid;
gap: 12px;
}
.section-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
}
.section-heading h3 {
margin: 0 0 4px;
font-size: 16px;
}
.section-heading p,
.empty-institutions {
margin: 0;
color: var(--sg-text-muted);
font-size: 13px;
}
.institution-list {
display: grid;
gap: 8px;
max-height: 320px;
overflow: auto;
}
.autocomplete-description {
display: block;
color: var(--sg-text-muted);
line-height: 1.2;
}
.institution-item {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: center;
gap: 12px;
padding: 10px 8px 10px 12px;
border: 1px solid var(--sg-border-color, #d8d8d8);
border-radius: 8px;
}
.institution-icon {
color: var(--sg-text-muted);
}
.institution-details {
display: grid;
min-width: 0;
gap: 3px;
}
.institution-details strong {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.institution-id {
color: var(--sg-text-muted);
font-size: 12px;
}
.origin-labels {
display: flex;
flex-wrap: wrap;
gap: 5px;
margin-top: 3px;
}
.origin-label {
padding: 2px 7px;
border-radius: 999px;
background: color-mix(in srgb, var(--mat-sys-primary) 10%, transparent);
color: var(--mat-sys-primary);
font-size: 11px;
}
.empty-institutions {
padding: 14px;
border: 1px dashed var(--sg-border-color, #d8d8d8);
border-radius: 8px;
text-align: center;
}
mat-dialog-actions {
padding: 12px 24px 20px;
}
@media (max-width: 600px) {
@media (max-width: 760px) {
.organization-form {
min-width: 0;
}
@@ -1,58 +1,108 @@
import { CommonModule } from '@angular/common';
import { Component, inject } from '@angular/core';
import { Component, computed, DestroyRef, inject, signal } from '@angular/core';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import {
MatAutocompleteModule,
MatAutocompleteSelectedEvent,
} from '@angular/material/autocomplete';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import {
MAT_DIALOG_DATA,
MatDialog,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { InseOrganizationManagementModelOrganizationProfile } from '../../../api';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
catchError,
debounceTime,
distinctUntilChanged,
finalize,
of,
switchMap,
} from 'rxjs';
import {
CreateOrganizationRequest,
InseOrganizationManagementModelOrganizationProfile,
Institution,
InstitutionAssociation,
InstitutionAssociationsResponse,
InstitutionsV2Service,
OrganizationService,
UpdateOrganizationRequest,
} from '../../../api';
import { InstitutionRemovalDialogComponent } from './institution-removal-dialog.component';
export interface CreateOrganizationPayload {
name: string;
other_inst_id?: string | null;
type Relationship = InstitutionAssociation.RelationshipEnum;
interface InstitutionOrigin {
sourceId: string;
sourceName: string;
relationship: Relationship;
}
export interface UpdateOrganizationPayload {
name?: string;
other_inst_id?: string | null;
deleted?: boolean;
interface EditableInstitution {
id: string;
institution: Institution;
manuallySelected: boolean;
origins: InstitutionOrigin[];
}
interface OriginLabel {
relationship: 'selected' | Relationship;
label: string;
tooltip?: string;
}
type OrganizationWithInstitutions =
InseOrganizationManagementModelOrganizationProfile & {
institutionAssociations?: InstitutionAssociationsResponse[];
};
export interface OrganizationDialogData {
mode: 'create' | 'edit';
organization?: InseOrganizationManagementModelOrganizationProfile;
organization?: OrganizationWithInstitutions;
isCurrentOrganization?: boolean;
}
export type OrganizationDialogResult =
| { mode: 'create'; payload: CreateOrganizationPayload }
| { mode: 'create'; payload: CreateOrganizationRequest }
| {
mode: 'edit';
organizationId: string;
payload: UpdateOrganizationPayload;
payload: UpdateOrganizationRequest;
};
const cleanInstitutionId = (id: string): string =>
id.split('/').filter(Boolean).pop() ?? id;
@Component({
selector: 'app-organization-dialog',
imports: [
CommonModule,
ReactiveFormsModule,
MatAutocompleteModule,
MatButtonModule,
MatCheckboxModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressSpinnerModule,
MatSnackBarModule,
MatTooltipModule,
],
templateUrl: './organization-dialog.component.html',
styleUrl: './organization-dialog.component.scss',
@@ -66,23 +116,217 @@ export class OrganizationDialogComponent {
OrganizationDialogResult | undefined
>
>(MatDialogRef);
private readonly dialog = inject(MatDialog);
private readonly organizationService = inject(OrganizationService);
private readonly institutionsService = inject(InstitutionsV2Service);
private readonly snackBar = inject(MatSnackBar);
private readonly destroyRef = inject(DestroyRef);
protected readonly data = inject<OrganizationDialogData>(MAT_DIALOG_DATA);
protected readonly isLoadingAssociations = signal(false);
protected readonly isSearchingInstitutions = signal(false);
protected readonly institutionSearchResults = signal<Institution[]>([]);
private readonly selectedAssociations = signal<
InstitutionAssociationsResponse[]
>([...(this.data.organization?.institutionAssociations ?? [])]);
protected readonly institutions = computed(() =>
this.expandInstitutions(this.selectedAssociations()),
);
protected readonly institutionSearch = new FormControl<string | Institution>(
'',
{ nonNullable: true },
);
protected readonly form = new FormGroup({
name: new FormControl(this.data.organization?.name ?? '', {
nonNullable: true,
validators: [Validators.required],
}),
otherInstId: new FormControl(this.data.organization?.other_inst_id ?? '', {
nonNullable: true,
}),
deleted: new FormControl(this.data.organization?.deleted ?? false, {
nonNullable: true,
}),
deleted: new FormControl(
{
value: this.data.organization?.deleted ?? false,
disabled: this.data.isCurrentOrganization ?? false,
},
{ nonNullable: true },
),
});
constructor() {
this.institutionSearch.valueChanges
.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((value) => {
if (typeof value !== 'string' || !value.trim()) {
this.isSearchingInstitutions.set(false);
return of({ elements: [] as Institution[] });
}
this.isSearchingInstitutions.set(true);
return this.institutionsService
.getInstitutionAutocompleteForSelector(value.trim())
.pipe(
catchError(() => {
this.snackBar.open(
'Institutionen konnten nicht geladen werden. Bitte versuche es später erneut.',
'OK',
{ duration: 5000 },
);
return of({ elements: [] as Institution[] });
}),
finalize(() => this.isSearchingInstitutions.set(false)),
);
}),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((page) =>
this.institutionSearchResults.set(page.elements ?? []),
);
}
private expandInstitutions(
roots: InstitutionAssociationsResponse[],
): EditableInstitution[] {
const entries = new Map<string, EditableInstitution>();
for (const root of roots) {
const id = cleanInstitutionId(root.id);
entries.set(id, {
id,
institution: {
id: `https://openalex.org/${id}`,
display_name: root.display_name,
},
manuallySelected: true,
origins: [],
});
}
for (const root of roots) {
const sourceId = cleanInstitutionId(root.id);
for (const association of root.associated_institutions ?? []) {
const id = cleanInstitutionId(association.id);
const entry = entries.get(id) ?? {
id,
institution: {
id: `https://openalex.org/${id}`,
display_name: association.display_name,
},
manuallySelected: false,
origins: [],
};
entry.origins.push({
sourceId,
sourceName: root.display_name,
relationship: association.relationship,
});
entries.set(id, entry);
}
}
return [...entries.values()];
}
protected selectInstitution(institution: Institution): void {
if (!institution.id || this.isLoadingAssociations()) return;
const selectedId = cleanInstitutionId(institution.id);
this.isLoadingAssociations.set(true);
this.organizationService
.getOrganizationInstitutionAssociations([selectedId])
.pipe(finalize(() => this.isLoadingAssociations.set(false)))
.subscribe({
next: ([response]) => {
if (!response) return;
const roots = [...this.selectedAssociations()];
const existingIndex = roots.findIndex(
(root) => cleanInstitutionId(root.id) === selectedId,
);
if (existingIndex === -1) roots.push(response);
else roots[existingIndex] = response;
this.selectedAssociations.set(roots);
},
error: () => {
this.snackBar.open(
'Die Institution konnte nicht hinzugefügt werden. Bitte versuche es später erneut.',
'OK',
{ duration: 5000 },
);
},
});
}
protected selectAutocompleteInstitution(
event: MatAutocompleteSelectedEvent,
): void {
const institution = event.option.value as Institution;
this.institutionSearch.setValue('', { emitEvent: false });
this.institutionSearchResults.set([]);
this.selectInstitution(institution);
}
protected displayInstitution(institution: Institution | string): string {
return typeof institution === 'string'
? institution
: (institution.display_name ?? '');
}
protected originLabels(entry: EditableInstitution): OriginLabel[] {
const labels: OriginLabel[] = [];
if (entry.manuallySelected) {
labels.push({ relationship: 'selected', label: 'Manuell ausgewählt' });
}
for (const relationship of ['child', 'related'] as const) {
const sourceNames = [
...new Set(
entry.origins
.filter((origin) => origin.relationship === relationship)
.map((origin) => origin.sourceName),
),
];
if (sourceNames.length === 0) continue;
labels.push({
relationship,
label: relationship === 'child' ? 'Untergeordnet' : 'Verbunden',
tooltip: `Automatisch hinzugefügt durch:\n${sourceNames.map((name) => `• ${name}`).join('\n')}`,
});
}
return labels;
}
protected removeInstitution(entry: EditableInstitution): void {
if (!entry.manuallySelected) return;
const remainingRoots = this.selectedAssociations().filter(
(root) => cleanInstitutionId(root.id) !== entry.id,
);
const remainingIds = new Set(
this.expandInstitutions(remainingRoots).map(
(institution) => institution.id,
),
);
const dependentCount = this.institutions().filter(
(institution) =>
institution.id !== entry.id && !remainingIds.has(institution.id),
).length;
this.dialog
.open<
InstitutionRemovalDialogComponent,
{ institutionName: string; dependentCount: number },
boolean | undefined
>(InstitutionRemovalDialogComponent, {
data: {
institutionName: entry.institution.display_name ?? entry.id,
dependentCount,
},
width: '520px',
maxWidth: 'calc(100vw - 32px)',
})
.afterClosed()
.subscribe((confirmed) => {
if (confirmed) this.selectedAssociations.set(remainingRoots);
});
}
protected submit(): void {
if (this.form.invalid) {
if (this.form.invalid || this.isLoadingAssociations()) {
this.form.markAllAsTouched();
return;
}
@@ -90,7 +334,9 @@ export class OrganizationDialogComponent {
const value = this.form.getRawValue();
const payload = {
name: value.name.trim(),
other_inst_id: value.otherInstId.trim(),
selected_openalex_institution_ids: this.selectedAssociations().map(
(root) => cleanInstitutionId(root.id),
),
};
if (this.data.mode === 'create') {
@@ -1,18 +1,17 @@
<section class="organizations-page">
<header class="page-header">
<div>
<h1>Organisationen</h1>
<p>Mandanten, externe Institutions-IDs und Status verwalten.</p>
<!-- Was meinte die KI mit Mandanten? -->
<h1>Organisationen</h1>
<div class="page-header-meta">
<p>Organisationen verwalten, OpenAlex-Institutionen zuordnen und Status festlegen</p>
<button
mat-flat-button
color="primary"
type="button"
(click)="startCreate()">
<mat-icon>add_business</mat-icon>
Neue Organisation
</button>
</div>
<button
mat-flat-button
color="primary"
type="button"
(click)="startCreate()">
<mat-icon>add_business</mat-icon>
Neue Organisation
</button>
</header>
<mat-card appearance="outlined">
@@ -31,6 +30,32 @@
</span>
</ng-template>
<ng-template #organizationInstitutionsTmp let-row>
@if ($any(row).institutions.length > 0) {
<span>
@for (
institution of $any(row).institutions;
track institution.id;
let index = $index
) {
@if (index < 3) {
{{ institution.display_name
}}{{
index < 2 && index < $any(row).institutions.length - 1 ? ', ' : ''
}}
}
}
@if ($any(row).institutions.length > 3) {
<span class="more-institutions">
+ {{ $any(row).institutions.length - 3 }} weitere
</span>
}
</span>
} @else {
<span class="no-institutions">Keine Institutionen</span>
}
</ng-template>
<ng-template #organizationActionsTmp let-row>
<div class="row-actions">
<button
@@ -44,7 +69,7 @@
mat-icon-button
type="button"
aria-label="Deaktivieren"
[disabled]="row.deleted"
[disabled]="row.deleted || isCurrentOrganization(row)"
(click)="deleteOrganization(row)">
<mat-icon>delete</mat-icon>
</button>
@@ -6,6 +6,12 @@
}
.page-header {
display: flex;
flex-direction: column;
gap: 6px;
}
.page-header-meta {
display: flex;
align-items: center;
justify-content: space-between;
@@ -24,7 +30,7 @@ p {
}
.page-header p {
margin-top: 6px;
flex: 1 1 auto;
}
.status {
@@ -49,7 +55,7 @@ p {
padding: 16px;
}
.page-header {
.page-header-meta {
align-items: flex-start;
flex-direction: column;
}
@@ -59,3 +65,8 @@ mat-card,
mat-paginator {
background-color: var(--sg-background);
}
.more-institutions,
.no-institutions {
color: var(--sg-text-muted);
}
@@ -16,11 +16,7 @@ import type {
OrganizationDialogData,
OrganizationDialogResult,
} from './organization-dialog/organization-dialog.component';
import {
InseOrganizationManagementModelOrganizationProfile,
OrganizationPage,
OrganizationService,
} from '../../api';
import { OrganizationService } from '../../api';
import {
GenericColumn,
DataTableComponent,
@@ -29,6 +25,11 @@ import { MatCardModule } from '@angular/material/card';
import { StatusPipe } from '../../shared/pipes/status.pipe';
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
import { Router } from '@angular/router';
import {
OrganizationPageWithInstitutions,
OrganizationWithInstitutions,
} from '../../resolvers/organizations-organizations.resolver';
import { CredentialService } from '../../shared/services/credential.service';
@Component({
selector: 'app-organizations',
@@ -52,10 +53,10 @@ export class OrganizationsComponent implements OnInit {
private readonly dialog = inject(MatDialog);
private readonly snackBar = inject(MatSnackBar);
private readonly organizationService = inject(OrganizationService);
private readonly credentialService = inject(CredentialService);
organizationPage = input.required<OrganizationPage>();
organizationColumns: GenericColumn<InseOrganizationManagementModelOrganizationProfile>[] =
[];
organizationPage = input.required<OrganizationPageWithInstitutions>();
organizationColumns: GenericColumn<OrganizationWithInstitutions>[] = [];
organizationStatusTmp = viewChild.required<TemplateRef<any>>(
'organizationStatusTmp',
@@ -63,6 +64,9 @@ export class OrganizationsComponent implements OnInit {
organizationActionsTmp = viewChild.required<TemplateRef<any>>(
'organizationActionsTmp',
);
organizationInstitutionsTmp = viewChild.required<TemplateRef<any>>(
'organizationInstitutionsTmp',
);
ngOnInit(): void {
this.organizationColumns = [
@@ -73,10 +77,10 @@ export class OrganizationsComponent implements OnInit {
accessorKey: 'name',
},
{
id: 'other_inst_id',
header: 'Externe ID',
type: 'accessor',
accessorKey: 'other_inst_id',
id: 'institutions',
header: 'OpenAlex-Institutionen',
type: 'display',
cellTemplate: this.organizationInstitutionsTmp(),
},
{
id: 'member_count',
@@ -104,16 +108,29 @@ export class OrganizationsComponent implements OnInit {
this.openDialog({ mode: 'create' });
}
protected startEdit(
organization: InseOrganizationManagementModelOrganizationProfile,
): void {
this.openDialog({ mode: 'edit', organization });
protected startEdit(organization: OrganizationWithInstitutions): void {
this.openDialog({
mode: 'edit',
organization,
isCurrentOrganization: this.isCurrentOrganization(organization),
});
}
protected isCurrentOrganization(
organization: OrganizationWithInstitutions,
): boolean {
return organization.id === this.credentialService.effectiveOrganizationId();
}
protected deleteOrganization(
organization: InseOrganizationManagementModelOrganizationProfile,
organization: OrganizationWithInstitutions,
): void {
if (organization.deleted) return;
if (
organization.deleted ||
this.isCurrentOrganization(organization)
) {
return;
}
import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then(
({ ConfirmationDialogComponent }) => {
@@ -134,7 +151,7 @@ export class OrganizationsComponent implements OnInit {
}
private softDeleteOrganization(
organization: InseOrganizationManagementModelOrganizationProfile,
organization: OrganizationWithInstitutions,
): void {
this.organizationService.deleteOrganisation(organization.id).subscribe({
next: () => {
@@ -146,8 +163,12 @@ export class OrganizationsComponent implements OnInit {
queryParamsHandling: 'merge',
});
},
error: () =>
this.showError('Organisation konnte nicht deaktiviert werden.'),
error: (error) =>
this.showError(
this.isProtectedOrganizationError(error)
? 'Die eigene Organisation kann nicht deaktiviert werden.'
: 'Organisation konnte nicht deaktiviert werden.',
),
});
}
@@ -159,7 +180,7 @@ export class OrganizationsComponent implements OnInit {
OrganizationDialogData,
OrganizationDialogResult | undefined
>(OrganizationDialogComponent, {
width: '620px',
width: '780px',
maxWidth: 'calc(100vw - 32px)',
data,
});
@@ -192,13 +213,24 @@ export class OrganizationsComponent implements OnInit {
},
error: (error) =>
this.showError(
error.status === 409
this.isProtectedOrganizationError(error)
? 'Die eigene Organisation kann nicht deaktiviert werden.'
: error.status === 409
? 'Eine Organisation mit diesem Namen existiert bereits.'
: 'Organisation konnte nicht gespeichert werden.',
),
});
}
private isProtectedOrganizationError(error: {
error?: { detail?: string };
}): boolean {
return (
error.error?.detail ===
'The organization of the real or effective account cannot be deleted.'
);
}
private showError(message: string): void {
this.snackBar.open(message, 'OK', { duration: 5000 });
}
@@ -138,6 +138,7 @@
track topic.topic_id ?? topic.topic_display_name
) {
<app-topic-chip
[topicId]="topic.topic_id"
[label]="topic.topic_display_name"
[fieldName]="topic.field_name"
[domainName]="topic.domain_name"
@@ -111,6 +111,7 @@
track topic.topic_id ?? topic.topic_display_name
) {
<app-topic-chip
[topicId]="topic.topic_id"
[label]="topic.topic_display_name"
[fieldName]="topic.field_name"
[domainName]="topic.domain_name"
@@ -106,6 +106,8 @@
[skText]="loading()"
class="person-topic-chip"
size="mini"
[topic]="topic"
[topicId]="topic.id"
[label]="topic.display_name || ''"
[description]="topic.description"
[subfieldName]="topic.subfield?.display_name"
@@ -34,6 +34,7 @@
} @else if (tags().length > 0) {
@for (tag of tags(); track tag.label) {
<app-topic-chip
[topicId]="tag.id"
[label]="tag.label"
[count]="tag.count"
[description]="tag.description"
@@ -41,9 +41,9 @@
<span
class="filter-topic-chip"
[style.--topic-color]="getFilterTopicColor(filter.value)"
[matTooltip]="getFilterTopicTooltip(filter.value)"
matTooltipClass="topic-chip-tooltip"
[matTooltipDisabled]="!getFilterTopicTooltip(filter.value)">
[appComponentTooltip]="AppTopicTooltipComponent"
[tooltipInputs]="getFilterTopicInputs(filter.value)"
[tooltipMaxWidth]="'500px'">
<mat-icon class="filter-topic-chip__icon">label</mat-icon>
<span class="filter-topic-chip__label">{{
filter.value
@@ -46,6 +46,9 @@ import {
import { SkTextDirective } from '../../custom-directives/sk-text.directive';
import { BookmarkService } from '../../shared/services/bookmark.service';
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
import { AppTopicTooltipComponent } from '../../shared/ui/app-topic-tooltip/app-topic-tooltip.component';
type InstitutionYearFilterMode = 'in' | 'from' | 'between';
@Component({
@@ -62,17 +65,19 @@ type InstitutionYearFilterMode = 'in' | 'from' | 'between';
MatCheckboxModule,
MatRadioModule,
MatTooltipModule,
MatAutocompleteModule,
TopicHierarchyComponent,
PersonCardComponent,
SkTextDirective,
MatAutocompleteModule,
CountryFlagComponent,
SkTextDirective,
ComponentTooltipDirective,
],
templateUrl: './person-list.component.html',
styleUrl: './person-list.component.scss',
standalone: true,
})
export class PersonListComponent {
readonly AppTopicTooltipComponent = AppTopicTooltipComponent;
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly personsService = inject(PersonsService);
@@ -477,6 +482,28 @@ export class PersonListComponent {
});
}
getFilterTopicInputs(topicName: string): { topicId?: string; topic?: any } {
const topic = this.findPersonTopic(topicName);
if (topic?.id) {
return { topicId: topic.id };
}
return {
topic: {
display_name: topicName,
description: this.getFilterTopicDescription(topicName) ?? undefined,
subfield: this.getFilterTopicSubfieldName(topicName)
? { display_name: this.getFilterTopicSubfieldName(topicName)! }
: undefined,
field: this.getFilterTopicFieldName(topicName)
? { display_name: this.getFilterTopicFieldName(topicName)! }
: undefined,
domain: this.getFilterTopicDomainName(topicName)
? { display_name: this.getFilterTopicDomainName(topicName)! }
: undefined,
},
};
}
clearAllFilters(): void {
this.selectedTopics.set(new Set<string>());
this.institutionControl.setValue('', { emitEvent: false });
@@ -171,11 +171,9 @@
type="button"
class="main-topic-button"
[disabled]="!getMainTopicItem(item)?.id"
[matTooltip]="getTopicTooltip(getMainTopicItem(item))"
matTooltipClass="topic-chip-tooltip"
[matTooltipDisabled]="
!hasTopicTooltip(getMainTopicItem(item))
"
[appComponentTooltip]="AppTopicTooltipComponent"
[tooltipInputs]="{ topicId: getMainTopicItem(item)?.id }"
[tooltipMaxWidth]="'500px'"
(click)="
selectTopic(getMainTopicItem(item), [item.year])
">
@@ -208,6 +206,7 @@
trackBy: trackByTopic
"
class="timeline-topic-chip"
[topicId]="topic.id"
[label]="topic.name"
[count]="topic.count"
[description]="getTopicDescription(topic)"
@@ -289,11 +288,9 @@
type="button"
class="main-topic-button"
[disabled]="!phase.primaryTopic.id"
[matTooltip]="getTopicTooltip(phase.primaryTopic)"
matTooltipClass="topic-chip-tooltip"
[matTooltipDisabled]="
!hasTopicTooltip(phase.primaryTopic)
"
[appComponentTooltip]="AppTopicTooltipComponent"
[tooltipInputs]="{ topicId: phase.primaryTopic.id }"
[tooltipMaxWidth]="'500px'"
(click)="
selectTopic(phase.primaryTopic, getPhaseYears(phase))
">
@@ -309,6 +306,7 @@
<app-topic-chip
*ngFor="let topic of phase.topics; trackBy: trackByTopic"
class="phase-topic-chip"
[topicId]="topic.id"
[label]="topic.name"
[count]="topic.count"
[description]="getTopicDescription(topic)"
@@ -387,6 +385,7 @@
trackBy: trackByTopic
"
size="mini"
[topicId]="topic.id"
[label]="topic.name"
[count]="topic.count"
[description]="getTopicDescription(topic)"
@@ -15,6 +15,8 @@ import {
import { TopicChipComponent } from '../../../../shared/ui/topic-chip/topic-chip.component';
import { TopicLegendComponent } from '../../../../shared/ui/topic-legend/topic-legend.component';
import { YearRangeSliderComponent } from '../../../../shared/ui/year-range-slider/year-range-slider.component';
import { ComponentTooltipDirective } from '../../../../directives/component-tooltip.directive';
import { AppTopicTooltipComponent } from '../../../../shared/ui/app-topic-tooltip/app-topic-tooltip.component';
import { topicHierarchyColor } from '../../../../resolvers/utils/topic-colors';
import {
buildTopicLegendGroups,
@@ -99,11 +101,13 @@ interface TimelineScrollAnchor {
TopicChipComponent,
TopicLegendComponent,
YearRangeSliderComponent,
ComponentTooltipDirective,
],
templateUrl: './research-timeline.component.html',
styleUrl: './research-timeline.component.scss',
})
export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
readonly AppTopicTooltipComponent = AppTopicTooltipComponent;
@ViewChild('timelineWrapper')
private readonly timelineWrapper?: ElementRef<HTMLDivElement>;
@Input() elements: TopicTimelineElement[] = [];
@@ -0,0 +1,28 @@
@if (loading) {
<div class="word-cloud-state">Forschungsthemen werden geladen ...</div>
} @else if (loadFailed) {
<div class="word-cloud-state">
Forschungsthemen konnten nicht geladen werden.
</div>
} @else if (words.length) {
<div class="word-cloud-chart">
@for (word of words; track word.name) {
<button
type="button"
class="word-cloud-word"
[style.color]="word.color"
[style.fontSize.px]="word.fontSize"
[style.fontWeight]="word.fontWeight"
[disabled]="!word.topicId"
[appComponentTooltip]="AppTopicTooltipComponent"
[tooltipInputs]="{ topicId: word.rawTopicId }"
[tooltipDisabled]="!word.rawTopicId"
[tooltipMaxWidth]="'500px'"
(click)="selectWord(word)">
{{ word.name }}
</button>
}
</div>
} @else {
<p class="word-cloud-state">Keine Forschungsthemen gefunden.</p>
}
@@ -0,0 +1,50 @@
:host {
display: block;
min-height: 420px;
}
.word-cloud-chart {
width: 100%;
min-height: 420px;
display: flex;
flex-wrap: wrap;
align-content: center;
align-items: baseline;
justify-content: center;
gap: 0.35em 1em;
padding: 1.5rem 1rem;
box-sizing: border-box;
}
.word-cloud-word {
appearance: none;
border: none;
background: none;
padding: 0;
margin: 0;
font-family: 'Open Sans', Arial, sans-serif;
line-height: 1.1;
cursor: pointer;
transition: transform 0.15s ease;
&:hover:not(:disabled),
&:focus-visible {
transform: scale(1.08);
outline: none;
}
&:disabled {
cursor: default;
}
}
.word-cloud-state {
margin: 0;
min-height: 420px;
display: flex;
align-items: center;
justify-content: center;
color: var(--sg-text-muted);
font-size: 14px;
text-align: center;
}
@@ -0,0 +1,164 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ComponentTooltipDirective } from '../../../../directives/component-tooltip.directive';
import { AppTopicTooltipComponent } from '../../../../shared/ui/app-topic-tooltip/app-topic-tooltip.component';
import { topicHierarchyColor } from '../../../../resolvers/utils/topic-colors';
import { TopicLegendTopic } from '../../../../resolvers/utils/topic-legend';
export interface WordCloudTopicOccurrence {
name: string;
topicId: string;
year: number | undefined;
fieldId: string | undefined;
fieldName: string | undefined;
domainId: string | undefined;
domainName: string | undefined;
subfieldId: string | undefined;
subfieldName: string | undefined;
}
export interface WordCloudWord {
name: string;
topicId: string;
rawTopicId: string;
color: string;
fontSize: number;
fontWeight: number;
}
export interface ResearchWordcloud {
words: WordCloudWord[];
legendTopics: TopicLegendTopic[];
}
const displayedWordLimit = 30;
const minimumFontSize = 12;
const maximumFontSize = 32;
export function buildResearchWordcloud(
occurrences: WordCloudTopicOccurrence[],
startYear: number | undefined,
endYear: number | undefined,
): ResearchWordcloud {
const counts = new Map<string, number>();
const legendTopicsByName = new Map<string, TopicLegendTopic>();
for (const occurrence of occurrences) {
if (!isWithinYearRange(occurrence.year, startYear, endYear)) {
continue;
}
counts.set(occurrence.name, (counts.get(occurrence.name) ?? 0) + 1);
if (!legendTopicsByName.has(occurrence.name)) {
legendTopicsByName.set(occurrence.name, {
id: occurrence.topicId,
name: occurrence.name,
field_id: occurrence.fieldId,
field_name: occurrence.fieldName,
domain_id: occurrence.domainId,
domain_name: occurrence.domainName,
subfield_id: occurrence.subfieldId,
subfield_name: occurrence.subfieldName,
});
}
}
if (counts.size === 0) {
return { words: [], legendTopics: [] };
}
const values = Array.from(counts.values());
const minimumValue = Math.min(...values);
const maximumValue = Math.max(...values);
const intensity = (value: number): number =>
maximumValue === minimumValue
? 1
: (value - minimumValue) / (maximumValue - minimumValue);
const displayed = Array.from(counts.entries())
.sort((left, right) => right[1] - left[1])
.slice(0, displayedWordLimit);
const legendTopics = displayed
.map(([name]) => legendTopicsByName.get(name))
.filter((topic): topic is TopicLegendTopic => Boolean(topic));
const words = displayed.map(([name, value]): WordCloudWord => {
const legendTopic = legendTopicsByName.get(name);
const scale = intensity(value);
return {
name,
topicId: legendTopic?.id ?? '',
rawTopicId: stripOpenAlexId(legendTopic?.id),
color: topicHierarchyColor(legendTopic),
fontSize: Math.round(
minimumFontSize + scale * (maximumFontSize - minimumFontSize),
),
fontWeight: scale > 0.66 ? 800 : scale > 0.33 ? 600 : 400,
};
});
return { words: centreWords(words), legendTopics };
}
function isWithinYearRange(
year: number | undefined,
startYear: number | undefined,
endYear: number | undefined,
): boolean {
if (startYear !== undefined && (year === undefined || year < startYear)) {
return false;
}
if (endYear !== undefined && (year === undefined || year > endYear)) {
return false;
}
return true;
}
function centreWords(words: WordCloudWord[]): WordCloudWord[] {
const centred: WordCloudWord[] = [];
words.forEach((word, index) => {
if (index % 2 === 0) {
centred.push(word);
return;
}
centred.unshift(word);
});
return centred;
}
function stripOpenAlexId(id: string | null | undefined): string {
return (id ?? '').replace('https://openalex.org/', '');
}
@Component({
selector: 'app-research-wordcloud',
standalone: true,
imports: [ComponentTooltipDirective],
templateUrl: './research-wordcloud.component.html',
styleUrl: './research-wordcloud.component.scss',
})
export class ResearchWordcloudComponent {
readonly AppTopicTooltipComponent = AppTopicTooltipComponent;
@Input() words: WordCloudWord[] = [];
@Input() loading = false;
@Input() loadFailed = false;
@Output() wordSelect = new EventEmitter<WordCloudWord>();
selectWord(word: WordCloudWord): void {
if (!word.topicId) {
return;
}
this.wordSelect.emit(word);
}
}
@@ -19,30 +19,11 @@
(topicSelect)="onTimelineTopicSelect($event)"
(yearSelect)="onTimelineYearSelect($event)"
(loadEarlierYears)="onTimelineLoadEarlierYears()">
<div timeline-wordcloud-content class="word-cloud-view">
@if (loadingWordCloud) {
<div class="word-cloud-state">Forschungsthemen werden geladen ...</div>
} @else if (wordCloudWords.length) {
<div class="word-cloud-chart">
@for (word of wordCloudWords; track word.name) {
<button
type="button"
class="word-cloud-word"
[style.color]="word.color"
[style.fontSize.px]="word.fontSize"
[style.fontWeight]="word.fontWeight"
[disabled]="!word.topicId"
[matTooltip]="word.tooltip"
[matTooltipDisabled]="!word.tooltip"
matTooltipClass="topic-chip-tooltip"
(click)="onWordClick(word)">
{{ word.name }}
</button>
}
</div>
} @else if (wordCloudEmpty) {
<p class="word-cloud-empty">Keine Forschungsthemen gefunden.</p>
}
</div>
<app-research-wordcloud
timeline-wordcloud-content
[words]="wordCloudWords"
[loading]="loadingWordCloud"
[loadFailed]="wordCloudLoadFailed"
(wordSelect)="onWordClick($event)" />
</app-research-timeline>
</section>
@@ -3,54 +3,3 @@
display: block;
box-sizing: border-box;
}
.word-cloud-view {
min-height: 420px;
}
.word-cloud-chart {
width: 100%;
min-height: 420px;
display: flex;
flex-wrap: wrap;
align-content: center;
align-items: baseline;
justify-content: center;
gap: 0.35em 1em;
padding: 1.5rem 1rem;
box-sizing: border-box;
}
.word-cloud-word {
appearance: none;
border: none;
background: none;
padding: 0;
margin: 0;
font-family: 'Open Sans', Arial, sans-serif;
line-height: 1.1;
cursor: pointer;
transition: transform 0.15s ease;
&:hover:not(:disabled),
&:focus-visible {
transform: scale(1.08);
outline: none;
}
&:disabled {
cursor: default;
}
}
.word-cloud-state,
.word-cloud-empty {
margin: 0;
min-height: 420px;
display: flex;
align-items: center;
justify-content: center;
color: var(--sg-text-muted);
font-size: 14px;
text-align: center;
}
@@ -1,8 +1,6 @@
import { CommonModule } from '@angular/common';
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { MatTooltipModule } from '@angular/material/tooltip';
import { combineLatest, distinctUntilChanged, map } from 'rxjs';
import { TopicCount, TopicsByYear, WorksService } from '../../api';
@@ -14,27 +12,19 @@ import {
TopicTimelineElement,
TopicTimelineTopic,
} from './components/research-timeline/research-timeline.component';
import {
buildResearchWordcloud,
ResearchWordcloudComponent,
WordCloudTopicOccurrence,
WordCloudWord,
} from './components/research-wordcloud/research-wordcloud.component';
import { workQueryParamKeys } from '../../resolvers/work-page.resolver';
import { TopicLegendTopic } from '../../resolvers/utils/topic-legend';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
import { buildTopicHierarchyTooltip } from '../../resolvers/utils/topic-tooltip';
export interface WordCloudWord {
name: string;
value: number;
topicId: string | undefined;
fieldName: string | undefined;
domainName: string | undefined;
color: string;
fontSize: number;
fontWeight: number;
tooltip: string;
}
@Component({
selector: 'app-person-overview',
standalone: true,
imports: [CommonModule, ResearchTimelineComponent, MatTooltipModule],
imports: [ResearchTimelineComponent, ResearchWordcloudComponent],
templateUrl: './person-overview.component.html',
styleUrl: './person-overview.component.scss',
})
@@ -73,19 +63,9 @@ export class PersonOverviewComponent implements OnInit {
wordCloudWords: WordCloudWord[] = [];
wordCloudLegendTopics: TopicLegendTopic[] = [];
loadingWordCloud = false;
wordCloudEmpty = false;
wordCloudLoadFailed = false;
private rawTopicOccurrences: Array<{
name: string;
topicId: string;
year: number | undefined;
fieldId: string | undefined;
fieldName: string | undefined;
domainId: string | undefined;
domainName: string | undefined;
subfieldId: string | undefined;
subfieldName: string | undefined;
}> = [];
private rawTopicOccurrences: WordCloudTopicOccurrence[] = [];
ngOnInit(): void {
combineLatest(this.route.pathFromRoot.map((route) => route.paramMap))
@@ -351,14 +331,14 @@ export class PersonOverviewComponent implements OnInit {
if (!authorId || authorId === '0') {
this.wordCloudWords = [];
this.wordCloudLegendTopics = [];
this.wordCloudEmpty = false;
this.wordCloudLoadFailed = false;
this.loadingWordCloud = false;
this.rawTopicOccurrences = [];
return;
}
this.loadingWordCloud = true;
this.wordCloudEmpty = false;
this.wordCloudLoadFailed = false;
this.wordCloudWords = [];
this.wordCloudLegendTopics = [];
@@ -389,104 +369,27 @@ export class PersonOverviewComponent implements OnInit {
this.loadingWordCloud = false;
if (this.rawTopicOccurrences.length === 0) {
this.wordCloudLegendTopics = [];
this.wordCloudEmpty = true;
return;
}
setTimeout(() => this.rebuildWordCloud());
},
error: (error) => {
console.error('Word cloud could not be loaded.', error);
this.loadingWordCloud = false;
this.rawTopicOccurrences = [];
this.wordCloudLegendTopics = [];
this.wordCloudEmpty = true;
this.wordCloudLoadFailed = true;
},
});
}
private rebuildWordCloud(): void {
const start = this.timelineStartYear;
const end = this.timelineEndYear;
const counts = new Map<string, number>();
const nameToId = new Map<string, string>();
const nameToColorInput = new Map<string, TopicLegendTopic>();
const wordCloud = buildResearchWordcloud(
this.rawTopicOccurrences,
this.timelineStartYear,
this.timelineEndYear,
);
for (const occ of this.rawTopicOccurrences) {
if (start !== undefined && (occ.year === undefined || occ.year < start))
continue;
if (end !== undefined && (occ.year === undefined || occ.year > end))
continue;
counts.set(occ.name, (counts.get(occ.name) ?? 0) + 1);
if (!nameToId.has(occ.name)) {
nameToId.set(occ.name, occ.topicId);
nameToColorInput.set(occ.name, {
id: occ.topicId,
name: occ.name,
field_id: occ.fieldId,
field_name: occ.fieldName,
domain_id: occ.domainId,
domain_name: occ.domainName,
subfield_id: occ.subfieldId,
subfield_name: occ.subfieldName,
});
}
}
if (counts.size === 0) {
this.wordCloudWords = [];
this.wordCloudLegendTopics = [];
this.wordCloudEmpty = true;
return;
}
this.wordCloudEmpty = false;
const allValues = Array.from(counts.values());
const minVal = Math.min(...allValues);
const maxVal = Math.max(...allValues);
const intensity = (v: number): number =>
maxVal === minVal ? 1 : (v - minVal) / (maxVal - minVal);
const sorted = Array.from(counts.entries()).sort((a, b) => b[1] - a[1]);
const topNames = sorted.slice(0, 30).map(([name]) => name);
this.wordCloudLegendTopics = topNames
.map((name) => nameToColorInput.get(name))
.filter((topic): topic is TopicLegendTopic => Boolean(topic));
const words = sorted.slice(0, 30).map(([name, value]): WordCloudWord => {
const t = intensity(value);
const colorInput = nameToColorInput.get(name);
return {
name,
value,
topicId: nameToId.get(name),
fieldName: colorInput?.field_name ?? undefined,
domainName: colorInput?.domain_name ?? undefined,
color: topicHierarchyColor(colorInput),
fontSize: Math.round(12 + t * (32 - 12)),
fontWeight: t > 0.66 ? 800 : t > 0.33 ? 600 : 400,
tooltip: buildTopicHierarchyTooltip({
topicName: name,
subfieldName: colorInput?.subfield_name,
fieldName: colorInput?.field_name,
domainName: colorInput?.domain_name,
}),
};
});
const centred: WordCloudWord[] = [];
words.forEach((word, i) => {
if (i % 2 === 0) {
centred.push(word);
} else {
centred.unshift(word);
}
});
this.wordCloudWords = centred;
this.wordCloudWords = wordCloud.words;
this.wordCloudLegendTopics = wordCloud.legendTopics;
}
private mapTimelineElements(
@@ -37,8 +37,11 @@
<mat-icon>circle</mat-icon>
<span>{{ getStatusDisplay(dfgProject.funding_end) }}</span>
</div>
@if (dfgProject.link) {
<a [href]="dfgProject.link" target="_blank" class="primary-action">
@if (dfgProject.page_url) {
<a
[href]="dfgProject.page_url"
target="_blank"
class="primary-action">
<mat-icon>open_in_new</mat-icon>
<span>Zum Projekt</span>
</a>
@@ -218,10 +221,7 @@
</div>
@if (getInstitutionsList().length > 0) {
<div class="institution-grid">
@for (
institution of getInstitutionsList();
track institution.institute_id + (institution.role_key || '')
) {
@for (institution of getInstitutionsList(); track $index) {
<div
(click)="
searchForInstitutionName(getInstitutionName(institution))
@@ -245,6 +245,7 @@
track keyword.id || keyword.label
) {
<app-topic-chip
[topicId]="keyword.id"
[label]="keyword.label"
[count]="keyword.count"
[subfieldName]="keyword.subfieldName"
@@ -40,13 +40,10 @@
}
@if (authorList.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isExpanded"
(click)="togglePublicationAuthorsExpansion(pub)">
{{ isExpanded ? 'weniger' : '+' + (authorList.length - 3) }}
</button>
<app-chip-overflow-toggle
[expanded]="isExpanded"
[hiddenCount]="authorList.length - 3"
(toggle)="togglePublicationAuthorsExpansion(pub)" />
}
</div>
} @else {
@@ -6,29 +6,6 @@
background: var(--sg-card-bg);
border: 1px solid var(--sg-border);
}
.publication-institution-more {
display: inline-flex;
align-items: center;
min-height: 24px;
padding: 3px 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-surface);
color: var(--sg-text-muted);
font-family: inherit;
font-size: 11px;
line-height: 1.2;
cursor: pointer;
transition: all 0.2s ease;
&:hover,
&:focus-visible {
border-color: var(--sg-primary);
color: var(--sg-primary);
background: var(--sg-surface-soft);
outline: none;
}
}
.section-header {
display: flex;
align-items: center;
@@ -20,10 +20,12 @@ import {
DataTableComponent,
GenericColumn,
} from '../../../../shared/ui/data-table/data-table.component';
import { ChipOverflowToggleComponent } from '../../../../shared/ui/chip-overflow-toggle/chip-overflow-toggle.component';
@Component({
selector: 'app-publications-table',
imports: [
ChipOverflowToggleComponent,
CommonModule,
MatIcon,
MatCard,
@@ -230,6 +230,8 @@
<div class="tags">
@for (topic of publication.topics; track topic.id) {
<app-topic-chip
[topic]="topic"
[topicId]="topic.id"
[label]="topic.display_name || ''"
[description]="topic.description"
[subfieldName]="topic.subfield?.display_name"

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