mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-27 14:23:05 +00:00
Merge pull request #223 from fsolla/cursor/pool-i171-b4f8ce5e-fad8
OH10 — Writes municipality staff CAS: update, declareVotes, tendência, engagement, advisors
This commit is contained in:
commit
b85d6f6227
36 changed files with 2068 additions and 32 deletions
|
|
@ -4,6 +4,8 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
**Recently resolved (2026-08-02):** **OH10** (Issue #171) — writes municipality staff CAS (`baseUpdatedAt`) + outbox irmão (`opsMunicipalityOutbox`) para municipalityUpdate, declareVotes, tendência, engagement e advisors; flag OFF mantém caminhos actuais. Plano: [`oh10-municipality-writes-cas.md`](docs/plans/oh10-municipality-writes-cas.md).
|
||||||
|
|
||||||
**Recently resolved (2026-08-02):** **OH9** (Issue #172) — detalhe de município dual-path: `MunicipalityDetailHeaderView` partilhado; `OfflineBoundary` (SSR=RSC; offline+`OPS_HYBRID`→Local); `MunicipalityDetailLocal` lê mirror (município + pledges×leaderships); regiões online-only com “Disponível quando estiveres online.”; e2e `campaignOpsOffline` (skip sem flag). Plano: [`oh9-municipio-detalhe-dualpath.md`](docs/plans/oh9-municipio-detalhe-dualpath.md).
|
**Recently resolved (2026-08-02):** **OH9** (Issue #172) — detalhe de município dual-path: `MunicipalityDetailHeaderView` partilhado; `OfflineBoundary` (SSR=RSC; offline+`OPS_HYBRID`→Local); `MunicipalityDetailLocal` lê mirror (município + pledges×leaderships); regiões online-only com “Disponível quando estiveres online.”; e2e `campaignOpsOffline` (skip sem flag). Plano: [`oh9-municipio-detalhe-dualpath.md`](docs/plans/oh9-municipio-detalhe-dualpath.md).
|
||||||
|
|
||||||
**Recently resolved (2026-08-01):** **B114** (Issue #195) — wizard Voltar header = Android back: contrato `wizardBack` + `useWizardBackHistory` (pushState/popstate), previousHrefs canônicos, layer form liderança. Plano: [`wizard-back-navigation-system.md`](docs/plans/wizard-back-navigation-system.md).
|
**Recently resolved (2026-08-01):** **B114** (Issue #195) — wizard Voltar header = Android back: contrato `wizardBack` + `useWizardBackHistory` (pushState/popstate), previousHrefs canônicos, layer form liderança. Plano: [`wizard-back-navigation-system.md`](docs/plans/wizard-back-navigation-system.md).
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
# OH10 — Writes municipality staff CAS: update, declareVotes, tendência, engagement, advisors
|
# OH10 — Writes municipality staff CAS: update, declareVotes, tendência, engagement, advisors
|
||||||
|
|
||||||
Status: rascunho
|
Status: pronto para PR
|
||||||
Atualizado em: 2026-08-01
|
Atualizado em: 2026-08-02
|
||||||
Issue: #171
|
Issue: #171
|
||||||
Priority: P1
|
Priority: P1
|
||||||
Model: cursor-grok-4.5-medium
|
Model: cursor-grok-4.5-medium
|
||||||
|
|
@ -10,13 +10,25 @@ Appetite: ~2–3 dias eng
|
||||||
Depends: OH7, OH9
|
Depends: OH7, OH9
|
||||||
Responsável: —
|
Responsável: —
|
||||||
|
|
||||||
|
## Débitos pós-/simplify (não bloqueiam OH10)
|
||||||
|
|
||||||
|
- Toast de conflito CAS em tendência/nível da lista (só advisors + declareVotes têm escolha Manter/Usar).
|
||||||
|
- Unificar executores OH6+OH10 (já previsto em OH13).
|
||||||
|
|
||||||
|
## Freshness audit (2026-08-02)
|
||||||
|
|
||||||
|
- OH7 (#169) e OH9 (#172) `done`+`in-prod`. OH6 CAS em `estimateVotesCas` + `opsEstimateOutbox` intactos; mirror tem `updatedAt` em `OpsMunicipality` / `OpsVotePledge`.
|
||||||
|
- Actions citadas batem: `declareVotesRecord`, `createMunicipalityUpdateRecord`, `setMunicipalityPoliticalTrendRecord`, `setMunicipalityEngagementLevelRecord`, `setMunicipalityAdvisorMembershipRecord` / `assignMunicipalityAdvisorsRecord`.
|
||||||
|
- Controles B9 intactos (JSON routes + forms). Sem `baseUpdatedAt` ainda — a implementar.
|
||||||
|
- Outbox: executor OH6 fica; OH10 adiciona executor irmão (`opsMunicipalityOutbox`) com as mesmas chaves de merge — evita refactor arriscado do singleton de estimativas; OH13 pode unificar.
|
||||||
|
|
||||||
## Premissas
|
## Premissas
|
||||||
|
|
||||||
1. Padrão provado: OH6/OH7 (CAS + outbox + mirror keys).
|
1. Padrão provado: OH6/OH7 (CAS + outbox + mirror keys).
|
||||||
2. Cada write ganha CAS por `baseUpdatedAt` do doc alvo; sem base → comportamento actual.
|
2. Cada write ganha CAS por `baseUpdatedAt` do doc alvo; sem base → comportamento actual.
|
||||||
3. Engagement level continua a escrever `allocationDecision` na mesma transação (invariante E14) — o outbox só re-executa a action inteira, nunca a parte.
|
3. Engagement level continua a escrever `allocationDecision` na mesma transação (invariante E14) — o outbox só re-executa a action inteira, nunca a parte.
|
||||||
|
|
||||||
→ Corrija agora ou sigo com estas.
|
→ Confirmadas; a implementar.
|
||||||
|
|
||||||
## Objetivos
|
## Objetivos
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -341,11 +341,13 @@ export const LeadershipsTab = async ({
|
||||||
export const UpdatesTab = async ({
|
export const UpdatesTab = async ({
|
||||||
municipalityID,
|
municipalityID,
|
||||||
municipalitySlug,
|
municipalitySlug,
|
||||||
|
municipalityUpdatedAt,
|
||||||
rawSearchParams,
|
rawSearchParams,
|
||||||
payloadUser: { payload, user },
|
payloadUser: { payload, user },
|
||||||
}: {
|
}: {
|
||||||
municipalityID: number
|
municipalityID: number
|
||||||
municipalitySlug: string
|
municipalitySlug: string
|
||||||
|
municipalityUpdatedAt?: string
|
||||||
rawSearchParams: MunicipalityDetailSearchParams
|
rawSearchParams: MunicipalityDetailSearchParams
|
||||||
payloadUser: PayloadUser
|
payloadUser: PayloadUser
|
||||||
}) => {
|
}) => {
|
||||||
|
|
@ -356,6 +358,7 @@ export const UpdatesTab = async ({
|
||||||
<div className="flex flex-col gap-6">
|
<div className="flex flex-col gap-6">
|
||||||
<MunicipalityUpdateForm
|
<MunicipalityUpdateForm
|
||||||
municipalityID={municipalityID}
|
municipalityID={municipalityID}
|
||||||
|
municipalityUpdatedAt={municipalityUpdatedAt}
|
||||||
formAction={createMunicipalityUpdateFormAction}
|
formAction={createMunicipalityUpdateFormAction}
|
||||||
/>
|
/>
|
||||||
<MunicipalityUpdateFeed updates={feed.updates} />
|
<MunicipalityUpdateFeed updates={feed.updates} />
|
||||||
|
|
|
||||||
|
|
@ -118,6 +118,7 @@ export default async function MunicipalityDetailPage({
|
||||||
<UpdatesTab
|
<UpdatesTab
|
||||||
municipalityID={view.id}
|
municipalityID={view.id}
|
||||||
municipalitySlug={view.slug}
|
municipalitySlug={view.slug}
|
||||||
|
municipalityUpdatedAt={view.updatedAt}
|
||||||
rawSearchParams={rawSearchParams}
|
rawSearchParams={rawSearchParams}
|
||||||
payloadUser={{ payload, user }}
|
payloadUser={{ payload, user }}
|
||||||
/>
|
/>
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ import { NextResponse } from 'next/server'
|
||||||
import { setMunicipalityEngagementLevel } from '@/app/(campaign)/campanha/actions/municipality'
|
import { setMunicipalityEngagementLevel } from '@/app/(campaign)/campanha/actions/municipality'
|
||||||
import { EngagementLevelBlockedError } from '@/lib/engagementLevel'
|
import { EngagementLevelBlockedError } from '@/lib/engagementLevel'
|
||||||
import {
|
import {
|
||||||
MUNICIPALITY_ENGAGEMENT_LEVEL_UNRESTRICTED_MESSAGE,
|
MUNICIPALITY_ENGAGEMENT_LEVEL_SAFE_MESSAGES,
|
||||||
municipalityEngagementLevelSchema,
|
municipalityEngagementLevelSchema,
|
||||||
} from '@/lib/schemas/municipality'
|
} from '@/lib/schemas/municipality'
|
||||||
import { positiveRelationshipId } from '@/lib/schemas/primitives'
|
import { positiveRelationshipId } from '@/lib/schemas/primitives'
|
||||||
|
|
@ -25,7 +25,7 @@ export const POST = campaignJsonMutationRoute(
|
||||||
bodySchema,
|
bodySchema,
|
||||||
// Only the unrestricted-actor message: this action reloads the actor with
|
// Only the unrestricted-actor message: this action reloads the actor with
|
||||||
// its own guard, never through `getFreshStaffActor` (same as `advisors/`).
|
// its own guard, never through `getFreshStaffActor` (same as `advisors/`).
|
||||||
safeMessages: [MUNICIPALITY_ENGAGEMENT_LEVEL_UNRESTRICTED_MESSAGE],
|
safeMessages: MUNICIPALITY_ENGAGEMENT_LEVEL_SAFE_MESSAGES,
|
||||||
genericMessage: 'Não foi possível registrar o nível. Verifique seu acesso e tente novamente.',
|
genericMessage: 'Não foi possível registrar o nível. Verifique seu acesso e tente novamente.',
|
||||||
},
|
},
|
||||||
async ({ municipalityId, ...movement }) => {
|
async ({ municipalityId, ...movement }) => {
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,7 @@
|
||||||
|
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||||
|
|
||||||
/** Shared form-error copy for municipality staff edits — kept out of `'use server'` files. */
|
/** Shared form-error copy for municipality staff edits — kept out of `'use server'` files. */
|
||||||
export const municipalityStaffEditSafeMessages = [
|
export const municipalityStaffEditSafeMessages = [
|
||||||
'Somente a coordenação e a assessoria podem editar o município.',
|
'Somente a coordenação e a assessoria podem editar o município.',
|
||||||
|
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||||
] as const
|
] as const
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,7 @@ import {
|
||||||
type MunicipalityPoliticalTrendInput,
|
type MunicipalityPoliticalTrendInput,
|
||||||
type MunicipalityStrategyUpdateInput,
|
type MunicipalityStrategyUpdateInput,
|
||||||
} from '@/lib/schemas/municipality'
|
} from '@/lib/schemas/municipality'
|
||||||
|
import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas'
|
||||||
import { normalizeVoteEstimateOnSave, toVoteEstimateScenarioViewModel } from '@/lib/voteEstimate'
|
import { normalizeVoteEstimateOnSave, toVoteEstimateScenarioViewModel } from '@/lib/voteEstimate'
|
||||||
import type { CampaignUser } from '@/payload-types'
|
import type { CampaignUser } from '@/payload-types'
|
||||||
import {
|
import {
|
||||||
|
|
@ -83,10 +84,25 @@ export const setMunicipalityPoliticalTrendRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
input: MunicipalityPoliticalTrendInput,
|
input: MunicipalityPoliticalTrendInput,
|
||||||
|
options?: { cas?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const { municipality, status, note } = municipalityPoliticalTrendSchema.parse(input)
|
const { municipality, status, note, baseUpdatedAt } =
|
||||||
|
municipalityPoliticalTrendSchema.parse(input)
|
||||||
|
const enforceCas = options?.cas === true
|
||||||
const currentActor = await getFreshStaffActor(payload, actor)
|
const currentActor = await getFreshStaffActor(payload, actor)
|
||||||
|
|
||||||
|
if (enforceCas && baseUpdatedAt !== undefined) {
|
||||||
|
const current = await payload.findByID({
|
||||||
|
collection: 'municipality',
|
||||||
|
id: municipality,
|
||||||
|
depth: 0,
|
||||||
|
select: { updatedAt: true },
|
||||||
|
user: currentActor,
|
||||||
|
overrideAccess: false,
|
||||||
|
})
|
||||||
|
assertOpsUpdatedAtCas(true, baseUpdatedAt, current.updatedAt)
|
||||||
|
}
|
||||||
|
|
||||||
return payload.update({
|
return payload.update({
|
||||||
collection: 'municipality',
|
collection: 'municipality',
|
||||||
id: municipality,
|
id: municipality,
|
||||||
|
|
@ -104,6 +120,17 @@ export const setMunicipalityPoliticalTrend = async (input: MunicipalityPolitical
|
||||||
return setMunicipalityPoliticalTrendRecord(payload, actor, input)
|
return setMunicipalityPoliticalTrendRecord(payload, actor, input)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const setMunicipalityPoliticalTrendCas = async (input: MunicipalityPoliticalTrendInput) => {
|
||||||
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
|
return setMunicipalityPoliticalTrendRecord(payload, actor, input, { cas: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const setMunicipalityPoliticalTrendCasRecord = async (
|
||||||
|
payload: Payload,
|
||||||
|
actor: CampaignUser,
|
||||||
|
input: MunicipalityPoliticalTrendInput,
|
||||||
|
) => setMunicipalityPoliticalTrendRecord(payload, actor, input, { cas: true })
|
||||||
|
|
||||||
/** Staff-only total expected votes for the municipality (distinct from pledge aggregates). */
|
/** Staff-only total expected votes for the municipality (distinct from pledge aggregates). */
|
||||||
export const setMunicipalityExpectedVotesRecord = async (
|
export const setMunicipalityExpectedVotesRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
|
|
@ -148,9 +175,11 @@ export const setMunicipalityEngagementLevelRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
input: MunicipalityEngagementLevelInput,
|
input: MunicipalityEngagementLevelInput,
|
||||||
|
options?: { cas?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const { municipality, level, note, reversalSignals, triangulatedShock, override } =
|
const { municipality, level, note, reversalSignals, triangulatedShock, override, baseUpdatedAt } =
|
||||||
municipalityEngagementLevelSchema.parse(input)
|
municipalityEngagementLevelSchema.parse(input)
|
||||||
|
const enforceCas = options?.cas === true
|
||||||
|
|
||||||
return withPayloadTransaction(
|
return withPayloadTransaction(
|
||||||
payload,
|
payload,
|
||||||
|
|
@ -170,12 +199,14 @@ export const setMunicipalityEngagementLevelRecord = async (
|
||||||
collection: 'municipality',
|
collection: 'municipality',
|
||||||
id: municipality,
|
id: municipality,
|
||||||
depth: 0,
|
depth: 0,
|
||||||
select: { engagementLevel: true, levelChangedAt: true },
|
select: { engagementLevel: true, levelChangedAt: true, updatedAt: true },
|
||||||
user: currentActor,
|
user: currentActor,
|
||||||
overrideAccess: false,
|
overrideAccess: false,
|
||||||
req,
|
req,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
assertOpsUpdatedAtCas(enforceCas, baseUpdatedAt, current.updatedAt)
|
||||||
|
|
||||||
const from = current.engagementLevel ?? null
|
const from = current.engagementLevel ?? null
|
||||||
const violations = getEngagementLevelViolations({
|
const violations = getEngagementLevelViolations({
|
||||||
from,
|
from,
|
||||||
|
|
@ -233,13 +264,29 @@ export const setMunicipalityEngagementLevel = async (input: MunicipalityEngageme
|
||||||
return setMunicipalityEngagementLevelRecord(payload, actor, input)
|
return setMunicipalityEngagementLevelRecord(payload, actor, input)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const setMunicipalityEngagementLevelCas = async (
|
||||||
|
input: MunicipalityEngagementLevelInput,
|
||||||
|
) => {
|
||||||
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
|
return setMunicipalityEngagementLevelRecord(payload, actor, input, { cas: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const setMunicipalityEngagementLevelCasRecord = async (
|
||||||
|
payload: Payload,
|
||||||
|
actor: CampaignUser,
|
||||||
|
input: MunicipalityEngagementLevelInput,
|
||||||
|
) => setMunicipalityEngagementLevelRecord(payload, actor, input, { cas: true })
|
||||||
|
|
||||||
/** Advisor assignment is unrestricted staff (coordinator + candidate); the hook validates eligibility. */
|
/** Advisor assignment is unrestricted staff (coordinator + candidate); the hook validates eligibility. */
|
||||||
export const assignMunicipalityAdvisorsRecord = async (
|
export const assignMunicipalityAdvisorsRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
input: MunicipalityAdvisorsAssignmentInput,
|
input: MunicipalityAdvisorsAssignmentInput,
|
||||||
|
options?: { cas?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const { municipality, advisors } = municipalityAdvisorsAssignmentSchema.parse(input)
|
const { municipality, advisors, baseUpdatedAt } =
|
||||||
|
municipalityAdvisorsAssignmentSchema.parse(input)
|
||||||
|
const enforceCas = options?.cas === true
|
||||||
|
|
||||||
return withPayloadTransaction(
|
return withPayloadTransaction(
|
||||||
payload,
|
payload,
|
||||||
|
|
@ -253,6 +300,20 @@ export const assignMunicipalityAdvisorsRecord = async (
|
||||||
|
|
||||||
await acquireTextAdvisoryLocks(payload, req, [`municipality-advisors:${municipality}`])
|
await acquireTextAdvisoryLocks(payload, req, [`municipality-advisors:${municipality}`])
|
||||||
|
|
||||||
|
if (enforceCas && baseUpdatedAt !== undefined) {
|
||||||
|
// Intentional admin bypass: unrestricted role verified above; advisors
|
||||||
|
// field access would otherwise hide `updatedAt` from some actors.
|
||||||
|
const current = await payload.findByID({
|
||||||
|
collection: 'municipality',
|
||||||
|
id: municipality,
|
||||||
|
depth: 0,
|
||||||
|
select: { updatedAt: true },
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
})
|
||||||
|
assertOpsUpdatedAtCas(true, baseUpdatedAt, current.updatedAt)
|
||||||
|
}
|
||||||
|
|
||||||
// Intentional admin bypass: unrestricted role was freshly verified above;
|
// Intentional admin bypass: unrestricted role was freshly verified above;
|
||||||
// the advisors field is admin-only by field access.
|
// the advisors field is admin-only by field access.
|
||||||
return payload.update({
|
return payload.update({
|
||||||
|
|
@ -273,6 +334,17 @@ export const assignMunicipalityAdvisors = async (input: MunicipalityAdvisorsAssi
|
||||||
return assignMunicipalityAdvisorsRecord(payload, actor, input)
|
return assignMunicipalityAdvisorsRecord(payload, actor, input)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const assignMunicipalityAdvisorsCas = async (input: MunicipalityAdvisorsAssignmentInput) => {
|
||||||
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
|
return assignMunicipalityAdvisorsRecord(payload, actor, input, { cas: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const assignMunicipalityAdvisorsCasRecord = async (
|
||||||
|
payload: Payload,
|
||||||
|
actor: CampaignUser,
|
||||||
|
input: MunicipalityAdvisorsAssignmentInput,
|
||||||
|
) => assignMunicipalityAdvisorsRecord(payload, actor, input, { cas: true })
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Single-advisor delta from the list popover — writes one toggle instead of
|
* Single-advisor delta from the list popover — writes one toggle instead of
|
||||||
* replacing the whole `advisors` array, so a concurrent edit from another
|
* replacing the whole `advisors` array, so a concurrent edit from another
|
||||||
|
|
@ -288,8 +360,11 @@ export const setMunicipalityAdvisorMembershipRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
input: MunicipalityAdvisorMembershipInput,
|
input: MunicipalityAdvisorMembershipInput,
|
||||||
|
options?: { cas?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const { municipality, advisor, assigned } = municipalityAdvisorMembershipSchema.parse(input)
|
const { municipality, advisor, assigned, baseUpdatedAt } =
|
||||||
|
municipalityAdvisorMembershipSchema.parse(input)
|
||||||
|
const enforceCas = options?.cas === true
|
||||||
|
|
||||||
return withPayloadTransaction(
|
return withPayloadTransaction(
|
||||||
payload,
|
payload,
|
||||||
|
|
@ -307,11 +382,13 @@ export const setMunicipalityAdvisorMembershipRecord = async (
|
||||||
collection: 'municipality',
|
collection: 'municipality',
|
||||||
id: municipality,
|
id: municipality,
|
||||||
depth: 0,
|
depth: 0,
|
||||||
select: { advisors: true },
|
select: { advisors: true, updatedAt: true },
|
||||||
overrideAccess: true,
|
overrideAccess: true,
|
||||||
req,
|
req,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
assertOpsUpdatedAtCas(enforceCas, baseUpdatedAt, current.updatedAt)
|
||||||
|
|
||||||
const currentAdvisorIDs = uniqueRelationshipIds(current.advisors)
|
const currentAdvisorIDs = uniqueRelationshipIds(current.advisors)
|
||||||
const nextAdvisorIDs = nextAdvisorIdsAfterMembership(currentAdvisorIDs, advisor, assigned)
|
const nextAdvisorIDs = nextAdvisorIdsAfterMembership(currentAdvisorIDs, advisor, assigned)
|
||||||
if (nextAdvisorIDs === null) return current
|
if (nextAdvisorIDs === null) return current
|
||||||
|
|
@ -338,3 +415,9 @@ export const setMunicipalityAdvisorMembership = async (
|
||||||
const { payload, actor } = await getCampaignActionContext()
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
return setMunicipalityAdvisorMembershipRecord(payload, actor, input)
|
return setMunicipalityAdvisorMembershipRecord(payload, actor, input)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const setMunicipalityAdvisorMembershipCasRecord = async (
|
||||||
|
payload: Payload,
|
||||||
|
actor: CampaignUser,
|
||||||
|
input: MunicipalityAdvisorMembershipInput,
|
||||||
|
) => setMunicipalityAdvisorMembershipRecord(payload, actor, input, { cas: true })
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import {
|
||||||
municipalityUpdateCreateSchema,
|
municipalityUpdateCreateSchema,
|
||||||
type MunicipalityUpdateCreateInput,
|
type MunicipalityUpdateCreateInput,
|
||||||
} from '@/lib/schemas/municipalityUpdate'
|
} from '@/lib/schemas/municipalityUpdate'
|
||||||
|
import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas'
|
||||||
import type { CampaignUser } from '@/payload-types'
|
import type { CampaignUser } from '@/payload-types'
|
||||||
import { getCampaignActionContext, reloadCampaignActor } from '@/utilities/campaignActionContext'
|
import { getCampaignActionContext, reloadCampaignActor } from '@/utilities/campaignActionContext'
|
||||||
import { hookFilledCreateData } from '@/utilities/hookFilledData'
|
import { hookFilledCreateData } from '@/utilities/hookFilledData'
|
||||||
|
|
@ -15,17 +16,35 @@ export const createMunicipalityUpdateRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
input: MunicipalityUpdateCreateInput,
|
input: MunicipalityUpdateCreateInput,
|
||||||
|
options?: { cas?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const data = municipalityUpdateCreateSchema.parse(input)
|
const data = municipalityUpdateCreateSchema.parse(input)
|
||||||
|
const enforceCas = options?.cas === true
|
||||||
|
|
||||||
return withPayloadTransaction(
|
return withPayloadTransaction(
|
||||||
payload,
|
payload,
|
||||||
async ({ req }) => {
|
async ({ req }) => {
|
||||||
const currentActor = await reloadCampaignActor(payload, actor, req)
|
const currentActor = await reloadCampaignActor(payload, actor, req)
|
||||||
|
|
||||||
|
// CAS on parent municipality `updatedAt` (feed order / consistency).
|
||||||
|
if (enforceCas && data.baseUpdatedAt !== undefined) {
|
||||||
|
const parent = await payload.findByID({
|
||||||
|
collection: 'municipality',
|
||||||
|
id: data.municipality,
|
||||||
|
depth: 0,
|
||||||
|
select: { updatedAt: true },
|
||||||
|
user: currentActor,
|
||||||
|
overrideAccess: false,
|
||||||
|
req,
|
||||||
|
})
|
||||||
|
assertOpsUpdatedAtCas(true, data.baseUpdatedAt, parent.updatedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
const { baseUpdatedAt: _baseUpdatedAt, ...createData } = data
|
||||||
|
|
||||||
return payload.create({
|
return payload.create({
|
||||||
collection: 'municipalityUpdate',
|
collection: 'municipalityUpdate',
|
||||||
data: hookFilledCreateData<'municipalityUpdate'>(data),
|
data: hookFilledCreateData<'municipalityUpdate'>(createData),
|
||||||
depth: 0,
|
depth: 0,
|
||||||
user: currentActor,
|
user: currentActor,
|
||||||
overrideAccess: false,
|
overrideAccess: false,
|
||||||
|
|
@ -40,3 +59,15 @@ export const createMunicipalityUpdate = async (input: MunicipalityUpdateCreateIn
|
||||||
const { payload, actor } = await getCampaignActionContext()
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
return createMunicipalityUpdateRecord(payload, actor, input)
|
return createMunicipalityUpdateRecord(payload, actor, input)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** OH10 — create feed update with optional CAS on parent municipality `updatedAt`. */
|
||||||
|
export const createMunicipalityUpdateCas = async (input: MunicipalityUpdateCreateInput) => {
|
||||||
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
|
return createMunicipalityUpdateRecord(payload, actor, input, { cas: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const createMunicipalityUpdateCasRecord = async (
|
||||||
|
payload: Payload,
|
||||||
|
actor: CampaignUser,
|
||||||
|
input: MunicipalityUpdateCreateInput,
|
||||||
|
) => createMunicipalityUpdateRecord(payload, actor, input, { cas: true })
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
import type { Payload } from 'payload'
|
import type { Payload } from 'payload'
|
||||||
|
|
||||||
import { relationshipId, requireRelationshipId } from '@/lib/relationship'
|
import { relationshipId, requireRelationshipId } from '@/lib/relationship'
|
||||||
|
import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas'
|
||||||
import {
|
import {
|
||||||
declareVotesSchema,
|
declareVotesSchema,
|
||||||
estimateVotesSchema,
|
estimateVotesSchema,
|
||||||
|
|
@ -29,8 +30,10 @@ export const declareVotesRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
input: DeclareVotesInput,
|
input: DeclareVotesInput,
|
||||||
|
options?: { cas?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const data = declareVotesSchema.parse(input)
|
const data = declareVotesSchema.parse(input)
|
||||||
|
const enforceCas = options?.cas === true
|
||||||
|
|
||||||
return withPayloadTransaction(
|
return withPayloadTransaction(
|
||||||
payload,
|
payload,
|
||||||
|
|
@ -89,6 +92,15 @@ export const declareVotesRecord = async (
|
||||||
})
|
})
|
||||||
const current = existing.docs[0]
|
const current = existing.docs[0]
|
||||||
|
|
||||||
|
if (enforceCas && data.baseUpdatedAt !== undefined) {
|
||||||
|
if (current) {
|
||||||
|
assertOpsUpdatedAtCas(true, data.baseUpdatedAt, current.updatedAt)
|
||||||
|
} else if (data.baseUpdatedAt !== null) {
|
||||||
|
// Client expected an existing pledge; it is gone — refuse.
|
||||||
|
assertOpsUpdatedAtCas(true, data.baseUpdatedAt, '')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (current) {
|
if (current) {
|
||||||
return payload.update({
|
return payload.update({
|
||||||
collection: 'votePledge',
|
collection: 'votePledge',
|
||||||
|
|
@ -123,6 +135,18 @@ export const declareVotes = async (input: DeclareVotesInput) => {
|
||||||
return declareVotesRecord(payload, actor, input)
|
return declareVotesRecord(payload, actor, input)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** OH10 — declare with optional CAS on pledge `updatedAt`. */
|
||||||
|
export const declareVotesCas = async (input: DeclareVotesInput) => {
|
||||||
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
|
return declareVotesRecord(payload, actor, input, { cas: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const declareVotesCasRecord = async (
|
||||||
|
payload: Payload,
|
||||||
|
actor: CampaignUser,
|
||||||
|
input: DeclareVotesInput,
|
||||||
|
) => declareVotesRecord(payload, actor, input, { cas: true })
|
||||||
|
|
||||||
/** Staff estimate of the real value — never visible to the leadership. */
|
/** Staff estimate of the real value — never visible to the leadership. */
|
||||||
export const estimateVotesRecord = async (
|
export const estimateVotesRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
|
|
|
||||||
|
|
@ -81,7 +81,9 @@ export const MunicipalityLeadershipsPanel = ({
|
||||||
<DeclareVotesForm
|
<DeclareVotesForm
|
||||||
municipalityID={municipalityID}
|
municipalityID={municipalityID}
|
||||||
leadershipID={leadership.id}
|
leadershipID={leadership.id}
|
||||||
|
pledgeId={pledge?.id}
|
||||||
currentDeclaredVotes={pledge?.declaredVotes ?? null}
|
currentDeclaredVotes={pledge?.declaredVotes ?? null}
|
||||||
|
currentUpdatedAt={pledge?.updatedAt ?? null}
|
||||||
formAction={declareFormAction}
|
formAction={declareFormAction}
|
||||||
/>
|
/>
|
||||||
</li>
|
</li>
|
||||||
|
|
|
||||||
|
|
@ -249,6 +249,7 @@ const municipalityListColumns = ({
|
||||||
level={municipality.engagementLevel}
|
level={municipality.engagementLevel}
|
||||||
levelNote={municipality.levelNote}
|
levelNote={municipality.levelNote}
|
||||||
levelChangedAt={municipality.levelChangedAt}
|
levelChangedAt={municipality.levelChangedAt}
|
||||||
|
updatedAt={municipality.updatedAt}
|
||||||
variant="popover"
|
variant="popover"
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
|
|
@ -288,6 +289,7 @@ const municipalityListColumns = ({
|
||||||
isPriority={municipality.priority === 'alta'}
|
isPriority={municipality.priority === 'alta'}
|
||||||
advisorNamesById={advisorNamesById}
|
advisorNamesById={advisorNamesById}
|
||||||
options={advisorOptions}
|
options={advisorOptions}
|
||||||
|
updatedAt={municipality.updatedAt}
|
||||||
variant="popover"
|
variant="popover"
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
|
|
@ -321,6 +323,7 @@ const municipalityListColumns = ({
|
||||||
municipalityName={municipality.name}
|
municipalityName={municipality.name}
|
||||||
status={municipality.politicalTrendStatus}
|
status={municipality.politicalTrendStatus}
|
||||||
trendNote={municipality.politicalTrendNote}
|
trendNote={municipality.politicalTrendNote}
|
||||||
|
updatedAt={municipality.updatedAt}
|
||||||
variant="popover"
|
variant="popover"
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { XIcon } from 'lucide-react'
|
import { XIcon } from 'lucide-react'
|
||||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
import type { MunicipalityListAdvisorsResponse } from '@/app/(campaign)/campanha/(app)/municipios/advisors/types'
|
import type { MunicipalityListAdvisorsResponse } from '@/app/(campaign)/campanha/(app)/municipios/advisors/types'
|
||||||
import {
|
import {
|
||||||
|
|
@ -9,6 +11,14 @@ import {
|
||||||
formatAdvisorNamesTooltip,
|
formatAdvisorNamesTooltip,
|
||||||
MunicipalityAdvisorAvatarStack,
|
MunicipalityAdvisorAvatarStack,
|
||||||
} from '@/components/campaign/municipality/MunicipalityAdvisorAvatarStack'
|
} from '@/components/campaign/municipality/MunicipalityAdvisorAvatarStack'
|
||||||
|
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
|
import {
|
||||||
|
discardOpsAdvisorsOutboxRow,
|
||||||
|
enqueueAdvisorsAssignment,
|
||||||
|
readOpsAdvisorsOutboxRow,
|
||||||
|
subscribeOpsAdvisorsOutboxRow,
|
||||||
|
} from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||||
|
import type { OpsMunicipalityWriteSyncStatus } from '@/components/campaign/opsSync/opsMunicipalityOutboxModel'
|
||||||
import {
|
import {
|
||||||
CampaignCellEditOverlay,
|
CampaignCellEditOverlay,
|
||||||
type CampaignCellEditOverlayVariant,
|
type CampaignCellEditOverlayVariant,
|
||||||
|
|
@ -19,7 +29,9 @@ import { Badge } from '@/components/ui/Badge'
|
||||||
import { Command, CommandInput, CommandItem, CommandList } from '@/components/ui/Command'
|
import { Command, CommandInput, CommandItem, CommandList } from '@/components/ui/Command'
|
||||||
import { Spinner } from '@/components/ui/Spinner'
|
import { Spinner } from '@/components/ui/Spinner'
|
||||||
import { postCampaignJson } from '@/lib/campaignJsonRequest'
|
import { postCampaignJson } from '@/lib/campaignJsonRequest'
|
||||||
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
import { sameIdSet } from '@/lib/sameIdSet'
|
import { sameIdSet } from '@/lib/sameIdSet'
|
||||||
|
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import { matchesAtWordStart } from '@/lib/wordStartFilter'
|
import { matchesAtWordStart } from '@/lib/wordStartFilter'
|
||||||
import type {
|
import type {
|
||||||
|
|
@ -29,6 +41,7 @@ import type {
|
||||||
|
|
||||||
const ADVISORS_ENDPOINT = '/campanha/municipios/advisors'
|
const ADVISORS_ENDPOINT = '/campanha/municipios/advisors'
|
||||||
const SAVE_ERROR_MESSAGE = 'Não foi possível atualizar os assessores. Tente novamente.'
|
const SAVE_ERROR_MESSAGE = 'Não foi possível atualizar os assessores. Tente novamente.'
|
||||||
|
const CONFLICT_TOAST_ID_PREFIX = 'ops-advisors-conflict:'
|
||||||
|
|
||||||
type MunicipalityListAdvisorsControlProps = {
|
type MunicipalityListAdvisorsControlProps = {
|
||||||
municipalityID: number
|
municipalityID: number
|
||||||
|
|
@ -38,6 +51,8 @@ type MunicipalityListAdvisorsControlProps = {
|
||||||
isPriority: boolean
|
isPriority: boolean
|
||||||
advisorNamesById: ReadonlyMap<number, MunicipalityAdvisorSummary>
|
advisorNamesById: ReadonlyMap<number, MunicipalityAdvisorSummary>
|
||||||
options: EligibleAdvisorOption[]
|
options: EligibleAdvisorOption[]
|
||||||
|
/** OH10 — CAS base when OPS_HYBRID outbox path is on. */
|
||||||
|
updatedAt?: string
|
||||||
variant: CampaignCellEditOverlayVariant
|
variant: CampaignCellEditOverlayVariant
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -48,8 +63,11 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
isPriority,
|
isPriority,
|
||||||
advisorNamesById,
|
advisorNamesById,
|
||||||
options,
|
options,
|
||||||
|
updatedAt,
|
||||||
variant,
|
variant,
|
||||||
}: MunicipalityListAdvisorsControlProps) => {
|
}: MunicipalityListAdvisorsControlProps) => {
|
||||||
|
const router = useRouter()
|
||||||
|
const opsHybrid = resolveOpsHybridEnabled()
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const [selectedIDs, setSelectedIDs] = useState<number[]>(currentAdvisorIDs)
|
const [selectedIDs, setSelectedIDs] = useState<number[]>(currentAdvisorIDs)
|
||||||
const [query, setQuery] = useState('')
|
const [query, setQuery] = useState('')
|
||||||
|
|
@ -69,6 +87,14 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
// clobber the optimistic state back to it.
|
// clobber the optimistic state back to it.
|
||||||
const requestSeqRef = useRef(0)
|
const requestSeqRef = useRef(0)
|
||||||
const latestConfirmedRef = useRef<{ seq: number; advisors: number[] } | null>(null)
|
const latestConfirmedRef = useRef<{ seq: number; advisors: number[] } | null>(null)
|
||||||
|
const previousOutboxStatusRef = useRef<OpsMunicipalityWriteSyncStatus | undefined>(undefined)
|
||||||
|
|
||||||
|
const outboxRow = useSyncExternalStore(
|
||||||
|
(onStoreChange) =>
|
||||||
|
opsHybrid ? subscribeOpsAdvisorsOutboxRow(municipalityID, onStoreChange) : () => undefined,
|
||||||
|
() => (opsHybrid ? readOpsAdvisorsOutboxRow(municipalityID) : undefined),
|
||||||
|
() => undefined,
|
||||||
|
)
|
||||||
|
|
||||||
const handleOpenChange = (nextOpen: boolean) => {
|
const handleOpenChange = (nextOpen: boolean) => {
|
||||||
noteOpenChange(nextOpen)
|
noteOpenChange(nextOpen)
|
||||||
|
|
@ -84,6 +110,51 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
setSelectedIDs(currentAdvisorIDs)
|
setSelectedIDs(currentAdvisorIDs)
|
||||||
}, [currentAdvisorIDs])
|
}, [currentAdvisorIDs])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const previous = previousOutboxStatusRef.current
|
||||||
|
previousOutboxStatusRef.current = outboxRow?.status
|
||||||
|
if (previous === 'pending' && outboxRow === undefined) {
|
||||||
|
router.refresh()
|
||||||
|
}
|
||||||
|
}, [outboxRow, router])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!opsHybrid || outboxRow?.status !== 'conflict') return
|
||||||
|
const toastId = `${CONFLICT_TOAST_ID_PREFIX}${municipalityID}`
|
||||||
|
toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
|
||||||
|
id: toastId,
|
||||||
|
duration: Infinity,
|
||||||
|
action: {
|
||||||
|
label: 'Manter o meu',
|
||||||
|
onClick: () => {
|
||||||
|
void enqueueAdvisorsAssignment({
|
||||||
|
municipalityId: municipalityID,
|
||||||
|
advisors: outboxRow.advisors,
|
||||||
|
baseUpdatedAt: outboxRow.serverUpdatedAt ?? null,
|
||||||
|
}).then(
|
||||||
|
() => setErrorMessage(null),
|
||||||
|
(error: unknown) => {
|
||||||
|
reportFailure(
|
||||||
|
error instanceof Error ? error.message : 'Não foi possível reenviar os assessores.',
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cancel: {
|
||||||
|
label: 'Usar o novo',
|
||||||
|
onClick: () => {
|
||||||
|
discardOpsAdvisorsOutboxRow(municipalityID)
|
||||||
|
setErrorMessage(null)
|
||||||
|
router.refresh()
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
toast.dismiss(toastId)
|
||||||
|
}
|
||||||
|
}, [opsHybrid, outboxRow, municipalityID, router, reportFailure, setErrorMessage])
|
||||||
|
|
||||||
// Every eligible account (coordinator/advisor/candidate) is listed here
|
// Every eligible account (coordinator/advisor/candidate) is listed here
|
||||||
// regardless of current assignment, so it doubles as the name lookup for an
|
// regardless of current assignment, so it doubles as the name lookup for an
|
||||||
// id the popover just optimistically added — no round trip needed to label
|
// id the popover just optimistically added — no round trip needed to label
|
||||||
|
|
@ -122,11 +193,13 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
|
|
||||||
const toggle = (advisorId: number, assigned: boolean) => {
|
const toggle = (advisorId: number, assigned: boolean) => {
|
||||||
setErrorMessage(null)
|
setErrorMessage(null)
|
||||||
|
let nextIds: number[] = []
|
||||||
setSelectedIDs((current) => {
|
setSelectedIDs((current) => {
|
||||||
const next = new Set(current)
|
const next = new Set(current)
|
||||||
if (assigned) next.add(advisorId)
|
if (assigned) next.add(advisorId)
|
||||||
else next.delete(advisorId)
|
else next.delete(advisorId)
|
||||||
return [...next]
|
nextIds = [...next]
|
||||||
|
return nextIds
|
||||||
})
|
})
|
||||||
setQuery('')
|
setQuery('')
|
||||||
|
|
||||||
|
|
@ -157,6 +230,20 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
if (opsHybrid) {
|
||||||
|
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
|
||||||
|
await enqueueAdvisorsAssignment({
|
||||||
|
municipalityId: municipalityID,
|
||||||
|
advisors: nextIds,
|
||||||
|
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
|
||||||
|
})
|
||||||
|
if (requestSeq > (latestConfirmedRef.current?.seq ?? 0)) {
|
||||||
|
latestConfirmedRef.current = { seq: requestSeq, advisors: nextIds }
|
||||||
|
}
|
||||||
|
finishRequest()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const { ok, payload } = await postCampaignJson<MunicipalityListAdvisorsResponse>(
|
const { ok, payload } = await postCampaignJson<MunicipalityListAdvisorsResponse>(
|
||||||
ADVISORS_ENDPOINT,
|
ADVISORS_ENDPOINT,
|
||||||
{ municipalityId: municipalityID, advisorId, assigned },
|
{ municipalityId: municipalityID, advisorId, assigned },
|
||||||
|
|
@ -181,7 +268,12 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
})()
|
})()
|
||||||
}
|
}
|
||||||
|
|
||||||
const statusMessage = errorMessage ? errorMessage : isPending ? 'Salvando assessores.' : ''
|
const outboxPending = outboxRow?.status === 'pending' || outboxRow?.status === 'conflict'
|
||||||
|
const statusMessage = errorMessage
|
||||||
|
? errorMessage
|
||||||
|
: isPending || outboxPending
|
||||||
|
? 'Salvando assessores.'
|
||||||
|
: ''
|
||||||
// The body pads its own sections (`px-4`, aligned with the Drawer header) so
|
// The body pads its own sections (`px-4`, aligned with the Drawer header) so
|
||||||
// the `Command` can stay full-bleed in both containers — hence `px-0` on the
|
// the `Command` can stay full-bleed in both containers — hence `px-0` on the
|
||||||
// sheet body and `p-0` on the popover content.
|
// sheet body and `p-0` on the popover content.
|
||||||
|
|
@ -197,7 +289,7 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
// The avatar stack reads as initials at best, and an `aria-label` replaces
|
// The avatar stack reads as initials at best, and an `aria-label` replaces
|
||||||
// even those — so who is assigned goes in the label, by extenso.
|
// even those — so who is assigned goes in the label, by extenso.
|
||||||
triggerLabel={`Editar assessores em ${municipalityName} — ${assignedLabel}`}
|
triggerLabel={`Editar assessores em ${municipalityName} — ${assignedLabel}`}
|
||||||
triggerBusy={isPending}
|
triggerBusy={isPending || outboxPending}
|
||||||
statusMessage={statusMessage}
|
statusMessage={statusMessage}
|
||||||
tooltipContent={tooltipContent}
|
tooltipContent={tooltipContent}
|
||||||
contentClassName="w-80 p-0"
|
contentClassName="w-80 p-0"
|
||||||
|
|
@ -212,7 +304,7 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
<p className={cn('text-xs text-muted-foreground', isSheet && 'pr-6')}>
|
<p className={cn('text-xs text-muted-foreground', isSheet && 'pr-6')}>
|
||||||
O assessor vê e gerencia somente os municípios que administra.
|
O assessor vê e gerencia somente os municípios que administra.
|
||||||
</p>
|
</p>
|
||||||
{isPending ? (
|
{isPending || outboxPending ? (
|
||||||
<Spinner
|
<Spinner
|
||||||
className={cn(
|
className={cn(
|
||||||
'absolute size-3.5 text-muted-foreground',
|
'absolute size-3.5 text-muted-foreground',
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@ import { useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
import type { MunicipalityListEngagementLevelResponse } from '@/app/(campaign)/campanha/(app)/municipios/engagement-level/types'
|
import type { MunicipalityListEngagementLevelResponse } from '@/app/(campaign)/campanha/(app)/municipios/engagement-level/types'
|
||||||
import { MunicipalityLevelBadge } from '@/components/campaign/municipality/MunicipalityLevelBadge'
|
import { MunicipalityLevelBadge } from '@/components/campaign/municipality/MunicipalityLevelBadge'
|
||||||
|
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
|
import { enqueueEngagementLevel } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||||
import {
|
import {
|
||||||
CampaignCellEditOverlay,
|
CampaignCellEditOverlay,
|
||||||
type CampaignCellEditOverlayVariant,
|
type CampaignCellEditOverlayVariant,
|
||||||
|
|
@ -17,6 +19,7 @@ import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
||||||
import { Spinner } from '@/components/ui/Spinner'
|
import { Spinner } from '@/components/ui/Spinner'
|
||||||
import { Textarea } from '@/components/ui/textarea'
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
import { postCampaignJson } from '@/lib/campaignJsonRequest'
|
import { postCampaignJson } from '@/lib/campaignJsonRequest'
|
||||||
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
import {
|
import {
|
||||||
EMPTY_ENGAGEMENT_LEVEL_LABEL,
|
EMPTY_ENGAGEMENT_LEVEL_LABEL,
|
||||||
ENGAGEMENT_LEVEL_RULES,
|
ENGAGEMENT_LEVEL_RULES,
|
||||||
|
|
@ -39,6 +42,8 @@ type MunicipalityListLevelControlProps = {
|
||||||
level: EngagementLevel | null
|
level: EngagementLevel | null
|
||||||
levelNote: string | null
|
levelNote: string | null
|
||||||
levelChangedAt: string | null
|
levelChangedAt: string | null
|
||||||
|
/** OH10 — CAS base when OPS_HYBRID outbox path is on. */
|
||||||
|
updatedAt?: string
|
||||||
variant: CampaignCellEditOverlayVariant
|
variant: CampaignCellEditOverlayVariant
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -54,6 +59,7 @@ export const MunicipalityListLevelControl = ({
|
||||||
level,
|
level,
|
||||||
levelNote,
|
levelNote,
|
||||||
levelChangedAt,
|
levelChangedAt,
|
||||||
|
updatedAt,
|
||||||
variant,
|
variant,
|
||||||
}: MunicipalityListLevelControlProps) => {
|
}: MunicipalityListLevelControlProps) => {
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
|
|
@ -164,6 +170,26 @@ export const MunicipalityListLevelControl = ({
|
||||||
setServerBlock(null)
|
setServerBlock(null)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
if (resolveOpsHybridEnabled()) {
|
||||||
|
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
|
||||||
|
await enqueueEngagementLevel({
|
||||||
|
municipalityId: municipalityID,
|
||||||
|
level: draftLevel,
|
||||||
|
note,
|
||||||
|
reversalSignals,
|
||||||
|
triangulatedShock,
|
||||||
|
override,
|
||||||
|
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
|
||||||
|
})
|
||||||
|
setSaved({
|
||||||
|
level: draftLevel,
|
||||||
|
note,
|
||||||
|
changedAt: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
handleOpenChange(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Deliberately ignores the transport's `ok` the way the siblings do not:
|
// Deliberately ignores the transport's `ok` the way the siblings do not:
|
||||||
// `blocked` arrives as a 409 carrying the violations the coordinator may
|
// `blocked` arrives as a 409 carrying the violations the coordinator may
|
||||||
// override, so the status line is not the signal here — the discriminant is.
|
// override, so the status line is not the signal here — the discriminant is.
|
||||||
|
|
|
||||||
|
|
@ -137,6 +137,7 @@ export const MunicipalityListMobileCards = ({
|
||||||
level={municipality.engagementLevel}
|
level={municipality.engagementLevel}
|
||||||
levelNote={municipality.levelNote}
|
levelNote={municipality.levelNote}
|
||||||
levelChangedAt={municipality.levelChangedAt}
|
levelChangedAt={municipality.levelChangedAt}
|
||||||
|
updatedAt={municipality.updatedAt}
|
||||||
variant="sheet"
|
variant="sheet"
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
|
|
@ -156,6 +157,7 @@ export const MunicipalityListMobileCards = ({
|
||||||
municipalityName={municipality.name}
|
municipalityName={municipality.name}
|
||||||
status={municipality.politicalTrendStatus}
|
status={municipality.politicalTrendStatus}
|
||||||
trendNote={municipality.politicalTrendNote}
|
trendNote={municipality.politicalTrendNote}
|
||||||
|
updatedAt={municipality.updatedAt}
|
||||||
variant="sheet"
|
variant="sheet"
|
||||||
/>
|
/>
|
||||||
</dd>
|
</dd>
|
||||||
|
|
@ -186,6 +188,7 @@ export const MunicipalityListMobileCards = ({
|
||||||
isPriority={isPriority}
|
isPriority={isPriority}
|
||||||
advisorNamesById={advisorNamesById}
|
advisorNamesById={advisorNamesById}
|
||||||
options={advisorOptions}
|
options={advisorOptions}
|
||||||
|
updatedAt={municipality.updatedAt}
|
||||||
variant="sheet"
|
variant="sheet"
|
||||||
/>
|
/>
|
||||||
) : names.length ? (
|
) : names.length ? (
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,8 @@ import type {
|
||||||
MunicipalityListPoliticalTrendResponse,
|
MunicipalityListPoliticalTrendResponse,
|
||||||
MunicipalityListSavedPoliticalTrend,
|
MunicipalityListSavedPoliticalTrend,
|
||||||
} from '@/app/(campaign)/campanha/(app)/municipios/political-trend/types'
|
} from '@/app/(campaign)/campanha/(app)/municipios/political-trend/types'
|
||||||
|
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
|
import { enqueuePoliticalTrend } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||||
import {
|
import {
|
||||||
CampaignCellEditOverlay,
|
CampaignCellEditOverlay,
|
||||||
type CampaignCellEditOverlayVariant,
|
type CampaignCellEditOverlayVariant,
|
||||||
|
|
@ -17,6 +19,7 @@ import { Field, FieldLabel } from '@/components/ui/field'
|
||||||
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
||||||
import { Spinner } from '@/components/ui/Spinner'
|
import { Spinner } from '@/components/ui/Spinner'
|
||||||
import { Textarea } from '@/components/ui/textarea'
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
import { parsePoliticalTrendStatusFormValue } from '@/lib/schemas/municipality'
|
import { parsePoliticalTrendStatusFormValue } from '@/lib/schemas/municipality'
|
||||||
import {
|
import {
|
||||||
politicalTrendBadgeVariant,
|
politicalTrendBadgeVariant,
|
||||||
|
|
@ -44,6 +47,8 @@ type MunicipalityListTrendControlProps = {
|
||||||
municipalityName: string
|
municipalityName: string
|
||||||
status: MunicipalityListSavedPoliticalTrend['status']
|
status: MunicipalityListSavedPoliticalTrend['status']
|
||||||
trendNote: string | null
|
trendNote: string | null
|
||||||
|
/** OH10 — CAS base when OPS_HYBRID outbox path is on. */
|
||||||
|
updatedAt?: string
|
||||||
variant: CampaignCellEditOverlayVariant
|
variant: CampaignCellEditOverlayVariant
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -52,8 +57,10 @@ export const MunicipalityListTrendControl = ({
|
||||||
municipalityName,
|
municipalityName,
|
||||||
status,
|
status,
|
||||||
trendNote,
|
trendNote,
|
||||||
|
updatedAt,
|
||||||
variant,
|
variant,
|
||||||
}: MunicipalityListTrendControlProps) => {
|
}: MunicipalityListTrendControlProps) => {
|
||||||
|
const opsHybrid = resolveOpsHybridEnabled()
|
||||||
const { open, onOpenChange, value, change, flush, isPending, errorMessage, statusMessage } =
|
const { open, onOpenChange, value, change, flush, isPending, errorMessage, statusMessage } =
|
||||||
useCampaignCellAutosave<
|
useCampaignCellAutosave<
|
||||||
MunicipalityListSavedPoliticalTrend,
|
MunicipalityListSavedPoliticalTrend,
|
||||||
|
|
@ -73,6 +80,25 @@ export const MunicipalityListTrendControl = ({
|
||||||
readSaved: (payload) => payload.savedTrend,
|
readSaved: (payload) => payload.savedTrend,
|
||||||
errorMessage: SAVE_ERROR_MESSAGE,
|
errorMessage: SAVE_ERROR_MESSAGE,
|
||||||
pendingMessage: 'Salvando tendência.',
|
pendingMessage: 'Salvando tendência.',
|
||||||
|
persist: opsHybrid
|
||||||
|
? async (trend) => {
|
||||||
|
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
|
||||||
|
await enqueuePoliticalTrend({
|
||||||
|
municipalityId: municipalityID,
|
||||||
|
status: trend.status,
|
||||||
|
note: trend.note,
|
||||||
|
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
payload: {
|
||||||
|
status: 'success',
|
||||||
|
message: 'Tendência política registrada.',
|
||||||
|
savedTrend: trend,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
})
|
})
|
||||||
|
|
||||||
// The only state the hook cannot hold: the textarea's raw text, which the
|
// The only state the hook cannot hold: the textarea's raw text, which the
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,25 @@
|
||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useActionState, useState } from 'react'
|
import { useActionState, useState, type FormEvent } from 'react'
|
||||||
|
|
||||||
|
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
|
import { enqueueMunicipalityUpdate } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||||
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
||||||
|
import { Badge } from '@/components/ui/Badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Field, FieldDescription, FieldError, FieldLabel } from '@/components/ui/field'
|
import { Field, FieldDescription, FieldError, FieldLabel } from '@/components/ui/field'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
||||||
import { Spinner } from '@/components/ui/Spinner'
|
import { Spinner } from '@/components/ui/Spinner'
|
||||||
import { Textarea } from '@/components/ui/textarea'
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
import {
|
import {
|
||||||
municipalitySignalTypeDescriptions,
|
municipalitySignalTypeDescriptions,
|
||||||
municipalitySignalTypeLabels,
|
municipalitySignalTypeLabels,
|
||||||
municipalitySignalTypes,
|
municipalitySignalTypes,
|
||||||
municipalityUpdateKindLabels,
|
municipalityUpdateKindLabels,
|
||||||
municipalityUpdateKinds,
|
municipalityUpdateKinds,
|
||||||
|
parseMunicipalitySignalType,
|
||||||
type MunicipalityUpdateKind,
|
type MunicipalityUpdateKind,
|
||||||
} from '@/lib/schemas/municipalityUpdate'
|
} from '@/lib/schemas/municipalityUpdate'
|
||||||
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
||||||
|
|
@ -22,6 +27,9 @@ import { fieldError } from '@/utilities/campaignFormFields'
|
||||||
|
|
||||||
type MunicipalityUpdateFormProps = {
|
type MunicipalityUpdateFormProps = {
|
||||||
municipalityID: number
|
municipalityID: number
|
||||||
|
/** OH10 — parent municipality `updatedAt` for CAS when OPS_HYBRID is on. */
|
||||||
|
municipalityUpdatedAt?: string
|
||||||
|
opsHybridEnabled?: boolean
|
||||||
formAction: (
|
formAction: (
|
||||||
state: CampaignFormActionState,
|
state: CampaignFormActionState,
|
||||||
formData: FormData,
|
formData: FormData,
|
||||||
|
|
@ -30,14 +38,79 @@ type MunicipalityUpdateFormProps = {
|
||||||
|
|
||||||
export const MunicipalityUpdateForm = ({
|
export const MunicipalityUpdateForm = ({
|
||||||
municipalityID,
|
municipalityID,
|
||||||
|
municipalityUpdatedAt,
|
||||||
|
opsHybridEnabled = resolveOpsHybridEnabled(),
|
||||||
formAction,
|
formAction,
|
||||||
}: MunicipalityUpdateFormProps) => {
|
}: MunicipalityUpdateFormProps) => {
|
||||||
const [state, submitAction, isPending] = useActionState(formAction, {})
|
const [state, submitAction, isPending] = useActionState(formAction, {})
|
||||||
const [kind, setKind] = useState<MunicipalityUpdateKind>('semanal')
|
const [kind, setKind] = useState<MunicipalityUpdateKind>('semanal')
|
||||||
|
const [hybridPending, setHybridPending] = useState(false)
|
||||||
|
const [hybridMessage, setHybridMessage] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const onHybridSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault()
|
||||||
|
const form = event.currentTarget
|
||||||
|
const data = new FormData(form)
|
||||||
|
const rawKind = data.get('kind')
|
||||||
|
const nextKind =
|
||||||
|
typeof rawKind === 'string' &&
|
||||||
|
municipalityUpdateKinds.includes(rawKind as MunicipalityUpdateKind)
|
||||||
|
? (rawKind as MunicipalityUpdateKind)
|
||||||
|
: 'semanal'
|
||||||
|
const readText = (name: string) => {
|
||||||
|
const raw = data.get(name)
|
||||||
|
return typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : undefined
|
||||||
|
}
|
||||||
|
const readCount = (name: string) => {
|
||||||
|
const raw = data.get(name)
|
||||||
|
if (typeof raw !== 'string' || raw.trim() === '') return undefined
|
||||||
|
const value = Number(raw)
|
||||||
|
return Number.isFinite(value) ? Math.trunc(value) : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
setHybridPending(true)
|
||||||
|
setHybridMessage(null)
|
||||||
|
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
|
||||||
|
void enqueueMunicipalityUpdate({
|
||||||
|
clientId: crypto.randomUUID(),
|
||||||
|
municipalityId: municipalityID,
|
||||||
|
kind: nextKind,
|
||||||
|
worked: readText('worked'),
|
||||||
|
failed: readText('failed'),
|
||||||
|
needs: readText('needs'),
|
||||||
|
body: readText('body'),
|
||||||
|
activeVolunteers: readCount('activeVolunteers'),
|
||||||
|
newSupports: readCount('newSupports'),
|
||||||
|
signalType: parseMunicipalitySignalType(readText('signalType')),
|
||||||
|
baseUpdatedAt: mirrorUpdatedAt ?? municipalityUpdatedAt,
|
||||||
|
}).then(
|
||||||
|
() => {
|
||||||
|
setHybridPending(false)
|
||||||
|
setHybridMessage('Atualização enfileirada. Será enviada ao reconectar.')
|
||||||
|
form.reset()
|
||||||
|
setKind('semanal')
|
||||||
|
},
|
||||||
|
(error: unknown) => {
|
||||||
|
setHybridPending(false)
|
||||||
|
setHybridMessage(
|
||||||
|
error instanceof Error ? error.message : 'Não foi possível enfileirar a atualização.',
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const pending = opsHybridEnabled ? hybridPending : isPending
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form action={submitAction} className="flex flex-col gap-4 rounded-xl border p-4">
|
<form
|
||||||
<h3 className="text-base font-medium">Registrar atualização</h3>
|
action={opsHybridEnabled ? undefined : submitAction}
|
||||||
|
onSubmit={opsHybridEnabled ? onHybridSubmit : undefined}
|
||||||
|
className="flex flex-col gap-4 rounded-xl border p-4"
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<h3 className="text-base font-medium">Registrar atualização</h3>
|
||||||
|
{hybridPending ? <Badge variant="estimate-pending">Pendente</Badge> : null}
|
||||||
|
</div>
|
||||||
<input type="hidden" name="municipalityId" value={municipalityID} />
|
<input type="hidden" name="municipalityId" value={municipalityID} />
|
||||||
<Field>
|
<Field>
|
||||||
<FieldLabel htmlFor="municipality-update-kind">Tipo</FieldLabel>
|
<FieldLabel htmlFor="municipality-update-kind">Tipo</FieldLabel>
|
||||||
|
|
@ -149,9 +222,15 @@ export const MunicipalityUpdateForm = ({
|
||||||
) : null}
|
) : null}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<CampaignFormActionMessage state={state} successFallbackMessage="Atualização registrada." />
|
{!opsHybridEnabled ? (
|
||||||
<Button type="submit" disabled={isPending} className="min-h-11 self-start">
|
<CampaignFormActionMessage state={state} successFallbackMessage="Atualização registrada." />
|
||||||
{isPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
) : hybridMessage ? (
|
||||||
|
<p className="text-sm text-muted-foreground" aria-live="polite">
|
||||||
|
{hybridMessage}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
<Button type="submit" disabled={pending} className="min-h-11 self-start">
|
||||||
|
{pending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
||||||
Registrar atualização
|
Registrar atualização
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import {
|
||||||
type OpsMirrorPersistenceMode,
|
type OpsMirrorPersistenceMode,
|
||||||
type OpsMirrorStore,
|
type OpsMirrorStore,
|
||||||
} from '@/components/campaign/opsSync/opsMirrorPersistence'
|
} from '@/components/campaign/opsSync/opsMirrorPersistence'
|
||||||
|
import { collectOpsMunicipalityOutboxKeys } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||||
import { votePledgesCollection } from '@/components/campaign/opsSync/opsVotePledgeMirror'
|
import { votePledgesCollection } from '@/components/campaign/opsSync/opsVotePledgeMirror'
|
||||||
import {
|
import {
|
||||||
createEmptyOpsSnapshot,
|
createEmptyOpsSnapshot,
|
||||||
|
|
@ -123,7 +124,9 @@ export const resetOpsMirrorClientForTests = async (): Promise<void> => {
|
||||||
|
|
||||||
const resolveOutboxKeys = (explicit?: ReadonlySet<OpsOutboxKey>): ReadonlySet<OpsOutboxKey> => {
|
const resolveOutboxKeys = (explicit?: ReadonlySet<OpsOutboxKey>): ReadonlySet<OpsOutboxKey> => {
|
||||||
if (explicit) return explicit
|
if (explicit) return explicit
|
||||||
return collectOpsEstimateOutboxKeys()
|
const keys = collectOpsEstimateOutboxKeys()
|
||||||
|
for (const key of collectOpsMunicipalityOutboxKeys()) keys.add(key)
|
||||||
|
return keys
|
||||||
}
|
}
|
||||||
|
|
||||||
const persistMirrorSnapshot = async (
|
const persistMirrorSnapshot = async (
|
||||||
|
|
|
||||||
656
src/components/campaign/opsSync/opsMunicipalityOutbox.ts
Normal file
656
src/components/campaign/opsSync/opsMunicipalityOutbox.ts
Normal file
|
|
@ -0,0 +1,656 @@
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
|
||||||
|
import {
|
||||||
|
IndexedDBAdapter,
|
||||||
|
NonRetriableError,
|
||||||
|
startOfflineExecutor,
|
||||||
|
type OfflineExecutor,
|
||||||
|
} from '@tanstack/offline-transactions'
|
||||||
|
|
||||||
|
import {
|
||||||
|
assignMunicipalityAdvisorsCas,
|
||||||
|
setMunicipalityEngagementLevelCas,
|
||||||
|
setMunicipalityPoliticalTrendCas,
|
||||||
|
} from '@/app/(campaign)/campanha/actions/municipality'
|
||||||
|
import { createMunicipalityUpdateCas } from '@/app/(campaign)/campanha/actions/municipalityUpdate'
|
||||||
|
import { declareVotesCas } from '@/app/(campaign)/campanha/actions/votePledge'
|
||||||
|
import {
|
||||||
|
collapseAdvisorsOutbox,
|
||||||
|
collapseDeclareVotesOutbox,
|
||||||
|
collapseEngagementLevelOutbox,
|
||||||
|
collapseMunicipalityUpdateOutbox,
|
||||||
|
collapsePoliticalTrendOutbox,
|
||||||
|
declareVotesOutboxKey,
|
||||||
|
type OpsAdvisorsOutboxRow,
|
||||||
|
type OpsDeclareVotesOutboxRow,
|
||||||
|
type OpsEngagementLevelOutboxRow,
|
||||||
|
type OpsMunicipalityUpdateOutboxRow,
|
||||||
|
type OpsPoliticalTrendOutboxRow,
|
||||||
|
} from '@/components/campaign/opsSync/opsMunicipalityOutboxModel'
|
||||||
|
import {
|
||||||
|
applyOpsVotePledgeEstimateWrite,
|
||||||
|
votePledgesCollection,
|
||||||
|
} from '@/components/campaign/opsSync/opsVotePledgeMirror'
|
||||||
|
import { opsOutboxKey, type OpsOutboxKey } from '@/lib/campaignOps/opsContract'
|
||||||
|
import type { EngagementLevel } from '@/lib/engagementLevel'
|
||||||
|
import type { PoliticalTrendStatusValue } from '@/lib/schemas/municipality'
|
||||||
|
import type {
|
||||||
|
MunicipalitySignalType,
|
||||||
|
MunicipalityUpdateKind,
|
||||||
|
} from '@/lib/schemas/municipalityUpdate'
|
||||||
|
import {
|
||||||
|
isOpsUpdatedAtConflictMessage,
|
||||||
|
parseOpsUpdatedAtConflictServerUpdatedAt,
|
||||||
|
} from '@/lib/schemas/opsCas'
|
||||||
|
|
||||||
|
const DECLARE_MUTATION_FN = 'declareVotes'
|
||||||
|
const MUNICIPALITY_UPDATE_MUTATION_FN = 'createMunicipalityUpdate'
|
||||||
|
const TREND_MUTATION_FN = 'setPoliticalTrend'
|
||||||
|
const ENGAGEMENT_MUTATION_FN = 'setEngagementLevel'
|
||||||
|
const ADVISORS_MUTATION_FN = 'assignAdvisors'
|
||||||
|
|
||||||
|
const declareVotesOutboxCollection = createCollection(
|
||||||
|
localOnlyCollectionOptions<OpsDeclareVotesOutboxRow, string>({
|
||||||
|
id: 'ops-declare-votes-outbox',
|
||||||
|
getKey: (row) => row.id,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const municipalityUpdateOutboxCollection = createCollection(
|
||||||
|
localOnlyCollectionOptions<OpsMunicipalityUpdateOutboxRow, string>({
|
||||||
|
id: 'ops-municipality-update-outbox',
|
||||||
|
getKey: (row) => row.id,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const politicalTrendOutboxCollection = createCollection(
|
||||||
|
localOnlyCollectionOptions<OpsPoliticalTrendOutboxRow, number>({
|
||||||
|
id: 'ops-political-trend-outbox',
|
||||||
|
getKey: (row) => row.municipalityId,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const engagementLevelOutboxCollection = createCollection(
|
||||||
|
localOnlyCollectionOptions<OpsEngagementLevelOutboxRow, number>({
|
||||||
|
id: 'ops-engagement-level-outbox',
|
||||||
|
getKey: (row) => row.municipalityId,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const advisorsOutboxCollection = createCollection(
|
||||||
|
localOnlyCollectionOptions<OpsAdvisorsOutboxRow, number>({
|
||||||
|
id: 'ops-advisors-outbox',
|
||||||
|
getKey: (row) => row.municipalityId,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
let executorSingleton: OfflineExecutor | null = null
|
||||||
|
let initPromise: Promise<OfflineExecutor> | null = null
|
||||||
|
|
||||||
|
const collapseAllMunicipalityOutbox = (
|
||||||
|
transactions: Parameters<typeof collapseDeclareVotesOutbox>[0],
|
||||||
|
) => {
|
||||||
|
const byFn = new Map<string, typeof transactions>()
|
||||||
|
for (const transaction of transactions) {
|
||||||
|
const fn = transaction.mutationFnName ?? ''
|
||||||
|
const list = byFn.get(fn) ?? []
|
||||||
|
list.push(transaction)
|
||||||
|
byFn.set(fn, list)
|
||||||
|
}
|
||||||
|
|
||||||
|
const collapsed = [
|
||||||
|
...(byFn.get(DECLARE_MUTATION_FN)
|
||||||
|
? collapseDeclareVotesOutbox(byFn.get(DECLARE_MUTATION_FN)!)
|
||||||
|
: []),
|
||||||
|
...(byFn.get(MUNICIPALITY_UPDATE_MUTATION_FN)
|
||||||
|
? collapseMunicipalityUpdateOutbox(byFn.get(MUNICIPALITY_UPDATE_MUTATION_FN)!)
|
||||||
|
: []),
|
||||||
|
...(byFn.get(TREND_MUTATION_FN)
|
||||||
|
? collapsePoliticalTrendOutbox(byFn.get(TREND_MUTATION_FN)!)
|
||||||
|
: []),
|
||||||
|
...(byFn.get(ENGAGEMENT_MUTATION_FN)
|
||||||
|
? collapseEngagementLevelOutbox(byFn.get(ENGAGEMENT_MUTATION_FN)!)
|
||||||
|
: []),
|
||||||
|
...(byFn.get(ADVISORS_MUTATION_FN)
|
||||||
|
? collapseAdvisorsOutbox(byFn.get(ADVISORS_MUTATION_FN)!)
|
||||||
|
: []),
|
||||||
|
]
|
||||||
|
|
||||||
|
for (const [fn, list] of byFn) {
|
||||||
|
if (
|
||||||
|
fn !== DECLARE_MUTATION_FN &&
|
||||||
|
fn !== MUNICIPALITY_UPDATE_MUTATION_FN &&
|
||||||
|
fn !== TREND_MUTATION_FN &&
|
||||||
|
fn !== ENGAGEMENT_MUTATION_FN &&
|
||||||
|
fn !== ADVISORS_MUTATION_FN
|
||||||
|
) {
|
||||||
|
collapsed.push(...list)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return collapsed.sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime())
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleUpdatedAtConflict = (
|
||||||
|
message: string,
|
||||||
|
onConflict: (serverUpdatedAt: string | null) => void,
|
||||||
|
): never => {
|
||||||
|
onConflict(parseOpsUpdatedAtConflictServerUpdatedAt(message))
|
||||||
|
throw new NonRetriableError(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
const createMunicipalityOfflineExecutor = (): OfflineExecutor =>
|
||||||
|
startOfflineExecutor({
|
||||||
|
collections: {
|
||||||
|
declareVotesOutbox: declareVotesOutboxCollection,
|
||||||
|
municipalityUpdateOutbox: municipalityUpdateOutboxCollection,
|
||||||
|
politicalTrendOutbox: politicalTrendOutboxCollection,
|
||||||
|
engagementLevelOutbox: engagementLevelOutboxCollection,
|
||||||
|
advisorsOutbox: advisorsOutboxCollection,
|
||||||
|
},
|
||||||
|
storage: new IndexedDBAdapter('teqo-ops-municipality', 'outbox'),
|
||||||
|
beforeRetry: collapseAllMunicipalityOutbox,
|
||||||
|
mutationFns: {
|
||||||
|
[DECLARE_MUTATION_FN]: async ({ transaction }) => {
|
||||||
|
const mutation = transaction.mutations[0]
|
||||||
|
if (!mutation) throw new NonRetriableError('Mutação de declaração vazia.')
|
||||||
|
const row = mutation.modified as OpsDeclareVotesOutboxRow
|
||||||
|
try {
|
||||||
|
const updated = await declareVotesCas({
|
||||||
|
municipality: row.municipalityId,
|
||||||
|
leadership: row.leadershipId,
|
||||||
|
declaredVotes: row.declaredVotes,
|
||||||
|
baseUpdatedAt: row.baseUpdatedAt,
|
||||||
|
})
|
||||||
|
applyOpsVotePledgeEstimateWrite(updated)
|
||||||
|
declareVotesOutboxCollection.utils.acceptMutations(transaction)
|
||||||
|
if (declareVotesOutboxCollection.has(row.id)) {
|
||||||
|
declareVotesOutboxCollection.delete(row.id)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
if (isOpsUpdatedAtConflictMessage(message)) {
|
||||||
|
handleUpdatedAtConflict(message, (serverUpdatedAt) => {
|
||||||
|
if (declareVotesOutboxCollection.has(row.id)) {
|
||||||
|
declareVotesOutboxCollection.update(row.id, (draft) => {
|
||||||
|
draft.status = 'conflict'
|
||||||
|
draft.serverUpdatedAt = serverUpdatedAt
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (declareVotesOutboxCollection.has(row.id)) {
|
||||||
|
declareVotesOutboxCollection.update(row.id, (draft) => {
|
||||||
|
draft.status = 'error'
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[MUNICIPALITY_UPDATE_MUTATION_FN]: async ({ transaction }) => {
|
||||||
|
const mutation = transaction.mutations[0]
|
||||||
|
if (!mutation) throw new NonRetriableError('Mutação de atualização vazia.')
|
||||||
|
const row = mutation.modified as OpsMunicipalityUpdateOutboxRow
|
||||||
|
try {
|
||||||
|
await createMunicipalityUpdateCas({
|
||||||
|
municipality: row.municipalityId,
|
||||||
|
kind: row.kind,
|
||||||
|
worked: row.worked,
|
||||||
|
failed: row.failed,
|
||||||
|
needs: row.needs,
|
||||||
|
body: row.body,
|
||||||
|
activeVolunteers: row.activeVolunteers,
|
||||||
|
newSupports: row.newSupports,
|
||||||
|
signalType: row.signalType,
|
||||||
|
baseUpdatedAt: row.baseUpdatedAt,
|
||||||
|
})
|
||||||
|
municipalityUpdateOutboxCollection.utils.acceptMutations(transaction)
|
||||||
|
if (municipalityUpdateOutboxCollection.has(row.id)) {
|
||||||
|
municipalityUpdateOutboxCollection.delete(row.id)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
if (isOpsUpdatedAtConflictMessage(message)) {
|
||||||
|
handleUpdatedAtConflict(message, (serverUpdatedAt) => {
|
||||||
|
if (municipalityUpdateOutboxCollection.has(row.id)) {
|
||||||
|
municipalityUpdateOutboxCollection.update(row.id, (draft) => {
|
||||||
|
draft.status = 'conflict'
|
||||||
|
draft.serverUpdatedAt = serverUpdatedAt
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (municipalityUpdateOutboxCollection.has(row.id)) {
|
||||||
|
municipalityUpdateOutboxCollection.update(row.id, (draft) => {
|
||||||
|
draft.status = 'error'
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[TREND_MUTATION_FN]: async ({ transaction }) => {
|
||||||
|
const mutation = transaction.mutations[0]
|
||||||
|
if (!mutation) throw new NonRetriableError('Mutação de tendência vazia.')
|
||||||
|
const row = mutation.modified as OpsPoliticalTrendOutboxRow
|
||||||
|
try {
|
||||||
|
await setMunicipalityPoliticalTrendCas({
|
||||||
|
municipality: row.municipalityId,
|
||||||
|
status: row.status,
|
||||||
|
note: row.note,
|
||||||
|
baseUpdatedAt: row.baseUpdatedAt,
|
||||||
|
})
|
||||||
|
politicalTrendOutboxCollection.utils.acceptMutations(transaction)
|
||||||
|
if (politicalTrendOutboxCollection.has(row.municipalityId)) {
|
||||||
|
politicalTrendOutboxCollection.delete(row.municipalityId)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
if (isOpsUpdatedAtConflictMessage(message)) {
|
||||||
|
handleUpdatedAtConflict(message, (serverUpdatedAt) => {
|
||||||
|
if (politicalTrendOutboxCollection.has(row.municipalityId)) {
|
||||||
|
politicalTrendOutboxCollection.update(row.municipalityId, (draft) => {
|
||||||
|
draft.statusSync = 'conflict'
|
||||||
|
draft.serverUpdatedAt = serverUpdatedAt
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (politicalTrendOutboxCollection.has(row.municipalityId)) {
|
||||||
|
politicalTrendOutboxCollection.update(row.municipalityId, (draft) => {
|
||||||
|
draft.statusSync = 'error'
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[ENGAGEMENT_MUTATION_FN]: async ({ transaction }) => {
|
||||||
|
const mutation = transaction.mutations[0]
|
||||||
|
if (!mutation) throw new NonRetriableError('Mutação de nível vazia.')
|
||||||
|
const row = mutation.modified as OpsEngagementLevelOutboxRow
|
||||||
|
try {
|
||||||
|
await setMunicipalityEngagementLevelCas({
|
||||||
|
municipality: row.municipalityId,
|
||||||
|
level: row.level,
|
||||||
|
note: row.note,
|
||||||
|
reversalSignals: row.reversalSignals,
|
||||||
|
triangulatedShock: row.triangulatedShock,
|
||||||
|
override: row.override,
|
||||||
|
baseUpdatedAt: row.baseUpdatedAt,
|
||||||
|
})
|
||||||
|
engagementLevelOutboxCollection.utils.acceptMutations(transaction)
|
||||||
|
if (engagementLevelOutboxCollection.has(row.municipalityId)) {
|
||||||
|
engagementLevelOutboxCollection.delete(row.municipalityId)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
if (isOpsUpdatedAtConflictMessage(message)) {
|
||||||
|
handleUpdatedAtConflict(message, (serverUpdatedAt) => {
|
||||||
|
if (engagementLevelOutboxCollection.has(row.municipalityId)) {
|
||||||
|
engagementLevelOutboxCollection.update(row.municipalityId, (draft) => {
|
||||||
|
draft.status = 'conflict'
|
||||||
|
draft.serverUpdatedAt = serverUpdatedAt
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (engagementLevelOutboxCollection.has(row.municipalityId)) {
|
||||||
|
engagementLevelOutboxCollection.update(row.municipalityId, (draft) => {
|
||||||
|
draft.status = 'error'
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[ADVISORS_MUTATION_FN]: async ({ transaction }) => {
|
||||||
|
const mutation = transaction.mutations[0]
|
||||||
|
if (!mutation) throw new NonRetriableError('Mutação de assessores vazia.')
|
||||||
|
const row = mutation.modified as OpsAdvisorsOutboxRow
|
||||||
|
try {
|
||||||
|
await assignMunicipalityAdvisorsCas({
|
||||||
|
municipality: row.municipalityId,
|
||||||
|
advisors: row.advisors,
|
||||||
|
baseUpdatedAt: row.baseUpdatedAt,
|
||||||
|
})
|
||||||
|
advisorsOutboxCollection.utils.acceptMutations(transaction)
|
||||||
|
if (advisorsOutboxCollection.has(row.municipalityId)) {
|
||||||
|
advisorsOutboxCollection.delete(row.municipalityId)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
if (isOpsUpdatedAtConflictMessage(message)) {
|
||||||
|
handleUpdatedAtConflict(message, (serverUpdatedAt) => {
|
||||||
|
if (advisorsOutboxCollection.has(row.municipalityId)) {
|
||||||
|
advisorsOutboxCollection.update(row.municipalityId, (draft) => {
|
||||||
|
draft.status = 'conflict'
|
||||||
|
draft.serverUpdatedAt = serverUpdatedAt
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (advisorsOutboxCollection.has(row.municipalityId)) {
|
||||||
|
advisorsOutboxCollection.update(row.municipalityId, (draft) => {
|
||||||
|
draft.status = 'error'
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const getOpsMunicipalityOfflineExecutor = async (): Promise<OfflineExecutor> => {
|
||||||
|
if (executorSingleton) {
|
||||||
|
await executorSingleton.waitForInit()
|
||||||
|
return executorSingleton
|
||||||
|
}
|
||||||
|
if (!initPromise) {
|
||||||
|
initPromise = (async () => {
|
||||||
|
const executor = createMunicipalityOfflineExecutor()
|
||||||
|
await executor.waitForInit()
|
||||||
|
executorSingleton = executor
|
||||||
|
return executor
|
||||||
|
})()
|
||||||
|
}
|
||||||
|
return initPromise
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueueDeclareVotes = async (input: {
|
||||||
|
municipalityId: number
|
||||||
|
leadershipId: number
|
||||||
|
declaredVotes: number
|
||||||
|
pledgeId?: number
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsMunicipalityOfflineExecutor()
|
||||||
|
const id = declareVotesOutboxKey(input.leadershipId, input.municipalityId)
|
||||||
|
const mirrorPledge =
|
||||||
|
input.pledgeId !== undefined
|
||||||
|
? votePledgesCollection.get(input.pledgeId)
|
||||||
|
: votePledgesCollection.toArray.find(
|
||||||
|
(row) =>
|
||||||
|
row.leadership === input.leadershipId && row.municipality === input.municipalityId,
|
||||||
|
)
|
||||||
|
const pledgeId = input.pledgeId ?? mirrorPledge?.id
|
||||||
|
const baseUpdatedAt =
|
||||||
|
input.baseUpdatedAt !== undefined ? input.baseUpdatedAt : (mirrorPledge?.updatedAt ?? null)
|
||||||
|
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: DECLARE_MUTATION_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsDeclareVotesOutboxRow = {
|
||||||
|
id,
|
||||||
|
municipalityId: variables.municipalityId,
|
||||||
|
leadershipId: variables.leadershipId,
|
||||||
|
pledgeId,
|
||||||
|
declaredVotes: variables.declaredVotes,
|
||||||
|
baseUpdatedAt: variables.baseUpdatedAt ?? baseUpdatedAt,
|
||||||
|
status: 'pending',
|
||||||
|
}
|
||||||
|
if (pledgeId !== undefined && votePledgesCollection.has(pledgeId)) {
|
||||||
|
votePledgesCollection.update(pledgeId, (draft) => {
|
||||||
|
draft.declaredVotes = variables.declaredVotes
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (declareVotesOutboxCollection.has(id)) {
|
||||||
|
declareVotesOutboxCollection.update(id, (draft) => {
|
||||||
|
draft.declaredVotes = next.declaredVotes
|
||||||
|
draft.pledgeId = next.pledgeId
|
||||||
|
draft.baseUpdatedAt = next.baseUpdatedAt
|
||||||
|
draft.status = 'pending'
|
||||||
|
draft.serverUpdatedAt = undefined
|
||||||
|
draft.errorMessage = undefined
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
declareVotesOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run({ ...input, baseUpdatedAt, pledgeId })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueueMunicipalityUpdate = async (input: {
|
||||||
|
clientId: string
|
||||||
|
municipalityId: number
|
||||||
|
kind: MunicipalityUpdateKind
|
||||||
|
worked?: string
|
||||||
|
failed?: string
|
||||||
|
needs?: string
|
||||||
|
body?: string
|
||||||
|
activeVolunteers?: number
|
||||||
|
newSupports?: number
|
||||||
|
signalType?: MunicipalitySignalType
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsMunicipalityOfflineExecutor()
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: MUNICIPALITY_UPDATE_MUTATION_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsMunicipalityUpdateOutboxRow = {
|
||||||
|
id: variables.clientId,
|
||||||
|
municipalityId: variables.municipalityId,
|
||||||
|
kind: variables.kind,
|
||||||
|
worked: variables.worked,
|
||||||
|
failed: variables.failed,
|
||||||
|
needs: variables.needs,
|
||||||
|
body: variables.body,
|
||||||
|
activeVolunteers: variables.activeVolunteers,
|
||||||
|
newSupports: variables.newSupports,
|
||||||
|
signalType: variables.signalType,
|
||||||
|
baseUpdatedAt: variables.baseUpdatedAt,
|
||||||
|
status: 'pending',
|
||||||
|
}
|
||||||
|
if (municipalityUpdateOutboxCollection.has(next.id)) {
|
||||||
|
municipalityUpdateOutboxCollection.update(next.id, (draft) => {
|
||||||
|
Object.assign(draft, next)
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
municipalityUpdateOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueuePoliticalTrend = async (input: {
|
||||||
|
municipalityId: number
|
||||||
|
status: PoliticalTrendStatusValue | null
|
||||||
|
note: string | null
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsMunicipalityOfflineExecutor()
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: TREND_MUTATION_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsPoliticalTrendOutboxRow = {
|
||||||
|
municipalityId: variables.municipalityId,
|
||||||
|
status: variables.status,
|
||||||
|
note: variables.note,
|
||||||
|
baseUpdatedAt: variables.baseUpdatedAt,
|
||||||
|
statusSync: 'pending',
|
||||||
|
}
|
||||||
|
if (politicalTrendOutboxCollection.has(variables.municipalityId)) {
|
||||||
|
politicalTrendOutboxCollection.update(variables.municipalityId, (draft) => {
|
||||||
|
draft.status = next.status
|
||||||
|
draft.note = next.note
|
||||||
|
draft.baseUpdatedAt = next.baseUpdatedAt
|
||||||
|
draft.statusSync = 'pending'
|
||||||
|
draft.serverUpdatedAt = undefined
|
||||||
|
draft.errorMessage = undefined
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
politicalTrendOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueueEngagementLevel = async (input: {
|
||||||
|
municipalityId: number
|
||||||
|
level: EngagementLevel
|
||||||
|
note: string
|
||||||
|
reversalSignals: string
|
||||||
|
triangulatedShock: boolean
|
||||||
|
override: boolean
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsMunicipalityOfflineExecutor()
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: ENGAGEMENT_MUTATION_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsEngagementLevelOutboxRow = {
|
||||||
|
municipalityId: variables.municipalityId,
|
||||||
|
level: variables.level,
|
||||||
|
note: variables.note,
|
||||||
|
reversalSignals: variables.reversalSignals,
|
||||||
|
triangulatedShock: variables.triangulatedShock,
|
||||||
|
override: variables.override,
|
||||||
|
baseUpdatedAt: variables.baseUpdatedAt,
|
||||||
|
status: 'pending',
|
||||||
|
}
|
||||||
|
if (engagementLevelOutboxCollection.has(variables.municipalityId)) {
|
||||||
|
engagementLevelOutboxCollection.update(variables.municipalityId, (draft) => {
|
||||||
|
Object.assign(draft, next)
|
||||||
|
draft.serverUpdatedAt = undefined
|
||||||
|
draft.errorMessage = undefined
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
engagementLevelOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueueAdvisorsAssignment = async (input: {
|
||||||
|
municipalityId: number
|
||||||
|
advisors: number[]
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsMunicipalityOfflineExecutor()
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: ADVISORS_MUTATION_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsAdvisorsOutboxRow = {
|
||||||
|
municipalityId: variables.municipalityId,
|
||||||
|
advisors: variables.advisors,
|
||||||
|
baseUpdatedAt: variables.baseUpdatedAt,
|
||||||
|
status: 'pending',
|
||||||
|
}
|
||||||
|
if (advisorsOutboxCollection.has(variables.municipalityId)) {
|
||||||
|
advisorsOutboxCollection.update(variables.municipalityId, (draft) => {
|
||||||
|
draft.advisors = next.advisors
|
||||||
|
draft.baseUpdatedAt = next.baseUpdatedAt
|
||||||
|
draft.status = 'pending'
|
||||||
|
draft.serverUpdatedAt = undefined
|
||||||
|
draft.errorMessage = undefined
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
advisorsOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const collectOpsMunicipalityOutboxKeys = (): Set<OpsOutboxKey> => {
|
||||||
|
const keys = new Set<OpsOutboxKey>()
|
||||||
|
for (const row of declareVotesOutboxCollection.toArray) {
|
||||||
|
if (row.status === 'pending' || row.status === 'conflict') {
|
||||||
|
if (row.pledgeId !== undefined) {
|
||||||
|
keys.add(opsOutboxKey('votePledges', row.pledgeId))
|
||||||
|
} else {
|
||||||
|
const pledge = votePledgesCollection.toArray.find(
|
||||||
|
(p) => p.leadership === row.leadershipId && p.municipality === row.municipalityId,
|
||||||
|
)
|
||||||
|
if (pledge) keys.add(opsOutboxKey('votePledges', pledge.id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of municipalityUpdateOutboxCollection.toArray) {
|
||||||
|
if (row.status === 'pending' || row.status === 'conflict') {
|
||||||
|
keys.add(opsOutboxKey('municipalities', row.municipalityId))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of politicalTrendOutboxCollection.toArray) {
|
||||||
|
if (row.statusSync === 'pending' || row.statusSync === 'conflict') {
|
||||||
|
keys.add(opsOutboxKey('municipalities', row.municipalityId))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of engagementLevelOutboxCollection.toArray) {
|
||||||
|
if (row.status === 'pending' || row.status === 'conflict') {
|
||||||
|
keys.add(opsOutboxKey('municipalities', row.municipalityId))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of advisorsOutboxCollection.toArray) {
|
||||||
|
if (row.status === 'pending' || row.status === 'conflict') {
|
||||||
|
keys.add(opsOutboxKey('municipalities', row.municipalityId))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return keys
|
||||||
|
}
|
||||||
|
|
||||||
|
export const readOpsDeclareVotesOutboxRow = (
|
||||||
|
leadershipId: number,
|
||||||
|
municipalityId: number,
|
||||||
|
): OpsDeclareVotesOutboxRow | undefined =>
|
||||||
|
declareVotesOutboxCollection.get(declareVotesOutboxKey(leadershipId, municipalityId))
|
||||||
|
|
||||||
|
export const subscribeOpsDeclareVotesOutboxRow = (
|
||||||
|
leadershipId: number,
|
||||||
|
municipalityId: number,
|
||||||
|
onStoreChange: () => void,
|
||||||
|
): (() => void) => {
|
||||||
|
const id = declareVotesOutboxKey(leadershipId, municipalityId)
|
||||||
|
let previous = declareVotesOutboxCollection.get(id)
|
||||||
|
const subscription = declareVotesOutboxCollection.subscribeChanges(() => {
|
||||||
|
const next = declareVotesOutboxCollection.get(id)
|
||||||
|
if (next === previous) return
|
||||||
|
previous = next
|
||||||
|
onStoreChange()
|
||||||
|
})
|
||||||
|
return () => subscription.unsubscribe()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const discardOpsDeclareVotesOutboxRow = (
|
||||||
|
leadershipId: number,
|
||||||
|
municipalityId: number,
|
||||||
|
): void => {
|
||||||
|
const id = declareVotesOutboxKey(leadershipId, municipalityId)
|
||||||
|
if (declareVotesOutboxCollection.has(id)) declareVotesOutboxCollection.delete(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const readOpsAdvisorsOutboxRow = (
|
||||||
|
municipalityId: number,
|
||||||
|
): OpsAdvisorsOutboxRow | undefined => advisorsOutboxCollection.get(municipalityId)
|
||||||
|
|
||||||
|
export const subscribeOpsAdvisorsOutboxRow = (
|
||||||
|
municipalityId: number,
|
||||||
|
onStoreChange: () => void,
|
||||||
|
): (() => void) => {
|
||||||
|
let previous = advisorsOutboxCollection.get(municipalityId)
|
||||||
|
const subscription = advisorsOutboxCollection.subscribeChanges(() => {
|
||||||
|
const next = advisorsOutboxCollection.get(municipalityId)
|
||||||
|
if (next === previous) return
|
||||||
|
previous = next
|
||||||
|
onStoreChange()
|
||||||
|
})
|
||||||
|
return () => subscription.unsubscribe()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const discardOpsAdvisorsOutboxRow = (municipalityId: number): void => {
|
||||||
|
if (advisorsOutboxCollection.has(municipalityId)) {
|
||||||
|
advisorsOutboxCollection.delete(municipalityId)
|
||||||
|
}
|
||||||
|
}
|
||||||
119
src/components/campaign/opsSync/opsMunicipalityOutboxModel.ts
Normal file
119
src/components/campaign/opsSync/opsMunicipalityOutboxModel.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
||||||
|
import type { OfflineTransaction } from '@tanstack/offline-transactions'
|
||||||
|
|
||||||
|
import type { EngagementLevel } from '@/lib/engagementLevel'
|
||||||
|
import type { PoliticalTrendStatusValue } from '@/lib/schemas/municipality'
|
||||||
|
import type {
|
||||||
|
MunicipalitySignalType,
|
||||||
|
MunicipalityUpdateKind,
|
||||||
|
} from '@/lib/schemas/municipalityUpdate'
|
||||||
|
|
||||||
|
export type OpsMunicipalityWriteSyncStatus = 'pending' | 'synced' | 'conflict' | 'error'
|
||||||
|
|
||||||
|
export type OpsDeclareVotesOutboxRow = {
|
||||||
|
id: string
|
||||||
|
municipalityId: number
|
||||||
|
leadershipId: number
|
||||||
|
/** Mirror pledge id when known — avoids O(n) lookup in collectOutboxKeys. */
|
||||||
|
pledgeId?: number
|
||||||
|
declaredVotes: number
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
status: OpsMunicipalityWriteSyncStatus
|
||||||
|
serverUpdatedAt?: string | null
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OpsMunicipalityUpdateOutboxRow = {
|
||||||
|
id: string
|
||||||
|
municipalityId: number
|
||||||
|
kind: MunicipalityUpdateKind
|
||||||
|
worked?: string
|
||||||
|
failed?: string
|
||||||
|
needs?: string
|
||||||
|
body?: string
|
||||||
|
activeVolunteers?: number
|
||||||
|
newSupports?: number
|
||||||
|
signalType?: MunicipalitySignalType
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
status: OpsMunicipalityWriteSyncStatus
|
||||||
|
serverUpdatedAt?: string | null
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OpsPoliticalTrendOutboxRow = {
|
||||||
|
municipalityId: number
|
||||||
|
status: PoliticalTrendStatusValue | null
|
||||||
|
note: string | null
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
statusSync: OpsMunicipalityWriteSyncStatus
|
||||||
|
serverUpdatedAt?: string | null
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OpsEngagementLevelOutboxRow = {
|
||||||
|
municipalityId: number
|
||||||
|
level: EngagementLevel
|
||||||
|
note: string
|
||||||
|
reversalSignals: string
|
||||||
|
triangulatedShock: boolean
|
||||||
|
override: boolean
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
status: OpsMunicipalityWriteSyncStatus
|
||||||
|
serverUpdatedAt?: string | null
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OpsAdvisorsOutboxRow = {
|
||||||
|
municipalityId: number
|
||||||
|
advisors: number[]
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
status: OpsMunicipalityWriteSyncStatus
|
||||||
|
serverUpdatedAt?: string | null
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Collapse declare-votes retries to the newest per leadership×municipality. */
|
||||||
|
export const collapseDeclareVotesOutbox = (
|
||||||
|
transactions: OfflineTransaction[],
|
||||||
|
): OfflineTransaction[] => collapseByMetadataKey(transactions, 'declareKey')
|
||||||
|
|
||||||
|
/** Feed creates are append-only — keep every distinct client id. */
|
||||||
|
export const collapseMunicipalityUpdateOutbox = (
|
||||||
|
transactions: OfflineTransaction[],
|
||||||
|
): OfflineTransaction[] => collapseByMetadataKey(transactions, 'clientId')
|
||||||
|
|
||||||
|
export const collapsePoliticalTrendOutbox = (
|
||||||
|
transactions: OfflineTransaction[],
|
||||||
|
): OfflineTransaction[] => collapseByMetadataKey(transactions, 'municipalityId')
|
||||||
|
|
||||||
|
export const collapseEngagementLevelOutbox = (
|
||||||
|
transactions: OfflineTransaction[],
|
||||||
|
): OfflineTransaction[] => collapseByMetadataKey(transactions, 'municipalityId')
|
||||||
|
|
||||||
|
export const collapseAdvisorsOutbox = (transactions: OfflineTransaction[]): OfflineTransaction[] =>
|
||||||
|
collapseByMetadataKey(transactions, 'municipalityId')
|
||||||
|
|
||||||
|
const collapseByMetadataKey = (
|
||||||
|
transactions: OfflineTransaction[],
|
||||||
|
metadataKey: string,
|
||||||
|
): OfflineTransaction[] => {
|
||||||
|
const latestByKey = new Map<string, OfflineTransaction>()
|
||||||
|
|
||||||
|
for (const transaction of transactions) {
|
||||||
|
const raw = transaction.metadata?.[metadataKey]
|
||||||
|
const key =
|
||||||
|
typeof raw === 'number' || typeof raw === 'string'
|
||||||
|
? String(raw)
|
||||||
|
: String(transaction.mutations[0]?.key ?? transaction.id)
|
||||||
|
const current = latestByKey.get(key)
|
||||||
|
if (!current || transaction.createdAt.getTime() >= current.createdAt.getTime()) {
|
||||||
|
latestByKey.set(key, transaction)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...latestByKey.values()].sort(
|
||||||
|
(left, right) => left.createdAt.getTime() - right.createdAt.getTime(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const declareVotesOutboxKey = (leadershipId: number, municipalityId: number): string =>
|
||||||
|
`${leadershipId}:${municipalityId}`
|
||||||
|
|
@ -48,11 +48,14 @@ export const patchOpsVotePledgeEstimateOptimistic = (
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Authoritative patch after a successful server write (OH7). */
|
/** Authoritative patch after a successful server write (OH7/OH10). */
|
||||||
export const applyOpsVotePledgeEstimateWrite = (doc: VotePledgeEstimateWriteResult): void => {
|
export const applyOpsVotePledgeEstimateWrite = (doc: VotePledgeEstimateWriteResult): void => {
|
||||||
const mapped = mapVotePledgeWriteToOps(doc)
|
const mapped = mapVotePledgeWriteToOps(doc)
|
||||||
if (votePledgesCollection.has(mapped.id)) {
|
if (votePledgesCollection.has(mapped.id)) {
|
||||||
votePledgesCollection.update(mapped.id, (draft) => {
|
votePledgesCollection.update(mapped.id, (draft) => {
|
||||||
|
draft.declaredVotes = mapped.declaredVotes
|
||||||
|
draft.declaredAt = mapped.declaredAt
|
||||||
|
draft.declaredBy = mapped.declaredBy
|
||||||
draft.estimatedVotes = mapped.estimatedVotes
|
draft.estimatedVotes = mapped.estimatedVotes
|
||||||
draft.estimateNote = mapped.estimateNote
|
draft.estimateNote = mapped.estimateNote
|
||||||
draft.estimatedAt = mapped.estimatedAt
|
draft.estimatedAt = mapped.estimatedAt
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,11 @@ type UseCampaignCellAutosaveOptions<TValue, TResponse extends CampaignCellAutosa
|
||||||
errorMessage: string
|
errorMessage: string
|
||||||
/** Announced while a save is in flight, e.g. "Salvando tendência." */
|
/** Announced while a save is in flight, e.g. "Salvando tendência." */
|
||||||
pendingMessage: string
|
pendingMessage: string
|
||||||
|
/**
|
||||||
|
* OH10 — optional persist path (outbox). When set, replaces the JSON POST.
|
||||||
|
* Must resolve a success-shaped payload so `readSaved` can adopt the value.
|
||||||
|
*/
|
||||||
|
persist?: (value: TValue, signal: AbortSignal) => Promise<{ ok: boolean; payload: TResponse }>
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -140,11 +145,13 @@ export const useCampaignCellAutosave = <TValue, TResponse extends CampaignCellAu
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { ok, payload } = await postCampaignJson<TResponse>(
|
const { ok, payload } = current.persist
|
||||||
current.endpoint,
|
? await current.persist(next, controller.signal)
|
||||||
current.buildBody(next),
|
: await postCampaignJson<TResponse>(
|
||||||
controller.signal,
|
current.endpoint,
|
||||||
)
|
current.buildBody(next),
|
||||||
|
controller.signal,
|
||||||
|
)
|
||||||
|
|
||||||
if (generation !== saveGenerationRef.current) return
|
if (generation !== saveGenerationRef.current) return
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,37 @@
|
||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useActionState } from 'react'
|
import { useRouter } from 'next/navigation'
|
||||||
|
import {
|
||||||
|
useActionState,
|
||||||
|
useEffect,
|
||||||
|
useId,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
useSyncExternalStore,
|
||||||
|
type FormEvent,
|
||||||
|
} from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import {
|
||||||
|
discardOpsDeclareVotesOutboxRow,
|
||||||
|
enqueueDeclareVotes,
|
||||||
|
getOpsMunicipalityOfflineExecutor,
|
||||||
|
readOpsDeclareVotesOutboxRow,
|
||||||
|
subscribeOpsDeclareVotesOutboxRow,
|
||||||
|
} from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||||
|
import type { OpsMunicipalityWriteSyncStatus } from '@/components/campaign/opsSync/opsMunicipalityOutboxModel'
|
||||||
|
import {
|
||||||
|
subscribeOpsVotePledge,
|
||||||
|
votePledgesCollection,
|
||||||
|
} from '@/components/campaign/opsSync/opsVotePledgeMirror'
|
||||||
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
||||||
|
import { Badge } from '@/components/ui/Badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
|
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { Spinner } from '@/components/ui/Spinner'
|
import { Spinner } from '@/components/ui/Spinner'
|
||||||
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
|
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||||
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
||||||
import { fieldError } from '@/utilities/campaignFormFields'
|
import { fieldError } from '@/utilities/campaignFormFields'
|
||||||
|
|
||||||
|
|
@ -14,19 +39,64 @@ type DeclareVotesFormProps = {
|
||||||
municipalityID: number
|
municipalityID: number
|
||||||
/** Present when staff declare on behalf of a leadership. */
|
/** Present when staff declare on behalf of a leadership. */
|
||||||
leadershipID?: number
|
leadershipID?: number
|
||||||
|
/** Mirror / outbox key when a pledge row already exists (OH10). */
|
||||||
|
pledgeId?: number
|
||||||
currentDeclaredVotes: number | null
|
currentDeclaredVotes: number | null
|
||||||
|
/** Pledge row `updatedAt` for CAS when a pledge already exists. */
|
||||||
|
currentUpdatedAt?: string | null
|
||||||
|
opsHybridEnabled?: boolean
|
||||||
formAction: (
|
formAction: (
|
||||||
state: CampaignFormActionState,
|
state: CampaignFormActionState,
|
||||||
formData: FormData,
|
formData: FormData,
|
||||||
) => Promise<CampaignFormActionState>
|
) => Promise<CampaignFormActionState>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const syncStatusLabel: Record<OpsMunicipalityWriteSyncStatus, string> = {
|
||||||
|
pending: 'Pendente',
|
||||||
|
synced: 'Sincronizado',
|
||||||
|
conflict: 'Conflito',
|
||||||
|
error: 'Erro',
|
||||||
|
}
|
||||||
|
|
||||||
|
const CONFLICT_TOAST_ID_PREFIX = 'ops-declare-conflict:'
|
||||||
|
|
||||||
export const DeclareVotesForm = ({
|
export const DeclareVotesForm = ({
|
||||||
|
municipalityID,
|
||||||
|
leadershipID,
|
||||||
|
pledgeId,
|
||||||
|
currentDeclaredVotes,
|
||||||
|
currentUpdatedAt = null,
|
||||||
|
opsHybridEnabled = resolveOpsHybridEnabled(),
|
||||||
|
formAction,
|
||||||
|
}: DeclareVotesFormProps) => {
|
||||||
|
if (!opsHybridEnabled || leadershipID === undefined) {
|
||||||
|
return (
|
||||||
|
<LegacyDeclareVotesForm
|
||||||
|
municipalityID={municipalityID}
|
||||||
|
leadershipID={leadershipID}
|
||||||
|
currentDeclaredVotes={currentDeclaredVotes}
|
||||||
|
formAction={formAction}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<HybridDeclareVotesForm
|
||||||
|
municipalityID={municipalityID}
|
||||||
|
leadershipID={leadershipID}
|
||||||
|
pledgeId={pledgeId}
|
||||||
|
currentDeclaredVotes={currentDeclaredVotes}
|
||||||
|
currentUpdatedAt={currentUpdatedAt}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const LegacyDeclareVotesForm = ({
|
||||||
municipalityID,
|
municipalityID,
|
||||||
leadershipID,
|
leadershipID,
|
||||||
currentDeclaredVotes,
|
currentDeclaredVotes,
|
||||||
formAction,
|
formAction,
|
||||||
}: DeclareVotesFormProps) => {
|
}: Omit<DeclareVotesFormProps, 'opsHybridEnabled' | 'currentUpdatedAt'>) => {
|
||||||
const [state, submitAction, isPending] = useActionState(formAction, {})
|
const [state, submitAction, isPending] = useActionState(formAction, {})
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
@ -66,3 +136,189 @@ export const DeclareVotesForm = ({
|
||||||
</form>
|
</form>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const HybridDeclareVotesForm = ({
|
||||||
|
municipalityID,
|
||||||
|
leadershipID,
|
||||||
|
pledgeId: initialPledgeId,
|
||||||
|
currentDeclaredVotes,
|
||||||
|
currentUpdatedAt,
|
||||||
|
}: {
|
||||||
|
municipalityID: number
|
||||||
|
leadershipID: number
|
||||||
|
pledgeId?: number
|
||||||
|
currentDeclaredVotes: number | null
|
||||||
|
currentUpdatedAt: string | null
|
||||||
|
}) => {
|
||||||
|
const router = useRouter()
|
||||||
|
const liveRegionId = useId()
|
||||||
|
const formRef = useRef<HTMLFormElement>(null)
|
||||||
|
const previousStatusRef = useRef<OpsMunicipalityWriteSyncStatus | undefined>(undefined)
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||||
|
const [formError, setFormError] = useState<string | null>(null)
|
||||||
|
const [baseOverride, setBaseOverride] = useState<string | null | undefined>(undefined)
|
||||||
|
|
||||||
|
const resolvedPledgeId =
|
||||||
|
initialPledgeId ??
|
||||||
|
votePledgesCollection.toArray.find(
|
||||||
|
(row) => row.leadership === leadershipID && row.municipality === municipalityID,
|
||||||
|
)?.id
|
||||||
|
|
||||||
|
const mirrorPledge = useSyncExternalStore(
|
||||||
|
(onStoreChange) => {
|
||||||
|
if (resolvedPledgeId === undefined) return () => undefined
|
||||||
|
return subscribeOpsVotePledge(resolvedPledgeId, onStoreChange)
|
||||||
|
},
|
||||||
|
() =>
|
||||||
|
resolvedPledgeId !== undefined
|
||||||
|
? votePledgesCollection.get(resolvedPledgeId)
|
||||||
|
: votePledgesCollection.toArray.find(
|
||||||
|
(row) => row.leadership === leadershipID && row.municipality === municipalityID,
|
||||||
|
),
|
||||||
|
() => undefined,
|
||||||
|
)
|
||||||
|
|
||||||
|
const pledgeId = initialPledgeId ?? mirrorPledge?.id
|
||||||
|
const displayVotes = mirrorPledge?.declaredVotes ?? currentDeclaredVotes
|
||||||
|
const mirrorUpdatedAt = mirrorPledge?.updatedAt ?? currentUpdatedAt
|
||||||
|
const baseUpdatedAt = baseOverride !== undefined ? baseOverride : mirrorUpdatedAt
|
||||||
|
|
||||||
|
const outboxRow = useSyncExternalStore(
|
||||||
|
(onStoreChange) =>
|
||||||
|
subscribeOpsDeclareVotesOutboxRow(leadershipID, municipalityID, onStoreChange),
|
||||||
|
() => readOpsDeclareVotesOutboxRow(leadershipID, municipalityID),
|
||||||
|
() => undefined,
|
||||||
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void getOpsMunicipalityOfflineExecutor()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setBaseOverride(undefined)
|
||||||
|
}, [mirrorUpdatedAt])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const previous = previousStatusRef.current
|
||||||
|
previousStatusRef.current = outboxRow?.status
|
||||||
|
if (previous === 'pending' && outboxRow === undefined) {
|
||||||
|
router.refresh()
|
||||||
|
}
|
||||||
|
}, [outboxRow, router])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (outboxRow?.status !== 'conflict') return
|
||||||
|
const toastId = `${CONFLICT_TOAST_ID_PREFIX}${leadershipID}:${municipalityID}`
|
||||||
|
toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
|
||||||
|
id: toastId,
|
||||||
|
duration: Infinity,
|
||||||
|
action: {
|
||||||
|
label: 'Manter o meu',
|
||||||
|
onClick: () => {
|
||||||
|
const form = formRef.current
|
||||||
|
if (!form) return
|
||||||
|
const raw = new FormData(form).get('declaredVotes')
|
||||||
|
const declaredVotes = typeof raw === 'string' ? Number(raw) : NaN
|
||||||
|
if (!Number.isFinite(declaredVotes)) return
|
||||||
|
void enqueueDeclareVotes({
|
||||||
|
municipalityId: municipalityID,
|
||||||
|
leadershipId: leadershipID,
|
||||||
|
pledgeId,
|
||||||
|
declaredVotes: Math.trunc(declaredVotes),
|
||||||
|
baseUpdatedAt: outboxRow.serverUpdatedAt ?? null,
|
||||||
|
}).then(
|
||||||
|
() => {
|
||||||
|
setBaseOverride(outboxRow.serverUpdatedAt ?? null)
|
||||||
|
setFormError(null)
|
||||||
|
},
|
||||||
|
(error: unknown) => {
|
||||||
|
setFormError(
|
||||||
|
error instanceof Error ? error.message : 'Não foi possível reenviar a declaração.',
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cancel: {
|
||||||
|
label: 'Usar o novo',
|
||||||
|
onClick: () => {
|
||||||
|
discardOpsDeclareVotesOutboxRow(leadershipID, municipalityID)
|
||||||
|
setFormError(null)
|
||||||
|
router.refresh()
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
toast.dismiss(toastId)
|
||||||
|
}
|
||||||
|
}, [outboxRow, leadershipID, municipalityID, pledgeId, router])
|
||||||
|
|
||||||
|
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault()
|
||||||
|
const form = event.currentTarget
|
||||||
|
const raw = new FormData(form).get('declaredVotes')
|
||||||
|
const declaredVotes = typeof raw === 'string' ? Number(raw) : NaN
|
||||||
|
if (!Number.isFinite(declaredVotes) || declaredVotes < 0) {
|
||||||
|
setFormError('Informe um número válido de votos.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setIsSubmitting(true)
|
||||||
|
setFormError(null)
|
||||||
|
void enqueueDeclareVotes({
|
||||||
|
municipalityId: municipalityID,
|
||||||
|
leadershipId: leadershipID,
|
||||||
|
pledgeId,
|
||||||
|
declaredVotes: Math.trunc(declaredVotes),
|
||||||
|
baseUpdatedAt,
|
||||||
|
}).then(
|
||||||
|
() => setIsSubmitting(false),
|
||||||
|
(error: unknown) => {
|
||||||
|
setIsSubmitting(false)
|
||||||
|
setFormError(
|
||||||
|
error instanceof Error ? error.message : 'Não foi possível enfileirar a declaração.',
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const status = outboxRow?.status
|
||||||
|
const pending = isSubmitting || status === 'pending'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form ref={formRef} onSubmit={onSubmit} className="flex flex-col gap-3">
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor={`declare-votes-${municipalityID}-${leadershipID}`}>
|
||||||
|
Quantos votos a liderança traz neste município?
|
||||||
|
</FieldLabel>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<Input
|
||||||
|
id={`declare-votes-${municipalityID}-${leadershipID}`}
|
||||||
|
name="declaredVotes"
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
max={1000000}
|
||||||
|
required
|
||||||
|
inputMode="numeric"
|
||||||
|
defaultValue={displayVotes ?? undefined}
|
||||||
|
className="min-h-11 w-36"
|
||||||
|
/>
|
||||||
|
<Button type="submit" disabled={pending} className="min-h-11">
|
||||||
|
{pending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
||||||
|
{displayVotes == null ? 'Declarar' : 'Atualizar'}
|
||||||
|
</Button>
|
||||||
|
{status && status !== 'synced' ? (
|
||||||
|
<Badge variant={status === 'pending' ? 'estimate-pending' : 'destructive'}>
|
||||||
|
{syncStatusLabel[status]}
|
||||||
|
</Badge>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
{formError || outboxRow?.errorMessage ? (
|
||||||
|
<FieldError>{formError ?? outboxRow?.errorMessage}</FieldError>
|
||||||
|
) : null}
|
||||||
|
</Field>
|
||||||
|
<p id={liveRegionId} className="sr-only" aria-live="polite">
|
||||||
|
{pending ? 'Salvando declaração…' : null}
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ export type OpsLocalStaffPledgeRow = {
|
||||||
estimatedVotes: VoteEstimateScenarioViewModel
|
estimatedVotes: VoteEstimateScenarioViewModel
|
||||||
estimateNote: string | null
|
estimateNote: string | null
|
||||||
estimatedAt: string | null
|
estimatedAt: string | null
|
||||||
|
updatedAt: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export const findOpsMunicipalityBySlug = (
|
export const findOpsMunicipalityBySlug = (
|
||||||
|
|
@ -41,6 +42,7 @@ export const toLocalStaffPledgeRows = (
|
||||||
estimatedVotes: toVoteEstimateScenarioViewModel(pledge.estimatedVotes),
|
estimatedVotes: toVoteEstimateScenarioViewModel(pledge.estimatedVotes),
|
||||||
estimateNote: pledge.estimateNote ?? null,
|
estimateNote: pledge.estimateNote ?? null,
|
||||||
estimatedAt: pledge.estimatedAt ?? null,
|
estimatedAt: pledge.estimatedAt ?? null,
|
||||||
|
updatedAt: pledge.updatedAt,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.sort((left, right) => left.contactName.localeCompare(right.contactName, 'pt-BR'))
|
.sort((left, right) => left.contactName.localeCompare(right.contactName, 'pt-BR'))
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
|
||||||
import { ENGAGEMENT_LEVEL_TEXT_MAX_LENGTH, engagementLevels } from '@/lib/engagementLevel'
|
import { ENGAGEMENT_LEVEL_TEXT_MAX_LENGTH, engagementLevels } from '@/lib/engagementLevel'
|
||||||
|
import { OPS_UPDATED_AT_CONFLICT_MESSAGE, optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
|
||||||
import { positiveRelationshipId, trimmedNullableText } from '@/lib/schemas/primitives'
|
import { positiveRelationshipId, trimmedNullableText } from '@/lib/schemas/primitives'
|
||||||
import { voteEstimateScenarioFieldsSchema } from '@/lib/schemas/votePledge'
|
import { voteEstimateScenarioFieldsSchema } from '@/lib/schemas/votePledge'
|
||||||
|
|
||||||
|
|
@ -47,6 +48,8 @@ export const municipalityPoliticalTrendSchema = z.object({
|
||||||
municipality: positiveRelationshipId,
|
municipality: positiveRelationshipId,
|
||||||
status: z.enum(politicalTrendStatuses).nullable(),
|
status: z.enum(politicalTrendStatuses).nullable(),
|
||||||
note: trimmedNullableText(2000),
|
note: trimmedNullableText(2000),
|
||||||
|
/** OH10 CAS opt-in on municipality `updatedAt`. Absent → last-write-wins. */
|
||||||
|
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||||
})
|
})
|
||||||
|
|
||||||
export const parsePoliticalTrendStatusFormValue = (
|
export const parsePoliticalTrendStatusFormValue = (
|
||||||
|
|
@ -68,6 +71,8 @@ export const municipalityAdvisorsAssignmentSchema = z.object({
|
||||||
.array(positiveRelationshipId)
|
.array(positiveRelationshipId)
|
||||||
.max(MAX_ADVISORS_PER_MUNICIPALITY)
|
.max(MAX_ADVISORS_PER_MUNICIPALITY)
|
||||||
.transform((ids) => [...new Set(ids)]),
|
.transform((ids) => [...new Set(ids)]),
|
||||||
|
/** OH10 CAS opt-in on municipality `updatedAt`. Absent → last-write-wins. */
|
||||||
|
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||||
})
|
})
|
||||||
|
|
||||||
/** Single-toggle delta from the list popover — one advisor at a time, never the whole array. */
|
/** Single-toggle delta from the list popover — one advisor at a time, never the whole array. */
|
||||||
|
|
@ -75,6 +80,8 @@ export const municipalityAdvisorMembershipSchema = z.object({
|
||||||
municipality: positiveRelationshipId,
|
municipality: positiveRelationshipId,
|
||||||
advisor: positiveRelationshipId,
|
advisor: positiveRelationshipId,
|
||||||
assigned: z.boolean(),
|
assigned: z.boolean(),
|
||||||
|
/** OH10 CAS opt-in on municipality `updatedAt`. Absent → last-write-wins. */
|
||||||
|
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||||
})
|
})
|
||||||
|
|
||||||
export const MUNICIPALITY_ADVISOR_MEMBERSHIP_UNRESTRICTED_MESSAGE =
|
export const MUNICIPALITY_ADVISOR_MEMBERSHIP_UNRESTRICTED_MESSAGE =
|
||||||
|
|
@ -83,11 +90,17 @@ export const MUNICIPALITY_ADVISOR_MEMBERSHIP_UNRESTRICTED_MESSAGE =
|
||||||
export const MUNICIPALITY_ADVISOR_MEMBERSHIP_SAFE_MESSAGES = [
|
export const MUNICIPALITY_ADVISOR_MEMBERSHIP_SAFE_MESSAGES = [
|
||||||
MUNICIPALITY_ADVISOR_MEMBERSHIP_UNRESTRICTED_MESSAGE,
|
MUNICIPALITY_ADVISOR_MEMBERSHIP_UNRESTRICTED_MESSAGE,
|
||||||
MUNICIPALITY_ADVISORS_CAP_MESSAGE,
|
MUNICIPALITY_ADVISORS_CAP_MESSAGE,
|
||||||
|
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
export const MUNICIPALITY_ENGAGEMENT_LEVEL_UNRESTRICTED_MESSAGE =
|
export const MUNICIPALITY_ENGAGEMENT_LEVEL_UNRESTRICTED_MESSAGE =
|
||||||
'Somente a coordenação geral ou o candidato move o nível de envolvimento.'
|
'Somente a coordenação geral ou o candidato move o nível de envolvimento.'
|
||||||
|
|
||||||
|
export const MUNICIPALITY_ENGAGEMENT_LEVEL_SAFE_MESSAGES = [
|
||||||
|
MUNICIPALITY_ENGAGEMENT_LEVEL_UNRESTRICTED_MESSAGE,
|
||||||
|
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||||
|
] as const
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* E14 — a movement is never just the new level: the motivo and the signals
|
* 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
|
* that would reverse it are what make the decision auditable later, so both
|
||||||
|
|
@ -102,6 +115,8 @@ export const municipalityEngagementLevelSchema = z.object({
|
||||||
triangulatedShock: z.boolean().default(false),
|
triangulatedShock: z.boolean().default(false),
|
||||||
/** Accepts the listed violations knowingly; recorded in the decision snapshot. */
|
/** Accepts the listed violations knowingly; recorded in the decision snapshot. */
|
||||||
override: z.boolean().default(false),
|
override: z.boolean().default(false),
|
||||||
|
/** OH10 CAS opt-in on municipality `updatedAt`. Absent → last-write-wins. */
|
||||||
|
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||||
})
|
})
|
||||||
|
|
||||||
export const municipalityExpectedVotesSchema = z.object({
|
export const municipalityExpectedVotesSchema = z.object({
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
import { optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
|
||||||
import {
|
import {
|
||||||
MAX_VOTE_COUNT,
|
MAX_VOTE_COUNT,
|
||||||
positiveRelationshipId,
|
positiveRelationshipId,
|
||||||
|
|
@ -63,6 +64,11 @@ export const municipalityUpdateCreateSchema = z
|
||||||
activeVolunteers: optionalCount,
|
activeVolunteers: optionalCount,
|
||||||
newSupports: optionalCount,
|
newSupports: optionalCount,
|
||||||
signalType: z.enum(municipalitySignalTypes).optional(),
|
signalType: z.enum(municipalitySignalTypes).optional(),
|
||||||
|
/**
|
||||||
|
* OH10 CAS opt-in on the parent municipality's `updatedAt` (feed order).
|
||||||
|
* Absent → last-write-wins create.
|
||||||
|
*/
|
||||||
|
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||||
})
|
})
|
||||||
.superRefine((data, context) => {
|
.superRefine((data, context) => {
|
||||||
if (data.kind === 'semanal') {
|
if (data.kind === 'semanal') {
|
||||||
|
|
|
||||||
38
src/lib/schemas/opsCas.ts
Normal file
38
src/lib/schemas/opsCas.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OH10 — shared CAS token for doc `updatedAt`. Opt-in: absent → last-write-wins
|
||||||
|
* (legacy). Present (including matching the current stamp) → refuse when the
|
||||||
|
* row's `updatedAt` differs. Same exact-string + optional stamp contract as
|
||||||
|
* OH6's `OPS_ESTIMATE_CONFLICT_MESSAGE` (safeMessages + outbox parse).
|
||||||
|
*/
|
||||||
|
export const optionalBaseUpdatedAtSchema = z.string().datetime().nullable().optional()
|
||||||
|
|
||||||
|
export const OPS_UPDATED_AT_CONFLICT_MESSAGE =
|
||||||
|
'Este registro foi alterado por outra pessoa. Escolha manter a sua ou usar a nova.'
|
||||||
|
|
||||||
|
export const opsUpdatedAtConflictError = (serverUpdatedAt: string): Error =>
|
||||||
|
new Error(`${OPS_UPDATED_AT_CONFLICT_MESSAGE}\n${serverUpdatedAt}`)
|
||||||
|
|
||||||
|
export const isOpsUpdatedAtConflictMessage = (message: string): boolean =>
|
||||||
|
message === OPS_UPDATED_AT_CONFLICT_MESSAGE ||
|
||||||
|
message.startsWith(`${OPS_UPDATED_AT_CONFLICT_MESSAGE}\n`)
|
||||||
|
|
||||||
|
export const parseOpsUpdatedAtConflictServerUpdatedAt = (message: string): string | null => {
|
||||||
|
if (!isOpsUpdatedAtConflictMessage(message)) return null
|
||||||
|
if (message === OPS_UPDATED_AT_CONFLICT_MESSAGE) return null
|
||||||
|
const stamped = message.slice(OPS_UPDATED_AT_CONFLICT_MESSAGE.length + 1)
|
||||||
|
return stamped === '' ? null : stamped
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Refuse when CAS is armed and the live stamp differs from the client's base. */
|
||||||
|
export const assertOpsUpdatedAtCas = (
|
||||||
|
enforceCas: boolean,
|
||||||
|
baseUpdatedAt: string | null | undefined,
|
||||||
|
currentUpdatedAt: string,
|
||||||
|
): void => {
|
||||||
|
if (!enforceCas || baseUpdatedAt === undefined) return
|
||||||
|
if (currentUpdatedAt !== baseUpdatedAt) {
|
||||||
|
throw opsUpdatedAtConflictError(currentUpdatedAt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
import { OPS_UPDATED_AT_CONFLICT_MESSAGE, optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
|
||||||
import {
|
import {
|
||||||
MAX_VOTE_COUNT,
|
MAX_VOTE_COUNT,
|
||||||
positiveRelationshipId,
|
positiveRelationshipId,
|
||||||
|
|
@ -34,6 +35,11 @@ export const declareVotesSchema = z.object({
|
||||||
municipality: positiveRelationshipId,
|
municipality: positiveRelationshipId,
|
||||||
leadership: positiveRelationshipId,
|
leadership: positiveRelationshipId,
|
||||||
declaredVotes: z.number().int().min(0).max(MAX_VOTE_COUNT),
|
declaredVotes: z.number().int().min(0).max(MAX_VOTE_COUNT),
|
||||||
|
/**
|
||||||
|
* OH10 CAS opt-in on the pledge row's `updatedAt`. Absent → last-write-wins.
|
||||||
|
* When no pledge exists yet, pass `null` to assert a create.
|
||||||
|
*/
|
||||||
|
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||||
})
|
})
|
||||||
|
|
||||||
/** Staff record their internal estimate for one pledge. */
|
/** Staff record their internal estimate for one pledge. */
|
||||||
|
|
@ -91,6 +97,7 @@ export const VOTE_PLEDGE_DECLARE_SAFE_MESSAGES = [
|
||||||
VOTE_PLEDGE_DECLARE_STAFF_MESSAGE,
|
VOTE_PLEDGE_DECLARE_STAFF_MESSAGE,
|
||||||
VOTE_PLEDGE_MUNICIPALITY_NOT_LINKED_MESSAGE,
|
VOTE_PLEDGE_MUNICIPALITY_NOT_LINKED_MESSAGE,
|
||||||
VOTE_PLEDGE_LEADERSHIP_REQUIRED_MESSAGE,
|
VOTE_PLEDGE_LEADERSHIP_REQUIRED_MESSAGE,
|
||||||
|
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
export const VOTE_PLEDGE_ESTIMATE_SAFE_MESSAGES = [
|
export const VOTE_PLEDGE_ESTIMATE_SAFE_MESSAGES = [
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,7 @@ export const municipalityListSelect = {
|
||||||
advisors: true,
|
advisors: true,
|
||||||
priority: true,
|
priority: true,
|
||||||
lastUpdateAt: true,
|
lastUpdateAt: true,
|
||||||
|
updatedAt: true,
|
||||||
expectedVotes: true,
|
expectedVotes: true,
|
||||||
politicalTrend: {
|
politicalTrend: {
|
||||||
status: true,
|
status: true,
|
||||||
|
|
@ -73,6 +74,8 @@ export type MunicipalityListViewModel = {
|
||||||
* ordering.
|
* ordering.
|
||||||
*/
|
*/
|
||||||
lastSignalAt: string | null
|
lastSignalAt: string | null
|
||||||
|
/** OH10 — CAS token for staff writes when OPS_HYBRID is on. */
|
||||||
|
updatedAt: string
|
||||||
expectedVotes: VoteEstimateScenarioViewModel
|
expectedVotes: VoteEstimateScenarioViewModel
|
||||||
politicalTrendStatus: PoliticalTrendStatus | null
|
politicalTrendStatus: PoliticalTrendStatus | null
|
||||||
politicalTrendNote: string | null
|
politicalTrendNote: string | null
|
||||||
|
|
@ -116,6 +119,7 @@ export const toMunicipalityListViewModel = (
|
||||||
municipality.lastUpdateAt ?? null,
|
municipality.lastUpdateAt ?? null,
|
||||||
pledges?.lastPledgeAt ?? null,
|
pledges?.lastPledgeAt ?? null,
|
||||||
),
|
),
|
||||||
|
updatedAt: municipality.updatedAt,
|
||||||
expectedVotes: toVoteEstimateScenarioViewModel(municipality.expectedVotes),
|
expectedVotes: toVoteEstimateScenarioViewModel(municipality.expectedVotes),
|
||||||
politicalTrendStatus: municipality.politicalTrend?.status ?? null,
|
politicalTrendStatus: municipality.politicalTrend?.status ?? null,
|
||||||
politicalTrendNote: municipality.politicalTrend?.note ?? null,
|
politicalTrendNote: municipality.politicalTrend?.note ?? null,
|
||||||
|
|
@ -149,6 +153,8 @@ export type MunicipalityDetailViewModel = {
|
||||||
tseZones: number[]
|
tseZones: number[]
|
||||||
advisorIDs: number[]
|
advisorIDs: number[]
|
||||||
lastUpdateAt: string | null
|
lastUpdateAt: string | null
|
||||||
|
/** OH10 — CAS token for staff writes when OPS_HYBRID is on. */
|
||||||
|
updatedAt: string
|
||||||
/** Staff-only block — null for the leader view model. */
|
/** Staff-only block — null for the leader view model. */
|
||||||
strategy: MunicipalityStrategyViewModel | null
|
strategy: MunicipalityStrategyViewModel | null
|
||||||
}
|
}
|
||||||
|
|
@ -196,6 +202,7 @@ export const toMunicipalityDetailViewModel = (
|
||||||
.map(relationshipId)
|
.map(relationshipId)
|
||||||
.filter((id): id is number => id !== null),
|
.filter((id): id is number => id !== null),
|
||||||
lastUpdateAt: municipality.lastUpdateAt ?? null,
|
lastUpdateAt: municipality.lastUpdateAt ?? null,
|
||||||
|
updatedAt: municipality.updatedAt,
|
||||||
strategy:
|
strategy:
|
||||||
role === 'leader'
|
role === 'leader'
|
||||||
? null
|
? null
|
||||||
|
|
|
||||||
|
|
@ -139,5 +139,6 @@ export const loadMunicipalityPledges = async (
|
||||||
estimatedVotes: toVoteEstimateScenarioViewModel(pledge.estimatedVotes),
|
estimatedVotes: toVoteEstimateScenarioViewModel(pledge.estimatedVotes),
|
||||||
estimateNote: pledge.estimateNote ?? null,
|
estimateNote: pledge.estimateNote ?? null,
|
||||||
estimatedAt: pledge.estimatedAt ?? null,
|
estimatedAt: pledge.estimatedAt ?? null,
|
||||||
|
updatedAt: pledge.updatedAt,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -162,4 +162,6 @@ export type StaffPledgeRow = {
|
||||||
estimatedVotes: VoteEstimateScenarioViewModel
|
estimatedVotes: VoteEstimateScenarioViewModel
|
||||||
estimateNote: string | null
|
estimateNote: string | null
|
||||||
estimatedAt: string | null
|
estimatedAt: string | null
|
||||||
|
/** OH10 — CAS token for declareVotes when OPS_HYBRID is on. */
|
||||||
|
updatedAt: string
|
||||||
}
|
}
|
||||||
|
|
|
||||||
243
tests/int/municipalityStaffCas.int.spec.ts
Normal file
243
tests/int/municipalityStaffCas.int.spec.ts
Normal file
|
|
@ -0,0 +1,243 @@
|
||||||
|
// @vitest-environment node
|
||||||
|
|
||||||
|
import type { Payload } from 'payload'
|
||||||
|
import { getPayload } from 'payload'
|
||||||
|
import { beforeAll, describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import {
|
||||||
|
assignMunicipalityAdvisorsCasRecord,
|
||||||
|
setMunicipalityAdvisorMembershipCasRecord,
|
||||||
|
setMunicipalityEngagementLevelCasRecord,
|
||||||
|
setMunicipalityEngagementLevelRecord,
|
||||||
|
setMunicipalityPoliticalTrendCasRecord,
|
||||||
|
setMunicipalityPoliticalTrendRecord,
|
||||||
|
} from '@/app/(campaign)/campanha/actions/municipality'
|
||||||
|
import { ENGAGEMENT_LEVEL_PATTERN_ID } from '@/lib/engagementLevel'
|
||||||
|
import { isOpsUpdatedAtConflictMessage } from '@/lib/schemas/opsCas'
|
||||||
|
import config from '@/payload.config'
|
||||||
|
|
||||||
|
import { installCampaignFixtures } from '../helpers/campaignFixtures'
|
||||||
|
|
||||||
|
let payload: Payload
|
||||||
|
const campaignFixtures = installCampaignFixtures({
|
||||||
|
getPayload: () => payload,
|
||||||
|
setPayload: (nextPayload) => {
|
||||||
|
payload = nextPayload
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('municipality staff CAS writes (OH10 fase 2)', () => {
|
||||||
|
beforeAll(async () => {
|
||||||
|
payload = await getPayload({ config: await config })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('politicalTrend: refuses stale baseUpdatedAt', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor')
|
||||||
|
await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
|
||||||
|
|
||||||
|
const first = await setMunicipalityPoliticalTrendRecord(payload, advisor, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
status: 'favoravel',
|
||||||
|
note: 'primeira',
|
||||||
|
})
|
||||||
|
const baseUpdatedAt = first.updatedAt
|
||||||
|
|
||||||
|
await setMunicipalityPoliticalTrendRecord(payload, advisor, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
status: 'neutra',
|
||||||
|
note: 'segunda',
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
setMunicipalityPoliticalTrendCasRecord(payload, advisor, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
status: 'desfavoravel',
|
||||||
|
note: 'stale',
|
||||||
|
baseUpdatedAt,
|
||||||
|
}),
|
||||||
|
).rejects.toSatisfy((error: unknown) => {
|
||||||
|
expect(isOpsUpdatedAtConflictMessage((error as Error).message)).toBe(true)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
const current = await payload.findByID({
|
||||||
|
collection: 'municipality',
|
||||||
|
id: municipality.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
expect(current.politicalTrend?.status).toBe('neutra')
|
||||||
|
expect(current.politicalTrend?.note).toBe('segunda')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('engagement: matching CAS writes level + allocationDecision in one transaction', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const coordinator = await fixtures.createCampaignUser('coordinator')
|
||||||
|
|
||||||
|
const parent = await payload.findByID({
|
||||||
|
collection: 'municipality',
|
||||||
|
id: municipality.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const updated = await setMunicipalityEngagementLevelCasRecord(payload, coordinator, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
level: 'n1',
|
||||||
|
note: 'Motivo CAS',
|
||||||
|
reversalSignals: 'Sinais de reversão',
|
||||||
|
triangulatedShock: false,
|
||||||
|
override: false,
|
||||||
|
baseUpdatedAt: parent.updatedAt,
|
||||||
|
})
|
||||||
|
fixtures.touchMunicipality(municipality.id)
|
||||||
|
|
||||||
|
expect(updated.engagementLevel).toBe('n1')
|
||||||
|
|
||||||
|
const decisions = await payload.find({
|
||||||
|
collection: 'allocationDecision',
|
||||||
|
where: {
|
||||||
|
and: [
|
||||||
|
{ municipality: { equals: municipality.id } },
|
||||||
|
{ patternId: { equals: ENGAGEMENT_LEVEL_PATTERN_ID } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
depth: 0,
|
||||||
|
limit: 5,
|
||||||
|
sort: '-createdAt',
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
fixtures.own('allocationDecision', decisions.docs[0]!.id)
|
||||||
|
expect(decisions.docs[0]?.rationale).toBe('Motivo CAS')
|
||||||
|
expect(decisions.docs[0]?.outcome).toBe('movimento')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('engagement: stale CAS refuses without writing a decision', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const coordinator = await fixtures.createCampaignUser('coordinator')
|
||||||
|
|
||||||
|
const first = await setMunicipalityEngagementLevelRecord(payload, coordinator, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
level: 'n0',
|
||||||
|
note: 'Primeiro movimento',
|
||||||
|
reversalSignals: 'Sinais',
|
||||||
|
triangulatedShock: false,
|
||||||
|
override: false,
|
||||||
|
})
|
||||||
|
const staleBase = first.updatedAt
|
||||||
|
|
||||||
|
await setMunicipalityEngagementLevelRecord(payload, coordinator, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
level: 'n1',
|
||||||
|
note: 'Segundo movimento',
|
||||||
|
reversalSignals: 'Sinais 2',
|
||||||
|
triangulatedShock: false,
|
||||||
|
override: true,
|
||||||
|
})
|
||||||
|
fixtures.touchMunicipality(municipality.id)
|
||||||
|
|
||||||
|
const beforeCount = await payload.count({
|
||||||
|
collection: 'allocationDecision',
|
||||||
|
where: {
|
||||||
|
and: [
|
||||||
|
{ municipality: { equals: municipality.id } },
|
||||||
|
{ patternId: { equals: ENGAGEMENT_LEVEL_PATTERN_ID } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
setMunicipalityEngagementLevelCasRecord(payload, coordinator, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
level: 'n2',
|
||||||
|
note: 'Stale',
|
||||||
|
reversalSignals: 'x',
|
||||||
|
triangulatedShock: false,
|
||||||
|
override: true,
|
||||||
|
baseUpdatedAt: staleBase,
|
||||||
|
}),
|
||||||
|
).rejects.toSatisfy((error: unknown) => {
|
||||||
|
expect(isOpsUpdatedAtConflictMessage((error as Error).message)).toBe(true)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
const afterCount = await payload.count({
|
||||||
|
collection: 'allocationDecision',
|
||||||
|
where: {
|
||||||
|
and: [
|
||||||
|
{ municipality: { equals: municipality.id } },
|
||||||
|
{ patternId: { equals: ENGAGEMENT_LEVEL_PATTERN_ID } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
expect(afterCount.totalDocs).toBe(beforeCount.totalDocs)
|
||||||
|
|
||||||
|
const current = await payload.findByID({
|
||||||
|
collection: 'municipality',
|
||||||
|
id: municipality.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
expect(current.engagementLevel).toBe('n1')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('advisors assignment: refuses stale baseUpdatedAt', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const coordinator = await fixtures.createCampaignUser('coordinator')
|
||||||
|
const advisorA = await fixtures.createCampaignUser('advisor')
|
||||||
|
const advisorB = await fixtures.createCampaignUser('advisor')
|
||||||
|
|
||||||
|
const first = await assignMunicipalityAdvisorsCasRecord(payload, coordinator, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
advisors: [advisorA.id],
|
||||||
|
})
|
||||||
|
const staleBase = first.updatedAt
|
||||||
|
|
||||||
|
await assignMunicipalityAdvisorsCasRecord(payload, coordinator, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
advisors: [advisorB.id],
|
||||||
|
baseUpdatedAt: first.updatedAt,
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
assignMunicipalityAdvisorsCasRecord(payload, coordinator, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
advisors: [advisorA.id, advisorB.id],
|
||||||
|
baseUpdatedAt: staleBase,
|
||||||
|
}),
|
||||||
|
).rejects.toSatisfy((error: unknown) => {
|
||||||
|
expect(isOpsUpdatedAtConflictMessage((error as Error).message)).toBe(true)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('advisor membership: matching CAS toggles one advisor', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const coordinator = await fixtures.createCampaignUser('coordinator')
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor')
|
||||||
|
|
||||||
|
const parent = await payload.findByID({
|
||||||
|
collection: 'municipality',
|
||||||
|
id: municipality.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const updated = await setMunicipalityAdvisorMembershipCasRecord(payload, coordinator, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
advisor: advisor.id,
|
||||||
|
assigned: true,
|
||||||
|
baseUpdatedAt: parent.updatedAt,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(updated.advisors).toEqual(expect.arrayContaining([advisor.id]))
|
||||||
|
})
|
||||||
|
})
|
||||||
218
tests/int/municipalityWritesCas.int.spec.ts
Normal file
218
tests/int/municipalityWritesCas.int.spec.ts
Normal file
|
|
@ -0,0 +1,218 @@
|
||||||
|
// @vitest-environment node
|
||||||
|
|
||||||
|
import type { Payload } from 'payload'
|
||||||
|
import { getPayload } from 'payload'
|
||||||
|
import { beforeAll, describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import {
|
||||||
|
createMunicipalityUpdateCasRecord,
|
||||||
|
createMunicipalityUpdateRecord,
|
||||||
|
} from '@/app/(campaign)/campanha/actions/municipalityUpdate'
|
||||||
|
import {
|
||||||
|
declareVotesCasRecord,
|
||||||
|
declareVotesRecord,
|
||||||
|
} from '@/app/(campaign)/campanha/actions/votePledge'
|
||||||
|
import {
|
||||||
|
isOpsUpdatedAtConflictMessage,
|
||||||
|
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||||
|
} from '@/lib/schemas/opsCas'
|
||||||
|
import config from '@/payload.config'
|
||||||
|
|
||||||
|
import { installCampaignFixtures } from '../helpers/campaignFixtures'
|
||||||
|
|
||||||
|
let payload: Payload
|
||||||
|
const campaignFixtures = installCampaignFixtures({
|
||||||
|
getPayload: () => payload,
|
||||||
|
setPayload: (nextPayload) => {
|
||||||
|
payload = nextPayload
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('declareVotesCas (OH10)', () => {
|
||||||
|
beforeAll(async () => {
|
||||||
|
payload = await getPayload({ config: await config })
|
||||||
|
})
|
||||||
|
|
||||||
|
const createLinkedLeadership = async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor')
|
||||||
|
await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
|
||||||
|
const contact = await fixtures.createContact()
|
||||||
|
const leadership = await fixtures.createLeadership({
|
||||||
|
contact: contact.id,
|
||||||
|
municipalities: [municipality.id],
|
||||||
|
supportStatus: 'engajado',
|
||||||
|
})
|
||||||
|
return { fixtures, advisor, municipality, leadership }
|
||||||
|
}
|
||||||
|
|
||||||
|
it('writes like declareVotes when baseUpdatedAt is omitted', async () => {
|
||||||
|
const { advisor, municipality, leadership, fixtures } = await createLinkedLeadership()
|
||||||
|
|
||||||
|
const pledge = await declareVotesCasRecord(payload, advisor, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
leadership: leadership.id,
|
||||||
|
declaredVotes: 40,
|
||||||
|
})
|
||||||
|
fixtures.own('votePledge', pledge.id)
|
||||||
|
|
||||||
|
expect(pledge.declaredVotes).toBe(40)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses a stale baseUpdatedAt without writing', async () => {
|
||||||
|
const { advisor, municipality, leadership, fixtures } = await createLinkedLeadership()
|
||||||
|
|
||||||
|
const first = await declareVotesRecord(payload, advisor, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
leadership: leadership.id,
|
||||||
|
declaredVotes: 50,
|
||||||
|
})
|
||||||
|
fixtures.own('votePledge', first.id)
|
||||||
|
const baseUpdatedAt = first.updatedAt
|
||||||
|
|
||||||
|
await declareVotesRecord(payload, advisor, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
leadership: leadership.id,
|
||||||
|
declaredVotes: 75,
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
declareVotesCasRecord(payload, advisor, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
leadership: leadership.id,
|
||||||
|
declaredVotes: 99,
|
||||||
|
baseUpdatedAt,
|
||||||
|
}),
|
||||||
|
).rejects.toSatisfy((error: unknown) => {
|
||||||
|
expect(error).toBeInstanceOf(Error)
|
||||||
|
const message = (error as Error).message
|
||||||
|
expect(isOpsUpdatedAtConflictMessage(message)).toBe(true)
|
||||||
|
expect(message.startsWith(OPS_UPDATED_AT_CONFLICT_MESSAGE)).toBe(true)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
const current = await payload.findByID({
|
||||||
|
collection: 'votePledge',
|
||||||
|
id: first.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
expect(current.declaredVotes).toBe(75)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('writes when baseUpdatedAt matches', async () => {
|
||||||
|
const { advisor, municipality, leadership, fixtures } = await createLinkedLeadership()
|
||||||
|
|
||||||
|
const first = await declareVotesRecord(payload, advisor, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
leadership: leadership.id,
|
||||||
|
declaredVotes: 10,
|
||||||
|
})
|
||||||
|
fixtures.own('votePledge', first.id)
|
||||||
|
|
||||||
|
const updated = await declareVotesCasRecord(payload, advisor, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
leadership: leadership.id,
|
||||||
|
declaredVotes: 22,
|
||||||
|
baseUpdatedAt: first.updatedAt,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(updated.declaredVotes).toBe(22)
|
||||||
|
expect(updated.updatedAt).not.toBe(first.updatedAt)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('createMunicipalityUpdateCas (OH10)', () => {
|
||||||
|
beforeAll(async () => {
|
||||||
|
payload = await getPayload({ config: await config })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('creates when baseUpdatedAt matches the parent municipality', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor')
|
||||||
|
await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
|
||||||
|
|
||||||
|
const parent = await payload.findByID({
|
||||||
|
collection: 'municipality',
|
||||||
|
id: municipality.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const created = await createMunicipalityUpdateCasRecord(payload, advisor, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
kind: 'nota',
|
||||||
|
body: 'Nota CAS ok',
|
||||||
|
baseUpdatedAt: parent.updatedAt,
|
||||||
|
})
|
||||||
|
fixtures.own('municipalityUpdate', created.id)
|
||||||
|
|
||||||
|
expect(created.body).toBe('Nota CAS ok')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses a stale parent baseUpdatedAt without creating', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor')
|
||||||
|
await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
|
||||||
|
|
||||||
|
const parent = await payload.findByID({
|
||||||
|
collection: 'municipality',
|
||||||
|
id: municipality.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
const staleBase = parent.updatedAt
|
||||||
|
|
||||||
|
// Bump parent updatedAt via a strategy-adjacent field write.
|
||||||
|
await payload.update({
|
||||||
|
collection: 'municipality',
|
||||||
|
id: municipality.id,
|
||||||
|
data: { nextSteps: 'bump' },
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const beforeCount = await payload.count({
|
||||||
|
collection: 'municipalityUpdate',
|
||||||
|
where: { municipality: { equals: municipality.id } },
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
createMunicipalityUpdateCasRecord(payload, advisor, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
kind: 'nota',
|
||||||
|
body: 'stale',
|
||||||
|
baseUpdatedAt: staleBase,
|
||||||
|
}),
|
||||||
|
).rejects.toSatisfy((error: unknown) => {
|
||||||
|
expect(isOpsUpdatedAtConflictMessage((error as Error).message)).toBe(true)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
const afterCount = await payload.count({
|
||||||
|
collection: 'municipalityUpdate',
|
||||||
|
where: { municipality: { equals: municipality.id } },
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
expect(afterCount.totalDocs).toBe(beforeCount.totalDocs)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('creates like today when baseUpdatedAt is omitted', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor')
|
||||||
|
await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
|
||||||
|
|
||||||
|
const created = await createMunicipalityUpdateRecord(payload, advisor, {
|
||||||
|
municipality: municipality.id,
|
||||||
|
kind: 'nota',
|
||||||
|
body: 'LWW create',
|
||||||
|
})
|
||||||
|
fixtures.own('municipalityUpdate', created.id)
|
||||||
|
expect(created.body).toBe('LWW create')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -13,6 +13,14 @@ import { MunicipalityPortfolioCell } from '@/components/campaign/shared/Municipa
|
||||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||||
import { toVoteEstimateScenarioViewModel } from '@/lib/voteEstimate'
|
import { toVoteEstimateScenarioViewModel } from '@/lib/voteEstimate'
|
||||||
|
|
||||||
|
vi.mock('next/navigation', () => ({
|
||||||
|
useRouter: () => ({
|
||||||
|
refresh: vi.fn(),
|
||||||
|
push: vi.fn(),
|
||||||
|
replace: vi.fn(),
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* B42: the quick-edit cells of `/campanha/municipios` share one container
|
* B42: the quick-edit cells of `/campanha/municipios` share one container
|
||||||
* (`CampaignCellEditOverlay`) that is a Popover in the desktop table and a
|
* (`CampaignCellEditOverlay`) that is a Popover in the desktop table and a
|
||||||
|
|
|
||||||
|
|
@ -194,6 +194,7 @@ describe('campaign visual foundation', () => {
|
||||||
priority: 'alta',
|
priority: 'alta',
|
||||||
lastUpdateAt: null,
|
lastUpdateAt: null,
|
||||||
lastSignalAt: null,
|
lastSignalAt: null,
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
expectedVotes: { pessimistic: null, central: 1500, optimistic: null },
|
expectedVotes: { pessimistic: null, central: 1500, optimistic: null },
|
||||||
politicalTrendStatus: 'favoravel',
|
politicalTrendStatus: 'favoravel',
|
||||||
politicalTrendNote: null,
|
politicalTrendNote: null,
|
||||||
|
|
@ -237,6 +238,7 @@ describe('campaign visual foundation', () => {
|
||||||
priority: 'normal',
|
priority: 'normal',
|
||||||
lastUpdateAt: null,
|
lastUpdateAt: null,
|
||||||
lastSignalAt: null,
|
lastSignalAt: null,
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
expectedVotes: toVoteEstimateScenarioViewModel(null),
|
expectedVotes: toVoteEstimateScenarioViewModel(null),
|
||||||
politicalTrendStatus: null,
|
politicalTrendStatus: null,
|
||||||
politicalTrendNote: null,
|
politicalTrendNote: null,
|
||||||
|
|
@ -377,6 +379,7 @@ describe('campaign visual foundation', () => {
|
||||||
priority: 'alta',
|
priority: 'alta',
|
||||||
lastUpdateAt: staleSignal,
|
lastUpdateAt: staleSignal,
|
||||||
lastSignalAt: staleSignal,
|
lastSignalAt: staleSignal,
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
expectedVotes: toVoteEstimateScenarioViewModel(null),
|
expectedVotes: toVoteEstimateScenarioViewModel(null),
|
||||||
politicalTrendStatus: null,
|
politicalTrendStatus: null,
|
||||||
politicalTrendNote: null,
|
politicalTrendNote: null,
|
||||||
|
|
@ -421,6 +424,7 @@ describe('campaign visual foundation', () => {
|
||||||
priority: 'normal',
|
priority: 'normal',
|
||||||
lastUpdateAt: null,
|
lastUpdateAt: null,
|
||||||
lastSignalAt: null,
|
lastSignalAt: null,
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
expectedVotes: toVoteEstimateScenarioViewModel(null),
|
expectedVotes: toVoteEstimateScenarioViewModel(null),
|
||||||
politicalTrendStatus: null,
|
politicalTrendStatus: null,
|
||||||
politicalTrendNote: null,
|
politicalTrendNote: null,
|
||||||
|
|
@ -462,6 +466,7 @@ describe('campaign visual foundation', () => {
|
||||||
priority: 'normal',
|
priority: 'normal',
|
||||||
lastUpdateAt: null,
|
lastUpdateAt: null,
|
||||||
lastSignalAt: null,
|
lastSignalAt: null,
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
expectedVotes: toVoteEstimateScenarioViewModel(null),
|
expectedVotes: toVoteEstimateScenarioViewModel(null),
|
||||||
politicalTrendStatus: null,
|
politicalTrendStatus: null,
|
||||||
politicalTrendNote: null,
|
politicalTrendNote: null,
|
||||||
|
|
@ -509,6 +514,7 @@ describe('campaign visual foundation', () => {
|
||||||
priority: 'alta',
|
priority: 'alta',
|
||||||
lastUpdateAt: null,
|
lastUpdateAt: null,
|
||||||
lastSignalAt: null,
|
lastSignalAt: null,
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
expectedVotes: toVoteEstimateScenarioViewModel(null),
|
expectedVotes: toVoteEstimateScenarioViewModel(null),
|
||||||
politicalTrendStatus: null,
|
politicalTrendStatus: null,
|
||||||
politicalTrendNote: null,
|
politicalTrendNote: null,
|
||||||
|
|
@ -582,6 +588,7 @@ describe('campaign visual foundation', () => {
|
||||||
priority: 'normal' as const,
|
priority: 'normal' as const,
|
||||||
lastUpdateAt: null,
|
lastUpdateAt: null,
|
||||||
lastSignalAt: null,
|
lastSignalAt: null,
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
expectedVotes: toVoteEstimateScenarioViewModel(null),
|
expectedVotes: toVoteEstimateScenarioViewModel(null),
|
||||||
politicalTrendStatus: null,
|
politicalTrendStatus: null,
|
||||||
politicalTrendNote: null,
|
politicalTrendNote: null,
|
||||||
|
|
|
||||||
|
|
@ -89,6 +89,7 @@ describe('municipalityDetailLocalViews (OH9)', () => {
|
||||||
declaredVotes: 120,
|
declaredVotes: 120,
|
||||||
estimatedVotes: { pessimistic: 80, central: 100, optimistic: 130 },
|
estimatedVotes: { pessimistic: 80, central: 100, optimistic: 130 },
|
||||||
estimateNote: 'Campo',
|
estimateNote: 'Campo',
|
||||||
|
updatedAt: '2026-07-21T00:00:00.000Z',
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
47
tests/unit/opsUpdatedAtCas.unit.spec.ts
Normal file
47
tests/unit/opsUpdatedAtCas.unit.spec.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import {
|
||||||
|
assertOpsUpdatedAtCas,
|
||||||
|
isOpsUpdatedAtConflictMessage,
|
||||||
|
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||||
|
opsUpdatedAtConflictError,
|
||||||
|
parseOpsUpdatedAtConflictServerUpdatedAt,
|
||||||
|
} from '@/lib/schemas/opsCas'
|
||||||
|
|
||||||
|
describe('opsUpdatedAtCas helpers (OH10)', () => {
|
||||||
|
it('round-trips a stamped server updatedAt through the error message', () => {
|
||||||
|
const stamped = opsUpdatedAtConflictError('2026-08-01T12:00:00.000Z')
|
||||||
|
expect(isOpsUpdatedAtConflictMessage(stamped.message)).toBe(true)
|
||||||
|
expect(parseOpsUpdatedAtConflictServerUpdatedAt(stamped.message)).toBe(
|
||||||
|
'2026-08-01T12:00:00.000Z',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps the bare conflict message exact for safeMessages matching', () => {
|
||||||
|
expect(OPS_UPDATED_AT_CONFLICT_MESSAGE.length).toBeGreaterThan(10)
|
||||||
|
expect(isOpsUpdatedAtConflictMessage(OPS_UPDATED_AT_CONFLICT_MESSAGE)).toBe(true)
|
||||||
|
expect(parseOpsUpdatedAtConflictServerUpdatedAt(OPS_UPDATED_AT_CONFLICT_MESSAGE)).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects unrelated messages', () => {
|
||||||
|
expect(isOpsUpdatedAtConflictMessage('outro erro')).toBe(false)
|
||||||
|
expect(parseOpsUpdatedAtConflictServerUpdatedAt('outro erro')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('assertOpsUpdatedAtCas is a no-op without enforce or base', () => {
|
||||||
|
expect(() => assertOpsUpdatedAtCas(false, '2026-08-01T12:00:00.000Z', 'other')).not.toThrow()
|
||||||
|
expect(() => assertOpsUpdatedAtCas(true, undefined, 'other')).not.toThrow()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('assertOpsUpdatedAtCas refuses a stale base', () => {
|
||||||
|
expect(() =>
|
||||||
|
assertOpsUpdatedAtCas(true, '2026-08-01T12:00:00.000Z', '2026-08-01T13:00:00.000Z'),
|
||||||
|
).toThrow(Error)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('assertOpsUpdatedAtCas allows a matching base', () => {
|
||||||
|
expect(() =>
|
||||||
|
assertOpsUpdatedAtCas(true, '2026-08-01T12:00:00.000Z', '2026-08-01T12:00:00.000Z'),
|
||||||
|
).not.toThrow()
|
||||||
|
})
|
||||||
|
})
|
||||||
Loading…
Reference in a new issue