teqo-backup/src/utilities/googleCalendarSyncHooks.ts
Francisco Solla 2f247d40a6 fix(C115): revisão /simplify — relógio com baseline de espelho, reopen sem re-cancelamento, hardening do webhook
- lastMirroredChangeAt (activity, migration): clock rule compara contra a
  última mudança espelhada, não updatedAt (task toggle não silencia edição
  pendente do Google)
- snapshot exclui ids que o motor deletou (removedEventIds separado do
  remoteEventIds): reopen pós-cancelamento não vira re-cancelamento fantasma
- cancelamento do Google respeita o relógio: cancel mais novo cancela; Teqo
  mais novo (reopen) limpa o trashed e recria
- escrita reversa sem req.user: autoria do registro correta + sem gate 403
  do deputado; hook de sync pula a própria escrita reversa (sem passada aninhada)
- canal: segredo rotaciona por criação; novo canal persistido antes do stop
  do antigo; identity fields read:false; create admin-only; leitura prefere
  linha configurada; pre-filter do webhook antes do bootstrap do Payload
- testes: all-day ida-e-volta, task-toggle, reopen, slug congelado, e2e dos
  caminhos 200, render tests do dialog/feed; asserções herméticas a
  atividades ambiente dos arquivos irmãos (DB compartilhado)
2026-08-11 22:42:05 -03:00

71 lines
2.3 KiB
TypeScript

import 'server-only'
import type { Activity, GoogleCalendarSync as GoogleCalendarSyncDoc } from '@/payload-types'
import type { PayloadRequest } from 'payload'
import {
runCampaignCalendarSync,
shouldSyncActivityOperation,
shouldSyncConfigChange,
} from '@/utilities/googleCalendarSync'
/**
* C114 — the two Payload hooks that trigger the Google mirror (in a module of
* their own so tests can mock the engine at the import boundary).
*
* Activity hook (afterChange + afterDelete): delegates the decision to the
* pure guard — task toggles, updates and result records never trigger a pass.
* afterDelete hooks carry no `operation`; its absence means delete.
* Config hook (afterChange on `googleCalendarSync`): D7 auto-resync — a
* changed `calendarId` or a re-enable runs the full reconciliation against
* the new calendar; state-only writes never re-trigger (no loop).
*
* Both NEVER throw: the Teqo write paths are independent of Google
* (fail-closed at the trigger; engine failures land in the `paused` state).
*/
export const activityGoogleCalendarSyncHook = async ({
doc,
previousDoc,
operation,
req,
}: {
doc: Activity
previousDoc?: Activity
operation?: 'create' | 'update'
req: PayloadRequest
}): Promise<unknown> => {
try {
// C115 — the reverse direction's own write must not re-enter the engine:
// the pass that applied the Google edit is still running; a nested pass
// would only re-list and converge (content equality) at double cost.
if (req.context?.mutationKind === 'googleCalendarSync') return doc
const resolvedOperation = operation ?? 'delete'
if (shouldSyncActivityOperation({ operation: resolvedOperation, doc, previousDoc })) {
await runCampaignCalendarSync(req.payload, { reason: resolvedOperation, req })
}
} catch {
// recorded as paused inside the engine; the write path stays intact
}
return doc
}
export const googleCalendarSyncConfigHook = async ({
doc,
previousDoc,
operation,
req,
}: {
doc: GoogleCalendarSyncDoc
previousDoc?: GoogleCalendarSyncDoc
operation: 'create' | 'update'
req: PayloadRequest
}): Promise<unknown> => {
try {
if (shouldSyncConfigChange({ operation, doc, previousDoc })) {
await runCampaignCalendarSync(req.payload, { reason: 'config-change', req })
}
} catch {
// never throw into admin writes
}
return doc
}