diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 8318ac59..07750aed 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -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) diff --git a/service/src/main/inse/projects/bund_institutions/model.py b/service/src/main/inse/projects/bund_institutions/model.py new file mode 100644 index 00000000..7a4099fe --- /dev/null +++ b/service/src/main/inse/projects/bund_institutions/model.py @@ -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 \ No newline at end of file diff --git a/service/src/main/inse/projects/bund_institutions/router.py b/service/src/main/inse/projects/bund_institutions/router.py new file mode 100644 index 00000000..51c2ae68 --- /dev/null +++ b/service/src/main/inse/projects/bund_institutions/router.py @@ -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) diff --git a/service/src/main/inse/projects/bund_institutions/service.py b/service/src/main/inse/projects/bund_institutions/service.py new file mode 100644 index 00000000..c550391e --- /dev/null +++ b/service/src/main/inse/projects/bund_institutions/service.py @@ -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, + ) \ No newline at end of file diff --git a/service/src/main/inse/projects/logic.py b/service/src/main/inse/projects/logic.py index 641a6f7e..2535073c 100644 --- a/service/src/main/inse/projects/logic.py +++ b/service/src/main/inse/projects/logic.py @@ -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. diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index af12afd7..7094cba5 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -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 diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 881480f7..8b63aaeb 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -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": {}} diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index 3440bd2f..c3bf0f89 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -24,3 +24,5 @@ class Tags(StrEnum): DFG_INSTITUTIONS = "DFG Institutions" DFG_PERSONS = "DFG Persons" BACKGROUND_JOBS = "Background Jobs" + + BUND_INSTITUTIONS = "BUND Institutions" diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 0670df10..20eadd30 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -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 diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index 0ae4a16e..154e0dc5 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -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, +]; diff --git a/webapp/src/app/api/api/bUNDInstitutions.service.ts b/webapp/src/app/api/api/bUNDInstitutions.service.ts new file mode 100644 index 00000000..1e01fb85 --- /dev/null +++ b/webapp/src/app/api/api/bUNDInstitutions.service.ts @@ -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; + public getBundInstitutionAutocompleteForSelector( + query?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBundInstitutionAutocompleteForSelector( + query?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBundInstitutionAutocompleteForSelector( + query?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + 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( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: 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, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getBundInstitutionsByName( + institutionNames?: Array, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBundInstitutionsByName( + institutionNames?: Array, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBundInstitutionsByName( + institutionNames?: Array, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (institutionNames) { + institutionNames.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + 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( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } +} diff --git a/webapp/src/app/api/model/bundInstitutionSummary.ts b/webapp/src/app/api/model/bundInstitutionSummary.ts new file mode 100644 index 00000000..dba7f1bc --- /dev/null +++ b/webapp/src/app/api/model/bundInstitutionSummary.ts @@ -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; +} diff --git a/webapp/src/app/api/model/bundInstitutionSummaryPage.ts b/webapp/src/app/api/model/bundInstitutionSummaryPage.ts new file mode 100644 index 00000000..f1e39b95 --- /dev/null +++ b/webapp/src/app/api/model/bundInstitutionSummaryPage.ts @@ -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; + /** + * The page number. (0-based) + */ + page?: number; + /** + * The page size in elements. + */ + size?: number; + /** + * The total number of elements. + */ + total?: number; +} diff --git a/webapp/src/app/api/model/bundProjectSummary.ts b/webapp/src/app/api/model/bundProjectSummary.ts index e4fa0346..7b0d011c 100644 --- a/webapp/src/app/api/model/bundProjectSummary.ts +++ b/webapp/src/app/api/model/bundProjectSummary.ts @@ -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 | 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 | null; + institution?: BundInstitutionSummary | null; } - diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 91138098..89361c91 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -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'; diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 27ab1022..35393b5c 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -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, - }, - }, ], }, { diff --git a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts index c58a9776..224b934f 100644 --- a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts @@ -41,5 +41,9 @@ export class KeywordsToProjectsResultsComponent { path: 'eu', label: 'EU-Projekte', }, + { + path: 'bund', + label: 'BUND-Projekte', + }, ]; } diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.html b/webapp/src/app/modules/keywords-search/search-results/search-results.component.html index 92e78a17..758b2d1c 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.html @@ -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"> {{ route.icon }} diff --git a/webapp/src/app/modules/person-projects/person-projects.component.ts b/webapp/src/app/modules/person-projects/person-projects.component.ts index 2463687b..359a9d9c 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -27,9 +27,5 @@ export class PersonProjectsComponent { path: 'eu', label: 'EU-Projekte', }, - { - path: 'bund', - label: 'Bund-Projekte', - }, ]; } diff --git a/webapp/src/app/modules/projects/bund-details/bund-details.component.html b/webapp/src/app/modules/projects/bund-details/bund-details.component.html index 48c7f9b7..345101a3 100644 --- a/webapp/src/app/modules/projects/bund-details/bund-details.component.html +++ b/webapp/src/app/modules/projects/bund-details/bund-details.component.html @@ -64,6 +64,7 @@
{{ getFundingStatus(bundProject.funding_end_date) + | date: 'dd.MM.yyyy' }} Förderende
diff --git a/webapp/src/app/resolvers/bund-projects.resolver.ts b/webapp/src/app/resolvers/bund-projects.resolver.ts index 4dd3e63f..78e8269a 100644 --- a/webapp/src/app/resolvers/bund-projects.resolver.ts +++ b/webapp/src/app/resolvers/bund-projects.resolver.ts @@ -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 = ( 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 = ( 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, ); }; diff --git a/webapp/src/app/resolvers/selected-bund-institutions.resolver.ts b/webapp/src/app/resolvers/selected-bund-institutions.resolver.ts new file mode 100644 index 00000000..a9155dac --- /dev/null +++ b/webapp/src/app/resolvers/selected-bund-institutions.resolver.ts @@ -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); +}; diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html index 83c8e2cf..25d99ee9 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.html @@ -6,21 +6,25 @@ + queryParamPageKey="page" + queryParamSizeKey="size" + [pageSizeOptions]="[10, 25, 50]" /> + + + {{ getStartDate(element) | date: 'dd.MM.yyyy' }} + - {{ - element.funding_end == '2999' || element.funding_end == null - ? 'laufend' - : element.funding_end - }} + {{ getEndDate(element) | date: 'dd.MM.yyyy' }} + + + + {{ getFundingAmount(element) | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} @@ -42,43 +46,6 @@ - - - - - @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) - ) { - - } @empty { - - - } - @if (institutions.length > 3) { - - } + + + @if (project.funding_type) { + + } @else { + - + } + + - @let projectTopics = project.topics ?? []; + @let projectTopics = project.oa_topics ?? []; @let isTopicsExpanded = isProjectTopicsExpanded(project); @let visibleTopics = isTopicsExpanded ? projectTopics : projectTopics.slice(0, 3); diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss index 3fd1bb17..adcd6203 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss @@ -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; diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts index b40d5649..e04dfdb7 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.ts @@ -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[] = []; titleTmp = viewChild.required>('titleTmp'); - authorsTmp = viewChild.required>('authorsTmp'); + fundingTypeTmp = viewChild.required>('fundingTypeTmp'); institutionsTmp = viewChild.required>('institutionsTmp'); fundingStartTmp = viewChild.required>('fundingStartTmp'); fundingEndTmp = viewChild.required>('fundingEndTmp'); actionsTmp = viewChild.required>('actionsTmp'); - detailRowTmp = viewChild.required>('detailRowTmp'); + fundingAmountTmp = + viewChild.required>('fundingAmountTmp'); topicsTmp = viewChild.required>('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(); - - 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); } } diff --git a/webapp/src/app/shared/ui/bund-projects/bund-projects.component.html b/webapp/src/app/shared/ui/bund-projects/bund-projects.component.html index 1d0cb5ac..a5d0c236 100644 --- a/webapp/src/app/shared/ui/bund-projects/bund-projects.component.html +++ b/webapp/src/app/shared/ui/bund-projects/bund-projects.component.html @@ -6,6 +6,7 @@ [selectedTopicsPage]="selectedTopicsPage()" [showFundingStartFilter]="true" [showTopicFilter]="topicFilterEnabled()" + [showBundFundingTypeFilter]="true" [showFundingEndFilter]="true" [showAuthorFilter]="true" [showInstitutionFilter]="true" diff --git a/webapp/src/app/shared/ui/bund-projects/bund-projects.component.ts b/webapp/src/app/shared/ui/bund-projects/bund-projects.component.ts index 18baaa84..d435a9b6 100644 --- a/webapp/src/app/shared/ui/bund-projects/bund-projects.component.ts +++ b/webapp/src/app/shared/ui/bund-projects/bund-projects.component.ts @@ -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(); - selectedBundInstitutionsPage = input.required(); - selectedBundAuthorsPage = input.required(); + selectedBundInstitutionsPage = input.required(); selectedTopicsPage = input.required(); diff --git a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html index 501834dc..5d934742 100644 --- a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html +++ b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.html @@ -6,9 +6,9 @@ + queryParamPageKey="page" + queryParamSizeKey="size" + [pageSizeOptions]="[10, 25, 50]" /> {{ diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html index 47dc0938..6a3c9c5c 100644 --- a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html +++ b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.html @@ -6,9 +6,9 @@ + queryParamPageKey="page" + queryParamSizeKey="size" + [pageSizeOptions]="[10, 25, 50]" /> @if (project.project_type) { diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts index d0dd36ef..ad0ac7be 100644 --- a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts +++ b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.ts @@ -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(), diff --git a/webapp/src/app/shared/ui/project-filters/project-filters.component.html b/webapp/src/app/shared/ui/project-filters/project-filters.component.html index dc2b3926..f6308146 100644 --- a/webapp/src/app/shared/ui/project-filters/project-filters.component.html +++ b/webapp/src/app/shared/ui/project-filters/project-filters.component.html @@ -22,6 +22,14 @@ [selectedYears]="selectedFundingEndYears()" (handleYearSelectChange)="handleFundingEndSelectChange($event)" /> } + @if (showBundFundingTypeFilter() && filterMode() === 'bund') { + + } @if (showEuProjectTypeFilter() && filterMode() === 'eu') { } + @if (showInstitutionFilter() && filterMode() === 'bund') { + + } @if (showAuthorFilter() && filterMode() === 'dfg') { (); selectedEuInstitutionsPage = input(); - selectedBundInstitutionsPage = input(); + selectedBundInstitutionsPage = input(); selectedDfgAuthorsPage = input(); selectedEuAuthorsPage = input(); @@ -100,6 +110,7 @@ export class ProjectFilterComponent { showFundingEndFilter = input(false); showTopicFilter = input(true); showEuProjectTypeFilter = input(false); + showBundFundingTypeFilter = input(false); selectedDfgAuthors = computed( () => this.selectedDfgAuthorsPage()?.elements || [], @@ -116,7 +127,9 @@ export class ProjectFilterComponent { selectedEuInstitutions = computed( () => this.selectedEuInstitutionsPage()?.elements || [], ); - + selectedBundInstitutions = computed( + () => this.selectedBundInstitutionsPage()?.elements || [], + ); selectedTopics = computed( () => 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`; + }); } diff --git a/webapp/src/app/shared/ui/searchable-bund-funding-type-select/searchable-bund-funding-type-select.component.html b/webapp/src/app/shared/ui/searchable-bund-funding-type-select/searchable-bund-funding-type-select.component.html new file mode 100644 index 00000000..cbf83cbd --- /dev/null +++ b/webapp/src/app/shared/ui/searchable-bund-funding-type-select/searchable-bund-funding-type-select.component.html @@ -0,0 +1,11 @@ + diff --git a/webapp/src/app/shared/ui/searchable-bund-funding-type-select/searchable-bund-funding-type-select.component.scss b/webapp/src/app/shared/ui/searchable-bund-funding-type-select/searchable-bund-funding-type-select.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/searchable-bund-funding-type-select/searchable-bund-funding-type-select.component.ts b/webapp/src/app/shared/ui/searchable-bund-funding-type-select/searchable-bund-funding-type-select.component.ts new file mode 100644 index 00000000..385367a5 --- /dev/null +++ b/webapp/src/app/shared/ui/searchable-bund-funding-type-select/searchable-bund-funding-type-select.component.ts @@ -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('Typen'); + selectedBundFundingTypes = input.required(); + + handleBundFundingTypeSelectChange = output(); + + fetchFundingTypes = (searchTerm: string): Observable => { + return new Observable((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; + }; +} diff --git a/webapp/src/app/shared/ui/searchable-bund-institution-select/searchable-bund-institution-select.component.html b/webapp/src/app/shared/ui/searchable-bund-institution-select/searchable-bund-institution-select.component.html new file mode 100644 index 00000000..ea0f7c1f --- /dev/null +++ b/webapp/src/app/shared/ui/searchable-bund-institution-select/searchable-bund-institution-select.component.html @@ -0,0 +1,12 @@ + diff --git a/webapp/src/app/shared/ui/searchable-bund-institution-select/searchable-bund-institution-select.component.scss b/webapp/src/app/shared/ui/searchable-bund-institution-select/searchable-bund-institution-select.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/searchable-bund-institution-select/searchable-bund-institution-select.component.ts b/webapp/src/app/shared/ui/searchable-bund-institution-select/searchable-bund-institution-select.component.ts new file mode 100644 index 00000000..c4caa643 --- /dev/null +++ b/webapp/src/app/shared/ui/searchable-bund-institution-select/searchable-bund-institution-select.component.ts @@ -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('Institutionen'); + selectedInstitutions = input.required(); + + handleInstitutionSelectChange = output(); + + fetchInstitutions = ( + searchTerm: string, + ): Observable => { + 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! + ); + }; +}