From 7515d2a959885677533e58b0a81cb9f72ad028e2 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 1 Aug 2026 22:07:54 +0000 Subject: [PATCH] =?UTF-8?q?OH2=20=E2=80=94=20lib/campaignOps=20contrato=20?= =?UTF-8?q?puro=20+=20merge=20+=20flag?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DTOs client-safe em src/lib/campaignOps/opsContract.ts - mergeOpsSnapshot/diffOpsIds com proteção de outbox - resolveOpsHybridEnabled + OPS_MIRROR_SCHEMA_VERSION - Pins unit em tests/unit/campaignOps.unit.spec.ts Closes #163 Co-authored-by: Francisco Solla --- src/lib/campaignOps/opsContract.ts | 214 ++++++++++++++++++++++ src/lib/campaignOps/opsHybridFlag.ts | 7 + src/lib/campaignOps/opsMerge.ts | 108 +++++++++++ src/lib/campaignOps/opsMirrorVersion.ts | 2 + src/lib/campaignOps/opsSyncMeta.ts | 7 + tests/unit/campaignOps.unit.spec.ts | 228 ++++++++++++++++++++++++ 6 files changed, 566 insertions(+) create mode 100644 src/lib/campaignOps/opsContract.ts create mode 100644 src/lib/campaignOps/opsHybridFlag.ts create mode 100644 src/lib/campaignOps/opsMerge.ts create mode 100644 src/lib/campaignOps/opsMirrorVersion.ts create mode 100644 src/lib/campaignOps/opsSyncMeta.ts create mode 100644 tests/unit/campaignOps.unit.spec.ts diff --git a/src/lib/campaignOps/opsContract.ts b/src/lib/campaignOps/opsContract.ts new file mode 100644 index 00000000..8c00a6dd --- /dev/null +++ b/src/lib/campaignOps/opsContract.ts @@ -0,0 +1,214 @@ +import type { VoteEstimateScenarioFields } from '@/lib/voteEstimate' + +import { OPS_MIRROR_SCHEMA_VERSION } from './opsMirrorVersion' + +export type OpsVoteEstimateScenarioFields = VoteEstimateScenarioFields + +export type OpsMunicipality = { + id: number + name: string + slug: string + kind: 'municipio' | 'zona' + city: string + region: string + ibgeCode: string + zoneNumber?: number | null + advisors?: number[] | null + priority?: ('alta' | 'normal') | null + engagementLevel?: ('n0' | 'n1' | 'n2' | 'n3' | 'n4') | null + levelNote?: string | null + levelChangedAt?: string | null + expectedVotes?: OpsVoteEstimateScenarioFields | null + politicalTrend?: { + status?: ('favoravel' | 'neutra' | 'desfavoravel') | null + note?: string | null + recordedBy?: number | null + recordedAt?: string | null + } | null + stateDeputies?: number[] | null + lastUpdateAt?: string | null + updatedAt: string +} + +export type OpsLeadershipContact = { + id: number + name: string + phone?: string | null +} + +export type OpsLeadership = { + id: number + contact: OpsLeadershipContact + municipalities: number[] + organizations?: number[] | null + stateDeputies?: number[] | null + exclusive?: boolean | null + supportStatus: 'engajado' | 'a_abordar' | 'em_disputa' | 'negativo' + notes?: string | null + updatedAt: string +} + +/** Leader-facing pledge fields — never includes staff-only estimates. */ +export type OpsVotePledgeLeaderView = { + id: number + leadership: number + municipality: number + declaredVotes: number + declaredAt?: string | null + declaredBy?: number | null + updatedAt: string +} + +export type OpsVotePledge = OpsVotePledgeLeaderView & { + estimatedVotes?: OpsVoteEstimateScenarioFields | null + estimateNote?: string | null + estimatedBy?: number | null + estimatedAt?: string | null +} + +export type OpsActivity = { + id: number + title: string + slug: string + kind: + | 'caminhada' + | 'comicio' + | 'carreata' + | 'panfletagem' + | 'porta_a_porta' + | 'reuniao_apoio' + | 'lancamento' + | 'convencao' + | 'ato' + | 'entrevista' + | 'producao_conteudo' + | 'digital' + | 'outro' + status: 'rascunho' | 'planejado' | 'confirmado' | 'realizado' | 'cancelado' + deputyPresent?: boolean | null + startAt?: string | null + endAt?: string | null + municipality: number + locality?: string | null + organizations?: number[] | null + advisors?: number[] | null + leadership?: number | null + taskTotal?: number | null + taskDoneCount?: number | null + updatedAt: string +} + +export type OpsStateDeputy = { + id: number + name: string + slug: string + party?: string | null + notes?: string | null + updatedAt: string +} + +export type OpsOrganization = { + id: number + name: string + slug: string + kind: + | 'sindicato' + | 'associacao' + | 'religioso' + | 'movimento' + | 'categoria_profissional' + | 'outro' + municipalities?: number[] | null + notes?: string | null + updatedAt: string +} + +export type OpsDemand = { + id: number + title: string + slug: string + kind: + | 'material' + | 'servico' + | 'transporte' + | 'alimentacao' + | 'infraestrutura' + | 'espaco' + | 'equipamento' + | 'pessoal_apoio' + | 'outro' + municipality: number + activity?: number | null + leadership?: number | null + status: 'aberta' | 'em_analise' | 'escalada' | 'aprovada' | 'rejeitada' + updatedAt: string +} + +export type OpsMunicipalityUpdate = { + id: number + municipality: number + author: number + kind: 'semanal' | 'urgente' | 'nota' | 'sinal' + body?: string | null + signalType?: ('invasao' | 'esfriamento' | 'visita_adversario' | 'proposta_broker' | 'outro') | null + updatedAt: string + createdAt: string +} + +export type OpsGoals = { + stateGoal: number + margin?: number | null + baseYear?: number | null + note?: string | null + updatedAt?: string | null +} + +export type OpsSnapshot = { + revisedAt: string + schemaVersion: number + municipalities: OpsMunicipality[] + leaderships: OpsLeadership[] + votePledges: OpsVotePledge[] + activities: OpsActivity[] + stateDeputies: OpsStateDeputy[] + organizations: OpsOrganization[] + demands: OpsDemand[] + municipalityUpdates: OpsMunicipalityUpdate[] + goals: OpsGoals | null +} + +export const OPS_COLLECTION_KEYS = [ + 'municipalities', + 'leaderships', + 'votePledges', + 'activities', + 'stateDeputies', + 'organizations', + 'demands', + 'municipalityUpdates', +] as const + +export type OpsCollectionKey = (typeof OPS_COLLECTION_KEYS)[number] + +export type OpsOutboxKey = `${OpsCollectionKey}:${number}` + +export const opsOutboxKey = (collection: OpsCollectionKey, id: number): OpsOutboxKey => + `${collection}:${id}` + +export const createEmptyOpsSnapshot = (revisedAt: string): OpsSnapshot => ({ + revisedAt, + schemaVersion: OPS_MIRROR_SCHEMA_VERSION, + municipalities: [], + leaderships: [], + votePledges: [], + activities: [], + stateDeputies: [], + organizations: [], + demands: [], + municipalityUpdates: [], + goals: null, +}) + +export const serializeOpsSnapshot = (snapshot: OpsSnapshot): string => JSON.stringify(snapshot) + +export const parseOpsSnapshot = (raw: string): OpsSnapshot => JSON.parse(raw) as OpsSnapshot diff --git a/src/lib/campaignOps/opsHybridFlag.ts b/src/lib/campaignOps/opsHybridFlag.ts new file mode 100644 index 00000000..a35e61d0 --- /dev/null +++ b/src/lib/campaignOps/opsHybridFlag.ts @@ -0,0 +1,7 @@ +type OpsHybridEnv = Record + +/** Compile-time env gate for the ops hybrid mirror (OH1). Truthy only for `'1'` or `'true'`. */ +export const resolveOpsHybridEnabled = (env: OpsHybridEnv = process.env): boolean => { + const value = env.OPS_HYBRID + return value === '1' || value === 'true' +} diff --git a/src/lib/campaignOps/opsMerge.ts b/src/lib/campaignOps/opsMerge.ts new file mode 100644 index 00000000..4c9d4d41 --- /dev/null +++ b/src/lib/campaignOps/opsMerge.ts @@ -0,0 +1,108 @@ +import { + OPS_COLLECTION_KEYS, + type OpsCollectionKey, + type OpsOutboxKey, + type OpsSnapshot, + opsOutboxKey, +} from './opsContract' + +type OpsRow = { id: number } + +export type OpsCollectionIdDiff = { + added: number[] + removed: number[] +} + +export type OpsIdDiff = Record + +const mergeRowCollection = ( + localRows: TRow[], + incomingRows: TRow[], + collection: OpsCollectionKey, + outboxKeys: ReadonlySet, +): TRow[] => { + const localById = new Map(localRows.map((row) => [row.id, row])) + const merged: TRow[] = [] + + for (const incomingRow of incomingRows) { + const key = opsOutboxKey(collection, incomingRow.id) + if (outboxKeys.has(key)) { + const localRow = localById.get(incomingRow.id) + if (localRow) merged.push(localRow) + continue + } + merged.push(incomingRow) + } + + for (const localRow of localRows) { + const key = opsOutboxKey(collection, localRow.id) + if (!outboxKeys.has(key)) continue + if (incomingRows.some((row) => row.id === localRow.id)) continue + merged.push(localRow) + } + + return merged +} + +const diffRowCollection = ( + localRows: readonly OpsRow[], + incomingRows: readonly OpsRow[], +): OpsCollectionIdDiff => { + const localIds = new Set(localRows.map((row) => row.id)) + const incomingIds = new Set(incomingRows.map((row) => row.id)) + + const added: number[] = [] + const removed: number[] = [] + + for (const id of incomingIds) { + if (!localIds.has(id)) added.push(id) + } + + for (const id of localIds) { + if (!incomingIds.has(id)) removed.push(id) + } + + added.sort((a, b) => a - b) + removed.sort((a, b) => a - b) + + return { added, removed } +} + +/** + * Full-replace merge scoped by outbox keys: rows with pending/conflict writes + * keep the local copy; everything else is replaced by `incoming`; rows absent + * from `incoming` are dropped unless outboxed. + */ +export const mergeOpsSnapshot = ( + local: OpsSnapshot, + incoming: OpsSnapshot, + outboxKeys: ReadonlySet, +): OpsSnapshot => ({ + revisedAt: incoming.revisedAt, + schemaVersion: incoming.schemaVersion, + municipalities: mergeRowCollection(local.municipalities, incoming.municipalities, 'municipalities', outboxKeys), + leaderships: mergeRowCollection(local.leaderships, incoming.leaderships, 'leaderships', outboxKeys), + votePledges: mergeRowCollection(local.votePledges, incoming.votePledges, 'votePledges', outboxKeys), + activities: mergeRowCollection(local.activities, incoming.activities, 'activities', outboxKeys), + stateDeputies: mergeRowCollection(local.stateDeputies, incoming.stateDeputies, 'stateDeputies', outboxKeys), + organizations: mergeRowCollection(local.organizations, incoming.organizations, 'organizations', outboxKeys), + demands: mergeRowCollection(local.demands, incoming.demands, 'demands', outboxKeys), + municipalityUpdates: mergeRowCollection( + local.municipalityUpdates, + incoming.municipalityUpdates, + 'municipalityUpdates', + outboxKeys, + ), + goals: incoming.goals, +}) + +/** Per-collection id adds/removals between two snapshots (ignores outbox). */ +export const diffOpsIds = (local: OpsSnapshot, incoming: OpsSnapshot): OpsIdDiff => { + const diff: Partial = {} + + for (const collection of OPS_COLLECTION_KEYS) { + diff[collection] = diffRowCollection(local[collection], incoming[collection]) + } + + return diff as OpsIdDiff +} diff --git a/src/lib/campaignOps/opsMirrorVersion.ts b/src/lib/campaignOps/opsMirrorVersion.ts new file mode 100644 index 00000000..16e3be77 --- /dev/null +++ b/src/lib/campaignOps/opsMirrorVersion.ts @@ -0,0 +1,2 @@ +/** Bumped when the mirror DTO shape changes — clients wipe and full re-sync. */ +export const OPS_MIRROR_SCHEMA_VERSION = 1 diff --git a/src/lib/campaignOps/opsSyncMeta.ts b/src/lib/campaignOps/opsSyncMeta.ts new file mode 100644 index 00000000..e9a0c050 --- /dev/null +++ b/src/lib/campaignOps/opsSyncMeta.ts @@ -0,0 +1,7 @@ +export type OpsSyncStatus = 'idle' | 'syncing' | 'error' + +export type OpsSyncState = { + status: OpsSyncStatus + lastSyncedAt: string | null + lastError?: string +} diff --git a/tests/unit/campaignOps.unit.spec.ts b/tests/unit/campaignOps.unit.spec.ts new file mode 100644 index 00000000..5e427bfe --- /dev/null +++ b/tests/unit/campaignOps.unit.spec.ts @@ -0,0 +1,228 @@ +import { describe, expect, it } from 'vitest' + +import { + createEmptyOpsSnapshot, + opsOutboxKey, + parseOpsSnapshot, + serializeOpsSnapshot, + type OpsMunicipality, + type OpsSnapshot, + type OpsVotePledge, + type OpsVotePledgeLeaderView, +} from '@/lib/campaignOps/opsContract' +import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag' +import { diffOpsIds, mergeOpsSnapshot } from '@/lib/campaignOps/opsMerge' +import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion' + +const municipality = (partial: Partial & Pick): OpsMunicipality => ({ + name: partial.slug, + kind: 'municipio', + city: partial.slug, + region: 'Região', + ibgeCode: '0000000', + updatedAt: '2026-08-01T12:00:00.000Z', + ...partial, +}) + +const pledge = (partial: Partial & Pick): OpsVotePledge => ({ + leadership: 1, + municipality: 1, + declaredVotes: 100, + updatedAt: '2026-08-01T12:00:00.000Z', + ...partial, +}) + +const snapshot = (partial: Partial = {}): OpsSnapshot => ({ + ...createEmptyOpsSnapshot('2026-08-01T12:00:00.000Z'), + ...partial, +}) + +describe('OPS_MIRROR_SCHEMA_VERSION', () => { + it('is pinned at 1', () => { + expect(OPS_MIRROR_SCHEMA_VERSION).toBe(1) + }) +}) + +describe('resolveOpsHybridEnabled', () => { + it.each([ + ['1', true], + ['true', true], + ['0', false], + ['false', false], + ['', false], + [undefined, false], + ['yes', false], + ] as const)('parses OPS_HYBRID=%j as %s', (value, expected) => { + expect(resolveOpsHybridEnabled({ OPS_HYBRID: value })).toBe(expected) + }) +}) + +describe('OpsVotePledgeLeaderView', () => { + it('excludes staff-only estimate fields at the type level', () => { + const leaderView: OpsVotePledgeLeaderView = { + id: 1, + leadership: 2, + municipality: 3, + declaredVotes: 50, + declaredAt: '2026-08-01T10:00:00.000Z', + declaredBy: 4, + updatedAt: '2026-08-01T12:00:00.000Z', + } + + expect(leaderView).not.toHaveProperty('estimatedVotes') + expect(leaderView).not.toHaveProperty('estimateNote') + expect(leaderView).not.toHaveProperty('estimatedBy') + expect(leaderView).not.toHaveProperty('estimatedAt') + }) +}) + +describe('serializeOpsSnapshot / parseOpsSnapshot', () => { + it('round-trips ISO date strings unchanged', () => { + const original = snapshot({ + revisedAt: '2026-08-01T15:30:45.123Z', + municipalities: [ + municipality({ + id: 1, + slug: 'itabuna', + lastUpdateAt: '2026-07-30T08:00:00.000Z', + updatedAt: '2026-08-01T09:00:00.000Z', + }), + ], + votePledges: [ + pledge({ + id: 10, + declaredAt: '2026-08-01T10:00:00.000Z', + estimatedAt: '2026-08-01T11:00:00.000Z', + }), + ], + }) + + const parsed = parseOpsSnapshot(serializeOpsSnapshot(original)) + + expect(parsed.revisedAt).toBe('2026-08-01T15:30:45.123Z') + expect(parsed.municipalities[0]?.lastUpdateAt).toBe('2026-07-30T08:00:00.000Z') + expect(parsed.votePledges[0]?.estimatedAt).toBe('2026-08-01T11:00:00.000Z') + }) +}) + +describe('mergeOpsSnapshot', () => { + it('keeps the local row when the id is pending in the outbox', () => { + const local = snapshot({ + votePledges: [ + pledge({ + id: 1, + declaredVotes: 200, + estimatedVotes: { central: 250, pessimistic: null, optimistic: null }, + estimatedAt: '2026-08-01T10:00:00.000Z', + }), + ], + }) + const incoming = snapshot({ + revisedAt: '2026-08-01T13:00:00.000Z', + votePledges: [ + pledge({ + id: 1, + declaredVotes: 100, + estimatedVotes: { central: 120, pessimistic: null, optimistic: null }, + estimatedAt: '2026-08-01T12:00:00.000Z', + }), + ], + }) + + const merged = mergeOpsSnapshot(local, incoming, new Set([opsOutboxKey('votePledges', 1)])) + + expect(merged.votePledges).toEqual(local.votePledges) + expect(merged.revisedAt).toBe(incoming.revisedAt) + }) + + it('keeps the local row when the id is in conflict in the outbox', () => { + const local = snapshot({ + municipalities: [ + municipality({ + id: 5, + slug: 'cairu', + name: 'Local name', + updatedAt: '2026-08-01T10:00:00.000Z', + }), + ], + }) + const incoming = snapshot({ + municipalities: [ + municipality({ + id: 5, + slug: 'cairu', + name: 'Server name', + updatedAt: '2026-08-01T12:00:00.000Z', + }), + ], + }) + + const merged = mergeOpsSnapshot(local, incoming, new Set([opsOutboxKey('municipalities', 5)])) + + expect(merged.municipalities[0]?.name).toBe('Local name') + }) + + it('replaces rows outside the outbox and removes rows absent from incoming', () => { + const local = snapshot({ + municipalities: [ + municipality({ id: 1, slug: 'itabuna', name: 'Old Itabuna' }), + municipality({ id: 2, slug: 'cairu', name: 'Cairu' }), + ], + votePledges: [pledge({ id: 10, declaredVotes: 50 })], + }) + const incoming = snapshot({ + municipalities: [ + municipality({ id: 1, slug: 'itabuna', name: 'New Itabuna' }), + municipality({ id: 3, slug: 'valenca', name: 'Valença' }), + ], + votePledges: [pledge({ id: 11, declaredVotes: 80 })], + }) + + const merged = mergeOpsSnapshot(local, incoming, new Set()) + + expect(merged.municipalities.map((row) => row.id)).toEqual([1, 3]) + expect(merged.municipalities[0]?.name).toBe('New Itabuna') + expect(merged.votePledges.map((row) => row.id)).toEqual([11]) + }) + + it('retains outboxed local rows missing from incoming', () => { + const local = snapshot({ + votePledges: [pledge({ id: 99, declaredVotes: 300 })], + }) + const incoming = snapshot({ votePledges: [] }) + + const merged = mergeOpsSnapshot(local, incoming, new Set([opsOutboxKey('votePledges', 99)])) + + expect(merged.votePledges).toEqual(local.votePledges) + }) +}) + +describe('diffOpsIds', () => { + it('reports added and removed ids per collection', () => { + const local = snapshot({ + municipalities: [ + municipality({ id: 1, slug: 'itabuna' }), + municipality({ id: 2, slug: 'cairu' }), + ], + votePledges: [pledge({ id: 10 })], + }) + const incoming = snapshot({ + municipalities: [ + municipality({ id: 1, slug: 'itabuna' }), + municipality({ id: 3, slug: 'valenca' }), + ], + votePledges: [], + }) + + expect(diffOpsIds(local, incoming)).toEqual({ + municipalities: { added: [3], removed: [2] }, + leaderships: { added: [], removed: [] }, + votePledges: { added: [], removed: [10] }, + activities: { added: [], removed: [] }, + stateDeputies: { added: [], removed: [] }, + organizations: { added: [], removed: [] }, + demands: { added: [], removed: [] }, + municipalityUpdates: { added: [], removed: [] }, + }) + }) +})