refactor(douyu): 统一活动查询与直播商品映射
- 收口斗鱼活动、商品、绑定信息和兑换资格查询 - 工作台改为复用统一客户端、快照与实时商品目录 - 补充活动查询与商品映射测试
This commit is contained in:
@@ -25,6 +25,16 @@
|
|||||||
- 内部 SKU 与斗鱼商品必须显式配置 `platform_commodity_mappings`。
|
- 内部 SKU 与斗鱼商品必须显式配置 `platform_commodity_mappings`。
|
||||||
- CK 始终保存在原有账号字段中,不进入履约任务接口。
|
- CK 始终保存在原有账号字段中,不进入履约任务接口。
|
||||||
|
|
||||||
|
## 斗鱼查询边界
|
||||||
|
|
||||||
|
斗鱼活动接口的只读查询统一收口在
|
||||||
|
`web/backend/services/douyu_activity_query.py`,包括角色绑定、精英宝典状态、
|
||||||
|
活动商品、积分、限兑商品、鱼翅、兑换记录和锁单记录。
|
||||||
|
|
||||||
|
页面、外部单协作、直播账号履约和任务执行器只能调用该模块,不得直接调用
|
||||||
|
`DouyuActivityClient` 的只读查询方法。商品映射弹窗使用实时活动商品接口,
|
||||||
|
不再依赖本地是否执行过 `refresh_goods`。
|
||||||
|
|
||||||
## 操作流程
|
## 操作流程
|
||||||
|
|
||||||
1. 在“直播账号履约工作台”点击“同步待履约订单”。
|
1. 在“直播账号履约工作台”点击“同步待履约订单”。
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
"""斗鱼只读活动查询统一入口的契约测试。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ast
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import cast
|
||||||
|
|
||||||
|
from core.douyu import DouyuActivityClient
|
||||||
|
from web.backend.models import User
|
||||||
|
from web.backend.routers import douyu as douyu_api
|
||||||
|
from web.backend.services import douyu_activity_query as query
|
||||||
|
|
||||||
|
READ_METHODS = {
|
||||||
|
"acf_ccn",
|
||||||
|
"bind_info",
|
||||||
|
"elite_user_info",
|
||||||
|
"esports_bind_info",
|
||||||
|
"exchange_balance",
|
||||||
|
"exchange_orders",
|
||||||
|
"exchange_records",
|
||||||
|
"gold_account",
|
||||||
|
"list_esports_goods",
|
||||||
|
"list_goods",
|
||||||
|
"query_limited_goods",
|
||||||
|
"query_points",
|
||||||
|
"xpd_bind_info",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class FakeActivityClient:
|
||||||
|
def __init__(self):
|
||||||
|
self.calls: list[str] = []
|
||||||
|
|
||||||
|
def acf_ccn(self, *, refresh_subscribe: bool = False):
|
||||||
|
self.calls.append("acf_ccn")
|
||||||
|
assert refresh_subscribe is False
|
||||||
|
return "csrf-token"
|
||||||
|
|
||||||
|
def elite_user_info(self, **_kwargs):
|
||||||
|
self.calls.append("elite_user_info")
|
||||||
|
return {"manual_type": 1, "manual_score": 5000}
|
||||||
|
|
||||||
|
def query_points(self, **_kwargs):
|
||||||
|
self.calls.append("query_points")
|
||||||
|
return {"points": 5200}
|
||||||
|
|
||||||
|
def query_limited_goods(self, **_kwargs):
|
||||||
|
self.calls.append("query_limited_goods")
|
||||||
|
return {
|
||||||
|
"limited_goods": [
|
||||||
|
{"commodityId": "limited-1", "commodityName": "套装-已达上限"},
|
||||||
|
{"commodityId": "limited-1", "commodityName": "重复项"},
|
||||||
|
{"commodityName": "无 ID 项"},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_goods(self, **_kwargs):
|
||||||
|
self.calls.append("list_goods")
|
||||||
|
return {
|
||||||
|
"goods": [
|
||||||
|
{
|
||||||
|
"commodityId": "gift-a",
|
||||||
|
"commodityName": "套装-兔兔白日梦",
|
||||||
|
"score": 1280,
|
||||||
|
"status": 0,
|
||||||
|
"openStatus": 1,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_exchange_eligibility_is_normalized_once():
|
||||||
|
client = FakeActivityClient()
|
||||||
|
|
||||||
|
result = query.query_exchange_eligibility(
|
||||||
|
cast(DouyuActivityClient, client),
|
||||||
|
cookie="acf_uid=100; acf_nickname=test",
|
||||||
|
manual_id="manual-1",
|
||||||
|
rid="room-1",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.elite_user_info["manual_type"] == 1
|
||||||
|
assert result.points == 5200
|
||||||
|
assert result.limited_ids == frozenset({"limited-1"})
|
||||||
|
assert client.calls == [
|
||||||
|
"acf_ccn",
|
||||||
|
"elite_user_info",
|
||||||
|
"query_points",
|
||||||
|
"query_limited_goods",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_live_goods_endpoint_uses_shared_query_contract(db, monkeypatch):
|
||||||
|
user = User(username="goods-admin", password_hash="hash", role="super_admin")
|
||||||
|
db.add(user)
|
||||||
|
db.commit()
|
||||||
|
monkeypatch.setattr(
|
||||||
|
douyu_api,
|
||||||
|
"query_activity_goods",
|
||||||
|
lambda *_args, **_kwargs: [
|
||||||
|
{
|
||||||
|
"commodityId": "gift-a",
|
||||||
|
"commodityName": "套装-兔兔白日梦",
|
||||||
|
"score": 1280,
|
||||||
|
"status": 0,
|
||||||
|
"openStatus": 1,
|
||||||
|
"mark": "",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
rows = douyu_api.list_live_goods(db=db, current=user)
|
||||||
|
|
||||||
|
assert len(rows) == 1
|
||||||
|
assert rows[0].commodity_id == "gift-a"
|
||||||
|
assert rows[0].name == "套装-兔兔白日梦"
|
||||||
|
assert rows[0].score == 1280
|
||||||
|
|
||||||
|
|
||||||
|
def test_douyu_read_queries_only_call_client_from_shared_module():
|
||||||
|
backend = Path(__file__).parents[1] / "web" / "backend"
|
||||||
|
allowed = backend / "services" / "douyu_activity_query.py"
|
||||||
|
violations: list[str] = []
|
||||||
|
paths = [
|
||||||
|
*backend.glob("services/douyu_*.py"),
|
||||||
|
*backend.glob("routers/douyu*.py"),
|
||||||
|
]
|
||||||
|
|
||||||
|
for path in paths:
|
||||||
|
if path == allowed:
|
||||||
|
continue
|
||||||
|
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||||||
|
for node in ast.walk(tree):
|
||||||
|
if not isinstance(node, ast.Call):
|
||||||
|
continue
|
||||||
|
func = node.func
|
||||||
|
if isinstance(func, ast.Attribute) and func.attr in READ_METHODS:
|
||||||
|
violations.append(
|
||||||
|
f"{path.relative_to(backend)}:{node.lineno}:{func.attr}"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert violations == []
|
||||||
@@ -20,6 +20,7 @@ from sqlalchemy import case, func, or_, select
|
|||||||
from sqlalchemy.orm import Session, joinedload
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
from core.douyu import (
|
from core.douyu import (
|
||||||
|
DouyuActivityError,
|
||||||
FishFinRechargeClient,
|
FishFinRechargeClient,
|
||||||
FishFinRechargeConfig,
|
FishFinRechargeConfig,
|
||||||
FishFinRechargeConfigError,
|
FishFinRechargeConfigError,
|
||||||
@@ -53,7 +54,9 @@ from ..schemas import (
|
|||||||
from ..services.account_binding import bind_payload
|
from ..services.account_binding import bind_payload
|
||||||
from ..services.audit_service import record_audit
|
from ..services.audit_service import record_audit
|
||||||
from ..services.business_events import record_recharge
|
from ..services.business_events import record_recharge
|
||||||
|
from ..services.douyu_activity_query import activity_client, query_activity_goods
|
||||||
from ..services.douyu_batch_launcher import start_douyu_batch
|
from ..services.douyu_batch_launcher import start_douyu_batch
|
||||||
|
from ..services.douyu_goods_service import serialize_goods
|
||||||
from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry
|
from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry
|
||||||
from ..services.douyu_service import (
|
from ..services.douyu_service import (
|
||||||
DOUYU_CONFIG_FIELDS,
|
DOUYU_CONFIG_FIELDS,
|
||||||
@@ -662,6 +665,37 @@ def list_goods(
|
|||||||
return rows
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/goods/live", response_model=list[DouyuGoodsOut])
|
||||||
|
def list_live_goods(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current: User = Depends(require_permission("douyu:task")),
|
||||||
|
):
|
||||||
|
"""实时读取精英宝典活动商品,不依赖账号或本地刷新任务。"""
|
||||||
|
del current
|
||||||
|
config = ensure_douyu_config(db)
|
||||||
|
try:
|
||||||
|
goods = query_activity_goods(
|
||||||
|
activity_client(),
|
||||||
|
manual_id=str(douyu_config_value("manual_id", config.manual_id)),
|
||||||
|
rid=str(douyu_config_value("rid", config.rid)),
|
||||||
|
)
|
||||||
|
except DouyuActivityError as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=f"活动商品加载失败:{exc}") from exc
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
return [
|
||||||
|
DouyuGoodsOut(
|
||||||
|
id=-(index + 1),
|
||||||
|
commodity_id=str(item.get("commodity_id") or ""),
|
||||||
|
name=str(item.get("name") or ""),
|
||||||
|
score=item.get("score"),
|
||||||
|
status=str(item.get("status") or ""),
|
||||||
|
raw=item.get("raw") if isinstance(item.get("raw"), dict) else None,
|
||||||
|
updated_at=now,
|
||||||
|
)
|
||||||
|
for index, item in enumerate(serialize_goods(raw) for raw in goods)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
@router.get("/esports-goods", response_model=list[DouyuGoodsOut])
|
@router.get("/esports-goods", response_model=list[DouyuGoodsOut])
|
||||||
def list_esports_goods(
|
def list_esports_goods(
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
|
|||||||
@@ -0,0 +1,309 @@
|
|||||||
|
"""斗鱼活动只读查询的唯一入口。
|
||||||
|
|
||||||
|
账号角色、精英宝典状态、活动商品、积分、限兑商品、鱼翅和官方记录
|
||||||
|
都在这里调用 ``DouyuActivityClient``。业务模块只消费归一化结果,不直接
|
||||||
|
拼接口参数或解析响应,避免工作台、协作台账和任务执行器各自漂移。
|
||||||
|
|
||||||
|
兑换、充值、锁定订单等写操作不在这里实现;它们继续由任务执行器负责。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from core.douyu import DouyuActivityClient
|
||||||
|
from core.douyu.cookie_utils import cookie_value
|
||||||
|
|
||||||
|
from .douyu_goods_service import serialize_goods
|
||||||
|
|
||||||
|
ERROR_MAX_LENGTH = 240
|
||||||
|
|
||||||
|
|
||||||
|
def activity_client(cookie: str = "") -> DouyuActivityClient:
|
||||||
|
"""创建统一活动客户端;空 Cookie 可用于公开商品目录查询。"""
|
||||||
|
return DouyuActivityClient(cookie)
|
||||||
|
|
||||||
|
|
||||||
|
def query_csrf(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
refresh_subscribe: bool = False,
|
||||||
|
) -> str:
|
||||||
|
return client.acf_ccn(refresh_subscribe=refresh_subscribe)
|
||||||
|
|
||||||
|
|
||||||
|
def query_elite_user_info(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
manual_id: str,
|
||||||
|
rid: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return client.elite_user_info(manual_id=manual_id, rid=rid)
|
||||||
|
|
||||||
|
|
||||||
|
def query_bind_info(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
act_alias: str,
|
||||||
|
v2: bool = False,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return client.bind_info(act_alias=act_alias, v2=v2)
|
||||||
|
|
||||||
|
|
||||||
|
def query_esports_bind_info(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
act_alias: str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return client.esports_bind_info(act_alias=act_alias)
|
||||||
|
|
||||||
|
|
||||||
|
def query_xpd_bind_info(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
act_alias: str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return client.xpd_bind_info(act_alias=act_alias)
|
||||||
|
|
||||||
|
|
||||||
|
def query_gold_account(client: DouyuActivityClient) -> dict[str, Any]:
|
||||||
|
return client.gold_account()
|
||||||
|
|
||||||
|
|
||||||
|
def query_exchange_balance(client: DouyuActivityClient) -> dict[str, Any]:
|
||||||
|
return client.exchange_balance()
|
||||||
|
|
||||||
|
|
||||||
|
def query_activity_goods(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
manual_id: str,
|
||||||
|
rid: str,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
result = client.list_goods(manual_id=manual_id, rid=rid)
|
||||||
|
return [dict(item) for item in result.get("goods") or [] if isinstance(item, dict)]
|
||||||
|
|
||||||
|
|
||||||
|
def query_esports_goods_result(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
manual_id: str,
|
||||||
|
rid: str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return client.list_esports_goods(manual_id=manual_id, rid=rid)
|
||||||
|
|
||||||
|
|
||||||
|
def query_esports_goods(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
manual_id: str,
|
||||||
|
rid: str,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
result = query_esports_goods_result(
|
||||||
|
client,
|
||||||
|
manual_id=manual_id,
|
||||||
|
rid=rid,
|
||||||
|
)
|
||||||
|
return [dict(item) for item in result.get("goods") or [] if isinstance(item, dict)]
|
||||||
|
|
||||||
|
|
||||||
|
def query_points(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
uid: str,
|
||||||
|
ctn: str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return client.query_points(uid=uid, ctn=ctn)
|
||||||
|
|
||||||
|
|
||||||
|
def query_limited_goods_result(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
manual_id: str,
|
||||||
|
rid: str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return client.query_limited_goods(manual_id=manual_id, rid=rid)
|
||||||
|
|
||||||
|
|
||||||
|
def query_limited_goods(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
manual_id: str,
|
||||||
|
rid: str,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
result = query_limited_goods_result(client, manual_id=manual_id, rid=rid)
|
||||||
|
return [
|
||||||
|
dict(item)
|
||||||
|
for item in result.get("limited_goods") or []
|
||||||
|
if isinstance(item, dict)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def query_exchange_records_result(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
manual_id: str,
|
||||||
|
limit: int = 100,
|
||||||
|
offset: int = 0,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return client.exchange_records(
|
||||||
|
manual_id=manual_id,
|
||||||
|
limit=limit,
|
||||||
|
offset=offset,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def query_exchange_records(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
manual_id: str,
|
||||||
|
limit: int = 100,
|
||||||
|
offset: int = 0,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
result = query_exchange_records_result(
|
||||||
|
client,
|
||||||
|
manual_id=manual_id,
|
||||||
|
limit=limit,
|
||||||
|
offset=offset,
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
dict(item) for item in result.get("records") or [] if isinstance(item, dict)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def query_exchange_orders_result(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
manual_id: str,
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 10,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return client.exchange_orders(
|
||||||
|
manual_id=manual_id,
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def query_exchange_orders(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
manual_id: str,
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 10,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
result = query_exchange_orders_result(
|
||||||
|
client,
|
||||||
|
manual_id=manual_id,
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
)
|
||||||
|
return [dict(item) for item in result.get("orders") or [] if isinstance(item, dict)]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class DouyuEligibilityResult:
|
||||||
|
elite_user_info: dict[str, Any]
|
||||||
|
points: int
|
||||||
|
limited_goods: list[dict[str, Any]]
|
||||||
|
limited_ids: frozenset[str]
|
||||||
|
|
||||||
|
|
||||||
|
def query_exchange_eligibility(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
cookie: str,
|
||||||
|
manual_id: str,
|
||||||
|
rid: str,
|
||||||
|
uid: str = "",
|
||||||
|
) -> DouyuEligibilityResult:
|
||||||
|
"""一次读取兑换资格需要的精英状态、积分和限兑商品。"""
|
||||||
|
ctn = query_csrf(client)
|
||||||
|
elite = query_elite_user_info(client, manual_id=manual_id, rid=rid)
|
||||||
|
resolved_uid = str(uid or cookie_value(cookie, "acf_uid") or "").strip()
|
||||||
|
points_result = query_points(client, uid=resolved_uid, ctn=ctn)
|
||||||
|
limited = query_limited_goods(client, manual_id=manual_id, rid=rid)
|
||||||
|
limited_ids = {
|
||||||
|
str(item.get("commodityId") or item.get("commodity_id") or "").strip()
|
||||||
|
for item in limited
|
||||||
|
}
|
||||||
|
limited_ids.discard("")
|
||||||
|
return DouyuEligibilityResult(
|
||||||
|
elite_user_info=elite,
|
||||||
|
points=int(points_result.get("points") or 0),
|
||||||
|
limited_goods=limited,
|
||||||
|
limited_ids=frozenset(limited_ids),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def query_account_overview(
|
||||||
|
client: DouyuActivityClient,
|
||||||
|
*,
|
||||||
|
manual_id: str,
|
||||||
|
rid: str,
|
||||||
|
act_alias: str,
|
||||||
|
with_goods: bool = True,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""账号只读探针,单项失败只进入 errors,不阻断其他查询。"""
|
||||||
|
elite: dict[str, Any] = {}
|
||||||
|
bind: dict[str, Any] = {}
|
||||||
|
gold: dict[str, Any] = {}
|
||||||
|
goods: list[dict[str, Any]] = []
|
||||||
|
errors: dict[str, str] = {}
|
||||||
|
|
||||||
|
try:
|
||||||
|
elite = query_elite_user_info(client, manual_id=manual_id, rid=rid)
|
||||||
|
except Exception as exc: # noqa: BLE001 - 外部接口边界
|
||||||
|
errors["elite"] = _error_text(exc)
|
||||||
|
try:
|
||||||
|
bind = query_bind_info(client, act_alias=act_alias)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
errors["bind"] = _error_text(exc)
|
||||||
|
try:
|
||||||
|
gold = query_gold_account(client)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
errors["gold"] = _error_text(exc)
|
||||||
|
if with_goods:
|
||||||
|
try:
|
||||||
|
goods = query_activity_goods(client, manual_id=manual_id, rid=rid)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
errors["goods"] = _error_text(exc)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"elite": elite,
|
||||||
|
"bind": bind,
|
||||||
|
"gold": gold,
|
||||||
|
"goods": goods,
|
||||||
|
"serialized_goods": [serialize_goods(item) for item in goods],
|
||||||
|
"errors": errors,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _error_text(exc: BaseException) -> str:
|
||||||
|
return f"{type(exc).__name__}: {exc}"[:ERROR_MAX_LENGTH]
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"DouyuEligibilityResult",
|
||||||
|
"activity_client",
|
||||||
|
"query_account_overview",
|
||||||
|
"query_activity_goods",
|
||||||
|
"query_bind_info",
|
||||||
|
"query_csrf",
|
||||||
|
"query_elite_user_info",
|
||||||
|
"query_esports_bind_info",
|
||||||
|
"query_esports_goods",
|
||||||
|
"query_esports_goods_result",
|
||||||
|
"query_exchange_balance",
|
||||||
|
"query_exchange_eligibility",
|
||||||
|
"query_exchange_orders",
|
||||||
|
"query_exchange_orders_result",
|
||||||
|
"query_exchange_records",
|
||||||
|
"query_exchange_records_result",
|
||||||
|
"query_gold_account",
|
||||||
|
"query_limited_goods",
|
||||||
|
"query_limited_goods_result",
|
||||||
|
"query_points",
|
||||||
|
"query_xpd_bind_info",
|
||||||
|
]
|
||||||
@@ -35,6 +35,15 @@ from ..models import (
|
|||||||
)
|
)
|
||||||
from .audit_service import record_audit
|
from .audit_service import record_audit
|
||||||
from .collab_common import apply_order_visibility, count_archived
|
from .collab_common import apply_order_visibility, count_archived
|
||||||
|
from .douyu_activity_query import (
|
||||||
|
activity_client,
|
||||||
|
query_account_overview,
|
||||||
|
query_activity_goods,
|
||||||
|
query_elite_user_info,
|
||||||
|
query_exchange_orders,
|
||||||
|
query_exchange_records,
|
||||||
|
query_gold_account,
|
||||||
|
)
|
||||||
from .douyu_goods_service import (
|
from .douyu_goods_service import (
|
||||||
serialize_live_goods as _serialize_live_goods,
|
serialize_live_goods as _serialize_live_goods,
|
||||||
)
|
)
|
||||||
@@ -251,7 +260,7 @@ def _client_for_account(account: Account) -> DouyuActivityClient:
|
|||||||
cookie = str(account.cookie or "").strip()
|
cookie = str(account.cookie or "").strip()
|
||||||
if not cookie:
|
if not cookie:
|
||||||
raise CollabError("该账号没有 CK", code="account_no_cookie")
|
raise CollabError("该账号没有 CK", code="account_no_cookie")
|
||||||
return DouyuActivityClient(cookie)
|
return activity_client(cookie)
|
||||||
|
|
||||||
|
|
||||||
def serialize_live_goods(goods: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
def serialize_live_goods(goods: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
@@ -279,35 +288,27 @@ def _probe_with_client(
|
|||||||
}
|
}
|
||||||
|
|
||||||
active_client = client or _client_for_account(account)
|
active_client = client or _client_for_account(account)
|
||||||
errors: list[str] = []
|
overview = query_account_overview(
|
||||||
elite: dict[str, Any] = {}
|
active_client,
|
||||||
bind: dict[str, Any] = {}
|
manual_id=manual_id,
|
||||||
gold: dict[str, Any] = {}
|
rid=rid,
|
||||||
goods: list[dict[str, Any]] = []
|
act_alias=act_alias,
|
||||||
|
with_goods=with_goods,
|
||||||
try:
|
)
|
||||||
elite = active_client.elite_user_info(manual_id=manual_id, rid=rid)
|
elite = overview["elite"]
|
||||||
except Exception as exc: # noqa: BLE001 - 外部接口边界
|
bind = overview["bind"]
|
||||||
errors.append(f"手册状态: {exc}")
|
gold = overview["gold"]
|
||||||
|
goods = overview["serialized_goods"]
|
||||||
try:
|
error_labels = {
|
||||||
bind = active_client.bind_info(act_alias=act_alias)
|
"elite": "手册状态",
|
||||||
except Exception as exc: # noqa: BLE001
|
"bind": "绑定角色",
|
||||||
errors.append(f"绑定角色: {exc}")
|
"gold": "鱼翅余额",
|
||||||
|
"goods": "活动商品",
|
||||||
try:
|
}
|
||||||
gold = active_client.gold_account()
|
errors = [
|
||||||
except Exception as exc: # noqa: BLE001
|
f"{error_labels.get(key, key)}: {value}"
|
||||||
errors.append(f"鱼翅余额: {exc}")
|
for key, value in overview["errors"].items()
|
||||||
|
]
|
||||||
if with_goods:
|
|
||||||
try:
|
|
||||||
goods = (
|
|
||||||
active_client.list_goods(manual_id=manual_id, rid=rid).get("goods")
|
|
||||||
or []
|
|
||||||
)
|
|
||||||
except Exception as exc: # noqa: BLE001
|
|
||||||
errors.append(f"活动商品: {exc}")
|
|
||||||
|
|
||||||
manual_type = _to_int(elite.get("manual_type"))
|
manual_type = _to_int(elite.get("manual_type"))
|
||||||
manual_score = _to_int(elite.get("manual_score"))
|
manual_score = _to_int(elite.get("manual_score"))
|
||||||
@@ -343,7 +344,7 @@ def _probe_with_client(
|
|||||||
"bind_game_role": bind_role,
|
"bind_game_role": bind_role,
|
||||||
"bind_game_channel": bind_channel,
|
"bind_game_channel": bind_channel,
|
||||||
"fish_fin_balance": _to_int(gold.get("gold")),
|
"fish_fin_balance": _to_int(gold.get("gold")),
|
||||||
"goods": serialize_live_goods(goods),
|
"goods": goods,
|
||||||
"goods_count": len(goods),
|
"goods_count": len(goods),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1121,31 +1122,33 @@ def query_activity(
|
|||||||
records: list[dict[str, Any]] = []
|
records: list[dict[str, Any]] = []
|
||||||
orders: list[dict[str, Any]] = []
|
orders: list[dict[str, Any]] = []
|
||||||
try:
|
try:
|
||||||
elite = active_client.elite_user_info(
|
elite = query_elite_user_info(
|
||||||
manual_id=str(config.manual_id or ""), rid=str(config.rid or "")
|
active_client,
|
||||||
|
manual_id=str(config.manual_id or ""),
|
||||||
|
rid=str(config.rid or ""),
|
||||||
)
|
)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
errors.append(f"积分: {exc}")
|
errors.append(f"积分: {exc}")
|
||||||
try:
|
try:
|
||||||
gold = active_client.gold_account()
|
gold = query_gold_account(active_client)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
errors.append(f"鱼翅: {exc}")
|
errors.append(f"鱼翅: {exc}")
|
||||||
if include_records:
|
if include_records:
|
||||||
try:
|
try:
|
||||||
records = (
|
records = query_exchange_records(
|
||||||
active_client.exchange_records(
|
active_client,
|
||||||
manual_id=str(config.manual_id or ""), limit=100, offset=0
|
manual_id=str(config.manual_id or ""),
|
||||||
).get("records")
|
limit=100,
|
||||||
or []
|
offset=0,
|
||||||
)
|
)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
errors.append(f"兑换记录: {exc}")
|
errors.append(f"兑换记录: {exc}")
|
||||||
try:
|
try:
|
||||||
orders = (
|
orders = query_exchange_orders(
|
||||||
active_client.exchange_orders(
|
active_client,
|
||||||
manual_id=str(config.manual_id or ""), page=1, page_size=10
|
manual_id=str(config.manual_id or ""),
|
||||||
).get("orders")
|
page=1,
|
||||||
or []
|
page_size=10,
|
||||||
)
|
)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
errors.append(f"锁单: {exc}")
|
errors.append(f"锁单: {exc}")
|
||||||
@@ -1634,10 +1637,9 @@ def refresh_activity_goods(
|
|||||||
if account is None:
|
if account is None:
|
||||||
raise CollabError("没有带 CK 的斗鱼账号,无法刷新活动商品", code="no_account")
|
raise CollabError("没有带 CK 的斗鱼账号,无法刷新活动商品", code="no_account")
|
||||||
active_client = client or _client_for_account(account)
|
active_client = client or _client_for_account(account)
|
||||||
result = active_client.list_goods(
|
goods = query_activity_goods(
|
||||||
manual_id=str(config.manual_id or ""), rid=str(config.rid or "")
|
active_client, manual_id=str(config.manual_id or ""), rid=str(config.rid or "")
|
||||||
)
|
)
|
||||||
goods = result.get("goods") or []
|
|
||||||
upsert_goods_snapshot(db, goods, commit=False)
|
upsert_goods_snapshot(db, goods, commit=False)
|
||||||
record_audit(
|
record_audit(
|
||||||
db,
|
db,
|
||||||
@@ -2226,6 +2228,7 @@ def export_cks(
|
|||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
assert account is not None
|
||||||
ck_status = str(account.ck_check_status or "")
|
ck_status = str(account.ck_check_status or "")
|
||||||
items.append(
|
items.append(
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ from .account_binding import (
|
|||||||
set_bind_status,
|
set_bind_status,
|
||||||
)
|
)
|
||||||
from .business_events import record_bind
|
from .business_events import record_bind
|
||||||
|
from .douyu_activity_query import query_bind_info, query_esports_bind_info
|
||||||
|
|
||||||
DOUYU_LEGACY_BIND_ACT_ALIAS = "20250213NQCYX"
|
DOUYU_LEGACY_BIND_ACT_ALIAS = "20250213NQCYX"
|
||||||
DOUYU_BIND_ROLE_POLL_SECONDS = 65
|
DOUYU_BIND_ROLE_POLL_SECONDS = 65
|
||||||
@@ -277,7 +278,7 @@ class BindMixin:
|
|||||||
act_alias: str,
|
act_alias: str,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""查询电竞手册活动状态,接口同时返回当前角色和换绑冷却信息。"""
|
"""查询电竞手册活动状态,接口同时返回当前角色和换绑冷却信息。"""
|
||||||
activity_info = client.esports_bind_info(act_alias)
|
activity_info = query_esports_bind_info(client, act_alias=act_alias)
|
||||||
activity_snapshot = self._bind_snapshot(activity_info)
|
activity_snapshot = self._bind_snapshot(activity_info)
|
||||||
esports_bound = activity_snapshot["is_bound_act"]
|
esports_bound = activity_snapshot["is_bound_act"]
|
||||||
has_selected_role = bool(activity_snapshot["role_name"])
|
has_selected_role = bool(activity_snapshot["role_name"])
|
||||||
@@ -322,7 +323,7 @@ class BindMixin:
|
|||||||
if not alias:
|
if not alias:
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
info = client.bind_info(alias, v2=True)
|
info = query_bind_info(client, act_alias=alias, v2=True)
|
||||||
except DouyuActivityError as exc:
|
except DouyuActivityError as exc:
|
||||||
self._push_log("warning", f"查询绑定信息失败 act={alias}: {exc}")
|
self._push_log("warning", f"查询绑定信息失败 act={alias}: {exc}")
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from core.douyu import DouyuActivityClient
|
|||||||
|
|
||||||
from ..models import Account, DouyuTask
|
from ..models import Account, DouyuTask
|
||||||
from .business_events import record_gold_spent, record_points_credit
|
from .business_events import record_gold_spent, record_points_credit
|
||||||
|
from .douyu_activity_query import query_csrf
|
||||||
|
|
||||||
DOUYU_GIFT_POINTS_REFRESH_TIMES = 3
|
DOUYU_GIFT_POINTS_REFRESH_TIMES = 3
|
||||||
DOUYU_GIFT_POINTS_REFRESH_INTERVAL = 2
|
DOUYU_GIFT_POINTS_REFRESH_INTERVAL = 2
|
||||||
@@ -262,7 +263,7 @@ class DonateMixin:
|
|||||||
ctn = None
|
ctn = None
|
||||||
baseline_points = account.points
|
baseline_points = account.points
|
||||||
try:
|
try:
|
||||||
ctn = client.acf_ccn(refresh_subscribe=False)
|
ctn = query_csrf(client)
|
||||||
baseline_result = self._refresh_account_points(
|
baseline_result = self._refresh_account_points(
|
||||||
client, account, cookie, ctn=ctn
|
client, account, cookie, ctn=ctn
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ from core.douyu import (
|
|||||||
|
|
||||||
from ..models import Account, DouyuTask
|
from ..models import Account, DouyuTask
|
||||||
from .business_events import record_recharge
|
from .business_events import record_recharge
|
||||||
|
from .douyu_activity_query import query_exchange_balance, query_gold_account
|
||||||
from .douyu_runner_core import DOUYU_PAYMENT_POLL_INTERVAL, DOUYU_PAYMENT_POLL_SECONDS
|
from .douyu_runner_core import DOUYU_PAYMENT_POLL_INTERVAL, DOUYU_PAYMENT_POLL_SECONDS
|
||||||
from .douyu_service import update_account_profile_from_cookie
|
from .douyu_service import update_account_profile_from_cookie
|
||||||
|
|
||||||
@@ -42,8 +43,8 @@ class GoldMixin:
|
|||||||
self, client: DouyuActivityClient, account: Account
|
self, client: DouyuActivityClient, account: Account
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""刷新鱼翅和钱包兑换余额并写回账号表。"""
|
"""刷新鱼翅和钱包兑换余额并写回账号表。"""
|
||||||
gold = client.gold_account()
|
gold = query_gold_account(client)
|
||||||
exchange = client.exchange_balance()
|
exchange = query_exchange_balance(client)
|
||||||
account.gold_balance = self._to_int(gold.get("gold"))
|
account.gold_balance = self._to_int(gold.get("gold"))
|
||||||
account.exchange_balance = self._to_int(exchange.get("count"))
|
account.exchange_balance = self._to_int(exchange.get("count"))
|
||||||
account.updated_at = datetime.now(UTC)
|
account.updated_at = datetime.now(UTC)
|
||||||
|
|||||||
@@ -13,6 +13,14 @@ from core.douyu import DouyuActivityClient, DouyuActivityError
|
|||||||
|
|
||||||
from ..models import Account, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, DouyuTask
|
from ..models import Account, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, DouyuTask
|
||||||
from .business_events import record_exchange
|
from .business_events import record_exchange
|
||||||
|
from .douyu_activity_query import (
|
||||||
|
query_activity_goods,
|
||||||
|
query_csrf,
|
||||||
|
query_elite_user_info,
|
||||||
|
query_esports_goods_result,
|
||||||
|
query_exchange_records_result,
|
||||||
|
query_limited_goods_result,
|
||||||
|
)
|
||||||
from .high_value_service import (
|
from .high_value_service import (
|
||||||
DEFAULT_HIGH_VALUE_GOODS,
|
DEFAULT_HIGH_VALUE_GOODS,
|
||||||
HIGH_VALUE_STATUS_OWNED,
|
HIGH_VALUE_STATUS_OWNED,
|
||||||
@@ -70,8 +78,11 @@ class GoodsMixin:
|
|||||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||||
):
|
):
|
||||||
client = self._client(cookie)
|
client = self._client(cookie)
|
||||||
result = client.list_goods(manual_id=config["manual_id"], rid=config["rid"])
|
goods = query_activity_goods(
|
||||||
goods = result["goods"]
|
client,
|
||||||
|
manual_id=str(config["manual_id"]),
|
||||||
|
rid=str(config["rid"]),
|
||||||
|
)
|
||||||
self._upsert_goods(db, goods)
|
self._upsert_goods(db, goods)
|
||||||
high_value_goods = extract_high_value_goods(goods, DEFAULT_HIGH_VALUE_GOODS, [])
|
high_value_goods = extract_high_value_goods(goods, DEFAULT_HIGH_VALUE_GOODS, [])
|
||||||
apply_high_value_goods(account, high_value_goods)
|
apply_high_value_goods(account, high_value_goods)
|
||||||
@@ -99,7 +110,7 @@ class GoodsMixin:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""兑换成功后立即刷新官方准入;失败时只标记本次已换套装。"""
|
"""兑换成功后立即刷新官方准入;失败时只标记本次已换套装。"""
|
||||||
try:
|
try:
|
||||||
goods = client.list_goods(manual_id=manual_id, rid=rid).get("goods") or []
|
goods = query_activity_goods(client, manual_id=manual_id, rid=rid)
|
||||||
evaluated = extract_high_value_goods(goods, DEFAULT_HIGH_VALUE_GOODS, [])
|
evaluated = extract_high_value_goods(goods, DEFAULT_HIGH_VALUE_GOODS, [])
|
||||||
apply_high_value_goods(account, evaluated)
|
apply_high_value_goods(account, evaluated)
|
||||||
key = high_value_key(commodity_name)
|
key = high_value_key(commodity_name)
|
||||||
@@ -132,7 +143,8 @@ class GoodsMixin:
|
|||||||
):
|
):
|
||||||
"""刷新电竞手册皮肤商城快照。"""
|
"""刷新电竞手册皮肤商城快照。"""
|
||||||
client = self._client(cookie)
|
client = self._client(cookie)
|
||||||
result = client.list_esports_goods(
|
result = query_esports_goods_result(
|
||||||
|
client,
|
||||||
manual_id=str(config["esports_manual_id"]),
|
manual_id=str(config["esports_manual_id"]),
|
||||||
rid=str(config["room_id"]),
|
rid=str(config["room_id"]),
|
||||||
)
|
)
|
||||||
@@ -243,7 +255,7 @@ class GoodsMixin:
|
|||||||
or f"#{account.id}",
|
or f"#{account.id}",
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
ctn = client.acf_ccn(refresh_subscribe=False)
|
ctn = query_csrf(client)
|
||||||
result.update(
|
result.update(
|
||||||
self._refresh_account_points(client, account, cookie, ctn=ctn)
|
self._refresh_account_points(client, account, cookie, ctn=ctn)
|
||||||
)
|
)
|
||||||
@@ -356,7 +368,7 @@ class GoodsMixin:
|
|||||||
# ---- 对齐浏览器:先查手册状态 + 商品详情,按页面状态机选兑换链路 ----
|
# ---- 对齐浏览器:先查手册状态 + 商品详情,按页面状态机选兑换链路 ----
|
||||||
manual_type = None
|
manual_type = None
|
||||||
try:
|
try:
|
||||||
user_info = client.elite_user_info(manual_id=manual_id, rid=rid)
|
user_info = query_elite_user_info(client, manual_id=manual_id, rid=rid)
|
||||||
manual_type = user_info.get("manual_type")
|
manual_type = user_info.get("manual_type")
|
||||||
except DouyuActivityError as exc:
|
except DouyuActivityError as exc:
|
||||||
self._push_log("warning", f"查询手册状态失败,按经典流程继续: {exc}")
|
self._push_log("warning", f"查询手册状态失败,按经典流程继续: {exc}")
|
||||||
@@ -554,7 +566,7 @@ class GoodsMixin:
|
|||||||
# 兑换成功后自动刷新积分,更新账号最新积分信息(失败不阻断兑换成功)
|
# 兑换成功后自动刷新积分,更新账号最新积分信息(失败不阻断兑换成功)
|
||||||
points_refresh = None
|
points_refresh = None
|
||||||
try:
|
try:
|
||||||
ctn = client.acf_ccn(refresh_subscribe=False)
|
ctn = query_csrf(client)
|
||||||
points_refresh = self._refresh_account_points(
|
points_refresh = self._refresh_account_points(
|
||||||
client, account, cookie, ctn=ctn
|
client, account, cookie, ctn=ctn
|
||||||
)
|
)
|
||||||
@@ -704,8 +716,8 @@ class GoodsMixin:
|
|||||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||||
):
|
):
|
||||||
client = self._client(cookie)
|
client = self._client(cookie)
|
||||||
result = client.query_limited_goods(
|
result = query_limited_goods_result(
|
||||||
manual_id=str(config["manual_id"]), rid=str(config["rid"])
|
client, manual_id=str(config["manual_id"]), rid=str(config["rid"])
|
||||||
)
|
)
|
||||||
limited = result["limited_goods"]
|
limited = result["limited_goods"]
|
||||||
goods = (result.get("raw") or {}).get("data", {}).get("list") or []
|
goods = (result.get("raw") or {}).get("data", {}).get("list") or []
|
||||||
@@ -738,8 +750,13 @@ class GoodsMixin:
|
|||||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||||
):
|
):
|
||||||
client = self._client(cookie)
|
client = self._client(cookie)
|
||||||
result = client.exchange_records(manual_id=str(config["manual_id"]))
|
result = query_exchange_records_result(
|
||||||
records = result["records"]
|
client,
|
||||||
|
manual_id=str(config["manual_id"]),
|
||||||
|
limit=100,
|
||||||
|
offset=0,
|
||||||
|
)
|
||||||
|
records = result.get("records") or []
|
||||||
account.updated_at = datetime.now(UTC)
|
account.updated_at = datetime.now(UTC)
|
||||||
self._mark_task(
|
self._mark_task(
|
||||||
db,
|
db,
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from core.douyu import DouyuActivityClient, DouyuActivityError
|
|||||||
|
|
||||||
from ..models import Account, DouyuTask
|
from ..models import Account, DouyuTask
|
||||||
from .account_events_service import EVENT_ELITE_OPENED, EVENT_ESPORTS_OPENED, emit
|
from .account_events_service import EVENT_ELITE_OPENED, EVENT_ESPORTS_OPENED, emit
|
||||||
|
from .douyu_activity_query import query_csrf, query_elite_user_info, query_points
|
||||||
from .douyu_runner_core import DOUYU_PAYMENT_POLL_INTERVAL, DOUYU_PAYMENT_POLL_SECONDS
|
from .douyu_runner_core import DOUYU_PAYMENT_POLL_INTERVAL, DOUYU_PAYMENT_POLL_SECONDS
|
||||||
from .douyu_service import account_uid, update_account_profile_from_cookie
|
from .douyu_service import account_uid, update_account_profile_from_cookie
|
||||||
|
|
||||||
@@ -49,8 +50,8 @@ class ManualMixin:
|
|||||||
uid = account_uid(account, cookie)
|
uid = account_uid(account, cookie)
|
||||||
if not uid:
|
if not uid:
|
||||||
raise DouyuActivityError("Cookie 中没有 acf_uid,无法查询积分")
|
raise DouyuActivityError("Cookie 中没有 acf_uid,无法查询积分")
|
||||||
ctn_value = ctn or client.acf_ccn(refresh_subscribe=False)
|
ctn_value = ctn or query_csrf(client)
|
||||||
result = client.query_points(uid=uid, ctn=ctn_value)
|
result = query_points(client, uid=uid, ctn=ctn_value)
|
||||||
points = self._to_int(result.get("points"))
|
points = self._to_int(result.get("points"))
|
||||||
account.uid = uid
|
account.uid = uid
|
||||||
account.points = points
|
account.points = points
|
||||||
@@ -79,7 +80,7 @@ class ManualMixin:
|
|||||||
积分区分不了「开通后积分花完」和「从未开通」,manualType 才是权威口径:
|
积分区分不了「开通后积分花完」和「从未开通」,manualType 才是权威口径:
|
||||||
0=未开通,>=1=已开通。
|
0=未开通,>=1=已开通。
|
||||||
"""
|
"""
|
||||||
result = client.elite_user_info(manual_id=manual_id, rid=rid)
|
result = query_elite_user_info(client, manual_id=manual_id, rid=rid)
|
||||||
manual_type = self._to_int(result.get("manual_type")) or 0
|
manual_type = self._to_int(result.get("manual_type")) or 0
|
||||||
manual_score = self._to_int(result.get("manual_score"))
|
manual_score = self._to_int(result.get("manual_score"))
|
||||||
expire_time = self._to_int(result.get("expire_time")) or 0
|
expire_time = self._to_int(result.get("expire_time")) or 0
|
||||||
@@ -211,9 +212,7 @@ class ManualMixin:
|
|||||||
account.esports_opened = manual_type is not None and manual_type >= 1
|
account.esports_opened = manual_type is not None and manual_type >= 1
|
||||||
# 到期时间也落库 —— 否则界面只能显示"已开通",看不到什么时候到期
|
# 到期时间也落库 —— 否则界面只能显示"已开通",看不到什么时候到期
|
||||||
expire_raw = result.get("expire_time")
|
expire_raw = result.get("expire_time")
|
||||||
expire_int = (
|
expire_int = self._to_int(expire_raw)
|
||||||
int(expire_raw) if str(expire_raw or "").strip().isdigit() else None
|
|
||||||
)
|
|
||||||
# ⚠️ 斗鱼用 0 表示「没有到期时间」。直接存 0 的话界面会显示 1970/1/1
|
# ⚠️ 斗鱼用 0 表示「没有到期时间」。直接存 0 的话界面会显示 1970/1/1
|
||||||
# (这个坑在积分到期上踩过一次,这里别再踩)。
|
# (这个坑在积分到期上踩过一次,这里别再踩)。
|
||||||
account.esports_expire_time = (
|
account.esports_expire_time = (
|
||||||
@@ -306,7 +305,7 @@ class ManualMixin:
|
|||||||
client = self._client(cookie)
|
client = self._client(cookie)
|
||||||
ctn = str(self._task_payload(task).get("ctn") or "")
|
ctn = str(self._task_payload(task).get("ctn") or "")
|
||||||
if not ctn:
|
if not ctn:
|
||||||
ctn = client.acf_ccn(refresh_subscribe=True)
|
ctn = query_csrf(client, refresh_subscribe=True)
|
||||||
act_alias = self._confirm_act_alias(config) or self._bind_qr_act_alias(config)
|
act_alias = self._confirm_act_alias(config) or self._bind_qr_act_alias(config)
|
||||||
if not act_alias:
|
if not act_alias:
|
||||||
self._mark_task(db, task, "failed", "请先配置开通宝典活动 actAlias")
|
self._mark_task(db, task, "failed", "请先配置开通宝典活动 actAlias")
|
||||||
@@ -435,7 +434,7 @@ class ManualMixin:
|
|||||||
client = self._client(cookie)
|
client = self._client(cookie)
|
||||||
ctn = str(self._task_payload(task).get("ctn") or "")
|
ctn = str(self._task_payload(task).get("ctn") or "")
|
||||||
if not ctn:
|
if not ctn:
|
||||||
ctn = client.acf_ccn(refresh_subscribe=True)
|
ctn = query_csrf(client, refresh_subscribe=True)
|
||||||
act_alias = str(config.get("esports_act_alias") or "").strip()
|
act_alias = str(config.get("esports_act_alias") or "").strip()
|
||||||
manual_id = str(config.get("esports_manual_id") or "").strip()
|
manual_id = str(config.get("esports_manual_id") or "").strip()
|
||||||
if not act_alias or not manual_id:
|
if not act_alias or not manual_id:
|
||||||
@@ -561,7 +560,7 @@ class ManualMixin:
|
|||||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||||
):
|
):
|
||||||
client = self._client(cookie)
|
client = self._client(cookie)
|
||||||
ctn = client.acf_ccn(refresh_subscribe=False)
|
ctn = query_csrf(client)
|
||||||
result = self._refresh_account_points(client, account, cookie, ctn=ctn)
|
result = self._refresh_account_points(client, account, cookie, ctn=ctn)
|
||||||
account.updated_at = datetime.now(UTC)
|
account.updated_at = datetime.now(UTC)
|
||||||
points = result["points"]
|
points = result["points"]
|
||||||
|
|||||||
@@ -35,6 +35,14 @@ from core.douyu import DouyuActivityClient
|
|||||||
from ..models import Account, DouyuTask
|
from ..models import Account, DouyuTask
|
||||||
from .account_binding import derive_from_bind_info, set_bind_status
|
from .account_binding import derive_from_bind_info, set_bind_status
|
||||||
from .business_events import record_official_exchange
|
from .business_events import record_official_exchange
|
||||||
|
from .douyu_activity_query import (
|
||||||
|
query_activity_goods,
|
||||||
|
query_bind_info,
|
||||||
|
query_csrf,
|
||||||
|
query_esports_bind_info,
|
||||||
|
query_exchange_records,
|
||||||
|
query_xpd_bind_info,
|
||||||
|
)
|
||||||
from .douyu_runner_donate import _parse_expire_at, _points_expire_at
|
from .douyu_runner_donate import _parse_expire_at, _points_expire_at
|
||||||
from .high_value_service import (
|
from .high_value_service import (
|
||||||
DEFAULT_HIGH_VALUE_GOODS,
|
DEFAULT_HIGH_VALUE_GOODS,
|
||||||
@@ -189,10 +197,10 @@ class OverviewMixin:
|
|||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""按作用域查绑定信息(三个接口不同,收敛在一处)。"""
|
"""按作用域查绑定信息(三个接口不同,收敛在一处)。"""
|
||||||
if scope == "elite":
|
if scope == "elite":
|
||||||
return client.bind_info(alias)
|
return query_bind_info(client, act_alias=alias)
|
||||||
if scope == "esports":
|
if scope == "esports":
|
||||||
return client.esports_bind_info(alias)
|
return query_esports_bind_info(client, act_alias=alias)
|
||||||
return client.xpd_bind_info(act_alias=alias)
|
return query_xpd_bind_info(client, act_alias=alias)
|
||||||
|
|
||||||
def _fetch_elite_records(
|
def _fetch_elite_records(
|
||||||
self,
|
self,
|
||||||
@@ -201,11 +209,10 @@ class OverviewMixin:
|
|||||||
manual_id: str,
|
manual_id: str,
|
||||||
esports_manual_id: str,
|
esports_manual_id: str,
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
return (
|
return query_exchange_records(
|
||||||
client.exchange_records(
|
client,
|
||||||
manual_id=manual_id, limit=EXCHANGE_RECORD_LIMIT
|
manual_id=manual_id,
|
||||||
).get("records")
|
limit=EXCHANGE_RECORD_LIMIT,
|
||||||
or []
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def _fetch_esports_records(
|
def _fetch_esports_records(
|
||||||
@@ -215,11 +222,10 @@ class OverviewMixin:
|
|||||||
manual_id: str,
|
manual_id: str,
|
||||||
esports_manual_id: str,
|
esports_manual_id: str,
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
return (
|
return query_exchange_records(
|
||||||
client.exchange_records(
|
client,
|
||||||
manual_id=esports_manual_id, limit=EXCHANGE_RECORD_LIMIT
|
manual_id=esports_manual_id,
|
||||||
).get("records")
|
limit=EXCHANGE_RECORD_LIMIT,
|
||||||
or []
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def _fetch_xpd_records(
|
def _fetch_xpd_records(
|
||||||
@@ -281,7 +287,7 @@ class OverviewMixin:
|
|||||||
|
|
||||||
# ---- 积分 + 到期时间 ----
|
# ---- 积分 + 到期时间 ----
|
||||||
try:
|
try:
|
||||||
ctn = client.acf_ccn(refresh_subscribe=False)
|
ctn = query_csrf(client)
|
||||||
points = self._refresh_account_points(client, account, cookie, ctn=ctn)
|
points = self._refresh_account_points(client, account, cookie, ctn=ctn)
|
||||||
overview["assets"]["points"] = points.get("points")
|
overview["assets"]["points"] = points.get("points")
|
||||||
# `_refresh_account_points` 只回 {"points", "points_query"},
|
# `_refresh_account_points` 只回 {"points", "points_query"},
|
||||||
@@ -349,8 +355,7 @@ class OverviewMixin:
|
|||||||
goods_items: list[dict[str, Any]] = []
|
goods_items: list[dict[str, Any]] = []
|
||||||
try:
|
try:
|
||||||
# 🎯 拉取完整商城商品列表(含每个商品准确的 status 状态:1=已达兑换上限,0=可兑换)
|
# 🎯 拉取完整商城商品列表(含每个商品准确的 status 状态:1=已达兑换上限,0=可兑换)
|
||||||
goods = client.list_goods(manual_id=manual_id, rid=rid)
|
goods_items = query_activity_goods(client, manual_id=manual_id, rid=rid)
|
||||||
goods_items = goods.get("goods") or []
|
|
||||||
overview["limited_goods_total"] = len(goods_items)
|
overview["limited_goods_total"] = len(goods_items)
|
||||||
goods_query_ok = True
|
goods_query_ok = True
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ from .account_binding import (
|
|||||||
set_bind_status,
|
set_bind_status,
|
||||||
)
|
)
|
||||||
from .business_events import record_exchange
|
from .business_events import record_exchange
|
||||||
|
from .douyu_activity_query import query_xpd_bind_info
|
||||||
|
|
||||||
DOUYU_XPD_BIND_POLL_SECONDS = 300
|
DOUYU_XPD_BIND_POLL_SECONDS = 300
|
||||||
DOUYU_XPD_BIND_POLL_INTERVAL = 5
|
DOUYU_XPD_BIND_POLL_INTERVAL = 5
|
||||||
@@ -138,7 +139,7 @@ class XpdMixin:
|
|||||||
db.commit()
|
db.commit()
|
||||||
# 记录绑定前状态:已绑定账号生成二维码后必须等扫码换绑,不能立即成功
|
# 记录绑定前状态:已绑定账号生成二维码后必须等扫码换绑,不能立即成功
|
||||||
try:
|
try:
|
||||||
before = client.xpd_bind_info(act_alias=act_alias)
|
before = query_xpd_bind_info(client, act_alias=act_alias)
|
||||||
result["before_bound"] = bool(before.get("bind_role"))
|
result["before_bound"] = bool(before.get("bind_role"))
|
||||||
result["before_role_name"] = str(before.get("role_name") or "")
|
result["before_role_name"] = str(before.get("role_name") or "")
|
||||||
result["before_area_name"] = str(before.get("area_name") or "")
|
result["before_area_name"] = str(before.get("area_name") or "")
|
||||||
@@ -193,7 +194,7 @@ class XpdMixin:
|
|||||||
poll_count = 0
|
poll_count = 0
|
||||||
while not self._stop.is_set() and time.monotonic() <= deadline:
|
while not self._stop.is_set() and time.monotonic() <= deadline:
|
||||||
try:
|
try:
|
||||||
info = client.xpd_bind_info(act_alias=act_alias)
|
info = query_xpd_bind_info(client, act_alias=act_alias)
|
||||||
poll_count += 1
|
poll_count += 1
|
||||||
result["bind_poll_count"] = poll_count
|
result["bind_poll_count"] = poll_count
|
||||||
result["bind_polling"] = True
|
result["bind_polling"] = True
|
||||||
@@ -246,7 +247,7 @@ class XpdMixin:
|
|||||||
if not act_alias:
|
if not act_alias:
|
||||||
self._mark_task(db, task, "failed", "请先配置小店活动代号 actAlias")
|
self._mark_task(db, task, "failed", "请先配置小店活动代号 actAlias")
|
||||||
return
|
return
|
||||||
result = client.xpd_bind_info(act_alias=act_alias)
|
result = query_xpd_bind_info(client, act_alias=act_alias)
|
||||||
role_name = str(result.get("role_name") or "")
|
role_name = str(result.get("role_name") or "")
|
||||||
if not result.get("bind_role") or not role_name:
|
if not result.get("bind_role") or not role_name:
|
||||||
set_bind_status(account, SCOPE_PEACE, BIND_UNBOUND)
|
set_bind_status(account, SCOPE_PEACE, BIND_UNBOUND)
|
||||||
@@ -294,7 +295,7 @@ class XpdMixin:
|
|||||||
if not act_alias:
|
if not act_alias:
|
||||||
self._mark_task(db, task, "failed", "请先配置小店活动代号 actAlias")
|
self._mark_task(db, task, "failed", "请先配置小店活动代号 actAlias")
|
||||||
return
|
return
|
||||||
result = client.xpd_bind_info(act_alias=act_alias)
|
result = query_xpd_bind_info(client, act_alias=act_alias)
|
||||||
status = "已绑定" if result.get("bind_role") else "未绑定"
|
status = "已绑定" if result.get("bind_role") else "未绑定"
|
||||||
text = str(result.get("role_name") or result.get("nick") or "-")
|
text = str(result.get("role_name") or result.get("nick") or "-")
|
||||||
self._mark_task(
|
self._mark_task(
|
||||||
|
|||||||
@@ -10,8 +10,7 @@ from fastapi import HTTPException
|
|||||||
from sqlalchemy import or_
|
from sqlalchemy import or_
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from core.douyu import DouyuActivityClient, DouyuActivityError
|
from core.douyu import DouyuActivityError
|
||||||
from core.douyu.cookie_utils import cookie_value
|
|
||||||
|
|
||||||
from ...models import (
|
from ...models import (
|
||||||
Account,
|
Account,
|
||||||
@@ -23,6 +22,7 @@ from ...models import (
|
|||||||
PlatformFulfillmentTask,
|
PlatformFulfillmentTask,
|
||||||
User,
|
User,
|
||||||
)
|
)
|
||||||
|
from ..douyu_activity_query import activity_client, query_exchange_eligibility
|
||||||
from ..douyu_batch_launcher import start_douyu_batch
|
from ..douyu_batch_launcher import start_douyu_batch
|
||||||
from ..douyu_service import douyu_config_value, ensure_douyu_config
|
from ..douyu_service import douyu_config_value, ensure_douyu_config
|
||||||
from ..external_order_source import (
|
from ..external_order_source import (
|
||||||
@@ -103,9 +103,11 @@ def _append_event(
|
|||||||
|
|
||||||
|
|
||||||
def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask:
|
def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask:
|
||||||
task = db.query(PlatformFulfillmentTask).filter(
|
task = (
|
||||||
PlatformFulfillmentTask.id == int(task_id)
|
db.query(PlatformFulfillmentTask)
|
||||||
).first()
|
.filter(PlatformFulfillmentTask.id == int(task_id))
|
||||||
|
.first()
|
||||||
|
)
|
||||||
if task is None:
|
if task is None:
|
||||||
raise HTTPException(status_code=404, detail="直播账号履约任务不存在")
|
raise HTTPException(status_code=404, detail="直播账号履约任务不存在")
|
||||||
return task
|
return task
|
||||||
@@ -339,9 +341,7 @@ def _task_out(
|
|||||||
"areaName": str(bind_result.get("area_name") or ""),
|
"areaName": str(bind_result.get("area_name") or ""),
|
||||||
"platName": str(bind_result.get("plat_name") or ""),
|
"platName": str(bind_result.get("plat_name") or ""),
|
||||||
"bindPhase": str(bind_result.get("bind_phase") or ""),
|
"bindPhase": str(bind_result.get("bind_phase") or ""),
|
||||||
"bindReadyForConfirm": bool(
|
"bindReadyForConfirm": bool(bind_result.get("bind_ready_for_confirm")),
|
||||||
bind_result.get("bind_ready_for_confirm")
|
|
||||||
),
|
|
||||||
"bindConfirmed": bool(bind_result.get("bind_confirmed")),
|
"bindConfirmed": bool(bind_result.get("bind_confirmed")),
|
||||||
}
|
}
|
||||||
if bind_task
|
if bind_task
|
||||||
@@ -474,12 +474,12 @@ def upsert_mapping(
|
|||||||
detail={"commodityId": row.commodity_id, "enabled": row.enabled},
|
detail={"commodityId": row.commodity_id, "enabled": row.enabled},
|
||||||
)
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
return next(item for item in list_mappings(db, keyword=sku_key) if item["id"] == row.id)
|
return next(
|
||||||
|
item for item in list_mappings(db, keyword=sku_key) if item["id"] == row.id
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def allocate_task(
|
def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]:
|
||||||
db: Session, *, task_id: int, current: User
|
|
||||||
) -> dict[str, Any]:
|
|
||||||
task = _load_task(db, task_id)
|
task = _load_task(db, task_id)
|
||||||
if task.execution_status in {"completed", "cancelled"}:
|
if task.execution_status in {"completed", "cancelled"}:
|
||||||
raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号")
|
raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号")
|
||||||
@@ -579,9 +579,7 @@ def release_task_account(
|
|||||||
return get_task_detail(db, task.id)
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
|
|
||||||
async def start_binding(
|
async def start_binding(db: Session, *, task_id: int, current: User) -> dict[str, Any]:
|
||||||
db: Session, *, task_id: int, current: User
|
|
||||||
) -> dict[str, Any]:
|
|
||||||
task = _load_task(db, task_id)
|
task = _load_task(db, task_id)
|
||||||
if not task.account_id or not task.lease_id:
|
if not task.account_id or not task.lease_id:
|
||||||
raise HTTPException(status_code=409, detail="请先分配账号")
|
raise HTTPException(status_code=409, detail="请先分配账号")
|
||||||
@@ -728,21 +726,17 @@ def refresh_exchange_eligibility(
|
|||||||
raise HTTPException(status_code=409, detail="账号 CK 不可用")
|
raise HTTPException(status_code=409, detail="账号 CK 不可用")
|
||||||
config = ensure_douyu_config(db)
|
config = ensure_douyu_config(db)
|
||||||
try:
|
try:
|
||||||
client = DouyuActivityClient(cookie=str(account.cookie))
|
cookie = str(account.cookie)
|
||||||
ctn = client.acf_ccn(refresh_subscribe=False)
|
client = activity_client(cookie)
|
||||||
user_info = client.elite_user_info(
|
eligibility = query_exchange_eligibility(
|
||||||
|
client,
|
||||||
|
cookie=cookie,
|
||||||
manual_id=str(douyu_config_value("manual_id", config.manual_id)),
|
manual_id=str(douyu_config_value("manual_id", config.manual_id)),
|
||||||
rid=str(douyu_config_value("rid", config.rid)),
|
rid=str(douyu_config_value("rid", config.rid)),
|
||||||
|
uid=str(account.uid or ""),
|
||||||
)
|
)
|
||||||
account.elite_opened = bool(user_info.get("manual_type"))
|
account.elite_opened = bool(eligibility.elite_user_info.get("manual_type"))
|
||||||
uid = account.uid or cookie_value(str(account.cookie), "acf_uid")
|
account.points = eligibility.points
|
||||||
points_result = client.query_points(uid=uid, ctn=ctn)
|
|
||||||
account.points = int(points_result.get("points") or 0)
|
|
||||||
result = client.query_limited_goods(
|
|
||||||
manual_id=str(douyu_config_value("manual_id", config.manual_id)),
|
|
||||||
rid=str(douyu_config_value("rid", config.rid)),
|
|
||||||
)
|
|
||||||
limited = result.get("limited_goods") or []
|
|
||||||
except DouyuActivityError as exc:
|
except DouyuActivityError as exc:
|
||||||
task.execution_status = "manual_required"
|
task.execution_status = "manual_required"
|
||||||
task.exchange_status = "check_failed"
|
task.exchange_status = "check_failed"
|
||||||
@@ -760,13 +754,7 @@ def refresh_exchange_eligibility(
|
|||||||
db.commit()
|
db.commit()
|
||||||
return get_task_detail(db, task.id)
|
return get_task_detail(db, task.id)
|
||||||
|
|
||||||
limited_ids = {
|
if task.commodity_id in eligibility.limited_ids:
|
||||||
str(item.get("commodityId") or item.get("commodity_id") or "")
|
|
||||||
for item in limited
|
|
||||||
if isinstance(item, dict)
|
|
||||||
}
|
|
||||||
limited_ids.discard("")
|
|
||||||
if task.commodity_id in limited_ids:
|
|
||||||
task.exchange_status = "limited"
|
task.exchange_status = "limited"
|
||||||
task.issue_code = "commodity_limit_reached"
|
task.issue_code = "commodity_limit_reached"
|
||||||
task.last_error = "该账号已达到此商品兑换上限"
|
task.last_error = "该账号已达到此商品兑换上限"
|
||||||
@@ -795,7 +783,7 @@ def refresh_exchange_eligibility(
|
|||||||
actor_id=current.id,
|
actor_id=current.id,
|
||||||
detail={
|
detail={
|
||||||
"exchangeStatus": task.exchange_status,
|
"exchangeStatus": task.exchange_status,
|
||||||
"limitedCount": len(limited_ids),
|
"limitedCount": len(eligibility.limited_ids),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ export const douyuApi = {
|
|||||||
getRechargeChannel: () => api.get<DouyuRechargeChannel, DouyuRechargeChannel>('/douyu/recharge-channel'),
|
getRechargeChannel: () => api.get<DouyuRechargeChannel, DouyuRechargeChannel>('/douyu/recharge-channel'),
|
||||||
updateConfig: (data: Partial<DouyuConfig>) => api.put<DouyuConfig, DouyuConfig>('/douyu/config', data),
|
updateConfig: (data: Partial<DouyuConfig>) => api.put<DouyuConfig, DouyuConfig>('/douyu/config', data),
|
||||||
listGoods: () => api.get<DouyuGoodsItem[], DouyuGoodsItem[]>('/douyu/goods'),
|
listGoods: () => api.get<DouyuGoodsItem[], DouyuGoodsItem[]>('/douyu/goods'),
|
||||||
|
listLiveGoods: () => api.get<DouyuGoodsItem[], DouyuGoodsItem[]>('/douyu/goods/live'),
|
||||||
listEsportsGoods: () => api.get<DouyuGoodsItem[], DouyuGoodsItem[]>('/douyu/esports-goods'),
|
listEsportsGoods: () => api.get<DouyuGoodsItem[], DouyuGoodsItem[]>('/douyu/esports-goods'),
|
||||||
listPeaceGoods: () => api.get<DouyuXpdGoodsItem[], DouyuXpdGoodsItem[]>('/douyu/xpd-goods'),
|
listPeaceGoods: () => api.get<DouyuXpdGoodsItem[], DouyuXpdGoodsItem[]>('/douyu/xpd-goods'),
|
||||||
createTasks: (data: DouyuTaskBatchRequest) =>
|
createTasks: (data: DouyuTaskBatchRequest) =>
|
||||||
|
|||||||
@@ -1,41 +1,9 @@
|
|||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
import {
|
import { Alert, Button, Card, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd';
|
||||||
Alert,
|
import { CheckCircleOutlined, CopyOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SyncOutlined, UserSwitchOutlined } from '@ant-design/icons';
|
||||||
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 type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import { douyuApi, platformFulfillmentApi } from '../api/modules';
|
import { douyuApi, platformFulfillmentApi } from '../api/modules';
|
||||||
import type {
|
import type { DouyuGoodsItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentTask } from '../api/modules';
|
||||||
DouyuGoodsItem,
|
|
||||||
PlatformFulfillmentDetail,
|
|
||||||
PlatformFulfillmentMapping,
|
|
||||||
PlatformFulfillmentTask,
|
|
||||||
} from '../api/modules';
|
|
||||||
import { getErrorMessage } from '../utils/error';
|
import { getErrorMessage } from '../utils/error';
|
||||||
import { message } from '../utils/antdMessage';
|
import { message } from '../utils/antdMessage';
|
||||||
import { formatTime } from '../utils/time';
|
import { formatTime } from '../utils/time';
|
||||||
@@ -100,6 +68,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
const [mappingPoints, setMappingPoints] = useState<number | null>(null);
|
const [mappingPoints, setMappingPoints] = useState<number | null>(null);
|
||||||
const [mappingEnabled, setMappingEnabled] = useState(true);
|
const [mappingEnabled, setMappingEnabled] = useState(true);
|
||||||
const [goods, setGoods] = useState<DouyuGoodsItem[]>([]);
|
const [goods, setGoods] = useState<DouyuGoodsItem[]>([]);
|
||||||
|
const [mappingGoodsLoading, setMappingGoodsLoading] = useState(false);
|
||||||
const [mappings, setMappings] = useState<PlatformFulfillmentMapping[]>([]);
|
const [mappings, setMappings] = useState<PlatformFulfillmentMapping[]>([]);
|
||||||
|
|
||||||
const loadTasks = useCallback(async () => {
|
const loadTasks = useCallback(async () => {
|
||||||
@@ -178,15 +147,35 @@ export default function PlatformFulfillmentPage() {
|
|||||||
setMappingPoints(task?.requiredPoints ?? null);
|
setMappingPoints(task?.requiredPoints ?? null);
|
||||||
setMappingEnabled(true);
|
setMappingEnabled(true);
|
||||||
setMappingOpen(true);
|
setMappingOpen(true);
|
||||||
|
setMappingGoodsLoading(true);
|
||||||
try {
|
try {
|
||||||
const [goodsRows, mappingRows] = await Promise.all([
|
const [goodsRows, mappingRows] = await Promise.all([douyuApi.listLiveGoods(), platformFulfillmentApi.listMappings(task?.internalSkuKey || '')]);
|
||||||
douyuApi.listGoods(),
|
|
||||||
platformFulfillmentApi.listMappings(task?.internalSkuKey || ''),
|
|
||||||
]);
|
|
||||||
setGoods(goodsRows);
|
setGoods(goodsRows);
|
||||||
setMappings(mappingRows);
|
setMappings(mappingRows);
|
||||||
|
if (goodsRows.length === 0) {
|
||||||
|
message.warning('斗鱼活动商品为空,请稍后刷新商品列表');
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
message.error(getErrorMessage(error));
|
message.error(getErrorMessage(error));
|
||||||
|
} finally {
|
||||||
|
setMappingGoodsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const reloadMappingGoods = async () => {
|
||||||
|
setMappingGoodsLoading(true);
|
||||||
|
try {
|
||||||
|
const rows = await douyuApi.listLiveGoods();
|
||||||
|
setGoods(rows);
|
||||||
|
if (rows.length === 0) {
|
||||||
|
message.warning('斗鱼活动商品为空,请稍后重试');
|
||||||
|
} else {
|
||||||
|
message.success(`已加载 ${rows.length} 个斗鱼活动商品`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
message.error(getErrorMessage(error));
|
||||||
|
} finally {
|
||||||
|
setMappingGoodsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -240,9 +229,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
render: (_, task) => (
|
render: (_, task) => (
|
||||||
<Space direction="vertical" size={2}>
|
<Space direction="vertical" size={2}>
|
||||||
<Text>{task.commodityId || '未映射'}</Text>
|
<Text>{task.commodityId || '未映射'}</Text>
|
||||||
<Text type="secondary">
|
<Text type="secondary">{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}</Text>
|
||||||
{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}
|
|
||||||
</Text>
|
|
||||||
</Space>
|
</Space>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -288,9 +275,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
width: 150,
|
width: 150,
|
||||||
render: (_, task) => (
|
render: (_, task) => (
|
||||||
<Space direction="vertical" size={4}>
|
<Space direction="vertical" size={4}>
|
||||||
<Tag color={STATUS_COLORS[task.executionStatus] || 'default'}>
|
<Tag color={STATUS_COLORS[task.executionStatus] || 'default'}>{statusLabel(task.executionStatus)}</Tag>
|
||||||
{statusLabel(task.executionStatus)}
|
|
||||||
</Tag>
|
|
||||||
<Text type="secondary">兑换:{task.exchangeStatus}</Text>
|
<Text type="secondary">兑换:{task.exchangeStatus}</Text>
|
||||||
</Space>
|
</Space>
|
||||||
),
|
),
|
||||||
@@ -311,86 +296,36 @@ export default function PlatformFulfillmentPage() {
|
|||||||
详情
|
详情
|
||||||
</Button>
|
</Button>
|
||||||
{task.executionStatus === 'pending_mapping' ? (
|
{task.executionStatus === 'pending_mapping' ? (
|
||||||
<Button
|
<Button size="small" type="primary" icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping(task)}>
|
||||||
size="small"
|
|
||||||
type="primary"
|
|
||||||
icon={<LinkOutlined />}
|
|
||||||
disabled={!can('platform_fulfillment:admin')}
|
|
||||||
onClick={() => void openMapping(task)}
|
|
||||||
>
|
|
||||||
配置映射
|
配置映射
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
{task.executionStatus === 'ready' ? (
|
{task.executionStatus === 'ready' ? (
|
||||||
<Button
|
<Button size="small" type="primary" icon={<UserSwitchOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.allocate(task.id))}>
|
||||||
size="small"
|
|
||||||
type="primary"
|
|
||||||
icon={<UserSwitchOutlined />}
|
|
||||||
onClick={() =>
|
|
||||||
void runTaskAction(() => platformFulfillmentApi.allocate(task.id))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
自动选号
|
自动选号
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
{task.executionStatus === 'allocated' ? (
|
{task.executionStatus === 'allocated' ? (
|
||||||
<Button
|
<Button size="small" type="primary" icon={<QrcodeOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.startBinding(task.id))}>
|
||||||
size="small"
|
|
||||||
type="primary"
|
|
||||||
icon={<QrcodeOutlined />}
|
|
||||||
onClick={() =>
|
|
||||||
void runTaskAction(() => platformFulfillmentApi.startBinding(task.id))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
生成二维码
|
生成二维码
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
{['waiting_bind', 'binding_confirming'].includes(task.executionStatus) ? (
|
{['waiting_bind', 'binding_confirming'].includes(task.executionStatus) ? (
|
||||||
<Button
|
<Button size="small" icon={<ReloadOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.refreshBinding(task.id))}>
|
||||||
size="small"
|
|
||||||
icon={<ReloadOutlined />}
|
|
||||||
onClick={() =>
|
|
||||||
void runTaskAction(() => platformFulfillmentApi.refreshBinding(task.id))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
刷新绑定
|
刷新绑定
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
{task.executionStatus === 'role_ready' ? (
|
{task.executionStatus === 'role_ready' ? (
|
||||||
<Button
|
<Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.confirmBinding(task.id))}>
|
||||||
size="small"
|
|
||||||
type="primary"
|
|
||||||
icon={<CheckCircleOutlined />}
|
|
||||||
onClick={() =>
|
|
||||||
void runTaskAction(() => platformFulfillmentApi.confirmBinding(task.id))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
确认绑定
|
确认绑定
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
{task.executionStatus === 'bound' ? (
|
{task.executionStatus === 'bound' ? (
|
||||||
<>
|
<>
|
||||||
<Button
|
<Button size="small" icon={<SyncOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.refreshEligibility(task.id))}>
|
||||||
size="small"
|
|
||||||
icon={<SyncOutlined />}
|
|
||||||
onClick={() =>
|
|
||||||
void runTaskAction(() =>
|
|
||||||
platformFulfillmentApi.refreshEligibility(task.id),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
刷新兑换资格
|
刷新兑换资格
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button size="small" type="primary" disabled={task.exchangeStatus !== 'eligible'} onClick={() => void runTaskAction(() => platformFulfillmentApi.complete(task.id, '人工兑换完成'))}>
|
||||||
size="small"
|
|
||||||
type="primary"
|
|
||||||
disabled={task.exchangeStatus !== 'eligible'}
|
|
||||||
onClick={() =>
|
|
||||||
void runTaskAction(() =>
|
|
||||||
platformFulfillmentApi.complete(task.id, '人工兑换完成'),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
完成
|
完成
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
@@ -407,25 +342,9 @@ export default function PlatformFulfillmentPage() {
|
|||||||
查看二维码
|
查看二维码
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
{selected.account ? (
|
{selected.account ? <Button onClick={() => void runTaskAction(() => platformFulfillmentApi.release(selected.id))}>释放账号</Button> : null}
|
||||||
<Button
|
{selected.executionStatus !== 'completed' && selected.executionStatus !== 'cancelled' ? (
|
||||||
onClick={() =>
|
<Button danger onClick={() => void runTaskAction(() => platformFulfillmentApi.cancel(selected.id, '运营取消'))}>
|
||||||
void runTaskAction(() => platformFulfillmentApi.release(selected.id))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
释放账号
|
|
||||||
</Button>
|
|
||||||
) : null}
|
|
||||||
{selected.executionStatus !== 'completed' &&
|
|
||||||
selected.executionStatus !== 'cancelled' ? (
|
|
||||||
<Button
|
|
||||||
danger
|
|
||||||
onClick={() =>
|
|
||||||
void runTaskAction(() =>
|
|
||||||
platformFulfillmentApi.cancel(selected.id, '运营取消'),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
取消
|
取消
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -440,9 +359,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
<Title level={4} style={{ margin: 0 }}>
|
<Title level={4} style={{ margin: 0 }}>
|
||||||
直播账号履约工作台
|
直播账号履约工作台
|
||||||
</Title>
|
</Title>
|
||||||
<Text type="secondary">
|
<Text type="secondary">读取 order_site 人工订单,客户扫码绑定游戏角色,运营使用斗鱼账号人工兑换。</Text>
|
||||||
读取 order_site 人工订单,客户扫码绑定游戏角色,运营使用斗鱼账号人工兑换。
|
|
||||||
</Text>
|
|
||||||
</div>
|
</div>
|
||||||
<Space wrap>
|
<Space wrap>
|
||||||
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
|
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
|
||||||
@@ -500,21 +417,16 @@ export default function PlatformFulfillmentPage() {
|
|||||||
/>
|
/>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Drawer
|
<Drawer open={Boolean(selectedId)} width={760} title={selected ? `履约详情 · ${selected.platformOrderId}` : '履约详情'} onClose={() => setSelectedId(null)}>
|
||||||
open={Boolean(selectedId)}
|
|
||||||
width={760}
|
|
||||||
title={selected ? `履约详情 · ${selected.platformOrderId}` : '履约详情'}
|
|
||||||
onClose={() => setSelectedId(null)}
|
|
||||||
>
|
|
||||||
{detailLoading || !selected ? (
|
{detailLoading || !selected ? (
|
||||||
<Text type="secondary">加载中...</Text>
|
<Text type="secondary">加载中...</Text>
|
||||||
) : (
|
) : (
|
||||||
<Space direction="vertical" size={16} style={{ width: '100%' }}>
|
<Space direction="vertical" size={16} style={{ width: '100%' }}>
|
||||||
{selected.lastError ? (
|
{selected.lastError ? <Alert type="warning" showIcon message={selected.lastError} /> : null}
|
||||||
<Alert type="warning" showIcon message={selected.lastError} />
|
|
||||||
) : null}
|
|
||||||
<Descriptions bordered size="small" column={2}>
|
<Descriptions bordered size="small" column={2}>
|
||||||
<Descriptions.Item label="商品" span={2}>{selected.skuName}</Descriptions.Item>
|
<Descriptions.Item label="商品" span={2}>
|
||||||
|
{selected.skuName}
|
||||||
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="内部 SKU">{selected.internalSkuKey || '-'}</Descriptions.Item>
|
<Descriptions.Item label="内部 SKU">{selected.internalSkuKey || '-'}</Descriptions.Item>
|
||||||
<Descriptions.Item label="斗鱼商品">{selected.commodityId || '-'}</Descriptions.Item>
|
<Descriptions.Item label="斗鱼商品">{selected.commodityId || '-'}</Descriptions.Item>
|
||||||
<Descriptions.Item label="订单金额">{money(selected.orderAmountFen)}</Descriptions.Item>
|
<Descriptions.Item label="订单金额">{money(selected.orderAmountFen)}</Descriptions.Item>
|
||||||
@@ -522,9 +434,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
<Descriptions.Item label="执行状态">{statusLabel(selected.executionStatus)}</Descriptions.Item>
|
<Descriptions.Item label="执行状态">{statusLabel(selected.executionStatus)}</Descriptions.Item>
|
||||||
<Descriptions.Item label="绑定状态">{selected.bindingStatus}</Descriptions.Item>
|
<Descriptions.Item label="绑定状态">{selected.bindingStatus}</Descriptions.Item>
|
||||||
<Descriptions.Item label="兑换状态">{selected.exchangeStatus}</Descriptions.Item>
|
<Descriptions.Item label="兑换状态">{selected.exchangeStatus}</Descriptions.Item>
|
||||||
<Descriptions.Item label="账号">
|
<Descriptions.Item label="账号">{selected.account?.nickname || selected.account?.username || '-'}</Descriptions.Item>
|
||||||
{selected.account?.nickname || selected.account?.username || '-'}
|
|
||||||
</Descriptions.Item>
|
|
||||||
</Descriptions>
|
</Descriptions>
|
||||||
<Card size="small" title="当前操作">
|
<Card size="small" title="当前操作">
|
||||||
{actionButtons}
|
{actionButtons}
|
||||||
@@ -549,17 +459,10 @@ export default function PlatformFulfillmentPage() {
|
|||||||
)}
|
)}
|
||||||
</Drawer>
|
</Drawer>
|
||||||
|
|
||||||
<Modal
|
<Modal open={qrOpen && Boolean(qrValue)} title="客户扫码绑定游戏角色" footer={null} onCancel={() => setQrOpen(false)}>
|
||||||
open={qrOpen && Boolean(qrValue)}
|
|
||||||
title="客户扫码绑定游戏角色"
|
|
||||||
footer={null}
|
|
||||||
onCancel={() => setQrOpen(false)}
|
|
||||||
>
|
|
||||||
<Space direction="vertical" align="center" style={{ width: '100%' }}>
|
<Space direction="vertical" align="center" style={{ width: '100%' }}>
|
||||||
{qrValue ? <QRCode value={qrValue} size={260} /> : null}
|
{qrValue ? <QRCode value={qrValue} size={260} /> : null}
|
||||||
<Text type="secondary">
|
<Text type="secondary">请客户使用对应游戏平台扫码。二维码只用于当前履约作业。</Text>
|
||||||
请客户使用对应游戏平台扫码。二维码只用于当前履约作业。
|
|
||||||
</Text>
|
|
||||||
<Button
|
<Button
|
||||||
icon={<CopyOutlined />}
|
icon={<CopyOutlined />}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -574,32 +477,28 @@ export default function PlatformFulfillmentPage() {
|
|||||||
</Space>
|
</Space>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
<Modal
|
<Modal open={mappingOpen} title="斗鱼商品映射" width={760} okText="保存映射" onOk={() => void saveMapping()} onCancel={() => setMappingOpen(false)}>
|
||||||
open={mappingOpen}
|
|
||||||
title="斗鱼商品映射"
|
|
||||||
width={760}
|
|
||||||
okText="保存映射"
|
|
||||||
onOk={() => void saveMapping()}
|
|
||||||
onCancel={() => setMappingOpen(false)}
|
|
||||||
>
|
|
||||||
<Space direction="vertical" size={14} style={{ width: '100%' }}>
|
<Space direction="vertical" size={14} style={{ width: '100%' }}>
|
||||||
<Input
|
<Input placeholder="内部 SKU,例如 套装-兔兔白日梦" value={mappingSku} onChange={(event) => setMappingSku(event.target.value)} />
|
||||||
placeholder="内部 SKU,例如 套装-兔兔白日梦"
|
<Space.Compact style={{ width: '100%' }}>
|
||||||
value={mappingSku}
|
<Select
|
||||||
onChange={(event) => setMappingSku(event.target.value)}
|
showSearch
|
||||||
/>
|
optionFilterProp="label"
|
||||||
<Select
|
loading={mappingGoodsLoading}
|
||||||
showSearch
|
placeholder={mappingGoodsLoading ? '正在加载斗鱼活动商品…' : '选择斗鱼精英宝典商品'}
|
||||||
optionFilterProp="label"
|
value={mappingGoodsId || undefined}
|
||||||
placeholder="选择斗鱼精英宝典商品"
|
onChange={selectGoods}
|
||||||
value={mappingGoodsId || undefined}
|
options={goods.map((item) => ({
|
||||||
onChange={selectGoods}
|
value: item.commodity_id,
|
||||||
options={goods.map((item) => ({
|
label: `${item.name || item.commodity_id} · ${item.score ?? '-'} 积分`,
|
||||||
value: item.commodity_id,
|
}))}
|
||||||
label: `${item.name || item.commodity_id} · ${item.score ?? '-'} 积分`,
|
notFoundContent={mappingGoodsLoading ? null : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无活动商品" />}
|
||||||
}))}
|
style={{ flex: 1 }}
|
||||||
style={{ width: '100%' }}
|
/>
|
||||||
/>
|
<Button icon={<ReloadOutlined />} loading={mappingGoodsLoading} onClick={() => void reloadMappingGoods()}>
|
||||||
|
刷新商品
|
||||||
|
</Button>
|
||||||
|
</Space.Compact>
|
||||||
<Space>
|
<Space>
|
||||||
<Text>所需积分</Text>
|
<Text>所需积分</Text>
|
||||||
<InputNumber min={0} value={mappingPoints} onChange={(value) => setMappingPoints(value)} />
|
<InputNumber min={0} value={mappingPoints} onChange={(value) => setMappingPoints(value)} />
|
||||||
@@ -625,11 +524,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
{
|
{
|
||||||
title: '状态',
|
title: '状态',
|
||||||
dataIndex: 'enabled',
|
dataIndex: 'enabled',
|
||||||
render: (value: boolean) => (
|
render: (value: boolean) => <Tag color={value ? 'green' : 'default'}>{value ? '启用' : '停用'}</Tag>,
|
||||||
<Tag color={value ? 'green' : 'default'}>
|
|
||||||
{value ? '启用' : '停用'}
|
|
||||||
</Tag>
|
|
||||||
),
|
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
|
|||||||
Reference in New Issue
Block a user