diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index a4b46494..a9864cf2 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -1,5 +1,5 @@ from enum import StrEnum -from typing import List, Literal, Optional +from typing import List, Optional from pydantic import BaseModel, Field @@ -8,6 +8,24 @@ from inse.models.eu_project import EuProject from inse.models.cordis_eu_project import CordisEuProject +class ProjectType(StrEnum): + BUND = "bund" + EU = "eu" + DFG = "dfg" + + +class ProjectsSortBy(StrEnum): + TITLE = "title" + FUNDING_START = "funding_start" + FUNDING_END = "funding_end" + FUNDING_AMOUNT = "funding_amount" + + +class SortDirection(StrEnum): + ASC = "asc" + DESC = "desc" + + class Page(BaseModel): page: int = Field(default=0, description="The current page number.") size: int = Field(default=20, description="The requested page size.") @@ -78,7 +96,7 @@ class DfgProjectPage(Page): class InstitutionFunderSummary(BaseModel): - type: Literal["bund", "eu", "dfg"] = Field( + type: ProjectType = Field( description="The type of funding data (e.g., 'bund', 'eu', 'dfg')." ) funding_per_year: dict = Field( @@ -91,24 +109,6 @@ class InstitutionFunderSummary(BaseModel): ) -class ProjectType(StrEnum): - BUND = "bund" - EU = "eu" - DFG = "dfg" - - -class ProjectsSortBy(StrEnum): - TITLE = "title" - FUNDING_START = "funding_start" - FUNDING_END = "funding_end" - FUNDING_AMOUNT = "funding_amount" - - -class SortDirection(StrEnum): - ASC = "asc" - DESC = "desc" - - class ProjectsFilteringProperties(BaseModel): project_type: ProjectType = Field(description="The type of projects to filter by.") page: int = Field(description="The page number for pagination.") diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 82877854..65821993 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -80,7 +80,7 @@ async def search_bund_projects( "/institution/bund/funding-over-time", summary="Get funding over time for bund projects.", description="Returns the funding over time for bund projects associated with the specified institution.", - operation_id="getBundFundingOverTime", + operation_id="getInstitutionBundProjectsFundingOverTime", responses={ status.HTTP_200_OK: { "description": "Successful Response", @@ -90,21 +90,21 @@ async def search_bund_projects( }, response_model_by_alias=False, ) -async def get_bund_funding_over_time( +async def get_institution_bund_projects_funding_over_time( bund_search_client: Annotated[ BundProjectsSearchClient, Depends(get_bund_search_client) ], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], - institution_id: Annotated[ + raw_oa_institution_id: Annotated[ str, Query(description="The institution ID to filter by.") ], ) -> InstitutionFunderSummary: - return await projects_service.get_institution_bund_funding_over_time( + return await projects_service.get_institution_bund_projects_funding_over_time( bund_search_client=bund_search_client, institutions_search_client=institutions_search_client, - institution_id=institution_id, + raw_oa_institution_id=raw_oa_institution_id, ) @@ -139,6 +139,36 @@ async def search_cordis_eu_projects( ) +@router.get( + "/institution/eu/funding-over-time", + summary="Get funding over time for EU projects.", + description="Returns the funding over time for EU projects associated with the specified institution.", + operation_id="getInstitutionCordisEuProjectsFundingOverTime", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": InstitutionFunderSummary, + }, + status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + }, + response_model_by_alias=False, +) +async def get_institution_cordis_eu_projects_funding_over_time( + eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)], + institutions_search_client: Annotated[ + InstitutionsSearchClient, Depends(get_institutions_search_client) + ], + raw_oa_institution_id: Annotated[ + str, Query(description="The institution ID to filter by.") + ], +) -> InstitutionFunderSummary: + return await projects_service.get_institution_cordis_eu_projects_funding_over_time( + eu_search_client=eu_search_client, + institutions_search_client=institutions_search_client, + raw_oa_institution_id=raw_oa_institution_id, + ) + + @router.get( "/person/dfg/search", summary="Get DFG projects.", diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 546bd9b1..430ab10f 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -1,6 +1,6 @@ import datetime import logging -from typing import Dict, List, Optional +from typing import Any, Dict, List, Optional from inse.projects.projects_search_client import ( BundProjectsSearchClient, @@ -13,6 +13,7 @@ from inse.projects.model import ( DfgProjectPage, EuProjectPage, InstitutionFunderSummary, + ProjectType, ProjectsFilteringProperties, ) from inse.institutions.institutions_search_client import ( @@ -204,17 +205,45 @@ async def get_dfg_projects_by_author_id( return response -async def get_institution_bund_funding_over_time( +async def get_institution_cordis_eu_projects_funding_over_time( + eu_search_client: EuProjectsSearchClient, + institutions_search_client: InstitutionsSearchClient, + raw_oa_institution_id: str, +) -> InstitutionFunderSummary: + + cordis_eu_project_page = await search_cordis_eu_projects( + eu_search_client, + institutions_search_client, + ProjectsFilteringProperties( + project_type=ProjectType.EU, + raw_oa_institution_id=raw_oa_institution_id, + page=0, + size=10000, + ), + ) + + return _calculate_funding_over_time( + project_type=ProjectType.EU, + projects=cordis_eu_project_page.elements, + funding_start_attr="startDate", + funding_end_attr="endDate", + funding_amount_attr="totalCost", + ) + + +async def get_institution_bund_projects_funding_over_time( bund_search_client: BundProjectsSearchClient, institutions_search_client: InstitutionsSearchClient, - institution_id: str, + raw_oa_institution_id: str, ) -> InstitutionFunderSummary: - logger.info(f"Fetching funding over time for institution_id={institution_id}") + logger.info( + f"Fetching funding over time for institution_id={raw_oa_institution_id}" + ) institution_aliases = institutions_search_client.get_institution_aliases_by_id( - institution_id + raw_oa_institution_id ) logger.debug( - f"Found institution aliases for institution_id={institution_id}: {institution_aliases}" + f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" ) response = await bund_search_client.search_bund_projects( page=0, @@ -222,14 +251,36 @@ async def get_institution_bund_funding_over_time( institution_names=institution_aliases, ) + return _calculate_funding_over_time( + project_type=ProjectType.BUND, + projects=response.elements, + funding_start_attr="funding_start", + funding_end_attr="funding_end", + funding_amount_attr="grant_amount", + ) + + +def _calculate_funding_over_time( + project_type: ProjectType, + projects: List[Any], + funding_start_attr: str, + funding_end_attr: str, + funding_amount_attr: str, +) -> InstitutionFunderSummary: funding_per_year: Dict[int, float] = {} - for project in response.elements: - funding_start = project.funding_start - funding_end = project.funding_end - funding_amount = project.grant_amount + + for project in projects: + funding_start = getattr(project, funding_start_attr) + funding_end = getattr(project, funding_end_attr) + funding_amount = getattr(project, funding_amount_attr) if not funding_start or not funding_end or not funding_amount: continue + if hasattr(funding_start, "date"): + funding_start = funding_start.date() + if hasattr(funding_end, "date"): + funding_end = funding_end.date() + delta = (funding_end - funding_start).days + 1 if delta <= 0: continue @@ -271,7 +322,7 @@ async def get_institution_bund_funding_over_time( annual_average_over_period = 0.0 return InstitutionFunderSummary( - type="bund", + type=project_type, funding_per_year=sorted_funding_per_year, annual_average_over_period=annual_average_over_period, ) diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 4c073561..1630fce1 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -45,67 +45,6 @@ export class ProjectsService extends BaseService { super(basePath, configuration); } - /** - * Get funding over time for bund projects. - * Returns the funding over time for bund projects associated with the specified institution. - * @endpoint get /api/projects/institution/bund/funding-over-time - * @param institutionId The institution ID to filter by. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getBundFundingOverTime(institutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getBundFundingOverTime(institutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getBundFundingOverTime(institutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getBundFundingOverTime(institutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (institutionId === null || institutionId === undefined) { - throw new Error('Required parameter institutionId was null or undefined when calling getBundFundingOverTime.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - institutionId, 'institution_id'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/projects/institution/bund/funding-over-time`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - /** * Get DFG projects. * Returns a page of DFG projects based on the provided pagination parameters and optional institution filter. @@ -182,6 +121,128 @@ export class ProjectsService extends BaseService { ); } + /** + * Get funding over time for bund projects. + * Returns the funding over time for bund projects associated with the specified institution. + * @endpoint get /api/projects/institution/bund/funding-over-time + * @param rawOaInstitutionId The institution ID to filter by. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) { + throw new Error('Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionBundProjectsFundingOverTime.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + rawOaInstitutionId, 'raw_oa_institution_id'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/projects/institution/bund/funding-over-time`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Get funding over time for EU projects. + * Returns the funding over time for EU projects associated with the specified institution. + * @endpoint get /api/projects/institution/eu/funding-over-time + * @param rawOaInstitutionId The institution ID to filter by. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) { + throw new Error('Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionCordisEuProjectsFundingOverTime.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + rawOaInstitutionId, 'raw_oa_institution_id'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/projects/institution/eu/funding-over-time`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Get bund projects. * Returns a page of bund projects based on the provided pagination parameters and optional institution filter. diff --git a/webapp/src/app/api/model/institutionFunderSummary.ts b/webapp/src/app/api/model/institutionFunderSummary.ts index 5f3216ca..48d147b2 100644 --- a/webapp/src/app/api/model/institutionFunderSummary.ts +++ b/webapp/src/app/api/model/institutionFunderSummary.ts @@ -7,13 +7,14 @@ * https://openapi-generator.tech * Do not edit the class manually. */ +import { ProjectType } from './projectType'; export interface InstitutionFunderSummary { /** * The type of funding data (e.g., \'bund\', \'eu\', \'dfg\'). */ - type: InstitutionFunderSummary.TypeEnum; + type: ProjectType; /** * A dictionary mapping years to total funding amounts for that year. */ @@ -24,12 +25,6 @@ export interface InstitutionFunderSummary { annual_average_over_period?: number; } export namespace InstitutionFunderSummary { - export const TypeEnum = { - Bund: 'bund', - Eu: 'eu', - Dfg: 'dfg' - } as const; - export type TypeEnum = typeof TypeEnum[keyof typeof TypeEnum]; } diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 59ef12bc..7e896d47 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -10,6 +10,7 @@ import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver'; import { institutionsResolver } from './resolvers/institutions.resolver'; import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.resolver'; import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page.resolver'; +import { cordisEuProjectsFundingResolver } from './resolvers/cordis-eu-projects-funding.resolver'; export const routes: Routes = [ { @@ -230,8 +231,9 @@ export const routes: Routes = [ }, resolve: { bundProjectPage: bundProjectPageResolver, - cordisEuProjectPage: cordisEuProjectPageResolver, bundProjectsFunding: bundProjectsFundingResolver, + cordisEuProjectPage: cordisEuProjectPageResolver, + cordisEuProjectsFunding: cordisEuProjectsFundingResolver, }, runGuardsAndResolvers: (from, to) => { const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; 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 7a25c2e3..ddfacab5 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.html +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.html @@ -51,7 +51,7 @@ + [fundings]="[bundProjectsFunding(), cordisEuProjectsFunding()]" /> @@ -71,7 +71,7 @@ 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 debef76a..4f547c61 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.ts +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.ts @@ -85,19 +85,29 @@ export class InstitutionProjectsComponent implements OnInit { bundProjectData: BundProjectRow[] = []; bundProjectsFunding = input.required(); - bundTotalFunding = computed(() => { const funding = this.bundProjectsFunding(); return Object.values( funding.funding_per_year as Record, ).reduce((sum, yearFunding) => sum + yearFunding, 0); }); - bundAverageAnnualFunding = computed(() => { const funding = this.bundProjectsFunding(); return funding.annual_average_over_period ?? 0; }); + cordisEuProjectsFunding = input.required(); + euTotalFunding = computed(() => { + const funding = this.cordisEuProjectsFunding(); + return Object.values( + funding.funding_per_year as Record, + ).reduce((sum, yearFunding) => sum + yearFunding, 0); + }); + euAverageAnnualFunding = computed(() => { + const funding = this.cordisEuProjectsFunding(); + return funding.annual_average_over_period ?? 0; + }); + urlSortKey = signal(''); urlSortDirection = signal(''); urlSearchTerm = signal(''); @@ -239,7 +249,7 @@ export class InstitutionProjectsComponent implements OnInit { type: 'accessor', accessorKey: 'funding_amount', cellTemplate: this.fundingAmountTmp(), - } + }, ]; } diff --git a/webapp/src/app/resolvers/bund-projects-funding.resolver.ts b/webapp/src/app/resolvers/bund-projects-funding.resolver.ts index 61591e66..27f188c5 100644 --- a/webapp/src/app/resolvers/bund-projects-funding.resolver.ts +++ b/webapp/src/app/resolvers/bund-projects-funding.resolver.ts @@ -5,9 +5,11 @@ import { inject } from '@angular/core'; export const bundProjectsFundingResolver: ResolveFn< InstitutionFunderSummary > = (route, state) => { - let institutionId = route.paramMap.get('institutionId'); + let institutionId = route.parent?.paramMap.get('institutionId') ?? null; if (!institutionId) { institutionId = route.parent?.paramMap.get('institutionId') ?? null; } - return inject(ProjectsService).getBundFundingOverTime(institutionId || ''); + return inject(ProjectsService).getInstitutionBundProjectsFundingOverTime( + institutionId!, + ); }; diff --git a/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts b/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts new file mode 100644 index 00000000..4b1e5385 --- /dev/null +++ b/webapp/src/app/resolvers/cordis-eu-projects-funding.resolver.ts @@ -0,0 +1,17 @@ +import { ResolveFn } from '@angular/router'; +import { InstitutionFunderSummary, ProjectsService } from '../api'; +import { inject } from '@angular/core'; + +export const cordisEuProjectsFundingResolver: ResolveFn< + InstitutionFunderSummary +> = (route, state) => { + let institutionId = route.parent?.paramMap.get('institutionId') ?? null; + if (!institutionId) { + throw new Error( + 'Institution ID is required to resolve Cordis EU projects funding', + ); + } + return inject(ProjectsService).getInstitutionCordisEuProjectsFundingOverTime( + institutionId, + ); +};