From fe2748c5abc3b5800c07695f3670344d637cb212 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 2 Aug 2026 00:56:47 +0000 Subject: [PATCH] =?UTF-8?q?B117=20=E2=80=94=20prefix=20nearest=20munic?= =?UTF-8?q?=C3=ADpio=20in=20global=20search=20suggest=20(geo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - loadHomeSearchSuggestions returns scopeMunicipalities for client merge - useHomeSearchNearestMunicipality prompts once per session (B14 key) - mergeHomeSearchNearestMunicipality prefixes hit without geo copy - HomeSearchMunicipalityGroup wires suggest reorder for Início + drawer Closes #204 Co-authored-by: Francisco Solla --- .../dashboard/HomeSearchMunicipalityGroup.tsx | 42 ++++++++- .../useHomeSearchNearestMunicipality.ts | 82 +++++++++++++++++ src/lib/campaignHomeSearchHits.ts | 11 +++ src/lib/homeSearchNearestMunicipalityMerge.ts | 20 +++++ .../homeSearch/loadHomeSearchSuggestions.ts | 7 ++ tests/int/homeSearchSuggestions.int.spec.ts | 1 + ...earchNearestMunicipalityMerge.unit.spec.ts | 69 +++++++++++++++ tests/unit/homeSearchUi.unit.spec.tsx | 88 +++++++++++-------- 8 files changed, 283 insertions(+), 37 deletions(-) create mode 100644 src/components/campaign/dashboard/useHomeSearchNearestMunicipality.ts create mode 100644 src/lib/homeSearchNearestMunicipalityMerge.ts create mode 100644 tests/unit/homeSearchNearestMunicipalityMerge.unit.spec.ts diff --git a/src/components/campaign/dashboard/HomeSearchMunicipalityGroup.tsx b/src/components/campaign/dashboard/HomeSearchMunicipalityGroup.tsx index 49373bb7..b6c55c69 100644 --- a/src/components/campaign/dashboard/HomeSearchMunicipalityGroup.tsx +++ b/src/components/campaign/dashboard/HomeSearchMunicipalityGroup.tsx @@ -1,27 +1,65 @@ 'use client' +import { useMemo } from 'react' + import { useHomeSearchHitLimit } from '@/components/campaign/dashboard/HomeSearchHitBudgetContext' import { HomeSearchHitRow } from '@/components/campaign/dashboard/HomeSearchHitRow' import { HomeSearchMunicipalityVoteTrailing } from '@/components/campaign/dashboard/HomeSearchMunicipalityVoteTrailing' +import { useHomeSearch } from '@/components/campaign/dashboard/HomeSearchContext' import { useHomeSearchResults } from '@/components/campaign/dashboard/HomeSearchResultsContext' -import { homeSearchMunicipalityGroupHasHits } from '@/lib/campaignHomeSearchHits' +import { useHomeSearchNearestMunicipality } from '@/components/campaign/dashboard/useHomeSearchNearestMunicipality' +import { + homeSearchMunicipalityGroupHasHits, + toHomeSearchMunicipalityHit, + type HomeSearchScopeMunicipality, +} from '@/lib/campaignHomeSearchHits' import { formatElectionNumber } from '@/lib/electionFormat' +import { mergeHomeSearchNearestMunicipality } from '@/lib/homeSearchNearestMunicipalityMerge' import { sliceHomeSearchMunicipalityGroup } from '@/lib/homeSearchHitBudget' import { HOME_SEARCH_GROUP_HEADING_CLASS, HOME_SEARCH_GROUP_LIST_CLASS } from '@/lib/homeSearchUi' +import type { AccessibleMunicipality } from '@/lib/municipalityProximity' import { buildTerritoryPageHref } from '@/lib/territoryAnchor' +const scopeToAccessible = (scope: readonly HomeSearchScopeMunicipality[]): AccessibleMunicipality[] => + scope.map(({ slug, name, ibgeCode }) => ({ slug, name, ibgeCode })) + +const buildHitBySlug = (scope: readonly HomeSearchScopeMunicipality[]) => + new Map(scope.map((doc) => [doc.slug, toHomeSearchMunicipalityHit(doc)])) + export const HomeSearchMunicipalityGroup = () => { + const { query, uiFocused } = useHomeSearch() const { results, resultKind } = useHomeSearchResults() const hitLimit = useHomeSearchHitLimit('municipalities') + const suggestMode = uiFocused && !query.isActive + + const scopeMunicipalities = useMemo( + () => (results.status === 'success' ? results.data.scopeMunicipalities ?? [] : []), + [results], + ) + + const accessible = useMemo(() => scopeToAccessible(scopeMunicipalities), [scopeMunicipalities]) + const hitBySlug = useMemo(() => buildHitBySlug(scopeMunicipalities), [scopeMunicipalities]) + + const nearestSlug = useHomeSearchNearestMunicipality(accessible, suggestMode && scopeMunicipalities.length > 0) + if (results.status !== 'success') return null const { municipalities, territories } = results.data if (!homeSearchMunicipalityGroupHasHits(results.data)) return null + const mergedMunicipalities = + resultKind === 'suggest' + ? mergeHomeSearchNearestMunicipality({ + nearestSlug, + serverHits: municipalities, + hitBySlug, + }) + : municipalities + const includeTerritories = resultKind === 'search' const { municipalities: visibleMunicipalities, territories: visibleTerritories } = - sliceHomeSearchMunicipalityGroup(municipalities, territories, hitLimit, includeTerritories) + sliceHomeSearchMunicipalityGroup(mergedMunicipalities, territories, hitLimit, includeTerritories) if (visibleMunicipalities.length === 0 && visibleTerritories.length === 0) return null diff --git a/src/components/campaign/dashboard/useHomeSearchNearestMunicipality.ts b/src/components/campaign/dashboard/useHomeSearchNearestMunicipality.ts new file mode 100644 index 00000000..cb593827 --- /dev/null +++ b/src/components/campaign/dashboard/useHomeSearchNearestMunicipality.ts @@ -0,0 +1,82 @@ +'use client' + +import { useEffect, useRef, useState } from 'react' + +import { + loadMunicipalityGeometryModule, + loadMunicipalityZoneGeometryModule, +} from '@/lib/bahiaGeometries' +import { resolveNearbyMunicipality, type AccessibleMunicipality } from '@/lib/municipalityProximity' +import { + hasPromptedThisSession, + markPromptedThisSession, + readGeolocationPermissionState, + requestCurrentPosition, +} from '@/utilities/campaignGeolocation' + +/** + * B117 — nearest in-scope município slug for global search suggest. + * Prompts once per tab session (B14 key) on first focus when permission is not denied. + * Fail-soft: every other outcome returns `null` with no error UI. + */ +export const useHomeSearchNearestMunicipality = ( + accessible: readonly AccessibleMunicipality[], + enabled: boolean, +): string | null => { + const [nearestSlug, setNearestSlug] = useState(null) + const autoStartedRef = useRef(false) + + useEffect(() => { + if (!enabled || autoStartedRef.current || accessible.length === 0) return + autoStartedRef.current = true + + let cancelled = false + + const resolveNearest = async () => { + const loaded = await Promise.all([ + requestCurrentPosition(), + loadMunicipalityGeometryModule(), + ]).catch(() => null) + + if (cancelled || !loaded) return + + const [result, geometry] = loaded + if (!result.ok) return + + const zoneModule = await loadMunicipalityZoneGeometryModule().catch(() => null) + + const resolution = resolveNearbyMunicipality({ + point: result.fix, + geometry, + zoneGeometry: zoneModule ?? undefined, + accessible, + }) + + if (cancelled || resolution.kind !== 'inScope') return + + setNearestSlug(resolution.municipality.slug) + } + + const start = async () => { + const permission = await readGeolocationPermissionState() + + if (permission === 'granted') { + void resolveNearest() + return + } + + if (permission !== 'denied' && !hasPromptedThisSession()) { + markPromptedThisSession() + void resolveNearest() + } + } + + void start() + + return () => { + cancelled = true + } + }, [accessible, enabled]) + + return nearestSlug +} diff --git a/src/lib/campaignHomeSearchHits.ts b/src/lib/campaignHomeSearchHits.ts index 511ec9b6..94f92d44 100644 --- a/src/lib/campaignHomeSearchHits.ts +++ b/src/lib/campaignHomeSearchHits.ts @@ -57,6 +57,15 @@ export type HomeSearchDemandHit = { type HomeSearchResultKind = 'search' | 'suggest' +/** Scope rows for client geo merge (B117) — full portfolio, not only top-8 suggest. */ +export type HomeSearchScopeMunicipality = { + slug: string + name: string + region: string + priority: 'alta' | 'normal' | null + ibgeCode: string +} + export type HomeSearchSuccessResponse = { status: 'success' resultKind: HomeSearchResultKind @@ -67,6 +76,8 @@ export type HomeSearchSuccessResponse = { stateDeputies: HomeSearchStateDeputyHit[] activities: HomeSearchActivityHit[] demands: HomeSearchDemandHit[] + /** Present on `suggest` for client nearest-municipality prefix (B117). */ + scopeMunicipalities?: HomeSearchScopeMunicipality[] } export const homeSearchMunicipalityGroupHasHits = ( diff --git a/src/lib/homeSearchNearestMunicipalityMerge.ts b/src/lib/homeSearchNearestMunicipalityMerge.ts new file mode 100644 index 00000000..428016e2 --- /dev/null +++ b/src/lib/homeSearchNearestMunicipalityMerge.ts @@ -0,0 +1,20 @@ +import type { HomeSearchMunicipalityHit } from '@/lib/campaignHomeSearchHits' + +/** + * B117 — prefix the nearest in-scope município on suggest, deduping the server list. + * The hit uses the normal suggest shape — no geo reason or distance metadata. + */ +export const mergeHomeSearchNearestMunicipality = (input: { + nearestSlug: string | null | undefined + serverHits: readonly HomeSearchMunicipalityHit[] + hitBySlug: ReadonlyMap +}): HomeSearchMunicipalityHit[] => { + const slug = input.nearestSlug?.trim() + if (!slug) return [...input.serverHits] + + const nearestHit = input.hitBySlug.get(slug) + if (!nearestHit) return [...input.serverHits] + + const withoutDup = input.serverHits.filter((hit) => hit.slug !== slug) + return [nearestHit, ...withoutDup] +} diff --git a/src/utilities/homeSearch/loadHomeSearchSuggestions.ts b/src/utilities/homeSearch/loadHomeSearchSuggestions.ts index 78eab864..853bf363 100644 --- a/src/utilities/homeSearch/loadHomeSearchSuggestions.ts +++ b/src/utilities/homeSearch/loadHomeSearchSuggestions.ts @@ -78,6 +78,13 @@ export const loadHomeSearchSuggestions = async ( status: 'success', resultKind: 'suggest', municipalities: municipalityHits, + scopeMunicipalities: municipalities.map((doc) => ({ + slug: doc.slug, + name: doc.name, + region: doc.region, + priority: doc.priority ?? null, + ibgeCode: doc.ibgeCode, + })), territories: [], advisors: [], leaderships: [], diff --git a/tests/int/homeSearchSuggestions.int.spec.ts b/tests/int/homeSearchSuggestions.int.spec.ts index 7416d68a..22730cf0 100644 --- a/tests/int/homeSearchSuggestions.int.spec.ts +++ b/tests/int/homeSearchSuggestions.int.spec.ts @@ -44,6 +44,7 @@ describe('loadHomeSearchSuggestions (B68)', () => { const result = await loadHomeSearchSuggestions(payload, advisor) expect(result.municipalities.every((hit) => hit.slug === administered.slug)).toBe(true) + expect(result.scopeMunicipalities?.map((row) => row.slug)).toEqual([administered.slug]) }) it('rejects leaders from home search suggestions', async () => { diff --git a/tests/unit/homeSearchNearestMunicipalityMerge.unit.spec.ts b/tests/unit/homeSearchNearestMunicipalityMerge.unit.spec.ts new file mode 100644 index 00000000..0775c23c --- /dev/null +++ b/tests/unit/homeSearchNearestMunicipalityMerge.unit.spec.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest' + +import type { HomeSearchMunicipalityHit } from '@/lib/campaignHomeSearchHits' +import { mergeHomeSearchNearestMunicipality } from '@/lib/homeSearchNearestMunicipalityMerge' + +const hit = (slug: string, name: string): HomeSearchMunicipalityHit => ({ + kind: 'municipality', + slug, + name, + region: 'TI', + priority: 'normal', + votePosition2022: null, +}) + +describe('mergeHomeSearchNearestMunicipality (B117)', () => { + const serverHits = [hit('b', 'Brumado'), hit('c', 'Cairu')] + const hitBySlug = new Map([ + ['a', hit('a', 'Abaíra')], + ['b', hit('b', 'Brumado')], + ['c', hit('c', 'Cairu')], + ]) + + it('prefixes nearest slug and dedupes from server list', () => { + const merged = mergeHomeSearchNearestMunicipality({ + nearestSlug: 'a', + serverHits, + hitBySlug, + }) + expect(merged.map((row) => row.slug)).toEqual(['a', 'b', 'c']) + }) + + it('keeps server order when nearest is already first on server', () => { + const merged = mergeHomeSearchNearestMunicipality({ + nearestSlug: 'b', + serverHits, + hitBySlug, + }) + expect(merged.map((row) => row.slug)).toEqual(['b', 'c']) + }) + + it('returns server list unchanged when nearest slug is missing', () => { + const merged = mergeHomeSearchNearestMunicipality({ + nearestSlug: 'missing', + serverHits, + hitBySlug, + }) + expect(merged).toEqual(serverHits) + }) + + it('returns server list unchanged when nearest slug is null', () => { + const merged = mergeHomeSearchNearestMunicipality({ + nearestSlug: null, + serverHits, + hitBySlug, + }) + expect(merged).toEqual(serverHits) + }) + + it('does not add geo reason or distance to the prefixed hit', () => { + const merged = mergeHomeSearchNearestMunicipality({ + nearestSlug: 'a', + serverHits, + hitBySlug, + }) + const nearest = merged[0] + expect(nearest.region).toBe('TI') + expect(JSON.stringify(nearest)).not.toMatch(/Perto de você|km/i) + }) +}) diff --git a/tests/unit/homeSearchUi.unit.spec.tsx b/tests/unit/homeSearchUi.unit.spec.tsx index 9b3f41a6..6be6ed17 100644 --- a/tests/unit/homeSearchUi.unit.spec.tsx +++ b/tests/unit/homeSearchUi.unit.spec.tsx @@ -2,6 +2,7 @@ import { cleanup, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it } from 'vitest' import { HomeSearchHitRow } from '@/components/campaign/dashboard/HomeSearchHitRow' +import { HomeSearchProvider } from '@/components/campaign/dashboard/HomeSearchContext' import { HomeSearchMunicipalityGroup } from '@/components/campaign/dashboard/HomeSearchMunicipalityGroup' import { HomeSearchResultsProvider } from '@/components/campaign/dashboard/HomeSearchResultsContext' import type { HomeSearchSuccessResponse } from '@/lib/campaignHomeSearchHits' @@ -10,6 +11,30 @@ import { HOME_SEARCH_GROUP_LIST_CLASS, HOME_SEARCH_HIT_ROW_WRAPPER_CLASS, } from '@/lib/homeSearchUi' +import { stub } from '../helpers/stub' + +const homeSearchController = (uiFocused = false) => + stub({ + query: { raw: '', debounced: '', isActive: false }, + setRaw: () => {}, + clear: () => {}, + isDebouncing: false, + inputFocused: uiFocused, + setInputFocused: () => {}, + uiFocused, + }) + +const renderMunicipalityGroup = ( + resultsValue: ReturnType, + uiFocused = false, +) => + render( + + + + + , + ) const searchResultsValue = ( data: Partial = {}, @@ -56,37 +81,9 @@ describe('HomeSearchHitRow', () => { describe('HomeSearchMunicipalityGroup', () => { it('omits the visible heading in suggest mode while keeping an accessible section name', () => { - render( - - - , - ) - - expect(screen.queryByRole('heading', { name: 'Sugestões' })).toBeNull() - expect(screen.getByRole('region', { name: 'Sugestões' })).toBeTruthy() - expect(screen.getByRole('link', { name: /Cairu/i })).toBeTruthy() - }) - - it('renders a discreet sentence-case heading and list without bullets', () => { - const { container } = render( - { votePosition2022: null, }, ], - })} - > - - , + }, + 'suggest', + ), + true, + ) + + expect(screen.queryByRole('heading', { name: 'Sugestões' })).toBeNull() + expect(screen.getByRole('region', { name: 'Sugestões' })).toBeTruthy() + expect(screen.getByRole('link', { name: /Cairu/i })).toBeTruthy() + }) + + it('renders a discreet sentence-case heading and list without bullets', () => { + const { container } = renderMunicipalityGroup( + searchResultsValue({ + municipalities: [ + { + kind: 'municipality', + slug: 'cairu', + name: 'Cairu', + region: 'Recôncavo', + priority: null, + votePosition2022: null, + }, + ], + }), ) const heading = screen.getByRole('heading', { name: 'Municípios' })