feat(fulfillment): 实时刷新斗鱼账号并支持租约时长设置

This commit is contained in:
yml
2026-11-18 10:59:20 +08:00
parent 0220ef995f
commit 9958e4ab7d
21 changed files with 1546 additions and 120 deletions
@@ -0,0 +1,94 @@
"""直播账号履约租约时长设置
默认账号租约无期限;运营可切换为按分钟或小时自动过期。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261117_0085"
down_revision: str | None = "20261117_0084"
branch_labels: str | None = None
depends_on: str | None = None
def _table_exists(table: str) -> bool:
return bool(
op.get_bind()
.execute(
sa.text(
"SELECT COUNT(*) FROM information_schema.tables "
"WHERE table_schema = DATABASE() AND table_name = :table"
),
{"table": table},
)
.scalar()
)
def upgrade() -> None:
op.alter_column(
"account_leases",
"expires_at",
existing_type=sa.DateTime(),
nullable=True,
)
if not _table_exists("platform_fulfillment_settings"):
op.create_table(
"platform_fulfillment_settings",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("lease_duration_minutes", sa.Integer(), nullable=True),
sa.Column("updated_by", sa.Integer(), nullable=True),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(
["updated_by"],
["users.id"],
name="fk_platform_fulfillment_settings_updated_by",
ondelete="SET NULL",
),
sa.PrimaryKeyConstraint("id"),
)
op.execute(
sa.text(
"""
INSERT INTO platform_fulfillment_settings (
id, lease_duration_minutes, updated_by, updated_at
) VALUES (1, NULL, NULL, NOW())
ON DUPLICATE KEY UPDATE id = id
"""
)
)
# 设置上线即默认无限期;正在使用的租约也立即转为无限期,避免几分钟后中断。
op.execute(
sa.text(
"""
UPDATE account_leases
SET expires_at = NULL
WHERE purpose = 'platform_fulfillment' AND status = 'active'
"""
)
)
def downgrade() -> None:
op.execute(
sa.text(
"""
UPDATE account_leases
SET expires_at = DATE_ADD(NOW(), INTERVAL 5 MINUTE)
WHERE purpose = 'platform_fulfillment'
AND status = 'active'
AND expires_at IS NULL
"""
)
)
if _table_exists("platform_fulfillment_settings"):
op.drop_table("platform_fulfillment_settings")
op.alter_column(
"account_leases",
"expires_at",
existing_type=sa.DateTime(),
nullable=False,
)
+18 -2
View File
@@ -1686,8 +1686,8 @@ class AccountLease(Base):
String(16), nullable=False, default="active", server_default="active"
)
leased_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
# TTL 兜底:进程重启、页面关掉都能靠它把租约收回来。
expires_at: Mapped[datetime] = mapped_column(UTCDateTime, nullable=False)
# 到期时间;NULL 表示按当前设置无限期占用。
expires_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
released_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
release_reason: Mapped[str] = mapped_column(
String(64), nullable=False, default="", server_default=""
@@ -1713,6 +1713,22 @@ class AccountLease(Base):
holder: Mapped[User] = relationship("User")
class PlatformFulfillmentSetting(Base):
"""直播账号履约工作台的持久化设置。"""
__tablename__ = "platform_fulfillment_settings"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
lease_duration_minutes: Mapped[int | None] = mapped_column(Integer, nullable=True)
updated_by: Mapped[int | None] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"),
nullable=True,
)
updated_at: Mapped[datetime] = mapped_column(
UTCDateTime, default=_utcnow, onupdate=_utcnow
)
class PlatformCommodityMapping(Base):
"""order_site 内部 SKU 到斗鱼商品的显式映射。"""
+33 -3
View File
@@ -14,6 +14,7 @@ from ..schemas import (
PlatformFulfillmentCompleteRequest,
PlatformFulfillmentMappingUpsert,
PlatformFulfillmentReasonRequest,
PlatformFulfillmentSettingsUpdate,
)
from ..services.audit_service import record_audit
from ..services.platform_fulfillment import service
@@ -21,6 +22,37 @@ from ..services.platform_fulfillment import service
router = APIRouter(prefix="/api/platform-fulfillment", tags=["直播账号履约"])
@router.get("/settings")
def get_settings(
db: Session = Depends(get_db),
current: User = Depends(require_permission("platform_fulfillment:view")),
) -> dict[str, Any]:
del current
return service.get_settings(db)
@router.put("/settings")
def update_settings(
req: PlatformFulfillmentSettingsUpdate,
db: Session = Depends(get_db),
current: User = Depends(require_permission("platform_fulfillment:admin")),
) -> dict[str, Any]:
result = service.update_settings(
db,
lease_duration_minutes=req.lease_duration_minutes,
current=current,
)
record_audit(
db,
current,
action="platform_fulfillment:settings:update",
target="platform_fulfillment_settings",
detail=result,
)
db.commit()
return result
@router.get("/tasks")
def list_tasks(
status: str = Query("", max_length=32),
@@ -174,9 +206,7 @@ def refresh_eligibility(
db: Session = Depends(get_db),
current: User = Depends(require_permission("platform_fulfillment:use")),
) -> dict[str, Any]:
result = service.refresh_exchange_eligibility(
db, task_id=task_id, current=current
)
result = service.refresh_exchange_eligibility(db, task_id=task_id, current=current)
record_audit(
db,
current,
+4
View File
@@ -1576,6 +1576,10 @@ class PlatformFulfillmentCompleteRequest(BaseModel):
note: str = Field(default="", max_length=1000)
class PlatformFulfillmentSettingsUpdate(BaseModel):
lease_duration_minutes: int | None = Field(..., ge=1, le=525600)
class DouyuTaskBatchRequest(BaseModel):
account_ids: list[int]
task_type: str
+37
View File
@@ -32,6 +32,9 @@
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from ..models import Account
# ── 作用域 ──────────────────────────────────────────────
@@ -239,3 +242,37 @@ def derive_from_bind_info(info: dict | None) -> str | None:
return BIND_UNBOUND
# 接口没给结论:保持 unknown,别把"没查到"写成"没绑定"
return None
def is_role_change_cooling(info: dict | None) -> bool:
"""是否处于真实换绑冷却:已有绑定角色且当前不可换绑。"""
if not isinstance(info, dict):
return False
role_name = str(info.get("role_name") or info.get("role") or "").strip()
if not role_name or not _truthy_flag(info.get("is_bound_act")):
return False
if str(info.get("api_version") or "") == "esports":
can_change_time = _to_int(info.get("can_change_time"))
if can_change_time is not None:
return can_change_time > int(datetime.now(UTC).timestamp())
wait_time = _to_int(info.get("change_role_wait_time"))
if wait_time is not None and wait_time > 0:
return True
if info.get("can_change_role") is not None:
return not _truthy_flag(info.get("can_change_role"))
return False
def _truthy_flag(value: Any) -> bool:
if value is True:
return True
if value is False or value is None:
return False
return str(value).strip().lower() in {"1", "true", "yes", "y"}
def _to_int(value: Any) -> int | None:
try:
return int(float(value))
except (TypeError, ValueError):
return None
@@ -23,24 +23,17 @@ from ...account_value import (
high_value_recheck_seconds,
value_tier_expr,
)
from ...cookie_check_service import check_douyu_cookie
from ...cookie_check_service import (
check_douyu_cookie,
)
from ...cookie_check_service import (
classify_douyu_cookie_result as classify_result,
)
from ...douyu_service import cookie_holding_filter, cookie_operable_filter
JOB_KEY = "ck_health"
FLUSH_EVERY = 25
# 斗鱼明确表示「这个 CK 不能用」的说法。只有命中这些才算真的失效。
AUTH_FAILURE_MARKERS = (
"登陆异常",
"登录异常",
"未登录",
"登陆失效",
"登录失效",
"重新登陆",
"重新登录",
"账户登陆",
)
# 非鉴权类失败(网络超时、响应异常、被判风控)占比超过它就自动暂停作业。
# 这类失败说明「我们查不到」,不是「这个 CK 失效了」;如果不加区分地写
# invalid,斗鱼接口抖动一小时就能把上千个好账号标成失效,客服会误判成
@@ -49,22 +42,6 @@ ERROR_PAUSE_RATIO = 0.3
ERROR_PAUSE_MIN_SCANNED = 20
def classify_result(result: dict[str, Any]) -> str:
"""把检测结果分成三类:valid / invalid(真失效)/ error(查不到)。
- ``valid``:斗鱼两个接口都通过;
- ``invalid``:斗鱼明确回复「未登录 / 登陆异常」之类的鉴权失败;
- ``error``:其余失败(请求失败、超时、响应异常、未知结构)——
**不能当成失效**,也不覆盖该行原来的结论。
"""
if result.get("valid"):
return "valid"
message = str(result.get("message") or "")
if any(marker in message for marker in AUTH_FAILURE_MARKERS):
return "invalid"
return "error"
def _candidates_query(db: Session, job: AutomationJob, now: datetime):
"""本轮「待检测账号」的完整候选集(**不带 LIMIT**,供计数复用)。
@@ -28,6 +28,7 @@ def run_platform_fulfillment_lease_reaper(
.filter(
AccountLease.purpose == "platform_fulfillment",
AccountLease.status == "active",
AccountLease.expires_at.isnot(None),
AccountLease.expires_at <= moment,
)
.limit(max(1, int(job.batch_size or 500)))
@@ -11,6 +11,27 @@ CHECK_UA = (
FISH_BALL_API = "https://www.douyu.com/wjapi/nc/exchange/fishBall"
USER_LEVEL_API = "https://www.douyu.com/japi/interactnc/web/userLevel/userLevelDetail"
AUTH_FAILURE_MARKERS = (
"登陆异常",
"登录异常",
"未登录",
"登陆失效",
"登录失效",
"重新登陆",
"重新登录",
"账户登陆",
)
def classify_douyu_cookie_result(result: dict) -> str:
"""把检测结果分成 valid / invalid / error,区分失效与暂时查不到。"""
if result.get("valid"):
return "valid"
message = str(result.get("message") or "")
if any(marker in message for marker in AUTH_FAILURE_MARKERS):
return "invalid"
return "error"
def check_douyu_cookie(cookie: str) -> dict:
"""检测斗鱼 Cookie 有效性,鱼丸与等级接口均通过才算有效。"""
+310
View File
@@ -0,0 +1,310 @@
"""斗鱼账号实时状态刷新。
选号不能依赖账号上的缓存字段。只要账号持有 CK,本模块就实时检测 CK、
查询精英宝典、积分、限兑商品和绑定冷却,并把结果写回账号生命周期与账号
快照。业务调用方只消费返回的实时结论。
"""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient
from ..models import Account
from .account_binding import (
SCOPE_ELITE,
derive_from_bind_info,
is_role_change_cooling,
set_bind_status,
)
from .account_lifecycle import on_ck_verdict
from .cookie_check_service import check_douyu_cookie, classify_douyu_cookie_result
from .douyu_activity_query import (
activity_client,
query_bind_info,
query_exchange_eligibility,
)
@dataclass(frozen=True)
class DouyuLiveAccountState:
account_id: int
account_name: str
checked_at: datetime
ck_verdict: str
ck_message: str
elite_opened: bool | None
points: int | None
limited_ids: frozenset[str]
role_change_available_at: datetime | None
error: str = ""
role_change_blocked: bool = False
def blocking_reasons(
self,
*,
commodity_id: str,
) -> list[str]:
reasons: list[str] = []
if self.ck_verdict != "valid":
reasons.append(f"CK {self.ck_verdict}: {self.ck_message}")
if self.error:
reasons.append(self.error)
if commodity_id in self.limited_ids:
reasons.append("该商品已达限兑上限")
if self.role_change_blocked:
available_text = (
self.role_change_available_at.isoformat()
if self.role_change_available_at
else "未知时间"
)
reasons.append(f"角色换绑冷却至 {available_text}")
return reasons
def soft_requirement_reasons(self, *, required_points: int) -> list[str]:
"""积分/开通不淘汰账号,只决定后续需要充值还是开通。"""
reasons: list[str] = []
if self.elite_opened is not True:
reasons.append("精英宝典未开通")
if self.points is None or self.points < required_points:
reasons.append(f"积分不足({self.points or 0}/{required_points})")
return reasons
def readiness_rank(self, *, required_points: int) -> int:
"""数值越小越接近直接兑换,用于软条件排序。"""
opened = self.elite_opened is True
enough = self.points is not None and self.points >= required_points
if opened and enough:
return 0
if opened:
return 1
if enough:
return 2
return 3
def refresh_douyu_account_state(
db: Session,
account: Account,
*,
manual_id: str,
rid: str,
act_alias: str,
client: DouyuActivityClient | None = None,
cookie_checker: Callable[[str], dict[str, Any]] = check_douyu_cookie,
commit: bool = True,
) -> DouyuLiveAccountState:
"""实时刷新单个账号,并把所有可落库状态写回账号。"""
now = datetime.now(UTC)
cookie = str(account.cookie or "").strip()
account_name = account.nickname or account.username or f"#{account.id}"
ck_result = cookie_checker(cookie)
ck_verdict = classify_douyu_cookie_result(ck_result)
ck_message = str(ck_result.get("message") or "")
on_ck_verdict(
db,
account,
ck_verdict,
detail=ck_result,
occurred_at=now,
)
if ck_verdict != "valid":
snapshot = {
"queried_at": now.isoformat(),
"ck": ck_result,
"errors": ["CK 检测未通过,未继续查询活动状态"],
}
account.overview_snapshot = _json_safe(snapshot)
account.updated_at = now
if commit:
db.commit()
return DouyuLiveAccountState(
account_id=int(account.id),
account_name=account_name,
checked_at=now,
ck_verdict=ck_verdict,
ck_message=ck_message,
elite_opened=account.elite_opened,
points=account.points,
limited_ids=frozenset(),
role_change_available_at=account.role_change_available_at,
)
active_client = client or activity_client(cookie)
try:
eligibility = query_exchange_eligibility(
active_client,
cookie=cookie,
manual_id=manual_id,
rid=rid,
uid=str(account.uid or ""),
)
except Exception as exc: # noqa: BLE001 外部接口边界需要保留单项诊断
error = f"{type(exc).__name__}: {exc}"[:240]
snapshot = {
"queried_at": now.isoformat(),
"ck": ck_result,
"errors": [error],
}
account.overview_snapshot = _json_safe(snapshot)
account.overview_queried_at = now
account.updated_at = now
if commit:
db.commit()
return DouyuLiveAccountState(
account_id=int(account.id),
account_name=account_name,
checked_at=now,
ck_verdict=ck_verdict,
ck_message=ck_message,
elite_opened=account.elite_opened,
points=account.points,
limited_ids=frozenset(),
role_change_available_at=account.role_change_available_at,
error=error,
)
errors: list[str] = []
bind_info: dict[str, Any] = {}
try:
bind_info = query_bind_info(
active_client,
act_alias=act_alias,
)
except Exception as exc: # noqa: BLE001 绑定查询失败不应丢弃资产查询结果
errors.append(f"绑定状态查询失败: {type(exc).__name__}: {exc}"[:240])
elite_opened = bool(eligibility.elite_user_info.get("manual_type"))
elite_expire_time = _to_int(eligibility.elite_user_info.get("expire_time"))
account.elite_opened = elite_opened
account.elite_expire_time = elite_expire_time or None
account.points = eligibility.points
account.points_expire_at = _points_expire_at(
eligibility.points_response,
checked_at=now,
)
role_change_available_at = account.role_change_available_at
if bind_info:
role_change_available_at = _apply_bind_state(
account,
bind_info,
checked_at=now,
)
account.overview_snapshot = _json_safe(
{
"queried_at": now.isoformat(),
"ck": ck_result,
"elite": eligibility.elite_user_info,
"points": eligibility.points_response,
"limited_goods": eligibility.limited_goods,
"bind": bind_info,
"errors": errors,
}
)
account.overview_queried_at = now
account.high_value_checked_at = now
account.updated_at = now
if commit:
db.commit()
return DouyuLiveAccountState(
account_id=int(account.id),
account_name=account_name,
checked_at=now,
ck_verdict=ck_verdict,
ck_message=ck_message,
elite_opened=elite_opened,
points=eligibility.points,
limited_ids=eligibility.limited_ids,
role_change_available_at=role_change_available_at,
error=";".join(errors),
role_change_blocked=is_role_change_cooling(bind_info),
)
def _apply_bind_state(
account: Account,
bind_info: dict[str, Any],
*,
checked_at: datetime,
) -> datetime | None:
derived = derive_from_bind_info(bind_info)
if derived is not None:
set_bind_status(account, SCOPE_ELITE, derived)
role_name = str(bind_info.get("role_name") or bind_info.get("role") or "").strip()
if role_name:
account.game_name = role_name[:128]
area_name = str(bind_info.get("area_name") or "").strip()
plat_name = str(bind_info.get("plat_name") or "").strip()
channel = " · ".join(item for item in (area_name, plat_name) if item)
if channel:
account.game_channel = channel[:128]
wait_seconds = _to_int(bind_info.get("change_role_wait_time"))
can_change_time = _to_int(bind_info.get("can_change_time"))
account.change_role_wait_time = wait_seconds
if not is_role_change_cooling(bind_info):
available_at = None
elif can_change_time is not None and can_change_time > 0:
available_at = datetime.fromtimestamp(can_change_time, tz=UTC)
elif wait_seconds is not None and wait_seconds > 0:
available_at = checked_at + timedelta(seconds=wait_seconds)
else:
available_at = account.role_change_available_at
account.role_change_available_at = available_at
return available_at
def _points_expire_at(
points_response: dict[str, Any],
*,
checked_at: datetime,
) -> datetime | None:
raw = (
points_response.get("willExpireTime")
or points_response.get("will_expire_time")
or points_response.get("expire_time")
)
value = _to_int(raw)
if value is None or value <= 0:
return None
if value > 10_000_000_000:
value //= 1000
if value < int(checked_at.timestamp()) - 60:
return None
return datetime.fromtimestamp(value, tz=UTC)
def _to_int(value: Any) -> int | None:
if value is None or value == "":
return None
try:
return int(float(value))
except (TypeError, ValueError):
return None
def _json_safe(value: Any) -> Any:
if isinstance(value, datetime):
return value.isoformat()
if isinstance(value, dict):
return {str(key): _json_safe(item) for key, item in value.items()}
if isinstance(value, (list, tuple, set, frozenset)):
return [_json_safe(item) for item in value]
if isinstance(value, (str, int, float, bool)) or value is None:
return value
return str(value)
__all__ = [
"DouyuLiveAccountState",
"refresh_douyu_account_state",
]
@@ -206,6 +206,7 @@ def query_exchange_orders(
class DouyuEligibilityResult:
elite_user_info: dict[str, Any]
points: int
points_response: dict[str, Any]
limited_goods: list[dict[str, Any]]
limited_ids: frozenset[str]
@@ -232,6 +233,7 @@ def query_exchange_eligibility(
return DouyuEligibilityResult(
elite_user_info=elite,
points=int(points_result.get("points") or 0),
points_response=points_result,
limited_goods=limited,
limited_ids=frozenset(limited_ids),
)
+2 -6
View File
@@ -17,6 +17,7 @@ from .account_binding import (
BIND_UNBOUND,
SCOPE_ELITE,
SCOPE_ESPORTS,
is_role_change_cooling,
set_bind_status,
)
from .business_events import record_bind
@@ -148,12 +149,7 @@ class BindMixin:
@classmethod
def _is_change_cooling(cls, bind_info: dict | None) -> bool:
"""是否处于换绑冷却:已有绑定角色且当前不可换绑。"""
if not bind_info:
return False
role_name = str(bind_info.get("role_name") or "").strip()
if not role_name or not cls._is_bound_act(bind_info):
return False
return not cls._can_change_role(bind_info)
return is_role_change_cooling(bind_info)
@classmethod
def _is_pending_role(
@@ -14,6 +14,7 @@ from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from ...models import Account, AccountEvent, AccountLease, User
from ..account_lifecycle import MANUAL_STATES
VALIDATION_LEASE_MINUTES = 5
BINDING_LEASE_MINUTES = 120
@@ -109,6 +110,62 @@ def eligible_accounts(
]
def live_candidate_accounts(
db: Session,
*,
limit: int = 20,
) -> list[Account]:
"""选出值得实时检测的账号,不读取 CK/积分/开通等缓存结论。"""
owner_ids = select(User.id).where(User.role.in_(POOL_OWNER_ROLES))
active_lease = (
select(AccountLease.id)
.where(AccountLease.active_account_id == Account.id)
.exists()
)
return (
db.query(Account)
.filter(
Account.cookie.isnot(None),
Account.cookie != "",
Account.auto_managed.is_(True),
Account.status.notin_(MANUAL_STATES),
or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)),
~active_lease,
)
.order_by(
Account.ck_checked_at.is_(None).desc(),
Account.ck_checked_at.asc(),
Account.points.is_(None).desc(),
Account.points.asc(),
Account.id.asc(),
)
.limit(max(1, min(int(limit), 100)))
.all()
)
def has_recent_exchange(
db: Session,
*,
account_id: int,
commodity_id: str,
now: datetime | None = None,
) -> bool:
moment = _now(now)
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
return (
db.query(AccountEvent.id)
.filter(
AccountEvent.account_id == account_id,
AccountEvent.event_type == "exchange",
AccountEvent.subject_key == commodity_id,
AccountEvent.occurred_at >= since,
)
.first()
is not None
)
def lease_account(
db: Session,
*,
@@ -116,7 +173,7 @@ def lease_account(
holder_user_id: int,
task_id: int,
commodity_id: str,
ttl_minutes: int = VALIDATION_LEASE_MINUTES,
ttl_minutes: int | None = None,
now: datetime | None = None,
) -> AccountLease | None:
"""尝试领取一个账号;撞唯一索引时返回 None。"""
@@ -130,7 +187,11 @@ def lease_account(
batch_id=f"pf:{task_id}",
status="active",
leased_at=moment,
expires_at=moment + timedelta(minutes=max(1, int(ttl_minutes))),
expires_at=(
None
if ttl_minutes is None
else moment + timedelta(minutes=max(1, int(ttl_minutes)))
),
release_reason="",
created_at=moment,
)
@@ -150,12 +211,16 @@ def renew_lease(
db: Session,
lease: AccountLease,
*,
ttl_minutes: int = BINDING_LEASE_MINUTES,
ttl_minutes: int | None = None,
now: datetime | None = None,
) -> AccountLease:
if lease.status != "active":
raise ValueError("租约已结束,不能续期")
lease.expires_at = _now(now) + timedelta(minutes=max(1, int(ttl_minutes)))
lease.expires_at = (
None
if ttl_minutes is None
else _now(now) + timedelta(minutes=max(1, int(ttl_minutes)))
)
db.commit()
return lease
@@ -188,6 +253,7 @@ def expire_platform_fulfillment_leases(
.filter(
AccountLease.purpose == "platform_fulfillment",
AccountLease.status == "active",
AccountLease.expires_at.isnot(None),
AccountLease.expires_at <= moment,
)
.order_by(AccountLease.id.asc())
@@ -210,7 +276,9 @@ __all__ = [
"AccountCandidate",
"eligible_accounts",
"expire_platform_fulfillment_leases",
"has_recent_exchange",
"lease_account",
"live_candidate_accounts",
"release_lease",
"renew_lease",
]
@@ -3,15 +3,13 @@
from __future__ import annotations
import uuid
from datetime import UTC, datetime
from datetime import UTC, datetime, timedelta
from typing import Any
from fastapi import HTTPException
from sqlalchemy import or_
from sqlalchemy.orm import Session
from core.douyu import DouyuActivityError
from ...models import (
Account,
AccountLease,
@@ -19,9 +17,11 @@ from ...models import (
DouyuTask,
PlatformCommodityMapping,
PlatformFulfillmentEvent,
PlatformFulfillmentSetting,
PlatformFulfillmentTask,
User,
)
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state
from ..douyu_activity_query import activity_client, query_exchange_eligibility
from ..douyu_batch_launcher import start_douyu_batch
from ..douyu_service import douyu_config_value, ensure_douyu_config
@@ -30,10 +30,10 @@ from ..external_order_source import (
list_pending_manual_fulfillments,
)
from .account_selector import (
BINDING_LEASE_MINUTES,
VALIDATION_LEASE_MINUTES,
eligible_accounts,
AccountCandidate,
has_recent_exchange,
lease_account,
live_candidate_accounts,
release_lease,
renew_lease,
)
@@ -81,6 +81,66 @@ def _mapping_for_sku(
)
def get_settings(db: Session) -> dict[str, Any]:
row = (
db.query(PlatformFulfillmentSetting)
.filter(PlatformFulfillmentSetting.id == 1)
.first()
)
if row is None:
row = PlatformFulfillmentSetting(id=1, lease_duration_minutes=None)
db.add(row)
db.commit()
db.refresh(row)
return {
"leaseDurationMinutes": row.lease_duration_minutes,
"updatedAt": _jsonable(row.updated_at),
}
def update_settings(
db: Session,
*,
lease_duration_minutes: int | None,
current: User,
) -> dict[str, Any]:
row = (
db.query(PlatformFulfillmentSetting)
.filter(PlatformFulfillmentSetting.id == 1)
.first()
)
if row is None:
row = PlatformFulfillmentSetting(id=1)
db.add(row)
now = _now()
row.lease_duration_minutes = lease_duration_minutes
row.updated_by = current.id
row.updated_at = now
active_leases = (
db.query(AccountLease)
.filter(
AccountLease.purpose == "platform_fulfillment",
AccountLease.status == "active",
)
.all()
)
for lease in active_leases:
lease.expires_at = (
None
if lease_duration_minutes is None
else now + timedelta(minutes=lease_duration_minutes)
)
db.commit()
return {
"leaseDurationMinutes": row.lease_duration_minutes,
"updatedAt": _jsonable(row.updated_at),
}
def _lease_duration_minutes(db: Session) -> int | None:
return get_settings(db)["leaseDurationMinutes"]
def _append_event(
db: Session,
task_id: int,
@@ -485,37 +545,119 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号")
if not task.commodity_id or not task.required_points:
raise HTTPException(status_code=409, detail="请先完成商品映射")
required_points = int(task.required_points)
if task.account_id and task.lease_id:
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if lease and lease.status == "active":
return get_task_detail(db, task.id)
candidates = eligible_accounts(
db,
commodity_id=task.commodity_id,
required_points=task.required_points,
limit=20,
)
selected = None
config = ensure_douyu_config(db)
lease_duration_minutes = _lease_duration_minutes(db)
manual_id = str(douyu_config_value("manual_id", config.manual_id))
rid = str(douyu_config_value("rid", config.rid))
act_alias = str(douyu_config_value("bind_act_alias", config.bind_act_alias))
# 单次最多实时检测 5 个,避免一次选号请求被外部接口拖到超时。
# 检测时间会写回 ck_checked_at,下一次点击自动轮到下一批。
candidates = live_candidate_accounts(db, limit=5)
diagnostics: list[dict[str, Any]] = []
qualified: list[tuple[Account, DouyuLiveAccountState]] = []
selected: AccountCandidate | None = None
selected_state: DouyuLiveAccountState | None = None
lease = None
for candidate in candidates:
for account in candidates:
live_state = refresh_douyu_account_state(
db,
account,
manual_id=manual_id,
rid=rid,
act_alias=act_alias,
)
reasons = live_state.blocking_reasons(commodity_id=task.commodity_id)
if has_recent_exchange(
db,
account_id=int(account.id),
commodity_id=task.commodity_id,
):
reasons.append("365 天内已有该商品兑换事件")
if reasons:
diagnostics.append(
{
"accountId": int(account.id),
"accountName": live_state.account_name,
"ck": live_state.ck_verdict,
"eliteOpened": live_state.elite_opened,
"points": live_state.points,
"reasons": reasons,
}
)
continue
qualified.append((account, live_state))
# 积分和宝典开通不淘汰账号,只影响后续处理成本。优先选已经可直接兑换的账号,
# 其次是只需充值、只需开通、两者都需要的账号。
qualified.sort(
key=lambda item: (
item[1].readiness_rank(required_points=required_points),
int(item[1].points or 0),
int(item[0].id),
)
)
for account, live_state in qualified:
candidate = AccountCandidate(
account_id=int(account.id),
username=str(account.username or ""),
nickname=str(account.nickname or ""),
points=int(live_state.points or 0),
gold_balance=account.gold_balance,
points_expire_at=account.points_expire_at,
role_change_available_at=live_state.role_change_available_at,
)
lease = lease_account(
db,
candidate=candidate,
holder_user_id=current.id,
task_id=task.id,
commodity_id=task.commodity_id,
ttl_minutes=VALIDATION_LEASE_MINUTES,
ttl_minutes=lease_duration_minutes,
)
if lease is not None:
selected = candidate
selected_state = live_state
break
if selected is None or lease is None:
diagnostics.append(
{
"accountId": int(account.id),
"accountName": live_state.account_name,
"ck": live_state.ck_verdict,
"eliteOpened": live_state.elite_opened,
"points": live_state.points,
"reasons": ["账号刚被其他任务占用"],
}
)
if selected is None or selected_state is None or lease is None:
task.execution_status = "ready"
task.issue_code = "no_eligible_account"
task.last_error = "当前没有满足 CK、积分、限兑和换绑条件的斗鱼账号"
if not candidates:
task.last_error = "没有带 CK、允许自动管理且未停用的斗鱼账号"
else:
summary = ";".join(
f"{item['accountName']}: {', '.join(item['reasons'][:3])}"
for item in diagnostics[:5]
)
task.last_error = (
f"已实时检测 {len(diagnostics)} 个账号,当前没有可用账号"
+ (f"。{summary}" if summary else "")
)[:500]
task.updated_at = _now()
_append_event(db, task.id, "account_allocation_failed")
_append_event(
db,
task.id,
"account_allocation_failed",
detail={
"candidateCount": len(candidates),
"diagnostics": diagnostics,
},
)
db.commit()
return get_task_detail(db, task.id)
@@ -524,9 +666,25 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
task.operator_id = current.id
task.execution_status = "allocated"
task.binding_status = "not_started"
task.exchange_status = "not_started"
task.issue_code = ""
task.last_error = ""
soft_reasons = selected_state.soft_requirement_reasons(
required_points=required_points
)
if task.commodity_id in selected_state.limited_ids:
task.exchange_status = "limited"
task.issue_code = "commodity_limit_reached"
task.last_error = "该账号已达到此商品兑换上限"
elif selected_state.elite_opened is not True:
task.exchange_status = "not_opened"
task.issue_code = "elite_not_opened"
task.last_error = "账号尚未开通精英宝典,可开通后继续"
elif selected_state.points is None or selected_state.points < required_points:
task.exchange_status = "points_short"
task.issue_code = "points_short"
task.last_error = "账号积分不足,可充值后继续"
else:
task.exchange_status = "eligible"
task.issue_code = ""
task.last_error = ""
task.updated_at = _now()
_append_event(
db,
@@ -538,6 +696,9 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
"accountId": selected.account_id,
"accountName": selected.display_name,
"points": selected.points,
"eliteOpened": selected_state.elite_opened,
"softReasons": soft_reasons,
"exchangeStatus": task.exchange_status,
},
)
db.commit()
@@ -613,7 +774,7 @@ async def start_binding(db: Session, *, task_id: int, current: User) -> dict[str
renew_lease(
db,
lease,
ttl_minutes=BINDING_LEASE_MINUTES,
ttl_minutes=_lease_duration_minutes(db),
)
_append_event(
db,
@@ -696,7 +857,7 @@ async def confirm_binding(
task.execution_status = "binding_confirming"
task.operator_id = current.id
task.updated_at = _now()
renew_lease(db, lease, ttl_minutes=BINDING_LEASE_MINUTES)
renew_lease(db, lease, ttl_minutes=_lease_duration_minutes(db))
_append_event(
db,
task.id,
@@ -737,7 +898,7 @@ def refresh_exchange_eligibility(
)
account.elite_opened = bool(eligibility.elite_user_info.get("manual_type"))
account.points = eligibility.points
except DouyuActivityError as exc:
except Exception as exc: # noqa: BLE001 外部接口错误要落成可重试的检查失败
task.execution_status = "manual_required"
task.exchange_status = "check_failed"
task.issue_code = "eligibility_check_failed"
@@ -770,9 +931,9 @@ def refresh_exchange_eligibility(
task.exchange_status = "eligible"
task.issue_code = ""
task.last_error = ""
task.execution_status = (
"manual_required" if task.exchange_status != "eligible" else "bound"
)
# 积分不足、未开通和限兑都不是流程终点:角色已经绑定,账号继续保留,
# 后续充值/开通/解除限兑后刷新资格即可。
task.execution_status = "bound"
task.updated_at = _now()
account.updated_at = _now()
_append_event(
@@ -3,9 +3,19 @@ import type {
PlatformFulfillmentDetail,
PlatformFulfillmentListResponse,
PlatformFulfillmentMapping,
PlatformFulfillmentSettings,
} from './types';
export const platformFulfillmentApi = {
getSettings: () =>
api.get<PlatformFulfillmentSettings, PlatformFulfillmentSettings>(
'/platform-fulfillment/settings',
),
updateSettings: (leaseDurationMinutes: number | null) =>
api.put<PlatformFulfillmentSettings, PlatformFulfillmentSettings>(
'/platform-fulfillment/settings',
{ lease_duration_minutes: leaseDurationMinutes },
),
listTasks: (params: {
status?: string;
keyword?: string;
+6 -1
View File
@@ -2118,6 +2118,11 @@ export interface PlatformFulfillmentAccount {
roleChangeAvailableAt: string | null;
}
export interface PlatformFulfillmentSettings {
leaseDurationMinutes: number | null;
updatedAt: string | null;
}
export interface PlatformFulfillmentBindTask {
id: number;
taskType: string;
@@ -2162,7 +2167,7 @@ export interface PlatformFulfillmentTask {
createdAt: string;
updatedAt: string;
account: PlatformFulfillmentAccount | null;
lease: { id: number; status: string; expiresAt: string } | null;
lease: { id: number; status: string; expiresAt: string | null } | null;
bindTask: PlatformFulfillmentBindTask | null;
}
@@ -1,9 +1,9 @@
import { useCallback, useEffect, useState } from 'react';
import { Alert, Button, Card, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd';
import { CheckCircleOutlined, CopyOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SyncOutlined, UserSwitchOutlined } from '@ant-design/icons';
import { Alert, Button, Card, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd';
import { CheckCircleOutlined, CopyOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, SyncOutlined, UserSwitchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { douyuApi, platformFulfillmentApi } from '../api/modules';
import type { DouyuGoodsItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentTask } from '../api/modules';
import type { DouyuGoodsItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules';
import { getErrorMessage } from '../utils/error';
import { message } from '../utils/antdMessage';
import { formatTime } from '../utils/time';
@@ -39,14 +39,180 @@ const STATUS_COLORS: Record<string, string> = {
cancelled: 'default',
};
const BINDING_STATUS_LABELS: Record<string, string> = {
not_started: '未开始',
preparing: '准备中',
qr_pending: '待扫码',
role_ready: '待确认角色',
bound: '已绑定',
failed: '绑定失败',
};
const EXCHANGE_STATUS_LABELS: Record<string, string> = {
not_started: '未开始',
eligible: '可兑换',
points_short: '积分不足',
not_opened: '精英宝典未开通',
limited: '已达限兑上限',
check_failed: '资格查询失败',
manual_done: '人工兑换完成',
};
const ACTOR_TYPE_LABELS: Record<string, string> = {
system: '系统',
user: '运营',
customer: '客户',
connector: '连接器',
};
const EVENT_LABELS: Record<string, string> = {
task_created: '同步人工履约订单',
mapping_updated: '更新商品映射',
account_allocation_failed: '自动选号未找到可分配账号',
account_allocated: '账号分配成功',
account_released: '释放履约账号',
binding_started: '开始绑定游戏角色',
binding_confirm_started: '提交角色绑定确认',
eligibility_check_failed: '兑换资格查询失败',
exchange_eligibility_checked: '刷新兑换资格',
manual_exchange_completed: '人工兑换完成',
marked_manual_required: '转人工处理',
task_cancelled: '任务已取消',
};
const ISSUE_LABELS: Record<string, string> = {
mapping_missing: '商品映射缺失',
no_eligible_account: '没有可分配账号',
points_short: '积分不足',
elite_not_opened: '精英宝典未开通',
commodity_limit_reached: '商品已达限兑上限',
eligibility_check_failed: '资格查询失败',
binding_failed: '绑定失败',
lease_expired: '账号租约已过期',
manual_required: '需要人工处理',
};
function statusLabel(value: string) {
return STATUS_OPTIONS.find((item) => item.value === value)?.label || value;
}
function bindingStatusLabel(value: string) {
return BINDING_STATUS_LABELS[value] || '未知状态';
}
function exchangeStatusLabel(value: string) {
return EXCHANGE_STATUS_LABELS[value] || '未知状态';
}
function issueLabel(value: string) {
if (!value) return '-';
return ISSUE_LABELS[value] || '其他处理事项';
}
function exchangeStatusHint(status: string) {
if (status === 'points_short') return '当前积分不足,账号不会被淘汰。完成充值后点击“刷新兑换资格”即可继续。';
if (status === 'not_opened') return '账号尚未开通精英宝典,不会被淘汰。开通后点击“刷新兑换资格”即可继续。';
if (status === 'limited') return '当前账号已达到该商品限兑上限,可等待限制解除、人工处理或释放后换号。';
if (status === 'check_failed') return '实时查询失败,账号仍保留。请稍后重新刷新兑换资格。';
if (status === 'eligible') return '账号已满足当前商品兑换条件,可以继续人工兑换。';
return '';
}
function ckStatusLabel(status: string) {
if (status === 'valid') return '有效';
if (status === 'invalid') return '已失效';
if (status === 'error') return '查询异常';
return '未检测';
}
function eliteOpenedLabel(value: boolean | null) {
if (value === true) return '已开通';
if (value === false) return '未开通';
return '未知';
}
function bindStatusLabel(value: string) {
if (value === 'bound') return '已绑定';
if (value === 'unbound') return '未绑定';
if (value === 'pending') return '待确认';
return '未知';
}
function providerLabel(value: string) {
if (value === 'livehub_douyu_dev') return '斗鱼联调';
if (!value) return '-';
return /^[a-z0-9_-]+$/i.test(value) ? '外部订单' : value;
}
function eventLabel(value: string) {
return EVENT_LABELS[value] || '履约记录';
}
function eventColor(value: string) {
if (value.includes('failed') || value.includes('cancelled')) return 'red';
if (value.includes('manual_required')) return 'orange';
if (value.includes('completed') || value.includes('allocated')) return 'green';
return 'blue';
}
function eventDescription(event: { eventType: string; detail: Record<string, unknown> }) {
const detail = event.detail || {};
if (event.eventType === 'account_allocation_failed') {
const diagnostics = Array.isArray(detail.diagnostics) ? detail.diagnostics : [];
const lines = diagnostics.slice(0, 3).map((item) => {
const row = item && typeof item === 'object' ? (item as Record<string, unknown>) : {};
const name = String(row.accountName || `账号 ${row.accountId || '-'}`);
const reasons = Array.isArray(row.reasons) ? row.reasons.map(String) : [];
return `${name}:${reasons.join('、') || '未满足分配条件'}`;
});
return lines.join(';') || '本批账号均不满足当前分配条件';
}
if (event.eventType === 'account_allocated') {
const reasons = Array.isArray(detail.softReasons) ? detail.softReasons.map(String) : [];
const base = `账号 ${String(detail.accountName || '-')},实时积分 ${String(detail.points ?? '-')}`;
return reasons.length ? `${base};后续需要:${reasons.join('、')}` : `${base};可直接兑换`;
}
if (event.eventType === 'mapping_updated') {
return `斗鱼商品 ${String(detail.commodityId || '-')},映射${detail.enabled === false ? '已停用' : '已启用'}`;
}
if (event.eventType === 'exchange_eligibility_checked') {
return `兑换状态:${exchangeStatusLabel(String(detail.exchangeStatus || ''))};限兑商品 ${String(detail.limitedCount ?? 0)} 个`;
}
if (event.eventType === 'eligibility_check_failed') {
return '实时查询兑换资格失败,可稍后重试';
}
if (event.eventType === 'account_released') {
return `释放原因:${String(detail.reason || '人工释放')}`;
}
if (event.eventType === 'manual_exchange_completed') {
return String(detail.note || '运营已确认人工兑换完成');
}
if (event.eventType === 'marked_manual_required') {
return String(detail.reason || '已转人工处理');
}
if (event.eventType === 'task_cancelled') {
return `取消原因:${String(detail.reason || '人工取消')}`;
}
if (event.eventType === 'binding_started') return '已生成客户绑定二维码';
if (event.eventType === 'binding_confirm_started') return '已提交游戏角色绑定确认';
if (event.eventType === 'task_created') return '订单已进入直播账号履约工作台';
return '履约状态已更新';
}
function money(fen: number) {
return `¥${(Number(fen || 0) / 100).toFixed(2)}`;
}
function leaseDurationLabel(minutes: number | null | undefined) {
if (minutes == null) return '无限制';
if (minutes % 60 === 0) return `${minutes / 60} 小时`;
return `${minutes} 分钟`;
}
function leaseExpiresLabel(expiresAt: string | null | undefined) {
return expiresAt ? formatTime(expiresAt) : '无限制';
}
export default function PlatformFulfillmentPage() {
const user = getUser();
const { can } = usePermissions(user);
@@ -70,6 +236,11 @@ export default function PlatformFulfillmentPage() {
const [goods, setGoods] = useState<DouyuGoodsItem[]>([]);
const [mappingGoodsLoading, setMappingGoodsLoading] = useState(false);
const [mappings, setMappings] = useState<PlatformFulfillmentMapping[]>([]);
const [settings, setSettings] = useState<PlatformFulfillmentSettings | null>(null);
const [settingsOpen, setSettingsOpen] = useState(false);
const [leaseDurationMode, setLeaseDurationMode] = useState<'unlimited' | 'minutes' | 'hours'>('unlimited');
const [leaseDurationValue, setLeaseDurationValue] = useState<number | null>(60);
const [savingSettings, setSavingSettings] = useState(false);
const loadTasks = useCallback(async () => {
setLoading(true);
@@ -105,6 +276,13 @@ export default function PlatformFulfillmentPage() {
void loadTasks();
}, [loadTasks]);
useEffect(() => {
void platformFulfillmentApi
.getSettings()
.then(setSettings)
.catch((error) => message.error(getErrorMessage(error)));
}, []);
useEffect(() => {
if (selectedId) void loadDetail(selectedId);
}, [loadDetail, selectedId]);
@@ -207,6 +385,47 @@ export default function PlatformFulfillmentPage() {
}
};
const openLeaseSettings = () => {
const minutes = settings?.leaseDurationMinutes ?? null;
if (minutes == null) {
setLeaseDurationMode('unlimited');
setLeaseDurationValue(60);
} else if (minutes % 60 === 0) {
setLeaseDurationMode('hours');
setLeaseDurationValue(minutes / 60);
} else {
setLeaseDurationMode('minutes');
setLeaseDurationValue(minutes);
}
setSettingsOpen(true);
};
const saveLeaseSettings = async () => {
const minutes =
leaseDurationMode === 'unlimited'
? null
: leaseDurationMode === 'hours'
? Number(leaseDurationValue || 0) * 60
: Number(leaseDurationValue || 0);
if (minutes != null && minutes < 1) {
message.warning('租约时长至少为 1 分钟');
return;
}
setSavingSettings(true);
try {
const result = await platformFulfillmentApi.updateSettings(minutes);
setSettings(result);
setSettingsOpen(false);
message.success(`租约设置已更新为${leaseDurationLabel(result.leaseDurationMinutes)}`);
if (selectedId) await loadDetail(selectedId);
await loadTasks();
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setSavingSettings(false);
}
};
const columns: ColumnsType<PlatformFulfillmentTask> = [
{
title: '订单 / 商品',
@@ -217,7 +436,7 @@ export default function PlatformFulfillmentPage() {
<Text strong>{task.platformOrderId || `#${task.sourceOrderId}`}</Text>
<Text>{task.skuName || task.internalSkuKey || '-'}</Text>
<Text type="secondary">
{task.provider || '-'} / {task.shopName || task.shopId || '-'}
{providerLabel(task.provider)} / {task.shopName || task.shopId || '-'}
</Text>
</Space>
),
@@ -251,7 +470,7 @@ export default function PlatformFulfillmentPage() {
积分 {task.account.points ?? '-'} · 鱼翅 {task.account.goldBalance ?? '-'}
</Text>
<Text type="secondary">
租约 {task.lease?.status || '-'} · {formatTime(task.lease?.expiresAt)}
租约 {task.lease ? '占用中' : '未占用'} · {task.lease ? leaseExpiresLabel(task.lease.expiresAt) : '-'}
</Text>
</Space>
) : (
@@ -264,8 +483,8 @@ export default function PlatformFulfillmentPage() {
width: 180,
render: (_, task) => (
<Space direction="vertical" size={2}>
<Tag>{task.bindingStatus}</Tag>
<Text>{task.bindTask?.roleName || task.bindTask?.bindPhase || '-'}</Text>
<Tag>{bindingStatusLabel(task.bindingStatus)}</Tag>
<Text>{task.bindTask?.roleName || (task.bindTask?.bindPhase === 'role_ready' ? '角色待确认' : '-')}</Text>
</Space>
),
},
@@ -276,7 +495,7 @@ export default function PlatformFulfillmentPage() {
render: (_, task) => (
<Space direction="vertical" size={4}>
<Tag color={STATUS_COLORS[task.executionStatus] || 'default'}>{statusLabel(task.executionStatus)}</Tag>
<Text type="secondary">兑换:{task.exchangeStatus}</Text>
<Text type="secondary">兑换:{exchangeStatusLabel(task.exchangeStatus)}</Text>
</Space>
),
},
@@ -362,6 +581,14 @@ export default function PlatformFulfillmentPage() {
<Text type="secondary">读取 order_site 人工订单,客户扫码绑定游戏角色,运营使用斗鱼账号人工兑换。</Text>
</div>
<Space wrap>
<Tag>账号租约:{leaseDurationLabel(settings?.leaseDurationMinutes)}</Tag>
<Button
icon={<SettingOutlined />}
disabled={!can('platform_fulfillment:admin')}
onClick={openLeaseSettings}
>
租约设置
</Button>
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
商品映射
</Button>
@@ -417,43 +644,131 @@ export default function PlatformFulfillmentPage() {
/>
</Card>
<Drawer open={Boolean(selectedId)} width={760} title={selected ? `履约详情 · ${selected.platformOrderId}` : '履约详情'} onClose={() => setSelectedId(null)}>
<Drawer
open={Boolean(selectedId)}
width="min(1080px, 94vw)"
title={selected ? `履约详情 · ${selected.platformOrderId}` : '履约详情'}
extra={
selected ? (
<Space>
<Tag color={STATUS_COLORS[selected.executionStatus] || 'default'}>
{statusLabel(selected.executionStatus)}
</Tag>
<Tag>{exchangeStatusLabel(selected.exchangeStatus)}</Tag>
</Space>
) : null
}
onClose={() => setSelectedId(null)}
>
{detailLoading || !selected ? (
<Text type="secondary">加载中...</Text>
) : (
<Space direction="vertical" size={16} style={{ width: '100%' }}>
{selected.lastError ? <Alert type="warning" showIcon message={selected.lastError} /> : null}
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="商品" span={2}>
{selected.skuName}
</Descriptions.Item>
<Descriptions.Item label="内部 SKU">{selected.internalSkuKey || '-'}</Descriptions.Item>
<Descriptions.Item label="斗鱼商品">{selected.commodityId || '-'}</Descriptions.Item>
<Descriptions.Item label="订单金额">{money(selected.orderAmountFen)}</Descriptions.Item>
<Descriptions.Item label="所需积分">{selected.requiredPoints ?? '-'}</Descriptions.Item>
<Descriptions.Item label="执行状态">{statusLabel(selected.executionStatus)}</Descriptions.Item>
<Descriptions.Item label="绑定状态">{selected.bindingStatus}</Descriptions.Item>
<Descriptions.Item label="兑换状态">{selected.exchangeStatus}</Descriptions.Item>
<Descriptions.Item label="账号">{selected.account?.nickname || selected.account?.username || '-'}</Descriptions.Item>
</Descriptions>
{selected.issueCode || selected.lastError ? (
<Alert
type={selected.exchangeStatus === 'eligible' ? 'success' : 'warning'}
showIcon
message={selected.issueCode ? issueLabel(selected.issueCode) : '处理提示'}
description={selected.lastError || exchangeStatusHint(selected.exchangeStatus)}
/>
) : exchangeStatusHint(selected.exchangeStatus) ? (
<Alert
type={selected.exchangeStatus === 'eligible' ? 'success' : 'warning'}
showIcon
message={exchangeStatusLabel(selected.exchangeStatus)}
description={exchangeStatusHint(selected.exchangeStatus)}
/>
) : null}
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(360px, 1fr))',
gap: 16,
}}
>
<Card size="small" title="订单与商品">
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="订单号" span={2}>
{selected.platformOrderId || '-'}
</Descriptions.Item>
<Descriptions.Item label="商品" span={2}>
{selected.skuName || selected.internalSkuKey || '-'}
</Descriptions.Item>
<Descriptions.Item label="内部 SKU" span={2}>
{selected.internalSkuKey || '-'}
</Descriptions.Item>
<Descriptions.Item label="斗鱼商品" span={2}>
{selected.commodityId || '未映射'}
</Descriptions.Item>
<Descriptions.Item label="订单金额">{money(selected.orderAmountFen)}</Descriptions.Item>
<Descriptions.Item label="所需积分">{selected.requiredPoints ?? '-'}</Descriptions.Item>
<Descriptions.Item label="执行状态">{statusLabel(selected.executionStatus)}</Descriptions.Item>
<Descriptions.Item label="绑定状态">{bindingStatusLabel(selected.bindingStatus)}</Descriptions.Item>
<Descriptions.Item label="兑换状态">{exchangeStatusLabel(selected.exchangeStatus)}</Descriptions.Item>
<Descriptions.Item label="处理提示">{issueLabel(selected.issueCode)}</Descriptions.Item>
</Descriptions>
</Card>
<Card size="small" title="账号实时状态">
{selected.account ? (
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="账号" span={2}>
{selected.account.nickname || selected.account.username}
</Descriptions.Item>
<Descriptions.Item label="CK 状态">
{ckStatusLabel(selected.account.ckCheckStatus)}
</Descriptions.Item>
<Descriptions.Item label="精英宝典">
{eliteOpenedLabel(selected.account.eliteOpened)}
</Descriptions.Item>
<Descriptions.Item label="当前积分">{selected.account.points ?? '-'}</Descriptions.Item>
<Descriptions.Item label="鱼翅余额">{selected.account.goldBalance ?? '-'}</Descriptions.Item>
<Descriptions.Item label="角色绑定">
{bindStatusLabel(selected.account.roleBindStatus)}
</Descriptions.Item>
<Descriptions.Item label="游戏角色">{selected.account.gameName || '-'}</Descriptions.Item>
<Descriptions.Item label="游戏渠道" span={2}>
{selected.account.gameChannel || '-'}
</Descriptions.Item>
<Descriptions.Item label="换绑可用时间" span={2}>
{formatTime(selected.account.roleChangeAvailableAt) || '无冷却'}
</Descriptions.Item>
<Descriptions.Item label="租约到期" span={2}>
{selected.lease ? leaseExpiresLabel(selected.lease.expiresAt) : '-'}
</Descriptions.Item>
</Descriptions>
) : (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="尚未分配账号" />
)}
</Card>
</div>
<Card size="small" title="当前操作">
{actionButtons}
</Card>
<Card size="small" title="事件时间线">
<Timeline
items={(detail?.events || []).map((event) => ({
color: event.eventType.includes('failed') ? 'red' : 'blue',
children: (
<Space direction="vertical" size={2}>
<Text strong>{event.eventType}</Text>
<Text type="secondary">
{formatTime(event.createdAt)} · {event.actorType}
{event.actorId ? ` ${event.actorId}` : ''}
</Text>
</Space>
),
}))}
/>
<Card size="small" title={`事件时间线(${detail?.events.length || 0})`}>
<div style={{ maxHeight: 440, overflowY: 'auto', paddingTop: 8 }}>
<Timeline
items={(detail?.events || [])
.slice()
.sort((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt))
.slice(0, 50)
.map((event) => ({
color: eventColor(event.eventType),
children: (
<Space direction="vertical" size={3} style={{ maxWidth: 860 }}>
<Text strong>{eventLabel(event.eventType)}</Text>
<Text>{eventDescription(event)}</Text>
<Text type="secondary">
{formatTime(event.createdAt)} · {ACTOR_TYPE_LABELS[event.actorType] || '系统'}
{event.actorId ? ` · 操作人 ${event.actorId}` : ''}
</Text>
</Space>
),
}))}
/>
</div>
</Card>
</Space>
)}
@@ -477,6 +792,44 @@ export default function PlatformFulfillmentPage() {
</Space>
</Modal>
<Modal
open={settingsOpen}
title="账号租约设置"
okText="保存设置"
confirmLoading={savingSettings}
onOk={() => void saveLeaseSettings()}
onCancel={() => setSettingsOpen(false)}
>
<Space direction="vertical" size={16} style={{ width: '100%' }}>
<Segmented
block
value={leaseDurationMode}
onChange={(value) => setLeaseDurationMode(value as 'unlimited' | 'minutes' | 'hours')}
options={[
{ label: '无限制', value: 'unlimited' },
{ label: '按分钟', value: 'minutes' },
{ label: '按小时', value: 'hours' },
]}
/>
{leaseDurationMode !== 'unlimited' ? (
<InputNumber
min={1}
precision={0}
value={leaseDurationValue}
onChange={setLeaseDurationValue}
addonAfter={leaseDurationMode === 'hours' ? '小时' : '分钟'}
style={{ width: '100%' }}
/>
) : null}
<Alert
type="info"
showIcon
message={`当前设置:${leaseDurationLabel(settings?.leaseDurationMinutes)}`}
description="保存后会立即同步当前所有活跃租约。无限制模式不会自动回收,任务完成、释放或取消时仍会正常释放账号。"
/>
</Space>
</Modal>
<Modal open={mappingOpen} title="斗鱼商品映射" width={760} okText="保存映射" onOk={() => void saveMapping()} onCancel={() => setMappingOpen(false)}>
<Space direction="vertical" size={14} style={{ width: '100%' }}>
<Input placeholder="内部 SKU,例如 套装-兔兔白日梦" value={mappingSku} onChange={(event) => setMappingSku(event.target.value)} />