Compare commits

...
Author SHA1 Message Date
Kazgatari 767f532e6f removed old unused components
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-23 17:15:56 +02:00
Kazgatari a21d5eaea4 changed other hardcoded icon values to variables 2026-08-23 17:06:20 +02:00
Kazgatari d8de0c2156 changed person-card to use global institution chip
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-23 16:46:37 +02:00
genja ba1c53b642 Merge pull request 'feature/keywords-analysis' (#299) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #299
2026-08-23 11:10:45 +02:00
genja ef00947786 disabled search button while new keyword is being added
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-23 11:03:46 +02:00
genja 9a4a4de379 prevented mouse event propagation in project tables 2026-08-23 11:00:21 +02:00
genja 04e3f97b8b prevented mouse event propagation for chips and togglers 2026-08-23 10:59:36 +02:00
genja 2bf8e03117 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis 2026-08-23 10:28:25 +02:00
tischer 1219970ba8 Merge pull request 'refactor/bio' (#298) from refactor/bio into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #298
2026-08-22 17:08:55 +02:00
Steven Tischer 5c50c29760 fix build: ensure client is closed after API calls
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-22 17:03:34 +02:00
Steven Tischer 5343c3204d execute pipeline
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-08-22 16:48:55 +02:00
Steven Tischer 613640a730 add AI-generated badge to bio
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-08-22 16:41:28 +02:00
Steven Tischer 3147de9fcb improve error handling in bio generation and update tests 2026-08-22 16:20:36 +02:00
Steven Tischer 7d3792c7b4 fix: update parameter documentation to use 'examples' instead of 'example'
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-08-22 14:14:17 +02:00
Steven Tischer eb5d6830a5 test: add tests for person bio generation 2026-08-22 14:12:03 +02:00
Steven Tischer 7da36d8777 remove unused 'include' parameter 2026-08-22 14:04:03 +02:00
Steven Tischer 21482f3c6f refactor: move bio logic to a separate module 2026-08-22 13:59:29 +02:00
tischer b772b100d5 Merge pull request 'feat/ranking' (#296) from feat/ranking into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #296
2026-08-22 13:39:52 +02:00
Steven Tischer bbce780609 fix: update toggleSelect to select only 4 authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-22 13:34:47 +02:00
Steven Tischer d719a34ab0 add fuzzy search logic and remove some stats from compare page
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-22 13:08:59 +02:00
Steven Tischer 57d0daa21b enable fuzzy search button 2026-08-22 09:35:55 +02:00
kuzko 1ca3db5c78 Merge pull request 'refactor/icons' (#295) from refactor/icons into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #295
2026-08-18 20:17:52 +02:00
Kazgatari c85d3fa03f fix: bound routing link to signal to remove console error
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-18 20:07:57 +02:00
Kazgatari ffc02a4e59 fix: used set to deduplicate entries 2026-08-18 20:06:55 +02:00
Kazgatari 6c20dc2b58 added expandible toggle to associated institutions 2026-08-18 20:02:12 +02:00
Kazgatari 24cc476dbe implemented overview in institution and added guardrails for card to fetch new information if existing is incomplete 2026-08-18 19:56:56 +02:00
Kazgatari b2f55bd05a changed institutions to hold associated institution array 2026-08-18 19:55:48 +02:00
Kazgatari e153e2d74a Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into refactor/icons 2026-08-18 18:27:38 +02:00
farajollahi 171b296c2a Merge pull request 'multi-organisations-statics' (#294) from multi-organisations-statics into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #294
2026-08-18 18:00:08 +02:00
Kazgatari 435c4ae3db added tooltip disable to undefined values for authors and institutions to avoid empty tooltips and links to undefined entities 2026-08-18 17:56:14 +02:00
Kazgatari ac6b5aa72b started with icon duplicate merge 2026-08-18 17:54:32 +02:00
farajollahi e8be0ae8aa Merge branch 'dev' into multi-organisations-statics
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-18 17:47:05 +02:00
kuzko 17e0909d69 Merge pull request 'refactor/icons' (#293) from refactor/icons into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #293
2026-08-18 12:25:21 +02:00
Kazgatari 3aa4c478f6 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into refactor/icons
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-18 12:13:27 +02:00
Kazgatari 9ef9e334fd refactor: changed all static icons to use central defined icons (duplicates not resolved) 2026-08-18 11:57:52 +02:00
genja e7269c6bd2 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-18 11:18:21 +02:00
genja 5aff658c16 replaced the keywords search results navbar with generic navbar component 2026-08-18 11:16:30 +02:00
khalti a40aca3dbe Merge pull request 'refactor(patents): share app-card-search/source-filter across patent page.' (#292) from ts-136-patent-to-researchers-v2 into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #292
2026-08-18 11:00:07 +02:00
khalti 95662119b1 fix(patent-table): resolve merge conflicts with dev
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-18 10:55:23 +02:00
Kazgatari 5b59aca4e6 fix: added option to disable tooltip on topic chip component
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-18 10:49:16 +02:00
khalti 83c809983c refactor(patents): share app-card-search/source-filter across patent page.
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-08-18 10:39:01 +02:00
Kazgatari f5cd79a718 fix: incorrect colors in person card due to missing information
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-18 08:28:43 +02:00
genja 81b7e04b66 Merge pull request 'feature/keywords-analysis' (#291) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #291
2026-08-17 23:17:24 +02:00
genja 25cf39ff69 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-17 22:54:36 +02:00
genja 9a6bae2df4 applied generoc table-data-row for project tables 2026-08-17 22:54:14 +02:00
genja 6eb159cc03 added generic table-detail-row component 2026-08-17 22:52:20 +02:00
genja 6b7a036128 highlight only if keywords are there 2026-08-17 22:52:04 +02:00
genja da70af9163 minor bug fix 2026-08-17 22:46:25 +02:00
genja 09e5af0016 fixed default projects sorting by title for keyword search 2026-08-17 22:45:21 +02:00
genja 203d9cb6d4 fixed wrong highlighted items for dfg projects query 2026-08-17 22:39:44 +02:00
Louis dde38bb680 Merge pull request 'fix/nested-tooltip-hover' (#290) from fix/nested-tooltip-hover into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #290
2026-08-17 22:29:40 +02:00
Louis e7b6255e54 fix(sidebar): highlight nav item for detail pages, not just their list route
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-17 22:20:43 +02:00
Louis 0f9991b618 feat(institution-card): show country flag next to city/country subtitle 2026-08-17 22:08:52 +02:00
Louis ac97c9f496 fix(publication-card): cap tooltip width, size topics to content, truncate chip labels 2026-08-17 22:02:58 +02:00
Louis 8261de4a02 fix(tooltip): prevent tooltips from clipping off-screen near edges 2026-08-17 21:44:55 +02:00
Louis f69b3cf871 fix(tooltip): don't close a tooltip while a nested tooltip inside it is open 2026-08-17 20:23:48 +02:00
farajollahi 6e7a8237ef Merge branch 'refactor-multi-organisation' into multi-organisations-statics
LocationBasedServices/smartguide/pipeline/head This commit looks good
# Conflicts:
#	webapp/src/app/modules/dashboard/dashboard.component.ts
2026-08-17 16:43:29 +02:00
farajollahi c8e5a65f5d fix(dashboard): support multiple institutions and improve project analytics
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-17 16:32:50 +02:00
farajollahi a6c4668d13 show projects of institut
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-17 14:57:31 +02:00
genja 4338b1cc0e Merge pull request 'feature/keywords-analysis' (#289) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #289
2026-08-17 14:53:48 +02:00
genja d5164f9863 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-17 14:48:46 +02:00
genja 86fc87f507 fixed wrong query param retrieval 2026-08-17 14:48:17 +02:00
genja 156e31643c added optional OR/AND matching of topic ids for projects search + changed keyword search from AND to OR matching 2026-08-17 14:48:00 +02:00
spsaefan dbe8f2449a Add institution tab navigation
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-17 14:30:38 +02:00
spsaefan 9c593a0d09 Update institution tab style 2026-08-17 14:30:09 +02:00
kallweit a21030309e Merge pull request 'feature/person-overview-wordcloud' (#288) from feature/person-overview-wordcloud into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #288
2026-08-17 14:18:47 +02:00
kallweit a8db8194cf feat(person-overview): add secondary action to tooltips in 'person interesting' section
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-17 14:04:12 +02:00
kallweit ce218cbfa1 feat(research-timeline): add secondary action to topic tooltip 2026-08-17 14:04:12 +02:00
kallweit ae80f0f812 feat(topic-card, person-overview): add optional secondary action to the topic card to link to person's publications 2026-08-17 14:04:12 +02:00
farajollahi df5f131320 fix(dashboard): synchronize institution selection and project status data 2026-08-17 13:03:26 +02:00
spsaefan 2f22240d94 Fix dashboard card navigation
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-17 11:50:47 +02:00
spsaefan 77095c8549 Set default institution tab 2026-08-17 11:50:21 +02:00
spsaefan c733442300 Remove all institutions tab 2026-08-17 11:47:43 +02:00
Louis fed1e56c81 Merge pull request 'refactor/list-card-heights' (#287) from refactor/list-card-heights into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #287
2026-08-17 00:16:03 +02:00
Louis e0d1f0df5c Merge remote-tracking branch 'origin/dev' into refactor/list-card-heights
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-17 00:05:35 +02:00
Louis 27301bf6a5 fix(card-search): keep a single result at normal card width
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-16 23:56:51 +02:00
Louis bbd4ff8685 fix(publications): refresh filter labels when a topic/author id is appended 2026-08-16 23:56:29 +02:00
Louis dbc53a9a49 fix(publication-card): stop card clicks navigating to /topic, wire chips to search filters 2026-08-16 23:56:11 +02:00
Louis 0f0f30f08c feat(publication-card): clamp title/topics/authors to fixed-height sections 2026-08-16 23:25:58 +02:00
Louis 6c3c43ef4f style(projects): wrap type filter chips in filter-card box 2026-08-16 23:00:13 +02:00
Louis a5f6ccc75b style(patents): align filter row with News's design and card grid 2026-08-16 22:37:12 +02:00
Louis cfa2c768eb fix(patents): clamp patent title to 3 lines 2026-08-16 22:26:18 +02:00
kuzko 54e0701698 Merge pull request 'refactor/static_topic_cache' (#285) from refactor/static_topic_cache into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #285
2026-08-16 22:24:23 +02:00
Louis 4a61c00642 fix(project-card): clamp title to prevent row-to-row height drift 2026-08-16 22:18:38 +02:00
Kazgatari 49c45cb924 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into refactor/static_topic_cache
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-16 22:13:52 +02:00
Kazgatari ad14f60a2c changed icons 2026-08-16 22:13:33 +02:00
Louis 2bcd1d4586 fix(institution-card): stabilize header heigh 2026-08-16 22:06:53 +02:00
genja 5d2d694a20 Merge pull request 'feature/keywords-analysis' (#284) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #284
2026-08-16 22:01:01 +02:00
Louis dc31b21dac fix(topic-card): stabilize header height and cap description length 2026-08-16 21:56:17 +02:00
genja d28a662da3 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 This commit looks good
2026-08-16 21:38:23 +02:00
genja 8a418a99b4 enabled project detail row only for projects where highlighted content is persistent 2026-08-16 21:38:01 +02:00
genja 17100024e5 moved topic resolving to search results state service 2026-08-16 21:36:32 +02:00
genja 9b95728c7b bund project field fixed 2026-08-16 21:36:12 +02:00
Kazgatari 4937889968 regenerate frontend 2026-08-16 21:19:05 +02:00
Kazgatari 36773c4ae2 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into refactor/static_topic_cache 2026-08-16 21:04:50 +02:00
Kazgatari 353d938d3e topic hierarchy model addition in backend and component change in frontend 2026-08-16 21:03:51 +02:00
genja f02e510847 expanded row view adjusted for DFG project table 2026-08-16 20:48:32 +02:00
genja 6e0acb9cde added expanded row for EU projects table 2026-08-16 20:47:23 +02:00
genja a0fdc8799b added expanded Row for bund project table 2026-08-16 20:47:03 +02:00
genja f4656fcf39 fixed eu projects resolver 2026-08-16 20:46:16 +02:00
genja d73ee592ea fixed Bund highlight model 2026-08-16 20:45:55 +02:00
Louis c6e1051059 Merge pull request 'fix/wordcloud-legend-highlight' (#283) from fix/wordcloud-legend-highlight into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #283
2026-08-16 20:40:37 +02:00
Kazgatari 024724b51d removed cache logic from patents 2026-08-16 19:14:26 +02:00
Kazgatari 7798cdaea5 cleanup of comments and changed import signature in main 2026-08-16 17:54:30 +02:00
Kazgatari a1b9f5a084 removed old service manualy from generated files for now 2026-08-16 17:52:57 +02:00
Kazgatari 6f79733b3e removed topic cache and all affiliated files to see what breaks 2026-08-16 17:35:20 +02:00
spsaefan 8d7323a387 Add institution filter tests
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-15 22:46:05 +02:00
spsaefan 6a6ec8662c Filter dashboard analytics by institution 2026-08-15 22:45:56 +02:00
spsaefan c70e6bf489 Filter word cloud by institution 2026-08-15 22:45:40 +02:00
spsaefan 82fa2e816b Add institution filtering 2026-08-15 22:45:24 +02:00
spsaefan fbcee778d2 Add institution tab styles 2026-08-15 22:44:34 +02:00
spsaefan 1758227f1e Add institution tabs 2026-08-15 22:43:52 +02:00
farajollahi 545f38bc3d Merge branch 'dev' into multi-organisations-statics
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-12 10:55:48 +02:00
farajollahi c8fa70e7f0 feat(dashboard): add institution filter for organization-wide statistics
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-11 12:53:13 +02:00
330 changed files with 10361 additions and 31666 deletions
File diff suppressed because it is too large Load Diff
+2
View File
@@ -213,6 +213,7 @@ async def change_password(
operation_id="canFetchGdprRelevantData",
)
async def can_fetch_gdpr_relevant_data(
session: SessionDep,
access_token: Annotated[
AccessTokenMetadata,
auth_service.CurrentUserAccessTokenPayloadDep,
@@ -227,6 +228,7 @@ async def can_fetch_gdpr_relevant_data(
] = None,
) -> bool:
return await auth_service.can_fetch_gdpr_relevant_data(
session=session,
access_token=access_token,
raw_oa_author_id=raw_oa_author_id,
raw_oa_institution_id=raw_oa_institution_id,
+50 -18
View File
@@ -1467,6 +1467,7 @@ def change_password(
async def can_fetch_gdpr_relevant_data(
session: Session,
access_token: AccessTokenMetadata,
raw_oa_author_id: str | None = None,
raw_oa_institution_id: str | None = None,
@@ -1493,40 +1494,71 @@ async def can_fetch_gdpr_relevant_data(
logger.debug("No OpenAlex author ID or institution ID provided")
return False
effective_institution_id = access_token.effective_institution_id
# Current user does not belong to any institution
if not effective_institution_id:
institution_ids = list(
session.exec(
select(OrganizationInstitution.openalex_institution_id)
.where(
OrganizationInstitution.organization_id
== access_token.effective_organization_id
)
.order_by(OrganizationInstitution.position)
).all()
)
if not institution_ids and access_token.effective_institution_id:
institution_ids = [access_token.effective_institution_id]
if not institution_ids:
logger.debug(
"Current user does not belong to any institution, cannot fetch GDPR-relevant data"
)
return False
# Current user belongs to an institution, but the request is for a different institution
from inse.organization_management import service as organization_service
association_groups = await organization_service.resolve_institution_associations(
institution_ids
)
organization_institution_ids = set(institution_ids)
for group in association_groups:
organization_institution_ids.add(group.id.rstrip("/").split("/")[-1])
organization_institution_ids.update(
association.id.rstrip("/").split("/")[-1]
for association in group.associated_institutions
)
requested_institution_id = (
raw_oa_institution_id.rstrip("/").split("/")[-1]
if raw_oa_institution_id
else None
)
if (
raw_oa_institution_id
and effective_institution_id
and raw_oa_institution_id != effective_institution_id
requested_institution_id
and requested_institution_id not in organization_institution_ids
):
logger.debug(
"Current user belongs to institution %s, but request is for institution %s, cannot fetch GDPR-relevant data",
effective_institution_id,
raw_oa_institution_id,
organization_institution_ids,
requested_institution_id,
)
return False
# Current user belongs to an institution, but request is for author not belonging to that institution
if raw_oa_author_id:
author_belongs_to_institution = (
await authors_service.author_currently_belongs_to_institution(
raw_oa_author_id or "", effective_institution_id
)
)
for institution_id in organization_institution_ids:
if await authors_service.author_currently_belongs_to_institution(
raw_oa_author_id, institution_id
):
logger.debug(
"Author %s belongs to organization institution %s",
raw_oa_author_id,
institution_id,
)
return True
logger.debug(
"Author %s belongs to institution %s: %s",
"Author %s does not belong to any organization institution %s",
raw_oa_author_id,
effective_institution_id,
author_belongs_to_institution,
organization_institution_ids,
)
return author_belongs_to_institution
return False
return True
@@ -1,6 +1,7 @@
import datetime as _dt
import uuid
from datetime import timedelta
from unittest.mock import AsyncMock, patch
import pytest
from fastapi import HTTPException, Response
@@ -14,11 +15,16 @@ from inse.auth.model import (
Account,
IdTokenMetadata,
Organization,
OrganizationInstitution,
RefreshTokenMetadata,
Secret,
SecretPurpose,
UserRole,
)
from inse.organization_management.model import (
InstitutionAssociation,
InstitutionAssociationsResponse,
)
@pytest.fixture()
@@ -81,6 +87,74 @@ def test_hash_and_verify_password():
assert auth_service._verify_password("wrong", h) is False
@pytest.mark.anyio
async def test_gdpr_access_allows_every_organization_institution(in_memory_session):
org, account = create_org_and_account(
in_memory_session, "multi-institution@example.com", "pw"
)
in_memory_session.add_all(
[
OrganizationInstitution(
organization_id=org.id,
openalex_institution_id="I111",
position=0,
),
OrganizationInstitution(
organization_id=org.id,
openalex_institution_id="I222",
position=1,
),
]
)
in_memory_session.commit()
token = AccessTokenMetadata(
real_account_id=account.id,
expires_at=_dt.datetime.now(_dt.UTC) + timedelta(hours=1),
user_fingerprint_hash="fingerprint",
effective_account_id=account.id,
effective_organization_id=org.id,
effective_institution_id="I111",
)
associations = [
InstitutionAssociationsResponse(
id="I111",
display_name="Root institution",
associated_institutions=[
InstitutionAssociation(
id="I333",
display_name="Child institution",
relationship="child",
)
],
),
InstitutionAssociationsResponse(
id="I222",
display_name="Second institution",
associated_institutions=[],
),
]
with patch(
"inse.organization_management.service.resolve_institution_associations",
new=AsyncMock(return_value=associations),
):
assert await auth_service.can_fetch_gdpr_relevant_data(
session=in_memory_session,
access_token=token,
raw_oa_institution_id="https://openalex.org/I222",
)
assert await auth_service.can_fetch_gdpr_relevant_data(
session=in_memory_session,
access_token=token,
raw_oa_institution_id="I333",
)
assert not await auth_service.can_fetch_gdpr_relevant_data(
session=in_memory_session,
access_token=token,
raw_oa_institution_id="I444",
)
def test_request_otk_and_login_flow(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "test-hmac-key"
config_module.settings.token_issuer_id = "test-issuer"
@@ -113,7 +187,9 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup):
assert login_result.id_token.real_account_id == acc.id
raw_id_token = _get_cookie_value(response, auth_service.ID_TOKEN_COOKIE_KEY)
payload = auth_service._verify_id_token(raw_id_token=raw_id_token, session=in_memory_session)
payload = auth_service._verify_id_token(
raw_id_token=raw_id_token, session=in_memory_session
)
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
@@ -175,7 +251,9 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
)
assert isinstance(access_response.access_token, AccessTokenMetadata)
raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY)
raw_refresh_token = _get_cookie_value(
response, auth_service.REFRESH_TOKEN_COOKIE_KEY
)
refresh_payload = auth_service._verify_refresh_token(
raw_refresh_token=raw_refresh_token,
session=in_memory_session,
@@ -185,9 +263,7 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
effective_account_id=uuid.UUID(
refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY]
),
expires_at=_dt.datetime.fromtimestamp(
refresh_payload["exp"], tz=_dt.UTC
),
expires_at=_dt.datetime.fromtimestamp(refresh_payload["exp"], tz=_dt.UTC),
epoch=refresh_payload[auth_service.EPOCH_KEY],
effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]),
effective_organization_id=uuid.UUID(
@@ -240,7 +316,9 @@ def test_access_and_refresh_token_preserve_multiple_roles(
UserRole.USER.value,
]
raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY)
raw_refresh_token = _get_cookie_value(
response, auth_service.REFRESH_TOKEN_COOKIE_KEY
)
refresh_payload = auth_service._verify_refresh_token(
raw_refresh_token=raw_refresh_token,
session=in_memory_session,
@@ -634,7 +712,6 @@ def test_get_account_epoch_not_found(in_memory_session):
auth_service._get_account_epoch(in_memory_session, random_id)
def test_request_password_reset_creates_secret(in_memory_session, settings_backup):
email = "reset@example.com"
password = "oldpw123"
+5
View File
@@ -1,6 +1,11 @@
from pydantic import BaseModel
class DashboardInstitution(BaseModel):
id: str
display_name: str
class DashboardStatistics(BaseModel):
institution_id: str
organization_name: str
@@ -1,3 +1,5 @@
import asyncio
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.projects import service as projects_service
from inse.projects.model import EuCordisProjectType
@@ -10,21 +12,53 @@ from .common import (
from .model import DashboardStatisticValue
def _institution_ids(value: str | list[str]) -> list[str]:
return value if isinstance(value, list) else [value]
def _scope_id(institution_ids: list[str]) -> str:
return (
_normalize_institution_id(institution_ids[0])
if len(institution_ids) == 1
else "all"
)
async def _institution_aliases(institution_ids: list[str]) -> list[str]:
client = InstitutionsSearchClient()
aliases = await asyncio.gather(
*(
client.get_institution_aliases_by_oa_institution_id(
_raw_institution_id(institution_id)
)
for institution_id in institution_ids
)
)
return list(dict.fromkeys(alias for group in aliases for alias in group))
async def get_dashboard_eu_projects(
institution_id: str,
institution_id: str | list[str],
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
institution_ids = _institution_ids(institution_id)
period = _dashboard_period(from_year, to_year)
multiple_institutions = len(institution_ids) > 1
projects = await projects_service.search_eu_cordis_projects(
institutions_search_client=InstitutionsSearchClient(),
raw_oa_institution_id=_raw_institution_id(normalized_id),
raw_oa_institution_id=(
None if multiple_institutions else _raw_institution_id(institution_ids[0])
),
author_id=None,
author_ids=None,
organization_ids=None,
organization_names=None,
organization_names=(
await _institution_aliases(institution_ids)
if multiple_institutions
else None
),
project_types=list(EuCordisProjectType),
keywords=None,
topic_ids=None,
@@ -45,24 +79,27 @@ async def get_dashboard_eu_projects(
fuzzy=False,
)
return DashboardStatisticValue(
institution_id=normalized_id,
institution_id=_scope_id(institution_ids),
organization_name=organization_name,
value=projects.total,
)
async def get_dashboard_bmbf_projects(
institution_id: str,
institution_id: str | list[str],
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
institution_ids = _institution_ids(institution_id)
period = _dashboard_period(from_year, to_year)
multiple_institutions = len(institution_ids) > 1
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),
raw_oa_institution_id=(
None if multiple_institutions else _raw_institution_id(institution_ids[0])
),
title=None,
keywords=None,
funding_arts=None,
@@ -78,25 +115,33 @@ async def get_dashboard_bmbf_projects(
sort_by="id",
sort_direction="asc",
fuzzy=False,
oa_institution_aliases=(
await _institution_aliases(institution_ids)
if multiple_institutions
else None
),
)
return DashboardStatisticValue(
institution_id=normalized_id,
institution_id=_scope_id(institution_ids),
organization_name=organization_name,
value=projects.total,
)
async def get_dashboard_dfg_projects(
institution_id: str,
institution_id: str | list[str],
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
institution_ids = _institution_ids(institution_id)
period = _dashboard_period(from_year, to_year)
multiple_institutions = len(institution_ids) > 1
projects = await projects_service.get_dfg_projects(
institutions_search_client=InstitutionsSearchClient(),
raw_oa_institution_id=_raw_institution_id(normalized_id),
raw_oa_institution_id=(
None if multiple_institutions else _raw_institution_id(institution_ids[0])
),
author_id=None,
author_filter_ids=None,
institution_ids=None,
@@ -114,9 +159,14 @@ async def get_dashboard_dfg_projects(
sort_direction="asc",
fuzzy=False,
skip_enrichment=True,
institution_aliases=(
await _institution_aliases(institution_ids)
if multiple_institutions
else None
),
)
return DashboardStatisticValue(
institution_id=normalized_id,
institution_id=_scope_id(institution_ids),
organization_name=organization_name,
value=projects.total,
)
@@ -25,6 +25,7 @@ from .project_statistics_service import (
get_dashboard_dfg_projects,
get_dashboard_eu_projects,
)
from .project_ids_service import _get_dfg_project_ids_from_projects_service
def _status_count(aggregations: dict[str, Any], status_name: str) -> int:
@@ -77,13 +78,22 @@ async def get_dashboard_eu_project_statuses(
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 total == 0:
return EuProjectStatusStatistics(
institution_id=normalized_id,
organization_name=organization_name,
ongoing=0,
upcoming=0,
completed=0,
)
aliases = await _institution_aliases(normalized_id, organization_name)
project_ids = await _eu_project_ids_for_aliases(aliases)
if not project_ids:
return EuProjectStatusStatistics(
institution_id=normalized_id,
@@ -152,6 +162,20 @@ async def get_dashboard_bmbf_project_statuses(
to_year: int | None = None,
) -> BmbfProjectStatusStatistics:
normalized_id = _normalize_institution_id(institution_id)
total = (
await get_dashboard_bmbf_projects(
normalized_id, organization_name, from_year=from_year, to_year=to_year
)
).value
if total == 0:
return BmbfProjectStatusStatistics(
institution_id=normalized_id,
organization_name=organization_name,
ongoing=0,
upcoming=0,
completed=0,
)
aliases = await _institution_aliases(normalized_id, organization_name)
period = _dashboard_period(from_year, to_year)
filters = [_alias_match_query("Zuwendungsempfänger", aliases)]
@@ -171,11 +195,6 @@ async def get_dashboard_bmbf_project_statuses(
cluster=ESCluster.INSE,
)
aggregations = response.get("aggregations", {})
total = (
await get_dashboard_bmbf_projects(
normalized_id, organization_name, from_year=from_year, to_year=to_year
)
).value
ongoing, upcoming, completed = reconcile_status_counts(
total,
int(aggregations.get("ongoing", {}).get("doc_count", 0)),
@@ -199,12 +218,25 @@ async def get_dashboard_dfg_project_statuses(
) -> 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 total == 0:
return DfgProjectStatusStatistics(
institution_id=normalized_id,
organization_name=organization_name,
ongoing=0,
upcoming=0,
completed=0,
)
project_ids = await _get_dfg_project_ids_from_projects_service(
normalized_id,
from_year=from_year,
to_year=to_year,
)
if not project_ids:
return DfgProjectStatusStatistics(
institution_id=normalized_id,
+143 -28
View File
@@ -11,6 +11,7 @@ from inse.tags import Tags
from .model import (
BmbfProjectStatusStatistics,
BundProjectTopics,
DashboardInstitution,
DashboardStatistics,
DashboardStatisticValue,
DfgProjectStatusStatistics,
@@ -23,10 +24,13 @@ from .model import (
TopicWordCloud,
)
from .service import (
get_dashboard_analytical_institution,
get_dashboard_institutions,
get_dashboard_organization,
get_dashboard_patents,
get_dashboard_persons,
get_dashboard_publications,
get_dashboard_statistic_institution_ids,
get_dashboard_statistics,
get_topic_heatmap,
get_topic_word_cloud,
@@ -56,6 +60,19 @@ from .top_authors_service import (
router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD])
@router.get(
"/institutions",
operation_id="getDashboardInstitutions",
response_model=list[DashboardInstitution],
)
async def dashboard_institutions(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[DashboardInstitution]:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_institutions(session, organization)
@router.get(
"/statistics",
operation_id="getDashboardStatistics",
@@ -78,14 +95,18 @@ async def dashboard_statistics(
response_model=DashboardStatisticValue,
)
async def dashboard_publications(
institution_id: str | None = Query(default=None),
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,
) -> DashboardStatisticValue:
organization = get_dashboard_organization(session, access_token)
institution_ids = await get_dashboard_statistic_institution_ids(
session, organization, institution_id
)
return await get_dashboard_publications(
organization.openalex_institution_id,
institution_ids,
organization.name,
from_year=from_year,
to_year=to_year,
@@ -98,14 +119,18 @@ async def dashboard_publications(
response_model=DashboardStatisticValue,
)
async def dashboard_persons(
institution_id: str | None = Query(default=None),
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,
) -> DashboardStatisticValue:
organization = get_dashboard_organization(session, access_token)
institution_ids = await get_dashboard_statistic_institution_ids(
session, organization, institution_id
)
return await get_dashboard_persons(
organization.openalex_institution_id,
institution_ids,
organization.name,
from_year=from_year,
to_year=to_year,
@@ -118,14 +143,18 @@ async def dashboard_persons(
response_model=DashboardStatisticValue,
)
async def dashboard_patents(
institution_id: str | None = Query(default=None),
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,
) -> DashboardStatisticValue:
organization = get_dashboard_organization(session, access_token)
institution_ids = await get_dashboard_statistic_institution_ids(
session, organization, institution_id
)
return await get_dashboard_patents(
organization.openalex_institution_id,
institution_ids,
organization.name,
from_year=from_year,
to_year=to_year,
@@ -138,14 +167,18 @@ async def dashboard_patents(
response_model=DashboardStatisticValue,
)
async def dashboard_eu_projects(
institution_id: str | None = Query(default=None),
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,
) -> DashboardStatisticValue:
organization = get_dashboard_organization(session, access_token)
institution_ids = await get_dashboard_statistic_institution_ids(
session, organization, institution_id
)
return await get_dashboard_eu_projects(
organization.openalex_institution_id,
institution_ids,
organization.name,
from_year=from_year,
to_year=to_year,
@@ -158,15 +191,21 @@ async def dashboard_eu_projects(
response_model=EuProjectStatusStatistics,
)
async def dashboard_eu_project_statuses(
institution_id: str | None = Query(default=None),
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,
) -> EuProjectStatusStatistics:
organization = get_dashboard_organization(session, access_token)
selected_institution_id, selected_institution_name = (
await get_dashboard_analytical_institution(
session, organization, institution_id
)
)
return await get_dashboard_eu_project_statuses(
organization.openalex_institution_id,
organization.name,
selected_institution_id,
selected_institution_name,
from_year=from_year,
to_year=to_year,
)
@@ -178,14 +217,18 @@ async def dashboard_eu_project_statuses(
response_model=DashboardStatisticValue,
)
async def dashboard_bmbf_projects(
institution_id: str | None = Query(default=None),
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,
) -> DashboardStatisticValue:
organization = get_dashboard_organization(session, access_token)
institution_ids = await get_dashboard_statistic_institution_ids(
session, organization, institution_id
)
return await get_dashboard_bmbf_projects(
organization.openalex_institution_id,
institution_ids,
organization.name,
from_year=from_year,
to_year=to_year,
@@ -198,15 +241,21 @@ async def dashboard_bmbf_projects(
response_model=BmbfProjectStatusStatistics,
)
async def dashboard_bmbf_project_statuses(
institution_id: str | None = Query(default=None),
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,
) -> BmbfProjectStatusStatistics:
organization = get_dashboard_organization(session, access_token)
selected_institution_id, selected_institution_name = (
await get_dashboard_analytical_institution(
session, organization, institution_id
)
)
return await get_dashboard_bmbf_project_statuses(
organization.openalex_institution_id,
organization.name,
selected_institution_id,
selected_institution_name,
from_year=from_year,
to_year=to_year,
)
@@ -218,14 +267,18 @@ async def dashboard_bmbf_project_statuses(
response_model=DashboardStatisticValue,
)
async def dashboard_dfg_projects(
institution_id: str | None = Query(default=None),
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,
) -> DashboardStatisticValue:
organization = get_dashboard_organization(session, access_token)
institution_ids = await get_dashboard_statistic_institution_ids(
session, organization, institution_id
)
return await get_dashboard_dfg_projects(
organization.openalex_institution_id,
institution_ids,
organization.name,
from_year=from_year,
to_year=to_year,
@@ -238,15 +291,21 @@ async def dashboard_dfg_projects(
response_model=DfgProjectStatusStatistics,
)
async def dashboard_dfg_project_statuses(
institution_id: str | None = Query(default=None),
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DfgProjectStatusStatistics:
organization = get_dashboard_organization(session, access_token)
selected_institution_id, selected_institution_name = (
await get_dashboard_analytical_institution(
session, organization, institution_id
)
)
return await get_dashboard_dfg_project_statuses(
organization.openalex_institution_id,
organization.name,
selected_institution_id,
selected_institution_name,
from_year=from_year,
to_year=to_year,
)
@@ -258,15 +317,21 @@ async def dashboard_dfg_project_statuses(
response_model=DfgProjectTopics,
)
async def dashboard_dfg_project_topics(
institution_id: str | None = Query(default=None),
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,
) -> DfgProjectTopics:
organization = get_dashboard_organization(session, access_token)
selected_institution_id, selected_institution_name = (
await get_dashboard_analytical_institution(
session, organization, institution_id
)
)
return await get_dashboard_dfg_topics(
organization.openalex_institution_id,
organization.name,
selected_institution_id,
selected_institution_name,
from_year=from_year,
to_year=to_year,
)
@@ -278,15 +343,21 @@ async def dashboard_dfg_project_topics(
response_model=EuProjectTopics,
)
async def dashboard_eu_project_topics(
institution_id: str | None = Query(default=None),
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)
selected_institution_id, selected_institution_name = (
await get_dashboard_analytical_institution(
session, organization, institution_id
)
)
return await get_dashboard_eu_topics(
organization.openalex_institution_id,
organization.name,
selected_institution_id,
selected_institution_name,
from_year=from_year,
to_year=to_year,
)
@@ -298,15 +369,21 @@ async def dashboard_eu_project_topics(
response_model=BundProjectTopics,
)
async def dashboard_bund_project_topics(
institution_id: str | None = Query(default=None),
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)
selected_institution_id, selected_institution_name = (
await get_dashboard_analytical_institution(
session, organization, institution_id
)
)
return await get_dashboard_bund_topics(
organization.openalex_institution_id,
organization.name,
selected_institution_id,
selected_institution_name,
from_year=from_year,
to_year=to_year,
)
@@ -322,15 +399,21 @@ async def dashboard_top_authors(
default="all_time",
pattern="^(all_time|last_5_years)$",
),
institution_id: str | None = Query(default=None),
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,
) -> TopAuthorStatistics:
organization = get_dashboard_organization(session, access_token)
selected_institution_id, selected_institution_name = (
await get_dashboard_analytical_institution(
session, organization, institution_id
)
)
return await get_top_authors(
organization.openalex_institution_id,
organization.name,
selected_institution_id,
selected_institution_name,
works_period=works_period,
from_year=from_year,
to_year=to_year,
@@ -346,14 +429,18 @@ async def dashboard_top_work_authors(
works_period: Literal["all_time", "last_5_years"] = Query(
default="all_time", pattern="^(all_time|last_5_years)$"
),
institution_id: str | None = Query(default=None),
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)
selected_institution_id, _ = await get_dashboard_analytical_institution(
session, organization, institution_id
)
return await get_top_work_authors(
organization.openalex_institution_id, works_period, from_year, to_year
selected_institution_id, works_period, from_year, to_year
)
@@ -363,14 +450,20 @@ async def dashboard_top_work_authors(
response_model=TopAuthorAnalysis,
)
async def dashboard_top_project_authors(
institution_id: str | None = Query(default=None),
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)
selected_institution_id, selected_institution_name = (
await get_dashboard_analytical_institution(
session, organization, institution_id
)
)
return await get_top_project_authors(
organization.openalex_institution_id, organization.name, from_year, to_year
selected_institution_id, selected_institution_name, from_year, to_year
)
@@ -380,14 +473,18 @@ async def dashboard_top_project_authors(
response_model=TopAuthorAnalysis,
)
async def dashboard_top_eu_project_authors(
institution_id: str | None = Query(default=None),
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)
selected_institution_id, _ = await get_dashboard_analytical_institution(
session, organization, institution_id
)
return await get_top_eu_project_authors(
organization.openalex_institution_id, from_year, to_year
selected_institution_id, from_year, to_year
)
@@ -397,14 +494,18 @@ async def dashboard_top_eu_project_authors(
response_model=TopAuthorAnalysis,
)
async def dashboard_top_patent_authors(
institution_id: str | None = Query(default=None),
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)
selected_institution_id, _ = await get_dashboard_analytical_institution(
session, organization, institution_id
)
return await get_top_patent_authors(
organization.openalex_institution_id, from_year, to_year
selected_institution_id, from_year, to_year
)
@@ -414,14 +515,18 @@ async def dashboard_top_patent_authors(
response_model=TopAuthorAnalysis,
)
async def dashboard_top_news_authors(
institution_id: str | None = Query(default=None),
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)
selected_institution_id, _ = await get_dashboard_analytical_institution(
session, organization, institution_id
)
return await get_top_news_authors(
organization.openalex_institution_id, from_year, to_year
selected_institution_id, from_year, to_year
)
@@ -431,6 +536,7 @@ async def dashboard_top_news_authors(
response_model=TopicHeatmap,
)
async def dashboard_topic_heatmap(
institution_id: str | None = Query(default=None),
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
limit: int = Query(default=25, ge=1, le=50),
@@ -438,9 +544,14 @@ async def dashboard_topic_heatmap(
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> TopicHeatmap:
organization = get_dashboard_organization(session, access_token)
selected_institution_id, selected_institution_name = (
await get_dashboard_analytical_institution(
session, organization, institution_id
)
)
return await get_topic_heatmap(
institution_id=organization.openalex_institution_id,
organization_name=organization.name,
institution_id=selected_institution_id,
organization_name=selected_institution_name,
from_year=from_year,
to_year=to_year,
limit=limit,
@@ -454,6 +565,7 @@ async def dashboard_topic_heatmap(
)
async def dashboard_topic_word_cloud(
topic_id: str = Query(alias="topicId", min_length=1),
institution_id: str | None = Query(default=None),
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
limit: int = Query(default=30, ge=1, le=100),
@@ -461,8 +573,11 @@ async def dashboard_topic_word_cloud(
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> TopicWordCloud:
organization = get_dashboard_organization(session, access_token)
selected_institution_id, _ = await get_dashboard_analytical_institution(
session, organization, institution_id
)
return await get_topic_word_cloud(
institution_id=organization.openalex_institution_id,
institution_id=selected_institution_id,
topic_id=topic_id,
from_year=from_year,
to_year=to_year,
+148 -27
View File
@@ -3,13 +3,17 @@ import logging
from typing import Any
from fastapi import HTTPException, status
from sqlmodel import Session
from sqlmodel import Session, select
from inse import config
from inse.auth.model import AccessToken, Organization
from inse.auth.model import AccessToken, Organization, OrganizationInstitution
from inse.authors.institution_membership_query import (
build_institution_membership_query,
)
from inse.institutions.v2 import service as institutions_v2_service
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.organization_management import service as organization_management_service
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
from inse.persons import service as persons_service
from inse.works.v2 import service as works_v2_service
@@ -22,6 +26,7 @@ from .common import (
raw_institution_id as _raw_institution_id,
)
from .model import (
DashboardInstitution,
DashboardStatistics,
DashboardStatisticValue,
TopicHeatmap,
@@ -45,6 +50,92 @@ TOPIC_WORD_CLOUD_LIMIT = 30
logger = logging.getLogger(__name__)
async def get_dashboard_institutions(
session: Session,
organization: Organization,
) -> list[DashboardInstitution]:
rows = session.exec(
select(OrganizationInstitution)
.where(OrganizationInstitution.organization_id == organization.id)
.order_by(OrganizationInstitution.position)
).all()
institution_ids = [row.openalex_institution_id for row in rows]
if not institution_ids and organization.openalex_institution_id:
institution_ids = [_raw_institution_id(organization.openalex_institution_id)]
if not institution_ids:
return []
association_groups = (
await organization_management_service.resolve_institution_associations(
institution_ids
)
)
institutions: dict[str, DashboardInstitution] = {}
for group in association_groups:
root_id = _raw_institution_id(group.id)
institutions[root_id] = DashboardInstitution(
id=root_id,
display_name=group.display_name,
)
for association in group.associated_institutions:
association_id = _raw_institution_id(association.id)
institutions.setdefault(
association_id,
DashboardInstitution(
id=association_id,
display_name=association.display_name,
),
)
return list(institutions.values())
async def get_dashboard_statistic_institution_ids(
session: Session,
organization: Organization,
selected_institution_id: str | None,
) -> list[str]:
institutions = await get_dashboard_institutions(session, organization)
institution_ids = [institution.id for institution in institutions]
if selected_institution_id in (None, "all"):
return institution_ids
selected_id = _raw_institution_id(selected_institution_id)
if selected_id not in institution_ids:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Institution is not associated with this organization.",
)
return [selected_id]
async def get_dashboard_analytical_institution(
session: Session,
organization: Organization,
selected_institution_id: str | None,
) -> tuple[str, str]:
if selected_institution_id in (None, "all"):
return organization.openalex_institution_id, organization.name
selected_id = _raw_institution_id(selected_institution_id)
institutions = await get_dashboard_institutions(session, organization)
for institution in institutions:
if institution.id == selected_id:
return selected_id, institution.display_name
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Institution is not associated with this organization.",
)
def _statistic_scope_id(institution_ids: list[str]) -> str:
return (
_normalize_institution_id(institution_ids[0])
if len(institution_ids) == 1
else "all"
)
def _publication_year_filter(period: DashboardPeriod) -> dict[str, Any] | None:
from_year, to_year = period
year_range: dict[str, int] = {}
@@ -104,12 +195,15 @@ async def get_dashboard_statistics(
async def get_dashboard_publications(
institution_id: str,
institution_id: str | list[str],
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
institution_ids = (
institution_id if isinstance(institution_id, list) else [institution_id]
)
normalized_ids = [_normalize_institution_id(value) for value in institution_ids]
period = _dashboard_period(from_year, to_year)
publication_years: list[int] = []
if period != (None, None):
@@ -120,67 +214,94 @@ async def get_dashboard_publications(
works = await works_v2_service.get_works(
page=0,
size=1,
institution_ids=[normalized_id],
institution_ids=normalized_ids,
publication_years=publication_years,
)
return DashboardStatisticValue(
institution_id=normalized_id,
institution_id=_statistic_scope_id(institution_ids),
organization_name=organization_name,
value=works.total,
)
async def get_dashboard_persons(
institution_id: str,
institution_id: str | list[str],
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
institution_ids = institution_id if isinstance(institution_id, list) else [institution_id]
normalized_ids = [_normalize_institution_id(value) for value in institution_ids]
period = _dashboard_period(from_year, to_year)
if (period[0] is None) != (period[1] is None):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="from_year and to_year must either both be provided or both omitted.",
)
persons = await persons_service.search_persons_list(
query=None,
institution_id=normalized_id,
sort_by=None,
sort_order=None,
topic=None,
page=1,
page_size=1,
include="",
year_filter_enabled=period[0] is not None,
filter_mode="between" if period[0] is not None else None,
filter_year=period[0],
filter_year_to=period[1],
if len(normalized_ids) == 1:
persons = await persons_service.search_persons_list(
query=None,
institution_id=normalized_ids[0],
sort_by=None,
sort_order=None,
topic=None,
page=1,
page_size=1,
include="",
year_filter_enabled=period[0] is not None,
filter_mode="between" if period[0] is not None else None,
filter_year=period[0],
filter_year_to=period[1],
)
return DashboardStatisticValue(
institution_id=normalized_ids[0],
organization_name=organization_name,
value=int(persons.meta.count or 0) if persons.meta else 0,
)
membership_queries = [
build_institution_membership_query(
institution_id=value,
year_mode="between" if period[0] is not None else "all",
year=period[0],
year_to=period[1],
)
for value in normalized_ids
]
value = await elasticsearch.count(
index="openalex-authors",
query={
"bool": {
"should": membership_queries,
"minimum_should_match": 1,
}
},
)
return DashboardStatisticValue(
institution_id=normalized_id,
institution_id=_statistic_scope_id(institution_ids),
organization_name=organization_name,
value=int(persons.meta.count or 0) if persons.meta else 0,
value=value,
)
async def get_dashboard_patents(
institution_id: str,
institution_id: str | list[str],
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
institution_ids = institution_id if isinstance(institution_id, list) else [institution_id]
normalized_ids = [_normalize_institution_id(value) for value in institution_ids]
period = _dashboard_period(from_year, to_year)
_, total = await OrgPatentsSearchClient().search_by_institution(
normalized_id,
normalized_ids,
page=0,
size=0,
from_year=period[0],
to_year=period[1],
)
return DashboardStatisticValue(
institution_id=normalized_id,
institution_id=_statistic_scope_id(institution_ids),
organization_name=organization_name,
value=total,
)
+270 -5
View File
@@ -8,8 +8,15 @@ from fastapi import HTTPException
from sqlmodel import Session, SQLModel, create_engine
from inse import config
from inse.auth.model import AccessToken, Organization, UserRole
from inse.auth.model import (
AccessToken,
Organization,
OrganizationInstitution,
UserRole,
)
from inse.dashboard.service import (
get_dashboard_analytical_institution,
get_dashboard_institutions,
get_dashboard_organization,
get_dashboard_persons,
get_dashboard_publications,
@@ -22,8 +29,13 @@ from inse.dashboard.common import (
)
from inse.dashboard.bund_topics_service import get_dashboard_bund_topics
from inse.dashboard.eu_topics_service import get_dashboard_eu_topics
from inse.dashboard.model import TopAuthor
from inse.dashboard.project_status_service import reconcile_status_counts
from inse.dashboard.model import DashboardStatisticValue, TopAuthor
from inse.dashboard.project_status_service import (
get_dashboard_bmbf_project_statuses,
get_dashboard_dfg_project_statuses,
get_dashboard_eu_project_statuses,
reconcile_status_counts,
)
from inse.dashboard.project_ids_service import (
_get_dfg_project_ids_from_projects_service,
)
@@ -42,6 +54,10 @@ from inse.exceptions import ElasticsearchException
from inse.model import ESIndex
from inse.models.openalex.institution import Institution
from inse.models.openalex.meta import Meta
from inse.organization_management.model import (
InstitutionAssociation,
InstitutionAssociationsResponse,
)
from inse.persons.model import CustomAuthorsListResponse
from inse.projects.model import (
BundProjectPage,
@@ -116,6 +132,100 @@ def test_project_status_counts_match_authoritative_total():
assert reconcile_status_counts(7, 4, 2, 3) == (2, 2, 3)
@pytest.mark.anyio
@pytest.mark.parametrize(
("status_loader", "count_loader", "extra_dependency"),
[
(
get_dashboard_eu_project_statuses,
"get_dashboard_eu_projects",
"_institution_aliases",
),
(
get_dashboard_bmbf_project_statuses,
"get_dashboard_bmbf_projects",
"_institution_aliases",
),
(
get_dashboard_dfg_project_statuses,
"get_dashboard_dfg_projects",
"_get_dfg_project_ids_from_projects_service",
),
],
)
async def test_project_status_zero_count_is_not_an_error(
status_loader, count_loader, extra_dependency
):
zero_count = DashboardStatisticValue(
institution_id=ORG_INSTITUTION_ID,
organization_name="Example University",
value=0,
)
with (
patch(
f"inse.dashboard.project_status_service.{count_loader}",
new=AsyncMock(return_value=zero_count),
),
patch(
f"inse.dashboard.project_status_service.{extra_dependency}",
new=AsyncMock(side_effect=AssertionError("must not be called")),
),
):
result = await status_loader(ORG_INSTITUTION_ID, "Example University")
assert result.ongoing == 0
assert result.upcoming == 0
assert result.completed == 0
@pytest.mark.anyio
async def test_dfg_project_status_uses_card_project_ids_and_total():
card_total = DashboardStatisticValue(
institution_id=ORG_INSTITUTION_ID,
organization_name="University Hospital Essen",
value=24,
)
status_aggregations = {
"aggregations": {
"projects_nested": {
"selected_projects": {
"ongoing": {"projects": {"value": 7}},
"completed": {"projects": {"value": 17}},
}
}
}
}
with (
patch(
"inse.dashboard.project_status_service.get_dashboard_dfg_projects",
new=AsyncMock(return_value=card_total),
),
patch(
"inse.dashboard.project_status_service._get_dfg_project_ids_from_projects_service",
new=AsyncMock(
return_value=[str(project_id) for project_id in range(1, 25)]
),
) as project_ids_loader,
patch(
"inse.dashboard.project_status_service.elasticsearch.search",
new=AsyncMock(return_value=status_aggregations),
),
):
result = await get_dashboard_dfg_project_statuses(
ORG_INSTITUTION_ID,
"University Hospital Essen",
)
project_ids_loader.assert_awaited_once_with(
ORG_INSTITUTION_ID,
from_year=None,
to_year=None,
)
assert result.ongoing == 7
assert result.completed == 17
assert result.ongoing + result.upcoming + result.completed == 24
def test_project_status_period_uses_interval_overlap():
assert _project_boundary_year_filter(
"startDate", "endDate", (2022, 2026), "iso"
@@ -971,11 +1081,11 @@ def test_eu_author_count_groups_multiple_publications_by_project_id():
works_response,
doi_project_ids,
ORG_INSTITUTION_ID,
{"https://openalex.org/A5007170803"},
)
assert [author.model_dump() for author in result] == [
{"id": "A5007170803", "name": "Marcus Example", "count": 1}
{"id": "A999", "name": "External Example", "count": 1},
{"id": "A5007170803", "name": "Marcus Example", "count": 1},
]
@@ -1618,6 +1728,161 @@ def test_get_dashboard_organization_uses_effective_organization():
assert result.openalex_institution_id == "I456"
@pytest.mark.anyio
async def test_dashboard_institutions_include_openalex_associations():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
organization = Organization(
name="Example University",
openalex_institution_id="I123",
)
session.add(organization)
session.commit()
session.refresh(organization)
session.add(
OrganizationInstitution(
organization_id=organization.id,
openalex_institution_id="I123",
position=0,
)
)
session.commit()
associations = [
InstitutionAssociationsResponse(
id="I123",
display_name="Main institution",
associated_institutions=[
InstitutionAssociation(
id="I456",
display_name="Child institution",
relationship="child",
),
InstitutionAssociation(
id="I789",
display_name="Related institution",
relationship="related",
),
],
)
]
with patch(
"inse.dashboard.service.organization_management_service."
"resolve_institution_associations",
new=AsyncMock(return_value=associations),
):
result = await get_dashboard_institutions(session, organization)
assert [institution.model_dump() for institution in result] == [
{"id": "I123", "display_name": "Main institution"},
{"id": "I456", "display_name": "Child institution"},
{"id": "I789", "display_name": "Related institution"},
]
@pytest.mark.anyio
async def test_dashboard_analytical_institution_all_uses_root_organization():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
organization = Organization(
name="Example University",
openalex_institution_id="I123",
)
session.add(organization)
session.commit()
session.refresh(organization)
result = await get_dashboard_analytical_institution(
session,
organization,
"all",
)
assert result == ("I123", "Example University")
@pytest.mark.anyio
async def test_dashboard_analytical_institution_uses_selected_tab_institution():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
organization = Organization(
name="Example University",
openalex_institution_id="I123",
)
session.add(organization)
session.commit()
session.refresh(organization)
session.add(
OrganizationInstitution(
organization_id=organization.id,
openalex_institution_id="I123",
position=0,
)
)
session.commit()
associations = [
InstitutionAssociationsResponse(
id="I123",
display_name="Main institution",
associated_institutions=[
InstitutionAssociation(
id="I456",
display_name="Child institution",
relationship="child",
),
],
)
]
with patch(
"inse.dashboard.service.organization_management_service."
"resolve_institution_associations",
new=AsyncMock(return_value=associations),
):
result = await get_dashboard_analytical_institution(
session,
organization,
"https://openalex.org/I456",
)
assert result == ("I456", "Child institution")
@pytest.mark.anyio
async def test_dashboard_analytical_institution_rejects_unassociated_selection():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
organization = Organization(
name="Example University",
openalex_institution_id="I123",
)
session.add(organization)
session.commit()
session.refresh(organization)
with patch(
"inse.dashboard.service.organization_management_service."
"resolve_institution_associations",
new=AsyncMock(return_value=[]),
):
with pytest.raises(HTTPException) as exc_info:
await get_dashboard_analytical_institution(
session,
organization,
"I999",
)
assert exc_info.value.status_code == 422
def test_get_dashboard_organization_rejects_missing_openalex_id():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)
@@ -79,7 +79,6 @@ async def get_top_authors(
"eu_projects",
_top_eu_project_publication_authors(
normalized_id,
authors,
from_year=period[0],
to_year=period[1],
),
@@ -152,12 +151,10 @@ async def get_top_eu_project_authors(
) -> TopAuthorAnalysis:
normalized_id = _normalize_institution_id(institution_id)
period = _period(from_year=from_year, to_year=to_year)
authors = await _safe_institution_authors(normalized_id)
return TopAuthorAnalysis(
institution_id=normalized_id,
authors=await _top_eu_project_publication_authors(
normalized_id,
authors,
from_year=period[0],
to_year=period[1],
),
@@ -825,18 +822,9 @@ async def _top_patent_authors(
async def _top_eu_project_publication_authors(
institution_id: str,
institution_authors: list[dict[str, Any]],
from_year: int | None = None,
to_year: int | None = None,
) -> list[TopAuthor]:
institution_author_ids = {
author_id
for author in institution_authors
if (author_id := _normalize_author_id(author.get("id")))
}
if not institution_author_ids:
return []
# Candidate discovery is deliberately all-time. The selected period is
# applied to each person's authoritative project count below. Otherwise a
# person can disappear merely because their recent projects have no linked
@@ -889,7 +877,6 @@ async def _top_eu_project_publication_authors(
works_response,
doi_project_ids,
institution_id,
institution_author_ids,
limit=None,
)
ranked = await _count_eu_projects_for_candidates(
@@ -976,7 +963,6 @@ def _openalex_work_authors_by_eu_projects(
response: dict[str, Any],
doi_project_ids: dict[str, set[str]],
institution_id: str,
institution_author_ids: set[str],
limit: int | None = TOP_AUTHOR_LIMIT,
) -> list[TopAuthor]:
# Count unique CORDIS projects per author, not publications. Multiple works
@@ -999,11 +985,7 @@ def _openalex_work_authors_by_eu_projects(
author = authorship.get("author") or {}
author_id = _normalize_author_id(author.get("id"))
author_name = str(author.get("display_name") or "").strip()
if (
not author_id
or author_id not in institution_author_ids
or not author_name
):
if not author_id or not author_name:
continue
author_project_ids[author_id].update(project_ids)
author_names.setdefault(author_id, author_name)
@@ -29,12 +29,17 @@ async def get_institution_by_id(
raw_oa_institution_id=institution_id,
source=[
"id",
"ror",
"display_name",
"country_code",
"type",
"homepage_url",
"display_name_alternatives",
"works_count",
"cited_by_count",
"geo",
"summary_stats",
"associated_institutions",
],
)
@@ -43,6 +43,8 @@ async def call(
)
except APIConnectionError:
return "Etwas ist schiefgelaufen. Bitte versuche es später erneut."
finally:
await client.close()
return response.choices[0].message.content or (
"Etwas ist schiefgelaufen. Bitte versuche es erneut."
@@ -126,5 +128,7 @@ async def call_stream(
print(f"LLM streaming failed: {type(e).__name__}: {e}")
traceback.print_exc()
return ""
finally:
await client.close()
return full_content
-193
View File
@@ -1,193 +0,0 @@
"""
This module defines the business logic for our
web service.
"""
import json
import logging
from inse.integrations import elasticsearch
from inse.models.openalex.topic import Topic
from inse.models.openalex.topic_domain import TopicDomain
from inse.models.openalex.topic_field import TopicField
from inse.models.openalex.topic_subfield import TopicSubfield
logger = logging.getLogger(__name__)
topic_cache_filename: str = "topic_hierarchy_cache.json"
def _load_topic_cache() -> dict:
"""Loads the topic hierarchy cache from a JSON file."""
import os
try:
cache_path = "/data/" + topic_cache_filename
if not os.path.exists(cache_path):
current_dir = os.path.dirname(__file__)
cache_path = os.path.join(current_dir, "..", "data", topic_cache_filename)
with open(cache_path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as exc:
logger.warning("Failed to load topic hierarchy cache: %s", exc)
return {}
async def build_topic_cache(save_json: bool = True) -> dict:
"""
Fetch topics from the hosted OpenAlex topics index and build a lookup cache (scheduled task).
Arguments:
save_json (bool): Whether to save the cache as a JSON file (default: True)
Returns:
taxonomy_cache (dict): The topic hierarchy dictionary.
"""
output_filename: str = "topic_hierarchy_cache.json"
taxonomy_cache = {}
try:
async for hit in elasticsearch.scan(
index="openalex-topics",
query={"match_all": {}},
source=["display_name", "name", "id", "subfield", "field", "domain"],
cluster="nes",
):
source = hit.get("_source", {})
topic_name = source.get("display_name") or source.get("name")
if not topic_name:
continue
taxonomy_cache[topic_name] = {
"topic_id": source.get("id") or hit.get("_id", ""),
"subfield": source.get("subfield", {}).get("display_name", ""),
"field": source.get("field", {}).get("display_name", ""),
"domain": source.get("domain", {}).get("display_name", ""),
}
except Exception as exc:
logger.error("Failed to scan topics from Elasticsearch: %s", exc)
logger.info("Processed %s topics total", len(taxonomy_cache))
if save_json:
data_json = json.dumps(taxonomy_cache, indent=2, ensure_ascii=True)
try:
output_path = "/data/" + output_filename
with open(output_path, "w", encoding="utf-8") as f:
f.write(data_json)
logger.info("Topic hierarchy cache written to %s", output_path)
except Exception as exc:
logger.warning("Failed to write topic hierarchy cache: %s", exc)
return taxonomy_cache
def get_topics_from_cache(topic_names: list[str]) -> list[Topic]:
"""
Given a list of topic names, retrieves their hierarchy information from the cache and returns a list of Topic models.
Arguments:
topic_names (List[str]): A list of topic names to retrieve.
Returns:
List[Topic]: A list of Topic models.
"""
cache = _load_topic_cache()
topics = []
for name in topic_names:
data = cache.get(name)
if not data:
continue
subfield_name = data.get("subfield", "")
field_name = data.get("field", "")
domain_name = data.get("domain", "")
topics.append(
Topic(
id=data.get("topic_id", ""),
display_name=name,
works_count=data.get("count", 1),
subfield=TopicSubfield(display_name=subfield_name)
if subfield_name
else None,
field=TopicField(display_name=field_name) if field_name else None,
domain=TopicDomain(display_name=domain_name) if domain_name else None,
)
)
return topics
def count_topic_hierarchy(topic_names: list[str]) -> dict:
"""
Given a list of topic names, counts the occurrences of each topic and their hierarchy levels (subfield, field, domain) using the cache.
Arguments:
topic_names (List[str]): A list of topic names to count.
Returns:
dict: A dictionary containing the counts of each hierarchy level.
"""
cache = _load_topic_cache()
counts = {"topics": {}, "subfields": {}, "fields": {}, "domains": {}}
for name in topic_names:
data = cache.get(name)
if not data:
continue
counts["topics"][name] = counts["topics"].get(name, 0) + 1
subfield = data.get("subfield", "")
if subfield:
counts["subfields"][subfield] = counts["subfields"].get(subfield, 0) + 1
field = data.get("field", "")
if field:
counts["fields"][field] = counts["fields"].get(field, 0) + 1
domain = data.get("domain", "")
if domain:
counts["domains"][domain] = counts["domains"].get(domain, 0) + 1
return counts
def get_topic_hierarchy() -> dict:
"""
Builds and returns a hierarchical tree structure of topics:
Domains -> Fields -> Subfields -> Topics
"""
flat_cache = _load_topic_cache()
tree = {}
for topic_name, info in flat_cache.items():
domain = info.get("domain") or "Unbekannter Bereich"
field = info.get("field") or "Unbekanntes Feld"
subfield = info.get("subfield") or "Unbekanntes Teilfeld"
topic_id = info.get("topic_id", "")
# Clean topic ID to just be the trailing ID or keep full URL
# For querying, display name is used in persons search, but ID is useful
if domain not in tree:
tree[domain] = {}
if field not in tree[domain]:
tree[domain][field] = {}
if subfield not in tree[domain][field]:
tree[domain][field][subfield] = []
tree[domain][field][subfield].append({"id": topic_id, "name": topic_name})
formatted_domains = []
for d_name, d_fields in tree.items():
formatted_fields = []
for f_name, f_subfields in d_fields.items():
formatted_subfields = []
for sf_name, sf_topics in f_subfields.items():
sf_topics.sort(key=lambda x: x["name"])
formatted_subfields.append({"name": sf_name, "topics": sf_topics})
formatted_subfields.sort(key=lambda x: x["name"])
formatted_fields.append({"name": f_name, "subfields": formatted_subfields})
formatted_fields.sort(key=lambda x: x["name"])
formatted_domains.append({"name": d_name, "fields": formatted_fields})
formatted_domains.sort(key=lambda x: x["name"])
return {"domains": formatted_domains}
-3
View File
@@ -64,7 +64,6 @@ from inse.works.service import router as works_service_router
from inse.works.v2.router import router as works_v2_router
from . import config
from .service import router as service_router
logger = logging.getLogger(__name__)
@@ -119,8 +118,6 @@ app.include_router(patents_all_router)
app.include_router(keywords_service_router)
app.include_router(keywords_patents_router)
app.include_router(service_router)
app.include_router(auth_router)
app.include_router(account_management_router)
app.include_router(organization_management_router)
+2 -2
View File
@@ -108,10 +108,10 @@ class BundProject(BaseModel):
examples=["Deutschland"],
)
implementing_agency: str | None = Field(
executing_agency: str | None = Field(
default=None,
validation_alias="Ausführende Stelle",
description="The implementing agency of the project",
description="The executing agency of the project",
examples=[
"Universität Duisburg-Essen - Fachbereich Allgemeine Informatik - Lehrstuhl Networked Embedded Systems (NES)"
],
@@ -25,6 +25,7 @@ from pydantic_core import to_jsonable_python
from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.openalex.author_summary_stats import AuthorSummaryStats
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
from inse.models.openalex.institution_geo import InstitutionGeo
from inse.models.openalex.institution_ids import InstitutionIds
@@ -51,9 +52,10 @@ class Institution(BaseModel):
ids: InstitutionIds | None = None
counts_by_year: list[AuthorCountsByYearInner] | None = Field(default=None, description="`works_count` and `cited_by_count` for each of the last ten years.")
works_api_url: StrictStr | None = Field(default=None, description="A URL that will get you a list of all works affiliated with this institution.")
associated_institutions: list[DehydratedInstitution] | None = Field(default=None, description="Associated institutions list.")
created_date: date | None = Field(default=None, description="When this institution was added to OpenAlex (ISO 8601 date).")
updated_date: datetime | None = Field(default=None, description="When this institution was last updated (ISO 8601 datetime).")
__properties: ClassVar[list[str]] = ["id", "ror", "display_name", "country_code", "type", "homepage_url", "image_url", "image_thumbnail_url", "display_name_acronyms", "display_name_alternatives", "works_count", "cited_by_count", "summary_stats", "geo", "lineage", "ids", "counts_by_year", "works_api_url", "created_date", "updated_date"]
__properties: ClassVar[list[str]] = ["id", "ror", "display_name", "country_code", "type", "homepage_url", "image_url", "image_thumbnail_url", "display_name_acronyms", "display_name_alternatives", "works_count", "cited_by_count", "summary_stats", "geo", "lineage", "ids", "counts_by_year", "works_api_url", "associated_institutions", "created_date", "updated_date"]
@field_validator('type')
def type_validate_enum(cls, value):
@@ -151,6 +153,7 @@ class Institution(BaseModel):
"ids": InstitutionIds.from_dict(obj["ids"]) if obj.get("ids") is not None else None,
"counts_by_year": [AuthorCountsByYearInner.from_dict(_item) for _item in obj["counts_by_year"]] if obj.get("counts_by_year") is not None else None,
"works_api_url": obj.get("works_api_url"),
"associated_institutions": [DehydratedInstitution.from_dict(_item) for _item in obj["associated_institutions"]] if obj.get("associated_institutions") is not None else None,
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
+1
View File
@@ -874,3 +874,4 @@ async def _related_search_terms(query_text: str) -> list:
terms.append(term)
return terms
@@ -352,6 +352,12 @@ async def get_institution_associations(
institution_ids: list[str],
) -> list[InstitutionAssociationsResponse]:
_require_super_admin(access_token)
return await resolve_institution_associations(institution_ids)
async def resolve_institution_associations(
institution_ids: list[str],
) -> list[InstitutionAssociationsResponse]:
clean_ids = _normalize_institution_ids(institution_ids)
if not clean_ids:
return []
@@ -12,19 +12,89 @@ from inse.patents.common import model
from inse.patents.ipc_lookup import extract_ipc_symbol, parse_ipc_symbol
MAPPING_FILENAME = "ipc_openalex_topic_mapping.json"
TOPIC_CACHE_FILENAME = "topic_hierarchy_cache.json"
LEVELS = ("section", "class", "subclass", "group", "subgroup")
MATCH_LEVELS = ("subgroup", "group", "subclass")
@dataclass(frozen=True)
class MappedOpenAlexTopic:
topic_id: str
topic_display_name: str | None = None
subfield_id: str | None = None
field_id: str | None = None
domain_id: str | None = None
subfield_name: str | None = None
field_name: str | None = None
domain_name: str | None = None
ipc_level: str | None = None
ipc_symbol: str | None = None
# High-frequency IPC subclasses missing from the ES-built mapping file.
SUBCLASS_TOPIC_OVERRIDES: dict[str, str] = {
"A61B": "Cardiac electrophysiology and arrhythmias",
"A61K": "Pharmaceutical studies and practices",
"A61P": "Cancer Immunotherapy and Biomarkers",
"C07K": "Cancer Immunotherapy and Biomarkers",
"C12N": "Biotechnology and Related Fields",
"C12Q": "Cancer Immunotherapy and Biomarkers",
"G01N": "Analytical Methods in Pharmaceuticals",
SUBCLASS_TOPIC_OVERRIDES: dict[str, MappedOpenAlexTopic] = {
"A61B": MappedOpenAlexTopic(
topic_id="https://openalex.org/T10217",
topic_display_name="Cardiac electrophysiology and arrhythmias",
subfield_name="Cardiology and Cardiovascular Medicine",
field_name="Medicine",
domain_name="Health Sciences",
ipc_level="subclass",
ipc_symbol="A61B",
),
"A61K": MappedOpenAlexTopic(
topic_id="https://openalex.org/T12015",
topic_display_name="Pharmaceutical studies and practices",
subfield_name="Pharmacology",
field_name="Pharmacology, Toxicology and Pharmaceutics",
domain_name="Health Sciences",
ipc_level="subclass",
ipc_symbol="A61K",
),
"A61P": MappedOpenAlexTopic(
topic_id="https://openalex.org/T11537",
topic_display_name="Cancer Immunotherapy and Biomarkers",
subfield_name="Oncology",
field_name="Medicine",
domain_name="Health Sciences",
ipc_level="subclass",
ipc_symbol="A61P",
),
"C07K": MappedOpenAlexTopic(
topic_id="https://openalex.org/T11537",
topic_display_name="Cancer Immunotherapy and Biomarkers",
subfield_name="Oncology",
field_name="Medicine",
domain_name="Health Sciences",
ipc_level="subclass",
ipc_symbol="C07K",
),
"C12N": MappedOpenAlexTopic(
topic_id="https://openalex.org/T10041",
topic_display_name="Biotechnology and Related Fields",
subfield_name="Biotechnology",
field_name="Immunology and Microbiology",
domain_name="Life Sciences",
ipc_level="subclass",
ipc_symbol="C12N",
),
"C12Q": MappedOpenAlexTopic(
topic_id="https://openalex.org/T11537",
topic_display_name="Cancer Immunotherapy and Biomarkers",
subfield_name="Oncology",
field_name="Medicine",
domain_name="Health Sciences",
ipc_level="subclass",
ipc_symbol="C12Q",
),
"G01N": MappedOpenAlexTopic(
topic_id="https://openalex.org/T10487",
topic_display_name="Analytical Methods in Pharmaceuticals",
subfield_name="Analytical Chemistry",
field_name="Chemistry",
domain_name="Physical Sciences",
ipc_level="subclass",
ipc_symbol="G01N",
),
}
_TOPIC_LABEL_STOPWORDS = frozenset({
@@ -92,20 +162,6 @@ def _meaningful_topic_tokens(label: str) -> set[str]:
}
@dataclass(frozen=True)
class MappedOpenAlexTopic:
topic_id: str
topic_display_name: str | None = None
subfield_id: str | None = None
field_id: str | None = None
domain_id: str | None = None
subfield_name: str | None = None
field_name: str | None = None
domain_name: str | None = None
ipc_level: str | None = None
ipc_symbol: str | None = None
@dataclass(frozen=True)
class OpenAlexTopicRefs:
topic_ids: frozenset[str]
@@ -141,84 +197,11 @@ def _mapping_path() -> str:
return os.path.join(_data_dir(), MAPPING_FILENAME)
@lru_cache(maxsize=1)
def _load_topic_cache() -> dict[str, dict[str, str]]:
path = os.path.join(_data_dir(), TOPIC_CACHE_FILENAME)
try:
with open(path, encoding="utf-8") as handle:
raw = json.load(handle)
except (OSError, json.JSONDecodeError):
return {}
if not isinstance(raw, dict):
return {}
return {
display_name: {
"topic_id": str(info.get("topic_id", "")),
"subfield": info.get("subfield"),
"field": info.get("field"),
"domain": info.get("domain"),
}
for display_name, info in raw.items()
if isinstance(info, dict) and info.get("topic_id")
}
def _enrich_mapped_topic(mapped: MappedOpenAlexTopic) -> MappedOpenAlexTopic:
cache = _load_topic_cache()
topic_name = mapped.topic_display_name or ""
info = cache.get(topic_name)
if info is None:
for candidate in cache.values():
if candidate.get("topic_id") == mapped.topic_id:
info = candidate
break
if info is None:
return mapped
return MappedOpenAlexTopic(
topic_id=mapped.topic_id,
topic_display_name=mapped.topic_display_name or topic_name,
subfield_id=mapped.subfield_id,
field_id=mapped.field_id,
domain_id=mapped.domain_id,
subfield_name=info.get("subfield"),
field_name=info.get("field"),
domain_name=info.get("domain"),
ipc_level=mapped.ipc_level,
ipc_symbol=mapped.ipc_symbol,
)
def _mapped_from_topic_name(
topic_display_name: str,
*,
ipc_level: str,
ipc_symbol: str,
) -> MappedOpenAlexTopic | None:
cache = _load_topic_cache()
info = cache.get(topic_display_name)
if info is None:
return None
return _enrich_mapped_topic(
MappedOpenAlexTopic(
topic_id=info["topic_id"],
topic_display_name=topic_display_name,
ipc_level=ipc_level,
ipc_symbol=ipc_symbol,
)
)
def _apply_subclass_overrides(
parsed: dict[str, dict[str, MappedOpenAlexTopic]],
) -> None:
for symbol, topic_name in SUBCLASS_TOPIC_OVERRIDES.items():
mapped = _mapped_from_topic_name(
topic_name,
ipc_level="subclass",
ipc_symbol=_normalize_symbol(symbol),
)
if mapped is not None:
parsed["subclass"][_normalize_symbol(symbol)] = mapped
for symbol, mapped in SUBCLASS_TOPIC_OVERRIDES.items():
parsed["subclass"][_normalize_symbol(symbol)] = mapped
@lru_cache(maxsize=1)
@@ -239,19 +222,17 @@ def load_ipc_openalex_mapping() -> dict[str, dict[str, MappedOpenAlexTopic]]:
if not topic_id:
continue
normalized_symbol = _normalize_symbol(symbol)
mapped = _enrich_mapped_topic(
MappedOpenAlexTopic(
topic_id=str(topic_id),
topic_display_name=entry.get("topic_display_name"),
subfield_id=entry.get("subfield_id"),
field_id=entry.get("field_id"),
domain_id=entry.get("domain_id"),
subfield_name=entry.get("subfield"),
field_name=entry.get("field"),
domain_name=entry.get("domain"),
ipc_level=level,
ipc_symbol=normalized_symbol,
)
mapped = MappedOpenAlexTopic(
topic_id=str(topic_id),
topic_display_name=entry.get("topic_display_name"),
subfield_id=entry.get("subfield_id"),
field_id=entry.get("field_id"),
domain_id=entry.get("domain_id"),
subfield_name=entry.get("subfield"),
field_name=entry.get("field"),
domain_name=entry.get("domain"),
ipc_level=level,
ipc_symbol=normalized_symbol,
)
parsed[level][normalized_symbol] = mapped
_apply_subclass_overrides(parsed)
@@ -260,7 +241,6 @@ def load_ipc_openalex_mapping() -> dict[str, dict[str, MappedOpenAlexTopic]]:
def clear_mapping_cache() -> None:
load_ipc_openalex_mapping.cache_clear()
_load_topic_cache.cache_clear()
from inse.patents.patents_openalex_keywords.resolver import clear_resolver_caches
clear_resolver_caches()
@@ -9,7 +9,6 @@ from typing import Any
import httpx
from inse.patents.authors.ipc_openalex_mapping import (
_load_topic_cache,
normalize_openalex_id,
)
from inse.patents.common.elastic_search_client import MissingApiKeyError
@@ -65,17 +64,7 @@ def _topic_id_variants(topic_id: str | None) -> list[str]:
def _topic_id_variants_for_item(item: KeywordPatentSearchItem) -> list[str]:
variants = _topic_id_variants(item.topic_id)
if variants:
return variants
display_name = (item.topic_display_name or "").strip()
if display_name:
info = _load_topic_cache().get(display_name)
if info and info.get("topic_id"):
return _topic_id_variants(str(info["topic_id"]))
return []
return _topic_id_variants(item.topic_id)
def _weighted_score(
@@ -1086,19 +1086,12 @@ def test_json_lookup_resolves_topic_id_from_display_name(monkeypatch) -> None:
}
},
)
monkeypatch.setattr(
"inse.patents.keywords.reverse_lookup._load_topic_cache",
lambda: {
"Science and Climate Studies": {
"topic_id": "https://openalex.org/T14329",
}
},
)
clear_reverse_lookup_caches()
items = [
KeywordPatentSearchItem(
keyword="Science and Climate Studies",
topic_id="https://openalex.org/T14329",
topic_display_name="Science and Climate Studies",
relevance_score=1.0,
)
@@ -251,7 +251,7 @@ class OrgPatentsSearchClient:
async def search_by_institution(
self,
institution_id: str,
institution_id: str | list[str],
match_type: MatchTypeFilter = "all",
page: int = 0,
size: int = DEFAULT_PAGE_SIZE,
@@ -259,8 +259,16 @@ class OrgPatentsSearchClient:
from_year: int | None = None,
to_year: int | None = None,
) -> tuple[list[OrgPatentEntry], int]:
short_id = institution_id.replace("https://openalex.org/", "").upper()
filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}]
institution_ids = (
institution_id if isinstance(institution_id, list) else [institution_id]
)
short_ids = [
value.replace("https://openalex.org/", "").upper()
for value in institution_ids
]
filters: list[dict[str, Any]] = [
{"terms": {"institution_id": short_ids}}
]
if match_type == "institution":
filters.append({"terms": {"match_type": ["institution", "both"]}})
@@ -18,7 +18,6 @@ from inse.util import get_model
logger = logging.getLogger(__name__)
TOPIC_CACHE_FILENAME = "topic_hierarchy_cache.json"
MATCH_METHOD = "sentence_transformer"
TOPIC_VECTORS_INDEX = "topicvectors"
@@ -39,31 +38,6 @@ class KeywordCandidate:
topic_display_name: str | None = None
def _data_dir() -> Path:
return Path(__file__).resolve().parents[4] / "data"
def load_topic_cache(cache_path: Path | None = None) -> list[TopicCandidate]:
path = cache_path or (_data_dir() / TOPIC_CACHE_FILENAME)
with path.open(encoding="utf-8") as handle:
raw = json.load(handle)
topics: list[TopicCandidate] = []
for display_name, info in raw.items():
topic_id = info.get("topic_id")
if not topic_id:
continue
topics.append(
TopicCandidate(
topic_id=str(topic_id),
display_name=display_name,
subfield=info.get("subfield"),
field=info.get("field"),
domain=info.get("domain"),
)
)
return topics
def topic_embedding_text(topic: TopicCandidate) -> str:
parts = [topic.display_name]
for label in (topic.subfield, topic.field, topic.domain):
@@ -8,7 +8,6 @@ from functools import lru_cache
from inse.patents.authors.ipc_openalex_mapping import (
MappedOpenAlexTopic,
_enrich_mapped_topic,
load_ipc_openalex_mapping,
normalize_openalex_id,
resolve_mapped_topics_for_code,
@@ -91,16 +90,14 @@ def mapped_topics_from_index_doc(doc: dict) -> list[MappedOpenAlexTopic]:
continue
seen.add(key)
mapped.append(
_enrich_mapped_topic(
MappedOpenAlexTopic(
topic_id=str(topic_id),
topic_display_name=match.get("topic_display_name"),
subfield_name=match.get("subfield"),
field_name=match.get("field"),
domain_name=match.get("domain"),
ipc_level=ipc_level,
ipc_symbol=ipc_symbol,
)
MappedOpenAlexTopic(
topic_id=str(topic_id),
topic_display_name=match.get("topic_display_name"),
subfield_name=match.get("subfield"),
field_name=match.get("field"),
domain_name=match.get("domain"),
ipc_level=ipc_level,
ipc_symbol=ipc_symbol,
)
)
@@ -113,13 +110,11 @@ def mapped_topics_from_index_doc(doc: dict) -> list[MappedOpenAlexTopic]:
continue
seen.add(key)
mapped.append(
_enrich_mapped_topic(
MappedOpenAlexTopic(
topic_id=str(topic_id),
topic_display_name=match.get("topic_display_name"),
ipc_level=ipc_level,
ipc_symbol=ipc_symbol,
)
MappedOpenAlexTopic(
topic_id=str(topic_id),
topic_display_name=match.get("topic_display_name"),
ipc_level=ipc_level,
ipc_symbol=ipc_symbol,
)
)
+186
View File
@@ -0,0 +1,186 @@
"""
Bio generation for persons / authors.
"""
import json
import logging
import time
from pydantic import ValidationError
from inse.exceptions import NotFoundException, UpstreamAPIException
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.persons.model import PersonBio
from .. import config
from ..integrations import llm
logger = logging.getLogger(__name__)
async def _fetch_author_display_name(author_id: str) -> str | None:
query = {
"query_string": {
"default_field": "_id",
"query": author_id,
}
}
response = await elasticsearch.search(
index=ESIndex.OPENALEX_AUTHORS,
query=query,
source=["display_name"],
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
return None
return hits[0].get("_source", {}).get("display_name")
async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
WORK_SOURCE_FIELDS = [
"title",
"display_name",
"abstract",
"cited_by_count",
"primary_topic",
]
author_url = f"https://openalex.org/{author_id.strip()}"
authorship_query = {
"nested": {
"path": "authorships",
"query": {
"bool": {
"filter": [{"term": {"authorships.author.id": author_url}}],
}
},
}
}
body = {
"size": 100,
"sort": [{"cited_by_count": {"order": "desc"}}],
"_source": WORK_SOURCE_FIELDS,
"query": authorship_query,
"aggs": {
"primary_topics": {
"terms": {"field": "primary_topic.id", "size": 5},
"aggs": {
"topic_name": {
"top_hits": {
"size": 1,
"_source": ["primary_topic.display_name"],
}
}
},
}
},
}
response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
works = []
for hit in response.get("hits", {}).get("hits", []):
works.append(hit.get("_source", {}))
topics = []
buckets = (
response.get("aggregations", {}).get("primary_topics", {}).get("buckets", [])
)
for bucket in buckets:
topic_hits = bucket.get("topic_name", {}).get("hits", {}).get("hits", [])
display_name = None
if topic_hits:
primary_topic = topic_hits[0].get("_source", {}).get("primary_topic", {})
display_name = primary_topic.get("display_name")
topics.append(
{
"id": bucket.get("key"),
"display_name": display_name,
"count": bucket.get("doc_count"),
}
)
return works, topics
def _build_papers(works: list) -> list:
papers = []
for work in works:
name = work.get("title") or work.get("display_name")
abstract = work.get("abstract")
papers.append(
{
"name": name,
"abstract": abstract,
"stats": {
"cited_by_count": work.get("cited_by_count"),
},
}
)
return papers
async def get_data_for_bio(author_id: str) -> dict | None:
display_name = await _fetch_author_display_name(author_id)
if display_name is None:
return None
works, top_topics = await _fetch_works_and_topics(author_id)
papers = _build_papers(works)
author_data = {
"display_name": display_name,
"topics": top_topics,
"papers": papers,
}
return author_data
async def generate_person_bio(author_id: str) -> str:
start_time = time.time()
author_data = await get_data_for_bio(author_id)
if author_data is None:
raise NotFoundException(f"No person found for author ID {author_id}.")
person_json = json.dumps(author_data, ensure_ascii=False)
system_prompt = """\
Beschreibe in zwei Sätzen das Hauptforschungsfeld des Autors. Formuliere dabei allgemeinverständlich, sodass auch Personen ohne Fachwissen einen Einblick in die Forschung gewinnen. Nenne keine konkreten Publikationen oder Einzelwerke, sondern konzentriere dich auf die übergeordneten Forschungsinteressen und Themen. Verzichte auf bloße Aufzählungen und verbinde die Informationen zu einem flüssigen Text.
Beschreibe anschließend in ein bis zwei Sätzen die wirtschaftliche Relevanz der Forschung anhand von Anwendungen, Technologien oder Branchen, die davon profitieren könnten.
Verwende insgesamt maximal 100 bis 120 Wörter. Formuliere die Antwort so, dass sie ohne weitere Anpassungen direkt als Kurzbiografie verwendet werden kann. Verwende keine Superlative oder übertriebene Formulierungen, sondern bleibe sachlich und informativ. Gebe den Text als One-Liner zurück, ohne Zeilenumbrüche oder Aufzählungen. Verwende keine Gedankenstriche (– oder —) zur Gliederung von Sätzen. Formuliere stattdessen mit Kommas, Klammern oder zwei getrennten Sätzen.
Gib ausschließlich ein JSON-Objekt zurück, das den Text im Feld "bio" enthält.
"""
user_prompt = f"Daten zur Person:\n{person_json}"
response = await llm.call(
system_prompt=system_prompt,
user_prompt=user_prompt,
json_schema=PersonBio.model_json_schema(),
schema_name="bio",
temperature=0.8,
top_p=0.95,
)
try:
bio = PersonBio.model_validate_json(response).bio
except ValidationError as error:
logger.warning(
f"Bio generation for author {author_id} returned no valid bio: {response}"
)
raise UpstreamAPIException("Bio generation failed.") from error
elapsed_time = time.time() - start_time
logger.info(f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds")
return bio
+3 -172
View File
@@ -4,13 +4,10 @@ Business logic for persons / authors.
"""
import hashlib
import json
import logging
import time
from datetime import datetime
from pydantic import ValidationError
from inse.exceptions import (
BadRequestException,
ElasticsearchException,
@@ -26,13 +23,11 @@ from inse.persons.model import (
CareerMetrics,
CustomAuthor,
CustomAuthorsListResponse,
PersonBio,
)
from inse.persons.query_builder import build_authors_search_rescored
from inse.works.logic import enrich_topic_descriptions
from .. import config, util
from ..integrations import llm
logger = logging.getLogger(__name__)
INDEX_NAME = "openalex-authors"
@@ -220,100 +215,6 @@ async def count_authors_by_last_name(last_name: str) -> int:
return await _count_authors(query)
async def _fetch_author_display_name(author_id: str) -> str | None:
query = {
"query_string": {
"default_field": "_id",
"query": author_id,
}
}
response = await elasticsearch.search(
index=INDEX_NAME,
query=query,
source=["display_name"],
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
return None
return hits[0].get("_source", {}).get("display_name")
async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
WORK_SOURCE_FIELDS = [
"title",
"display_name",
"abstract",
"cited_by_count",
"primary_topic",
]
author_url = f"https://openalex.org/{author_id.strip()}"
authorship_query = {
"nested": {
"path": "authorships",
"query": {
"bool": {
"filter": [{"term": {"authorships.author.id": author_url}}],
}
},
}
}
body = {
"size": 100,
"sort": [{"cited_by_count": {"order": "desc"}}],
"_source": WORK_SOURCE_FIELDS,
"query": authorship_query,
"aggs": {
"primary_topics": {
"terms": {"field": "primary_topic.id", "size": 5},
"aggs": {
"topic_name": {
"top_hits": {
"size": 1,
"_source": ["primary_topic.display_name"],
}
}
},
}
},
}
response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
works = []
for hit in response.get("hits", {}).get("hits", []):
works.append(hit.get("_source", {}))
topics = []
buckets = (
response.get("aggregations", {}).get("primary_topics", {}).get("buckets", [])
)
for bucket in buckets:
topic_hits = bucket.get("topic_name", {}).get("hits", {}).get("hits", [])
display_name = None
if topic_hits:
primary_topic = topic_hits[0].get("_source", {}).get("primary_topic", {})
display_name = primary_topic.get("display_name")
topics.append(
{
"id": bucket.get("key"),
"display_name": display_name,
"count": bucket.get("doc_count"),
}
)
return works, topics
async def _get_publication_years_for_author(author_id: str) -> list[int]:
author_url = f"https://openalex.org/{author_id.strip()}"
@@ -427,79 +328,6 @@ async def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
return _compute_career_metrics(publication_years)
def _build_papers(works: list) -> list:
papers = []
for work in works:
name = work.get("title") or work.get("display_name")
abstract = work.get("abstract")
papers.append(
{
"name": name,
"abstract": abstract,
"stats": {
"cited_by_count": work.get("cited_by_count"),
},
}
)
return papers
async def get_data_for_bio(author_id: str) -> dict | None:
display_name = await _fetch_author_display_name(author_id)
if display_name is None:
return None
works, top_topics = await _fetch_works_and_topics(author_id)
papers = _build_papers(works)
author_data = {
"display_name": display_name,
"topics": top_topics,
"papers": papers,
}
return author_data
async def generate_person_bio(
author_id: str, include: set[str] | None = None
) -> str:
start_time = time.time()
author_data = await get_data_for_bio(author_id)
if author_data is None:
return "No person found."
person_json = json.dumps(author_data, ensure_ascii=False)
system_prompt = """\
Beschreibe in zwei Sätzen das Hauptforschungsfeld des Autors. Formuliere dabei allgemeinverständlich, sodass auch Personen ohne Fachwissen einen Einblick in die Forschung gewinnen. Nenne keine konkreten Publikationen oder Einzelwerke, sondern konzentriere dich auf die übergeordneten Forschungsinteressen und Themen. Verzichte auf bloße Aufzählungen und verbinde die Informationen zu einem flüssigen Text.
Beschreibe anschließend in ein bis zwei Sätzen die wirtschaftliche Relevanz der Forschung anhand von Anwendungen, Technologien oder Branchen, die davon profitieren könnten.
Verwende insgesamt maximal 100 bis 120 Wörter. Formuliere die Antwort so, dass sie ohne weitere Anpassungen direkt als Kurzbiografie verwendet werden kann. Verwende keine Superlative oder übertriebene Formulierungen, sondern bleibe sachlich und informativ. Gebe den Text als One-Liner zurück, ohne Zeilenumbrüche oder Aufzählungen. Verwende keine Gedankenstriche (– oder —) zur Gliederung von Sätzen. Formuliere stattdessen mit Kommas, Klammern oder zwei getrennten Sätzen.
Gib ausschließlich ein JSON-Objekt zurück, das den Text im Feld "bio" enthält.
"""
user_prompt = f"Daten zur Person:\n{person_json}"
response = await llm.call(
system_prompt=system_prompt,
user_prompt=user_prompt,
json_schema=PersonBio.model_json_schema(),
schema_name="bio",
temperature=0.8,
top_p=0.95,
)
try:
bio = PersonBio.model_validate_json(response).bio
except ValidationError:
logger.warning(f"Bio generation for author {author_id} returned no valid JSON: {response}")
bio = "Etwas ist schiefgelaufen."
elapsed_time = time.time() - start_time
logger.info(f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds")
return bio
async def get_person_by_id(
author_id: str, include: str | None = None
) -> CustomAuthorsListResponse:
@@ -528,6 +356,9 @@ async def get_person_by_id(
career_metrics=career_metrics,
)
if custom_author.topics:
await enrich_topic_descriptions(custom_author.topics)
return CustomAuthorsListResponse(results=[custom_author])
+8 -36
View File
@@ -9,7 +9,7 @@ from fastapi import APIRouter, HTTPException, Path, Query, status
from inse.models.openalex.authors_list_response import AuthorsListResponse
from . import logic, model
from . import bio as bio_logic, logic, model
router = APIRouter(
prefix="/api/inse-service",
@@ -32,23 +32,7 @@ async def search_persons(
query: Annotated[
str, Query(description="Search query (e.g., Arman AND Arzani)")
] = None,
include: Annotated[
str | None,
Query(
description=(
"Comma-separated include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, sources, counts_by_year, works_api_url, dates, "
"cited_by_count_boost"
),
example="topics_full,topic_share",
),
] = None,
):
include_set = (
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
if include
else None
)
return await logic.search_persons(author_id, query)
@@ -62,20 +46,8 @@ async def generate_person_bio(
author_id: Annotated[
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
],
include: Annotated[
str | None,
Query(
description=("Comma-separated list to include tags"),
example="topics_full,topic_share",
),
] = None,
):
include_set = (
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
if include
else None
)
bio = await logic.generate_person_bio(author_id, include_set)
bio = await bio_logic.generate_person_bio(author_id)
return model.PersonBio(bio=bio)
@router.get(
@@ -96,7 +68,7 @@ async def get_person_by_id(
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, ..."
),
example="topics_full,topic_share",
examples="topics_full,topic_share",
),
] = None,
):
@@ -119,11 +91,11 @@ async def search_persons_by_name(
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, ..."
),
example="topics_full,topic_share",
examples="topics_full,topic_share",
),
],
limit:Annotated[int | None, Query(description=("Limit of search page results"),example ="2")]= None,
page_offset : Annotated[int | None, Query(description=("Offset of the result page"),example="2")] = None,
limit:Annotated[int | None, Query(description=("Limit of search page results"),examples ="2")]= None,
page_offset : Annotated[int | None, Query(description=("Offset of the result page"),examples="2")] = None,
):
return await logic.search_persons_by_name(author_name=author_name, include=include, page_offset=page_offset, limit=limit)
@@ -141,7 +113,7 @@ async def search_persons_autocomplete(
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, ..."
),
example="topics_full,topic_share"
examples="topics_full,topic_share"
)]):
return await logic.search_persons_autocomplete(author_name=author_name, include=include)
@@ -181,7 +153,7 @@ async def search_persons_list(
str | None,
Query(
description="Comma-separated include tags",
example="topics_full,topic_share",
examples="topics_full,topic_share",
),
] = None,
year_filter_enabled: Annotated[
+48
View File
@@ -0,0 +1,48 @@
import pytest
from inse import config
from inse.exceptions import NotFoundException
from inse.persons import service
@pytest.fixture()
def anyio_backend():
return "asyncio"
def elasticsearch_configured():
return bool(
config.settings.elasticsearch_url and config.settings.elasticsearch_api_key
)
def llm_configured():
return bool(
config.settings.llm_api_url
and config.settings.llm_api_key
and config.settings.llm_model
)
requires_elasticsearch = pytest.mark.skipif(
not elasticsearch_configured(), reason="Elasticsearch is not configured"
)
requires_elasticsearch_and_llm = pytest.mark.skipif(
not (elasticsearch_configured() and llm_configured()),
reason="Elasticsearch and/or LLM are not configured",
)
@pytest.mark.anyio
@requires_elasticsearch_and_llm
async def test_bio_is_generated_for_person():
response = await service.generate_person_bio(author_id="A5093075883")
assert len(response.bio) >= 10, f"bio is too short: {response.bio!r}"
@pytest.mark.anyio
@requires_elasticsearch
async def test_bio_generation_fails_for_unknown_author():
with pytest.raises(NotFoundException):
await service.generate_person_bio(author_id="A000")
@@ -508,7 +508,7 @@ def _eu_sort_field(sort_by: str) -> str:
"id": "id",
"project_type": "_index",
}
return mapping.get(sort_by, "title.keyword")
return mapping.get(sort_by, "")
async def get_eu_project_ids_by_organization_filters(
@@ -781,6 +781,7 @@ async def _build_eu_cordis_search_query(
topic_project_ids_by_type = await get_eu_project_ids_by_openalex_topic_ids(
project_types=project_types,
topic_ids=topic_ids,
match_all=False
)
topic_filter = _eu_project_type_index_filter(topic_project_ids_by_type)
@@ -829,13 +830,14 @@ async def _build_eu_cordis_search_query(
)
if keyword_clauses:
must_clauses.append({"bool": {"must": keyword_clauses}})
must_clauses.append({"bool": {"should": keyword_clauses, "minimum_should_match": 1}})
# === Independent OpenAlex topic filters ===
if filter_topic_ids:
filter_topic_project_ids_by_type = await get_eu_project_ids_by_openalex_topic_ids(
project_types=project_types,
topic_ids=filter_topic_ids,
match_all=True
)
topic_filter = _eu_project_type_index_filter(filter_topic_project_ids_by_type)
@@ -957,7 +959,7 @@ async def search_eu_cordis_projects(
framework_programmes: list[str] | None = None,
funding_schemes: list[str] | None = None,
statuses: list[str] | None = None,
sort_by: str = "title",
sort_by: str = "",
sort_direction: str = "asc",
fuzzy: bool = False,
skip_enrichment: bool = False,
+58 -30
View File
@@ -115,17 +115,23 @@ async def get_person_ids_by_institution_ids(
}
)
async def get_bund_project_ids_by_topic_ids(topic_ids: list[str]) -> list[str]:
async def get_bund_project_ids_by_topic_ids(
topic_ids: list[str],
match_all: bool = True,
) -> list[str]:
"""
Query the `projects_bund_openalex_topics` index to find BUND project IDs
that match any of the given OpenAlex topic IDs.
that match:
- ALL of the given OpenAlex topic IDs if match_all=True
- ANY of the given OpenAlex topic IDs if match_all=False
Topics may be distributed across multiple documents for the same project.
"""
if not topic_ids:
return []
required_topics = set(topic_ids)
project_topics: dict[str, set[str]] = defaultdict(set)
body = {
@@ -143,8 +149,8 @@ async def get_bund_project_ids_by_topic_ids(topic_ids: list[str]) -> list[str]:
cluster=ESCluster.INSE,
body=body,
)
hits = response.get("hits", {}).get("hits", [])
hits = response.get("hits", {}).get("hits", [])
for hit in hits:
source = hit["_source"]
@@ -163,26 +169,35 @@ async def get_bund_project_ids_by_topic_ids(topic_ids: list[str]) -> list[str]:
if topic_id in required_topics:
project_topics[project_id].add(topic_id)
if match_all:
return [
project_id
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
# OR match: project has at least one requested topic
return list(project_topics.keys())
return [
project_id
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
async def get_dfg_project_ids_by_topic_ids(
topic_ids: list[str],
match_all: bool = True,
) -> list[str]:
"""
Fetches project IDs whose topic_matches contain:
async def get_dfg_project_ids_by_topic_ids(topic_ids: list[str]) -> list[str]:
"""Fetches project IDs whose topic_matches contain EVERY given topic ID,
even if the topics are distributed across multiple documents for the same project.
- ALL given topic IDs if match_all=True
- ANY given topic ID if match_all=False
Topics may be distributed across multiple documents for the same project.
"""
if not topic_ids:
return []
required_topics = set(topic_ids)
project_topics: dict[str, set[str]] = defaultdict(set)
body = {
"size": 10000,
"_source": ["project_id", "topic_matches"],
@@ -192,7 +207,7 @@ async def get_dfg_project_ids_by_topic_ids(topic_ids: list[str]) -> list[str]:
}
},
}
print("BODY", body)
response = await elasticsearch.search(
index=ESIndex.PROJECTS_DFG_TOPICS,
cluster=ESCluster.INSE,
@@ -201,7 +216,6 @@ async def get_dfg_project_ids_by_topic_ids(topic_ids: list[str]) -> list[str]:
hits = response.get("hits", {}).get("hits", [])
for hit in hits:
source = hit["_source"]
@@ -219,12 +233,15 @@ async def get_dfg_project_ids_by_topic_ids(topic_ids: list[str]) -> list[str]:
if topic_id in required_topics:
project_topics[project_id].add(topic_id)
if match_all:
return [
project_id
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
return [
project_id
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
# OR match: project has at least one requested topic
return list(project_topics.keys())
async def get_openalex_topics_for_bund_projects(project_ids: list[str]) -> dict[str, list[dict]]:
@@ -428,14 +445,18 @@ async def get_dfg_institutes_by_ids(
#EU Cordis Projects
async def get_eu_project_ids_by_openalex_topic_ids(
project_types: list[EuCordisProjectType],
topic_ids: list[str],
match_all: bool = True,
) -> dict[EuCordisProjectType, list[str]]:
"""
Returns EU CORDIS project IDs whose mapped OpenAlex topic_matches contain
EVERY given topic ID. Same semantics as DFG topic filtering.
Returns EU CORDIS project IDs whose mapped OpenAlex topic_matches contain:
- ALL given topic IDs if match_all=True
- ANY given topic ID if match_all=False
Topics may be distributed across multiple documents for the same project.
"""
if not topic_ids:
return {project_type: [] for project_type in project_types}
@@ -474,15 +495,18 @@ async def get_eu_project_ids_by_openalex_topic_ids(
for hit in hits:
source = hit.get("_source", {})
project_id = source.get("project_id")
if not project_id:
continue
topic_matches = source.get("topic_matches") or []
if isinstance(topic_matches, dict):
topic_matches = [topic_matches]
for match in topic_matches:
topic_id = match.get("topic_id")
if topic_id in required_topics:
project_topics[project_id].add(topic_id)
@@ -491,11 +515,15 @@ async def get_eu_project_ids_by_openalex_topic_ids(
from_ += page_size
result[project_type] = [
project_id
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
if match_all:
result[project_type] = [
project_id
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
else:
# OR match: project has at least one requested topic
result[project_type] = list(project_topics.keys())
return result
+4 -4
View File
@@ -88,7 +88,7 @@ class BundProjectHighlight(BaseModel):
default_factory=list,
description='Highlights from the Elasticsearch field "Zuwendungsempfänger".',
)
implementing_agency: list[str] = Field(
executing_agency: list[str] = Field(
default_factory=list,
description='Highlights from the Elasticsearch field "Ausführende Stelle".',
)
@@ -146,7 +146,7 @@ class BundProjectSummary(BundProject):
place=source.get("Ort"),
state=source.get("Bundesland"),
country=source.get("Staat"),
implementing_agency=source.get("Ausführende Stelle"),
executing_agency=source.get("Ausführende Stelle"),
topic=source.get("Thema"),
performance_plan_system=source.get("Leistungsplansystematik"),
performance_plan_system_text=source.get(
@@ -205,7 +205,7 @@ class BundProjectSummary(BundProject):
recipient=cls._highlight_fragments(
raw_highlight.get("Zuwendungsempfänger")
),
implementing_agency=cls._highlight_fragments(
executing_agency=cls._highlight_fragments(
raw_highlight.get("Ausführende Stelle")
),
)
@@ -215,7 +215,7 @@ class BundProjectSummary(BundProject):
highlight.joint_project,
highlight.topic,
highlight.recipient,
highlight.implementing_agency,
highlight.executing_agency,
)
)
@@ -364,7 +364,7 @@ async def search_dfg_projects(
title: str | None = None,
funding_start_years: list[str] | None = None,
funding_end_years: list[str] | None = None,
sort_by: str = "id",
sort_by: str = "",
sort_direction: str = "asc",
fuzzy: bool = False,
skip_enrichment: bool = False,
@@ -426,9 +426,8 @@ async def search_dfg_projects(
# === Primary search clause: mutually exclusive fuzzy(topic_ids) vs keyword phrase search ===
if fuzzy and topic_ids:
matching_project_ids = await get_dfg_project_ids_by_topic_ids(
topic_ids=topic_ids
topic_ids=topic_ids, match_all = False
)
if not matching_project_ids:
return DfgProjectPage(elements=[], total=0, page=page, size=size)
@@ -436,69 +435,94 @@ async def search_dfg_projects(
elif keywords:
keyword_clauses = []
#Add highlighting for the title and abstract fields
title_abstract_query = {
"bool": {
"should": [
{
"multi_match": {
"query": keyword,
"fields": ["title_de", "title_en", "abstract_de", "abstract_en"],
"type": "phrase_prefix",
"max_expansions": 100,
}
}
for keyword in keywords if keyword.strip()
],
"minimum_should_match": 1,
}
}
body["highlight"] = {
"fragment_size": 200,
"number_of_fragments": 0,
"pre_tags": ["<em>"],
"post_tags": ["</em>"],
"require_field_match": True,
"fields": {
"title_de": {"highlight_query": title_abstract_query},
"title_en": {"highlight_query": title_abstract_query},
"abstract_de": {"highlight_query": title_abstract_query},
"abstract_en": {"highlight_query": title_abstract_query},
},
}
for keyword in keywords:
if keyword.strip() == "":
continue
keyword_clauses.append(
{
keyword_clauses.append({
"bool": {
"should": [
{
"multi_match": {
"query": keyword,
"fields": [
"title_de",
"title_en",
"abstract_de",
"abstract_en",
],
"query": keyword,
"fields": ["title_de^4", "title_en^4", "abstract_de^2", "abstract_en^2"],
"type": "phrase_prefix",
"max_expansions": 100,
}
},
{
"nested": {
"path": "subject_classifications",
"query": {
"multi_match": {
"query": keyword,
"fields": [
"subject_classifications.fach",
"subject_classifications.fachkollegium",
"subject_classifications.fachgebiet",
"subject_classifications.fachgebiet_de",
"subject_classifications.wissenschaftsbereich",
],
"type": "phrase_prefix",
"max_expansions": 100,
}
},
"inner_hits": {
"name": keyword,
"highlight": {
"fields": {
"subject_classifications.fach": {},
"subject_classifications.fachkollegium": {},
"subject_classifications.fachgebiet": {},
"subject_classifications.fachgebiet_de": {},
"subject_classifications.wissenschaftsbereich": {},
"nested": {
"path": "subject_classifications",
"query": {
"multi_match": {
"query": keyword,
"fields": [
"subject_classifications.fach^4",
"subject_classifications.fachkollegium^4",
"subject_classifications.fachgebiet^4",
"subject_classifications.fachgebiet_de^4",
"subject_classifications.wissenschaftsbereich^4",
],
"type": "phrase_prefix",
"max_expansions": 100,
}
}
},
}
},
},
"inner_hits": {
"name": keyword,
"highlight": {
"fields": {
"subject_classifications.fach": {},
"subject_classifications.fachkollegium": {},
"subject_classifications.fachgebiet": {},
"subject_classifications.fachgebiet_de": {},
"subject_classifications.wissenschaftsbereich": {},
}
}
},
}
},
],
"minimum_should_match": 1,
"minimum_should_match": 1,
}
}
)
})
if keyword_clauses:
must_clauses.append({"bool": {"must": keyword_clauses}})
must_clauses.append({"bool": {"should": keyword_clauses, "minimum_should_match": 1}})
# === Additional independent filters (applied regardless of fuzzy/keyword mode) ===
if filter_topic_ids:
matching_filter_project_ids = await get_dfg_project_ids_by_topic_ids(
topic_ids=filter_topic_ids
topic_ids=filter_topic_ids, match_all=True
)
if not matching_filter_project_ids:
@@ -558,7 +582,7 @@ async def search_dfg_projects(
)
if name_must_clauses:
must_clauses.append({"bool": {"must": name_must_clauses}})
must_clauses.append({"bool": {"should": name_must_clauses, "minimum_should_match": 1}})
if institution_aliases:
matching_institution_ids = await get_institution_ids_by_institution_aliases(
@@ -635,25 +659,13 @@ async def search_dfg_projects(
elif sort_by == "professional_classification":
sort_config = {"subject_area_de.keyword": {"order": sort_direction}}
else:
sort_config = {"id": {"order": sort_direction}}
sort_config = {"_score": {"order": "desc"}}
body["sort"] = [sort_config]
#Add highlighting for the title and abstract fields
body["highlight"] = {
"fields": {
"title_de": {},
"title_en": {},
"abstract_de": {},
"abstract_en": {},
},
"pre_tags": ["<em>"],
"post_tags": ["</em>"],
"require_field_match": True,
}
# print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
# === Execute Search ===
# print(f"Executing DFG project search with body: {body}")
print(f"Executing DFG project search with body: {body}")
response = await elasticsearch.search(
index=ESIndex.DFG_PROJECTS,
body=body,
@@ -910,7 +922,7 @@ async def search_bund_projects_with_filters(
countries: list[str] | None = None,
page: int = 0,
size: int = 10,
sort_by: str = "title",
sort_by: str = "",
sort_direction: str = "asc",
fuzzy: bool = False,
skip_topic_enrichment: bool = False,
@@ -987,30 +999,42 @@ async def search_bund_projects_with_filters(
)
# === Primary search clause: fuzzy(topic_ids) vs keyword phrase search ===
if fuzzy and topic_ids:
matching_project_ids = await get_bund_project_ids_by_topic_ids(topic_ids=topic_ids)
matching_project_ids = await get_bund_project_ids_by_topic_ids(topic_ids=topic_ids, match_all=False)
if not matching_project_ids:
return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({"terms": {"_id": matching_project_ids}})
elif keywords:
keyword_clauses = []
#Add highlighting for the title and abstract fields
body["highlight"] = {
"fields": {
"Verbundprojekt": {},
"Thema": {},
"Zuwendungsempfänger": {},
"Ausführende Stelle": {},
},
"pre_tags": ["<em>"],
"post_tags": ["</em>"],
"require_field_match": True,
}
for kw in keywords:
if kw.strip() == "":
continue
keyword_clauses.append({
"multi_match": {
"query": kw,
"fields": ["Verbundprojekt","Thema"], # searching title/acronym field
"fields": ["Verbundprojekt^4","Thema^4"],
"type": "phrase_prefix",
"max_expansions": 100,
}
})
if keyword_clauses:
must_clauses.append({"bool": {"must": keyword_clauses}})
must_clauses.append({"bool": {"should": keyword_clauses, "minimum_should_match": 1}})
# === Additional independent filters (applied regardless of fuzzy/keyword mode) ===
if filter_topic_ids:
matching_filter_ids = await get_bund_project_ids_by_topic_ids(topic_ids=filter_topic_ids)
matching_filter_ids = await get_bund_project_ids_by_topic_ids(topic_ids=filter_topic_ids, match_all=True)
if not matching_filter_ids:
return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({"terms": {"_id": matching_filter_ids}})
@@ -1072,7 +1096,7 @@ async def search_bund_projects_with_filters(
sort_direction = sort_direction.strip().lower()
if sort_direction not in ("asc", "desc"):
sort_direction = "asc"
sort_config = {}
if sort_by == "title":
sort_config = {"Verbundprojekt.keyword": {"order": sort_direction}}
elif sort_by == "funding_start":
@@ -1080,22 +1104,9 @@ async def search_bund_projects_with_filters(
elif sort_by == "funding_end":
sort_config = {"funding_end": {"order": sort_direction}}
else:
# Fallback to project ID
sort_config = {"Förderkennzeichen.keyword": {"order": sort_direction}}
sort_config = "_score"
body["sort"] = [sort_config]
#Add highlighting for the title and abstract fields
body["highlight"] = {
"fields": {
"Verbundprojekt": {},
"Thema": {},
"Zuwendungsempfänger": {},
"Ausführende Stelle": {},
},
"pre_tags": ["<em>"],
"post_tags": ["</em>"],
"require_field_match": True,
}
# print(f"Executing BUND project search with body: {json.dumps(body, indent=2)}")
# === Execute Search ===
response = await elasticsearch.search(
+120 -60
View File
@@ -30,6 +30,7 @@ from inse.projects.model import (
SortDirection,
)
from inse.tags import Tags
from inse.database import SessionDep
from inse.auth.service import can_fetch_gdpr_relevant_data
from fastapi import HTTPException as HttpException
@@ -78,26 +79,36 @@ async def search_bund_projects(
"model": DfgProjectPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"},
status.HTTP_403_FORBIDDEN: {
"description": "Access denied for the provided institution ID"
},
},
response_model_by_alias=False,
)
async def get_dfg_projects(
access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep],
session: SessionDep,
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
raw_oa_institution_id: Annotated[
str | None, Query(description="The openalex institution ID to filter by.")
] = None,
author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None,
author_filter_ids: Annotated[list[str] | None, Query(description="The dfg author IDs to filter by.")] = None,
institution_ids: Annotated[list[str] | None, Query(description="The institution IDs to filter by.")] = None,
title: Annotated[
str | None, Query(description="The title to filter by.")
author_id: Annotated[
str | None, Query(description="The openalex author ID to filter by.")
] = None,
author_filter_ids: Annotated[
list[str] | None, Query(description="The dfg author IDs to filter by.")
] = None,
institution_ids: Annotated[
list[str] | None, Query(description="The institution IDs to filter by.")
] = None,
title: Annotated[str | None, Query(description="The title to filter by.")] = None,
keywords: Annotated[
list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.")
list[str] | None,
Query(description="Raw keywords to search in title/abstract/subject fields."),
] = None,
topic_ids: Annotated[
list[str] | None, Query(description="The openalex topic IDs to filter by.")
@@ -106,23 +117,27 @@ async def get_dfg_projects(
list[str] | None,
Query(
description="Additional topic IDs to merge into the fuzzy topic-id resolution "
"(union with topic_ids). Only used when fuzzy=True."
"(union with topic_ids). Only used when fuzzy=True."
),
] = None,
funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None,
funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None,
funding_start_years: Annotated[
list[str] | None, Query(description="The funding start years to filter by.")
] = None,
funding_end_years: Annotated[
list[str] | None, Query(description="The funding end years to filter by.")
] = None,
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
sort_by: Annotated[str, Query(description="The field to sort by.")] = "title",
sort_by: Annotated[str, Query(description="The field to sort by.")] = "",
sort_direction: Annotated[
str, Query(description="The sort direction (asc or desc).")
] = "asc",
fuzzy: Annotated[
bool,
Query(description="Use topic_id resolution if True, otherwise use raw keyword search."),
Query(
description="Use topic_id resolution if True, otherwise use raw keyword search."
),
] = False,
) -> DfgProjectPage:
logger.debug(
"Received request to get DFG projects for author_id=%s, author_filter_ids=%s, "
@@ -144,8 +159,13 @@ async def get_dfg_projects(
sort_direction,
fuzzy,
)
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 author_id or raw_oa_institution_id:
is_allowed = await can_fetch_gdpr_relevant_data(
session=session,
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,
@@ -170,6 +190,7 @@ async def get_dfg_projects(
fuzzy=fuzzy,
)
@router.get(
"/dfg/{id}",
summary="Get a single DFG project.",
@@ -204,12 +225,17 @@ async def get_single_dfg_project(
"model": BundProjectPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"},
status.HTTP_403_FORBIDDEN: {
"description": "Access denied for the provided institution ID"
},
},
response_model_by_alias=False,
)
async def search_bund_projects(
access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep],
session: SessionDep,
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -255,18 +281,25 @@ async def search_bund_projects(
] = None,
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
sort_by: Annotated[str, Query(description="Sort field.")] = "title",
sort_by: Annotated[str, Query(description="Sort field.")] = "",
sort_direction: Annotated[
str,
Query(description="Sort direction: asc or desc."),
] = "asc",
fuzzy: Annotated[
bool,
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
Query(
description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."
),
] = False,
) -> BundProjectPage:
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 raw_oa_institution_id:
is_allowed = await can_fetch_gdpr_relevant_data(
session=session,
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,
@@ -288,9 +321,10 @@ async def search_bund_projects(
size=size,
sort_by=sort_by,
sort_direction=sort_direction,
fuzzy=fuzzy
fuzzy=fuzzy,
)
@router.get(
"/bund/{id}",
summary="Get a single BUND project.",
@@ -313,6 +347,7 @@ async def get_single_bund_project(
project_id=id,
)
########
from inse.projects.model import EuCordisProjectSearchPage, EuCordisProjectType
from inse.projects.service import search_eu_cordis_projects
@@ -334,12 +369,17 @@ from inse.projects.service import search_eu_cordis_projects
"model": EuCordisProjectSearchPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"},
status.HTTP_403_FORBIDDEN: {
"description": "Access denied for the provided institution ID"
},
},
response_model_by_alias=False,
)
async def search_eu_cordis_projects_endpoint(
access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep],
session: SessionDep,
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -353,15 +393,21 @@ async def search_eu_cordis_projects_endpoint(
] = None,
author_ids: Annotated[
list[str] | None,
Query(description="Additional OpenAlex author IDs to filter by. All selected authors must match."),
Query(
description="Additional OpenAlex author IDs to filter by. All selected authors must match."
),
] = None,
organization_ids: Annotated[
list[str] | None,
Query(description="CORDIS organisation IDs. All selected organizations must match."),
Query(
description="CORDIS organisation IDs. All selected organizations must match."
),
] = None,
organization_names: Annotated[
list[str] | None,
Query(description="CORDIS organization names. All selected organizations must match."),
Query(
description="CORDIS organization names. All selected organizations must match."
),
] = None,
project_types: Annotated[
list[EuCordisProjectType] | None,
@@ -409,16 +455,17 @@ async def search_eu_cordis_projects_endpoint(
] = None,
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
sort_by: Annotated[str, Query(description="Sort field.")] = "title",
sort_by: Annotated[str, Query(description="Sort field.")] = "",
sort_direction: Annotated[
str,
Query(description="Sort direction: asc or desc."),
] = "asc",
fuzzy: Annotated[
bool,
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
Query(
description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."
),
] = False,
) -> EuCordisProjectSearchPage:
logger.debug(
"Received EU CORDIS search request: raw_oa_institution_id=%s, "
@@ -450,8 +497,13 @@ async def search_eu_cordis_projects_endpoint(
sort_direction,
fuzzy,
)
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 author_id or raw_oa_institution_id:
is_allowed = await can_fetch_gdpr_relevant_data(
session=session,
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,
@@ -482,6 +534,7 @@ async def search_eu_cordis_projects_endpoint(
fuzzy=fuzzy,
)
@router.get(
"/eu/{id}",
summary="Get a single EU Cordis project.",
@@ -494,27 +547,29 @@ async def search_eu_cordis_projects_endpoint(
},
status.HTTP_404_NOT_FOUND: {
"description": "Project not found",
"model": EuCordisProjectResponse
"model": EuCordisProjectResponse,
},
status.HTTP_500_INTERNAL_SERVER_ERROR: {
"description": "Internal server error",
"model": EuCordisProjectResponse
}
"model": EuCordisProjectResponse,
},
},
)
async def get_single_eu_cordis_project(
id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")],
id: Annotated[
str, Path(description="The ID of the EU Cordis project to retrieve.")
],
) -> EuCordisProjectResponse:
"""
Get a single EU Cordis project by ID.
Returns a wrapper response containing the project data or error information.
"""
logger.debug(f"Received request to get single EU Cordis project for id={id}")
try:
# Get the project from the service
project = await projects_service.get_single_eu_cordis_project(project_id=id)
# Check if project exists
if project is None:
logger.warning(f"Project with ID {id} not found")
@@ -522,9 +577,9 @@ async def get_single_eu_cordis_project(
success=False,
project_type=None,
eu_project_data=None,
error=f"Project with ID {id} not found"
error=f"Project with ID {id} not found",
)
# Determine the project type
if isinstance(project, Fp7ProjectDetails):
project_type = "fp7"
@@ -539,24 +594,21 @@ async def get_single_eu_cordis_project(
success=False,
project_type=None,
eu_project_data=None,
error=f"Unknown project type for ID {id}"
error=f"Unknown project type for ID {id}",
)
# Return success with the project data
return EuCordisProjectResponse(
success=True,
project_type=project_type,
eu_project_data=project,
error=None
success=True, project_type=project_type, eu_project_data=project, error=None
)
except Exception as e:
logger.error(f"Error retrieving project with ID {id}: {e!s}", exc_info=True)
return EuCordisProjectResponse(
success=False,
project_type=None,
eu_project_data=None,
error=f"Internal server error: {e!s}"
error=f"Internal server error: {e!s}",
)
@@ -623,7 +675,9 @@ async def get_institution_bund_projects_funding_over_time(
] = None,
fuzzy: Annotated[
bool,
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
Query(
description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."
),
] = False,
) -> InstitutionFunderSummary:
return await projects_service.get_institution_bund_projects_funding_over_time(
@@ -674,15 +728,21 @@ async def get_institution_cordis_eu_projects_funding_over_time(
] = None,
author_ids: Annotated[
list[str] | None,
Query(description="Additional OpenAlex author IDs to filter by. All selected authors must match."),
Query(
description="Additional OpenAlex author IDs to filter by. All selected authors must match."
),
] = None,
organization_ids: Annotated[
list[str] | None,
Query(description="CORDIS organisation IDs. All selected organizations must match."),
Query(
description="CORDIS organisation IDs. All selected organizations must match."
),
] = None,
organization_names: Annotated[
list[str] | None,
Query(description="CORDIS organization names. All selected organizations must match."),
Query(
description="CORDIS organization names. All selected organizations must match."
),
] = None,
project_types: Annotated[
list[EuCordisProjectType] | None,
@@ -730,7 +790,9 @@ async def get_institution_cordis_eu_projects_funding_over_time(
] = None,
fuzzy: Annotated[
bool,
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
Query(
description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."
),
] = False,
) -> InstitutionFunderSummary:
return await projects_service.get_institution_cordis_eu_projects_funding_over_time(
@@ -777,9 +839,7 @@ async def search_projects(
description="The set of project types to filter by (e.g., 'bund', 'eu', 'dfg'). If not provided, projects of all types will be included."
),
] = None,
title: Annotated[
str | None, Query(description="The title to filter by.")
] = None,
title: Annotated[str | None, Query(description="The title to filter by.")] = None,
sort_by: Annotated[
ProjectsSortBy, Query(description="The field to sort by.")
] = ProjectsSortBy.TITLE,
@@ -794,4 +854,4 @@ async def search_projects(
title=title,
sort_by=sort_by,
sort_direction=sort_direction,
)
)
+10 -8
View File
@@ -184,12 +184,13 @@ async def get_dfg_projects(
funding_end_years: list[str] | None,
page: int,
size: int,
sort_by: str = "topic",
sort_by: str = "",
sort_direction: str = "asc",
fuzzy: bool = False,
skip_enrichment: bool = False,
active_from_year: int | None = None,
active_to_year: int | None = None,
institution_aliases: list[str] | None = None,
) -> DfgProjectPage:
logger.debug(
"Fetching DFG projects for author_id=%s, author_filter_ids=%s, "
@@ -251,18 +252,18 @@ async def get_dfg_projects(
"No author names found for author_filter_ids=%s",
author_filter_ids_int,
)
institution_aliases = []
resolved_institution_aliases = list(institution_aliases or [])
if raw_oa_institution_id:
if institutions_search_client is None:
raise ValueError(
"institutions_search_client must be provided when raw_oa_institution_id is set"
)
institution_aliases = (
resolved_institution_aliases.extend(
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
)
if not institution_aliases:
if not resolved_institution_aliases:
return DfgProjectPage(
elements=[],
page=page,
@@ -272,7 +273,7 @@ async def get_dfg_projects(
return await projects_search_client.search_dfg_projects(
page=page,
size=size,
institution_aliases=institution_aliases,
institution_aliases=resolved_institution_aliases,
project_ids=author_project_ids,
names=filter_names or [],
institution_ids=institution_ids_int,
@@ -460,13 +461,14 @@ async def search_bund_projects_with_filters(
countries: list[str] | None,
page: int,
size: int,
sort_by: str = "title",
sort_by: str = "",
sort_direction: str = "asc",
fuzzy: bool = False,
active_from_year: int | None = None,
active_to_year: int | None = None,
oa_institution_aliases: list[str] | None = None,
) -> BundProjectPage:
institution_aliases = []
institution_aliases = list(oa_institution_aliases or [])
if raw_oa_institution_id:
if institutions_search_client is None:
raise ValueError(
@@ -670,7 +672,7 @@ async def search_eu_cordis_projects(
framework_programmes: list[str] | None = None,
funding_schemes: list[str] | None = None,
statuses: list[str] | None = None,
sort_by: str = "title",
sort_by: str = "",
sort_direction: str = "asc",
fuzzy: bool = False,
skip_enrichment: bool = False,
+98 -102
View File
@@ -2,7 +2,6 @@
import asyncio
import logging
from dataclasses import dataclass
from math import floor
from time import time
from typing import Any
@@ -21,7 +20,6 @@ from .model import (
AuthorTopicStats,
CareerStage,
CompanyStatusFilter,
FilterType,
KeywordOperator,
PublicationType,
PublicationTypeCount,
@@ -69,59 +67,88 @@ async def _get_author_ids_from_institution(institution_id: str) -> list[str]:
@dataclass(frozen=True)
class MatchConfig:
"""Where a topic filter matches on a work: keyword display names or topic ids."""
path: str
match_field: str
score_field: str
_KEYWORD_MATCH = MatchConfig(
path="keywords",
match_field="keywords.display_name.keyword",
score_field="keywords.score",
)
_TOPIC_MATCH = MatchConfig(
path="topics",
match_field="topics.display_name.keyword",
score_field="topics.score",
)
def _match_config(filter_type: FilterType) -> MatchConfig:
"""Resolves the request's filter_type into the single set of fields to match on."""
if filter_type == FilterType.TOPIC:
return _TOPIC_MATCH
return _KEYWORD_MATCH
def _keyword_clause(value: str, config: MatchConfig = _KEYWORD_MATCH) -> dict:
"""A single nested clause that matches one keyword/topic value on a work."""
def _topics_nested_clause(should_clauses: list[dict]) -> dict:
"""Wraps should-clauses on the nested topics of a work."""
return {
"nested": {
"path": config.path,
"path": "topics",
"query": {
"term": {config.match_field: value},
"bool": {
"should": should_clauses,
"minimum_should_match": 1,
},
},
},
}
def _topic_id_clause(topic_id: str) -> dict:
"""Matches one OpenAlex topic id against a work (fuzzy mode).
A work matches when the topic is either its primary topic or one of its
other topics.
"""
return {
"bool": {
"should": [
_topics_nested_clause([{"term": {"topics.id": topic_id}}]),
{"term": {"primary_topic.id": topic_id}},
],
"minimum_should_match": 1,
},
}
def _keyword_clause(keyword: str) -> dict:
"""Matches one raw keyword as a phrase against a work (non-fuzzy mode).
The keyword has to occur as a phrase in at least one of the work's own text
fields or in one of the names of its topic hierarchy.
"""
return {
"bool": {
"should": [
{
"nested": {
"path": "keywords",
"query": {
"match_phrase": {"keywords.display_name": keyword},
},
},
},
{"match_phrase": {"primary_topic.display_name": keyword}},
{"match_phrase": {"title": keyword}},
{"match_phrase": {"abstract": keyword}},
_topics_nested_clause(
[
{"match_phrase": {"topics.display_name": keyword}},
{"match_phrase": {"topics.field.display_name": keyword}},
{"match_phrase": {"topics.subfield.display_name": keyword}},
{"match_phrase": {"topics.domain.display_name": keyword}},
]
),
],
"minimum_should_match": 1,
},
}
def _build_keyword_query(
keywords: list[str],
operator: KeywordOperator,
config: MatchConfig = _KEYWORD_MATCH,
fuzzy: bool = False,
) -> dict:
"""Combines the keyword/topic clauses according to the operator.
AND: a work must carry all values (every clause is required).
OR: a work must carry at least one of the values.
AND: a work must match all values (every clause is required).
OR: a work must match at least one of the values.
"""
clauses = []
for keyword in keywords:
clauses.append(_keyword_clause(keyword, config))
if fuzzy:
clauses.append(_topic_id_clause(keyword))
else:
clauses.append(_keyword_clause(keyword))
if operator == KeywordOperator.OR:
return {
@@ -156,12 +183,12 @@ def _topic_stats_query(
operator: KeywordOperator,
publication_types: list[PublicationType],
timespan: Timespan | None,
config: MatchConfig = _KEYWORD_MATCH,
fuzzy: bool = False,
) -> dict:
"""Builds a single query with all stats for Section 1"""
filters = [
_build_keyword_query(keywords, operator, config),
_build_keyword_query(keywords, operator, fuzzy),
_author_filter(author_ids),
]
@@ -283,38 +310,6 @@ def _topic_stats_query(
"_source": {"includes": ["cited_by_count"]},
},
},
# works whose matched keyword/topic scores above 0.8
"relevance_above_80": {
"filter": {
"nested": {
"path": config.path,
"query": {
"bool": {
"filter": [
{"terms": {config.match_field: keywords}},
{"range": {config.score_field: {"gt": 0.8}}},
],
},
},
},
},
},
# average matched relevance score over the works
"matched_keywords": {
"nested": {"path": config.path},
"aggs": {
"only_searched": {
"filter": {
"terms": {config.match_field: keywords},
},
"aggs": {
"avg_score": {
"avg": {"field": config.score_field},
},
},
},
},
},
},
},
},
@@ -347,17 +342,16 @@ async def topic_stats_for_authors(
operator: KeywordOperator,
publication_types: list[PublicationType],
timespan: Timespan | None,
filter_type: FilterType = FilterType.KEYWORD,
fuzzy: bool = False,
) -> list[AuthorTopicStats]:
if not author_ids:
return []
match_cfg = _match_config(filter_type)
response: dict[str, Any] = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=_topic_stats_query(
author_ids, keywords, operator, publication_types, timespan, match_cfg
author_ids, keywords, operator, publication_types, timespan, fuzzy
),
cluster=ESCluster.NES,
)
@@ -375,12 +369,6 @@ async def topic_stats_for_authors(
for author_bucket in author_buckets:
to_work = author_bucket.get("to_work", {})
avg_value = to_work.get("avg_percentile", {}).get("value")
avg_rel = (
to_work.get("matched_keywords", {})
.get("only_searched", {})
.get("avg_score", {})
.get("value")
)
positions = {
bucket.get("key", ""): bucket.get("doc_count", 0)
for bucket in author_bucket.get("positions", {}).get("buckets", [])
@@ -413,8 +401,6 @@ async def topic_stats_for_authors(
industry_works_count=to_work.get("industry_collab", {}).get("doc_count", 0),
first_year=int(first_year) if first_year is not None else None,
last_year=int(last_year) if last_year is not None else None,
relevance_above_80_count=to_work.get("relevance_above_80", {}).get("doc_count", 0),
avg_relevance=float(avg_rel) if avg_rel is not None else 0.0,
first_author_count=positions.get("first", 0),
middle_author_count=positions.get("middle", 0),
last_author_count=positions.get("last", 0),
@@ -424,13 +410,29 @@ async def topic_stats_for_authors(
return results
def _primary_topic_match(keywords: list[str], fuzzy: bool) -> dict:
"""Matches works whose primary topic is one of the searched topics/keywords."""
if fuzzy:
return {"terms": {"primary_topic.id": keywords}}
return {
"bool": {
"should": [
{"match_phrase": {"primary_topic.display_name": keyword}}
for keyword in keywords
],
"minimum_should_match": 1,
},
}
def _topic_profile_query(
author_ids: list[str],
keywords: list[str],
operator: KeywordOperator,
publication_types: list[PublicationType],
timespan: Timespan | None,
config: MatchConfig = _KEYWORD_MATCH,
fuzzy: bool = False,
) -> dict:
"""Builds the Section 3 query"""
@@ -474,14 +476,10 @@ def _topic_profile_query(
"reverse_nested": {},
"aggs": {
"matched": {
"filter": _build_keyword_query(keywords, operator, config),
"filter": _build_keyword_query(keywords, operator, fuzzy),
"aggs": {
"primary_match": {
"filter": {
"terms": {
"primary_topic.display_name.keyword": keywords,
},
},
"filter": _primary_topic_match(keywords, fuzzy),
},
},
},
@@ -561,17 +559,16 @@ async def topic_profile_for_authors(
operator: KeywordOperator,
publication_types: list[PublicationType],
timespan: Timespan | None,
filter_type: FilterType = FilterType.KEYWORD,
fuzzy: bool = False,
) -> list[AuthorTopicProfile]:
if not author_ids:
return []
match_cfg = _match_config(filter_type)
response: dict[str, Any] = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=_topic_profile_query(
author_ids, keywords, operator, publication_types, timespan, match_cfg
author_ids, keywords, operator, publication_types, timespan, fuzzy
),
cluster=ESCluster.NES,
)
@@ -727,11 +724,11 @@ def _build_query(
author_ids: list[str],
publication_types: list[PublicationType],
timespan: Timespan | None,
config: MatchConfig = _KEYWORD_MATCH,
fuzzy: bool = False,
) -> dict:
"""Builds the Elasticsearch query that returns the raw stats per author."""
work_filters = [
_build_keyword_query(keywords, operator, config),
_build_keyword_query(keywords, operator, fuzzy),
_author_filter(author_ids),
]
if publication_types:
@@ -794,7 +791,7 @@ def _build_publication_type_counts_query(
operator: KeywordOperator,
author_ids: list[str],
timespan: Timespan | None,
config: MatchConfig = _KEYWORD_MATCH,
fuzzy: bool = False,
) -> dict:
"""Builds the query that counts matching works per publication type.
@@ -802,7 +799,7 @@ def _build_publication_type_counts_query(
filter itself, since it aggregates over all types instead of one score.
"""
work_filters = [
_build_keyword_query(keywords, operator, config),
_build_keyword_query(keywords, operator, fuzzy),
_author_filter(author_ids),
]
if timespan is not None:
@@ -832,7 +829,7 @@ async def publication_type_counts_for_keywords(
institution_id: str,
career_stages: list[CareerStage],
timespan: Timespan | None,
filter_type: FilterType = FilterType.KEYWORD,
fuzzy: bool = False,
) -> list[PublicationTypeCount]:
"""Counts the university's matching works per publication type, largest first."""
author_ids = await _get_author_ids_from_institution(institution_id)
@@ -844,7 +841,7 @@ async def publication_type_counts_for_keywords(
author_ids = await _filter_author_ids_by_career_stage(author_ids, career_stages)
query_body = _build_publication_type_counts_query(
keywords, operator, author_ids, timespan, _match_config(filter_type),
keywords, operator, author_ids, timespan, fuzzy,
)
response: dict[str, Any] = await elasticsearch.search(
@@ -1175,7 +1172,7 @@ async def rank_authors_by_keywords(
publication_types: list[PublicationType],
timespan: Timespan | None,
company_status: CompanyStatusFilter = CompanyStatusFilter.ALL,
filter_type: FilterType = FilterType.KEYWORD,
fuzzy: bool = False,
) -> list[RankedAuthor]:
"""Ranks the university's authors by a weighted score over works and citations.
@@ -1193,8 +1190,7 @@ async def rank_authors_by_keywords(
author_ids = await _filter_author_ids_by_career_stage(author_ids, career_stages)
query_body = _build_query(
keywords, operator, author_ids, publication_types, timespan,
_match_config(filter_type),
keywords, operator, author_ids, publication_types, timespan, fuzzy,
)
response: dict[str, Any] = await elasticsearch.search(
+21 -36
View File
@@ -12,11 +12,6 @@ class KeywordOperator(StrEnum):
OR = "or"
class FilterType(StrEnum):
KEYWORD = "keyword"
TOPIC = "topic"
class CompanyStatusFilter(StrEnum):
ALL = "all"
ACTIVE = "active"
@@ -107,10 +102,12 @@ class KeywordToAuthorRequest(BaseModel):
default=KeywordOperator.AND,
description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.",
)
filter_type: FilterType = Field(
default=FilterType.KEYWORD,
description="What the 'keywords' values match against: 'keyword' (OpenAlex "
"keyword display names) or 'topic' (OpenAlex topic display names). Defaults to 'keyword'.",
fuzzy: bool = Field(
default=False,
description="How the 'keywords' values are matched: True means they are "
"OpenAlex topic ids matched against the work's topics, False means they are "
"raw keywords matched as phrases in the work's title, abstract, keywords and "
"topic names. Defaults to False.",
)
weights: RankingWeights = Field(
description="Weights for the ranking metrics. Required.",
@@ -133,7 +130,7 @@ class KeywordToAuthorRequest(BaseModel):
"'all', only 'active' (non-deleted), or only 'deleted'.",
)
@field_validator("operator", "filter_type", mode="before")
@field_validator("operator", mode="before")
@classmethod
def operator_case_insensitive(cls, value):
if isinstance(value, str):
@@ -154,10 +151,12 @@ class SelectedAuthorsRequest(BaseModel):
default=KeywordOperator.AND,
description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.",
)
filter_type: FilterType = Field(
default=FilterType.KEYWORD,
description="What the 'keywords' values match against: 'keyword' (OpenAlex "
"keyword display names) or 'topic' (OpenAlex topic ids). Defaults to 'keyword'.",
fuzzy: bool = Field(
default=False,
description="How the 'keywords' values are matched: True means they are "
"OpenAlex topic ids matched against the work's topics, False means they are "
"raw keywords matched as phrases in the work's title, abstract, keywords and "
"topic names. Defaults to False.",
)
publication_types: list[PublicationType] = Field(
default_factory=list,
@@ -175,13 +174,6 @@ class SelectedAuthorsRequest(BaseModel):
return value.lower()
return value
@field_validator("filter_type", mode="before")
@classmethod
def filter_type_case_insensitive(cls, value):
if isinstance(value, str):
return value.lower()
return value
class AuthorMetricsRequest(BaseModel):
author_ids: list[str] = Field(
@@ -204,10 +196,12 @@ class PublicationTypeCountsRequest(BaseModel):
default=KeywordOperator.AND,
description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.",
)
filter_type: FilterType = Field(
default=FilterType.KEYWORD,
description="What the 'keywords' values match against: 'keyword' (OpenAlex "
"keyword display names) or 'topic' (OpenAlex topic display names). Defaults to 'keyword'.",
fuzzy: bool = Field(
default=False,
description="How the 'keywords' values are matched: True means they are "
"OpenAlex topic ids matched against the work's topics, False means they are "
"raw keywords matched as phrases in the work's title, abstract, keywords and "
"topic names. Defaults to False.",
)
career_stages: list[CareerStage] = Field(
default_factory=list,
@@ -218,7 +212,7 @@ class PublicationTypeCountsRequest(BaseModel):
description="Optional filter: only count works whose publication_year is within [from, to].",
)
@field_validator("operator", "filter_type", mode="before")
@field_validator("operator", mode="before")
@classmethod
def operator_case_insensitive(cls, value):
if isinstance(value, str):
@@ -290,15 +284,6 @@ class AuthorTopicStats(BaseModel):
default=None,
description="Latest publication year among the author's topic works.",
)
relevance_above_80_count: int = Field(
default=0,
description="Number of the author's topic works where the matched keyword's "
"relevance score is above 0.8.",
)
avg_relevance: float = Field(
default=0.0,
description="Average matched-keyword relevance score (0-1) over the author's topic works.",
)
first_author_count: int = Field(
default=0,
description="Number of the author's topic works where they are the first author.",
@@ -355,7 +340,7 @@ class AuthorTopicProfile(BaseModel):
)
primary_topic_matches: int = Field(
description="Matched works where one of the searched topics is the work's "
"primary topic (only meaningful for filter_type 'topic').",
"primary topic.",
)
distinct_topics: int = Field(
description="Number of distinct primary topics across all works.",
+12 -12
View File
@@ -48,11 +48,11 @@ async def rank_author(
)
logger.info(
"rank-author keywords=%s operator=%s filter_type=%s institution_id=%s career_stages=%s "
"rank-author keywords=%s operator=%s fuzzy=%s institution_id=%s career_stages=%s "
"publication_types=%s timespan=%s",
request.keywords,
request.operator,
request.filter_type,
request.fuzzy,
institution_id,
request.career_stages,
request.publication_types,
@@ -67,7 +67,7 @@ async def rank_author(
publication_types=request.publication_types,
timespan=request.timespan,
company_status=request.company_status,
filter_type=request.filter_type,
fuzzy=request.fuzzy,
)
# Publication-type facet counts for the "Art der Work" filter
@@ -86,11 +86,11 @@ async def publication_type_counts(
)
logger.info(
"publication-type-counts keywords=%s operator=%s filter_type=%s institution_id=%s "
"publication-type-counts keywords=%s operator=%s fuzzy=%s institution_id=%s "
"career_stages=%s timespan=%s",
request.keywords,
request.operator,
request.filter_type,
request.fuzzy,
institution_id,
request.career_stages,
request.timespan,
@@ -101,18 +101,18 @@ async def publication_type_counts(
institution_id=institution_id,
career_stages=request.career_stages,
timespan=request.timespan,
filter_type=request.filter_type,
fuzzy=request.fuzzy,
)
# Compare authors table 1 (topic stats)
@router.post("/topic-stats", response_model=list[AuthorTopicStats])
async def topic_stats(request: SelectedAuthorsRequest):
logger.info(
"topic-stats author_ids=%s keywords=%s operator=%s filter_type=%s publication_types=%s timespan=%s",
"topic-stats author_ids=%s keywords=%s operator=%s fuzzy=%s publication_types=%s timespan=%s",
request.author_ids,
request.keywords,
request.operator,
request.filter_type,
request.fuzzy,
request.publication_types,
request.timespan,
)
@@ -122,19 +122,19 @@ async def topic_stats(request: SelectedAuthorsRequest):
request.operator,
request.publication_types,
request.timespan,
request.filter_type,
request.fuzzy,
)
# Compare authors section 3 (topic profile over ALL works of each author)
@router.post("/topic-profile", response_model=list[AuthorTopicProfile])
async def topic_profile(request: SelectedAuthorsRequest):
logger.info(
"topic-profile author_ids=%s keywords=%s operator=%s filter_type=%s "
"topic-profile author_ids=%s keywords=%s operator=%s fuzzy=%s "
"publication_types=%s timespan=%s",
request.author_ids,
request.keywords,
request.operator,
request.filter_type,
request.fuzzy,
request.publication_types,
request.timespan,
)
@@ -144,7 +144,7 @@ async def topic_profile(request: SelectedAuthorsRequest):
request.operator,
request.publication_types,
request.timespan,
request.filter_type,
request.fuzzy,
)
# Compare authors table 2 (author-level stats, keyword/time-independent)
-84
View File
@@ -1,84 +0,0 @@
"""
This module contains the rest api of the
service.
"""
import logging
from typing import Annotated
from fastapi import APIRouter, Query
from inse.config import get_settings
from . import logic
logger = logging.getLogger(__name__)
### startup
settings = get_settings()
router = APIRouter(
prefix="/api/inse-service",
tags=["INSE Service"],
responses={404: {"description": "Not found"}},
)
### topics
# hierarchy cache (temporaray => should be called by a scheduled job, with new openalex data indexing)
@router.get(
"/topics/cache",
operation_id="buildTopicCache",
response_model=dict,
summary="Builds the topic hierarchy cache.",
tags=["Topics"],
)
def build_topic_cache(
page_size: Annotated[
int, Query(description="Page size for each search page.", ge=1, le=1000)
] = 200,
save_json: Annotated[
bool, Query(description="Persist cache JSON to data folder.")
] = True,
):
return logic.build_topic_cache(page_size=page_size, save_json=save_json)
@router.get(
"/topics/count",
operation_id="countTopicHierarchy",
response_model=dict,
summary="Counts topic hierarchy occurrences from cache.",
tags=["Topics"],
)
def count_topic_hierarchy(
topic_names: Annotated[
list[str],
Query(
alias="topic",
description="Topic names (repeat parameter).",
example=[
"Big Data and Business Intelligence",
"Big Data and Business Intelligence",
"Topic Modeling",
"Entrepreneurship Studies and Influences",
"Complex Network Analysis Techniques",
"Semantic Web and Ontologies",
],
),
],
):
return logic.count_topic_hierarchy(topic_names)
@router.get(
"/topics/hierarchy",
operation_id="getTopicHierarchy",
response_model=dict,
summary="Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).",
tags=["Topics"],
)
def get_topic_hierarchy():
return logic.get_topic_hierarchy()
+2 -103
View File
@@ -1,111 +1,10 @@
from fastapi.testclient import TestClient
from inse.main import app
client = TestClient(app)
URL_SERVICE_PREFIX="/inse-service"
def test_redirect_root():
response = client.get("/", follow_redirects=False)
assert response.status_code == 307
# def test_get_person_by_id_success():
# mock_person = model.Person(
# id="A5093075883",
# name="Arman Arzani",
# works_count=6,
# cited_by_count=4,
# affiliations=[],
# topics=[]
# )
# with patch("inse.logic.get_person_by_id", return_value=mock_person):
# response = client.get(
# URL_SERVICE_PREFIX + "/persons/id",
# params={"author_id": "A5093075883"}
# )
# assert response.status_code == 200
# data = response.json()
# assert data["id"] == "A5093075883"
# assert data["name"] == "Arman Arzani"
# assert data["works_count"] == 6
# assert data["cited_by_count"] == 4
# def test_get_person_by_id_not_found():
# invalid_id = "INVALID"
# with patch(
# "inse.logic.get_person_by_id",
# side_effect=HTTPException(
# status_code=404,
# detail="Person with id INVALID not found"
# )
# ):
# response = client.get(
# URL_SERVICE_PREFIX + "/persons/id",
# params={"author_id": invalid_id}
# )
# assert response.status_code == 404
# def test_get_person_by_id_missing_query_param():
# response = client.get(URL_SERVICE_PREFIX + "/persons/id")
# assert response.status_code == 422
# def test_search_persons_by_name_success():
# mock_result = model.PersonSearchResult(
# persons=[
# model.Person(
# id="A5047117780",
# name="Pedro José Marrón",
# works_count=285,
# cited_by_count=2638,
# )
# ]
# )
# with patch(
# "inse.logic.search_persons_by_name",
# return_value=mock_result
# ):
# response = client.get(
# URL_SERVICE_PREFIX + "/persons/searchByName",
# params={"author_name": "Pedro José Marrón"}
# )
# assert response.status_code == 200
# data = response.json()
# assert "persons" in data
# assert data["persons"][0]["name"] == "Pedro José Marrón"
# def test_search_persons_by_name_empty_result():
# response = client.get(
# URL_SERVICE_PREFIX + "/persons/searchByName",
# params={"author_name": "zzzz_nonexistent_name_123"}
# )
# assert response.status_code == 200
# data = response.json()
# assert data["persons"] == []
# def test_search_persons_by_name_missing_query_param():
# response = client.get(URL_SERVICE_PREFIX + "/persons/searchByName")
# assert response.status_code == 422
assert response.status_code == 307
+23
View File
@@ -1,4 +1,5 @@
from enum import StrEnum
from pydantic import BaseModel
from inse.model import Page
from inse.models.openalex.topic import Topic
@@ -12,3 +13,25 @@ class TopicSortBy(StrEnum):
class TopicPageV2(Page[Topic]):
pass
class TopicHierarchySubfield(BaseModel):
id: str | None = None
name: str
topics: list[Topic] = []
class TopicHierarchyField(BaseModel):
id: str | None = None
name: str
subfields: list[TopicHierarchySubfield] = []
class TopicHierarchyDomain(BaseModel):
id: str | None = None
name: str
fields: list[TopicHierarchyField] = []
class TopicHierarchyResponse(BaseModel):
domains: list[TopicHierarchyDomain] = []
+14 -1
View File
@@ -10,7 +10,11 @@ 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
from inse.topics.v2.model import TopicPageV2, TopicSortBy
from inse.topics.v2.model import (
TopicHierarchyResponse,
TopicPageV2,
TopicSortBy,
)
logger = logging.getLogger(__name__)
@@ -18,6 +22,15 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix=RouterPrefixes.TOPICS_V2, tags=[Tags.TOPICS_V2])
@router.get(
"/hierarchy",
operation_id="getTopicHierarchy",
summary="Returns the full topic hierarchy tree (Domain -> Field -> Subfield -> Topics).",
)
async def get_topic_hierarchy() -> TopicHierarchyResponse:
return await topics_service.get_topic_hierarchy()
@router.get(
"/search",
operation_id="searchTopics",
+123 -1
View File
@@ -5,7 +5,14 @@ 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
from inse.topics.v2.model import (
TopicHierarchyDomain,
TopicHierarchyField,
TopicHierarchyResponse,
TopicHierarchySubfield,
TopicPageV2,
TopicSortBy,
)
async def _search_topics(
@@ -322,3 +329,118 @@ async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2:
"domain",
],
)
_cached_hierarchy: TopicHierarchyResponse | None = None #cache is small, data is static => reduces database calls
def clear_topic_hierarchy_cache() -> None:
global _cached_hierarchy
_cached_hierarchy = None
async def get_topic_hierarchy() -> TopicHierarchyResponse:
"""Builds and returns a hierarchical tree structure of topics:
Domains -> Fields -> Subfields -> Topics
Data is dynamically streamed from Elasticsearch openalex-topics using PIT+search_after scan and cached in-memory.
"""
global _cached_hierarchy
if _cached_hierarchy is not None:
return _cached_hierarchy
domains_map: dict[str, dict] = {}
async for hit in elasticsearch.scan(
index=ESIndex.OPENALEX_TOPICS,
query={"match_all": {}},
source=[
"id",
"display_name",
"description",
"subfield",
"field",
"domain",
"works_count",
"cited_by_count",
],
page_size=2000,
):
source = hit.get("_source", {})
topic_name = source.get("display_name")
topic_id = source.get("id") or hit.get("_id")
if not topic_name or not topic_id:
continue
domain_info = source.get("domain") or {}
field_info = source.get("field") or {}
subfield_info = source.get("subfield") or {}
domain_name = domain_info.get("display_name") or "Unbekannter Bereich"
domain_id = domain_info.get("id")
field_name = field_info.get("display_name") or "Unbekanntes Feld"
field_id = field_info.get("id")
subfield_name = subfield_info.get("display_name") or "Unbekanntes Teilfeld"
subfield_id = subfield_info.get("id")
if domain_name not in domains_map:
domains_map[domain_name] = {
"id": domain_id,
"name": domain_name,
"fields": {},
}
fields_map = domains_map[domain_name]["fields"]
if field_name not in fields_map:
fields_map[field_name] = {
"id": field_id,
"name": field_name,
"subfields": {},
}
subfields_map = fields_map[field_name]["subfields"]
if subfield_name not in subfields_map:
subfields_map[subfield_name] = {
"id": subfield_id,
"name": subfield_name,
"topics": [],
}
topic_obj = Topic.from_dict(source) if hasattr(Topic, "from_dict") else Topic(**source)
subfields_map[subfield_name]["topics"].append(topic_obj)
formatted_domains: list[TopicHierarchyDomain] = []
for d_name, d_val in sorted(domains_map.items(), key=lambda x: x[0]):
formatted_fields: list[TopicHierarchyField] = []
for f_name, f_val in sorted(d_val["fields"].items(), key=lambda x: x[0]):
formatted_subfields: list[TopicHierarchySubfield] = []
for sf_name, sf_val in sorted(
f_val["subfields"].items(), key=lambda x: x[0]
):
sf_val["topics"].sort(
key=lambda t: t.display_name or ""
)
formatted_subfields.append(
TopicHierarchySubfield(
id=sf_val["id"],
name=sf_name,
topics=sf_val["topics"],
)
)
formatted_fields.append(
TopicHierarchyField(
id=f_val["id"],
name=f_name,
subfields=formatted_subfields,
)
)
formatted_domains.append(
TopicHierarchyDomain(
id=d_val["id"],
name=d_name,
fields=formatted_fields,
)
)
result = TopicHierarchyResponse(domains=formatted_domains)
_cached_hierarchy = result
return result
+23 -6
View File
@@ -20,6 +20,10 @@ from inse.models.openalex.topics_by_time import TopicsByTime
from inse.models.openalex.topics_by_year import TopicsByYear
from inse.models.openalex.work import Work
from inse.models.openalex.work_page import WorkPage
from inse.models.openalex.work_topic import WorkTopic
from inse.models.openalex.work_topic_domain import WorkTopicDomain
from inse.models.openalex.work_topic_field import WorkTopicField
from inse.models.openalex.work_topic_subfield import WorkTopicSubfield
from inse.models.openalex.works_list_response import WorksListResponse
from .search_client import OpenAlexWorksSearchClient
@@ -235,26 +239,39 @@ async def get_work(
return elements[0]
async def enrich_topic_descriptions(topics: list) -> None:
"""Batch-fill missing descriptions on dehydrated topics.
async def enrich_topic_descriptions(topics: list[WorkTopic]) -> None:
"""Batch-fill missing hierarchy metadata and descriptions on dehydrated topics.
OpenAlex work and author documents carry dehydrated topics without a
description, so we batch-load the details from the openalex-topics index.
description, subfield, field, or domain, so we batch-load the details from
the openalex-topics index.
"""
pending = [topic for topic in topics if topic.id and not topic.description]
pending = [
topic
for topic in topics
if topic.id and (not topic.description or not topic.var_field or not topic.domain)
]
if not pending:
return
details = await _get_topic_details(list({topic.id for topic in pending}))
if not details:
return
for topic in pending:
info = details.get(topic.id)
if info:
if not info:
continue
if not topic.description:
topic.description = info.get("description")
if not topic.subfield and info.get("subfield"):
topic.subfield = WorkTopicSubfield.from_dict(info["subfield"])
if not topic.var_field and info.get("field"):
topic.var_field = WorkTopicField.from_dict(info["field"])
if not topic.domain and info.get("domain"):
topic.domain = WorkTopicDomain.from_dict(info["domain"])
async def _enrich_work_topic_descriptions(works: list[Work]) -> None:
+88
View File
@@ -712,6 +712,53 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" },
]
[[package]]
name = "pandas"
version = "2.3.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "numpy" },
{ name = "python-dateutil" },
{ name = "pytz" },
{ name = "tzdata" },
]
sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/9c/fb/231d89e8637c808b997d172b18e9d4a4bc7bf31296196c260526055d1ea0/pandas-2.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d21f6d74eb1725c2efaa71a2bfc661a0689579b58e9c0ca58a739ff0b002b53", size = 11597846, upload-time = "2025-09-29T23:19:48.856Z" },
{ url = "https://files.pythonhosted.org/packages/5c/bd/bf8064d9cfa214294356c2d6702b716d3cf3bb24be59287a6a21e24cae6b/pandas-2.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3fd2f887589c7aa868e02632612ba39acb0b8948faf5cc58f0850e165bd46f35", size = 10729618, upload-time = "2025-09-29T23:39:08.659Z" },
{ url = "https://files.pythonhosted.org/packages/57/56/cf2dbe1a3f5271370669475ead12ce77c61726ffd19a35546e31aa8edf4e/pandas-2.3.3-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecaf1e12bdc03c86ad4a7ea848d66c685cb6851d807a26aa245ca3d2017a1908", size = 11737212, upload-time = "2025-09-29T23:19:59.765Z" },
{ url = "https://files.pythonhosted.org/packages/e5/63/cd7d615331b328e287d8233ba9fdf191a9c2d11b6af0c7a59cfcec23de68/pandas-2.3.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b3d11d2fda7eb164ef27ffc14b4fcab16a80e1ce67e9f57e19ec0afaf715ba89", size = 12362693, upload-time = "2025-09-29T23:20:14.098Z" },
{ url = "https://files.pythonhosted.org/packages/a6/de/8b1895b107277d52f2b42d3a6806e69cfef0d5cf1d0ba343470b9d8e0a04/pandas-2.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a68e15f780eddf2b07d242e17a04aa187a7ee12b40b930bfdd78070556550e98", size = 12771002, upload-time = "2025-09-29T23:20:26.76Z" },
{ url = "https://files.pythonhosted.org/packages/87/21/84072af3187a677c5893b170ba2c8fbe450a6ff911234916da889b698220/pandas-2.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:371a4ab48e950033bcf52b6527eccb564f52dc826c02afd9a1bc0ab731bba084", size = 13450971, upload-time = "2025-09-29T23:20:41.344Z" },
{ url = "https://files.pythonhosted.org/packages/86/41/585a168330ff063014880a80d744219dbf1dd7a1c706e75ab3425a987384/pandas-2.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:a16dcec078a01eeef8ee61bf64074b4e524a2a3f4b3be9326420cabe59c4778b", size = 10992722, upload-time = "2025-09-29T23:20:54.139Z" },
{ url = "https://files.pythonhosted.org/packages/cd/4b/18b035ee18f97c1040d94debd8f2e737000ad70ccc8f5513f4eefad75f4b/pandas-2.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:56851a737e3470de7fa88e6131f41281ed440d29a9268dcbf0002da5ac366713", size = 11544671, upload-time = "2025-09-29T23:21:05.024Z" },
{ url = "https://files.pythonhosted.org/packages/31/94/72fac03573102779920099bcac1c3b05975c2cb5f01eac609faf34bed1ca/pandas-2.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bdcd9d1167f4885211e401b3036c0c8d9e274eee67ea8d0758a256d60704cfe8", size = 10680807, upload-time = "2025-09-29T23:21:15.979Z" },
{ url = "https://files.pythonhosted.org/packages/16/87/9472cf4a487d848476865321de18cc8c920b8cab98453ab79dbbc98db63a/pandas-2.3.3-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e32e7cc9af0f1cc15548288a51a3b681cc2a219faa838e995f7dc53dbab1062d", size = 11709872, upload-time = "2025-09-29T23:21:27.165Z" },
{ url = "https://files.pythonhosted.org/packages/15/07/284f757f63f8a8d69ed4472bfd85122bd086e637bf4ed09de572d575a693/pandas-2.3.3-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:318d77e0e42a628c04dc56bcef4b40de67918f7041c2b061af1da41dcff670ac", size = 12306371, upload-time = "2025-09-29T23:21:40.532Z" },
{ url = "https://files.pythonhosted.org/packages/33/81/a3afc88fca4aa925804a27d2676d22dcd2031c2ebe08aabd0ae55b9ff282/pandas-2.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4e0a175408804d566144e170d0476b15d78458795bb18f1304fb94160cabf40c", size = 12765333, upload-time = "2025-09-29T23:21:55.77Z" },
{ url = "https://files.pythonhosted.org/packages/8d/0f/b4d4ae743a83742f1153464cf1a8ecfafc3ac59722a0b5c8602310cb7158/pandas-2.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:93c2d9ab0fc11822b5eece72ec9587e172f63cff87c00b062f6e37448ced4493", size = 13418120, upload-time = "2025-09-29T23:22:10.109Z" },
{ url = "https://files.pythonhosted.org/packages/4f/c7/e54682c96a895d0c808453269e0b5928a07a127a15704fedb643e9b0a4c8/pandas-2.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:f8bfc0e12dc78f777f323f55c58649591b2cd0c43534e8355c51d3fede5f4dee", size = 10993991, upload-time = "2025-09-29T23:25:04.889Z" },
{ url = "https://files.pythonhosted.org/packages/f9/ca/3f8d4f49740799189e1395812f3bf23b5e8fc7c190827d55a610da72ce55/pandas-2.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:75ea25f9529fdec2d2e93a42c523962261e567d250b0013b16210e1d40d7c2e5", size = 12048227, upload-time = "2025-09-29T23:22:24.343Z" },
{ url = "https://files.pythonhosted.org/packages/0e/5a/f43efec3e8c0cc92c4663ccad372dbdff72b60bdb56b2749f04aa1d07d7e/pandas-2.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:74ecdf1d301e812db96a465a525952f4dde225fdb6d8e5a521d47e1f42041e21", size = 11411056, upload-time = "2025-09-29T23:22:37.762Z" },
{ url = "https://files.pythonhosted.org/packages/46/b1/85331edfc591208c9d1a63a06baa67b21d332e63b7a591a5ba42a10bb507/pandas-2.3.3-cp313-cp313t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6435cb949cb34ec11cc9860246ccb2fdc9ecd742c12d3304989017d53f039a78", size = 11645189, upload-time = "2025-09-29T23:22:51.688Z" },
{ url = "https://files.pythonhosted.org/packages/44/23/78d645adc35d94d1ac4f2a3c4112ab6f5b8999f4898b8cdf01252f8df4a9/pandas-2.3.3-cp313-cp313t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:900f47d8f20860de523a1ac881c4c36d65efcb2eb850e6948140fa781736e110", size = 12121912, upload-time = "2025-09-29T23:23:05.042Z" },
{ url = "https://files.pythonhosted.org/packages/53/da/d10013df5e6aaef6b425aa0c32e1fc1f3e431e4bcabd420517dceadce354/pandas-2.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:a45c765238e2ed7d7c608fc5bc4a6f88b642f2f01e70c0c23d2224dd21829d86", size = 12712160, upload-time = "2025-09-29T23:23:28.57Z" },
{ url = "https://files.pythonhosted.org/packages/bd/17/e756653095a083d8a37cbd816cb87148debcfcd920129b25f99dd8d04271/pandas-2.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c4fc4c21971a1a9f4bdb4c73978c7f7256caa3e62b323f70d6cb80db583350bc", size = 13199233, upload-time = "2025-09-29T23:24:24.876Z" },
{ url = "https://files.pythonhosted.org/packages/04/fd/74903979833db8390b73b3a8a7d30d146d710bd32703724dd9083950386f/pandas-2.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:ee15f284898e7b246df8087fc82b87b01686f98ee67d85a17b7ab44143a3a9a0", size = 11540635, upload-time = "2025-09-29T23:25:52.486Z" },
{ url = "https://files.pythonhosted.org/packages/21/00/266d6b357ad5e6d3ad55093a7e8efc7dd245f5a842b584db9f30b0f0a287/pandas-2.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1611aedd912e1ff81ff41c745822980c49ce4a7907537be8692c8dbc31924593", size = 10759079, upload-time = "2025-09-29T23:26:33.204Z" },
{ url = "https://files.pythonhosted.org/packages/ca/05/d01ef80a7a3a12b2f8bbf16daba1e17c98a2f039cbc8e2f77a2c5a63d382/pandas-2.3.3-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d2cefc361461662ac48810cb14365a365ce864afe85ef1f447ff5a1e99ea81c", size = 11814049, upload-time = "2025-09-29T23:27:15.384Z" },
{ url = "https://files.pythonhosted.org/packages/15/b2/0e62f78c0c5ba7e3d2c5945a82456f4fac76c480940f805e0b97fcbc2f65/pandas-2.3.3-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ee67acbbf05014ea6c763beb097e03cd629961c8a632075eeb34247120abcb4b", size = 12332638, upload-time = "2025-09-29T23:27:51.625Z" },
{ url = "https://files.pythonhosted.org/packages/c5/33/dd70400631b62b9b29c3c93d2feee1d0964dc2bae2e5ad7a6c73a7f25325/pandas-2.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c46467899aaa4da076d5abc11084634e2d197e9460643dd455ac3db5856b24d6", size = 12886834, upload-time = "2025-09-29T23:28:21.289Z" },
{ url = "https://files.pythonhosted.org/packages/d3/18/b5d48f55821228d0d2692b34fd5034bb185e854bdb592e9c640f6290e012/pandas-2.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6253c72c6a1d990a410bc7de641d34053364ef8bcd3126f7e7450125887dffe3", size = 13409925, upload-time = "2025-09-29T23:28:58.261Z" },
{ url = "https://files.pythonhosted.org/packages/a6/3d/124ac75fcd0ecc09b8fdccb0246ef65e35b012030defb0e0eba2cbbbe948/pandas-2.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:1b07204a219b3b7350abaae088f451860223a52cfb8a6c53358e7948735158e5", size = 11109071, upload-time = "2025-09-29T23:32:27.484Z" },
{ url = "https://files.pythonhosted.org/packages/89/9c/0e21c895c38a157e0faa1fb64587a9226d6dd46452cac4532d80c3c4a244/pandas-2.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:2462b1a365b6109d275250baaae7b760fd25c726aaca0054649286bcfbb3e8ec", size = 12048504, upload-time = "2025-09-29T23:29:31.47Z" },
{ url = "https://files.pythonhosted.org/packages/d7/82/b69a1c95df796858777b68fbe6a81d37443a33319761d7c652ce77797475/pandas-2.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0242fe9a49aa8b4d78a4fa03acb397a58833ef6199e9aa40a95f027bb3a1b6e7", size = 11410702, upload-time = "2025-09-29T23:29:54.591Z" },
{ url = "https://files.pythonhosted.org/packages/f9/88/702bde3ba0a94b8c73a0181e05144b10f13f29ebfc2150c3a79062a8195d/pandas-2.3.3-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a21d830e78df0a515db2b3d2f5570610f5e6bd2e27749770e8bb7b524b89b450", size = 11634535, upload-time = "2025-09-29T23:30:21.003Z" },
{ url = "https://files.pythonhosted.org/packages/a4/1e/1bac1a839d12e6a82ec6cb40cda2edde64a2013a66963293696bbf31fbbb/pandas-2.3.3-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e3ebdb170b5ef78f19bfb71b0dc5dc58775032361fa188e814959b74d726dd5", size = 12121582, upload-time = "2025-09-29T23:30:43.391Z" },
{ url = "https://files.pythonhosted.org/packages/44/91/483de934193e12a3b1d6ae7c8645d083ff88dec75f46e827562f1e4b4da6/pandas-2.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d051c0e065b94b7a3cea50eb1ec32e912cd96dba41647eb24104b6c6c14c5788", size = 12699963, upload-time = "2025-09-29T23:31:10.009Z" },
{ url = "https://files.pythonhosted.org/packages/70/44/5191d2e4026f86a2a109053e194d3ba7a31a2d10a9c2348368c63ed4e85a/pandas-2.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3869faf4bd07b3b66a9f462417d0ca3a9df29a9f6abd5d0d0dbab15dac7abe87", size = 13202175, upload-time = "2025-09-29T23:31:59.173Z" },
]
[[package]]
name = "pluggy"
version = "1.6.0"
@@ -823,6 +870,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" },
]
[[package]]
name = "python-dateutil"
version = "2.9.0.post0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "six" },
]
sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
]
[[package]]
name = "python-dotenv"
version = "1.2.2"
@@ -841,6 +900,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/8f/cb/769cfc37177252872a45a71f3fbdde9d51b471a3f3c14bfe95dde3407386/python_multipart-0.0.29-py3-none-any.whl", hash = "sha256:2ddcc971cef266225f54f552d8fa10bcfbb1f14446caec199060daac59ff2d69", size = 29640, upload-time = "2026-05-17T17:29:45.69Z" },
]
[[package]]
name = "pytz"
version = "2026.3.post1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/fb/48/fb042503b6ca6cd271261dc559fd6432f7d8c713153e9ec5c591af4dfc1c/pytz-2026.3.post1.tar.gz", hash = "sha256:2211d3fcf9a797d3405cac96ac7f61d80e6a644f72a3309607282fe8a2010c5d", size = 319745, upload-time = "2026-07-25T15:12:07.385Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/0f/7b/39c34ca613b0b198cb866466651b26b045e2009864c5183c979a3b83f383/pytz-2026.3.post1-py2.py3-none-any.whl", hash = "sha256:dd95840dd199baea12d9cc096a1d452caa6596a1c1e4b5f3dbd1541855d5e815", size = 508283, upload-time = "2026-07-25T15:12:05.782Z" },
]
[[package]]
name = "pyyaml"
version = "6.0.3"
@@ -1143,6 +1211,7 @@ dependencies = [
{ name = "fastapi" },
{ name = "httpx" },
{ name = "openai" },
{ name = "pandas" },
{ name = "pydantic" },
{ name = "pydantic-settings" },
{ name = "pyjwt" },
@@ -1165,6 +1234,7 @@ requires-dist = [
{ name = "fastapi", specifier = "~=0.115.0" },
{ name = "httpx", specifier = "~=0.27.0" },
{ name = "openai", specifier = "~=2.41.0" },
{ name = "pandas", specifier = "~=2.3.3" },
{ name = "pydantic", specifier = "~=2.7.1" },
{ name = "pydantic-settings", specifier = "~=2.2.1" },
{ name = "pyjwt", specifier = "~=2.8.0" },
@@ -1196,6 +1266,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
]
[[package]]
name = "six"
version = "1.17.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
]
[[package]]
name = "sniffio"
version = "1.3.1"
@@ -1441,6 +1520,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" },
]
[[package]]
name = "tzdata"
version = "2026.3"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/92/ff/5a28bdfd8c3ebec42564ac7d0e54ca3db65044a9314a97f9564fa7a1e926/tzdata-2026.3.tar.gz", hash = "sha256:4a1518b8993086a7982523e071643f3c0e5f213e75b21318e78bcabfff9d1415", size = 198674, upload-time = "2026-07-10T08:50:37.887Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e5/6d/b53b99a9f2766d095985947a5782f1702cabb129a34f7a802d7197af832f/tzdata-2026.3-py2.py3-none-any.whl", hash = "sha256:dc096730c87af6cab1b171c9d532be840741ff5d459015e7f6947bd7d7e54931", size = 348168, upload-time = "2026-07-10T08:50:36.46Z" },
]
[[package]]
name = "uvicorn"
version = "0.29.0"
+9 -2
View File
@@ -14,7 +14,6 @@ api/dFGInstitutions.service.ts
api/dFGPersons.service.ts
api/dashboard.service.ts
api/funding.service.ts
api/iNSEService.service.ts
api/institutions.service.ts
api/institutionsV2.service.ts
api/keywords.service.ts
@@ -137,8 +136,8 @@ model/euProjectTopics.ts
model/extractedKeywords.ts
model/extractedKeywordsLLM.ts
model/extractedKeywordsResponse.ts
model/fieldNode.ts
model/fileUpload.ts
model/filterType.ts
model/fp7EurosciVoc.ts
model/fp7LegalBasis.ts
model/fp7Organization.ts
@@ -244,6 +243,8 @@ model/projectsSortBy.ts
model/publicationDetailByFunder.ts
model/publicationIdsByAuthorPosition.ts
model/publicationType.ts
model/publicationTypeCount.ts
model/publicationTypeCountsRequest.ts
model/publicationsByAuthorResponse.ts
model/rankedAuthor.ts
model/rankingResponse.ts
@@ -257,6 +258,7 @@ model/startCollaborationGraphResponse.ts
model/subfield.ts
model/subfieldDomain.ts
model/subfieldField.ts
model/subfieldNode.ts
model/subfieldShare.ts
model/timespan.ts
model/tokenType.ts
@@ -275,7 +277,12 @@ model/topicHeatmapField.ts
model/topicHeatmapSubfield.ts
model/topicHeatmapTopic.ts
model/topicHeatmapValue.ts
model/topicHierarchyDomain.ts
model/topicHierarchyField.ts
model/topicHierarchyResponse.ts
model/topicHierarchySubfield.ts
model/topicIds.ts
model/topicNode.ts
model/topicPageV2.ts
model/topicSortBy.ts
model/topicSubfield.ts
-3
View File
@@ -18,8 +18,6 @@ export * from './dashboard.service';
import { DashboardService } from './dashboard.service';
export * from './funding.service';
import { FundingService } from './funding.service';
export * from './iNSEService.service';
import { INSEServiceService } from './iNSEService.service';
export * from './institutions.service';
import { InstitutionsService } from './institutions.service';
export * from './institutionsV2.service';
@@ -59,7 +57,6 @@ export const APIS = [
DFGPersonsService,
DashboardService,
FundingService,
INSEServiceService,
InstitutionsService,
InstitutionsV2Service,
KeywordsService,
+899
View File
@@ -320,6 +320,133 @@ export class DashboardService extends BaseService {
);
}
/**
* Dashboard Bund Project Topics
* @endpoint get /api/dashboard/projects/bund/topics
* @param fromYear
* @param toYear
* @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 getDashboardBundProjectTopics(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<BundProjectTopics>;
public getDashboardBundProjectTopics(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<BundProjectTopics>>;
public getDashboardBundProjectTopics(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<BundProjectTopics>>;
public getDashboardBundProjectTopics(
fromYear?: number,
toYear?: 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>fromYear,
'from_year',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>toYear,
'to_year',
);
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/dashboard/projects/bund/topics`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<BundProjectTopics>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Dashboard Dfg Project Statuses
* @endpoint get /api/dashboard/projects/dfg/status
@@ -828,6 +955,133 @@ export class DashboardService extends BaseService {
);
}
/**
* Dashboard Eu Project Topics
* @endpoint get /api/dashboard/projects/eu/topics
* @param fromYear
* @param toYear
* @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 getDashboardEuProjectTopics(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<EuProjectTopics>;
public getDashboardEuProjectTopics(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<EuProjectTopics>>;
public getDashboardEuProjectTopics(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<EuProjectTopics>>;
public getDashboardEuProjectTopics(
fromYear?: number,
toYear?: 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>fromYear,
'from_year',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>toYear,
'to_year',
);
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/dashboard/projects/eu/topics`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<EuProjectTopics>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Dashboard Eu Projects
* @endpoint get /api/dashboard/statistics/projects/eu
@@ -1577,6 +1831,651 @@ export class DashboardService extends BaseService {
);
}
/**
* Dashboard Top Eu Project Authors
* @endpoint get /api/dashboard/top-authors/eu-projects
* @param fromYear
* @param toYear
* @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 getDashboardTopEuProjectAuthors(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<TopAuthorAnalysis>;
public getDashboardTopEuProjectAuthors(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<TopAuthorAnalysis>>;
public getDashboardTopEuProjectAuthors(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<TopAuthorAnalysis>>;
public getDashboardTopEuProjectAuthors(
fromYear?: number,
toYear?: 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>fromYear,
'from_year',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>toYear,
'to_year',
);
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/dashboard/top-authors/eu-projects`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<TopAuthorAnalysis>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Dashboard Top News Authors
* @endpoint get /api/dashboard/top-authors/news
* @param fromYear
* @param toYear
* @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 getDashboardTopNewsAuthors(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<TopAuthorAnalysis>;
public getDashboardTopNewsAuthors(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<TopAuthorAnalysis>>;
public getDashboardTopNewsAuthors(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<TopAuthorAnalysis>>;
public getDashboardTopNewsAuthors(
fromYear?: number,
toYear?: 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>fromYear,
'from_year',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>toYear,
'to_year',
);
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/dashboard/top-authors/news`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<TopAuthorAnalysis>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Dashboard Top Patent Authors
* @endpoint get /api/dashboard/top-authors/patents
* @param fromYear
* @param toYear
* @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 getDashboardTopPatentAuthors(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<TopAuthorAnalysis>;
public getDashboardTopPatentAuthors(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<TopAuthorAnalysis>>;
public getDashboardTopPatentAuthors(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<TopAuthorAnalysis>>;
public getDashboardTopPatentAuthors(
fromYear?: number,
toYear?: 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>fromYear,
'from_year',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>toYear,
'to_year',
);
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/dashboard/top-authors/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<TopAuthorAnalysis>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Dashboard Top Project Authors
* @endpoint get /api/dashboard/top-authors/projects
* @param fromYear
* @param toYear
* @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 getDashboardTopProjectAuthors(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<TopAuthorAnalysis>;
public getDashboardTopProjectAuthors(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<TopAuthorAnalysis>>;
public getDashboardTopProjectAuthors(
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<TopAuthorAnalysis>>;
public getDashboardTopProjectAuthors(
fromYear?: number,
toYear?: 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>fromYear,
'from_year',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>toYear,
'to_year',
);
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/dashboard/top-authors/projects`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<TopAuthorAnalysis>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Dashboard Top Work Authors
* @endpoint get /api/dashboard/top-authors/works
* @param worksPeriod
* @param fromYear
* @param toYear
* @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 getDashboardTopWorkAuthors(
worksPeriod?: 'all_time' | 'last_5_years',
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<TopAuthorAnalysis>;
public getDashboardTopWorkAuthors(
worksPeriod?: 'all_time' | 'last_5_years',
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<TopAuthorAnalysis>>;
public getDashboardTopWorkAuthors(
worksPeriod?: 'all_time' | 'last_5_years',
fromYear?: number,
toYear?: number,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<TopAuthorAnalysis>>;
public getDashboardTopWorkAuthors(
worksPeriod?: 'all_time' | 'last_5_years',
fromYear?: number,
toYear?: 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>worksPeriod,
'works_period',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>fromYear,
'from_year',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>toYear,
'to_year',
);
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/dashboard/top-authors/works`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<TopAuthorAnalysis>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Dashboard Topic Heatmap
* @endpoint get /api/dashboard/topic-heatmap
@@ -1,213 +0,0 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
})
export class INSEServiceService extends BaseService {
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
/**
* Builds the topic hierarchy cache.
* @endpoint get /api/inse-service/topics/cache
* @param pageSize Page size for each search page.
* @param saveJson Persist cache JSON to data folder.
* @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 buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
public buildTopicCache(pageSize?: number, saveJson?: boolean, 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>pageSize, 'page_size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>saveJson, 'save_json');
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/topics/cache`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Counts topic hierarchy occurrences from cache.
* @endpoint get /api/inse-service/topics/count
* @param topic Topic names (repeat parameter).
* @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 countTopicHierarchy(topic: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
public countTopicHierarchy(topic: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
public countTopicHierarchy(topic: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
public countTopicHierarchy(topic: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (topic === null || topic === undefined) {
throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (topic) {
topic.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'topic');
})
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/topics/count`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns the nested topic hierarchy (Domains -&gt; Fields -&gt; Subfields -&gt; Topics).
* @endpoint get /api/inse-service/topics/hierarchy
* @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 getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/topics/hierarchy`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
-20
View File
@@ -52,13 +52,11 @@ export class PersonsService extends BaseService {
* Generates a bio for a person by author ID.
* @endpoint get /api/inse-service/persons/bio
* @param authorId OpenAlex author ID (e.g., A5093075883)
* @param include Comma-separated list to include tags
* @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 generatePersonBio(
authorId: string,
include?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
@@ -69,7 +67,6 @@ export class PersonsService extends BaseService {
): Observable<PersonBio>;
public generatePersonBio(
authorId: string,
include?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
@@ -80,7 +77,6 @@ export class PersonsService extends BaseService {
): Observable<HttpResponse<PersonBio>>;
public generatePersonBio(
authorId: string,
include?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
@@ -91,7 +87,6 @@ export class PersonsService extends BaseService {
): Observable<HttpEvent<PersonBio>>;
public generatePersonBio(
authorId: string,
include?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
@@ -112,11 +107,6 @@ export class PersonsService extends BaseService {
<any>authorId,
'author_id',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>include,
'include',
);
let localVarHeaders = this.defaultHeaders;
@@ -403,14 +393,12 @@ export class PersonsService extends BaseService {
* @endpoint get /api/inse-service/persons/search
* @param authorId OpenAlex author ID (e.g., A5093075883)
* @param query Search query (e.g., Arman AND Arzani)
* @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost
* @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 searchPersons(
authorId?: string,
query?: string,
include?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
@@ -422,7 +410,6 @@ export class PersonsService extends BaseService {
public searchPersons(
authorId?: string,
query?: string,
include?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
@@ -434,7 +421,6 @@ export class PersonsService extends BaseService {
public searchPersons(
authorId?: string,
query?: string,
include?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
@@ -446,7 +432,6 @@ export class PersonsService extends BaseService {
public searchPersons(
authorId?: string,
query?: string,
include?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
@@ -466,11 +451,6 @@ export class PersonsService extends BaseService {
<any>query,
'query',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>include,
'include',
);
let localVarHeaders = this.defaultHeaders;
@@ -89,6 +89,7 @@ export class ProjectsService extends BaseService {
* @param sortBy The field to sort by.
* @param sortDirection The sort direction (asc or desc).
* @param fuzzy Use topic_id resolution if True, otherwise use raw keyword search.
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
@@ -108,6 +109,7 @@ export class ProjectsService extends BaseService {
sortBy?: string,
sortDirection?: string,
fuzzy?: boolean,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
@@ -132,6 +134,7 @@ export class ProjectsService extends BaseService {
sortBy?: string,
sortDirection?: string,
fuzzy?: boolean,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
@@ -156,6 +159,7 @@ export class ProjectsService extends BaseService {
sortBy?: string,
sortDirection?: string,
fuzzy?: boolean,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
@@ -180,6 +184,7 @@ export class ProjectsService extends BaseService {
sortBy?: string,
sortDirection?: string,
fuzzy?: boolean,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
@@ -295,6 +300,14 @@ export class ProjectsService extends BaseService {
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
@@ -1575,6 +1588,7 @@ export class ProjectsService extends BaseService {
* @param sortBy Sort field.
* @param sortDirection Sort direction: asc or desc.
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
@@ -1594,6 +1608,7 @@ export class ProjectsService extends BaseService {
sortBy?: string,
sortDirection?: string,
fuzzy?: boolean,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
@@ -1618,6 +1633,7 @@ export class ProjectsService extends BaseService {
sortBy?: string,
sortDirection?: string,
fuzzy?: boolean,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
@@ -1642,6 +1658,7 @@ export class ProjectsService extends BaseService {
sortBy?: string,
sortDirection?: string,
fuzzy?: boolean,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
@@ -1666,6 +1683,7 @@ export class ProjectsService extends BaseService {
sortBy?: string,
sortDirection?: string,
fuzzy?: boolean,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
@@ -1785,6 +1803,14 @@ export class ProjectsService extends BaseService {
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
@@ -1858,6 +1884,7 @@ export class ProjectsService extends BaseService {
* @param sortBy Sort field.
* @param sortDirection Sort direction: asc or desc.
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
@@ -1883,6 +1910,7 @@ export class ProjectsService extends BaseService {
sortBy?: string,
sortDirection?: string,
fuzzy?: boolean,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
@@ -1913,6 +1941,7 @@ export class ProjectsService extends BaseService {
sortBy?: string,
sortDirection?: string,
fuzzy?: boolean,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
@@ -1943,6 +1972,7 @@ export class ProjectsService extends BaseService {
sortBy?: string,
sortDirection?: string,
fuzzy?: boolean,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
@@ -1973,6 +2003,7 @@ export class ProjectsService extends BaseService {
sortBy?: string,
sortDirection?: string,
fuzzy?: boolean,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
@@ -2142,6 +2173,14 @@ export class ProjectsService extends BaseService {
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
File diff suppressed because it is too large Load Diff
@@ -35,6 +35,8 @@ import { Subfield } from '../model/subfield';
// @ts-ignore
import { Topic } from '../model/topic';
// @ts-ignore
import { TopicHierarchyResponse } from '../model/topicHierarchyResponse';
// @ts-ignore
import { TopicPageV2 } from '../model/topicPageV2';
// @ts-ignore
import { TopicSortBy } from '../model/topicSortBy';
@@ -564,6 +566,97 @@ export class TopicsV2Service extends BaseService {
});
}
/**
* Returns the full topic hierarchy tree (Domain -&gt; Field -&gt; Subfield -&gt; Topics).
* @endpoint get /api/topics/v2/hierarchy
* @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 getTopicHierarchy(
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<TopicHierarchyResponse>;
public getTopicHierarchy(
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<TopicHierarchyResponse>>;
public getTopicHierarchy(
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<TopicHierarchyResponse>>;
public getTopicHierarchy(
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/topics/v2/hierarchy`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<TopicHierarchyResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Returns a paginated list of topics for a given list of topic IDs.
* @endpoint get /api/topics/v2/topics/id
+4 -66
View File
@@ -7,70 +7,9 @@
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { FieldNode } from './fieldNode';
import { SubfieldShare } from './subfieldShare';
/**
* A primary topic within a subfield.
*/
export interface TopicNode {
/**
* The OpenAlex ID of the primary topic.
*/
id: string;
/**
* The primary-topic display name.
*/
name: string;
/**
* Number of works whose primary topic is this topic.
*/
count: number;
}
/**
* A subfield within a field, with its primary topics.
*/
export interface SubfieldNode {
/**
* The OpenAlex ID of the subfield.
*/
id: string;
/**
* The subfield display name.
*/
name: string;
/**
* Number of works whose primary topic belongs to this subfield.
*/
count: number;
/**
* Primary topics within this subfield, largest first.
*/
topics: Array<TopicNode>;
}
/**
* A field with its subfields, top of the primary-topic hierarchy.
*/
export interface FieldNode {
/**
* The OpenAlex ID of the field.
*/
id: string;
/**
* The field display name.
*/
name: string;
/**
* Number of works whose primary topic belongs to this field.
*/
count: number;
/**
* Subfields within this field, largest first.
*/
subfields: Array<SubfieldNode>;
}
export interface AuthorTopicProfile {
/**
* The OpenAlex ID of the author.
@@ -89,7 +28,7 @@ export interface AuthorTopicProfile {
*/
matched_works: number;
/**
* Matched works where one of the searched topics is the work\'s primary topic (only meaningful for filter_type \'topic\').
* Matched works where one of the searched topics is the work\'s primary topic.
*/
primary_topic_matches: number;
/**
@@ -109,8 +48,7 @@ export interface AuthorTopicProfile {
*/
subfields?: Array<SubfieldShare>;
/**
* Field -> subfield -> topic hierarchy over all works, by primary topic,
* each level largest first. Drives the interactive topic treemap.
* Field -> subfield -> topic hierarchy over all works, by primary topic, each level largest first. Drives the interactive topic treemap.
*/
field_tree: Array<FieldNode>;
field_tree?: Array<FieldNode>;
}
@@ -70,14 +70,6 @@ export interface AuthorTopicStats {
industry_works_count?: number;
first_year?: number | null;
last_year?: number | null;
/**
* Number of the author\'s topic works where the matched keyword\'s relevance score is above 0.8.
*/
relevance_above_80_count?: number;
/**
* Average matched-keyword relevance score (0-1) over the author\'s topic works.
*/
avg_relevance?: number;
/**
* Number of the author\'s topic works where they are the first author.
*/
@@ -1,33 +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.
*/
/**
* Highlighted matching fragments from a BUND project search.
*/
export interface BundProjectHighlight {
/**
* Highlights from the Elasticsearch field \"Verbundprojekt\".
*/
joint_project?: Array<string>;
/**
* Highlights from the Elasticsearch field \"Thema\".
*/
topic?: Array<string>;
/**
* Highlights from the Elasticsearch field \"Zuwendungsempfänger\".
*/
recipient?: Array<string>;
/**
* Highlights from the Elasticsearch field \"Ausführende Stelle\".
*/
implementing_agency?: Array<string>;
export interface BundProjectHighlight {
/**
* Highlights from the Elasticsearch field \"Verbundprojekt\".
*/
joint_project?: Array<string>;
/**
* Highlights from the Elasticsearch field \"Thema\".
*/
topic?: Array<string>;
/**
* Highlights from the Elasticsearch field \"Zuwendungsempfänger\".
*/
recipient?: Array<string>;
/**
* Highlights from the Elasticsearch field \"Ausführende Stelle\".
*/
executing_agency?: Array<string>;
}
@@ -25,7 +25,7 @@ export interface BundProjectSummary {
place?: string | null;
state?: string | null;
country?: string | null;
implementing_agency?: string | null;
executing_agency?: string | null;
topic?: string | null;
performance_plan_system?: string | null;
performance_plan_system_text?: string | null;
+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 { SubfieldNode } from './subfieldNode';
export interface FieldNode {
/**
* The OpenAlex ID of the field.
*/
id: string;
/**
* The field display name.
*/
name: string;
/**
* Number of works whose primary topic belongs to this field.
*/
count: number;
/**
* Subfields within this field, largest first.
*/
subfields?: Array<SubfieldNode>;
}
+24 -24
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -11,31 +11,31 @@ import { InstitutionIds } from './institutionIds';
import { AuthorCountsByYearInner } from './authorCountsByYearInner';
import { AuthorSummaryStats } from './authorSummaryStats';
import { InstitutionGeo } from './institutionGeo';
import { DehydratedInstitution } from './dehydratedInstitution';
/**
* A university, research organization, or other affiliation
*/
export interface Institution {
id?: string | null;
ror?: string | null;
display_name?: string | null;
country_code?: string | null;
type?: string | null;
homepage_url?: string | null;
image_url?: string | null;
image_thumbnail_url?: string | null;
display_name_acronyms?: Array<string> | null;
display_name_alternatives?: Array<string> | null;
works_count?: number | null;
cited_by_count?: number | null;
summary_stats?: AuthorSummaryStats | null;
geo?: InstitutionGeo | null;
lineage?: Array<string> | null;
ids?: InstitutionIds | null;
counts_by_year?: Array<AuthorCountsByYearInner> | null;
works_api_url?: string | null;
created_date?: string | null;
updated_date?: string | null;
export interface Institution {
id?: string | null;
ror?: string | null;
display_name?: string | null;
country_code?: string | null;
type?: string | null;
homepage_url?: string | null;
image_url?: string | null;
image_thumbnail_url?: string | null;
display_name_acronyms?: Array<string> | null;
display_name_alternatives?: Array<string> | null;
works_count?: number | null;
cited_by_count?: number | null;
summary_stats?: AuthorSummaryStats | null;
geo?: InstitutionGeo | null;
lineage?: Array<string> | null;
ids?: InstitutionIds | null;
counts_by_year?: Array<AuthorCountsByYearInner> | null;
works_api_url?: string | null;
associated_institutions?: Array<DehydratedInstitution> | null;
created_date?: string | null;
updated_date?: string | null;
}
@@ -8,7 +8,6 @@
* Do not edit the class manually.
*/
import { Timespan } from './timespan';
import { FilterType } from './filterType';
import { CareerStage } from './careerStage';
import { KeywordOperator } from './keywordOperator';
import { PublicationType } from './publicationType';
@@ -25,9 +24,9 @@ export interface KeywordToAuthorRequest {
*/
operator?: KeywordOperator;
/**
* What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic display names). Defaults to \'keyword\'.
* How the \'keywords\' values are matched: True means they are OpenAlex topic ids matched against the work\'s topics, False means they are raw keywords matched as phrases in the work\'s title, abstract, keywords and topic names. Defaults to False.
*/
filter_type?: FilterType;
fuzzy?: boolean;
/**
* Weights for the ranking metrics. Required.
*/
+7 -1
View File
@@ -102,8 +102,8 @@ export * from './euProjectTopics';
export * from './extractedKeywords';
export * from './extractedKeywordsLLM';
export * from './extractedKeywordsResponse';
export * from './fieldNode';
export * from './fileUpload';
export * from './filterType';
export * from './fp7EurosciVoc';
export * from './fp7LegalBasis';
export * from './fp7Organization';
@@ -223,6 +223,7 @@ export * from './startCollaborationGraphResponse';
export * from './subfield';
export * from './subfieldDomain';
export * from './subfieldField';
export * from './subfieldNode';
export * from './subfieldShare';
export * from './timespan';
export * from './tokenType';
@@ -241,7 +242,12 @@ export * from './topicHeatmapField';
export * from './topicHeatmapSubfield';
export * from './topicHeatmapTopic';
export * from './topicHeatmapValue';
export * from './topicHierarchyDomain';
export * from './topicHierarchyField';
export * from './topicHierarchyResponse';
export * from './topicHierarchySubfield';
export * from './topicIds';
export * from './topicNode';
export * from './topicPageV2';
export * from './topicSortBy';
export * from './topicSubfield';
@@ -8,7 +8,6 @@
* Do not edit the class manually.
*/
import { Timespan } from './timespan';
import { FilterType } from './filterType';
import { CareerStage } from './careerStage';
import { KeywordOperator } from './keywordOperator';
@@ -22,9 +21,9 @@ export interface PublicationTypeCountsRequest {
*/
operator?: KeywordOperator;
/**
* What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic display names). Defaults to \'keyword\'.
* How the \'keywords\' values are matched: True means they are OpenAlex topic ids matched against the work\'s topics, False means they are raw keywords matched as phrases in the work\'s title, abstract, keywords and topic names. Defaults to False.
*/
filter_type?: FilterType;
fuzzy?: boolean;
/**
* Optional filter: only count works of authors in one of these career stages. Empty = no filter.
*/
@@ -1,42 +1,37 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Timespan } from './timespan';
import { FilterType } from './filterType';
import { KeywordOperator } from './keywordOperator';
import { PublicationType } from './publicationType';
export interface SelectedAuthorsRequest {
/**
* OpenAlex IDs of the authors to rank.
*/
author_ids: Array<string>;
/**
* One or more keywords defining the topic.
*/
keywords: Array<string>;
/**
* How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'.
*/
operator?: KeywordOperator;
/**
* What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic ids). Defaults to \'keyword\'.
*/
filter_type?: FilterType;
/**
* Optional filter: only count works of these publication types. Empty = no filter.
*/
publication_types?: Array<PublicationType>;
timespan?: Timespan | null;
export interface SelectedAuthorsRequest {
/**
* OpenAlex IDs of the authors to rank.
*/
author_ids: Array<string>;
/**
* One or more keywords defining the topic.
*/
keywords: Array<string>;
/**
* How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'.
*/
operator?: KeywordOperator;
/**
* How the \'keywords\' values are matched: True means they are OpenAlex topic ids matched against the work\'s topics, False means they are raw keywords matched as phrases in the work\'s title, abstract, keywords and topic names. Defaults to False.
*/
fuzzy?: boolean;
/**
* Optional filter: only count works of these publication types. Empty = no filter.
*/
publication_types?: Array<PublicationType>;
timespan?: Timespan | null;
}
export namespace SelectedAuthorsRequest {
}
export namespace SelectedAuthorsRequest {}
+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 { TopicNode } from './topicNode';
export interface SubfieldNode {
/**
* The OpenAlex ID of the subfield.
*/
id: string;
/**
* The subfield display name.
*/
name: string;
/**
* Number of works whose primary topic belongs to this subfield.
*/
count: number;
/**
* Primary topics within this subfield, largest first.
*/
topics?: Array<TopicNode>;
}
@@ -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 { TopicHierarchyField } from './topicHierarchyField';
export interface TopicHierarchyDomain {
id?: string | null;
name: string;
fields?: Array<TopicHierarchyField>;
}
@@ -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 { TopicHierarchySubfield } from './topicHierarchySubfield';
export interface TopicHierarchyField {
id?: string | null;
name: string;
subfields?: Array<TopicHierarchySubfield>;
}
@@ -1,17 +1,14 @@
/**
* 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 { TopicHierarchyDomain } from './topicHierarchyDomain';
export const FilterType = {
Keyword: 'keyword',
Topic: 'topic'
} as const;
export type FilterType = typeof FilterType[keyof typeof FilterType];
export interface TopicHierarchyResponse {
domains?: Array<TopicHierarchyDomain>;
}
@@ -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 { Topic } from './topic';
export interface TopicHierarchySubfield {
id?: string | null;
name: string;
topics?: Array<Topic>;
}
+24
View File
@@ -0,0 +1,24 @@
/**
* 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 TopicNode {
/**
* The OpenAlex ID of the primary topic.
*/
id: string;
/**
* The primary-topic display name.
*/
name: string;
/**
* Number of works whose primary topic is this topic.
*/
count: number;
}
+6 -2
View File
@@ -788,7 +788,9 @@ export const routes: Routes = [
},
runGuardsAndResolvers: (from, to) => {
return Object.values(workQueryParamKeys).some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
(key) =>
from.queryParamMap.getAll(key).join(',') !==
to.queryParamMap.getAll(key).join(','),
);
},
},
@@ -852,7 +854,9 @@ export const routes: Routes = [
),
runGuardsAndResolvers: (from, to) => {
return Object.values(workQueryParamKeys).some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
(key) =>
from.queryParamMap.getAll(key).join(',') !==
to.queryParamMap.getAll(key).join(','),
);
},
resolve: {
@@ -18,6 +18,12 @@ import {
} from '@angular/cdk/overlay';
import { ComponentPortal, ComponentType } from '@angular/cdk/portal';
const STICKY_TOOLBAR_HEIGHT_PX = 76;
const EDGE_MARGIN_PX = 8;
const TOP_MARGIN_PX = STICKY_TOOLBAR_HEIGHT_PX + EDGE_MARGIN_PX;
const MIN_PANEL_WIDTH_PX = 240;
const MIN_PANEL_HEIGHT_PX = 150;
type UnwrapInputSignals<T> = {
[K in keyof T]: T[K] extends InputSignal<infer V> ? V : T[K];
};
@@ -27,6 +33,10 @@ type UnwrapInputSignals<T> = {
standalone: true,
})
export class ComponentTooltipDirective<T extends object> implements OnDestroy {
private static readonly openInstances = new Set<
ComponentTooltipDirective<any>
>();
readonly component = input.required<ComponentType<T>>({
alias: 'appComponentTooltip',
});
@@ -43,8 +53,10 @@ export class ComponentTooltipDirective<T extends object> implements OnDestroy {
private overlayRef: OverlayRef | null = null;
private componentRef: ComponentRef<T> | null = null;
private computedMaxWidthPx = MIN_PANEL_WIDTH_PX;
private showTimeout?: ReturnType<typeof setTimeout>;
private hideTimeout?: ReturnType<typeof setTimeout>;
private dismissTimeout?: ReturnType<typeof setTimeout>;
private isOverHost = false;
private isOverOverlay = false;
@@ -84,60 +96,188 @@ export class ComponentTooltipDirective<T extends object> implements OnDestroy {
this.scheduleHide();
}
@HostListener('click')
onHostClick(): void {
this.scheduleDismiss();
}
private scheduleDismiss(): void {
clearTimeout(this.dismissTimeout);
this.dismissTimeout = setTimeout(() => this.dismiss());
}
private dismiss(): void {
clearTimeout(this.showTimeout);
clearTimeout(this.hideTimeout);
this.isOverHost = false;
this.isOverOverlay = false;
this.hide();
}
private scheduleHide(): void {
clearTimeout(this.hideTimeout);
this.hideTimeout = setTimeout(() => {
if (!this.isOverHost && !this.isOverOverlay) {
this.hide();
if (this.isOverHost || this.isOverOverlay) {
return;
}
if (this.hasOpenDescendantTooltip()) {
this.scheduleHide();
return;
}
this.hide();
}, this.tooltipHideDelay());
}
private hasOpenDescendantTooltip(): boolean {
const paneElement = this.overlayRef?.overlayElement;
if (!paneElement) return false;
for (const other of ComponentTooltipDirective.openInstances) {
if (other === this) continue;
if (paneElement.contains(other.elementRef.nativeElement)) {
return true;
}
}
return false;
}
private clampedOffsetX(
alignToStart: boolean,
triggerRect: DOMRect,
actualWidthPx: number,
viewportWidth: number,
): number {
const desiredLeft = alignToStart
? triggerRect.left
: triggerRect.right - actualWidthPx;
const minLeft = EDGE_MARGIN_PX;
const maxLeft = Math.max(
EDGE_MARGIN_PX,
viewportWidth - actualWidthPx - EDGE_MARGIN_PX,
);
const clampedLeft = Math.min(Math.max(desiredLeft, minLeft), maxLeft);
const anchor = alignToStart ? triggerRect.left : triggerRect.right;
return clampedLeft - anchor + (alignToStart ? 0 : actualWidthPx);
}
private computePositioning(): {
positions: ConnectedPosition[];
maxWidthPx: number;
maxHeightPx: number;
} {
const triggerRect = this.elementRef.nativeElement.getBoundingClientRect();
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const spaceAbove = triggerRect.top - TOP_MARGIN_PX;
const spaceBelow = viewportHeight - triggerRect.bottom - EDGE_MARGIN_PX;
const spaceLeft = triggerRect.left - EDGE_MARGIN_PX;
const spaceRight = viewportWidth - triggerRect.right - EDGE_MARGIN_PX;
const preferBelow = spaceBelow >= spaceAbove;
const preferStartAligned = spaceRight >= spaceLeft;
const bestVerticalSpace = Math.max(spaceAbove, spaceBelow);
const bestHorizontalSpace = Math.max(spaceLeft, spaceRight);
const maxHeightPx = Math.max(bestVerticalSpace, MIN_PANEL_HEIGHT_PX);
const maxWidthPx = Math.max(bestHorizontalSpace, MIN_PANEL_WIDTH_PX);
const actualWidthPx = Math.min(
maxWidthPx,
this.resolveConfiguredWidthPx(this.tooltipMaxWidth()) ?? maxWidthPx,
);
const primaryOffsetX = this.clampedOffsetX(
preferStartAligned,
triggerRect,
actualWidthPx,
viewportWidth,
);
const secondaryOffsetX = this.clampedOffsetX(
!preferStartAligned,
triggerRect,
actualWidthPx,
viewportWidth,
);
const verticalPrimary: ConnectedPosition = preferBelow
? {
originX: preferStartAligned ? 'start' : 'end',
originY: 'bottom',
overlayX: preferStartAligned ? 'start' : 'end',
overlayY: 'top',
offsetX: primaryOffsetX,
offsetY: EDGE_MARGIN_PX,
}
: {
originX: preferStartAligned ? 'start' : 'end',
originY: 'top',
overlayX: preferStartAligned ? 'start' : 'end',
overlayY: 'bottom',
offsetX: primaryOffsetX,
offsetY: -EDGE_MARGIN_PX,
};
const verticalSecondary: ConnectedPosition = preferBelow
? {
originX: preferStartAligned ? 'end' : 'start',
originY: 'top',
overlayX: preferStartAligned ? 'end' : 'start',
overlayY: 'bottom',
offsetX: secondaryOffsetX,
offsetY: -EDGE_MARGIN_PX,
}
: {
originX: preferStartAligned ? 'end' : 'start',
originY: 'bottom',
overlayX: preferStartAligned ? 'end' : 'start',
overlayY: 'top',
offsetX: secondaryOffsetX,
offsetY: EDGE_MARGIN_PX,
};
const sidePrimary: ConnectedPosition = preferStartAligned
? {
originX: 'end',
originY: 'center',
overlayX: 'start',
overlayY: 'center',
offsetX: EDGE_MARGIN_PX,
}
: {
originX: 'start',
originY: 'center',
overlayX: 'end',
overlayY: 'center',
offsetX: -EDGE_MARGIN_PX,
};
const positions: ConnectedPosition[] = [
verticalPrimary,
verticalSecondary,
sidePrimary,
];
return { positions, maxWidthPx, maxHeightPx };
}
private show(): void {
if (this.overlayRef?.hasAttached()) return;
const positions: ConnectedPosition[] = [
{
originX: 'center',
originY: 'top',
overlayX: 'center',
overlayY: 'bottom',
offsetY: -8,
},
{
originX: 'center',
originY: 'bottom',
overlayX: 'center',
overlayY: 'top',
offsetY: 8,
},
{
originX: 'end',
originY: 'center',
overlayX: 'start',
overlayY: 'center',
offsetX: 8,
},
{
originX: 'start',
originY: 'center',
overlayX: 'end',
overlayY: 'center',
offsetX: -8,
},
];
const { positions, maxWidthPx, maxHeightPx } = this.computePositioning();
this.computedMaxWidthPx = maxWidthPx;
const positionStrategy = this.overlayPositionBuilder
.flexibleConnectedTo(this.elementRef)
.withPositions(positions)
.withFlexibleDimensions(false)
.withViewportMargin(12)
.withViewportMargin(EDGE_MARGIN_PX)
.withPush(true);
this.overlayRef = this.overlay.create({
positionStrategy,
scrollStrategy: this.overlay.scrollStrategies.reposition(),
panelClass: 'app-tooltip-panel',
maxWidth: this.tooltipMaxWidth() ?? 'calc(100vw - 24px)',
maxWidth: this.resolveMaxWidth(this.tooltipMaxWidth()),
maxHeight: `${maxHeightPx}px`,
});
const portal = new ComponentPortal(this.component(), null, this.injector);
@@ -155,18 +295,35 @@ export class ComponentTooltipDirective<T extends object> implements OnDestroy {
overlayElement.addEventListener('mouseenter', this.onOverlayEnter);
overlayElement.addEventListener('mouseleave', this.onOverlayLeave);
overlayElement.addEventListener('click', this.onOverlayClick, true);
ComponentTooltipDirective.openInstances.add(this);
}
private applyMaxWidth(
element: HTMLElement,
maxWidth: string | number | null,
): void {
if (maxWidth === null) {
element.style.maxWidth = '';
return;
element.style.maxWidth = this.resolveMaxWidth(maxWidth);
}
private resolveMaxWidth(maxWidth: string | number | null): string {
const configuredPx = this.resolveConfiguredWidthPx(maxWidth);
if (configuredPx === null) {
return typeof maxWidth === 'number'
? `${maxWidth}px`
: (maxWidth ?? `${this.computedMaxWidthPx}px`);
}
element.style.maxWidth =
typeof maxWidth === 'number' ? `${maxWidth}px` : maxWidth;
return `${Math.min(configuredPx, this.computedMaxWidthPx)}px`;
}
private resolveConfiguredWidthPx(
maxWidth: string | number | null,
): number | null {
if (maxWidth === null) return null;
if (typeof maxWidth === 'number') return maxWidth;
const trimmed = maxWidth.trim();
return trimmed.endsWith('px') ? parseFloat(trimmed) : null;
}
private readonly onOverlayEnter = (): void => {
@@ -179,19 +336,27 @@ export class ComponentTooltipDirective<T extends object> implements OnDestroy {
this.scheduleHide();
};
private readonly onOverlayClick = (): void => {
this.scheduleDismiss();
};
private hide(): void {
if (this.overlayRef) {
const overlayElement = this.overlayRef.overlayElement;
overlayElement.removeEventListener('mouseenter', this.onOverlayEnter);
overlayElement.removeEventListener('mouseleave', this.onOverlayLeave);
overlayElement.removeEventListener('click', this.onOverlayClick, true);
this.overlayRef.detach();
}
this.componentRef = null;
ComponentTooltipDirective.openInstances.delete(this);
}
ngOnDestroy(): void {
clearTimeout(this.showTimeout);
clearTimeout(this.hideTimeout);
clearTimeout(this.dismissTimeout);
ComponentTooltipDirective.openInstances.delete(this);
this.overlayRef?.dispose();
}
}
@@ -61,7 +61,7 @@
<mat-dialog-actions align="end">
<button mat-button type="button" (click)="close()">Abbrechen</button>
<button mat-flat-button color="primary" type="button" (click)="submit()">
<mat-icon>save</mat-icon>
<mat-icon>{{ SAVE_ICON }}</mat-icon>
Speichern
</button>
</mat-dialog-actions>
@@ -21,6 +21,7 @@ import {
InseAccountManagementModelOrganizationProfile,
UserRole,
} from '../../api';
import { SAVE_ICON } from '../../shared/ui/icons';
export type AccountDialogMode = 'create' | 'edit';
@@ -71,6 +72,8 @@ export type AccountDialogResult =
standalone: true,
})
export class AccountDialogComponent {
readonly SAVE_ICON = SAVE_ICON;
private readonly dialogRef =
inject<
MatDialogRef<AccountDialogComponent, AccountDialogResult | undefined>
@@ -31,7 +31,7 @@
type="button"
matTooltip="Neuen Account anlegen"
(click)="startCreate()">
<mat-icon>person_add</mat-icon>
<mat-icon>{{ PERSON_ADD_ICON }}</mat-icon>
Neuer Account
</button>
}
@@ -68,7 +68,7 @@
type="button"
aria-label="Bearbeiten"
(click)="startEdit(row)">
<mat-icon>edit</mat-icon>
<mat-icon>{{ EDIT_ICON }}</mat-icon>
</button>
<button
mat-icon-button
@@ -76,7 +76,7 @@
aria-label="Impersonate"
[disabled]="!canImpersonate(row)"
(click)="impersonate(row)">
<mat-icon>switch_account</mat-icon>
<mat-icon>{{ SWITCH_ACCOUNT_ICON }}</mat-icon>
</button>
<button
mat-icon-button
@@ -84,7 +84,9 @@
[attr.aria-label]="row.activated ? 'Deaktivieren' : 'Aktivieren'"
[disabled]="row.is_current || row.deleted"
(click)="toggleAccountActivation(row)">
<mat-icon>{{ row.activated ? 'person_off' : 'person_check' }}</mat-icon>
<mat-icon>{{
row.activated ? PERSON_OFF_ICON : PERSON_CHECK_ICON
}}</mat-icon>
</button>
<button
mat-icon-button
@@ -92,7 +94,7 @@
aria-label="Deaktivieren"
[disabled]="row.is_current || row.deleted"
(click)="deleteAccount(row)">
<mat-icon>delete</mat-icon>
<mat-icon>{{ DELETE_ICON }}</mat-icon>
</button>
</div>
</ng-template>
@@ -44,6 +44,14 @@ import {
UserRole,
} from '../../api';
import { StatusPipe } from '../../shared/pipes/status.pipe';
import {
DELETE_ICON,
EDIT_ICON,
PERSON_ADD_ICON,
PERSON_CHECK_ICON,
PERSON_OFF_ICON,
SWITCH_ACCOUNT_ICON,
} from '../../shared/ui/icons';
@Component({
selector: 'app-accounts',
@@ -71,6 +79,13 @@ import { StatusPipe } from '../../shared/pipes/status.pipe';
standalone: true,
})
export class AccountsComponent implements OnInit {
readonly PERSON_ADD_ICON = PERSON_ADD_ICON;
readonly EDIT_ICON = EDIT_ICON;
readonly SWITCH_ACCOUNT_ICON = SWITCH_ACCOUNT_ICON;
readonly PERSON_CHECK_ICON = PERSON_CHECK_ICON;
readonly PERSON_OFF_ICON = PERSON_OFF_ICON;
readonly DELETE_ICON = DELETE_ICON;
protected readonly credentialService = inject(CredentialService);
private readonly snackBar = inject(MatSnackBar);
private readonly router = inject(Router);
@@ -58,7 +58,7 @@
"
(click)="showPassword = !showPassword">
<mat-icon>{{
showPassword ? 'visibility' : 'visibility_off'
showPassword ? VISIBILITY_ICON : VISIBILITY_OFF_ICON
}}</mat-icon>
</button>
@if (credentialsForm.controls.password.hasError('required')) {
@@ -91,7 +91,7 @@
} @else {
<form class="login-form" [formGroup]="otkForm" (ngSubmit)="login()">
<div class="code-intro">
<mat-icon>mark_email_unread</mat-icon>
<mat-icon>{{ EMAIL_UNREAD_ICON }}</mat-icon>
<div>
<strong>Code eingeben</strong>
<span>
@@ -123,7 +123,7 @@
class="expiry"
[class.expiry--expired]="codeExpiresIn === 0"
aria-live="polite">
<mat-icon>timer</mat-icon>
<mat-icon>{{ TIMER_ICON }}</mat-icon>
@if (codeExpiresIn > 0) {
<span>Code läuft in {{ formatCountdown() }} ab.</span>
} @else {
@@ -15,6 +15,12 @@ import { finalize, Subscription } from 'rxjs';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { Router, RouterLink } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import {
EMAIL_UNREAD_ICON,
TIMER_ICON,
VISIBILITY_ICON,
VISIBILITY_OFF_ICON,
} from '../../shared/ui/icons';
type LoginStep = 'credentials' | 'otk';
@@ -35,6 +41,11 @@ type LoginStep = 'credentials' | 'otk';
standalone: true,
})
export class AppLoginComponent implements OnDestroy {
readonly EMAIL_UNREAD_ICON = EMAIL_UNREAD_ICON;
readonly TIMER_ICON = TIMER_ICON;
readonly VISIBILITY_ICON = VISIBILITY_ICON;
readonly VISIBILITY_OFF_ICON = VISIBILITY_OFF_ICON;
credentialsForm = new FormGroup({
email: new FormControl<string>('', [Validators.required, Validators.email]),
password: new FormControl<string>('', [
@@ -6,7 +6,7 @@
<p>Gespeicherte Personen für den schnellen Zugriff.</p>
</div>
<div class="bookmark-count">
<mat-icon>bookmarks</mat-icon>
<mat-icon>{{ BOOKMARKS_ICON }}</mat-icon>
<strong>{{ persons().length }}</strong>
<span>Personen</span>
</div>
@@ -15,7 +15,7 @@
@if (loading()) {
<app-loading
text="Bookmarks werden geladen …"
icon="bookmarks"
[icon]="BOOKMARKS_ICON"
[size]="60"
[diameter]="60" />
} @else if (persons().length) {
@@ -30,7 +30,7 @@
</section>
} @else {
<section class="empty-state">
<mat-icon>bookmark_border</mat-icon>
<mat-icon>{{ BOOKMARK_BORDER_ICON }}</mat-icon>
<h2>Noch keine Bookmarks</h2>
<p>
Speichere Personen über das Bookmark-Symbol auf einer Personenkarte.
@@ -8,6 +8,7 @@ import { CustomAuthor, PersonsService } from '../../api';
import { BookmarkService } from '../../shared/services/bookmark.service';
import { PersonCardComponent } from '../person-card/person-card.component';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { BOOKMARKS_ICON, BOOKMARK_BORDER_ICON } from '../../shared/ui/icons';
const PERSON_INCLUDE_TAGS =
'display_name,works_count,cited_by_count,summary_stats,ids,' +
@@ -22,6 +23,9 @@ const PERSON_INCLUDE_TAGS =
styleUrl: './bookmarks.component.scss',
})
export class BookmarksComponent {
readonly BOOKMARKS_ICON = BOOKMARKS_ICON;
readonly BOOKMARK_BORDER_ICON = BOOKMARK_BORDER_ICON;
readonly bookmarkService = inject(BookmarkService);
private readonly personsService = inject(PersonsService);
private readonly destroyRef = inject(DestroyRef);
@@ -1,7 +1,7 @@
@if (visible()) {
<mat-card appearance="outlined" class="research-profile-card">
<mat-card-header class="profile-header">
<mat-icon class="profile-icon">science</mat-icon>
<mat-icon class="profile-icon">{{ SCIENCE_ICON }}</mat-icon>
<div class="profile-heading">
<mat-card-title>Forschungsprofil</mat-card-title>
<mat-card-subtitle>
@@ -11,6 +11,7 @@ import {
AuthorCategoryPieComponent,
buildAuthorCategoryLegend,
} from './author-category-pie.component';
import { SCIENCE_ICON } from '../../../shared/ui/icons';
export interface ResearchProfileAuthor {
authorId: string;
@@ -36,6 +37,8 @@ interface AuthorOrientationView {
styleUrl: './author-research-profile.component.scss',
})
export class AuthorResearchProfileComponent {
readonly SCIENCE_ICON = SCIENCE_ICON;
private readonly chartTheme = inject(ChartThemeService);
authors = input.required<ResearchProfileAuthor[]>();
@@ -22,7 +22,7 @@
<div class="meta-row">
<span class="meta-label">Betrachteter Zeitraum:</span>
<app-chip color="secondary">
<mat-icon>date_range</mat-icon>
<mat-icon>{{ DATE_RANGE_ICON }}</mat-icon>
{{ span.from }}–{{ span.to }}
</app-chip>
</div>
@@ -42,7 +42,7 @@
]"
title="Zur Autor:innen-Seite">
{{ author.name }}
<mat-icon>open_in_new</mat-icon>
<mat-icon>{{ OPEN_IN_NEW_ICON }}</mat-icon>
</a>
</app-chip>
}
@@ -181,7 +181,7 @@
]"
title="Zur Autor:innen-Seite">
{{ author.name }}
<mat-icon>open_in_new</mat-icon>
<mat-icon>{{ OPEN_IN_NEW_ICON }}</mat-icon>
</a>
</app-chip>
</th>
@@ -198,7 +198,7 @@
<mat-icon
class="icon-small name-match-star"
aria-hidden="true">
star
{{ STAR_ICON }}
</mat-icon>
}
</span>
@@ -257,7 +257,7 @@
</div>
@if (hasNameMatchedRow(rows)) {
<p class="name-match-note">
<mat-icon class="icon-small">star</mat-icon>
<mat-icon class="icon-small">{{ STAR_ICON }}</mat-icon>
Diese Kennzahlen basieren auf einem automatischen Namensabgleich mit
externen Quellen, wodurch es in Einzelfällen zu Fehlzuordnungen kommen
kann.
@@ -220,12 +220,6 @@ app-chip mat-icon {
&.pos-last {
color: var(--sg-primary);
}
&.rel-count {
color: var(--sg-blue-highlight);
}
&.rel-avg {
color: var(--sg-blue-highlight);
}
&.cit-total {
color: var(--sg-error);
}
@@ -29,6 +29,11 @@ import { ChipComponent } from '../../shared/ui/chip/chip.component';
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
import { ChartThemeService } from '../../shared/services/chart-theme.service';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
import {
DATE_RANGE_ICON,
OPEN_IN_NEW_ICON,
STAR_ICON,
} from '../../shared/ui/icons';
import {
AUTHOR_COLORS,
OTHER_COLOR,
@@ -61,9 +66,6 @@ interface AuthorSummary {
// active years within the topic
firstYear: number | null;
lastYear: number | null;
// topic-relevance (matched keyword score)
relevanceAbove80: number | null;
avgRelevance: number | null;
// author-position split (first / middle / last)
firstAuthor: number | null;
middleAuthor: number | null;
@@ -135,6 +137,10 @@ interface SegmentDef {
styleUrl: './compare-authors.component.scss',
})
export class CompareAuthorsComponent implements OnInit {
readonly DATE_RANGE_ICON = DATE_RANGE_ICON;
readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON;
readonly STAR_ICON = STAR_ICON;
private readonly route = inject(ActivatedRoute);
private readonly rankingService = inject(RankingService);
private readonly topicsService = inject(TopicsService);
@@ -218,8 +224,6 @@ export class CompareAuthorsComponent implements OnInit {
: null,
firstYear: t?.first_year ?? null,
lastYear: t?.last_year ?? null,
relevanceAbove80: t?.relevance_above_80_count ?? null,
avgRelevance: t?.avg_relevance ?? null,
firstAuthor: t?.first_author_count ?? null,
middleAuthor: t?.middle_author_count ?? null,
lastAuthor: t?.last_author_count ?? null,
@@ -310,23 +314,6 @@ export class CompareAuthorsComponent implements OnInit {
},
],
),
this.buildGroupRow(
'Themen-Relevanz',
'Match-Score der Keywords: Werke > 80% | Ø über alle',
[
{
label: '> 80%',
colorClass: 'rel-count',
select: (a) => a.relevanceAbove80,
},
{
label: 'Ø',
colorClass: 'rel-avg',
decimals: true,
select: (a) => a.avgRelevance,
},
],
),
this.buildGroupRow(
'Autor-Position',
'Werke nach Position (Erst | Mittel | Letzt)',
@@ -442,17 +429,17 @@ export class CompareAuthorsComponent implements OnInit {
institution_id: profile.author_id,
organization_name: profile.display_name,
years: [],
fields: profile.field_tree.map((field) => ({
fields: (profile.field_tree ?? []).map((field) => ({
id: field.id,
name: field.name,
total: field.count,
values: [],
subfields: field.subfields.map((subfield) => ({
subfields: (field.subfields ?? []).map((subfield) => ({
id: subfield.id,
name: subfield.name,
total: subfield.count,
values: [],
topics: subfield.topics.map((topic) => ({
topics: (subfield.topics ?? []).map((topic) => ({
id: topic.id,
name: topic.name,
total: topic.count,
@@ -756,6 +743,8 @@ export class CompareAuthorsComponent implements OnInit {
const rawAuthors = this.route.snapshot.queryParamMap.get('authors') ?? '';
const rawKeywords = this.route.snapshot.queryParamMap.get('keywords') ?? '';
const rawOperator = this.route.snapshot.queryParamMap.get('operator');
const rawTopics = this.route.snapshot.queryParamMap.get('topics') ?? '';
const fuzzy = this.route.snapshot.queryParamMap.get('fuzzy') === 'true';
const rawPubType = this.route.snapshot.queryParamMap.get('pubType');
const rawTFrom = this.route.snapshot.queryParamMap.get('tFrom');
const rawTTo = this.route.snapshot.queryParamMap.get('tTo');
@@ -784,11 +773,13 @@ export class CompareAuthorsComponent implements OnInit {
const fullIds = authorIds.map((id) => `https://openalex.org/${id}`);
this.authorIds.set(fullIds);
// same two match modes as the persons list: topic ids when fuzzy, raw keywords otherwise
const topicIds = this.parseList(rawTopics);
const request: SelectedAuthorsRequest = {
author_ids: fullIds,
keywords: keywords,
keywords: fuzzy && topicIds.length > 0 ? topicIds : keywords,
operator: operator,
filter_type: 'topic',
fuzzy: fuzzy && topicIds.length > 0,
publication_types: publication_types,
timespan: timespan,
};
@@ -0,0 +1,91 @@
import { TestBed } from '@angular/core/testing';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { provideHttpClient } from '@angular/common/http';
import { DashboardStatisticsService } from './dashboard-statistics.service';
describe('DashboardStatisticsService', () => {
let service: DashboardStatisticsService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
DashboardStatisticsService,
provideHttpClient(),
provideHttpClientTesting(),
],
});
service = TestBed.inject(DashboardStatisticsService);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
it('sends the selected institution and period for lower project status requests', () => {
service
.getEuProjectStatuses({ fromYear: 2024, toYear: 2026 }, 'I456')
.subscribe();
const request = httpMock.expectOne((req) => {
return req.url === '/api/dashboard/projects/eu/status';
});
expect(request.request.params.get('institution_id')).toBe('I456');
expect(request.request.params.get('from_year')).toBe('2024');
expect(request.request.params.get('to_year')).toBe('2026');
request.flush({
institution_id: 'https://openalex.org/I456',
organization_name: 'Selected institution',
ongoing: 1,
upcoming: 0,
completed: 2,
});
});
it('sends only the active institution for a topic treemap request', () => {
service.getTopicTreemap(2024, 2026, 'I789').subscribe();
const request = httpMock.expectOne((req) => {
return req.url === '/api/dashboard/topic-heatmap';
});
expect(request.request.params.get('institution_id')).toBe('I789');
expect(request.request.params.get('from_year')).toBe('2024');
expect(request.request.params.get('to_year')).toBe('2026');
request.flush({
institution_id: 'https://openalex.org/I789',
organization_name: 'Selected institution',
years: [],
fields: [],
});
});
it('keeps all as the default lower-dashboard institution scope', () => {
service.getBundProjectTopics().subscribe();
const request = httpMock.expectOne((req) => {
return req.url === '/api/dashboard/projects/bund/topics';
});
expect(request.request.params.get('institution_id')).toBe('all');
expect(request.request.params.has('from_year')).toBeFalse();
expect(request.request.params.has('to_year')).toBeFalse();
request.flush({
institution_id: 'https://openalex.org/I123',
organization_name: 'Root organization',
project_count: 0,
matched_project_count: 0,
topics: [],
});
});
});
@@ -10,6 +10,11 @@ export interface DashboardPeriodBounds {
toYear?: number;
}
export interface DashboardInstitution {
id: string;
display_name: string;
}
export interface DashboardStatistics {
institution_id: string;
organization_name: string;
@@ -116,6 +121,12 @@ export class DashboardStatisticsService {
private readonly httpClient = inject(HttpClient);
private readonly apiConfiguration = inject(Configuration, { optional: true });
getInstitutions(): Observable<DashboardInstitution[]> {
return this.httpClient.get<DashboardInstitution[]>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/institutions`,
);
}
getStatistics(): Observable<DashboardStatistics> {
return this.httpClient.get<DashboardStatistics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics`,
@@ -124,120 +135,133 @@ export class DashboardStatisticsService {
getPublicationCount(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<DashboardStatisticValue> {
return this.httpClient.get<DashboardStatisticValue>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/publications`,
{ params: this.periodParams(period) },
{ params: this.statisticParams(period, institutionId) },
);
}
getPersonCount(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<DashboardStatisticValue> {
return this.httpClient.get<DashboardStatisticValue>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/persons`,
{ params: this.periodParams(period) },
{ params: this.statisticParams(period, institutionId) },
);
}
getPatentCount(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<DashboardStatisticValue> {
return this.httpClient.get<DashboardStatisticValue>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/patents`,
{ params: this.periodParams(period) },
{ params: this.statisticParams(period, institutionId) },
);
}
getEuProjectCount(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<DashboardStatisticValue> {
return this.httpClient.get<DashboardStatisticValue>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/eu`,
{ params: this.periodParams(period) },
{ params: this.statisticParams(period, institutionId) },
);
}
getEuProjectStatuses(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<EuProjectStatusStatistics> {
return this.httpClient.get<EuProjectStatusStatistics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/status`,
{ params: this.periodParams(period) },
{ params: this.analyticalParams(period, institutionId) },
);
}
getBmbfProjectStatuses(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<BmbfProjectStatusStatistics> {
return this.httpClient.get<BmbfProjectStatusStatistics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bmbf/status`,
{ params: this.periodParams(period) },
{ params: this.analyticalParams(period, institutionId) },
);
}
getDfgProjectStatuses(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<DfgProjectStatusStatistics> {
return this.httpClient.get<DfgProjectStatusStatistics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/status`,
{ params: this.periodParams(period) },
{ params: this.analyticalParams(period, institutionId) },
);
}
getBmbfProjectCount(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<DashboardStatisticValue> {
return this.httpClient.get<DashboardStatisticValue>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/bmbf`,
{ params: this.periodParams(period) },
{ params: this.statisticParams(period, institutionId) },
);
}
getDfgProjectCount(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<DashboardStatisticValue> {
return this.httpClient.get<DashboardStatisticValue>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/dfg`,
{ params: this.periodParams(period) },
{ params: this.statisticParams(period, institutionId) },
);
}
getDfgProjectTopics(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<DfgProjectTopics> {
return this.httpClient.get<DfgProjectTopics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/topics`,
{ params: this.periodParams(period) },
{ params: this.analyticalParams(period, institutionId) },
);
}
getEuProjectTopics(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<EuProjectTopics> {
return this.httpClient.get<EuProjectTopics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/topics`,
{ params: this.periodParams(period) },
{ params: this.analyticalParams(period, institutionId) },
);
}
getBundProjectTopics(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<BundProjectTopics> {
return this.httpClient.get<BundProjectTopics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bund/topics`,
{ params: this.periodParams(period) },
{ params: this.analyticalParams(period, institutionId) },
);
}
getTopAuthors(
period: DashboardPeriodBounds = {},
institutionId = 'all',
): Observable<TopAuthorStatistics> {
const analysis = (source: string) =>
this.httpClient
.get<TopAuthorAnalysis>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors/${source}`,
{ params: this.periodParams(period) },
{ params: this.analyticalParams(period, institutionId) },
)
.pipe(catchError(() => of(null)));
@@ -271,8 +295,11 @@ export class DashboardStatisticsService {
getTopicTreemap(
fromYear?: number,
toYear?: number,
institutionId = 'all',
): Observable<TopicTreemapData> {
const params: Record<string, number> = {};
const params: Record<string, string | number> = {
institution_id: institutionId,
};
if (fromYear !== undefined) params['from_year'] = fromYear;
if (toYear !== undefined) params['to_year'] = toYear;
@@ -286,8 +313,12 @@ export class DashboardStatisticsService {
topicId: string,
fromYear?: number,
toYear?: number,
institutionId = 'all',
): Observable<TopicWordCloud> {
const params: Record<string, string | number> = { topicId };
const params: Record<string, string | number> = {
topicId,
institution_id: institutionId,
};
if (fromYear !== undefined) params['from_year'] = fromYear;
if (toYear !== undefined) params['to_year'] = toYear;
return this.httpClient.get<TopicWordCloud>(
@@ -302,4 +333,24 @@ export class DashboardStatisticsService {
if (period.toYear !== undefined) params['to_year'] = period.toYear;
return params;
}
private statisticParams(
period: DashboardPeriodBounds,
institutionId: string,
): Record<string, string | number> {
return {
...this.periodParams(period),
institution_id: institutionId,
};
}
private analyticalParams(
period: DashboardPeriodBounds,
institutionId: string,
): Record<string, string | number> {
return {
...this.periodParams(period),
institution_id: institutionId,
};
}
}
@@ -30,6 +30,25 @@
(endYearChange)="onDashboardPeriodRangeChange()">
</app-year-range-slider>
</div>
<mat-form-field
class="dashboard-institution-filter"
appearance="outline"
subscriptSizing="dynamic">
<mat-label>Institution</mat-label>
<mat-select
[value]="selectedDashboardInstitutionId"
[disabled]="
dashboardInstitutionsLoading || dashboardInstitutions.length === 0
"
(selectionChange)="onDashboardInstitutionChange($event.value)">
<mat-option value="all">Alle Institutionen</mat-option>
@for (institution of dashboardInstitutions; track institution.id) {
<mat-option [value]="institution.id">
{{ institution.display_name }}
</mat-option>
}
</mat-select>
</mat-form-field>
</section>
<section class="statistics-grid" aria-label="Kennzahlen">
@@ -44,7 +63,7 @@
matTooltip="Anzahl der Publikationen im ausgewählten Zeitraum"
matTooltipPosition="above">
<div class="statistics-icon statistics-icon--publications">
<mat-icon>menu_book</mat-icon>
<mat-icon>{{ MENU_BOOK_ICON }}</mat-icon>
</div>
<div>
<span>Publikationen</span>
@@ -66,7 +85,7 @@
matTooltip="Anzahl der Personen im ausgewählten Zeitraum"
matTooltipPosition="above">
<div class="statistics-icon statistics-icon--persons">
<mat-icon>groups</mat-icon>
<mat-icon>{{ GROUPS_ICON }}</mat-icon>
</div>
<div>
<span>Personen</span>
@@ -111,7 +130,7 @@
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>
<mat-icon>{{ PUBLIC_ICON }}</mat-icon>
</div>
<div>
<span>EU-Projekte</span>
@@ -133,7 +152,7 @@
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>
<mat-icon>{{ ACCOUNT_BALANCE_ICON }}</mat-icon>
</div>
<div>
<span>Bund-Projekte</span>
@@ -155,7 +174,7 @@
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>
<mat-icon>{{ SCIENCE_ICON }}</mat-icon>
</div>
<div>
<span>DFG-Projekte</span>
@@ -174,321 +193,384 @@
<p class="statistics-error">Die Kennzahlen konnten nicht geladen werden.</p>
}
@if (
euProjectStatusesLoading ||
bmbfProjectStatusesLoading ||
dfgProjectStatusesLoading ||
euProjectStatusesError ||
bmbfProjectStatusesError ||
dfgProjectStatusesError ||
(euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses)
) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>Projektstatus nach Fördergeber</h2>
<p>
Laufende, kommende und abgeschlossene EU-, Bund- und DFG-Projekte
Ihrer Organisation.
</p>
</div>
@if (euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses) {
<div class="project-status-summary">
<span>
EU:
{{
euProjectStatuses.ongoing +
euProjectStatuses.upcoming +
euProjectStatuses.completed | number
}}
</span>
<span>
Bund:
{{
bmbfProjectStatuses.ongoing +
bmbfProjectStatuses.upcoming +
bmbfProjectStatuses.completed | number
}}
</span>
<span>
DFG:
{{
dfgProjectStatuses.ongoing +
dfgProjectStatuses.upcoming +
dfgProjectStatuses.completed | number
}}
</span>
<section
class="dashboard-institution-tabs"
aria-label="Institutionen für Analysebereiche">
<h2>Institution auswählen</h2>
<div class="dashboard-institution-tab-bar">
<button
type="button"
class="dashboard-institution-tab-arrow"
[class.is-hidden]="!canScrollAnalyticalInstitutionTabsLeft"
[disabled]="!canScrollAnalyticalInstitutionTabsLeft"
aria-label="Vorherige Institutionen anzeigen"
(click)="scrollAnalyticalInstitutionTabs(-1)">
<mat-icon>{{ CHEVRON_LEFT_ICON }}</mat-icon>
</button>
<div
#analyticalInstitutionTabList
class="dashboard-institution-tab-list sg-tab-nav"
role="tablist"
(scroll)="updateAnalyticalInstitutionTabScrollState()">
@for (institution of dashboardInstitutions; track institution.id) {
<button
type="button"
role="tab"
[attr.aria-selected]="
selectedAnalyticalInstitutionId === institution.id
"
[class.active]="selectedAnalyticalInstitutionId === institution.id"
(click)="onAnalyticalInstitutionChange(institution.id)">
{{ institution.display_name }}
</button>
}
</div>
<button
type="button"
class="dashboard-institution-tab-arrow"
[class.is-hidden]="!canScrollAnalyticalInstitutionTabsRight"
[disabled]="!canScrollAnalyticalInstitutionTabsRight"
aria-label="Weitere Institutionen anzeigen"
(click)="scrollAnalyticalInstitutionTabs(1)">
<mat-icon>{{ CHEVRON_RIGHT_ICON }}</mat-icon>
</button>
</div>
@if (dashboardInstitutionsError) {
<p class="statistics-error">
Die Institutionen konnten nicht geladen werden.
</p>
}
</section>
@if (selectedAnalyticalInstitutionId) {
@if (
euProjectStatusesLoading ||
bmbfProjectStatusesLoading ||
dfgProjectStatusesLoading ||
euProjectStatusesError ||
bmbfProjectStatusesError ||
dfgProjectStatusesError ||
(euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses)
) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>Projektstatus nach Fördergeber</h2>
<p>
Laufende, kommende und abgeschlossene EU-, Bund- und DFG-Projekte
Ihrer Organisation.
</p>
</div>
@if (euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses) {
<div class="project-status-summary">
<span>
EU:
{{
euProjectStatuses.ongoing +
euProjectStatuses.upcoming +
euProjectStatuses.completed | number
}}
</span>
<span>
Bund:
{{
bmbfProjectStatuses.ongoing +
bmbfProjectStatuses.upcoming +
bmbfProjectStatuses.completed | number
}}
</span>
<span>
DFG:
{{
dfgProjectStatuses.ongoing +
dfgProjectStatuses.upcoming +
dfgProjectStatuses.completed | number
}}
</span>
</div>
}
</header>
@if (
euProjectStatusesLoading ||
bmbfProjectStatusesLoading ||
dfgProjectStatusesLoading
) {
<div class="project-status-loading" role="status" aria-live="polite">
<app-loading
text="Projektstatus wird geladen …"
[icon]="STACKED_BAR_CHART_ICON"
size="64"
diameter="64"></app-loading>
</div>
} @else if (
euProjectStatusesError &&
bmbfProjectStatusesError &&
dfgProjectStatusesError
) {
<p class="statistics-error">
Der Status der EU-, Bund- und DFG-Projekte konnte nicht geladen
werden.
</p>
} @else if (
euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses
) {
@if (
euProjectStatusesError ||
bmbfProjectStatusesError ||
dfgProjectStatusesError
) {
<p class="statistics-error">
Projektstatusdaten für {{ failedProjectStatusSources() }} konnten
nicht geladen werden. Die übrigen Daten werden weiterhin
angezeigt.
</p>
}
<app-eu-project-status-chart
[statuses]="euProjectStatuses"
[bmbfStatuses]="bmbfProjectStatuses"
[dfgStatuses]="dfgProjectStatuses"></app-eu-project-status-chart>
}
</header>
</section>
}
@if (
euProjectStatusesLoading ||
bmbfProjectStatusesLoading ||
dfgProjectStatusesLoading
) {
<div class="project-status-loading" role="status" aria-live="polite">
<app-loading
text="Projektstatus wird geladen …"
icon="stacked_bar_chart"
size="64"
diameter="64"></app-loading>
</div>
} @else if (
euProjectStatusesError ||
bmbfProjectStatusesError ||
dfgProjectStatusesError
) {
<p class="statistics-error">
Der Status der EU-, Bund- und DFG-Projekte konnte nicht geladen
werden.
</p>
} @else if (
euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses
) {
<app-eu-project-status-chart
[statuses]="euProjectStatuses"
[bmbfStatuses]="bmbfProjectStatuses"
[dfgStatuses]="dfgProjectStatuses"></app-eu-project-status-chart>
}
</section>
}
@if (topicTreemapLoading || topicTreemapError || hasTopicTreemapData()) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>Field Treemap</h2>
<p>Publikationen Ihrer Organisation nach Field.</p>
</div>
</header>
@if (topicTreemapLoading || topicTreemapError || hasTopicTreemapData()) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>Field Treemap</h2>
<p>Publikationen Ihrer Organisation nach Field.</p>
</div>
</header>
@if (topicTreemapLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="Treemap-Daten für den gewählten Zeitraum werden geladen …"
icon="account_tree"
size="72"
diameter="72"></app-loading>
</div>
} @else if (topicTreemapError) {
<p class="statistics-error">
Die Field-Treemap konnte nicht geladen werden.
</p>
} @else {
<app-topic-treemap
[data]="topicTreemap"
[selectedNodeId]="selectedTopicTreemapNode"
(selectedNodeIdChange)="onTopicTreemapNodeChange($event)"
(topicSelect)="onTopicTreemapTopicSelect($event)">
</app-topic-treemap>
}
</section>
}
@if (dfgTopicsLoading || dfgTopicsError || dfgProjectTopics) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>DFG-Projekt-Topics</h2>
<p>
Gematchte DFG-Projekte nach Field, Subfield und Topic. Ein Klick auf
ein Topic zeigt die zugehörigen Keywords.
</p>
</div>
@if (dfgProjectTopics) {
<p class="dfg-topic-summary">
{{ dfgProjectTopics.matched_project_count | number }} von
{{ dfgProjectTopics.project_count | number }} Projekten gematcht
@if (topicTreemapLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="Treemap-Daten für den gewählten Zeitraum werden geladen …"
[icon]="ACCOUNT_TREE_ICON"
size="72"
diameter="72"></app-loading>
</div>
} @else if (topicTreemapError) {
<p class="statistics-error">
Die Field-Treemap konnte nicht geladen werden.
</p>
} @else {
<app-topic-treemap
[data]="topicTreemap"
[selectedNodeId]="selectedTopicTreemapNode"
(selectedNodeIdChange)="onTopicTreemapNodeChange($event)"
(topicSelect)="onTopicTreemapTopicSelect($event)">
</app-topic-treemap>
}
</header>
</section>
}
@if (dfgTopicsLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="DFG-Topics werden geladen …"
icon="account_tree"
size="72"
diameter="72"></app-loading>
</div>
} @else if (dfgTopicsError) {
<p class="statistics-error">
Die DFG-Topic-Treemap konnte nicht geladen werden.
</p>
} @else {
<app-topic-treemap
[data]="dfgTopicTreemap"
[selectedNodeId]="selectedDfgTopicTreemapNode"
countLabel="DFG-Projekte"
[showCountInTooltip]="false"
(selectedNodeIdChange)="onDfgTopicTreemapNodeChange($event)"
(topicSelect)="onDfgTopicTreemapTopicSelect($event)">
</app-topic-treemap>
}
</section>
}
@if (dfgTopicsLoading || dfgTopicsError || dfgProjectTopics) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>DFG-Projekt-Topics</h2>
<p>
Gematchte DFG-Projekte nach Field, Subfield und Topic. Ein Klick
auf ein Topic zeigt die zugehörigen Keywords.
</p>
</div>
@if (dfgProjectTopics) {
<p class="dfg-topic-summary">
{{ dfgProjectTopics.matched_project_count | number }} von
{{ dfgProjectTopics.project_count | number }} Projekten gematcht
</p>
}
</header>
@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
@if (dfgTopicsLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="DFG-Topics werden geladen …"
[icon]="ACCOUNT_TREE_ICON"
size="72"
diameter="72"></app-loading>
</div>
} @else if (dfgTopicsError) {
<p class="statistics-error">
Die DFG-Topic-Treemap konnte nicht geladen werden.
</p>
} @else {
<app-topic-treemap
[data]="dfgTopicTreemap"
[selectedNodeId]="selectedDfgTopicTreemapNode"
countLabel="DFG-Projekte"
[showCountInTooltip]="false"
(selectedNodeIdChange)="onDfgTopicTreemapNodeChange($event)"
(topicSelect)="onDfgTopicTreemapTopicSelect($event)">
</app-topic-treemap>
}
</header>
</section>
}
@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 (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 (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
@if (euTopicsLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="EU-Topics werden geladen …"
[icon]="ACCOUNT_TREE_ICON"
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>
}
</header>
</section>
}
@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 (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 (topAuthorsLoading || topAuthorsError || hasTopAuthorData()) {
<section class="top-authors-section">
<header class="top-authors-header">
<div>
<h2>Top 10 Personen</h2>
<p>
Nach Anzahl der Works, DFG-Projekte, Patente und News Ihrer
Organisation.
@if (bundTopicsLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="BUND-Topics werden geladen …"
[icon]="ACCOUNT_TREE_ICON"
size="72"
diameter="72"></app-loading>
</div>
} @else if (bundTopicsError) {
<p class="statistics-error">
Die BUND-Topic-Treemap konnte nicht geladen werden.
</p>
</div>
</header>
} @else {
<app-topic-treemap
[data]="bundTopicTreemap"
[selectedNodeId]="selectedBundTopicTreemapNode"
countLabel="BUND-Projekte"
[showCountInTooltip]="false"
(selectedNodeIdChange)="onBundTopicTreemapNodeChange($event)"
(topicSelect)="onBundTopicTreemapTopicSelect($event)">
</app-topic-treemap>
}
</section>
}
@if (topAuthorsError) {
<p class="statistics-error">
Die Autorenstatistiken konnten nicht geladen werden.
</p>
} @else {
<div class="top-authors-grid" [class.loading]="topAuthorsLoading">
@for (dataset of visibleTopAuthorDatasets(); track dataset.title) {
<article class="top-authors-chart">
<h3>
<mat-icon>{{ dataset.icon }}</mat-icon
>{{ dataset.title }}
</h3>
@for (
entry of dataset.entries;
track entry.id || entry.name;
let rank = $index
) {
<div class="author-bar-row">
<span class="author-rank">{{ rank + 1 }}</span>
<div class="author-bar-content">
<div class="author-bar-label">
@if (entry.id) {
<a
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>
} @else {
@if (topAuthorsLoading || topAuthorsError || hasTopAuthorData()) {
<section class="top-authors-section">
<header class="top-authors-header">
<div>
<h2>Top 10 Personen</h2>
<p>
Nach Anzahl der Works, DFG-Projekte, Patente und News Ihrer
Organisation.
</p>
</div>
</header>
@if (topAuthorsError) {
<p class="statistics-error">
Die Autorenstatistiken konnten nicht geladen werden.
</p>
} @else {
<div class="top-authors-grid" [class.loading]="topAuthorsLoading">
@for (dataset of visibleTopAuthorDatasets(); track dataset.title) {
<article class="top-authors-chart">
<h3>
<mat-icon>{{ dataset.icon }}</mat-icon
>{{ dataset.title }}
</h3>
@for (
entry of dataset.entries;
track entry.id || entry.name;
let rank = $index
) {
<div class="author-bar-row">
<span class="author-rank">{{ rank + 1 }}</span>
<div class="author-bar-content">
<div class="author-bar-label">
@if (entry.id) {
<a
class="author-name author-link"
[routerLink]="authorLink(dataset, entry)"
[queryParams]="authorQueryParams(dataset, entry)"
[appComponentTooltip]="AuthorTooltipComponent"
[tooltipInputs]="{ authorId: entry.id }"
[tooltipMaxWidth]="'500px'"
[title]="authorDisplayName(dataset, entry)">
{{ authorDisplayName(dataset, entry) }}
</a>
} @else {
<span
class="author-name"
[title]="authorDisplayName(dataset, entry)">
{{ authorDisplayName(dataset, entry) }}
</span>
}
<strong>{{ entry.count | number }}</strong>
</div>
<div class="author-bar-track">
<span
class="author-name"
[title]="authorDisplayName(dataset, entry)">
{{ authorDisplayName(dataset, entry) }}
</span>
}
<strong>{{ entry.count | number }}</strong>
</div>
<div class="author-bar-track">
<span
class="author-bar-fill"
[style.width.%]="
authorBarWidth(dataset.entries, entry.count)
"></span>
class="author-bar-fill"
[style.width.%]="
authorBarWidth(dataset.entries, entry.count)
"></span>
</div>
</div>
</div>
</div>
} @empty {
<p class="empty-chart">
{{
topAuthorsLoading
? 'Wird geladen …'
: 'Keine Daten vorhanden.'
}}
</p>
}
</article>
}
</div>
}
</section>
} @empty {
<p class="empty-chart">
{{
topAuthorsLoading
? 'Wird geladen …'
: 'Keine Daten vorhanden.'
}}
</p>
}
</article>
}
</div>
}
</section>
}
}
</div>
@@ -41,10 +41,16 @@
.dashboard-period-slider {
width: 280px;
max-width: 100%;
}
.dashboard-institution-filter {
width: 280px;
max-width: 100%;
margin-left: auto;
}
@media (max-width: 720px) {
.dashboard-institution-filter,
.dashboard-period-slider {
width: 100%;
margin-left: 0;
@@ -146,6 +152,120 @@
color: var(--sg-error);
}
.dashboard-institution-tabs {
margin: -0.25rem 0 2rem;
h2 {
margin: 0 0 0.75rem;
font-size: 1.2rem;
line-height: 1.25;
}
}
.dashboard-institution-tab-bar {
display: grid;
grid-template-columns: 40px minmax(0, 1fr) 40px;
align-items: stretch;
border-bottom: 1px solid var(--sg-border);
}
.dashboard-institution-tab-arrow {
display: grid;
width: 40px;
height: 48px;
padding: 0;
place-items: center;
border: 0;
background: transparent;
color: var(--sg-text-muted);
cursor: pointer;
transition:
color 0.15s ease,
background-color 0.15s ease,
opacity 0.15s ease;
&:hover:not(:disabled) {
background: var(--sg-option-hover);
color: var(--sg-text);
}
&:focus-visible {
outline-offset: -3px;
}
&:disabled {
cursor: default;
}
&.is-hidden {
visibility: hidden;
opacity: 0;
}
}
.dashboard-institution-tab-list {
display: flex;
overflow-x: auto;
overflow-y: hidden;
border-bottom: 0;
background: transparent;
scrollbar-width: none;
&::-webkit-scrollbar {
display: none;
}
button {
position: relative;
flex: 0 0 auto;
min-width: 120px;
height: 48px;
padding: 0 16px;
border: 0;
border-radius: 0;
background: transparent;
color: var(--sg-text-muted);
cursor: pointer;
font: inherit;
font-size: 14px;
font-weight: 600;
line-height: 48px;
text-align: center;
white-space: nowrap;
transition:
color 0.15s ease,
background-color 0.15s ease;
&::after {
position: absolute;
right: 0;
bottom: 0;
left: 0;
border-top: 3px solid transparent;
background: transparent;
content: '';
}
&:hover {
background: var(--sg-option-hover);
color: var(--sg-text);
}
&:focus-visible {
outline: 3px solid var(--sg-card-hover-border);
outline-offset: -3px;
}
&.active {
color: var(--sg-blue-highlight);
&::after {
border-top-color: var(--sg-blue-highlight);
}
}
}
}
.top-authors-section {
margin-bottom: 2.5rem;
}
@@ -1,13 +1,35 @@
import { Component, OnInit } from '@angular/core';
import {
AfterViewInit,
Component,
ElementRef,
HostListener,
OnInit,
ViewChild,
} from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatSelectModule } from '@angular/material/select';
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 {
ACCOUNT_BALANCE_ICON,
ACCOUNT_TREE_ICON,
ARTICLE_ICON,
CHEVRON_LEFT_ICON,
CHEVRON_RIGHT_ICON,
DESCRIPTION_ICON,
GROUPS_ICON,
MENU_BOOK_ICON,
PATENT_ICON,
PUBLIC_ICON,
SCIENCE_ICON,
STACKED_BAR_CHART_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';
@@ -23,6 +45,7 @@ import {
import {
BmbfProjectStatusStatistics,
BundProjectTopics,
DashboardInstitution,
DashboardPeriodBounds,
DashboardStatisticValue,
DashboardStatistics,
@@ -61,7 +84,9 @@ type DashboardPeriodMode =
selector: 'dashboard',
imports: [
DecimalPipe,
MatFormFieldModule,
MatIconModule,
MatSelectModule,
MatTooltipModule,
ComponentTooltipDirective,
RouterLink,
@@ -73,9 +98,23 @@ type DashboardPeriodMode =
templateUrl: './dashboard.component.html',
styleUrl: './dashboard.component.scss',
})
export class DashboardComponent implements OnInit {
export class DashboardComponent implements OnInit, AfterViewInit {
@ViewChild('analyticalInstitutionTabList')
private analyticalInstitutionTabList?: ElementRef<HTMLElement>;
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
readonly patentIcon = PATENT_ICON;
readonly PATENT_ICON = PATENT_ICON;
readonly CHEVRON_LEFT_ICON = CHEVRON_LEFT_ICON;
readonly CHEVRON_RIGHT_ICON = CHEVRON_RIGHT_ICON;
readonly MENU_BOOK_ICON = MENU_BOOK_ICON;
readonly GROUPS_ICON = GROUPS_ICON;
readonly PUBLIC_ICON = PUBLIC_ICON;
readonly ACCOUNT_BALANCE_ICON = ACCOUNT_BALANCE_ICON;
readonly SCIENCE_ICON = SCIENCE_ICON;
readonly STACKED_BAR_CHART_ICON = STACKED_BAR_CHART_ICON;
readonly ACCOUNT_TREE_ICON = ACCOUNT_TREE_ICON;
statistics?: Partial<DashboardStatistics>;
statisticsLoading = false;
statisticsError = false;
@@ -128,12 +167,20 @@ export class DashboardComponent implements OnInit {
dashboardPeriodMode: DashboardPeriodMode = 'all_time';
dashboardFromYear = this.topicTreemapMinYear;
dashboardToYear = this.topicTreemapMaxYear;
dashboardInstitutions: DashboardInstitution[] = [];
selectedDashboardInstitutionId = 'all';
selectedAnalyticalInstitutionId = '';
dashboardInstitutionsLoading = false;
dashboardInstitutionsError = false;
canScrollAnalyticalInstitutionTabsLeft = false;
canScrollAnalyticalInstitutionTabsRight = false;
selectedTopicTreemapNode?: string;
selectedDfgTopicTreemapNode?: string;
selectedEuTopicTreemapNode?: string;
selectedBundTopicTreemapNode?: string;
private topicTreemapReloadQueued = false;
private topicTreemapRequestId = 0;
private analyticalRequestId = 0;
constructor(
private statisticsService: DashboardStatisticsService,
@@ -144,43 +191,85 @@ export class DashboardComponent implements OnInit {
ngOnInit() {
this.restoreDashboardPeriodState();
this.loadDashboardInstitutions();
this.loadStatistics();
this.loadTopAuthors();
this.loadTopicTreemap();
this.loadDfgProjectTopics();
this.loadEuProjectTopics();
this.loadBundProjectTopics();
this.loadEuProjectStatuses();
this.loadBmbfProjectStatuses();
this.loadDfgProjectStatuses();
}
ngAfterViewInit(): void {
setTimeout(() => this.updateAnalyticalInstitutionTabScrollState());
}
@HostListener('window:resize')
onWindowResize(): void {
this.updateAnalyticalInstitutionTabScrollState();
}
private loadDashboardInstitutions(): void {
this.dashboardInstitutionsLoading = true;
this.dashboardInstitutionsError = false;
this.statisticsService
.getInstitutions()
.pipe(finalize(() => (this.dashboardInstitutionsLoading = false)))
.subscribe({
next: (institutions) => {
this.dashboardInstitutions = institutions;
setTimeout(() => this.updateAnalyticalInstitutionTabScrollState());
const requestedInstitution =
this.route.snapshot.queryParamMap.get('institution') ?? 'all';
const restoredInstitution = institutions.some(
(institution) => institution.id === requestedInstitution,
)
? requestedInstitution
: 'all';
if (restoredInstitution !== this.selectedDashboardInstitutionId) {
this.selectedDashboardInstitutionId = restoredInstitution;
this.loadStatistics();
}
const restoredAnalyticalInstitution =
restoredInstitution === 'all' ? '' : restoredInstitution;
if (
restoredAnalyticalInstitution !==
this.selectedAnalyticalInstitutionId
) {
this.selectedAnalyticalInstitutionId =
restoredAnalyticalInstitution;
this.reloadAnalyticalData();
}
},
error: () => {
this.dashboardInstitutions = [];
this.dashboardInstitutionsError = true;
},
});
}
private loadStatistics(): void {
this.statisticsError = false;
const period = this.selectedPeriodBounds();
const institutionId = this.selectedDashboardInstitutionId;
this.loadStatistic(
'publications',
this.statisticsService.getPublicationCount(period),
this.statisticsService.getPublicationCount(period, institutionId),
);
this.loadStatistic(
'persons',
this.statisticsService.getPersonCount(period),
this.statisticsService.getPersonCount(period, institutionId),
);
this.loadStatistic(
'patents',
this.statisticsService.getPatentCount(period),
this.statisticsService.getPatentCount(period, institutionId),
);
this.loadStatistic(
'eu_projects',
this.statisticsService.getEuProjectCount(period),
this.statisticsService.getEuProjectCount(period, institutionId),
);
this.loadStatistic(
'bmbf_projects',
this.statisticsService.getBmbfProjectCount(period),
this.statisticsService.getBmbfProjectCount(period, institutionId),
);
this.loadStatistic(
'dfg_projects',
this.statisticsService.getDfgProjectCount(period),
this.statisticsService.getDfgProjectCount(period, institutionId),
);
}
@@ -192,26 +281,30 @@ export class DashboardComponent implements OnInit {
return [
{
title: 'Publikationen',
icon: 'menu_book',
icon: MENU_BOOK_ICON,
entries: this.topAuthors?.works ?? [],
},
{
title: 'EU-Projekte',
icon: 'public',
icon: PUBLIC_ICON,
entries: this.topAuthors?.eu_projects ?? [],
},
{
title: 'Patente',
icon: 'description',
icon: DESCRIPTION_ICON,
entries: this.topAuthors?.patents ?? [],
},
{
title: 'DFG Projekte',
icon: 'account_tree',
icon: ACCOUNT_TREE_ICON,
entries: this.topAuthors?.projects ?? [],
stripAuthorTitle: true,
},
{ title: 'News', icon: 'article', entries: this.topAuthors?.news ?? [] },
{
title: 'News',
icon: ARTICLE_ICON,
entries: this.topAuthors?.news ?? [],
},
];
}
@@ -334,11 +427,22 @@ export class DashboardComponent implements OnInit {
}
institutionRouteId(): string {
return (
this.statistics?.institution_id?.replace('https://openalex.org/', '') ??
this.topAuthors?.institution_id?.replace('https://openalex.org/', '') ??
''
const selectedInstitutionId = this.routeableInstitutionId(
this.selectedDashboardInstitutionId,
);
if (selectedInstitutionId) return selectedInstitutionId;
return this.routeableInstitutionId(this.dashboardInstitutions[0]?.id) ?? '';
}
private routeableInstitutionId(institutionId?: string | null): string | null {
const normalizedInstitutionId = institutionId
?.replace('https://openalex.org/', '')
.trim();
return normalizedInstitutionId && normalizedInstitutionId !== 'all'
? normalizedInstitutionId
: null;
}
personListQueryParams(): PersonListQueryParams {
@@ -365,6 +469,65 @@ export class DashboardComponent implements OnInit {
});
}
onDashboardInstitutionChange(institutionId: string): void {
this.selectedDashboardInstitutionId = institutionId;
const analyticalInstitutionId =
institutionId === 'all' ? '' : institutionId;
const analyticalInstitutionChanged =
analyticalInstitutionId !== this.selectedAnalyticalInstitutionId;
this.selectedAnalyticalInstitutionId = analyticalInstitutionId;
this.updateDashboardPeriodUrl();
this.loadStatistics();
if (analyticalInstitutionChanged) {
if (analyticalInstitutionId) {
this.reloadAnalyticalData();
} else {
// Invalidate pending requests when "Alle Institutionen" is selected.
this.analyticalRequestId += 1;
}
}
}
onAnalyticalInstitutionChange(institutionId: string): void {
if (institutionId === this.selectedAnalyticalInstitutionId) return;
this.selectedAnalyticalInstitutionId = institutionId;
this.updateDashboardPeriodUrl();
this.reloadAnalyticalData();
}
scrollAnalyticalInstitutionTabs(direction: -1 | 1): void {
const tabList = this.analyticalInstitutionTabList?.nativeElement;
if (!tabList) return;
tabList.scrollBy({
left: direction * Math.floor(tabList.clientWidth * 0.75),
behavior: 'smooth',
});
}
updateAnalyticalInstitutionTabScrollState(): void {
const tabList = this.analyticalInstitutionTabList?.nativeElement;
if (!tabList) {
this.canScrollAnalyticalInstitutionTabsLeft = false;
this.canScrollAnalyticalInstitutionTabsRight = false;
return;
}
const maxScrollLeft = tabList.scrollWidth - tabList.clientWidth;
this.canScrollAnalyticalInstitutionTabsLeft = tabList.scrollLeft > 1;
this.canScrollAnalyticalInstitutionTabsRight =
tabList.scrollLeft < maxScrollLeft - 1;
}
failedProjectStatusSources(): string {
const sources = [
this.euProjectStatusesError ? 'EU' : undefined,
this.bmbfProjectStatusesError ? 'Bund' : undefined,
this.dfgProjectStatusesError ? 'DFG' : undefined,
].filter((source): source is string => source !== undefined);
return sources.join(' und ');
}
onTopicTreemapNodeChange(nodeId: string | undefined): void {
this.selectedTopicTreemapNode = nodeId;
this.updateDashboardPeriodUrl();
@@ -468,6 +631,7 @@ export class DashboardComponent implements OnInit {
...topic,
fromYear: period.fromYear,
toYear: period.toYear,
institutionId: this.selectedAnalyticalInstitutionId,
},
},
);
@@ -532,6 +696,8 @@ export class DashboardComponent implements OnInit {
dfgTreemapNode: this.selectedDfgTopicTreemapNode ?? null,
euTreemapNode: this.selectedEuTopicTreemapNode ?? null,
bundTreemapNode: this.selectedBundTopicTreemapNode ?? null,
institution: this.selectedDashboardInstitutionId,
analyticalInstitution: this.selectedAnalyticalInstitutionId || null,
},
queryParamsHandling: 'merge',
replaceUrl: true,
@@ -558,14 +724,23 @@ export class DashboardComponent implements OnInit {
private reloadPeriodData(): void {
this.loadStatistics();
this.loadTopAuthors();
this.loadTopicTreemap();
this.loadDfgProjectTopics();
this.loadEuProjectTopics();
this.loadBundProjectTopics();
this.loadEuProjectStatuses();
this.loadBmbfProjectStatuses();
this.loadDfgProjectStatuses();
this.reloadAnalyticalData();
}
private reloadAnalyticalData(): void {
if (!this.selectedAnalyticalInstitutionId) return;
const requestId = ++this.analyticalRequestId;
this.euProjectStatuses = undefined;
this.bmbfProjectStatuses = undefined;
this.dfgProjectStatuses = undefined;
this.loadTopAuthors(requestId);
this.loadTopicTreemap(requestId);
this.loadDfgProjectTopics(requestId);
this.loadEuProjectTopics(requestId);
this.loadBundProjectTopics(requestId);
this.loadEuProjectStatuses(requestId);
this.loadBmbfProjectStatuses(requestId);
this.loadDfgProjectStatuses(requestId);
}
private loadStatistic(
@@ -613,149 +788,271 @@ export class DashboardComponent implements OnInit {
this.statistics = nextStatistics;
}
private loadTopAuthors(): void {
private loadTopAuthors(requestId = this.analyticalRequestId): void {
this.topAuthorsLoading = true;
this.topAuthorsError = false;
this.statisticsService
.getTopAuthors(this.selectedPeriodBounds())
.pipe(finalize(() => (this.topAuthorsLoading = false)))
.getTopAuthors(
this.selectedPeriodBounds(),
this.selectedAnalyticalInstitutionId,
)
.pipe(
finalize(() => {
if (requestId === this.analyticalRequestId) {
this.topAuthorsLoading = false;
}
}),
)
.subscribe({
next: (statistics) => {
this.topAuthors = statistics;
if (requestId === this.analyticalRequestId) {
this.topAuthors = statistics;
}
},
error: () => {
this.topAuthorsError = true;
if (requestId === this.analyticalRequestId) {
this.topAuthorsError = true;
}
},
});
}
private loadDfgProjectTopics(): void {
private loadDfgProjectTopics(requestId = this.analyticalRequestId): void {
this.dfgTopicsLoading = true;
this.dfgTopicsError = false;
this.statisticsService
.getDfgProjectTopics(this.selectedPeriodBounds())
.pipe(finalize(() => (this.dfgTopicsLoading = false)))
.getDfgProjectTopics(
this.selectedPeriodBounds(),
this.selectedAnalyticalInstitutionId,
)
.pipe(
finalize(() => {
if (requestId === this.analyticalRequestId) {
this.dfgTopicsLoading = false;
}
}),
)
.subscribe({
next: (topics) => {
this.dfgProjectTopics = topics;
this.dfgTopicTreemap = this.buildDfgTopicTreemapData(topics);
if (requestId === this.analyticalRequestId) {
this.dfgProjectTopics = topics;
this.dfgTopicTreemap = this.buildDfgTopicTreemapData(topics);
}
},
error: () => {
this.dfgTopicsError = true;
if (requestId === this.analyticalRequestId) {
this.dfgTopicsError = true;
}
},
});
}
private loadEuProjectTopics(): void {
private loadEuProjectTopics(requestId = this.analyticalRequestId): void {
this.euTopicsLoading = true;
this.euTopicsError = false;
this.statisticsService
.getEuProjectTopics(this.selectedPeriodBounds())
.pipe(finalize(() => (this.euTopicsLoading = false)))
.getEuProjectTopics(
this.selectedPeriodBounds(),
this.selectedAnalyticalInstitutionId,
)
.pipe(
finalize(() => {
if (requestId === this.analyticalRequestId) {
this.euTopicsLoading = false;
}
}),
)
.subscribe({
next: (topics) => {
this.euProjectTopics = topics;
this.euTopicTreemap = this.buildDfgTopicTreemapData(topics);
if (requestId === this.analyticalRequestId) {
this.euProjectTopics = topics;
this.euTopicTreemap = this.buildDfgTopicTreemapData(topics);
}
},
error: () => {
this.euTopicsError = true;
if (requestId === this.analyticalRequestId) {
this.euTopicsError = true;
}
},
});
}
private loadBundProjectTopics(): void {
private loadBundProjectTopics(requestId = this.analyticalRequestId): void {
this.bundTopicsLoading = true;
this.bundTopicsError = false;
this.statisticsService
.getBundProjectTopics(this.selectedPeriodBounds())
.pipe(finalize(() => (this.bundTopicsLoading = false)))
.getBundProjectTopics(
this.selectedPeriodBounds(),
this.selectedAnalyticalInstitutionId,
)
.pipe(
finalize(() => {
if (requestId === this.analyticalRequestId) {
this.bundTopicsLoading = false;
}
}),
)
.subscribe({
next: (topics) => {
this.bundProjectTopics = topics;
this.bundTopicTreemap = this.buildDfgTopicTreemapData(topics);
if (requestId === this.analyticalRequestId) {
this.bundProjectTopics = topics;
this.bundTopicTreemap = this.buildDfgTopicTreemapData(topics);
}
},
error: () => {
this.bundTopicsError = true;
if (requestId === this.analyticalRequestId) {
this.bundTopicsError = true;
}
},
});
}
private loadEuProjectStatuses(): void {
private loadEuProjectStatuses(requestId = this.analyticalRequestId): void {
this.euProjectStatusesLoading = true;
this.euProjectStatusesError = false;
this.statisticsService
.getEuProjectStatuses(this.selectedPeriodBounds())
.pipe(finalize(() => (this.euProjectStatusesLoading = false)))
.getEuProjectStatuses(
this.selectedPeriodBounds(),
this.selectedAnalyticalInstitutionId,
)
.pipe(
finalize(() => {
if (requestId === this.analyticalRequestId) {
this.euProjectStatusesLoading = false;
}
}),
)
.subscribe({
next: (statuses) => {
this.euProjectStatuses = statuses;
if (requestId === this.analyticalRequestId) {
this.euProjectStatuses = statuses;
}
},
error: () => {
this.euProjectStatusesError = true;
if (requestId === this.analyticalRequestId) {
this.euProjectStatusesError = true;
this.euProjectStatuses = this.emptyProjectStatuses();
}
},
});
}
private loadBmbfProjectStatuses(): void {
private loadBmbfProjectStatuses(requestId = this.analyticalRequestId): void {
this.bmbfProjectStatusesLoading = true;
this.bmbfProjectStatusesError = false;
this.statisticsService
.getBmbfProjectStatuses(this.selectedPeriodBounds())
.pipe(finalize(() => (this.bmbfProjectStatusesLoading = false)))
.getBmbfProjectStatuses(
this.selectedPeriodBounds(),
this.selectedAnalyticalInstitutionId,
)
.pipe(
finalize(() => {
if (requestId === this.analyticalRequestId) {
this.bmbfProjectStatusesLoading = false;
}
}),
)
.subscribe({
next: (statuses) => {
this.bmbfProjectStatuses = statuses;
if (requestId === this.analyticalRequestId) {
this.bmbfProjectStatuses = statuses;
}
},
error: () => {
this.bmbfProjectStatusesError = true;
if (requestId === this.analyticalRequestId) {
this.bmbfProjectStatusesError = true;
this.bmbfProjectStatuses = this.emptyProjectStatuses();
}
},
});
}
private loadDfgProjectStatuses(): void {
private loadDfgProjectStatuses(requestId = this.analyticalRequestId): void {
this.dfgProjectStatusesLoading = true;
this.dfgProjectStatusesError = false;
this.statisticsService
.getDfgProjectStatuses(this.selectedPeriodBounds())
.pipe(finalize(() => (this.dfgProjectStatusesLoading = false)))
.getDfgProjectStatuses(
this.selectedPeriodBounds(),
this.selectedAnalyticalInstitutionId,
)
.pipe(
finalize(() => {
if (requestId === this.analyticalRequestId) {
this.dfgProjectStatusesLoading = false;
}
}),
)
.subscribe({
next: (statuses) => {
this.dfgProjectStatuses = statuses;
if (requestId === this.analyticalRequestId) {
this.dfgProjectStatuses = statuses;
}
},
error: () => {
this.dfgProjectStatusesError = true;
if (requestId === this.analyticalRequestId) {
this.dfgProjectStatusesError = true;
this.dfgProjectStatuses = this.emptyProjectStatuses();
}
},
});
}
private loadTopicTreemap(): void {
private emptyProjectStatuses(): EuProjectStatusStatistics {
const institution = this.dashboardInstitutions.find(
({ id }) => id === this.selectedAnalyticalInstitutionId,
);
return {
institution_id: this.selectedAnalyticalInstitutionId,
organization_name: institution?.display_name ?? '',
ongoing: 0,
upcoming: 0,
completed: 0,
};
}
private loadTopicTreemap(
analyticalRequestId = this.analyticalRequestId,
): void {
if (this.dashboardFromYear > this.dashboardToYear) {
this.topicTreemapLoading = false;
this.topicTreemapError = true;
return;
}
const requestId = ++this.topicTreemapRequestId;
const treemapRequestId = ++this.topicTreemapRequestId;
const period = this.selectedPeriodBounds();
this.topicTreemapLoading = true;
this.topicTreemapError = false;
this.statisticsService
.getTopicTreemap(period.fromYear, period.toYear)
.getTopicTreemap(
period.fromYear,
period.toYear,
this.selectedAnalyticalInstitutionId,
)
.pipe(
finalize(() => {
if (requestId === this.topicTreemapRequestId) {
if (
analyticalRequestId === this.analyticalRequestId &&
treemapRequestId === this.topicTreemapRequestId
) {
this.topicTreemapLoading = false;
}
}),
)
.subscribe({
next: (treemap) => {
if (requestId === this.topicTreemapRequestId) {
if (
analyticalRequestId === this.analyticalRequestId &&
treemapRequestId === this.topicTreemapRequestId
) {
this.topicTreemap = treemap;
}
},
error: () => {
if (requestId === this.topicTreemapRequestId) {
if (
analyticalRequestId === this.analyticalRequestId &&
treemapRequestId === this.topicTreemapRequestId
) {
this.topicTreemapError = true;
}
},
@@ -22,7 +22,7 @@
type="button"
aria-label="Dialog schließen"
mat-dialog-close>
<mat-icon>close</mat-icon>
<mat-icon>{{ CLOSE_ICON }}</mat-icon>
</button>
</div>
@@ -32,7 +32,7 @@
<span
class="topic-context-icon topic-context-icon--field"
aria-hidden="true">
<mat-icon>category</mat-icon>
<mat-icon>{{ CATEGORY_ICON }}</mat-icon>
</span>
<span class="topic-context-copy">
<span class="topic-context-label">Field</span>
@@ -41,14 +41,14 @@
}}</strong>
</span>
</div>
<mat-icon class="topic-context-arrow" aria-hidden="true"
>chevron_right</mat-icon
>
<mat-icon class="topic-context-arrow" aria-hidden="true">{{
CHEVRON_RIGHT_ICON
}}</mat-icon>
<div class="topic-context-item">
<span
class="topic-context-icon topic-context-icon--subfield"
aria-hidden="true">
<mat-icon>account_tree</mat-icon>
<mat-icon>{{ ACCOUNT_TREE_ICON }}</mat-icon>
</span>
<span class="topic-context-copy">
<span class="topic-context-label">Subfield</span>
@@ -57,14 +57,14 @@
}}</strong>
</span>
</div>
<mat-icon class="topic-context-arrow" aria-hidden="true"
>chevron_right</mat-icon
>
<mat-icon class="topic-context-arrow" aria-hidden="true">{{
CHEVRON_RIGHT_ICON
}}</mat-icon>
<div class="topic-context-item topic-context-item--topic">
<span
class="topic-context-icon topic-context-icon--topic"
aria-hidden="true">
<mat-icon>label</mat-icon>
<mat-icon>{{ LABEL_ICON }}</mat-icon>
</span>
<span class="topic-context-copy">
<span class="topic-context-label">Topic</span>
@@ -90,7 +90,7 @@
@if (loading) {
<div class="word-cloud-state">
<span class="state-icon state-icon--loading" aria-hidden="true">
<mat-icon>hourglass_top</mat-icon>
<mat-icon>{{ HOURGLASS_ICON }}</mat-icon>
</span>
<strong>Wordcloud wird erstellt</strong>
<span>Die wichtigsten Keywords werden geladen …</span>
@@ -98,7 +98,7 @@
} @else if (loadFailed) {
<div class="word-cloud-state word-cloud-state--error">
<span class="state-icon" aria-hidden="true"
><mat-icon>cloud_off</mat-icon></span
><mat-icon>{{ CLOUD_OFF_ICON }}</mat-icon></span
>
<strong>Wordcloud nicht verfügbar</strong>
<span>Die Keywords konnten nicht geladen werden.</span>
@@ -106,7 +106,7 @@
} @else if (words.length) {
<div class="keyword-toolbar" aria-label="Ausgewählte Keywords">
<div class="keyword-toolbar-label">
<mat-icon aria-hidden="true">tune</mat-icon>
<mat-icon aria-hidden="true">{{ TUNE_ICON }}</mat-icon>
<span>
<strong>Keyword-Auswahl</strong>
<small
@@ -124,7 +124,7 @@
[attr.aria-label]="word.name + ' aus Auswahl entfernen'"
(click)="toggleWord(word)">
{{ word.name }}
<mat-icon aria-hidden="true">close</mat-icon>
<mat-icon aria-hidden="true">{{ CLOSE_ICON }}</mat-icon>
</button>
} @empty {
<span class="keyword-selection-empty">Noch nichts ausgewählt</span>
@@ -157,7 +157,7 @@
? $event.preventDefault()
: closeForSearchNavigation()
">
<mat-icon aria-hidden="true">manage_search</mat-icon>
<mat-icon aria-hidden="true">{{ MANAGE_SEARCH_ICON }}</mat-icon>
Suche in Keywords
</a>
<a
@@ -178,7 +178,7 @@
? $event.preventDefault()
: closeForSearchNavigation()
">
<mat-icon aria-hidden="true">search</mat-icon>
<mat-icon aria-hidden="true">{{ SEARCH_ICON }}</mat-icon>
Suche in Themen
</a>
</div>
@@ -208,7 +208,7 @@
} @else {
<div class="word-cloud-state">
<span class="state-icon" aria-hidden="true"
><mat-icon>search_off</mat-icon></span
><mat-icon>{{ SEARCH_OFF_ICON }}</mat-icon></span
>
<strong>Keine Keywords gefunden</strong>
<span
@@ -14,6 +14,19 @@ import {
DashboardStatisticsService,
TopicWordCloudWord,
} from '../dashboard-statistics.service';
import {
ACCOUNT_TREE_ICON,
CATEGORY_ICON,
CHEVRON_RIGHT_ICON,
CLOSE_ICON,
CLOUD_OFF_ICON,
HOURGLASS_ICON,
LABEL_ICON,
MANAGE_SEARCH_ICON,
SEARCH_ICON,
SEARCH_OFF_ICON,
TUNE_ICON,
} from '../../../shared/ui/icons';
export interface TopicWordCloudDialogData {
topicId: string;
@@ -22,6 +35,7 @@ export interface TopicWordCloudDialogData {
subfieldName?: string;
fromYear?: number;
toYear?: number;
institutionId?: string;
words?: TopicWordCloudWord[];
source?: 'publications' | 'dfg' | 'eu' | 'bund';
}
@@ -46,6 +60,18 @@ interface DisplayWord extends TopicWordCloudWord {
styleUrl: './topic-wordcloud-dialog.component.scss',
})
export class TopicWordCloudDialogComponent {
readonly CLOSE_ICON = CLOSE_ICON;
readonly CATEGORY_ICON = CATEGORY_ICON;
readonly CHEVRON_RIGHT_ICON = CHEVRON_RIGHT_ICON;
readonly ACCOUNT_TREE_ICON = ACCOUNT_TREE_ICON;
readonly LABEL_ICON = LABEL_ICON;
readonly HOURGLASS_ICON = HOURGLASS_ICON;
readonly CLOUD_OFF_ICON = CLOUD_OFF_ICON;
readonly TUNE_ICON = TUNE_ICON;
readonly MANAGE_SEARCH_ICON = MANAGE_SEARCH_ICON;
readonly SEARCH_ICON = SEARCH_ICON;
readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON;
readonly data = inject<TopicWordCloudDialogData>(MAT_DIALOG_DATA);
private readonly dialogRef = inject(
MatDialogRef<TopicWordCloudDialogComponent>,
@@ -82,6 +108,7 @@ export class TopicWordCloudDialogComponent {
this.data.topicId,
this.data.fromYear,
this.data.toYear,
this.data.institutionId,
)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
@@ -7,7 +7,7 @@
aria-describedby="error-message">
<mat-card-content class="error-content">
<div class="icon-wrapper" aria-hidden="true">
<mat-icon class="error-icon">warning</mat-icon>
<mat-icon class="error-icon">{{ WARNING_ICON }}</mat-icon>
</div>
<span class="status-code"> Fehler {{ error().statusCode }} </span>
@@ -34,12 +34,12 @@
color="primary"
type="button"
(click)="goBack()">
<mat-icon aria-hidden="true">arrow_back</mat-icon>
<mat-icon aria-hidden="true">{{ ARROW_BACK_ICON }}</mat-icon>
Zurück
</button>
<a mat-button routerLink="/" aria-label="Zur Startseite">
<mat-icon aria-hidden="true">home</mat-icon>
<mat-icon aria-hidden="true">{{ HOME_ICON }}</mat-icon>
Startseite
</a>
</div>
@@ -14,6 +14,12 @@ import { MatExpansionModule } from '@angular/material/expansion';
import { MatIconModule } from '@angular/material/icon';
import { ErrorService, ErrorState } from '../../shared/services/error.service';
import { RouterLink } from '@angular/router';
import {
ARROW_BACK_ICON,
HOME_ICON,
WARNING_ICON,
} from '../../shared/ui/icons';
@Component({
selector: 'app-error-page',
standalone: true,
@@ -28,6 +34,10 @@ import { RouterLink } from '@angular/router';
styleUrl: './error-page.component.scss',
})
export class ErrorPageComponent {
readonly WARNING_ICON = WARNING_ICON;
readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly HOME_ICON = HOME_ICON;
readonly routeStatusCode = input(500, { transform: numberAttribute });
readonly routeTitle = input('Da ist was schiefgelaufen');
readonly routeMessage = input(
@@ -13,7 +13,7 @@
<div class="login-form">
<div class="code-intro">
<mat-icon>
{{ rateLimited() ? 'hourglass_empty' : 'mark_email_unread' }}
{{ rateLimited() ? HOURGLASS_EMPTY_ICON : EMAIL_UNREAD_ICON }}
</mat-icon>
<div>
@if (rateLimited()) {
@@ -35,7 +35,7 @@
@if (errorMessage()) {
<div class="code-intro">
<mat-icon>error_outline</mat-icon>
<mat-icon>{{ ERROR_OUTLINE_ICON }}</mat-icon>
<div>
<strong>Fehler</strong>
<span>{{ errorMessage() }}</span>
@@ -75,7 +75,7 @@
@if (errorMessage()) {
<div class="code-intro">
<mat-icon>error_outline</mat-icon>
<mat-icon>{{ ERROR_OUTLINE_ICON }}</mat-icon>
<div>
<strong>Fehler</strong>
<span>{{ errorMessage() }}</span>
@@ -13,6 +13,11 @@ import { MatInputModule } from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
import { CredentialService } from '../../shared/services/credential.service';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import {
EMAIL_UNREAD_ICON,
ERROR_OUTLINE_ICON,
HOURGLASS_EMPTY_ICON,
} from '../../shared/ui/icons';
@Component({
selector: 'app-forgot-password',
@@ -30,6 +35,10 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
standalone: true,
})
export class ForgotPasswordComponent {
readonly HOURGLASS_EMPTY_ICON = HOURGLASS_EMPTY_ICON;
readonly EMAIL_UNREAD_ICON = EMAIL_UNREAD_ICON;
readonly ERROR_OUTLINE_ICON = ERROR_OUTLINE_ICON;
private readonly credentialService = inject(CredentialService);
private readonly snackBar = inject(MatSnackBar);
@@ -1,7 +1,7 @@
@if (loading) {
<app-loading
text="Patentdaten werden geladen..."
icon="workspace_premium"
[icon]="PATENT_ICON"
[size]="150"
[diameter]="150" />
} @else if (error) {
@@ -25,7 +25,7 @@
<mat-form-field
class="patents-toolbar-field"
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="rule"></mat-icon>
<mat-icon matPrefix>{{ RULE_ICON }}</mat-icon>
<mat-select
[value]="activeMatchType"
(selectionChange)="setMatchType($event.value)">
@@ -36,23 +36,13 @@
<mat-option value="both">Beides</mat-option>
</mat-select>
</mat-form-field>
<app-source-filter
[value]="activeFilter"
(valueChange)="setFilter($event)" />
<mat-form-field
class="patents-toolbar-field"
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="filter_alt"></mat-icon>
<mat-select
[value]="activeFilter"
(selectionChange)="setFilter($event.value)">
<mat-select-trigger>Filter nach Quelle</mat-select-trigger>
<mat-option value="all">Alle</mat-option>
<mat-option value="EPO">EPO</mat-option>
<mat-option value="USPTO">USPTO</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field
class="patents-toolbar-field"
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="sort"></mat-icon>
<mat-icon matPrefix>{{ SORT_ICON }}</mat-icon>
<mat-select
[value]="sortColumn"
(selectionChange)="setSort($event.value)">
@@ -141,7 +131,8 @@
[appComponentTooltip]="AuthorTooltipComponent"
[tooltipInputs]="{
authorId: author.openalex_author_id,
}">
}"
[tooltipMaxWidth]="'500px'">
{{ author.author_name }}
</a>
</li>
@@ -164,7 +155,7 @@
<span class="patent-detail-action__label"
>Patentdetails anzeigen</span
>
<mat-icon aria-hidden="true">chevron_right</mat-icon>
<mat-icon aria-hidden="true">{{ CHEVRON_RIGHT_ICON }}</mat-icon>
</button>
<p class="patent-detail-hint">
Abstract, Erfinder, Anmelder und IPC/CPC-Klassifikation
@@ -17,6 +17,14 @@ import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-pagina
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
import { AppAuthorTooltipComponent } from '../../shared/ui/app-author-tooltip/app-author-tooltip.component';
import { PatentTableComponent } from '../../shared/ui/patent-table/patent-table.component';
import { SourceFilterComponent } from '../../shared/ui/source-filter/source-filter.component';
import {
CHEVRON_RIGHT_ICON,
FILTER_ICON,
PATENT_ICON,
RULE_ICON,
SORT_ICON,
} from '../../shared/ui/icons';
type SortColumn = 'title' | 'publication_year' | 'source' | 'match_type';
type SortDirection = 'asc' | 'desc';
@@ -35,11 +43,18 @@ type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both';
QueryParamPaginatorComponent,
ComponentTooltipDirective,
PatentTableComponent,
SourceFilterComponent,
],
templateUrl: './institution-patents.component.html',
styleUrl: './institution-patents.component.scss',
})
export class InstitutionPatentsComponent implements OnInit {
readonly PATENT_ICON = PATENT_ICON;
readonly RULE_ICON = RULE_ICON;
readonly FILTER_ICON = FILTER_ICON;
readonly SORT_ICON = SORT_ICON;
readonly CHEVRON_RIGHT_ICON = CHEVRON_RIGHT_ICON;
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
private route = inject(ActivatedRoute);
private router = inject(Router);
@@ -81,7 +81,7 @@
<ng-template #euProjectActionsTmp let-row>
<a mat-icon-button color="primary" [routerLink]="['/projects/eu', row.id]">
<mat-icon>open_in_new</mat-icon>
<mat-icon>{{ OPEN_IN_NEW_ICON }}</mat-icon>
</a>
</ng-template>
@@ -90,7 +90,7 @@
mat-icon-button
color="primary"
[routerLink]="['/projects/bund', row.id]">
<mat-icon>open_in_new</mat-icon>
<mat-icon>{{ OPEN_IN_NEW_ICON }}</mat-icon>
</a>
</ng-template>
</div>
@@ -32,6 +32,8 @@ import {
LinkTabNavBarComponent,
LinkTabNavBarItem,
} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
import { OPEN_IN_NEW_ICON } from '../../shared/ui/icons';
type BundProjectRow = {
id: string;
topic: string;
@@ -71,6 +73,8 @@ type EuProjectRow = {
styleUrl: './institution-projects.component.scss',
})
export class InstitutionProjectsComponent implements OnInit {
readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON;
fundingStartTmp = viewChild.required<TemplateRef<any>>('fundingStartTmp');
fundingEndTmp = viewChild.required<TemplateRef<any>>('fundingEndTmp');
fundingAmountTmp = viewChild.required<TemplateRef<any>>('fundingAmountTmp');
@@ -0,0 +1,166 @@
<div class="institution-overview">
<mat-card class="institution-overview-card" appearance="outlined">
<!-- Header Section -->
<div class="overview-header">
<div class="avatar-col">
<div class="institution-avatar" [class]="typeInfo().badgeClass">
<mat-icon>{{ typeInfo().icon }}</mat-icon>
</div>
</div>
<div class="identity-col">
<div class="title-row">
<h1 class="institution-name">{{ displayName() }}</h1>
<span [class]="'type-badge ' + typeInfo().badgeClass">
<mat-icon class="badge-icon">{{ typeInfo().icon }}</mat-icon>
{{ typeInfo().label }}
</span>
</div>
<div class="meta-row">
@if (locationText()) {
<div class="meta-item location-item">
@if (countryCode()) {
<app-country-flag
[countryCode]="countryCode()!"
[height]="14"
[bordered]="false" />
}
<span>{{ locationText() }}</span>
</div>
}
@if (homepageUrl()) {
<a
class="meta-link"
[href]="homepageUrl()!"
target="_blank"
rel="noopener noreferrer"
matTooltip="Offizielle Webseite öffnen">
<mat-icon>{{ LANGUAGE_ICON }}</mat-icon>
<span>Webseite</span>
<mat-icon class="external-icon">{{ OPEN_IN_NEW_ICON }}</mat-icon>
</a>
}
@if (rorUrl()) {
<a
class="meta-link ror-link"
[href]="rorUrl()!"
target="_blank"
rel="noopener noreferrer"
matTooltip="ROR-Register öffnen">
<span class="ror-tag">ROR</span>
<mat-icon class="external-icon">{{ OPEN_IN_NEW_ICON }}</mat-icon>
</a>
}
</div>
</div>
</div>
<!-- Key Metrics Section -->
<div class="metrics-row">
@if (worksCount() !== null && worksCount() !== undefined) {
<div class="stat-card">
<div class="stat-icon-wrapper pub-icon">
<mat-icon>{{ PUBLICATION_ICON }}</mat-icon>
</div>
<div class="stat-content">
<span class="stat-value">{{
worksCount() | number: undefined : 'de'
}}</span>
<span class="stat-label">Publikationen</span>
</div>
</div>
}
@if (citedByCount() !== null && citedByCount() !== undefined) {
<div class="stat-card">
<div class="stat-icon-wrapper cite-icon">
<mat-icon>{{ CITATION_ICON }}</mat-icon>
</div>
<div class="stat-content">
<span class="stat-value">{{
citedByCount() | number: undefined : 'de'
}}</span>
<span class="stat-label">Zitationen</span>
</div>
</div>
}
@if (hIndex() !== null && hIndex() !== undefined) {
<div class="stat-card">
<div class="stat-icon-wrapper hindex-icon">
<mat-icon>{{ TRENDING_UP_ICON }}</mat-icon>
</div>
<div class="stat-content">
<span class="stat-value">{{ hIndex() }}</span>
<span class="stat-label">h-Index</span>
</div>
</div>
}
</div>
<!-- Alternative Names / Acronyms -->
@if (alternatives().length > 0) {
<mat-divider />
<div class="details-section">
<h4 class="section-title">Alternative Bezeichnungen</h4>
<div class="alternatives-list">
@for (alt of visibleAlternatives(); track alt) {
<span class="alternative-chip">{{ alt }}</span>
}
@if (hasMoreAlternatives()) {
<button
mat-button
class="expand-btn"
(click)="toggleAlternatives()">
{{
showAllAlternatives()
? 'Weniger anzeigen'
: '+' + (alternatives().length - 4) + ' weitere'
}}
</button>
}
</div>
</div>
}
<!-- Associated Institutions -->
@if (associatedInstitutions().length > 0) {
<mat-divider />
<div class="details-section">
<h4 class="section-title">
Assoziierte Institutionen
<span class="section-count"
>({{ associatedInstitutions().length }})</span
>
</h4>
<div class="associated-chips-container">
@for (
assoc of visibleAssociatedInstitutions();
track assoc.id ?? assoc.display_name ?? $index
) {
<div class="associated-chip-wrapper">
<app-institution-chip
[institution]="assoc"
[showIcon]="true"
size="normal"
[isClickable]="true"
(handleChipClick)="navigateToInstitution(assoc)" />
</div>
}
@if (hasMoreAssociated()) {
<button mat-button class="expand-btn" (click)="toggleAssociated()">
{{
showAllAssociated()
? 'Weniger anzeigen'
: '+' + (associatedInstitutions().length - 10) + ' weitere'
}}
</button>
}
</div>
</div>
}
</mat-card>
</div>

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