Merge branch 'dev' into feat/ranking
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
Steven Tischer
2026-07-24 09:01:10 +02:00
117 changed files with 9277 additions and 3122 deletions
@@ -2,6 +2,7 @@ from __future__ import annotations
import argparse
import json
import sys
import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from datetime import datetime, timezone
@@ -12,6 +13,15 @@ import requests
from openai import OpenAI
ROOT = Path(__file__).resolve().parent
SERVICE_SOURCE_ROOT = ROOT.parents[1] / "service" / "src" / "main"
if str(SERVICE_SOURCE_ROOT) not in sys.path:
sys.path.insert(0, str(SERVICE_SOURCE_ROOT))
from inse.authors.institution_membership_query import ( # noqa: E402
build_institution_membership_query,
current_affiliation_year_cutoff,
)
PROMPT_FILE = ROOT / "prompt_frascati_hard_ranges_v2.txt"
REPORTS_DIR = ROOT / "run_reports"
@@ -27,11 +37,13 @@ LLM_MODEL = "gemma4-e4b"
PROMPT_VERSION = "frascati_hard_ranges_v2"
UDE_ID = "https://openalex.org/I62318514"
UDE_ROR = "https://ror.org/04mz5ra38"
UDE_NAME = "University of Duisburg-Essen"
AFFILIATION_YEAR_GTE = 2025
AFFILIATION_YEAR_GTE = current_affiliation_year_cutoff()
WORK_YEAR_GTE = 1950
SELECTION_AUTHOR_COHORT = "author-cohort"
SELECTION_INSTITUTION_WORKS = "institution-works"
SELECTION_MODES = (SELECTION_AUTHOR_COHORT, SELECTION_INSTITUTION_WORKS)
AUTHOR_PAGE_SIZE = 1000
AUTHOR_BATCH_SIZE = 1000
WORK_PAGE_SIZE = 2000
@@ -201,6 +213,7 @@ TARGET_TOP_LEVEL_FIELDS = {
"work_id",
"title",
"publication_year",
"publication_type",
"doi",
"authors",
"institutions",
@@ -209,6 +222,7 @@ TARGET_TOP_LEVEL_FIELDS = {
"validation",
"classification_meta",
}
TARGET_OPTIONAL_TOP_LEVEL_FIELDS = {"publication_type"}
TARGET_CLASSIFICATION_FIELDS = {
"primary_category",
"applied_orientation_score",
@@ -398,6 +412,7 @@ def build_work_metadata(
"work_id": full_work_id,
"title": title,
"publication_year": publication_year,
"publication_type": nullable_text(work.get("type")),
"doi": nullable_text(work.get("doi")),
"authors": target_authors(work),
"institutions": target_institutions(work),
@@ -409,12 +424,13 @@ def exact_fields(
value: Any,
expected: set[str],
path: str,
optional: set[str] | None = None,
) -> list[str]:
if not isinstance(value, dict):
return [f"{path}_must_be_object"]
actual = set(value)
errors: list[str] = []
missing = expected - actual
missing = expected - (optional or set()) - actual
unknown = actual - expected
if missing:
errors.append(f"{path}_missing_fields:{','.join(sorted(missing))}")
@@ -456,7 +472,12 @@ def validate_target_document(
short_work_id: str,
document: Any,
) -> list[str]:
errors = exact_fields(document, TARGET_TOP_LEVEL_FIELDS, "document")
errors = exact_fields(
document,
TARGET_TOP_LEVEL_FIELDS,
"document",
optional=TARGET_OPTIONAL_TOP_LEVEL_FIELDS,
)
if not isinstance(document, dict):
return errors
@@ -466,6 +487,12 @@ def validate_target_document(
errors.extend(validate_nullable_string(document.get("title"), "title"))
errors.extend(validate_nullable_string(document.get("doi"), "doi"))
errors.extend(
validate_nullable_string(
document.get("publication_type"),
"publication_type",
)
)
year = document.get("publication_year")
if year is not None and (isinstance(year, bool) or not isinstance(year, int)):
@@ -854,69 +881,20 @@ def validate(result: dict[str, Any]) -> list[str]:
return errors
def ude_affiliation_filter() -> dict[str, Any]:
return {
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{
"bool": {
"should": [
{"term": {"affiliations.institution.id": UDE_ID}},
{"term": {"affiliations.institution.ror": UDE_ROR}},
{
"match_phrase": {
"affiliations.institution.display_name": UDE_NAME
}
},
],
"minimum_should_match": 1,
}
},
{
"range": {
"affiliations.years": {"gte": AFFILIATION_YEAR_GTE}
}
},
]
}
},
}
}
def author_query(group: str, after: list[Any] | None) -> dict[str, Any]:
last_known = {
"nested": {
"path": "last_known_institutions",
"query": {
"match_phrase": {"last_known_institutions.display_name": UDE_NAME}
},
}
}
last_known_exists = {
"nested": {
"path": "last_known_institutions",
"query": {"exists": {"field": "last_known_institutions.display_name"}},
}
}
query = (
{"bool": {"filter": [last_known, ude_affiliation_filter()]}}
if group == "known"
else {
"bool": {
"filter": [ude_affiliation_filter()],
"must_not": [last_known_exists],
}
}
)
def author_query(
after: list[Any] | None,
institution_id: str = UDE_ID,
affiliation_year_gte: int = AFFILIATION_YEAR_GTE,
) -> dict[str, Any]:
body: dict[str, Any] = {
"size": AUTHOR_PAGE_SIZE,
"track_total_hits": True,
"_source": ["id"],
"query": query,
"query": build_institution_membership_query(
institution_id=institution_id,
year_mode="from",
year=affiliation_year_gte,
),
"sort": [{"id": "asc"}],
}
if after is not None:
@@ -924,7 +902,22 @@ def author_query(group: str, after: list[Any] | None) -> dict[str, Any]:
return body
def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]:
def work_query(
author_ids: list[str],
after: list[Any] | None,
work_year_gte: int | None = WORK_YEAR_GTE,
) -> dict[str, Any]:
filters: list[dict[str, Any]] = [
{
"nested": {
"path": "authorships",
"query": {"terms": {"authorships.author.id": author_ids}},
}
}
]
if work_year_gte is not None:
filters.insert(0, {"range": {"publication_year": {"gte": work_year_gte}}})
body: dict[str, Any] = {
"size": WORK_PAGE_SIZE,
"track_total_hits": False,
@@ -964,15 +957,7 @@ def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]
],
"query": {
"bool": {
"filter": [
{"range": {"publication_year": {"gte": WORK_YEAR_GTE}}},
{
"nested": {
"path": "authorships",
"query": {"terms": {"authorships.author.id": author_ids}},
}
},
]
"filter": filters
}
},
"sort": [{"id": "asc"}],
@@ -982,6 +967,36 @@ def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]
return body
def institution_work_query(
institution_id: str,
after: list[Any] | None,
) -> dict[str, Any]:
"""Select all works attributed to an institution, like Publikationsliste."""
body = work_query([], after)
body["query"] = {
"bool": {
"must": [
{
"nested": {
"path": "authorships",
"query": {
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": [institution_id]
}
},
}
},
}
}
]
}
}
return body
def choose_work_hit(
current: dict[str, Any] | None,
candidate: dict[str, Any],
@@ -1016,6 +1031,7 @@ EXPECTED_MAPPING_TYPES = {
"work_id": "keyword",
"title": "text",
"publication_year": "integer",
"publication_type": "keyword",
"doi": "keyword",
"authors": "nested",
"authors.id": "keyword",
@@ -1510,32 +1526,42 @@ def classify(
raise StopPipeline(f"LLM unavailable for {work_id}: {error}")
def collect_authors(es: ES) -> list[str]:
def collect_authors(
es: ES,
institution_id: str = UDE_ID,
affiliation_year_gte: int = AFFILIATION_YEAR_GTE,
) -> list[str]:
ids: set[str] = set()
for group in ("known", "empty"):
after = None
total = None
read = 0
while True:
result = es.search(AUTHORS_INDEX, author_query(group, after))
hits = result.get("hits", {}).get("hits", [])
if total is None:
value = result.get("hits", {}).get("total", 0)
total = int(value.get("value", 0) if isinstance(value, dict) else value)
print(f"Authors {group}: expected {total}")
if not hits:
break
for hit in hits:
author_id = (hit.get("_source") or {}).get("id")
if isinstance(author_id, str):
ids.add(author_id)
read += len(hits)
after = hits[-1].get("sort")
if not isinstance(after, list):
raise StopPipeline("Missing author search_after")
print(f"Authors {group}: {read}/{total}")
after = None
total = None
read = 0
while True:
result = es.search(
AUTHORS_INDEX,
author_query(
after,
institution_id,
affiliation_year_gte,
),
)
hits = result.get("hits", {}).get("hits", [])
if total is None:
value = result.get("hits", {}).get("total", 0)
total = int(value.get("value", 0) if isinstance(value, dict) else value)
print(f"Authors: expected {total}")
if not hits:
break
for hit in hits:
author_id = (hit.get("_source") or {}).get("id")
if isinstance(author_id, str):
ids.add(author_id)
read += len(hits)
after = hits[-1].get("sort")
if not isinstance(after, list):
raise StopPipeline("Missing author search_after")
print(f"Authors: {read}/{total}")
result = sorted(ids)
print(f"Final UDE author count: {len(result)}")
print(f"Final institution author count: {len(result)}")
return result
@@ -1726,6 +1752,10 @@ def run(
limit: int | None,
workers: int,
report: dict[str, Any],
selection_mode: str = SELECTION_AUTHOR_COHORT,
institution_id: str = UDE_ID,
affiliation_year_gte: int = AFFILIATION_YEAR_GTE,
work_year_gte: int | None = WORK_YEAR_GTE,
preflight_only: bool = False,
) -> None:
if not ES_API_KEY.strip():
@@ -1749,17 +1779,32 @@ def run(
api_key=LLM_API_KEY,
timeout=REQUEST_TIMEOUT,
)
authors = collect_authors(es)
count = 0
warm = False
batches = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE
for start in range(0, len(authors), AUTHOR_BATCH_SIZE):
if selection_mode == SELECTION_INSTITUTION_WORKS:
work_batches: list[tuple[str, list[str] | None]] = [
(f"Institution works: {institution_id}", None)
]
else:
authors = collect_authors(
es,
institution_id,
affiliation_year_gte,
)
batch_count = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE
work_batches = [
(
f"Author batch {start // AUTHOR_BATCH_SIZE + 1}/{batch_count}",
authors[start : start + AUTHOR_BATCH_SIZE],
)
for start in range(0, len(authors), AUTHOR_BATCH_SIZE)
]
for batch_label, author_ids in work_batches:
if limit is not None and count >= limit:
break
batch = authors[start : start + AUTHOR_BATCH_SIZE]
print(f"\nAuthor batch {start // AUTHOR_BATCH_SIZE + 1}/{batches}")
print(f"\n{batch_label}")
after = None
page = 0
@@ -1767,7 +1812,12 @@ def run(
if limit is not None and count >= limit:
break
result = es.search(WORKS_INDEX, work_query(batch, after))
query = (
institution_work_query(institution_id, after)
if author_ids is None
else work_query(author_ids, after, work_year_gte)
)
result = es.search(WORKS_INDEX, query)
hits = result.get("hits", {}).get("hits", [])
if not hits:
break
@@ -1843,15 +1893,58 @@ def main() -> None:
parser.add_argument("--limit", type=int)
parser.add_argument("--workers", type=int, default=MAX_WORKERS)
parser.add_argument("--preflight-only", action="store_true")
parser.add_argument(
"--selection-mode",
choices=SELECTION_MODES,
default=SELECTION_AUTHOR_COHORT,
help=(
"author-cohort selects works by current affiliated authors; "
"institution-works selects every work attributed to --institution-id"
),
)
parser.add_argument("--institution-id", default=UDE_ID)
parser.add_argument(
"--affiliation-year-gte", type=int, default=AFFILIATION_YEAR_GTE
)
parser.add_argument("--work-year-gte", type=int, default=WORK_YEAR_GTE)
parser.add_argument(
"--all-work-years",
action="store_true",
help=(
"disable the publication-year filter in author-cohort mode, "
"including works without publication_year"
),
)
args = parser.parse_args()
if args.limit is not None and args.limit < 1:
raise SystemExit("--limit must be at least 1")
if args.workers < 1:
raise SystemExit("--workers must be at least 1")
if args.affiliation_year_gte < 0:
raise SystemExit("--affiliation-year-gte must not be negative")
if args.work_year_gte < 0:
raise SystemExit("--work-year-gte must not be negative")
work_year_gte = None if args.all_work_years else args.work_year_gte
institution_id = args.institution_id.strip()
if not institution_id:
raise SystemExit("--institution-id must not be empty")
if not institution_id.startswith("https://openalex.org/"):
institution_id = f"https://openalex.org/{bare_id(institution_id)}"
report = new_run_report(args.limit, args.workers)
report["parameters"]["preflight_only"] = args.preflight_only
report["parameters"].update(
{
"selection_mode": args.selection_mode,
"institution_id": institution_id,
"affiliation_year_gte": args.affiliation_year_gte,
"work_year_gte": work_year_gte,
"all_work_years": args.all_work_years,
}
)
exit_code = 0
try:
@@ -1859,6 +1952,10 @@ def main() -> None:
args.limit,
args.workers,
report,
selection_mode=args.selection_mode,
institution_id=institution_id,
affiliation_year_gte=args.affiliation_year_gte,
work_year_gte=work_year_gte,
preflight_only=args.preflight_only,
)
report["status"] = "completed"
@@ -0,0 +1,50 @@
{
"run_id": "20260722_021910_049378",
"started_at": "2026-07-22T02:19:10Z",
"finished_at": "2026-07-22T09:26:37Z",
"duration_seconds": 25645.781,
"status": "completed",
"error": null,
"parameters": {
"limit": null,
"workers": 25,
"model": "gemma4-e4b",
"prompt_version": "frascati_hard_ranges_v2",
"target_index": "work-classifications",
"bulk_batch_size": 200,
"state_storage": "memory_only",
"preflight_only": false,
"selection_mode": "institution-works",
"institution_id": "https://openalex.org/I62318514",
"institution_ror": "https://ror.org/04mz5ra38",
"institution_name": "University of Duisburg-Essen",
"affiliation_year_gte": 2025,
"work_year_gte": 1950
},
"classification": {
"llm_completed": 32189,
"valid": 32189,
"invalid": 0,
"categories": {
"applied_research": 10001,
"basic_research": 17089,
"experimental_development": 1813,
"non_research": 3286
},
"validation_errors": {}
},
"indexing": {
"newly_indexed": 32189,
"bulk_requests": 183,
"bulk_documents_submitted": 32589,
"bulk_failures": 0
},
"token_usage": {
"prompt_tokens": 119788565,
"cached_prompt_tokens": 110500800,
"uncached_prompt_tokens": 9287765,
"completion_tokens": 29352270,
"real_total_usage": 38640035
},
"throughput_indexed_per_hour": 4518.5
}
@@ -0,0 +1,51 @@
{
"run_id": "20260723_154918_847690",
"started_at": "2026-07-23T15:49:18Z",
"finished_at": "2026-07-23T19:49:04Z",
"duration_seconds": 14385.39,
"status": "completed",
"error": null,
"parameters": {
"limit": null,
"workers": 25,
"model": "gemma4-e4b",
"prompt_version": "frascati_hard_ranges_v2",
"target_index": "work-classifications",
"bulk_batch_size": 200,
"state_storage": "memory_only",
"preflight_only": false,
"selection_mode": "author-cohort",
"institution_id": "https://openalex.org/I62318514",
"institution_ror": "https://ror.org/04mz5ra38",
"institution_name": "University of Duisburg-Essen",
"affiliation_year_gte": 2024,
"work_year_gte": 1950,
"all_work_years": false
},
"classification": {
"llm_completed": 16272,
"valid": 16272,
"invalid": 0,
"categories": {
"basic_research": 8658,
"applied_research": 4889,
"non_research": 1190,
"experimental_development": 1535
},
"validation_errors": {}
},
"indexing": {
"newly_indexed": 16272,
"bulk_requests": 148,
"bulk_documents_submitted": 16472,
"bulk_failures": 0
},
"token_usage": {
"prompt_tokens": 60051102,
"cached_prompt_tokens": 55752000,
"uncached_prompt_tokens": 4299102,
"completion_tokens": 14983831,
"real_total_usage": 19282933
},
"throughput_indexed_per_hour": 4072.13
}
@@ -0,0 +1,231 @@
from __future__ import annotations
from collections.abc import Iterable
from datetime import datetime, timezone
from typing import Any, Literal
AFFILIATION_LOOKBACK_YEARS = 2
OPENALEX_ID_PREFIX = "https://openalex.org/"
AffiliationYearMode = Literal["all", "in", "from"]
def current_affiliation_year_cutoff(
reference_time: datetime | None = None,
) -> int:
"""Return the inclusive first year used for active membership.
The shared active cohort includes affiliation years greater than or equal
to the current UTC year minus ``AFFILIATION_LOOKBACK_YEARS``.
``reference_time`` exists so callers can make the cutoff deterministic
when needed.
"""
current_time = reference_time or datetime.now(timezone.utc)
return current_time.year - AFFILIATION_LOOKBACK_YEARS
def build_institution_affiliation_query(
institution_id: str,
year_mode: AffiliationYearMode = "all",
year: int | None = None,
) -> dict[str, Any]:
"""Build an affiliation query for an institution and optional year rule.
``all`` accepts an affiliation from any year and requires ``year=None``.
``in`` requires an affiliation in exactly ``year``.
``from`` requires an affiliation in ``year`` or any later year.
Institution IDs are normalized to their full OpenAlex URL.
"""
normalized_institution_id = _normalize_openalex_id(institution_id)
_validate_year_mode(year_mode, year)
affiliation_filters: list[dict[str, Any]] = [
{
"term": {
"affiliations.institution.id": normalized_institution_id
}
}
]
if year_mode == "in":
affiliation_filters.append(
{"term": {"affiliations.years": year}}
)
elif year_mode == "from":
affiliation_filters.append(
{"range": {"affiliations.years": {"gte": year}}}
)
return {
"nested": {
"path": "affiliations",
"query": {"bool": {"filter": affiliation_filters}},
}
}
def build_institution_membership_query(
institution_id: str,
year_mode: AffiliationYearMode = "all",
year: int | None = None,
author_ids: Iterable[str] | None = None,
) -> dict[str, Any]:
"""Build an institution membership query for the selected year mode.
Membership is accepted when one of these conditions matches:
1. The institution is both last known and present in the selected
affiliation period.
2. The institution is last known and no affiliation institution IDs are
available. This fallback is used only for ``all`` and ``from``.
3. The institution is present in the selected affiliation period and no
last-known institution IDs are available.
``in`` deliberately excludes condition 2 because an exact year requires
explicit affiliation evidence for that year. When ``author_ids`` are
supplied, the query is restricted to those authors in the same
Elasticsearch request. Empty ``author_ids`` produce ``match_none``.
Institution and author IDs are normalized to full OpenAlex URLs.
"""
normalized_institution_id = _normalize_openalex_id(institution_id)
affiliation = build_institution_affiliation_query(
normalized_institution_id,
year_mode=year_mode,
year=year,
)
author_filters: list[dict[str, Any]] = []
if author_ids is not None:
normalized_author_ids = list(
dict.fromkeys(
_normalize_openalex_id(author_id)
for author_id in author_ids
if author_id and author_id.strip()
)
)
if not normalized_author_ids:
return {"match_none": {}}
author_filters.append({"terms": {"id": normalized_author_ids}})
matching_last_known_institution = {
"nested": {
"path": "last_known_institutions",
"query": {
"term": {
"last_known_institutions.id": normalized_institution_id
}
},
}
}
any_affiliation_id = {
"nested": {
"path": "affiliations",
"query": {
"exists": {
"field": "affiliations.institution.id"
}
},
}
}
any_last_known_institution_id = {
"nested": {
"path": "last_known_institutions",
"query": {
"exists": {
"field": "last_known_institutions.id"
}
},
}
}
# Confirmed by both last-known and affiliation evidence.
membership_branches: list[dict[str, Any]] = [
{
"bool": {
"filter": [
matching_last_known_institution,
affiliation,
]
}
},
# Affiliation evidence is accepted when last-known data is unavailable.
{
"bool": {
"filter": [affiliation],
"must_not": [any_last_known_institution_id],
}
},
]
if year_mode != "in":
# Last-known is the fallback only when affiliation IDs are unavailable.
membership_branches.insert(
1,
{
"bool": {
"filter": [matching_last_known_institution],
"must_not": [any_affiliation_id],
}
},
)
membership_query = {
"bool": {
"should": membership_branches,
"minimum_should_match": 1,
}
}
if not author_filters:
return membership_query
return {
"bool": {
"filter": [
*author_filters,
membership_query,
],
}
}
def build_active_institution_membership_query(
institution_id: str,
author_ids: Iterable[str] | None = None,
reference_time: datetime | None = None,
) -> dict[str, Any]:
"""Build the shared active-cohort query.
Active membership uses ``from`` with the inclusive cutoff returned by
``current_affiliation_year_cutoff``. It therefore applies the same
membership and fallback rules everywhere that consumes this helper.
"""
return build_institution_membership_query(
institution_id=institution_id,
year_mode="from",
year=current_affiliation_year_cutoff(reference_time),
author_ids=author_ids,
)
def _validate_year_mode(
year_mode: AffiliationYearMode,
year: int | None,
) -> None:
if year_mode not in {"all", "in", "from"}:
raise ValueError(f"Unsupported affiliation year mode: {year_mode}")
if year_mode == "all":
if year is not None:
raise ValueError("year must be omitted when year_mode is 'all'")
return
if isinstance(year, bool) or not isinstance(year, int):
raise ValueError(f"year is required when year_mode is '{year_mode}'")
def _normalize_openalex_id(raw_id: str) -> str:
normalized_id = raw_id.strip()
if normalized_id.startswith(OPENALEX_ID_PREFIX):
return normalized_id
return f"{OPENALEX_ID_PREFIX}{normalized_id}"
+9 -145
View File
@@ -1,11 +1,12 @@
from typing import Dict, List, Optional, Set
from inse.authors.institution_membership_query import (
build_active_institution_membership_query,
)
from inse.authors.v2.model import AuthorPage
from inse.integrations import elasticsearch
from inse.institutions.v2 import service as institution_service
from inse.model import ESIndex
from inse.models.openalex.author import Author
from inse.models.openalex.institution import Institution
async def search_authors(
@@ -117,177 +118,40 @@ async def get_authors_by_ids(author_ids: List[str]) -> AuthorPage:
async def author_currently_belongs_to_institution(
raw_oa_author_id: str,
raw_oa_institution_id: str,
current_years: List[int] = [2025, 2026],
) -> bool:
"""Checks if an author currently belongs to a specific institution based on their affiliations and the provided years.
"""Return whether one author belongs to the institution's active cohort.
Args:
raw_oa_author_id (str): The ID of the author to check.
raw_oa_institution_id (str): The ID of the institution to check.
current_years (List[int], optional): The years to check for affiliation. Defaults to [2025, 2026].
Returns:
bool: True if the author belongs to the institution in any of the specified years, False otherwise.
bool: True if the author matches the shared active-membership query.
"""
if not current_years:
return False
matching_author_ids = await _authors_belong_to_institution(
matching_author_ids = await authors_currently_belong_to_institution(
[raw_oa_author_id],
raw_oa_institution_id,
affiliation_year_filter={"terms": {"affiliations.years": current_years}},
)
return bool(matching_author_ids)
def _prefix_openalex_id(raw_id: str) -> str:
if raw_id.startswith("https://openalex.org/"):
return raw_id
return f"https://openalex.org/{raw_id}"
async def _get_institution_identity(
raw_oa_institution_id: str,
) -> Optional[Institution]:
page = await institution_service.get_institutions_by_ids(
[_prefix_openalex_id(raw_oa_institution_id)]
)
return page.elements[0] if page.elements else None
def _current_institution_cohort_query(
author_ids: List[str],
institution_id: str,
institution_ror: Optional[str],
institution_display_name: str,
affiliation_year_filter: Dict,
) -> Dict:
"""Build the author cohort query used by work classification access."""
affiliation_identifiers = [
{"term": {"affiliations.institution.id": institution_id}},
]
if institution_ror:
affiliation_identifiers.append(
{"term": {"affiliations.institution.ror": institution_ror}}
)
affiliation_identifiers.append(
{
"match_phrase": {
"affiliations.institution.display_name": institution_display_name
}
}
)
recent_affiliation = {
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{
"bool": {
"should": affiliation_identifiers,
"minimum_should_match": 1,
}
},
affiliation_year_filter,
]
}
},
}
}
matching_last_known_institution = {
"nested": {
"path": "last_known_institutions",
"query": {
"match_phrase": {
"last_known_institutions.display_name": institution_display_name
}
},
}
}
missing_last_known_institutions = {
"bool": {
"must_not": [
{
"nested": {
"path": "last_known_institutions",
"query": {
"exists": {
"field": "last_known_institutions.display_name"
}
},
}
}
]
}
}
return {
"bool": {
"filter": [
{
"terms": {
"id": [_prefix_openalex_id(author_id) for author_id in author_ids]
}
},
recent_affiliation,
{
"bool": {
"should": [
matching_last_known_institution,
missing_last_known_institutions,
],
"minimum_should_match": 1,
}
},
]
}
}
async def authors_currently_belong_to_institution(
raw_oa_author_ids: List[str],
raw_oa_institution_id: str,
) -> Set[str]:
"""Return current cohort members using one query for all author IDs."""
return await _authors_belong_to_institution(
raw_oa_author_ids,
raw_oa_institution_id,
affiliation_year_filter={
"range": {"affiliations.years": {"gte": 2025}}
},
)
async def _authors_belong_to_institution(
raw_oa_author_ids: List[str],
raw_oa_institution_id: str,
affiliation_year_filter: Dict,
) -> Set[str]:
"""Return matching author IDs for the supplied affiliation-year filter."""
"""Return active cohort members using one query for all supplied authors."""
author_ids = list(dict.fromkeys(filter(None, raw_oa_author_ids)))
if not author_ids:
return set()
institution = await _get_institution_identity(raw_oa_institution_id)
if not institution or not institution.display_name:
return set()
authors = await search_authors(
page=0,
size=len(author_ids),
query=_current_institution_cohort_query(
query=build_active_institution_membership_query(
institution_id=raw_oa_institution_id,
author_ids=author_ids,
institution_id=institution.id
or _prefix_openalex_id(raw_oa_institution_id),
institution_ror=institution.ror,
institution_display_name=institution.display_name,
affiliation_year_filter=affiliation_year_filter,
),
source=["id"],
)
@@ -2,18 +2,30 @@ import logging
from typing import Any
from . import model
from inse.exceptions import MissingApiKeyError, ElasticsearchException, NotFoundException
from inse.authors.v2.service import author_currently_belongs_to_institution
from inse.exceptions import NotFoundException
from .search_client import CompanyConnectionsSearchClient
logger = logging.getLogger(__name__)
UDE_OPENALEX_ID = "https://openalex.org/I62318514"
UDE_ROR = "https://ror.org/04mz5ra38"
UDE_DISPLAY_NAME = "University of Duisburg-Essen"
MATCHING_METHOD = "exact_openalex_display_name_to_handelsregister_officer_name"
async def author_has_company_connections_access(
author_id: str,
institution_id: str | None,
) -> bool:
"""Return whether the author belongs to the account institution's active cohort."""
if not institution_id:
return False
return await author_currently_belongs_to_institution(
raw_oa_author_id=author_id,
raw_oa_institution_id=institution_id,
)
async def get_company_connections_by_author_id(
author_id: str,
client: CompanyConnectionsSearchClient | None = None,
@@ -27,16 +39,11 @@ async def get_company_connections_by_author_id(
source = author_hit.get("_source", {})
display_name = _clean(source.get("display_name"))
institution_scope, matching_institutions = _get_ude_institution_scope(source)
is_ude_author = institution_scope is not None
if not is_ude_author or not display_name:
if not display_name:
return model.CompanyConnectionsResponse(
author_id=author_id,
display_name=display_name or None,
is_ude_author=is_ude_author,
institution_scope=institution_scope,
matching_institutions=matching_institutions,
matching_method=None,
company_count=0,
has_more_results=False,
@@ -62,9 +69,6 @@ async def get_company_connections_by_author_id(
return model.CompanyConnectionsResponse(
author_id=author_id,
display_name=display_name,
is_ude_author=True,
institution_scope=institution_scope,
matching_institutions=matching_institutions,
matching_method=MATCHING_METHOD,
company_count=company_count,
has_more_results=has_more_results,
@@ -95,44 +99,6 @@ async def get_company_counts_by_names(
)
def _get_ude_institution_scope(source: dict[str, Any]) -> tuple[str | None, list[str]]:
institutions = source.get("last_known_institutions") or []
direct_matches: list[str] = []
child_matches: list[str] = []
for institution in institutions:
if not isinstance(institution, dict):
continue
institution_id = _clean(institution.get("id"))
ror = _clean(institution.get("ror"))
name = _clean(institution.get("display_name"))
lineage = institution.get("lineage") or []
label = name or institution_id or ror
is_direct = (
institution_id == UDE_OPENALEX_ID
or ror == UDE_ROR
or name == UDE_DISPLAY_NAME
)
is_child = UDE_OPENALEX_ID in lineage and not is_direct
if is_direct:
direct_matches.append(label)
elif is_child:
child_matches.append(label)
if direct_matches:
return "direct_ude", sorted(set(direct_matches))
if child_matches:
return "child_of_ude", sorted(set(child_matches))
return None, []
def _parse_total(response: dict[str, Any]) -> tuple[int, str]:
total = response.get("hits", {}).get("total", 0)
@@ -28,12 +28,13 @@ class CompanyConnection(BaseModel):
officers: list[MatchedOfficer] = Field(default_factory=list)
class CompanyConnectionsAvailability(BaseModel):
available: bool
class CompanyConnectionsResponse(BaseModel):
author_id: str
display_name: str | None = None
is_ude_author: bool
institution_scope: str | None = None
matching_institutions: list[str] = Field(default_factory=list)
matching_method: str | None = None
@@ -4,7 +4,12 @@
REST API for possible company connections of OpenAlex authors.
"""
from fastapi import APIRouter
from typing import Annotated
from fastapi import APIRouter, HTTPException, status
from inse.auth.model import AccessTokenMetadata
from inse.auth.service import CurrentUserAccessTokenPayloadDep
from . import logic, model
@@ -14,6 +19,25 @@ router = APIRouter(
)
@router.get(
"/{author_id}/company-connections/availability",
operation_id="getCompanyConnectionsAvailability",
response_model=model.CompanyConnectionsAvailability,
summary="Check whether company connections are available for an author.",
)
async def get_company_connections_availability(
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
author_id: str,
) -> model.CompanyConnectionsAvailability:
available = await logic.author_has_company_connections_access(
author_id=author_id,
institution_id=access_token_metadata.effective_institution_id,
)
return model.CompanyConnectionsAvailability(available=available)
@router.get(
"/{author_id}/company-connections",
operation_id="getCompanyConnectionsByAuthor",
@@ -21,5 +45,23 @@ router = APIRouter(
response_model_exclude_none=True,
summary="Get possible company connections by OpenAlex author ID.",
)
async def get_company_connections_by_author(author_id: str):
async def get_company_connections_by_author(
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
author_id: str,
):
available = await logic.author_has_company_connections_access(
author_id=author_id,
institution_id=access_token_metadata.effective_institution_id,
)
if not available:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=(
"Company connections are only available for active members "
"of the account institution."
),
)
return await logic.get_company_connections_by_author_id(author_id)
@@ -157,49 +157,6 @@ class InstitutionsSearchClient:
total=total,
)
async def get_authors_by_institution_id(self, raw_institution_id: str) -> List[str]:
"""
Fetches authors associated with an institution.
Note: This query is specifically looking for current affiliations (2026).
"""
query = {
"nested": {
"path": "affiliations",
"query": {
"bool": {
"must": [
{
"term": {
"affiliations.institution.id": f"https://openalex.org/{raw_institution_id.upper()}"
}
},
{
"range": {
"affiliations.years": {"gte": 2026, "lte": 2026}
}
},
]
}
},
}
}
logger.debug(
"Fetching authors for institution_id=%s with query: %s",
raw_institution_id,
query,
)
res = await elasticsearch.search(index="openalex-authors", query=query)
hits = res.get("hits", {}).get("hits", [])
# Extracting display_name directly from the author document source
authors = {
hit["_source"].get("display_name")
for hit in hits
if hit["_source"].get("display_name")
}
return list(authors)
async def search_institutions(
self,
query_text: str,
+6 -6
View File
@@ -1,9 +1,9 @@
from openai import OpenAI, APIConnectionError
from openai import APIConnectionError
from openai import AsyncOpenAI
from .. import config
from typing import Optional, Dict, Any
import asyncio
def call(
async def call(
system_prompt: str,
user_prompt: str,
model: str = None,
@@ -16,18 +16,18 @@ def call(
if model is None:
model = config.settings.llm_model
response_format = None
if json_schema is not None:
response_format = _get_response_format(schema = json_schema,schema_name=schema_name)
client = OpenAI(
client = AsyncOpenAI(
base_url=config.settings.llm_api_url,
api_key=config.settings.llm_api_key,
timeout=timeout,
)
try:
response = client.chat.completions.create(
response = await client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": system_prompt},
+1 -1
View File
@@ -82,7 +82,7 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor
user_prompt += f"""Input:{text}"""
keywords = llm.call(
keywords = await llm.call(
system_prompt=system_prompt,
user_prompt=user_prompt,
json_schema = ExtractedKeywordsLLM.model_json_schema(),
+4
View File
@@ -61,6 +61,9 @@ from inse.topics.v2.router import router as topics_v2_router
from inse.projects.dfg_institutions.router import router as dfg_institutions_router
from inse.projects.dfg_persons.router import router as dfg_persons_router
from inse.projects.eu_organizations.router import router as eu_organizations_router
logger = logging.getLogger(__name__)
### startup
@@ -120,6 +123,7 @@ app.include_router(dfg_institutions_router)
app.include_router(dfg_persons_router)
app.include_router(bookmarks_router)
app.include_router(eu_organizations_router)
app.add_middleware(
ETagCacheMiddleware,
ttl=120, # 2 minutes expiration time
+84 -33
View File
@@ -8,14 +8,23 @@ from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
# Paths excluded from caching entirely (everything concerning auth/identity/mutations)
EXCLUDED_PATHS = (
"/api/auth/v2",
"/api/accounts",
"/api/bookmarks",
"/api/organizations",
)
# Responses whose contents depend on the current account or effective
# organization must never be reused by the browser.
NO_STORE_PATH_PREFIXES = (
"/api/auth/v2",
"/api/accounts",
"/api/bookmarks",
"/api/organizations",
"/api/dashboard",
"/api/rank/rank-author",
"/api/v2/works/classification/",
)
NO_STORE_PATH_FRAGMENTS = (
"/company-connections",
"/primary-category-aggregations",
)
# POST is opt-out. Add any endpoint here that MUTATES state (create/update/delete/
# trigger side effects), even if it "usually" returns 200.
EXCLUDED_POST_PATHS = (
@@ -82,21 +91,61 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
return f"{user_id}:{base}"
return base
def _content_type(self, response: Response) -> str | None:
return response.headers.get("content-type")
def _is_cacheable_request(self, request: Request) -> bool:
if request.url.path.startswith(EXCLUDED_PATHS):
return False
def _content_type(self, response: Response) -> str | None:
return response.headers.get("content-type")
def _requires_no_store(self, request: Request) -> bool:
path = request.url.path
return path.startswith(NO_STORE_PATH_PREFIXES) or any(
fragment in path for fragment in NO_STORE_PATH_FRAGMENTS
)
def _set_no_store_headers(self, response: Response) -> None:
response.headers["Cache-Control"] = "private, no-store, max-age=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
self._append_vary_authorization(response.headers)
@staticmethod
def _append_vary_authorization(headers) -> None:
vary_values = [
value.strip()
for value in headers.get("Vary", "").split(",")
if value.strip()
]
if not any(value.lower() == "authorization" for value in vary_values):
vary_values.append("Authorization")
headers["Vary"] = ", ".join(vary_values)
def _cache_response_headers(
self, request: Request, etag: str, content_type: str | None
) -> dict[str, str]:
cache_control = f"max-age={self.ttl}"
headers = {"ETag": etag, "Cache-Control": cache_control}
if request.headers.get("authorization"):
headers["Cache-Control"] = f"private, {cache_control}"
headers["Vary"] = "Authorization"
if content_type:
headers["Content-Type"] = content_type
return headers
def _is_cacheable_request(self, request: Request) -> bool:
if self._requires_no_store(request):
return False
if request.method == "GET":
return True
if request.method == "POST":
return not request.url.path.startswith(EXCLUDED_POST_PATHS)
return False
async def dispatch(self, request: Request, call_next):
if not self._is_cacheable_request(request):
return await call_next(request)
async def dispatch(self, request: Request, call_next):
if self._requires_no_store(request):
response = await call_next(request)
self._set_no_store_headers(response)
return response
if not self._is_cacheable_request(request):
return await call_next(request)
body_bytes = b""
if request.method == "POST":
@@ -116,17 +165,21 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
client_etag = request.headers.get("if-none-match")
# Cache hit + not expired
if entry:
if client_etag == entry["etag"]:
headers = {"ETag": entry["etag"]}
if entry.get("content_type"):
headers["Content-Type"] = entry["content_type"]
return Response(status_code=304, headers=headers)
headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
if entry.get("content_type"):
headers["Content-Type"] = entry["content_type"]
return Response(
if entry:
if client_etag == entry["etag"]:
headers = self._cache_response_headers(
request,
entry["etag"],
entry.get("content_type"),
)
return Response(status_code=304, headers=headers)
headers = self._cache_response_headers(
request,
entry["etag"],
entry.get("content_type"),
)
return Response(
content=entry["body"],
status_code=entry["status_code"],
headers=headers,
@@ -151,11 +204,9 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
},
)
headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
if content_type:
headers["Content-Type"] = content_type
return Response(
headers = self._cache_response_headers(request, etag, content_type)
return Response(
content=body,
status_code=response.status_code,
headers=headers,
)
)
+1 -1
View File
@@ -292,7 +292,7 @@ async def _get_article_keywords(
if not text:
return []
raw = llm.call(
raw = await llm.call(
system_prompt=KEYWORD_SYSTEM_PROMPT,
user_prompt=f"Artikel:\n{text}",
temperature=0.3,
+5 -99
View File
@@ -444,7 +444,7 @@ async def generate_person_bio(
user_prompt = f"Daten zur Person:\n{person_json}"
bio = llm.call(
bio = await llm.call(
system_prompt=system_prompt,
user_prompt=user_prompt,
temperature=0.8,
@@ -608,100 +608,6 @@ async def search_persons_autocomplete(
return AuthorsListResponse(results=persons)
async def search_persons_by_institution(
institution_name: str,
limit: Optional[int] = 10,
page_offset: Optional[int] = 0,
include: Optional[str] = None,
) -> AuthorsListResponse:
if not institution_name:
raise BadRequestException("institution_name must be provided")
target_year = datetime.now().year - 1
recent_affiliation_query = {
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{
"match_phrase": {
"affiliations.institution.display_name": institution_name
}
},
{"range": {"affiliations.years": {"gte": target_year}}},
]
}
},
}
}
matching_last_known_institution_query = {
"nested": {
"path": "last_known_institutions",
"query": {
"match_phrase": {
"last_known_institutions.display_name": institution_name
}
},
}
}
missing_last_known_institutions_query = {
"bool": {
"must_not": [
{
"nested": {
"path": "last_known_institutions",
"query": {"exists": {"field": "last_known_institutions.id"}},
}
}
]
}
}
search_query = {
"bool": {
"should": [
{
"bool": {
"filter": [
matching_last_known_institution_query,
recent_affiliation_query,
]
}
},
{
"bool": {
"filter": [
missing_last_known_institutions_query,
recent_affiliation_query,
]
}
},
],
"minimum_should_match": 1,
}
}
try:
response = await elasticsearch.search(
index="openalex-authors",
query=search_query,
source=include.split(",") if include else True,
size=limit,
offset=page_offset,
sort=[{"works_count": {"order": "desc"}}],
track_total_hits=True,
)
except ElasticsearchException as e:
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
hits = response.get("hits", {}).get("hits", [])
persons = [util.get_persons_data(hit) for hit in hits]
return AuthorsListResponse(
results=persons, meta=Meta(count=total_count, page=page_offset)
)
def _enrich_author_data(author_data) -> Optional[CustomAuthor]:
if not author_data:
return None
@@ -747,28 +653,28 @@ def _enrich_author_data(author_data) -> Optional[CustomAuthor]:
async def advanced_search_persons(
query: Optional[str] = None,
institution_name: Optional[str] = None,
institution_id: Optional[str] = None,
sort_by: Optional[str] = None,
sort_order: Optional[str] = None,
topics: Optional[List[str]] = None,
page: int = 1,
page_size: int = 10,
include: Optional[set[str]] = None,
strict: Optional[bool] = False,
year_filter_enabled: bool = True,
filter_mode: Optional[str] = "from",
filter_year: Optional[int] = None,
) -> CustomAuthorsListResponse:
try:
query_body = build_authors_search_rescored(
query=query,
institution_name=institution_name,
institution_id=institution_id,
sort_by=sort_by,
sort_order=sort_order,
topics=topics,
page=page,
page_size=page_size,
include=include,
strict=strict,
year_filter_enabled=year_filter_enabled,
track_total_hits=True,
filter_mode=filter_mode,
filter_year=filter_year,
+27 -106
View File
@@ -1,10 +1,15 @@
from typing import Any, List, Optional, Set
from inse.authors.institution_membership_query import (
build_institution_membership_query,
current_affiliation_year_cutoff,
)
def build_author_filter_clauses(
institution_name: Optional[str] = None,
institution_id: Optional[str] = None,
topics: Optional[List[str]] = None,
strict: Optional[bool] = False,
year_filter_enabled: bool = True,
filter_mode: Optional[str] = "from",
filter_year: Optional[int] = None,
) -> List[dict]:
@@ -46,109 +51,25 @@ def build_author_filter_clauses(
}
}
)
# Institution filter with optional year-based filtering
if institution_name:
if filter_year is not None:
target_year = filter_year
mode = filter_mode or "from"
else:
from datetime import datetime
current_year = datetime.now().year
target_year = current_year - 1
mode = "from"
range_query = {"gte": target_year}
if mode == "in":
range_query["lte"] = target_year
if strict:
filter_clauses.append(
{
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{
"match_phrase": {
"affiliations.institution.display_name": institution_name
}
},
{"range": {"affiliations.years": range_query}},
]
}
},
}
}
if institution_id:
if year_filter_enabled:
membership_mode = "in" if filter_mode == "in" else "from"
membership_year = (
filter_year
if filter_year is not None
else current_affiliation_year_cutoff()
)
else:
recent_affiliation_query = {
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{
"match_phrase": {
"affiliations.institution.display_name": institution_name
}
},
{"range": {"affiliations.years": range_query}},
]
}
},
}
}
matching_last_known_institution_query = {
"nested": {
"path": "last_known_institutions",
"query": {
"match_phrase": {
"last_known_institutions.display_name": institution_name
}
},
}
}
missing_last_known_institutions_query = {
"bool": {
"must_not": [
{
"nested": {
"path": "last_known_institutions",
"query": {
"exists": {"field": "last_known_institutions.id"}
},
}
}
]
}
}
filter_clauses.append(
{
"bool": {
"should": [
{
"bool": {
"filter": [
matching_last_known_institution_query,
recent_affiliation_query,
]
}
},
{
"bool": {
"filter": [
missing_last_known_institutions_query,
recent_affiliation_query,
]
}
},
],
"minimum_should_match": 1,
}
}
membership_mode = "all"
membership_year = None
filter_clauses.append(
build_institution_membership_query(
institution_id=institution_id,
year_mode=membership_mode,
year=membership_year,
)
)
if topics:
for t in topics:
@@ -169,14 +90,14 @@ def build_authors_search_rescored(
using: Any = None,
index: Optional[str] = None,
query: Optional[str] = None,
institution_name: Optional[str] = None,
institution_id: Optional[str] = None,
sort_by: Optional[str] = None,
sort_order: Optional[str] = None,
topics: Optional[List[str]] = None,
page: int = 1,
page_size: int = 10,
include: Optional[Set[str]] = None,
strict: Optional[bool] = False,
year_filter_enabled: bool = True,
track_total_hits: Optional[bool] = False,
filter_mode: Optional[str] = "from",
filter_year: Optional[int] = None,
@@ -209,9 +130,9 @@ def build_authors_search_rescored(
# 2. Build Filters
filter_clauses = build_author_filter_clauses(
institution_name=institution_name,
institution_id=institution_id,
topics=topics,
strict=strict,
year_filter_enabled=year_filter_enabled,
filter_mode=filter_mode,
filter_year=filter_year,
)
+12 -34
View File
@@ -150,33 +150,6 @@ async def search_persons_autocomplete(
return await logic.search_persons_autocomplete(author_name=author_name, include=include)
@router.get(
"/persons/searchByInstitution",
operation_id="searchPersonsByInstitution",
response_model=AuthorsListResponse,
summary="Searches for persons by institution name.",
tags=["Persons"],
)
async def search_persons_by_institution(
institution_name: Annotated[
str, Query(description="Institution name (e.g., MIT, Oxford University)")
],
include: Annotated[
Optional[str],
Query(
description=(
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, ..."
),
example="topics_full,topic_share",
),
],
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
):
return await logic.search_persons_by_institution(institution_name, include=include, page_offset=page_offset, limit=limit)
@router.get(
"/persons/search-list",
operation_id="searchPersonsList",
@@ -189,8 +162,9 @@ async def search_persons_list(
query: Annotated[
Optional[str], Query(description="Search query (e.g., Arman AND Arzani)")
] = None,
institution_name: Annotated[
Optional[str], Query(alias="institutionName", description="Filter by institution name")
institution_id: Annotated[
Optional[str],
Query(alias="institutionId", description="Filter by OpenAlex institution ID"),
] = None,
sort_by: Annotated[
Optional[str], Query(alias="sortBy", description="Value to sort by")
@@ -214,9 +188,13 @@ async def search_persons_list(
example="topics_full,topic_share",
),
] = None,
strict: Annotated[
Optional[bool], Query(description="Strict institution search by target year")
] = False,
year_filter_enabled: Annotated[
bool,
Query(
alias="yearFilterEnabled",
description="Apply the selected affiliation year rule",
),
] = True,
filter_mode: Annotated[
Optional[str], Query(alias="filterMode", description="Filter mode: 'in' or 'from'")
] = "from",
@@ -231,14 +209,14 @@ async def search_persons_list(
)
return await logic.advanced_search_persons(
query=query,
institution_name=institution_name,
institution_id=institution_id,
sort_by=sort_by,
sort_order=sort_order,
topics=topic,
page=page,
page_size=page_size,
include=include_set,
strict=strict,
year_filter_enabled=year_filter_enabled,
filter_mode=filter_mode,
filter_year=filter_year,
)
File diff suppressed because it is too large Load Diff
@@ -1,281 +0,0 @@
import logging
import asyncio
from typing import Any, Dict, List, Optional, Union
from inse.config import get_settings
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
# Import base models
from inse.models.cordis_eu_project import CordisEuProject
# Import FP7 models
from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project
from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization
from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication
from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR
from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary
from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic
from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink
from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc
from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis
from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
# Import H2020 models
from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project
from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization
from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication
from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable
from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary
from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic
from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink
from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc
from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis
from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI
from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
# Import Horizon Europe models
from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject
from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization
from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication
from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable
from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary
from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic
from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink
from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
settings = get_settings()
logger = logging.getLogger(__name__)
logger.setLevel(settings.logging_level)
# Entity config
_FP7_ENTITY_CONFIGS = [
{"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, "model_class": Fp7Organization},
{"key": "publications", "index_pattern": ESIndex.CORDIS_EU_FP7_PUBLICATIONS, "model_class": Fp7Publication},
{"key": "iprs", "index_pattern": ESIndex.CORDIS_EU_FP7_PROJECT_IPRS, "model_class": Fp7ProjectIPR},
{"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_FP7_REPORT_SUMMARIES, "model_class": Fp7ReportSummary},
{"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_FP7_TOPICS, "model_class": Fp7Topic},
{"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_FP7_WEB_LINKS, "model_class": Fp7WebLink},
{"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_FP7_EUROSCIVOC, "model_class": Fp7EurosciVoc},
{"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_FP7_LEGAL_BASIS, "model_class": Fp7LegalBasis},
]
_H2020_ENTITY_CONFIGS = [
{"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, "model_class": H2020Organization},
{"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, "model_class": H2020Publication},
{"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_DELIVERABLES, "model_class": H2020Deliverable},
{"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES, "model_class": H2020ReportSummary},
{"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, "model_class": H2020Topic},
{"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_WEB_LINKS, "model_class": H2020WebLink},
{"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, "model_class": H2020EurosciVoc},
{"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_LEGAL_BASIS, "model_class": H2020LegalBasis},
{"key": "erc_principal_investigators", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ERC_PIS, "model_class": H2020ErcPI},
]
_HEU_ENTITY_CONFIGS = [
{"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, "model_class": HEUOrganization},
{"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, "model_class": HEUPublication},
{"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_DELIVERABLES, "model_class": HEUDeliverable},
{"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES, "model_class": HEUReportSummary},
{"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, "model_class": HEUTopic},
{"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_WEB_LINKS, "model_class": HEUWebLink},
{"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc},
{"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis},
]
async def get_enriched_cordis_project_by_id(
project_id: str,
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
"""
Fetches and enriches a single Cordis EU project by its ID across all programme types.
Args:
project_id: The project ID to fetch.
Returns:
The enriched detailed project model, or None if not found.
"""
if not project_id:
return None
query = {"bool": {"filter": [{"term": {"id": project_id}}]}}
response = await elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
size=1,
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
logger.info(f"No project found with ID: {project_id}")
return None
hit = hits[0]
index = hit.get("_index", "")
source = hit.get("_source", {})
program_type = _determine_program_type_from_index(index)
enrichers = {
"fp7": _enrich_fp7_project,
"h2020": _enrich_h2020_project,
"heu": _enrich_heu_project,
}
enricher = enrichers.get(program_type)
if enricher is None:
logger.warning(f"Unknown programme type for index: {index}")
return CordisEuProject.model_validate(source)
return await enricher(project_id, source)
# helpers
def _determine_program_type_from_index(index: str) -> str:
"""Determines the programme type from the Elasticsearch index name."""
index_lower = index.lower()
if "fp7" in index_lower:
return "fp7"
if "horizon_2020" in index_lower:
return "h2020"
if "heu" in index_lower or "horizon_europe" in index_lower:
return "heu"
return "unknown"
async def _fetch_related_entities_parallel(
project_id: str,
entity_configs: List[Dict[str, Any]],
) -> Dict[str, List[Any]]:
"""
Fetches all related entity types for a project in parallel.
Args:
project_id: The project ID to fetch entities for.
entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'.
Returns:
Dictionary mapping each config 'key' to a list of validated entities.
"""
async def _fetch_one(config: Dict[str, Any]):
entities = await _fetch_related_entities(
project_ids=[project_id],
index_pattern=config["index_pattern"],
model_class=config["model_class"],
)
return config["key"], entities.get(project_id, [])
tasks = [_fetch_one(cfg) for cfg in entity_configs]
completed = await asyncio.gather(*tasks, return_exceptions=True)
results: Dict[str, List[Any]] = {}
for cfg, res in zip(entity_configs, completed):
key = cfg["key"]
if isinstance(res, Exception):
logger.error(f"Parallel fetch failed for '{key}': {res}")
results[key] = []
else:
key_name, data = res
results[key_name] = data
return results
async def _fetch_related_entities(
project_ids: List[str],
index_pattern: str,
model_class: Any,
) -> Dict[str, List[Any]]:
"""
Fetches and groups related entities from Elasticsearch by project ID.
Args:
project_ids: List of project IDs to fetch entities for.
index_pattern: The index pattern to search (supports wildcards).
model_class: The Pydantic model class to validate against.
Returns:
Dictionary mapping project IDs to lists of validated entities.
"""
query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}}
try:
response = await elasticsearch.search(
query=query,
index=index_pattern,
cluster=ESCluster.INSE,
size=10000,
)
except Exception as e:
logger.warning(f"Failed to fetch from {index_pattern}: {e}")
return {}
grouped: Dict[str, List[Any]] = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
project_id = source.get("projectID")
if not project_id:
continue
grouped.setdefault(project_id, [])
try:
entity = model_class.model_validate(source)
grouped[project_id].append(entity)
except Exception as e:
logger.warning(f"Failed to validate {model_class.__name__} for project {project_id}: {e}")
return grouped
async def _enrich_fp7_project(
project_id: str,
project_source: Dict[str, Any],
) -> Optional[Fp7ProjectDetails]:
"""Enriches a single FP7 project with all related data."""
try:
project = Fp7Project.model_validate(project_source)
except Exception as e:
logger.error(f"Failed to validate FP7 project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
return Fp7ProjectDetails.from_project_with_relations(project=project, **related)
async def _enrich_h2020_project(
project_id: str,
project_source: Dict[str, Any],
) -> Optional[H2020ProjectDetails]:
"""Enriches a single H2020 project with all related data."""
try:
project = H2020Project.model_validate(project_source)
except Exception as e:
logger.error(f"Failed to validate H2020 project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
return H2020ProjectDetails.from_project_with_relations(project=project, **related)
async def _enrich_heu_project(
project_id: str,
project_source: Dict[str, Any],
) -> Optional[HEUProjectDetails]:
"""Enriches a single Horizon Europe project with all related data."""
try:
project = HEUProject.model_validate(project_source)
except Exception as e:
logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
return HEUProjectDetails.from_project_with_relations(project=project, **related)
@@ -0,0 +1,51 @@
import logging
from typing import Annotated, List
from fastapi import APIRouter, Query
from inse.projects.eu_organizations.service import autocomplete_organizations_for_selector, get_organizations_by_ids
from inse.projects.model import EuCordisOrganizationSelectorPage
from inse.tags import Tags
logger = logging.getLogger(__name__)
EU_ORGANIZATIONS_PREFIX = "/api/eu/organizations"
router = APIRouter(prefix=EU_ORGANIZATIONS_PREFIX, tags=[Tags.PROJECTS])
@router.get(
"/ids",
operation_id="getEuOrganizationsByIds",
summary="Returns EU CORDIS organizations by organisation IDs.",
response_model=EuCordisOrganizationSelectorPage,
)
async def get_eu_organizations_by_ids(
organization_ids: Annotated[
List[str],
Query(description="CORDIS organisation IDs to retrieve."),
] = [],
) -> EuCordisOrganizationSelectorPage:
return await get_organizations_by_ids(organization_ids=organization_ids or [])
@router.get(
"/autocomplete/selector",
operation_id="getEuOrganizationAutocompleteForSelector",
summary="Returns EU CORDIS organizations based on a search term.",
response_model=EuCordisOrganizationSelectorPage,
)
async def get_eu_organization_autocomplete(
query: Annotated[
str,
Query(description="Search term for organization autocomplete."),
] = "",
page: Annotated[int, Query(ge=0)] = 0,
size: Annotated[int, Query(ge=1)] = 10,
) -> EuCordisOrganizationSelectorPage:
return await autocomplete_organizations_for_selector(
query=query,
page=page,
size=size,
)
@@ -0,0 +1,160 @@
import logging
from typing import Dict, List, Optional
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.projects.model import (
EuCordisOrganizationSelectorPage,
EuCordisOrganizationSelectorSummary,
EuCordisProjectType,
)
logger = logging.getLogger(__name__)
def _project_type_from_org_index(index_name: str) -> Optional[EuCordisProjectType]:
if index_name == ESIndex.CORDIS_EU_FP7_ORGANIZATIONS.value:
return EuCordisProjectType.FP7
if index_name == ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS.value:
return EuCordisProjectType.H2020
if index_name == ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS.value:
return EuCordisProjectType.HEU
return None
async def get_organizations_by_ids(
organization_ids: List[str],
) -> EuCordisOrganizationSelectorPage:
if not organization_ids:
return EuCordisOrganizationSelectorPage(elements=[], total=0, page=0, size=0)
response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
cluster=ESCluster.INSE,
body={
"size": len(organization_ids) * 3,
"_source": [
"id",
"organisationID",
"name",
"shortName",
"country",
"city",
],
"query": {
"terms": {
"organisationID": organization_ids
}
},
"collapse": {
"field": "organisationID"
},
},
)
elements: List[EuCordisOrganizationSelectorSummary] = []
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
source["project_type"] = _project_type_from_org_index(hit.get("_index", ""))
elements.append(EuCordisOrganizationSelectorSummary.from_es_source(source))
return EuCordisOrganizationSelectorPage(
elements=elements,
total=response.get("hits", {}).get("total", {}).get("value", len(elements)),
page=0,
size=len(elements),
)
async def autocomplete_organizations_for_selector(
query: str,
page: int = 0,
size: int = 10,
) -> EuCordisOrganizationSelectorPage:
if not query or not query.strip():
return EuCordisOrganizationSelectorPage(
elements=[],
total=0,
page=page,
size=size,
)
query = query.strip()
response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
cluster=ESCluster.INSE,
body={
"size": size,
"from": page * size,
"_source": [
"id",
"organisationID",
"name",
"shortName",
"country",
"city",
],
"query": {
"bool": {
"should": [
{
"match_phrase_prefix": {
"name": {
"query": query,
"max_expansions": 50,
}
}
},
{
"wildcard": {
"shortName": {
"value": f"*{query}*",
"case_insensitive": True,
}
}
},
{
"term": {
"organisationID": query,
}
},
],
"minimum_should_match": 1,
}
},
"collapse": {
"field": "organisationID",
},
"sort": [
{
"name.keyword": {
"order": "asc",
"missing": "_last",
"unmapped_type": "keyword",
}
}
],
},
)
elements: List[EuCordisOrganizationSelectorSummary] = []
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
source["project_type"] = _project_type_from_org_index(hit.get("_index", ""))
elements.append(
EuCordisOrganizationSelectorSummary.from_es_source(
source=source,
project_type=source["project_type"],
)
)
return EuCordisOrganizationSelectorPage(
elements=elements,
total=response.get("hits", {}).get("total", {}).get("value", len(elements)),
page=page,
size=size,
)
+132 -2
View File
@@ -3,11 +3,11 @@ import logging
from typing import Any, Dict, List, Optional, Set, Tuple
from collections import defaultdict
from inse.projects.eu_cordis_projects_enrichment_client import get_enriched_cordis_project_by_id
from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.projects.model import EuCordisProjectType
logger = logging.getLogger(__name__)
@@ -244,3 +244,133 @@ async def get_person_institutes(
"address_country_en": source.get("address_country_en"),
}
return result
#EU Cordis Projects
async def get_eu_project_ids_by_openalex_topic_ids(
project_types: List[EuCordisProjectType],
topic_ids: List[str],
) -> Dict[EuCordisProjectType, List[str]]:
"""
Returns EU CORDIS project IDs whose mapped OpenAlex topic_matches contain
EVERY given topic ID. Same semantics as DFG topic filtering.
"""
if not topic_ids:
return {project_type: [] for project_type in project_types}
required_topics = set(topic_ids)
result: Dict[EuCordisProjectType, List[str]] = {}
for project_type in project_types:
project_topics: Dict[str, Set[str]] = defaultdict(set)
page_size = 1000
from_ = 0
while True:
body = {
"size": page_size,
"from": from_,
"_source": ["project_id", "topic_matches"],
"query": {
"terms": {
"topic_matches.topic_id.keyword": topic_ids
}
},
}
response = await elasticsearch.search(
index=project_type.to_openalex_topics_index(),
cluster=ESCluster.INSE,
body=body,
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
for hit in hits:
source = hit.get("_source", {})
project_id = source.get("project_id")
if not project_id:
continue
topic_matches = source.get("topic_matches") or []
if isinstance(topic_matches, dict):
topic_matches = [topic_matches]
for match in topic_matches:
topic_id = match.get("topic_id")
if topic_id in required_topics:
project_topics[project_id].add(topic_id)
if len(hits) < page_size:
break
from_ += page_size
result[project_type] = [
project_id
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
return result
async def get_openalex_topics_for_eu_projects(
project_ids_by_type: Dict[EuCordisProjectType, List[str]],
) -> Dict[Tuple[EuCordisProjectType, str], List[Dict[str, Any]]]:
"""
Fetches mapped OpenAlex topic matches for EU CORDIS projects.
"""
topic_lookup: Dict[Tuple[EuCordisProjectType, str], List[Dict[str, Any]]] = {}
for project_type, project_ids in project_ids_by_type.items():
if not project_ids:
continue
page_size = 1000
from_ = 0
while True:
response = await elasticsearch.search(
index=project_type.to_openalex_topics_index(),
cluster=ESCluster.INSE,
body={
"size": page_size,
"from": from_,
"_source": ["project_id", "topic_matches"],
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
},
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
for hit in hits:
source = hit.get("_source", {})
project_id = source.get("project_id")
if not project_id:
continue
topic_matches = source.get("topic_matches") or []
if isinstance(topic_matches, dict):
topic_matches = [topic_matches]
topic_lookup.setdefault((project_type, project_id), []).extend(topic_matches)
if len(hits) < page_size:
break
from_ += page_size
return topic_lookup
+262 -5
View File
@@ -14,6 +14,7 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HE
from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
from inse.authors.v2.model import AuthorPage
from typing import Union
class ProjectType(StrEnum):
@@ -81,11 +82,6 @@ class BundProjectList(BaseModel):
)
total: int = Field(default=0, description="The total number of bund projects.")
class EuProjectPage(Page):
elements: List[EuProject] = Field(
default_factory=list, description="The EU projects on this page."
)
class DfgInstitutionSummary(BaseModel):
"""A summary of a DFG institution."""
@@ -443,6 +439,12 @@ class FundingProjectPage(Page):
)
#EU CORDIS PROJECTS
class EuProjectPage(Page):
elements: List[EuProject] = Field(
default_factory=list, description="The EU projects on this page."
)
class EuOrganizationShort(BaseModel):
project_id: str = Field(description="The unique identifier of the project.")
organization_id: str = Field(
@@ -496,3 +498,258 @@ class EuOrganizationProjectSummaryPage(Page):
default_factory=list,
description="The organization project summaries on this page.",
)
################
class EuCordisProjectType(StrEnum):
FP7 = "fp7"
H2020 = "h2020"
HEU = "heu"
def to_project_index(self) -> ESIndex:
mapping = {
self.FP7: ESIndex.CORDIS_EU_FP7_PROJECTS,
self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS,
self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS,
}
return mapping[self]
def to_organization_index(self) -> ESIndex:
mapping = {
self.FP7: ESIndex.CORDIS_EU_FP7_ORGANIZATIONS,
self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS,
self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS,
}
return mapping[self]
def to_cordis_topic_index(self) -> ESIndex:
mapping = {
self.FP7: ESIndex.CORDIS_EU_FP7_TOPICS,
self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_TOPICS,
self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS,
}
return mapping[self]
def to_cordis_publications_index(self) -> ESIndex:
mapping = {
self.FP7: ESIndex.CORDIS_EU_FP7_PUBLICATIONS,
self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS,
self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS,
}
return mapping[self]
def to_euroscivoc_index(self) -> ESIndex:
mapping = {
self.FP7: ESIndex.CORDIS_EU_FP7_EUROSCIVOC,
self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC,
self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC,
}
return mapping[self]
def to_openalex_topics_index(self) -> ESIndex:
mapping = {
self.FP7: ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING,
self.H2020: ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS,
self.HEU: ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS,
}
return mapping[self]
@classmethod
def from_index_name(cls, index_name: str) -> "EuCordisProjectType":
if index_name == ESIndex.CORDIS_EU_FP7_PROJECTS.value:
return cls.FP7
if index_name == ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS.value:
return cls.H2020
if index_name == ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS.value:
return cls.HEU
raise ValueError(f"Unsupported EU CORDIS project index: {index_name}")
class EuCordisOrganizationSummary(BaseModel):
id: Optional[str] = None
organisation_id: Optional[str] = None
name: Optional[str] = None
short_name: Optional[str] = None
country: Optional[str] = None
city: Optional[str] = None
role: Optional[str] = None
activity_type: Optional[str] = None
project_id: Optional[str] = None
ec_contribution: Optional[float] = None
total_cost: Optional[float] = None
@classmethod
def from_es_source(cls, source: Dict[str, Any]) -> "EuCordisOrganizationSummary":
return cls(
id=source.get("id"),
organisation_id=source.get("organisationID"),
name=source.get("name"),
short_name=source.get("shortName"),
country=source.get("country"),
city=source.get("city"),
role=source.get("role"),
activity_type=source.get("activityType"),
project_id=source.get("projectID"),
ec_contribution=source.get("ecContribution"),
total_cost=source.get("totalCost"),
)
class EuCordisTopicSummary(BaseModel):
id: Optional[str] = None
project_id: Optional[str] = None
title: Optional[str] = None
topic: Optional[str] = None
@classmethod
def from_es_source(cls, source: Dict[str, Any]) -> "EuCordisTopicSummary":
return cls(
id=source.get("id"),
project_id=source.get("projectID"),
title=source.get("title"),
topic=source.get("topic"),
)
class EuCordisEurosciVocSummary(BaseModel):
id: Optional[str] = None
project_id: Optional[str] = None
code: Optional[str] = None
title: Optional[str] = None
description: Optional[str] = None
path: Optional[str] = None
@classmethod
def from_es_source(cls, source: Dict[str, Any]) -> "EuCordisEurosciVocSummary":
return cls(
id=source.get("id"),
project_id=source.get("projectID"),
code=source.get("code"),
title=source.get("title"),
description=source.get("description"),
path=source.get("path"),
)
class EuCordisProjectSummary(BaseModel):
id: str
project_type: EuCordisProjectType
title: Optional[str] = None
acronym: Optional[str] = None
objective: Optional[str] = None
keywords: Optional[str] = None
framework_programme: Optional[str] = None
funding_scheme: Optional[str] = None
status: Optional[str] = None
start_date: Optional[date] = None
end_date: Optional[date] = None
ec_max_contribution: Optional[float] = None
total_cost: Optional[float] = None
authors: Optional[AuthorPage] = None
organizations: List[EuCordisOrganizationSummary] = Field(default_factory=list)
cordis_topics: List[EuCordisTopicSummary] = Field(default_factory=list)
eurosci_voc: List[EuCordisEurosciVocSummary] = Field(default_factory=list)
topics: List[Topic] = Field(default_factory=list, description="Mapped OpenAlex topics.")
@classmethod
def from_hit(
cls,
hit: Dict[str, Any],
authors: Optional[AuthorPage] = None,
organizations: Optional[List[EuCordisOrganizationSummary]] = None,
cordis_topics: Optional[List[EuCordisTopicSummary]] = None,
eurosci_voc: Optional[List[EuCordisEurosciVocSummary]] = None,
topics: Optional[List[Topic]] = None,
) -> "EuCordisProjectSummary":
source = hit.get("_source", {})
project_type = EuCordisProjectType.from_index_name(hit.get("_index", ""))
return cls(
id=source.get("id") or hit.get("_id", ""),
project_type=project_type,
title=source.get("title"),
acronym=source.get("acronym"),
objective=source.get("objective"),
keywords=source.get("keywords"),
framework_programme=source.get("frameworkProgramme"),
funding_scheme=source.get("fundingScheme"),
status=source.get("status"),
start_date=source.get("startDate"),
end_date=source.get("endDate"),
ec_max_contribution=source.get("ecMaxContribution"),
total_cost=source.get("totalCost"),
authors=authors or None,
organizations=organizations or [],
cordis_topics=cordis_topics or [],
eurosci_voc=eurosci_voc or [],
topics=topics or [],
)
@staticmethod
def topic_from_match(match: Dict[str, Any]) -> Topic:
domain_name = match.get("domain")
field_name = match.get("field")
subfield_name = match.get("subfield")
domain = TopicDomain(display_name=domain_name) if domain_name else None
field = TopicField(display_name=field_name) if field_name else None
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
return Topic(
id=match.get("topic_id"),
display_name=match.get("topic_display_name"),
domain=domain,
field=field,
subfield=subfield,
)
class EuCordisProjectSearchPage(Page):
elements: List[EuCordisProjectSummary] = Field(
default_factory=list,
description="The EU CORDIS project summaries on this page.",
)
class EuCordisOrganizationSelectorSummary(BaseModel):
id: Optional[str] = None
organisation_id: Optional[str] = None
name: Optional[str] = None
short_name: Optional[str] = None
country: Optional[str] = None
city: Optional[str] = None
project_type: Optional[EuCordisProjectType] = None
@classmethod
def from_es_source(
cls,
source: Dict[str, Any],
project_type: Optional[EuCordisProjectType] = None,
) -> "EuCordisOrganizationSelectorSummary":
return cls(
id=source.get("id"),
organisation_id=source.get("organisationID"),
name=source.get("name"),
short_name=source.get("shortName"),
country=source.get("country"),
city=source.get("city"),
project_type=project_type,
)
class EuCordisOrganizationSelectorPage(Page):
elements: List[EuCordisOrganizationSelectorSummary] = Field(default_factory=list)
@@ -21,7 +21,7 @@ from inse.projects.model import (
ProjectsSortBy,
SortDirection,
)
from inse.projects.eu_cordis_projects_enrichment_client import get_enriched_cordis_project_by_id
from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id
from inse.models.dfg_project_details import DfgProjectDetails
from inse.models.bund_project_details import BundProjectDetails
from inse.models.cordis_eu_project import CordisEuProject
@@ -505,8 +505,32 @@ async def get_cordis_eu_publications_by_dois(dois: List[str]):
Returns:
_type_: The retrieved publications.
"""
raw_dois = [_get_raw_doi(doi) for doi in dois]
query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}}
query_dois = list({
variant
for doi in dois
for variant in (
_get_raw_doi(doi),
_get_raw_doi(doi).lower(),
_get_raw_doi(doi).upper(),
)
})
query = {
"bool": {
"filter": [
{
"bool": {
"should": [
{"terms": {"doi": query_dois}},
{"terms": {"qaProcessedDoi": query_dois}},
],
"minimum_should_match": 1,
}
}
]
}
}
response = await elasticsearch.search(
query=query,
+142 -1
View File
@@ -134,7 +134,148 @@ async def get_single_bund_project(
return await projects_service.get_single_bund_project(
project_id=id,
)
########
from inse.projects.model import EuCordisProjectSearchPage, EuCordisProjectType
from inse.projects.service import search_eu_cordis_projects_summary_impl
@router.get(
"/eu/search",
summary="Search EU CORDIS projects.",
description="Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and Horizon Europe.",
operation_id="searchEuCordisProjectsSummary",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": EuCordisProjectSearchPage,
},
},
response_model_by_alias=False,
)
async def search_eu_cordis_projects_summary(
author_id: Annotated[
Optional[str],
Query(description="OpenAlex author ID to filter by."),
] = None,
author_ids: Annotated[
Optional[List[str]],
Query(description="Additional OpenAlex author IDs to filter by. All selected authors must match."),
] = None,
organization_ids: Annotated[
Optional[List[str]],
Query(description="CORDIS organisation IDs. All selected organizations must match."),
] = None,
organization_names: Annotated[
Optional[List[str]],
Query(description="CORDIS organization names. All selected organizations must match."),
] = None,
project_types: Annotated[
Optional[List[EuCordisProjectType]],
Query(description="Project types to include: fp7, h2020, heu."),
] = None,
title: Annotated[
Optional[str],
Query(description="Project title/acronym search."),
] = None,
keywords: Annotated[
Optional[List[str]],
Query(description="Raw keywords to search in title/objective/keywords/topics."),
] = None,
topic_ids: Annotated[
Optional[List[str]],
Query(description="OpenAlex topic IDs used for fuzzy topic resolution."),
] = None,
filter_topic_ids: Annotated[
Optional[List[str]],
Query(description="Additional OpenAlex topic IDs used as mandatory filters."),
] = None,
funding_start_years: Annotated[
Optional[List[str]],
Query(description="Funding start years."),
] = None,
funding_end_years: Annotated[
Optional[List[str]],
Query(description="Funding end years."),
] = None,
countries: Annotated[
Optional[List[str]],
Query(description="Organization countries."),
] = None,
framework_programmes: Annotated[
Optional[List[str]],
Query(description="Framework programme filters."),
] = None,
funding_schemes: Annotated[
Optional[List[str]],
Query(description="Funding scheme filters."),
] = None,
statuses: Annotated[
Optional[List[str]],
Query(description="Project status filters."),
] = None,
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
sort_by: Annotated[str, Query(description="Sort field.")] = "title",
sort_direction: Annotated[
str,
Query(description="Sort direction: asc or desc."),
] = "asc",
fuzzy: Annotated[
bool,
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
] = False,
) -> EuCordisProjectSearchPage:
logger.debug(
"Received EU CORDIS search request: author_id=%s, author_ids=%s, "
"organization_ids=%s, organization_names=%s, project_types=%s, "
"title=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, "
"funding_start_years=%s, funding_end_years=%s, countries=%s, "
"framework_programmes=%s, funding_schemes=%s, statuses=%s, "
"page=%s, size=%s, sort_by=%s, sort_direction=%s, fuzzy=%s",
author_id,
author_ids,
organization_ids,
organization_names,
project_types,
title,
keywords,
topic_ids,
filter_topic_ids,
funding_start_years,
funding_end_years,
countries,
framework_programmes,
funding_schemes,
statuses,
page,
size,
sort_by,
sort_direction,
fuzzy,
)
return await search_eu_cordis_projects_summary_impl(
author_id=author_id,
author_ids=author_ids,
organization_ids=organization_ids,
organization_names=organization_names,
project_types=project_types,
title=title,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
statuses=statuses,
page=page,
size=size,
sort_by=sort_by,
sort_direction=sort_direction,
fuzzy=fuzzy,
)
@router.get(
"/eu/{id}",
@@ -209,7 +350,7 @@ async def get_single_eu_cordis_project(
return EuCordisProjectResponse(
success=False,
project_type=None,
data=None,
eu_project_data=None,
error=f"Internal server error: {str(e)}"
)
+96 -1
View File
@@ -385,7 +385,7 @@ async def get_single_eu_cordis_project(
project = await projects_search_client.get_eu_cordis_projects_by_id(project_id)
if not project:
raise NotFoundException(f"EU project with id {project_id} not found")
return None
return project
@@ -414,3 +414,98 @@ async def search_cordis_eu_projects_for_author_id(
return funding_project_page
################
from inse.projects.eu_cordis_projects_client import search_eu_cordis_projects
from inse.projects.model import EuCordisProjectType, EuCordisProjectSearchPage
from inse.works.logic import get_publication_dois_of_author
async def _get_eu_project_ids_for_openalex_authors(
author_ids: List[str],
) -> Optional[List[str]]:
"""
Resolves OpenAlex authors to CORDIS EU project IDs via publication DOIs.
Multiple authors use AND semantics:
project must be connected to publications from every selected author.
"""
author_ids = [author_id for author_id in author_ids if author_id and author_id.strip()]
if not author_ids:
return None
project_sets: List[Set[str]] = []
for author_id in author_ids:
dois = await get_publication_dois_of_author(raw_oa_author_id=author_id)
if not dois:
return []
project_ids = await projects_search_client.get_cordis_eu_project_ids_by_dois(
dois=dois
)
if not project_ids:
return []
project_sets.append(set(project_ids))
if not project_sets:
return None
return list(set.intersection(*project_sets))
async def search_eu_cordis_projects_summary_impl(
page: int,
size: int,
project_types: Optional[List[EuCordisProjectType]] = None,
author_id: Optional[str] = None,
author_ids: Optional[List[str]] = None,
organization_ids: Optional[List[str]] = None,
organization_names: Optional[List[str]] = None,
keywords: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
filter_topic_ids: Optional[List[str]] = None,
title: Optional[str] = None,
funding_start_years: Optional[List[str]] = None,
funding_end_years: Optional[List[str]] = None,
countries: Optional[List[str]] = None,
framework_programmes: Optional[List[str]] = None,
funding_schemes: Optional[List[str]] = None,
statuses: Optional[List[str]] = None,
sort_by: str = "title",
sort_direction: str = "asc",
fuzzy: bool = False,
) -> EuCordisProjectSearchPage:
all_author_ids: List[str] = []
if author_id:
all_author_ids.append(author_id)
all_author_ids.extend(author_ids or [])
author_project_ids = await _get_eu_project_ids_for_openalex_authors(
author_ids=all_author_ids
)
return await search_eu_cordis_projects(
page=page,
size=size,
project_types=project_types,
organization_ids=organization_ids,
organization_names=organization_names,
author_project_ids=author_project_ids,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
statuses=statuses,
sort_by=sort_by,
sort_direction=sort_direction,
fuzzy=fuzzy,
)
@@ -0,0 +1,364 @@
import pytest
from inse.projects import eu_cordis_projects_client as eu_cordis_search_client
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_title():
"""Test searching EU CORDIS projects by title."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
title="Artificial Intelligence",
)
assert res is not None
assert res.total > 0
assert len(res.elements) > 0
for element in res.elements:
assert element.id is not None
assert element.title is not None
assert "artificial" in element.title.lower() or "intelligence" in element.title.lower()
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_keywords():
"""Test searching EU CORDIS projects by keywords."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
keywords=["machine learning", "deep learning"],
)
assert res is not None
assert res.total > 0
assert len(res.elements) > 0
for element in res.elements:
assert element.id is not None
assert element.title is not None
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_framework_programme():
"""Test filtering EU CORDIS projects by framework programme."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
framework_programmes=["H2020"],
)
assert res is not None
assert res.total > 0
assert len(res.elements) > 0
for element in res.elements:
assert element.id is not None
assert element.framework_programme == "H2020"
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_status():
"""Test filtering EU CORDIS projects by status."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
statuses=["SIGNED"],
)
assert res is not None
assert res.total > 0
assert len(res.elements) > 0
for element in res.elements:
assert element.id is not None
assert element.status == "SIGNED"
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_funding_years():
"""Test filtering EU CORDIS projects by funding start years."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
funding_start_years=["2020"],
)
assert res is not None
assert res.total > 0
assert len(res.elements) > 0
for element in res.elements:
assert element.id is not None
assert element.start_date is not None
assert element.start_date.year == 2020
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_country():
"""Test filtering EU CORDIS projects by country."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
countries=["DE"],
)
assert res is not None
assert res.total > 0
assert len(res.elements) > 0
for element in res.elements:
assert element.id is not None
# Verify at least one organization is from Germany
assert any(
org.country == "DE" for org in element.organizations
)
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_organization_name():
"""Test filtering EU CORDIS projects by organization name."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
organization_names=["Max Planck"],
)
assert res is not None
assert res.total > 0
assert len(res.elements) > 0
for element in res.elements:
assert element.id is not None
# Verify at least one organization matches the name
assert any(
"max planck" in org.name.lower() for org in element.organizations
)
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_organization_id():
"""Test filtering EU CORDIS projects by organization ID."""
# Use a known organization ID (e.g., Max Planck Society)
known_org_id = "999990267"
res = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
organization_ids=[known_org_id],
)
assert res is not None
assert res.total > 0
assert len(res.elements) > 0
for element in res.elements:
assert element.id is not None
# Verify the organization is present in the project
assert any(
org.organisation_id == known_org_id for org in element.organizations
)
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_project_type():
"""Test filtering EU CORDIS projects by project type (FP7, H2020, HEU)."""
from inse.projects.model import EuCordisProjectType
# Test FP7 projects
res_fp7 = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
project_types=[EuCordisProjectType.FP7],
)
assert res_fp7 is not None
assert res_fp7.total > 0
assert len(res_fp7.elements) > 0
for element in res_fp7.elements:
assert element.id is not None
assert element.project_type == EuCordisProjectType.FP7
# Test H2020 projects
res_h2020 = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
project_types=[EuCordisProjectType.H2020],
)
assert res_h2020 is not None
assert res_h2020.total > 0
assert len(res_h2020.elements) > 0
for element in res_h2020.elements:
assert element.id is not None
assert element.project_type == EuCordisProjectType.H2020
@pytest.mark.anyio
async def test_search_eu_cordis_projects_with_sorting():
"""Test sorting EU CORDIS projects."""
# Test ascending sort by title
res_asc = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
sort_by="title",
sort_direction="asc",
)
assert res_asc is not None
assert len(res_asc.elements) > 0
titles_asc = [element.title for element in res_asc.elements]
assert titles_asc == sorted(titles_asc)
# Test descending sort by title
res_desc = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
sort_by="title",
sort_direction="desc",
)
assert res_desc is not None
assert len(res_desc.elements) > 0
titles_desc = [element.title for element in res_desc.elements]
assert titles_desc == sorted(titles_desc, reverse=True)
@pytest.mark.anyio
async def test_search_eu_cordis_projects_pagination():
"""Test pagination of EU CORDIS project search results."""
# Get first page
page1 = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=3,
)
assert page1 is not None
assert len(page1.elements) <= 3
assert page1.page == 0
assert page1.size == 3
# Get second page
page2 = await eu_cordis_search_client.search_eu_cordis_projects(
page=1,
size=3,
)
assert page2 is not None
assert len(page2.elements) <= 3
assert page2.page == 1
assert page2.size == 3
# Ensure pages don't overlap
page1_ids = {element.id for element in page1.elements}
page2_ids = {element.id for element in page2.elements}
assert page1_ids.isdisjoint(page2_ids)
@pytest.mark.anyio
async def test_get_enriched_cordis_project_by_id():
"""Test fetching an enriched EU CORDIS project by ID."""
# Use a known project ID (e.g., an H2020 project)
known_id = "101016442" # Example H2020 project ID
project = await eu_cordis_search_client.get_enriched_cordis_project_by_id(known_id)
assert project is not None
assert project.id == known_id
assert project.title is not None
assert project.objective is not None
# Verify enriched data
assert hasattr(project, 'organizations')
assert hasattr(project, 'publications')
assert hasattr(project, 'report_summaries')
assert hasattr(project, 'topics_list')
@pytest.mark.anyio
async def test_get_enriched_cordis_project_by_id_not_found():
"""Test fetching a non-existent EU CORDIS project."""
project = await eu_cordis_search_client.get_enriched_cordis_project_by_id("nonexistent_id")
assert project is None
@pytest.mark.anyio
async def test_get_enriched_cordis_project_by_id_empty():
"""Test fetching with empty project ID."""
project = await eu_cordis_search_client.get_enriched_cordis_project_by_id("")
assert project is None
project = await eu_cordis_search_client.get_enriched_cordis_project_by_id(None)
assert project is None
@pytest.mark.anyio
async def test_get_dois_by_cordis_eu_project_id():
"""Test retrieving DOIs for a CORDIS EU project."""
known_id = "101016442" # Example H2020 project ID
dois = await eu_cordis_search_client.get_dois_by_cordis_eu_project_id(known_id)
assert dois is not None
assert len(dois) > 0
@pytest.mark.anyio
async def test_get_openalex_authors_for_cordis_project_ids():
"""Test retrieving OpenAlex authors for CORDIS project IDs."""
project_ids = ["101016442"] # Example H2020 project ID
authors_by_project = await eu_cordis_search_client.get_openalex_authors_for_cordis_project_ids(project_ids)
assert authors_by_project is not None
assert len(authors_by_project) > 0
for project_id, author_page in authors_by_project.items():
assert project_id in project_ids
assert author_page is not None
if author_page.total > 0:
for author in author_page.elements:
assert author.id is not None
assert author.display_name is not None
@pytest.mark.anyio
async def test_search_eu_cordis_projects_with_multiple_filters():
"""Test combining multiple filters in EU CORDIS project search."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
framework_programmes=["H2020"],
funding_start_years=["2020"],
countries=["US"],
statuses=["SIGNED"],
)
assert res is not None
assert res.total > 0
assert len(res.elements) > 0
for element in res.elements:
assert element.id is not None
assert element.framework_programme == "H2020"
assert element.status == "SIGNED"
assert element.start_date.year == 2020
assert any(org.country == "US" for org in element.organizations)
@pytest.mark.anyio
async def test_search_eu_cordis_projects_empty_results():
"""Test search that should return no results."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
title="ThisProjectDoesNotExistXYZ123",
)
assert res is not None
assert res.total == 0
assert len(res.elements) == 0
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_funding_scheme():
"""Test filtering EU CORDIS projects by funding scheme."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
funding_schemes=["ERC-ADG"], # ERC Advanced Grant
)
assert res is not None
assert res.total > 0
assert len(res.elements) > 0
for element in res.elements:
assert element.id is not None
assert element.funding_scheme == "ERC-ADG"
@pytest.mark.anyio
async def test_search_eu_cordis_projects_with_fuzzy_topic_search():
"""Test fuzzy search with OpenAlex topic IDs."""
# This test requires known OpenAlex topic IDs
topic_ids = ["https://openalex.org/T12345"] # Example topic ID
res = await eu_cordis_search_client.search_eu_cordis_projects(
page=0,
size=5,
topic_ids=topic_ids,
fuzzy=True,
)
assert res is not None
# Note: This may return 0 results if the topic ID doesn't exist
# The important thing is that it doesn't crash
assert isinstance(res.total, int)
assert isinstance(res.elements, list)
+24 -17
View File
@@ -9,11 +9,14 @@ from typing import Any, List, Optional
import pandas as pd
from inse.authors.institution_membership_query import (
current_affiliation_year_cutoff,
)
from inse.company_connections.logic import get_company_counts_by_names
from inse.integrations import elasticsearch
from inse.model import ESCluster
from inse.persons.logic import _classify_career_stage
from inse.persons.query_builder import build_author_filter_clauses
from inse.company_connections.logic import get_company_counts_by_names
from .. import config
from .model import (
AuthorStaticStats,
@@ -39,19 +42,23 @@ logger = logging.getLogger(__name__)
# terms size: gather all matching authors as candidates before the score is
# computed, so a strong citation weight can still lift a low-works author.
CANDIDATE_POOL_SIZE = 10000
UNI_AUTHOR_LIMIT = 20000
INSTITUTION_AUTHOR_LIMIT = 20000
async def _get_author_ids_from_uni(institution_name: str) -> List[str]:
"""Returns the ids of all authors of the given institution.
async def _get_author_ids_from_institution(institution_id: str) -> List[str]:
"""Returns the IDs of active authors of the given institution.
Uses the same author selection as the persons search endpoint (by institution
display name, see ``build_author_filter_clauses``), but scrolls over the whole
result set instead of paginating so that *all* matching author ids are returned.
Uses the same author selection as the persons search endpoint, but scrolls
over the result set instead of paginating it.
"""
query = {
"bool": {
"filter": build_author_filter_clauses(institution_name=institution_name),
"filter": build_author_filter_clauses(
institution_id=institution_id,
year_filter_enabled=True,
filter_mode="from",
filter_year=current_affiliation_year_cutoff(),
),
},
}
@@ -67,7 +74,7 @@ async def _get_author_ids_from_uni(institution_name: str) -> List[str]:
author_id = source.get("id") or hit.get("_id", "")
if author_id:
author_ids.append(author_id)
if len(author_ids) >= UNI_AUTHOR_LIMIT:
if len(author_ids) >= INSTITUTION_AUTHOR_LIMIT:
break
return author_ids
@@ -376,7 +383,7 @@ async def topic_stats_for_authors(
)
results = []
for author_bucket in author_buckets:
to_work = author_bucket.get("to_work", {})
avg_value = to_work.get("avg_percentile", {}).get("value")
@@ -690,7 +697,7 @@ async def static_stats_for_authors(
)
results = []
for author_id in author_ids:
name = names_by_id.get(author_id, "")
results.append(
@@ -837,7 +844,7 @@ def _min_max_normalize(values: pd.Series) -> pd.Series:
# if all values are the same, return a series of 1.0 to avoid division by zero.
if maximum == minimum:
return pd.Series([1.0] * len(values))
return (values - minimum) / (maximum - minimum)
@@ -1091,7 +1098,7 @@ async def _filter_author_ids_by_career_stage(
async def rank_authors_by_keywords(
keywords: List[str],
operator: KeywordOperator,
institution_name: str,
institution_id: str,
weights: RankingWeights,
career_stages: List[CareerStage],
publication_types: List[PublicationType],
@@ -1106,11 +1113,11 @@ async def rank_authors_by_keywords(
"""
query_start_time = time()
author_ids = await _get_author_ids_from_uni(institution_name)
author_ids = await _get_author_ids_from_institution(institution_id)
if not author_ids:
return []
if career_stages:
author_ids = await _filter_author_ids_by_career_stage(author_ids, career_stages)
-4
View File
@@ -114,10 +114,6 @@ class KeywordToAuthorRequest(BaseModel):
description="What the 'keywords' values match against: 'keyword' (OpenAlex "
"keyword display names) or 'topic' (OpenAlex topic display names). Defaults to 'keyword'.",
)
institution_name: str = Field(
default="University of Duisburg-Essen",
description="The selected institution display name. (Default Uni-Due)",
)
weights: RankingWeights = Field(
description="Weights for the ranking metrics. Required.",
)
+28 -14
View File
@@ -1,8 +1,10 @@
import logging
from typing import List
from typing import Annotated, List
from fastapi import APIRouter
from fastapi import APIRouter, HTTPException, status
from inse.auth.model import AccessTokenMetadata
from inse.auth.service import CurrentUserAccessTokenPayloadDep
from inse.tags import Tags
from . import logic
from .model import (
@@ -24,28 +26,40 @@ router = APIRouter(
# Author ranking
@router.post("/rank-author", response_model=List[RankedAuthor])
async def rank_author(request: KeywordToAuthorRequest):
async def rank_author(
request: KeywordToAuthorRequest,
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
):
institution_id = access_token_metadata.effective_institution_id
if not institution_id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="No OpenAlex institution is assigned to the current organization.",
)
logger.info(
"rank-author keywords=%s operator=%s filter_type=%s institution_name=%s career_stages=%s "
"rank-author keywords=%s operator=%s filter_type=%s institution_id=%s career_stages=%s "
"publication_types=%s timespan=%s",
request.keywords,
request.operator,
request.filter_type,
request.institution_name,
institution_id,
request.career_stages,
request.publication_types,
request.timespan,
)
return await logic.rank_authors_by_keywords(
request.keywords,
request.operator,
request.institution_name,
request.weights,
request.career_stages,
request.publication_types,
request.timespan,
request.company_status,
request.filter_type,
keywords=request.keywords,
operator=request.operator,
institution_id=institution_id,
weights=request.weights,
career_stages=request.career_stages,
publication_types=request.publication_types,
timespan=request.timespan,
company_status=request.company_status,
filter_type=request.filter_type,
)
# Compare authors table 1 (topic stats)
@@ -942,9 +942,6 @@ async def get_top_topics_for_entity(
except Exception as e:
logger.error("Failed to query top project topics for entity: %s", e)
return {"items": []}
# Default fallback institution: University of Duisburg-Essen
DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514"
DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
DEFAULT_TOP_TOPICS_SIZE = 20
@@ -995,18 +992,34 @@ async def get_top_topics_for_entity(
from inse.patents.search_client import PatentSearchClient
patent_client = PatentSearchClient()
short_id = entity_id.split("/")[-1]
full_id = f"https://openalex.org/{short_id}"
aliases = [short_id, entity_id]
aliases = [short_id, entity_id, full_id]
if entity_type == "institution":
try:
from inse.institutions.institutions_search_client import InstitutionsSearchClient
client = InstitutionsSearchClient()
resolved_aliases = await client.get_institution_aliases_by_oa_institution_id(short_id)
if resolved_aliases:
aliases = list(resolved_aliases)
aliases.extend(resolved_aliases)
inst_res = await elasticsearch.search(
index=str(ESIndex.OPENALEX_INSTITUTIONS),
query={"terms": {"id": [full_id, short_id]}},
size=1,
source=["display_name"],
cluster="nes"
)
hits = inst_res.get("hits", {}).get("hits", [])
if hits:
d_name = hits[0]["_source"].get("display_name")
if d_name:
aliases.append(d_name)
except Exception as e:
logger.warning("Failed to resolve institution aliases in get_top_topics_for_entity: %s", e)
aliases = list(set([a for a in aliases if a]))
include_german = True
if entity_type == "country" and entity_id.strip().upper() != "DE":
include_german = False
@@ -1100,22 +1113,35 @@ async def get_top_topics_for_entity(
for topic_idx, p_ids in project_ids_by_index.items():
if not p_ids:
continue
for i in range(0, len(p_ids), 500):
chunk = p_ids[i:i+500]
for i in range(0, len(p_ids), 1000):
chunk = p_ids[i:i+1000]
payload = {
"query": {"terms": {"project_id": chunk}},
"size": 10000,
"_source": ["topic_matches"]
"query": {
"bool": {
"should": [
{"terms": {"project_id": chunk}},
{"terms": {"project_id.keyword": chunk}}
],
"minimum_should_match": 1
}
},
"size": 0,
"aggs": {
"topics": {
"terms": {
"field": "topic_matches.topic_display_name.keyword",
"size": 100
}
}
}
}
try:
res = await patent_client._search(index=topic_idx, payload=payload)
hits = res.get("hits", {}).get("hits", [])
for hit in hits:
matches = hit.get("_source", {}).get("topic_matches", [])
for m in matches:
t_name = m.get("topic_display_name")
if t_name:
topic_counts[t_name] = topic_counts.get(t_name, 0) + 1
buckets = res.get("aggregations", {}).get("topics", {}).get("buckets", [])
for b in buckets:
t_name = b["key"]
cnt = b["doc_count"]
topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt
except Exception as e:
logger.warning("Failed to aggregate topics from %s: %s", topic_idx, e)
@@ -1134,6 +1160,37 @@ async def get_top_topics_for_entity(
logger.error("Failed to query top project topics for entity: %s", e)
return {"items": []}
if search_type == "news":
try:
res = await elasticsearch.search(
index="aktuell_postproc",
body={
"query": {"match_all": {}},
"size": 0,
"aggs": {
"top_topics": {
"terms": {
"field": "topics.display_name.keyword",
"size": DEFAULT_TOP_TOPICS_SIZE
}
}
}
},
cluster="inse"
)
buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", [])
items = [{"name": b["key"], "count": b["doc_count"]} for b in buckets]
total_hits = res.get("hits", {}).get("total", {})
total_val = total_hits.get("value", 0) if isinstance(total_hits, dict) else int(total_hits or 0)
sum_top = sum(b["count"] for b in items)
other_count = max(0, total_val - sum_top)
if other_count > 0:
items.append({"name": "Andere Themen", "count": other_count})
return {"items": items}
except Exception as e:
logger.error("Failed to query top news topics for entity: %s", e)
return {"items": []}
# Default fallback: openalex-works* query for publications/authors
# 1. Normalize ID and prepare filter clause
if entity_type == "institution":
@@ -1448,33 +1448,67 @@ class NewsTrendStrategy(TrendStrategy):
end_year = datetime.datetime.now().year - 1
years_range = list(range(start_year, end_year + 1))
search_terms = keywords if keywords else topics
# Each series will map all topic keys to its data.
# Each series entity represents one topic/keyword.
accumulated_data = {
f"news_topic_{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
for t in topics
}
# Query UDE news postprocessed index to get matching news IDs
AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"]
STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"}
# Query UDE news postprocessed index to get matching news IDs without 10k capping
async def fetch_news_ids_for_term(idx: int, t_name: str) -> List[str]:
term = search_terms[idx] if idx < len(search_terms) else t_name
if fuzzy:
term = t_name
es_query = {"match": {"topics.display_name": term}}
else:
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
es_query = {"match": {"keywords": term}}
news_ids = set()
try:
res = await elasticsearch.search(
async for hit in elasticsearch.scan(
index="aktuell_postproc",
query={"match": {"keywords": term}},
size=10000,
query=es_query,
source=["news_id"],
cluster="inse"
)
return [
hit["_source"]["news_id"]
for hit in res.get("hits", {}).get("hits", [])
if hit.get("_source", {}).get("news_id")
]
):
nid = hit.get("_source", {}).get("news_id")
if nid:
news_ids.add(nid)
except Exception as e:
logger.warning("Failed to search UDE news postproc keywords: %s", e)
return []
logger.warning("Failed to scan UDE news postproc: %s", e)
# If non-fuzzy keyword search, also search article content fields in 'aktuell' index
if not fuzzy and term and term.lower() not in STOP_WORDS and len(term.strip()) > 1:
try:
content_query = {
"query_string": {
"query": term,
"fields": AKTUELLES_SEARCH_FIELDS,
"default_operator": "AND"
}
}
async for hit in elasticsearch.scan(
index="aktuell",
query=content_query,
source=["news_id"],
cluster="inse"
):
nid = hit.get("_id") or hit.get("_source", {}).get("news_id")
if nid:
news_ids.add(nid)
except Exception as e:
logger.warning("Failed to scan UDE news content in aktuell: %s", e)
return list(news_ids)
# Find all matching news IDs concurrently
matching_ids_list = await asyncio.gather(*[
@@ -1484,36 +1518,36 @@ class NewsTrendStrategy(TrendStrategy):
async def count_by_year(t_name: str, news_ids: List[str]):
if not news_ids:
return
try:
# Query aktuell index using matching news IDs and aggregate by date_year
res = await elasticsearch.search(
index="aktuell",
body={
"query": {"bool": {"filter": [
{"ids": {"values": news_ids}},
{"range": {"date_year": {"gte": start_year, "lte": end_year}}}
]}},
"aggs": {
"by_year": {
"terms": {"field": "date_year", "size": len(years_range) * 2}
entity_key = f"news_topic_{t_name}"
# Batch news_ids in chunks of 2000 to avoid ES query clause limits
for i in range(0, len(news_ids), 2000):
chunk = news_ids[i:i+2000]
try:
res = await elasticsearch.search(
index="aktuell",
body={
"query": {"bool": {"filter": [
{"ids": {"values": chunk}},
{"range": {"date_year": {"gte": start_year, "lte": end_year}}}
]}},
"aggs": {
"by_year": {
"terms": {"field": "date_year", "size": len(years_range) * 2}
}
}
}
},
size=0,
cluster="inse"
)
buckets = res.get("aggregations", {}).get("by_year", {}).get("buckets", [])
for b in buckets:
yr = int(b.get("key"))
count = int(b.get("doc_count", 0))
if yr in years_range:
entity_key = f"news_topic_{t_name}"
# Set this count for all topic keys in this topic's series
for top in topics:
accumulated_data[entity_key][top] = dict(accumulated_data[entity_key][top])
accumulated_data[entity_key][top][yr] = (count, 1)
except Exception as e:
logger.warning("Failed to aggregate news years from ES: %s", e)
},
size=0,
cluster="inse"
)
buckets = res.get("aggregations", {}).get("by_year", {}).get("buckets", [])
for b in buckets:
yr = int(b.get("key"))
count = int(b.get("doc_count", 0))
if yr in years_range:
prev_count, _ = accumulated_data[entity_key][t_name][yr]
accumulated_data[entity_key][t_name][yr] = (prev_count + count, 1)
except Exception as e:
logger.warning("Failed to aggregate news years from ES for chunk: %s", e)
# Aggregate news publication years concurrently
await asyncio.gather(*[
@@ -1526,21 +1560,27 @@ class NewsTrendStrategy(TrendStrategy):
for t_name in topics:
entity_key = f"news_topic_{t_name}"
topic_data_map = {}
for topic in topics:
yearly_data_items = []
lookup = normalized_lookup.get((entity_key, topic), {})
norm_vals = lookup.get("normalized", [0.0] * len(years_range))
cum_vals = lookup.get("cumulative", [0.0] * len(years_range))
for idx, yr in enumerate(years_range):
count, _ = accumulated_data[entity_key][topic][yr]
yearly_data_items.append(TopicYearlyData(
year=yr,
raw=count,
normalized=norm_vals[idx],
cumulative=cum_vals[idx],
institutions_count=1
))
# Extract yearly data items for t_name from accumulated_data[entity_key][t_name]
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))
yearly_data_items = []
for idx, yr in enumerate(years_range):
count, _ = accumulated_data[entity_key][t_name][yr]
yearly_data_items.append(TopicYearlyData(
year=yr,
raw=count,
normalized=norm_vals[idx],
cumulative=cum_vals[idx],
institutions_count=1
))
# Populate topic_data_map for ALL topic keys in topics with t_name's yearly items.
# This ensures uni-trend-chart accessing topic_data[selectedTopic] for any selected topic
# always gets t_name's true data items for series t_name.
for topic in topics:
topic_data_map[topic] = yearly_data_items
series_list.append(TrendSeries(
+11 -7
View File
@@ -22,7 +22,7 @@ from inse.models.openalex.topics_by_year import TopicsByYear
from inse.models.openalex.topics_by_time import TopicsByTime
from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
from .search_client import OpenAlexWorksSearchClient
from inse.model import ESCluster, ESIndex
logger = logging.getLogger(__name__)
TOPIC_DETAIL_SOURCE_FIELDS = [
@@ -183,7 +183,8 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
try:
response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
index=ESIndex.OPENALEX_WORKS_WILDCARD,
cluster=ESCluster.NES,
body=body,
)
except ElasticsearchException as exc:
@@ -273,7 +274,8 @@ async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
try:
response = await elasticsearch.search(
index="openalex-topics",
index=ESIndex.OPENALEX_TOPICS,
cluster=ESCluster.NES,
query={"terms": {"id": topic_ids}},
source=TOPIC_DETAIL_SOURCE_FIELDS,
size=len(topic_ids),
@@ -698,7 +700,8 @@ async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dic
try:
response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
index=ESIndex.OPENALEX_WORKS_WILDCARD,
cluster=ESCluster.NES,
body=body,
)
except ElasticsearchException as exc:
@@ -766,7 +769,8 @@ async def _get_timeline_topic_counts_from_es(
try:
response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
index=ESIndex.OPENALEX_WORKS_WILDCARD,
cluster=ESCluster.NES,
body=body,
)
except ElasticsearchException as exc:
@@ -1015,11 +1019,11 @@ async def get_publication_dois_of_author(
try:
response = await elasticsearch.search(
index="openalex-works",
index=ESIndex.OPENALEX_WORKS_WILDCARD,
source=["doi"],
size=10000,
query=query,
cluster="nes",
cluster=ESCluster.NES,
)
except ElasticsearchException as exc:
logger.exception("Request for publication DOIs of author failed.")
+3
View File
@@ -149,6 +149,9 @@ class WorkClassification(BaseModel):
publication_year: Optional[int] = Field(
default=None, description="The publication year of the work."
)
publication_type: Optional[str] = Field(
default=None, description="The OpenAlex publication type of the work."
)
authors: List[WorkClassificationAuthor] = Field(
default_factory=list, description="The authors of the work."
)
+16 -11
View File
@@ -1,8 +1,13 @@
import logging
from typing import Dict, List, Optional
import inse.authors.v2.service as author_service
from fastapi import Query
from inse.auth.model import AccessTokenMetadata
from inse.exceptions import ElasticsearchNotFoundException
from inse.integrations import elasticsearch
from inse.model import ESIndex, SortDirection, ESCluster
from inse.model import ESCluster, ESIndex, SortDirection
from inse.models.openalex.work import Work
from inse.works.v2.model import (
PrimaryCategoryYearAggregation,
PrimaryCategoryYearAggregationPage,
@@ -11,10 +16,6 @@ from inse.works.v2.model import (
WorkPageV2,
WorkSortBy,
)
from inse.models.openalex.work import Work
from inse.auth.model import AccessTokenMetadata
import inse.authors.v2.service as author_service
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
@@ -357,7 +358,7 @@ async def get_works_by_keywords(
sort = [{"title.keyword": sort_order.value}]
else:
sort = [{sort_by.value: sort_order.value}]
print(f"Final query:", must)
print("Final query:", must)
# search
response = await elasticsearch.search(
index=ESIndex.OPENALEX_WORKS_WILDCARD,
@@ -698,6 +699,7 @@ async def _get_work_classifications_by_work_ids(
"doi",
"title",
"publication_year",
"publication_type",
"authors",
"institutions",
"topics",
@@ -755,11 +757,14 @@ async def _get_work_classification_by_work_id(
Optional[WorkClassification]: The work classification if found, otherwise None.
"""
response = await elasticsearch.get(
ESIndex.WORK_CLASSIFICATIONS,
doc_id=raw_oa_work_id,
source=source,
)
try:
response = await elasticsearch.get(
ESIndex.WORK_CLASSIFICATIONS,
doc_id=raw_oa_work_id,
source=source,
)
except ElasticsearchNotFoundException:
return None
_source = response.get("_source")
if _source:
@@ -22,6 +22,7 @@ api/patents.service.ts
api/personNetwork.service.ts
api/persons.service.ts
api/projects.service.ts
api/ranking.service.ts
api/topics.service.ts
api/topicsV2.service.ts
api/universityRankings.service.ts
@@ -40,11 +41,15 @@ model/author.ts
model/authorAffiliationsInner.ts
model/authorCountsByYearInner.ts
model/authorIds.ts
model/authorMetricsRequest.ts
model/authorNetworkNode.ts
model/authorPage.ts
model/authorParsedLongestName.ts
model/authorPositionCount.ts
model/authorStaticStats.ts
model/authorSummaryStats.ts
model/authorTopicProfile.ts
model/authorTopicStats.ts
model/authorsFilterProperties.ts
model/authorsListResponse.ts
model/authorship.ts
@@ -63,11 +68,13 @@ model/bundProject.ts
model/bundProjectDetails.ts
model/bundProjectPage.ts
model/careerMetrics.ts
model/careerStage.ts
model/collaborationNetwork.ts
model/collaborationNetworkEdge.ts
model/collaborationNetworkNodeType.ts
model/companyConnection.ts
model/companyConnectionsResponse.ts
model/companyStatusFilter.ts
model/cordisEuProject.ts
model/cordisEuProjectPage.ts
model/costUsd.ts
@@ -90,7 +97,15 @@ model/dfgPersonSummaryPage.ts
model/dfgProjectDetails.ts
model/dfgProjectPage.ts
model/dfgProjectSummary.ts
model/euCordisEurosciVocSummary.ts
model/euCordisOrganizationSelectorPage.ts
model/euCordisOrganizationSelectorSummary.ts
model/euCordisOrganizationSummary.ts
model/euCordisProjectResponse.ts
model/euCordisProjectSearchPage.ts
model/euCordisProjectSummary.ts
model/euCordisProjectType.ts
model/euCordisTopicSummary.ts
model/euOrganizationProjectSummary.ts
model/euOrganizationProjectSummaryPage.ts
model/euProjectData.ts
@@ -100,6 +115,7 @@ model/extractedKeywordsResponse.ts
model/fileUpload.ts
model/filterInformation.ts
model/filterProperties.ts
model/filterType.ts
model/fp7EurosciVoc.ts
model/fp7LegalBasis.ts
model/fp7Organization.ts
@@ -151,11 +167,13 @@ model/ipcClassification.ts
model/keywordEntry.ts
model/keywordEntryWithTopic.ts
model/keywordEvidence.ts
model/keywordOperator.ts
model/keywordPatentLevel.ts
model/keywordPatentMappingStatus.ts
model/keywordPatentMatch.ts
model/keywordPatentSearchDiagnostics.ts
model/keywordPatentSearchItem.ts
model/keywordToAuthorRequest.ts
model/keywordTopicMatch.ts
model/keywords.ts
model/keywordsRequest.ts
@@ -195,11 +213,17 @@ model/projectsFilteringProperties.ts
model/projectsSortBy.ts
model/publicationDetailByFunder.ts
model/publicationIdsByAuthorPosition.ts
model/publicationType.ts
model/publicationsByAuthorResponse.ts
model/rankedAuthor.ts
model/rankingResponse.ts
model/rankingWeights.ts
model/rebuildResponse.ts
model/score.ts
model/selectedAuthorsRequest.ts
model/sortDirection.ts
model/subfieldShare.ts
model/timespan.ts
model/tokenType.ts
model/topAuthor.ts
model/topAuthorStatistics.ts
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -9,87 +9,244 @@
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { CompanyConnectionsAvailability } from '../model/companyConnectionsAvailability';
// @ts-ignore
import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class CompanyConnectionsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
/**
* Check whether company connections are available for an author.
* @endpoint get /api/inse-service/authors/{author_id}/company-connections/availability
* @param authorId
* @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 getCompanyConnectionsAvailability(
authorId: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<CompanyConnectionsAvailability>;
public getCompanyConnectionsAvailability(
authorId: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<CompanyConnectionsAvailability>>;
public getCompanyConnectionsAvailability(
authorId: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<CompanyConnectionsAvailability>>;
public getCompanyConnectionsAvailability(
authorId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getCompanyConnectionsAvailability.',
);
}
/**
* Get possible company connections by OpenAlex author ID.
* @endpoint get /api/inse-service/authors/{author_id}/company-connections
* @param authorId
* @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 getCompanyConnectionsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CompanyConnectionsResponse>;
public getCompanyConnectionsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CompanyConnectionsResponse>>;
public getCompanyConnectionsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CompanyConnectionsResponse>>;
public getCompanyConnectionsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getCompanyConnectionsByAuthor.');
}
let localVarHeaders = this.defaultHeaders;
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/company-connections`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CompanyConnectionsResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/company-connections/availability`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CompanyConnectionsAvailability>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Get possible company connections by OpenAlex author ID.
* @endpoint get /api/inse-service/authors/{author_id}/company-connections
* @param authorId
* @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 getCompanyConnectionsByAuthor(
authorId: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<CompanyConnectionsResponse>;
public getCompanyConnectionsByAuthor(
authorId: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<CompanyConnectionsResponse>>;
public getCompanyConnectionsByAuthor(
authorId: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<CompanyConnectionsResponse>>;
public getCompanyConnectionsByAuthor(
authorId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getCompanyConnectionsByAuthor.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/company-connections`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CompanyConnectionsResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
File diff suppressed because it is too large Load Diff
+585
View File
@@ -33,8 +33,14 @@ import { DfgProjectDetails } from '../model/dfgProjectDetails';
// @ts-ignore
import { DfgProjectPage } from '../model/dfgProjectPage';
// @ts-ignore
import { EuCordisOrganizationSelectorPage } from '../model/euCordisOrganizationSelectorPage';
// @ts-ignore
import { EuCordisProjectResponse } from '../model/euCordisProjectResponse';
// @ts-ignore
import { EuCordisProjectSearchPage } from '../model/euCordisProjectSearchPage';
// @ts-ignore
import { EuCordisProjectType } from '../model/euCordisProjectType';
// @ts-ignore
import { EuOrganizationProjectSummaryPage } from '../model/euOrganizationProjectSummaryPage';
// @ts-ignore
import { FundingProjectPage } from '../model/fundingProjectPage';
@@ -331,6 +337,238 @@ export class ProjectsService extends BaseService {
);
}
/**
* Returns EU CORDIS organizations based on a search term.
* @endpoint get /api/eu/organizations/autocomplete/selector
* @param query Search term for organization autocomplete.
* @param page
* @param size
* @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 getEuOrganizationAutocompleteForSelector(
query?: string,
page?: number,
size?: number,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<EuCordisOrganizationSelectorPage>;
public getEuOrganizationAutocompleteForSelector(
query?: string,
page?: number,
size?: number,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<EuCordisOrganizationSelectorPage>>;
public getEuOrganizationAutocompleteForSelector(
query?: string,
page?: number,
size?: number,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<EuCordisOrganizationSelectorPage>>;
public getEuOrganizationAutocompleteForSelector(
query?: string,
page?: number,
size?: number,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>query,
'query',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>page,
'page',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>size,
'size',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/eu/organizations/autocomplete/selector`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<EuCordisOrganizationSelectorPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Returns EU CORDIS organizations by organisation IDs.
* @endpoint get /api/eu/organizations/ids
* @param organizationIds CORDIS organisation IDs to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getEuOrganizationsByIds(
organizationIds?: Array<string>,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<EuCordisOrganizationSelectorPage>;
public getEuOrganizationsByIds(
organizationIds?: Array<string>,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<EuCordisOrganizationSelectorPage>>;
public getEuOrganizationsByIds(
organizationIds?: Array<string>,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<EuCordisOrganizationSelectorPage>>;
public getEuOrganizationsByIds(
organizationIds?: Array<string>,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (organizationIds) {
organizationIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'organization_ids',
);
});
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/eu/organizations/ids`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<EuCordisOrganizationSelectorPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Get EU projects for an author.
* Returns a list of EU projects associated with the specified author ID.
@@ -1201,6 +1439,353 @@ export class ProjectsService extends BaseService {
);
}
/**
* Search EU CORDIS projects.
* Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and Horizon Europe.
* @endpoint get /api/projects/eu/search
* @param authorId OpenAlex author ID to filter by.
* @param authorIds Additional OpenAlex author IDs to filter by. All selected authors must match.
* @param organizationIds CORDIS organisation IDs. All selected organizations must match.
* @param organizationNames CORDIS organization names. All selected organizations must match.
* @param projectTypes Project types to include: fp7, h2020, heu.
* @param title Project title/acronym search.
* @param keywords Raw keywords to search in title/objective/keywords/topics.
* @param topicIds OpenAlex topic IDs used for fuzzy topic resolution.
* @param filterTopicIds Additional OpenAlex topic IDs used as mandatory filters.
* @param fundingStartYears Funding start years.
* @param fundingEndYears Funding end years.
* @param countries Organization countries.
* @param frameworkProgrammes Framework programme filters.
* @param fundingSchemes Funding scheme filters.
* @param statuses Project status filters.
* @param page The page number.
* @param size The page size.
* @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 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 searchEuCordisProjectsSummary(
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 searchEuCordisProjectsSummary(
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 searchEuCordisProjectsSummary(
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 searchEuCordisProjectsSummary(
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,
<any>authorId,
'author_id',
);
if (authorIds) {
authorIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'author_ids',
);
});
}
if (organizationIds) {
organizationIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'organization_ids',
);
});
}
if (organizationNames) {
organizationNames.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'organization_names',
);
});
}
if (projectTypes) {
projectTypes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'project_types',
);
});
}
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>title,
'title',
);
if (keywords) {
keywords.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'keywords',
);
});
}
if (topicIds) {
topicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'topic_ids',
);
});
}
if (filterTopicIds) {
filterTopicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'filter_topic_ids',
);
});
}
if (fundingStartYears) {
fundingStartYears.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'funding_start_years',
);
});
}
if (fundingEndYears) {
fundingEndYears.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'funding_end_years',
);
});
}
if (countries) {
countries.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'countries',
);
});
}
if (frameworkProgrammes) {
frameworkProgrammes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'framework_programmes',
);
});
}
if (fundingSchemes) {
fundingSchemes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'funding_schemes',
);
});
}
if (statuses) {
statuses.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'statuses',
);
});
}
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>page,
'page',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>size,
'size',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>sortBy,
'sort_by',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>sortDirection,
'sort_direction',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>fuzzy,
'fuzzy',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/projects/eu/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<EuCordisProjectSearchPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Search projects across all funders.
* Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter.
+20
View File
@@ -0,0 +1,20 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export const CareerStage = {
Unknown: 'unknown',
Early: 'Early',
Emerging: 'Emerging',
Established: 'Established',
Senior: 'Senior'
} as const;
export type CareerStage = typeof CareerStage[keyof typeof CareerStage];
@@ -0,0 +1,13 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface CompanyConnectionsAvailability {
available: boolean;
}
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -9,17 +9,12 @@
*/
import { CompanyConnection } from './companyConnection';
export interface CompanyConnectionsResponse {
author_id: string;
display_name?: string | null;
is_ude_author: boolean;
institution_scope?: string | null;
matching_institutions?: Array<string>;
matching_method?: string | null;
company_count: number;
has_more_results: boolean;
common_name_warning: boolean;
connections?: Array<CompanyConnection>;
export interface CompanyConnectionsResponse {
author_id: string;
display_name?: string | null;
matching_method?: string | null;
company_count: number;
has_more_results: boolean;
common_name_warning: boolean;
connections?: Array<CompanyConnection>;
}
@@ -0,0 +1,18 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export const CompanyStatusFilter = {
All: 'all',
Active: 'active',
Deleted: 'deleted'
} as const;
export type CompanyStatusFilter = typeof CompanyStatusFilter[keyof typeof CompanyStatusFilter];
+27 -25
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -12,28 +12,30 @@ import { DFGProjectFachgebieteInner } from './dFGProjectFachgebieteInner';
import { Topic } from './topic';
import { DfgPersonSummary } from './dfgPersonSummary';
export interface DfgProjectSummary {
/**
* The unique identifier of the DFG project.
*/
id: string;
link?: string | null;
title?: string | null;
professional_classification?: string | null;
funding_start?: string | null;
funding_end?: string | null;
/**
* Institutions associated with the project.
*/
institutions?: Array<DfgInstitutionSummary>;
/**
* The names of the persons involved in the DFG project.
*/
names?: Array<string>;
/**
* The persons involved in the DFG project.
*/
persons?: Array<DfgPersonSummary>;
subject_classifications?: Array<DFGProjectFachgebieteInner> | null;
topics?: Array<Topic> | null;
export interface DfgProjectSummary {
/**
* The unique identifier of the DFG project.
*/
id: string;
link?: string | null;
title?: string | null;
professional_classification?: string | null;
funding_start?: string | null;
funding_end?: string | null;
/**
* Institutions associated with the project.
*/
institutions?: Array<DfgInstitutionSummary>;
/**
* The names of the persons involved in the DFG project.
*/
names?: Array<string>;
/**
* The persons involved in the DFG project.
*/
persons?: Array<DfgPersonSummary>;
subject_classifications?: Array<DFGProjectFachgebieteInner> | null;
topics?: Array<Topic> | null;
}
@@ -0,0 +1,20 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface EuCordisEurosciVocSummary {
id?: string | null;
project_id?: string | null;
code?: string | null;
title?: string | null;
description?: string | null;
path?: string | null;
}
@@ -0,0 +1,28 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { EuCordisOrganizationSelectorSummary } from './euCordisOrganizationSelectorSummary';
export interface EuCordisOrganizationSelectorPage {
/**
* The current page number.
*/
page?: number;
/**
* The requested page size.
*/
size?: number;
/**
* The total number of items.
*/
total?: number;
elements?: Array<EuCordisOrganizationSelectorSummary>;
}
@@ -0,0 +1,25 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { EuCordisProjectType } from './euCordisProjectType';
export interface EuCordisOrganizationSelectorSummary {
id?: string | null;
organisation_id?: string | null;
name?: string | null;
short_name?: string | null;
country?: string | null;
city?: string | null;
project_type?: EuCordisProjectType | null;
}
export namespace EuCordisOrganizationSelectorSummary {
}
@@ -0,0 +1,25 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface EuCordisOrganizationSummary {
id?: string | null;
organisation_id?: string | null;
name?: string | null;
short_name?: string | null;
country?: string | null;
city?: string | null;
role?: string | null;
activity_type?: string | null;
project_id?: string | null;
ec_contribution?: number | null;
total_cost?: number | null;
}
@@ -0,0 +1,31 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { EuCordisProjectSummary } from './euCordisProjectSummary';
export interface EuCordisProjectSearchPage {
/**
* The current page number.
*/
page?: number;
/**
* The requested page size.
*/
size?: number;
/**
* The total number of items.
*/
total?: number;
/**
* The EU CORDIS project summaries on this page.
*/
elements?: Array<EuCordisProjectSummary>;
}
@@ -0,0 +1,44 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { EuCordisTopicSummary } from './euCordisTopicSummary';
import { AuthorPage } from './authorPage';
import { EuCordisEurosciVocSummary } from './euCordisEurosciVocSummary';
import { Topic } from './topic';
import { EuCordisOrganizationSummary } from './euCordisOrganizationSummary';
import { EuCordisProjectType } from './euCordisProjectType';
export interface EuCordisProjectSummary {
id: string;
project_type: EuCordisProjectType;
title?: string | null;
acronym?: string | null;
objective?: string | null;
keywords?: string | null;
framework_programme?: string | null;
funding_scheme?: string | null;
status?: string | null;
start_date?: string | null;
end_date?: string | null;
ec_max_contribution?: number | null;
total_cost?: number | null;
authors?: AuthorPage | null;
organizations?: Array<EuCordisOrganizationSummary>;
cordis_topics?: Array<EuCordisTopicSummary>;
eurosci_voc?: Array<EuCordisEurosciVocSummary>;
/**
* Mapped OpenAlex topics.
*/
topics?: Array<Topic>;
}
export namespace EuCordisProjectSummary {
}
@@ -0,0 +1,18 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export const EuCordisProjectType = {
Fp7: 'fp7',
H2020: 'h2020',
Heu: 'heu'
} as const;
export type EuCordisProjectType = typeof EuCordisProjectType[keyof typeof EuCordisProjectType];
@@ -0,0 +1,18 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface EuCordisTopicSummary {
id?: string | null;
project_id?: string | null;
title?: string | null;
topic?: string | null;
}
+17
View File
@@ -0,0 +1,17 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export const FilterType = {
Keyword: 'keyword',
Topic: 'topic'
} as const;
export type FilterType = typeof FilterType[keyof typeof FilterType];
@@ -0,0 +1,17 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export const KeywordOperator = {
And: 'and',
Or: 'or'
} as const;
export type KeywordOperator = typeof KeywordOperator[keyof typeof KeywordOperator];
@@ -26,10 +26,6 @@ export interface KeywordToAuthorRequest {
* What the \'keywords\' values match against: \'keyword\' or \'topic\'. Defaults to \'keyword\'.
*/
filter_type?: string;
/**
* The selected institution display name. (Default Uni-Due)
*/
institution_name?: string;
/**
* Optional filter: only keep authors in one of these career stages.
*/
+9
View File
@@ -34,6 +34,7 @@ export * from './collaborationNetwork';
export * from './collaborationNetworkEdge';
export * from './collaborationNetworkNodeType';
export * from './companyConnection';
export * from './companyConnectionsAvailability';
export * from './companyConnectionsResponse';
export * from './cordisEuProject';
export * from './cordisEuProjectPage';
@@ -57,7 +58,15 @@ export * from './dfgPersonSummaryPage';
export * from './dfgProjectDetails';
export * from './dfgProjectPage';
export * from './dfgProjectSummary';
export * from './euCordisEurosciVocSummary';
export * from './euCordisOrganizationSelectorPage';
export * from './euCordisOrganizationSelectorSummary';
export * from './euCordisOrganizationSummary';
export * from './euCordisProjectResponse';
export * from './euCordisProjectSearchPage';
export * from './euCordisProjectSummary';
export * from './euCordisProjectType';
export * from './euCordisTopicSummary';
export * from './euOrganizationProjectSummary';
export * from './euOrganizationProjectSummaryPage';
export * from './euProjectData';
@@ -0,0 +1,39 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export const PublicationType = {
Article: 'article',
Other: 'other',
Dataset: 'dataset',
BookChapter: 'book-chapter',
Book: 'book',
Dissertation: 'dissertation',
Preprint: 'preprint',
Paratext: 'paratext',
Libguides: 'libguides',
Review: 'review',
Letter: 'letter',
ReferenceEntry: 'reference-entry',
Editorial: 'editorial',
PeerReview: 'peer-review',
Report: 'report',
Standard: 'standard',
Erratum: 'erratum',
Retraction: 'retraction',
SupplementaryMaterials: 'supplementary-materials',
BookSection: 'book-section',
Database: 'database',
Software: 'software',
ReportComponent: 'report-component',
Grant: 'grant'
} as const;
export type PublicationType = typeof PublicationType[keyof typeof PublicationType];
@@ -0,0 +1,42 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Timespan } from './timespan';
import { FilterType } from './filterType';
import { KeywordOperator } from './keywordOperator';
import { PublicationType } from './publicationType';
export interface SelectedAuthorsRequest {
/**
* OpenAlex IDs of the authors to rank.
*/
author_ids: Array<string>;
/**
* One or more keywords defining the topic.
*/
keywords: Array<string>;
/**
* How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'.
*/
operator?: KeywordOperator;
/**
* What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic ids). Defaults to \'keyword\'.
*/
filter_type?: FilterType;
/**
* Optional filter: only count works of these publication types. Empty = no filter.
*/
publication_types?: Array<PublicationType>;
timespan?: Timespan | null;
}
export namespace SelectedAuthorsRequest {
}
+22
View File
@@ -0,0 +1,22 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface SubfieldShare {
/**
* The subfield display name.
*/
name: string;
/**
* Number of works whose primary topic belongs to this subfield.
*/
count: number;
}
+22
View File
@@ -0,0 +1,22 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface Timespan {
/**
* Start year (inclusive).
*/
from: number;
/**
* End year (inclusive).
*/
to: number;
}
+100 -27
View File
@@ -41,11 +41,16 @@ import { SearchResultsStateService } from './modules/keywords-search/search-resu
import { roleGuard } from './shared/guards/role.guard';
import { UserRole } from './api';
import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver';
import { euCordisProjectsResolver } from './resolvers/eu-cordis-projects.resolver';
import { selectedAuthorsResolver } from './resolvers/selected-authors.resolver';
import { workClassificationResolver } from './resolvers/work-classification.resolver';
import { selectedDfgAuthorsResolver } from './resolvers/selected-dfg-authors.resolver';
import { selectedDfgInstitutionsResolver } from './resolvers/selected-dfg-institutions.resolver';
import { primaryCategoryYearAggregationPageResolver } from './resolvers/primary-category-year-aggregation-page.resolver';
import { selectedEuInstitutionsResolver } from './resolvers/selected-eu-institutions.resolver';
import { uniTrendResolver } from './resolvers/uni-trend.resolver';
import { EuProjectsComponent } from './shared/ui/eu-projects/eu-projects.component';
import { DfgProjectsComponent } from './shared/ui/dfg-projects/dfg-projects.component';
export const routes: Routes = [
{
path: '',
@@ -142,6 +147,7 @@ export const routes: Routes = [
'query',
'page',
'pageSize',
'institutionId',
'institutionName',
'sortBy',
'sortOrder',
@@ -188,19 +194,41 @@ export const routes: Routes = [
{
path: 'projects',
component: KeywordsToProjectsResultsComponent,
runGuardsAndResolvers: 'always',
resolve: {
dfgProjectPage: dfgProjectsResolver,
personCordisEuProjectPage: personCordisEuProjectPageResolver,
selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver,
selectedDfgAuthorsPage: selectedDfgAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
selectedEuInstitutionsPage: selectedInstitutionsResolver,
selectedEuAuthorsPage: selectedAuthorsResolver,
},
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'dfg',
},
{
path: 'dfg',
component: DfgProjectsComponent,
resolve: {
dfgProjectPage: dfgProjectsResolver,
selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver,
selectedDfgAuthorsPage: selectedDfgAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
{
path: 'eu',
component: EuProjectsComponent,
resolve: {
euCordisProjectPage: euCordisProjectsResolver,
selectedEuInstitutionsPage: selectedEuInstitutionsResolver,
selectedEuAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
],
},
{ path: 'patents', component: KeywordsToPatentsResultsComponent },
{
@@ -218,7 +246,30 @@ export const routes: Routes = [
},
},
{ path: 'news', component: KeywordsToNewsResultsComponent },
{ path: 'trends', component: UniTrendParentComponent },
{
path: 'trends',
component: UniTrendParentComponent,
resolve: {
trendData: uniTrendResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = [
'search_type',
'topic',
'topics',
'keyword',
'keywords',
'institutions',
'countries',
'regions',
'authors',
'fuzzy',
];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
},
],
},
{
@@ -417,19 +468,41 @@ export const routes: Routes = [
import('./modules/person-projects/person-projects.component').then(
(mod) => mod.PersonProjectsComponent,
),
resolve: {
dfgProjectPage: dfgProjectsResolver,
personCordisEuProjectPage: personCordisEuProjectPageResolver,
selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver,
selectedDfgAuthorsPage: selectedDfgAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
selectedEuInstitutionsPage: selectedInstitutionsResolver,
selectedEuAuthorsPage: selectedAuthorsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON,
},
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'dfg',
},
{
path: 'dfg',
component: DfgProjectsComponent,
resolve: {
dfgProjectPage: dfgProjectsResolver,
selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver,
selectedDfgAuthorsPage: selectedDfgAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON,
},
},
{
path: 'eu',
component: EuProjectsComponent,
resolve: {
euCordisProjectPage: euCordisProjectsResolver,
selectedEuInstitutionsPage: selectedEuInstitutionsResolver,
selectedEuAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON,
},
},
],
},
{
path: 'publications',
@@ -26,7 +26,7 @@
<a
class="statistics-card"
routerLink="/persons"
[queryParams]="{ institutionName: organizationName() }"
[queryParams]="personListQueryParams()"
[attr.aria-label]="'Personen von ' + organizationName() + ' anzeigen'">
<div class="statistics-icon statistics-icon--persons">
<mat-icon>groups</mat-icon>
@@ -13,6 +13,10 @@ import {
TopAuthorsWorksPeriod,
TopicHeatmap,
} from './dashboard-statistics.service';
import {
activeInstitutionPersonListQueryParams,
PersonListQueryParams,
} from '../../shared/person-list-query-params';
type DashboardStatisticKey =
| 'publications'
| 'persons'
@@ -161,6 +165,13 @@ export class DashboardComponent implements OnInit {
);
}
personListQueryParams(): PersonListQueryParams {
return activeInstitutionPersonListQueryParams(
this.institutionRouteId(),
this.organizationName(),
);
}
setTopicTreemapPeriod(period: TopicTreemapPeriod): void {
if (period === this.topicTreemapPeriod && period !== 'custom') return;
@@ -962,8 +962,8 @@ export class KeywordsSearchComponent {
const selected = this.parseKeywordList(queryParams.get('selected'));
const source = queryParams.get('source') ?? '';
const view = queryParams.get('view') ?? 'llm';
const legend = queryParams.get('legend') ?? 'on';
const legendExpanded = queryParams.get('legendExpanded') ?? 'off';
const legend = queryParams.get('legend') === 'true';
const legendExpanded = queryParams.get('legendExpanded') === 'true';
const fuzzy = queryParams.get('fuzzy') === 'true';
this.isRestoringState = true;
this.form.patchValue(
@@ -975,8 +975,8 @@ export class KeywordsSearchComponent {
{ emitEvent: false },
);
this.keywordView.set(view as KeywordView);
this.subfieldLegendVisible.set(legend === 'on');
this.subfieldLegendExpanded.set(legendExpanded === 'on');
this.subfieldLegendVisible.set(legend);
this.subfieldLegendExpanded.set(legendExpanded);
this.extractionSource.set(source as InputMode);
this.topicMappingSearch.set(fuzzy);
this.restoreStateFromSession();
@@ -1036,8 +1036,8 @@ export class KeywordsSearchComponent {
url: this.toNullableParam(this.form.controls.urlInput.value),
text: this.toNullableParam(this.form.controls.textInput.value),
view: this.keywordView(),
legend: this.subfieldLegendVisible() ? 'on' : 'off',
legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off',
legend: this.subfieldLegendVisible() ? 'true' : 'false',
legendExpanded: this.subfieldLegendExpanded() ? 'true' : 'false',
broad: this.serializeKeywords(
this.getKeywordLabels(this.broadKeywords()),
),
@@ -3,34 +3,22 @@
<h5 style="font-weight: bold">Projekte</h5>
<p>Übersicht der durchgeführten Projekte.</p>
</div>
<mat-card appearance="outlined">
<mat-card-content>
<mat-tab-group
[selectedIndex]="selectedTabIndex()"
(selectedIndexChange)="onTabChange($event)">
<mat-tab label="DFG">
<app-project-filters
[selectedInstitutionsPage]="selectedDfgInstitutionsPage()"
[selectedAuthorsPage]="selectedDfgAuthorsPage()"
[selectedTopicsPage]="selectedTopicsPage()"
[showFundingStartFilter]="true"
[showTopicFilter]="fuzzySearch()"
[showFundingEndFilter]="true"
[showAuthorFilter]="true"
[showInstitutionFilter]="true" />
<app-dfg-project-table
[page]="dfgProjectPage()"
[authorFilterEnabled]="true"
[topicFilterEnabled]="fuzzySearch()"
[institutionFilterEnabled]="true" />
</mat-tab>
<mat-tab label="EU">
<!-- <app-project-filters
[selectedInstitutionsPage]="selectedEuInstitutionsPage()"
[selectedAuthorsPage]="selectedEuAuthorsPage()" /> -->
<app-eu-project-table [page]="personCordisEuProjectPage()" />
</mat-tab>
</mat-tab-group>
</mat-card-content>
</mat-card>
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
@for (route of childRoutes; track route.path) {
<a
matTabLink
[routerLink]="[route.path]"
queryParamsHandling="merge"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive">
{{ route.label }}
</a>
}
</nav>
<mat-tab-nav-panel #resultTabPanel>
<router-outlet />
</mat-tab-nav-panel>
</div>
@@ -1,73 +1,45 @@
import { Component, computed, input, signal } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import { DfgInstitutionSummaryPage } from '../../../../api/model/dfgInstitutionSummaryPage';
import {
CordisEuProjectPage,
DfgProjectPage,
AuthorPage,
InstitutionPageV2,
DfgPersonSummaryPage,
TopicPageV2,
} from '../../../../api';
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 { ProjectFilterComponent } from '../../../../shared/ui/project-filters/project-filters.component';
import { DfgProjectTableComponent } from '../../../../shared/ui/dfg-project-table/dfg-project-table.component';
import { EuProjectTableComponent } from '../../../../shared/ui/eu-project-table/eu-project-table.component';
import { projectQueryParamKeys } from '../../../../resolvers/dfg-projects.resolver';
import { euProjectQueryParamKeys } from '../../../../resolvers/person-cordis-eu-project-page.resolver';
import { OnInit, computed } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
const PROJECT_TAB_QUERY_PARAM_KEY = 'project_type';
import { SearchResultsStateService } from '../search-results-state.service';
@Component({
selector: 'app-projects-results',
imports: [
MatCardModule,
MatTabsModule,
ProjectFilterComponent,
DfgProjectTableComponent,
EuProjectTableComponent,
RouterLink,
RouterLinkActive,
RouterOutlet,
],
templateUrl: './projects-results.component.html',
styleUrl: './projects-results.component.scss',
})
export class KeywordsToProjectsResultsComponent {
dfgProjectPage = input.required<DfgProjectPage>();
personCordisEuProjectPage = input.required<CordisEuProjectPage>();
selectedDfgInstitutionsPage = input.required<DfgInstitutionSummaryPage>();
selectedDfgAuthorsPage = input.required<DfgPersonSummaryPage>();
selectedTopicsPage = input.required<TopicPageV2>();
selectedEuInstitutionsPage = input.required<InstitutionPageV2>();
selectedEuAuthorsPage = input.required<AuthorPage>();
readonly dfgQueryParamKeys = projectQueryParamKeys;
readonly euQueryParamKeys = euProjectQueryParamKeys;
constructor(
private readonly router: Router,
private readonly activatedRoute: ActivatedRoute,
) {}
loading = signal<boolean>(false);
queryParamMap = toSignal(this.activatedRoute.queryParamMap, {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
readonly fuzzySearch = computed(
() => this.queryParamMap().get('fuzzy') === 'true',
);
selectedTabIndex = computed(() => {
const type = this.queryParamMap().get(PROJECT_TAB_QUERY_PARAM_KEY);
return type === 'eu' ? 1 : 0;
});
onTabChange(index: number): void {
const type = index === 1 ? 'eu' : 'dfg';
this.router.navigate([], {
queryParams: { [PROJECT_TAB_QUERY_PARAM_KEY]: type },
queryParamsHandling: 'merge',
});
}
readonly childRoutes = [
{
path: 'dfg',
label: 'DFG-Projekte',
},
{
path: 'eu',
label: 'EU-Projekte',
},
];
}
@@ -69,7 +69,8 @@
keywords: state.payload()?.keywords?.join(','),
fuzzy: state.payload()?.options?.fuzzy,
topics: state.payload()?.options?.fuzzy ? state.topicIds() : null,
}">
}"
queryParamsHandling="replace">
<mat-icon>{{ route.icon }}</mat-icon>
{{ route.label }}
</a>
@@ -217,6 +217,7 @@ export class KeywordsSearchResultsComponent {
const queryParams = {
fuzzy: fuzzy,
topics: fuzzy ? this.state.topicIds() : null,
topicId: null,
};
this.router.navigate([], {
@@ -68,10 +68,7 @@
[matTooltip]="inst.display_name || ''"
[matTooltipDisabled]="loading()"
matTooltipPosition="above"
(click)="
institutionClick.emit(inst.display_name || '');
$event.stopPropagation()
">
(click)="institutionClick.emit(inst); $event.stopPropagation()">
<mat-icon
style="
font-size: 12px;
@@ -29,11 +29,11 @@ export class PersonCardComponent {
isBookmarked = input<boolean>(false);
loading = input<boolean>(false);
selectedTopics = input<Set<string>>(new Set<string>());
activeInstitutionName = input<string>('');
activeInstitutionId = input<string>('');
bookmarkToggle = output<CustomAuthor>();
topicClick = output<string>();
institutionClick = output<string>();
institutionClick = output<DehydratedInstitution>();
initials = computed<string>(() => {
const name = this.person().display_name;
@@ -83,11 +83,9 @@ export class PersonCardComponent {
}
isInstitutionActive = computed<boolean>(() => {
const active = this.activeInstitutionName().trim().toLowerCase();
const active = this.normalizeInstitutionId(this.activeInstitutionId());
if (!active) return false;
return (
(this.institution()?.display_name ?? '').trim().toLowerCase() === active
);
return this.normalizeInstitutionId(this.institution()?.id ?? '') === active;
});
topics = computed<WorkTopic[]>(() => {
@@ -170,6 +168,10 @@ export class PersonCardComponent {
this.topicClick.emit(topicName);
}
private normalizeInstitutionId(id: string): string {
return id.replace('https://openalex.org/', '').trim().toUpperCase();
}
getCareerStageTooltip(careerStage: string): string {
const activeYears = this.person().career_metrics?.active_years ?? '-';
@@ -7,11 +7,6 @@
<div class="state state-error">
Verbindungen zu Unternehmen konnten nicht geladen werden.
</div>
} @else if (data && !data.is_ude_author) {
<section class="empty-state">
<h2>Keine Unternehmenssuche verfügbar</h2>
<p>Für diese Person wird aktuell keine Suche nach Unternehmen angezeigt.</p>
</section>
} @else if (data && connections.length === 0) {
<section class="empty-state">
<h2>Keine Treffer im Handelsregister</h2>
@@ -1,12 +1,14 @@
import { CommonModule, LocationStrategy } from '@angular/common';
import {
Component,
DestroyRef,
ElementRef,
OnInit,
QueryList,
ViewChildren,
inject,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
@@ -22,6 +24,7 @@ import {
CompanyConnectionsService,
MatchedOfficer,
} from '../../api';
import { PersonDataResolved } from '../../resolvers/person.resolver';
interface RoleLegendItem {
role: string;
@@ -47,6 +50,7 @@ interface RoleLegendItem {
export class PersonCompanyConnectionsComponent implements OnInit {
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly destroyRef = inject(DestroyRef);
private readonly locationStrategy = inject(LocationStrategy);
private readonly companyConnectionsApi = inject(CompanyConnectionsService);
@@ -115,17 +119,31 @@ export class PersonCompanyConnectionsComponent implements OnInit {
}
ngOnInit(): void {
this.route.parent?.paramMap.subscribe((params) => {
const authorId = params.get('id');
const parentRoute = this.route.parent;
const authorId = parentRoute?.snapshot.paramMap.get('id');
const resolved = parentRoute?.snapshot.data['personData'] as
| PersonDataResolved
| undefined;
if (!authorId) {
this.loading = false;
this.error = true;
return;
}
if (!authorId || !resolved) {
this.loading = false;
this.error = true;
return;
}
this.loadCompanyConnections(authorId);
});
resolved.companyConnectionsAvailable$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((available) => {
if (!available) {
void this.router.navigate(['overview'], {
relativeTo: parentRoute,
replaceUrl: true,
});
return;
}
this.loadCompanyConnections(authorId);
});
}
getPrimaryOfficer(connection: CompanyConnection): MatchedOfficer | null {
@@ -329,7 +347,7 @@ export class PersonCompanyConnectionsComponent implements OnInit {
): EChartsOption | null {
const connections = response.connections ?? [];
if (!response.is_ude_author || connections.length === 0) {
if (connections.length === 0) {
return null;
}
@@ -59,7 +59,7 @@
<mat-icon>close</mat-icon>
</button>
</span>
} @else if (filter.category === 'institutionName') {
} @else if (filter.category === 'institutionId') {
<span [skText]="loading" class="active-institution-filter">
<span class="filter-institution-chip">
<mat-icon class="filter-institution-chip__icon"
@@ -82,7 +82,7 @@
filter.countryCode.toUpperCase()
}}</span>
}
@if (findInstitutionPageIdByName(filter.value)) {
@if (filter.value) {
<mat-icon
class="institution-open-icon"
(click)="openInstitutionPage(filter.value, $event)"
@@ -165,7 +165,7 @@
[person]="person"
[isBookmarked]="isBookmarked(person)"
[selectedTopics]="selectedTopics()"
[activeInstitutionName]="appliedInstitutionName"
[activeInstitutionId]="appliedInstitutionId"
(bookmarkToggle)="toggleBookmark($event)"
(topicClick)="onCardTopicClick($event)"
(institutionClick)="onCardInstitutionClick($event)">
@@ -246,9 +246,10 @@
(keyup.enter)="applySidebarFilters()" />
<mat-autocomplete
#auto="matAutocomplete"
[displayWith]="displayInstitution"
(optionSelected)="onInstitutionSelected($event)">
@for (institution of institutionOptions(); track institution.id) {
<mat-option [value]="institution.display_name">
<mat-option [value]="institution">
<span>{{ institution.display_name }}</span>
@if (institution.hint) {
<small>{{ institution.hint }}</small>
@@ -259,7 +260,7 @@
!institutionLookupLoading() &&
institutionOptions().length === 0 &&
institutionControl.value &&
institutionControl.value.trim().length >= 2
displayInstitution(institutionControl.value).trim().length >= 2
) {
<mat-option disabled>Keine Institution gefunden</mat-option>
}
@@ -284,11 +285,11 @@
<mat-checkbox
[formControl]="yearFilterEnabledControl"
(change)="applySidebarFilters()"
aria-label="Zusammenarbeit nach Jahr filtern">
aria-label="Institutionszugehörigkeit nach Jahr filtern">
<span
style="font-size: 12px; font-weight: 500; color: var(--sg-text)"
>Zusammenarbeit nach Jahr filtern</span
>
style="font-size: 12px; font-weight: 500; color: var(--sg-text)">
Institutionszugehörigkeit nach Jahr filtern
</span>
</mat-checkbox>
@if (yearFilterEnabledControl.value) {
@@ -305,16 +306,16 @@
(change)="applySidebarFilters()"
style="display: flex; gap: 16px"
aria-label="Modus für Jahresfilter">
<mat-radio-button value="in"
><span style="font-size: 12px; color: var(--sg-text)"
>Genau in</span
></mat-radio-button
>
<mat-radio-button value="from"
><span style="font-size: 12px; color: var(--sg-text)"
>Seit</span
></mat-radio-button
>
<mat-radio-button value="in">
<span style="font-size: 12px; color: var(--sg-text)">
Genau im Jahr
</span>
</mat-radio-button>
<mat-radio-button value="from">
<span style="font-size: 12px; color: var(--sg-text)">
Seit
</span>
</mat-radio-button>
</mat-radio-group>
<mat-form-field
@@ -86,6 +86,8 @@ export class PersonListComponent {
currentPage = 1;
readonly institutionOptions = signal<any[]>([]);
readonly institutionLookupLoading = signal<boolean>(false);
readonly selectedInstitution = signal<DehydratedInstitution | null>(null);
readonly defaultMembershipYear = new Date().getUTCFullYear() - 2;
defaultOrderValue = 'desc';
@@ -95,10 +97,11 @@ export class PersonListComponent {
readonly topicSearchType = signal<'hybrid' | 'semantic'>('hybrid');
// Applied filter states (reflecting actual URL query params)
appliedInstitutionName = '';
appliedYearFilterEnabled = false;
appliedFilterMode: 'in' | 'from' = 'from';
appliedFilterYear = new Date().getFullYear() - 1;
public appliedInstitutionId = '';
public appliedInstitutionName = '';
public appliedYearFilterEnabled = false;
public appliedFilterMode: 'in' | 'from' = 'from';
public appliedFilterYear = this.defaultMembershipYear;
// Forms
sortValueControl = new FormControl(null, {
@@ -109,12 +112,14 @@ export class PersonListComponent {
{ nonNullable: true },
);
topicSearchControl = new FormControl('', { nonNullable: true });
institutionControl = new FormControl('', { nonNullable: true });
institutionControl = new FormControl<string | DehydratedInstitution>('', {
nonNullable: true,
});
yearFilterEnabledControl = new FormControl(false, { nonNullable: true });
filterModeControl = new FormControl<'in' | 'from'>('from', {
nonNullable: true,
});
filterYearControl = new FormControl<number>(new Date().getFullYear() - 1, {
filterYearControl = new FormControl<number>(this.defaultMembershipYear, {
nonNullable: true,
validators: [
Validators.min(1900),
@@ -134,11 +139,14 @@ export class PersonListComponent {
this.setupInstitutionAutocomplete();
// Enable/disable the year filter checkbox based on the presence of an institution value
this.updateYearFilterState(this.institutionControl.value);
this.updateYearFilterState(this.selectedInstitution());
this.institutionControl.valueChanges
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((val) => {
this.updateYearFilterState(val);
if (typeof val === 'string') {
this.selectedInstitution.set(null);
this.updateYearFilterState(null);
}
});
this.route.queryParams
@@ -149,17 +157,19 @@ export class PersonListComponent {
const pageSize = params['pageSize']
? Number.parseInt(params['pageSize'], 10)
: 10;
const institutionId = params['institutionId'] || '';
const institutionName = params['institutionName'] || '';
const sortBy = params['sortBy'] || null;
const sortOrder = params['sortOrder'] || this.defaultOrderValue;
const yearFilterEnabled = params['yearFilterEnabled'] === 'true';
const yearFilterEnabled =
!!institutionId && params['yearFilterEnabled'] !== 'false';
const filterMode =
params['filterMode'] === 'in' || params['filterMode'] === 'from'
? params['filterMode']
: 'from';
const filterYear = params['filterYear']
? Number.parseInt(params['filterYear'], 10)
: new Date().getFullYear() - 1;
: this.defaultMembershipYear;
const topicSearch = params['topicSearch'] || '';
const topicSearchType =
params['topicSearchType'] === 'semantic' ? 'semantic' : 'hybrid';
@@ -181,12 +191,23 @@ export class PersonListComponent {
if (this.searchValue() !== query) {
this.searchValue.set(query || null);
}
if (this.institutionControl.value !== institutionName) {
this.institutionControl.setValue(institutionName, {
const institution =
institutionId && institutionName
? ({
id: institutionId,
display_name: institutionName,
} satisfies DehydratedInstitution)
: null;
this.selectedInstitution.set(institution);
if (
this.displayInstitution(this.institutionControl.value) !==
institutionName
) {
this.institutionControl.setValue(institution ?? '', {
emitEvent: false,
});
this.updateYearFilterState(institutionName);
}
this.updateYearFilterState(institution);
if (this.yearFilterEnabledControl.value !== yearFilterEnabled) {
this.yearFilterEnabledControl.setValue(yearFilterEnabled);
}
@@ -202,6 +223,7 @@ export class PersonListComponent {
this.topicSearchType.set(topicSearchType);
// Update applied filter states
this.appliedInstitutionId = institutionId;
this.appliedInstitutionName = institutionName;
this.appliedYearFilterEnabled = yearFilterEnabled;
this.appliedFilterMode = filterMode;
@@ -311,15 +333,18 @@ export class PersonListComponent {
this.selectedTopics().forEach((t) => {
list.push({ category: 'topic', value: t, label: `Thema: ${t}` });
});
if (this.appliedInstitutionName) {
if (this.appliedInstitutionId && this.appliedInstitutionName) {
let label = `Institution: ${this.appliedInstitutionName}`;
if (this.appliedYearFilterEnabled) {
const modeLabel = this.appliedFilterMode === 'in' ? 'in' : 'from';
label += ` (${modeLabel} ${this.appliedFilterYear})`;
const periodLabel =
this.appliedFilterMode === 'in'
? `im Jahr ${this.appliedFilterYear}`
: `seit ${this.appliedFilterYear}`;
label += ` (${periodLabel})`;
}
list.push({
category: 'institutionName',
value: this.appliedInstitutionName,
category: 'institutionId',
value: this.appliedInstitutionId,
label: label,
countryCode: this.findInstitutionCountryCode(
this.appliedInstitutionName,
@@ -333,36 +358,11 @@ export class PersonListComponent {
return filter.label.replace(/^Institution:\s*/, '');
}
findInstitutionPageIdByName(institutionName: string): string | null {
const normalized = institutionName.trim().toLowerCase();
if (!normalized) {
return null;
}
for (const person of this.persons) {
const candidates: Array<DehydratedInstitution | undefined> = [
...(person.last_known_institutions ?? []),
...(person.affiliations ?? []).map((a) => a.institution ?? undefined),
];
for (const inst of candidates) {
if (
inst?.id &&
(inst.display_name ?? '').trim().toLowerCase() === normalized
) {
return inst.id.split('/').pop() ?? null;
}
}
}
return null;
}
openInstitutionPage(institutionName: string, event: Event): void {
openInstitutionPage(institutionId: string, event: Event): void {
event.stopPropagation();
event.preventDefault();
const id = this.findInstitutionPageIdByName(institutionName);
const id = institutionId.split('/').pop();
if (!id) return;
void this.router.navigate(['/institution', id]);
@@ -400,13 +400,14 @@ export class PersonListComponent {
next.delete(filter.value);
return next;
});
} else if (filter.category === 'institutionName') {
} else if (filter.category === 'institutionId') {
this.institutionControl.setValue('', { emitEvent: false });
this.updateYearFilterState('');
this.selectedInstitution.set(null);
this.updateYearFilterState(null);
this.institutionOptions.set([]);
this.yearFilterEnabledControl.setValue(false);
this.filterModeControl.setValue('from');
this.filterYearControl.setValue(new Date().getFullYear() - 1);
this.filterYearControl.setValue(this.defaultMembershipYear);
}
this.applySidebarFilters();
}
@@ -453,11 +454,12 @@ export class PersonListComponent {
clearAllFilters(): void {
this.selectedTopics.set(new Set<string>());
this.institutionControl.setValue('', { emitEvent: false });
this.updateYearFilterState('');
this.selectedInstitution.set(null);
this.updateYearFilterState(null);
this.institutionOptions.set([]);
this.yearFilterEnabledControl.setValue(false);
this.filterModeControl.setValue('from');
this.filterYearControl.setValue(new Date().getFullYear() - 1);
this.filterYearControl.setValue(this.defaultMembershipYear);
this.applySidebarFilters();
}
@@ -465,6 +467,7 @@ export class PersonListComponent {
if (this.yearFilterEnabledControl.value && this.filterYearControl.invalid) {
return;
}
const institution = this.selectedInstitution();
this.router.navigate([], {
queryParams: {
topic: this.selectedTopics().size
@@ -473,22 +476,23 @@ export class PersonListComponent {
topicSearch: this.topicSearchControl.value || null,
topicSearchType:
this.topicSearchType() === 'semantic' ? 'semantic' : null,
institutionName: this.institutionControl.value || null,
institutionId: institution?.id || null,
institutionName: institution?.display_name || null,
sortBy: this.sortValueControl.value || null,
sortOrder: this.sortOrderControl.value || null,
yearFilterEnabled:
this.institutionControl.value && this.yearFilterEnabledControl.value
yearFilterEnabled: institution
? this.yearFilterEnabledControl.value
? 'true'
: null,
: 'false'
: null,
filterMode:
this.institutionControl.value && this.yearFilterEnabledControl.value
institution && this.yearFilterEnabledControl.value
? this.filterModeControl.value
: null,
filterYear:
this.institutionControl.value && this.yearFilterEnabledControl.value
institution && this.yearFilterEnabledControl.value
? this.filterYearControl.value
: null,
strict: null,
page: 1,
},
queryParamsHandling: 'merge',
@@ -535,9 +539,14 @@ export class PersonListComponent {
this.toggleTopic(topic);
}
onCardInstitutionClick(institutionName: string): void {
this.institutionControl.setValue(institutionName, { emitEvent: false });
this.updateYearFilterState(institutionName);
onCardInstitutionClick(institution: DehydratedInstitution): void {
if (!institution.id || !institution.display_name) {
return;
}
this.selectedInstitution.set(institution);
this.institutionControl.setValue(institution, { emitEvent: false });
this.resetActiveMembershipFilter();
this.updateYearFilterState(institution);
this.institutionOptions.set([]);
this.applySidebarFilters();
}
@@ -604,8 +613,8 @@ export class PersonListComponent {
.pipe(map((response) => response.results ?? []));
}
updateYearFilterState(val: string): void {
if (!val) {
updateYearFilterState(institution: DehydratedInstitution | null): void {
if (!institution?.id) {
this.yearFilterEnabledControl.disable();
this.yearFilterEnabledControl.setValue(false);
} else {
@@ -615,19 +624,40 @@ export class PersonListComponent {
clearInstitutionFilter(): void {
this.institutionControl.setValue('', { emitEvent: false });
this.updateYearFilterState('');
this.selectedInstitution.set(null);
this.updateYearFilterState(null);
this.institutionOptions.set([]);
this.applySidebarFilters();
}
onInstitutionSelected(event: MatAutocompleteSelectedEvent): void {
const val = event.option.value;
this.institutionControl.setValue(val, { emitEvent: false });
this.updateYearFilterState(val);
const institution = event.option.value as DehydratedInstitution;
if (!institution.id || !institution.display_name) {
return;
}
this.selectedInstitution.set(institution);
this.institutionControl.setValue(institution, { emitEvent: false });
this.resetActiveMembershipFilter();
this.updateYearFilterState(institution);
this.institutionOptions.set([]);
this.applySidebarFilters();
}
public readonly displayInstitution = (
institution: string | DehydratedInstitution | null,
): string =>
typeof institution === 'string'
? institution
: (institution?.display_name ?? '');
private resetActiveMembershipFilter(): void {
this.yearFilterEnabledControl.setValue(true, { emitEvent: false });
this.filterModeControl.setValue('from', { emitEvent: false });
this.filterYearControl.setValue(this.defaultMembershipYear, {
emitEvent: false,
});
}
private parseQueryParamArray(val: any): string[] {
if (!val) return [];
if (Array.isArray(val)) return val;
@@ -3,34 +3,22 @@
<h5 style="font-weight: bold">Projekte</h5>
<p>Übersicht der durchgeführten Projekte.</p>
</div>
<mat-card appearance="outlined">
<mat-card-content>
<mat-tab-group
[selectedIndex]="selectedTabIndex()"
(selectedIndexChange)="onTabChange($event)">
<mat-tab label="DFG">
<app-project-filters
[selectedInstitutionsPage]="selectedDfgInstitutionsPage()"
[selectedAuthorsPage]="selectedDfgAuthorsPage()"
[selectedTopicsPage]="selectedTopicsPage()"
[showFundingStartFilter]="true"
[showTopicFilter]="true"
[showFundingEndFilter]="true"
[showAuthorFilter]="true"
[showInstitutionFilter]="true" />
<app-dfg-project-table
[page]="dfgProjectPage()"
[authorFilterEnabled]="true"
[topicFilterEnabled]="true"
[institutionFilterEnabled]="true" />
</mat-tab>
<mat-tab label="EU">
<!-- <app-project-filters
[selectedInstitutionsPage]="selectedEuInstitutionsPage()"
[selectedAuthorsPage]="selectedEuAuthorsPage()" /> -->
<app-eu-project-table [page]="personCordisEuProjectPage()" />
</mat-tab>
</mat-tab-group>
</mat-card-content>
</mat-card>
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
@for (route of childRoutes; track route.path) {
<a
matTabLink
[routerLink]="[route.path]"
queryParamsHandling="merge"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive">
{{ route.label }}
</a>
}
</nav>
<mat-tab-nav-panel #resultTabPanel>
<router-outlet />
</mat-tab-nav-panel>
</div>
@@ -1,69 +1,31 @@
import { Component, computed, input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import { DfgInstitutionSummaryPage } from '../../api/model/dfgInstitutionSummaryPage';
import {
CordisEuProjectPage,
DfgProjectPage,
AuthorPage,
InstitutionPageV2,
TopicPageV2,
DfgPersonSummaryPage,
} from '../../api';
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 { ProjectFilterComponent } from '../../shared/ui/project-filters/project-filters.component';
import { DfgProjectTableComponent } from '../../shared/ui/dfg-project-table/dfg-project-table.component';
import { EuProjectTableComponent } from '../../shared/ui/eu-project-table/eu-project-table.component';
import { projectQueryParamKeys } from '../../resolvers/dfg-projects.resolver';
import { euProjectQueryParamKeys } from '../../resolvers/person-cordis-eu-project-page.resolver';
const PROJECT_TAB_QUERY_PARAM_KEY = 'project_type';
@Component({
selector: 'app-person-projects',
standalone: true,
imports: [
MatCardModule,
MatTabsModule,
ProjectFilterComponent,
DfgProjectTableComponent,
EuProjectTableComponent,
RouterOutlet,
RouterLink,
RouterLinkActive,
],
templateUrl: './person-projects.component.html',
styleUrl: './person-projects.component.scss',
})
export class PersonProjectsComponent {
dfgProjectPage = input.required<DfgProjectPage>();
personCordisEuProjectPage = input.required<CordisEuProjectPage>();
selectedDfgInstitutionsPage = input.required<DfgInstitutionSummaryPage>();
selectedDfgAuthorsPage = input.required<DfgPersonSummaryPage>();
selectedEuInstitutionsPage = input.required<InstitutionPageV2>();
selectedEuAuthorsPage = input.required<AuthorPage>();
selectedTopicsPage = input.required<TopicPageV2>();
readonly dfgQueryParamKeys = projectQueryParamKeys;
readonly euQueryParamKeys = euProjectQueryParamKeys;
constructor(
private readonly router: Router,
private readonly activatedRoute: ActivatedRoute,
) {}
queryParamMap = toSignal(this.activatedRoute.queryParamMap, {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
selectedTabIndex = computed(() => {
const type = this.queryParamMap().get(PROJECT_TAB_QUERY_PARAM_KEY);
return type === 'eu' ? 1 : 0;
});
onTabChange(index: number): void {
const type = index === 1 ? 'eu' : 'dfg';
this.router.navigate([], {
queryParams: { [PROJECT_TAB_QUERY_PARAM_KEY]: type },
queryParamsHandling: 'merge',
});
}
readonly childRoutes = [
{
path: 'dfg',
label: 'DFG-Projekte',
},
{
path: 'eu',
label: 'EU-Projekte',
},
];
}
@@ -149,7 +149,7 @@
(tagClick)="onInterestingTagClick($event)"></app-person-interesting>
</section>
<nav class="person-tabs" mat-tab-nav-bar [tabPanel]="tabPanel">
@for (link of links; track link.path) {
@for (link of links(); track link.path) {
<a
mat-tab-link
[routerLink]="link.path"
@@ -118,6 +118,19 @@ export class PersonComponent {
{ initialValue: null },
);
readonly companyConnectionsAvailable = toSignal(
this.activatedRoute.data.pipe(
switchMap((data) => {
const resolved = data['personData'] as PersonDataResolved | undefined;
if (!resolved) {
return of(false);
}
return resolved.companyConnectionsAvailable$;
}),
),
{ initialValue: false },
);
toggleBookmark(): void {
const person = this.person();
if (!person) return;
@@ -250,7 +263,7 @@ export class PersonComponent {
{ initialValue: [] },
);
links = [
readonly links = computed(() => [
{ label: 'Übersicht', path: 'overview', disabled: false },
{
label: 'Projekte',
@@ -266,11 +279,19 @@ export class PersonComponent {
},
{ label: 'Publikationen', path: 'publications', disabled: false },
{ label: 'Netzwerk', path: 'network', disabled: false },
{ label: 'Unternehmen', path: 'company-connections', disabled: false },
...(this.companyConnectionsAvailable()
? [
{
label: 'Unternehmen',
path: 'company-connections',
disabled: false,
},
]
: []),
{ label: 'Förderungen', path: 'funding', disabled: false },
{ label: 'Nachrichten', path: 'news', disabled: false },
{ label: 'Patente', path: 'patents', disabled: false },
];
]);
onInterestingTagClick(selection: {
id: string;
@@ -41,7 +41,7 @@
<app-topic-chip
[label]="category | workPrimaryCategory"
[color]="primaryCategoryChipColor()"
[disabled]="true" />
[disabled]="false" />
}
</div>
</section>
@@ -39,10 +39,14 @@ export class UniTrendChartComponent {
const xAxisData = years.map(String);
// Resolve the active topic to compare one at a time to prevent line overlaps
const topics = Object.keys(trendData.series[0].topic_data || {});
const availableKeys = Object.keys(trendData.series[0].topic_data || {});
const displayNameKeys = availableKeys.filter(
(k) => !/^T\d+$/i.test(k) && !k.startsWith('http'),
);
const topics = displayNameKeys.length > 0 ? displayNameKeys : availableKeys;
const active = this.activeTopic();
const selectedTopic =
active && topics.includes(active)
active && (availableKeys.includes(active) || topics.includes(active))
? active
: topics.length > 0
? topics[0]
@@ -2,139 +2,129 @@
<!-- Strategy Selection Toggles Bar -->
<div class="strategy-toggles-bar">
<button
mat-button
[class.active]="selectedSearchType() === 'publications'"
(click)="setSearchType('publications')">
(click)="setSearchType('publications')"
matTooltip="Zeigt Publikationstrends nach Einrichtung, Land oder Region">
<mat-icon>library_books</mat-icon> Publikationen
</button>
<button
mat-button
[class.active]="selectedSearchType() === 'authors'"
(click)="setSearchType('authors')">
(click)="setSearchType('authors')"
matTooltip="Zeigt Publikationstrends einzelner Autoren">
<mat-icon>people</mat-icon> Autoren
</button>
<button
mat-button
[class.active]="selectedSearchType() === 'patents'"
(click)="setSearchType('patents')">
(click)="setSearchType('patents')"
matTooltip="Zeigt Patentanmeldungstrends">
<mat-icon>assignment</mat-icon> Patente
</button>
<button
mat-button
[class.active]="selectedSearchType() === 'projects'"
(click)="setSearchType('projects')">
(click)="setSearchType('projects')"
matTooltip="Zeigt Drittmittelförderungstrends">
<mat-icon>business_center</mat-icon> Projekte
</button>
<button
mat-button
[class.active]="selectedSearchType() === 'news'"
[disabled]="!isUde()"
[title]="
[matTooltip]="
!isUde()
? 'News-Trends sind nur für die Universität Duisburg-Essen verfügbar'
: ''
: 'Zeigt Pressemitteilungstrends der UDE'
"
(click)="setSearchType('news')">
<mat-icon>campaign</mat-icon> News
</button>
<button
mat-button
[class.active]="selectedSearchType() === 'all'"
(click)="setSearchType('all')">
(click)="setSearchType('all')"
matTooltip="Zeigt den aggregierten Themenlebenszyklus über alle Fachbereiche">
<mat-icon>dashboard</mat-icon> Themenlebenszyklus (All)
</button>
</div>
<div class="trend-layout">
<!-- Linkes Sidebar-Panel: Steuerung -->
<aside class="trend-sidebar">
<!-- Zeitraum-Auswahl -->
<app-year-range-slider
[minYear]="2000"
[maxYear]="2026"
[(startYear)]="startYear"
[(endYear)]="endYear"
(startYearChange)="updateUrlParams()"
(endYearChange)="updateUrlParams()">
</app-year-range-slider>
<!-- Combined Header Controls Bar: Slider and Scale Toggles on the Same Height -->
<div class="trend-top-controls-bar">
<div class="control-section slider-section">
<app-year-range-slider
[minYear]="2000"
[maxYear]="2026"
[(startYear)]="startYear"
[(endYear)]="endYear"
(startYearChange)="updateUrlParams()"
(endYearChange)="updateUrlParams()">
</app-year-range-slider>
</div>
<!-- Länder/Kontinente vergleichen -->
@if (activeConfig().showLocationSelector) {
<app-location-selector
[comparisonCountries]="comparisonCountries()"
[comparisonRegions]="comparisonRegions()"
[locationQuery]="locationQuery()"
[locationSearchResults]="locationSearchResults()"
[getEntityColor]="boundGetEntityColor"
[isVisible]="boundIsVisible"
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
(addLocation)="addLocation($event)"
(removeLocation)="removeLocation($event.id, $event.type)"
(searchChange)="onLocationSearchChange($event)"
(toggleVisibility)="toggleVisibility($event)"
(selectPie)="onSelectPieEntity($event)">
</app-location-selector>
}
<div class="control-section scale-section">
<span class="toggle-label">Visualisierungsskala:</span>
<mat-button-toggle-group
[value]="chartMode()"
(change)="onChartModeChange($event)"
aria-label="Visualisierungsskala">
<mat-button-toggle
value="normalized"
matTooltip="Normiert das Publikationsvolumen auf [0,1], um die Form von Wachstumstrends zu vergleichen.">
<mat-icon>trending_down</mat-icon>
<span class="toggle-text">Normierte Skala</span>
</mat-button-toggle>
<mat-button-toggle
value="total"
matTooltip="Zeigt die absolute Anzahl der Publikationen.">
<mat-icon>bar_chart</mat-icon>
<span class="toggle-text">Gesamtvolumen</span>
</mat-button-toggle>
<mat-button-toggle
value="cumulative"
matTooltip="Zeigt das normierte kumulierte Publikationswachstum (S-Kurve).">
<mat-icon>trending_up</mat-icon>
<span class="toggle-text">S-Kurve (Normiert)</span>
</mat-button-toggle>
</mat-button-toggle-group>
</div>
</div>
<!-- Top-Autoren einer Einrichtung hinzufügen (Authors Tab Sidebar Placement) -->
@if (activeConfig().showAuthorSelector) {
<app-author-institution-selector
[searchQuery]="authorInstSearchQuery()"
[searchResults]="authorInstSearchResults()"
(addInstitutionAuthors)="
addInstitutionAuthors($event.id, $event.name)
"
(searchChange)="onAuthorInstSearchChange($event)">
</app-author-institution-selector>
}
</aside>
<!-- Rechtes Haupt-Panel: Toggles & Diagramm -->
<main class="trend-main">
@if (isTrendLoading() && !rawTrendResponse()) {
<!-- Main Full-Width Content Area -->
<main class="trend-main-fullwidth">
@if (isPageResolving() || (isTrendLoading() && !rawTrendResponse())) {
<app-loading
text="Trenddaten werden initialisiert..."
text="Trenddaten werden geladen..."
icon="trending_up"
[size]="200"
[diameter]="200"></app-loading>
} @else if (rawTrendResponse()) {
<div class="trend-toggles-bar">
<span class="toggle-label">Visualisierungsskala:</span>
<div class="toggle-buttons">
<button
[class.active]="chartMode() === 'normalized'"
(click)="setChartMode('normalized')"
title="Normiert das Publikationsvolumen auf [0,1], um die Form von Wachstumstrends zu vergleichen.">
<mat-icon>trending_down</mat-icon> Normierte Skala
</button>
<button
[class.active]="chartMode() === 'total'"
(click)="setChartMode('total')"
title="Zeigt die absolute Anzahl der Publikationen.">
<mat-icon>bar_chart</mat-icon> Gesamtvolumen
</button>
<button
[class.active]="chartMode() === 'cumulative'"
(click)="setChartMode('cumulative')"
title="Zeigt das normierte kumulierte Publikationswachstum (S-Kurve).">
<mat-icon>trending_up</mat-icon> S-Kurve (Normiert)
</button>
</div>
</div>
<!-- Chart Holder Card (100% Full Width) -->
<div class="chart-holder-card">
@if (isTrendLoading()) {
<div class="loader-overlay">
<div class="spinner"></div>
<p>Trenddaten werden abgerufen...</p>
</div>
}
@if (
selectedTrendTopics().length > 1 && selectedSearchType() !== 'news'
) {
@if (selectedTrendTopics().length > 0) {
<div class="chart-topic-tabs">
@for (topic of selectedTrendTopics(); track topic) {
<app-topic-chip
[label]="topic"
[active]="activeChartTopic() === topic"
[color]="getTopicColor(topic)"
[disabled]="isTopicEmpty(topic)"
(chipClick)="updateActiveChartTopic(topic)">
</app-topic-chip>
@if (selectedSearchType() === 'news') {
<app-topic-chip
[label]="topic"
[active]="true"
[color]="getTopicColor(topic)"
[disabled]="false"
[matTooltip]="topic"
style="pointer-events: none; cursor: default">
</app-topic-chip>
} @else if (selectedTrendTopics().length > 1) {
<app-topic-chip
[label]="topic"
[active]="activeChartTopic() === topic"
[color]="getTopicColor(topic)"
[disabled]="isTopicEmpty(topic)"
[matTooltip]="topic"
(chipClick)="updateActiveChartTopic(topic)">
</app-topic-chip>
}
}
</div>
}
@@ -149,27 +139,39 @@
<!-- Pie Charts Row -->
@if (
selectedPieEntity() &&
selectedSearchType() !== 'news' &&
(selectedPieEntity() || selectedSearchType() === 'news') &&
selectedSearchType() !== 'all'
) {
<div class="pie-charts-row" style="margin-bottom: 24px">
<app-uni-pie-chart
[data]="trendResponse()"
[loading]="isTrendLoading()"
[entityId]="selectedPieEntity()!.id"
[entityName]="selectedPieEntity()!.name"
[startYear]="startYear()"
[endYear]="endYear()"
[getTopicColor]="boundGetTopicColor">
</app-uni-pie-chart>
<div class="pie-charts-row">
@if (selectedSearchType() === 'news') {
<app-uni-pie-chart
[titleText]="'Verteilung der ausgewählten Themen'"
[pieData]="newsSelectedTopicsPieData()"
[loading]="isTrendLoading()"
[startYear]="startYear()"
[endYear]="endYear()"
[getTopicColor]="boundGetTopicColor">
</app-uni-pie-chart>
} @else {
<app-uni-pie-chart
[data]="trendResponse()"
[loading]="isTrendLoading()"
[entityId]="selectedPieEntity()!.id"
[entityName]="selectedPieEntity()!.name"
[startYear]="startYear()"
[endYear]="endYear()"
[getTopicColor]="boundGetTopicColor">
</app-uni-pie-chart>
}
<app-uni-pie-chart
[titleText]="
'Top ' +
topTopicsSize() +
' Themen (Gesamt): ' +
selectedPieEntity()!.name
(selectedSearchType() === 'news'
? 'Alle News'
: (selectedPieEntity()?.name ?? ''))
"
[pieData]="topTopicsData()"
[loading]="isTopTopicsLoading() || isTrendLoading()"
@@ -181,49 +183,86 @@
</div>
}
<!-- Unified Institution Search, Compare, & Recommendations -->
@if (activeConfig().showInstitutionSelector) {
<app-institution-selector
[activeTab]="selectedSearchType()"
[comparisonInstitutions]="comparisonInstitutions()"
[primaryInstitution]="primaryInstitution()"
[primaryInstitutionName]="primaryInstitutionName()"
[topSuggestions]="topSuggestions()"
[isSuggestionsLoading]="isSuggestionsLoading()"
[activeChartTopic]="activeChartTopic()"
[searchQuery]="searchQuery()"
[searchResults]="searchResults()"
[getEntityColor]="boundGetEntityColor"
[isVisible]="boundIsVisible"
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
(addInstitution)="addInstitution($event.id, $event.name)"
(removeInstitution)="removeInstitution($event)"
(searchChange)="onSearchChange($event)"
(toggleVisibility)="toggleVisibility($event)"
(selectPie)="onSelectPieEntity($event)">
</app-institution-selector>
}
<!-- Combined Child Component Selectors Row (fits into a single line on desktop) -->
<div class="comparison-selectors-row">
<!-- Countries / Regions Selector -->
@if (activeConfig().showLocationSelector) {
<app-location-selector
class="selector-item"
[comparisonCountries]="comparisonCountries()"
[comparisonRegions]="comparisonRegions()"
[locationQuery]="locationQuery()"
[locationSearchResults]="locationSearchResults()"
[getEntityColor]="boundGetEntityColor"
[isVisible]="boundIsVisible"
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
(addLocation)="addLocation($event)"
(removeLocation)="removeLocation($event.id, $event.type)"
(searchChange)="onLocationSearchChange($event)"
(toggleVisibility)="toggleVisibility($event)"
(selectPie)="onSelectPieEntity($event)">
</app-location-selector>
}
<!-- Reusable Author Selection UI (Main Panel below chart) -->
@if (activeConfig().showAuthorSelector) {
<app-author-selector
[activeTab]="selectedSearchType()"
[comparisonAuthors]="comparisonAuthors()"
[topSuggestions]="recommendedAuthors()"
[isSuggestionsLoading]="isSuggestionsLoading()"
[activeChartTopic]="activeChartTopic()"
[searchQuery]="authorSearchQuery()"
[searchResults]="authorSearchResults()"
[getEntityColor]="boundGetEntityColor"
[isVisible]="boundIsVisible"
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
(addAuthor)="addAuthor($event.id, $event.name)"
(removeAuthor)="removeAuthor($event)"
(searchChange)="onAuthorSearchChange($event)"
(toggleVisibility)="toggleVisibility($event)"
(selectPie)="onSelectPieEntity($event)">
</app-author-selector>
}
<!-- Top-Autoren einer Einrichtung hinzufügen -->
@if (activeConfig().showAuthorSelector) {
<app-author-institution-selector
class="selector-item"
[searchQuery]="authorInstSearchQuery()"
[searchResults]="authorInstSearchResults()"
(addInstitutionAuthors)="
addInstitutionAuthors($event.id, $event.name)
"
(searchChange)="onAuthorInstSearchChange($event)">
</app-author-institution-selector>
}
<!-- Unified Institution Search, Compare, & Recommendations -->
@if (activeConfig().showInstitutionSelector) {
<app-institution-selector
class="selector-item selector-item--main"
[activeTab]="selectedSearchType()"
[comparisonInstitutions]="comparisonInstitutions()"
[primaryInstitution]="primaryInstitution()"
[primaryInstitutionName]="primaryInstitutionName()"
[topSuggestions]="topSuggestions()"
[isSuggestionsLoading]="isSuggestionsLoading()"
[activeChartTopic]="activeChartTopic()"
[searchQuery]="searchQuery()"
[searchResults]="searchResults()"
[getEntityColor]="boundGetEntityColor"
[isVisible]="boundIsVisible"
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
(addInstitution)="addInstitution($event.id, $event.name)"
(removeInstitution)="removeInstitution($event)"
(searchChange)="onSearchChange($event)"
(toggleVisibility)="toggleVisibility($event)"
(selectPie)="onSelectPieEntity($event)">
</app-institution-selector>
}
<!-- Reusable Author Selection UI -->
@if (activeConfig().showAuthorSelector) {
<app-author-selector
class="selector-item selector-item--main"
[activeTab]="selectedSearchType()"
[comparisonAuthors]="comparisonAuthors()"
[topSuggestions]="recommendedAuthors()"
[isSuggestionsLoading]="isSuggestionsLoading()"
[activeChartTopic]="activeChartTopic()"
[searchQuery]="authorSearchQuery()"
[searchResults]="authorSearchResults()"
[getEntityColor]="boundGetEntityColor"
[isVisible]="boundIsVisible"
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
(addAuthor)="addAuthor($event.id, $event.name)"
(removeAuthor)="removeAuthor($event)"
(searchChange)="onAuthorSearchChange($event)"
(toggleVisibility)="toggleVisibility($event)"
(selectPie)="onSelectPieEntity($event)">
</app-author-selector>
}
</div>
} @else {
<div class="no-data-fallback">
<mat-icon>trending_up</mat-icon>
@@ -1,185 +1,14 @@
.trend-layout {
display: grid;
grid-template-columns: 300px minmax(0, 1fr);
gap: 1.5rem;
margin-top: 1.5rem;
font-family: 'Inter', sans-serif;
@media (max-width: 1024px) {
grid-template-columns: 1fr;
}
}
.trend-sidebar {
.trend-layout-wrapper {
display: flex;
flex-direction: column;
gap: 1rem;
}
.control-card {
background: white;
border-radius: 10px;
padding: 1.25rem;
border: 1px solid #e5e7eb;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
h3 {
font-size: 0.8rem;
font-weight: 600;
text-transform: uppercase;
color: #6b7280;
margin: 0 0 0.75rem 0;
letter-spacing: 0.05em;
}
}
.checkbox-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.checkbox-label {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
color: #374151;
cursor: pointer;
input[type='checkbox'] {
accent-color: #3b82f6;
width: 15px;
height: 15px;
cursor: pointer;
}
}
.empty-list-info {
font-size: 0.75rem;
color: #9ca3af;
text-align: center;
padding: 8px 0;
border: 1px dashed #e5e7eb;
border-radius: 5px;
}
.trend-main {
display: flex;
flex-direction: column;
gap: 1rem;
}
.trend-toggles-bar {
display: flex;
justify-content: space-between;
align-items: center;
background: white;
border-radius: 10px;
padding: 0.6rem 1rem;
border: 1px solid #e5e7eb;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
.toggle-label {
font-size: 0.8125rem;
font-weight: 500;
color: #4b5563;
}
}
.toggle-buttons {
display: flex;
background: #f3f4f6;
border-radius: 6px;
padding: 2px;
button {
padding: 0.4rem 0.8rem;
border: none;
background: none;
font-size: 0.75rem;
font-weight: 500;
color: #4b5563;
border-radius: 5px;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 6px;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
}
&:hover:not(.active) {
color: #111827;
background: rgba(255, 255, 255, 0.5);
}
&.active {
background: white;
color: #3b82f6;
font-weight: 600;
}
}
}
.chart-holder-card {
position: relative;
background: white;
border-radius: 10px;
border: 1px solid #e5e7eb;
overflow: hidden;
min-height: 400px;
}
.chart-topic-tabs {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.4rem;
padding: 0.6rem 1rem;
background: #f9fafb;
border-bottom: 1px solid #e5e7eb;
}
.loader-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.8);
z-index: 10;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
.spinner {
width: 32px;
height: 32px;
border: 3px solid rgba(59, 130, 246, 0.1);
border-radius: 50%;
border-top-color: #3b82f6;
animation: spin 0.8s linear infinite;
margin-bottom: 8px;
}
p {
font-size: 0.8125rem;
color: #4b5563;
margin: 0;
}
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
width: 100%;
box-sizing: border-box;
font-family:
'Inter',
system-ui,
-apple-system,
sans-serif;
}
.strategy-toggles-bar {
@@ -190,14 +19,13 @@
border-radius: 12px;
padding: 6px;
border: 1px solid #e2e8f0;
margin-bottom: 0.5rem;
button {
padding: 0.5rem 1rem;
padding: 0.45rem 0.9rem;
border: none;
background: none;
font-size: 0.75rem;
font-weight: 600;
font-size: 0.8125rem;
font-weight: 500;
color: #64748b;
border-radius: 8px;
cursor: pointer;
@@ -207,38 +35,189 @@
transition: all 0.2s ease;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
font-size: 18px;
width: 18px;
height: 18px;
}
&:hover:not(.active):not([disabled]) {
color: #0f172a;
background: #f1f5f9;
}
&[disabled] {
opacity: 0.4;
opacity: 0.45;
cursor: not-allowed;
}
&.active {
background: white;
color: #3b82f6;
color: #2563eb;
font-weight: 600;
box-shadow:
0 4px 6px -1px rgba(0, 0, 0, 0.05),
0 2px 4px -1px rgba(0, 0, 0, 0.03);
0 2px 4px rgba(0, 0, 0, 0.05),
0 1px 2px rgba(0, 0, 0, 0.03);
}
}
}
.trend-layout {
display: flex;
flex-direction: column;
gap: 1.25rem;
width: 100%;
box-sizing: border-box;
}
/* Combined Top Header Control Bar */
.trend-top-controls-bar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1.5rem;
background: white;
border-radius: 12px;
padding: 0.75rem 1.25rem;
border: 1px solid #e5e7eb;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
width: 100%;
box-sizing: border-box;
.slider-section {
flex: 1;
min-width: 280px;
}
.scale-section {
display: flex;
align-items: center;
gap: 0.75rem;
flex-shrink: 0;
.toggle-label {
font-size: 0.8125rem;
font-weight: 600;
color: #4b5563;
white-space: nowrap;
}
mat-button-toggle-group {
border: 1px solid #e2e8f0;
border-radius: 8px;
overflow: hidden;
background: #f8fafc;
box-shadow: none;
mat-button-toggle {
font-size: 0.75rem;
font-weight: 500;
color: #475569;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
margin-right: 4px;
vertical-align: middle;
}
.toggle-text {
white-space: nowrap;
}
}
.mat-button-toggle-checked {
background-color: white !important;
color: #2563eb !important;
font-weight: 600;
}
}
}
@media (max-width: 900px) {
flex-direction: column;
align-items: stretch;
gap: 1rem;
}
}
.trend-main-fullwidth {
display: flex;
flex-direction: column;
gap: 1.25rem;
width: 100%;
box-sizing: border-box;
}
.chart-holder-card {
position: relative;
background: white;
border-radius: 12px;
border: 1px solid #e5e7eb;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
overflow: hidden;
min-height: 450px;
width: 100%;
box-sizing: border-box;
}
.chart-topic-tabs {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
padding: 0.75rem 1.25rem;
background: #f8fafc;
border-bottom: 1px solid #e2e8f0;
}
.loader-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.85);
z-index: 10;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 0.75rem;
p {
font-size: 0.875rem;
font-weight: 500;
color: #3b82f6;
margin: 0;
}
}
.pie-charts-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1.5rem;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 1.25rem;
width: 100%;
box-sizing: border-box;
}
.comparison-selectors-row {
display: flex;
flex-wrap: wrap;
align-items: stretch;
gap: 1.25rem;
width: 100%;
box-sizing: border-box;
@media (max-width: 768px) {
grid-template-columns: 1fr;
.selector-item {
flex: 1 1 300px;
min-width: 0;
max-width: 100%;
box-sizing: border-box;
&.selector-item--main {
flex: 2 1 450px;
}
}
}
@@ -249,14 +228,21 @@
justify-content: center;
min-height: 400px;
background: white;
border-radius: 10px;
border-radius: 12px;
border: 1px solid #e5e7eb;
color: #9ca3af;
gap: 0.5rem;
gap: 0.75rem;
mat-icon {
font-size: 48px;
width: 48px;
height: 48px;
font-size: 56px;
width: 56px;
height: 56px;
}
p {
font-size: 0.9375rem;
font-weight: 500;
color: #6b7280;
margin: 0;
}
}
@@ -11,16 +11,26 @@ import {
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import {
ActivatedRoute,
Router,
ResolveStart,
ResolveEnd,
} from '@angular/router';
import { forkJoin } from 'rxjs';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import {
MatButtonToggleModule,
MatButtonToggleChange,
} from '@angular/material/button-toggle';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatTooltipModule } from '@angular/material/tooltip';
import { UniTrendChartComponent } from '../uni-trend-chart/uni-trend-chart.component';
import { UniPieChartComponent } from '../uni-pie-chart/uni-pie-chart.component';
import {
@@ -115,8 +125,10 @@ export const TREND_CONFIGS: Record<string, TrendStrategyConfig> = {
UniPieChartComponent,
MatCheckboxModule,
MatButtonModule,
MatButtonToggleModule,
MatIconModule,
MatProgressSpinnerModule,
MatTooltipModule,
TopicChipComponent,
YearRangeSliderComponent,
LocationSelectorComponent,
@@ -208,6 +220,7 @@ export class UniTrendParentComponent implements OnInit {
readonly fetchedFuzzy = signal<boolean | null>(null);
// Results & Loading signals
readonly isPageResolving = signal<boolean>(false);
readonly rawTrendResponse = signal<TrendResponse | null>(null);
readonly isTrendLoading = signal<boolean>(false);
readonly topSuggestions = signal<TopInstitutionItem[]>([]);
@@ -263,6 +276,29 @@ export class UniTrendParentComponent implements OnInit {
readonly boundGetTopicColor = this.getTopicColor.bind(this);
readonly newsSelectedTopicsPieData = computed(() => {
const data = this.trendResponse();
if (!data || !data.series || this.selectedSearchType() !== 'news') {
return null;
}
const startYr = this.startYear();
const endYr = this.endYear();
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,
};
});
});
// Autocomplete UI state
readonly searchQuery = signal<string>('');
readonly searchResults = signal<AutocompleteResponseResultsInner[]>([]);
@@ -294,12 +330,25 @@ export class UniTrendParentComponent implements OnInit {
}
getEntityColor(entityId: string): string {
if (this.selectedSearchType() === 'news') {
const topicName = entityId.startsWith('news_topic_')
? entityId.slice('news_topic_'.length)
: entityId;
return this.getTopicColor(topicName);
}
const cleanId = (id: string | null | undefined): string => {
if (!id) return '';
const lower = id.toLowerCase().trim();
return lower.includes('/') ? lower.split('/').pop()! : lower;
};
const defaultInstId = 'https://openalex.org/I62318514';
const primaryId = this.primaryInstitution() || defaultInstId;
const insts = this.comparisonInstitutions().map((i) => i.id);
const countries = this.comparisonCountries().map((c) => c.id);
const regions = this.comparisonRegions().map((r) => r.id);
const authors = this.comparisonAuthors().map((a) => a.id);
const primaryId = cleanId(this.primaryInstitution() || defaultInstId);
const insts = this.comparisonInstitutions().map((i) => cleanId(i.id));
const countries = this.comparisonCountries().map((c) => cleanId(c.id));
const regions = this.comparisonRegions().map((r) => cleanId(r.id));
const authors = this.comparisonAuthors().map((a) => cleanId(a.id));
const orderedIds = [
primaryId,
@@ -309,7 +358,8 @@ export class UniTrendParentComponent implements OnInit {
...authors,
];
const idx = orderedIds.indexOf(entityId);
const targetCleanId = cleanId(entityId);
const idx = orderedIds.indexOf(targetCleanId);
if (idx === -1) return '#9ca3af';
const entityColors = [
@@ -345,17 +395,128 @@ export class UniTrendParentComponent implements OnInit {
readonly boundGetEntityColor = (id: string) => this.getEntityColor(id);
readonly boundIsVisible = (id: string) => this.isVisible(id);
// Computed: filters out items locally if they were removed from list
// Computed: filters out items locally if they were removed from list and normalizes topic_data keys & entity names
readonly trendResponse = computed(() => {
const raw = this.rawTrendResponse();
if (!raw) return null;
if (!raw || !raw.series) return null;
const topics = this.selectedTrendTopics();
const type = this.selectedSearchType();
const cleanId = (id: string | null | undefined): string => {
if (!id) return '';
const lower = id.toLowerCase().trim();
return lower.includes('/') ? lower.split('/').pop()! : lower;
};
const primaryInstCleanId = cleanId(
this.primaryInstitution() || 'I62318514',
);
const resolveEntityName = (s: TrendSeries): string => {
const cId = cleanId(s.entity_id);
if (s.entity_type === 'institution') {
if (cId === primaryInstCleanId) {
return (
this.primaryInstitutionName() ||
s.entity_name ||
'Haupt-Einrichtung'
);
}
const foundInst = this.comparisonInstitutions().find(
(i) => cleanId(i.id) === cId,
);
if (foundInst && foundInst.name && foundInst.name !== foundInst.id) {
return foundInst.name;
}
} else if (s.entity_type === 'country') {
const foundCountry = this.comparisonCountries().find(
(c) => cleanId(c.id) === cId,
);
if (
foundCountry &&
foundCountry.name &&
foundCountry.name !== foundCountry.id
) {
return foundCountry.name;
}
} else if (s.entity_type === 'region') {
const foundRegion = this.comparisonRegions().find(
(r) => cleanId(r.id) === cId,
);
if (
foundRegion &&
foundRegion.name &&
foundRegion.name !== foundRegion.id
) {
return foundRegion.name;
}
} else if (s.entity_type === 'author') {
const foundAuthor = this.comparisonAuthors().find(
(a) => cleanId(a.id) === cId,
);
if (
foundAuthor &&
foundAuthor.name &&
foundAuthor.name !== foundAuthor.id
) {
return foundAuthor.name;
}
}
return s.entity_name &&
!s.entity_name.startsWith('I') &&
s.entity_name.length > 8
? s.entity_name
: s.entity_name || cId;
};
// Map series topic_data keys to display names so they match selectedTrendTopics
const normalizeTopicData = (s: TrendSeries): TrendSeries => {
const nameResolved = resolveEntityName(s);
if (!s.topic_data) return { ...s, entity_name: nameResolved };
const rawTopicKeys = Object.keys(s.topic_data);
if (rawTopicKeys.length === 0) return { ...s, entity_name: nameResolved };
const newTopicData: Record<string, TopicYearlyData[]> = {};
topics.forEach((topicName, idx) => {
const mappedName = this.getMappedTopic(topicName);
let matchKey = rawTopicKeys.find(
(rk) =>
rk.toLowerCase() === topicName.toLowerCase() ||
rk.toLowerCase() === mappedName.toLowerCase() ||
rk.toLowerCase().includes(topicName.toLowerCase()) ||
rk.toLowerCase().includes(mappedName.toLowerCase()),
);
if (!matchKey && rawTopicKeys[idx]) {
matchKey = rawTopicKeys[idx];
}
if (matchKey && s.topic_data[matchKey]) {
newTopicData[topicName] = s.topic_data[matchKey];
} else if (rawTopicKeys[0] && s.topic_data[rawTopicKeys[0]]) {
newTopicData[topicName] = s.topic_data[rawTopicKeys[0]];
}
});
// Preserve existing keys as well
Object.assign(newTopicData, s.topic_data);
return {
...s,
entity_name: nameResolved,
topic_data: newTopicData,
};
};
if (type === 'news' || type === 'all' || type === 'patents') {
return {
...raw,
series: raw.series.map((s) => ({
...s,
...normalizeTopicData(s),
visible: this.isVisible(s.entity_id),
})),
};
@@ -368,7 +529,7 @@ export class UniTrendParentComponent implements OnInit {
const filtered = raw.series
.filter((s) => currentAuthorIds.has(s.entity_id.toLowerCase()))
.map((s) => ({
...s,
...normalizeTopicData(s),
visible: this.isVisible(s.entity_id),
}));
return {
@@ -378,13 +539,6 @@ export class UniTrendParentComponent implements OnInit {
}
// Default: publications, patents, projects
// Resilient ID normalization helper
const cleanId = (id: string | null | undefined): string => {
if (!id) return '';
const lower = id.toLowerCase().trim();
return lower.includes('/') ? lower.split('/').pop()! : lower;
};
const currentInstIds = new Set(
this.comparisonInstitutions().map((i: CompareItem) => cleanId(i.id)),
);
@@ -394,9 +548,6 @@ export class UniTrendParentComponent implements OnInit {
const currentRegionIds = new Set(
this.comparisonRegions().map((r: CompareItem) => cleanId(r.id)),
);
const primaryInstCleanId = cleanId(
this.primaryInstitution() || 'I62318514',
);
const primaryInstSeries: TrendSeries[] = [];
const compInstSeries: TrendSeries[] = [];
@@ -428,7 +579,7 @@ export class UniTrendParentComponent implements OnInit {
...countrySeries,
...regionSeries,
].map((s) => ({
...s,
...normalizeTopicData(s),
visible: this.isVisible(s.entity_id),
}));
@@ -445,6 +596,50 @@ export class UniTrendParentComponent implements OnInit {
this.availableYears.push(y);
}
this.router.events.subscribe((event) => {
if (event instanceof ResolveStart) {
this.isPageResolving.set(true);
} else if (event instanceof ResolveEnd) {
this.isPageResolving.set(false);
}
});
// Subscribe to route resolver data
this.route.data.subscribe((data) => {
if (data['trendData']) {
const resolved = data['trendData'];
const res = resolved.trendResponse ?? resolved;
this.rawTrendResponse.set(res);
const type = resolved.searchType || this.selectedSearchType();
this.selectedSearchType.set(type);
this.fetchedSearchType.set(type);
const fuzzy = this.state?.fuzzySearch() ?? true;
this.fetchedFuzzy.set(fuzzy);
if (resolved.topics && resolved.topics.length > 0) {
this.selectedTrendTopics.set(resolved.topics);
this.fetchedTopics.set([...resolved.topics]);
if (
!this.activeChartTopic() ||
!resolved.topics.includes(this.activeChartTopic())
) {
this.activeChartTopic.set(resolved.topics[0]);
}
} else {
this.fetchedTopics.set([...this.selectedTrendTopics()]);
}
this.fetchedInstitutions.set([...this.comparisonInstitutions()]);
this.fetchedCountries.set([...this.comparisonCountries()]);
this.fetchedRegions.set([...this.comparisonRegions()]);
this.fetchedAuthors.set([...this.comparisonAuthors()]);
this.isTrendLoading.set(false);
}
});
// Effect: automatically sync checkboxes list whenever input keywords or fuzzy state changes
effect(() => {
const kws = this.keywords();
@@ -511,7 +706,7 @@ export class UniTrendParentComponent implements OnInit {
});
});
// Effect: automatically refetch trend data whenever topics or comparisons change (fully reactive with subset check)
// Effect: automatically refetch trend data whenever topics or comparisons change (fully reactive with cached rawTrendResponse check)
effect(() => {
const topics = this.selectedTrendTopics();
const insts = this.comparisonInstitutions();
@@ -526,55 +721,59 @@ export class UniTrendParentComponent implements OnInit {
const fetchedT = new Set(untracked(() => this.fetchedTopics()));
const fetchedType = untracked(() => this.fetchedSearchType());
const fetchedF = untracked(() => this.fetchedFuzzy());
const rawRes = untracked(() => this.rawTrendResponse());
const allTopicsFetched = topics.every((t) => fetchedT.has(t));
const sameType = searchType === fetchedType;
const sameFuzzy = fuzzy === fetchedF;
let allEntitiesFetched = false;
if (sameType) {
if (sameType && rawRes && rawRes.series) {
const rawSeriesCleanIds = new Set(
rawRes.series.map((s) => {
const id = s.entity_id;
return id.includes('/')
? id.split('/').pop()!.toLowerCase()
: id.toLowerCase();
}),
);
if (searchType === 'authors') {
const fetchedA = new Set(
untracked(() => this.fetchedAuthors()).map((a) =>
a.id.toLowerCase(),
),
);
allEntitiesFetched = authors.every((a) =>
fetchedA.has(a.id.toLowerCase()),
);
allEntitiesFetched =
authors.length === 0 ||
authors.every((a) => {
const cleanA = a.id.includes('/')
? a.id.split('/').pop()!.toLowerCase()
: a.id.toLowerCase();
return rawSeriesCleanIds.has(cleanA);
});
} else if (searchType === 'news' || searchType === 'all') {
allEntitiesFetched = true;
} else {
// publications, patents, projects
const fetchedI = new Set(
untracked(() => this.fetchedInstitutions()).map((i) =>
i.id.toLowerCase(),
),
);
const fetchedC = new Set(
untracked(() => this.fetchedCountries()).map((c) =>
c.id.toLowerCase(),
),
);
const fetchedR = new Set(
untracked(() => this.fetchedRegions()).map((r) =>
r.id.toLowerCase(),
),
);
allEntitiesFetched =
insts.every((i) => fetchedI.has(i.id.toLowerCase())) &&
countries.every((c) => fetchedC.has(c.id.toLowerCase())) &&
regions.every((r) => fetchedR.has(r.id.toLowerCase()));
(insts.length === 0 ||
insts.every((i) => {
const cleanI = i.id.includes('/')
? i.id.split('/').pop()!.toLowerCase()
: i.id.toLowerCase();
return rawSeriesCleanIds.has(cleanI);
})) &&
(countries.length === 0 ||
countries.every((c) =>
rawSeriesCleanIds.has(c.id.toLowerCase()),
)) &&
(regions.length === 0 ||
regions.every((r) => rawSeriesCleanIds.has(r.id.toLowerCase())));
}
}
const hasResponse = !!untracked(() => this.rawTrendResponse());
if (
allTopicsFetched &&
sameType &&
sameFuzzy &&
allEntitiesFetched &&
hasResponse
!!rawRes
) {
// All requested data is already present in rawTrendResponse, so skip backend call!
return;
@@ -762,7 +961,7 @@ export class UniTrendParentComponent implements OnInit {
const end = this.endYear();
const strategy = this.selectedSearchType();
if (!entity || strategy === 'news' || strategy === 'all') {
if (!entity || strategy === 'all') {
this.topTopicsData.set([]);
return;
}
@@ -904,7 +1103,7 @@ export class UniTrendParentComponent implements OnInit {
this.personsApiService
.searchPersonsList(
undefined, // query
'University of Duisburg-Essen', // primary institution
this.primaryInstitution() || 'I62318514', // primary institution ID
'cited_by_count', // sortBy
'desc', // sortOrder
[topic], // topic
@@ -993,7 +1192,7 @@ export class UniTrendParentComponent implements OnInit {
this.personsApiService
.searchPersonsList(
undefined, // query
'University of Duisburg-Essen', // UDE
this.primaryInstitution() || 'I62318514', // UDE institution ID
'cited_by_count', // sortBy
'desc', // sortOrder
[topic], // topic
@@ -1068,7 +1267,32 @@ export class UniTrendParentComponent implements OnInit {
)
.subscribe({
next: (response: TrendResponse) => {
this.rawTrendResponse.set(response);
const currentRaw = untracked(() => this.rawTrendResponse());
if (!currentRaw || !currentRaw.series) {
this.rawTrendResponse.set(response);
} else {
const seriesMap = new Map<string, TrendSeries>();
currentRaw.series.forEach((s) => {
seriesMap.set(`${s.entity_type}_${s.entity_id}`, s);
});
response.series.forEach((s) => {
const key = `${s.entity_type}_${s.entity_id}`;
const prev = seriesMap.get(key);
if (prev && prev.topic_data && s.topic_data) {
seriesMap.set(key, {
...prev,
...s,
topic_data: { ...prev.topic_data, ...s.topic_data },
});
} else {
seriesMap.set(key, s);
}
});
this.rawTrendResponse.set({
...response,
series: Array.from(seriesMap.values()),
});
}
this.isTrendLoading.set(false);
this.updateUrlParams();
},
@@ -1252,7 +1476,7 @@ export class UniTrendParentComponent implements OnInit {
this.personsApiService
.searchPersonsList(
undefined, // query
name, // institutionName
id, // institutionId
'cited_by_count', // sortBy
'desc', // sortOrder
[topic], // topic
@@ -1311,6 +1535,12 @@ export class UniTrendParentComponent implements OnInit {
this.updateUrlParams();
}
onChartModeChange(event: MatButtonToggleChange) {
if (event.value) {
this.setChartMode(event.value);
}
}
isTopicEmpty(topic: string): boolean {
const data = this.trendResponse();
if (!data || !data.series || data.series.length === 0) {
@@ -13,6 +13,8 @@ export const projectQueryParamKeys = {
topicId: 'topicId',
sortBy: 'sort_by',
sortDirection: 'sort_direction',
legend: 'legend',
legend_expanded: 'legend_expanded',
} as const;
const RESOLVING_PROJECT_PAGE_FOR_KEY = 'resolvingFor';
export const RESOLVING_PROJECT_PAGE_FOR = {
@@ -34,8 +36,6 @@ export const dfgProjectsResolver: ResolveFn<DfgProjectPage> = (
route.data,
);
const rawAuthorId = route.parent?.params['id'];
const page = Number(route.queryParamMap.get(projectQueryParamKeys.page)) || 0;
const size =
Number(route.queryParamMap.get(projectQueryParamKeys.size)) || 10;
@@ -57,13 +57,13 @@ export const dfgProjectsResolver: ResolveFn<DfgProjectPage> = (
);
const institutionIds = route.queryParamMap
.getAll(projectQueryParamKeys.institutionId)
.map((id) => Number(id))
.filter((id) => !isNaN(id));
.map((id) => Number(id));
const authorIds = route.queryParamMap
.getAll(projectQueryParamKeys.authorId)
.map((id) => Number(id))
.filter((id) => !isNaN(id));
.map((id) => Number(id));
if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) {
const rawAuthorId = route.parent?.parent?.params['id'];
return inject(ProjectsService).getDfgProjects(
rawAuthorId,
authorIds,
@@ -0,0 +1,199 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { ProjectsService } from '../api';
import { EuCordisProjectSearchPage } from '../api/model/euCordisProjectSearchPage';
export const euProjectQueryParamKeys = {
page: 'page',
size: 'size',
title: 'title',
institutionId: 'institutionId',
funding_start: 'funding_start',
funding_end: 'funding_end',
authorId: 'authorId',
topicId: 'topicId',
projectType: 'projectType',
country: 'country',
frameworkProgramme: 'frameworkProgramme',
fundingScheme: 'fundingScheme',
status: 'status',
sortBy: 'sort_by',
sortDirection: 'sort_direction',
legend: 'legend',
legend_expanded: 'legend_expanded',
} as const;
const RESOLVING_PROJECT_PAGE_FOR_KEY = 'resolvingFor';
export const RESOLVING_PROJECT_PAGE_FOR = {
PERSON: 'PERSON',
KEYWORDS_SEARCH: 'KEYWORDS_SEARCH',
} as const;
type ResolvingEuProjectPageFor =
(typeof RESOLVING_PROJECT_PAGE_FOR)[keyof typeof RESOLVING_PROJECT_PAGE_FOR];
function getRepeatedOrCsv(routeQueryParamMap: any, key: string): string[] {
const repeatedValues = routeQueryParamMap.getAll(key) ?? [];
const csvValues =
routeQueryParamMap
.get(key)
?.split(',')
.map((value: string) => value.trim())
.filter(Boolean) ?? [];
return Array.from(
new Set(
[...repeatedValues, ...csvValues]
.map((value) => String(value).trim())
.filter(Boolean),
),
);
}
export const euCordisProjectsResolver: ResolveFn<EuCordisProjectSearchPage> = (
route,
state,
) => {
const resolvingFor: ResolvingEuProjectPageFor =
route.data[RESOLVING_PROJECT_PAGE_FOR_KEY] ||
RESOLVING_PROJECT_PAGE_FOR.PERSON;
console.log(
'Resolving EU project page for',
resolvingFor,
'with route data:',
route.data,
);
/**
* For EU author filtering, this should be an OpenAlex author ID.
* Backend resolves:
* OpenAlex author -> publication DOIs -> CORDIS publications -> CORDIS project IDs
*/
const page =
Number(route.queryParamMap.get(euProjectQueryParamKeys.page)) || 0;
const size =
Number(route.queryParamMap.get(euProjectQueryParamKeys.size)) || 10;
const searchTerm =
route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined;
const sortBy =
route.queryParamMap.get(euProjectQueryParamKeys.sortBy) || 'title';
const sortDirection =
route.queryParamMap.get(euProjectQueryParamKeys.sortDirection) || 'asc';
const fundingStart = route.queryParamMap.getAll(
euProjectQueryParamKeys.funding_start,
);
const fundingEnd = route.queryParamMap.getAll(
euProjectQueryParamKeys.funding_end,
);
const filteredTopicIds = route.queryParamMap.getAll(
euProjectQueryParamKeys.topicId,
);
/**
* EU project types:
* fp7 | h2020 | heu
*/
const projectTypes = route.queryParamMap.getAll(
euProjectQueryParamKeys.projectType,
);
/**
* CORDIS organisation IDs are strings, not numeric DFG institution IDs.
*/
const organizationIds = route.queryParamMap.getAll(
euProjectQueryParamKeys.institutionId,
);
/**
* Additional OpenAlex author IDs from query params.
* Keep them as strings.
*/
const authorIds = route.queryParamMap
.getAll(euProjectQueryParamKeys.authorId)
.map((id) => id.split('/').pop() || id); // Extract the last part of the OpenAlex ID if it's a URL
const countries = route.queryParamMap.getAll(euProjectQueryParamKeys.country);
const frameworkProgrammes = route.queryParamMap.getAll(
euProjectQueryParamKeys.frameworkProgramme,
);
const fundingSchemes = route.queryParamMap.getAll(
euProjectQueryParamKeys.fundingScheme,
);
const statuses = route.queryParamMap.getAll(euProjectQueryParamKeys.status);
if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) {
const rawAuthorId = route.parent?.parent?.params['id'];
return inject(ProjectsService).searchEuCordisProjectsSummary(
rawAuthorId,
authorIds,
organizationIds,
[],
projectTypes as any,
searchTerm,
[],
[],
filteredTopicIds,
fundingStart,
fundingEnd,
countries,
frameworkProgrammes,
fundingSchemes,
statuses,
page,
size,
sortBy,
sortDirection,
false,
);
}
if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH) {
const keywords = getRepeatedOrCsv(route.queryParamMap, 'keywords');
const selectedTopicIds = route.queryParamMap.getAll('topics');
const fuzzySearch = route.queryParamMap.get('fuzzy') === 'true';
return inject(ProjectsService).searchEuCordisProjectsSummary(
undefined,
authorIds,
organizationIds,
[],
projectTypes as any,
searchTerm,
keywords,
selectedTopicIds,
filteredTopicIds,
fundingStart,
fundingEnd,
countries,
frameworkProgrammes,
fundingSchemes,
statuses,
page,
size,
sortBy,
sortDirection,
fuzzySearch,
);
}
throw new Error(`Unknown resolvingFor value: ${resolvingFor}`);
};
@@ -25,14 +25,15 @@ export const personListResolver: ResolveFn<CustomAuthorsListResponse> = (
? Number.parseInt(params.get('pageSize')!, 10)
: 10;
const institutionName = params.get('institutionName') || undefined;
const institutionId = params.get('institutionId') || undefined;
const sortBy = params.get('sortBy') || undefined;
const sortOrder = params.get('sortOrder') || undefined;
const topicsParam = params.getAll('topic');
const topics = parseQueryParamArray(topicsParam);
const yearFilterEnabled = params.get('yearFilterEnabled') === 'true';
const yearFilterEnabled =
!!institutionId && params.get('yearFilterEnabled') !== 'false';
const filterModeRaw = params.get('filterMode');
const filterMode =
@@ -42,20 +43,20 @@ export const personListResolver: ResolveFn<CustomAuthorsListResponse> = (
const filterYear = params.get('filterYear')
? Number.parseInt(params.get('filterYear')!, 10)
: undefined;
: new Date().getUTCFullYear() - 2;
const personsService = inject(PersonsService);
return personsService.searchPersonsList(
query,
institutionName,
institutionId,
sortBy,
sortOrder,
topics,
page,
pageSize,
defaultIncludes,
yearFilterEnabled ? true : undefined,
yearFilterEnabled,
yearFilterEnabled ? filterMode : undefined,
yearFilterEnabled ? filterYear : undefined,
);
+49 -4
View File
@@ -1,10 +1,25 @@
import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core';
import { CustomAuthorsListResponse, PersonsService } from '../api';
import { Observable, of, catchError, shareReplay } from 'rxjs';
import {
CompanyConnectionsService,
CustomAuthorsListResponse,
PersonsService,
} from '../api';
import {
Observable,
of,
catchError,
distinctUntilChanged,
map,
shareReplay,
switchMap,
} from 'rxjs';
import { CredentialService } from '../shared/services/credential.service';
import { toObservable } from '@angular/core/rxjs-interop';
export interface PersonDataResolved {
personData$: Observable<CustomAuthorsListResponse | null>;
companyConnectionsAvailable$: Observable<boolean>;
}
export const personResolver: ResolveFn<PersonDataResolved> = (route, state) => {
@@ -16,9 +31,14 @@ export const personResolver: ResolveFn<PersonDataResolved> = (route, state) => {
const authorId = route.paramMap.get('id') || undefined;
const personsService = inject(PersonsService);
const companyConnectionsService = inject(CompanyConnectionsService);
const credentialService = inject(CredentialService);
if (!authorId) {
return { personData$: of(null) };
return {
personData$: of(null),
companyConnectionsAvailable$: of(false),
};
}
const personData$ = personsService
@@ -31,5 +51,30 @@ export const personResolver: ResolveFn<PersonDataResolved> = (route, state) => {
shareReplay(1),
);
return { personData$ };
const companyConnectionsAvailable$ = toObservable(
credentialService.effectiveInstitutionId,
).pipe(
distinctUntilChanged(),
switchMap((institutionId) => {
if (!institutionId) {
return of(false);
}
return companyConnectionsService
.getCompanyConnectionsAvailability(authorId)
.pipe(
map((response) => response.available),
catchError((err) => {
console.error(
'Failed to check company connections availability:',
err,
);
return of(false);
}),
);
}),
shareReplay({ bufferSize: 1, refCount: true }),
);
return { personData$, companyConnectionsAvailable$ };
};
@@ -11,12 +11,13 @@ export const selectedDfgAuthorsResolver: ResolveFn<DfgPersonSummaryPage> = (
const authorIdQueryParamKey =
(route.data['authorIdQueryParamKey'] as string) || 'authorId';
const authorIds = route.queryParamMap.getAll(authorIdQueryParamKey);
const authorIds = route.queryParamMap
.getAll(authorIdQueryParamKey)
.map((id) => Number(id))
.filter((id) => !isNaN(id));
if (authorIds.length === 0) {
return { elements: [] };
}
return inject(DFGPersonsService).getDfgPersonsByIds(
authorIds.map((id) => id.trim()).filter((id) => id.length > 0),
);
return inject(DFGPersonsService).getDfgPersonsByIds(authorIds.map(String));
};
@@ -0,0 +1,17 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { ProjectsService } from '../api';
import { EuCordisOrganizationSelectorPage } from '../api/model/euCordisOrganizationSelectorPage';
export const selectedEuInstitutionsResolver: ResolveFn<
EuCordisOrganizationSelectorPage
> = (route, state) => {
const institutionIdQueryParamKey =
(route.data['institutionIdQueryParamKey'] as string) || 'institutionId';
const institutionIds = route.queryParamMap
.getAll(institutionIdQueryParamKey)
.map((id) => id.trim())
.filter((id) => id.length > 0);
return inject(ProjectsService).getEuOrganizationsByIds(institutionIds);
};
@@ -0,0 +1,123 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { catchError, of, Observable, map } from 'rxjs';
import { TrendResponse, UniversityRankingsService } from '../api';
import { SearchResultsStateService } from '../modules/keywords-search/search-results/search-results-state.service';
export interface UniTrendResolvedData {
trendResponse: TrendResponse | null;
searchType: string;
topics: string[];
keywords: string[];
fuzzy: boolean;
}
export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
route,
_state,
): Observable<UniTrendResolvedData> => {
const params = route.queryParamMap;
const searchState = inject(SearchResultsStateService, { optional: true });
const searchType = params.get('search_type') || 'publications';
const fuzzy = params.get('fuzzy') !== 'false';
// Extract keywords & topics
let keywords = params.getAll('keyword');
if (keywords.length === 0) {
const rawKeywords = params.get('keywords');
if (rawKeywords) {
keywords = rawKeywords
.split(',')
.map((k) => k.trim())
.filter((k) => k.length > 0);
}
}
if (keywords.length === 0 && searchState) {
keywords = searchState.keywords();
}
let topics = params.getAll('topic');
if (topics.length === 0) {
const rawTopics = params.get('topics');
if (rawTopics) {
topics = rawTopics
.split(',')
.map((t) => t.trim())
.filter((t) => t.length > 0);
}
}
if (topics.length === 0 && searchState) {
topics = fuzzy ? searchState.topicsList() : searchState.keywords();
}
// Fallback defaults if no topics/keywords present yet
if (topics.length === 0 && keywords.length === 0) {
topics = ['Artificial Intelligence'];
keywords = ['artificial intelligence'];
} else if (topics.length === 0) {
topics = keywords;
} else if (keywords.length === 0) {
keywords = topics;
}
// Parse institutions
const instParams = params.getAll('institutions');
let institutions = instParams.map((i) => {
const parts = i.split('|');
const cleanId = parts[0].includes('/')
? parts[0].split('/').pop() || parts[0]
: parts[0];
return cleanId;
});
if (institutions.length === 0) {
institutions = ['I62318514'];
}
// Parse countries
const countryParams = params.getAll('countries');
let countries = countryParams.map((c) => c.split('|')[0]);
if (countries.length === 0) {
countries = ['DE'];
}
// Parse regions & authors
const regionParams = params.getAll('regions');
const regions = regionParams.map((r) => r.split('|')[0]);
const authorParams = params.getAll('authors');
const authors = authorParams.map((a) => a.split('|')[0]);
const apiService = inject(UniversityRankingsService);
return apiService
.getTrendApiInseServiceUniversityRankingsTrendGet(
topics,
keywords,
fuzzy,
institutions,
countries,
regions,
authors,
searchType as any,
)
.pipe(
map((trendResponse) => ({
trendResponse,
searchType,
topics,
keywords,
fuzzy,
})),
catchError((err) => {
console.error('uniTrendResolver failed to load trend data:', err);
return of({
trendResponse: null,
searchType,
topics,
keywords,
fuzzy,
});
}),
);
};
@@ -0,0 +1,29 @@
export type PersonListQueryParams = Record<string, string | number | boolean>;
export function activeInstitutionPersonListQueryParams(
institutionId: string,
institutionName: string,
): PersonListQueryParams {
const normalizedInstitutionId = institutionId
.trim()
.replace(/^https:\/\/openalex\.org\//i, '');
const hasInstitution = normalizedInstitutionId.length > 0;
if (!hasInstitution) {
return {
sortOrder: 'desc',
yearFilterEnabled: false,
page: 1,
};
}
return {
institutionId: normalizedInstitutionId,
institutionName,
sortOrder: 'desc',
yearFilterEnabled: true,
filterMode: 'from',
filterYear: new Date().getUTCFullYear() - 2,
page: 1,
};
}
@@ -41,7 +41,7 @@
</div>
<mat-nav-list class="nav-list">
@for (itemGroup of navItemGroups; track $index) {
@for (itemGroup of navItemGroups(); track $index) {
<div>
@if (
(!itemGroup.adminOnly ||
@@ -11,6 +11,7 @@ import { MatDialog } from '@angular/material/dialog';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
import { MatCardContent, MatCardModule } from '@angular/material/card';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { activeInstitutionPersonListQueryParams } from '../../person-list-query-params';
type NavItem = {
label: string;
@@ -60,113 +61,120 @@ export class AppMenuComponent {
fragment: 'ignored',
};
navItems: NavItem[] = [
{
label: 'Dashboard',
icon: 'dashboard',
route: '/dashboard',
disabled: false,
},
{
label: 'Personen',
icon: 'groups',
route: '/persons',
queryParams: {
institutionName: this.credentialService.organizationName(),
readonly navItems = computed<NavItem[]>(() => {
const items: NavItem[] = [
{
label: 'Dashboard',
icon: 'dashboard',
route: '/dashboard',
disabled: false,
},
disabled: false,
},
{
label: 'Bookmarks',
icon: 'bookmarks',
route: '/bookmarks',
disabled: false,
},
{
label: 'News',
icon: 'newspaper',
route: '/news',
disabled: false,
},
{
label: 'Institutionen',
icon: 'apartment',
route: '/institutions',
disabled: false,
queryParams: {
search: '',
page: 0,
size: 10,
sort_by: 'works_count',
sorting_order: 'desc',
{
label: 'Personen',
icon: 'groups',
route: '/persons',
queryParams: activeInstitutionPersonListQueryParams(
this.credentialService.effectiveInstitutionId(),
this.credentialService.organizationName(),
),
disabled: false,
},
},
{
label: 'Projekte',
icon: 'work',
route: '/projects',
disabled: false,
queryParams: {
search: '',
page: 0,
size: 10,
selected_project_types: 'eu,bund,dfg',
sort_by: 'title',
sorting_order: 'asc',
{
label: 'Bookmarks',
icon: 'bookmarks',
route: '/bookmarks',
disabled: false,
},
},
{
label: 'Patente',
icon: 'workspace_premium',
route: '/patents',
disabled: false,
},
{
label: 'Keywords',
icon: 'join_left',
route: '/keywords',
disabled: false,
queryParams: {
mode: 'url',
{
label: 'News',
icon: 'newspaper',
route: '/news',
disabled: false,
},
},
{
label: 'Accounts',
icon: 'manage_accounts',
route: '/accounts',
disabled: false,
managerOrAdminOnly: true,
},
{
label: 'Organisationen',
icon: 'domain',
route: '/organizations',
disabled: false,
superAdminOnly: true,
},
];
navItemGroups: NavItemGroup[] = [
{
label: 'Navigation',
items: this.navItems.filter(
(item) =>
!item.adminOnly && !item.superAdminOnly && !item.managerOrAdminOnly,
),
},
{
label: 'Administration',
items: this.navItems.filter(
(item) =>
(item.adminOnly || item.managerOrAdminOnly) && !item.superAdminOnly,
),
managerOrAdminOnly: true,
},
{
label: 'Super Administration',
items: this.navItems.filter((item) => item.superAdminOnly),
superAdminOnly: true,
},
];
{
label: 'Institutionen',
icon: 'apartment',
route: '/institutions',
disabled: false,
queryParams: {
search: '',
page: 0,
size: 10,
sort_by: 'works_count',
sorting_order: 'desc',
},
},
{
label: 'Projekte',
icon: 'work',
route: '/projects',
disabled: false,
queryParams: {
search: '',
page: 0,
size: 10,
selected_project_types: 'eu,bund,dfg',
sort_by: 'title',
sorting_order: 'asc',
},
},
{
label: 'Patente',
icon: 'workspace_premium',
route: '/patents',
disabled: false,
},
{
label: 'Keywords',
icon: 'join_left',
route: '/keywords',
disabled: false,
queryParams: {
mode: 'url',
},
},
{
label: 'Accounts',
icon: 'manage_accounts',
route: '/accounts',
disabled: false,
managerOrAdminOnly: true,
},
{
label: 'Organisationen',
icon: 'domain',
route: '/organizations',
disabled: false,
superAdminOnly: true,
},
];
return items;
});
readonly navItemGroups = computed<NavItemGroup[]>(() => {
const navItems = this.navItems();
return [
{
label: 'Navigation',
items: navItems.filter(
(item) =>
!item.adminOnly && !item.superAdminOnly && !item.managerOrAdminOnly,
),
},
{
label: 'Administration',
items: navItems.filter(
(item) =>
(item.adminOnly || item.managerOrAdminOnly) && !item.superAdminOnly,
),
managerOrAdminOnly: true,
},
{
label: 'Super Administration',
items: navItems.filter((item) => item.superAdminOnly),
superAdminOnly: true,
},
];
});
constructor(
public credentialService: CredentialService,
@@ -1,3 +1,10 @@
:host {
display: block;
width: 100%;
min-width: 0;
max-width: 100%;
}
.author-institution-selector-container {
display: flex;
flex-direction: column;
@@ -7,7 +14,7 @@
padding: 24px;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
box-sizing: border-box;
margin-top: 20px;
margin-top: 0;
width: 100%;
}
@@ -1,3 +1,10 @@
:host {
display: block;
width: 100%;
min-width: 0;
max-width: 100%;
}
.author-selector-container {
display: grid;
grid-template-columns: 1fr 1.5fr;
@@ -8,7 +15,7 @@
padding: 24px;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
box-sizing: border-box;
margin-top: 20px;
margin-top: 0;
@media (max-width: 1024px) {
grid-template-columns: 1fr;
@@ -146,6 +153,8 @@
max-height: 180px;
overflow-y: auto;
padding-right: 4px;
width: 100%;
box-sizing: border-box;
}
.comparison-item {
@@ -158,6 +167,8 @@
gap: 8px;
transition: all 0.2s ease;
max-width: 100%;
min-width: 0;
box-sizing: border-box;
.item-name {
display: inline-flex;
@@ -168,7 +179,9 @@
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 180px;
min-width: 0;
max-width: 240px;
flex: 1 1 auto;
mat-icon {
font-size: 14px;
@@ -220,15 +233,13 @@
.suggestions-flex {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 10px;
max-height: 250px;
overflow-y: auto;
padding-right: 4px;
@media (max-width: 600px) {
grid-template-columns: 1fr;
}
width: 100%;
box-sizing: border-box;
}
.suggestion-item-horizontal {
@@ -94,7 +94,6 @@ export class DfgProjectTableComponent implements OnInit {
});
ngOnInit(): void {
console.log('DFG PROJECTS', this.page());
this.columns = [
{ id: 'title', header: 'Titel', type: 'accessor', accessorKey: 'title' },
{
@@ -126,8 +125,7 @@ export class DfgProjectTableComponent implements OnInit {
{
id: 'professional_classification',
header: 'Fachliche Zuordnung',
type: 'accessor',
accessorKey: 'professional_classification',
type: 'display',
cellTemplate: this.detailRowTmp(),
},
@@ -0,0 +1,20 @@
<div>
<app-project-filters
filterMode="dfg"
[queryParamKeys]="dfgQueryParamKeys"
[selectedDfgInstitutionsPage]="selectedDfgInstitutionsPage()"
[selectedDfgAuthorsPage]="selectedDfgAuthorsPage()"
[selectedTopicsPage]="selectedTopicsPage()"
[showFundingStartFilter]="true"
[showTopicFilter]="fuzzySearch()"
[showFundingEndFilter]="true"
[showAuthorFilter]="true"
[showInstitutionFilter]="true"
[showEuProjectTypeFilter]="false" />
<app-dfg-project-table
[page]="dfgProjectPage()"
[authorFilterEnabled]="true"
[topicFilterEnabled]="fuzzySearch()"
[institutionFilterEnabled]="true" />
</div>
@@ -0,0 +1,47 @@
import { Component, computed, input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import { DfgPersonSummaryPage, TopicPageV2 } from '../../../api';
import { DfgProjectPage } from '../../../api/model/dfgProjectPage';
import { DfgInstitutionSummaryPage } from '../../../api/model/dfgInstitutionSummaryPage';
import { MatCardModule } from '@angular/material/card';
import { MatTabsModule } from '@angular/material/tabs';
import { ProjectFilterComponent } from '../project-filters/project-filters.component';
import { DfgProjectTableComponent } from '../dfg-project-table/dfg-project-table.component';
import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver';
@Component({
selector: 'app-dfg-projects',
imports: [
MatCardModule,
MatTabsModule,
ProjectFilterComponent,
DfgProjectTableComponent,
],
templateUrl: './dfg-projects.component.html',
styleUrl: './dfg-projects.component.scss',
})
export class DfgProjectsComponent {
dfgProjectPage = input.required<DfgProjectPage>();
selectedDfgInstitutionsPage = input.required<DfgInstitutionSummaryPage>();
selectedDfgAuthorsPage = input.required<DfgPersonSummaryPage>();
selectedTopicsPage = input.required<TopicPageV2>();
readonly dfgQueryParamKeys = projectQueryParamKeys;
constructor(
private readonly router: Router,
private readonly activatedRoute: ActivatedRoute,
) {}
ngOnInit(): void {
console.log('DFG PROJECTS', this.dfgProjectPage());
}
queryParamMap = toSignal(this.activatedRoute.queryParamMap, {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
readonly fuzzySearch = computed(
() => this.queryParamMap().get('fuzzy') === 'true',
);
}

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