teqo-backup/src/components/campaign/municipality/MunicipalityListLeadershipsControl.tsx
Francisco Solla b210939226 refactor(B193): simplify fixes pós-revisão — mapper único de updates, API de trigger uniforme, grupos de relação extraídos, hardening do sheet host
- Extrai toMunicipalityUpdateViewModel/loadUpdateAuthorNames compartilhados
  (feed + batch da lista); remove avatarClassName morto.
- MunicipalityRelationTriggerProps compartilhado nos 3 wrappers; triggerClassName
  no ExpectedVotesControl; ChipLabel/RelationGroup/CityDash no card.
- Sheet host: cleanup de unmount no overlay (sem drawer órfão), registerFooter
  valida open, branch nulo do handleOpenChange limpa footer; chrome freeze
  documentado.
- A11y/UX: ícone de alerta no rodapé frio (WCAG 1.4.1), iniciais de avatar
  aria-hidden, chip sem_base sem target morto, label da cidade com Tendência,
  aria-label da barra anuncia os 3 cenários, card layout 'colocação · votos'.
- E2E: settleStream no B184 (flake da cópia transitória do streaming), cards
  ancorados por hasText (q= casa prefixos), cor da borda via classe do token.
2026-08-10 11:23:49 -03:00

112 lines
4.1 KiB
TypeScript

'use client'
import type { MunicipalityListLeadershipsResponse } from '@/app/(campaign)/campanha/(app)/municipios/leaderships/types'
import { useMunicipalityLeadershipCreate } from '@/components/campaign/municipality/MunicipalityLeadershipCreateProvider'
import type { CampaignCellEditOverlayVariant } from '@/components/campaign/shared/CampaignCellEditOverlay'
import type { MunicipalityRelationEntry } from '@/components/campaign/shared/MunicipalityRelationAvatarStack'
import {
MunicipalityRelationEditor,
type MunicipalityRelationMutationResult,
type MunicipalityRelationTriggerProps,
} from '@/components/campaign/shared/MunicipalityRelationEditor'
import { postCampaignJson } from '@/lib/campaignJsonRequest'
import type {
EligibleLeadershipOption,
MunicipalityLeadershipSummary,
} from '@/utilities/municipality/municipalityViewModels'
const LEADERSHIPS_ENDPOINT = '/campanha/municipios/leaderships'
const SAVE_ERROR_MESSAGE = 'Não foi possível atualizar as lideranças. Tente novamente.'
type MunicipalityListLeadershipsControlProps = MunicipalityRelationTriggerProps & {
municipalityID: number
municipalityName: string
currentLeadershipIDs: number[]
leadershipNamesById: ReadonlyMap<number, MunicipalityLeadershipSummary>
options: EligibleLeadershipOption[]
variant: CampaignCellEditOverlayVariant
}
const entryOf = (option: { id: number; name: string }): MunicipalityRelationEntry => ({
id: option.id,
label: option.name,
})
export const MunicipalityListLeadershipsControl = ({
municipalityID,
municipalityName,
currentLeadershipIDs,
leadershipNamesById,
options,
variant,
trigger,
triggerClassName,
}: MunicipalityListLeadershipsControlProps) => {
const createBridge = useMunicipalityLeadershipCreate()
const createdOptions = createBridge?.createdOptions ?? []
const toggle = async (
leadershipID: number,
assigned: boolean,
): Promise<MunicipalityRelationMutationResult> => {
const { ok, payload } = await postCampaignJson<MunicipalityListLeadershipsResponse>(
LEADERSHIPS_ENDPOINT,
{ municipalityId: municipalityID, leadershipId: leadershipID, assigned },
)
if (!ok || payload.status !== 'success') {
return {
status: 'error',
message: payload.status === 'error' ? payload.message : SAVE_ERROR_MESSAGE,
}
}
return { status: 'success', selectedIDs: payload.leadershipIDs }
}
const create = async (name: string): Promise<MunicipalityRelationMutationResult> => {
const { ok, payload } = await postCampaignJson<MunicipalityListLeadershipsResponse>(
LEADERSHIPS_ENDPOINT,
{ municipalityId: municipalityID, name },
)
if (!ok || payload.status !== 'success' || !payload.createdLeadership) {
return {
status: 'error',
message: payload.status === 'error' ? payload.message : SAVE_ERROR_MESSAGE,
}
}
return {
status: 'success',
selectedIDs: payload.leadershipIDs,
createdEntry: entryOf(payload.createdLeadership),
}
}
return (
<MunicipalityRelationEditor
municipalityName={municipalityName}
currentIDs={currentLeadershipIDs}
knownEntries={[...leadershipNamesById.values()].map(entryOf)}
options={[...options, ...createdOptions].map(entryOf)}
variant={variant}
title="Gerenciar lideranças"
description="A liderança passa a aparecer também na ficha dela, na área Lideranças."
searchPlaceholder="Buscar liderança…"
searchLabel="Buscar liderança"
savingMessage="Salvando lideranças."
saveErrorMessage={SAVE_ERROR_MESSAGE}
triggerLabel={(entries) =>
`Editar lideranças em ${municipalityName} — ${
entries.length ? entries.map((entry) => entry.label).join(', ') : 'nenhuma'
}`
}
emptyState={<span className="text-sm text-muted-foreground">Nenhuma</span>}
trigger={trigger}
triggerClassName={triggerClassName}
createLabel={(name) => `Criar liderança “${name}”`}
onToggle={toggle}
onCreate={create}
onCreated={(entry) =>
createBridge?.registerCreatedLeadership({ id: entry.id, name: entry.label })
}
/>
)
}