From 42bcac251bded6f734e2c9f8e6ec3a2bd2ef1dc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Tue, 4 Aug 2026 15:03:50 +0200 Subject: [PATCH 01/18] feat(person): moved link tab nav bar to dedicated component --- .../app/modules/person/person.component.html | 20 ++--- .../app/modules/person/person.component.ts | 74 ++++++++++++------- .../shared/ui/app-menu/app-menu.component.ts | 41 ++++++---- webapp/src/app/shared/ui/icons.ts | 18 +++++ .../link-tab-nav-bar.component.html | 19 +++++ .../link-tab-nav-bar.component.scss | 5 ++ .../link-tab-nav-bar.component.ts | 50 +++++++++++++ webapp/src/styles.scss | 3 +- 8 files changed, 174 insertions(+), 56 deletions(-) create mode 100644 webapp/src/app/shared/ui/icons.ts create mode 100644 webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html create mode 100644 webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.scss create mode 100644 webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index 362af283..1fd0a34b 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -132,20 +132,12 @@ [loading]="isTopicsLoading()" (tagClick)="onInterestingTagClick($event)"> - + @if (this.links()) { + + } } @else { ; - disabled: boolean; -}; +import { + LinkTabNavBarComponent, + LinkTabNavBarItem, +} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; +import { + COMPANY_CONNECTION_ICON, + FUNDING_ICON, + NETWORK_ICON, + NEWS_ICON, + OVERVIEW_ICON, + PATENT_ICON, + PROJECT_ICON, + PUBLICATION_ICON, +} from '../../shared/ui/icons'; @Component({ selector: 'app-person', @@ -55,6 +62,7 @@ type PersonLink = { LoadingComponent, CountryFlagComponent, CareerStageChipComponent, + LinkTabNavBarComponent, ], templateUrl: './person.component.html', styleUrl: './person.component.scss', @@ -69,6 +77,11 @@ export class PersonComponent { canFetchGdprRelevantData = input.required(); + protected readonly navBar = viewChild('navBar'); + protected readonly activeLink = computed( + () => this.navBar()?.activeLink() ?? null, + ); + constructor() { this.bookmarkService .load() @@ -236,11 +249,12 @@ export class PersonComponent { { initialValue: [] }, ); - readonly links = computed(() => { + readonly links = computed(() => { const links = [ { label: 'Übersicht', description: 'Übersicht über die Person', + icon: OVERVIEW_ICON, path: 'overview', disabled: false, }, @@ -249,6 +263,7 @@ export class PersonComponent { { label: 'Projekte', description: 'Übersicht der durchgeführten Projekte der Person', + icon: PROJECT_ICON, path: 'projects', queryParams: { page: 0, @@ -264,12 +279,13 @@ export class PersonComponent { { label: 'Publikationen', description: 'Übersicht der Publikationen der Person', + icon: PUBLICATION_ICON, path: 'publications', - disabled: false, }, { label: 'Netzwerk', description: 'Kooperationsnetzwerk der Person', + icon: NETWORK_ICON, path: 'network', disabled: false, queryParams: { @@ -284,6 +300,7 @@ export class PersonComponent { { label: 'Unternehmen', description: 'Unternehmen, mit denen die Person verbunden ist', + icon: COMPANY_CONNECTION_ICON, path: 'company-connections', disabled: false, }, @@ -292,18 +309,21 @@ export class PersonComponent { { label: 'Förderungen', description: 'Übersicht der Förderungen der Person', + icon: FUNDING_ICON, path: 'funding', disabled: false, }, { label: 'Nachrichten', description: 'Nachrichten über die Person', + icon: NEWS_ICON, path: 'news', disabled: false, }, { label: 'Patente', description: 'Patente der Person', + icon: PATENT_ICON, path: 'patents', disabled: false, }, @@ -311,25 +331,25 @@ export class PersonComponent { return links; }); - readonly activeLink = computed(() => { - const currentUrl = this.currentUrl(); - if (!currentUrl) { - return null; - } + // readonly activeLink = computed(() => { + // const currentUrl = this.currentUrl(); + // if (!currentUrl) { + // return null; + // } - for (const link of this.links()) { - const linkUrl = this.router - .createUrlTree([link.path], { - relativeTo: this.activatedRoute, - }) - .toString(); + // for (const link of this.links()) { + // const linkUrl = this.router + // .createUrlTree([link.path], { + // relativeTo: this.activatedRoute, + // }) + // .toString(); - if (linkUrl.startsWith(currentUrl) || currentUrl.startsWith(linkUrl)) { - return link; - } - } - return null; - }); + // if (linkUrl.startsWith(currentUrl) || currentUrl.startsWith(linkUrl)) { + // return link; + // } + // } + // return null; + // }); onInterestingTagClick(selection: { id: string; 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 fa0072f3..52d86a73 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 @@ -17,6 +17,21 @@ import { topicQueryParamKeys } from '../../../resolvers/topic-page.resolver'; import { SortDirection, TopicSortBy, WorkSortBy } from '../../../api'; import { workQueryParamKeys } from '../../../resolvers/work-page.resolver'; import { MatMenuModule } from '@angular/material/menu'; +import { + BOOKMARKS_ICON, + DASHBOARD_ICON, + INSTITUTION_ICON, + JOBS_ICON, + KEYWORDS_ICON, + MANAGE_ACCOUNTS_ICON, + NEWS_ICON, + ORGANIZATIONS_ICON, + PATENT_ICON, + PERSONS_ICON, + PROJECT_ICON, + PUBLICATION_ICON, + TOPIC_ICON, +} from '../icons'; type NavItem = { label: string; @@ -71,13 +86,13 @@ export class AppMenuComponent { const items: NavItem[] = [ { label: 'Dashboard', - icon: 'dashboard', + icon: DASHBOARD_ICON, route: '/dashboard', disabled: false, }, { label: 'Personen', - icon: 'groups', + icon: PERSONS_ICON, route: '/persons', queryParams: activeInstitutionPersonListQueryParams( this.credentialService.effectiveInstitutionId(), @@ -87,19 +102,19 @@ export class AppMenuComponent { }, { label: 'Bookmarks', - icon: 'bookmarks', + icon: BOOKMARKS_ICON, route: '/bookmarks', disabled: false, }, { label: 'News', - icon: 'newspaper', + icon: NEWS_ICON, route: '/news', disabled: false, }, { label: 'Institutionen', - icon: 'apartment', + icon: INSTITUTION_ICON, route: '/institutions', disabled: false, queryParams: { @@ -112,7 +127,7 @@ export class AppMenuComponent { }, { label: 'Publikationen', - icon: 'menu_book', + icon: PUBLICATION_ICON, route: '/publications', disabled: false, queryParams: { @@ -125,7 +140,7 @@ export class AppMenuComponent { }, { label: 'Themen', - icon: 'topic', + icon: TOPIC_ICON, route: '/topics', disabled: false, queryParams: { @@ -138,7 +153,7 @@ export class AppMenuComponent { }, { label: 'Projekte', - icon: 'work', + icon: PROJECT_ICON, route: '/projects', disabled: false, queryParams: { @@ -152,13 +167,13 @@ export class AppMenuComponent { }, { label: 'Patente', - icon: 'workspace_premium', + icon: PATENT_ICON, route: '/patents', disabled: false, }, { label: 'Keywords', - icon: 'join_left', + icon: KEYWORDS_ICON, route: '/keywords', disabled: false, queryParams: { @@ -167,21 +182,21 @@ export class AppMenuComponent { }, { label: 'Accounts', - icon: 'manage_accounts', + icon: MANAGE_ACCOUNTS_ICON, route: '/accounts', disabled: false, managerOrAdminOnly: true, }, { label: 'Organisationen', - icon: 'domain', + icon: ORGANIZATIONS_ICON, route: '/organizations', disabled: false, superAdminOnly: true, }, { label: 'Jobs', - icon: 'sync', + icon: JOBS_ICON, route: '/jobs', disabled: false, superAdminOnly: true, diff --git a/webapp/src/app/shared/ui/icons.ts b/webapp/src/app/shared/ui/icons.ts new file mode 100644 index 00000000..ed81f570 --- /dev/null +++ b/webapp/src/app/shared/ui/icons.ts @@ -0,0 +1,18 @@ +export const BOOKMARKS_ICON = "bookmarks" as const; +export const COMPANY_CONNECTION_ICON = 'business' as const; +export const DASHBOARD_ICON = 'dashboard' as const; +export const FUNDING_ICON = 'account_balance' as const; +export const INSTITUTION_ICON = 'school' as const; +export const JOBS_ICON = "sync" as const; +export const KEYWORDS_ICON = 'join_left' as const; +export const MANAGE_ACCOUNTS_ICON = 'manage_accounts' as const; +export const NETWORK_ICON = 'share' as const; +export const NEWS_ICON = 'newspaper' as const; +export const ORGANIZATIONS_ICON = 'domain' as const; +export const OVERVIEW_ICON = 'visibility' as const; +export const PATENT_ICON = 'workspace_premium' as const; +export const PERSONS_ICON = 'groups' as const; +export const PERSON_ICON = 'person' as const; +export const PROJECT_ICON = 'work' as const; +export const PUBLICATION_ICON = 'menu_book' as const; +export const TOPIC_ICON = 'topic' as const; \ No newline at end of file diff --git a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html new file mode 100644 index 00000000..fa54da5b --- /dev/null +++ b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html @@ -0,0 +1,19 @@ + diff --git a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.scss b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.scss new file mode 100644 index 00000000..aaa131c5 --- /dev/null +++ b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.scss @@ -0,0 +1,5 @@ +.link-tab-nav-bar-item { + display: flex; + align-items: center; + gap: 0.25rem; +} \ No newline at end of file diff --git a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts new file mode 100644 index 00000000..3f87669d --- /dev/null +++ b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts @@ -0,0 +1,50 @@ +import { Component, computed, inject, input } from '@angular/core'; +import { MatTabNavPanel, MatTabsModule } from '@angular/material/tabs'; +import { + ActivatedRoute, + isActive, + Router, + RouterModule, +} from '@angular/router'; +import { MatIconModule } from '@angular/material/icon'; + +export type LinkTabNavBarItem = { + label: string; + path: string; + icon?: string; + description?: string; + queryParams?: Record; + disabled?: boolean; +}; + +@Component({ + selector: 'app-link-tab-nav-bar', + imports: [MatTabsModule, RouterModule, MatIconModule], + templateUrl: './link-tab-nav-bar.component.html', + styleUrl: './link-tab-nav-bar.component.scss', +}) +export class LinkTabNavBarComponent { + private readonly router = inject(Router); + private readonly activatedRoute = inject(ActivatedRoute); + + links = input.required(); + tabPanel = input(); + + activeLink = computed(() => { + for (const link of this.links()) { + const linkUrlTree = this.router.createUrlTree([link.path], { + relativeTo: this.activatedRoute, + }); + + if ( + isActive(linkUrlTree, this.router, { + paths: 'subset', + queryParams: 'ignored', + })() + ) { + return link; + } + } + return null; + }); +} diff --git a/webapp/src/styles.scss b/webapp/src/styles.scss index fdcaec2f..95a45697 100644 --- a/webapp/src/styles.scss +++ b/webapp/src/styles.scss @@ -2,12 +2,11 @@ // For more information: https://material.angular.io/guide/theming @use '@angular/material' as mat; @use 'm3-theme' as m3; +@import url('https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,200..700,0..1,-50..200'); @include mat.elevation-classes(); @include mat.app-background(); -@import url('https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,200..700,0..1,-50..200'); - @font-face { font-display: swap; font-family: 'Montserrat'; From 6c55493acb9c382f4869cc597f62889883dd4fdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Tue, 4 Aug 2026 15:30:34 +0200 Subject: [PATCH 02/18] feat(topic, institution): reused generic link tab nav bar --- .../institution/institution.component.html | 36 +++++---------- .../institution/institution.component.scss | 12 +++-- .../institution/institution.component.ts | 45 +++++++++++-------- .../app/modules/topic/topic.component.html | 15 +------ .../src/app/modules/topic/topic.component.ts | 9 +++- 5 files changed, 56 insertions(+), 61 deletions(-) diff --git a/webapp/src/app/modules/institution/institution.component.html b/webapp/src/app/modules/institution/institution.component.html index ef072421..4b53e760 100644 --- a/webapp/src/app/modules/institution/institution.component.html +++ b/webapp/src/app/modules/institution/institution.component.html @@ -1,27 +1,15 @@ -
-

{{ institution().display_name }}

- - -

{{ institution().homepage_url }}

-

{{ institution().display_name_alternatives }}

-

And many more useful details...

-
-
- - +
+
+

{{ institution().display_name }}

+ + +

{{ institution().homepage_url }}

+

{{ institution().display_name_alternatives }}

+

And many more useful details...

+
+
+
+
diff --git a/webapp/src/app/modules/institution/institution.component.scss b/webapp/src/app/modules/institution/institution.component.scss index 2521fee5..0aae5047 100644 --- a/webapp/src/app/modules/institution/institution.component.scss +++ b/webapp/src/app/modules/institution/institution.component.scss @@ -1,6 +1,12 @@ -.content { - padding: 16px; +.container { display: flex; flex-direction: column; - gap: 16px; + gap: 1rem; +} + +.content { + display: flex; + flex-direction: column; + gap: 1rem; + margin: 0 1rem; } diff --git a/webapp/src/app/modules/institution/institution.component.ts b/webapp/src/app/modules/institution/institution.component.ts index 124b4f13..0edce91b 100644 --- a/webapp/src/app/modules/institution/institution.component.ts +++ b/webapp/src/app/modules/institution/institution.component.ts @@ -1,25 +1,21 @@ import { Component, computed, input } from '@angular/core'; -import { RouterLink, RouterOutlet, RouterLinkActive } from '@angular/router'; +import { RouterModule } from '@angular/router'; import { Institution } from '../../api'; import { MatCardModule } from '@angular/material/card'; import { MatTabsModule } from '@angular/material/tabs'; - -type TabLink = { - label: string; - path: string; - disabled: boolean; - queryParams?: Record; -}; +import { + LinkTabNavBarComponent, + LinkTabNavBarItem, +} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; +import { + PATENT_ICON, + PROJECT_ICON, + PUBLICATION_ICON, +} from '../../shared/ui/icons'; @Component({ selector: 'app-institution', - imports: [ - MatCardModule, - MatTabsModule, - RouterLink, - RouterOutlet, - RouterLinkActive, - ], + imports: [MatCardModule, MatTabsModule, RouterModule, LinkTabNavBarComponent], templateUrl: './institution.component.html', styleUrl: './institution.component.scss', }) @@ -27,14 +23,20 @@ export class InstitutionComponent { institution = input.required(); canFetchGdprRelevantData = input.required(); - _links = computed(() => { - const links: TabLink[] = [ - { label: 'Publikationen', path: 'publications', disabled: false }, + _links = computed(() => { + const links: LinkTabNavBarItem[] = [ + { + label: 'Publikationen', + icon: PUBLICATION_ICON, + path: 'publications', + disabled: false, + }, ]; if (this.canFetchGdprRelevantData()) { links.push( { label: 'Projekte', + icon: PROJECT_ICON, path: 'projects', disabled: false, queryParams: { @@ -46,7 +48,12 @@ export class InstitutionComponent { sort_direction: 'asc', }, }, - { label: 'Patente', path: 'patents', disabled: false }, + { + label: 'Patente', + icon: PATENT_ICON, + path: 'patents', + disabled: false, + }, ); } return links; diff --git a/webapp/src/app/modules/topic/topic.component.html b/webapp/src/app/modules/topic/topic.component.html index fb4bc779..d75b8c70 100644 --- a/webapp/src/app/modules/topic/topic.component.html +++ b/webapp/src/app/modules/topic/topic.component.html @@ -31,21 +31,8 @@
+ -
diff --git a/webapp/src/app/modules/topic/topic.component.ts b/webapp/src/app/modules/topic/topic.component.ts index 38c102f6..306cbcb8 100644 --- a/webapp/src/app/modules/topic/topic.component.ts +++ b/webapp/src/app/modules/topic/topic.component.ts @@ -6,6 +6,11 @@ import { MatDividerModule } from '@angular/material/divider'; import { MatIconModule } from '@angular/material/icon'; import { DecimalPipe } from '@angular/common'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; +import { PUBLICATION_ICON } from '../../shared/ui/icons'; +import { + LinkTabNavBarComponent, + LinkTabNavBarItem, +} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; @Component({ host: { @@ -18,6 +23,7 @@ import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; MatDividerModule, MatIconModule, DecimalPipe, + LinkTabNavBarComponent, ], templateUrl: './topic.component.html', styleUrl: './topic.component.scss', @@ -25,9 +31,10 @@ import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; export class TopicComponent { topic = input.required(); - links = [ + links: LinkTabNavBarItem[] = [ { label: 'Publikationen', + icon: PUBLICATION_ICON, path: 'publications', disabled: false, queryParams: { From 1d7a54c8663b3853c13eb648f53aa10b148fa3cb Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 19:29:17 +0200 Subject: [PATCH 03/18] institutes: fixed total results for publications table --- service/src/main/inse/works/v2/service.py | 1 + 1 file changed, 1 insertion(+) diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index f1fa10d2..20e139a8 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -654,6 +654,7 @@ async def _search_works( size=size, offset=page * size, sort=sort, + track_total_hits=True ) hits_block = response.get("hits", {}) From 7628f219e271261ed34eee309472537363c76dad Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 19:30:55 +0200 Subject: [PATCH 04/18] institutions: moved the fundings chart and projects table into exandable accordions --- .../institution-projects.component.html | 76 ++++++++++++------- .../institution-projects.component.scss | 34 +++++---- .../institution-projects.component.ts | 10 +-- 3 files changed, 70 insertions(+), 50 deletions(-) diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.html b/webapp/src/app/modules/institution-projects/institution-projects.component.html index 66a1bc1b..b5e22762 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.html +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.html @@ -1,30 +1,15 @@
-

Projekte

+
+
Projekte
+

Übersicht der Projekte, die von der Institution durchgeführt werden.

+
-
-
- + + + + Förderung über Zeit + - - -
@@ -56,15 +41,48 @@ | currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined " />
-
-
+ + + + + Projektliste + + +
+ + + + + +
+
+ {{ row.funding_start | date: 'dd.MM.yyyy' }} @@ -79,8 +97,8 @@ open_in_new - + + Date: Tue, 4 Aug 2026 19:33:28 +0200 Subject: [PATCH 05/18] adjusted the description for publications table expansion panel --- .../institution-publications.component.html | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/webapp/src/app/modules/institution-publications/institution-publications.component.html b/webapp/src/app/modules/institution-publications/institution-publications.component.html index 864afd0b..6228de7e 100644 --- a/webapp/src/app/modules/institution-publications/institution-publications.component.html +++ b/webapp/src/app/modules/institution-publications/institution-publications.component.html @@ -16,8 +16,7 @@ Publikationsliste - {{ total() >= 10000 ? 'mehr als' : '' }} + {{ total() }} Publikationen From 62f0812aae459f506995e2d1e3b0e1000d3b616c Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 19:34:25 +0200 Subject: [PATCH 06/18] added optional disable/enable fitlers logic into resolvers, disabled filters for BUND und EU fundings --- webapp/src/app/app.routes.ts | 16 +-- .../bund-projects-funding.resolver.ts | 15 +++ .../cordis-eu-projects-funding.resolver.ts | 124 +++++++++++------- 3 files changed, 94 insertions(+), 61 deletions(-) diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 40deb417..0f4bec64 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -693,7 +693,9 @@ export const routes: Routes = [ bundProjectsFunding: bundProjectsFundingResolver, cordisEuProjectsFunding: cordisEuProjectsFundingResolver, }, - runGuardsAndResolvers: 'always', + data: { + enableFilters: false, + }, children: [ { path: '', @@ -743,18 +745,6 @@ export const routes: Routes = [ }, }, ], - // resolve: { - // bundProjectPage: bundProjectPageResolver, - // bundProjectsFunding: bundProjectsFundingResolver, - // cordisEuProjectPage: euCordisProjectsResolver, - // cordisEuProjectsFunding: cordisEuProjectsFundingResolver, - // }, - // runGuardsAndResolvers: (from, to) => { - // const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; - // return keys.some( - // (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), - // ); - // }, }, { path: 'patents', diff --git a/webapp/src/app/resolvers/bund-projects-funding.resolver.ts b/webapp/src/app/resolvers/bund-projects-funding.resolver.ts index df29c79d..3f501c67 100644 --- a/webapp/src/app/resolvers/bund-projects-funding.resolver.ts +++ b/webapp/src/app/resolvers/bund-projects-funding.resolver.ts @@ -15,7 +15,22 @@ export const bundProjectsFundingResolver: ResolveFn< 'Institution ID is required to resolve BUND projects funding', ); } + const filtersEnabled = route.data['enableFilters'] ?? false; + if (!filtersEnabled) { + return inject(ProjectsService).getInstitutionBundProjectsFundingOverTime( + institutionId, + [], + [], + undefined, + [], + [], + [], + [], + [], + undefined, + ); + } const fundingStartYears = route.queryParamMap.getAll( bundProjectQueryParamKeys.funding_start, ); diff --git a/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts b/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts index 0e60a95b..0ea05f87 100644 --- a/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts +++ b/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts @@ -15,62 +15,90 @@ export const cordisEuProjectsFundingResolver: ResolveFn< 'Institution ID is required to resolve Cordis EU projects funding', ); } + const filtersEnabled = route.data['enableFilters'] ?? false; + if (!filtersEnabled) { + return inject( + ProjectsService, + ).getInstitutionCordisEuProjectsFundingOverTime( + institutionId, + undefined, // authorId (single) - institution view doesn't use this + [], + [], + [], + [], + undefined, + [], + [], + [], + [], + [], + [], + [], + [], + [], + undefined, + ); + } else { + const searchTerm = + route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined; - const searchTerm = - route.queryParamMap.get(euProjectQueryParamKeys.title) ?? undefined; + const fundingStart = route.queryParamMap.getAll( + euProjectQueryParamKeys.funding_start, + ); + const fundingEnd = route.queryParamMap.getAll( + euProjectQueryParamKeys.funding_end, + ); - const fundingStart = route.queryParamMap.getAll( - euProjectQueryParamKeys.funding_start, - ); - const fundingEnd = route.queryParamMap.getAll( - euProjectQueryParamKeys.funding_end, - ); + const filteredTopicIds = route.queryParamMap.getAll( + euProjectQueryParamKeys.topicId, + ); - const filteredTopicIds = route.queryParamMap.getAll( - euProjectQueryParamKeys.topicId, - ); + const projectTypes = route.queryParamMap.getAll( + euProjectQueryParamKeys.projectType, + ); - const projectTypes = route.queryParamMap.getAll( - euProjectQueryParamKeys.projectType, - ); + const organizationIds = route.queryParamMap.getAll( + euProjectQueryParamKeys.institutionId, + ); - const organizationIds = route.queryParamMap.getAll( - euProjectQueryParamKeys.institutionId, - ); + const authorIds = route.queryParamMap + .getAll(euProjectQueryParamKeys.authorId) + .map((id) => id.split('/').pop() || id); - const authorIds = route.queryParamMap - .getAll(euProjectQueryParamKeys.authorId) - .map((id) => id.split('/').pop() || id); + const countries = route.queryParamMap.getAll( + euProjectQueryParamKeys.country, + ); - const countries = route.queryParamMap.getAll(euProjectQueryParamKeys.country); + const frameworkProgrammes = route.queryParamMap.getAll( + euProjectQueryParamKeys.frameworkProgramme, + ); - const frameworkProgrammes = route.queryParamMap.getAll( - euProjectQueryParamKeys.frameworkProgramme, - ); + const fundingSchemes = route.queryParamMap.getAll( + euProjectQueryParamKeys.fundingScheme, + ); - const fundingSchemes = route.queryParamMap.getAll( - euProjectQueryParamKeys.fundingScheme, - ); + const statuses = route.queryParamMap.getAll(euProjectQueryParamKeys.status); - const statuses = route.queryParamMap.getAll(euProjectQueryParamKeys.status); - - return inject(ProjectsService).getInstitutionCordisEuProjectsFundingOverTime( - institutionId, - undefined, // authorId (single) - institution view doesn't use this - authorIds, - organizationIds, - [], // organizationNames - projectTypes as any, - searchTerm, - [], // keywords - institution view doesn't use free-text keywords - [], // topicIds (fuzzy) - institution view doesn't use fuzzy topic search - filteredTopicIds, - fundingStart, - fundingEnd, - countries, - frameworkProgrammes, - fundingSchemes, - statuses, - false, // fuzzy - ); + return inject( + ProjectsService, + ).getInstitutionCordisEuProjectsFundingOverTime( + institutionId, + undefined, // authorId (single) - institution view doesn't use this + authorIds, + organizationIds, + [], // organizationNames + projectTypes as any, + searchTerm, + [], // keywords - institution view doesn't use free-text keywords + [], // topicIds (fuzzy) - institution view doesn't use fuzzy topic search + filteredTopicIds, + fundingStart, + fundingEnd, + countries, + frameworkProgrammes, + fundingSchemes, + statuses, + false, // fuzzy + ); + } }; From d06c1954a50e219a0fc19a5e267bec68b4dc8aa8 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Tue, 4 Aug 2026 20:36:33 +0200 Subject: [PATCH 07/18] feat(person-funding, person-patents, institution-patents, keywords-patents): add sortable column headers and refine inventor/assignee chip styling --- .../institution-patents.component.html | 137 ++++++++++++++++-- .../institution-patents.component.scss | 86 +++++++++-- .../institution-patents.component.ts | 114 +++++++++++---- .../keywords-patents.component.html | 122 ++++++++++++++-- .../keywords-patents.component.scss | 106 +++++++++----- .../keywords-patents.component.ts | 88 ++++++++--- .../person-funding.component.html | 71 +++++++-- .../person-funding.component.scss | 35 +++-- .../person-funding.component.ts | 80 +++++++--- .../person-patents.component.html | 114 +++++++++++++-- .../person-patents.component.scss | 90 ++++++++++-- .../person-patents.component.ts | 95 +++++++++--- 12 files changed, 942 insertions(+), 196 deletions(-) diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.html b/webapp/src/app/modules/institution-patents/institution-patents.component.html index 290cf522..fbb05df2 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.html +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.html @@ -54,11 +54,13 @@ subscriptSizing="dynamic"> + [value]="sortColumn" + (selectionChange)="setSort($event.value)"> Sortieren nach - Datum + Jahr Titel + Quelle + Match-Typ @@ -67,11 +69,41 @@ Patent - Quelle - Jahr + + Quelle + @if (sortColumn === 'source') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + + + Jahr + @if (sortColumn === 'year') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + Erfinder Applicant/Assignee - Match-Typ + + Match-Typ + @if (sortColumn === 'matchType') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + Personen @@ -94,9 +126,86 @@ {{ patent.source }} - {{ patent.publication_year ?? '-' }} - {{ getInventorsPreview(patent) }} - {{ getAssigneesPreview(patent) }} + + @if (patent.publication_year) { + {{ + patent.publication_year + }} + } @else { + - + } + + + @if (patent.inventors && patent.inventors.length) { +
+ @for ( + inventor of patent.inventors.slice(0, 2); + track inventor + ) { + + person + {{ inventor }} + + } + @if (patent.inventors.length > 2) { + + + person + {{ patent.inventors[2] }} + + @if (patent.inventors.length > 3) { + +{{ patent.inventors.length - 3 }} + } + + } +
+ } @else { + - + } + + + @if (patent.assignees && patent.assignees.length) { +
+ @for ( + assignee of patent.assignees.slice(0, 2); + track assignee + ) { + + {{ + isAssigneeLikelyPerson(assignee, patent) + ? 'person' + : 'apartment' + }} + {{ assignee }} + + } + @if (patent.assignees.length > 2) { + + + {{ + isAssigneeLikelyPerson( + patent.assignees[2], + patent + ) + ? 'person' + : 'apartment' + }} + {{ patent.assignees[2] }} + + @if (patent.assignees.length > 3) { + +{{ patent.assignees.length - 3 }} + } + + } +
+ } @else { + - + } + @@ -118,6 +227,10 @@ '/person', author.openalex_author_id, ]" + [appComponentTooltip]="AuthorTooltipComponent" + [tooltipInputs]="{ + authorId: author.openalex_author_id, + }" (click)="$event.stopPropagation()"> {{ author.author_name }}
@@ -197,7 +310,11 @@
  • + [routerLink]="['/person', author.openalex_author_id]" + [appComponentTooltip]="AuthorTooltipComponent" + [tooltipInputs]="{ + authorId: author.openalex_author_id, + }"> {{ author.author_name }}
  • diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.scss b/webapp/src/app/modules/institution-patents/institution-patents.component.scss index 4b3fdb39..c0827596 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.scss +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.scss @@ -66,9 +66,24 @@ app-query-param-paginator { text-align: left; padding: 12px 16px; border-bottom: 1px solid var(--sg-border); - font-size: 13px; - font-weight: 600; + font-size: 12px; + font-weight: 700; color: var(--sg-text-muted); + + &.sortable { + display: table-cell; + cursor: pointer; + -webkit-user-select: none; + user-select: none; + } + + .sort-icon { + vertical-align: middle; + margin-left: 2px; + width: 14px; + height: 14px; + font-size: 14px; + } } tr { @@ -101,13 +116,8 @@ app-query-param-paginator { word-break: break-word; } - .cell-preview { - max-width: 160px; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - color: var(--sg-text-muted); - font-size: 13px; + .patent-people { + max-width: 220px; } .cell-authors { @@ -119,6 +129,64 @@ app-query-param-paginator { } } +.year-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 26px; + padding: 2px 10px; + border-radius: 999px; + border: 1px solid var(--sg-border); + color: var(--sg-text); + font-size: 0.8rem; + font-weight: 600; +} + +.person-chips { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 4px; +} + +.person-chip-row { + display: flex; + flex-direction: row; + align-items: center; + flex-wrap: wrap; + gap: 4px; +} + +.person-chip { + display: inline-flex; + align-items: center; + gap: 4px; + max-width: 100%; + padding: 2px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-soft); + color: var(--sg-text); + font-size: 0.75rem; + line-height: 1.4; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + + mat-icon { + flex-shrink: 0; + width: 14px; + height: 14px; + font-size: 14px; + color: var(--sg-text-soft); + } + + &--more { + color: var(--sg-text-muted); + font-weight: 600; + } +} + .match-badge { display: inline-flex; align-items: center; diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.ts b/webapp/src/app/modules/institution-patents/institution-patents.component.ts index 196200d0..ea75813b 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.ts +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.ts @@ -13,8 +13,11 @@ import { import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { PageEvent } from '@angular/material/paginator'; import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive'; +import { AppAuthorTooltipComponent } from '../../shared/ui/app-author-tooltip/app-author-tooltip.component'; -type SortMode = 'date' | 'title'; +type SortColumn = 'title' | 'year' | 'source' | 'matchType'; +type SortDirection = 'asc' | 'desc'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both'; @@ -28,11 +31,13 @@ type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both'; MatSelectModule, MatIconModule, QueryParamPaginatorComponent, + ComponentTooltipDirective, ], templateUrl: './institution-patents.component.html', styleUrl: './institution-patents.component.scss', }) export class InstitutionPatentsComponent implements OnInit { + readonly AuthorTooltipComponent = AppAuthorTooltipComponent; private route = inject(ActivatedRoute); private router = inject(Router); private patentsApi = inject(PatentsService); @@ -48,7 +53,8 @@ export class InstitutionPatentsComponent implements OnInit { activeFilter: SourceFilter = 'all'; activeMatchType: OrgPatentMatchTypeFilter = 'all'; - sortMode: SortMode = 'date'; + sortColumn: SortColumn = 'year'; + sortDirection: SortDirection = 'desc'; pageIndex = 0; pageSize = 20; @@ -59,7 +65,8 @@ export class InstitutionPatentsComponent implements OnInit { const institutionId = params.get('institutionId') ?? ''; const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); - const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const sortByFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const sortDirFromUrl = this.route.snapshot.queryParamMap.get('sortDir'); const matchTypeFromUrl = this.route.snapshot.queryParamMap.get('matchType'); this.pageIndex = this.parsePageIndexParam( @@ -72,8 +79,11 @@ export class InstitutionPatentsComponent implements OnInit { if (this.isValidFilter(filterFromUrl)) { this.activeFilter = filterFromUrl; } - if (this.isValidSortMode(sortFromUrl)) { - this.sortMode = sortFromUrl; + if (this.isValidSortColumn(sortByFromUrl)) { + this.sortColumn = sortByFromUrl; + } + if (this.isValidSortDirection(sortDirFromUrl)) { + this.sortDirection = sortDirFromUrl; } if (this.isValidMatchType(matchTypeFromUrl)) { this.activeMatchType = matchTypeFromUrl; @@ -101,8 +111,13 @@ export class InstitutionPatentsComponent implements OnInit { this.reloadPatents(); } - setSortMode(sortMode: SortMode): void { - this.sortMode = sortMode; + setSort(column: SortColumn): void { + if (this.sortColumn === column) { + this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc'; + } else { + this.sortColumn = column; + this.sortDirection = column === 'year' ? 'desc' : 'asc'; + } this.filteredPatents = this.sortPatents(this.patents); this.updateQueryParams(); } @@ -168,14 +183,27 @@ export class InstitutionPatentsComponent implements OnInit { } private sortPatents(patents: OrgPatentEntry[]): OrgPatentEntry[] { - if (this.sortMode === 'title') { - return [...patents].sort((a, b) => - (a.title ?? '').localeCompare(b.title ?? '', 'de', { - sensitivity: 'base', - }), - ); - } - return [...patents]; + const direction = this.sortDirection === 'asc' ? 1 : -1; + return [...patents].sort((a, b) => { + switch (this.sortColumn) { + case 'year': { + const yearA = a.publication_date ?? String(a.publication_year ?? ''); + const yearB = b.publication_date ?? String(b.publication_year ?? ''); + return direction * yearA.localeCompare(yearB); + } + case 'source': + return direction * a.source.localeCompare(b.source); + case 'matchType': + return direction * a.match_type.localeCompare(b.match_type); + default: + return ( + direction * + (a.title ?? '').localeCompare(b.title ?? '', 'de', { + sensitivity: 'base', + }) + ); + } + }); } private updateQueryParams(): void { @@ -183,7 +211,8 @@ export class InstitutionPatentsComponent implements OnInit { relativeTo: this.route, queryParams: { filter: this.activeFilter, - sortBy: this.sortMode, + sortBy: this.sortColumn, + sortDir: this.sortDirection, matchType: this.activeMatchType, page: this.pageIndex, size: this.pageSize, @@ -207,8 +236,17 @@ export class InstitutionPatentsComponent implements OnInit { return value === 'all' || value === 'EPO' || value === 'USPTO'; } - private isValidSortMode(value: string | null): value is SortMode { - return value === 'date' || value === 'title'; + private isValidSortColumn(value: string | null): value is SortColumn { + return ( + value === 'title' || + value === 'year' || + value === 'source' || + value === 'matchType' + ); + } + + private isValidSortDirection(value: string | null): value is SortDirection { + return value === 'asc' || value === 'desc'; } private isValidMatchType( @@ -287,18 +325,40 @@ export class InstitutionPatentsComponent implements OnInit { } } - getInventorsPreview(patent: OrgPatentEntry): string { - if (!patent.inventors?.length) { - return '-'; - } - return patent.inventors.slice(0, 2).join(', '); + private static readonly ORG_SUFFIX_PATTERN = + /\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i; + private static readonly PERSON_SUFFIX_PATTERN = + /\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i; + + private normalizeNameForComparison(name: string): string { + return name + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .replace(/[.,]/g, '') + .toUpperCase() + .split(/\s+/) + .filter(Boolean) + .sort() + .join(' '); } - getAssigneesPreview(patent: OrgPatentEntry): string { - if (!patent.assignees?.length) { - return '-'; + isAssigneeLikelyPerson(assignee: string, patent: OrgPatentEntry): boolean { + if (InstitutionPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) { + return false; } - return patent.assignees.slice(0, 2).join(', '); + + const normalizedAssignee = this.normalizeNameForComparison( + assignee.replace(InstitutionPatentsComponent.PERSON_SUFFIX_PATTERN, ''), + ); + const matchesInventor = (patent.inventors ?? []).some( + (inventor) => + this.normalizeNameForComparison(inventor) === normalizedAssignee, + ); + if (matchesInventor) { + return true; + } + + return InstitutionPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee); } getMatchedAuthorsPreview(patent: OrgPatentEntry): string { diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html index 20d2eef7..838a42ad 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -31,11 +31,12 @@ subscriptSizing="dynamic"> + [value]="sortColumn()" + (selectionChange)="setSort($event.value)"> Sortieren nach - Datum + Jahr Titel + Quelle @@ -44,8 +45,32 @@ Patent - Quelle - Jahr + + Quelle + @if (sortColumn() === 'source') { + {{ + sortDirection() === 'asc' + ? 'arrow_upward' + : 'arrow_downward' + }} + } + + + Jahr + @if (sortColumn() === 'year') { + {{ + sortDirection() === 'asc' + ? 'arrow_upward' + : 'arrow_downward' + }} + } + Erfinder Anmelder @@ -66,16 +91,85 @@ {{ item.patent.source }} - {{ item.patent.publication_year ?? '-' }} - - {{ getInventorsLabel(item.patent) }} + + @if (item.patent.publication_year) { + {{ + item.patent.publication_year + }} + } @else { + - + } - - {{ getAssigneesLabel(item.patent) }} + + @if (item.patent.inventors && item.patent.inventors.length) { +
    + @for ( + inventor of item.patent.inventors.slice(0, 2); + track inventor + ) { + + person + {{ inventor }} + + } + @if (item.patent.inventors.length > 2) { + + + person + {{ item.patent.inventors[2] }} + + @if (item.patent.inventors.length > 3) { + +{{ item.patent.inventors.length - 3 }} + } + + } +
    + } @else { + - + } + + + @if (item.patent.assignees && item.patent.assignees.length) { +
    + @for ( + assignee of item.patent.assignees.slice(0, 2); + track assignee + ) { + + {{ + isAssigneeLikelyPerson(assignee, item.patent) + ? 'person' + : 'apartment' + }} + {{ assignee }} + + } + @if (item.patent.assignees.length > 2) { + + + {{ + isAssigneeLikelyPerson( + item.patent.assignees[2], + item.patent + ) + ? 'person' + : 'apartment' + }} + {{ item.patent.assignees[2] }} + + @if (item.patent.assignees.length > 3) { + +{{ item.patent.assignees.length - 3 }} + } + + } +
    + } @else { + - + } } diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss index a8ddbb74..75c648eb 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss @@ -97,9 +97,24 @@ app-query-param-paginator { text-align: left; padding: 12px 16px; border-bottom: 1px solid var(--sg-border); - font-size: 13px; - font-weight: 600; + font-size: 12px; + font-weight: 700; color: var(--sg-text-muted); + + &.sortable { + display: table-cell; + cursor: pointer; + -webkit-user-select: none; + user-select: none; + } + + .sort-icon { + vertical-align: middle; + margin-left: 2px; + width: 14px; + height: 14px; + font-size: 14px; + } } tr { @@ -133,41 +148,66 @@ app-query-param-paginator { .patent-people { max-width: 220px; - color: var(--sg-text-muted); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; } } - - th { - text-align: left; - padding: 10px 12px; - border-bottom: 2px solid var(--sg-border); - color: var(--sg-text); - } - - tr { - cursor: pointer; - color: var(--sg-text); - - &:hover { - background: var(--sg-surface-soft); - } - - &.selected { - background: var(--sg-surface-muted); - } - } - - td { - padding: 10px 12px; - border-bottom: 1px solid var(--sg-border); - } } -.patent-title { - font-weight: 500; +.year-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 26px; + padding: 2px 10px; + border-radius: 999px; + border: 1px solid var(--sg-border); + color: var(--sg-text); + font-size: 0.8rem; + font-weight: 600; +} + +.person-chips { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 4px; +} + +.person-chip-row { + display: flex; + flex-direction: row; + align-items: center; + flex-wrap: wrap; + gap: 4px; +} + +.person-chip { + display: inline-flex; + align-items: center; + gap: 4px; + max-width: 100%; + padding: 2px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-soft); + color: var(--sg-text); + font-size: 0.75rem; + line-height: 1.4; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + + mat-icon { + flex-shrink: 0; + width: 14px; + height: 14px; + font-size: 14px; + color: var(--sg-text-soft); + } + + &--more { + color: var(--sg-text-muted); + font-weight: 600; + } } .source-badge { diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts index 4a636af1..4674b509 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts @@ -16,7 +16,8 @@ import { import { KeywordPatentMappingStatus } from '../../../api'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; -type SortMode = 'date' | 'title'; +type SortColumn = 'title' | 'year' | 'source'; +type SortDirection = 'asc' | 'desc'; @Component({ selector: 'app-keywords-patents', @@ -44,7 +45,8 @@ export class KeywordsPatentsComponent { readonly reload = output(); activeFilter = signal('all'); - sortMode = signal('date'); + sortColumn = signal('year'); + sortDirection = signal('desc'); selectedMatch = signal(null); readonly pageIndex = computed(() => { @@ -86,12 +88,53 @@ export class KeywordsPatentsComponent { this.resetPage(); } - setSortMode(sortMode: SortMode): void { - this.sortMode.set(sortMode); + setSort(column: SortColumn): void { + if (this.sortColumn() === column) { + this.sortDirection.set(this.sortDirection() === 'asc' ? 'desc' : 'asc'); + } else { + this.sortColumn.set(column); + this.sortDirection.set(column === 'year' ? 'desc' : 'asc'); + } this.selectedMatch.set(null); this.resetPage(); } + isAssigneeLikelyPerson(assignee: string, patent: PatentEntry): boolean { + if (KeywordsPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) { + return false; + } + + const normalizedAssignee = this.normalizeNameForComparison( + assignee.replace(KeywordsPatentsComponent.PERSON_SUFFIX_PATTERN, ''), + ); + const matchesInventor = (patent.inventors ?? []).some( + (inventor) => + this.normalizeNameForComparison(inventor) === normalizedAssignee, + ); + if (matchesInventor) { + return true; + } + + return KeywordsPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee); + } + + private static readonly ORG_SUFFIX_PATTERN = + /\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i; + private static readonly PERSON_SUFFIX_PATTERN = + /\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i; + + private normalizeNameForComparison(name: string): string { + return name + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .replace(/[.,]/g, '') + .toUpperCase() + .split(/\s+/) + .filter(Boolean) + .sort() + .join(' '); + } + onPatentPageChange(_event: PageEvent): void { this.selectedMatch.set(null); } @@ -124,14 +167,6 @@ export class KeywordsPatentsComponent { .length; } - getInventorsLabel(patent: PatentEntry): string { - return patent.inventors?.length ? patent.inventors.join(', ') : '-'; - } - - getAssigneesLabel(patent: PatentEntry): string { - return patent.assignees?.length ? patent.assignees.join(', ') : '-'; - } - formatDate(date: string | null | undefined): string { return formatPatentDate(date); } @@ -163,16 +198,29 @@ export class KeywordsPatentsComponent { } private sortMatches(items: KeywordPatentMatch[]): KeywordPatentMatch[] { - const mode = this.sortMode(); + const column = this.sortColumn(); + const direction = this.sortDirection() === 'asc' ? 1 : -1; return [...items].sort((a, b) => { - if (mode === 'date') { - return (b.patent.publication_date ?? '').localeCompare( - a.patent.publication_date ?? '', - ); + switch (column) { + case 'year': { + const yearA = + a.patent.publication_date ?? + String(a.patent.publication_year ?? ''); + const yearB = + b.patent.publication_date ?? + String(b.patent.publication_year ?? ''); + return direction * yearA.localeCompare(yearB); + } + case 'source': + return direction * a.patent.source.localeCompare(b.patent.source); + default: + return ( + direction * + (a.patent.title ?? '').localeCompare(b.patent.title ?? '', 'de', { + sensitivity: 'base', + }) + ); } - return (a.patent.title ?? '').localeCompare(b.patent.title ?? '', 'de', { - sensitivity: 'base', - }); }); } } diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index 85a34c96..70bec121 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -33,22 +33,75 @@ subscriptSizing="dynamic"> + [value]="sortColumn" + (selectionChange)="setSort($event.value)"> Sortieren nach - Name - Top Förderer + Förderer + Publikationen + Erstautor + Mitautor + Letztautor - - - - - + + + + + diff --git a/webapp/src/app/modules/person-funding/person-funding.component.scss b/webapp/src/app/modules/person-funding/person-funding.component.scss index 282f90e9..079c6a46 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.scss +++ b/webapp/src/app/modules/person-funding/person-funding.component.scss @@ -45,9 +45,24 @@ app-query-param-paginator { text-align: left; padding: 12px 16px; border-bottom: 1px solid var(--sg-border); - font-size: 13px; - font-weight: 600; + font-size: 12px; + font-weight: 700; color: var(--sg-text-muted); + + &.sortable { + display: table-cell; + cursor: pointer; + -webkit-user-select: none; + user-select: none; + } + + .sort-icon { + vertical-align: middle; + margin-left: 2px; + width: 14px; + height: 14px; + font-size: 14px; + } } tr { @@ -86,8 +101,11 @@ app-query-param-paginator { display: inline-flex; align-items: center; justify-content: center; - min-width: 20px; - font-size: 13px; + min-width: 26px; + padding: 2px 10px; + border-radius: 999px; + border: 1px solid var(--sg-border); + font-size: 0.8rem; font-weight: 700; &--first { @@ -157,9 +175,6 @@ app-query-param-paginator { } &.stat-first { - background: var(--sg-success-soft); - border-color: var(--sg-success); - .stat-label, .stat-value { color: var(--sg-success); @@ -167,9 +182,6 @@ app-query-param-paginator { } &.stat-middle { - background: var(--sg-warning-soft); - border-color: var(--sg-warning); - .stat-label, .stat-value { color: var(--sg-warning); @@ -177,9 +189,6 @@ app-query-param-paginator { } &.stat-last { - background: var(--sg-error-soft); - border-color: var(--sg-error); - .stat-label, .stat-value { color: var(--sg-error); diff --git a/webapp/src/app/modules/person-funding/person-funding.component.ts b/webapp/src/app/modules/person-funding/person-funding.component.ts index b6e5c211..7a5bac13 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -10,7 +10,8 @@ import { FundingService } from '../../api'; import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; -type SortMode = 'name' | 'top'; +type SortColumn = 'name' | 'publications' | 'first' | 'middle' | 'last'; +type SortDirection = 'asc' | 'desc'; type AuthorPosition = 'first' | 'middle' | 'last' | 'unknown'; type FundingPublicationDetail = { @@ -53,7 +54,8 @@ export class PersonFundingComponent implements OnInit { publicationPageIndex = 0; publicationPageSize = 10; activeFilter: 'all' | 'first' | 'middle' | 'last' = 'all'; - sortMode: SortMode = 'name'; + sortColumn: SortColumn = 'name'; + sortDirection: SortDirection = 'asc'; loading = true; error = false; @@ -61,7 +63,8 @@ export class PersonFundingComponent implements OnInit { this.route.parent?.paramMap.subscribe((params) => { const authorId = params.get('id') ?? ''; const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); - const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const sortByFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const sortDirFromUrl = this.route.snapshot.queryParamMap.get('sortDir'); this.initialSelectedFunderKey = this.route.snapshot.queryParamMap.get('funder'); this.initialFunderPageIndex = this.parsePageIndexParam( @@ -79,8 +82,11 @@ export class PersonFundingComponent implements OnInit { if (this.isValidFilter(filterFromUrl)) { this.activeFilter = filterFromUrl; } - if (this.isValidSortMode(sortFromUrl)) { - this.sortMode = sortFromUrl; + if (this.isValidSortColumn(sortByFromUrl)) { + this.sortColumn = sortByFromUrl; + } + if (this.isValidSortDirection(sortDirFromUrl)) { + this.sortDirection = sortDirFromUrl; } if (authorId) { @@ -118,8 +124,13 @@ export class PersonFundingComponent implements OnInit { this.updateQueryParams(); } - setSortMode(sortMode: SortMode): void { - this.sortMode = sortMode; + setSort(column: SortColumn): void { + if (this.sortColumn === column) { + this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc'; + } else { + this.sortColumn = column; + this.sortDirection = column === 'name' ? 'asc' : 'desc'; + } this.applyFilter(); this.updateQueryParams(); } @@ -185,7 +196,8 @@ export class PersonFundingComponent implements OnInit { relativeTo: this.route, queryParams: { filter: this.activeFilter, - sortBy: this.sortMode, + sortBy: this.sortColumn, + sortDir: this.sortDirection, funder: this.selectedFunder ? this.getFunderKey(this.selectedFunder) : null, @@ -214,8 +226,18 @@ export class PersonFundingComponent implements OnInit { ); } - private isValidSortMode(value: string | null): value is SortMode { - return value === 'name' || value === 'top'; + private isValidSortColumn(value: string | null): value is SortColumn { + return ( + value === 'name' || + value === 'publications' || + value === 'first' || + value === 'middle' || + value === 'last' + ); + } + + private isValidSortDirection(value: string | null): value is SortDirection { + return value === 'asc' || value === 'desc'; } getPublicationCount(funder: any): number { @@ -294,24 +316,44 @@ export class PersonFundingComponent implements OnInit { } private sortFunders(funders: any[]): any[] { + const direction = this.sortDirection === 'asc' ? 1 : -1; const sortedFunders = [...funders]; return sortedFunders.sort((first, second) => { - if (this.sortMode === 'top') { - const publicationCountDifference = - this.getPublicationCount(second) - this.getPublicationCount(first); - if (publicationCountDifference !== 0) { - return publicationCountDifference; + if (this.sortColumn !== 'name') { + const valueDifference = + direction * + (this.getSortColumnValue(first) - this.getSortColumnValue(second)); + if (valueDifference !== 0) { + return valueDifference; } } - return this.getSortableFunderName(first).localeCompare( - this.getSortableFunderName(second), - 'de', - { sensitivity: 'base' }, + return ( + direction * + this.getSortableFunderName(first).localeCompare( + this.getSortableFunderName(second), + 'de', + { sensitivity: 'base' }, + ) ); }); } + private getSortColumnValue(funder: any): number { + switch (this.sortColumn) { + case 'publications': + return this.getPublicationCount(funder); + case 'first': + return funder.author_position_count?.first ?? 0; + case 'middle': + return funder.author_position_count?.middle ?? 0; + case 'last': + return funder.author_position_count?.last ?? 0; + default: + return 0; + } + } + private getSortableFunderName(funder: any): string { return funder.funder_name ?? ''; } diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html index 398004ef..b32185a7 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -31,11 +31,12 @@ subscriptSizing="dynamic"> + [value]="sortColumn" + (selectionChange)="setSort($event.value)"> Sortieren nach - Datum + Jahr Titel + Quelle @@ -44,8 +45,28 @@ - - + + @@ -69,12 +90,85 @@ {{ patent.source }} - - - + } diff --git a/webapp/src/app/modules/person-patents/person-patents.component.scss b/webapp/src/app/modules/person-patents/person-patents.component.scss index 6bed2a07..9c9c1410 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.scss +++ b/webapp/src/app/modules/person-patents/person-patents.component.scss @@ -50,9 +50,24 @@ app-query-param-paginator { text-align: left; padding: 12px 16px; border-bottom: 1px solid var(--sg-border); - font-size: 13px; - font-weight: 600; + font-size: 12px; + font-weight: 700; color: var(--sg-text-muted); + + &.sortable { + display: table-cell; + cursor: pointer; + -webkit-user-select: none; + user-select: none; + } + + .sort-icon { + vertical-align: middle; + margin-left: 2px; + width: 14px; + height: 14px; + font-size: 14px; + } } tr { @@ -80,22 +95,75 @@ app-query-param-paginator { .patent-title { color: var(--sg-text); font-weight: 600; - max-width: 400px; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; + max-width: 320px; + white-space: normal; + word-break: break-word; } .patent-people { - max-width: 220px; - color: var(--sg-text-muted); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; + max-width: 260px; } } } +.year-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 26px; + padding: 2px 10px; + border-radius: 999px; + border: 1px solid var(--sg-border); + color: var(--sg-text); + font-size: 0.8rem; + font-weight: 600; +} + +.person-chips { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 4px; +} + +.person-chip-row { + display: flex; + flex-direction: row; + align-items: center; + flex-wrap: wrap; + gap: 4px; +} + +.person-chip { + display: inline-flex; + align-items: center; + gap: 4px; + max-width: 100%; + padding: 2px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-soft); + color: var(--sg-text); + font-size: 0.75rem; + line-height: 1.4; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + + mat-icon { + flex-shrink: 0; + width: 14px; + height: 14px; + font-size: 14px; + color: var(--sg-text-soft); + } + + &--more { + color: var(--sg-text-muted); + font-weight: 600; + } +} + .match-badges { display: flex; flex-wrap: wrap; diff --git a/webapp/src/app/modules/person-patents/person-patents.component.ts b/webapp/src/app/modules/person-patents/person-patents.component.ts index ece9c4dd..508f41ed 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -16,7 +16,8 @@ import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { PageEvent } from '@angular/material/paginator'; import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; -type SortMode = 'date' | 'title'; +type SortColumn = 'title' | 'year' | 'source'; +type SortDirection = 'asc' | 'desc'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; @Component({ @@ -46,14 +47,16 @@ export class PersonPatentsComponent { error = false; activeFilter: SourceFilter = 'all'; - sortMode: SortMode = 'date'; + sortColumn: SortColumn = 'year'; + sortDirection: SortDirection = 'desc'; pageIndex = 0; pageSize = 10; constructor() { const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); - const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const sortByFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const sortDirFromUrl = this.route.snapshot.queryParamMap.get('sortDir'); this.pageIndex = this.parsePageIndexParam( this.route.snapshot.queryParamMap.get('page'), ); @@ -64,8 +67,11 @@ export class PersonPatentsComponent { if (this.isValidFilter(filterFromUrl)) { this.activeFilter = filterFromUrl; } - if (this.isValidSortMode(sortFromUrl)) { - this.sortMode = sortFromUrl; + if (this.isValidSortColumn(sortByFromUrl)) { + this.sortColumn = sortByFromUrl; + } + if (this.isValidSortDirection(sortDirFromUrl)) { + this.sortDirection = sortDirFromUrl; } this.route.parent?.data @@ -113,8 +119,13 @@ export class PersonPatentsComponent { this.pageSize = event.pageSize; } - setSortMode(sortMode: SortMode): void { - this.sortMode = sortMode; + setSort(column: SortColumn): void { + if (this.sortColumn === column) { + this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc'; + } else { + this.sortColumn = column; + this.sortDirection = column === 'year' ? 'desc' : 'asc'; + } this.applyFilter(); this.updateQueryParams(); } @@ -140,15 +151,24 @@ export class PersonPatentsComponent { } private sortPatents(patents: PatentEntry[]): PatentEntry[] { + const direction = this.sortDirection === 'asc' ? 1 : -1; return [...patents].sort((a, b) => { - if (this.sortMode === 'date') { - return (b.publication_date ?? '').localeCompare( - a.publication_date ?? '', - ); + switch (this.sortColumn) { + case 'year': { + const yearA = a.publication_date ?? String(a.publication_year ?? ''); + const yearB = b.publication_date ?? String(b.publication_year ?? ''); + return direction * yearA.localeCompare(yearB); + } + case 'source': + return direction * a.source.localeCompare(b.source); + default: + return ( + direction * + (a.title ?? '').localeCompare(b.title ?? '', 'de', { + sensitivity: 'base', + }) + ); } - return (a.title ?? '').localeCompare(b.title ?? '', 'de', { - sensitivity: 'base', - }); }); } @@ -157,7 +177,8 @@ export class PersonPatentsComponent { relativeTo: this.route, queryParams: { filter: this.activeFilter, - sortBy: this.sortMode, + sortBy: this.sortColumn, + sortDir: this.sortDirection, page: this.pageIndex, size: this.pageSize, }, @@ -180,8 +201,12 @@ export class PersonPatentsComponent { return value === 'all' || value === 'EPO' || value === 'USPTO'; } - private isValidSortMode(value: string | null): value is SortMode { - return value === 'date' || value === 'title'; + private isValidSortColumn(value: string | null): value is SortColumn { + return value === 'title' || value === 'year' || value === 'source'; + } + + private isValidSortDirection(value: string | null): value is SortDirection { + return value === 'asc' || value === 'desc'; } getPagedPatents(): PatentEntry[] { @@ -189,12 +214,40 @@ export class PersonPatentsComponent { return this.filteredPatents.slice(start, start + this.pageSize); } - getInventorsLabel(patent: PatentEntry): string { - return patent.inventors?.length ? patent.inventors.join(', ') : '-'; + private static readonly ORG_SUFFIX_PATTERN = + /\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i; + private static readonly PERSON_SUFFIX_PATTERN = + /\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i; + + private normalizeNameForComparison(name: string): string { + return name + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .replace(/[.,]/g, '') + .toUpperCase() + .split(/\s+/) + .filter(Boolean) + .sort() + .join(' '); } - getAssigneesLabel(patent: PatentEntry): string { - return patent.assignees?.length ? patent.assignees.join(', ') : '-'; + isAssigneeLikelyPerson(assignee: string, patent: PatentEntry): boolean { + if (PersonPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) { + return false; + } + + const normalizedAssignee = this.normalizeNameForComparison( + assignee.replace(PersonPatentsComponent.PERSON_SUFFIX_PATTERN, ''), + ); + const matchesInventor = (patent.inventors ?? []).some( + (inventor) => + this.normalizeNameForComparison(inventor) === normalizedAssignee, + ); + if (matchesInventor) { + return true; + } + + return PersonPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee); } formatDate(date: string | null | undefined): string { From 71b075b36535527a7bb319a1687dc42347bcbbf2 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 23:25:37 +0200 Subject: [PATCH 08/18] Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis --- .../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html | 1 + .../app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html index fa54da5b..88075208 100644 --- a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html +++ b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.html @@ -4,6 +4,7 @@ mat-tab-link [routerLink]="link.path" [queryParams]="link.queryParams" + [queryParamsHandling]="link.queryParamsHandling" routerLinkActive #rla="routerLinkActive" [active]="rla.isActive" diff --git a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts index 3f87669d..d62cd205 100644 --- a/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts +++ b/webapp/src/app/shared/ui/link-tab-nav-bar/link-tab-nav-bar.component.ts @@ -14,6 +14,7 @@ export type LinkTabNavBarItem = { icon?: string; description?: string; queryParams?: Record; + queryParamsHandling?: 'merge' | 'preserve' | 'replace'; disabled?: boolean; }; From ae7d1a54cb5b37b38b370755b9395c69611ca95c Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 23:25:59 +0200 Subject: [PATCH 09/18] fixed EU matching bug --- .../projects/eu_cordis_projects_client.py | 66 ------------------- .../inse/projects/projects_search_client.py | 15 +++-- 2 files changed, 8 insertions(+), 73 deletions(-) diff --git a/service/src/main/inse/projects/eu_cordis_projects_client.py b/service/src/main/inse/projects/eu_cordis_projects_client.py index 8f0af70f..731cd699 100644 --- a/service/src/main/inse/projects/eu_cordis_projects_client.py +++ b/service/src/main/inse/projects/eu_cordis_projects_client.py @@ -1133,10 +1133,6 @@ async def get_eu_cordis_projects_funding_data( "track_total_hits": False, "_source": ["id", "startDate", "endDate", "ecMaxContribution"], "query": query, - # "id" is unique per project and used elsewhere as a term-filter - # field, so it's mapped as keyword - safe + deterministic sort - # key for search_after pagination across an arbitrarily large - # result set. "sort": [{"id": {"order": "asc", "unmapped_type": "keyword"}}], } if search_after is not None: @@ -1256,68 +1252,6 @@ async def get_openalex_author_ids_by_dois( return result -async def get_openalex_authors_for_cordis_project_ids( - project_ids: list[str], -) -> dict[str, AuthorPage]: - """Returns a mapping of project_id -> AuthorPage for a batch of projects.""" - if not project_ids: - return {} - - query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} - response = await elasticsearch.search( - query=query, - index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, - cluster=ESCluster.INSE, - source=["projectID", "doi","qaProcessedDoi"], - size=10000, - ) - dois_by_project: dict[str, set[str]] = {} - for hit in response.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - pid = source.get("projectID") - doi = source.get("doi") - qa_processed_doi = source.get("qaProcessedDoi") - if pid: - dois_by_project.setdefault(pid, set()) - if doi: - dois_by_project[pid].add(doi) - elif qa_processed_doi: - dois_by_project[pid].add(qa_processed_doi) - - all_dois = list({doi for dois in dois_by_project.values() for doi in dois}) - - # single ES call for the whole batch, keyed by raw DOI - author_ids_by_doi = await get_openalex_author_ids_by_dois(dois=all_dois) - - # aggregate per project, dedupe author_ids within a project - author_ids_by_project: dict[str, list[str]] = {} - for pid, dois in dois_by_project.items(): - project_author_ids: set[str] = set() - for doi in dois: - project_author_ids.update(author_ids_by_doi.get(doi, [])) - author_ids_by_project[pid] = list(project_author_ids) - - # single ES call to fetch all Author objects across every project - all_author_ids = list({aid for ids in author_ids_by_project.values() for aid in ids}) - - author_page = await get_authors_by_ids(author_ids=all_author_ids) - authors_by_id = {author.id: author for author in author_page.elements} - - # split the fetched authors back out per project - result: dict[str, AuthorPage] = {} - for pid in project_ids: - ids_for_project = author_ids_by_project.get(pid, []) - authors_for_project = [ - authors_by_id[aid] for aid in ids_for_project if aid in authors_by_id - ] - result[pid] = AuthorPage( - elements=authors_for_project, - total=len(authors_for_project), - page=0, - size=len(authors_for_project), - ) - - return result async def get_openalex_authors_for_projects_ids( project_ids_by_type: dict[EuCordisProjectType, list[str]], diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 3b80b959..f3b2f1e2 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -195,7 +195,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]): _type_: The retrieved publications. """ - query_dois = list({ + query_dois = set({ variant for doi in dois for variant in ( @@ -211,8 +211,8 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]): { "bool": { "should": [ - {"terms": {"doi": query_dois}}, - {"terms": {"qaProcessedDoi": query_dois}}, + {"terms": {"doi": list(query_dois)}}, + {"terms": {"qaProcessedDoi": list(query_dois)}}, ], "minimum_should_match": 1, } @@ -223,6 +223,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]): response = await elasticsearch.search( query=query, + size=10000, index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, cluster=ESCluster.INSE, ) @@ -264,7 +265,7 @@ async def get_dfg_publications_by_dois(dois: list[str]): _type_: The retrieved publications. """ - query_dois = list({ + query_dois = set({ variant for doi in dois for variant in ( @@ -281,7 +282,7 @@ async def get_dfg_publications_by_dois(dois: list[str]): "query": { "terms": { "publications.doi": - query_dois + list(query_dois) } } } @@ -291,7 +292,7 @@ async def get_dfg_publications_by_dois(dois: list[str]): } response = await elasticsearch.search( - size=1000, + size=10000, query=query, index=ESIndex.DFG_PROJECTS, cluster=ESCluster.INSE, @@ -318,7 +319,7 @@ async def get_dfg_project_ids_by_names(names: list[str]) -> list[str]: response = await elasticsearch.search( source=["projects.project_id"], - size=1000, + size=10000, query=query, index=ESIndex.DFG_PERSONS, cluster=ESCluster.INSE, From 57f221868d43bcdce7067b0aad4eb2326c6c5c6a Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 23:26:24 +0200 Subject: [PATCH 10/18] robust handling of wrong query params added --- .../app/resolvers/dfg-projects.resolver.ts | 53 ++++++++++++++++--- 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/resolvers/dfg-projects.resolver.ts b/webapp/src/app/resolvers/dfg-projects.resolver.ts index 1391bd49..365a4214 100644 --- a/webapp/src/app/resolvers/dfg-projects.resolver.ts +++ b/webapp/src/app/resolvers/dfg-projects.resolver.ts @@ -1,5 +1,6 @@ import { inject } from '@angular/core'; import { ResolveFn } from '@angular/router'; +import { of } from 'rxjs'; import { DfgProjectPage, ProjectsService } from '../api'; export const dfgProjectQueryParamKeys = { @@ -24,6 +25,34 @@ export const RESOLVING_PROJECT_PAGE_FOR = { KEYWORDS_SEARCH: 'KEYWORDS_SEARCH', } as const; +// Empty page returned whenever a required numeric param fails to parse. +const EMPTY_DFG_PROJECT_PAGE: DfgProjectPage = { + page: 0, + size: 0, + total: 0, + elements: [], +} as DfgProjectPage; + +function toNumberOrNull(value: unknown): number | null { + if (value === undefined || value === null || value === '') { + return null; + } + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : null; +} + +function toNumberArrayOrNull(values: string[]): number[] | null { + const result: number[] = []; + for (const value of values) { + const parsed = toNumberOrNull(value); + if (parsed === null) { + return null; + } + result.push(parsed); + } + return result; +} + export const dfgProjectsResolver: ResolveFn = ( route, state, @@ -40,9 +69,12 @@ export const dfgProjectsResolver: ResolveFn = ( ); const page = - Number(route.queryParamMap.get(dfgProjectQueryParamKeys.page)) || 0; + toNumberOrNull(route.queryParamMap.get(dfgProjectQueryParamKeys.page)) ?? 0; + const size = - Number(route.queryParamMap.get(dfgProjectQueryParamKeys.size)) || 10; + toNumberOrNull(route.queryParamMap.get(dfgProjectQueryParamKeys.size)) ?? + 10; + const searchTerm = route.queryParamMap.get(dfgProjectQueryParamKeys.title) ?? undefined; const sortBy = @@ -59,12 +91,16 @@ export const dfgProjectsResolver: ResolveFn = ( const filteredTopicIds = route.queryParamMap.getAll( dfgProjectQueryParamKeys.topicId, ); - const institutionIds = route.queryParamMap - .getAll(dfgProjectQueryParamKeys.institutionId) - .map((id) => Number(id)); - const authorIds = route.queryParamMap - .getAll(dfgProjectQueryParamKeys.authorId) - .map((id) => Number(id)); + + const institutionIds = toNumberArrayOrNull( + route.queryParamMap.getAll(dfgProjectQueryParamKeys.institutionId), + ); + const authorIds = toNumberArrayOrNull( + route.queryParamMap.getAll(dfgProjectQueryParamKeys.authorId), + ); + if (institutionIds === null || authorIds === null) { + return of(EMPTY_DFG_PROJECT_PAGE); + } if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) { const rawAuthorId = route.parent?.parent?.params['id']; @@ -108,6 +144,7 @@ export const dfgProjectsResolver: ResolveFn = ( ); } else if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.INSTITUTION) { const oaInstitutionId = route.parent?.parent?.params['institutionId']; + console.log( 'Resolving project page for institution', oaInstitutionId, From e9fdf7d538bfc997dffe1dd8804fa65f647e4742 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 4 Aug 2026 23:28:28 +0200 Subject: [PATCH 11/18] replaced projects navs with generic navbar --- .../institution-projects.component.html | 23 ++------ .../institution-projects.component.ts | 27 +++++++++- .../projects-results.component.html | 21 ++------ .../projects-results.component.ts | 53 +++++++++++-------- .../person-projects.component.html | 21 ++------ .../person-projects.component.ts | 40 +++++++------- 6 files changed, 89 insertions(+), 96 deletions(-) diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.html b/webapp/src/app/modules/institution-projects/institution-projects.component.html index b5e22762..d6c902db 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.html +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.html @@ -58,24 +58,11 @@
    - + @if (resultTabPanel) { + + } diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.ts b/webapp/src/app/modules/institution-projects/institution-projects.component.ts index ddad7159..fa7061ee 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.ts +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.ts @@ -28,7 +28,10 @@ import { MatIconModule } from '@angular/material/icon'; import { MatButtonModule } from '@angular/material/button'; import { InstitutionProjectsFundingGraphComponent } from '../institution-projects-funding-graph/institution-projects-funding-graph.component'; import { AppInfoCardComponent } from '../../shared/ui/app-info-card/app-info-card.component'; - +import { + LinkTabNavBarComponent, + LinkTabNavBarItem, +} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; type BundProjectRow = { id: string; topic: string; @@ -61,6 +64,7 @@ type EuProjectRow = { MatButtonModule, InstitutionProjectsFundingGraphComponent, AppInfoCardComponent, + LinkTabNavBarComponent, RouterModule, ], templateUrl: './institution-projects.component.html', @@ -124,6 +128,27 @@ export class InstitutionProjectsComponent implements OnInit { label: 'BUND-Projekte', }, ]; + + _links = computed(() => { + const links: LinkTabNavBarItem[] = [ + { + label: 'DFG-Projekte', + path: 'dfg', + disabled: false, + }, + { + label: 'EU-Projekte', + path: 'eu', + disabled: false, + }, + { + label: 'BUND-Projekte', + path: 'bund', + disabled: false, + }, + ]; + return links; + }); constructor( private readonly activatedRoute: ActivatedRoute, private readonly router: Router, 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 4ff6ee31..2270f628 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 @@ -4,24 +4,9 @@

    Übersicht der durchgeführten Projekte.

    - + @if (resultTabPanel) { + + } 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 224b934f..9adbcbc6 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 @@ -6,16 +6,13 @@ import { MatTabsModule } from '@angular/material/tabs'; import { OnInit, computed } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { toSignal } from '@angular/core/rxjs-interop'; - +import { + LinkTabNavBarComponent, + LinkTabNavBarItem, +} from '../../../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; @Component({ selector: 'app-projects-results', - imports: [ - MatCardModule, - MatTabsModule, - RouterLink, - RouterLinkActive, - RouterOutlet, - ], + imports: [MatCardModule, MatTabsModule, RouterOutlet, LinkTabNavBarComponent], templateUrl: './projects-results.component.html', styleUrl: './projects-results.component.scss', }) @@ -32,18 +29,30 @@ export class KeywordsToProjectsResultsComponent { () => this.queryParamMap().get('fuzzy') === 'true', ); - readonly childRoutes = [ - { - path: 'dfg', - label: 'DFG-Projekte', - }, - { - path: 'eu', - label: 'EU-Projekte', - }, - { - path: 'bund', - label: 'BUND-Projekte', - }, - ]; + _links = computed(() => { + const links: LinkTabNavBarItem[] = [ + { + label: 'DFG-Projekte', + path: 'dfg', + queryParams: { authorId: null, institutionId: null, agency: null }, + queryParamsHandling: 'merge', + disabled: false, + }, + { + label: 'EU-Projekte', + path: 'eu', + queryParams: { authorId: null, institutionId: null, agency: null }, + queryParamsHandling: 'merge', + disabled: false, + }, + { + label: 'BUND-Projekte', + path: 'bund', + queryParams: { authorId: null, institutionId: null, agency: null }, + queryParamsHandling: 'merge', + disabled: false, + }, + ]; + return links; + }); } 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 958f8daa..16b344e7 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.html +++ b/webapp/src/app/modules/person-projects/person-projects.component.html @@ -1,22 +1,7 @@
    - + @if (resultTabPanel) { + + } 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 359a9d9c..519b28af 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -1,31 +1,33 @@ -import { Component } from '@angular/core'; +import { Component, computed } from '@angular/core'; import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'; import { MatCardModule } from '@angular/material/card'; import { MatTabsModule } from '@angular/material/tabs'; - +import { + LinkTabNavBarComponent, + LinkTabNavBarItem, +} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; @Component({ selector: 'app-person-projects', standalone: true, - imports: [ - MatCardModule, - MatTabsModule, - RouterOutlet, - RouterLink, - RouterLinkActive, - ], + imports: [MatCardModule, MatTabsModule, RouterOutlet, LinkTabNavBarComponent], templateUrl: './person-projects.component.html', styleUrl: './person-projects.component.scss', }) export class PersonProjectsComponent { - readonly childRoutes = [ - { - path: 'dfg', - label: 'DFG-Projekte', - }, - { - path: 'eu', - label: 'EU-Projekte', - }, - ]; + _links = computed(() => { + const links: LinkTabNavBarItem[] = [ + { + label: 'DFG-Projekte', + path: 'dfg', + disabled: false, + }, + { + label: 'EU-Projekte', + path: 'eu', + disabled: false, + }, + ]; + return links; + }); } From 3b1ffda3b280d79eac677a07fa43b2a6780de578 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 6 Aug 2026 01:41:20 +0200 Subject: [PATCH 12/18] added HTTP 403 Forbidden for project access requests from unauthorized institutions --- service/src/main/inse/projects/logic.py | 38 +++- service/src/main/inse/projects/router.py | 205 +++++++++++---------- service/src/main/inse/projects/service.py | 35 +++- webapp/src/app/api/api/projects.service.ts | 40 ++-- 4 files changed, 204 insertions(+), 114 deletions(-) diff --git a/service/src/main/inse/projects/logic.py b/service/src/main/inse/projects/logic.py index ef96aec4..5683280a 100644 --- a/service/src/main/inse/projects/logic.py +++ b/service/src/main/inse/projects/logic.py @@ -1,13 +1,49 @@ import logging from collections import defaultdict from typing import Any - +import inse.authors.v2.service as author_service +from inse.auth.model import AccessTokenMetadata from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex from inse.projects.model import EuCordisProjectType logger = logging.getLogger(__name__) + +async def is_projects_access_forbidden( + access_token_metadata: AccessTokenMetadata, + raw_oa_institution_id: str | None, + raw_oa_author_id: str | None, +) -> bool: + """ + Determines if access to projects is forbidden based on the provided access token metadata + and the raw OpenAlex institution and author IDs. + + Args: + access_token_metadata (AccessTokenMetadata): Metadata from the access token. + raw_oa_institution_id (str | None): The raw OpenAlex institution ID. + raw_oa_author_id (str | None): The raw OpenAlex author ID. + + Returns: + bool: True if access is forbidden, False otherwise. + """ + effective_institution_id = access_token_metadata.effective_institution_id + + if raw_oa_institution_id and effective_institution_id != raw_oa_institution_id: + return True + + if raw_oa_author_id: + authors_profile = await author_service.get_author_by_id(raw_oa_author_id) + if not authors_profile: + return True # Author not found, access forbidden + + authors_last_known_institution_ids = [inst.id.split("/")[-1] for inst in authors_profile.last_known_institutions] + print(f"Author's last known institution IDs: {authors_last_known_institution_ids}") + if effective_institution_id not in authors_last_known_institution_ids: + return True # Effective institution ID does not match any of the author's last known institutions + + return False + async def get_dfg_author_names_by_ids(author_ids: list[int]) -> list[str] | None: try: body = { diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 5c7c426f..71e44778 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -2,6 +2,8 @@ import logging from typing import Annotated from fastapi import APIRouter, Body, Depends, Path, Query, status +from inse.auth.model import AccessTokenMetadata +from inse.auth.service import CurrentUserAccessTokenPayloadDep from inse.institutions.institutions_search_client import ( InstitutionsSearchClient, ) @@ -63,6 +65,105 @@ async def search_bund_projects( ) +@router.get( + "/dfg/search", + summary="Get DFG projects.", + description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.", + operation_id="getDfgProjects", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": DfgProjectPage, + }, + status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, + }, + response_model_by_alias=False, +) +async def get_dfg_projects( + access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], + institutions_search_client: Annotated[ + InstitutionsSearchClient, Depends(get_institutions_search_client) + ], + raw_oa_institution_id: Annotated[ + str | None, Query(description="The openalex institution ID to filter by.") + ] = None, + author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None, + author_filter_ids: Annotated[list[int] | None, Query(description="The dfg author IDs to filter by.")] = None, + institution_ids: Annotated[ + list[int] | None, Query(description="The institution IDs to filter by.") + ] = None, + title: Annotated[ + str | None, Query(description="The title to filter by.") + ] = None, + keywords: Annotated[ + list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.") + ] = None, + topic_ids: Annotated[ + list[str] | None, Query(description="The openalex topic IDs to filter by.") + ] = None, + filter_topic_ids: Annotated[ + list[str] | None, + Query( + description="Additional topic IDs to merge into the fuzzy topic-id resolution " + "(union with topic_ids). Only used when fuzzy=True." + ), + ] = None, + funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None, + funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None, + + page: Annotated[int, Query(description="The page number.", ge=0)] = 0, + size: Annotated[int, Query(description="The page size.", ge=1)] = 20, + sort_by: Annotated[str, Query(description="The field to sort by.")] = "title", + sort_direction: Annotated[ + str, Query(description="The sort direction (asc or desc).") + ] = "asc", + fuzzy: Annotated[ + bool, + Query(description="Use topic_id resolution if True, otherwise use raw keyword search."), + ] = False, + +) -> DfgProjectPage: + logger.debug( + "Received request to get DFG projects for author_id=%s, author_filter_ids=%s, " + "institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, " + "funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, " + "sort_direction=%s, fuzzy=%s", + author_id, + author_filter_ids, + institution_ids, + keywords, + topic_ids, + filter_topic_ids, + title, + funding_start_years, + funding_end_years, + page, + size, + sort_by, + sort_direction, + fuzzy, + ) + return await projects_service.get_dfg_projects_by_author_id( + access_token_metadata=access_token_metadata, + institutions_search_client=institutions_search_client, + raw_oa_institution_id=raw_oa_institution_id, + author_id=author_id, + author_filter_ids=author_filter_ids, + institution_ids=institution_ids, + funding_start_years=funding_start_years, + funding_end_years=funding_end_years, + title=title, + keywords=keywords, + topic_ids=topic_ids, + filter_topic_ids=filter_topic_ids, + page=page, + size=size, + sort_by=sort_by, + sort_direction=sort_direction, + fuzzy=fuzzy, + ) + @router.get( "/dfg/{id}", summary="Get a single DFG project.", @@ -96,10 +197,13 @@ async def get_single_dfg_project( "description": "Successful Response", "model": BundProjectPage, }, + status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, }, response_model_by_alias=False, ) async def search_bund_projects( + access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -156,6 +260,7 @@ async def search_bund_projects( ] = False, ) -> BundProjectPage: return await projects_service.search_bund_projects_with_filters( + access_token_metadata=access_token_metadata, institutions_search_client=institutions_search_client, executing_agency=executing_agency, funding_arts=funding_arts, @@ -217,10 +322,12 @@ from inse.projects.service import search_eu_cordis_projects "model": EuCordisProjectSearchPage, }, status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, }, response_model_by_alias=False, ) async def search_eu_cordis_projects_endpoint( + access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -299,6 +406,7 @@ async def search_eu_cordis_projects_endpoint( bool, Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), ] = False, + ) -> EuCordisProjectSearchPage: logger.debug( "Received EU CORDIS search request: raw_oa_institution_id=%s, " @@ -332,6 +440,7 @@ async def search_eu_cordis_projects_endpoint( ) return await search_eu_cordis_projects( + access_token_metadata=access_token_metadata, institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, author_id=author_id, @@ -629,102 +738,6 @@ async def get_institution_cordis_eu_projects_funding_over_time( ) -@router.get( - "/person/dfg/search", - summary="Get DFG projects.", - description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.", - operation_id="getDfgProjects", - responses={ - status.HTTP_200_OK: { - "description": "Successful Response", - "model": DfgProjectPage, - }, - status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, - }, - response_model_by_alias=False, -) -async def get_dfg_projects( - institutions_search_client: Annotated[ - InstitutionsSearchClient, Depends(get_institutions_search_client) - ], - raw_oa_institution_id: Annotated[ - str | None, Query(description="The openalex institution ID to filter by.") - ] = None, - author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None, - author_filter_ids: Annotated[list[int] | None, Query(description="The dfg author IDs to filter by.")] = None, - institution_ids: Annotated[ - list[int] | None, Query(description="The institution IDs to filter by.") - ] = None, - title: Annotated[ - str | None, Query(description="The title to filter by.") - ] = None, - keywords: Annotated[ - list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.") - ] = None, - topic_ids: Annotated[ - list[str] | None, Query(description="The openalex topic IDs to filter by.") - ] = None, - filter_topic_ids: Annotated[ - list[str] | None, - Query( - description="Additional topic IDs to merge into the fuzzy topic-id resolution " - "(union with topic_ids). Only used when fuzzy=True." - ), - ] = None, - funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None, - funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None, - - page: Annotated[int, Query(description="The page number.", ge=0)] = 0, - size: Annotated[int, Query(description="The page size.", ge=1)] = 20, - sort_by: Annotated[str, Query(description="The field to sort by.")] = "title", - sort_direction: Annotated[ - str, Query(description="The sort direction (asc or desc).") - ] = "asc", - fuzzy: Annotated[ - bool, - Query(description="Use topic_id resolution if True, otherwise use raw keyword search."), - ] = False, - -) -> DfgProjectPage: - logger.debug( - "Received request to get DFG projects for author_id=%s, author_filter_ids=%s, " - "institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, " - "funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, " - "sort_direction=%s, fuzzy=%s", - author_id, - author_filter_ids, - institution_ids, - keywords, - topic_ids, - filter_topic_ids, - title, - funding_start_years, - funding_end_years, - page, - size, - sort_by, - sort_direction, - fuzzy, - ) - return await projects_service.get_dfg_projects_by_author_id( - institutions_search_client=institutions_search_client, - raw_oa_institution_id=raw_oa_institution_id, - author_id=author_id, - author_filter_ids=author_filter_ids, - institution_ids=institution_ids, - funding_start_years=funding_start_years, - funding_end_years=funding_end_years, - title=title, - keywords=keywords, - topic_ids=topic_ids, - filter_topic_ids=filter_topic_ids, - page=page, - size=size, - sort_by=sort_by, - sort_direction=sort_direction, - fuzzy=fuzzy, - ) - @router.get( "/search", summary="Search projects across all funders.", diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index ab5fa644..dc5b92ca 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -3,6 +3,7 @@ import logging from typing import Any from inse.exceptions import NotFoundException +from inse.auth.model import AccessTokenMetadata from inse.institutions.institutions_search_client import ( InstitutionsSearchClient, ) @@ -27,7 +28,7 @@ from inse.projects.eu_cordis_projects_client import ( search_eu_cordis_projects as _search_eu_cordis_projects_es, ) from inse.projects.logic import ( - get_dfg_author_names_by_ids, + get_dfg_author_names_by_ids, is_projects_access_forbidden ) from inse.projects.model import ( BundProjectPage, @@ -42,7 +43,7 @@ from inse.projects.model import ( SortDirection, ) from inse.works.logic import get_publication_dois_of_author - +from fastapi import HTTPException as HttpException logger = logging.getLogger(__name__) @@ -158,6 +159,7 @@ async def _get_dfg_project_ids_for_openalex_authors( return list(set.intersection(*project_sets)) async def get_dfg_projects_by_author_id( + access_token_metadata: AccessTokenMetadata, institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str | None, author_id: str | None, @@ -198,6 +200,12 @@ async def get_dfg_projects_by_author_id( ) filter_names = [] author_project_ids = [] + is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) + if is_forbidden: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) if author_id: author_project_ids = await _get_dfg_project_ids_for_openalex_authors([author_id]) logger.info("Author project IDs for author_id:%s: %s", author_id, author_project_ids) @@ -221,6 +229,10 @@ async def get_dfg_projects_by_author_id( ) institution_aliases = [] if raw_oa_institution_id: + if institutions_search_client is None: + raise ValueError( + "institutions_search_client must be provided when raw_oa_institution_id is set" + ) institution_aliases = ( await institutions_search_client.get_institution_aliases_by_oa_institution_id( raw_oa_institution_id @@ -409,6 +421,7 @@ async def get_institution_bund_projects_funding_over_time( #Bund async def search_bund_projects_with_filters( + access_token_metadata: AccessTokenMetadata, institutions_search_client: InstitutionsSearchClient, executing_agency: str | None, raw_oa_institution_id: str | None, @@ -426,8 +439,18 @@ async def search_bund_projects_with_filters( sort_direction: str = "asc", fuzzy: bool = False, ) -> BundProjectPage: + is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, None) + if is_forbidden: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) institution_aliases = [] if raw_oa_institution_id: + if institutions_search_client is None: + raise ValueError( + "institutions_search_client must be provided when raw_oa_institution_id is set" + ) institution_aliases = ( await institutions_search_client.get_institution_aliases_by_oa_institution_id( raw_oa_institution_id @@ -603,6 +626,7 @@ async def _get_eu_project_ids_for_openalex_authors( async def search_eu_cordis_projects( + access_token_metadata: AccessTokenMetadata, page: int, size: int, project_types: list[EuCordisProjectType] | None = None, @@ -641,8 +665,13 @@ async def search_eu_cordis_projects( funding scheme, status, funding years, country) are ANDed together as in eu_cordis_projects_client.search_eu_cordis_projects. """ + is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) + if is_forbidden: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) resolved_organization_names: list[str] = list(organization_names or []) - if raw_oa_institution_id: if institutions_search_client is None: raise ValueError( diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index a5095f5b..0db7818b 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -66,7 +66,7 @@ export class ProjectsService extends BaseService { /** * Get DFG projects. * Returns a page of DFG projects based on the provided pagination parameters and optional institution filter. - * @endpoint get /api/projects/person/dfg/search + * @endpoint get /api/projects/dfg/search * @param rawOaInstitutionId The openalex institution ID to filter by. * @param authorId The openalex author ID to filter by. * @param authorFilterIds The dfg author IDs to filter by. @@ -82,13 +82,14 @@ export class ProjectsService extends BaseService { * @param sortBy The field to sort by. * @param sortDirection The sort direction (asc or desc). * @param fuzzy Use topic_id resolution if True, otherwise use raw keyword search. + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: 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 getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: 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 getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: 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 getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: 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 { + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, @@ -152,6 +153,9 @@ export class ProjectsService extends BaseService { let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ 'application/json' ]); @@ -175,7 +179,7 @@ export class ProjectsService extends BaseService { } } - let localVarPath = `/api/projects/person/dfg/search`; + let localVarPath = `/api/projects/dfg/search`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request('get', `${basePath}${localVarPath}`, { @@ -846,13 +850,14 @@ export class ProjectsService extends BaseService { * @param sortBy Sort field. * @param sortDirection Sort direction: asc or desc. * @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search. + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchBundProjectsWithFilters(executingAgency?: Array, fundingArts?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, countries?: Array, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (executingAgency) { @@ -920,6 +925,9 @@ export class ProjectsService extends BaseService { let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ 'application/json' ]); @@ -984,13 +992,14 @@ export class ProjectsService extends BaseService { * @param sortBy Sort field. * @param sortDirection Sort direction: asc or desc. * @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search. + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array, 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 searchEuCordisProjects(rawOaInstitutionId?: string, 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 searchEuCordisProjects(rawOaInstitutionId?: string, 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 searchEuCordisProjects(rawOaInstitutionId?: string, 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 { + public searchEuCordisProjects(rawOaInstitutionId?: string, 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, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchEuCordisProjects(rawOaInstitutionId?: string, 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, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchEuCordisProjects(rawOaInstitutionId?: string, 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, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchEuCordisProjects(rawOaInstitutionId?: string, 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, secureFgpAcc?: 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, @@ -1090,6 +1099,9 @@ export class ProjectsService extends BaseService { let localVarHeaders = this.defaultHeaders; + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ 'application/json' ]); From 916af846513761424450ba6b95341eca0ff4a18a Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 6 Aug 2026 13:56:25 +0200 Subject: [PATCH 13/18] fixed service function name --- service/src/main/inse/dashboard/service.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 4f1fe83d..ec065b45 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -622,7 +622,7 @@ async def get_dashboard_dfg_projects( ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) period = _dashboard_period(from_year, to_year) - projects = await projects_service.get_dfg_projects_by_author_id( + projects = await projects_service.get_dfg_projects( institutions_search_client=InstitutionsSearchClient(), raw_oa_institution_id=_raw_institution_id(normalized_id), author_id=None, @@ -871,7 +871,7 @@ async def _get_dfg_project_ids_from_projects_service( project_ids: set[str] = set() while True: - projects = await projects_service.get_dfg_projects_by_author_id( + projects = await projects_service.get_dfg_projects( institutions_search_client=InstitutionsSearchClient(), raw_oa_institution_id=_raw_institution_id(institution_id), author_id=None, From be89e2986b46d26d9dfcd42e4fadf1922ee5de8d Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 6 Aug 2026 13:56:52 +0200 Subject: [PATCH 14/18] check for 403 on the router, not in service! --- service/src/main/inse/projects/router.py | 27 +++++++++++++++++++---- service/src/main/inse/projects/service.py | 27 ++--------------------- 2 files changed, 25 insertions(+), 29 deletions(-) diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 71e44778..7161b89a 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -7,6 +7,9 @@ from inse.auth.service import CurrentUserAccessTokenPayloadDep from inse.institutions.institutions_search_client import ( InstitutionsSearchClient, ) +from inse.projects.logic import ( + is_projects_access_forbidden +) from inse.institutions.router import get_institutions_search_client from inse.models.bund_project_details import BundProjectDetails from inse.models.dfg_project_details import DfgProjectDetails @@ -30,6 +33,7 @@ from inse.projects.model import ( SortDirection, ) from inse.tags import Tags +from fastapi import HTTPException as HttpException logger = logging.getLogger(__name__) @@ -144,8 +148,13 @@ async def get_dfg_projects( sort_direction, fuzzy, ) - return await projects_service.get_dfg_projects_by_author_id( - access_token_metadata=access_token_metadata, + is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) + if is_forbidden: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) + return await projects_service.get_dfg_projects( institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, author_id=author_id, @@ -259,6 +268,12 @@ async def search_bund_projects( Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), ] = False, ) -> BundProjectPage: + is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, None) + if is_forbidden: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) return await projects_service.search_bund_projects_with_filters( access_token_metadata=access_token_metadata, institutions_search_client=institutions_search_client, @@ -438,9 +453,13 @@ async def search_eu_cordis_projects_endpoint( sort_direction, fuzzy, ) - + is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) + if is_forbidden: + raise HttpException( + status_code=403, + detail="Access denied for the provided author ID or institution ID", + ) return await search_eu_cordis_projects( - access_token_metadata=access_token_metadata, institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, author_id=author_id, diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index dc5b92ca..813ff0e2 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -27,9 +27,7 @@ from inse.projects.eu_cordis_projects_client import ( from inse.projects.eu_cordis_projects_client import ( search_eu_cordis_projects as _search_eu_cordis_projects_es, ) -from inse.projects.logic import ( - get_dfg_author_names_by_ids, is_projects_access_forbidden -) + from inse.projects.model import ( BundProjectPage, DfgProjectPage, @@ -158,8 +156,7 @@ async def _get_dfg_project_ids_for_openalex_authors( return list(set.intersection(*project_sets)) -async def get_dfg_projects_by_author_id( - access_token_metadata: AccessTokenMetadata, +async def get_dfg_projects( institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str | None, author_id: str | None, @@ -200,12 +197,6 @@ async def get_dfg_projects_by_author_id( ) filter_names = [] author_project_ids = [] - is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) - if is_forbidden: - raise HttpException( - status_code=403, - detail="Access denied for the provided author ID or institution ID", - ) if author_id: author_project_ids = await _get_dfg_project_ids_for_openalex_authors([author_id]) logger.info("Author project IDs for author_id:%s: %s", author_id, author_project_ids) @@ -421,7 +412,6 @@ async def get_institution_bund_projects_funding_over_time( #Bund async def search_bund_projects_with_filters( - access_token_metadata: AccessTokenMetadata, institutions_search_client: InstitutionsSearchClient, executing_agency: str | None, raw_oa_institution_id: str | None, @@ -439,12 +429,6 @@ async def search_bund_projects_with_filters( sort_direction: str = "asc", fuzzy: bool = False, ) -> BundProjectPage: - is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, None) - if is_forbidden: - raise HttpException( - status_code=403, - detail="Access denied for the provided author ID or institution ID", - ) institution_aliases = [] if raw_oa_institution_id: if institutions_search_client is None: @@ -626,7 +610,6 @@ async def _get_eu_project_ids_for_openalex_authors( async def search_eu_cordis_projects( - access_token_metadata: AccessTokenMetadata, page: int, size: int, project_types: list[EuCordisProjectType] | None = None, @@ -665,12 +648,6 @@ async def search_eu_cordis_projects( funding scheme, status, funding years, country) are ANDed together as in eu_cordis_projects_client.search_eu_cordis_projects. """ - is_forbidden = await is_projects_access_forbidden(access_token_metadata, raw_oa_institution_id, author_id) - if is_forbidden: - raise HttpException( - status_code=403, - detail="Access denied for the provided author ID or institution ID", - ) resolved_organization_names: list[str] = list(organization_names or []) if raw_oa_institution_id: if institutions_search_client is None: From d8eec59d5deb2c1cc7f7a2b977dd6afacab8bcea Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 6 Aug 2026 14:18:46 +0200 Subject: [PATCH 15/18] moved filter ids validation to backend --- service/src/main/inse/projects/router.py | 6 +-- service/src/main/inse/projects/service.py | 47 +++++++++++++++---- webapp/src/app/api/api/projects.service.ts | 8 ++-- .../app/resolvers/dfg-projects.resolver.ts | 45 +++--------------- 4 files changed, 51 insertions(+), 55 deletions(-) diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 7161b89a..6382f575 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -93,10 +93,8 @@ async def get_dfg_projects( str | None, Query(description="The openalex institution ID to filter by.") ] = None, author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None, - author_filter_ids: Annotated[list[int] | None, Query(description="The dfg author IDs to filter by.")] = None, - institution_ids: Annotated[ - list[int] | None, Query(description="The institution IDs to filter by.") - ] = None, + author_filter_ids: Annotated[list[str] | None, Query(description="The dfg author IDs to filter by.")] = None, + institution_ids: Annotated[list[str] | None, Query(description="The institution IDs to filter by.")] = None, title: Annotated[ str | None, Query(description="The title to filter by.") ] = None, diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 813ff0e2..f1abccf8 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -40,6 +40,7 @@ from inse.projects.model import ( ProjectType, SortDirection, ) +from inse.projects.logic import get_dfg_author_names_by_ids from inse.works.logic import get_publication_dois_of_author from fastapi import HTTPException as HttpException logger = logging.getLogger(__name__) @@ -156,12 +157,25 @@ async def _get_dfg_project_ids_for_openalex_authors( return list(set.intersection(*project_sets)) +def _is_number_list(values: list[str] | None) -> bool: + if not values: + return True # nothing to validate, treat as valid/empty + for value in values: + if value is None or value == "": + return False + try: + float(value) + except (TypeError, ValueError): + return False + return True + + async def get_dfg_projects( institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str | None, author_id: str | None, - author_filter_ids: list[int] | None, - institution_ids: list[int] | None, + author_filter_ids: list[str] | None, + institution_ids: list[str] | None, keywords: list[str] | None, topic_ids: list[str] | None, filter_topic_ids: list[str] | None, @@ -195,6 +209,23 @@ async def get_dfg_projects( sort_direction, fuzzy, ) + + # Validate author_filter_ids / institution_ids. Return an empty page + if not _is_number_list(author_filter_ids) or not _is_number_list(institution_ids): + logger.debug( + "Invalid author_filter_ids=%s or institution_ids=%s, returning empty page", + author_filter_ids, + institution_ids, + ) + return DfgProjectPage(elements=[], page=page, size=size, total=0) + + author_filter_ids_int = ( + [int(float(v)) for v in author_filter_ids] if author_filter_ids else None + ) + institution_ids_int = ( + [int(float(v)) for v in institution_ids] if institution_ids else None + ) + filter_names = [] author_project_ids = [] if author_id: @@ -207,16 +238,16 @@ async def get_dfg_projects( size=size, total=0) - if author_filter_ids: + if author_filter_ids_int: filter_names = ( - await get_dfg_author_names_by_ids(author_ids=author_filter_ids) - if author_filter_ids + await get_dfg_author_names_by_ids(author_ids=author_filter_ids_int) + if author_filter_ids_int else [] ) - if author_filter_ids and not filter_names: + if author_filter_ids_int and not filter_names: logger.debug( "No author names found for author_filter_ids=%s", - author_filter_ids, + author_filter_ids_int, ) institution_aliases = [] if raw_oa_institution_id: @@ -242,7 +273,7 @@ async def get_dfg_projects( institution_aliases=institution_aliases, project_ids=author_project_ids, names=filter_names or [], - institution_ids=institution_ids, + institution_ids=institution_ids_int, keywords=keywords, topic_ids=topic_ids, filter_topic_ids=filter_topic_ids, diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 0db7818b..938af152 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -86,10 +86,10 @@ export class ProjectsService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array, institutionIds?: Array, title?: string, keywords?: Array, topicIds?: Array, filterTopicIds?: Array, fundingStartYears?: Array, fundingEndYears?: Array, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, diff --git a/webapp/src/app/resolvers/dfg-projects.resolver.ts b/webapp/src/app/resolvers/dfg-projects.resolver.ts index 365a4214..102976f9 100644 --- a/webapp/src/app/resolvers/dfg-projects.resolver.ts +++ b/webapp/src/app/resolvers/dfg-projects.resolver.ts @@ -1,6 +1,5 @@ import { inject } from '@angular/core'; import { ResolveFn } from '@angular/router'; -import { of } from 'rxjs'; import { DfgProjectPage, ProjectsService } from '../api'; export const dfgProjectQueryParamKeys = { @@ -25,34 +24,6 @@ export const RESOLVING_PROJECT_PAGE_FOR = { KEYWORDS_SEARCH: 'KEYWORDS_SEARCH', } as const; -// Empty page returned whenever a required numeric param fails to parse. -const EMPTY_DFG_PROJECT_PAGE: DfgProjectPage = { - page: 0, - size: 0, - total: 0, - elements: [], -} as DfgProjectPage; - -function toNumberOrNull(value: unknown): number | null { - if (value === undefined || value === null || value === '') { - return null; - } - const parsed = Number(value); - return Number.isFinite(parsed) ? parsed : null; -} - -function toNumberArrayOrNull(values: string[]): number[] | null { - const result: number[] = []; - for (const value of values) { - const parsed = toNumberOrNull(value); - if (parsed === null) { - return null; - } - result.push(parsed); - } - return result; -} - export const dfgProjectsResolver: ResolveFn = ( route, state, @@ -69,11 +40,10 @@ export const dfgProjectsResolver: ResolveFn = ( ); const page = - toNumberOrNull(route.queryParamMap.get(dfgProjectQueryParamKeys.page)) ?? 0; + Number(route.queryParamMap.get(dfgProjectQueryParamKeys.page)) || 0; const size = - toNumberOrNull(route.queryParamMap.get(dfgProjectQueryParamKeys.size)) ?? - 10; + Number(route.queryParamMap.get(dfgProjectQueryParamKeys.size)) || 10; const searchTerm = route.queryParamMap.get(dfgProjectQueryParamKeys.title) ?? undefined; @@ -92,15 +62,12 @@ export const dfgProjectsResolver: ResolveFn = ( dfgProjectQueryParamKeys.topicId, ); - const institutionIds = toNumberArrayOrNull( - route.queryParamMap.getAll(dfgProjectQueryParamKeys.institutionId), + const institutionIds = route.queryParamMap.getAll( + dfgProjectQueryParamKeys.institutionId, ); - const authorIds = toNumberArrayOrNull( - route.queryParamMap.getAll(dfgProjectQueryParamKeys.authorId), + const authorIds = route.queryParamMap.getAll( + dfgProjectQueryParamKeys.authorId, ); - if (institutionIds === null || authorIds === null) { - return of(EMPTY_DFG_PROJECT_PAGE); - } if (resolvingFor === RESOLVING_PROJECT_PAGE_FOR.PERSON) { const rawAuthorId = route.parent?.parent?.params['id']; From 30cbb080b015b34fc415ce6a21067dd23470c085 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 6 Aug 2026 14:19:16 +0200 Subject: [PATCH 16/18] adjusted tests for new service function name --- service/src/main/inse/dashboard/test_service.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 630f8121..2de2ca6e 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -68,7 +68,7 @@ async def test_dfg_topic_project_ids_use_paginated_projects_service(): ] with patch( - "inse.dashboard.service.projects_service.get_dfg_projects_by_author_id", + "inse.dashboard.service.projects_service.get_dfg_projects", new=AsyncMock(side_effect=pages), ) as mocked_get_projects: project_ids = await _get_dfg_project_ids_from_projects_service( @@ -144,7 +144,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): ) ), ), patch( - "inse.dashboard.service.projects_service.get_dfg_projects_by_author_id", + "inse.dashboard.service.projects_service.get_dfg_projects", new=AsyncMock( return_value=DfgProjectPage(elements=[], total=3, page=0, size=1) ), @@ -254,7 +254,7 @@ async def test_dashboard_dfg_projects_uses_projects_service_total(): project_page = DfgProjectPage(elements=[], total=42, page=0, size=1) with patch( - "inse.dashboard.service.projects_service.get_dfg_projects_by_author_id", + "inse.dashboard.service.projects_service.get_dfg_projects", new=AsyncMock(return_value=project_page), ) as mocked_get_projects: result = await get_dashboard_dfg_projects( From c70a56651429fab872884c0c1caaf964c6869233 Mon Sep 17 00:00:00 2001 From: arzani Date: Thu, 6 Aug 2026 15:03:54 +0200 Subject: [PATCH 17/18] cc-news integration in keyword analysis via explicit non-fuzzy search --- .../main/inse/integrations/elasticsearch.py | 9 +- service/src/main/inse/model.py | 1 + .../university_ranking/trend_query_builder.py | 65 +++++++ .../university_ranking/trend_strategies.py | 181 ++++++++++++++---- .../university-ranking/models/trend.models.ts | 7 +- .../uni-trend-chart.component.ts | 20 +- .../uni-trend-parent.component.html | 39 ++-- .../uni-trend-parent.component.scss | 20 ++ .../uni-trend-parent.component.ts | 85 ++++++-- .../university-ranking/utils/trend.utils.ts | 58 +++--- .../src/app/resolvers/uni-trend.resolver.ts | 2 +- 11 files changed, 376 insertions(+), 111 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 0ad63956..c0553de1 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -96,6 +96,7 @@ def _index_to_cluster(index: ESIndex) -> ESCluster | None: ESIndex.OPENALEX_INSTITUTIONS, ESIndex.OPENALEX_PUBLICATIONS, ESIndex.WORK_CLASSIFICATIONS, + ESIndex.CC_NEWS_WILDCARD, }: return ESCluster.NES elif index in { @@ -439,12 +440,16 @@ async def count( async def msearch( searches: list[tuple[ESIndex | str | list[str], dict[str, Any]]], cluster: ESCluster = ESCluster.NES, + request_cache: bool = False, ) -> list[dict[str, Any]]: """Performs a multi-search request (_msearch) on Elasticsearch. Args: searches: A list of tuples, each containing (index, payload_dict). cluster: The Elasticsearch cluster to execute searches on. + request_cache: Whether to enable the shard request cache for each search. + Elasticsearch rejects `request_cache` as an _msearch URL parameter, so + it goes into the per-search header line instead. Returns: List[Dict[str, Any]]: List of response dictionaries for each search in order. @@ -464,7 +469,9 @@ async def msearch( idx_str = ",".join(str(i) for i in idx) else: idx_str = str(idx) - header_obj = {"index": idx_str} + header_obj: dict[str, Any] = {"index": idx_str} + if request_cache: + header_obj["request_cache"] = True lines.append(json.dumps(header_obj)) lines.append(json.dumps(body)) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index e1f0d3aa..83c064c3 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -65,6 +65,7 @@ class ESIndex(StrEnum): AKTUELLES = "aktuell" AKTUELLES_POSTPROC = "aktuell_postproc" AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics" + CC_NEWS_WILDCARD = "cc-news-*" CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" diff --git a/service/src/main/inse/university_ranking/trend_query_builder.py b/service/src/main/inse/university_ranking/trend_query_builder.py index dc639132..10e4b805 100644 --- a/service/src/main/inse/university_ranking/trend_query_builder.py +++ b/service/src/main/inse/university_ranking/trend_query_builder.py @@ -1,5 +1,6 @@ import asyncio import logging +import re from typing import Any from inse.integrations import elasticsearch @@ -11,6 +12,17 @@ logger = logging.getLogger(__name__) DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514" DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen" +# Reserved characters and boolean operators of the Lucene query_string syntax +_LUCENE_SPECIAL_CHARS = re.compile(r'([+\-=&|> str: + """Escapes a free-text search term so it is safe inside a ``query_string`` query.""" + if not term: + return "" + escaped = _LUCENE_SPECIAL_CHARS.sub(r"\\\1", term) + return _LUCENE_BOOL_OPERATORS.sub(lambda m: f'"{m.group(1)}"', escaped) def clean_inst_id(id_str: str) -> str: @@ -407,6 +419,56 @@ class TrendQueryBuilder: } } + @staticmethod + def build_cc_news_year_agg_body( + term: str, + start_year: int, + end_year: int, + languages: list[str] | None = None, + ) -> dict[str, Any]: + """Builds a size=0 yearly-count aggregation over the Common Crawl News indices. Buckets + by year with a `date_histogram`, since cc-news has a real `content_date` date field rather than + the integer `date_year` of `aktuell`. + """ + return { + "size": 0, + "track_total_hits": False, + "_source": False, + "query": { + "bool": { + "filter": [ + { + "query_string": { + "query": escape_lucene_query(term), + "fields": CC_NEWS_SEARCH_FIELDS, + "default_operator": "AND", + } + }, + {"terms": {"language_code": languages or CC_NEWS_LANGUAGES}}, + { + "range": { + "content_date": { + "gte": f"{start_year}-01-01", + "lte": f"{end_year}-12-31", + "format": "yyyy-MM-dd", + } + } + }, + ] + } + }, + "aggs": { + "by_year": { + "date_histogram": { + "field": "content_date", + "calendar_interval": "year", + "format": "yyyy", + "min_doc_count": 0, + } + } + }, + } + @staticmethod def build_bund_receiver_clause(aliases: list[str]) -> dict[str, Any]: """Builds Zuwendungsempfänger matching clause for BUND projects.""" @@ -443,4 +505,7 @@ DFG_PROJECT_TEXT_FIELDS = [ CORDIS_PROJECT_TEXT_FIELDS = ["title", "objective"] AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"] +CC_NEWS_SEARCH_FIELDS = ["title", "body"] +CC_NEWS_LANGUAGES = ["de", "en"] +CC_NEWS_START_YEAR = 2017 diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index f46c6be2..c0badec6 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -16,11 +16,13 @@ from .model import ( ) from .trend_query_builder import ( AKTUELLES_SEARCH_FIELDS, + CC_NEWS_START_YEAR, DEFAULT_INSTITUTION_ID, DEFAULT_INSTITUTION_NAME, TrendMetadataResolver, TrendQueryBuilder, clean_inst_id, + escape_lucene_query, to_full_inst_url, ) @@ -47,6 +49,13 @@ EPO_PATENT_FIELDS = [ "openalex_topics.topic_id", ] +# Synthetic entity id prefixes for the news trend series. The webapp keys colouring, chip +# visibility and pie filtering off these, so keep them in sync with uni-trend-parent.component.ts. +NEWS_ENTITY_PREFIX = "news_topic_" +CC_NEWS_ENTITY_PREFIX = "ccnews_topic_" +# Entity id of the collapsed CC-News series in the cross-domain ("all") view. +CC_NEWS_COMPOSITE_ID = "ccnews" + DFG_INSTITUTION_FIELDS = [ "Antragstellende Institution", "Mitantragstellende Institution", @@ -1042,6 +1051,18 @@ class ProjectsTrendStrategy(TrendStrategy): class NewsTrendStrategy(TrendStrategy): + """Yearly news counts per topic. + + Produces one series per topic from the UDE-internal `aktuell` index (entity id + ``news_topic_``). When keyword matching is active (``fuzzy=False``) it additionally + produces an external Common Crawl News baseline per topic (``ccnews_topic_``) so the + internal coverage can be compared against the wider web. CC-News has no OpenAlex topic + mapping, so it is skipped entirely in topic-mapping mode. + """ + + def __init__(self, include_cc_news: bool = True): + self.include_cc_news = include_cc_news + async def get_trend( self, topics: list[str], @@ -1054,20 +1075,40 @@ class NewsTrendStrategy(TrendStrategy): ) -> TrendResponse: years_range = self._get_years_range() start_year, end_year = years_range[0], years_range[-1] + years_set = set(years_range) + + cc_news_enabled = self.include_cc_news and not fuzzy accumulated_data = { - f"news_topic_{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} + f"{NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} for t in topics } + if cc_news_enabled: + accumulated_data.update({ + f"{CC_NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} + for t in topics + }) STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"} + def resolve_keyword_term(idx: int, t_name: str) -> str: + """Picks the raw keyword for a topic, falling back to the topic name itself.""" + if keywords and idx < len(keywords) and keywords[idx]: + raw_kw = keywords[idx] + term = raw_kw.split(",")[0].strip() if isinstance(raw_kw, str) else raw_kw + if term: + return term + return t_name + + def is_searchable_term(term: str) -> bool: + return bool(term) and term.lower() not in STOP_WORDS and len(term.strip()) > 1 + # Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs async def fetch_news_ids_for_term(idx: int, t_name: str) -> list[str]: news_ids: Set[str] = set() if fuzzy: term = t_name - es_query = {"term": {"topic_matches.topic_display_name.keyword": term}} + es_query = {"match_phrase": {"topic_matches.topic_display_name": term}} try: async for hit in elasticsearch.scan( index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value, @@ -1081,20 +1122,14 @@ class NewsTrendStrategy(TrendStrategy): except Exception as e: logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e) else: - 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 + term = resolve_keyword_term(idx, t_name) # If non-fuzzy keyword search, search article content fields in 'aktuell' index - if term and term.lower() not in STOP_WORDS and len(term.strip()) > 1: + if is_searchable_term(term): try: content_query = { "query_string": { - "query": term, + "query": escape_lucene_query(term), "fields": AKTUELLES_SEARCH_FIELDS, "default_operator": "AND", } @@ -1113,12 +1148,59 @@ class NewsTrendStrategy(TrendStrategy): return list(news_ids) - matching_ids_list = await asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics))) + async def fetch_cc_news_counts() -> dict[int, dict[int, int]]: + """Yearly CC-News counts per topic index, from a single _msearch over cc-news-*. + The year buckets are read straight off a size=0 date_histogram instead. + """ + searchable = [ + (idx, term) + for idx, t_name in enumerate(topics) + if is_searchable_term(term := resolve_keyword_term(idx, t_name)) + ] + if not searchable: + return {} + + searches = [ + ( + ESIndex.CC_NEWS_WILDCARD.value, + TrendQueryBuilder.build_cc_news_year_agg_body(term, CC_NEWS_START_YEAR, end_year), + ) + for _, term in searchable + ] + try: + responses = await elasticsearch.msearch( + searches, cluster=ESCluster.NES, request_cache=True + ) + except Exception as e: + logger.warning("Failed to aggregate CC-News years via msearch: %s", e) + return {} + + counts: dict[int, dict[int, int]] = {} + for (topic_idx, term), res in zip(searchable, responses): + if not isinstance(res, dict) or "error" in res: + logger.warning("CC-News msearch entry for %r failed: %s", term, (res or {}).get("error")) + continue + by_year: dict[int, int] = {} + for b in res.get("aggregations", {}).get("by_year", {}).get("buckets", []): + try: + yr = int(b.get("key_as_string")) + except (TypeError, ValueError): + continue + if yr in years_set: + by_year[yr] = int(b.get("doc_count", 0)) + counts[topic_idx] = by_year + return counts + + news_ids_future = asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics))) + if cc_news_enabled: + matching_ids_list, cc_news_counts = await asyncio.gather(news_ids_future, fetch_cc_news_counts()) + else: + matching_ids_list, cc_news_counts = await news_ids_future, {} async def count_by_year(t_name: str, news_ids: list[str]): if not news_ids: return - entity_key = f"news_topic_{t_name}" + entity_key = f"{NEWS_ENTITY_PREFIX}{t_name}" # Prepare multi-search payloads for chunks of news_ids to avoid payload limits chunk_queries = [] @@ -1164,13 +1246,15 @@ class NewsTrendStrategy(TrendStrategy): await asyncio.gather(*(count_by_year(t, ids) for t, ids in zip(topics, matching_ids_list))) + for topic_idx, t_name in enumerate(topics): + entity_key = f"{CC_NEWS_ENTITY_PREFIX}{t_name}" + for yr, count in cc_news_counts.get(topic_idx, {}).items(): + prev_count, _ = accumulated_data[entity_key][t_name][yr] + accumulated_data[entity_key][t_name][yr] = (prev_count + count, 1) + normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) - series_list: list[TrendSeries] = [] - for t_name in topics: - entity_key = f"news_topic_{t_name}" - topic_data_map: dict[str, list[TopicYearlyData]] = {} - + def build_series(entity_key: str, t_name: str, entity_name: str) -> TrendSeries: 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)) @@ -1188,16 +1272,22 @@ class NewsTrendStrategy(TrendStrategy): ) ) - for topic in topics: - topic_data_map[topic] = yearly_data_items + topic_data_map: dict[str, list[TopicYearlyData]] = {topic: yearly_data_items for topic in topics} - series_list.append( - TrendSeries( - entity_id=entity_key, - entity_name=t_name, - entity_type="institution", - topic_data=topic_data_map, - ) + return TrendSeries( + entity_id=entity_key, + entity_name=entity_name, + entity_type="institution", + topic_data=topic_data_map, + ) + + series_list: list[TrendSeries] = [ + build_series(f"{NEWS_ENTITY_PREFIX}{t_name}", t_name, t_name) for t_name in topics + ] + if cc_news_enabled: + series_list.extend( + build_series(f"{CC_NEWS_ENTITY_PREFIX}{t_name}", t_name, f"{t_name} (CC-News)") + for t_name in topics ) return TrendResponse(series=series_list, years=years_range) @@ -1269,25 +1359,40 @@ class AllTrendStrategy(TrendStrategy): add_composite(pat_series, "patents", "Patentanmeldungen") add_composite(proj_series, "projects", "Drittmittelförderung") - if is_ude and news_res: - merged_news_topic_data: dict[str, list[TopicYearlyData]] = {} + def merge_news_composite(prefix: str, c_id: str, c_name: str) -> bool: + """Collapses the per-topic news series of one source into a single composite. + + Returns False when the source produced no series at all. + """ + if not news_res or not any(s.entity_id.startswith(prefix) for s in news_res.series): + return False + + merged_topic_data: dict[str, list[TopicYearlyData]] = {} for topic in topics: - term_key = f"news_topic_{topic}" + term_key = f"{prefix}{topic}" matching_series = next((s for s in news_res.series if s.entity_id == term_key), None) if matching_series and topic in matching_series.topic_data: - merged_news_topic_data[topic] = matching_series.topic_data[topic] + merged_topic_data[topic] = matching_series.topic_data[topic] else: - merged_news_topic_data[topic] = [ + merged_topic_data[topic] = [ TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1) for yr in years_range ] - news_series = TrendSeries( - entity_id="news", - entity_name="UDE Campus Aktuell Beiträge", - entity_type="institution", - topic_data=merged_news_topic_data, + add_composite( + TrendSeries( + entity_id=c_id, + entity_name=c_name, + entity_type="institution", + topic_data=merged_topic_data, + ), + c_id, + c_name, ) - add_composite(news_series, "news", "UDE Campus Aktuell Beiträge") + return True + + if is_ude: + merge_news_composite(NEWS_ENTITY_PREFIX, "news", "UDE Campus Aktuell Beiträge") + merge_news_composite(CC_NEWS_ENTITY_PREFIX, CC_NEWS_COMPOSITE_ID, "Web-Nachrichten (CC-News)") return TrendResponse(series=composite_series, years=years_range) diff --git a/webapp/src/app/modules/university-ranking/models/trend.models.ts b/webapp/src/app/modules/university-ranking/models/trend.models.ts index 9e049604..e333c281 100644 --- a/webapp/src/app/modules/university-ranking/models/trend.models.ts +++ b/webapp/src/app/modules/university-ranking/models/trend.models.ts @@ -15,6 +15,11 @@ export interface TrendStrategyConfig { export type TrendSeriesWithVisibility = TrendSeries & { visible?: boolean }; +export const NEWS_ENTITY_PREFIX = 'news_topic_'; +export const CC_NEWS_ENTITY_PREFIX = 'ccnews_topic_'; +export const CC_NEWS_COMPOSITE_ID = 'ccnews'; +export const CC_NEWS_START_YEAR = 2017; + export const TREND_CONFIGS: Record = { publications: { showInstitutionSelector: true, @@ -49,7 +54,7 @@ export const TREND_CONFIGS: Record = { showLocationSelector: false, showAuthorSelector: false, yAxisLabel: 'Pressemitteilungen', - chartTitle: 'Nachrichtentrends', + chartTitle: 'Nachrichtentrends (UDE vs. CC-News)', }, all: { showInstitutionSelector: false, 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 82061df7..b9b36dd5 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 @@ -10,6 +10,8 @@ import { NgxEchartsDirective } from 'ngx-echarts'; import { MatIconModule } from '@angular/material/icon'; import { TrendResponse, TrendSeries, TopicYearlyData } from '../../../api'; import { ChartThemeService } from '../../../shared/services/chart-theme.service'; +import { CC_NEWS_START_YEAR } from '../models/trend.models'; +import { isCcNewsSeries } from '../utils/trend.utils'; @Component({ selector: 'app-uni-trend-chart', @@ -111,8 +113,9 @@ export class UniTrendChartComponent { return; } const yrTopicData = entity.topic_data[selectedTopic] || []; - + const isCcNews = isCcNewsSeries(entity.entity_id); const lineData = years.map((year) => { + if (isCcNews && year < CC_NEWS_START_YEAR) return null; const yrData = yrTopicData.find((y) => y.year === year); if (!yrData) return 0; if (currentMode === 'cumulative') { @@ -126,13 +129,14 @@ export class UniTrendChartComponent { type: 'line', xAxisIndex: 0, yAxisIndex: 0, - areaStyle: { - opacity: 0.12, - }, + areaStyle: { opacity: isCcNews ? 0.3 : 0.12 }, data: lineData, smooth: true, + connectNulls: false, + showSymbol: !isCcNews, + z: isCcNews ? 1 : 2, lineStyle: { - width: 2.5, + width: isCcNews ? 1 : 2.5, color: color, }, itemStyle: { @@ -140,10 +144,14 @@ export class UniTrendChartComponent { }, emphasis: { focus: 'series', - lineStyle: { width: 3.5 }, + lineStyle: { width: isCcNews ? 2 : 3.5 }, }, }); + if (isCcNews) { + return; + } + const bars = years.map((year) => { const yrData = yrTopicData.find((y) => y.year === year); const val = yrData ? yrData.raw : 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 4183676e..6560cc05 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 @@ -36,7 +36,7 @@ [matTooltip]=" !isUde() ? 'News-Trends sind nur für die Universität Duisburg-Essen verfügbar' - : 'Zeigt Pressemitteilungstrends der UDE' + : 'Zeigt Pressemitteilungstrends der UDE im Vergleich zur Web-Berichterstattung (CC-News). Der CC-News-Vergleich erfordert deaktivierte Fuzzy-Suche.' " (click)="setSearchType('news')"> campaign News @@ -184,28 +184,27 @@

    Daten werden geladen...

    } + @if (selectedSearchType() === 'news' && !hasCcNewsSeries()) { +
    + info_outline + + Der CC-News-Vergleich (hinterlegte Fläche, ab 2017) ist aktuell nur bei + deaktivierter Fuzzy-Suche verfügbar, da für Web-Nachrichten kein + Themen-Mapping existiert. + +
    + } @if (selectedTrendTopics().length > 0) {
    @for (topic of selectedTrendTopics(); track $index) { - @if (selectedSearchType() === 'news') { - - - } @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 30951435..6f25eca7 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 @@ -164,6 +164,26 @@ border-bottom: 1px solid var(--sg-border); } +.cc-news-hint { + display: flex; + align-items: flex-start; + gap: 0.5rem; + padding: 0.75rem 1.25rem; + background: var(--sg-surface-muted); + border-bottom: 1px solid var(--sg-border); + color: var(--sg-text-muted); + font-size: 0.85rem; + line-height: 1.4; + + mat-icon { + flex: none; + font-size: 1.1rem; + width: 1.1rem; + height: 1.1rem; + color: var(--sg-primary); + } +} + .loader-overlay { position: absolute; top: 0; 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 b55c799f..f9dfc8e2 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 @@ -69,12 +69,19 @@ import { } from '../../../shared/ui/topic-treemap/topic-treemap.models'; import { TopicsService } from '../../../api/api/topics.service'; -import { CompareItem, TREND_CONFIGS } from '../models/trend.models'; +import { + CC_NEWS_COMPOSITE_ID, + CC_NEWS_ENTITY_PREFIX, + CompareItem, + NEWS_ENTITY_PREFIX, + TREND_CONFIGS, +} from '../models/trend.models'; import { cleanEntityId, isTopicEmptyForSeries, findFirstNonEmptyTopic, buildEntityColorIndex, + newsSourceColor, } from '../utils/trend.utils'; import { TrendDataService } from '../services/trend-data.service'; @@ -326,28 +333,37 @@ export class UniTrendParentComponent implements OnInit { readonly boundGetTopicColor = this.getTopicColor.bind(this); readonly newsSelectedTopicsPieData = computed(() => { - const data = this.trendResponse(); + const data = this.rawTrendResponse(); 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 data.series + .filter((s) => s.entity_id.startsWith(NEWS_ENTITY_PREFIX)) + .map((s) => { + const topicName = s.entity_name; + const yearlyItems = + s.topic_data[topicName] || Object.values(s.topic_data)[0] || []; + const totalRaw = yearlyItems + .filter((y) => y.year >= startYr && y.year <= endYr) + .reduce((sum, item) => sum + (item.raw || 0), 0); - return { - name: topicName, - value: totalRaw, - }; - }); + return { + name: topicName, + value: totalRaw, + }; + }); }); + readonly hasCcNewsSeries = computed( + () => + this.rawTrendResponse()?.series?.some((s) => + s.entity_id.startsWith(CC_NEWS_ENTITY_PREFIX), + ) ?? false, + ); + readonly activeTreemapData = computed(() => { const data = this.trendResponse(); const searchType = this.selectedSearchType(); @@ -530,9 +546,24 @@ export class UniTrendParentComponent implements OnInit { }; }); + seriesTopicName(entityId: string): string { + if (entityId.startsWith(NEWS_ENTITY_PREFIX)) { + return entityId.slice(NEWS_ENTITY_PREFIX.length); + } + if (entityId.startsWith(CC_NEWS_ENTITY_PREFIX)) { + return entityId.slice(CC_NEWS_ENTITY_PREFIX.length); + } + return entityId; + } + isTopicEmpty(topic: string): boolean { - const series = this.rawTrendResponse()?.series || []; - if (!series || series.length === 0) return true; + const allSeries = this.rawTrendResponse()?.series || []; + if (allSeries.length === 0) return true; + const series = + this.selectedSearchType() === 'news' + ? allSeries.filter((s) => this.seriesTopicName(s.entity_id) === topic) + : allSeries; + if (series.length === 0) return true; const mapped = this.getMappedTopic(topic); const startYr = this.startYear(); @@ -593,6 +624,7 @@ export class UniTrendParentComponent implements OnInit { patents: '#f59e0b', projects: '#10b981', news: '#ec4899', + [CC_NEWS_COMPOSITE_ID]: '#06b6d4', }; const cleanKey = entityId.toLowerCase().trim(); if (categoryColors[cleanKey]) { @@ -600,10 +632,7 @@ export class UniTrendParentComponent implements OnInit { } } if (this.selectedSearchType() === 'news') { - const topicName = entityId.startsWith('news_topic_') - ? entityId.slice('news_topic_'.length) - : entityId; - return this.getTopicColor(topicName); + return newsSourceColor(entityId); } const colorFn = buildEntityColorIndex( this.primaryInstitution(), @@ -739,7 +768,21 @@ export class UniTrendParentComponent implements OnInit { }; }; - if (type === 'news' || type === 'all' || type === 'patents') { + if (type === 'news') { + const active = this.activeChartTopic() || topics[0] || ''; + const wanted = new Set([ + NEWS_ENTITY_PREFIX + active, + CC_NEWS_ENTITY_PREFIX + active, + ]); + return { + ...raw, + series: raw.series + .filter((s) => wanted.has(s.entity_id)) + .map((s) => ({ ...normalizeTopicData(s), visible: true })), + }; + } + + if (type === 'all' || type === 'patents') { return { ...raw, series: raw.series.map((s) => ({ diff --git a/webapp/src/app/modules/university-ranking/utils/trend.utils.ts b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts index b5f28f9e..d8e720ae 100644 --- a/webapp/src/app/modules/university-ranking/utils/trend.utils.ts +++ b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts @@ -1,5 +1,9 @@ import { TrendSeries, TopicYearlyData } from '../../../api'; -import { CompareItem } from '../models/trend.models'; +import { + CC_NEWS_COMPOSITE_ID, + CC_NEWS_ENTITY_PREFIX, + CompareItem, +} from '../models/trend.models'; /** * Extracts short OpenAlex ID from full URL or string, ensuring uppercase ID prefix (e.g. I62318514, A50012345). @@ -53,9 +57,36 @@ export function findFirstNonEmptyTopic( return topics[0]; } -/** - * Builds deterministic entity color lookup map based on entity order and ID. - */ +const entityColors = [ + '#ec4899', // Pink (Primary UDE) + '#3b82f6', // Blue + '#10b981', // Emerald Green + '#f59e0b', // Amber/Yellow + '#8b5cf6', // Purple + '#06b6d4', // Cyan + '#6366f1', // Indigo + '#ef4444', // Red + '#14b8a6', // Teal + '#f97316', // Orange + '#d946ef', // Fuchsia + '#84cc16', // Lime + '#22c55e', // Green + '#a855f7', // Purple/Fuchsia + '#eab308', // Yellow + '#f43f5e', // Rose +]; + +export function isCcNewsSeries(entityId: string): boolean { + return ( + entityId === CC_NEWS_COMPOSITE_ID || + entityId.startsWith(CC_NEWS_ENTITY_PREFIX) + ); +} + +export function newsSourceColor(entityId: string): string { + return isCcNewsSeries(entityId) ? entityColors[1] : entityColors[0]; +} + export function buildEntityColorIndex( primaryId: string | null, institutions: CompareItem[], @@ -63,25 +94,6 @@ export function buildEntityColorIndex( regions: CompareItem[], authors: CompareItem[], ): (id: string) => string { - const entityColors = [ - '#ec4899', // Pink (Primary UDE) - '#3b82f6', // Blue - '#10b981', // Emerald Green - '#f59e0b', // Amber/Yellow - '#8b5cf6', // Purple - '#06b6d4', // Cyan - '#6366f1', // Indigo - '#ef4444', // Red - '#14b8a6', // Teal - '#f97316', // Orange - '#d946ef', // Fuchsia - '#84cc16', // Lime - '#22c55e', // Green - '#a855f7', // Purple/Fuchsia - '#eab308', // Yellow - '#f43f5e', // Rose - ]; - const colorMap = new Map(); let nextIdx = 0; diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index 679ac38a..60e54789 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -42,7 +42,7 @@ export const uniTrendResolver: ResolveFn = ( const trendDataService = inject(TrendDataService); const searchType = params.get('search_type') || 'publications'; - const fuzzy = params.get('fuzzy') !== 'false'; + const fuzzy = params.get('fuzzy') === 'true'; const treemapNode = params.get('treemapNode'); // Primary institution from user token / credential service From daa4f79ea08a0ad8f0fa0c1dad7a157c213e5c80 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Thu, 6 Aug 2026 16:30:28 +0200 Subject: [PATCH 18/18] fix: author prefetch did not work (moved away from excessive effect() usage, implemented additional methods to avoid missmatches) --- .../services/trend-data.service.ts | 223 +++++++------ .../uni-trend-parent.component.ts | 57 ++-- .../university-ranking/utils/trend.utils.ts | 44 ++- .../src/app/resolvers/uni-trend.resolver.ts | 312 ++++++++++-------- 4 files changed, 358 insertions(+), 278 deletions(-) diff --git a/webapp/src/app/modules/university-ranking/services/trend-data.service.ts b/webapp/src/app/modules/university-ranking/services/trend-data.service.ts index 626102f3..55e47938 100644 --- a/webapp/src/app/modules/university-ranking/services/trend-data.service.ts +++ b/webapp/src/app/modules/university-ranking/services/trend-data.service.ts @@ -1,4 +1,6 @@ import { Injectable, inject, signal } from '@angular/core'; +import { Subject, of } from 'rxjs'; +import { catchError, map, switchMap } from 'rxjs/operators'; import { UniversityRankingsService, PersonsService, @@ -42,6 +44,124 @@ export class TrendDataService { private readonly cacheMap = new Map(); + // RxJS Subjects for cancellation of pending requests + private readonly topTopicsSubject = new Subject<{ + cleanId: string; + entityType: string; + startYear: number; + endYear: number; + searchType: string; + }>(); + + private readonly instSuggestionsSubject = new Subject<{ + topic: string; + countryFilter?: string; + regionFilter?: string; + }>(); + + private readonly recAuthorsSubject = new Subject<{ + topic: string; + primaryInstId: string; + }>(); + + constructor() { + this.topTopicsSubject + .pipe( + switchMap((params) => { + if (!params.cleanId || params.searchType === 'all') { + this.isTopTopicsLoading.set(false); + this.topTopicsData.set([]); + return of([]); + } + return this.apiService + .getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet( + params.cleanId, + params.entityType, + params.startYear, + params.endYear, + params.searchType, + ) + .pipe( + map((res) => + (res.items || []).map((item) => ({ + value: item.count, + name: item.name, + })), + ), + catchError((err) => { + console.error('Failed to load top topics:', err); + this.topTopicsError.set(true); + return of([]); + }), + ); + }), + ) + .subscribe((data) => { + this.topTopicsData.set(data); + this.isTopTopicsLoading.set(false); + }); + + this.instSuggestionsSubject + .pipe( + switchMap((params) => + this.apiService + .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + params.topic, + params.regionFilter, + params.countryFilter, + 6, + ) + .pipe(catchError(() => of([]))), + ), + ) + .subscribe((data: any) => { + this.topSuggestions.set(data || []); + this.isSuggestionsLoading.set(false); + }); + + this.recAuthorsSubject + .pipe( + switchMap((params) => { + const cleanInst = cleanEntityId(params.primaryInstId) || 'I62318514'; + return this.personsApiService + .searchPersonsList( + undefined, + cleanInst, + 'cited_by_count', + 'desc', + [params.topic], + 1, + 6, + undefined, + ) + .pipe( + switchMap((res) => { + if (res.results && res.results.length > 0) { + return of(res.results); + } + return this.personsApiService + .searchPersonsList( + undefined, + undefined, + 'cited_by_count', + 'desc', + [params.topic], + 1, + 6, + undefined, + ) + .pipe(map((gRes) => gRes.results || [])); + }), + catchError(() => of([])), + ); + }), + ) + .subscribe((authors) => { + this.recommendedAuthors.set(authors); + this.isSuggestionsLoading.set(false); + }); + } + private getCacheKey(params: TrendRequestParams): string { return JSON.stringify({ searchType: params.searchType, @@ -93,38 +213,19 @@ export class TrendDataService { ): void { if (!entityId || searchType === 'all') { this.topTopicsData.set([]); + this.isTopTopicsLoading.set(false); return; } this.isTopTopicsLoading.set(true); this.topTopicsError.set(false); - - const cleanId = cleanEntityId(entityId); - - this.apiService - .getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet( - cleanId, - entityType, - startYear, - endYear, - searchType, - ) - .subscribe({ - next: (res) => { - const mapped = (res.items || []).map((item) => ({ - value: item.count, - name: item.name, - })); - this.topTopicsData.set(mapped); - this.isTopTopicsLoading.set(false); - }, - error: (err) => { - console.error('Failed to load top topics:', err); - this.topTopicsError.set(true); - this.isTopTopicsLoading.set(false); - this.topTopicsData.set([]); - }, - }); + this.topTopicsSubject.next({ + cleanId: cleanEntityId(entityId), + entityType, + startYear, + endYear, + searchType, + }); } /** @@ -136,24 +237,7 @@ export class TrendDataService { regionFilter?: string, ): void { this.isSuggestionsLoading.set(true); - - this.apiService - .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( - topic, - regionFilter, - countryFilter, - 6, - ) - .subscribe({ - next: (res: any) => { - this.topSuggestions.set(res || []); - this.isSuggestionsLoading.set(false); - }, - error: () => { - this.topSuggestions.set([]); - this.isSuggestionsLoading.set(false); - }, - }); + this.instSuggestionsSubject.next({ topic, countryFilter, regionFilter }); } /** @@ -161,53 +245,6 @@ export class TrendDataService { */ loadRecommendedAuthors(topic: string, primaryInstId: string): void { this.isSuggestionsLoading.set(true); - const cleanInst = cleanEntityId(primaryInstId) || 'I62318514'; - - this.personsApiService - .searchPersonsList( - undefined, - cleanInst, - 'cited_by_count', - 'desc', - [topic], - 1, - 6, - undefined, - ) - .subscribe({ - next: (res) => { - if (res.results && res.results.length > 0) { - this.recommendedAuthors.set(res.results); - this.isSuggestionsLoading.set(false); - } else { - // Global fallback search across all institutions - this.personsApiService - .searchPersonsList( - undefined, - undefined, - 'cited_by_count', - 'desc', - [topic], - 1, - 6, - undefined, - ) - .subscribe({ - next: (globalRes) => { - this.recommendedAuthors.set(globalRes.results || []); - this.isSuggestionsLoading.set(false); - }, - error: () => { - this.recommendedAuthors.set([]); - this.isSuggestionsLoading.set(false); - }, - }); - } - }, - error: () => { - this.recommendedAuthors.set([]); - this.isSuggestionsLoading.set(false); - }, - }); + this.recAuthorsSubject.next({ topic, primaryInstId }); } } 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 f9dfc8e2..ef57e6dc 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 @@ -557,49 +557,33 @@ export class UniTrendParentComponent implements OnInit { } isTopicEmpty(topic: string): boolean { - const allSeries = this.rawTrendResponse()?.series || []; + const allSeries = + this.trendResponse()?.series || this.rawTrendResponse()?.series || []; if (allSeries.length === 0) return true; const series = this.selectedSearchType() === 'news' ? allSeries.filter((s) => this.seriesTopicName(s.entity_id) === topic) : allSeries; - if (series.length === 0) return true; - - const mapped = this.getMappedTopic(topic); - const startYr = this.startYear(); - const endYr = this.endYear(); - const cId = cleanEntityId(topic); - - for (const s of series) { - if (!s.topic_data) continue; - const keys = [ - topic, - mapped, - cId ? `https://openalex.org/${cId}` : '', - cId, - ].filter(Boolean); - - for (const k of keys) { - const topicItems = s.topic_data[k]; - if (topicItems && topicItems.length > 0) { - const sumRaw = topicItems - .filter((y) => y.year >= startYr && y.year <= endYr) - .reduce((acc, curr) => acc + (curr.raw || 0), 0); - if (sumRaw > 0) return false; - } - } - } - return true; + return isTopicEmptyForSeries( + topic, + series, + this.startYear(), + this.endYear(), + (t) => this.getMappedTopic(t), + ); } findFirstNonEmptyTopic(topics: string[]): string { + const allSeries = + this.trendResponse()?.series || this.rawTrendResponse()?.series || []; if (!topics || topics.length === 0) return ''; - for (const t of topics) { - if (!this.isTopicEmpty(t)) { - return t; - } - } - return topics[0]; + return findFirstNonEmptyTopic( + topics, + allSeries, + this.startYear(), + this.endYear(), + (t) => this.getMappedTopic(t), + ); } isVisible(id: string): boolean { @@ -903,6 +887,11 @@ export class UniTrendParentComponent implements OnInit { } if (resolved.authors && resolved.authors.length > 0) { this.comparisonAuthors.set(resolved.authors); + const currentUrlAuthors = + this.route.snapshot.queryParamMap.getAll('authors'); + if (currentUrlAuthors.length === 0 && type === 'authors') { + this.updateUrlParams(); + } } if (resolved.treemapNode !== undefined) { diff --git a/webapp/src/app/modules/university-ranking/utils/trend.utils.ts b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts index d8e720ae..b0a30958 100644 --- a/webapp/src/app/modules/university-ranking/utils/trend.utils.ts +++ b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts @@ -26,15 +26,42 @@ export function isTopicEmptyForSeries( seriesList: TrendSeries[], startYr: number, endYr: number, + getMappedTopicFn?: (topic: string) => string, ): boolean { if (!seriesList || seriesList.length === 0) return true; + const mapped = getMappedTopicFn ? getMappedTopicFn(topicName) : topicName; + const cleanId = cleanEntityId(topicName); + const cleanMappedId = cleanEntityId(mapped); + const topicLower = topicName.toLowerCase().trim(); + const mappedLower = mapped.toLowerCase().trim(); + for (const s of seriesList) { - const topicItems = s.topic_data?.[topicName] || []; - const filtered = topicItems.filter( - (y) => y.year >= startYr && y.year <= endYr, - ); - const sumRaw = filtered.reduce((acc, curr) => acc + (curr.raw || 0), 0); - if (sumRaw > 0) return false; + if (!s.topic_data) continue; + const entries = Object.entries(s.topic_data); + + for (const [key, topicItems] of entries) { + if (!topicItems || topicItems.length === 0) continue; + + const keyLower = key.toLowerCase().trim(); + const keyClean = cleanEntityId(key); + const revMapped = getMappedTopicFn + ? getMappedTopicFn(key).toLowerCase().trim() + : ''; + + const isMatch = + keyLower === topicLower || + keyLower === mappedLower || + (cleanId && keyClean === cleanId) || + (cleanMappedId && keyClean === cleanMappedId) || + (revMapped && (revMapped === topicLower || revMapped === mappedLower)); + + if (isMatch) { + const sumRaw = topicItems + .filter((y) => y.year >= startYr && y.year <= endYr) + .reduce((acc, curr) => acc + (curr.raw || 0), 0); + if (sumRaw > 0) return false; + } + } } return true; } @@ -47,10 +74,13 @@ export function findFirstNonEmptyTopic( seriesList: TrendSeries[], startYr: number, endYr: number, + getMappedTopicFn?: (topic: string) => string, ): string { if (!topics || topics.length === 0) return ''; for (const t of topics) { - if (!isTopicEmptyForSeries(t, seriesList, startYr, endYr)) { + if ( + !isTopicEmptyForSeries(t, seriesList, startYr, endYr, getMappedTopicFn) + ) { return t; } } diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index 60e54789..887f1bae 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -1,6 +1,6 @@ import { inject } from '@angular/core'; import { ResolveFn } from '@angular/router'; -import { catchError, of, Observable, map, forkJoin } from 'rxjs'; +import { catchError, of, Observable, map, forkJoin, switchMap } from 'rxjs'; import { TrendResponse, UniversityRankingsService, @@ -142,13 +142,6 @@ export const uniTrendResolver: ResolveFn = ( return { id: cleanId, name: parts[1] || parts[0] }; }); - const instIds = - parsedInstitutions.length > 0 - ? parsedInstitutions.map((i) => i.id) - : [primaryInstId]; - const countryIds = parsedCountries.map((c) => c.id); - const regionIds = parsedRegions.map((r) => r.id); - const authorIds = parsedAuthors.map((a) => a.id); const apiService = inject(UniversityRankingsService); const errorService = inject(ErrorService); const personsService = inject(PersonsService, { optional: true }); @@ -159,148 +152,179 @@ export const uniTrendResolver: ResolveFn = ( const regionFilter = parsedRegions.length > 0 ? parsedRegions[0].id : undefined; - const currentParams: TrendRequestParams = { - topics, - keywords, - fuzzy, - institutions: instIds, - countries: countryIds, - regions: regionIds, - authors: authorIds, - searchType, + const fetchTrendAndSuggestions = ( + authors: CompareItem[], + ): Observable => { + const instIds = + parsedInstitutions.length > 0 + ? parsedInstitutions.map((i) => i.id) + : [primaryInstId]; + const countryIds = parsedCountries.map((c) => c.id); + const regionIds = parsedRegions.map((r) => r.id); + const authorIds = authors.map((a) => a.id); + + const currentParams: TrendRequestParams = { + topics, + keywords, + fuzzy, + institutions: instIds, + countries: countryIds, + regions: regionIds, + authors: authorIds, + searchType, + }; + + let trendObs$: Observable; + if (trendDataService.canReuseCache(currentParams)) { + trendObs$ = of(trendDataService.getCachedResponse(currentParams)); + } else { + trendObs$ = apiService + .getTrendApiInseServiceUniversityRankingsTrendGet( + topics, + keywords, + fuzzy, + instIds, + countryIds, + regionIds, + authorIds, + searchType as any, + ) + .pipe( + map((res) => { + trendDataService.updateCache(res, currentParams); + return res; + }), + catchError((err) => { + errorService.setError({ + statusCode: err?.status || 500, + title: 'Visualisierungs-Fehler', + message: 'Trenddaten konnten nicht geladen werden.', + errorDetails: err?.message || String(err), + }); + return of(null); + }), + ); + } + + const topInstObs$ = + searchType !== 'authors' + ? apiService + .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + primaryTopic, + regionFilter, + countryFilter, + 6, + ) + .pipe(catchError(() => of([]))) + : of([]); + + const recAuthorsObs$ = + searchType === 'authors' && personsService + ? personsService + .searchPersonsList( + undefined, + primaryInstId, + 'cited_by_count', + 'desc', + [primaryTopic], + 1, + 6, + undefined, + ) + .pipe( + map((res: any) => res.results || []), + catchError(() => of([])), + ) + : of([]); + + return forkJoin({ + trendResponse: trendObs$, + topSuggestions: topInstObs$, + recommendedAuthors: recAuthorsObs$, + }).pipe( + map(({ trendResponse, topSuggestions, recommendedAuthors }) => { + let initialActiveTopic = primaryTopic; + if ( + trendResponse?.series && + trendResponse.series.length > 0 && + topics.length > 0 + ) { + const nonEmptyTopic = topics.find((t) => + trendResponse.series.some((s) => { + if (!s.topic_data) return false; + const tLower = t.toLowerCase().trim(); + const matchingKey = Object.keys(s.topic_data).find((key) => { + const kLower = key.toLowerCase().trim(); + return ( + kLower === tLower || + (kLower.startsWith('news_topic_') && + kLower.slice('news_topic_'.length) === tLower) + ); + }); + if (!matchingKey) return false; + const yearlyList = s.topic_data[matchingKey]; + if (!yearlyList || !Array.isArray(yearlyList)) return false; + const total = yearlyList.reduce( + (sum, item) => sum + (item.raw || 0), + 0, + ); + return total > 0; + }), + ); + if (nonEmptyTopic) { + initialActiveTopic = nonEmptyTopic; + } + } + + return { + trendResponse, + searchType, + topics, + keywords, + fuzzy, + institutions: parsedInstitutions, + countries: parsedCountries, + regions: parsedRegions, + authors, + initialActiveTopic, + topSuggestions: topSuggestions as any[], + recommendedAuthors: recommendedAuthors as any[], + treemapNode, + }; + }), + ); }; - // Check exact parameter keyed cache - let trendObs$: Observable; - if (trendDataService.canReuseCache(currentParams)) { - trendObs$ = of(trendDataService.getCachedResponse(currentParams)); - } else { - trendObs$ = apiService - .getTrendApiInseServiceUniversityRankingsTrendGet( - topics, - keywords, - fuzzy, - instIds, - countryIds, - regionIds, - authorIds, - searchType as any, + if ( + searchType === 'authors' && + parsedAuthors.length === 0 && + personsService + ) { + return personsService + .searchPersonsList( + undefined, + primaryInstId, + 'cited_by_count', + 'desc', + [primaryTopic], + 1, + 6, + undefined, ) .pipe( - map((res) => { - trendDataService.updateCache(res, currentParams); - return res; - }), - catchError((err) => { - errorService.setError({ - statusCode: err?.status || 500, - title: 'Visualisierungs-Fehler', - message: 'Trenddaten konnten nicht geladen werden.', - errorDetails: err?.message || String(err), - }); - return of(null); + map((res: any) => res.results || []), + catchError(() => of([])), + switchMap((recAuthors) => { + const defaultAuthors: CompareItem[] = recAuthors + .slice(0, 3) + .map((author: any) => ({ + id: cleanEntityId(author.id), + name: author.display_name || 'Unbekannt', + })); + return fetchTrendAndSuggestions(defaultAuthors); }), ); } - const topInstObs$ = - searchType !== 'authors' - ? apiService - .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( - primaryTopic, - regionFilter, - countryFilter, - 6, - ) - .pipe(catchError(() => of([]))) - : of([]); - - const recAuthorsObs$ = - searchType === 'authors' && personsService - ? personsService - .searchPersonsList( - undefined, - primaryInstId, - 'cited_by_count', - 'desc', - [primaryTopic], - 1, - 6, - undefined, - ) - .pipe( - map((res: any) => res.results || []), - catchError(() => of([])), - ) - : of([]); - - return forkJoin({ - trendResponse: trendObs$, - topSuggestions: topInstObs$, - recommendedAuthors: recAuthorsObs$, - }).pipe( - map(({ trendResponse, topSuggestions, recommendedAuthors }) => { - let initialActiveTopic = primaryTopic; - if ( - trendResponse?.series && - trendResponse.series.length > 0 && - topics.length > 0 - ) { - const nonEmptyTopic = topics.find((t) => - trendResponse.series.some((s) => { - if (!s.topic_data) return false; - const tLower = t.toLowerCase().trim(); - const matchingKey = Object.keys(s.topic_data).find((key) => { - const kLower = key.toLowerCase().trim(); - return ( - kLower === tLower || - (kLower.startsWith('news_topic_') && - kLower.slice('news_topic_'.length) === tLower) - ); - }); - if (!matchingKey) return false; - const yearlyList = s.topic_data[matchingKey]; - if (!yearlyList || !Array.isArray(yearlyList)) return false; - const total = yearlyList.reduce( - (sum, item) => sum + (item.raw || 0), - 0, - ); - return total > 0; - }), - ); - if (nonEmptyTopic) { - initialActiveTopic = nonEmptyTopic; - } - } - - if ( - searchType === 'authors' && - parsedAuthors.length === 0 && - recommendedAuthors?.length - ) { - recommendedAuthors.slice(0, 3).forEach((author: any) => { - parsedAuthors.push({ - id: cleanEntityId(author.id), - name: author.display_name || 'Unbekannt', - }); - }); - } - - return { - trendResponse, - searchType, - topics, - keywords, - fuzzy, - institutions: parsedInstitutions, - countries: parsedCountries, - regions: parsedRegions, - authors: parsedAuthors, - initialActiveTopic, - topSuggestions: topSuggestions as any[], - recommendedAuthors: recommendedAuthors as any[], - treemapNode, - }; - }), - ); + return fetchTrendAndSuggestions(parsedAuthors); };
    FördererPublikationenErstautorMitautorLetztautor + Förderer + @if (sortColumn === 'name') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + + Publikationen + @if (sortColumn === 'publications') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + + Erstautor + @if (sortColumn === 'first') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + + Mitautor + @if (sortColumn === 'middle') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + + Letztautor + @if (sortColumn === 'last') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } +
    PatentQuelleJahr + Quelle + @if (sortColumn === 'source') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + + Jahr + @if (sortColumn === 'year') { + {{ + sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward' + }} + } + Erfinder Anmelder
    {{ patent.publication_year ?? '-' }} - {{ getInventorsLabel(patent) }} + + @if (patent.publication_year) { + {{ + patent.publication_year + }} + } @else { + - + } - {{ getAssigneesLabel(patent) }} + + @if (patent.inventors && patent.inventors.length) { +
    + @for ( + inventor of patent.inventors.slice(0, 2); + track inventor + ) { + + person + {{ inventor }} + + } + @if (patent.inventors.length > 2) { + + + person + {{ patent.inventors[2] }} + + @if (patent.inventors.length > 3) { + +{{ patent.inventors.length - 3 }} + } + + } +
    + } @else { + - + } +
    + @if (patent.assignees && patent.assignees.length) { +
    + @for ( + assignee of patent.assignees.slice(0, 2); + track assignee + ) { + + {{ + isAssigneeLikelyPerson(assignee, patent) + ? 'person' + : 'apartment' + }} + {{ assignee }} + + } + @if (patent.assignees.length > 2) { + + + {{ + isAssigneeLikelyPerson( + patent.assignees[2], + patent + ) + ? 'person' + : 'apartment' + }} + {{ patent.assignees[2] }} + + @if (patent.assignees.length > 3) { + +{{ patent.assignees.length - 3 }} + } + + } +
    + } @else { + - + }