Compare commits

...
Author SHA1 Message Date
farajollahi 7e3559432b Merge branch 'dev' into publidher-for-publications
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-20 20:14:33 +02:00
farajollahi cae7e4299b add publisher to publications
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-20 20:01:56 +02:00
12 changed files with 295 additions and 98 deletions
+4
View File
@@ -39,6 +39,7 @@ async def get_author_works(
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
search: str | None = None,
client: OpenAlexWorksSearchClient | None = None,
) -> WorkPage:
search_client = client or OpenAlexWorksSearchClient()
@@ -52,6 +53,7 @@ async def get_author_works(
language=language,
institution_id=institution_id,
topic_id=topic_id,
search=search,
)
elements, total = _parse_full_work_search_response(data)
@@ -791,6 +793,7 @@ async def _search_author_works_data(
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
search: str | None = None,
) -> dict:
try:
return await search_client.search_author_works(
@@ -802,6 +805,7 @@ async def _search_author_works_data(
language=language,
institution_id=institution_id,
topic_id=topic_id,
search=search,
)
except MissingApiKeyError as exc:
logger.error("OpenAlex works Elasticsearch API key is not configured.")
@@ -42,6 +42,7 @@ class OpenAlexWorksSearchClient:
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
search: str | None = None,
) -> dict[str, Any]:
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
filters = self._work_filters(
@@ -80,6 +81,15 @@ class OpenAlexWorksSearchClient:
},
},
})
if search and search.strip():
must_clauses.append({
"match": {
"title": {
"query": search.strip(),
"operator": "and",
},
},
})
return {
"from": (page - 1) * size,
"size": size,
@@ -136,6 +146,7 @@ class OpenAlexWorksSearchClient:
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
search: str | None = None,
) -> dict[str, Any]:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
@@ -157,6 +168,7 @@ class OpenAlexWorksSearchClient:
language=language,
institution_id=institution_id,
topic_id=topic_id,
search=search,
),
)
# logging.debug(f"Response: {response.text}")
+5
View File
@@ -56,6 +56,10 @@ async def get_author_works(
list[str] | None,
Query(description="Filter by OpenAlex topic id. Can be repeated."),
] = None,
search: Annotated[
str | None,
Query(description="Search publication titles."),
] = None,
principal: security.Principal = Depends(
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
),
@@ -69,6 +73,7 @@ async def get_author_works(
language=language,
institution_id=institution_id,
topic_id=topic_id,
search=search,
)
@@ -152,6 +152,26 @@ def test_author_works_query_adds_topic_filter():
]
def test_author_works_query_adds_title_search():
client = OpenAlexWorksSearchClient(api_key="test-key")
query = client.author_works_query(
"A5023888391",
page=1,
size=20,
search="machine learning",
)
assert query["query"]["bool"]["must"][1] == {
"match": {
"title": {
"query": "machine learning",
"operator": "and",
},
},
}
@pytest.mark.anyio
async def test_search_author_works_passes_institution_filter_to_query():
def handler(request: httpx.Request) -> httpx.Response:
+97 -21
View File
@@ -103,27 +103,98 @@ export class WorksService extends BaseService {
);
}
/**
* Returns a page of works for an author.
* @endpoint get /api/works/{author_id}
* @param authorId The author id, for example A5023888391.
* @param page The page number.
* @param size The page size.
* @param publicationYear Filter by publication year. Can be repeated.
* @param type Filter by publication type. Can be repeated.
* @param language Filter by language code. Can be repeated.
* @param institutionId Filter by OpenAlex institution id. Can be repeated.
* @param topicId Filter by OpenAlex topic id. Can be repeated.
* @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 getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorkPage>;
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorkPage>>;
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorkPage>>;
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.');
}
/**
* Returns a page of works for an author.
* @endpoint get /api/works/{author_id}
* @param authorId The author id, for example A5023888391.
* @param page The page number.
* @param size The page size.
* @param publicationYear Filter by publication year. Can be repeated.
* @param type Filter by publication type. Can be repeated.
* @param language Filter by language code. Can be repeated.
* @param institutionId Filter by OpenAlex institution id. Can be repeated.
* @param topicId Filter by OpenAlex topic id. Can be repeated.
* @param search Search publication titles.
* @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 getAuthorWorks(
authorId: string,
page?: number,
size?: number,
publicationYear?: Array<number>,
type?: Array<string>,
language?: Array<string>,
institutionId?: Array<string>,
topicId?: Array<string>,
search?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<WorkPage>;
public getAuthorWorks(
authorId: string,
page?: number,
size?: number,
publicationYear?: Array<number>,
type?: Array<string>,
language?: Array<string>,
institutionId?: Array<string>,
topicId?: Array<string>,
search?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<WorkPage>>;
public getAuthorWorks(
authorId: string,
page?: number,
size?: number,
publicationYear?: Array<number>,
type?: Array<string>,
language?: Array<string>,
institutionId?: Array<string>,
topicId?: Array<string>,
search?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<WorkPage>>;
public getAuthorWorks(
authorId: string,
page?: number,
size?: number,
publicationYear?: Array<number>,
type?: Array<string>,
language?: Array<string>,
institutionId?: Array<string>,
topicId?: Array<string>,
search?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getAuthorWorks.',
);
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -160,6 +231,11 @@ export class WorksService extends BaseService {
<any>element, 'topic_id');
})
}
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>search,
'search',
);
let localVarHeaders = this.defaultHeaders;
+22
View File
@@ -14,6 +14,7 @@ import { bundSingleProjectResolver } from './resolvers/bund-single-project-resol
import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page.resolver';
import { cordisEuProjectsFundingResolver } from './resolvers/cordis-eu-projects-funding.resolver';
import { fundingProjectPageResolver } from './resolvers/funding-project-page.resolver';
import { publicationsResolver } from './resolvers/publications.resolver';
export const routes: Routes = [
{
@@ -162,6 +163,27 @@ export const routes: Routes = [
import('./modules/person-publications/person-publications.component').then(
(mod) => mod.PersonPublicationsComponent,
),
resolve: {
publicationPage: publicationsResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = [
'publicationPage',
'publicationPageSize',
'publicationYear',
'publicationType',
'publicationLanguage',
'publicationInstitutionId',
'publicationTopicId',
'publicationSearch',
];
return keys.some(
(key) =>
from.queryParamMap.getAll(key).join(',') !==
to.queryParamMap.getAll(key).join(','),
);
},
},
{
path: 'network',
@@ -5,6 +5,16 @@
</div>
<div class="publication-filter-stack">
<form class="publication-filters" [formGroup]="filterForm">
<mat-form-field class="publication-search">
<mat-icon matPrefix>search</mat-icon>
<input
type="search"
matInput
[formControl]="publicationSearchControl"
placeholder="Publikationen suchen"
aria-label="Publikationen suchen" />
</mat-form-field>
<mat-form-field>
<mat-select
placeholder="Jahr"
@@ -141,12 +151,6 @@
</div>
<div class="table-wrap">
@if (loading) {
<div class="loading">
<mat-spinner diameter="36"></mat-spinner>
</div>
}
<table mat-table [dataSource]="publications" class="mat-elevation-z2">
<ng-container matColumnDef="title">
<th mat-header-cell *matHeaderCellDef>Titel</th>
@@ -180,12 +184,27 @@
</ng-container>
<ng-container matColumnDef="language">
<th mat-header-cell *matHeaderCellDef>Sprache / Quelle</th>
<th mat-header-cell *matHeaderCellDef>Sprache</th>
<td mat-cell *matCellDef="let publication">
{{ publication.language || '-' }}
</td>
</ng-container>
<ng-container matColumnDef="publisher">
<th mat-header-cell *matHeaderCellDef>Publisher</th>
<td mat-cell *matCellDef="let publication">
@if (publication.primary_location?.source?.display_name) {
<span
class="publication-source"
[title]="publication.primary_location.source.display_name">
{{ publication.primary_location.source.display_name }}
</span>
} @else {
<span class="empty-text">-</span>
}
</td>
</ng-container>
<ng-container matColumnDef="institutions">
<th mat-header-cell *matHeaderCellDef>Institutionen</th>
<td mat-cell *matCellDef="let publication">
@@ -244,7 +263,7 @@
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
@if (!loading && publications.length === 0) {
@if (publications.length === 0) {
<div class="empty-state">Keine Publikationen gefunden.</div>
}
</div>
@@ -46,6 +46,10 @@ h2 {
width: 150px;
}
.publication-filters .publication-search {
width: 320px;
}
.publication-filters .institution-filter,
.publication-filters .topic-filter {
width: 320px;
@@ -164,7 +168,7 @@ h2 {
table {
width: 100%;
min-width: 1120px;
min-width: 1240px;
border-collapse: separate;
border-spacing: 0 10px;
overflow: hidden;
@@ -193,15 +197,6 @@ a.title:hover {
font-size: 12px;
}
.loading {
position: absolute;
inset: 0;
z-index: 1;
display: grid;
place-items: center;
background: rgba(255, 255, 255, 0.65);
}
.empty-state {
padding: 28px;
text-align: center;
@@ -213,6 +208,14 @@ a.title:hover {
color: rgba(0, 0, 0, 0.54);
}
.publication-source {
display: inline-block;
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.topic-chips {
display: flex;
flex-wrap: wrap;
@@ -336,7 +339,8 @@ mat-paginator {
}
.publication-filters .institution-filter,
.publication-filters .topic-filter {
.publication-filters .topic-filter,
.publication-filters .publication-search {
width: 100%;
}
@@ -18,8 +18,6 @@ import {
MatPaginatorModule,
PageEvent,
} from '@angular/material/paginator';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
@@ -37,9 +35,8 @@ import {
switchMap,
} from 'rxjs';
import { Work, WorksService } from '../../api';
import { Work, WorkPage, WorksService } from '../../api';
import { PaginationService } from '../../shared/services/pagination.service';
import { createLoadError } from '../../shared/utils/errorHandler';
import { ChipComponent } from '../../shared/ui/chip/chip.component';
interface InstitutionAutocompleteOption {
@@ -73,6 +70,7 @@ interface TopicAutocompleteResponse {
interface PublicationFilterQueryState {
pageIndex: number;
pageSize: number;
search: string;
publicationYears: number[];
types: string[];
languages: string[];
@@ -90,9 +88,7 @@ interface PublicationFilterQueryState {
MatFormFieldModule,
MatInputModule,
MatPaginatorModule,
MatProgressSpinnerModule,
MatSelectModule,
MatSnackBarModule,
MatTableModule,
ReactiveFormsModule,
RouterLink,
@@ -109,21 +105,21 @@ export class PersonPublicationsComponent implements OnInit {
'type',
'year',
'language',
'publisher',
'institutions',
'topics',
'citations',
];
publications: Work[] = [];
total = 0;
loading = false;
institutionLookupLoading = false;
topicLookupLoading = false;
authorId = '';
currentPageIndex = 0;
institutionOptions: InstitutionAutocompleteOption[] = [];
selectedInstitutions: InstitutionAutocompleteOption[] = [];
topicOptions: TopicAutocompleteOption[] = [];
selectedTopics: TopicAutocompleteOption[] = [];
readonly publicationSearchControl = new FormControl('', { nonNullable: true });
readonly institutionSearchControl = new FormControl<
string | InstitutionAutocompleteOption
>('', { nonNullable: true });
@@ -151,6 +147,7 @@ export class PersonPublicationsComponent implements OnInit {
institutionNames: 'publicationInstitutionName',
topicIds: 'publicationTopicId',
topicNames: 'publicationTopicName',
search: 'publicationSearch',
} as const;
readonly typeOptions = [
@@ -186,57 +183,19 @@ export class PersonPublicationsComponent implements OnInit {
private readonly workService: WorksService,
private readonly httpClient: HttpClient,
public readonly paginationService: PaginationService,
private readonly snackBar: MatSnackBar,
) {}
ngOnInit(): void {
this.setupPublicationSearch();
this.setupInstitutionAutocomplete();
this.setupTopicAutocomplete();
const parentParamMap = this.route.parent?.paramMap;
if (!parentParamMap) return;
combineLatest([parentParamMap, this.route.queryParamMap])
combineLatest([this.route.data, this.route.queryParamMap])
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(([params, queryParams]) => {
this.authorId = params.get('id') ?? '';
.subscribe(([data, queryParams]) => {
const queryState = this.parsePublicationFilterQueryParams(queryParams);
this.applyPublicationFilterQueryState(queryState);
this.load(queryState.pageIndex, queryState.pageSize);
});
}
load(pageIndex = 0, pageSize = this.paginationService.selection): void {
console.log('Loading publications for author ID:', this.authorId);
if (!this.authorId) return;
this.loading = true;
this.workService
.getAuthorWorks(
this.authorId,
pageIndex + 1,
pageSize,
this.filters().publicationYears,
this.filters().types,
this.filters().languages,
this.selectedInstitutionIds(),
this.selectedTopicIds(),
)
.subscribe({
next: (page) => {
this.publications = page.elements ?? [];
this.total = page.total ?? 0;
this.loading = false;
},
error: (error) => {
this.loading = false;
createLoadError(
this.snackBar,
() => this.load(pageIndex, pageSize),
'Publikationen konnten nicht geladen werden',
)(error);
},
this.applyPublicationPage(data['publicationPage'] as WorkPage);
});
}
@@ -266,6 +225,7 @@ export class PersonPublicationsComponent implements OnInit {
});
this.selectedInstitutions = [];
this.selectedTopics = [];
this.publicationSearchControl.setValue('', { emitEvent: false });
this.institutionOptions = [];
this.topicOptions = [];
this.institutionSearchControl.setValue('', { emitEvent: false });
@@ -280,6 +240,7 @@ export class PersonPublicationsComponent implements OnInit {
[this.queryParamKeys.institutionNames]: null,
[this.queryParamKeys.topicIds]: null,
[this.queryParamKeys.topicNames]: null,
[this.queryParamKeys.search]: null,
});
}
@@ -379,6 +340,27 @@ export class PersonPublicationsComponent implements OnInit {
};
}
private applyPublicationPage(page: WorkPage): void {
this.publications = page.elements ?? [];
this.total = page.total ?? 0;
}
private setupPublicationSearch(): void {
this.publicationSearchControl.valueChanges
.pipe(
map((value) => value.trim()),
debounceTime(350),
distinctUntilChanged(),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((search) => {
this.updatePublicationFilterQueryParams({
[this.queryParamKeys.page]: 1,
[this.queryParamKeys.search]: search || null,
});
});
}
private setupInstitutionAutocomplete(): void {
this.institutionSearchControl.valueChanges
.pipe(
@@ -535,6 +517,7 @@ export class PersonPublicationsComponent implements OnInit {
queryParams.get(this.queryParamKeys.pageSize),
this.paginationService.selection,
),
search: queryParams.get(this.queryParamKeys.search)?.trim() ?? '',
publicationYears: this.parseNumberParams(
queryParams.getAll(this.queryParamKeys.years),
),
@@ -562,6 +545,9 @@ export class PersonPublicationsComponent implements OnInit {
this.paginationService.selection = queryState.pageSize;
this.selectedInstitutions = queryState.institutions;
this.selectedTopics = queryState.topics;
this.publicationSearchControl.setValue(queryState.search, {
emitEvent: false,
});
this.filterForm.setValue(
{
publicationYears: queryState.publicationYears,
@@ -107,15 +107,17 @@
<div class="content-grid">
<main>
@if (abstractText(); as abstract) {
<section class="card abstract-card">
<div class="section-title">
<mat-icon>subject</mat-icon>
<h2>Abstract</h2>
</div>
<section class="card abstract-card">
<div class="section-title">
<mat-icon>subject</mat-icon>
<h2>Abstract</h2>
</div>
@if (abstractText(); as abstract) {
<p>{{ abstract }}</p>
</section>
}
} @else {
<p class="empty">Kein Abstract verfügbar.</p>
}
</section>
<section class="card">
<div class="section-title">
@@ -261,6 +263,12 @@
<dt>Sprache</dt>
<dd>{{ publication.language || '-' }}</dd>
</div>
<div>
<dt>Publisher</dt>
<dd>
{{ publication.primary_location?.source?.display_name || '-' }}
</dd>
</div>
<div>
<dt>Open Access</dt>
<dd>{{ openAccessLabel() }}</dd>
@@ -73,6 +73,11 @@ export class PublicationDetailComponent implements OnInit {
}
abstractText(): string | null {
const plainAbstract = (
this.publication as (Work & { abstract?: string | null }) | null
)?.abstract?.trim();
if (plainAbstract) return plainAbstract;
const index = this.publication?.abstract_inverted_index;
if (!index || typeof index !== 'object') return null;
@@ -0,0 +1,36 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { WorkPage, WorksService } from '../api';
import { PaginationService } from '../shared/services/pagination.service';
export const publicationsResolver: ResolveFn<WorkPage> = (route) => {
const authorId = route.parent?.paramMap.get('id');
if (!authorId) {
throw new Error('Author ID is required to resolve publications');
}
const params = route.queryParamMap;
const pageSize = inject(PaginationService).selection;
return inject(WorksService).getAuthorWorks(
authorId,
parsePositiveInteger(params.get('publicationPage'), 1),
parsePositiveInteger(params.get('publicationPageSize'), pageSize),
params
.getAll('publicationYear')
.map(Number)
.filter(Number.isInteger),
params.getAll('publicationType').filter(Boolean),
params.getAll('publicationLanguage').filter(Boolean),
params.getAll('publicationInstitutionId').filter(Boolean),
params.getAll('publicationTopicId').filter(Boolean),
params.get('publicationSearch')?.trim() || undefined,
);
};
function parsePositiveInteger(value: string | null, fallback: number): number {
const parsedValue = Number(value);
return Number.isInteger(parsedValue) && parsedValue > 0
? parsedValue
: fallback;
}