Files
smartguide/service/src/main/inse/projects/router.py
T

403 lines
14 KiB
Python

import logging
from typing import Annotated, Optional, Set, List
from fastapi import APIRouter, Body, Depends, Path, Query, status
from inse.projects.model import (
BundProjectPage,
CordisEuProjectPage,
DfgProjectPage,
EuOrganizationProjectSummaryPage,
FundingProjectPage,
InstitutionFunderSummary,
ProjectType,
ProjectsFilteringProperties,
ProjectsSortBy,
SortDirection,
EuCordisProjectResponse
)
from inse.models.dfg_project_details import DfgProjectDetails
from inse.models.bund_project_details import BundProjectDetails
from inse.tags import Tags
from inse.projects import service as projects_service
from inse.institutions.institutions_search_client import (
InstitutionsSearchClient,
)
from inse.institutions.router import get_institutions_search_client
from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
from typing import Union
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
@router.get(
"/author/{raw_oa_author_id}/eu",
summary="Get EU projects for an author.",
description="Returns a list of EU projects associated with the specified author ID.",
operation_id="getEuProjectsForAuthor",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": CordisEuProjectPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Author not found"},
},
response_model_by_alias=False,
)
async def get_eu_projects_for_author(
raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")],
) -> CordisEuProjectPage:
logger.debug(
f"Received request to get EU projects for author_id={raw_oa_author_id}"
)
return await projects_service.search_cordis_eu_projects_for_author_id(
raw_oa_author_id=raw_oa_author_id,
)
@router.post(
"/institution/bund/search",
summary="Get bund projects.",
description="Returns a page of bund projects based on the provided pagination parameters and optional institution filter.",
operation_id="searchBundProjects",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": BundProjectPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
},
response_model_by_alias=False,
)
async def search_bund_projects(
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
filtering_properties: Annotated[
ProjectsFilteringProperties,
Body(description="The filtering properties for the projects search."),
],
) -> BundProjectPage:
return await projects_service.search_bund_projects(
institutions_search_client=institutions_search_client,
filtering_properties=filtering_properties,
)
@router.get(
"/dfg/{id}",
summary="Get a single DFG project.",
description="Returns a single DFG project based on its ID.",
operation_id="getSingleDfgProject",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": DfgProjectDetails,
},
status.HTTP_404_NOT_FOUND: {"description": "Project not found"},
},
response_model_by_alias=False,
)
async def get_single_dfg_project(
id: Annotated[str, Path(description="The ID of the DFG project to retrieve.")],
) -> DfgProjectDetails:
logger.debug(f"Received request to get single DFG project for id={id}")
return await projects_service.get_single_dfg_project(
project_id=id,
)
@router.get(
"/bund/{id}",
summary="Get a single BUND project.",
description="Returns a single BUND project based on its ID.",
operation_id="getSingleBundProject",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": BundProjectDetails,
},
status.HTTP_404_NOT_FOUND: {"description": "Project not found"},
},
response_model_by_alias=False,
)
async def get_single_bund_project(
id: Annotated[str, Path(description="The ID of the BUND project to retrieve.")],
) -> BundProjectDetails:
logger.debug(f"Received request to get single BUND project for id={id}")
return await projects_service.get_single_bund_project(
project_id=id,
)
@router.get(
"/eu/{id}",
summary="Get a single EU Cordis project.",
description="Returns a single EU Cordis project based on its ID.",
operation_id="getSingleEuCordisProject",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": EuCordisProjectResponse,
},
status.HTTP_404_NOT_FOUND: {
"description": "Project not found",
"model": EuCordisProjectResponse
},
status.HTTP_500_INTERNAL_SERVER_ERROR: {
"description": "Internal server error",
"model": EuCordisProjectResponse
}
},
)
async def get_single_eu_cordis_project(
id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")],
) -> EuCordisProjectResponse:
"""
Get a single EU Cordis project by ID.
Returns a wrapper response containing the project data or error information.
"""
logger.debug(f"Received request to get single EU Cordis project for id={id}")
try:
# Get the project from the service
project = await projects_service.get_single_eu_cordis_project(project_id=id)
# Check if project exists
if project is None:
logger.warning(f"Project with ID {id} not found")
return EuCordisProjectResponse(
success=False,
project_type=None,
eu_project_data=None,
error=f"Project with ID {id} not found"
)
# Determine the project type
if isinstance(project, Fp7ProjectDetails):
project_type = "fp7"
elif isinstance(project, H2020ProjectDetails):
project_type = "h2020"
elif isinstance(project, HEUProjectDetails):
project_type = "heu"
else:
# Unknown project type - maybe it's the base CordisEuProject
logger.warning(f"Unknown project type for ID {id}: {type(project)}")
return EuCordisProjectResponse(
success=False,
project_type=None,
eu_project_data=None,
error=f"Unknown project type for ID {id}"
)
# Return success with the project data
return EuCordisProjectResponse(
success=True,
project_type=project_type,
eu_project_data=project,
error=None
)
except Exception as e:
logger.error(f"Error retrieving project with ID {id}: {str(e)}", exc_info=True)
return EuCordisProjectResponse(
success=False,
project_type=None,
data=None,
error=f"Internal server error: {str(e)}"
)
@router.get(
"/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="getInstitutionBundProjectsFundingOverTime",
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_bund_projects_funding_over_time(
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_bund_projects_funding_over_time(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
)
@router.post(
"/institution/eu/search",
summary="Get EU projects.",
description="Returns a page of EU projects based on the provided pagination parameters and optional institution filter.",
operation_id="searchCordisEuProjects",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": EuOrganizationProjectSummaryPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
},
response_model_by_alias=False,
)
async def search_cordis_eu_projects(
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
projects_filtering_properties: Annotated[
ProjectsFilteringProperties,
Body(description="The filtering properties for the projects search."),
],
) -> EuOrganizationProjectSummaryPage:
return await projects_service.search_cordis_eu_projects(
institutions_search_client=institutions_search_client,
projects_filtering_properties=projects_filtering_properties,
)
@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(
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(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
)
@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(
author_id: Annotated[Optional[str], Query(description="The openalex author ID to filter by.")] = None,
author_filter_ids: Annotated[Optional[List[str]], Query(description="The author IDs to filter by.")] = None,
institution_ids: Annotated[
Optional[List[str]], Query(description="The institution IDs to filter by.")
] = None,
title: Annotated[
Optional[str], Query(description="The title to filter by.")
] = None,
topics: Annotated[
Optional[List[str]], Query(description="The topics to filter by.")
] = None,
funding_years: Annotated[Optional[List[str]], Query(description="The funding 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",
) -> DfgProjectPage:
logger.debug(
"Received request to get DFG projects for author_id=%s, author_filter_ids=%s, topics=%s, title=%s, funding_years=%s, page=%d, size=%d, sort_by=%s, sort_direction=%s",
author_id,
author_filter_ids,
topics,
title,
funding_years,
page,
size,
sort_by,
sort_direction,
)
return await projects_service.get_dfg_projects_by_author_id(
author_id=author_id,
author_filter_ids=author_filter_ids,
institution_ids=institution_ids,
funding_years=funding_years,
title=title,
topics=topics,
page=page,
size=size,
sort_by=sort_by,
sort_direction=sort_direction,
)
@router.get(
"/search",
summary="Search projects across all funders.",
description="Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter.",
operation_id="searchProjects",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": FundingProjectPage,
},
},
response_model_by_alias=False,
)
async def search_projects(
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
size: Annotated[int, Query(description="The page size.", ge=1)] = 10,
selected_project_types: Annotated[
Optional[Set[ProjectType]],
Query(
description="The set of project types to filter by (e.g., 'bund', 'eu', 'dfg'). If not provided, projects of all types will be included."
),
] = None,
title: Annotated[
Optional[str], Query(description="The title to filter by.")
] = None,
sort_by: Annotated[
ProjectsSortBy, Query(description="The field to sort by.")
] = ProjectsSortBy.TITLE,
sort_direction: Annotated[
SortDirection, Query(description="The sort direction (asc or desc).")
] = SortDirection.ASC,
) -> FundingProjectPage:
return await projects_service.search_all_projects(
page=page,
size=size,
selected_project_types=selected_project_types,
title=title,
sort_by=sort_by,
sort_direction=sort_direction,
)