feature/keywords-analysis #249

Merged
genja merged 15 commits from feature/keywords-analysis into dev 2026-07-28 10:09:57 +02:00
38 changed files with 1278 additions and 411 deletions
+2
View File
@@ -52,6 +52,7 @@ from inse.patents.service import (
)
from inse.persons.service import router as persons_service_router
from inse.projects.dfg_institutions.router import router as dfg_institutions_router
from inse.projects.bund_institutions.router import router as bund_institutions_router
from inse.projects.dfg_persons.router import router as dfg_persons_router
from inse.projects.eu_organizations.router import router as eu_organizations_router
from inse.projects.router import router as projects_router
@@ -103,6 +104,7 @@ app = FastAPI(
app.include_router(institution_patents_router)
app.include_router(org_patents_router)
app.include_router(institutions_router)
app.include_router(bund_institutions_router)
app.include_router(topics_service_router)
app.include_router(works_service_router)
app.include_router(persons_service_router)
@@ -0,0 +1,42 @@
from typing import Optional
from inse.model import Page
from pydantic import BaseModel
class BundInstitutionSummary(BaseModel):
"""A single institution entry derived from a BUND project record.
Note: this index has no dedicated institution entity — each entry is
reconstructed from the agency/recipient fields on a single project hit,
so the same institution may appear multiple times (once per project).
"""
department: Optional[str] = None
department_fullname: Optional[str] = None
name: Optional[str] = None
recepient: Optional[str] = None
municipality: Optional[str] = None
place: Optional[str] = None
state: Optional[str] = None
country: Optional[str] = None
@classmethod
def from_source(cls, source: dict) -> "BundInstitutionSummary":
"""Build a BundInstitutionSummary from a raw Elasticsearch _source dict."""
return cls(
department=source.get("Ressort"),
department_fullname=source.get("Ressort_fullname"),
name=source.get("Ausführende Stelle"),
recepient=source.get("Zuwendungsempfänger"),
municipality=source.get("Stadt/Gemeinde"),
place=source.get("Ort"),
state=source.get("Bundesland"),
country=source.get("Staat"),
)
class BundInstitutionSummaryPage(Page[BundInstitutionSummary]):
"""A paginated response containing a list of institutions."""
pass
@@ -0,0 +1,47 @@
import logging
from typing import Annotated
from fastapi import APIRouter, Query
from inse.projects.bund_institutions.model import BundInstitutionSummaryPage
from inse.tags import Tags
from inse.projects.bund_institutions.service import autocomplete_institutions_for_selector, get_institutions_by_names
logger = logging.getLogger(__name__)
INSTITUTIONS_BUND_PREFIX = "/api/bund/institutions"
router = APIRouter(prefix=INSTITUTIONS_BUND_PREFIX, tags=[Tags.BUND_INSTITUTIONS])
@router.get(
"/names",
operation_id="getBundInstitutionsByName",
summary="Returns a list of institutions based on their names.",
)
async def get_bund_institutions(
institution_names: Annotated[
list[str],
Query(description="A list of institution names to retrieve."),
] = [],
) -> BundInstitutionSummaryPage:
return await get_institutions_by_names(institution_names=institution_names or [])
@router.get(
"/autocomplete/selector",
operation_id="getBundInstitutionAutocompleteForSelector",
summary="Returns a list of institutions based on a search term for autocomplete functionality.",
)
async def get_bund_institution_autocomplete(
query: Annotated[
str,
Query(
description="A search term to filter institutions by (partial matches allowed)."
),
] = "",
) -> BundInstitutionSummaryPage:
return await autocomplete_institutions_for_selector(query=query)
@@ -0,0 +1,169 @@
import logging
from typing import Dict, List, Optional
from inse.integrations import elasticsearch
from inse.model import ESIndex, ESCluster
from inse.projects.bund_institutions.model import BundInstitutionSummary
from inse.projects.bund_institutions.model import BundInstitutionSummaryPage
logger = logging.getLogger(__name__)
# Fields on the BUND project index that describe the institution/agency involved,
# used consistently across all lookup functions below.
_INSTITUTION_SOURCE_FIELDS = [
"Ressort",
"Ressort_fullname",
"Ausführende Stelle",
"Zuwendungsempfänger",
"Stadt/Gemeinde",
"Ort",
"Bundesland",
"Staat",
]
async def search_institutions(
page: int = 0,
size: int = 10,
query: Optional[Dict] = None,
source: Optional[List[str]] = None,
sort: Optional[List[Dict]] = None,
body: Optional[Dict] = None,
) -> BundInstitutionSummaryPage:
"""Searches for institutions in the BUND Projects Elasticsearch index based on the provided parameters.
Note: PROJECTS_BUND_V1 indexes projects, not institutions directly, so each
matching project hit is reshaped into a BundInstitutionSummary. The same
institution may therefore appear multiple times if it's tied to multiple projects.
Args:
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
query (Optional[Dict], optional): The search query to filter institutions by. Defaults to None.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
sort (Optional[List[Dict]], optional): A list of sorting criteria. Defaults to None.
body (Optional[Dict], optional): The request body for the Elasticsearch search query. Defaults to None.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the search criteria.
"""
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
cluster=ESCluster.INSE,
query=query,
source=source or _INSTITUTION_SOURCE_FIELDS,
size=size,
offset=size * page,
sort=sort,
body=body,
)
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
institutions: List[BundInstitutionSummary] = [
BundInstitutionSummary.from_source(hit.get("_source", {})) for hit in hits
]
return BundInstitutionSummaryPage(
elements=institutions,
total=hits_block.get("total", {}).get("value", len(institutions)),
page=page,
size=size,
)
async def get_institutions_by_names(institution_names: List[str]) -> BundInstitutionSummaryPage:
"""Retrieves institutions based on a list of institution (Ausführende Stelle) names.
Args:
institution_names (List[str]): A list of institution names to retrieve.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the provided names.
"""
logger.debug(f"Fetching institutions for names: {institution_names}")
if not institution_names:
return BundInstitutionSummaryPage(elements=[], total=0, page=0, size=0)
return await search_institutions(
page=0,
size=len(institution_names),
query={
"terms": {
"Ausführende Stelle.keyword": institution_names,
}
},
source=_INSTITUTION_SOURCE_FIELDS,
)
async def autocomplete_institutions(
query: str, page: int = 0, size: int = 10, source: Optional[List[str]] = None
) -> BundInstitutionSummaryPage:
"""Autocompletes institutions based on a search term, matching against both the
executing agency (Ausführende Stelle) and recipient (Zuwendungsempfänger) fields.
Args:
query (str): The search term to autocomplete institutions with.
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the autocomplete criteria.
"""
logger.debug(f"Autocomplete institutions for query: {query}")
if not query:
return BundInstitutionSummaryPage(elements=[], total=0, page=0, size=0)
return await search_institutions(
page=page,
size=size,
query={
"bool": {
"should": [
{
"match_phrase_prefix": {
"Ausführende Stelle": {
"query": query,
"max_expansions": 50,
"boost": 2,
}
}
},
{
"match_phrase_prefix": {
"Zuwendungsempfänger": {
"query": query,
"max_expansions": 50,
}
}
},
],
"minimum_should_match": 1,
}
},
source=source or _INSTITUTION_SOURCE_FIELDS,
)
async def autocomplete_institutions_for_selector(
query: str, page: int = 0, size: int = 10
) -> BundInstitutionSummaryPage:
"""Autocompletes institutions based on a search term for use in a selector component.
Args:
query (str): The search term to filter institutions by (partial matches allowed).
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the autocomplete criteria.
"""
return await autocomplete_institutions(
query=query,
page=page,
size=size,
source=_INSTITUTION_SOURCE_FIELDS,
)
+67
View File
@@ -74,6 +74,73 @@ async def get_person_ids_by_institution_ids(
if hit.get("_source", {}).get("person_id") is not None
}
)
async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""
Query the `projects_bund_openalex_topics` index to find BUND project IDs
that match any of the given OpenAlex topic IDs.
"""
if not topic_ids:
return []
required_topics = set(topic_ids)
project_topics: dict[str, Set[str]] = defaultdict(set)
page_size = 1000
from_ = 0
while True:
body = {
"size": page_size,
"from": from_,
"_source": ["project_id", "topic_matches"],
"query": {
"terms": {
"topic_matches.topic_id.keyword": topic_ids
}
},
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
cluster=ESCluster.INSE,
body=body,
)
print(f"Response from Elasticsearch: {json.dumps(response, indent=2)}") # Debugging line
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
for hit in hits:
source = hit["_source"]
project_id = source.get("project_id")
if not project_id:
continue
topic_matches = source.get("topic_matches") or []
if isinstance(topic_matches, dict):
topic_matches = [topic_matches]
for match in topic_matches:
topic_id = match.get("topic_id")
if topic_id in required_topics:
project_topics[project_id].add(topic_id)
if len(hits) < page_size:
break
from_ += page_size
return [
project_id
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
async def get_dfg_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""Fetches project IDs whose topic_matches contain EVERY given topic ID,
even if the topics are distributed across multiple documents for the same project.
+9 -2
View File
@@ -14,6 +14,7 @@ from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDet
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
from inse.authors.v2.model import AuthorPage
from inse.projects.bund_institutions.model import BundInstitutionSummary
from typing import Union
class ProjectType(StrEnum):
@@ -75,6 +76,11 @@ class BundProjectSummary(BundProject):
description="The OpenAlex topics of the project",
examples=[["Artificial Intelligence", "Machine Learning"]],
)
institution: Optional[BundInstitutionSummary] = Field(
default=None,
description="The executing agency / recipient institution for this project, "
"derived from the project's own agency fields.",
)
@classmethod
def from_hit(cls, hit: dict) -> "BundProjectSummary":
@@ -109,8 +115,8 @@ class BundProjectSummary(BundProject):
topic=source.get("Thema"),
performance_plan_system=source.get("Leistungsplansystematik"),
performance_plan_system_text=source.get("Klartext Leistungsplansystematik"),
funding_start=source.get("Förderbeginn"),
funding_end=source.get("Förderende"),
funding_start=source.get("funding_start"),
funding_end=source.get("funding_end"),
grant_amount=source.get("Fördersumme"),
funding_profile=source.get("Förderprofil"),
joint_project=source.get("Verbundprojekt"),
@@ -121,6 +127,7 @@ class BundProjectSummary(BundProject):
new=source.get("neu"),
duration=source.get("Laufzeit"),
oa_topics=oa_topics,
institution=BundInstitutionSummary.from_source(source),
)
@staticmethod
@@ -21,7 +21,7 @@ from inse.models.dfg_project_details import DfgProjectDetails
from inse.models.bund_project_details import BundProjectDetails
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes, get_openalex_topics_for_bund_projects
from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids,get_bund_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes, get_openalex_topics_for_bund_projects
settings = get_settings()
@@ -29,66 +29,6 @@ logger = logging.getLogger(__name__)
logger.setLevel(settings.logging_level)
DFG_PERSON_FIELDS: List[str] = [
"Antragsteller",
"Antragstellerin",
"Antragstellerinnen",
"Antragstellerinnen / Antragsteller",
"Beteiligte Person",
"Beteiligte Personen",
"Co-Sprecher",
"Co-Sprecherinnen / Co-Sprecher",
"Ehemalige Antragsteller",
"Ehemalige Antragstellerin",
"Ehemalige Antragstellerinnen",
"Ehemalige Antragstellerinnen / Ehemalige Antragsteller",
"Ehemaliger Antragsteller",
"Gastgeber",
"Gastgeberin",
"Gastgeberinnen",
"Gastgeberinnen / Gastgeber",
"Kooperationspartner",
"Kooperationspartnerin",
"Kooperationspartnerinnen",
"Kooperationspartnerinnen / Kooperationspartner",
"Leiter",
"Leiterin",
"Leiterinnen",
"Leiterinnen / Leiter",
"Mitantragsteller",
"Mitantragstellerin",
"Mitantragstellerinnen",
"Mitantragstellerinnen / Mitantragsteller",
"Mitverantwortlich",
"Mitverantwortlich(e)",
"Mitverantwortliche",
"Sprecher",
"Sprecher (IGK-Partner)",
"Sprecherin",
"Sprecherin (IGK-Partner)",
"Sprecherinnen",
"Sprecherinnen (IGK-Partner) / Sprecher (IGK-Partner)",
"Sprecherinnen / Sprecher",
"Teilprojektleiter",
"Teilprojektleiterin",
"Teilprojektleiterinnen",
"Teilprojektleiterinnen / Teilprojektleiter",
"ausländ. Mitantragstellerin",
"ausländ. Mitantragstellerinnen",
"ausländ. Mitantragstellerinnen / ausländische Mitantragsteller",
"ausländische Mitantragsteller",
"ausländischer Mitantragsteller",
"beteiligte Wissenschaftler",
"beteiligte Wissenschaftlerin",
"beteiligte Wissenschaftlerinnen",
"beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler",
"beteiligter Wissenschaftler",
"person_creater_name",
"stellvertr. Sprecher",
"stellvertr. Sprecherin",
"stellvertr. Sprecherinnen / stellvertr. Sprecher",
]
# BUND
@@ -701,40 +641,35 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
#BUND
async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""
Query the `projects_bund_openalex_topics` index to find BUND project IDs
that match any of the given OpenAlex topic IDs.
"""
body: Dict[str, Any] = {
"size": 0,
"query": {
"terms": {
"topic_matches.topic_id": topic_ids
}
},
"aggs": {
"project_ids": {
"terms": {
"field": "project_id.keyword",
"size": 10000
def _bund_year_filters(field: str, years: List[str]) -> Dict[str, Any]:
should = []
for year in years:
year = str(year).strip()
if not year:
continue
should.append(
{
"range": {
field: {
"gte": f"01.01.{year}",
"lte": f"31.12.{year}",
}
}
}
)
return {
"bool": {
"should": should,
"minimum_should_match": 1,
}
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
body=body,
cluster=ESCluster.INSE
)
buckets = response.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
return [bucket["key"] for bucket in buckets]
async def search_bund_projects_with_filters(
executing_agency: Optional[List[str]] = None,
institution_ids: Optional[List[int]] = None,
institution_ids: Optional[List[str]] = None,
funding_arts: Optional[List[str]] = None, # actually EuCordisProjectType, but treated as strings
title: Optional[str] = None,
keywords: Optional[List[str]] = None,
@@ -753,7 +688,7 @@ async def search_bund_projects_with_filters(
Main search function for BUND projects, analogous to the DFG search.
"""
from_ = page * size
#institution_ids = ["I62318514"]
# Fields we need to build BundProject objects (validation aliases match these exact names)
source_fields = [
"Förderkennzeichen",
@@ -784,7 +719,6 @@ async def search_bund_projects_with_filters(
"datum",
"neu",
"Laufzeit",
# Also include funding_start/end for sorting and filtering (they may also be needed)
"funding_start",
"funding_end",
]
@@ -797,13 +731,12 @@ async def search_bund_projects_with_filters(
}
must_clauses: List[Dict[str, Any]] = []
# === Primary search clause: fuzzy(topic_ids) vs keyword phrase search ===
if fuzzy and topic_ids:
matching_project_ids = await get_bund_project_ids_by_topic_ids(topic_ids=topic_ids)
if not matching_project_ids:
return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_project_ids}})
must_clauses.append({"terms": {"_id": matching_project_ids}})
elif keywords:
keyword_clauses = []
@@ -813,7 +746,7 @@ async def search_bund_projects_with_filters(
keyword_clauses.append({
"multi_match": {
"query": kw,
"fields": ["Verbundprojekt"], # searching title/acronym field
"fields": ["Verbundprojekt","Thema"], # searching title/acronym field
"type": "phrase_prefix",
"max_expansions": 100,
}
@@ -826,21 +759,38 @@ async def search_bund_projects_with_filters(
matching_filter_ids = await get_bund_project_ids_by_topic_ids(topic_ids=filter_topic_ids)
if not matching_filter_ids:
return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_filter_ids}})
must_clauses.append({"terms": {"_id": matching_filter_ids}})
if title:
must_clauses.append({
"multi_match": {
"query": title,
"fields": ["Verbundprojekt"],
"fields": ["Verbundprojekt","Thema"], # searching title field
"type": "phrase_prefix",
"max_expansions": 100,
}
})
# print(f"Executing BUND project search with institution_ids: {institution_ids}, executing_agency: {executing_agency}, funding_arts: {funding_arts}, countries: {countries}, funding_start_years: {funding_start_years}, funding_end_years: {funding_end_years}")
if executing_agency:
must_clauses.append({"terms": {"Ausführende Stelle.keyword": executing_agency}})
# institution_names = await institutions_search_client.get_institution_aliases_by_oa_institution_id(executing_agency[0].split("/")[-1])
# institution_page = await institutions_search_client.get_institutions_by_alias(alias=institution_names[0])
# print(f"Retrieved institution names for IDs {executing_agency}: {institution_names}")
# print(f"Retrieved institution page for names {institution_names}: {institution_page}")
# if not institution_names:
# return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({
"bool": {
"should": [
clause
for name in executing_agency
for clause in (
{"match": {"Zuwendungsempfänger": {"query": name, "operator": "and"}}},
{"match": {"Ausführende Stelle": {"query": name, "operator": "and"}}},
)
],
"minimum_should_match": 1,
}
})
if funding_arts:
must_clauses.append({"terms": {"Förderart.keyword": funding_arts}})
@@ -848,10 +798,10 @@ async def search_bund_projects_with_filters(
must_clauses.append({"terms": {"Staat.keyword": countries}})
if funding_start_years:
must_clauses.append({"terms": {"funding_start": funding_start_years}})
must_clauses.append(_bund_year_filters("funding_start", funding_start_years))
if funding_end_years:
must_clauses.append({"terms": {"funding_end": funding_end_years}})
must_clauses.append(_bund_year_filters("funding_end", funding_end_years))
body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
+2
View File
@@ -24,3 +24,5 @@ class Tags(StrEnum):
DFG_INSTITUTIONS = "DFG Institutions"
DFG_PERSONS = "DFG Persons"
BACKGROUND_JOBS = "Background Jobs"
BUND_INSTITUTIONS = "BUND Institutions"
@@ -6,6 +6,7 @@ api.module.ts
api/api.ts
api/auth.service.ts
api/authorsV2.service.ts
api/bUNDInstitutions.service.ts
api/backgroundJobs.service.ts
api/bookmarks.service.ts
api/companyConnections.service.ts
@@ -69,6 +70,8 @@ model/bodyLogin.ts
model/bodyRequestOtk.ts
model/bodyRequestPasswordReset.ts
model/bodyResetPassword.ts
model/bundInstitutionSummary.ts
model/bundInstitutionSummaryPage.ts
model/bundProjectDetails.ts
model/bundProjectPage.ts
model/bundProjectSummary.ts
+29 -1
View File
@@ -2,6 +2,8 @@ export * from './auth.service';
import { AuthService } from './auth.service';
export * from './authorsV2.service';
import { AuthorsV2Service } from './authorsV2.service';
export * from './bUNDInstitutions.service';
import { BUNDInstitutionsService } from './bUNDInstitutions.service';
export * from './backgroundJobs.service';
import { BackgroundJobsService } from './backgroundJobs.service';
export * from './bookmarks.service';
@@ -46,4 +48,30 @@ export * from './works.service';
import { WorksService } from './works.service';
export * from './worksV2.service';
import { WorksV2Service } from './worksV2.service';
export const APIS = [AuthService, AuthorsV2Service, BackgroundJobsService, BookmarksService, CompanyConnectionsService, DFGInstitutionsService, DFGPersonsService, DashboardService, FundingService, INSEServiceService, InstitutionsService, InstitutionsV2Service, KeywordsService, NewsService, OrganizationService, PatentsService, PersonsService, ProjectsService, RankingService, TopicsService, TopicsV2Service, UniversityRankingsService, WorksService, WorksV2Service];
export const APIS = [
AuthService,
AuthorsV2Service,
BUNDInstitutionsService,
BackgroundJobsService,
BookmarksService,
CompanyConnectionsService,
DFGInstitutionsService,
DFGPersonsService,
DashboardService,
FundingService,
INSEServiceService,
InstitutionsService,
InstitutionsV2Service,
KeywordsService,
NewsService,
OrganizationService,
PatentsService,
PersonsService,
ProjectsService,
RankingService,
TopicsService,
TopicsV2Service,
UniversityRankingsService,
WorksService,
WorksV2Service,
];
@@ -0,0 +1,258 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { BundInstitutionSummaryPage } from '../model/bundInstitutionSummaryPage';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root',
})
export class BUNDInstitutionsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
/**
* Returns a list of institutions based on a search term for autocomplete functionality.
* @endpoint get /api/bund/institutions/autocomplete/selector
* @param query A search term to filter institutions by (partial matches allowed).
* @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 getBundInstitutionAutocompleteForSelector(
query?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<BundInstitutionSummaryPage>;
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<BundInstitutionSummaryPage>>;
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<BundInstitutionSummaryPage>>;
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>query,
'query',
);
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/bund/institutions/autocomplete/selector`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<BundInstitutionSummaryPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Returns a list of institutions based on their names.
* @endpoint get /api/bund/institutions/names
* @param institutionNames A list of institution names to retrieve.
* @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 getBundInstitutionsByName(
institutionNames?: Array<string>,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<BundInstitutionSummaryPage>;
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<BundInstitutionSummaryPage>>;
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<BundInstitutionSummaryPage>>;
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (institutionNames) {
institutionNames.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'institution_names',
);
});
}
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/bund/institutions/names`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<BundInstitutionSummaryPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
@@ -0,0 +1,23 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A single institution entry derived from a BUND project record. Note: this index has no dedicated institution entity — each entry is reconstructed from the agency/recipient fields on a single project hit, so the same institution may appear multiple times (once per project).
*/
export interface BundInstitutionSummary {
department?: string | null;
department_fullname?: string | null;
name?: string | null;
recepient?: string | null;
municipality?: string | null;
place?: string | null;
state?: string | null;
country?: string | null;
}
@@ -0,0 +1,32 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { BundInstitutionSummary } from './bundInstitutionSummary';
/**
* A paginated response containing a list of institutions.
*/
export interface BundInstitutionSummaryPage {
/**
* The elements of the page.
*/
elements?: Array<BundInstitutionSummary>;
/**
* The page number. (0-based)
*/
page?: number;
/**
* The page size in elements.
*/
size?: number;
/**
* The total number of elements.
*/
total?: number;
}
+33 -33
View File
@@ -1,44 +1,44 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Topic } from './topic';
import { BundInstitutionSummary } from './bundInstitutionSummary';
export interface BundProjectSummary {
funding_code?: string | null;
department?: string | null;
department_fullname?: string | null;
referat?: string | null;
project_sponsor?: string | null;
project_sponsor_fullname?: string | null;
work_unit?: string | null;
recipient?: string | null;
municipal_code?: string | null;
municipality?: string | null;
place?: string | null;
state?: string | null;
country?: string | null;
implementing_agency?: string | null;
topic?: string | null;
performance_plan_system?: string | null;
performance_plan_system_text?: string | null;
funding_start?: string | null;
funding_end?: string | null;
grant_amount?: number | null;
funding_profile?: string | null;
joint_project?: string | null;
funding_type?: string | null;
publication_date?: string | null;
unix_timestamp?: number | null;
date?: string | null;
'new'?: boolean | null;
duration?: string | null;
oa_topics?: Array<Topic> | null;
export interface BundProjectSummary {
funding_code?: string | null;
department?: string | null;
department_fullname?: string | null;
referat?: string | null;
project_sponsor?: string | null;
project_sponsor_fullname?: string | null;
work_unit?: string | null;
recipient?: string | null;
municipal_code?: string | null;
municipality?: string | null;
place?: string | null;
state?: string | null;
country?: string | null;
implementing_agency?: string | null;
topic?: string | null;
performance_plan_system?: string | null;
performance_plan_system_text?: string | null;
funding_start?: string | null;
funding_end?: string | null;
grant_amount?: number | null;
funding_profile?: string | null;
joint_project?: string | null;
funding_type?: string | null;
publication_date?: string | null;
unix_timestamp?: number | null;
date?: string | null;
new?: boolean | null;
duration?: string | null;
oa_topics?: Array<Topic> | null;
institution?: BundInstitutionSummary | null;
}
+2
View File
@@ -35,6 +35,8 @@ export * from './bodyLogin';
export * from './bodyRequestOtk';
export * from './bodyRequestPasswordReset';
export * from './bodyResetPassword';
export * from './bundInstitutionSummary';
export * from './bundInstitutionSummaryPage';
export * from './bundProjectDetails';
export * from './bundProjectPage';
export * from './bundProjectSummary';
+15 -14
View File
@@ -39,6 +39,7 @@ import {
} from './resolvers/work-page.resolver';
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
import { selectedBundInstitutionsResolver } from './resolvers/selected-bund-institutions.resolver';
import { SearchResultsStateService } from './modules/keywords-search/search-results/search-results-state.service';
import { roleGuard } from './shared/guards/role.guard';
import { UserRole } from './api';
@@ -241,6 +242,20 @@ export const routes: Routes = [
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
{
path: 'bund',
component: BundProjectsComponent,
resolve: {
bundProjectPage: bundProjectsResolver,
selectedBundInstitutionsPage: selectedBundInstitutionsResolver,
selectedBundAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
],
},
{ path: 'patents', component: KeywordsToPatentsResultsComponent },
@@ -526,20 +541,6 @@ export const routes: Routes = [
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON,
},
},
{
path: 'bund',
component: BundProjectsComponent,
resolve: {
bundProjectPage: bundProjectsResolver,
selectedBundInstitutionsPage: selectedInstitutionsResolver,
selectedBundAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
],
},
{
@@ -41,5 +41,9 @@ export class KeywordsToProjectsResultsComponent {
path: 'eu',
label: 'EU-Projekte',
},
{
path: 'bund',
label: 'BUND-Projekte',
},
];
}
@@ -69,6 +69,7 @@
keywords: state.payload()?.keywords?.join(','),
fuzzy: state.payload()?.options?.fuzzy,
topics: state.payload()?.options?.fuzzy ? state.topicIds() : null,
topicId: null,
}"
queryParamsHandling="replace">
<mat-icon>{{ route.icon }}</mat-icon>
@@ -27,9 +27,5 @@ export class PersonProjectsComponent {
path: 'eu',
label: 'EU-Projekte',
},
{
path: 'bund',
label: 'Bund-Projekte',
},
];
}
@@ -64,6 +64,7 @@
<div class="metric-content">
<strong>{{
getFundingStatus(bundProject.funding_end_date)
| date: 'dd.MM.yyyy'
}}</strong>
<span>Förderende</span>
</div>
@@ -11,7 +11,7 @@ export const bundProjectQueryParamKeys = {
size: 'size',
title: 'title',
authorId: 'authorId',
funding_art: 'funding_art',
funding_type: 'funding_type',
institutionId: 'institutionId',
funding_start: 'funding_start',
funding_end: 'funding_end',
@@ -20,13 +20,15 @@ export const bundProjectQueryParamKeys = {
sortDirection: 'sort_direction',
legend: 'legend',
legend_expanded: 'legend_expanded',
keywords: 'keywords',
topics: 'topics',
agency: 'agency',
} as const;
export const bundProjectsResolver: ResolveFn<BundProjectPage> = (
route,
state,
) => {
console.log('bundProjectsResolver called with route:', route);
const page = route.queryParamMap.get(bundProjectQueryParamKeys.page) ?? '0';
const size = route.queryParamMap.get(bundProjectQueryParamKeys.size) ?? '10';
const institutionIds = route.queryParamMap.getAll(
@@ -38,34 +40,43 @@ export const bundProjectsResolver: ResolveFn<BundProjectPage> = (
const fundingEndYears = route.queryParamMap.getAll(
bundProjectQueryParamKeys.funding_end,
);
const topicIds = route.queryParamMap.get(bundProjectQueryParamKeys.topicId);
const fundingArts = route.queryParamMap.getAll(
bundProjectQueryParamKeys.funding_art,
const keywords =
route.queryParamMap.get(bundProjectQueryParamKeys.keywords)?.split(',') ||
[];
const topicIds = route.queryParamMap.getAll(
bundProjectQueryParamKeys.topicId,
);
const topics = route.queryParamMap.getAll(bundProjectQueryParamKeys.topics);
const fundingType = route.queryParamMap.getAll(
bundProjectQueryParamKeys.funding_type,
);
const sortBy = (route.queryParamMap.get(bundProjectQueryParamKeys.sortBy) ||
'title') as ProjectsSortBy;
const sortDirection = (route.queryParamMap.get(
bundProjectQueryParamKeys.sortDirection,
) || 'asc') as SortDirection;
const fuzzySearch = route.queryParamMap.get('fuzzy') === 'true';
const search =
route.queryParamMap.get(bundProjectQueryParamKeys.title) || undefined;
const executingAgency = route.queryParamMap.getAll(
bundProjectQueryParamKeys.agency,
);
return inject(ProjectsService).searchBundProjectsWithFilters(
institutionIds,
fundingArts,
executingAgency,
fundingType,
search,
[],
[],
[],
keywords,
topics,
topicIds,
fundingStartYears,
fundingEndYears,
[],
[],
institutionIds,
Number(page),
Number(size),
sortBy,
sortDirection,
false,
fuzzySearch,
);
};
@@ -0,0 +1,15 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { BUNDInstitutionsService } from '../api';
import { BundInstitutionSummaryPage } from '../api/model/bundInstitutionSummaryPage';
export const selectedBundInstitutionsResolver: ResolveFn<
BundInstitutionSummaryPage
> = (route, state) => {
const agencyNameQueryParamKey =
(route.data['institutionIdQueryParamKey'] as string) || 'agency';
const agencies = route.queryParamMap.getAll(agencyNameQueryParamKey);
return inject(BUNDInstitutionsService).getBundInstitutionsByName(agencies);
};
@@ -6,21 +6,25 @@
<app-query-param-paginator
[total]="total()"
[queryParamPageKey]="queryParamKeys.page"
[queryParamSizeKey]="queryParamKeys.size"
[pageSizeOptions]="[10]" />
queryParamPageKey="page"
queryParamSizeKey="size"
[pageSizeOptions]="[10, 25, 50]" />
<ng-template #fundingStartTmp let-element>
{{ getStartDate(element) | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #fundingEndTmp let-element>
{{
element.funding_end == '2999' || element.funding_end == null
? 'laufend'
: element.funding_end
}}
{{ getEndDate(element) | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #fundingAmountTmp let-element>
{{ getFundingAmount(element) | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }}
</ng-template>
<ng-template #actionsTmp let-element>
<a
[routerLink]="['/projects/dfg', element.id]"
[routerLink]="['/projects/bund', element.funding_code]"
target="_blank"
mat-icon-button
color="primary">
@@ -42,43 +46,6 @@
</div>
</ng-template>
<!-- <ng-template #authorsTmp let-project>
@let projectAuthors = getProjectAuthors(project);
@let isProjectAuthorsExpanded = isProjectPersonsExpanded(project);
@let visibleAuthors =
isProjectAuthorsExpanded ? projectAuthors : projectAuthors.slice(0, 3); -->
<!-- <div class="author-tags" aria-label="Autoren" style="padding: 0.5rem 0">
@for (author of visibleAuthors; track author.person_id) {
<button
type="button"
class="publication-institution-tag"
[class.active]="isAuthorActive(author.person_id!)"
[matTooltip]="getAuthorTooltipText(author)"
matTooltipPosition="above"
[attr.aria-label]="getAuthorTooltipText(author)"
(click)="filterByAuthor(author.person_id!)">
<mat-icon class="institution-icon">person</mat-icon>
<span class="institution-name">{{ author.full_name }}</span>
</button>
} @empty {
<span class="empty-text">-</span>
} -->
<!-- @if (projectAuthors.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isProjectAuthorsExpanded"
(click)="toggleProjectAuthorsExpansion(project)">
{{
isProjectAuthorsExpanded
? 'weniger'
: '+' + (projectAuthors.length - 3)
}}
</button>
} -->
<!-- </div>
</ng-template> -->
<ng-template #institutionsTmp let-project>
@let institutions = getProjectInstitutions(project);
@@ -86,45 +53,42 @@
class="institution-tags"
aria-label="Institutionen"
style="padding: 0.5rem 0">
@for (
institution of isProjectInstitutionsExpanded(project)
? institutions
: institutions.slice(0, 3);
track getProjectInstitutionId(institution)
) {
<button
type="button"
class="publication-institution-tag"
[class.active]="isInstitutionActive(institution.id!)"
[matTooltip]="getInstitutionTooltipText(institution)"
matTooltipPosition="above"
[attr.aria-label]="getInstitutionTooltipText(institution)"
(click)="filterByInstitution(institution)">
<mat-icon class="institution-icon">apartment</mat-icon>
<span class="institution-name">{{
institution.institute_name_de || institution.institute_name_en
}}</span>
</button>
} @empty {
<span class="empty-text">-</span>
}
@if (institutions.length > 3) {
<button
type="button"
class="publication-institution-more"
(click)="toggleProjectInstitutionsExpansion(project)">
@if (isProjectInstitutionsExpanded(project)) {
Weniger anzeigen
} @else {
+{{ institutions.length - 3 }} weitere
}
</button>
}
<button
type="button"
class="publication-institution-tag"
[class.active]="isInstitutionActive(institutions[0].name!)"
[matTooltip]="getInstitutionTooltipText(institutions[0])"
matTooltipPosition="above"
[attr.aria-label]="getInstitutionTooltipText(institutions[0])"
(click)="filterByInstitution(institutions[0])">
<mat-icon class="institution-icon">apartment</mat-icon>
<span class="institution-name">{{
institutions[0].name || institutions[0].recepient || '-'
}}</span>
</button>
</div>
</ng-template>
<ng-template #fundingTypeTmp let-project>
@if (project.funding_type) {
<button
type="button"
class="type-filter-btn"
[class.active]="isFundingTypeActive(project.funding_type)"
matTooltip="Nach Typ filtern"
matTooltipPosition="above"
(click)="toggleFundingTypeFilter(project.funding_type)">
<app-chip [color]="getFundingTypeColor(project.funding_type)">
{{ project.funding_type }}
</app-chip>
</button>
} @else {
<span class="empty-text">-</span>
}
</ng-template>
<ng-template #topicsTmp let-project>
@let projectTopics = project.topics ?? [];
@let projectTopics = project.oa_topics ?? [];
@let isTopicsExpanded = isProjectTopicsExpanded(project);
@let visibleTopics =
isTopicsExpanded ? projectTopics : projectTopics.slice(0, 3);
@@ -7,7 +7,28 @@
// ------------------------
// Shared tags & chips
// ------------------------
.type-filter-btn {
display: inline-flex;
margin: 0;
padding: 0;
border: 0;
border-radius: 7px;
background: transparent;
cursor: pointer;
transition: box-shadow 0.2s ease;
&:hover,
&:focus-visible {
outline: none;
box-shadow: 0 0 0 1px var(--sg-primary);
}
&.active {
box-shadow:
0 0 0 1px #ffffff,
0 0 0 3px var(--sg-primary);
}
}
.publication-institution-tag {
display: inline-flex;
align-items: center;
@@ -7,12 +7,8 @@ import {
viewChild,
inject,
} from '@angular/core';
import {
BundProjectPage,
DfgProjectPage,
DfgProjectSummary,
Topic,
} from '../../../api';
import { CurrencyPipe, DatePipe } from '@angular/common';
import { BundProjectPage, Topic } from '../../../api';
import { BundProjectSummary } from '../../../api/model/bundProjectSummary';
import { TopicChipComponent } from '../topic-chip/topic-chip.component';
import {
@@ -23,12 +19,12 @@ import { RouterModule } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { QueryParamPaginatorComponent } from '../query-param-paginator/query-param-paginator.component';
import { dfgProjectQueryParamKeys } from '../../../resolvers/dfg-projects.resolver';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute, Router } from '@angular/router';
import { DfgPersonSummary } from '../../../api/model/dfgPersonSummary';
import { ChipComponent } from '../chip/chip.component';
import { MatTooltip } from '@angular/material/tooltip';
import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors';
import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.resolver';
@Component({
selector: 'app-bund-project-table',
imports: [
@@ -39,6 +35,9 @@ import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors';
QueryParamPaginatorComponent,
MatTooltip,
TopicChipComponent,
CurrencyPipe,
DatePipe,
ChipComponent,
],
templateUrl: './bund-project-table.component.html',
styleUrl: './bund-project-table.component.scss',
@@ -58,17 +57,18 @@ export class BundProjectTableComponent implements OnInit {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
queryParamKeys = dfgProjectQueryParamKeys;
queryParamKeys = bundProjectQueryParamKeys;
total = computed(() => this.page().total ?? 0);
columns: GenericColumn<BundProjectSummary>[] = [];
titleTmp = viewChild.required<TemplateRef<any>>('titleTmp');
authorsTmp = viewChild.required<TemplateRef<any>>('authorsTmp');
fundingTypeTmp = viewChild.required<TemplateRef<any>>('fundingTypeTmp');
institutionsTmp = viewChild.required<TemplateRef<any>>('institutionsTmp');
fundingStartTmp = viewChild.required<TemplateRef<any>>('fundingStartTmp');
fundingEndTmp = viewChild.required<TemplateRef<any>>('fundingEndTmp');
actionsTmp = viewChild.required<TemplateRef<any>>('actionsTmp');
detailRowTmp = viewChild.required<TemplateRef<any>>('detailRowTmp');
fundingAmountTmp =
viewChild.required<TemplateRef<unknown>>('fundingAmountTmp');
topicsTmp = viewChild.required<TemplateRef<any>>('topicsTmp');
expandedProjectAuthorsId: string[] = [];
@@ -92,21 +92,32 @@ export class BundProjectTableComponent implements OnInit {
});
selectedInstitutionIdsQueryParams = computed(() => {
return this.queryParamMap().getAll(this.queryParamKeys.institutionId);
return this.queryParamMap().getAll(this.queryParamKeys.agency);
});
selectedTopicIdsQueryParams = computed(() => {
return this.queryParamMap().getAll(this.queryParamKeys.topicId);
});
selectedFundingTypesQueryParams = computed(() => {
return this.queryParamMap().getAll(this.queryParamKeys.funding_type);
});
ngOnInit(): void {
this.columns = [
{ id: 'title', header: 'Titel', type: 'accessor', accessorKey: 'topic' },
{
id: 'funding_type',
header: 'Förderart',
type: 'accessor',
accessorKey: 'funding_type',
cellTemplate: this.fundingTypeTmp(),
},
{
id: 'funding_start',
header: 'Förderbeginn',
type: 'accessor',
accessorKey: 'funding_start',
cellTemplate: this.fundingStartTmp(),
},
{
id: 'funding_end',
@@ -115,13 +126,6 @@ export class BundProjectTableComponent implements OnInit {
accessorKey: 'funding_end',
cellTemplate: this.fundingEndTmp(),
},
// {
// id: 'names',
// header: 'Autoren',
// type: 'accessor',
// accessorKey: 'names',
// cellTemplate: this.authorsTmp(),
// },
{
id: 'institutions',
header: 'Institutionen',
@@ -129,10 +133,11 @@ export class BundProjectTableComponent implements OnInit {
cellTemplate: this.institutionsTmp(),
},
{
id: 'professional_classification',
header: 'Fachliche Zuordnung',
type: 'display',
cellTemplate: this.detailRowTmp(),
id: 'grant_amount',
header: 'Förderbetrag',
type: 'accessor',
accessorKey: 'grant_amount',
cellTemplate: this.fundingAmountTmp(),
},
{
@@ -160,125 +165,23 @@ export class BundProjectTableComponent implements OnInit {
this.selectedAuthorIdsQueryParams().includes(String(authorId))
);
}
// getProjectAuthors(project: DfgProjectSummary): DfgPersonSummary[] {
// return project.persons?.filter((a): a is DfgPersonSummary => !!a) || [];
// }
// toggleProjectAuthorsExpansion(project: DfgProjectSummary): void {
// if (!project.id) return;
// if (this.expandedProjectAuthorsId.includes(project.id)) {
// this.expandedProjectAuthorsId = this.expandedProjectAuthorsId.filter(
// (id) => id !== project.id,
// );
// } else {
// this.expandedProjectAuthorsId.push(project.id);
// }
// }
isProjectPersonsExpanded(project: DfgProjectSummary): boolean {
if (!project.id) return false;
return this.expandedProjectAuthorsId.includes(project.id);
isFundingTypeActive(type: string): boolean {
return this.selectedFundingTypesQueryParams().includes(type);
}
// getAuthorTooltipText(author: DfgPersonSummary): string {
// if (this.authorFilterEnabled() && author.person_id) {
// return `Nach Autor filtern: ${author.full_name}`;
// }
// return `Autor: ${author.full_name}`;
// }
// filterByAuthor(authorId: number): void {
// if (!authorId || !this.authorFilterEnabled()) return;
// const selectedAuthorIds = this.selectedAuthorIdsQueryParams();
// if (selectedAuthorIds.includes(String(authorId))) {
// this.router.navigate([], {
// queryParams: {
// [this.queryParamKeys.authorId]: selectedAuthorIds.filter(
// (id) => id !== String(authorId),
// ),
// [this.queryParamKeys.page]: 0,
// },
// queryParamsHandling: 'merge',
// });
// } else {
// this.router.navigate([], {
// queryParams: {
// [this.queryParamKeys.authorId]: [
// ...selectedAuthorIds,
// String(authorId),
// ],
// [this.queryParamKeys.page]: 0,
// },
// queryParamsHandling: 'merge',
// });
// }
// }
isProjectInstitutionsExpanded(project: DfgProjectSummary): boolean {
if (!project.id) return false;
return this.expandedProjectInstitutionsId.includes(project.id);
getFundingTypeColor(type: string | null | undefined): string {
const normalized = (type ?? '').toLowerCase();
if (normalized == 'direkte projektförderung') return 'success';
if (normalized == 'indirekte projektförderung') return 'warning';
if (normalized == 'übrige indirekte projektförderung') return 'help';
return 'info';
}
toggleProjectInstitutionsExpansion(project: DfgProjectSummary): void {
if (!project.id) return;
if (this.expandedProjectInstitutionsId.includes(project.id)) {
this.expandedProjectInstitutionsId =
this.expandedProjectInstitutionsId.filter((id) => id !== project.id);
} else {
this.expandedProjectInstitutionsId.push(project.id);
}
}
getProjectInstitutions(project: DfgProjectSummary): any[] {
const institutions = new Map<string, any>();
for (const institution of project.institutions ?? []) {
const id = this.getProjectInstitutionId(institution);
if (!id) continue;
institutions.set(id, institution);
}
return Array.from(institutions.values()).sort((a, b) =>
this.getProjectInstitutionName(a).localeCompare(
this.getProjectInstitutionName(b),
),
);
}
getProjectInstitutionId(institution: any): string | null {
const id = institution.id;
return id == null ? null : String(id);
}
getProjectInstitutionName(institution: any): string {
return institution.institute_name_de ?? institution.institute_name_en;
}
isInstitutionActive(
institutionId: string | number | null | undefined,
): boolean {
return (
!!institutionId &&
this.institutionFilterEnabled() &&
this.selectedInstitutionIdsQueryParams().includes(String(institutionId))
);
}
filterByInstitution(institution: any): void {
const institutionId = this.getProjectInstitutionId(institution);
if (!institutionId || !this.institutionFilterEnabled()) return;
const selectedInstitutionIds = this.selectedInstitutionIdsQueryParams();
if (selectedInstitutionIds.includes(institutionId)) {
toggleFundingTypeFilter(type: string): void {
const selectedTypes = this.selectedFundingTypesQueryParams();
if (selectedTypes.includes(type)) {
this.router.navigate([], {
queryParams: {
[this.queryParamKeys.institutionId]: selectedInstitutionIds.filter(
(id) => id !== institutionId,
[this.queryParamKeys.funding_type]: selectedTypes.filter(
(t) => t !== type,
),
[this.queryParamKeys.page]: 0,
},
@@ -287,9 +190,70 @@ export class BundProjectTableComponent implements OnInit {
} else {
this.router.navigate([], {
queryParams: {
[this.queryParamKeys.institutionId]: [
[this.queryParamKeys.funding_type]: [...selectedTypes, type],
[this.queryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
}
}
isProjectPersonsExpanded(project: BundProjectSummary): boolean {
if (!project.institution?.name) return false;
return this.expandedProjectAuthorsId.includes(project.institution.name);
}
getStartDate(element: BundProjectSummary): string | Date | undefined {
return (element as any).funding_start;
}
getEndDate(element: BundProjectSummary): string | Date | undefined {
return (element as any).funding_end;
}
getFundingAmount(element: BundProjectSummary): number | undefined {
return (element as any).grant_amount;
}
getProjectInstitutions(project: BundProjectSummary): any[] {
return project.institution ? [project.institution] : [];
}
isInstitutionActive(
institution_name: string | number | null | undefined,
): boolean {
return (
!!institution_name &&
this.institutionFilterEnabled() &&
this.selectedInstitutionIdsQueryParams().includes(
String(institution_name),
)
);
}
filterByInstitution(institution: any): void {
const institutionName = institution.name ?? institution.recepient;
if (!institutionName || !this.institutionFilterEnabled()) return;
const selectedInstitutionIds = this.selectedInstitutionIdsQueryParams();
if (selectedInstitutionIds.includes(institutionName)) {
this.router.navigate([], {
queryParams: {
[this.queryParamKeys.agency]: selectedInstitutionIds.filter(
(id) => id !== institutionName,
),
[this.queryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
} else {
this.router.navigate([], {
queryParams: {
[this.queryParamKeys.agency]: [
...selectedInstitutionIds,
institutionId,
institutionName,
],
[this.queryParamKeys.page]: 0,
},
@@ -299,7 +263,7 @@ export class BundProjectTableComponent implements OnInit {
}
getInstitutionTooltipText(institution: any): string {
const name = this.getProjectInstitutionName(institution);
const name = institution.name ?? institution.recepient ?? 'Unbekannt';
if (this.institutionFilterEnabled()) {
return `Nach Institution filtern: ${name}`;
@@ -350,20 +314,20 @@ export class BundProjectTableComponent implements OnInit {
});
}
}
toggleProjectTopicsExpansion(project: DfgProjectSummary): void {
if (!project.id) return;
toggleProjectTopicsExpansion(project: BundProjectSummary): void {
if (!project.funding_code) return;
if (this.expandedProjectTopicsId.includes(project.id)) {
if (this.expandedProjectTopicsId.includes(project.funding_code)) {
this.expandedProjectTopicsId = this.expandedProjectTopicsId.filter(
(id) => id !== project.id,
(id) => id !== project.funding_code,
);
} else {
this.expandedProjectTopicsId.push(project.id);
this.expandedProjectTopicsId.push(project.funding_code);
}
}
isProjectTopicsExpanded(project: DfgProjectSummary): boolean {
if (!project.id) return false;
isProjectTopicsExpanded(project: BundProjectSummary): boolean {
if (!project.funding_code) return false;
return this.expandedProjectTopicsId.includes(project.id);
return this.expandedProjectTopicsId.includes(project.funding_code);
}
}
@@ -6,6 +6,7 @@
[selectedTopicsPage]="selectedTopicsPage()"
[showFundingStartFilter]="true"
[showTopicFilter]="topicFilterEnabled()"
[showBundFundingTypeFilter]="true"
[showFundingEndFilter]="true"
[showAuthorFilter]="true"
[showInstitutionFilter]="true"
@@ -6,7 +6,7 @@ import {
DfgPersonSummaryPage,
TopicPageV2,
} from '../../../api';
import { DfgInstitutionSummaryPage } from '../../../api/model/dfgInstitutionSummaryPage';
import { BundInstitutionSummaryPage } from '../../../api/model/bundInstitutionSummaryPage';
import { MatCardModule } from '@angular/material/card';
import { MatTabsModule } from '@angular/material/tabs';
import { ProjectFilterComponent } from '../project-filters/project-filters.component';
@@ -26,8 +26,7 @@ import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.reso
export class BundProjectsComponent {
bundProjectPage = input.required<BundProjectPage>();
selectedBundInstitutionsPage = input.required<DfgInstitutionSummaryPage>();
selectedBundAuthorsPage = input.required<DfgPersonSummaryPage>();
selectedBundInstitutionsPage = input.required<BundInstitutionSummaryPage>();
selectedTopicsPage = input.required<TopicPageV2>();
@@ -6,9 +6,9 @@
<app-query-param-paginator
[total]="total()"
[queryParamPageKey]="queryParamKeys.page"
[queryParamSizeKey]="queryParamKeys.size"
[pageSizeOptions]="[10]" />
queryParamPageKey="page"
queryParamSizeKey="size"
[pageSizeOptions]="[10, 25, 50]" />
<ng-template #fundingEndTmp let-element>
{{
@@ -6,9 +6,9 @@
<app-query-param-paginator
[total]="total()"
[queryParamPageKey]="queryParamKeys.page"
[queryParamSizeKey]="queryParamKeys.size"
[pageSizeOptions]="[10]" />
queryParamPageKey="page"
queryParamSizeKey="size"
[pageSizeOptions]="[10, 25, 50]" />
<ng-template #projectTypeTmp let-project>
@if (project.project_type) {
@@ -120,14 +120,14 @@ export class EuProjectTableComponent {
},
{
id: 'startDate',
header: 'Startdatum',
header: 'Förderbeginn',
type: 'accessor',
accessorKey: 'start_date',
cellTemplate: this.fundingStartTmp(),
},
{
id: 'endDate',
header: 'Enddatum',
header: 'Förderende',
type: 'accessor',
accessorKey: 'end_date',
cellTemplate: this.fundingEndTmp(),
@@ -22,6 +22,14 @@
[selectedYears]="selectedFundingEndYears()"
(handleYearSelectChange)="handleFundingEndSelectChange($event)" />
}
@if (showBundFundingTypeFilter() && filterMode() === 'bund') {
<app-searchable-bund-funding-type-select
[label]="bundFundingTypeLabel()"
[selectedBundFundingTypes]="selectedBundFundingTypes()"
(handleBundFundingTypeSelectChange)="
handleBundFundingTypeSelectChange($event)
" />
}
@if (showEuProjectTypeFilter() && filterMode() === 'eu') {
<app-searchable-eu-project-type-select
[label]="euProjectTypeLabel()"
@@ -48,6 +56,14 @@
handleEuInstitutionSelectChange($event)
" />
}
@if (showInstitutionFilter() && filterMode() === 'bund') {
<app-searchable-bund-institution-select
[label]="bundInstitutionLabel()"
[selectedInstitutions]="selectedBundInstitutions()"
(handleInstitutionSelectChange)="
handleBundInstitutionSelectChange($event)
" />
}
@if (showAuthorFilter() && filterMode() === 'dfg') {
<app-searchable-dfg-author-select
@@ -9,6 +9,8 @@ import { MatSelectModule } from '@angular/material/select';
import { DfgInstitutionSummaryPage } from '../../../api/model/dfgInstitutionSummaryPage';
import { DfgInstitutionSummary } from '../../../api/model/dfgInstitutionSummary';
import { BundInstitutionSummary } from '../../../api/model/bundInstitutionSummary';
import { BundInstitutionSummaryPage } from '../../../api/model/bundInstitutionSummaryPage';
import {
Author,
@@ -32,9 +34,15 @@ import { TopicLegendComponent } from '../topic-legend/topic-legend.component';
import { QueryParamInputComponent } from '../query-param-input/query-param-input.component';
import { SearchableDfgInstitutionSelectComponent } from '../searchable-dfg-institution-select/searchable-dfg-institution-select.component';
import { SearchableEuInstitutionSelectComponent } from '../searchable-eu-institution-select/searchable-eu-institution-select.component';
import { SearchableBundInstitutionSelectComponent } from '../searchable-bund-institution-select/searchable-bund-institution-select.component';
import { SearchableYearSelectComponent } from '../searchable-year-select/searchable-year-select.component';
import { SearchableDfgAuthorSelectComponent } from '../searchable-dfg-author-select/searchable-dfg-author-select.component';
import { SearchableTopicSelectComponent } from '../searchable-topic-select/searchable-topic-select.component';
import {
SearchableBundFundingTypeSelectComponent,
FundingType,
findFundingTypeById,
} from '../searchable-bund-funding-type-select/searchable-bund-funding-type-select.component';
import {
SearchableEuProjectTypeSelectComponent,
ProjectType,
@@ -74,6 +82,8 @@ type ProjectQueryParamKeys =
SearchableTopicSelectComponent,
TopicLegendComponent,
SearchableEuProjectTypeSelectComponent,
SearchableBundFundingTypeSelectComponent,
SearchableBundInstitutionSelectComponent,
],
templateUrl: './project-filters.component.html',
styleUrl: './project-filters.component.scss',
@@ -87,7 +97,7 @@ export class ProjectFilterComponent {
selectedDfgInstitutionsPage = input<DfgInstitutionSummaryPage>();
selectedEuInstitutionsPage = input<EuCordisOrganizationSelectorPage>();
selectedBundInstitutionsPage = input<DfgInstitutionSummaryPage>();
selectedBundInstitutionsPage = input<BundInstitutionSummaryPage>();
selectedDfgAuthorsPage = input<DfgPersonSummaryPage>();
selectedEuAuthorsPage = input<AuthorPage>();
@@ -100,6 +110,7 @@ export class ProjectFilterComponent {
showFundingEndFilter = input<boolean>(false);
showTopicFilter = input<boolean>(true);
showEuProjectTypeFilter = input<boolean>(false);
showBundFundingTypeFilter = input<boolean>(false);
selectedDfgAuthors = computed<DfgPersonSummary[]>(
() => this.selectedDfgAuthorsPage()?.elements || [],
@@ -116,7 +127,9 @@ export class ProjectFilterComponent {
selectedEuInstitutions = computed<EuCordisOrganizationSelectorSummary[]>(
() => this.selectedEuInstitutionsPage()?.elements || [],
);
selectedBundInstitutions = computed<BundInstitutionSummary[]>(
() => this.selectedBundInstitutionsPage()?.elements || [],
);
selectedTopics = computed<Topic[]>(
() => this.selectedTopicsPage()?.elements || [],
);
@@ -228,6 +241,19 @@ export class ProjectFilterComponent {
return `${selected.length} Institutionen`;
});
bundInstitutionLabel = computed(() => {
const selected = this.selectedBundInstitutions().filter((i) =>
this.selectedInstitutionIds().includes(String(i.name!)),
);
if (selected.length === 0) return 'Institution';
if (selected.length === 1) {
return selected[0].name ?? 'Institution';
}
return `${selected.length} Institutionen`;
});
dfgAuthorLabel = computed(() => {
const selected = this.selectedDfgAuthors().filter((a) =>
this.dfgSelectedAuthorIds().includes(String(a.person_id!)),
@@ -362,6 +388,30 @@ export class ProjectFilterComponent {
},
});
}
if (this.filterMode() === 'bund') {
const bundKeys = keys as typeof bundProjectQueryParamKeys;
observers.push({
id: 'fundingTypes',
queryParamKey: bundKeys.funding_type,
icon: 'category',
valueFormatter: (value: string) => {
const fundingType = findFundingTypeById(value);
return fundingType ? fundingType.name : value;
},
});
observers.push({
id: 'agencies',
queryParamKey: bundKeys.agency,
icon: 'apartment',
valueFormatter: (value: string) => {
const institution = this.selectedBundInstitutions().find(
(i) => String(i.name) === value,
);
return institution ? institution.name : value;
},
});
}
return observers;
});
@@ -465,7 +515,28 @@ export class ProjectFilterComponent {
queryParamsHandling: 'merge',
});
};
handleBundInstitutionSelectChange = (
institution: BundInstitutionSummary,
): void => {
if (!institution.name) return;
const keys = this.queryParamKeys() as typeof bundProjectQueryParamKeys;
const selectedIds = this.selectedInstitutionIds();
const agency_name = String(institution.name);
const nextIds = selectedIds.includes(agency_name)
? selectedIds.filter((id) => id !== agency_name)
: [...selectedIds, agency_name];
this.router.navigate([], {
queryParams: {
[keys.agency]: nextIds,
[keys.page]: 0,
},
queryParamsHandling: 'merge',
});
};
handleDfgAuthorSelectChange = (author: DfgPersonSummary): void => {
if (!author.person_id) return;
@@ -539,6 +610,19 @@ export class ProjectFilterComponent {
queryParamsHandling: 'merge',
});
};
handleBundFundingTypeSelectChange = (
selectedFundingTypes: FundingType,
): void => {
const keys = this.queryParamKeys() as typeof bundProjectQueryParamKeys;
this.router.navigate([], {
queryParams: {
[keys.funding_type]: selectedFundingTypes.id,
[keys.page]: 0,
},
queryParamsHandling: 'merge',
});
};
get topicLegendGroups(): TopicLegendGroup[] {
const topics = this.selectedTopics().map((topic) =>
@@ -563,4 +647,23 @@ export class ProjectFilterComponent {
subfield_description: null,
};
}
selectedBundFundingTypes = computed(() => {
const projectTypeIds = this.queryParamMap().getAll(
(this.queryParamKeys() as any).project_type,
);
return projectTypeIds
.map((id) => findFundingTypeById(id))
.filter((type) => type !== undefined) as FundingType[];
});
bundFundingTypeLabel = computed(() => {
const selected = this.selectedBundFundingTypes();
if (selected.length === 0) return 'Förderungstyp';
if (selected.length === 1) {
return selected[0].name ?? 'Förderungstyp';
}
return `${selected.length} Förderungstypen`;
});
}
@@ -0,0 +1,11 @@
<app-searchable-select
inputPlaceholder="Typ suchen..."
icon="category"
[label]="label()"
selectedLabel="Ausgewählte Typen"
fetchedLabel="Weitere Typen"
[fetchElements]="fetchFundingTypes"
[selectedElements]="selectedBundFundingTypes()"
[getSelectLabel]="getFundingTypeLabel"
[getSelectValue]="getFundingTypeValue"
(handleSelectChange)="handleBundFundingTypeSelectChange.emit($event)" />
@@ -0,0 +1,64 @@
import { Component, input, output } from '@angular/core';
import { SearchableSelectComponent } from '../searchable-select/searchable-select.component';
import { Observable } from 'rxjs';
export type FundingType = {
id: string;
name: string;
};
export const projectTypes: FundingType[] = [
{ id: 'Direkte Projektförderung', name: 'Direkte Projektförderung' },
{ id: 'Indirekte Projektförderung', name: 'Indirekte Projektförderung' },
{
id: 'Übrige indirekte Projektförderung',
name: 'Übrige indirekte Projektförderung',
},
{
id: 'Sonstige internationale Leistungen',
name: 'Sonstige internationale Leistungen',
},
];
export const findFundingTypeById = (id: string): FundingType | undefined => {
return projectTypes.find((fundingType) => fundingType.id === id);
};
type FundingTypePage = {
elements?: FundingType[];
page?: number;
size?: number;
total?: number;
};
@Component({
selector: 'app-searchable-bund-funding-type-select',
imports: [SearchableSelectComponent],
templateUrl: './searchable-bund-funding-type-select.component.html',
styleUrl: './searchable-bund-funding-type-select.component.scss',
})
export class SearchableBundFundingTypeSelectComponent {
label = input<string>('Typen');
selectedBundFundingTypes = input.required<FundingType[]>();
handleBundFundingTypeSelectChange = output<FundingType>();
fetchFundingTypes = (searchTerm: string): Observable<FundingTypePage> => {
return new Observable<FundingTypePage>((observer) => {
observer.next({
elements: projectTypes.filter((fundingType) =>
fundingType.name.toLowerCase().includes(searchTerm.toLowerCase()),
),
});
observer.complete();
});
};
getFundingTypeLabel = (fundingType: FundingType): string => {
return fundingType.name;
};
getFundingTypeValue = (fundingType: FundingType): string => {
return fundingType.id;
};
}
@@ -0,0 +1,12 @@
<app-searchable-select
inputPlaceholder="Institution suchen..."
icon="apartment"
[label]="label()"
selectedLabel="Ausgewählte Institutionen"
fetchedLabel="Gefundene Institutionen"
[fetchElements]="fetchInstitutions"
[selectedElements]="selectedInstitutions()"
[getSelectLabel]="getInstitutionLabel"
[getSelectValue]="getInstitutionValue"
[getSelectDescription]="getInstitutionDescription"
(handleSelectChange)="handleInstitutionSelectChange.emit($event)" />
@@ -0,0 +1,51 @@
import { Component, inject, input, output } from '@angular/core';
import { BUNDInstitutionsService } from '../../../api';
import { Observable } from 'rxjs';
import { SearchableSelectComponent } from '../searchable-select/searchable-select.component';
import { BundInstitutionSummary } from '../../../api/model/bundInstitutionSummary';
import { BundInstitutionSummaryPage } from '../../../api/model/bundInstitutionSummaryPage';
@Component({
selector: 'app-searchable-bund-institution-select',
imports: [SearchableSelectComponent],
templateUrl: './searchable-bund-institution-select.component.html',
styleUrl: './searchable-bund-institution-select.component.scss',
})
export class SearchableBundInstitutionSelectComponent {
private readonly bundInstitutionService = inject(BUNDInstitutionsService);
label = input<string>('Institutionen');
selectedInstitutions = input.required<BundInstitutionSummary[]>();
handleInstitutionSelectChange = output<BundInstitutionSummary>();
fetchInstitutions = (
searchTerm: string,
): Observable<BundInstitutionSummaryPage> => {
return this.bundInstitutionService.getBundInstitutionAutocompleteForSelector(
searchTerm,
);
};
getInstitutionLabel = (institution: BundInstitutionSummary): string => {
return (
institution.name ||
institution.recepient ||
institution.department ||
'Unbekannte Institution'
);
};
getInstitutionValue = (institution: BundInstitutionSummary): string => {
return Number(institution.name!).toString();
};
getInstitutionDescription = (institution: BundInstitutionSummary): string => {
return (
institution.country! +
' - ' +
institution.state! +
'- ' +
institution.municipality!
);
};
}