diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 7372716..4aa7e47 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -1154,6 +1154,30 @@ class TestSnapshotSync(_Base): assert task.state_version == 2 assert task.next_allocate_at is None + def test_valid_snapshot_restores_source_cancelled_task(self): + self.mapping() + service.sync_order_snapshot(self.session, {"data": self.snapshot()}) + service.sync_order_snapshot( + self.session, + {"data": self.snapshot(douyuFulfillmentEnabled=False)}, + ) + task = self.session.query(PlatformFulfillmentTask).one() + assert task.execution_status == "cancelled" + assert task.issue_code == "source_cancelled" + + service.sync_order_snapshot(self.session, {"data": self.snapshot()}) + + self.session.refresh(task) + assert task.execution_status == "ready" + assert task.issue_code == "" + assert task.last_error == "" + assert ( + self.session.query(PlatformFulfillmentEvent) + .filter_by(task_id=task.id, event_type="source_order_restored") + .count() + == 1 + ) + def test_unpaid_snapshot_does_not_enter_live_fulfillment(self): self.mapping() diff --git a/web/backend/services/platform_fulfillment/order_sync.py b/web/backend/services/platform_fulfillment/order_sync.py index a5eaea8..b786241 100644 --- a/web/backend/services/platform_fulfillment/order_sync.py +++ b/web/backend/services/platform_fulfillment/order_sync.py @@ -217,11 +217,6 @@ def _upsert_order_snapshot( task.issue_code, ) _apply_customer_profile(task, snapshot) - if task.execution_status in {"completed", "cancelled"}: - task.source_snapshot_json = _jsonable(snapshot) - return task, created, False - - previous_execution_status = task.execution_status terminal = ( terminal_order or _snapshot_value( @@ -246,6 +241,30 @@ def _upsert_order_snapshot( ) is False ) + if task.execution_status in {"completed", "cancelled"}: + # 历史“停用配置”的旧快照可能先到,随后开启配置的新快照又到; + # 系统原因取消的任务允许被后续有效快照恢复。用户取消/完成的仍保持终态。 + if ( + task.execution_status == "cancelled" + and task.issue_code == "source_cancelled" + and not terminal + ): + task.execution_status = "pending_mapping" + task.issue_code = "" + task.last_error = "" + task.next_allocate_at = None + task.completed_at = None + _append_event( + db, + task.id, + "source_order_restored", + detail={"reason": "valid_snapshot_after_source_cancel"}, + ) + else: + task.source_snapshot_json = _jsonable(snapshot) + return task, created, False + + previous_execution_status = task.execution_status task.platform_order_id = str( _snapshot_value(snapshot, "platformOrderId", "platform_order_id", default="")