diff --git a/service/src/main/inse/company_connections/logic.py b/service/src/main/inse/company_connections/logic.py index a11d21f9..ceb39e06 100644 --- a/service/src/main/inse/company_connections/logic.py +++ b/service/src/main/inse/company_connections/logic.py @@ -75,20 +75,24 @@ async def get_company_connections_by_author_id( async def get_company_counts_by_names( names: list[str], + company_status: str = "all", client: CompanyConnectionsSearchClient | None = None, ) -> dict[str, int]: """Bulk variant of the per-author lookup for the ranking pipeline. Returns a mapping ``display_name -> company_count`` for the given names in a single Elasticsearch aggregation. Names without a match are absent from the - mapping (callers should treat them as 0). + mapping (callers should treat them as 0). ``company_status`` selects which + companies to count: ``all``, only ``active`` (non-deleted), or only ``deleted``. """ search_client = client or CompanyConnectionsSearchClient() cleaned = [name for name in (_clean(n) for n in names) if name] if not cleaned: return {} - return await search_client.count_companies_by_founder_names(cleaned) + return await search_client.count_companies_by_founder_names( + cleaned, company_status=str(company_status) + ) def _get_ude_institution_scope(source: dict[str, Any]) -> tuple[str | None, list[str]]: diff --git a/service/src/main/inse/company_connections/search_client.py b/service/src/main/inse/company_connections/search_client.py index cae4dd3b..3e391ac8 100644 --- a/service/src/main/inse/company_connections/search_client.py +++ b/service/src/main/inse/company_connections/search_client.py @@ -61,14 +61,18 @@ class CompanyConnectionsSearchClient: async def count_companies_by_founder_names( self, founder_names: list[str], + company_status: str = "all", ) -> dict[str, int]: """Returns the number of companies they are linked to a author. + + ``company_status`` selects which companies are counted: ``all``, only + ``active`` (non-deleted), or only ``deleted`` (``current_status: removed``). """ names = sorted({name for name in founder_names if name}) if not names: return {} - payload = self.handelsregister_founder_counts_query(names) + payload = self.handelsregister_founder_counts_query(names, company_status) response = await elasticsearch.search( index=self.handelsregister_index, body=payload, @@ -95,17 +99,19 @@ class CompanyConnectionsSearchClient: @staticmethod def handelsregister_founder_counts_query( founder_names: list[str], + company_status: str = "all", ) -> dict[str, Any]: """Aggregation that counts distinct companies per founder name. The ``matched`` filter keeps only the founders whose name is one of the candidates, then ``reverse_nested`` steps back to the company level so the per-name ``doc_count`` is a company count, not a founder-occurrence count. + ``company_status`` restricts which companies are counted at the company + level: ``all`` (no restriction), only ``active`` (exclude + ``current_status: removed``), or only ``deleted`` (only that status). """ - return { - "size": 0, - "track_total_hits": False, - "query": { + query_filters: list[dict[str, Any]] = [ + { "nested": { "path": "officers", "query": { @@ -117,7 +123,19 @@ class CompanyConnectionsSearchClient: } }, } - }, + } + ] + + bool_query: dict[str, Any] = {"filter": query_filters} + if company_status == "active": + bool_query["must_not"] = [{"term": {"current_status": "removed"}}] + elif company_status == "deleted": + query_filters.append({"term": {"current_status": "removed"}}) + + return { + "size": 0, + "track_total_hits": False, + "query": {"bool": bool_query}, "aggs": { "founders": { "nested": {"path": "officers"}, diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 5af9cf2b..b9e5b148 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -17,6 +17,7 @@ from .model import ( AuthorImpactStats, AuthorYearlyWorks, CareerStage, + CompanyStatusFilter, KeywordOperator, PublicationType, RankedAuthor, @@ -706,17 +707,21 @@ async def _career_stages_for_authors(author_ids: List[str]) -> dict: return stages -async def _enrich_with_company_counts(authors: List[RankedAuthor]) -> None: +async def _enrich_with_company_counts( + authors: List[RankedAuthor], + company_status: CompanyStatusFilter = CompanyStatusFilter.ALL, +) -> None: """Sets each author's company_count from a single bulk Handelsregister query. Matching is by exact display name (same as the company-connections feature), so - authors without a name match keep a count of 0. + authors without a name match keep a count of 0. ``company_status`` selects which + companies are counted: all, only active (non-deleted), or only deleted. """ if not authors: return names = [author.display_name for author in authors if author.display_name] - counts = await get_company_counts_by_names(names) + counts = await get_company_counts_by_names(names, company_status=company_status) for author in authors: author.companies_count = counts.get(author.display_name, 0) @@ -730,6 +735,7 @@ async def rank_authors_by_keywords( career_stages: List[CareerStage], publication_types: List[PublicationType], timespan: Optional[Timespan], + company_status: CompanyStatusFilter = CompanyStatusFilter.ALL, ) -> List[RankedAuthor]: """Ranks the university's authors by a weighted score over works and citations. @@ -771,7 +777,7 @@ async def rank_authors_by_keywords( # Company connections are only fetched when they actually influence the score, # avoiding an extra Handelsregister query for the common works/citations case. if weights.companies > 0: - await _enrich_with_company_counts(ranked_authors) + await _enrich_with_company_counts(ranked_authors, company_status) _apply_scores(ranked_authors, weights) diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index dcb0e7d4..1121a515 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -13,6 +13,12 @@ class KeywordOperator(StrEnum): AND = "and" OR = "or" + +class CompanyStatusFilter(StrEnum): + ALL = "all" + ACTIVE = "active" + DELETED = "deleted" + class CareerStage(StrEnum): UNKNOWN = "unknown" EARLY = "Early" @@ -105,6 +111,11 @@ class KeywordToAuthorRequest(BaseModel): default=None, description="Optional filter: only count works whose publication_year is within [from, to].", ) + company_status: CompanyStatusFilter = Field( + default=CompanyStatusFilter.ALL, + description="Which companies to count for the company-foundations metric: " + "'all', only 'active' (non-deleted), or only 'deleted'.", + ) @field_validator("operator", mode="before") @classmethod diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index 1ac770e1..26bd5b80 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -42,6 +42,7 @@ async def rank_author(request: KeywordToAuthorRequest): request.career_stages, request.publication_types, request.timespan, + request.company_status, ) diff --git a/webapp/src/app/api/model/keywordToAuthorRequest.ts b/webapp/src/app/api/model/keywordToAuthorRequest.ts index 3eb1d8f9..8710d957 100644 --- a/webapp/src/app/api/model/keywordToAuthorRequest.ts +++ b/webapp/src/app/api/model/keywordToAuthorRequest.ts @@ -38,4 +38,8 @@ export interface KeywordToAuthorRequest { * Optional filter: only count works whose publication_year is within [from, to]. */ timespan?: { from: number; to: number }; + /** + * Which companies to count for the company-foundations metric: \'all\', only \'active\' (non-deleted), or only \'deleted\'. + */ + company_status?: string; } diff --git a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html index 5ec55e27..fa3daef6 100644 --- a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html @@ -136,6 +136,19 @@ + +
+ + Unternehmen + + @for (option of COMPANY_STATUS_OPTIONS; track option.value) { + {{ option.label }} + } + + +
diff --git a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.scss b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.scss index bb2547eb..d4c9a253 100644 --- a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.scss +++ b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.scss @@ -98,6 +98,13 @@ border-top: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); } +::ng-deep .company-filter-row { + margin-top: 0.5rem; + padding-top: 0.5rem; + border-top: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); + font-size: 0.8rem; +} + ::ng-deep .timespan-range-label { justify-content: center !important; font-weight: 500; diff --git a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts index 24361675..c325b769 100644 --- a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts @@ -156,6 +156,14 @@ export class KeywordsToPersonsResultsComponent implements OnInit { readonly timespanFrom = signal(this.minYear); readonly timespanTo = signal(this.maxYear); + // which companies to count for the company-foundations metric + readonly COMPANY_STATUS_OPTIONS = [ + { value: 'all', label: 'Alle Unternehmen' }, + { value: 'active', label: 'Nur aktive Unternehmen' }, + { value: 'deleted', label: 'Nur gelöschte Unternehmen' }, + ]; + readonly companyStatus = signal<'all' | 'active' | 'deleted'>('all'); + // publication types readonly ALL_PUBLICATION_TYPES = [ 'article', @@ -225,6 +233,10 @@ export class KeywordsToPersonsResultsComponent implements OnInit { // restore the timespan from the URL so the range is shareable/bookmarkable this.timespanFrom.set(this.readYearParam('tFrom', this.minYear)); this.timespanTo.set(this.readYearParam('tTo', this.maxYear)); + const status = this.route.snapshot.queryParamMap.get('companyStatus'); + if (status === 'active' || status === 'deleted') { + this.companyStatus.set(status); + } } // reads a year query param, clamped to the valid range; falls back on invalid input @@ -266,6 +278,21 @@ export class KeywordsToPersonsResultsComponent implements OnInit { this.loadAuthors(); } + // change the company-status filter — persist to the URL and reload + onCompanyStatusChange(status: 'all' | 'active' | 'deleted'): void { + this.companyStatus.set(status); + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + companyStatus: status === 'all' ? null : status, + page: null, + }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + this.loadAuthors(); + } + // called when a timespan thumb is released — persist to the URL and reload onTimespanChange(): void { if (this.timespanFrom() > this.timespanTo()) { @@ -343,6 +370,7 @@ export class KeywordsToPersonsResultsComponent implements OnInit { from: this.timespanFrom(), to: this.timespanTo(), }, + company_status: this.companyStatus(), }; this.loading.set(true);