feat(topic): added topic detail page with publication table
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
Mats Paul Tončik
2026-07-26 13:15:29 +02:00
parent 3ef8c28191
commit def210b4b9
12 changed files with 483 additions and 20 deletions
+59
View File
@@ -218,6 +218,65 @@ async def get_institution_works(
)
@router.get(
"/topic/{raw_oa_topic_id}",
operation_id="getTopicWorkPage",
summary="Returns a paginated list of works for a given topic based on its ID.",
)
async def get_topic_works(
raw_oa_topic_id: Annotated[str, Path(description="The raw OpenAlex topic id.")],
page: Annotated[
int, Query(description="The page number to retrieve. (0-based)", ge=0)
] = 0,
size: Annotated[
int,
Query(description="The number of works to retrieve per page.", ge=1, le=100),
] = 10,
title: Annotated[
str, Query(description="A title to filter by (partial matches allowed).")
] = "",
publication_years: Annotated[
list[int] | None,
Query(description="A list of publication years to filter by."),
] = None,
publication_types: Annotated[
list[str] | None,
Query(description="A list of publication types to filter by."),
] = None,
author_ids: Annotated[
list[str] | None,
Query(description="A list of author IDs to filter by."),
] = None,
institution_ids: Annotated[
list[str] | None,
Query(description="A list of institution IDs to filter by."),
] = None,
language_codes: Annotated[
list[str] | None,
Query(description="A list of language codes to filter by."),
] = None,
sort_by: Annotated[
WorkSortBy, Query(description="The field to sort by.")
] = WorkSortBy.PUBLICATION_YEAR,
sort_order: Annotated[
SortDirection, Query(description="The order to sort by.")
] = SortDirection.DESCENDING,
) -> WorkPageV2:
return await works_service.get_topic_works(
raw_oa_topic_id=raw_oa_topic_id,
page=page,
size=size,
title=title,
publication_years=publication_years or [],
publication_types=publication_types or [],
author_ids=author_ids or [],
institution_ids=institution_ids or [],
language_codes=language_codes or [],
sort_by=sort_by,
sort_order=sort_order,
)
@router.get(
"/classification/work/{raw_oa_work_id}",
operation_id="getWorkClassificationByWorkId",
+82 -14
View File
@@ -60,6 +60,19 @@ def _institutions_nested_query(institution_ids: list[str]) -> dict:
}
def _topics_nested_query(topic_ids: list[str]) -> dict:
"""Returns a nested query for filtering works by a list of topic IDs.
Args:
topic_ids (list[str]): A list of topic IDs to filter by.
Returns:
dict: A nested query for filtering works by the specified topic IDs.
"""
prefixed = [_prefix_id(tid) for tid in topic_ids]
return {"nested": {"path": "topics", "query": {"terms": {"topics.id": prefixed}}}}
def _title_query(title: str) -> dict:
"""Returns a query for filtering works by title using a multi-match query.
@@ -87,7 +100,6 @@ def _apply_common_filters(
publication_years: list[int] | None,
publication_types: list[str] | None,
language_codes: list[str] | None,
topic_ids: list[str] | None,
title: str | None = None,
) -> None:
"""Applies common filters to the provided list of must conditions for filtering works.
@@ -106,10 +118,6 @@ def _apply_common_filters(
must.append({"terms": {"type": publication_types}})
if language_codes:
must.append({"terms": {"language": language_codes}})
if topic_ids:
must.append(
{"nested": {"path": "topics", "query": {"terms": {"topics.id": topic_ids}}}}
)
if title and len(title.strip()) > 0:
must.append(_title_query(title))
@@ -174,6 +182,7 @@ async def get_works(
size: int,
raw_oa_author_id: str | None = None,
raw_oa_institution_id: str | None = None,
raw_oa_topic_id: str | None = None,
title: str | None = None,
author_ids: list[str] | None = None,
institution_ids: list[str] | None = None,
@@ -191,6 +200,7 @@ async def get_works(
size (int): The number of results per page.
raw_oa_author_id (Optional[str], optional): The ID of the author to filter by. Defaults to None.
raw_oa_institution_id (Optional[str], optional): The ID of the institution to filter by. Defaults to None.
raw_oa_topic_id (Optional[str], optional): The ID of the topic to filter by. Defaults to None.
title (Optional[str], optional): The title of the works to filter by. Defaults to None.
author_ids (Optional[List[str]], optional): A list of author IDs to filter by. Defaults to None.
institution_ids (Optional[List[str]], optional): A list of institution IDs to filter by. Defaults to None.
@@ -202,33 +212,44 @@ async def get_works(
sort_order (SortDirection, optional): The direction to sort in. Defaults to SortDirection.DESCENDING.
Raises:
ValueError: If neither raw_oa_author_id nor raw_oa_institution_id is provided.
ValueError: If neither raw_oa_author_id nor raw_oa_institution_id nor raw_oa_topic_id is provided.
Returns:
WorkPageV2: The page of works matching the criteria.
"""
if not raw_oa_author_id and not raw_oa_institution_id:
if not raw_oa_author_id and not raw_oa_institution_id and not raw_oa_topic_id:
raise ValueError(
"get_works requires at least one of raw_oa_author_id or raw_oa_institution_id"
"get_works requires at least one of raw_oa_author_id or raw_oa_institution_id or raw_oa_topic_id"
)
must: list = []
if raw_oa_author_id:
must.append(_authors_nested_query([raw_oa_author_id]))
must.append(_authors_nested_query(author_ids=[raw_oa_author_id]))
elif author_ids:
must.append(_authors_nested_query(author_ids))
must.append(_authors_nested_query(author_ids=author_ids))
if raw_oa_institution_id:
must.append(_institutions_nested_query([raw_oa_institution_id]))
must.append(_institutions_nested_query(institution_ids=[raw_oa_institution_id]))
elif institution_ids:
must.append(_institutions_nested_query(institution_ids))
must.append(_institutions_nested_query(institution_ids=institution_ids))
if raw_oa_topic_id:
must.append(_topics_nested_query(topic_ids=[raw_oa_topic_id]))
elif topic_ids:
must.append(_topics_nested_query(topic_ids=topic_ids))
_apply_common_filters(
must, publication_years, publication_types, language_codes, topic_ids, title
must=must,
publication_years=publication_years,
publication_types=publication_types,
language_codes=language_codes,
title=title,
)
return await _execute_works_search(must, page, size, sort_by, sort_order)
return await _execute_works_search(
must=must, page=page, size=size, sort_by=sort_by, sort_order=sort_order
)
async def get_works_by_keywords(
@@ -486,6 +507,53 @@ async def get_institution_works(
)
async def get_topic_works(
raw_oa_topic_id: str,
page: int,
size: int,
title: str = "",
publication_years: list[int] | None = None,
publication_types: list[str] | None = None,
institution_ids: list[str] | None = None,
author_ids: list[str] | None = None,
language_codes: list[str] | None = None,
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
sort_order: SortDirection = SortDirection.DESCENDING,
) -> WorkPageV2:
"""Retrieves works for a specific topic based on the provided criteria.
Args:
raw_oa_topic_id (str): The ID of the topic for whom to retrieve works.
page (int): The page number of the results to retrieve.
size (int): The number of results per page.
title (str, optional): The title of the works to filter by. Defaults to "".
publication_years (Optional[List[int]], optional): A list of publication years to filter by. Defaults to None.
publication_types (Optional[List[str]], optional): A list of publication types to filter by. Defaults to None.
institution_ids (Optional[List[str]], optional): A list of institution IDs to filter by. Defaults to None.
author_ids (Optional[List[str]], optional): A list of author IDs to filter by. Defaults to None.
language_codes (Optional[List[str]], optional): A list of language codes to filter by. Defaults to None.
sort_by (WorkSortBy, optional): The field by which to sort the results. Defaults to WorkSortBy.PUBLICATION_YEAR.
sort_order (SortDirection, optional): The direction to sort in. Defaults to SortDirection.DESCENDING.
Returns:
WorkPageV2: The page of works matching the criteria.
"""
return await get_works(
page=page,
size=size,
raw_oa_topic_id=raw_oa_topic_id,
title=title,
institution_ids=institution_ids,
author_ids=author_ids,
publication_years=publication_years,
publication_types=publication_types,
language_codes=language_codes,
sort_by=sort_by,
sort_order=sort_order,
)
async def get_work(raw_oa_work_id: str, source: list[str] | None = None) -> Work | None:
"""Retrieves a work based on its OpenAlex ID.
+108
View File
@@ -399,6 +399,114 @@ export class WorksV2Service extends BaseService {
);
}
/**
* Returns a paginated list of works for a given topic based on its ID.
* @endpoint get /api/works/v2/topic/{raw_oa_topic_id}
* @param rawOaTopicId The raw OpenAlex topic id.
* @param page The page number to retrieve. (0-based)
* @param size The number of works to retrieve per page.
* @param title A title to filter by (partial matches allowed).
* @param publicationYears A list of publication years to filter by.
* @param publicationTypes A list of publication types to filter by.
* @param authorIds A list of author IDs to filter by.
* @param institutionIds A list of institution IDs to filter by.
* @param languageCodes A list of language codes to filter by.
* @param sortBy The field to sort by.
* @param sortOrder The order to sort by.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getTopicWorkPage(rawOaTopicId: string, page?: number, size?: number, title?: string, publicationYears?: Array<number>, publicationTypes?: Array<string>, authorIds?: Array<string>, institutionIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorkPageV2>;
public getTopicWorkPage(rawOaTopicId: string, page?: number, size?: number, title?: string, publicationYears?: Array<number>, publicationTypes?: Array<string>, authorIds?: Array<string>, institutionIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorkPageV2>>;
public getTopicWorkPage(rawOaTopicId: string, page?: number, size?: number, title?: string, publicationYears?: Array<number>, publicationTypes?: Array<string>, authorIds?: Array<string>, institutionIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorkPageV2>>;
public getTopicWorkPage(rawOaTopicId: string, page?: number, size?: number, title?: string, publicationYears?: Array<number>, publicationTypes?: Array<string>, authorIds?: Array<string>, institutionIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (rawOaTopicId === null || rawOaTopicId === undefined) {
throw new Error('Required parameter rawOaTopicId was null or undefined when calling getTopicWorkPage.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>size, 'size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>title, 'title');
if (publicationYears) {
publicationYears.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'publication_years');
})
}
if (publicationTypes) {
publicationTypes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'publication_types');
})
}
if (authorIds) {
authorIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'author_ids');
})
}
if (institutionIds) {
institutionIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'institution_ids');
})
}
if (languageCodes) {
languageCodes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'language_codes');
})
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortBy, 'sort_by');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortOrder, 'sort_order');
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/works/v2/topic/${this.configuration.encodeParam({name: "rawOaTopicId", value: rawOaTopicId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<WorkPageV2>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns the classifications of a work based on its ID.
* @endpoint get /api/works/v2/classification/work/{raw_oa_work_id}
+29
View File
@@ -35,6 +35,7 @@ import { UniTrendParentComponent } from './modules/university-ranking/uni-trend-
import {
RESOLVING_WORK_PAGE_FOR,
workPageResolver,
workQueryParamKeys,
} from './resolvers/work-page.resolver';
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
@@ -749,6 +750,34 @@ export const routes: Routes = [
resolve: {
topic: topicResolver,
},
runGuardsAndResolvers: 'paramsChange',
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'publications',
},
{
path: 'publications',
loadComponent: () =>
import('./modules/topic-publications/topic-publications.component').then(
(mod) => mod.TopicPublicationsComponent,
),
runGuardsAndResolvers: (from, to) => {
return Object.values(workQueryParamKeys).some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
resolve: {
workPage: workPageResolver,
selectedAuthorsPage: selectedAuthorsResolver,
selectedInstitutionsPage: selectedInstitutionsResolver,
},
data: {
resolvingFor: RESOLVING_WORK_PAGE_FOR.TOPIC,
},
},
],
},
{
path: 'projects',
@@ -0,0 +1,15 @@
<app-publication-filter
[selectedAuthorsPage]="selectedAuthorsPage()"
[selectedInstitutionsPage]="selectedInstitutionsPage()"
[showTopicFilter]="false" />
<app-publication-table
[page]="workPage()"
[authorFilterEnabled]="true"
[institutionFilterEnabled]="true" />
<app-query-param-paginator
[total]="total()"
queryParamPageKey="page"
queryParamSizeKey="size"
[pageSizeOptions]="[10, 25, 50]" />
@@ -0,0 +1,20 @@
import { Component, computed, input } from '@angular/core';
import { AuthorPage, InstitutionPageV2, WorkPageV2 } from '../../api';
import { PublicationFilterComponent } from "../../shared/ui/publication-filters/publication-filters.component";
import { PublicationTableComponent } from "../../shared/ui/publication-table/publication-table.component";
import { QueryParamPaginatorComponent } from "../../shared/ui/query-param-paginator/query-param-paginator.component";
@Component({
selector: 'app-topic-publications',
imports: [PublicationFilterComponent, PublicationTableComponent, QueryParamPaginatorComponent],
templateUrl: './topic-publications.component.html',
styleUrl: './topic-publications.component.scss',
})
export class TopicPublicationsComponent {
workPage = input.required<WorkPageV2>();
selectedAuthorsPage = input.required<AuthorPage>();
selectedInstitutionsPage = input.required<InstitutionPageV2>();
total = computed<number>(() => this.workPage().total ?? 0);
}
@@ -1 +1,52 @@
<p>topic works!</p>
<div class="content">
@if (topic(); as topic) {
<div>
<h2>{{ topic.display_name }}</h2>
<span class="subtitle">{{ subtitle() }}</span>
</div>
<mat-divider />
<p style="width: 50%">{{ description() }}</p>
<mat-divider />
<div class="metrics">
<div class="metric-item">
<mat-icon>menu_book</mat-icon>
<span
>{{
topic.works_count | number: undefined : 'de'
}}
Publikationen</span
>
</div>
<div class="metric-item">
<mat-icon>format_quote</mat-icon>
<span
>{{
topic.cited_by_count | number: undefined : 'de'
}}
Zitationen</span
>
</div>
</div>
}
</div>
<mat-divider />
<mat-tab-nav-panel #tabPanel>
<nav mat-tab-nav-bar [tabPanel]="tabPanel">
@for (link of links; track link.path) {
<a
mat-tab-link
[routerLink]="link.path"
[queryParams]="link.queryParams"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive"
[disabled]="link.disabled">
{{ link.label }}
</a>
}
</nav>
<div class="outlet-container">
<router-outlet />
</div>
</mat-tab-nav-panel>
@@ -0,0 +1,36 @@
.content {
--topic-border: color-mix(in srgb, hsl(var(--topic-color)) 72%, #ffffff);
--topic-background: color-mix(in srgb, hsl(var(--topic-color)) 8%, #ffffff);
padding: 2rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
background-color: var(--topic-background);
--mat-divider-color: var(--topic-border);
}
.outlet-container {
margin: 2rem;
}
.subtitle {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--sg-text-muted);
}
.metrics {
display: flex;
flex-direction: column;
gap: 0.5rem;
font-size: 0.875rem;
}
.metric-item {
display: flex;
align-items: center;
gap: 0.25rem;
color: var(--sg-text-muted);
}
@@ -1,11 +1,64 @@
import { Component } from '@angular/core';
import { Component, computed, input } from '@angular/core';
import { Topic } from '../../api';
import { MatTabsModule } from '@angular/material/tabs';
import { RouterModule } from '@angular/router';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { DecimalPipe } from '@angular/common';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
@Component({
host: {
'[style.--topic-color]': 'color()',
},
selector: 'app-topic',
imports: [],
imports: [
MatTabsModule,
RouterModule,
MatDividerModule,
MatIconModule,
DecimalPipe,
],
templateUrl: './topic.component.html',
styleUrl: './topic.component.scss',
})
export class TopicComponent {
topic = input.required<Topic>();
links = [
{
label: 'Publikationen',
path: 'publications',
disabled: false,
queryParams: {
page: 0,
size: 10,
title: '',
sort_by: 'title',
sort_direction: 'asc',
},
},
];
subtitle = computed(() => {
return `${this.topic().subfield?.display_name} - ${this.topic().field?.display_name} - ${this.topic().domain?.display_name}`;
});
description = computed(() => {
return this.topic().description || 'Keine Beschreibung verfügbar';
});
color = computed<string>(() => {
const topic = this.topic();
return topicHierarchyColor({
id: topic.id ?? undefined,
name: topic.display_name ?? undefined,
field_id: topic.field?.id ?? undefined,
field_name: topic.field?.display_name ?? undefined,
domain_id: topic.domain?.id ?? undefined,
domain_name: topic.domain?.display_name ?? undefined,
})
.replace('hsl(', '')
.replace(')', '');
});
}
@@ -10,6 +10,7 @@ const RESOLVING_WORK_PAGE_FOR_KEY = 'resolvingFor';
export const RESOLVING_WORK_PAGE_FOR = {
PERSON: 'PERSON',
INSTITUTION: 'INSTITUTION',
TOPIC: 'TOPIC',
KEYWORDS_SEARCH: 'KEYWORDS_SEARCH',
} as const;
@@ -151,6 +152,29 @@ export const workPageResolver: ResolveFn<WorkPageV2> = (
sortBy,
sortDirection,
);
} else if (resolvingFor === RESOLVING_WORK_PAGE_FOR.TOPIC) {
const topicId =
route.parent?.paramMap.get('topicId') || route.paramMap.get('topicId');
if (!topicId) {
throw new Error('Topic ID is required to resolve topic works.');
}
const authorIds = route.queryParamMap.getAll(workQueryParamKeys.authorId);
const institutionIds = route.queryParamMap.getAll(
workQueryParamKeys.institutionId,
);
return inject(WorksV2Service).getTopicWorkPage(
topicId,
page,
size,
title,
publicationYears,
publicationTypes,
authorIds,
institutionIds,
languages,
sortBy,
sortDirection,
);
} else {
throw new Error(`Unknown resolvingFor value: ${resolvingFor}`);
}
@@ -41,11 +41,11 @@
<mat-card-actions class="card-actions">
<a
class="card-action"
[routerLink]="['/topic', stripOpenAlexId(topic.id)]"
[routerLink]="['/topic', stripOpenAlexId(topic.id), 'publications']"
matButton="outlined"
(click)="$event.stopPropagation()">
<mat-icon>info</mat-icon>
Übersicht
<mat-icon>menu_book</mat-icon>
Publikationen
</a>
</mat-card-actions>
</mat-card-footer>