From 9958e4ab7d4e450fbf98c10c5b2a0325420d636b Mon Sep 17 00:00:00 2001 From: yml Date: Tue, 17 Nov 2026 17:44:41 +0800 Subject: [PATCH] =?UTF-8?q?feat(fulfillment):=20=E5=AE=9E=E6=97=B6?= =?UTF-8?q?=E5=88=B7=E6=96=B0=E6=96=97=E9=B1=BC=E8=B4=A6=E5=8F=B7=E5=B9=B6?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E7=A7=9F=E7=BA=A6=E6=97=B6=E9=95=BF=E8=AE=BE?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/直播账号履约工作台.md | 30 +- tests/support/db.py | 16 +- tests/test_douyu_account_state.py | 131 ++++++ tests/test_migrations.py | 2 +- tests/test_platform_fulfillment.py | 182 +++++++- ...085_platform_fulfillment_lease_settings.py | 94 ++++ web/backend/models.py | 20 +- web/backend/routers/platform_fulfillment.py | 36 +- web/backend/schemas.py | 4 + web/backend/services/account_binding.py | 37 ++ .../services/automation/jobs/ck_health.py | 35 +- .../jobs/platform_fulfillment_lease_reaper.py | 1 + web/backend/services/cookie_check_service.py | 21 + web/backend/services/douyu_account_state.py | 310 +++++++++++++ web/backend/services/douyu_activity_query.py | 2 + web/backend/services/douyu_runner_bind.py | 8 +- .../platform_fulfillment/account_selector.py | 76 +++- .../services/platform_fulfillment/service.py | 215 +++++++-- web/frontend/src/api/platformFulfillment.ts | 10 + web/frontend/src/api/types.ts | 7 +- .../src/pages/PlatformFulfillmentPage.tsx | 429 ++++++++++++++++-- 21 files changed, 1546 insertions(+), 120 deletions(-) create mode 100644 tests/test_douyu_account_state.py create mode 100644 web/backend/migrations/versions/20261117_0085_platform_fulfillment_lease_settings.py create mode 100644 web/backend/services/douyu_account_state.py diff --git a/docs/直播账号履约工作台.md b/docs/直播账号履约工作台.md index 892c241..8da09e7 100644 --- a/docs/直播账号履约工作台.md +++ b/docs/直播账号履约工作台.md @@ -35,18 +35,44 @@ `DouyuActivityClient` 的只读查询方法。商品映射弹窗使用实时活动商品接口, 不再依赖本地是否执行过 `refresh_goods`。 +选号前会调用 `web/backend/services/douyu_account_state.py` 实时刷新账号: + +- 不依赖 `status`、`ck_check_status`、`elite_opened`、`points` 等缓存结论; +- 只要账号有 CK、允许自动管理且未停用/归档,就进入实时检测; +- 每次选号最多检测 5 个账号,结果写回 `ck_check_*`、生命周期状态、 + 精英宝典、积分、限兑、绑定状态、换绑冷却和账号概览快照; +- 下一次点击会优先检测尚未检测或最久未检测的下一批账号; +- 实时刷新完成后才判断是否创建租约,失败事件会记录每个账号的具体原因。 + +选号硬条件只保留:CK 实时有效、未达到该商品官方限兑上限、角色换绑冷却已结束、 +无有效租约。积分不足和精英宝典未开通属于**软条件**: + +- 不会淘汰账号,也不会阻止生成绑定二维码; +- 优先选择已开通且积分足够的账号,其次选择只需充值或只需开通的账号; +- 分配后分别记录为“积分不足”或“精英宝典未开通”; +- 完成充值、开通或限兑解除后,刷新兑换资格即可继续,原账号和绑定关系保留。 + ## 操作流程 1. 在“直播账号履约工作台”点击“同步待履约订单”。 2. 为待映射商品选择斗鱼商品和积分价格。 -3. 点击“自动选号”,系统按 CK、积分、开通状态、租约、365 天限兑和 - 换绑冷却筛选账号。 +3. 点击“自动选号”,系统实时检查 CK、租约、365 天限兑和换绑冷却; + 积分与精英宝典开通状态只影响账号排序和后续处理提示。 4. 点击“生成二维码”,让客户扫码绑定游戏角色。 5. 角色出现后点击“确认绑定”。 6. 点击“刷新兑换资格”,核对限兑、积分和精英宝典开通状态。 7. 运营在斗鱼侧人工完成兑换。 8. 回到工作台点击“完成”,系统释放账号租约并记录操作时间线。 +## 账号租约 + +账号租约默认无限制,适合当前“分配后由运营人工处理”的流程。管理员可在 +“租约设置”中切换为按分钟或按小时自动过期: + +- 保存设置后会立即同步当前所有活跃租约; +- 无限制租约不会自动回收,任务完成、取消或人工释放时仍会正常释放账号; +- 有限租约到期后由自动任务将未完成任务转入人工处理。 + ## 环境 读取 `order_site` 需要: diff --git a/tests/support/db.py b/tests/support/db.py index 3f8ebde..b7cc4f0 100644 --- a/tests/support/db.py +++ b/tests/support/db.py @@ -147,12 +147,20 @@ def _add_missing_columns(engine: Engine) -> None: for table in Base.metadata.sorted_tables: if not inspector.has_table(table.name): continue - existing = {column["name"] for column in inspector.get_columns(table.name)} + existing_columns = { + column["name"]: column for column in inspector.get_columns(table.name) + } for column in table.columns: - if column.name in existing: + existing = existing_columns.get(column.name) + if existing is None: + ddl = CreateColumn(column).compile(dialect=engine.dialect) + conn.execute(text(f"ALTER TABLE `{table.name}` ADD COLUMN {ddl}")) continue - ddl = CreateColumn(column).compile(dialect=engine.dialect) - conn.execute(text(f"ALTER TABLE `{table.name}` ADD COLUMN {ddl}")) + if bool(existing["nullable"]) != bool(column.nullable): + ddl = CreateColumn(column).compile(dialect=engine.dialect) + conn.execute( + text(f"ALTER TABLE `{table.name}` MODIFY COLUMN {ddl}") + ) def init_test_schema(engine: Engine | None = None) -> None: diff --git a/tests/test_douyu_account_state.py b/tests/test_douyu_account_state.py new file mode 100644 index 0000000..821cb30 --- /dev/null +++ b/tests/test_douyu_account_state.py @@ -0,0 +1,131 @@ +"""斗鱼账号实时状态刷新与生命周期写回测试。""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import cast + +from core.douyu import DouyuActivityClient +from web.backend.models import Account +from web.backend.services.douyu_account_state import refresh_douyu_account_state + + +class FakeClient: + def acf_ccn(self, *, refresh_subscribe: bool = False): + assert refresh_subscribe is False + return "csrf" + + def elite_user_info(self, **_kwargs): + return { + "manual_type": 1, + "manual_score": 5200, + "expire_time": 1799999999, + } + + def query_points(self, **_kwargs): + return { + "points": 5200, + "willExpireTime": 1799999999, + } + + def query_limited_goods(self, **_kwargs): + return {"limited_goods": [{"commodityId": "limited-goods"}]} + + def bind_info(self, **_kwargs): + return { + "is_bound_role": False, + "role_name": "", + "change_role_wait_time": 3600, + "area_name": "安卓", + "plat_name": "QQ", + } + + +def test_refresh_writes_ck_elite_points_limited_and_bind_lifecycle(db): + account = Account( + username="refresh-account", + password="p", + email="refresh@example.com", + email_password="ep", + status="imported", + ck_check_status="", + cookie="acf_uid=100; acf_nickname=test", + elite_opened=None, + points=None, + auto_managed=True, + ) + db.add(account) + db.commit() + + state = refresh_douyu_account_state( + db, + account, + manual_id="manual", + rid="room", + act_alias="alias", + client=cast(DouyuActivityClient, FakeClient()), + cookie_checker=lambda _cookie: { + "valid": True, + "message": "有效", + "fish_ball": 10, + "nickname": "测试", + "level": 5, + "checked_at": datetime.now(UTC), + }, + ) + + db.refresh(account) + assert state.ck_verdict == "valid" + assert state.limited_ids == frozenset({"limited-goods"}) + assert account.status == "active" + assert account.ck_check_status == "valid" + assert account.elite_opened is True + assert account.points == 5200 + assert account.role_bind_status == "unbound" + assert account.change_role_wait_time == 3600 + assert account.role_change_available_at is None + assert state.role_change_available_at is None + assert state.role_change_blocked is False + assert account.overview_queried_at is not None + assert account.overview_snapshot is not None + assert ( + account.overview_snapshot["limited_goods"][0]["commodityId"] == "limited-goods" + ) + + +def test_invalid_ck_writes_lifecycle_without_querying_activity(db): + account = Account( + username="invalid-account", + password="p", + email="invalid@example.com", + email_password="ep", + status="active", + ck_check_status="", + cookie="acf_uid=100", + auto_managed=True, + ) + db.add(account) + db.commit() + + state = refresh_douyu_account_state( + db, + account, + manual_id="manual", + rid="room", + act_alias="alias", + client=cast(DouyuActivityClient, FakeClient()), + cookie_checker=lambda _cookie: { + "valid": False, + "message": "未登录", + "fish_ball": None, + "nickname": None, + "level": None, + "checked_at": datetime.now(UTC), + }, + ) + + db.refresh(account) + assert state.ck_verdict == "invalid" + assert account.ck_check_status == "invalid" + assert account.status == "invalid" + assert state.elite_opened is None diff --git a/tests/test_migrations.py b/tests/test_migrations.py index afe1645..c2bf5d9 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -35,7 +35,7 @@ TESTS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = TESTS_DIR.parent VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" -HEAD_REVISION = "20261117_0084" +HEAD_REVISION = "20261117_0085" # 迁移新增、但不声明在模型里的复合查询索引。 EXTRA_INDEXES = ( diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 60253d8..c5ef22d 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -3,8 +3,10 @@ from __future__ import annotations from datetime import UTC, datetime, timedelta +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 ( @@ -17,7 +19,11 @@ from web.backend.models import ( PlatformFulfillmentTask, User, ) -from web.backend.services.automation.jobs import platform_fulfillment_lease_reaper as reaper +from web.backend.services.automation.jobs import ( + platform_fulfillment_lease_reaper as reaper, +) +from web.backend.services.douyu_account_state import DouyuLiveAccountState +from web.backend.services.douyu_activity_query import DouyuEligibilityResult from web.backend.services.platform_fulfillment import account_selector, service NOW = datetime.now(UTC).replace(microsecond=0) @@ -37,10 +43,31 @@ class _Base: self.session.add(self.admin) self.session.commit() self.admin_id = self.admin.id + self.refresh_patch = patch.object( + service, + "refresh_douyu_account_state", + side_effect=self._live_state, + ) + self.refresh_mock = self.refresh_patch.start() def teardown_method(self): + self.refresh_patch.stop() self.session.close() + @staticmethod + def _live_state(_db, account, **_kwargs): + return DouyuLiveAccountState( + account_id=account.id, + account_name=account.username, + checked_at=NOW, + ck_verdict="valid", + ck_message="有效", + elite_opened=True, + points=account.points or 2000, + limited_ids=frozenset(), + role_change_available_at=account.role_change_available_at, + ) + def account( self, name: str, @@ -216,6 +243,77 @@ class TestSyncAndMapping(_Base): class TestAccountSelection(_Base): + def test_allocation_refreshes_live_state_instead_of_cached_filters(self): + account = Account( + username="live-refresh-account", + password="p", + email="live@example.com", + email_password="ep", + status="imported", + ck_check_status="", + cookie="PHPSESSID=live", + elite_opened=None, + points=None, + gold_balance=100, + auto_managed=True, + ) + self.session.add(account) + self.session.commit() + task = self.task() + + detail = service.allocate_task( + self.session, + task_id=task.id, + current=self.admin, + ) + + assert detail["task"]["account"]["id"] == account.id + assert detail["task"]["executionStatus"] == "allocated" + self.refresh_mock.assert_called() + + def test_points_short_is_soft_and_does_not_block_allocation(self): + account = self.account("points-short", points=100) + task = self.task() + + detail = service.allocate_task( + self.session, + task_id=task.id, + current=self.admin, + ) + + assert detail["task"]["account"]["id"] == account.id + assert detail["task"]["executionStatus"] == "allocated" + assert detail["task"]["exchangeStatus"] == "points_short" + assert detail["task"]["issueCode"] == "points_short" + + def test_elite_not_opened_is_soft_and_does_not_block_allocation(self): + account = self.account("elite-closed", opened=False) + self.refresh_mock.side_effect = lambda _db, row, **_kwargs: ( + DouyuLiveAccountState( + account_id=row.id, + account_name=row.username, + checked_at=NOW, + ck_verdict="valid", + ck_message="有效", + elite_opened=False, + points=2000, + limited_ids=frozenset(), + role_change_available_at=None, + ) + ) + task = self.task() + + detail = service.allocate_task( + self.session, + task_id=task.id, + current=self.admin, + ) + + assert detail["task"]["account"]["id"] == account.id + assert detail["task"]["executionStatus"] == "allocated" + assert detail["task"]["exchangeStatus"] == "not_opened" + assert detail["task"]["issueCode"] == "elite_not_opened" + def test_eligible_account_excludes_cooldown_and_uses_least_points(self): self.account("small", points=1300) self.account("large", points=9000) @@ -262,7 +360,10 @@ class TestAccountSelection(_Base): assert first is not None assert second is None - assert self.session.query(AccountLease).filter_by(account_id=account.id).count() == 1 + assert ( + self.session.query(AccountLease).filter_by(account_id=account.id).count() + == 1 + ) def test_allocate_and_release_task(self): account = self.account("allocated") @@ -279,6 +380,7 @@ class TestAccountSelection(_Base): lease = self.session.query(AccountLease).one() assert lease.purpose == "platform_fulfillment" assert lease.status == "active" + assert lease.expires_at is None released = service.release_task_account( self.session, @@ -289,6 +391,31 @@ class TestAccountSelection(_Base): self.session.refresh(lease) assert lease.status == "released" + def test_lease_settings_support_unlimited_and_finite_duration(self): + self.account("settings-account") + task = self.task() + service.allocate_task(self.session, task_id=task.id, current=self.admin) + lease = self.session.query(AccountLease).one() + assert lease.expires_at is None + + finite = service.update_settings( + self.session, + lease_duration_minutes=90, + current=self.admin, + ) + self.session.refresh(lease) + assert finite["leaseDurationMinutes"] == 90 + assert lease.expires_at is not None + + unlimited = service.update_settings( + self.session, + lease_duration_minutes=None, + current=self.admin, + ) + self.session.refresh(lease) + assert unlimited["leaseDurationMinutes"] is None + assert lease.expires_at is None + class TestBindingAndCompletion(_Base): def _allocated(self): @@ -366,6 +493,38 @@ class TestBindingAndCompletion(_Base): lease = self.session.query(AccountLease).one() assert lease.status == "released" + def test_points_short_after_binding_keeps_account_and_stays_bound( + self, monkeypatch + ): + task = self._allocated() + account = ( + self.session.query(Account).filter(Account.id == task.account_id).one() + ) + task.binding_status = "bound" + task.execution_status = "bound" + self.session.commit() + monkeypatch.setattr( + service, + "query_exchange_eligibility", + lambda *_args, **_kwargs: DouyuEligibilityResult( + elite_user_info={"manual_type": 1}, + points=100, + points_response={"points": 100}, + limited_goods=[], + limited_ids=frozenset(), + ), + ) + + detail = service.refresh_exchange_eligibility( + self.session, + task_id=task.id, + current=self.admin, + ) + + assert detail["task"]["executionStatus"] == "bound" + assert detail["task"]["exchangeStatus"] == "points_short" + assert detail["task"]["account"]["id"] == account.id + def test_expired_lease_moves_unfinished_task_to_manual(self): task = self._allocated() lease = self.session.query(AccountLease).one() @@ -384,6 +543,23 @@ class TestBindingAndCompletion(_Base): assert task.execution_status == "manual_required" assert task.issue_code == "lease_expired" + def test_unlimited_lease_is_ignored_by_reaper(self): + task = self._allocated() + lease = self.session.query(AccountLease).one() + lease.expires_at = None + self.session.commit() + + job = AutomationJob(key=reaper.JOB_KEY, batch_size=100) + result = reaper.run_platform_fulfillment_lease_reaper( + self.session, + job, + now=NOW + timedelta(days=365), + ) + + self.session.refresh(task) + assert result["expired"] == 0 + assert task.execution_status == "allocated" + def test_completion_rejects_limited_exchange(self): task = self._allocated() task.binding_status = "bound" @@ -391,7 +567,7 @@ class TestBindingAndCompletion(_Base): task.exchange_status = "limited" self.session.commit() - with pytest.raises(Exception): + with pytest.raises(HTTPException): service.complete_manual_exchange( self.session, task_id=task.id, diff --git a/web/backend/migrations/versions/20261117_0085_platform_fulfillment_lease_settings.py b/web/backend/migrations/versions/20261117_0085_platform_fulfillment_lease_settings.py new file mode 100644 index 0000000..e20212e --- /dev/null +++ b/web/backend/migrations/versions/20261117_0085_platform_fulfillment_lease_settings.py @@ -0,0 +1,94 @@ +"""直播账号履约租约时长设置 + +默认账号租约无期限;运营可切换为按分钟或小时自动过期。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261117_0085" +down_revision: str | None = "20261117_0084" +branch_labels: str | None = None +depends_on: str | None = None + + +def _table_exists(table: str) -> bool: + return bool( + op.get_bind() + .execute( + sa.text( + "SELECT COUNT(*) FROM information_schema.tables " + "WHERE table_schema = DATABASE() AND table_name = :table" + ), + {"table": table}, + ) + .scalar() + ) + + +def upgrade() -> None: + op.alter_column( + "account_leases", + "expires_at", + existing_type=sa.DateTime(), + nullable=True, + ) + if not _table_exists("platform_fulfillment_settings"): + op.create_table( + "platform_fulfillment_settings", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("lease_duration_minutes", sa.Integer(), nullable=True), + sa.Column("updated_by", sa.Integer(), nullable=True), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint( + ["updated_by"], + ["users.id"], + name="fk_platform_fulfillment_settings_updated_by", + ondelete="SET NULL", + ), + sa.PrimaryKeyConstraint("id"), + ) + op.execute( + sa.text( + """ + INSERT INTO platform_fulfillment_settings ( + id, lease_duration_minutes, updated_by, updated_at + ) VALUES (1, NULL, NULL, NOW()) + ON DUPLICATE KEY UPDATE id = id + """ + ) + ) + # 设置上线即默认无限期;正在使用的租约也立即转为无限期,避免几分钟后中断。 + op.execute( + sa.text( + """ + UPDATE account_leases + SET expires_at = NULL + WHERE purpose = 'platform_fulfillment' AND status = 'active' + """ + ) + ) + + +def downgrade() -> None: + op.execute( + sa.text( + """ + UPDATE account_leases + SET expires_at = DATE_ADD(NOW(), INTERVAL 5 MINUTE) + WHERE purpose = 'platform_fulfillment' + AND status = 'active' + AND expires_at IS NULL + """ + ) + ) + if _table_exists("platform_fulfillment_settings"): + op.drop_table("platform_fulfillment_settings") + op.alter_column( + "account_leases", + "expires_at", + existing_type=sa.DateTime(), + nullable=False, + ) diff --git a/web/backend/models.py b/web/backend/models.py index a3d24bf..491e933 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -1686,8 +1686,8 @@ class AccountLease(Base): String(16), nullable=False, default="active", server_default="active" ) leased_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow) - # TTL 兜底:进程重启、页面关掉都能靠它把租约收回来。 - expires_at: Mapped[datetime] = mapped_column(UTCDateTime, nullable=False) + # 到期时间;NULL 表示按当前设置无限期占用。 + expires_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) released_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) release_reason: Mapped[str] = mapped_column( String(64), nullable=False, default="", server_default="" @@ -1713,6 +1713,22 @@ class AccountLease(Base): holder: Mapped[User] = relationship("User") +class PlatformFulfillmentSetting(Base): + """直播账号履约工作台的持久化设置。""" + + __tablename__ = "platform_fulfillment_settings" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + lease_duration_minutes: Mapped[int | None] = mapped_column(Integer, nullable=True) + updated_by: Mapped[int | None] = mapped_column( + ForeignKey("users.id", ondelete="SET NULL"), + nullable=True, + ) + updated_at: Mapped[datetime] = mapped_column( + UTCDateTime, default=_utcnow, onupdate=_utcnow + ) + + class PlatformCommodityMapping(Base): """order_site 内部 SKU 到斗鱼商品的显式映射。""" diff --git a/web/backend/routers/platform_fulfillment.py b/web/backend/routers/platform_fulfillment.py index db95279..0b4b504 100644 --- a/web/backend/routers/platform_fulfillment.py +++ b/web/backend/routers/platform_fulfillment.py @@ -14,6 +14,7 @@ from ..schemas import ( PlatformFulfillmentCompleteRequest, PlatformFulfillmentMappingUpsert, PlatformFulfillmentReasonRequest, + PlatformFulfillmentSettingsUpdate, ) from ..services.audit_service import record_audit from ..services.platform_fulfillment import service @@ -21,6 +22,37 @@ from ..services.platform_fulfillment import service router = APIRouter(prefix="/api/platform-fulfillment", tags=["直播账号履约"]) +@router.get("/settings") +def get_settings( + db: Session = Depends(get_db), + current: User = Depends(require_permission("platform_fulfillment:view")), +) -> dict[str, Any]: + del current + return service.get_settings(db) + + +@router.put("/settings") +def update_settings( + req: PlatformFulfillmentSettingsUpdate, + db: Session = Depends(get_db), + current: User = Depends(require_permission("platform_fulfillment:admin")), +) -> dict[str, Any]: + result = service.update_settings( + db, + lease_duration_minutes=req.lease_duration_minutes, + current=current, + ) + record_audit( + db, + current, + action="platform_fulfillment:settings:update", + target="platform_fulfillment_settings", + detail=result, + ) + db.commit() + return result + + @router.get("/tasks") def list_tasks( status: str = Query("", max_length=32), @@ -174,9 +206,7 @@ def refresh_eligibility( db: Session = Depends(get_db), current: User = Depends(require_permission("platform_fulfillment:use")), ) -> dict[str, Any]: - result = service.refresh_exchange_eligibility( - db, task_id=task_id, current=current - ) + result = service.refresh_exchange_eligibility(db, task_id=task_id, current=current) record_audit( db, current, diff --git a/web/backend/schemas.py b/web/backend/schemas.py index 1d3a8af..c7c2f3d 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -1576,6 +1576,10 @@ class PlatformFulfillmentCompleteRequest(BaseModel): note: str = Field(default="", max_length=1000) +class PlatformFulfillmentSettingsUpdate(BaseModel): + lease_duration_minutes: int | None = Field(..., ge=1, le=525600) + + class DouyuTaskBatchRequest(BaseModel): account_ids: list[int] task_type: str diff --git a/web/backend/services/account_binding.py b/web/backend/services/account_binding.py index 22b783d..332a510 100644 --- a/web/backend/services/account_binding.py +++ b/web/backend/services/account_binding.py @@ -32,6 +32,9 @@ from __future__ import annotations +from datetime import UTC, datetime +from typing import Any + from ..models import Account # ── 作用域 ────────────────────────────────────────────── @@ -239,3 +242,37 @@ def derive_from_bind_info(info: dict | None) -> str | None: return BIND_UNBOUND # 接口没给结论:保持 unknown,别把"没查到"写成"没绑定" return None + + +def is_role_change_cooling(info: dict | None) -> bool: + """是否处于真实换绑冷却:已有绑定角色且当前不可换绑。""" + if not isinstance(info, dict): + return False + role_name = str(info.get("role_name") or info.get("role") or "").strip() + if not role_name or not _truthy_flag(info.get("is_bound_act")): + return False + if str(info.get("api_version") or "") == "esports": + can_change_time = _to_int(info.get("can_change_time")) + if can_change_time is not None: + return can_change_time > int(datetime.now(UTC).timestamp()) + wait_time = _to_int(info.get("change_role_wait_time")) + if wait_time is not None and wait_time > 0: + return True + if info.get("can_change_role") is not None: + return not _truthy_flag(info.get("can_change_role")) + return False + + +def _truthy_flag(value: Any) -> bool: + if value is True: + return True + if value is False or value is None: + return False + return str(value).strip().lower() in {"1", "true", "yes", "y"} + + +def _to_int(value: Any) -> int | None: + try: + return int(float(value)) + except (TypeError, ValueError): + return None diff --git a/web/backend/services/automation/jobs/ck_health.py b/web/backend/services/automation/jobs/ck_health.py index 7496c32..c61ecbb 100644 --- a/web/backend/services/automation/jobs/ck_health.py +++ b/web/backend/services/automation/jobs/ck_health.py @@ -23,24 +23,17 @@ from ...account_value import ( high_value_recheck_seconds, value_tier_expr, ) -from ...cookie_check_service import check_douyu_cookie +from ...cookie_check_service import ( + check_douyu_cookie, +) +from ...cookie_check_service import ( + classify_douyu_cookie_result as classify_result, +) from ...douyu_service import cookie_holding_filter, cookie_operable_filter JOB_KEY = "ck_health" FLUSH_EVERY = 25 -# 斗鱼明确表示「这个 CK 不能用」的说法。只有命中这些才算真的失效。 -AUTH_FAILURE_MARKERS = ( - "登陆异常", - "登录异常", - "未登录", - "登陆失效", - "登录失效", - "重新登陆", - "重新登录", - "账户登陆", -) - # 非鉴权类失败(网络超时、响应异常、被判风控)占比超过它就自动暂停作业。 # 这类失败说明「我们查不到」,不是「这个 CK 失效了」;如果不加区分地写 # invalid,斗鱼接口抖动一小时就能把上千个好账号标成失效,客服会误判成 @@ -49,22 +42,6 @@ ERROR_PAUSE_RATIO = 0.3 ERROR_PAUSE_MIN_SCANNED = 20 -def classify_result(result: dict[str, Any]) -> str: - """把检测结果分成三类:valid / invalid(真失效)/ error(查不到)。 - - - ``valid``:斗鱼两个接口都通过; - - ``invalid``:斗鱼明确回复「未登录 / 登陆异常」之类的鉴权失败; - - ``error``:其余失败(请求失败、超时、响应异常、未知结构)—— - **不能当成失效**,也不覆盖该行原来的结论。 - """ - if result.get("valid"): - return "valid" - message = str(result.get("message") or "") - if any(marker in message for marker in AUTH_FAILURE_MARKERS): - return "invalid" - return "error" - - def _candidates_query(db: Session, job: AutomationJob, now: datetime): """本轮「待检测账号」的完整候选集(**不带 LIMIT**,供计数复用)。 diff --git a/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py b/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py index ec5eee9..34a3a8e 100644 --- a/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py +++ b/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py @@ -28,6 +28,7 @@ def run_platform_fulfillment_lease_reaper( .filter( AccountLease.purpose == "platform_fulfillment", AccountLease.status == "active", + AccountLease.expires_at.isnot(None), AccountLease.expires_at <= moment, ) .limit(max(1, int(job.batch_size or 500))) diff --git a/web/backend/services/cookie_check_service.py b/web/backend/services/cookie_check_service.py index 6f7b8b8..71687a6 100644 --- a/web/backend/services/cookie_check_service.py +++ b/web/backend/services/cookie_check_service.py @@ -11,6 +11,27 @@ CHECK_UA = ( FISH_BALL_API = "https://www.douyu.com/wjapi/nc/exchange/fishBall" USER_LEVEL_API = "https://www.douyu.com/japi/interactnc/web/userLevel/userLevelDetail" +AUTH_FAILURE_MARKERS = ( + "登陆异常", + "登录异常", + "未登录", + "登陆失效", + "登录失效", + "重新登陆", + "重新登录", + "账户登陆", +) + + +def classify_douyu_cookie_result(result: dict) -> str: + """把检测结果分成 valid / invalid / error,区分失效与暂时查不到。""" + if result.get("valid"): + return "valid" + message = str(result.get("message") or "") + if any(marker in message for marker in AUTH_FAILURE_MARKERS): + return "invalid" + return "error" + def check_douyu_cookie(cookie: str) -> dict: """检测斗鱼 Cookie 有效性,鱼丸与等级接口均通过才算有效。""" diff --git a/web/backend/services/douyu_account_state.py b/web/backend/services/douyu_account_state.py new file mode 100644 index 0000000..07a5f45 --- /dev/null +++ b/web/backend/services/douyu_account_state.py @@ -0,0 +1,310 @@ +"""斗鱼账号实时状态刷新。 + +选号不能依赖账号上的缓存字段。只要账号持有 CK,本模块就实时检测 CK、 +查询精英宝典、积分、限兑商品和绑定冷却,并把结果写回账号生命周期与账号 +快照。业务调用方只消费返回的实时结论。 +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta +from typing import Any + +from sqlalchemy.orm import Session + +from core.douyu import DouyuActivityClient + +from ..models import Account +from .account_binding import ( + SCOPE_ELITE, + derive_from_bind_info, + is_role_change_cooling, + set_bind_status, +) +from .account_lifecycle import on_ck_verdict +from .cookie_check_service import check_douyu_cookie, classify_douyu_cookie_result +from .douyu_activity_query import ( + activity_client, + query_bind_info, + query_exchange_eligibility, +) + + +@dataclass(frozen=True) +class DouyuLiveAccountState: + account_id: int + account_name: str + checked_at: datetime + ck_verdict: str + ck_message: str + elite_opened: bool | None + points: int | None + limited_ids: frozenset[str] + role_change_available_at: datetime | None + error: str = "" + role_change_blocked: bool = False + + def blocking_reasons( + self, + *, + commodity_id: str, + ) -> list[str]: + reasons: list[str] = [] + if self.ck_verdict != "valid": + reasons.append(f"CK {self.ck_verdict}: {self.ck_message}") + if self.error: + reasons.append(self.error) + if commodity_id in self.limited_ids: + reasons.append("该商品已达限兑上限") + if self.role_change_blocked: + available_text = ( + self.role_change_available_at.isoformat() + if self.role_change_available_at + else "未知时间" + ) + reasons.append(f"角色换绑冷却至 {available_text}") + return reasons + + def soft_requirement_reasons(self, *, required_points: int) -> list[str]: + """积分/开通不淘汰账号,只决定后续需要充值还是开通。""" + reasons: list[str] = [] + if self.elite_opened is not True: + reasons.append("精英宝典未开通") + if self.points is None or self.points < required_points: + reasons.append(f"积分不足({self.points or 0}/{required_points})") + return reasons + + def readiness_rank(self, *, required_points: int) -> int: + """数值越小越接近直接兑换,用于软条件排序。""" + opened = self.elite_opened is True + enough = self.points is not None and self.points >= required_points + if opened and enough: + return 0 + if opened: + return 1 + if enough: + return 2 + return 3 + + +def refresh_douyu_account_state( + db: Session, + account: Account, + *, + manual_id: str, + rid: str, + act_alias: str, + client: DouyuActivityClient | None = None, + cookie_checker: Callable[[str], dict[str, Any]] = check_douyu_cookie, + commit: bool = True, +) -> DouyuLiveAccountState: + """实时刷新单个账号,并把所有可落库状态写回账号。""" + now = datetime.now(UTC) + cookie = str(account.cookie or "").strip() + account_name = account.nickname or account.username or f"#{account.id}" + ck_result = cookie_checker(cookie) + ck_verdict = classify_douyu_cookie_result(ck_result) + ck_message = str(ck_result.get("message") or "") + on_ck_verdict( + db, + account, + ck_verdict, + detail=ck_result, + occurred_at=now, + ) + + if ck_verdict != "valid": + snapshot = { + "queried_at": now.isoformat(), + "ck": ck_result, + "errors": ["CK 检测未通过,未继续查询活动状态"], + } + account.overview_snapshot = _json_safe(snapshot) + account.updated_at = now + if commit: + db.commit() + return DouyuLiveAccountState( + account_id=int(account.id), + account_name=account_name, + checked_at=now, + ck_verdict=ck_verdict, + ck_message=ck_message, + elite_opened=account.elite_opened, + points=account.points, + limited_ids=frozenset(), + role_change_available_at=account.role_change_available_at, + ) + + active_client = client or activity_client(cookie) + try: + eligibility = query_exchange_eligibility( + active_client, + cookie=cookie, + manual_id=manual_id, + rid=rid, + uid=str(account.uid or ""), + ) + except Exception as exc: # noqa: BLE001 外部接口边界需要保留单项诊断 + error = f"{type(exc).__name__}: {exc}"[:240] + snapshot = { + "queried_at": now.isoformat(), + "ck": ck_result, + "errors": [error], + } + account.overview_snapshot = _json_safe(snapshot) + account.overview_queried_at = now + account.updated_at = now + if commit: + db.commit() + return DouyuLiveAccountState( + account_id=int(account.id), + account_name=account_name, + checked_at=now, + ck_verdict=ck_verdict, + ck_message=ck_message, + elite_opened=account.elite_opened, + points=account.points, + limited_ids=frozenset(), + role_change_available_at=account.role_change_available_at, + error=error, + ) + + errors: list[str] = [] + bind_info: dict[str, Any] = {} + try: + bind_info = query_bind_info( + active_client, + act_alias=act_alias, + ) + except Exception as exc: # noqa: BLE001 绑定查询失败不应丢弃资产查询结果 + errors.append(f"绑定状态查询失败: {type(exc).__name__}: {exc}"[:240]) + + elite_opened = bool(eligibility.elite_user_info.get("manual_type")) + elite_expire_time = _to_int(eligibility.elite_user_info.get("expire_time")) + account.elite_opened = elite_opened + account.elite_expire_time = elite_expire_time or None + account.points = eligibility.points + account.points_expire_at = _points_expire_at( + eligibility.points_response, + checked_at=now, + ) + role_change_available_at = account.role_change_available_at + if bind_info: + role_change_available_at = _apply_bind_state( + account, + bind_info, + checked_at=now, + ) + account.overview_snapshot = _json_safe( + { + "queried_at": now.isoformat(), + "ck": ck_result, + "elite": eligibility.elite_user_info, + "points": eligibility.points_response, + "limited_goods": eligibility.limited_goods, + "bind": bind_info, + "errors": errors, + } + ) + account.overview_queried_at = now + account.high_value_checked_at = now + account.updated_at = now + if commit: + db.commit() + + return DouyuLiveAccountState( + account_id=int(account.id), + account_name=account_name, + checked_at=now, + ck_verdict=ck_verdict, + ck_message=ck_message, + elite_opened=elite_opened, + points=eligibility.points, + limited_ids=eligibility.limited_ids, + role_change_available_at=role_change_available_at, + error=";".join(errors), + role_change_blocked=is_role_change_cooling(bind_info), + ) + + +def _apply_bind_state( + account: Account, + bind_info: dict[str, Any], + *, + checked_at: datetime, +) -> datetime | None: + derived = derive_from_bind_info(bind_info) + if derived is not None: + set_bind_status(account, SCOPE_ELITE, derived) + + role_name = str(bind_info.get("role_name") or bind_info.get("role") or "").strip() + if role_name: + account.game_name = role_name[:128] + area_name = str(bind_info.get("area_name") or "").strip() + plat_name = str(bind_info.get("plat_name") or "").strip() + channel = " · ".join(item for item in (area_name, plat_name) if item) + if channel: + account.game_channel = channel[:128] + + wait_seconds = _to_int(bind_info.get("change_role_wait_time")) + can_change_time = _to_int(bind_info.get("can_change_time")) + account.change_role_wait_time = wait_seconds + if not is_role_change_cooling(bind_info): + available_at = None + elif can_change_time is not None and can_change_time > 0: + available_at = datetime.fromtimestamp(can_change_time, tz=UTC) + elif wait_seconds is not None and wait_seconds > 0: + available_at = checked_at + timedelta(seconds=wait_seconds) + else: + available_at = account.role_change_available_at + account.role_change_available_at = available_at + return available_at + + +def _points_expire_at( + points_response: dict[str, Any], + *, + checked_at: datetime, +) -> datetime | None: + raw = ( + points_response.get("willExpireTime") + or points_response.get("will_expire_time") + or points_response.get("expire_time") + ) + value = _to_int(raw) + if value is None or value <= 0: + return None + if value > 10_000_000_000: + value //= 1000 + if value < int(checked_at.timestamp()) - 60: + return None + return datetime.fromtimestamp(value, tz=UTC) + + +def _to_int(value: Any) -> int | None: + if value is None or value == "": + return None + try: + return int(float(value)) + except (TypeError, ValueError): + return None + + +def _json_safe(value: Any) -> Any: + if isinstance(value, datetime): + return value.isoformat() + if isinstance(value, dict): + return {str(key): _json_safe(item) for key, item in value.items()} + if isinstance(value, (list, tuple, set, frozenset)): + return [_json_safe(item) for item in value] + if isinstance(value, (str, int, float, bool)) or value is None: + return value + return str(value) + + +__all__ = [ + "DouyuLiveAccountState", + "refresh_douyu_account_state", +] diff --git a/web/backend/services/douyu_activity_query.py b/web/backend/services/douyu_activity_query.py index 2981663..ceda7fc 100644 --- a/web/backend/services/douyu_activity_query.py +++ b/web/backend/services/douyu_activity_query.py @@ -206,6 +206,7 @@ def query_exchange_orders( class DouyuEligibilityResult: elite_user_info: dict[str, Any] points: int + points_response: dict[str, Any] limited_goods: list[dict[str, Any]] limited_ids: frozenset[str] @@ -232,6 +233,7 @@ def query_exchange_eligibility( return DouyuEligibilityResult( elite_user_info=elite, points=int(points_result.get("points") or 0), + points_response=points_result, limited_goods=limited, limited_ids=frozenset(limited_ids), ) diff --git a/web/backend/services/douyu_runner_bind.py b/web/backend/services/douyu_runner_bind.py index e60a47a..85cc7ff 100644 --- a/web/backend/services/douyu_runner_bind.py +++ b/web/backend/services/douyu_runner_bind.py @@ -17,6 +17,7 @@ from .account_binding import ( BIND_UNBOUND, SCOPE_ELITE, SCOPE_ESPORTS, + is_role_change_cooling, set_bind_status, ) from .business_events import record_bind @@ -148,12 +149,7 @@ class BindMixin: @classmethod def _is_change_cooling(cls, bind_info: dict | None) -> bool: """是否处于换绑冷却:已有绑定角色且当前不可换绑。""" - if not bind_info: - return False - role_name = str(bind_info.get("role_name") or "").strip() - if not role_name or not cls._is_bound_act(bind_info): - return False - return not cls._can_change_role(bind_info) + return is_role_change_cooling(bind_info) @classmethod def _is_pending_role( diff --git a/web/backend/services/platform_fulfillment/account_selector.py b/web/backend/services/platform_fulfillment/account_selector.py index a3f13b3..cd548b0 100644 --- a/web/backend/services/platform_fulfillment/account_selector.py +++ b/web/backend/services/platform_fulfillment/account_selector.py @@ -14,6 +14,7 @@ from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from ...models import Account, AccountEvent, AccountLease, User +from ..account_lifecycle import MANUAL_STATES VALIDATION_LEASE_MINUTES = 5 BINDING_LEASE_MINUTES = 120 @@ -109,6 +110,62 @@ def eligible_accounts( ] +def live_candidate_accounts( + db: Session, + *, + limit: int = 20, +) -> list[Account]: + """选出值得实时检测的账号,不读取 CK/积分/开通等缓存结论。""" + owner_ids = select(User.id).where(User.role.in_(POOL_OWNER_ROLES)) + active_lease = ( + select(AccountLease.id) + .where(AccountLease.active_account_id == Account.id) + .exists() + ) + return ( + db.query(Account) + .filter( + Account.cookie.isnot(None), + Account.cookie != "", + Account.auto_managed.is_(True), + Account.status.notin_(MANUAL_STATES), + or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)), + ~active_lease, + ) + .order_by( + Account.ck_checked_at.is_(None).desc(), + Account.ck_checked_at.asc(), + Account.points.is_(None).desc(), + Account.points.asc(), + Account.id.asc(), + ) + .limit(max(1, min(int(limit), 100))) + .all() + ) + + +def has_recent_exchange( + db: Session, + *, + account_id: int, + commodity_id: str, + now: datetime | None = None, +) -> bool: + moment = _now(now) + since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS) + return ( + db.query(AccountEvent.id) + .filter( + AccountEvent.account_id == account_id, + AccountEvent.event_type == "exchange", + AccountEvent.subject_key == commodity_id, + AccountEvent.occurred_at >= since, + ) + .first() + is not None + ) + + def lease_account( db: Session, *, @@ -116,7 +173,7 @@ def lease_account( holder_user_id: int, task_id: int, commodity_id: str, - ttl_minutes: int = VALIDATION_LEASE_MINUTES, + ttl_minutes: int | None = None, now: datetime | None = None, ) -> AccountLease | None: """尝试领取一个账号;撞唯一索引时返回 None。""" @@ -130,7 +187,11 @@ def lease_account( batch_id=f"pf:{task_id}", status="active", leased_at=moment, - expires_at=moment + timedelta(minutes=max(1, int(ttl_minutes))), + expires_at=( + None + if ttl_minutes is None + else moment + timedelta(minutes=max(1, int(ttl_minutes))) + ), release_reason="", created_at=moment, ) @@ -150,12 +211,16 @@ def renew_lease( db: Session, lease: AccountLease, *, - ttl_minutes: int = BINDING_LEASE_MINUTES, + ttl_minutes: int | None = None, now: datetime | None = None, ) -> AccountLease: if lease.status != "active": raise ValueError("租约已结束,不能续期") - lease.expires_at = _now(now) + timedelta(minutes=max(1, int(ttl_minutes))) + lease.expires_at = ( + None + if ttl_minutes is None + else _now(now) + timedelta(minutes=max(1, int(ttl_minutes))) + ) db.commit() return lease @@ -188,6 +253,7 @@ def expire_platform_fulfillment_leases( .filter( AccountLease.purpose == "platform_fulfillment", AccountLease.status == "active", + AccountLease.expires_at.isnot(None), AccountLease.expires_at <= moment, ) .order_by(AccountLease.id.asc()) @@ -210,7 +276,9 @@ __all__ = [ "AccountCandidate", "eligible_accounts", "expire_platform_fulfillment_leases", + "has_recent_exchange", "lease_account", + "live_candidate_accounts", "release_lease", "renew_lease", ] diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index bd63076..8561690 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -3,15 +3,13 @@ from __future__ import annotations import uuid -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from typing import Any from fastapi import HTTPException from sqlalchemy import or_ from sqlalchemy.orm import Session -from core.douyu import DouyuActivityError - from ...models import ( Account, AccountLease, @@ -19,9 +17,11 @@ from ...models import ( DouyuTask, PlatformCommodityMapping, PlatformFulfillmentEvent, + PlatformFulfillmentSetting, PlatformFulfillmentTask, User, ) +from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state from ..douyu_activity_query import activity_client, query_exchange_eligibility from ..douyu_batch_launcher import start_douyu_batch from ..douyu_service import douyu_config_value, ensure_douyu_config @@ -30,10 +30,10 @@ from ..external_order_source import ( list_pending_manual_fulfillments, ) from .account_selector import ( - BINDING_LEASE_MINUTES, - VALIDATION_LEASE_MINUTES, - eligible_accounts, + AccountCandidate, + has_recent_exchange, lease_account, + live_candidate_accounts, release_lease, renew_lease, ) @@ -81,6 +81,66 @@ def _mapping_for_sku( ) +def get_settings(db: Session) -> dict[str, Any]: + row = ( + db.query(PlatformFulfillmentSetting) + .filter(PlatformFulfillmentSetting.id == 1) + .first() + ) + if row is None: + row = PlatformFulfillmentSetting(id=1, lease_duration_minutes=None) + db.add(row) + db.commit() + db.refresh(row) + return { + "leaseDurationMinutes": row.lease_duration_minutes, + "updatedAt": _jsonable(row.updated_at), + } + + +def update_settings( + db: Session, + *, + lease_duration_minutes: int | None, + current: User, +) -> dict[str, Any]: + row = ( + db.query(PlatformFulfillmentSetting) + .filter(PlatformFulfillmentSetting.id == 1) + .first() + ) + if row is None: + row = PlatformFulfillmentSetting(id=1) + db.add(row) + now = _now() + row.lease_duration_minutes = lease_duration_minutes + row.updated_by = current.id + row.updated_at = now + active_leases = ( + db.query(AccountLease) + .filter( + AccountLease.purpose == "platform_fulfillment", + AccountLease.status == "active", + ) + .all() + ) + for lease in active_leases: + lease.expires_at = ( + None + if lease_duration_minutes is None + else now + timedelta(minutes=lease_duration_minutes) + ) + db.commit() + return { + "leaseDurationMinutes": row.lease_duration_minutes, + "updatedAt": _jsonable(row.updated_at), + } + + +def _lease_duration_minutes(db: Session) -> int | None: + return get_settings(db)["leaseDurationMinutes"] + + def _append_event( db: Session, task_id: int, @@ -485,37 +545,119 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any] raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号") if not task.commodity_id or not task.required_points: raise HTTPException(status_code=409, detail="请先完成商品映射") + required_points = int(task.required_points) if task.account_id and task.lease_id: lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if lease and lease.status == "active": return get_task_detail(db, task.id) - candidates = eligible_accounts( - db, - commodity_id=task.commodity_id, - required_points=task.required_points, - limit=20, - ) - selected = None + config = ensure_douyu_config(db) + lease_duration_minutes = _lease_duration_minutes(db) + manual_id = str(douyu_config_value("manual_id", config.manual_id)) + rid = str(douyu_config_value("rid", config.rid)) + act_alias = str(douyu_config_value("bind_act_alias", config.bind_act_alias)) + # 单次最多实时检测 5 个,避免一次选号请求被外部接口拖到超时。 + # 检测时间会写回 ck_checked_at,下一次点击自动轮到下一批。 + candidates = live_candidate_accounts(db, limit=5) + diagnostics: list[dict[str, Any]] = [] + qualified: list[tuple[Account, DouyuLiveAccountState]] = [] + selected: AccountCandidate | None = None + selected_state: DouyuLiveAccountState | None = None lease = None - for candidate in candidates: + for account in candidates: + live_state = refresh_douyu_account_state( + db, + account, + manual_id=manual_id, + rid=rid, + act_alias=act_alias, + ) + reasons = live_state.blocking_reasons(commodity_id=task.commodity_id) + if has_recent_exchange( + db, + account_id=int(account.id), + commodity_id=task.commodity_id, + ): + reasons.append("365 天内已有该商品兑换事件") + if reasons: + diagnostics.append( + { + "accountId": int(account.id), + "accountName": live_state.account_name, + "ck": live_state.ck_verdict, + "eliteOpened": live_state.elite_opened, + "points": live_state.points, + "reasons": reasons, + } + ) + continue + qualified.append((account, live_state)) + + # 积分和宝典开通不淘汰账号,只影响后续处理成本。优先选已经可直接兑换的账号, + # 其次是只需充值、只需开通、两者都需要的账号。 + qualified.sort( + key=lambda item: ( + item[1].readiness_rank(required_points=required_points), + int(item[1].points or 0), + int(item[0].id), + ) + ) + for account, live_state in qualified: + candidate = AccountCandidate( + account_id=int(account.id), + username=str(account.username or ""), + nickname=str(account.nickname or ""), + points=int(live_state.points or 0), + gold_balance=account.gold_balance, + points_expire_at=account.points_expire_at, + role_change_available_at=live_state.role_change_available_at, + ) lease = lease_account( db, candidate=candidate, holder_user_id=current.id, task_id=task.id, commodity_id=task.commodity_id, - ttl_minutes=VALIDATION_LEASE_MINUTES, + ttl_minutes=lease_duration_minutes, ) if lease is not None: selected = candidate + selected_state = live_state break - if selected is None or lease is None: + diagnostics.append( + { + "accountId": int(account.id), + "accountName": live_state.account_name, + "ck": live_state.ck_verdict, + "eliteOpened": live_state.elite_opened, + "points": live_state.points, + "reasons": ["账号刚被其他任务占用"], + } + ) + if selected is None or selected_state is None or lease is None: task.execution_status = "ready" task.issue_code = "no_eligible_account" - task.last_error = "当前没有满足 CK、积分、限兑和换绑条件的斗鱼账号" + if not candidates: + task.last_error = "没有带 CK、允许自动管理且未停用的斗鱼账号" + else: + summary = ";".join( + f"{item['accountName']}: {', '.join(item['reasons'][:3])}" + for item in diagnostics[:5] + ) + task.last_error = ( + f"已实时检测 {len(diagnostics)} 个账号,当前没有可用账号" + + (f"。{summary}" if summary else "") + )[:500] task.updated_at = _now() - _append_event(db, task.id, "account_allocation_failed") + _append_event( + db, + task.id, + "account_allocation_failed", + detail={ + "candidateCount": len(candidates), + "diagnostics": diagnostics, + }, + ) db.commit() return get_task_detail(db, task.id) @@ -524,9 +666,25 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any] task.operator_id = current.id task.execution_status = "allocated" task.binding_status = "not_started" - task.exchange_status = "not_started" - task.issue_code = "" - task.last_error = "" + soft_reasons = selected_state.soft_requirement_reasons( + required_points=required_points + ) + if task.commodity_id in selected_state.limited_ids: + task.exchange_status = "limited" + task.issue_code = "commodity_limit_reached" + task.last_error = "该账号已达到此商品兑换上限" + elif selected_state.elite_opened is not True: + task.exchange_status = "not_opened" + task.issue_code = "elite_not_opened" + task.last_error = "账号尚未开通精英宝典,可开通后继续" + elif selected_state.points is None or selected_state.points < required_points: + task.exchange_status = "points_short" + task.issue_code = "points_short" + task.last_error = "账号积分不足,可充值后继续" + else: + task.exchange_status = "eligible" + task.issue_code = "" + task.last_error = "" task.updated_at = _now() _append_event( db, @@ -538,6 +696,9 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any] "accountId": selected.account_id, "accountName": selected.display_name, "points": selected.points, + "eliteOpened": selected_state.elite_opened, + "softReasons": soft_reasons, + "exchangeStatus": task.exchange_status, }, ) db.commit() @@ -613,7 +774,7 @@ async def start_binding(db: Session, *, task_id: int, current: User) -> dict[str renew_lease( db, lease, - ttl_minutes=BINDING_LEASE_MINUTES, + ttl_minutes=_lease_duration_minutes(db), ) _append_event( db, @@ -696,7 +857,7 @@ async def confirm_binding( task.execution_status = "binding_confirming" task.operator_id = current.id task.updated_at = _now() - renew_lease(db, lease, ttl_minutes=BINDING_LEASE_MINUTES) + renew_lease(db, lease, ttl_minutes=_lease_duration_minutes(db)) _append_event( db, task.id, @@ -737,7 +898,7 @@ def refresh_exchange_eligibility( ) account.elite_opened = bool(eligibility.elite_user_info.get("manual_type")) account.points = eligibility.points - except DouyuActivityError as exc: + except Exception as exc: # noqa: BLE001 外部接口错误要落成可重试的检查失败 task.execution_status = "manual_required" task.exchange_status = "check_failed" task.issue_code = "eligibility_check_failed" @@ -770,9 +931,9 @@ def refresh_exchange_eligibility( task.exchange_status = "eligible" task.issue_code = "" task.last_error = "" - task.execution_status = ( - "manual_required" if task.exchange_status != "eligible" else "bound" - ) + # 积分不足、未开通和限兑都不是流程终点:角色已经绑定,账号继续保留, + # 后续充值/开通/解除限兑后刷新资格即可。 + task.execution_status = "bound" task.updated_at = _now() account.updated_at = _now() _append_event( diff --git a/web/frontend/src/api/platformFulfillment.ts b/web/frontend/src/api/platformFulfillment.ts index 990a4a2..abe6202 100644 --- a/web/frontend/src/api/platformFulfillment.ts +++ b/web/frontend/src/api/platformFulfillment.ts @@ -3,9 +3,19 @@ import type { PlatformFulfillmentDetail, PlatformFulfillmentListResponse, PlatformFulfillmentMapping, + PlatformFulfillmentSettings, } from './types'; export const platformFulfillmentApi = { + getSettings: () => + api.get( + '/platform-fulfillment/settings', + ), + updateSettings: (leaseDurationMinutes: number | null) => + api.put( + '/platform-fulfillment/settings', + { lease_duration_minutes: leaseDurationMinutes }, + ), listTasks: (params: { status?: string; keyword?: string; diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index b6f2270..14bb542 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -2118,6 +2118,11 @@ export interface PlatformFulfillmentAccount { roleChangeAvailableAt: string | null; } +export interface PlatformFulfillmentSettings { + leaseDurationMinutes: number | null; + updatedAt: string | null; +} + export interface PlatformFulfillmentBindTask { id: number; taskType: string; @@ -2162,7 +2167,7 @@ export interface PlatformFulfillmentTask { createdAt: string; updatedAt: string; account: PlatformFulfillmentAccount | null; - lease: { id: number; status: string; expiresAt: string } | null; + lease: { id: number; status: string; expiresAt: string | null } | null; bindTask: PlatformFulfillmentBindTask | null; } diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index 19aa805..772d3d1 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -1,9 +1,9 @@ import { useCallback, useEffect, useState } from 'react'; -import { Alert, Button, Card, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd'; -import { CheckCircleOutlined, CopyOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SyncOutlined, UserSwitchOutlined } from '@ant-design/icons'; +import { Alert, Button, Card, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd'; +import { CheckCircleOutlined, CopyOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, SyncOutlined, UserSwitchOutlined } from '@ant-design/icons'; import type { ColumnsType } from 'antd/es/table'; import { douyuApi, platformFulfillmentApi } from '../api/modules'; -import type { DouyuGoodsItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentTask } from '../api/modules'; +import type { DouyuGoodsItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules'; import { getErrorMessage } from '../utils/error'; import { message } from '../utils/antdMessage'; import { formatTime } from '../utils/time'; @@ -39,14 +39,180 @@ const STATUS_COLORS: Record = { cancelled: 'default', }; +const BINDING_STATUS_LABELS: Record = { + not_started: '未开始', + preparing: '准备中', + qr_pending: '待扫码', + role_ready: '待确认角色', + bound: '已绑定', + failed: '绑定失败', +}; + +const EXCHANGE_STATUS_LABELS: Record = { + not_started: '未开始', + eligible: '可兑换', + points_short: '积分不足', + not_opened: '精英宝典未开通', + limited: '已达限兑上限', + check_failed: '资格查询失败', + manual_done: '人工兑换完成', +}; + +const ACTOR_TYPE_LABELS: Record = { + system: '系统', + user: '运营', + customer: '客户', + connector: '连接器', +}; + +const EVENT_LABELS: Record = { + task_created: '同步人工履约订单', + mapping_updated: '更新商品映射', + account_allocation_failed: '自动选号未找到可分配账号', + account_allocated: '账号分配成功', + account_released: '释放履约账号', + binding_started: '开始绑定游戏角色', + binding_confirm_started: '提交角色绑定确认', + eligibility_check_failed: '兑换资格查询失败', + exchange_eligibility_checked: '刷新兑换资格', + manual_exchange_completed: '人工兑换完成', + marked_manual_required: '转人工处理', + task_cancelled: '任务已取消', +}; + +const ISSUE_LABELS: Record = { + mapping_missing: '商品映射缺失', + no_eligible_account: '没有可分配账号', + points_short: '积分不足', + elite_not_opened: '精英宝典未开通', + commodity_limit_reached: '商品已达限兑上限', + eligibility_check_failed: '资格查询失败', + binding_failed: '绑定失败', + lease_expired: '账号租约已过期', + manual_required: '需要人工处理', +}; + function statusLabel(value: string) { return STATUS_OPTIONS.find((item) => item.value === value)?.label || value; } +function bindingStatusLabel(value: string) { + return BINDING_STATUS_LABELS[value] || '未知状态'; +} + +function exchangeStatusLabel(value: string) { + return EXCHANGE_STATUS_LABELS[value] || '未知状态'; +} + +function issueLabel(value: string) { + if (!value) return '-'; + return ISSUE_LABELS[value] || '其他处理事项'; +} + +function exchangeStatusHint(status: string) { + if (status === 'points_short') return '当前积分不足,账号不会被淘汰。完成充值后点击“刷新兑换资格”即可继续。'; + if (status === 'not_opened') return '账号尚未开通精英宝典,不会被淘汰。开通后点击“刷新兑换资格”即可继续。'; + if (status === 'limited') return '当前账号已达到该商品限兑上限,可等待限制解除、人工处理或释放后换号。'; + if (status === 'check_failed') return '实时查询失败,账号仍保留。请稍后重新刷新兑换资格。'; + if (status === 'eligible') return '账号已满足当前商品兑换条件,可以继续人工兑换。'; + return ''; +} + +function ckStatusLabel(status: string) { + if (status === 'valid') return '有效'; + if (status === 'invalid') return '已失效'; + if (status === 'error') return '查询异常'; + return '未检测'; +} + +function eliteOpenedLabel(value: boolean | null) { + if (value === true) return '已开通'; + if (value === false) return '未开通'; + return '未知'; +} + +function bindStatusLabel(value: string) { + if (value === 'bound') return '已绑定'; + if (value === 'unbound') return '未绑定'; + if (value === 'pending') return '待确认'; + return '未知'; +} + +function providerLabel(value: string) { + if (value === 'livehub_douyu_dev') return '斗鱼联调'; + if (!value) return '-'; + return /^[a-z0-9_-]+$/i.test(value) ? '外部订单' : value; +} + +function eventLabel(value: string) { + return EVENT_LABELS[value] || '履约记录'; +} + +function eventColor(value: string) { + if (value.includes('failed') || value.includes('cancelled')) return 'red'; + if (value.includes('manual_required')) return 'orange'; + if (value.includes('completed') || value.includes('allocated')) return 'green'; + return 'blue'; +} + +function eventDescription(event: { eventType: string; detail: Record }) { + const detail = event.detail || {}; + if (event.eventType === 'account_allocation_failed') { + const diagnostics = Array.isArray(detail.diagnostics) ? detail.diagnostics : []; + const lines = diagnostics.slice(0, 3).map((item) => { + const row = item && typeof item === 'object' ? (item as Record) : {}; + const name = String(row.accountName || `账号 ${row.accountId || '-'}`); + const reasons = Array.isArray(row.reasons) ? row.reasons.map(String) : []; + return `${name}:${reasons.join('、') || '未满足分配条件'}`; + }); + return lines.join(';') || '本批账号均不满足当前分配条件'; + } + if (event.eventType === 'account_allocated') { + const reasons = Array.isArray(detail.softReasons) ? detail.softReasons.map(String) : []; + const base = `账号 ${String(detail.accountName || '-')},实时积分 ${String(detail.points ?? '-')}`; + return reasons.length ? `${base};后续需要:${reasons.join('、')}` : `${base};可直接兑换`; + } + if (event.eventType === 'mapping_updated') { + return `斗鱼商品 ${String(detail.commodityId || '-')},映射${detail.enabled === false ? '已停用' : '已启用'}`; + } + if (event.eventType === 'exchange_eligibility_checked') { + return `兑换状态:${exchangeStatusLabel(String(detail.exchangeStatus || ''))};限兑商品 ${String(detail.limitedCount ?? 0)} 个`; + } + if (event.eventType === 'eligibility_check_failed') { + return '实时查询兑换资格失败,可稍后重试'; + } + if (event.eventType === 'account_released') { + return `释放原因:${String(detail.reason || '人工释放')}`; + } + if (event.eventType === 'manual_exchange_completed') { + return String(detail.note || '运营已确认人工兑换完成'); + } + if (event.eventType === 'marked_manual_required') { + return String(detail.reason || '已转人工处理'); + } + if (event.eventType === 'task_cancelled') { + return `取消原因:${String(detail.reason || '人工取消')}`; + } + if (event.eventType === 'binding_started') return '已生成客户绑定二维码'; + if (event.eventType === 'binding_confirm_started') return '已提交游戏角色绑定确认'; + if (event.eventType === 'task_created') return '订单已进入直播账号履约工作台'; + return '履约状态已更新'; +} + function money(fen: number) { return `¥${(Number(fen || 0) / 100).toFixed(2)}`; } +function leaseDurationLabel(minutes: number | null | undefined) { + if (minutes == null) return '无限制'; + if (minutes % 60 === 0) return `${minutes / 60} 小时`; + return `${minutes} 分钟`; +} + +function leaseExpiresLabel(expiresAt: string | null | undefined) { + return expiresAt ? formatTime(expiresAt) : '无限制'; +} + export default function PlatformFulfillmentPage() { const user = getUser(); const { can } = usePermissions(user); @@ -70,6 +236,11 @@ export default function PlatformFulfillmentPage() { const [goods, setGoods] = useState([]); const [mappingGoodsLoading, setMappingGoodsLoading] = useState(false); const [mappings, setMappings] = useState([]); + const [settings, setSettings] = useState(null); + const [settingsOpen, setSettingsOpen] = useState(false); + const [leaseDurationMode, setLeaseDurationMode] = useState<'unlimited' | 'minutes' | 'hours'>('unlimited'); + const [leaseDurationValue, setLeaseDurationValue] = useState(60); + const [savingSettings, setSavingSettings] = useState(false); const loadTasks = useCallback(async () => { setLoading(true); @@ -105,6 +276,13 @@ export default function PlatformFulfillmentPage() { void loadTasks(); }, [loadTasks]); + useEffect(() => { + void platformFulfillmentApi + .getSettings() + .then(setSettings) + .catch((error) => message.error(getErrorMessage(error))); + }, []); + useEffect(() => { if (selectedId) void loadDetail(selectedId); }, [loadDetail, selectedId]); @@ -207,6 +385,47 @@ export default function PlatformFulfillmentPage() { } }; + const openLeaseSettings = () => { + const minutes = settings?.leaseDurationMinutes ?? null; + if (minutes == null) { + setLeaseDurationMode('unlimited'); + setLeaseDurationValue(60); + } else if (minutes % 60 === 0) { + setLeaseDurationMode('hours'); + setLeaseDurationValue(minutes / 60); + } else { + setLeaseDurationMode('minutes'); + setLeaseDurationValue(minutes); + } + setSettingsOpen(true); + }; + + const saveLeaseSettings = async () => { + const minutes = + leaseDurationMode === 'unlimited' + ? null + : leaseDurationMode === 'hours' + ? Number(leaseDurationValue || 0) * 60 + : Number(leaseDurationValue || 0); + if (minutes != null && minutes < 1) { + message.warning('租约时长至少为 1 分钟'); + return; + } + setSavingSettings(true); + try { + const result = await platformFulfillmentApi.updateSettings(minutes); + setSettings(result); + setSettingsOpen(false); + message.success(`租约设置已更新为${leaseDurationLabel(result.leaseDurationMinutes)}`); + if (selectedId) await loadDetail(selectedId); + await loadTasks(); + } catch (error) { + message.error(getErrorMessage(error)); + } finally { + setSavingSettings(false); + } + }; + const columns: ColumnsType = [ { title: '订单 / 商品', @@ -217,7 +436,7 @@ export default function PlatformFulfillmentPage() { {task.platformOrderId || `#${task.sourceOrderId}`} {task.skuName || task.internalSkuKey || '-'} - {task.provider || '-'} / {task.shopName || task.shopId || '-'} + {providerLabel(task.provider)} / {task.shopName || task.shopId || '-'} ), @@ -251,7 +470,7 @@ export default function PlatformFulfillmentPage() { 积分 {task.account.points ?? '-'} · 鱼翅 {task.account.goldBalance ?? '-'} - 租约 {task.lease?.status || '-'} · {formatTime(task.lease?.expiresAt)} + 租约 {task.lease ? '占用中' : '未占用'} · {task.lease ? leaseExpiresLabel(task.lease.expiresAt) : '-'} ) : ( @@ -264,8 +483,8 @@ export default function PlatformFulfillmentPage() { width: 180, render: (_, task) => ( - {task.bindingStatus} - {task.bindTask?.roleName || task.bindTask?.bindPhase || '-'} + {bindingStatusLabel(task.bindingStatus)} + {task.bindTask?.roleName || (task.bindTask?.bindPhase === 'role_ready' ? '角色待确认' : '-')} ), }, @@ -276,7 +495,7 @@ export default function PlatformFulfillmentPage() { render: (_, task) => ( {statusLabel(task.executionStatus)} - 兑换:{task.exchangeStatus} + 兑换:{exchangeStatusLabel(task.exchangeStatus)} ), }, @@ -362,6 +581,14 @@ export default function PlatformFulfillmentPage() { 读取 order_site 人工订单,客户扫码绑定游戏角色,运营使用斗鱼账号人工兑换。 + 账号租约:{leaseDurationLabel(settings?.leaseDurationMinutes)} + @@ -417,43 +644,131 @@ export default function PlatformFulfillmentPage() { /> - setSelectedId(null)}> + + + {statusLabel(selected.executionStatus)} + + {exchangeStatusLabel(selected.exchangeStatus)} + + ) : null + } + onClose={() => setSelectedId(null)} + > {detailLoading || !selected ? ( 加载中... ) : ( - {selected.lastError ? : null} - - - {selected.skuName} - - {selected.internalSkuKey || '-'} - {selected.commodityId || '-'} - {money(selected.orderAmountFen)} - {selected.requiredPoints ?? '-'} - {statusLabel(selected.executionStatus)} - {selected.bindingStatus} - {selected.exchangeStatus} - {selected.account?.nickname || selected.account?.username || '-'} - + {selected.issueCode || selected.lastError ? ( + + ) : exchangeStatusHint(selected.exchangeStatus) ? ( + + ) : null} + +
+ + + + {selected.platformOrderId || '-'} + + + {selected.skuName || selected.internalSkuKey || '-'} + + + {selected.internalSkuKey || '-'} + + + {selected.commodityId || '未映射'} + + {money(selected.orderAmountFen)} + {selected.requiredPoints ?? '-'} + {statusLabel(selected.executionStatus)} + {bindingStatusLabel(selected.bindingStatus)} + {exchangeStatusLabel(selected.exchangeStatus)} + {issueLabel(selected.issueCode)} + + + + + {selected.account ? ( + + + {selected.account.nickname || selected.account.username} + + + {ckStatusLabel(selected.account.ckCheckStatus)} + + + {eliteOpenedLabel(selected.account.eliteOpened)} + + {selected.account.points ?? '-'} + {selected.account.goldBalance ?? '-'} + + {bindStatusLabel(selected.account.roleBindStatus)} + + {selected.account.gameName || '-'} + + {selected.account.gameChannel || '-'} + + + {formatTime(selected.account.roleChangeAvailableAt) || '无冷却'} + + + {selected.lease ? leaseExpiresLabel(selected.lease.expiresAt) : '-'} + + + ) : ( + + )} + +
+ {actionButtons} - - ({ - color: event.eventType.includes('failed') ? 'red' : 'blue', - children: ( - - {event.eventType} - - {formatTime(event.createdAt)} · {event.actorType} - {event.actorId ? ` ${event.actorId}` : ''} - - - ), - }))} - /> + +
+ Date.parse(right.createdAt) - Date.parse(left.createdAt)) + .slice(0, 50) + .map((event) => ({ + color: eventColor(event.eventType), + children: ( + + {eventLabel(event.eventType)} + {eventDescription(event)} + + {formatTime(event.createdAt)} · {ACTOR_TYPE_LABELS[event.actorType] || '系统'} + {event.actorId ? ` · 操作人 ${event.actorId}` : ''} + + + ), + }))} + /> +
)} @@ -477,6 +792,44 @@ export default function PlatformFulfillmentPage() { + void saveLeaseSettings()} + onCancel={() => setSettingsOpen(false)} + > + + setLeaseDurationMode(value as 'unlimited' | 'minutes' | 'hours')} + options={[ + { label: '无限制', value: 'unlimited' }, + { label: '按分钟', value: 'minutes' }, + { label: '按小时', value: 'hours' }, + ]} + /> + {leaseDurationMode !== 'unlimited' ? ( + + ) : null} + + + + void saveMapping()} onCancel={() => setMappingOpen(false)}> setMappingSku(event.target.value)} />