-- 主系统**事件补账消费**的游标与去重(2026-10-24 主系统定稿: -- `GET /api/supplier/events?since=&cursor=&limit=500`,按 (created_at,id) 升序,响应带 server_time/next_cursor/has_more)。 -- -- 为什么需要两张表: -- ① `main_system_event_cursors`:每分公司持久化 `next_cursor` + `last_event_at`(首次接入用 server_time 作起点); -- ② `main_system_events_seen`:事件 id 去重 —— 游标翻页可能重复投递同一条(含 failed 重试), -- 靠唯一键保证"同一条事件只处理一次"。 CREATE TABLE IF NOT EXISTS public.main_system_event_cursors ( branch_code VARCHAR(20) PRIMARY KEY, /** 主系统返回的不透明游标(下轮原样带回) */ cursor TEXT, /** 最近一次消费到的事件时间(诊断/回看窗口用;首次接入写 server_time) */ last_event_at TIMESTAMPTZ, /** 最近一次对账的 server_time(时钟基准,便于排查时间漂移) */ server_time TIMESTAMPTZ, /** 回看窗口被主系统截断过(clamped=true)⇒ 需要全量兜底补齐 */ needs_full_reconcile BOOLEAN NOT NULL DEFAULT FALSE, updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS public.main_system_events_seen ( branch_code VARCHAR(20) NOT NULL, event_id VARCHAR(64) NOT NULL, event VARCHAR(80), order_code VARCHAR(64), created_at TIMESTAMPTZ, /** 我方处理结果:applied / triggered_reconcile / binding_sync / ignored */ action VARCHAR(40), processed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY (branch_code, event_id) ); CREATE INDEX IF NOT EXISTS idx_events_seen_processed ON public.main_system_events_seen (branch_code, processed_at DESC); -- 与核心表同口径:两张表都是"按分公司隔离"的运营数据 DO $$ BEGIN IF to_regclass('public.main_system_event_cursors') IS NOT NULL THEN EXECUTE 'ALTER TABLE public.main_system_event_cursors ENABLE ROW LEVEL SECURITY'; EXECUTE 'ALTER TABLE public.main_system_event_cursors FORCE ROW LEVEL SECURITY'; EXECUTE 'DROP POLICY IF EXISTS main_system_event_cursors_branch ON public.main_system_event_cursors'; EXECUTE $p$CREATE POLICY main_system_event_cursors_branch ON public.main_system_event_cursors USING (COALESCE(current_setting('app.branch_code', true), '') = '' OR branch_code = current_setting('app.branch_code', true)) WITH CHECK (COALESCE(current_setting('app.branch_code', true), '') = '' OR branch_code = current_setting('app.branch_code', true))$p$; END IF; IF to_regclass('public.main_system_events_seen') IS NOT NULL THEN EXECUTE 'ALTER TABLE public.main_system_events_seen ENABLE ROW LEVEL SECURITY'; EXECUTE 'ALTER TABLE public.main_system_events_seen FORCE ROW LEVEL SECURITY'; EXECUTE 'DROP POLICY IF EXISTS main_system_events_seen_branch ON public.main_system_events_seen'; EXECUTE $p$CREATE POLICY main_system_events_seen_branch ON public.main_system_events_seen USING (COALESCE(current_setting('app.branch_code', true), '') = '' OR branch_code = current_setting('app.branch_code', true)) WITH CHECK (COALESCE(current_setting('app.branch_code', true), '') = '' OR branch_code = current_setting('app.branch_code', true))$p$; END IF; END $$;