diff --git a/docs/直播账号履约工作台.md b/docs/直播账号履约工作台.md index 10d50a8..219ced1 100644 --- a/docs/直播账号履约工作台.md +++ b/docs/直播账号履约工作台.md @@ -102,6 +102,23 @@ - 无限制租约不会自动回收,任务完成、取消或人工释放时仍会正常释放账号; - 有限租约到期后由自动任务将未完成任务转入人工处理。 +## 外部协作误关联修复 + +斗鱼外部单协作允许同一账号挂多张人工单,但如果账号已经被直播账号履约占用, +不能继续把历史人工单视为该账号的一次有效使用。超级管理员和运营可以在协作单 +编辑弹窗中执行: + +1. **解除账号**:只解除协作单与内部账号的关联,不删除内部账号。账号身份、 + 角色、鱼翅和积分快照会被清空,订单回到「待补资料」;若账号仍被履约任务或 + 其他活动协作单占用,其租约不会被释放。 +2. **推荐账号**:复用履约候选池的硬条件,实时检查 CK、有效租约、活动协作单、 + 角色换绑冷却、商品限兑和 365 天兑换记录。默认未绑定账号优先,可选择是否 + 纳入已经过了换绑冷却的账号。 + +推荐结果不会预占账号。运营确认候选后,仍调用原有账号绑定接口重新校验并在同一 +事务内建立协作租约;如果候选在推荐后被其他任务占用,接口会拒绝并要求重新推荐。 +客服没有解除或推荐账号的入口和 API 权限。 + ## 环境 旧版定向兼容或人工补查 `order_site` 时才需要: diff --git a/tests/test_douyu_collab_orders.py b/tests/test_douyu_collab_orders.py index 3d43a6c..a3fb815 100644 --- a/tests/test_douyu_collab_orders.py +++ b/tests/test_douyu_collab_orders.py @@ -9,6 +9,7 @@ from web.backend.models import ( AccountLease, AuditLog, DouyuTask, + PlatformCommodityMapping, PlatformFulfillmentEvent, PlatformFulfillmentTask, User, @@ -16,6 +17,7 @@ from web.backend.models import ( from web.backend.routers import douyu_collab as collab_api from web.backend.schemas import ( DouyuCollabAccountLookupOut, + DouyuCollabAccountRecommendOut, DouyuCollabAccountRequest, DouyuCollabCkExportOut, DouyuCollabOrderCreate, @@ -85,6 +87,19 @@ class FakeNoBindClient(FakeClient): raise RuntimeError("未绑定角色") +class FakeUnboundClient(FakeClient): + def bind_info(self, **_): + return { + "is_bound_account": False, + "is_bound_role": False, + "is_bound_act": False, + "role_name": "", + "area_name": "", + "plat_name": "", + "nickname": "", + } + + class TestDouyuCollabOrders: def setup_method(self): self.engine = get_test_engine() @@ -172,6 +187,226 @@ class TestDouyuCollabOrders: assert result["goods"][0]["commodity_id"] == "gift-a" DouyuCollabAccountLookupOut.model_validate(result) + def test_unlink_account_clears_snapshots_and_keeps_platform_lease(self): + order = collab.create_order( + self.session, + self.admin, + order_no="DY-UNLINK-PLATFORM", + shop="店铺A", + account_username="douyu-account-a", + gift_name="礼包A", + required_points=100, + home_images=["collab/unlink.png"], + client=FakeClient(), + ) + collab_lease = self.session.query(AccountLease).one() + collab_lease.status = "released" + collab_lease.release_reason = "test_handoff" + platform_lease = AccountLease( + account_id=self.account.id, + holder_user_id=self.admin.id, + scope="elite", + purpose="platform_fulfillment", + batch_id="pf:unlink-platform", + status="active", + ) + self.session.add(platform_lease) + self.session.commit() + + collab.unlink_account( + self.session, + self.admin, + order, + reason="账号已用于其它履约订单", + expected_version=order.version, + ) + + self.session.refresh(order) + self.session.refresh(platform_lease) + assert order.account_id is None + assert order.account_username == "" + assert order.bind_game_role == "" + assert order.fish_fin_balance is None + assert order.points_balance is None + assert order.status == collab.STATUS_INCOMPLETE + assert platform_lease.status == "active" + assert platform_lease.purpose == "platform_fulfillment" + assert ( + self.session.query(AuditLog) + .filter_by(action="douyu:collab:account_unlink") + .count() + == 1 + ) + + def test_unlink_account_releases_last_collab_lease(self): + order = collab.create_order( + self.session, + self.admin, + order_no="DY-UNLINK-LEASE", + shop="店铺A", + account_username="douyu-account-a", + gift_name="礼包A", + required_points=100, + home_images=["collab/unlink-lease.png"], + client=FakeClient(), + ) + lease = self.session.query(AccountLease).one() + + collab.unlink_account( + self.session, + self.admin, + order, + reason="误关联", + expected_version=order.version, + ) + + self.session.refresh(lease) + assert lease.status == "released" + assert lease.release_reason == "douyu_collab_account_unlinked" + + def test_account_replace_requires_super_admin_or_operation(self): + order = collab.create_order( + self.session, + self.admin, + order_no="DY-UNLINK-SUPPORT", + shop="店铺A", + account_username="douyu-account-a", + gift_name="礼包A", + required_points=100, + home_images=["collab/unlink-support.png"], + client=FakeClient(), + ) + support = User( + username="douyu-collab-support", + password_hash="hash", + role="support", + custom_permissions=[], + is_active=True, + ) + self.session.add(support) + self.session.commit() + + with pytest.raises(collab.CollabError) as excinfo: + collab.unlink_account( + self.session, + support, + order, + reason="越权测试", + ) + + assert excinfo.value.code == "account_replace_forbidden" + + def test_operation_can_unlink_account(self): + order = collab.create_order( + self.session, + self.admin, + order_no="DY-UNLINK-OPERATION", + shop="店铺A", + account_username="douyu-account-a", + gift_name="礼包A", + required_points=100, + home_images=["collab/unlink-operation.png"], + client=FakeClient(), + ) + operator = User( + username="douyu-collab-operation", + password_hash="hash", + role="operation", + is_active=True, + ) + self.session.add(operator) + self.session.commit() + + collab.unlink_account( + self.session, + operator, + order, + reason="运营纠正误关联", + expected_version=order.version, + ) + + self.session.refresh(order) + assert order.account_id is None + assert order.status == collab.STATUS_INCOMPLETE + + def test_recommend_accounts_prefers_unbound_and_can_exclude_rebindable(self): + mapping = PlatformCommodityMapping( + target_platform="douyu", + internal_sku_key="推荐礼包", + commodity_id="gift-a", + goods_name="推荐礼包", + required_points=100, + scope="elite", + enabled=True, + ) + self.session.add(mapping) + self.session.flush() + order = collab.create_order( + self.session, + self.admin, + order_no="DY-RECOMMEND", + shop="店铺A", + gift_name="推荐礼包", + draft=True, + ) + bound = Account( + username="douyu-account-bound", + password="password", + email="bound@example.com", + email_password="mail-password", + cookie="acf_uid=200; acf_nickname=bound", + status="active", + auto_managed=True, + elite_opened=True, + points=1000, + ) + empty = Account( + username="douyu-account-empty", + password="password", + email="empty@example.com", + email_password="mail-password", + cookie="acf_uid=300; acf_nickname=empty", + status="active", + auto_managed=True, + elite_opened=True, + points=500, + role_bind_status="unbound", + ) + self.session.add_all([bound, empty]) + self.session.commit() + clients = { + int(self.account.id): FakeClient(), + int(bound.id): FakeClient(), + int(empty.id): FakeUnboundClient(), + } + + result = collab.recommend_accounts( + self.session, + self.admin, + order, + include_rebindable=True, + limit=5, + client_factory=lambda account: clients[int(account.id)], + ) + + assert order.commodity_id == "gift-a" + assert result["candidates"][0]["account_id"] == empty.id + assert result["candidates"][0]["match_type"] == "empty" + assert any(item["match_type"] == "rebind" for item in result["candidates"]) + DouyuCollabAccountRecommendOut.model_validate(result) + + unbound_only = collab.recommend_accounts( + self.session, + self.admin, + order, + include_rebindable=False, + limit=5, + client_factory=lambda account: clients[int(account.id)], + ) + assert [item["account_id"] for item in unbound_only["candidates"]] == [ + empty.id + ] + def test_create_strict_order_uses_internal_account_and_advances(self): order = collab.create_order( self.session, diff --git a/web/backend/routers/douyu_collab.py b/web/backend/routers/douyu_collab.py index ab146c8..9d42661 100644 --- a/web/backend/routers/douyu_collab.py +++ b/web/backend/routers/douyu_collab.py @@ -28,7 +28,10 @@ from ..permissions import get_user_permissions from ..schemas import ( DouyuCollabAccountLookupOut, DouyuCollabAccountLookupRequest, + DouyuCollabAccountRecommendOut, + DouyuCollabAccountRecommendRequest, DouyuCollabAccountRequest, + DouyuCollabAccountUnlinkRequest, DouyuCollabArchiveRequest, DouyuCollabCkExportOut, DouyuCollabCkExportRequest, @@ -344,6 +347,57 @@ def set_external_order_account( raise _http_error(exc) from exc +@router.post( + "/external-orders/{order_id}/account/unlink", + response_model=DouyuCollabOrderOut, +) +def unlink_external_order_account( + order_id: int, + req: DouyuCollabAccountUnlinkRequest, + db: Session = Depends(get_db), + current: User = Depends(require_permission("douyu:collab:edit")), +): + try: + order = collab.get_order(db, order_id) + collab.unlink_account( + db, + current, + order, + reason=req.reason, + expected_version=req.expected_version, + ) + _publish_change(current, scope="orders", action="order.account_unlink") + return _one(db, order) + except collab.CollabError as exc: + raise _http_error(exc) from exc + + +@router.post( + "/external-orders/{order_id}/account/recommend", + response_model=DouyuCollabAccountRecommendOut, +) +def recommend_external_order_account( + order_id: int, + req: DouyuCollabAccountRecommendRequest, + db: Session = Depends(get_db), + current: User = Depends(require_permission("douyu:collab:edit")), +): + try: + order = collab.get_order(db, order_id) + return collab.recommend_accounts( + db, + current, + order, + include_rebindable=req.include_rebindable, + limit=req.limit, + gift_name=req.gift_name, + commodity_id=req.commodity_id, + required_points=req.required_points, + ) + except collab.CollabError as exc: + raise _http_error(exc) from exc + + @router.post("/external-orders/{order_id}/verify") def verify_external_order( order_id: int, diff --git a/web/backend/schemas.py b/web/backend/schemas.py index 64fa807..80afbd8 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -2599,6 +2599,49 @@ class DouyuCollabAccountRequest(BaseModel): takeover_platform_lease: bool = False +class DouyuCollabAccountUnlinkRequest(BaseModel): + reason: str = Field(..., min_length=1, max_length=256) + expected_version: int | None = None + + +class DouyuCollabAccountRecommendRequest(BaseModel): + """按当前订单礼包推荐可绑定账号;不会预占账号。""" + + include_rebindable: bool = True + limit: int = Field(5, ge=1, le=10) + gift_name: str | None = Field(None, max_length=128) + commodity_id: str | None = Field(None, max_length=64) + required_points: int | None = Field(None, ge=0) + + +class DouyuCollabAccountCandidateOut(BaseModel): + account_id: int + account_username: str = "" + account_uid: str = "" + account_nickname: str = "" + ck_status: str = "" + role_status: str = "" + bind_game_role: str = "" + role_change_available_at: datetime | None = None + points: int | None = None + elite_opened: bool | None = None + match_type: str = "" + match_type_label: str = "" + ready: bool = False + reasons: list[str] = Field(default_factory=list) + + +class DouyuCollabAccountRecommendOut(BaseModel): + order_id: int + gift_name: str = "" + commodity_id: str = "" + required_points: int | None = None + include_rebindable: bool = True + scanned: int = 0 + candidates: list[DouyuCollabAccountCandidateOut] = Field(default_factory=list) + message: str = "" + + class DouyuCollabImagesRequest(BaseModel): home_images: list[str] = Field(default_factory=list) expected_version: int | None = None diff --git a/web/backend/services/douyu_collab_service.py b/web/backend/services/douyu_collab_service.py index 06289d0..a59dda5 100644 --- a/web/backend/services/douyu_collab_service.py +++ b/web/backend/services/douyu_collab_service.py @@ -13,7 +13,7 @@ from __future__ import annotations -from collections.abc import Mapping, Sequence +from collections.abc import Callable, Mapping, Sequence from datetime import UTC, datetime from typing import Any @@ -39,7 +39,12 @@ from ..models import ( User, ) from ..permissions import user_has_permission -from .account_binding import binding_channel, binding_role_from_result +from .account_binding import ( + binding_channel, + binding_role_from_result, + can_change_role, + role_change_available_at, +) from .account_events_service import ( CATEGORY_OPS, EVENT_COLLAB_SYNCED, @@ -54,6 +59,7 @@ from .douyu_account_probe import ( ROLE_BOUND, ROLE_ERROR, ROLE_PENDING, + ROLE_UNBOUND, ROLE_UNKNOWN, SESSION_INVALID, SESSION_VALID, @@ -77,6 +83,8 @@ from .file_service import build_file_url from .platform_fulfillment.account_selector import ( acquire_account_lease, active_lease_for_account, + has_recent_exchange, + live_candidate_accounts, release_lease, ) @@ -137,6 +145,8 @@ STATUS_FLOW: tuple[str, ...] = ( ) SOURCE_TYPE_PLATFORM_FULFILLMENT = "platform_fulfillment" +ACCOUNT_REPLACE_ROLES = frozenset({"super_admin", "operation"}) +ACCOUNT_RECOMMEND_DEFAULT_SCAN_LIMIT = 30 PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES = frozenset( { "lock_goods", @@ -498,6 +508,295 @@ def lookup_account( return probe +def unlink_account( + db: Session, + current: User, + order: DouyuExternalOrder, + *, + reason: str, + expected_version: int | None = None, + commit: bool = True, +) -> DouyuExternalOrder: + """解除协作单与账号的关联,但不删除内部账号。""" + _assert_account_replace_permission(current) + _assert_account_replaceable(order) + _assert_version(order, expected_version) + if not order.account_id and not _text(order.account_username): + raise CollabError("这单还没有关联斗鱼账号", code="account_not_linked") + + clean_reason = _text(reason, max_length=256) + if not clean_reason: + raise CollabError("请填写解除账号的原因", code="reason_required") + + previous = { + "account_id": order.account_id, + "account_username": order.account_username or "", + "account_uid": order.account_uid or "", + "account_nickname": order.account_nickname or "", + "bind_game_account": order.bind_game_account or "", + "bind_game_role": order.bind_game_role or "", + "bind_game_channel": order.bind_game_channel or "", + "status": order.status, + } + released_lease = _release_order_account_lease( + db, + current, + order, + reason="douyu_collab_account_unlinked", + ) + + order.account_id = None + order.account_username = "" + order.account_uid = "" + order.account_nickname = "" + order.bind_game_account = "" + order.bind_game_role = "" + order.bind_game_channel = "" + order.bind_snapshot_at = None + order.fish_fin_balance = None + order.points_balance = None + order.points_required_total = None + order.points_surplus = None + order.points_checked_at = None + order.points_check_reason = "" + order.points_check_message = "" + order.points_check_detail = None + order.recharged_at = None + order.scripted_at = None + order.done_at = None + order.status = STATUS_INCOMPLETE + order.updated_by = current.id + order.updated_at = _now() + order.version = int(order.version or 0) + 1 + + record_audit( + db, + current, + action="douyu:collab:account_unlink", + target=f"douyu_external_order:{order.id}", + detail={ + "reason": clean_reason, + "previous": previous, + "released_lease": bool(released_lease), + "status": order.status, + }, + ) + if commit: + db.commit() + db.refresh(order) + return order + + +def recommend_accounts( + db: Session, + current: User, + order: DouyuExternalOrder, + *, + include_rebindable: bool = True, + limit: int = 5, + gift_name: str | None = None, + commodity_id: str | None = None, + required_points: Any = None, + scan_limit: int | None = None, + client_factory: Callable[[Account], Any] | None = None, +) -> dict[str, Any]: + """推荐可绑定/可换绑账号;只读探测,不创建租约。""" + _assert_account_replace_permission(current) + _assert_account_replaceable(order) + + name, cid, points = _resolve_gift( + db, + gift_name=gift_name if gift_name is not None else order.gift_name, + commodity_id=( + commodity_id if commodity_id is not None else order.commodity_id + ), + required_points=( + required_points if required_points is not None else order.required_points + ), + ) + required = max(0, int(points or 0)) + effective_scan_limit = max( + 1, + min( + int(scan_limit or ACCOUNT_RECOMMEND_DEFAULT_SCAN_LIMIT), + 100, + ), + ) + candidates = live_candidate_accounts( + db, + limit=effective_scan_limit, + required_points=required, + commodity_id=cid, + prefer_unbound=True, + empty_only=not include_rebindable, + ) + config = resolve_config(db) + manual_id = str(config.manual_id or "") + rid = str(config.rid or "") + act_alias = str(config.bind_act_alias or "") + confirm_act_alias = str(config.confirm_act_alias or "") + legacy_act_alias = str(config.legacy_act_alias or "") + output: list[dict[str, Any]] = [] + scanned = 0 + + for account in candidates: + if order.account_id and int(account.id) == int(order.account_id): + continue + scanned += 1 + try: + probe = _probe_with_client( + account, + manual_id=manual_id, + rid=rid, + act_alias=act_alias, + confirm_act_alias=confirm_act_alias, + legacy_act_alias=legacy_act_alias, + client=client_factory(account) if client_factory else None, + with_goods=bool(cid), + ) + except Exception as exc: # noqa: BLE001 - 单账号失败继续扫描 + logger.info( + "[douyu-collab] 推荐账号跳过 account_id={} error={}", + account.id, + exc, + ) + continue + + if str(probe.get("ck_status") or "") != CK_VALID: + continue + role_status = str(probe.get("role_status") or ROLE_UNKNOWN) + canonical = probe.get("_probe_result") + canonical_role = ( + (canonical.get("roles") or {}).get("elite") or {} + if isinstance(canonical, Mapping) + else {} + ) + bind_info = ( + canonical_role.get("bind_info") + if isinstance(canonical_role.get("bind_info"), dict) + else None + ) + if role_status == ROLE_UNBOUND: + match_type = "empty" + match_label = "未绑定" + elif role_status == ROLE_BOUND and can_change_role(bind_info): + if not include_rebindable: + continue + match_type = "rebind" + match_label = "可换绑" + else: + continue + + canonical_eligibility = ( + canonical.get("eligibility") or {} + if isinstance(canonical, Mapping) + else {} + ) + limited_ids = { + str(item) + for item in canonical_eligibility.get("limited_ids") or [] + if str(item) + } + if cid and cid in limited_ids: + continue + if cid and has_recent_exchange( + db, + account_id=int(account.id), + commodity_id=cid, + ): + continue + + goods = probe.get("goods") or [] + target_goods = next( + ( + item + for item in goods + if isinstance(item, Mapping) + and str(item.get("commodity_id") or "") == cid + ), + None, + ) + if target_goods is not None: + if str(target_goods.get("status") or "") == "1": + continue + if _to_int(target_goods.get("open_status")) == 0: + continue + + live_points = _to_int(probe.get("manual_score")) + elite_opened = probe.get("manual_opened") + elite_opened_value = bool(elite_opened) if elite_opened is not None else None + ready = bool( + elite_opened_value is True + and live_points is not None + and live_points >= required + ) + reasons = [ + "未绑定角色,可直接绑定" + if match_type == "empty" + else "已绑定角色,当前可换绑" + ] + if elite_opened_value is not True: + reasons.append("精英宝典未开通") + if live_points is None or live_points < required: + reasons.append(f"积分不足({live_points or 0}/{required})") + if cid and target_goods is None: + reasons.append("商品列表未返回该礼包,绑定后请复核") + + output.append( + { + "account_id": int(account.id), + # 后续“使用此账号”会按内部 username 反查,不能用接口返回的展示昵称。 + "account_username": str(account.username or ""), + "account_uid": str(probe.get("account_uid") or account.uid or ""), + "account_nickname": str( + probe.get("account_nickname") + or account.nickname + or account.username + or "" + ), + "ck_status": str(probe.get("ck_status") or ""), + "role_status": role_status, + "bind_game_role": str(probe.get("bind_game_role") or ""), + "role_change_available_at": role_change_available_at(bind_info), + "points": live_points, + "elite_opened": elite_opened_value, + "match_type": match_type, + "match_type_label": match_label, + "ready": ready, + "reasons": reasons, + } + ) + if len(output) >= max(1, min(int(limit), 10)): + break + + output.sort( + key=lambda item: ( + 0 if item["match_type"] == "empty" else 1, + 0 if item["ready"] else 1, + int(item["points"] or 0), + int(item["account_id"]), + ) + ) + selected = output[: max(1, min(int(limit), 10))] + message = ( + f"找到 {len(selected)} 个可用账号,未绑定账号优先" + if selected + else "当前没有找到未绑定或已过换绑冷却的可用账号" + ) + if not include_rebindable: + message += ";当前仅搜索未绑定账号" + return { + "order_id": int(order.id), + "gift_name": name, + "commodity_id": cid, + "required_points": points, + "include_rebindable": bool(include_rebindable), + "scanned": scanned, + "candidates": selected, + "message": message, + } + + def apply_probe_snapshot( db: Session, current: User, @@ -555,6 +854,25 @@ def _assert_mutable(order: DouyuExternalOrder) -> None: raise CollabError("已作废的订单不能再编辑", code="order_void") +def _assert_account_replace_permission(current: User) -> None: + """撤号和推荐属于高风险改号操作,只允许超级管理员和运营。""" + if current.role not in ACCOUNT_REPLACE_ROLES: + raise CollabError( + "仅超级管理员和运营可以解除或推荐账号", + status_code=403, + code="account_replace_forbidden", + ) + + +def _assert_account_replaceable(order: DouyuExternalOrder) -> None: + _assert_mutable(order) + if order.status == STATUS_DONE or order.done_at is not None: + raise CollabError( + "已完成订单不能更换账号,请先确认是否需要回退状态", + code="order_done_immutable", + ) + + def _order_occupies_account(order: DouyuExternalOrder) -> bool: return ( bool(order.account_id) @@ -1058,6 +1376,24 @@ def _resolve_gift( points = int(manual.points or 0) return name, cid, points if not cid and name: + mapping = ( + db.query(PlatformCommodityMapping) + .filter( + PlatformCommodityMapping.target_platform == "douyu", + PlatformCommodityMapping.enabled.is_(True), + or_( + PlatformCommodityMapping.goods_name == name, + PlatformCommodityMapping.internal_sku_key == name, + ), + ) + .order_by(PlatformCommodityMapping.id.desc()) + .first() + ) + if mapping is not None: + cid = _text(mapping.commodity_id, max_length=64) + if points is None: + points = _to_int(mapping.required_points) + return name, cid, points # 接口暂时不返回商品时,管理员配置的礼包名称和积分仍然可用。 manual = db.query(DouyuCollabGift).filter(DouyuCollabGift.name == name).first() if manual is not None: diff --git a/web/backend/services/platform_fulfillment/account_selector.py b/web/backend/services/platform_fulfillment/account_selector.py index 229c725..b449abd 100644 --- a/web/backend/services/platform_fulfillment/account_selector.py +++ b/web/backend/services/platform_fulfillment/account_selector.py @@ -161,6 +161,8 @@ def live_candidate_accounts( limit: int = 20, required_points: int = 0, commodity_id: str = "", + prefer_unbound: bool = False, + empty_only: bool = False, ) -> list[Account]: """按缓存质量优先排序,但保留实时检测作为最终准入判断。""" owner_ids = _pool_owner_ids() @@ -197,20 +199,25 @@ def live_candidate_accounts( .exists() ) query = query.filter(~exchanged) + if empty_only: + query = query.filter(Account.role_bind_status == "unbound") + order_by = [ + case((Account.ck_check_status == "valid", 0), else_=1), + case((Account.status == "active", 0), else_=1), + case((Account.elite_opened.is_(True), 0), else_=1), + case( + (Account.points >= max(0, int(required_points)), 0), + else_=1, + ), + Account.ck_checked_at.is_(None).desc(), + Account.ck_checked_at.asc(), + Account.points.asc(), + Account.id.asc(), + ] + if prefer_unbound: + order_by.insert(0, case((Account.role_bind_status == "unbound", 0), else_=1)) return ( - query.order_by( - case((Account.ck_check_status == "valid", 0), else_=1), - case((Account.status == "active", 0), else_=1), - case((Account.elite_opened.is_(True), 0), else_=1), - case( - (Account.points >= max(0, int(required_points)), 0), - else_=1, - ), - Account.ck_checked_at.is_(None).desc(), - Account.ck_checked_at.asc(), - Account.points.asc(), - Account.id.asc(), - ) + query.order_by(*order_by) .limit(max(1, min(int(limit), 100))) .all() ) diff --git a/web/frontend/src/api/douyuCollab.ts b/web/frontend/src/api/douyuCollab.ts index 0c85413..1323aeb 100644 --- a/web/frontend/src/api/douyuCollab.ts +++ b/web/frontend/src/api/douyuCollab.ts @@ -221,6 +221,34 @@ export interface DouyuCollabAccountLookup { }>; } +export interface DouyuCollabAccountCandidate { + account_id: number; + account_username: string; + account_uid: string; + account_nickname: string; + ck_status: string; + role_status: string; + bind_game_role: string; + role_change_available_at: string | null; + points: number | null; + elite_opened: boolean | null; + match_type: 'empty' | 'rebind' | string; + match_type_label: string; + ready: boolean; + reasons: string[]; +} + +export interface DouyuCollabAccountRecommendation { + order_id: number; + gift_name: string; + commodity_id: string; + required_points: number | null; + include_rebindable: boolean; + scanned: number; + candidates: DouyuCollabAccountCandidate[]; + message: string; +} + export interface DouyuCollabOrderCreate { order_no: string; shop?: string; @@ -383,6 +411,25 @@ export const douyuCollabApi = { expected_version, takeover_platform_lease, }), + unlinkAccount: (id: number, reason: string, expected_version?: number) => + api.post( + `/douyu/external-orders/${id}/account/unlink`, + { reason, expected_version }, + ), + recommendAccount: ( + id: number, + data: { + include_rebindable?: boolean; + limit?: number; + gift_name?: string; + commodity_id?: string; + required_points?: number | null; + } = {}, + ) => + api.post( + `/douyu/external-orders/${id}/account/recommend`, + data, + ), verifyOrder: (id: number) => api.post<{ order: DouyuCollabOrder; probe: DouyuCollabAccountLookup }, { order: DouyuCollabOrder; probe: DouyuCollabAccountLookup }>( `/douyu/external-orders/${id}/verify`, diff --git a/web/frontend/src/pages/DouyuCollabPage.tsx b/web/frontend/src/pages/DouyuCollabPage.tsx index 1aaad79..05f7d91 100644 --- a/web/frontend/src/pages/DouyuCollabPage.tsx +++ b/web/frontend/src/pages/DouyuCollabPage.tsx @@ -33,6 +33,7 @@ import { CheckCircleOutlined, CopyOutlined, DeleteOutlined, + DisconnectOutlined, EditOutlined, FormOutlined, GiftOutlined, @@ -40,6 +41,7 @@ import { LinkOutlined, PlusOutlined, ReloadOutlined, + RobotOutlined, SafetyCertificateOutlined, SearchOutlined, ShopOutlined, @@ -47,6 +49,7 @@ import { TagOutlined, UndoOutlined, UserOutlined, + UserSwitchOutlined, } from '@ant-design/icons'; import HuyaCollabHomeImageUploader from '../components/HuyaCollabHomeImageUploader'; import DouyuCollabGiftModal from '../components/DouyuCollabGiftModal'; @@ -54,7 +57,9 @@ import DouyuCollabShopModal from '../components/DouyuCollabShopModal'; import DouyuCollabShopPicker from '../components/DouyuCollabShopPicker'; import { douyuCollabApi } from '../api/modules'; import type { + DouyuCollabAccountCandidate, DouyuCollabAccountLookup, + DouyuCollabAccountRecommendation, DouyuCollabCkExportResult, DouyuCollabGift, DouyuCollabGoods, @@ -211,6 +216,8 @@ export default function DouyuCollabPage() { const canEdit = can('douyu:collab:edit'); const canManage = can('douyu:collab:manage'); const canExportCk = can('douyu:collab:ck_export'); + const canReplaceAccount = + canEdit && (user?.role === 'super_admin' || user?.role === 'operation'); // 单行复制是一键带走凭据,和虎牙台账保持一致:只给超级管理员(后端再校验) const isAdmin = user?.role === 'super_admin'; @@ -256,6 +263,16 @@ export default function DouyuCollabPage() { const lookupSeq = useRef(0); const [lookupLoading, setLookupLoading] = useState(false); const [submitting, setSubmitting] = useState(false); + const [unlinkOpen, setUnlinkOpen] = useState(false); + const [unlinkReason, setUnlinkReason] = useState(''); + const [unlinkBusy, setUnlinkBusy] = useState(false); + const [recommendOpen, setRecommendOpen] = useState(false); + const [recommendLoading, setRecommendLoading] = useState(false); + const [recommendResult, setRecommendResult] = + useState(null); + const [recommendIncludeRebindable, setRecommendIncludeRebindable] = useState(true); + const [applyingCandidateId, setApplyingCandidateId] = useState(null); + const recommendSeq = useRef(0); const [detail, setDetail] = useState(null); const [detailOpen, setDetailOpen] = useState(false); @@ -375,7 +392,9 @@ export default function DouyuCollabPage() { batchStatusOpen || statusTarget || ckExportOpen || - usernameExportOpen, + usernameExportOpen || + unlinkOpen || + recommendOpen, ); // 暂停后连 WebSocket 也不建:既不自动重拉,也不做断线兜底轮询。 const realtimeSyncEnabled = canView && !realtimePaused; @@ -534,6 +553,10 @@ export default function DouyuCollabPage() { lookupSeq.current += 1; setLookup(null); setLookupLoading(false); + recommendSeq.current += 1; + setUnlinkOpen(false); + setRecommendOpen(false); + setRecommendResult(null); setCreateOpen(true); }; @@ -553,6 +576,10 @@ export default function DouyuCollabPage() { lookupSeq.current += 1; setLookup(null); setLookupLoading(false); + recommendSeq.current += 1; + setUnlinkOpen(false); + setRecommendOpen(false); + setRecommendResult(null); setCreateOpen(true); }; @@ -718,6 +745,104 @@ export default function DouyuCollabPage() { } }; + const openUnlinkAccount = () => { + if (!editing || !form.account_username.trim()) return; + setUnlinkReason(''); + setUnlinkOpen(true); + }; + + const submitUnlinkAccount = async () => { + if (!editing) return; + const reason = unlinkReason.trim(); + if (!reason) { + message.warning('请填写解除账号的原因'); + return; + } + setUnlinkBusy(true); + try { + const updated = await douyuCollabApi.unlinkAccount( + editing.id, + reason, + editing.version, + ); + setEditing(updated); + setForm((previous) => ({ ...previous, account_username: '' })); + lookupSeq.current += 1; + setLookup(null); + setUnlinkOpen(false); + message.success('已解除账号关联,订单已回到待补资料'); + refreshAll(); + } catch (error) { + message.error(getErrorMessage(error)); + } finally { + setUnlinkBusy(false); + } + }; + + const loadRecommendations = async (includeRebindable: boolean) => { + if (!editing) return; + const seq = ++recommendSeq.current; + setRecommendLoading(true); + try { + const result = await douyuCollabApi.recommendAccount(editing.id, { + include_rebindable: includeRebindable, + limit: 5, + gift_name: form.gift_name || undefined, + commodity_id: form.commodity_id || undefined, + required_points: form.required_points, + }); + if (seq !== recommendSeq.current) return; + setRecommendResult(result); + } catch (error) { + if (seq === recommendSeq.current) message.error(getErrorMessage(error)); + } finally { + if (seq === recommendSeq.current) setRecommendLoading(false); + } + }; + + const openRecommendAccount = () => { + if (!editing) return; + setRecommendIncludeRebindable(true); + setRecommendResult(null); + setRecommendOpen(true); + void loadRecommendations(true); + }; + + const applyRecommendedAccount = async ( + candidate: DouyuCollabAccountCandidate, + ) => { + if (!editing) return; + setApplyingCandidateId(candidate.account_id); + try { + const updated = await douyuCollabApi.setAccount( + editing.id, + candidate.account_username, + editing.version, + ); + setEditing(updated); + setForm((previous) => ({ + ...previous, + account_username: updated.account_username, + })); + lookupSeq.current += 1; + setLookup(null); + recommendSeq.current += 1; + setRecommendOpen(false); + setRecommendResult(null); + message.success(`已绑定推荐账号 ${updated.account_username}`); + refreshAll(); + } catch (error) { + if (errorCodeOf(error) === 'account_lease_conflict') { + message.warning('推荐账号刚刚被其他任务占用,请重新推荐'); + void loadRecommendations(recommendIncludeRebindable); + } else { + message.error(getErrorMessage(error)); + } + } finally { + setApplyingCandidateId(null); + } + }; + const verifyOrder = async (order: DouyuCollabOrder) => { try { message.loading({ content: '正在校验账号…', key: 'dy-collab-verify' }); @@ -1447,6 +1572,15 @@ export default function DouyuCollabPage() { menu={{ items: [ { key: 'edit', label: '编辑资料', icon: }, + ...(canReplaceAccount && row.status !== 'done' + ? [ + { + key: 'account_replace', + label: '换绑账号…', + icon: , + }, + ] + : []), { key: 'status', label: '改状态…', icon: }, ...(row.status === 'done' ? [{ key: 'archive', label: '归档…', icon: }] @@ -1457,6 +1591,7 @@ export default function DouyuCollabPage() { ], onClick: ({ key }) => { if (key === 'edit') openEdit(row); + if (key === 'account_replace') openEdit(row); if (key === 'status') openStatus(row); if (key === 'archive') void archiveOrders(row); if (key === 'delete') deleteOrder(row); @@ -1995,6 +2130,30 @@ export default function DouyuCollabPage() { } /> )} + {editing && + canReplaceAccount && + editing.status !== 'done' && + editing.status !== 'void' && ( + + + + + 解除不会删除内部账号;推荐结果确认后才会占用账号 + + + )} @@ -2078,6 +2237,137 @@ export default function DouyuCollabPage() { + setUnlinkOpen(false)} + onOk={() => void submitUnlinkAccount()} + confirmLoading={unlinkBusy} + okText="确认解除" + okButtonProps={{ danger: true }} + destroyOnHidden + > + + + setUnlinkReason(event.target.value)} + /> + + + + setRecommendOpen(false)} + width={760} + footer={[ + , + , + ]} + destroyOnHidden + > + + + + { + setRecommendIncludeRebindable(checked); + void loadRecommendations(checked); + }} + /> + 包含已过换绑冷却的账号 + + + 礼包:{recommendResult?.gift_name || form.gift_name || '-'} · 需要{' '} + {recommendResult?.required_points ?? form.required_points ?? '-'} 积分 · 已扫描{' '} + {recommendResult?.scanned ?? 0} 个候选 + + {recommendResult?.message && {recommendResult.message}} + {recommendLoading ? ( + 正在实时检查账号 CK、角色和换绑状态… + ) : recommendResult?.candidates.length ? ( + recommendResult.candidates.map((candidate) => ( + + + + + {candidate.account_nickname || candidate.account_username} + + + {candidate.match_type_label} + + {candidate.ready ? ( + 资格齐全 + ) : ( + 需后续处理 + )} + 账号 {candidate.account_username} + {candidate.account_uid && ( + UID {candidate.account_uid} + )} + + + 积分 {candidate.points ?? '-'} + + 精英宝典{candidate.elite_opened === true ? '已开通' : '未开通'} + + {candidate.bind_game_role && ( + 当前角色 {candidate.bind_game_role} + )} + + + {candidate.reasons.map((reason) => ( + {reason} + ))} + + + + + )) + ) : ( + + )} + + +