From 7e8b7eb2c00f0a045aaa5a4248672ddd353fa8ae Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 21 Jul 2026 13:48:48 +0200 Subject: [PATCH 01/26] removed sorting by fachliche zuordnung --- .../shared/ui/dfg-project-table/dfg-project-table.component.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts index dc166678..9c961758 100644 --- a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts +++ b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts @@ -126,8 +126,7 @@ export class DfgProjectTableComponent implements OnInit { { id: 'professional_classification', header: 'Fachliche Zuordnung', - type: 'accessor', - accessorKey: 'professional_classification', + type: 'display', cellTemplate: this.detailRowTmp(), }, From 81b768b244dbe7560aa20a7bac1c3b72ce109223 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 21 Jul 2026 13:50:43 +0200 Subject: [PATCH 02/26] added topic legend to projects filters --- .../project-filters.component.html | 11 ++++ .../project-filters.component.scss | 3 + .../project-filters.component.ts | 58 +++++++++++++++++++ 3 files changed, 72 insertions(+) diff --git a/webapp/src/app/shared/ui/project-filters/project-filters.component.html b/webapp/src/app/shared/ui/project-filters/project-filters.component.html index c04b5464..9e84960d 100644 --- a/webapp/src/app/shared/ui/project-filters/project-filters.component.html +++ b/webapp/src/app/shared/ui/project-filters/project-filters.component.html @@ -45,4 +45,15 @@ + @if (topicLegendGroups.length > 0) { + + + } diff --git a/webapp/src/app/shared/ui/project-filters/project-filters.component.scss b/webapp/src/app/shared/ui/project-filters/project-filters.component.scss index 94044ea1..76941729 100644 --- a/webapp/src/app/shared/ui/project-filters/project-filters.component.scss +++ b/webapp/src/app/shared/ui/project-filters/project-filters.component.scss @@ -2,6 +2,9 @@ display: flex; flex-direction: column; gap: 1rem; + ::ng-deep app-topic-legend .topic-legend { + width: 100%; + } } .select-area { diff --git a/webapp/src/app/shared/ui/project-filters/project-filters.component.ts b/webapp/src/app/shared/ui/project-filters/project-filters.component.ts index 22f41f3b..8d91cfe4 100644 --- a/webapp/src/app/shared/ui/project-filters/project-filters.component.ts +++ b/webapp/src/app/shared/ui/project-filters/project-filters.component.ts @@ -5,6 +5,12 @@ import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { DfgInstitutionSummaryPage } from '../../../api/model/dfgInstitutionSummaryPage'; import { DfgInstitutionSummary } from '../../../api/model/dfgInstitutionSummary'; +import { + buildTopicLegendGroups, + TopicLegendGroup, + TopicLegendTopic, +} from '../../../resolvers/utils/topic-legend'; +import { TopicLegendComponent } from '../topic-legend/topic-legend.component'; import { DfgPersonSummary, DfgPersonSummaryPage, @@ -35,6 +41,7 @@ import { SearchableTopicSelectComponent } from '../searchable-topic-select/searc SearchableYearSelectComponent, SelectedFiltersComponent, SearchableTopicSelectComponent, + TopicLegendComponent, ], templateUrl: './project-filters.component.html', styleUrl: './project-filters.component.scss', @@ -68,6 +75,15 @@ export class ProjectFilterComponent { showFundingStartFilter = input(true); showFundingEndFilter = input(false); showTopicFilter = input(true); + + subfieldLegendVisible = computed( + () => this.queryParamMap().get(this.queryParamKeys.legend) === 'true', + ); + subfieldLegendExpanded = computed( + () => + this.queryParamMap().get(this.queryParamKeys.legend_expanded) === 'true', + ); + queryParamMap = toSignal(this.router.routerState.root.queryParamMap, { initialValue: this.router.routerState.snapshot.root.queryParamMap, }); @@ -159,6 +175,7 @@ export class ProjectFilterComponent { this.selectedAuthors().find((a) => String(a.person_id) === value) ?.full_name ?? value, }, + { id: 'topics', queryParamKey: keys.topicId, @@ -217,6 +234,24 @@ export class ProjectFilterComponent { }); } }; + handleLegendVisibleChange = (visible: boolean): void => { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.legend]: visible ? 'true' : null, + }, + queryParamsHandling: 'merge', + }); + }; + + handleLegendExpandedChange = (expanded: boolean): void => { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.legend_expanded]: expanded ? 'true' : null, + }, + queryParamsHandling: 'merge', + }); + }; + handleInstitutionSelectChange = ( institution: DfgInstitutionSummary, ): void => { @@ -290,10 +325,33 @@ export class ProjectFilterComponent { [keys.institutionId]: null, [keys.authorId]: null, [keys.funding_start]: null, + [keys.topicId]: null, [keys.funding_end]: null, [keys.page]: 0, }, queryParamsHandling: 'merge', }); }; + + get topicLegendGroups(): TopicLegendGroup[] { + const topics = this.selectedTopics().map((topic) => + this.toTopicLegendTopic(topic), + ); + return buildTopicLegendGroups(topics); + } + private toTopicLegendTopic(topic: Topic): TopicLegendTopic { + return { + id: topic.id ?? topic.display_name ?? '', + name: topic.display_name ?? '', + field_id: topic.field?.id ?? null, + field_name: topic.field?.display_name ?? null, + field_description: null, + domain_id: topic.domain?.id ?? null, + domain_name: topic.domain?.display_name ?? null, + domain_description: null, + subfield_id: topic.subfield?.id ?? null, + subfield_name: topic.subfield?.display_name ?? null, + subfield_description: null, + }; + } } From ad83def6ab6c82e65fac76fbe986f9d8b5c6d046 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 21 Jul 2026 13:51:17 +0200 Subject: [PATCH 03/26] added new query param keys for legend visibility and expansion --- webapp/src/app/resolvers/dfg-projects.resolver.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webapp/src/app/resolvers/dfg-projects.resolver.ts b/webapp/src/app/resolvers/dfg-projects.resolver.ts index ab88d9c7..a1fcd3a0 100644 --- a/webapp/src/app/resolvers/dfg-projects.resolver.ts +++ b/webapp/src/app/resolvers/dfg-projects.resolver.ts @@ -13,6 +13,8 @@ export const projectQueryParamKeys = { topicId: 'topicId', sortBy: 'sort_by', sortDirection: 'sort_direction', + legend: 'legend', + legend_expanded: 'legend_expanded', } as const; const RESOLVING_PROJECT_PAGE_FOR_KEY = 'resolvingFor'; export const RESOLVING_PROJECT_PAGE_FOR = { From 3b926837d8ff59ef4ae40920c9b719249b05e83e Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 21 Jul 2026 13:51:37 +0200 Subject: [PATCH 04/26] adjusted legend visibility query params --- .../keywords-search/keywords-search.component.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index b698ea4e..1e30196d 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -962,8 +962,8 @@ export class KeywordsSearchComponent { const selected = this.parseKeywordList(queryParams.get('selected')); const source = queryParams.get('source') ?? ''; const view = queryParams.get('view') ?? 'llm'; - const legend = queryParams.get('legend') ?? 'on'; - const legendExpanded = queryParams.get('legendExpanded') ?? 'off'; + const legend = queryParams.get('legend') === 'true'; + const legendExpanded = queryParams.get('legendExpanded') === 'true'; const fuzzy = queryParams.get('fuzzy') === 'true'; this.isRestoringState = true; this.form.patchValue( @@ -975,8 +975,8 @@ export class KeywordsSearchComponent { { emitEvent: false }, ); this.keywordView.set(view as KeywordView); - this.subfieldLegendVisible.set(legend === 'on'); - this.subfieldLegendExpanded.set(legendExpanded === 'on'); + this.subfieldLegendVisible.set(legend); + this.subfieldLegendExpanded.set(legendExpanded); this.extractionSource.set(source as InputMode); this.topicMappingSearch.set(fuzzy); this.restoreStateFromSession(); @@ -1036,8 +1036,8 @@ export class KeywordsSearchComponent { url: this.toNullableParam(this.form.controls.urlInput.value), text: this.toNullableParam(this.form.controls.textInput.value), view: this.keywordView(), - legend: this.subfieldLegendVisible() ? 'on' : 'off', - legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off', + legend: this.subfieldLegendVisible() ? 'true' : 'false', + legendExpanded: this.subfieldLegendExpanded() ? 'true' : 'false', broad: this.serializeKeywords( this.getKeywordLabels(this.broadKeywords()), ), From c02d2e4744fcb3c6d5c0372c40bdc937cb93347a Mon Sep 17 00:00:00 2001 From: Roman Date: Wed, 22 Jul 2026 19:58:20 +0200 Subject: [PATCH 05/26] updated work-classification-script + small frontend fix --- .../classify_ude_works_to_index.py | 252 +++++++++++++++--- .../run_20260722_021910_049378.json | 50 ++++ .../research-profile.component.html | 2 +- 3 files changed, 268 insertions(+), 36 deletions(-) create mode 100644 llm_evaluations/basic_applied_experimental/run_reports/run_20260722_021910_049378.json diff --git a/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py b/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py index 329842c4..0b1de043 100644 --- a/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py +++ b/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py @@ -32,6 +32,10 @@ UDE_NAME = "University of Duisburg-Essen" AFFILIATION_YEAR_GTE = 2025 WORK_YEAR_GTE = 1950 +SELECTION_AUTHOR_COHORT = "author-cohort" +SELECTION_INSTITUTION_WORKS = "institution-works" +SELECTION_MODES = (SELECTION_AUTHOR_COHORT, SELECTION_INSTITUTION_WORKS) + AUTHOR_PAGE_SIZE = 1000 AUTHOR_BATCH_SIZE = 1000 WORK_PAGE_SIZE = 2000 @@ -854,7 +858,26 @@ def validate(result: dict[str, Any]) -> list[str]: return errors -def ude_affiliation_filter() -> dict[str, Any]: +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", @@ -863,21 +886,13 @@ def ude_affiliation_filter() -> dict[str, Any]: "filter": [ { "bool": { - "should": [ - {"term": {"affiliations.institution.id": UDE_ID}}, - {"term": {"affiliations.institution.ror": UDE_ROR}}, - { - "match_phrase": { - "affiliations.institution.display_name": UDE_NAME - } - }, - ], + "should": institution_matches, "minimum_should_match": 1, } }, { "range": { - "affiliations.years": {"gte": AFFILIATION_YEAR_GTE} + "affiliations.years": {"gte": affiliation_year_gte} } }, ] @@ -887,12 +902,21 @@ def ude_affiliation_filter() -> dict[str, Any]: } -def author_query(group: str, after: list[Any] | None) -> dict[str, Any]: +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": UDE_NAME} + "match_phrase": { + "last_known_institutions.display_name": institution_name + } }, } } @@ -903,11 +927,30 @@ def author_query(group: str, after: list[Any] | None) -> dict[str, Any]: } } query = ( - {"bool": {"filter": [last_known, ude_affiliation_filter()]}} + { + "bool": { + "filter": [ + last_known, + institution_affiliation_filter( + institution_id, + institution_ror, + institution_name, + affiliation_year_gte, + ), + ] + } + } if group == "known" else { "bool": { - "filter": [ude_affiliation_filter()], + "filter": [ + institution_affiliation_filter( + institution_id, + institution_ror, + institution_name, + affiliation_year_gte, + ) + ], "must_not": [last_known_exists], } } @@ -924,7 +967,22 @@ def author_query(group: str, after: list[Any] | None) -> dict[str, Any]: return body -def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]: +def work_query( + author_ids: list[str], + after: list[Any] | None, + work_year_gte: int | None = WORK_YEAR_GTE, +) -> dict[str, Any]: + filters: list[dict[str, Any]] = [ + { + "nested": { + "path": "authorships", + "query": {"terms": {"authorships.author.id": author_ids}}, + } + } + ] + if work_year_gte is not None: + filters.insert(0, {"range": {"publication_year": {"gte": work_year_gte}}}) + body: dict[str, Any] = { "size": WORK_PAGE_SIZE, "track_total_hits": False, @@ -964,15 +1022,7 @@ def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any] ], "query": { "bool": { - "filter": [ - {"range": {"publication_year": {"gte": WORK_YEAR_GTE}}}, - { - "nested": { - "path": "authorships", - "query": {"terms": {"authorships.author.id": author_ids}}, - } - }, - ] + "filter": filters } }, "sort": [{"id": "asc"}], @@ -982,6 +1032,36 @@ def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any] return body +def institution_work_query( + institution_id: str, + after: list[Any] | None, +) -> dict[str, Any]: + """Select all works attributed to an institution, like Publikationsliste.""" + body = work_query([], after) + body["query"] = { + "bool": { + "must": [ + { + "nested": { + "path": "authorships", + "query": { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [institution_id] + } + }, + } + }, + } + } + ] + } + } + return body + + def choose_work_hit( current: dict[str, Any] | None, candidate: dict[str, Any], @@ -1510,14 +1590,30 @@ def classify( raise StopPipeline(f"LLM unavailable for {work_id}: {error}") -def collect_authors(es: ES) -> list[str]: +def collect_authors( + es: ES, + institution_id: str = UDE_ID, + 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)) + 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) @@ -1535,7 +1631,7 @@ def collect_authors(es: ES) -> list[str]: raise StopPipeline("Missing author search_after") print(f"Authors {group}: {read}/{total}") result = sorted(ids) - print(f"Final UDE author count: {len(result)}") + print(f"Final institution author count: {len(result)}") return result @@ -1726,6 +1822,12 @@ def run( limit: int | None, workers: int, 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, ) -> None: if not ES_API_KEY.strip(): @@ -1749,17 +1851,34 @@ def run( api_key=LLM_API_KEY, timeout=REQUEST_TIMEOUT, ) - authors = collect_authors(es) - count = 0 warm = False - batches = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE - for start in range(0, len(authors), AUTHOR_BATCH_SIZE): + if selection_mode == SELECTION_INSTITUTION_WORKS: + work_batches: list[tuple[str, list[str] | None]] = [ + (f"Institution works: {institution_id}", None) + ] + else: + authors = collect_authors( + es, + institution_id, + institution_ror, + institution_name, + affiliation_year_gte, + ) + batch_count = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE + work_batches = [ + ( + f"Author batch {start // AUTHOR_BATCH_SIZE + 1}/{batch_count}", + authors[start : start + AUTHOR_BATCH_SIZE], + ) + for start in range(0, len(authors), AUTHOR_BATCH_SIZE) + ] + + for batch_label, author_ids in work_batches: if limit is not None and count >= limit: break - batch = authors[start : start + AUTHOR_BATCH_SIZE] - print(f"\nAuthor batch {start // AUTHOR_BATCH_SIZE + 1}/{batches}") + print(f"\n{batch_label}") after = None page = 0 @@ -1767,7 +1886,12 @@ def run( if limit is not None and count >= limit: break - result = es.search(WORKS_INDEX, work_query(batch, after)) + query = ( + institution_work_query(institution_id, after) + if author_ids is None + else work_query(author_ids, after, work_year_gte) + ) + result = es.search(WORKS_INDEX, query) hits = result.get("hits", {}).get("hits", []) if not hits: break @@ -1843,15 +1967,67 @@ def main() -> None: parser.add_argument("--limit", type=int) parser.add_argument("--workers", type=int, default=MAX_WORKERS) parser.add_argument("--preflight-only", action="store_true") + parser.add_argument( + "--selection-mode", + choices=SELECTION_MODES, + default=SELECTION_AUTHOR_COHORT, + help=( + "author-cohort selects works by current affiliated authors; " + "institution-works selects every work attributed to --institution-id" + ), + ) + parser.add_argument("--institution-id", default=UDE_ID) + parser.add_argument("--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 + ) + parser.add_argument("--work-year-gte", type=int, default=WORK_YEAR_GTE) + parser.add_argument( + "--all-work-years", + action="store_true", + help=( + "disable the publication-year filter in author-cohort mode, " + "including works without publication_year" + ), + ) args = parser.parse_args() if args.limit is not None and args.limit < 1: raise SystemExit("--limit must be at least 1") if args.workers < 1: raise SystemExit("--workers must be at least 1") + if args.affiliation_year_gte < 0: + raise SystemExit("--affiliation-year-gte must not be negative") + if args.work_year_gte < 0: + raise SystemExit("--work-year-gte must not be negative") + + work_year_gte = None if args.all_work_years else args.work_year_gte + + institution_id = args.institution_id.strip() + if not institution_id: + raise SystemExit("--institution-id must not be empty") + if not institution_id.startswith("https://openalex.org/"): + institution_id = f"https://openalex.org/{bare_id(institution_id)}" + + 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, + } + ) exit_code = 0 try: @@ -1859,6 +2035,12 @@ def main() -> None: args.limit, args.workers, 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, ) report["status"] = "completed" diff --git a/llm_evaluations/basic_applied_experimental/run_reports/run_20260722_021910_049378.json b/llm_evaluations/basic_applied_experimental/run_reports/run_20260722_021910_049378.json new file mode 100644 index 00000000..169d8c92 --- /dev/null +++ b/llm_evaluations/basic_applied_experimental/run_reports/run_20260722_021910_049378.json @@ -0,0 +1,50 @@ +{ + "run_id": "20260722_021910_049378", + "started_at": "2026-07-22T02:19:10Z", + "finished_at": "2026-07-22T09:26:37Z", + "duration_seconds": 25645.781, + "status": "completed", + "error": null, + "parameters": { + "limit": null, + "workers": 25, + "model": "gemma4-e4b", + "prompt_version": "frascati_hard_ranges_v2", + "target_index": "work-classifications", + "bulk_batch_size": 200, + "state_storage": "memory_only", + "preflight_only": false, + "selection_mode": "institution-works", + "institution_id": "https://openalex.org/I62318514", + "institution_ror": "https://ror.org/04mz5ra38", + "institution_name": "University of Duisburg-Essen", + "affiliation_year_gte": 2025, + "work_year_gte": 1950 + }, + "classification": { + "llm_completed": 32189, + "valid": 32189, + "invalid": 0, + "categories": { + "applied_research": 10001, + "basic_research": 17089, + "experimental_development": 1813, + "non_research": 3286 + }, + "validation_errors": {} + }, + "indexing": { + "newly_indexed": 32189, + "bulk_requests": 183, + "bulk_documents_submitted": 32589, + "bulk_failures": 0 + }, + "token_usage": { + "prompt_tokens": 119788565, + "cached_prompt_tokens": 110500800, + "uncached_prompt_tokens": 9287765, + "completion_tokens": 29352270, + "real_total_usage": 38640035 + }, + "throughput_indexed_per_hour": 4518.5 +} diff --git a/webapp/src/app/modules/publication-detail/research-profile/research-profile.component.html b/webapp/src/app/modules/publication-detail/research-profile/research-profile.component.html index 54400cd9..80bf9d20 100644 --- a/webapp/src/app/modules/publication-detail/research-profile/research-profile.component.html +++ b/webapp/src/app/modules/publication-detail/research-profile/research-profile.component.html @@ -41,7 +41,7 @@ + [disabled]="false" /> } From 720e6f96123816ba5411146f394378fef07d5134 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 22 Jul 2026 23:35:57 +0200 Subject: [PATCH 06/26] added new endpoint for EU Cordis projects retrieval --- service/src/main/inse/main.py | 4 + .../projects/eu_cordis_projects_client.py | 1027 +++++++++++++++++ .../eu_cordis_projects_enrichment_client.py | 281 ----- .../inse/projects/eu_organizations/model.py | 0 service/src/main/inse/projects/logic.py | 134 ++- service/src/main/inse/projects/model.py | 267 ++++- .../inse/projects/projects_search_client.py | 30 +- service/src/main/inse/projects/router.py | 143 ++- service/src/main/inse/projects/service.py | 97 +- .../projects/test_eu_cordis_search_client.py | 364 ++++++ 10 files changed, 2054 insertions(+), 293 deletions(-) create mode 100644 service/src/main/inse/projects/eu_cordis_projects_client.py delete mode 100644 service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py create mode 100644 service/src/main/inse/projects/eu_organizations/model.py create mode 100644 service/src/main/inse/projects/test_eu_cordis_search_client.py diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 083faa6d..b2b41da8 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -60,6 +60,9 @@ from inse.topics.v2.router import router as topics_v2_router from inse.projects.dfg_institutions.router import router as dfg_institutions_router from inse.projects.dfg_persons.router import router as dfg_persons_router + +from inse.projects.eu_organizations.router import router as eu_organizations_router + logger = logging.getLogger(__name__) ### startup @@ -118,6 +121,7 @@ app.include_router(dfg_institutions_router) app.include_router(dfg_persons_router) app.include_router(bookmarks_router) +app.include_router(eu_organizations_router) app.add_middleware( ETagCacheMiddleware, ttl=120, # 2 minutes expiration time diff --git a/service/src/main/inse/projects/eu_cordis_projects_client.py b/service/src/main/inse/projects/eu_cordis_projects_client.py new file mode 100644 index 00000000..8efd3813 --- /dev/null +++ b/service/src/main/inse/projects/eu_cordis_projects_client.py @@ -0,0 +1,1027 @@ +import logging +import asyncio +from typing import Any, Dict, List, Optional, Union, Tuple, Set +from collections import defaultdict +from inse.config import get_settings +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex +from inse.authors.v2.model import AuthorPage +from inse.authors.v2.service import get_authors_by_ids +# Import base models +from inse.models.cordis_eu_project import CordisEuProject + +# Import FP7 models +from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project +from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization +from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication +from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR +from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary +from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic +from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink +from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc +from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis +from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails + +# Import H2020 models +from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project +from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization +from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication +from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable +from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary +from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic +from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink +from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc +from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis +from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI +from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails + +# Import Horizon Europe models +from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject +from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization +from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication +from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable +from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary +from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic +from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink +from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc +from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis +from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails + +settings = get_settings() +logger = logging.getLogger(__name__) +logger.setLevel(settings.logging_level) + +# Entity config +_FP7_ENTITY_CONFIGS = [ + {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, "model_class": Fp7Organization}, + {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_FP7_PUBLICATIONS, "model_class": Fp7Publication}, + {"key": "iprs", "index_pattern": ESIndex.CORDIS_EU_FP7_PROJECT_IPRS, "model_class": Fp7ProjectIPR}, + {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_FP7_REPORT_SUMMARIES, "model_class": Fp7ReportSummary}, + {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_FP7_TOPICS, "model_class": Fp7Topic}, + {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_FP7_WEB_LINKS, "model_class": Fp7WebLink}, + {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_FP7_EUROSCIVOC, "model_class": Fp7EurosciVoc}, + {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_FP7_LEGAL_BASIS, "model_class": Fp7LegalBasis}, +] + +_H2020_ENTITY_CONFIGS = [ + {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, "model_class": H2020Organization}, + {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, "model_class": H2020Publication}, + {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_DELIVERABLES, "model_class": H2020Deliverable}, + {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES, "model_class": H2020ReportSummary}, + {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, "model_class": H2020Topic}, + {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_WEB_LINKS, "model_class": H2020WebLink}, + {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, "model_class": H2020EurosciVoc}, + {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_LEGAL_BASIS, "model_class": H2020LegalBasis}, + {"key": "erc_principal_investigators", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ERC_PIS, "model_class": H2020ErcPI}, +] + +_HEU_ENTITY_CONFIGS = [ + {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, "model_class": HEUOrganization}, + {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, "model_class": HEUPublication}, + {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_DELIVERABLES, "model_class": HEUDeliverable}, + {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES, "model_class": HEUReportSummary}, + {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, "model_class": HEUTopic}, + {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_WEB_LINKS, "model_class": HEUWebLink}, + {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc}, + {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis}, +] + +async def get_enriched_cordis_project_by_id( + project_id: str, +) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: + """ + Fetches and enriches a single Cordis EU project by its ID across all programme types. + + Args: + project_id: The project ID to fetch. + + Returns: + The enriched detailed project model, or None if not found. + """ + if not project_id: + return None + + query = {"bool": {"filter": [{"term": {"id": project_id}}]}} + + response = await elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + size=1, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + logger.info(f"No project found with ID: {project_id}") + return None + + hit = hits[0] + index = hit.get("_index", "") + source = hit.get("_source", {}) + + program_type = _determine_program_type_from_index(index) + + enrichers = { + "fp7": _enrich_fp7_project, + "h2020": _enrich_h2020_project, + "heu": _enrich_heu_project, + } + + enricher = enrichers.get(program_type) + if enricher is None: + logger.warning(f"Unknown programme type for index: {index}") + return CordisEuProject.model_validate(source) + + return await enricher(project_id, source) + +# helpers +def _determine_program_type_from_index(index: str) -> str: + """Determines the programme type from the Elasticsearch index name.""" + index_lower = index.lower() + if "fp7" in index_lower: + return "fp7" + if "horizon_2020" in index_lower: + return "h2020" + if "heu" in index_lower or "horizon_europe" in index_lower: + return "heu" + return "unknown" + + +async def _fetch_related_entities_parallel( + project_id: str, + entity_configs: List[Dict[str, Any]], +) -> Dict[str, List[Any]]: + """ + Fetches all related entity types for a project in parallel. + + Args: + project_id: The project ID to fetch entities for. + entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'. + + Returns: + Dictionary mapping each config 'key' to a list of validated entities. + """ + async def _fetch_one(config: Dict[str, Any]): + entities = await _fetch_related_entities( + project_ids=[project_id], + index_pattern=config["index_pattern"], + model_class=config["model_class"], + ) + return config["key"], entities.get(project_id, []) + + tasks = [_fetch_one(cfg) for cfg in entity_configs] + completed = await asyncio.gather(*tasks, return_exceptions=True) + + results: Dict[str, List[Any]] = {} + for cfg, res in zip(entity_configs, completed): + key = cfg["key"] + if isinstance(res, Exception): + logger.error(f"Parallel fetch failed for '{key}': {res}") + results[key] = [] + else: + key_name, data = res + results[key_name] = data + + return results + + +async def _fetch_related_entities( + project_ids: List[str], + index_pattern: str, + model_class: Any, +) -> Dict[str, List[Any]]: + """ + Fetches and groups related entities from Elasticsearch by project ID. + + Args: + project_ids: List of project IDs to fetch entities for. + index_pattern: The index pattern to search (supports wildcards). + model_class: The Pydantic model class to validate against. + + Returns: + Dictionary mapping project IDs to lists of validated entities. + """ + query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} + + try: + response = await elasticsearch.search( + query=query, + index=index_pattern, + cluster=ESCluster.INSE, + size=10000, + ) + except Exception as e: + logger.warning(f"Failed to fetch from {index_pattern}: {e}") + return {} + + grouped: Dict[str, List[Any]] = {} + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + + if not project_id: + continue + + grouped.setdefault(project_id, []) + + try: + entity = model_class.model_validate(source) + grouped[project_id].append(entity) + except Exception as e: + logger.warning(f"Failed to validate {model_class.__name__} for project {project_id}: {e}") + + return grouped + + +async def _enrich_fp7_project( + project_id: str, + project_source: Dict[str, Any], +) -> Optional[Fp7ProjectDetails]: + """Enriches a single FP7 project with all related data.""" + try: + project = Fp7Project.model_validate(project_source) + except Exception as e: + logger.error(f"Failed to validate FP7 project {project_id}: {e}") + return None + + related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS) + + return Fp7ProjectDetails.from_project_with_relations(project=project, **related) + + +async def _enrich_h2020_project( + project_id: str, + project_source: Dict[str, Any], +) -> Optional[H2020ProjectDetails]: + """Enriches a single H2020 project with all related data.""" + try: + project = H2020Project.model_validate(project_source) + except Exception as e: + logger.error(f"Failed to validate H2020 project {project_id}: {e}") + return None + + related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS) + + return H2020ProjectDetails.from_project_with_relations(project=project, **related) + + +async def _enrich_heu_project( + project_id: str, + project_source: Dict[str, Any], +) -> Optional[HEUProjectDetails]: + """Enriches a single Horizon Europe project with all related data.""" + try: + project = HEUProject.model_validate(project_source) + except Exception as e: + logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}") + return None + + related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS) + + return HEUProjectDetails.from_project_with_relations(project=project, **related) + + + + +from inse.projects.model import ( + EuCordisProjectType, + EuCordisProjectSearchPage, + EuCordisProjectSummary, + EuCordisOrganizationSummary, + EuCordisTopicSummary, + EuCordisEurosciVocSummary, +) +from inse.projects.logic import ( + get_eu_project_ids_by_openalex_topic_ids, + get_openalex_topics_for_eu_projects, +) + +def _eu_project_type_index_filter( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Optional[Dict[str, Any]]: + should_clauses = [] + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + should_clauses.append( + { + "bool": { + "filter": [ + {"term": {"_index": project_type.to_project_index().value}}, + {"terms": {"id": project_ids}}, + ] + } + } + ) + + if not should_clauses: + return None + + return { + "bool": { + "should": should_clauses, + "minimum_should_match": 1, + } + } + + +def _eu_year_filters(field: str, years: List[str]) -> Dict[str, Any]: + should = [] + + for year in years: + year = str(year).strip() + if not year: + continue + + should.append( + { + "range": { + field: { + "gte": f"{year}-01-01", + "lte": f"{year}-12-31", + } + } + } + ) + + return { + "bool": { + "should": should, + "minimum_should_match": 1, + } + } + + +def _eu_sort_field(sort_by: str) -> str: + mapping = { + "title": "title.keyword", + "funding_start": "startDate", + "funding_end": "endDate", + "funding_amount": "ecMaxContribution", + "id": "id", + "project_type": "_index", + } + return mapping.get(sort_by, "title.keyword") + + +async def get_eu_project_ids_by_organization_filters( + project_types: List[EuCordisProjectType], + organization_ids: Optional[List[str]] = None, + organization_names: Optional[List[str]] = None, +) -> Dict[EuCordisProjectType, List[str]]: + """ + Returns project IDs matching ALL selected organizations. + If organization_ids=[A,B], a project must have both A and B. + Same semantics requested as DFG topic filters. + """ + organization_ids = [x for x in (organization_ids or []) if str(x).strip()] + organization_names = [x for x in (organization_names or []) if str(x).strip()] + + if not organization_ids and not organization_names: + return {} + + result: Dict[EuCordisProjectType, List[str]] = {} + + for project_type in project_types: + project_org_matches: Dict[str, Set[str]] = defaultdict(set) + + should = [] + + if organization_ids: + should.append({"terms": {"organisationID": organization_ids}}) + + for name in organization_names: + should.append( + { + "match": { + "name": { + "query": name, + "operator": "and", + } + } + } + ) + + response = await elasticsearch.search( + index=project_type.to_organization_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["projectID", "organisationID", "name"], + "query": { + "bool": { + "should": should, + "minimum_should_match": 1, + } + }, + }, + ) + + hits = response.get("hits", {}).get("hits", []) + + for hit in hits: + source = hit.get("_source", {}) + project_id = source.get("projectID") + if not project_id: + continue + + organisation_id = source.get("organisationID") + name = source.get("name") + + if organisation_id in organization_ids: + project_org_matches[project_id].add(f"id:{organisation_id}") + + for org_name in organization_names: + if name and org_name.lower() in name.lower(): + project_org_matches[project_id].add(f"name:{org_name.lower()}") + + required = {f"id:{x}" for x in organization_ids} + required.update({f"name:{x.lower()}" for x in organization_names}) + + result[project_type] = [ + project_id + for project_id, found in project_org_matches.items() + if required.issubset(found) + ] + + return result + +async def get_eu_organizations_for_projects( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], List[EuCordisOrganizationSummary]]: + lookup: Dict[Tuple[EuCordisProjectType, str], List[EuCordisOrganizationSummary]] = {} + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + response = await elasticsearch.search( + index=project_type.to_organization_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": [ + "id", + "organisationID", + "name", + "shortName", + "country", + "city", + "role", + "activityType", + "projectID", + "ecContribution", + "totalCost", + ], + "query": { + "terms": { + "projectID": project_ids + } + }, + "sort": [ + {"order": {"order": "asc", "unmapped_type": "integer"}} + ], + }, + ) + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if not project_id: + continue + + lookup.setdefault((project_type, project_id), []).append( + EuCordisOrganizationSummary.from_es_source(source) + ) + + return lookup + + +async def get_eu_cordis_topics_for_projects( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], List[EuCordisTopicSummary]]: + lookup: Dict[Tuple[EuCordisProjectType, str], List[EuCordisTopicSummary]] = {} + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + response = await elasticsearch.search( + index=project_type.to_cordis_topic_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["id", "projectID", "title", "topic"], + "query": { + "terms": { + "projectID": project_ids + } + }, + }, + ) + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if not project_id: + continue + + lookup.setdefault((project_type, project_id), []).append( + EuCordisTopicSummary.from_es_source(source) + ) + + return lookup + + +async def get_eu_euroscivoc_for_projects( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], List[EuCordisEurosciVocSummary]]: + lookup: Dict[Tuple[EuCordisProjectType, str], List[EuCordisEurosciVocSummary]] = {} + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + response = await elasticsearch.search( + index=project_type.to_euroscivoc_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["id", "projectID", "code", "title", "description", "path"], + "query": { + "terms": { + "projectID": project_ids + } + }, + }, + ) + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if not project_id: + continue + + lookup.setdefault((project_type, project_id), []).append( + EuCordisEurosciVocSummary.from_es_source(source) + ) + + return lookup + + +async def search_eu_cordis_projects( + page: int, + size: int, + project_types: Optional[List[EuCordisProjectType]] = None, + organization_ids: Optional[List[str]] = None, + organization_names: Optional[List[str]] = None, + author_project_ids: Optional[List[str]] = None, + keywords: Optional[List[str]] = None, + topic_ids: Optional[List[str]] = None, + filter_topic_ids: Optional[List[str]] = None, + title: Optional[str] = None, + funding_start_years: Optional[List[str]] = None, + funding_end_years: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + framework_programmes: Optional[List[str]] = None, + funding_schemes: Optional[List[str]] = None, + statuses: Optional[List[str]] = None, + sort_by: str = "title", + sort_direction: str = "asc", + fuzzy: bool = False, +) -> EuCordisProjectSearchPage: + """ + Generic EU CORDIS project search across FP7, H2020 and Horizon Europe. + Mirrors DFG behavior: + - fuzzy=True + topic_ids => OpenAlex topic mapping lookup + - filter_topic_ids are always applied independently + - selected organizations/topics must ALL match + """ + if not project_types: + project_types = [ + EuCordisProjectType.FP7, + EuCordisProjectType.H2020, + EuCordisProjectType.HEU, + ] + + indices = [project_type.to_project_index() for project_type in project_types] + + must_clauses: List[Dict[str, Any]] = [] + + # === Author filter resolved in service layer === + if author_project_ids is not None: + if not author_project_ids: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append({"terms": {"id": author_project_ids}}) + + # === Primary search: fuzzy OpenAlex topics or raw keywords === + if fuzzy and topic_ids: + topic_project_ids_by_type = await get_eu_project_ids_by_openalex_topic_ids( + project_types=project_types, + topic_ids=topic_ids, + ) + + topic_filter = _eu_project_type_index_filter(topic_project_ids_by_type) + if not topic_filter: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append(topic_filter) + + elif keywords: + keyword_clauses = [] + + for keyword in keywords: + keyword = keyword.strip() + if not keyword: + continue + + keyword_clauses.append( + { + "bool": { + "should": [ + { + "multi_match": { + "query": keyword, + "fields": [ + "title^4", + "acronym^3", + "objective^2", + "keywords^2", + ], + "type": "phrase_prefix", + "max_expansions": 100, + } + }, + { + "wildcard": { + "topics": { + "value": f"*{keyword}*", + "case_insensitive": True, + } + } + }, + ], + "minimum_should_match": 1, + } + } + ) + + if keyword_clauses: + must_clauses.append({"bool": {"must": keyword_clauses}}) + + # === Independent OpenAlex topic filters === + if filter_topic_ids: + filter_topic_project_ids_by_type = await get_eu_project_ids_by_openalex_topic_ids( + project_types=project_types, + topic_ids=filter_topic_ids, + ) + + topic_filter = _eu_project_type_index_filter(filter_topic_project_ids_by_type) + if not topic_filter: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append(topic_filter) + + # === Organization filters: all selected organizations must match === + if organization_ids or organization_names: + org_project_ids_by_type = await get_eu_project_ids_by_organization_filters( + project_types=project_types, + organization_ids=organization_ids, + organization_names=organization_names, + ) + + org_filter = _eu_project_type_index_filter(org_project_ids_by_type) + if not org_filter: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append(org_filter) + + # === Title === + if title: + must_clauses.append( + { + "multi_match": { + "query": title, + "fields": ["title^4", "acronym^2"], + "type": "phrase_prefix", + "max_expansions": 100, + } + } + ) + + # === Funding dates === + if funding_start_years: + must_clauses.append(_eu_year_filters("startDate", funding_start_years)) + + if funding_end_years: + must_clauses.append(_eu_year_filters("endDate", funding_end_years)) + + # === Project core filters === + if framework_programmes: + must_clauses.append({"terms": {"frameworkProgramme": framework_programmes}}) + + if funding_schemes: + must_clauses.append({"terms": {"fundingScheme": funding_schemes}}) + + if statuses: + must_clauses.append({"terms": {"status": statuses}}) + + # === Country filter requires organization lookup === + if countries: + country_project_ids_by_type: Dict[EuCordisProjectType, List[str]] = {} + + for project_type in project_types: + response = await elasticsearch.search( + index=project_type.to_organization_index(), + cluster=ESCluster.INSE, + body={ + "size": 10000, + "_source": ["projectID"], + "query": { + "terms": { + "country": countries + } + }, + }, + ) + + country_project_ids_by_type[project_type] = list( + { + hit.get("_source", {}).get("projectID") + for hit in response.get("hits", {}).get("hits", []) + if hit.get("_source", {}).get("projectID") + } + ) + + country_filter = _eu_project_type_index_filter(country_project_ids_by_type) + if not country_filter: + return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size) + + must_clauses.append(country_filter) + + query = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}} + + sort_direction = sort_direction.lower() + if sort_direction not in ["asc", "desc"]: + sort_direction = "asc" + + sort_field = _eu_sort_field(sort_by.strip().lower()) + response = await elasticsearch.search( + index=indices, + cluster=ESCluster.INSE, + body={ + "size": size, + "from": page * size, + "track_total_hits": True, + "_source": [ + "id", + "title", + "acronym", + "objective", + "keywords", + "frameworkProgramme", + "fundingScheme", + "status", + "startDate", + "endDate", + "ecMaxContribution", + "totalCost", + ], + "query": query, + "sort": [ + { + sort_field: { + "order": sort_direction, + "missing": "_last", + "unmapped_type": "keyword" if sort_field.endswith(".keyword") else "date", + } + } + ], + }, + ) + + hits = response.get("hits", {}).get("hits", []) + total = response.get("hits", {}).get("total", {}).get("value", 0) + + project_ids_by_type: Dict[EuCordisProjectType, List[str]] = defaultdict(list) + + for hit in hits: + project_type = EuCordisProjectType.from_index_name(hit.get("_index", "")) + project_id = hit.get("_source", {}).get("id") + if project_id: + project_ids_by_type[project_type].append(project_id) + authors_lookup = await get_openalex_authors_for_projects_ids(project_ids_by_type) + organizations_lookup = await get_eu_organizations_for_projects(project_ids_by_type) + cordis_topics_lookup = await get_eu_cordis_topics_for_projects(project_ids_by_type) + euroscivoc_lookup = await get_eu_euroscivoc_for_projects(project_ids_by_type) + openalex_topics_lookup = await get_openalex_topics_for_eu_projects(project_ids_by_type) + + elements: List[EuCordisProjectSummary] = [] + + for hit in hits: + source = hit.get("_source", {}) + project_type = EuCordisProjectType.from_index_name(hit.get("_index", "")) + project_id = source.get("id") + + raw_topic_matches = openalex_topics_lookup.get((project_type, project_id), []) + raw_topic_matches = sorted( + raw_topic_matches, + key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"), + ) + + topics = [ + EuCordisProjectSummary.topic_from_match(match) + for match in raw_topic_matches + if isinstance(match, dict) + ] + elements.append( + EuCordisProjectSummary.from_hit( + hit=hit, + authors=authors_lookup.get((project_type, project_id), AuthorPage(elements=[], total=0, page=0, size=0)), + organizations=organizations_lookup.get((project_type, project_id), []), + cordis_topics=cordis_topics_lookup.get((project_type, project_id), []), + eurosci_voc=euroscivoc_lookup.get((project_type, project_id), []), + topics=topics, + ) + ) + return EuCordisProjectSearchPage( + elements=elements, + total=total, + page=page, + size=size, + ) + +def _to_openalex_doi_url(raw_doi: str) -> str: + """CORDIS stores bare DOIs (e.g. '10.1093/toxsci/kfs018'); + OpenAlex works index stores full URLs ('https://doi.org/10.1093/toxsci/kfs018').""" + raw_doi = raw_doi.strip() + if raw_doi.startswith("http://") or raw_doi.startswith("https://"): + return raw_doi + return f"https://doi.org/{raw_doi}" + +async def get_dois_by_cordis_eu_project_id(project_id: str) -> List[str]: + """Retrieves the raw DOIs of publications associated with a given CORDIS EU project ID.""" + query = {"bool": {"filter": [{"term": {"projectID": project_id}}]}} + + response = await elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + cluster=ESCluster.INSE, + source=["doi","qaProcessedDoi"], + size=10000, + ) + + dois = [] + for hit in response.get("hits", {}).get("hits", []): + doi = hit.get("_source", {}).get("doi") + qa_processed_doi = hit.get("_source", {}).get("qaProcessedDoi") + if doi: + dois.append(doi) + if qa_processed_doi: + dois.append(qa_processed_doi) + return list(set(dois)) # Remove duplicates + +async def get_openalex_author_ids_by_dois( + dois: List[str], +) -> Dict[str, List[str]]: + """Retrieves the OpenAlex author IDs (full URL form) authoring works for each + given (raw, non-prefixed) DOI. Returns a mapping of the *original raw DOI* + (as passed in) -> list of author_ids, so callers can trace authors back to + whatever the DOI was associated with (e.g. a project).""" + if not dois: + return {} + + url_to_raw = { + _to_openalex_doi_url(doi.lower()): doi + for doi in dois + } + + doi_urls = list(url_to_raw.keys()) + + query = { + "bool": { + "filter": [ + { + "terms": { + "doi": doi_urls + } + } + ] + } + } + + response = await elasticsearch.search( + index=ESIndex.OPENALEX_WORKS_WILDCARD, + source=["doi", "authorships.author.id"], + query=query, + size=10000, + cluster=ESCluster.NES, + ) + result: Dict[str, List[str]] = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + doi_url = source.get("doi") + raw_doi = url_to_raw.get(doi_url) + if not raw_doi: + continue + author_ids = [ + authorship.get("author", {}).get("id") + for authorship in source.get("authorships", []) + if authorship.get("author", {}).get("id") + ] + result.setdefault(raw_doi, []).extend(author_ids) + + return result + + +async def get_openalex_authors_for_cordis_project_ids( + project_ids: List[str], +) -> Dict[str, AuthorPage]: + """Returns a mapping of project_id -> AuthorPage for a batch of projects.""" + if not project_ids: + return {} + + query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} + response = await elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + cluster=ESCluster.INSE, + source=["projectID", "doi","qaProcessedDoi"], + size=10000, + ) + dois_by_project: Dict[str, Set[str]] = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + pid = source.get("projectID") + doi = source.get("doi") + qa_processed_doi = source.get("qaProcessedDoi") + if pid: + dois_by_project.setdefault(pid, set()) + if doi: + dois_by_project[pid].add(doi) + elif qa_processed_doi: + dois_by_project[pid].add(qa_processed_doi) + + all_dois = list({doi for dois in dois_by_project.values() for doi in dois}) + + # single ES call for the whole batch, keyed by raw DOI + author_ids_by_doi = await get_openalex_author_ids_by_dois(dois=all_dois) + + # aggregate per project, dedupe author_ids within a project + author_ids_by_project: Dict[str, List[str]] = {} + for pid, dois in dois_by_project.items(): + project_author_ids: Set[str] = set() + for doi in dois: + project_author_ids.update(author_ids_by_doi.get(doi, [])) + author_ids_by_project[pid] = list(project_author_ids) + + # single ES call to fetch all Author objects across every project + all_author_ids = list({aid for ids in author_ids_by_project.values() for aid in ids}) + + author_page = await get_authors_by_ids(author_ids=all_author_ids) + authors_by_id = {author.id: author for author in author_page.elements} + + # split the fetched authors back out per project + result: Dict[str, AuthorPage] = {} + for pid in project_ids: + ids_for_project = author_ids_by_project.get(pid, []) + authors_for_project = [ + authors_by_id[aid] for aid in ids_for_project if aid in authors_by_id + ] + result[pid] = AuthorPage( + elements=authors_for_project, + total=len(authors_for_project), + page=0, + size=len(authors_for_project), + ) + + return result + +async def get_openalex_authors_for_projects_ids( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], AuthorPage]: + """Adapts get_openalex_authors_for_cordis_project_ids to the + (project_type, project_id)-keyed lookup convention used across this module.""" + all_project_ids = [ + pid for pids in project_ids_by_type.values() for pid in pids + ] + if not all_project_ids: + return {} + + # NOTE: get_openalex_authors_for_cordis_project_ids is keyed purely by project_id, + # not (type, id). This assumes project_id is globally unique across FP7/H2020/HEU. + author_pages_by_project_id = await get_openalex_authors_for_cordis_project_ids( + project_ids=all_project_ids + ) + + result: Dict[Tuple[EuCordisProjectType, str], AuthorPage] = {} + for project_type, project_ids in project_ids_by_type.items(): + for pid in project_ids: + result[(project_type, pid)] = author_pages_by_project_id.get( + pid, AuthorPage(elements=[], total=0, page=0, size=0) + ) + return result \ No newline at end of file diff --git a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py deleted file mode 100644 index cb120418..00000000 --- a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py +++ /dev/null @@ -1,281 +0,0 @@ -import logging -import asyncio -from typing import Any, Dict, List, Optional, Union - -from inse.config import get_settings -from inse.integrations import elasticsearch -from inse.model import ESCluster, ESIndex - -# Import base models -from inse.models.cordis_eu_project import CordisEuProject - -# Import FP7 models -from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project -from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization -from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication -from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR -from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary -from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic -from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink -from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc -from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis -from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails - -# Import H2020 models -from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project -from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization -from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication -from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable -from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary -from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic -from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink -from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc -from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis -from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI -from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails - -# Import Horizon Europe models -from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject -from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization -from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication -from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable -from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary -from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic -from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink -from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc -from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis -from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails - -settings = get_settings() -logger = logging.getLogger(__name__) -logger.setLevel(settings.logging_level) - -# Entity config -_FP7_ENTITY_CONFIGS = [ - {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, "model_class": Fp7Organization}, - {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_FP7_PUBLICATIONS, "model_class": Fp7Publication}, - {"key": "iprs", "index_pattern": ESIndex.CORDIS_EU_FP7_PROJECT_IPRS, "model_class": Fp7ProjectIPR}, - {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_FP7_REPORT_SUMMARIES, "model_class": Fp7ReportSummary}, - {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_FP7_TOPICS, "model_class": Fp7Topic}, - {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_FP7_WEB_LINKS, "model_class": Fp7WebLink}, - {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_FP7_EUROSCIVOC, "model_class": Fp7EurosciVoc}, - {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_FP7_LEGAL_BASIS, "model_class": Fp7LegalBasis}, -] - -_H2020_ENTITY_CONFIGS = [ - {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, "model_class": H2020Organization}, - {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, "model_class": H2020Publication}, - {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_DELIVERABLES, "model_class": H2020Deliverable}, - {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES, "model_class": H2020ReportSummary}, - {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, "model_class": H2020Topic}, - {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_WEB_LINKS, "model_class": H2020WebLink}, - {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, "model_class": H2020EurosciVoc}, - {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_LEGAL_BASIS, "model_class": H2020LegalBasis}, - {"key": "erc_principal_investigators", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ERC_PIS, "model_class": H2020ErcPI}, -] - -_HEU_ENTITY_CONFIGS = [ - {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, "model_class": HEUOrganization}, - {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, "model_class": HEUPublication}, - {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_DELIVERABLES, "model_class": HEUDeliverable}, - {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES, "model_class": HEUReportSummary}, - {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, "model_class": HEUTopic}, - {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_WEB_LINKS, "model_class": HEUWebLink}, - {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc}, - {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis}, -] - -async def get_enriched_cordis_project_by_id( - project_id: str, -) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: - """ - Fetches and enriches a single Cordis EU project by its ID across all programme types. - - Args: - project_id: The project ID to fetch. - - Returns: - The enriched detailed project model, or None if not found. - """ - if not project_id: - return None - - query = {"bool": {"filter": [{"term": {"id": project_id}}]}} - - response = await elasticsearch.search( - query=query, - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - cluster=ESCluster.INSE, - size=1, - ) - - hits = response.get("hits", {}).get("hits", []) - if not hits: - logger.info(f"No project found with ID: {project_id}") - return None - - hit = hits[0] - index = hit.get("_index", "") - source = hit.get("_source", {}) - - program_type = _determine_program_type_from_index(index) - - enrichers = { - "fp7": _enrich_fp7_project, - "h2020": _enrich_h2020_project, - "heu": _enrich_heu_project, - } - - enricher = enrichers.get(program_type) - if enricher is None: - logger.warning(f"Unknown programme type for index: {index}") - return CordisEuProject.model_validate(source) - - return await enricher(project_id, source) - -# helpers -def _determine_program_type_from_index(index: str) -> str: - """Determines the programme type from the Elasticsearch index name.""" - index_lower = index.lower() - if "fp7" in index_lower: - return "fp7" - if "horizon_2020" in index_lower: - return "h2020" - if "heu" in index_lower or "horizon_europe" in index_lower: - return "heu" - return "unknown" - - -async def _fetch_related_entities_parallel( - project_id: str, - entity_configs: List[Dict[str, Any]], -) -> Dict[str, List[Any]]: - """ - Fetches all related entity types for a project in parallel. - - Args: - project_id: The project ID to fetch entities for. - entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'. - - Returns: - Dictionary mapping each config 'key' to a list of validated entities. - """ - async def _fetch_one(config: Dict[str, Any]): - entities = await _fetch_related_entities( - project_ids=[project_id], - index_pattern=config["index_pattern"], - model_class=config["model_class"], - ) - return config["key"], entities.get(project_id, []) - - tasks = [_fetch_one(cfg) for cfg in entity_configs] - completed = await asyncio.gather(*tasks, return_exceptions=True) - - results: Dict[str, List[Any]] = {} - for cfg, res in zip(entity_configs, completed): - key = cfg["key"] - if isinstance(res, Exception): - logger.error(f"Parallel fetch failed for '{key}': {res}") - results[key] = [] - else: - key_name, data = res - results[key_name] = data - - return results - - -async def _fetch_related_entities( - project_ids: List[str], - index_pattern: str, - model_class: Any, -) -> Dict[str, List[Any]]: - """ - Fetches and groups related entities from Elasticsearch by project ID. - - Args: - project_ids: List of project IDs to fetch entities for. - index_pattern: The index pattern to search (supports wildcards). - model_class: The Pydantic model class to validate against. - - Returns: - Dictionary mapping project IDs to lists of validated entities. - """ - query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} - - try: - response = await elasticsearch.search( - query=query, - index=index_pattern, - cluster=ESCluster.INSE, - size=10000, - ) - except Exception as e: - logger.warning(f"Failed to fetch from {index_pattern}: {e}") - return {} - - grouped: Dict[str, List[Any]] = {} - - for hit in response.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - project_id = source.get("projectID") - - if not project_id: - continue - - grouped.setdefault(project_id, []) - - try: - entity = model_class.model_validate(source) - grouped[project_id].append(entity) - except Exception as e: - logger.warning(f"Failed to validate {model_class.__name__} for project {project_id}: {e}") - - return grouped - - -async def _enrich_fp7_project( - project_id: str, - project_source: Dict[str, Any], -) -> Optional[Fp7ProjectDetails]: - """Enriches a single FP7 project with all related data.""" - try: - project = Fp7Project.model_validate(project_source) - except Exception as e: - logger.error(f"Failed to validate FP7 project {project_id}: {e}") - return None - - related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS) - - return Fp7ProjectDetails.from_project_with_relations(project=project, **related) - - -async def _enrich_h2020_project( - project_id: str, - project_source: Dict[str, Any], -) -> Optional[H2020ProjectDetails]: - """Enriches a single H2020 project with all related data.""" - try: - project = H2020Project.model_validate(project_source) - except Exception as e: - logger.error(f"Failed to validate H2020 project {project_id}: {e}") - return None - - related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS) - - return H2020ProjectDetails.from_project_with_relations(project=project, **related) - - -async def _enrich_heu_project( - project_id: str, - project_source: Dict[str, Any], -) -> Optional[HEUProjectDetails]: - """Enriches a single Horizon Europe project with all related data.""" - try: - project = HEUProject.model_validate(project_source) - except Exception as e: - logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}") - return None - - related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS) - - return HEUProjectDetails.from_project_with_relations(project=project, **related) \ No newline at end of file diff --git a/service/src/main/inse/projects/eu_organizations/model.py b/service/src/main/inse/projects/eu_organizations/model.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/projects/logic.py b/service/src/main/inse/projects/logic.py index 2a01e5ca..01b3fa7a 100644 --- a/service/src/main/inse/projects/logic.py +++ b/service/src/main/inse/projects/logic.py @@ -3,11 +3,11 @@ import logging from typing import Any, Dict, List, Optional, Set, Tuple from collections import defaultdict -from inse.projects.eu_cordis_projects_enrichment_client import get_enriched_cordis_project_by_id +from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex - +from inse.projects.model import EuCordisProjectType logger = logging.getLogger(__name__) @@ -244,3 +244,133 @@ async def get_person_institutes( "address_country_en": source.get("address_country_en"), } return result + + +#EU Cordis Projects + + + +async def get_eu_project_ids_by_openalex_topic_ids( + project_types: List[EuCordisProjectType], + topic_ids: List[str], +) -> Dict[EuCordisProjectType, List[str]]: + """ + Returns EU CORDIS project IDs whose mapped OpenAlex topic_matches contain + EVERY given topic ID. Same semantics as DFG topic filtering. + """ + if not topic_ids: + return {project_type: [] for project_type in project_types} + + required_topics = set(topic_ids) + result: Dict[EuCordisProjectType, List[str]] = {} + + for project_type in project_types: + project_topics: Dict[str, Set[str]] = defaultdict(set) + + page_size = 1000 + from_ = 0 + + while True: + body = { + "size": page_size, + "from": from_, + "_source": ["project_id", "topic_matches"], + "query": { + "terms": { + "topic_matches.topic_id.keyword": topic_ids + } + }, + } + + response = await elasticsearch.search( + index=project_type.to_openalex_topics_index(), + cluster=ESCluster.INSE, + body=body, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + source = hit.get("_source", {}) + project_id = source.get("project_id") + if not project_id: + continue + + topic_matches = source.get("topic_matches") or [] + if isinstance(topic_matches, dict): + topic_matches = [topic_matches] + + for match in topic_matches: + topic_id = match.get("topic_id") + if topic_id in required_topics: + project_topics[project_id].add(topic_id) + + if len(hits) < page_size: + break + + from_ += page_size + + result[project_type] = [ + project_id + for project_id, found_topics in project_topics.items() + if required_topics.issubset(found_topics) + ] + + return result + + +async def get_openalex_topics_for_eu_projects( + project_ids_by_type: Dict[EuCordisProjectType, List[str]], +) -> Dict[Tuple[EuCordisProjectType, str], List[Dict[str, Any]]]: + """ + Fetches mapped OpenAlex topic matches for EU CORDIS projects. + """ + topic_lookup: Dict[Tuple[EuCordisProjectType, str], List[Dict[str, Any]]] = {} + + for project_type, project_ids in project_ids_by_type.items(): + if not project_ids: + continue + + page_size = 1000 + from_ = 0 + + while True: + response = await elasticsearch.search( + index=project_type.to_openalex_topics_index(), + cluster=ESCluster.INSE, + body={ + "size": page_size, + "from": from_, + "_source": ["project_id", "topic_matches"], + "query": { + "terms": { + "project_id.keyword": project_ids + } + }, + }, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + source = hit.get("_source", {}) + project_id = source.get("project_id") + if not project_id: + continue + + topic_matches = source.get("topic_matches") or [] + if isinstance(topic_matches, dict): + topic_matches = [topic_matches] + + topic_lookup.setdefault((project_type, project_id), []).extend(topic_matches) + + if len(hits) < page_size: + break + + from_ += page_size + + return topic_lookup \ No newline at end of file diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index 8284b33a..558cdadb 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -14,6 +14,7 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HE from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield +from inse.authors.v2.model import AuthorPage from typing import Union class ProjectType(StrEnum): @@ -81,11 +82,6 @@ class BundProjectList(BaseModel): ) total: int = Field(default=0, description="The total number of bund projects.") - -class EuProjectPage(Page): - elements: List[EuProject] = Field( - default_factory=list, description="The EU projects on this page." - ) class DfgInstitutionSummary(BaseModel): """A summary of a DFG institution.""" @@ -443,6 +439,12 @@ class FundingProjectPage(Page): ) +#EU CORDIS PROJECTS +class EuProjectPage(Page): + elements: List[EuProject] = Field( + default_factory=list, description="The EU projects on this page." + ) + class EuOrganizationShort(BaseModel): project_id: str = Field(description="The unique identifier of the project.") organization_id: str = Field( @@ -496,3 +498,258 @@ class EuOrganizationProjectSummaryPage(Page): default_factory=list, description="The organization project summaries on this page.", ) + + + +################ +class EuCordisProjectType(StrEnum): + FP7 = "fp7" + H2020 = "h2020" + HEU = "heu" + + def to_project_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_PROJECTS, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, + } + return mapping[self] + + def to_organization_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, + } + return mapping[self] + + def to_cordis_topic_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_TOPICS, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, + } + return mapping[self] + def to_cordis_publications_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_PUBLICATIONS, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, + } + return mapping[self] + + def to_euroscivoc_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.CORDIS_EU_FP7_EUROSCIVOC, + self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, + self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, + } + return mapping[self] + + def to_openalex_topics_index(self) -> ESIndex: + mapping = { + self.FP7: ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING, + self.H2020: ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS, + self.HEU: ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS, + } + return mapping[self] + + + @classmethod + def from_index_name(cls, index_name: str) -> "EuCordisProjectType": + if index_name == ESIndex.CORDIS_EU_FP7_PROJECTS.value: + return cls.FP7 + if index_name == ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS.value: + return cls.H2020 + if index_name == ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS.value: + return cls.HEU + + raise ValueError(f"Unsupported EU CORDIS project index: {index_name}") + + +class EuCordisOrganizationSummary(BaseModel): + id: Optional[str] = None + organisation_id: Optional[str] = None + name: Optional[str] = None + short_name: Optional[str] = None + country: Optional[str] = None + city: Optional[str] = None + role: Optional[str] = None + activity_type: Optional[str] = None + project_id: Optional[str] = None + ec_contribution: Optional[float] = None + total_cost: Optional[float] = None + + @classmethod + def from_es_source(cls, source: Dict[str, Any]) -> "EuCordisOrganizationSummary": + return cls( + id=source.get("id"), + organisation_id=source.get("organisationID"), + name=source.get("name"), + short_name=source.get("shortName"), + country=source.get("country"), + city=source.get("city"), + role=source.get("role"), + activity_type=source.get("activityType"), + project_id=source.get("projectID"), + ec_contribution=source.get("ecContribution"), + total_cost=source.get("totalCost"), + ) + + + +class EuCordisTopicSummary(BaseModel): + id: Optional[str] = None + project_id: Optional[str] = None + title: Optional[str] = None + topic: Optional[str] = None + + @classmethod + def from_es_source(cls, source: Dict[str, Any]) -> "EuCordisTopicSummary": + return cls( + id=source.get("id"), + project_id=source.get("projectID"), + title=source.get("title"), + topic=source.get("topic"), + ) + + + +class EuCordisEurosciVocSummary(BaseModel): + id: Optional[str] = None + project_id: Optional[str] = None + code: Optional[str] = None + title: Optional[str] = None + description: Optional[str] = None + path: Optional[str] = None + + @classmethod + def from_es_source(cls, source: Dict[str, Any]) -> "EuCordisEurosciVocSummary": + return cls( + id=source.get("id"), + project_id=source.get("projectID"), + code=source.get("code"), + title=source.get("title"), + description=source.get("description"), + path=source.get("path"), + ) + + +class EuCordisProjectSummary(BaseModel): + id: str + project_type: EuCordisProjectType + + title: Optional[str] = None + acronym: Optional[str] = None + objective: Optional[str] = None + keywords: Optional[str] = None + + framework_programme: Optional[str] = None + funding_scheme: Optional[str] = None + status: Optional[str] = None + + start_date: Optional[date] = None + end_date: Optional[date] = None + + ec_max_contribution: Optional[float] = None + total_cost: Optional[float] = None + authors: Optional[AuthorPage] = None + organizations: List[EuCordisOrganizationSummary] = Field(default_factory=list) + cordis_topics: List[EuCordisTopicSummary] = Field(default_factory=list) + eurosci_voc: List[EuCordisEurosciVocSummary] = Field(default_factory=list) + topics: List[Topic] = Field(default_factory=list, description="Mapped OpenAlex topics.") + + @classmethod + def from_hit( + cls, + hit: Dict[str, Any], + authors: Optional[AuthorPage] = None, + organizations: Optional[List[EuCordisOrganizationSummary]] = None, + cordis_topics: Optional[List[EuCordisTopicSummary]] = None, + eurosci_voc: Optional[List[EuCordisEurosciVocSummary]] = None, + topics: Optional[List[Topic]] = None, + ) -> "EuCordisProjectSummary": + source = hit.get("_source", {}) + project_type = EuCordisProjectType.from_index_name(hit.get("_index", "")) + + return cls( + id=source.get("id") or hit.get("_id", ""), + project_type=project_type, + + title=source.get("title"), + acronym=source.get("acronym"), + objective=source.get("objective"), + keywords=source.get("keywords"), + + framework_programme=source.get("frameworkProgramme"), + funding_scheme=source.get("fundingScheme"), + status=source.get("status"), + + start_date=source.get("startDate"), + end_date=source.get("endDate"), + + ec_max_contribution=source.get("ecMaxContribution"), + total_cost=source.get("totalCost"), + + authors=authors or None, + organizations=organizations or [], + cordis_topics=cordis_topics or [], + eurosci_voc=eurosci_voc or [], + topics=topics or [], + ) + + @staticmethod + def topic_from_match(match: Dict[str, Any]) -> Topic: + domain_name = match.get("domain") + field_name = match.get("field") + subfield_name = match.get("subfield") + + domain = TopicDomain(display_name=domain_name) if domain_name else None + field = TopicField(display_name=field_name) if field_name else None + subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None + + return Topic( + id=match.get("topic_id"), + display_name=match.get("topic_display_name"), + domain=domain, + field=field, + subfield=subfield, + ) + + +class EuCordisProjectSearchPage(Page): + elements: List[EuCordisProjectSummary] = Field( + default_factory=list, + description="The EU CORDIS project summaries on this page.", + ) + + +class EuCordisOrganizationSelectorSummary(BaseModel): + id: Optional[str] = None + organisation_id: Optional[str] = None + name: Optional[str] = None + short_name: Optional[str] = None + country: Optional[str] = None + city: Optional[str] = None + project_type: Optional[EuCordisProjectType] = None + + @classmethod + def from_es_source( + cls, + source: Dict[str, Any], + project_type: Optional[EuCordisProjectType] = None, + ) -> "EuCordisOrganizationSelectorSummary": + return cls( + id=source.get("id"), + organisation_id=source.get("organisationID"), + name=source.get("name"), + short_name=source.get("shortName"), + country=source.get("country"), + city=source.get("city"), + project_type=project_type, + ) + + + +class EuCordisOrganizationSelectorPage(Page): + elements: List[EuCordisOrganizationSelectorSummary] = Field(default_factory=list) \ No newline at end of file diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 3a0a7557..7404421a 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -21,7 +21,7 @@ from inse.projects.model import ( ProjectsSortBy, SortDirection, ) -from inse.projects.eu_cordis_projects_enrichment_client import get_enriched_cordis_project_by_id +from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails from inse.models.cordis_eu_project import CordisEuProject @@ -505,8 +505,32 @@ async def get_cordis_eu_publications_by_dois(dois: List[str]): Returns: _type_: The retrieved publications. """ - raw_dois = [_get_raw_doi(doi) for doi in dois] - query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} + + query_dois = list({ + variant + for doi in dois + for variant in ( + _get_raw_doi(doi), + _get_raw_doi(doi).lower(), + _get_raw_doi(doi).upper(), + ) + }) + + query = { + "bool": { + "filter": [ + { + "bool": { + "should": [ + {"terms": {"doi": query_dois}}, + {"terms": {"qaProcessedDoi": query_dois}}, + ], + "minimum_should_match": 1, + } + } + ] + } + } response = await elasticsearch.search( query=query, diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 699b4d22..8fbc5f70 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -134,7 +134,148 @@ async def get_single_bund_project( return await projects_service.get_single_bund_project( project_id=id, ) + + +######## +from inse.projects.model import EuCordisProjectSearchPage, EuCordisProjectType +from inse.projects.service import search_eu_cordis_projects_summary_impl +@router.get( + "/eu/search", + summary="Search EU CORDIS projects.", + description="Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and Horizon Europe.", + operation_id="searchEuCordisProjectsSummary", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": EuCordisProjectSearchPage, + }, + }, + response_model_by_alias=False, +) +async def search_eu_cordis_projects_summary( + author_id: Annotated[ + Optional[str], + Query(description="OpenAlex author ID to filter by."), + ] = None, + author_ids: Annotated[ + Optional[List[str]], + Query(description="Additional OpenAlex author IDs to filter by. All selected authors must match."), + ] = None, + organization_ids: Annotated[ + Optional[List[str]], + Query(description="CORDIS organisation IDs. All selected organizations must match."), + ] = None, + organization_names: Annotated[ + Optional[List[str]], + Query(description="CORDIS organization names. All selected organizations must match."), + ] = None, + project_types: Annotated[ + Optional[List[EuCordisProjectType]], + Query(description="Project types to include: fp7, h2020, heu."), + ] = None, + title: Annotated[ + Optional[str], + Query(description="Project title/acronym search."), + ] = None, + keywords: Annotated[ + Optional[List[str]], + Query(description="Raw keywords to search in title/objective/keywords/topics."), + ] = None, + topic_ids: Annotated[ + Optional[List[str]], + Query(description="OpenAlex topic IDs used for fuzzy topic resolution."), + ] = None, + filter_topic_ids: Annotated[ + Optional[List[str]], + Query(description="Additional OpenAlex topic IDs used as mandatory filters."), + ] = None, + funding_start_years: Annotated[ + Optional[List[str]], + Query(description="Funding start years."), + ] = None, + funding_end_years: Annotated[ + Optional[List[str]], + Query(description="Funding end years."), + ] = None, + countries: Annotated[ + Optional[List[str]], + Query(description="Organization countries."), + ] = None, + framework_programmes: Annotated[ + Optional[List[str]], + Query(description="Framework programme filters."), + ] = None, + funding_schemes: Annotated[ + Optional[List[str]], + Query(description="Funding scheme filters."), + ] = None, + statuses: Annotated[ + Optional[List[str]], + Query(description="Project status filters."), + ] = None, + page: Annotated[int, Query(description="The page number.", ge=0)] = 0, + size: Annotated[int, Query(description="The page size.", ge=1)] = 20, + sort_by: Annotated[str, Query(description="Sort field.")] = "title", + sort_direction: Annotated[ + str, + Query(description="Sort direction: asc or desc."), + ] = "asc", + fuzzy: Annotated[ + bool, + Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + ] = False, +) -> EuCordisProjectSearchPage: + logger.debug( + "Received EU CORDIS search request: author_id=%s, author_ids=%s, " + "organization_ids=%s, organization_names=%s, project_types=%s, " + "title=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, " + "funding_start_years=%s, funding_end_years=%s, countries=%s, " + "framework_programmes=%s, funding_schemes=%s, statuses=%s, " + "page=%s, size=%s, sort_by=%s, sort_direction=%s, fuzzy=%s", + author_id, + author_ids, + organization_ids, + organization_names, + project_types, + title, + keywords, + topic_ids, + filter_topic_ids, + funding_start_years, + funding_end_years, + countries, + framework_programmes, + funding_schemes, + statuses, + page, + size, + sort_by, + sort_direction, + fuzzy, + ) + return await search_eu_cordis_projects_summary_impl( + author_id=author_id, + author_ids=author_ids, + organization_ids=organization_ids, + organization_names=organization_names, + project_types=project_types, + title=title, + keywords=keywords, + topic_ids=topic_ids, + filter_topic_ids=filter_topic_ids, + funding_start_years=funding_start_years, + funding_end_years=funding_end_years, + countries=countries, + framework_programmes=framework_programmes, + funding_schemes=funding_schemes, + statuses=statuses, + page=page, + size=size, + sort_by=sort_by, + sort_direction=sort_direction, + fuzzy=fuzzy, + ) @router.get( "/eu/{id}", @@ -209,7 +350,7 @@ async def get_single_eu_cordis_project( return EuCordisProjectResponse( success=False, project_type=None, - data=None, + eu_project_data=None, error=f"Internal server error: {str(e)}" ) diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 86637a6f..65a7ded5 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -385,7 +385,7 @@ async def get_single_eu_cordis_project( project = await projects_search_client.get_eu_cordis_projects_by_id(project_id) if not project: - raise NotFoundException(f"EU project with id {project_id} not found") + return None return project @@ -414,3 +414,98 @@ async def search_cordis_eu_projects_for_author_id( return funding_project_page + + +################ +from inse.projects.eu_cordis_projects_client import search_eu_cordis_projects +from inse.projects.model import EuCordisProjectType, EuCordisProjectSearchPage +from inse.works.logic import get_publication_dois_of_author + +async def _get_eu_project_ids_for_openalex_authors( + author_ids: List[str], +) -> Optional[List[str]]: + """ + Resolves OpenAlex authors to CORDIS EU project IDs via publication DOIs. + + Multiple authors use AND semantics: + project must be connected to publications from every selected author. + """ + author_ids = [author_id for author_id in author_ids if author_id and author_id.strip()] + if not author_ids: + return None + + project_sets: List[Set[str]] = [] + + for author_id in author_ids: + dois = await get_publication_dois_of_author(raw_oa_author_id=author_id) + if not dois: + return [] + + project_ids = await projects_search_client.get_cordis_eu_project_ids_by_dois( + dois=dois + ) + + if not project_ids: + return [] + + project_sets.append(set(project_ids)) + + if not project_sets: + return None + + return list(set.intersection(*project_sets)) + + +async def search_eu_cordis_projects_summary_impl( + page: int, + size: int, + project_types: Optional[List[EuCordisProjectType]] = None, + author_id: Optional[str] = None, + author_ids: Optional[List[str]] = None, + organization_ids: Optional[List[str]] = None, + organization_names: Optional[List[str]] = None, + keywords: Optional[List[str]] = None, + topic_ids: Optional[List[str]] = None, + filter_topic_ids: Optional[List[str]] = None, + title: Optional[str] = None, + funding_start_years: Optional[List[str]] = None, + funding_end_years: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + framework_programmes: Optional[List[str]] = None, + funding_schemes: Optional[List[str]] = None, + statuses: Optional[List[str]] = None, + sort_by: str = "title", + sort_direction: str = "asc", + fuzzy: bool = False, +) -> EuCordisProjectSearchPage: + + all_author_ids: List[str] = [] + + if author_id: + all_author_ids.append(author_id) + all_author_ids.extend(author_ids or []) + author_project_ids = await _get_eu_project_ids_for_openalex_authors( + author_ids=all_author_ids + ) + + return await search_eu_cordis_projects( + page=page, + size=size, + project_types=project_types, + organization_ids=organization_ids, + organization_names=organization_names, + author_project_ids=author_project_ids, + keywords=keywords, + topic_ids=topic_ids, + filter_topic_ids=filter_topic_ids, + title=title, + funding_start_years=funding_start_years, + funding_end_years=funding_end_years, + countries=countries, + framework_programmes=framework_programmes, + funding_schemes=funding_schemes, + statuses=statuses, + sort_by=sort_by, + sort_direction=sort_direction, + fuzzy=fuzzy, + ) \ No newline at end of file diff --git a/service/src/main/inse/projects/test_eu_cordis_search_client.py b/service/src/main/inse/projects/test_eu_cordis_search_client.py new file mode 100644 index 00000000..b9bc7aa1 --- /dev/null +++ b/service/src/main/inse/projects/test_eu_cordis_search_client.py @@ -0,0 +1,364 @@ +import pytest +from inse.projects import eu_cordis_projects_client as eu_cordis_search_client + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_title(): + """Test searching EU CORDIS projects by title.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + title="Artificial Intelligence", + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.title is not None + assert "artificial" in element.title.lower() or "intelligence" in element.title.lower() + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_keywords(): + """Test searching EU CORDIS projects by keywords.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + keywords=["machine learning", "deep learning"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.title is not None + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_framework_programme(): + """Test filtering EU CORDIS projects by framework programme.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + framework_programmes=["H2020"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.framework_programme == "H2020" + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_status(): + """Test filtering EU CORDIS projects by status.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + statuses=["SIGNED"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.status == "SIGNED" + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_funding_years(): + """Test filtering EU CORDIS projects by funding start years.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + funding_start_years=["2020"], + ) + + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.start_date is not None + assert element.start_date.year == 2020 + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_country(): + """Test filtering EU CORDIS projects by country.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + countries=["DE"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + # Verify at least one organization is from Germany + assert any( + org.country == "DE" for org in element.organizations + ) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_organization_name(): + """Test filtering EU CORDIS projects by organization name.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + organization_names=["Max Planck"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + # Verify at least one organization matches the name + assert any( + "max planck" in org.name.lower() for org in element.organizations + ) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_organization_id(): + """Test filtering EU CORDIS projects by organization ID.""" + # Use a known organization ID (e.g., Max Planck Society) + known_org_id = "999990267" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + organization_ids=[known_org_id], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + # Verify the organization is present in the project + assert any( + org.organisation_id == known_org_id for org in element.organizations + ) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_project_type(): + """Test filtering EU CORDIS projects by project type (FP7, H2020, HEU).""" + from inse.projects.model import EuCordisProjectType + + # Test FP7 projects + res_fp7 = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + project_types=[EuCordisProjectType.FP7], + ) + assert res_fp7 is not None + assert res_fp7.total > 0 + assert len(res_fp7.elements) > 0 + for element in res_fp7.elements: + assert element.id is not None + assert element.project_type == EuCordisProjectType.FP7 + + # Test H2020 projects + res_h2020 = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + project_types=[EuCordisProjectType.H2020], + ) + assert res_h2020 is not None + assert res_h2020.total > 0 + assert len(res_h2020.elements) > 0 + for element in res_h2020.elements: + assert element.id is not None + assert element.project_type == EuCordisProjectType.H2020 + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_with_sorting(): + """Test sorting EU CORDIS projects.""" + # Test ascending sort by title + res_asc = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + sort_by="title", + sort_direction="asc", + ) + assert res_asc is not None + assert len(res_asc.elements) > 0 + + titles_asc = [element.title for element in res_asc.elements] + assert titles_asc == sorted(titles_asc) + + # Test descending sort by title + res_desc = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + sort_by="title", + sort_direction="desc", + ) + assert res_desc is not None + assert len(res_desc.elements) > 0 + + titles_desc = [element.title for element in res_desc.elements] + assert titles_desc == sorted(titles_desc, reverse=True) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_pagination(): + """Test pagination of EU CORDIS project search results.""" + # Get first page + page1 = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=3, + ) + assert page1 is not None + assert len(page1.elements) <= 3 + assert page1.page == 0 + assert page1.size == 3 + + # Get second page + page2 = await eu_cordis_search_client.search_eu_cordis_projects( + page=1, + size=3, + ) + assert page2 is not None + assert len(page2.elements) <= 3 + assert page2.page == 1 + assert page2.size == 3 + + # Ensure pages don't overlap + page1_ids = {element.id for element in page1.elements} + page2_ids = {element.id for element in page2.elements} + assert page1_ids.isdisjoint(page2_ids) + + +@pytest.mark.anyio +async def test_get_enriched_cordis_project_by_id(): + """Test fetching an enriched EU CORDIS project by ID.""" + # Use a known project ID (e.g., an H2020 project) + known_id = "101016442" # Example H2020 project ID + project = await eu_cordis_search_client.get_enriched_cordis_project_by_id(known_id) + assert project is not None + assert project.id == known_id + assert project.title is not None + assert project.objective is not None + + # Verify enriched data + assert hasattr(project, 'organizations') + assert hasattr(project, 'publications') + assert hasattr(project, 'report_summaries') + assert hasattr(project, 'topics_list') + + +@pytest.mark.anyio +async def test_get_enriched_cordis_project_by_id_not_found(): + """Test fetching a non-existent EU CORDIS project.""" + project = await eu_cordis_search_client.get_enriched_cordis_project_by_id("nonexistent_id") + assert project is None + + +@pytest.mark.anyio +async def test_get_enriched_cordis_project_by_id_empty(): + """Test fetching with empty project ID.""" + project = await eu_cordis_search_client.get_enriched_cordis_project_by_id("") + assert project is None + + project = await eu_cordis_search_client.get_enriched_cordis_project_by_id(None) + assert project is None + + +@pytest.mark.anyio +async def test_get_dois_by_cordis_eu_project_id(): + """Test retrieving DOIs for a CORDIS EU project.""" + known_id = "101016442" # Example H2020 project ID + dois = await eu_cordis_search_client.get_dois_by_cordis_eu_project_id(known_id) + assert dois is not None + assert len(dois) > 0 + + +@pytest.mark.anyio +async def test_get_openalex_authors_for_cordis_project_ids(): + """Test retrieving OpenAlex authors for CORDIS project IDs.""" + project_ids = ["101016442"] # Example H2020 project ID + authors_by_project = await eu_cordis_search_client.get_openalex_authors_for_cordis_project_ids(project_ids) + assert authors_by_project is not None + assert len(authors_by_project) > 0 + + for project_id, author_page in authors_by_project.items(): + assert project_id in project_ids + assert author_page is not None + if author_page.total > 0: + for author in author_page.elements: + assert author.id is not None + assert author.display_name is not None + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_with_multiple_filters(): + """Test combining multiple filters in EU CORDIS project search.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + framework_programmes=["H2020"], + funding_start_years=["2020"], + countries=["US"], + statuses=["SIGNED"], + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.framework_programme == "H2020" + assert element.status == "SIGNED" + assert element.start_date.year == 2020 + assert any(org.country == "US" for org in element.organizations) + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_empty_results(): + """Test search that should return no results.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + title="ThisProjectDoesNotExistXYZ123", + ) + assert res is not None + assert res.total == 0 + assert len(res.elements) == 0 + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_by_funding_scheme(): + """Test filtering EU CORDIS projects by funding scheme.""" + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + funding_schemes=["ERC-ADG"], # ERC Advanced Grant + ) + assert res is not None + assert res.total > 0 + assert len(res.elements) > 0 + for element in res.elements: + assert element.id is not None + assert element.funding_scheme == "ERC-ADG" + + +@pytest.mark.anyio +async def test_search_eu_cordis_projects_with_fuzzy_topic_search(): + """Test fuzzy search with OpenAlex topic IDs.""" + # This test requires known OpenAlex topic IDs + topic_ids = ["https://openalex.org/T12345"] # Example topic ID + res = await eu_cordis_search_client.search_eu_cordis_projects( + page=0, + size=5, + topic_ids=topic_ids, + fuzzy=True, + ) + assert res is not None + # Note: This may return 0 results if the topic ID doesn't exist + # The important thing is that it doesn't crash + assert isinstance(res.total, int) + assert isinstance(res.elements, list) \ No newline at end of file From 8d0a4f2e5a0b1ce0500a3ad791be701efde73b0d Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 22 Jul 2026 23:36:34 +0200 Subject: [PATCH 07/26] added EU cordis organizations autocompletion --- .../inse/projects/eu_organizations/router.py | 51 ++++++ .../inse/projects/eu_organizations/service.py | 160 ++++++++++++++++++ 2 files changed, 211 insertions(+) create mode 100644 service/src/main/inse/projects/eu_organizations/router.py create mode 100644 service/src/main/inse/projects/eu_organizations/service.py diff --git a/service/src/main/inse/projects/eu_organizations/router.py b/service/src/main/inse/projects/eu_organizations/router.py new file mode 100644 index 00000000..263587c4 --- /dev/null +++ b/service/src/main/inse/projects/eu_organizations/router.py @@ -0,0 +1,51 @@ +import logging +from typing import Annotated, List + +from fastapi import APIRouter, Query + +from inse.projects.eu_organizations.service import autocomplete_organizations_for_selector, get_organizations_by_ids + +from inse.projects.model import EuCordisOrganizationSelectorPage +from inse.tags import Tags + +logger = logging.getLogger(__name__) + +EU_ORGANIZATIONS_PREFIX = "/api/eu/organizations" + +router = APIRouter(prefix=EU_ORGANIZATIONS_PREFIX, tags=[Tags.PROJECTS]) + + +@router.get( + "/ids", + operation_id="getEuOrganizationsByIds", + summary="Returns EU CORDIS organizations by organisation IDs.", + response_model=EuCordisOrganizationSelectorPage, +) +async def get_eu_organizations_by_ids( + organization_ids: Annotated[ + List[str], + Query(description="CORDIS organisation IDs to retrieve."), + ] = [], +) -> EuCordisOrganizationSelectorPage: + return await get_organizations_by_ids(organization_ids=organization_ids or []) + + +@router.get( + "/autocomplete/selector", + operation_id="getEuOrganizationAutocompleteForSelector", + summary="Returns EU CORDIS organizations based on a search term.", + response_model=EuCordisOrganizationSelectorPage, +) +async def get_eu_organization_autocomplete( + query: Annotated[ + str, + Query(description="Search term for organization autocomplete."), + ] = "", + page: Annotated[int, Query(ge=0)] = 0, + size: Annotated[int, Query(ge=1)] = 10, +) -> EuCordisOrganizationSelectorPage: + return await autocomplete_organizations_for_selector( + query=query, + page=page, + size=size, + ) \ No newline at end of file diff --git a/service/src/main/inse/projects/eu_organizations/service.py b/service/src/main/inse/projects/eu_organizations/service.py new file mode 100644 index 00000000..376cb592 --- /dev/null +++ b/service/src/main/inse/projects/eu_organizations/service.py @@ -0,0 +1,160 @@ +import logging +from typing import Dict, List, Optional + +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex +from inse.projects.model import ( + EuCordisOrganizationSelectorPage, + EuCordisOrganizationSelectorSummary, + EuCordisProjectType, +) + +logger = logging.getLogger(__name__) + + +def _project_type_from_org_index(index_name: str) -> Optional[EuCordisProjectType]: + if index_name == ESIndex.CORDIS_EU_FP7_ORGANIZATIONS.value: + return EuCordisProjectType.FP7 + if index_name == ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS.value: + return EuCordisProjectType.H2020 + if index_name == ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS.value: + return EuCordisProjectType.HEU + return None + + +async def get_organizations_by_ids( + organization_ids: List[str], +) -> EuCordisOrganizationSelectorPage: + if not organization_ids: + return EuCordisOrganizationSelectorPage(elements=[], total=0, page=0, size=0) + + response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, + cluster=ESCluster.INSE, + body={ + "size": len(organization_ids) * 3, + "_source": [ + "id", + "organisationID", + "name", + "shortName", + "country", + "city", + ], + "query": { + "terms": { + "organisationID": organization_ids + } + }, + "collapse": { + "field": "organisationID" + }, + }, + ) + + elements: List[EuCordisOrganizationSelectorSummary] = [] + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + source["project_type"] = _project_type_from_org_index(hit.get("_index", "")) + elements.append(EuCordisOrganizationSelectorSummary.from_es_source(source)) + + return EuCordisOrganizationSelectorPage( + elements=elements, + total=response.get("hits", {}).get("total", {}).get("value", len(elements)), + page=0, + size=len(elements), + ) + + +async def autocomplete_organizations_for_selector( + query: str, + page: int = 0, + size: int = 10, +) -> EuCordisOrganizationSelectorPage: + if not query or not query.strip(): + return EuCordisOrganizationSelectorPage( + elements=[], + total=0, + page=page, + size=size, + ) + + query = query.strip() + + response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, + cluster=ESCluster.INSE, + body={ + "size": size, + "from": page * size, + "_source": [ + "id", + "organisationID", + "name", + "shortName", + "country", + "city", + ], + "query": { + "bool": { + "should": [ + { + "match_phrase_prefix": { + "name": { + "query": query, + "max_expansions": 50, + } + } + }, + { + "wildcard": { + "shortName": { + "value": f"*{query}*", + "case_insensitive": True, + } + } + }, + { + "term": { + "organisationID": query, + } + }, + ], + "minimum_should_match": 1, + } + }, + "collapse": { + "field": "organisationID", + }, + "sort": [ + { + "name.keyword": { + "order": "asc", + "missing": "_last", + "unmapped_type": "keyword", + } + } + ], + }, + ) + + elements: List[EuCordisOrganizationSelectorSummary] = [] + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + source["project_type"] = _project_type_from_org_index(hit.get("_index", "")) + + elements.append( + EuCordisOrganizationSelectorSummary.from_es_source( + source=source, + project_type=source["project_type"], + ) + ) + + return EuCordisOrganizationSelectorPage( + elements=elements, + total=response.get("hits", {}).get("total", {}).get("value", len(elements)), + page=page, + size=size, + ) \ No newline at end of file From f119de52d34611ce2705c69eeee10bad9c5f54dd Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 22 Jul 2026 23:37:11 +0200 Subject: [PATCH 08/26] replaced hardcoded index names with values from global ENUM --- service/src/main/inse/works/logic.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index ec4f16af..6384b39b 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -22,7 +22,7 @@ from inse.models.openalex.topics_by_year import TopicsByYear from inse.models.openalex.topics_by_time import TopicsByTime from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException from .search_client import OpenAlexWorksSearchClient - +from inse.model import ESCluster, ESIndex logger = logging.getLogger(__name__) TOPIC_DETAIL_SOURCE_FIELDS = [ @@ -183,7 +183,8 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]: try: response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, + index=ESIndex.OPENALEX_WORKS_WILDCARD, + cluster=ESCluster.NES, body=body, ) except ElasticsearchException as exc: @@ -273,7 +274,8 @@ async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]: try: response = await elasticsearch.search( - index="openalex-topics", + index=ESIndex.OPENALEX_TOPICS, + cluster=ESCluster.NES, query={"terms": {"id": topic_ids}}, source=TOPIC_DETAIL_SOURCE_FIELDS, size=len(topic_ids), @@ -698,7 +700,8 @@ async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dic try: response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, + index=ESIndex.OPENALEX_WORKS_WILDCARD, + cluster=ESCluster.NES, body=body, ) except ElasticsearchException as exc: @@ -766,7 +769,8 @@ async def _get_timeline_topic_counts_from_es( try: response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, + index=ESIndex.OPENALEX_WORKS_WILDCARD, + cluster=ESCluster.NES, body=body, ) except ElasticsearchException as exc: @@ -1015,11 +1019,11 @@ async def get_publication_dois_of_author( try: response = await elasticsearch.search( - index="openalex-works", + index=ESIndex.OPENALEX_WORKS_WILDCARD, source=["doi"], size=10000, query=query, - cluster="nes", + cluster=ESCluster.NES, ) except ElasticsearchException as exc: logger.exception("Request for publication DOIs of author failed.") From c3ec095ed1ee150980afc3111b4dfbe2aaac2f64 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 22 Jul 2026 23:39:11 +0200 Subject: [PATCH 09/26] added new resolvers for EU cordis autocompletion, projects retrieval, reworked routing logic for projects --- webapp/src/app/app.routes.ts | 100 ++++++--- .../app/resolvers/dfg-projects.resolver.ts | 4 +- .../resolvers/eu-cordis-projects.resolver.ts | 199 ++++++++++++++++++ .../selected-dfg-authors.resolver.ts | 9 +- .../selected-eu-institutions.resolver.ts | 17 ++ 5 files changed, 297 insertions(+), 32 deletions(-) create mode 100644 webapp/src/app/resolvers/eu-cordis-projects.resolver.ts create mode 100644 webapp/src/app/resolvers/selected-eu-institutions.resolver.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index d3cfe683..05077246 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -41,11 +41,15 @@ import { SearchResultsStateService } from './modules/keywords-search/search-resu import { roleGuard } from './shared/guards/role.guard'; import { UserRole } from './api'; import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver'; +import { euCordisProjectsResolver } from './resolvers/eu-cordis-projects.resolver'; import { selectedAuthorsResolver } from './resolvers/selected-authors.resolver'; import { workClassificationResolver } from './resolvers/work-classification.resolver'; import { selectedDfgAuthorsResolver } from './resolvers/selected-dfg-authors.resolver'; import { selectedDfgInstitutionsResolver } from './resolvers/selected-dfg-institutions.resolver'; import { primaryCategoryYearAggregationPageResolver } from './resolvers/primary-category-year-aggregation-page.resolver'; +import { selectedEuInstitutionsResolver } from './resolvers/selected-eu-institutions.resolver'; +import { EuProjectsComponent } from './shared/ui/eu-projects/eu-projects.component'; +import { DfgProjectsComponent } from './shared/ui/dfg-projects/dfg-projects.component'; export const routes: Routes = [ { path: '', @@ -173,19 +177,41 @@ export const routes: Routes = [ { path: 'projects', component: KeywordsToProjectsResultsComponent, - runGuardsAndResolvers: 'always', - resolve: { - dfgProjectPage: dfgProjectsResolver, - personCordisEuProjectPage: personCordisEuProjectPageResolver, - selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, - selectedDfgAuthorsPage: selectedDfgAuthorsResolver, - selectedTopicsPage: selectedTopicsResolver, - selectedEuInstitutionsPage: selectedInstitutionsResolver, - selectedEuAuthorsPage: selectedAuthorsResolver, - }, - data: { - resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH, - }, + children: [ + { + path: '', + pathMatch: 'full', + redirectTo: 'dfg', + }, + { + path: 'dfg', + component: DfgProjectsComponent, + resolve: { + dfgProjectPage: dfgProjectsResolver, + selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, + selectedDfgAuthorsPage: selectedDfgAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH, + }, + }, + { + path: 'eu', + component: EuProjectsComponent, + resolve: { + euCordisProjectPage: euCordisProjectsResolver, + selectedEuInstitutionsPage: selectedEuInstitutionsResolver, + selectedEuAuthorsPage: selectedAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH, + }, + }, + ], }, { path: 'patents', component: KeywordsToPatentsResultsComponent }, { @@ -402,19 +428,41 @@ export const routes: Routes = [ import('./modules/person-projects/person-projects.component').then( (mod) => mod.PersonProjectsComponent, ), - resolve: { - dfgProjectPage: dfgProjectsResolver, - personCordisEuProjectPage: personCordisEuProjectPageResolver, - selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, - selectedDfgAuthorsPage: selectedDfgAuthorsResolver, - selectedTopicsPage: selectedTopicsResolver, - selectedEuInstitutionsPage: selectedInstitutionsResolver, - selectedEuAuthorsPage: selectedAuthorsResolver, - }, - runGuardsAndResolvers: 'always', - data: { - resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON, - }, + children: [ + { + path: '', + pathMatch: 'full', + redirectTo: 'dfg', + }, + { + path: 'dfg', + component: DfgProjectsComponent, + resolve: { + dfgProjectPage: dfgProjectsResolver, + selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, + selectedDfgAuthorsPage: selectedDfgAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON, + }, + }, + { + path: 'eu', + component: EuProjectsComponent, + resolve: { + euCordisProjectPage: euCordisProjectsResolver, + selectedEuInstitutionsPage: selectedEuInstitutionsResolver, + selectedEuAuthorsPage: selectedAuthorsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + runGuardsAndResolvers: 'always', + data: { + resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON, + }, + }, + ], }, { path: 'publications', diff --git a/webapp/src/app/resolvers/dfg-projects.resolver.ts b/webapp/src/app/resolvers/dfg-projects.resolver.ts index a1fcd3a0..2bd67a6d 100644 --- a/webapp/src/app/resolvers/dfg-projects.resolver.ts +++ b/webapp/src/app/resolvers/dfg-projects.resolver.ts @@ -36,8 +36,6 @@ export const dfgProjectsResolver: ResolveFn = ( route.data, ); - const rawAuthorId = route.parent?.params['id']; - const page = Number(route.queryParamMap.get(projectQueryParamKeys.page)) || 0; const size = Number(route.queryParamMap.get(projectQueryParamKeys.size)) || 10; @@ -65,7 +63,9 @@ export const dfgProjectsResolver: ResolveFn = ( .getAll(projectQueryParamKeys.authorId) .map((id) => Number(id)) .filter((id) => !isNaN(id)); + if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) { + const rawAuthorId = route.parent?.parent?.params['id']; return inject(ProjectsService).getDfgProjects( rawAuthorId, authorIds, diff --git a/webapp/src/app/resolvers/eu-cordis-projects.resolver.ts b/webapp/src/app/resolvers/eu-cordis-projects.resolver.ts new file mode 100644 index 00000000..41fc1f3b --- /dev/null +++ b/webapp/src/app/resolvers/eu-cordis-projects.resolver.ts @@ -0,0 +1,199 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { ProjectsService } from '../api'; +import { EuCordisProjectSearchPage } from '../api/model/euCordisProjectSearchPage'; + +export const euProjectQueryParamKeys = { + page: 'page', + size: 'size', + title: 'title', + + institutionId: 'institutionId', + + funding_start: 'funding_start', + funding_end: 'funding_end', + + authorId: 'authorId', + topicId: 'topicId', + + projectType: 'projectType', + + country: 'country', + frameworkProgramme: 'frameworkProgramme', + fundingScheme: 'fundingScheme', + status: 'status', + + sortBy: 'sort_by', + sortDirection: 'sort_direction', + + legend: 'legend', + legend_expanded: 'legend_expanded', +} as const; + +const RESOLVING_PROJECT_PAGE_FOR_KEY = 'resolvingFor'; + +export const RESOLVING_PROJECT_PAGE_FOR = { + PERSON: 'PERSON', + KEYWORDS_SEARCH: 'KEYWORDS_SEARCH', +} as const; + +type ResolvingEuProjectPageFor = + (typeof RESOLVING_PROJECT_PAGE_FOR)[keyof typeof RESOLVING_PROJECT_PAGE_FOR]; + +function getRepeatedOrCsv(routeQueryParamMap: any, key: string): string[] { + const repeatedValues = routeQueryParamMap.getAll(key) ?? []; + + const csvValues = + routeQueryParamMap + .get(key) + ?.split(',') + .map((value: string) => value.trim()) + .filter(Boolean) ?? []; + + return Array.from( + new Set( + [...repeatedValues, ...csvValues] + .map((value) => String(value).trim()) + .filter(Boolean), + ), + ); +} + +export const euCordisProjectsResolver: ResolveFn = ( + route, + state, +) => { + const resolvingFor: ResolvingEuProjectPageFor = + route.data[RESOLVING_PROJECT_PAGE_FOR_KEY] || + RESOLVING_PROJECT_PAGE_FOR.PERSON; + + console.log( + 'Resolving EU project page for', + resolvingFor, + 'with route data:', + route.data, + ); + + /** + * For EU author filtering, this should be an OpenAlex author ID. + * Backend resolves: + * OpenAlex author -> publication DOIs -> CORDIS publications -> CORDIS project IDs + */ + + const page = + Number(route.queryParamMap.get(euProjectQueryParamKeys.page)) || 0; + const size = + Number(route.queryParamMap.get(euProjectQueryParamKeys.size)) || 10; + + const searchTerm = + route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined; + + const sortBy = + route.queryParamMap.get(euProjectQueryParamKeys.sortBy) || 'title'; + + const sortDirection = + route.queryParamMap.get(euProjectQueryParamKeys.sortDirection) || 'asc'; + + const fundingStart = route.queryParamMap.getAll( + euProjectQueryParamKeys.funding_start, + ); + + const fundingEnd = route.queryParamMap.getAll( + euProjectQueryParamKeys.funding_end, + ); + + const filteredTopicIds = route.queryParamMap.getAll( + euProjectQueryParamKeys.topicId, + ); + + /** + * EU project types: + * fp7 | h2020 | heu + */ + const projectTypes = route.queryParamMap.getAll( + euProjectQueryParamKeys.projectType, + ); + + /** + * CORDIS organisation IDs are strings, not numeric DFG institution IDs. + */ + const organizationIds = route.queryParamMap.getAll( + euProjectQueryParamKeys.institutionId, + ); + + /** + * Additional OpenAlex author IDs from query params. + * Keep them as strings. + */ + const authorIds = route.queryParamMap + .getAll(euProjectQueryParamKeys.authorId) + .map((id) => id.split('/').pop() || id); // Extract the last part of the OpenAlex ID if it's a URL + const countries = route.queryParamMap.getAll(euProjectQueryParamKeys.country); + + const frameworkProgrammes = route.queryParamMap.getAll( + euProjectQueryParamKeys.frameworkProgramme, + ); + + const fundingSchemes = route.queryParamMap.getAll( + euProjectQueryParamKeys.fundingScheme, + ); + + const statuses = route.queryParamMap.getAll(euProjectQueryParamKeys.status); + + if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) { + const rawAuthorId = route.parent?.parent?.params['id']; + return inject(ProjectsService).searchEuCordisProjectsSummary( + rawAuthorId, + authorIds, + organizationIds, + [], + projectTypes as any, + searchTerm, + [], + [], + filteredTopicIds, + fundingStart, + fundingEnd, + countries, + frameworkProgrammes, + fundingSchemes, + statuses, + page, + size, + sortBy, + sortDirection, + false, + ); + } + + if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH) { + const keywords = getRepeatedOrCsv(route.queryParamMap, 'keywords'); + const selectedTopicIds = route.queryParamMap.getAll('topics'); + const fuzzySearch = route.queryParamMap.get('fuzzy') === 'true'; + + return inject(ProjectsService).searchEuCordisProjectsSummary( + undefined, + authorIds, + organizationIds, + [], + projectTypes as any, + searchTerm, + keywords, + selectedTopicIds, + filteredTopicIds, + fundingStart, + fundingEnd, + countries, + frameworkProgrammes, + fundingSchemes, + statuses, + page, + size, + sortBy, + sortDirection, + fuzzySearch, + ); + } + + throw new Error(`Unknown resolvingFor value: ${resolvingFor}`); +}; diff --git a/webapp/src/app/resolvers/selected-dfg-authors.resolver.ts b/webapp/src/app/resolvers/selected-dfg-authors.resolver.ts index c932e13d..b2c811c8 100644 --- a/webapp/src/app/resolvers/selected-dfg-authors.resolver.ts +++ b/webapp/src/app/resolvers/selected-dfg-authors.resolver.ts @@ -11,12 +11,13 @@ export const selectedDfgAuthorsResolver: ResolveFn = ( const authorIdQueryParamKey = (route.data['authorIdQueryParamKey'] as string) || 'authorId'; - const authorIds = route.queryParamMap.getAll(authorIdQueryParamKey); + const authorIds = route.queryParamMap + .getAll(authorIdQueryParamKey) + .map((id) => Number(id)) + .filter((id) => !isNaN(id)); if (authorIds.length === 0) { return { elements: [] }; } - return inject(DFGPersonsService).getDfgPersonsByIds( - authorIds.map((id) => id.trim()).filter((id) => id.length > 0), - ); + return inject(DFGPersonsService).getDfgPersonsByIds(authorIds.map(String)); }; diff --git a/webapp/src/app/resolvers/selected-eu-institutions.resolver.ts b/webapp/src/app/resolvers/selected-eu-institutions.resolver.ts new file mode 100644 index 00000000..b2ad9206 --- /dev/null +++ b/webapp/src/app/resolvers/selected-eu-institutions.resolver.ts @@ -0,0 +1,17 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { ProjectsService } from '../api'; +import { EuCordisOrganizationSelectorPage } from '../api/model/euCordisOrganizationSelectorPage'; +export const selectedEuInstitutionsResolver: ResolveFn< + EuCordisOrganizationSelectorPage +> = (route, state) => { + const institutionIdQueryParamKey = + (route.data['institutionIdQueryParamKey'] as string) || 'institutionId'; + + const institutionIds = route.queryParamMap + .getAll(institutionIdQueryParamKey) + .map((id) => id.trim()) + .filter((id) => id.length > 0); + + return inject(ProjectsService).getEuOrganizationsByIds(institutionIds); +}; From b28271edf69cd2c0a37ec720b620725370d82208 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 22 Jul 2026 23:39:43 +0200 Subject: [PATCH 10/26] new EU cordis models and services --- webapp/src/app/api/.openapi-generator/FILES | 8 + webapp/src/app/api/api/projects.service.ts | 297 ++++++++++++++++++ webapp/src/app/api/model/dfgProjectSummary.ts | 52 +-- .../api/model/euCordisEurosciVocSummary.ts | 20 ++ .../model/euCordisOrganizationSelectorPage.ts | 28 ++ .../euCordisOrganizationSelectorSummary.ts | 25 ++ .../api/model/euCordisOrganizationSummary.ts | 25 ++ .../api/model/euCordisProjectSearchPage.ts | 31 ++ .../app/api/model/euCordisProjectSummary.ts | 44 +++ .../src/app/api/model/euCordisProjectType.ts | 18 ++ .../src/app/api/model/euCordisTopicSummary.ts | 18 ++ webapp/src/app/api/model/models.ts | 8 + 12 files changed, 549 insertions(+), 25 deletions(-) create mode 100644 webapp/src/app/api/model/euCordisEurosciVocSummary.ts create mode 100644 webapp/src/app/api/model/euCordisOrganizationSelectorPage.ts create mode 100644 webapp/src/app/api/model/euCordisOrganizationSelectorSummary.ts create mode 100644 webapp/src/app/api/model/euCordisOrganizationSummary.ts create mode 100644 webapp/src/app/api/model/euCordisProjectSearchPage.ts create mode 100644 webapp/src/app/api/model/euCordisProjectSummary.ts create mode 100644 webapp/src/app/api/model/euCordisProjectType.ts create mode 100644 webapp/src/app/api/model/euCordisTopicSummary.ts diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index bcaf568d..11257e71 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -90,7 +90,15 @@ model/dfgPersonSummaryPage.ts model/dfgProjectDetails.ts model/dfgProjectPage.ts model/dfgProjectSummary.ts +model/euCordisEurosciVocSummary.ts +model/euCordisOrganizationSelectorPage.ts +model/euCordisOrganizationSelectorSummary.ts +model/euCordisOrganizationSummary.ts model/euCordisProjectResponse.ts +model/euCordisProjectSearchPage.ts +model/euCordisProjectSummary.ts +model/euCordisProjectType.ts +model/euCordisTopicSummary.ts model/euOrganizationProjectSummary.ts model/euOrganizationProjectSummaryPage.ts model/euProjectData.ts diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 9689556f..fbf184cc 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -27,8 +27,14 @@ import { DfgProjectDetails } from '../model/dfgProjectDetails'; // @ts-ignore import { DfgProjectPage } from '../model/dfgProjectPage'; // @ts-ignore +import { EuCordisOrganizationSelectorPage } from '../model/euCordisOrganizationSelectorPage'; +// @ts-ignore import { EuCordisProjectResponse } from '../model/euCordisProjectResponse'; // @ts-ignore +import { EuCordisProjectSearchPage } from '../model/euCordisProjectSearchPage'; +// @ts-ignore +import { EuCordisProjectType } from '../model/euCordisProjectType'; +// @ts-ignore import { EuOrganizationProjectSummaryPage } from '../model/euOrganizationProjectSummaryPage'; // @ts-ignore import { FundingProjectPage } from '../model/fundingProjectPage'; @@ -186,6 +192,130 @@ export class ProjectsService extends BaseService { ); } + /** + * Returns EU CORDIS organizations based on a search term. + * @endpoint get /api/eu/organizations/autocomplete/selector + * @param query Search term for organization autocomplete. + * @param page + * @param size + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getEuOrganizationAutocompleteForSelector(query?: string, page?: number, size?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getEuOrganizationAutocompleteForSelector(query?: string, page?: number, size?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getEuOrganizationAutocompleteForSelector(query?: string, page?: number, size?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getEuOrganizationAutocompleteForSelector(query?: string, page?: number, size?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/eu/organizations/autocomplete/selector`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Returns EU CORDIS organizations by organisation IDs. + * @endpoint get /api/eu/organizations/ids + * @param organizationIds CORDIS organisation IDs to retrieve. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getEuOrganizationsByIds(organizationIds?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getEuOrganizationsByIds(organizationIds?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getEuOrganizationsByIds(organizationIds?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getEuOrganizationsByIds(organizationIds?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (organizationIds) { + organizationIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'organization_ids'); + }) + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/eu/organizations/ids`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Get EU projects for an author. * Returns a list of EU projects associated with the specified author ID. @@ -664,6 +794,173 @@ export class ProjectsService extends BaseService { ); } + /** + * Search EU CORDIS projects. + * Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and Horizon Europe. + * @endpoint get /api/projects/eu/search + * @param authorId OpenAlex author ID to filter by. + * @param authorIds Additional OpenAlex author IDs to filter by. All selected authors must match. + * @param organizationIds CORDIS organisation IDs. All selected organizations must match. + * @param organizationNames CORDIS organization names. All selected organizations must match. + * @param projectTypes Project types to include: fp7, h2020, heu. + * @param title Project title/acronym search. + * @param keywords Raw keywords to search in title/objective/keywords/topics. + * @param topicIds OpenAlex topic IDs used for fuzzy topic resolution. + * @param filterTopicIds Additional OpenAlex topic IDs used as mandatory filters. + * @param fundingStartYears Funding start years. + * @param fundingEndYears Funding end years. + * @param countries Organization countries. + * @param frameworkProgrammes Framework programme filters. + * @param fundingSchemes Funding scheme filters. + * @param statuses Project status filters. + * @param page The page number. + * @param size The page size. + * @param sortBy Sort field. + * @param sortDirection Sort direction: asc or desc. + * @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public searchEuCordisProjectsSummary(authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchEuCordisProjectsSummary(authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchEuCordisProjectsSummary(authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchEuCordisProjectsSummary(authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorId, 'author_id'); + if (authorIds) { + authorIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'author_ids'); + }) + } + if (organizationIds) { + organizationIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'organization_ids'); + }) + } + if (organizationNames) { + organizationNames.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'organization_names'); + }) + } + if (projectTypes) { + projectTypes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'project_types'); + }) + } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + title, 'title'); + if (keywords) { + keywords.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'keywords'); + }) + } + if (topicIds) { + topicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic_ids'); + }) + } + if (filterTopicIds) { + filterTopicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'filter_topic_ids'); + }) + } + if (fundingStartYears) { + fundingStartYears.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'funding_start_years'); + }) + } + if (fundingEndYears) { + fundingEndYears.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'funding_end_years'); + }) + } + if (countries) { + countries.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'countries'); + }) + } + if (frameworkProgrammes) { + frameworkProgrammes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'framework_programmes'); + }) + } + if (fundingSchemes) { + fundingSchemes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'funding_schemes'); + }) + } + if (statuses) { + statuses.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'statuses'); + }) + } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortBy, 'sort_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortDirection, 'sort_direction'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + fuzzy, 'fuzzy'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/projects/eu/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Search projects across all funders. * Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter. diff --git a/webapp/src/app/api/model/dfgProjectSummary.ts b/webapp/src/app/api/model/dfgProjectSummary.ts index cc1d2b59..c68e8926 100644 --- a/webapp/src/app/api/model/dfgProjectSummary.ts +++ b/webapp/src/app/api/model/dfgProjectSummary.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -12,28 +12,30 @@ import { DFGProjectFachgebieteInner } from './dFGProjectFachgebieteInner'; import { Topic } from './topic'; import { DfgPersonSummary } from './dfgPersonSummary'; -export interface DfgProjectSummary { - /** - * The unique identifier of the DFG project. - */ - id: string; - link?: string | null; - title?: string | null; - professional_classification?: string | null; - funding_start?: string | null; - funding_end?: string | null; - /** - * Institutions associated with the project. - */ - institutions?: Array; - /** - * The names of the persons involved in the DFG project. - */ - names?: Array; - /** - * The persons involved in the DFG project. - */ - persons?: Array; - subject_classifications?: Array | null; - topics?: Array | null; + +export interface DfgProjectSummary { + /** + * The unique identifier of the DFG project. + */ + id: string; + link?: string | null; + title?: string | null; + professional_classification?: string | null; + funding_start?: string | null; + funding_end?: string | null; + /** + * Institutions associated with the project. + */ + institutions?: Array; + /** + * The names of the persons involved in the DFG project. + */ + names?: Array; + /** + * The persons involved in the DFG project. + */ + persons?: Array; + subject_classifications?: Array | null; + topics?: Array | null; } + diff --git a/webapp/src/app/api/model/euCordisEurosciVocSummary.ts b/webapp/src/app/api/model/euCordisEurosciVocSummary.ts new file mode 100644 index 00000000..c45f9b09 --- /dev/null +++ b/webapp/src/app/api/model/euCordisEurosciVocSummary.ts @@ -0,0 +1,20 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface EuCordisEurosciVocSummary { + id?: string | null; + project_id?: string | null; + code?: string | null; + title?: string | null; + description?: string | null; + path?: string | null; +} + diff --git a/webapp/src/app/api/model/euCordisOrganizationSelectorPage.ts b/webapp/src/app/api/model/euCordisOrganizationSelectorPage.ts new file mode 100644 index 00000000..824bf430 --- /dev/null +++ b/webapp/src/app/api/model/euCordisOrganizationSelectorPage.ts @@ -0,0 +1,28 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { EuCordisOrganizationSelectorSummary } from './euCordisOrganizationSelectorSummary'; + + +export interface EuCordisOrganizationSelectorPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + elements?: Array; +} + diff --git a/webapp/src/app/api/model/euCordisOrganizationSelectorSummary.ts b/webapp/src/app/api/model/euCordisOrganizationSelectorSummary.ts new file mode 100644 index 00000000..647c7a90 --- /dev/null +++ b/webapp/src/app/api/model/euCordisOrganizationSelectorSummary.ts @@ -0,0 +1,25 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { EuCordisProjectType } from './euCordisProjectType'; + + +export interface EuCordisOrganizationSelectorSummary { + id?: string | null; + organisation_id?: string | null; + name?: string | null; + short_name?: string | null; + country?: string | null; + city?: string | null; + project_type?: EuCordisProjectType | null; +} +export namespace EuCordisOrganizationSelectorSummary { +} + + diff --git a/webapp/src/app/api/model/euCordisOrganizationSummary.ts b/webapp/src/app/api/model/euCordisOrganizationSummary.ts new file mode 100644 index 00000000..7fe70356 --- /dev/null +++ b/webapp/src/app/api/model/euCordisOrganizationSummary.ts @@ -0,0 +1,25 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface EuCordisOrganizationSummary { + id?: string | null; + organisation_id?: string | null; + name?: string | null; + short_name?: string | null; + country?: string | null; + city?: string | null; + role?: string | null; + activity_type?: string | null; + project_id?: string | null; + ec_contribution?: number | null; + total_cost?: number | null; +} + diff --git a/webapp/src/app/api/model/euCordisProjectSearchPage.ts b/webapp/src/app/api/model/euCordisProjectSearchPage.ts new file mode 100644 index 00000000..c78066c6 --- /dev/null +++ b/webapp/src/app/api/model/euCordisProjectSearchPage.ts @@ -0,0 +1,31 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { EuCordisProjectSummary } from './euCordisProjectSummary'; + + +export interface EuCordisProjectSearchPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + /** + * The EU CORDIS project summaries on this page. + */ + elements?: Array; +} + diff --git a/webapp/src/app/api/model/euCordisProjectSummary.ts b/webapp/src/app/api/model/euCordisProjectSummary.ts new file mode 100644 index 00000000..41197749 --- /dev/null +++ b/webapp/src/app/api/model/euCordisProjectSummary.ts @@ -0,0 +1,44 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { EuCordisTopicSummary } from './euCordisTopicSummary'; +import { AuthorPage } from './authorPage'; +import { EuCordisEurosciVocSummary } from './euCordisEurosciVocSummary'; +import { Topic } from './topic'; +import { EuCordisOrganizationSummary } from './euCordisOrganizationSummary'; +import { EuCordisProjectType } from './euCordisProjectType'; + + +export interface EuCordisProjectSummary { + id: string; + project_type: EuCordisProjectType; + title?: string | null; + acronym?: string | null; + objective?: string | null; + keywords?: string | null; + framework_programme?: string | null; + funding_scheme?: string | null; + status?: string | null; + start_date?: string | null; + end_date?: string | null; + ec_max_contribution?: number | null; + total_cost?: number | null; + authors?: AuthorPage | null; + organizations?: Array; + cordis_topics?: Array; + eurosci_voc?: Array; + /** + * Mapped OpenAlex topics. + */ + topics?: Array; +} +export namespace EuCordisProjectSummary { +} + + diff --git a/webapp/src/app/api/model/euCordisProjectType.ts b/webapp/src/app/api/model/euCordisProjectType.ts new file mode 100644 index 00000000..7720922b --- /dev/null +++ b/webapp/src/app/api/model/euCordisProjectType.ts @@ -0,0 +1,18 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const EuCordisProjectType = { + Fp7: 'fp7', + H2020: 'h2020', + Heu: 'heu' +} as const; +export type EuCordisProjectType = typeof EuCordisProjectType[keyof typeof EuCordisProjectType]; + diff --git a/webapp/src/app/api/model/euCordisTopicSummary.ts b/webapp/src/app/api/model/euCordisTopicSummary.ts new file mode 100644 index 00000000..c13fbb8b --- /dev/null +++ b/webapp/src/app/api/model/euCordisTopicSummary.ts @@ -0,0 +1,18 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface EuCordisTopicSummary { + id?: string | null; + project_id?: string | null; + title?: string | null; + topic?: string | null; +} + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 7be7ffb2..5fdaf7e4 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -57,7 +57,15 @@ export * from './dfgPersonSummaryPage'; export * from './dfgProjectDetails'; export * from './dfgProjectPage'; export * from './dfgProjectSummary'; +export * from './euCordisEurosciVocSummary'; +export * from './euCordisOrganizationSelectorPage'; +export * from './euCordisOrganizationSelectorSummary'; +export * from './euCordisOrganizationSummary'; export * from './euCordisProjectResponse'; +export * from './euCordisProjectSearchPage'; +export * from './euCordisProjectSummary'; +export * from './euCordisProjectType'; +export * from './euCordisTopicSummary'; export * from './euOrganizationProjectSummary'; export * from './euOrganizationProjectSummaryPage'; export * from './euProjectData'; From b2c6534c6018003736f10594b164de72a0cfcc64 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 22 Jul 2026 23:40:21 +0200 Subject: [PATCH 11/26] fixed bug with remaining filters on fuzzy search switching --- .../search-results/search-results.component.html | 3 ++- .../keywords-search/search-results/search-results.component.ts | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.html b/webapp/src/app/modules/keywords-search/search-results/search-results.component.html index 94c091e4..ddc28113 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.html @@ -69,7 +69,8 @@ keywords: state.payload()?.keywords?.join(','), fuzzy: state.payload()?.options?.fuzzy, topics: state.payload()?.options?.fuzzy ? state.topicIds() : null, - }"> + }" + queryParamsHandling="replace"> {{ route.icon }} {{ route.label }} diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts index 6cb4c2ab..176100ec 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts @@ -217,6 +217,7 @@ export class KeywordsSearchResultsComponent { const queryParams = { fuzzy: fuzzy, topics: fuzzy ? this.state.topicIds() : null, + topicId: null, }; this.router.navigate([], { From 2ca6f2ae390d4339ebf023c89c5057fc83462219 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 22 Jul 2026 23:40:59 +0200 Subject: [PATCH 12/26] outsourced dfg-projects content to new components --- .../dfg-projects/dfg-projects.component.html | 20 ++++++++ .../dfg-projects/dfg-projects.component.scss | 0 .../ui/dfg-projects/dfg-projects.component.ts | 47 ++++++++++++++++++ .../ui/eu-projects/eu-projects.component.html | 18 +++++++ .../ui/eu-projects/eu-projects.component.scss | 0 .../ui/eu-projects/eu-projects.component.ts | 49 +++++++++++++++++++ 6 files changed, 134 insertions(+) create mode 100644 webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.html create mode 100644 webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.scss create mode 100644 webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.ts create mode 100644 webapp/src/app/shared/ui/eu-projects/eu-projects.component.html create mode 100644 webapp/src/app/shared/ui/eu-projects/eu-projects.component.scss create mode 100644 webapp/src/app/shared/ui/eu-projects/eu-projects.component.ts diff --git a/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.html b/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.html new file mode 100644 index 00000000..13fb5295 --- /dev/null +++ b/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.html @@ -0,0 +1,20 @@ +
+ + + +
diff --git a/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.scss b/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.ts b/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.ts new file mode 100644 index 00000000..4e82df6b --- /dev/null +++ b/webapp/src/app/shared/ui/dfg-projects/dfg-projects.component.ts @@ -0,0 +1,47 @@ +import { Component, computed, input } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { DfgPersonSummaryPage, TopicPageV2 } from '../../../api'; +import { DfgProjectPage } from '../../../api/model/dfgProjectPage'; +import { DfgInstitutionSummaryPage } from '../../../api/model/dfgInstitutionSummaryPage'; +import { MatCardModule } from '@angular/material/card'; +import { MatTabsModule } from '@angular/material/tabs'; +import { ProjectFilterComponent } from '../project-filters/project-filters.component'; +import { DfgProjectTableComponent } from '../dfg-project-table/dfg-project-table.component'; +import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver'; + +@Component({ + selector: 'app-dfg-projects', + imports: [ + MatCardModule, + MatTabsModule, + ProjectFilterComponent, + DfgProjectTableComponent, + ], + templateUrl: './dfg-projects.component.html', + styleUrl: './dfg-projects.component.scss', +}) +export class DfgProjectsComponent { + dfgProjectPage = input.required(); + + selectedDfgInstitutionsPage = input.required(); + selectedDfgAuthorsPage = input.required(); + + selectedTopicsPage = input.required(); + + readonly dfgQueryParamKeys = projectQueryParamKeys; + + constructor( + private readonly router: Router, + private readonly activatedRoute: ActivatedRoute, + ) {} + ngOnInit(): void { + console.log('DFG PROJECTS', this.dfgProjectPage()); + } + queryParamMap = toSignal(this.activatedRoute.queryParamMap, { + initialValue: this.activatedRoute.snapshot.queryParamMap, + }); + readonly fuzzySearch = computed( + () => this.queryParamMap().get('fuzzy') === 'true', + ); +} diff --git a/webapp/src/app/shared/ui/eu-projects/eu-projects.component.html b/webapp/src/app/shared/ui/eu-projects/eu-projects.component.html new file mode 100644 index 00000000..8f49a79f --- /dev/null +++ b/webapp/src/app/shared/ui/eu-projects/eu-projects.component.html @@ -0,0 +1,18 @@ + + + diff --git a/webapp/src/app/shared/ui/eu-projects/eu-projects.component.scss b/webapp/src/app/shared/ui/eu-projects/eu-projects.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/eu-projects/eu-projects.component.ts b/webapp/src/app/shared/ui/eu-projects/eu-projects.component.ts new file mode 100644 index 00000000..0876814b --- /dev/null +++ b/webapp/src/app/shared/ui/eu-projects/eu-projects.component.ts @@ -0,0 +1,49 @@ +import { Component, computed, input } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { OnInit } from '@angular/core'; +import { + AuthorPage, + DfgProjectPage, + TopicPageV2, + DfgPersonSummaryPage, +} from '../../../api'; + +import { EuCordisProjectSearchPage } from '../../../api/model/euCordisProjectSearchPage'; +import { EuCordisOrganizationSelectorPage } from '../../../api/model/euCordisOrganizationSelectorPage'; +import { ProjectFilterComponent } from '../project-filters/project-filters.component'; +import { EuProjectTableComponent } from '../eu-project-table/eu-project-table.component'; + +import { euProjectQueryParamKeys } from '../../../resolvers/eu-cordis-projects.resolver'; + +@Component({ + selector: 'app-eu-projects', + imports: [ProjectFilterComponent, EuProjectTableComponent], + templateUrl: './eu-projects.component.html', + styleUrl: './eu-projects.component.scss', +}) +export class EuProjectsComponent { + euCordisProjectPage = input.required(); + + selectedEuInstitutionsPage = + input.required(); + + selectedEuAuthorsPage = input.required(); + + selectedTopicsPage = input.required(); + + readonly euQueryParamKeys = euProjectQueryParamKeys; + + constructor( + private readonly router: Router, + private readonly activatedRoute: ActivatedRoute, + ) {} + + queryParamMap = toSignal(this.activatedRoute.queryParamMap, { + initialValue: this.activatedRoute.snapshot.queryParamMap, + }); + + readonly fuzzySearch = computed( + () => this.queryParamMap().get('fuzzy') === 'true', + ); +} From 2962b784adea442c4ecb5f65a6e4dbfd1c435d12 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 22 Jul 2026 23:41:27 +0200 Subject: [PATCH 13/26] added project type selector and institution selector for EU Cordis Projects --- ...hable-eu-institution-select.component.html | 12 ++++ ...hable-eu-institution-select.component.scss | 0 ...rchable-eu-institution-select.component.ts | 48 ++++++++++++++++ ...able-eu-project-type-select.component.html | 11 ++++ ...able-eu-project-type-select.component.scss | 0 ...chable-eu-project-type-select.component.ts | 57 +++++++++++++++++++ 6 files changed, 128 insertions(+) create mode 100644 webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.html create mode 100644 webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.scss create mode 100644 webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.ts create mode 100644 webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.html create mode 100644 webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.scss create mode 100644 webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.ts diff --git a/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.html b/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.html new file mode 100644 index 00000000..ea0f7c1f --- /dev/null +++ b/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.html @@ -0,0 +1,12 @@ + diff --git a/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.scss b/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.ts b/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.ts new file mode 100644 index 00000000..bbd4254b --- /dev/null +++ b/webapp/src/app/shared/ui/searchable-eu-institution-select/searchable-eu-institution-select.component.ts @@ -0,0 +1,48 @@ +import { Component, inject, input, output } from '@angular/core'; + +import { ProjectsService } from '../../../api'; +import { Observable } from 'rxjs'; +import { SearchableSelectComponent } from '../searchable-select/searchable-select.component'; +import { EuCordisOrganizationSelectorPage } from '../../../api/model/euCordisOrganizationSelectorPage'; +import { EuCordisOrganizationSelectorSummary } from '../../../api/model/euCordisOrganizationSelectorSummary'; +@Component({ + selector: 'app-searchable-eu-institution-select', + imports: [SearchableSelectComponent], + templateUrl: './searchable-eu-institution-select.component.html', + styleUrl: './searchable-eu-institution-select.component.scss', +}) +export class SearchableEuInstitutionSelectComponent { + private readonly projectsService = inject(ProjectsService); + + label = input('Institutionen'); + selectedInstitutions = + input.required(); + + handleInstitutionSelectChange = output(); + + fetchInstitutions = ( + searchTerm: string, + ): Observable => { + return this.projectsService.getEuOrganizationAutocompleteForSelector( + searchTerm, + ); + }; + + getInstitutionLabel = ( + institution: EuCordisOrganizationSelectorSummary, + ): string => { + return institution.name ?? institution.short_name ?? 'Institution'; + }; + + getInstitutionValue = ( + institution: EuCordisOrganizationSelectorSummary, + ): string => { + return institution.id!; + }; + + getInstitutionDescription = ( + institution: EuCordisOrganizationSelectorSummary, + ): string => { + return institution.country + ' - ' + institution.city; + }; +} diff --git a/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.html b/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.html new file mode 100644 index 00000000..f2d998e4 --- /dev/null +++ b/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.html @@ -0,0 +1,11 @@ + diff --git a/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.scss b/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.ts b/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.ts new file mode 100644 index 00000000..3a26e038 --- /dev/null +++ b/webapp/src/app/shared/ui/searchable-eu-project-type-select/searchable-eu-project-type-select.component.ts @@ -0,0 +1,57 @@ +import { Component, input, output } from '@angular/core'; +import { SearchableSelectComponent } from '../searchable-select/searchable-select.component'; +import { Observable } from 'rxjs'; + +export type ProjectType = { + id: string; + name: string; +}; + +export const projectTypes: ProjectType[] = [ + { id: 'h2020', name: 'Horizon 2020' }, + { id: 'heu', name: 'Horizon Europe' }, + { id: 'fp7', name: 'Framework Programme 7' }, +]; + +export const findprojectTypeById = (id: string): ProjectType | undefined => { + return projectTypes.find((projectType) => projectType.id === id); +}; + +type ProjectTypePage = { + elements?: ProjectType[]; + page?: number; + size?: number; + total?: number; +}; + +@Component({ + selector: 'app-searchable-eu-project-type-select', + imports: [SearchableSelectComponent], + templateUrl: './searchable-eu-project-type-select.component.html', + styleUrl: './searchable-eu-project-type-select.component.scss', +}) +export class SearchableEuProjectTypeSelectComponent { + label = input('Typen'); + selectedEuProjectTypes = input.required(); + + handleEuProjectTypeSelectChange = output(); + + fetchprojectTypes = (searchTerm: string): Observable => { + return new Observable((observer) => { + observer.next({ + elements: projectTypes.filter((projectType) => + projectType.name.toLowerCase().includes(searchTerm.toLowerCase()), + ), + }); + observer.complete(); + }); + }; + + getprojectTypeLabel = (projectType: ProjectType): string => { + return projectType.name; + }; + + getprojectTypeValue = (projectType: ProjectType): string => { + return projectType.id; + }; +} From 387a7d8da0fb26eae9e05617d9907c122ecf9195 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 22 Jul 2026 23:42:24 +0200 Subject: [PATCH 14/26] cleaned components due to new resolving logic and new DFG and EU components --- .../projects-results.component.html | 48 +++++-------- .../projects-results.component.ts | 68 ++++++------------ .../person-projects.component.html | 48 +++++-------- .../person-projects.component.ts | 72 +++++-------------- 4 files changed, 73 insertions(+), 163 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.html b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.html index dd9481b3..3d42eb98 100644 --- a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.html @@ -3,34 +3,22 @@
Projekte

Übersicht der durchgeführten Projekte.

- - - - - - - - - - - - - - + + + + + + diff --git a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts index aec16222..c58a9776 100644 --- a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts @@ -1,73 +1,45 @@ -import { Component, computed, input, signal } from '@angular/core'; -import { ActivatedRoute, Router } from '@angular/router'; -import { toSignal } from '@angular/core/rxjs-interop'; -import { DfgInstitutionSummaryPage } from '../../../../api/model/dfgInstitutionSummaryPage'; -import { - CordisEuProjectPage, - DfgProjectPage, - AuthorPage, - InstitutionPageV2, - DfgPersonSummaryPage, - TopicPageV2, -} from '../../../../api'; +import { Component } from '@angular/core'; +import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'; + import { MatCardModule } from '@angular/material/card'; import { MatTabsModule } from '@angular/material/tabs'; -import { ProjectFilterComponent } from '../../../../shared/ui/project-filters/project-filters.component'; -import { DfgProjectTableComponent } from '../../../../shared/ui/dfg-project-table/dfg-project-table.component'; -import { EuProjectTableComponent } from '../../../../shared/ui/eu-project-table/eu-project-table.component'; -import { projectQueryParamKeys } from '../../../../resolvers/dfg-projects.resolver'; -import { euProjectQueryParamKeys } from '../../../../resolvers/person-cordis-eu-project-page.resolver'; +import { OnInit, computed } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; +import { toSignal } from '@angular/core/rxjs-interop'; -const PROJECT_TAB_QUERY_PARAM_KEY = 'project_type'; - -import { SearchResultsStateService } from '../search-results-state.service'; @Component({ selector: 'app-projects-results', imports: [ MatCardModule, MatTabsModule, - ProjectFilterComponent, - DfgProjectTableComponent, - EuProjectTableComponent, + RouterLink, + RouterLinkActive, + RouterOutlet, ], templateUrl: './projects-results.component.html', styleUrl: './projects-results.component.scss', }) export class KeywordsToProjectsResultsComponent { - dfgProjectPage = input.required(); - personCordisEuProjectPage = input.required(); - - selectedDfgInstitutionsPage = input.required(); - selectedDfgAuthorsPage = input.required(); - selectedTopicsPage = input.required(); - - selectedEuInstitutionsPage = input.required(); - selectedEuAuthorsPage = input.required(); - - readonly dfgQueryParamKeys = projectQueryParamKeys; - readonly euQueryParamKeys = euProjectQueryParamKeys; - constructor( private readonly router: Router, private readonly activatedRoute: ActivatedRoute, ) {} - loading = signal(false); + queryParamMap = toSignal(this.activatedRoute.queryParamMap, { initialValue: this.activatedRoute.snapshot.queryParamMap, }); readonly fuzzySearch = computed( () => this.queryParamMap().get('fuzzy') === 'true', ); - selectedTabIndex = computed(() => { - const type = this.queryParamMap().get(PROJECT_TAB_QUERY_PARAM_KEY); - return type === 'eu' ? 1 : 0; - }); - onTabChange(index: number): void { - const type = index === 1 ? 'eu' : 'dfg'; - this.router.navigate([], { - queryParams: { [PROJECT_TAB_QUERY_PARAM_KEY]: type }, - queryParamsHandling: 'merge', - }); - } + readonly childRoutes = [ + { + path: 'dfg', + label: 'DFG-Projekte', + }, + { + path: 'eu', + label: 'EU-Projekte', + }, + ]; } diff --git a/webapp/src/app/modules/person-projects/person-projects.component.html b/webapp/src/app/modules/person-projects/person-projects.component.html index 5372cfb4..3d42eb98 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.html +++ b/webapp/src/app/modules/person-projects/person-projects.component.html @@ -3,34 +3,22 @@
Projekte

Übersicht der durchgeführten Projekte.

- - - - - - - - - - - - - - + + + + + + diff --git a/webapp/src/app/modules/person-projects/person-projects.component.ts b/webapp/src/app/modules/person-projects/person-projects.component.ts index 91dda724..359a9d9c 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -1,69 +1,31 @@ -import { Component, computed, input } from '@angular/core'; -import { ActivatedRoute, Router } from '@angular/router'; -import { toSignal } from '@angular/core/rxjs-interop'; -import { DfgInstitutionSummaryPage } from '../../api/model/dfgInstitutionSummaryPage'; -import { - CordisEuProjectPage, - DfgProjectPage, - AuthorPage, - InstitutionPageV2, - TopicPageV2, - DfgPersonSummaryPage, -} from '../../api'; +import { Component } from '@angular/core'; +import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'; + import { MatCardModule } from '@angular/material/card'; import { MatTabsModule } from '@angular/material/tabs'; -import { ProjectFilterComponent } from '../../shared/ui/project-filters/project-filters.component'; -import { DfgProjectTableComponent } from '../../shared/ui/dfg-project-table/dfg-project-table.component'; -import { EuProjectTableComponent } from '../../shared/ui/eu-project-table/eu-project-table.component'; -import { projectQueryParamKeys } from '../../resolvers/dfg-projects.resolver'; -import { euProjectQueryParamKeys } from '../../resolvers/person-cordis-eu-project-page.resolver'; - -const PROJECT_TAB_QUERY_PARAM_KEY = 'project_type'; @Component({ selector: 'app-person-projects', + standalone: true, imports: [ MatCardModule, MatTabsModule, - ProjectFilterComponent, - DfgProjectTableComponent, - EuProjectTableComponent, + RouterOutlet, + RouterLink, + RouterLinkActive, ], templateUrl: './person-projects.component.html', styleUrl: './person-projects.component.scss', }) export class PersonProjectsComponent { - dfgProjectPage = input.required(); - personCordisEuProjectPage = input.required(); - - selectedDfgInstitutionsPage = input.required(); - selectedDfgAuthorsPage = input.required(); - selectedEuInstitutionsPage = input.required(); - selectedEuAuthorsPage = input.required(); - selectedTopicsPage = input.required(); - - readonly dfgQueryParamKeys = projectQueryParamKeys; - readonly euQueryParamKeys = euProjectQueryParamKeys; - - constructor( - private readonly router: Router, - private readonly activatedRoute: ActivatedRoute, - ) {} - - queryParamMap = toSignal(this.activatedRoute.queryParamMap, { - initialValue: this.activatedRoute.snapshot.queryParamMap, - }); - - selectedTabIndex = computed(() => { - const type = this.queryParamMap().get(PROJECT_TAB_QUERY_PARAM_KEY); - return type === 'eu' ? 1 : 0; - }); - - onTabChange(index: number): void { - const type = index === 1 ? 'eu' : 'dfg'; - this.router.navigate([], { - queryParams: { [PROJECT_TAB_QUERY_PARAM_KEY]: type }, - queryParamsHandling: 'merge', - }); - } + readonly childRoutes = [ + { + path: 'dfg', + label: 'DFG-Projekte', + }, + { + path: 'eu', + label: 'EU-Projekte', + }, + ]; } From a103609485894a116215ec159f1c51825785f3d5 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 22 Jul 2026 23:42:50 +0200 Subject: [PATCH 15/26] new filters applied, table view fixed for EU Cordis projects --- .../eu-project-table.component.html | 143 ++++- .../eu-project-table.component.scss | 242 ++++++++ .../eu-project-table.component.ts | 495 +++++++++++++-- .../project-filters.component.html | 130 ++-- .../project-filters.component.ts | 573 ++++++++++++------ 5 files changed, 1316 insertions(+), 267 deletions(-) diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html index 46ba403b..47dc0938 100644 --- a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html +++ b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html @@ -1,6 +1,6 @@ @@ -10,16 +10,149 @@ [queryParamSizeKey]="queryParamKeys.size" [pageSizeOptions]="[10]" /> + + @if (project.project_type) { + + } @else { + - + } + + - {{ element.startDate | date: 'dd.MM.yyyy' }} + {{ getStartDate(element) | date: 'dd.MM.yyyy' }} - {{ element.endDate | date: 'dd.MM.yyyy' }} + {{ getEndDate(element) | date: 'dd.MM.yyyy' }} - {{ element.ecMaxContribution | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} + {{ getFundingAmount(element) | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} + + + + @let projectAuthors = getProjectAuthors(project); + @let isExpanded = isProjectAuthorsExpanded(project); + @let visibleAuthors = + isExpanded ? projectAuthors : projectAuthors.slice(0, 3); + +
+ @for (author of visibleAuthors; track getAuthorTrackId(author, $index)) { + + } @empty { + - + } + + @if (projectAuthors.length > 3) { + + } +
+
+ + + @let organizations = getProjectOrganizations(project); + @let isExpanded = isProjectOrganizationsExpanded(project); + @let visibleOrganizations = + isExpanded ? organizations : organizations.slice(0, 3); + +
+ @for ( + organization of visibleOrganizations; + track getOrganizationId(organization) + ) { + + } @empty { + - + } + + @if (organizations.length > 3) { + + } +
+
+ + + @let projectTopics = getProjectTopics(project); + @let isExpanded = isProjectTopicsExpanded(project); + @let visibleTopics = isExpanded ? projectTopics : projectTopics.slice(0, 3); + +
+ @for (topic of visibleTopics; track topic.id ?? $index) { + + + } @empty { + - + } + + @if (projectTopics.length > 3) { + + } +
diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss index e69de29b..4028f9e4 100644 --- a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss +++ b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss @@ -0,0 +1,242 @@ +.page { + padding: 28px 32px 42px; + max-width: 100%; + margin: 0 auto; +} + +// ------------------------ +// Shared tags & chips +// ------------------------ + +.publication-institution-tag { + display: inline-flex; + align-items: center; + padding: 2px 6px; + border: 1px solid var(--sg-primary-border, var(--sg-border)); + border-radius: 4px; + background: var(--sg-primary-soft); + color: var(--sg-primary); + font-size: 10px; + font-weight: 600; + line-height: normal; + max-width: 100%; + margin: 0; + font-family: inherit; + cursor: pointer; + transition: all 0.2s ease; + + &:hover, + &:focus-visible { + background: var(--sg-primary); + color: #fff; + border-color: var(--sg-primary); + outline: none; + box-shadow: + 0 0 0 2px var(--sg-background), + 0 0 0 4px var(--sg-primary); + } + + &.active { + border-color: var(--sg-primary); + box-shadow: + 0 0 0 1px #ffffff, + 0 0 0 3px var(--sg-primary); + } + + &.active:hover, + &.active:focus-visible { + background: var(--sg-primary); + color: #fff; + } + + .institution-icon { + flex-shrink: 0; + width: 12px; + height: 12px; + margin-right: 4px; + font-size: 12px; + } + + .institution-name { + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + min-width: 0; + white-space: normal; + overflow-wrap: anywhere; + } + + .flag-img { + flex-shrink: 0; + margin-left: 6px; + border: 1px solid; + } + + .country-code { + flex-shrink: 0; + margin-left: 2px; + font-size: 9px; + } + + .institution-open-icon { + flex-shrink: 0; + width: 12px; + height: 12px; + margin-left: 5px; + font-size: 12px; + line-height: 1; + cursor: pointer; + opacity: 0; + transition: opacity 0.15s ease; + } + + &:hover .institution-open-icon { + opacity: 0.7; + } + + .institution-open-icon:hover { + opacity: 1; + } +} + +.publication-institution-more { + display: inline-flex; + align-items: center; + min-height: 24px; + padding: 3px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text-muted); + font-family: inherit; + font-size: 11px; + line-height: 1.2; + cursor: pointer; + transition: all 0.2s ease; + + &:hover, + &:focus-visible { + border-color: var(--sg-primary); + color: var(--sg-primary); + background: var(--sg-surface-soft); + outline: none; + } +} + +// ------------------------ +// Containers for chips +// ------------------------ + +.topic-chips, +.institution-tags, +.author-tags { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.topic-chips { + max-width: 320px; +} + +.institution-tags { + align-items: flex-start; + max-width: 280px; +} + +.author-tags { + align-items: flex-start; + max-width: 280px; + padding: 0.5rem 0; +} + +// ------------------------ +// Empty text +// ------------------------ + +.empty-text { + color: rgba(0, 0, 0, 0.54); +} + +// ------------------------ +// Classification container +// ------------------------ + +.classification-container { + max-width: 200px; +} + +// ------------------------ +// Data table overrides (applied via ::ng-deep) +// ------------------------ + +::ng-deep { + .mat-mdc-header-cell { + color: var(--sg-text-muted); + font-size: 12px; + font-weight: 700; + } + + .mat-mdc-row { + height: 86px; + } + + .mat-mdc-cell { + color: var(--sg-text); + border-bottom-color: var(--sg-border); + font-size: 13px; + } + + .table-wrap { + .mat-column-type, + .mat-column-year, + .mat-column-language, + .mat-column-citations, + .mat-mdc-header-cell { + text-align: center; + } + + .mat-mdc-cell:not(:last-child), + .mat-mdc-header-cell:not(:last-child) { + border-right: 1px solid var(--sg-border); + } + + .mat-column-institutions, + .mat-column-topics { + overflow: visible; + } + } +} +.type-filter-btn { + display: inline-flex; + margin: 0; + padding: 0; + border: 0; + border-radius: 7px; + background: transparent; + cursor: pointer; + transition: box-shadow 0.2s ease; + + &:hover, + &:focus-visible { + outline: none; + box-shadow: 0 0 0 1px var(--sg-primary); + } + + &.active { + box-shadow: + 0 0 0 1px #ffffff, + 0 0 0 3px var(--sg-primary); + } +} + +// ------------------------ +// Responsive adjustments +// ------------------------ + +@media (max-width: 600px) { + .page { + padding: 16px; + } +} diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts index abd257a5..d0dd36ef 100644 --- a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts +++ b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts @@ -2,22 +2,35 @@ import { Component, computed, input, - OnInit, TemplateRef, viewChild, + inject, } from '@angular/core'; -import { CordisEuProject, CordisEuProjectPage } from '../../../api'; + +import { ActivatedRoute, Router, RouterModule } from '@angular/router'; +import { toSignal } from '@angular/core/rxjs-interop'; + +import { MatIconModule } from '@angular/material/icon'; +import { MatButtonModule } from '@angular/material/button'; +import { MatTooltip } from '@angular/material/tooltip'; +import { CurrencyPipe, DatePipe } from '@angular/common'; + import { DataTableComponent, GenericColumn, } from '../data-table/data-table.component'; -import { RouterModule } from '@angular/router'; -import { MatIconModule } from '@angular/material/icon'; -import { MatButtonModule } from '@angular/material/button'; -import { CurrencyPipe, DatePipe } from '@angular/common'; -import { QueryParamPaginatorComponent } from '../query-param-paginator/query-param-paginator.component'; -import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver'; +import { QueryParamPaginatorComponent } from '../query-param-paginator/query-param-paginator.component'; +import { TopicChipComponent } from '../topic-chip/topic-chip.component'; + +import { EuCordisProjectSearchPage } from '../../../api/model/euCordisProjectSearchPage'; +import { EuCordisProjectSummary } from '../../../api/model/euCordisProjectSummary'; +import { EuCordisOrganizationSummary } from '../../../api/model/euCordisOrganizationSummary'; +import { Author, Topic } from '../../../api'; + +import { euProjectQueryParamKeys } from '../../../resolvers/eu-cordis-projects.resolver'; +import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; +import { ChipComponent } from '../chip/chip.component'; @Component({ selector: 'app-eu-project-table', imports: [ @@ -25,54 +38,450 @@ import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver' RouterModule, MatIconModule, MatButtonModule, + MatTooltip, DatePipe, CurrencyPipe, QueryParamPaginatorComponent, + TopicChipComponent, + ChipComponent, ], templateUrl: './eu-project-table.component.html', styleUrl: './eu-project-table.component.scss', }) -export class EuProjectTableComponent implements OnInit { - page = input.required(); - queryParamKeys = projectQueryParamKeys; +export class EuProjectTableComponent { + private readonly activatedRoute = inject(ActivatedRoute); + private readonly router = inject(Router); - elements = computed(() => this.page().elements ?? []); - total = computed(() => this.page().total ?? 0); + queryParamKeys = euProjectQueryParamKeys; - columns: GenericColumn[] = []; + page = input(); - fundingStartTmp = viewChild.required>('fundingStartTmp'); - fundingEndTmp = viewChild.required>('fundingEndTmp'); - fundingAmountTmp = viewChild.required>('fundingAmountTmp'); - actionsTmp = viewChild.required>('actionsTmp'); + authorFilterEnabled = input(false); + institutionFilterEnabled = input(false); + topicFilterEnabled = input(false); - ngOnInit(): void { - this.columns = [ - { id: 'title', header: 'Titel', type: 'accessor', accessorKey: 'title' }, - { - id: 'startDate', - header: 'Startdatum', - type: 'display', - cellTemplate: this.fundingStartTmp(), + projects = computed(() => { + return this.page()?.elements ?? []; + }); + + total = computed(() => { + return this.page()?.total ?? 0; + }); + + queryParamMap = toSignal(this.activatedRoute.queryParamMap, { + initialValue: this.activatedRoute.snapshot.queryParamMap, + }); + + selectedAuthorIdsQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.authorId); + }); + + selectedOrganizationIdsQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.institutionId); + }); + + selectedTopicIdsQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.topicId); + }); + selectedTypesQueryParams = computed(() => { + return this.queryParamMap().getAll(this.queryParamKeys.projectType); + }); + + projectTypeTmp = viewChild.required>('projectTypeTmp'); + fundingStartTmp = viewChild.required>('fundingStartTmp'); + fundingEndTmp = viewChild.required>('fundingEndTmp'); + fundingAmountTmp = + viewChild.required>('fundingAmountTmp'); + + authorsTmp = viewChild.required>('authorsTmp'); + organizationsTmp = + viewChild.required>('organizationsTmp'); + topicsTmp = viewChild.required>('topicsTmp'); + + actionsTmp = viewChild.required>('actionsTmp'); + + expandedProjectAuthorsIds: string[] = []; + expandedProjectOrganizationsIds: string[] = []; + expandedProjectTopicsIds: string[] = []; + + columns = computed[]>(() => [ + { + id: 'title', + header: 'Titel', + type: 'accessor', + accessorKey: 'title', + }, + { + id: 'projectType', + header: 'Typ', + type: 'accessor', + accessorKey: 'project_type', + cellTemplate: this.projectTypeTmp(), + }, + { + id: 'startDate', + header: 'Startdatum', + type: 'accessor', + accessorKey: 'start_date', + cellTemplate: this.fundingStartTmp(), + }, + { + id: 'endDate', + header: 'Enddatum', + type: 'accessor', + accessorKey: 'end_date', + cellTemplate: this.fundingEndTmp(), + }, + { + id: 'ecMaxContribution', + header: 'Förderbetrag (EU)', + type: 'accessor', + accessorKey: 'ec_max_contribution', + cellTemplate: this.fundingAmountTmp(), + }, + { + id: 'authors', + header: 'Autoren', + type: 'display', + cellTemplate: this.authorsTmp(), + }, + { + id: 'organizations', + header: 'Organisationen', + type: 'display', + cellTemplate: this.organizationsTmp(), + }, + { + id: 'topics', + header: 'Themen', + type: 'display', + cellTemplate: this.topicsTmp(), + }, + { + id: 'actions', + header: '', + type: 'display', + cellTemplate: this.actionsTmp(), + }, + ]); + getProjectTypeColor(type: string | null | undefined): string { + //console.log(type); + const normalized = (type ?? '').toLowerCase(); + if (normalized == 'fp7') return 'success'; + if (normalized == 'h2020') return 'help'; + return 'info'; + } + isTypeActive(type: string): boolean { + return this.selectedTypesQueryParams().includes(type); + } + toggleTypeFilter(type: string): void { + const selectedTypes = this.selectedTypesQueryParams(); + if (selectedTypes.includes(type)) { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.projectType]: selectedTypes.filter( + (t) => t !== type, + ), + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } else { + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.projectType]: [...selectedTypes, type], + [this.queryParamKeys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + } + } + getProjectTypeLabel(element: EuCordisProjectSummary): string { + const value = (element as any).project_type ?? (element as any).projectType; + + switch (value) { + case 'fp7': + return 'FP7'; + case 'h2020': + return 'Horizon 2020'; + case 'heu': + return 'Horizon Europe'; + default: + return value ?? ''; + } + } + + getStartDate(element: EuCordisProjectSummary): string | Date | undefined { + return (element as any).start_date ?? (element as any).startDate; + } + + getEndDate(element: EuCordisProjectSummary): string | Date | undefined { + return (element as any).end_date ?? (element as any).endDate; + } + + getFundingAmount(element: EuCordisProjectSummary): number | undefined { + return ( + (element as any).ec_max_contribution ?? (element as any).ecMaxContribution + ); + } + + private getProjectId(project: EuCordisProjectSummary): string { + return String((project as any).id ?? ''); + } + + // ------------------------- + // Authors + // ------------------------- + + getProjectAuthors(project: EuCordisProjectSummary): Author[] { + return project.authors?.elements ?? []; + } + getAuthorTrackId(author: any, index: number): string { + return String( + this.getAuthorId(author) ?? this.getAuthorName(author) ?? index, + ); + } + + getAuthorId(author: any): string | null { + const id = + author?.id ?? + author?.author_id ?? + author?.authorId ?? + author?.openalex_id ?? + author?.openAlexId; + + return id == null ? null : String(id); + } + + getAuthorName(author: any): string { + return ( + author?.display_name ?? + author?.displayName ?? + author?.full_name ?? + author?.fullName ?? + author?.name ?? + '-' + ); + } + + isAuthorActive(authorId: string | null): boolean { + return ( + !!authorId && + this.authorFilterEnabled() && + this.selectedAuthorIdsQueryParams().includes(String(authorId)) + ); + } + + getAuthorTooltipText(author: any): string { + const name = this.getAuthorName(author); + const id = this.getAuthorId(author); + + if (!id) { + return `Autor: ${name}`; + } + + if (this.authorFilterEnabled()) { + return `Nach Autor filtern: ${name}`; + } + + return `Autor: ${name}`; + } + + filterByAuthor(author: any): void { + const authorId = this.getAuthorId(author); + + if (!authorId || !this.authorFilterEnabled()) return; + + const selectedAuthorIds = this.selectedAuthorIdsQueryParams(); + + const nextIds = selectedAuthorIds.includes(authorId) + ? selectedAuthorIds.filter((id) => id !== authorId) + : [...selectedAuthorIds, authorId]; + + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.authorId]: nextIds, + [this.queryParamKeys.page]: 0, }, - { - id: 'endDate', - header: 'Enddatum', - type: 'display', - cellTemplate: this.fundingEndTmp(), + queryParamsHandling: 'merge', + }); + } + + isProjectAuthorsExpanded(project: EuCordisProjectSummary): boolean { + const projectId = this.getProjectId(project); + return this.expandedProjectAuthorsIds.includes(projectId); + } + + toggleProjectAuthorsExpansion(project: EuCordisProjectSummary): void { + const projectId = this.getProjectId(project); + if (!projectId) return; + + this.expandedProjectAuthorsIds = this.expandedProjectAuthorsIds.includes( + projectId, + ) + ? this.expandedProjectAuthorsIds.filter((id) => id !== projectId) + : [...this.expandedProjectAuthorsIds, projectId]; + } + + // ------------------------- + // Organizations + // ------------------------- + + getProjectOrganizations( + project: EuCordisProjectSummary, + ): EuCordisOrganizationSummary[] { + const organizations = + (project as any).organizations ?? (project as any).organisations ?? []; + + if (!Array.isArray(organizations)) { + return []; + } + + const byId = new Map(); + + for (const organization of organizations) { + const id = this.getOrganizationId(organization); + if (!id) continue; + + byId.set(id, organization); + } + + return Array.from(byId.values()).sort((a, b) => + this.getOrganizationName(a).localeCompare(this.getOrganizationName(b)), + ); + } + + getOrganizationId( + organization: EuCordisOrganizationSummary | any, + ): string | null { + const id = organization?.organisation_id ?? organization?.id; + + return id == null ? null : String(id); + } + + getOrganizationName(organization: EuCordisOrganizationSummary | any): string { + return ( + organization?.name ?? + organization?.short_name ?? + organization?.organisation_id ?? + '-' + ); + } + + isOrganizationActive(organizationId: string | null): boolean { + return ( + !!organizationId && + this.institutionFilterEnabled() && + this.selectedOrganizationIdsQueryParams().includes(String(organizationId)) + ); + } + + getOrganizationTooltipText( + organization: EuCordisOrganizationSummary | any, + ): string { + const name = this.getOrganizationName(organization); + + if (this.institutionFilterEnabled()) { + return `Nach Organisation filtern: ${name}`; + } + + return `Organisation: ${name}`; + } + + filterByOrganization(organization: EuCordisOrganizationSummary | any): void { + const organizationId = this.getOrganizationId(organization); + + if (!organizationId || !this.institutionFilterEnabled()) return; + + const selectedOrganizationIds = this.selectedOrganizationIdsQueryParams(); + + const nextIds = selectedOrganizationIds.includes(organizationId) + ? selectedOrganizationIds.filter((id) => id !== organizationId) + : [...selectedOrganizationIds, organizationId]; + + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.institutionId]: nextIds, + [this.queryParamKeys.page]: 0, }, - { - id: 'ecMaxContribution', - header: 'Förderbetrag (EU)', - type: 'display', - cellTemplate: this.fundingAmountTmp(), + queryParamsHandling: 'merge', + }); + } + + isProjectOrganizationsExpanded(project: EuCordisProjectSummary): boolean { + const projectId = this.getProjectId(project); + return this.expandedProjectOrganizationsIds.includes(projectId); + } + + toggleProjectOrganizationsExpansion(project: EuCordisProjectSummary): void { + const projectId = this.getProjectId(project); + if (!projectId) return; + + this.expandedProjectOrganizationsIds = + this.expandedProjectOrganizationsIds.includes(projectId) + ? this.expandedProjectOrganizationsIds.filter((id) => id !== projectId) + : [...this.expandedProjectOrganizationsIds, projectId]; + } + + // ------------------------- + // Topics + // ------------------------- + + getProjectTopics(project: EuCordisProjectSummary): Topic[] { + const topics = (project as any).topics ?? []; + return Array.isArray(topics) ? topics : []; + } + + getWorkTopicColor(topic: Topic): string { + return topicHierarchyColor({ + id: topic.id, + name: topic.display_name, + field_id: topic.field?.id, + field_name: topic.field?.display_name, + domain_id: topic.domain?.id, + domain_name: topic.domain?.display_name, + }); + } + + isTopicActive(topic: Topic): boolean { + return ( + !!topic.id && + this.topicFilterEnabled() && + this.selectedTopicIdsQueryParams().includes(topic.id) + ); + } + + filterByTopic(topic: Topic): void { + if (!topic.id || !this.topicFilterEnabled()) return; + + const selectedTopicIds = this.selectedTopicIdsQueryParams(); + + const nextIds = selectedTopicIds.includes(topic.id) + ? selectedTopicIds.filter((id) => id !== topic.id) + : [...selectedTopicIds, topic.id]; + + this.router.navigate([], { + queryParams: { + [this.queryParamKeys.topicId]: nextIds, + [this.queryParamKeys.page]: 0, }, - { - id: 'actions', - header: '', - type: 'display', - cellTemplate: this.actionsTmp(), - }, - ]; + queryParamsHandling: 'merge', + }); + } + + isProjectTopicsExpanded(project: EuCordisProjectSummary): boolean { + const projectId = this.getProjectId(project); + return this.expandedProjectTopicsIds.includes(projectId); + } + + toggleProjectTopicsExpansion(project: EuCordisProjectSummary): void { + const projectId = this.getProjectId(project); + if (!projectId) return; + + this.expandedProjectTopicsIds = this.expandedProjectTopicsIds.includes( + projectId, + ) + ? this.expandedProjectTopicsIds.filter((id) => id !== projectId) + : [...this.expandedProjectTopicsIds, projectId]; } } diff --git a/webapp/src/app/shared/ui/project-filters/project-filters.component.html b/webapp/src/app/shared/ui/project-filters/project-filters.component.html index 9e84960d..dfba58c4 100644 --- a/webapp/src/app/shared/ui/project-filters/project-filters.component.html +++ b/webapp/src/app/shared/ui/project-filters/project-filters.component.html @@ -1,59 +1,93 @@
@if (showTitleFilter()) { } +
- @if (showFundingStartFilter()) { - +
+ @if (showFundingStartFilter()) { + + } + + @if (showFundingEndFilter()) { + + } + @if (showEuProjectTypeFilter() && filterMode() === 'eu') { + + } + + @if (showInstitutionFilter() && filterMode() === 'dfg') { + + } + + @if (showInstitutionFilter() && filterMode() === 'eu') { + + } + + @if (showAuthorFilter() && filterMode() === 'dfg') { + + } + + @if (showAuthorFilter() && filterMode() === 'eu') { + + } + + @if (showTopicFilter()) { + + } + + +
+ + + + @if (topicLegendGroups.length > 0) { + + } - @if (showFundingEndFilter()) { - - } - @if (showInstitutionFilter()) { - - } - @if (showAuthorFilter()) { - - } - @if (showTopicFilter()) { - - } -
- - @if (topicLegendGroups.length > 0) { - - - }
diff --git a/webapp/src/app/shared/ui/project-filters/project-filters.component.ts b/webapp/src/app/shared/ui/project-filters/project-filters.component.ts index 8d91cfe4..bafccf35 100644 --- a/webapp/src/app/shared/ui/project-filters/project-filters.component.ts +++ b/webapp/src/app/shared/ui/project-filters/project-filters.component.ts @@ -1,47 +1,77 @@ import { Component, computed, input } from '@angular/core'; import { Router } from '@angular/router'; import { toSignal } from '@angular/core/rxjs-interop'; + import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatSelectModule } from '@angular/material/select'; + import { DfgInstitutionSummaryPage } from '../../../api/model/dfgInstitutionSummaryPage'; import { DfgInstitutionSummary } from '../../../api/model/dfgInstitutionSummary'; + import { - buildTopicLegendGroups, - TopicLegendGroup, - TopicLegendTopic, -} from '../../../resolvers/utils/topic-legend'; -import { TopicLegendComponent } from '../topic-legend/topic-legend.component'; -import { + Author, + AuthorPage, DfgPersonSummary, DfgPersonSummaryPage, Topic, TopicPageV2, } from '../../../api'; + +import { EuCordisOrganizationSelectorPage } from '../../../api/model/euCordisOrganizationSelectorPage'; +import { EuCordisOrganizationSelectorSummary } from '../../../api/model/euCordisOrganizationSelectorSummary'; + +import { + buildTopicLegendGroups, + TopicLegendGroup, + TopicLegendTopic, +} from '../../../resolvers/utils/topic-legend'; + +import { TopicLegendComponent } from '../topic-legend/topic-legend.component'; import { QueryParamInputComponent } from '../query-param-input/query-param-input.component'; import { SearchableDfgInstitutionSelectComponent } from '../searchable-dfg-institution-select/searchable-dfg-institution-select.component'; - +import { SearchableEuInstitutionSelectComponent } from '../searchable-eu-institution-select/searchable-eu-institution-select.component'; import { SearchableYearSelectComponent } from '../searchable-year-select/searchable-year-select.component'; -import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver'; +import { SearchableDfgAuthorSelectComponent } from '../searchable-dfg-author-select/searchable-dfg-author-select.component'; +import { SearchableTopicSelectComponent } from '../searchable-topic-select/searchable-topic-select.component'; +import { + SearchableEuProjectTypeSelectComponent, + ProjectType, + findprojectTypeById, +} from '../searchable-eu-project-type-select/searchable-eu-project-type-select.component'; import { FilterObserver, SelectedFiltersComponent, } from '../selected-filters/selected-filters.component'; -import { map } from 'rxjs/internal/operators/map'; -import { SearchableDfgAuthorSelectComponent } from '../searchable-dfg-author-select/searchable-dfg-author-select.component'; -import { SearchableTopicSelectComponent } from '../searchable-topic-select/searchable-topic-select.component'; + +import { projectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver'; +import { euProjectQueryParamKeys } from '../../../resolvers/eu-cordis-projects.resolver'; +import { SearchableAuthorSelectComponent } from '../searchable-author-select/searchable-author-select.component'; + +type ProjectFilterMode = 'dfg' | 'eu'; + +type ProjectQueryParamKeys = + | typeof projectQueryParamKeys + | typeof euProjectQueryParamKeys; @Component({ selector: 'app-project-filters', imports: [ MatButtonModule, MatIconModule, + MatFormFieldModule, + MatSelectModule, QueryParamInputComponent, SearchableDfgInstitutionSelectComponent, + SearchableEuInstitutionSelectComponent, SearchableDfgAuthorSelectComponent, + SearchableAuthorSelectComponent, SearchableYearSelectComponent, SelectedFiltersComponent, SearchableTopicSelectComponent, TopicLegendComponent, + SearchableEuProjectTypeSelectComponent, ], templateUrl: './project-filters.component.html', styleUrl: './project-filters.component.scss', @@ -49,25 +79,17 @@ import { SearchableTopicSelectComponent } from '../searchable-topic-select/searc export class ProjectFilterComponent { constructor(private readonly router: Router) {} - // Each tab (DFG / EU) passes its OWN key set so they never collide. - queryParamKeys = projectQueryParamKeys; + filterMode = input('dfg'); + + queryParamKeys = input(projectQueryParamKeys); + + selectedDfgInstitutionsPage = input(); + selectedEuInstitutionsPage = input(); + + selectedDfgAuthorsPage = input(); + selectedEuAuthorsPage = input(); - // selectedAuthorsPage = input(); - // selectedAuthors = computed( - // () => this.selectedAuthorsPage()?.elements || [], - // ); - selectedAuthorsPage = input(); - selectedAuthors = computed( - () => this.selectedAuthorsPage()?.elements || [], - ); - selectedInstitutionsPage = input(); - selectedInstitutions = computed( - () => this.selectedInstitutionsPage()?.elements || [], - ); selectedTopicsPage = input(); - selectedTopics = computed( - () => this.selectedTopicsPage()?.elements || [], - ); showTitleFilter = input(true); showInstitutionFilter = input(true); @@ -75,87 +97,190 @@ export class ProjectFilterComponent { showFundingStartFilter = input(true); showFundingEndFilter = input(false); showTopicFilter = input(true); + showEuProjectTypeFilter = input(false); - subfieldLegendVisible = computed( - () => this.queryParamMap().get(this.queryParamKeys.legend) === 'true', + selectedDfgAuthors = computed( + () => this.selectedDfgAuthorsPage()?.elements || [], ); - subfieldLegendExpanded = computed( - () => - this.queryParamMap().get(this.queryParamKeys.legend_expanded) === 'true', + + selectedEuAuthors = computed( + () => this.selectedEuAuthorsPage()?.elements || [], + ); + + selectedDfgInstitutions = computed( + () => this.selectedDfgInstitutionsPage()?.elements || [], + ); + + selectedEuInstitutions = computed( + () => this.selectedEuInstitutionsPage()?.elements || [], + ); + + selectedTopics = computed( + () => this.selectedTopicsPage()?.elements || [], ); queryParamMap = toSignal(this.router.routerState.root.queryParamMap, { initialValue: this.router.routerState.snapshot.root.queryParamMap, }); - selectedInstitutionIds = computed(() => - this.queryParamMap().getAll(this.queryParamKeys.institutionId), + subfieldLegendVisible = computed( + () => this.queryParamMap().get(this.queryParamKeys().legend) === 'true', ); - selectedAuthorIds = computed(() => - this.queryParamMap().getAll(this.queryParamKeys.authorId), + subfieldLegendExpanded = computed( + () => + this.queryParamMap().get(this.queryParamKeys().legend_expanded) === + 'true', + ); + + selectedInstitutionIds = computed(() => + this.queryParamMap().getAll(this.queryParamKeys().institutionId), + ); + + euSelectedAuthorIds = computed(() => + this.queryParamMap().getAll(this.queryParamKeys().authorId), + ); + dfgSelectedAuthorIds = computed(() => + this.queryParamMap().getAll(this.queryParamKeys().authorId), ); selectedFundingStartYears = computed(() => - this.queryParamMap().getAll(this.queryParamKeys.funding_start).map(Number), + this.queryParamMap() + .getAll(this.queryParamKeys().funding_start) + .map(Number), ); + selectedFundingEndYears = computed(() => - this.queryParamMap().getAll(this.queryParamKeys.funding_end).map(Number), + this.queryParamMap().getAll(this.queryParamKeys().funding_end).map(Number), ); + + selectedEuProjectTypes = computed(() => { + const projectTypeIds = this.queryParamMap().getAll( + (this.queryParamKeys() as any).projectType, + ); + return projectTypeIds + .map((id) => findprojectTypeById(id)) + .filter((type) => type !== undefined) as ProjectType[]; + }); + fundingStartYearLabel = computed(() => { const selectedYears = this.selectedFundingStartYears(); - if (selectedYears.length === 0) { - return 'Förderbeginn'; - } else if (selectedYears.length === 1) { - return selectedYears[0].toString(); - } else { - return `${selectedYears.join(', ')} Jahre`; - } + + if (selectedYears.length === 0) return 'Förderbeginn'; + if (selectedYears.length === 1) return selectedYears[0].toString(); + + return `${selectedYears.join(', ')} Jahre`; }); fundingEndYearLabel = computed(() => { const selectedYears = this.selectedFundingEndYears(); - if (selectedYears.length === 0) { - return 'Förderende'; - } else if (selectedYears.length === 1) { - return selectedYears[0].toString(); - } else { - return `${selectedYears.join(', ')} Jahre`; - } + + if (selectedYears.length === 0) return 'Förderende'; + if (selectedYears.length === 1) return selectedYears[0].toString(); + + return `${selectedYears.join(', ')} Jahre`; }); - institutionLabel = computed(() => { - const selected = this.selectedInstitutions().filter((i) => + dfgInstitutionLabel = computed(() => { + const selected = this.selectedDfgInstitutions().filter((i) => this.selectedInstitutionIds().includes(String(i.id!)), ); + if (selected.length === 0) return 'Institution'; - if (selected.length === 1) + if (selected.length === 1) { return selected[0].institute_name_de ?? 'Institution'; + } + + return `${selected.length} Institutionen`; + }); + euProjectTypeLabel = computed(() => { + const selected = this.selectedEuProjectTypes(); + + if (selected.length === 0) return 'Projekttyp'; + if (selected.length === 1) { + switch (selected[0].id) { + case 'fp7': + return 'FP7'; + case 'h2020': + return 'Horizon 2020'; + case 'heu': + return 'Horizon Europe'; + default: + return selected[0].name ?? 'Projekttyp'; + } + } + + return `${selected.length} Projekttypen`; + }); + + euInstitutionLabel = computed(() => { + const selected = this.selectedEuInstitutions().filter((org) => + this.selectedInstitutionIds().includes(String(org.organisation_id)), + ); + + if (selected.length === 0) return 'Institution'; + if (selected.length === 1) { + return selected[0].name ?? selected[0].short_name ?? 'Institution'; + } + return `${selected.length} Institutionen`; }); - authorLabel = computed(() => { - const selected = this.selectedAuthors().filter((a) => - this.selectedAuthorIds().includes(String(a.person_id!)), + dfgAuthorLabel = computed(() => { + const selected = this.selectedDfgAuthors().filter((a) => + this.dfgSelectedAuthorIds().includes(String(a.person_id!)), ); + if (selected.length === 0) return 'Autor'; if (selected.length === 1) return selected[0].full_name ?? 'Autor'; + return `${selected.length} Autoren`; }); + euAuthorLabel = computed(() => { + const selected = this.selectedEuAuthors().filter((a: any) => + this.euSelectedAuthorIds().includes(String(a.id)), + ); + + if (selected.length === 0) return 'Autor'; + if (selected.length === 1) { + return selected[0].display_name ?? 'Autor'; + } + + return `${selected.length} Autoren`; + }); + + topicLabel = computed(() => { + const selectedTopicIds = this.selectedTopics().map((t) => t.id); + + if (selectedTopicIds.length === 0) return 'Thema'; + + if (selectedTopicIds.length === 1) { + const topic = this.selectedTopics()[0]; + return topic.display_name || 'Thema'; + } + + return `${selectedTopicIds.length} Themen`; + }); + observers = computed(() => { - const keys = this.queryParamKeys; - return [ - { id: 'search', queryParamKey: keys.title, icon: 'search' }, + const keys = this.queryParamKeys(); + + const observers: FilterObserver[] = [ + { + id: 'search', + queryParamKey: keys.title, + icon: 'search', + }, { id: 'fundingStart', - queryParamKey: projectQueryParamKeys.funding_start, + queryParamKey: keys.funding_start, icon: 'calendar_today', valueFormatter: (value: string) => `Förderbeginn ${value}`, }, { id: 'fundingEnd', - queryParamKey: projectQueryParamKeys.funding_end, + queryParamKey: keys.funding_end, icon: 'event_busy', valueFormatter: (value: string) => `Förderende ${value}`, }, @@ -163,19 +288,40 @@ export class ProjectFilterComponent { id: 'institutions', queryParamKey: keys.institutionId, icon: 'apartment', - valueFormatter: (value: string) => - this.selectedInstitutions().find((i) => String(i.id) === value) - ?.institute_name_de ?? value, + valueFormatter: (value: string) => { + if (this.filterMode() === 'eu') { + return ( + this.selectedEuInstitutions().find( + (org) => String(org.organisation_id) === value, + )?.name ?? 'pizda' + ); + } + + return ( + this.selectedDfgInstitutions().find((i) => String(i.id) === value) + ?.institute_name_de ?? value + ); + }, }, { id: 'authors', queryParamKey: keys.authorId, icon: 'person', - valueFormatter: (value: string) => - this.selectedAuthors().find((a) => String(a.person_id) === value) - ?.full_name ?? value, - }, + valueFormatter: (value: string) => { + if (this.filterMode() === 'eu') { + const author = this.selectedEuAuthors().find( + (a: any) => String(a.id) === value, + ) as any; + return author?.display_name ?? author?.full_name ?? value; + } + + return ( + this.selectedDfgAuthors().find((a) => String(a.person_id) === value) + ?.full_name ?? value + ); + }, + }, { id: 'topics', queryParamKey: keys.topicId, @@ -186,149 +332,232 @@ export class ProjectFilterComponent { }, }, ]; + + if (this.filterMode() === 'eu') { + const euKeys = keys as typeof euProjectQueryParamKeys; + + observers.push({ + id: 'projectTypes', + queryParamKey: euKeys.projectType, + icon: 'category', + valueFormatter: (value: string) => { + switch (value) { + case 'fp7': + return 'Framework Programme 7'; + case 'h2020': + return 'Horizon 2020'; + case 'heu': + return 'Horizon Europe'; + default: + return value; + } + }, + }); + } + + return observers; }); handleFundingStartSelectChange = (selectedYear: number): void => { - if (this.selectedFundingStartYears().includes(selectedYear)) { - this.router.navigate([], { - queryParams: { - [projectQueryParamKeys.funding_start]: - this.selectedFundingStartYears().filter( - (year) => year !== selectedYear, - ), - }, - queryParamsHandling: 'merge', - }); - } else { - this.router.navigate([], { - queryParams: { - [projectQueryParamKeys.funding_start]: [ - ...this.selectedFundingStartYears(), - selectedYear, - ], - }, - queryParamsHandling: 'merge', - }); - } - }; - handleFundingEndSelectChange = (selectedYear: number): void => { - if (this.selectedFundingEndYears().includes(selectedYear)) { - this.router.navigate([], { - queryParams: { - [projectQueryParamKeys.funding_end]: - this.selectedFundingEndYears().filter( - (year) => year !== selectedYear, - ), - }, - queryParamsHandling: 'merge', - }); - } else { - this.router.navigate([], { - queryParams: { - [projectQueryParamKeys.funding_end]: [ - ...this.selectedFundingEndYears(), - selectedYear, - ], - }, - queryParamsHandling: 'merge', - }); - } - }; - handleLegendVisibleChange = (visible: boolean): void => { + const keys = this.queryParamKeys(); + const selectedYears = this.selectedFundingStartYears(); + + const nextYears = selectedYears.includes(selectedYear) + ? selectedYears.filter((year) => year !== selectedYear) + : [...selectedYears, selectedYear]; + this.router.navigate([], { queryParams: { - [this.queryParamKeys.legend]: visible ? 'true' : null, + [keys.funding_start]: nextYears, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + }; + + handleFundingEndSelectChange = (selectedYear: number): void => { + const keys = this.queryParamKeys(); + const selectedYears = this.selectedFundingEndYears(); + + const nextYears = selectedYears.includes(selectedYear) + ? selectedYears.filter((year) => year !== selectedYear) + : [...selectedYears, selectedYear]; + + this.router.navigate([], { + queryParams: { + [keys.funding_end]: nextYears, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + }; + + handleLegendVisibleChange = (visible: boolean): void => { + const keys = this.queryParamKeys(); + + this.router.navigate([], { + queryParams: { + [keys.legend]: visible ? 'true' : null, }, queryParamsHandling: 'merge', }); }; handleLegendExpandedChange = (expanded: boolean): void => { + const keys = this.queryParamKeys(); + this.router.navigate([], { queryParams: { - [this.queryParamKeys.legend_expanded]: expanded ? 'true' : null, + [keys.legend_expanded]: expanded ? 'true' : null, }, queryParamsHandling: 'merge', }); }; - handleInstitutionSelectChange = ( + handleDfgInstitutionSelectChange = ( institution: DfgInstitutionSummary, ): void => { if (!institution.id) return; - const keys = this.queryParamKeys; + + const keys = this.queryParamKeys(); const selectedIds = this.selectedInstitutionIds(); + const nextIds = selectedIds.includes(String(institution.id)) ? selectedIds.filter((id) => id !== String(institution.id)) : [...selectedIds, String(institution.id)]; this.router.navigate([], { - queryParams: { [keys.institutionId]: nextIds, [keys.page]: 0 }, + queryParams: { + [keys.institutionId]: nextIds, + [keys.page]: 0, + }, queryParamsHandling: 'merge', }); }; - handleAuthorSelectChange = (author: DfgPersonSummary): void => { - if (!author.person_id) return; - const keys = this.queryParamKeys; - const selectedIds = this.selectedAuthorIds(); - const nextIds = selectedIds.includes(String(author.person_id)) - ? selectedIds.filter((id) => id !== String(author.person_id)) - : [...selectedIds, String(author.person_id)]; + handleEuInstitutionSelectChange = ( + organization: EuCordisOrganizationSelectorSummary, + ): void => { + if (!organization.organisation_id) return; + + const keys = this.queryParamKeys(); + const selectedIds = this.selectedInstitutionIds(); + + const organizationId = String(organization.organisation_id); + + const nextIds = selectedIds.includes(organizationId) + ? selectedIds.filter((id) => id !== organizationId) + : [...selectedIds, organizationId]; this.router.navigate([], { - queryParams: { [keys.authorId]: nextIds, [keys.page]: 0 }, + queryParams: { + [keys.institutionId]: nextIds, + [keys.page]: 0, + }, queryParamsHandling: 'merge', }); }; - topicLabel = computed(() => { - const selectedTopicIds = this.selectedTopics().map((t) => t.id); - if (selectedTopicIds.length === 0) { - return 'Thema'; - } else if (selectedTopicIds.length === 1) { - const topic = this.selectedTopics()[0]; - return topic.display_name || 'Thema'; - } else { - return `${selectedTopicIds.length} Themen`; - } - }); + handleDfgAuthorSelectChange = (author: DfgPersonSummary): void => { + if (!author.person_id) return; + + const keys = this.queryParamKeys(); + const selectedIds = this.dfgSelectedAuthorIds(); + + const authorId = String(author.person_id); + + const nextIds = selectedIds.includes(authorId) + ? selectedIds.filter((id) => id !== authorId) + : [...selectedIds, authorId]; + + this.router.navigate([], { + queryParams: { + [keys.authorId]: nextIds, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + }; + + handleEuAuthorSelectChange = (author: Author): void => { + const rawAuthor = author as any; + if (!rawAuthor.id) return; + + const keys = this.queryParamKeys(); + const selectedIds = this.euSelectedAuthorIds(); + + const authorId = String(rawAuthor.id); + + const nextIds = selectedIds.includes(authorId) + ? selectedIds.filter((id) => id !== authorId) + : [...selectedIds, authorId]; + + this.router.navigate([], { + queryParams: { + [keys.authorId]: nextIds, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + }; handleTopicSelectChange = (selectedTopic: Topic): void => { - if (this.selectedTopics().some((t) => t.id === selectedTopic.id)) { - this.router.navigate([], { - queryParams: { - [this.queryParamKeys.topicId]: this.selectedTopics() - .filter((t) => t.id !== selectedTopic.id) - .map((t) => t.id), - }, - queryParamsHandling: 'merge', - }); - } else { - this.router.navigate([], { - queryParams: { - [this.queryParamKeys.topicId]: [ - ...this.selectedTopics().map((t) => t.id!), - selectedTopic.id, - ], - }, - queryParamsHandling: 'merge', - }); - } + const keys = this.queryParamKeys(); + const selectedTopicIds = this.selectedTopics().map((t) => t.id!); + + const nextIds = selectedTopicIds.includes(selectedTopic.id!) + ? selectedTopicIds.filter((id) => id !== selectedTopic.id) + : [...selectedTopicIds, selectedTopic.id!]; + + this.router.navigate([], { + queryParams: { + [keys.topicId]: nextIds, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); + }; + + handleEuProjectTypeSelectChange = ( + selectedProjectTypes: ProjectType, + ): void => { + const keys = this.queryParamKeys() as typeof euProjectQueryParamKeys; + + this.router.navigate([], { + queryParams: { + [keys.projectType]: selectedProjectTypes.id, + [keys.page]: 0, + }, + queryParamsHandling: 'merge', + }); }; resetFilters = (): void => { - const keys = this.queryParamKeys; + const keys = this.queryParamKeys(); + + const resetQueryParams: Record = { + [keys.title]: null, + [keys.institutionId]: null, + [keys.authorId]: null, + [keys.funding_start]: null, + [keys.funding_end]: null, + [keys.topicId]: null, + [keys.legend]: null, + [keys.legend_expanded]: null, + [keys.page]: 0, + }; + + if (this.filterMode() === 'eu') { + const euKeys = keys as typeof euProjectQueryParamKeys; + resetQueryParams[euKeys.projectType] = null; + resetQueryParams[euKeys.country] = null; + resetQueryParams[euKeys.frameworkProgramme] = null; + resetQueryParams[euKeys.fundingScheme] = null; + resetQueryParams[euKeys.status] = null; + } + this.router.navigate([], { - queryParams: { - [keys.title]: null, - [keys.institutionId]: null, - [keys.authorId]: null, - [keys.funding_start]: null, - [keys.topicId]: null, - [keys.funding_end]: null, - [keys.page]: 0, - }, + queryParams: resetQueryParams, queryParamsHandling: 'merge', }); }; @@ -337,8 +566,10 @@ export class ProjectFilterComponent { const topics = this.selectedTopics().map((topic) => this.toTopicLegendTopic(topic), ); + return buildTopicLegendGroups(topics); } + private toTopicLegendTopic(topic: Topic): TopicLegendTopic { return { id: topic.id ?? topic.display_name ?? '', From a344c3f05562b3c9f43849a661e5b893bf52024a Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 23 Jul 2026 00:04:32 +0200 Subject: [PATCH 16/26] added log to frontend for EU projects --- .../ui/eu-projects/eu-projects.component.ts | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/webapp/src/app/shared/ui/eu-projects/eu-projects.component.ts b/webapp/src/app/shared/ui/eu-projects/eu-projects.component.ts index 0876814b..d9b0c770 100644 --- a/webapp/src/app/shared/ui/eu-projects/eu-projects.component.ts +++ b/webapp/src/app/shared/ui/eu-projects/eu-projects.component.ts @@ -1,13 +1,7 @@ -import { Component, computed, input } from '@angular/core'; +import { Component, computed, input, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { toSignal } from '@angular/core/rxjs-interop'; -import { OnInit } from '@angular/core'; -import { - AuthorPage, - DfgProjectPage, - TopicPageV2, - DfgPersonSummaryPage, -} from '../../../api'; +import { AuthorPage, TopicPageV2 } from '../../../api'; import { EuCordisProjectSearchPage } from '../../../api/model/euCordisProjectSearchPage'; import { EuCordisOrganizationSelectorPage } from '../../../api/model/euCordisOrganizationSelectorPage'; @@ -22,7 +16,7 @@ import { euProjectQueryParamKeys } from '../../../resolvers/eu-cordis-projects.r templateUrl: './eu-projects.component.html', styleUrl: './eu-projects.component.scss', }) -export class EuProjectsComponent { +export class EuProjectsComponent implements OnInit { euCordisProjectPage = input.required(); selectedEuInstitutionsPage = @@ -38,7 +32,9 @@ export class EuProjectsComponent { private readonly router: Router, private readonly activatedRoute: ActivatedRoute, ) {} - + ngOnInit(): void { + console.log('EU PROJECTS', this.euCordisProjectPage()); + } queryParamMap = toSignal(this.activatedRoute.queryParamMap, { initialValue: this.activatedRoute.snapshot.queryParamMap, }); From 2f5ed6ad154558b748077378b2b6a1c94a3bd97e Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 23 Jul 2026 00:05:29 +0200 Subject: [PATCH 17/26] regenerated missing models --- webapp/src/app/api/.openapi-generator/FILES | 16 + webapp/src/app/api/api/projects.service.ts | 1064 +++++++++-------- webapp/src/app/api/model/careerStage.ts | 20 + .../src/app/api/model/companyStatusFilter.ts | 18 + webapp/src/app/api/model/filterType.ts | 17 + webapp/src/app/api/model/keywordOperator.ts | 17 + webapp/src/app/api/model/publicationType.ts | 39 + .../app/api/model/selectedAuthorsRequest.ts | 42 + webapp/src/app/api/model/subfieldShare.ts | 22 + webapp/src/app/api/model/timespan.ts | 22 + 10 files changed, 809 insertions(+), 468 deletions(-) create mode 100644 webapp/src/app/api/model/careerStage.ts create mode 100644 webapp/src/app/api/model/companyStatusFilter.ts create mode 100644 webapp/src/app/api/model/filterType.ts create mode 100644 webapp/src/app/api/model/keywordOperator.ts create mode 100644 webapp/src/app/api/model/publicationType.ts create mode 100644 webapp/src/app/api/model/selectedAuthorsRequest.ts create mode 100644 webapp/src/app/api/model/subfieldShare.ts create mode 100644 webapp/src/app/api/model/timespan.ts diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 11257e71..9122548b 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -22,6 +22,7 @@ api/patents.service.ts api/personNetwork.service.ts api/persons.service.ts api/projects.service.ts +api/ranking.service.ts api/topics.service.ts api/topicsV2.service.ts api/universityRankings.service.ts @@ -40,11 +41,15 @@ model/author.ts model/authorAffiliationsInner.ts model/authorCountsByYearInner.ts model/authorIds.ts +model/authorMetricsRequest.ts model/authorNetworkNode.ts model/authorPage.ts model/authorParsedLongestName.ts model/authorPositionCount.ts +model/authorStaticStats.ts model/authorSummaryStats.ts +model/authorTopicProfile.ts +model/authorTopicStats.ts model/authorsFilterProperties.ts model/authorsListResponse.ts model/authorship.ts @@ -63,11 +68,13 @@ model/bundProject.ts model/bundProjectDetails.ts model/bundProjectPage.ts model/careerMetrics.ts +model/careerStage.ts model/collaborationNetwork.ts model/collaborationNetworkEdge.ts model/collaborationNetworkNodeType.ts model/companyConnection.ts model/companyConnectionsResponse.ts +model/companyStatusFilter.ts model/cordisEuProject.ts model/cordisEuProjectPage.ts model/costUsd.ts @@ -108,6 +115,7 @@ model/extractedKeywordsResponse.ts model/fileUpload.ts model/filterInformation.ts model/filterProperties.ts +model/filterType.ts model/fp7EurosciVoc.ts model/fp7LegalBasis.ts model/fp7Organization.ts @@ -159,11 +167,13 @@ model/ipcClassification.ts model/keywordEntry.ts model/keywordEntryWithTopic.ts model/keywordEvidence.ts +model/keywordOperator.ts model/keywordPatentLevel.ts model/keywordPatentMappingStatus.ts model/keywordPatentMatch.ts model/keywordPatentSearchDiagnostics.ts model/keywordPatentSearchItem.ts +model/keywordToAuthorRequest.ts model/keywordTopicMatch.ts model/keywords.ts model/keywordsRequest.ts @@ -203,11 +213,17 @@ model/projectsFilteringProperties.ts model/projectsSortBy.ts model/publicationDetailByFunder.ts model/publicationIdsByAuthorPosition.ts +model/publicationType.ts model/publicationsByAuthorResponse.ts +model/rankedAuthor.ts model/rankingResponse.ts +model/rankingWeights.ts model/rebuildResponse.ts model/score.ts +model/selectedAuthorsRequest.ts model/sortDirection.ts +model/subfieldShare.ts +model/timespan.ts model/tokenType.ts model/topAuthor.ts model/topAuthorStatistics.ts diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index cc45ae68..a63fc5bc 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -202,184 +202,12 @@ export class ProjectsService extends BaseService { ); }); } - - /** - * Returns EU CORDIS organizations based on a search term. - * @endpoint get /api/eu/organizations/autocomplete/selector - * @param query Search term for organization autocomplete. - * @param page - * @param size - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getEuOrganizationAutocompleteForSelector(query?: string, page?: number, size?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getEuOrganizationAutocompleteForSelector(query?: string, page?: number, size?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getEuOrganizationAutocompleteForSelector(query?: string, page?: number, size?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getEuOrganizationAutocompleteForSelector(query?: string, page?: number, size?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - size, 'size'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/eu/organizations/autocomplete/selector`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Returns EU CORDIS organizations by organisation IDs. - * @endpoint get /api/eu/organizations/ids - * @param organizationIds CORDIS organisation IDs to retrieve. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getEuOrganizationsByIds(organizationIds?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getEuOrganizationsByIds(organizationIds?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getEuOrganizationsByIds(organizationIds?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getEuOrganizationsByIds(organizationIds?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - if (organizationIds) { - organizationIds.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'organization_ids'); - }) - } - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/eu/organizations/ids`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Get EU projects for an author. - * Returns a list of EU projects associated with the specified author ID. - * @endpoint get /api/projects/author/{raw_oa_author_id}/eu - * @param rawOaAuthorId The author ID to filter by. - * @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 getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getEuProjectsForAuthor(rawOaAuthorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (rawOaAuthorId === null || rawOaAuthorId === undefined) { - throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getEuProjectsForAuthor.'); - } - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/projects/author/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/eu`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + if (institutionIds) { + institutionIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'institution_ids', ); }); } @@ -509,6 +337,238 @@ export class ProjectsService extends BaseService { ); } + /** + * Returns EU CORDIS organizations based on a search term. + * @endpoint get /api/eu/organizations/autocomplete/selector + * @param query Search term for organization autocomplete. + * @param page + * @param size + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getEuOrganizationAutocompleteForSelector( + query?: string, + page?: number, + size?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getEuOrganizationAutocompleteForSelector( + query?: string, + page?: number, + size?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getEuOrganizationAutocompleteForSelector( + query?: string, + page?: number, + size?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getEuOrganizationAutocompleteForSelector( + query?: string, + page?: number, + size?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + size, + 'size', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/eu/organizations/autocomplete/selector`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns EU CORDIS organizations by organisation IDs. + * @endpoint get /api/eu/organizations/ids + * @param organizationIds CORDIS organisation IDs to retrieve. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getEuOrganizationsByIds( + organizationIds?: Array, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getEuOrganizationsByIds( + organizationIds?: Array, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getEuOrganizationsByIds( + organizationIds?: Array, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getEuOrganizationsByIds( + organizationIds?: Array, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (organizationIds) { + organizationIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'organization_ids', + ); + }); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/eu/organizations/ids`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + /** * Get EU projects for an author. * Returns a list of EU projects associated with the specified author ID. @@ -1379,6 +1439,353 @@ export class ProjectsService extends BaseService { ); } + /** + * Search EU CORDIS projects. + * Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and Horizon Europe. + * @endpoint get /api/projects/eu/search + * @param authorId OpenAlex author ID to filter by. + * @param authorIds Additional OpenAlex author IDs to filter by. All selected authors must match. + * @param organizationIds CORDIS organisation IDs. All selected organizations must match. + * @param organizationNames CORDIS organization names. All selected organizations must match. + * @param projectTypes Project types to include: fp7, h2020, heu. + * @param title Project title/acronym search. + * @param keywords Raw keywords to search in title/objective/keywords/topics. + * @param topicIds OpenAlex topic IDs used for fuzzy topic resolution. + * @param filterTopicIds Additional OpenAlex topic IDs used as mandatory filters. + * @param fundingStartYears Funding start years. + * @param fundingEndYears Funding end years. + * @param countries Organization countries. + * @param frameworkProgrammes Framework programme filters. + * @param fundingSchemes Funding scheme filters. + * @param statuses Project status filters. + * @param page The page number. + * @param size The page size. + * @param sortBy Sort field. + * @param sortDirection Sort direction: asc or desc. + * @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public searchEuCordisProjectsSummary( + authorId?: string, + authorIds?: Array, + organizationIds?: Array, + organizationNames?: Array, + projectTypes?: Array, + title?: string, + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fundingStartYears?: Array, + fundingEndYears?: Array, + countries?: Array, + frameworkProgrammes?: Array, + fundingSchemes?: Array, + statuses?: Array, + page?: number, + size?: number, + sortBy?: string, + sortDirection?: string, + fuzzy?: boolean, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchEuCordisProjectsSummary( + authorId?: string, + authorIds?: Array, + organizationIds?: Array, + organizationNames?: Array, + projectTypes?: Array, + title?: string, + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fundingStartYears?: Array, + fundingEndYears?: Array, + countries?: Array, + frameworkProgrammes?: Array, + fundingSchemes?: Array, + statuses?: Array, + page?: number, + size?: number, + sortBy?: string, + sortDirection?: string, + fuzzy?: boolean, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchEuCordisProjectsSummary( + authorId?: string, + authorIds?: Array, + organizationIds?: Array, + organizationNames?: Array, + projectTypes?: Array, + title?: string, + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fundingStartYears?: Array, + fundingEndYears?: Array, + countries?: Array, + frameworkProgrammes?: Array, + fundingSchemes?: Array, + statuses?: Array, + page?: number, + size?: number, + sortBy?: string, + sortDirection?: string, + fuzzy?: boolean, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchEuCordisProjectsSummary( + authorId?: string, + authorIds?: Array, + organizationIds?: Array, + organizationNames?: Array, + projectTypes?: Array, + title?: string, + keywords?: Array, + topicIds?: Array, + filterTopicIds?: Array, + fundingStartYears?: Array, + fundingEndYears?: Array, + countries?: Array, + frameworkProgrammes?: Array, + fundingSchemes?: Array, + statuses?: Array, + page?: number, + size?: number, + sortBy?: string, + sortDirection?: string, + fuzzy?: boolean, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorId, + 'author_id', + ); + if (authorIds) { + authorIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'author_ids', + ); + }); + } + if (organizationIds) { + organizationIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'organization_ids', + ); + }); + } + if (organizationNames) { + organizationNames.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'organization_names', + ); + }); + } + if (projectTypes) { + projectTypes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'project_types', + ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + title, + 'title', + ); + if (keywords) { + keywords.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'keywords', + ); + }); + } + if (topicIds) { + topicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topic_ids', + ); + }); + } + if (filterTopicIds) { + filterTopicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'filter_topic_ids', + ); + }); + } + if (fundingStartYears) { + fundingStartYears.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'funding_start_years', + ); + }); + } + if (fundingEndYears) { + fundingEndYears.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'funding_end_years', + ); + }); + } + if (countries) { + countries.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'countries', + ); + }); + } + if (frameworkProgrammes) { + frameworkProgrammes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'framework_programmes', + ); + }); + } + if (fundingSchemes) { + fundingSchemes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'funding_schemes', + ); + }); + } + if (statuses) { + statuses.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'statuses', + ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + size, + 'size', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortBy, + 'sort_by', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortDirection, + 'sort_direction', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + fuzzy, + 'fuzzy', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/projects/eu/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + /** * Search projects across all funders. * Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter. @@ -1505,296 +1912,17 @@ export class ProjectsService extends BaseService { const localVarTransferCache: boolean = options?.transferCache ?? true; - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - // to determine the Content-Type header - const consumes: string[] = [ - 'application/json' - ]; - const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/projects/institution/eu/search`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: projectsFilteringProperties, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Search EU CORDIS projects. - * Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and Horizon Europe. - * @endpoint get /api/projects/eu/search - * @param authorId OpenAlex author ID to filter by. - * @param authorIds Additional OpenAlex author IDs to filter by. All selected authors must match. - * @param organizationIds CORDIS organisation IDs. All selected organizations must match. - * @param organizationNames CORDIS organization names. All selected organizations must match. - * @param projectTypes Project types to include: fp7, h2020, heu. - * @param title Project title/acronym search. - * @param keywords Raw keywords to search in title/objective/keywords/topics. - * @param topicIds OpenAlex topic IDs used for fuzzy topic resolution. - * @param filterTopicIds Additional OpenAlex topic IDs used as mandatory filters. - * @param fundingStartYears Funding start years. - * @param fundingEndYears Funding end years. - * @param countries Organization countries. - * @param frameworkProgrammes Framework programme filters. - * @param fundingSchemes Funding scheme filters. - * @param statuses Project status filters. - * @param page The page number. - * @param size The page size. - * @param sortBy Sort field. - * @param sortDirection Sort direction: asc or desc. - * @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public searchEuCordisProjectsSummary(authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchEuCordisProjectsSummary(authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchEuCordisProjectsSummary(authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchEuCordisProjectsSummary(authorId?: string, authorIds?: Array, organizationIds?: Array, organizationNames?: Array, projectTypes?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, frameworkProgrammes?: Array, fundingSchemes?: Array, statuses?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorId, 'author_id'); - if (authorIds) { - authorIds.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'author_ids'); - }) - } - if (organizationIds) { - organizationIds.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'organization_ids'); - }) - } - if (organizationNames) { - organizationNames.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'organization_names'); - }) - } - if (projectTypes) { - projectTypes.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'project_types'); - }) - } - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - title, 'title'); - if (keywords) { - keywords.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'keywords'); - }) - } - if (topicIds) { - topicIds.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'topic_ids'); - }) - } - if (filterTopicIds) { - filterTopicIds.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'filter_topic_ids'); - }) - } - if (fundingStartYears) { - fundingStartYears.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'funding_start_years'); - }) - } - if (fundingEndYears) { - fundingEndYears.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'funding_end_years'); - }) - } - if (countries) { - countries.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'countries'); - }) - } - if (frameworkProgrammes) { - frameworkProgrammes.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'framework_programmes'); - }) - } - if (fundingSchemes) { - fundingSchemes.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'funding_schemes'); - }) - } - if (statuses) { - statuses.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'statuses'); - }) - } - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - size, 'size'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortBy, 'sort_by'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortDirection, 'sort_direction'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - fuzzy, 'fuzzy'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/projects/eu/search`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Search projects across all funders. - * Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter. - * @endpoint get /api/projects/search - * @param page The page number. - * @param size The page size. - * @param selectedProjectTypes The set of project types to filter by (e.g., \'bund\', \'eu\', \'dfg\'). If not provided, projects of all types will be included. - * @param title The title to filter by. - * @param sortBy The field to sort by. - * @param sortDirection The sort direction (asc or desc). - * @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 searchProjects(page?: number, size?: number, selectedProjectTypes?: Set, title?: string, sortBy?: ProjectsSortBy, sortDirection?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchProjects(page?: number, size?: number, selectedProjectTypes?: Set, title?: string, sortBy?: ProjectsSortBy, sortDirection?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchProjects(page?: number, size?: number, selectedProjectTypes?: Set, title?: string, sortBy?: ProjectsSortBy, sortDirection?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchProjects(page?: number, size?: number, selectedProjectTypes?: Set, title?: string, sortBy?: ProjectsSortBy, sortDirection?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - size, 'size'); - if (selectedProjectTypes) { - selectedProjectTypes.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'selected_project_types'); - }) - } - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - title, 'title'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortBy, 'sort_by'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortDirection, 'sort_direction'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/projects/search`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } let localVarPath = `/api/projects/search`; diff --git a/webapp/src/app/api/model/careerStage.ts b/webapp/src/app/api/model/careerStage.ts new file mode 100644 index 00000000..d2a4e844 --- /dev/null +++ b/webapp/src/app/api/model/careerStage.ts @@ -0,0 +1,20 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const CareerStage = { + Unknown: 'unknown', + Early: 'Early', + Emerging: 'Emerging', + Established: 'Established', + Senior: 'Senior' +} as const; +export type CareerStage = typeof CareerStage[keyof typeof CareerStage]; + diff --git a/webapp/src/app/api/model/companyStatusFilter.ts b/webapp/src/app/api/model/companyStatusFilter.ts new file mode 100644 index 00000000..7d4355e7 --- /dev/null +++ b/webapp/src/app/api/model/companyStatusFilter.ts @@ -0,0 +1,18 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const CompanyStatusFilter = { + All: 'all', + Active: 'active', + Deleted: 'deleted' +} as const; +export type CompanyStatusFilter = typeof CompanyStatusFilter[keyof typeof CompanyStatusFilter]; + diff --git a/webapp/src/app/api/model/filterType.ts b/webapp/src/app/api/model/filterType.ts new file mode 100644 index 00000000..bee9d0d7 --- /dev/null +++ b/webapp/src/app/api/model/filterType.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const FilterType = { + Keyword: 'keyword', + Topic: 'topic' +} as const; +export type FilterType = typeof FilterType[keyof typeof FilterType]; + diff --git a/webapp/src/app/api/model/keywordOperator.ts b/webapp/src/app/api/model/keywordOperator.ts new file mode 100644 index 00000000..d4d4bf1f --- /dev/null +++ b/webapp/src/app/api/model/keywordOperator.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const KeywordOperator = { + And: 'and', + Or: 'or' +} as const; +export type KeywordOperator = typeof KeywordOperator[keyof typeof KeywordOperator]; + diff --git a/webapp/src/app/api/model/publicationType.ts b/webapp/src/app/api/model/publicationType.ts new file mode 100644 index 00000000..753c47e8 --- /dev/null +++ b/webapp/src/app/api/model/publicationType.ts @@ -0,0 +1,39 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const PublicationType = { + Article: 'article', + Other: 'other', + Dataset: 'dataset', + BookChapter: 'book-chapter', + Book: 'book', + Dissertation: 'dissertation', + Preprint: 'preprint', + Paratext: 'paratext', + Libguides: 'libguides', + Review: 'review', + Letter: 'letter', + ReferenceEntry: 'reference-entry', + Editorial: 'editorial', + PeerReview: 'peer-review', + Report: 'report', + Standard: 'standard', + Erratum: 'erratum', + Retraction: 'retraction', + SupplementaryMaterials: 'supplementary-materials', + BookSection: 'book-section', + Database: 'database', + Software: 'software', + ReportComponent: 'report-component', + Grant: 'grant' +} as const; +export type PublicationType = typeof PublicationType[keyof typeof PublicationType]; + diff --git a/webapp/src/app/api/model/selectedAuthorsRequest.ts b/webapp/src/app/api/model/selectedAuthorsRequest.ts new file mode 100644 index 00000000..79f008fe --- /dev/null +++ b/webapp/src/app/api/model/selectedAuthorsRequest.ts @@ -0,0 +1,42 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Timespan } from './timespan'; +import { FilterType } from './filterType'; +import { KeywordOperator } from './keywordOperator'; +import { PublicationType } from './publicationType'; + + +export interface SelectedAuthorsRequest { + /** + * OpenAlex IDs of the authors to rank. + */ + author_ids: Array; + /** + * One or more keywords defining the topic. + */ + keywords: Array; + /** + * How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'. + */ + operator?: KeywordOperator; + /** + * What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic ids). Defaults to \'keyword\'. + */ + filter_type?: FilterType; + /** + * Optional filter: only count works of these publication types. Empty = no filter. + */ + publication_types?: Array; + timespan?: Timespan | null; +} +export namespace SelectedAuthorsRequest { +} + + diff --git a/webapp/src/app/api/model/subfieldShare.ts b/webapp/src/app/api/model/subfieldShare.ts new file mode 100644 index 00000000..83185941 --- /dev/null +++ b/webapp/src/app/api/model/subfieldShare.ts @@ -0,0 +1,22 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface SubfieldShare { + /** + * The subfield display name. + */ + name: string; + /** + * Number of works whose primary topic belongs to this subfield. + */ + count: number; +} + diff --git a/webapp/src/app/api/model/timespan.ts b/webapp/src/app/api/model/timespan.ts new file mode 100644 index 00000000..c44eee8a --- /dev/null +++ b/webapp/src/app/api/model/timespan.ts @@ -0,0 +1,22 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface Timespan { + /** + * Start year (inclusive). + */ + from: number; + /** + * End year (inclusive). + */ + to: number; +} + From 14e25a522cbb614f4216005871c25b4b4f29c469 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 23 Jul 2026 00:17:53 +0200 Subject: [PATCH 18/26] minor fixes --- webapp/src/app/resolvers/dfg-projects.resolver.ts | 6 ++---- .../ui/dfg-project-table/dfg-project-table.component.ts | 1 - 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/webapp/src/app/resolvers/dfg-projects.resolver.ts b/webapp/src/app/resolvers/dfg-projects.resolver.ts index 2bd67a6d..59f06e3a 100644 --- a/webapp/src/app/resolvers/dfg-projects.resolver.ts +++ b/webapp/src/app/resolvers/dfg-projects.resolver.ts @@ -57,12 +57,10 @@ export const dfgProjectsResolver: ResolveFn = ( ); const institutionIds = route.queryParamMap .getAll(projectQueryParamKeys.institutionId) - .map((id) => Number(id)) - .filter((id) => !isNaN(id)); + .map((id) => Number(id)); const authorIds = route.queryParamMap .getAll(projectQueryParamKeys.authorId) - .map((id) => Number(id)) - .filter((id) => !isNaN(id)); + .map((id) => Number(id)); if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) { const rawAuthorId = route.parent?.parent?.params['id']; diff --git a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts index 9c961758..f0d4906e 100644 --- a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts +++ b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.ts @@ -94,7 +94,6 @@ export class DfgProjectTableComponent implements OnInit { }); ngOnInit(): void { - console.log('DFG PROJECTS', this.page()); this.columns = [ { id: 'title', header: 'Titel', type: 'accessor', accessorKey: 'title' }, { From daf71a6dae6c7505ce2c15ec98a7c5fecdc3b7de Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 23 Jul 2026 14:19:42 +0200 Subject: [PATCH 19/26] refactor: update llm.call to async await for improved performance --- service/src/main/inse/integrations/llm.py | 12 ++++++------ service/src/main/inse/keywords/logic.py | 2 +- service/src/main/inse/news/logic.py | 2 +- service/src/main/inse/persons/logic.py | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/service/src/main/inse/integrations/llm.py b/service/src/main/inse/integrations/llm.py index 180edfbc..101ce92c 100644 --- a/service/src/main/inse/integrations/llm.py +++ b/service/src/main/inse/integrations/llm.py @@ -1,9 +1,9 @@ -from openai import OpenAI, APIConnectionError +from openai import APIConnectionError from openai import AsyncOpenAI from .. import config from typing import Optional, Dict, Any import asyncio -def call( +async def call( system_prompt: str, user_prompt: str, model: str = None, @@ -16,18 +16,18 @@ def call( if model is None: model = config.settings.llm_model - + response_format = None if json_schema is not None: response_format = _get_response_format(schema = json_schema,schema_name=schema_name) - - client = OpenAI( + + client = AsyncOpenAI( base_url=config.settings.llm_api_url, api_key=config.settings.llm_api_key, timeout=timeout, ) try: - response = client.chat.completions.create( + response = await client.chat.completions.create( model=model, messages=[ {"role": "system", "content": system_prompt}, diff --git a/service/src/main/inse/keywords/logic.py b/service/src/main/inse/keywords/logic.py index 964c5364..b2bdcb2e 100644 --- a/service/src/main/inse/keywords/logic.py +++ b/service/src/main/inse/keywords/logic.py @@ -82,7 +82,7 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor user_prompt += f"""Input:{text}""" - keywords = llm.call( + keywords = await llm.call( system_prompt=system_prompt, user_prompt=user_prompt, json_schema = ExtractedKeywordsLLM.model_json_schema(), diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 3ced9bf5..bb423948 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -292,7 +292,7 @@ async def _get_article_keywords( if not text: return [] - raw = llm.call( + raw = await llm.call( system_prompt=KEYWORD_SYSTEM_PROMPT, user_prompt=f"Artikel:\n{text}", temperature=0.3, diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 43db5add..0168d39a 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -444,7 +444,7 @@ async def generate_person_bio( user_prompt = f"Daten zur Person:\n{person_json}" - bio = llm.call( + bio = await llm.call( system_prompt=system_prompt, user_prompt=user_prompt, temperature=0.8, From 399ed285e20abf4f300b74b8fc2c7dc5464ac9bb Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Thu, 23 Jul 2026 19:24:14 +0200 Subject: [PATCH 20/26] implemented news query in backend --- .../inse/university_ranking/trend_logic.py | 67 ++++++-- .../university_ranking/trend_strategies.py | 158 +++++++++++------- 2 files changed, 150 insertions(+), 75 deletions(-) diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index e77225e6..83a6f472 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -942,9 +942,6 @@ async def get_top_topics_for_entity( except Exception as e: logger.error("Failed to query top project topics for entity: %s", e) return {"items": []} - -# Default fallback institution: University of Duisburg-Essen -DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514" DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen" DEFAULT_TOP_TOPICS_SIZE = 20 @@ -1001,9 +998,9 @@ async def get_top_topics_for_entity( try: from inse.institutions.institutions_search_client import InstitutionsSearchClient client = InstitutionsSearchClient() - resolved_aliases = await client.get_institution_aliases_by_oa_institution_id(short_id) + resolved_aliases = await client.get_institution_aliases_by_oa_institution_id(entity_id) if resolved_aliases: - aliases = list(resolved_aliases) + aliases = resolved_aliases except Exception as e: logger.warning("Failed to resolve institution aliases in get_top_topics_for_entity: %s", e) @@ -1100,22 +1097,29 @@ async def get_top_topics_for_entity( for topic_idx, p_ids in project_ids_by_index.items(): if not p_ids: continue - for i in range(0, len(p_ids), 500): - chunk = p_ids[i:i+500] + for i in range(0, len(p_ids), 1000): + chunk = p_ids[i:i+1000] payload = { "query": {"terms": {"project_id": chunk}}, - "size": 10000, - "_source": ["topic_matches"] + "size": 0, + "aggs": { + "topic_matches": { + "nested": {"path": "topic_matches"}, + "aggs": { + "topics": { + "terms": {"field": "topic_matches.topic_display_name", "size": 100} + } + } + } + } } try: res = await patent_client._search(index=topic_idx, payload=payload) - hits = res.get("hits", {}).get("hits", []) - for hit in hits: - matches = hit.get("_source", {}).get("topic_matches", []) - for m in matches: - t_name = m.get("topic_display_name") - if t_name: - topic_counts[t_name] = topic_counts.get(t_name, 0) + 1 + buckets = res.get("aggregations", {}).get("topic_matches", {}).get("topics", {}).get("buckets", []) + for b in buckets: + t_name = b["key"] + cnt = b["doc_count"] + topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt except Exception as e: logger.warning("Failed to aggregate topics from %s: %s", topic_idx, e) @@ -1134,6 +1138,37 @@ async def get_top_topics_for_entity( logger.error("Failed to query top project topics for entity: %s", e) return {"items": []} + if search_type == "news": + try: + res = await elasticsearch.search( + index="aktuell_postproc", + body={ + "query": {"match_all": {}}, + "size": 0, + "aggs": { + "top_topics": { + "terms": { + "field": "topics.display_name.keyword", + "size": DEFAULT_TOP_TOPICS_SIZE + } + } + } + }, + cluster="inse" + ) + buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", []) + items = [{"name": b["key"], "count": b["doc_count"]} for b in buckets] + total_hits = res.get("hits", {}).get("total", {}) + total_val = total_hits.get("value", 0) if isinstance(total_hits, dict) else int(total_hits or 0) + sum_top = sum(b["count"] for b in items) + other_count = max(0, total_val - sum_top) + if other_count > 0: + items.append({"name": "Andere Themen", "count": other_count}) + return {"items": items} + except Exception as e: + logger.error("Failed to query top news topics for entity: %s", e) + return {"items": []} + # Default fallback: openalex-works* query for publications/authors # 1. Normalize ID and prepare filter clause if entity_type == "institution": diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index 4a93704a..4cf56e6e 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -1448,33 +1448,67 @@ class NewsTrendStrategy(TrendStrategy): end_year = datetime.datetime.now().year - 1 years_range = list(range(start_year, end_year + 1)) - search_terms = keywords if keywords else topics - - # Each series will map all topic keys to its data. + # Each series entity represents one topic/keyword. accumulated_data = { f"news_topic_{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} for t in topics } - # Query UDE news postprocessed index to get matching news IDs + AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"] + STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"} + + # Query UDE news postprocessed index to get matching news IDs without 10k capping async def fetch_news_ids_for_term(idx: int, t_name: str) -> List[str]: - term = search_terms[idx] if idx < len(search_terms) else t_name + if fuzzy: + term = t_name + es_query = {"match": {"topics.display_name": term}} + else: + if keywords and idx < len(keywords) and keywords[idx]: + raw_kw = keywords[idx] + term = raw_kw.split(",")[0].strip() if isinstance(raw_kw, str) else raw_kw + if not term: + term = t_name + else: + term = t_name + es_query = {"match": {"keywords": term}} + + news_ids = set() try: - res = await elasticsearch.search( + async for hit in elasticsearch.scan( index="aktuell_postproc", - query={"match": {"keywords": term}}, - size=10000, + query=es_query, source=["news_id"], cluster="inse" - ) - return [ - hit["_source"]["news_id"] - for hit in res.get("hits", {}).get("hits", []) - if hit.get("_source", {}).get("news_id") - ] + ): + nid = hit.get("_source", {}).get("news_id") + if nid: + news_ids.add(nid) except Exception as e: - logger.warning("Failed to search UDE news postproc keywords: %s", e) - return [] + logger.warning("Failed to scan UDE news postproc: %s", e) + + # If non-fuzzy keyword search, also search article content fields in 'aktuell' index + if not fuzzy and term and term.lower() not in STOP_WORDS and len(term.strip()) > 1: + try: + content_query = { + "query_string": { + "query": term, + "fields": AKTUELLES_SEARCH_FIELDS, + "default_operator": "AND" + } + } + async for hit in elasticsearch.scan( + index="aktuell", + query=content_query, + source=["news_id"], + cluster="inse" + ): + nid = hit.get("_id") or hit.get("_source", {}).get("news_id") + if nid: + news_ids.add(nid) + except Exception as e: + logger.warning("Failed to scan UDE news content in aktuell: %s", e) + + return list(news_ids) # Find all matching news IDs concurrently matching_ids_list = await asyncio.gather(*[ @@ -1484,36 +1518,36 @@ class NewsTrendStrategy(TrendStrategy): async def count_by_year(t_name: str, news_ids: List[str]): if not news_ids: return - try: - # Query aktuell index using matching news IDs and aggregate by date_year - res = await elasticsearch.search( - index="aktuell", - body={ - "query": {"bool": {"filter": [ - {"ids": {"values": news_ids}}, - {"range": {"date_year": {"gte": start_year, "lte": end_year}}} - ]}}, - "aggs": { - "by_year": { - "terms": {"field": "date_year", "size": len(years_range) * 2} + entity_key = f"news_topic_{t_name}" + # Batch news_ids in chunks of 2000 to avoid ES query clause limits + for i in range(0, len(news_ids), 2000): + chunk = news_ids[i:i+2000] + try: + res = await elasticsearch.search( + index="aktuell", + body={ + "query": {"bool": {"filter": [ + {"ids": {"values": chunk}}, + {"range": {"date_year": {"gte": start_year, "lte": end_year}}} + ]}}, + "aggs": { + "by_year": { + "terms": {"field": "date_year", "size": len(years_range) * 2} + } } - } - }, - size=0, - cluster="inse" - ) - buckets = res.get("aggregations", {}).get("by_year", {}).get("buckets", []) - for b in buckets: - yr = int(b.get("key")) - count = int(b.get("doc_count", 0)) - if yr in years_range: - entity_key = f"news_topic_{t_name}" - # Set this count for all topic keys in this topic's series - for top in topics: - accumulated_data[entity_key][top] = dict(accumulated_data[entity_key][top]) - accumulated_data[entity_key][top][yr] = (count, 1) - except Exception as e: - logger.warning("Failed to aggregate news years from ES: %s", e) + }, + size=0, + cluster="inse" + ) + buckets = res.get("aggregations", {}).get("by_year", {}).get("buckets", []) + for b in buckets: + yr = int(b.get("key")) + count = int(b.get("doc_count", 0)) + if yr in years_range: + prev_count, _ = accumulated_data[entity_key][t_name][yr] + accumulated_data[entity_key][t_name][yr] = (prev_count + count, 1) + except Exception as e: + logger.warning("Failed to aggregate news years from ES for chunk: %s", e) # Aggregate news publication years concurrently await asyncio.gather(*[ @@ -1526,21 +1560,27 @@ class NewsTrendStrategy(TrendStrategy): for t_name in topics: entity_key = f"news_topic_{t_name}" topic_data_map = {} - for topic in topics: - yearly_data_items = [] - lookup = normalized_lookup.get((entity_key, topic), {}) - norm_vals = lookup.get("normalized", [0.0] * len(years_range)) - cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) - for idx, yr in enumerate(years_range): - count, _ = accumulated_data[entity_key][topic][yr] - yearly_data_items.append(TopicYearlyData( - year=yr, - raw=count, - normalized=norm_vals[idx], - cumulative=cum_vals[idx], - institutions_count=1 - )) + # Extract yearly data items for t_name from accumulated_data[entity_key][t_name] + lookup = normalized_lookup.get((entity_key, t_name), {}) + norm_vals = lookup.get("normalized", [0.0] * len(years_range)) + cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) + + yearly_data_items = [] + for idx, yr in enumerate(years_range): + count, _ = accumulated_data[entity_key][t_name][yr] + yearly_data_items.append(TopicYearlyData( + year=yr, + raw=count, + normalized=norm_vals[idx], + cumulative=cum_vals[idx], + institutions_count=1 + )) + + # Populate topic_data_map for ALL topic keys in topics with t_name's yearly items. + # This ensures uni-trend-chart accessing topic_data[selectedTopic] for any selected topic + # always gets t_name's true data items for series t_name. + for topic in topics: topic_data_map[topic] = yearly_data_items series_list.append(TrendSeries( From d3686f9de99f80261be28d99872ec199fcccca18 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Thu, 23 Jul 2026 19:29:22 +0200 Subject: [PATCH 21/26] added resolver and changed layout --- webapp/src/app/app.routes.ts | 28 +- .../uni-trend-chart.component.ts | 8 +- .../uni-trend-parent.component.html | 337 ++++++++------- .../uni-trend-parent.component.scss | 386 +++++++++--------- .../uni-trend-parent.component.ts | 133 +++++- .../src/app/resolvers/uni-trend.resolver.ts | 123 ++++++ 6 files changed, 659 insertions(+), 356 deletions(-) create mode 100644 webapp/src/app/resolvers/uni-trend.resolver.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 70d53fd4..0f21900e 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -48,6 +48,7 @@ import { selectedDfgAuthorsResolver } from './resolvers/selected-dfg-authors.res import { selectedDfgInstitutionsResolver } from './resolvers/selected-dfg-institutions.resolver'; import { primaryCategoryYearAggregationPageResolver } from './resolvers/primary-category-year-aggregation-page.resolver'; import { selectedEuInstitutionsResolver } from './resolvers/selected-eu-institutions.resolver'; +import { uniTrendResolver } from './resolvers/uni-trend.resolver'; import { EuProjectsComponent } from './shared/ui/eu-projects/eu-projects.component'; import { DfgProjectsComponent } from './shared/ui/dfg-projects/dfg-projects.component'; export const routes: Routes = [ @@ -244,7 +245,32 @@ export const routes: Routes = [ }, }, { path: 'news', component: KeywordsToNewsResultsComponent }, - { path: 'trends', component: UniTrendParentComponent }, + { + path: 'trends', + component: UniTrendParentComponent, + resolve: { + trendData: uniTrendResolver, + }, + runGuardsAndResolvers: (from, to) => { + const keys = [ + 'search_type', + 'topic', + 'topics', + 'keyword', + 'keywords', + 'institutions', + 'countries', + 'regions', + 'authors', + 'start_year', + 'end_year', + 'fuzzy', + ]; + return keys.some( + (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + ); + }, + }, ], }, { diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts index cfa68ac1..4a0fe311 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -39,10 +39,14 @@ export class UniTrendChartComponent { const xAxisData = years.map(String); // Resolve the active topic to compare one at a time to prevent line overlaps - const topics = Object.keys(trendData.series[0].topic_data || {}); + const availableKeys = Object.keys(trendData.series[0].topic_data || {}); + const displayNameKeys = availableKeys.filter( + (k) => !/^T\d+$/i.test(k) && !k.startsWith('http'), + ); + const topics = displayNameKeys.length > 0 ? displayNameKeys : availableKeys; const active = this.activeTopic(); const selectedTopic = - active && topics.includes(active) + active && (availableKeys.includes(active) || topics.includes(active)) ? active : topics.length > 0 ? topics[0] diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html index 474ba499..5dde3d72 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html @@ -2,139 +2,129 @@
- - - - -
- @if (isTrendLoading() && !rawTrendResponse()) { + +
+ @if (isPageResolving() || (isTrendLoading() && !rawTrendResponse())) { } @else if (rawTrendResponse()) { -
- Visualisierungsskala: -
- - - -
-
- +
- @if (isTrendLoading()) { -
-
-

Trenddaten werden abgerufen...

-
- } - @if ( - selectedTrendTopics().length > 1 && selectedSearchType() !== 'news' - ) { + @if (selectedTrendTopics().length > 0) {
@for (topic of selectedTrendTopics(); track topic) { - - + @if (selectedSearchType() === 'news') { + + + } @else if (selectedTrendTopics().length > 1) { + + + } }
} @@ -149,27 +139,39 @@ @if ( - selectedPieEntity() && - selectedSearchType() !== 'news' && + (selectedPieEntity() || selectedSearchType() === 'news') && selectedSearchType() !== 'all' ) { -
- - +
+ @if (selectedSearchType() === 'news') { + + + } @else { + + + } } - - @if (activeConfig().showInstitutionSelector) { - - - } + +
+ + @if (activeConfig().showLocationSelector) { +
+ + +
+ } - - @if (activeConfig().showAuthorSelector) { - - - } + + @if (activeConfig().showAuthorSelector) { +
+ + +
+ } + + + @if (activeConfig().showInstitutionSelector) { +
+ + +
+ } + + + @if (activeConfig().showAuthorSelector) { +
+ + +
+ } +
} @else {
trending_up diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss index 02e5b1b7..3b8c9181 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss @@ -1,185 +1,14 @@ -.trend-layout { - display: grid; - grid-template-columns: 300px minmax(0, 1fr); - gap: 1.5rem; - margin-top: 1.5rem; - font-family: 'Inter', sans-serif; - - @media (max-width: 1024px) { - grid-template-columns: 1fr; - } -} - -.trend-sidebar { +.trend-layout-wrapper { display: flex; flex-direction: column; gap: 1rem; -} - -.control-card { - background: white; - border-radius: 10px; - padding: 1.25rem; - border: 1px solid #e5e7eb; - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); - - h3 { - font-size: 0.8rem; - font-weight: 600; - text-transform: uppercase; - color: #6b7280; - margin: 0 0 0.75rem 0; - letter-spacing: 0.05em; - } -} - -.checkbox-group { - display: flex; - flex-direction: column; - gap: 0.5rem; -} - -.checkbox-label { - display: flex; - align-items: center; - gap: 0.5rem; - font-size: 0.875rem; - color: #374151; - cursor: pointer; - - input[type='checkbox'] { - accent-color: #3b82f6; - width: 15px; - height: 15px; - cursor: pointer; - } -} - -.empty-list-info { - font-size: 0.75rem; - color: #9ca3af; - text-align: center; - padding: 8px 0; - border: 1px dashed #e5e7eb; - border-radius: 5px; -} - -.trend-main { - display: flex; - flex-direction: column; - gap: 1rem; -} - -.trend-toggles-bar { - display: flex; - justify-content: space-between; - align-items: center; - background: white; - border-radius: 10px; - padding: 0.6rem 1rem; - border: 1px solid #e5e7eb; - box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); - - .toggle-label { - font-size: 0.8125rem; - font-weight: 500; - color: #4b5563; - } -} - -.toggle-buttons { - display: flex; - background: #f3f4f6; - border-radius: 6px; - padding: 2px; - - button { - padding: 0.4rem 0.8rem; - border: none; - background: none; - font-size: 0.75rem; - font-weight: 500; - color: #4b5563; - border-radius: 5px; - cursor: pointer; - display: inline-flex; - align-items: center; - gap: 6px; - - mat-icon { - font-size: 16px; - width: 16px; - height: 16px; - } - - &:hover:not(.active) { - color: #111827; - background: rgba(255, 255, 255, 0.5); - } - &.active { - background: white; - color: #3b82f6; - font-weight: 600; - } - } -} - -.chart-holder-card { - position: relative; - background: white; - border-radius: 10px; - border: 1px solid #e5e7eb; - overflow: hidden; - min-height: 400px; -} - -.chart-topic-tabs { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.4rem; - padding: 0.6rem 1rem; - background: #f9fafb; - border-bottom: 1px solid #e5e7eb; -} - -.loader-overlay { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - background: rgba(255, 255, 255, 0.8); - z-index: 10; - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - - .spinner { - width: 32px; - height: 32px; - border: 3px solid rgba(59, 130, 246, 0.1); - border-radius: 50%; - border-top-color: #3b82f6; - animation: spin 0.8s linear infinite; - margin-bottom: 8px; - } - - p { - font-size: 0.8125rem; - color: #4b5563; - margin: 0; - } -} - -@keyframes spin { - 0% { - transform: rotate(0deg); - } - 100% { - transform: rotate(360deg); - } + width: 100%; + box-sizing: border-box; + font-family: + 'Inter', + system-ui, + -apple-system, + sans-serif; } .strategy-toggles-bar { @@ -190,14 +19,13 @@ border-radius: 12px; padding: 6px; border: 1px solid #e2e8f0; - margin-bottom: 0.5rem; button { - padding: 0.5rem 1rem; + padding: 0.45rem 0.9rem; border: none; background: none; - font-size: 0.75rem; - font-weight: 600; + font-size: 0.8125rem; + font-weight: 500; color: #64748b; border-radius: 8px; cursor: pointer; @@ -207,41 +35,194 @@ transition: all 0.2s ease; mat-icon { - font-size: 16px; - width: 16px; - height: 16px; + font-size: 18px; + width: 18px; + height: 18px; } &:hover:not(.active):not([disabled]) { color: #0f172a; background: #f1f5f9; } + &[disabled] { - opacity: 0.4; + opacity: 0.45; cursor: not-allowed; } + &.active { background: white; - color: #3b82f6; + color: #2563eb; + font-weight: 600; box-shadow: - 0 4px 6px -1px rgba(0, 0, 0, 0.05), - 0 2px 4px -1px rgba(0, 0, 0, 0.03); + 0 2px 4px rgba(0, 0, 0, 0.05), + 0 1px 2px rgba(0, 0, 0, 0.03); } } } +.trend-layout { + display: flex; + flex-direction: column; + gap: 1.25rem; + width: 100%; + box-sizing: border-box; +} + +/* Combined Top Header Control Bar */ +.trend-top-controls-bar { + display: flex; + justify-content: space-between; + align-items: center; + gap: 1.5rem; + background: white; + border-radius: 12px; + padding: 0.75rem 1.25rem; + border: 1px solid #e5e7eb; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04); + width: 100%; + box-sizing: border-box; + + .slider-section { + flex: 1; + min-width: 280px; + } + + .scale-section { + display: flex; + align-items: center; + gap: 0.75rem; + flex-shrink: 0; + + .toggle-label { + font-size: 0.8125rem; + font-weight: 600; + color: #4b5563; + white-space: nowrap; + } + + mat-button-toggle-group { + border: 1px solid #e2e8f0; + border-radius: 8px; + overflow: hidden; + background: #f8fafc; + box-shadow: none; + + mat-button-toggle { + font-size: 0.75rem; + font-weight: 500; + color: #475569; + + mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + margin-right: 4px; + vertical-align: middle; + } + + .toggle-text { + white-space: nowrap; + } + } + + .mat-button-toggle-checked { + background-color: white !important; + color: #2563eb !important; + font-weight: 600; + } + } + } + + @media (max-width: 900px) { + flex-direction: column; + align-items: stretch; + gap: 1rem; + } +} + +.trend-main-fullwidth { + display: flex; + flex-direction: column; + gap: 1.25rem; + width: 100%; + box-sizing: border-box; +} + +.chart-holder-card { + position: relative; + background: white; + border-radius: 12px; + border: 1px solid #e5e7eb; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04); + overflow: hidden; + min-height: 450px; + width: 100%; + box-sizing: border-box; +} + +.chart-topic-tabs { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + padding: 0.75rem 1.25rem; + background: #f8fafc; + border-bottom: 1px solid #e2e8f0; +} + +.loader-overlay { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(255, 255, 255, 0.85); + z-index: 10; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + gap: 0.75rem; + + p { + font-size: 0.875rem; + font-weight: 500; + color: #3b82f6; + margin: 0; + } +} + .pie-charts-row { display: grid; - grid-template-columns: 1fr 1fr; - gap: 1.5rem; + grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); + gap: 1.25rem; + width: 100%; + box-sizing: border-box; +} + +.comparison-panels-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); + gap: 1.25rem; width: 100%; box-sizing: border-box; - @media (max-width: 768px) { - grid-template-columns: 1fr; + .full-width-panel { + grid-column: 1 / -1; } } +.comparison-panel-card { + background: white; + border-radius: 12px; + border: 1px solid #e5e7eb; + padding: 1.25rem; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04); + width: 100%; + box-sizing: border-box; +} + .no-data-fallback { display: flex; flex-direction: column; @@ -249,14 +230,21 @@ justify-content: center; min-height: 400px; background: white; - border-radius: 10px; + border-radius: 12px; border: 1px solid #e5e7eb; color: #9ca3af; - gap: 0.5rem; + gap: 0.75rem; mat-icon { - font-size: 48px; - width: 48px; - height: 48px; + font-size: 56px; + width: 56px; + height: 56px; + } + + p { + font-size: 0.9375rem; + font-weight: 500; + color: #6b7280; + margin: 0; } } diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index b223be24..7a1635eb 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -11,16 +11,26 @@ import { } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; -import { ActivatedRoute, Router } from '@angular/router'; +import { + ActivatedRoute, + Router, + ResolveStart, + ResolveEnd, +} from '@angular/router'; import { forkJoin } from 'rxjs'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatButtonModule } from '@angular/material/button'; +import { + MatButtonToggleModule, + MatButtonToggleChange, +} from '@angular/material/button-toggle'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatAutocompleteModule } from '@angular/material/autocomplete'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { UniTrendChartComponent } from '../uni-trend-chart/uni-trend-chart.component'; import { UniPieChartComponent } from '../uni-pie-chart/uni-pie-chart.component'; import { @@ -115,8 +125,10 @@ export const TREND_CONFIGS: Record = { UniPieChartComponent, MatCheckboxModule, MatButtonModule, + MatButtonToggleModule, MatIconModule, MatProgressSpinnerModule, + MatTooltipModule, TopicChipComponent, YearRangeSliderComponent, LocationSelectorComponent, @@ -208,6 +220,7 @@ export class UniTrendParentComponent implements OnInit { readonly fetchedFuzzy = signal(null); // Results & Loading signals + readonly isPageResolving = signal(false); readonly rawTrendResponse = signal(null); readonly isTrendLoading = signal(false); readonly topSuggestions = signal([]); @@ -263,6 +276,29 @@ export class UniTrendParentComponent implements OnInit { readonly boundGetTopicColor = this.getTopicColor.bind(this); + readonly newsSelectedTopicsPieData = computed(() => { + const data = this.trendResponse(); + if (!data || !data.series || this.selectedSearchType() !== 'news') { + return null; + } + const startYr = this.startYear(); + const endYr = this.endYear(); + + return data.series.map((s) => { + const topicName = s.entity_name; + const yearlyItems = + s.topic_data[topicName] || Object.values(s.topic_data)[0] || []; + const totalRaw = yearlyItems + .filter((y) => y.year >= startYr && y.year <= endYr) + .reduce((sum, item) => sum + (item.raw || 0), 0); + + return { + name: topicName, + value: totalRaw, + }; + }); + }); + // Autocomplete UI state readonly searchQuery = signal(''); readonly searchResults = signal([]); @@ -294,6 +330,13 @@ export class UniTrendParentComponent implements OnInit { } getEntityColor(entityId: string): string { + if (this.selectedSearchType() === 'news') { + const topicName = entityId.startsWith('news_topic_') + ? entityId.slice('news_topic_'.length) + : entityId; + return this.getTopicColor(topicName); + } + const defaultInstId = 'https://openalex.org/I62318514'; const primaryId = this.primaryInstitution() || defaultInstId; const insts = this.comparisonInstitutions().map((i) => i.id); @@ -345,17 +388,57 @@ export class UniTrendParentComponent implements OnInit { readonly boundGetEntityColor = (id: string) => this.getEntityColor(id); readonly boundIsVisible = (id: string) => this.isVisible(id); - // Computed: filters out items locally if they were removed from list + // Computed: filters out items locally if they were removed from list and normalizes topic_data keys readonly trendResponse = computed(() => { const raw = this.rawTrendResponse(); - if (!raw) return null; + if (!raw || !raw.series) return null; + const topics = this.selectedTrendTopics(); const type = this.selectedSearchType(); + + // Map series topic_data keys to display names so they match selectedTrendTopics + const normalizeTopicData = (s: TrendSeries): TrendSeries => { + if (!s.topic_data) return s; + const rawTopicKeys = Object.keys(s.topic_data); + if (rawTopicKeys.length === 0) return s; + + const newTopicData: Record = {}; + + topics.forEach((topicName, idx) => { + const mappedName = this.getMappedTopic(topicName); + let matchKey = rawTopicKeys.find( + (rk) => + rk.toLowerCase() === topicName.toLowerCase() || + rk.toLowerCase() === mappedName.toLowerCase() || + rk.toLowerCase().includes(topicName.toLowerCase()) || + rk.toLowerCase().includes(mappedName.toLowerCase()), + ); + + if (!matchKey && rawTopicKeys[idx]) { + matchKey = rawTopicKeys[idx]; + } + + if (matchKey && s.topic_data[matchKey]) { + newTopicData[topicName] = s.topic_data[matchKey]; + } else if (rawTopicKeys[0] && s.topic_data[rawTopicKeys[0]]) { + newTopicData[topicName] = s.topic_data[rawTopicKeys[0]]; + } + }); + + // Preserve existing keys as well + Object.assign(newTopicData, s.topic_data); + + return { + ...s, + topic_data: newTopicData, + }; + }; + if (type === 'news' || type === 'all' || type === 'patents') { return { ...raw, series: raw.series.map((s) => ({ - ...s, + ...normalizeTopicData(s), visible: this.isVisible(s.entity_id), })), }; @@ -368,7 +451,7 @@ export class UniTrendParentComponent implements OnInit { const filtered = raw.series .filter((s) => currentAuthorIds.has(s.entity_id.toLowerCase())) .map((s) => ({ - ...s, + ...normalizeTopicData(s), visible: this.isVisible(s.entity_id), })); return { @@ -428,7 +511,7 @@ export class UniTrendParentComponent implements OnInit { ...countrySeries, ...regionSeries, ].map((s) => ({ - ...s, + ...normalizeTopicData(s), visible: this.isVisible(s.entity_id), })); @@ -445,6 +528,36 @@ export class UniTrendParentComponent implements OnInit { this.availableYears.push(y); } + this.router.events.subscribe((event) => { + if (event instanceof ResolveStart) { + this.isPageResolving.set(true); + } else if (event instanceof ResolveEnd) { + this.isPageResolving.set(false); + } + }); + + // Subscribe to route resolver data + this.route.data.subscribe((data) => { + if (data['trendData']) { + const resolved = data['trendData']; + const res = resolved.trendResponse ?? resolved; + this.rawTrendResponse.set(res); + if (resolved.searchType) { + this.selectedSearchType.set(resolved.searchType); + } + if (resolved.topics && resolved.topics.length > 0) { + this.selectedTrendTopics.set(resolved.topics); + if ( + !this.activeChartTopic() || + !resolved.topics.includes(this.activeChartTopic()) + ) { + this.activeChartTopic.set(resolved.topics[0]); + } + } + this.isTrendLoading.set(false); + } + }); + // Effect: automatically sync checkboxes list whenever input keywords or fuzzy state changes effect(() => { const kws = this.keywords(); @@ -762,7 +875,7 @@ export class UniTrendParentComponent implements OnInit { const end = this.endYear(); const strategy = this.selectedSearchType(); - if (!entity || strategy === 'news' || strategy === 'all') { + if (!entity || strategy === 'all') { this.topTopicsData.set([]); return; } @@ -1311,6 +1424,12 @@ export class UniTrendParentComponent implements OnInit { this.updateUrlParams(); } + onChartModeChange(event: MatButtonToggleChange) { + if (event.value) { + this.setChartMode(event.value); + } + } + isTopicEmpty(topic: string): boolean { const data = this.trendResponse(); if (!data || !data.series || data.series.length === 0) { diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts new file mode 100644 index 00000000..0382efef --- /dev/null +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -0,0 +1,123 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { catchError, of, Observable, map } from 'rxjs'; +import { TrendResponse, UniversityRankingsService } from '../api'; +import { SearchResultsStateService } from '../modules/keywords-search/search-results/search-results-state.service'; + +export interface UniTrendResolvedData { + trendResponse: TrendResponse | null; + searchType: string; + topics: string[]; + keywords: string[]; + fuzzy: boolean; +} + +export const uniTrendResolver: ResolveFn = ( + route, + _state, +): Observable => { + const params = route.queryParamMap; + const searchState = inject(SearchResultsStateService, { optional: true }); + + const searchType = params.get('search_type') || 'publications'; + const fuzzy = params.get('fuzzy') !== 'false'; + + // Extract keywords & topics + let keywords = params.getAll('keyword'); + if (keywords.length === 0) { + const rawKeywords = params.get('keywords'); + if (rawKeywords) { + keywords = rawKeywords + .split(',') + .map((k) => k.trim()) + .filter((k) => k.length > 0); + } + } + if (keywords.length === 0 && searchState) { + keywords = searchState.keywords(); + } + + let topics = params.getAll('topic'); + if (topics.length === 0) { + const rawTopics = params.get('topics'); + if (rawTopics) { + topics = rawTopics + .split(',') + .map((t) => t.trim()) + .filter((t) => t.length > 0); + } + } + if (topics.length === 0 && searchState) { + topics = fuzzy ? searchState.topicsList() : searchState.keywords(); + } + + // Fallback defaults if no topics/keywords present yet + if (topics.length === 0 && keywords.length === 0) { + topics = ['Artificial Intelligence']; + keywords = ['artificial intelligence']; + } else if (topics.length === 0) { + topics = keywords; + } else if (keywords.length === 0) { + keywords = topics; + } + + // Parse institutions + const instParams = params.getAll('institutions'); + let institutions = instParams.map((i) => { + const parts = i.split('|'); + const cleanId = parts[0].includes('/') + ? parts[0].split('/').pop() || parts[0] + : parts[0]; + return cleanId; + }); + if (institutions.length === 0) { + institutions = ['I62318514']; + } + + // Parse countries + const countryParams = params.getAll('countries'); + let countries = countryParams.map((c) => c.split('|')[0]); + if (countries.length === 0) { + countries = ['DE']; + } + + // Parse regions & authors + const regionParams = params.getAll('regions'); + const regions = regionParams.map((r) => r.split('|')[0]); + + const authorParams = params.getAll('authors'); + const authors = authorParams.map((a) => a.split('|')[0]); + + const apiService = inject(UniversityRankingsService); + + return apiService + .getTrendApiInseServiceUniversityRankingsTrendGet( + topics, + keywords, + fuzzy, + institutions, + countries, + regions, + authors, + searchType as any, + ) + .pipe( + map((trendResponse) => ({ + trendResponse, + searchType, + topics, + keywords, + fuzzy, + })), + catchError((err) => { + console.error('uniTrendResolver failed to load trend data:', err); + return of({ + trendResponse: null, + searchType, + topics, + keywords, + fuzzy, + }); + }), + ); +}; From 5c4dbe602f6b51411095d6e82105ec4f249ae614 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Thu, 23 Jul 2026 19:43:26 +0200 Subject: [PATCH 22/26] removed year selector from resolver. Adapted child components to scale dynamically --- webapp/src/app/app.routes.ts | 2 - .../uni-trend-parent.component.html | 132 +++++++++--------- .../uni-trend-parent.component.scss | 28 ++-- .../uni-trend-parent.component.ts | 106 +++++++++++--- .../institution-selector.component.scss | 9 +- .../location-selector.component.scss | 7 + 6 files changed, 179 insertions(+), 105 deletions(-) diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 0f21900e..48127b36 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -262,8 +262,6 @@ export const routes: Routes = [ 'countries', 'regions', 'authors', - 'start_year', - 'end_year', 'fuzzy', ]; return keys.some( diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html index 5dde3d72..ccc758ea 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html @@ -183,88 +183,84 @@
} - -
+ +
@if (activeConfig().showLocationSelector) { -
- - -
+ + } @if (activeConfig().showAuthorSelector) { -
- - -
+ + } @if (activeConfig().showInstitutionSelector) { -
- - -
+ + } @if (activeConfig().showAuthorSelector) { -
- - -
+ + }
} @else { diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss index 3b8c9181..c6318867 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss @@ -201,26 +201,24 @@ box-sizing: border-box; } -.comparison-panels-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); +.comparison-selectors-row { + display: flex; + flex-wrap: wrap; + align-items: stretch; gap: 1.25rem; width: 100%; box-sizing: border-box; - .full-width-panel { - grid-column: 1 / -1; - } -} + .selector-item { + flex: 1 1 300px; + min-width: 0; + max-width: 100%; + box-sizing: border-box; -.comparison-panel-card { - background: white; - border-radius: 12px; - border: 1px solid #e5e7eb; - padding: 1.25rem; - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04); - width: 100%; - box-sizing: border-box; + &.selector-item--main { + flex: 2 1 450px; + } + } } .no-data-fallback { diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index 7a1635eb..93a3b375 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -337,12 +337,18 @@ export class UniTrendParentComponent implements OnInit { return this.getTopicColor(topicName); } + const cleanId = (id: string | null | undefined): string => { + if (!id) return ''; + const lower = id.toLowerCase().trim(); + return lower.includes('/') ? lower.split('/').pop()! : lower; + }; + const defaultInstId = 'https://openalex.org/I62318514'; - const primaryId = this.primaryInstitution() || defaultInstId; - const insts = this.comparisonInstitutions().map((i) => i.id); - const countries = this.comparisonCountries().map((c) => c.id); - const regions = this.comparisonRegions().map((r) => r.id); - const authors = this.comparisonAuthors().map((a) => a.id); + const primaryId = cleanId(this.primaryInstitution() || defaultInstId); + const insts = this.comparisonInstitutions().map((i) => cleanId(i.id)); + const countries = this.comparisonCountries().map((c) => cleanId(c.id)); + const regions = this.comparisonRegions().map((r) => cleanId(r.id)); + const authors = this.comparisonAuthors().map((a) => cleanId(a.id)); const orderedIds = [ primaryId, @@ -352,7 +358,8 @@ export class UniTrendParentComponent implements OnInit { ...authors, ]; - const idx = orderedIds.indexOf(entityId); + const targetCleanId = cleanId(entityId); + const idx = orderedIds.indexOf(targetCleanId); if (idx === -1) return '#9ca3af'; const entityColors = [ @@ -388,7 +395,7 @@ export class UniTrendParentComponent implements OnInit { readonly boundGetEntityColor = (id: string) => this.getEntityColor(id); readonly boundIsVisible = (id: string) => this.isVisible(id); - // Computed: filters out items locally if they were removed from list and normalizes topic_data keys + // Computed: filters out items locally if they were removed from list and normalizes topic_data keys & entity names readonly trendResponse = computed(() => { const raw = this.rawTrendResponse(); if (!raw || !raw.series) return null; @@ -396,11 +403,81 @@ export class UniTrendParentComponent implements OnInit { const topics = this.selectedTrendTopics(); const type = this.selectedSearchType(); + const cleanId = (id: string | null | undefined): string => { + if (!id) return ''; + const lower = id.toLowerCase().trim(); + return lower.includes('/') ? lower.split('/').pop()! : lower; + }; + + const primaryInstCleanId = cleanId( + this.primaryInstitution() || 'I62318514', + ); + + const resolveEntityName = (s: TrendSeries): string => { + const cId = cleanId(s.entity_id); + + if (s.entity_type === 'institution') { + if (cId === primaryInstCleanId) { + return ( + this.primaryInstitutionName() || + s.entity_name || + 'Haupt-Einrichtung' + ); + } + const foundInst = this.comparisonInstitutions().find( + (i) => cleanId(i.id) === cId, + ); + if (foundInst && foundInst.name && foundInst.name !== foundInst.id) { + return foundInst.name; + } + } else if (s.entity_type === 'country') { + const foundCountry = this.comparisonCountries().find( + (c) => cleanId(c.id) === cId, + ); + if ( + foundCountry && + foundCountry.name && + foundCountry.name !== foundCountry.id + ) { + return foundCountry.name; + } + } else if (s.entity_type === 'region') { + const foundRegion = this.comparisonRegions().find( + (r) => cleanId(r.id) === cId, + ); + if ( + foundRegion && + foundRegion.name && + foundRegion.name !== foundRegion.id + ) { + return foundRegion.name; + } + } else if (s.entity_type === 'author') { + const foundAuthor = this.comparisonAuthors().find( + (a) => cleanId(a.id) === cId, + ); + if ( + foundAuthor && + foundAuthor.name && + foundAuthor.name !== foundAuthor.id + ) { + return foundAuthor.name; + } + } + + return s.entity_name && + !s.entity_name.startsWith('I') && + s.entity_name.length > 8 + ? s.entity_name + : s.entity_name || cId; + }; + // Map series topic_data keys to display names so they match selectedTrendTopics const normalizeTopicData = (s: TrendSeries): TrendSeries => { - if (!s.topic_data) return s; + const nameResolved = resolveEntityName(s); + if (!s.topic_data) return { ...s, entity_name: nameResolved }; const rawTopicKeys = Object.keys(s.topic_data); - if (rawTopicKeys.length === 0) return s; + if (rawTopicKeys.length === 0) return { ...s, entity_name: nameResolved }; const newTopicData: Record = {}; @@ -430,6 +507,7 @@ export class UniTrendParentComponent implements OnInit { return { ...s, + entity_name: nameResolved, topic_data: newTopicData, }; }; @@ -461,13 +539,6 @@ export class UniTrendParentComponent implements OnInit { } // Default: publications, patents, projects - // Resilient ID normalization helper - const cleanId = (id: string | null | undefined): string => { - if (!id) return ''; - const lower = id.toLowerCase().trim(); - return lower.includes('/') ? lower.split('/').pop()! : lower; - }; - const currentInstIds = new Set( this.comparisonInstitutions().map((i: CompareItem) => cleanId(i.id)), ); @@ -477,9 +548,6 @@ export class UniTrendParentComponent implements OnInit { const currentRegionIds = new Set( this.comparisonRegions().map((r: CompareItem) => cleanId(r.id)), ); - const primaryInstCleanId = cleanId( - this.primaryInstitution() || 'I62318514', - ); const primaryInstSeries: TrendSeries[] = []; const compInstSeries: TrendSeries[] = []; diff --git a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss index 733745d7..6f9d42f5 100644 --- a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss +++ b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss @@ -1,3 +1,10 @@ +:host { + display: block; + width: 100%; + min-width: 0; + max-width: 100%; +} + .institution-selector-container { display: grid; grid-template-columns: 1fr 1.5fr; @@ -8,7 +15,7 @@ padding: 24px; box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04); box-sizing: border-box; - margin-top: 20px; + margin-top: 0; @media (max-width: 1024px) { grid-template-columns: 1fr; diff --git a/webapp/src/app/shared/ui/location-selector/location-selector.component.scss b/webapp/src/app/shared/ui/location-selector/location-selector.component.scss index 08b79102..d61042fb 100644 --- a/webapp/src/app/shared/ui/location-selector/location-selector.component.scss +++ b/webapp/src/app/shared/ui/location-selector/location-selector.component.scss @@ -1,3 +1,10 @@ +:host { + display: block; + width: 100%; + min-width: 0; + max-width: 100%; +} + .control-card { background: white; border-radius: 10px; From db2fb18e897b21417bf0ab81642ba039277d936f Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Thu, 23 Jul 2026 19:52:53 +0200 Subject: [PATCH 23/26] Changed other components to be dynamic as well --- ...author-institution-selector.component.scss | 9 ++++++- .../author-selector.component.scss | 25 +++++++++++++------ .../institution-selector.component.scss | 25 ++++++++++++++----- .../location-selector.component.scss | 5 ++++ 4 files changed, 50 insertions(+), 14 deletions(-) diff --git a/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.scss b/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.scss index 99442ae2..958d92c8 100644 --- a/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.scss +++ b/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.scss @@ -1,3 +1,10 @@ +:host { + display: block; + width: 100%; + min-width: 0; + max-width: 100%; +} + .author-institution-selector-container { display: flex; flex-direction: column; @@ -7,7 +14,7 @@ padding: 24px; box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04); box-sizing: border-box; - margin-top: 20px; + margin-top: 0; width: 100%; } diff --git a/webapp/src/app/shared/ui/author-selector/author-selector.component.scss b/webapp/src/app/shared/ui/author-selector/author-selector.component.scss index 3b24a598..0468ed85 100644 --- a/webapp/src/app/shared/ui/author-selector/author-selector.component.scss +++ b/webapp/src/app/shared/ui/author-selector/author-selector.component.scss @@ -1,3 +1,10 @@ +:host { + display: block; + width: 100%; + min-width: 0; + max-width: 100%; +} + .author-selector-container { display: grid; grid-template-columns: 1fr 1.5fr; @@ -8,7 +15,7 @@ padding: 24px; box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04); box-sizing: border-box; - margin-top: 20px; + margin-top: 0; @media (max-width: 1024px) { grid-template-columns: 1fr; @@ -146,6 +153,8 @@ max-height: 180px; overflow-y: auto; padding-right: 4px; + width: 100%; + box-sizing: border-box; } .comparison-item { @@ -158,6 +167,8 @@ gap: 8px; transition: all 0.2s ease; max-width: 100%; + min-width: 0; + box-sizing: border-box; .item-name { display: inline-flex; @@ -168,7 +179,9 @@ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; - max-width: 180px; + min-width: 0; + max-width: 240px; + flex: 1 1 auto; mat-icon { font-size: 14px; @@ -220,15 +233,13 @@ .suggestions-flex { display: grid; - grid-template-columns: repeat(2, 1fr); + grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 10px; max-height: 250px; overflow-y: auto; padding-right: 4px; - - @media (max-width: 600px) { - grid-template-columns: 1fr; - } + width: 100%; + box-sizing: border-box; } .suggestion-item-horizontal { diff --git a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss index 6f9d42f5..4720d6d2 100644 --- a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss +++ b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss @@ -61,14 +61,23 @@ padding: 3px 8px; border-radius: 6px; font-size: 0.7rem; + max-width: 100%; + box-sizing: border-box; .label { color: #166534; font-weight: 500; + white-space: nowrap; + flex-shrink: 0; } .name { color: #15803d; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; + max-width: 260px; } } @@ -173,6 +182,8 @@ max-height: 180px; overflow-y: auto; padding-right: 4px; + width: 100%; + box-sizing: border-box; } .comparison-item { @@ -185,6 +196,8 @@ gap: 8px; transition: all 0.2s ease; max-width: 100%; + min-width: 0; + box-sizing: border-box; .item-name { display: inline-flex; @@ -195,7 +208,9 @@ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; - max-width: 180px; + min-width: 0; + max-width: 240px; + flex: 1 1 auto; mat-icon { font-size: 14px; @@ -247,15 +262,13 @@ .suggestions-flex { display: grid; - grid-template-columns: repeat(2, 1fr); + grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 10px; max-height: 250px; overflow-y: auto; padding-right: 4px; - - @media (max-width: 600px) { - grid-template-columns: 1fr; - } + width: 100%; + box-sizing: border-box; } .suggestion-item-horizontal { diff --git a/webapp/src/app/shared/ui/location-selector/location-selector.component.scss b/webapp/src/app/shared/ui/location-selector/location-selector.component.scss index d61042fb..8a4ca439 100644 --- a/webapp/src/app/shared/ui/location-selector/location-selector.component.scss +++ b/webapp/src/app/shared/ui/location-selector/location-selector.component.scss @@ -106,6 +106,11 @@ position: relative; width: 100%; + .search-form-field { + width: 100%; + display: block; + } + input { width: 100%; padding: 0.5rem; From f5f4fb77990cfc7b8af8098b065726a778bf46d9 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Thu, 23 Jul 2026 20:00:32 +0200 Subject: [PATCH 24/26] fixed projects top 20 bug --- .../inse/university_ranking/trend_logic.py | 46 ++++++++++++++----- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index 83a6f472..d6314793 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -992,18 +992,34 @@ async def get_top_topics_for_entity( from inse.patents.search_client import PatentSearchClient patent_client = PatentSearchClient() short_id = entity_id.split("/")[-1] + full_id = f"https://openalex.org/{short_id}" - aliases = [short_id, entity_id] + aliases = [short_id, entity_id, full_id] if entity_type == "institution": try: from inse.institutions.institutions_search_client import InstitutionsSearchClient client = InstitutionsSearchClient() - resolved_aliases = await client.get_institution_aliases_by_oa_institution_id(entity_id) + resolved_aliases = await client.get_institution_aliases_by_oa_institution_id(short_id) if resolved_aliases: - aliases = resolved_aliases + aliases.extend(resolved_aliases) + + inst_res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_INSTITUTIONS), + query={"terms": {"id": [full_id, short_id]}}, + size=1, + source=["display_name"], + cluster="nes" + ) + hits = inst_res.get("hits", {}).get("hits", []) + if hits: + d_name = hits[0]["_source"].get("display_name") + if d_name: + aliases.append(d_name) except Exception as e: logger.warning("Failed to resolve institution aliases in get_top_topics_for_entity: %s", e) - + + aliases = list(set([a for a in aliases if a])) + include_german = True if entity_type == "country" and entity_id.strip().upper() != "DE": include_german = False @@ -1100,22 +1116,28 @@ async def get_top_topics_for_entity( for i in range(0, len(p_ids), 1000): chunk = p_ids[i:i+1000] payload = { - "query": {"terms": {"project_id": chunk}}, + "query": { + "bool": { + "should": [ + {"terms": {"project_id": chunk}}, + {"terms": {"project_id.keyword": chunk}} + ], + "minimum_should_match": 1 + } + }, "size": 0, "aggs": { - "topic_matches": { - "nested": {"path": "topic_matches"}, - "aggs": { - "topics": { - "terms": {"field": "topic_matches.topic_display_name", "size": 100} - } + "topics": { + "terms": { + "field": "topic_matches.topic_display_name.keyword", + "size": 100 } } } } try: res = await patent_client._search(index=topic_idx, payload=payload) - buckets = res.get("aggregations", {}).get("topic_matches", {}).get("topics", {}).get("buckets", []) + buckets = res.get("aggregations", {}).get("topics", {}).get("buckets", []) for b in buckets: t_name = b["key"] cnt = b["doc_count"] From 9533db313ee53b614c1c591e37813ceb67d0ca77 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Thu, 23 Jul 2026 20:11:20 +0200 Subject: [PATCH 25/26] added caching for projects --- .../uni-trend-parent.component.ts | 111 ++++++++++++------ 1 file changed, 77 insertions(+), 34 deletions(-) diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index 93a3b375..279e68c1 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -610,18 +610,32 @@ export class UniTrendParentComponent implements OnInit { const resolved = data['trendData']; const res = resolved.trendResponse ?? resolved; this.rawTrendResponse.set(res); - if (resolved.searchType) { - this.selectedSearchType.set(resolved.searchType); - } + + const type = resolved.searchType || this.selectedSearchType(); + this.selectedSearchType.set(type); + this.fetchedSearchType.set(type); + + const fuzzy = this.state?.fuzzySearch() ?? true; + this.fetchedFuzzy.set(fuzzy); + if (resolved.topics && resolved.topics.length > 0) { this.selectedTrendTopics.set(resolved.topics); + this.fetchedTopics.set([...resolved.topics]); if ( !this.activeChartTopic() || !resolved.topics.includes(this.activeChartTopic()) ) { this.activeChartTopic.set(resolved.topics[0]); } + } else { + this.fetchedTopics.set([...this.selectedTrendTopics()]); } + + this.fetchedInstitutions.set([...this.comparisonInstitutions()]); + this.fetchedCountries.set([...this.comparisonCountries()]); + this.fetchedRegions.set([...this.comparisonRegions()]); + this.fetchedAuthors.set([...this.comparisonAuthors()]); + this.isTrendLoading.set(false); } }); @@ -692,7 +706,7 @@ export class UniTrendParentComponent implements OnInit { }); }); - // Effect: automatically refetch trend data whenever topics or comparisons change (fully reactive with subset check) + // Effect: automatically refetch trend data whenever topics or comparisons change (fully reactive with cached rawTrendResponse check) effect(() => { const topics = this.selectedTrendTopics(); const insts = this.comparisonInstitutions(); @@ -707,55 +721,59 @@ export class UniTrendParentComponent implements OnInit { const fetchedT = new Set(untracked(() => this.fetchedTopics())); const fetchedType = untracked(() => this.fetchedSearchType()); const fetchedF = untracked(() => this.fetchedFuzzy()); + const rawRes = untracked(() => this.rawTrendResponse()); const allTopicsFetched = topics.every((t) => fetchedT.has(t)); const sameType = searchType === fetchedType; const sameFuzzy = fuzzy === fetchedF; let allEntitiesFetched = false; - if (sameType) { + if (sameType && rawRes && rawRes.series) { + const rawSeriesCleanIds = new Set( + rawRes.series.map((s) => { + const id = s.entity_id; + return id.includes('/') + ? id.split('/').pop()!.toLowerCase() + : id.toLowerCase(); + }), + ); + if (searchType === 'authors') { - const fetchedA = new Set( - untracked(() => this.fetchedAuthors()).map((a) => - a.id.toLowerCase(), - ), - ); - allEntitiesFetched = authors.every((a) => - fetchedA.has(a.id.toLowerCase()), - ); + allEntitiesFetched = + authors.length === 0 || + authors.every((a) => { + const cleanA = a.id.includes('/') + ? a.id.split('/').pop()!.toLowerCase() + : a.id.toLowerCase(); + return rawSeriesCleanIds.has(cleanA); + }); } else if (searchType === 'news' || searchType === 'all') { allEntitiesFetched = true; } else { // publications, patents, projects - const fetchedI = new Set( - untracked(() => this.fetchedInstitutions()).map((i) => - i.id.toLowerCase(), - ), - ); - const fetchedC = new Set( - untracked(() => this.fetchedCountries()).map((c) => - c.id.toLowerCase(), - ), - ); - const fetchedR = new Set( - untracked(() => this.fetchedRegions()).map((r) => - r.id.toLowerCase(), - ), - ); allEntitiesFetched = - insts.every((i) => fetchedI.has(i.id.toLowerCase())) && - countries.every((c) => fetchedC.has(c.id.toLowerCase())) && - regions.every((r) => fetchedR.has(r.id.toLowerCase())); + (insts.length === 0 || + insts.every((i) => { + const cleanI = i.id.includes('/') + ? i.id.split('/').pop()!.toLowerCase() + : i.id.toLowerCase(); + return rawSeriesCleanIds.has(cleanI); + })) && + (countries.length === 0 || + countries.every((c) => + rawSeriesCleanIds.has(c.id.toLowerCase()), + )) && + (regions.length === 0 || + regions.every((r) => rawSeriesCleanIds.has(r.id.toLowerCase()))); } } - const hasResponse = !!untracked(() => this.rawTrendResponse()); if ( allTopicsFetched && sameType && sameFuzzy && allEntitiesFetched && - hasResponse + !!rawRes ) { // All requested data is already present in rawTrendResponse, so skip backend call! return; @@ -1249,7 +1267,32 @@ export class UniTrendParentComponent implements OnInit { ) .subscribe({ next: (response: TrendResponse) => { - this.rawTrendResponse.set(response); + const currentRaw = untracked(() => this.rawTrendResponse()); + if (!currentRaw || !currentRaw.series) { + this.rawTrendResponse.set(response); + } else { + const seriesMap = new Map(); + currentRaw.series.forEach((s) => { + seriesMap.set(`${s.entity_type}_${s.entity_id}`, s); + }); + response.series.forEach((s) => { + const key = `${s.entity_type}_${s.entity_id}`; + const prev = seriesMap.get(key); + if (prev && prev.topic_data && s.topic_data) { + seriesMap.set(key, { + ...prev, + ...s, + topic_data: { ...prev.topic_data, ...s.topic_data }, + }); + } else { + seriesMap.set(key, s); + } + }); + this.rawTrendResponse.set({ + ...response, + series: Array.from(seriesMap.values()), + }); + } this.isTrendLoading.set(false); this.updateUrlParams(); }, From 0aadbdbe7a4618eb12f51e2f35aaa59c119f3af6 Mon Sep 17 00:00:00 2001 From: Roman Date: Fri, 24 Jul 2026 02:26:47 +0200 Subject: [PATCH 26/26] feat(institution-membership): centralize institution-scoped access - 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 --- .../classify_ude_works_to_index.py | 209 +- .../run_20260723_154918_847690.json | 51 + .../authors/institution_membership_query.py | 231 ++ service/src/main/inse/authors/v2/service.py | 154 +- .../main/inse/company_connections/logic.py | 70 +- .../main/inse/company_connections/model.py | 7 +- .../main/inse/company_connections/service.py | 46 +- .../institutions_search_client.py | 43 - .../src/main/inse/middleware/etag_cache.py | 117 +- service/src/main/inse/persons/logic.py | 102 +- .../src/main/inse/persons/query_builder.py | 133 +- service/src/main/inse/persons/service.py | 46 +- service/src/main/inse/ranking/logic.py | 41 +- service/src/main/inse/ranking/model.py | 4 - service/src/main/inse/ranking/router.py | 42 +- service/src/main/inse/works/v2/model.py | 3 + service/src/main/inse/works/v2/service.py | 27 +- .../app/api/api/companyConnections.service.ts | 289 ++- webapp/src/app/api/api/persons.service.ts | 2270 +++++++++++------ .../model/companyConnectionsAvailability.ts | 13 + .../api/model/companyConnectionsResponse.ts | 23 +- .../app/api/model/keywordToAuthorRequest.ts | 4 - webapp/src/app/api/model/models.ts | 1 + webapp/src/app/app.routes.ts | 1 + .../dashboard/dashboard.component.html | 2 +- .../modules/dashboard/dashboard.component.ts | 11 + .../person-card/person-card.component.html | 5 +- .../person-card/person-card.component.ts | 14 +- .../person-company-connections.component.html | 5 - .../person-company-connections.component.ts | 38 +- .../person-list/person-list.component.html | 39 +- .../person-list/person-list.component.ts | 162 +- .../app/modules/person/person.component.html | 2 +- .../app/modules/person/person.component.ts | 27 +- .../uni-trend-parent.component.ts | 6 +- .../src/app/resolvers/person-list.resolver.ts | 11 +- webapp/src/app/resolvers/person.resolver.ts | 53 +- .../app/shared/person-list-query-params.ts | 29 + .../ui/app-menu/app-menu.component.html | 2 +- .../shared/ui/app-menu/app-menu.component.ts | 214 +- 40 files changed, 2681 insertions(+), 1866 deletions(-) create mode 100644 llm_evaluations/basic_applied_experimental/run_reports/run_20260723_154918_847690.json create mode 100644 service/src/main/inse/authors/institution_membership_query.py create mode 100644 webapp/src/app/api/model/companyConnectionsAvailability.ts create mode 100644 webapp/src/app/shared/person-list-query-params.ts diff --git a/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py b/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py index 0b1de043..d006ed68 100644 --- a/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py +++ b/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py @@ -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, diff --git a/llm_evaluations/basic_applied_experimental/run_reports/run_20260723_154918_847690.json b/llm_evaluations/basic_applied_experimental/run_reports/run_20260723_154918_847690.json new file mode 100644 index 00000000..a2c15e78 --- /dev/null +++ b/llm_evaluations/basic_applied_experimental/run_reports/run_20260723_154918_847690.json @@ -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 +} diff --git a/service/src/main/inse/authors/institution_membership_query.py b/service/src/main/inse/authors/institution_membership_query.py new file mode 100644 index 00000000..8f4906f1 --- /dev/null +++ b/service/src/main/inse/authors/institution_membership_query.py @@ -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}" diff --git a/service/src/main/inse/authors/v2/service.py b/service/src/main/inse/authors/v2/service.py index e0347314..b4b8b928 100644 --- a/service/src/main/inse/authors/v2/service.py +++ b/service/src/main/inse/authors/v2/service.py @@ -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"], ) diff --git a/service/src/main/inse/company_connections/logic.py b/service/src/main/inse/company_connections/logic.py index ceb39e06..14ccae33 100644 --- a/service/src/main/inse/company_connections/logic.py +++ b/service/src/main/inse/company_connections/logic.py @@ -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) diff --git a/service/src/main/inse/company_connections/model.py b/service/src/main/inse/company_connections/model.py index dd7d28c0..bb7c567e 100644 --- a/service/src/main/inse/company_connections/model.py +++ b/service/src/main/inse/company_connections/model.py @@ -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 diff --git a/service/src/main/inse/company_connections/service.py b/service/src/main/inse/company_connections/service.py index a739aa1c..19bef518 100644 --- a/service/src/main/inse/company_connections/service.py +++ b/service/src/main/inse/company_connections/service.py @@ -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) diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 1c3a060f..af18216e 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -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, diff --git a/service/src/main/inse/middleware/etag_cache.py b/service/src/main/inse/middleware/etag_cache.py index 3f36e483..47076a63 100644 --- a/service/src/main/inse/middleware/etag_cache.py +++ b/service/src/main/inse/middleware/etag_cache.py @@ -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, - ) \ No newline at end of file + ) diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 0168d39a..c8c7a157 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -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, diff --git a/service/src/main/inse/persons/query_builder.py b/service/src/main/inse/persons/query_builder.py index a45a492f..788ea3ac 100644 --- a/service/src/main/inse/persons/query_builder.py +++ b/service/src/main/inse/persons/query_builder.py @@ -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, ) diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index dfdf7fd7..51fb1c5c 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -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, ) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index faa023bf..770edd83 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -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) diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index 1321102f..686f98a4 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -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.", ) diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index 6f00eca7..df0c227d 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -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) diff --git a/service/src/main/inse/works/v2/model.py b/service/src/main/inse/works/v2/model.py index 5cde6e77..121ea2cc 100644 --- a/service/src/main/inse/works/v2/model.py +++ b/service/src/main/inse/works/v2/model.py @@ -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." ) diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index b7941d11..9c86b65e 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -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: diff --git a/webapp/src/app/api/api/companyConnections.service.ts b/webapp/src/app/api/api/companyConnections.service.ts index cbc5f803..59c13e2a 100644 --- a/webapp/src/app/api/api/companyConnections.service.ts +++ b/webapp/src/app/api/api/companyConnections.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,87 +9,244 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { HttpClient, HttpHeaders, HttpParams, - HttpResponse, HttpEvent, HttpParameterCodec, HttpContext - } from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { + HttpClient, + HttpHeaders, + HttpParams, + HttpResponse, + HttpEvent, + HttpParameterCodec, + HttpContext, +} from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; +// @ts-ignore +import { CompanyConnectionsAvailability } from '../model/companyConnectionsAvailability'; // @ts-ignore import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; - - @Injectable({ - providedIn: 'root' + providedIn: 'root', }) export class CompanyConnectionsService extends BaseService { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + } - constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { - super(basePath, configuration); + /** + * Check whether company connections are available for an author. + * @endpoint get /api/inse-service/authors/{author_id}/company-connections/availability + * @param authorId + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getCompanyConnectionsAvailability( + authorId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getCompanyConnectionsAvailability( + authorId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getCompanyConnectionsAvailability( + authorId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getCompanyConnectionsAvailability( + authorId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + 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; - public getCompanyConnectionsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getCompanyConnectionsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getCompanyConnectionsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - 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('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: 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( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: 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; + public getCompanyConnectionsByAuthor( + authorId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getCompanyConnectionsByAuthor( + authorId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getCompanyConnectionsByAuthor( + authorId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + 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( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } diff --git a/webapp/src/app/api/api/persons.service.ts b/webapp/src/app/api/api/persons.service.ts index 03222a4c..2dd47272 100644 --- a/webapp/src/app/api/api/persons.service.ts +++ b/webapp/src/app/api/api/persons.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,12 +9,18 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { HttpClient, HttpHeaders, HttpParams, - HttpResponse, HttpEvent, HttpParameterCodec, HttpContext - } from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { + HttpClient, + HttpHeaders, + HttpParams, + HttpResponse, + HttpEvent, + HttpParameterCodec, + HttpContext, +} from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { AuthorsListResponse } from '../model/authorsListResponse'; @@ -26,869 +32,1449 @@ import { HTTPValidationError } from '../model/hTTPValidationError'; import { PersonBio } from '../model/personBio'; // @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 PersonsService 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); + /** + * Generates a bio for a person by author ID. + * @endpoint get /api/inse-service/persons/bio + * @param authorId OpenAlex author ID (e.g., A5093075883) + * @param include Comma-separated list to include tags + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public generatePersonBio( + authorId: string, + include?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public generatePersonBio( + authorId: string, + include?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public generatePersonBio( + authorId: string, + include?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public generatePersonBio( + authorId: string, + include?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorId === null || authorId === undefined) { + throw new Error( + 'Required parameter authorId was null or undefined when calling generatePersonBio.', + ); } - /** - * Generates a bio for a person by author ID. - * @endpoint get /api/inse-service/persons/bio - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param include Comma-separated list to include tags - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public generatePersonBio(authorId: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public generatePersonBio(authorId: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public generatePersonBio(authorId: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public generatePersonBio(authorId: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorId === null || authorId === undefined) { - throw new Error('Required parameter authorId was null or undefined when calling generatePersonBio.'); - } + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorId, + 'author_id', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorId, 'author_id'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); + 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 localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; - const localVarTransferCache: boolean = options?.transferCache ?? true; + 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/persons/bio`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } + /** + * Searches for person by ID. + * @endpoint get /api/inse-service/person/{id} + * @param id OpenAlex author ID + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 getPersonByID( + id: string, + include?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getPersonByID( + id: string, + include?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPersonByID( + id: string, + include?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPersonByID( + id: string, + include?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (id === null || id === undefined) { + throw new Error( + 'Required parameter id was null or undefined when calling getPersonByID.', + ); + } - let localVarPath = `/api/inse-service/persons/bio`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + + 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/person/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Searches for person by ID. + * @endpoint get /api/inse-service/person/{id} + * @param id OpenAlex author ID + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 getPersonByID_1( + id: string, + include?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getPersonByID_1( + id: string, + include?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPersonByID_1( + id: string, + include?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPersonByID_1( + id: string, + include?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (id === null || id === undefined) { + throw new Error( + 'Required parameter id was null or undefined when calling getPersonByID_1.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + + 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/person/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Searches for persons by ID or name. + * @endpoint get /api/inse-service/persons/search + * @param authorId OpenAlex author ID (e.g., A5093075883) + * @param query Search query (e.g., Arman AND Arzani) + * @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public searchPersons( + authorId?: string, + query?: string, + include?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersons( + authorId?: string, + query?: string, + include?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersons( + authorId?: string, + query?: string, + include?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersons( + authorId?: string, + query?: string, + include?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorId, + 'author_id', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + + 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/persons/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Searches for person by name. + * @endpoint get /api/inse-service/persons/autocomplete + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 searchPersonsAutocomplete( + authorName: string, + include: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersonsAutocomplete( + authorName: string, + include: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsAutocomplete( + authorName: string, + include: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsAutocomplete( + authorName: string, + include: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorName === null || authorName === undefined) { + throw new Error( + 'Required parameter authorName was null or undefined when calling searchPersonsAutocomplete.', + ); + } + if (include === null || include === undefined) { + throw new Error( + 'Required parameter include was null or undefined when calling searchPersonsAutocomplete.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorName, + 'author_name', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + + 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/persons/autocomplete`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Searches for person by name. + * @endpoint get /api/inse-service/persons/autocomplete + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 searchPersonsAutocomplete_2( + authorName: string, + include: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersonsAutocomplete_2( + authorName: string, + include: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsAutocomplete_2( + authorName: string, + include: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsAutocomplete_2( + authorName: string, + include: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorName === null || authorName === undefined) { + throw new Error( + 'Required parameter authorName was null or undefined when calling searchPersonsAutocomplete_2.', + ); + } + if (include === null || include === undefined) { + throw new Error( + 'Required parameter include was null or undefined when calling searchPersonsAutocomplete_2.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorName, + 'author_name', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + + 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/persons/autocomplete`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Searches for person by name. + * @endpoint get /api/inse-service/persons/searchByName + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param limit Limit of search page results + * @param pageOffset Offset of the result page + * @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 searchPersonsByName( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersonsByName( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsByName( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsByName( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorName === null || authorName === undefined) { + throw new Error( + 'Required parameter authorName was null or undefined when calling searchPersonsByName.', + ); + } + if (include === null || include === undefined) { + throw new Error( + 'Required parameter include was null or undefined when calling searchPersonsByName.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorName, + 'author_name', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + limit, + 'limit', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageOffset, + 'page_offset', + ); + + 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/persons/searchByName`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Searches for person by name. + * @endpoint get /api/inse-service/persons/searchByName + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param limit Limit of search page results + * @param pageOffset Offset of the result page + * @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 searchPersonsByName_3( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersonsByName_3( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsByName_3( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsByName_3( + authorName: string, + include: string, + limit?: number, + pageOffset?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorName === null || authorName === undefined) { + throw new Error( + 'Required parameter authorName was null or undefined when calling searchPersonsByName_3.', + ); + } + if (include === null || include === undefined) { + throw new Error( + 'Required parameter include was null or undefined when calling searchPersonsByName_3.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + authorName, + 'author_name', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + limit, + 'limit', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageOffset, + 'page_offset', + ); + + 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/persons/searchByName`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Searches for persons with advanced filters (Topic & Institution) and pagination. + * @endpoint get /api/inse-service/persons/search-list + * @param query Search query (e.g., Arman AND Arzani) + * @param institutionId Filter by OpenAlex institution ID + * @param sortBy Value to sort by + * @param sortOrder asc or desc? + * @param topic Filter by topic display names + * @param page Page number (1-indexed) + * @param pageSize Results per page + * @param include Comma-separated include tags + * @param yearFilterEnabled Apply the selected affiliation year rule + * @param filterMode Filter mode: \'in\' or \'from\' + * @param filterYear Filter year + * @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 searchPersonsList( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersonsList( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsList( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsList( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + institutionId, + 'institutionId', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortBy, + 'sortBy', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topic', ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFilterEnabled, + 'yearFilterEnabled', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + filterMode, + 'filterMode', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + filterYear, + 'filterYear', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Searches for person by ID. - * @endpoint get /api/inse-service/person/{id} - * @param id OpenAlex author ID - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 getPersonByID(id: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getPersonByID(id: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID(id: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID(id: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (id === null || id === undefined) { - throw new Error('Required parameter id was null or undefined when calling getPersonByID.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarHeaders = this.defaultHeaders; + 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'; + } + } - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } + let localVarPath = `/api/inse-service/persons/search-list`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - 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/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + /** + * Searches for persons with advanced filters (Topic & Institution) and pagination. + * @endpoint get /api/inse-service/persons/search-list + * @param query Search query (e.g., Arman AND Arzani) + * @param institutionId Filter by OpenAlex institution ID + * @param sortBy Value to sort by + * @param sortOrder asc or desc? + * @param topic Filter by topic display names + * @param page Page number (1-indexed) + * @param pageSize Results per page + * @param include Comma-separated include tags + * @param yearFilterEnabled Apply the selected affiliation year rule + * @param filterMode Filter mode: \'in\' or \'from\' + * @param filterYear Filter year + * @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 searchPersonsList_4( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchPersonsList_4( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsList_4( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchPersonsList_4( + query?: string, + institutionId?: string, + sortBy?: string, + sortOrder?: string, + topic?: Array, + page?: number, + pageSize?: number, + include?: string, + yearFilterEnabled?: boolean, + filterMode?: string, + filterYear?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + institutionId, + 'institutionId', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortBy, + 'sortBy', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortOrder, + 'sortOrder', + ); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topic', ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'pageSize', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + include, + 'include', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + yearFilterEnabled, + 'yearFilterEnabled', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + filterMode, + 'filterMode', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + filterYear, + 'filterYear', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Searches for person by ID. - * @endpoint get /api/inse-service/person/{id} - * @param id OpenAlex author ID - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 getPersonByID_1(id: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getPersonByID_1(id: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID_1(id: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID_1(id: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (id === null || id === undefined) { - throw new Error('Required parameter id was null or undefined when calling getPersonByID_1.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); + const localVarTransferCache: boolean = options?.transferCache ?? true; - 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/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Searches for persons by ID or name. - * @endpoint get /api/inse-service/persons/search - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param query Search query (e.g., Arman AND Arzani) - * @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public searchPersons(authorId?: string, query?: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersons(authorId?: string, query?: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersons(authorId?: string, query?: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersons(authorId?: string, query?: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorId, 'author_id'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - 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/persons/search`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Searches for person by name. - * @endpoint get /api/inse-service/persons/autocomplete - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 searchPersonsAutocomplete(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsAutocomplete(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorName === null || authorName === undefined) { - throw new Error('Required parameter authorName was null or undefined when calling searchPersonsAutocomplete.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsAutocomplete.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorName, 'author_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - 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/persons/autocomplete`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Searches for person by name. - * @endpoint get /api/inse-service/persons/autocomplete - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsAutocomplete_2(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorName === null || authorName === undefined) { - throw new Error('Required parameter authorName was null or undefined when calling searchPersonsAutocomplete_2.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsAutocomplete_2.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorName, 'author_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - 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/persons/autocomplete`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Searches for persons by institution name. - * @endpoint get /api/inse-service/persons/searchByInstitution - * @param institutionName Institution name (e.g., MIT, Oxford University) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - * @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 searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (institutionName === null || institutionName === undefined) { - throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsByInstitution.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - institutionName, 'institution_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - limit, 'limit'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageOffset, 'page_offset'); - - 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/persons/searchByInstitution`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Searches for persons by institution name. - * @endpoint get /api/inse-service/persons/searchByInstitution - * @param institutionName Institution name (e.g., MIT, Oxford University) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - * @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 searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (institutionName === null || institutionName === undefined) { - throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution_3.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsByInstitution_3.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - institutionName, 'institution_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - limit, 'limit'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageOffset, 'page_offset'); - - 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/persons/searchByInstitution`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Searches for person by name. - * @endpoint get /api/inse-service/persons/searchByName - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - * @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 searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorName === null || authorName === undefined) { - throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsByName.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorName, 'author_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - limit, 'limit'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageOffset, 'page_offset'); - - 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/persons/searchByName`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Searches for person by name. - * @endpoint get /api/inse-service/persons/searchByName - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @param limit Limit of search page results - * @param pageOffset Offset of the result page - * @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 searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorName === null || authorName === undefined) { - throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName_4.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsByName_4.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorName, 'author_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - limit, 'limit'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageOffset, 'page_offset'); - - 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/persons/searchByName`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Searches for persons with advanced filters (Topic & Institution) and pagination. - * @endpoint get /api/inse-service/persons/search-list - * @param query Search query (e.g., Arman AND Arzani) - * @param institutionName Filter by institution name - * @param sortBy Value to sort by - * @param sortOrder asc or desc? - * @param topic Filter by topic display names - * @param page Page number (1-indexed) - * @param pageSize Results per page - * @param include Comma-separated include tags - * @param strict Strict institution search by target year - * @param filterMode Filter mode: \'in\' or \'from\' - * @param filterYear Filter year - * @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 searchPersonsList(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsList(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsList(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsList(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - institutionName, 'institutionName'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortBy, 'sortBy'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortOrder, 'sortOrder'); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'topic'); - }) - } - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - strict, 'strict'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - filterMode, 'filterMode'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - filterYear, 'filterYear'); - - 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/persons/search-list`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Searches for persons with advanced filters (Topic & Institution) and pagination. - * @endpoint get /api/inse-service/persons/search-list - * @param query Search query (e.g., Arman AND Arzani) - * @param institutionName Filter by institution name - * @param sortBy Value to sort by - * @param sortOrder asc or desc? - * @param topic Filter by topic display names - * @param page Page number (1-indexed) - * @param pageSize Results per page - * @param include Comma-separated include tags - * @param strict Strict institution search by target year - * @param filterMode Filter mode: \'in\' or \'from\' - * @param filterYear Filter year - * @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 searchPersonsList_5(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsList_5(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsList_5(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsList_5(query?: string, institutionName?: string, sortBy?: string, sortOrder?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - institutionName, 'institutionName'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortBy, 'sortBy'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortOrder, 'sortOrder'); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'topic'); - }) - } - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'pageSize'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - strict, 'strict'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - filterMode, 'filterMode'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - filterYear, 'filterYear'); - - 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/persons/search-list`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } + let localVarPath = `/api/inse-service/persons/search-list`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } diff --git a/webapp/src/app/api/model/companyConnectionsAvailability.ts b/webapp/src/app/api/model/companyConnectionsAvailability.ts new file mode 100644 index 00000000..cefa8680 --- /dev/null +++ b/webapp/src/app/api/model/companyConnectionsAvailability.ts @@ -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; +} diff --git a/webapp/src/app/api/model/companyConnectionsResponse.ts b/webapp/src/app/api/model/companyConnectionsResponse.ts index 9beabd1e..9b86a710 100644 --- a/webapp/src/app/api/model/companyConnectionsResponse.ts +++ b/webapp/src/app/api/model/companyConnectionsResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,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; - matching_method?: string | null; - company_count: number; - has_more_results: boolean; - common_name_warning: boolean; - connections?: Array; +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; } - diff --git a/webapp/src/app/api/model/keywordToAuthorRequest.ts b/webapp/src/app/api/model/keywordToAuthorRequest.ts index 9d34e1d9..97edef03 100644 --- a/webapp/src/app/api/model/keywordToAuthorRequest.ts +++ b/webapp/src/app/api/model/keywordToAuthorRequest.ts @@ -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. */ diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 46e3858a..d85f7041 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -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'; diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 48127b36..3ac157fe 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -147,6 +147,7 @@ export const routes: Routes = [ 'query', 'page', 'pageSize', + 'institutionId', 'institutionName', 'sortBy', 'sortOrder', diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 4b827cb2..e7479263 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -26,7 +26,7 @@
groups diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index ea16ab26..171c3d6f 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -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; diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index 9f7bf142..1231d2a5 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -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()"> Verbindungen zu Unternehmen konnten nicht geladen werden.
-} @else if (data && !data.is_ude_author) { -
-

Keine Unternehmenssuche verfügbar

-

Für diese Person wird aktuell keine Suche nach Unternehmen angezeigt.

-
} @else if (data && connections.length === 0) {

Keine Treffer im Handelsregister

diff --git a/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts b/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts index 742349e8..0194c0a6 100644 --- a/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts +++ b/webapp/src/app/modules/person-company-connections/person-company-connections.component.ts @@ -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; } diff --git a/webapp/src/app/modules/person-list/person-list.component.html b/webapp/src/app/modules/person-list/person-list.component.html index 9647b24a..9dc0f676 100644 --- a/webapp/src/app/modules/person-list/person-list.component.html +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -59,7 +59,7 @@ close - } @else if (filter.category === 'institutionName') { + } @else if (filter.category === 'institutionId') { } - @if (findInstitutionPageIdByName(filter.value)) { + @if (filter.value) { @@ -246,9 +246,10 @@ (keyup.enter)="applySidebarFilters()" /> @for (institution of institutionOptions(); track institution.id) { - + {{ institution.display_name }} @if (institution.hint) { {{ institution.hint }} @@ -259,7 +260,7 @@ !institutionLookupLoading() && institutionOptions().length === 0 && institutionControl.value && - institutionControl.value.trim().length >= 2 + displayInstitution(institutionControl.value).trim().length >= 2 ) { Keine Institution gefunden } @@ -284,11 +285,11 @@ + aria-label="Institutionszugehörigkeit nach Jahr filtern"> Zusammenarbeit nach Jahr filtern + style="font-size: 12px; font-weight: 500; color: var(--sg-text)"> + Institutionszugehörigkeit nach Jahr filtern + @if (yearFilterEnabledControl.value) { @@ -305,16 +306,16 @@ (change)="applySidebarFilters()" style="display: flex; gap: 16px" aria-label="Modus für Jahresfilter"> - Genau in - Seit + + + Genau im Jahr + + + + + Seit + + ([]); readonly institutionLookupLoading = signal(false); + readonly selectedInstitution = signal(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('', { + nonNullable: true, + }); yearFilterEnabledControl = new FormControl(false, { nonNullable: true }); filterModeControl = new FormControl<'in' | 'from'>('from', { nonNullable: true, }); - filterYearControl = new FormControl(new Date().getFullYear() - 1, { + filterYearControl = new FormControl(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 = [ - ...(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()); 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; diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index 316c07be..37b613aa 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -149,7 +149,7 @@ (tagClick)="onInterestingTagClick($event)">
- @for (itemGroup of navItemGroups; track $index) { + @for (itemGroup of navItemGroups(); track $index) {
@if ( (!itemGroup.adminOnly || diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index cf3cc849..7f0e1896 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -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(() => { + 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(() => { + 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,