feat(institution-membership): centralize institution-scoped access
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
- add a shared institution membership query with all, exact-year, and from-year modes - use the active membership cohort in the classifier, work classification access, person search, company connections, and author ranking - derive restricted access from the effective institution of the authenticated organization - make the company connections tab dynamically available and protect its backend endpoints - standardize person-list URLs and active-membership filter defaults - prevent caching of organization-dependent responses and refresh availability after organization changes - remove legacy UDE-specific ranking logic, display-name compatibility queries, and unused institution lookup code - update the work-classification metadata
This commit is contained in:
@@ -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,9 +37,7 @@ 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"
|
||||
@@ -205,6 +213,7 @@ TARGET_TOP_LEVEL_FIELDS = {
|
||||
"work_id",
|
||||
"title",
|
||||
"publication_year",
|
||||
"publication_type",
|
||||
"doi",
|
||||
"authors",
|
||||
"institutions",
|
||||
@@ -213,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",
|
||||
@@ -402,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),
|
||||
@@ -413,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))}")
|
||||
@@ -460,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
|
||||
|
||||
@@ -470,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)):
|
||||
@@ -858,108 +881,20 @@ def validate(result: dict[str, Any]) -> list[str]:
|
||||
return errors
|
||||
|
||||
|
||||
def institution_affiliation_filter(
|
||||
institution_id: str,
|
||||
institution_ror: str | None,
|
||||
institution_name: str,
|
||||
affiliation_year_gte: int,
|
||||
) -> dict[str, Any]:
|
||||
institution_matches: list[dict[str, Any]] = [
|
||||
{"term": {"affiliations.institution.id": institution_id}},
|
||||
{
|
||||
"match_phrase": {
|
||||
"affiliations.institution.display_name": institution_name
|
||||
}
|
||||
},
|
||||
]
|
||||
if institution_ror:
|
||||
institution_matches.insert(
|
||||
1,
|
||||
{"term": {"affiliations.institution.ror": institution_ror}},
|
||||
)
|
||||
|
||||
return {
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"bool": {
|
||||
"should": institution_matches,
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
{
|
||||
"range": {
|
||||
"affiliations.years": {"gte": affiliation_year_gte}
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def author_query(
|
||||
group: str,
|
||||
after: list[Any] | None,
|
||||
institution_id: str = UDE_ID,
|
||||
institution_ror: str | None = UDE_ROR,
|
||||
institution_name: str = UDE_NAME,
|
||||
affiliation_year_gte: int = AFFILIATION_YEAR_GTE,
|
||||
) -> dict[str, Any]:
|
||||
last_known = {
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {
|
||||
"match_phrase": {
|
||||
"last_known_institutions.display_name": institution_name
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
last_known_exists = {
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {"exists": {"field": "last_known_institutions.display_name"}},
|
||||
}
|
||||
}
|
||||
query = (
|
||||
{
|
||||
"bool": {
|
||||
"filter": [
|
||||
last_known,
|
||||
institution_affiliation_filter(
|
||||
institution_id,
|
||||
institution_ror,
|
||||
institution_name,
|
||||
affiliation_year_gte,
|
||||
),
|
||||
]
|
||||
}
|
||||
}
|
||||
if group == "known"
|
||||
else {
|
||||
"bool": {
|
||||
"filter": [
|
||||
institution_affiliation_filter(
|
||||
institution_id,
|
||||
institution_ror,
|
||||
institution_name,
|
||||
affiliation_year_gte,
|
||||
)
|
||||
],
|
||||
"must_not": [last_known_exists],
|
||||
}
|
||||
}
|
||||
)
|
||||
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:
|
||||
@@ -1096,6 +1031,7 @@ EXPECTED_MAPPING_TYPES = {
|
||||
"work_id": "keyword",
|
||||
"title": "text",
|
||||
"publication_year": "integer",
|
||||
"publication_type": "keyword",
|
||||
"doi": "keyword",
|
||||
"authors": "nested",
|
||||
"authors.id": "keyword",
|
||||
@@ -1593,43 +1529,37 @@ def classify(
|
||||
def collect_authors(
|
||||
es: ES,
|
||||
institution_id: str = UDE_ID,
|
||||
institution_ror: str | None = UDE_ROR,
|
||||
institution_name: str = UDE_NAME,
|
||||
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,
|
||||
institution_id,
|
||||
institution_ror,
|
||||
institution_name,
|
||||
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 {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 institution author count: {len(result)}")
|
||||
return result
|
||||
@@ -1824,8 +1754,6 @@ def run(
|
||||
report: dict[str, Any],
|
||||
selection_mode: str = SELECTION_AUTHOR_COHORT,
|
||||
institution_id: str = UDE_ID,
|
||||
institution_ror: str | None = UDE_ROR,
|
||||
institution_name: str = UDE_NAME,
|
||||
affiliation_year_gte: int = AFFILIATION_YEAR_GTE,
|
||||
work_year_gte: int | None = WORK_YEAR_GTE,
|
||||
preflight_only: bool = False,
|
||||
@@ -1862,8 +1790,6 @@ def run(
|
||||
authors = collect_authors(
|
||||
es,
|
||||
institution_id,
|
||||
institution_ror,
|
||||
institution_name,
|
||||
affiliation_year_gte,
|
||||
)
|
||||
batch_count = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE
|
||||
@@ -1977,8 +1903,6 @@ def main() -> None:
|
||||
),
|
||||
)
|
||||
parser.add_argument("--institution-id", default=UDE_ID)
|
||||
parser.add_argument("--institution-ror", default=UDE_ROR)
|
||||
parser.add_argument("--institution-name", default=UDE_NAME)
|
||||
parser.add_argument(
|
||||
"--affiliation-year-gte", type=int, default=AFFILIATION_YEAR_GTE
|
||||
)
|
||||
@@ -2010,19 +1934,12 @@ def main() -> None:
|
||||
if not institution_id.startswith("https://openalex.org/"):
|
||||
institution_id = f"https://openalex.org/{bare_id(institution_id)}"
|
||||
|
||||
institution_ror = nullable_text(args.institution_ror)
|
||||
institution_name = args.institution_name.strip()
|
||||
if args.selection_mode == SELECTION_AUTHOR_COHORT and not institution_name:
|
||||
raise SystemExit("--institution-name is required for author-cohort")
|
||||
|
||||
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,
|
||||
"institution_ror": institution_ror,
|
||||
"institution_name": institution_name,
|
||||
"affiliation_year_gte": args.affiliation_year_gte,
|
||||
"work_year_gte": work_year_gte,
|
||||
"all_work_years": args.all_work_years,
|
||||
@@ -2037,8 +1954,6 @@ def main() -> None:
|
||||
report,
|
||||
selection_mode=args.selection_mode,
|
||||
institution_id=institution_id,
|
||||
institution_ror=institution_ror,
|
||||
institution_name=institution_name,
|
||||
affiliation_year_gte=args.affiliation_year_gte,
|
||||
work_year_gte=work_year_gte,
|
||||
preflight_only=args.preflight_only,
|
||||
|
||||
+51
@@ -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}"
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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,
|
||||
@@ -36,19 +39,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(),
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -64,7 +71,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
|
||||
@@ -373,7 +380,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")
|
||||
@@ -619,7 +626,7 @@ async def static_stats_for_authors(
|
||||
)
|
||||
|
||||
results = []
|
||||
|
||||
|
||||
for author_id in author_ids:
|
||||
name = names_by_id.get(author_id, "")
|
||||
results.append(
|
||||
@@ -758,7 +765,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)
|
||||
|
||||
|
||||
@@ -1012,7 +1019,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],
|
||||
@@ -1027,11 +1034,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)
|
||||
|
||||
|
||||
@@ -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.",
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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."
|
||||
)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
@@ -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>;
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -147,6 +147,7 @@ export const routes: Routes = [
|
||||
'query',
|
||||
'page',
|
||||
'pageSize',
|
||||
'institutionId',
|
||||
'institutionName',
|
||||
'sortBy',
|
||||
'sortOrder',
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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 ?? '-';
|
||||
|
||||
|
||||
-5
@@ -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>
|
||||
|
||||
+28
-10
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
+3
-3
@@ -1103,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
|
||||
@@ -1192,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
|
||||
@@ -1476,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
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
|
||||
@@ -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$ };
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user