11 Commits
Author SHA1 Message Date
yml b0be3d15cc test: 拆分慢速迁移测试并优化 pre-push
- 迁移测试标记 migration,单独运行约 130 秒
- 非迁移测试约 90 秒,日常开发跑快速集
- pre-push 默认跳过 migration;改迁移/模型/迁移测试时自动全量
- FULL_TESTS=1 可强制全量,不删除任何迁移测试
2026-11-24 19:14:40 +08:00
yml b10018efdd fix(fulfillment): 修复分配重试产生的孤儿租约
- 分配前锁平台任务行,避免同一任务并发领两个账
- 落库前释放同任务下其他 active 租约
- 租约回收作业增加 task/租约不一致的孤儿回收
- 补充孤儿租约回收测试与订单 2632301937741357 复盘
2026-11-24 19:03:07 +08:00
yml 1081e93522 fix(automation): 租约巡检降为4小时并收紧首次登录样本
- lease_bound 30 分钟会超出 ck_health 吞吐,改为 240 分钟
- 首次登录样本排除缺账号/密码和已判极验/凭证失败的账号
- 补充保护组和首登样本准入测试
2026-11-24 18:36:34 +08:00
yml 03c7c74eab feat(automation): 增加租约 CK 到期前刷新
- 保护组新增 lease_bound,覆盖全部生效履约/协作租约
- 新增 lease_ck_refresh 作业,提前 24h 为有效 CK 续期
- 已失效重登仍由 ck_relogin 处理
- 失败按类型设置退避,避免每轮重复撞
- 补充保护组、选行、作业执行测试
2026-11-24 18:04:09 +08:00
yml 2e6303361c feat(accounts): 统一可换绑时间并加本地 7 天锁
- 新增官方时间、本地 bind_ok、7 天锁到期、检查时间和来源字段
- role_change_available_at 改为官方时间与本地锁取较晚者
- 绑定成功和官方探测统一写有效时间
- 分配过滤增加最近 elite bind_ok 的数据库兜底
- 迁移 0129 从 account_events 回填历史账号
- 补充字段/回填过滤测试和生命周期文档
2026-11-24 17:37:15 +08:00
yml a1530b7e74 feat(fulfillment): 映射操作全部展开并用居中弹窗编辑
- 每行直接展示编辑/启用停用/归档恢复/删除,不再收进更多菜单
- 新建和编辑改为居中 Modal,不再使用右侧抽屉
- 调整操作列宽,表格仍无横向滚动
2026-11-24 17:12:09 +08:00
yml 95bfa0dcb7 feat(fulfillment): 分类只展示销售模式
- 移除“待开放/可兑换”第二标签,只保留预售/直接兑换/人工
- 任务列表、详情、商品映射分类保持一致
- 详情移除“开放状态”行
2026-11-24 17:10:31 +08:00
yml 751a45782f feat(fulfillment): 优化斗鱼商品映射管理界面
- 表格压缩为无横向滚动,操作收进更多菜单,删除/归档随时可见
- 新建和编辑改为右侧抽屉表单,不再占用列表顶部
- 增加 SKU 搜索、销售模式过滤、归档开关和刷新
- 表格合并活动批次/商品 ID 到次要信息,减少列宽
2026-11-24 17:08:37 +08:00
yml c6e6e66f2d feat(fulfillment): 区分普通代确认与人工强制确认
- 普通代确认走 refresh_binding + actBind,不填角色/备注
- 强制确认保留角色+依据,并校验账号当前角色一致
- 前端拆成“代客户确认”和红色“强制确认”
- 补充普通代确认/角色不匹配回归测试与文档
2026-11-24 16:57:49 +08:00
yml 55afbaa903 fix(fulfillment): 人工确认必须匹配账号当前角色
- 账号当前角色与确认角色不一致时拒绝人工确认
- 前端不一致时禁用确认并提示
- 补充角色不匹配回归测试
- 记录订单 2632801603123492 强制确认问题
2026-11-24 16:52:08 +08:00
yml abab55a810 docs(douyu): 记录账号供给优化后续 TODO 2026-11-24 16:32:02 +08:00
36 changed files with 1690 additions and 221 deletions
+10 -1
View File
@@ -18,6 +18,7 @@ fi
python_files=() python_files=()
frontend_changed=0 frontend_changed=0
migration_changed=0
while read -r local_ref local_sha remote_ref remote_sha; do while read -r local_ref local_sha remote_ref remote_sha; do
[ -z "$local_sha" ] && continue [ -z "$local_sha" ] && continue
if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then
@@ -37,6 +38,9 @@ while read -r local_ref local_sha remote_ref remote_sha; do
web/frontend/*) web/frontend/*)
frontend_changed=1 frontend_changed=1
;; ;;
web/backend/migrations/*|web/backend/models.py|tests/test_migrations.py|tests/test_migration_*.py|tests/test_login_attempt_migration.py)
migration_changed=1
;;
esac esac
done <<< "$changed_paths" done <<< "$changed_paths"
done <<< "$push_lines" done <<< "$push_lines"
@@ -88,6 +92,11 @@ ensure_test_mysql() {
ensure_test_mysql ensure_test_mysql
echo "[pre-push] 运行 pytest..." if [ "${FULL_TESTS:-0}" = "1" ] || [ "$migration_changed" -eq 1 ]; then
echo "[pre-push] 运行全量 pytest(含迁移测试)..."
./dev.sh test -q ./dev.sh test -q
else
echo "[pre-push] 运行 pytest(跳过慢速迁移测试;FULL_TESTS=1 可跑全量)..."
./dev.sh test -q -m "not migration"
fi
echo "[pre-push] pytest 通过" echo "[pre-push] pytest 通过"
+9 -2
View File
@@ -142,7 +142,9 @@ python3 -c 'import secrets; print(secrets.token_urlsafe(32))'
## 运行测试 ## 运行测试
```bash ```bash
uv run --group dev pytest # 或 ./dev.sh test uv run --group dev pytest # 全量(含迁移测试,约 3-4 分钟)
./dev.sh test -q -m "not migration" # 日常快速:约 90 秒,跳过 22 个慢速迁移测试
./dev.sh test -q -m migration # 只跑迁移/回填测试
uv run --group dev pytest tests/test_cookie_operations.py uv run --group dev pytest tests/test_cookie_operations.py
./dev.sh format tests conftest.py ./dev.sh format tests conftest.py
./dev.sh format-check tests conftest.py ./dev.sh format-check tests conftest.py
@@ -150,6 +152,11 @@ uv run --group dev pytest tests/test_cookie_operations.py
docker compose --profile test run --rm test docker compose --profile test run --rm test
``` ```
迁移测试会为每个用例创建临时 MySQL 库并重跑 Alembic 链,约占全量时间
**60%**;保留它们,不改历史迁移数据。pre-push 默认跳过迁移测试,只有改到
`web/backend/migrations/`、`web/backend/models.py` 或迁移测试文件时才跑全量;
需要强制全量时用 `FULL_TESTS=1 git push`。
测试跑在**真实 MySQL** 上(不再使用 SQLite):生产是 MySQL,SQLite 与它有方言差异, 测试跑在**真实 MySQL** 上(不再使用 SQLite):生产是 MySQL,SQLite 与它有方言差异,
曾出现「`ORDER BY ... NULLS FIRST` 本地全绿、生产直接 1064」的事故。因此: 曾出现「`ORDER BY ... NULLS FIRST` 本地全绿、生产直接 1064」的事故。因此:
@@ -170,7 +177,7 @@ docker compose --profile test run --rm test
``` ```
- **pre-commit**:暂存的 Python 文件做 Ruff 格式检查;改了 `web/frontend/` 则跑 `tsc -b` - **pre-commit**:暂存的 Python 文件做 Ruff 格式检查;改了 `web/frontend/` 则跑 `tsc -b`
- **pre-push**:上述检查 + 全量 pytest - **pre-push**:上述检查 + pytest(普通改动跳过 migration marker;迁移/模型改动自动全量)
- Pyright 默认不开(噪音大):`TYPECHECK=1 git push` - Pyright 默认不开(噪音大):`TYPECHECK=1 git push`
- 紧急绕过:`git push --no-verify` 或 `SKIP_TESTS=1 git push` - 紧急绕过:`git push --no-verify` 或 `SKIP_TESTS=1 git push`
@@ -588,3 +588,101 @@ GET bindInfo?actAlias=20260120QYOOB
bindAct、换绑等待、错误/消息; bindAct、换绑等待、错误/消息;
- 以后先看这张表,再看平台任务状态,不再把“绑定任务 role_ready”和 - 以后先看这张表,再看平台任务状态,不再把“绑定任务 role_ready”和
“平台任务 qr_pending”混为一谈。 “平台任务 qr_pending”混为一谈。
### 9.11 2026-11-24 人工确认被误用:账号旧角色 ≠ 客户角色(订单 2632801603123492)
生产只读:
```text
平台任务 7882:
binding_status=bound, execution_status=bound
account_id=24087, bind_task_id=575407
账号 24087:
game_name=小乖悄, role_bind_status=bound
绑定任务 575407:
status=success, role_ready
role_name=等清晰, current_role_name=小乖悄
act_alias=cjm, action_act_aliases=[20260120QYOOB]
手工事件 58716:
binding_manually_confirmed
roleName=等清晰, account_role=小乖悄
note=等清晰, operator=45
```
后续确认:
```text
08:44/08:46 confirm_bind.precheck:
QYOOB 小乖悄 bindAct=1
cjm 等清晰 bindAct=0
confirm_bind.error:
error=-200001
msg=该账号未到可换绑时间,请使用其他账号
```
判断:
1. 客户扫到的是 cjm 的「等清晰」;
2. 账号 24087 官方当前角色仍是「小乖悄」,QYOOB 没有「等清晰」pending;
3. 账号的 `canChangeTime` 已过(2026-11-24 00:00 北京时间),所以不是账号侧冷却;
4. actBind 仍返回 `-200001`,说明更可能是**客户角色侧**未到换绑时间/绑定在其他账号;
5. 本地 `account_events` 没有「等清晰」的 bind_ok,所以本地角色锁无法提前发现,只有官方 actBind 是权威;
6. 人工确认在 08:38 直接把订单标成 bound,但账号角色仍是「小乖悄」,这是**错误的强制确认**。
根因:
- 人工确认接口只要求“填写确认角色”,没有要求账号当前角色等于确认角色;
- 运营填了「等清晰」,就绕过了 actBind 和角色校验;
- 结果订单 bound,但账号并没有换绑到客户角色,兑换会在错误角色上执行。
修复:
- 人工确认必须同时满足:
- 账号 `role_bind_status=bound`;
- 账号 `game_name` 与确认角色完全一致;
- 备注至少 2 个字;
- 不一致直接 409,提示“账号当前角色是 X,确认角色是 Y,不能人工确认;换绑请先 actBind 或使用正确账号”;
- 前端确认角色与账号当前角色不一致时禁用“确认绑定”,并显示错误提示;
- 该订单 7882 应释放/转人工,重新分配能绑定「等清晰」的账号,或等角色冷却结束,不能继续按 bound 走兑换。
教训:
人工确认只能作为“账号已经绑定到该角色、只是缺本次扫码证据”的兜底,
不能作为“换绑失败后强行标记成功”的按钮。
### 9.12 普通代确认 vs 人工强制确认
两种人工动作必须分开,不能都要求填角色/备注:
| 动作 | 使用场景 | 是否填信息 | 行为 |
| --- | --- | --- | --- |
| 代客户确认 | 客户已登记资料、已扫码,只是没点确认 | 否 | 刷新绑定证据后走正常 `actBind`;成功才 bound |
| 人工强制确认 | 账号已确认绑定该角色,但没有本次扫码证据 | 是(角色+依据) | 直接标 bound;必须记录操作人/角色/备注 |
普通代确认:
- `POST /tasks/{id}/bind/operator-confirm`;
- 内部 `refresh_binding` → 要求平台任务 `role_ready` → 创建正常 `confirm_bind`;
- 不直接改 bound,不写 `binding_manually_confirmed`;
- 同账号同角色可复用的情况会直接 bound(已有复用逻辑);
- 角色锁/actBind 冷却仍然生效。
人工强制确认:
- `POST /tasks/{id}/bind/manual-confirm`;
- 必须账号 `role_bind_status=bound` 且 `game_name == 确认角色`;
- 必须填写角色 + 至少 2 字依据;
- 不一致 409;
- 前端红色按钮,不一致时禁用。
订单 2632801853205627(任务 7936)这类:
```text
本次扫码角色 = 账号当前角色
本次可确认 = 不可确认(same_role_stale)
本次扫码与账号当前角色相同,可复用
```
属于**普通代确认**,运营一键“代客户确认”即可;不需要填写角色/备注,也不应该走强制确认。
订单 2632801603123492(任务 7882)这类账号当前角色与客户角色不一致的,普通代确认会被 actBind/角色锁挡住;强制确认也必须拒绝,只能换号或等冷却。
@@ -304,3 +304,36 @@ capability_key = elite:<commodity_id>
2. 做租约 CK 保护优先级(P1); 2. 做租约 CK 保护优先级(P1);
3. 做首次登录普查(P2,已有 `account_onboarding`); 3. 做首次登录普查(P2,已有 `account_onboarding`);
4. 最后才把质量分/冗余接入选号(P3)。 4. 最后才把质量分/冗余接入选号(P3)。
## 11. 后续 TODO(2026-11-24 部署后)
当前生产:`c883f83`,Alembic `20261124_0128`,账号供给画像作业已开启。
| 优先级 | 事项 | 状态/说明 |
| --- | --- | --- |
| P0 | 等 31k 画像铺满(约 7 批、70 分钟) | 第一批 5000 条已成功,游标 5188 |
| P0 | 分析全量角色/质量分/冗余/租约 CK 分布 | 形成基线后再改行为 |
| P1 | 租约 CK 保护优先级 | 接入现有 `ck_health` protection groups,不新建重复机制 |
| P1 | 登录任务“触发方式/执行人”验收 | 自动化/人工/首次登录/重登/检测 |
| P2 | 首次登录作业 20 个样本 | 默认关闭;成功后再打开、放量 |
| P2 | 观察重登邮箱回退 | `ck_relogin` 已启用;18,355 失效积压,先看回退与失败率 |
| P3 | 选号接入质量分/冗余预留 | 观察 3 天后;unique/rare 不用于普通单 |
| P4 | 告警 | 租约 CK 24h 到期、unique/rare 不足、供给 buffer、普查停滞 |
| 运维 | 7887/7889 预确认投影缺口 | 旧单;7871/7868 人工处理 |
### 执行顺序
1. 等画像铺满,导出角色/冗余/质量分基线;
2. 验收登录任务来源列;
3. 首次登录 20 个样本;
4. 观察 `ck_relogin` 回退 1–2 天,再评估 batch/concurrency;
5. 做 P1 租约 CK 保护;
6. 观察 3 天后再做 P3 选号接入;
7. P4 告警与每周复盘。
### 不做
- 不在画像未铺满前改选号;
- 不用总分替代硬约束;
- 不把租约账号算进供给池;
- 不一次性全量跑首次登录。
+27
View File
@@ -288,3 +288,30 @@ live-hub 创建新的绑定任务。
- 自动兑换 - 自动兑换
- 多数量拆分 - 多数量拆分
- 电竞手册、和平小店、虎牙和微博 - 电竞手册、和平小店、虎牙和微博
## 租约孤儿与协作单接管冲突(2026-11-24)
订单 `2632301937741357` / 任务 #1057 在“当前待办”搜不到,是因为任务已经是
`manual_required` / `lease_expired`,需要到“需要人工”里查。
协作单编辑报“平台履约任务 #7482 与账号租约不一致”,根因不是 #1057,而是
任务 #7482 的分配重试留下了孤儿租约:
```text
lease 8877 account 5566 batch_id pf:7482
task 7482 account 5567 lease_id 8879
```
协作单按 `batch_id=pf:7482` 找到任务,再核对账号/租约不一致,拒绝接管。
修复:
1. `allocate_task` 先对平台任务行加锁,避免同一任务并发领到两个租约;
2. 分配落库前释放同任务下其他 active 租约(reason=`allocation_replaced`);
3. `platform_fulfillment_lease_reaper` 增加孤儿租约回收:
- active 租约的 `batch_id=pf:<task>`;
- task 不存在,或 task.account_id / task.lease_id 与租约不一致;
- 释放 reason=`lease_task_mismatch`。
这条回收会顺带释放账号 5566 的 8877。释放后把任务 #1057 重新分配到 5566,
协作单才能正常接管。
+108
View File
@@ -207,3 +207,111 @@ CK 本体和健康结果都在账号上:
- `web/backend/services/automation/jobs/`:巡检、重登和资料刷新 - `web/backend/services/automation/jobs/`:巡检、重登和资料刷新
- `tests/test_account_lifecycle.py`:状态真值表、漂移检查和写入点约束 - `tests/test_account_lifecycle.py`:状态真值表、漂移检查和写入点约束
- `tests/test_account_overview.py`:一键查询、字段落库和高价值资产判定 - `tests/test_account_overview.py`:一键查询、字段落库和高价值资产判定
## 可换绑时间与本地 7 天锁(2026-11-24)
### 为什么要拆开
`accounts.role_change_available_at` 原来只存官方 `canChangeTime`。但账号还有一个
**本地规则**:同一斗鱼账号 7 天内只能绑定一个精英角色(`account_events.bind_ok`)。
两个时间不一致时,分配器按官方时间选中账号,真正绑定时才被
`binding_account_locked_elsewhere` 拦下。
订单 `2632801766531717` / 账号 23168 就是实例:
```text
官方 canChangeTime: 2026-11-24 00:00
本地 bind_ok: 2026-11-17 22:49
本地锁到期: 2026-11-24 22:49
```
分配器只看官方时间,于是 16:47 选中;17:00 释放后又选回同一个;17:07 人工强制确认。
### 字段
| 字段 | 含义 |
| --- | --- |
| `role_change_official_at` | 官方 `canChangeTime` / `now+wait_time` |
| `last_bind_ok_at` | 最近一次精英 `bind_ok` |
| `role_bind_lock_until` | `last_bind_ok_at + 7d` |
| `role_change_available_at` | **有效可换绑时间 = max(官方, 本地锁)** |
| `role_change_checked_at` | 最近一次判断时间 |
| `role_change_source` | `official` / `local_bind` / `backfill` |
### 写入规则
1. 官方 `bindInfo` / probe:
- 写 `role_change_official_at`、`role_change_checked_at`;
- `role_change_available_at = max(官方, role_bind_lock_until)`。
2. `record_bind` 真正绑定成功:
- 写 `last_bind_ok_at`、`role_bind_lock_until`;
- 有效时间取大;
- `role_change_source=local_bind`。
3. 分配/人工选号:
- 只判断 `role_change_available_at <= now`;
- 同时加数据库兜底:最近 7 天有 `elite_role` 的 `bind_ok` 直接排除。
4. 同账号同角色复用不产生新的 `bind_ok`,不重置本地锁。
### 迁移与回填
`20261124_0129`:
- 新增上述字段;
- 从 `account_events`(`event_type=bind_ok`、`subject_type=elite_role`)回填
`last_bind_ok_at`;
- 有效时间取官方与本地锁的较大值;
- 旧 `role_change_available_at` 保留到 `role_change_official_at`。
### 不做什么
- 不新增同义的 `can_change_time` 字段;
- 不用官方时间替换本地 7 天规则;
- 不把 `change_role_wait_time`(相对秒数)当分配依据;
- 不为了“能选中”绕过本地锁。
## P1:租约 CK 到期前刷新(2026-11-24)
生产基线:3,973 个生效租约,其中约 293 个有效 CK 预测 24 小时内到期
(`platform_fulfillment` 202,`douyu_collab` 91)。
### 保护组
`ck_health.config["protection_groups"]` 新增 `lease_bound`:
- 成员:`account_leases.status=active` 且 purpose 为
`platform_fulfillment` / `douyu_collab`;
- 默认开启;
- 巡检间隔 240 分钟(比普通账号更短,且不挤占 ck_health 吞吐);
- 自动重登开启。
这样所有生效租约账号都会进入 CK 巡检和失效重登保护,不再只覆盖预售/协作单。
### 到期前刷新作业
新增 `lease_ck_refresh`:
- 只处理仍为 `ck_check_status=valid` 的生效租约账号;
- 预测到期时间在 24h 内;
- 有 Cookie、可自动管理、没有在途登录;
- 人工失败分型和退避中的账号跳过;
- 每轮 batch=10,10 分钟一轮,默认开启;
- 走 `run_login_batch_with_fallback`,与首次登录/重登共用登录配额和审计。
与 `ck_relogin` 的分工:
| 作业 | 对象 |
| --- | --- |
| `lease_ck_refresh` | 仍有效、但 24h 内到期的租约账号,提前续 CK |
| `ck_relogin` | 已经 invalid 的账号,失效后重登 |
### 为什么不是等失效再登
租约账号在履约期间 CK 失效会出现不可用窗口;提前登录可以把窗口前移到空闲时段。
作业不直接改绑定或订单,只刷新 Cookie。
### 首次登录样本
`account_onboarding` 保持默认关闭。先点“立即跑一次”跑 20 个样本,不打开自动作业;
样本账号会排除缺账号/密码和已判定极验/凭证失败的账号,避免样本被必失败账号污染。
确认成功率、失败分型和登录后商品能力同步后,再启用作业放量。
+3
View File
@@ -44,6 +44,9 @@ packages = ["core", "utils", "web"]
[tool.pytest.ini_options] [tool.pytest.ini_options]
testpaths = ["tests"] testpaths = ["tests"]
markers = [
"migration: 创建临时 MySQL 库并执行 Alembic 迁移链;比普通用例慢很多",
]
[tool.ruff.lint.per-file-ignores] [tool.ruff.lint.per-file-ignores]
# FastAPI evaluates dependency metadata in route parameter defaults by design. # FastAPI evaluates dependency metadata in route parameter defaults by design.
+13
View File
@@ -70,6 +70,19 @@ def test_selector_only_picks_unlogged_automatable_accounts(db):
assert job.count_pending_onboarding(db) == 1 assert job.count_pending_onboarding(db) == 1
def test_selector_skips_missing_password_and_manual_failure(db):
_admin(db)
selectable = _account("onboarding-eligible")
missing_password = _account("onboarding-no-password", password="")
manual_failure = _account("onboarding-captcha", relogin_failure_kind="captcha")
db.add_all([selectable, missing_password, manual_failure])
db.commit()
rows = job.build_select_query(db, _job()).all()
assert [row.id for row in rows] == [selectable.id]
def test_run_account_onboarding_returns_batch_summary(db, monkeypatch): def test_run_account_onboarding_returns_batch_summary(db, monkeypatch):
_admin(db) _admin(db)
first = _account("onboarding-first") first = _account("onboarding-first")
+53
View File
@@ -6,6 +6,7 @@ from datetime import UTC, datetime, timedelta
from web.backend.models import ( from web.backend.models import (
Account, Account,
AccountLease,
AutomationJob, AutomationJob,
DouyuExternalOrder, DouyuExternalOrder,
PlatformFulfillmentTask, PlatformFulfillmentTask,
@@ -123,6 +124,58 @@ def test_protection_membership_uses_active_fulfillment_relationships(db):
) )
def test_lease_bound_includes_all_active_lease_purposes(db):
user = User(
username="lease-protection-user",
password_hash="h",
role="super_admin",
is_active=True,
)
leased = _account("protection-leased")
collab_leased = _account("protection-collab-leased")
released = _account("protection-released")
other_purpose = _account("protection-other-purpose")
db.add_all([user, leased, collab_leased, released, other_purpose])
db.flush()
db.add_all(
[
AccountLease(
account_id=leased.id,
holder_user_id=user.id,
purpose="platform_fulfillment",
status="active",
),
AccountLease(
account_id=collab_leased.id,
holder_user_id=user.id,
purpose="douyu_collab",
status="active",
),
AccountLease(
account_id=released.id,
holder_user_id=user.id,
purpose="platform_fulfillment",
status="released",
),
AccountLease(
account_id=other_purpose.id,
holder_user_id=user.id,
purpose="other",
status="active",
),
]
)
db.commit()
snapshot = load_protection_snapshot(db, job_config=None)
assert snapshot.group_account_ids["lease_bound"] == frozenset(
{leased.id, collab_leased.id}
)
assert snapshot.groups["lease_bound"]["probe_interval_minutes"] == 240
assert leased.id in snapshot.relogin_ids
def test_protection_target_reports_ck_health_and_shortage(db): def test_protection_target_reports_ck_health_and_shortage(db):
valid = _account("protection-valid") valid = _account("protection-valid")
invalid = _account("protection-invalid", ck_status="invalid") invalid = _account("protection-invalid", ck_status="invalid")
+135
View File
@@ -0,0 +1,135 @@
"""账号可换绑时间:本地 7 天锁、有效时间与分配过滤。"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from web.backend.models import Account, AccountEvent
from web.backend.services.account_binding import (
effective_role_change_available_at,
role_bind_lock_until,
)
from web.backend.services.account_query_filters import role_change_ready_filter
from web.backend.services.business_events import record_bind
NOW = datetime.now(UTC).replace(microsecond=0)
def _account(name: str, **overrides) -> Account:
values = {
"username": name,
"password": "p",
"email": f"{name}@example.com",
"email_password": "ep",
"status": "active",
"auto_managed": True,
"cookie": "acf_uid=1",
"ck_check_status": "valid",
"ck_checked_at": NOW,
"cookie_updated_at": NOW,
}
values.update(overrides)
return Account(**values)
def _bind_event(account: Account, occurred_at: datetime, ref: str) -> AccountEvent:
return AccountEvent(
account_id=account.id,
event_type="bind_ok",
category="business",
occurred_at=occurred_at,
title="精英宝典绑定:旧角色",
detail={"scope": "elite", "role_name": "旧角色"},
source="douyu_task",
subject_type="elite_role",
subject_key="旧角色",
source_ref=ref,
)
def test_effective_time_uses_later_of_official_and_local_lock():
official = datetime(2026, 11, 24, 0, 0, tzinfo=UTC)
bound = datetime(2026, 11, 17, 14, 49, 25, tzinfo=UTC)
assert role_bind_lock_until(bound) == datetime(2026, 11, 24, 14, 49, 25, tzinfo=UTC)
assert effective_role_change_available_at(
official_at=official, last_bind_ok_at=bound
) == datetime(2026, 11, 24, 14, 49, 25, tzinfo=UTC)
assert effective_role_change_available_at(
official_at=official, last_bind_ok_at=None
) == official
assert effective_role_change_available_at(
official_at=None, last_bind_ok_at=None
) is None
def test_record_bind_sets_local_lock_and_effective_time(db):
account = _account(
"role-lock-bind",
role_change_official_at=datetime(2026, 11, 24, 0, 0, tzinfo=UTC),
role_change_available_at=datetime(2026, 11, 24, 0, 0, tzinfo=UTC),
)
db.add(account)
db.commit()
occurred = datetime(2026, 11, 17, 14, 49, 25, tzinfo=UTC)
assert record_bind(
db,
account,
task_id=990001,
scope="elite",
role_name="旧角色",
occurred_at=occurred,
actor_id=1,
)
db.commit()
db.refresh(account)
assert account.last_bind_ok_at == occurred
assert account.role_bind_lock_until == datetime(2026, 11, 24, 14, 49, 25, tzinfo=UTC)
assert account.role_change_available_at == account.role_bind_lock_until
assert account.role_change_source == "local_bind"
def test_role_change_filter_rejects_recent_bind_even_if_field_says_ready(db):
ready = _account(
"role-lock-ready",
role_change_available_at=NOW - timedelta(days=1),
)
locked = _account(
"role-lock-recent",
role_change_available_at=NOW - timedelta(days=1),
)
db.add_all([ready, locked])
db.flush()
db.add(_bind_event(locked, NOW - timedelta(days=1), "role-filter:recent"))
db.commit()
rows = (
db.query(Account.id)
.filter(role_change_ready_filter(NOW))
.filter(Account.id.in_([ready.id, locked.id]))
.all()
)
assert [row[0] for row in rows] == [ready.id]
def test_role_change_filter_allows_old_bind(db):
old = _account(
"role-lock-old",
role_change_available_at=NOW - timedelta(days=8),
)
db.add(old)
db.flush()
db.add(_bind_event(old, NOW - timedelta(days=8), "role-filter:old"))
db.commit()
rows = (
db.query(Account.id)
.filter(role_change_ready_filter(NOW))
.filter(Account.id == old.id)
.all()
)
assert [row[0] for row in rows] == [old.id]
+131
View File
@@ -0,0 +1,131 @@
"""租约 CK 到期前刷新的选行和作业测试。"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from web.backend.models import Account, AccountLease, AutomationJob, User
from web.backend.services.automation.jobs import lease_ck_refresh
def _account(name: str, *, cookie_updated_at: datetime, ck_status: str = "valid", **overrides) -> Account:
values = {
"username": name,
"password": "p",
"email": f"{name}@example.com",
"email_password": "ep",
"cookie": "acf_uid=1",
"cookie_updated_at": cookie_updated_at,
"ck_check_status": ck_status,
"ck_checked_at": cookie_updated_at,
"status": "active",
"auto_managed": True,
}
values.update(overrides)
return Account(**values)
def _user(db) -> User:
user = User(
username="lease-refresh-admin",
password_hash="h",
role="super_admin",
is_active=True,
)
db.add(user)
db.commit()
return user
def _lease(db, user: User, account: Account, *, purpose: str = "platform_fulfillment", status: str = "active") -> AccountLease:
lease = AccountLease(
account_id=account.id,
holder_user_id=user.id,
purpose=purpose,
status=status,
)
db.add(lease)
return lease
def test_select_due_lease_accounts_only_returns_valid_expiring_leases(db):
now = datetime.now(UTC).replace(microsecond=0)
user = _user(db)
due = _account("lease-due", cookie_updated_at=now - timedelta(days=6, hours=20))
due_collab = _account("lease-due-collab", cookie_updated_at=now - timedelta(days=6, hours=21))
fresh = _account("lease-fresh", cookie_updated_at=now - timedelta(days=1))
invalid = _account("lease-invalid", cookie_updated_at=now - timedelta(days=6, hours=20), ck_status="invalid")
no_lease = _account("lease-none", cookie_updated_at=now - timedelta(days=6, hours=20))
manual = _account("lease-manual", cookie_updated_at=now - timedelta(days=6, hours=20), auto_managed=False)
db.add_all([due, due_collab, fresh, invalid, no_lease, manual])
db.flush()
_lease(db, user, due)
_lease(db, user, due_collab, purpose="douyu_collab")
_lease(db, user, fresh)
_lease(db, user, invalid)
_lease(db, user, manual)
db.commit()
rows = lease_ck_refresh.select_due_lease_accounts(db, now=now, limit=10)
assert {row.id for row in rows} == {due.id, due_collab.id}
def test_select_due_lease_accounts_skips_released_lease(db):
now = datetime.now(UTC).replace(microsecond=0)
user = _user(db)
released = _account("lease-released", cookie_updated_at=now - timedelta(days=6, hours=20))
db.add(released)
db.flush()
_lease(db, user, released, status="released")
db.commit()
assert lease_ck_refresh.select_due_lease_accounts(db, now=now, limit=10) == []
def test_run_lease_ck_refresh_calls_login_for_selected_accounts(db, monkeypatch):
from web.backend.services.automation.jobs import lease_ck_refresh as job_module
now = datetime.now(UTC).replace(microsecond=0)
user = _user(db)
due = _account("lease-run-due", cookie_updated_at=now - timedelta(days=6, hours=20))
db.add(due)
db.flush()
_lease(db, user, due)
db.commit()
job = AutomationJob(
key=job_module.JOB_KEY,
title=job_module.TITLE,
enabled=True,
batch_size=10,
concurrency=3,
config={},
)
db.add(job)
db.commit()
calls: dict[str, object] = {}
def fake_run(db_session, **kwargs):
calls["db"] = db_session
calls["kwargs"] = kwargs
return SimpleNamespace(
success_ids=[due.id],
failed_ids=[],
skipped_ids=[],
fallback_used=False,
batch_ids=["lease-batch"],
fallback_batch_ids=[],
)
monkeypatch.setattr(job_module, "run_login_batch_with_fallback", fake_run)
result = job_module.run_lease_ck_refresh(db, job)
assert calls["kwargs"]["account_ids"] == [due.id]
assert calls["kwargs"]["mode"] == "login"
assert result["scanned"] == 1
assert result["success"] == 1
assert result["batchIds"] == ["lease-batch"]
+2
View File
@@ -10,6 +10,7 @@ import secrets
from pathlib import Path from pathlib import Path
from urllib.parse import quote_plus from urllib.parse import quote_plus
import pytest
from alembic import command from alembic import command
from alembic.config import Config from alembic.config import Config
from sqlalchemy import create_engine, text from sqlalchemy import create_engine, text
@@ -45,6 +46,7 @@ def _insert_task(conn, *, status: str, cookie: str, message: str = "") -> None:
) )
@pytest.mark.migration
class TestLoginAttemptMigration: class TestLoginAttemptMigration:
def setup_method(self): def setup_method(self):
creds = get_mysql_credentials() creds = get_mysql_credentials()
@@ -5,6 +5,7 @@ import secrets
from datetime import UTC, datetime from datetime import UTC, datetime
from urllib.parse import quote_plus from urllib.parse import quote_plus
import pytest
from alembic import command from alembic import command
from alembic.config import Config from alembic.config import Config
from sqlalchemy import create_engine, inspect, text from sqlalchemy import create_engine, inspect, text
@@ -15,6 +16,7 @@ from tests.support.db import get_mysql_credentials
TARGET_REVISION = "20261106_0065" TARGET_REVISION = "20261106_0065"
@pytest.mark.migration
def test_0065_upgrade_downgrade_roundtrip(): def test_0065_upgrade_downgrade_roundtrip():
creds = get_mysql_credentials() creds = get_mysql_credentials()
mig_db = f"douyu_login_mig_rt_{secrets.token_hex(4)}" mig_db = f"douyu_login_mig_rt_{secrets.token_hex(4)}"
+11 -1
View File
@@ -15,6 +15,7 @@ from datetime import UTC, datetime
from pathlib import Path from pathlib import Path
from urllib.parse import quote_plus from urllib.parse import quote_plus
import pytest
from alembic import command from alembic import command
from alembic.config import Config from alembic.config import Config
from alembic.script import ScriptDirectory from alembic.script import ScriptDirectory
@@ -44,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261124_0128" HEAD_REVISION = "20261124_0129"
# 迁移新增、但不声明在模型里的复合查询索引。 # 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = ( EXTRA_INDEXES = (
@@ -67,6 +68,11 @@ _ACCOUNT_PLATFORM_COLUMNS = {
"ck_observed_lifetime_seconds": "INTEGER NULL", "ck_observed_lifetime_seconds": "INTEGER NULL",
"ck_expiry_source": "VARCHAR(24) NOT NULL DEFAULT ''", "ck_expiry_source": "VARCHAR(24) NOT NULL DEFAULT ''",
"value_tier": "INTEGER NULL", "value_tier": "INTEGER NULL",
"role_change_official_at": "DATETIME NULL",
"last_bind_ok_at": "DATETIME NULL",
"role_bind_lock_until": "DATETIME NULL",
"role_change_checked_at": "DATETIME NULL",
"role_change_source": "VARCHAR(16) NULL",
} }
_LATER_ORM_COLUMNS = { _LATER_ORM_COLUMNS = {
@@ -127,6 +133,7 @@ def _migration_config() -> Config:
return config return config
@pytest.mark.migration
class TestMigrationSmoke: class TestMigrationSmoke:
def test_chain_is_linear_and_head_matches_latest_file(self): def test_chain_is_linear_and_head_matches_latest_file(self):
directory = ScriptDirectory.from_config(_migration_config()) directory = ScriptDirectory.from_config(_migration_config())
@@ -399,6 +406,7 @@ class TestMigrationSmoke:
cfg = _migration_config() cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url) cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0123") command.upgrade(cfg, "20261123_0123")
_add_account_platform_columns(mig_engine)
with Session(mig_engine) as session: with Session(mig_engine) as session:
user = User( user = User(
username="binding-sync-user", username="binding-sync-user",
@@ -490,6 +498,7 @@ class TestMigrationSmoke:
cfg = _migration_config() cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url) cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0125") command.upgrade(cfg, "20261123_0125")
_add_account_platform_columns(mig_engine)
with Session(mig_engine) as session: with Session(mig_engine) as session:
user = User( user = User(
username="false-binding-user", username="false-binding-user",
@@ -607,6 +616,7 @@ class TestMigrationSmoke:
cfg = _migration_config() cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url) cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0126") command.upgrade(cfg, "20261123_0126")
_add_account_platform_columns(mig_engine)
with Session(mig_engine) as session: with Session(mig_engine) as session:
user = User( user = User(
username="pending-link-user", username="pending-link-user",
+135
View File
@@ -3089,6 +3089,109 @@ class TestBindingAndCompletion(_Base):
== 1 == 1
) )
def test_operator_confirm_uses_scanned_role_without_form(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "旧角色"
account.role_bind_status = "bound"
qr_task = DouyuTask(
batch_id="operator-confirm-qr",
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={
"act_alias": "cjm",
"role_name": "新角色",
"current_role_name": "旧角色",
"baseline_role_name": "旧角色",
"action_act_aliases": ["20260120QYOOB"],
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
"bind_decision": {
"alias": "cjm",
"role_name": "新角色",
"reason": "role_changed",
"confirmable": True,
"actionable_alias": False,
},
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
detail = service.operator_confirm_binding_sync(
self.session,
task_id=task.id,
current=self.admin,
)
confirm_task = (
self.session.query(DouyuTask)
.filter_by(task_type="confirm_bind", platform_task_id=task.id)
.one()
)
assert confirm_task.result["expected_role_name"] == "新角色"
assert detail["task"]["bindingStatus"] in {"role_ready", "confirming"}
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_manually_confirmed")
.count()
== 0
)
def test_manual_confirm_rejects_role_not_currently_bound(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "小乖悄"
account.role_bind_status = "bound"
qr_task = DouyuTask(
batch_id="manual-mismatch-qr",
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={"bind_phase": "waiting_scan", "role_name": "等清晰"},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
with pytest.raises(HTTPException) as exc_info:
service.manual_confirm_binding_sync(
self.session,
task_id=task.id,
current=self.admin,
role_name="等清晰",
note="客户说角色是等清晰",
)
self.session.refresh(task)
assert exc_info.value.status_code == 409
assert "不一致" in str(exc_info.value.detail)
assert task.binding_status == "qr_pending"
assert task.execution_status == "waiting_bind"
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_manually_confirmed")
.count()
== 0
)
def test_cjm_only_new_role_enters_role_ready_for_customer_confirm(self): def test_cjm_only_new_role_enters_role_ready_for_customer_confirm(self):
task = self._allocated() task = self._allocated()
qr_task = DouyuTask( qr_task = DouyuTask(
@@ -4812,6 +4915,38 @@ class TestBindingAndCompletion(_Base):
assert result["expired"] == 0 assert result["expired"] == 0
assert task.execution_status == "allocated" assert task.execution_status == "allocated"
def test_reaper_releases_orphan_active_lease_from_task_retry(self):
task = self._allocated()
orphan_account = self.account("orphan-retry-account")
orphan_lease = AccountLease(
account_id=orphan_account.id,
holder_user_id=self.admin_id,
purpose="platform_fulfillment",
status="active",
batch_id=f"pf:{task.id}",
commodity_id=task.commodity_id,
)
self.session.add(orphan_lease)
self.session.commit()
job = AutomationJob(key=reaper.JOB_KEY, batch_size=100)
result = reaper.run_platform_fulfillment_lease_reaper(
self.session,
job,
now=NOW,
)
self.session.refresh(orphan_lease)
task_lease = (
self.session.query(AccountLease)
.filter(AccountLease.id == task.lease_id)
.one()
)
assert result["orphan_released"] == 1
assert orphan_lease.status == "released"
assert task_lease.status == "active"
assert task.account_id is not None
def test_expired_platform_lease_hands_off_to_active_collab(self): def test_expired_platform_lease_hands_off_to_active_collab(self):
task = self._allocated() task = self._allocated()
lease = self.session.query(AccountLease).one() lease = self.session.query(AccountLease).one()
@@ -513,6 +513,10 @@
"20261124_0128_account_supply_profiles.py": { "20261124_0128_account_supply_profiles.py": {
"revision": "20261124_0128", "revision": "20261124_0128",
"sha256": "4a95dfe1e6634cb318710423f8ab8d06321e09a7a58548bd3a159f3445f72ea7" "sha256": "4a95dfe1e6634cb318710423f8ab8d06321e09a7a58548bd3a159f3445f72ea7"
},
"20261124_0129_account_role_change_lock.py": {
"revision": "20261124_0129",
"sha256": "75b97c990e0c870add48073da26a9d2ac9ffd75ba1ffe477ae97268155cab42c"
} }
} }
} }
@@ -0,0 +1,98 @@
"""账号可换绑时间:官方时间、本地 7 天锁、有效时间与来源
背景:`accounts.role_change_available_at` 原来只存官方 `canChangeTime`,
而本地规则是「同一账号 7 天内只能绑一个精英角色」。两者不一致时,分配器
按官方时间选中了账号,真正绑定时才被 `binding_account_locked_elsewhere`
拦下(订单 2632801766531717 / 账号 23168:官方 11-24 00:00,本地锁 11-24 22:49)。
本迁移:
1. 新增 `role_change_official_at`、`last_bind_ok_at`、`role_bind_lock_until`、
`role_change_checked_at`、`role_change_source`;
2. 从 `account_events.bind_ok`(subject_type=elite_role)回填最近绑定时间;
3. `role_change_available_at` 改为「官方时间与本地锁取较晚者」;
4. 保留原 `role_change_available_at` 到 `role_change_official_at`。
可重跑:列存在性守卫;回填 SQL 幂等。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261124_0129"
down_revision: str | None = "20261124_0128"
branch_labels: str | None = None
depends_on: str | None = None
TABLE = "accounts"
COLUMNS = {
"role_change_official_at": sa.DateTime(),
"last_bind_ok_at": sa.DateTime(),
"role_bind_lock_until": sa.DateTime(),
"role_change_checked_at": sa.DateTime(),
"role_change_source": sa.String(length=16),
}
BACKFILL_SQL = """
UPDATE accounts a
LEFT JOIN (
SELECT account_id, MAX(occurred_at) AS last_bind_ok_at
FROM account_events
WHERE event_type = 'bind_ok'
AND subject_type = 'elite_role'
GROUP BY account_id
) e ON e.account_id = a.id
SET
a.role_change_official_at = COALESCE(
a.role_change_official_at,
a.role_change_available_at
),
a.last_bind_ok_at = e.last_bind_ok_at,
a.role_bind_lock_until = CASE
WHEN e.last_bind_ok_at IS NULL THEN NULL
ELSE DATE_ADD(e.last_bind_ok_at, INTERVAL 7 DAY)
END,
a.role_change_available_at = GREATEST(
COALESCE(a.role_change_official_at, a.role_change_available_at),
COALESCE(DATE_ADD(e.last_bind_ok_at, INTERVAL 7 DAY), a.role_change_available_at)
),
a.role_change_checked_at = UTC_TIMESTAMP(),
a.role_change_source = CASE
WHEN e.last_bind_ok_at IS NOT NULL THEN 'backfill'
ELSE COALESCE(a.role_change_source, 'official')
END
"""
def _column_exists(name: str) -> bool:
conn = op.get_bind()
count = conn.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()
return bool(count)
def upgrade() -> None:
for name, column_type in COLUMNS.items():
if not _column_exists(name):
op.add_column(TABLE, sa.Column(name, column_type, nullable=True))
op.execute(sa.text(BACKFILL_SQL))
def downgrade() -> None:
# 先恢复官方时间,再删除新增列;本地锁信息随列一起丢弃。
op.execute(
sa.text(
"UPDATE accounts SET role_change_available_at = "
"role_change_official_at WHERE role_change_official_at IS NOT NULL"
)
)
for name in reversed(tuple(COLUMNS)):
if _column_exists(name):
op.drop_column(TABLE, name)
+19
View File
@@ -173,6 +173,25 @@ class Account(Base):
role_change_available_at: Mapped[datetime | None] = mapped_column( role_change_available_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True UTCDateTime, nullable=True
) )
# 官方接口给出的可换绑时刻(canChangeTime / now+wait_time)。与下面的本地
# 7 天锁分开存:官方时间可能早于本地锁,不能直接用于分配。
role_change_official_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
# 最近一次精英 bind_ok 的业务发生时间,以及本地“一个账号 7 天只能绑一个角色”
# 的锁到期时间。分配只看 role_change_available_at(官方时间与本地锁取大)。
last_bind_ok_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
role_bind_lock_until: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
role_change_checked_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
role_change_source: Mapped[str | None] = mapped_column(
String(16), nullable=True
)
# 精英宝典当前有效开通状态(getUserInfo 的 manualType + expireTime)。 # 精英宝典当前有效开通状态(getUserInfo 的 manualType + expireTime)。
# manualType 只表示开过;写入时还要按 expireTime 判断是否已过期。 # manualType 只表示开过;写入时还要按 expireTime 判断是否已过期。
# 光看积分区分不了「开通后积分花完」和「从未开通」,必须单独落库。 # 光看积分区分不了「开通后积分花完」和「从未开通」,必须单独落库。
@@ -465,6 +465,29 @@ async def confirm_binding(
return result return result
@router.post("/tasks/{task_id}/bind/operator-confirm")
def operator_confirm_binding(
task_id: int,
db: Session = Depends(get_db),
current: User = Depends(require_permission("platform_fulfillment:use")),
) -> dict[str, Any]:
"""普通人工代确认:客户已扫码但没点确认,运营代为提交正常 actBind。"""
result = service.operator_confirm_binding_sync(
db,
task_id=task_id,
current=current,
)
record_audit(
db,
current,
action="platform_fulfillment:binding:operator_confirm",
target=f"platform_fulfillment_task:{task_id}",
detail={"bindingStatus": result.get("task", {}).get("bindingStatus")},
)
db.commit()
return result
@router.post("/tasks/{task_id}/bind/manual-confirm") @router.post("/tasks/{task_id}/bind/manual-confirm")
def manual_confirm_binding( def manual_confirm_binding(
task_id: int, task_id: int,
+27
View File
@@ -285,6 +285,33 @@ def role_change_available_at(
return None return None
#: 本地规则:同一斗鱼账号 7 天内只能绑定一个精英角色。
ROLE_BIND_LOCK = timedelta(days=7)
def role_bind_lock_until(last_bind_ok_at: datetime | None) -> datetime | None:
if last_bind_ok_at is None:
return None
return last_bind_ok_at + ROLE_BIND_LOCK
def effective_role_change_available_at(
*,
official_at: datetime | None,
last_bind_ok_at: datetime | None,
) -> datetime | None:
"""官方可换绑时间与本地 7 天锁取较晚者。
分配/人工选号只看这个结果;官方时间早于本地锁时,本地锁优先。
"""
candidates = [
value
for value in (official_at, role_bind_lock_until(last_bind_ok_at))
if value is not None
]
return max(candidates) if candidates else None
BindCooldownKind = Literal["platform", "customer"] BindCooldownKind = Literal["platform", "customer"]
@@ -22,6 +22,7 @@ from sqlalchemy.orm import Session
from ..models import ( from ..models import (
Account, Account,
AccountLease,
AutomationJob, AutomationJob,
DouyuExternalOrder, DouyuExternalOrder,
PlatformFulfillmentTask, PlatformFulfillmentTask,
@@ -55,6 +56,14 @@ GROUP_DEFINITIONS: dict[str, dict[str, Any]] = {
"probe_interval_minutes": DEFAULT_PROBE_INTERVAL_MINUTES, "probe_interval_minutes": DEFAULT_PROBE_INTERVAL_MINUTES,
"auto_relogin": True, "auto_relogin": True,
}, },
"lease_bound": {
"label": "生效租约账号",
"description": "当前所有生效的直播履约/协作租约账号,优先 CK 巡检和到期前刷新",
"enabled": True,
"target_count": 0,
"probe_interval_minutes": 240,
"auto_relogin": True,
},
} }
@@ -136,6 +145,19 @@ def _collab_account_ids(db: Session) -> set[int]:
return {int(row[0]) for row in rows if row[0] is not None} return {int(row[0]) for row in rows if row[0] is not None}
def _lease_account_ids(db: Session) -> set[int]:
rows = (
db.query(AccountLease.account_id)
.filter(
AccountLease.status == "active",
AccountLease.purpose.in_(("platform_fulfillment", "douyu_collab")),
)
.distinct()
.all()
)
return {int(row[0]) for row in rows if row[0] is not None}
@dataclass(frozen=True) @dataclass(frozen=True)
class ProtectionSnapshot: class ProtectionSnapshot:
groups: dict[str, dict[str, Any]] groups: dict[str, dict[str, Any]]
@@ -189,6 +211,7 @@ def load_protection_snapshot(
group_account_ids={ group_account_ids={
"presale_bound": frozenset(_presale_account_ids(db)), "presale_bound": frozenset(_presale_account_ids(db)),
"collab_bound": frozenset(_collab_account_ids(db)), "collab_bound": frozenset(_collab_account_ids(db)),
"lease_bound": frozenset(_lease_account_ids(db)),
}, },
) )
+24 -1
View File
@@ -9,6 +9,7 @@ from sqlalchemy import and_, func, or_, select
from ..models import ( from ..models import (
Account, Account,
AccountCommodityState, AccountCommodityState,
AccountEvent,
AccountLease, AccountLease,
DouyuExternalOrder, DouyuExternalOrder,
LoginTask, LoginTask,
@@ -121,10 +122,31 @@ def active_collab_order_exists():
) )
def recent_elite_bind_lock_exists(now: datetime):
"""本地 7 天规则:最近 7 天有精英 bind_ok 的账号不能再接新角色。
这是 `role_change_available_at` 的数据库兜底:即使字段回填/写入有遗漏,
分配前也不会选中一个刚绑定过的账号。
"""
return (
select(AccountEvent.id)
.where(
AccountEvent.account_id == Account.id,
AccountEvent.event_type == "bind_ok",
AccountEvent.subject_type == "elite_role",
AccountEvent.occurred_at > now - timedelta(days=7),
)
.exists()
)
def role_change_ready_filter(now: datetime): def role_change_ready_filter(now: datetime):
return or_( return and_(
or_(
Account.role_change_available_at.is_(None), Account.role_change_available_at.is_(None),
Account.role_change_available_at <= now, Account.role_change_available_at <= now,
),
~recent_elite_bind_lock_exists(now),
) )
@@ -167,6 +189,7 @@ __all__ = [
"fresh_ck_cutoff", "fresh_ck_cutoff",
"fresh_eligible_state_filter", "fresh_eligible_state_filter",
"pool_owner_ids", "pool_owner_ids",
"recent_elite_bind_lock_exists",
"role_change_ready_filter", "role_change_ready_filter",
"valid_ck_filter", "valid_ck_filter",
] ]
@@ -52,6 +52,8 @@ from .jobs.douyu_tasks_retention import (
from .jobs.douyu_tasks_retention import ( from .jobs.douyu_tasks_retention import (
run_douyu_tasks_retention, run_douyu_tasks_retention,
) )
from .jobs.lease_ck_refresh import JOB_KEY as LEASE_CK_REFRESH_KEY
from .jobs.lease_ck_refresh import run_lease_ck_refresh
from .jobs.platform_fulfillment_lease_reaper import ( from .jobs.platform_fulfillment_lease_reaper import (
JOB_KEY as PLATFORM_FULFILLMENT_LEASE_REAPER_KEY, JOB_KEY as PLATFORM_FULFILLMENT_LEASE_REAPER_KEY,
) )
@@ -84,6 +86,7 @@ __all__ = [
"CK_HEALTH_KEY", "CK_HEALTH_KEY",
"CK_RELOGIN_KEY", "CK_RELOGIN_KEY",
"DOUYU_TASKS_RETENTION_KEY", "DOUYU_TASKS_RETENTION_KEY",
"LEASE_CK_REFRESH_KEY",
"PLATFORM_FULFILLMENT_LEASE_REAPER_KEY", "PLATFORM_FULFILLMENT_LEASE_REAPER_KEY",
"POINTS_EXPIRE_KEY", "POINTS_EXPIRE_KEY",
"JobSpec", "JobSpec",
@@ -104,6 +107,7 @@ __all__ = [
"run_douyu_tasks_retention", "run_douyu_tasks_retention",
"run_due_jobs", "run_due_jobs",
"run_job_now", "run_job_now",
"run_lease_ck_refresh",
"run_platform_fulfillment_lease_reaper", "run_platform_fulfillment_lease_reaper",
"run_points_expire_check", "run_points_expire_check",
"scheduler_status", "scheduler_status",
@@ -226,6 +230,20 @@ def register_default_jobs() -> None:
run=run_ck_relogin, run=run_ck_relogin,
) )
) )
register_job(
JobSpec(
key=LEASE_CK_REFRESH_KEY,
title="租约 CK 到期前刷新",
# 只处理仍有效、但预测 24h 内到期的生效租约账号;提前续 CK,
# 不参与普通失效重登的批次。
interval_seconds=600,
run_interval_seconds=600,
batch_size=10,
concurrency=3,
run=run_lease_ck_refresh,
default_enabled=True,
)
)
register_job( register_job(
JobSpec( JobSpec(
key=CK_HEALTH_KEY, key=CK_HEALTH_KEY,
@@ -9,7 +9,7 @@ from sqlalchemy import func, or_, select
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from ....models import Account, AutomationJob, LoginTask from ....models import Account, AutomationJob, LoginTask
from ...account_lifecycle import MANUAL_STATES, STATUS_MANUAL from ...account_lifecycle import MANUAL_KINDS, MANUAL_STATES, STATUS_MANUAL
from ...login_automation import run_login_batch_with_fallback, system_user_id from ...login_automation import run_login_batch_with_fallback, system_user_id
JOB_KEY = "account_onboarding" JOB_KEY = "account_onboarding"
@@ -38,6 +38,13 @@ def build_select_query(
.filter( .filter(
Account.auto_managed.is_(True), Account.auto_managed.is_(True),
Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)), Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)),
# 缺账号/密码的账号首登必失败,不能占样本名额。
Account.username != "",
Account.password != "",
# 已经判定为极验/凭证问题的账号不再自动首登。
func.coalesce(Account.relogin_failure_kind, "").notin_(
tuple(sorted(MANUAL_KINDS))
),
or_(Account.cookie.is_(None), Account.cookie == ""), or_(Account.cookie.is_(None), Account.cookie == ""),
~_in_flight_login_exists(), ~_in_flight_login_exists(),
) )
@@ -53,6 +60,11 @@ def count_pending_onboarding(db: Session) -> int:
.filter( .filter(
Account.auto_managed.is_(True), Account.auto_managed.is_(True),
Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)), Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)),
Account.username != "",
Account.password != "",
func.coalesce(Account.relogin_failure_kind, "").notin_(
tuple(sorted(MANUAL_KINDS))
),
or_(Account.cookie.is_(None), Account.cookie == ""), or_(Account.cookie.is_(None), Account.cookie == ""),
~_in_flight_login_exists(), ~_in_flight_login_exists(),
) )
@@ -0,0 +1,170 @@
"""租约账号 CK 到期前刷新(P1)。
`ck_relogin` 只处理已经 `ck_check_status=invalid` 的账号;但租约账号如果等到
失效再重登,履约期间会出现一段不可用窗口。这个作业专门在 CK **预测到期前
24 小时**,对仍持有有效 CK 的生效租约账号做一次主动登录,延长 CK 生命周期。
范围:
- `account_leases.status=active` 且 purpose 为 `platform_fulfillment` / `douyu_collab`;
- `ck_check_status=valid`、有 Cookie、可自动管理、没有在途登录;
- 预测到期时间 <= now + 24h(`ck_expected_expires_at` 或 `cookie_updated_at + 7d`);
- 失败分型为人工的账号、仍在退避窗口内的账号不碰。
作业只负责“提前续 CK”,不替代 `ck_relogin` 的失效重登;两者共用登录配额和
登录任务审计。
"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import func, or_
from sqlalchemy.orm import Session
from ....models import Account, AccountLease, AutomationJob, User
from ...account_lifecycle import DEFAULT_CK_LIFETIME, MANUAL_KINDS
from ...account_query_filters import automation_account_filter
from ...login_automation import run_login_batch_with_fallback
JOB_KEY = "lease_ck_refresh"
TITLE = "租约 CK 到期前刷新"
REFRESH_BEFORE = timedelta(hours=24)
def _system_user_id(db: Session) -> int | None:
row = (
db.query(User.id)
.filter(User.role == "super_admin")
.order_by(User.id.asc())
.first()
)
if row:
return int(row[0])
row = db.query(User.id).order_by(User.id.asc()).first()
return int(row[0]) if row else None
def due_lease_account_query(
db: Session,
now: datetime | None = None,
):
"""到期前 24h 的租约账号查询(执行和测试共用)。"""
moment = now or datetime.now(UTC)
cutoff = moment + REFRESH_BEFORE
return (
db.query(Account)
.join(AccountLease, AccountLease.account_id == Account.id)
.filter(
AccountLease.status == "active",
AccountLease.purpose.in_(("platform_fulfillment", "douyu_collab")),
Account.ck_check_status == "valid",
Account.cookie_updated_at.isnot(None),
automation_account_filter(cookie_operable=True),
func.coalesce(Account.relogin_failure_kind, "").notin_(
tuple(sorted(MANUAL_KINDS))
),
or_(
Account.ck_expected_expires_at <= cutoff,
Account.cookie_updated_at <= cutoff - DEFAULT_CK_LIFETIME,
),
or_(
Account.relogin_next_at.is_(None),
Account.relogin_next_at <= moment,
),
)
.order_by(Account.cookie_updated_at.asc(), Account.id.asc())
)
def select_due_lease_accounts(
db: Session,
*,
now: datetime | None = None,
limit: int = 10,
) -> list[Account]:
return due_lease_account_query(db, now=now).limit(max(1, int(limit))).all()
def run_lease_ck_refresh(db: Session, job: AutomationJob) -> dict[str, Any]:
now = datetime.now(UTC)
system_user_id = _system_user_id(db)
if system_user_id is None:
return {
"scanned": 0,
"success": 0,
"failed": 0,
"message": "库里没有可用用户,无法以系统身份发起租约 CK 刷新",
}
batch_size = max(1, int(job.batch_size or 10))
accounts = select_due_lease_accounts(db, now=now, limit=batch_size)
if not accounts:
return {
"scanned": 0,
"success": 0,
"failed": 0,
"message": "没有 24h 内到期的租约账号需要刷新",
}
account_ids = [int(account.id) for account in accounts]
outcome = run_login_batch_with_fallback(
db,
account_ids=account_ids,
mode="login",
created_by=system_user_id,
concurrency=max(1, min(int(job.concurrency or 3), 8)),
max_total_time=240,
)
_settle_outcome(accounts, outcome, now=now)
db.commit()
retry = len(outcome.failed_ids) - _manual_count(outcome)
return {
"scanned": len(account_ids),
"success": len(outcome.success_ids),
"failed": len(outcome.failed_ids),
"retry": max(0, retry),
"manual": _manual_count(outcome),
"skipped": len(outcome.skipped_ids),
"fallbackUsed": outcome.fallback_used,
"batchIds": list(outcome.batch_ids) + list(outcome.fallback_batch_ids),
"message": (
f"租约 CK 到期前刷新 {len(account_ids)} 条,"
f"成功 {len(outcome.success_ids)},失败 {len(outcome.failed_ids)}"
),
}
def _manual_count(outcome) -> int:
return sum(
1
for account_id in outcome.failed_ids
if outcome.failure_kinds.get(account_id) in MANUAL_KINDS
)
def _settle_outcome(accounts: list[Account], outcome, *, now: datetime) -> None:
"""成功清退避,失败按类型设置下次重试,避免每 10 分钟撞一次。"""
by_id = {int(account.id): account for account in accounts}
for account_id in outcome.success_ids:
account = by_id.get(int(account_id))
if account is None:
continue
account.relogin_failure_kind = ""
account.relogin_last_error = ""
account.relogin_attempts = 0
account.relogin_next_at = None
for account_id in outcome.failed_ids:
account = by_id.get(int(account_id))
if account is None:
continue
kind = str(outcome.failure_kinds.get(account_id) or "unknown")
account.relogin_failure_kind = kind
account.relogin_attempts = int(account.relogin_attempts or 0) + 1
if kind in MANUAL_KINDS:
account.relogin_next_at = None
elif kind == "email_quota":
account.relogin_next_at = now + timedelta(hours=12)
else:
account.relogin_next_at = now + timedelta(hours=1)
@@ -10,6 +10,7 @@ from sqlalchemy.orm import Session
from ....models import Account, AccountLease, AutomationJob, PlatformFulfillmentTask from ....models import Account, AccountLease, AutomationJob, PlatformFulfillmentTask
from ...platform_fulfillment.account_selector import ( from ...platform_fulfillment.account_selector import (
expire_platform_fulfillment_leases, expire_platform_fulfillment_leases,
release_lease,
) )
from ...platform_fulfillment.service import binding_failed_lease_ttl_minutes from ...platform_fulfillment.service import binding_failed_lease_ttl_minutes
@@ -93,6 +94,44 @@ def run_platform_fulfillment_lease_reaper(
if task is not None: if task is not None:
converted_tasks[int(task.id)] = task converted_tasks[int(task.id)] = task
# 分配并发/重试可能留下「batch_id 指向 task,但 task 实际用另一个账号/租约」
# 的孤儿 active 租约。它不会自然过期(expires_at 常为 NULL),会永久占住账号,
# 并让协作单接管时报“任务与租约不一致”。这里按 task 的真实归属回收。
orphan_leases = (
db.query(AccountLease)
.filter(
AccountLease.purpose == "platform_fulfillment",
AccountLease.status == "active",
AccountLease.batch_id.like("pf:%"),
)
.order_by(AccountLease.id.asc())
.limit(max(1, int(job.batch_size or 500)))
.all()
)
orphan_released = 0
for lease in orphan_leases:
try:
task_id = int(str(lease.batch_id).removeprefix("pf:"))
except ValueError:
task_id = 0
task = (
db.get(PlatformFulfillmentTask, task_id) if task_id else None
)
if (
task is not None
and task.account_id == lease.account_id
and task.lease_id == lease.id
):
continue
if release_lease(
db,
lease,
reason="lease_task_mismatch",
now=moment,
commit=False,
):
orphan_released += 1
expired = expire_platform_fulfillment_leases( expired = expire_platform_fulfillment_leases(
db, db,
now=moment, now=moment,
@@ -126,14 +165,15 @@ def run_platform_fulfillment_lease_reaper(
task.last_error = "账号租约已过期,请重新分配账号" task.last_error = "账号租约已过期,请重新分配账号"
task.updated_at = moment task.updated_at = moment
affected += 1 affected += 1
if released_ids or converted_tasks: if released_ids or converted_tasks or orphan_released:
db.commit() db.commit()
return { return {
"scanned": expired, "scanned": expired + orphan_released,
"expired": expired, "expired": expired,
"orphan_released": orphan_released,
"stale_binding_recovered": len(stale_binding_leases), "stale_binding_recovered": len(stale_binding_leases),
"affected_tasks": affected, "affected_tasks": affected,
"message": f"直播账号履约租约回收 {expired} 条", "message": f"直播账号履约租约回收 {expired + orphan_released} 条",
} }
+19 -2
View File
@@ -30,13 +30,17 @@
from __future__ import annotations from __future__ import annotations
from datetime import datetime from datetime import UTC, datetime
from typing import Any from typing import Any
from loguru import logger from loguru import logger
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from ..models import Account from ..models import Account
from .account_binding import (
effective_role_change_available_at,
role_bind_lock_until,
)
from .account_events_service import ( from .account_events_service import (
CATEGORY_ACTIVITY, CATEGORY_ACTIVITY,
CATEGORY_BUSINESS, CATEGORY_BUSINESS,
@@ -467,7 +471,7 @@ def record_bind(
title += f":{role_name}" title += f":{role_name}"
if weak: if weak:
title += "(未回查确认)" title += "(未回查确认)"
return emit( emitted = emit(
db, db,
account_id=account.id, account_id=account.id,
event_type=EVENT_BIND_OK, event_type=EVENT_BIND_OK,
@@ -488,6 +492,19 @@ def record_bind(
actor_id=actor_id, actor_id=actor_id,
source_ref=task_ref(task_id), source_ref=task_ref(task_id),
) )
if scope == "elite":
# 本地 7 天锁:绑定事实发生即生效,不能等下一次官方查询。
moment = occurred_at or datetime.now(UTC)
if account.last_bind_ok_at is None or moment > account.last_bind_ok_at:
account.last_bind_ok_at = moment
account.role_bind_lock_until = role_bind_lock_until(moment)
account.role_change_available_at = effective_role_change_available_at(
official_at=account.role_change_official_at,
last_bind_ok_at=account.last_bind_ok_at,
)
account.role_change_checked_at = datetime.now(UTC)
account.role_change_source = "local_bind"
return emitted
def record_official_exchange( def record_official_exchange(
+8 -2
View File
@@ -32,6 +32,7 @@ from .account_binding import (
binding_pending_decision, binding_pending_decision,
binding_snapshot, binding_snapshot,
derive_from_bind_info, derive_from_bind_info,
effective_role_change_available_at,
is_bound_act, is_bound_act,
role_change_available_at, role_change_available_at,
set_bind_status, set_bind_status,
@@ -1011,9 +1012,14 @@ def _apply_role_result(
account.game_name = role_name account.game_name = role_name
account.game_channel = channel account.game_channel = channel
account.change_role_wait_time = _to_int(role.get("change_role_wait_time")) account.change_role_wait_time = _to_int(role.get("change_role_wait_time"))
account.role_change_available_at = role_change_available_at( official_at = role_change_available_at(role.get("bind_info"))
role.get("bind_info") account.role_change_official_at = official_at
account.role_change_checked_at = datetime.now(UTC)
account.role_change_available_at = effective_role_change_available_at(
official_at=official_at,
last_bind_ok_at=account.last_bind_ok_at,
) )
account.role_change_source = "official"
elif scope == SCOPE_ESPORTS: elif scope == SCOPE_ESPORTS:
account.esports_game_name = role_name account.esports_game_name = role_name
account.esports_game_channel = channel account.esports_game_channel = channel
+9 -1
View File
@@ -22,6 +22,7 @@ from .account_binding import (
binding_pending_decision, binding_pending_decision,
binding_snapshot, binding_snapshot,
classify_bind_cooldown, classify_bind_cooldown,
effective_role_change_available_at,
is_bound_act, is_bound_act,
is_pending_binding_role, is_pending_binding_role,
is_role_change_cooling, is_role_change_cooling,
@@ -408,7 +409,14 @@ class BindMixin:
snapshot["game_channel"].replace(" / ", " · ") or account.game_channel snapshot["game_channel"].replace(" / ", " · ") or account.game_channel
) )
account.change_role_wait_time = snapshot["change_role_wait_time"] account.change_role_wait_time = snapshot["change_role_wait_time"]
account.role_change_available_at = role_change_available_at(bind_info) official_at = role_change_available_at(bind_info)
account.role_change_official_at = official_at
account.role_change_checked_at = datetime.now(UTC)
account.role_change_available_at = effective_role_change_available_at(
official_at=official_at,
last_bind_ok_at=account.last_bind_ok_at,
)
account.role_change_source = "official"
if state is not None: if state is not None:
set_bind_status(account, SCOPE_ELITE, state) set_bind_status(account, SCOPE_ELITE, state)
account.updated_at = datetime.now(UTC) account.updated_at = datetime.now(UTC)
@@ -48,6 +48,7 @@ from .account_selector import (
capability_candidate_rows, capability_candidate_rows,
capability_refresh_candidate_accounts, capability_refresh_candidate_accounts,
lease_account, lease_account,
release_lease,
) )
from .common import ( from .common import (
DEFAULT_CAPABILITY_CANDIDATE_LIMIT, DEFAULT_CAPABILITY_CANDIDATE_LIMIT,
@@ -61,7 +62,7 @@ from .common import (
_now, _now,
) )
from .outbox import _emit_order_site_binding_state from .outbox import _emit_order_site_binding_state
from .repository import _load_task from .repository import _load_task, _load_task_for_update
from .runtime import ( from .runtime import (
_append_event, _append_event,
_apply_task_lease_policy, _apply_task_lease_policy,
@@ -329,6 +330,18 @@ def _allocate_task_from_capability(
current: User, current: User,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""只用本地能力索引选号;外部资格查询留给独立同步队列。""" """只用本地能力索引选号;外部资格查询留给独立同步队列。"""
# 同一任务并发点击/调度重试时,先在任务行上加锁。否则两个请求会各自
# 领到一个账号租约,后提交的一方覆盖 task.lease_id,先前的 active 租约
# 就变成孤儿(生产 7482/8877 就是这么来的)。
task = _load_task_for_update(db, int(task.id))
if task.account_id and task.lease_id:
current_lease = (
db.query(AccountLease)
.filter(AccountLease.id == int(task.lease_id))
.first()
)
if current_lease is not None and current_lease.status == "active":
return get_task_detail(db, task.id)
moment = _now() moment = _now()
required_points = int(task.required_points or 0) required_points = int(task.required_points or 0)
try: try:
@@ -511,6 +524,23 @@ def _allocate_task_from_capability(
return get_task_detail(db, task.id) return get_task_detail(db, task.id)
selected_account = selected.account selected_account = selected.account
stale_leases = (
db.query(AccountLease)
.filter(
AccountLease.status == "active",
AccountLease.batch_id == f"pf:{int(task.id)}",
AccountLease.id != int(lease.id),
)
.with_for_update()
.all()
)
for stale in stale_leases:
release_lease(
db,
stale,
reason="allocation_replaced",
commit=False,
)
task.account_id = selected_account.id task.account_id = selected_account.id
task.lease_id = lease.id task.lease_id = lease.id
task.operator_id = current.id task.operator_id = current.id
@@ -598,6 +598,35 @@ def _mark_reused_pair(
return True return True
def operator_confirm_binding_sync(
db: Session,
*,
task_id: int,
current: User,
) -> dict[str, Any]:
"""普通人工代确认:客户已扫码但没点确认,运营代为提交正常 actBind。
不填写角色/备注,不直接标 bound;复用客户确认的同一套确认任务。
当前没有可确认的扫码角色时,要求客户扫码或走“强制确认”。
"""
task = _load_task_for_update(db, task_id)
if _frozen(task):
return get_task_detail(db, task.id)
refresh_binding(db, task_id=task.id)
task = _load_task(db, task.id)
if task.binding_status == "bound":
return get_task_detail(db, task.id)
if task.binding_status != "role_ready":
raise HTTPException(
status_code=409,
detail=(
"当前没有可代确认的扫码角色。请让客户先扫码;"
"只有账号已绑定到该角色、但缺少本次扫码证据时,才使用强制确认。"
),
)
return confirm_binding_sync(db, task_id=task.id, current=current)
def manual_confirm_binding_sync( def manual_confirm_binding_sync(
db: Session, db: Session,
*, *,
@@ -629,7 +658,24 @@ def manual_confirm_binding_sync(
status_code=409, status_code=409,
detail="账号没有可确认的角色,请先查询角色或填写确认角色", detail="账号没有可确认的角色,请先查询角色或填写确认角色",
) )
account_role = str(account.game_name or "").strip()
if str(account.role_bind_status or "") != "bound" or not account_role:
raise HTTPException(
status_code=409,
detail="账号当前没有已生效角色,不能人工确认;请先刷新/查询角色",
)
if account_role != confirmed_role:
raise HTTPException(
status_code=409,
detail=(
f"账号当前角色是「{account_role}」,确认角色是「{confirmed_role}」,"
"不一致,不能人工确认。人工确认只能用于账号已经绑定到该角色的场景;"
"换绑请先完成 actBind 或使用正确账号。"
),
)
note = str(note or "").strip()[:500] note = str(note or "").strip()[:500]
if len(note) < 2:
raise HTTPException(status_code=409, detail="请填写人工确认依据/备注")
previous_binding = str(task.binding_status or "") previous_binding = str(task.binding_status or "")
previous_execution = str(task.execution_status or "") previous_execution = str(task.execution_status or "")
@@ -30,6 +30,7 @@ from .binding import ( # noqa: F401
confirm_binding, confirm_binding,
confirm_binding_sync, confirm_binding_sync,
manual_confirm_binding_sync, manual_confirm_binding_sync,
operator_confirm_binding_sync,
reconcile_binding_observations, reconcile_binding_observations,
reconcile_binding_state_outbox, reconcile_binding_state_outbox,
refresh_binding, refresh_binding,
@@ -156,6 +157,7 @@ __all__ = [
"manual_confirm_binding_sync", "manual_confirm_binding_sync",
"mapping_impact", "mapping_impact",
"mark_manual_required", "mark_manual_required",
"operator_confirm_binding_sync",
"prepare_manual_allocation", "prepare_manual_allocation",
"prepare_platform_task_for_collab_takeover", "prepare_platform_task_for_collab_takeover",
"reconcile_binding_observations", "reconcile_binding_observations",
@@ -137,6 +137,10 @@ export const platformFulfillmentApi = {
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>( api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
`/platform-fulfillment/tasks/${taskId}/bind/confirm`, `/platform-fulfillment/tasks/${taskId}/bind/confirm`,
), ),
operatorConfirmBinding: (taskId: number) =>
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
`/platform-fulfillment/tasks/${taskId}/bind/operator-confirm`,
),
manualConfirmBinding: (taskId: number, roleName: string, note: string) => manualConfirmBinding: (taskId: number, roleName: string, note: string) =>
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>( api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
`/platform-fulfillment/tasks/${taskId}/bind/manual-confirm`, `/platform-fulfillment/tasks/${taskId}/bind/manual-confirm`,
+1 -1
View File
@@ -802,7 +802,7 @@ export interface DouyuSupplyTargetUpdate {
} }
export interface DouyuAccountProtectionTarget { export interface DouyuAccountProtectionTarget {
group_key: 'presale_bound' | 'collab_bound'; group_key: 'presale_bound' | 'collab_bound' | 'lease_bound';
label: string; label: string;
description: string; description: string;
enabled: boolean; enabled: boolean;
@@ -118,6 +118,12 @@ const JOB_UI: Record<string, JobUiSpec> = {
showRecheck: false, showRecheck: false,
showConcurrency: false, showConcurrency: false,
}, },
lease_ck_refresh: {
description: "对仍有效、但预测 24 小时内到期的生效租约账号提前登录续 CK;只处理 platform_fulfillment / douyu_collab 租约。",
core: true,
showRecheck: false,
showConcurrency: true,
},
account_onboarding: { account_onboarding: {
description: "对没有 CK 的未登录账号执行首次真实登录;成功后写入 CK 并联动商品能力同步。默认关闭,建议先小批量。", description: "对没有 CK 的未登录账号执行首次真实登录;成功后写入 CK 并联动商品能力同步。默认关闭,建议先小批量。",
core: true, core: true,
+252 -125
View File
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs'; import type { Dayjs } from 'dayjs';
import { Alert, Button, Card, Col, DatePicker, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Row, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd'; import { Alert, Button, Card, Col, DatePicker, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Row, Segmented, Select, Space, Switch, Table, Tag, Timeline, Typography } from 'antd';
import { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, DownloadOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons'; import { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, DownloadOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { douyuApi, platformFulfillmentApi } from '../api/modules'; import { douyuApi, platformFulfillmentApi } from '../api/modules';
@@ -95,14 +95,6 @@ const SALE_MODE_LABELS: Record<string, string> = {
unknown: '未分类', unknown: '未分类',
}; };
const AVAILABILITY_LABELS: Record<string, string> = {
waiting_release: '待开放',
available: '可兑换',
sold_out: '已售罄',
ended: '已结束',
unknown: '未知',
};
const MANUAL_REASON_LABELS: Record<string, string> = { const MANUAL_REASON_LABELS: Record<string, string> = {
points_short: '积分不足', points_short: '积分不足',
elite_not_opened: '宝典未开通', elite_not_opened: '宝典未开通',
@@ -466,6 +458,13 @@ export default function PlatformFulfillmentPage() {
const [manualBindRole, setManualBindRole] = useState(''); const [manualBindRole, setManualBindRole] = useState('');
const [manualBindNote, setManualBindNote] = useState(''); const [manualBindNote, setManualBindNote] = useState('');
const [manualBinding, setManualBinding] = useState(false); const [manualBinding, setManualBinding] = useState(false);
const manualBindCurrentRole =
manualBindTarget?.bindingEvidence?.accountCurrentRole || '';
const manualBindMismatch = Boolean(
manualBindCurrentRole &&
manualBindRole.trim() &&
manualBindRole.trim() !== manualBindCurrentRole,
);
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]); const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
const [selectedId, setSelectedId] = useState<number | null>(null); const [selectedId, setSelectedId] = useState<number | null>(null);
const [detail, setDetail] = useState<PlatformFulfillmentDetail | null>(null); const [detail, setDetail] = useState<PlatformFulfillmentDetail | null>(null);
@@ -475,6 +474,9 @@ export default function PlatformFulfillmentPage() {
const [bindingQrImage, setBindingQrImage] = useState(''); const [bindingQrImage, setBindingQrImage] = useState('');
const [bindingQrLoading, setBindingQrLoading] = useState(false); const [bindingQrLoading, setBindingQrLoading] = useState(false);
const [mappingOpen, setMappingOpen] = useState(false); const [mappingOpen, setMappingOpen] = useState(false);
const [mappingEditorOpen, setMappingEditorOpen] = useState(false);
const [mappingSaving, setMappingSaving] = useState(false);
const [mappingKeyword, setMappingKeyword] = useState('');
const [mappingSku, setMappingSku] = useState(''); const [mappingSku, setMappingSku] = useState('');
const [mappingEditingId, setMappingEditingId] = useState<number | null>(null); const [mappingEditingId, setMappingEditingId] = useState<number | null>(null);
const [mappingCampaignKey, setMappingCampaignKey] = useState('douyu-current'); const [mappingCampaignKey, setMappingCampaignKey] = useState('douyu-current');
@@ -860,6 +862,10 @@ export default function PlatformFulfillmentPage() {
message.warning('请填写客户确认的游戏角色'); message.warning('请填写客户确认的游戏角色');
return; return;
} }
if (manualBindCurrentRole && role !== manualBindCurrentRole) {
message.error(`账号当前角色是「${manualBindCurrentRole}」,不能人工确认「${role}」`);
return;
}
if (note.length < 2) { if (note.length < 2) {
message.warning('请填写人工确认依据/备注'); message.warning('请填写人工确认依据/备注');
return; return;
@@ -885,6 +891,18 @@ export default function PlatformFulfillmentPage() {
} }
}; };
const submitOperatorConfirm = async (task: PlatformFulfillmentTask) => {
try {
const result = await platformFulfillmentApi.operatorConfirmBinding(task.id);
setDetail(result);
setSelectedId(result.task.id);
await loadTasks();
message.success('已代客户提交确认,等待绑定结果');
} catch (error) {
message.error(getErrorMessage(error));
}
};
const runDouyuAccountAction = async (taskType: string) => { const runDouyuAccountAction = async (taskType: string) => {
if (!selected?.account) { if (!selected?.account) {
message.warning('当前履约任务还没有分配斗鱼账号'); message.warning('当前履约任务还没有分配斗鱼账号');
@@ -997,7 +1015,7 @@ export default function PlatformFulfillmentPage() {
}; };
const loadMappingRows = async ( const loadMappingRows = async (
keyword = mappingSku.trim(), keyword = mappingKeyword.trim(),
mode = mappingFilterMode, mode = mappingFilterMode,
includeArchived = mappingIncludeArchived, includeArchived = mappingIncludeArchived,
) => { ) => {
@@ -1012,12 +1030,15 @@ export default function PlatformFulfillmentPage() {
const openMapping = async (task?: PlatformFulfillmentTask) => { const openMapping = async (task?: PlatformFulfillmentTask) => {
resetMappingForm(task); resetMappingForm(task);
setMappingOpen(true); setMappingOpen(true);
if (task) setMappingEditorOpen(true);
setMappingGoodsLoading(true); setMappingGoodsLoading(true);
try { try {
const keyword = task?.internalSkuKey || '';
setMappingKeyword(keyword);
const [goodsRows, mappingRows] = await Promise.all([ const [goodsRows, mappingRows] = await Promise.all([
douyuApi.listLiveGoods(), douyuApi.listLiveGoods(),
platformFulfillmentApi.listMappings({ platformFulfillmentApi.listMappings({
keyword: task?.internalSkuKey || '', keyword,
sale_mode: mappingFilterMode || undefined, sale_mode: mappingFilterMode || undefined,
include_archived: mappingIncludeArchived, include_archived: mappingIncludeArchived,
}), }),
@@ -1034,7 +1055,13 @@ export default function PlatformFulfillmentPage() {
} }
}; };
const openMappingCreate = () => {
resetMappingForm();
setMappingEditorOpen(true);
};
const editMapping = (row: PlatformFulfillmentMapping) => { const editMapping = (row: PlatformFulfillmentMapping) => {
setMappingEditorOpen(true);
setMappingEditingId(row.id); setMappingEditingId(row.id);
setMappingSku(row.internalSkuKey); setMappingSku(row.internalSkuKey);
setMappingCampaignKey(row.campaignKey || 'douyu-current'); setMappingCampaignKey(row.campaignKey || 'douyu-current');
@@ -1118,6 +1145,7 @@ export default function PlatformFulfillmentPage() {
}; };
const saveMapping = async () => { const saveMapping = async () => {
if (mappingSaving) return;
if (!mappingSku.trim() || !mappingCampaignKey.trim() || !mappingGoodsId || !mappingSaleMode) { if (!mappingSku.trim() || !mappingCampaignKey.trim() || !mappingGoodsId || !mappingSaleMode) {
message.warning('请填写内部 SKU、活动批次、销售模式并选择斗鱼商品'); message.warning('请填写内部 SKU、活动批次、销售模式并选择斗鱼商品');
return; return;
@@ -1140,17 +1168,21 @@ export default function PlatformFulfillmentPage() {
available_until: mappingAvailableUntil?.toISOString() || null, available_until: mappingAvailableUntil?.toISOString() || null,
enabled: mappingEnabled, enabled: mappingEnabled,
}; };
setMappingSaving(true);
if (mappingEditingId) { if (mappingEditingId) {
await platformFulfillmentApi.updateMapping(mappingEditingId, payload); await platformFulfillmentApi.updateMapping(mappingEditingId, payload);
} else { } else {
await platformFulfillmentApi.createMapping(payload); await platformFulfillmentApi.createMapping(payload);
} }
message.success('商品映射已保存'); message.success('商品映射已保存');
setMappingEditorOpen(false);
resetMappingForm(); resetMappingForm();
await loadMappingRows(); await loadMappingRows();
await loadTasks(); await loadTasks();
} catch (error) { } catch (error) {
message.error(getErrorMessage(error)); message.error(getErrorMessage(error));
} finally {
setMappingSaving(false);
} }
}; };
@@ -1268,7 +1300,6 @@ export default function PlatformFulfillmentPage() {
<Tag color={task.saleMode === 'presale' ? 'gold' : task.saleMode === 'direct' ? 'green' : 'default'}> <Tag color={task.saleMode === 'presale' ? 'gold' : task.saleMode === 'direct' ? 'green' : 'default'}>
{SALE_MODE_LABELS[task.saleMode] || task.saleMode} {SALE_MODE_LABELS[task.saleMode] || task.saleMode}
</Tag> </Tag>
<Tag>{AVAILABILITY_LABELS[task.availabilityState] || task.availabilityState}</Tag>
</Space> </Space>
<Text type="secondary" ellipsis title={task.campaignName || task.campaignKey || '-'}> <Text type="secondary" ellipsis title={task.campaignName || task.campaignKey || '-'}>
{task.campaignName || task.campaignKey || '未设置活动批次'} {task.campaignName || task.campaignKey || '未设置活动批次'}
@@ -1421,12 +1452,17 @@ export default function PlatformFulfillmentPage() {
) : null} ) : null}
{task.executionStatus === 'role_ready' ? ( {task.executionStatus === 'role_ready' ? (
<Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.confirmBinding(task.id))}> <Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.confirmBinding(task.id))}>
确认绑定 代客户确认
</Button>
) : null}
{canManualConfirmBinding(task) && task.executionStatus !== 'role_ready' && task.bindTask?.roleName ? (
<Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => void submitOperatorConfirm(task)}>
代客户确认
</Button> </Button>
) : null} ) : null}
{can('platform_fulfillment:use') && canManualConfirmBinding(task) ? ( {can('platform_fulfillment:use') && canManualConfirmBinding(task) ? (
<Button size="small" icon={<CheckCircleOutlined />} onClick={() => openManualBinding(task)}> <Button size="small" danger icon={<CheckCircleOutlined />} onClick={() => openManualBinding(task)}>
人工确认绑定 强制确认
</Button> </Button>
) : null} ) : null}
{canResetBinding(task) ? ( {canResetBinding(task) ? (
@@ -1474,9 +1510,17 @@ export default function PlatformFulfillmentPage() {
刷新二维码 刷新二维码
</Button> </Button>
) : null} ) : null}
{selected &&
selected.executionStatus !== 'role_ready' &&
selected.executionStatus !== 'bound' &&
(selected.bindingEvidence?.scannedRole || selected.bindTask?.roleName) ? (
<Button type="primary" icon={<CheckCircleOutlined />} onClick={() => void submitOperatorConfirm(selected)}>
代客户确认
</Button>
) : null}
{selected && can('platform_fulfillment:use') && canManualConfirmBinding(selected) ? ( {selected && can('platform_fulfillment:use') && canManualConfirmBinding(selected) ? (
<Button icon={<CheckCircleOutlined />} onClick={() => openManualBinding(selected)}> <Button danger icon={<CheckCircleOutlined />} onClick={() => openManualBinding(selected)}>
人工确认绑定 强制确认
</Button> </Button>
) : null} ) : null}
{selected.account && {selected.account &&
@@ -1733,9 +1777,6 @@ export default function PlatformFulfillmentPage() {
<Descriptions.Item label="销售模式"> <Descriptions.Item label="销售模式">
{SALE_MODE_LABELS[selected.saleMode] || selected.saleMode} {SALE_MODE_LABELS[selected.saleMode] || selected.saleMode}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="开放状态">
{AVAILABILITY_LABELS[selected.availabilityState] || selected.availabilityState}
</Descriptions.Item>
<Descriptions.Item label="活动批次" span={2}> <Descriptions.Item label="活动批次" span={2}>
{selected.campaignName || selected.campaignKey || '-'} {selected.campaignName || selected.campaignKey || '-'}
</Descriptions.Item> </Descriptions.Item>
@@ -2240,11 +2281,14 @@ export default function PlatformFulfillmentPage() {
</Modal> </Modal>
<Modal <Modal
title={`人工确认绑定 ${manualBindTarget ? `#${manualBindTarget.id}` : ''}`} title={`人工强制确认 ${manualBindTarget ? `#${manualBindTarget.id}` : ''}`}
open={Boolean(manualBindTarget)} open={Boolean(manualBindTarget)}
okText="确认绑定" okText="强制绑定"
cancelText="取消" cancelText="取消"
confirmLoading={manualBinding} confirmLoading={manualBinding}
okButtonProps={{
disabled: manualBindMismatch || !manualBindRole.trim() || manualBindNote.trim().length < 2,
}}
onOk={() => void confirmManualBinding()} onOk={() => void confirmManualBinding()}
onCancel={() => { onCancel={() => {
setManualBindTarget(null); setManualBindTarget(null);
@@ -2256,9 +2300,17 @@ export default function PlatformFulfillmentPage() {
<Alert <Alert
type="warning" type="warning"
showIcon showIcon
message="人工确认会直接把订单标记为已绑定" message="强制确认会跳过 actBind 直接把订单标记为已绑定"
description="只在已核实客户游戏角色确实绑定在当前账号上时使用;会停止当前二维码轮询,并记录操作人、角色和备注。" description="只在账号当前角色已经确认绑定到该角色、但缺少本次扫码证据时使用;必须填写依据。普通代确认请用“代客户确认”。"
/> />
{manualBindMismatch ? (
<Alert
type="error"
showIcon
message="确认角色与账号当前角色不一致"
description="人工确认只能用于账号已经绑定到该角色的场景;换绑必须先完成 actBind 或使用正确账号。"
/>
) : null}
<Text type="secondary"> <Text type="secondary">
账号当前角色:{manualBindTarget?.bindingEvidence?.accountCurrentRole || '未知'} 账号当前角色:{manualBindTarget?.bindingEvidence?.accountCurrentRole || '未知'}
{manualBindTarget?.bindingEvidence?.scannedRole {manualBindTarget?.bindingEvidence?.scannedRole
@@ -2409,13 +2461,27 @@ export default function PlatformFulfillmentPage() {
<Modal <Modal
open={mappingOpen} open={mappingOpen}
title="斗鱼商品映射管理" title="斗鱼商品映射管理"
width={1120} width={1080}
okText="保存映射" footer={null}
onOk={() => void saveMapping()} onCancel={() => {
onCancel={() => setMappingOpen(false)} setMappingOpen(false);
setMappingEditorOpen(false);
}}
> >
<Space direction="vertical" size={14} style={{ width: '100%' }}> <Space direction="vertical" size={12} style={{ width: '100%' }}>
<Space wrap style={{ width: '100%', justifyContent: 'space-between' }}>
<Space wrap> <Space wrap>
<Input.Search
allowClear
value={mappingKeyword}
placeholder="搜索内部 SKU / 商品"
style={{ width: 260 }}
onChange={(event) => setMappingKeyword(event.target.value)}
onSearch={(value) => {
setMappingKeyword(value);
void loadMappingRows(value).catch((error) => message.error(getErrorMessage(error)));
}}
/>
<Select <Select
value={mappingFilterMode} value={mappingFilterMode}
options={[ options={[
@@ -2424,134 +2490,86 @@ export default function PlatformFulfillmentPage() {
]} ]}
onChange={(value) => { onChange={(value) => {
setMappingFilterMode(value); setMappingFilterMode(value);
void loadMappingRows(mappingSku.trim(), value).catch((error) => message.error(getErrorMessage(error))); void loadMappingRows(mappingKeyword.trim(), value).catch((error) => message.error(getErrorMessage(error)));
}} }}
style={{ width: 160 }} style={{ width: 150 }}
/> />
<Space> <Space size={6}>
<Text>显示已归档</Text> <Text type="secondary">显示已归档</Text>
<Switch <Switch
checked={mappingIncludeArchived} checked={mappingIncludeArchived}
onChange={(checked) => { onChange={(checked) => {
setMappingIncludeArchived(checked); setMappingIncludeArchived(checked);
void platformFulfillmentApi.listMappings({ void loadMappingRows(mappingKeyword.trim(), mappingFilterMode, checked).catch((error) => message.error(getErrorMessage(error)));
keyword: mappingSku.trim(),
sale_mode: mappingFilterMode || undefined,
include_archived: checked,
}).then(setMappings).catch((error) => message.error(getErrorMessage(error)));
}} }}
/> />
</Space> </Space>
<Button onClick={() => resetMappingForm()}> </Space>
<Space>
<Button icon={<ReloadOutlined />} onClick={() => void loadMappingRows().catch((error) => message.error(getErrorMessage(error)))}>
刷新
</Button>
<Button type="primary" onClick={openMappingCreate}>
新建映射 新建映射
</Button> </Button>
</Space> </Space>
<Space wrap style={{ width: '100%' }}>
<Input placeholder="内部 SKU,例如 套装-兔兔白日梦" value={mappingSku} onChange={(event) => setMappingSku(event.target.value)} style={{ width: 260 }} />
<Input placeholder="活动批次,例如 douyu-2026-11-return" value={mappingCampaignKey} onChange={(event) => setMappingCampaignKey(event.target.value)} style={{ width: 260 }} />
<Input placeholder="活动名称,例如 11 月返场" value={mappingCampaignName} onChange={(event) => setMappingCampaignName(event.target.value)} style={{ width: 220 }} />
</Space> </Space>
<Space.Compact style={{ width: '100%' }}> <Text type="secondary" style={{ fontSize: 12 }}>
<Select 共 {mappings.length} 条映射;编辑、停用、归档、删除都在“更多”里,不需要横向滚动。
showSearch </Text>
optionFilterProp="label"
loading={mappingGoodsLoading}
placeholder={mappingGoodsLoading ? '正在加载斗鱼活动商品…' : '选择斗鱼精英宝典商品'}
value={mappingGoodsId || undefined}
onChange={selectGoods}
options={[
...goods.map((item) => ({
value: item.commodity_id,
label: `${item.name || item.commodity_id} · ${item.score ?? '-'} 积分`,
})),
...(mappingGoodsId && !goods.some((item) => item.commodity_id === mappingGoodsId)
? [{
value: mappingGoodsId,
label: `${mappingGoodsName || mappingGoodsId} · 当前已缓存`,
}]
: []),
]}
notFoundContent={mappingGoodsLoading ? null : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无活动商品" />}
style={{ flex: 1 }}
/>
<Button icon={<ReloadOutlined />} loading={mappingGoodsLoading} onClick={() => void reloadMappingGoods()}>
刷新商品
</Button>
</Space.Compact>
<Space wrap>
<Text>销售模式</Text>
<Select
value={mappingSaleMode}
options={Object.entries(SALE_MODE_LABELS).map(([value, label]) => ({ value, label }))}
onChange={setMappingSaleMode}
style={{ width: 140 }}
/>
<Text>所需积分</Text>
<InputNumber min={0} value={mappingPoints} onChange={(value) => setMappingPoints(value)} />
<Text>启用</Text>
<Switch checked={mappingEnabled} onChange={setMappingEnabled} />
</Space>
<Space wrap>
<Text>商品开放时间</Text>
<DatePicker
showTime
value={mappingAvailableFrom}
onChange={setMappingAvailableFrom}
placeholder="开始时间"
/>
<Text>至</Text>
<DatePicker
showTime
value={mappingAvailableUntil}
onChange={setMappingAvailableUntil}
placeholder="结束时间"
/>
</Space>
<Tabs
items={[
{
key: 'current',
label: '当前映射',
children: (
<Table<PlatformFulfillmentMapping> <Table<PlatformFulfillmentMapping>
rowKey="id" rowKey="id"
size="small" size="small"
pagination={false} tableLayout="fixed"
pagination={{ pageSize: 10, hideOnSinglePage: true, showSizeChanger: false }}
dataSource={mappings} dataSource={mappings}
columns={[ columns={[
{ title: '内部 SKU', dataIndex: 'internalSkuKey', width: 150 },
{ {
title: '活动批次', title: '内部 SKU',
key: 'campaign', dataIndex: 'internalSkuKey',
width: 170, width: 170,
render: (_: unknown, row) => ( ellipsis: true,
<Space direction="vertical" size={0}> render: (value: string, row) => (
<Text>{row.campaignName || row.campaignKey}</Text> <Space direction="vertical" size={0} style={{ maxWidth: '100%' }}>
<Text type="secondary" style={{ fontSize: 12 }}>{row.campaignKey}</Text> <Text strong ellipsis style={{ maxWidth: '100%' }}>{value}</Text>
<Text type="secondary" style={{ fontSize: 12 }} ellipsis>
{row.campaignName || row.campaignKey || '-'}
</Text>
</Space>
),
},
{
title: '商品',
dataIndex: 'goodsName',
width: 250,
ellipsis: true,
render: (value: string, row) => (
<Space direction="vertical" size={0} style={{ maxWidth: '100%' }}>
<Text ellipsis style={{ maxWidth: '100%' }}>{value || row.commodityId || '-'}</Text>
<Text type="secondary" style={{ fontSize: 12 }} ellipsis>
{row.commodityId}
</Text>
</Space> </Space>
), ),
}, },
{ title: '商品', dataIndex: 'goodsName', width: 150 },
{ title: '商品 ID', dataIndex: 'commodityId', width: 180 },
{ {
title: '分类', title: '分类',
key: 'saleMode', key: 'saleMode',
width: 130, width: 90,
render: (_: unknown, row) => ( render: (_: unknown, row) => (
<Space direction="vertical" size={2}> <Space direction="vertical" size={2}>
<Tag color={row.saleMode === 'presale' ? 'gold' : row.saleMode === 'direct' ? 'green' : 'default'}> <Tag color={row.saleMode === 'presale' ? 'gold' : row.saleMode === 'direct' ? 'green' : 'default'}>
{SALE_MODE_LABELS[row.saleMode] || row.saleMode} {SALE_MODE_LABELS[row.saleMode] || row.saleMode}
</Tag> </Tag>
<Tag>{AVAILABILITY_LABELS[row.availabilityState] || row.availabilityState}</Tag>
</Space> </Space>
), ),
}, },
{ title: '积分', dataIndex: 'requiredPoints', width: 80 }, { title: '积分', dataIndex: 'requiredPoints', width: 70 },
{ title: '影响任务', dataIndex: 'affectedTasks', width: 90 }, { title: '影响任务', dataIndex: 'affectedTasks', width: 80 },
{ {
title: '状态', title: '状态',
dataIndex: 'enabled', dataIndex: 'enabled',
width: 100, width: 80,
render: (value: boolean, row) => ( render: (value: boolean, row) => (
<Tag color={row.archivedAt ? 'default' : value ? 'green' : 'orange'}> <Tag color={row.archivedAt ? 'default' : value ? 'green' : 'orange'}>
{row.archivedAt ? '已归档' : value ? '启用' : '停用'} {row.archivedAt ? '已归档' : value ? '启用' : '停用'}
@@ -2561,9 +2579,9 @@ export default function PlatformFulfillmentPage() {
{ {
title: '操作', title: '操作',
key: 'actions', key: 'actions',
width: 310, width: 250,
render: (_: unknown, row) => ( render: (_: unknown, row) => (
<Space wrap size={4}> <Space size={2} wrap>
<Button size="small" disabled={Boolean(row.archivedAt)} onClick={() => editMapping(row)}> <Button size="small" disabled={Boolean(row.archivedAt)} onClick={() => editMapping(row)}>
编辑 编辑
</Button> </Button>
@@ -2591,11 +2609,120 @@ export default function PlatformFulfillmentPage() {
), ),
}, },
]} ]}
scroll={{ x: 1300 }}
/> />
), </Space>
}, </Modal>
<Modal
title={mappingEditingId ? '编辑商品映射' : '新建商品映射'}
open={mappingEditorOpen}
width={620}
centered
okText="保存映射"
cancelText="取消"
confirmLoading={mappingSaving}
onOk={() => void saveMapping()}
onCancel={() => setMappingEditorOpen(false)}
>
<Space direction="vertical" size={14} style={{ width: '100%' }}>
<div>
<Text strong>内部 SKU</Text>
<Input
value={mappingSku}
placeholder="例如 套装-兔兔白日梦"
onChange={(event) => setMappingSku(event.target.value)}
style={{ marginTop: 6 }}
/>
</div>
<Row gutter={12}>
<Col span={12}>
<Text strong>活动批次</Text>
<Input
value={mappingCampaignKey}
placeholder="douyu-current"
onChange={(event) => setMappingCampaignKey(event.target.value)}
style={{ marginTop: 6 }}
/>
</Col>
<Col span={12}>
<Text strong>活动名称</Text>
<Input
value={mappingCampaignName}
placeholder="例如 11 月返场"
onChange={(event) => setMappingCampaignName(event.target.value)}
style={{ marginTop: 6 }}
/>
</Col>
</Row>
<div>
<Text strong>斗鱼精英宝典商品</Text>
<Space.Compact style={{ width: '100%', marginTop: 6 }}>
<Select
showSearch
optionFilterProp="label"
loading={mappingGoodsLoading}
placeholder={mappingGoodsLoading ? '正在加载斗鱼活动商品…' : '选择斗鱼精英宝典商品'}
value={mappingGoodsId || undefined}
onChange={selectGoods}
options={[
...goods.map((item) => ({
value: item.commodity_id,
label: `${item.name || item.commodity_id} · ${item.score ?? '-'} 积分`,
})),
...(mappingGoodsId && !goods.some((item) => item.commodity_id === mappingGoodsId)
? [{
value: mappingGoodsId,
label: `${mappingGoodsName || mappingGoodsId} · 当前已缓存`,
}]
: []),
]} ]}
notFoundContent={mappingGoodsLoading ? null : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无活动商品" />}
style={{ flex: 1 }}
/>
<Button icon={<ReloadOutlined />} loading={mappingGoodsLoading} onClick={() => void reloadMappingGoods()}>
刷新
</Button>
</Space.Compact>
</div>
<Row gutter={12}>
<Col span={9}>
<Text strong>销售模式</Text>
<Select
value={mappingSaleMode}
options={Object.entries(SALE_MODE_LABELS).map(([value, label]) => ({ value, label }))}
onChange={setMappingSaleMode}
style={{ width: '100%', marginTop: 6 }}
/>
</Col>
<Col span={8}>
<Text strong>所需积分</Text>
<InputNumber
min={0}
value={mappingPoints}
onChange={(value) => setMappingPoints(value)}
style={{ width: '100%', marginTop: 6 }}
/>
</Col>
<Col span={7}>
<Text strong>启用</Text>
<div style={{ marginTop: 6 }}>
<Switch checked={mappingEnabled} onChange={setMappingEnabled} />
</div>
</Col>
</Row>
<div>
<Text strong>商品开放时间</Text>
<Space wrap style={{ width: '100%', marginTop: 6 }}>
<DatePicker showTime value={mappingAvailableFrom} onChange={setMappingAvailableFrom} placeholder="开始时间" />
<Text>至</Text>
<DatePicker showTime value={mappingAvailableUntil} onChange={setMappingAvailableUntil} placeholder="结束时间" />
</Space>
</div>
<Alert
type={mappingEditingId ? 'info' : 'success'}
showIcon
message={mappingEditingId ? '修改后会同步影响订单选号和兑换资格判断' : '保存后会立即进入商品映射列表'}
description="内部 SKU 必须和 order_site 订单商品一致;商品 ID 来自斗鱼精英宝典活动。"
/> />
</Space> </Space>
</Modal> </Modal>