Compare commits
4
Commits
331208742e
...
2de5d374df
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2de5d374df | ||
|
|
2c87deed78 | ||
|
|
84d7c8e0a4 | ||
|
|
d81f0524a8 |
@@ -57,6 +57,37 @@ if [ "${TYPECHECK:-0}" = "1" ]; then
|
||||
echo "[pre-push] Pyright 通过"
|
||||
fi
|
||||
|
||||
# pytest 跑在真实 MySQL 上;钩子自己确保测试库可用,避免只抛一堆连接错误。
|
||||
ensure_test_mysql() {
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
echo "[pre-push] ❌ 未安装 Docker,无法启动测试 MySQL"
|
||||
return 1
|
||||
fi
|
||||
if ! docker info >/dev/null 2>&1; then
|
||||
echo "[pre-push] ❌ Docker 未运行,请先启动 Docker"
|
||||
return 1
|
||||
fi
|
||||
if docker compose ps -q mysql 2>/dev/null | grep -q .; then
|
||||
echo "[pre-push] 测试 MySQL 已在运行"
|
||||
else
|
||||
echo "[pre-push] 测试 MySQL 未运行,正在启动..."
|
||||
docker compose up -d mysql
|
||||
fi
|
||||
for _ in $(seq 1 30); do
|
||||
if docker compose exec -T mysql sh -c \
|
||||
'mysqladmin ping -h localhost -uroot -p"$MYSQL_ROOT_PASSWORD" --silent' \
|
||||
>/dev/null 2>&1; then
|
||||
echo "[pre-push] 测试 MySQL 已就绪"
|
||||
return 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "[pre-push] ❌ 测试 MySQL 启动超时"
|
||||
return 1
|
||||
}
|
||||
|
||||
ensure_test_mysql
|
||||
|
||||
echo "[pre-push] 运行 pytest..."
|
||||
./dev.sh test -q
|
||||
echo "[pre-push] pytest 通过"
|
||||
|
||||
@@ -19,6 +19,8 @@ class FakeClient:
|
||||
self.points = points
|
||||
self.fish = fish
|
||||
self.records = records if records is not None else []
|
||||
self.records_calls = 0
|
||||
self.orders_calls = 0
|
||||
|
||||
def elite_user_info(self, **_):
|
||||
return {
|
||||
@@ -55,9 +57,11 @@ class FakeClient:
|
||||
}
|
||||
|
||||
def exchange_records(self, **_):
|
||||
self.records_calls += 1
|
||||
return {"records": self.records}
|
||||
|
||||
def exchange_orders(self, **_):
|
||||
self.orders_calls += 1
|
||||
return {"orders": []}
|
||||
|
||||
|
||||
@@ -215,6 +219,96 @@ class TestDouyuCollabOrders:
|
||||
assert result["points_reason"] == "shortage"
|
||||
assert result["order"].status == collab.STATUS_POINTS_ERROR
|
||||
|
||||
def test_balance_query_skips_records_and_never_changes_status(self):
|
||||
order = collab.create_order(
|
||||
self.session,
|
||||
self.admin,
|
||||
order_no="DY-106",
|
||||
shop="店铺A",
|
||||
account_username="douyu-account-a",
|
||||
gift_name="礼包A",
|
||||
required_points=100,
|
||||
home_images=["collab/home-5.png"],
|
||||
client=FakeClient(),
|
||||
)
|
||||
collab.set_status(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
status=collab.STATUS_RECHARGED,
|
||||
reason="鱼翅已充值",
|
||||
)
|
||||
order.points_threshold = 10
|
||||
self.session.commit()
|
||||
client = FakeClient(points=50, records=[{"commodityName": "礼包A"}])
|
||||
|
||||
result = collab.query_activity(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
client=client,
|
||||
source="balance_batch",
|
||||
include_records=False,
|
||||
)
|
||||
|
||||
assert client.records_calls == 0
|
||||
assert client.orders_calls == 0
|
||||
assert result["scope"] == "balances"
|
||||
assert result["verdict"] == collab.VERDICT_UNKNOWN
|
||||
assert result["points_reason"] == "shortage"
|
||||
assert result["order"].status == collab.STATUS_RECHARGED
|
||||
assert result["metric"].source == "balance_batch"
|
||||
assert result["metric"].records_total == 0
|
||||
|
||||
def test_balance_query_keeps_last_exchange_verdict_visible(self):
|
||||
order = collab.create_order(
|
||||
self.session,
|
||||
self.admin,
|
||||
order_no="DY-107",
|
||||
shop="店铺A",
|
||||
account_username="douyu-account-a",
|
||||
gift_name="礼包A",
|
||||
required_points=100,
|
||||
home_images=["collab/home-6.png"],
|
||||
client=FakeClient(),
|
||||
)
|
||||
collab.set_status(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
status=collab.STATUS_RECHARGED,
|
||||
reason="鱼翅已充值",
|
||||
)
|
||||
collab.set_status(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
status=collab.STATUS_SCRIPTED,
|
||||
reason="脚本已上",
|
||||
)
|
||||
record_result = collab.query_activity(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
client=FakeClient(records=[{"commodityName": "礼包A"}]),
|
||||
)
|
||||
assert record_result["order"].status == collab.STATUS_DONE
|
||||
|
||||
collab.query_activity(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
client=FakeClient(),
|
||||
source="balance_batch",
|
||||
include_records=False,
|
||||
)
|
||||
payload = collab.serialize_one(self.session, order)
|
||||
|
||||
assert payload["status"] == collab.STATUS_DONE
|
||||
assert payload["last_verdict"] == collab.VERDICT_SUCCESS
|
||||
assert payload["last_records_matched"] == 1
|
||||
assert payload["last_metric_message"] == "仅查询鱼翅与积分,未查询兑换记录"
|
||||
|
||||
def test_draft_can_be_created_before_account_resolution(self):
|
||||
order = collab.create_order(
|
||||
self.session,
|
||||
@@ -432,6 +526,7 @@ class TestDouyuCollabOrders:
|
||||
assert result["items"][0]["order_no"] == "DY-EXP-1"
|
||||
assert result["items"][0]["ck_text"] == self.account.cookie
|
||||
assert result["items"][0]["account_username"] == self.account.username
|
||||
assert result["items"][0]["account_password"] == "password"
|
||||
assert result["items"][0]["ck_status_label"] == "CK 正常"
|
||||
assert [item["order_no"] for item in result["skipped"]] == [
|
||||
"DY-EXP-2",
|
||||
@@ -497,6 +592,7 @@ class TestDouyuCollabOrders:
|
||||
result = collab_api.copy_external_order_ck(order.id, self.session, self.admin)
|
||||
assert result["exported"] == 1
|
||||
assert result["items"][0]["ck_text"] == self.account.cookie
|
||||
assert result["items"][0]["account_password"] == "password"
|
||||
|
||||
with pytest.raises(collab_api.HTTPException) as excinfo:
|
||||
collab_api.copy_external_order_ck(order.id, self.session, operator)
|
||||
@@ -577,6 +673,10 @@ class TestDouyuCollabOrders:
|
||||
assert "/api/douyu/external-orders/ck/export" in paths
|
||||
assert "/api/douyu/external-orders/{order_id}/ck/copy" in paths
|
||||
assert "/api/douyu/external-orders/usernames/export" in paths
|
||||
assert "/api/douyu/external-orders/balances/query" in paths
|
||||
assert "/api/douyu/external-orders/{order_id}/balances/query" in paths
|
||||
assert "/api/douyu/external-orders/activity/query" in paths
|
||||
assert "/api/douyu/external-orders/{order_id}/activity/query" in paths
|
||||
assert "/api/douyu/collab-shops/{shop_id}" in paths
|
||||
assert "put" in paths["/api/douyu/collab-shops/{shop_id}"]
|
||||
assert "delete" in paths["/api/douyu/collab-shops/{shop_id}"]
|
||||
|
||||
@@ -10,12 +10,22 @@
|
||||
「根本不看记录」。
|
||||
"""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from tests.support.db import get_test_engine, make_test_session
|
||||
from web.backend.models import Account, LoginTask, User
|
||||
from web.backend.routers.cookies import list_cookies
|
||||
from web.backend.routers.douyu import list_task_account_ids, list_task_accounts
|
||||
from web.backend.routers.douyu import (
|
||||
check_task_accounts_ck,
|
||||
list_task_account_ids,
|
||||
list_task_accounts,
|
||||
relogin_invalid_task_accounts,
|
||||
)
|
||||
from web.backend.schemas import CookieReloginRequest
|
||||
from web.backend.services.account_service import cookie_account_ids_query
|
||||
from web.backend.services.douyu_service import (
|
||||
create_douyu_planned_tasks,
|
||||
@@ -175,3 +185,87 @@ class TestDouyuCookieVisibility:
|
||||
assert fresh.cookie == "acf_uid=481802039"
|
||||
assert fresh.ck_check_status == "valid"
|
||||
assert self._task_account_names(self.admin) == {"远行者103", "排队中账号"}
|
||||
|
||||
def test_task_account_payload_contains_ck_status(self):
|
||||
rows = list_task_accounts(
|
||||
search="",
|
||||
tag="",
|
||||
ids="",
|
||||
account_names="",
|
||||
page=None,
|
||||
page_size=50,
|
||||
db=self.session,
|
||||
current=self.admin,
|
||||
)
|
||||
row = next(item for item in rows if item.id == self.relogin_account.id)
|
||||
assert row.ck_check_status == "valid"
|
||||
assert row.ck_checked_at is None
|
||||
|
||||
def test_workbench_ck_check_marks_invalid(self):
|
||||
checked_at = datetime.now(UTC)
|
||||
with patch(
|
||||
"web.backend.routers.cookies.check_douyu_cookie",
|
||||
return_value={
|
||||
"valid": False,
|
||||
"message": "ck expired",
|
||||
"fish_ball": None,
|
||||
"nickname": None,
|
||||
"level": None,
|
||||
"checked_at": checked_at,
|
||||
},
|
||||
):
|
||||
result = check_task_accounts_ck(
|
||||
ids=str(self.relogin_account.id),
|
||||
db=self.session,
|
||||
current=self.admin,
|
||||
)
|
||||
|
||||
assert result["success"] is True
|
||||
assert result["results"] == [
|
||||
{
|
||||
"id": self.relogin_account.id,
|
||||
"valid": False,
|
||||
"checked_at": checked_at.isoformat(),
|
||||
}
|
||||
]
|
||||
self.session.refresh(self.relogin_account)
|
||||
assert self.relogin_account.ck_check_status == "invalid"
|
||||
|
||||
def test_workbench_relogin_invalid_is_admin_only_and_filters_invalid(self):
|
||||
self.relogin_account.ck_check_status = "invalid"
|
||||
self.session.commit()
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def fake_start(accounts, db, current, *, action=""):
|
||||
captured["ids"] = [account.id for account in accounts]
|
||||
captured["action"] = action
|
||||
return {
|
||||
"batch_id": "workbench-relogin",
|
||||
"count": len(accounts),
|
||||
"skipped": 0,
|
||||
"success": True,
|
||||
}
|
||||
|
||||
with patch(
|
||||
"web.backend.routers.cookies._start_relogin_accounts",
|
||||
side_effect=fake_start,
|
||||
):
|
||||
result = relogin_invalid_task_accounts(
|
||||
CookieReloginRequest(
|
||||
ids=[self.relogin_account.id, self.pending_account.id]
|
||||
),
|
||||
db=self.session,
|
||||
current=self.admin,
|
||||
)
|
||||
|
||||
assert result["count"] == 1
|
||||
assert captured["ids"] == [self.relogin_account.id]
|
||||
assert captured["action"] == "douyu:task:relogin_invalid"
|
||||
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
relogin_invalid_task_accounts(
|
||||
CookieReloginRequest(ids=[self.relogin_account.id]),
|
||||
db=self.session,
|
||||
current=self.support,
|
||||
)
|
||||
assert excinfo.value.status_code == 403
|
||||
|
||||
@@ -158,3 +158,10 @@ class TestDouyuWorkbenchScope:
|
||||
delete_account(self.account.id, db=self.session, current=self.user)
|
||||
|
||||
assert self.session.query(DouyuWorkbenchAccount).count() == 0
|
||||
|
||||
def test_workbench_ck_routes_registered(self):
|
||||
from web.backend.main import app
|
||||
|
||||
paths = app.openapi()["paths"]
|
||||
assert "/api/douyu/accounts/ck-check" in paths
|
||||
assert "/api/douyu/accounts/relogin-invalid" in paths
|
||||
|
||||
@@ -41,6 +41,7 @@ from ..models import (
|
||||
)
|
||||
from ..permissions import user_has_permission
|
||||
from ..schemas import (
|
||||
CookieReloginRequest,
|
||||
DouyuConfigOut,
|
||||
DouyuConfigUpdate,
|
||||
DouyuGoodsOut,
|
||||
@@ -333,6 +334,8 @@ def _account_out(account: Account) -> DouyuTaskAccountOut:
|
||||
uid=account.uid or "",
|
||||
nickname=account.nickname or "",
|
||||
tag=account.tag or "",
|
||||
ck_check_status=account.ck_check_status or "",
|
||||
ck_checked_at=account.ck_checked_at,
|
||||
points=account.points,
|
||||
game_name=account.game_name or "",
|
||||
game_channel=account.game_channel or "",
|
||||
@@ -471,6 +474,54 @@ def list_task_account_ids(
|
||||
return {"account_ids": account_ids, "total": len(account_ids)}
|
||||
|
||||
|
||||
@router.post("/accounts/ck-check")
|
||||
def check_task_accounts_ck(
|
||||
ids: str = Query(""),
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("douyu:task")),
|
||||
):
|
||||
"""工作台批量检测 CK,只返回有效性,不暴露 Cookie 原文。
|
||||
|
||||
复用 CK 操作页的检测逻辑:检测结果会写回 ``accounts.ck_check_status``,
|
||||
因此导入账号后刷新列表仍能看到「有效 / 失效」。
|
||||
"""
|
||||
from .cookies import _check_cookies
|
||||
|
||||
return _check_cookies(ids, db, current, detailed=False)
|
||||
|
||||
|
||||
@router.post("/accounts/relogin-invalid")
|
||||
def relogin_invalid_task_accounts(
|
||||
req: CookieReloginRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(get_current_user),
|
||||
):
|
||||
"""重登工作台选中的 CK 失效账号(仅超级管理员)。"""
|
||||
if current.role != "super_admin":
|
||||
raise HTTPException(status_code=403, detail="仅超级管理员可重登失效账号")
|
||||
ids = sorted({int(item) for item in req.ids if int(item) > 0})
|
||||
if not ids:
|
||||
raise HTTPException(status_code=400, detail="请先勾选账号")
|
||||
accounts = (
|
||||
_visible_task_accounts_query(db, current)
|
||||
.filter(
|
||||
Account.id.in_(ids),
|
||||
Account.ck_check_status == "invalid",
|
||||
)
|
||||
.all()
|
||||
)
|
||||
if not accounts:
|
||||
raise HTTPException(status_code=400, detail="选中的账号里没有 CK 失效账号")
|
||||
from .cookies import _start_relogin_accounts
|
||||
|
||||
return _start_relogin_accounts(
|
||||
accounts,
|
||||
db,
|
||||
current,
|
||||
action="douyu:task:relogin_invalid",
|
||||
)
|
||||
|
||||
|
||||
@router.get("/workbench-accounts")
|
||||
def list_workbench_accounts(
|
||||
handbook_scope: str = Query(..., pattern="^(elite|esports|peace)$"),
|
||||
|
||||
@@ -79,6 +79,22 @@ def _publish_change(current: User, *, scope: str, action: str) -> None:
|
||||
collab_events.publish(scope=scope, action=action, actor_id=int(current.id))
|
||||
|
||||
|
||||
def _query_result_out(db: Session, result: dict) -> dict:
|
||||
return {
|
||||
"order": _one(db, result["order"]),
|
||||
"metric": collab.serialize_metric(result["metric"]),
|
||||
"scope": result["scope"],
|
||||
"verdict": result["verdict"],
|
||||
"message": result["message"],
|
||||
"points_reason": result["points_reason"],
|
||||
"fish_fin_balance": result["fish_fin_balance"],
|
||||
"points_balance": result["points_balance"],
|
||||
"required_total": result["required_total"],
|
||||
"surplus": result["surplus"],
|
||||
"errors": result["errors"],
|
||||
}
|
||||
|
||||
|
||||
@router.websocket("/external-orders/ws")
|
||||
async def ws_external_orders(websocket: WebSocket):
|
||||
"""协作台账实时失效通知:前端收到后按自己的筛选静默重拉。"""
|
||||
@@ -400,18 +416,29 @@ def query_external_order_activity(
|
||||
order = collab.get_order(db, order_id)
|
||||
result = collab.query_activity(db, current, order, source="manual")
|
||||
_publish_change(current, scope="orders", action="order.activity")
|
||||
return {
|
||||
"order": _one(db, result["order"]),
|
||||
"metric": collab.serialize_metric(result["metric"]),
|
||||
"verdict": result["verdict"],
|
||||
"message": result["message"],
|
||||
"points_reason": result["points_reason"],
|
||||
"fish_fin_balance": result["fish_fin_balance"],
|
||||
"points_balance": result["points_balance"],
|
||||
"required_total": result["required_total"],
|
||||
"surplus": result["surplus"],
|
||||
"errors": result["errors"],
|
||||
}
|
||||
return _query_result_out(db, result)
|
||||
except collab.CollabError as exc:
|
||||
raise _http_error(exc) from exc
|
||||
|
||||
|
||||
@router.post("/external-orders/{order_id}/balances/query")
|
||||
def query_external_order_balances(
|
||||
order_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("douyu:collab:edit")),
|
||||
):
|
||||
"""只刷新鱼翅和手册积分,不查兑换记录、不判定、不改状态。"""
|
||||
try:
|
||||
order = collab.get_order(db, order_id)
|
||||
result = collab.query_activity(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
source="balance_manual",
|
||||
include_records=False,
|
||||
)
|
||||
_publish_change(current, scope="orders", action="order.balances")
|
||||
return _query_result_out(db, result)
|
||||
except collab.CollabError as exc:
|
||||
raise _http_error(exc) from exc
|
||||
|
||||
@@ -467,6 +494,42 @@ def set_external_order_status_batch(
|
||||
return {"results": results, "success": all(item["success"] for item in results)}
|
||||
|
||||
|
||||
@router.post("/external-orders/balances/query")
|
||||
def query_external_orders_balances(
|
||||
ids: list[int],
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("douyu:collab:edit")),
|
||||
):
|
||||
"""批量刷新鱼翅和手册积分,不查兑换记录、不判定、不改状态。"""
|
||||
results: list[dict] = []
|
||||
for order_id in ids:
|
||||
try:
|
||||
order = collab.get_order(db, order_id)
|
||||
result = collab.query_activity(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
source="balance_batch",
|
||||
include_records=False,
|
||||
)
|
||||
results.append(
|
||||
{
|
||||
"id": order_id,
|
||||
"success": True,
|
||||
"message": result["message"],
|
||||
"fish_fin_balance": result["fish_fin_balance"],
|
||||
"points_balance": result["points_balance"],
|
||||
"points_reason": result["points_reason"],
|
||||
}
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
db.rollback()
|
||||
results.append({"id": order_id, "success": False, "message": str(exc)})
|
||||
if any(item["success"] for item in results):
|
||||
_publish_change(current, scope="orders", action="order.balances_batch")
|
||||
return {"results": results, "success": all(item["success"] for item in results)}
|
||||
|
||||
|
||||
@router.post("/external-orders/activity/query")
|
||||
def query_external_orders_activity(
|
||||
ids: list[int],
|
||||
|
||||
@@ -1025,6 +1025,8 @@ class DouyuTaskAccountOut(BaseModel):
|
||||
uid: str = ""
|
||||
nickname: str = ""
|
||||
tag: str = ""
|
||||
ck_check_status: str = ""
|
||||
ck_checked_at: datetime | None = None
|
||||
points: int | None = None
|
||||
game_name: str = ""
|
||||
game_channel: str = ""
|
||||
@@ -1883,6 +1885,7 @@ class DouyuCollabCkExportItemOut(BaseModel):
|
||||
order_no: str = ""
|
||||
account_id: int | None = None
|
||||
account_username: str = ""
|
||||
account_password: str = ""
|
||||
account_nickname: str = ""
|
||||
status: str = ""
|
||||
status_label: str = ""
|
||||
|
||||
@@ -1042,9 +1042,10 @@ def query_activity(
|
||||
*,
|
||||
client: Any | None = None,
|
||||
source: str = "manual",
|
||||
include_records: bool = True,
|
||||
commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""查询鱼翅、积分和当前账号兑换记录,落一条快照。"""
|
||||
"""查询鱼翅、积分;``include_records`` 时同时查兑换记录并判定。"""
|
||||
account = account_by_id(db, order.account_id) or account_by_username(
|
||||
db, order.account_username
|
||||
)
|
||||
@@ -1067,24 +1068,25 @@ def query_activity(
|
||||
gold = active_client.gold_account()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"鱼翅: {exc}")
|
||||
try:
|
||||
records = (
|
||||
active_client.exchange_records(
|
||||
manual_id=str(config.manual_id or ""), limit=100, offset=0
|
||||
).get("records")
|
||||
or []
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"兑换记录: {exc}")
|
||||
try:
|
||||
orders = (
|
||||
active_client.exchange_orders(
|
||||
manual_id=str(config.manual_id or ""), page=1, page_size=10
|
||||
).get("orders")
|
||||
or []
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"锁单: {exc}")
|
||||
if include_records:
|
||||
try:
|
||||
records = (
|
||||
active_client.exchange_records(
|
||||
manual_id=str(config.manual_id or ""), limit=100, offset=0
|
||||
).get("records")
|
||||
or []
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"兑换记录: {exc}")
|
||||
try:
|
||||
orders = (
|
||||
active_client.exchange_orders(
|
||||
manual_id=str(config.manual_id or ""), page=1, page_size=10
|
||||
).get("orders")
|
||||
or []
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"锁单: {exc}")
|
||||
|
||||
manual_score = _to_int(elite.get("manual_score"))
|
||||
fish = _to_int(gold.get("gold"))
|
||||
@@ -1107,7 +1109,11 @@ def query_activity(
|
||||
threshold = normalize_threshold(order.points_threshold)
|
||||
order.points_threshold = threshold
|
||||
|
||||
if errors:
|
||||
matched = 0
|
||||
if not include_records:
|
||||
verdict = VERDICT_UNKNOWN
|
||||
message = ";".join(errors) if errors else "仅查询鱼翅与积分,未查询兑换记录"
|
||||
elif errors:
|
||||
verdict = VERDICT_UNKNOWN
|
||||
message = ";".join(errors)
|
||||
elif not order.gift_name:
|
||||
@@ -1160,7 +1166,7 @@ def query_activity(
|
||||
points_required_total=required_total,
|
||||
points_surplus=surplus,
|
||||
records_total=len(records),
|
||||
records_matched=_match_gift(records, order.gift_name),
|
||||
records_matched=matched,
|
||||
verdict=verdict,
|
||||
message=message,
|
||||
source=_text(source, max_length=16) or "manual",
|
||||
@@ -1183,6 +1189,7 @@ def query_activity(
|
||||
action="douyu:collab:activity",
|
||||
target=_status_audit_target(order),
|
||||
detail={
|
||||
"scope": "activity" if include_records else "balances",
|
||||
"verdict": verdict,
|
||||
"message": message,
|
||||
"fish_fin_balance": fish,
|
||||
@@ -1193,40 +1200,41 @@ def query_activity(
|
||||
},
|
||||
)
|
||||
|
||||
# 已上脚本的单,兑换记录命中/未命中是业务事实;其它状态只记快照。
|
||||
if order.status == STATUS_SCRIPTED and verdict == VERDICT_SUCCESS:
|
||||
set_status(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
status=STATUS_DONE,
|
||||
reason=message,
|
||||
expected_version=None,
|
||||
commit=False,
|
||||
)
|
||||
elif order.status == STATUS_SCRIPTED and verdict == VERDICT_FAILED:
|
||||
set_status(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
status=STATUS_FAILED,
|
||||
reason=message,
|
||||
expected_version=None,
|
||||
commit=False,
|
||||
)
|
||||
elif order.status in (STATUS_RECHARGED, STATUS_SCRIPTED) and reason in (
|
||||
"shortage",
|
||||
"excess",
|
||||
):
|
||||
set_status(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
status=STATUS_POINTS_ERROR,
|
||||
reason=points_message,
|
||||
expected_version=None,
|
||||
commit=False,
|
||||
)
|
||||
# 只有查兑换记录时才做业务判定;余额查询保持只读,不动状态。
|
||||
if include_records:
|
||||
if order.status == STATUS_SCRIPTED and verdict == VERDICT_SUCCESS:
|
||||
set_status(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
status=STATUS_DONE,
|
||||
reason=message,
|
||||
expected_version=None,
|
||||
commit=False,
|
||||
)
|
||||
elif order.status == STATUS_SCRIPTED and verdict == VERDICT_FAILED:
|
||||
set_status(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
status=STATUS_FAILED,
|
||||
reason=message,
|
||||
expected_version=None,
|
||||
commit=False,
|
||||
)
|
||||
elif order.status in (STATUS_RECHARGED, STATUS_SCRIPTED) and reason in (
|
||||
"shortage",
|
||||
"excess",
|
||||
):
|
||||
set_status(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
status=STATUS_POINTS_ERROR,
|
||||
reason=points_message,
|
||||
expected_version=None,
|
||||
commit=False,
|
||||
)
|
||||
|
||||
if commit:
|
||||
db.commit()
|
||||
@@ -1235,6 +1243,7 @@ def query_activity(
|
||||
return {
|
||||
"order": order,
|
||||
"metric": metric,
|
||||
"scope": "activity" if include_records else "balances",
|
||||
"verdict": verdict,
|
||||
"message": message,
|
||||
"points_reason": reason,
|
||||
@@ -1487,9 +1496,14 @@ def serialized_goods(db: Session) -> list[dict[str, Any]]:
|
||||
|
||||
def _metric_views(
|
||||
db: Session, order_ids: list[int]
|
||||
) -> dict[int, DouyuExternalOrderMetric]:
|
||||
) -> tuple[dict[int, DouyuExternalOrderMetric], dict[int, DouyuExternalOrderMetric]]:
|
||||
"""返回最近一条快照,以及最近一条带兑换判定的快照。
|
||||
|
||||
余额查询也会落快照,但它的 verdict 是 unknown;列表上的兑换结论应沿用
|
||||
最近一次「查兑换记录」的结果,不能被余额刷新覆盖。
|
||||
"""
|
||||
if not order_ids:
|
||||
return {}
|
||||
return {}, {}
|
||||
rows = (
|
||||
db.query(DouyuExternalOrderMetric)
|
||||
.filter(DouyuExternalOrderMetric.order_id.in_(order_ids))
|
||||
@@ -1499,10 +1513,14 @@ def _metric_views(
|
||||
)
|
||||
.all()
|
||||
)
|
||||
result: dict[int, DouyuExternalOrderMetric] = {}
|
||||
latest: dict[int, DouyuExternalOrderMetric] = {}
|
||||
verdict_latest: dict[int, DouyuExternalOrderMetric] = {}
|
||||
for row in rows:
|
||||
result.setdefault(int(row.order_id), row)
|
||||
return result
|
||||
order_id = int(row.order_id)
|
||||
latest.setdefault(order_id, row)
|
||||
if not str(row.source or "").startswith("balance"):
|
||||
verdict_latest.setdefault(order_id, row)
|
||||
return latest, verdict_latest
|
||||
|
||||
|
||||
def account_clusters(
|
||||
@@ -1556,6 +1574,7 @@ def serialize_order(
|
||||
accounts: Mapping[int, Account] | None = None,
|
||||
cluster: Mapping[str, Any] | None = None,
|
||||
metric: DouyuExternalOrderMetric | None = None,
|
||||
verdict_metric: DouyuExternalOrderMetric | None = None,
|
||||
) -> dict[str, Any]:
|
||||
users = users or {}
|
||||
accounts = accounts or {}
|
||||
@@ -1630,16 +1649,16 @@ def serialize_order(
|
||||
"account_cluster": dict(cluster) if cluster else None,
|
||||
"last_metric_at": metric.created_at if metric else None,
|
||||
"last_metric_message": metric.message if metric else "",
|
||||
"last_verdict": metric.verdict if metric else "",
|
||||
"last_verdict": verdict_metric.verdict if verdict_metric else "",
|
||||
"last_verdict_label": {
|
||||
VERDICT_SUCCESS: "兑换成功",
|
||||
VERDICT_FAILED: "兑换失败",
|
||||
VERDICT_UNKNOWN: "无法判定",
|
||||
}.get(metric.verdict, "")
|
||||
if metric
|
||||
}.get(verdict_metric.verdict, "")
|
||||
if verdict_metric
|
||||
else "",
|
||||
"last_records_total": metric.records_total if metric else 0,
|
||||
"last_records_matched": metric.records_matched if metric else 0,
|
||||
"last_records_total": verdict_metric.records_total if verdict_metric else 0,
|
||||
"last_records_matched": verdict_metric.records_matched if verdict_metric else 0,
|
||||
}
|
||||
return payload
|
||||
|
||||
@@ -1761,7 +1780,7 @@ def list_orders(
|
||||
db, {int(order.account_id) for order in orders if order.account_id}
|
||||
)
|
||||
clusters = account_clusters(db, orders)
|
||||
metrics = _metric_views(db, [int(order.id) for order in orders])
|
||||
metrics, verdict_metrics = _metric_views(db, [int(order.id) for order in orders])
|
||||
items = [
|
||||
serialize_order(
|
||||
order,
|
||||
@@ -1769,6 +1788,7 @@ def list_orders(
|
||||
accounts=accounts,
|
||||
cluster=clusters.get(int(order.account_id)) if order.account_id else None,
|
||||
metric=metrics.get(int(order.id)),
|
||||
verdict_metric=verdict_metrics.get(int(order.id)),
|
||||
)
|
||||
for order in orders
|
||||
]
|
||||
@@ -1802,13 +1822,14 @@ def serialize_one(db: Session, order: DouyuExternalOrder) -> dict[str, Any]:
|
||||
db, {int(order.account_id)} if order.account_id else set()
|
||||
)
|
||||
clusters = account_clusters(db, [order])
|
||||
metrics = _metric_views(db, [int(order.id)])
|
||||
metrics, verdict_metrics = _metric_views(db, [int(order.id)])
|
||||
return serialize_order(
|
||||
order,
|
||||
users=users,
|
||||
accounts=accounts,
|
||||
cluster=clusters.get(int(order.account_id)) if order.account_id else None,
|
||||
metric=metrics.get(int(order.id)),
|
||||
verdict_metric=verdict_metrics.get(int(order.id)),
|
||||
)
|
||||
|
||||
|
||||
@@ -2057,6 +2078,7 @@ def export_cks(
|
||||
"order_no": order.order_no,
|
||||
"account_id": int(account.id),
|
||||
"account_username": account.username or order.account_username or "",
|
||||
"account_password": str(account.password or ""),
|
||||
"account_nickname": account.nickname or order.account_nickname or "",
|
||||
"status": order.status,
|
||||
"status_label": ORDER_STATUS_LABELS.get(order.status, order.status),
|
||||
|
||||
@@ -19,8 +19,18 @@ export const douyuApi = {
|
||||
api.get<DouyuTaskAccountItem[], DouyuTaskAccountItem[]>('/douyu/accounts', { params }),
|
||||
listAccountsPaged: (params: PageParams & { ids?: string; tag?: string }) =>
|
||||
api.get<PaginatedResponse<DouyuTaskAccountItem>, PaginatedResponse<DouyuTaskAccountItem>>('/douyu/accounts', { params }),
|
||||
listAccountIds: (params?: { search?: string; tag?: string; account_names?: string }) =>
|
||||
listAccountIds: (params: { search?: string; tag?: string; account_names?: string } = {}) =>
|
||||
api.get<{ account_ids: number[]; total: number }, { account_ids: number[]; total: number }>('/douyu/accounts/ids', { params }),
|
||||
checkAccountsCk: (ids: number[]) =>
|
||||
api.post<
|
||||
{ results: Array<{ id: number; valid: boolean; checked_at: string }>; success: boolean },
|
||||
{ results: Array<{ id: number; valid: boolean; checked_at: string }>; success: boolean }
|
||||
>('/douyu/accounts/ck-check', null, { params: { ids: ids.join(',') } }),
|
||||
reloginInvalidAccounts: (ids: number[]) =>
|
||||
api.post<
|
||||
{ batch_id: string; count: number; skipped: number; success: boolean },
|
||||
{ batch_id: string; count: number; skipped: number; success: boolean }
|
||||
>('/douyu/accounts/relogin-invalid', { ids }),
|
||||
getConfig: () => api.get<DouyuConfig, DouyuConfig>('/douyu/config'),
|
||||
getRechargeChannel: () => api.get<DouyuRechargeChannel, DouyuRechargeChannel>('/douyu/recharge-channel'),
|
||||
updateConfig: (data: Partial<DouyuConfig>) => api.put<DouyuConfig, DouyuConfig>('/douyu/config', data),
|
||||
|
||||
@@ -109,6 +109,7 @@ export interface DouyuCollabCkExportItem {
|
||||
order_no: string;
|
||||
account_id: number | null;
|
||||
account_username: string;
|
||||
account_password: string;
|
||||
account_nickname: string;
|
||||
status: DouyuCollabStatus;
|
||||
status_label: string;
|
||||
@@ -259,6 +260,7 @@ export interface DouyuCollabTimeline {
|
||||
export interface DouyuCollabQueryResult {
|
||||
order: DouyuCollabOrder;
|
||||
metric: DouyuCollabMetric;
|
||||
scope: 'activity' | 'balances';
|
||||
verdict: string;
|
||||
message: string;
|
||||
points_reason: string;
|
||||
@@ -346,9 +348,13 @@ export const douyuCollabApi = {
|
||||
{ results: Array<{ id: number; success: boolean; ck_status?: string; role?: string; message?: string }>; success: boolean },
|
||||
{ results: Array<{ id: number; success: boolean; ck_status?: string; role?: string; message?: string }>; success: boolean }
|
||||
>('/douyu/external-orders/verify/batch', ids),
|
||||
queryActivity: (id: number) =>
|
||||
queryActivity: (id: number) => api.post<DouyuCollabQueryResult, DouyuCollabQueryResult>(
|
||||
`/douyu/external-orders/${id}/activity/query`,
|
||||
),
|
||||
/** 只刷新鱼翅与手册积分,不查兑换记录、不判定、不改状态 */
|
||||
queryBalances: (id: number) =>
|
||||
api.post<DouyuCollabQueryResult, DouyuCollabQueryResult>(
|
||||
`/douyu/external-orders/${id}/activity/query`,
|
||||
`/douyu/external-orders/${id}/balances/query`,
|
||||
),
|
||||
setStatus: (id: number, data: {
|
||||
status: DouyuCollabStatus;
|
||||
@@ -370,6 +376,12 @@ export const douyuCollabApi = {
|
||||
'/douyu/external-orders/activity/query',
|
||||
ids,
|
||||
),
|
||||
/** 批量只刷新鱼翅/积分,不查兑换记录、不判定、不改状态 */
|
||||
batchBalances: (ids: number[]) =>
|
||||
api.post<{ results: Array<Record<string, unknown>>; success: boolean }, { results: Array<Record<string, unknown>>; success: boolean }>(
|
||||
'/douyu/external-orders/balances/query',
|
||||
ids,
|
||||
),
|
||||
updateImages: (id: number, home_images: string[], expected_version?: number) =>
|
||||
api.post<DouyuCollabOrder, DouyuCollabOrder>(`/douyu/external-orders/${id}/images`, {
|
||||
home_images,
|
||||
|
||||
@@ -613,6 +613,8 @@ export interface DouyuTaskAccountItem {
|
||||
uid: string;
|
||||
nickname: string;
|
||||
tag: string;
|
||||
ck_check_status: string;
|
||||
ck_checked_at: string | null;
|
||||
points: number | null;
|
||||
game_name: string;
|
||||
game_channel: string;
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Radio,
|
||||
Row,
|
||||
Select,
|
||||
Space,
|
||||
@@ -39,6 +38,7 @@ import {
|
||||
PlusOutlined,
|
||||
ReloadOutlined,
|
||||
SafetyCertificateOutlined,
|
||||
SearchOutlined,
|
||||
ShopOutlined,
|
||||
SyncOutlined,
|
||||
TagOutlined,
|
||||
@@ -215,6 +215,8 @@ export default function DouyuCollabPage() {
|
||||
const [gifts, setGifts] = useState<string[]>([]);
|
||||
const [goods, setGoods] = useState<DouyuCollabGoods[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [balanceQuerying, setBalanceQuerying] = useState(false);
|
||||
const [recordQuerying, setRecordQuerying] = useState(false);
|
||||
const [goodsLoading, setGoodsLoading] = useState(false);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
@@ -258,7 +260,6 @@ export default function DouyuCollabPage() {
|
||||
const [ckExporting, setCkExporting] = useState(false);
|
||||
const [ckCopyingId, setCkCopyingId] = useState<number | null>(null);
|
||||
const [ckExport, setCkExport] = useState<DouyuCollabCkExportResult | null>(null);
|
||||
const [ckExportFormat, setCkExportFormat] = useState<'plain' | 'with_order'>('plain');
|
||||
|
||||
// 批量导出斗鱼用户名:只读列表数据,不含 CK
|
||||
const [usernameExportOpen, setUsernameExportOpen] = useState(false);
|
||||
@@ -434,15 +435,13 @@ export default function DouyuCollabPage() {
|
||||
selectedOrders.length === selectedIds.length &&
|
||||
selectedOrders.every((row) => row.status === 'done' && !row.is_archived);
|
||||
|
||||
/** 导出文本:默认每行一份纯 CK,也可以带订单号方便多选对号。 */
|
||||
/** 与「CK 管理」保持一致:账号----密码----CK,每行一条。 */
|
||||
const ckExportText = useMemo(() => {
|
||||
if (!ckExport) return '';
|
||||
return ckExport.items
|
||||
.map((item) =>
|
||||
ckExportFormat === 'with_order' ? `${item.order_no}\t${item.ck_text}` : item.ck_text,
|
||||
)
|
||||
.join('\n');
|
||||
}, [ckExport, ckExportFormat]);
|
||||
.map((item) => `${item.account_username}----${item.account_password || ''}----${item.ck_text}`)
|
||||
.join('\r\n');
|
||||
}, [ckExport]);
|
||||
|
||||
const ckExportRisky = useMemo(
|
||||
() => (ckExport?.items ?? []).filter((item) => item.ck_status === 'invalid'),
|
||||
@@ -635,18 +634,35 @@ export default function DouyuCollabPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const queryOrder = async (order: DouyuCollabOrder) => {
|
||||
const queryOneBalances = async (order: DouyuCollabOrder) => {
|
||||
try {
|
||||
message.loading({ content: '正在查询鱼翅、积分与兑换记录…', key: 'dy-collab-query' });
|
||||
const result = await douyuCollabApi.queryActivity(order.id);
|
||||
message.loading({ content: '正在查询鱼翅、积分…', key: 'dy-collab-balance' });
|
||||
const result = await douyuCollabApi.queryBalances(order.id);
|
||||
message.success({
|
||||
content: `${result.message}${result.points_reason ? `;${pointsReasonMeta(result.points_reason).label}` : ''}`,
|
||||
key: 'dy-collab-query',
|
||||
content: `鱼翅 ${result.fish_fin_balance ?? '-'} / 积分 ${result.points_balance ?? '-'}${
|
||||
result.points_reason ? `;${pointsReasonMeta(result.points_reason).label}` : ''
|
||||
}`,
|
||||
key: 'dy-collab-balance',
|
||||
});
|
||||
refreshAll();
|
||||
if (detail?.id === order.id) void openDetail(order);
|
||||
} catch (error) {
|
||||
message.error({ content: getErrorMessage(error), key: 'dy-collab-query' });
|
||||
message.error({ content: getErrorMessage(error), key: 'dy-collab-balance' });
|
||||
}
|
||||
};
|
||||
|
||||
const queryOneRecords = async (order: DouyuCollabOrder) => {
|
||||
try {
|
||||
message.loading({ content: '正在查询兑换记录…', key: 'dy-collab-records' });
|
||||
const result = await douyuCollabApi.queryActivity(order.id);
|
||||
message.success({
|
||||
content: `${result.message}${result.points_reason ? `;${pointsReasonMeta(result.points_reason).label}` : ''}`,
|
||||
key: 'dy-collab-records',
|
||||
});
|
||||
refreshAll();
|
||||
if (detail?.id === order.id) void openDetail(order);
|
||||
} catch (error) {
|
||||
message.error({ content: getErrorMessage(error), key: 'dy-collab-records' });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -720,21 +736,39 @@ export default function DouyuCollabPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const batchQuery = async () => {
|
||||
const batchQueryBalances = async () => {
|
||||
if (selectedIds.length === 0) {
|
||||
message.warning('请先勾选协作单');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setBalanceQuerying(true);
|
||||
try {
|
||||
const result = await douyuCollabApi.batchActivity(selectedIds);
|
||||
const result = await douyuCollabApi.batchBalances(selectedIds);
|
||||
const ok = result.results.filter((item) => item.success).length;
|
||||
message.success(`查询完成:${ok}/${result.results.length}`);
|
||||
message.success(`鱼翅/积分查询完成:${ok}/${result.results.length}`);
|
||||
refreshAll();
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setBalanceQuerying(false);
|
||||
}
|
||||
};
|
||||
|
||||
const batchQueryRecords = async () => {
|
||||
if (selectedIds.length === 0) {
|
||||
message.warning('请先勾选协作单');
|
||||
return;
|
||||
}
|
||||
setRecordQuerying(true);
|
||||
try {
|
||||
const result = await douyuCollabApi.batchActivity(selectedIds);
|
||||
const ok = result.results.filter((item) => item.success).length;
|
||||
message.success(`兑换记录查询完成:${ok}/${result.results.length}`);
|
||||
refreshAll();
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setRecordQuerying(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -801,8 +835,10 @@ export default function DouyuCollabPage() {
|
||||
message.warning(result.skipped[0]?.reason || '这行还没有可复制的 CK');
|
||||
return;
|
||||
}
|
||||
await copyTextToClipboard(item.ck_text);
|
||||
message.success(`已复制 ${row.order_no} 的 CK`);
|
||||
await copyTextToClipboard(
|
||||
`${item.account_username}----${item.account_password || ''}----${item.ck_text}`,
|
||||
);
|
||||
message.success(`已复制 ${row.order_no} 的账号密码与 CK`);
|
||||
} catch (error) {
|
||||
message.error(`复制失败:${getErrorMessage(error)}`);
|
||||
} finally {
|
||||
@@ -1160,7 +1196,7 @@ export default function DouyuCollabPage() {
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 400,
|
||||
width: 500,
|
||||
fixed: 'right',
|
||||
align: 'center',
|
||||
render: (_, row) => (
|
||||
@@ -1198,9 +1234,16 @@ export default function DouyuCollabPage() {
|
||||
校验
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Button size="small" icon={<SyncOutlined />} onClick={() => void queryOrder(row)}>
|
||||
查询
|
||||
</Button>
|
||||
<Tooltip title="只刷新鱼翅与手册积分,不查兑换记录,也不会改状态">
|
||||
<Button size="small" icon={<SyncOutlined />} onClick={() => void queryOneBalances(row)}>
|
||||
查鱼翅/积分
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Tooltip title="查询当前账号兑换记录,命中礼包名后自动推进订单状态">
|
||||
<Button size="small" icon={<SearchOutlined />} onClick={() => void queryOneRecords(row)}>
|
||||
查兑换记录
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Dropdown
|
||||
menu={{
|
||||
items: [
|
||||
@@ -1503,13 +1546,26 @@ export default function DouyuCollabPage() {
|
||||
<Button icon={<CheckCircleOutlined />} disabled={selectedCount === 0} onClick={openBatchStatus}>
|
||||
批量改状态{selectedCount > 0 ? `(${selectedCount})` : ''}
|
||||
</Button>
|
||||
<Button
|
||||
icon={<SyncOutlined />}
|
||||
disabled={selectedCount === 0 || loading}
|
||||
onClick={() => void batchQuery()}
|
||||
>
|
||||
批量查鱼翅/积分{selectedCount > 0 ? `(${selectedCount})` : ''}
|
||||
</Button>
|
||||
<Tooltip title="只刷新鱼翅与手册积分,不查兑换记录,也不会改状态">
|
||||
<Button
|
||||
icon={<SyncOutlined />}
|
||||
disabled={selectedCount === 0 || loading || balanceQuerying}
|
||||
loading={balanceQuerying}
|
||||
onClick={() => void batchQueryBalances()}
|
||||
>
|
||||
批量查鱼翅/积分{selectedCount > 0 ? `(${selectedCount})` : ''}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Tooltip title="查询勾选订单的兑换记录;命中礼包名后自动改状态,积分短缺/超额也会标记">
|
||||
<Button
|
||||
icon={<SearchOutlined />}
|
||||
disabled={selectedCount === 0 || loading || recordQuerying}
|
||||
loading={recordQuerying}
|
||||
onClick={() => void batchQueryRecords()}
|
||||
>
|
||||
批量查兑换记录{selectedCount > 0 ? `(${selectedCount})` : ''}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Button
|
||||
icon={<InboxOutlined />}
|
||||
disabled={!canArchiveSelected || loading}
|
||||
@@ -1554,7 +1610,7 @@ export default function DouyuCollabPage() {
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={orders}
|
||||
scroll={{ x: 2090 }}
|
||||
scroll={{ x: 2190 }}
|
||||
rowSelection={{
|
||||
selectedRowKeys,
|
||||
onChange: (keys) => setSelectedRowKeys(keys),
|
||||
@@ -1878,8 +1934,8 @@ export default function DouyuCollabPage() {
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
message="CK 是账号凭据"
|
||||
description="斗鱼协作单不存 CK,这里导出的是关联内部账号当前的 cookie。复制后请勿发群 / 截图外传;每次导出都会写审计(谁、什么时候、导出了哪几单),审计里不存 CK 本体。"
|
||||
message="账号、密码、CK 都是凭据"
|
||||
description="格式与「CK 管理」一致:账号----密码----CK,每行一条。斗鱼协作单不存 CK,这里导出的是关联内部账号当前的 CK。复制后请勿发群 / 截图外传;每次导出都会写审计,审计里不存凭据本体。"
|
||||
/>
|
||||
{ckExport && ckExport.skipped.length > 0 && (
|
||||
<Text type="warning" style={{ fontSize: 12 }}>
|
||||
@@ -1899,13 +1955,6 @@ export default function DouyuCollabPage() {
|
||||
.join(';')}
|
||||
</Text>
|
||||
)}
|
||||
<Radio.Group
|
||||
value={ckExportFormat}
|
||||
onChange={(event) => setCkExportFormat(event.target.value)}
|
||||
>
|
||||
<Radio value="plain">每行一份纯 CK(直接粘)</Radio>
|
||||
<Radio value="with_order">订单号 + Tab + CK(多选时好对号)</Radio>
|
||||
</Radio.Group>
|
||||
<Input.TextArea
|
||||
rows={10}
|
||||
value={ckExportText}
|
||||
@@ -1918,7 +1967,7 @@ export default function DouyuCollabPage() {
|
||||
/>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
共 {ckExport?.exported ?? 0} 份 · {ckExportText.length} 字符;
|
||||
关掉这个弹窗就清掉,不会留在页面上。
|
||||
每行格式:账号----密码----CK;关掉这个弹窗就清掉,不会留在页面上。
|
||||
</Text>
|
||||
</Space>
|
||||
</Modal>
|
||||
@@ -1942,9 +1991,12 @@ export default function DouyuCollabPage() {
|
||||
<Button icon={<SafetyCertificateOutlined />} onClick={() => void verifyOrder(detail)}>
|
||||
校验
|
||||
</Button>
|
||||
<Button icon={<SyncOutlined />} onClick={() => void queryOrder(detail)}>
|
||||
<Button icon={<SyncOutlined />} onClick={() => void queryOneBalances(detail)}>
|
||||
查鱼翅/积分
|
||||
</Button>
|
||||
<Button icon={<SearchOutlined />} onClick={() => void queryOneRecords(detail)}>
|
||||
查兑换记录
|
||||
</Button>
|
||||
</Space>
|
||||
) : undefined
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
import type { TableProps } from 'antd';
|
||||
import {
|
||||
CheckCircleOutlined, ColumnWidthOutlined, CopyOutlined, CreditCardOutlined, ExclamationCircleOutlined, FieldTimeOutlined, FilterOutlined, GiftOutlined,
|
||||
ImportOutlined, QrcodeOutlined, ReloadOutlined,
|
||||
ImportOutlined, LoadingOutlined, QrcodeOutlined, ReloadOutlined,
|
||||
SearchOutlined, SettingOutlined, ShoppingOutlined, StopOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
@@ -87,7 +87,8 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
const isEsportsHandbook = handbook === 'esports';
|
||||
const isEliteHandbook = handbook === 'elite';
|
||||
const { title: handbookTitle, description: handbookDescription, taskTypes: activeTaskTypes, quickActions } = HANDBOOK_META[handbook];
|
||||
const { can } = usePermissions();
|
||||
const { can, user } = usePermissions();
|
||||
const isAdmin = user?.role === 'super_admin';
|
||||
const { token } = theme.useToken();
|
||||
const [accounts, setAccounts] = useState<DouyuTaskAccountItem[]>([]);
|
||||
// 工作台账号归属由服务端按用户保存;localStorage 仅用于首次升级迁移旧浏览器数据。
|
||||
@@ -120,6 +121,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
});
|
||||
const [accountPage, setAccountPage] = useState(1);
|
||||
const [accountTotal, setAccountTotal] = useState(0);
|
||||
const [ckCheckingIds, setCkCheckingIds] = useState<Set<number>>(new Set());
|
||||
const tasksLoadingRef = useRef(false);
|
||||
|
||||
const [importOpen, setImportOpen] = useState(false);
|
||||
@@ -814,6 +816,39 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
return saved.account_ids;
|
||||
};
|
||||
|
||||
const checkWorkbenchCk = async (ids: number[]) => {
|
||||
if (ids.length === 0) return;
|
||||
setCkCheckingIds((previous) => new Set([...previous, ...ids]));
|
||||
message.info(`正在检测 ${ids.length} 个账号的 CK...`);
|
||||
try {
|
||||
const result = await douyuApi.checkAccountsCk(ids);
|
||||
const byId = new Map(result.results.map((item) => [item.id, item]));
|
||||
setAccounts((previous) => previous.map((account) => {
|
||||
const checked = byId.get(account.id);
|
||||
if (!checked) return account;
|
||||
return {
|
||||
...account,
|
||||
ck_check_status: checked.valid ? 'valid' : 'invalid',
|
||||
ck_checked_at: checked.checked_at,
|
||||
};
|
||||
}));
|
||||
const invalid = result.results.filter((item) => !item.valid).length;
|
||||
if (invalid > 0) {
|
||||
message.warning(`CK 检测完成:${invalid} 个账号 CK 失效`);
|
||||
} else {
|
||||
message.success(`CK 检测完成:${result.results.length} 个账号全部有效`);
|
||||
}
|
||||
} catch (error) {
|
||||
message.error(`CK 检测失败:${getErrorMessage(error)}`);
|
||||
} finally {
|
||||
setCkCheckingIds((previous) => {
|
||||
const next = new Set(previous);
|
||||
ids.forEach((id) => next.delete(id));
|
||||
return next;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const importAccounts = async (ids: number[]) => {
|
||||
const toImport = importPool.filter((a) => ids.includes(a.id));
|
||||
const nextIds = [...new Set([...workbenchIds, ...toImport.map((a) => a.id)])];
|
||||
@@ -830,6 +865,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
setImportSelectedIds([]);
|
||||
closeImportModal();
|
||||
message.success(`已导入 ${toImport.length} 个账号`);
|
||||
void checkWorkbenchCk(toImport.map((a) => a.id));
|
||||
};
|
||||
|
||||
const closeImportModal = () => {
|
||||
@@ -873,6 +909,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
await saveWorkbenchIds([...new Set([...workbenchIds, ...imported])]);
|
||||
closeImportModal();
|
||||
message.success(`已一键导入 ${imported.length} 个账号`);
|
||||
void checkWorkbenchCk(imported);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
@@ -893,6 +930,30 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
message.success(`已移出 ${sel.size} 个账号`);
|
||||
};
|
||||
|
||||
const reloginInvalidSelected = () => {
|
||||
if (selectedIds.length === 0) {
|
||||
message.warning('请先勾选账号');
|
||||
return;
|
||||
}
|
||||
Modal.confirm({
|
||||
title: `重登选中的 ${selectedIds.length} 个账号中的失效 CK?`,
|
||||
content: '只会处理 CK 已失效的账号;新登录成功后才替换旧 CK,失败的账号会保留原 CK。',
|
||||
okText: '开始重登',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
try {
|
||||
const result = await douyuApi.reloginInvalidAccounts(selectedIds);
|
||||
const skipped = result.skipped ? `,${result.skipped} 个因缺少登录凭据跳过` : '';
|
||||
message.success(`已开始重登 ${result.count} 个失效账号${skipped}`);
|
||||
setSelectedIds([]);
|
||||
window.setTimeout(() => void loadData(), 2000);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// ---- Context menu ----
|
||||
const [contextMenu, setContextMenu] = useState<{
|
||||
accountIds: number[]; x: number; y: number;
|
||||
@@ -1142,6 +1203,29 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'CK状态', width: 100, align: 'center',
|
||||
render: (_, record) => {
|
||||
if (ckCheckingIds.has(record.id)) {
|
||||
return <Tag color="processing" icon={<LoadingOutlined />}>检测中</Tag>;
|
||||
}
|
||||
if (record.ck_check_status === 'valid') {
|
||||
return (
|
||||
<Tooltip title={record.ck_checked_at ? `检测时间:${formatTime(record.ck_checked_at)}` : undefined}>
|
||||
<Tag color="success">有效</Tag>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
if (record.ck_check_status === 'invalid') {
|
||||
return (
|
||||
<Tooltip title={record.ck_checked_at ? `检测时间:${formatTime(record.ck_checked_at)}` : undefined}>
|
||||
<Tag color="error">失效</Tag>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
return <Text type="secondary">未检测</Text>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '游戏名', dataIndex: 'game_name', width: 170,
|
||||
render: (_, record) => {
|
||||
@@ -1742,6 +1826,25 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
</Space>
|
||||
<Space>
|
||||
<Button size="small" icon={<ImportOutlined />} onClick={() => setImportOpen(true)}>导入账号</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<CheckCircleOutlined />}
|
||||
disabled={selectedIds.length === 0 || ckCheckingIds.size > 0}
|
||||
onClick={() => void checkWorkbenchCk(selectedIds)}
|
||||
>
|
||||
检测 CK{selectedIds.length > 0 ? `(${selectedIds.length})` : ''}
|
||||
</Button>
|
||||
{isAdmin && (
|
||||
<Button
|
||||
size="small"
|
||||
danger
|
||||
icon={<ReloadOutlined />}
|
||||
disabled={selectedIds.length === 0}
|
||||
onClick={reloginInvalidSelected}
|
||||
>
|
||||
重登失效
|
||||
</Button>
|
||||
)}
|
||||
{selectedIds.length > 0 && (
|
||||
<Button size="small" danger onClick={removeSelected}>移出选中</Button>
|
||||
)}
|
||||
@@ -1778,7 +1881,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
},
|
||||
}}
|
||||
tableLayout="fixed"
|
||||
scroll={{ x: 1280, y: Math.max(120, accountTableAreaHeight - 80) }}
|
||||
scroll={{ x: 1380, y: Math.max(120, accountTableAreaHeight - 80) }}
|
||||
onRow={(record) => ({
|
||||
onContextMenu: (e) => handleRowContextMenu(record, e),
|
||||
style: { cursor: 'context-menu' },
|
||||
|
||||
Reference in New Issue
Block a user