feat(douyu): 支持外部协作单撤销并推荐账号
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
)
|
||||
|
||||
@@ -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<DouyuCollabOrder, DouyuCollabOrder>(
|
||||
`/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<DouyuCollabAccountRecommendation, DouyuCollabAccountRecommendation>(
|
||||
`/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`,
|
||||
|
||||
@@ -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<DouyuCollabAccountRecommendation | null>(null);
|
||||
const [recommendIncludeRebindable, setRecommendIncludeRebindable] = useState(true);
|
||||
const [applyingCandidateId, setApplyingCandidateId] = useState<number | null>(null);
|
||||
const recommendSeq = useRef(0);
|
||||
|
||||
const [detail, setDetail] = useState<DouyuCollabOrder | null>(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: <EditOutlined /> },
|
||||
...(canReplaceAccount && row.status !== 'done'
|
||||
? [
|
||||
{
|
||||
key: 'account_replace',
|
||||
label: '换绑账号…',
|
||||
icon: <UserSwitchOutlined />,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{ key: 'status', label: '改状态…', icon: <CheckCircleOutlined /> },
|
||||
...(row.status === 'done'
|
||||
? [{ key: 'archive', label: '归档…', icon: <InboxOutlined /> }]
|
||||
@@ -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' && (
|
||||
<Space style={{ marginTop: 8 }} wrap>
|
||||
<Button
|
||||
danger
|
||||
icon={<DisconnectOutlined />}
|
||||
disabled={!form.account_username.trim()}
|
||||
onClick={openUnlinkAccount}
|
||||
>
|
||||
解除账号
|
||||
</Button>
|
||||
<Button
|
||||
icon={<RobotOutlined />}
|
||||
onClick={openRecommendAccount}
|
||||
>
|
||||
推荐账号
|
||||
</Button>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
解除不会删除内部账号;推荐结果确认后才会占用账号
|
||||
</Text>
|
||||
</Space>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Row gutter={16}>
|
||||
@@ -2078,6 +2237,137 @@ export default function DouyuCollabPage() {
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title={`解除账号:${editing?.order_no || ''}`}
|
||||
open={unlinkOpen}
|
||||
onCancel={() => setUnlinkOpen(false)}
|
||||
onOk={() => void submitUnlinkAccount()}
|
||||
confirmLoading={unlinkBusy}
|
||||
okText="确认解除"
|
||||
okButtonProps={{ danger: true }}
|
||||
destroyOnHidden
|
||||
>
|
||||
<Space direction="vertical" size={12} style={{ width: '100%' }}>
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
message={`将解除账号「${form.account_username || '-'}」与本单的关联`}
|
||||
description="不会删除内部账号。账号身份、角色、鱼翅和积分快照会清空,订单回到待补资料;如果账号仍被履约任务或其他活动协作单占用,不会释放其租约。"
|
||||
/>
|
||||
<Input.TextArea
|
||||
rows={3}
|
||||
maxLength={256}
|
||||
value={unlinkReason}
|
||||
placeholder="填写解除原因,例如:账号已被履约单 6919748168831020505 使用"
|
||||
onChange={(event) => setUnlinkReason(event.target.value)}
|
||||
/>
|
||||
</Space>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title={`推荐账号:${editing?.order_no || ''}`}
|
||||
open={recommendOpen}
|
||||
onCancel={() => setRecommendOpen(false)}
|
||||
width={760}
|
||||
footer={[
|
||||
<Button key="close" onClick={() => setRecommendOpen(false)}>
|
||||
关闭
|
||||
</Button>,
|
||||
<Button
|
||||
key="reload"
|
||||
icon={<ReloadOutlined />}
|
||||
loading={recommendLoading}
|
||||
onClick={() => void loadRecommendations(recommendIncludeRebindable)}
|
||||
>
|
||||
重新推荐
|
||||
</Button>,
|
||||
]}
|
||||
destroyOnHidden
|
||||
>
|
||||
<Space direction="vertical" size={12} style={{ width: '100%' }}>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
message="推荐结果不会预占账号"
|
||||
description="选择后会再次实时校验 CK、租约、活动协作单和换绑冷却。未绑定账号优先;关闭下方开关后只搜索未绑定账号。"
|
||||
/>
|
||||
<Space>
|
||||
<Switch
|
||||
checked={recommendIncludeRebindable}
|
||||
onChange={(checked) => {
|
||||
setRecommendIncludeRebindable(checked);
|
||||
void loadRecommendations(checked);
|
||||
}}
|
||||
/>
|
||||
<Text>包含已过换绑冷却的账号</Text>
|
||||
</Space>
|
||||
<Text type="secondary">
|
||||
礼包:{recommendResult?.gift_name || form.gift_name || '-'} · 需要{' '}
|
||||
{recommendResult?.required_points ?? form.required_points ?? '-'} 积分 · 已扫描{' '}
|
||||
{recommendResult?.scanned ?? 0} 个候选
|
||||
</Text>
|
||||
{recommendResult?.message && <Text>{recommendResult.message}</Text>}
|
||||
{recommendLoading ? (
|
||||
<Text type="secondary">正在实时检查账号 CK、角色和换绑状态…</Text>
|
||||
) : recommendResult?.candidates.length ? (
|
||||
recommendResult.candidates.map((candidate) => (
|
||||
<Card key={candidate.account_id} size="small">
|
||||
<Space direction="vertical" size={8} style={{ width: '100%' }}>
|
||||
<Space wrap>
|
||||
<Text strong>
|
||||
{candidate.account_nickname || candidate.account_username}
|
||||
</Text>
|
||||
<Tag color={candidate.match_type === 'empty' ? 'green' : 'blue'}>
|
||||
{candidate.match_type_label}
|
||||
</Tag>
|
||||
{candidate.ready ? (
|
||||
<Tag color="success">资格齐全</Tag>
|
||||
) : (
|
||||
<Tag color="orange">需后续处理</Tag>
|
||||
)}
|
||||
<Text type="secondary">账号 {candidate.account_username}</Text>
|
||||
{candidate.account_uid && (
|
||||
<Text type="secondary">UID {candidate.account_uid}</Text>
|
||||
)}
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<Text>积分 {candidate.points ?? '-'}</Text>
|
||||
<Text>
|
||||
精英宝典{candidate.elite_opened === true ? '已开通' : '未开通'}
|
||||
</Text>
|
||||
{candidate.bind_game_role && (
|
||||
<Text>当前角色 {candidate.bind_game_role}</Text>
|
||||
)}
|
||||
</Space>
|
||||
<Space wrap>
|
||||
{candidate.reasons.map((reason) => (
|
||||
<Tag key={reason}>{reason}</Tag>
|
||||
))}
|
||||
</Space>
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
loading={applyingCandidateId === candidate.account_id}
|
||||
disabled={
|
||||
applyingCandidateId !== null &&
|
||||
applyingCandidateId !== candidate.account_id
|
||||
}
|
||||
onClick={() => void applyRecommendedAccount(candidate)}
|
||||
>
|
||||
使用此账号
|
||||
</Button>
|
||||
</Space>
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
description="当前没有找到可绑定账号"
|
||||
/>
|
||||
)}
|
||||
</Space>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title={
|
||||
batchStatusOpen
|
||||
|
||||
Reference in New Issue
Block a user