From efb140cf270adf1f98a0c927d7c208ca6d3069e3 Mon Sep 17 00:00:00 2001 From: yml Date: Tue, 24 Nov 2026 01:44:57 +0800 Subject: [PATCH] =?UTF-8?q?fix(fulfillment):=20=E6=8C=89=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=E5=BD=92=E5=B1=9E=E6=94=B6=E6=95=9B=E5=B1=A5=E7=BA=A6=E8=A7=92?= =?UTF-8?q?=E8=89=B2=E7=BB=91=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 绑定任务创建时写入订单归属,不再按账号和最新任务猜测 - 只有订单自己的绑定证据能改变订单状态,查询任务不再结算 - 无归属确认必须匹配本单目标角色且创建于本租约 - 订单 bound 后冻结,失败只认当前绑定任务 - 启动对账支持确认回调丢失恢复 - 补充归属、目标、租约窗口回归测试与复盘文档,并记录生产只读审计结论 --- docs/README.md | 1 + docs/斗鱼/DOUYU_PROTOCOL_OVERVIEW.md | 6 + docs/斗鱼/履约绑定状态机与踩坑复盘.md | 281 ++++++ docs/直播账号履约工作台.md | 14 + tests/test_douyu_binding_state.py | 4 +- tests/test_migrations.py | 2 + tests/test_platform_fulfillment.py | 493 +++++++--- web/backend/background_runtime.py | 2 +- web/backend/services/binding_ownership.py | 163 ++++ web/backend/services/douyu_service.py | 16 +- .../services/platform_fulfillment/binding.py | 887 ++++++++++++------ .../src/pages/PlatformFulfillmentPage.tsx | 15 + 12 files changed, 1467 insertions(+), 417 deletions(-) create mode 100644 docs/斗鱼/履约绑定状态机与踩坑复盘.md create mode 100644 web/backend/services/binding_ownership.py diff --git a/docs/README.md b/docs/README.md index 5fbc547..1723377 100644 --- a/docs/README.md +++ b/docs/README.md @@ -20,6 +20,7 @@ - [精英宝典 HAR 提取](虎牙/HAR提取CK与积分中心.md):HAR 中的完整 CK、积分中心和商品结构。 - [皮肤准入映射分析](皮肤准入映射分析.md):快手皮肤订单到斗鱼商品的覆盖与映射边界。 - [直播账号履约工作台](直播账号履约工作台.md):order_site 人工订单、斗鱼账号租约、客户扫码绑定和人工兑换。 +- [履约绑定状态机与踩坑复盘](斗鱼/履约绑定状态机与踩坑复盘.md):为什么履约绑定反复出错、任务归属、目标角色匹配和绑定不变量。 - [直播账号履约分类与映射规划](直播账号履约工作台分类与映射规划.md):斗鱼单平台阶段的预售/现货分类、工作队列、映射 CRUD 和分阶段 TODO。 - [斗鱼协议总览](斗鱼/DOUYU_PROTOCOL_OVERVIEW.md):斗鱼绑定、精英宝典、兑换、支付、多 alias 判定和排障日志的统一入口。 - [斗鱼账号平台最终实施设计](斗鱼/斗鱼账号平台最终实施设计.md):统一查询、同步投影、工作队列、登录预算、供给库存和选号的最终实施主线。 diff --git a/docs/斗鱼/DOUYU_PROTOCOL_OVERVIEW.md b/docs/斗鱼/DOUYU_PROTOCOL_OVERVIEW.md index 7eb0675..0b936b0 100644 --- a/docs/斗鱼/DOUYU_PROTOCOL_OVERVIEW.md +++ b/docs/斗鱼/DOUYU_PROTOCOL_OVERVIEW.md @@ -29,11 +29,17 @@ | 只读查询统一入口 | `web/backend/services/douyu_activity_query.py` | | 任务类型和入口校验 | `web/backend/services/douyu_service.py` | | 任务并发与任务槽 | `web/backend/services/task_runtime.py` | +| 履约绑定任务归属 | `web/backend/services/binding_ownership.py` | | 履约投影和客户侧会话 | `web/backend/services/platform_fulfillment/` | 页面、履约、外部单协作和自动化不得自行解释 `bindAct` / `needBindAct`,只能消费 `binding_snapshot()`、`binding_pending_decision()` 及其派生结果。 +履约订单还必须在**任务归属**成立时才消费绑定结果:只有带 +`platform_task_id == 订单 id` 的绑定任务(或订单当前挂着的兼容旧任务)才能结算, +查询任务不能结算订单。归属规则、目标角色匹配和踩坑复盘见 +[履约绑定状态机与踩坑复盘](履约绑定状态机与踩坑复盘.md)。 + ## 凭证与请求约束 - 业务请求依赖斗鱼登录 Cookie;写请求还可能需要 `cvl_csrf_token` / `acf_ccn`。 diff --git a/docs/斗鱼/履约绑定状态机与踩坑复盘.md b/docs/斗鱼/履约绑定状态机与踩坑复盘.md new file mode 100644 index 0000000..ab85fa2 --- /dev/null +++ b/docs/斗鱼/履约绑定状态机与踩坑复盘.md @@ -0,0 +1,281 @@ +# 履约绑定为什么反复出问题:根因复盘与状态机 + +更新时间:2026-11-24 + +本文回答一个问题:精英宝典工作台的「获取绑定二维码 / 确认绑定」一直正常, +为什么直播账号履约工作台的角色绑定改了四五次还是经常出错,以及现在用哪几条 +不变量把它收住。 + +相关文档: + +- 协议字段与 pending 判定:[DOUYU_PROTOCOL_OVERVIEW](DOUYU_PROTOCOL_OVERVIEW.md) +- 履约流程与选号:[直播账号履约工作台](../直播账号履约工作台.md) + +## 一、先区分两件事:任务视图 vs 订单投影 + +精英宝典工作台是**任务视图**: + +```text +一条 DouyuTask -> 一个 result -> 页面直接渲染这个 result +``` + +- 待确认角色、二维码、`bindAct` 都只属于这条任务; +- 账号的 `game_name` / `role_bind_status` 只是任务的副产物; +- 任务结束,视图结束。没有「这条结果属于哪张订单」的问题。 + +直播账号履约是**订单投影**: + +```text +一个账号在一段时间内属于一张订单 +账号上可能出现多条任务(订单自己创建的、工作台手工创建的、上一张订单遗留的) +订单要在这些任务里判断:哪条证据属于我、我现在该是什么状态 +``` + +出问题的从来不是斗鱼协议,而是**归属**:履约层一直试图用「账号 + 最新任务 + +租约 active」去猜一条任务属于哪张订单。猜错一次,订单状态就错一次。 + +## 二、这轮修复各自修了什么,又留下了什么 + +从 2026-11-18 到 11-23,绑定相关提交有 13 个;下表只列与履约投影直接相关的几条。 + +| 提交 | 做法 | 当时修的现象 | 留下的新问题 | +| --- | --- | --- | --- | +| `9e6055b` 通过状态转换识别最新角色 | pending 判定引入 baseline / 同 alias 状态迁移 | 同名旧角色被当成待确认 | 仍是任务内判定,没有订单归属 | +| `8f1b0e2` 收口绑定状态判定 | 履约只消费 `binding_snapshot()` | 各处各写一套 `bindAct` | 订单仍不知道证据属于谁 | +| `fa75ce6` 修正状态与冷却 | 冷却只在 `bindAct=1` 时成立 | `bindAct=0` 被误判冷却 | 同上 | +| `23c4b93` 用较新观测收敛旧 pending | 新增 `query_game_name` 观测 -> bound | 客户在工作台完成后订单卡在待确认 | 观测是账号级事实,不能证明本单;且运行时根本不会创建带 `platform_task_id` 的查询任务,这条路径基本是死代码 | +| `58d7826` 确认角色观测直接置 bound | 当前任务 confirmed 或较新观测 confirmed -> bound | 回调丢失后订单卡住 | 观测无法区分「本次确认」和「账号历史同名绑定」,会把误判重新引回来 | +| `0a32f24` + 迁移 0126 | 一次性把误判的 bound 改回 role_ready | 历史账号绑定覆盖待确认角色 | **只修数据,没加代码约束**;同样的误判可以再次发生 | +| `e6629a9` + 迁移 0127 | 把账号上最新的待确认任务挂到活跃订单 | 工作台扫码后订单看不到角色 | 「最新」仍然是猜测:另一个订单/另一条手工任务也可以是最新 | + +共同点: + +1. 每次都在**增加一个新的推断来源**(账号绑定、较新观测、最新待确认任务), + 但没有定义「什么证据才允许改这张订单」; +2. 每个修复只覆盖当时那个最小复现场景,测试也是「这个场景现在能过」, + 没有一条测试写「不属于本单的任务永远不能改订单」; +3. 旧的状态守卫被一段段搬移/删除,最后几条入口的过滤条件各不相同: + `refresh_binding`、`sync_task_from_binding_runner`、`reconcile_*`、 + 迁移回填,各有一套 `binding_status` / `scope` / 时间条件; +4. 所有写入都直接改 `platform_fulfillment_tasks`,没有「本次绑定会话」的概念, + 所以「上一个订单的迟到回调」和「本单的确认」在数据上长得一样。 + +## 三、抓包能证明什么 + +2026-11-17 / 11-22 的 HAR(`/Users/yml/抓包/斗鱼`)确认了协议事实: + +- 扫码前:`bindAccount=0, bindRole=0, bindAct=0`; +- 扫码选中角色后:`bindAccount=1, bindRole=1, bindAct=0`,同一活动 alias 下 + `needBindAct=1`; +- `actBind` 成功后:`bindAct=1`,此时才允许写 `bound`; +- `needBindAct` 在绑定完成后仍长期为 1,**不能单独证明 pending**; +- 多个 alias 可能给出不同角色:`11.22-斗鱼可以换绑-客户账号无法绑定-2.har` + 中,`20260120QYOOB` 是 `bindAct=1`(旧角色 Dollh),`cjm` 是 `bindAct=0` + (新扫角色 鉤ヾ),随后 `actBind` 返回 `-200001 未到可换绑时间`。 + 也就是说:**某条 alias 的 pending 不等于本单可以确认**,动作 alias 才是唯一 + 可确认通道(代码里由 `binding_pending_decision` 的 `actionable_aliases` 处理)。 + +这些结论解决的是「一条任务的结果怎么解释」。它们**不能**回答「这条任务属于哪张 +订单」。这一轮修复之后仍然出问题,就是因为一直在这层之上加推断。 + +## 四、现在的模型:归属优先,再谈状态 + +### 4.1 归属在任务创建时盖章 + +`web/backend/services/binding_ownership.py` + `create_douyu_planned_tasks`: + +- 履约订单自己创建的 `get_bind_qr` / `confirm_bind` 带 `platform_task_id`(原本就是); +- 运营从精英宝典工作台操作**已租给履约订单**的账号时,创建入口查 + `active_fulfillment_lease(account_id)`,把订单 id 写进任务的 `platform_task_id`; +- 订单处于 `bound / manual_required / completed / cancelled` 或账号没有 + `platform_fulfillment` 租约时不归属,工作台任务只是工作台任务。 + +从这一刻起,不需要再猜「最新任务是不是本次扫码」。 + +### 4.2 只有订单自己的证据能改订单 + +`binding.py::_apply_binding_task` 的硬守卫: + +1. `handbook_scope == "elite"`(电竞/和平小店任务一律不投影); +2. 任务账号 == 订单账号; +3. 订单租约 active; +4. 任务带 `platform_task_id == order.id`(`owned`),或它是订单当前挂着的 + 兼容旧任务; +5. 任务创建时间不早于 `lease.leased_at`(兼容路径); +6. 订单阶段必须是 `not_started/allocated/preparing/qr_pending/waiting_bind/role_ready` + 或当前确认任务; +7. 订单 `binding_status == "bound"` 后冻结,任何绑定证据都不能把它打回去。 + +### 4.3 结算必须证明「绑的是本单的目标角色」 + +- 订单的目标角色来自它自己的绑码任务(`pending_binding_role_from_result`), + 不是账号当前角色; +- 工作台/无归属确认任务只有在 `confirmed_role == target_role` 时才结算; +- 目标角色为空(本单还没出现过待确认角色)时,无归属确认一律不结算; +- 带 `platform_task_id` 的确认任务如果角色不一致,同样拒绝; +- 拒绝不是静默失败:写 `binding_sync_rejected` 事件(含双方角色、原因), + 订单保持原状态,运营在时间线能看到「为什么没结算」。 + +### 4.4 查询任务永远不结算 + +`query_game_name` / `query_change_bind_time` 只描述账号当前角色,不能证明本单 +发生过确认。它们: + +- 不参与 `pending` 链接; +- 不参与 `bound` 判定; +- 只用于页面展示和排障。 + +同一角色重新绑定时尤其重要:账号上本来就有同名绑定,查询结果无法区分「旧的同名 +绑定」和「本次刚确认」,必须有成功确认任务。 + +### 4.5 失败只认订单当前任务 + +- 订单自己当前的绑码/确认任务失败 -> 订单 `failed / manual_required`; +- 工作台额外任务的失败(不是订单当前指针)只写时间线,不打死订单; +- 已 `bound` 订单不会被迟到的失败任务改回 `manual_required`。 + +### 4.6 阶段单调 + 租约窗口 + +- `confirming` 阶段不会被后到的 QR 结果打回 `role_ready`; +- 任务创建时间早于当前租约的(上一个订单遗留)不能结算当前订单; +- 启动对账(`reconcile_binding_observations`)只处理订单自己的证据, + 包括「确认任务已成功落库但回调丢失」的 `confirming` 订单,不再扫账号观测。 + +## 五、现在的状态流 + +```text +not_started / allocated + -> preparing 订单创建 get_bind_qr(platform_task_id=order.id) + -> qr_pending 二维码就绪(running 也可展示,但不推进角色) + -> role_ready 动作 alias 上出现可确认 pending,记录目标角色 + -> confirming 订单创建 confirm_bind(platform_task_id=order.id) + -> bound 确认任务/当前绑码任务回查 bindAct=1 + -> failed / manual_required 当前任务失败(冷却等) +``` + +兼容路径(2026-11-24 之前创建、没有归属的任务): + +- 无归属 `get_bind_qr` + pending:仅在订单阶段 active、租约 active、任务创建于 + 本租约期间时为订单补挂目标; +- 无归属 `confirm_bind` + confirmed:仅当角色 == 本单目标、任务创建于本租约期间 + 时结算; +- 无归属查询任务:忽略。 + +## 六、回归用例(不变量,而不是某个 bug 的复现) + +`tests/test_platform_fulfillment.py::TestBindingAndCompletion`: + +- `test_observation_never_settles_fulfillment_task` +- `test_startup_recovers_lost_confirm_callback` +- `test_unlinked_confirm_requires_matching_target_role` +- `test_unlinked_confirm_created_before_lease_is_rejected` +- `test_bound_task_ignores_late_unlinked_bind_failure` +- `test_esports_binding_task_does_not_touch_elite_fulfillment` +- `test_workbench_binding_tasks_are_owned_by_active_fulfillment_order` +- `test_owned_confirm_with_mismatched_role_is_rejected` +- `test_refresh_binding_attaches_latest_pending_account_workbench_role` +- `test_standalone_account_confirmation_syncs_active_fulfillment_task` + +以后修绑定问题,先问三个问题: + +1. 这条任务是否带 `platform_task_id == order.id`? +2. 如果不带,它是否创建于本单租约期间,并且角色 == 本单目标? +3. 这个改动会不会让 `bound` / `completed` / `cancelled` 被回退? + +答不上来就不要加新的推断分支。 + +## 七、排障线索 + +- 时间线 `binding_sync_rejected`:账号上有绑定任务被拒绝结算,`detail.reason`: + - `target_mismatch`:确认角色 != 本单目标; + - `source_outside_lease`:任务创建于本租约之前; + - `missing_target`:本单还没有待确认角色; + - `foreign_current_task`:订单当前指针指向了别的订单的任务(数据异常)。 +- `binding_confirmed`:本单由自己的证据结算,`detail` 里同时有 + `targetRoleName` 和 `confirmedRoleName`,两者应一致。 +- `binding_pending_task_linked`:目标角色被更新,`detail.source` 为 + `owned` / `legacy-current` / `account_workbench`。 +- 账号工作台的绑定任务在任务列表里会带 `platform_task_id`(前端不展示), + 用于确认它被归属到了哪张订单。 + +## 八、存量数据:先审计,不自动修 + +新规则只保证以后不再写错;历史上已经被误判为 `bound` 的订单不会被自动改回。 +上线后先用**只读** SQL 审计(不要直接 UPDATE): + +```sql +-- 1) 旧「账号确认」路径:绑定任务仍是待确认快照,但订单已 bound +SELECT t.id, t.source_order_item_id, t.bind_task_id, t.updated_at, + d.task_type, + JSON_UNQUOTE(JSON_EXTRACT(d.result, '$.role_name')) AS pending_role, + JSON_UNQUOTE(JSON_EXTRACT(d.result, '$.bind_ready_for_confirm')) AS ready, + JSON_UNQUOTE(JSON_EXTRACT(d.result, '$.bind_confirmed')) AS confirmed +FROM platform_fulfillment_tasks t +JOIN douyu_tasks d ON d.id = t.bind_task_id +WHERE t.binding_status = 'bound' + AND JSON_UNQUOTE(JSON_EXTRACT(d.result, '$.bind_ready_for_confirm')) = 'true' + AND COALESCE(JSON_UNQUOTE(JSON_EXTRACT(d.result, '$.bind_confirmed')), 'false') = 'false'; + +-- 2) 新事件里 target 与 confirmed 不一致(2026-11-24 之后才可能有) +SELECT t.id, t.source_order_item_id, e.created_at, + JSON_UNQUOTE(JSON_EXTRACT(e.detail_json, '$.targetRoleName')) AS target_role, + JSON_UNQUOTE(JSON_EXTRACT(e.detail_json, '$.confirmedRoleName')) AS confirmed_role +FROM platform_fulfillment_tasks t +JOIN platform_fulfillment_events e + ON e.task_id = t.id AND e.event_type = 'binding_confirmed' +WHERE t.binding_status = 'bound' + AND JSON_UNQUOTE(JSON_EXTRACT(e.detail_json, '$.targetRoleName')) <> '' + AND JSON_UNQUOTE(JSON_EXTRACT(e.detail_json, '$.confirmedRoleName')) + <> JSON_UNQUOTE(JSON_EXTRACT(e.detail_json, '$.targetRoleName')); +``` + +对第 1 类,历史修复迁移 `20261123_0126` 已经处理过一批;第 2 类在新代码里 +被 `binding_sync_rejected` 拦住,正常不会产生,出现即说明有绕过写入的入口,需要排查。 + +存量卡在 `role_ready`、但账号实际已在工作台确认的订单:先看时间线是否有 +`binding_sync_rejected`(reason=`target_mismatch`/`source_outside_lease`); +若确认角色确实不是本单目标,应让运营确认后重置绑定,而不是直接改库。 + +## 九、2026-11-24 生产只读审计结果 + +审计时生产版本 `58d7826`、Alembic `20261123_0127`;全部为只读查询,未改任何数据。 + +### 9.1 已确认的误结算(2 单) + +| 订单 | 目标角色(待确认) | 实际绑定 | 根因 | +| --- | --- | --- | --- | +| 6334 | 快手翔天乐 | 冷净期 | 58d7826 的 `query_game_name` 观测路径,pending 被旧角色 superseded 后 confirmed | +| 7545 | 布丁贩卖机 | 续梦乖 | 同上 | + +两单时间线都有 `binding_pending_observation_superseded` + `binding_observation_confirmed`, +且 observed role 与 pending 不同。新代码已删除观测结算路径、增加目标角色匹配, +不会再产生;存量需要人工处理。 + +### 9.2 9 单 bound 但绑码任务仍是 pending —— 不是误判 + +9 单由 `binding_synced_from_account`(`backfilled: true`,2026-11-23 11:17:29)结算, +事件 roleName 与 pending 角色一致(忧郁悲觉 / 泪痣鸢 / 粘降 / 啊湆 / 小财迷敏敏 / +烤鸭造福全人类 / 星困儿 等),属于工作台确认后绑码任务快照未更新。新代码对 bound +冻结,不会回退;无需处理。 + +### 9.3 失败分布(近 7 天) + +- 事件:`binding_failed` 4444 条;其中 generic 3675、`customer_role_cooldown` 603、 + `account_role_cooldown` 166。 +- generic 消息 Top:二维码过期 2437、任务中断(无执行器)850、CK 失效 260、 + 服务重启 54。 +- 任务:failed 近 7 天 2891;`lease_expired` 2354(11-22 单日 2064,任务已无 + account/lease,属清理/过期口径)、`customer_role_cooldown` 414、 + `account_role_cooldown` 67、`binding_failed` 56。 +- 确认失败 alias:323/414 是 `query_alias=cjm, bind_alias=cjm`,但 + `confirm_act_alias=QYOOB`,`actBind` 返回“该账号未到可换绑时间”;60 条是 + QYOOB 自身真实冷却;22 条系统错误。 + +结论:当前最大问题不是状态投影,而是: + +1. **cjm-only pending 仍对 QYOOB 调 `actBind`**,必然失败,却被报成 + `customer_role_cooldown`; +2. **二维码过期(2437)/ 执行器不接管(850)/ CK 失效(260)** 是量的主体; +3. 失败分类把 alias 问题报成“客户角色冷却”,客服无法据此处理。 + +这三项是下一步修复对象;不要再用“账号级观测”兜底。 diff --git a/docs/直播账号履约工作台.md b/docs/直播账号履约工作台.md index d071620..59ad704 100644 --- a/docs/直播账号履约工作台.md +++ b/docs/直播账号履约工作台.md @@ -45,6 +45,20 @@ 账号概览只能消费 `binding_snapshot()` 及其派生函数,不得各自判断 `bindRole` / `bindAct`。 +履约订单还必须消费**任务归属**,不能把账号上的任意最新绑定任务当成自己的: + +- 订单自己创建的 `get_bind_qr` / `confirm_bind` 带 `platform_task_id`; +- 运营从精英宝典工作台为已租给履约订单的账号创建绑码/确认任务时, + `create_douyu_planned_tasks` 会把订单 id 写进 `platform_task_id`; +- 只有带 `platform_task_id == order.id`(或订单当前挂着的兼容旧任务)的绑定证据 + 才能改订单;查询任务永远不能结算订单; +- 无归属确认任务必须「确认角色 == 本单目标角色 + 任务创建于本单租约期间」, + 否则只写 `binding_sync_rejected`,订单保持原状态; +- 订单 `bound` 之后绑定状态冻结,迟到的任务不能把它打回待确认/人工处理。 + +完整根因、五次修复复盘、状态流和不变量见 +[履约绑定状态机与踩坑复盘](斗鱼/履约绑定状态机与踩坑复盘.md)。 + 2026-11-17 最新抓包确认: - 扫码选中角色后是 `bindRole=1, bindAct=0`,业务状态为待确认; diff --git a/tests/test_douyu_binding_state.py b/tests/test_douyu_binding_state.py index 30de7f6..863909c 100644 --- a/tests/test_douyu_binding_state.py +++ b/tests/test_douyu_binding_state.py @@ -697,7 +697,9 @@ def test_expected_role_never_falls_back_to_old_activity_role(): def test_act_bind_is_the_single_final_bound_signal(): - can_change_time = 1_795_449_600 + # 用例断言的是「未来时间 -> 冷却中」。写死时间戳会随日期过期, + # 这里用相对当前时间,避免在 2026-11-23 之后必然失败。 + can_change_time = int(datetime.now(UTC).timestamp()) + 600_000 parsed = _parse( _payload( bind_account=1, diff --git a/tests/test_migrations.py b/tests/test_migrations.py index f609af0..35e241c 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -82,6 +82,8 @@ _LATER_ORM_COLUMNS = { }, "douyu_external_orders": { "succeeded_at": "DATETIME NULL", + # 20261123_0125 新增;旧 revision 上仍用当前 ORM 写夹具,必须补齐。 + "shop_original_name": "VARCHAR(128) NOT NULL DEFAULT ''", }, "account_commodity_states": { "account_eligibility": "VARCHAR(16) NOT NULL DEFAULT 'unknown'", diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 246efe5..76bc7c4 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -2076,21 +2076,19 @@ class TestBindingAndCompletion(_Base): assert event.detail_json["previousBindTaskId"] == old_bind_task.id assert event.detail_json["bindTaskId"] == latest_bind_task.id - def test_newer_observation_confirms_different_pending_role(self): + def test_observation_never_settles_fulfillment_task(self): + """查询任务只能展示账号当前角色,不能证明本单已确认。""" task = self._allocated() account = self.session.get(Account, task.account_id) account.game_name = "续梦乖" - account.game_channel = "手Q · 安卓(android)" account.role_bind_status = "bound" - account.role_change_available_at = NOW + timedelta(days=6) pending_task = DouyuTask( - batch_id="pending-old-role", + batch_id="pending-for-observation", account_id=task.account_id, account_assigned_to=self.admin_id, task_type="get_bind_qr", handbook_scope="elite", status="success", - platform_task_id=task.id, result={ "role_name": "布丁贩卖机", "area_name": "微信", @@ -2102,8 +2100,6 @@ class TestBindingAndCompletion(_Base): "is_bound_act": True, "need_bind_act": True, }, - "act_alias": "20260120QYOOB", - "need_bind_act": True, "bind_ready_for_confirm": True, "bind_confirmed": False, "bind_phase": "role_ready", @@ -2115,57 +2111,385 @@ class TestBindingAndCompletion(_Base): task.bind_task_id = pending_task.id task.binding_status = "role_ready" task.execution_status = "role_ready" - observation = DouyuTask( - batch_id="observe-new-role", + observed_roles = ["续梦乖", "布丁贩卖机"] + observations = [] + for index, role_name in enumerate(observed_roles): + observation = DouyuTask( + batch_id=f"observe-{index}", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="query_game_name", + handbook_scope="elite", + status="success", + platform_task_id=task.id, + result={ + "role_name": role_name, + "area_name": "手Q", + "plat_name": "安卓(android)", + "is_bound_act": True, + "bind_confirmed": True, + "bind_phase": "confirmed", + }, + created_by=self.admin_id, + ) + self.session.add(observation) + observations.append(observation) + self.session.commit() + + for observation in observations: + assert ( + service.sync_task_from_binding_runner( + self.session, + douyu_task_id=observation.id, + ) + == 0 + ) + assert service.reconcile_binding_observations(self.session) == 0 + + self.session.refresh(task) + assert task.binding_status == "role_ready" + assert task.execution_status == "role_ready" + assert task.bind_task_id == pending_task.id + assert ( + self.session.query(PlatformFulfillmentEvent) + .filter_by(task_id=task.id, event_type="binding_confirmed") + .count() + == 0 + ) + + def test_startup_recovers_lost_confirm_callback(self): + """确认任务已成功落库但回调丢失时,启动对账能收敛为 bound。""" + task = self._allocated() + task.binding_status = "confirming" + task.execution_status = "binding_confirming" + confirm_task = DouyuTask( + batch_id="lost-confirm-callback", account_id=task.account_id, account_assigned_to=self.admin_id, - task_type="query_game_name", + task_type="confirm_bind", handbook_scope="elite", status="success", platform_task_id=task.id, result={ - "role_name": "续梦乖", + "role_name": "目标角色", "area_name": "手Q", - "plat_name": "安卓(android)", - "is_bound_act": True, + "plat_name": "苹果(iOS)", "bind_confirmed": True, "bind_phase": "confirmed", }, created_by=self.admin_id, ) - self.session.add(observation) + self.session.add(confirm_task) + self.session.flush() + task.bind_task_id = confirm_task.id self.session.commit() - synced = service.reconcile_binding_observations(self.session) + reconciled = service.reconcile_binding_observations(self.session) self.session.refresh(task) - detail = service.get_task_detail(self.session, task.id) - event = ( - self.session.query(PlatformFulfillmentEvent) - .filter_by( - task_id=task.id, - event_type="binding_observation_confirmed", - ) - .one() - ) - assert synced == 1 - assert task.bind_task_id == observation.id + assert reconciled == 1 assert task.binding_status == "bound" assert task.execution_status == "bound" - assert detail["task"]["bindTask"]["roleName"] == "续梦乖" - assert detail["task"]["bindTask"]["bindReadyForConfirm"] is False - assert detail["task"]["bindTask"]["bindConfirmed"] is True - assert detail["task"]["account"]["roleChangeAvailableAt"] is not None - assert event.detail_json["pendingRoleName"] == "布丁贩卖机" - assert event.detail_json["observedRoleName"] == "续梦乖" + assert task.bind_task_id == confirm_task.id + assert ( + self.session.query(PlatformFulfillmentEvent) + .filter_by(task_id=task.id, event_type="binding_confirmed") + .count() + == 1 + ) - def test_newer_observation_confirms_matching_pending_role(self): + def test_unlinked_confirm_requires_matching_target_role(self): + """精英宝典工作台的无归属确认任务必须和本单目标角色一致。""" task = self._allocated() - account = self.session.get(Account, task.account_id) - account.game_name = "续梦乖" - account.role_bind_status = "bound" - pending_task = DouyuTask( - batch_id="pending-matching-role", + qr_task = DouyuTask( + batch_id="unlinked-target-qr", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="success", + result={ + "role_name": "本单目标角色", + "area_name": "手Q", + "plat_name": "苹果(iOS)", + "current_role_name": "历史角色", + "baseline_role_name": "历史角色", + "before_bind_info": { + "act_alias": "20260120QYOOB", + "role_name": "历史角色", + "is_bound_act": True, + "need_bind_act": True, + }, + "bind_ready_for_confirm": True, + "bind_confirmed": False, + "bind_phase": "role_ready", + }, + created_by=self.admin_id, + ) + self.session.add(qr_task) + self.session.flush() + task.bind_task_id = qr_task.id + task.binding_status = "role_ready" + task.execution_status = "role_ready" + mismatched = DouyuTask( + batch_id="unlinked-mismatched-confirm", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="confirm_bind", + handbook_scope="elite", + status="success", + result={ + "role_name": "别的角色", + "area_name": "手Q", + "plat_name": "苹果(iOS)", + "bind_confirmed": True, + "bind_phase": "confirmed", + }, + created_by=self.admin_id, + ) + self.session.add(mismatched) + self.session.commit() + + synced = service.sync_task_from_binding_runner( + self.session, + douyu_task_id=mismatched.id, + ) + + self.session.refresh(task) + rejection = ( + self.session.query(PlatformFulfillmentEvent) + .filter_by(task_id=task.id, event_type="binding_sync_rejected") + .one() + ) + assert synced == 0 + assert task.binding_status == "role_ready" + assert task.bind_task_id == qr_task.id + assert rejection.detail_json["reason"] == "target_mismatch" + assert rejection.detail_json["confirmedRoleName"] == "别的角色" + assert rejection.detail_json["targetRoleName"] == "本单目标角色" + + def test_unlinked_confirm_created_before_lease_is_rejected(self): + """上一个租约遗留的确认任务不能结算当前订单。""" + task = self._allocated() + qr_task = DouyuTask( + batch_id="outside-lease-qr", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="success", + result={ + "role_name": "当前目标角色", + "area_name": "手Q", + "plat_name": "苹果(iOS)", + "current_role_name": "历史角色", + "baseline_role_name": "历史角色", + "before_bind_info": { + "act_alias": "20260120QYOOB", + "role_name": "历史角色", + "is_bound_act": True, + "need_bind_act": True, + }, + "bind_ready_for_confirm": True, + "bind_confirmed": False, + "bind_phase": "role_ready", + }, + created_by=self.admin_id, + ) + old_confirm = DouyuTask( + batch_id="outside-lease-confirm", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="confirm_bind", + handbook_scope="elite", + status="success", + result={ + "role_name": "当前目标角色", + "area_name": "手Q", + "plat_name": "苹果(iOS)", + "bind_confirmed": True, + "bind_phase": "confirmed", + }, + created_by=self.admin_id, + created_at=NOW - timedelta(days=1), + ) + self.session.add_all([qr_task, old_confirm]) + self.session.flush() + task.bind_task_id = qr_task.id + task.binding_status = "role_ready" + task.execution_status = "role_ready" + self.session.commit() + + synced = service.sync_task_from_binding_runner( + self.session, + douyu_task_id=old_confirm.id, + ) + + self.session.refresh(task) + rejection = ( + self.session.query(PlatformFulfillmentEvent) + .filter_by(task_id=task.id, event_type="binding_sync_rejected") + .one() + ) + assert synced == 0 + assert task.binding_status == "role_ready" + assert rejection.detail_json["reason"] == "source_outside_lease" + + def test_bound_task_ignores_late_unlinked_bind_failure(self): + """已绑定订单不能被账号工作台迟到的失败任务打成人工处理。""" + task = self._allocated() + task.binding_status = "bound" + task.execution_status = "exchanging" + task.exchange_status = "checking" + self.session.commit() + late_failed = DouyuTask( + batch_id="late-workbench-failure", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="failed", + message="换绑冷却", + result={"bind_phase": "change_waiting"}, + created_by=self.admin_id, + ) + self.session.add(late_failed) + self.session.commit() + + synced = service.sync_task_from_binding_runner( + self.session, + douyu_task_id=late_failed.id, + ) + + self.session.refresh(task) + assert synced == 0 + assert task.binding_status == "bound" + assert task.execution_status == "exchanging" + assert task.issue_code == "" + + def test_esports_binding_task_does_not_touch_elite_fulfillment(self): + """电竞/和平小店任务与精英履约互不投影。""" + task = self._allocated() + esports_task = DouyuTask( + batch_id="esports-cross-scope", + account_id=task.account_id, + account_assigned_to=self.admin_id, + task_type="confirm_esports_bind", + handbook_scope="esports", + status="success", + platform_task_id=None, + result={ + "role_name": "电竞角色", + "area_name": "手Q", + "plat_name": "苹果(iOS)", + "esports_bound": True, + "bind_confirmed": True, + "bind_phase": "confirmed", + }, + created_by=self.admin_id, + ) + self.session.add(esports_task) + self.session.commit() + + synced = service.sync_task_from_binding_runner( + self.session, + douyu_task_id=esports_task.id, + ) + + self.session.refresh(task) + assert synced == 0 + assert task.binding_status == "not_started" + assert task.bind_task_id is None + + def test_workbench_binding_tasks_are_owned_by_active_fulfillment_order(self): + """已租给履约订单的账号,工作台绑定任务在创建时就写入订单归属。""" + from web.backend.services.douyu_service import create_douyu_planned_tasks + + task = self._allocated() + qr_batch, qr_count = create_douyu_planned_tasks( + self.session, + [task.account_id], + "get_bind_qr", + "elite", + self.admin_id, + enqueue_execution=False, + ) + qr_task = ( + self.session.query(DouyuTask) + .filter(DouyuTask.batch_id == qr_batch) + .one() + ) + assert qr_count == 1 + assert qr_task.platform_task_id == task.id + + qr_task.status = "success" + qr_task.result = { + "role_name": "工作台扫码角色", + "area_name": "手Q", + "plat_name": "苹果(iOS)", + "current_role_name": "历史角色", + "baseline_role_name": "历史角色", + "before_bind_info": { + "act_alias": "20260120QYOOB", + "role_name": "历史角色", + "is_bound_act": True, + "need_bind_act": True, + }, + "bind_ready_for_confirm": True, + "bind_confirmed": False, + "bind_phase": "role_ready", + } + self.session.commit() + assert ( + service.sync_task_from_binding_runner( + self.session, + douyu_task_id=qr_task.id, + ) + == 1 + ) + self.session.refresh(task) + assert task.binding_status == "role_ready" + assert task.bind_task_id == qr_task.id + + confirm_batch, _ = create_douyu_planned_tasks( + self.session, + [task.account_id], + "confirm_bind", + "elite", + self.admin_id, + enqueue_execution=False, + ) + confirm_task = ( + self.session.query(DouyuTask) + .filter(DouyuTask.batch_id == confirm_batch) + .one() + ) + assert confirm_task.platform_task_id == task.id + confirm_task.status = "success" + confirm_task.result = { + "role_name": "工作台扫码角色", + "area_name": "手Q", + "plat_name": "苹果(iOS)", + "bind_confirmed": True, + "bind_phase": "confirmed", + } + self.session.commit() + assert ( + service.sync_task_from_binding_runner( + self.session, + douyu_task_id=confirm_task.id, + ) + == 1 + ) + self.session.refresh(task) + assert task.binding_status == "bound" + assert task.bind_task_id == confirm_task.id + + def test_owned_confirm_with_mismatched_role_is_rejected(self): + """带订单归属的确认任务如果绑了别的角色,也不能结算订单。""" + task = self._allocated() + qr_task = DouyuTask( + batch_id="owned-target-qr", account_id=task.account_id, account_assigned_to=self.admin_id, task_type="get_bind_qr", @@ -2173,114 +2497,63 @@ class TestBindingAndCompletion(_Base): status="success", platform_task_id=task.id, result={ - "role_name": "续梦乖", - "baseline_role_name": "旧角色", + "role_name": "本单目标角色", + "area_name": "手Q", + "plat_name": "苹果(iOS)", + "current_role_name": "历史角色", + "baseline_role_name": "历史角色", "before_bind_info": { "act_alias": "20260120QYOOB", - "role_name": "旧角色", + "role_name": "历史角色", "is_bound_act": True, "need_bind_act": True, }, - "act_alias": "20260120QYOOB", - "need_bind_act": True, "bind_ready_for_confirm": True, "bind_confirmed": False, "bind_phase": "role_ready", }, created_by=self.admin_id, ) - self.session.add(pending_task) + self.session.add(qr_task) self.session.flush() - task.bind_task_id = pending_task.id + task.bind_task_id = qr_task.id task.binding_status = "role_ready" task.execution_status = "role_ready" - observation = DouyuTask( - batch_id="observe-matching-role", + confirm_task = DouyuTask( + batch_id="owned-mismatched-confirm", account_id=task.account_id, account_assigned_to=self.admin_id, - task_type="query_game_name", + task_type="confirm_bind", handbook_scope="elite", status="success", platform_task_id=task.id, result={ - "role_name": "续梦乖", + "role_name": "别的角色", "area_name": "手Q", - "plat_name": "安卓(android)", - "is_bound_act": True, + "plat_name": "苹果(iOS)", "bind_confirmed": True, "bind_phase": "confirmed", }, created_by=self.admin_id, ) - self.session.add(observation) + self.session.add(confirm_task) self.session.commit() synced = service.sync_task_from_binding_runner( self.session, - douyu_task_id=observation.id, + douyu_task_id=confirm_task.id, ) self.session.refresh(task) - detail = service.get_task_detail(self.session, task.id) - assert synced == 1 - assert task.bind_task_id == observation.id - assert task.binding_status == "bound" - assert task.execution_status == "bound" - assert detail["task"]["bindTask"]["roleName"] == "续梦乖" - assert detail["task"]["bindTask"]["bindReadyForConfirm"] is False - assert detail["task"]["bindTask"]["bindConfirmed"] is True - - def test_startup_promotes_waiting_task_with_confirmed_observation(self): - task = self._allocated() - account = self.session.get(Account, task.account_id) - account.game_name = "续梦乖" - account.game_channel = "手Q · 安卓(android)" - account.role_bind_status = "bound" - account.role_change_available_at = NOW + timedelta(days=6) - observation = DouyuTask( - batch_id="observe-already-bound", - account_id=task.account_id, - account_assigned_to=self.admin_id, - task_type="query_game_name", - handbook_scope="elite", - status="success", - platform_task_id=task.id, - result={ - "role_name": "续梦乖", - "area_name": "手Q", - "plat_name": "安卓(android)", - "is_bound_act": True, - "bind_confirmed": True, - "bind_phase": "confirmed", - }, - created_by=self.admin_id, - ) - self.session.add(observation) - self.session.flush() - task.bind_task_id = observation.id - task.binding_status = "waiting_bind" - task.execution_status = "waiting_bind" - self.session.commit() - - reconciled = service.reconcile_binding_observations(self.session) - - self.session.refresh(task) - detail = service.get_task_detail(self.session, task.id) - event = ( + rejection = ( self.session.query(PlatformFulfillmentEvent) - .filter_by( - task_id=task.id, - event_type="binding_observation_confirmed", - ) + .filter_by(task_id=task.id, event_type="binding_sync_rejected") .one() ) - assert reconciled == 1 - assert task.binding_status == "bound" - assert task.execution_status == "bound" - assert detail["task"]["bindTask"]["roleName"] == "续梦乖" - assert detail["task"]["bindTask"]["bindConfirmed"] is True - assert detail["task"]["account"]["roleChangeAvailableAt"] is not None - assert event.detail_json["observedRoleName"] == "续梦乖" + assert synced == 0 + assert task.binding_status == "role_ready" + assert task.bind_task_id == qr_task.id + assert rejection.detail_json["reason"] == "target_mismatch" def test_refresh_binding_attaches_latest_pending_account_workbench_role(self): task = self._allocated() diff --git a/web/backend/background_runtime.py b/web/backend/background_runtime.py index 8f132b2..9949c1f 100644 --- a/web/backend/background_runtime.py +++ b/web/backend/background_runtime.py @@ -186,7 +186,7 @@ def recover_orphaned_work() -> None: reconciled_bindings = reconcile_binding_observations(db) if reconciled_bindings: logger.info( - "启动收敛账号角色观测到履约任务: {} 条", + "启动收敛履约绑定证据: {} 条", reconciled_bindings, ) seeded_targets = ensure_default_supply_targets(db) diff --git a/web/backend/services/binding_ownership.py b/web/backend/services/binding_ownership.py new file mode 100644 index 0000000..3953fe1 --- /dev/null +++ b/web/backend/services/binding_ownership.py @@ -0,0 +1,163 @@ +"""绑定任务的归属判定:一条绑定任务到底属于哪个履约订单。 + +## 为什么需要这个模块 + +精英宝典工作台只关心「这条任务自己的结果」,所以任务和账号之间不需要归属关系。 +直播账号履约不一样:一个订单会占用一个账号一段时间,期间账号上可能出现多条 +绑定任务(订单自己创建的、运营从精英宝典工作台创建的、上一个订单遗留下来的)。 +以前履约层靠「账号 + 最新 id + 租约 active」去猜一条任务属于哪张订单,猜错就会 +把别人的绑定结果投影到当前订单上。 + +这里把归属变成显式事实: + +1. 履约订单自己创建的绑定任务在创建时就带 ``platform_task_id``; +2. 运营从精英宝典工作台为**已租给履约订单**的账号创建绑码/确认任务时, + 创建入口调用 :func:`active_fulfillment_binding_task_id` 把订单 id 盖到任务上; +3. 只有带 ``platform_task_id`` 的任务才是订单的权威证据; +4. 没有归属的历史任务只能走 ``binding.py`` 里受严格限制的兼容路径。 + +归属一确定,剩下的事情就简单了:阶段、租约、角色目标都是可验证的,不需要 +再猜「最新任务是不是本次扫码」。 +""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +from sqlalchemy import or_ +from sqlalchemy.orm import Session + +from ..models import AccountLease, DouyuTask, PlatformFulfillmentTask + +#: 允许把工作台任务挂到订单上的绑定阶段。已 bound / manual_required 的订单 +#: 不再接受自动归属,避免工作台的一次手工操作改写已完成订单。 +BINDING_LINKABLE_STATUSES = frozenset( + { + "not_started", + "allocated", + "preparing", + "qr_pending", + "waiting_bind", + "role_ready", + } +) + +#: 绑定任务类型。查询类任务(query_game_name / query_change_bind_time)故意 +#: 不在此列:查询只能证明账号当前状态,不能证明某个订单的绑定已经确认。 +BINDING_TASK_TYPES = frozenset({"get_bind_qr", "confirm_bind"}) + +#: 任务创建时间与租约起点的容差。两者由不同事务写入,允许几秒偏差; +#: 不允许跨租约归属(上一个订单的任务不能算到下一张订单上)。 +LEASE_CLOCK_TOLERANCE = timedelta(seconds=5) + + +def active_fulfillment_lease( + db: Session, + account_id: int, +) -> AccountLease | None: + """账号当前生效的履约租约;没有则返回 ``None``。""" + return ( + db.query(AccountLease) + .filter( + AccountLease.account_id == int(account_id), + AccountLease.status == "active", + AccountLease.purpose == "platform_fulfillment", + or_( + AccountLease.expires_at.is_(None), + AccountLease.expires_at > datetime.now(UTC), + ), + ) + .order_by(AccountLease.leased_at.desc(), AccountLease.id.desc()) + .first() + ) + + +def active_fulfillment_binding_task_id( + db: Session, + account_id: int, +) -> int | None: + """账号当前租约对应的、仍可接收绑定证据的履约任务 id。 + + 只用于任务创建入口主动打归属;``None`` 表示这是一次与履约无关的工作台操作。 + """ + lease = active_fulfillment_lease(db, account_id) + if lease is None: + return None + task = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.lease_id == int(lease.id), + PlatformFulfillmentTask.account_id == int(account_id), + PlatformFulfillmentTask.scope == "elite", + PlatformFulfillmentTask.execution_status.notin_( + ("completed", "cancelled", "manual_required") + ), + PlatformFulfillmentTask.binding_status.in_(BINDING_LINKABLE_STATUSES), + ) + .order_by( + PlatformFulfillmentTask.updated_at.desc(), + PlatformFulfillmentTask.id.desc(), + ) + .first() + ) + return int(task.id) if task is not None else None + + +def fulfillment_lease_for_task( + db: Session, + task: PlatformFulfillmentTask, +) -> AccountLease | None: + """订单自己的租约(不按账号重新查,避免订单换号后拿到别的账号租约)。""" + if not task.lease_id: + return None + return db.query(AccountLease).filter(AccountLease.id == int(task.lease_id)).first() + + +def lease_is_active(lease: AccountLease | None) -> bool: + if lease is None or lease.status != "active": + return False + expires_at = lease.expires_at + return not ( + isinstance(expires_at, datetime) and expires_at <= datetime.now(UTC) + ) + + +def source_created_within_lease( + lease: AccountLease | None, + source: DouyuTask | None, +) -> bool: + """任务是否创建于本次租约期间。 + + 这是防止「上一个订单的迟到任务结算当前订单」的硬约束。 + """ + if lease is None or source is None: + return False + created_at = source.created_at + leased_at = lease.leased_at + if not isinstance(created_at, datetime) or not isinstance(leased_at, datetime): + return False + return created_at >= leased_at - LEASE_CLOCK_TOLERANCE + + +def normalize_role_name(value: object) -> str: + return str(value or "").strip().casefold() + + +def role_names_match(left: object, right: object) -> bool: + left_key = normalize_role_name(left) + right_key = normalize_role_name(right) + return bool(left_key) and left_key == right_key + + +__all__ = [ + "BINDING_LINKABLE_STATUSES", + "BINDING_TASK_TYPES", + "LEASE_CLOCK_TOLERANCE", + "active_fulfillment_binding_task_id", + "active_fulfillment_lease", + "fulfillment_lease_for_task", + "lease_is_active", + "normalize_role_name", + "role_names_match", + "source_created_within_lease", +] diff --git a/web/backend/services/douyu_service.py b/web/backend/services/douyu_service.py index c92a1e1..f22c24b 100644 --- a/web/backend/services/douyu_service.py +++ b/web/backend/services/douyu_service.py @@ -15,6 +15,7 @@ from core.douyu.cookie_utils import cookie_value from ..models import Account, DouyuConfig, DouyuTask from . import account_query_filters as account_filters from .account_events_service import CATEGORY_ACTIVITY, EVENT_TASK_STARTED, emit_bulk +from .binding_ownership import BINDING_TASK_TYPES, active_fulfillment_binding_task_id from .douyu_binding import resolve_douyu_binding LOGIN_ATTEMPT_IN_FLIGHT_STATUSES = account_filters.LOGIN_ATTEMPT_IN_FLIGHT_STATUSES @@ -370,8 +371,21 @@ def create_douyu_planned_tasks( batch_id = uuid.uuid4().hex[:12] payload = payload or {} recharge_requested_at = datetime.now(UTC) + auto_link_binding = ( + platform_task_id is None + and handbook_scope == "elite" + and task_type in BINDING_TASK_TYPES + ) task_rows: list[tuple[DouyuTask, Account]] = [] for account in accounts: + # 已租给履约订单的账号:运营从精英宝典工作台发起的绑码/确认任务在 + # 创建时就写入订单归属,后续只认任务自己的 platform_task_id,不猜。 + linked_platform_task_id = platform_task_id + if auto_link_binding: + linked_platform_task_id = active_fulfillment_binding_task_id( + db, + account.id, + ) task = DouyuTask( batch_id=batch_id, account_id=account.id, @@ -382,7 +396,7 @@ def create_douyu_planned_tasks( message="任务已创建,等待执行", result={"payload": payload} if payload else None, created_by=created_by, - platform_task_id=platform_task_id, + platform_task_id=linked_platform_task_id, recharge_channel=recharge_channel, recharge_amount=recharge_amount, recharge_requested_at=( diff --git a/web/backend/services/platform_fulfillment/binding.py b/web/backend/services/platform_fulfillment/binding.py index 29b1cb5..065d6f4 100644 --- a/web/backend/services/platform_fulfillment/binding.py +++ b/web/backend/services/platform_fulfillment/binding.py @@ -14,17 +14,23 @@ from ...models import ( Account, AccountLease, DouyuTask, + PlatformFulfillmentEvent, PlatformFulfillmentTask, User, ) +from ..account_binding import pending_binding_role_from_result +from ..binding_ownership import ( + BINDING_TASK_TYPES, + fulfillment_lease_for_task, + lease_is_active, + role_names_match, + source_created_within_lease, +) from ..business_events import record_douyu_task_started from ..douyu_binding import ( BINDING_OBSERVATION_TASK_TYPES, - BINDING_RECONCILE_CONFIRMED, BINDING_VIEW_CONFIRMED, BINDING_VIEW_PENDING, - DouyuBindingReconciliation, - reconcile_douyu_binding, resolve_douyu_binding, resolve_fulfillment_binding, ) @@ -64,17 +70,24 @@ BINDING_SYNC_TASK_TYPES = frozenset( "confirm_xpd_bind", } ) -ACCOUNT_CONFIRMATION_TASK_TYPES = frozenset( +PENDING_BINDING_TASK_TYPES = frozenset({"get_bind_qr"}) + +#: 订单仍可接收绑定证据的阶段。bound / completed / cancelled 一律冻结。 +ACTIVE_BINDING_STATUSES = frozenset( { - "confirm_bind", - "confirm_esports_bind", - "confirm_xpd_bind", + "not_started", + "allocated", + "preparing", + "qr_pending", + "waiting_bind", + "role_ready", } ) -PENDING_BINDING_TASK_TYPES = frozenset({"get_bind_qr"}) -ACTIVE_PENDING_TASK_STATUSES = frozenset( - {"allocated", "waiting_bind", "role_ready"} -) +#: 可以接受确认任务结算的阶段。 +CONFIRMABLE_BINDING_STATUSES = frozenset({"role_ready", "confirming"}) +#: 订单的权威绑定任务类型。查询任务只能展示,不能结算。 +BINDING_EVIDENCE_TASK_TYPES = frozenset({"get_bind_qr", "confirm_bind"}) +assert BINDING_EVIDENCE_TASK_TYPES <= BINDING_TASK_TYPES def start_binding_sync( @@ -92,6 +105,9 @@ def start_binding_sync( raise HTTPException(status_code=409, detail="账号租约已失效,请重新分配") if task.bind_task_id: existing = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() + if existing is not None and existing.platform_task_id not in (None, int(task.id)): + # 当前指针指向了别的订单的任务:当作没有绑定任务,重新出码。 + existing = None if existing: binding = resolve_fulfillment_binding( existing, @@ -207,64 +223,362 @@ async def start_binding( ) -def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: - task = _load_task(db, task_id) - if task.execution_status in {"completed", "cancelled"}: - return get_task_detail(db, task.id) - if task.binding_status == "role_ready": - observation_task = _binding_observation_task(db, task) - if observation_task is not None and _apply_binding_observation( - db, - task, - observation_task, - ): - db.commit() - task = _load_task(db, task.id) - latest_pending = _latest_pending_binding_task(db, task) - if latest_pending is not None and _attach_pending_binding_task( +def _frozen(task: PlatformFulfillmentTask) -> bool: + """已结束或已绑定的订单不再接受绑定证据回写。""" + return ( + task.execution_status in {"completed", "cancelled"} + or task.binding_status == "bound" + ) + + +def _lease_for_task( + db: Session, + task: PlatformFulfillmentTask, +) -> AccountLease | None: + return fulfillment_lease_for_task(db, task) + + +def _pending_role_of(task: DouyuTask | None) -> str: + if task is None or not isinstance(task.result, dict): + return "" + return pending_binding_role_from_result(task.result) + + +def _owned_binding_tasks( + db: Session, + task: PlatformFulfillmentTask, + *, + newer_than: int = 0, +) -> list[DouyuTask]: + if not task.account_id: + return [] + return ( + db.query(DouyuTask) + .filter( + DouyuTask.platform_task_id == int(task.id), + DouyuTask.account_id == int(task.account_id), + DouyuTask.handbook_scope == "elite", + DouyuTask.task_type.in_(BINDING_EVIDENCE_TASK_TYPES), + DouyuTask.id > int(newer_than), + ) + .order_by(DouyuTask.id.desc()) + .limit(8) + .all() + ) + + +def _order_target_role( + db: Session, + task: PlatformFulfillmentTask, + *, + before_task_id: int | None = None, +) -> str: + """订单本次要绑定的目标角色。 + + 优先取当前绑定任务;当前任务已经是确认任务时,从订单自己更新的绑码任务里回看。 + 只用带订单归属的任务,不看账号历史。 + """ + current = ( + db.get(DouyuTask, int(task.bind_task_id)) + if task.bind_task_id + else None + ) + role = _pending_role_of(current) + if role: + return role + for row in _owned_binding_tasks(db, task): + if before_task_id is not None and int(row.id) >= int(before_task_id): + continue + if row.status != "success": + continue + role = _pending_role_of(row) + if role: + return role + return "" + + +def _record_binding_rejection( + db: Session, + task: PlatformFulfillmentTask, + source: DouyuTask, + *, + reason: str, + confirmed_role: str = "", + target_role: str = "", +) -> None: + """记录一条不采纳的绑定证据;不改变订单状态,供时间线排查。""" + exists = ( + db.query(PlatformFulfillmentEvent.id) + .filter( + PlatformFulfillmentEvent.task_id == int(task.id), + PlatformFulfillmentEvent.event_type == "binding_sync_rejected", + PlatformFulfillmentEvent.detail_json["sourceTaskId"].as_integer() + == int(source.id), + ) + .first() + ) + if exists is not None: + return + _append_event( db, - task, - latest_pending, + task.id, + "binding_sync_rejected", + detail={ + "sourceTaskId": int(source.id), + "sourceTaskType": str(source.task_type or ""), + "reason": reason, + "confirmedRoleName": confirmed_role[:128], + "targetRoleName": target_role[:128], + "bindingStatus": task.binding_status, + "executionStatus": task.execution_status, + }, + ) + + +def _apply_binding_qr_display( + db: Session, + task: PlatformFulfillmentTask, + source: DouyuTask, + *, + owned: bool, + is_current: bool, + phase: str, + lease: AccountLease, +) -> bool: + """运行中/成功的绑码任务只推进二维码展示,不推进角色状态。""" + result = source.result if isinstance(source.result, dict) else {} + qr_url = str(result.get("url") or "") + if not qr_url or phase == "confirming": + return False + if not (is_current or (owned and phase in ACTIVE_BINDING_STATUSES)): + return False + if task.binding_status == "qr_pending" and int(task.bind_task_id or 0) == int( + source.id ): - db.commit() - task = _load_task(db, task.id) - if not task.bind_task_id: - return get_task_detail(db, task.id) - bind_task = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() - if bind_task is None: - return get_task_detail(db, task.id) - before = ( - task.binding_status, - task.execution_status, - task.exchange_status, - task.issue_code, - task.last_error, - ) - result = bind_task.result or {} + return False + task.bind_task_id = int(source.id) + task.binding_status = "qr_pending" + task.execution_status = "waiting_bind" + task.issue_code = "" + task.last_error = "" + task.updated_at = _now() + _apply_task_lease_policy(db, task, lease=lease) + _emit_order_site_binding_state(db, task.id) + return True + + +def _apply_binding_task( + db: Session, + task: PlatformFulfillmentTask, + source: DouyuTask, + *, + owned: bool, +) -> bool: + """把一条绑定任务合并进订单状态。 + + ``owned=True``:任务带 ``platform_task_id == task.id``,是订单自己的证据; + ``owned=False``:只允许订单当前已经挂着的任务(兼容旧数据)。 + """ + if _frozen(task): + return False + if not task.account_id or not source.account_id: + return False + if int(source.account_id) != int(task.account_id): + return False + if str(source.handbook_scope or "") != "elite": + return False + lease = _lease_for_task(db, task) + if not lease_is_active(lease): + return False + if not owned and not source_created_within_lease(lease, source): + return False + if ( + not owned + and source.platform_task_id is not None + and int(source.platform_task_id) != int(task.id) + ): + # 明确属于另一张订单的任务,不能写到本单。 + return False + + phase = str(task.binding_status or "") + is_current = bool(task.bind_task_id) and int(task.bind_task_id) == int(source.id) + if not owned and not is_current: + return False + if not is_current and int(source.id) < int(task.bind_task_id or 0): + return False + + account = db.get(Account, int(task.account_id)) binding = resolve_fulfillment_binding( - bind_task, - account=db.get(Account, int(task.account_id)) if task.account_id else None, - binding_status=task.binding_status, + source, + account=account, + binding_status=phase, ) - if bind_task.status in {"failed", "error", "stopped"}: + result = source.result if isinstance(source.result, dict) else {} + previous_bind_task_id = task.bind_task_id + + if source.status in {"failed", "error", "stopped"}: + # 只有订单当前挂着的任务失败才允许判失败;工作台额外任务失败不能打死订单。 + if not is_current: + return False + if phase not in ACTIVE_BINDING_STATUSES | {"confirming", "failed"}: + return False + issue_code = _binding_failure_issue(source, result) + if ( + task.binding_status == "failed" + and task.issue_code == issue_code + and int(task.bind_task_id or 0) == int(source.id) + ): + return False task.binding_status = "failed" task.execution_status = "manual_required" - task.issue_code = _binding_failure_issue(bind_task, result) + task.issue_code = issue_code task.last_error = _customer_task_message(task) - elif binding.status == BINDING_VIEW_CONFIRMED: + task.updated_at = _now() + _append_event( + db, + task.id, + "binding_failed", + detail={ + "issueCode": task.issue_code, + "bindTaskId": int(source.id), + "bindPhase": str(result.get("bind_phase") or ""), + "rawError": _binding_failure_raw_message( + task.issue_code, + result, + fallback=str(source.message or ""), + )[:1000], + }, + ) + _apply_task_lease_policy(db, task, lease=lease) + _emit_order_site_binding_state(db, task.id) + return True + + if source.status != "success": + # 运行中的绑码任务可以展示二维码,但不能据此推进角色/结算。 + return _apply_binding_qr_display( + db, + task, + source, + owned=owned, + is_current=is_current, + phase=phase, + lease=lease, + ) + + if binding.status == BINDING_VIEW_CONFIRMED: + confirmed_role = binding.confirmed_role_name + target_role = _order_target_role( + db, + task, + before_task_id=int(source.id) if source.task_type == "confirm_bind" else None, + ) + if is_current: + # 订单自己的当前任务(订单创建的或兼容路径挂上的)回查到 bindAct=1。 + # 查询类任务不会走到这里:resolve_fulfillment_binding 会把观测降级。 + accepted = source.task_type in BINDING_EVIDENCE_TASK_TYPES + elif not owned: + accepted = False + elif phase == "confirming": + # 订单已经在确认中,只认它自己当前那条确认任务。 + accepted = False + elif source.task_type == "confirm_bind": + accepted = ( + phase in CONFIRMABLE_BINDING_STATUSES + and bool(target_role) + and role_names_match(confirmed_role, target_role) + ) + else: + # 订单自己的绑码任务直接被官网确认:有目标时必须一致,无目标视为全新绑定。 + accepted = phase in ACTIVE_BINDING_STATUSES and ( + not target_role or role_names_match(confirmed_role, target_role) + ) + if not accepted: + _record_binding_rejection( + db, + task, + source, + reason=( + "target_mismatch" + if target_role and not role_names_match(confirmed_role, target_role) + else "untrusted_confirmation" + ), + confirmed_role=confirmed_role, + target_role=target_role, + ) + return False + task.bind_task_id = int(source.id) task.binding_status = "bound" task.execution_status = "bound" task.issue_code = "" task.last_error = "" - elif binding.status == BINDING_VIEW_PENDING: + task.updated_at = _now() + _append_event( + db, + task.id, + "binding_confirmed", + detail={ + "bindTaskId": int(source.id), + "previousBindTaskId": previous_bind_task_id, + "sourceTaskType": str(source.task_type or ""), + "baselineRoleName": str( + result.get("baseline_role_name") + or result.get("current_role_name") + or "" + )[:128], + "targetRoleName": target_role[:128], + "confirmedRoleName": confirmed_role[:128], + "confirmedChannel": binding.confirmed_channel, + }, + ) + _apply_task_lease_policy(db, task, lease=lease) + _emit_order_site_binding_state(db, task.id) + return True + + if binding.status == BINDING_VIEW_PENDING: + role_name = binding.pending_role_name + if not role_name: + return False + if phase == "confirming": + # 确认任务执行中,后到的扫码结果不能把订单打回待确认、丢掉确认任务指针。 + return False + if not is_current and phase not in ACTIVE_BINDING_STATUSES: + return False + if ( + task.binding_status == "role_ready" + and int(task.bind_task_id or 0) == int(source.id) + and not task.issue_code + and not task.last_error + ): + return False + task.bind_task_id = int(source.id) task.binding_status = "role_ready" task.execution_status = "role_ready" task.issue_code = "" task.last_error = "" - elif binding.reported_ready_for_confirm: - # 兼容旧快照:同名旧角色曾被误标为待确认。清掉绑定指针后,客户页会 - # 回到已分配状态,并在下一次刷新时自动生成新二维码、重新开始轮询。 - previous_bind_task_id = task.bind_task_id + task.updated_at = _now() + if previous_bind_task_id != source.id: + _append_event( + db, + task.id, + "binding_pending_task_linked", + detail={ + "bindTaskId": int(source.id), + "previousBindTaskId": previous_bind_task_id, + "roleName": role_name[:128], + "source": "owned" if owned else "legacy-current", + }, + ) + _apply_task_lease_policy(db, task, lease=lease) + _emit_order_site_binding_state(db, task.id) + return True + + if ( + is_current + and str(source.task_type or "") == "get_bind_qr" + and bool(result.get("bind_ready_for_confirm")) + and not _pending_role_of(source) + ): + # 兼容旧快照:同名旧角色曾被误标为待确认。清掉绑定指针,让客户页重新出码。 task.bind_task_id = None task.binding_status = "not_started" task.execution_status = "allocated" @@ -276,7 +590,8 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: task.id, "binding_stale_role_ignored", detail={ - "bindTaskId": previous_bind_task_id, + "bindTaskId": int(source.id), + "previousBindTaskId": previous_bind_task_id, "roleName": str(result.get("role_name") or "")[:100], "baselineRoleName": str( result.get("baseline_role_name") @@ -286,80 +601,117 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: }, ) _emit_order_site_binding_state(db, task.id) - _apply_task_lease_policy(db, task) + _apply_task_lease_policy(db, task, lease=lease) + return True + + return _apply_binding_qr_display( + db, + task, + source, + owned=owned, + is_current=is_current, + phase=phase, + lease=lease, + ) + + +def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: + """从订单当前挂着的绑定任务刷新订单状态。 + + 只消费订单自己的证据:当前 ``bind_task_id`` 指向的任务、以及显式带 + ``platform_task_id`` 的任务。账号上的其它任务不能改写订单。 + """ + task = _load_task(db, task_id) + if _frozen(task): + return get_task_detail(db, task.id) + if task.binding_status in ACTIVE_BINDING_STATUSES: + latest_pending = _latest_pending_binding_task(db, task) + if latest_pending is not None and _attach_pending_binding_task( + db, + task, + latest_pending, + ): + db.commit() + task = _load_task(db, task.id) + if not task.bind_task_id: + return get_task_detail(db, task.id) + bind_task = ( + db.query(DouyuTask).filter(DouyuTask.id == int(task.bind_task_id)).first() + ) + if bind_task is None: + return get_task_detail(db, task.id) + if bind_task.platform_task_id not in (None, int(task.id)): + # 数据异常:当前指针指向了别的订单的任务。只记录,不据此改状态。 + _record_binding_rejection( + db, + task, + bind_task, + reason="foreign_current_task", + ) db.commit() return get_task_detail(db, task.id) - elif binding.qr_url: - task.binding_status = "qr_pending" - task.execution_status = "waiting_bind" - task.issue_code = "" - task.last_error = "" - after = ( - task.binding_status, - task.execution_status, - task.exchange_status, - task.issue_code, - task.last_error, - ) - if after != before: - task.updated_at = _now() - if task.binding_status == "failed": - _append_event( - db, - task.id, - "binding_failed", - detail={ - "issueCode": task.issue_code, - "bindTaskId": bind_task.id, - "bindPhase": str(result.get("bind_phase") or ""), - "rawError": _binding_failure_raw_message( - task.issue_code, - result, - fallback=str(bind_task.message or ""), - )[:1000], - }, - ) - _emit_order_site_binding_state(db, task.id) - _apply_task_lease_policy(db, task) + owned = bind_task.platform_task_id is not None + _apply_binding_task(db, task, bind_task, owned=owned) db.commit() return get_task_detail(db, task.id) def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int: - """斗鱼绑定任务落库后,把关联履约任务和 Outbox 一并刷新。""" - task_ids = [ + """斗鱼绑定任务落库后,把订单自己的绑定证据合并回履约任务。""" + douyu_task = db.get(DouyuTask, int(douyu_task_id)) + if ( + douyu_task is None + or not douyu_task.account_id + or douyu_task.task_type not in BINDING_SYNC_TASK_TYPES + or str(douyu_task.handbook_scope or "") != "elite" + ): + # 电竞/和平小店任务与精英履约是不同作用域,绝不互相投影。 + return 0 + linked_task_ids = [ int(row.id) for row in ( db.query(PlatformFulfillmentTask.id) - .filter(PlatformFulfillmentTask.bind_task_id == int(douyu_task_id)) + .filter(PlatformFulfillmentTask.bind_task_id == int(douyu_task.id)) .all() ) ] - for task_id in task_ids: + for task_id in linked_task_ids: refresh_binding(db, task_id=task_id) - douyu_task = db.get(DouyuTask, int(douyu_task_id)) - if douyu_task is None or douyu_task.task_type not in BINDING_SYNC_TASK_TYPES: - return len(task_ids) + changed = len(linked_task_ids) if douyu_task.task_type in BINDING_OBSERVATION_TASK_TYPES: - return len(task_ids) + _sync_binding_observation(db, douyu_task) - binding = resolve_douyu_binding( - douyu_task, - account=db.get(Account, int(douyu_task.account_id)) - if douyu_task.account_id - else None, - ) - if ( - douyu_task.task_type not in ACCOUNT_CONFIRMATION_TASK_TYPES - or binding.status != BINDING_VIEW_CONFIRMED - ): - # 查询/出码任务只能证明“账号历史绑定是什么”,不能证明本次订单已经确认。 - # 只有明确执行成功并回查到 bind_confirmed 的确认任务,才允许把任务级 - # 确认事实投影到履约任务。 - linked = 0 + # 查询任务只用于展示账号当前角色,永远不能结算订单。 + return changed + if douyu_task.platform_task_id: + task = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.id == int(douyu_task.platform_task_id) + ) + .with_for_update() + .first() + ) if ( - douyu_task.task_type in PENDING_BINDING_TASK_TYPES - and binding.status == BINDING_VIEW_PENDING + task is not None + and task.id not in linked_task_ids + and task.account_id + and int(task.account_id) == int(douyu_task.account_id) + and not _frozen(task) + and _apply_binding_task(db, task, douyu_task, owned=True) ): + db.commit() + changed += 1 + return changed + # 兼容旧数据:部署前创建、没有 platform_task_id 的工作台绑定任务。 + if ( + str(douyu_task.task_type or "") == "get_bind_qr" + and douyu_task.status == "success" + ): + binding = resolve_fulfillment_binding( + douyu_task, + account=db.get(Account, int(douyu_task.account_id)), + binding_status="role_ready", + ) + if binding.status == BINDING_VIEW_PENDING: active_task = ( db.query(PlatformFulfillmentTask) .join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id) @@ -367,12 +719,13 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int: PlatformFulfillmentTask.account_id == int(douyu_task.account_id), PlatformFulfillmentTask.scope == "elite", PlatformFulfillmentTask.binding_status.in_( - ACTIVE_PENDING_TASK_STATUSES + ACTIVE_BINDING_STATUSES ), PlatformFulfillmentTask.execution_status.notin_( ("completed", "cancelled", "manual_required") ), AccountLease.status == "active", + AccountLease.purpose == "platform_fulfillment", ) .order_by( PlatformFulfillmentTask.updated_at.desc(), @@ -389,154 +742,19 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int: _apply_task_lease_policy(db, active_task) _emit_order_site_binding_state(db, active_task.id) db.commit() - linked = 1 - return len(task_ids) + linked - return len(task_ids) + sync_active_task_from_account_binding( - db, - account_id=int(douyu_task.account_id), - scope=str(douyu_task.handbook_scope or ""), - source_task_id=int(douyu_task.id), - ) - - -def _binding_observation_task( - db: Session, - task: PlatformFulfillmentTask, -) -> DouyuTask | None: - if not task.account_id or not task.bind_task_id: - return None - return ( - db.query(DouyuTask) - .filter( - DouyuTask.platform_task_id == int(task.id), - DouyuTask.account_id == int(task.account_id), - DouyuTask.task_type.in_(BINDING_OBSERVATION_TASK_TYPES), - DouyuTask.status == "success", - DouyuTask.id > int(task.bind_task_id), - ) - .order_by(DouyuTask.id.desc()) - .limit(1) - .first() - ) - - -def _apply_binding_observation( - db: Session, - task: PlatformFulfillmentTask, - observation_task: DouyuTask, - *, - account: Account | None = None, -) -> DouyuBindingReconciliation | None: - if not task.account_id: - return None - current_task = ( - db.get(DouyuTask, int(task.bind_task_id)) - if task.bind_task_id - else None - ) - resolved_account = account or db.get(Account, int(task.account_id)) - current = resolve_douyu_binding(current_task, account=resolved_account) - observation = resolve_douyu_binding( - observation_task, - account=resolved_account, - ) - reconciliation = reconcile_douyu_binding(current, observation) - if reconciliation.action != BINDING_RECONCILE_CONFIRMED: - return None - previous_bind_task_id = task.bind_task_id - task.bind_task_id = int(observation_task.id) - task.issue_code = "" - task.last_error = "" - task.updated_at = _now() - task.binding_status = "bound" - task.execution_status = "bound" - event_type = "binding_observation_confirmed" - _append_event( - db, - task.id, - event_type, - detail={ - "bindTaskId": int(observation_task.id), - "previousBindTaskId": previous_bind_task_id, - "pendingRoleName": reconciliation.pending_role_name, - "observedRoleName": reconciliation.observed_role_name, - "sourceTaskType": observation_task.task_type, - }, - ) - _apply_task_lease_policy(db, task) - _emit_order_site_binding_state(db, task.id) - return reconciliation - - -def _sync_binding_observation( - db: Session, - observation_task: DouyuTask, -) -> int: + changed += 1 + return changed if ( - not observation_task.platform_task_id - or not observation_task.account_id - or str(observation_task.handbook_scope or "") != "elite" + str(douyu_task.task_type or "") == "confirm_bind" + and douyu_task.status == "success" ): - return 0 - task = ( - db.query(PlatformFulfillmentTask) - .filter(PlatformFulfillmentTask.id == int(observation_task.platform_task_id)) - .with_for_update() - .first() - ) - if task is None or task.execution_status in {"completed", "cancelled"}: - return 0 - reconciled = _apply_binding_observation( - db, - task, - observation_task, - account=db.get(Account, int(observation_task.account_id)), - ) - if reconciled is None: - return 0 - db.commit() - return 1 - - -def _promote_bound_observation( - db: Session, - task: PlatformFulfillmentTask, - observation_task: DouyuTask, - *, - account: Account | None = None, -) -> bool: - if observation_task.task_type not in BINDING_OBSERVATION_TASK_TYPES: - return False - binding = resolve_douyu_binding( - observation_task, - account=account - or ( - db.get(Account, int(task.account_id)) - if task.account_id - else None - ), - ) - if binding.status != BINDING_VIEW_CONFIRMED: - return False - task.binding_status = "bound" - task.execution_status = "bound" - task.issue_code = "" - task.last_error = "" - task.updated_at = _now() - _append_event( - db, - task.id, - "binding_observation_confirmed", - detail={ - "bindTaskId": int(observation_task.id), - "previousBindTaskId": task.bind_task_id, - "observedRoleName": binding.confirmed_role_name, - "sourceTaskType": observation_task.task_type, - }, - ) - _apply_task_lease_policy(db, task) - _emit_order_site_binding_state(db, task.id) - return True + changed += sync_active_task_from_account_binding( + db, + account_id=int(douyu_task.account_id), + scope=str(douyu_task.handbook_scope or ""), + source_task_id=int(douyu_task.id), + ) + return changed def reconcile_binding_observations( @@ -544,18 +762,22 @@ def reconcile_binding_observations( *, limit: int = 500, ) -> int: - """启动时收敛已落库但尚未触发的较新账号角色观测。""" + """启动时收敛已落库但回调丢失的绑定证据。 + + 只处理订单自己的证据(``platform_task_id``)和兼容路径的旧待确认任务; + 账号上的查询任务不再参与订单结算。 + """ tasks = ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.scope == "elite", + PlatformFulfillmentTask.account_id.isnot(None), PlatformFulfillmentTask.binding_status.in_( - ("role_ready", "waiting_bind") + tuple(ACTIVE_BINDING_STATUSES) + ("confirming", "failed") ), PlatformFulfillmentTask.execution_status.notin_( - ("completed", "cancelled", "manual_required") + ("completed", "cancelled") ), - PlatformFulfillmentTask.bind_task_id.isnot(None), ) .order_by(PlatformFulfillmentTask.id.asc()) .limit(max(1, min(limit, 2000))) @@ -563,23 +785,45 @@ def reconcile_binding_observations( ) reconciled = 0 for task in tasks: - current_task = ( + if _frozen(task): + continue + changed = False + current = ( db.get(DouyuTask, int(task.bind_task_id)) if task.bind_task_id else None ) - if current_task is not None and _promote_bound_observation( - db, - task, - current_task, + if ( + current is not None + and current.status == "success" + and current.platform_task_id in (None, int(task.id)) ): - reconciled += 1 - continue - observation_task = _binding_observation_task(db, task) - if observation_task is None: - continue - result = _apply_binding_observation(db, task, observation_task) - if result is not None: + changed = _apply_binding_task( + db, + task, + current, + owned=current.platform_task_id is not None, + ) + if not changed: + for evidence in _owned_binding_tasks( + db, + task, + newer_than=int(task.bind_task_id or 0), + ): + if evidence.status != "success": + continue + if _apply_binding_task(db, task, evidence, owned=True): + changed = True + break + if not changed and task.binding_status in ACTIVE_BINDING_STATUSES: + latest_pending = _latest_pending_binding_task(db, task) + if latest_pending is not None and _attach_pending_binding_task( + db, + task, + latest_pending, + ): + changed = True + if changed: reconciled += 1 if reconciled: db.commit() @@ -592,9 +836,12 @@ def _latest_pending_binding_task( ) -> DouyuTask | None: if ( not task.account_id - or task.binding_status not in ACTIVE_PENDING_TASK_STATUSES + or task.binding_status not in ACTIVE_BINDING_STATUSES ): return None + lease = _lease_for_task(db, task) + if not lease_is_active(lease): + return None rows = ( db.query(DouyuTask) .filter( @@ -603,6 +850,10 @@ def _latest_pending_binding_task( DouyuTask.handbook_scope == "elite", DouyuTask.status == "success", DouyuTask.id > int(task.bind_task_id or 0), + ( + (DouyuTask.platform_task_id == int(task.id)) + | DouyuTask.platform_task_id.is_(None) + ), ) .order_by(DouyuTask.id.desc()) .limit(20) @@ -610,10 +861,9 @@ def _latest_pending_binding_task( ) account = db.get(Account, int(task.account_id)) for row in rows: - if resolve_douyu_binding( - row, - account=account, - ).status == BINDING_VIEW_PENDING: + if not source_created_within_lease(lease, row): + continue + if resolve_douyu_binding(row, account=account).status == BINDING_VIEW_PENDING: return row return None @@ -628,13 +878,20 @@ def _attach_pending_binding_task( if task.account_id else None ) + lease = _lease_for_task(db, task) binding = resolve_douyu_binding(bind_task, account=account) if ( - task.binding_status not in ACTIVE_PENDING_TASK_STATUSES + task.binding_status not in ACTIVE_BINDING_STATUSES or not task.account_id or int(bind_task.account_id or 0) != int(task.account_id) or bind_task.task_type not in PENDING_BINDING_TASK_TYPES or binding.status != BINDING_VIEW_PENDING + or not lease_is_active(lease) + or not source_created_within_lease(lease, bind_task) + or ( + bind_task.platform_task_id is not None + and int(bind_task.platform_task_id) != int(task.id) + ) ): return False current_id = int(task.bind_task_id or 0) @@ -671,12 +928,11 @@ def sync_active_task_from_account_binding( scope: str, source_task_id: int | None = None, ) -> int: - """确认任务成功后,把当前活跃履约任务同步到 bound。 + """兼容旧流程:精英宝典工作台的无归属确认任务结算当前待确认订单。 - 精英宝典工作台发出的确认任务不挂在履约任务上,因此不能只看 - ``PlatformFulfillmentTask.bind_task_id``。这里的唯一事实是确认任务的 - ``result``:只有 ``resolve_douyu_binding`` 返回 confirmed 才允许投影。 - 账号上的 ``role_bind_status`` 只描述当前生效角色,不能证明本订单已确认。 + 必须同时满足:订单还在 role_ready、确认任务创建于本订单租约期间、 + 确认角色等于订单当前待确认角色。任何一条不满足都不改订单,只记录 + ``binding_sync_rejected``。 """ if scope != "elite": return 0 @@ -685,30 +941,28 @@ def sync_active_task_from_account_binding( if source_task_id is not None else None ) - account = db.get(Account, int(account_id)) - binding = ( - resolve_douyu_binding(source_task, account=account) - if source_task is not None - else None - ) if ( source_task is None - or binding is None - or source_task.task_type not in ACCOUNT_CONFIRMATION_TASK_TYPES - or binding.status != BINDING_VIEW_CONFIRMED + or source_task.status != "success" + or str(source_task.task_type or "") != "confirm_bind" ): return 0 + account = db.get(Account, int(account_id)) + binding = resolve_douyu_binding(source_task, account=account) + if binding.status != BINDING_VIEW_CONFIRMED: + return 0 task = ( db.query(PlatformFulfillmentTask) .join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id) .filter( PlatformFulfillmentTask.account_id == int(account_id), PlatformFulfillmentTask.scope == "elite", - PlatformFulfillmentTask.binding_status.in_(("role_ready", "confirming")), + PlatformFulfillmentTask.binding_status == "role_ready", PlatformFulfillmentTask.execution_status.notin_( ("completed", "cancelled") ), AccountLease.status == "active", + AccountLease.purpose == "platform_fulfillment", ) .order_by( PlatformFulfillmentTask.updated_at.desc(), @@ -719,6 +973,35 @@ def sync_active_task_from_account_binding( ) if task is None: return 0 + lease = _lease_for_task(db, task) + if not lease_is_active(lease) or not source_created_within_lease( + lease, + source_task, + ): + _record_binding_rejection( + db, + task, + source_task, + reason="source_outside_lease", + confirmed_role=binding.confirmed_role_name, + ) + db.commit() + return 0 + target_role = _order_target_role(db, task, before_task_id=int(source_task.id)) + if not target_role or not role_names_match( + binding.confirmed_role_name, + target_role, + ): + _record_binding_rejection( + db, + task, + source_task, + reason="target_mismatch" if target_role else "missing_target", + confirmed_role=binding.confirmed_role_name, + target_role=target_role, + ) + db.commit() + return 0 task.bind_task_id = int(source_task.id) task.binding_status = "bound" task.execution_status = "bound" @@ -736,30 +1019,26 @@ def sync_active_task_from_account_binding( if account is not None else "" ), - "roleName": ( - binding.confirmed_role_name - or binding.effective_role_name - or binding.current_role_name - ), + "roleName": binding.confirmed_role_name, "gameChannel": ( binding.confirmed_channel or binding.effective_channel or binding.current_channel ), + "targetRoleName": target_role, + "sourceTaskId": int(source_task.id), "roleChangeAvailableAt": ( account.role_change_available_at.isoformat() if account is not None and account.role_change_available_at else None ), - "sourceTaskId": source_task_id, }, ) - _apply_task_lease_policy(db, task) + _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) db.commit() return 1 - def requires_account_binding_sync(task_type: str) -> bool: return str(task_type or "") in BINDING_SYNC_TASK_TYPES diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index 8031fe5..05388de 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -134,6 +134,8 @@ const EVENT_LABELS: Record = { binding_pending_task_linked: '关联最新待确认角色', binding_pending_observation_superseded: '旧待确认角色已被最新绑定替换', binding_observation_confirmed: '账号观测确认角色绑定', + binding_confirmed: '履约绑定已确认', + binding_sync_rejected: '忽略不匹配的绑定证据', eligibility_check_failed: '兑换资格查询失败', eligibility_auto_refresh_failed: '自动刷新兑换资格失败', exchange_eligibility_checked: '刷新兑换资格', @@ -357,6 +359,19 @@ function eventDescription(event: { eventType: string; detail: Record