mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
B121 — wizard liderança: edição rápida status + votos declarados
- Estende WizardLeadershipTileViewModel com declaredVotes - Batch load de votePledge no loadWizardLeadershipTiles - Drawers de status (auto-save) e votos (Salvar) no grid B70 - declareVotesWizardFormAction com revalidate do wizard - Unit tests do mapeamento pledge→tile Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
parent
50bd6f0764
commit
c845550cdb
6 changed files with 498 additions and 30 deletions
|
|
@ -1,11 +1,22 @@
|
||||||
'use server'
|
'use server'
|
||||||
|
|
||||||
|
import { revalidatePath } from 'next/cache'
|
||||||
|
|
||||||
import { leadershipStaffEditSafeMessages } from '@/app/(campaign)/campanha/(app)/liderancas/leadershipStaffEditMessages'
|
import { leadershipStaffEditSafeMessages } from '@/app/(campaign)/campanha/(app)/liderancas/leadershipStaffEditMessages'
|
||||||
import {
|
import {
|
||||||
createLeadershipWizard,
|
createLeadershipWizard,
|
||||||
updateLeadershipWizard,
|
updateLeadershipWizard,
|
||||||
} from '@/app/(campaign)/campanha/actions/leadership'
|
} from '@/app/(campaign)/campanha/actions/leadership'
|
||||||
import { optionalFormText, requiredFormText, requiredRelationshipFormValue } from '@/lib/formData'
|
import { declareVotes } from '@/app/(campaign)/campanha/actions/votePledge'
|
||||||
|
import {
|
||||||
|
optionalFormText,
|
||||||
|
requiredFormText,
|
||||||
|
requiredIntegerFormValue,
|
||||||
|
requiredRelationshipFormValue,
|
||||||
|
} from '@/lib/formData'
|
||||||
|
import { MAX_VOTE_COUNT } from '@/lib/schemas/primitives'
|
||||||
|
import { WIZARD_LEADERSHIP_VOTES_SAVED } from '@/lib/campaignWizardCopy'
|
||||||
|
import { VOTE_PLEDGE_DECLARE_SAFE_MESSAGES } from '@/lib/schemas/votePledge'
|
||||||
import {
|
import {
|
||||||
LEADERSHIP_DUPLICATE_MESSAGE,
|
LEADERSHIP_DUPLICATE_MESSAGE,
|
||||||
LEADERSHIP_INVALID_CONTACT_MESSAGE,
|
LEADERSHIP_INVALID_CONTACT_MESSAGE,
|
||||||
|
|
@ -87,3 +98,25 @@ export const updateLeadershipWizardFormAction = async (
|
||||||
safeMessages,
|
safeMessages,
|
||||||
genericMessage: 'Não foi possível salvar a liderança. Verifique os dados e tente novamente.',
|
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.',
|
||||||
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,18 @@
|
||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { InfoIcon, PlusIcon } from 'lucide-react'
|
import { CheckIcon, InfoIcon, PlusIcon, TriangleAlertIcon } from 'lucide-react'
|
||||||
import { useRouter } from 'next/navigation'
|
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 { toast } from 'sonner'
|
||||||
|
|
||||||
|
import type { LeadershipListSupportStatusResponse } from '@/app/(campaign)/campanha/(app)/liderancas/support-status/types'
|
||||||
|
import { declareVotesWizardFormAction } from '@/app/(campaign)/campanha/(app)/acoes/wizardLeadershipFormActions'
|
||||||
import { SupportStatusBadge } from '@/components/campaign/leadership/SupportStatusBadge'
|
import { SupportStatusBadge } from '@/components/campaign/leadership/SupportStatusBadge'
|
||||||
import { WizardLeadershipForm } from '@/components/campaign/leadership/WizardLeadershipForm'
|
import { WizardLeadershipForm } from '@/components/campaign/leadership/WizardLeadershipForm'
|
||||||
|
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
||||||
import { CampaignWizardNavLink } from '@/components/campaign/shared/CampaignWizardNavLink'
|
import { CampaignWizardNavLink } from '@/components/campaign/shared/CampaignWizardNavLink'
|
||||||
import { CampaignWizardShell } from '@/components/campaign/shared/CampaignWizardShell'
|
import { CampaignWizardShell } from '@/components/campaign/shared/CampaignWizardShell'
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
||||||
import { Badge } from '@/components/ui/Badge'
|
import { Badge } from '@/components/ui/Badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import {
|
import {
|
||||||
|
|
@ -18,22 +22,40 @@ import {
|
||||||
DrawerHeader,
|
DrawerHeader,
|
||||||
DrawerTitle,
|
DrawerTitle,
|
||||||
} from '@/components/ui/Drawer'
|
} 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 { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||||
import type { CampaignWizardActionId } from '@/lib/campaignActionRoutes'
|
import type { CampaignWizardActionId } from '@/lib/campaignActionRoutes'
|
||||||
|
import { postCampaignJson } from '@/lib/campaignJsonRequest'
|
||||||
import { recordLastActedMunicipality } from '@/lib/campaignLastActedMunicipality'
|
import { recordLastActedMunicipality } from '@/lib/campaignLastActedMunicipality'
|
||||||
import {
|
import {
|
||||||
WIZARD_LEADERSHIP_ADD_TILE_LABEL,
|
WIZARD_LEADERSHIP_ADD_TILE_LABEL,
|
||||||
WIZARD_LEADERSHIP_CONTINUE_LABEL,
|
WIZARD_LEADERSHIP_CONTINUE_LABEL,
|
||||||
|
WIZARD_LEADERSHIP_DECLARE_VOTES_LABEL,
|
||||||
WIZARD_LEADERSHIP_EMPTY_GRID,
|
WIZARD_LEADERSHIP_EMPTY_GRID,
|
||||||
WIZARD_LEADERSHIP_EMPTY_NOTES,
|
WIZARD_LEADERSHIP_EMPTY_NOTES,
|
||||||
WIZARD_LEADERSHIP_FORM_CREATE_TITLE,
|
WIZARD_LEADERSHIP_FORM_CREATE_TITLE,
|
||||||
WIZARD_LEADERSHIP_FORM_EDIT_TITLE,
|
WIZARD_LEADERSHIP_FORM_EDIT_TITLE,
|
||||||
WIZARD_LEADERSHIP_GRID_TITLE,
|
WIZARD_LEADERSHIP_GRID_TITLE,
|
||||||
WIZARD_LEADERSHIP_SAVED_TOAST,
|
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,
|
wizardFlowTitleForSlug,
|
||||||
} from '@/lib/campaignWizardCopy'
|
} from '@/lib/campaignWizardCopy'
|
||||||
import { truncateNameAtWordBoundary } from '@/lib/leadershipNameTruncate'
|
import { truncateNameAtWordBoundary } from '@/lib/leadershipNameTruncate'
|
||||||
|
import {
|
||||||
|
isSupportStatus,
|
||||||
|
leadershipSupportStatuses,
|
||||||
|
type SupportStatus,
|
||||||
|
} from '@/lib/schemas/leadership'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
|
import { fieldError } from '@/utilities/campaignFormFields'
|
||||||
|
import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
|
||||||
import {
|
import {
|
||||||
resolveWizardChainEntry,
|
resolveWizardChainEntry,
|
||||||
wizardChainContinueHref,
|
wizardChainContinueHref,
|
||||||
|
|
@ -45,6 +67,9 @@ import {
|
||||||
type WizardLeadershipTileViewModel,
|
type WizardLeadershipTileViewModel,
|
||||||
} from '@/lib/wizardLeadershipContract'
|
} from '@/lib/wizardLeadershipContract'
|
||||||
|
|
||||||
|
const SUPPORT_STATUS_ENDPOINT = '/campanha/liderancas/support-status'
|
||||||
|
const DEFAULT_STATUS: SupportStatus = 'a_abordar'
|
||||||
|
|
||||||
type WizardLeadershipStepProps = {
|
type WizardLeadershipStepProps = {
|
||||||
actionSlug: string
|
actionSlug: string
|
||||||
municipalityId: number
|
municipalityId: number
|
||||||
|
|
@ -66,6 +91,9 @@ const notesLabel = (notes: string | null): string =>
|
||||||
const secondaryContact = (tile: WizardLeadershipTileViewModel): string | null =>
|
const secondaryContact = (tile: WizardLeadershipTileViewModel): string | null =>
|
||||||
tile.phone?.trim() || tile.email?.trim() || null
|
tile.phone?.trim() || tile.email?.trim() || null
|
||||||
|
|
||||||
|
const drawerContextLabel = (tile: WizardLeadershipTileViewModel, municipalityName: string): string =>
|
||||||
|
`${tile.name} · ${municipalityName}`
|
||||||
|
|
||||||
export const WizardLeadershipStep = ({
|
export const WizardLeadershipStep = ({
|
||||||
actionSlug,
|
actionSlug,
|
||||||
municipalityId,
|
municipalityId,
|
||||||
|
|
@ -87,7 +115,14 @@ export const WizardLeadershipStep = ({
|
||||||
}, [initialLeadershipId, initialTiles])
|
}, [initialLeadershipId, initialTiles])
|
||||||
const [mode, setMode] = useState<WizardLeadershipMode>(initialMode)
|
const [mode, setMode] = useState<WizardLeadershipMode>(initialMode)
|
||||||
const [dirty, setDirty] = useState(false)
|
const [dirty, setDirty] = useState(false)
|
||||||
|
const [tiles, setTiles] = useState(initialTiles)
|
||||||
const [infoTile, setInfoTile] = useState<WizardLeadershipTileViewModel | null>(null)
|
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 skipConfig = resolveWizardLeadershipSkip(entryAction, municipalitySlug, returnPath)
|
||||||
const chainContinueHref = wizardChainContinueHref(
|
const chainContinueHref = wizardChainContinueHref(
|
||||||
|
|
@ -110,18 +145,44 @@ export const WizardLeadershipStep = ({
|
||||||
</Button>
|
</Button>
|
||||||
) : undefined
|
) : undefined
|
||||||
|
|
||||||
const handleSaved = useCallback(() => {
|
const markDirtyAndRefresh = useCallback(() => {
|
||||||
recordLastActedMunicipality(municipalitySlug)
|
recordLastActedMunicipality(municipalitySlug)
|
||||||
setDirty(true)
|
setDirty(true)
|
||||||
setMode({ kind: 'grid' })
|
|
||||||
router.refresh()
|
router.refresh()
|
||||||
toast.success(WIZARD_LEADERSHIP_SAVED_TOAST)
|
|
||||||
}, [municipalitySlug, router])
|
}, [municipalitySlug, router])
|
||||||
|
|
||||||
const handlePopFormLayer = useCallback(() => {
|
const handlePopFormLayer = useCallback(() => {
|
||||||
setMode({ kind: 'grid' })
|
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 = () => {
|
const handleContinue = () => {
|
||||||
startContinueTransition(() => {
|
startContinueTransition(() => {
|
||||||
router.replace(chainContinueHref)
|
router.replace(chainContinueHref)
|
||||||
|
|
@ -157,16 +218,18 @@ export const WizardLeadershipStep = ({
|
||||||
) : (
|
) : (
|
||||||
<TooltipProvider delayDuration={200}>
|
<TooltipProvider delayDuration={200}>
|
||||||
<div className="flex flex-col gap-4">
|
<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>
|
<p className="text-sm text-muted-foreground">{WIZARD_LEADERSHIP_EMPTY_GRID}</p>
|
||||||
) : null}
|
) : null}
|
||||||
<ul className="grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-4">
|
<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}>
|
<li key={tile.id}>
|
||||||
<LeadershipTileButton
|
<LeadershipTileButton
|
||||||
tile={tile}
|
tile={tile}
|
||||||
onOpen={() => setMode({ kind: 'form', leadership: tile })}
|
onOpen={() => setMode({ kind: 'form', leadership: tile })}
|
||||||
onInfo={() => setInfoTile(tile)}
|
onInfo={() => setInfoTile(tile)}
|
||||||
|
onStatus={() => setStatusTile(tile)}
|
||||||
|
onVotes={() => setVotesTile(tile)}
|
||||||
/>
|
/>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|
@ -206,6 +269,21 @@ export const WizardLeadershipStep = ({
|
||||||
</div>
|
</div>
|
||||||
</DrawerContent>
|
</DrawerContent>
|
||||||
</Drawer>
|
</Drawer>
|
||||||
|
|
||||||
|
<WizardLeadershipStatusDrawer
|
||||||
|
tile={statusTile}
|
||||||
|
municipalityName={municipalityName}
|
||||||
|
onClose={() => setStatusTile(null)}
|
||||||
|
onSaved={handleStatusSaved}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<WizardLeadershipVotesDrawer
|
||||||
|
tile={votesTile}
|
||||||
|
municipalityId={municipalityId}
|
||||||
|
municipalityName={municipalityName}
|
||||||
|
onClose={() => setVotesTile(null)}
|
||||||
|
onSaved={handleVotesSaved}
|
||||||
|
/>
|
||||||
</CampaignWizardShell>
|
</CampaignWizardShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -214,32 +292,96 @@ type LeadershipTileButtonProps = {
|
||||||
tile: WizardLeadershipTileViewModel
|
tile: WizardLeadershipTileViewModel
|
||||||
onOpen: () => void
|
onOpen: () => void
|
||||||
onInfo: () => 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 secondary = secondaryContact(tile)
|
||||||
const noteText = notesLabel(tile.notes)
|
const noteText = notesLabel(tile.notes)
|
||||||
|
const status = tile.supportStatus ?? DEFAULT_STATUS
|
||||||
|
const showDeclareVotesWarning = tile.declaredVotes === 0
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative aspect-square w-full">
|
<div className="relative aspect-square w-full">
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<button
|
<div
|
||||||
type="button"
|
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex h-full w-full flex-col rounded-xl border border-border bg-transparent p-3 pr-11 text-left transition-colors',
|
'flex h-full w-full flex-col rounded-xl border border-border bg-transparent transition-colors',
|
||||||
'hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
|
||||||
'pointer-coarse:hover:bg-transparent',
|
'pointer-coarse:hover:bg-transparent',
|
||||||
)}
|
)}
|
||||||
onClick={onOpen}
|
|
||||||
>
|
>
|
||||||
<div className="max-w-full">
|
<div className="flex items-start justify-between gap-2 p-3 pb-0">
|
||||||
{tile.supportStatus ? <SupportStatusBadge status={tile.supportStatus} /> : null}
|
<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>
|
||||||
<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">
|
<p className="text-sm font-medium leading-snug text-foreground">
|
||||||
{truncateNameAtWordBoundary(tile.name, 28)}
|
{truncateNameAtWordBoundary(tile.name, 28)}
|
||||||
</p>
|
</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 ? (
|
{secondary ? (
|
||||||
<p className="truncate text-xs text-muted-foreground">{secondary}</p>
|
<p className="truncate text-xs text-muted-foreground">{secondary}</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
@ -248,21 +390,218 @@ const LeadershipTileButton = ({ tile, onOpen, onInfo }: LeadershipTileButtonProp
|
||||||
Não exclusivo
|
Não exclusivo
|
||||||
</Badge>
|
</Badge>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</button>
|
||||||
</button>
|
</div>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent className="pointer-coarse:hidden max-w-xs whitespace-pre-wrap">
|
<TooltipContent className="pointer-coarse:hidden max-w-xs whitespace-pre-wrap">
|
||||||
{noteText}
|
{noteText}
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</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>
|
</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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -91,3 +91,21 @@ export const WIZARD_LEADERSHIP_EMPTY_GRID =
|
||||||
'Nenhuma liderança cadastrada neste município ainda.' as const
|
'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_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_VOTES_SAVE_ERROR =
|
||||||
|
'Não foi possível registrar a declaração. Verifique seu acesso e 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
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,21 @@ export type WizardLeadershipTileViewModel = {
|
||||||
supportStatus: SupportStatus | null
|
supportStatus: SupportStatus | null
|
||||||
exclusive: boolean
|
exclusive: boolean
|
||||||
notes: string | null
|
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 = {
|
export type WizardLeadershipSkipAction = {
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,10 @@ import type { Payload } from 'payload'
|
||||||
import { relationshipId } from '@/lib/relationship'
|
import { relationshipId } from '@/lib/relationship'
|
||||||
import type { SupportStatus } from '@/lib/schemas/leadership'
|
import type { SupportStatus } from '@/lib/schemas/leadership'
|
||||||
import { isSupportStatus } 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 type { CampaignUser, Leadership } from '@/payload-types'
|
||||||
import { isCampaignStaff } from '@/utilities/campaignAccess'
|
import { isCampaignStaff } from '@/utilities/campaignAccess'
|
||||||
import {
|
import {
|
||||||
|
|
@ -73,7 +76,10 @@ const findMunicipalityLeadershipDocs = async (
|
||||||
return result.docs as Leadership[]
|
return result.docs as Leadership[]
|
||||||
}
|
}
|
||||||
|
|
||||||
const toWizardLeadershipTile = (doc: Leadership): WizardLeadershipTileViewModel => {
|
const toWizardLeadershipTile = (
|
||||||
|
doc: Leadership,
|
||||||
|
declaredVotes: number,
|
||||||
|
): WizardLeadershipTileViewModel => {
|
||||||
const contact = contactSummary(doc.contact)
|
const contact = contactSummary(doc.contact)
|
||||||
return {
|
return {
|
||||||
id: doc.id,
|
id: doc.id,
|
||||||
|
|
@ -83,6 +89,7 @@ const toWizardLeadershipTile = (doc: Leadership): WizardLeadershipTileViewModel
|
||||||
supportStatus: isSupportStatus(doc.supportStatus) ? doc.supportStatus : null,
|
supportStatus: isSupportStatus(doc.supportStatus) ? doc.supportStatus : null,
|
||||||
exclusive: doc.exclusive ?? true,
|
exclusive: doc.exclusive ?? true,
|
||||||
notes: doc.notes ?? null,
|
notes: doc.notes ?? null,
|
||||||
|
declaredVotes,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -155,8 +162,33 @@ export const loadWizardLeadershipTiles = async (
|
||||||
municipalityID: number,
|
municipalityID: number,
|
||||||
): Promise<WizardLeadershipTileViewModel[]> => {
|
): Promise<WizardLeadershipTileViewModel[]> => {
|
||||||
const docs = await findMunicipalityLeadershipDocs(payload, user, municipalityID)
|
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
|
return docs
|
||||||
.map(toWizardLeadershipTile)
|
.map((doc) => toWizardLeadershipTile(doc, declaredVotesByLeadership.get(doc.id) ?? 0))
|
||||||
.sort((left, right) => left.name.localeCompare(right.name, 'pt-BR'))
|
.sort((left, right) => left.name.localeCompare(right.name, 'pt-BR'))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
31
tests/unit/wizardLeadershipDeclaredVotes.unit.spec.ts
Normal file
31
tests/unit/wizardLeadershipDeclaredVotes.unit.spec.ts
Normal 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)
|
||||||
|
})
|
||||||
|
})
|
||||||
Loading…
Reference in a new issue