mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-27 06:13:06 +00:00
OH13: CAS writes for leadership, demand, activity, stateDeputy
Add baseUpdatedAt CAS on domain staff writes, assertCampaignDocCas helper, opsDomainOutbox with hybrid forms (Manter/Usar), and int/unit pins. Closes #176. Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
parent
40afd80254
commit
e8f315d67b
28 changed files with 2322 additions and 48 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):** **OH13** (Issue #176) — writes CAS por domínio: `baseUpdatedAt` + `*Cas` em leadership / demand transition / activity update / stateDeputy vínculos; helper `assertCampaignDocCas`; outbox `opsDomainOutbox` com Manter/Usar nos forms; flag OFF intacto. Plano: [`oh13-domain-writes-cas.md`](docs/plans/oh13-domain-writes-cas.md).
|
||||||
|
|
||||||
**Recently resolved (2026-08-02):** **OH12** (Issue #174) — `OpsListLocal` read-only via registry + mirror: `OfflineBoundary` nas 8 rotas de lista; Local com `CampaignTable` + parsers canónicos sobre o mirror (municípios/lideranças/dobradinhas/orgs/demandas); assessores/territórios/apoiadores com estado honesto; saved filters create/delete disabled offline; e2e lista `?q=`. Plano: [`oh12-ops-list-local.md`](docs/plans/oh12-ops-list-local.md).
|
**Recently resolved (2026-08-02):** **OH12** (Issue #174) — `OpsListLocal` read-only via registry + mirror: `OfflineBoundary` nas 8 rotas de lista; Local com `CampaignTable` + parsers canónicos sobre o mirror (municípios/lideranças/dobradinhas/orgs/demandas); assessores/territórios/apoiadores com estado honesto; saved filters create/delete disabled offline; e2e lista `?q=`. Plano: [`oh12-ops-list-local.md`](docs/plans/oh12-ops-list-local.md).
|
||||||
|
|
||||||
**Recently resolved (2026-08-02):** **OH11** (Issue #173) — SW cache-first para `/_next/static/` (chunks hashed, prefixo `campanha-<buildId>`); logout limpa campaignOps na ordem abort sync → outbox → persistence → Cache API (`clearCampaignOpsStorage` + `clearCampaignPwaCaches`); e2e `campaignOpsOffline` com jornada write→reload→online→sync (`OPS_HYBRID=1`). Plano: [`oh11-sw-e2e-docs.md`](docs/plans/oh11-sw-e2e-docs.md).
|
**Recently resolved (2026-08-02):** **OH11** (Issue #173) — SW cache-first para `/_next/static/` (chunks hashed, prefixo `campanha-<buildId>`); logout limpa campaignOps na ordem abort sync → outbox → persistence → Cache API (`clearCampaignOpsStorage` + `clearCampaignPwaCaches`); e2e `campaignOpsOffline` com jornada write→reload→online→sync (`OPS_HYBRID=1`). Plano: [`oh11-sw-e2e-docs.md`](docs/plans/oh11-sw-e2e-docs.md).
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
# OH13 — Writes CAS por domínio: leadership, stateDeputy, activity, demand
|
# OH13 — Writes CAS por domínio: leadership, stateDeputy, activity, demand
|
||||||
|
|
||||||
Status: rascunho
|
Status: em implementação
|
||||||
Atualizado em: 2026-08-01
|
Atualizado em: 2026-08-02
|
||||||
Issue: #176
|
Issue: #176
|
||||||
Priority: P1
|
Priority: P1
|
||||||
Model: cursor-grok-4.5-medium
|
Model: cursor-grok-4.5-medium
|
||||||
|
|
@ -10,13 +10,21 @@ Appetite: ~2–3 dias eng
|
||||||
Depends: OH10, OH12
|
Depends: OH10, OH12
|
||||||
Responsável: —
|
Responsável: —
|
||||||
|
|
||||||
|
## Freshness audit (2026-08-02)
|
||||||
|
|
||||||
|
- OH10 (#171) e OH12 (#174) `done`+`in-prod`. Padrão CAS (`optionalBaseUpdatedAtSchema` + `assertOpsUpdatedAtCas`) e outbox irmão (`opsMunicipalityOutbox`) intactos; mirror já tem `updatedAt` em `OpsLeadership` / `OpsActivity` / `OpsStateDeputy` / `OpsDemand`.
|
||||||
|
- Actions citadas batem: `updateLeadershipInternalRecord`, `createLeadership`/`createValidatedLeadershipRecord`, `transitionCampaignDemandRecord`, `setStateDeputyMunicipalitiesBatchRecord`, `updateActivity`/`createActivityRecord`. Sem `baseUpdatedAt` ainda — a implementar.
|
||||||
|
- Controles: `LeadershipInternalForm`, `LeadershipForm`, `LeadershipListSupportStatusControl`, `DemandWorkflowCard`, `ActivityForm`, `MunicipalityPortfolioCell` (dobradinhas). Flag `OPS_HYBRID` via `resolveOpsHybridEnabled`.
|
||||||
|
- Helper `runCampaignCasMutation` / `assertCampaignDocCas` ainda não existe — extrair após 3+ call sites OH13.
|
||||||
|
- Premissas confirmadas; a implementar.
|
||||||
|
|
||||||
## Premissas
|
## Premissas
|
||||||
|
|
||||||
1. Padrão estabilizado em OH6/OH10 — agora com 3+ call sites, avaliar extração de helper `*Cas` (regra do repo).
|
1. Padrão estabilizado em OH6/OH10 — agora com 3+ call sites, avaliar extração de helper `*Cas` (regra do repo).
|
||||||
2. Cada write respeita access por papel (advisor scoped, coordinator/candidate unrestricted) — o CAS é adicional, nunca substitui RBAC.
|
2. Cada write respeita access por papel (advisor scoped, coordinator/candidate unrestricted) — o CAS é adicional, nunca substitui RBAC.
|
||||||
3. Sem migration: todas estas writes usam collections existentes.
|
3. Sem migration: todas estas writes usam collections existentes.
|
||||||
|
|
||||||
→ Corrija agora ou sigo com estas.
|
→ Confirmadas; a implementar.
|
||||||
|
|
||||||
## Objetivos
|
## Objetivos
|
||||||
|
|
||||||
|
|
@ -49,8 +57,8 @@ Componentes:
|
||||||
|
|
||||||
- **Quota:** ~0,5
|
- **Quota:** ~0,5
|
||||||
- **Aceite:**
|
- **Aceite:**
|
||||||
- [ ] criar/editar leadership offline → pending → aplica; conflito com escolha
|
- [x] criar/editar leadership offline → pending → aplica; conflito com escolha
|
||||||
- [ ] decisão de demanda offline → pending → aplica; access advisor respeitado (pin int)
|
- [x] decisão de demanda offline → pending → aplica; access advisor respeitado (pin int)
|
||||||
- **Verify:** `pnpm gate:fast` + int CAS + e2e flaky
|
- **Verify:** `pnpm gate:fast` + int CAS + e2e flaky
|
||||||
- **Files:** schemas, actions, outbox, specs
|
- **Files:** schemas, actions, outbox, specs
|
||||||
- **Tamanho:** M
|
- **Tamanho:** M
|
||||||
|
|
@ -59,11 +67,11 @@ Componentes:
|
||||||
|
|
||||||
- **Quota:** ~0,5
|
- **Quota:** ~0,5
|
||||||
- **Aceite:**
|
- **Aceite:**
|
||||||
- [ ] vínculos offline aplicam; conflito UI
|
- [x] vínculos offline aplicam; conflito UI (CAS server + outbox; listas Local read-only OH12)
|
||||||
- [ ] campos de activity offline aplicam
|
- [x] campos de activity offline aplicam
|
||||||
- [ ] helper extraído **só se** 3+ call sites (senão, nota no PR por que não)
|
- [x] helper extraído: `assertCampaignDocCas` (3+ call sites OH13)
|
||||||
- **Verify:** `pnpm gate:fast` + int + e2e
|
- **Verify:** `pnpm gate:fast` + int + e2e
|
||||||
- **Files:** idem + helper condicional
|
- **Files:** idem + helper
|
||||||
- **Tamanho:** M
|
- **Tamanho:** M
|
||||||
|
|
||||||
## Dependências
|
## Dependências
|
||||||
|
|
|
||||||
|
|
@ -128,6 +128,7 @@ export default async function DemandDetailPage({ params }: DemandDetailPageProps
|
||||||
status={demand.status}
|
status={demand.status}
|
||||||
canDecideEscalated={isCampaignUnrestricted(user)}
|
canDecideEscalated={isCampaignUnrestricted(user)}
|
||||||
currentCost={demand.cost}
|
currentCost={demand.cost}
|
||||||
|
updatedAt={demand.updatedAt}
|
||||||
transitionFormAction={transitionDemandFormAction}
|
transitionFormAction={transitionDemandFormAction}
|
||||||
costFormAction={setDemandCostFormAction}
|
costFormAction={setDemandCostFormAction}
|
||||||
receiptFormAction={attachDemandReceiptFormAction}
|
receiptFormAction={attachDemandReceiptFormAction}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,8 @@
|
||||||
|
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||||
import { LEADERSHIP_STAFF_MESSAGE } from '@/lib/schemas/leadership'
|
import { LEADERSHIP_STAFF_MESSAGE } from '@/lib/schemas/leadership'
|
||||||
|
|
||||||
/** Shared form-error copy for leadership staff edits — kept out of `'use server'` files. */
|
/** Shared form-error copy for leadership staff edits — kept out of `'use server'` files. */
|
||||||
export const leadershipStaffEditSafeMessages = [LEADERSHIP_STAFF_MESSAGE] as const
|
export const leadershipStaffEditSafeMessages = [
|
||||||
|
LEADERSHIP_STAFF_MESSAGE,
|
||||||
|
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||||
|
] as const
|
||||||
|
|
|
||||||
|
|
@ -176,7 +176,11 @@ const leadershipColumns = ({
|
||||||
<LeadershipSortableHead state={state} sortKey="supportStatus" filterParam="supportStatus" />
|
<LeadershipSortableHead state={state} sortKey="supportStatus" filterParam="supportStatus" />
|
||||||
),
|
),
|
||||||
cell: (row) => (
|
cell: (row) => (
|
||||||
<LeadershipListSupportStatusControl leadershipID={row.id} status={row.supportStatus} />
|
<LeadershipListSupportStatusControl
|
||||||
|
leadershipID={row.id}
|
||||||
|
status={row.supportStatus}
|
||||||
|
updatedAt={row.updatedAt}
|
||||||
|
/>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
import type { Payload } from 'payload'
|
import type { Payload } from 'payload'
|
||||||
|
|
||||||
|
import { assertCampaignDocCas } from '@/app/(campaign)/campanha/actions/assertCampaignDocCas'
|
||||||
import {
|
import {
|
||||||
ACTIVITY_RESULT_REQUIRED_MESSAGE,
|
ACTIVITY_RESULT_REQUIRED_MESSAGE,
|
||||||
ACTIVITY_RESULT_STAFF_MESSAGE,
|
ACTIVITY_RESULT_STAFF_MESSAGE,
|
||||||
|
|
@ -162,15 +163,26 @@ const updateActivityRecord = async (
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
input: ActivityUpdateInput,
|
input: ActivityUpdateInput,
|
||||||
demandDrafts: ActivityDemandDraft[] = [],
|
demandDrafts: ActivityDemandDraft[] = [],
|
||||||
|
options?: { cas?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const { id, ...data } = activityUpdateSchema.parse(input)
|
const { id, baseUpdatedAt, ...data } = activityUpdateSchema.parse(input)
|
||||||
const demands = activityDemandDraftsSchema.parse(demandDrafts)
|
const demands = activityDemandDraftsSchema.parse(demandDrafts)
|
||||||
|
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)
|
||||||
|
|
||||||
|
await assertCampaignDocCas(payload, {
|
||||||
|
collection: 'activity',
|
||||||
|
id,
|
||||||
|
actor: currentActor,
|
||||||
|
enforceCas,
|
||||||
|
baseUpdatedAt,
|
||||||
|
req,
|
||||||
|
})
|
||||||
|
|
||||||
const activity = await payload.update({
|
const activity = await payload.update({
|
||||||
collection: 'activity',
|
collection: 'activity',
|
||||||
id,
|
id,
|
||||||
|
|
@ -363,6 +375,12 @@ export const createActivity = async (
|
||||||
return createActivityRecord(payload, actor, input, demandDrafts)
|
return createActivityRecord(payload, actor, input, demandDrafts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Outbox entry for create — no CAS (new doc). */
|
||||||
|
export const createActivityCas = async (
|
||||||
|
input: ActivityCreateInput,
|
||||||
|
demandDrafts: ActivityDemandDraft[] = [],
|
||||||
|
) => createActivity(input, demandDrafts)
|
||||||
|
|
||||||
export const updateActivity = async (
|
export const updateActivity = async (
|
||||||
input: ActivityUpdateInput,
|
input: ActivityUpdateInput,
|
||||||
demandDrafts: ActivityDemandDraft[] = [],
|
demandDrafts: ActivityDemandDraft[] = [],
|
||||||
|
|
@ -371,6 +389,21 @@ export const updateActivity = async (
|
||||||
return updateActivityRecord(payload, actor, input, demandDrafts)
|
return updateActivityRecord(payload, actor, input, demandDrafts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const updateActivityCas = async (
|
||||||
|
input: ActivityUpdateInput,
|
||||||
|
demandDrafts: ActivityDemandDraft[] = [],
|
||||||
|
) => {
|
||||||
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
|
return updateActivityRecord(payload, actor, input, demandDrafts, { cas: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const updateActivityCasRecord = async (
|
||||||
|
payload: Payload,
|
||||||
|
actor: CampaignUser,
|
||||||
|
input: ActivityUpdateInput,
|
||||||
|
demandDrafts: ActivityDemandDraft[] = [],
|
||||||
|
) => updateActivityRecord(payload, actor, input, demandDrafts, { cas: true })
|
||||||
|
|
||||||
export const cancelActivity = async (id: number) => {
|
export const cancelActivity = async (id: number) => {
|
||||||
const { payload, actor } = await getCampaignActionContext()
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
return setActivityLifecycleStatusRecord(payload, actor, id, 'cancelado')
|
return setActivityLifecycleStatusRecord(payload, actor, id, 'cancelado')
|
||||||
|
|
|
||||||
38
src/app/(campaign)/campanha/actions/assertCampaignDocCas.ts
Normal file
38
src/app/(campaign)/campanha/actions/assertCampaignDocCas.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
import type { Payload } from 'payload'
|
||||||
|
|
||||||
|
import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas'
|
||||||
|
import type { CampaignUser } from '@/payload-types'
|
||||||
|
import type { PayloadTransactionRequest } from '@/utilities/payloadTransaction'
|
||||||
|
|
||||||
|
type CasCollection = 'leadership' | 'campaignDemand' | 'activity' | 'stateDeputy' | 'municipality'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OH13 — shared CAS gate used by domain writes (3+ call sites). When armed,
|
||||||
|
* loads the doc's `updatedAt` under the actor's row access and refuses on
|
||||||
|
* mismatch. Does not replace RBAC or wrap the mutation itself.
|
||||||
|
*/
|
||||||
|
export const assertCampaignDocCas = async (
|
||||||
|
payload: Payload,
|
||||||
|
args: {
|
||||||
|
collection: CasCollection
|
||||||
|
id: number
|
||||||
|
actor: CampaignUser
|
||||||
|
enforceCas: boolean
|
||||||
|
baseUpdatedAt: string | null | undefined
|
||||||
|
req?: PayloadTransactionRequest
|
||||||
|
},
|
||||||
|
): Promise<void> => {
|
||||||
|
if (!args.enforceCas || args.baseUpdatedAt === undefined) return
|
||||||
|
|
||||||
|
const current = await payload.findByID({
|
||||||
|
collection: args.collection,
|
||||||
|
id: args.id,
|
||||||
|
depth: 0,
|
||||||
|
select: { updatedAt: true },
|
||||||
|
user: args.actor,
|
||||||
|
overrideAccess: false,
|
||||||
|
...(args.req ? { req: args.req } : {}),
|
||||||
|
})
|
||||||
|
|
||||||
|
assertOpsUpdatedAtCas(true, args.baseUpdatedAt, current.updatedAt)
|
||||||
|
}
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
import type { Payload } from 'payload'
|
import type { Payload } from 'payload'
|
||||||
|
|
||||||
|
import { assertCampaignDocCas } from '@/app/(campaign)/campanha/actions/assertCampaignDocCas'
|
||||||
import {
|
import {
|
||||||
CAMPAIGN_DEMAND_COST_STAFF_MESSAGE,
|
CAMPAIGN_DEMAND_COST_STAFF_MESSAGE,
|
||||||
CAMPAIGN_DEMAND_RECEIPT_EMPTY_MESSAGE,
|
CAMPAIGN_DEMAND_RECEIPT_EMPTY_MESSAGE,
|
||||||
|
|
@ -60,8 +61,10 @@ export const transitionCampaignDemandRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
input: CampaignDemandTransitionInput,
|
input: CampaignDemandTransitionInput,
|
||||||
|
options?: { cas?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const { id, status, decisionNote } = campaignDemandTransitionSchema.parse(input)
|
const { id, status, decisionNote, baseUpdatedAt } = campaignDemandTransitionSchema.parse(input)
|
||||||
|
const enforceCas = options?.cas === true
|
||||||
|
|
||||||
return withPayloadTransaction(
|
return withPayloadTransaction(
|
||||||
payload,
|
payload,
|
||||||
|
|
@ -72,6 +75,15 @@ export const transitionCampaignDemandRecord = async (
|
||||||
}
|
}
|
||||||
await acquireTextAdvisoryLocks(payload, req, [`campaign-demand:${id}`])
|
await acquireTextAdvisoryLocks(payload, req, [`campaign-demand:${id}`])
|
||||||
|
|
||||||
|
await assertCampaignDocCas(payload, {
|
||||||
|
collection: 'campaignDemand',
|
||||||
|
id,
|
||||||
|
actor: currentActor,
|
||||||
|
enforceCas,
|
||||||
|
baseUpdatedAt,
|
||||||
|
req,
|
||||||
|
})
|
||||||
|
|
||||||
// Transition validity + coordinator-only escalated decisions are
|
// Transition validity + coordinator-only escalated decisions are
|
||||||
// enforced by the collection hook.
|
// enforced by the collection hook.
|
||||||
return payload.update({
|
return payload.update({
|
||||||
|
|
@ -199,6 +211,17 @@ export const transitionCampaignDemand = async (input: CampaignDemandTransitionIn
|
||||||
return transitionCampaignDemandRecord(payload, actor, input)
|
return transitionCampaignDemandRecord(payload, actor, input)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const transitionCampaignDemandCas = async (input: CampaignDemandTransitionInput) => {
|
||||||
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
|
return transitionCampaignDemandRecord(payload, actor, input, { cas: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const transitionCampaignDemandCasRecord = async (
|
||||||
|
payload: Payload,
|
||||||
|
actor: CampaignUser,
|
||||||
|
input: CampaignDemandTransitionInput,
|
||||||
|
) => transitionCampaignDemandRecord(payload, actor, input, { cas: true })
|
||||||
|
|
||||||
export const setCampaignDemandCost = async (input: CampaignDemandCostInput) => {
|
export const setCampaignDemandCost = async (input: CampaignDemandCostInput) => {
|
||||||
const { payload, actor } = await getCampaignActionContext()
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
return setCampaignDemandCostRecord(payload, actor, input)
|
return setCampaignDemandCostRecord(payload, actor, input)
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
import { revalidatePath } from 'next/cache'
|
import { revalidatePath } from 'next/cache'
|
||||||
import type { Payload } from 'payload'
|
import type { Payload } from 'payload'
|
||||||
|
|
||||||
|
import { assertCampaignDocCas } from '@/app/(campaign)/campanha/actions/assertCampaignDocCas'
|
||||||
import { nextMunicipalityIdsAfterLeadershipMembership } from '@/lib/leadershipMunicipalityMembership'
|
import { nextMunicipalityIdsAfterLeadershipMembership } from '@/lib/leadershipMunicipalityMembership'
|
||||||
import { nextStateDeputyIdsAfterMembership } from '@/lib/leadershipStateDeputyMembership'
|
import { nextStateDeputyIdsAfterMembership } from '@/lib/leadershipStateDeputyMembership'
|
||||||
import { relationshipId, uniqueRelationshipIds } from '@/lib/relationship'
|
import { relationshipId, uniqueRelationshipIds } from '@/lib/relationship'
|
||||||
|
|
@ -23,6 +24,7 @@ import {
|
||||||
type LeadershipWizardCreateInput,
|
type LeadershipWizardCreateInput,
|
||||||
type LeadershipWizardUpdateInput,
|
type LeadershipWizardUpdateInput,
|
||||||
} from '@/lib/schemas/leadership'
|
} from '@/lib/schemas/leadership'
|
||||||
|
import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas'
|
||||||
import type { CampaignUser, Contact } from '@/payload-types'
|
import type { CampaignUser, Contact } from '@/payload-types'
|
||||||
import { getAdvisorMunicipalityIds } from '@/utilities/campaignAccess'
|
import { getAdvisorMunicipalityIds } from '@/utilities/campaignAccess'
|
||||||
import { getCampaignActionContext, reloadStaffActor } from '@/utilities/campaignActionContext'
|
import { getCampaignActionContext, reloadStaffActor } from '@/utilities/campaignActionContext'
|
||||||
|
|
@ -176,9 +178,11 @@ export const updateLeadershipInternalRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
input: LeadershipInternalUpdateInput,
|
input: LeadershipInternalUpdateInput,
|
||||||
|
options?: { cas?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const { id, municipalities, organizations, stateDeputies, ...data } =
|
const { id, municipalities, organizations, stateDeputies, baseUpdatedAt, ...data } =
|
||||||
leadershipInternalUpdateSchema.parse(input)
|
leadershipInternalUpdateSchema.parse(input)
|
||||||
|
const enforceCas = options?.cas === true
|
||||||
const currentActor = await getFreshStaffActor(payload, actor)
|
const currentActor = await getFreshStaffActor(payload, actor)
|
||||||
|
|
||||||
// Row access verifies the current record is in the actor's scope.
|
// Row access verifies the current record is in the actor's scope.
|
||||||
|
|
@ -190,6 +194,9 @@ export const updateLeadershipInternalRecord = async (
|
||||||
overrideAccess: false,
|
overrideAccess: false,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Stamp already loaded with the row — avoid a second find via assertCampaignDocCas.
|
||||||
|
assertOpsUpdatedAtCas(enforceCas, baseUpdatedAt, current.updatedAt)
|
||||||
|
|
||||||
if (municipalities !== undefined) {
|
if (municipalities !== undefined) {
|
||||||
await assertMunicipalitiesWithinScope(payload, currentActor, municipalities)
|
await assertMunicipalitiesWithinScope(payload, currentActor, municipalities)
|
||||||
}
|
}
|
||||||
|
|
@ -232,11 +239,25 @@ export const createLeadership = async (input: unknown) => {
|
||||||
return createValidatedLeadershipRecord(payload, actor, data)
|
return createValidatedLeadershipRecord(payload, actor, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Outbox entry for create — no CAS (new doc). Same write path as `createLeadership`. */
|
||||||
|
export const createLeadershipCas = async (input: unknown) => createLeadership(input)
|
||||||
|
|
||||||
export const updateLeadershipInternal = async (input: LeadershipInternalUpdateInput) => {
|
export const updateLeadershipInternal = async (input: LeadershipInternalUpdateInput) => {
|
||||||
const { payload, actor } = await getCampaignActionContext()
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
return updateLeadershipInternalRecord(payload, actor, input)
|
return updateLeadershipInternalRecord(payload, actor, input)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const updateLeadershipInternalCas = async (input: LeadershipInternalUpdateInput) => {
|
||||||
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
|
return updateLeadershipInternalRecord(payload, actor, input, { cas: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const updateLeadershipInternalCasRecord = async (
|
||||||
|
payload: Payload,
|
||||||
|
actor: CampaignUser,
|
||||||
|
input: LeadershipInternalUpdateInput,
|
||||||
|
) => updateLeadershipInternalRecord(payload, actor, input, { cas: true })
|
||||||
|
|
||||||
const revalidateLeadershipWizardPaths = (leadershipId: number, municipalitySlug: string) => {
|
const revalidateLeadershipWizardPaths = (leadershipId: number, municipalitySlug: string) => {
|
||||||
revalidatePath(`/campanha/liderancas/${leadershipId}`, 'page')
|
revalidatePath(`/campanha/liderancas/${leadershipId}`, 'page')
|
||||||
revalidatePath(`/campanha/municipios/${municipalitySlug}`, 'page')
|
revalidatePath(`/campanha/municipios/${municipalitySlug}`, 'page')
|
||||||
|
|
@ -436,9 +457,11 @@ export const setLeadershipStateDeputyMembershipRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
input: LeadershipStateDeputyMembershipInput,
|
input: LeadershipStateDeputyMembershipInput,
|
||||||
|
options?: { cas?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const { leadershipId, stateDeputyId, assigned } =
|
const { leadershipId, stateDeputyId, assigned, baseUpdatedAt } =
|
||||||
leadershipStateDeputyMembershipSchema.parse(input)
|
leadershipStateDeputyMembershipSchema.parse(input)
|
||||||
|
const enforceCas = options?.cas === true
|
||||||
|
|
||||||
return withPayloadTransaction(
|
return withPayloadTransaction(
|
||||||
payload,
|
payload,
|
||||||
|
|
@ -451,6 +474,15 @@ export const setLeadershipStateDeputyMembershipRecord = async (
|
||||||
'stateDeputies',
|
'stateDeputies',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
await assertCampaignDocCas(payload, {
|
||||||
|
collection: 'leadership',
|
||||||
|
id: leadershipId,
|
||||||
|
actor: currentActor,
|
||||||
|
enforceCas,
|
||||||
|
baseUpdatedAt,
|
||||||
|
req,
|
||||||
|
})
|
||||||
|
|
||||||
const currentStateDeputyIDs = uniqueRelationshipIds(current.stateDeputies)
|
const currentStateDeputyIDs = uniqueRelationshipIds(current.stateDeputies)
|
||||||
const nextStateDeputyIDs = nextStateDeputyIdsAfterMembership(
|
const nextStateDeputyIDs = nextStateDeputyIdsAfterMembership(
|
||||||
currentStateDeputyIDs,
|
currentStateDeputyIDs,
|
||||||
|
|
@ -508,6 +540,20 @@ export const setLeadershipStateDeputyMembership = async (
|
||||||
return leadership
|
return leadership
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const setLeadershipStateDeputyMembershipCas = async (
|
||||||
|
input: LeadershipStateDeputyMembershipInput,
|
||||||
|
) => {
|
||||||
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
|
const { leadership, stateDeputySlug } = await setLeadershipStateDeputyMembershipRecord(
|
||||||
|
payload,
|
||||||
|
actor,
|
||||||
|
input,
|
||||||
|
{ cas: true },
|
||||||
|
)
|
||||||
|
if (stateDeputySlug) revalidateLeadershipStateDeputyPaths(input.leadershipId, stateDeputySlug)
|
||||||
|
return leadership
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `/campanha/liderancas` is deliberately absent: the chip cell that calls this
|
* `/campanha/liderancas` is deliberately absent: the chip cell that calls this
|
||||||
* IS on that list, and it already shows the result optimistically, so
|
* IS on that list, and it already shows the result optimistically, so
|
||||||
|
|
@ -544,9 +590,11 @@ export const setLeadershipMunicipalitiesMembershipRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
input: LeadershipMunicipalitiesMembershipInput,
|
input: LeadershipMunicipalitiesMembershipInput,
|
||||||
|
options?: { cas?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const { leadershipId, municipalityIds, assigned } =
|
const { leadershipId, municipalityIds, assigned, baseUpdatedAt } =
|
||||||
leadershipMunicipalitiesMembershipSchema.parse(input)
|
leadershipMunicipalitiesMembershipSchema.parse(input)
|
||||||
|
const enforceCas = options?.cas === true
|
||||||
|
|
||||||
return withPayloadTransaction(
|
return withPayloadTransaction(
|
||||||
payload,
|
payload,
|
||||||
|
|
@ -559,6 +607,15 @@ export const setLeadershipMunicipalitiesMembershipRecord = async (
|
||||||
'municipalities',
|
'municipalities',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
await assertCampaignDocCas(payload, {
|
||||||
|
collection: 'leadership',
|
||||||
|
id: leadershipId,
|
||||||
|
actor: currentActor,
|
||||||
|
enforceCas,
|
||||||
|
baseUpdatedAt,
|
||||||
|
req,
|
||||||
|
})
|
||||||
|
|
||||||
const change = nextMunicipalityIdsAfterLeadershipMembership(
|
const change = nextMunicipalityIdsAfterLeadershipMembership(
|
||||||
uniqueRelationshipIds(current.municipalities),
|
uniqueRelationshipIds(current.municipalities),
|
||||||
municipalityIds,
|
municipalityIds,
|
||||||
|
|
@ -621,3 +678,19 @@ export const setLeadershipMunicipalitiesMembership = async (
|
||||||
}
|
}
|
||||||
return leadership
|
return leadership
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const setLeadershipMunicipalitiesMembershipCas = async (
|
||||||
|
input: LeadershipMunicipalitiesMembershipInput,
|
||||||
|
) => {
|
||||||
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
|
const { leadership, municipalitySlugs } = await setLeadershipMunicipalitiesMembershipRecord(
|
||||||
|
payload,
|
||||||
|
actor,
|
||||||
|
input,
|
||||||
|
{ cas: true },
|
||||||
|
)
|
||||||
|
if (municipalitySlugs.length > 0) {
|
||||||
|
revalidateLeadershipMunicipalityPaths(input.leadershipId, municipalitySlugs)
|
||||||
|
}
|
||||||
|
return leadership
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
import { revalidatePath } from 'next/cache'
|
import { revalidatePath } from 'next/cache'
|
||||||
import type { Payload } from 'payload'
|
import type { Payload } from 'payload'
|
||||||
|
|
||||||
|
import { assertCampaignDocCas } from '@/app/(campaign)/campanha/actions/assertCampaignDocCas'
|
||||||
import { nextStateDeputyIdsAfterMunicipalityMembership } from '@/lib/municipalityStateDeputyMembership'
|
import { nextStateDeputyIdsAfterMunicipalityMembership } from '@/lib/municipalityStateDeputyMembership'
|
||||||
import { uniqueRelationshipIds } from '@/lib/relationship'
|
import { uniqueRelationshipIds } from '@/lib/relationship'
|
||||||
import {
|
import {
|
||||||
|
|
@ -108,9 +109,11 @@ export const setStateDeputyMunicipalitiesBatchRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
input: StateDeputyMunicipalitiesBatchInput,
|
input: StateDeputyMunicipalitiesBatchInput,
|
||||||
|
options?: { cas?: boolean },
|
||||||
) => {
|
) => {
|
||||||
const { stateDeputyId, municipalityIds, assigned } =
|
const { stateDeputyId, municipalityIds, assigned, municipalityBaseUpdatedAt } =
|
||||||
stateDeputyMunicipalitiesBatchSchema.parse(input)
|
stateDeputyMunicipalitiesBatchSchema.parse(input)
|
||||||
|
const enforceCas = options?.cas === true
|
||||||
// Already deduped by the schema's `.transform`; sorted only so a batch applies
|
// Already deduped by the schema's `.transform`; sorted only so a batch applies
|
||||||
// and reports in a stable order — `acquireTextAdvisoryLocks` sorts its own keys,
|
// and reports in a stable order — `acquireTextAdvisoryLocks` sorts its own keys,
|
||||||
// so the deadlock-avoidance ordering does not depend on this line.
|
// so the deadlock-avoidance ordering does not depend on this line.
|
||||||
|
|
@ -134,6 +137,16 @@ export const setStateDeputyMunicipalitiesBatchRecord = async (
|
||||||
const changedSlugs: string[] = []
|
const changedSlugs: string[] = []
|
||||||
|
|
||||||
for (const municipalityId of uniqueMunicipalityIds) {
|
for (const municipalityId of uniqueMunicipalityIds) {
|
||||||
|
const baseForMunicipality = municipalityBaseUpdatedAt?.[String(municipalityId)]
|
||||||
|
await assertCampaignDocCas(payload, {
|
||||||
|
collection: 'municipality',
|
||||||
|
id: municipalityId,
|
||||||
|
actor: currentActor,
|
||||||
|
enforceCas,
|
||||||
|
baseUpdatedAt: baseForMunicipality,
|
||||||
|
req,
|
||||||
|
})
|
||||||
|
|
||||||
// Row + field access verify the município is in the actor's scope
|
// Row + field access verify the município is in the actor's scope
|
||||||
// (`canUpdateMunicipality` for advisors, `canManageCampaignStaffField`
|
// (`canUpdateMunicipality` for advisors, `canManageCampaignStaffField`
|
||||||
// for the field) — an out-of-scope município throws here.
|
// for the field) — an out-of-scope município throws here.
|
||||||
|
|
@ -204,3 +217,22 @@ export const setStateDeputyMunicipalitiesBatch = async (
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const setStateDeputyMunicipalitiesBatchCas = async (
|
||||||
|
input: StateDeputyMunicipalitiesBatchInput,
|
||||||
|
) => {
|
||||||
|
const { payload, actor } = await getCampaignActionContext()
|
||||||
|
const result = await setStateDeputyMunicipalitiesBatchRecord(payload, actor, input, {
|
||||||
|
cas: true,
|
||||||
|
})
|
||||||
|
if (result.slugs.length > 0) {
|
||||||
|
revalidateStateDeputyMunicipalityPaths(result.stateDeputySlug, result.slugs)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
export const setStateDeputyMunicipalitiesBatchCasRecord = async (
|
||||||
|
payload: Payload,
|
||||||
|
actor: CampaignUser,
|
||||||
|
input: StateDeputyMunicipalitiesBatchInput,
|
||||||
|
) => setStateDeputyMunicipalitiesBatchRecord(payload, actor, input, { cas: true })
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,19 @@
|
||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import Link from 'next/link'
|
import Link from 'next/link'
|
||||||
import { useActionState, useState } from 'react'
|
import { useActionState, useEffect, useRef, useState, useSyncExternalStore, type FormEvent } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
import { ActivityDemandFields } from '@/components/campaign/activity/ActivityDemandFields'
|
import { ActivityDemandFields } from '@/components/campaign/activity/ActivityDemandFields'
|
||||||
import { ActivityTaskFields } from '@/components/campaign/activity/ActivityTaskFields'
|
import { ActivityTaskFields } from '@/components/campaign/activity/ActivityTaskFields'
|
||||||
|
import {
|
||||||
|
discardOpsActivityUpdateOutboxRow,
|
||||||
|
enqueueActivityUpdate,
|
||||||
|
readOpsActivityUpdateOutboxRow,
|
||||||
|
subscribeOpsActivityUpdateOutboxRow,
|
||||||
|
} from '@/components/campaign/opsSync/opsDomainOutbox'
|
||||||
|
import { activitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
import { AsyncSearchCombobox } from '@/components/campaign/shared/AsyncSearchCombobox'
|
import { AsyncSearchCombobox } from '@/components/campaign/shared/AsyncSearchCombobox'
|
||||||
import {
|
import {
|
||||||
ContactCombobox,
|
ContactCombobox,
|
||||||
|
|
@ -15,6 +24,7 @@ import {
|
||||||
type RelationOption,
|
type RelationOption,
|
||||||
} from '@/components/campaign/shared/RelationMultiSelect'
|
} from '@/components/campaign/shared/RelationMultiSelect'
|
||||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/Alert'
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/Alert'
|
||||||
|
import { Badge } from '@/components/ui/Badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
import { Checkbox } from '@/components/ui/Checkbox'
|
import { Checkbox } from '@/components/ui/Checkbox'
|
||||||
|
|
@ -33,12 +43,19 @@ import { Spinner } from '@/components/ui/Spinner'
|
||||||
import { Textarea } from '@/components/ui/textarea'
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/ToggleGroup'
|
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/ToggleGroup'
|
||||||
import { formatIsoAsBahiaDateTimeInput } from '@/lib/campaignTime'
|
import { formatIsoAsBahiaDateTimeInput } from '@/lib/campaignTime'
|
||||||
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
import { isContactSearchQueryReady } from '@/lib/contactSearchQuery'
|
import { isContactSearchQueryReady } from '@/lib/contactSearchQuery'
|
||||||
import {
|
import {
|
||||||
activityKindLabels,
|
activityKindLabels,
|
||||||
|
activityKinds,
|
||||||
activityOriginLabels,
|
activityOriginLabels,
|
||||||
|
activityOrigins,
|
||||||
activityStatusLabels,
|
activityStatusLabels,
|
||||||
|
activityStatuses,
|
||||||
|
type ActivityKind,
|
||||||
|
type ActivityOrigin,
|
||||||
} from '@/lib/schemas/activity'
|
} from '@/lib/schemas/activity'
|
||||||
|
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||||
import type { ActivityLeadershipOption } from '@/utilities/activityLeadershipOptions'
|
import type { ActivityLeadershipOption } from '@/utilities/activityLeadershipOptions'
|
||||||
import type { ActivityFormViewModel } from '@/utilities/activityViewModels'
|
import type { ActivityFormViewModel } from '@/utilities/activityViewModels'
|
||||||
import { fieldError } from '@/utilities/campaignFormFields'
|
import { fieldError } from '@/utilities/campaignFormFields'
|
||||||
|
|
@ -458,6 +475,23 @@ const ActivityFormFields = ({
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CONFLICT_TOAST_ID_PREFIX = 'ops-activity-update-conflict:'
|
||||||
|
|
||||||
|
const readOptionalText = (data: FormData, name: string): string | undefined => {
|
||||||
|
const raw = data.get(name)
|
||||||
|
return typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const readRelationshipIds = (data: FormData, name: string): number[] => {
|
||||||
|
const ids: number[] = []
|
||||||
|
for (const raw of data.getAll(name)) {
|
||||||
|
if (typeof raw !== 'string' || raw.trim() === '') continue
|
||||||
|
const value = Number(raw)
|
||||||
|
if (Number.isInteger(value) && value > 0) ids.push(value)
|
||||||
|
}
|
||||||
|
return [...new Set(ids)]
|
||||||
|
}
|
||||||
|
|
||||||
export const ActivityForm = ({
|
export const ActivityForm = ({
|
||||||
action,
|
action,
|
||||||
municipalityOptions,
|
municipalityOptions,
|
||||||
|
|
@ -468,26 +502,154 @@ export const ActivityForm = ({
|
||||||
submitLabel,
|
submitLabel,
|
||||||
searchContacts,
|
searchContacts,
|
||||||
searchLeaderships,
|
searchLeaderships,
|
||||||
|
opsHybridEnabled = resolveOpsHybridEnabled(),
|
||||||
}: ActivityFormFieldsProps & {
|
}: ActivityFormFieldsProps & {
|
||||||
action: ActivityFormAction
|
action: ActivityFormAction
|
||||||
submitLabel: string
|
submitLabel: string
|
||||||
|
opsHybridEnabled?: boolean
|
||||||
}) => {
|
}) => {
|
||||||
|
const router = useRouter()
|
||||||
const [state, formAction, pending] = useActionState(action, {})
|
const [state, formAction, pending] = useActionState(action, {})
|
||||||
|
const [hybridPending, setHybridPending] = useState(false)
|
||||||
|
const [hybridMessage, setHybridMessage] = useState<string | null>(null)
|
||||||
|
const previousOutboxStatusRef = useRef<string | undefined>(undefined)
|
||||||
|
const hybridUpdate = Boolean(opsHybridEnabled && activity)
|
||||||
|
|
||||||
|
const outboxRow = useSyncExternalStore(
|
||||||
|
(onStoreChange) =>
|
||||||
|
hybridUpdate && activity
|
||||||
|
? subscribeOpsActivityUpdateOutboxRow(activity.id, onStoreChange)
|
||||||
|
: () => undefined,
|
||||||
|
() =>
|
||||||
|
hybridUpdate && activity ? readOpsActivityUpdateOutboxRow(activity.id) : undefined,
|
||||||
|
() => undefined,
|
||||||
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const previous = previousOutboxStatusRef.current
|
||||||
|
previousOutboxStatusRef.current = outboxRow?.status
|
||||||
|
if (previous === 'pending' && outboxRow === undefined) {
|
||||||
|
router.refresh()
|
||||||
|
}
|
||||||
|
}, [outboxRow, router])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!hybridUpdate || !activity || outboxRow?.status !== 'conflict') return
|
||||||
|
const toastId = `${CONFLICT_TOAST_ID_PREFIX}${activity.id}`
|
||||||
|
toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
|
||||||
|
id: toastId,
|
||||||
|
duration: Infinity,
|
||||||
|
action: {
|
||||||
|
label: 'Manter o meu',
|
||||||
|
onClick: () => {
|
||||||
|
void enqueueActivityUpdate({
|
||||||
|
activityId: activity.id,
|
||||||
|
payload: outboxRow.payload,
|
||||||
|
baseUpdatedAt: outboxRow.serverUpdatedAt ?? null,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cancel: {
|
||||||
|
label: 'Usar o novo',
|
||||||
|
onClick: () => {
|
||||||
|
discardOpsActivityUpdateOutboxRow(activity.id)
|
||||||
|
router.refresh()
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
toast.dismiss(toastId)
|
||||||
|
}
|
||||||
|
}, [hybridUpdate, activity, outboxRow, router])
|
||||||
|
|
||||||
|
const onHybridSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault()
|
||||||
|
if (!activity) return
|
||||||
|
const data = new FormData(event.currentTarget)
|
||||||
|
const kindRaw = data.get('kind')
|
||||||
|
const statusRaw = data.get('status')
|
||||||
|
const kind =
|
||||||
|
typeof kindRaw === 'string' && activityKinds.includes(kindRaw as ActivityKind)
|
||||||
|
? (kindRaw as ActivityKind)
|
||||||
|
: undefined
|
||||||
|
const status =
|
||||||
|
typeof statusRaw === 'string' &&
|
||||||
|
activityStatuses.includes(statusRaw as (typeof activityStatuses)[number])
|
||||||
|
? (statusRaw as (typeof activityStatuses)[number])
|
||||||
|
: undefined
|
||||||
|
const originRaw = data.get('origin')
|
||||||
|
const origin =
|
||||||
|
typeof originRaw === 'string' && activityOrigins.includes(originRaw as ActivityOrigin)
|
||||||
|
? (originRaw as ActivityOrigin)
|
||||||
|
: undefined
|
||||||
|
const municipalityRaw = data.get('municipality')
|
||||||
|
const municipality =
|
||||||
|
typeof municipalityRaw === 'string' && Number.isInteger(Number(municipalityRaw))
|
||||||
|
? Number(municipalityRaw)
|
||||||
|
: undefined
|
||||||
|
const mirrorUpdatedAt = activitiesCollection.get(activity.id)?.updatedAt
|
||||||
|
|
||||||
|
setHybridPending(true)
|
||||||
|
setHybridMessage(null)
|
||||||
|
void enqueueActivityUpdate({
|
||||||
|
activityId: activity.id,
|
||||||
|
payload: {
|
||||||
|
...(kind ? { kind } : {}),
|
||||||
|
...(status ? { status } : {}),
|
||||||
|
...(origin ? { origin } : {}),
|
||||||
|
...(municipality ? { municipality } : {}),
|
||||||
|
description: readOptionalText(data, 'description') ?? null,
|
||||||
|
locality: readOptionalText(data, 'locality') ?? null,
|
||||||
|
organizations: readRelationshipIds(data, 'organizations'),
|
||||||
|
advisors: readRelationshipIds(data, 'advisors'),
|
||||||
|
deputyPresent: data.get('deputyPresent') === 'true' || data.get('deputyPresent') === 'on',
|
||||||
|
},
|
||||||
|
baseUpdatedAt: mirrorUpdatedAt ?? activity.updatedAt,
|
||||||
|
}).then(
|
||||||
|
() => {
|
||||||
|
setHybridPending(false)
|
||||||
|
setHybridMessage(
|
||||||
|
'Alterações enfileiradas (campos principais). Tarefas e novas demandas exigem conexão.',
|
||||||
|
)
|
||||||
|
},
|
||||||
|
(error: unknown) => {
|
||||||
|
setHybridPending(false)
|
||||||
|
setHybridMessage(
|
||||||
|
error instanceof Error ? error.message : 'Não foi possível enfileirar as alterações.',
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const busy = hybridUpdate ? hybridPending || outboxRow?.status === 'pending' : pending
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form action={formAction} className="flex max-w-3xl flex-col gap-6">
|
<form
|
||||||
|
action={hybridUpdate ? undefined : formAction}
|
||||||
|
onSubmit={hybridUpdate ? onHybridSubmit : undefined}
|
||||||
|
className="flex max-w-3xl flex-col gap-6"
|
||||||
|
>
|
||||||
{activity ? <input type="hidden" name="id" value={activity.id} /> : null}
|
{activity ? <input type="hidden" name="id" value={activity.id} /> : null}
|
||||||
{state.message ? (
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
{outboxRow?.status === 'pending' ? <Badge variant="estimate-pending">Pendente</Badge> : null}
|
||||||
|
{outboxRow?.status === 'conflict' ? <Badge variant="destructive">Conflito</Badge> : null}
|
||||||
|
</div>
|
||||||
|
{!hybridUpdate && state.message ? (
|
||||||
<Alert variant="destructive" aria-live="polite">
|
<Alert variant="destructive" aria-live="polite">
|
||||||
<AlertTitle>Não foi possível salvar</AlertTitle>
|
<AlertTitle>Não foi possível salvar</AlertTitle>
|
||||||
<AlertDescription>{state.message}</AlertDescription>
|
<AlertDescription>{state.message}</AlertDescription>
|
||||||
</Alert>
|
</Alert>
|
||||||
) : null}
|
) : null}
|
||||||
{state.existingHref ? (
|
{!hybridUpdate && state.existingHref ? (
|
||||||
<Button asChild variant="outline" className="min-h-11 w-fit">
|
<Button asChild variant="outline" className="min-h-11 w-fit">
|
||||||
<Link href={state.existingHref}>Abrir atividade existente</Link>
|
<Link href={state.existingHref}>Abrir atividade existente</Link>
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
|
{hybridMessage ? (
|
||||||
|
<p className="text-sm text-muted-foreground" role="status">
|
||||||
|
{hybridMessage}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
<ActivityFormFields
|
<ActivityFormFields
|
||||||
municipalityOptions={municipalityOptions}
|
municipalityOptions={municipalityOptions}
|
||||||
organizationOptions={organizationOptions}
|
organizationOptions={organizationOptions}
|
||||||
|
|
@ -505,9 +667,9 @@ export const ActivityForm = ({
|
||||||
Cancelar
|
Cancelar
|
||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="submit" className="min-h-11" disabled={pending}>
|
<Button type="submit" className="min-h-11" disabled={busy}>
|
||||||
{pending ? <Spinner data-icon="inline-start" /> : null}
|
{busy ? <Spinner data-icon="inline-start" /> : null}
|
||||||
{pending ? 'Salvando…' : submitLabel}
|
{busy ? 'Salvando…' : submitLabel}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,38 @@
|
||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useActionState } from 'react'
|
import {
|
||||||
|
useActionState,
|
||||||
|
useEffect,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
useSyncExternalStore,
|
||||||
|
type FormEvent,
|
||||||
|
} from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import {
|
||||||
|
discardOpsDemandTransitionOutboxRow,
|
||||||
|
enqueueDemandTransition,
|
||||||
|
readOpsDemandTransitionOutboxRow,
|
||||||
|
subscribeOpsDemandTransitionOutboxRow,
|
||||||
|
} from '@/components/campaign/opsSync/opsDomainOutbox'
|
||||||
|
import { demandsCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
||||||
|
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 { Textarea } from '@/components/ui/textarea'
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
import {
|
import {
|
||||||
|
campaignDemandStatuses,
|
||||||
campaignDemandTransitionLabels,
|
campaignDemandTransitionLabels,
|
||||||
campaignDemandTransitions,
|
campaignDemandTransitions,
|
||||||
type CampaignDemandStatus,
|
type CampaignDemandStatus,
|
||||||
} from '@/lib/schemas/campaignDemand'
|
} from '@/lib/schemas/campaignDemand'
|
||||||
|
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'
|
||||||
|
|
||||||
|
|
@ -27,11 +47,16 @@ type DemandWorkflowCardProps = {
|
||||||
/** Coordinator or candidate — the roles allowed to decide escalated demands. */
|
/** Coordinator or candidate — the roles allowed to decide escalated demands. */
|
||||||
canDecideEscalated: boolean
|
canDecideEscalated: boolean
|
||||||
currentCost: number | null
|
currentCost: number | null
|
||||||
|
/** OH13 — CAS base when OPS_HYBRID outbox path is on. */
|
||||||
|
updatedAt?: string
|
||||||
|
opsHybridEnabled?: boolean
|
||||||
transitionFormAction: FormAction
|
transitionFormAction: FormAction
|
||||||
costFormAction: FormAction
|
costFormAction: FormAction
|
||||||
receiptFormAction: FormAction
|
receiptFormAction: FormAction
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CONFLICT_TOAST_ID_PREFIX = 'ops-demand-transition-conflict:'
|
||||||
|
|
||||||
const transitionVariant = (target: CampaignDemandStatus) =>
|
const transitionVariant = (target: CampaignDemandStatus) =>
|
||||||
target === 'aprovada' ? 'default' : target === 'rejeitada' ? 'destructive' : 'secondary'
|
target === 'aprovada' ? 'default' : target === 'rejeitada' ? 'destructive' : 'secondary'
|
||||||
|
|
||||||
|
|
@ -41,16 +66,69 @@ export const DemandWorkflowCard = ({
|
||||||
status,
|
status,
|
||||||
canDecideEscalated,
|
canDecideEscalated,
|
||||||
currentCost,
|
currentCost,
|
||||||
|
updatedAt,
|
||||||
|
opsHybridEnabled = resolveOpsHybridEnabled(),
|
||||||
transitionFormAction,
|
transitionFormAction,
|
||||||
costFormAction,
|
costFormAction,
|
||||||
receiptFormAction,
|
receiptFormAction,
|
||||||
}: DemandWorkflowCardProps) => {
|
}: DemandWorkflowCardProps) => {
|
||||||
|
const router = useRouter()
|
||||||
const [transitionState, submitTransition, transitionPending] = useActionState(
|
const [transitionState, submitTransition, transitionPending] = useActionState(
|
||||||
transitionFormAction,
|
transitionFormAction,
|
||||||
{},
|
{},
|
||||||
)
|
)
|
||||||
const [costState, submitCost, costPending] = useActionState(costFormAction, {})
|
const [costState, submitCost, costPending] = useActionState(costFormAction, {})
|
||||||
const [receiptState, submitReceipt, receiptPending] = useActionState(receiptFormAction, {})
|
const [receiptState, submitReceipt, receiptPending] = useActionState(receiptFormAction, {})
|
||||||
|
const [hybridPending, setHybridPending] = useState(false)
|
||||||
|
const [hybridMessage, setHybridMessage] = useState<string | null>(null)
|
||||||
|
const previousOutboxStatusRef = useRef<string | undefined>(undefined)
|
||||||
|
|
||||||
|
const outboxRow = useSyncExternalStore(
|
||||||
|
(onStoreChange) =>
|
||||||
|
opsHybridEnabled
|
||||||
|
? subscribeOpsDemandTransitionOutboxRow(demandID, onStoreChange)
|
||||||
|
: () => undefined,
|
||||||
|
() => (opsHybridEnabled ? readOpsDemandTransitionOutboxRow(demandID) : undefined),
|
||||||
|
() => undefined,
|
||||||
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const previous = previousOutboxStatusRef.current
|
||||||
|
previousOutboxStatusRef.current = outboxRow?.statusSync
|
||||||
|
if (previous === 'pending' && outboxRow === undefined) {
|
||||||
|
router.refresh()
|
||||||
|
}
|
||||||
|
}, [outboxRow, router])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!opsHybridEnabled || outboxRow?.statusSync !== 'conflict') return
|
||||||
|
const toastId = `${CONFLICT_TOAST_ID_PREFIX}${demandID}`
|
||||||
|
toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
|
||||||
|
id: toastId,
|
||||||
|
duration: Infinity,
|
||||||
|
action: {
|
||||||
|
label: 'Manter o meu',
|
||||||
|
onClick: () => {
|
||||||
|
void enqueueDemandTransition({
|
||||||
|
demandId: demandID,
|
||||||
|
status: outboxRow.status,
|
||||||
|
decisionNote: outboxRow.decisionNote,
|
||||||
|
baseUpdatedAt: outboxRow.serverUpdatedAt ?? null,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cancel: {
|
||||||
|
label: 'Usar o novo',
|
||||||
|
onClick: () => {
|
||||||
|
discardOpsDemandTransitionOutboxRow(demandID)
|
||||||
|
router.refresh()
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
toast.dismiss(toastId)
|
||||||
|
}
|
||||||
|
}, [opsHybridEnabled, outboxRow, demandID, router])
|
||||||
|
|
||||||
const availableTransitions = campaignDemandTransitions[status].filter(
|
const availableTransitions = campaignDemandTransitions[status].filter(
|
||||||
(target) =>
|
(target) =>
|
||||||
|
|
@ -59,15 +137,72 @@ export const DemandWorkflowCard = ({
|
||||||
(target !== 'aprovada' && target !== 'rejeitada'),
|
(target !== 'aprovada' && target !== 'rejeitada'),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const onHybridTransition = (event: FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault()
|
||||||
|
const form = event.currentTarget
|
||||||
|
const data = new FormData(form)
|
||||||
|
const submitter = (event.nativeEvent as SubmitEvent).submitter
|
||||||
|
const rawStatus =
|
||||||
|
submitter instanceof HTMLButtonElement && submitter.name === 'status'
|
||||||
|
? submitter.value
|
||||||
|
: data.get('status')
|
||||||
|
if (
|
||||||
|
typeof rawStatus !== 'string' ||
|
||||||
|
!campaignDemandStatuses.includes(rawStatus as CampaignDemandStatus)
|
||||||
|
) {
|
||||||
|
setHybridMessage('Status de demanda inválido.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const decisionNoteRaw = data.get('decisionNote')
|
||||||
|
const decisionNote =
|
||||||
|
typeof decisionNoteRaw === 'string' && decisionNoteRaw.trim() !== ''
|
||||||
|
? decisionNoteRaw.trim()
|
||||||
|
: null
|
||||||
|
const mirrorUpdatedAt = demandsCollection.get(demandID)?.updatedAt
|
||||||
|
|
||||||
|
setHybridPending(true)
|
||||||
|
setHybridMessage(null)
|
||||||
|
void enqueueDemandTransition({
|
||||||
|
demandId: demandID,
|
||||||
|
status: rawStatus as CampaignDemandStatus,
|
||||||
|
decisionNote,
|
||||||
|
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
|
||||||
|
}).then(
|
||||||
|
() => {
|
||||||
|
setHybridPending(false)
|
||||||
|
setHybridMessage('Decisão enfileirada. Será enviada ao reconectar.')
|
||||||
|
},
|
||||||
|
(error: unknown) => {
|
||||||
|
setHybridPending(false)
|
||||||
|
setHybridMessage(
|
||||||
|
error instanceof Error ? error.message : 'Não foi possível enfileirar a decisão.',
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const transitionBusy =
|
||||||
|
opsHybridEnabled
|
||||||
|
? hybridPending || outboxRow?.statusSync === 'pending'
|
||||||
|
: transitionPending
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
aria-labelledby="demand-workflow-title"
|
aria-labelledby="demand-workflow-title"
|
||||||
className="flex flex-col gap-6 rounded-xl border p-4"
|
className="flex flex-col gap-6 rounded-xl border p-4"
|
||||||
>
|
>
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
<h2 id="demand-workflow-title" className="text-base font-medium">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
Tratar demanda
|
<h2 id="demand-workflow-title" className="text-base font-medium">
|
||||||
</h2>
|
Tratar demanda
|
||||||
|
</h2>
|
||||||
|
{outboxRow?.statusSync === 'pending' ? (
|
||||||
|
<Badge variant="estimate-pending">Pendente</Badge>
|
||||||
|
) : null}
|
||||||
|
{outboxRow?.statusSync === 'conflict' ? (
|
||||||
|
<Badge variant="destructive">Conflito</Badge>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
O assessor analisa e decide — ou escala ao Coordenador Geral. Demandas escaladas são
|
O assessor analisa e decide — ou escala ao Coordenador Geral. Demandas escaladas são
|
||||||
decididas somente por ele.
|
decididas somente por ele.
|
||||||
|
|
@ -75,7 +210,11 @@ export const DemandWorkflowCard = ({
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{availableTransitions.length ? (
|
{availableTransitions.length ? (
|
||||||
<form action={submitTransition} className="flex flex-col gap-3">
|
<form
|
||||||
|
action={opsHybridEnabled ? undefined : submitTransition}
|
||||||
|
onSubmit={opsHybridEnabled ? onHybridTransition : undefined}
|
||||||
|
className="flex flex-col gap-3"
|
||||||
|
>
|
||||||
<input type="hidden" name="demandId" value={demandID} />
|
<input type="hidden" name="demandId" value={demandID} />
|
||||||
<Field>
|
<Field>
|
||||||
<FieldLabel htmlFor={`demand-note-${demandID}`}>Nota da decisão</FieldLabel>
|
<FieldLabel htmlFor={`demand-note-${demandID}`}>Nota da decisão</FieldLabel>
|
||||||
|
|
@ -95,24 +234,29 @@ export const DemandWorkflowCard = ({
|
||||||
name="status"
|
name="status"
|
||||||
value={target}
|
value={target}
|
||||||
variant={transitionVariant(target)}
|
variant={transitionVariant(target)}
|
||||||
disabled={transitionPending}
|
disabled={transitionBusy}
|
||||||
className="min-h-11"
|
className="min-h-11"
|
||||||
>
|
>
|
||||||
{transitionPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
{transitionBusy ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
||||||
{campaignDemandTransitionLabels[target]}
|
{campaignDemandTransitionLabels[target]}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
{transitionState.message && transitionState.status !== 'success' ? (
|
{!opsHybridEnabled && transitionState.message && transitionState.status !== 'success' ? (
|
||||||
<Alert variant="destructive">
|
<Alert variant="destructive">
|
||||||
<AlertDescription>{transitionState.message}</AlertDescription>
|
<AlertDescription>{transitionState.message}</AlertDescription>
|
||||||
</Alert>
|
</Alert>
|
||||||
) : null}
|
) : null}
|
||||||
{transitionState.status === 'success' ? (
|
{!opsHybridEnabled && transitionState.status === 'success' ? (
|
||||||
<Alert>
|
<Alert>
|
||||||
<AlertDescription>{transitionState.message}</AlertDescription>
|
<AlertDescription>{transitionState.message}</AlertDescription>
|
||||||
</Alert>
|
</Alert>
|
||||||
) : null}
|
) : null}
|
||||||
|
{hybridMessage ? (
|
||||||
|
<p className="text-sm text-muted-foreground" role="status">
|
||||||
|
{hybridMessage}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
</form>
|
</form>
|
||||||
) : (
|
) : (
|
||||||
<p className="text-sm text-muted-foreground">Esta demanda já foi decidida.</p>
|
<p className="text-sm text-muted-foreground">Esta demanda já foi decidida.</p>
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,14 @@
|
||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useActionState } from 'react'
|
import { useActionState, useState, type FormEvent } from 'react'
|
||||||
|
|
||||||
|
import { enqueueLeadershipCreate } from '@/components/campaign/opsSync/opsDomainOutbox'
|
||||||
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
||||||
import {
|
import {
|
||||||
RelationMultiSelect,
|
RelationMultiSelect,
|
||||||
type RelationOption,
|
type RelationOption,
|
||||||
} from '@/components/campaign/shared/RelationMultiSelect'
|
} from '@/components/campaign/shared/RelationMultiSelect'
|
||||||
|
import { Badge } from '@/components/ui/Badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Checkbox } from '@/components/ui/Checkbox'
|
import { Checkbox } from '@/components/ui/Checkbox'
|
||||||
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
|
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
|
||||||
|
|
@ -14,7 +16,12 @@ 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 { leadershipSupportStatuses } from '@/lib/schemas/leadership'
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
|
import {
|
||||||
|
isSupportStatus,
|
||||||
|
leadershipSupportStatuses,
|
||||||
|
type SupportStatus,
|
||||||
|
} from '@/lib/schemas/leadership'
|
||||||
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
||||||
import { fieldError } from '@/utilities/campaignFormFields'
|
import { fieldError } from '@/utilities/campaignFormFields'
|
||||||
import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
|
import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
|
||||||
|
|
@ -28,6 +35,17 @@ type LeadershipFormProps = {
|
||||||
state: CampaignFormActionState,
|
state: CampaignFormActionState,
|
||||||
formData: FormData,
|
formData: FormData,
|
||||||
) => Promise<CampaignFormActionState>
|
) => Promise<CampaignFormActionState>
|
||||||
|
opsHybridEnabled?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const readRelationshipIds = (data: FormData, name: string): number[] => {
|
||||||
|
const ids: number[] = []
|
||||||
|
for (const raw of data.getAll(name)) {
|
||||||
|
if (typeof raw !== 'string' || raw.trim() === '') continue
|
||||||
|
const value = Number(raw)
|
||||||
|
if (Number.isInteger(value) && value > 0) ids.push(value)
|
||||||
|
}
|
||||||
|
return [...new Set(ids)]
|
||||||
}
|
}
|
||||||
|
|
||||||
export const LeadershipForm = ({
|
export const LeadershipForm = ({
|
||||||
|
|
@ -36,11 +54,76 @@ export const LeadershipForm = ({
|
||||||
stateDeputyOptions,
|
stateDeputyOptions,
|
||||||
initialMunicipalityIDs,
|
initialMunicipalityIDs,
|
||||||
formAction,
|
formAction,
|
||||||
|
opsHybridEnabled = resolveOpsHybridEnabled(),
|
||||||
}: LeadershipFormProps) => {
|
}: LeadershipFormProps) => {
|
||||||
const [state, submitAction, isPending] = useActionState(formAction, {})
|
const [state, submitAction, isPending] = useActionState(formAction, {})
|
||||||
|
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 name = data.get('name')
|
||||||
|
const phone = data.get('phone')
|
||||||
|
if (typeof name !== 'string' || name.trim().length < 2) {
|
||||||
|
setHybridMessage('Informe o nome completo.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (typeof phone !== 'string' || phone.trim() === '') {
|
||||||
|
setHybridMessage('Informe o celular.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const supportStatusRaw = data.get('supportStatus')
|
||||||
|
const supportStatus =
|
||||||
|
typeof supportStatusRaw === 'string' && isSupportStatus(supportStatusRaw)
|
||||||
|
? (supportStatusRaw as SupportStatus)
|
||||||
|
: 'a_abordar'
|
||||||
|
const exclusiveValues = data.getAll('exclusive')
|
||||||
|
const emailRaw = data.get('email')
|
||||||
|
const notesRaw = data.get('notes')
|
||||||
|
|
||||||
|
setHybridPending(true)
|
||||||
|
setHybridMessage(null)
|
||||||
|
void enqueueLeadershipCreate({
|
||||||
|
clientId: crypto.randomUUID(),
|
||||||
|
name: name.trim(),
|
||||||
|
phone: phone.trim(),
|
||||||
|
email: typeof emailRaw === 'string' && emailRaw.trim() !== '' ? emailRaw.trim() : null,
|
||||||
|
municipalities: readRelationshipIds(data, 'municipalities'),
|
||||||
|
organizations: readRelationshipIds(data, 'organizations'),
|
||||||
|
stateDeputies: readRelationshipIds(data, 'stateDeputies'),
|
||||||
|
exclusive: exclusiveValues.length === 0 ? true : exclusiveValues.at(-1) === 'true',
|
||||||
|
supportStatus,
|
||||||
|
notes: typeof notesRaw === 'string' && notesRaw.trim() !== '' ? notesRaw.trim() : undefined,
|
||||||
|
}).then(
|
||||||
|
() => {
|
||||||
|
setHybridPending(false)
|
||||||
|
setHybridMessage(
|
||||||
|
'Cadastro enfileirado. Será enviado ao reconectar — a ficha aparece depois da sincronização.',
|
||||||
|
)
|
||||||
|
form.reset()
|
||||||
|
},
|
||||||
|
(error: unknown) => {
|
||||||
|
setHybridPending(false)
|
||||||
|
setHybridMessage(
|
||||||
|
error instanceof Error ? error.message : 'Não foi possível enfileirar o cadastro.',
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const pending = opsHybridEnabled ? hybridPending : isPending
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form action={submitAction} className="flex max-w-2xl flex-col gap-4">
|
<form
|
||||||
|
action={opsHybridEnabled ? undefined : submitAction}
|
||||||
|
onSubmit={opsHybridEnabled ? onHybridSubmit : undefined}
|
||||||
|
className="flex max-w-2xl flex-col gap-4"
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
{hybridPending ? <Badge variant="estimate-pending">Pendente</Badge> : null}
|
||||||
|
</div>
|
||||||
<Field>
|
<Field>
|
||||||
<FieldLabel htmlFor="leadership-name">Nome completo</FieldLabel>
|
<FieldLabel htmlFor="leadership-name">Nome completo</FieldLabel>
|
||||||
<Input
|
<Input
|
||||||
|
|
@ -134,9 +217,16 @@ export const LeadershipForm = ({
|
||||||
<Textarea id="leadership-notes" name="notes" rows={3} maxLength={3000} />
|
<Textarea id="leadership-notes" name="notes" rows={3} maxLength={3000} />
|
||||||
</Field>
|
</Field>
|
||||||
|
|
||||||
{state.status !== 'success' ? <CampaignFormActionMessage state={state} /> : null}
|
{!opsHybridEnabled && state.status !== 'success' ? (
|
||||||
<Button type="submit" disabled={isPending} className="min-h-11 self-start">
|
<CampaignFormActionMessage state={state} />
|
||||||
{isPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
) : null}
|
||||||
|
{hybridMessage ? (
|
||||||
|
<p className="text-sm text-muted-foreground" role="status">
|
||||||
|
{hybridMessage}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
<Button type="submit" disabled={pending} className="min-h-11 self-start">
|
||||||
|
{pending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
||||||
Cadastrar liderança
|
Cadastrar liderança
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|
|
||||||
|
|
@ -1,24 +1,52 @@
|
||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useActionState } from 'react'
|
import { useActionState, useEffect, useRef, useState, useSyncExternalStore, type FormEvent } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import {
|
||||||
|
discardOpsLeadershipUpdateOutboxRow,
|
||||||
|
enqueueLeadershipUpdate,
|
||||||
|
readOpsLeadershipUpdateOutboxRow,
|
||||||
|
subscribeOpsLeadershipUpdateOutboxRow,
|
||||||
|
} from '@/components/campaign/opsSync/opsDomainOutbox'
|
||||||
|
import { leadershipsCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
||||||
import {
|
import {
|
||||||
RelationMultiSelect,
|
RelationMultiSelect,
|
||||||
type RelationOption,
|
type RelationOption,
|
||||||
} from '@/components/campaign/shared/RelationMultiSelect'
|
} from '@/components/campaign/shared/RelationMultiSelect'
|
||||||
|
import { Badge } from '@/components/ui/Badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Checkbox } from '@/components/ui/Checkbox'
|
import { Checkbox } from '@/components/ui/Checkbox'
|
||||||
import { Field, FieldLabel } from '@/components/ui/field'
|
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 { leadershipSupportStatuses } from '@/lib/schemas/leadership'
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
|
import {
|
||||||
|
isSupportStatus,
|
||||||
|
leadershipSupportStatuses,
|
||||||
|
type SupportStatus,
|
||||||
|
} from '@/lib/schemas/leadership'
|
||||||
|
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'
|
||||||
import type { LeadershipDetailViewModel } from '@/utilities/leadership/leadershipData'
|
import type { LeadershipDetailViewModel } from '@/utilities/leadership/leadershipData'
|
||||||
import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
|
import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
|
||||||
|
|
||||||
|
const CONFLICT_TOAST_ID_PREFIX = 'ops-leadership-update-conflict:'
|
||||||
|
|
||||||
|
const readRelationshipIds = (data: FormData, name: string): number[] => {
|
||||||
|
const ids: number[] = []
|
||||||
|
for (const raw of data.getAll(name)) {
|
||||||
|
if (typeof raw !== 'string' || raw.trim() === '') continue
|
||||||
|
const value = Number(raw)
|
||||||
|
if (Number.isInteger(value) && value > 0) ids.push(value)
|
||||||
|
}
|
||||||
|
return [...new Set(ids)]
|
||||||
|
}
|
||||||
|
|
||||||
type LeadershipInternalFormProps = {
|
type LeadershipInternalFormProps = {
|
||||||
leadership: LeadershipDetailViewModel
|
leadership: LeadershipDetailViewModel
|
||||||
municipalityOptions: RelationOption[]
|
municipalityOptions: RelationOption[]
|
||||||
|
|
@ -28,6 +56,7 @@ type LeadershipInternalFormProps = {
|
||||||
state: CampaignFormActionState,
|
state: CampaignFormActionState,
|
||||||
formData: FormData,
|
formData: FormData,
|
||||||
) => Promise<CampaignFormActionState>
|
) => Promise<CampaignFormActionState>
|
||||||
|
opsHybridEnabled?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Staff-only internal evaluation + links (municipalities, organizations). */
|
/** Staff-only internal evaluation + links (municipalities, organizations). */
|
||||||
|
|
@ -37,12 +66,119 @@ export const LeadershipInternalForm = ({
|
||||||
organizationOptions,
|
organizationOptions,
|
||||||
stateDeputyOptions,
|
stateDeputyOptions,
|
||||||
formAction,
|
formAction,
|
||||||
|
opsHybridEnabled = resolveOpsHybridEnabled(),
|
||||||
}: LeadershipInternalFormProps) => {
|
}: LeadershipInternalFormProps) => {
|
||||||
|
const router = useRouter()
|
||||||
const [state, submitAction, isPending] = useActionState(formAction, {})
|
const [state, submitAction, isPending] = useActionState(formAction, {})
|
||||||
|
const [hybridPending, setHybridPending] = useState(false)
|
||||||
|
const [hybridMessage, setHybridMessage] = useState<string | null>(null)
|
||||||
|
const previousOutboxStatusRef = useRef<string | undefined>(undefined)
|
||||||
|
|
||||||
|
const outboxRow = useSyncExternalStore(
|
||||||
|
(onStoreChange) =>
|
||||||
|
opsHybridEnabled
|
||||||
|
? subscribeOpsLeadershipUpdateOutboxRow(leadership.id, onStoreChange)
|
||||||
|
: () => undefined,
|
||||||
|
() => (opsHybridEnabled ? readOpsLeadershipUpdateOutboxRow(leadership.id) : undefined),
|
||||||
|
() => undefined,
|
||||||
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const previous = previousOutboxStatusRef.current
|
||||||
|
previousOutboxStatusRef.current = outboxRow?.status
|
||||||
|
if (previous === 'pending' && outboxRow === undefined) {
|
||||||
|
router.refresh()
|
||||||
|
}
|
||||||
|
}, [outboxRow, router])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!opsHybridEnabled || outboxRow?.status !== 'conflict') return
|
||||||
|
const toastId = `${CONFLICT_TOAST_ID_PREFIX}${leadership.id}`
|
||||||
|
toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
|
||||||
|
id: toastId,
|
||||||
|
duration: Infinity,
|
||||||
|
action: {
|
||||||
|
label: 'Manter o meu',
|
||||||
|
onClick: () => {
|
||||||
|
void enqueueLeadershipUpdate({
|
||||||
|
leadershipId: leadership.id,
|
||||||
|
municipalities: outboxRow.municipalities,
|
||||||
|
organizations: outboxRow.organizations,
|
||||||
|
stateDeputies: outboxRow.stateDeputies,
|
||||||
|
exclusive: outboxRow.exclusive,
|
||||||
|
supportStatus: outboxRow.supportStatus,
|
||||||
|
notes: outboxRow.notes,
|
||||||
|
baseUpdatedAt: outboxRow.serverUpdatedAt ?? null,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cancel: {
|
||||||
|
label: 'Usar o novo',
|
||||||
|
onClick: () => {
|
||||||
|
discardOpsLeadershipUpdateOutboxRow(leadership.id)
|
||||||
|
router.refresh()
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
toast.dismiss(toastId)
|
||||||
|
}
|
||||||
|
}, [opsHybridEnabled, outboxRow, leadership.id, router])
|
||||||
|
|
||||||
|
const onHybridSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault()
|
||||||
|
const form = event.currentTarget
|
||||||
|
const data = new FormData(form)
|
||||||
|
const supportStatusRaw = data.get('supportStatus')
|
||||||
|
const supportStatus =
|
||||||
|
typeof supportStatusRaw === 'string' && isSupportStatus(supportStatusRaw)
|
||||||
|
? (supportStatusRaw as SupportStatus)
|
||||||
|
: undefined
|
||||||
|
const mirrorUpdatedAt = leadershipsCollection.get(leadership.id)?.updatedAt
|
||||||
|
|
||||||
|
setHybridPending(true)
|
||||||
|
setHybridMessage(null)
|
||||||
|
void enqueueLeadershipUpdate({
|
||||||
|
leadershipId: leadership.id,
|
||||||
|
municipalities: readRelationshipIds(data, 'municipalities'),
|
||||||
|
organizations: readRelationshipIds(data, 'organizations'),
|
||||||
|
stateDeputies: readRelationshipIds(data, 'stateDeputies'),
|
||||||
|
exclusive: data.get('exclusive') === 'true',
|
||||||
|
supportStatus,
|
||||||
|
notes: (() => {
|
||||||
|
const raw = data.get('notes')
|
||||||
|
return typeof raw === 'string' ? raw : null
|
||||||
|
})(),
|
||||||
|
baseUpdatedAt: mirrorUpdatedAt ?? leadership.updatedAt,
|
||||||
|
}).then(
|
||||||
|
() => {
|
||||||
|
setHybridPending(false)
|
||||||
|
setHybridMessage('Alterações enfileiradas. Serão enviadas ao reconectar.')
|
||||||
|
},
|
||||||
|
(error: unknown) => {
|
||||||
|
setHybridPending(false)
|
||||||
|
setHybridMessage(
|
||||||
|
error instanceof Error ? error.message : 'Não foi possível enfileirar as alterações.',
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const pending = opsHybridEnabled ? hybridPending || outboxRow?.status === 'pending' : isPending
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form action={submitAction} className="flex max-w-2xl flex-col gap-4">
|
<form
|
||||||
<input type="hidden" name="leadershipId" value={leadership.id} />
|
action={opsHybridEnabled ? undefined : submitAction}
|
||||||
|
onSubmit={opsHybridEnabled ? onHybridSubmit : undefined}
|
||||||
|
className="flex max-w-2xl flex-col gap-4"
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<input type="hidden" name="leadershipId" value={leadership.id} />
|
||||||
|
{outboxRow?.status === 'pending' ? <Badge variant="estimate-pending">Pendente</Badge> : null}
|
||||||
|
{outboxRow?.status === 'conflict' ? (
|
||||||
|
<Badge variant="destructive">Conflito</Badge>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
<RelationMultiSelect
|
<RelationMultiSelect
|
||||||
name="municipalities"
|
name="municipalities"
|
||||||
|
|
@ -111,9 +247,14 @@ export const LeadershipInternalForm = ({
|
||||||
/>
|
/>
|
||||||
</Field>
|
</Field>
|
||||||
|
|
||||||
<CampaignFormActionMessage state={state} />
|
{!opsHybridEnabled ? <CampaignFormActionMessage state={state} /> : null}
|
||||||
<Button type="submit" disabled={isPending} className="min-h-11 self-start">
|
{hybridMessage ? (
|
||||||
{isPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
<p className="text-sm text-muted-foreground" role="status">
|
||||||
|
{hybridMessage}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
<Button type="submit" disabled={pending} className="min-h-11 self-start">
|
||||||
|
{pending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
||||||
Salvar
|
Salvar
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|
|
||||||
|
|
@ -2,12 +2,15 @@
|
||||||
|
|
||||||
import type { LeadershipListSupportStatusResponse } from '@/app/(campaign)/campanha/(app)/liderancas/support-status/types'
|
import type { LeadershipListSupportStatusResponse } from '@/app/(campaign)/campanha/(app)/liderancas/support-status/types'
|
||||||
import { SupportStatusBadge } from '@/components/campaign/leadership/SupportStatusBadge'
|
import { SupportStatusBadge } from '@/components/campaign/leadership/SupportStatusBadge'
|
||||||
|
import { enqueueLeadershipUpdate } from '@/components/campaign/opsSync/opsDomainOutbox'
|
||||||
|
import { leadershipsCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
import { CampaignCellEditOverlay } from '@/components/campaign/shared/CampaignCellEditOverlay'
|
import { CampaignCellEditOverlay } from '@/components/campaign/shared/CampaignCellEditOverlay'
|
||||||
import { useCampaignCellAutosave } from '@/components/campaign/shared/useCampaignCellAutosave'
|
import { useCampaignCellAutosave } from '@/components/campaign/shared/useCampaignCellAutosave'
|
||||||
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
||||||
import { Field, FieldLabel } from '@/components/ui/field'
|
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 { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
import {
|
import {
|
||||||
isSupportStatus,
|
isSupportStatus,
|
||||||
leadershipSupportStatuses,
|
leadershipSupportStatuses,
|
||||||
|
|
@ -23,12 +26,16 @@ const DEFAULT_STATUS: SupportStatus = 'a_abordar'
|
||||||
type LeadershipListSupportStatusControlProps = {
|
type LeadershipListSupportStatusControlProps = {
|
||||||
leadershipID: number
|
leadershipID: number
|
||||||
status: SupportStatus | null
|
status: SupportStatus | null
|
||||||
|
/** OH13 — CAS base when OPS_HYBRID outbox path is on. */
|
||||||
|
updatedAt?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export const LeadershipListSupportStatusControl = ({
|
export const LeadershipListSupportStatusControl = ({
|
||||||
leadershipID,
|
leadershipID,
|
||||||
status,
|
status,
|
||||||
|
updatedAt,
|
||||||
}: LeadershipListSupportStatusControlProps) => {
|
}: LeadershipListSupportStatusControlProps) => {
|
||||||
|
const opsHybrid = resolveOpsHybridEnabled()
|
||||||
const { open, onOpenChange, value, change, isPending, errorMessage, statusMessage } =
|
const { open, onOpenChange, value, change, isPending, errorMessage, statusMessage } =
|
||||||
useCampaignCellAutosave<SupportStatus, LeadershipListSupportStatusResponse>({
|
useCampaignCellAutosave<SupportStatus, LeadershipListSupportStatusResponse>({
|
||||||
value: status ?? DEFAULT_STATUS,
|
value: status ?? DEFAULT_STATUS,
|
||||||
|
|
@ -38,6 +45,24 @@ export const LeadershipListSupportStatusControl = ({
|
||||||
readSaved: (payload) => payload.savedSupportStatus,
|
readSaved: (payload) => payload.savedSupportStatus,
|
||||||
errorMessage: SAVE_ERROR_MESSAGE,
|
errorMessage: SAVE_ERROR_MESSAGE,
|
||||||
pendingMessage: 'Salvando status de apoio.',
|
pendingMessage: 'Salvando status de apoio.',
|
||||||
|
persist: opsHybrid
|
||||||
|
? async (supportStatus) => {
|
||||||
|
const mirrorUpdatedAt = leadershipsCollection.get(leadershipID)?.updatedAt
|
||||||
|
await enqueueLeadershipUpdate({
|
||||||
|
leadershipId: leadershipID,
|
||||||
|
supportStatus,
|
||||||
|
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
payload: {
|
||||||
|
status: 'success',
|
||||||
|
message: 'Status de apoio atualizado.',
|
||||||
|
savedSupportStatus: supportStatus,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
})
|
})
|
||||||
|
|
||||||
const handleStatusChange = (raw: string) => {
|
const handleStatusChange = (raw: string) => {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
|
import { clearOpsDomainOutboxForLogout } from '@/components/campaign/opsSync/opsDomainOutbox'
|
||||||
import { clearOpsEstimateOutboxForLogout } from '@/components/campaign/opsSync/opsEstimateOutbox'
|
import { clearOpsEstimateOutboxForLogout } from '@/components/campaign/opsSync/opsEstimateOutbox'
|
||||||
import {
|
import {
|
||||||
abortOpsMirrorSync,
|
abortOpsMirrorSync,
|
||||||
|
|
@ -14,6 +15,10 @@ import { clearOpsMunicipalityOutboxForLogout } from '@/components/campaign/opsSy
|
||||||
*/
|
*/
|
||||||
export const clearCampaignOpsStorage = async (): Promise<void> => {
|
export const clearCampaignOpsStorage = async (): Promise<void> => {
|
||||||
abortOpsMirrorSync()
|
abortOpsMirrorSync()
|
||||||
await Promise.all([clearOpsEstimateOutboxForLogout(), clearOpsMunicipalityOutboxForLogout()])
|
await Promise.all([
|
||||||
|
clearOpsEstimateOutboxForLogout(),
|
||||||
|
clearOpsMunicipalityOutboxForLogout(),
|
||||||
|
clearOpsDomainOutboxForLogout(),
|
||||||
|
])
|
||||||
await clearOpsMirrorPersistenceForLogout()
|
await clearOpsMirrorPersistenceForLogout()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
968
src/components/campaign/opsSync/opsDomainOutbox.ts
Normal file
968
src/components/campaign/opsSync/opsDomainOutbox.ts
Normal file
|
|
@ -0,0 +1,968 @@
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
|
||||||
|
import {
|
||||||
|
IndexedDBAdapter,
|
||||||
|
NonRetriableError,
|
||||||
|
startOfflineExecutor,
|
||||||
|
type OfflineExecutor,
|
||||||
|
} from '@tanstack/offline-transactions'
|
||||||
|
|
||||||
|
import {
|
||||||
|
createActivityCas,
|
||||||
|
updateActivityCas,
|
||||||
|
} from '@/app/(campaign)/campanha/actions/activity'
|
||||||
|
import { transitionCampaignDemandCas } from '@/app/(campaign)/campanha/actions/demand'
|
||||||
|
import {
|
||||||
|
createLeadershipCas,
|
||||||
|
setLeadershipMunicipalitiesMembershipCas,
|
||||||
|
setLeadershipStateDeputyMembershipCas,
|
||||||
|
updateLeadershipInternalCas,
|
||||||
|
} from '@/app/(campaign)/campanha/actions/leadership'
|
||||||
|
import { setStateDeputyMunicipalitiesBatchCas } from '@/app/(campaign)/campanha/actions/stateDeputy'
|
||||||
|
import {
|
||||||
|
collapseActivityCreateOutbox,
|
||||||
|
collapseActivityUpdateOutbox,
|
||||||
|
collapseDemandTransitionOutbox,
|
||||||
|
collapseLeadershipCreateOutbox,
|
||||||
|
collapseLeadershipMembershipOutbox,
|
||||||
|
collapseLeadershipUpdateOutbox,
|
||||||
|
collapseStateDeputyMunicipalitiesOutbox,
|
||||||
|
leadershipMembershipOutboxKey,
|
||||||
|
stateDeputyMunicipalitiesOutboxKey,
|
||||||
|
type OpsActivityCreateOutboxRow,
|
||||||
|
type OpsActivityUpdateOutboxRow,
|
||||||
|
type OpsDemandTransitionOutboxRow,
|
||||||
|
type OpsLeadershipCreateOutboxRow,
|
||||||
|
type OpsLeadershipMembershipOutboxRow,
|
||||||
|
type OpsLeadershipUpdateOutboxRow,
|
||||||
|
type OpsStateDeputyMunicipalitiesOutboxRow,
|
||||||
|
} from '@/components/campaign/opsSync/opsDomainOutboxModel'
|
||||||
|
import {
|
||||||
|
activitiesCollection,
|
||||||
|
demandsCollection,
|
||||||
|
leadershipsCollection,
|
||||||
|
municipalitiesCollection,
|
||||||
|
} from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
|
import { opsOutboxKey, type OpsOutboxKey } from '@/lib/campaignOps/opsContract'
|
||||||
|
import type { ActivityCreateInput, ActivityUpdateInput } from '@/lib/schemas/activity'
|
||||||
|
import type { CampaignDemandStatus } from '@/lib/schemas/campaignDemand'
|
||||||
|
import type { SupportStatus } from '@/lib/schemas/leadership'
|
||||||
|
import {
|
||||||
|
isOpsUpdatedAtConflictMessage,
|
||||||
|
parseOpsUpdatedAtConflictServerUpdatedAt,
|
||||||
|
} from '@/lib/schemas/opsCas'
|
||||||
|
|
||||||
|
const LEADERSHIP_UPDATE_FN = 'updateLeadershipInternal'
|
||||||
|
const LEADERSHIP_CREATE_FN = 'createLeadership'
|
||||||
|
const DEMAND_TRANSITION_FN = 'transitionCampaignDemand'
|
||||||
|
const ACTIVITY_UPDATE_FN = 'updateActivity'
|
||||||
|
const ACTIVITY_CREATE_FN = 'createActivity'
|
||||||
|
const STATE_DEPUTY_MUNICIPALITIES_FN = 'setStateDeputyMunicipalitiesBatch'
|
||||||
|
const LEADERSHIP_MEMBERSHIP_FN = 'setLeadershipMembership'
|
||||||
|
|
||||||
|
const leadershipUpdateOutboxCollection = createCollection(
|
||||||
|
localOnlyCollectionOptions<OpsLeadershipUpdateOutboxRow, number>({
|
||||||
|
id: 'ops-leadership-update-outbox',
|
||||||
|
getKey: (row) => row.leadershipId,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const leadershipCreateOutboxCollection = createCollection(
|
||||||
|
localOnlyCollectionOptions<OpsLeadershipCreateOutboxRow, string>({
|
||||||
|
id: 'ops-leadership-create-outbox',
|
||||||
|
getKey: (row) => row.id,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const demandTransitionOutboxCollection = createCollection(
|
||||||
|
localOnlyCollectionOptions<OpsDemandTransitionOutboxRow, number>({
|
||||||
|
id: 'ops-demand-transition-outbox',
|
||||||
|
getKey: (row) => row.demandId,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const activityUpdateOutboxCollection = createCollection(
|
||||||
|
localOnlyCollectionOptions<OpsActivityUpdateOutboxRow, number>({
|
||||||
|
id: 'ops-activity-update-outbox',
|
||||||
|
getKey: (row) => row.activityId,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const activityCreateOutboxCollection = createCollection(
|
||||||
|
localOnlyCollectionOptions<OpsActivityCreateOutboxRow, string>({
|
||||||
|
id: 'ops-activity-create-outbox',
|
||||||
|
getKey: (row) => row.id,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const stateDeputyMunicipalitiesOutboxCollection = createCollection(
|
||||||
|
localOnlyCollectionOptions<OpsStateDeputyMunicipalitiesOutboxRow, string>({
|
||||||
|
id: 'ops-state-deputy-municipalities-outbox',
|
||||||
|
getKey: (row) => row.id,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const leadershipMembershipOutboxCollection = createCollection(
|
||||||
|
localOnlyCollectionOptions<OpsLeadershipMembershipOutboxRow, string>({
|
||||||
|
id: 'ops-leadership-membership-outbox',
|
||||||
|
getKey: (row) => row.id,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
let executorSingleton: OfflineExecutor | null = null
|
||||||
|
let initPromise: Promise<OfflineExecutor> | null = null
|
||||||
|
|
||||||
|
const collapseAllDomainOutbox = (
|
||||||
|
transactions: Parameters<typeof collapseLeadershipUpdateOutbox>[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(LEADERSHIP_UPDATE_FN)
|
||||||
|
? collapseLeadershipUpdateOutbox(byFn.get(LEADERSHIP_UPDATE_FN)!)
|
||||||
|
: []),
|
||||||
|
...(byFn.get(LEADERSHIP_CREATE_FN)
|
||||||
|
? collapseLeadershipCreateOutbox(byFn.get(LEADERSHIP_CREATE_FN)!)
|
||||||
|
: []),
|
||||||
|
...(byFn.get(DEMAND_TRANSITION_FN)
|
||||||
|
? collapseDemandTransitionOutbox(byFn.get(DEMAND_TRANSITION_FN)!)
|
||||||
|
: []),
|
||||||
|
...(byFn.get(ACTIVITY_UPDATE_FN)
|
||||||
|
? collapseActivityUpdateOutbox(byFn.get(ACTIVITY_UPDATE_FN)!)
|
||||||
|
: []),
|
||||||
|
...(byFn.get(ACTIVITY_CREATE_FN)
|
||||||
|
? collapseActivityCreateOutbox(byFn.get(ACTIVITY_CREATE_FN)!)
|
||||||
|
: []),
|
||||||
|
...(byFn.get(STATE_DEPUTY_MUNICIPALITIES_FN)
|
||||||
|
? collapseStateDeputyMunicipalitiesOutbox(byFn.get(STATE_DEPUTY_MUNICIPALITIES_FN)!)
|
||||||
|
: []),
|
||||||
|
...(byFn.get(LEADERSHIP_MEMBERSHIP_FN)
|
||||||
|
? collapseLeadershipMembershipOutbox(byFn.get(LEADERSHIP_MEMBERSHIP_FN)!)
|
||||||
|
: []),
|
||||||
|
]
|
||||||
|
|
||||||
|
for (const [fn, list] of byFn) {
|
||||||
|
if (
|
||||||
|
fn !== LEADERSHIP_UPDATE_FN &&
|
||||||
|
fn !== LEADERSHIP_CREATE_FN &&
|
||||||
|
fn !== DEMAND_TRANSITION_FN &&
|
||||||
|
fn !== ACTIVITY_UPDATE_FN &&
|
||||||
|
fn !== ACTIVITY_CREATE_FN &&
|
||||||
|
fn !== STATE_DEPUTY_MUNICIPALITIES_FN &&
|
||||||
|
fn !== LEADERSHIP_MEMBERSHIP_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 createDomainOfflineExecutor = (): OfflineExecutor =>
|
||||||
|
startOfflineExecutor({
|
||||||
|
collections: {
|
||||||
|
leadershipUpdateOutbox: leadershipUpdateOutboxCollection,
|
||||||
|
leadershipCreateOutbox: leadershipCreateOutboxCollection,
|
||||||
|
demandTransitionOutbox: demandTransitionOutboxCollection,
|
||||||
|
activityUpdateOutbox: activityUpdateOutboxCollection,
|
||||||
|
activityCreateOutbox: activityCreateOutboxCollection,
|
||||||
|
stateDeputyMunicipalitiesOutbox: stateDeputyMunicipalitiesOutboxCollection,
|
||||||
|
leadershipMembershipOutbox: leadershipMembershipOutboxCollection,
|
||||||
|
},
|
||||||
|
storage: new IndexedDBAdapter('teqo-ops-domain', 'outbox'),
|
||||||
|
beforeRetry: collapseAllDomainOutbox,
|
||||||
|
mutationFns: {
|
||||||
|
[LEADERSHIP_UPDATE_FN]: async ({ transaction }) => {
|
||||||
|
const mutation = transaction.mutations[0]
|
||||||
|
if (!mutation) throw new NonRetriableError('Mutação de liderança vazia.')
|
||||||
|
const row = mutation.modified as OpsLeadershipUpdateOutboxRow
|
||||||
|
try {
|
||||||
|
const updated = await updateLeadershipInternalCas({
|
||||||
|
id: row.leadershipId,
|
||||||
|
municipalities: row.municipalities,
|
||||||
|
organizations: row.organizations,
|
||||||
|
stateDeputies: row.stateDeputies,
|
||||||
|
exclusive: row.exclusive,
|
||||||
|
supportStatus: row.supportStatus,
|
||||||
|
notes: row.notes,
|
||||||
|
baseUpdatedAt: row.baseUpdatedAt,
|
||||||
|
})
|
||||||
|
if (leadershipsCollection.has(updated.id)) {
|
||||||
|
leadershipsCollection.update(updated.id, (draft) => {
|
||||||
|
draft.supportStatus = updated.supportStatus
|
||||||
|
draft.exclusive = updated.exclusive
|
||||||
|
draft.notes = updated.notes
|
||||||
|
draft.municipalities = Array.isArray(updated.municipalities)
|
||||||
|
? updated.municipalities.map((entry) =>
|
||||||
|
typeof entry === 'number' ? entry : entry.id,
|
||||||
|
)
|
||||||
|
: draft.municipalities
|
||||||
|
draft.stateDeputies = Array.isArray(updated.stateDeputies)
|
||||||
|
? updated.stateDeputies.map((entry) =>
|
||||||
|
typeof entry === 'number' ? entry : entry.id,
|
||||||
|
)
|
||||||
|
: draft.stateDeputies
|
||||||
|
draft.updatedAt = updated.updatedAt
|
||||||
|
})
|
||||||
|
}
|
||||||
|
leadershipUpdateOutboxCollection.utils.acceptMutations(transaction)
|
||||||
|
if (leadershipUpdateOutboxCollection.has(row.leadershipId)) {
|
||||||
|
leadershipUpdateOutboxCollection.delete(row.leadershipId)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
if (isOpsUpdatedAtConflictMessage(message)) {
|
||||||
|
handleUpdatedAtConflict(message, (serverUpdatedAt) => {
|
||||||
|
if (leadershipUpdateOutboxCollection.has(row.leadershipId)) {
|
||||||
|
leadershipUpdateOutboxCollection.update(row.leadershipId, (draft) => {
|
||||||
|
draft.status = 'conflict'
|
||||||
|
draft.serverUpdatedAt = serverUpdatedAt
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (leadershipUpdateOutboxCollection.has(row.leadershipId)) {
|
||||||
|
leadershipUpdateOutboxCollection.update(row.leadershipId, (draft) => {
|
||||||
|
draft.status = 'error'
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[LEADERSHIP_CREATE_FN]: async ({ transaction }) => {
|
||||||
|
const mutation = transaction.mutations[0]
|
||||||
|
if (!mutation) throw new NonRetriableError('Mutação de cadastro vazia.')
|
||||||
|
const row = mutation.modified as OpsLeadershipCreateOutboxRow
|
||||||
|
try {
|
||||||
|
await createLeadershipCas({
|
||||||
|
name: row.name,
|
||||||
|
phone: row.phone,
|
||||||
|
email: row.email,
|
||||||
|
municipalities: row.municipalities,
|
||||||
|
organizations: row.organizations,
|
||||||
|
stateDeputies: row.stateDeputies,
|
||||||
|
exclusive: row.exclusive,
|
||||||
|
supportStatus: row.supportStatus,
|
||||||
|
notes: row.notes,
|
||||||
|
})
|
||||||
|
leadershipCreateOutboxCollection.utils.acceptMutations(transaction)
|
||||||
|
if (leadershipCreateOutboxCollection.has(row.id)) {
|
||||||
|
leadershipCreateOutboxCollection.delete(row.id)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
if (leadershipCreateOutboxCollection.has(row.id)) {
|
||||||
|
leadershipCreateOutboxCollection.update(row.id, (draft) => {
|
||||||
|
draft.status = 'error'
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[DEMAND_TRANSITION_FN]: async ({ transaction }) => {
|
||||||
|
const mutation = transaction.mutations[0]
|
||||||
|
if (!mutation) throw new NonRetriableError('Mutação de demanda vazia.')
|
||||||
|
const row = mutation.modified as OpsDemandTransitionOutboxRow
|
||||||
|
try {
|
||||||
|
const updated = await transitionCampaignDemandCas({
|
||||||
|
id: row.demandId,
|
||||||
|
status: row.status,
|
||||||
|
decisionNote: row.decisionNote,
|
||||||
|
baseUpdatedAt: row.baseUpdatedAt,
|
||||||
|
})
|
||||||
|
if (demandsCollection.has(updated.id)) {
|
||||||
|
demandsCollection.update(updated.id, (draft) => {
|
||||||
|
draft.status = updated.status
|
||||||
|
draft.updatedAt = updated.updatedAt
|
||||||
|
})
|
||||||
|
}
|
||||||
|
demandTransitionOutboxCollection.utils.acceptMutations(transaction)
|
||||||
|
if (demandTransitionOutboxCollection.has(row.demandId)) {
|
||||||
|
demandTransitionOutboxCollection.delete(row.demandId)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
if (isOpsUpdatedAtConflictMessage(message)) {
|
||||||
|
handleUpdatedAtConflict(message, (serverUpdatedAt) => {
|
||||||
|
if (demandTransitionOutboxCollection.has(row.demandId)) {
|
||||||
|
demandTransitionOutboxCollection.update(row.demandId, (draft) => {
|
||||||
|
draft.statusSync = 'conflict'
|
||||||
|
draft.serverUpdatedAt = serverUpdatedAt
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (demandTransitionOutboxCollection.has(row.demandId)) {
|
||||||
|
demandTransitionOutboxCollection.update(row.demandId, (draft) => {
|
||||||
|
draft.statusSync = 'error'
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[ACTIVITY_UPDATE_FN]: async ({ transaction }) => {
|
||||||
|
const mutation = transaction.mutations[0]
|
||||||
|
if (!mutation) throw new NonRetriableError('Mutação de atividade vazia.')
|
||||||
|
const row = mutation.modified as OpsActivityUpdateOutboxRow
|
||||||
|
try {
|
||||||
|
const updated = await updateActivityCas({
|
||||||
|
id: row.activityId,
|
||||||
|
...row.payload,
|
||||||
|
baseUpdatedAt: row.baseUpdatedAt,
|
||||||
|
})
|
||||||
|
if (activitiesCollection.has(updated.id)) {
|
||||||
|
activitiesCollection.update(updated.id, (draft) => {
|
||||||
|
draft.title = updated.title
|
||||||
|
draft.kind = updated.kind
|
||||||
|
draft.status = updated.status
|
||||||
|
draft.updatedAt = updated.updatedAt
|
||||||
|
})
|
||||||
|
}
|
||||||
|
activityUpdateOutboxCollection.utils.acceptMutations(transaction)
|
||||||
|
if (activityUpdateOutboxCollection.has(row.activityId)) {
|
||||||
|
activityUpdateOutboxCollection.delete(row.activityId)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
if (isOpsUpdatedAtConflictMessage(message)) {
|
||||||
|
handleUpdatedAtConflict(message, (serverUpdatedAt) => {
|
||||||
|
if (activityUpdateOutboxCollection.has(row.activityId)) {
|
||||||
|
activityUpdateOutboxCollection.update(row.activityId, (draft) => {
|
||||||
|
draft.status = 'conflict'
|
||||||
|
draft.serverUpdatedAt = serverUpdatedAt
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (activityUpdateOutboxCollection.has(row.activityId)) {
|
||||||
|
activityUpdateOutboxCollection.update(row.activityId, (draft) => {
|
||||||
|
draft.status = 'error'
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[ACTIVITY_CREATE_FN]: async ({ transaction }) => {
|
||||||
|
const mutation = transaction.mutations[0]
|
||||||
|
if (!mutation) throw new NonRetriableError('Mutação de criação de atividade vazia.')
|
||||||
|
const row = mutation.modified as OpsActivityCreateOutboxRow
|
||||||
|
try {
|
||||||
|
await createActivityCas(row.payload)
|
||||||
|
activityCreateOutboxCollection.utils.acceptMutations(transaction)
|
||||||
|
if (activityCreateOutboxCollection.has(row.id)) {
|
||||||
|
activityCreateOutboxCollection.delete(row.id)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
if (activityCreateOutboxCollection.has(row.id)) {
|
||||||
|
activityCreateOutboxCollection.update(row.id, (draft) => {
|
||||||
|
draft.status = 'error'
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[STATE_DEPUTY_MUNICIPALITIES_FN]: async ({ transaction }) => {
|
||||||
|
const mutation = transaction.mutations[0]
|
||||||
|
if (!mutation) throw new NonRetriableError('Mutação de municípios da dobradinha vazia.')
|
||||||
|
const row = mutation.modified as OpsStateDeputyMunicipalitiesOutboxRow
|
||||||
|
try {
|
||||||
|
await setStateDeputyMunicipalitiesBatchCas({
|
||||||
|
stateDeputyId: row.stateDeputyId,
|
||||||
|
municipalityIds: row.municipalityIds,
|
||||||
|
assigned: row.assigned,
|
||||||
|
municipalityBaseUpdatedAt: row.municipalityBaseUpdatedAt,
|
||||||
|
})
|
||||||
|
stateDeputyMunicipalitiesOutboxCollection.utils.acceptMutations(transaction)
|
||||||
|
if (stateDeputyMunicipalitiesOutboxCollection.has(row.id)) {
|
||||||
|
stateDeputyMunicipalitiesOutboxCollection.delete(row.id)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
if (isOpsUpdatedAtConflictMessage(message)) {
|
||||||
|
handleUpdatedAtConflict(message, (serverUpdatedAt) => {
|
||||||
|
if (stateDeputyMunicipalitiesOutboxCollection.has(row.id)) {
|
||||||
|
stateDeputyMunicipalitiesOutboxCollection.update(row.id, (draft) => {
|
||||||
|
draft.status = 'conflict'
|
||||||
|
draft.serverUpdatedAt = serverUpdatedAt
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (stateDeputyMunicipalitiesOutboxCollection.has(row.id)) {
|
||||||
|
stateDeputyMunicipalitiesOutboxCollection.update(row.id, (draft) => {
|
||||||
|
draft.status = 'error'
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[LEADERSHIP_MEMBERSHIP_FN]: async ({ transaction }) => {
|
||||||
|
const mutation = transaction.mutations[0]
|
||||||
|
if (!mutation) throw new NonRetriableError('Mutação de vínculo vazia.')
|
||||||
|
const row = mutation.modified as OpsLeadershipMembershipOutboxRow
|
||||||
|
try {
|
||||||
|
if (row.kind === 'municipalities') {
|
||||||
|
await setLeadershipMunicipalitiesMembershipCas({
|
||||||
|
leadershipId: row.leadershipId,
|
||||||
|
municipalityIds: row.municipalityIds ?? [],
|
||||||
|
assigned: row.assigned,
|
||||||
|
baseUpdatedAt: row.baseUpdatedAt,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
await setLeadershipStateDeputyMembershipCas({
|
||||||
|
leadershipId: row.leadershipId,
|
||||||
|
stateDeputyId: row.stateDeputyId!,
|
||||||
|
assigned: row.assigned,
|
||||||
|
baseUpdatedAt: row.baseUpdatedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
leadershipMembershipOutboxCollection.utils.acceptMutations(transaction)
|
||||||
|
if (leadershipMembershipOutboxCollection.has(row.id)) {
|
||||||
|
leadershipMembershipOutboxCollection.delete(row.id)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
if (isOpsUpdatedAtConflictMessage(message)) {
|
||||||
|
handleUpdatedAtConflict(message, (serverUpdatedAt) => {
|
||||||
|
if (leadershipMembershipOutboxCollection.has(row.id)) {
|
||||||
|
leadershipMembershipOutboxCollection.update(row.id, (draft) => {
|
||||||
|
draft.status = 'conflict'
|
||||||
|
draft.serverUpdatedAt = serverUpdatedAt
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (leadershipMembershipOutboxCollection.has(row.id)) {
|
||||||
|
leadershipMembershipOutboxCollection.update(row.id, (draft) => {
|
||||||
|
draft.status = 'error'
|
||||||
|
draft.errorMessage = message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const getOpsDomainOfflineExecutor = async (): Promise<OfflineExecutor> => {
|
||||||
|
if (executorSingleton) {
|
||||||
|
await executorSingleton.waitForInit()
|
||||||
|
return executorSingleton
|
||||||
|
}
|
||||||
|
if (!initPromise) {
|
||||||
|
initPromise = (async () => {
|
||||||
|
const executor = createDomainOfflineExecutor()
|
||||||
|
await executor.waitForInit()
|
||||||
|
executorSingleton = executor
|
||||||
|
return executor
|
||||||
|
})()
|
||||||
|
}
|
||||||
|
return initPromise
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueueLeadershipUpdate = async (input: {
|
||||||
|
leadershipId: number
|
||||||
|
municipalities?: number[]
|
||||||
|
organizations?: number[] | null
|
||||||
|
stateDeputies?: number[] | null
|
||||||
|
exclusive?: boolean
|
||||||
|
supportStatus?: SupportStatus
|
||||||
|
notes?: string | null
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsDomainOfflineExecutor()
|
||||||
|
const mirror = leadershipsCollection.get(input.leadershipId)
|
||||||
|
const baseUpdatedAt =
|
||||||
|
input.baseUpdatedAt !== undefined ? input.baseUpdatedAt : (mirror?.updatedAt ?? null)
|
||||||
|
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: LEADERSHIP_UPDATE_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsLeadershipUpdateOutboxRow = {
|
||||||
|
leadershipId: variables.leadershipId,
|
||||||
|
municipalities: variables.municipalities,
|
||||||
|
organizations: variables.organizations,
|
||||||
|
stateDeputies: variables.stateDeputies,
|
||||||
|
exclusive: variables.exclusive,
|
||||||
|
supportStatus: variables.supportStatus,
|
||||||
|
notes: variables.notes,
|
||||||
|
baseUpdatedAt: variables.baseUpdatedAt ?? baseUpdatedAt,
|
||||||
|
status: 'pending',
|
||||||
|
}
|
||||||
|
if (leadershipsCollection.has(variables.leadershipId)) {
|
||||||
|
leadershipsCollection.update(variables.leadershipId, (draft) => {
|
||||||
|
if (variables.supportStatus !== undefined) draft.supportStatus = variables.supportStatus
|
||||||
|
if (variables.exclusive !== undefined) draft.exclusive = variables.exclusive
|
||||||
|
if (variables.notes !== undefined) draft.notes = variables.notes
|
||||||
|
if (variables.municipalities !== undefined) draft.municipalities = variables.municipalities
|
||||||
|
if (variables.stateDeputies !== undefined) {
|
||||||
|
draft.stateDeputies = variables.stateDeputies ?? []
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (leadershipUpdateOutboxCollection.has(variables.leadershipId)) {
|
||||||
|
leadershipUpdateOutboxCollection.update(variables.leadershipId, (draft) => {
|
||||||
|
Object.assign(draft, next)
|
||||||
|
draft.serverUpdatedAt = undefined
|
||||||
|
draft.errorMessage = undefined
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
leadershipUpdateOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run({ ...input, baseUpdatedAt })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueueLeadershipCreate = async (input: {
|
||||||
|
clientId: string
|
||||||
|
name: string
|
||||||
|
phone: string
|
||||||
|
email?: string | null
|
||||||
|
municipalities: number[]
|
||||||
|
organizations?: number[]
|
||||||
|
stateDeputies?: number[]
|
||||||
|
exclusive?: boolean
|
||||||
|
supportStatus?: SupportStatus
|
||||||
|
notes?: string
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsDomainOfflineExecutor()
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: LEADERSHIP_CREATE_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsLeadershipCreateOutboxRow = {
|
||||||
|
id: variables.clientId,
|
||||||
|
name: variables.name,
|
||||||
|
phone: variables.phone,
|
||||||
|
email: variables.email,
|
||||||
|
municipalities: variables.municipalities,
|
||||||
|
organizations: variables.organizations,
|
||||||
|
stateDeputies: variables.stateDeputies,
|
||||||
|
exclusive: variables.exclusive,
|
||||||
|
supportStatus: variables.supportStatus,
|
||||||
|
notes: variables.notes,
|
||||||
|
status: 'pending',
|
||||||
|
}
|
||||||
|
if (leadershipCreateOutboxCollection.has(next.id)) {
|
||||||
|
leadershipCreateOutboxCollection.update(next.id, (draft) => {
|
||||||
|
Object.assign(draft, next)
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
leadershipCreateOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueueDemandTransition = async (input: {
|
||||||
|
demandId: number
|
||||||
|
status: CampaignDemandStatus
|
||||||
|
decisionNote?: string | null
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsDomainOfflineExecutor()
|
||||||
|
const mirror = demandsCollection.get(input.demandId)
|
||||||
|
const baseUpdatedAt =
|
||||||
|
input.baseUpdatedAt !== undefined ? input.baseUpdatedAt : (mirror?.updatedAt ?? null)
|
||||||
|
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: DEMAND_TRANSITION_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsDemandTransitionOutboxRow = {
|
||||||
|
demandId: variables.demandId,
|
||||||
|
status: variables.status,
|
||||||
|
decisionNote: variables.decisionNote,
|
||||||
|
baseUpdatedAt: variables.baseUpdatedAt ?? baseUpdatedAt,
|
||||||
|
statusSync: 'pending',
|
||||||
|
}
|
||||||
|
if (demandsCollection.has(variables.demandId)) {
|
||||||
|
demandsCollection.update(variables.demandId, (draft) => {
|
||||||
|
draft.status = variables.status
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (demandTransitionOutboxCollection.has(variables.demandId)) {
|
||||||
|
demandTransitionOutboxCollection.update(variables.demandId, (draft) => {
|
||||||
|
Object.assign(draft, next)
|
||||||
|
draft.serverUpdatedAt = undefined
|
||||||
|
draft.errorMessage = undefined
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
demandTransitionOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run({ ...input, baseUpdatedAt })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueueActivityUpdate = async (input: {
|
||||||
|
activityId: number
|
||||||
|
payload: Omit<ActivityUpdateInput, 'id' | 'baseUpdatedAt'>
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsDomainOfflineExecutor()
|
||||||
|
const mirror = activitiesCollection.get(input.activityId)
|
||||||
|
const baseUpdatedAt =
|
||||||
|
input.baseUpdatedAt !== undefined ? input.baseUpdatedAt : (mirror?.updatedAt ?? null)
|
||||||
|
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: ACTIVITY_UPDATE_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsActivityUpdateOutboxRow = {
|
||||||
|
activityId: variables.activityId,
|
||||||
|
payload: variables.payload,
|
||||||
|
baseUpdatedAt: variables.baseUpdatedAt ?? baseUpdatedAt,
|
||||||
|
status: 'pending',
|
||||||
|
}
|
||||||
|
if (activitiesCollection.has(variables.activityId) && variables.payload.title) {
|
||||||
|
activitiesCollection.update(variables.activityId, (draft) => {
|
||||||
|
if (variables.payload.title) draft.title = variables.payload.title
|
||||||
|
if (variables.payload.kind) draft.kind = variables.payload.kind
|
||||||
|
if (variables.payload.status) draft.status = variables.payload.status
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (activityUpdateOutboxCollection.has(variables.activityId)) {
|
||||||
|
activityUpdateOutboxCollection.update(variables.activityId, (draft) => {
|
||||||
|
Object.assign(draft, next)
|
||||||
|
draft.serverUpdatedAt = undefined
|
||||||
|
draft.errorMessage = undefined
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
activityUpdateOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run({ ...input, baseUpdatedAt })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueueActivityCreate = async (input: {
|
||||||
|
clientId: string
|
||||||
|
payload: ActivityCreateInput
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsDomainOfflineExecutor()
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: ACTIVITY_CREATE_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsActivityCreateOutboxRow = {
|
||||||
|
id: variables.clientId,
|
||||||
|
payload: variables.payload,
|
||||||
|
status: 'pending',
|
||||||
|
}
|
||||||
|
if (activityCreateOutboxCollection.has(next.id)) {
|
||||||
|
activityCreateOutboxCollection.update(next.id, (draft) => {
|
||||||
|
Object.assign(draft, next)
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
activityCreateOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueueStateDeputyMunicipalities = async (input: {
|
||||||
|
stateDeputyId: number
|
||||||
|
municipalityIds: number[]
|
||||||
|
assigned: boolean
|
||||||
|
municipalityBaseUpdatedAt?: Record<string, string | null | undefined>
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsDomainOfflineExecutor()
|
||||||
|
const id = stateDeputyMunicipalitiesOutboxKey(
|
||||||
|
input.stateDeputyId,
|
||||||
|
input.municipalityIds,
|
||||||
|
input.assigned,
|
||||||
|
)
|
||||||
|
const municipalityBaseUpdatedAt =
|
||||||
|
input.municipalityBaseUpdatedAt ??
|
||||||
|
Object.fromEntries(
|
||||||
|
input.municipalityIds.map((municipalityId) => [
|
||||||
|
String(municipalityId),
|
||||||
|
municipalitiesCollection.get(municipalityId)?.updatedAt ?? null,
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: STATE_DEPUTY_MUNICIPALITIES_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsStateDeputyMunicipalitiesOutboxRow = {
|
||||||
|
id,
|
||||||
|
stateDeputyId: variables.stateDeputyId,
|
||||||
|
municipalityIds: variables.municipalityIds,
|
||||||
|
assigned: variables.assigned,
|
||||||
|
municipalityBaseUpdatedAt: variables.municipalityBaseUpdatedAt ?? municipalityBaseUpdatedAt,
|
||||||
|
status: 'pending',
|
||||||
|
}
|
||||||
|
if (stateDeputyMunicipalitiesOutboxCollection.has(id)) {
|
||||||
|
stateDeputyMunicipalitiesOutboxCollection.update(id, (draft) => {
|
||||||
|
Object.assign(draft, next)
|
||||||
|
draft.serverUpdatedAt = undefined
|
||||||
|
draft.errorMessage = undefined
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
stateDeputyMunicipalitiesOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run({ ...input, municipalityBaseUpdatedAt })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueueLeadershipMunicipalitiesMembership = async (input: {
|
||||||
|
leadershipId: number
|
||||||
|
municipalityIds: number[]
|
||||||
|
assigned: boolean
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsDomainOfflineExecutor()
|
||||||
|
const targetId = input.municipalityIds[0] ?? 0
|
||||||
|
const id = leadershipMembershipOutboxKey('municipalities', input.leadershipId, targetId)
|
||||||
|
const mirror = leadershipsCollection.get(input.leadershipId)
|
||||||
|
const baseUpdatedAt =
|
||||||
|
input.baseUpdatedAt !== undefined ? input.baseUpdatedAt : (mirror?.updatedAt ?? null)
|
||||||
|
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: LEADERSHIP_MEMBERSHIP_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsLeadershipMembershipOutboxRow = {
|
||||||
|
id,
|
||||||
|
kind: 'municipalities',
|
||||||
|
leadershipId: variables.leadershipId,
|
||||||
|
municipalityIds: variables.municipalityIds,
|
||||||
|
assigned: variables.assigned,
|
||||||
|
baseUpdatedAt: variables.baseUpdatedAt ?? baseUpdatedAt,
|
||||||
|
status: 'pending',
|
||||||
|
}
|
||||||
|
if (leadershipMembershipOutboxCollection.has(id)) {
|
||||||
|
leadershipMembershipOutboxCollection.update(id, (draft) => {
|
||||||
|
Object.assign(draft, next)
|
||||||
|
draft.serverUpdatedAt = undefined
|
||||||
|
draft.errorMessage = undefined
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
leadershipMembershipOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run({ ...input, baseUpdatedAt })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enqueueLeadershipStateDeputyMembership = async (input: {
|
||||||
|
leadershipId: number
|
||||||
|
stateDeputyId: number
|
||||||
|
assigned: boolean
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
}): Promise<void> => {
|
||||||
|
const executor = await getOpsDomainOfflineExecutor()
|
||||||
|
const id = leadershipMembershipOutboxKey('stateDeputies', input.leadershipId, input.stateDeputyId)
|
||||||
|
const mirror = leadershipsCollection.get(input.leadershipId)
|
||||||
|
const baseUpdatedAt =
|
||||||
|
input.baseUpdatedAt !== undefined ? input.baseUpdatedAt : (mirror?.updatedAt ?? null)
|
||||||
|
|
||||||
|
const run = executor.createOfflineAction<typeof input>({
|
||||||
|
mutationFnName: LEADERSHIP_MEMBERSHIP_FN,
|
||||||
|
onMutate: (variables) => {
|
||||||
|
const next: OpsLeadershipMembershipOutboxRow = {
|
||||||
|
id,
|
||||||
|
kind: 'stateDeputies',
|
||||||
|
leadershipId: variables.leadershipId,
|
||||||
|
stateDeputyId: variables.stateDeputyId,
|
||||||
|
assigned: variables.assigned,
|
||||||
|
baseUpdatedAt: variables.baseUpdatedAt ?? baseUpdatedAt,
|
||||||
|
status: 'pending',
|
||||||
|
}
|
||||||
|
if (leadershipMembershipOutboxCollection.has(id)) {
|
||||||
|
leadershipMembershipOutboxCollection.update(id, (draft) => {
|
||||||
|
Object.assign(draft, next)
|
||||||
|
draft.serverUpdatedAt = undefined
|
||||||
|
draft.errorMessage = undefined
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
leadershipMembershipOutboxCollection.insert(next)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
run({ ...input, baseUpdatedAt })
|
||||||
|
}
|
||||||
|
|
||||||
|
export const collectOpsDomainOutboxKeys = (): Set<OpsOutboxKey> => {
|
||||||
|
const keys = new Set<OpsOutboxKey>()
|
||||||
|
for (const row of leadershipUpdateOutboxCollection.toArray) {
|
||||||
|
if (row.status === 'pending' || row.status === 'conflict') {
|
||||||
|
keys.add(opsOutboxKey('leaderships', row.leadershipId))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of demandTransitionOutboxCollection.toArray) {
|
||||||
|
if (row.statusSync === 'pending' || row.statusSync === 'conflict') {
|
||||||
|
keys.add(opsOutboxKey('demands', row.demandId))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of activityUpdateOutboxCollection.toArray) {
|
||||||
|
if (row.status === 'pending' || row.status === 'conflict') {
|
||||||
|
keys.add(opsOutboxKey('activities', row.activityId))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of stateDeputyMunicipalitiesOutboxCollection.toArray) {
|
||||||
|
if (row.status === 'pending' || row.status === 'conflict') {
|
||||||
|
for (const municipalityId of row.municipalityIds) {
|
||||||
|
keys.add(opsOutboxKey('municipalities', municipalityId))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of leadershipMembershipOutboxCollection.toArray) {
|
||||||
|
if (row.status === 'pending' || row.status === 'conflict') {
|
||||||
|
keys.add(opsOutboxKey('leaderships', row.leadershipId))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return keys
|
||||||
|
}
|
||||||
|
|
||||||
|
export const readOpsLeadershipUpdateOutboxRow = (
|
||||||
|
leadershipId: number,
|
||||||
|
): OpsLeadershipUpdateOutboxRow | undefined => leadershipUpdateOutboxCollection.get(leadershipId)
|
||||||
|
|
||||||
|
export const subscribeOpsLeadershipUpdateOutboxRow = (
|
||||||
|
leadershipId: number,
|
||||||
|
onStoreChange: () => void,
|
||||||
|
): (() => void) => {
|
||||||
|
let previous = leadershipUpdateOutboxCollection.get(leadershipId)
|
||||||
|
const subscription = leadershipUpdateOutboxCollection.subscribeChanges(() => {
|
||||||
|
const next = leadershipUpdateOutboxCollection.get(leadershipId)
|
||||||
|
if (next === previous) return
|
||||||
|
previous = next
|
||||||
|
onStoreChange()
|
||||||
|
})
|
||||||
|
return () => subscription.unsubscribe()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const discardOpsLeadershipUpdateOutboxRow = (leadershipId: number): void => {
|
||||||
|
if (leadershipUpdateOutboxCollection.has(leadershipId)) {
|
||||||
|
leadershipUpdateOutboxCollection.delete(leadershipId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const readOpsDemandTransitionOutboxRow = (
|
||||||
|
demandId: number,
|
||||||
|
): OpsDemandTransitionOutboxRow | undefined => demandTransitionOutboxCollection.get(demandId)
|
||||||
|
|
||||||
|
export const subscribeOpsDemandTransitionOutboxRow = (
|
||||||
|
demandId: number,
|
||||||
|
onStoreChange: () => void,
|
||||||
|
): (() => void) => {
|
||||||
|
let previous = demandTransitionOutboxCollection.get(demandId)
|
||||||
|
const subscription = demandTransitionOutboxCollection.subscribeChanges(() => {
|
||||||
|
const next = demandTransitionOutboxCollection.get(demandId)
|
||||||
|
if (next === previous) return
|
||||||
|
previous = next
|
||||||
|
onStoreChange()
|
||||||
|
})
|
||||||
|
return () => subscription.unsubscribe()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const discardOpsDemandTransitionOutboxRow = (demandId: number): void => {
|
||||||
|
if (demandTransitionOutboxCollection.has(demandId)) {
|
||||||
|
demandTransitionOutboxCollection.delete(demandId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const readOpsActivityUpdateOutboxRow = (
|
||||||
|
activityId: number,
|
||||||
|
): OpsActivityUpdateOutboxRow | undefined => activityUpdateOutboxCollection.get(activityId)
|
||||||
|
|
||||||
|
export const subscribeOpsActivityUpdateOutboxRow = (
|
||||||
|
activityId: number,
|
||||||
|
onStoreChange: () => void,
|
||||||
|
): (() => void) => {
|
||||||
|
let previous = activityUpdateOutboxCollection.get(activityId)
|
||||||
|
const subscription = activityUpdateOutboxCollection.subscribeChanges(() => {
|
||||||
|
const next = activityUpdateOutboxCollection.get(activityId)
|
||||||
|
if (next === previous) return
|
||||||
|
previous = next
|
||||||
|
onStoreChange()
|
||||||
|
})
|
||||||
|
return () => subscription.unsubscribe()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const discardOpsActivityUpdateOutboxRow = (activityId: number): void => {
|
||||||
|
if (activityUpdateOutboxCollection.has(activityId)) {
|
||||||
|
activityUpdateOutboxCollection.delete(activityId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const wipeDomainOutboxCollections = (): void => {
|
||||||
|
for (const row of leadershipUpdateOutboxCollection.toArray) {
|
||||||
|
if (leadershipUpdateOutboxCollection.has(row.leadershipId)) {
|
||||||
|
leadershipUpdateOutboxCollection.delete(row.leadershipId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of leadershipCreateOutboxCollection.toArray) {
|
||||||
|
if (leadershipCreateOutboxCollection.has(row.id)) {
|
||||||
|
leadershipCreateOutboxCollection.delete(row.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of demandTransitionOutboxCollection.toArray) {
|
||||||
|
if (demandTransitionOutboxCollection.has(row.demandId)) {
|
||||||
|
demandTransitionOutboxCollection.delete(row.demandId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of activityUpdateOutboxCollection.toArray) {
|
||||||
|
if (activityUpdateOutboxCollection.has(row.activityId)) {
|
||||||
|
activityUpdateOutboxCollection.delete(row.activityId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of activityCreateOutboxCollection.toArray) {
|
||||||
|
if (activityCreateOutboxCollection.has(row.id)) {
|
||||||
|
activityCreateOutboxCollection.delete(row.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of stateDeputyMunicipalitiesOutboxCollection.toArray) {
|
||||||
|
if (stateDeputyMunicipalitiesOutboxCollection.has(row.id)) {
|
||||||
|
stateDeputyMunicipalitiesOutboxCollection.delete(row.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of leadershipMembershipOutboxCollection.toArray) {
|
||||||
|
if (leadershipMembershipOutboxCollection.has(row.id)) {
|
||||||
|
leadershipMembershipOutboxCollection.delete(row.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Logout wipe — outbox storage + in-memory rows (OH11/OH13). */
|
||||||
|
export const clearOpsDomainOutboxForLogout = async (): Promise<void> => {
|
||||||
|
if (executorSingleton) {
|
||||||
|
try {
|
||||||
|
await executorSingleton.clearOutbox()
|
||||||
|
executorSingleton.dispose()
|
||||||
|
} catch {
|
||||||
|
// Best effort — private mode / torn-down storage.
|
||||||
|
}
|
||||||
|
executorSingleton = null
|
||||||
|
initPromise = null
|
||||||
|
}
|
||||||
|
wipeDomainOutboxCollections()
|
||||||
|
}
|
||||||
151
src/components/campaign/opsSync/opsDomainOutboxModel.ts
Normal file
151
src/components/campaign/opsSync/opsDomainOutboxModel.ts
Normal file
|
|
@ -0,0 +1,151 @@
|
||||||
|
import type { OfflineTransaction } from '@tanstack/offline-transactions'
|
||||||
|
|
||||||
|
import type { ActivityCreateInput, ActivityUpdateInput } from '@/lib/schemas/activity'
|
||||||
|
import type { CampaignDemandStatus } from '@/lib/schemas/campaignDemand'
|
||||||
|
import type { SupportStatus } from '@/lib/schemas/leadership'
|
||||||
|
|
||||||
|
export type OpsDomainWriteSyncStatus = 'pending' | 'synced' | 'conflict' | 'error'
|
||||||
|
|
||||||
|
export type OpsLeadershipUpdateOutboxRow = {
|
||||||
|
leadershipId: number
|
||||||
|
municipalities?: number[]
|
||||||
|
organizations?: number[] | null
|
||||||
|
stateDeputies?: number[] | null
|
||||||
|
exclusive?: boolean
|
||||||
|
supportStatus?: SupportStatus
|
||||||
|
notes?: string | null
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
status: OpsDomainWriteSyncStatus
|
||||||
|
serverUpdatedAt?: string | null
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OpsLeadershipCreateOutboxRow = {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
phone: string
|
||||||
|
email?: string | null
|
||||||
|
municipalities: number[]
|
||||||
|
organizations?: number[]
|
||||||
|
stateDeputies?: number[]
|
||||||
|
exclusive?: boolean
|
||||||
|
supportStatus?: SupportStatus
|
||||||
|
notes?: string
|
||||||
|
status: OpsDomainWriteSyncStatus
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OpsDemandTransitionOutboxRow = {
|
||||||
|
demandId: number
|
||||||
|
status: CampaignDemandStatus
|
||||||
|
decisionNote?: string | null
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
statusSync: OpsDomainWriteSyncStatus
|
||||||
|
serverUpdatedAt?: string | null
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OpsActivityUpdateOutboxRow = {
|
||||||
|
activityId: number
|
||||||
|
payload: Omit<ActivityUpdateInput, 'id' | 'baseUpdatedAt'>
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
status: OpsDomainWriteSyncStatus
|
||||||
|
serverUpdatedAt?: string | null
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OpsActivityCreateOutboxRow = {
|
||||||
|
id: string
|
||||||
|
payload: ActivityCreateInput
|
||||||
|
status: OpsDomainWriteSyncStatus
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OpsStateDeputyMunicipalitiesOutboxRow = {
|
||||||
|
id: string
|
||||||
|
stateDeputyId: number
|
||||||
|
municipalityIds: number[]
|
||||||
|
assigned: boolean
|
||||||
|
municipalityBaseUpdatedAt?: Record<string, string | null | undefined>
|
||||||
|
status: OpsDomainWriteSyncStatus
|
||||||
|
serverUpdatedAt?: string | null
|
||||||
|
conflictMunicipalityId?: number
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OpsLeadershipMembershipOutboxRow = {
|
||||||
|
id: string
|
||||||
|
kind: 'municipalities' | 'stateDeputies'
|
||||||
|
leadershipId: number
|
||||||
|
municipalityIds?: number[]
|
||||||
|
stateDeputyId?: number
|
||||||
|
assigned: boolean
|
||||||
|
baseUpdatedAt?: string | null
|
||||||
|
status: OpsDomainWriteSyncStatus
|
||||||
|
serverUpdatedAt?: string | null
|
||||||
|
errorMessage?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
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 collapseLeadershipUpdateOutbox = (
|
||||||
|
transactions: OfflineTransaction[],
|
||||||
|
): OfflineTransaction[] => collapseByMetadataKey(transactions, 'leadershipId')
|
||||||
|
|
||||||
|
export const collapseLeadershipCreateOutbox = (
|
||||||
|
transactions: OfflineTransaction[],
|
||||||
|
): OfflineTransaction[] => collapseByMetadataKey(transactions, 'clientId')
|
||||||
|
|
||||||
|
export const collapseDemandTransitionOutbox = (
|
||||||
|
transactions: OfflineTransaction[],
|
||||||
|
): OfflineTransaction[] => collapseByMetadataKey(transactions, 'demandId')
|
||||||
|
|
||||||
|
export const collapseActivityUpdateOutbox = (
|
||||||
|
transactions: OfflineTransaction[],
|
||||||
|
): OfflineTransaction[] => collapseByMetadataKey(transactions, 'activityId')
|
||||||
|
|
||||||
|
export const collapseActivityCreateOutbox = (
|
||||||
|
transactions: OfflineTransaction[],
|
||||||
|
): OfflineTransaction[] => collapseByMetadataKey(transactions, 'clientId')
|
||||||
|
|
||||||
|
export const collapseStateDeputyMunicipalitiesOutbox = (
|
||||||
|
transactions: OfflineTransaction[],
|
||||||
|
): OfflineTransaction[] => collapseByMetadataKey(transactions, 'batchKey')
|
||||||
|
|
||||||
|
export const collapseLeadershipMembershipOutbox = (
|
||||||
|
transactions: OfflineTransaction[],
|
||||||
|
): OfflineTransaction[] => collapseByMetadataKey(transactions, 'membershipKey')
|
||||||
|
|
||||||
|
export const leadershipMembershipOutboxKey = (
|
||||||
|
kind: 'municipalities' | 'stateDeputies',
|
||||||
|
leadershipId: number,
|
||||||
|
targetId: number,
|
||||||
|
): string => `${kind}:${leadershipId}:${targetId}`
|
||||||
|
|
||||||
|
export const stateDeputyMunicipalitiesOutboxKey = (
|
||||||
|
stateDeputyId: number,
|
||||||
|
municipalityIds: readonly number[],
|
||||||
|
assigned: boolean,
|
||||||
|
): string =>
|
||||||
|
`${stateDeputyId}:${assigned ? 'add' : 'remove'}:${[...municipalityIds].sort((a, b) => a - b).join(',')}`
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
|
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
|
||||||
|
|
||||||
import { collectOpsEstimateOutboxKeys } from '@/components/campaign/opsSync/opsEstimateOutbox'
|
import { collectOpsEstimateOutboxKeys } from '@/components/campaign/opsSync/opsEstimateOutbox'
|
||||||
|
import { collectOpsDomainOutboxKeys } from '@/components/campaign/opsSync/opsDomainOutbox'
|
||||||
import {
|
import {
|
||||||
openOpsMirrorStore,
|
openOpsMirrorStore,
|
||||||
type OpsMirrorPersistenceMode,
|
type OpsMirrorPersistenceMode,
|
||||||
|
|
@ -40,7 +41,7 @@ const createRowCollection = <T extends { id: number }>(id: string) =>
|
||||||
export const municipalitiesCollection = createRowCollection<OpsMunicipality>('ops-municipalities')
|
export const municipalitiesCollection = createRowCollection<OpsMunicipality>('ops-municipalities')
|
||||||
export const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships')
|
export const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships')
|
||||||
export { votePledgesCollection }
|
export { votePledgesCollection }
|
||||||
const activitiesCollection = createRowCollection<OpsActivity>('ops-activities')
|
export const activitiesCollection = createRowCollection<OpsActivity>('ops-activities')
|
||||||
export const stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies')
|
export const stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies')
|
||||||
export const organizationsCollection = createRowCollection<OpsOrganization>('ops-organizations')
|
export const organizationsCollection = createRowCollection<OpsOrganization>('ops-organizations')
|
||||||
export const demandsCollection = createRowCollection<OpsDemand>('ops-demands')
|
export const demandsCollection = createRowCollection<OpsDemand>('ops-demands')
|
||||||
|
|
@ -143,6 +144,7 @@ const resolveOutboxKeys = (explicit?: ReadonlySet<OpsOutboxKey>): ReadonlySet<Op
|
||||||
if (explicit) return explicit
|
if (explicit) return explicit
|
||||||
const keys = collectOpsEstimateOutboxKeys()
|
const keys = collectOpsEstimateOutboxKeys()
|
||||||
for (const key of collectOpsMunicipalityOutboxKeys()) keys.add(key)
|
for (const key of collectOpsMunicipalityOutboxKeys()) keys.add(key)
|
||||||
|
for (const key of collectOpsDomainOutboxKeys()) keys.add(key)
|
||||||
return keys
|
return keys
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
|
||||||
import { campaignDemandCreateSchema } from '@/lib/schemas/campaignDemandInput'
|
import { campaignDemandCreateSchema } from '@/lib/schemas/campaignDemandInput'
|
||||||
|
import { optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
|
||||||
import {
|
import {
|
||||||
positiveRelationshipId,
|
positiveRelationshipId,
|
||||||
trimmedNullableText,
|
trimmedNullableText,
|
||||||
|
|
@ -178,6 +179,8 @@ export const activityUpdateSchema = activityFieldsSchema
|
||||||
responsible: positiveRelationshipId.nullable().optional(),
|
responsible: positiveRelationshipId.nullable().optional(),
|
||||||
leadership: positiveRelationshipId.nullable().optional(),
|
leadership: positiveRelationshipId.nullable().optional(),
|
||||||
status: z.enum(activityStatuses).optional(),
|
status: z.enum(activityStatuses).optional(),
|
||||||
|
/** OH13 — CAS token; absent → last-write-wins. */
|
||||||
|
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||||
})
|
})
|
||||||
.superRefine((data, context) => {
|
.superRefine((data, context) => {
|
||||||
validateSchedule(data, context, 'patch')
|
validateSchedule(data, context, 'patch')
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
|
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||||
|
|
||||||
export const campaignDemandKinds = [
|
export const campaignDemandKinds = [
|
||||||
'material',
|
'material',
|
||||||
'servico',
|
'servico',
|
||||||
|
|
@ -82,6 +84,7 @@ export const CAMPAIGN_DEMAND_TRANSITION_SAFE_MESSAGES = [
|
||||||
CAMPAIGN_DEMAND_TRANSITION_STAFF_MESSAGE,
|
CAMPAIGN_DEMAND_TRANSITION_STAFF_MESSAGE,
|
||||||
CAMPAIGN_DEMAND_ESCALATED_DECISION_MESSAGE,
|
CAMPAIGN_DEMAND_ESCALATED_DECISION_MESSAGE,
|
||||||
CAMPAIGN_DEMAND_INVALID_STATUS_MESSAGE,
|
CAMPAIGN_DEMAND_INVALID_STATUS_MESSAGE,
|
||||||
|
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
export const CAMPAIGN_DEMAND_RECEIPT_SAFE_MESSAGES = [
|
export const CAMPAIGN_DEMAND_RECEIPT_SAFE_MESSAGES = [
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
|
||||||
import { campaignDemandKinds, campaignDemandStatuses } from '@/lib/schemas/campaignDemand'
|
import { campaignDemandKinds, campaignDemandStatuses } from '@/lib/schemas/campaignDemand'
|
||||||
|
import { optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
|
||||||
import {
|
import {
|
||||||
positiveRelationshipId,
|
positiveRelationshipId,
|
||||||
trimmedNullableText,
|
trimmedNullableText,
|
||||||
|
|
@ -21,6 +22,8 @@ export const campaignDemandTransitionSchema = z.object({
|
||||||
id: positiveRelationshipId,
|
id: positiveRelationshipId,
|
||||||
status: z.enum(campaignDemandStatuses),
|
status: z.enum(campaignDemandStatuses),
|
||||||
decisionNote: trimmedNullableText(2000),
|
decisionNote: trimmedNullableText(2000),
|
||||||
|
/** OH13 — CAS token; absent → last-write-wins. */
|
||||||
|
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||||
})
|
})
|
||||||
|
|
||||||
export const campaignDemandCostSchema = z.object({
|
export const campaignDemandCostSchema = z.object({
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
import { optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
|
||||||
import {
|
import {
|
||||||
brazilianMobile,
|
brazilianMobile,
|
||||||
optionalPersistedEmail,
|
optionalPersistedEmail,
|
||||||
|
|
@ -85,6 +86,8 @@ export const leadershipInternalUpdateSchema = z.object({
|
||||||
exclusive: z.boolean().optional(),
|
exclusive: z.boolean().optional(),
|
||||||
supportStatus: z.enum(leadershipSupportStatuses).optional(),
|
supportStatus: z.enum(leadershipSupportStatuses).optional(),
|
||||||
notes: trimmedNullableText(3000),
|
notes: trimmedNullableText(3000),
|
||||||
|
/** OH13 — CAS token; absent → last-write-wins. */
|
||||||
|
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||||
})
|
})
|
||||||
|
|
||||||
export type LeadershipInternalUpdateInput = z.input<typeof leadershipInternalUpdateSchema>
|
export type LeadershipInternalUpdateInput = z.input<typeof leadershipInternalUpdateSchema>
|
||||||
|
|
@ -114,6 +117,7 @@ export const leadershipStateDeputyMembershipSchema = z.object({
|
||||||
leadershipId: positiveRelationshipId,
|
leadershipId: positiveRelationshipId,
|
||||||
stateDeputyId: positiveRelationshipId,
|
stateDeputyId: positiveRelationshipId,
|
||||||
assigned: z.boolean(),
|
assigned: z.boolean(),
|
||||||
|
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||||
})
|
})
|
||||||
|
|
||||||
export type LeadershipStateDeputyMembershipInput = z.input<
|
export type LeadershipStateDeputyMembershipInput = z.input<
|
||||||
|
|
@ -134,6 +138,7 @@ export const leadershipMunicipalitiesMembershipSchema = z.object({
|
||||||
.max(MAX_LEADERSHIP_MUNICIPALITIES)
|
.max(MAX_LEADERSHIP_MUNICIPALITIES)
|
||||||
.transform((ids) => [...new Set(ids)]),
|
.transform((ids) => [...new Set(ids)]),
|
||||||
assigned: z.boolean(),
|
assigned: z.boolean(),
|
||||||
|
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||||
})
|
})
|
||||||
|
|
||||||
export type LeadershipMunicipalitiesMembershipInput = z.input<
|
export type LeadershipMunicipalitiesMembershipInput = z.input<
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import {
|
||||||
MAX_MUNICIPALITIES_PER_BATCH,
|
MAX_MUNICIPALITIES_PER_BATCH,
|
||||||
MUNICIPALITY_STATE_DEPUTIES_CAP_MESSAGE,
|
MUNICIPALITY_STATE_DEPUTIES_CAP_MESSAGE,
|
||||||
} from '@/lib/schemas/municipality'
|
} from '@/lib/schemas/municipality'
|
||||||
|
import { OPS_UPDATED_AT_CONFLICT_MESSAGE, optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
|
||||||
import {
|
import {
|
||||||
positiveRelationshipId,
|
positiveRelationshipId,
|
||||||
trimmedNullableText,
|
trimmedNullableText,
|
||||||
|
|
@ -50,11 +51,17 @@ export const stateDeputyMunicipalitiesBatchSchema = z.object({
|
||||||
.max(MAX_MUNICIPALITIES_PER_BATCH)
|
.max(MAX_MUNICIPALITIES_PER_BATCH)
|
||||||
.transform((ids) => [...new Set(ids)]),
|
.transform((ids) => [...new Set(ids)]),
|
||||||
assigned: z.boolean(),
|
assigned: z.boolean(),
|
||||||
|
/**
|
||||||
|
* OH13 — CAS bases keyed by municipality id (batch touches many docs).
|
||||||
|
* Absent / missing id → last-write-wins for that município.
|
||||||
|
*/
|
||||||
|
municipalityBaseUpdatedAt: z.record(z.string(), optionalBaseUpdatedAtSchema).optional(),
|
||||||
})
|
})
|
||||||
|
|
||||||
export const STATE_DEPUTY_MUNICIPALITIES_SAFE_MESSAGES = [
|
export const STATE_DEPUTY_MUNICIPALITIES_SAFE_MESSAGES = [
|
||||||
STATE_DEPUTY_STAFF_MESSAGE,
|
STATE_DEPUTY_STAFF_MESSAGE,
|
||||||
MUNICIPALITY_STATE_DEPUTIES_CAP_MESSAGE,
|
MUNICIPALITY_STATE_DEPUTIES_CAP_MESSAGE,
|
||||||
|
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
export type StateDeputyCreateInput = z.input<typeof stateDeputyCreateSchema>
|
export type StateDeputyCreateInput = z.input<typeof stateDeputyCreateSchema>
|
||||||
|
|
|
||||||
|
|
@ -143,6 +143,8 @@ export type ActivityFormViewModel = {
|
||||||
responsible: { id: number; name: string; phone: string | null } | null
|
responsible: { id: number; name: string; phone: string | null } | null
|
||||||
leadership: { id: number; label: string } | null
|
leadership: { id: number; label: string } | null
|
||||||
tasks: ActivityFormTaskViewModel[]
|
tasks: ActivityFormTaskViewModel[]
|
||||||
|
/** OH13 — CAS token for staff updates when OPS_HYBRID is on. */
|
||||||
|
updatedAt: string
|
||||||
}
|
}
|
||||||
|
|
||||||
const relationshipIds = (value: unknown): number[] =>
|
const relationshipIds = (value: unknown): number[] =>
|
||||||
|
|
@ -196,6 +198,7 @@ export const toActivityFormViewModel = (activity: Activity): ActivityFormViewMod
|
||||||
due: task.due ?? null,
|
due: task.due ?? null,
|
||||||
done: Boolean(task.done),
|
done: Boolean(task.done),
|
||||||
})),
|
})),
|
||||||
|
updatedAt: activity.updatedAt,
|
||||||
})
|
})
|
||||||
|
|
||||||
const activityDetailContextSelect = {
|
const activityDetailContextSelect = {
|
||||||
|
|
|
||||||
|
|
@ -153,6 +153,8 @@ export type DemandDetailViewModel = DemandRowViewModel & {
|
||||||
}>
|
}>
|
||||||
canLeaderEdit: boolean
|
canLeaderEdit: boolean
|
||||||
activity: { title: string; slug: string } | null
|
activity: { title: string; slug: string } | null
|
||||||
|
/** OH13 — CAS token for staff transitions when OPS_HYBRID is on. */
|
||||||
|
updatedAt: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export const loadDemandDetail = async (
|
export const loadDemandDetail = async (
|
||||||
|
|
@ -217,5 +219,6 @@ export const loadDemandDetail = async (
|
||||||
activity: isPopulatedRelationship<Activity>(demand.activity)
|
activity: isPopulatedRelationship<Activity>(demand.activity)
|
||||||
? { title: demand.activity.title, slug: demand.activity.slug }
|
? { title: demand.activity.title, slug: demand.activity.slug }
|
||||||
: null,
|
: null,
|
||||||
|
updatedAt: demand.updatedAt,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
298
tests/int/domainWritesCas.int.spec.ts
Normal file
298
tests/int/domainWritesCas.int.spec.ts
Normal file
|
|
@ -0,0 +1,298 @@
|
||||||
|
// @vitest-environment node
|
||||||
|
|
||||||
|
import type { Payload } from 'payload'
|
||||||
|
import { getPayload } from 'payload'
|
||||||
|
import { beforeAll, describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import {
|
||||||
|
updateLeadershipInternalCasRecord,
|
||||||
|
updateLeadershipInternalRecord,
|
||||||
|
} from '@/app/(campaign)/campanha/actions/leadership'
|
||||||
|
import {
|
||||||
|
createCampaignDemandRecord,
|
||||||
|
transitionCampaignDemandCasRecord,
|
||||||
|
transitionCampaignDemandRecord,
|
||||||
|
} from '@/app/(campaign)/campanha/actions/demand'
|
||||||
|
import { updateActivityCasRecord, createActivityRecord } from '@/app/(campaign)/campanha/actions/activity'
|
||||||
|
import {
|
||||||
|
setStateDeputyMunicipalitiesBatchCasRecord,
|
||||||
|
setStateDeputyMunicipalitiesBatchRecord,
|
||||||
|
} from '@/app/(campaign)/campanha/actions/stateDeputy'
|
||||||
|
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('updateLeadershipInternalCas (OH13)', () => {
|
||||||
|
beforeAll(async () => {
|
||||||
|
payload = await getPayload({ config: await config })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('writes 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 contact = await fixtures.createContact()
|
||||||
|
const leadership = await fixtures.createLeadership({
|
||||||
|
contact: contact.id,
|
||||||
|
municipalities: [municipality.id],
|
||||||
|
supportStatus: 'a_abordar',
|
||||||
|
})
|
||||||
|
|
||||||
|
const updated = await updateLeadershipInternalCasRecord(payload, advisor, {
|
||||||
|
id: leadership.id,
|
||||||
|
supportStatus: 'engajado',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(updated.supportStatus).toBe('engajado')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses a stale baseUpdatedAt without writing', 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: 'a_abordar',
|
||||||
|
})
|
||||||
|
const baseUpdatedAt = leadership.updatedAt
|
||||||
|
|
||||||
|
await updateLeadershipInternalRecord(payload, advisor, {
|
||||||
|
id: leadership.id,
|
||||||
|
supportStatus: 'em_disputa',
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
updateLeadershipInternalCasRecord(payload, advisor, {
|
||||||
|
id: leadership.id,
|
||||||
|
supportStatus: 'engajado',
|
||||||
|
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: 'leadership',
|
||||||
|
id: leadership.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
expect(current.supportStatus).toBe('em_disputa')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('writes when baseUpdatedAt matches', 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: 'a_abordar',
|
||||||
|
})
|
||||||
|
|
||||||
|
const updated = await updateLeadershipInternalCasRecord(payload, advisor, {
|
||||||
|
id: leadership.id,
|
||||||
|
supportStatus: 'engajado',
|
||||||
|
baseUpdatedAt: leadership.updatedAt,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(updated.supportStatus).toBe('engajado')
|
||||||
|
expect(updated.updatedAt).not.toBe(leadership.updatedAt)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('transitionCampaignDemandCas (OH13)', () => {
|
||||||
|
beforeAll(async () => {
|
||||||
|
payload = await getPayload({ config: await config })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('writes when baseUpdatedAt matches and respects advisor scope', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor')
|
||||||
|
await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
|
||||||
|
|
||||||
|
const demand = await createCampaignDemandRecord(payload, advisor, {
|
||||||
|
title: 'CAS demanda ok',
|
||||||
|
kind: 'material',
|
||||||
|
municipality: municipality.id,
|
||||||
|
})
|
||||||
|
fixtures.own('campaignDemand', demand.id)
|
||||||
|
|
||||||
|
const updated = await transitionCampaignDemandCasRecord(payload, advisor, {
|
||||||
|
id: demand.id,
|
||||||
|
status: 'em_analise',
|
||||||
|
baseUpdatedAt: demand.updatedAt,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(updated.status).toBe('em_analise')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses a stale baseUpdatedAt without writing', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor')
|
||||||
|
await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
|
||||||
|
|
||||||
|
const demand = await createCampaignDemandRecord(payload, advisor, {
|
||||||
|
title: 'CAS demanda stale',
|
||||||
|
kind: 'servico',
|
||||||
|
municipality: municipality.id,
|
||||||
|
})
|
||||||
|
fixtures.own('campaignDemand', demand.id)
|
||||||
|
const baseUpdatedAt = demand.updatedAt
|
||||||
|
|
||||||
|
await transitionCampaignDemandRecord(payload, advisor, {
|
||||||
|
id: demand.id,
|
||||||
|
status: 'em_analise',
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
transitionCampaignDemandCasRecord(payload, advisor, {
|
||||||
|
id: demand.id,
|
||||||
|
status: 'aprovada',
|
||||||
|
baseUpdatedAt,
|
||||||
|
}),
|
||||||
|
).rejects.toSatisfy((error: unknown) => {
|
||||||
|
expect(error).toBeInstanceOf(Error)
|
||||||
|
expect(isOpsUpdatedAtConflictMessage((error as Error).message)).toBe(true)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
const current = await payload.findByID({
|
||||||
|
collection: 'campaignDemand',
|
||||||
|
id: demand.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
expect(current.status).toBe('em_analise')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('still refuses escalated decisions for advisors under CAS', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor')
|
||||||
|
await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
|
||||||
|
|
||||||
|
const demand = await createCampaignDemandRecord(payload, advisor, {
|
||||||
|
title: 'CAS demanda escalada',
|
||||||
|
kind: 'transporte',
|
||||||
|
municipality: municipality.id,
|
||||||
|
})
|
||||||
|
fixtures.own('campaignDemand', demand.id)
|
||||||
|
|
||||||
|
const escalated = await transitionCampaignDemandRecord(payload, advisor, {
|
||||||
|
id: demand.id,
|
||||||
|
status: 'escalada',
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
transitionCampaignDemandCasRecord(payload, advisor, {
|
||||||
|
id: demand.id,
|
||||||
|
status: 'aprovada',
|
||||||
|
baseUpdatedAt: escalated.updatedAt,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('updateActivityCas (OH13)', () => {
|
||||||
|
beforeAll(async () => {
|
||||||
|
payload = await getPayload({ config: await config })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses a stale baseUpdatedAt without writing', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor')
|
||||||
|
await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
|
||||||
|
|
||||||
|
const activity = await createActivityRecord(payload, advisor, {
|
||||||
|
title: 'CAS atividade',
|
||||||
|
kind: 'reuniao_apoio',
|
||||||
|
municipality: municipality.id,
|
||||||
|
status: 'rascunho',
|
||||||
|
advisors: [advisor.id],
|
||||||
|
})
|
||||||
|
fixtures.own('activity', activity.id)
|
||||||
|
const baseUpdatedAt = activity.updatedAt
|
||||||
|
|
||||||
|
await updateActivityCasRecord(payload, advisor, {
|
||||||
|
id: activity.id,
|
||||||
|
locality: 'Centro',
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
updateActivityCasRecord(payload, advisor, {
|
||||||
|
id: activity.id,
|
||||||
|
locality: 'Bairro Novo',
|
||||||
|
baseUpdatedAt,
|
||||||
|
}),
|
||||||
|
).rejects.toSatisfy((error: unknown) => {
|
||||||
|
expect(isOpsUpdatedAtConflictMessage((error as Error).message)).toBe(true)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
const current = await payload.findByID({
|
||||||
|
collection: 'activity',
|
||||||
|
id: activity.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
expect(current.locality).toBe('Centro')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('setStateDeputyMunicipalitiesBatchCas (OH13)', () => {
|
||||||
|
beforeAll(async () => {
|
||||||
|
payload = await getPayload({ config: await config })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses when a municipality base is stale', async () => {
|
||||||
|
const fixtures = campaignFixtures()
|
||||||
|
const municipality = await fixtures.getMunicipality()
|
||||||
|
const coordinator = await fixtures.createCampaignUser('coordinator')
|
||||||
|
const stateDeputy = await fixtures.createStateDeputy({ name: `CAS SD ${Date.now()}` })
|
||||||
|
const baseUpdatedAt = municipality.updatedAt
|
||||||
|
|
||||||
|
await setStateDeputyMunicipalitiesBatchRecord(payload, coordinator, {
|
||||||
|
stateDeputyId: stateDeputy.id,
|
||||||
|
municipalityIds: [municipality.id],
|
||||||
|
assigned: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
setStateDeputyMunicipalitiesBatchCasRecord(payload, coordinator, {
|
||||||
|
stateDeputyId: stateDeputy.id,
|
||||||
|
municipalityIds: [municipality.id],
|
||||||
|
assigned: false,
|
||||||
|
municipalityBaseUpdatedAt: { [String(municipality.id)]: baseUpdatedAt },
|
||||||
|
}),
|
||||||
|
).rejects.toSatisfy((error: unknown) => {
|
||||||
|
expect(isOpsUpdatedAtConflictMessage((error as Error).message)).toBe(true)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
43
tests/unit/opsDomainOutbox.unit.spec.ts
Normal file
43
tests/unit/opsDomainOutbox.unit.spec.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import {
|
||||||
|
collapseLeadershipUpdateOutbox,
|
||||||
|
leadershipMembershipOutboxKey,
|
||||||
|
stateDeputyMunicipalitiesOutboxKey,
|
||||||
|
} from '@/components/campaign/opsSync/opsDomainOutboxModel'
|
||||||
|
import type { OfflineTransaction } from '@tanstack/offline-transactions'
|
||||||
|
|
||||||
|
const tx = (
|
||||||
|
id: string,
|
||||||
|
leadershipId: number,
|
||||||
|
createdAtMs: number,
|
||||||
|
): OfflineTransaction =>
|
||||||
|
({
|
||||||
|
id,
|
||||||
|
mutationFnName: 'updateLeadershipInternal',
|
||||||
|
mutations: [{ key: leadershipId } as OfflineTransaction['mutations'][number]],
|
||||||
|
keys: [String(leadershipId)],
|
||||||
|
idempotencyKey: id,
|
||||||
|
createdAt: new Date(createdAtMs),
|
||||||
|
retryCount: 0,
|
||||||
|
nextAttemptAt: createdAtMs,
|
||||||
|
metadata: { leadershipId },
|
||||||
|
version: 1,
|
||||||
|
}) as OfflineTransaction
|
||||||
|
|
||||||
|
describe('opsDomainOutboxModel (OH13)', () => {
|
||||||
|
it('collapses superseded leadership updates', () => {
|
||||||
|
const collapsed = collapseLeadershipUpdateOutbox([
|
||||||
|
tx('a', 1, 1000),
|
||||||
|
tx('b', 1, 3000),
|
||||||
|
tx('c', 2, 2000),
|
||||||
|
])
|
||||||
|
|
||||||
|
expect(collapsed.map((entry) => entry.id)).toEqual(['c', 'b'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('builds stable membership and batch keys', () => {
|
||||||
|
expect(leadershipMembershipOutboxKey('municipalities', 9, 3)).toBe('municipalities:9:3')
|
||||||
|
expect(stateDeputyMunicipalitiesOutboxKey(4, [3, 1, 2], true)).toBe('4:add:1,2,3')
|
||||||
|
})
|
||||||
|
})
|
||||||
Loading…
Reference in a new issue