fix(douyu): 自动校验兑换资格并稳定账号导入顺序

This commit is contained in:
yml
2026-11-19 15:36:47 +08:00
parent ddead2284d
commit d611c0ed14
8 changed files with 275 additions and 18 deletions
+16
View File
@@ -69,3 +69,19 @@ class TestDouyuAccountNameFilter:
self.accounts["account-a"].id,
]
assert result["total"] == 2
def test_list_task_accounts_follows_ids_order(self):
result = list_task_accounts(
search="",
tag="",
ids=f"{self.accounts['account-c'].id},{self.accounts['account-a'].id}",
account_names="",
page=1,
page_size=50,
db=self.session,
current=self.user,
)
assert [item.username for item in result["items"]] == [
"account-c",
"account-a",
]
+108 -1
View File
@@ -1,16 +1,27 @@
"""验证 DouyuTask 的 account_assigned_to 字段与任务查询优化。"""
import asyncio
import pytest
from fastapi import HTTPException
from sqlalchemy.orm import Session
from tests.support.db import init_test_schema, make_test_session
from web.backend.models import Account, DouyuTask, PlatformFulfillmentTask, User
from web.backend.models import (
Account,
DouyuTask,
PlatformFulfillmentEvent,
PlatformFulfillmentTask,
User,
)
from web.backend.routers import douyu as douyu_router
from web.backend.routers.douyu import (
_require_task_account_access,
_visible_tasks_query,
)
from web.backend.schemas import DouyuTaskBatchRequest
from web.backend.services.douyu_service import create_douyu_planned_tasks
from web.backend.services.platform_fulfillment import service as platform_service
def test_douyu_task_assigned_to_flow():
@@ -192,3 +203,99 @@ def test_platform_task_context_allows_shared_account_operation():
finally:
db.rollback()
db.close()
def test_platform_exchange_checks_eligibility_before_creating_task(monkeypatch):
init_test_schema()
db: Session = make_test_session()
try:
owner = User(username="elig-owner", password_hash="h", role="support")
operator = User(
username="elig-operator",
password_hash="h",
role="support",
custom_permissions=[
"douyu:task",
"account:view_assigned",
"platform_fulfillment:use",
],
)
db.add_all([owner, operator])
db.flush()
account = Account(
username="elig-account",
password="p",
email="elig@test.com",
email_password="p",
cookie="acf_uid=1; acf_auth=x",
assigned_to=owner.id,
)
db.add(account)
db.flush()
task = PlatformFulfillmentTask(
source_order_id="elig-order",
source_order_item_id="elig-item",
platform_order_id="elig-platform-order",
account_id=account.id,
commodity_id="commodity-1",
required_points=1280,
binding_status="bound",
execution_status="bound",
exchange_status="not_opened",
)
db.add(task)
db.commit()
refreshed: list[int] = []
def fake_refresh(db_session, *, task_id, current):
refreshed.append(task_id)
row = db_session.get(PlatformFulfillmentTask, task_id)
assert row is not None and current.id == operator.id
row.exchange_status = "eligible"
row.issue_code = ""
row.last_error = ""
db_session.commit()
return platform_service.get_task_detail(db_session, task_id)
monkeypatch.setattr(
platform_service,
"refresh_exchange_eligibility",
fake_refresh,
)
monkeypatch.setattr(
douyu_router,
"start_douyu_batch",
lambda **_kwargs: None,
)
result = asyncio.run(
douyu_router.create_task_batch(
DouyuTaskBatchRequest(
account_ids=[account.id],
task_type="exchange_goods",
handbook_scope="elite",
concurrency=1,
payload={"commodity_id": "commodity-1"},
platform_task_id=task.id,
),
db=db,
current=operator,
)
)
assert refreshed == [task.id]
assert result["count"] == 1
created = db.query(DouyuTask).filter(DouyuTask.batch_id == result["batch_id"]).one()
assert created.platform_task_id == task.id
event = (
db.query(PlatformFulfillmentEvent)
.filter(
PlatformFulfillmentEvent.task_id == task.id,
PlatformFulfillmentEvent.event_type == "douyu_operation_started",
)
.one()
)
assert event.detail_json["taskType"] == "exchange_goods"
finally:
db.rollback()
db.close()
+39
View File
@@ -67,6 +67,45 @@ class TestDouyuWorkbenchScope:
assert empty_elite["configured"]
assert self.session.query(DouyuWorkbench).count() == 1
def test_workbench_accounts_keep_import_order(self):
extra = [
Account(
username=name,
password="password",
email=f"{name}@example.com",
email_password="mail-password",
cookie="acf_uid=1",
)
for name in ("order-a", "order-b")
]
self.session.add_all(extra)
self.session.commit()
desired = [extra[1].id, self.account.id, extra[0].id]
update_workbench_accounts(
DouyuWorkbenchAccountsUpdate(
handbook_scope="elite",
account_ids=desired,
),
db=self.session,
current=self.user,
)
saved = list_workbench_accounts(
"elite",
db=self.session,
current=self.user,
)
rows = (
self.session.query(DouyuWorkbenchAccount)
.filter(DouyuWorkbenchAccount.user_id == self.user.id)
.order_by(DouyuWorkbenchAccount.sort_order.asc())
.all()
)
assert saved["account_ids"] == desired
assert [row.account_id for row in rows] == desired
assert [row.sort_order for row in rows] == [0, 1, 2]
def test_task_scope_is_persisted_and_filters_shared_task_types(self):
elite_batch, _ = create_douyu_planned_tasks(
self.session,
+1 -1
View File
@@ -40,7 +40,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261118_0096"
HEAD_REVISION = "20261119_0097"
# 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = (
@@ -0,0 +1,49 @@
"""保存斗鱼工作台账号的显式展示顺序。"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261119_0097"
down_revision: str | None = "20261118_0096"
branch_labels: str | None = None
depends_on: str | None = None
TABLE = "douyu_workbench_accounts"
COLUMN = "sort_order"
def _column_exists() -> bool:
return bool(
op.get_bind()
.execute(
sa.text(
"SELECT COUNT(*) FROM information_schema.columns "
"WHERE table_schema = DATABASE() "
"AND table_name = :table AND column_name = :column"
),
{"table": TABLE, "column": COLUMN},
)
.scalar()
)
def upgrade() -> None:
if not _column_exists():
op.add_column(
TABLE,
sa.Column(
COLUMN,
sa.Integer(),
nullable=False,
server_default="0",
),
)
# 历史数据没有显式顺序,用原自增 ID 恢复当时的插入顺序。
op.execute(f"UPDATE `{TABLE}` SET `{COLUMN}` = `id`")
def downgrade() -> None:
if _column_exists():
op.drop_column(TABLE, COLUMN)
+3
View File
@@ -397,6 +397,9 @@ class DouyuWorkbenchAccount(Base):
account_id: Mapped[int] = mapped_column(
ForeignKey("accounts.id"), nullable=False, index=True
)
sort_order: Mapped[int] = mapped_column(
Integer, nullable=False, default=0, server_default="0"
)
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
__table_args__ = (
+50 -14
View File
@@ -329,7 +329,12 @@ def _apply_task_account_filters(
ids: str = "",
):
"""按工作台导入弹窗的搜索、标签、多行账号名筛选任务账号。"""
id_list = [int(item) for item in ids.split(",") if item.strip().isdigit()]
id_list = [
int(item)
for item in dict.fromkeys(
value.strip() for value in ids.split(",") if value.strip().isdigit()
)
]
if id_list:
query = query.filter(Account.id.in_(id_list))
tag_text = (tag or "").strip()
@@ -352,10 +357,14 @@ def _apply_task_account_filters(
Account.xpd_game_name.ilike(pattern),
)
)
return query, selected_names
return query, selected_names, id_list
def _order_task_accounts(query, selected_names: list[str]):
def _order_task_accounts(
query,
selected_names: list[str],
selected_ids: list[int] | None = None,
):
"""自定义账号名按粘贴顺序排序,未指定时保持最新账号优先。"""
if selected_names:
input_order = case(
@@ -364,6 +373,13 @@ def _order_task_accounts(query, selected_names: list[str]):
else_=len(selected_names),
)
return query.order_by(input_order, Account.id.desc())
if selected_ids:
input_order = case(
{account_id: index for index, account_id in enumerate(selected_ids)},
value=Account.id,
else_=len(selected_ids),
)
return query.order_by(input_order, Account.id.desc())
return query.order_by(Account.id.desc())
@@ -463,7 +479,7 @@ def list_task_accounts(
tag 按账号标签精确筛选;ids 为逗号分隔的账号 ID,用于工作台按已导入账号过滤;
account_names 为多行斗鱼账户名(每行一个),按粘贴顺序精确匹配;为空时返回全部。
"""
query, selected_names = _apply_task_account_filters(
query, selected_names, selected_ids = _apply_task_account_filters(
_visible_task_accounts_query(db, current),
search=search,
tag=tag,
@@ -473,7 +489,7 @@ def list_task_accounts(
total = None
if page is not None:
total = query.order_by(None).count()
query = _order_task_accounts(query, selected_names)
query = _order_task_accounts(query, selected_names, selected_ids)
if page is not None:
query = query.offset((page - 1) * page_size).limit(page_size)
else:
@@ -498,7 +514,7 @@ def list_task_account_ids(
current: User = Depends(get_current_user),
):
"""返回当前用户可导入工作台的全部账号 ID,不受列表分页限制。"""
query, selected_names = _apply_task_account_filters(
query, selected_names, selected_ids = _apply_task_account_filters(
_visible_task_accounts_query(db, current),
search=search,
tag=tag,
@@ -509,6 +525,7 @@ def list_task_account_ids(
for (account_id,) in _order_task_accounts(
query.enable_eagerloads(False).with_entities(Account.id),
selected_names,
selected_ids,
).all()
]
return {"account_ids": account_ids, "total": len(account_ids)}
@@ -581,7 +598,10 @@ def list_workbench_accounts(
rows = rows.filter(Account.assigned_to == current.id)
account_ids = [
account_id
for (account_id,) in rows.order_by(DouyuWorkbenchAccount.id.asc()).all()
for (account_id,) in rows.order_by(
DouyuWorkbenchAccount.sort_order.asc(),
DouyuWorkbenchAccount.id.asc(),
).all()
]
configured = (
db.query(DouyuWorkbench.id)
@@ -602,7 +622,7 @@ def update_workbench_accounts(
current: User = Depends(require_permission("douyu:task")),
):
"""用当前完整账号集合覆盖一个工作台,作为跨浏览器的同步状态。"""
account_ids = sorted(set(req.account_ids))
account_ids = list(dict.fromkeys(req.account_ids))
if any(account_id < 1 for account_id in account_ids):
raise HTTPException(status_code=400, detail="无效的账号ID")
if account_ids:
@@ -629,8 +649,9 @@ def update_workbench_accounts(
user_id=current.id,
handbook_scope=req.handbook_scope,
account_id=account_id,
sort_order=index,
)
for account_id in account_ids
for index, account_id in enumerate(account_ids)
]
)
db.commit()
@@ -774,6 +795,26 @@ async def create_task_batch(
req.account_ids,
platform_task_id=req.platform_task_id,
)
platform_task = (
db.query(PlatformFulfillmentTask)
.filter(PlatformFulfillmentTask.id == int(req.platform_task_id))
.first()
if req.platform_task_id
else None
)
if platform_task is not None and req.task_type == "exchange_goods":
eligibility = platform_fulfillment_service.refresh_exchange_eligibility(
db,
task_id=int(platform_task.id),
current=current,
)
refreshed_task = eligibility["task"]
if refreshed_task.get("exchangeStatus") != "eligible":
raise HTTPException(
status_code=409,
detail=refreshed_task.get("lastError") or "当前账号不满足兑换条件",
)
platform_task = db.get(PlatformFulfillmentTask, int(platform_task.id))
cleanup_orphan_douyu_tasks(
db,
@@ -799,11 +840,6 @@ async def create_task_batch(
status_code=400, detail="没有可执行的斗鱼账号,请先登录获取 Cookie"
)
if req.platform_task_id:
platform_task = (
db.query(PlatformFulfillmentTask)
.filter(PlatformFulfillmentTask.id == int(req.platform_task_id))
.first()
)
douyu_task_ids = [
int(task_id)
for (task_id,) in (
@@ -624,8 +624,16 @@ export default function PlatformFulfillmentPage() {
setDouyuActionType(taskType);
setDouyuActionBatchId(result.batch_id);
message.success(`${DOUYU_ACTION_LABELS[taskType] || '斗鱼任务'}已提交`);
if (taskType === 'exchange_goods' && selectedId) {
await loadDetail(selectedId, true);
await loadTasks(true);
}
} catch (error) {
message.error(getErrorMessage(error));
if (taskType === 'exchange_goods') {
if (selectedId) await loadDetail(selectedId, true);
await loadTasks(true);
}
} finally {
setDouyuActionLoading('');
}
@@ -1261,8 +1269,7 @@ export default function PlatformFulfillmentPage() {
disabled={
!selected.account ||
!can('douyu:task') ||
!selected.commodityId ||
selected.exchangeStatus !== 'eligible'
!selected.commodityId
}
loading={douyuActionLoading === 'exchange_goods'}
onClick={() => void runDouyuAccountAction('exchange_goods')}