mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
Merge pull request #227 from fsolla/cursor/pool-i176-3ee4bb09-eb8c
OH13 — Writes CAS por domínio: leadership, stateDeputy, activity, demand
This commit is contained in:
commit
15949be761
30 changed files with 2040 additions and 77 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):** **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
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-08-01
|
||||
Status: pronto para PR
|
||||
Atualizado em: 2026-08-02
|
||||
Issue: #176
|
||||
Priority: P1
|
||||
Model: cursor-grok-4.5-medium
|
||||
|
|
@ -10,13 +10,21 @@ Appetite: ~2–3 dias eng
|
|||
Depends: OH10, OH12
|
||||
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
|
||||
|
||||
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.
|
||||
3. Sem migration: todas estas writes usam collections existentes.
|
||||
|
||||
→ Corrija agora ou sigo com estas.
|
||||
→ Confirmadas; a implementar.
|
||||
|
||||
## Objetivos
|
||||
|
||||
|
|
@ -49,8 +57,8 @@ Componentes:
|
|||
|
||||
- **Quota:** ~0,5
|
||||
- **Aceite:**
|
||||
- [ ] criar/editar leadership offline → pending → aplica; conflito com escolha
|
||||
- [ ] decisão de demanda offline → pending → aplica; access advisor respeitado (pin int)
|
||||
- [x] criar/editar leadership offline → pending → aplica; conflito com escolha
|
||||
- [x] decisão de demanda offline → pending → aplica; access advisor respeitado (pin int)
|
||||
- **Verify:** `pnpm gate:fast` + int CAS + e2e flaky
|
||||
- **Files:** schemas, actions, outbox, specs
|
||||
- **Tamanho:** M
|
||||
|
|
@ -59,11 +67,11 @@ Componentes:
|
|||
|
||||
- **Quota:** ~0,5
|
||||
- **Aceite:**
|
||||
- [ ] vínculos offline aplicam; conflito UI
|
||||
- [ ] campos de activity offline aplicam
|
||||
- [ ] helper extraído **só se** 3+ call sites (senão, nota no PR por que não)
|
||||
- [x] vínculos offline aplicam; conflito UI (CAS server + `*Cas` entry points; list chips stay online form — OH12 Local read-only; outbox trimmed to used surfaces)
|
||||
- [x] campos de activity offline aplicam
|
||||
- [x] helper extraído: `assertCampaignDocCas` (demand/activity) + inline `assertOpsUpdatedAtCas` when stamp already loaded
|
||||
- **Verify:** `pnpm gate:fast` + int + e2e
|
||||
- **Files:** idem + helper condicional
|
||||
- **Files:** idem + helper
|
||||
- **Tamanho:** M
|
||||
|
||||
## Dependências
|
||||
|
|
|
|||
|
|
@ -128,6 +128,7 @@ export default async function DemandDetailPage({ params }: DemandDetailPageProps
|
|||
status={demand.status}
|
||||
canDecideEscalated={isCampaignUnrestricted(user)}
|
||||
currentCost={demand.cost}
|
||||
updatedAt={demand.updatedAt}
|
||||
transitionFormAction={transitionDemandFormAction}
|
||||
costFormAction={setDemandCostFormAction}
|
||||
receiptFormAction={attachDemandReceiptFormAction}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import { LEADERSHIP_STAFF_MESSAGE } from '@/lib/schemas/leadership'
|
||||
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||
|
||||
/** 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" />
|
||||
),
|
||||
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 { assertCampaignDocCas } from '@/app/(campaign)/campanha/actions/assertCampaignDocCas'
|
||||
import {
|
||||
ACTIVITY_RESULT_REQUIRED_MESSAGE,
|
||||
ACTIVITY_RESULT_STAFF_MESSAGE,
|
||||
|
|
@ -162,15 +163,26 @@ const updateActivityRecord = async (
|
|||
actor: CampaignUser,
|
||||
input: ActivityUpdateInput,
|
||||
demandDrafts: ActivityDemandDraft[] = [],
|
||||
options?: { cas?: boolean },
|
||||
) => {
|
||||
const { id, ...data } = activityUpdateSchema.parse(input)
|
||||
const { id, baseUpdatedAt, ...data } = activityUpdateSchema.parse(input)
|
||||
const demands = activityDemandDraftsSchema.parse(demandDrafts)
|
||||
const enforceCas = options?.cas === true
|
||||
|
||||
return withPayloadTransaction(
|
||||
payload,
|
||||
async ({ req }) => {
|
||||
const currentActor = await reloadCampaignActor(payload, actor, req)
|
||||
|
||||
await assertCampaignDocCas(payload, {
|
||||
collection: 'activity',
|
||||
id,
|
||||
actor: currentActor,
|
||||
enforceCas,
|
||||
baseUpdatedAt,
|
||||
req,
|
||||
})
|
||||
|
||||
const activity = await payload.update({
|
||||
collection: 'activity',
|
||||
id,
|
||||
|
|
@ -363,6 +375,15 @@ export const createActivity = async (
|
|||
return createActivityRecord(payload, actor, input, demandDrafts)
|
||||
}
|
||||
|
||||
/**
|
||||
* Outbox / hybrid entry for create — no CAS (new doc).
|
||||
* @public Kept as the CAS-named twin of `createActivity` for offline enqueue.
|
||||
*/
|
||||
export const createActivityCas = async (
|
||||
input: ActivityCreateInput,
|
||||
demandDrafts: ActivityDemandDraft[] = [],
|
||||
) => createActivity(input, demandDrafts)
|
||||
|
||||
export const updateActivity = async (
|
||||
input: ActivityUpdateInput,
|
||||
demandDrafts: ActivityDemandDraft[] = [],
|
||||
|
|
@ -371,6 +392,21 @@ export const updateActivity = async (
|
|||
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) => {
|
||||
const { payload, actor } = await getCampaignActionContext()
|
||||
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 { assertCampaignDocCas } from '@/app/(campaign)/campanha/actions/assertCampaignDocCas'
|
||||
import {
|
||||
CAMPAIGN_DEMAND_COST_STAFF_MESSAGE,
|
||||
CAMPAIGN_DEMAND_RECEIPT_EMPTY_MESSAGE,
|
||||
|
|
@ -60,8 +61,10 @@ export const transitionCampaignDemandRecord = async (
|
|||
payload: Payload,
|
||||
actor: CampaignUser,
|
||||
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(
|
||||
payload,
|
||||
|
|
@ -72,6 +75,15 @@ export const transitionCampaignDemandRecord = async (
|
|||
}
|
||||
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
|
||||
// enforced by the collection hook.
|
||||
return payload.update({
|
||||
|
|
@ -199,6 +211,17 @@ export const transitionCampaignDemand = async (input: CampaignDemandTransitionIn
|
|||
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) => {
|
||||
const { payload, actor } = await getCampaignActionContext()
|
||||
return setCampaignDemandCostRecord(payload, actor, input)
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ import {
|
|||
type LeadershipWizardCreateInput,
|
||||
type LeadershipWizardUpdateInput,
|
||||
} from '@/lib/schemas/leadership'
|
||||
import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas'
|
||||
import type { CampaignUser, Contact } from '@/payload-types'
|
||||
import { getAdvisorMunicipalityIds } from '@/utilities/campaignAccess'
|
||||
import { getCampaignActionContext, reloadStaffActor } from '@/utilities/campaignActionContext'
|
||||
|
|
@ -176,9 +177,11 @@ export const updateLeadershipInternalRecord = async (
|
|||
payload: Payload,
|
||||
actor: CampaignUser,
|
||||
input: LeadershipInternalUpdateInput,
|
||||
options?: { cas?: boolean },
|
||||
) => {
|
||||
const { id, municipalities, organizations, stateDeputies, ...data } =
|
||||
const { id, municipalities, organizations, stateDeputies, baseUpdatedAt, ...data } =
|
||||
leadershipInternalUpdateSchema.parse(input)
|
||||
const enforceCas = options?.cas === true
|
||||
const currentActor = await getFreshStaffActor(payload, actor)
|
||||
|
||||
// Row access verifies the current record is in the actor's scope.
|
||||
|
|
@ -190,6 +193,9 @@ export const updateLeadershipInternalRecord = async (
|
|||
overrideAccess: false,
|
||||
})
|
||||
|
||||
// Stamp already loaded with the row — avoid a second find via assertCampaignDocCas.
|
||||
assertOpsUpdatedAtCas(enforceCas, baseUpdatedAt, current.updatedAt)
|
||||
|
||||
if (municipalities !== undefined) {
|
||||
await assertMunicipalitiesWithinScope(payload, currentActor, municipalities)
|
||||
}
|
||||
|
|
@ -232,11 +238,25 @@ export const createLeadership = async (input: unknown) => {
|
|||
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) => {
|
||||
const { payload, actor } = await getCampaignActionContext()
|
||||
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) => {
|
||||
revalidatePath(`/campanha/liderancas/${leadershipId}`, 'page')
|
||||
revalidatePath(`/campanha/municipios/${municipalitySlug}`, 'page')
|
||||
|
|
@ -416,7 +436,7 @@ const openLeadershipForRelationDelta = async <
|
|||
collection: 'leadership',
|
||||
id: leadershipId,
|
||||
depth: 0,
|
||||
select: { [relation]: true } as Record<Relation, true>,
|
||||
select: { [relation]: true, updatedAt: true } as Record<Relation | 'updatedAt', true>,
|
||||
user: currentActor,
|
||||
overrideAccess: false,
|
||||
req,
|
||||
|
|
@ -436,9 +456,11 @@ export const setLeadershipStateDeputyMembershipRecord = async (
|
|||
payload: Payload,
|
||||
actor: CampaignUser,
|
||||
input: LeadershipStateDeputyMembershipInput,
|
||||
options?: { cas?: boolean },
|
||||
) => {
|
||||
const { leadershipId, stateDeputyId, assigned } =
|
||||
const { leadershipId, stateDeputyId, assigned, baseUpdatedAt } =
|
||||
leadershipStateDeputyMembershipSchema.parse(input)
|
||||
const enforceCas = options?.cas === true
|
||||
|
||||
return withPayloadTransaction(
|
||||
payload,
|
||||
|
|
@ -451,6 +473,8 @@ export const setLeadershipStateDeputyMembershipRecord = async (
|
|||
'stateDeputies',
|
||||
)
|
||||
|
||||
assertOpsUpdatedAtCas(enforceCas, baseUpdatedAt, current.updatedAt)
|
||||
|
||||
const currentStateDeputyIDs = uniqueRelationshipIds(current.stateDeputies)
|
||||
const nextStateDeputyIDs = nextStateDeputyIdsAfterMembership(
|
||||
currentStateDeputyIDs,
|
||||
|
|
@ -508,6 +532,21 @@ export const setLeadershipStateDeputyMembership = async (
|
|||
return leadership
|
||||
}
|
||||
|
||||
/** @public CAS entry for offline/hybrid membership writes (OH13). */
|
||||
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
|
||||
* IS on that list, and it already shows the result optimistically, so
|
||||
|
|
@ -544,9 +583,11 @@ export const setLeadershipMunicipalitiesMembershipRecord = async (
|
|||
payload: Payload,
|
||||
actor: CampaignUser,
|
||||
input: LeadershipMunicipalitiesMembershipInput,
|
||||
options?: { cas?: boolean },
|
||||
) => {
|
||||
const { leadershipId, municipalityIds, assigned } =
|
||||
const { leadershipId, municipalityIds, assigned, baseUpdatedAt } =
|
||||
leadershipMunicipalitiesMembershipSchema.parse(input)
|
||||
const enforceCas = options?.cas === true
|
||||
|
||||
return withPayloadTransaction(
|
||||
payload,
|
||||
|
|
@ -559,6 +600,8 @@ export const setLeadershipMunicipalitiesMembershipRecord = async (
|
|||
'municipalities',
|
||||
)
|
||||
|
||||
assertOpsUpdatedAtCas(enforceCas, baseUpdatedAt, current.updatedAt)
|
||||
|
||||
const change = nextMunicipalityIdsAfterLeadershipMembership(
|
||||
uniqueRelationshipIds(current.municipalities),
|
||||
municipalityIds,
|
||||
|
|
@ -621,3 +664,20 @@ export const setLeadershipMunicipalitiesMembership = async (
|
|||
}
|
||||
return leadership
|
||||
}
|
||||
|
||||
/** @public CAS entry for offline/hybrid membership writes (OH13). */
|
||||
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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import type { Payload } from 'payload'
|
|||
|
||||
import { nextStateDeputyIdsAfterMunicipalityMembership } from '@/lib/municipalityStateDeputyMembership'
|
||||
import { uniqueRelationshipIds } from '@/lib/relationship'
|
||||
import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas'
|
||||
import {
|
||||
STATE_DEPUTY_CONFLICT_MESSAGE,
|
||||
STATE_DEPUTY_STAFF_MESSAGE,
|
||||
|
|
@ -108,9 +109,11 @@ export const setStateDeputyMunicipalitiesBatchRecord = async (
|
|||
payload: Payload,
|
||||
actor: CampaignUser,
|
||||
input: StateDeputyMunicipalitiesBatchInput,
|
||||
options?: { cas?: boolean },
|
||||
) => {
|
||||
const { stateDeputyId, municipalityIds, assigned } =
|
||||
const { stateDeputyId, municipalityIds, assigned, municipalityBaseUpdatedAt } =
|
||||
stateDeputyMunicipalitiesBatchSchema.parse(input)
|
||||
const enforceCas = options?.cas === true
|
||||
// Already deduped by the schema's `.transform`; sorted only so a batch applies
|
||||
// and reports in a stable order — `acquireTextAdvisoryLocks` sorts its own keys,
|
||||
// so the deadlock-avoidance ordering does not depend on this line.
|
||||
|
|
@ -134,19 +137,24 @@ export const setStateDeputyMunicipalitiesBatchRecord = async (
|
|||
const changedSlugs: string[] = []
|
||||
|
||||
for (const municipalityId of uniqueMunicipalityIds) {
|
||||
const baseForMunicipality = municipalityBaseUpdatedAt?.[String(municipalityId)]
|
||||
|
||||
// Row + field access verify the município is in the actor's scope
|
||||
// (`canUpdateMunicipality` for advisors, `canManageCampaignStaffField`
|
||||
// for the field) — an out-of-scope município throws here.
|
||||
// CAS stamp rides the same load (OH13) — avoid a second findByID.
|
||||
const municipality = await payload.findByID({
|
||||
collection: 'municipality',
|
||||
id: municipalityId,
|
||||
depth: 0,
|
||||
select: { stateDeputies: true, slug: true },
|
||||
select: { stateDeputies: true, slug: true, updatedAt: true },
|
||||
user: currentActor,
|
||||
overrideAccess: false,
|
||||
req,
|
||||
})
|
||||
|
||||
assertOpsUpdatedAtCas(enforceCas, baseForMunicipality, municipality.updatedAt)
|
||||
|
||||
const currentStateDeputyIDs = uniqueRelationshipIds(municipality.stateDeputies)
|
||||
const nextStateDeputyIDs = nextStateDeputyIdsAfterMunicipalityMembership(
|
||||
currentStateDeputyIDs,
|
||||
|
|
@ -204,3 +212,23 @@ export const setStateDeputyMunicipalitiesBatch = async (
|
|||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** @public CAS entry for offline/hybrid batch municipality writes (OH13). */
|
||||
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,26 @@
|
|||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { useActionState, useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import {
|
||||
useActionState,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
type FormEvent,
|
||||
} from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { ActivityDemandFields } from '@/components/campaign/activity/ActivityDemandFields'
|
||||
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 {
|
||||
ContactCombobox,
|
||||
|
|
@ -15,6 +31,7 @@ import {
|
|||
type RelationOption,
|
||||
} from '@/components/campaign/shared/RelationMultiSelect'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/Alert'
|
||||
import { Badge } from '@/components/ui/Badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Checkbox } from '@/components/ui/Checkbox'
|
||||
|
|
@ -32,13 +49,21 @@ import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
|||
import { Spinner } from '@/components/ui/Spinner'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/ToggleGroup'
|
||||
import { formatIsoAsBahiaDateTimeInput } from '@/lib/campaignTime'
|
||||
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||
import { readFormRelationshipIds, readOptionalFormText } from '@/lib/campaignOps/opsHybridFormData'
|
||||
import { formatIsoAsBahiaDateTimeInput, parseBahiaDateTimeInput } from '@/lib/campaignTime'
|
||||
import { isContactSearchQueryReady } from '@/lib/contactSearchQuery'
|
||||
import {
|
||||
activityKindLabels,
|
||||
activityKinds,
|
||||
activityOriginLabels,
|
||||
activityOrigins,
|
||||
activityStatusLabels,
|
||||
activityStatuses,
|
||||
type ActivityKind,
|
||||
type ActivityOrigin,
|
||||
} from '@/lib/schemas/activity'
|
||||
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||
import type { ActivityLeadershipOption } from '@/utilities/activityLeadershipOptions'
|
||||
import type { ActivityFormViewModel } from '@/utilities/activityViewModels'
|
||||
import { fieldError } from '@/utilities/campaignFormFields'
|
||||
|
|
@ -458,6 +483,8 @@ const ActivityFormFields = ({
|
|||
)
|
||||
}
|
||||
|
||||
const CONFLICT_TOAST_ID_PREFIX = 'ops-activity-update-conflict:'
|
||||
|
||||
export const ActivityForm = ({
|
||||
action,
|
||||
municipalityOptions,
|
||||
|
|
@ -468,26 +495,176 @@ export const ActivityForm = ({
|
|||
submitLabel,
|
||||
searchContacts,
|
||||
searchLeaderships,
|
||||
opsHybridEnabled = resolveOpsHybridEnabled(),
|
||||
}: ActivityFormFieldsProps & {
|
||||
action: ActivityFormAction
|
||||
submitLabel: string
|
||||
opsHybridEnabled?: boolean
|
||||
}) => {
|
||||
const router = useRouter()
|
||||
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 responsibleRaw = data.get('responsible')
|
||||
const responsible =
|
||||
typeof responsibleRaw === 'string' && Number.isInteger(Number(responsibleRaw))
|
||||
? Number(responsibleRaw)
|
||||
: undefined
|
||||
const leadershipRaw = data.get('leadership')
|
||||
const leadershipId =
|
||||
typeof leadershipRaw === 'string' && Number.isInteger(Number(leadershipRaw))
|
||||
? Number(leadershipRaw)
|
||||
: undefined
|
||||
const startAtRaw = readOptionalFormText(data, 'startAt')
|
||||
const endAtRaw = readOptionalFormText(data, 'endAt')
|
||||
const deadlineRaw = readOptionalFormText(data, 'deadline')
|
||||
const startAt = startAtRaw ? (parseBahiaDateTimeInput(startAtRaw) ?? null) : null
|
||||
const endAt = endAtRaw ? (parseBahiaDateTimeInput(endAtRaw) ?? null) : null
|
||||
const deadline = deadlineRaw ? (parseBahiaDateTimeInput(deadlineRaw) ?? null) : null
|
||||
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: readOptionalFormText(data, 'description') ?? null,
|
||||
locality: readOptionalFormText(data, 'locality') ?? null,
|
||||
organizations: readFormRelationshipIds(data, 'organizations'),
|
||||
advisors: readFormRelationshipIds(data, 'advisors'),
|
||||
deputyPresent: data.get('deputyPresent') === 'true' || data.get('deputyPresent') === 'on',
|
||||
startAt,
|
||||
endAt,
|
||||
deadline,
|
||||
...(responsible !== undefined ? { responsible } : {}),
|
||||
...(leadershipId !== undefined ? { leadership: leadershipId } : {}),
|
||||
},
|
||||
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 (
|
||||
<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}
|
||||
{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">
|
||||
<AlertTitle>Não foi possível salvar</AlertTitle>
|
||||
<AlertDescription>{state.message}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
{state.existingHref ? (
|
||||
{!hybridUpdate && state.existingHref ? (
|
||||
<Button asChild variant="outline" className="min-h-11 w-fit">
|
||||
<Link href={state.existingHref}>Abrir atividade existente</Link>
|
||||
</Button>
|
||||
) : null}
|
||||
{hybridMessage ? (
|
||||
<p className="text-sm text-muted-foreground" role="status">
|
||||
{hybridMessage}
|
||||
</p>
|
||||
) : null}
|
||||
<ActivityFormFields
|
||||
municipalityOptions={municipalityOptions}
|
||||
organizationOptions={organizationOptions}
|
||||
|
|
@ -505,9 +682,9 @@ export const ActivityForm = ({
|
|||
Cancelar
|
||||
</Link>
|
||||
</Button>
|
||||
<Button type="submit" className="min-h-11" disabled={pending}>
|
||||
{pending ? <Spinner data-icon="inline-start" /> : null}
|
||||
{pending ? 'Salvando…' : submitLabel}
|
||||
<Button type="submit" className="min-h-11" disabled={busy}>
|
||||
{busy ? <Spinner data-icon="inline-start" /> : null}
|
||||
{busy ? 'Salvando…' : submitLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
|
|
|||
|
|
@ -1,18 +1,38 @@
|
|||
'use client'
|
||||
|
||||
import { useActionState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import {
|
||||
useActionState,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
type FormEvent,
|
||||
} from 'react'
|
||||
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 { Badge } from '@/components/ui/Badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Spinner } from '@/components/ui/Spinner'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||
import {
|
||||
campaignDemandStatuses,
|
||||
campaignDemandTransitionLabels,
|
||||
campaignDemandTransitions,
|
||||
type CampaignDemandStatus,
|
||||
} from '@/lib/schemas/campaignDemand'
|
||||
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
||||
import { fieldError } from '@/utilities/campaignFormFields'
|
||||
|
||||
|
|
@ -27,11 +47,16 @@ type DemandWorkflowCardProps = {
|
|||
/** Coordinator or candidate — the roles allowed to decide escalated demands. */
|
||||
canDecideEscalated: boolean
|
||||
currentCost: number | null
|
||||
/** OH13 — CAS base when OPS_HYBRID outbox path is on. */
|
||||
updatedAt?: string
|
||||
opsHybridEnabled?: boolean
|
||||
transitionFormAction: FormAction
|
||||
costFormAction: FormAction
|
||||
receiptFormAction: FormAction
|
||||
}
|
||||
|
||||
const CONFLICT_TOAST_ID_PREFIX = 'ops-demand-transition-conflict:'
|
||||
|
||||
const transitionVariant = (target: CampaignDemandStatus) =>
|
||||
target === 'aprovada' ? 'default' : target === 'rejeitada' ? 'destructive' : 'secondary'
|
||||
|
||||
|
|
@ -41,16 +66,69 @@ export const DemandWorkflowCard = ({
|
|||
status,
|
||||
canDecideEscalated,
|
||||
currentCost,
|
||||
updatedAt,
|
||||
opsHybridEnabled = resolveOpsHybridEnabled(),
|
||||
transitionFormAction,
|
||||
costFormAction,
|
||||
receiptFormAction,
|
||||
}: DemandWorkflowCardProps) => {
|
||||
const router = useRouter()
|
||||
const [transitionState, submitTransition, transitionPending] = useActionState(
|
||||
transitionFormAction,
|
||||
{},
|
||||
)
|
||||
const [costState, submitCost, costPending] = useActionState(costFormAction, {})
|
||||
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(
|
||||
(target) =>
|
||||
|
|
@ -59,15 +137,71 @@ export const DemandWorkflowCard = ({
|
|||
(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 (
|
||||
<section
|
||||
aria-labelledby="demand-workflow-title"
|
||||
className="flex flex-col gap-6 rounded-xl border p-4"
|
||||
>
|
||||
<div className="flex flex-col gap-1">
|
||||
<h2 id="demand-workflow-title" className="text-base font-medium">
|
||||
Tratar demanda
|
||||
</h2>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h2 id="demand-workflow-title" className="text-base font-medium">
|
||||
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">
|
||||
O assessor analisa e decide — ou escala ao Coordenador Geral. Demandas escaladas são
|
||||
decididas somente por ele.
|
||||
|
|
@ -75,7 +209,11 @@ export const DemandWorkflowCard = ({
|
|||
</div>
|
||||
|
||||
{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} />
|
||||
<Field>
|
||||
<FieldLabel htmlFor={`demand-note-${demandID}`}>Nota da decisão</FieldLabel>
|
||||
|
|
@ -95,24 +233,29 @@ export const DemandWorkflowCard = ({
|
|||
name="status"
|
||||
value={target}
|
||||
variant={transitionVariant(target)}
|
||||
disabled={transitionPending}
|
||||
disabled={transitionBusy}
|
||||
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]}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
{transitionState.message && transitionState.status !== 'success' ? (
|
||||
{!opsHybridEnabled && transitionState.message && transitionState.status !== 'success' ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{transitionState.message}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
{transitionState.status === 'success' ? (
|
||||
{!opsHybridEnabled && transitionState.status === 'success' ? (
|
||||
<Alert>
|
||||
<AlertDescription>{transitionState.message}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
{hybridMessage ? (
|
||||
<p className="text-sm text-muted-foreground" role="status">
|
||||
{hybridMessage}
|
||||
</p>
|
||||
) : null}
|
||||
</form>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">Esta demanda já foi decidida.</p>
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
'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 {
|
||||
RelationMultiSelect,
|
||||
type RelationOption,
|
||||
} from '@/components/campaign/shared/RelationMultiSelect'
|
||||
import { Badge } from '@/components/ui/Badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/Checkbox'
|
||||
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
|
||||
|
|
@ -14,7 +16,13 @@ import { Input } from '@/components/ui/input'
|
|||
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
||||
import { Spinner } from '@/components/ui/Spinner'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { leadershipSupportStatuses } from '@/lib/schemas/leadership'
|
||||
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||
import { readFormRelationshipIds, readOptionalFormText } from '@/lib/campaignOps/opsHybridFormData'
|
||||
import {
|
||||
isSupportStatus,
|
||||
leadershipSupportStatuses,
|
||||
type SupportStatus,
|
||||
} from '@/lib/schemas/leadership'
|
||||
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
||||
import { fieldError } from '@/utilities/campaignFormFields'
|
||||
import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
|
||||
|
|
@ -28,6 +36,7 @@ type LeadershipFormProps = {
|
|||
state: CampaignFormActionState,
|
||||
formData: FormData,
|
||||
) => Promise<CampaignFormActionState>
|
||||
opsHybridEnabled?: boolean
|
||||
}
|
||||
|
||||
export const LeadershipForm = ({
|
||||
|
|
@ -36,11 +45,74 @@ export const LeadershipForm = ({
|
|||
stateDeputyOptions,
|
||||
initialMunicipalityIDs,
|
||||
formAction,
|
||||
opsHybridEnabled = resolveOpsHybridEnabled(),
|
||||
}: LeadershipFormProps) => {
|
||||
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')
|
||||
|
||||
setHybridPending(true)
|
||||
setHybridMessage(null)
|
||||
void enqueueLeadershipCreate({
|
||||
clientId: crypto.randomUUID(),
|
||||
name: name.trim(),
|
||||
phone: phone.trim(),
|
||||
email: readOptionalFormText(data, 'email') ?? null,
|
||||
municipalities: readFormRelationshipIds(data, 'municipalities'),
|
||||
organizations: readFormRelationshipIds(data, 'organizations'),
|
||||
stateDeputies: readFormRelationshipIds(data, 'stateDeputies'),
|
||||
exclusive: exclusiveValues.length === 0 ? true : exclusiveValues.at(-1) === 'true',
|
||||
supportStatus,
|
||||
notes: readOptionalFormText(data, 'notes'),
|
||||
}).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 (
|
||||
<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>
|
||||
<FieldLabel htmlFor="leadership-name">Nome completo</FieldLabel>
|
||||
<Input
|
||||
|
|
@ -134,9 +206,16 @@ export const LeadershipForm = ({
|
|||
<Textarea id="leadership-notes" name="notes" rows={3} maxLength={3000} />
|
||||
</Field>
|
||||
|
||||
{state.status !== 'success' ? <CampaignFormActionMessage state={state} /> : null}
|
||||
<Button type="submit" disabled={isPending} className="min-h-11 self-start">
|
||||
{isPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
||||
{!opsHybridEnabled && state.status !== 'success' ? (
|
||||
<CampaignFormActionMessage state={state} />
|
||||
) : 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
|
||||
</Button>
|
||||
</form>
|
||||
|
|
|
|||
|
|
@ -1,24 +1,50 @@
|
|||
'use client'
|
||||
|
||||
import { useActionState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import {
|
||||
useActionState,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
type FormEvent,
|
||||
} from 'react'
|
||||
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 {
|
||||
RelationMultiSelect,
|
||||
type RelationOption,
|
||||
} from '@/components/campaign/shared/RelationMultiSelect'
|
||||
import { Badge } from '@/components/ui/Badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/Checkbox'
|
||||
import { Field, FieldLabel } from '@/components/ui/field'
|
||||
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
||||
import { Spinner } from '@/components/ui/Spinner'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { leadershipSupportStatuses } from '@/lib/schemas/leadership'
|
||||
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||
import { readFormRelationshipIds, readOptionalFormText } from '@/lib/campaignOps/opsHybridFormData'
|
||||
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 { fieldError } from '@/utilities/campaignFormFields'
|
||||
import type { LeadershipDetailViewModel } from '@/utilities/leadership/leadershipData'
|
||||
import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
|
||||
|
||||
const CONFLICT_TOAST_ID_PREFIX = 'ops-leadership-update-conflict:'
|
||||
|
||||
type LeadershipInternalFormProps = {
|
||||
leadership: LeadershipDetailViewModel
|
||||
municipalityOptions: RelationOption[]
|
||||
|
|
@ -28,6 +54,7 @@ type LeadershipInternalFormProps = {
|
|||
state: CampaignFormActionState,
|
||||
formData: FormData,
|
||||
) => Promise<CampaignFormActionState>
|
||||
opsHybridEnabled?: boolean
|
||||
}
|
||||
|
||||
/** Staff-only internal evaluation + links (municipalities, organizations). */
|
||||
|
|
@ -37,12 +64,116 @@ export const LeadershipInternalForm = ({
|
|||
organizationOptions,
|
||||
stateDeputyOptions,
|
||||
formAction,
|
||||
opsHybridEnabled = resolveOpsHybridEnabled(),
|
||||
}: LeadershipInternalFormProps) => {
|
||||
const router = useRouter()
|
||||
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: readFormRelationshipIds(data, 'municipalities'),
|
||||
organizations: readFormRelationshipIds(data, 'organizations'),
|
||||
stateDeputies: readFormRelationshipIds(data, 'stateDeputies'),
|
||||
exclusive: data.get('exclusive') === 'true',
|
||||
supportStatus,
|
||||
notes: readOptionalFormText(data, 'notes') ?? 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 (
|
||||
<form action={submitAction} className="flex max-w-2xl flex-col gap-4">
|
||||
<input type="hidden" name="leadershipId" value={leadership.id} />
|
||||
<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">
|
||||
<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
|
||||
name="municipalities"
|
||||
|
|
@ -111,9 +242,14 @@ export const LeadershipInternalForm = ({
|
|||
/>
|
||||
</Field>
|
||||
|
||||
<CampaignFormActionMessage state={state} />
|
||||
<Button type="submit" disabled={isPending} className="min-h-11 self-start">
|
||||
{isPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
||||
{!opsHybridEnabled ? <CampaignFormActionMessage state={state} /> : 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}
|
||||
Salvar
|
||||
</Button>
|
||||
</form>
|
||||
|
|
|
|||
|
|
@ -1,34 +1,106 @@
|
|||
'use client'
|
||||
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useEffect, useRef, useSyncExternalStore } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import type { LeadershipListSupportStatusResponse } from '@/app/(campaign)/campanha/(app)/liderancas/support-status/types'
|
||||
import { SupportStatusBadge } from '@/components/campaign/leadership/SupportStatusBadge'
|
||||
import {
|
||||
discardOpsLeadershipUpdateOutboxRow,
|
||||
enqueueLeadershipUpdate,
|
||||
readOpsLeadershipUpdateOutboxRow,
|
||||
subscribeOpsLeadershipUpdateOutboxRow,
|
||||
} from '@/components/campaign/opsSync/opsDomainOutbox'
|
||||
import { leadershipsCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||
import { CampaignCellEditOverlay } from '@/components/campaign/shared/CampaignCellEditOverlay'
|
||||
import { useCampaignCellAutosave } from '@/components/campaign/shared/useCampaignCellAutosave'
|
||||
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
||||
import { Field, FieldLabel } from '@/components/ui/field'
|
||||
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
||||
import { Spinner } from '@/components/ui/Spinner'
|
||||
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 { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
|
||||
|
||||
const STATUS_AUTOSAVE_MS = 150
|
||||
const SUPPORT_STATUS_ENDPOINT = '/campanha/liderancas/support-status'
|
||||
const SAVE_ERROR_MESSAGE = 'Não foi possível salvar o status. Tente novamente.'
|
||||
const DEFAULT_STATUS: SupportStatus = 'a_abordar'
|
||||
const CONFLICT_TOAST_ID_PREFIX = 'ops-leadership-status-conflict:'
|
||||
|
||||
type LeadershipListSupportStatusControlProps = {
|
||||
leadershipID: number
|
||||
status: SupportStatus | null
|
||||
/** OH13 — CAS base when OPS_HYBRID outbox path is on. */
|
||||
updatedAt?: string
|
||||
}
|
||||
|
||||
export const LeadershipListSupportStatusControl = ({
|
||||
leadershipID,
|
||||
status,
|
||||
updatedAt,
|
||||
}: LeadershipListSupportStatusControlProps) => {
|
||||
const router = useRouter()
|
||||
const opsHybrid = resolveOpsHybridEnabled()
|
||||
const previousOutboxStatusRef = useRef<string | undefined>(undefined)
|
||||
|
||||
const outboxRow = useSyncExternalStore(
|
||||
(onStoreChange) =>
|
||||
opsHybrid
|
||||
? subscribeOpsLeadershipUpdateOutboxRow(leadershipID, onStoreChange)
|
||||
: () => undefined,
|
||||
() => (opsHybrid ? readOpsLeadershipUpdateOutboxRow(leadershipID) : undefined),
|
||||
() => undefined,
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousOutboxStatusRef.current
|
||||
previousOutboxStatusRef.current = outboxRow?.status
|
||||
if (previous === 'pending' && outboxRow === undefined) {
|
||||
router.refresh()
|
||||
}
|
||||
}, [outboxRow, router])
|
||||
|
||||
useEffect(() => {
|
||||
if (!opsHybrid || outboxRow?.status !== 'conflict') return
|
||||
const toastId = `${CONFLICT_TOAST_ID_PREFIX}${leadershipID}`
|
||||
toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
|
||||
id: toastId,
|
||||
duration: Infinity,
|
||||
action: {
|
||||
label: 'Manter o meu',
|
||||
onClick: () => {
|
||||
void enqueueLeadershipUpdate({
|
||||
leadershipId: leadershipID,
|
||||
supportStatus: outboxRow.supportStatus,
|
||||
municipalities: outboxRow.municipalities,
|
||||
organizations: outboxRow.organizations,
|
||||
stateDeputies: outboxRow.stateDeputies,
|
||||
exclusive: outboxRow.exclusive,
|
||||
notes: outboxRow.notes,
|
||||
baseUpdatedAt: outboxRow.serverUpdatedAt ?? null,
|
||||
})
|
||||
},
|
||||
},
|
||||
cancel: {
|
||||
label: 'Usar o novo',
|
||||
onClick: () => {
|
||||
discardOpsLeadershipUpdateOutboxRow(leadershipID)
|
||||
router.refresh()
|
||||
},
|
||||
},
|
||||
})
|
||||
return () => {
|
||||
toast.dismiss(toastId)
|
||||
}
|
||||
}, [opsHybrid, outboxRow, leadershipID, router])
|
||||
|
||||
const { open, onOpenChange, value, change, isPending, errorMessage, statusMessage } =
|
||||
useCampaignCellAutosave<SupportStatus, LeadershipListSupportStatusResponse>({
|
||||
value: status ?? DEFAULT_STATUS,
|
||||
|
|
@ -38,6 +110,24 @@ export const LeadershipListSupportStatusControl = ({
|
|||
readSaved: (payload) => payload.savedSupportStatus,
|
||||
errorMessage: SAVE_ERROR_MESSAGE,
|
||||
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) => {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
'use client'
|
||||
|
||||
import { clearOpsDomainOutboxForLogout } from '@/components/campaign/opsSync/opsDomainOutbox'
|
||||
import { clearOpsEstimateOutboxForLogout } from '@/components/campaign/opsSync/opsEstimateOutbox'
|
||||
import {
|
||||
abortOpsMirrorSync,
|
||||
|
|
@ -14,6 +15,10 @@ import { clearOpsMunicipalityOutboxForLogout } from '@/components/campaign/opsSy
|
|||
*/
|
||||
export const clearCampaignOpsStorage = async (): Promise<void> => {
|
||||
abortOpsMirrorSync()
|
||||
await Promise.all([clearOpsEstimateOutboxForLogout(), clearOpsMunicipalityOutboxForLogout()])
|
||||
await Promise.all([
|
||||
clearOpsEstimateOutboxForLogout(),
|
||||
clearOpsMunicipalityOutboxForLogout(),
|
||||
clearOpsDomainOutboxForLogout(),
|
||||
])
|
||||
await clearOpsMirrorPersistenceForLogout()
|
||||
}
|
||||
|
|
|
|||
636
src/components/campaign/opsSync/opsDomainOutbox.ts
Normal file
636
src/components/campaign/opsSync/opsDomainOutbox.ts
Normal file
|
|
@ -0,0 +1,636 @@
|
|||
'use client'
|
||||
|
||||
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
|
||||
import {
|
||||
IndexedDBAdapter,
|
||||
NonRetriableError,
|
||||
startOfflineExecutor,
|
||||
type OfflineExecutor,
|
||||
} from '@tanstack/offline-transactions'
|
||||
|
||||
import { updateActivityCas } from '@/app/(campaign)/campanha/actions/activity'
|
||||
import { transitionCampaignDemandCas } from '@/app/(campaign)/campanha/actions/demand'
|
||||
import {
|
||||
createLeadershipCas,
|
||||
updateLeadershipInternalCas,
|
||||
} from '@/app/(campaign)/campanha/actions/leadership'
|
||||
import {
|
||||
collapseActivityUpdateOutbox,
|
||||
collapseDemandTransitionOutbox,
|
||||
collapseLeadershipCreateOutbox,
|
||||
collapseLeadershipUpdateOutbox,
|
||||
type OpsActivityUpdateOutboxRow,
|
||||
type OpsDemandTransitionOutboxRow,
|
||||
type OpsLeadershipCreateOutboxRow,
|
||||
type OpsLeadershipUpdateOutboxRow,
|
||||
} from '@/components/campaign/opsSync/opsDomainOutboxModel'
|
||||
import {
|
||||
activitiesCollection,
|
||||
demandsCollection,
|
||||
leadershipsCollection,
|
||||
} from '@/components/campaign/opsSync/opsMirrorCollections'
|
||||
import { opsOutboxKey, type OpsOutboxKey } from '@/lib/campaignOps/opsContract'
|
||||
import type { 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 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,
|
||||
}),
|
||||
)
|
||||
|
||||
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)!)
|
||||
: []),
|
||||
]
|
||||
|
||||
for (const [fn, list] of byFn) {
|
||||
if (
|
||||
fn !== LEADERSHIP_UPDATE_FN &&
|
||||
fn !== LEADERSHIP_CREATE_FN &&
|
||||
fn !== DEMAND_TRANSITION_FN &&
|
||||
fn !== ACTIVITY_UPDATE_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,
|
||||
},
|
||||
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)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
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 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))
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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()
|
||||
}
|
||||
94
src/components/campaign/opsSync/opsDomainOutboxModel.ts
Normal file
94
src/components/campaign/opsSync/opsDomainOutboxModel.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import type { OfflineTransaction } from '@tanstack/offline-transactions'
|
||||
|
||||
import type { ActivityUpdateInput } from '@/lib/schemas/activity'
|
||||
import type { CampaignDemandStatus } from '@/lib/schemas/campaignDemand'
|
||||
import type { SupportStatus } from '@/lib/schemas/leadership'
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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')
|
||||
|
|
@ -1,8 +1,16 @@
|
|||
'use client'
|
||||
|
||||
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
|
||||
|
||||
import { collectOpsDomainOutboxKeys } from '@/components/campaign/opsSync/opsDomainOutbox'
|
||||
import { collectOpsEstimateOutboxKeys } from '@/components/campaign/opsSync/opsEstimateOutbox'
|
||||
import {
|
||||
activitiesCollection,
|
||||
demandsCollection,
|
||||
leadershipsCollection,
|
||||
municipalitiesCollection,
|
||||
municipalityUpdatesCollection,
|
||||
organizationsCollection,
|
||||
stateDeputiesCollection,
|
||||
} from '@/components/campaign/opsSync/opsMirrorCollections'
|
||||
import {
|
||||
openOpsMirrorStore,
|
||||
type OpsMirrorPersistenceMode,
|
||||
|
|
@ -12,16 +20,9 @@ import { collectOpsMunicipalityOutboxKeys } from '@/components/campaign/opsSync/
|
|||
import { votePledgesCollection } from '@/components/campaign/opsSync/opsVotePledgeMirror'
|
||||
import {
|
||||
createEmptyOpsSnapshot,
|
||||
type OpsActivity,
|
||||
type OpsDemand,
|
||||
type OpsGoals,
|
||||
type OpsLeadership,
|
||||
type OpsMunicipality,
|
||||
type OpsMunicipalityUpdate,
|
||||
type OpsOrganization,
|
||||
type OpsOutboxKey,
|
||||
type OpsSnapshot,
|
||||
type OpsStateDeputy,
|
||||
} from '@/lib/campaignOps/opsContract'
|
||||
import { mergeOpsSnapshot } from '@/lib/campaignOps/opsMerge'
|
||||
import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion'
|
||||
|
|
@ -29,24 +30,15 @@ import type { OpsSyncState } from '@/lib/campaignOps/opsSyncMeta'
|
|||
|
||||
export const OPS_SYNC_PATH = '/campanha/api/ops-sync'
|
||||
|
||||
const createRowCollection = <T extends { id: number }>(id: string) =>
|
||||
createCollection(
|
||||
localOnlyCollectionOptions<T, number>({
|
||||
id,
|
||||
getKey: (row) => row.id,
|
||||
}),
|
||||
)
|
||||
|
||||
export const municipalitiesCollection = createRowCollection<OpsMunicipality>('ops-municipalities')
|
||||
export const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships')
|
||||
export { votePledgesCollection }
|
||||
const activitiesCollection = createRowCollection<OpsActivity>('ops-activities')
|
||||
export const stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies')
|
||||
export const organizationsCollection = createRowCollection<OpsOrganization>('ops-organizations')
|
||||
export const demandsCollection = createRowCollection<OpsDemand>('ops-demands')
|
||||
const municipalityUpdatesCollection = createRowCollection<OpsMunicipalityUpdate>(
|
||||
'ops-municipality-updates',
|
||||
)
|
||||
export {
|
||||
activitiesCollection,
|
||||
demandsCollection,
|
||||
leadershipsCollection,
|
||||
municipalitiesCollection,
|
||||
organizationsCollection,
|
||||
stateDeputiesCollection,
|
||||
votePledgesCollection,
|
||||
}
|
||||
|
||||
let goalsMirror: OpsGoals | null = null
|
||||
let revisedAtMirror: string = new Date(0).toISOString()
|
||||
|
|
@ -143,6 +135,7 @@ const resolveOutboxKeys = (explicit?: ReadonlySet<OpsOutboxKey>): ReadonlySet<Op
|
|||
if (explicit) return explicit
|
||||
const keys = collectOpsEstimateOutboxKeys()
|
||||
for (const key of collectOpsMunicipalityOutboxKeys()) keys.add(key)
|
||||
for (const key of collectOpsDomainOutboxKeys()) keys.add(key)
|
||||
return keys
|
||||
}
|
||||
|
||||
|
|
|
|||
32
src/components/campaign/opsSync/opsMirrorCollections.ts
Normal file
32
src/components/campaign/opsSync/opsMirrorCollections.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
'use client'
|
||||
|
||||
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
|
||||
|
||||
import type {
|
||||
OpsActivity,
|
||||
OpsDemand,
|
||||
OpsLeadership,
|
||||
OpsMunicipality,
|
||||
OpsMunicipalityUpdate,
|
||||
OpsOrganization,
|
||||
OpsStateDeputy,
|
||||
} from '@/lib/campaignOps/opsContract'
|
||||
|
||||
const createRowCollection = <T extends { id: number }>(id: string) =>
|
||||
createCollection(
|
||||
localOnlyCollectionOptions<T, number>({
|
||||
id,
|
||||
getKey: (row) => row.id,
|
||||
}),
|
||||
)
|
||||
|
||||
/** Shared TanStack local collections — imported by outbox + mirror without a cycle. */
|
||||
export const municipalitiesCollection = createRowCollection<OpsMunicipality>('ops-municipalities')
|
||||
export const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships')
|
||||
export const activitiesCollection = createRowCollection<OpsActivity>('ops-activities')
|
||||
export const stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies')
|
||||
export const organizationsCollection = createRowCollection<OpsOrganization>('ops-organizations')
|
||||
export const demandsCollection = createRowCollection<OpsDemand>('ops-demands')
|
||||
export const municipalityUpdatesCollection = createRowCollection<OpsMunicipalityUpdate>(
|
||||
'ops-municipality-updates',
|
||||
)
|
||||
16
src/lib/campaignOps/opsHybridFormData.ts
Normal file
16
src/lib/campaignOps/opsHybridFormData.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
/** Client-safe FormData helpers for OPS_HYBRID enqueue paths (OH13). */
|
||||
|
||||
export const readFormRelationshipIds = (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 readOptionalFormText = (data: FormData, name: string): string | undefined => {
|
||||
const raw = data.get(name)
|
||||
return typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : undefined
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { z } from 'zod'
|
||||
|
||||
import { campaignDemandCreateSchema } from '@/lib/schemas/campaignDemandInput'
|
||||
import { optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
|
||||
import {
|
||||
positiveRelationshipId,
|
||||
trimmedNullableText,
|
||||
|
|
@ -178,6 +179,8 @@ export const activityUpdateSchema = activityFieldsSchema
|
|||
responsible: positiveRelationshipId.nullable().optional(),
|
||||
leadership: positiveRelationshipId.nullable().optional(),
|
||||
status: z.enum(activityStatuses).optional(),
|
||||
/** OH13 — CAS token; absent → last-write-wins. */
|
||||
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||
})
|
||||
.superRefine((data, context) => {
|
||||
validateSchedule(data, context, 'patch')
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||
|
||||
export const campaignDemandKinds = [
|
||||
'material',
|
||||
'servico',
|
||||
|
|
@ -82,6 +84,7 @@ export const CAMPAIGN_DEMAND_TRANSITION_SAFE_MESSAGES = [
|
|||
CAMPAIGN_DEMAND_TRANSITION_STAFF_MESSAGE,
|
||||
CAMPAIGN_DEMAND_ESCALATED_DECISION_MESSAGE,
|
||||
CAMPAIGN_DEMAND_INVALID_STATUS_MESSAGE,
|
||||
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||
] as const
|
||||
|
||||
export const CAMPAIGN_DEMAND_RECEIPT_SAFE_MESSAGES = [
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { z } from 'zod'
|
||||
|
||||
import { campaignDemandKinds, campaignDemandStatuses } from '@/lib/schemas/campaignDemand'
|
||||
import { optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
|
||||
import {
|
||||
positiveRelationshipId,
|
||||
trimmedNullableText,
|
||||
|
|
@ -21,6 +22,8 @@ export const campaignDemandTransitionSchema = z.object({
|
|||
id: positiveRelationshipId,
|
||||
status: z.enum(campaignDemandStatuses),
|
||||
decisionNote: trimmedNullableText(2000),
|
||||
/** OH13 — CAS token; absent → last-write-wins. */
|
||||
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||
})
|
||||
|
||||
export const campaignDemandCostSchema = z.object({
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { z } from 'zod'
|
||||
|
||||
import { optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
|
||||
import {
|
||||
brazilianMobile,
|
||||
optionalPersistedEmail,
|
||||
|
|
@ -85,6 +86,8 @@ export const leadershipInternalUpdateSchema = z.object({
|
|||
exclusive: z.boolean().optional(),
|
||||
supportStatus: z.enum(leadershipSupportStatuses).optional(),
|
||||
notes: trimmedNullableText(3000),
|
||||
/** OH13 — CAS token; absent → last-write-wins. */
|
||||
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||
})
|
||||
|
||||
export type LeadershipInternalUpdateInput = z.input<typeof leadershipInternalUpdateSchema>
|
||||
|
|
@ -114,6 +117,7 @@ export const leadershipStateDeputyMembershipSchema = z.object({
|
|||
leadershipId: positiveRelationshipId,
|
||||
stateDeputyId: positiveRelationshipId,
|
||||
assigned: z.boolean(),
|
||||
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||
})
|
||||
|
||||
export type LeadershipStateDeputyMembershipInput = z.input<
|
||||
|
|
@ -134,6 +138,7 @@ export const leadershipMunicipalitiesMembershipSchema = z.object({
|
|||
.max(MAX_LEADERSHIP_MUNICIPALITIES)
|
||||
.transform((ids) => [...new Set(ids)]),
|
||||
assigned: z.boolean(),
|
||||
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||
})
|
||||
|
||||
export type LeadershipMunicipalitiesMembershipInput = z.input<
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import {
|
|||
MAX_MUNICIPALITIES_PER_BATCH,
|
||||
MUNICIPALITY_STATE_DEPUTIES_CAP_MESSAGE,
|
||||
} from '@/lib/schemas/municipality'
|
||||
import { OPS_UPDATED_AT_CONFLICT_MESSAGE, optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
|
||||
import {
|
||||
positiveRelationshipId,
|
||||
trimmedNullableText,
|
||||
|
|
@ -50,11 +51,17 @@ export const stateDeputyMunicipalitiesBatchSchema = z.object({
|
|||
.max(MAX_MUNICIPALITIES_PER_BATCH)
|
||||
.transform((ids) => [...new Set(ids)]),
|
||||
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 = [
|
||||
STATE_DEPUTY_STAFF_MESSAGE,
|
||||
MUNICIPALITY_STATE_DEPUTIES_CAP_MESSAGE,
|
||||
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||
] as const
|
||||
|
||||
export type StateDeputyCreateInput = z.input<typeof stateDeputyCreateSchema>
|
||||
|
|
|
|||
|
|
@ -143,6 +143,8 @@ export type ActivityFormViewModel = {
|
|||
responsible: { id: number; name: string; phone: string | null } | null
|
||||
leadership: { id: number; label: string } | null
|
||||
tasks: ActivityFormTaskViewModel[]
|
||||
/** OH13 — CAS token for staff updates when OPS_HYBRID is on. */
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
const relationshipIds = (value: unknown): number[] =>
|
||||
|
|
@ -196,6 +198,7 @@ export const toActivityFormViewModel = (activity: Activity): ActivityFormViewMod
|
|||
due: task.due ?? null,
|
||||
done: Boolean(task.done),
|
||||
})),
|
||||
updatedAt: activity.updatedAt,
|
||||
})
|
||||
|
||||
const activityDetailContextSelect = {
|
||||
|
|
|
|||
|
|
@ -153,6 +153,8 @@ export type DemandDetailViewModel = DemandRowViewModel & {
|
|||
}>
|
||||
canLeaderEdit: boolean
|
||||
activity: { title: string; slug: string } | null
|
||||
/** OH13 — CAS token for staff transitions when OPS_HYBRID is on. */
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export const loadDemandDetail = async (
|
||||
|
|
@ -217,5 +219,6 @@ export const loadDemandDetail = async (
|
|||
activity: isPopulatedRelationship<Activity>(demand.activity)
|
||||
? { title: demand.activity.title, slug: demand.activity.slug }
|
||||
: null,
|
||||
updatedAt: demand.updatedAt,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
301
tests/int/domainWritesCas.int.spec.ts
Normal file
301
tests/int/domainWritesCas.int.spec.ts
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import type { Payload } from 'payload'
|
||||
import { getPayload } from 'payload'
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
createActivityRecord,
|
||||
updateActivityCasRecord,
|
||||
} from '@/app/(campaign)/campanha/actions/activity'
|
||||
import {
|
||||
createCampaignDemandRecord,
|
||||
transitionCampaignDemandCasRecord,
|
||||
transitionCampaignDemandRecord,
|
||||
} from '@/app/(campaign)/campanha/actions/demand'
|
||||
import {
|
||||
updateLeadershipInternalCasRecord,
|
||||
updateLeadershipInternalRecord,
|
||||
} from '@/app/(campaign)/campanha/actions/leadership'
|
||||
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
|
||||
})
|
||||
})
|
||||
})
|
||||
30
tests/unit/opsDomainOutbox.unit.spec.ts
Normal file
30
tests/unit/opsDomainOutbox.unit.spec.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { collapseLeadershipUpdateOutbox } 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'])
|
||||
})
|
||||
})
|
||||
Loading…
Reference in a new issue