From 85837944d0dc9c4d28d08319d305373b3676751c Mon Sep 17 00:00:00 2001 From: yml Date: Fri, 20 Nov 2026 00:14:36 +0800 Subject: [PATCH] fix(douyu): coordinate collab and platform account leases Avoid automatic allocation of accounts with active external collaboration, require explicit manual takeover of platform leases, and add Douyu account identity search. --- tests/test_douyu_collab_orders.py | 251 ++++++++++++++++-- tests/test_douyu_payment_sessions.py | 14 +- tests/test_platform_fulfillment.py | 96 +++++++ web/backend/routers/douyu_collab.py | 12 +- web/backend/schemas.py | 3 + web/backend/services/douyu_collab_service.py | 206 +++++++++++++- web/backend/services/douyu_service.py | 14 +- .../platform_fulfillment/account_selector.py | 37 ++- .../services/platform_fulfillment/service.py | 50 +++- web/frontend/src/api/douyuCollab.ts | 10 +- web/frontend/src/pages/DouyuCollabPage.tsx | 68 +++-- .../src/pages/PlatformFulfillmentPage.tsx | 2 +- 12 files changed, 704 insertions(+), 59 deletions(-) diff --git a/tests/test_douyu_collab_orders.py b/tests/test_douyu_collab_orders.py index 03630ac..f04ee9f 100644 --- a/tests/test_douyu_collab_orders.py +++ b/tests/test_douyu_collab_orders.py @@ -3,12 +3,24 @@ import pytest from tests.support.db import get_test_engine, make_test_session -from web.backend.models import Account, AccountEvent, AccountLease, AuditLog, User +from web.backend.models import ( + Account, + AccountEvent, + AccountLease, + AuditLog, + DouyuTask, + PlatformFulfillmentEvent, + PlatformFulfillmentTask, + User, +) from web.backend.routers import douyu_collab as collab_api from web.backend.schemas import ( DouyuCollabAccountLookupOut, + DouyuCollabAccountRequest, DouyuCollabCkExportOut, + DouyuCollabOrderCreate, DouyuCollabOrderOut, + DouyuCollabOrderUpdate, DouyuCollabUsernameExportOut, ) from web.backend.services import douyu_collab_service as collab @@ -98,6 +110,55 @@ class TestDouyuCollabOrders: def teardown_method(self): self.session.close() + def _platform_task_lease(self): + task = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="PLATFORM-TAKEOVER-ORDER", + source_order_item_id="PLATFORM-TAKEOVER-ITEM", + source_fulfillment_id="PLATFORM-TAKEOVER-FULFILLMENT", + platform_order_id="PLATFORM-TAKEOVER-NO", + target_platform="douyu", + scope="elite", + internal_sku_key="套装-接管测试", + commodity_id="takeover-goods", + required_points=100, + account_id=self.account.id, + execution_status="allocated", + binding_status="not_started", + exchange_status="not_started", + ) + self.session.add(task) + self.session.flush() + lease = AccountLease( + account_id=self.account.id, + holder_user_id=self.admin.id, + scope="elite", + purpose="platform_fulfillment", + commodity_id="takeover-goods", + batch_id=f"pf:{task.id}", + status="active", + ) + self.session.add(lease) + self.session.flush() + task.lease_id = lease.id + self.session.commit() + return task, lease + + def test_douyu_order_mutations_accept_takeover_flag(self): + create = DouyuCollabOrderCreate( + order_no="DY-TAKEOVER-SCHEMA", + takeover_platform_lease=True, + ) + update = DouyuCollabOrderUpdate(takeover_platform_lease=True) + account = DouyuCollabAccountRequest( + account_username="douyu-account-a", + takeover_platform_lease=True, + ) + + assert create.takeover_platform_lease is True + assert update.takeover_platform_lease is True + assert account.takeover_platform_lease is True + def test_lookup_account_resolves_internal_ck_and_role(self): result = collab.lookup_account( self.session, "douyu-account-a", client=FakeClient() @@ -329,6 +390,157 @@ class TestDouyuCollabOrders: is None ) + def test_create_order_explicitly_takes_over_platform_lease(self): + task, lease = self._platform_task_lease() + lease_id = lease.id + + order = collab.create_order( + self.session, + self.admin, + order_no="DY-LEASE-TAKEOVER", + shop="店铺A", + account_username="douyu-account-a", + gift_name="礼包A", + required_points=100, + home_images=["collab/home-takeover.png"], + takeover_platform_lease=True, + client=FakeClient(), + ) + + self.session.refresh(task) + self.session.refresh(lease) + assert order.account_id == self.account.id + assert task.execution_status == "manual_required" + assert task.account_id is None + assert task.lease_id is None + assert lease.id == lease_id + assert lease.status == "active" + assert lease.purpose == collab.LEASE_PURPOSE_DOUYU_COLLAB + assert lease.batch_id == f"collab:{self.account.id}" + assert lease.expires_at is None + event = ( + self.session.query(PlatformFulfillmentEvent) + .filter_by(task_id=task.id, event_type="collab_takeover") + .one() + ) + assert event.detail_json["collabOrderNo"] == "DY-LEASE-TAKEOVER" + assert event.detail_json["releasedLeaseId"] == lease_id + assert ( + self.session.query(AuditLog) + .filter_by(action="douyu:collab:lease_takeover") + .count() + == 1 + ) + assert ( + self.session.query(AccountEvent) + .filter_by(event_type="lease_acquired") + .count() + == 1 + ) + + def test_same_source_platform_lease_is_forced_to_collab_on_takeover(self): + task, lease = self._platform_task_lease() + order = collab.DouyuExternalOrder( + order_no="DY-SAME-SOURCE-TAKEOVER", + source_type=collab.SOURCE_TYPE_PLATFORM_FULFILLMENT, + source_task_id=task.id, + account_id=self.account.id, + account_username=self.account.username, + status=collab.STATUS_INCOMPLETE, + owner_id=self.admin.id, + created_by=self.admin.id, + ) + self.session.add(order) + self.session.commit() + + collab.set_account( + self.session, + self.admin, + order, + self.account.username, + takeover_platform_lease=True, + client=FakeClient(), + ) + + self.session.refresh(task) + self.session.refresh(lease) + assert task.execution_status == "manual_required" + assert task.account_id is None + assert task.lease_id is None + assert lease.status == "active" + assert lease.purpose == collab.LEASE_PURPOSE_DOUYU_COLLAB + + def test_takeover_rejects_running_exchange_task(self): + task, lease = self._platform_task_lease() + self.session.add( + DouyuTask( + batch_id="platform-exchange-running", + account_id=self.account.id, + account_assigned_to=self.admin.id, + task_type="exchange_goods", + handbook_scope="elite", + status="running", + platform_task_id=task.id, + created_by=self.admin.id, + ) + ) + self.session.commit() + + with pytest.raises(collab.CollabError) as excinfo: + collab.create_order( + self.session, + self.admin, + order_no="DY-TAKEOVER-BLOCKED", + shop="店铺A", + account_username="douyu-account-a", + gift_name="礼包A", + required_points=100, + home_images=["collab/home-takeover-blocked.png"], + takeover_platform_lease=True, + client=FakeClient(), + ) + + assert excinfo.value.code == "platform_task_running" + self.session.refresh(task) + self.session.refresh(lease) + assert task.execution_status == "allocated" + assert task.account_id == self.account.id + assert task.lease_id == lease.id + assert lease.purpose == "platform_fulfillment" + + def test_takeover_requires_platform_permission(self): + task, lease = self._platform_task_lease() + operator = User( + username="douyu-collab-no-platform", + password_hash="hash", + role="operation", + custom_permissions=[], + is_active=True, + ) + self.session.add(operator) + self.session.commit() + + with pytest.raises(collab.CollabError) as excinfo: + collab.create_order( + self.session, + operator, + order_no="DY-TAKEOVER-FORBIDDEN", + shop="店铺A", + account_username="douyu-account-a", + gift_name="礼包A", + required_points=100, + home_images=["collab/home-takeover-forbidden.png"], + takeover_platform_lease=True, + client=FakeClient(), + ) + + assert excinfo.value.code == "platform_takeover_forbidden" + self.session.refresh(task) + self.session.refresh(lease) + assert task.execution_status == "allocated" + assert task.account_id == self.account.id + assert lease.purpose == "platform_fulfillment" + def test_void_releases_only_after_last_active_order(self): first = collab.create_order( self.session, @@ -484,7 +696,7 @@ class TestDouyuCollabOrders: assert lease.status == "released" assert lease.release_reason == "douyu_collab_done" - def test_status_change_does_not_steal_active_platform_lease(self): + def test_status_change_rejects_unrelated_active_platform_lease(self): order = collab.create_order( self.session, self.admin, @@ -510,27 +722,22 @@ class TestDouyuCollabOrders: self.session.add(platform_lease) self.session.commit() - changed = collab.set_status( - self.session, - self.admin, - order, - status=collab.STATUS_RECHARGED, - reason="仅补记充值状态", - ) - - assert changed.status == collab.STATUS_RECHARGED - self.session.refresh(platform_lease) - assert platform_lease.status == "active" - assert ( - self.session.query(AccountLease) - .filter( - AccountLease.account_id == self.account.id, - AccountLease.status == "active", - AccountLease.purpose == collab.LEASE_PURPOSE_DOUYU_COLLAB, + with pytest.raises(collab.CollabError) as excinfo: + collab.set_status( + self.session, + self.admin, + order, + status=collab.STATUS_RECHARGED, + reason="仅补记充值状态", ) - .count() - == 0 - ) + + assert excinfo.value.code == "account_lease_conflict" + self.session.rollback() + self.session.refresh(order) + self.session.refresh(platform_lease) + assert order.status == collab.STATUS_TO_RECHARGE + assert platform_lease.status == "active" + assert platform_lease.purpose == "platform_fulfillment" def test_status_change_backfills_missing_collab_lease(self): order = collab.create_order( diff --git a/tests/test_douyu_payment_sessions.py b/tests/test_douyu_payment_sessions.py index 5d3d0bf..38d6a19 100644 --- a/tests/test_douyu_payment_sessions.py +++ b/tests/test_douyu_payment_sessions.py @@ -43,7 +43,7 @@ def test_active_payment_blocks_same_account_across_users(db): owner.id, ) - with pytest.raises(DouyuActivePaymentError, match=first_batch): + with pytest.raises(DouyuActivePaymentError) as exc_info: create_douyu_planned_tasks( db, [account.id], @@ -52,11 +52,13 @@ def test_active_payment_blocks_same_account_across_users(db): other.id, ) - task = ( - db.query(DouyuTask) - .filter(DouyuTask.batch_id == first_batch) - .one() - ) + message = str(exc_info.value) + assert first_batch in message + assert "开通精英宝典" in message + assert "已创建,等待执行" in message + assert "二维码或支付会话串单" in message + + task = db.query(DouyuTask).filter(DouyuTask.batch_id == first_batch).one() task.status = "stopped" db.commit() diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index ebe5adb..862370e 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -276,6 +276,20 @@ class TestSyncAndMapping(_Base): assert listed["pagination"]["total"] == 1 assert legacy.id != mapped.id + def test_list_searches_assigned_douyu_account_identity(self): + task = self.task() + account = self.account("douyu-search-account") + account.nickname = "斗鱼昵称-搜索" + account.uid = "90000123" + task.account_id = account.id + self.session.commit() + + for keyword in ("douyu-search-account", "斗鱼昵称-搜索", "90000123"): + listed = service.list_tasks(self.session, keyword=keyword) + assert listed["pagination"]["total"] == 1 + assert listed["items"][0]["id"] == task.id + assert listed["items"][0]["account"]["id"] == account.id + def test_list_hides_tasks_paid_before_order_match_cutoff(self): mapping = self.mapping() task = PlatformFulfillmentTask( @@ -1151,6 +1165,88 @@ class TestAccountSelection(_Base): assert [row.username for row in candidates] == ["small", "large"] + def test_active_collab_order_blocks_all_automatic_candidate_pools(self): + account = self.account("active-collab-candidate", points=2000) + self.session.add( + AccountCommodityState( + account_id=account.id, + platform="douyu", + scope="elite", + commodity_id=COMMODITY, + commodity_name=INTERNAL_SKU, + availability="available", + observed_at=NOW, + valid_until=NOW + timedelta(hours=1), + ) + ) + order = DouyuExternalOrder( + order_no="DY-ACTIVE-CANDIDATE", + account_id=account.id, + account_username=account.username, + status=collab.STATUS_TO_RECHARGE, + owner_id=self.admin.id, + created_by=self.admin.id, + ) + self.session.add(order) + self.session.commit() + + assert ( + account_selector.eligible_accounts( + self.session, + commodity_id=COMMODITY, + required_points=1280, + now=NOW, + ) + == [] + ) + assert ( + account_selector.live_candidate_accounts( + self.session, + required_points=1280, + commodity_id=COMMODITY, + ) + == [] + ) + assert ( + account_selector.capability_candidate_accounts( + self.session, + commodity_id=COMMODITY, + required_points=1280, + now=NOW, + ) + == [] + ) + + order.status = collab.STATUS_DONE + self.session.commit() + + assert [ + row.account_id + for row in account_selector.eligible_accounts( + self.session, + commodity_id=COMMODITY, + required_points=1280, + now=NOW, + ) + ] == [account.id] + assert [ + row.id + for row in account_selector.live_candidate_accounts( + self.session, + required_points=1280, + commodity_id=COMMODITY, + ) + ] == [account.id] + assert [ + row.id + for row in account_selector.capability_candidate_accounts( + self.session, + commodity_id=COMMODITY, + required_points=1280, + now=NOW, + ) + ] == [account.id] + def test_lease_is_unique_per_account(self): account = self.account("leased") candidate = account_selector.eligible_accounts( diff --git a/web/backend/routers/douyu_collab.py b/web/backend/routers/douyu_collab.py index a066927..51134f2 100644 --- a/web/backend/routers/douyu_collab.py +++ b/web/backend/routers/douyu_collab.py @@ -20,6 +20,7 @@ from sqlalchemy.orm import Session from ..database import get_db from ..deps import authenticate_websocket, get_current_user, require_permission +from ..errors import ApiError from ..models import User from ..permissions import get_user_permissions from ..schemas import ( @@ -56,8 +57,12 @@ from ..services.douyu_collab_events import collab_events router = APIRouter(prefix="/api/douyu", tags=["斗鱼外部单协作"]) -def _http_error(exc: collab.CollabError) -> HTTPException: - return HTTPException(status_code=exc.status_code, detail=exc.detail) +def _http_error(exc: collab.CollabError) -> ApiError: + return ApiError( + status_code=exc.status_code, + detail=exc.detail, + error_code=exc.code or "douyu_collab_error", + ) def _one(db: Session, order) -> dict: @@ -263,6 +268,7 @@ def create_external_order( remark=req.remark, draft=req.draft, require_verified=req.require_verified, + takeover_platform_lease=req.takeover_platform_lease, ) except collab.CollabError as exc: raise _http_error(exc) from exc @@ -297,6 +303,7 @@ def update_external_order( order, req.model_dump(exclude_unset=True), expected_version=req.expected_version, + takeover_platform_lease=req.takeover_platform_lease, ) _publish_change(current, scope="orders", action="order.update") return _one(db, order) @@ -319,6 +326,7 @@ def set_external_order_account( order, req.account_username, expected_version=req.expected_version, + takeover_platform_lease=req.takeover_platform_lease, ) _publish_change(current, scope="orders", action="order.account") return _one(db, order) diff --git a/web/backend/schemas.py b/web/backend/schemas.py index 933c437..0dbb125 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -2560,6 +2560,7 @@ class DouyuCollabOrderCreate(BaseModel): remark: str = Field("", max_length=512) draft: bool = False require_verified: bool = True + takeover_platform_lease: bool = False class DouyuCollabOrderUpdate(BaseModel): @@ -2573,6 +2574,7 @@ class DouyuCollabOrderUpdate(BaseModel): home_images: list[str] | None = None remark: str | None = Field(None, max_length=512) expected_version: int | None = None + takeover_platform_lease: bool = False class DouyuCollabStatusRequest(BaseModel): @@ -2592,6 +2594,7 @@ class DouyuCollabStatusBatchRequest(BaseModel): class DouyuCollabAccountRequest(BaseModel): account_username: str = Field(..., min_length=1, max_length=128) expected_version: int | None = None + takeover_platform_lease: bool = False class DouyuCollabImagesRequest(BaseModel): diff --git a/web/backend/services/douyu_collab_service.py b/web/backend/services/douyu_collab_service.py index 8188dbd..ad9c407 100644 --- a/web/backend/services/douyu_collab_service.py +++ b/web/backend/services/douyu_collab_service.py @@ -38,6 +38,7 @@ from ..models import ( PlatformFulfillmentTask, User, ) +from ..permissions import user_has_permission from .account_binding import binding_channel, binding_role_from_result from .account_events_service import ( CATEGORY_OPS, @@ -132,6 +133,21 @@ STATUS_FLOW: tuple[str, ...] = ( ) SOURCE_TYPE_PLATFORM_FULFILLMENT = "platform_fulfillment" +PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES = frozenset( + { + "lock_goods", + "pay_locked_order", + "exchange_goods", + "exchange_esports_goods", + "exchange_xpd_goods", + "create_elite_qr", + "create_esports_qr", + "create_gold_qr", + "donate_elite_gift", + "donate_esports_chicken_gift", + "donate_esports_firework_gift", + } +) STAGE_INDEX = { STATUS_INCOMPLETE: 0, @@ -521,6 +537,145 @@ def _platform_lease_matches_source( ) +def _lock_active_lease_for_account( + db: Session, + account_id: int, +) -> AccountLease | None: + return ( + db.query(AccountLease) + .filter( + AccountLease.account_id == int(account_id), + AccountLease.status == "active", + ) + .with_for_update() + .first() + ) + + +def _platform_task_for_lease( + db: Session, + lease: AccountLease, +) -> PlatformFulfillmentTask | None: + task_id = 0 + if lease.batch_id.startswith("pf:"): + try: + task_id = int(lease.batch_id.removeprefix("pf:")) + except ValueError: + task_id = 0 + query = db.query(PlatformFulfillmentTask).with_for_update() + if task_id: + task = query.filter(PlatformFulfillmentTask.id == task_id).first() + if task is not None: + return task + return query.filter(PlatformFulfillmentTask.lease_id == int(lease.id)).first() + + +def _takeover_platform_lease_for_collab( + db: Session, + current: User, + order: DouyuExternalOrder, + lease: AccountLease, +) -> AccountLease: + """外部协作显式接管平台租约,并在同一事务内把平台任务转人工。""" + if not user_has_permission(current, "platform_fulfillment:use"): + raise CollabError( + "没有接管平台履约账号的权限", + status_code=403, + code="platform_takeover_forbidden", + ) + platform_task = _platform_task_for_lease(db, lease) + if platform_task is None: + raise CollabError( + "平台履约任务不存在,请刷新后重试", + status_code=409, + code="account_lease_conflict", + ) + if platform_task.execution_status in {"completed", "cancelled"}: + raise CollabError( + f"平台履约任务 #{platform_task.id} 已结束,不能由协作单接管", + status_code=409, + code="platform_task_not_takeoverable", + ) + if ( + platform_task.account_id != lease.account_id + or platform_task.lease_id != lease.id + ): + raise CollabError( + f"平台履约任务 #{platform_task.id} 与账号租约不一致,请先核对", + status_code=409, + code="account_lease_conflict", + ) + blocking = ( + db.query(DouyuTask) + .filter( + DouyuTask.platform_task_id == int(platform_task.id), + DouyuTask.status.in_(("planned", "pending", "running")), + DouyuTask.task_type.in_(PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES), + ) + .order_by(DouyuTask.id.desc()) + .first() + ) + if blocking is not None: + raise CollabError( + f"平台履约任务 #{platform_task.id} 正在执行资金/兑换操作,请先停止任务", + status_code=409, + code="platform_task_running", + ) + + from .platform_fulfillment import service as platform_service + + platform_service.prepare_platform_task_for_collab_takeover( + db, + task=platform_task, + current=current, + collab_order_no=order.order_no, + ) + previous_task_id = int(platform_task.id) + lease.purpose = LEASE_PURPOSE_DOUYU_COLLAB + lease.batch_id = f"collab:{int(lease.account_id)}"[:64] + lease.commodity_id = "" + lease.holder_user_id = int(current.id) + lease.expires_at = None + lease.released_at = None + lease.release_reason = "" + emit( + db, + account_id=int(lease.account_id), + event_type=EVENT_LEASE_ACQUIRED, + title=f"外部协作接管平台履约账号:{order.order_no}", + category=CATEGORY_OPS, + detail={ + "lease_id": lease.id, + "order_id": order.id, + "order_no": order.order_no, + "platform_task_id": previous_task_id, + "reason": "collab_manual_takeover", + }, + source="lease", + subject_type="order", + subject_key=order.order_no, + actor_type="user", + actor_id=int(current.id), + source_ref=f"account_lease_collab_takeover:{lease.id}", + ) + _audit_lease_action( + db, + current, + order=order, + account_id=int(lease.account_id), + action="douyu:collab:lease_takeover", + lease=lease, + detail={ + "lease_id": lease.id, + "order_id": order.id, + "order_no": order.order_no, + "platform_task_id": previous_task_id, + "reason": "collab_manual_takeover", + }, + ) + return lease + + def _audit_lease_action( db: Session, current: User, @@ -556,6 +711,7 @@ def _ensure_order_account_lease( *, account_id: int | None = None, force_active: bool = False, + takeover_platform_lease: bool = False, commit: bool = False, ) -> AccountLease | None: target_account_id = int(account_id or order.account_id or 0) @@ -564,14 +720,27 @@ def _ensure_order_account_lease( if not force_active and not _order_occupies_account(order): return None - lease = active_lease_for_account(db, target_account_id) + lease = _lock_active_lease_for_account(db, target_account_id) if lease is not None: if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: return lease + if takeover_platform_lease: + return _takeover_platform_lease_for_collab( + db, + current, + order, + lease, + ) if _platform_lease_matches_source(db, lease, order): return lease + platform_task = _platform_task_for_lease(db, lease) + task_label = ( + f"平台履约任务 #{platform_task.id}" + if platform_task is not None + else "平台履约任务" + ) raise CollabError( - "该账号当前被平台履约占用,请先释放或转人工后再使用", + f"该账号当前被{task_label}占用,请确认转人工后再使用", status_code=409, code="account_lease_conflict", ) @@ -659,10 +828,24 @@ def _sync_order_lease( ) -> AccountLease | None: if force_active or _order_occupies_account(order): if reuse_active_lease: - # 纯状态回写允许沿用平台履约或其他业务的有效占用,不抢占、不转换。 - lease = active_lease_for_account(db, order.account_id) + # 纯状态回写只沿用协作租约或同一平台来源的租约;其他业务占用必须显式接管。 + lease = _lock_active_lease_for_account(db, int(order.account_id or 0)) if lease is not None: - return lease + if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: + return lease + if _platform_lease_matches_source(db, lease, order): + return lease + platform_task = _platform_task_for_lease(db, lease) + task_label = ( + f"平台履约任务 #{platform_task.id}" + if platform_task is not None + else "平台履约任务" + ) + raise CollabError( + f"该账号当前被{task_label}占用,请先由协作单确认接管", + status_code=409, + code="account_lease_conflict", + ) # 没有任何有效占用的历史异常行仍需补建协作租约,避免自动分配选中。 return _ensure_order_account_lease( db, @@ -876,6 +1059,7 @@ def create_order( remark: str = "", draft: bool = False, require_verified: bool = True, + takeover_platform_lease: bool = False, client: Any | None = None, commit: bool = True, ) -> DouyuExternalOrder: @@ -986,7 +1170,13 @@ def create_order( if order.shop: ensure_shops_registered(db, current, [order.shop]) - _ensure_order_account_lease(db, current, order, force_active=True) + _ensure_order_account_lease( + db, + current, + order, + force_active=True, + takeover_platform_lease=takeover_platform_lease, + ) db.add(order) db.flush() record_audit( @@ -1352,6 +1542,7 @@ def update_order( payload: Mapping[str, Any], *, expected_version: int | None = None, + takeover_platform_lease: bool = False, client: Any | None = None, commit: bool = True, ) -> dict[str, Any]: @@ -1426,6 +1617,7 @@ def update_order( order, account_id=int(account.id), force_active=order.status in COLLAB_LEASE_STATUSES, + takeover_platform_lease=takeover_platform_lease, ) apply_probe_snapshot(order, account, probe) changes["account_id"] = { @@ -1483,6 +1675,7 @@ def set_account( username: str, *, expected_version: int | None = None, + takeover_platform_lease: bool = False, client: Any | None = None, commit: bool = True, ) -> dict[str, Any]: @@ -1507,6 +1700,7 @@ def set_account( order, account_id=int(account.id), force_active=order.status in COLLAB_LEASE_STATUSES, + takeover_platform_lease=takeover_platform_lease, ) apply_probe_snapshot(order, account, probe) order.updated_by = current.id diff --git a/web/backend/services/douyu_service.py b/web/backend/services/douyu_service.py index 955dc7f..ea8f6aa 100644 --- a/web/backend/services/douyu_service.py +++ b/web/backend/services/douyu_service.py @@ -344,9 +344,19 @@ def _lock_payment_accounts( if account is not None else f"#{conflict.account_id}" ) + task_label = SUPPORTED_DOUYU_TASK_TYPES.get( + str(conflict.task_type or ""), + "斗鱼付费任务", + ) + status_label = { + "planned": "已创建,等待执行", + "pending": "正在排队等待执行", + "running": "正在执行", + }.get(conflict.status, "仍在处理中") raise DouyuActivePaymentError( - f"账号 {label} 已有充值任务处理中(批次 {conflict.batch_id})," - "请先完成或停止该充值" + f"账号 {label} 的「{task_label}」{status_label}" + f"(批次 {conflict.batch_id})。为避免同账号二维码或支付会话串单," + "请等待任务结束;若长时间未结束,请联系批次创建人或管理员停止后再试" ) diff --git a/web/backend/services/platform_fulfillment/account_selector.py b/web/backend/services/platform_fulfillment/account_selector.py index 33096cb..229c725 100644 --- a/web/backend/services/platform_fulfillment/account_selector.py +++ b/web/backend/services/platform_fulfillment/account_selector.py @@ -13,7 +13,14 @@ from sqlalchemy import case, or_, select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session -from ...models import Account, AccountCommodityState, AccountEvent, AccountLease, User +from ...models import ( + Account, + AccountCommodityState, + AccountEvent, + AccountLease, + DouyuExternalOrder, + User, +) from ..account_capability_service import AVAILABILITY_AVAILABLE from ..account_events_service import ( CATEGORY_OPS, @@ -27,6 +34,15 @@ VALIDATION_LEASE_MINUTES = 5 BINDING_LEASE_MINUTES = 120 EXCHANGE_COOLDOWN_DAYS = 365 POOL_OWNER_ROLES = ("super_admin", "operation", "support") +ACTIVE_COLLAB_ORDER_STATUSES = ( + "incomplete", + "to_recharge", + "recharged", + "scripted", + "points_error", + "role_error", + "failed", +) @dataclass(frozen=True) @@ -55,6 +71,19 @@ def _pool_owner_ids(): ) +def _active_collab_order(): + """账号即使缺少协作租约,只要还有活动协作单也不能进入自动选号。""" + return ( + select(DouyuExternalOrder.id) + .where( + DouyuExternalOrder.account_id == Account.id, + DouyuExternalOrder.archived_at.is_(None), + DouyuExternalOrder.status.in_(ACTIVE_COLLAB_ORDER_STATUSES), + ) + .exists() + ) + + def eligible_accounts( db: Session, *, @@ -72,6 +101,7 @@ def eligible_accounts( .where(AccountLease.active_account_id == Account.id) .exists() ) + active_collab = _active_collab_order() exchanged = ( select(AccountEvent.id) .where( @@ -95,6 +125,7 @@ def eligible_accounts( Account.points >= max(0, int(required_points)), or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)), ~active_lease, + ~active_collab, ~exchanged, or_( Account.role_change_available_at.is_(None), @@ -138,6 +169,7 @@ def live_candidate_accounts( .where(AccountLease.active_account_id == Account.id) .exists() ) + active_collab = _active_collab_order() query = db.query(Account).filter( Account.cookie.isnot(None), Account.cookie != "", @@ -149,6 +181,7 @@ def live_candidate_accounts( ), or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)), ~active_lease, + ~active_collab, ) commodity = commodity_id.strip() if commodity: @@ -204,6 +237,7 @@ def capability_candidate_accounts( .where(AccountLease.active_account_id == Account.id) .exists() ) + active_collab = _active_collab_order() return ( db.query(Account) .join( @@ -239,6 +273,7 @@ def capability_candidate_accounts( ), or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)), ~active_lease, + ~active_collab, ) .order_by( case((Account.ck_check_status == "valid", 0), else_=1), diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index bc6fff9..a23402c 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -1001,13 +1001,19 @@ def list_tasks( text = keyword.strip() if text: pattern = f"%{text}%" - query = query.filter( + 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() @@ -2581,6 +2587,48 @@ def restore_cancelled_task( 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, *, diff --git a/web/frontend/src/api/douyuCollab.ts b/web/frontend/src/api/douyuCollab.ts index 635d4e4..71cdc55 100644 --- a/web/frontend/src/api/douyuCollab.ts +++ b/web/frontend/src/api/douyuCollab.ts @@ -231,6 +231,7 @@ export interface DouyuCollabOrderCreate { remark?: string; draft?: boolean; require_verified?: boolean; + takeover_platform_lease?: boolean; } export interface DouyuCollabOrderUpdate { @@ -244,6 +245,7 @@ export interface DouyuCollabOrderUpdate { home_images?: string[]; remark?: string; expected_version?: number; + takeover_platform_lease?: boolean; } export interface DouyuCollabMetric { @@ -368,10 +370,16 @@ export const douyuCollabApi = { api.get(`/douyu/external-orders/${id}`), updateOrder: (id: number, data: DouyuCollabOrderUpdate) => api.put(`/douyu/external-orders/${id}`, data), - setAccount: (id: number, account_username: string, expected_version?: number) => + setAccount: ( + id: number, + account_username: string, + expected_version?: number, + takeover_platform_lease = false, + ) => api.post(`/douyu/external-orders/${id}/account`, { account_username, expected_version, + takeover_platform_lease, }), verifyOrder: (id: number) => api.post<{ order: DouyuCollabOrder; probe: DouyuCollabAccountLookup }, { order: DouyuCollabOrder; probe: DouyuCollabAccountLookup }>( diff --git a/web/frontend/src/pages/DouyuCollabPage.tsx b/web/frontend/src/pages/DouyuCollabPage.tsx index 1769c72..3295261 100644 --- a/web/frontend/src/pages/DouyuCollabPage.tsx +++ b/web/frontend/src/pages/DouyuCollabPage.tsx @@ -74,6 +74,10 @@ import { copyTextToClipboard } from '../utils/clipboard'; const { Text } = Typography; +function errorCodeOf(error: unknown): string { + return (error as { errorCode?: string } | null)?.errorCode || ''; +} + function hasTextInputFocus(): boolean { const active = document.activeElement; return ( @@ -635,10 +639,9 @@ export default function DouyuCollabPage() { !form.account_username.trim() || !form.gift_name.trim() || form.home_images.length === 0; - setSubmitting(true); - try { + const saveOrder = async (takeoverPlatformLease: boolean) => { if (editing) { - const updated = await douyuCollabApi.updateOrder(editing.id, { + return douyuCollabApi.updateOrder(editing.id, { order_no: form.order_no.trim(), shop: form.shop.trim(), owner_id: form.owner_id, @@ -649,7 +652,26 @@ export default function DouyuCollabPage() { home_images: form.home_images, remark: form.remark, expected_version: editing.version, + takeover_platform_lease: takeoverPlatformLease, }); + } + return douyuCollabApi.createOrder({ + order_no: form.order_no.trim(), + shop: form.shop.trim(), + owner_id: form.owner_id, + account_username: form.account_username.trim(), + gift_name: form.gift_name, + commodity_id: form.commodity_id, + required_points: form.required_points, + home_images: form.home_images, + remark: form.remark, + draft: createAsDraft, + require_verified: !createAsDraft, + takeover_platform_lease: takeoverPlatformLease, + }); + }; + const finishSaved = (updated: DouyuCollabOrder) => { + if (editing) { if (updated.status === 'incomplete' && updated.missing_fields?.length) { message.warning(`资料已保存,但仍缺:${updated.missing_fields.join('、')}`); } else if (editing.status === 'incomplete') { @@ -658,26 +680,38 @@ export default function DouyuCollabPage() { message.success('协作单已更新'); } } else { - const created = await douyuCollabApi.createOrder({ - order_no: form.order_no.trim(), - shop: form.shop.trim(), - owner_id: form.owner_id, - account_username: form.account_username.trim(), - gift_name: form.gift_name, - commodity_id: form.commodity_id, - required_points: form.required_points, - home_images: form.home_images, - remark: form.remark, - draft: createAsDraft, - require_verified: !createAsDraft, - }); message.success( - created.status === 'incomplete' ? '已创建待补资料协作单' : '协作单已创建', + updated.status === 'incomplete' ? '已创建待补资料协作单' : '协作单已创建', ); } setCreateOpen(false); refreshAll(); + }; + + setSubmitting(true); + try { + finishSaved(await saveOrder(false)); } catch (error) { + if (errorCodeOf(error) === 'account_lease_conflict') { + setSubmitting(false); + modal.confirm({ + title: '平台履约账号需要转人工', + content: `${getErrorMessage(error)}。确认后平台履约任务会转为人工,并由当前协作单接管账号。`, + okText: '确认接管并转人工', + cancelText: '取消', + onOk: async () => { + setSubmitting(true); + try { + finishSaved(await saveOrder(true)); + } catch (retryError) { + message.error(getErrorMessage(retryError)); + } finally { + setSubmitting(false); + } + }, + }); + return; + } message.error(getErrorMessage(error)); } finally { setSubmitting(false); diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index 1b0f900..a292752 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -1053,7 +1053,7 @@ export default function PlatformFulfillmentPage() { { setKeyword(event.target.value);