diff --git a/.env.example b/.env.example index 89b4447..920982e 100644 --- a/.env.example +++ b/.env.example @@ -161,6 +161,10 @@ INTEGRATION_OUTBOX_MAX_ATTEMPTS=12 PLATFORM_FULFILLMENT_RECONCILE_SECONDS=900 # 可选:指定集成操作人;不填时使用最早创建的有效超级管理员 # PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID=1 +# 账号商品能力快照有效期(秒);过期后不再直接参与自动匹配 +ACCOUNT_COMMODITY_STATE_TTL_SECONDS=900 +# legacy=旧实时扫号 / hybrid=能力索引优先、失败回退旧逻辑 / capability=只读能力索引 +PLATFORM_FULFILLMENT_MATCH_MODE=hybrid # 客户绑定二维码有效期 PLATFORM_BINDING_QR_TTL_SECONDS=600 diff --git a/docker-compose.yml b/docker-compose.yml index 38886e5..afbb02c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -89,6 +89,8 @@ services: - PLATFORM_FULFILLMENT_INTEGRATION_KEY=${PLATFORM_FULFILLMENT_INTEGRATION_KEY:-} - ORDER_SITE_PLATFORM_FULFILLMENT_URL=${ORDER_SITE_PLATFORM_FULFILLMENT_URL:-} - PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID=${PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID:-} + - ACCOUNT_COMMODITY_STATE_TTL_SECONDS=${ACCOUNT_COMMODITY_STATE_TTL_SECONDS:-900} + - PLATFORM_FULFILLMENT_MATCH_MODE=${PLATFORM_FULFILLMENT_MATCH_MODE:-hybrid} - PLATFORM_BINDING_QR_TTL_SECONDS=${PLATFORM_BINDING_QR_TTL_SECONDS:-600} # 用户上传图片的桶(在线协作 / P2 资料收集共用;生产用内网 endpoint)。 # OSS_MODE=oss 才走对象存储,否则落容器内 ./data/file_storage。 diff --git a/docs/直播账号履约工作台.md b/docs/直播账号履约工作台.md index 395dc63..10d50a8 100644 --- a/docs/直播账号履约工作台.md +++ b/docs/直播账号履约工作台.md @@ -58,6 +58,21 @@ - 下一次点击会优先检测尚未检测或最久未检测的下一批账号; - 实时刷新完成后才判断是否创建租约,失败事件会记录每个账号的具体原因。 +2026-11-18 起增加“能力索引优先”的混合匹配: + +- 一键查询或资料刷新把官方 `storehome` 商品状态写入 `account_commodity_states`; +- `storehome` 一次返回账号可见的全部商品,逐商品写状态,但每个账号只需一次列表请求; +- 同时保存 `timeLimited`、`specTimes` 和起止时间,未开始/已结束与账号限兑分别处理; +- `PLATFORM_FULFILLMENT_MATCH_MODE=hybrid` 时先查新鲜能力索引,没有结果再回退旧扫号; +- `capability` 模式只读能力索引,不执行全量候选扫描; +- `legacy` 模式保留旧逻辑,用于快速回滚; +- 能力索引命中后仍只对最终候选做一次实时确认,避免缓存过期直接分配; +- 有 pending 履约需求时,`account_capability_refresh` 作业优先刷新对应商品的过期能力。 + +能力快照默认 15 分钟有效,可用 `ACCOUNT_COMMODITY_STATE_TTL_SECONDS` 调整。 +过期能力不会直接参与自动匹配。真正创建租约仍然依赖账号租约唯一约束, +因此并发 worker 不会把同一账号分配给两张订单。 + 选号硬条件只保留:CK 实时有效、未达到该商品官方限兑上限、角色换绑冷却已结束、 无有效租约。积分不足和精英宝典未开通属于**软条件**: diff --git a/docs/设计-账号全生命周期.md b/docs/设计-账号全生命周期.md index e449f59..863b1ec 100644 --- a/docs/设计-账号全生命周期.md +++ b/docs/设计-账号全生命周期.md @@ -72,6 +72,7 @@ CK 本体和健康结果都在账号上: - `lifecycle`:状态变迁; - `auth`:登录、CK 失效、CK 清除; - `business`:充值、兑换、积分、到期、开通、鱼翅消耗; +- `activity`:查询、绑定、开通、充值等账号任务的创建与终态; - `ops`:分配、标签、备注、人工操作。 `source_ref` 是可选幂等键。重复查询官方记录或重复发射事件时,唯一键冲突按幂等命中处理, @@ -92,8 +93,34 @@ CK 本体和健康结果都在账号上: 不返回整份快照,避免响应体积膨胀。 `high_value_checked_at` 是“最近一次形成高价值结论”的时钟,结论本身可以为 `unknown`;它不表示每次执行都成功读到了可用的官方 `status`。 -一键查询本身是只读聚合,不直接修改生命周期状态;官方兑换记录会以 -`source=official_sync` 幂等补入事件流。 +一键查询不修改账号生命周期状态;官方兑换记录会以 +`source=official_sync` 幂等补入事件流。查询任务本身会由统一执行器写入 +`activity` 分类的 `task_started / task_succeeded / task_failed / task_stopped` +事件,因此账号详情能查到“某次查询/绑定是否执行、何时完成、失败原因是什么”, +但不会把扫码轮询的每一次请求都写成事件。 + +## 账号商品能力索引 + +账号“是否可登录”和“能否兑换某件商品”是两层状态。前者继续存 `accounts`, +后者存 `account_commodity_states`: + +- `availability`:`available / limited / no_stock / not_open / expired / not_offered / unknown`; +- `observed_at` / `valid_until` / `next_check_at`:区分最后确认时间和可用期限; +- `time_limited` / `available_from` / `available_until` / `schedule_json`: + 保存 `storehome.timeLimited`、`startTime/endTime` 与 `specTimes`,区分未开始、进行中和已结束; +- `last_exchange_at` / `exchange_count_365d`:从 `account_events` 派生的兑换摘要; +- 真正发生过的兑换仍然只追加到 `account_events.exchange`。 + +一键查询拿到完整 `storehome` 商品列表后,会在同一个事务里更新账号快照和商品能力。 +商品接口失败时**不更新**能力,避免把“没查到”写成“不可兑换”。CK 由好变坏时, +该账号所有 `available` 能力立即作废为 `unknown`。 + +官方 `storehome` 一次返回完整商品列表,因此一个账号一次请求即可写入全部商品状态, +不需要按商品逐个请求。账号级 `status=1` 表示达到限兑上限;`timeLimited/specTimes` +是商品开放窗口。时间窗口优先判断:未开始、已结束不会被误写成“该账号已兑换”。 + +履约匹配只读取新鲜的能力索引,并对最终选中的账号做一次实时确认。能力索引不是 +第二套账号主数据,而是账号当前状态和商品目录的查询投影。 ## 高价值套装的准入判定 @@ -148,6 +175,7 @@ CK 本体和健康结果都在账号上: - 高价值账号优先巡检,其余按最久未检测排序。 - 非鉴权失败计入 `error`,失败率过高时自动暂停作业。 - 资料刷新只处理 `ck_check_status=valid`、允许自动管理且非人工态的账号。 +- 履约商品能力刷新只处理“有 pending 任务且快照已过期”的账号,避免无条件全量轮询。 - “从未查询过”的账号优先于“查询结果已过期”的账号。 - **高价值结论有自己的时钟**:资料刷新除了看 `overview_queried_at`, 还看 `high_value_checked_at`。两者会脱钩 —— 一键查询里商品接口单独失败时 diff --git a/tests/test_account_capability_refresh_job.py b/tests/test_account_capability_refresh_job.py new file mode 100644 index 0000000..adabe28 --- /dev/null +++ b/tests/test_account_capability_refresh_job.py @@ -0,0 +1,123 @@ +"""履约需求驱动的账号商品能力刷新作业。""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +from web.backend.models import ( + Account, + AccountCommodityState, + AccountLease, + AutomationJob, + PlatformFulfillmentTask, + User, +) +from web.backend.services.automation.jobs import account_capability_refresh as job + +NOW = datetime.now(UTC).replace(microsecond=0) + + +def _account(db, name: str) -> Account: + row = Account( + username=name, + password="p", + email=f"{name}@example.com", + email_password="ep", + cookie="acf_uid=1; acf_ccn=c", + ck_check_status="valid", + status="active", + auto_managed=True, + overview_queried_at=NOW - timedelta(days=1), + ) + db.add(row) + db.flush() + return row + + +def _state( + db, + account: Account, + *, + commodity_id: str = "C", + valid_until: datetime | None = None, +) -> AccountCommodityState: + row = AccountCommodityState( + account_id=account.id, + platform="douyu", + scope="elite", + commodity_id=commodity_id, + availability="available", + observed_at=NOW - timedelta(hours=2), + valid_until=valid_until, + next_check_at=valid_until, + ) + db.add(row) + return row + + +def test_selects_only_stale_demand_accounts(db): + user = User( + username="cap-refresh-admin", + password_hash="h", + role="super_admin", + is_active=True, + ) + db.add(user) + db.flush() + db.add( + PlatformFulfillmentTask( + source_system="order_site", + source_order_id="1", + source_order_item_id="1", + internal_sku_key="skin", + commodity_id="C", + execution_status="ready", + binding_status="not_started", + exchange_status="not_started", + paid_at=NOW, + ) + ) + stale = _account(db, "cap-stale") + fresh = _account(db, "cap-fresh") + other = _account(db, "cap-other") + leased = _account(db, "cap-leased") + _state(db, stale, valid_until=NOW - timedelta(minutes=1)) + _state(db, fresh, valid_until=NOW + timedelta(hours=1)) + _state(db, other, commodity_id="OTHER", valid_until=NOW - timedelta(minutes=1)) + _state(db, leased, valid_until=NOW - timedelta(minutes=1)) + db.add( + AccountLease( + account_id=leased.id, + holder_user_id=user.id, + scope="elite", + purpose="platform_fulfillment", + status="active", + ) + ) + db.commit() + automation_job = AutomationJob( + key=job.JOB_KEY, + title="履约商品能力补充刷新", + interval_seconds=3600, + batch_size=10, + concurrency=3, + ) + + selected = job.build_select_query(db, automation_job, NOW).all() + + assert [row.id for row in selected] == [stale.id] + + +def test_no_pending_task_means_no_refresh(db): + stale = _account(db, "cap-no-demand") + _state(db, stale, valid_until=NOW - timedelta(minutes=1)) + db.commit() + automation_job = AutomationJob( + key=job.JOB_KEY, + title="履约商品能力补充刷新", + interval_seconds=3600, + batch_size=10, + concurrency=3, + ) + + assert job.build_select_query(db, automation_job, NOW).all() == [] diff --git a/tests/test_account_capability_service.py b/tests/test_account_capability_service.py new file mode 100644 index 0000000..68123d6 --- /dev/null +++ b/tests/test_account_capability_service.py @@ -0,0 +1,300 @@ +"""账号商品能力索引与兑换历史投影。""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +from web.backend.models import Account, AccountCommodityState, AccountEvent, User +from web.backend.routers.accounts import account_commodities +from web.backend.services import account_capability_service as service + +NOW = datetime.now(UTC).replace(microsecond=0) + + +def _account(db, name: str = "cap-account") -> Account: + account = Account( + username=name, + password="p", + email=f"{name}@example.com", + email_password="ep", + cookie="acf_uid=1; acf_ccn=c", + ck_check_status="valid", + status="active", + auto_managed=True, + ) + db.add(account) + db.commit() + return account + + +def test_classify_goods_item_keeps_unknown_when_status_missing(): + available, reason, raw = service.classify_goods_item({"status": 0}) + assert (available, reason, raw) == ("available", "", "0") + + limited, reason, raw = service.classify_goods_item({"status": "1"}) + assert (limited, reason, raw) == ("limited", "该账号已达此商品兑换上限", "1") + + no_stock, reason, _ = service.classify_goods_item( + {"status": 0, "storeStatus": 0} + ) + assert (no_stock, reason) == ("no_stock", "官方商城当前无库存") + + unknown, reason, raw = service.classify_goods_item({}) + assert unknown == "unknown" + assert "未返回" in reason + assert raw == "" + + +def test_time_limited_goods_use_schedule_before_account_limit(): + limited = { + "status": "1", + "timeLimited": 1, + "startTime": str(int((NOW - timedelta(hours=1)).timestamp())), + "endTime": str(int((NOW + timedelta(hours=1)).timestamp())), + "specTimes": [ + { + "startTime": str(int((NOW - timedelta(hours=1)).timestamp())), + "endTime": str(int((NOW + timedelta(hours=1)).timestamp())), + } + ], + } + availability, reason, _ = service.classify_goods_item(limited, now=NOW) + assert availability == "limited" + assert "上限" in reason + + future = { + "status": "1", + "timeLimited": 1, + "startTime": str(int((NOW + timedelta(hours=2)).timestamp())), + "endTime": str(int((NOW + timedelta(hours=3)).timestamp())), + } + availability, reason, _ = service.classify_goods_item(future, now=NOW) + assert availability == "not_open" + assert "未开始" in reason + + expired = { + "status": "0", + "timeLimited": 1, + "startTime": str(int((NOW - timedelta(hours=3)).timestamp())), + "endTime": str(int((NOW - timedelta(hours=2)).timestamp())), + } + availability, reason, _ = service.classify_goods_item(expired, now=NOW) + assert availability == "expired" + assert "已结束" in reason + + +def test_sync_stores_time_window_and_next_boundary(db): + account = _account(db, "cap-window") + end_at = NOW + timedelta(minutes=5) + service.sync_account_goods_states( + db, + account, + [ + { + "commodityId": "LIMITED", + "commodityName": "套装-兔兔白日梦", + "status": "1", + "timeLimited": 1, + "startTime": str(int((NOW - timedelta(days=1)).timestamp())), + "endTime": str(int(end_at.timestamp())), + "specTimes": [ + { + "startTime": str(int((NOW - timedelta(days=1)).timestamp())), + "endTime": str(int(end_at.timestamp())), + } + ], + } + ], + observed_at=NOW, + ) + db.commit() + + state = ( + db.query(AccountCommodityState) + .filter_by(account_id=account.id, commodity_id="LIMITED") + .one() + ) + assert state.availability == "limited" + assert state.time_limited is True + assert state.available_until == end_at + assert state.next_check_at == end_at + assert state.schedule_json + + +def test_sync_account_goods_states_writes_capabilities_and_exchange_stats(db): + account = _account(db) + db.add( + AccountEvent( + account_id=account.id, + event_type="exchange", + category="business", + occurred_at=NOW - timedelta(days=10), + title="兑换 A", + source="official_sync", + subject_type="commodity", + subject_key="A", + ) + ) + db.commit() + + changed = service.sync_account_goods_states( + db, + account, + [ + {"commodityId": "A", "name": "商品 A", "status": "0"}, + {"commodityId": "B", "name": "商品 B", "status": "1"}, + {"commodityId": "C", "name": "商品 C", "status": "0", "storeStatus": 0}, + {"commodityId": "D", "name": "商品 D"}, + ], + observed_at=NOW, + ) + db.commit() + + assert changed == 4 + states = { + row.commodity_id: row + for row in db.query(AccountCommodityState).filter_by(account_id=account.id) + } + assert states["A"].availability == "available" + assert states["A"].exchange_count_365d == 1 + assert states["A"].last_exchange_at == NOW - timedelta(days=10) + assert states["B"].availability == "limited" + assert states["C"].availability == "no_stock" + assert states["D"].availability == "unknown" + assert states["A"].valid_until == NOW + timedelta( + seconds=service.capability_ttl_seconds() + ) + + +def test_next_sync_marks_missing_goods_not_offered(db): + account = _account(db, "cap-remove") + service.sync_account_goods_states( + db, + account, + [ + {"commodityId": "A", "status": "0"}, + {"commodityId": "B", "status": "0"}, + ], + observed_at=NOW, + ) + db.commit() + + service.sync_account_goods_states( + db, + account, + [{"commodityId": "A", "status": "0"}], + observed_at=NOW + timedelta(minutes=1), + ) + db.commit() + + removed = ( + db.query(AccountCommodityState) + .filter_by(account_id=account.id, commodity_id="B") + .one() + ) + assert removed.availability == "not_offered" + assert removed.valid_until is None + + +def test_mark_exchange_keeps_projection_in_sync(db): + account = _account(db, "cap-exchange") + service.sync_account_goods_states( + db, + account, + [{"commodityId": "A", "name": "商品 A", "status": "0"}], + observed_at=NOW, + ) + db.commit() + + occurred_at = NOW + timedelta(minutes=2) + db.add( + AccountEvent( + account_id=account.id, + event_type="exchange", + category="business", + occurred_at=occurred_at, + title="兑换 商品 A", + source="douyu_task", + subject_type="commodity", + subject_key="A", + ) + ) + db.flush() + service.mark_commodity_exchanged( + db, + account_id=account.id, + commodity_id="A", + occurred_at=occurred_at, + commodity_name="商品 A", + ) + db.commit() + + state = ( + db.query(AccountCommodityState) + .filter_by(account_id=account.id, commodity_id="A") + .one() + ) + assert state.availability == "limited" + assert state.exchange_count_365d == 1 + assert state.last_exchange_at == occurred_at + assert state.valid_until is None + + +def test_invalidating_ck_removes_available_from_matching_pool(db): + account = _account(db, "cap-invalid") + service.sync_account_goods_states( + db, + account, + [{"commodityId": "A", "status": "0"}], + observed_at=NOW, + ) + db.commit() + + changed = service.invalidate_account_commodity_states( + db, + account_id=account.id, + reason="CK 已失效", + observed_at=NOW + timedelta(minutes=1), + ) + db.commit() + + assert changed == 1 + state = db.query(AccountCommodityState).filter_by(account_id=account.id).one() + assert state.availability == "unknown" + assert state.valid_until is None + assert "CK" in state.blocking_reason + + +def test_account_commodities_api_returns_summary_and_freshness(db): + account = _account(db, "cap-api") + user = User( + username="cap-api-admin", + password_hash="h", + role="super_admin", + is_active=True, + ) + db.add(user) + service.sync_account_goods_states( + db, + account, + [ + {"commodityId": "A", "name": "商品 A", "status": "0"}, + {"commodityId": "B", "name": "商品 B", "status": "1"}, + ], + observed_at=NOW, + ) + db.commit() + + result = account_commodities( + account.id, + scope="", + availability="", + limit=500, + db=db, + current=user, + ) + + assert result["summary"]["total"] == 2 + assert result["summary"]["fresh_available"] == 1 + assert {item["commodity_id"] for item in result["items"]} == {"A", "B"} + assert all(item["fresh"] for item in result["items"]) diff --git a/tests/test_account_lifecycle.py b/tests/test_account_lifecycle.py index bfd876d..2ba96d1 100644 --- a/tests/test_account_lifecycle.py +++ b/tests/test_account_lifecycle.py @@ -656,6 +656,15 @@ class TestLifecycleApi(_Base): assert res["success"] and account.auto_managed is False # 关掉自动化不等于停用:账号状态仍可用 assert account.status == life.STATUS_ACTIVE + event = ( + self.session.query(AccountEvent) + .filter( + AccountEvent.account_id == account.id, + AccountEvent.event_type == "automation_changed", + ) + .one() + ) + assert event.detail["to"] is False class TestStatusWriteFunnel: diff --git a/tests/test_account_overview.py b/tests/test_account_overview.py index 35df0bf..9435158 100644 --- a/tests/test_account_overview.py +++ b/tests/test_account_overview.py @@ -485,6 +485,15 @@ class TestOverviewTaskTypeWiring: .all() ) assert len(created) == len(accs) + started_events = ( + session.query(AccountEvent) + .filter(AccountEvent.event_type == "task_started") + .all() + ) + assert len(started_events) == len(accs) + assert {event.account_id for event in started_events} == { + account.id for account in accs + } finally: session.close() @@ -1113,6 +1122,8 @@ class TestOfficialExchangeBecomesAccountEvent: assert event.occurred_at.year == 2026 assert event.occurred_at.month == 8 # 1788054985 → 2026-08-30 前后 assert event.amount == -1280 + assert event.subject_type == "commodity" + assert event.subject_key == "C1" assert event.detail["source"] == "official_sync" assert event.source == "official_sync" diff --git a/tests/test_business_events.py b/tests/test_business_events.py index 79da8a0..70fbded 100644 --- a/tests/test_business_events.py +++ b/tests/test_business_events.py @@ -524,3 +524,58 @@ class TestExpireAtParsing: from web.backend.services.douyu_runner_donate import _parse_expire_at assert _parse_expire_at(value) is None, "认不出来就返回 None,不要猜一个时刻" + + +class TestAccountTaskActivity(_Base): + def test_task_start_and_result_are_written_to_account_timeline(self): + assert biz.record_douyu_task_started( + self.session, + self.account, + task_id=501, + task_type="query_account_overview", + task_label="一键查询账号信息", + scope="elite", + actor_id=self.user.id, + ) + assert biz.record_douyu_task_result( + self.session, + self.account, + task_id=501, + task_type="query_account_overview", + task_label="一键查询账号信息", + scope="elite", + status="success", + message="查询完成", + ) + self.session.commit() + + started = self.events(svc.EVENT_TASK_STARTED) + succeeded = self.events(svc.EVENT_TASK_SUCCEEDED) + assert len(started) == 1 + assert started[0].category == svc.CATEGORY_ACTIVITY + assert started[0].detail["task_id"] == 501 + assert len(succeeded) == 1 + assert succeeded[0].title == "一键查询账号信息:成功" + assert succeeded[0].detail["message"] == "查询完成" + + def test_task_result_is_idempotent(self): + kwargs = { + "task_id": 502, + "task_type": "query_points", + "task_label": "一键查询积分", + "scope": "elite", + "status": "failed", + "message": "网络失败", + } + assert biz.record_douyu_task_result( + self.session, + self.account, + **kwargs, + ) + assert not biz.record_douyu_task_result( + self.session, + self.account, + **kwargs, + ) + self.session.commit() + assert len(self.events(svc.EVENT_TASK_FAILED)) == 1 diff --git a/tests/test_migrations.py b/tests/test_migrations.py index 97f39db..9aa578d 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -25,8 +25,12 @@ import web.backend.database as database_module from tests.support.db import get_mysql_credentials, get_test_engine from web.backend.database import Base from web.backend.models import ( + Account, + AccountEvent, + AccountLease, AuditLog, HuyaExternalOrder, + PlatformFulfillmentTask, User, WeiboAccount, ) @@ -35,7 +39,7 @@ TESTS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = TESTS_DIR.parent VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" -HEAD_REVISION = "20261118_0089" +HEAD_REVISION = "20261118_0093" # 迁移新增、但不声明在模型里的复合查询索引。 EXTRA_INDEXES = ( @@ -521,3 +525,162 @@ class TestMigrationSmoke: mig_engine.dispose() with admin_engine.begin() as conn: conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;")) + + def test_0090_restores_allocated_tasks_with_active_leases(self): + creds = get_mysql_credentials() + mig_db = f"douyu_login_mig_{secrets.token_hex(4)}" + mig_url = ( + f"mysql+pymysql://{quote_plus(creds['user'])}:" + f"{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/" + f"{mig_db}?charset=utf8mb4" + ) + + admin_engine = get_test_engine() + with admin_engine.begin() as conn: + conn.execute( + text( + f"CREATE DATABASE `{mig_db}` " + "CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;" + ) + ) + + original_url = database_module.DATABASE_URL + mig_engine = create_engine(mig_url) + try: + database_module.DATABASE_URL = mig_url + cfg = _migration_config() + cfg.set_main_option("sqlalchemy.url", mig_url) + command.upgrade(cfg, "20261118_0089") + + with Session(mig_engine) as session: + user = User( + username="migration-pf-actor", + password_hash="hash", + role="super_admin", + is_active=True, + ) + account = Account( + username="migration-pf-account", + password="p", + email="migration-pf@example.com", + email_password="ep", + ) + session.add_all([user, account]) + session.commit() + lease = AccountLease( + account_id=account.id, + holder_user_id=user.id, + scope="elite", + purpose="platform_fulfillment", + status="active", + ) + session.add(lease) + session.commit() + broken = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="MIG-0090", + source_order_item_id="MIG-0090-1", + account_id=account.id, + lease_id=lease.id, + execution_status="ready", + binding_status="not_started", + exchange_status="points_short", + issue_code="", + last_error="", + ) + unassigned = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="MIG-0090", + source_order_item_id="MIG-0090-2", + execution_status="ready", + binding_status="not_started", + exchange_status="not_started", + issue_code="no_eligible_account", + last_error="当前没有可用账号", + ) + session.add_all([broken, unassigned]) + session.commit() + broken_id = broken.id + unassigned_id = unassigned.id + + command.upgrade(cfg, "20261118_0090") + + with Session(mig_engine) as session: + repaired = session.get(PlatformFulfillmentTask, broken_id) + untouched = session.get(PlatformFulfillmentTask, unassigned_id) + assert repaired is not None + assert repaired.execution_status == "allocated" + assert repaired.issue_code == "points_short" + assert repaired.last_error == "账号积分不足,可充值后继续" + assert repaired.next_allocate_at is None + assert untouched is not None + assert untouched.execution_status == "ready" + assert untouched.issue_code == "no_eligible_account" + finally: + database_module.DATABASE_URL = original_url + mig_engine.dispose() + with admin_engine.begin() as conn: + conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;")) + + def test_0092_backfills_official_exchange_subject_key(self): + creds = get_mysql_credentials() + mig_db = f"douyu_login_mig_{secrets.token_hex(4)}" + mig_url = ( + f"mysql+pymysql://{quote_plus(creds['user'])}:" + f"{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/" + f"{mig_db}?charset=utf8mb4" + ) + + admin_engine = get_test_engine() + with admin_engine.begin() as conn: + conn.execute( + text( + f"CREATE DATABASE `{mig_db}` " + "CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;" + ) + ) + + original_url = database_module.DATABASE_URL + mig_engine = create_engine(mig_url) + try: + database_module.DATABASE_URL = mig_url + cfg = _migration_config() + cfg.set_main_option("sqlalchemy.url", mig_url) + command.upgrade(cfg, "20261118_0091") + + with Session(mig_engine) as session: + account = Account( + username="migration-exchange-account", + password="p", + email="migration-exchange@example.com", + email_password="ep", + ) + session.add(account) + session.commit() + event = AccountEvent( + account_id=account.id, + event_type="exchange", + category="business", + occurred_at=datetime.now(UTC), + title="兑换测试商品", + detail={"commodity_id": "MIG-COMMODITY-0092"}, + source="official_sync", + subject_type="goods", + subject_key="", + ) + session.add(event) + session.commit() + event_id = event.id + + command.upgrade(cfg, "20261118_0092") + + with Session(mig_engine) as session: + repaired = session.get(AccountEvent, event_id) + assert repaired is not None + assert repaired.subject_type == "commodity" + assert repaired.subject_key == "MIG-COMMODITY-0092" + finally: + database_module.DATABASE_URL = original_url + mig_engine.dispose() + with admin_engine.begin() as conn: + conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;")) diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 7a8f9fa..1e51178 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -12,6 +12,8 @@ from fastapi import HTTPException from tests.support.db import get_test_engine, make_test_session from web.backend.models import ( Account, + AccountCommodityState, + AccountEvent, AccountLease, AutomationJob, DouyuGoodsSnapshot, @@ -453,6 +455,45 @@ class TestSnapshotSync(_Base): outbox = self.session.query(IntegrationOutbox).one() assert outbox.payload_json["items"][0]["stateVersion"] == 1 + def test_duplicate_snapshot_keeps_allocated_task_state(self): + self.mapping() + account = self.account("snapshot-allocated") + service.sync_order_snapshot(self.session, {"data": self.snapshot()}) + task = self.session.query(PlatformFulfillmentTask).one() + service.allocate_task( + self.session, + task_id=task.id, + current=self.admin, + ) + + service.sync_order_snapshot(self.session, {"data": self.snapshot()}) + + self.session.refresh(task) + assert task.execution_status == "allocated" + assert task.account_id == account.id + assert task.lease_id is not None + assert task.next_allocate_at is None + assert task.exchange_status == "eligible" + assert task.issue_code == "" + + def test_duplicate_snapshot_preserves_allocation_retry(self): + self.mapping() + service.sync_order_snapshot(self.session, {"data": self.snapshot()}) + task = self.session.query(PlatformFulfillmentTask).one() + retry_at = NOW + timedelta(seconds=45) + task.issue_code = "no_eligible_account" + task.last_error = "当前没有可用账号" + task.next_allocate_at = retry_at + self.session.commit() + + service.sync_order_snapshot(self.session, {"data": self.snapshot()}) + + self.session.refresh(task) + assert task.execution_status == "ready" + assert task.issue_code == "no_eligible_account" + assert task.last_error == "当前没有可用账号" + assert task.next_allocate_at == retry_at + def test_legacy_event_only_reads_the_specified_order_item(self, monkeypatch): self.mapping() requested: list[str] = [] @@ -496,6 +537,85 @@ class TestSnapshotSync(_Base): class TestAccountSelection(_Base): + def test_capability_match_checks_only_selected_candidate(self, monkeypatch): + account = self.account("capability-fast") + task = self.task() + self.session.add( + AccountCommodityState( + account_id=account.id, + platform="douyu", + scope="elite", + commodity_id=COMMODITY, + commodity_name=INTERNAL_SKU, + availability="available", + observed_at=NOW, + valid_until=NOW + timedelta(minutes=15), + source="overview", + ) + ) + self.session.commit() + monkeypatch.setenv("PLATFORM_FULFILLMENT_MATCH_MODE", "capability") + + 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_once() + + def test_hybrid_falls_back_to_live_scan_when_capability_candidate_fails( + self, + monkeypatch, + ): + capability_account = self.account("capability-stale") + live_account = self.account("live-fallback") + task = self.task() + self.session.add( + AccountCommodityState( + account_id=capability_account.id, + platform="douyu", + scope="elite", + commodity_id=COMMODITY, + availability="available", + observed_at=NOW, + valid_until=NOW + timedelta(minutes=15), + source="overview", + ) + ) + self.session.commit() + + 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=2000, + limited_ids=( + frozenset({COMMODITY}) + if account.id == capability_account.id + else frozenset() + ), + role_change_available_at=None, + ) + + self.refresh_mock.side_effect = live_state + monkeypatch.setenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid") + + detail = service.allocate_task( + self.session, + task_id=task.id, + current=self.admin, + ) + + assert detail["task"]["account"]["id"] == live_account.id + assert self.refresh_mock.call_count == 2 + def test_allocation_refreshes_live_state_instead_of_cached_filters(self): account = Account( username="live-refresh-account", @@ -678,6 +798,15 @@ class TestAccountSelection(_Base): assert lease.purpose == "platform_fulfillment" assert lease.status == "active" assert lease.expires_at is None + acquired = ( + self.session.query(AccountEvent) + .filter( + AccountEvent.account_id == account.id, + AccountEvent.event_type == "lease_acquired", + ) + .one() + ) + assert acquired.detail["task_id"] == task.id released = service.release_task_account( self.session, @@ -687,6 +816,15 @@ class TestAccountSelection(_Base): assert released["task"]["executionStatus"] == "ready" self.session.refresh(lease) assert lease.status == "released" + released_event = ( + self.session.query(AccountEvent) + .filter( + AccountEvent.account_id == account.id, + AccountEvent.event_type == "lease_released", + ) + .one() + ) + assert released_event.detail["lease_id"] == lease.id def test_lease_settings_support_unlimited_and_finite_duration(self): self.account("settings-account") diff --git a/tests/test_platform_fulfillment_auto_allocator.py b/tests/test_platform_fulfillment_auto_allocator.py index 904df5c..9066aec 100644 --- a/tests/test_platform_fulfillment_auto_allocator.py +++ b/tests/test_platform_fulfillment_auto_allocator.py @@ -124,3 +124,60 @@ def test_auto_allocator_schedules_retry_only_after_failed_allocation(db): assert result == {"checked": 1, "allocated": 0, "failed": 1} assert task.next_allocate_at is not None assert task.next_allocate_at >= moment + timedelta(seconds=10) + + +def test_auto_allocator_prioritizes_oldest_paid_task_after_due_check(db): + actor = User(username="auto-fair-actor", password_hash="h", role="super_admin") + moment = datetime.now(UTC) + db.add( + PlatformFulfillmentSetting( + id=1, + lease_duration_minutes=None, + order_match_started_at=moment - timedelta(days=1), + ) + ) + older = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="20", + source_order_item_id="20", + platform_order_id="AUTO-OLDER", + internal_sku_key="skin", + commodity_id="commodity-1", + execution_status="ready", + binding_status="not_started", + exchange_status="not_started", + paid_at=moment - timedelta(minutes=10), + next_allocate_at=moment, + updated_at=moment, + ) + newer = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="21", + source_order_item_id="21", + platform_order_id="AUTO-NEWER", + internal_sku_key="skin", + commodity_id="commodity-1", + execution_status="ready", + binding_status="not_started", + exchange_status="not_started", + paid_at=moment - timedelta(minutes=1), + next_allocate_at=moment, + updated_at=moment, + ) + db.add_all([actor, older, newer]) + db.commit() + + calls: list[int] = [] + with ( + patch.object(auto_allocator.service, "_integration_actor", return_value=actor), + patch.object( + auto_allocator.service, + "allocate_task", + side_effect=lambda _db, *, task_id, current: ( + calls.append(task_id) or {"task": {"account": {"id": 9}}} + ), + ), + ): + auto_allocator.run_auto_allocation_once(db, limit=1, now=moment) + + assert calls == [older.id] diff --git a/web/backend/migrations/versions/20261118_0090_repair_snapshot_ready_with_account.py b/web/backend/migrations/versions/20261118_0090_repair_snapshot_ready_with_account.py new file mode 100644 index 0000000..60f4637 --- /dev/null +++ b/web/backend/migrations/versions/20261118_0090_repair_snapshot_ready_with_account.py @@ -0,0 +1,52 @@ +"""修复重复订单快照把已分配履约任务打回待分配的问题。 + +旧逻辑在每次消费非终态订单快照时都会执行 ``_apply_mapping``,无条件把 +``execution_status`` 改成 ``ready``,但保留 ``account_id`` 和活跃租约。 +自动选号只扫描 ``ready + account_id IS NULL``,因此这些任务不会被再次处理。 +这里只修复带有效租约、且尚未开始绑定的异常任务,并依据兑换状态恢复提示。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261118_0090" +down_revision: str | None = "20261118_0089" +branch_labels: str | None = None +depends_on: str | None = None + + +def upgrade() -> None: + op.get_bind().execute( + sa.text( + "UPDATE platform_fulfillment_tasks t " + "JOIN account_leases l ON l.id = t.lease_id " + "SET t.execution_status = 'allocated', " + "t.next_allocate_at = NULL, " + "t.issue_code = CASE t.exchange_status " + "WHEN 'points_short' THEN 'points_short' " + "WHEN 'not_opened' THEN 'elite_not_opened' " + "WHEN 'limited' THEN 'commodity_limit_reached' " + "WHEN 'check_failed' THEN 'eligibility_check_failed' " + "ELSE '' END, " + "t.last_error = CASE t.exchange_status " + "WHEN 'points_short' THEN '账号积分不足,可充值后继续' " + "WHEN 'not_opened' THEN '账号尚未开通精英宝典,可开通后继续' " + "WHEN 'limited' THEN '该账号已达到此商品兑换上限' " + "WHEN 'check_failed' THEN '兑换资格查询失败,请刷新后重试' " + "ELSE '' END, " + "t.updated_at = UTC_TIMESTAMP() " + "WHERE t.execution_status = 'ready' " + "AND t.account_id IS NOT NULL " + "AND t.lease_id IS NOT NULL " + "AND t.binding_status = 'not_started' " + "AND l.purpose = 'platform_fulfillment' " + "AND l.status = 'active'" + ) + ) + + +def downgrade() -> None: + # 这是不可逆的数据修复;回滚代码版本也无需重新制造异常状态。 + pass diff --git a/web/backend/migrations/versions/20261118_0091_account_commodity_states.py b/web/backend/migrations/versions/20261118_0091_account_commodity_states.py new file mode 100644 index 0000000..7dac237 --- /dev/null +++ b/web/backend/migrations/versions/20261118_0091_account_commodity_states.py @@ -0,0 +1,167 @@ +"""账号商品兑换能力索引。 + +本表把“某账号对某商品当前能不能换”从 ``overview_snapshot`` JSON 中拆出来, +用于履约秒级候选查询。它只保存最后一次官方查询的派生结论;兑换事实仍写 +``account_events``。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261118_0091" +down_revision: str | None = "20261118_0090" +branch_labels: str | None = None +depends_on: str | None = None + +TABLE = "account_commodity_states" + + +def _table_exists(name: str) -> bool: + return bool( + op.get_bind() + .execute( + sa.text( + "SELECT COUNT(*) FROM information_schema.tables " + "WHERE table_schema = DATABASE() AND table_name = :name" + ), + {"name": name}, + ) + .scalar() + ) + + +def _index_exists(name: str) -> bool: + return bool( + op.get_bind() + .execute( + sa.text( + "SELECT COUNT(*) FROM information_schema.statistics " + "WHERE table_schema = DATABASE() " + "AND table_name = :table AND index_name = :name" + ), + {"table": TABLE, "name": name}, + ) + .scalar() + ) + + +def upgrade() -> None: + if not _table_exists(TABLE): + op.create_table( + TABLE, + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("account_id", sa.Integer(), nullable=False), + sa.Column( + "platform", + sa.String(length=16), + nullable=False, + server_default="douyu", + ), + sa.Column( + "scope", + sa.String(length=16), + nullable=False, + server_default="elite", + ), + sa.Column("commodity_id", sa.String(length=64), nullable=False), + sa.Column( + "commodity_name", + sa.String(length=256), + nullable=False, + server_default="", + ), + sa.Column( + "availability", + sa.String(length=16), + nullable=False, + server_default="unknown", + ), + sa.Column( + "blocking_reason", + sa.String(length=255), + nullable=False, + server_default="", + ), + sa.Column( + "raw_status", + sa.String(length=16), + nullable=False, + server_default="", + ), + sa.Column("observed_at", sa.DateTime(), nullable=True), + sa.Column("valid_until", sa.DateTime(), nullable=True), + sa.Column("next_check_at", sa.DateTime(), nullable=True), + sa.Column("last_exchange_at", sa.DateTime(), nullable=True), + sa.Column( + "exchange_count_365d", + sa.Integer(), + nullable=False, + server_default="0", + ), + sa.Column( + "source", sa.String(length=24), nullable=False, server_default="" + ), + sa.Column( + "error_code", + sa.String(length=64), + nullable=False, + server_default="", + ), + sa.Column( + "created_at", + sa.DateTime(), + nullable=False, + server_default=sa.text("CURRENT_TIMESTAMP"), + ), + sa.Column( + "updated_at", + sa.DateTime(), + nullable=False, + server_default=sa.text("CURRENT_TIMESTAMP"), + ), + sa.PrimaryKeyConstraint("id"), + sa.ForeignKeyConstraint( + ["account_id"], + ["accounts.id"], + name="fk_account_commodity_account", + ondelete="CASCADE", + ), + sa.UniqueConstraint( + "account_id", + "platform", + "scope", + "commodity_id", + name="uq_account_commodity_state", + ), + ) + + if not _index_exists("ix_account_commodity_match"): + op.create_index( + "ix_account_commodity_match", + TABLE, + [ + "platform", + "scope", + "commodity_id", + "availability", + "valid_until", + "account_id", + ], + ) + if not _index_exists("ix_account_commodity_account"): + op.create_index( + "ix_account_commodity_account", + TABLE, + ["account_id", "platform", "scope"], + ) + + +def downgrade() -> None: + if _index_exists("ix_account_commodity_account"): + op.drop_index("ix_account_commodity_account", table_name=TABLE) + if _index_exists("ix_account_commodity_match"): + op.drop_index("ix_account_commodity_match", table_name=TABLE) + if _table_exists(TABLE): + op.drop_table(TABLE) diff --git a/web/backend/migrations/versions/20261118_0092_backfill_exchange_subject_key.py b/web/backend/migrations/versions/20261118_0092_backfill_exchange_subject_key.py new file mode 100644 index 0000000..48a68fc --- /dev/null +++ b/web/backend/migrations/versions/20261118_0092_backfill_exchange_subject_key.py @@ -0,0 +1,38 @@ +"""回填官方兑换事件的商品检索键。 + +早期 ``record_official_exchange`` 只把 ``commodity_id`` 放进 JSON detail, +没有写 ``subject_key``。履约的 365 天同商品规则按 ``subject_key`` 查询, +因此这些官方历史记录实际没有参与匹配。这里从 detail 幂等回填。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261118_0092" +down_revision: str | None = "20261118_0091" +branch_labels: str | None = None +depends_on: str | None = None + + +def upgrade() -> None: + op.get_bind().execute( + sa.text( + "UPDATE account_events " + "SET subject_key = LEFT(" + "JSON_UNQUOTE(JSON_EXTRACT(detail, '$.commodity_id')), 96" + "), subject_type = 'commodity' " + "WHERE event_type = 'exchange' " + "AND source = 'official_sync' " + "AND subject_key = '' " + "AND detail IS NOT NULL " + "AND JSON_UNQUOTE(JSON_EXTRACT(detail, '$.commodity_id')) IS NOT NULL " + "AND JSON_UNQUOTE(JSON_EXTRACT(detail, '$.commodity_id')) <> ''" + ) + ) + + +def downgrade() -> None: + # 回填的是可重建的检索投影,不回滚,避免影响后续新写入事件。 + pass diff --git a/web/backend/migrations/versions/20261118_0093_account_commodity_time_windows.py b/web/backend/migrations/versions/20261118_0093_account_commodity_time_windows.py new file mode 100644 index 0000000..cdd341b --- /dev/null +++ b/web/backend/migrations/versions/20261118_0093_account_commodity_time_windows.py @@ -0,0 +1,72 @@ +"""账号商品能力增加限时兑换窗口。 + +斗鱼 ``storehome`` 同时返回账号级 ``status`` 和商品级限时规则: +``timeLimited``、``startTime`` / ``endTime``、``specTimes``。这三类信息 +必须分明,不能把未开始、已结束和账号限兑都显示成同一种“不可兑换”。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261118_0093" +down_revision: str | None = "20261118_0092" +branch_labels: str | None = None +depends_on: str | None = None + +TABLE = "account_commodity_states" + + +def _column_exists(name: str) -> 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 = :name" + ), + {"table": TABLE, "name": name}, + ) + .scalar() + ) + + +def upgrade() -> None: + if not _column_exists("time_limited"): + op.add_column( + TABLE, + sa.Column( + "time_limited", + sa.Boolean(), + nullable=False, + server_default="0", + ), + ) + if not _column_exists("available_from"): + op.add_column( + TABLE, + sa.Column("available_from", sa.DateTime(), nullable=True), + ) + if not _column_exists("available_until"): + op.add_column( + TABLE, + sa.Column("available_until", sa.DateTime(), nullable=True), + ) + if not _column_exists("schedule_json"): + op.add_column( + TABLE, + sa.Column("schedule_json", sa.JSON(), nullable=True), + ) + + +def downgrade() -> None: + if _column_exists("schedule_json"): + op.drop_column(TABLE, "schedule_json") + if _column_exists("available_until"): + op.drop_column(TABLE, "available_until") + if _column_exists("available_from"): + op.drop_column(TABLE, "available_from") + if _column_exists("time_limited"): + op.drop_column(TABLE, "time_limited") diff --git a/web/backend/models.py b/web/backend/models.py index 0d759a4..4cf75f8 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -1637,6 +1637,109 @@ class AccountEvent(Base): ) +class AccountCommodityState(Base): + """账号对具体斗鱼商品的当前兑换能力。 + + ``accounts`` 保存账号级状态(CK、积分、宝典、换绑冷却),本表保存 + “这个账号现在能不能换这个商品”。它是查询快照的派生索引,不是新的账号主表: + + - ``availability`` 是最近一次官方商品列表得出的结论; + - ``observed_at`` / ``valid_until`` 明确这条结论的有效期; + - ``last_exchange_at`` / ``exchange_count_365d`` 是兑换历史的高频反规范化; + - 真正发生过的兑换仍然只追加到 ``account_events``。 + + 匹配读取本表,真正占用账号前再做一次实时确认。查不到时保留上一有效结论, + 但过期的 ``available`` 不允许继续参与自动匹配。 + """ + + __tablename__ = "account_commodity_states" + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True) + account_id: Mapped[int] = mapped_column( + ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False + ) + platform: Mapped[str] = mapped_column( + String(16), nullable=False, default="douyu", server_default="douyu" + ) + scope: Mapped[str] = mapped_column( + String(16), nullable=False, default="elite", server_default="elite" + ) + commodity_id: Mapped[str] = mapped_column(String(64), nullable=False) + commodity_name: Mapped[str] = mapped_column( + String(256), nullable=False, default="", server_default="" + ) + # available / limited / no_stock / not_open / not_offered / unknown + availability: Mapped[str] = mapped_column( + String(16), nullable=False, default="unknown", server_default="unknown" + ) + blocking_reason: Mapped[str] = mapped_column( + String(255), nullable=False, default="", server_default="" + ) + raw_status: Mapped[str] = mapped_column( + String(16), nullable=False, default="", server_default="" + ) + time_limited: Mapped[bool] = mapped_column( + Boolean, nullable=False, default=False, server_default="0" + ) + available_from: Mapped[datetime | None] = mapped_column( + UTCDateTime, nullable=True + ) + available_until: Mapped[datetime | None] = mapped_column( + UTCDateTime, nullable=True + ) + schedule_json: Mapped[list | None] = mapped_column(JSON, nullable=True) + observed_at: Mapped[datetime | None] = mapped_column( + UTCDateTime, nullable=True + ) + valid_until: Mapped[datetime | None] = mapped_column( + UTCDateTime, nullable=True + ) + next_check_at: Mapped[datetime | None] = mapped_column( + UTCDateTime, nullable=True + ) + last_exchange_at: Mapped[datetime | None] = mapped_column( + UTCDateTime, nullable=True + ) + exchange_count_365d: Mapped[int] = mapped_column( + Integer, nullable=False, default=0, server_default="0" + ) + source: Mapped[str] = mapped_column( + String(24), nullable=False, default="", server_default="" + ) + error_code: Mapped[str] = mapped_column( + String(64), nullable=False, default="", server_default="" + ) + created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow) + updated_at: Mapped[datetime] = mapped_column( + UTCDateTime, default=_utcnow, onupdate=_utcnow + ) + + __table_args__ = ( + UniqueConstraint( + "account_id", + "platform", + "scope", + "commodity_id", + name="uq_account_commodity_state", + ), + Index( + "ix_account_commodity_match", + "platform", + "scope", + "commodity_id", + "availability", + "valid_until", + "account_id", + ), + Index( + "ix_account_commodity_account", + "account_id", + "platform", + "scope", + ), + ) + + class AccountLease(Base): """账号租约:谁在**此刻**可以使用这个账号。 diff --git a/web/backend/routers/accounts.py b/web/backend/routers/accounts.py index ed704c6..1a802ce 100644 --- a/web/backend/routers/accounts.py +++ b/web/backend/routers/accounts.py @@ -1,5 +1,6 @@ import csv import io +from datetime import UTC, datetime from typing import Any from fastapi import APIRouter, Depends, HTTPException, Query, Response @@ -10,6 +11,7 @@ from ..database import get_db from ..deps import get_current_user, require_permission from ..models import ( Account, + AccountCommodityState, AccountEvent, AuditLog, DouyuTask, @@ -32,13 +34,16 @@ from ..schemas import ( BatchAssign, ) from ..services.account_binding import bind_payload +from ..services.account_capability_service import account_capability_counts from ..services.account_events_service import ( CATEGORY_OPS, EVENT_ASSIGNED, + EVENT_AUTOMATION_CHANGED, EVENT_CK_INVALID, EVENT_ELITE_OPENED, EVENT_ESPORTS_OPENED, EVENT_EXCHANGE, + EVENT_IMPORTED, EVENT_RECHARGE, EVENT_REMARK_CHANGED, EVENT_TAG_CHANGED, @@ -967,6 +972,7 @@ def import_accounts( if accounts: db.add_all(accounts) + db.flush() db.add( AuditLog( user_id=current.id, @@ -975,6 +981,22 @@ def import_accounts( target=f"导入{len(accounts)}个", ) ) + emit_bulk( + db, + [ + { + "account_id": account.id, + "event_type": EVENT_IMPORTED, + "title": "账号已导入", + "category": CATEGORY_OPS, + "source": "audit", + "actor_type": "user", + "actor_id": current.id, + "source_ref": f"account_imported:{account.id}", + } + for account in accounts + ], + ) db.commit() duplicated_note = f",重复跳过 {duplicated} 个" if duplicated else "" @@ -1254,16 +1276,23 @@ def set_account_automation( acc = db.query(Account).filter(Account.id == account_id).first() if not acc: raise HTTPException(status_code=404, detail="账号不存在") + previous = bool(acc.auto_managed) acc.auto_managed = bool(req.auto_managed) - db.add( - AuditLog( - user_id=current.id, - username=current.username, - action="account:automation", - target=acc.username, - account_id=acc.id, - detail="参与自动化" if req.auto_managed else "不参与自动化", - ) + record_account_action( + db, + current, + account=acc, + action="account:automation", + event_type=EVENT_AUTOMATION_CHANGED, + title=( + "自动化:不参与 → 参与" + if req.auto_managed + else "自动化:参与 → 不参与" + ), + detail={ + "from": previous, + "to": bool(req.auto_managed), + }, ) db.commit() return { @@ -1509,6 +1538,81 @@ def batch_delete_accounts_selection( return {"message": f"已删除 {deleted} 个账号", "deleted": deleted, "success": True} +@router.get("/{account_id}/commodities") +def account_commodities( + account_id: int, + scope: str = Query("", max_length=16), + availability: str = Query("", max_length=16), + limit: int = Query(500, ge=1, le=1000), + db: Session = Depends(get_db), + current: User = Depends(get_current_user), +): + """账号 × 商品当前兑换能力及最后确认时间。""" + if ( + not _visible_accounts_query(db, current) + .filter(Account.id == account_id) + .first() + ): + raise HTTPException(status_code=404, detail="账号不存在或无权查看") + + now = datetime.now(UTC) + query = db.query(AccountCommodityState).filter( + AccountCommodityState.account_id == account_id, + AccountCommodityState.platform == "douyu", + ) + scope_value = scope.strip() + availability_value = availability.strip() + if scope_value: + query = query.filter(AccountCommodityState.scope == scope_value) + if availability_value: + query = query.filter( + AccountCommodityState.availability == availability_value + ) + rows = ( + query.order_by( + case( + (AccountCommodityState.availability == "available", 0), + (AccountCommodityState.availability == "limited", 1), + else_=2, + ), + AccountCommodityState.valid_until.desc(), + AccountCommodityState.commodity_id.asc(), + ) + .limit(limit) + .all() + ) + return { + "items": [ + { + "commodity_id": row.commodity_id, + "commodity_name": row.commodity_name, + "scope": row.scope, + "availability": row.availability, + "blocking_reason": row.blocking_reason, + "raw_status": row.raw_status, + "time_limited": bool(row.time_limited), + "available_from": row.available_from, + "available_until": row.available_until, + "schedule": row.schedule_json or [], + "observed_at": row.observed_at, + "valid_until": row.valid_until, + "next_check_at": row.next_check_at, + "last_exchange_at": row.last_exchange_at, + "exchange_count_365d": row.exchange_count_365d, + "fresh": bool(row.valid_until and row.valid_until > now), + "source": row.source, + "error_code": row.error_code, + } + for row in rows + ], + "summary": account_capability_counts( + db, + account_id=account_id, + now=now, + ), + } + + @router.get("/{account_id}/exchange-records") def account_exchange_records( account_id: int, @@ -1660,6 +1764,10 @@ def account_overview( "points_expire_at": acc.points_expire_at, "overview_snapshot": acc.overview_snapshot, "overview_queried_at": acc.overview_queried_at, + "commodity_capability": account_capability_counts( + db, + account_id=int(acc.id), + ), "high_value": high_value_payload(acc), "elite_opened": acc.elite_opened, "elite_expire_time": acc.elite_expire_time, @@ -1694,7 +1802,7 @@ def account_events( page_size: int = 50, event_type: str = "", category: str = Query( - "", description="按粗分类筛选:lifecycle / auth / business / ops" + "", description="按粗分类筛选:lifecycle / auth / business / activity / ops" ), db: Session = Depends(get_db), current: User = Depends(get_current_user), diff --git a/web/backend/services/account_capability_service.py b/web/backend/services/account_capability_service.py new file mode 100644 index 0000000..efc4027 --- /dev/null +++ b/web/backend/services/account_capability_service.py @@ -0,0 +1,568 @@ +"""账号商品能力索引。 + +``accounts`` 回答“账号整体能不能用”,本模块回答“账号对具体商品现在能不能换”。 +能力索引只保存查询投影;兑换等不可变事实仍写 ``account_events``。 +""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta +from typing import Any + +from sqlalchemy import case, func +from sqlalchemy.orm import Session + +from ..models import Account, AccountCommodityState, AccountEvent + +AVAILABILITY_AVAILABLE = "available" +AVAILABILITY_LIMITED = "limited" +AVAILABILITY_NO_STOCK = "no_stock" +AVAILABILITY_NOT_OPEN = "not_open" +AVAILABILITY_NOT_OFFERED = "not_offered" +AVAILABILITY_EXPIRED = "expired" +AVAILABILITY_UNKNOWN = "unknown" + +DEFAULT_CAPABILITY_TTL_SECONDS = 15 * 60 + + +def _env_positive_int(name: str, default: int) -> int: + try: + value = int(os.getenv(name, str(default))) + except ValueError: + return default + return value if value > 0 else default + + +def capability_ttl_seconds() -> int: + return _env_positive_int( + "ACCOUNT_COMMODITY_STATE_TTL_SECONDS", + DEFAULT_CAPABILITY_TTL_SECONDS, + ) + + +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 _to_datetime(value: Any) -> datetime | None: + timestamp = _to_int(value) + if timestamp is None or timestamp <= 0: + return None + if timestamp > 10_000_000_000: + timestamp //= 1000 + return datetime.fromtimestamp(timestamp, tz=UTC) + + +@dataclass(frozen=True) +class GoodsTimeWindow: + time_limited: bool + start: datetime | None + end: datetime | None + state: str + next_boundary: datetime | None + schedule: list[dict[str, Any]] + + +def goods_time_window( + item: dict[str, Any], + *, + now: datetime | None = None, +) -> GoodsTimeWindow: + """解析商品限时窗口。 + + ``status`` 是账号维度的限兑;时间窗口是商品维度的开放区间。两者必须同时 + 判断。``specTimes`` 优先于外层 start/end,用于一天多场或分阶段开放。 + """ + moment = now or datetime.now(UTC) + intervals: list[tuple[datetime, datetime]] = [] + schedule: list[dict[str, Any]] = [] + raw_spec_times = item.get("specTimes") + if isinstance(raw_spec_times, list): + for raw in raw_spec_times: + if not isinstance(raw, dict): + continue + schedule.append(dict(raw)) + start = _to_datetime(raw.get("startTime")) + end = _to_datetime(raw.get("endTime")) + if start is not None and end is not None and end >= start: + intervals.append((start, end)) + if not intervals: + start = _to_datetime(item.get("startTime")) + end = _to_datetime(item.get("endTime")) + if start is not None and end is not None and end >= start: + intervals.append((start, end)) + + time_limited = bool(_to_int(item.get("timeLimited"))) + if not intervals: + return GoodsTimeWindow( + time_limited=time_limited, + start=None, + end=None, + state="", + next_boundary=None, + schedule=schedule, + ) + + intervals.sort(key=lambda value: value[0]) + for start, end in intervals: + if start <= moment <= end: + return GoodsTimeWindow( + time_limited=time_limited, + start=start, + end=end, + state="active", + next_boundary=end, + schedule=schedule, + ) + for start, end in intervals: + if start > moment: + return GoodsTimeWindow( + time_limited=time_limited, + start=start, + end=end, + state="before", + next_boundary=start, + schedule=schedule, + ) + start, end = intervals[-1] + return GoodsTimeWindow( + time_limited=time_limited, + start=start, + end=end, + state="after", + next_boundary=None, + schedule=schedule, + ) + + +def classify_goods_item( + item: dict[str, Any], + *, + now: datetime | None = None, +) -> tuple[str, str, str]: + """把官方 storehome 商品项归一成能力状态。 + + 返回 ``(availability, blocking_reason, raw_status)``。只有官方明确给出的 + 账号级 ``status`` 才允许写成 available / limited;缺字段一律 unknown。 + """ + moment = now or datetime.now(UTC) + window = goods_time_window(item, now=moment) + raw_status = str(item.get("status") if item.get("status") is not None else "") + status = _to_int(item.get("status")) + store_status = _to_int( + item.get("storeStatus") + if item.get("storeStatus") is not None + else item.get("store_status") + ) + open_status = _to_int( + item.get("openStatus") + if item.get("openStatus") is not None + else item.get("open_status") + ) + count = _to_int(item.get("count")) + + if window.state == "before": + return ( + AVAILABILITY_NOT_OPEN, + f"限时兑换未开始,开始于 {window.start.isoformat() if window.start else '未知时间'}", + raw_status, + ) + if window.state == "after": + return AVAILABILITY_EXPIRED, "限时兑换已结束", raw_status + if status == 1: + return AVAILABILITY_LIMITED, "该账号已达此商品兑换上限", raw_status + if store_status == 0: + return AVAILABILITY_NO_STOCK, "官方商城当前无库存", raw_status + if count is not None and count <= 0: + return AVAILABILITY_NO_STOCK, "官方商城当前无库存", raw_status + if open_status == 0: + return AVAILABILITY_NOT_OPEN, "活动尚未开放兑换", raw_status + if status == 0: + return AVAILABILITY_AVAILABLE, "", raw_status + return AVAILABILITY_UNKNOWN, "官方商品列表未返回可判定的账号状态", raw_status + + +def _exchange_stats( + db: Session, + *, + account_id: int, + now: datetime, +) -> dict[str, tuple[datetime | None, int]]: + since = now - timedelta(days=365) + recent_rows = ( + db.query( + AccountEvent.subject_key, + func.max(AccountEvent.occurred_at), + func.count(AccountEvent.id), + ) + .filter( + AccountEvent.account_id == account_id, + AccountEvent.event_type == "exchange", + AccountEvent.subject_key != "", + AccountEvent.occurred_at >= since, + ) + .group_by(AccountEvent.subject_key) + .all() + ) + latest_rows = ( + db.query( + AccountEvent.subject_key, + func.max(AccountEvent.occurred_at), + ) + .filter( + AccountEvent.account_id == account_id, + AccountEvent.event_type == "exchange", + AccountEvent.subject_key != "", + ) + .group_by(AccountEvent.subject_key) + .all() + ) + latest = { + str(key or ""): value + for key, value in latest_rows + if str(key or "") + } + stats: dict[str, tuple[datetime | None, int]] = {} + for key, recent_at, recent_count in recent_rows: + commodity_id = str(key or "") + if not commodity_id: + continue + stats[commodity_id] = ( + latest.get(commodity_id) or recent_at, + int(recent_count or 0), + ) + for commodity_id, value in latest.items(): + stats.setdefault(commodity_id, (value, 0)) + return stats + + +def _commodity_id(item: dict[str, Any]) -> str: + return str( + item.get("commodityId") + or item.get("commodity_id") + or item.get("id") + or "" + ).strip() + + +def _commodity_name(item: dict[str, Any]) -> str: + return str( + item.get("name") + or item.get("commodityName") + or item.get("commodity_name") + or "" + ).strip() + + +def sync_account_goods_states( + db: Session, + account: Account, + goods_items: list[dict[str, Any]], + *, + scope: str = "elite", + observed_at: datetime | None = None, + source: str = "overview", + replace_missing: bool = True, +) -> int: + """用一次完整官方商品列表刷新账号商品能力。 + + 只在整份商品列表查询成功时调用。单项/整份失败时不要调用本函数,避免把 + “没查到”误写成“不可兑换”。 + """ + if not goods_items or account.id is None: + return 0 + moment = observed_at or datetime.now(UTC) + valid_until = moment + timedelta(seconds=capability_ttl_seconds()) + + existing_rows = ( + db.query(AccountCommodityState) + .filter( + AccountCommodityState.account_id == account.id, + AccountCommodityState.platform == "douyu", + AccountCommodityState.scope == scope, + ) + .all() + ) + by_commodity = {row.commodity_id: row for row in existing_rows} + exchange_stats = _exchange_stats(db, account_id=int(account.id), now=moment) + seen: set[str] = set() + changed = 0 + + for item in goods_items: + if not isinstance(item, dict): + continue + commodity_id = _commodity_id(item) + if not commodity_id: + continue + seen.add(commodity_id) + state = by_commodity.get(commodity_id) + if state is None: + state = AccountCommodityState( + account_id=int(account.id), + platform="douyu", + scope=scope, + commodity_id=commodity_id, + created_at=moment, + ) + db.add(state) + by_commodity[commodity_id] = state + + availability, reason, raw_status = classify_goods_item(item, now=moment) + window = goods_time_window(item, now=moment) + last_exchange_at, exchange_count = exchange_stats.get( + commodity_id, + (None, 0), + ) + state.commodity_name = _commodity_name(item)[:256] + state.availability = availability + state.blocking_reason = reason[:255] + state.raw_status = raw_status[:16] + state.time_limited = window.time_limited + state.available_from = window.start + state.available_until = window.end + state.schedule_json = window.schedule or None + state.observed_at = moment + state.valid_until = valid_until + state.next_check_at = ( + min(valid_until, window.next_boundary) + if window.next_boundary is not None + else valid_until + ) + state.last_exchange_at = last_exchange_at + state.exchange_count_365d = int(exchange_count) + state.source = source[:24] + state.error_code = "" + state.updated_at = moment + changed += 1 + + if replace_missing: + for commodity_id, state in by_commodity.items(): + if commodity_id in seen: + continue + if ( + state.availability == AVAILABILITY_NOT_OFFERED + and state.blocking_reason == "官方商品列表本次未返回该商品" + ): + continue + state.availability = AVAILABILITY_NOT_OFFERED + state.blocking_reason = "官方商品列表本次未返回该商品" + state.observed_at = moment + state.valid_until = None + state.next_check_at = valid_until + state.source = source[:24] + state.updated_at = moment + changed += 1 + + db.flush() + return changed + + +def record_account_commodity_state( + db: Session, + account: Account, + *, + commodity_id: str, + availability: str, + blocking_reason: str = "", + raw_status: str = "", + observed_at: datetime | None = None, + source: str = "live_check", + scope: str = "elite", + valid_for_seconds: int | None = None, + error_code: str = "", +) -> AccountCommodityState: + """写入单个商品的实时检查结论,供下一轮匹配直接使用。""" + moment = observed_at or datetime.now(UTC) + ttl = ( + capability_ttl_seconds() + if valid_for_seconds is None + else max(1, int(valid_for_seconds)) + ) + state = ( + db.query(AccountCommodityState) + .filter( + AccountCommodityState.account_id == account.id, + AccountCommodityState.platform == "douyu", + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id == commodity_id, + ) + .first() + ) + if state is None: + state = AccountCommodityState( + account_id=int(account.id), + platform="douyu", + scope=scope, + commodity_id=commodity_id, + created_at=moment, + ) + db.add(state) + exchange_stats = _exchange_stats( + db, + account_id=int(account.id), + now=moment, + ) + last_exchange_at, exchange_count = exchange_stats.get(commodity_id, (None, 0)) + state.availability = availability + state.blocking_reason = blocking_reason[:255] + state.raw_status = raw_status[:16] + state.observed_at = moment + state.valid_until = moment + timedelta(seconds=ttl) + state.next_check_at = state.valid_until + state.last_exchange_at = last_exchange_at + state.exchange_count_365d = int(exchange_count) + state.source = source[:24] + state.error_code = error_code[:64] + state.updated_at = moment + db.flush() + return state + + +def mark_commodity_exchanged( + db: Session, + *, + account_id: int, + commodity_id: str, + occurred_at: datetime | None = None, + scope: str = "elite", + commodity_name: str = "", +) -> None: + """实际兑换后立即更新匹配投影,避免下一单再次选中。""" + if not commodity_id: + return + moment = occurred_at or datetime.now(UTC) + state = ( + db.query(AccountCommodityState) + .filter( + AccountCommodityState.account_id == account_id, + AccountCommodityState.platform == "douyu", + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id == commodity_id, + ) + .first() + ) + if state is None: + state = AccountCommodityState( + account_id=account_id, + platform="douyu", + scope=scope, + commodity_id=commodity_id, + created_at=moment, + ) + db.add(state) + exchange_stats = _exchange_stats(db, account_id=account_id, now=moment) + last_exchange_at, exchange_count = exchange_stats.get(commodity_id, (moment, 1)) + if commodity_name: + state.commodity_name = commodity_name[:256] + state.availability = AVAILABILITY_LIMITED + state.blocking_reason = "该账号已兑换过此商品,365 天内不可重复分配" + state.observed_at = moment + state.valid_until = None + state.next_check_at = moment + timedelta(days=365) + state.last_exchange_at = last_exchange_at + state.exchange_count_365d = max(1, int(exchange_count)) + state.source = "exchange" + state.error_code = "" + state.updated_at = moment + db.flush() + + +def invalidate_account_commodity_states( + db: Session, + *, + account_id: int, + reason: str, + observed_at: datetime | None = None, +) -> int: + """CK 失效等全局风险发生时,立即作废所有可匹配能力。""" + moment = observed_at or datetime.now(UTC) + changed = ( + db.query(AccountCommodityState) + .filter( + AccountCommodityState.account_id == account_id, + AccountCommodityState.availability == AVAILABILITY_AVAILABLE, + ) + .update( + { + AccountCommodityState.availability: AVAILABILITY_UNKNOWN, + AccountCommodityState.blocking_reason: reason[:255], + AccountCommodityState.observed_at: moment, + AccountCommodityState.valid_until: None, + AccountCommodityState.next_check_at: moment, + AccountCommodityState.updated_at: moment, + }, + synchronize_session=False, + ) + ) + return int(changed or 0) + + +def account_capability_counts( + db: Session, + *, + account_id: int, + now: datetime | None = None, +) -> dict[str, int]: + moment = now or datetime.now(UTC) + rows = ( + db.query( + AccountCommodityState.availability, + func.count(AccountCommodityState.id), + func.sum( + case( + ( + AccountCommodityState.availability + == AVAILABILITY_AVAILABLE, + 1, + ), + else_=0, + ) + ), + ) + .filter(AccountCommodityState.account_id == account_id) + .group_by(AccountCommodityState.availability) + .all() + ) + result = {str(status): int(count or 0) for status, count, _ in rows} + fresh_available = ( + db.query(func.count(AccountCommodityState.id)) + .filter( + AccountCommodityState.account_id == account_id, + AccountCommodityState.availability == AVAILABILITY_AVAILABLE, + AccountCommodityState.valid_until.isnot(None), + AccountCommodityState.valid_until > moment, + ) + .scalar() + or 0 + ) + result["fresh_available"] = int(fresh_available) + result["total"] = sum( + value for key, value in result.items() if key not in {"fresh_available", "total"} + ) + return result + + +__all__ = [ + "AVAILABILITY_AVAILABLE", + "AVAILABILITY_EXPIRED", + "AVAILABILITY_LIMITED", + "AVAILABILITY_NOT_OFFERED", + "AVAILABILITY_NOT_OPEN", + "AVAILABILITY_NO_STOCK", + "AVAILABILITY_UNKNOWN", + "account_capability_counts", + "capability_ttl_seconds", + "classify_goods_item", + "goods_time_window", + "invalidate_account_commodity_states", + "mark_commodity_exchanged", + "record_account_commodity_state", + "sync_account_goods_states", +] diff --git a/web/backend/services/account_events_service.py b/web/backend/services/account_events_service.py index 0794137..262a297 100644 --- a/web/backend/services/account_events_service.py +++ b/web/backend/services/account_events_service.py @@ -69,6 +69,14 @@ EVENT_ASSIGNED = "assigned" # 分配客服 EVENT_TAG_CHANGED = "tag_changed" # 标签变更 EVENT_REMARK_CHANGED = "remark_changed" # 备注变更 EVENT_STATUS_CHANGED = "status_changed" # 生命周期状态变迁(停用/归档/失效…) +EVENT_AUTOMATION_CHANGED = "automation_changed" # 自动化开关 +EVENT_TASK_STARTED = "task_started" # 斗鱼账号任务创建 +EVENT_TASK_SUCCEEDED = "task_succeeded" # 斗鱼账号任务成功 +EVENT_TASK_FAILED = "task_failed" # 斗鱼账号任务失败 +EVENT_TASK_STOPPED = "task_stopped" # 斗鱼账号任务停止/中断 +EVENT_QUERY_COMPLETED = "query_completed" # 同步查询完成(含部分失败) +EVENT_LEASE_ACQUIRED = "lease_acquired" # 分配履约账号使用权 +EVENT_LEASE_RELEASED = "lease_released" # 释放履约账号使用权 # 有符号金额的事件类型(用于页面「累计充值/累计消耗」): # 充值为正、兑换为负,其余不计入金额统计。 @@ -80,6 +88,7 @@ CATEGORY_LIFECYCLE = "lifecycle" # 生命周期状态变迁 CATEGORY_AUTH = "auth" # 登录与 CK CATEGORY_BUSINESS = "business" # 充值 / 兑换 / 积分 / 开通 CATEGORY_OPS = "ops" # 人工操作(分配 / 标签 / 停用) +CATEGORY_ACTIVITY = "activity" # 查询 / 绑定 / 账号任务等活动 def _is_duplicate_entry(exc: BaseException) -> bool: diff --git a/web/backend/services/account_lifecycle.py b/web/backend/services/account_lifecycle.py index ebc34bd..b7212f5 100644 --- a/web/backend/services/account_lifecycle.py +++ b/web/backend/services/account_lifecycle.py @@ -290,6 +290,24 @@ def on_ck_verdict( # `error`(查不到)**不**作废:查不到不等于账号出问题了。 if verdict == "invalid": invalidate_high_value(account) + if account.id is not None: + from .account_capability_service import ( + invalidate_account_commodity_states, + ) + + try: + invalidate_account_commodity_states( + db, + account_id=int(account.id), + reason="CK 已失效,账号商品能力待重新确认", + observed_at=now, + ) + except Exception as exc: # noqa: BLE001 - 生命周期主流程不能被派生索引拖垮 + logger.warning( + "作废账号商品能力失败 account_id={}: {}", + account.id, + exc, + ) data = detail or {} account.ck_check_result = { "fish_ball": data.get("fish_ball"), diff --git a/web/backend/services/automation/__init__.py b/web/backend/services/automation/__init__.py index bfc7cc8..ea84eb4 100644 --- a/web/backend/services/automation/__init__.py +++ b/web/backend/services/automation/__init__.py @@ -6,6 +6,12 @@ from __future__ import annotations +from .jobs.account_capability_refresh import ( + JOB_KEY as ACCOUNT_CAPABILITY_REFRESH_KEY, +) +from .jobs.account_capability_refresh import ( + run_account_capability_refresh, +) from .jobs.account_overview_refresh import ( JOB_KEY as ACCOUNT_OVERVIEW_REFRESH_KEY, ) @@ -45,6 +51,7 @@ from .scheduler import ( ) __all__ = [ + "ACCOUNT_CAPABILITY_REFRESH_KEY", "ACCOUNT_OVERVIEW_REFRESH_KEY", "CK_HEALTH_KEY", "CK_RELOGIN_KEY", @@ -58,6 +65,7 @@ __all__ = [ "register_job", "registered_jobs", "reset_registry", + "run_account_capability_refresh", "run_account_overview_refresh", "run_ck_health", "run_ck_relogin", @@ -74,6 +82,18 @@ __all__ = [ def register_default_jobs() -> None: """登记内置作业(幂等)。""" + register_job( + JobSpec( + key=ACCOUNT_CAPABILITY_REFRESH_KEY, + title="履约商品能力补充刷新", + # 只刷新有 pending 履约需求且能力快照已过期的账号。 + interval_seconds=3600, + run_interval_seconds=5 * 60, + batch_size=100, + concurrency=3, + run=run_account_capability_refresh, + ) + ) register_job( JobSpec( key=POINTS_EXPIRE_KEY, diff --git a/web/backend/services/automation/jobs/account_capability_refresh.py b/web/backend/services/automation/jobs/account_capability_refresh.py new file mode 100644 index 0000000..1ac6e23 --- /dev/null +++ b/web/backend/services/automation/jobs/account_capability_refresh.py @@ -0,0 +1,118 @@ +"""按直播履约需求刷新账号商品能力。 + +全量资料补全仍由 ``account_overview_refresh`` 负责;本作业只处理“有 pending +任务、但对应商品能力快照已经过期”的账号,避免为了秒匹配把两万多个账号 +无条件轮询一遍。 +""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any + +from sqlalchemy import exists, or_, select +from sqlalchemy.orm import Session + +from ....models import ( + Account, + AccountCommodityState, + AccountLease, + AutomationJob, + PlatformFulfillmentTask, +) +from ...account_lifecycle import MANUAL_STATES +from ...douyu_service import cookie_operable_filter +from .account_overview_refresh import run_refresh_for_accounts + +JOB_KEY = "account_capability_refresh" + + +def _base_query(db: Session, now: datetime): + pending_commodities = ( + select(PlatformFulfillmentTask.commodity_id) + .where( + PlatformFulfillmentTask.execution_status == "ready", + PlatformFulfillmentTask.account_id.is_(None), + PlatformFulfillmentTask.commodity_id != "", + ) + .distinct() + ) + stale_demand_state = exists( + select(AccountCommodityState.id).where( + AccountCommodityState.account_id == Account.id, + AccountCommodityState.platform == "douyu", + AccountCommodityState.scope == "elite", + AccountCommodityState.commodity_id.in_(pending_commodities), + or_( + AccountCommodityState.valid_until.is_(None), + AccountCommodityState.valid_until <= now, + AccountCommodityState.next_check_at.is_(None), + AccountCommodityState.next_check_at <= now, + ), + ) + ) + active_lease = exists( + select(AccountLease.id).where( + AccountLease.active_account_id == Account.id, + ) + ) + return db.query(Account).filter( + cookie_operable_filter(), + Account.auto_managed.is_(True), + Account.status.notin_(MANUAL_STATES), + Account.ck_check_status == "valid", + stale_demand_state, + ~active_lease, + ) + + +def build_select_query( + db: Session, + job: AutomationJob, + now: datetime | None = None, +): + moment = now or datetime.now(UTC) + batch = max(1, int(job.batch_size or 100)) + return ( + _base_query(db, moment) + .order_by( + Account.overview_queried_at.is_(None).desc(), + Account.overview_queried_at.asc(), + Account.id.asc(), + ) + .limit(batch) + ) + + +def count_remaining( + db: Session, + *, + now: datetime | None = None, +) -> int: + return _base_query(db, now or datetime.now(UTC)).count() + + +def run_account_capability_refresh( + db: Session, + job: AutomationJob, +) -> dict[str, Any]: + now = datetime.now(UTC) + accounts = build_select_query(db, job, now).all() + return run_refresh_for_accounts( + db, + job, + accounts, + now=now, + remaining_count=count_remaining(db, now=now), + source="capability_demand_refresh", + log_label="capability", + empty_message="当前履约商品没有到期待刷新的账号能力", + ) + + +__all__ = [ + "JOB_KEY", + "build_select_query", + "count_remaining", + "run_account_capability_refresh", +] diff --git a/web/backend/services/automation/jobs/account_overview_refresh.py b/web/backend/services/automation/jobs/account_overview_refresh.py index 5ce4d83..3f76184 100644 --- a/web/backend/services/automation/jobs/account_overview_refresh.py +++ b/web/backend/services/automation/jobs/account_overview_refresh.py @@ -159,10 +159,18 @@ def _system_user_id(db: Session) -> int: return int(user.id) -def run_account_overview_refresh(db: Session, job: AutomationJob) -> dict[str, Any]: - """本轮:选一批 → 建任务 → 就地跑完 → 看失败率决定要不要熔断。""" - now = datetime.now(UTC) - accounts = build_select_query(db, job, now).all() +def run_refresh_for_accounts( + db: Session, + job: AutomationJob, + accounts: list[Account], + *, + now: datetime, + remaining_count: int | None = None, + source: str = "scheduled_refresh", + log_label: str = "overview", + empty_message: str = "全库暂无待补全或到期的账号", +) -> dict[str, Any]: + """对指定账号执行资料刷新;能力刷新作业也复用这条写入链。""" if not accounts: return { "scanned": 0, @@ -170,7 +178,7 @@ def run_account_overview_refresh(db: Session, job: AutomationJob) -> dict[str, A "invalid": 0, "succeeded": 0, "failed": 0, - "message": "全库暂无待补全或到期的账号", + "message": empty_message, } account_ids = [a.id for a in accounts] @@ -181,7 +189,7 @@ def run_account_overview_refresh(db: Session, job: AutomationJob) -> dict[str, A "elite", _system_user_id(db), # 标上来源,便于在任务列表里区分「定时巡检」与「人工点查询」 - {"source": "scheduled_refresh"}, + {"source": source}, ) if count == 0: return { @@ -220,19 +228,18 @@ def run_account_overview_refresh(db: Session, job: AutomationJob) -> dict[str, A db.commit() paused = True logger.warning( - f"[overview] 失败率 {error_ratio:.0%} 过高,已自动关闭作业" + f"[{log_label}] 失败率 {error_ratio:.0%} 过高,已自动关闭作业" f"(batch={batch_id},failed={failed}/{len(rows)})—— 请确认是否被风控" ) - message = ( - f"本轮查 {len(rows)} 个:成功 {succeeded} / 失败 {failed}" - f"(剩 {count_remaining(db, job, now)} 个待查)" - ) + message = f"本轮查 {len(rows)} 个:成功 {succeeded} / 失败 {failed}" + if remaining_count is not None: + message += f"(剩 {remaining_count} 个待查)" if paused: # 把**可能的原因**写进消息里:运维看作业历史时才知道该去查什么, # 否则只看到"失败率高"会一头雾水。 message += ";失败率过高,已自动关闭作业(大面积失败通常是**被风控**或接口抖动,请先确认再重开)" - logger.info(f"[overview] {message}") + logger.info(f"[{log_label}] {message}") return { "scanned": len(rows), "valid": succeeded, @@ -243,3 +250,16 @@ def run_account_overview_refresh(db: Session, job: AutomationJob) -> dict[str, A "paused": paused, "message": message, } + + +def run_account_overview_refresh(db: Session, job: AutomationJob) -> dict[str, Any]: + """本轮:选一批 → 建任务 → 就地跑完 → 看失败率决定要不要熔断。""" + now = datetime.now(UTC) + accounts = build_select_query(db, job, now).all() + return run_refresh_for_accounts( + db, + job, + accounts, + now=now, + remaining_count=count_remaining(db, job, now), + ) diff --git a/web/backend/services/business_events.py b/web/backend/services/business_events.py index 5ab6b18..c4e527e 100644 --- a/web/backend/services/business_events.py +++ b/web/backend/services/business_events.py @@ -33,17 +33,24 @@ from __future__ import annotations from datetime import datetime from typing import Any +from loguru import logger from sqlalchemy.orm import Session from ..models import Account from .account_events_service import ( + CATEGORY_ACTIVITY, CATEGORY_BUSINESS, EVENT_BIND_OK, EVENT_EXCHANGE, EVENT_GOLD_SPENT, EVENT_POINTS_CREDIT, EVENT_POINTS_EXPIRE, + EVENT_QUERY_COMPLETED, EVENT_RECHARGE, + EVENT_TASK_FAILED, + EVENT_TASK_STARTED, + EVENT_TASK_STOPPED, + EVENT_TASK_SUCCEEDED, OFFICIAL_SYNC_SOURCE, emit, to_naive_utc, @@ -64,6 +71,116 @@ def task_ref(task_id: int, kind: str = "") -> str: return f"{base}:{kind}" if kind else base +def record_douyu_task_started( + db: Session, + account: Account, + *, + task_id: int, + task_type: str, + task_label: str, + scope: str, + actor_id: int | None = None, +) -> bool: + """记录账号任务已创建;每次任务只写一条。""" + return emit( + db, + account_id=account.id, + event_type=EVENT_TASK_STARTED, + title=f"{task_label}:任务已创建", + category=CATEGORY_ACTIVITY, + detail={ + "task_id": task_id, + "task_type": task_type, + "scope": scope, + "status": "planned", + }, + source="douyu_task", + subject_type="task", + subject_key=str(task_id), + actor_type="user" if actor_id else "system", + actor_id=actor_id, + source_ref=f"douyu_task_started:{task_id}", + ) + + +def record_douyu_task_result( + db: Session, + account: Account, + *, + task_id: int, + task_type: str, + task_label: str, + scope: str, + status: str, + message: str = "", + occurred_at: datetime | None = None, +) -> bool: + """记录账号任务终态;成功不等于业务事实,因此单独作为活动事件。""" + event_type = { + "success": EVENT_TASK_SUCCEEDED, + "failed": EVENT_TASK_FAILED, + "error": EVENT_TASK_FAILED, + "stopped": EVENT_TASK_STOPPED, + }.get(status) + if event_type is None: + return False + status_label = { + EVENT_TASK_SUCCEEDED: "成功", + EVENT_TASK_FAILED: "失败", + EVENT_TASK_STOPPED: "已停止", + }[event_type] + return emit( + db, + account_id=account.id, + event_type=event_type, + title=f"{task_label}:{status_label}", + category=CATEGORY_ACTIVITY, + occurred_at=occurred_at, + detail={ + "task_id": task_id, + "task_type": task_type, + "scope": scope, + "status": status, + "message": (message or "")[:1000], + }, + source="douyu_task", + subject_type="task", + subject_key=str(task_id), + source_ref=f"douyu_task_result:{task_id}", + ) + + +def record_account_query( + db: Session, + account: Account, + *, + query_type: str, + title: str, + ok: bool, + detail: dict[str, Any] | None = None, + actor_id: int | None = None, +) -> bool: + """记录同步查询结果;允许同一查询反复发生,不做跨次幂等。""" + suffix = "" if ok else "(部分失败)" + return emit( + db, + account_id=account.id, + event_type=EVENT_QUERY_COMPLETED, + title=f"{title}{suffix}", + category=CATEGORY_ACTIVITY, + detail={ + "query_type": query_type, + "ok": ok, + **(detail or {}), + }, + source="douyu_query", + subject_type="query", + subject_key=query_type, + actor_type="user" if actor_id else "system", + actor_id=actor_id, + ) + + def record_recharge( db: Session, account: Account, @@ -137,7 +254,7 @@ def record_exchange( `score` 为负写入 `amount`(消耗),`points_after` 是兑换后的积分余额。 """ - return emit( + written = emit( db, account_id=account.id, event_type=EVENT_EXCHANGE, @@ -161,6 +278,26 @@ def record_exchange( subject_key=commodity_id or name or "", source_ref=task_ref(task_id), ) + if commodity_id: + from .account_capability_service import mark_commodity_exchanged + + try: + mark_commodity_exchanged( + db, + account_id=int(account.id), + commodity_id=commodity_id, + occurred_at=occurred_at, + scope=scope, + commodity_name=name, + ) + except Exception as exc: # noqa: BLE001 - 派生索引不能破坏兑换主流程 + logger.warning( + "更新账号商品能力失败 account_id={} commodity_id={}: {}", + account.id, + commodity_id, + exc, + ) + return written def record_gold_spent( @@ -366,7 +503,7 @@ def record_official_exchange( """ if not commodity_id: return False - return emit( + written = emit( db, account_id=account.id, event_type=EVENT_EXCHANGE, @@ -386,11 +523,13 @@ def record_official_exchange( "scope": scope, }, source=OFFICIAL_SYNC_SOURCE, - subject_type="goods", + subject_type="commodity", + subject_key=commodity_id, source_ref=( f"official_exchange:{scope}:{account.id}:{commodity_id}:{_stamp(occurred_at)}" ), ) + return written def _stamp(value: datetime | None) -> str: diff --git a/web/backend/services/douyu_collab_service.py b/web/backend/services/douyu_collab_service.py index fa99f01..37dfcf5 100644 --- a/web/backend/services/douyu_collab_service.py +++ b/web/backend/services/douyu_collab_service.py @@ -34,6 +34,7 @@ from ..models import ( User, ) from .audit_service import record_audit +from .business_events import record_account_query from .collab_common import apply_order_visibility, count_archived from .douyu_activity_query import ( activity_client, @@ -1304,6 +1305,22 @@ def query_activity( commit=False, ) + record_account_query( + db, + account, + query_type="collab_activity", + title="查询鱼翅与积分" if not include_records else "查询积分与兑换记录", + ok=not bool(errors), + detail={ + "order_no": order.order_no, + "include_records": include_records, + "verdict": verdict, + "records": len(records), + "errors": errors[:10], + }, + actor_id=current.id, + ) + if commit: db.commit() db.refresh(order) @@ -1640,10 +1657,34 @@ def refresh_activity_goods( if account is None: raise CollabError("没有带 CK 的斗鱼账号,无法刷新活动商品", code="no_account") active_client = client or _client_for_account(account) - goods = query_activity_goods( - active_client, manual_id=str(config.manual_id or ""), rid=str(config.rid or "") - ) + try: + goods = query_activity_goods( + active_client, + manual_id=str(config.manual_id or ""), + rid=str(config.rid or ""), + ) + except Exception as exc: + record_account_query( + db, + account, + query_type="goods_refresh", + title="刷新活动商品", + ok=False, + detail={"error": str(exc)[:1000]}, + actor_id=current.id, + ) + db.commit() + raise upsert_goods_snapshot(db, goods, commit=False) + record_account_query( + db, + account, + query_type="goods_refresh", + title="刷新活动商品", + ok=True, + detail={"count": len(goods)}, + actor_id=current.id, + ) record_audit( db, current, diff --git a/web/backend/services/douyu_runner_core.py b/web/backend/services/douyu_runner_core.py index 8884be5..fe73501 100644 --- a/web/backend/services/douyu_runner_core.py +++ b/web/backend/services/douyu_runner_core.py @@ -26,6 +26,7 @@ from ..models import ( from .douyu_goods_service import upsert_goods_snapshot from .douyu_service import ( DOUYU_CONFIG_FIELDS, + SUPPORTED_DOUYU_TASK_TYPES, douyu_config_value, douyu_task_payload, ensure_douyu_config, @@ -212,6 +213,27 @@ class DouyuBatchRunnerCore: if result is not None: task.result = result task.finished_at = datetime.now(UTC) + if task.account_id and status in {"success", "failed", "error", "stopped"}: + from .business_events import record_douyu_task_result + + account = ( + db.query(Account).filter(Account.id == task.account_id).first() + ) + if account is not None: + record_douyu_task_result( + db, + account, + task_id=int(task.id), + task_type=str(task.task_type or ""), + task_label=SUPPORTED_DOUYU_TASK_TYPES.get( + str(task.task_type or ""), + str(task.task_type or "斗鱼任务"), + ), + scope=str(task.handbook_scope or ""), + status=status, + message=message, + occurred_at=task.finished_at, + ) db.commit() self._push_task_event(task) self._sync_platform_fulfillment(db, task) diff --git a/web/backend/services/douyu_runner_overview.py b/web/backend/services/douyu_runner_overview.py index 7ae8153..d4e38c1 100644 --- a/web/backend/services/douyu_runner_overview.py +++ b/web/backend/services/douyu_runner_overview.py @@ -5,8 +5,8 @@ 一个**只读**聚合任务:鱼翅 / 积分(含到期时间)/ 精英宝典 / 电竞手册 / 小店 / 官方兑换记录 / **限兑商品(重点看高价值套装是否已拥有)**。 -**不改任何账号状态、不发业务事件** —— 纯查询不是「事实」, -按既有设计例行查询不进时间线,否则查几次就把时间线刷满了。 +查询结果会投影成账号当前状态和商品能力,但不会制造兑换等业务事实。 +任务本身由执行器统一写入 `activity` 时间线;轮询过程不逐次刷事件。 ## 为什么「是否已拥有」能直接查官方 @@ -34,6 +34,7 @@ from core.douyu import DouyuActivityClient from ..models import Account, DouyuTask from .account_binding import binding_snapshot, set_bind_status +from .account_capability_service import sync_account_goods_states from .business_events import record_official_exchange from .douyu_activity_query import ( query_activity_goods, @@ -50,8 +51,9 @@ from .high_value_service import ( extract_high_value_goods, ) -#: 官方兑换记录默认取多少条(完整记录可能很多,一次性拉回来没必要) -EXCHANGE_RECORD_LIMIT = 20 +#: 官方兑换记录单次抓取上限。能力匹配需要更完整的一年记录,详情页只展示前 20 条。 +EXCHANGE_RECORD_FETCH_LIMIT = 100 +EXCHANGE_RECORD_DISPLAY_LIMIT = 20 #: 单项错误的摘要长度(避免把整个 traceback 塞进 task.result) _ERROR_MAX = 200 @@ -144,7 +146,7 @@ def _ts(value: Any) -> Any: class OverviewMixin: - """一键查询域:只读聚合,不写状态、不发事件。""" + """一键查询域:读取官方数据并投影到账号当前状态。""" if TYPE_CHECKING: @@ -212,7 +214,7 @@ class OverviewMixin: return query_exchange_records( client, manual_id=manual_id, - limit=EXCHANGE_RECORD_LIMIT, + limit=EXCHANGE_RECORD_FETCH_LIMIT, ) def _fetch_esports_records( @@ -225,7 +227,7 @@ class OverviewMixin: return query_exchange_records( client, manual_id=esports_manual_id, - limit=EXCHANGE_RECORD_LIMIT, + limit=EXCHANGE_RECORD_FETCH_LIMIT, ) def _fetch_xpd_records( @@ -440,7 +442,7 @@ class OverviewMixin: except Exception as exc: # noqa: BLE001 外部接口边界需要宽泛兜底 errors[key] = _err(exc) continue - overview["exchange_records"][scope] = rows[:EXCHANGE_RECORD_LIMIT] + overview["exchange_records"][scope] = rows[:EXCHANGE_RECORD_DISPLAY_LIMIT] all_records.extend((scope, r) for r in rows) overview[f"exchange_record_count_{scope}"] = len(rows) @@ -450,10 +452,25 @@ class OverviewMixin: db, account, all_records ) overview["exchange_records"] = { - scope: rows[:EXCHANGE_RECORD_LIMIT] + scope: rows[:EXCHANGE_RECORD_DISPLAY_LIMIT] for scope, rows in _group_by_scope(all_records).items() } + # ---- 账号 × 商品能力索引 ---- + # 只有完整商城列表查询成功时才更新,避免把网络失败写成“不可兑换”。 + if goods_query_ok: + try: + overview["commodity_states_synced"] = sync_account_goods_states( + db, + account, + pending_goods, + scope="elite", + observed_at=queried_at, + source="overview", + ) + except Exception as exc: # noqa: BLE001 + errors["commodity_states"] = _err(exc) + # ---- 🎯 高价值套装判定(依赖兑换记录,必须放在它之后)---- if not manual_id: errors["high_value_goods"] = "未配置精英宝典 manualID" @@ -478,7 +495,7 @@ class OverviewMixin: errors["high_value_goods"] = _err(exc) # 查询会回写账号上的余额/积分缓存(各 _refresh_* 内部已写), - # 但**不改生命周期状态**,也不发事件。 + # 但**不改生命周期状态,也不制造业务事实事件**;任务活动由执行器统一记录。 account.updated_at = datetime.now(UTC) owned = [ diff --git a/web/backend/services/douyu_service.py b/web/backend/services/douyu_service.py index 68afac0..a85b93e 100644 --- a/web/backend/services/douyu_service.py +++ b/web/backend/services/douyu_service.py @@ -12,6 +12,7 @@ from core.douyu.activity_client import DouyuActivityClient from core.douyu.cookie_utils import cookie_value from ..models import Account, DouyuConfig, DouyuTask, LoginTask +from .account_events_service import CATEGORY_ACTIVITY, EVENT_TASK_STARTED, emit_bulk SUPPORTED_DOUYU_TASK_TYPES = { "get_bind_qr": "获取绑定二维码", @@ -291,19 +292,47 @@ def create_douyu_planned_tasks( batch_id = uuid.uuid4().hex[:12] payload = payload or {} + task_rows: list[tuple[DouyuTask, Account]] = [] for account in accounts: - db.add( - DouyuTask( - batch_id=batch_id, - account_id=account.id, - account_assigned_to=account.assigned_to, - task_type=task_type, - handbook_scope=handbook_scope, - status="planned", - message="任务已创建,等待执行", - result={"payload": payload} if payload else None, - created_by=created_by, - ) + task = DouyuTask( + batch_id=batch_id, + account_id=account.id, + account_assigned_to=account.assigned_to, + task_type=task_type, + handbook_scope=handbook_scope, + status="planned", + message="任务已创建,等待执行", + result={"payload": payload} if payload else None, + created_by=created_by, + ) + db.add(task) + task_rows.append((task, account)) + db.flush() + if task_rows: + label = SUPPORTED_DOUYU_TASK_TYPES[task_type] + emit_bulk( + db, + [ + { + "account_id": account.id, + "event_type": EVENT_TASK_STARTED, + "title": f"{label}:任务已创建", + "category": CATEGORY_ACTIVITY, + "detail": { + "task_id": task.id, + "task_type": task_type, + "scope": handbook_scope, + "status": "planned", + }, + "source": "douyu_task", + "subject_type": "task", + "subject_key": str(task.id), + "actor_type": "user", + "actor_id": created_by, + "source_ref": f"douyu_task_started:{task.id}", + } + for task, account in task_rows + ], ) db.commit() return batch_id, len(accounts) @@ -328,10 +357,29 @@ def cleanup_orphan_douyu_tasks( if not tasks: return 0 now = datetime.now(UTC) + from .business_events import record_douyu_task_result + for task in tasks: task.status = "stopped" task.message = message task.finished_at = now + if task.account_id: + account = db.query(Account).filter(Account.id == task.account_id).first() + if account is not None: + record_douyu_task_result( + db, + account, + task_id=int(task.id), + task_type=str(task.task_type or ""), + task_label=SUPPORTED_DOUYU_TASK_TYPES.get( + str(task.task_type or ""), + str(task.task_type or "斗鱼任务"), + ), + scope=str(task.handbook_scope or ""), + status="stopped", + message=message, + occurred_at=now, + ) db.commit() return len(tasks) diff --git a/web/backend/services/platform_fulfillment/account_selector.py b/web/backend/services/platform_fulfillment/account_selector.py index cad7947..d01c76e 100644 --- a/web/backend/services/platform_fulfillment/account_selector.py +++ b/web/backend/services/platform_fulfillment/account_selector.py @@ -13,7 +13,14 @@ from sqlalchemy import case, or_, select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session -from ...models import Account, AccountEvent, AccountLease, User +from ...models import Account, AccountCommodityState, AccountEvent, AccountLease, User +from ..account_capability_service import AVAILABILITY_AVAILABLE +from ..account_events_service import ( + CATEGORY_OPS, + EVENT_LEASE_ACQUIRED, + EVENT_LEASE_RELEASED, + emit, +) from ..account_lifecycle import MANUAL_STATES VALIDATION_LEASE_MINUTES = 5 @@ -136,6 +143,10 @@ def live_candidate_accounts( Account.cookie != "", Account.auto_managed.is_(True), Account.status.notin_(MANUAL_STATES), + or_( + Account.role_change_available_at.is_(None), + Account.role_change_available_at <= _now(), + ), or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)), ~active_lease, ) @@ -172,6 +183,80 @@ def live_candidate_accounts( ) +def capability_candidate_accounts( + db: Session, + *, + commodity_id: str, + required_points: int = 0, + scope: str = "elite", + limit: int = 20, + now: datetime | None = None, +) -> list[Account]: + """从新鲜的商品能力索引读取候选账号,不产生外部请求。""" + commodity = commodity_id.strip() + if not commodity: + return [] + moment = _now(now) + since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS) + owner_ids = _pool_owner_ids() + active_lease = ( + select(AccountLease.id) + .where(AccountLease.active_account_id == Account.id) + .exists() + ) + return ( + db.query(Account) + .join( + AccountCommodityState, + AccountCommodityState.account_id == Account.id, + ) + .filter( + AccountCommodityState.platform == "douyu", + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id == commodity, + AccountCommodityState.availability == AVAILABILITY_AVAILABLE, + AccountCommodityState.valid_until.isnot(None), + AccountCommodityState.valid_until > moment, + or_( + AccountCommodityState.available_from.is_(None), + AccountCommodityState.available_from <= moment, + ), + or_( + AccountCommodityState.available_until.is_(None), + AccountCommodityState.available_until >= moment, + ), + or_( + AccountCommodityState.last_exchange_at.is_(None), + AccountCommodityState.last_exchange_at < since, + ), + Account.cookie.isnot(None), + Account.cookie != "", + Account.auto_managed.is_(True), + Account.status.notin_(MANUAL_STATES), + or_( + Account.role_change_available_at.is_(None), + Account.role_change_available_at <= moment, + ), + or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)), + ~active_lease, + ) + .order_by( + case((Account.ck_check_status == "valid", 0), else_=1), + case((Account.status == "active", 0), else_=1), + case((Account.elite_opened.is_(True), 0), else_=1), + case( + (Account.points >= max(0, int(required_points)), 0), + else_=1, + ), + Account.points.asc(), + AccountCommodityState.observed_at.desc(), + Account.id.asc(), + ) + .limit(max(1, min(int(limit), 100))) + .all() + ) + + def has_recent_exchange( db: Session, *, @@ -231,6 +316,26 @@ def lease_account( if lease in db: db.expunge(lease) return None + emit( + db, + account_id=int(candidate.account_id), + event_type=EVENT_LEASE_ACQUIRED, + title=f"履约占用:任务 #{task_id}", + category=CATEGORY_OPS, + detail={ + "lease_id": lease.id, + "task_id": task_id, + "holder_user_id": holder_user_id, + "commodity_id": commodity_id, + "purpose": "platform_fulfillment", + }, + source="lease", + subject_type="task", + subject_key=str(task_id), + actor_type="user", + actor_id=holder_user_id, + source_ref=f"account_lease_acquired:{lease.id}", + ) db.commit() return lease @@ -265,6 +370,23 @@ def release_lease( lease.status = "released" lease.released_at = _now(now) lease.release_reason = str(reason or "")[:64] + emit( + db, + account_id=int(lease.account_id), + event_type=EVENT_LEASE_RELEASED, + title=f"释放履约占用:{reason}", + category=CATEGORY_OPS, + detail={ + "lease_id": lease.id, + "task_id": lease.batch_id, + "reason": str(reason or "")[:64], + }, + source="lease", + subject_type="lease", + subject_key=str(lease.id), + actor_type="system", + source_ref=f"account_lease_released:{lease.id}", + ) db.commit() return True @@ -292,6 +414,24 @@ def expire_platform_fulfillment_leases( lease.status = "expired" lease.released_at = moment lease.release_reason = "ttl_expired" + emit( + db, + account_id=int(lease.account_id), + event_type=EVENT_LEASE_RELEASED, + title="履约租约已过期", + category=CATEGORY_OPS, + occurred_at=moment, + detail={ + "lease_id": lease.id, + "task_id": lease.batch_id, + "reason": "ttl_expired", + }, + source="lease", + subject_type="lease", + subject_key=str(lease.id), + actor_type="system", + source_ref=f"account_lease_released:{lease.id}", + ) if leases: db.commit() return len(leases) @@ -302,6 +442,7 @@ __all__ = [ "EXCHANGE_COOLDOWN_DAYS", "VALIDATION_LEASE_MINUTES", "AccountCandidate", + "capability_candidate_accounts", "eligible_accounts", "expire_platform_fulfillment_leases", "has_recent_exchange", diff --git a/web/backend/services/platform_fulfillment/auto_allocator.py b/web/backend/services/platform_fulfillment/auto_allocator.py index 71eea09..9eb6267 100644 --- a/web/backend/services/platform_fulfillment/auto_allocator.py +++ b/web/backend/services/platform_fulfillment/auto_allocator.py @@ -116,7 +116,7 @@ def run_auto_allocation_once( ) candidates = ( query.order_by( - PlatformFulfillmentTask.next_allocate_at.asc(), + PlatformFulfillmentTask.paid_at.asc(), PlatformFulfillmentTask.id.asc(), ) .limit(batch_size) diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index 588b731..d654e08 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -10,6 +10,7 @@ from threading import Lock from typing import Any from fastapi import HTTPException +from loguru import logger from sqlalchemy import or_ from sqlalchemy.orm import Session @@ -28,6 +29,12 @@ from ..account_binding import ( binding_role_from_result, pending_binding_role_from_result, ) +from ..account_capability_service import ( + AVAILABILITY_AVAILABLE, + AVAILABILITY_LIMITED, + record_account_commodity_state, +) +from ..business_events import record_account_query, record_douyu_task_started 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, stop_douyu_batches @@ -39,6 +46,7 @@ from ..external_order_source import ( ) from .account_selector import ( AccountCandidate, + capability_candidate_accounts, has_recent_exchange, lease_account, live_candidate_accounts, @@ -63,6 +71,11 @@ BINDING_QR_TTL_SECONDS = int(os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "600") AUTO_SYNC_INTERVAL_SECONDS = 900.0 DEFAULT_LIVE_CANDIDATE_LIMIT = 20 + +def _matching_mode() -> str: + mode = os.getenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid").strip().lower() + return mode if mode in {"legacy", "hybrid", "capability"} else "hybrid" + _SYNC_LOCK = Lock() _AUTO_SYNC_LOCK = Lock() _AUTO_SYNC_LAST_ATTEMPT = float("-inf") @@ -237,6 +250,7 @@ def _upsert_order_snapshot( task.source_snapshot_json = _jsonable(snapshot) return task, created, False + previous_execution_status = task.execution_status terminal = ( terminal_order or _snapshot_value( @@ -331,10 +345,22 @@ def _upsert_order_snapshot( task.last_error = "订单已关闭或直播履约配置已停用" task.next_allocate_at = None else: - _apply_mapping(task, mapping) - if task.execution_status == "ready" and task.account_id is None: - task.next_allocate_at = _now() - elif task.account_id is not None: + # 订单快照会被重复投递。只有未分配任务从「待映射」进入「待分配」时 + # 才允许改生命周期状态;已分配任务不能被快照更新打回 pending。 + update_execution_status = task.account_id is None and ( + previous_execution_status == "pending_mapping" or mapping is None + ) + _apply_mapping( + task, + mapping, + update_execution_status=update_execution_status, + ) + if task.account_id is not None: + task.next_allocate_at = None + elif task.execution_status == "ready": + if previous_execution_status != "ready" or task.next_allocate_at is None: + task.next_allocate_at = _now() + else: task.next_allocate_at = None after = ( @@ -662,18 +688,24 @@ def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask: def _apply_mapping( task: PlatformFulfillmentTask, mapping: PlatformCommodityMapping | None, + *, + update_execution_status: bool = True, ) -> None: - if mapping is None: + if mapping is not None: + task.commodity_mapping_id = mapping.id + task.commodity_id = mapping.commodity_id + task.required_points = mapping.required_points + else: task.commodity_mapping_id = None task.commodity_id = "" task.required_points = None + if not update_execution_status: + return + if mapping is None: task.execution_status = "pending_mapping" task.issue_code = "mapping_missing" task.last_error = "内部 SKU 尚未配置斗鱼商品映射" return - task.commodity_mapping_id = mapping.id - task.commodity_id = mapping.commodity_id - task.required_points = mapping.required_points task.execution_status = "ready" task.issue_code = "" task.last_error = "" @@ -780,7 +812,10 @@ def _sync_pending_tasks( task.scope = SCOPE_ELITE task.source_snapshot_json = _jsonable(row) task.updated_at = _now() - if task.execution_status in {"pending_mapping", "ready"}: + if ( + task.account_id is None + and task.execution_status in {"pending_mapping", "ready"} + ): _apply_mapping(task, mapping) if task.execution_status == "ready" and task.account_id is None: task.next_allocate_at = _now() @@ -1262,6 +1297,7 @@ def upsert_mapping( pending = db.query(PlatformFulfillmentTask).filter( PlatformFulfillmentTask.internal_sku_key == sku_key, + PlatformFulfillmentTask.account_id.is_(None), PlatformFulfillmentTask.execution_status.in_( ["pending_mapping", "ready", "manual_required"] ), @@ -1324,19 +1360,39 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any] except ValueError: candidate_limit = DEFAULT_LIVE_CANDIDATE_LIMIT candidate_limit = max(1, min(candidate_limit, 100)) - # 缓存用于优先排序,最终是否可用仍由下面的逐个实时检测决定。 - candidates = live_candidate_accounts( - db, - limit=candidate_limit, - required_points=required_points, - commodity_id=task.commodity_id, + mode = _matching_mode() + capability_candidates = ( + capability_candidate_accounts( + db, + limit=candidate_limit, + required_points=required_points, + commodity_id=task.commodity_id, + scope=task.scope or SCOPE_ELITE, + ) + if mode in {"hybrid", "capability"} + else [] ) + capability_first = bool(capability_candidates) + candidates = capability_candidates + if not candidates and mode != "capability": + # hybrid 模式下能力索引为空或全部过期时,保留旧逻辑兜底。 + candidates = live_candidate_accounts( + db, + limit=candidate_limit, + required_points=required_points, + commodity_id=task.commodity_id, + ) diagnostics: list[dict[str, Any]] = [] qualified: list[tuple[Account, DouyuLiveAccountState]] = [] selected: AccountCandidate | None = None selected_state: DouyuLiveAccountState | None = None lease = None - for account in candidates: + + def inspect_candidate( + account: Account, + *, + source: str, + ) -> tuple[Account, DouyuLiveAccountState] | None: live_state = refresh_douyu_account_state( db, account, @@ -1344,13 +1400,40 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any] rid=rid, act_alias=act_alias, ) - reasons = live_state.blocking_reasons(commodity_id=task.commodity_id) - if has_recent_exchange( + limited = task.commodity_id in live_state.limited_ids + recent_exchange = has_recent_exchange( db, account_id=int(account.id), commodity_id=task.commodity_id, - ): + ) + reasons = live_state.blocking_reasons(commodity_id=task.commodity_id) + if recent_exchange: reasons.append("365 天内已有该商品兑换事件") + + if live_state.ck_verdict == "valid" and not live_state.error: + try: + record_account_commodity_state( + db, + account, + commodity_id=task.commodity_id, + availability=( + AVAILABILITY_LIMITED if limited else AVAILABILITY_AVAILABLE + ), + blocking_reason=( + "该账号已达此商品兑换上限" if limited else "" + ), + raw_status="1" if limited else "0", + observed_at=live_state.checked_at, + source="live_check", + scope=task.scope or SCOPE_ELITE, + ) + except Exception as exc: # noqa: BLE001 - 派生索引不能阻止本次选号 + logger.warning( + "写入选号商品能力失败 account_id={} commodity_id={}: {}", + account.id, + task.commodity_id, + exc, + ) if reasons: diagnostics.append( { @@ -1360,10 +1443,45 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any] "eliteOpened": live_state.elite_opened, "points": live_state.points, "reasons": reasons, + "source": source, } ) - continue - qualified.append((account, live_state)) + return None + return account, live_state + + def inspect_batch( + batch: list[Account], + *, + source: str, + ) -> None: + # 能力索引已按成本排序,首个确认通过即可;旧兜底最多比较 3 个。 + for account in batch: + inspected = inspect_candidate(account, source=source) + if inspected is None: + continue + qualified.append(inspected) + if source == "capability" or len(qualified) >= 3: + return + + if capability_candidates: + inspect_batch(capability_candidates, source="capability") + elif mode != "capability": + inspect_batch(candidates, source="live") + + if not qualified and capability_first and mode == "hybrid": + checked_ids = {int(account.id) for account in capability_candidates} + fallback_candidates = [ + account + for account in live_candidate_accounts( + db, + limit=candidate_limit, + required_points=required_points, + commodity_id=task.commodity_id, + ) + if int(account.id) not in checked_ids + ] + candidates = [*candidates, *fallback_candidates] + inspect_batch(fallback_candidates, source="live_fallback") # 积分和宝典开通不淘汰账号,只影响后续处理成本。优先选已经可直接兑换的账号, # 其次是只需充值、只需开通、两者都需要的账号。 @@ -1404,6 +1522,7 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any] "eliteOpened": live_state.elite_opened, "points": live_state.points, "reasons": ["账号刚被其他任务占用"], + "source": "capability" if capability_first else "live", } ) if selected is None or selected_state is None or lease is None: @@ -1411,7 +1530,11 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any] task.next_allocate_at = _now() + timedelta(seconds=45) task.issue_code = "no_eligible_account" if not candidates: - task.last_error = "没有带 CK、允许自动管理且未停用的斗鱼账号" + task.last_error = ( + "商品能力池暂无可用账号" + if mode == "capability" + else "没有带 CK、允许自动管理且未停用的斗鱼账号" + ) else: summary = ";".join( f"{item['accountName']}: {', '.join(item['reasons'][:3])}" @@ -1428,6 +1551,8 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any] "account_allocation_failed", detail={ "candidateCount": len(candidates), + "matchingMode": mode, + "capabilityCandidates": len(capability_candidates), "diagnostics": diagnostics, }, ) @@ -1644,6 +1769,17 @@ async def start_binding( ) db.add(bind_task) db.flush() + account = db.query(Account).filter(Account.id == task.account_id).first() + if account is not None: + record_douyu_task_started( + db, + account, + task_id=int(bind_task.id), + task_type="get_bind_qr", + task_label="获取绑定二维码", + scope="elite", + actor_id=current.id, + ) task.bind_task_id = bind_task.id task.binding_status = "preparing" task.execution_status = "waiting_bind" @@ -1855,6 +1991,17 @@ async def confirm_binding( ) db.add(confirm_task) db.flush() + account = db.query(Account).filter(Account.id == task.account_id).first() + if account is not None: + record_douyu_task_started( + db, + account, + task_id=int(confirm_task.id), + task_type="confirm_bind", + task_label="确认绑定", + scope="elite", + actor_id=current.id, + ) task.bind_task_id = confirm_task.id task.binding_status = "confirming" task.execution_status = "binding_confirming" @@ -1903,6 +2050,15 @@ def refresh_exchange_eligibility( account.elite_opened = bool(eligibility.elite_user_info.get("manual_type")) account.points = eligibility.points except Exception as exc: # noqa: BLE001 外部接口错误要落成可重试的检查失败 + record_account_query( + db, + account, + query_type="exchange_eligibility", + title="刷新兑换资格", + ok=False, + detail={"error": str(exc)[:1000], "commodity_id": task.commodity_id}, + actor_id=current.id, + ) task.execution_status = "manual_required" task.exchange_status = "check_failed" task.issue_code = "eligibility_check_failed" @@ -1936,6 +2092,40 @@ def refresh_exchange_eligibility( task.exchange_status = "eligible" task.issue_code = "" task.last_error = "" + record_account_commodity_state( + db, + account, + commodity_id=task.commodity_id, + availability=( + AVAILABILITY_LIMITED + if task.commodity_id in eligibility.limited_ids + else AVAILABILITY_AVAILABLE + ), + blocking_reason=( + "该账号已达此商品兑换上限" + if task.commodity_id in eligibility.limited_ids + else "" + ), + raw_status="1" if task.commodity_id in eligibility.limited_ids else "0", + observed_at=_now(), + source="eligibility_check", + scope=task.scope or SCOPE_ELITE, + ) + record_account_query( + db, + account, + query_type="exchange_eligibility", + title="刷新兑换资格", + ok=True, + detail={ + "commodity_id": task.commodity_id, + "exchange_status": task.exchange_status, + "limited": task.commodity_id in eligibility.limited_ids, + "points": account.points, + "elite_opened": account.elite_opened, + }, + actor_id=current.id, + ) # 积分不足、未开通和限兑都不是流程终点:角色已经绑定,账号继续保留, # 后续充值/开通/解除限兑后刷新资格即可。 task.execution_status = "bound" diff --git a/web/frontend/src/api/accounts.ts b/web/frontend/src/api/accounts.ts index f7dab6d..255701c 100644 --- a/web/frontend/src/api/accounts.ts +++ b/web/frontend/src/api/accounts.ts @@ -1,5 +1,6 @@ import api from './client'; import type { + AccountCommodityStates, AccountExchangeRecords, AccountEventPage, AccountItem, @@ -113,6 +114,9 @@ export const accountApi = { // 三个作用域的**官方**兑换记录(点列表那一格时按需拉取,不进列表响应) exchangeRecords: (id: number) => api.get(`/accounts/${id}/exchange-records`), + // 账号 × 商品当前能力索引(查询快照,带最后确认时间) + commodities: (id: number, params?: { scope?: string; availability?: string; limit?: number }) => + api.get(`/accounts/${id}/commodities`, { params }), // 时间线(倒序分页),event_type 为空表示全部 events: ( id: number, diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index 538ac58..833dd66 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -160,12 +160,21 @@ export type AccountEventType = | 'elite_opened' | 'esports_opened' | 'assigned' - | 'tag_changed'; + | 'tag_changed' + | 'remark_changed' + | 'automation_changed' + | 'task_started' + | 'task_succeeded' + | 'task_failed' + | 'task_stopped' + | 'query_completed' + | 'lease_acquired' + | 'lease_released'; export interface AccountEventItem { id: number; event_type: AccountEventType | string; - /** 粗分类:lifecycle / auth / business / ops */ + /** 粗分类:lifecycle / auth / business / activity / ops */ category?: string; occurred_at: string; title: string; @@ -187,6 +196,41 @@ export interface AccountEventPage { page_size: number; } +export type AccountCommodityAvailability = + | 'available' + | 'limited' + | 'no_stock' + | 'not_open' + | 'not_offered' + | 'expired' + | 'unknown'; + +export interface AccountCommodityState { + commodity_id: string; + commodity_name: string; + scope: string; + availability: AccountCommodityAvailability; + blocking_reason: string; + raw_status: string; + time_limited: boolean; + available_from: string | null; + available_until: string | null; + schedule: Array>; + observed_at: string | null; + valid_until: string | null; + next_check_at: string | null; + last_exchange_at: string | null; + exchange_count_365d: number; + fresh: boolean; + source: string; + error_code: string; +} + +export interface AccountCommodityStates { + items: AccountCommodityState[]; + summary: Record; +} + export interface AccountOverviewStats { recharge_total: number; exchange_count: number; @@ -220,6 +264,7 @@ export interface AccountOverview { points: number | null; gold_balance: number | null; exchange_balance: number | null; + commodity_capability?: Record; /** 积分到期时间(一键查询会刷新它) */ points_expire_at: string | null; game_name: string; diff --git a/web/frontend/src/pages/AccountDetailPage.tsx b/web/frontend/src/pages/AccountDetailPage.tsx index 4873572..71eee0a 100644 --- a/web/frontend/src/pages/AccountDetailPage.tsx +++ b/web/frontend/src/pages/AccountDetailPage.tsx @@ -7,7 +7,7 @@ import type { TableProps } from 'antd'; import { ArrowLeftOutlined, EditOutlined, ReloadOutlined, ThunderboltOutlined, } from '@ant-design/icons'; -import { accountApi, douyuApi, userApi, type AccountEventItem, type AccountOverview, type HighValueAssetState, type HighValueStatus, type UserInfo } from '../api/modules'; +import { accountApi, douyuApi, userApi, type AccountCommodityState, type AccountEventItem, type AccountOverview, type HighValueAssetState, type HighValueStatus, type UserInfo } from '../api/modules'; import AccountOverviewPanel from './douyu-tasks/AccountOverviewPanel'; import { getErrorMessage } from '../utils/error'; import { message } from '../utils/antdMessage'; @@ -36,6 +36,14 @@ const EVENT_STYLE: Record = { assigned: { label: '分配', color: 'default' }, tag_changed: { label: '标签', color: 'default' }, remark_changed: { label: '备注', color: 'default' }, + automation_changed: { label: '自动化开关', color: 'geekblue' }, + task_started: { label: '任务创建', color: 'blue' }, + task_succeeded: { label: '任务成功', color: 'green' }, + task_failed: { label: '任务失败', color: 'red' }, + task_stopped: { label: '任务停止', color: 'orange' }, + query_completed: { label: '查询完成', color: 'blue' }, + lease_acquired: { label: '账号占用', color: 'cyan' }, + lease_released: { label: '账号释放', color: 'default' }, }; /** 事件粗分类(与后端 `account_events_service.CATEGORY_*` 对应)。 */ @@ -43,6 +51,7 @@ const CATEGORY_OPTIONS = [ { value: 'lifecycle', label: '状态变迁' }, { value: 'auth', label: '登录与 CK' }, { value: 'business', label: '业务流水' }, + { value: 'activity', label: '查询与任务' }, { value: 'ops', label: '人工操作' }, ]; @@ -96,6 +105,21 @@ function eventTag(type: string) { return {style.label}; } +const COMMODITY_STATE: Record = { + available: { label: '可兑换', color: 'green' }, + limited: { label: '已达上限', color: 'orange' }, + no_stock: { label: '无库存', color: 'default' }, + not_open: { label: '未开放', color: 'gold' }, + not_offered: { label: '本次未返回', color: 'default' }, + expired: { label: '限时已结束', color: 'default' }, + unknown: { label: '待确认', color: 'default' }, +}; + +function commodityStateTag(value: string) { + const state = COMMODITY_STATE[value] ?? COMMODITY_STATE.unknown; + return {state.label}; +} + /** 金额展示:充值为正(绿色 ¥),兑换消耗为负(红色积分)。 */ function amountText(item: AccountEventItem) { if (item.amount === null || item.amount === undefined) return null; @@ -127,6 +151,9 @@ export default function AccountDetailPage() { const [eventType, setEventType] = useState(''); const [category, setCategory] = useState(''); const [eventsLoading, setEventsLoading] = useState(false); + const [commodities, setCommodities] = useState([]); + const [commoditySummary, setCommoditySummary] = useState>({}); + const [commoditiesLoading, setCommoditiesLoading] = useState(false); const [tagDraft, setTagDraft] = useState(''); // 一键查询:向斗鱼实时查一次该账号的全部关键信息(异步任务 + 轮询结果) const [ovLoading, setOvLoading] = useState(false); @@ -150,6 +177,20 @@ export default function AccountDetailPage() { return () => { alive = false; }; }, []); + const loadCommodities = useCallback(async () => { + if (!accountId) return; + setCommoditiesLoading(true); + try { + const data = await accountApi.commodities(accountId); + setCommodities(data.items); + setCommoditySummary(data.summary); + } catch (e: unknown) { + message.error(getErrorMessage(e)); + } finally { + setCommoditiesLoading(false); + } + }, [accountId]); + // 一键查询:建一个只读聚合任务 → 轮询**账号自身**直到快照更新。 // @@ -185,6 +226,7 @@ export default function AccountDetailPage() { first = false; if ((marker ?? '') !== before) { setOverview(fresh); + void loadCommodities(); message.success('查询完成'); return; } @@ -195,7 +237,7 @@ export default function AccountDetailPage() { } finally { setOvLoading(false); } - }, [id, overview?.overview_queried_at]); + }, [id, loadCommodities, overview?.overview_queried_at]); const loadOverview = useCallback(async () => { if (!accountId) return; @@ -232,6 +274,10 @@ export default function AccountDetailPage() { void loadOverview(); }, [loadOverview]); + useEffect(() => { + void loadCommodities(); + }, [loadCommodities]); + useEffect(() => { void loadEvents(); }, [loadEvents]); @@ -267,6 +313,73 @@ export default function AccountDetailPage() { }, ]; + const commodityColumns: TableProps['columns'] = [ + { + title: '商品', + key: 'commodity', + width: 240, + render: (_value, row) => ( + + {row.commodity_name || row.commodity_id} + + {row.commodity_id} + + + ), + }, + { + title: '当前能力', + dataIndex: 'availability', + width: 110, + render: (value: string) => commodityStateTag(value), + }, + { + title: '阻塞原因', + dataIndex: 'blocking_reason', + ellipsis: true, + render: (value: string) => value || -, + }, + { + title: '限时窗口', + width: 210, + render: (_value, row) => + row.time_limited || row.available_from || row.available_until ? ( + + {row.time_limited && 限时兑换} + + {formatTime(row.available_from)} ~ {formatTime(row.available_until)} + + + ) : ( + 长期 + ), + }, + { + title: '近一年兑换', + width: 150, + render: (_value, row) => ( + + {row.exchange_count_365d} 次 + + {row.last_exchange_at ? formatTime(row.last_exchange_at) : '无记录'} + + + ), + }, + { + title: '最后确认', + width: 170, + render: (_value, row) => ( + + {formatTime(row.observed_at)} + + {row.fresh ? '有效' : '需复查'} + + + ), + }, + ]; + if (!accountId) { return ; } @@ -344,7 +457,7 @@ export default function AccountDetailPage() { - {status === 'disabled' || status === 'archived' ? ( @@ -660,6 +773,42 @@ export default function AccountDetailPage() { + + 商品兑换能力 + + 可兑换 {commoditySummary.fresh_available ?? 0} / 共 {commoditySummary.total ?? 0} + + + } + extra={ + + } + > + + rowKey={(row) => `${row.scope}:${row.commodity_id}`} + columns={commodityColumns} + dataSource={commodities} + size="small" + loading={commoditiesLoading} + pagination={false} + scroll={{ x: 900, y: 320 }} + locale={{ + emptyText: ( + + ), + }} + /> + + {/* ── 卡片 3:一键查询结果 ────────────────────────── 放在账号信息**下面** —— 它是补充信息(账号表里没有的两项), 不该压在最上面抢主视觉。 */}