teqo/src/app/(campaign)/campanha/(app)/municipios/municipalityStaffFormActions.ts
Francisco Ignácio Fontoura Solla 7c50e29aa7 B27: combobox + chips + auto-save no popover de Assessores da lista de municípios
Replaces the checkbox-list + "Salvar assessores" button in the
Assessors popover (/campanha/municipios) with removable chips + a
Command combobox, delta-based auto-save (one advisor add/remove per
request, never the whole array), and optimistic UI with request
sequencing to resolve out-of-order responses correctly.

- New POST /campanha/municipios/advisors JSON route (mirrors
  expected-votes/), backed by setMunicipalityAdvisorMembership(Record)
  in actions/municipality.ts (text advisory lock + transaction).
- nextAdvisorIdsAfterMembership moved to
  src/lib/municipalityAdvisorMembership.ts with unit tests.
- Shared isSameOriginRequest (src/utilities/sameOriginRequest.ts) and
  uniqueRelationshipIds (src/utilities/relationship.ts) helpers,
  de-duplicating the same-origin CSRF check and the
  Set+map(relationshipId)+filter pattern across advisor call sites.
- MunicipalityListAdvisorsControl.tsx rewritten: chips, Command
  combobox, per-item pending affordance, rollback on error, and a
  request-sequence guard so only the most recently sent delta's
  response is adopted when concurrent optimistic updates settle.
- e2e coverage for the combobox auto-save flow; setup prewarms the new
  POST-only route to avoid Playwright dev-server HMR aborting the
  first request.
- Plan and roadmap marked as delivered (B27).
2026-07-26 03:31:51 -03:00

121 lines
4.4 KiB
TypeScript

'use server'
import {
assignMunicipalityAdvisors,
setMunicipalityExpectedVotes,
setMunicipalityPoliticalTrend,
} from '@/app/(campaign)/campanha/actions/municipality'
import { createMunicipalityUpdate } from '@/app/(campaign)/campanha/actions/municipalityUpdate'
import {
checkboxFormValue,
nullableFormText,
optionalFormText,
optionalMunicipalitySlugFromForm,
repeatedRelationshipFormValues,
requiredRelationshipFormValue,
voteEstimateScenarioFromForm,
} from '@/lib/formData'
import {
MUNICIPALITY_ADVISOR_MEMBERSHIP_UNRESTRICTED_MESSAGE,
parsePoliticalTrendStatusFormValue,
} from '@/lib/schemas/municipality'
import { parseMunicipalitySignalType } from '@/lib/schemas/municipalityUpdate'
import {
mapCampaignFormActionError,
type CampaignFormActionState,
} from '@/utilities/campaignFormActionError'
import { revalidateMunicipalityListPaths } from '@/utilities/municipalityRevalidation'
import { municipalityStaffEditSafeMessages } from './municipalityStaffEditMessages'
export const setMunicipalityExpectedVotesFormAction = async (
_state: CampaignFormActionState,
formData: FormData,
): Promise<CampaignFormActionState> => {
try {
const municipality = requiredRelationshipFormValue(formData, 'municipalityId')
const expectedVotes = voteEstimateScenarioFromForm(formData, 'expectedVotes')
await setMunicipalityExpectedVotes({ municipality, expectedVotes })
revalidateMunicipalityListPaths({ slug: optionalMunicipalitySlugFromForm(formData) })
return { status: 'success', message: 'Votos estimados atualizados.' }
} catch (error) {
return mapCampaignFormActionError({
error,
safeMessages: municipalityStaffEditSafeMessages,
genericMessage:
'Não foi possível salvar os votos estimados. Verifique seu acesso e tente novamente.',
})
}
}
export const setMunicipalityPoliticalTrendFormAction = async (
_state: CampaignFormActionState,
formData: FormData,
): Promise<CampaignFormActionState> => {
try {
const municipality = requiredRelationshipFormValue(formData, 'municipalityId')
const status = parsePoliticalTrendStatusFormValue(optionalFormText(formData, 'trendStatus'))
await setMunicipalityPoliticalTrend({
municipality,
status,
note: nullableFormText(formData, 'trendNote'),
})
revalidateMunicipalityListPaths({ slug: optionalMunicipalitySlugFromForm(formData) })
return { status: 'success', message: 'Tendência política registrada.' }
} catch (error) {
return mapCampaignFormActionError({
error,
safeMessages: municipalityStaffEditSafeMessages,
genericMessage:
'Não foi possível registrar a tendência. Verifique seu acesso e tente novamente.',
})
}
}
export const assignMunicipalityAdvisorsFormAction = async (
_state: CampaignFormActionState,
formData: FormData,
): Promise<CampaignFormActionState> => {
try {
const municipality = requiredRelationshipFormValue(formData, 'municipalityId')
const advisors = repeatedRelationshipFormValues(formData, 'advisors')
await assignMunicipalityAdvisors({ municipality, advisors })
revalidateMunicipalityListPaths({ slug: optionalMunicipalitySlugFromForm(formData) })
return { status: 'success', message: 'Assessores atualizados.' }
} catch (error) {
return mapCampaignFormActionError({
error,
safeMessages: [MUNICIPALITY_ADVISOR_MEMBERSHIP_UNRESTRICTED_MESSAGE],
genericMessage:
'Não foi possível atualizar os assessores. Verifique seu acesso e tente novamente.',
})
}
}
export const createMunicipalityListSignalFormAction = async (
_state: CampaignFormActionState,
formData: FormData,
): Promise<CampaignFormActionState> => {
try {
const municipality = requiredRelationshipFormValue(formData, 'municipalityId')
await createMunicipalityUpdate({
municipality,
kind: 'sinal',
body: optionalFormText(formData, 'body'),
signalType: parseMunicipalitySignalType(optionalFormText(formData, 'signalType')),
signalSource: optionalFormText(formData, 'signalSource'),
triangulated: checkboxFormValue(formData, 'triangulated'),
})
revalidateMunicipalityListPaths({ slug: optionalMunicipalitySlugFromForm(formData) })
return { status: 'success', message: 'Sinal registrado.' }
} catch (error) {
return mapCampaignFormActionError({
error,
genericMessage: 'Não foi possível registrar o sinal. Verifique seu acesso e tente novamente.',
})
}
}