From 05a7a56c4e2f895f14697b8f9f7785fbd7262f80 Mon Sep 17 00:00:00 2001 From: yml Date: Mon, 23 Nov 2026 13:56:32 +0800 Subject: [PATCH] =?UTF-8?q?refactor(fulfillment):=20=E6=8B=86=E5=88=86?= =?UTF-8?q?=E5=B1=A5=E7=BA=A6=E6=9C=8D=E5=8A=A1=E5=B9=B6=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E6=8D=A2=E7=BB=91=E5=86=B7=E5=8D=B4=E5=88=86=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_douyu_binding_state.py | 12 + tests/test_douyu_task_concurrency.py | 46 +- tests/test_platform_fulfillment.py | 165 +- .../test_platform_fulfillment_integration.py | 8 +- web/backend/services/account_binding.py | 48 +- web/backend/services/douyu_runner_bind.py | 14 +- .../platform_fulfillment/allocation.py | 613 +++ .../services/platform_fulfillment/binding.py | 390 ++ .../platform_fulfillment/binding_status.py | 184 + .../services/platform_fulfillment/common.py | 157 + .../services/platform_fulfillment/customer.py | 130 + .../platform_fulfillment/lifecycle.py | 760 ++++ .../services/platform_fulfillment/mappings.py | 548 +++ .../platform_fulfillment/order_sync.py | 541 +++ .../services/platform_fulfillment/outbox.py | 41 + .../platform_fulfillment/repository.py | 127 + .../services/platform_fulfillment/runtime.py | 381 ++ .../services/platform_fulfillment/service.py | 4030 +---------------- .../services/platform_fulfillment/views.py | 516 +++ 19 files changed, 4760 insertions(+), 3951 deletions(-) create mode 100644 web/backend/services/platform_fulfillment/allocation.py create mode 100644 web/backend/services/platform_fulfillment/binding.py create mode 100644 web/backend/services/platform_fulfillment/binding_status.py create mode 100644 web/backend/services/platform_fulfillment/common.py create mode 100644 web/backend/services/platform_fulfillment/customer.py create mode 100644 web/backend/services/platform_fulfillment/lifecycle.py create mode 100644 web/backend/services/platform_fulfillment/mappings.py create mode 100644 web/backend/services/platform_fulfillment/order_sync.py create mode 100644 web/backend/services/platform_fulfillment/outbox.py create mode 100644 web/backend/services/platform_fulfillment/repository.py create mode 100644 web/backend/services/platform_fulfillment/runtime.py create mode 100644 web/backend/services/platform_fulfillment/views.py diff --git a/tests/test_douyu_binding_state.py b/tests/test_douyu_binding_state.py index 47e45e4..b159a1f 100644 --- a/tests/test_douyu_binding_state.py +++ b/tests/test_douyu_binding_state.py @@ -16,6 +16,7 @@ from web.backend.services.account_binding import ( binding_pending_decision, binding_role_from_result, binding_snapshot, + classify_bind_cooldown, derive_from_bind_info, is_pending_binding_role, is_platform_account_bind_cooldown, @@ -627,6 +628,17 @@ def test_bind_cooldown_messages_distinguish_platform_and_customer_accounts(): assert is_platform_account_bind_cooldown(-200001, customer_message) is False assert is_platform_account_bind_cooldown(-200001, platform_message) is True + assert classify_bind_cooldown(-200001, customer_message) == "customer" + assert classify_bind_cooldown(-200001, platform_message) == "platform" + assert ( + classify_bind_cooldown(-200001, "斗鱼账号当前绑定角色(旧角色)未到可换绑时间") + == "platform" + ) + assert ( + classify_bind_cooldown(-200001, "待绑定游戏账号(新角色)未到换绑时间") + == "customer" + ) + assert classify_bind_cooldown(-1, "系统繁忙,请稍后重试") is None def test_get_bind_qr_uses_role_param_url_for_mini_qrcode(monkeypatch): diff --git a/tests/test_douyu_task_concurrency.py b/tests/test_douyu_task_concurrency.py index 71ab4ad..7a5520a 100644 --- a/tests/test_douyu_task_concurrency.py +++ b/tests/test_douyu_task_concurrency.py @@ -856,10 +856,38 @@ def test_deadline_poll_still_checks_role_once_before_timeout(db, monkeypatch): assert task.result["bind_ready_for_confirm"] is True -def test_confirm_bind_maps_platform_cooldown_and_keeps_old_role( - db, monkeypatch +@pytest.mark.parametrize( + ("confirm_code", "confirm_message", "expected_issue", "message_markers"), + [ + ( + -200001, + "该平台账号未到可换绑时间,请使用其他平台账号", + "account_role_cooldown", + ("斗鱼账号", "更换斗鱼账号"), + ), + ( + -200001, + "该账号未到可换绑时间,请使用其他账号", + "customer_role_cooldown", + ("待绑定游戏账号", "重新换账号"), + ), + ( + -1, + "系统繁忙,请稍后重试", + "binding_failed", + ("确认绑定失败", "系统繁忙"), + ), + ], +) +def test_confirm_bind_maps_cooldown_and_keeps_old_role( + db, + monkeypatch, + confirm_code, + confirm_message, + expected_issue, + message_markers, ): - """2026-11-22 失败 HAR:-200001 是斗鱼账号冷却,旧绑定不能被新角色覆盖。""" + """两类 -200001 必须按原始文案区分,且旧绑定不能被失败角色覆盖。""" _, account, task = _fixtures(db, status="running") old_role = "狗鼻子弗尼亚bd" new_role = "巫师基尔斯84" @@ -900,8 +928,8 @@ def test_confirm_bind_maps_platform_cooldown_and_keeps_old_role( "can_change_role": True, } payload = { - "error": -200001, - "msg": "该平台账号未到可换绑时间,请使用其他平台账号", + "error": confirm_code, + "msg": confirm_message, "data": None, } @@ -942,13 +970,13 @@ def test_confirm_bind_maps_platform_cooldown_and_keeps_old_role( db.refresh(task) db.refresh(account) assert task.status == "failed" - assert task.result["issue_code"] == "account_role_cooldown" - assert task.result["confirm_error_code"] == -200001 + assert task.result["issue_code"] == expected_issue + assert task.result["confirm_error_code"] == confirm_code assert task.result["before_bound_bind_info"]["role_name"] == old_role assert task.result["role_name"] == new_role assert task.result["bind_ready_for_confirm"] is False - assert "斗鱼账号" in task.message - assert "更换斗鱼账号" in task.message + for marker in message_markers: + assert marker in task.message assert account.game_name == old_role assert account.role_bind_status == "bound" diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index d16aabe..da82b3f 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -171,7 +171,7 @@ class TestSyncAndMapping(_Base): self, monkeypatch ): monkeypatch.setattr( - service, + service.order_sync, "list_pending_manual_fulfillments", lambda **_kwargs: (_ for _ in ()).throw( AssertionError("没有映射时不应查询 order_site") @@ -221,7 +221,7 @@ class TestSyncAndMapping(_Base): ] monkeypatch.setattr( - service, + service.order_sync, "list_pending_manual_fulfillments", _rows, ) @@ -418,7 +418,7 @@ class TestSyncAndMapping(_Base): current=self.admin, ) monkeypatch.setattr( - service, + service.order_sync, "lookup_pending_manual_fulfillment", lambda *_args, **_kwargs: None, ) @@ -905,6 +905,51 @@ class TestDouyuOperationTimeline(_Base): assert operation_events[0]["detail"]["douyuTaskId"] == douyu_task.id assert operation_events[1]["detail"]["batchId"] == douyu_task.batch_id + def test_binding_failure_event_uses_raw_confirm_error_classification(self): + task = self.task() + account = self.account("operation-customer-cooldown") + task.account_id = account.id + self.session.commit() + douyu_task = DouyuTask( + batch_id="platform-customer-cooldown", + account_id=account.id, + account_assigned_to=account.assigned_to, + task_type="confirm_bind", + handbook_scope="elite", + status="failed", + message="斗鱼账号当前绑定角色(旧角色)未到可换绑时间", + result={ + "issue_code": "account_role_cooldown", + "bind_phase": "confirm_failed", + "role_name": "客户角色", + "confirm_error": "该账号未到可换绑时间,请使用其他账号", + "confirm_error_code": -200001, + }, + created_by=self.admin_id, + platform_task_id=task.id, + ) + self.session.add(douyu_task) + self.session.commit() + + service.record_douyu_operation_result( + self.session, + douyu_task, + status="failed", + message=douyu_task.message, + ) + self.session.commit() + + event = ( + self.session.query(PlatformFulfillmentEvent) + .filter( + PlatformFulfillmentEvent.task_id == task.id, + PlatformFulfillmentEvent.event_type == "douyu_operation_failed", + ) + .one() + ) + assert event.detail_json["issueCode"] == "customer_role_cooldown" + assert "待绑定游戏账号(客户角色)" in event.detail_json["message"] + class TestSnapshotSync(_Base): def snapshot(self, **overrides): @@ -938,7 +983,7 @@ class TestSnapshotSync(_Base): ): self.mapping() monkeypatch.setattr( - service, + service.order_sync, "lookup_pending_manual_fulfillment", lambda *_args, **_kwargs: (_ for _ in ()).throw( AssertionError("新快照契约不应回查 order_site") @@ -1011,7 +1056,11 @@ class TestSnapshotSync(_Base): requested.append(item_id) return self.snapshot() - monkeypatch.setattr(service, "lookup_pending_manual_fulfillment", lookup) + monkeypatch.setattr( + service.order_sync, + "lookup_pending_manual_fulfillment", + lookup, + ) result = service.sync_order_item_ids(self.session, ["101"]) @@ -1646,7 +1695,11 @@ class TestBindingAndCompletion(_Base): task.issue_code = "binding_failed" task.last_error = "绑定失败,请刷新二维码后重试" self.session.commit() - monkeypatch.setattr(service, "start_douyu_batch", lambda **_kwargs: None) + monkeypatch.setattr( + service.binding, + "start_douyu_batch", + lambda **_kwargs: None, + ) asyncio.run( service.start_binding( @@ -1709,7 +1762,11 @@ class TestBindingAndCompletion(_Base): def test_customer_start_creates_one_binding_task_and_links_platform(self, monkeypatch): task = self._allocated() - monkeypatch.setattr(service, "start_douyu_batch", lambda **_kwargs: None) + monkeypatch.setattr( + service.binding, + "start_douyu_batch", + lambda **_kwargs: None, + ) first = asyncio.run(service.customer_start_binding(self.session, task_id=task.id)) second = asyncio.run(service.customer_start_binding(self.session, task_id=task.id)) @@ -1732,7 +1789,7 @@ class TestBindingAndCompletion(_Base): task = self._allocated() captured: dict[str, object] = {} monkeypatch.setattr( - service, + service.binding, "start_douyu_batch", lambda **kwargs: captured.update(kwargs), ) @@ -1744,7 +1801,11 @@ class TestBindingAndCompletion(_Base): def test_concurrent_start_binding_creates_one_task(self, monkeypatch): task = self._allocated() - monkeypatch.setattr(service, "start_douyu_batch", lambda **_kwargs: None) + monkeypatch.setattr( + service.binding, + "start_douyu_batch", + lambda **_kwargs: None, + ) barrier = threading.Barrier(2) errors: list[BaseException] = [] other_session = make_test_session(self.engine) @@ -1815,7 +1876,11 @@ class TestBindingAndCompletion(_Base): task.binding_status = "role_ready" task.execution_status = "role_ready" self.session.commit() - monkeypatch.setattr(service, "start_douyu_batch", lambda **_kwargs: None) + monkeypatch.setattr( + service.binding, + "start_douyu_batch", + lambda **_kwargs: None, + ) asyncio.run( service.confirm_binding( @@ -1985,7 +2050,7 @@ class TestBindingAndCompletion(_Base): self.session.add(collab_order) self.session.commit() monkeypatch.setattr( - service, + service.lifecycle, "lookup_pending_manual_fulfillment", lambda _item_id: { "order_status": "paid", @@ -2054,7 +2119,7 @@ class TestBindingAndCompletion(_Base): ) self.session.commit() monkeypatch.setattr( - service, + service.lifecycle, "lookup_pending_manual_fulfillment", lambda _item_id: { "order_status": "paid", @@ -2083,7 +2148,7 @@ class TestBindingAndCompletion(_Base): reason="客服误点取消", ) monkeypatch.setattr( - service, + service.lifecycle, "lookup_pending_manual_fulfillment", lambda _item_id: { "order_status": "refunded", @@ -2128,7 +2193,7 @@ class TestBindingAndCompletion(_Base): lease_id = task.lease_id stopped: list[str] = [] monkeypatch.setattr( - service, + service.lifecycle, "stop_douyu_batches", lambda batch_ids: stopped.extend(batch_ids) or len(batch_ids), ) @@ -2230,7 +2295,7 @@ class TestBindingAndCompletion(_Base): def test_refresh_binding_maps_role_ready(self, monkeypatch): notified: list[int] = [] monkeypatch.setattr( - service, + service.binding, "_emit_order_site_binding_state", lambda _db, task_id: notified.append(task_id) or True, ) @@ -2332,7 +2397,11 @@ class TestBindingAndCompletion(_Base): task.binding_status = "qr_pending" task.execution_status = "waiting_bind" self.session.commit() - monkeypatch.setattr(service, "start_douyu_batch", lambda **_kwargs: None) + monkeypatch.setattr( + service.binding, + "start_douyu_batch", + lambda **_kwargs: None, + ) asyncio.run( service.start_binding( @@ -2509,6 +2578,7 @@ class TestBindingAndCompletion(_Base): message="待绑定游戏账号(测试角色)未到换绑时间,请重新换账号扫码绑定", result={ "bind_phase": "confirm_failed", + "issue_code": "account_role_cooldown", "role_name": "测试角色", "bind_ready_for_confirm": True, "bind_confirmed": False, @@ -2520,10 +2590,59 @@ class TestBindingAndCompletion(_Base): self.session.add(bind_task) self.session.flush() task.bind_task_id = bind_task.id - task.binding_status = "role_ready" - task.execution_status = "role_ready" + task.binding_status = "failed" + task.execution_status = "manual_required" + task.issue_code = "account_role_cooldown" + task.last_error = ( + "斗鱼账号当前绑定角色(测试角色)未到可换绑时间," + "请更换斗鱼账号或稍后重试" + ) + self.session.add_all( + [ + PlatformFulfillmentEvent( + task_id=task.id, + event_type="douyu_operation_failed", + actor_type="system", + detail_json={ + "douyuTaskId": bind_task.id, + "message": task.last_error, + }, + ), + PlatformFulfillmentEvent( + task_id=task.id, + event_type="binding_failed", + actor_type="system", + detail_json={ + "bindTaskId": bind_task.id, + "issueCode": "account_role_cooldown", + "rawError": task.last_error, + }, + ), + ] + ) self.session.commit() + historical = service.get_task_detail(self.session, task_id=task.id) + assert historical["task"]["issueCode"] == "customer_role_cooldown" + assert "游戏角色" in historical["task"]["lastError"] + operation_event = next( + event + for event in historical["events"] + if event["eventType"] == "douyu_operation_failed" + ) + binding_event = next( + event + for event in historical["events"] + if event["eventType"] == "binding_failed" + ) + assert "待绑定游戏账号" in operation_event["detail"]["message"] + assert operation_event["detail"]["issueCode"] == "customer_role_cooldown" + assert "待绑定游戏账号" in binding_event["detail"]["rawError"] + assert binding_event["detail"]["issueCode"] == "customer_role_cooldown" + historical_live = service.customer_binding_out(self.session, task.id) + assert historical_live["issueCode"] == "customer_role_cooldown" + assert "游戏角色" in historical_live["message"] + detail = service.refresh_binding(self.session, task_id=task.id) assert detail["task"]["issueCode"] == "customer_role_cooldown" @@ -2531,7 +2650,11 @@ class TestBindingAndCompletion(_Base): assert detail["task"]["executionStatus"] == "manual_required" assert "截图" in detail["task"]["lastError"] assert "联系客服" in detail["task"]["lastError"] + self.session.refresh(task) + assert task.issue_code == "customer_role_cooldown" live = service.customer_binding_out(self.session, task.id) + assert live["issueCode"] == "customer_role_cooldown" + assert "游戏角色" in live["message"] assert live["bindingStatus"] == "failed" assert live["executionStatus"] == "manual_required" assert live["bindReadyForConfirm"] is False @@ -2696,7 +2819,7 @@ class TestBindingAndCompletion(_Base): task.execution_status = "bound" self.session.commit() monkeypatch.setattr( - service, + service.lifecycle, "probe_account", lambda *_args, **_kwargs: { "probe_id": "points-short", @@ -2740,7 +2863,7 @@ class TestBindingAndCompletion(_Base): start_at = NOW + timedelta(days=4) end_at = NOW + timedelta(days=10) monkeypatch.setattr( - service, + service.lifecycle, "probe_account", lambda *_args, **_kwargs: { "probe_id": "presale-waiting", @@ -2792,7 +2915,7 @@ class TestBindingAndCompletion(_Base): task.execution_status = "bound" self.session.commit() monkeypatch.setattr( - service, + service.lifecycle, "probe_account", lambda *_args, **_kwargs: { "probe_id": "expired-elite", diff --git a/tests/test_platform_fulfillment_integration.py b/tests/test_platform_fulfillment_integration.py index 3a445df..d568586 100644 --- a/tests/test_platform_fulfillment_integration.py +++ b/tests/test_platform_fulfillment_integration.py @@ -155,9 +155,13 @@ def test_binding_qr_expiry_uses_customer_ttl(): def test_auto_order_sync_is_throttled(monkeypatch): calls: list[int] = [] - monkeypatch.setattr(service, "_AUTO_SYNC_LAST_ATTEMPT", float("-inf")) monkeypatch.setattr( - service, + service.order_sync, + "_AUTO_SYNC_LAST_ATTEMPT", + float("-inf"), + ) + monkeypatch.setattr( + service.order_sync, "sync_pending_tasks", lambda _db, *, limit: calls.append(limit) or {"fetched": 1}, ) diff --git a/web/backend/services/account_binding.py b/web/backend/services/account_binding.py index 2b79209..7c0a364 100644 --- a/web/backend/services/account_binding.py +++ b/web/backend/services/account_binding.py @@ -34,7 +34,7 @@ from __future__ import annotations from collections.abc import Sequence from datetime import UTC, datetime, timedelta -from typing import Any +from typing import Any, Literal from ..models import Account @@ -285,27 +285,55 @@ def role_change_available_at( return None -def is_platform_account_bind_cooldown( +BindCooldownKind = Literal["platform", "customer"] + + +def classify_bind_cooldown( error_code: Any = None, message: str = "", -) -> bool: - """是否为斗鱼平台账号自身的换绑冷却。 +) -> BindCooldownKind | None: + """区分斗鱼平台账号和客户游戏角色的换绑冷却。 两种冷却都是 ``-200001``,必须继续用文案区分: - “该平台账号未到可换绑时间,请使用其他平台账号”:斗鱼账号冷却; - “该账号未到可换绑时间,请使用其他账号”:客户游戏账号冷却。 + + 兼容本系统历史版本生成的展示文案,避免旧任务刷新后继续误判。 + ``-200001`` 但没有可识别文案时沿用历史兜底,按斗鱼账号冷却处理。 """ try: normalized_code = int(error_code) except (TypeError, ValueError): normalized_code = None - text = str(message or "") - if "该平台账号未到可换绑时间" in text: - return True - if "该账号未到可换绑时间" in text or "请使用其他账号" in text: - return False - return normalized_code == -200001 + text = "".join(str(message or "").split()) + platform_markers = ( + "该平台账号未到可换绑时间", + "请使用其他平台账号", + "斗鱼账号当前绑定角色", + "斗鱼账号当前角色", + ) + customer_markers = ( + "该账号未到可换绑时间", + "请使用其他账号", + "待绑定游戏账号", + "该游戏角色仍在换绑冷却期", + ) + if any(marker in text for marker in platform_markers): + return "platform" + if any(marker in text for marker in customer_markers): + return "customer" + if normalized_code == -200001: + return "platform" + return None + + +def is_platform_account_bind_cooldown( + error_code: Any = None, + message: str = "", +) -> bool: + """是否为斗鱼平台账号自身的换绑冷却。""" + return classify_bind_cooldown(error_code, message) == "platform" def binding_pending_decision( diff --git a/web/backend/services/douyu_runner_bind.py b/web/backend/services/douyu_runner_bind.py index 0644eeb..324941c 100644 --- a/web/backend/services/douyu_runner_bind.py +++ b/web/backend/services/douyu_runner_bind.py @@ -21,9 +21,9 @@ from .account_binding import ( SCOPE_ESPORTS, binding_pending_decision, binding_snapshot, + classify_bind_cooldown, is_bound_act, is_pending_binding_role, - is_platform_account_bind_cooldown, is_role_change_cooling, role_change_available_at, set_bind_status, @@ -1619,7 +1619,7 @@ class BindMixin: source="douyu_task.confirm_bind", act_alias=use_confirm_alias, ) - account_cooldown = is_platform_account_bind_cooldown( + cooldown_kind = classify_bind_cooldown( confirm_code, confirm_msg, ) @@ -1627,7 +1627,7 @@ class BindMixin: before_bound_role = str(before_bound_snapshot["role_name"] or "") before_bound_wait = before_bound_snapshot["change_role_wait_time"] before_bound_wait_text = self._format_wait_time(before_bound_wait) - if account_cooldown: + if cooldown_kind == "platform": issue_code = "account_role_cooldown" role_label = before_bound_role or role_name or "当前角色" suffix = f",剩余 {before_bound_wait_text}" if before_bound_wait_text else "" @@ -1635,12 +1635,18 @@ class BindMixin: f"斗鱼账号当前绑定角色({role_label})未到可换绑时间" f"{suffix},请更换斗鱼账号或稍后重试" ) - else: + elif cooldown_kind == "customer": issue_code = "customer_role_cooldown" failure_message = ( f"待绑定游戏账号({role_name or '-'})未到换绑时间" "(不是斗鱼/虎牙账号),请重新换账号扫码绑定" ) + else: + issue_code = "binding_failed" + failure_message = ( + f"确认绑定失败:{confirm_msg or '斗鱼接口返回异常'}" + ",请稍后重试或联系客服" + ) # 2026-11-22 换绑失败 HAR:actBind 已拒绝时新角色只存在于 cjm 候选态, # 活动 alias 仍是原绑定。必须保留旧角色,不能让失败角色污染账号库。 if before_bound is not None: diff --git a/web/backend/services/platform_fulfillment/allocation.py b/web/backend/services/platform_fulfillment/allocation.py new file mode 100644 index 0000000..0bcc80e --- /dev/null +++ b/web/backend/services/platform_fulfillment/allocation.py @@ -0,0 +1,613 @@ +"""能力池诊断、自动选号和租约分配。""" + +from __future__ import annotations + +import os +from datetime import datetime, timedelta +from typing import Any + +from fastapi import HTTPException +from sqlalchemy import func, select +from sqlalchemy.orm import Session + +from ...models import ( + Account, + AccountCommodityState, + AccountEvent, + AccountLease, + PlatformFulfillmentTask, + User, +) +from ..account_capability_service import ( + AVAILABILITY_AVAILABLE, + AVAILABILITY_LIMITED, + AVAILABILITY_NOT_OPEN, + OFFER_STATE_ACTIVE, + OFFER_STATE_BEFORE, + allocation_availability, +) +from ..account_query_filters import ( + active_collab_order_exists, + active_lease_exists, + assigned_to_pool_filter, + automatable_account_filter, + cookie_present_filter, + role_change_ready_filter, + valid_ck_filter, +) +from ..account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, WORK_STOREHOME_SYNC +from ..account_work_queue import ( + active_account_work_count, + enqueue_account_work, +) +from ..douyu_account_state import DouyuLiveAccountState +from . import classification +from .account_selector import ( + AccountCandidate, + CapabilityCandidate, + capability_candidate_rows, + capability_refresh_candidate_accounts, + lease_account, +) +from .common import ( + DEFAULT_CAPABILITY_CANDIDATE_LIMIT, + LOCAL_CACHE_MISS_RETRY_SECONDS, + LOCAL_LEASE_CONFLICT_RETRY_SECONDS, + LOCAL_STOCK_RETRY_SECONDS, + SCOPE_ELITE, + TARGET_PLATFORM, + _exchange_gate, + _jsonable, + _now, +) +from .outbox import _emit_order_site_binding_state +from .repository import _load_task +from .runtime import ( + _append_event, + _apply_task_lease_policy, + _lease_duration_minutes, +) +from .views import get_task_detail + + +def _cached_capability_state( + candidate: CapabilityCandidate, + *, + commodity_id: str, +) -> DouyuLiveAccountState: + """把新鲜本地能力快照转换成统一的履约状态,不访问斗鱼官网。""" + account = candidate.account + state = candidate.state + availability = allocation_availability( + state.account_eligibility, + state.offer_state, + ) + if availability == AVAILABILITY_AVAILABLE: + reason = "" + elif availability == AVAILABILITY_LIMITED: + reason = "该账号已达此商品兑换上限" + elif availability == AVAILABILITY_NOT_OPEN: + reason = ( + f"限时兑换未开始,开始于 {state.available_from.isoformat()}" + if state.available_from + else "活动尚未开放兑换" + ) + else: + reason = str(state.blocking_reason or "") + return DouyuLiveAccountState( + account_id=int(account.id), + account_name=account.nickname or account.username or f"#{account.id}", + checked_at=state.observed_at or _now(), + ck_verdict="valid", + ck_message="本地能力快照关联账号 CK 有效", + elite_opened=account.elite_opened, + points=account.points, + limited_ids=frozenset(), + role_change_available_at=account.role_change_available_at, + commodity_availability={commodity_id: availability}, + commodity_blocking_reasons=({commodity_id: reason} if reason else {}), + ) + + +def _capability_availability_counts( + db: Session, + *, + commodity_id: str, + scope: str, + now: datetime, +) -> dict[str, Any]: + base = db.query(AccountCommodityState).filter( + AccountCommodityState.platform == TARGET_PLATFORM, + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id == commodity_id, + AccountCommodityState.valid_until.isnot(None), + AccountCommodityState.valid_until > now, + ) + eligibility_rows = ( + base.with_entities( + AccountCommodityState.account_eligibility, + func.count(AccountCommodityState.id), + ) + .group_by(AccountCommodityState.account_eligibility) + .all() + ) + offer_rows = ( + db.query( + AccountCommodityState.offer_state, func.count(AccountCommodityState.id) + ) + .filter( + AccountCommodityState.platform == TARGET_PLATFORM, + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id == commodity_id, + AccountCommodityState.valid_until.isnot(None), + AccountCommodityState.valid_until > now, + ) + .group_by(AccountCommodityState.offer_state) + .all() + ) + stock_rows = ( + db.query( + AccountCommodityState.stock_state, func.count(AccountCommodityState.id) + ) + .filter( + AccountCommodityState.platform == TARGET_PLATFORM, + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id == commodity_id, + AccountCommodityState.valid_until.isnot(None), + AccountCommodityState.valid_until > now, + ) + .group_by(AccountCommodityState.stock_state) + .all() + ) + eligible_account_ids = ( + select(AccountCommodityState.account_id) + .where( + AccountCommodityState.platform == TARGET_PLATFORM, + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id == commodity_id, + AccountCommodityState.account_eligibility == "eligible", + AccountCommodityState.offer_state.in_( + (OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE) + ), + AccountCommodityState.valid_until.isnot(None), + AccountCommodityState.valid_until > now, + ) + .distinct() + ) + account_base = db.query(Account).filter(Account.id.in_(eligible_account_ids)) + eligible_accounts = int(account_base.count()) + role_ready_accounts = int( + account_base.filter(role_change_ready_filter(now)).count() + ) + leased_accounts = int(account_base.filter(active_lease_exists()).count()) + collab_accounts = int(account_base.filter(active_collab_order_exists()).count()) + allocatable_accounts = int( + account_base.filter( + cookie_present_filter(), + valid_ck_filter(), + automatable_account_filter(), + assigned_to_pool_filter(), + role_change_ready_filter(now), + ~active_lease_exists(), + ~active_collab_order_exists(), + ).count() + ) + next_role_ready_at = ( + account_base.filter( + Account.role_change_available_at.isnot(None), + Account.role_change_available_at > now, + ) + .with_entities(func.min(Account.role_change_available_at)) + .scalar() + ) + return { + **{f"eligibility:{key}": int(count or 0) for key, count in eligibility_rows}, + **{f"offer:{key}": int(count or 0) for key, count in offer_rows}, + **{f"stock:{key}": int(count or 0) for key, count in stock_rows}, + "account:eligible": eligible_accounts, + "account:roleReady": role_ready_accounts, + "account:roleCooldown": max(0, eligible_accounts - role_ready_accounts), + "account:leased": leased_accounts, + "account:activeCollab": collab_accounts, + "account:allocatable": allocatable_accounts, + "account:nextRoleReadyAt": _jsonable(next_role_ready_at), + } + + +def _local_allocation_retry_at( + db: Session, + *, + task: PlatformFulfillmentTask, + now: datetime, + availability_counts: dict[str, int], + lease_conflict: bool, +) -> tuple[datetime, str]: + """按本地状态决定下一轮时间,避免永久无库存任务每 45 秒占槽。""" + if lease_conflict: + return ( + now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS), + "lease_conflict", + ) + next_open_at = ( + db.query(func.min(AccountCommodityState.available_from)) + .filter( + AccountCommodityState.platform == TARGET_PLATFORM, + AccountCommodityState.scope == (task.scope or SCOPE_ELITE), + AccountCommodityState.commodity_id == task.commodity_id, + AccountCommodityState.offer_state == OFFER_STATE_BEFORE, + AccountCommodityState.available_from.isnot(None), + AccountCommodityState.available_from > now, + ) + .scalar() + ) + if next_open_at is not None: + return next_open_at + timedelta(seconds=5), "commodity_not_open" + if availability_counts.get(f"offer:{OFFER_STATE_BEFORE}"): + return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "commodity_not_open" + has_capability_rows = any( + int(value or 0) + for key, value in availability_counts.items() + if key.startswith(("eligibility:", "offer:", "stock:")) + ) + if has_capability_rows: + if int(availability_counts.get("account:allocatable") or 0) > 0: + return ( + now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS), + "lease_conflict", + ) + if int(availability_counts.get("account:roleCooldown") or 0) > 0: + return ( + now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), + "account_role_cooldown", + ) + if int(availability_counts.get("account:eligible") or 0) > 0: + return ( + now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), + "account_pool_busy", + ) + return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "no_eligible_account" + return now + timedelta( + seconds=LOCAL_CACHE_MISS_RETRY_SECONDS + ), "capability_cache_miss" + + +def _seed_capability_refresh( + db: Session, + *, + task: PlatformFulfillmentTask, + now: datetime, +) -> int: + """能力池不足时只入队独立同步槽,不在分配线程里请求官网。""" + try: + seed_limit = int( + os.getenv("PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT", "20") + ) + except ValueError: + seed_limit = 20 + seed_limit = max(1, min(seed_limit, 100)) + try: + target_pending = max( + 1, + int(os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "60")), + ) + except ValueError: + target_pending = 60 + pending = active_account_work_count( + db, + work_types=ACCOUNT_SYNC_WORK_TYPES, + ) + headroom = max(0, target_pending - pending) + if headroom <= 0: + return 0 + accounts = capability_refresh_candidate_accounts( + db, + commodity_ids=[task.commodity_id], + scope=task.scope or SCOPE_ELITE, + limit=min(seed_limit, headroom), + now=now, + ) + for account in accounts: + enqueue_account_work( + db, + account_id=int(account.id), + work_type=WORK_STOREHOME_SYNC, + priority=20, + due_at=now, + reason=f"履约任务 #{task.id} 缺少商品能力快照", + payload={ + "commodity_id": task.commodity_id, + "platform_task_id": int(task.id), + }, + ) + return len(accounts) + + +def _allocate_task_from_capability( + db: Session, + *, + task: PlatformFulfillmentTask, + current: User, +) -> dict[str, Any]: + """只用本地能力索引选号;外部资格查询留给独立同步队列。""" + moment = _now() + required_points = int(task.required_points or 0) + try: + candidate_limit = int( + os.getenv( + "PLATFORM_FULFILLMENT_CAPABILITY_CANDIDATE_LIMIT", + str(DEFAULT_CAPABILITY_CANDIDATE_LIMIT), + ) + ) + except ValueError: + candidate_limit = DEFAULT_CAPABILITY_CANDIDATE_LIMIT + candidate_limit = max(1, min(candidate_limit, 100)) + is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale" + capability_candidates = capability_candidate_rows( + db, + limit=candidate_limit, + required_points=required_points, + commodity_id=task.commodity_id, + scope=task.scope or SCOPE_ELITE, + now=moment, + allow_before_open=is_presale, + ) + recent_exchange_ids: set[int] = set() + if capability_candidates: + candidate_ids = [int(item.account.id) for item in capability_candidates] + since = moment - timedelta(days=365) + recent_exchange_ids = { + int(account_id) + for (account_id,) in ( + db.query(AccountEvent.account_id) + .filter( + AccountEvent.account_id.in_(candidate_ids), + AccountEvent.event_type == "exchange", + AccountEvent.subject_key == task.commodity_id, + AccountEvent.occurred_at >= since, + ) + .distinct() + .all() + ) + } + + diagnostics: list[dict[str, Any]] = [] + qualified: list[tuple[CapabilityCandidate, DouyuLiveAccountState]] = [] + for candidate in capability_candidates: + account_id = int(candidate.account.id) + if account_id in recent_exchange_ids: + diagnostics.append( + { + "accountId": account_id, + "accountName": candidate.account.nickname + or candidate.account.username, + "reasons": ["365 天内已有该商品兑换事件"], + "source": "capability", + } + ) + continue + qualified.append( + ( + candidate, + _cached_capability_state( + candidate, + commodity_id=task.commodity_id, + ), + ) + ) + + qualified.sort( + key=lambda item: ( + item[1].readiness_rank(required_points=required_points), + int(item[1].points or 0), + int(item[0].account.id), + ) + ) + selected: CapabilityCandidate | None = None + selected_state: DouyuLiveAccountState | None = None + lease = None + lease_duration_minutes = _lease_duration_minutes(db) + for candidate, cached_state in qualified: + account = candidate.account + candidate_model = AccountCandidate( + account_id=int(account.id), + username=str(account.username or ""), + nickname=str(account.nickname or ""), + points=int(cached_state.points or 0), + gold_balance=account.gold_balance, + points_expire_at=account.points_expire_at, + role_change_available_at=account.role_change_available_at, + ) + lease = lease_account( + db, + candidate=candidate_model, + holder_user_id=current.id, + task_id=task.id, + commodity_id=task.commodity_id, + ttl_minutes=lease_duration_minutes, + commit=False, + ) + if lease is not None: + selected = candidate + selected_state = cached_state + break + diagnostics.append( + { + "accountId": int(account.id), + "accountName": cached_state.account_name, + "reasons": ["账号刚被其他任务占用"], + "source": "capability", + } + ) + + if selected is None or selected_state is None or lease is None: + availability_counts = _capability_availability_counts( + db, + commodity_id=task.commodity_id, + scope=task.scope or SCOPE_ELITE, + now=moment, + ) + retry_at, retry_reason = _local_allocation_retry_at( + db, + task=task, + now=moment, + availability_counts=availability_counts, + lease_conflict=bool(qualified), + ) + refresh_queued = ( + _seed_capability_refresh(db, task=task, now=moment) + if retry_reason + in { + "capability_cache_miss", + "account_role_cooldown", + "account_pool_busy", + } + else 0 + ) + if retry_reason == "commodity_not_open": + task.issue_code = "commodity_not_open" + task.last_error = "该商品尚未到开放时间,已按开放时间安排重新选号" + elif retry_reason == "capability_cache_miss": + task.issue_code = "capability_cache_miss" + task.last_error = "暂无该商品的新鲜账号兑换资格,等待后台刷新" + elif retry_reason == "lease_conflict": + task.issue_code = "account_lease_conflict" + task.last_error = "已找到候选账号,但刚被其他任务占用" + elif retry_reason == "account_role_cooldown": + task.issue_code = "account_role_cooldown" + task.last_error = ( + "已有具备兑换资格的账号,但都处于斗鱼换绑冷却期;" + "后台正在继续补充未绑定角色的可用账号" + ) + elif retry_reason == "account_pool_busy": + task.issue_code = "account_pool_busy" + task.last_error = ( + "已有具备兑换资格的账号,但当前被租约或外部协作单占用;" + "后台正在继续补充可用账号" + ) + else: + task.issue_code = "no_eligible_account" + task.last_error = "本地能力池暂无可用账号" + task.execution_status = "ready" + task.next_allocate_at = retry_at + task.updated_at = moment + _append_event( + db, + task.id, + "account_allocation_failed", + detail={ + "candidateCount": len(capability_candidates), + "matchingMode": "capability", + "strategy": "local_capability", + "capabilityCandidates": len(capability_candidates), + "availabilityCounts": availability_counts, + "retryAt": _jsonable(retry_at), + "retryReason": retry_reason, + "refreshQueued": refresh_queued, + "diagnostics": diagnostics[:20], + }, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) + + selected_account = selected.account + task.account_id = selected_account.id + task.lease_id = lease.id + task.operator_id = current.id + task.execution_status = "allocated" + task.next_allocate_at = None + task.binding_status = "not_started" + soft_reasons = selected_state.soft_requirement_reasons( + required_points=required_points + ) + gate_status, gate_issue, gate_message = _exchange_gate( + selected_state, + task.commodity_id, + allow_not_open=is_presale, + ) + if gate_status: + task.exchange_status = gate_status + task.issue_code = gate_issue + task.last_error = gate_message + elif selected_state.elite_opened is not True: + task.exchange_status = "not_opened" + task.issue_code = "elite_not_opened" + task.last_error = "账号尚未开通精英宝典,可开通后继续" + elif selected_state.points is None or selected_state.points < required_points: + task.exchange_status = "points_short" + task.issue_code = "points_short" + task.last_error = "账号积分不足,可充值后继续" + else: + task.exchange_status = "eligible" + task.issue_code = "" + task.last_error = "" + task.updated_at = moment + _apply_task_lease_policy(db, task, lease=lease) + _append_event( + db, + task.id, + "account_allocated", + actor_type="user", + actor_id=current.id, + detail={ + "accountId": selected_account.id, + "accountName": selected_state.account_name, + "points": selected_state.points, + "eliteOpened": selected_state.elite_opened, + "softReasons": soft_reasons, + "exchangeStatus": task.exchange_status, + "allocationStrategy": "local_capability", + "capabilityObservedAt": _jsonable(selected.state.observed_at), + "capabilityValidUntil": _jsonable(selected.state.valid_until), + }, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) + + +def prepare_manual_allocation( + db: Session, + *, + task_id: int, + current: User, +) -> dict[str, Any]: + """在短请求内完成人工选号校验,并把任务标记为立即可领取。 + + 真正的官网账号检测由后台 auto allocator 执行。这样 API 请求不会在多次外部 + HTTP 调用期间一直持有数据库事务,也不会因为重复点击占满连接池。 + """ + task = _load_task(db, task_id) + if task.execution_status in {"completed", "cancelled"}: + raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号") + if not task.commodity_id or not task.required_points: + raise HTTPException(status_code=409, detail="请先完成商品映射") + if task.account_id and task.lease_id: + lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if lease and lease.status == "active": + return get_task_detail(db, task.id) + if task.execution_status != "ready": + raise HTTPException(status_code=409, detail="只有待分配任务可以重新选号") + task.next_allocate_at = _now() + task.updated_at = _now() + db.flush() + return get_task_detail(db, task.id) + + +def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]: + task = _load_task(db, task_id) + if task.execution_status in {"completed", "cancelled"}: + raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号") + if not task.commodity_id or not task.required_points: + raise HTTPException(status_code=409, detail="请先完成商品映射") + if task.account_id and task.lease_id: + lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if lease and lease.status == "active": + return get_task_detail(db, task.id) + # 阶段 5:生产选号只允许读取本地能力索引。官网查询由 + # account_sync_queue/商品能力补货完成,绑码与兑换前各自实时复核。 + return _allocate_task_from_capability( + db, + task=task, + current=current, + ) diff --git a/web/backend/services/platform_fulfillment/binding.py b/web/backend/services/platform_fulfillment/binding.py new file mode 100644 index 0000000..077b2fc --- /dev/null +++ b/web/backend/services/platform_fulfillment/binding.py @@ -0,0 +1,390 @@ +"""游戏角色绑定启动、确认与刷新。""" + +from __future__ import annotations + +import uuid +from typing import Any + +from fastapi import HTTPException +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import Session +from starlette.concurrency import run_in_threadpool + +from ...models import ( + Account, + AccountLease, + DouyuTask, + PlatformFulfillmentTask, + User, +) +from ..account_binding import ( + pending_binding_role_from_result, +) +from ..business_events import record_douyu_task_started +from ..douyu_batch_launcher import start_douyu_batch +from .binding_status import ( + _binding_failure_issue, + _binding_failure_raw_message, + _customer_task_message, +) +from .common import _now +from .outbox import _emit_order_site_binding_state +from .repository import ( + _binding_qr_expired, + _load_task, + _load_task_for_update, +) +from .runtime import ( + _append_event, + _apply_task_lease_policy, +) +from .views import get_task_detail + + +def start_binding_sync( + db: Session, + *, + task_id: int, + current: User, + force_refresh: bool = False, +) -> dict[str, Any]: + task = _load_task_for_update(db, task_id) + if not task.account_id or not task.lease_id: + raise HTTPException(status_code=409, detail="请先分配账号") + lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if lease is None or lease.status != "active": + raise HTTPException(status_code=409, detail="账号租约已失效,请重新分配") + if task.bind_task_id: + existing = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() + if existing: + result = existing.result or {} + pending_role = pending_binding_role_from_result(result) + stale_pending = ( + bool(result.get("bind_ready_for_confirm")) and not pending_role + ) + if bool(result.get("bind_confirmed")) or pending_role: + return get_task_detail(db, task.id) + if existing.status in {"planned", "pending", "running"}: + return get_task_detail(db, task.id) + if ( + existing.status == "success" + and not _binding_qr_expired(existing) + and not stale_pending + ): + return get_task_detail(db, task.id) + if not force_refresh and existing.status not in { + "success", + "failed", + "error", + "stopped", + }: + return get_task_detail(db, task.id) + + batch_id = f"pfbind-{task.id}-{uuid.uuid4().hex[:8]}" + bind_task = DouyuTask( + batch_id=batch_id, + account_id=task.account_id, + account_assigned_to=current.id, + task_type="get_bind_qr", + handbook_scope="elite", + status="planned", + message="等待生成绑定二维码", + result={"payload": {}}, + created_by=current.id, + platform_task_id=task.id, + ) + db.add(bind_task) + try: + db.flush() + except IntegrityError: + # The database uniqueness gate wins a race that started before either + # request could acquire the fulfillment row lock. + db.rollback() + return get_task_detail(db, task_id) + account = db.query(Account).filter(Account.id == task.account_id).first() + if account is not None: + record_douyu_task_started( + db, + account, + task_id=int(bind_task.id), + task_type="get_bind_qr", + task_label="获取绑定二维码", + scope="elite", + actor_id=current.id, + ) + task.bind_task_id = bind_task.id + task.binding_status = "preparing" + task.execution_status = "waiting_bind" + task.issue_code = "" + task.last_error = "" + task.operator_id = current.id + task.updated_at = _now() + _apply_task_lease_policy(db, task, lease=lease) + _append_event( + db, + task.id, + "binding_started", + actor_type="user", + actor_id=current.id, + detail={"bindTaskId": bind_task.id}, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + start_douyu_batch( + batch_id=batch_id, + task_type="get_bind_qr", + payload={}, + concurrency=1, + capture_event_loop=False, + ) + return get_task_detail(db, task.id) + + +async def start_binding( + db: Session, + *, + task_id: int, + current: User, + force_refresh: bool = False, +) -> dict[str, Any]: + """Run the blocking DB/network dispatch path outside the ASGI event loop.""" + return await run_in_threadpool( + start_binding_sync, + db, + task_id=task_id, + current=current, + force_refresh=force_refresh, + ) + + +def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: + task = _load_task(db, task_id) + if task.execution_status in {"completed", "cancelled"}: + return get_task_detail(db, task.id) + if not task.bind_task_id: + return get_task_detail(db, task.id) + bind_task = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() + if bind_task is None: + return get_task_detail(db, task.id) + before = ( + task.binding_status, + task.execution_status, + task.exchange_status, + task.issue_code, + task.last_error, + ) + result = bind_task.result or {} + pending_role = pending_binding_role_from_result(result) + if bind_task.status in {"failed", "error", "stopped"}: + task.binding_status = "failed" + task.execution_status = "manual_required" + task.issue_code = _binding_failure_issue(bind_task, result) + task.last_error = _customer_task_message(task) + elif bool(result.get("bind_confirmed")): + task.binding_status = "bound" + task.execution_status = "bound" + task.issue_code = "" + task.last_error = "" + elif pending_role: + task.binding_status = "role_ready" + task.execution_status = "role_ready" + task.issue_code = "" + task.last_error = "" + elif bool(result.get("bind_ready_for_confirm")): + # 兼容旧快照:同名旧角色曾被误标为待确认。清掉绑定指针后,客户页会 + # 回到已分配状态,并在下一次刷新时自动生成新二维码、重新开始轮询。 + previous_bind_task_id = task.bind_task_id + task.bind_task_id = None + task.binding_status = "not_started" + task.execution_status = "allocated" + task.issue_code = "" + task.last_error = "" + task.updated_at = _now() + _append_event( + db, + task.id, + "binding_stale_role_ignored", + detail={ + "bindTaskId": previous_bind_task_id, + "roleName": str(result.get("role_name") or "")[:100], + "baselineRoleName": str( + result.get("baseline_role_name") + or result.get("current_role_name") + or "" + )[:100], + }, + ) + _emit_order_site_binding_state(db, task.id) + _apply_task_lease_policy(db, task) + db.commit() + return get_task_detail(db, task.id) + elif result.get("url"): + task.binding_status = "qr_pending" + task.execution_status = "waiting_bind" + task.issue_code = "" + task.last_error = "" + after = ( + task.binding_status, + task.execution_status, + task.exchange_status, + task.issue_code, + task.last_error, + ) + if after != before: + task.updated_at = _now() + if task.binding_status == "failed": + _append_event( + db, + task.id, + "binding_failed", + detail={ + "issueCode": task.issue_code, + "bindTaskId": bind_task.id, + "bindPhase": str(result.get("bind_phase") or ""), + "rawError": _binding_failure_raw_message( + task.issue_code, + result, + fallback=str(bind_task.message or ""), + )[:1000], + }, + ) + _emit_order_site_binding_state(db, task.id) + _apply_task_lease_policy(db, task) + db.commit() + return get_task_detail(db, task.id) + + +def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int: + """斗鱼绑定任务落库后,把关联履约任务和 Outbox 一并刷新。""" + task_ids = [ + int(row.id) + for row in ( + db.query(PlatformFulfillmentTask.id) + .filter(PlatformFulfillmentTask.bind_task_id == int(douyu_task_id)) + .all() + ) + ] + for task_id in task_ids: + refresh_binding(db, task_id=task_id) + return len(task_ids) + + +def reconcile_binding_state_outbox( + db: Session, + *, + limit: int = 500, + after_task_id: int = 0, +) -> dict[str, Any]: + """按 ID 游标补齐 active 快照;批次只限制吞吐,不形成永久扫描窗口。""" + batch_size = max(1, min(limit, 500)) + normalized_after = max(0, int(after_task_id or 0)) + task_ids = [ + int(row.id) + for row in ( + db.query(PlatformFulfillmentTask.id) + .filter( + PlatformFulfillmentTask.id > normalized_after, + PlatformFulfillmentTask.execution_status.notin_( + ["completed", "cancelled"] + ), + ) + .order_by(PlatformFulfillmentTask.id.asc()) + .limit(batch_size) + .all() + ) + ] + queued = sum( + 1 for task_id in task_ids if _emit_order_site_binding_state(db, task_id) + ) + db.commit() + return { + "queued": queued, + "nextTaskId": max(task_ids, default=normalized_after), + "hasMore": len(task_ids) == batch_size, + } + + +def confirm_binding_sync(db: Session, *, task_id: int, current: User) -> dict[str, Any]: + task = _load_task_for_update(db, task_id) + task = _load_task(db, refresh_binding(db, task_id=task.id)["task"]["id"]) + if task.binding_status != "role_ready": + raise HTTPException(status_code=409, detail="当前没有待确认的游戏角色") + if not task.account_id or not task.lease_id: + raise HTTPException(status_code=409, detail="账号租约不存在") + lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if lease is None or lease.status != "active": + raise HTTPException(status_code=409, detail="账号租约已失效") + + current_bind_task = ( + db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() + if task.bind_task_id + else None + ) + current_bind_result = (current_bind_task.result or {}) if current_bind_task else {} + expected_role_name = str(current_bind_result.get("role_name") or "").strip() + baseline_role_name = str(current_bind_result.get("current_role_name") or "").strip() + batch_id = f"pfconfirm-{task.id}-{uuid.uuid4().hex[:8]}" + confirm_task = DouyuTask( + batch_id=batch_id, + account_id=task.account_id, + account_assigned_to=current.id, + task_type="confirm_bind", + handbook_scope="elite", + status="planned", + message="等待确认角色绑定", + result={ + "payload": {}, + "expected_role_name": expected_role_name, + "baseline_role_name": baseline_role_name, + }, + created_by=current.id, + platform_task_id=task.id, + ) + db.add(confirm_task) + db.flush() + account = db.query(Account).filter(Account.id == task.account_id).first() + if account is not None: + record_douyu_task_started( + db, + account, + task_id=int(confirm_task.id), + task_type="confirm_bind", + task_label="确认绑定", + scope="elite", + actor_id=current.id, + ) + task.bind_task_id = confirm_task.id + task.binding_status = "confirming" + task.execution_status = "binding_confirming" + task.operator_id = current.id + task.updated_at = _now() + _apply_task_lease_policy(db, task, lease=lease) + _append_event( + db, + task.id, + "binding_confirm_started", + actor_type="user", + actor_id=current.id, + detail={"confirmTaskId": confirm_task.id}, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + start_douyu_batch( + batch_id=batch_id, + task_type="confirm_bind", + payload={}, + concurrency=1, + capture_event_loop=False, + ) + return get_task_detail(db, task.id) + + +async def confirm_binding( + db: Session, *, task_id: int, current: User +) -> dict[str, Any]: + return await run_in_threadpool( + confirm_binding_sync, + db, + task_id=task_id, + current=current, + ) diff --git a/web/backend/services/platform_fulfillment/binding_status.py b/web/backend/services/platform_fulfillment/binding_status.py new file mode 100644 index 0000000..6420274 --- /dev/null +++ b/web/backend/services/platform_fulfillment/binding_status.py @@ -0,0 +1,184 @@ +"""绑定失败分类、客户提示与历史事件展示修正。""" + +from __future__ import annotations + +from typing import Any + +from ...models import ( + DouyuTask, + PlatformFulfillmentEvent, + PlatformFulfillmentTask, +) +from ..account_binding import ( + classify_bind_cooldown, + is_platform_account_bind_cooldown, +) +from .common import BINDING_COOLDOWN_ISSUES + + +def _customer_task_message_for(issue_code: str) -> str: + messages = { + "mapping_missing": "商品正在准备中,请稍后重试", + "no_eligible_account": "正在准备可用账号,请稍后重试", + "elite_not_opened": "账号正在准备精英宝典,请稍后重试", + "points_short": "账号正在补充积分,请稍后重试", + "commodity_limit_reached": "当前商品暂时无法兑换,请联系客服", + "binding_failed": "暂未识别到绑定角色,请继续使用当前二维码完成扫码", + "account_role_cooldown": "当前斗鱼账号未到换绑时间,请截图本页面并联系客服处理", + "customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理", + "eligibility_check_failed": "状态查询异常,请稍后刷新", + "manual_required": "当前需要人工处理,请联系客服", + } + return messages.get(issue_code, "") if issue_code else "" + + +def _customer_task_message(task: PlatformFulfillmentTask) -> str: + return _customer_task_message_for(task.issue_code) + + +def _binding_failure_raw_message( + issue_code: str, + result: dict[str, Any], + *, + fallback: str = "", +) -> str: + before_bound = result.get("before_bound_snapshot") + before_bound_role = ( + str(before_bound.get("role_name") or "") + if isinstance(before_bound, dict) + else "" + ) + role_name = str(result.get("role_name") or "") + if issue_code == "account_role_cooldown": + role_label = before_bound_role or role_name or "当前角色" + return ( + f"斗鱼账号当前绑定角色({role_label})未到可换绑时间" + ",请更换斗鱼账号或稍后重试" + ) + if issue_code == "customer_role_cooldown": + return ( + f"待绑定游戏账号({role_name or '-'})未到换绑时间" + "(不是斗鱼/虎牙账号),请重新换账号扫码绑定" + ) + return fallback + + +def _binding_failure_issue(bind_task: DouyuTask, result: dict[str, Any]) -> str: + phase = str(result.get("bind_phase") or "") + message = str(bind_task.message or "") + confirm_error = str(result.get("confirm_error") or "") + confirm_code = result.get("confirm_error_code") + # 原始接口文案是分类的第一事实源。历史任务可能已经写入了错误的 + # derived issue_code,不能在刷新时继续让错误派生值覆盖原始响应。 + cooldown_kind = classify_bind_cooldown(None, confirm_error) + if cooldown_kind is None: + cooldown_kind = classify_bind_cooldown(None, message) + if cooldown_kind == "platform": + return "account_role_cooldown" + if cooldown_kind == "customer": + return "customer_role_cooldown" + explicit_issue = str(result.get("issue_code") or "") + if explicit_issue in BINDING_COOLDOWN_ISSUES: + return explicit_issue + ambiguous_kind = classify_bind_cooldown( + confirm_code, + f"{confirm_error} {message}", + ) + if ambiguous_kind == "platform": + return "account_role_cooldown" + if ambiguous_kind == "customer": + return "customer_role_cooldown" + if ( + phase == "change_waiting" + or is_platform_account_bind_cooldown( + confirm_code, + f"{message} {confirm_error}", + ) + or "暂不能换绑" in message + ): + task_issue = "account_role_cooldown" + elif ( + phase == "confirm_failed" + or "待绑定游戏账号" in message + or "未到换绑时间" in message + ): + task_issue = "customer_role_cooldown" + else: + return "binding_failed" + messages = { + "account_role_cooldown": "当前斗鱼账号未到换绑时间,请截图本页面并联系客服处理", + "customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理", + } + return task_issue if messages.get(task_issue) else "binding_failed" + + +def _effective_binding_issue( + task: PlatformFulfillmentTask, + bind_task: DouyuTask | None, + result: dict[str, Any], +) -> str: + if ( + task.binding_status == "failed" + and bind_task is not None + and bind_task.status in {"failed", "error", "stopped"} + ): + corrected = _binding_failure_issue(bind_task, result) + if corrected in BINDING_COOLDOWN_ISSUES: + return corrected + return task.issue_code + + +def _effective_task_message( + task: PlatformFulfillmentTask, + issue_code: str, +) -> str: + if issue_code != task.issue_code and issue_code in BINDING_COOLDOWN_ISSUES: + return _customer_task_message_for(issue_code) + return task.last_error + + +def _normalized_event_detail( + event: PlatformFulfillmentEvent, + bind_tasks: dict[int, DouyuTask], +) -> dict[str, Any]: + """只修正派生展示,不篡改 append-only 的原始事件。 + + 历史版本曾把客户角色冷却写成斗鱼账号冷却。事件表保留原值用于审计, + API 返回使用原始 confirm_error 重新计算后的展示字段。 + """ + detail = dict(event.detail_json or {}) + if event.event_type not in { + "douyu_operation_failed", + "douyu_operation_stopped", + "binding_failed", + }: + return detail + raw_id = ( + detail.get("douyuTaskId") + if event.event_type.startswith("douyu_operation_") + else detail.get("bindTaskId") + ) + try: + bind_task_id = int(raw_id) if raw_id is not None else 0 + except (TypeError, ValueError): + bind_task_id = 0 + bind_task = bind_tasks.get(bind_task_id) + if bind_task is None or bind_task.status not in {"failed", "error", "stopped"}: + return detail + result = bind_task.result or {} + issue_code = _binding_failure_issue(bind_task, result) + if issue_code not in BINDING_COOLDOWN_ISSUES: + return detail + corrected_message = _binding_failure_raw_message( + issue_code, + result, + fallback=str( + detail.get("rawError") or detail.get("message") or bind_task.message or "" + ), + ) + detail["issueCode"] = issue_code + if event.event_type == "binding_failed": + detail["rawError"] = corrected_message + else: + detail["message"] = corrected_message + return detail diff --git a/web/backend/services/platform_fulfillment/common.py b/web/backend/services/platform_fulfillment/common.py new file mode 100644 index 0000000..5dc365d --- /dev/null +++ b/web/backend/services/platform_fulfillment/common.py @@ -0,0 +1,157 @@ +"""共享常量、快照解析与订单匹配基础函数。""" + +from __future__ import annotations + +import os +from datetime import UTC, datetime +from typing import Any + +from sqlalchemy.orm import Session + +from ...models import ( + PlatformCommodityMapping, + PlatformFulfillmentSetting, + PlatformFulfillmentTask, +) +from ..account_capability_service import ( + AVAILABILITY_AVAILABLE, + exchange_gate_for_availability, +) +from ..douyu_account_state import DouyuLiveAccountState + +TARGET_PLATFORM = "douyu" +SCOPE_ELITE = "elite" +BINDING_COOLDOWN_ISSUES = frozenset({"account_role_cooldown", "customer_role_cooldown"}) +ACTIVE_STATUSES = { + "ready", + "allocated", + "waiting_bind", + "role_ready", + "binding_confirming", + "bound", + "manual_required", +} + +BINDING_QR_TTL_SECONDS = int(os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "1260")) +AUTO_SYNC_INTERVAL_SECONDS = 900.0 +DEFAULT_CAPABILITY_CANDIDATE_LIMIT = 20 +LOCAL_STOCK_RETRY_SECONDS = 5 * 60 +LOCAL_CACHE_MISS_RETRY_SECONDS = 2 * 60 +LOCAL_LEASE_CONFLICT_RETRY_SECONDS = 5 +DEFAULT_BINDING_FAILED_LEASE_TTL_MINUTES = 120 + + +def binding_failed_lease_ttl_minutes() -> int: + """扫码超时任务的账号保留时间;过期后允许重新进入选号池。""" + try: + value = int( + os.getenv( + "PLATFORM_BINDING_FAILED_LEASE_TTL_MINUTES", + str(DEFAULT_BINDING_FAILED_LEASE_TTL_MINUTES), + ) + ) + except ValueError: + return DEFAULT_BINDING_FAILED_LEASE_TTL_MINUTES + return max(1, value) + + +def _exchange_gate( + state: DouyuLiveAccountState, + commodity_id: str, + *, + allow_not_open: bool = False, +) -> tuple[str, str, str]: + """把实时商品资格映射为履约可展示的硬门槛。""" + limited = commodity_id in state.limited_ids + if not state.commodity_availability: + return ( + exchange_gate_for_availability( + AVAILABILITY_AVAILABLE, + limited=limited, + ) + if limited + else ("", "", "") + ) + availability = state.commodity_availability.get(commodity_id) + reason = state.commodity_blocking_reasons.get(commodity_id, "") + return exchange_gate_for_availability( + availability, + reason=reason, + limited=limited, + allow_not_open=allow_not_open, + ) + + +def _now() -> datetime: + return datetime.now(UTC) + + +def _jsonable(value: Any) -> Any: + if isinstance(value, datetime): + return value.isoformat() + if isinstance(value, dict): + return {str(key): _jsonable(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_jsonable(item) for item in value] + if isinstance(value, (str, int, float, bool)) or value is None: + return value + return str(value) + + +def _mapping_for_sku( + db: Session, internal_sku_key: str +) -> PlatformCommodityMapping | None: + return ( + db.query(PlatformCommodityMapping) + .filter( + PlatformCommodityMapping.target_platform == TARGET_PLATFORM, + PlatformCommodityMapping.internal_sku_key == internal_sku_key, + PlatformCommodityMapping.enabled.is_(True), + PlatformCommodityMapping.archived_at.is_(None), + ) + .order_by(PlatformCommodityMapping.updated_at.desc()) + .first() + ) + + +def _parse_snapshot_datetime(value: Any) -> datetime | None: + if isinstance(value, datetime): + return value if value.tzinfo is not None else value.replace(tzinfo=UTC) + text = str(value or "").strip() + if not text: + return None + try: + parsed = datetime.fromisoformat(text) + except ValueError: + return None + return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC) + + +def _snapshot_value(data: dict[str, Any], *names: str, default: Any = "") -> Any: + for name in names: + if name in data and data[name] is not None: + return data[name] + return default + + +def _order_snapshot_from_event(payload: dict[str, Any]) -> dict[str, Any]: + data = payload.get("data") + return data if isinstance(data, dict) else payload + + +def _order_match_started_at(db: Session) -> datetime | None: + row = ( + db.query(PlatformFulfillmentSetting) + .filter(PlatformFulfillmentSetting.id == 1) + .first() + ) + return row.order_match_started_at if row is not None else None + + +def _apply_order_match_cutoff( + query, + match_started_at: datetime | None, +): + if match_started_at is None: + return query + return query.filter(PlatformFulfillmentTask.paid_at >= match_started_at) diff --git a/web/backend/services/platform_fulfillment/customer.py b/web/backend/services/platform_fulfillment/customer.py new file mode 100644 index 0000000..352cda5 --- /dev/null +++ b/web/backend/services/platform_fulfillment/customer.py @@ -0,0 +1,130 @@ +"""外部客户会话与绑定接口编排。""" + +from __future__ import annotations + +from typing import Any + +from fastapi import HTTPException +from sqlalchemy.orm import Session + +from ...models import ( + AccountLease, + PlatformFulfillmentTask, +) +from .binding import ( + confirm_binding, + refresh_binding, + start_binding, +) +from .order_sync import sync_order_item_ids +from .repository import ( + _find_customer_task, + _integration_actor, + _load_task, +) +from .views import customer_binding_out + + +def ensure_customer_session( + db: Session, + *, + source_order_item_id: str, + platform_order_id: str = "", +) -> dict[str, Any]: + """按订单项幂等准备客户绑定会话;必要时同步订单并自动分配账号。""" + task = _find_customer_task( + db, + source_order_item_id=source_order_item_id, + platform_order_id=platform_order_id, + ) + if task is None: + sync_order_item_ids( + db, + [source_order_item_id], + commit=True, + ) + task = _find_customer_task( + db, + source_order_item_id=source_order_item_id, + platform_order_id=platform_order_id, + ) + if task is None: + raise HTTPException(status_code=404, detail="订单尚未进入直播账号履约队列") + if task.execution_status in {"completed", "cancelled"}: + return customer_binding_out(db, task.id) + if task.execution_status in {"pending_mapping", "ready", "manual_required"}: + if task.issue_code == "mapping_missing": + return customer_binding_out(db, task.id) + from .auto_allocator import wake_auto_allocator + + wake_auto_allocator([int(task.id)]) + return customer_binding_out(db, task.id) + + +async def customer_start_binding( + db: Session, + *, + task_id: int, + force_refresh: bool = False, +) -> dict[str, Any]: + task = _load_task(db, task_id) + if task.execution_status in {"completed", "cancelled"}: + return customer_binding_out(db, task.id) + if task.issue_code == "mapping_missing": + return customer_binding_out(db, task.id) + + if not task.account_id or not task.lease_id: + from .auto_allocator import wake_auto_allocator + + wake_auto_allocator([int(task.id)]) + payload = customer_binding_out(db, task.id) + payload["accepted"] = True + payload["queueState"] = "allocation_queued" + payload["retryAfterMs"] = 2000 + return payload + + lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if lease is None or lease.status != "active": + return customer_binding_out(db, task.id) + + previous_bind_task_id = task.bind_task_id + actor = _integration_actor(db) + await start_binding( + db, + task_id=task.id, + current=actor, + force_refresh=force_refresh, + ) + payload = customer_binding_out(db, task.id) + accepted = task.bind_task_id != previous_bind_task_id + payload["accepted"] = accepted + if accepted: + payload["queueState"] = "qr_queued" + payload["retryAfterMs"] = 1000 + return payload + + +def customer_refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: + refresh_binding(db, task_id=task_id) + return customer_binding_out(db, task_id) + + +def customer_refresh_bindings(db: Session, *, task_ids: list[int]) -> dict[str, Any]: + items: list[dict[str, Any]] = [] + for task_id in dict.fromkeys(task_ids): + task = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id == task_id) + .first() + ) + if task is None: + continue + refresh_binding(db, task_id=task.id) + items.append(customer_binding_out(db, task.id)) + return {"items": items} + + +async def customer_confirm_binding(db: Session, *, task_id: int) -> dict[str, Any]: + refresh_binding(db, task_id=task_id) + await confirm_binding(db, task_id=task_id, current=_integration_actor(db)) + return customer_binding_out(db, task_id) diff --git a/web/backend/services/platform_fulfillment/lifecycle.py b/web/backend/services/platform_fulfillment/lifecycle.py new file mode 100644 index 0000000..1b81cc4 --- /dev/null +++ b/web/backend/services/platform_fulfillment/lifecycle.py @@ -0,0 +1,760 @@ +"""兑换、人工处理、释放、取消和恢复等生命周期操作。""" + +from __future__ import annotations + +from typing import Any + +from fastapi import HTTPException +from sqlalchemy.orm import Session + +from ...models import ( + Account, + AccountLease, + DouyuExternalOrder, + DouyuTask, + PlatformFulfillmentEvent, + PlatformFulfillmentTask, + User, +) +from ..account_capability_service import ( + ACCOUNT_ELIGIBILITY_LIMITED, + ACCOUNT_ELIGIBILITY_UNKNOWN, + AVAILABILITY_AVAILABLE, + AVAILABILITY_LIMITED, + AVAILABILITY_NOT_OFFERED, + OFFER_STATE_NOT_OFFERED, + OFFER_STATE_UNKNOWN, + STOCK_STATE_UNKNOWN, + classify_goods_items, + exchange_gate_for_availability, + record_account_commodity_state, +) +from ..business_events import record_account_query +from ..douyu_account_probe import ( + CAPABILITY_OK, + config_mapping, + persist_probe_result, + probe_account, +) +from ..douyu_batch_launcher import stop_douyu_batches +from ..douyu_service import ( + ensure_douyu_config, +) +from ..external_order_source import ( + OrderLookupUnavailable, + lookup_pending_manual_fulfillment, +) +from . import classification +from .account_selector import ( + release_lease, +) +from .common import ( + SCOPE_ELITE, + _mapping_for_sku, + _now, +) +from .mappings import _apply_mapping +from .outbox import _emit_order_site_binding_state +from .repository import ( + _load_task, + _retain_lease_for_active_collab, +) +from .runtime import ( + _append_event, + _apply_task_lease_policy, +) +from .views import get_task_detail + + +def release_task_account( + db: Session, + *, + task_id: int, + current: User, + reason: str = "manual_release", +) -> dict[str, Any]: + task = _load_task(db, task_id) + lease = ( + db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if task.lease_id + else None + ) + retained = _retain_lease_for_active_collab( + db, + task=task, + lease=lease, + current=current, + reason="platform_released_to_collab", + ) + if retained is None: + release_lease(db, lease, reason=reason, commit=False) + task.account_id = None + task.lease_id = None + task.bind_task_id = None + task.execution_status = "ready" + task.binding_status = "not_started" + task.exchange_status = "not_started" + task.issue_code = "" + task.last_error = "" + task.updated_at = _now() + _append_event( + db, + task.id, + "account_released", + actor_type="user", + actor_id=current.id, + detail={"reason": reason}, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) + + +def reset_task_binding( + db: Session, + *, + task_id: int, + current: User, + reason: str = "客服重置角色绑定", +) -> dict[str, Any]: + """清空本单旧绑定与客户资料,保留账号租约供客户重新扫码。""" + task = _load_task(db, task_id) + if task.execution_status in {"completed", "cancelled"}: + raise HTTPException(status_code=409, detail="已结束任务不能重置绑定") + if task.binding_status != "failed": + raise HTTPException( + status_code=409, detail="只有绑定失败的任务可以重置角色资料" + ) + if not task.account_id or not task.lease_id: + raise HTTPException(status_code=409, detail="当前任务没有可保留的履约账号") + + lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if lease is None or lease.status != "active": + raise HTTPException( + status_code=409, detail="账号租约已失效,请释放账号后重新选号" + ) + + previous_bind_task_id = task.bind_task_id + previous_bind_task = ( + db.query(DouyuTask).filter(DouyuTask.id == previous_bind_task_id).first() + if previous_bind_task_id + else None + ) + if previous_bind_task and previous_bind_task.status in { + "planned", + "pending", + "running", + }: + raise HTTPException(status_code=409, detail="当前绑定任务仍在执行,不能重置") + + previous_binding_status = task.binding_status + previous_issue_code = task.issue_code + task.bind_task_id = None + task.binding_status = "not_started" + task.execution_status = "allocated" + task.exchange_status = "not_started" + task.issue_code = "" + task.last_error = "" + task.operator_id = current.id + task.updated_at = _now() + _apply_task_lease_policy(db, task, lease=lease) + _append_event( + db, + task.id, + "binding_reset", + actor_type="user", + actor_id=current.id, + detail={ + "reason": reason.strip()[:1000], + "previousBindTaskId": previous_bind_task_id, + "previousBindingStatus": previous_binding_status, + "previousIssueCode": previous_issue_code, + "customerProfileReset": True, + }, + ) + _emit_order_site_binding_state( + db, + task.id, + extra={ + "customerProfileReset": True, + "resetReason": reason.strip()[:1000], + }, + ) + db.commit() + return get_task_detail(db, task.id) + + +def refresh_exchange_eligibility( + db: Session, *, task_id: int, current: User +) -> dict[str, Any]: + task = _load_task(db, task_id) + if task.binding_status != "bound": + raise HTTPException(status_code=409, detail="请先确认游戏角色绑定") + account = db.query(Account).filter(Account.id == task.account_id).first() + if account is None or not account.cookie: + raise HTTPException(status_code=409, detail="账号 CK 不可用") + config = ensure_douyu_config(db) + try: + probe = probe_account( + account, + config_mapping(config), + session_checker=None, + with_elite_role=False, + with_eligibility=True, + ) + if (probe.get("elite") or {}).get("status") != CAPABILITY_OK: + raise RuntimeError( + (probe.get("errors") or {}).get("elite") or "精英宝典状态查询失败" + ) + if "points" in (probe.get("errors") or {}): + raise RuntimeError((probe.get("errors") or {})["points"]) + limited_ids = frozenset( + str(item) + for item in (probe.get("eligibility") or {}).get("limited_ids") or [] + if str(item) + ) + persist_probe_result( + db, + account, + probe, + current=current, + source="platform.exchange_eligibility", + record_event=True, + ) + except Exception as exc: # noqa: BLE001 外部接口错误要落成可重试的检查失败 + record_account_query( + db, + account, + query_type="exchange_eligibility", + title="刷新兑换资格", + ok=False, + detail={"error": str(exc)[:1000], "commodity_id": task.commodity_id}, + actor_id=current.id, + ) + task.execution_status = "manual_required" + task.exchange_status = "check_failed" + task.issue_code = "eligibility_check_failed" + task.last_error = str(exc) + task.updated_at = _now() + _append_event( + db, + task.id, + "eligibility_check_failed", + actor_type="user", + actor_id=current.id, + detail={"error": str(exc)}, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) + + eligibility = probe.get("eligibility") or {} + storehome_goods = [ + dict(item) + for item in eligibility.get("storehome_goods") or [] + if isinstance(item, dict) + ] + assessments = classify_goods_items(storehome_goods, now=_now()) + assessment = assessments.get(task.commodity_id) + is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale" + if task.commodity_id in limited_ids: + account_eligibility = ACCOUNT_ELIGIBILITY_LIMITED + offer_state = assessment.offer_state if assessment else OFFER_STATE_UNKNOWN + stock_state = assessment.stock_state if assessment else STOCK_STATE_UNKNOWN + availability = AVAILABILITY_LIMITED + commodity_message = "该账号已达到此商品兑换上限" + elif assessments and assessment is None: + account_eligibility = ACCOUNT_ELIGIBILITY_UNKNOWN + offer_state = OFFER_STATE_NOT_OFFERED + stock_state = STOCK_STATE_UNKNOWN + availability = AVAILABILITY_NOT_OFFERED + commodity_message = "官方商品列表本次未返回该商品,可能已下架" + elif assessment is not None and assessment.availability != AVAILABILITY_AVAILABLE: + account_eligibility = assessment.account_eligibility + offer_state = assessment.offer_state + stock_state = assessment.stock_state + availability = assessment.availability + commodity_message = assessment.blocking_reason + else: + account_eligibility = ( + assessment.account_eligibility + if assessment is not None + else ACCOUNT_ELIGIBILITY_UNKNOWN + ) + offer_state = ( + assessment.offer_state if assessment is not None else OFFER_STATE_UNKNOWN + ) + stock_state = ( + assessment.stock_state if assessment is not None else STOCK_STATE_UNKNOWN + ) + availability = AVAILABILITY_AVAILABLE + commodity_message = "" + + gate_status, gate_issue, gate_message = exchange_gate_for_availability( + availability, + reason=commodity_message, + allow_not_open=is_presale, + ) + if gate_status: + task.exchange_status = gate_status + task.issue_code = gate_issue + task.last_error = gate_message + elif not account.elite_opened: + task.exchange_status = "not_opened" + task.issue_code = "elite_not_opened" + task.last_error = "该账号精英宝典未开通" + elif task.required_points and int(account.points or 0) < int(task.required_points): + task.exchange_status = "points_short" + task.issue_code = "points_short" + task.last_error = "该账号精英积分不足,需人工充值" + else: + task.exchange_status = "eligible" + task.issue_code = "" + task.last_error = "" + record_account_commodity_state( + db, + account, + commodity_id=task.commodity_id, + availability=availability, + account_eligibility=account_eligibility, + offer_state=offer_state, + stock_state=stock_state, + stock_count=assessment.stock_count if assessment is not None else None, + store_status=assessment.store_status if assessment is not None else None, + open_status=assessment.open_status if assessment is not None else None, + blocking_reason=commodity_message, + raw_status=( + assessment.raw_status + if assessment is not None + else "1" + if task.commodity_id in limited_ids + else "0" + ), + observed_at=_now(), + source="eligibility_check", + scope=task.scope or SCOPE_ELITE, + ) + record_account_query( + db, + account, + query_type="exchange_eligibility", + title="刷新兑换资格", + ok=True, + detail={ + "commodity_id": task.commodity_id, + "exchange_status": task.exchange_status, + "limited": task.commodity_id in limited_ids, + "account_eligibility": account_eligibility, + "offer_state": offer_state, + "stock_state": stock_state, + "availability": availability, + "issue_code": task.issue_code, + "points": account.points, + "elite_opened": account.elite_opened, + }, + actor_id=current.id, + ) + # 积分不足、未开通和限兑都不是流程终点:角色已经绑定,账号继续保留, + # 后续充值/开通/解除限兑后刷新资格即可。 + task.execution_status = "bound" + task.updated_at = _now() + account.updated_at = _now() + # waiting_release 的预售任务在这里切回无限租约,普通 bound 也遵循 + # “进行中默认无限”的状态策略。 + _apply_task_lease_policy(db, task) + _append_event( + db, + task.id, + "exchange_eligibility_checked", + actor_type="user", + actor_id=current.id, + detail={ + "exchangeStatus": task.exchange_status, + "limitedCount": len(limited_ids), + }, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) + + +def complete_manual_exchange( + db: Session, + *, + task_id: int, + current: User, + note: str = "", +) -> dict[str, Any]: + task = _load_task(db, task_id) + if task.binding_status != "bound": + raise HTTPException(status_code=409, detail="游戏角色尚未确认绑定") + if task.exchange_status not in {"eligible", "manual_done"}: + raise HTTPException( + status_code=409, + detail="当前兑换资格不是可兑换状态,请先刷新检查结果", + ) + lease = ( + db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if task.lease_id + else None + ) + task.exchange_status = "manual_done" + task.execution_status = "completed" + task.completed_at = _now() + task.operator_id = current.id + task.last_error = "" + task.issue_code = "" + task.updated_at = _now() + retained = _retain_lease_for_active_collab( + db, + task=task, + lease=lease, + current=current, + reason="platform_completed_but_collab_active", + ) + if retained is None: + # 2026-11-22:兑换完成不再一律立即释放。任务已完成但保留一段可配置 + # 的复核窗口;默认人工兑换完成后保留 120 分钟,期间仍可供截图与纠错。 + _apply_task_lease_policy( + db, + task, + lease=lease, + ) + _append_event( + db, + task.id, + "manual_exchange_completed", + actor_type="user", + actor_id=current.id, + detail={"note": note[:1000]}, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) + + +def mark_manual_required( + db: Session, + *, + task_id: int, + current: User, + reason: str, +) -> dict[str, Any]: + task = _load_task(db, task_id) + task.execution_status = "manual_required" + task.operator_id = current.id + task.last_error = reason.strip()[:2000] + task.issue_code = task.issue_code or "manual_required" + task.updated_at = _now() + _apply_task_lease_policy(db, task) + _append_event( + db, + task.id, + "marked_manual_required", + actor_type="user", + actor_id=current.id, + detail={"reason": task.last_error}, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) + + +def cancel_task( + db: Session, + *, + task_id: int, + current: User, + reason: str, +) -> dict[str, Any]: + task = _load_task(db, task_id) + if task.execution_status == "cancelled": + return get_task_detail(db, task.id) + if task.execution_status == "completed": + raise HTTPException(status_code=409, detail="已完成任务不能取消") + account_id = task.account_id + lease_id = task.lease_id + previous_execution_status = task.execution_status + previous_binding_status = task.binding_status + previous_exchange_status = task.exchange_status + lease = ( + db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if task.lease_id + else None + ) + linked_tasks = ( + db.query(DouyuTask) + .filter( + DouyuTask.id.in_( + [value for value in [task.bind_task_id, task.exchange_task_id] if value] + ) + ) + .all() + if task.bind_task_id or task.exchange_task_id + else [] + ) + stopped_batches = stop_douyu_batches( + [str(linked_task.batch_id or "") for linked_task in linked_tasks] + ) + for linked_task in linked_tasks: + if linked_task.status in {"planned", "pending", "running"}: + linked_task.status = "stopped" + linked_task.message = "履约任务已取消" + linked_task.finished_at = _now() + retained = _retain_lease_for_active_collab( + db, + task=task, + lease=lease, + current=current, + reason="platform_cancelled_but_collab_active", + ) + if retained is None: + release_lease( + db, + lease, + reason="platform_fulfillment_cancelled", + commit=False, + ) + task.account_id = None + task.lease_id = None + task.bind_task_id = None + task.exchange_task_id = None + task.binding_status = "not_started" + task.execution_status = "cancelled" + task.exchange_status = "not_started" + task.issue_code = "" + task.operator_id = current.id + task.last_error = reason.strip()[:2000] + task.updated_at = _now() + _append_event( + db, + task.id, + "task_cancelled", + actor_type="user", + actor_id=current.id, + detail={ + "reason": task.last_error, + "previousExecutionStatus": previous_execution_status, + "previousBindingStatus": previous_binding_status, + "previousExchangeStatus": previous_exchange_status, + "releasedAccountId": account_id, + "releasedLeaseId": lease_id, + "stoppedBatches": stopped_batches, + }, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) + + +def restore_cancelled_task( + db: Session, + *, + task_id: int, + current: User, + reason: str, +) -> dict[str, Any]: + """仅恢复人工误取消、且来源订单仍可履约的任务;不复用旧租约。""" + task = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id == int(task_id)) + .with_for_update() + .first() + ) + if task is None: + raise HTTPException(status_code=404, detail="直播账号履约任务不存在") + if task.execution_status != "cancelled": + raise HTTPException(status_code=409, detail="只有已取消任务可以恢复") + if task.issue_code == "source_cancelled": + raise HTTPException(status_code=409, detail="来源订单已取消,不能恢复") + manual_cancel = ( + db.query(PlatformFulfillmentEvent.id) + .filter( + PlatformFulfillmentEvent.task_id == task.id, + PlatformFulfillmentEvent.event_type == "task_cancelled", + PlatformFulfillmentEvent.actor_type == "user", + ) + .first() + ) + if manual_cancel is None: + raise HTTPException(status_code=409, detail="只有人工取消的任务可以恢复") + + try: + source = lookup_pending_manual_fulfillment(task.source_order_item_id) + except OrderLookupUnavailable as exc: + raise HTTPException(status_code=503, detail=f"订单源不可用:{exc}") from exc + if source is None: + raise HTTPException(status_code=409, detail="来源订单不存在或已不可履约") + if ( + str(source.get("order_status") or "") in {"refunded", "cancelled", "closed"} + or str(source.get("pay_status") or "") != "paid" + or str(source.get("fulfillment_issue_code") or "") + in {"user_refund", "platform_cancelled"} + ): + raise HTTPException( + status_code=409, detail="来源订单已退款、关闭或取消,不能恢复" + ) + + restore_reason = reason.strip() + if len(restore_reason) < 2: + raise HTTPException(status_code=400, detail="请填写恢复原因") + + restored_collab = ( + db.query(DouyuExternalOrder) + .filter(DouyuExternalOrder.source_task_id == task.id) + .first() + ) + if restored_collab is not None and ( + restored_collab.status not in {"incomplete", "void"} + or restored_collab.bind_game_role + or restored_collab.home_images + ): + raise HTTPException( + status_code=409, + detail="关联外部协作单已在人工处理,请继续使用外部协作单", + ) + + mapping = _mapping_for_sku(db, task.internal_sku_key) + _apply_mapping(task, mapping) + task.account_id = None + task.lease_id = None + task.bind_task_id = None + task.exchange_task_id = None + task.binding_status = "not_started" + task.exchange_status = "not_started" + task.completed_at = None + task.next_allocate_at = _now() if task.execution_status == "ready" else None + task.operator_id = current.id + task.updated_at = _now() + + restored_collab_status = "" + if restored_collab is not None and restored_collab.status == "void": + restored_collab.status = "incomplete" + restored_collab.void_reason = "" + restored_collab.updated_by = current.id + restored_collab.updated_at = _now() + restored_collab.version = int(restored_collab.version or 0) + 1 + restored_collab_status = restored_collab.status + + _append_event( + db, + task.id, + "task_restored", + actor_type="user", + actor_id=current.id, + detail={ + "reason": restore_reason, + "restoredExecutionStatus": task.execution_status, + "restoredCollabOrderId": ( + int(restored_collab.id) if restored_collab is not None else None + ), + "restoredCollabStatus": restored_collab_status, + }, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) + + +def prepare_platform_task_for_collab_takeover( + db: Session, + *, + task: PlatformFulfillmentTask, + current: User, + collab_order_no: str, +) -> None: + """把平台履约任务转为人工,但不提交事务;由协作单接管流程原子提交。""" + if task.execution_status in {"completed", "cancelled"}: + raise HTTPException(status_code=409, detail="已结束的履约任务不能被协作单接管") + account_id = task.account_id + lease_id = task.lease_id + reason = f"外部协作单 {collab_order_no} 人工接管账号" + task.account_id = None + task.lease_id = None + task.bind_task_id = None + task.exchange_task_id = None + task.execution_status = "manual_required" + task.binding_status = "not_started" + task.exchange_status = "not_started" + task.issue_code = "manual_required" + task.next_allocate_at = None + task.operator_id = current.id + task.last_error = reason + task.updated_at = _now() + _append_event( + db, + task.id, + "collab_takeover", + actor_type="user", + actor_id=current.id, + detail={ + "reason": reason, + "collabOrderNo": collab_order_no, + "releasedAccountId": account_id, + "releasedLeaseId": lease_id, + }, + ) + _emit_order_site_binding_state(db, task.id) + db.flush() + + +def release_task_to_manual( + db: Session, + *, + task_id: int, + current: User, + reason: str, +) -> dict[str, Any]: + """释放履约账号并转人工,不再进入自动选号。""" + task = _load_task(db, task_id) + if task.execution_status in {"completed", "cancelled"}: + raise HTTPException(status_code=409, detail="已结束任务不能转人工") + manual_reason = reason.strip()[:2000] or "以外部单协作人工处理为准" + account_id = task.account_id + lease_id = task.lease_id + lease = ( + db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if task.lease_id + else None + ) + retained = _retain_lease_for_active_collab( + db, + task=task, + lease=lease, + current=current, + reason="platform_release_to_manual", + ) + if retained is None: + release_lease( + db, + lease, + reason="platform_fulfillment_manual", + commit=False, + ) + task.account_id = None + task.lease_id = None + task.bind_task_id = None + task.exchange_task_id = None + task.execution_status = "manual_required" + task.binding_status = "not_started" + task.exchange_status = "not_started" + task.issue_code = "manual_required" + task.next_allocate_at = None + task.operator_id = current.id + task.last_error = manual_reason + task.updated_at = _now() + _append_event( + db, + task.id, + "released_to_manual", + actor_type="user", + actor_id=current.id, + detail={ + "reason": manual_reason, + "releasedAccountId": account_id, + "releasedLeaseId": lease_id, + }, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) diff --git a/web/backend/services/platform_fulfillment/mappings.py b/web/backend/services/platform_fulfillment/mappings.py new file mode 100644 index 0000000..b5fc41a --- /dev/null +++ b/web/backend/services/platform_fulfillment/mappings.py @@ -0,0 +1,548 @@ +"""商品映射管理和映射变更后的任务重放。""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any + +from fastapi import HTTPException +from sqlalchemy import func, or_ +from sqlalchemy.orm import Session + +from ...models import ( + DouyuGoodsSnapshot, + PlatformCommodityMapping, + PlatformFulfillmentTask, + User, +) +from . import classification +from .common import ( + SCOPE_ELITE, + TARGET_PLATFORM, + _apply_order_match_cutoff, + _now, + _order_match_started_at, +) +from .outbox import _emit_order_site_binding_state +from .runtime import _append_event + + +def _apply_mapping( + task: PlatformFulfillmentTask, + mapping: PlatformCommodityMapping | None, + *, + update_execution_status: bool = True, +) -> None: + if mapping is not None: + snapshot_classification = ( + task.execution_status == "pending_mapping" + or task.classification_source in {"", "unknown"} + or task.sale_mode in {"", "unknown"} + ) + task.commodity_mapping_id = mapping.id + task.commodity_id = mapping.commodity_id + task.required_points = mapping.required_points + if snapshot_classification: + task.sale_mode = classification.normalize_sale_mode(mapping.sale_mode) + task.campaign_key = mapping.campaign_key + task.campaign_name = mapping.campaign_name + task.offer_available_from = mapping.available_from + task.offer_available_until = mapping.available_until + task.classification_source = ( + "mapping" if task.sale_mode != "unknown" else "unknown" + ) + else: + task.commodity_mapping_id = None + task.commodity_id = "" + task.required_points = None + task.sale_mode = "unknown" + task.campaign_key = "" + task.campaign_name = "" + task.offer_available_from = None + task.offer_available_until = None + task.classification_source = "unknown" + if not update_execution_status: + return + if mapping is None: + task.execution_status = "pending_mapping" + task.issue_code = "mapping_missing" + task.last_error = "内部 SKU 尚未配置斗鱼商品映射" + return + task.execution_status = "ready" + task.issue_code = "" + task.last_error = "" + + +def _mapping_impact(db: Session, row: PlatformCommodityMapping) -> int: + query = db.query(func.count(PlatformFulfillmentTask.id)).filter( + PlatformFulfillmentTask.internal_sku_key == row.internal_sku_key, + PlatformFulfillmentTask.account_id.is_(None), + PlatformFulfillmentTask.execution_status.in_( + ["pending_mapping", "ready", "manual_required"] + ), + ) + return int(query.scalar() or 0) + + +def _mapping_out( + db: Session, + row: PlatformCommodityMapping, + *, + now: datetime | None = None, +) -> dict[str, Any]: + mode = classification.normalize_sale_mode(row.sale_mode) + availability = classification.availability_state( + sale_mode=mode, + available_from=row.available_from, + available_until=row.available_until, + goods_status=row.goods_status, + now=now, + ) + return { + "id": row.id, + "targetPlatform": row.target_platform, + "internalSkuKey": row.internal_sku_key, + "campaignKey": row.campaign_key, + "campaignName": row.campaign_name, + "commodityId": row.commodity_id, + "goodsName": row.goods_name, + "requiredPoints": row.required_points, + "scope": row.scope, + "saleMode": mode, + "availableFrom": row.available_from, + "availableUntil": row.available_until, + "releasedAt": row.released_at, + "goodsStatus": row.goods_status, + "availabilityState": availability, + "enabled": row.enabled, + "version": row.version, + "archivedAt": row.archived_at, + "affectedTasks": _mapping_impact(db, row), + "updatedAt": row.updated_at, + } + + +def list_mappings( + db: Session, + *, + keyword: str = "", + sale_mode: str = "", + enabled: bool | None = None, + include_archived: bool = False, +) -> list[dict[str, Any]]: + query = db.query(PlatformCommodityMapping).filter( + PlatformCommodityMapping.target_platform == TARGET_PLATFORM + ) + if not include_archived: + query = query.filter(PlatformCommodityMapping.archived_at.is_(None)) + if enabled is not None: + query = query.filter(PlatformCommodityMapping.enabled.is_(enabled)) + if sale_mode: + query = query.filter( + PlatformCommodityMapping.sale_mode + == classification.normalize_sale_mode(sale_mode) + ) + text = keyword.strip() + if text: + pattern = f"%{text}%" + query = query.filter( + or_( + PlatformCommodityMapping.internal_sku_key.ilike(pattern), + PlatformCommodityMapping.commodity_id.ilike(pattern), + PlatformCommodityMapping.goods_name.ilike(pattern), + PlatformCommodityMapping.campaign_key.ilike(pattern), + PlatformCommodityMapping.campaign_name.ilike(pattern), + ) + ) + rows = ( + query.order_by( + PlatformCommodityMapping.archived_at.asc(), + PlatformCommodityMapping.enabled.desc(), + PlatformCommodityMapping.updated_at.desc(), + ) + .limit(500) + .all() + ) + now = datetime.now(UTC) + return [_mapping_out(db, row, now=now) for row in rows] + + +def _validate_mapping_window( + available_from: datetime | None, + available_until: datetime | None, +) -> None: + if ( + available_from is not None + and available_until is not None + and available_from >= available_until + ): + raise HTTPException(status_code=400, detail="商品开放时间必须早于结束时间") + + +def _disable_other_current_mappings( + db: Session, + *, + row: PlatformCommodityMapping, +) -> None: + others = ( + db.query(PlatformCommodityMapping) + .filter( + PlatformCommodityMapping.id != row.id, + PlatformCommodityMapping.target_platform == row.target_platform, + PlatformCommodityMapping.internal_sku_key == row.internal_sku_key, + PlatformCommodityMapping.enabled.is_(True), + PlatformCommodityMapping.archived_at.is_(None), + ) + .all() + ) + for other in others: + other.enabled = False + other.version = int(other.version or 1) + 1 + other.updated_at = _now() + + +def _reapply_mapping_tasks( + db: Session, + *, + row: PlatformCommodityMapping, + current: User, +) -> None: + pending = db.query(PlatformFulfillmentTask).filter( + PlatformFulfillmentTask.internal_sku_key == row.internal_sku_key, + PlatformFulfillmentTask.account_id.is_(None), + PlatformFulfillmentTask.execution_status.in_( + ["pending_mapping", "ready", "manual_required"] + ), + ) + pending = _apply_order_match_cutoff(pending, _order_match_started_at(db)) + task_ids: list[int] = [] + for task in pending.all(): + _apply_mapping(task, row if row.enabled else None) + task.updated_at = _now() + task.next_allocate_at = ( + _now() + if task.execution_status == "ready" and task.account_id is None + else None + ) + _append_event( + db, + task.id, + "mapping_updated", + actor_type="user", + actor_id=current.id, + detail={ + "mappingId": row.id, + "commodityId": row.commodity_id, + "goodsName": row.goods_name, + "saleMode": row.sale_mode, + "campaignKey": row.campaign_key, + "enabled": row.enabled, + }, + ) + _emit_order_site_binding_state(db, task.id) + task_ids.append(int(task.id)) + if task_ids: + from .auto_allocator import wake_auto_allocator + + wake_auto_allocator(task_ids) + + +def _write_mapping( + db: Session, + row: PlatformCommodityMapping, + *, + internal_sku_key: str, + campaign_key: str, + campaign_name: str, + commodity_id: str, + goods_name: str, + required_points: int | None, + sale_mode: str, + available_from: datetime | None, + available_until: datetime | None, + released_at: datetime | None, + enabled: bool, + current: User, +) -> None: + sku_key = internal_sku_key.strip() + campaign = campaign_key.strip() + commodity = commodity_id.strip() + if not sku_key or not campaign or not commodity: + raise HTTPException( + status_code=400, + detail="内部 SKU、活动批次和斗鱼商品 ID 不能为空", + ) + _validate_mapping_window(available_from, available_until) + goods = ( + db.query(DouyuGoodsSnapshot) + .filter(DouyuGoodsSnapshot.commodity_id == commodity) + .order_by(DouyuGoodsSnapshot.id.desc()) + .first() + ) + row.target_platform = TARGET_PLATFORM + row.scope = SCOPE_ELITE + row.internal_sku_key = sku_key + row.campaign_key = campaign + row.campaign_name = campaign_name.strip() + row.commodity_id = commodity + row.goods_name = (goods_name or (goods.name if goods else "")).strip() + row.required_points = ( + int(required_points) + if required_points is not None + else (int(goods.score) if goods and goods.score is not None else None) + ) + row.sale_mode = classification.normalize_sale_mode(sale_mode) + row.available_from = available_from + row.available_until = available_until + row.released_at = released_at + row.goods_status = str(goods.status if goods else "").strip() + row.enabled = bool(enabled) + row.updated_at = _now() + row.version = max(1, int(row.version or 1)) + db.flush() + if row.enabled: + _disable_other_current_mappings(db, row=row) + _reapply_mapping_tasks(db, row=row, current=current) + db.commit() + + +def create_mapping( + db: Session, + *, + internal_sku_key: str, + campaign_key: str, + campaign_name: str, + commodity_id: str, + goods_name: str, + required_points: int | None, + sale_mode: str, + available_from: datetime | None, + available_until: datetime | None, + released_at: datetime | None, + enabled: bool, + current: User, +) -> dict[str, Any]: + row = PlatformCommodityMapping( + target_platform=TARGET_PLATFORM, + scope=SCOPE_ELITE, + internal_sku_key=internal_sku_key.strip(), + campaign_key=campaign_key.strip(), + commodity_id=commodity_id.strip(), + created_by=current.id, + created_at=_now(), + updated_at=_now(), + version=1, + ) + duplicate = ( + db.query(PlatformCommodityMapping.id) + .filter( + PlatformCommodityMapping.target_platform == TARGET_PLATFORM, + PlatformCommodityMapping.internal_sku_key == internal_sku_key.strip(), + PlatformCommodityMapping.campaign_key == campaign_key.strip(), + ) + .first() + ) + if duplicate: + raise HTTPException(status_code=409, detail="该 SKU 的活动批次映射已存在") + db.add(row) + _write_mapping( + db, + row, + internal_sku_key=internal_sku_key, + campaign_key=campaign_key, + campaign_name=campaign_name, + commodity_id=commodity_id, + goods_name=goods_name, + required_points=required_points, + sale_mode=sale_mode, + available_from=available_from, + available_until=available_until, + released_at=released_at, + enabled=enabled, + current=current, + ) + return _mapping_out(db, row) + + +def update_mapping( + db: Session, + *, + mapping_id: int, + **values: Any, +) -> dict[str, Any]: + row = db.get(PlatformCommodityMapping, int(mapping_id)) + if row is None or row.target_platform != TARGET_PLATFORM: + raise HTTPException(status_code=404, detail="商品映射不存在") + if row.archived_at is not None: + raise HTTPException(status_code=409, detail="已归档映射不能编辑,请先恢复") + current = values.pop("current") + duplicate = ( + db.query(PlatformCommodityMapping.id) + .filter( + PlatformCommodityMapping.id != row.id, + PlatformCommodityMapping.target_platform == TARGET_PLATFORM, + PlatformCommodityMapping.internal_sku_key + == str(values.get("internal_sku_key") or "").strip(), + PlatformCommodityMapping.campaign_key + == str(values.get("campaign_key") or "").strip(), + ) + .first() + ) + if duplicate: + raise HTTPException(status_code=409, detail="该 SKU 的活动批次映射已存在") + row.version = int(row.version or 1) + 1 + _write_mapping(db, row, current=current, **values) + return _mapping_out(db, row) + + +def set_mapping_enabled( + db: Session, + *, + mapping_id: int, + enabled: bool, + current: User, +) -> dict[str, Any]: + row = db.get(PlatformCommodityMapping, int(mapping_id)) + if row is None or row.target_platform != TARGET_PLATFORM: + raise HTTPException(status_code=404, detail="商品映射不存在") + if row.archived_at is not None: + raise HTTPException(status_code=409, detail="已归档映射不能启停,请先恢复") + row.enabled = bool(enabled) + row.version = int(row.version or 1) + 1 + row.updated_at = _now() + db.flush() + if enabled: + _disable_other_current_mappings(db, row=row) + _reapply_mapping_tasks(db, row=row, current=current) + db.commit() + return _mapping_out(db, row) + + +def archive_mapping( + db: Session, + *, + mapping_id: int, + current: User, +) -> dict[str, Any]: + row = db.get(PlatformCommodityMapping, int(mapping_id)) + if row is None or row.target_platform != TARGET_PLATFORM: + raise HTTPException(status_code=404, detail="商品映射不存在") + row.enabled = False + row.archived_at = _now() + row.archived_by = current.id + row.version = int(row.version or 1) + 1 + row.updated_at = _now() + _reapply_mapping_tasks(db, row=row, current=current) + db.commit() + return _mapping_out(db, row) + + +def restore_mapping( + db: Session, + *, + mapping_id: int, +) -> dict[str, Any]: + row = db.get(PlatformCommodityMapping, int(mapping_id)) + if row is None or row.target_platform != TARGET_PLATFORM: + raise HTTPException(status_code=404, detail="商品映射不存在") + row.archived_at = None + row.archived_by = None + row.enabled = False + row.version = int(row.version or 1) + 1 + row.updated_at = _now() + db.commit() + return _mapping_out(db, row) + + +def delete_mapping(db: Session, *, mapping_id: int) -> None: + row = db.get(PlatformCommodityMapping, int(mapping_id)) + if row is None or row.target_platform != TARGET_PLATFORM: + raise HTTPException(status_code=404, detail="商品映射不存在") + referenced = ( + db.query(PlatformFulfillmentTask.id) + .filter(PlatformFulfillmentTask.commodity_mapping_id == row.id) + .first() + ) + if referenced: + raise HTTPException(status_code=409, detail="映射已被任务引用,只能归档") + db.delete(row) + db.commit() + + +def mapping_impact(db: Session, *, mapping_id: int) -> dict[str, Any]: + row = db.get(PlatformCommodityMapping, int(mapping_id)) + if row is None or row.target_platform != TARGET_PLATFORM: + raise HTTPException(status_code=404, detail="商品映射不存在") + rows = ( + db.query( + PlatformFulfillmentTask.execution_status, + PlatformFulfillmentTask.sale_mode, + func.count(PlatformFulfillmentTask.id), + ) + .filter( + PlatformFulfillmentTask.internal_sku_key == row.internal_sku_key, + PlatformFulfillmentTask.account_id.is_(None), + ) + .group_by( + PlatformFulfillmentTask.execution_status, + PlatformFulfillmentTask.sale_mode, + ) + .all() + ) + return { + "mappingId": row.id, + "internalSkuKey": row.internal_sku_key, + "affectedTasks": sum(int(count) for _status, _mode, count in rows), + "groups": [ + { + "executionStatus": status, + "saleMode": mode, + "count": int(count), + } + for status, mode, count in rows + ], + } + + +def upsert_mapping( + db: Session, + *, + internal_sku_key: str, + commodity_id: str, + goods_name: str, + required_points: int | None, + enabled: bool, + current: User, + campaign_key: str = "douyu-current", + campaign_name: str = "", + sale_mode: str = "unknown", + available_from: datetime | None = None, + available_until: datetime | None = None, + released_at: datetime | None = None, +) -> dict[str, Any]: + row = ( + db.query(PlatformCommodityMapping) + .filter( + PlatformCommodityMapping.target_platform == TARGET_PLATFORM, + PlatformCommodityMapping.internal_sku_key == internal_sku_key.strip(), + PlatformCommodityMapping.campaign_key == campaign_key.strip(), + ) + .first() + ) + values = { + "internal_sku_key": internal_sku_key, + "campaign_key": campaign_key, + "campaign_name": campaign_name, + "commodity_id": commodity_id, + "goods_name": goods_name, + "required_points": required_points, + "sale_mode": sale_mode, + "available_from": available_from, + "available_until": available_until, + "released_at": released_at, + "enabled": enabled, + "current": current, + } + if row is None: + return create_mapping(db, **values) + return update_mapping(db, mapping_id=row.id, **values) diff --git a/web/backend/services/platform_fulfillment/order_sync.py b/web/backend/services/platform_fulfillment/order_sync.py new file mode 100644 index 0000000..0ad7cf3 --- /dev/null +++ b/web/backend/services/platform_fulfillment/order_sync.py @@ -0,0 +1,541 @@ +"""订单快照同步与待履约任务生成。""" + +from __future__ import annotations + +import threading +import time +from datetime import datetime +from typing import Any + +from fastapi import HTTPException +from sqlalchemy.orm import Session + +from ...models import ( + PlatformCommodityMapping, + PlatformFulfillmentTask, +) +from ..external_order_source import ( + OrderLookupUnavailable, + list_pending_manual_fulfillments, + lookup_pending_manual_fulfillment, +) +from .common import ( + AUTO_SYNC_INTERVAL_SECONDS, + SCOPE_ELITE, + TARGET_PLATFORM, + _jsonable, + _now, + _order_match_started_at, + _order_snapshot_from_event, + _parse_snapshot_datetime, + _snapshot_value, +) +from .mappings import _apply_mapping +from .outbox import _emit_order_site_binding_state +from .runtime import ( + _append_event, + _apply_task_lease_policy, +) + +_SYNC_LOCK = threading.Lock() +_AUTO_SYNC_LOCK = threading.Lock() +_AUTO_SYNC_LAST_ATTEMPT = float("-inf") + + +def _upsert_order_snapshot( + db: Session, + snapshot: dict[str, Any], + *, + mapping: PlatformCommodityMapping | None, +) -> tuple[PlatformFulfillmentTask | None, bool, bool]: + """应用一条订单项快照,返回 (task, created, ignored)。""" + item_id = str( + _snapshot_value( + snapshot, "sourceOrderItemId", "source_order_item_id", default="" + ) + ).strip() + if not item_id: + return None, False, True + + paid_at = _parse_snapshot_datetime( + _snapshot_value(snapshot, "paidAt", "paid_at", default=None) + ) + order_created_at = _parse_snapshot_datetime( + _snapshot_value( + snapshot, + "orderCreatedAt", + "order_created_at", + default=None, + ) + ) + order_status = str( + _snapshot_value(snapshot, "orderStatus", "order_status", default="") + ) + pay_status = str( + _snapshot_value(snapshot, "payStatus", "pay_status", default="paid") + ) + terminal_order = order_status in {"refunded", "cancelled", "closed"} + if not terminal_order and pay_status != "paid": + return None, False, True + cutoff = _order_match_started_at(db) + match_basis_at = paid_at or order_created_at + if match_basis_at is not None and cutoff is not None and match_basis_at < cutoff: + return None, False, True + + task = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.source_system == "order_site", + PlatformFulfillmentTask.source_order_item_id == item_id, + ) + .first() + ) + created = task is None + if task is None: + task = PlatformFulfillmentTask( + source_system="order_site", + source_order_id=str( + _snapshot_value( + snapshot, + "sourceOrderId", + "source_order_id", + "orderId", + default="", + ) + ), + source_order_item_id=item_id, + source_fulfillment_id=str( + _snapshot_value( + snapshot, + "sourceFulfillmentId", + "source_fulfillment_id", + "fulfillmentId", + default="", + ) + ), + target_platform=TARGET_PLATFORM, + scope=SCOPE_ELITE, + created_at=_now(), + updated_at=_now(), + ) + db.add(task) + db.flush() + _append_event( + db, + task.id, + "task_created", + detail={ + "platformOrderId": _snapshot_value( + snapshot, "platformOrderId", "platform_order_id", default="" + ) + }, + ) + + before = ( + task.platform_order_id, + task.source_order_id, + task.source_fulfillment_id, + task.provider, + task.shop_id, + task.shop_name, + task.sku_code, + task.sku_name, + task.internal_sku_key, + task.quantity, + task.order_amount_fen, + task.paid_at, + task.execution_status, + task.commodity_mapping_id, + task.commodity_id, + task.required_points, + task.issue_code, + ) + 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( + snapshot, + "fulfillmentStatus", + "fulfillment_status", + default="", + ) + == "archived" + or _snapshot_value( + snapshot, + "configEnabled", + "config_enabled", + default=True, + ) + is False + or _snapshot_value( + snapshot, + "douyuFulfillmentEnabled", + "douyu_fulfillment_enabled", + default=True, + ) + is False + ) + + task.platform_order_id = str( + _snapshot_value(snapshot, "platformOrderId", "platform_order_id", default="") + ) + task.source_order_id = str( + _snapshot_value( + snapshot, + "sourceOrderId", + "source_order_id", + "orderId", + default=task.source_order_id, + ) + ) + task.source_fulfillment_id = str( + _snapshot_value( + snapshot, + "sourceFulfillmentId", + "source_fulfillment_id", + "fulfillmentId", + default=task.source_fulfillment_id, + ) + ) + task.provider = str(_snapshot_value(snapshot, "provider", default=task.provider)) + task.shop_id = str(_snapshot_value(snapshot, "shopId", "shop_id", default="")) + task.shop_name = str(_snapshot_value(snapshot, "shopName", "shop_name", default="")) + task.sku_code = str(_snapshot_value(snapshot, "skuCode", "sku_code", default="")) + task.sku_name = str(_snapshot_value(snapshot, "skuName", "sku_name", default="")) + task.internal_sku_key = str( + _snapshot_value( + snapshot, + "internalSkuKey", + "internal_sku_key", + default="", + ) + ).strip() + task.quantity = max( + 1, + int(_snapshot_value(snapshot, "quantity", default=1) or 1), + ) + task.order_amount_fen = int( + _snapshot_value( + snapshot, + "revenueAmountFen", + "revenue_amount_fen", + "totalAmountFen", + "total_amount", + default=0, + ) + or 0 + ) + task.paid_at = paid_at + task.source_snapshot_json = _jsonable(snapshot) + task.updated_at = _now() + + if terminal: + task.execution_status = "cancelled" + task.issue_code = "source_cancelled" + task.last_error = "订单已关闭或直播履约配置已停用" + task.next_allocate_at = None + # 订单源头取消/关闭后不再保留执行账号;统一策略会立即释放租约。 + _apply_task_lease_policy(db, task) + else: + # 订单快照会被重复投递。只有未分配任务从「待映射」进入「待分配」时 + # 才允许改生命周期状态;已分配任务不能被快照更新打回 pending。 + update_execution_status = task.account_id is None and ( + previous_execution_status == "pending_mapping" or mapping is None + ) + _apply_mapping( + task, + mapping, + update_execution_status=update_execution_status, + ) + if task.account_id is not None: + task.next_allocate_at = None + elif task.execution_status == "ready": + if previous_execution_status != "ready" or task.next_allocate_at is None: + task.next_allocate_at = _now() + else: + task.next_allocate_at = None + + after = ( + task.platform_order_id, + task.source_order_id, + task.source_fulfillment_id, + task.provider, + task.shop_id, + task.shop_name, + task.sku_code, + task.sku_name, + task.internal_sku_key, + task.quantity, + task.order_amount_fen, + task.paid_at, + task.execution_status, + task.commodity_mapping_id, + task.commodity_id, + task.required_points, + task.issue_code, + ) + changed = created or before != after + if changed: + _emit_order_site_binding_state(db, task.id) + return task, created, False + + +def _mapping_map(db: Session) -> dict[str, PlatformCommodityMapping]: + rows = ( + db.query(PlatformCommodityMapping) + .filter( + PlatformCommodityMapping.target_platform == TARGET_PLATFORM, + PlatformCommodityMapping.enabled.is_(True), + PlatformCommodityMapping.archived_at.is_(None), + ) + .order_by(PlatformCommodityMapping.updated_at.desc()) + .all() + ) + result: dict[str, PlatformCommodityMapping] = {} + for row in rows: + sku_key = str(row.internal_sku_key or "").strip() + if sku_key and sku_key not in result: + result[sku_key] = row + return result + + +def sync_order_snapshot( + db: Session, + payload: dict[str, Any], + *, + commit: bool = True, +) -> dict[str, Any]: + """消费 order_site 订单项快照;正常路径不再读取 order_site 数据库。""" + snapshot = _order_snapshot_from_event(payload) + mapping_by_sku = _mapping_map(db) + mapping = mapping_by_sku.get( + str( + _snapshot_value( + snapshot, + "internalSkuKey", + "internal_sku_key", + default="", + ) + ).strip() + ) + task, created, ignored = _upsert_order_snapshot(db, snapshot, mapping=mapping) + if commit: + db.commit() + return { + "fetched": 1, + "created": int(created), + "updated": int(task is not None and not created), + "ignored": int(ignored), + "taskIds": [int(task.id)] if task is not None else [], + } + + +def sync_order_item_ids( + db: Session, + source_order_item_ids: list[str], + *, + commit: bool = True, +) -> dict[str, Any]: + """兼容旧版事件:只定向读取明确订单项,不再走最近 500 条窗口。""" + mapping_by_sku = _mapping_map(db) + created = 0 + updated = 0 + ignored = 0 + task_ids: list[int] = [] + for item_id in dict.fromkeys( + str(item or "").strip() for item in source_order_item_ids + ): + if not item_id: + ignored += 1 + continue + snapshot = lookup_pending_manual_fulfillment(item_id) + if snapshot is None: + ignored += 1 + continue + mapping = mapping_by_sku.get( + str(snapshot.get("internal_sku_key") or "").strip() + ) + task, was_created, was_ignored = _upsert_order_snapshot( + db, + snapshot, + mapping=mapping, + ) + if task is None: + ignored += int(was_ignored) + continue + created += int(was_created) + updated += int(not was_created) + task_ids.append(int(task.id)) + if commit: + db.commit() + return { + "fetched": len(task_ids), + "created": created, + "updated": updated, + "ignored": ignored, + "taskIds": task_ids, + } + + +def _sync_pending_tasks( + db: Session, + *, + limit: int = 100, + commit: bool = True, +) -> dict[str, Any]: + """只拉取已配置商品映射的人工待履约订单项并生成本地作业。""" + match_started_at = _order_match_started_at(db) + mappings = ( + db.query(PlatformCommodityMapping) + .filter( + PlatformCommodityMapping.target_platform == TARGET_PLATFORM, + PlatformCommodityMapping.enabled.is_(True), + ) + .all() + ) + mappings_by_sku = { + str(mapping.internal_sku_key or "").strip(): mapping + for mapping in mappings + if str(mapping.internal_sku_key or "").strip() + } + if not mappings_by_sku: + if commit: + db.commit() + return { + "fetched": 0, + "created": 0, + "updated": 0, + "skippedUnmapped": 0, + "configuredSkuCount": 0, + } + try: + rows = list_pending_manual_fulfillments( + limit=limit, + internal_sku_keys=list(mappings_by_sku), + paid_at_from=match_started_at, + ) + except OrderLookupUnavailable as exc: + raise HTTPException(status_code=503, detail=f"订单源不可用:{exc}") from exc + + created = 0 + updated = 0 + skipped_unmapped = 0 + task_ids: list[int] = [] + for row in rows: + item_id = str(row.get("source_order_item_id") or "") + if not item_id: + continue + internal_sku_key = str(row.get("internal_sku_key") or "").strip() + mapping = mappings_by_sku.get(internal_sku_key) + if mapping is None: + skipped_unmapped += 1 + continue + task = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.source_system == "order_site", + PlatformFulfillmentTask.source_order_item_id == item_id, + ) + .first() + ) + if task is None: + task = PlatformFulfillmentTask( + source_system="order_site", + 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 ""), + created_at=_now(), + updated_at=_now(), + ) + db.add(task) + db.flush() + created += 1 + _append_event( + db, + task.id, + "task_created", + detail={"platformOrderId": row.get("platform_order_id")}, + ) + else: + updated += 1 + + if task.execution_status in {"completed", "cancelled"}: + continue + task.platform_order_id = str(row.get("platform_order_id") or "") + task.provider = str(row.get("provider") or "") + task.shop_id = str(row.get("shop_id") or "") + task.shop_name = str(row.get("shop_name") or "") + task.sku_code = str(row.get("sku_code") or "") + task.sku_name = str(row.get("sku_name") or "") + task.internal_sku_key = internal_sku_key + task.quantity = 1 + if isinstance(row.get("paid_at"), datetime): + task.paid_at = row["paid_at"] + task.order_amount_fen = int( + row.get("revenue_amount_fen") or row.get("total_amount") or 0 + ) + task.target_platform = TARGET_PLATFORM + task.scope = SCOPE_ELITE + task.source_snapshot_json = _jsonable(row) + task.updated_at = _now() + if task.account_id is None and task.execution_status in { + "pending_mapping", + "ready", + }: + _apply_mapping(task, mapping) + if task.execution_status == "ready" and task.account_id is None: + task.next_allocate_at = _now() + _emit_order_site_binding_state(db, task.id) + task_ids.append(int(task.id)) + + if commit: + db.commit() + return { + "fetched": len(rows), + "created": created, + "updated": updated, + "skippedUnmapped": skipped_unmapped, + "configuredSkuCount": len(mappings_by_sku), + "orderMatchStartedAt": _jsonable(match_started_at), + "taskIds": task_ids, + } + + +def sync_pending_tasks( + db: Session, + *, + limit: int = 100, + commit: bool = True, +) -> dict[str, Any]: + """串行同步订单,避免自动同步与人工同步并发创建重复任务。""" + with _SYNC_LOCK: + return _sync_pending_tasks(db, limit=limit, commit=commit) + + +def sync_pending_tasks_if_due( + db: Session, + *, + limit: int = 100, + now: float | None = None, +) -> dict[str, Any] | None: + """工作台读取时自动同步;按进程节流,不阻塞每 5 秒一次的列表轮询。""" + global _AUTO_SYNC_LAST_ATTEMPT + + if not _AUTO_SYNC_LOCK.acquire(blocking=False): + return None + try: + current = time.monotonic() if now is None else now + if current - _AUTO_SYNC_LAST_ATTEMPT < AUTO_SYNC_INTERVAL_SECONDS: + return None + _AUTO_SYNC_LAST_ATTEMPT = current + try: + return sync_pending_tasks(db, limit=limit) + except Exception: + _AUTO_SYNC_LAST_ATTEMPT = float("-inf") + raise + finally: + _AUTO_SYNC_LOCK.release() diff --git a/web/backend/services/platform_fulfillment/outbox.py b/web/backend/services/platform_fulfillment/outbox.py new file mode 100644 index 0000000..b6e1694 --- /dev/null +++ b/web/backend/services/platform_fulfillment/outbox.py @@ -0,0 +1,41 @@ +"""履约状态 Outbox 写入。""" + +from __future__ import annotations + +from typing import Any + +from sqlalchemy.orm import Session + +from ...models import ( + PlatformFulfillmentTask, +) +from .order_site_notifier import enqueue_order_site_binding_state +from .views import customer_binding_out + + +def _emit_order_site_binding_state( + db: Session, + task_id: int, + *, + extra: dict[str, Any] | None = None, +) -> bool: + """当前事务内写 Outbox;HTTP 投递由独立 worker 完成。""" + task = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id == int(task_id)) + .with_for_update() + .one() + ) + next_state_version = int(task.state_version or 0) + 1 + payload = customer_binding_out(db, task_id) + payload["stateVersion"] = next_state_version + if extra: + payload.update(extra) + enqueued = enqueue_order_site_binding_state( + db, + payload, + ) + if enqueued: + task.state_version = next_state_version + db.flush() + return enqueued diff --git a/web/backend/services/platform_fulfillment/repository.py b/web/backend/services/platform_fulfillment/repository.py new file mode 100644 index 0000000..dfd407e --- /dev/null +++ b/web/backend/services/platform_fulfillment/repository.py @@ -0,0 +1,127 @@ +"""履约任务加载、集成操作人和绑定任务查询。""" + +from __future__ import annotations + +import os +from datetime import UTC, datetime, timedelta + +from fastapi import HTTPException +from sqlalchemy.orm import Session + +from ...models import ( + AccountLease, + DouyuTask, + PlatformFulfillmentTask, + User, +) +from .common import ( + BINDING_QR_TTL_SECONDS, + _apply_order_match_cutoff, + _now, + _order_match_started_at, +) + + +def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask: + task = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id == int(task_id)) + .first() + ) + if task is None: + raise HTTPException(status_code=404, detail="直播账号履约任务不存在") + return task + + +def _load_task_for_update(db: Session, task_id: int) -> PlatformFulfillmentTask: + task = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id == int(task_id)) + .populate_existing() + .with_for_update() + .first() + ) + if task is None: + raise HTTPException(status_code=404, detail="直播账号履约任务不存在") + return task + + +def _retain_lease_for_active_collab( + db: Session, + *, + task: PlatformFulfillmentTask, + lease: AccountLease | None, + current: User, + reason: str, +) -> AccountLease | None: + """平台释放账号前,把仍在活动的协作单占用接续到同一租约。""" + if lease is None or not task.account_id: + return None + from ..douyu_collab_service import retain_lease_for_active_collab + + return retain_lease_for_active_collab( + db, + account_id=int(task.account_id), + holder_user_id=int(current.id), + current=current, + lease=lease, + source_task_id=int(task.id), + reason=reason, + commit=False, + ) + + +def _integration_actor(db: Session) -> User: + raw_user_id = os.getenv("PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID", "").strip() + query = db.query(User).filter(User.is_active.is_(True)) + if raw_user_id: + try: + user = query.filter(User.id == int(raw_user_id)).first() + except ValueError: + user = None + else: + user = query.filter(User.role == "super_admin").order_by(User.id.asc()).first() + if user is None: + raise HTTPException( + status_code=503, + detail="未配置可用的直播账号履约集成操作人", + ) + return user + + +def _find_customer_task( + db: Session, + *, + source_order_item_id: str, + platform_order_id: str = "", +) -> PlatformFulfillmentTask | None: + item_id = str(source_order_item_id or "").strip() + if not item_id: + return None + query = db.query(PlatformFulfillmentTask).filter( + PlatformFulfillmentTask.source_system == "order_site", + PlatformFulfillmentTask.source_order_item_id == item_id, + ) + query = _apply_order_match_cutoff(query, _order_match_started_at(db)) + order_no = str(platform_order_id or "").strip() + if order_no: + query = query.filter(PlatformFulfillmentTask.platform_order_id == order_no) + return query.first() + + +def _binding_qr_expired(bind_task: DouyuTask, now: datetime | None = None) -> bool: + result = bind_task.result or {} + raw_expires_at = str(result.get("qr_expires_at") or "").strip() + if raw_expires_at: + try: + expires_at = datetime.fromisoformat(raw_expires_at) + except ValueError: + expires_at = None + if expires_at is not None: + if expires_at.tzinfo is None: + expires_at = expires_at.replace(tzinfo=UTC) + return expires_at <= (now or _now()) + created_at = bind_task.created_at + if created_at.tzinfo is None: + created_at = created_at.replace(tzinfo=UTC) + return created_at + timedelta(seconds=BINDING_QR_TTL_SECONDS) <= (now or _now()) diff --git a/web/backend/services/platform_fulfillment/runtime.py b/web/backend/services/platform_fulfillment/runtime.py new file mode 100644 index 0000000..04eb338 --- /dev/null +++ b/web/backend/services/platform_fulfillment/runtime.py @@ -0,0 +1,381 @@ +"""履约设置、租约策略、事件写入和斗鱼操作结果投影。""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from typing import Any + +from sqlalchemy.orm import Session + +from ...models import ( + AccountLease, + DouyuTask, + PlatformFulfillmentEvent, + PlatformFulfillmentSetting, + PlatformFulfillmentTask, + User, +) +from ..douyu_service import ( + SUPPORTED_DOUYU_TASK_TYPES, +) +from . import classification +from .account_selector import ( + release_lease, +) +from .binding_status import ( + _binding_failure_issue, + _binding_failure_raw_message, +) +from .common import ( + BINDING_COOLDOWN_ISSUES, + _jsonable, + _now, + binding_failed_lease_ttl_minutes, +) + + +def get_settings(db: Session) -> dict[str, Any]: + now = _now() + row = ( + db.query(PlatformFulfillmentSetting) + .filter(PlatformFulfillmentSetting.id == 1) + .first() + ) + if row is None: + row = PlatformFulfillmentSetting( + id=1, + lease_duration_minutes=None, + completed_release_delay_minutes=30, + manual_completed_release_delay_minutes=120, + presale_waiting_release_ttl_minutes=None, + manual_required_lease_ttl_minutes=None, + order_match_started_at=now, + ) + db.add(row) + db.commit() + db.refresh(row) + return { + "leaseDurationMinutes": row.lease_duration_minutes, + "completedReleaseDelayMinutes": row.completed_release_delay_minutes, + "manualCompletedReleaseDelayMinutes": ( + row.manual_completed_release_delay_minutes + ), + "presaleWaitingReleaseTtlMinutes": (row.presale_waiting_release_ttl_minutes), + "manualRequiredLeaseTtlMinutes": (row.manual_required_lease_ttl_minutes), + "orderMatchStartedAt": _jsonable(row.order_match_started_at), + "updatedAt": _jsonable(row.updated_at), + } + + +def _lease_policy_for_task( + task: PlatformFulfillmentTask, + settings: dict[str, Any], +) -> tuple[str, int | None]: + """返回任务当前状态对应的租约策略代码和保留分钟数。 + + ``None`` 表示无限租约。2026-11-22 的业务规则: + + - 预售等待开放、人工处理、所有正常进行中状态默认无限; + - 只有兑换完成后的短暂复核窗口自动设置到期时间; + - 普通进行中 TTL 只作为兜底配置,不能再套到预售或人工状态上。 + """ + status = str(task.execution_status or "") + exchange_status = str(task.exchange_status or "") + if status == "completed": + if exchange_status == "manual_done": + return ( + "manual_completed", + settings.get("manualCompletedReleaseDelayMinutes"), + ) + return "completed", settings.get("completedReleaseDelayMinutes") + if status == "cancelled": + return "cancelled", 0 + if status == "manual_required": + if task.issue_code == "binding_failed": + return ( + "binding_failed_cleanup", + binding_failed_lease_ttl_minutes(), + ) + return ( + "manual_required", + settings.get("manualRequiredLeaseTtlMinutes"), + ) + if ( + classification.normalize_sale_mode(task.sale_mode) == "presale" + and exchange_status == "waiting_release" + ): + return ( + "presale_waiting_release", + settings.get("presaleWaitingReleaseTtlMinutes"), + ) + return "active", settings.get("leaseDurationMinutes") + + +def _apply_task_lease_policy( + db: Session, + task: PlatformFulfillmentTask, + *, + lease: AccountLease | None = None, + settings: dict[str, Any] | None = None, + now: datetime | None = None, +) -> AccountLease | None: + """按任务状态重设租约到期时间,不提交事务。 + + 当前生产默认无限租约。只有 ``completed`` 等明确终态才设置到期时间, + 回收器因此不会再误伤预售等待和人工处理任务。 + """ + moment = now or _now() + active_lease = lease + if active_lease is None and task.lease_id: + active_lease = ( + db.query(AccountLease).filter(AccountLease.id == int(task.lease_id)).first() + ) + if ( + active_lease is None + or active_lease.status != "active" + or active_lease.purpose != "platform_fulfillment" + ): + return active_lease + + if str(task.execution_status or "") in {"completed", "cancelled"}: + # 终态释放前先检查活动外部协作单。若账号仍被协作单使用,租约转换为 + # douyu_collab 并保持无限,不能被平台 TTL 抢走。 + from ..douyu_collab_service import retain_lease_for_active_collab + + retained = retain_lease_for_active_collab( + db, + account_id=int(active_lease.account_id), + holder_user_id=int(active_lease.holder_user_id), + lease=active_lease, + source_task_id=int(task.id), + reason=f"platform_{task.execution_status}_retained_for_collab", + commit=False, + ) + if retained is not None: + return retained + + policy, minutes = _lease_policy_for_task(task, settings or get_settings(db)) + if minutes is not None: + minutes = max(0, int(minutes)) + old_expiry = active_lease.expires_at + if minutes is None: + active_lease.expires_at = None + else: + active_lease.expires_at = moment + timedelta(minutes=minutes) + + if active_lease.expires_at != old_expiry: + _append_event( + db, + task.id, + "lease_policy_applied", + actor_type="system", + detail={ + "policy": policy, + "minutes": minutes, + "expiresAt": _jsonable(active_lease.expires_at), + "previousExpiresAt": _jsonable(old_expiry), + }, + ) + + if minutes == 0: + release_lease( + db, + active_lease, + reason=f"lease_policy:{policy}", + commit=False, + now=moment, + ) + return None + return active_lease + + +def update_settings( + db: Session, + *, + lease_duration_minutes: int | None, + completed_release_delay_minutes: int | None = 30, + manual_completed_release_delay_minutes: int | None = 120, + presale_waiting_release_ttl_minutes: int | None = None, + manual_required_lease_ttl_minutes: int | None = None, + order_match_started_at: datetime | None = None, + current: User, +) -> dict[str, Any]: + row = ( + db.query(PlatformFulfillmentSetting) + .filter(PlatformFulfillmentSetting.id == 1) + .first() + ) + now = _now() + if row is None: + row = PlatformFulfillmentSetting( + id=1, + order_match_started_at=order_match_started_at or now, + ) + db.add(row) + elif order_match_started_at is not None: + row.order_match_started_at = order_match_started_at + row.lease_duration_minutes = lease_duration_minutes + row.completed_release_delay_minutes = completed_release_delay_minutes + row.manual_completed_release_delay_minutes = manual_completed_release_delay_minutes + row.presale_waiting_release_ttl_minutes = presale_waiting_release_ttl_minutes + row.manual_required_lease_ttl_minutes = manual_required_lease_ttl_minutes + row.updated_by = current.id + row.updated_at = now + settings = { + "leaseDurationMinutes": lease_duration_minutes, + "completedReleaseDelayMinutes": completed_release_delay_minutes, + "manualCompletedReleaseDelayMinutes": (manual_completed_release_delay_minutes), + "presaleWaitingReleaseTtlMinutes": (presale_waiting_release_ttl_minutes), + "manualRequiredLeaseTtlMinutes": manual_required_lease_ttl_minutes, + } + active_leases = ( + db.query(AccountLease) + .filter( + AccountLease.purpose == "platform_fulfillment", + AccountLease.status == "active", + ) + .all() + ) + for lease in active_leases: + task = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.lease_id == lease.id) + .first() + ) + if task is None: + # 没有可解释业务状态的租约不能套通用 TTL,保持无限并等待人工排查。 + lease.expires_at = None + continue + _apply_task_lease_policy( + db, + task, + lease=lease, + settings=settings, + now=now, + ) + db.commit() + return { + "leaseDurationMinutes": row.lease_duration_minutes, + "completedReleaseDelayMinutes": row.completed_release_delay_minutes, + "manualCompletedReleaseDelayMinutes": ( + row.manual_completed_release_delay_minutes + ), + "presaleWaitingReleaseTtlMinutes": (row.presale_waiting_release_ttl_minutes), + "manualRequiredLeaseTtlMinutes": (row.manual_required_lease_ttl_minutes), + "orderMatchStartedAt": _jsonable(row.order_match_started_at), + "updatedAt": _jsonable(row.updated_at), + } + + +def _lease_duration_minutes(db: Session) -> int | None: + return get_settings(db)["leaseDurationMinutes"] + + +def _append_event( + db: Session, + task_id: int, + event_type: str, + *, + actor_type: str = "system", + actor_id: int | str | None = None, + detail: dict[str, Any] | None = None, +) -> None: + db.add( + PlatformFulfillmentEvent( + task_id=task_id, + event_type=event_type, + actor_type=actor_type, + actor_id=str(actor_id or ""), + detail_json=detail or {}, + created_at=_now(), + ) + ) + + +def record_douyu_operation_started( + db: Session, + task: PlatformFulfillmentTask, + *, + current: User, + batch_id: str, + task_type: str, + douyu_task_ids: list[int], + payload: dict[str, Any] | None = None, +) -> None: + """记录履约上下文发起的斗鱼操作,账号任务结果由执行器补写。""" + if task_type == "exchange_goods" and len(douyu_task_ids) == 1: + task.exchange_task_id = int(douyu_task_ids[0]) + _append_event( + db, + task.id, + "douyu_operation_started", + actor_type="user", + actor_id=current.id, + detail={ + "batchId": batch_id, + "douyuTaskIds": douyu_task_ids, + "taskType": task_type, + "taskLabel": SUPPORTED_DOUYU_TASK_TYPES.get(task_type, task_type), + "accountId": task.account_id, + "payload": payload or {}, + }, + ) + _apply_task_lease_policy(db, task) + db.commit() + + +def record_douyu_operation_result( + db: Session, + douyu_task: DouyuTask, + *, + status: str, + message: str, +) -> None: + """把履约上下文的斗鱼任务终态投影到履约时间线。""" + if not douyu_task.platform_task_id: + return + event_type = { + "success": "douyu_operation_succeeded", + "stopped": "douyu_operation_stopped", + }.get(status, "douyu_operation_failed") + result = douyu_task.result or {} + issue_code = "" + projected_message = message or "" + if status != "success" and douyu_task.task_type in {"get_bind_qr", "confirm_bind"}: + issue_code = _binding_failure_issue(douyu_task, result) + if issue_code in BINDING_COOLDOWN_ISSUES: + projected_message = _binding_failure_raw_message( + issue_code, + result, + fallback=projected_message, + ) + exists = ( + db.query(PlatformFulfillmentEvent.id) + .filter( + PlatformFulfillmentEvent.task_id == int(douyu_task.platform_task_id), + PlatformFulfillmentEvent.event_type == event_type, + PlatformFulfillmentEvent.detail_json["douyuTaskId"].as_integer() + == int(douyu_task.id), + ) + .first() + ) + if exists is not None: + return + _append_event( + db, + int(douyu_task.platform_task_id), + event_type, + detail={ + "batchId": douyu_task.batch_id, + "douyuTaskId": int(douyu_task.id), + "taskType": douyu_task.task_type, + "taskLabel": SUPPORTED_DOUYU_TASK_TYPES.get( + douyu_task.task_type, + douyu_task.task_type, + ), + "accountId": douyu_task.account_id, + "status": status, + "message": projected_message[:1000], + "issueCode": issue_code, + }, + ) diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index ceca257..2d81c43 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -1,3921 +1,134 @@ -"""直播账号履约作业服务:订单同步、映射、选号、绑码和人工完成。""" +"""直播账号履约服务兼容入口。 + +具体实现已按领域拆分到同包子模块;保留本模块是为了稳定 router、worker、 +测试和既有调用方的导入路径。 +""" from __future__ import annotations -import os -import time -import uuid -from datetime import UTC, datetime, timedelta -from threading import Lock -from typing import Any - -from fastapi import HTTPException -from sqlalchemy import func, or_, select -from sqlalchemy.exc import IntegrityError -from sqlalchemy.orm import Session -from starlette.concurrency import run_in_threadpool - -from ...models import ( - Account, - AccountCommodityState, - AccountEvent, - AccountLease, - DouyuExternalOrder, - DouyuGoodsSnapshot, - DouyuTask, - PlatformCommodityMapping, - PlatformFulfillmentEvent, - PlatformFulfillmentSetting, - PlatformFulfillmentTask, - User, +from . import ( # noqa: F401 + allocation, + binding, + customer, + lifecycle, + mappings, + order_sync, + outbox, + runtime, + views, ) -from ...permissions import ROLE_LABELS -from ..account_binding import ( - binding_role_from_result, - is_platform_account_bind_cooldown, - pending_binding_role_from_result, +from .allocation import ( # noqa: F401 + _allocate_task_from_capability, + _cached_capability_state, + _capability_availability_counts, + _local_allocation_retry_at, + _seed_capability_refresh, + allocate_task, + prepare_manual_allocation, ) -from ..account_capability_service import ( - ACCOUNT_ELIGIBILITY_LIMITED, - ACCOUNT_ELIGIBILITY_UNKNOWN, - AVAILABILITY_AVAILABLE, - AVAILABILITY_LIMITED, - AVAILABILITY_NOT_OFFERED, - AVAILABILITY_NOT_OPEN, - OFFER_STATE_ACTIVE, - OFFER_STATE_BEFORE, - OFFER_STATE_NOT_OFFERED, - OFFER_STATE_UNKNOWN, - STOCK_STATE_UNKNOWN, - allocation_availability, - classify_goods_items, - exchange_gate_for_availability, - record_account_commodity_state, +from .binding import ( # noqa: F401 + confirm_binding, + confirm_binding_sync, + reconcile_binding_state_outbox, + refresh_binding, + start_binding, + start_binding_sync, + sync_task_from_binding_runner, ) -from ..account_query_filters import ( - active_collab_order_exists, - active_lease_exists, - assigned_to_pool_filter, - automatable_account_filter, - cookie_present_filter, - role_change_ready_filter, - valid_ck_filter, +from .binding_status import ( # noqa: F401 + _binding_failure_issue, + _binding_failure_raw_message, + _customer_task_message, + _customer_task_message_for, + _effective_binding_issue, + _effective_task_message, + _normalized_event_detail, ) -from ..account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, WORK_STOREHOME_SYNC -from ..account_work_queue import ( - active_account_work_count, - enqueue_account_work, +from .common import ( # noqa: F401 + _apply_order_match_cutoff, + _exchange_gate, + _jsonable, + _mapping_for_sku, + _now, + _order_match_started_at, + _order_snapshot_from_event, + _parse_snapshot_datetime, + _snapshot_value, + binding_failed_lease_ttl_minutes, ) -from ..business_events import record_account_query, record_douyu_task_started -from ..douyu_account_probe import ( - CAPABILITY_OK, - config_mapping, - persist_probe_result, - probe_account, +from .customer import ( + customer_confirm_binding, + customer_refresh_binding, + customer_refresh_bindings, + customer_start_binding, + ensure_customer_session, ) -from ..douyu_account_state import DouyuLiveAccountState -from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches -from ..douyu_service import ( - SUPPORTED_DOUYU_TASK_TYPES, - ensure_douyu_config, +from .lifecycle import ( + cancel_task, + complete_manual_exchange, + mark_manual_required, + prepare_platform_task_for_collab_takeover, + refresh_exchange_eligibility, + release_task_account, + release_task_to_manual, + reset_task_binding, + restore_cancelled_task, ) -from ..external_order_source import ( - OrderLookupUnavailable, - list_pending_manual_fulfillments, - lookup_pending_manual_fulfillment, +from .mappings import ( # noqa: F401 + _apply_mapping, + _disable_other_current_mappings, + _mapping_impact, + _mapping_out, + _reapply_mapping_tasks, + _validate_mapping_window, + _write_mapping, + archive_mapping, + create_mapping, + delete_mapping, + list_mappings, + mapping_impact, + restore_mapping, + set_mapping_enabled, + update_mapping, + upsert_mapping, ) -from ..file_service import build_file_url -from . import classification -from .account_selector import ( - AccountCandidate, - CapabilityCandidate, - capability_candidate_rows, - capability_refresh_candidate_accounts, - lease_account, - release_lease, +from .order_sync import ( # noqa: F401 + _mapping_map, + _sync_pending_tasks, + _upsert_order_snapshot, + sync_order_item_ids, + sync_order_snapshot, + sync_pending_tasks, + sync_pending_tasks_if_due, ) -from .order_site_notifier import enqueue_order_site_binding_state - -TARGET_PLATFORM = "douyu" -SCOPE_ELITE = "elite" -ACTIVE_STATUSES = { - "ready", - "allocated", - "waiting_bind", - "role_ready", - "binding_confirming", - "bound", - "manual_required", -} - -BINDING_QR_TTL_SECONDS = int( - os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "1260") +from .outbox import ( # noqa: F401 + _emit_order_site_binding_state, +) +from .repository import ( # noqa: F401 + _binding_qr_expired, + _find_customer_task, + _integration_actor, + _load_task, + _load_task_for_update, + _retain_lease_for_active_collab, +) +from .runtime import ( # noqa: F401 + _append_event, + _apply_task_lease_policy, + _lease_duration_minutes, + _lease_policy_for_task, + get_settings, + record_douyu_operation_result, + record_douyu_operation_started, + update_settings, +) +from .views import ( # noqa: F401 + _customer_binding_queue_state, + _task_out, + customer_binding_out, + get_task_detail, + list_tasks, ) -AUTO_SYNC_INTERVAL_SECONDS = 900.0 -DEFAULT_CAPABILITY_CANDIDATE_LIMIT = 20 -LOCAL_STOCK_RETRY_SECONDS = 5 * 60 -LOCAL_CACHE_MISS_RETRY_SECONDS = 2 * 60 -LOCAL_LEASE_CONFLICT_RETRY_SECONDS = 5 -DEFAULT_BINDING_FAILED_LEASE_TTL_MINUTES = 120 - - -def binding_failed_lease_ttl_minutes() -> int: - """扫码超时任务的账号保留时间;过期后允许重新进入选号池。""" - try: - value = int( - os.getenv( - "PLATFORM_BINDING_FAILED_LEASE_TTL_MINUTES", - str(DEFAULT_BINDING_FAILED_LEASE_TTL_MINUTES), - ) - ) - except ValueError: - return DEFAULT_BINDING_FAILED_LEASE_TTL_MINUTES - return max(1, value) - - -def _exchange_gate( - state: DouyuLiveAccountState, - commodity_id: str, - *, - allow_not_open: bool = False, -) -> tuple[str, str, str]: - """把实时商品资格映射为履约可展示的硬门槛。""" - limited = commodity_id in state.limited_ids - if not state.commodity_availability: - return ( - exchange_gate_for_availability( - AVAILABILITY_AVAILABLE, - limited=limited, - ) - if limited - else ("", "", "") - ) - availability = state.commodity_availability.get(commodity_id) - reason = state.commodity_blocking_reasons.get(commodity_id, "") - return exchange_gate_for_availability( - availability, - reason=reason, - limited=limited, - allow_not_open=allow_not_open, - ) - - -_SYNC_LOCK = Lock() -_AUTO_SYNC_LOCK = Lock() -_AUTO_SYNC_LAST_ATTEMPT = float("-inf") - - -def _now() -> datetime: - return datetime.now(UTC) - - -def _jsonable(value: Any) -> Any: - if isinstance(value, datetime): - return value.isoformat() - if isinstance(value, dict): - return {str(key): _jsonable(item) for key, item in value.items()} - if isinstance(value, (list, tuple)): - return [_jsonable(item) for item in value] - if isinstance(value, (str, int, float, bool)) or value is None: - return value - return str(value) - - -def _mapping_for_sku( - db: Session, internal_sku_key: str -) -> PlatformCommodityMapping | None: - return ( - db.query(PlatformCommodityMapping) - .filter( - PlatformCommodityMapping.target_platform == TARGET_PLATFORM, - PlatformCommodityMapping.internal_sku_key == internal_sku_key, - PlatformCommodityMapping.enabled.is_(True), - PlatformCommodityMapping.archived_at.is_(None), - ) - .order_by(PlatformCommodityMapping.updated_at.desc()) - .first() - ) - - -def _parse_snapshot_datetime(value: Any) -> datetime | None: - if isinstance(value, datetime): - return value if value.tzinfo is not None else value.replace(tzinfo=UTC) - text = str(value or "").strip() - if not text: - return None - try: - parsed = datetime.fromisoformat(text) - except ValueError: - return None - return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC) - - -def _snapshot_value(data: dict[str, Any], *names: str, default: Any = "") -> Any: - for name in names: - if name in data and data[name] is not None: - return data[name] - return default - - -def _order_snapshot_from_event(payload: dict[str, Any]) -> dict[str, Any]: - data = payload.get("data") - return data if isinstance(data, dict) else payload - - -def _upsert_order_snapshot( - db: Session, - snapshot: dict[str, Any], - *, - mapping: PlatformCommodityMapping | None, -) -> tuple[PlatformFulfillmentTask | None, bool, bool]: - """应用一条订单项快照,返回 (task, created, ignored)。""" - item_id = str( - _snapshot_value( - snapshot, "sourceOrderItemId", "source_order_item_id", default="" - ) - ).strip() - if not item_id: - return None, False, True - - paid_at = _parse_snapshot_datetime( - _snapshot_value(snapshot, "paidAt", "paid_at", default=None) - ) - order_created_at = _parse_snapshot_datetime( - _snapshot_value( - snapshot, - "orderCreatedAt", - "order_created_at", - default=None, - ) - ) - order_status = str( - _snapshot_value(snapshot, "orderStatus", "order_status", default="") - ) - pay_status = str( - _snapshot_value(snapshot, "payStatus", "pay_status", default="paid") - ) - terminal_order = order_status in {"refunded", "cancelled", "closed"} - if not terminal_order and pay_status != "paid": - return None, False, True - cutoff = _order_match_started_at(db) - match_basis_at = paid_at or order_created_at - if match_basis_at is not None and cutoff is not None and match_basis_at < cutoff: - return None, False, True - - task = ( - db.query(PlatformFulfillmentTask) - .filter( - PlatformFulfillmentTask.source_system == "order_site", - PlatformFulfillmentTask.source_order_item_id == item_id, - ) - .first() - ) - created = task is None - if task is None: - task = PlatformFulfillmentTask( - source_system="order_site", - source_order_id=str( - _snapshot_value( - snapshot, - "sourceOrderId", - "source_order_id", - "orderId", - default="", - ) - ), - source_order_item_id=item_id, - source_fulfillment_id=str( - _snapshot_value( - snapshot, - "sourceFulfillmentId", - "source_fulfillment_id", - "fulfillmentId", - default="", - ) - ), - target_platform=TARGET_PLATFORM, - scope=SCOPE_ELITE, - created_at=_now(), - updated_at=_now(), - ) - db.add(task) - db.flush() - _append_event( - db, - task.id, - "task_created", - detail={ - "platformOrderId": _snapshot_value( - snapshot, "platformOrderId", "platform_order_id", default="" - ) - }, - ) - - before = ( - task.platform_order_id, - task.source_order_id, - task.source_fulfillment_id, - task.provider, - task.shop_id, - task.shop_name, - task.sku_code, - task.sku_name, - task.internal_sku_key, - task.quantity, - task.order_amount_fen, - task.paid_at, - task.execution_status, - task.commodity_mapping_id, - task.commodity_id, - task.required_points, - task.issue_code, - ) - 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( - snapshot, - "fulfillmentStatus", - "fulfillment_status", - default="", - ) - == "archived" - or _snapshot_value( - snapshot, - "configEnabled", - "config_enabled", - default=True, - ) - is False - or _snapshot_value( - snapshot, - "douyuFulfillmentEnabled", - "douyu_fulfillment_enabled", - default=True, - ) - is False - ) - - task.platform_order_id = str( - _snapshot_value(snapshot, "platformOrderId", "platform_order_id", default="") - ) - task.source_order_id = str( - _snapshot_value( - snapshot, - "sourceOrderId", - "source_order_id", - "orderId", - default=task.source_order_id, - ) - ) - task.source_fulfillment_id = str( - _snapshot_value( - snapshot, - "sourceFulfillmentId", - "source_fulfillment_id", - "fulfillmentId", - default=task.source_fulfillment_id, - ) - ) - task.provider = str(_snapshot_value(snapshot, "provider", default=task.provider)) - task.shop_id = str(_snapshot_value(snapshot, "shopId", "shop_id", default="")) - task.shop_name = str(_snapshot_value(snapshot, "shopName", "shop_name", default="")) - task.sku_code = str(_snapshot_value(snapshot, "skuCode", "sku_code", default="")) - task.sku_name = str(_snapshot_value(snapshot, "skuName", "sku_name", default="")) - task.internal_sku_key = str( - _snapshot_value( - snapshot, - "internalSkuKey", - "internal_sku_key", - default="", - ) - ).strip() - task.quantity = max( - 1, - int(_snapshot_value(snapshot, "quantity", default=1) or 1), - ) - task.order_amount_fen = int( - _snapshot_value( - snapshot, - "revenueAmountFen", - "revenue_amount_fen", - "totalAmountFen", - "total_amount", - default=0, - ) - or 0 - ) - task.paid_at = paid_at - task.source_snapshot_json = _jsonable(snapshot) - task.updated_at = _now() - - if terminal: - task.execution_status = "cancelled" - task.issue_code = "source_cancelled" - task.last_error = "订单已关闭或直播履约配置已停用" - task.next_allocate_at = None - # 订单源头取消/关闭后不再保留执行账号;统一策略会立即释放租约。 - _apply_task_lease_policy(db, task) - else: - # 订单快照会被重复投递。只有未分配任务从「待映射」进入「待分配」时 - # 才允许改生命周期状态;已分配任务不能被快照更新打回 pending。 - update_execution_status = task.account_id is None and ( - previous_execution_status == "pending_mapping" or mapping is None - ) - _apply_mapping( - task, - mapping, - update_execution_status=update_execution_status, - ) - if task.account_id is not None: - task.next_allocate_at = None - elif task.execution_status == "ready": - if previous_execution_status != "ready" or task.next_allocate_at is None: - task.next_allocate_at = _now() - else: - task.next_allocate_at = None - - after = ( - task.platform_order_id, - task.source_order_id, - task.source_fulfillment_id, - task.provider, - task.shop_id, - task.shop_name, - task.sku_code, - task.sku_name, - task.internal_sku_key, - task.quantity, - task.order_amount_fen, - task.paid_at, - task.execution_status, - task.commodity_mapping_id, - task.commodity_id, - task.required_points, - task.issue_code, - ) - changed = created or before != after - if changed: - _emit_order_site_binding_state(db, task.id) - return task, created, False - - -def _mapping_map(db: Session) -> dict[str, PlatformCommodityMapping]: - rows = ( - db.query(PlatformCommodityMapping) - .filter( - PlatformCommodityMapping.target_platform == TARGET_PLATFORM, - PlatformCommodityMapping.enabled.is_(True), - PlatformCommodityMapping.archived_at.is_(None), - ) - .order_by(PlatformCommodityMapping.updated_at.desc()) - .all() - ) - result: dict[str, PlatformCommodityMapping] = {} - for row in rows: - sku_key = str(row.internal_sku_key or "").strip() - if sku_key and sku_key not in result: - result[sku_key] = row - return result - - -def sync_order_snapshot( - db: Session, - payload: dict[str, Any], - *, - commit: bool = True, -) -> dict[str, Any]: - """消费 order_site 订单项快照;正常路径不再读取 order_site 数据库。""" - snapshot = _order_snapshot_from_event(payload) - mapping_by_sku = _mapping_map(db) - mapping = mapping_by_sku.get( - str( - _snapshot_value( - snapshot, - "internalSkuKey", - "internal_sku_key", - default="", - ) - ).strip() - ) - task, created, ignored = _upsert_order_snapshot(db, snapshot, mapping=mapping) - if commit: - db.commit() - return { - "fetched": 1, - "created": int(created), - "updated": int(task is not None and not created), - "ignored": int(ignored), - "taskIds": [int(task.id)] if task is not None else [], - } - - -def sync_order_item_ids( - db: Session, - source_order_item_ids: list[str], - *, - commit: bool = True, -) -> dict[str, Any]: - """兼容旧版事件:只定向读取明确订单项,不再走最近 500 条窗口。""" - mapping_by_sku = _mapping_map(db) - created = 0 - updated = 0 - ignored = 0 - task_ids: list[int] = [] - for item_id in dict.fromkeys( - str(item or "").strip() for item in source_order_item_ids - ): - if not item_id: - ignored += 1 - continue - snapshot = lookup_pending_manual_fulfillment(item_id) - if snapshot is None: - ignored += 1 - continue - mapping = mapping_by_sku.get( - str(snapshot.get("internal_sku_key") or "").strip() - ) - task, was_created, was_ignored = _upsert_order_snapshot( - db, - snapshot, - mapping=mapping, - ) - if task is None: - ignored += int(was_ignored) - continue - created += int(was_created) - updated += int(not was_created) - task_ids.append(int(task.id)) - if commit: - db.commit() - return { - "fetched": len(task_ids), - "created": created, - "updated": updated, - "ignored": ignored, - "taskIds": task_ids, - } - - -def get_settings(db: Session) -> dict[str, Any]: - now = _now() - row = ( - db.query(PlatformFulfillmentSetting) - .filter(PlatformFulfillmentSetting.id == 1) - .first() - ) - if row is None: - row = PlatformFulfillmentSetting( - id=1, - lease_duration_minutes=None, - completed_release_delay_minutes=30, - manual_completed_release_delay_minutes=120, - presale_waiting_release_ttl_minutes=None, - manual_required_lease_ttl_minutes=None, - order_match_started_at=now, - ) - db.add(row) - db.commit() - db.refresh(row) - return { - "leaseDurationMinutes": row.lease_duration_minutes, - "completedReleaseDelayMinutes": row.completed_release_delay_minutes, - "manualCompletedReleaseDelayMinutes": ( - row.manual_completed_release_delay_minutes - ), - "presaleWaitingReleaseTtlMinutes": ( - row.presale_waiting_release_ttl_minutes - ), - "manualRequiredLeaseTtlMinutes": ( - row.manual_required_lease_ttl_minutes - ), - "orderMatchStartedAt": _jsonable(row.order_match_started_at), - "updatedAt": _jsonable(row.updated_at), - } - - -def _lease_policy_for_task( - task: PlatformFulfillmentTask, - settings: dict[str, Any], -) -> tuple[str, int | None]: - """返回任务当前状态对应的租约策略代码和保留分钟数。 - - ``None`` 表示无限租约。2026-11-22 的业务规则: - - - 预售等待开放、人工处理、所有正常进行中状态默认无限; - - 只有兑换完成后的短暂复核窗口自动设置到期时间; - - 普通进行中 TTL 只作为兜底配置,不能再套到预售或人工状态上。 - """ - status = str(task.execution_status or "") - exchange_status = str(task.exchange_status or "") - if status == "completed": - if exchange_status == "manual_done": - return ( - "manual_completed", - settings.get("manualCompletedReleaseDelayMinutes"), - ) - return "completed", settings.get("completedReleaseDelayMinutes") - if status == "cancelled": - return "cancelled", 0 - if status == "manual_required": - if task.issue_code == "binding_failed": - return ( - "binding_failed_cleanup", - binding_failed_lease_ttl_minutes(), - ) - return ( - "manual_required", - settings.get("manualRequiredLeaseTtlMinutes"), - ) - if ( - classification.normalize_sale_mode(task.sale_mode) == "presale" - and exchange_status == "waiting_release" - ): - return ( - "presale_waiting_release", - settings.get("presaleWaitingReleaseTtlMinutes"), - ) - return "active", settings.get("leaseDurationMinutes") - - -def _apply_task_lease_policy( - db: Session, - task: PlatformFulfillmentTask, - *, - lease: AccountLease | None = None, - settings: dict[str, Any] | None = None, - now: datetime | None = None, -) -> AccountLease | None: - """按任务状态重设租约到期时间,不提交事务。 - - 当前生产默认无限租约。只有 ``completed`` 等明确终态才设置到期时间, - 回收器因此不会再误伤预售等待和人工处理任务。 - """ - moment = now or _now() - active_lease = lease - if active_lease is None and task.lease_id: - active_lease = ( - db.query(AccountLease) - .filter(AccountLease.id == int(task.lease_id)) - .first() - ) - if ( - active_lease is None - or active_lease.status != "active" - or active_lease.purpose != "platform_fulfillment" - ): - return active_lease - - if str(task.execution_status or "") in {"completed", "cancelled"}: - # 终态释放前先检查活动外部协作单。若账号仍被协作单使用,租约转换为 - # douyu_collab 并保持无限,不能被平台 TTL 抢走。 - from ..douyu_collab_service import retain_lease_for_active_collab - - retained = retain_lease_for_active_collab( - db, - account_id=int(active_lease.account_id), - holder_user_id=int(active_lease.holder_user_id), - lease=active_lease, - source_task_id=int(task.id), - reason=f"platform_{task.execution_status}_retained_for_collab", - commit=False, - ) - if retained is not None: - return retained - - policy, minutes = _lease_policy_for_task(task, settings or get_settings(db)) - if minutes is not None: - minutes = max(0, int(minutes)) - old_expiry = active_lease.expires_at - if minutes is None: - active_lease.expires_at = None - else: - active_lease.expires_at = moment + timedelta(minutes=minutes) - - if active_lease.expires_at != old_expiry: - _append_event( - db, - task.id, - "lease_policy_applied", - actor_type="system", - detail={ - "policy": policy, - "minutes": minutes, - "expiresAt": _jsonable(active_lease.expires_at), - "previousExpiresAt": _jsonable(old_expiry), - }, - ) - - if minutes == 0: - release_lease( - db, - active_lease, - reason=f"lease_policy:{policy}", - commit=False, - now=moment, - ) - return None - return active_lease - - -def update_settings( - db: Session, - *, - lease_duration_minutes: int | None, - completed_release_delay_minutes: int | None = 30, - manual_completed_release_delay_minutes: int | None = 120, - presale_waiting_release_ttl_minutes: int | None = None, - manual_required_lease_ttl_minutes: int | None = None, - order_match_started_at: datetime | None = None, - current: User, -) -> dict[str, Any]: - row = ( - db.query(PlatformFulfillmentSetting) - .filter(PlatformFulfillmentSetting.id == 1) - .first() - ) - now = _now() - if row is None: - row = PlatformFulfillmentSetting( - id=1, - order_match_started_at=order_match_started_at or now, - ) - db.add(row) - elif order_match_started_at is not None: - row.order_match_started_at = order_match_started_at - row.lease_duration_minutes = lease_duration_minutes - row.completed_release_delay_minutes = completed_release_delay_minutes - row.manual_completed_release_delay_minutes = ( - manual_completed_release_delay_minutes - ) - row.presale_waiting_release_ttl_minutes = ( - presale_waiting_release_ttl_minutes - ) - row.manual_required_lease_ttl_minutes = manual_required_lease_ttl_minutes - row.updated_by = current.id - row.updated_at = now - settings = { - "leaseDurationMinutes": lease_duration_minutes, - "completedReleaseDelayMinutes": completed_release_delay_minutes, - "manualCompletedReleaseDelayMinutes": ( - manual_completed_release_delay_minutes - ), - "presaleWaitingReleaseTtlMinutes": ( - presale_waiting_release_ttl_minutes - ), - "manualRequiredLeaseTtlMinutes": manual_required_lease_ttl_minutes, - } - active_leases = ( - db.query(AccountLease) - .filter( - AccountLease.purpose == "platform_fulfillment", - AccountLease.status == "active", - ) - .all() - ) - for lease in active_leases: - task = ( - db.query(PlatformFulfillmentTask) - .filter(PlatformFulfillmentTask.lease_id == lease.id) - .first() - ) - if task is None: - # 没有可解释业务状态的租约不能套通用 TTL,保持无限并等待人工排查。 - lease.expires_at = None - continue - _apply_task_lease_policy( - db, - task, - lease=lease, - settings=settings, - now=now, - ) - db.commit() - return { - "leaseDurationMinutes": row.lease_duration_minutes, - "completedReleaseDelayMinutes": row.completed_release_delay_minutes, - "manualCompletedReleaseDelayMinutes": ( - row.manual_completed_release_delay_minutes - ), - "presaleWaitingReleaseTtlMinutes": ( - row.presale_waiting_release_ttl_minutes - ), - "manualRequiredLeaseTtlMinutes": ( - row.manual_required_lease_ttl_minutes - ), - "orderMatchStartedAt": _jsonable(row.order_match_started_at), - "updatedAt": _jsonable(row.updated_at), - } - - -def _lease_duration_minutes(db: Session) -> int | None: - return get_settings(db)["leaseDurationMinutes"] - - -def _order_match_started_at(db: Session) -> datetime | None: - row = ( - db.query(PlatformFulfillmentSetting) - .filter(PlatformFulfillmentSetting.id == 1) - .first() - ) - return row.order_match_started_at if row is not None else None - - -def _apply_order_match_cutoff( - query, - match_started_at: datetime | None, -): - if match_started_at is None: - return query - return query.filter(PlatformFulfillmentTask.paid_at >= match_started_at) - - -def _integration_actor(db: Session) -> User: - raw_user_id = os.getenv("PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID", "").strip() - query = db.query(User).filter(User.is_active.is_(True)) - if raw_user_id: - try: - user = query.filter(User.id == int(raw_user_id)).first() - except ValueError: - user = None - else: - user = query.filter(User.role == "super_admin").order_by(User.id.asc()).first() - if user is None: - raise HTTPException( - status_code=503, - detail="未配置可用的直播账号履约集成操作人", - ) - return user - - -def _find_customer_task( - db: Session, - *, - source_order_item_id: str, - platform_order_id: str = "", -) -> PlatformFulfillmentTask | None: - item_id = str(source_order_item_id or "").strip() - if not item_id: - return None - query = db.query(PlatformFulfillmentTask).filter( - PlatformFulfillmentTask.source_system == "order_site", - PlatformFulfillmentTask.source_order_item_id == item_id, - ) - query = _apply_order_match_cutoff(query, _order_match_started_at(db)) - order_no = str(platform_order_id or "").strip() - if order_no: - query = query.filter(PlatformFulfillmentTask.platform_order_id == order_no) - return query.first() - - -def _binding_qr_expired(bind_task: DouyuTask, now: datetime | None = None) -> bool: - result = bind_task.result or {} - raw_expires_at = str(result.get("qr_expires_at") or "").strip() - if raw_expires_at: - try: - expires_at = datetime.fromisoformat(raw_expires_at) - except ValueError: - expires_at = None - if expires_at is not None: - if expires_at.tzinfo is None: - expires_at = expires_at.replace(tzinfo=UTC) - return expires_at <= (now or _now()) - created_at = bind_task.created_at - if created_at.tzinfo is None: - created_at = created_at.replace(tzinfo=UTC) - return created_at + timedelta(seconds=BINDING_QR_TTL_SECONDS) <= (now or _now()) - - -def _append_event( - db: Session, - task_id: int, - event_type: str, - *, - actor_type: str = "system", - actor_id: int | str | None = None, - detail: dict[str, Any] | None = None, -) -> None: - db.add( - PlatformFulfillmentEvent( - task_id=task_id, - event_type=event_type, - actor_type=actor_type, - actor_id=str(actor_id or ""), - detail_json=detail or {}, - created_at=_now(), - ) - ) - - -def record_douyu_operation_started( - db: Session, - task: PlatformFulfillmentTask, - *, - current: User, - batch_id: str, - task_type: str, - douyu_task_ids: list[int], - payload: dict[str, Any] | None = None, -) -> None: - """记录履约上下文发起的斗鱼操作,账号任务结果由执行器补写。""" - if task_type == "exchange_goods" and len(douyu_task_ids) == 1: - task.exchange_task_id = int(douyu_task_ids[0]) - _append_event( - db, - task.id, - "douyu_operation_started", - actor_type="user", - actor_id=current.id, - detail={ - "batchId": batch_id, - "douyuTaskIds": douyu_task_ids, - "taskType": task_type, - "taskLabel": SUPPORTED_DOUYU_TASK_TYPES.get(task_type, task_type), - "accountId": task.account_id, - "payload": payload or {}, - }, - ) - _apply_task_lease_policy(db, task) - db.commit() - - -def record_douyu_operation_result( - db: Session, - douyu_task: DouyuTask, - *, - status: str, - message: str, -) -> None: - """把履约上下文的斗鱼任务终态投影到履约时间线。""" - if not douyu_task.platform_task_id: - return - event_type = { - "success": "douyu_operation_succeeded", - "stopped": "douyu_operation_stopped", - }.get(status, "douyu_operation_failed") - exists = ( - db.query(PlatformFulfillmentEvent.id) - .filter( - PlatformFulfillmentEvent.task_id == int(douyu_task.platform_task_id), - PlatformFulfillmentEvent.event_type == event_type, - PlatformFulfillmentEvent.detail_json["douyuTaskId"].as_integer() - == int(douyu_task.id), - ) - .first() - ) - if exists is not None: - return - _append_event( - db, - int(douyu_task.platform_task_id), - event_type, - detail={ - "batchId": douyu_task.batch_id, - "douyuTaskId": int(douyu_task.id), - "taskType": douyu_task.task_type, - "taskLabel": SUPPORTED_DOUYU_TASK_TYPES.get( - douyu_task.task_type, - douyu_task.task_type, - ), - "accountId": douyu_task.account_id, - "status": status, - "message": (message or "")[:1000], - }, - ) - - -def _emit_order_site_binding_state( - db: Session, - task_id: int, - *, - extra: dict[str, Any] | None = None, -) -> bool: - """当前事务内写 Outbox;HTTP 投递由独立 worker 完成。""" - task = ( - db.query(PlatformFulfillmentTask) - .filter(PlatformFulfillmentTask.id == int(task_id)) - .with_for_update() - .one() - ) - next_state_version = int(task.state_version or 0) + 1 - payload = customer_binding_out(db, task_id) - payload["stateVersion"] = next_state_version - if extra: - payload.update(extra) - enqueued = enqueue_order_site_binding_state( - db, - payload, - ) - if enqueued: - task.state_version = next_state_version - db.flush() - return enqueued - - -def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask: - task = ( - db.query(PlatformFulfillmentTask) - .filter(PlatformFulfillmentTask.id == int(task_id)) - .first() - ) - if task is None: - raise HTTPException(status_code=404, detail="直播账号履约任务不存在") - return task - - -def _load_task_for_update(db: Session, task_id: int) -> PlatformFulfillmentTask: - task = ( - db.query(PlatformFulfillmentTask) - .filter(PlatformFulfillmentTask.id == int(task_id)) - .populate_existing() - .with_for_update() - .first() - ) - if task is None: - raise HTTPException(status_code=404, detail="直播账号履约任务不存在") - return task - - -def _retain_lease_for_active_collab( - db: Session, - *, - task: PlatformFulfillmentTask, - lease: AccountLease | None, - current: User, - reason: str, -) -> AccountLease | None: - """平台释放账号前,把仍在活动的协作单占用接续到同一租约。""" - if lease is None or not task.account_id: - return None - from ..douyu_collab_service import retain_lease_for_active_collab - - return retain_lease_for_active_collab( - db, - account_id=int(task.account_id), - holder_user_id=int(current.id), - current=current, - lease=lease, - source_task_id=int(task.id), - reason=reason, - commit=False, - ) - - -def _apply_mapping( - task: PlatformFulfillmentTask, - mapping: PlatformCommodityMapping | None, - *, - update_execution_status: bool = True, -) -> None: - if mapping is not None: - snapshot_classification = ( - task.execution_status == "pending_mapping" - or task.classification_source in {"", "unknown"} - or task.sale_mode in {"", "unknown"} - ) - task.commodity_mapping_id = mapping.id - task.commodity_id = mapping.commodity_id - task.required_points = mapping.required_points - if snapshot_classification: - task.sale_mode = classification.normalize_sale_mode(mapping.sale_mode) - task.campaign_key = mapping.campaign_key - task.campaign_name = mapping.campaign_name - task.offer_available_from = mapping.available_from - task.offer_available_until = mapping.available_until - task.classification_source = ( - "mapping" if task.sale_mode != "unknown" else "unknown" - ) - else: - task.commodity_mapping_id = None - task.commodity_id = "" - task.required_points = None - task.sale_mode = "unknown" - task.campaign_key = "" - task.campaign_name = "" - task.offer_available_from = None - task.offer_available_until = None - task.classification_source = "unknown" - if not update_execution_status: - return - if mapping is None: - task.execution_status = "pending_mapping" - task.issue_code = "mapping_missing" - task.last_error = "内部 SKU 尚未配置斗鱼商品映射" - return - task.execution_status = "ready" - task.issue_code = "" - task.last_error = "" - - -def _sync_pending_tasks( - db: Session, - *, - limit: int = 100, - commit: bool = True, -) -> dict[str, Any]: - """只拉取已配置商品映射的人工待履约订单项并生成本地作业。""" - match_started_at = _order_match_started_at(db) - mappings = ( - db.query(PlatformCommodityMapping) - .filter( - PlatformCommodityMapping.target_platform == TARGET_PLATFORM, - PlatformCommodityMapping.enabled.is_(True), - ) - .all() - ) - mappings_by_sku = { - str(mapping.internal_sku_key or "").strip(): mapping - for mapping in mappings - if str(mapping.internal_sku_key or "").strip() - } - if not mappings_by_sku: - if commit: - db.commit() - return { - "fetched": 0, - "created": 0, - "updated": 0, - "skippedUnmapped": 0, - "configuredSkuCount": 0, - } - try: - rows = list_pending_manual_fulfillments( - limit=limit, - internal_sku_keys=list(mappings_by_sku), - paid_at_from=match_started_at, - ) - except OrderLookupUnavailable as exc: - raise HTTPException(status_code=503, detail=f"订单源不可用:{exc}") from exc - - created = 0 - updated = 0 - skipped_unmapped = 0 - task_ids: list[int] = [] - for row in rows: - item_id = str(row.get("source_order_item_id") or "") - if not item_id: - continue - internal_sku_key = str(row.get("internal_sku_key") or "").strip() - mapping = mappings_by_sku.get(internal_sku_key) - if mapping is None: - skipped_unmapped += 1 - continue - task = ( - db.query(PlatformFulfillmentTask) - .filter( - PlatformFulfillmentTask.source_system == "order_site", - PlatformFulfillmentTask.source_order_item_id == item_id, - ) - .first() - ) - if task is None: - task = PlatformFulfillmentTask( - source_system="order_site", - 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 ""), - created_at=_now(), - updated_at=_now(), - ) - db.add(task) - db.flush() - created += 1 - _append_event( - db, - task.id, - "task_created", - detail={"platformOrderId": row.get("platform_order_id")}, - ) - else: - updated += 1 - - if task.execution_status in {"completed", "cancelled"}: - continue - task.platform_order_id = str(row.get("platform_order_id") or "") - task.provider = str(row.get("provider") or "") - task.shop_id = str(row.get("shop_id") or "") - task.shop_name = str(row.get("shop_name") or "") - task.sku_code = str(row.get("sku_code") or "") - task.sku_name = str(row.get("sku_name") or "") - task.internal_sku_key = internal_sku_key - task.quantity = 1 - if isinstance(row.get("paid_at"), datetime): - task.paid_at = row["paid_at"] - task.order_amount_fen = int( - row.get("revenue_amount_fen") or row.get("total_amount") or 0 - ) - task.target_platform = TARGET_PLATFORM - task.scope = SCOPE_ELITE - task.source_snapshot_json = _jsonable(row) - task.updated_at = _now() - if task.account_id is None and task.execution_status in { - "pending_mapping", - "ready", - }: - _apply_mapping(task, mapping) - if task.execution_status == "ready" and task.account_id is None: - task.next_allocate_at = _now() - _emit_order_site_binding_state(db, task.id) - task_ids.append(int(task.id)) - - if commit: - db.commit() - return { - "fetched": len(rows), - "created": created, - "updated": updated, - "skippedUnmapped": skipped_unmapped, - "configuredSkuCount": len(mappings_by_sku), - "orderMatchStartedAt": _jsonable(match_started_at), - "taskIds": task_ids, - } - - -def sync_pending_tasks( - db: Session, - *, - limit: int = 100, - commit: bool = True, -) -> dict[str, Any]: - """串行同步订单,避免自动同步与人工同步并发创建重复任务。""" - with _SYNC_LOCK: - return _sync_pending_tasks(db, limit=limit, commit=commit) - - -def sync_pending_tasks_if_due( - db: Session, - *, - limit: int = 100, - now: float | None = None, -) -> dict[str, Any] | None: - """工作台读取时自动同步;按进程节流,不阻塞每 5 秒一次的列表轮询。""" - global _AUTO_SYNC_LAST_ATTEMPT - - if not _AUTO_SYNC_LOCK.acquire(blocking=False): - return None - try: - current = time.monotonic() if now is None else now - if current - _AUTO_SYNC_LAST_ATTEMPT < AUTO_SYNC_INTERVAL_SECONDS: - return None - _AUTO_SYNC_LAST_ATTEMPT = current - try: - return sync_pending_tasks(db, limit=limit) - except Exception: - _AUTO_SYNC_LAST_ATTEMPT = float("-inf") - raise - finally: - _AUTO_SYNC_LOCK.release() - - -def list_tasks( - db: Session, - *, - status: str = "", - queue_bucket: str = "", - sale_mode: str = "", - keyword: str = "", - page: int = 1, - page_size: int = 20, -) -> dict[str, Any]: - query = db.query(PlatformFulfillmentTask) - query = _apply_order_match_cutoff(query, _order_match_started_at(db)) - query = query.filter( - or_( - PlatformFulfillmentTask.commodity_mapping_id.isnot(None), - PlatformFulfillmentTask.commodity_id != "", - ) - ) - mode_filter = classification.normalize_sale_mode(sale_mode) - if sale_mode and mode_filter != "unknown": - query = query.filter(PlatformFulfillmentTask.sale_mode == mode_filter) - elif sale_mode == "unknown": - query = query.filter(PlatformFulfillmentTask.sale_mode == "unknown") - if queue_bucket: - now = datetime.now(UTC) - if queue_bucket == classification.QUEUE_CANCELLED: - query = query.filter(PlatformFulfillmentTask.execution_status == "cancelled") - elif queue_bucket == classification.QUEUE_COMPLETED: - query = query.filter(PlatformFulfillmentTask.execution_status == "completed") - elif queue_bucket == classification.QUEUE_PENDING_MAPPING: - query = query.filter( - PlatformFulfillmentTask.execution_status == "pending_mapping" - ) - elif queue_bucket == classification.QUEUE_NEEDS_ACTION: - query = query.filter( - PlatformFulfillmentTask.execution_status == "manual_required" - ) - elif queue_bucket == classification.QUEUE_PRESALE_WAITING: - query = query.filter( - PlatformFulfillmentTask.execution_status.notin_( - ["completed", "cancelled", "pending_mapping", "manual_required"] - ), - PlatformFulfillmentTask.sale_mode == "presale", - or_( - PlatformFulfillmentTask.offer_available_from.is_(None), - PlatformFulfillmentTask.offer_available_from > now, - ), - ) - elif queue_bucket == classification.QUEUE_READY: - query = query.filter( - PlatformFulfillmentTask.execution_status.notin_( - ["completed", "cancelled", "pending_mapping", "manual_required"] - ), - or_( - PlatformFulfillmentTask.sale_mode != "presale", - PlatformFulfillmentTask.offer_available_from.is_(None), - PlatformFulfillmentTask.offer_available_from <= now, - ), - ) - else: - query = query.filter( - PlatformFulfillmentTask.execution_status.notin_(["completed", "cancelled"]) - ) - if status: - if status == "unfinished": - query = query.filter( - PlatformFulfillmentTask.execution_status.notin_( - ["completed", "cancelled"] - ) - ) - else: - query = query.filter(PlatformFulfillmentTask.execution_status == status) - text = keyword.strip() - if text: - pattern = f"%{text}%" - query = query.outerjoin( - Account, - Account.id == PlatformFulfillmentTask.account_id, - ).filter( - or_( - PlatformFulfillmentTask.platform_order_id.ilike(pattern), - PlatformFulfillmentTask.sku_name.ilike(pattern), - PlatformFulfillmentTask.sku_code.ilike(pattern), - PlatformFulfillmentTask.internal_sku_key.ilike(pattern), - PlatformFulfillmentTask.commodity_id.ilike(pattern), - Account.username.ilike(pattern), - Account.nickname.ilike(pattern), - Account.uid.ilike(pattern), - ) - ) - total = query.count() - rows = ( - query.order_by( - PlatformFulfillmentTask.paid_at.desc(), - PlatformFulfillmentTask.id.desc(), - ) - .offset((max(1, page) - 1) * max(1, page_size)) - .limit(max(1, min(page_size, 100))) - .all() - ) - return { - "items": [_task_out(db, row) for row in rows], - "pagination": { - "page": max(1, page), - "pageSize": max(1, page_size), - "total": total, - }, - } - - -def _task_out( - db: Session, - task: PlatformFulfillmentTask, - *, - include_qr: bool = False, - include_exchange_task: bool = False, -) -> dict[str, Any]: - mapping = ( - db.query(PlatformCommodityMapping) - .filter(PlatformCommodityMapping.id == task.commodity_mapping_id) - .first() - if task.commodity_mapping_id - else None - ) - goods = ( - db.query(DouyuGoodsSnapshot) - .filter(DouyuGoodsSnapshot.commodity_id == task.commodity_id) - .order_by(DouyuGoodsSnapshot.id.desc()) - .first() - if task.commodity_id - else None - ) - goods_name = ( - str(getattr(mapping, "goods_name", "") or "") - or str(getattr(goods, "name", "") or "") - or task.sku_name - or task.internal_sku_key - ) - account = ( - db.query(Account).filter(Account.id == task.account_id).first() - if task.account_id - else None - ) - lease = ( - db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if task.lease_id - else None - ) - bind_task = ( - db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() - if task.bind_task_id - else None - ) - collab_order = ( - db.query(DouyuExternalOrder) - .filter(DouyuExternalOrder.source_task_id == task.id) - .first() - ) - bind_result = (bind_task.result or {}) if bind_task else {} - exchange_task_id = task.exchange_task_id - if exchange_task_id is None and include_exchange_task: - exchange_task_id = ( - db.query(DouyuTask.id) - .filter( - DouyuTask.platform_task_id == task.id, - DouyuTask.task_type == "exchange_goods", - ) - .order_by(DouyuTask.id.desc()) - .limit(1) - .scalar() - ) - # 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。 - pending_role = pending_binding_role_from_result(bind_result) - sale_mode = classification.normalize_sale_mode(task.sale_mode) - availability = classification.availability_state( - sale_mode=sale_mode, - available_from=task.offer_available_from, - available_until=task.offer_available_until, - ) - queue_bucket = classification.queue_bucket( - execution_status=task.execution_status, - sale_mode=sale_mode, - availability=availability, - ) - manual_reason = ( - classification.manual_reason(task.issue_code, task.exchange_status) - if task.execution_status == "manual_required" - else "" - ) - return { - "id": task.id, - "sourceSystem": task.source_system, - "sourceOrderId": task.source_order_id, - "sourceOrderItemId": task.source_order_item_id, - "sourceFulfillmentId": task.source_fulfillment_id, - "platformOrderId": task.platform_order_id, - "provider": task.provider, - "shopId": task.shop_id, - "shopName": task.shop_name, - "skuCode": task.sku_code, - "skuName": task.sku_name, - "internalSkuKey": task.internal_sku_key, - "quantity": task.quantity, - "orderAmountFen": task.order_amount_fen, - "targetPlatform": task.target_platform, - "scope": task.scope, - "commodityMappingId": task.commodity_mapping_id, - "commodityId": task.commodity_id, - "goodsName": goods_name, - "requiredPoints": task.required_points, - "saleMode": sale_mode, - "campaignKey": task.campaign_key, - "campaignName": task.campaign_name, - "offerAvailableFrom": task.offer_available_from, - "offerAvailableUntil": task.offer_available_until, - "availabilityState": availability, - "queueBucket": queue_bucket, - "manualReason": manual_reason, - "classificationSource": task.classification_source, - "bindingStatus": task.binding_status, - "executionStatus": task.execution_status, - "exchangeStatus": task.exchange_status, - "issueCode": task.issue_code, - "lastError": task.last_error, - "operatorId": task.operator_id, - "completedAt": task.completed_at, - "paidAt": task.paid_at, - "createdAt": task.created_at, - "updatedAt": task.updated_at, - "collabOrder": ( - { - "id": collab_order.id, - "orderNo": collab_order.order_no, - "status": collab_order.status, - "lastSyncedAt": collab_order.last_synced_at, - } - if collab_order - else None - ), - "account": ( - { - "id": account.id, - "username": account.username, - "nickname": account.nickname or "", - "points": account.points, - "goldBalance": account.gold_balance, - "eliteOpened": account.elite_opened, - "ckCheckStatus": account.ck_check_status, - "roleBindStatus": account.role_bind_status, - "gameName": account.game_name, - "gameChannel": account.game_channel, - "roleChangeAvailableAt": account.role_change_available_at, - } - if account - else None - ), - "lease": ( - { - "id": lease.id, - "status": lease.status, - "expiresAt": lease.expires_at, - } - if lease - else None - ), - "bindTask": ( - { - "id": bind_task.id, - "taskType": bind_task.task_type, - "status": bind_task.status, - "message": bind_task.message, - "qrUrl": str(bind_result.get("url") or "") if include_qr else "", - "roleName": binding_role_from_result(bind_result), - "areaName": str(bind_result.get("area_name") or ""), - "platName": str(bind_result.get("plat_name") or ""), - "bindPhase": str(bind_result.get("bind_phase") or ""), - "bindReadyForConfirm": bool(pending_role), - "bindConfirmed": bool(bind_result.get("bind_confirmed")), - } - if bind_task - else None - ), - "exchangeTaskId": exchange_task_id, - "exchangeResultImage": ( - { - "objectKey": task.exchange_result_image_key, - "url": build_file_url(task.exchange_result_image_key), - "savedAt": task.exchange_result_image_saved_at, - } - if task.exchange_result_image_key - else None - ), - } - - -def get_task_detail(db: Session, task_id: int) -> dict[str, Any]: - task = _load_task(db, task_id) - events = ( - db.query(PlatformFulfillmentEvent) - .filter(PlatformFulfillmentEvent.task_id == task.id) - .order_by(PlatformFulfillmentEvent.id.desc()) - .limit(200) - .all() - ) - actor_ids = { - int(event.actor_id) - for event in events - if event.actor_type == "user" and str(event.actor_id or "").isdigit() - } - actors = ( - { - int(user.id): user - for user in db.query(User).filter(User.id.in_(actor_ids)).all() - } - if actor_ids - else {} - ) - return { - "task": _task_out(db, task, include_qr=True, include_exchange_task=True), - "events": [ - { - "id": event.id, - "eventType": event.event_type, - "actorType": event.actor_type, - "actorId": event.actor_id, - "actorName": ( - actors[int(event.actor_id)].deleted_username - or actors[int(event.actor_id)].username - ) - if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors - else "", - "actorRole": actors[int(event.actor_id)].role - if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors - else "", - "actorRoleLabel": ROLE_LABELS.get( - actors[int(event.actor_id)].role, - actors[int(event.actor_id)].role, - ) - if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors - else "", - "detail": event.detail_json or {}, - "createdAt": event.created_at, - } - for event in events - ], - } - - -def _customer_task_message(task: PlatformFulfillmentTask) -> str: - messages = { - "mapping_missing": "商品正在准备中,请稍后重试", - "no_eligible_account": "正在准备可用账号,请稍后重试", - "elite_not_opened": "账号正在准备精英宝典,请稍后重试", - "points_short": "账号正在补充积分,请稍后重试", - "commodity_limit_reached": "当前商品暂时无法兑换,请联系客服", - "binding_failed": "暂未识别到绑定角色,请继续使用当前二维码完成扫码", - "account_role_cooldown": "当前斗鱼账号未到换绑时间,请截图本页面并联系客服处理", - "customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理", - "eligibility_check_failed": "状态查询异常,请稍后刷新", - "manual_required": "当前需要人工处理,请联系客服", - } - return messages.get(task.issue_code, "") if task.issue_code else "" - - -def _binding_failure_issue(bind_task: DouyuTask, result: dict[str, Any]) -> str: - explicit_issue = str(result.get("issue_code") or "") - if explicit_issue in {"account_role_cooldown", "customer_role_cooldown"}: - return explicit_issue - phase = str(result.get("bind_phase") or "") - message = str(bind_task.message or "") - confirm_error = str(result.get("confirm_error") or "") - if ( - phase == "change_waiting" - or is_platform_account_bind_cooldown( - result.get("confirm_error_code"), - f"{message} {confirm_error}", - ) - or "暂不能换绑" in message - ): - task_issue = "account_role_cooldown" - elif ( - phase == "confirm_failed" - or "待绑定游戏账号" in message - or "未到换绑时间" in message - ): - task_issue = "customer_role_cooldown" - else: - return "binding_failed" - messages = { - "account_role_cooldown": "当前斗鱼账号未到换绑时间,请截图本页面并联系客服处理", - "customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理", - } - return task_issue if messages.get(task_issue) else "binding_failed" - - -def _customer_binding_queue_state( - task: PlatformFulfillmentTask, - bind_task: DouyuTask | None, - *, - lease_ready: bool, -) -> tuple[str, int]: - if task.execution_status == "completed": - return "completed", 0 - if task.execution_status == "cancelled": - return "cancelled", 0 - if task.issue_code == "mapping_missing": - return "mapping_missing", 0 - if not task.account_id or not task.lease_id: - return "allocation_queued", 2000 - if not lease_ready: - return "lease_inactive", 0 - if task.binding_status == "failed": - return "failed", 0 - if bind_task is None: - return "ready_to_start", 0 - result = bind_task.result or {} - if bool(result.get("bind_confirmed")) or task.binding_status == "bound": - return "confirmed", 0 - if pending_binding_role_from_result(result): - return "role_ready", 0 - if bind_task.status in {"failed", "error", "stopped"}: - return "failed", 0 - if task.binding_status == "confirming": - return "confirming", 1000 - if bind_task.status in {"planned", "pending"}: - return "qr_queued", 1000 - if result.get("url"): - return "waiting_scan", 5000 if result.get("bind_polling") else 0 - return "preparing", 1000 - - -def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]: - """面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。""" - task = _load_task(db, task_id) - bind_task = ( - db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() - if task.bind_task_id - else None - ) - bind_result = (bind_task.result or {}) if bind_task else {} - pending_role = pending_binding_role_from_result(bind_result) - lease = ( - db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if task.lease_id - else None - ) - lease_ready = bool(task.account_id and lease and lease.status == "active") - binding_failed = task.binding_status == "failed" - binding_confirmed = task.binding_status == "bound" - queue_state, retry_after_ms = _customer_binding_queue_state( - task, - bind_task, - lease_ready=lease_ready, - ) - return { - "sessionId": task.id, - "platformOrderId": task.platform_order_id, - "sourceOrderItemId": task.source_order_item_id, - "productName": task.sku_name, - "quantity": task.quantity, - "executionStatus": task.execution_status, - "bindingStatus": task.binding_status, - "exchangeStatus": task.exchange_status, - "issueCode": task.issue_code, - "message": _customer_task_message(task), - "accountReady": lease_ready, - "bindTaskId": bind_task.id if bind_task else None, - "bindTaskStatus": bind_task.status if bind_task else "", - "bindPhase": str(bind_result.get("bind_phase") or ""), - "qrUrl": str(bind_result.get("url") or ""), - "qrGeneratedAt": str(bind_result.get("qr_generated_at") or ""), - "qrExpiresAt": str(bind_result.get("qr_expires_at") or ""), - "roleName": binding_role_from_result(bind_result), - "areaName": str(bind_result.get("area_name") or ""), - "platName": str(bind_result.get("plat_name") or ""), - "bindReadyForConfirm": (bool(pending_role) and not binding_failed), - "bindConfirmed": bool(bind_result.get("bind_confirmed")) and binding_confirmed, - "queueState": queue_state, - "retryAfterMs": retry_after_ms, - "queueLane": bind_task.queue_lane if bind_task else "", - "accepted": False, - "stateVersion": int(task.state_version or 0), - "completedAt": _jsonable(task.completed_at), - "updatedAt": _jsonable(task.updated_at), - } - - -def ensure_customer_session( - db: Session, - *, - source_order_item_id: str, - platform_order_id: str = "", -) -> dict[str, Any]: - """按订单项幂等准备客户绑定会话;必要时同步订单并自动分配账号。""" - task = _find_customer_task( - db, - source_order_item_id=source_order_item_id, - platform_order_id=platform_order_id, - ) - if task is None: - sync_order_item_ids( - db, - [source_order_item_id], - commit=True, - ) - task = _find_customer_task( - db, - source_order_item_id=source_order_item_id, - platform_order_id=platform_order_id, - ) - if task is None: - raise HTTPException(status_code=404, detail="订单尚未进入直播账号履约队列") - if task.execution_status in {"completed", "cancelled"}: - return customer_binding_out(db, task.id) - if task.execution_status in {"pending_mapping", "ready", "manual_required"}: - if task.issue_code == "mapping_missing": - return customer_binding_out(db, task.id) - from .auto_allocator import wake_auto_allocator - - wake_auto_allocator([int(task.id)]) - return customer_binding_out(db, task.id) - - -async def customer_start_binding( - db: Session, - *, - task_id: int, - force_refresh: bool = False, -) -> dict[str, Any]: - task = _load_task(db, task_id) - if task.execution_status in {"completed", "cancelled"}: - return customer_binding_out(db, task.id) - if task.issue_code == "mapping_missing": - return customer_binding_out(db, task.id) - - if not task.account_id or not task.lease_id: - from .auto_allocator import wake_auto_allocator - - wake_auto_allocator([int(task.id)]) - payload = customer_binding_out(db, task.id) - payload["accepted"] = True - payload["queueState"] = "allocation_queued" - payload["retryAfterMs"] = 2000 - return payload - - lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if lease is None or lease.status != "active": - return customer_binding_out(db, task.id) - - previous_bind_task_id = task.bind_task_id - actor = _integration_actor(db) - await start_binding( - db, - task_id=task.id, - current=actor, - force_refresh=force_refresh, - ) - payload = customer_binding_out(db, task.id) - accepted = task.bind_task_id != previous_bind_task_id - payload["accepted"] = accepted - if accepted: - payload["queueState"] = "qr_queued" - payload["retryAfterMs"] = 1000 - return payload - - -def customer_refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: - refresh_binding(db, task_id=task_id) - return customer_binding_out(db, task_id) - - -def customer_refresh_bindings(db: Session, *, task_ids: list[int]) -> dict[str, Any]: - items: list[dict[str, Any]] = [] - for task_id in dict.fromkeys(task_ids): - task = ( - db.query(PlatformFulfillmentTask) - .filter(PlatformFulfillmentTask.id == task_id) - .first() - ) - if task is None: - continue - refresh_binding(db, task_id=task.id) - items.append(customer_binding_out(db, task.id)) - return {"items": items} - - -async def customer_confirm_binding(db: Session, *, task_id: int) -> dict[str, Any]: - refresh_binding(db, task_id=task_id) - await confirm_binding(db, task_id=task_id, current=_integration_actor(db)) - return customer_binding_out(db, task_id) - - -def _mapping_impact(db: Session, row: PlatformCommodityMapping) -> int: - query = db.query(func.count(PlatformFulfillmentTask.id)).filter( - PlatformFulfillmentTask.internal_sku_key == row.internal_sku_key, - PlatformFulfillmentTask.account_id.is_(None), - PlatformFulfillmentTask.execution_status.in_( - ["pending_mapping", "ready", "manual_required"] - ), - ) - return int(query.scalar() or 0) - - -def _mapping_out( - db: Session, - row: PlatformCommodityMapping, - *, - now: datetime | None = None, -) -> dict[str, Any]: - mode = classification.normalize_sale_mode(row.sale_mode) - availability = classification.availability_state( - sale_mode=mode, - available_from=row.available_from, - available_until=row.available_until, - goods_status=row.goods_status, - now=now, - ) - return { - "id": row.id, - "targetPlatform": row.target_platform, - "internalSkuKey": row.internal_sku_key, - "campaignKey": row.campaign_key, - "campaignName": row.campaign_name, - "commodityId": row.commodity_id, - "goodsName": row.goods_name, - "requiredPoints": row.required_points, - "scope": row.scope, - "saleMode": mode, - "availableFrom": row.available_from, - "availableUntil": row.available_until, - "releasedAt": row.released_at, - "goodsStatus": row.goods_status, - "availabilityState": availability, - "enabled": row.enabled, - "version": row.version, - "archivedAt": row.archived_at, - "affectedTasks": _mapping_impact(db, row), - "updatedAt": row.updated_at, - } - - -def list_mappings( - db: Session, - *, - keyword: str = "", - sale_mode: str = "", - enabled: bool | None = None, - include_archived: bool = False, -) -> list[dict[str, Any]]: - query = db.query(PlatformCommodityMapping).filter( - PlatformCommodityMapping.target_platform == TARGET_PLATFORM - ) - if not include_archived: - query = query.filter(PlatformCommodityMapping.archived_at.is_(None)) - if enabled is not None: - query = query.filter(PlatformCommodityMapping.enabled.is_(enabled)) - if sale_mode: - query = query.filter( - PlatformCommodityMapping.sale_mode - == classification.normalize_sale_mode(sale_mode) - ) - text = keyword.strip() - if text: - pattern = f"%{text}%" - query = query.filter( - or_( - PlatformCommodityMapping.internal_sku_key.ilike(pattern), - PlatformCommodityMapping.commodity_id.ilike(pattern), - PlatformCommodityMapping.goods_name.ilike(pattern), - PlatformCommodityMapping.campaign_key.ilike(pattern), - PlatformCommodityMapping.campaign_name.ilike(pattern), - ) - ) - rows = query.order_by( - PlatformCommodityMapping.archived_at.asc(), - PlatformCommodityMapping.enabled.desc(), - PlatformCommodityMapping.updated_at.desc(), - ).limit(500).all() - now = datetime.now(UTC) - return [_mapping_out(db, row, now=now) for row in rows] - - -def _validate_mapping_window( - available_from: datetime | None, - available_until: datetime | None, -) -> None: - if ( - available_from is not None - and available_until is not None - and available_from >= available_until - ): - raise HTTPException(status_code=400, detail="商品开放时间必须早于结束时间") - - -def _disable_other_current_mappings( - db: Session, - *, - row: PlatformCommodityMapping, -) -> None: - others = ( - db.query(PlatformCommodityMapping) - .filter( - PlatformCommodityMapping.id != row.id, - PlatformCommodityMapping.target_platform == row.target_platform, - PlatformCommodityMapping.internal_sku_key == row.internal_sku_key, - PlatformCommodityMapping.enabled.is_(True), - PlatformCommodityMapping.archived_at.is_(None), - ) - .all() - ) - for other in others: - other.enabled = False - other.version = int(other.version or 1) + 1 - other.updated_at = _now() - - -def _reapply_mapping_tasks( - db: Session, - *, - row: PlatformCommodityMapping, - current: User, -) -> None: - pending = db.query(PlatformFulfillmentTask).filter( - PlatformFulfillmentTask.internal_sku_key == row.internal_sku_key, - PlatformFulfillmentTask.account_id.is_(None), - PlatformFulfillmentTask.execution_status.in_( - ["pending_mapping", "ready", "manual_required"] - ), - ) - pending = _apply_order_match_cutoff(pending, _order_match_started_at(db)) - task_ids: list[int] = [] - for task in pending.all(): - _apply_mapping(task, row if row.enabled else None) - task.updated_at = _now() - task.next_allocate_at = ( - _now() - if task.execution_status == "ready" and task.account_id is None - else None - ) - _append_event( - db, - task.id, - "mapping_updated", - actor_type="user", - actor_id=current.id, - detail={ - "mappingId": row.id, - "commodityId": row.commodity_id, - "goodsName": row.goods_name, - "saleMode": row.sale_mode, - "campaignKey": row.campaign_key, - "enabled": row.enabled, - }, - ) - _emit_order_site_binding_state(db, task.id) - task_ids.append(int(task.id)) - if task_ids: - from .auto_allocator import wake_auto_allocator - - wake_auto_allocator(task_ids) - - -def _write_mapping( - db: Session, - row: PlatformCommodityMapping, - *, - internal_sku_key: str, - campaign_key: str, - campaign_name: str, - commodity_id: str, - goods_name: str, - required_points: int | None, - sale_mode: str, - available_from: datetime | None, - available_until: datetime | None, - released_at: datetime | None, - enabled: bool, - current: User, -) -> None: - sku_key = internal_sku_key.strip() - campaign = campaign_key.strip() - commodity = commodity_id.strip() - if not sku_key or not campaign or not commodity: - raise HTTPException( - status_code=400, - detail="内部 SKU、活动批次和斗鱼商品 ID 不能为空", - ) - _validate_mapping_window(available_from, available_until) - goods = ( - db.query(DouyuGoodsSnapshot) - .filter(DouyuGoodsSnapshot.commodity_id == commodity) - .order_by(DouyuGoodsSnapshot.id.desc()) - .first() - ) - row.target_platform = TARGET_PLATFORM - row.scope = SCOPE_ELITE - row.internal_sku_key = sku_key - row.campaign_key = campaign - row.campaign_name = campaign_name.strip() - row.commodity_id = commodity - row.goods_name = (goods_name or (goods.name if goods else "")).strip() - row.required_points = ( - int(required_points) - if required_points is not None - else (int(goods.score) if goods and goods.score is not None else None) - ) - row.sale_mode = classification.normalize_sale_mode(sale_mode) - row.available_from = available_from - row.available_until = available_until - row.released_at = released_at - row.goods_status = str(goods.status if goods else "").strip() - row.enabled = bool(enabled) - row.updated_at = _now() - row.version = max(1, int(row.version or 1)) - db.flush() - if row.enabled: - _disable_other_current_mappings(db, row=row) - _reapply_mapping_tasks(db, row=row, current=current) - db.commit() - - -def create_mapping( - db: Session, - *, - internal_sku_key: str, - campaign_key: str, - campaign_name: str, - commodity_id: str, - goods_name: str, - required_points: int | None, - sale_mode: str, - available_from: datetime | None, - available_until: datetime | None, - released_at: datetime | None, - enabled: bool, - current: User, -) -> dict[str, Any]: - row = PlatformCommodityMapping( - target_platform=TARGET_PLATFORM, - scope=SCOPE_ELITE, - internal_sku_key=internal_sku_key.strip(), - campaign_key=campaign_key.strip(), - commodity_id=commodity_id.strip(), - created_by=current.id, - created_at=_now(), - updated_at=_now(), - version=1, - ) - duplicate = ( - db.query(PlatformCommodityMapping.id) - .filter( - PlatformCommodityMapping.target_platform == TARGET_PLATFORM, - PlatformCommodityMapping.internal_sku_key == internal_sku_key.strip(), - PlatformCommodityMapping.campaign_key == campaign_key.strip(), - ) - .first() - ) - if duplicate: - raise HTTPException(status_code=409, detail="该 SKU 的活动批次映射已存在") - db.add(row) - _write_mapping( - db, - row, - internal_sku_key=internal_sku_key, - campaign_key=campaign_key, - campaign_name=campaign_name, - commodity_id=commodity_id, - goods_name=goods_name, - required_points=required_points, - sale_mode=sale_mode, - available_from=available_from, - available_until=available_until, - released_at=released_at, - enabled=enabled, - current=current, - ) - return _mapping_out(db, row) - - -def update_mapping( - db: Session, - *, - mapping_id: int, - **values: Any, -) -> dict[str, Any]: - row = db.get(PlatformCommodityMapping, int(mapping_id)) - if row is None or row.target_platform != TARGET_PLATFORM: - raise HTTPException(status_code=404, detail="商品映射不存在") - if row.archived_at is not None: - raise HTTPException(status_code=409, detail="已归档映射不能编辑,请先恢复") - current = values.pop("current") - duplicate = ( - db.query(PlatformCommodityMapping.id) - .filter( - PlatformCommodityMapping.id != row.id, - PlatformCommodityMapping.target_platform == TARGET_PLATFORM, - PlatformCommodityMapping.internal_sku_key - == str(values.get("internal_sku_key") or "").strip(), - PlatformCommodityMapping.campaign_key - == str(values.get("campaign_key") or "").strip(), - ) - .first() - ) - if duplicate: - raise HTTPException(status_code=409, detail="该 SKU 的活动批次映射已存在") - row.version = int(row.version or 1) + 1 - _write_mapping(db, row, current=current, **values) - return _mapping_out(db, row) - - -def set_mapping_enabled( - db: Session, - *, - mapping_id: int, - enabled: bool, - current: User, -) -> dict[str, Any]: - row = db.get(PlatformCommodityMapping, int(mapping_id)) - if row is None or row.target_platform != TARGET_PLATFORM: - raise HTTPException(status_code=404, detail="商品映射不存在") - if row.archived_at is not None: - raise HTTPException(status_code=409, detail="已归档映射不能启停,请先恢复") - row.enabled = bool(enabled) - row.version = int(row.version or 1) + 1 - row.updated_at = _now() - db.flush() - if enabled: - _disable_other_current_mappings(db, row=row) - _reapply_mapping_tasks(db, row=row, current=current) - db.commit() - return _mapping_out(db, row) - - -def archive_mapping( - db: Session, - *, - mapping_id: int, - current: User, -) -> dict[str, Any]: - row = db.get(PlatformCommodityMapping, int(mapping_id)) - if row is None or row.target_platform != TARGET_PLATFORM: - raise HTTPException(status_code=404, detail="商品映射不存在") - row.enabled = False - row.archived_at = _now() - row.archived_by = current.id - row.version = int(row.version or 1) + 1 - row.updated_at = _now() - _reapply_mapping_tasks(db, row=row, current=current) - db.commit() - return _mapping_out(db, row) - - -def restore_mapping( - db: Session, - *, - mapping_id: int, -) -> dict[str, Any]: - row = db.get(PlatformCommodityMapping, int(mapping_id)) - if row is None or row.target_platform != TARGET_PLATFORM: - raise HTTPException(status_code=404, detail="商品映射不存在") - row.archived_at = None - row.archived_by = None - row.enabled = False - row.version = int(row.version or 1) + 1 - row.updated_at = _now() - db.commit() - return _mapping_out(db, row) - - -def delete_mapping(db: Session, *, mapping_id: int) -> None: - row = db.get(PlatformCommodityMapping, int(mapping_id)) - if row is None or row.target_platform != TARGET_PLATFORM: - raise HTTPException(status_code=404, detail="商品映射不存在") - referenced = ( - db.query(PlatformFulfillmentTask.id) - .filter(PlatformFulfillmentTask.commodity_mapping_id == row.id) - .first() - ) - if referenced: - raise HTTPException(status_code=409, detail="映射已被任务引用,只能归档") - db.delete(row) - db.commit() - - -def mapping_impact(db: Session, *, mapping_id: int) -> dict[str, Any]: - row = db.get(PlatformCommodityMapping, int(mapping_id)) - if row is None or row.target_platform != TARGET_PLATFORM: - raise HTTPException(status_code=404, detail="商品映射不存在") - rows = ( - db.query( - PlatformFulfillmentTask.execution_status, - PlatformFulfillmentTask.sale_mode, - func.count(PlatformFulfillmentTask.id), - ) - .filter( - PlatformFulfillmentTask.internal_sku_key == row.internal_sku_key, - PlatformFulfillmentTask.account_id.is_(None), - ) - .group_by( - PlatformFulfillmentTask.execution_status, - PlatformFulfillmentTask.sale_mode, - ) - .all() - ) - return { - "mappingId": row.id, - "internalSkuKey": row.internal_sku_key, - "affectedTasks": sum(int(count) for _status, _mode, count in rows), - "groups": [ - { - "executionStatus": status, - "saleMode": mode, - "count": int(count), - } - for status, mode, count in rows - ], - } - - -def upsert_mapping( - db: Session, - *, - internal_sku_key: str, - commodity_id: str, - goods_name: str, - required_points: int | None, - enabled: bool, - current: User, - campaign_key: str = "douyu-current", - campaign_name: str = "", - sale_mode: str = "unknown", - available_from: datetime | None = None, - available_until: datetime | None = None, - released_at: datetime | None = None, -) -> dict[str, Any]: - row = ( - db.query(PlatformCommodityMapping) - .filter( - PlatformCommodityMapping.target_platform == TARGET_PLATFORM, - PlatformCommodityMapping.internal_sku_key == internal_sku_key.strip(), - PlatformCommodityMapping.campaign_key == campaign_key.strip(), - ) - .first() - ) - values = { - "internal_sku_key": internal_sku_key, - "campaign_key": campaign_key, - "campaign_name": campaign_name, - "commodity_id": commodity_id, - "goods_name": goods_name, - "required_points": required_points, - "sale_mode": sale_mode, - "available_from": available_from, - "available_until": available_until, - "released_at": released_at, - "enabled": enabled, - "current": current, - } - if row is None: - return create_mapping(db, **values) - return update_mapping(db, mapping_id=row.id, **values) - - -def _cached_capability_state( - candidate: CapabilityCandidate, - *, - commodity_id: str, -) -> DouyuLiveAccountState: - """把新鲜本地能力快照转换成统一的履约状态,不访问斗鱼官网。""" - account = candidate.account - state = candidate.state - availability = allocation_availability( - state.account_eligibility, - state.offer_state, - ) - if availability == AVAILABILITY_AVAILABLE: - reason = "" - elif availability == AVAILABILITY_LIMITED: - reason = "该账号已达此商品兑换上限" - elif availability == AVAILABILITY_NOT_OPEN: - reason = ( - f"限时兑换未开始,开始于 {state.available_from.isoformat()}" - if state.available_from - else "活动尚未开放兑换" - ) - else: - reason = str(state.blocking_reason or "") - return DouyuLiveAccountState( - account_id=int(account.id), - account_name=account.nickname or account.username or f"#{account.id}", - checked_at=state.observed_at or _now(), - ck_verdict="valid", - ck_message="本地能力快照关联账号 CK 有效", - elite_opened=account.elite_opened, - points=account.points, - limited_ids=frozenset(), - role_change_available_at=account.role_change_available_at, - commodity_availability={commodity_id: availability}, - commodity_blocking_reasons=( - {commodity_id: reason} if reason else {} - ), - ) - - -def _capability_availability_counts( - db: Session, - *, - commodity_id: str, - scope: str, - now: datetime, -) -> dict[str, Any]: - base = db.query(AccountCommodityState).filter( - AccountCommodityState.platform == TARGET_PLATFORM, - AccountCommodityState.scope == scope, - AccountCommodityState.commodity_id == commodity_id, - AccountCommodityState.valid_until.isnot(None), - AccountCommodityState.valid_until > now, - ) - eligibility_rows = ( - base.with_entities( - AccountCommodityState.account_eligibility, - func.count(AccountCommodityState.id), - ) - .group_by(AccountCommodityState.account_eligibility) - .all() - ) - offer_rows = ( - db.query(AccountCommodityState.offer_state, func.count(AccountCommodityState.id)) - .filter( - AccountCommodityState.platform == TARGET_PLATFORM, - AccountCommodityState.scope == scope, - AccountCommodityState.commodity_id == commodity_id, - AccountCommodityState.valid_until.isnot(None), - AccountCommodityState.valid_until > now, - ) - .group_by(AccountCommodityState.offer_state) - .all() - ) - stock_rows = ( - db.query(AccountCommodityState.stock_state, func.count(AccountCommodityState.id)) - .filter( - AccountCommodityState.platform == TARGET_PLATFORM, - AccountCommodityState.scope == scope, - AccountCommodityState.commodity_id == commodity_id, - AccountCommodityState.valid_until.isnot(None), - AccountCommodityState.valid_until > now, - ) - .group_by(AccountCommodityState.stock_state) - .all() - ) - eligible_account_ids = ( - select(AccountCommodityState.account_id) - .where( - AccountCommodityState.platform == TARGET_PLATFORM, - AccountCommodityState.scope == scope, - AccountCommodityState.commodity_id == commodity_id, - AccountCommodityState.account_eligibility == "eligible", - AccountCommodityState.offer_state.in_((OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)), - AccountCommodityState.valid_until.isnot(None), - AccountCommodityState.valid_until > now, - ) - .distinct() - ) - account_base = db.query(Account).filter(Account.id.in_(eligible_account_ids)) - eligible_accounts = int(account_base.count()) - role_ready_accounts = int( - account_base.filter(role_change_ready_filter(now)).count() - ) - leased_accounts = int(account_base.filter(active_lease_exists()).count()) - collab_accounts = int( - account_base.filter(active_collab_order_exists()).count() - ) - allocatable_accounts = int( - account_base.filter( - cookie_present_filter(), - valid_ck_filter(), - automatable_account_filter(), - assigned_to_pool_filter(), - role_change_ready_filter(now), - ~active_lease_exists(), - ~active_collab_order_exists(), - ).count() - ) - next_role_ready_at = ( - account_base.filter( - Account.role_change_available_at.isnot(None), - Account.role_change_available_at > now, - ) - .with_entities(func.min(Account.role_change_available_at)) - .scalar() - ) - return { - **{ - f"eligibility:{key}": int(count or 0) - for key, count in eligibility_rows - }, - **{f"offer:{key}": int(count or 0) for key, count in offer_rows}, - **{f"stock:{key}": int(count or 0) for key, count in stock_rows}, - "account:eligible": eligible_accounts, - "account:roleReady": role_ready_accounts, - "account:roleCooldown": max(0, eligible_accounts - role_ready_accounts), - "account:leased": leased_accounts, - "account:activeCollab": collab_accounts, - "account:allocatable": allocatable_accounts, - "account:nextRoleReadyAt": _jsonable(next_role_ready_at), - } - - -def _local_allocation_retry_at( - db: Session, - *, - task: PlatformFulfillmentTask, - now: datetime, - availability_counts: dict[str, int], - lease_conflict: bool, -) -> tuple[datetime, str]: - """按本地状态决定下一轮时间,避免永久无库存任务每 45 秒占槽。""" - if lease_conflict: - return ( - now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS), - "lease_conflict", - ) - next_open_at = ( - db.query(func.min(AccountCommodityState.available_from)) - .filter( - AccountCommodityState.platform == TARGET_PLATFORM, - AccountCommodityState.scope == (task.scope or SCOPE_ELITE), - AccountCommodityState.commodity_id == task.commodity_id, - AccountCommodityState.offer_state == OFFER_STATE_BEFORE, - AccountCommodityState.available_from.isnot(None), - AccountCommodityState.available_from > now, - ) - .scalar() - ) - if next_open_at is not None: - return next_open_at + timedelta(seconds=5), "commodity_not_open" - if availability_counts.get(f"offer:{OFFER_STATE_BEFORE}"): - return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "commodity_not_open" - has_capability_rows = any( - int(value or 0) - for key, value in availability_counts.items() - if key.startswith(("eligibility:", "offer:", "stock:")) - ) - if has_capability_rows: - if int(availability_counts.get("account:allocatable") or 0) > 0: - return ( - now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS), - "lease_conflict", - ) - if int(availability_counts.get("account:roleCooldown") or 0) > 0: - return ( - now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), - "account_role_cooldown", - ) - if int(availability_counts.get("account:eligible") or 0) > 0: - return ( - now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), - "account_pool_busy", - ) - return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "no_eligible_account" - return now + timedelta(seconds=LOCAL_CACHE_MISS_RETRY_SECONDS), "capability_cache_miss" - - -def _seed_capability_refresh( - db: Session, - *, - task: PlatformFulfillmentTask, - now: datetime, -) -> int: - """能力池不足时只入队独立同步槽,不在分配线程里请求官网。""" - try: - seed_limit = int( - os.getenv("PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT", "20") - ) - except ValueError: - seed_limit = 20 - seed_limit = max(1, min(seed_limit, 100)) - try: - target_pending = max( - 1, - int(os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "60")), - ) - except ValueError: - target_pending = 60 - pending = active_account_work_count( - db, - work_types=ACCOUNT_SYNC_WORK_TYPES, - ) - headroom = max(0, target_pending - pending) - if headroom <= 0: - return 0 - accounts = capability_refresh_candidate_accounts( - db, - commodity_ids=[task.commodity_id], - scope=task.scope or SCOPE_ELITE, - limit=min(seed_limit, headroom), - now=now, - ) - for account in accounts: - enqueue_account_work( - db, - account_id=int(account.id), - work_type=WORK_STOREHOME_SYNC, - priority=20, - due_at=now, - reason=f"履约任务 #{task.id} 缺少商品能力快照", - payload={ - "commodity_id": task.commodity_id, - "platform_task_id": int(task.id), - }, - ) - return len(accounts) - - -def _allocate_task_from_capability( - db: Session, - *, - task: PlatformFulfillmentTask, - current: User, -) -> dict[str, Any]: - """只用本地能力索引选号;外部资格查询留给独立同步队列。""" - moment = _now() - required_points = int(task.required_points or 0) - try: - candidate_limit = int( - os.getenv( - "PLATFORM_FULFILLMENT_CAPABILITY_CANDIDATE_LIMIT", - str(DEFAULT_CAPABILITY_CANDIDATE_LIMIT), - ) - ) - except ValueError: - candidate_limit = DEFAULT_CAPABILITY_CANDIDATE_LIMIT - candidate_limit = max(1, min(candidate_limit, 100)) - is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale" - capability_candidates = capability_candidate_rows( - db, - limit=candidate_limit, - required_points=required_points, - commodity_id=task.commodity_id, - scope=task.scope or SCOPE_ELITE, - now=moment, - allow_before_open=is_presale, - ) - recent_exchange_ids: set[int] = set() - if capability_candidates: - candidate_ids = [int(item.account.id) for item in capability_candidates] - since = moment - timedelta(days=365) - recent_exchange_ids = { - int(account_id) - for (account_id,) in ( - db.query(AccountEvent.account_id) - .filter( - AccountEvent.account_id.in_(candidate_ids), - AccountEvent.event_type == "exchange", - AccountEvent.subject_key == task.commodity_id, - AccountEvent.occurred_at >= since, - ) - .distinct() - .all() - ) - } - - diagnostics: list[dict[str, Any]] = [] - qualified: list[tuple[CapabilityCandidate, DouyuLiveAccountState]] = [] - for candidate in capability_candidates: - account_id = int(candidate.account.id) - if account_id in recent_exchange_ids: - diagnostics.append( - { - "accountId": account_id, - "accountName": candidate.account.nickname - or candidate.account.username, - "reasons": ["365 天内已有该商品兑换事件"], - "source": "capability", - } - ) - continue - qualified.append( - ( - candidate, - _cached_capability_state( - candidate, - commodity_id=task.commodity_id, - ), - ) - ) - - qualified.sort( - key=lambda item: ( - item[1].readiness_rank(required_points=required_points), - int(item[1].points or 0), - int(item[0].account.id), - ) - ) - selected: CapabilityCandidate | None = None - selected_state: DouyuLiveAccountState | None = None - lease = None - lease_duration_minutes = _lease_duration_minutes(db) - for candidate, cached_state in qualified: - account = candidate.account - candidate_model = AccountCandidate( - account_id=int(account.id), - username=str(account.username or ""), - nickname=str(account.nickname or ""), - points=int(cached_state.points or 0), - gold_balance=account.gold_balance, - points_expire_at=account.points_expire_at, - role_change_available_at=account.role_change_available_at, - ) - lease = lease_account( - db, - candidate=candidate_model, - holder_user_id=current.id, - task_id=task.id, - commodity_id=task.commodity_id, - ttl_minutes=lease_duration_minutes, - commit=False, - ) - if lease is not None: - selected = candidate - selected_state = cached_state - break - diagnostics.append( - { - "accountId": int(account.id), - "accountName": cached_state.account_name, - "reasons": ["账号刚被其他任务占用"], - "source": "capability", - } - ) - - if selected is None or selected_state is None or lease is None: - availability_counts = _capability_availability_counts( - db, - commodity_id=task.commodity_id, - scope=task.scope or SCOPE_ELITE, - now=moment, - ) - retry_at, retry_reason = _local_allocation_retry_at( - db, - task=task, - now=moment, - availability_counts=availability_counts, - lease_conflict=bool(qualified), - ) - refresh_queued = ( - _seed_capability_refresh(db, task=task, now=moment) - if retry_reason - in { - "capability_cache_miss", - "account_role_cooldown", - "account_pool_busy", - } - else 0 - ) - if retry_reason == "commodity_not_open": - task.issue_code = "commodity_not_open" - task.last_error = "该商品尚未到开放时间,已按开放时间安排重新选号" - elif retry_reason == "capability_cache_miss": - task.issue_code = "capability_cache_miss" - task.last_error = "暂无该商品的新鲜账号兑换资格,等待后台刷新" - elif retry_reason == "lease_conflict": - task.issue_code = "account_lease_conflict" - task.last_error = "已找到候选账号,但刚被其他任务占用" - elif retry_reason == "account_role_cooldown": - task.issue_code = "account_role_cooldown" - task.last_error = ( - "已有具备兑换资格的账号,但都处于斗鱼换绑冷却期;" - "后台正在继续补充未绑定角色的可用账号" - ) - elif retry_reason == "account_pool_busy": - task.issue_code = "account_pool_busy" - task.last_error = ( - "已有具备兑换资格的账号,但当前被租约或外部协作单占用;" - "后台正在继续补充可用账号" - ) - else: - task.issue_code = "no_eligible_account" - task.last_error = "本地能力池暂无可用账号" - task.execution_status = "ready" - task.next_allocate_at = retry_at - task.updated_at = moment - _append_event( - db, - task.id, - "account_allocation_failed", - detail={ - "candidateCount": len(capability_candidates), - "matchingMode": "capability", - "strategy": "local_capability", - "capabilityCandidates": len(capability_candidates), - "availabilityCounts": availability_counts, - "retryAt": _jsonable(retry_at), - "retryReason": retry_reason, - "refreshQueued": refresh_queued, - "diagnostics": diagnostics[:20], - }, - ) - _emit_order_site_binding_state(db, task.id) - db.commit() - return get_task_detail(db, task.id) - - selected_account = selected.account - task.account_id = selected_account.id - task.lease_id = lease.id - task.operator_id = current.id - task.execution_status = "allocated" - task.next_allocate_at = None - task.binding_status = "not_started" - soft_reasons = selected_state.soft_requirement_reasons( - required_points=required_points - ) - gate_status, gate_issue, gate_message = _exchange_gate( - selected_state, - task.commodity_id, - allow_not_open=is_presale, - ) - if gate_status: - task.exchange_status = gate_status - task.issue_code = gate_issue - task.last_error = gate_message - elif selected_state.elite_opened is not True: - task.exchange_status = "not_opened" - task.issue_code = "elite_not_opened" - task.last_error = "账号尚未开通精英宝典,可开通后继续" - elif selected_state.points is None or selected_state.points < required_points: - task.exchange_status = "points_short" - task.issue_code = "points_short" - task.last_error = "账号积分不足,可充值后继续" - else: - task.exchange_status = "eligible" - task.issue_code = "" - task.last_error = "" - task.updated_at = moment - _apply_task_lease_policy(db, task, lease=lease) - _append_event( - db, - task.id, - "account_allocated", - actor_type="user", - actor_id=current.id, - detail={ - "accountId": selected_account.id, - "accountName": selected_state.account_name, - "points": selected_state.points, - "eliteOpened": selected_state.elite_opened, - "softReasons": soft_reasons, - "exchangeStatus": task.exchange_status, - "allocationStrategy": "local_capability", - "capabilityObservedAt": _jsonable(selected.state.observed_at), - "capabilityValidUntil": _jsonable(selected.state.valid_until), - }, - ) - _emit_order_site_binding_state(db, task.id) - db.commit() - return get_task_detail(db, task.id) - - -def prepare_manual_allocation( - db: Session, - *, - task_id: int, - current: User, -) -> dict[str, Any]: - """在短请求内完成人工选号校验,并把任务标记为立即可领取。 - - 真正的官网账号检测由后台 auto allocator 执行。这样 API 请求不会在多次外部 - HTTP 调用期间一直持有数据库事务,也不会因为重复点击占满连接池。 - """ - task = _load_task(db, task_id) - if task.execution_status in {"completed", "cancelled"}: - raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号") - if not task.commodity_id or not task.required_points: - raise HTTPException(status_code=409, detail="请先完成商品映射") - if task.account_id and task.lease_id: - lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if lease and lease.status == "active": - return get_task_detail(db, task.id) - if task.execution_status != "ready": - raise HTTPException(status_code=409, detail="只有待分配任务可以重新选号") - task.next_allocate_at = _now() - task.updated_at = _now() - db.flush() - return get_task_detail(db, task.id) - - -def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]: - task = _load_task(db, task_id) - if task.execution_status in {"completed", "cancelled"}: - raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号") - if not task.commodity_id or not task.required_points: - raise HTTPException(status_code=409, detail="请先完成商品映射") - if task.account_id and task.lease_id: - lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if lease and lease.status == "active": - return get_task_detail(db, task.id) - # 阶段 5:生产选号只允许读取本地能力索引。官网查询由 - # account_sync_queue/商品能力补货完成,绑码与兑换前各自实时复核。 - return _allocate_task_from_capability( - db, - task=task, - current=current, - ) - - -def release_task_account( - db: Session, - *, - task_id: int, - current: User, - reason: str = "manual_release", -) -> dict[str, Any]: - task = _load_task(db, task_id) - lease = ( - db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if task.lease_id - else None - ) - retained = _retain_lease_for_active_collab( - db, - task=task, - lease=lease, - current=current, - reason="platform_released_to_collab", - ) - if retained is None: - release_lease(db, lease, reason=reason, commit=False) - task.account_id = None - task.lease_id = None - task.bind_task_id = None - task.execution_status = "ready" - task.binding_status = "not_started" - task.exchange_status = "not_started" - task.issue_code = "" - task.last_error = "" - task.updated_at = _now() - _append_event( - db, - task.id, - "account_released", - actor_type="user", - actor_id=current.id, - detail={"reason": reason}, - ) - _emit_order_site_binding_state(db, task.id) - db.commit() - return get_task_detail(db, task.id) - - -def reset_task_binding( - db: Session, - *, - task_id: int, - current: User, - reason: str = "客服重置角色绑定", -) -> dict[str, Any]: - """清空本单旧绑定与客户资料,保留账号租约供客户重新扫码。""" - task = _load_task(db, task_id) - if task.execution_status in {"completed", "cancelled"}: - raise HTTPException(status_code=409, detail="已结束任务不能重置绑定") - if task.binding_status != "failed": - raise HTTPException( - status_code=409, detail="只有绑定失败的任务可以重置角色资料" - ) - if not task.account_id or not task.lease_id: - raise HTTPException(status_code=409, detail="当前任务没有可保留的履约账号") - - lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if lease is None or lease.status != "active": - raise HTTPException( - status_code=409, detail="账号租约已失效,请释放账号后重新选号" - ) - - previous_bind_task_id = task.bind_task_id - previous_bind_task = ( - db.query(DouyuTask).filter(DouyuTask.id == previous_bind_task_id).first() - if previous_bind_task_id - else None - ) - if previous_bind_task and previous_bind_task.status in { - "planned", - "pending", - "running", - }: - raise HTTPException(status_code=409, detail="当前绑定任务仍在执行,不能重置") - - previous_binding_status = task.binding_status - previous_issue_code = task.issue_code - task.bind_task_id = None - task.binding_status = "not_started" - task.execution_status = "allocated" - task.exchange_status = "not_started" - task.issue_code = "" - task.last_error = "" - task.operator_id = current.id - task.updated_at = _now() - _apply_task_lease_policy(db, task, lease=lease) - _append_event( - db, - task.id, - "binding_reset", - actor_type="user", - actor_id=current.id, - detail={ - "reason": reason.strip()[:1000], - "previousBindTaskId": previous_bind_task_id, - "previousBindingStatus": previous_binding_status, - "previousIssueCode": previous_issue_code, - "customerProfileReset": True, - }, - ) - _emit_order_site_binding_state( - db, - task.id, - extra={ - "customerProfileReset": True, - "resetReason": reason.strip()[:1000], - }, - ) - db.commit() - return get_task_detail(db, task.id) - - -def start_binding_sync( - db: Session, - *, - task_id: int, - current: User, - force_refresh: bool = False, -) -> dict[str, Any]: - task = _load_task_for_update(db, task_id) - if not task.account_id or not task.lease_id: - raise HTTPException(status_code=409, detail="请先分配账号") - lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if lease is None or lease.status != "active": - raise HTTPException(status_code=409, detail="账号租约已失效,请重新分配") - if task.bind_task_id: - existing = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() - if existing: - result = existing.result or {} - pending_role = pending_binding_role_from_result(result) - stale_pending = ( - bool(result.get("bind_ready_for_confirm")) and not pending_role - ) - if bool(result.get("bind_confirmed")) or pending_role: - return get_task_detail(db, task.id) - if existing.status in {"planned", "pending", "running"}: - return get_task_detail(db, task.id) - if ( - existing.status == "success" - and not _binding_qr_expired(existing) - and not stale_pending - ): - return get_task_detail(db, task.id) - if not force_refresh and existing.status not in { - "success", - "failed", - "error", - "stopped", - }: - return get_task_detail(db, task.id) - - batch_id = f"pfbind-{task.id}-{uuid.uuid4().hex[:8]}" - bind_task = DouyuTask( - batch_id=batch_id, - account_id=task.account_id, - account_assigned_to=current.id, - task_type="get_bind_qr", - handbook_scope="elite", - status="planned", - message="等待生成绑定二维码", - result={"payload": {}}, - created_by=current.id, - platform_task_id=task.id, - ) - db.add(bind_task) - try: - db.flush() - except IntegrityError: - # The database uniqueness gate wins a race that started before either - # request could acquire the fulfillment row lock. - db.rollback() - return get_task_detail(db, task_id) - account = db.query(Account).filter(Account.id == task.account_id).first() - if account is not None: - record_douyu_task_started( - db, - account, - task_id=int(bind_task.id), - task_type="get_bind_qr", - task_label="获取绑定二维码", - scope="elite", - actor_id=current.id, - ) - task.bind_task_id = bind_task.id - task.binding_status = "preparing" - task.execution_status = "waiting_bind" - task.issue_code = "" - task.last_error = "" - task.operator_id = current.id - task.updated_at = _now() - _apply_task_lease_policy(db, task, lease=lease) - _append_event( - db, - task.id, - "binding_started", - actor_type="user", - actor_id=current.id, - detail={"bindTaskId": bind_task.id}, - ) - _emit_order_site_binding_state(db, task.id) - db.commit() - start_douyu_batch( - batch_id=batch_id, - task_type="get_bind_qr", - payload={}, - concurrency=1, - capture_event_loop=False, - ) - return get_task_detail(db, task.id) - - -async def start_binding( - db: Session, - *, - task_id: int, - current: User, - force_refresh: bool = False, -) -> dict[str, Any]: - """Run the blocking DB/network dispatch path outside the ASGI event loop.""" - return await run_in_threadpool( - start_binding_sync, - db, - task_id=task_id, - current=current, - force_refresh=force_refresh, - ) - - -def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: - task = _load_task(db, task_id) - if task.execution_status in {"completed", "cancelled"}: - return get_task_detail(db, task.id) - if not task.bind_task_id: - return get_task_detail(db, task.id) - bind_task = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() - if bind_task is None: - return get_task_detail(db, task.id) - before = ( - task.binding_status, - task.execution_status, - task.exchange_status, - task.issue_code, - task.last_error, - ) - result = bind_task.result or {} - pending_role = pending_binding_role_from_result(result) - if bind_task.status in {"failed", "error", "stopped"}: - task.binding_status = "failed" - task.execution_status = "manual_required" - task.issue_code = _binding_failure_issue(bind_task, result) - task.last_error = _customer_task_message(task) - elif bool(result.get("bind_confirmed")): - task.binding_status = "bound" - task.execution_status = "bound" - task.issue_code = "" - task.last_error = "" - elif pending_role: - task.binding_status = "role_ready" - task.execution_status = "role_ready" - task.issue_code = "" - task.last_error = "" - elif bool(result.get("bind_ready_for_confirm")): - # 兼容旧快照:同名旧角色曾被误标为待确认。清掉绑定指针后,客户页会 - # 回到已分配状态,并在下一次刷新时自动生成新二维码、重新开始轮询。 - previous_bind_task_id = task.bind_task_id - task.bind_task_id = None - task.binding_status = "not_started" - task.execution_status = "allocated" - task.issue_code = "" - task.last_error = "" - task.updated_at = _now() - _append_event( - db, - task.id, - "binding_stale_role_ignored", - detail={ - "bindTaskId": previous_bind_task_id, - "roleName": str(result.get("role_name") or "")[:100], - "baselineRoleName": str( - result.get("baseline_role_name") - or result.get("current_role_name") - or "" - )[:100], - }, - ) - _emit_order_site_binding_state(db, task.id) - _apply_task_lease_policy(db, task) - db.commit() - return get_task_detail(db, task.id) - elif result.get("url"): - task.binding_status = "qr_pending" - task.execution_status = "waiting_bind" - task.issue_code = "" - task.last_error = "" - after = ( - task.binding_status, - task.execution_status, - task.exchange_status, - task.issue_code, - task.last_error, - ) - if after != before: - task.updated_at = _now() - if task.binding_status == "failed": - _append_event( - db, - task.id, - "binding_failed", - detail={ - "issueCode": task.issue_code, - "bindTaskId": bind_task.id, - "bindPhase": str(result.get("bind_phase") or ""), - "rawError": str(bind_task.message or "")[:1000], - }, - ) - _emit_order_site_binding_state(db, task.id) - _apply_task_lease_policy(db, task) - db.commit() - return get_task_detail(db, task.id) - - -def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int: - """斗鱼绑定任务落库后,把关联履约任务和 Outbox 一并刷新。""" - task_ids = [ - int(row.id) - for row in ( - db.query(PlatformFulfillmentTask.id) - .filter(PlatformFulfillmentTask.bind_task_id == int(douyu_task_id)) - .all() - ) - ] - for task_id in task_ids: - refresh_binding(db, task_id=task_id) - return len(task_ids) - - -def reconcile_binding_state_outbox( - db: Session, - *, - limit: int = 500, - after_task_id: int = 0, -) -> dict[str, Any]: - """按 ID 游标补齐 active 快照;批次只限制吞吐,不形成永久扫描窗口。""" - batch_size = max(1, min(limit, 500)) - normalized_after = max(0, int(after_task_id or 0)) - task_ids = [ - int(row.id) - for row in ( - db.query(PlatformFulfillmentTask.id) - .filter( - PlatformFulfillmentTask.id > normalized_after, - PlatformFulfillmentTask.execution_status.notin_( - ["completed", "cancelled"] - ), - ) - .order_by(PlatformFulfillmentTask.id.asc()) - .limit(batch_size) - .all() - ) - ] - queued = sum( - 1 for task_id in task_ids if _emit_order_site_binding_state(db, task_id) - ) - db.commit() - return { - "queued": queued, - "nextTaskId": max(task_ids, default=normalized_after), - "hasMore": len(task_ids) == batch_size, - } - - -def confirm_binding_sync( - db: Session, *, task_id: int, current: User -) -> dict[str, Any]: - task = _load_task_for_update(db, task_id) - task = _load_task(db, refresh_binding(db, task_id=task.id)["task"]["id"]) - if task.binding_status != "role_ready": - raise HTTPException(status_code=409, detail="当前没有待确认的游戏角色") - if not task.account_id or not task.lease_id: - raise HTTPException(status_code=409, detail="账号租约不存在") - lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if lease is None or lease.status != "active": - raise HTTPException(status_code=409, detail="账号租约已失效") - - current_bind_task = ( - db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() - if task.bind_task_id - else None - ) - current_bind_result = (current_bind_task.result or {}) if current_bind_task else {} - expected_role_name = str(current_bind_result.get("role_name") or "").strip() - baseline_role_name = str(current_bind_result.get("current_role_name") or "").strip() - batch_id = f"pfconfirm-{task.id}-{uuid.uuid4().hex[:8]}" - confirm_task = DouyuTask( - batch_id=batch_id, - account_id=task.account_id, - account_assigned_to=current.id, - task_type="confirm_bind", - handbook_scope="elite", - status="planned", - message="等待确认角色绑定", - result={ - "payload": {}, - "expected_role_name": expected_role_name, - "baseline_role_name": baseline_role_name, - }, - created_by=current.id, - platform_task_id=task.id, - ) - db.add(confirm_task) - db.flush() - account = db.query(Account).filter(Account.id == task.account_id).first() - if account is not None: - record_douyu_task_started( - db, - account, - task_id=int(confirm_task.id), - task_type="confirm_bind", - task_label="确认绑定", - scope="elite", - actor_id=current.id, - ) - task.bind_task_id = confirm_task.id - task.binding_status = "confirming" - task.execution_status = "binding_confirming" - task.operator_id = current.id - task.updated_at = _now() - _apply_task_lease_policy(db, task, lease=lease) - _append_event( - db, - task.id, - "binding_confirm_started", - actor_type="user", - actor_id=current.id, - detail={"confirmTaskId": confirm_task.id}, - ) - _emit_order_site_binding_state(db, task.id) - db.commit() - start_douyu_batch( - batch_id=batch_id, - task_type="confirm_bind", - payload={}, - concurrency=1, - capture_event_loop=False, - ) - return get_task_detail(db, task.id) - - -async def confirm_binding( - db: Session, *, task_id: int, current: User -) -> dict[str, Any]: - return await run_in_threadpool( - confirm_binding_sync, - db, - task_id=task_id, - current=current, - ) - - -def refresh_exchange_eligibility( - db: Session, *, task_id: int, current: User -) -> dict[str, Any]: - task = _load_task(db, task_id) - if task.binding_status != "bound": - raise HTTPException(status_code=409, detail="请先确认游戏角色绑定") - account = db.query(Account).filter(Account.id == task.account_id).first() - if account is None or not account.cookie: - raise HTTPException(status_code=409, detail="账号 CK 不可用") - config = ensure_douyu_config(db) - try: - probe = probe_account( - account, - config_mapping(config), - session_checker=None, - with_elite_role=False, - with_eligibility=True, - ) - if (probe.get("elite") or {}).get("status") != CAPABILITY_OK: - raise RuntimeError( - (probe.get("errors") or {}).get("elite") or "精英宝典状态查询失败" - ) - if "points" in (probe.get("errors") or {}): - raise RuntimeError((probe.get("errors") or {})["points"]) - limited_ids = frozenset( - str(item) - for item in (probe.get("eligibility") or {}).get("limited_ids") or [] - if str(item) - ) - persist_probe_result( - db, - account, - probe, - current=current, - source="platform.exchange_eligibility", - record_event=True, - ) - except Exception as exc: # noqa: BLE001 外部接口错误要落成可重试的检查失败 - record_account_query( - db, - account, - query_type="exchange_eligibility", - title="刷新兑换资格", - ok=False, - detail={"error": str(exc)[:1000], "commodity_id": task.commodity_id}, - actor_id=current.id, - ) - task.execution_status = "manual_required" - task.exchange_status = "check_failed" - task.issue_code = "eligibility_check_failed" - task.last_error = str(exc) - task.updated_at = _now() - _append_event( - db, - task.id, - "eligibility_check_failed", - actor_type="user", - actor_id=current.id, - detail={"error": str(exc)}, - ) - _emit_order_site_binding_state(db, task.id) - db.commit() - return get_task_detail(db, task.id) - - eligibility = probe.get("eligibility") or {} - storehome_goods = [ - dict(item) - for item in eligibility.get("storehome_goods") or [] - if isinstance(item, dict) - ] - assessments = classify_goods_items(storehome_goods, now=_now()) - assessment = assessments.get(task.commodity_id) - is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale" - if task.commodity_id in limited_ids: - account_eligibility = ACCOUNT_ELIGIBILITY_LIMITED - offer_state = assessment.offer_state if assessment else OFFER_STATE_UNKNOWN - stock_state = assessment.stock_state if assessment else STOCK_STATE_UNKNOWN - availability = AVAILABILITY_LIMITED - commodity_message = "该账号已达到此商品兑换上限" - elif assessments and assessment is None: - account_eligibility = ACCOUNT_ELIGIBILITY_UNKNOWN - offer_state = OFFER_STATE_NOT_OFFERED - stock_state = STOCK_STATE_UNKNOWN - availability = AVAILABILITY_NOT_OFFERED - commodity_message = "官方商品列表本次未返回该商品,可能已下架" - elif assessment is not None and assessment.availability != AVAILABILITY_AVAILABLE: - account_eligibility = assessment.account_eligibility - offer_state = assessment.offer_state - stock_state = assessment.stock_state - availability = assessment.availability - commodity_message = assessment.blocking_reason - else: - account_eligibility = ( - assessment.account_eligibility - if assessment is not None - else ACCOUNT_ELIGIBILITY_UNKNOWN - ) - offer_state = ( - assessment.offer_state if assessment is not None else OFFER_STATE_UNKNOWN - ) - stock_state = ( - assessment.stock_state if assessment is not None else STOCK_STATE_UNKNOWN - ) - availability = AVAILABILITY_AVAILABLE - commodity_message = "" - - gate_status, gate_issue, gate_message = exchange_gate_for_availability( - availability, - reason=commodity_message, - allow_not_open=is_presale, - ) - if gate_status: - task.exchange_status = gate_status - task.issue_code = gate_issue - task.last_error = gate_message - elif not account.elite_opened: - task.exchange_status = "not_opened" - task.issue_code = "elite_not_opened" - task.last_error = "该账号精英宝典未开通" - elif task.required_points and int(account.points or 0) < int(task.required_points): - task.exchange_status = "points_short" - task.issue_code = "points_short" - task.last_error = "该账号精英积分不足,需人工充值" - else: - task.exchange_status = "eligible" - task.issue_code = "" - task.last_error = "" - record_account_commodity_state( - db, - account, - commodity_id=task.commodity_id, - availability=availability, - account_eligibility=account_eligibility, - offer_state=offer_state, - stock_state=stock_state, - stock_count=assessment.stock_count if assessment is not None else None, - store_status=assessment.store_status if assessment is not None else None, - open_status=assessment.open_status if assessment is not None else None, - blocking_reason=commodity_message, - raw_status=( - assessment.raw_status - if assessment is not None - else "1" - if task.commodity_id in limited_ids - else "0" - ), - observed_at=_now(), - source="eligibility_check", - scope=task.scope or SCOPE_ELITE, - ) - record_account_query( - db, - account, - query_type="exchange_eligibility", - title="刷新兑换资格", - ok=True, - detail={ - "commodity_id": task.commodity_id, - "exchange_status": task.exchange_status, - "limited": task.commodity_id in limited_ids, - "account_eligibility": account_eligibility, - "offer_state": offer_state, - "stock_state": stock_state, - "availability": availability, - "issue_code": task.issue_code, - "points": account.points, - "elite_opened": account.elite_opened, - }, - actor_id=current.id, - ) - # 积分不足、未开通和限兑都不是流程终点:角色已经绑定,账号继续保留, - # 后续充值/开通/解除限兑后刷新资格即可。 - task.execution_status = "bound" - task.updated_at = _now() - account.updated_at = _now() - # waiting_release 的预售任务在这里切回无限租约,普通 bound 也遵循 - # “进行中默认无限”的状态策略。 - _apply_task_lease_policy(db, task) - _append_event( - db, - task.id, - "exchange_eligibility_checked", - actor_type="user", - actor_id=current.id, - detail={ - "exchangeStatus": task.exchange_status, - "limitedCount": len(limited_ids), - }, - ) - _emit_order_site_binding_state(db, task.id) - db.commit() - return get_task_detail(db, task.id) - - -def complete_manual_exchange( - db: Session, - *, - task_id: int, - current: User, - note: str = "", -) -> dict[str, Any]: - task = _load_task(db, task_id) - if task.binding_status != "bound": - raise HTTPException(status_code=409, detail="游戏角色尚未确认绑定") - if task.exchange_status not in {"eligible", "manual_done"}: - raise HTTPException( - status_code=409, - detail="当前兑换资格不是可兑换状态,请先刷新检查结果", - ) - lease = ( - db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if task.lease_id - else None - ) - task.exchange_status = "manual_done" - task.execution_status = "completed" - task.completed_at = _now() - task.operator_id = current.id - task.last_error = "" - task.issue_code = "" - task.updated_at = _now() - retained = _retain_lease_for_active_collab( - db, - task=task, - lease=lease, - current=current, - reason="platform_completed_but_collab_active", - ) - if retained is None: - # 2026-11-22:兑换完成不再一律立即释放。任务已完成但保留一段可配置 - # 的复核窗口;默认人工兑换完成后保留 120 分钟,期间仍可供截图与纠错。 - _apply_task_lease_policy( - db, - task, - lease=lease, - ) - _append_event( - db, - task.id, - "manual_exchange_completed", - actor_type="user", - actor_id=current.id, - detail={"note": note[:1000]}, - ) - _emit_order_site_binding_state(db, task.id) - db.commit() - return get_task_detail(db, task.id) - - -def mark_manual_required( - db: Session, - *, - task_id: int, - current: User, - reason: str, -) -> dict[str, Any]: - task = _load_task(db, task_id) - task.execution_status = "manual_required" - task.operator_id = current.id - task.last_error = reason.strip()[:2000] - task.issue_code = task.issue_code or "manual_required" - task.updated_at = _now() - _apply_task_lease_policy(db, task) - _append_event( - db, - task.id, - "marked_manual_required", - actor_type="user", - actor_id=current.id, - detail={"reason": task.last_error}, - ) - _emit_order_site_binding_state(db, task.id) - db.commit() - return get_task_detail(db, task.id) - - -def cancel_task( - db: Session, - *, - task_id: int, - current: User, - reason: str, -) -> dict[str, Any]: - task = _load_task(db, task_id) - if task.execution_status == "cancelled": - return get_task_detail(db, task.id) - if task.execution_status == "completed": - raise HTTPException(status_code=409, detail="已完成任务不能取消") - account_id = task.account_id - lease_id = task.lease_id - previous_execution_status = task.execution_status - previous_binding_status = task.binding_status - previous_exchange_status = task.exchange_status - lease = ( - db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if task.lease_id - else None - ) - linked_tasks = ( - db.query(DouyuTask) - .filter( - DouyuTask.id.in_( - [value for value in [task.bind_task_id, task.exchange_task_id] if value] - ) - ) - .all() - if task.bind_task_id or task.exchange_task_id - else [] - ) - stopped_batches = stop_douyu_batches( - [str(linked_task.batch_id or "") for linked_task in linked_tasks] - ) - for linked_task in linked_tasks: - if linked_task.status in {"planned", "pending", "running"}: - linked_task.status = "stopped" - linked_task.message = "履约任务已取消" - linked_task.finished_at = _now() - retained = _retain_lease_for_active_collab( - db, - task=task, - lease=lease, - current=current, - reason="platform_cancelled_but_collab_active", - ) - if retained is None: - release_lease( - db, - lease, - reason="platform_fulfillment_cancelled", - commit=False, - ) - task.account_id = None - task.lease_id = None - task.bind_task_id = None - task.exchange_task_id = None - task.binding_status = "not_started" - task.execution_status = "cancelled" - task.exchange_status = "not_started" - task.issue_code = "" - task.operator_id = current.id - task.last_error = reason.strip()[:2000] - task.updated_at = _now() - _append_event( - db, - task.id, - "task_cancelled", - actor_type="user", - actor_id=current.id, - detail={ - "reason": task.last_error, - "previousExecutionStatus": previous_execution_status, - "previousBindingStatus": previous_binding_status, - "previousExchangeStatus": previous_exchange_status, - "releasedAccountId": account_id, - "releasedLeaseId": lease_id, - "stoppedBatches": stopped_batches, - }, - ) - _emit_order_site_binding_state(db, task.id) - db.commit() - return get_task_detail(db, task.id) - - -def restore_cancelled_task( - db: Session, - *, - task_id: int, - current: User, - reason: str, -) -> dict[str, Any]: - """仅恢复人工误取消、且来源订单仍可履约的任务;不复用旧租约。""" - task = ( - db.query(PlatformFulfillmentTask) - .filter(PlatformFulfillmentTask.id == int(task_id)) - .with_for_update() - .first() - ) - if task is None: - raise HTTPException(status_code=404, detail="直播账号履约任务不存在") - if task.execution_status != "cancelled": - raise HTTPException(status_code=409, detail="只有已取消任务可以恢复") - if task.issue_code == "source_cancelled": - raise HTTPException(status_code=409, detail="来源订单已取消,不能恢复") - manual_cancel = ( - db.query(PlatformFulfillmentEvent.id) - .filter( - PlatformFulfillmentEvent.task_id == task.id, - PlatformFulfillmentEvent.event_type == "task_cancelled", - PlatformFulfillmentEvent.actor_type == "user", - ) - .first() - ) - if manual_cancel is None: - raise HTTPException(status_code=409, detail="只有人工取消的任务可以恢复") - - try: - source = lookup_pending_manual_fulfillment(task.source_order_item_id) - except OrderLookupUnavailable as exc: - raise HTTPException(status_code=503, detail=f"订单源不可用:{exc}") from exc - if source is None: - raise HTTPException(status_code=409, detail="来源订单不存在或已不可履约") - if ( - str(source.get("order_status") or "") in {"refunded", "cancelled", "closed"} - or str(source.get("pay_status") or "") != "paid" - or str(source.get("fulfillment_issue_code") or "") - in {"user_refund", "platform_cancelled"} - ): - raise HTTPException( - status_code=409, detail="来源订单已退款、关闭或取消,不能恢复" - ) - - restore_reason = reason.strip() - if len(restore_reason) < 2: - raise HTTPException(status_code=400, detail="请填写恢复原因") - - restored_collab = ( - db.query(DouyuExternalOrder) - .filter(DouyuExternalOrder.source_task_id == task.id) - .first() - ) - if restored_collab is not None and ( - restored_collab.status not in {"incomplete", "void"} - or restored_collab.bind_game_role - or restored_collab.home_images - ): - raise HTTPException( - status_code=409, - detail="关联外部协作单已在人工处理,请继续使用外部协作单", - ) - - mapping = _mapping_for_sku(db, task.internal_sku_key) - _apply_mapping(task, mapping) - task.account_id = None - task.lease_id = None - task.bind_task_id = None - task.exchange_task_id = None - task.binding_status = "not_started" - task.exchange_status = "not_started" - task.completed_at = None - task.next_allocate_at = _now() if task.execution_status == "ready" else None - task.operator_id = current.id - task.updated_at = _now() - - restored_collab_status = "" - if restored_collab is not None and restored_collab.status == "void": - restored_collab.status = "incomplete" - restored_collab.void_reason = "" - restored_collab.updated_by = current.id - restored_collab.updated_at = _now() - restored_collab.version = int(restored_collab.version or 0) + 1 - restored_collab_status = restored_collab.status - - _append_event( - db, - task.id, - "task_restored", - actor_type="user", - actor_id=current.id, - detail={ - "reason": restore_reason, - "restoredExecutionStatus": task.execution_status, - "restoredCollabOrderId": ( - int(restored_collab.id) if restored_collab is not None else None - ), - "restoredCollabStatus": restored_collab_status, - }, - ) - _emit_order_site_binding_state(db, task.id) - db.commit() - return get_task_detail(db, task.id) - - -def prepare_platform_task_for_collab_takeover( - db: Session, - *, - task: PlatformFulfillmentTask, - current: User, - collab_order_no: str, -) -> None: - """把平台履约任务转为人工,但不提交事务;由协作单接管流程原子提交。""" - if task.execution_status in {"completed", "cancelled"}: - raise HTTPException(status_code=409, detail="已结束的履约任务不能被协作单接管") - account_id = task.account_id - lease_id = task.lease_id - reason = f"外部协作单 {collab_order_no} 人工接管账号" - task.account_id = None - task.lease_id = None - task.bind_task_id = None - task.exchange_task_id = None - task.execution_status = "manual_required" - task.binding_status = "not_started" - task.exchange_status = "not_started" - task.issue_code = "manual_required" - task.next_allocate_at = None - task.operator_id = current.id - task.last_error = reason - task.updated_at = _now() - _append_event( - db, - task.id, - "collab_takeover", - actor_type="user", - actor_id=current.id, - detail={ - "reason": reason, - "collabOrderNo": collab_order_no, - "releasedAccountId": account_id, - "releasedLeaseId": lease_id, - }, - ) - _emit_order_site_binding_state(db, task.id) - db.flush() - - -def release_task_to_manual( - db: Session, - *, - task_id: int, - current: User, - reason: str, -) -> dict[str, Any]: - """释放履约账号并转人工,不再进入自动选号。""" - task = _load_task(db, task_id) - if task.execution_status in {"completed", "cancelled"}: - raise HTTPException(status_code=409, detail="已结束任务不能转人工") - manual_reason = reason.strip()[:2000] or "以外部单协作人工处理为准" - account_id = task.account_id - lease_id = task.lease_id - lease = ( - db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if task.lease_id - else None - ) - retained = _retain_lease_for_active_collab( - db, - task=task, - lease=lease, - current=current, - reason="platform_release_to_manual", - ) - if retained is None: - release_lease( - db, - lease, - reason="platform_fulfillment_manual", - commit=False, - ) - task.account_id = None - task.lease_id = None - task.bind_task_id = None - task.exchange_task_id = None - task.execution_status = "manual_required" - task.binding_status = "not_started" - task.exchange_status = "not_started" - task.issue_code = "manual_required" - task.next_allocate_at = None - task.operator_id = current.id - task.last_error = manual_reason - task.updated_at = _now() - _append_event( - db, - task.id, - "released_to_manual", - actor_type="user", - actor_id=current.id, - detail={ - "reason": manual_reason, - "releasedAccountId": account_id, - "releasedLeaseId": lease_id, - }, - ) - _emit_order_site_binding_state(db, task.id) - db.commit() - return get_task_detail(db, task.id) - __all__ = [ "allocate_task", @@ -3925,14 +138,20 @@ __all__ = [ "complete_manual_exchange", "confirm_binding", "create_mapping", + "customer_confirm_binding", + "customer_refresh_binding", "customer_refresh_bindings", + "customer_start_binding", "delete_mapping", + "ensure_customer_session", + "get_settings", "get_task_detail", "list_mappings", "list_tasks", "mapping_impact", "mark_manual_required", "prepare_manual_allocation", + "prepare_platform_task_for_collab_takeover", "reconcile_binding_state_outbox", "record_douyu_operation_result", "record_douyu_operation_started", @@ -3951,5 +170,6 @@ __all__ = [ "sync_pending_tasks_if_due", "sync_task_from_binding_runner", "update_mapping", + "update_settings", "upsert_mapping", ] diff --git a/web/backend/services/platform_fulfillment/views.py b/web/backend/services/platform_fulfillment/views.py new file mode 100644 index 0000000..2e4ce87 --- /dev/null +++ b/web/backend/services/platform_fulfillment/views.py @@ -0,0 +1,516 @@ +"""履约任务列表、详情和面客绑定视图。""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any + +from sqlalchemy import or_ +from sqlalchemy.orm import Session + +from ...models import ( + Account, + AccountLease, + DouyuExternalOrder, + DouyuGoodsSnapshot, + DouyuTask, + PlatformCommodityMapping, + PlatformFulfillmentEvent, + PlatformFulfillmentTask, + User, +) +from ...permissions import ROLE_LABELS +from ..account_binding import ( + binding_role_from_result, + pending_binding_role_from_result, +) +from ..file_service import build_file_url +from . import classification +from .binding_status import ( + _customer_task_message, + _customer_task_message_for, + _effective_binding_issue, + _effective_task_message, + _normalized_event_detail, +) +from .common import ( + _apply_order_match_cutoff, + _jsonable, + _order_match_started_at, +) +from .repository import _load_task + + +def list_tasks( + db: Session, + *, + status: str = "", + queue_bucket: str = "", + sale_mode: str = "", + keyword: str = "", + page: int = 1, + page_size: int = 20, +) -> dict[str, Any]: + query = db.query(PlatformFulfillmentTask) + query = _apply_order_match_cutoff(query, _order_match_started_at(db)) + query = query.filter( + or_( + PlatformFulfillmentTask.commodity_mapping_id.isnot(None), + PlatformFulfillmentTask.commodity_id != "", + ) + ) + mode_filter = classification.normalize_sale_mode(sale_mode) + if sale_mode and mode_filter != "unknown": + query = query.filter(PlatformFulfillmentTask.sale_mode == mode_filter) + elif sale_mode == "unknown": + query = query.filter(PlatformFulfillmentTask.sale_mode == "unknown") + if queue_bucket: + now = datetime.now(UTC) + if queue_bucket == classification.QUEUE_CANCELLED: + query = query.filter( + PlatformFulfillmentTask.execution_status == "cancelled" + ) + elif queue_bucket == classification.QUEUE_COMPLETED: + query = query.filter( + PlatformFulfillmentTask.execution_status == "completed" + ) + elif queue_bucket == classification.QUEUE_PENDING_MAPPING: + query = query.filter( + PlatformFulfillmentTask.execution_status == "pending_mapping" + ) + elif queue_bucket == classification.QUEUE_NEEDS_ACTION: + query = query.filter( + PlatformFulfillmentTask.execution_status == "manual_required" + ) + elif queue_bucket == classification.QUEUE_PRESALE_WAITING: + query = query.filter( + PlatformFulfillmentTask.execution_status.notin_( + ["completed", "cancelled", "pending_mapping", "manual_required"] + ), + PlatformFulfillmentTask.sale_mode == "presale", + or_( + PlatformFulfillmentTask.offer_available_from.is_(None), + PlatformFulfillmentTask.offer_available_from > now, + ), + ) + elif queue_bucket == classification.QUEUE_READY: + query = query.filter( + PlatformFulfillmentTask.execution_status.notin_( + ["completed", "cancelled", "pending_mapping", "manual_required"] + ), + or_( + PlatformFulfillmentTask.sale_mode != "presale", + PlatformFulfillmentTask.offer_available_from.is_(None), + PlatformFulfillmentTask.offer_available_from <= now, + ), + ) + else: + query = query.filter( + PlatformFulfillmentTask.execution_status.notin_( + ["completed", "cancelled"] + ) + ) + if status: + if status == "unfinished": + query = query.filter( + PlatformFulfillmentTask.execution_status.notin_( + ["completed", "cancelled"] + ) + ) + else: + query = query.filter(PlatformFulfillmentTask.execution_status == status) + text = keyword.strip() + if text: + pattern = f"%{text}%" + query = query.outerjoin( + Account, + Account.id == PlatformFulfillmentTask.account_id, + ).filter( + or_( + PlatformFulfillmentTask.platform_order_id.ilike(pattern), + PlatformFulfillmentTask.sku_name.ilike(pattern), + PlatformFulfillmentTask.sku_code.ilike(pattern), + PlatformFulfillmentTask.internal_sku_key.ilike(pattern), + PlatformFulfillmentTask.commodity_id.ilike(pattern), + Account.username.ilike(pattern), + Account.nickname.ilike(pattern), + Account.uid.ilike(pattern), + ) + ) + total = query.count() + rows = ( + query.order_by( + PlatformFulfillmentTask.paid_at.desc(), + PlatformFulfillmentTask.id.desc(), + ) + .offset((max(1, page) - 1) * max(1, page_size)) + .limit(max(1, min(page_size, 100))) + .all() + ) + return { + "items": [_task_out(db, row) for row in rows], + "pagination": { + "page": max(1, page), + "pageSize": max(1, page_size), + "total": total, + }, + } + + +def _task_out( + db: Session, + task: PlatformFulfillmentTask, + *, + include_qr: bool = False, + include_exchange_task: bool = False, +) -> dict[str, Any]: + mapping = ( + db.query(PlatformCommodityMapping) + .filter(PlatformCommodityMapping.id == task.commodity_mapping_id) + .first() + if task.commodity_mapping_id + else None + ) + goods = ( + db.query(DouyuGoodsSnapshot) + .filter(DouyuGoodsSnapshot.commodity_id == task.commodity_id) + .order_by(DouyuGoodsSnapshot.id.desc()) + .first() + if task.commodity_id + else None + ) + goods_name = ( + str(getattr(mapping, "goods_name", "") or "") + or str(getattr(goods, "name", "") or "") + or task.sku_name + or task.internal_sku_key + ) + account = ( + db.query(Account).filter(Account.id == task.account_id).first() + if task.account_id + else None + ) + lease = ( + db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if task.lease_id + else None + ) + bind_task = ( + db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() + if task.bind_task_id + else None + ) + collab_order = ( + db.query(DouyuExternalOrder) + .filter(DouyuExternalOrder.source_task_id == task.id) + .first() + ) + bind_result = (bind_task.result or {}) if bind_task else {} + effective_issue = _effective_binding_issue(task, bind_task, bind_result) + effective_last_error = _effective_task_message(task, effective_issue) + exchange_task_id = task.exchange_task_id + if exchange_task_id is None and include_exchange_task: + exchange_task_id = ( + db.query(DouyuTask.id) + .filter( + DouyuTask.platform_task_id == task.id, + DouyuTask.task_type == "exchange_goods", + ) + .order_by(DouyuTask.id.desc()) + .limit(1) + .scalar() + ) + # 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。 + pending_role = pending_binding_role_from_result(bind_result) + sale_mode = classification.normalize_sale_mode(task.sale_mode) + availability = classification.availability_state( + sale_mode=sale_mode, + available_from=task.offer_available_from, + available_until=task.offer_available_until, + ) + queue_bucket = classification.queue_bucket( + execution_status=task.execution_status, + sale_mode=sale_mode, + availability=availability, + ) + manual_reason = ( + classification.manual_reason(effective_issue, task.exchange_status) + if task.execution_status == "manual_required" + else "" + ) + return { + "id": task.id, + "sourceSystem": task.source_system, + "sourceOrderId": task.source_order_id, + "sourceOrderItemId": task.source_order_item_id, + "sourceFulfillmentId": task.source_fulfillment_id, + "platformOrderId": task.platform_order_id, + "provider": task.provider, + "shopId": task.shop_id, + "shopName": task.shop_name, + "skuCode": task.sku_code, + "skuName": task.sku_name, + "internalSkuKey": task.internal_sku_key, + "quantity": task.quantity, + "orderAmountFen": task.order_amount_fen, + "targetPlatform": task.target_platform, + "scope": task.scope, + "commodityMappingId": task.commodity_mapping_id, + "commodityId": task.commodity_id, + "goodsName": goods_name, + "requiredPoints": task.required_points, + "saleMode": sale_mode, + "campaignKey": task.campaign_key, + "campaignName": task.campaign_name, + "offerAvailableFrom": task.offer_available_from, + "offerAvailableUntil": task.offer_available_until, + "availabilityState": availability, + "queueBucket": queue_bucket, + "manualReason": manual_reason, + "classificationSource": task.classification_source, + "bindingStatus": task.binding_status, + "executionStatus": task.execution_status, + "exchangeStatus": task.exchange_status, + "issueCode": effective_issue, + "lastError": effective_last_error, + "operatorId": task.operator_id, + "completedAt": task.completed_at, + "paidAt": task.paid_at, + "createdAt": task.created_at, + "updatedAt": task.updated_at, + "collabOrder": ( + { + "id": collab_order.id, + "orderNo": collab_order.order_no, + "status": collab_order.status, + "lastSyncedAt": collab_order.last_synced_at, + } + if collab_order + else None + ), + "account": ( + { + "id": account.id, + "username": account.username, + "nickname": account.nickname or "", + "points": account.points, + "goldBalance": account.gold_balance, + "eliteOpened": account.elite_opened, + "ckCheckStatus": account.ck_check_status, + "roleBindStatus": account.role_bind_status, + "gameName": account.game_name, + "gameChannel": account.game_channel, + "roleChangeAvailableAt": account.role_change_available_at, + } + if account + else None + ), + "lease": ( + { + "id": lease.id, + "status": lease.status, + "expiresAt": lease.expires_at, + } + if lease + else None + ), + "bindTask": ( + { + "id": bind_task.id, + "taskType": bind_task.task_type, + "status": bind_task.status, + "message": bind_task.message, + "qrUrl": str(bind_result.get("url") or "") if include_qr else "", + "roleName": binding_role_from_result(bind_result), + "areaName": str(bind_result.get("area_name") or ""), + "platName": str(bind_result.get("plat_name") or ""), + "bindPhase": str(bind_result.get("bind_phase") or ""), + "bindReadyForConfirm": bool(pending_role), + "bindConfirmed": bool(bind_result.get("bind_confirmed")), + } + if bind_task + else None + ), + "exchangeTaskId": exchange_task_id, + "exchangeResultImage": ( + { + "objectKey": task.exchange_result_image_key, + "url": build_file_url(task.exchange_result_image_key), + "savedAt": task.exchange_result_image_saved_at, + } + if task.exchange_result_image_key + else None + ), + } + + +def get_task_detail(db: Session, task_id: int) -> dict[str, Any]: + task = _load_task(db, task_id) + events = ( + db.query(PlatformFulfillmentEvent) + .filter(PlatformFulfillmentEvent.task_id == task.id) + .order_by(PlatformFulfillmentEvent.id.desc()) + .limit(200) + .all() + ) + actor_ids = { + int(event.actor_id) + for event in events + if event.actor_type == "user" and str(event.actor_id or "").isdigit() + } + actors = ( + { + int(user.id): user + for user in db.query(User).filter(User.id.in_(actor_ids)).all() + } + if actor_ids + else {} + ) + bind_task_ids: set[int] = set() + for event in events: + detail = event.detail_json or {} + raw_id = ( + detail.get("douyuTaskId") + if event.event_type.startswith("douyu_operation_") + else detail.get("bindTaskId") + ) + try: + bind_task_id = int(raw_id) if raw_id is not None else 0 + except (TypeError, ValueError): + bind_task_id = 0 + if bind_task_id: + bind_task_ids.add(bind_task_id) + bind_tasks = ( + { + int(row.id): row + for row in db.query(DouyuTask).filter(DouyuTask.id.in_(bind_task_ids)).all() + } + if bind_task_ids + else {} + ) + return { + "task": _task_out(db, task, include_qr=True, include_exchange_task=True), + "events": [ + { + "id": event.id, + "eventType": event.event_type, + "actorType": event.actor_type, + "actorId": event.actor_id, + "actorName": ( + actors[int(event.actor_id)].deleted_username + or actors[int(event.actor_id)].username + ) + if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors + else "", + "actorRole": actors[int(event.actor_id)].role + if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors + else "", + "actorRoleLabel": ROLE_LABELS.get( + actors[int(event.actor_id)].role, + actors[int(event.actor_id)].role, + ) + if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors + else "", + "detail": _normalized_event_detail(event, bind_tasks), + "createdAt": event.created_at, + } + for event in events + ], + } + + +def _customer_binding_queue_state( + task: PlatformFulfillmentTask, + bind_task: DouyuTask | None, + *, + lease_ready: bool, +) -> tuple[str, int]: + if task.execution_status == "completed": + return "completed", 0 + if task.execution_status == "cancelled": + return "cancelled", 0 + if task.issue_code == "mapping_missing": + return "mapping_missing", 0 + if not task.account_id or not task.lease_id: + return "allocation_queued", 2000 + if not lease_ready: + return "lease_inactive", 0 + if task.binding_status == "failed": + return "failed", 0 + if bind_task is None: + return "ready_to_start", 0 + result = bind_task.result or {} + if bool(result.get("bind_confirmed")) or task.binding_status == "bound": + return "confirmed", 0 + if pending_binding_role_from_result(result): + return "role_ready", 0 + if bind_task.status in {"failed", "error", "stopped"}: + return "failed", 0 + if task.binding_status == "confirming": + return "confirming", 1000 + if bind_task.status in {"planned", "pending"}: + return "qr_queued", 1000 + if result.get("url"): + return "waiting_scan", 5000 if result.get("bind_polling") else 0 + return "preparing", 1000 + + +def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]: + """面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。""" + task = _load_task(db, task_id) + bind_task = ( + db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() + if task.bind_task_id + else None + ) + bind_result = (bind_task.result or {}) if bind_task else {} + pending_role = pending_binding_role_from_result(bind_result) + effective_issue = _effective_binding_issue(task, bind_task, bind_result) + lease = ( + db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if task.lease_id + else None + ) + lease_ready = bool(task.account_id and lease and lease.status == "active") + binding_failed = task.binding_status == "failed" + binding_confirmed = task.binding_status == "bound" + queue_state, retry_after_ms = _customer_binding_queue_state( + task, + bind_task, + lease_ready=lease_ready, + ) + return { + "sessionId": task.id, + "platformOrderId": task.platform_order_id, + "sourceOrderItemId": task.source_order_item_id, + "productName": task.sku_name, + "quantity": task.quantity, + "executionStatus": task.execution_status, + "bindingStatus": task.binding_status, + "exchangeStatus": task.exchange_status, + "issueCode": effective_issue, + "message": ( + _customer_task_message_for(effective_issue) + if effective_issue != task.issue_code + else _customer_task_message(task) + ), + "accountReady": lease_ready, + "bindTaskId": bind_task.id if bind_task else None, + "bindTaskStatus": bind_task.status if bind_task else "", + "bindPhase": str(bind_result.get("bind_phase") or ""), + "qrUrl": str(bind_result.get("url") or ""), + "qrGeneratedAt": str(bind_result.get("qr_generated_at") or ""), + "qrExpiresAt": str(bind_result.get("qr_expires_at") or ""), + "roleName": binding_role_from_result(bind_result), + "areaName": str(bind_result.get("area_name") or ""), + "platName": str(bind_result.get("plat_name") or ""), + "bindReadyForConfirm": (bool(pending_role) and not binding_failed), + "bindConfirmed": bool(bind_result.get("bind_confirmed")) and binding_confirmed, + "queueState": queue_state, + "retryAfterMs": retry_after_ms, + "queueLane": bind_task.queue_lane if bind_task else "", + "accepted": False, + "stateVersion": int(task.state_version or 0), + "completedAt": _jsonable(task.completed_at), + "updatedAt": _jsonable(task.updated_at), + }