Compare commits

..
Author SHA1 Message Date
farajollahi d48435b948 fix bug
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-06 18:12:38 +02:00
spsaefan c054cf99fe Fix all time slider
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-04 23:19:50 +02:00
spsaefan 98a742f024 Match dashboard publications with publications page
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-04 22:59:36 +02:00
58 changed files with 1103 additions and 2132 deletions
+91 -51
View File
@@ -30,6 +30,7 @@ from inse.projects.model import (
ProjectsFilteringProperties,
ProjectType,
)
from inse.works.v2 import service as works_v2_service
from .institute_helper import get_openalex_institution
from .model import (
@@ -241,28 +242,34 @@ async def get_dashboard_publications(
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
institution = await institutions_v2_service.get_institution_by_id_or_raise(
raw_oa_institution_id=_raw_institution_id(normalized_id),
source=["id", "works_count", "counts_by_year"],
must = [
works_v2_service._institutions_nested_query([normalized_id]),
]
if publication_years := _dashboard_publication_years(period):
must.append({"terms": {"publication_year": publication_years}})
response = await elasticsearch.search(
index=ESIndex.OPENALEX_WORKS_WILDCARD,
body={
"size": 0,
"track_total_hits": True,
"query": {"bool": {"must": must}},
},
cluster=ESCluster.NES,
)
if period == (None, None):
value = int(institution.works_count or 0)
else:
value = sum(
int(entry.works_count or 0)
for entry in institution.counts_by_year or []
if (
(period[0] is None or int(entry.year or 0) >= period[0])
and (period[1] is None or int(entry.year or 0) <= period[1])
)
)
return DashboardStatisticValue(
institution_id=normalized_id,
organization_name=organization_name,
value=value,
value=_total(response),
)
def _dashboard_publication_years(period: DashboardPeriod) -> list[int] | None:
from_year, to_year = period
if from_year is None and to_year is None:
return None
return list(range(from_year or 1900, (to_year or 2100) + 1))
async def get_dashboard_persons(
institution_id: str,
organization_name: str,
@@ -622,7 +629,7 @@ async def get_dashboard_dfg_projects(
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
projects = await projects_service.get_dfg_projects(
projects = await projects_service.get_dfg_projects_by_author_id(
institutions_search_client=InstitutionsSearchClient(),
raw_oa_institution_id=_raw_institution_id(normalized_id),
author_id=None,
@@ -871,7 +878,7 @@ async def _get_dfg_project_ids_from_projects_service(
project_ids: set[str] = set()
while True:
projects = await projects_service.get_dfg_projects(
projects = await projects_service.get_dfg_projects_by_author_id(
institutions_search_client=InstitutionsSearchClient(),
raw_oa_institution_id=_raw_institution_id(institution_id),
author_id=None,
@@ -1183,7 +1190,10 @@ async def get_top_authors(
to_year = datetime.now().year
period = _dashboard_period(from_year, to_year)
authors = await _safe_institution_authors(normalized_id)
works = _top_work_authors(authors, period)
works = await _safe_top_authors(
"works",
_top_work_authors(normalized_id, period, authors),
)
projects = await _safe_top_authors(
"projects",
_top_project_authors(
@@ -1595,51 +1605,81 @@ def _short_author_id(value: str) -> str:
return value.replace("https://openalex.org/", "").strip().upper()
def _top_work_authors(
authors: list[dict[str, Any]],
async def _top_work_authors(
institution_id: str,
period: DashboardPeriod,
institution_authors: list[dict[str, Any]],
) -> list[TopAuthor]:
if period != (None, None):
ranked_authors = sorted(
(
{
**author,
"selected_works_count": _works_count_in_period(author, period),
}
for author in authors
),
key=lambda author: author["selected_works_count"],
reverse=True,
)
else:
ranked_authors = [
{**author, "selected_works_count": author["works_count"]}
for author in authors
]
institution_author_ids = {
_short_author_id(str(author["id"]))
for author in institution_authors
if author.get("id")
}
if not institution_author_ids:
return []
must = [works_v2_service._institutions_nested_query([institution_id])]
if publication_years := _dashboard_publication_years(period):
must.append({"terms": {"publication_year": publication_years}})
author_counts: dict[str, int] = defaultdict(int)
author_names: dict[str, str] = {}
async for hit in elasticsearch.scan(
index=str(ESIndex.OPENALEX_WORKS_WILDCARD),
query={"bool": {"must": must}},
source=[
"id",
"authorships.author.id",
"authorships.author.display_name",
"authorships.institutions.id",
],
page_size=1000,
cluster=ESCluster.NES,
):
hit_author_ids: set[str] = set()
for authorship in hit.get("_source", {}).get("authorships", []):
if not any(
_normalize_institution_id(institution.get("id")) == institution_id
for institution in authorship.get("institutions") or []
if institution.get("id")
):
continue
author = authorship.get("author") or {}
author_id = author.get("id")
if not author_id:
continue
author_id = str(author_id)
if _short_author_id(author_id) not in institution_author_ids:
continue
hit_author_ids.add(author_id)
if author.get("display_name"):
author_names.setdefault(author_id, str(author["display_name"]))
for author_id in hit_author_ids:
author_counts[author_id] += 1
ranked_authors = sorted(
(
{
"id": author_id,
"name": author_names.get(author_id, author_id),
"count": count,
}
for author_id, count in author_counts.items()
),
key=lambda author: author["count"],
reverse=True,
)
return [
TopAuthor(
id=_short_author_id(author["id"]),
name=author["name"],
count=author["selected_works_count"],
count=author["count"],
)
for author in ranked_authors[:TOP_AUTHOR_LIMIT]
if author["selected_works_count"] > 0
if author["count"] > 0
]
def _works_count_in_period(author: dict[str, Any], period: DashboardPeriod) -> int:
from_year, to_year = period
return sum(
int(item.get("works_count", 0) or 0)
for item in author.get("counts_by_year", [])
if (
(from_year is None or int(item.get("year", 0) or 0) >= from_year)
and (to_year is None or int(item.get("year", 0) or 0) <= to_year)
)
)
async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]:
try:
return await _institution_authors(institution_id)
+180 -28
View File
@@ -24,7 +24,6 @@ from inse.dashboard.service import (
get_topic_word_cloud,
)
from inse.model import ESCluster, ESIndex
from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.openalex.institution import Institution
from inse.models.openalex.meta import Meta
from inse.persons.model import CustomAuthorsListResponse
@@ -68,7 +67,7 @@ async def test_dfg_topic_project_ids_use_paginated_projects_service():
]
with patch(
"inse.dashboard.service.projects_service.get_dfg_projects",
"inse.dashboard.service.projects_service.get_dfg_projects_by_author_id",
new=AsyncMock(side_effect=pages),
) as mocked_get_projects:
project_ids = await _get_dfg_project_ids_from_projects_service(
@@ -144,7 +143,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
)
),
), patch(
"inse.dashboard.service.projects_service.get_dfg_projects",
"inse.dashboard.service.projects_service.get_dfg_projects_by_author_id",
new=AsyncMock(
return_value=DfgProjectPage(elements=[], total=3, page=0, size=1)
),
@@ -188,21 +187,16 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
}
@pytest.mark.anyio
async def test_dashboard_publications_uses_institutions_v2_counts():
institution = Institution(
id=ORG_INSTITUTION_ID,
works_count=250,
counts_by_year=[
AuthorCountsByYearInner(year=2021, works_count=10),
AuthorCountsByYearInner(year=2022, works_count=12),
AuthorCountsByYearInner(year=2023, works_count=14),
],
)
async def test_dashboard_publications_counts_matching_openalex_works():
with patch(
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
new=AsyncMock(return_value=institution),
) as mocked_get_institution:
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(
side_effect=[
{"hits": {"total": {"value": 250}}},
{"hits": {"total": {"value": 22}}},
]
),
) as mocked_search:
all_time = await get_dashboard_publications(
ORG_INSTITUTION_ID,
"Example Org",
@@ -216,10 +210,33 @@ async def test_dashboard_publications_uses_institutions_v2_counts():
assert all_time.value == 250
assert selected_period.value == 22
assert mocked_get_institution.await_args_list[0].kwargs == {
"raw_oa_institution_id": "I123",
"source": ["id", "works_count", "counts_by_year"],
}
all_time_body = mocked_search.await_args_list[0].kwargs["body"]
selected_period_body = mocked_search.await_args_list[1].kwargs["body"]
assert mocked_search.await_args_list[0].kwargs["index"] == (
ESIndex.OPENALEX_WORKS_WILDCARD
)
assert all_time_body["track_total_hits"] is True
assert all_time_body["query"]["bool"]["must"] == [
{
"nested": {
"path": "authorships",
"query": {
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": [ORG_INSTITUTION_ID]
}
},
}
},
}
}
]
assert selected_period_body["query"]["bool"]["must"] == [
all_time_body["query"]["bool"]["must"][0],
{"terms": {"publication_year": [2021, 2022]}},
]
@pytest.mark.anyio
@@ -254,7 +271,7 @@ async def test_dashboard_dfg_projects_uses_projects_service_total():
project_page = DfgProjectPage(elements=[], total=42, page=0, size=1)
with patch(
"inse.dashboard.service.projects_service.get_dfg_projects",
"inse.dashboard.service.projects_service.get_dfg_projects_by_author_id",
new=AsyncMock(return_value=project_page),
) as mocked_get_projects:
result = await get_dashboard_dfg_projects(
@@ -438,6 +455,48 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
return {"aggregations": {"people": {"buckets": []}}}
scan_calls = []
async def scan(**kwargs):
scan_calls.append(kwargs)
yield {
"_id": "W1",
"_source": {
"id": "https://openalex.org/W1",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
},
"institutions": [{"id": "https://openalex.org/I999"}],
},
],
},
}
yield {
"_id": "W2",
"_source": {
"id": "https://openalex.org/W2",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
},
}
async def eu_projects(**kwargs):
if kwargs.get("raw_oa_institution_id"):
return EuCordisProjectSearchPage(
@@ -461,6 +520,9 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
) as mocked_search, patch(
"inse.dashboard.service.elasticsearch.scan",
new=scan,
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
@@ -482,8 +544,9 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
assert result.works[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
"count": 42,
"count": 2,
}
assert len(result.works) == 1
assert result.patents[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
@@ -523,18 +586,44 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
assert eu_body["_source"] == ["projectID", "qaProcessedDoi"]
assert "aggs" not in eu_body
works_calls = [
assert len(scan_calls) == 1
assert scan_calls[0]["index"] == str(ESIndex.OPENALEX_WORKS_WILDCARD)
assert scan_calls[0]["query"]["bool"]["must"] == [
{
"nested": {
"path": "authorships",
"query": {
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": [ORG_INSTITUTION_ID]
}
},
}
},
}
}
]
assert scan_calls[0]["source"] == [
"id",
"authorships.author.id",
"authorships.author.display_name",
"authorships.institutions.id",
]
eu_work_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == "openalex-works"
]
assert len(works_calls) == 1
works_body = works_calls[0].kwargs["body"]
assert works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
assert len(eu_work_calls) == 1
eu_works_body = eu_work_calls[0].kwargs["body"]
assert eu_works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
"https://doi.org/10.1234/p1",
"https://doi.org/10.1234/p2",
]
assert works_body["_source"] == [
assert eu_works_body["_source"] == [
"doi",
"authorships.author.id",
"authorships.author.display_name",
@@ -813,9 +902,29 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
raise RuntimeError("projects unavailable")
async def scan(**kwargs):
yield {
"_id": "W1",
"_source": {
"id": "https://openalex.org/W1",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
},
}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.elasticsearch.scan",
new=scan,
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
@@ -879,9 +988,47 @@ async def test_top_authors_can_rank_works_by_last_five_years():
}
return {"aggregations": {"people": {"buckets": []}}}
scan_calls = []
async def scan(**kwargs):
scan_calls.append(kwargs)
for index in range(16):
yield {
"_id": f"W-grace-{index}",
"_source": {
"authorships": [
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
]
},
}
for index in range(2):
yield {
"_id": f"W-ada-{index}",
"_source": {
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
]
},
}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
) as mocked_search, patch(
"inse.dashboard.service.elasticsearch.scan",
new=scan,
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
@@ -909,6 +1056,11 @@ async def test_top_authors_can_rank_works_by_last_five_years():
"count": 2,
}
assert len(scan_calls) == 1
assert scan_calls[0]["query"]["bool"]["must"][1] == {
"terms": {"publication_year": list(range(current_year - 4, current_year + 1))}
}
@pytest.mark.anyio
async def test_topic_heatmap_maps_field_year_counts_and_shares():
@@ -96,7 +96,6 @@ def _index_to_cluster(index: ESIndex) -> ESCluster | None:
ESIndex.OPENALEX_INSTITUTIONS,
ESIndex.OPENALEX_PUBLICATIONS,
ESIndex.WORK_CLASSIFICATIONS,
ESIndex.CC_NEWS_WILDCARD,
}:
return ESCluster.NES
elif index in {
@@ -440,16 +439,12 @@ async def count(
async def msearch(
searches: list[tuple[ESIndex | str | list[str], dict[str, Any]]],
cluster: ESCluster = ESCluster.NES,
request_cache: bool = False,
) -> list[dict[str, Any]]:
"""Performs a multi-search request (_msearch) on Elasticsearch.
Args:
searches: A list of tuples, each containing (index, payload_dict).
cluster: The Elasticsearch cluster to execute searches on.
request_cache: Whether to enable the shard request cache for each search.
Elasticsearch rejects `request_cache` as an _msearch URL parameter, so
it goes into the per-search header line instead.
Returns:
List[Dict[str, Any]]: List of response dictionaries for each search in order.
@@ -469,9 +464,7 @@ async def msearch(
idx_str = ",".join(str(i) for i in idx)
else:
idx_str = str(idx)
header_obj: dict[str, Any] = {"index": idx_str}
if request_cache:
header_obj["request_cache"] = True
header_obj = {"index": idx_str}
lines.append(json.dumps(header_obj))
lines.append(json.dumps(body))
-1
View File
@@ -65,7 +65,6 @@ class ESIndex(StrEnum):
AKTUELLES = "aktuell"
AKTUELLES_POSTPROC = "aktuell_postproc"
AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics"
CC_NEWS_WILDCARD = "cc-news-*"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
@@ -1133,6 +1133,10 @@ async def get_eu_cordis_projects_funding_data(
"track_total_hits": False,
"_source": ["id", "startDate", "endDate", "ecMaxContribution"],
"query": query,
# "id" is unique per project and used elsewhere as a term-filter
# field, so it's mapped as keyword - safe + deterministic sort
# key for search_after pagination across an arbitrarily large
# result set.
"sort": [{"id": {"order": "asc", "unmapped_type": "keyword"}}],
}
if search_after is not None:
@@ -1252,6 +1256,68 @@ async def get_openalex_author_ids_by_dois(
return result
async def get_openalex_authors_for_cordis_project_ids(
project_ids: list[str],
) -> dict[str, AuthorPage]:
"""Returns a mapping of project_id -> AuthorPage for a batch of projects."""
if not project_ids:
return {}
query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}}
response = await elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
cluster=ESCluster.INSE,
source=["projectID", "doi","qaProcessedDoi"],
size=10000,
)
dois_by_project: dict[str, set[str]] = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
pid = source.get("projectID")
doi = source.get("doi")
qa_processed_doi = source.get("qaProcessedDoi")
if pid:
dois_by_project.setdefault(pid, set())
if doi:
dois_by_project[pid].add(doi)
elif qa_processed_doi:
dois_by_project[pid].add(qa_processed_doi)
all_dois = list({doi for dois in dois_by_project.values() for doi in dois})
# single ES call for the whole batch, keyed by raw DOI
author_ids_by_doi = await get_openalex_author_ids_by_dois(dois=all_dois)
# aggregate per project, dedupe author_ids within a project
author_ids_by_project: dict[str, list[str]] = {}
for pid, dois in dois_by_project.items():
project_author_ids: set[str] = set()
for doi in dois:
project_author_ids.update(author_ids_by_doi.get(doi, []))
author_ids_by_project[pid] = list(project_author_ids)
# single ES call to fetch all Author objects across every project
all_author_ids = list({aid for ids in author_ids_by_project.values() for aid in ids})
author_page = await get_authors_by_ids(author_ids=all_author_ids)
authors_by_id = {author.id: author for author in author_page.elements}
# split the fetched authors back out per project
result: dict[str, AuthorPage] = {}
for pid in project_ids:
ids_for_project = author_ids_by_project.get(pid, [])
authors_for_project = [
authors_by_id[aid] for aid in ids_for_project if aid in authors_by_id
]
result[pid] = AuthorPage(
elements=authors_for_project,
total=len(authors_for_project),
page=0,
size=len(authors_for_project),
)
return result
async def get_openalex_authors_for_projects_ids(
project_ids_by_type: dict[EuCordisProjectType, list[str]],
+1 -37
View File
@@ -1,49 +1,13 @@
import logging
from collections import defaultdict
from typing import Any
import inse.authors.v2.service as author_service
from inse.auth.model import AccessTokenMetadata
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.projects.model import EuCordisProjectType
logger = logging.getLogger(__name__)
async def is_projects_access_forbidden(
access_token_metadata: AccessTokenMetadata,
raw_oa_institution_id: str | None,
raw_oa_author_id: str | None,
) -> bool:
"""
Determines if access to projects is forbidden based on the provided access token metadata
and the raw OpenAlex institution and author IDs.
Args:
access_token_metadata (AccessTokenMetadata): Metadata from the access token.
raw_oa_institution_id (str | None): The raw OpenAlex institution ID.
raw_oa_author_id (str | None): The raw OpenAlex author ID.
Returns:
bool: True if access is forbidden, False otherwise.
"""
effective_institution_id = access_token_metadata.effective_institution_id
if raw_oa_institution_id and effective_institution_id != raw_oa_institution_id:
return True
if raw_oa_author_id:
authors_profile = await author_service.get_author_by_id(raw_oa_author_id)
if not authors_profile:
return True # Author not found, access forbidden
authors_last_known_institution_ids = [inst.id.split("/")[-1] for inst in authors_profile.last_known_institutions]
print(f"Author's last known institution IDs: {authors_last_known_institution_ids}")
if effective_institution_id not in authors_last_known_institution_ids:
return True # Effective institution ID does not match any of the author's last known institutions
return False
async def get_dfg_author_names_by_ids(author_ids: list[int]) -> list[str] | None:
try:
body = {
@@ -195,7 +195,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]):
_type_: The retrieved publications.
"""
query_dois = set({
query_dois = list({
variant
for doi in dois
for variant in (
@@ -211,8 +211,8 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]):
{
"bool": {
"should": [
{"terms": {"doi": list(query_dois)}},
{"terms": {"qaProcessedDoi": list(query_dois)}},
{"terms": {"doi": query_dois}},
{"terms": {"qaProcessedDoi": query_dois}},
],
"minimum_should_match": 1,
}
@@ -223,7 +223,6 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]):
response = await elasticsearch.search(
query=query,
size=10000,
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
cluster=ESCluster.INSE,
)
@@ -265,7 +264,7 @@ async def get_dfg_publications_by_dois(dois: list[str]):
_type_: The retrieved publications.
"""
query_dois = set({
query_dois = list({
variant
for doi in dois
for variant in (
@@ -282,7 +281,7 @@ async def get_dfg_publications_by_dois(dois: list[str]):
"query": {
"terms": {
"publications.doi":
list(query_dois)
query_dois
}
}
}
@@ -292,7 +291,7 @@ async def get_dfg_publications_by_dois(dois: list[str]):
}
response = await elasticsearch.search(
size=10000,
size=1000,
query=query,
index=ESIndex.DFG_PROJECTS,
cluster=ESCluster.INSE,
@@ -319,7 +318,7 @@ async def get_dfg_project_ids_by_names(names: list[str]) -> list[str]:
response = await elasticsearch.search(
source=["projects.project_id"],
size=10000,
size=1000,
query=query,
index=ESIndex.DFG_PERSONS,
cluster=ESCluster.INSE,
+97 -127
View File
@@ -2,14 +2,9 @@ import logging
from typing import Annotated
from fastapi import APIRouter, Body, Depends, Path, Query, status
from inse.auth.model import AccessTokenMetadata
from inse.auth.service import CurrentUserAccessTokenPayloadDep
from inse.institutions.institutions_search_client import (
InstitutionsSearchClient,
)
from inse.projects.logic import (
is_projects_access_forbidden
)
from inse.institutions.router import get_institutions_search_client
from inse.models.bund_project_details import BundProjectDetails
from inse.models.dfg_project_details import DfgProjectDetails
@@ -33,7 +28,6 @@ from inse.projects.model import (
SortDirection,
)
from inse.tags import Tags
from fastapi import HTTPException as HttpException
logger = logging.getLogger(__name__)
@@ -69,108 +63,6 @@ async def search_bund_projects(
)
@router.get(
"/dfg/search",
summary="Get DFG projects.",
description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.",
operation_id="getDfgProjects",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": DfgProjectPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"},
},
response_model_by_alias=False,
)
async def get_dfg_projects(
access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
raw_oa_institution_id: Annotated[
str | None, Query(description="The openalex institution ID to filter by.")
] = None,
author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None,
author_filter_ids: Annotated[list[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.")
] = None,
topic_ids: Annotated[
list[str] | None, Query(description="The openalex topic IDs to filter by.")
] = None,
filter_topic_ids: Annotated[
list[str] | None,
Query(
description="Additional topic IDs to merge into the fuzzy topic-id resolution "
"(union with topic_ids). Only used when fuzzy=True."
),
] = None,
funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None,
funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None,
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
sort_by: Annotated[str, Query(description="The field to sort by.")] = "title",
sort_direction: Annotated[
str, Query(description="The sort direction (asc or desc).")
] = "asc",
fuzzy: Annotated[
bool,
Query(description="Use topic_id resolution if True, otherwise use raw keyword search."),
] = False,
) -> DfgProjectPage:
logger.debug(
"Received request to get DFG projects for author_id=%s, author_filter_ids=%s, "
"institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, "
"funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, "
"sort_direction=%s, fuzzy=%s",
author_id,
author_filter_ids,
institution_ids,
keywords,
topic_ids,
filter_topic_ids,
title,
funding_start_years,
funding_end_years,
page,
size,
sort_by,
sort_direction,
fuzzy,
)
is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id)
if is_forbidden:
raise HttpException(
status_code=403,
detail="Access denied for the provided author ID or institution ID",
)
return await projects_service.get_dfg_projects(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
author_id=author_id,
author_filter_ids=author_filter_ids,
institution_ids=institution_ids,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
title=title,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
page=page,
size=size,
sort_by=sort_by,
sort_direction=sort_direction,
fuzzy=fuzzy,
)
@router.get(
"/dfg/{id}",
summary="Get a single DFG project.",
@@ -204,13 +96,10 @@ async def get_single_dfg_project(
"description": "Successful Response",
"model": BundProjectPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"},
},
response_model_by_alias=False,
)
async def search_bund_projects(
access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -266,14 +155,7 @@ async def search_bund_projects(
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
] = False,
) -> BundProjectPage:
is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, None)
if is_forbidden:
raise HttpException(
status_code=403,
detail="Access denied for the provided author ID or institution ID",
)
return await projects_service.search_bund_projects_with_filters(
access_token_metadata=access_token_metadata,
institutions_search_client=institutions_search_client,
executing_agency=executing_agency,
funding_arts=funding_arts,
@@ -335,12 +217,10 @@ from inse.projects.service import search_eu_cordis_projects
"model": EuCordisProjectSearchPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"},
},
response_model_by_alias=False,
)
async def search_eu_cordis_projects_endpoint(
access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -419,7 +299,6 @@ async def search_eu_cordis_projects_endpoint(
bool,
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
] = False,
) -> EuCordisProjectSearchPage:
logger.debug(
"Received EU CORDIS search request: raw_oa_institution_id=%s, "
@@ -451,12 +330,7 @@ async def search_eu_cordis_projects_endpoint(
sort_direction,
fuzzy,
)
is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id)
if is_forbidden:
raise HttpException(
status_code=403,
detail="Access denied for the provided author ID or institution ID",
)
return await search_eu_cordis_projects(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
@@ -755,6 +629,102 @@ async def get_institution_cordis_eu_projects_funding_over_time(
)
@router.get(
"/person/dfg/search",
summary="Get DFG projects.",
description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.",
operation_id="getDfgProjects",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": DfgProjectPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
},
response_model_by_alias=False,
)
async def get_dfg_projects(
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
raw_oa_institution_id: Annotated[
str | None, Query(description="The openalex institution ID to filter by.")
] = None,
author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None,
author_filter_ids: Annotated[list[int] | None, Query(description="The dfg author IDs to filter by.")] = None,
institution_ids: Annotated[
list[int] | None, Query(description="The institution IDs to filter by.")
] = None,
title: Annotated[
str | None, Query(description="The title to filter by.")
] = None,
keywords: Annotated[
list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.")
] = None,
topic_ids: Annotated[
list[str] | None, Query(description="The openalex topic IDs to filter by.")
] = None,
filter_topic_ids: Annotated[
list[str] | None,
Query(
description="Additional topic IDs to merge into the fuzzy topic-id resolution "
"(union with topic_ids). Only used when fuzzy=True."
),
] = None,
funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None,
funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None,
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
sort_by: Annotated[str, Query(description="The field to sort by.")] = "title",
sort_direction: Annotated[
str, Query(description="The sort direction (asc or desc).")
] = "asc",
fuzzy: Annotated[
bool,
Query(description="Use topic_id resolution if True, otherwise use raw keyword search."),
] = False,
) -> DfgProjectPage:
logger.debug(
"Received request to get DFG projects for author_id=%s, author_filter_ids=%s, "
"institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, "
"funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, "
"sort_direction=%s, fuzzy=%s",
author_id,
author_filter_ids,
institution_ids,
keywords,
topic_ids,
filter_topic_ids,
title,
funding_start_years,
funding_end_years,
page,
size,
sort_by,
sort_direction,
fuzzy,
)
return await projects_service.get_dfg_projects_by_author_id(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
author_id=author_id,
author_filter_ids=author_filter_ids,
institution_ids=institution_ids,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
title=title,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
page=page,
size=size,
sort_by=sort_by,
sort_direction=sort_direction,
fuzzy=fuzzy,
)
@router.get(
"/search",
summary="Search projects across all funders.",
+14 -51
View File
@@ -3,7 +3,6 @@ import logging
from typing import Any
from inse.exceptions import NotFoundException
from inse.auth.model import AccessTokenMetadata
from inse.institutions.institutions_search_client import (
InstitutionsSearchClient,
)
@@ -27,7 +26,9 @@ from inse.projects.eu_cordis_projects_client import (
from inse.projects.eu_cordis_projects_client import (
search_eu_cordis_projects as _search_eu_cordis_projects_es,
)
from inse.projects.logic import (
get_dfg_author_names_by_ids,
)
from inse.projects.model import (
BundProjectPage,
DfgProjectPage,
@@ -40,9 +41,8 @@ from inse.projects.model import (
ProjectType,
SortDirection,
)
from inse.projects.logic import get_dfg_author_names_by_ids
from inse.works.logic import get_publication_dois_of_author
from fastapi import HTTPException as HttpException
logger = logging.getLogger(__name__)
@@ -157,25 +157,12 @@ async def _get_dfg_project_ids_for_openalex_authors(
return list(set.intersection(*project_sets))
def _is_number_list(values: list[str] | None) -> bool:
if not values:
return True # nothing to validate, treat as valid/empty
for value in values:
if value is None or value == "":
return False
try:
float(value)
except (TypeError, ValueError):
return False
return True
async def get_dfg_projects(
async def get_dfg_projects_by_author_id(
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str | None,
author_id: str | None,
author_filter_ids: list[str] | None,
institution_ids: list[str] | None,
author_filter_ids: list[int] | None,
institution_ids: list[int] | None,
keywords: list[str] | None,
topic_ids: list[str] | None,
filter_topic_ids: list[str] | None,
@@ -209,23 +196,6 @@ async def get_dfg_projects(
sort_direction,
fuzzy,
)
# Validate author_filter_ids / institution_ids. Return an empty page
if not _is_number_list(author_filter_ids) or not _is_number_list(institution_ids):
logger.debug(
"Invalid author_filter_ids=%s or institution_ids=%s, returning empty page",
author_filter_ids,
institution_ids,
)
return DfgProjectPage(elements=[], page=page, size=size, total=0)
author_filter_ids_int = (
[int(float(v)) for v in author_filter_ids] if author_filter_ids else None
)
institution_ids_int = (
[int(float(v)) for v in institution_ids] if institution_ids else None
)
filter_names = []
author_project_ids = []
if author_id:
@@ -238,23 +208,19 @@ async def get_dfg_projects(
size=size,
total=0)
if author_filter_ids_int:
if author_filter_ids:
filter_names = (
await get_dfg_author_names_by_ids(author_ids=author_filter_ids_int)
if author_filter_ids_int
await get_dfg_author_names_by_ids(author_ids=author_filter_ids)
if author_filter_ids
else []
)
if author_filter_ids_int and not filter_names:
if author_filter_ids and not filter_names:
logger.debug(
"No author names found for author_filter_ids=%s",
author_filter_ids_int,
author_filter_ids,
)
institution_aliases = []
if raw_oa_institution_id:
if institutions_search_client is None:
raise ValueError(
"institutions_search_client must be provided when raw_oa_institution_id is set"
)
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
@@ -273,7 +239,7 @@ async def get_dfg_projects(
institution_aliases=institution_aliases,
project_ids=author_project_ids,
names=filter_names or [],
institution_ids=institution_ids_int,
institution_ids=institution_ids,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
@@ -462,10 +428,6 @@ async def search_bund_projects_with_filters(
) -> BundProjectPage:
institution_aliases = []
if raw_oa_institution_id:
if institutions_search_client is None:
raise ValueError(
"institutions_search_client must be provided when raw_oa_institution_id is set"
)
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
@@ -680,6 +642,7 @@ async def search_eu_cordis_projects(
eu_cordis_projects_client.search_eu_cordis_projects.
"""
resolved_organization_names: list[str] = list(organization_names or [])
if raw_oa_institution_id:
if institutions_search_client is None:
raise ValueError(
@@ -1,6 +1,5 @@
import asyncio
import logging
import re
from typing import Any
from inse.integrations import elasticsearch
@@ -12,17 +11,6 @@ logger = logging.getLogger(__name__)
DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514"
DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
# Reserved characters and boolean operators of the Lucene query_string syntax
_LUCENE_SPECIAL_CHARS = re.compile(r'([+\-=&|><!(){}\[\]^"~*?:\\/])')
_LUCENE_BOOL_OPERATORS = re.compile(r"\b(AND|OR|NOT)\b")
def escape_lucene_query(term: str) -> str:
"""Escapes a free-text search term so it is safe inside a ``query_string`` query."""
if not term:
return ""
escaped = _LUCENE_SPECIAL_CHARS.sub(r"\\\1", term)
return _LUCENE_BOOL_OPERATORS.sub(lambda m: f'"{m.group(1)}"', escaped)
def clean_inst_id(id_str: str) -> str:
@@ -419,56 +407,6 @@ class TrendQueryBuilder:
}
}
@staticmethod
def build_cc_news_year_agg_body(
term: str,
start_year: int,
end_year: int,
languages: list[str] | None = None,
) -> dict[str, Any]:
"""Builds a size=0 yearly-count aggregation over the Common Crawl News indices. Buckets
by year with a `date_histogram`, since cc-news has a real `content_date` date field rather than
the integer `date_year` of `aktuell`.
"""
return {
"size": 0,
"track_total_hits": False,
"_source": False,
"query": {
"bool": {
"filter": [
{
"query_string": {
"query": escape_lucene_query(term),
"fields": CC_NEWS_SEARCH_FIELDS,
"default_operator": "AND",
}
},
{"terms": {"language_code": languages or CC_NEWS_LANGUAGES}},
{
"range": {
"content_date": {
"gte": f"{start_year}-01-01",
"lte": f"{end_year}-12-31",
"format": "yyyy-MM-dd",
}
}
},
]
}
},
"aggs": {
"by_year": {
"date_histogram": {
"field": "content_date",
"calendar_interval": "year",
"format": "yyyy",
"min_doc_count": 0,
}
}
},
}
@staticmethod
def build_bund_receiver_clause(aliases: list[str]) -> dict[str, Any]:
"""Builds Zuwendungsempfänger matching clause for BUND projects."""
@@ -505,7 +443,4 @@ DFG_PROJECT_TEXT_FIELDS = [
CORDIS_PROJECT_TEXT_FIELDS = ["title", "objective"]
AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"]
CC_NEWS_SEARCH_FIELDS = ["title", "body"]
CC_NEWS_LANGUAGES = ["de", "en"]
CC_NEWS_START_YEAR = 2017
@@ -16,13 +16,11 @@ from .model import (
)
from .trend_query_builder import (
AKTUELLES_SEARCH_FIELDS,
CC_NEWS_START_YEAR,
DEFAULT_INSTITUTION_ID,
DEFAULT_INSTITUTION_NAME,
TrendMetadataResolver,
TrendQueryBuilder,
clean_inst_id,
escape_lucene_query,
to_full_inst_url,
)
@@ -49,13 +47,6 @@ EPO_PATENT_FIELDS = [
"openalex_topics.topic_id",
]
# Synthetic entity id prefixes for the news trend series. The webapp keys colouring, chip
# visibility and pie filtering off these, so keep them in sync with uni-trend-parent.component.ts.
NEWS_ENTITY_PREFIX = "news_topic_"
CC_NEWS_ENTITY_PREFIX = "ccnews_topic_"
# Entity id of the collapsed CC-News series in the cross-domain ("all") view.
CC_NEWS_COMPOSITE_ID = "ccnews"
DFG_INSTITUTION_FIELDS = [
"Antragstellende Institution",
"Mitantragstellende Institution",
@@ -1051,18 +1042,6 @@ class ProjectsTrendStrategy(TrendStrategy):
class NewsTrendStrategy(TrendStrategy):
"""Yearly news counts per topic.
Produces one series per topic from the UDE-internal `aktuell` index (entity id
``news_topic_<topic>``). When keyword matching is active (``fuzzy=False``) it additionally
produces an external Common Crawl News baseline per topic (``ccnews_topic_<topic>``) so the
internal coverage can be compared against the wider web. CC-News has no OpenAlex topic
mapping, so it is skipped entirely in topic-mapping mode.
"""
def __init__(self, include_cc_news: bool = True):
self.include_cc_news = include_cc_news
async def get_trend(
self,
topics: list[str],
@@ -1075,40 +1054,20 @@ class NewsTrendStrategy(TrendStrategy):
) -> TrendResponse:
years_range = self._get_years_range()
start_year, end_year = years_range[0], years_range[-1]
years_set = set(years_range)
cc_news_enabled = self.include_cc_news and not fuzzy
accumulated_data = {
f"{NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
f"news_topic_{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
for t in topics
}
if cc_news_enabled:
accumulated_data.update({
f"{CC_NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
for t in topics
})
STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"}
def resolve_keyword_term(idx: int, t_name: str) -> str:
"""Picks the raw keyword for a topic, falling back to the topic name itself."""
if keywords and idx < len(keywords) and keywords[idx]:
raw_kw = keywords[idx]
term = raw_kw.split(",")[0].strip() if isinstance(raw_kw, str) else raw_kw
if term:
return term
return t_name
def is_searchable_term(term: str) -> bool:
return bool(term) and term.lower() not in STOP_WORDS and len(term.strip()) > 1
# Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs
async def fetch_news_ids_for_term(idx: int, t_name: str) -> list[str]:
news_ids: Set[str] = set()
if fuzzy:
term = t_name
es_query = {"match_phrase": {"topic_matches.topic_display_name": term}}
es_query = {"term": {"topic_matches.topic_display_name.keyword": term}}
try:
async for hit in elasticsearch.scan(
index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value,
@@ -1122,14 +1081,20 @@ class NewsTrendStrategy(TrendStrategy):
except Exception as e:
logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e)
else:
term = resolve_keyword_term(idx, t_name)
if keywords and idx < len(keywords) and keywords[idx]:
raw_kw = keywords[idx]
term = raw_kw.split(",")[0].strip() if isinstance(raw_kw, str) else raw_kw
if not term:
term = t_name
else:
term = t_name
# If non-fuzzy keyword search, search article content fields in 'aktuell' index
if is_searchable_term(term):
if term and term.lower() not in STOP_WORDS and len(term.strip()) > 1:
try:
content_query = {
"query_string": {
"query": escape_lucene_query(term),
"query": term,
"fields": AKTUELLES_SEARCH_FIELDS,
"default_operator": "AND",
}
@@ -1148,59 +1113,12 @@ class NewsTrendStrategy(TrendStrategy):
return list(news_ids)
async def fetch_cc_news_counts() -> dict[int, dict[int, int]]:
"""Yearly CC-News counts per topic index, from a single _msearch over cc-news-*.
The year buckets are read straight off a size=0 date_histogram instead.
"""
searchable = [
(idx, term)
for idx, t_name in enumerate(topics)
if is_searchable_term(term := resolve_keyword_term(idx, t_name))
]
if not searchable:
return {}
searches = [
(
ESIndex.CC_NEWS_WILDCARD.value,
TrendQueryBuilder.build_cc_news_year_agg_body(term, CC_NEWS_START_YEAR, end_year),
)
for _, term in searchable
]
try:
responses = await elasticsearch.msearch(
searches, cluster=ESCluster.NES, request_cache=True
)
except Exception as e:
logger.warning("Failed to aggregate CC-News years via msearch: %s", e)
return {}
counts: dict[int, dict[int, int]] = {}
for (topic_idx, term), res in zip(searchable, responses):
if not isinstance(res, dict) or "error" in res:
logger.warning("CC-News msearch entry for %r failed: %s", term, (res or {}).get("error"))
continue
by_year: dict[int, int] = {}
for b in res.get("aggregations", {}).get("by_year", {}).get("buckets", []):
try:
yr = int(b.get("key_as_string"))
except (TypeError, ValueError):
continue
if yr in years_set:
by_year[yr] = int(b.get("doc_count", 0))
counts[topic_idx] = by_year
return counts
news_ids_future = asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics)))
if cc_news_enabled:
matching_ids_list, cc_news_counts = await asyncio.gather(news_ids_future, fetch_cc_news_counts())
else:
matching_ids_list, cc_news_counts = await news_ids_future, {}
matching_ids_list = await asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics)))
async def count_by_year(t_name: str, news_ids: list[str]):
if not news_ids:
return
entity_key = f"{NEWS_ENTITY_PREFIX}{t_name}"
entity_key = f"news_topic_{t_name}"
# Prepare multi-search payloads for chunks of news_ids to avoid payload limits
chunk_queries = []
@@ -1246,15 +1164,13 @@ class NewsTrendStrategy(TrendStrategy):
await asyncio.gather(*(count_by_year(t, ids) for t, ids in zip(topics, matching_ids_list)))
for topic_idx, t_name in enumerate(topics):
entity_key = f"{CC_NEWS_ENTITY_PREFIX}{t_name}"
for yr, count in cc_news_counts.get(topic_idx, {}).items():
prev_count, _ = accumulated_data[entity_key][t_name][yr]
accumulated_data[entity_key][t_name][yr] = (prev_count + count, 1)
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
def build_series(entity_key: str, t_name: str, entity_name: str) -> TrendSeries:
series_list: list[TrendSeries] = []
for t_name in topics:
entity_key = f"news_topic_{t_name}"
topic_data_map: dict[str, list[TopicYearlyData]] = {}
lookup = normalized_lookup.get((entity_key, t_name), {})
norm_vals = lookup.get("normalized", [0.0] * len(years_range))
cum_vals = lookup.get("cumulative", [0.0] * len(years_range))
@@ -1272,22 +1188,16 @@ class NewsTrendStrategy(TrendStrategy):
)
)
topic_data_map: dict[str, list[TopicYearlyData]] = {topic: yearly_data_items for topic in topics}
for topic in topics:
topic_data_map[topic] = yearly_data_items
return TrendSeries(
entity_id=entity_key,
entity_name=entity_name,
entity_type="institution",
topic_data=topic_data_map,
)
series_list: list[TrendSeries] = [
build_series(f"{NEWS_ENTITY_PREFIX}{t_name}", t_name, t_name) for t_name in topics
]
if cc_news_enabled:
series_list.extend(
build_series(f"{CC_NEWS_ENTITY_PREFIX}{t_name}", t_name, f"{t_name} (CC-News)")
for t_name in topics
series_list.append(
TrendSeries(
entity_id=entity_key,
entity_name=t_name,
entity_type="institution",
topic_data=topic_data_map,
)
)
return TrendResponse(series=series_list, years=years_range)
@@ -1359,40 +1269,25 @@ class AllTrendStrategy(TrendStrategy):
add_composite(pat_series, "patents", "Patentanmeldungen")
add_composite(proj_series, "projects", "Drittmittelförderung")
def merge_news_composite(prefix: str, c_id: str, c_name: str) -> bool:
"""Collapses the per-topic news series of one source into a single composite.
Returns False when the source produced no series at all.
"""
if not news_res or not any(s.entity_id.startswith(prefix) for s in news_res.series):
return False
merged_topic_data: dict[str, list[TopicYearlyData]] = {}
if is_ude and news_res:
merged_news_topic_data: dict[str, list[TopicYearlyData]] = {}
for topic in topics:
term_key = f"{prefix}{topic}"
term_key = f"news_topic_{topic}"
matching_series = next((s for s in news_res.series if s.entity_id == term_key), None)
if matching_series and topic in matching_series.topic_data:
merged_topic_data[topic] = matching_series.topic_data[topic]
merged_news_topic_data[topic] = matching_series.topic_data[topic]
else:
merged_topic_data[topic] = [
merged_news_topic_data[topic] = [
TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1)
for yr in years_range
]
add_composite(
TrendSeries(
entity_id=c_id,
entity_name=c_name,
entity_type="institution",
topic_data=merged_topic_data,
),
c_id,
c_name,
news_series = TrendSeries(
entity_id="news",
entity_name="UDE Campus Aktuell Beiträge",
entity_type="institution",
topic_data=merged_news_topic_data,
)
return True
if is_ude:
merge_news_composite(NEWS_ENTITY_PREFIX, "news", "UDE Campus Aktuell Beiträge")
merge_news_composite(CC_NEWS_ENTITY_PREFIX, CC_NEWS_COMPOSITE_ID, "Web-Nachrichten (CC-News)")
add_composite(news_series, "news", "UDE Campus Aktuell Beiträge")
return TrendResponse(series=composite_series, years=years_range)
@@ -654,7 +654,6 @@ async def _search_works(
size=size,
offset=page * size,
sort=sort,
track_total_hits=True
)
hits_block = response.get("hits", {})
+14 -26
View File
@@ -66,7 +66,7 @@ export class ProjectsService extends BaseService {
/**
* Get DFG projects.
* Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.
* @endpoint get /api/projects/dfg/search
* @endpoint get /api/projects/person/dfg/search
* @param rawOaInstitutionId The openalex institution ID to filter by.
* @param authorId The openalex author ID to filter by.
* @param authorFilterIds The dfg author IDs to filter by.
@@ -82,14 +82,13 @@ export class ProjectsService extends BaseService {
* @param sortBy The field to sort by.
* @param sortDirection The sort direction (asc or desc).
* @param fuzzy Use topic_id resolution if True, otherwise use raw keyword search.
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<string>, institutionIds?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgProjectPage>;
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<string>, institutionIds?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgProjectPage>>;
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<string>, institutionIds?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgProjectPage>>;
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<string>, institutionIds?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgProjectPage>;
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgProjectPage>>;
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgProjectPage>>;
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -153,9 +152,6 @@ 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'
]);
@@ -179,7 +175,7 @@ export class ProjectsService extends BaseService {
}
}
let localVarPath = `/api/projects/dfg/search`;
let localVarPath = `/api/projects/person/dfg/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<DfgProjectPage>('get', `${basePath}${localVarPath}`,
{
@@ -850,14 +846,13 @@ export class ProjectsService extends BaseService {
* @param sortBy Sort field.
* @param sortDirection Sort direction: asc or desc.
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<BundProjectPage>;
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<BundProjectPage>>;
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<BundProjectPage>>;
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<BundProjectPage>;
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<BundProjectPage>>;
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<BundProjectPage>>;
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (executingAgency) {
@@ -925,9 +920,6 @@ 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'
]);
@@ -992,14 +984,13 @@ export class ProjectsService extends BaseService {
* @param sortBy Sort field.
* @param sortDirection Sort direction: asc or desc.
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<EuCordisProjectSearchPage>;
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<EuCordisProjectSearchPage>>;
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<EuCordisProjectSearchPage>>;
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<EuCordisProjectSearchPage>;
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<EuCordisProjectSearchPage>>;
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<EuCordisProjectSearchPage>>;
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -1099,9 +1090,6 @@ 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'
]);
+13 -3
View File
@@ -693,9 +693,7 @@ export const routes: Routes = [
bundProjectsFunding: bundProjectsFundingResolver,
cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
},
data: {
enableFilters: false,
},
runGuardsAndResolvers: 'always',
children: [
{
path: '',
@@ -745,6 +743,18 @@ export const routes: Routes = [
},
},
],
// resolve: {
// bundProjectPage: bundProjectPageResolver,
// bundProjectsFunding: bundProjectsFundingResolver,
// cordisEuProjectPage: euCordisProjectsResolver,
// cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
// },
// runGuardsAndResolvers: (from, to) => {
// const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
// return keys.some(
// (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
// );
// },
},
{
path: 'patents',
@@ -108,7 +108,7 @@ export class DashboardComponent implements OnInit {
readonly topicTreemapMinYear = 1900;
readonly topicTreemapMaxYear = new Date().getFullYear();
dashboardPeriodMode: DashboardPeriodMode = 'all_time';
dashboardFromYear = this.topicTreemapMaxYear - 4;
dashboardFromYear = this.topicTreemapMinYear;
dashboardToYear = this.topicTreemapMaxYear;
selectedTopicTreemapNode?: string;
selectedDfgTopicTreemapNode?: string;
@@ -406,14 +406,16 @@ export class DashboardComponent implements OnInit {
this.dashboardPeriodMode = mode;
}
this.applyPresetPeriod();
this.dashboardFromYear = this.parseDashboardYear(
params.get('fromYear'),
this.dashboardFromYear,
);
this.dashboardToYear = this.parseDashboardYear(
params.get('toYear'),
this.dashboardToYear,
);
if (this.dashboardPeriodMode !== 'all_time') {
this.dashboardFromYear = this.parseDashboardYear(
params.get('fromYear'),
this.dashboardFromYear,
);
this.dashboardToYear = this.parseDashboardYear(
params.get('toYear'),
this.dashboardToYear,
);
}
if (this.dashboardFromYear > this.dashboardToYear) {
this.dashboardFromYear = this.dashboardToYear;
}
@@ -422,7 +424,10 @@ export class DashboardComponent implements OnInit {
private applyPresetPeriod(): void {
const currentYear = this.topicTreemapMaxYear;
if (this.dashboardPeriodMode === 'last_10_years') {
if (this.dashboardPeriodMode === 'all_time') {
this.dashboardFromYear = this.topicTreemapMinYear;
this.dashboardToYear = currentYear;
} else if (this.dashboardPeriodMode === 'last_10_years') {
this.dashboardFromYear = currentYear - 9;
this.dashboardToYear = currentYear;
} else if (this.dashboardPeriodMode === 'last_5_years') {
@@ -54,13 +54,11 @@
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="sort"></mat-icon>
<mat-select
[value]="sortColumn"
(selectionChange)="setSort($event.value)">
[value]="sortMode"
(selectionChange)="setSortMode($event.value)">
<mat-select-trigger>Sortieren nach</mat-select-trigger>
<mat-option value="year">Jahr</mat-option>
<mat-option value="date">Datum</mat-option>
<mat-option value="title">Titel</mat-option>
<mat-option value="source">Quelle</mat-option>
<mat-option value="matchType">Match-Typ</mat-option>
</mat-select>
</mat-form-field>
</div>
@@ -69,41 +67,11 @@
<thead>
<tr>
<th>Patent</th>
<th
class="sortable"
[class.sort-active]="sortColumn === 'source'"
(click)="setSort('source')">
Quelle
@if (sortColumn === 'source') {
<mat-icon class="sort-icon">{{
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
}}</mat-icon>
}
</th>
<th
class="sortable"
[class.sort-active]="sortColumn === 'year'"
(click)="setSort('year')">
Jahr
@if (sortColumn === 'year') {
<mat-icon class="sort-icon">{{
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
}}</mat-icon>
}
</th>
<th>Quelle</th>
<th>Jahr</th>
<th>Erfinder</th>
<th>Applicant/Assignee</th>
<th
class="sortable"
[class.sort-active]="sortColumn === 'matchType'"
(click)="setSort('matchType')">
Match-Typ
@if (sortColumn === 'matchType') {
<mat-icon class="sort-icon">{{
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
}}</mat-icon>
}
</th>
<th>Match-Typ</th>
<th>Personen</th>
</tr>
</thead>
@@ -126,86 +94,9 @@
{{ patent.source }}
</span>
</td>
<td>
@if (patent.publication_year) {
<span class="year-badge">{{
patent.publication_year
}}</span>
} @else {
<span>-</span>
}
</td>
<td class="patent-people">
@if (patent.inventors && patent.inventors.length) {
<div class="person-chips">
@for (
inventor of patent.inventors.slice(0, 2);
track inventor
) {
<span class="person-chip">
<mat-icon>person</mat-icon>
{{ inventor }}
</span>
}
@if (patent.inventors.length > 2) {
<span class="person-chip-row">
<span class="person-chip">
<mat-icon>person</mat-icon>
{{ patent.inventors[2] }}
</span>
@if (patent.inventors.length > 3) {
<span class="person-chip person-chip--more"
>+{{ patent.inventors.length - 3 }}</span
>
}
</span>
}
</div>
} @else {
<span>-</span>
}
</td>
<td class="patent-people">
@if (patent.assignees && patent.assignees.length) {
<div class="person-chips">
@for (
assignee of patent.assignees.slice(0, 2);
track assignee
) {
<span class="person-chip">
<mat-icon>{{
isAssigneeLikelyPerson(assignee, patent)
? 'person'
: 'apartment'
}}</mat-icon>
{{ assignee }}
</span>
}
@if (patent.assignees.length > 2) {
<span class="person-chip-row">
<span class="person-chip">
<mat-icon>{{
isAssigneeLikelyPerson(
patent.assignees[2],
patent
)
? 'person'
: 'apartment'
}}</mat-icon>
{{ patent.assignees[2] }}
</span>
@if (patent.assignees.length > 3) {
<span class="person-chip person-chip--more"
>+{{ patent.assignees.length - 3 }}</span
>
}
</span>
}
</div>
} @else {
<span>-</span>
}
</td>
<td>{{ patent.publication_year ?? '-' }}</td>
<td class="cell-preview">{{ getInventorsPreview(patent) }}</td>
<td class="cell-preview">{{ getAssigneesPreview(patent) }}</td>
<td>
<span
class="match-badge match-badge--{{ patent.match_type }}">
@@ -227,10 +118,6 @@
'/person',
author.openalex_author_id,
]"
[appComponentTooltip]="AuthorTooltipComponent"
[tooltipInputs]="{
authorId: author.openalex_author_id,
}"
(click)="$event.stopPropagation()">
{{ author.author_name }}
</a>
@@ -310,11 +197,7 @@
<li>
<a
class="tag author-link"
[routerLink]="['/person', author.openalex_author_id]"
[appComponentTooltip]="AuthorTooltipComponent"
[tooltipInputs]="{
authorId: author.openalex_author_id,
}">
[routerLink]="['/person', author.openalex_author_id]">
{{ author.author_name }}
</a>
</li>
@@ -66,24 +66,9 @@ app-query-param-paginator {
text-align: left;
padding: 12px 16px;
border-bottom: 1px solid var(--sg-border);
font-size: 12px;
font-weight: 700;
font-size: 13px;
font-weight: 600;
color: var(--sg-text-muted);
&.sortable {
display: table-cell;
cursor: pointer;
-webkit-user-select: none;
user-select: none;
}
.sort-icon {
vertical-align: middle;
margin-left: 2px;
width: 14px;
height: 14px;
font-size: 14px;
}
}
tr {
@@ -116,8 +101,13 @@ app-query-param-paginator {
word-break: break-word;
}
.patent-people {
max-width: 220px;
.cell-preview {
max-width: 160px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: var(--sg-text-muted);
font-size: 13px;
}
.cell-authors {
@@ -129,64 +119,6 @@ app-query-param-paginator {
}
}
.year-badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 26px;
padding: 2px 10px;
border-radius: 999px;
border: 1px solid var(--sg-border);
color: var(--sg-text);
font-size: 0.8rem;
font-weight: 600;
}
.person-chips {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
}
.person-chip-row {
display: flex;
flex-direction: row;
align-items: center;
flex-wrap: wrap;
gap: 4px;
}
.person-chip {
display: inline-flex;
align-items: center;
gap: 4px;
max-width: 100%;
padding: 2px 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-surface-soft);
color: var(--sg-text);
font-size: 0.75rem;
line-height: 1.4;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
mat-icon {
flex-shrink: 0;
width: 14px;
height: 14px;
font-size: 14px;
color: var(--sg-text-soft);
}
&--more {
color: var(--sg-text-muted);
font-weight: 600;
}
}
.match-badge {
display: inline-flex;
align-items: center;
@@ -13,11 +13,8 @@ import {
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { PageEvent } from '@angular/material/paginator';
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
import { AppAuthorTooltipComponent } from '../../shared/ui/app-author-tooltip/app-author-tooltip.component';
type SortColumn = 'title' | 'year' | 'source' | 'matchType';
type SortDirection = 'asc' | 'desc';
type SortMode = 'date' | 'title';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both';
@@ -31,13 +28,11 @@ type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both';
MatSelectModule,
MatIconModule,
QueryParamPaginatorComponent,
ComponentTooltipDirective,
],
templateUrl: './institution-patents.component.html',
styleUrl: './institution-patents.component.scss',
})
export class InstitutionPatentsComponent implements OnInit {
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
private route = inject(ActivatedRoute);
private router = inject(Router);
private patentsApi = inject(PatentsService);
@@ -53,8 +48,7 @@ export class InstitutionPatentsComponent implements OnInit {
activeFilter: SourceFilter = 'all';
activeMatchType: OrgPatentMatchTypeFilter = 'all';
sortColumn: SortColumn = 'year';
sortDirection: SortDirection = 'desc';
sortMode: SortMode = 'date';
pageIndex = 0;
pageSize = 20;
@@ -65,8 +59,7 @@ export class InstitutionPatentsComponent implements OnInit {
const institutionId = params.get('institutionId') ?? '';
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
const sortByFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
const sortDirFromUrl = this.route.snapshot.queryParamMap.get('sortDir');
const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
const matchTypeFromUrl =
this.route.snapshot.queryParamMap.get('matchType');
this.pageIndex = this.parsePageIndexParam(
@@ -79,11 +72,8 @@ export class InstitutionPatentsComponent implements OnInit {
if (this.isValidFilter(filterFromUrl)) {
this.activeFilter = filterFromUrl;
}
if (this.isValidSortColumn(sortByFromUrl)) {
this.sortColumn = sortByFromUrl;
}
if (this.isValidSortDirection(sortDirFromUrl)) {
this.sortDirection = sortDirFromUrl;
if (this.isValidSortMode(sortFromUrl)) {
this.sortMode = sortFromUrl;
}
if (this.isValidMatchType(matchTypeFromUrl)) {
this.activeMatchType = matchTypeFromUrl;
@@ -111,13 +101,8 @@ export class InstitutionPatentsComponent implements OnInit {
this.reloadPatents();
}
setSort(column: SortColumn): void {
if (this.sortColumn === column) {
this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
} else {
this.sortColumn = column;
this.sortDirection = column === 'year' ? 'desc' : 'asc';
}
setSortMode(sortMode: SortMode): void {
this.sortMode = sortMode;
this.filteredPatents = this.sortPatents(this.patents);
this.updateQueryParams();
}
@@ -183,27 +168,14 @@ export class InstitutionPatentsComponent implements OnInit {
}
private sortPatents(patents: OrgPatentEntry[]): OrgPatentEntry[] {
const direction = this.sortDirection === 'asc' ? 1 : -1;
return [...patents].sort((a, b) => {
switch (this.sortColumn) {
case 'year': {
const yearA = a.publication_date ?? String(a.publication_year ?? '');
const yearB = b.publication_date ?? String(b.publication_year ?? '');
return direction * yearA.localeCompare(yearB);
}
case 'source':
return direction * a.source.localeCompare(b.source);
case 'matchType':
return direction * a.match_type.localeCompare(b.match_type);
default:
return (
direction *
(a.title ?? '').localeCompare(b.title ?? '', 'de', {
sensitivity: 'base',
})
);
}
});
if (this.sortMode === 'title') {
return [...patents].sort((a, b) =>
(a.title ?? '').localeCompare(b.title ?? '', 'de', {
sensitivity: 'base',
}),
);
}
return [...patents];
}
private updateQueryParams(): void {
@@ -211,8 +183,7 @@ export class InstitutionPatentsComponent implements OnInit {
relativeTo: this.route,
queryParams: {
filter: this.activeFilter,
sortBy: this.sortColumn,
sortDir: this.sortDirection,
sortBy: this.sortMode,
matchType: this.activeMatchType,
page: this.pageIndex,
size: this.pageSize,
@@ -236,17 +207,8 @@ export class InstitutionPatentsComponent implements OnInit {
return value === 'all' || value === 'EPO' || value === 'USPTO';
}
private isValidSortColumn(value: string | null): value is SortColumn {
return (
value === 'title' ||
value === 'year' ||
value === 'source' ||
value === 'matchType'
);
}
private isValidSortDirection(value: string | null): value is SortDirection {
return value === 'asc' || value === 'desc';
private isValidSortMode(value: string | null): value is SortMode {
return value === 'date' || value === 'title';
}
private isValidMatchType(
@@ -325,40 +287,18 @@ export class InstitutionPatentsComponent implements OnInit {
}
}
private static readonly ORG_SUFFIX_PATTERN =
/\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i;
private static readonly PERSON_SUFFIX_PATTERN =
/\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i;
private normalizeNameForComparison(name: string): string {
return name
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/[.,]/g, '')
.toUpperCase()
.split(/\s+/)
.filter(Boolean)
.sort()
.join(' ');
getInventorsPreview(patent: OrgPatentEntry): string {
if (!patent.inventors?.length) {
return '-';
}
return patent.inventors.slice(0, 2).join(', ');
}
isAssigneeLikelyPerson(assignee: string, patent: OrgPatentEntry): boolean {
if (InstitutionPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) {
return false;
getAssigneesPreview(patent: OrgPatentEntry): string {
if (!patent.assignees?.length) {
return '-';
}
const normalizedAssignee = this.normalizeNameForComparison(
assignee.replace(InstitutionPatentsComponent.PERSON_SUFFIX_PATTERN, ''),
);
const matchesInventor = (patent.inventors ?? []).some(
(inventor) =>
this.normalizeNameForComparison(inventor) === normalizedAssignee,
);
if (matchesInventor) {
return true;
}
return InstitutionPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee);
return patent.assignees.slice(0, 2).join(', ');
}
getMatchedAuthorsPreview(patent: OrgPatentEntry): string {
@@ -1,15 +1,30 @@
<div class="content">
<div>
<h6>Projekte</h6>
<p>Übersicht der Projekte, die von der Institution durchgeführt werden.</p>
</div>
<h3>Projekte</h3>
<mat-accordion multi>
<mat-expansion-panel class="mat-elevation-z1">
<mat-expansion-panel-header>
<mat-panel-title>Förderung über Zeit</mat-panel-title>
</mat-expansion-panel-header>
<div class="funding-area">
<div class="person-projects">
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
@for (route of childRoutes; track route.path) {
<a
matTabLink
[routerLink]="[route.path]"
[queryParams]="{
authorId: null,
institutionId: null,
agency: null,
}"
queryParamsHandling="merge"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive">
{{ route.label }}
</a>
}
</nav>
<mat-tab-nav-panel #resultTabPanel>
<router-outlet />
</mat-tab-nav-panel>
<div class="funding-info-section">
<mat-card appearance="outlined">
<mat-card-header>
@@ -41,35 +56,15 @@
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-info-card
[description]="
'Durchschnittliche jährliche Förderung durch die Europäische Union'
"
[description]="'Durchschnittliche jährliche Förderung durch die Europäische Union'"
[value]="
(euAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
</div>
</div>
</mat-expansion-panel>
<mat-expansion-panel class="mat-elevation-z1" [expanded]="true">
<mat-expansion-panel-header>
<mat-panel-title>Projektliste</mat-panel-title>
</mat-expansion-panel-header>
<div class="person-projects">
@if (resultTabPanel) {
<app-link-tab-nav-bar
[links]="_links()"
[tabPanel]="resultTabPanel" />
}
<mat-tab-nav-panel #resultTabPanel>
<router-outlet />
</mat-tab-nav-panel>
</div>
</mat-expansion-panel>
</mat-accordion>
</div>
</div>
<ng-template #fundingStartTmp let-row>
{{ row.funding_start | date: 'dd.MM.yyyy' }}
@@ -84,8 +79,8 @@
<ng-template #euProjectActionsTmp let-row>
<a mat-icon-button color="primary" [routerLink]="['/projects/eu', row.id]">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
</a></ng-template
>
<ng-template #bundProjectActionsTmp let-row>
<a
@@ -1,30 +1,22 @@
.content {
padding: 16px;
}
mat-card,
mat-paginator {
background-color: var(--sg-background);
}
.funding-area {
display: flex;
flex-direction: column;
gap: 1rem;
padding: 2rem;
}
mat-expansion-panel {
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-none);
box-shadow: none;
}
mat-expansion-panel-header {
padding: 0 16px;
min-height: 48px;
}
mat-panel-title {
font-size: 16px;
font-weight: 700;
}
mat-panel-description {
font-size: 14px;
color: var(--sg-text-muted);
.funding-info-section {
display: flex;
flex-direction: column;
gap: 1rem;
}
.funding-info-cards {
@@ -17,7 +17,6 @@ import {
import { BundProjectSummary } from '../../api/model/bundProjectSummary';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatTabChangeEvent, MatTabsModule } from '@angular/material/tabs';
import { FormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
@@ -28,10 +27,7 @@ import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { InstitutionProjectsFundingGraphComponent } from '../institution-projects-funding-graph/institution-projects-funding-graph.component';
import { AppInfoCardComponent } from '../../shared/ui/app-info-card/app-info-card.component';
import {
LinkTabNavBarComponent,
LinkTabNavBarItem,
} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
type BundProjectRow = {
id: string;
topic: string;
@@ -55,7 +51,6 @@ type EuProjectRow = {
MatCardModule,
MatFormFieldModule,
MatTabsModule,
MatExpansionModule,
FormsModule,
MatInputModule,
DatePipe,
@@ -64,7 +59,6 @@ type EuProjectRow = {
MatButtonModule,
InstitutionProjectsFundingGraphComponent,
AppInfoCardComponent,
LinkTabNavBarComponent,
RouterModule,
],
templateUrl: './institution-projects.component.html',
@@ -128,27 +122,6 @@ export class InstitutionProjectsComponent implements OnInit {
label: 'BUND-Projekte',
},
];
_links = computed<LinkTabNavBarItem[]>(() => {
const links: LinkTabNavBarItem[] = [
{
label: 'DFG-Projekte',
path: 'dfg',
disabled: false,
},
{
label: 'EU-Projekte',
path: 'eu',
disabled: false,
},
{
label: 'BUND-Projekte',
path: 'bund',
disabled: false,
},
];
return links;
});
constructor(
private readonly activatedRoute: ActivatedRoute,
private readonly router: Router,
@@ -302,4 +275,12 @@ export class InstitutionProjectsComponent implements OnInit {
return 0;
}
});
selectedTabChange(event: MatTabChangeEvent): void {
const tab = ['eu', 'bund'][event.index];
this.router.navigate([], {
queryParams: { project_tab: tab, page: 0, size: 10 },
queryParamsHandling: 'merge',
});
}
}
@@ -16,7 +16,8 @@
<mat-expansion-panel class="mat-elevation-z1" [expanded]="true">
<mat-expansion-panel-header>
<mat-panel-title>Publikationsliste</mat-panel-title>
<mat-panel-description>
<mat-panel-description
>{{ total() >= 10000 ? 'mehr als' : '' }}
{{ total() }} Publikationen</mat-panel-description
>
</mat-expansion-panel-header>
@@ -1,15 +1,27 @@
<div class="container">
<div class="content">
<h1>{{ institution().display_name }}</h1>
<mat-card appearance="outlined">
<mat-card-content>
<p>{{ institution().homepage_url }}</p>
<p>{{ institution().display_name_alternatives }}</p>
<p>And many more useful details...</p>
</mat-card-content>
</mat-card>
</div>
<app-link-tab-nav-bar [links]="_links()" [tabPanel]="tabPanel" />
<div class="content">
<h1>{{ institution().display_name }}</h1>
<mat-card appearance="outlined">
<mat-card-content>
<p>{{ institution().homepage_url }}</p>
<p>{{ institution().display_name_alternatives }}</p>
<p>And many more useful details...</p>
</mat-card-content>
</mat-card>
<nav mat-tab-nav-bar [tabPanel]="tabPanel">
@for (link of _links(); track link.path) {
<a
mat-tab-link
[routerLink]="link.path"
[queryParams]="link.queryParams"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive"
[disabled]="link.disabled">
{{ link.label }}
</a>
}
</nav>
</div>
<mat-tab-nav-panel #tabPanel>
<router-outlet />
@@ -1,12 +1,6 @@
.container {
display: flex;
flex-direction: column;
gap: 1rem;
}
.content {
padding: 16px;
display: flex;
flex-direction: column;
gap: 1rem;
margin: 0 1rem;
gap: 16px;
}
@@ -1,21 +1,25 @@
import { Component, computed, input } from '@angular/core';
import { RouterModule } from '@angular/router';
import { RouterLink, RouterOutlet, RouterLinkActive } from '@angular/router';
import { Institution } from '../../api';
import { MatCardModule } from '@angular/material/card';
import { MatTabsModule } from '@angular/material/tabs';
import {
LinkTabNavBarComponent,
LinkTabNavBarItem,
} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
import {
PATENT_ICON,
PROJECT_ICON,
PUBLICATION_ICON,
} from '../../shared/ui/icons';
type TabLink = {
label: string;
path: string;
disabled: boolean;
queryParams?: Record<string, any>;
};
@Component({
selector: 'app-institution',
imports: [MatCardModule, MatTabsModule, RouterModule, LinkTabNavBarComponent],
imports: [
MatCardModule,
MatTabsModule,
RouterLink,
RouterOutlet,
RouterLinkActive,
],
templateUrl: './institution.component.html',
styleUrl: './institution.component.scss',
})
@@ -23,20 +27,14 @@ export class InstitutionComponent {
institution = input.required<Institution>();
canFetchGdprRelevantData = input.required<boolean>();
_links = computed<LinkTabNavBarItem[]>(() => {
const links: LinkTabNavBarItem[] = [
{
label: 'Publikationen',
icon: PUBLICATION_ICON,
path: 'publications',
disabled: false,
},
_links = computed<TabLink[]>(() => {
const links: TabLink[] = [
{ label: 'Publikationen', path: 'publications', disabled: false },
];
if (this.canFetchGdprRelevantData()) {
links.push(
{
label: 'Projekte',
icon: PROJECT_ICON,
path: 'projects',
disabled: false,
queryParams: {
@@ -48,12 +46,7 @@ export class InstitutionComponent {
sort_direction: 'asc',
},
},
{
label: 'Patente',
icon: PATENT_ICON,
path: 'patents',
disabled: false,
},
{ label: 'Patente', path: 'patents', disabled: false },
);
}
return links;
@@ -31,12 +31,11 @@
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="sort"></mat-icon>
<mat-select
[value]="sortColumn()"
(selectionChange)="setSort($event.value)">
[value]="sortMode()"
(selectionChange)="setSortMode($event.value)">
<mat-select-trigger>Sortieren nach</mat-select-trigger>
<mat-option value="year">Jahr</mat-option>
<mat-option value="date">Datum</mat-option>
<mat-option value="title">Titel</mat-option>
<mat-option value="source">Quelle</mat-option>
</mat-select>
</mat-form-field>
</div>
@@ -45,32 +44,8 @@
<thead>
<tr>
<th>Patent</th>
<th
class="sortable"
[class.sort-active]="sortColumn() === 'source'"
(click)="setSort('source')">
Quelle
@if (sortColumn() === 'source') {
<mat-icon class="sort-icon">{{
sortDirection() === 'asc'
? 'arrow_upward'
: 'arrow_downward'
}}</mat-icon>
}
</th>
<th
class="sortable"
[class.sort-active]="sortColumn() === 'year'"
(click)="setSort('year')">
Jahr
@if (sortColumn() === 'year') {
<mat-icon class="sort-icon">{{
sortDirection() === 'asc'
? 'arrow_upward'
: 'arrow_downward'
}}</mat-icon>
}
</th>
<th>Quelle</th>
<th>Jahr</th>
<th>Erfinder</th>
<th>Anmelder</th>
</tr>
@@ -91,85 +66,16 @@
{{ item.patent.source }}
</span>
</td>
<td>
@if (item.patent.publication_year) {
<span class="year-badge">{{
item.patent.publication_year
}}</span>
} @else {
<span>-</span>
}
<td>{{ item.patent.publication_year ?? '-' }}</td>
<td
class="patent-people"
[title]="getInventorsLabel(item.patent)">
{{ getInventorsLabel(item.patent) }}
</td>
<td class="patent-people">
@if (item.patent.inventors && item.patent.inventors.length) {
<div class="person-chips">
@for (
inventor of item.patent.inventors.slice(0, 2);
track inventor
) {
<span class="person-chip">
<mat-icon>person</mat-icon>
{{ inventor }}
</span>
}
@if (item.patent.inventors.length > 2) {
<span class="person-chip-row">
<span class="person-chip">
<mat-icon>person</mat-icon>
{{ item.patent.inventors[2] }}
</span>
@if (item.patent.inventors.length > 3) {
<span class="person-chip person-chip--more"
>+{{ item.patent.inventors.length - 3 }}</span
>
}
</span>
}
</div>
} @else {
<span>-</span>
}
</td>
<td class="patent-people">
@if (item.patent.assignees && item.patent.assignees.length) {
<div class="person-chips">
@for (
assignee of item.patent.assignees.slice(0, 2);
track assignee
) {
<span class="person-chip">
<mat-icon>{{
isAssigneeLikelyPerson(assignee, item.patent)
? 'person'
: 'apartment'
}}</mat-icon>
{{ assignee }}
</span>
}
@if (item.patent.assignees.length > 2) {
<span class="person-chip-row">
<span class="person-chip">
<mat-icon>{{
isAssigneeLikelyPerson(
item.patent.assignees[2],
item.patent
)
? 'person'
: 'apartment'
}}</mat-icon>
{{ item.patent.assignees[2] }}
</span>
@if (item.patent.assignees.length > 3) {
<span class="person-chip person-chip--more"
>+{{ item.patent.assignees.length - 3 }}</span
>
}
</span>
}
</div>
} @else {
<span>-</span>
}
<td
class="patent-people"
[title]="getAssigneesLabel(item.patent)">
{{ getAssigneesLabel(item.patent) }}
</td>
</tr>
}
@@ -97,24 +97,9 @@ app-query-param-paginator {
text-align: left;
padding: 12px 16px;
border-bottom: 1px solid var(--sg-border);
font-size: 12px;
font-weight: 700;
font-size: 13px;
font-weight: 600;
color: var(--sg-text-muted);
&.sortable {
display: table-cell;
cursor: pointer;
-webkit-user-select: none;
user-select: none;
}
.sort-icon {
vertical-align: middle;
margin-left: 2px;
width: 14px;
height: 14px;
font-size: 14px;
}
}
tr {
@@ -148,66 +133,41 @@ app-query-param-paginator {
.patent-people {
max-width: 220px;
color: var(--sg-text-muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
.year-badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 26px;
padding: 2px 10px;
border-radius: 999px;
border: 1px solid var(--sg-border);
color: var(--sg-text);
font-size: 0.8rem;
font-weight: 600;
}
.person-chips {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
}
.person-chip-row {
display: flex;
flex-direction: row;
align-items: center;
flex-wrap: wrap;
gap: 4px;
}
.person-chip {
display: inline-flex;
align-items: center;
gap: 4px;
max-width: 100%;
padding: 2px 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-surface-soft);
color: var(--sg-text);
font-size: 0.75rem;
line-height: 1.4;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
mat-icon {
flex-shrink: 0;
width: 14px;
height: 14px;
font-size: 14px;
color: var(--sg-text-soft);
th {
text-align: left;
padding: 10px 12px;
border-bottom: 2px solid var(--sg-border);
color: var(--sg-text);
}
&--more {
color: var(--sg-text-muted);
font-weight: 600;
tr {
cursor: pointer;
color: var(--sg-text);
&:hover {
background: var(--sg-surface-soft);
}
&.selected {
background: var(--sg-surface-muted);
}
}
td {
padding: 10px 12px;
border-bottom: 1px solid var(--sg-border);
}
}
.patent-title {
font-weight: 500;
}
.source-badge {
@@ -16,8 +16,7 @@ import {
import { KeywordPatentMappingStatus } from '../../../api';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
type SortColumn = 'title' | 'year' | 'source';
type SortDirection = 'asc' | 'desc';
type SortMode = 'date' | 'title';
@Component({
selector: 'app-keywords-patents',
@@ -45,8 +44,7 @@ export class KeywordsPatentsComponent {
readonly reload = output<void>();
activeFilter = signal<SourceFilter>('all');
sortColumn = signal<SortColumn>('year');
sortDirection = signal<SortDirection>('desc');
sortMode = signal<SortMode>('date');
selectedMatch = signal<KeywordPatentMatch | null>(null);
readonly pageIndex = computed(() => {
@@ -88,53 +86,12 @@ export class KeywordsPatentsComponent {
this.resetPage();
}
setSort(column: SortColumn): void {
if (this.sortColumn() === column) {
this.sortDirection.set(this.sortDirection() === 'asc' ? 'desc' : 'asc');
} else {
this.sortColumn.set(column);
this.sortDirection.set(column === 'year' ? 'desc' : 'asc');
}
setSortMode(sortMode: SortMode): void {
this.sortMode.set(sortMode);
this.selectedMatch.set(null);
this.resetPage();
}
isAssigneeLikelyPerson(assignee: string, patent: PatentEntry): boolean {
if (KeywordsPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) {
return false;
}
const normalizedAssignee = this.normalizeNameForComparison(
assignee.replace(KeywordsPatentsComponent.PERSON_SUFFIX_PATTERN, ''),
);
const matchesInventor = (patent.inventors ?? []).some(
(inventor) =>
this.normalizeNameForComparison(inventor) === normalizedAssignee,
);
if (matchesInventor) {
return true;
}
return KeywordsPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee);
}
private static readonly ORG_SUFFIX_PATTERN =
/\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i;
private static readonly PERSON_SUFFIX_PATTERN =
/\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i;
private normalizeNameForComparison(name: string): string {
return name
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/[.,]/g, '')
.toUpperCase()
.split(/\s+/)
.filter(Boolean)
.sort()
.join(' ');
}
onPatentPageChange(_event: PageEvent): void {
this.selectedMatch.set(null);
}
@@ -167,6 +124,14 @@ export class KeywordsPatentsComponent {
.length;
}
getInventorsLabel(patent: PatentEntry): string {
return patent.inventors?.length ? patent.inventors.join(', ') : '-';
}
getAssigneesLabel(patent: PatentEntry): string {
return patent.assignees?.length ? patent.assignees.join(', ') : '-';
}
formatDate(date: string | null | undefined): string {
return formatPatentDate(date);
}
@@ -198,29 +163,16 @@ export class KeywordsPatentsComponent {
}
private sortMatches(items: KeywordPatentMatch[]): KeywordPatentMatch[] {
const column = this.sortColumn();
const direction = this.sortDirection() === 'asc' ? 1 : -1;
const mode = this.sortMode();
return [...items].sort((a, b) => {
switch (column) {
case 'year': {
const yearA =
a.patent.publication_date ??
String(a.patent.publication_year ?? '');
const yearB =
b.patent.publication_date ??
String(b.patent.publication_year ?? '');
return direction * yearA.localeCompare(yearB);
}
case 'source':
return direction * a.patent.source.localeCompare(b.patent.source);
default:
return (
direction *
(a.patent.title ?? '').localeCompare(b.patent.title ?? '', 'de', {
sensitivity: 'base',
})
);
if (mode === 'date') {
return (b.patent.publication_date ?? '').localeCompare(
a.patent.publication_date ?? '',
);
}
return (a.patent.title ?? '').localeCompare(b.patent.title ?? '', 'de', {
sensitivity: 'base',
});
});
}
}
@@ -4,9 +4,24 @@
<p>Übersicht der durchgeführten Projekte.</p>
</div>
@if (resultTabPanel) {
<app-link-tab-nav-bar [links]="_links()" [tabPanel]="resultTabPanel" />
}
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
@for (route of childRoutes; track route.path) {
<a
matTabLink
[routerLink]="[route.path]"
[queryParams]="{
authorId: null,
institutionId: null,
agency: null,
}"
queryParamsHandling="merge"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive">
{{ route.label }}
</a>
}
</nav>
<mat-tab-nav-panel #resultTabPanel>
<router-outlet />
@@ -6,13 +6,16 @@ import { MatTabsModule } from '@angular/material/tabs';
import { OnInit, computed } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import {
LinkTabNavBarComponent,
LinkTabNavBarItem,
} from '../../../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
@Component({
selector: 'app-projects-results',
imports: [MatCardModule, MatTabsModule, RouterOutlet, LinkTabNavBarComponent],
imports: [
MatCardModule,
MatTabsModule,
RouterLink,
RouterLinkActive,
RouterOutlet,
],
templateUrl: './projects-results.component.html',
styleUrl: './projects-results.component.scss',
})
@@ -29,30 +32,18 @@ export class KeywordsToProjectsResultsComponent {
() => this.queryParamMap().get('fuzzy') === 'true',
);
_links = computed<LinkTabNavBarItem[]>(() => {
const links: LinkTabNavBarItem[] = [
{
label: 'DFG-Projekte',
path: 'dfg',
queryParams: { authorId: null, institutionId: null, agency: null },
queryParamsHandling: 'merge',
disabled: false,
},
{
label: 'EU-Projekte',
path: 'eu',
queryParams: { authorId: null, institutionId: null, agency: null },
queryParamsHandling: 'merge',
disabled: false,
},
{
label: 'BUND-Projekte',
path: 'bund',
queryParams: { authorId: null, institutionId: null, agency: null },
queryParamsHandling: 'merge',
disabled: false,
},
];
return links;
});
readonly childRoutes = [
{
path: 'dfg',
label: 'DFG-Projekte',
},
{
path: 'eu',
label: 'EU-Projekte',
},
{
path: 'bund',
label: 'BUND-Projekte',
},
];
}
@@ -33,75 +33,22 @@
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="sort"></mat-icon>
<mat-select
[value]="sortColumn"
(selectionChange)="setSort($event.value)">
[value]="sortMode"
(selectionChange)="setSortMode($event.value)">
<mat-select-trigger>Sortieren nach</mat-select-trigger>
<mat-option value="name">Förderer</mat-option>
<mat-option value="publications">Publikationen</mat-option>
<mat-option value="first">Erstautor</mat-option>
<mat-option value="middle">Mitautor</mat-option>
<mat-option value="last">Letztautor</mat-option>
<mat-option value="name">Name</mat-option>
<mat-option value="top">Top Förderer</mat-option>
</mat-select>
</mat-form-field>
</div>
<table>
<thead>
<tr>
<th
class="sortable"
[class.sort-active]="sortColumn === 'name'"
(click)="setSort('name')">
Förderer
@if (sortColumn === 'name') {
<mat-icon class="sort-icon">{{
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
}}</mat-icon>
}
</th>
<th
class="text-center sortable"
[class.sort-active]="sortColumn === 'publications'"
(click)="setSort('publications')">
Publikationen
@if (sortColumn === 'publications') {
<mat-icon class="sort-icon">{{
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
}}</mat-icon>
}
</th>
<th
class="text-center sortable"
[class.sort-active]="sortColumn === 'first'"
(click)="setSort('first')">
Erstautor
@if (sortColumn === 'first') {
<mat-icon class="sort-icon">{{
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
}}</mat-icon>
}
</th>
<th
class="text-center sortable"
[class.sort-active]="sortColumn === 'middle'"
(click)="setSort('middle')">
Mitautor
@if (sortColumn === 'middle') {
<mat-icon class="sort-icon">{{
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
}}</mat-icon>
}
</th>
<th
class="text-center sortable"
[class.sort-active]="sortColumn === 'last'"
(click)="setSort('last')">
Letztautor
@if (sortColumn === 'last') {
<mat-icon class="sort-icon">{{
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
}}</mat-icon>
}
</th>
<th>Förderer</th>
<th class="text-center">Publikationen</th>
<th class="text-center">Erstautor</th>
<th class="text-center">Mitautor</th>
<th class="text-center">Letztautor</th>
</tr>
</thead>
<tbody>
@@ -45,24 +45,9 @@ app-query-param-paginator {
text-align: left;
padding: 12px 16px;
border-bottom: 1px solid var(--sg-border);
font-size: 12px;
font-weight: 700;
font-size: 13px;
font-weight: 600;
color: var(--sg-text-muted);
&.sortable {
display: table-cell;
cursor: pointer;
-webkit-user-select: none;
user-select: none;
}
.sort-icon {
vertical-align: middle;
margin-left: 2px;
width: 14px;
height: 14px;
font-size: 14px;
}
}
tr {
@@ -101,11 +86,8 @@ app-query-param-paginator {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 26px;
padding: 2px 10px;
border-radius: 999px;
border: 1px solid var(--sg-border);
font-size: 0.8rem;
min-width: 20px;
font-size: 13px;
font-weight: 700;
&--first {
@@ -175,6 +157,9 @@ app-query-param-paginator {
}
&.stat-first {
background: var(--sg-success-soft);
border-color: var(--sg-success);
.stat-label,
.stat-value {
color: var(--sg-success);
@@ -182,6 +167,9 @@ app-query-param-paginator {
}
&.stat-middle {
background: var(--sg-warning-soft);
border-color: var(--sg-warning);
.stat-label,
.stat-value {
color: var(--sg-warning);
@@ -189,6 +177,9 @@ app-query-param-paginator {
}
&.stat-last {
background: var(--sg-error-soft);
border-color: var(--sg-error);
.stat-label,
.stat-value {
color: var(--sg-error);
@@ -10,8 +10,7 @@ import { FundingService } from '../../api';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
type SortColumn = 'name' | 'publications' | 'first' | 'middle' | 'last';
type SortDirection = 'asc' | 'desc';
type SortMode = 'name' | 'top';
type AuthorPosition = 'first' | 'middle' | 'last' | 'unknown';
type FundingPublicationDetail = {
@@ -54,8 +53,7 @@ export class PersonFundingComponent implements OnInit {
publicationPageIndex = 0;
publicationPageSize = 10;
activeFilter: 'all' | 'first' | 'middle' | 'last' = 'all';
sortColumn: SortColumn = 'name';
sortDirection: SortDirection = 'asc';
sortMode: SortMode = 'name';
loading = true;
error = false;
@@ -63,8 +61,7 @@ export class PersonFundingComponent implements OnInit {
this.route.parent?.paramMap.subscribe((params) => {
const authorId = params.get('id') ?? '';
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
const sortByFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
const sortDirFromUrl = this.route.snapshot.queryParamMap.get('sortDir');
const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
this.initialSelectedFunderKey =
this.route.snapshot.queryParamMap.get('funder');
this.initialFunderPageIndex = this.parsePageIndexParam(
@@ -82,11 +79,8 @@ export class PersonFundingComponent implements OnInit {
if (this.isValidFilter(filterFromUrl)) {
this.activeFilter = filterFromUrl;
}
if (this.isValidSortColumn(sortByFromUrl)) {
this.sortColumn = sortByFromUrl;
}
if (this.isValidSortDirection(sortDirFromUrl)) {
this.sortDirection = sortDirFromUrl;
if (this.isValidSortMode(sortFromUrl)) {
this.sortMode = sortFromUrl;
}
if (authorId) {
@@ -124,13 +118,8 @@ export class PersonFundingComponent implements OnInit {
this.updateQueryParams();
}
setSort(column: SortColumn): void {
if (this.sortColumn === column) {
this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
} else {
this.sortColumn = column;
this.sortDirection = column === 'name' ? 'asc' : 'desc';
}
setSortMode(sortMode: SortMode): void {
this.sortMode = sortMode;
this.applyFilter();
this.updateQueryParams();
}
@@ -196,8 +185,7 @@ export class PersonFundingComponent implements OnInit {
relativeTo: this.route,
queryParams: {
filter: this.activeFilter,
sortBy: this.sortColumn,
sortDir: this.sortDirection,
sortBy: this.sortMode,
funder: this.selectedFunder
? this.getFunderKey(this.selectedFunder)
: null,
@@ -226,18 +214,8 @@ export class PersonFundingComponent implements OnInit {
);
}
private isValidSortColumn(value: string | null): value is SortColumn {
return (
value === 'name' ||
value === 'publications' ||
value === 'first' ||
value === 'middle' ||
value === 'last'
);
}
private isValidSortDirection(value: string | null): value is SortDirection {
return value === 'asc' || value === 'desc';
private isValidSortMode(value: string | null): value is SortMode {
return value === 'name' || value === 'top';
}
getPublicationCount(funder: any): number {
@@ -316,44 +294,24 @@ export class PersonFundingComponent implements OnInit {
}
private sortFunders(funders: any[]): any[] {
const direction = this.sortDirection === 'asc' ? 1 : -1;
const sortedFunders = [...funders];
return sortedFunders.sort((first, second) => {
if (this.sortColumn !== 'name') {
const valueDifference =
direction *
(this.getSortColumnValue(first) - this.getSortColumnValue(second));
if (valueDifference !== 0) {
return valueDifference;
if (this.sortMode === 'top') {
const publicationCountDifference =
this.getPublicationCount(second) - this.getPublicationCount(first);
if (publicationCountDifference !== 0) {
return publicationCountDifference;
}
}
return (
direction *
this.getSortableFunderName(first).localeCompare(
this.getSortableFunderName(second),
'de',
{ sensitivity: 'base' },
)
return this.getSortableFunderName(first).localeCompare(
this.getSortableFunderName(second),
'de',
{ sensitivity: 'base' },
);
});
}
private getSortColumnValue(funder: any): number {
switch (this.sortColumn) {
case 'publications':
return this.getPublicationCount(funder);
case 'first':
return funder.author_position_count?.first ?? 0;
case 'middle':
return funder.author_position_count?.middle ?? 0;
case 'last':
return funder.author_position_count?.last ?? 0;
default:
return 0;
}
}
private getSortableFunderName(funder: any): string {
return funder.funder_name ?? '';
}
@@ -31,12 +31,11 @@
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="sort"></mat-icon>
<mat-select
[value]="sortColumn"
(selectionChange)="setSort($event.value)">
[value]="sortMode"
(selectionChange)="setSortMode($event.value)">
<mat-select-trigger>Sortieren nach</mat-select-trigger>
<mat-option value="year">Jahr</mat-option>
<mat-option value="date">Datum</mat-option>
<mat-option value="title">Titel</mat-option>
<mat-option value="source">Quelle</mat-option>
</mat-select>
</mat-form-field>
</div>
@@ -45,28 +44,8 @@
<thead>
<tr>
<th>Patent</th>
<th
class="sortable"
[class.sort-active]="sortColumn === 'source'"
(click)="setSort('source')">
Quelle
@if (sortColumn === 'source') {
<mat-icon class="sort-icon">{{
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
}}</mat-icon>
}
</th>
<th
class="sortable"
[class.sort-active]="sortColumn === 'year'"
(click)="setSort('year')">
Jahr
@if (sortColumn === 'year') {
<mat-icon class="sort-icon">{{
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
}}</mat-icon>
}
</th>
<th>Quelle</th>
<th>Jahr</th>
<th>Erfinder</th>
<th>Anmelder</th>
</tr>
@@ -90,85 +69,12 @@
{{ patent.source }}
</span>
</td>
<td>
@if (patent.publication_year) {
<span class="year-badge">{{
patent.publication_year
}}</span>
} @else {
<span>-</span>
}
<td>{{ patent.publication_year ?? '-' }}</td>
<td class="patent-people" [title]="getInventorsLabel(patent)">
{{ getInventorsLabel(patent) }}
</td>
<td class="patent-people">
@if (patent.inventors && patent.inventors.length) {
<div class="person-chips">
@for (
inventor of patent.inventors.slice(0, 2);
track inventor
) {
<span class="person-chip">
<mat-icon>person</mat-icon>
{{ inventor }}
</span>
}
@if (patent.inventors.length > 2) {
<span class="person-chip-row">
<span class="person-chip">
<mat-icon>person</mat-icon>
{{ patent.inventors[2] }}
</span>
@if (patent.inventors.length > 3) {
<span class="person-chip person-chip--more"
>+{{ patent.inventors.length - 3 }}</span
>
}
</span>
}
</div>
} @else {
<span>-</span>
}
</td>
<td class="patent-people">
@if (patent.assignees && patent.assignees.length) {
<div class="person-chips">
@for (
assignee of patent.assignees.slice(0, 2);
track assignee
) {
<span class="person-chip">
<mat-icon>{{
isAssigneeLikelyPerson(assignee, patent)
? 'person'
: 'apartment'
}}</mat-icon>
{{ assignee }}
</span>
}
@if (patent.assignees.length > 2) {
<span class="person-chip-row">
<span class="person-chip">
<mat-icon>{{
isAssigneeLikelyPerson(
patent.assignees[2],
patent
)
? 'person'
: 'apartment'
}}</mat-icon>
{{ patent.assignees[2] }}
</span>
@if (patent.assignees.length > 3) {
<span class="person-chip person-chip--more"
>+{{ patent.assignees.length - 3 }}</span
>
}
</span>
}
</div>
} @else {
<span>-</span>
}
<td class="patent-people" [title]="getAssigneesLabel(patent)">
{{ getAssigneesLabel(patent) }}
</td>
</tr>
}
@@ -50,24 +50,9 @@ app-query-param-paginator {
text-align: left;
padding: 12px 16px;
border-bottom: 1px solid var(--sg-border);
font-size: 12px;
font-weight: 700;
font-size: 13px;
font-weight: 600;
color: var(--sg-text-muted);
&.sortable {
display: table-cell;
cursor: pointer;
-webkit-user-select: none;
user-select: none;
}
.sort-icon {
vertical-align: middle;
margin-left: 2px;
width: 14px;
height: 14px;
font-size: 14px;
}
}
tr {
@@ -95,75 +80,22 @@ app-query-param-paginator {
.patent-title {
color: var(--sg-text);
font-weight: 600;
max-width: 320px;
white-space: normal;
word-break: break-word;
max-width: 400px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.patent-people {
max-width: 260px;
max-width: 220px;
color: var(--sg-text-muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
.year-badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 26px;
padding: 2px 10px;
border-radius: 999px;
border: 1px solid var(--sg-border);
color: var(--sg-text);
font-size: 0.8rem;
font-weight: 600;
}
.person-chips {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
}
.person-chip-row {
display: flex;
flex-direction: row;
align-items: center;
flex-wrap: wrap;
gap: 4px;
}
.person-chip {
display: inline-flex;
align-items: center;
gap: 4px;
max-width: 100%;
padding: 2px 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-surface-soft);
color: var(--sg-text);
font-size: 0.75rem;
line-height: 1.4;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
mat-icon {
flex-shrink: 0;
width: 14px;
height: 14px;
font-size: 14px;
color: var(--sg-text-soft);
}
&--more {
color: var(--sg-text-muted);
font-weight: 600;
}
}
.match-badges {
display: flex;
flex-wrap: wrap;
@@ -16,8 +16,7 @@ import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { PageEvent } from '@angular/material/paginator';
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
type SortColumn = 'title' | 'year' | 'source';
type SortDirection = 'asc' | 'desc';
type SortMode = 'date' | 'title';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
@Component({
@@ -47,16 +46,14 @@ export class PersonPatentsComponent {
error = false;
activeFilter: SourceFilter = 'all';
sortColumn: SortColumn = 'year';
sortDirection: SortDirection = 'desc';
sortMode: SortMode = 'date';
pageIndex = 0;
pageSize = 10;
constructor() {
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
const sortByFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
const sortDirFromUrl = this.route.snapshot.queryParamMap.get('sortDir');
const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
this.pageIndex = this.parsePageIndexParam(
this.route.snapshot.queryParamMap.get('page'),
);
@@ -67,11 +64,8 @@ export class PersonPatentsComponent {
if (this.isValidFilter(filterFromUrl)) {
this.activeFilter = filterFromUrl;
}
if (this.isValidSortColumn(sortByFromUrl)) {
this.sortColumn = sortByFromUrl;
}
if (this.isValidSortDirection(sortDirFromUrl)) {
this.sortDirection = sortDirFromUrl;
if (this.isValidSortMode(sortFromUrl)) {
this.sortMode = sortFromUrl;
}
this.route.parent?.data
@@ -119,13 +113,8 @@ export class PersonPatentsComponent {
this.pageSize = event.pageSize;
}
setSort(column: SortColumn): void {
if (this.sortColumn === column) {
this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
} else {
this.sortColumn = column;
this.sortDirection = column === 'year' ? 'desc' : 'asc';
}
setSortMode(sortMode: SortMode): void {
this.sortMode = sortMode;
this.applyFilter();
this.updateQueryParams();
}
@@ -151,24 +140,15 @@ export class PersonPatentsComponent {
}
private sortPatents(patents: PatentEntry[]): PatentEntry[] {
const direction = this.sortDirection === 'asc' ? 1 : -1;
return [...patents].sort((a, b) => {
switch (this.sortColumn) {
case 'year': {
const yearA = a.publication_date ?? String(a.publication_year ?? '');
const yearB = b.publication_date ?? String(b.publication_year ?? '');
return direction * yearA.localeCompare(yearB);
}
case 'source':
return direction * a.source.localeCompare(b.source);
default:
return (
direction *
(a.title ?? '').localeCompare(b.title ?? '', 'de', {
sensitivity: 'base',
})
);
if (this.sortMode === 'date') {
return (b.publication_date ?? '').localeCompare(
a.publication_date ?? '',
);
}
return (a.title ?? '').localeCompare(b.title ?? '', 'de', {
sensitivity: 'base',
});
});
}
@@ -177,8 +157,7 @@ export class PersonPatentsComponent {
relativeTo: this.route,
queryParams: {
filter: this.activeFilter,
sortBy: this.sortColumn,
sortDir: this.sortDirection,
sortBy: this.sortMode,
page: this.pageIndex,
size: this.pageSize,
},
@@ -201,12 +180,8 @@ export class PersonPatentsComponent {
return value === 'all' || value === 'EPO' || value === 'USPTO';
}
private isValidSortColumn(value: string | null): value is SortColumn {
return value === 'title' || value === 'year' || value === 'source';
}
private isValidSortDirection(value: string | null): value is SortDirection {
return value === 'asc' || value === 'desc';
private isValidSortMode(value: string | null): value is SortMode {
return value === 'date' || value === 'title';
}
getPagedPatents(): PatentEntry[] {
@@ -214,40 +189,12 @@ export class PersonPatentsComponent {
return this.filteredPatents.slice(start, start + this.pageSize);
}
private static readonly ORG_SUFFIX_PATTERN =
/\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i;
private static readonly PERSON_SUFFIX_PATTERN =
/\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i;
private normalizeNameForComparison(name: string): string {
return name
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/[.,]/g, '')
.toUpperCase()
.split(/\s+/)
.filter(Boolean)
.sort()
.join(' ');
getInventorsLabel(patent: PatentEntry): string {
return patent.inventors?.length ? patent.inventors.join(', ') : '-';
}
isAssigneeLikelyPerson(assignee: string, patent: PatentEntry): boolean {
if (PersonPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) {
return false;
}
const normalizedAssignee = this.normalizeNameForComparison(
assignee.replace(PersonPatentsComponent.PERSON_SUFFIX_PATTERN, ''),
);
const matchesInventor = (patent.inventors ?? []).some(
(inventor) =>
this.normalizeNameForComparison(inventor) === normalizedAssignee,
);
if (matchesInventor) {
return true;
}
return PersonPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee);
getAssigneesLabel(patent: PatentEntry): string {
return patent.assignees?.length ? patent.assignees.join(', ') : '-';
}
formatDate(date: string | null | undefined): string {
@@ -1,7 +1,22 @@
<div class="person-projects">
@if (resultTabPanel) {
<app-link-tab-nav-bar [links]="_links()" [tabPanel]="resultTabPanel" />
}
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
@for (route of childRoutes; track route.path) {
<a
matTabLink
[routerLink]="[route.path]"
[queryParams]="{
authorId: null,
institutionId: null,
agency: null,
}"
queryParamsHandling="merge"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive">
{{ route.label }}
</a>
}
</nav>
<mat-tab-nav-panel #resultTabPanel>
<router-outlet />
@@ -1,33 +1,31 @@
import { Component, computed } from '@angular/core';
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatTabsModule } from '@angular/material/tabs';
import {
LinkTabNavBarComponent,
LinkTabNavBarItem,
} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
@Component({
selector: 'app-person-projects',
standalone: true,
imports: [MatCardModule, MatTabsModule, RouterOutlet, LinkTabNavBarComponent],
imports: [
MatCardModule,
MatTabsModule,
RouterOutlet,
RouterLink,
RouterLinkActive,
],
templateUrl: './person-projects.component.html',
styleUrl: './person-projects.component.scss',
})
export class PersonProjectsComponent {
_links = computed<LinkTabNavBarItem[]>(() => {
const links: LinkTabNavBarItem[] = [
{
label: 'DFG-Projekte',
path: 'dfg',
disabled: false,
},
{
label: 'EU-Projekte',
path: 'eu',
disabled: false,
},
];
return links;
});
readonly childRoutes = [
{
path: 'dfg',
label: 'DFG-Projekte',
},
{
path: 'eu',
label: 'EU-Projekte',
},
];
}
@@ -132,12 +132,20 @@
[loading]="isTopicsLoading()"
(tagClick)="onInterestingTagClick($event)"></app-person-interesting>
</section>
@if (this.links()) {
<app-link-tab-nav-bar
#navBar
[links]="links()"
[tabPanel]="tabPanel"></app-link-tab-nav-bar>
}
<nav class="person-tabs sg-tab-nav" mat-tab-nav-bar [tabPanel]="tabPanel">
@for (link of links(); track link.path) {
<a
mat-tab-link
[routerLink]="link.path"
[queryParams]="link.queryParams"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive"
[disabled]="link.disabled">
{{ link.label }}
</a>
}
</nav>
} @else {
<app-loading
text="Person wird geladen..."
@@ -6,7 +6,6 @@ import {
signal,
DestroyRef,
input,
viewChild,
} from '@angular/core';
import {
toSignal,
@@ -34,20 +33,14 @@ import { PersonDataResolved } from '../../resolvers/person.resolver';
import { BookmarkService } from '../../shared/services/bookmark.service';
import { collaborationGraphQueryParamKeys } from '../../resolvers/collaboration-graph.resolver';
import { workQueryParamKeys } from '../../resolvers/work-page.resolver';
import {
LinkTabNavBarComponent,
LinkTabNavBarItem,
} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
import {
COMPANY_CONNECTION_ICON,
FUNDING_ICON,
NETWORK_ICON,
NEWS_ICON,
OVERVIEW_ICON,
PATENT_ICON,
PROJECT_ICON,
PUBLICATION_ICON,
} from '../../shared/ui/icons';
type PersonLink = {
label: string;
description?: string;
path: string;
queryParams?: Record<string, any>;
disabled: boolean;
};
@Component({
selector: 'app-person',
@@ -62,7 +55,6 @@ import {
LoadingComponent,
CountryFlagComponent,
CareerStageChipComponent,
LinkTabNavBarComponent,
],
templateUrl: './person.component.html',
styleUrl: './person.component.scss',
@@ -77,11 +69,6 @@ export class PersonComponent {
canFetchGdprRelevantData = input.required<boolean>();
protected readonly navBar = viewChild<LinkTabNavBarComponent>('navBar');
protected readonly activeLink = computed(
() => this.navBar()?.activeLink() ?? null,
);
constructor() {
this.bookmarkService
.load()
@@ -249,12 +236,11 @@ export class PersonComponent {
{ initialValue: [] },
);
readonly links = computed<LinkTabNavBarItem[]>(() => {
readonly links = computed<PersonLink[]>(() => {
const links = [
{
label: 'Übersicht',
description: 'Übersicht über die Person',
icon: OVERVIEW_ICON,
path: 'overview',
disabled: false,
},
@@ -263,7 +249,6 @@ export class PersonComponent {
{
label: 'Projekte',
description: 'Übersicht der durchgeführten Projekte der Person',
icon: PROJECT_ICON,
path: 'projects',
queryParams: {
page: 0,
@@ -279,13 +264,12 @@ export class PersonComponent {
{
label: 'Publikationen',
description: 'Übersicht der Publikationen der Person',
icon: PUBLICATION_ICON,
path: 'publications',
disabled: false,
},
{
label: 'Netzwerk',
description: 'Kooperationsnetzwerk der Person',
icon: NETWORK_ICON,
path: 'network',
disabled: false,
queryParams: {
@@ -300,7 +284,6 @@ export class PersonComponent {
{
label: 'Unternehmen',
description: 'Unternehmen, mit denen die Person verbunden ist',
icon: COMPANY_CONNECTION_ICON,
path: 'company-connections',
disabled: false,
},
@@ -309,21 +292,18 @@ export class PersonComponent {
{
label: 'Förderungen',
description: 'Übersicht der Förderungen der Person',
icon: FUNDING_ICON,
path: 'funding',
disabled: false,
},
{
label: 'Nachrichten',
description: 'Nachrichten über die Person',
icon: NEWS_ICON,
path: 'news',
disabled: false,
},
{
label: 'Patente',
description: 'Patente der Person',
icon: PATENT_ICON,
path: 'patents',
disabled: false,
},
@@ -331,25 +311,25 @@ export class PersonComponent {
return links;
});
// readonly activeLink = computed<LinkTabNavBarItem | null>(() => {
// const currentUrl = this.currentUrl();
// if (!currentUrl) {
// return null;
// }
readonly activeLink = computed<PersonLink | null>(() => {
const currentUrl = this.currentUrl();
if (!currentUrl) {
return null;
}
// for (const link of this.links()) {
// const linkUrl = this.router
// .createUrlTree([link.path], {
// relativeTo: this.activatedRoute,
// })
// .toString();
for (const link of this.links()) {
const linkUrl = this.router
.createUrlTree([link.path], {
relativeTo: this.activatedRoute,
})
.toString();
// if (linkUrl.startsWith(currentUrl) || currentUrl.startsWith(linkUrl)) {
// return link;
// }
// }
// return null;
// });
if (linkUrl.startsWith(currentUrl) || currentUrl.startsWith(linkUrl)) {
return link;
}
}
return null;
});
onInterestingTagClick(selection: {
id: string;
@@ -31,8 +31,21 @@
</div>
<mat-divider />
<app-link-tab-nav-bar [links]="links" [tabPanel]="tabPanel" />
<mat-tab-nav-panel #tabPanel>
<nav mat-tab-nav-bar [tabPanel]="tabPanel">
@for (link of links; track link.path) {
<a
mat-tab-link
[routerLink]="link.path"
[queryParams]="link.queryParams"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive"
[disabled]="link.disabled">
{{ link.label }}
</a>
}
</nav>
<div class="outlet-container">
<router-outlet />
</div>
@@ -6,11 +6,6 @@ import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { DecimalPipe } from '@angular/common';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
import { PUBLICATION_ICON } from '../../shared/ui/icons';
import {
LinkTabNavBarComponent,
LinkTabNavBarItem,
} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
@Component({
host: {
@@ -23,7 +18,6 @@ import {
MatDividerModule,
MatIconModule,
DecimalPipe,
LinkTabNavBarComponent,
],
templateUrl: './topic.component.html',
styleUrl: './topic.component.scss',
@@ -31,10 +25,9 @@ import {
export class TopicComponent {
topic = input.required<Topic>();
links: LinkTabNavBarItem[] = [
links = [
{
label: 'Publikationen',
icon: PUBLICATION_ICON,
path: 'publications',
disabled: false,
queryParams: {
@@ -15,11 +15,6 @@ export interface TrendStrategyConfig {
export type TrendSeriesWithVisibility = TrendSeries & { visible?: boolean };
export const NEWS_ENTITY_PREFIX = 'news_topic_';
export const CC_NEWS_ENTITY_PREFIX = 'ccnews_topic_';
export const CC_NEWS_COMPOSITE_ID = 'ccnews';
export const CC_NEWS_START_YEAR = 2017;
export const TREND_CONFIGS: Record<string, TrendStrategyConfig> = {
publications: {
showInstitutionSelector: true,
@@ -54,7 +49,7 @@ export const TREND_CONFIGS: Record<string, TrendStrategyConfig> = {
showLocationSelector: false,
showAuthorSelector: false,
yAxisLabel: 'Pressemitteilungen',
chartTitle: 'Nachrichtentrends (UDE vs. CC-News)',
chartTitle: 'Nachrichtentrends',
},
all: {
showInstitutionSelector: false,
@@ -10,8 +10,6 @@ import { NgxEchartsDirective } from 'ngx-echarts';
import { MatIconModule } from '@angular/material/icon';
import { TrendResponse, TrendSeries, TopicYearlyData } from '../../../api';
import { ChartThemeService } from '../../../shared/services/chart-theme.service';
import { CC_NEWS_START_YEAR } from '../models/trend.models';
import { isCcNewsSeries } from '../utils/trend.utils';
@Component({
selector: 'app-uni-trend-chart',
@@ -113,9 +111,8 @@ export class UniTrendChartComponent {
return;
}
const yrTopicData = entity.topic_data[selectedTopic] || [];
const isCcNews = isCcNewsSeries(entity.entity_id);
const lineData = years.map((year) => {
if (isCcNews && year < CC_NEWS_START_YEAR) return null;
const yrData = yrTopicData.find((y) => y.year === year);
if (!yrData) return 0;
if (currentMode === 'cumulative') {
@@ -129,14 +126,13 @@ export class UniTrendChartComponent {
type: 'line',
xAxisIndex: 0,
yAxisIndex: 0,
areaStyle: { opacity: isCcNews ? 0.3 : 0.12 },
areaStyle: {
opacity: 0.12,
},
data: lineData,
smooth: true,
connectNulls: false,
showSymbol: !isCcNews,
z: isCcNews ? 1 : 2,
lineStyle: {
width: isCcNews ? 1 : 2.5,
width: 2.5,
color: color,
},
itemStyle: {
@@ -144,14 +140,10 @@ export class UniTrendChartComponent {
},
emphasis: {
focus: 'series',
lineStyle: { width: isCcNews ? 2 : 3.5 },
lineStyle: { width: 3.5 },
},
});
if (isCcNews) {
return;
}
const bars = years.map((year) => {
const yrData = yrTopicData.find((y) => y.year === year);
const val = yrData ? yrData.raw : 0;
@@ -36,7 +36,7 @@
[matTooltip]="
!isUde()
? 'News-Trends sind nur für die Universität Duisburg-Essen verfügbar'
: 'Zeigt Pressemitteilungstrends der UDE im Vergleich zur Web-Berichterstattung (CC-News). Der CC-News-Vergleich erfordert deaktivierte Fuzzy-Suche.'
: 'Zeigt Pressemitteilungstrends der UDE'
"
(click)="setSearchType('news')">
<mat-icon>campaign</mat-icon> News
@@ -184,27 +184,28 @@
<p>Daten werden geladen...</p>
</div>
}
@if (selectedSearchType() === 'news' && !hasCcNewsSeries()) {
<div class="cc-news-hint">
<mat-icon>info_outline</mat-icon>
<span>
Der CC-News-Vergleich (hinterlegte Fläche, ab 2017) ist aktuell nur bei
deaktivierter Fuzzy-Suche verfügbar, da für Web-Nachrichten kein
Themen-Mapping existiert.
</span>
</div>
}
@if (selectedTrendTopics().length > 0) {
<div class="chart-topic-tabs">
@for (topic of selectedTrendTopics(); track $index) {
<app-topic-chip
[label]="getMappedTopic(topic)"
[active]="activeChartTopic() === topic"
[color]="getTopicColor(topic)"
[disabled]="isTopicEmpty(topic)"
[matTooltip]="getMappedTopic(topic)"
(chipClick)="updateActiveChartTopic(topic)">
</app-topic-chip>
@if (selectedSearchType() === 'news') {
<app-topic-chip
[label]="getMappedTopic(topic)"
[active]="isVisible('news_topic_' + topic)"
[color]="getTopicColor(topic)"
[disabled]="false"
[matTooltip]="getMappedTopic(topic)"
(chipClick)="toggleVisibility('news_topic_' + topic)">
</app-topic-chip>
} @else {
<app-topic-chip
[label]="getMappedTopic(topic)"
[active]="activeChartTopic() === topic"
[color]="getTopicColor(topic)"
[disabled]="isTopicEmpty(topic)"
[matTooltip]="getMappedTopic(topic)"
(chipClick)="updateActiveChartTopic(topic)">
</app-topic-chip>
}
}
</div>
}
@@ -164,26 +164,6 @@
border-bottom: 1px solid var(--sg-border);
}
.cc-news-hint {
display: flex;
align-items: flex-start;
gap: 0.5rem;
padding: 0.75rem 1.25rem;
background: var(--sg-surface-muted);
border-bottom: 1px solid var(--sg-border);
color: var(--sg-text-muted);
font-size: 0.85rem;
line-height: 1.4;
mat-icon {
flex: none;
font-size: 1.1rem;
width: 1.1rem;
height: 1.1rem;
color: var(--sg-primary);
}
}
.loader-overlay {
position: absolute;
top: 0;
@@ -69,19 +69,12 @@ import {
} from '../../../shared/ui/topic-treemap/topic-treemap.models';
import { TopicsService } from '../../../api/api/topics.service';
import {
CC_NEWS_COMPOSITE_ID,
CC_NEWS_ENTITY_PREFIX,
CompareItem,
NEWS_ENTITY_PREFIX,
TREND_CONFIGS,
} from '../models/trend.models';
import { CompareItem, TREND_CONFIGS } from '../models/trend.models';
import {
cleanEntityId,
isTopicEmptyForSeries,
findFirstNonEmptyTopic,
buildEntityColorIndex,
newsSourceColor,
} from '../utils/trend.utils';
import { TrendDataService } from '../services/trend-data.service';
@@ -333,37 +326,28 @@ export class UniTrendParentComponent implements OnInit {
readonly boundGetTopicColor = this.getTopicColor.bind(this);
readonly newsSelectedTopicsPieData = computed(() => {
const data = this.rawTrendResponse();
const data = this.trendResponse();
if (!data || !data.series || this.selectedSearchType() !== 'news') {
return null;
}
const startYr = this.startYear();
const endYr = this.endYear();
return data.series
.filter((s) => s.entity_id.startsWith(NEWS_ENTITY_PREFIX))
.map((s) => {
const topicName = s.entity_name;
const yearlyItems =
s.topic_data[topicName] || Object.values(s.topic_data)[0] || [];
const totalRaw = yearlyItems
.filter((y) => y.year >= startYr && y.year <= endYr)
.reduce((sum, item) => sum + (item.raw || 0), 0);
return data.series.map((s) => {
const topicName = s.entity_name;
const yearlyItems =
s.topic_data[topicName] || Object.values(s.topic_data)[0] || [];
const totalRaw = yearlyItems
.filter((y) => y.year >= startYr && y.year <= endYr)
.reduce((sum, item) => sum + (item.raw || 0), 0);
return {
name: topicName,
value: totalRaw,
};
});
return {
name: topicName,
value: totalRaw,
};
});
});
readonly hasCcNewsSeries = computed(
() =>
this.rawTrendResponse()?.series?.some((s) =>
s.entity_id.startsWith(CC_NEWS_ENTITY_PREFIX),
) ?? false,
);
readonly activeTreemapData = computed<TopicTreemapData | null>(() => {
const data = this.trendResponse();
const searchType = this.selectedSearchType();
@@ -546,24 +530,9 @@ export class UniTrendParentComponent implements OnInit {
};
});
seriesTopicName(entityId: string): string {
if (entityId.startsWith(NEWS_ENTITY_PREFIX)) {
return entityId.slice(NEWS_ENTITY_PREFIX.length);
}
if (entityId.startsWith(CC_NEWS_ENTITY_PREFIX)) {
return entityId.slice(CC_NEWS_ENTITY_PREFIX.length);
}
return entityId;
}
isTopicEmpty(topic: string): boolean {
const allSeries = this.rawTrendResponse()?.series || [];
if (allSeries.length === 0) return true;
const series =
this.selectedSearchType() === 'news'
? allSeries.filter((s) => this.seriesTopicName(s.entity_id) === topic)
: allSeries;
if (series.length === 0) return true;
const series = this.rawTrendResponse()?.series || [];
if (!series || series.length === 0) return true;
const mapped = this.getMappedTopic(topic);
const startYr = this.startYear();
@@ -624,7 +593,6 @@ export class UniTrendParentComponent implements OnInit {
patents: '#f59e0b',
projects: '#10b981',
news: '#ec4899',
[CC_NEWS_COMPOSITE_ID]: '#06b6d4',
};
const cleanKey = entityId.toLowerCase().trim();
if (categoryColors[cleanKey]) {
@@ -632,7 +600,10 @@ export class UniTrendParentComponent implements OnInit {
}
}
if (this.selectedSearchType() === 'news') {
return newsSourceColor(entityId);
const topicName = entityId.startsWith('news_topic_')
? entityId.slice('news_topic_'.length)
: entityId;
return this.getTopicColor(topicName);
}
const colorFn = buildEntityColorIndex(
this.primaryInstitution(),
@@ -768,21 +739,7 @@ export class UniTrendParentComponent implements OnInit {
};
};
if (type === 'news') {
const active = this.activeChartTopic() || topics[0] || '';
const wanted = new Set([
NEWS_ENTITY_PREFIX + active,
CC_NEWS_ENTITY_PREFIX + active,
]);
return {
...raw,
series: raw.series
.filter((s) => wanted.has(s.entity_id))
.map((s) => ({ ...normalizeTopicData(s), visible: true })),
};
}
if (type === 'all' || type === 'patents') {
if (type === 'news' || type === 'all' || type === 'patents') {
return {
...raw,
series: raw.series.map((s) => ({
@@ -1,9 +1,5 @@
import { TrendSeries, TopicYearlyData } from '../../../api';
import {
CC_NEWS_COMPOSITE_ID,
CC_NEWS_ENTITY_PREFIX,
CompareItem,
} from '../models/trend.models';
import { CompareItem } from '../models/trend.models';
/**
* Extracts short OpenAlex ID from full URL or string, ensuring uppercase ID prefix (e.g. I62318514, A50012345).
@@ -57,36 +53,9 @@ export function findFirstNonEmptyTopic(
return topics[0];
}
const entityColors = [
'#ec4899', // Pink (Primary UDE)
'#3b82f6', // Blue
'#10b981', // Emerald Green
'#f59e0b', // Amber/Yellow
'#8b5cf6', // Purple
'#06b6d4', // Cyan
'#6366f1', // Indigo
'#ef4444', // Red
'#14b8a6', // Teal
'#f97316', // Orange
'#d946ef', // Fuchsia
'#84cc16', // Lime
'#22c55e', // Green
'#a855f7', // Purple/Fuchsia
'#eab308', // Yellow
'#f43f5e', // Rose
];
export function isCcNewsSeries(entityId: string): boolean {
return (
entityId === CC_NEWS_COMPOSITE_ID ||
entityId.startsWith(CC_NEWS_ENTITY_PREFIX)
);
}
export function newsSourceColor(entityId: string): string {
return isCcNewsSeries(entityId) ? entityColors[1] : entityColors[0];
}
/**
* Builds deterministic entity color lookup map based on entity order and ID.
*/
export function buildEntityColorIndex(
primaryId: string | null,
institutions: CompareItem[],
@@ -94,6 +63,25 @@ export function buildEntityColorIndex(
regions: CompareItem[],
authors: CompareItem[],
): (id: string) => string {
const entityColors = [
'#ec4899', // Pink (Primary UDE)
'#3b82f6', // Blue
'#10b981', // Emerald Green
'#f59e0b', // Amber/Yellow
'#8b5cf6', // Purple
'#06b6d4', // Cyan
'#6366f1', // Indigo
'#ef4444', // Red
'#14b8a6', // Teal
'#f97316', // Orange
'#d946ef', // Fuchsia
'#84cc16', // Lime
'#22c55e', // Green
'#a855f7', // Purple/Fuchsia
'#eab308', // Yellow
'#f43f5e', // Rose
];
const colorMap = new Map<string, string>();
let nextIdx = 0;
@@ -15,22 +15,7 @@ export const bundProjectsFundingResolver: ResolveFn<
'Institution ID is required to resolve BUND projects funding',
);
}
const filtersEnabled = route.data['enableFilters'] ?? false;
if (!filtersEnabled) {
return inject(ProjectsService).getInstitutionBundProjectsFundingOverTime(
institutionId,
[],
[],
undefined,
[],
[],
[],
[],
[],
undefined,
);
}
const fundingStartYears = route.queryParamMap.getAll(
bundProjectQueryParamKeys.funding_start,
);
@@ -15,90 +15,62 @@ export const cordisEuProjectsFundingResolver: ResolveFn<
'Institution ID is required to resolve Cordis EU projects funding',
);
}
const filtersEnabled = route.data['enableFilters'] ?? false;
if (!filtersEnabled) {
return inject(
ProjectsService,
).getInstitutionCordisEuProjectsFundingOverTime(
institutionId,
undefined, // authorId (single) - institution view doesn't use this
[],
[],
[],
[],
undefined,
[],
[],
[],
[],
[],
[],
[],
[],
[],
undefined,
);
} else {
const searchTerm =
route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined;
const fundingStart = route.queryParamMap.getAll(
euProjectQueryParamKeys.funding_start,
);
const fundingEnd = route.queryParamMap.getAll(
euProjectQueryParamKeys.funding_end,
);
const searchTerm =
route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined;
const filteredTopicIds = route.queryParamMap.getAll(
euProjectQueryParamKeys.topicId,
);
const fundingStart = route.queryParamMap.getAll(
euProjectQueryParamKeys.funding_start,
);
const fundingEnd = route.queryParamMap.getAll(
euProjectQueryParamKeys.funding_end,
);
const projectTypes = route.queryParamMap.getAll(
euProjectQueryParamKeys.projectType,
);
const filteredTopicIds = route.queryParamMap.getAll(
euProjectQueryParamKeys.topicId,
);
const organizationIds = route.queryParamMap.getAll(
euProjectQueryParamKeys.institutionId,
);
const projectTypes = route.queryParamMap.getAll(
euProjectQueryParamKeys.projectType,
);
const authorIds = route.queryParamMap
.getAll(euProjectQueryParamKeys.authorId)
.map((id) => id.split('/').pop() || id);
const organizationIds = route.queryParamMap.getAll(
euProjectQueryParamKeys.institutionId,
);
const countries = route.queryParamMap.getAll(
euProjectQueryParamKeys.country,
);
const authorIds = route.queryParamMap
.getAll(euProjectQueryParamKeys.authorId)
.map((id) => id.split('/').pop() || id);
const frameworkProgrammes = route.queryParamMap.getAll(
euProjectQueryParamKeys.frameworkProgramme,
);
const countries = route.queryParamMap.getAll(euProjectQueryParamKeys.country);
const fundingSchemes = route.queryParamMap.getAll(
euProjectQueryParamKeys.fundingScheme,
);
const frameworkProgrammes = route.queryParamMap.getAll(
euProjectQueryParamKeys.frameworkProgramme,
);
const statuses = route.queryParamMap.getAll(euProjectQueryParamKeys.status);
const fundingSchemes = route.queryParamMap.getAll(
euProjectQueryParamKeys.fundingScheme,
);
return inject(
ProjectsService,
).getInstitutionCordisEuProjectsFundingOverTime(
institutionId,
undefined, // authorId (single) - institution view doesn't use this
authorIds,
organizationIds,
[], // organizationNames
projectTypes as any,
searchTerm,
[], // keywords - institution view doesn't use free-text keywords
[], // topicIds (fuzzy) - institution view doesn't use fuzzy topic search
filteredTopicIds,
fundingStart,
fundingEnd,
countries,
frameworkProgrammes,
fundingSchemes,
statuses,
false, // fuzzy
);
}
const statuses = route.queryParamMap.getAll(euProjectQueryParamKeys.status);
return inject(ProjectsService).getInstitutionCordisEuProjectsFundingOverTime(
institutionId,
undefined, // authorId (single) - institution view doesn't use this
authorIds,
organizationIds,
[], // organizationNames
projectTypes as any,
searchTerm,
[], // keywords - institution view doesn't use free-text keywords
[], // topicIds (fuzzy) - institution view doesn't use fuzzy topic search
filteredTopicIds,
fundingStart,
fundingEnd,
countries,
frameworkProgrammes,
fundingSchemes,
statuses,
false, // fuzzy
);
};
@@ -41,10 +41,8 @@ export const dfgProjectsResolver: ResolveFn<DfgProjectPage> = (
const page =
Number(route.queryParamMap.get(dfgProjectQueryParamKeys.page)) || 0;
const size =
Number(route.queryParamMap.get(dfgProjectQueryParamKeys.size)) || 10;
const searchTerm =
route.queryParamMap.get(dfgProjectQueryParamKeys.title) ?? undefined;
const sortBy =
@@ -61,13 +59,12 @@ export const dfgProjectsResolver: ResolveFn<DfgProjectPage> = (
const filteredTopicIds = route.queryParamMap.getAll(
dfgProjectQueryParamKeys.topicId,
);
const institutionIds = route.queryParamMap.getAll(
dfgProjectQueryParamKeys.institutionId,
);
const authorIds = route.queryParamMap.getAll(
dfgProjectQueryParamKeys.authorId,
);
const institutionIds = route.queryParamMap
.getAll(dfgProjectQueryParamKeys.institutionId)
.map((id) => Number(id));
const authorIds = route.queryParamMap
.getAll(dfgProjectQueryParamKeys.authorId)
.map((id) => Number(id));
if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) {
const rawAuthorId = route.parent?.parent?.params['id'];
@@ -111,7 +108,6 @@ export const dfgProjectsResolver: ResolveFn<DfgProjectPage> = (
);
} else if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.INSTITUTION) {
const oaInstitutionId = route.parent?.parent?.params['institutionId'];
console.log(
'Resolving project page for institution',
oaInstitutionId,
@@ -42,7 +42,7 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
const trendDataService = inject(TrendDataService);
const searchType = params.get('search_type') || 'publications';
const fuzzy = params.get('fuzzy') === 'true';
const fuzzy = params.get('fuzzy') !== 'false';
const treemapNode = params.get('treemapNode');
// Primary institution from user token / credential service
@@ -17,21 +17,6 @@ import { topicQueryParamKeys } from '../../../resolvers/topic-page.resolver';
import { SortDirection, TopicSortBy, WorkSortBy } from '../../../api';
import { workQueryParamKeys } from '../../../resolvers/work-page.resolver';
import { MatMenuModule } from '@angular/material/menu';
import {
BOOKMARKS_ICON,
DASHBOARD_ICON,
INSTITUTION_ICON,
JOBS_ICON,
KEYWORDS_ICON,
MANAGE_ACCOUNTS_ICON,
NEWS_ICON,
ORGANIZATIONS_ICON,
PATENT_ICON,
PERSONS_ICON,
PROJECT_ICON,
PUBLICATION_ICON,
TOPIC_ICON,
} from '../icons';
type NavItem = {
label: string;
@@ -86,13 +71,13 @@ export class AppMenuComponent {
const items: NavItem[] = [
{
label: 'Dashboard',
icon: DASHBOARD_ICON,
icon: 'dashboard',
route: '/dashboard',
disabled: false,
},
{
label: 'Personen',
icon: PERSONS_ICON,
icon: 'groups',
route: '/persons',
queryParams: activeInstitutionPersonListQueryParams(
this.credentialService.effectiveInstitutionId(),
@@ -102,19 +87,19 @@ export class AppMenuComponent {
},
{
label: 'Bookmarks',
icon: BOOKMARKS_ICON,
icon: 'bookmarks',
route: '/bookmarks',
disabled: false,
},
{
label: 'News',
icon: NEWS_ICON,
icon: 'newspaper',
route: '/news',
disabled: false,
},
{
label: 'Institutionen',
icon: INSTITUTION_ICON,
icon: 'apartment',
route: '/institutions',
disabled: false,
queryParams: {
@@ -127,7 +112,7 @@ export class AppMenuComponent {
},
{
label: 'Publikationen',
icon: PUBLICATION_ICON,
icon: 'menu_book',
route: '/publications',
disabled: false,
queryParams: {
@@ -140,7 +125,7 @@ export class AppMenuComponent {
},
{
label: 'Themen',
icon: TOPIC_ICON,
icon: 'topic',
route: '/topics',
disabled: false,
queryParams: {
@@ -153,7 +138,7 @@ export class AppMenuComponent {
},
{
label: 'Projekte',
icon: PROJECT_ICON,
icon: 'work',
route: '/projects',
disabled: false,
queryParams: {
@@ -167,13 +152,13 @@ export class AppMenuComponent {
},
{
label: 'Patente',
icon: PATENT_ICON,
icon: 'workspace_premium',
route: '/patents',
disabled: false,
},
{
label: 'Keywords',
icon: KEYWORDS_ICON,
icon: 'join_left',
route: '/keywords',
disabled: false,
queryParams: {
@@ -182,21 +167,21 @@ export class AppMenuComponent {
},
{
label: 'Accounts',
icon: MANAGE_ACCOUNTS_ICON,
icon: 'manage_accounts',
route: '/accounts',
disabled: false,
managerOrAdminOnly: true,
},
{
label: 'Organisationen',
icon: ORGANIZATIONS_ICON,
icon: 'domain',
route: '/organizations',
disabled: false,
superAdminOnly: true,
},
{
label: 'Jobs',
icon: JOBS_ICON,
icon: 'sync',
route: '/jobs',
disabled: false,
superAdminOnly: true,
-18
View File
@@ -1,18 +0,0 @@
export const BOOKMARKS_ICON = "bookmarks" as const;
export const COMPANY_CONNECTION_ICON = 'business' as const;
export const DASHBOARD_ICON = 'dashboard' as const;
export const FUNDING_ICON = 'account_balance' as const;
export const INSTITUTION_ICON = 'school' as const;
export const JOBS_ICON = "sync" as const;
export const KEYWORDS_ICON = 'join_left' as const;
export const MANAGE_ACCOUNTS_ICON = 'manage_accounts' as const;
export const NETWORK_ICON = 'share' as const;
export const NEWS_ICON = 'newspaper' as const;
export const ORGANIZATIONS_ICON = 'domain' as const;
export const OVERVIEW_ICON = 'visibility' as const;
export const PATENT_ICON = 'workspace_premium' as const;
export const PERSONS_ICON = 'groups' as const;
export const PERSON_ICON = 'person' as const;
export const PROJECT_ICON = 'work' as const;
export const PUBLICATION_ICON = 'menu_book' as const;
export const TOPIC_ICON = 'topic' as const;
@@ -1,20 +0,0 @@
<nav mat-tab-nav-bar [tabPanel]="tabPanel()" mat-stretch-tabs="true">
@for (link of links(); track link.path) {
<a
mat-tab-link
[routerLink]="link.path"
[queryParams]="link.queryParams"
[queryParamsHandling]="link.queryParamsHandling"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive"
[disabled]="link.disabled">
<div class="link-tab-nav-bar-item">
@if (link.icon) {
<mat-icon>{{ link.icon }}</mat-icon>
}
<span>{{ link.label }}</span>
</div>
</a>
}
</nav>
@@ -1,5 +0,0 @@
.link-tab-nav-bar-item {
display: flex;
align-items: center;
gap: 0.25rem;
}
@@ -1,51 +0,0 @@
import { Component, computed, inject, input } from '@angular/core';
import { MatTabNavPanel, MatTabsModule } from '@angular/material/tabs';
import {
ActivatedRoute,
isActive,
Router,
RouterModule,
} from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
export type LinkTabNavBarItem = {
label: string;
path: string;
icon?: string;
description?: string;
queryParams?: Record<string, any>;
queryParamsHandling?: 'merge' | 'preserve' | 'replace';
disabled?: boolean;
};
@Component({
selector: 'app-link-tab-nav-bar',
imports: [MatTabsModule, RouterModule, MatIconModule],
templateUrl: './link-tab-nav-bar.component.html',
styleUrl: './link-tab-nav-bar.component.scss',
})
export class LinkTabNavBarComponent {
private readonly router = inject(Router);
private readonly activatedRoute = inject(ActivatedRoute);
links = input.required<LinkTabNavBarItem[]>();
tabPanel = input<MatTabNavPanel>();
activeLink = computed<LinkTabNavBarItem | null>(() => {
for (const link of this.links()) {
const linkUrlTree = this.router.createUrlTree([link.path], {
relativeTo: this.activatedRoute,
});
if (
isActive(linkUrlTree, this.router, {
paths: 'subset',
queryParams: 'ignored',
})()
) {
return link;
}
}
return null;
});
}
+2 -1
View File
@@ -2,11 +2,12 @@
// For more information: https://material.angular.io/guide/theming
@use '@angular/material' as mat;
@use 'm3-theme' as m3;
@import url('https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,200..700,0..1,-50..200');
@include mat.elevation-classes();
@include mat.app-background();
@import url('https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,200..700,0..1,-50..200');
@font-face {
font-display: swap;
font-family: 'Montserrat';