Merge pull request #221 from fsolla/cursor/pool-i209-b0d5e6cd-eaa9

B121 — Wizard atualizar liderança — edição rápida (status + votos declarados)
This commit is contained in:
Francisco Solla 2026-08-01 22:26:33 -03:00 committed by GitHub
commit b96b962d73
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 505 additions and 30 deletions

View file

@ -1,17 +1,28 @@
'use server'
import { revalidatePath } from 'next/cache'
import { leadershipStaffEditSafeMessages } from '@/app/(campaign)/campanha/(app)/liderancas/leadershipStaffEditMessages'
import {
createLeadershipWizard,
updateLeadershipWizard,
} from '@/app/(campaign)/campanha/actions/leadership'
import { optionalFormText, requiredFormText, requiredRelationshipFormValue } from '@/lib/formData'
import { declareVotes } from '@/app/(campaign)/campanha/actions/votePledge'
import { WIZARD_LEADERSHIP_VOTES_SAVED } from '@/lib/campaignWizardCopy'
import {
optionalFormText,
requiredFormText,
requiredIntegerFormValue,
requiredRelationshipFormValue,
} from '@/lib/formData'
import {
LEADERSHIP_DUPLICATE_MESSAGE,
LEADERSHIP_INVALID_CONTACT_MESSAGE,
LEADERSHIP_MUNICIPALITY_SCOPE_MESSAGE,
isSupportStatus,
} from '@/lib/schemas/leadership'
import { MAX_VOTE_COUNT } from '@/lib/schemas/primitives'
import { VOTE_PLEDGE_DECLARE_SAFE_MESSAGES } from '@/lib/schemas/votePledge'
import {
runCampaignFormAction,
type CampaignFormActionState,
@ -87,3 +98,25 @@ export const updateLeadershipWizardFormAction = async (
safeMessages,
genericMessage: 'Não foi possível salvar a liderança. Verifique os dados e tente novamente.',
})
export const declareVotesWizardFormAction = async (
_state: CampaignFormActionState,
formData: FormData,
): Promise<CampaignFormActionState> =>
runCampaignFormAction({
execute: async () => {
const municipality = requiredRelationshipFormValue(formData, 'municipalityId')
const leadership = requiredRelationshipFormValue(formData, 'leadershipId')
const declaredVotes = requiredIntegerFormValue(formData, 'declaredVotes', {
minimum: 0,
maximum: MAX_VOTE_COUNT,
})
await declareVotes({ municipality, leadership, declaredVotes })
revalidatePath('/campanha/acoes/atualizar-lideranca', 'page')
return { message: WIZARD_LEADERSHIP_VOTES_SAVED }
},
safeMessages: VOTE_PLEDGE_DECLARE_SAFE_MESSAGES,
genericMessage:
'Não foi possível registrar a declaração. Verifique seu acesso e tente novamente.',
})

View file

@ -1,14 +1,26 @@
'use client'
import { InfoIcon, PlusIcon } from 'lucide-react'
import { CheckIcon, InfoIcon, PlusIcon, TriangleAlertIcon } from 'lucide-react'
import { useRouter } from 'next/navigation'
import { useCallback, useMemo, useState, useTransition } from 'react'
import {
useActionState,
useCallback,
useEffect,
useMemo,
useRef,
useState,
useTransition,
} from 'react'
import { toast } from 'sonner'
import { declareVotesWizardFormAction } from '@/app/(campaign)/campanha/(app)/acoes/wizardLeadershipFormActions'
import type { LeadershipListSupportStatusResponse } from '@/app/(campaign)/campanha/(app)/liderancas/support-status/types'
import { SupportStatusBadge } from '@/components/campaign/leadership/SupportStatusBadge'
import { WizardLeadershipForm } from '@/components/campaign/leadership/WizardLeadershipForm'
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
import { CampaignWizardNavLink } from '@/components/campaign/shared/CampaignWizardNavLink'
import { CampaignWizardShell } from '@/components/campaign/shared/CampaignWizardShell'
import { Alert, AlertDescription } from '@/components/ui/Alert'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/button'
import {
@ -18,21 +30,37 @@ import {
DrawerHeader,
DrawerTitle,
} from '@/components/ui/Drawer'
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { Spinner } from '@/components/ui/Spinner'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import type { CampaignWizardActionId } from '@/lib/campaignActionRoutes'
import { postCampaignJson } from '@/lib/campaignJsonRequest'
import { recordLastActedMunicipality } from '@/lib/campaignLastActedMunicipality'
import {
WIZARD_LEADERSHIP_ADD_TILE_LABEL,
WIZARD_LEADERSHIP_CONTINUE_LABEL,
WIZARD_LEADERSHIP_DECLARE_VOTES_LABEL,
WIZARD_LEADERSHIP_EMPTY_GRID,
WIZARD_LEADERSHIP_EMPTY_NOTES,
WIZARD_LEADERSHIP_FORM_CREATE_TITLE,
WIZARD_LEADERSHIP_FORM_EDIT_TITLE,
WIZARD_LEADERSHIP_GRID_TITLE,
WIZARD_LEADERSHIP_SAVED_TOAST,
WIZARD_LEADERSHIP_STATUS_DRAWER_TITLE,
WIZARD_LEADERSHIP_STATUS_PENDING,
WIZARD_LEADERSHIP_STATUS_SAVE_ERROR,
WIZARD_LEADERSHIP_VOTES_DRAWER_TITLE,
WIZARD_LEADERSHIP_VOTES_PENDING,
WIZARD_LEADERSHIP_VOTES_SAVED,
wizardFlowTitleForSlug,
} from '@/lib/campaignWizardCopy'
import { truncateNameAtWordBoundary } from '@/lib/leadershipNameTruncate'
import {
isSupportStatus,
leadershipSupportStatuses,
type SupportStatus,
} from '@/lib/schemas/leadership'
import { cn } from '@/lib/utils'
import {
resolveWizardChainEntry,
@ -44,6 +72,11 @@ import {
resolveWizardLeadershipSkip,
type WizardLeadershipTileViewModel,
} from '@/lib/wizardLeadershipContract'
import { fieldError } from '@/utilities/campaignFormFields'
import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
const SUPPORT_STATUS_ENDPOINT = '/campanha/liderancas/support-status'
const DEFAULT_STATUS: SupportStatus = 'a_abordar'
type WizardLeadershipStepProps = {
actionSlug: string
@ -66,6 +99,11 @@ const notesLabel = (notes: string | null): string =>
const secondaryContact = (tile: WizardLeadershipTileViewModel): string | null =>
tile.phone?.trim() || tile.email?.trim() || null
const drawerContextLabel = (
tile: WizardLeadershipTileViewModel,
municipalityName: string,
): string => `${tile.name} · ${municipalityName}`
export const WizardLeadershipStep = ({
actionSlug,
municipalityId,
@ -87,7 +125,14 @@ export const WizardLeadershipStep = ({
}, [initialLeadershipId, initialTiles])
const [mode, setMode] = useState<WizardLeadershipMode>(initialMode)
const [dirty, setDirty] = useState(false)
const [tiles, setTiles] = useState(initialTiles)
const [infoTile, setInfoTile] = useState<WizardLeadershipTileViewModel | null>(null)
const [statusTile, setStatusTile] = useState<WizardLeadershipTileViewModel | null>(null)
const [votesTile, setVotesTile] = useState<WizardLeadershipTileViewModel | null>(null)
useEffect(() => {
setTiles(initialTiles)
}, [initialTiles])
const skipConfig = resolveWizardLeadershipSkip(entryAction, municipalitySlug, returnPath)
const chainContinueHref = wizardChainContinueHref(
@ -110,18 +155,44 @@ export const WizardLeadershipStep = ({
</Button>
) : undefined
const handleSaved = useCallback(() => {
const markDirtyAndRefresh = useCallback(() => {
recordLastActedMunicipality(municipalitySlug)
setDirty(true)
setMode({ kind: 'grid' })
router.refresh()
toast.success(WIZARD_LEADERSHIP_SAVED_TOAST)
}, [municipalitySlug, router])
const handlePopFormLayer = useCallback(() => {
setMode({ kind: 'grid' })
}, [])
const handleSaved = useCallback(() => {
markDirtyAndRefresh()
setMode({ kind: 'grid' })
toast.success(WIZARD_LEADERSHIP_SAVED_TOAST)
}, [markDirtyAndRefresh])
const handleStatusSaved = useCallback(
(leadershipId: number, supportStatus: SupportStatus) => {
setTiles((current) =>
current.map((tile) => (tile.id === leadershipId ? { ...tile, supportStatus } : tile)),
)
setStatusTile(null)
markDirtyAndRefresh()
},
[markDirtyAndRefresh],
)
const handleVotesSaved = useCallback(
(leadershipId: number, declaredVotes: number) => {
setTiles((current) =>
current.map((tile) => (tile.id === leadershipId ? { ...tile, declaredVotes } : tile)),
)
setVotesTile(null)
markDirtyAndRefresh()
},
[markDirtyAndRefresh],
)
const handleContinue = () => {
startContinueTransition(() => {
router.replace(chainContinueHref)
@ -157,16 +228,18 @@ export const WizardLeadershipStep = ({
) : (
<TooltipProvider delayDuration={200}>
<div className="flex flex-col gap-4">
{initialTiles.length === 0 ? (
{tiles.length === 0 ? (
<p className="text-sm text-muted-foreground">{WIZARD_LEADERSHIP_EMPTY_GRID}</p>
) : null}
<ul className="grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-4">
{initialTiles.map((tile) => (
{tiles.map((tile) => (
<li key={tile.id}>
<LeadershipTileButton
tile={tile}
onOpen={() => setMode({ kind: 'form', leadership: tile })}
onInfo={() => setInfoTile(tile)}
onStatus={() => setStatusTile(tile)}
onVotes={() => setVotesTile(tile)}
/>
</li>
))}
@ -206,6 +279,21 @@ export const WizardLeadershipStep = ({
</div>
</DrawerContent>
</Drawer>
<WizardLeadershipStatusDrawer
tile={statusTile}
municipalityName={municipalityName}
onClose={() => setStatusTile(null)}
onSaved={handleStatusSaved}
/>
<WizardLeadershipVotesDrawer
tile={votesTile}
municipalityId={municipalityId}
municipalityName={municipalityName}
onClose={() => setVotesTile(null)}
onSaved={handleVotesSaved}
/>
</CampaignWizardShell>
)
}
@ -214,32 +302,96 @@ type LeadershipTileButtonProps = {
tile: WizardLeadershipTileViewModel
onOpen: () => void
onInfo: () => void
onStatus: () => void
onVotes: () => void
}
const LeadershipTileButton = ({ tile, onOpen, onInfo }: LeadershipTileButtonProps) => {
const LeadershipTileButton = ({
tile,
onOpen,
onInfo,
onStatus,
onVotes,
}: LeadershipTileButtonProps) => {
const secondary = secondaryContact(tile)
const noteText = notesLabel(tile.notes)
const status = tile.supportStatus ?? DEFAULT_STATUS
const showDeclareVotesWarning = tile.declaredVotes === 0
return (
<div className="relative aspect-square w-full">
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
<div
className={cn(
'flex h-full w-full flex-col rounded-xl border border-border bg-transparent p-3 pr-11 text-left transition-colors',
'hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
'flex h-full w-full flex-col rounded-xl border border-border bg-transparent transition-colors',
'pointer-coarse:hover:bg-transparent',
)}
onClick={onOpen}
>
<div className="max-w-full">
{tile.supportStatus ? <SupportStatusBadge status={tile.supportStatus} /> : null}
<div className="flex items-start justify-between gap-2 p-3 pb-0">
<button
type="button"
className="shrink-0 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={(event) => {
event.stopPropagation()
onStatus()
}}
aria-label={`Editar status de apoio — ${supportStatusLabels[status]}`}
>
<SupportStatusBadge status={status} />
</button>
<button
type="button"
className="inline-flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={(event) => {
event.stopPropagation()
onInfo()
}}
aria-label={`Ver observação de ${tile.name}`}
>
<InfoIcon className="size-4" aria-hidden />
</button>
</div>
<div className="mt-auto flex flex-col gap-1">
<button
type="button"
className="flex flex-1 flex-col px-3 pt-2 text-left hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={onOpen}
>
<p className="text-sm font-medium leading-snug text-foreground">
{truncateNameAtWordBoundary(tile.name, 28)}
</p>
</button>
<div className="px-3">
<button
type="button"
className="min-h-8 rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={(event) => {
event.stopPropagation()
onVotes()
}}
aria-label={
showDeclareVotesWarning
? `Declarar votos de ${tile.name}`
: `${tile.declaredVotes} votos declarados de ${tile.name}`
}
>
{showDeclareVotesWarning ? (
<Badge variant="estimate-pending" className="gap-1">
<TriangleAlertIcon aria-hidden />
{WIZARD_LEADERSHIP_DECLARE_VOTES_LABEL}
</Badge>
) : (
<span className="text-sm font-medium tabular-nums text-foreground">
{tile.declaredVotes}
</span>
)}
</button>
</div>
<button
type="button"
className="mt-auto flex flex-col gap-1 px-3 pb-3 text-left hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={onOpen}
>
{secondary ? (
<p className="truncate text-xs text-muted-foreground">{secondary}</p>
) : null}
@ -248,21 +400,218 @@ const LeadershipTileButton = ({ tile, onOpen, onInfo }: LeadershipTileButtonProp
Não exclusivo
</Badge>
) : null}
</div>
</button>
</button>
</div>
</TooltipTrigger>
<TooltipContent className="pointer-coarse:hidden max-w-xs whitespace-pre-wrap">
{noteText}
</TooltipContent>
</Tooltip>
<button
type="button"
className="absolute top-3 right-3 inline-flex size-8 items-center justify-center rounded-md text-muted-foreground hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={onInfo}
aria-label={`Ver observação de ${tile.name}`}
>
<InfoIcon className="size-4" aria-hidden />
</button>
</div>
)
}
type WizardLeadershipStatusDrawerProps = {
tile: WizardLeadershipTileViewModel | null
municipalityName: string
onClose: () => void
onSaved: (leadershipId: number, supportStatus: SupportStatus) => void
}
const WizardLeadershipStatusDrawer = ({
tile,
municipalityName,
onClose,
onSaved,
}: WizardLeadershipStatusDrawerProps) => {
const [pendingStatus, setPendingStatus] = useState<SupportStatus | null>(null)
const [errorMessage, setErrorMessage] = useState<string | null>(null)
useEffect(() => {
if (tile === null) {
setPendingStatus(null)
setErrorMessage(null)
}
}, [tile])
const currentStatus = tile?.supportStatus ?? DEFAULT_STATUS
const handleSelect = async (nextStatus: SupportStatus) => {
if (tile === null || nextStatus === currentStatus || pendingStatus !== null) return
setPendingStatus(nextStatus)
setErrorMessage(null)
const { ok, payload } = await postCampaignJson<LeadershipListSupportStatusResponse>(
SUPPORT_STATUS_ENDPOINT,
{ leadershipId: tile.id, supportStatus: nextStatus },
)
if (!ok || payload.status !== 'success') {
setPendingStatus(null)
setErrorMessage(
payload.status === 'error' ? payload.message : WIZARD_LEADERSHIP_STATUS_SAVE_ERROR,
)
return
}
if (!isSupportStatus(payload.savedSupportStatus)) {
setPendingStatus(null)
setErrorMessage(WIZARD_LEADERSHIP_STATUS_SAVE_ERROR)
return
}
onSaved(tile.id, payload.savedSupportStatus)
setPendingStatus(null)
}
const statusMessage = errorMessage
? errorMessage
: pendingStatus !== null
? WIZARD_LEADERSHIP_STATUS_PENDING
: ''
return (
<Drawer open={tile !== null} onOpenChange={(open) => !open && onClose()}>
<DrawerContent>
<DrawerHeader>
<DrawerTitle>{WIZARD_LEADERSHIP_STATUS_DRAWER_TITLE}</DrawerTitle>
<DrawerDescription>
{tile ? drawerContextLabel(tile, municipalityName) : null}
</DrawerDescription>
</DrawerHeader>
<div className="flex flex-col gap-2 px-4 pb-6" aria-busy={pendingStatus !== null}>
<p className="sr-only" aria-live="polite">
{statusMessage}
</p>
<ul className="flex list-none flex-col gap-1">
{leadershipSupportStatuses.map((option) => {
const isCurrent = option === currentStatus
const isPending = pendingStatus === option
return (
<li key={option}>
<button
type="button"
className={cn(
'flex min-h-11 w-full items-center justify-between rounded-lg px-3 text-left text-sm transition-colors',
'hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
isCurrent && 'bg-muted/60 font-medium',
)}
disabled={pendingStatus !== null}
onClick={() => void handleSelect(option)}
aria-current={isCurrent ? 'true' : undefined}
>
<span>{supportStatusLabels[option]}</span>
{isPending ? (
<Spinner className="size-4 text-muted-foreground" aria-hidden />
) : isCurrent ? (
<CheckIcon className="size-4 text-muted-foreground" aria-hidden />
) : null}
</button>
</li>
)
})}
</ul>
{errorMessage ? (
<Alert variant="destructive" className="py-2">
<AlertDescription className="text-xs">{errorMessage}</AlertDescription>
</Alert>
) : null}
</div>
</DrawerContent>
</Drawer>
)
}
type WizardLeadershipVotesDrawerProps = {
tile: WizardLeadershipTileViewModel | null
municipalityId: number
municipalityName: string
onClose: () => void
onSaved: (leadershipId: number, declaredVotes: number) => void
}
const WizardLeadershipVotesDrawer = ({
tile,
municipalityId,
municipalityName,
onClose,
onSaved,
}: WizardLeadershipVotesDrawerProps) => {
const [state, submitAction, isPending] = useActionState(declareVotesWizardFormAction, {})
const [inputValue, setInputValue] = useState('')
const handledMessageRef = useRef<string | undefined>(undefined)
useEffect(() => {
if (tile !== null) {
setInputValue(tile.declaredVotes > 0 ? String(tile.declaredVotes) : '')
handledMessageRef.current = undefined
}
}, [tile])
useEffect(() => {
if (
tile === null ||
!state.message ||
state.message === handledMessageRef.current ||
state.fieldErrors
) {
return
}
if (state.message === WIZARD_LEADERSHIP_VOTES_SAVED) {
handledMessageRef.current = state.message
const parsed = Number.parseInt(inputValue, 10)
if (!Number.isNaN(parsed)) {
onSaved(tile.id, parsed)
}
}
}, [inputValue, onSaved, state.fieldErrors, state.message, tile])
return (
<Drawer open={tile !== null} onOpenChange={(open) => !open && onClose()}>
<DrawerContent>
<DrawerHeader>
<DrawerTitle>{WIZARD_LEADERSHIP_VOTES_DRAWER_TITLE}</DrawerTitle>
<DrawerDescription>
{tile ? drawerContextLabel(tile, municipalityName) : null}
</DrawerDescription>
</DrawerHeader>
<form action={submitAction} className="flex flex-col gap-3 px-4 pb-6" aria-busy={isPending}>
<input type="hidden" name="municipalityId" value={municipalityId} />
{tile !== null ? <input type="hidden" name="leadershipId" value={tile.id} /> : null}
<p className="sr-only" aria-live="polite">
{isPending ? WIZARD_LEADERSHIP_VOTES_PENDING : (state.message ?? '')}
</p>
<Field>
<FieldLabel htmlFor="wizard-leadership-declared-votes">Votos declarados</FieldLabel>
<Input
id="wizard-leadership-declared-votes"
name="declaredVotes"
type="number"
min={0}
max={1000000}
required
inputMode="numeric"
value={inputValue}
onChange={(event) => setInputValue(event.target.value)}
className="min-h-11"
disabled={isPending}
/>
{fieldError(state.fieldErrors, 'declaredVotes') ? (
<FieldError>{fieldError(state.fieldErrors, 'declaredVotes')}</FieldError>
) : null}
</Field>
<Button type="submit" className="min-h-11" disabled={isPending}>
{isPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
Salvar
</Button>
<CampaignFormActionMessage
state={state}
successFallbackMessage={WIZARD_LEADERSHIP_VOTES_SAVED}
/>
</form>
</DrawerContent>
</Drawer>
)
}

View file

@ -91,3 +91,18 @@ export const WIZARD_LEADERSHIP_EMPTY_GRID =
'Nenhuma liderança cadastrada neste município ainda.' as const
export const WIZARD_LEADERSHIP_SAVED_TOAST = 'Liderança salva.' as const
export const WIZARD_LEADERSHIP_STATUS_DRAWER_TITLE = 'Status de apoio' as const
export const WIZARD_LEADERSHIP_VOTES_DRAWER_TITLE = 'Votos declarados' as const
export const WIZARD_LEADERSHIP_DECLARE_VOTES_LABEL = 'Declarar votos' as const
export const WIZARD_LEADERSHIP_STATUS_SAVE_ERROR =
'Não foi possível salvar o status. Tente novamente.' as const
export const WIZARD_LEADERSHIP_STATUS_PENDING = 'Salvando status de apoio.' as const
export const WIZARD_LEADERSHIP_VOTES_PENDING = 'Salvando declaração de votos.' as const
export const WIZARD_LEADERSHIP_VOTES_SAVED = 'Declaração registrada.' as const

View file

@ -12,6 +12,21 @@ export type WizardLeadershipTileViewModel = {
supportStatus: SupportStatus | null
exclusive: boolean
notes: string | null
/** Declared votes for leadership × wizard municipality; 0 when no pledge. */
declaredVotes: number
}
/** Maps pledge rows to leadership id → declaredVotes (absent leadership → omitted). */
export const declaredVotesByLeadershipFromPledges = (
pledges: ReadonlyArray<{ leadership: number | { id: number }; declaredVotes?: number | null }>,
): Map<number, number> => {
const map = new Map<number, number>()
for (const pledge of pledges) {
const leadershipId =
typeof pledge.leadership === 'number' ? pledge.leadership : pledge.leadership.id
map.set(leadershipId, pledge.declaredVotes ?? 0)
}
return map
}
export type WizardLeadershipSkipAction = {

View file

@ -5,7 +5,10 @@ import type { Payload } from 'payload'
import { relationshipId } from '@/lib/relationship'
import type { SupportStatus } from '@/lib/schemas/leadership'
import { isSupportStatus } from '@/lib/schemas/leadership'
import type { WizardLeadershipTileViewModel } from '@/lib/wizardLeadershipContract'
import {
declaredVotesByLeadershipFromPledges,
type WizardLeadershipTileViewModel,
} from '@/lib/wizardLeadershipContract'
import type { CampaignUser, Leadership } from '@/payload-types'
import { isCampaignStaff } from '@/utilities/campaignAccess'
import {
@ -73,7 +76,10 @@ const findMunicipalityLeadershipDocs = async (
return result.docs as Leadership[]
}
const toWizardLeadershipTile = (doc: Leadership): WizardLeadershipTileViewModel => {
const toWizardLeadershipTile = (
doc: Leadership,
declaredVotes: number,
): WizardLeadershipTileViewModel => {
const contact = contactSummary(doc.contact)
return {
id: doc.id,
@ -83,6 +89,7 @@ const toWizardLeadershipTile = (doc: Leadership): WizardLeadershipTileViewModel
supportStatus: isSupportStatus(doc.supportStatus) ? doc.supportStatus : null,
exclusive: doc.exclusive ?? true,
notes: doc.notes ?? null,
declaredVotes,
}
}
@ -155,8 +162,33 @@ export const loadWizardLeadershipTiles = async (
municipalityID: number,
): Promise<WizardLeadershipTileViewModel[]> => {
const docs = await findMunicipalityLeadershipDocs(payload, user, municipalityID)
const leadershipIDs = docs.map((doc) => doc.id)
const declaredVotesByLeadership =
leadershipIDs.length === 0
? new Map<number, number>()
: declaredVotesByLeadershipFromPledges(
(
await payload.find({
collection: 'votePledge',
where: {
and: [
{ municipality: { equals: municipalityID } },
{ leadership: { in: leadershipIDs } },
],
},
depth: 0,
limit: 0,
pagination: false,
select: { leadership: true, declaredVotes: true },
user,
overrideAccess: false,
})
).docs,
)
return docs
.map(toWizardLeadershipTile)
.map((doc) => toWizardLeadershipTile(doc, declaredVotesByLeadership.get(doc.id) ?? 0))
.sort((left, right) => left.name.localeCompare(right.name, 'pt-BR'))
}

View file

@ -0,0 +1,31 @@
import { describe, expect, it } from 'vitest'
import { declaredVotesByLeadershipFromPledges } from '@/lib/wizardLeadershipContract'
describe('declaredVotesByLeadershipFromPledges', () => {
it('maps leadership id to declared votes', () => {
const map = declaredVotesByLeadershipFromPledges([
{ leadership: 7, declaredVotes: 120 },
{ leadership: { id: 9 }, declaredVotes: 45 },
])
expect(map.get(7)).toBe(120)
expect(map.get(9)).toBe(45)
expect(map.get(99)).toBeUndefined()
})
it('treats null declaredVotes as zero', () => {
const map = declaredVotesByLeadershipFromPledges([{ leadership: 3, declaredVotes: null }])
expect(map.get(3)).toBe(0)
})
it('last pledge wins when duplicate leadership ids appear', () => {
const map = declaredVotesByLeadershipFromPledges([
{ leadership: 5, declaredVotes: 10 },
{ leadership: 5, declaredVotes: 20 },
])
expect(map.get(5)).toBe(20)
})
})