teqo-backup/src/lib/schemas/municipality.ts
Francisco Ignácio Fontoura Solla 0a63621d4b B37 simplify: one membership delta, cap messages named once.
nextStateDeputyIdsAfterMunicipalityMembership was the third byte-for-byte copy
of the same single-id delta — nextAdvisorIdsAfterMembership and
nextStateDeputyIdsAfterMembership differ from it only in which cap they read —
so the algorithm now lives once in nextIdsAfterMembership with the cap as data,
and the three named wrappers just bind their own. The three cloned spec files
became one describe.each suite: coverage went up rather than down, since every
relation now gets the "can go to zero" and no-mutation cases only B37's clone
had, plus an explicit assertion that each wrapper refuses at ITS cap with ITS
message.

That pairing matters because mapCampaignFormActionError matches thrown messages
against safeMessages by exact string, and two of those cap messages were bare
literals in three src places each (thrown, plus two independent allowlists):
rewording any one would have silently collapsed a real refusal into "tente
novamente". Both are constants now, next to their caps, following the
MUNICIPALITY_STATE_DEPUTIES_CAP_MESSAGE precedent already in those same files.
The dobradinha staff message had the same exposure in four places — and
actions/stateDeputy.ts already imported the constant while restating it as a
literal one line below — so it is STATE_DEPUTY_STAFF_MESSAGE (renamed: it
guards create/update too, not just the batch), and the conflict message it
shares with the create route is named too.

The batch action stopped resolving the dobradinha slug before its loop: the
slug exists only to target the revalidate, which the caller already skips when
nothing changed, so on a no-op batch that read was fetched and thrown away —
the guard setLeadershipMunicipalitiesMembershipRecord already had. Its
redundant second dedup is gone (the schema's transform already deduped; the
sort stays, for deadlock-free lock ordering), and the bare 435 shared with the
advisor batch is MAX_MUNICIPALITIES_PER_BATCH.

Two memoization gaps closed, both restoring invariants the codebase had already
established elsewhere. An advisor's scoped .filter() returned a fresh array per
row, defeating the WeakMap that exists precisely to share derivations across
rows, so scopedPortfolioIndex memoizes on (index, addableIds) and every row
gets one array. And LeadershipStateDeputyRelationCell called matchesAtWordStart
per candidate, paying an NFD pass plus three Unicode regexes on both sides per
keystroke over the unpaginated leadership catalog — the cost wordStartFilter's
own doc comment warns about; it now normalizes the query once against labels
cached on options, like municipalityPortfolio.

Rejected with reason: maxItems on the dobradinhas cell. A dobradinha has no
product ceiling on municípios (that is why the bound is the catalog), so a
"generous 30" would invent a rule that refuses a legitimate statewide
dobradinha, and the honest 435 is unreachable when ids are unique.

Also dropped the dead addPlaceholder knob no caller ever set.
2026-07-28 10:25:47 -03:00

119 lines
5.1 KiB
TypeScript

import { z } from 'zod'
import { ENGAGEMENT_LEVEL_TEXT_MAX_LENGTH, engagementLevels } from '@/lib/engagementLevel'
import { positiveRelationshipId, trimmedNullableText } from '@/lib/schemas/primitives'
import { voteEstimateScenarioFieldsSchema } from '@/lib/schemas/votePledge'
export const politicalTrendStatuses = ['favoravel', 'neutra', 'desfavoravel'] as const
export type PoliticalTrendStatusValue = (typeof politicalTrendStatuses)[number]
/**
* Anti-payload bound, not a domain rule: `municipality.stateDeputies` has no
* product-level ceiling (a município can be dobrado with any number of
* deputados), and the catalog itself caps out at 435. Named so the chip-batch
* write (B37) and this whole-array strategy update stay on the same number —
* they parse through the same schema, and a batch write that pushed past a
* lower bound would leave the strategy ficha unsavable on its next submit.
*/
export const MAX_STATE_DEPUTIES_PER_MUNICIPALITY = 435
/**
* Anti-payload bound on a batch that names many municípios at once (a whole
* território/ZE): the catalog is 435 rows and ids are unique, so this is the
* whole universe and not a product rule. Named because both município-side
* batch schemas (`advisor`, `stateDeputy`) were carrying a bare `435`.
*/
export const MAX_MUNICIPALITIES_PER_BATCH = 435
export const MUNICIPALITY_STATE_DEPUTIES_CAP_MESSAGE = `Cada município aceita no máximo ${MAX_STATE_DEPUTIES_PER_MUNICIPALITY} dobradinhas.`
const stateDeputiesArraySchema = z
.array(positiveRelationshipId)
.max(MAX_STATE_DEPUTIES_PER_MUNICIPALITY)
.transform((ids) => [...new Set(ids)])
export const municipalityStrategyUpdateSchema = z.object({
municipality: positiveRelationshipId,
priority: z.enum(['alta', 'normal']).optional(),
strengths: z.array(z.string().trim().min(1).max(1000)).max(20).optional(),
risks: z.array(z.string().trim().min(1).max(1000)).max(20).optional(),
stateDeputies: stateDeputiesArraySchema.optional(),
dobradinhaNotes: trimmedNullableText(4000),
nextSteps: trimmedNullableText(4000),
budgetNotes: trimmedNullableText(4000),
})
export const municipalityPoliticalTrendSchema = z.object({
municipality: positiveRelationshipId,
status: z.enum(politicalTrendStatuses).nullable(),
note: trimmedNullableText(2000),
})
export const parsePoliticalTrendStatusFormValue = (
raw: string | undefined,
): PoliticalTrendStatusValue | null => {
if (!raw) return null
return politicalTrendStatuses.includes(raw as PoliticalTrendStatusValue)
? (raw as PoliticalTrendStatusValue)
: null
}
export const MAX_ADVISORS_PER_MUNICIPALITY = 10
export const MUNICIPALITY_ADVISORS_CAP_MESSAGE = `Cada município aceita no máximo ${MAX_ADVISORS_PER_MUNICIPALITY} assessores.`
export const municipalityAdvisorsAssignmentSchema = z.object({
municipality: positiveRelationshipId,
advisors: z
.array(positiveRelationshipId)
.max(MAX_ADVISORS_PER_MUNICIPALITY)
.transform((ids) => [...new Set(ids)]),
})
/** Single-toggle delta from the list popover — one advisor at a time, never the whole array. */
export const municipalityAdvisorMembershipSchema = z.object({
municipality: positiveRelationshipId,
advisor: positiveRelationshipId,
assigned: z.boolean(),
})
export const MUNICIPALITY_ADVISOR_MEMBERSHIP_UNRESTRICTED_MESSAGE =
'Somente a coordenação geral ou o candidato designa assessores.'
export const MUNICIPALITY_ADVISOR_MEMBERSHIP_SAFE_MESSAGES = [
MUNICIPALITY_ADVISOR_MEMBERSHIP_UNRESTRICTED_MESSAGE,
MUNICIPALITY_ADVISORS_CAP_MESSAGE,
] as const
export const MUNICIPALITY_ENGAGEMENT_LEVEL_UNRESTRICTED_MESSAGE =
'Somente a coordenação geral ou o candidato move o nível de envolvimento.'
/**
* E14 — a movement is never just the new level: the motivo and the signals
* that would reverse it are what make the decision auditable later, so both
* are required by the schema rather than by the form alone.
*/
export const municipalityEngagementLevelSchema = z.object({
municipality: positiveRelationshipId,
level: z.enum(engagementLevels),
note: z.string().trim().min(1).max(ENGAGEMENT_LEVEL_TEXT_MAX_LENGTH),
reversalSignals: z.string().trim().min(1).max(ENGAGEMENT_LEVEL_TEXT_MAX_LENGTH),
/** Licenses a two-level jump (research §6.8). */
triangulatedShock: z.boolean().default(false),
/** Accepts the listed violations knowingly; recorded in the decision snapshot. */
override: z.boolean().default(false),
})
export const municipalityExpectedVotesSchema = z.object({
municipality: positiveRelationshipId,
expectedVotes: voteEstimateScenarioFieldsSchema,
})
export type MunicipalityStrategyUpdateInput = z.input<typeof municipalityStrategyUpdateSchema>
export type MunicipalityPoliticalTrendInput = z.input<typeof municipalityPoliticalTrendSchema>
export type MunicipalityAdvisorsAssignmentInput = z.input<
typeof municipalityAdvisorsAssignmentSchema
>
export type MunicipalityAdvisorMembershipInput = z.input<typeof municipalityAdvisorMembershipSchema>
export type MunicipalityExpectedVotesInput = z.input<typeof municipalityExpectedVotesSchema>
export type MunicipalityEngagementLevelInput = z.input<typeof municipalityEngagementLevelSchema>