feat(douyu): 支持外部协作单撤销并推荐账号

This commit is contained in:
yml
2026-11-20 13:02:40 +08:00
parent 1a49bcd481
commit 55021a683c
8 changed files with 1045 additions and 16 deletions
+54
View File
@@ -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,
+43
View File
@@ -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
+338 -2
View File
@@ -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:
@@ -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()
)