From aafac6e5365e4487ea6b6a019073a5f81512009e Mon Sep 17 00:00:00 2001 From: yml Date: Tue, 24 Nov 2026 23:11:13 +0800 Subject: [PATCH] =?UTF-8?q?feat(fulfillment):=20=E5=A2=9E=E5=8A=A0=20Clean?= =?UTF-8?q?=20Cutover=EF=BC=8C=E5=8E=86=E5=8F=B2=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=E9=9A=94=E7=A6=BB=E5=88=B0=E4=BA=BA=E5=B7=A5=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 flow_version,存量任务回填 1,Cutover 后新任务写 2 - 迁移设置 clean_flow_started_at,按订单支付/创建时间判定 - 自动选号只处理 clean 任务 - 工作台新增历史任务 Tab,历史列表不受订单起算时间限制 - 历史任务不参与自动重试和预售台账同步 - 补充流程边界测试和计划文档 --- docs/斗鱼/斗鱼业务彻底优化与重构计划.md | 25 +++++ tests/test_migrations.py | 3 +- tests/test_platform_fulfillment.py | 38 ++++++++ ...est_platform_fulfillment_auto_allocator.py | 41 +++++++++ .../migrations/migration_manifest.json | 4 + .../20261124_0132_fulfillment_flow_version.py | 91 +++++++++++++++++++ web/backend/models.py | 13 +++ web/backend/routers/platform_fulfillment.py | 2 + .../platform_fulfillment/auto_allocator.py | 3 + .../services/platform_fulfillment/common.py | 29 ++++++ .../platform_fulfillment/order_sync.py | 11 +++ .../services/platform_fulfillment/views.py | 11 ++- web/frontend/src/api/platformFulfillment.ts | 1 + web/frontend/src/api/types.ts | 1 + .../src/pages/PlatformFulfillmentPage.tsx | 28 +++++- 15 files changed, 294 insertions(+), 7 deletions(-) create mode 100644 web/backend/migrations/versions/20261124_0132_fulfillment_flow_version.py diff --git a/docs/斗鱼/斗鱼业务彻底优化与重构计划.md b/docs/斗鱼/斗鱼业务彻底优化与重构计划.md index 4d1e8e0..0944e6f 100644 --- a/docs/斗鱼/斗鱼业务彻底优化与重构计划.md +++ b/docs/斗鱼/斗鱼业务彻底优化与重构计划.md @@ -654,3 +654,28 @@ manual_override_at - 平台任务变更后自动投影到台账; - 旧人工台账与平台来源台账的视觉分组; - 台账只读后,特殊异常单的「转人工台账」入口。 + +## 15. Clean Cutover:旧数据冻结(2026-11-24 确认) + +旧任务不再逐条清洗,统一隔离为历史任务;新订单进入 clean 流程。 + +### 15.1 数据边界 + +- `platform_fulfillment_tasks.flow_version = 1`:历史存量; +- `flow_version = 2`:Cutover 之后的新任务; +- 迁移执行时刻写入 `platform_fulfillment_settings.clean_flow_started_at`; +- 旧订单在 Cutover 后补建的任务,按订单支付/创建时间仍归为 legacy。 + +### 15.2 行为边界 + +- 自动选号只处理 `flow_version=2`; +- 历史任务只允许人工操作,不参与自动重试、自动收口和预售台账自动同步; +- 工作台新增“历史任务”入口,主工作台默认只看 clean; +- 历史列表不受订单起算时间限制,确保旧单可查; +- 旧 active 租约不做强制批量释放,后续单独出候选清单。 + +### 15.3 目标 + +- 不再为 2,462 条 lease_expired 等旧噪音逐条修数据; +- 新单人工队列只保留当前真实异常; +- 旧数据保留可查、可审计、可人工处理。 diff --git a/tests/test_migrations.py b/tests/test_migrations.py index 21dbf43..508d7a5 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -45,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = TESTS_DIR.parent VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" -HEAD_REVISION = "20261124_0131" +HEAD_REVISION = "20261124_0132" # 迁移新增、但不声明在模型里的复合查询索引。 EXTRA_INDEXES = ( @@ -90,6 +90,7 @@ _LATER_ORM_COLUMNS = { "customer_system": "VARCHAR(16) NOT NULL DEFAULT ''", "customer_home_images": "JSON NULL", "customer_profile_updated_at": "DATETIME NULL", + "flow_version": "INTEGER NOT NULL DEFAULT 1", }, "douyu_external_orders": { "succeeded_at": "DATETIME NULL", diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 101b0cc..eff2a97 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -1082,6 +1082,44 @@ class TestSnapshotSync(_Base): outbox = self.session.query(IntegrationOutbox).one() assert outbox.payload_json["items"][0]["stateVersion"] == 1 + def test_snapshot_before_clean_cutover_creates_legacy_task(self): + self.mapping() + setting = self.session.get(PlatformFulfillmentSetting, 1) + setting.clean_flow_started_at = NOW + self.session.commit() + + service.sync_order_snapshot( + self.session, + {"data": self.snapshot(paidAt=(NOW - timedelta(hours=1)).isoformat())}, + ) + + task = self.session.query(PlatformFulfillmentTask).one() + assert task.flow_version == 1 + assert service.list_tasks(self.session, flow_version=2)["pagination"]["total"] == 0 + assert service.list_tasks(self.session, flow_version=1)["pagination"]["total"] == 1 + + def test_snapshot_after_clean_cutover_creates_clean_task(self): + self.mapping() + setting = self.session.get(PlatformFulfillmentSetting, 1) + setting.clean_flow_started_at = NOW - timedelta(hours=1) + self.session.commit() + + service.sync_order_snapshot(self.session, {"data": self.snapshot()}) + + task = self.session.query(PlatformFulfillmentTask).one() + assert task.flow_version == 2 + + def test_legacy_list_ignores_order_match_cutoff(self): + task = self.task() + task.flow_version = 1 + task.paid_at = NOW - timedelta(days=10) + self.session.commit() + + listed = service.list_tasks(self.session, flow_version=1) + + assert listed["pagination"]["total"] == 1 + assert listed["items"][0]["flowVersion"] == 1 + def test_duplicate_snapshot_keeps_allocated_task_state(self): self.mapping() account = self.account("snapshot-allocated") diff --git a/tests/test_platform_fulfillment_auto_allocator.py b/tests/test_platform_fulfillment_auto_allocator.py index 6ab110d..0145aff 100644 --- a/tests/test_platform_fulfillment_auto_allocator.py +++ b/tests/test_platform_fulfillment_auto_allocator.py @@ -357,3 +357,44 @@ def test_schedule_retry_preserves_longer_capability_retry(db): db.refresh(task) assert task.next_allocate_at == retry_at + + +def test_auto_allocator_ignores_legacy_tasks(db): + actor = User( + username="auto-legacy-actor", password_hash="h", role="super_admin" + ) + db.add_all( + [ + actor, + PlatformFulfillmentSetting( + id=1, + lease_duration_minutes=None, + order_match_started_at=datetime.now(UTC) - timedelta(days=1), + ), + PlatformFulfillmentTask( + source_system="order_site", + source_order_id="legacy-1", + source_order_item_id="legacy-1", + platform_order_id="AUTO-LEGACY", + internal_sku_key="skin", + commodity_id="commodity-1", + flow_version=1, + execution_status="ready", + binding_status="not_started", + exchange_status="not_started", + paid_at=datetime.now(UTC), + next_allocate_at=datetime.now(UTC), + updated_at=datetime.now(UTC), + ), + ] + ) + db.commit() + + with patch.object( + auto_allocator.service, + "allocate_task", + side_effect=AssertionError("legacy tasks must not be auto allocated"), + ): + result = auto_allocator.run_auto_allocation_once(db, limit=10) + + assert result == {"checked": 0, "allocated": 0, "failed": 0} diff --git a/web/backend/migrations/migration_manifest.json b/web/backend/migrations/migration_manifest.json index 02c6a4a..f914a51 100644 --- a/web/backend/migrations/migration_manifest.json +++ b/web/backend/migrations/migration_manifest.json @@ -525,6 +525,10 @@ "20261124_0131_fulfillment_customer_profile.py": { "revision": "20261124_0131", "sha256": "23f8780eb16a689a5f929f3f1e1865e84c0896dbde70be6bbffb0ef77d06d587" + }, + "20261124_0132_fulfillment_flow_version.py": { + "revision": "20261124_0132", + "sha256": "c32ae403de640251e4ae8d86bd0948c189c3580141f1454490b4798bb286e3a3" } } } diff --git a/web/backend/migrations/versions/20261124_0132_fulfillment_flow_version.py b/web/backend/migrations/versions/20261124_0132_fulfillment_flow_version.py new file mode 100644 index 0000000..e451333 --- /dev/null +++ b/web/backend/migrations/versions/20261124_0132_fulfillment_flow_version.py @@ -0,0 +1,91 @@ +"""直播履约 clean/legacy 流程分界。 + +- 存量任务统一标记为 legacy(flow_version=1); +- 迁移执行时设置 clean_flow_started_at,之后的订单进入 clean 流程; +- 已经是 clean 的任务不会再被自动调度逻辑回退。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261124_0132" +down_revision: str | None = "20261124_0131" +branch_labels: str | None = None +depends_on: str | None = None + +TASK_TABLE = "platform_fulfillment_tasks" +SETTINGS_TABLE = "platform_fulfillment_settings" + + +def _column_exists(table: str, name: str) -> bool: + conn = op.get_bind() + count = conn.execute( + sa.text( + "SELECT COUNT(*) FROM information_schema.columns " + "WHERE table_schema = DATABASE() AND table_name = :table " + "AND column_name = :name" + ), + {"table": table, "name": name}, + ).scalar() + return bool(count) + + +def _index_exists(table: str, name: str) -> bool: + conn = op.get_bind() + count = conn.execute( + sa.text( + "SELECT COUNT(*) FROM information_schema.statistics " + "WHERE table_schema = DATABASE() AND table_name = :table " + "AND index_name = :name" + ), + {"table": table, "name": name}, + ).scalar() + return bool(count) + + +def upgrade() -> None: + if not _column_exists(TASK_TABLE, "flow_version"): + op.add_column( + TASK_TABLE, + sa.Column( + "flow_version", + sa.Integer(), + nullable=False, + server_default="1", + ), + ) + if not _index_exists(TASK_TABLE, "ix_platform_fulfillment_tasks_flow_version"): + op.create_index( + "ix_platform_fulfillment_tasks_flow_version", + TASK_TABLE, + ["flow_version"], + ) + if not _column_exists(SETTINGS_TABLE, "clean_flow_started_at"): + op.add_column( + SETTINGS_TABLE, + sa.Column("clean_flow_started_at", sa.DateTime(), nullable=True), + ) + # 迁移执行时刻就是 Cutover;存量任务已在 flow_version 默认值 1。 + op.execute( + sa.text( + """ + UPDATE platform_fulfillment_settings + SET clean_flow_started_at = UTC_TIMESTAMP() + WHERE id = 1 AND clean_flow_started_at IS NULL + """ + ) + ) + + +def downgrade() -> None: + if _column_exists(SETTINGS_TABLE, "clean_flow_started_at"): + op.drop_column(SETTINGS_TABLE, "clean_flow_started_at") + if _index_exists(TASK_TABLE, "ix_platform_fulfillment_tasks_flow_version"): + op.drop_index( + "ix_platform_fulfillment_tasks_flow_version", + table_name=TASK_TABLE, + ) + if _column_exists(TASK_TABLE, "flow_version"): + op.drop_column(TASK_TABLE, "flow_version") diff --git a/web/backend/models.py b/web/backend/models.py index 688cbef..2896f11 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -2313,6 +2313,11 @@ class PlatformFulfillmentSetting(Base): nullable=False, default=_utcnow, ) + # Clean Cutover 时间;之前是 legacy 任务,之后进入 clean 流程。 + clean_flow_started_at: Mapped[datetime | None] = mapped_column( + UTCDateTime, + nullable=True, + ) updated_by: Mapped[int | None] = mapped_column( ForeignKey("users.id", ondelete="SET NULL"), nullable=True, @@ -2408,6 +2413,14 @@ class PlatformFulfillmentTask(Base): source_fulfillment_id: Mapped[str] = mapped_column( String(64), nullable=False, default="", server_default="" ) + # 1 = 历史存量,只允许人工处理;2 = Clean Cutover 后的新单。 + flow_version: Mapped[int] = mapped_column( + Integer, + nullable=False, + default=2, + server_default="1", + index=True, + ) platform_order_id: Mapped[str] = mapped_column( String(128), nullable=False, default="", server_default="" ) diff --git a/web/backend/routers/platform_fulfillment.py b/web/backend/routers/platform_fulfillment.py index 416a718..5239217 100644 --- a/web/backend/routers/platform_fulfillment.py +++ b/web/backend/routers/platform_fulfillment.py @@ -80,6 +80,7 @@ def list_tasks( status: str = Query("", max_length=32), queue_bucket: str = Query("", max_length=32), sale_mode: str = Query("", max_length=16), + flow_version: int | None = Query(None, ge=1, le=2), keyword: str = Query("", max_length=200), page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100), @@ -92,6 +93,7 @@ def list_tasks( status=status, queue_bucket=queue_bucket, sale_mode=sale_mode, + flow_version=flow_version, keyword=keyword, page=page, page_size=page_size, diff --git a/web/backend/services/platform_fulfillment/auto_allocator.py b/web/backend/services/platform_fulfillment/auto_allocator.py index 48564ad..a0b5d56 100644 --- a/web/backend/services/platform_fulfillment/auto_allocator.py +++ b/web/backend/services/platform_fulfillment/auto_allocator.py @@ -16,6 +16,7 @@ from sqlalchemy.orm import Session from ...database import WorkerSessionLocal from ...models import PlatformFulfillmentTask from . import service +from .common import FLOW_VERSION_CLEAN DEFAULT_INTERVAL_SECONDS = 20 DEFAULT_MIN_INTERVAL_SECONDS = 5 @@ -138,6 +139,8 @@ def run_auto_allocation_once( due_cutoff = moment + timedelta(seconds=1) query = db.query(PlatformFulfillmentTask).filter( PlatformFulfillmentTask.execution_status == "ready", + # 存量任务只允许人工处理,自动选号只服务 Clean Cutover 之后的新单。 + PlatformFulfillmentTask.flow_version == FLOW_VERSION_CLEAN, PlatformFulfillmentTask.account_id.is_(None), PlatformFulfillmentTask.commodity_id != "", or_( diff --git a/web/backend/services/platform_fulfillment/common.py b/web/backend/services/platform_fulfillment/common.py index 5dc365d..0ed122c 100644 --- a/web/backend/services/platform_fulfillment/common.py +++ b/web/backend/services/platform_fulfillment/common.py @@ -21,6 +21,8 @@ from ..douyu_account_state import DouyuLiveAccountState TARGET_PLATFORM = "douyu" SCOPE_ELITE = "elite" +FLOW_VERSION_LEGACY = 1 +FLOW_VERSION_CLEAN = 2 BINDING_COOLDOWN_ISSUES = frozenset({"account_role_cooldown", "customer_role_cooldown"}) ACTIVE_STATUSES = { "ready", @@ -148,6 +150,33 @@ def _order_match_started_at(db: Session) -> datetime | None: return row.order_match_started_at if row is not None else None +def _clean_flow_started_at(db: Session) -> datetime | None: + row = ( + db.query(PlatformFulfillmentSetting) + .filter(PlatformFulfillmentSetting.id == 1) + .first() + ) + return row.clean_flow_started_at if row is not None else None + + +def _flow_version_for_order( + db: Session, + *, + paid_at: datetime | None, + created_at: datetime | None, +) -> int: + """按订单支付/创建时间划分 legacy/clean,避免旧订单补建任务混入新流程。""" + cutoff = _clean_flow_started_at(db) + basis = paid_at or created_at + if cutoff is None or basis is None: + return FLOW_VERSION_CLEAN + if cutoff.tzinfo is None: + cutoff = cutoff.replace(tzinfo=UTC) + if basis.tzinfo is None: + basis = basis.replace(tzinfo=UTC) + return FLOW_VERSION_LEGACY if basis < cutoff else FLOW_VERSION_CLEAN + + def _apply_order_match_cutoff( query, match_started_at: datetime | None, diff --git a/web/backend/services/platform_fulfillment/order_sync.py b/web/backend/services/platform_fulfillment/order_sync.py index b786241..9a2c5f2 100644 --- a/web/backend/services/platform_fulfillment/order_sync.py +++ b/web/backend/services/platform_fulfillment/order_sync.py @@ -23,6 +23,7 @@ from .common import ( AUTO_SYNC_INTERVAL_SECONDS, SCOPE_ELITE, TARGET_PLATFORM, + _flow_version_for_order, _jsonable, _now, _order_match_started_at, @@ -181,6 +182,11 @@ def _upsert_order_snapshot( ), target_platform=TARGET_PLATFORM, scope=SCOPE_ELITE, + flow_version=_flow_version_for_order( + db, + paid_at=paid_at, + created_at=order_created_at, + ), created_at=_now(), updated_at=_now(), ) @@ -534,6 +540,11 @@ def _sync_pending_tasks( source_order_id=str(row.get("source_order_id") or ""), source_order_item_id=item_id, source_fulfillment_id=str(row.get("source_fulfillment_id") or ""), + flow_version=_flow_version_for_order( + db, + paid_at=_parse_snapshot_datetime(row.get("paid_at")), + created_at=_now(), + ), created_at=_now(), updated_at=_now(), ) diff --git a/web/backend/services/platform_fulfillment/views.py b/web/backend/services/platform_fulfillment/views.py index cf90b6d..3c0f4e7 100644 --- a/web/backend/services/platform_fulfillment/views.py +++ b/web/backend/services/platform_fulfillment/views.py @@ -79,6 +79,7 @@ def _count_cache_key( status: str, queue_bucket: str, sale_mode: str, + flow_version: int | None, keyword: str, ) -> tuple[Any, ...]: return ( @@ -86,6 +87,7 @@ def _count_cache_key( status, queue_bucket, sale_mode, + flow_version, keyword.strip(), ) @@ -209,13 +211,18 @@ def list_tasks( status: str = "", queue_bucket: str = "", sale_mode: str = "", + flow_version: int | None = None, keyword: str = "", page: int = 1, page_size: int = 20, ) -> dict[str, Any]: cutoff = _order_match_started_at(db) query = db.query(PlatformFulfillmentTask) - query = _apply_order_match_cutoff(query, cutoff) + if flow_version is not None: + query = query.filter(PlatformFulfillmentTask.flow_version == flow_version) + # 历史任务不受订单起算时间限制,否则很多旧单在工作台里永远看不到。 + if flow_version != 1: + query = _apply_order_match_cutoff(query, cutoff) # 待映射队列本身就是要展示“还没有映射”的任务,不能再套映射存在条件。 if queue_bucket != "pending_mapping": query = query.filter( @@ -310,6 +317,7 @@ def list_tasks( status=status, queue_bucket=queue_bucket, sale_mode=sale_mode, + flow_version=flow_version, keyword=keyword, ), ) @@ -426,6 +434,7 @@ def _task_out( "goodsName": goods_name, "requiredPoints": task.required_points, "saleMode": sale_mode, + "flowVersion": int(task.flow_version or 1), "campaignKey": task.campaign_key, "campaignName": task.campaign_name, "offerAvailableFrom": task.offer_available_from, diff --git a/web/frontend/src/api/platformFulfillment.ts b/web/frontend/src/api/platformFulfillment.ts index 39be3b1..9b9af38 100644 --- a/web/frontend/src/api/platformFulfillment.ts +++ b/web/frontend/src/api/platformFulfillment.ts @@ -53,6 +53,7 @@ export const platformFulfillmentApi = { status?: string; queue_bucket?: string; sale_mode?: string; + flow_version?: number; keyword?: string; page?: number; page_size?: number; diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index ad5fee6..7296500 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -2573,6 +2573,7 @@ export interface PlatformFulfillmentTask { goodsName: string; requiredPoints: number | null; saleMode: 'presale' | 'direct' | 'manual' | 'unknown'; + flowVersion: number; campaignKey: string; campaignName: string; offerAvailableFrom: string | null; diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index cc034b7..edc84c7 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -465,9 +465,9 @@ export default function PlatformFulfillmentPage() { const navigate = useNavigate(); const { can } = usePermissions(user); const [queueBucket, setQueueBucket] = useState('current'); - const [saleModeTab, setSaleModeTab] = useState<'direct' | 'presale' | 'unknown'>(() => { + const [saleModeTab, setSaleModeTab] = useState<'direct' | 'presale' | 'unknown' | 'legacy'>(() => { const saved = localStorage.getItem(SALE_MODE_TAB_STORAGE_KEY); - if (saved === 'presale' || saved === 'unknown') return saved; + if (saved === 'presale' || saved === 'unknown' || saved === 'legacy') return saved; return 'direct'; }); @@ -568,7 +568,8 @@ export default function PlatformFulfillmentPage() { const result = await platformFulfillmentApi.listTasks({ status: queueBackedStatus, queue_bucket: backendBucket, - sale_mode: saleModeTab, + sale_mode: saleModeTab === 'legacy' ? undefined : saleModeTab, + flow_version: saleModeTab === 'legacy' ? 1 : 2, keyword: keyword.trim() || undefined, page, page_size: pageSize, @@ -1693,7 +1694,13 @@ export default function PlatformFulfillmentPage() { activeKey={saleModeTab} onChange={(value) => { const next = - value === 'presale' ? 'presale' : value === 'unknown' ? 'unknown' : 'direct'; + value === 'presale' + ? 'presale' + : value === 'unknown' + ? 'unknown' + : value === 'legacy' + ? 'legacy' + : 'direct'; setSaleModeTab(next); if (next !== 'presale' && queueBucket === 'presale_waiting') { setQueueBucket('current'); @@ -1705,9 +1712,18 @@ export default function PlatformFulfillmentPage() { { key: 'direct', label: '直接兑换' }, { key: 'presale', label: '预售' }, { key: 'unknown', label: '未分类' }, + { key: 'legacy', label: '历史任务' }, ]} /> + {saleModeTab === 'legacy' ? ( + + ) : null} + { setQueueBucket(String(value)); setSelectedRowKeys([]);