B117 — prefix nearest município in global search suggest (geo)

- 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 <fsolla@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-08-02 00:56:47 +00:00
parent dde938bbb1
commit fe2748c5ab
No known key found for this signature in database
8 changed files with 283 additions and 37 deletions

View file

@ -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

View file

@ -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<string | null>(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
}

View file

@ -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 = (

View file

@ -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<string, HomeSearchMunicipalityHit>
}): 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]
}

View file

@ -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: [],

View file

@ -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 () => {

View file

@ -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)
})
})

View file

@ -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<typeof searchResultsValue>,
uiFocused = false,
) =>
render(
<HomeSearchProvider value={homeSearchController(uiFocused)}>
<HomeSearchResultsProvider value={resultsValue}>
<HomeSearchMunicipalityGroup />
</HomeSearchResultsProvider>
</HomeSearchProvider>,
)
const searchResultsValue = (
data: Partial<HomeSearchSuccessResponse> = {},
@ -56,37 +81,9 @@ describe('HomeSearchHitRow', () => {
describe('HomeSearchMunicipalityGroup', () => {
it('omits the visible heading in suggest mode while keeping an accessible section name', () => {
render(
<HomeSearchResultsProvider
value={searchResultsValue(
{
municipalities: [
{
kind: 'municipality',
slug: 'cairu',
name: 'Cairu',
region: 'Recôncavo',
priority: null,
votePosition2022: null,
},
],
},
'suggest',
)}
>
<HomeSearchMunicipalityGroup />
</HomeSearchResultsProvider>,
)
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(
<HomeSearchResultsProvider
value={searchResultsValue({
renderMunicipalityGroup(
searchResultsValue(
{
municipalities: [
{
kind: 'municipality',
@ -97,10 +94,31 @@ describe('HomeSearchMunicipalityGroup', () => {
votePosition2022: null,
},
],
})}
>
<HomeSearchMunicipalityGroup />
</HomeSearchResultsProvider>,
},
'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' })