18 Commits
Author SHA1 Message Date
yml 8aa4ea7342 修复(履约绑定): 客户资料不全时禁止开始绑定
- 自动选号后不再在缺少游戏主页截图时启动绑定
- 补启动查询只挑资料完整的任务,避免阻塞后续任务
- 客户绑定启动接口校验角色/登录方式/系统/截图
2026-11-25 10:07:14 +08:00
yml b495a2d999 优化(履约工作台): 游戏主页截图文案与对接文档统一 2026-11-25 00:16:31 +08:00
yml 5c448bf954 feat(fulfillment): 队列筛选增加全部并默认全部
- 直接兑换/预售/未分类/历史任务的队列默认全部
- 全部展示包含未映射、已完成、已取消任务
- 保留当前待办/待映射/可履约/需要人工等筛选
- 后端 all 队列不再套映射过滤
2026-11-25 00:02:46 +08:00
yml 1a02733cda fix(fulfillment): 历史任务冻结,快照不再触发自动状态迁移 2026-11-24 23:43:00 +08:00
yml aafac6e536 feat(fulfillment): 增加 Clean Cutover,历史任务隔离到人工入口
- 新增 flow_version,存量任务回填 1,Cutover 后新任务写 2
- 迁移设置 clean_flow_started_at,按订单支付/创建时间判定
- 自动选号只处理 clean 任务
- 工作台新增历史任务 Tab,历史列表不受订单起算时间限制
- 历史任务不参与自动重试和预售台账同步
- 补充流程边界测试和计划文档
2026-11-24 23:11:13 +08:00
yml 7dec3c4c48 fix(fulfillment): 客户资料渠道比对兼容线上手Q标签
- 线上账号渠道为微信/手Q,不能直接用QQ比较
- 补充手Q+苹果渠道匹配测试
2026-11-24 22:38:21 +08:00
yml 9feb6f4bf4 fix(fulfillment): 增加未分类 Tab,避免历史 sale_mode=unknown 任务丢失
- 生产存在大量 sale_mode=unknown 任务,直接兑换/预售两 Tab 会隐藏
- 增加未分类兜底入口,未分类不显示预售台账列和同步按钮
- Tab 记忆支持未分类
2026-11-24 22:35:07 +08:00
yml 628081986f feat(fulfillment): 记住上次选择的直接兑换/预售 Tab
- sale mode tab 写入 localStorage
- 刷新页面/重新进入沿用上次选择
2026-11-24 22:22:56 +08:00
yml ad74fdb743 feat(fulfillment): 工作台拆分直接兑换/预售两个入口
- 直接兑换和预售独立 Tab,按 sale_mode 查询
- 直接兑换不显示预售台账列和同步按钮,流程在工作台完成
- 预售绑定成功后才显示/启用同步到斗鱼预售台账
- 台账页面、菜单、按钮统一改名斗鱼预售台账
- 取消销售模式下拉,队列筛选按 Tab 动态展示
2026-11-24 22:21:15 +08:00
yml 56e9568fed feat(fulfillment): 分类合并进商品映射列
- 删除单独分类列
- 商品映射列展示销售模式、积分、活动批次和开放时间
2026-11-24 22:04:11 +08:00
yml 8822f0ab42 feat(fulfillment): 工作台表头/内容居中,订单台账同步需绑定成功
- 表头和单元格统一居中
- 同步按钮改名“同步到订单台账”
- 行同步仅在绑定状态 bound 后可用,批量同步要求全选任务均已绑定
2026-11-24 22:02:29 +08:00
yml 292f61b56a feat(fulfillment): 工作台增加买家主页列并重命名绑定列
- 买家主页截图放在用户角色绑定右侧,支持缩略图预览
- 绑定列改名用户角色绑定,便于与客户资料对比
2026-11-24 21:59:55 +08:00
yml 70afd34b71 fix(fulfillment): 允许有效快照恢复 source_cancelled 任务
- 先到的停用配置快照可能把任务取消,后到的启用快照此前被终态拦截
- 仅 source_cancelled 且新快照有效时恢复,用户取消/完成仍保持终态
- 补充恢复测试
2026-11-24 21:54:57 +08:00
yml eb93e7aca2 fix(fulfillment): 增加待映射队列
- 待映射任务未配置商品映射时不再被列表过滤掉
- 工作台新增待映射标签,显示同步后尚未映射的订单
- 补充未映射任务列表测试
2026-11-24 21:44:37 +08:00
yml 6ec8248068 feat(fulfillment): 接收并展示 order_site 客户主页截图
- 履约任务新增客户角色/平台/系统/主页截图/更新时间字段
- 迁移 0131
- order_site contractVersion=3 快照自动落客户资料
- 增加客户资料 integration 写入接口
- 工作台详情展示客户资料、平台角色比对和截图
- 补充客户资料保存/快照解析测试与对接文档
2026-11-24 21:25:14 +08:00
yml 06a226f51f fix(douyu): 台账投影限制仅约束非管理员
- 人工 source_type=manual 订单完全不受投影限制
- 平台来源订单普通客服/运营只读,超级管理员可修正并审计
- 前端管理员解锁投影字段,普通账号仍只读
- 补充管理员/客服两条权限测试
2026-11-24 21:02:20 +08:00
yml ee593fa5b4 feat(douyu): 订单台账按平台履约只读投影
- 外部单协作改名为斗鱼订单台账
- 平台来源台账单的订单号/账号/礼包/商品/积分只读
- 台账显示来源履约任务,隐藏解除/推荐账号入口
- 后端 update_order 拒绝投影字段变更
- set_account 对平台来源要求显式接管转人工
- 补充重构计划第一刀实施状态
2026-11-24 20:56:46 +08:00
yml 9654df542f feat(douyu-collab): 状态列展示备注并支持快速备注
- 状态列下方展示订单备注,未填显示 + 备注
- 点击备注弹窗快速编辑,保存后更新列表/详情/版本
- 参考微博外部单协作交互,归档或只读状态不可编辑
2026-11-24 20:27:25 +08:00
25 changed files with 2046 additions and 99 deletions
@@ -0,0 +1,50 @@
# order_site 游戏主页截图对接
## 流程
```text
order_site 斗鱼领取页
→ 客户填写游戏角色 + 上传游戏主页截图(必填)
→ order_site 文件服务上传,保存 objectKey
→ douyu_fulfillment_tasks 保存截图字段
→ live_hub outbox:platform_fulfillment.order_snapshot
contractVersion=3
customerRoleName / customerPlatform / customerSystem
homeImages[{url,thumbnailUrl,objectKey,filename}]
customerProfileUpdatedAt
→ live-hub sync_order_snapshot 落平台履约任务
→ 直播账号履约工作台「用户资料(order_site)」展示并比对
```
## order_site
- 迁移:`180_douyu_customer_homepage_screenshot.sql`
- 上传接口:`POST /api/v1/douyu-fulfillment/:orderNo/homepage-screenshot`
- 保存资料:`POST /api/v1/douyu-fulfillment/:orderNo/profile`
- `homepageScreenshotObjectKey` 必填;
- 后端校验 `file_assets` 的 scene/uploader/type;
- 截图 URL 使用 `orders.claimBaseUrl` 的 origin 生成绝对地址。
## live-hub
- 迁移:`20261124_0131_fulfillment_customer_profile`
- 字段:
- `customer_role_name`
- `customer_platform`
- `customer_system`
- `customer_home_images`(URL/缩略图/objectKey)
- `customer_profile_updated_at`
- 快照同步自动落这些字段;
- 备用 integration 接口:
`POST /api/integration/platform-fulfillment/customer-sessions/{task_id}/profile`
- 工作台详情显示:
- 客户角色、登录方式、系统;
- 平台当前角色/渠道;
- 一致/不一致标签;
- 游戏主页截图缩略图预览。
## 约束
- order_site 当前必填 1 张;live-hub 接收接口兼容最多 5 张;
- 截图只用于核对绑定,不进入斗鱼账号 CK;
- 客户资料更新通过 outbox 快照同步,不靠客服手动转发图片。
@@ -0,0 +1,681 @@
# 斗鱼业务彻底优化与重构计划
> 目标不是“再修几个页面”,而是把斗鱼业务从多套状态、多个入口、多处实现的现状,
> 收敛成一套可持续演进的账号/订单/任务模型。
>
> 原则:**不做一次性大爆炸重写;用绞杀者模式分阶段替换;数据先自洽,入口再收敛,
> 最后清代码。**
---
## 1. 结论先行
当前斗鱼业务的主要问题不是单个 bug,而是:
1. **账号有 5 个入口、订单有 2 套视图、任务有 4 张表、状态有 7 个维度;**
2. 同一个“状态”列在不同页面含义不同;
3. 外部协作和平台履约对同一订单各自维护账号/状态,已经出现分叉;
4. 大量人工任务占着租约,旧任务淹没工作台;
5. 绑定、CK、兑换、充值各有多个实现入口;
6. 供给画像/质量分已经算出来,但没有真正进入选号。
生产实测:
```text
账号总数 31,291
账号生命周期组合 14 种
平台人工任务 3,399
其中仍持有 active 租约 561
无账号的开放任务 3,352
外部协作订单 5,935
协作/履约重叠订单 1,823
其中账号不一致 94
协作有账号、履约任务无账号 839
协作进行中、任务已结束 134
有效 CK 但已过期 409(其中 67 个有租约)
绑定任务与账号角色不一致 1
```
这不是 UI 问题,是**领域模型没有收敛**。
---
## 2. 目标与非目标
### 2.1 目标
- 一个账号只有一个详情页;
- 一个订单只有一个详情页;
- 一个业务动作只有一个后端服务入口;
- 状态必须带维度,不再用裸“状态”;
- 所有列表/搜索/详情共享同一套状态和权限;
- 人工任务有明确原因、租约策略和批量处理;
- 供给/保护/自动化有统一控制面;
- 暗色模式、表格宽度、操作区等 UI 规范统一;
- 新功能不再需要同时改 3 个页面。
### 2.2 非目标
- 不重写已经稳定的斗鱼协议 runner(登录、绑定、兑换的底层请求保留);
- 不删除历史事件和审计;
- 不做一次性数据库大迁移;
- 不为了“看起来统一”把不同业务维度强行压成一个状态;
- 不在没有对账数据前直接改选号/兑换主流程。
---
## 3. 现状问题清单
### 3.1 账号维度
| 问题 | 现象 |
| --- | --- |
| 多入口 | 账号管理、账号检测、分配管理、登录任务、Cookie 管理、CK 检测与重登、自动化都能操作账号 |
| 多详情 | AccountsPage、AccountDetailPage、DouyuTasksPage、PlatformFulfillmentPage、DouyuCollabPage 各有一套 |
| 多状态 | `status`、`ck_check_status`、`role_bind_status`、租约状态、供给角色都展示成“状态” |
| CK 口径 | `valid` 可能已过期;`cookie_updated_at`、`ck_checked_at`、`ck_expected_expires_at` 各页面用法不同 |
| 角色口径 | 本地 7 天锁、官方 canChangeTime、角色绑定状态分散 |
### 3.2 订单维度
| 问题 | 现象 |
| --- | --- |
| 两套订单 | `douyu_external_orders` 和 `platform_fulfillment_tasks` 各自维护账号/状态 |
| 账号分叉 | 同一订单协作页显示 8021,履约页显示 7373(生产实例) |
| 状态分叉 | 协作 to_recharge,履约 manual_required;协作 done,任务仍 open |
| 搜索范围 | 默认“当前待办”搜不到 manual 单,用户以为订单丢了 |
| 操作分叉 | 绑定/改状态/充值/兑换在不同页面有不同按钮 |
### 3.3 任务维度
```text
manual_required 3,399
lease_expired 2,439
customer_role_cooldown 460
manual_required 393
binding_failed 62
role bound elsewhere 43
collab handoff 2
```
问题:
- 2,439 条旧 lease_expired 没有自动收口;
- 561 条 manual 仍占租约(460 条客户角色冷却、58 条绑定失败等);
- 3,352 条开放任务没有账号,工作台噪音大;
- 人工原因没有形成可操作的队列分组。
### 3.4 供给/自动化维度
```text
供给池 3,403(high 2,291 + ordinary 1,112)
供给目标已超额
ck_health 待检 4,700+
invalid 自动重登积压 17,000+
onboarding 5,260
```
问题:
- 画像角色/质量分展示但选号未使用;
- 供给目标按 value_class 聚合,和角色/商品/冗余没有完全对齐;
- 保护组、CK 到期、租约、登录配额是四套控制,缺统一告警;
- 自动化页面作业多,但没有“影响面/积压/保护对象”的统一视图。
### 3.5 代码维度
```text
DouyuTasksPage.tsx 3,757 行,46 处 handbook 条件
DouyuCollabPage.tsx 3,108 行
PlatformFulfillmentPage.tsx 2,731 行
routers/douyu.py 30 路由
routers/douyu_collab.py 40 路由
routers/platform_fulfillment.py 30 路由
```
绑定相关至少 6 个服务文件;CK/登录至少 8 个服务文件;兑换/充值分散在多个 runner 和页面。
这些不全是冗余,但**边界没有定义**,导致同一个动作有多个“看起来都能做”的入口。
---
## 4. 目标架构
### 4.1 逻辑聚合
```text
Account Aggregate
identity 斗鱼 UID / 用户名 / 昵称
auth CK、登录、过期、失败分型
role 当前角色、绑定状态、换绑锁、角色来源
occupancy 租约、当前任务
capability 精英/电竞/和平/商城能力
supply 供给角色、质量、冗余(派生,不参与事实判断)
Order Aggregate
order 平台单 / 协作单统一订单头
source link 平台履约任务 / 外部协作单 / 手工单
item 商品、积分、金额、店铺
fulfillment 分配、绑定、兑换、完成
finance 充值、核账、作废
events 订单时间线
Task / Attempt
login attempt、bind attempt、exchange attempt、recharge attempt
只记录“尝试”,订单状态由 Order 聚合决定
Supply / Protection
供给目标、账号画像、CK 保护组、租约保护、告警
```
### 4.2 状态维度(必须分开展示)
| 维度 | 取值 | 页面文案 |
| --- | --- | --- |
| 账号生命周期 | active/invalid/imported/manual/disabled/archived | 账号状态 |
| 登录/CK | valid/invalid/error/expired/unknown | 登录状态 |
| 角色绑定 | unknown/unbound/pending/bound/cooldown/conflict | 角色绑定 |
| 占用 | free/leased/manual | 租约状态 |
| 履约 | pending/mapped/allocated/binding/bound/ready/exchanging/done/failed/cancelled | 履约状态 |
| 绑定执行 | not_started/qr_pending/waiting_bind/role_ready/bound/failed | 绑定进度 |
| 兑换 | not_started/waiting_release/eligible/points_short/exchanging/done/failed | 兑换状态 |
| 财务 | incomplete/to_recharge/recharged/points_error/void | 财务状态 |
**禁止**:一个没有维度前缀的“状态”列同时承载以上两种含义。
### 4.3 目标数据模型
不要求一次改完,但方向如下:
1. **账号**
- 保留 `accounts` 作为跨平台身份表;
- 斗鱼专属字段收口到只读投影 `douyu_account_state`(或明确字段分区);
- 账号事件只追加,不作为当前状态直接读。
2. **订单**
- 新增 `douyu_orders` 作为唯一订单头;
- `douyu_order_sources` 保存平台履约单/协作单/手工单的 source 映射;
- `platform_fulfillment_tasks` 逐步降级为执行视图/历史表;
- `douyu_external_orders` 逐步降级为财务/客户视图;
- 阶段内允许双写,但**只允许一个写入口**。
3. **任务**
- `douyu_tasks` 继续作为执行尝试;
- 订单状态由 `douyu_orders` 唯一维护;
- 绑定/兑换/充值尝试通过事件回写订单投影。
4. **事件**
- 保留 `account_events`;
- 订单事件统一 `douyu_order_events`(或复用现有事件表加 `order_id`);
- UI 时间线只读事件投影。
5. **供给**
- `account_supply_profiles` 保留为派生表;
- 选号真正使用它,或暂时从界面隐藏质量分/供给角色;
- 目标/冗余/保护组统一控制面。
### 4.4 目标服务边界
```text
AccountService
profile / lifecycle / assignment
AccountAuthService
ck verify / relogin / quota / login attempts
BindingService
role read / start bind / confirm / force / cooldown
OrderService
create / sync / reconcile / status transitions
FulfillmentService
allocate / reserve lease / bind / exchange / complete
FinanceService
recharge / points check / void
SupplyService
targets / profile / replenishment / protection
AutomationFacade
jobs / runs / backlog / alerts
```
Routers 只做鉴权、参数校验、调用 facade,不再写业务分支。
---
## 5. 前端目标信息架构
### 5.1 菜单收敛
从当前 13 个斗鱼菜单收敛到 6 个:
```text
斗鱼
1. 账号池
2. 登录与 CK
3. 履约中心(平台单 + 协作单 + 待处理)
4. 账号工作台(精英 / 电竞 / 和平 Tab)
5. 商品与配置
6. 自动化与告警
```
具体:
- 账号管理、分配管理合并为「账号池」;
- 账号检测、登录任务、Cookie 管理、CK 检测与重登合并为「登录与 CK」;
- 外部单协作、直播账号履约合并为「履约中心」;
- 精英/电竞/和平三个菜单合并为一个工作台的 Tab;
- 自动化独立,但增加积压/保护/告警视图。
### 5.2 统一组件
必须做成共享组件,不允许每页重写:
- `DouyuStatusBadge`:按维度渲染标签和颜色;
- `DouyuAccountDrawer`:概览、CK/登录、角色、租约/任务、能力、时间线;
- `DouyuOrderDrawer`:订单概况、账号/角色、绑定、兑换、充值、来源、时间线;
- `DouyuTaskActionBar`:按当前任务状态给唯一主操作;
- `DouyuManualQueue`:按原因分组 + 批量释放/重配/关闭;
- `DouyuTable`:统一无横向滚动、操作区、空状态、暗色 token;
- `DouyuSearch`:全局搜索,不受当前队列限制。
### 5.3 关键交互
- 订单搜索默认全局,显示“在哪个队列/哪个来源”;
- 账号详情不跳页,统一抽屉;协作/履约页共用;
- 人工单首屏显示原因、占用账号、下一步动作;
- 所有“强制”操作二次确认,红色,记录审计;
- 历史截图/历史记录默认折叠,不干扰当前操作。
---
## 6. 分阶段实施计划
> 采用绞杀者模式:旧页面保留可用,新中心逐步接管;每个阶段有独立回滚点。
### Phase 0:冻结与基线(1–2 天)
- 冻结新增斗鱼页面/入口,禁止再复制详情/状态逻辑;
- 建立不变量 SQL 巡检:
- 协作/履约账号不一致;
- manual + active lease;
- bound 任务角色不一致;
- valid 但过期 CK;
- 孤儿租约;
- 输出每日对账报告。
**退出标准**:所有问题有可重复查询和数字基线。
### Phase 1:数据对账与清理(1 周)
1. 订单对账
- 1,823 个重叠单逐一归类;
- 94 个账号不一致、839 个协作有账号/任务无账号、134 个状态过期;
- 明确“平台履约执行事实优先,协作财务视图跟随”的规则;
- 不直接改历史,先生成修复建议/审计。
2. 人工单清租
- 561 个 manual + active lease 分类;
- `customer_role_cooldown` 等不可执行单释放租约或转入等待池;
- 2,439 个旧 lease_expired 转归档/关闭;
- 366 个 pending_mapping 补映射或转人工。
3. CK 清理
- 409 个 valid but expired,67 个有租约;
- 优先刷新/重登;
- 清理无效 CK 与 cookie 状态不一致。
**退出标准**:0 个未解释的账号不一致/孤儿租约;manual 占租下降 80%。
### Phase 2:后端唯一读模型(2–3 周)
- 新增 `DouyuOrderService` 读模型和 `GET /api/douyu/orders/{id}`;
- 双读旧平台/协作数据,输出差异报告;
- 新增 `GET /api/douyu/accounts/{id}` 统一账号详情;
- 所有列表 API 返回统一状态维度结构;
- 旧接口保留,逐步适配新 DTO。
**退出标准**:新旧读模型对 1,823 重叠单 100% 可解释;差异有清单。
### Phase 3:前端统一中心(2–3 周)
- 新建 `/douyu` 中心壳;
- 上线统一账号抽屉、订单抽屉、全局搜索、状态维度组件;
- 账号池、履约中心先接新 API;
- 旧路由保留并跳转/提示;
- 菜单收敛到 6 项。
**退出标准**:用户完成一次“找账号 → 看详情 → 处理订单”全流程不需要跨 3 个页面。
### Phase 4:服务收口与旧入口下线(2 周)
- 绑定、CK、兑换、充值各保留一个 facade;
- 旧路由标记 deprecated,观察调用量;
- 删除重复的前端详情/操作组件;
- 旧后台任务迁移到新服务;
- 旧表保留只读历史。
**退出标准**:一个动作只有一个 API;前端不再出现两套详情。
### Phase 5:供给/自动化/告警(1–2 周)
- 质量分/供给角色真正接入选号,或从 UI 隐藏;
- 保护组、CK 到期、租约、登录配额统一告警;
- 人工队列、自动重登、首登、补货共享积压视图;
- 自动化作业增加影响面和失败分型。
### Phase 6:清理与加固(1 周)
- 删除 dead code/重复服务/旧页面;
- 统一暗色 token,清理 `#fff/#f5f7fa`;
- 表格/移动端/横向滚动统一;
- 文档、迁移、runbook 更新;
- 全量回归 + 生产 canary。
---
## 7. 迁移与回滚策略
1. **双写/双读**
- 新订单表先影子写;
- 旧接口继续读旧表;
- 影子读差异报告,不直接影响用户。
2. **Feature flag**
- `douyu_center_v2` 控制新 UI;
- 按用户/角色灰度;
- 随时切回旧页面。
3. **数据迁移**
- 先回填映射,不删除旧列;
- 每个迁移可重跑;
- 保留 `legacy_*` 映射,至少一个发布周期。
4. **回滚**
- 新表/新 API 只读回滚不影响旧流程;
- 写入口切换必须可开关;
- 生产数据修复先出报告,再执行。
---
## 8. 测试与验收
### 8.1 必测
- 状态机单测:账号、订单、绑定、兑换、租约;
- 不变量 SQL 测试:
- 协作/履约账号一致;
- manual 占租策略;
- bound 角色一致;
- 孤儿租约;
- CK 过期;
- 迁移测试:新表回填、双写、回滚;
- API 契约测试:列表/详情/搜索;
- 前端构建 + 关键组件测试(如引入测试框架)。
### 8.2 验收指标
```text
订单/账号详情入口数量: 1
同一订单跨页账号不一致: 0
manual + active lease 未解释: 0
bound 任务角色不一致: 0
孤儿租约: 0
valid 但过期超过 24h: 0
全局搜索命中率: 100%(订单号/账号/角色)
快速测试: < 2 分钟;迁移测试独立
```
---
## 9. 资源与时间
粗估(1 名熟悉项目的全栈 + 1 名后端/测试配合):
| 阶段 | 工作量 |
| --- | --- |
| Phase 0 | 1–2 天 |
| Phase 1 | 1 周 |
| Phase 2 | 2–3 周 |
| Phase 3 | 2–3 周 |
| Phase 4 | 2 周 |
| Phase 5 | 1–2 周 |
| Phase 6 | 1 周 |
总计约 **8–12 周**;如果 2 人并行,约 **5–7 周**。
不建议压缩到 2 周内做“大爆炸”,数据分叉风险高于收益。
---
## 10. 立即可做的五件事
1. 运行订单/租约/CK 不变量对账,生成修复清单;
2. 冻结新增斗鱼页面和重复入口;
3. 先做统一 `DouyuOrderDrawer` 和 `DouyuAccountDrawer` 原型;
4. 把 561 个 manual 占租按原因分组,先释放不可执行单;
5. 选一个高频流程(订单搜索 → 详情 → 人工处理)做端到端新路径试点。
---
## 11. 明确不做
- 不直接重写斗鱼协议 runner;
- 不删除历史任务/事件;
- 不在 Phase 1 前改选号/兑换主流程;
- 不为统一而把不同状态压成一个字段;
- 不做无 feature flag 的一次性前端替换。
---
## 12. 决策清单
需要产品/运营确认:
1. 平台履约和外部协作,谁是订单执行事实源?
2. 客户角色冷却、账号角色冷却的人工单,租约保留还是释放?
3. 旧 lease_expired 单是关闭、归档还是重开?
4. 供给画像质量分是否进入选号,还是先只做展示?
5. 菜单收敛是否接受旧路由跳转/短期双入口?
这 5 个决策确定后,Phase 1 可以立即开始。
---
## 13. 第一项拆分:订单域收敛(已确认方向)
### 13.1 业务定义
用户确认:
- **直播账号履约工作台是主工作台**;
- 外部协作单不是“外部”,而是早期的**人工登记台账**;
- 自动发货系统跑正常的订单,都应该进入直播账号履约工作台;
- 外部协作台账可以从直播账号履约工作台**导入**;
- 只有特殊/异常订单才在台账里人工补登记。
因此后续统一叫法建议:
```text
直播账号履约工作台 = 订单执行事实源
斗鱼订单台账 = 财务/客服/异常补登记视图
```
代码里已经有一句注释:
> `douyu_collab_sync.py`:直播账号履约任务向斗鱼外部单协作的幂等投影。
这说明方向本来就是“平台 → 台账投影”,只是 UI/权限/数据没有按这个方向收紧。
### 13.2 唯一事实源
| 数据 | 事实源 | 台账行为 |
| --- | --- | --- |
| 订单是否存在 | 平台履约任务 | 只读投影 |
| 账号 | 平台履约任务 | 只读展示;特殊补登记除外 |
| 角色绑定 | 平台履约任务 | 只读展示 |
| 履约状态 | 平台履约任务 | 只读展示 |
| 兑换状态 | 平台履约任务 | 只读展示 |
| 财务/充值/积分核账 | 台账 | 台账可编辑 |
| 人工备注/截图 | 台账 | 台账可编辑 |
| 手工异常单 | 台账 | `source_type=manual`,台账独占 |
### 13.3 两类台账订单
```text
source_type = platform_fulfillment
由平台任务幂等投影
account / role / status / exchange 只读
财务字段、备注、主页截图可编辑
页面显示「来源:履约任务 #ID」和跳转
source_type = manual
人工补登记
账号、角色、状态、财务都由台账维护
不反向覆盖平台任务
```
如果平台来源订单确实需要人工覆盖某个字段,不能直接改,应写入:
```text
manual_override_fields
manual_override_reason
manual_override_by
manual_override_at
```
并显示“人工覆盖”标签,下一次同步不能静默覆盖。
### 13.4 对账规则
当前生产:
```text
协作/履约重叠订单 1,823
账号不一致 94
协作有账号、履约无账号 839
协作进行中、履约已结束 134
```
按以下规则处理:
1. **双方都有账号但不一致**
- 平台任务账号胜出;
- 台账投影改成平台账号;
- 记录 `projection_corrected` 审计。
2. **台账有账号、平台无账号**
- 不自动反向写平台;
- 标记 `needs_platform_account`;
- 平台继续 manual,台账保留人工补录账号;
- 若人工确认要接管,走平台「人工选号」流程。
3. **协作进行中、平台任务已结束**
- 平台状态胜出;
- 台账同步为 done/void/failed,并保留财务差异说明。
4. **平台任务不存在**
- 保留为 manual 台账单;
- 不伪造平台任务。
5. **自动投影失败**
- 进 `order_projection_failures` 或现有事件表;
- 不静默跳过。
### 13.5 改造步骤(第一项内部再拆)
| 步骤 | 内容 | 风险 |
| --- | --- | --- |
| 1 | 台账页面改名「订单台账」,去掉“外部”误导 | 低 |
| 2 | 平台来源台账单禁止编辑账号/角色/履约状态 | 中 |
| 3 | 平台 → 台账自动投影/补投影,幂等 | 中 |
| 4 | 回填 1,823 重叠单,修复 94/839/134 | 中 |
| 5 | 台账详情显示来源任务、账号、状态对照 | 低 |
| 6 | 加不变量巡检,任何新分叉立即告警 | 低 |
### 13.6 验收标准
```text
平台来源台账单 = 平台任务投影:
account / role / status 不一致 = 0
手动修改账号/角色/状态 = 0(只能人工覆盖标记)
手工台账单:
source_type=manual
不影响平台任务
搜索:
同一订单在履约工作台和台账都能按订单号找到
搜索结果明确标注「执行任务」/「台账」
```
### 13.7 这一项不做什么
- 不把两张表立即合成一张;
- 不删除旧人工台账;
- 不让台账反向成为执行事实源;
- 不直接批量修改 1,823 条历史数据,先出对账清单。
### 13.8 下一项拆分顺序
订单域收敛完成后,按以下顺序继续:
1. 账号域:统一账号详情、CK/角色/租约/能力;
2. 状态域:统一维度命名和颜色;
3. 登录/CK 域:合并账号检测、登录任务、Cookie 管理、CK 检测;
4. 绑定域:统一 start/confirm/force/cooldown;
5. 自动化/供给域:画像、保护组、告警;
6. UI 规范:菜单、表格、暗色模式、全局搜索。
---
## 14. 第一刀实施状态(dev_11.27-order-ledger)
已完成:
- 「斗鱼外部单协作」改名为「斗鱼订单台账」,菜单同步改名;
- 平台来源订单(`source_type=platform_fulfillment`)在台账里:
- 非管理员:订单号、账号、礼包、商品、积分字段只读;
- 超级管理员:可修正,操作会记录审计;
- 页面显示「来源:直播账号履约任务 #ID」;
- 解除账号、推荐账号入口隐藏;
- 后端 `update_order` 对**非管理员**拒绝平台来源订单修改投影字段:
`platform_projection_readonly`;
- 后端 `set_account` 对**非管理员**要求显式
`takeover_platform_lease=True`,否则拒绝;
- **超级管理员保留全部修正权限**;人工新建的 `source_type=manual` 订单完全不受限制。
- 保留显式接管流程(服务层),供特殊异常单使用。
尚未完成(下一刀):
- 1,823 个重叠单的回填/对账;
- 94 个账号不一致、839 个协作有账号/履约无账号、134 个状态过期;
- 平台任务变更后自动投影到台账;
- 旧人工台账与平台来源台账的视觉分组;
- 台账只读后,特殊异常单的「转人工台账」入口。
## 15. Clean Cutover:旧数据冻结(2026-11-24 确认)
旧任务不再逐条清洗,统一隔离为历史任务;新订单进入 clean 流程。
### 15.1 数据边界
- `platform_fulfillment_tasks.flow_version = 1`:历史存量;
- `flow_version = 2`:Cutover 之后的新任务;
- 迁移执行时刻写入 `platform_fulfillment_settings.clean_flow_started_at`;
- 旧订单在 Cutover 后补建的任务,按订单支付/创建时间仍归为 legacy。
### 15.2 行为边界
- 自动选号只处理 `flow_version=2`;
- 历史任务只允许人工操作,不参与自动重试、自动收口和预售台账自动同步;
- 工作台新增“历史任务”入口,主工作台默认只看 clean;
- 历史列表不受订单起算时间限制,确保旧单可查;
- 旧 active 租约不做强制批量释放,后续单独出候选清单。
### 15.3 目标
- 不再为 2,462 条 lease_expired 等旧噪音逐条修数据;
- 新单人工队列只保留当前真实异常;
- 旧数据保留可查、可审计、可人工处理。
+77
View File
@@ -747,6 +747,83 @@ class TestDouyuCollabOrders:
== 1
)
def test_platform_source_rejects_projected_field_changes_but_allows_remark(self):
order = collab.DouyuExternalOrder(
order_no="DY-PLATFORM-READONLY",
source_type=collab.SOURCE_TYPE_PLATFORM_FULFILLMENT,
source_task_id=None,
account_id=self.account.id,
account_username=self.account.username,
gift_name="礼包A",
commodity_id="gift-a",
required_points=100,
status=collab.STATUS_INCOMPLETE,
owner_id=self.admin.id,
created_by=self.admin.id,
)
self.session.add(order)
support = User(
username="douyu-collab-support-projection",
password_hash="hash",
role="support",
is_active=True,
)
self.session.add(support)
self.session.commit()
with pytest.raises(collab.CollabError) as exc_info:
collab.update_order(
self.session,
support,
order,
{"gift_name": "礼包B"},
expected_version=order.version,
)
assert exc_info.value.code == "platform_projection_readonly"
assert order.gift_name == "礼包A"
# 管理员保留全部修正权限
collab.update_order(
self.session,
self.admin,
order,
{"gift_name": "礼包B", "remark": "管理员修正投影"},
expected_version=order.version,
)
assert order.gift_name == "礼包B"
assert order.remark == "管理员修正投影"
def test_platform_source_set_account_requires_explicit_takeover(self):
order = collab.DouyuExternalOrder(
order_no="DY-PLATFORM-SET-ACCOUNT",
source_type=collab.SOURCE_TYPE_PLATFORM_FULFILLMENT,
source_task_id=None,
account_id=self.account.id,
account_username=self.account.username,
status=collab.STATUS_INCOMPLETE,
owner_id=self.admin.id,
created_by=self.admin.id,
)
self.session.add(order)
support = User(
username="douyu-collab-support-set-account",
password_hash="hash",
role="support",
is_active=True,
)
self.session.add(support)
self.session.commit()
with pytest.raises(collab.CollabError) as exc_info:
collab.set_account(
self.session,
support,
order,
self.account.username,
client=FakeClient(),
)
assert exc_info.value.code == "platform_projection_readonly"
def test_same_source_platform_lease_is_forced_to_collab_on_takeover(self):
task, lease = self._platform_task_lease()
order = collab.DouyuExternalOrder(
+14 -1
View File
@@ -45,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261124_0130"
HEAD_REVISION = "20261124_0132"
# 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = (
@@ -85,6 +85,12 @@ _LATER_ORM_COLUMNS = {
"classification_source": "VARCHAR(24) NOT NULL DEFAULT 'unknown'",
"exchange_result_image_key": "VARCHAR(512) NOT NULL DEFAULT ''",
"exchange_result_image_saved_at": "DATETIME NULL",
"customer_role_name": "VARCHAR(128) NOT NULL DEFAULT ''",
"customer_platform": "VARCHAR(16) NOT NULL DEFAULT ''",
"customer_system": "VARCHAR(16) NOT NULL DEFAULT ''",
"customer_home_images": "JSON NULL",
"customer_profile_updated_at": "DATETIME NULL",
"flow_version": "INTEGER NOT NULL DEFAULT 1",
},
"douyu_external_orders": {
"succeeded_at": "DATETIME NULL",
@@ -407,6 +413,7 @@ class TestMigrationSmoke:
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0123")
_add_account_platform_columns(mig_engine)
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
with Session(mig_engine) as session:
user = User(
username="binding-sync-user",
@@ -499,6 +506,7 @@ class TestMigrationSmoke:
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0125")
_add_account_platform_columns(mig_engine)
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
with Session(mig_engine) as session:
user = User(
username="false-binding-user",
@@ -617,6 +625,7 @@ class TestMigrationSmoke:
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0126")
_add_account_platform_columns(mig_engine)
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
with Session(mig_engine) as session:
user = User(
username="pending-link-user",
@@ -969,6 +978,7 @@ class TestMigrationSmoke:
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261121_0106")
_add_account_platform_columns(mig_engine)
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
with Session(mig_engine) as session:
user = User(
username="repair-0107-user",
@@ -1431,6 +1441,7 @@ class TestMigrationSmoke:
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261118_0089")
_add_account_platform_columns(mig_engine)
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
with Session(mig_engine) as session:
user = User(
@@ -1572,6 +1583,7 @@ class TestMigrationSmoke:
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261118_0091")
_add_account_platform_columns(mig_engine)
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
with Session(mig_engine) as session:
account = Account(
@@ -1712,6 +1724,7 @@ class TestMigrationSmoke:
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261119_0097")
_add_account_platform_columns(mig_engine)
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
_add_later_orm_columns(mig_engine, ("douyu_external_orders",))
with Session(mig_engine) as session:
+240
View File
@@ -38,6 +38,7 @@ from web.backend.services.automation.jobs import (
platform_fulfillment_lease_reaper as reaper,
)
from web.backend.services.platform_fulfillment import account_selector, service, views
from web.backend.services.platform_fulfillment.order_sync import _apply_customer_profile
NOW = datetime.now(UTC).replace(microsecond=0)
COMMODITY = "20260120QYOOB_bag10"
@@ -68,6 +69,19 @@ class _Base:
views.invalidate_task_list_count_cache()
self.session.close()
def complete_customer_profile(self, task: PlatformFulfillmentTask) -> None:
task.customer_role_name = "小淋笨"
task.customer_platform = "wechat"
task.customer_system = "android"
task.customer_home_images = [
{
"url": "https://example.com/game-home.png",
"thumbnailUrl": "https://example.com/game-home-thumb.png",
"objectKey": "game-home.png",
}
]
self.session.commit()
def account(
self,
name: str,
@@ -181,6 +195,48 @@ class TestWorkbenchReadPath(_Base):
self.session.commit()
return task
def test_all_queue_includes_mapped_and_unmapped_tasks(self):
views.invalidate_task_list_count_cache()
self.task()
unmapped = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="all-unmapped",
source_order_item_id="all-unmapped",
platform_order_id="ALL-UNMAPPED",
internal_sku_key="all-unmapped",
execution_status="pending_mapping",
binding_status="not_started",
exchange_status="not_started",
paid_at=NOW,
created_at=NOW,
updated_at=NOW,
)
self.session.add(unmapped)
self.session.commit()
default_result = service.list_tasks(self.session, page_size=100)
all_result = service.list_tasks(
self.session,
queue_bucket="all",
page_size=100,
)
assert default_result["pagination"]["total"] == 1
assert all_result["pagination"]["total"] == 2
def test_pending_mapping_queue_shows_unmapped_tasks(self):
views.invalidate_task_list_count_cache()
task = self.task(mapped=False)
result = service.list_tasks(
self.session,
queue_bucket="pending_mapping",
page_size=100,
)
assert [item["id"] for item in result["items"]] == [task.id]
assert result["items"][0]["executionStatus"] == "pending_mapping"
def test_task_list_count_uses_short_ttl_cache_until_invalidated(self):
views.invalidate_task_list_count_cache()
mapping = self.mapping()
@@ -1068,6 +1124,60 @@ class TestSnapshotSync(_Base):
outbox = self.session.query(IntegrationOutbox).one()
assert outbox.payload_json["items"][0]["stateVersion"] == 1
def test_snapshot_before_clean_cutover_creates_legacy_task(self):
self.mapping()
setting = self.session.get(PlatformFulfillmentSetting, 1)
setting.clean_flow_started_at = NOW
self.session.commit()
service.sync_order_snapshot(
self.session,
{"data": self.snapshot(paidAt=(NOW - timedelta(hours=1)).isoformat())},
)
task = self.session.query(PlatformFulfillmentTask).one()
assert task.flow_version == 1
assert service.list_tasks(self.session, flow_version=2)["pagination"]["total"] == 0
assert service.list_tasks(self.session, flow_version=1)["pagination"]["total"] == 1
def test_legacy_task_is_frozen_against_snapshot_transitions(self):
task = self.task()
task.flow_version = 1
self.session.commit()
service.sync_order_snapshot(
self.session,
{"data": self.snapshot(orderStatus="refunded", douyuFulfillmentEnabled=False)},
)
self.session.refresh(task)
assert task.flow_version == 1
assert task.execution_status == "ready"
assert task.issue_code == ""
assert task.source_snapshot_json["orderStatus"] == "refunded"
def test_snapshot_after_clean_cutover_creates_clean_task(self):
self.mapping()
setting = self.session.get(PlatformFulfillmentSetting, 1)
setting.clean_flow_started_at = NOW - timedelta(hours=1)
self.session.commit()
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
task = self.session.query(PlatformFulfillmentTask).one()
assert task.flow_version == 2
def test_legacy_list_ignores_order_match_cutoff(self):
task = self.task()
task.flow_version = 1
task.paid_at = NOW - timedelta(days=10)
self.session.commit()
listed = service.list_tasks(self.session, flow_version=1)
assert listed["pagination"]["total"] == 1
assert listed["items"][0]["flowVersion"] == 1
def test_duplicate_snapshot_keeps_allocated_task_state(self):
self.mapping()
account = self.account("snapshot-allocated")
@@ -1140,6 +1250,30 @@ class TestSnapshotSync(_Base):
assert task.state_version == 2
assert task.next_allocate_at is None
def test_valid_snapshot_restores_source_cancelled_task(self):
self.mapping()
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
service.sync_order_snapshot(
self.session,
{"data": self.snapshot(douyuFulfillmentEnabled=False)},
)
task = self.session.query(PlatformFulfillmentTask).one()
assert task.execution_status == "cancelled"
assert task.issue_code == "source_cancelled"
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
self.session.refresh(task)
assert task.execution_status == "ready"
assert task.issue_code == ""
assert task.last_error == ""
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="source_order_restored")
.count()
== 1
)
def test_unpaid_snapshot_does_not_enter_live_fulfillment(self):
self.mapping()
@@ -3148,6 +3282,98 @@ class TestBindingAndCompletion(_Base):
== 0
)
def test_customer_profile_snapshot_is_applied_to_task(self):
task = self._allocated()
_apply_customer_profile(
task,
{
"customerRoleName": "小淋笨",
"customerPlatform": "wechat",
"customerSystem": "android",
"homeImages": [
{
"url": "https://order.example.com/a.png",
"thumbnailUrl": "https://order.example.com/a-thumb.png",
"objectKey": "douyu-homepage-screenshot/a.png",
}
],
"customerProfileUpdatedAt": "2026-11-24T12:00:00.000Z",
},
)
assert task.customer_role_name == "小淋笨"
assert task.customer_platform == "wechat"
assert task.customer_system == "android"
assert task.customer_home_images[0]["objectKey"].endswith("a.png")
assert task.customer_profile_updated_at is not None
def test_customer_profile_with_home_image_is_saved_and_compared(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "小淋笨"
account.game_channel = "微信 · 安卓(android)"
self.session.commit()
detail = service.save_customer_profile(
self.session,
task_id=task.id,
customer_role_name="小淋笨",
platform="wechat",
system="android",
home_images=[
{
"url": "https://example.com/customer-home.png",
"thumbnail_url": "https://example.com/customer-home-thumb.png",
"object_key": "collect-material/customer-home.png",
}
],
)
self.session.refresh(task)
profile = detail["customerProfile"]
assert task.customer_role_name == "小淋笨"
assert task.customer_home_images[0]["url"].endswith("customer-home.png")
assert profile["roleMatched"] is True
assert profile["channelMatched"] is True
assert profile["homeImages"][0]["thumbnailUrl"].endswith("thumb.png")
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="customer_profile_saved")
.count()
== 1
)
def test_customer_profile_matches_online_qq_channel_label(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "手Q角色"
account.game_channel = "手Q · 苹果(iOS)"
self.session.commit()
detail = service.save_customer_profile(
self.session,
task_id=task.id,
customer_role_name="手Q角色",
platform="qq",
system="ios",
home_images=[{"url": "https://example.com/qq-home.png"}],
)
assert detail["customerProfile"]["channelMatched"] is True
def test_customer_profile_requires_home_image(self):
task = self._allocated()
with pytest.raises(HTTPException) as exc_info:
service.save_customer_profile(
self.session,
task_id=task.id,
customer_role_name="小淋笨",
platform="wechat",
system="android",
home_images=[],
)
assert exc_info.value.status_code == 409
assert "主页截图" in str(exc_info.value.detail)
def test_manual_confirm_rejects_role_not_currently_bound(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
@@ -3519,6 +3745,7 @@ class TestBindingAndCompletion(_Base):
def test_customer_start_queues_allocation_without_sync_network(self, monkeypatch):
task = self.task()
self.complete_customer_profile(task)
calls: list[list[int]] = []
monkeypatch.setattr(
"web.backend.services.platform_fulfillment.auto_allocator.wake_auto_allocator",
@@ -3540,6 +3767,7 @@ class TestBindingAndCompletion(_Base):
def test_customer_start_creates_one_binding_task_and_links_platform(self, monkeypatch):
task = self._allocated()
self.complete_customer_profile(task)
monkeypatch.setattr(
service.binding,
"enqueue_execution_job",
@@ -3565,6 +3793,7 @@ class TestBindingAndCompletion(_Base):
def test_customer_started_binding_does_not_capture_request_loop(self, monkeypatch):
task = self._allocated()
self.complete_customer_profile(task)
captured: dict[str, object] = {}
monkeypatch.setattr(
service.binding,
@@ -3577,6 +3806,17 @@ class TestBindingAndCompletion(_Base):
assert captured["job_type"] == "douyu_binding"
assert captured["batch_id"].startswith(f"pfbind-{task.id}-")
def test_customer_start_requires_game_home_profile(self):
task = self._allocated()
with pytest.raises(HTTPException) as exc_info:
asyncio.run(
service.customer_start_binding(self.session, task_id=task.id)
)
assert exc_info.value.status_code == 409
assert "游戏主页截图" in str(exc_info.value.detail)
def test_concurrent_start_binding_creates_one_task(self, monkeypatch):
task = self._allocated()
monkeypatch.setattr(
@@ -357,3 +357,44 @@ def test_schedule_retry_preserves_longer_capability_retry(db):
db.refresh(task)
assert task.next_allocate_at == retry_at
def test_auto_allocator_ignores_legacy_tasks(db):
actor = User(
username="auto-legacy-actor", password_hash="h", role="super_admin"
)
db.add_all(
[
actor,
PlatformFulfillmentSetting(
id=1,
lease_duration_minutes=None,
order_match_started_at=datetime.now(UTC) - timedelta(days=1),
),
PlatformFulfillmentTask(
source_system="order_site",
source_order_id="legacy-1",
source_order_item_id="legacy-1",
platform_order_id="AUTO-LEGACY",
internal_sku_key="skin",
commodity_id="commodity-1",
flow_version=1,
execution_status="ready",
binding_status="not_started",
exchange_status="not_started",
paid_at=datetime.now(UTC),
next_allocate_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
),
]
)
db.commit()
with patch.object(
auto_allocator.service,
"allocate_task",
side_effect=AssertionError("legacy tasks must not be auto allocated"),
):
result = auto_allocator.run_auto_allocation_once(db, limit=10)
assert result == {"checked": 0, "allocated": 0, "failed": 0}
@@ -521,6 +521,14 @@
"20261124_0130_douyu_api_max_amount.py": {
"revision": "20261124_0130",
"sha256": "fcaa64dfa069084fd6636b459b53f670376c79adf765f41646f05b6829ee9885"
},
"20261124_0131_fulfillment_customer_profile.py": {
"revision": "20261124_0131",
"sha256": "23f8780eb16a689a5f929f3f1e1865e84c0896dbde70be6bbffb0ef77d06d587"
},
"20261124_0132_fulfillment_flow_version.py": {
"revision": "20261124_0132",
"sha256": "c32ae403de640251e4ae8d86bd0948c189c3580141f1454490b4798bb286e3a3"
}
}
}
@@ -0,0 +1,64 @@
"""直播账号履约保存 order_site 客户资料与主页截图。
客户领取页改为必填主页截图;order_site 通过 integration API 推送到 live-hub,
履约工作台直接展示并和绑定角色比对,不再由客服手动索要。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261124_0131"
down_revision: str | None = "20261124_0130"
branch_labels: str | None = None
depends_on: str | None = None
TABLE = "platform_fulfillment_tasks"
COLUMNS = {
"customer_role_name": sa.String(length=128),
"customer_platform": sa.String(length=16),
"customer_system": sa.String(length=16),
"customer_home_images": sa.JSON(),
"customer_profile_updated_at": sa.DateTime(),
}
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:
text_columns = {
"customer_role_name",
"customer_platform",
"customer_system",
}
for name, column_type in COLUMNS.items():
if _column_exists(name):
continue
op.add_column(
TABLE,
sa.Column(
name,
column_type,
nullable=name not in text_columns,
server_default="" if name in text_columns else None,
),
)
def downgrade() -> None:
for name in reversed(tuple(COLUMNS)):
if _column_exists(name):
op.drop_column(TABLE, name)
@@ -0,0 +1,91 @@
"""直播履约 clean/legacy 流程分界。
- 存量任务统一标记为 legacy(flow_version=1);
- 迁移执行时设置 clean_flow_started_at,之后的订单进入 clean 流程;
- 已经是 clean 的任务不会再被自动调度逻辑回退。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261124_0132"
down_revision: str | None = "20261124_0131"
branch_labels: str | None = None
depends_on: str | None = None
TASK_TABLE = "platform_fulfillment_tasks"
SETTINGS_TABLE = "platform_fulfillment_settings"
def _column_exists(table: str, 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 _index_exists(table: str, name: str) -> bool:
conn = op.get_bind()
count = conn.execute(
sa.text(
"SELECT COUNT(*) FROM information_schema.statistics "
"WHERE table_schema = DATABASE() AND table_name = :table "
"AND index_name = :name"
),
{"table": table, "name": name},
).scalar()
return bool(count)
def upgrade() -> None:
if not _column_exists(TASK_TABLE, "flow_version"):
op.add_column(
TASK_TABLE,
sa.Column(
"flow_version",
sa.Integer(),
nullable=False,
server_default="1",
),
)
if not _index_exists(TASK_TABLE, "ix_platform_fulfillment_tasks_flow_version"):
op.create_index(
"ix_platform_fulfillment_tasks_flow_version",
TASK_TABLE,
["flow_version"],
)
if not _column_exists(SETTINGS_TABLE, "clean_flow_started_at"):
op.add_column(
SETTINGS_TABLE,
sa.Column("clean_flow_started_at", sa.DateTime(), nullable=True),
)
# 迁移执行时刻就是 Cutover;存量任务已在 flow_version 默认值 1。
op.execute(
sa.text(
"""
UPDATE platform_fulfillment_settings
SET clean_flow_started_at = UTC_TIMESTAMP()
WHERE id = 1 AND clean_flow_started_at IS NULL
"""
)
)
def downgrade() -> None:
if _column_exists(SETTINGS_TABLE, "clean_flow_started_at"):
op.drop_column(SETTINGS_TABLE, "clean_flow_started_at")
if _index_exists(TASK_TABLE, "ix_platform_fulfillment_tasks_flow_version"):
op.drop_index(
"ix_platform_fulfillment_tasks_flow_version",
table_name=TASK_TABLE,
)
if _column_exists(TASK_TABLE, "flow_version"):
op.drop_column(TASK_TABLE, "flow_version")
+28
View File
@@ -2313,6 +2313,11 @@ class PlatformFulfillmentSetting(Base):
nullable=False,
default=_utcnow,
)
# Clean Cutover 时间;之前是 legacy 任务,之后进入 clean 流程。
clean_flow_started_at: Mapped[datetime | None] = mapped_column(
UTCDateTime,
nullable=True,
)
updated_by: Mapped[int | None] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"),
nullable=True,
@@ -2408,6 +2413,14 @@ class PlatformFulfillmentTask(Base):
source_fulfillment_id: Mapped[str] = mapped_column(
String(64), nullable=False, default="", server_default=""
)
# 1 = 历史存量,只允许人工处理;2 = Clean Cutover 后的新单。
flow_version: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=2,
server_default="1",
index=True,
)
platform_order_id: Mapped[str] = mapped_column(
String(128), nullable=False, default="", server_default=""
)
@@ -2467,6 +2480,21 @@ class PlatformFulfillmentTask(Base):
classification_source: Mapped[str] = mapped_column(
String(24), nullable=False, default="unknown", server_default="unknown"
)
# 客户在 order_site 领取页填写的资料。图片存 order_site 文件 URL,
# live-hub 只做展示和绑定比对,不再让客服手动索要主页截图。
customer_role_name: Mapped[str] = mapped_column(
String(128), nullable=False, default="", server_default=""
)
customer_platform: Mapped[str] = mapped_column(
String(16), nullable=False, default="", server_default=""
)
customer_system: Mapped[str] = mapped_column(
String(16), nullable=False, default="", server_default=""
)
customer_home_images: Mapped[list | None] = mapped_column(JSON, nullable=True)
customer_profile_updated_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
account_id: Mapped[int | None] = mapped_column(
ForeignKey("accounts.id", ondelete="SET NULL"), nullable=True, index=True
)
@@ -80,6 +80,7 @@ def list_tasks(
status: str = Query("", max_length=32),
queue_bucket: str = Query("", max_length=32),
sale_mode: str = Query("", max_length=16),
flow_version: int | None = Query(None, ge=1, le=2),
keyword: str = Query("", max_length=200),
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
@@ -92,6 +93,7 @@ def list_tasks(
status=status,
queue_bucket=queue_bucket,
sale_mode=sale_mode,
flow_version=flow_version,
keyword=keyword,
page=page,
page_size=page_size,
@@ -17,6 +17,7 @@ from ..database import get_db
from ..models import IntegrationInbox
from ..schemas import (
PlatformFulfillmentCustomerBindingAction,
PlatformFulfillmentCustomerProfileRequest,
PlatformFulfillmentCustomerSessionBatchRequest,
PlatformFulfillmentCustomerSessionRequest,
)
@@ -132,6 +133,26 @@ def ensure_customer_session(
)
@router.post(
"/customer-sessions/{task_id}/profile",
dependencies=[Depends(require_integration_key)],
)
def save_customer_profile(
task_id: int,
req: PlatformFulfillmentCustomerProfileRequest,
db: Session = Depends(get_db),
) -> dict[str, Any]:
"""接 order_site 客户领取页资料与主页截图;order_site 端保证必填。"""
return service.save_customer_profile(
db,
task_id=task_id,
customer_role_name=req.customer_role_name,
platform=req.platform,
system=req.system,
home_images=[item.model_dump() for item in req.home_images],
)
@router.post(
"/customer-sessions/{task_id}/binding/start",
dependencies=[Depends(require_integration_key)],
+15
View File
@@ -1762,6 +1762,21 @@ class PlatformFulfillmentCustomerSessionRequest(BaseModel):
platform_order_id: str = Field(default="", max_length=255)
class PlatformFulfillmentCustomerImage(BaseModel):
url: str = Field(..., min_length=1, max_length=2048)
thumbnail_url: str = Field("", max_length=2048)
object_key: str = Field("", max_length=512)
class PlatformFulfillmentCustomerProfileRequest(BaseModel):
customer_role_name: str = Field(..., min_length=1, max_length=128)
platform: str = Field(..., pattern="^(wechat|qq)$")
system: str = Field(..., pattern="^(ios|android)$")
home_images: list[PlatformFulfillmentCustomerImage] = Field(
..., min_length=1, max_length=5
)
class PlatformFulfillmentCustomerBindingAction(BaseModel):
force_refresh: bool = False
@@ -893,6 +893,15 @@ def create_order(
return order
PLATFORM_PROJECTED_FIELDS = {
"order_no",
"account_username",
"gift_name",
"commodity_id",
"required_points",
}
def update_order(
db: Session,
current: User,
@@ -950,6 +959,24 @@ def update_order(
if new != old:
changes[field] = {"old": old, "new": new}
if (
order.source_type == SOURCE_TYPE_PLATFORM_FULFILLMENT
and current.role != "super_admin"
):
# 平台来源台账单是履约任务的投影:订单号/商品/积分/账号由平台维护。
# 超级管理员保留全部修正权限;普通运营/客服只能走接管转人工。
# 账号变更只有显式“接管转人工”才允许,避免协作页静默改出两个账号。
projected = PLATFORM_PROJECTED_FIELDS.intersection(changes)
if "account_username" in projected and takeover_platform_lease:
projected.discard("account_username")
if projected:
raise CollabError(
"本单来自直播账号履约,订单号/商品/积分/账号由履约工作台维护;"
"确需改账号请先走“接管并转人工”",
status_code=409,
code="platform_projection_readonly",
)
if order.succeeded_at is not None:
locked_changes = SUCCESS_PURCHASE_FIELDS.intersection(changes)
if locked_changes:
@@ -1074,6 +1101,17 @@ def set_account(
_assert_mutable(order)
_assert_success_account_change_allowed(current, order)
_assert_version(order, expected_version)
if (
order.source_type == SOURCE_TYPE_PLATFORM_FULFILLMENT
and current.role != "super_admin"
and not takeover_platform_lease
):
raise CollabError(
"本单来自直播账号履约,账号由履约工作台维护;"
"确需更换账号请确认“接管并转人工”",
status_code=409,
code="platform_projection_readonly",
)
account = account_by_username(db, username)
if account is None:
raise CollabError("斗鱼账号不存在", code="account_not_found")
@@ -10,12 +10,13 @@ from datetime import UTC, datetime, timedelta
from typing import Any
from loguru import logger
from sqlalchemy import or_
from sqlalchemy import func, or_
from sqlalchemy.orm import Session
from ...database import WorkerSessionLocal
from ...models import PlatformFulfillmentTask
from . import service
from .common import FLOW_VERSION_CLEAN, _has_game_home_profile
DEFAULT_INTERVAL_SECONDS = 20
DEFAULT_MIN_INTERVAL_SECONDS = 5
@@ -138,6 +139,8 @@ def run_auto_allocation_once(
due_cutoff = moment + timedelta(seconds=1)
query = db.query(PlatformFulfillmentTask).filter(
PlatformFulfillmentTask.execution_status == "ready",
# 存量任务只允许人工处理,自动选号只服务 Clean Cutover 之后的新单。
PlatformFulfillmentTask.flow_version == FLOW_VERSION_CLEAN,
PlatformFulfillmentTask.account_id.is_(None),
PlatformFulfillmentTask.commodity_id != "",
or_(
@@ -191,6 +194,8 @@ def run_auto_allocation_once(
if allocated_task is not None:
allocated_task.next_allocate_at = None
db.commit()
if not _has_game_home_profile(allocated_task):
continue
try:
service.start_binding_sync(
db,
@@ -277,6 +282,10 @@ def start_allocated_bindings_once(
PlatformFulfillmentTask.binding_status == "not_started",
PlatformFulfillmentTask.account_id.isnot(None),
PlatformFulfillmentTask.lease_id.isnot(None),
PlatformFulfillmentTask.customer_role_name != "",
PlatformFulfillmentTask.customer_platform != "",
PlatformFulfillmentTask.customer_system != "",
func.json_length(PlatformFulfillmentTask.customer_home_images) > 0,
)
.order_by(
PlatformFulfillmentTask.updated_at.asc(), PlatformFulfillmentTask.id.asc()
@@ -289,6 +298,8 @@ def start_allocated_bindings_once(
actor = service._integration_actor(db)
started = 0
for task in rows:
if not _has_game_home_profile(task):
continue
try:
service.start_binding_sync(
db,
@@ -21,6 +21,8 @@ from ..douyu_account_state import DouyuLiveAccountState
TARGET_PLATFORM = "douyu"
SCOPE_ELITE = "elite"
FLOW_VERSION_LEGACY = 1
FLOW_VERSION_CLEAN = 2
BINDING_COOLDOWN_ISSUES = frozenset({"account_role_cooldown", "customer_role_cooldown"})
ACTIVE_STATUSES = {
"ready",
@@ -139,6 +141,21 @@ def _order_snapshot_from_event(payload: dict[str, Any]) -> dict[str, Any]:
return data if isinstance(data, dict) else payload
def _has_game_home_profile(task: PlatformFulfillmentTask) -> bool:
"""Clean 任务必须同时有游戏角色、登录方式、系统和至少一张主页截图。"""
images = task.customer_home_images or []
return bool(
str(task.customer_role_name or "").strip()
and str(task.customer_platform or "").strip() in {"wechat", "qq"}
and str(task.customer_system or "").strip() in {"ios", "android"}
and isinstance(images, list)
and any(
isinstance(item, dict) and str(item.get("url") or "").strip()
for item in images
)
)
def _order_match_started_at(db: Session) -> datetime | None:
row = (
db.query(PlatformFulfillmentSetting)
@@ -148,6 +165,33 @@ def _order_match_started_at(db: Session) -> datetime | None:
return row.order_match_started_at if row is not None else None
def _clean_flow_started_at(db: Session) -> datetime | None:
row = (
db.query(PlatformFulfillmentSetting)
.filter(PlatformFulfillmentSetting.id == 1)
.first()
)
return row.clean_flow_started_at if row is not None else None
def _flow_version_for_order(
db: Session,
*,
paid_at: datetime | None,
created_at: datetime | None,
) -> int:
"""按订单支付/创建时间划分 legacy/clean,避免旧订单补建任务混入新流程。"""
cutoff = _clean_flow_started_at(db)
basis = paid_at or created_at
if cutoff is None or basis is None:
return FLOW_VERSION_CLEAN
if cutoff.tzinfo is None:
cutoff = cutoff.replace(tzinfo=UTC)
if basis.tzinfo is None:
basis = basis.replace(tzinfo=UTC)
return FLOW_VERSION_LEGACY if basis < cutoff else FLOW_VERSION_CLEAN
def _apply_order_match_cutoff(
query,
match_started_at: datetime | None,
@@ -2,6 +2,7 @@
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from fastapi import HTTPException
@@ -16,12 +17,15 @@ from .binding import (
refresh_binding,
start_binding,
)
from .common import FLOW_VERSION_CLEAN, _has_game_home_profile
from .order_sync import sync_order_item_ids
from .repository import (
_find_customer_task,
_integration_actor,
_load_task,
_load_task_for_update,
)
from .runtime import _append_event
from .views import customer_binding_out
@@ -61,6 +65,57 @@ def ensure_customer_session(
return customer_binding_out(db, task.id)
def save_customer_profile(
db: Session,
*,
task_id: int,
customer_role_name: str,
platform: str,
system: str,
home_images: list[dict[str, str]],
commit: bool = True,
) -> dict[str, Any]:
"""保存 order_site 客户资料;至少一张主页截图由 order_site 端强制。"""
task = _load_task_for_update(db, task_id)
if task.execution_status in {"completed", "cancelled"}:
raise HTTPException(status_code=409, detail="订单已结束,不能修改客户资料")
images = []
for item in home_images[:5]:
url = str(item.get("url") or "").strip()
if not url:
continue
images.append(
{
"url": url[:2048],
"thumbnailUrl": str(item.get("thumbnail_url") or item.get("thumbnailUrl") or url)[:2048],
"objectKey": str(item.get("object_key") or item.get("objectKey") or "")[:512],
}
)
if not images:
raise HTTPException(status_code=409, detail="客户主页截图至少需要 1 张")
task.customer_role_name = str(customer_role_name or "").strip()[:128]
task.customer_platform = str(platform or "").strip()[:16]
task.customer_system = str(system or "").strip()[:16]
task.customer_home_images = images
task.customer_profile_updated_at = datetime.now(UTC)
task.updated_at = datetime.now(UTC)
_append_event(
db,
task.id,
"customer_profile_saved",
actor_type="integration",
detail={
"customerRoleName": task.customer_role_name,
"platform": task.customer_platform,
"system": task.customer_system,
"homeImageCount": len(images),
},
)
if commit:
db.commit()
return customer_binding_out(db, task.id)
async def customer_start_binding(
db: Session,
*,
@@ -72,6 +127,8 @@ async def customer_start_binding(
return customer_binding_out(db, task.id)
if task.issue_code == "mapping_missing":
return customer_binding_out(db, task.id)
if task.flow_version == FLOW_VERSION_CLEAN and not _has_game_home_profile(task):
raise HTTPException(status_code=409, detail="请先提交游戏角色和游戏主页截图")
if not task.account_id or not task.lease_id:
from .auto_allocator import wake_auto_allocator
@@ -21,8 +21,10 @@ from ..external_order_source import (
)
from .common import (
AUTO_SYNC_INTERVAL_SECONDS,
FLOW_VERSION_LEGACY,
SCOPE_ELITE,
TARGET_PLATFORM,
_flow_version_for_order,
_jsonable,
_now,
_order_match_started_at,
@@ -42,6 +44,72 @@ _AUTO_SYNC_LOCK = threading.Lock()
_AUTO_SYNC_LAST_ATTEMPT = float("-inf")
def _apply_customer_profile(
task: PlatformFulfillmentTask,
snapshot: dict[str, Any],
) -> None:
"""order_site contractVersion=3 快照里的客户资料和主页截图。"""
keys = {
"customerRoleName",
"customer_role_name",
"homeImages",
"home_images",
}
if not keys.intersection(snapshot):
return
task.customer_role_name = str(
_snapshot_value(snapshot, "customerRoleName", "customer_role_name")
or ""
)[:128]
task.customer_platform = str(
_snapshot_value(snapshot, "customerPlatform", "customer_platform")
or ""
)[:16]
task.customer_system = str(
_snapshot_value(snapshot, "customerSystem", "customer_system")
or ""
)[:16]
raw_images = _snapshot_value(
snapshot,
"homeImages",
"home_images",
default=[],
)
images: list[dict[str, str]] = []
if isinstance(raw_images, list):
for item in raw_images[:5]:
if isinstance(item, str):
url = item.strip()
if url:
images.append({"url": url[:2048], "thumbnailUrl": url[:2048], "objectKey": ""})
continue
if not isinstance(item, dict):
continue
url = str(item.get("url") or "").strip()
if not url:
continue
images.append(
{
"url": url[:2048],
"thumbnailUrl": str(
item.get("thumbnailUrl") or item.get("thumbnail_url") or url
)[:2048],
"objectKey": str(
item.get("objectKey") or item.get("object_key") or ""
)[:512],
}
)
task.customer_home_images = images or None
task.customer_profile_updated_at = _parse_snapshot_datetime(
_snapshot_value(
snapshot,
"customerProfileUpdatedAt",
"customer_profile_updated_at",
default=None,
)
)
def _upsert_order_snapshot(
db: Session,
snapshot: dict[str, Any],
@@ -91,6 +159,10 @@ def _upsert_order_snapshot(
.first()
)
created = task is None
if task is not None and task.flow_version == FLOW_VERSION_LEGACY:
# 历史任务冻结:只保留来源快照,不参与任何自动状态迁移。
task.source_snapshot_json = _jsonable(snapshot)
return task, created, False
if task is None:
task = PlatformFulfillmentTask(
source_system="order_site",
@@ -115,6 +187,11 @@ def _upsert_order_snapshot(
),
target_platform=TARGET_PLATFORM,
scope=SCOPE_ELITE,
flow_version=_flow_version_for_order(
db,
paid_at=paid_at,
created_at=order_created_at,
),
created_at=_now(),
updated_at=_now(),
)
@@ -150,11 +227,7 @@ def _upsert_order_snapshot(
task.required_points,
task.issue_code,
)
if task.execution_status in {"completed", "cancelled"}:
task.source_snapshot_json = _jsonable(snapshot)
return task, created, False
previous_execution_status = task.execution_status
_apply_customer_profile(task, snapshot)
terminal = (
terminal_order
or _snapshot_value(
@@ -179,6 +252,30 @@ def _upsert_order_snapshot(
)
is False
)
if task.execution_status in {"completed", "cancelled"}:
# 历史“停用配置”的旧快照可能先到,随后开启配置的新快照又到;
# 系统原因取消的任务允许被后续有效快照恢复。用户取消/完成的仍保持终态。
if (
task.execution_status == "cancelled"
and task.issue_code == "source_cancelled"
and not terminal
):
task.execution_status = "pending_mapping"
task.issue_code = ""
task.last_error = ""
task.next_allocate_at = None
task.completed_at = None
_append_event(
db,
task.id,
"source_order_restored",
detail={"reason": "valid_snapshot_after_source_cancel"},
)
else:
task.source_snapshot_json = _jsonable(snapshot)
return task, created, False
previous_execution_status = task.execution_status
task.platform_order_id = str(
_snapshot_value(snapshot, "platformOrderId", "platform_order_id", default="")
@@ -448,6 +545,11 @@ def _sync_pending_tasks(
source_order_id=str(row.get("source_order_id") or ""),
source_order_item_id=item_id,
source_fulfillment_id=str(row.get("source_fulfillment_id") or ""),
flow_version=_flow_version_for_order(
db,
paid_at=_parse_snapshot_datetime(row.get("paid_at")),
created_at=_now(),
),
created_at=_now(),
updated_at=_now(),
)
@@ -481,6 +583,7 @@ def _sync_pending_tasks(
task.target_platform = TARGET_PLATFORM
task.scope = SCOPE_ELITE
task.source_snapshot_json = _jsonable(row)
_apply_customer_profile(task, row)
task.updated_at = _now()
if task.account_id is None and task.execution_status in {
"pending_mapping",
@@ -67,6 +67,7 @@ from .customer import (
customer_refresh_bindings,
customer_start_binding,
ensure_customer_session,
save_customer_profile,
)
from .lifecycle import (
cancel_task,
@@ -173,6 +174,7 @@ __all__ = [
"reset_task_binding",
"restore_cancelled_task",
"restore_mapping",
"save_customer_profile",
"set_mapping_enabled",
"start_binding",
"sync_active_task_from_account_binding",
@@ -79,6 +79,7 @@ def _count_cache_key(
status: str,
queue_bucket: str,
sale_mode: str,
flow_version: int | None,
keyword: str,
) -> tuple[Any, ...]:
return (
@@ -86,6 +87,7 @@ def _count_cache_key(
status,
queue_bucket,
sale_mode,
flow_version,
keyword.strip(),
)
@@ -209,25 +211,32 @@ def list_tasks(
status: str = "",
queue_bucket: str = "",
sale_mode: str = "",
flow_version: int | None = None,
keyword: str = "",
page: int = 1,
page_size: int = 20,
) -> dict[str, Any]:
cutoff = _order_match_started_at(db)
query = db.query(PlatformFulfillmentTask)
query = _apply_order_match_cutoff(query, cutoff)
query = query.filter(
or_(
PlatformFulfillmentTask.commodity_mapping_id.isnot(None),
PlatformFulfillmentTask.commodity_id != "",
if flow_version is not None:
query = query.filter(PlatformFulfillmentTask.flow_version == flow_version)
# 历史任务不受订单起算时间限制,否则很多旧单在工作台里永远看不到。
if flow_version != 1:
query = _apply_order_match_cutoff(query, cutoff)
# “全部”和“待映射”都要展示未映射任务,不能再套映射存在条件。
if queue_bucket not in {"all", "pending_mapping"}:
query = query.filter(
or_(
PlatformFulfillmentTask.commodity_mapping_id.isnot(None),
PlatformFulfillmentTask.commodity_id != "",
)
)
)
mode_filter = classification.normalize_sale_mode(sale_mode)
if sale_mode and mode_filter != "unknown":
query = query.filter(PlatformFulfillmentTask.sale_mode == mode_filter)
elif sale_mode == "unknown":
query = query.filter(PlatformFulfillmentTask.sale_mode == "unknown")
if queue_bucket:
if queue_bucket and queue_bucket != "all":
now = datetime.now(UTC)
if queue_bucket == classification.QUEUE_CANCELLED:
query = query.filter(
@@ -308,6 +317,7 @@ def list_tasks(
status=status,
queue_bucket=queue_bucket,
sale_mode=sale_mode,
flow_version=flow_version,
keyword=keyword,
),
)
@@ -424,6 +434,7 @@ def _task_out(
"goodsName": goods_name,
"requiredPoints": task.required_points,
"saleMode": sale_mode,
"flowVersion": int(task.flow_version or 1),
"campaignKey": task.campaign_key,
"campaignName": task.campaign_name,
"offerAvailableFrom": task.offer_available_from,
@@ -506,6 +517,7 @@ def _task_out(
if include_qr and bind_task is not None
else None
),
"customerProfile": _customer_profile_out(task, account, binding),
"exchangeTaskId": exchange_task_id,
"exchangeResultImage": (
{
@@ -690,6 +702,63 @@ def _customer_binding_queue_state(
return "preparing", 1000
def _customer_profile_out(
task: PlatformFulfillmentTask,
account: Account | None,
binding,
) -> dict[str, Any] | None:
"""客户资料 + 与平台当前/确认角色的绑定比对。"""
role = str(task.customer_role_name or "").strip()
images = list(task.customer_home_images or [])
if not role and not images:
return None
platform_role = str(binding.effective_role_name or "").strip()
if not platform_role and account is not None:
platform_role = str(account.game_name or "").strip()
role_matched: bool | None = None
if role and platform_role:
role_matched = role == platform_role
channel_matched: bool | None = None
# 线上账号渠道写作「微信 / 手Q」,QQ 不能直接拿 "QQ" 去比。
customer_channel = " ".join(
[
"微信"
if task.customer_platform == "wechat"
else ("手Q" if task.customer_platform == "qq" else ""),
"苹果"
if task.customer_system == "ios"
else ("安卓" if task.customer_system == "android" else ""),
]
).strip()
account_channel = str(
binding.effective_channel
or (account.game_channel if account is not None else "")
or ""
)
if customer_channel and account_channel:
channel_matched = all(part in account_channel for part in customer_channel.split())
if role and not platform_role:
message = "客户已填角色,平台还未识别绑定角色"
elif role_matched is True and channel_matched is not False:
message = "客户资料与平台角色一致"
elif role_matched is False or channel_matched is False:
message = "客户资料与平台角色不一致,请核对绑定"
else:
message = "客户资料已收到,等待平台识别角色"
return {
"roleName": role,
"platform": str(task.customer_platform or ""),
"system": str(task.customer_system or ""),
"homeImages": images,
"updatedAt": _jsonable(task.customer_profile_updated_at),
"platformRoleName": platform_role,
"platformChannel": account_channel,
"roleMatched": role_matched,
"channelMatched": channel_matched,
"message": message,
}
def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
"""面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。"""
task = _load_task(db, task_id)
@@ -754,6 +823,7 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
"queueLane": bind_task.queue_lane if bind_task else "",
"accepted": False,
"stateVersion": int(task.state_version or 0),
"customerProfile": _customer_profile_out(task, account, binding),
"completedAt": _jsonable(task.completed_at),
"updatedAt": _jsonable(task.updated_at),
}
@@ -53,6 +53,7 @@ export const platformFulfillmentApi = {
status?: string;
queue_bucket?: string;
sale_mode?: string;
flow_version?: number;
keyword?: string;
page?: number;
page_size?: number;
+21
View File
@@ -2532,6 +2532,25 @@ export interface PlatformFulfillmentBindingEvidence {
accountLock: PlatformFulfillmentBindingLock | null;
}
export interface PlatformFulfillmentCustomerImage {
url: string;
thumbnailUrl: string;
objectKey: string;
}
export interface PlatformFulfillmentCustomerProfile {
roleName: string;
platform: string;
system: string;
homeImages: PlatformFulfillmentCustomerImage[];
updatedAt: string | null;
platformRoleName: string;
platformChannel: string;
roleMatched: boolean | null;
channelMatched: boolean | null;
message: string;
}
export interface PlatformFulfillmentTask {
id: number;
sourceSystem: string;
@@ -2554,6 +2573,7 @@ export interface PlatformFulfillmentTask {
goodsName: string;
requiredPoints: number | null;
saleMode: 'presale' | 'direct' | 'manual' | 'unknown';
flowVersion: number;
campaignKey: string;
campaignName: string;
offerAvailableFrom: string | null;
@@ -2582,6 +2602,7 @@ export interface PlatformFulfillmentTask {
lease: { id: number; status: string; expiresAt: string | null } | null;
bindTask: PlatformFulfillmentBindTask | null;
bindingEvidence: PlatformFulfillmentBindingEvidence | null;
customerProfile: PlatformFulfillmentCustomerProfile | null;
exchangeTaskId: number | null;
exchangeResultImage: {
objectKey: string;
+1 -1
View File
@@ -88,7 +88,7 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
// 外部单协作:权限独立,客服没有 douyu:task 也要能进共享台账。
if (can('douyu:collab:view')) {
douyuItems.push({ key: '/douyu/collab', label: '外部单协作', icon: <FileExcelOutlined /> });
douyuItems.push({ key: '/douyu/collab', label: '斗鱼预售台账', icon: <FileExcelOutlined /> });
}
if (can('platform_fulfillment:view')) {
douyuItems.push({ key: '/platform-fulfillment', label: '直播账号履约', icon: <ThunderboltOutlined /> });
+119 -18
View File
@@ -167,6 +167,8 @@ export default function DouyuCollabPage() {
const [createOpen, setCreateOpen] = useState(false);
const [editing, setEditing] = useState<DouyuCollabOrder | null>(null);
const successfulPurchaseFieldsLocked = Boolean(editing?.succeeded_at && !isAdmin);
const isPlatformProjection = editing?.source_type === 'platform_fulfillment';
const platformProjectionLocked = isPlatformProjection && !isAdmin;
const [form, setForm] = useState<OrderFormState>(EMPTY_FORM);
const [lookup, setLookup] = useState<DouyuCollabAccountLookup | null>(null);
const lookupSeq = useRef(0);
@@ -201,6 +203,9 @@ export default function DouyuCollabPage() {
const [statusReason, setStatusReason] = useState('');
const [batchStatusRollback, setBatchStatusRollback] = useState(false);
const [statusBusy, setStatusBusy] = useState(false);
const [noteTarget, setNoteTarget] = useState<DouyuCollabOrder | null>(null);
const [noteValue, setNoteValue] = useState('');
const [noteSaving, setNoteSaving] = useState(false);
// 勾选导出 CK:明文只在弹窗 state 里,关闭即清空
const [ckExportOpen, setCkExportOpen] = useState(false);
@@ -473,6 +478,34 @@ export default function DouyuCollabPage() {
setCreateOpen(true);
};
const openNote = (order: DouyuCollabOrder) => {
if (!canEdit || order.is_archived) return;
setNoteTarget(order);
setNoteValue(order.remark || '');
};
const saveNote = async () => {
if (!noteTarget) return;
setNoteSaving(true);
try {
const saved = await douyuCollabApi.updateOrder(noteTarget.id, {
remark: noteValue.trim(),
expected_version: noteTarget.version,
});
setOrders((current) => current.map((row) => (
row.id === saved.id ? saved : row
)));
setDetail((current) => (current?.id === saved.id ? saved : current));
setNoteTarget(null);
setNoteValue('');
message.success(noteValue.trim() ? '备注已保存' : '备注已清空');
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setNoteSaving(false);
}
};
const openEdit = (order: DouyuCollabOrder) => {
setEditing(order);
setForm({
@@ -585,18 +618,22 @@ export default function DouyuCollabPage() {
) => {
if (editing) {
return douyuCollabApi.updateOrder(editing.id, {
order_no: form.order_no.trim(),
shop: form.shop.trim(),
owner_id: form.owner_id,
account_username: form.account_username.trim(),
gift_name: form.gift_name,
commodity_id: form.commodity_id,
required_points: form.required_points,
home_images: form.home_images,
remark: form.remark,
expected_version: editing.version,
confirm_purchase_change: confirmPurchaseChange,
takeover_platform_lease: takeoverPlatformLease,
...(!platformProjectionLocked
? {
order_no: form.order_no.trim(),
account_username: form.account_username.trim(),
gift_name: form.gift_name,
commodity_id: form.commodity_id,
required_points: form.required_points,
}
: {}),
});
}
return douyuCollabApi.createOrder({
@@ -1466,11 +1503,38 @@ export default function DouyuCollabPage() {
key: 'status',
title: '状态',
dataIndex: 'status',
width: 130,
width: 210,
render: (value: DouyuCollabStatus, row) => (
<Space size={4} wrap>
<Tag color={STATUS_META[value]?.color}>{row.status_label || STATUS_META[value]?.label || value}</Tag>
{row.is_archived && <Tag>已归档</Tag>}
<Space direction="vertical" size={2} style={{ width: '100%' }}>
<Space size={4} wrap>
<Tag color={STATUS_META[value]?.color}>{row.status_label || STATUS_META[value]?.label || value}</Tag>
{row.is_archived && <Tag>已归档</Tag>}
</Space>
<div
role={canEdit && !row.is_archived ? 'button' : undefined}
tabIndex={canEdit && !row.is_archived ? 0 : undefined}
title={row.remark || (canEdit && !row.is_archived ? '点击添加备注' : undefined)}
onClick={(event) => {
if (!canEdit || row.is_archived) return;
event.stopPropagation();
openNote(row);
}}
onKeyDown={(event) => {
if (!canEdit || row.is_archived) return;
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
openNote(row);
}
}}
style={{
cursor: canEdit && !row.is_archived ? 'text' : 'default',
minHeight: 22,
wordBreak: 'break-word',
lineHeight: 1.35,
}}
>
{row.remark || <Text type="secondary">+ 备注</Text>}
</div>
</Space>
),
},
@@ -1679,8 +1743,8 @@ export default function DouyuCollabPage() {
return (
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<div>
<h2 style={{ margin: 0 }}>斗鱼外部单协作</h2>
<Text type="secondary">订单挂内部斗鱼账号;输入用户名即可读取 CK、角色、鱼翅与手册积分</Text>
<h2 style={{ margin: 0 }}>斗鱼预售台账</h2>
<Text type="secondary">预售订单在直播账号履约工作台绑定完成后同步到这里;这里记录财务、异常和人工补登记</Text>
</div>
<Row gutter={[8, 8]}>
@@ -2114,6 +2178,19 @@ export default function DouyuCollabPage() {
destroyOnHidden
styles={{ body: { maxHeight: '78vh', overflowY: 'auto', paddingRight: 12 } }}
>
{isPlatformProjection && (
<Alert
style={{ marginBottom: 12 }}
type="info"
showIcon
message="本单来自直播账号履约工作台"
description={
isAdmin
? `履约任务 #${editing?.source_task_id ?? '-'} 的投影字段由履约工作台维护;管理员可直接修正,修正会记录审计。`
: `履约任务 #${editing?.source_task_id ?? '-'} 的账号、订单号、礼包和积分由履约工作台维护;这里只维护财务、备注和主页截图。`
}
/>
)}
{!editing && (
<Alert
style={{ marginBottom: 12 }}
@@ -2157,8 +2234,8 @@ export default function DouyuCollabPage() {
style={{ marginTop: 4 }}
value={form.order_no}
maxLength={64}
placeholder="外部订单编号"
disabled={successfulPurchaseFieldsLocked}
placeholder="订单编号"
disabled={successfulPurchaseFieldsLocked || platformProjectionLocked}
onChange={(event) => updateForm('order_no', event.target.value)}
/>
</div>
@@ -2200,12 +2277,12 @@ export default function DouyuCollabPage() {
<Input
value={form.account_username}
placeholder="输入内部斗鱼账号用户名,停止输入后自动查询"
disabled={successfulPurchaseFieldsLocked}
disabled={successfulPurchaseFieldsLocked || platformProjectionLocked}
onChange={(event) => updateForm('account_username', event.target.value)}
/>
<Button
loading={lookupLoading}
disabled={successfulPurchaseFieldsLocked}
disabled={successfulPurchaseFieldsLocked || platformProjectionLocked}
onClick={() => void handleLookup()}
>
查询账号
@@ -2229,6 +2306,7 @@ export default function DouyuCollabPage() {
/>
)}
{editing &&
!platformProjectionLocked &&
canReplaceAccount &&
!editing.succeeded_at &&
editing.status !== 'done' &&
@@ -2265,7 +2343,7 @@ export default function DouyuCollabPage() {
allowClear
value={form.gift_name}
options={giftNameOptions}
disabled={successfulPurchaseFieldsLocked}
disabled={successfulPurchaseFieldsLocked || platformProjectionLocked}
placeholder={
goodsPool.length || giftRecords.length
? '输入礼包名称,或选择已有礼包'
@@ -2281,7 +2359,7 @@ export default function DouyuCollabPage() {
optionFilterProp="label"
value={form.gift_name || undefined}
options={giftNameOptions}
disabled={successfulPurchaseFieldsLocked}
disabled={successfulPurchaseFieldsLocked || platformProjectionLocked}
placeholder={
giftNameOptions.length
? '选择礼包(由管理员统一维护)'
@@ -2307,7 +2385,7 @@ export default function DouyuCollabPage() {
min={0}
precision={0}
value={form.required_points}
disabled={!canManage || successfulPurchaseFieldsLocked}
disabled={!canManage || successfulPurchaseFieldsLocked || platformProjectionLocked}
placeholder={canManage ? '手动填写;选择礼包后自动带出' : '由管理员统一配置'}
onChange={(value) => updateForm('required_points', value ?? null)}
/>
@@ -2469,6 +2547,29 @@ export default function DouyuCollabPage() {
</Space>
</Modal>
<Modal
title="订单备注"
open={noteTarget !== null}
confirmLoading={noteSaving}
okText="保存备注"
cancelText="取消"
onOk={() => void saveNote()}
onCancel={() => {
setNoteTarget(null);
setNoteValue('');
}}
destroyOnHidden
>
<Input.TextArea
rows={5}
maxLength={512}
showCount
value={noteValue}
onChange={(event) => setNoteValue(event.target.value)}
placeholder="填写订单备注,保存后会记录到审计日志"
/>
</Modal>
<Modal
title={
batchStatusOpen
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import 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, Tag, Timeline, Typography } from 'antd';
import { Alert, Button, Card, Col, DatePicker, Descriptions, Drawer, Empty, Image, Input, InputNumber, Modal, QRCode, Row, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd';
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 { douyuApi, platformFulfillmentApi } from '../api/modules';
@@ -18,6 +18,22 @@ import { usePermissions } from '../hooks/usePermissions';
const { Text, Title } = Typography;
const CUSTOMER_PLATFORM_LABELS: Record<string, string> = {
wechat: '微信',
qq: 'QQ',
};
const CUSTOMER_SYSTEM_LABELS: Record<string, string> = {
ios: '苹果',
android: '安卓',
};
function customerMatchTone(profile: NonNullable<PlatformFulfillmentTask['customerProfile']>) {
if (profile.roleMatched === false || profile.channelMatched === false) return 'red';
if (profile.roleMatched === true && profile.channelMatched === true) return 'green';
return 'gold';
}
const STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'pending_mapping', label: '待映射' },
@@ -104,9 +120,23 @@ const MANUAL_REASON_LABELS: Record<string, string> = {
other_manual: '其他人工',
};
const SALE_MODE_TAB_STORAGE_KEY = 'platform_fulfillment_sale_mode_tab';
const QUEUE_BUCKET_OPTIONS = [
{ value: 'all', label: '全部' },
{ value: 'current', label: '当前待办' },
{ value: 'pending_mapping', label: '待映射' },
{ value: 'ready_for_fulfillment', label: '可履约' },
{ value: 'needs_action', label: '需要人工' },
{ value: 'completed', label: '已完成' },
{ value: 'cancelled', label: '已取消' },
];
const PRESALE_QUEUE_BUCKET_OPTIONS = [
{ value: 'all', label: '全部' },
{ value: 'current', label: '当前待办' },
{ value: 'presale_waiting', label: '预售待开放' },
{ value: 'pending_mapping', label: '待映射' },
{ value: 'ready_for_fulfillment', label: '可履约' },
{ value: 'needs_action', label: '需要人工' },
{ value: 'completed', label: '已完成' },
@@ -330,7 +360,7 @@ function eventDescription(event: { eventType: string; detail: Record<string, unk
return String(detail.reason || '已转人工处理');
}
if (event.eventType === 'released_to_manual') {
return `转人工原因:${String(detail.reason || '以外部单协作人工处理为准')}`;
return `转人工原因:${String(detail.reason || '以订单台账人工处理为准')}`;
}
if (event.eventType === 'task_cancelled') {
return `取消原因:${String(detail.reason || '人工取消')}`;
@@ -436,8 +466,16 @@ export default function PlatformFulfillmentPage() {
const user = getUser();
const navigate = useNavigate();
const { can } = usePermissions(user);
const [queueBucket, setQueueBucket] = useState('current');
const [saleModeFilter, setSaleModeFilter] = useState('');
const [queueBucket, setQueueBucket] = useState('all');
const [saleModeTab, setSaleModeTab] = useState<'direct' | 'presale' | 'unknown' | 'legacy'>(() => {
const saved = localStorage.getItem(SALE_MODE_TAB_STORAGE_KEY);
if (saved === 'presale' || saved === 'unknown' || saved === 'legacy') return saved;
return 'direct';
});
useEffect(() => {
localStorage.setItem(SALE_MODE_TAB_STORAGE_KEY, saleModeTab);
}, [saleModeTab]);
const [keyword, setKeyword] = useState('');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
@@ -521,13 +559,19 @@ export default function PlatformFulfillmentPage() {
const queueBackedStatus = queueBucket === 'current'
? 'unfinished'
: (['completed', 'cancelled'].includes(queueBucket) ? queueBucket : undefined);
const backendBucket = ['presale_waiting', 'ready_for_fulfillment', 'needs_action'].includes(queueBucket)
const backendBucket = [
'pending_mapping',
'presale_waiting',
'ready_for_fulfillment',
'needs_action',
].includes(queueBucket)
? queueBucket
: undefined;
const result = await platformFulfillmentApi.listTasks({
status: queueBackedStatus,
queue_bucket: backendBucket,
sale_mode: saleModeFilter || undefined,
queue_bucket: queueBucket === 'all' ? 'all' : backendBucket,
sale_mode: saleModeTab === 'legacy' ? undefined : saleModeTab,
flow_version: saleModeTab === 'legacy' ? 1 : 2,
keyword: keyword.trim() || undefined,
page,
page_size: pageSize,
@@ -539,7 +583,7 @@ export default function PlatformFulfillmentPage() {
} finally {
if (!silent) setLoading(false);
}
}, [keyword, page, pageSize, queueBucket, saleModeFilter]);
}, [keyword, page, pageSize, queueBucket, saleModeTab]);
const loadDetail = useCallback(async (taskId: number, silent = false) => {
if (!silent) setDetailLoading(true);
@@ -687,7 +731,7 @@ export default function PlatformFulfillmentPage() {
const result = await platformFulfillmentApi.syncCollab(taskIds);
const syncedOrderNo =
result.items.find((item) => item.action === 'created' || item.action === 'updated')?.orderNo || '';
const summary = `外部协作同步完成:新增 ${result.created},更新 ${result.updated}${
const summary = `斗鱼预售台账同步完成:新增 ${result.created},更新 ${result.updated}${
taskIds.length === 1 && syncedOrderNo ? `,订单 ${syncedOrderNo}` : ''
}`;
if (result.failed || result.skipped) {
@@ -1280,26 +1324,19 @@ export default function PlatformFulfillmentPage() {
{
title: '商品映射',
key: 'mapping',
width: 230,
width: 270,
render: (_, task) => (
<Space direction="vertical" size={2}>
<Space direction="vertical" size={3}>
<Text ellipsis title={task.commodityId}>
{task.goodsName || task.skuName || task.internalSkuKey || '未映射'}
</Text>
<Text type="secondary">{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}</Text>
</Space>
),
},
{
title: '分类',
key: 'classification',
width: 190,
render: (_, task) => (
<Space direction="vertical" size={3}>
<Space size={4}>
<Space size={6} wrap>
<Tag color={task.saleMode === 'presale' ? 'gold' : task.saleMode === 'direct' ? 'green' : 'default'}>
{SALE_MODE_LABELS[task.saleMode] || task.saleMode}
</Tag>
<Text type="secondary">
{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}
</Text>
</Space>
<Text type="secondary" ellipsis title={task.campaignName || task.campaignKey || '-'}>
{task.campaignName || task.campaignKey || '未设置活动批次'}
@@ -1336,7 +1373,7 @@ export default function PlatformFulfillmentPage() {
),
},
{
title: '绑定',
title: '用户角色绑定',
key: 'binding',
width: 180,
render: (_, task) => (
@@ -1353,6 +1390,31 @@ export default function PlatformFulfillmentPage() {
</Space>
),
},
{
title: '游戏主页',
key: 'customer_home_images',
width: 120,
render: (_, task) => {
const images = task.customerProfile?.homeImages || [];
if (images.length === 0) return <Text type="secondary">未上传</Text>;
return (
<Image.PreviewGroup items={images.map((item) => item.url)}>
<Space size={4} wrap>
{images.slice(0, 2).map((item, index) => (
<Image
key={`${item.objectKey || item.url}-${index}`}
src={item.thumbnailUrl || item.url}
width={44}
height={44}
style={{ objectFit: 'cover', borderRadius: 4 }}
alt={`游戏主页截图 ${index + 1}`}
/>
))}
</Space>
</Image.PreviewGroup>
);
},
},
{
title: '状态',
key: 'status',
@@ -1370,7 +1432,7 @@ export default function PlatformFulfillmentPage() {
),
},
{
title: '外部协作',
title: '斗鱼预售台账',
key: 'collab',
width: 150,
render: (_, task) =>
@@ -1414,20 +1476,23 @@ export default function PlatformFulfillmentPage() {
<Button size="small" onClick={() => setSelectedId(task.id)}>
详情
</Button>
<Button
size="small"
type={task.collabOrder ? 'default' : 'primary'}
icon={<LinkOutlined />}
loading={rowCollabSyncingId === task.id}
disabled={
!can('platform_fulfillment:use') ||
collabSyncing ||
(rowCollabSyncingId !== null && rowCollabSyncingId !== task.id)
}
onClick={() => void performCollabSync([task.id], task.id)}
>
同步外部单协作
</Button>
{saleModeTab === 'presale' ? (
<Button
size="small"
type={task.collabOrder ? 'default' : 'primary'}
icon={<LinkOutlined />}
loading={rowCollabSyncingId === task.id}
disabled={
!can('platform_fulfillment:use') ||
task.bindingStatus !== 'bound' ||
collabSyncing ||
(rowCollabSyncingId !== null && rowCollabSyncingId !== task.id)
}
onClick={() => void performCollabSync([task.id], task.id)}
>
同步到斗鱼预售台账
</Button>
) : null}
{task.executionStatus === 'pending_mapping' ? (
<Button size="small" type="primary" icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping(task)}>
配置映射
@@ -1490,6 +1555,22 @@ export default function PlatformFulfillmentPage() {
},
];
const centeredColumns = columns
.filter((column) => saleModeTab !== 'direct' || column.key !== 'collab')
.map((column) => ({
...column,
align: 'center' as const,
onHeaderCell: () => ({ style: { textAlign: 'center' as const } }),
}));
const selectedCollabReady =
selectedRowKeys.length > 0 &&
rows.filter((row) => selectedRowKeys.map(String).includes(String(row.id))).length ===
selectedRowKeys.length &&
rows
.filter((row) => selectedRowKeys.map(String).includes(String(row.id)))
.every((row) => row.bindingStatus === 'bound');
const actionButtons = selected ? (
<Space wrap>
{selected.bindTask?.qrUrl ? (
@@ -1531,7 +1612,7 @@ export default function PlatformFulfillmentPage() {
icon={<UserSwitchOutlined />}
onClick={() => {
setManualReleaseTarget(selected);
setManualReleaseReason('以外部单协作人工处理为准');
setManualReleaseReason('以订单台账人工处理为准');
}}
>
释放并转人工
@@ -1589,18 +1670,21 @@ export default function PlatformFulfillmentPage() {
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
商品映射
</Button>
<Button
icon={<LinkOutlined />}
loading={collabSyncing}
disabled={
!can('platform_fulfillment:use') ||
selectedRowKeys.length === 0 ||
rowCollabSyncingId !== null
}
onClick={() => void syncCollab()}
>
同步外部单协作{selectedRowKeys.length > 0 ? `(${selectedRowKeys.length})` : ''}
</Button>
{saleModeTab === 'presale' ? (
<Button
icon={<LinkOutlined />}
loading={collabSyncing}
disabled={
!can('platform_fulfillment:use') ||
selectedRowKeys.length === 0 ||
!selectedCollabReady ||
rowCollabSyncingId !== null
}
onClick={() => void syncCollab()}
>
同步到斗鱼预售台账{selectedRowKeys.length > 0 ? `(${selectedRowKeys.length})` : ''}
</Button>
) : null}
<Button type="primary" loading={syncing} icon={<SyncOutlined />} onClick={() => void sync()}>
同步待履约订单
</Button>
@@ -1608,6 +1692,40 @@ export default function PlatformFulfillmentPage() {
</Space>
</Card>
<Tabs
activeKey={saleModeTab}
onChange={(value) => {
const next =
value === 'presale'
? 'presale'
: value === 'unknown'
? 'unknown'
: value === 'legacy'
? 'legacy'
: 'direct';
setSaleModeTab(next);
if (next !== 'presale' && queueBucket === 'presale_waiting') {
setQueueBucket('current');
}
setSelectedRowKeys([]);
setPage(1);
}}
items={[
{ key: 'direct', label: '直接兑换' },
{ key: 'presale', label: '预售' },
{ key: 'unknown', label: '未分类' },
{ key: 'legacy', label: '历史任务' },
]}
/>
{saleModeTab === 'legacy' ? (
<Alert
type="warning"
showIcon
message="历史任务仅允许人工处理,不参与自动选号、自动重试和预售台账同步。"
/>
) : null}
<Card size="small">
<Space wrap style={{ marginBottom: 16 }}>
<Input.Search
@@ -1622,24 +1740,15 @@ export default function PlatformFulfillmentPage() {
/>
<Segmented
value={queueBucket}
options={QUEUE_BUCKET_OPTIONS}
options={
saleModeTab === 'presale' ? PRESALE_QUEUE_BUCKET_OPTIONS : QUEUE_BUCKET_OPTIONS
}
onChange={(value) => {
setQueueBucket(String(value));
setSelectedRowKeys([]);
setPage(1);
}}
/>
<Select
value={saleModeFilter}
options={[
{ value: '', label: '全部销售模式' },
...Object.entries(SALE_MODE_LABELS).map(([value, label]) => ({ value, label })),
]}
onChange={(value) => {
setSaleModeFilter(value);
setPage(1);
}}
style={{ width: 150 }}
/>
<Button icon={<ReloadOutlined />} onClick={() => void loadTasks()}>
刷新
</Button>
@@ -1647,7 +1756,7 @@ export default function PlatformFulfillmentPage() {
<Table<PlatformFulfillmentTask>
rowKey="id"
loading={loading}
columns={columns}
columns={centeredColumns}
dataSource={rows}
rowSelection={{
selectedRowKeys,
@@ -1788,7 +1897,7 @@ export default function PlatformFulfillmentPage() {
{bindingStatusLabel(selected.bindingStatus)}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="外部协作单" span={2}>
<Descriptions.Item label="斗鱼预售台账" span={2}>
{selected.collabOrder
? `${selected.collabOrder.orderNo} · ${collabStatusLabel(selected.collabOrder.status)}`
: '未同步'}
@@ -1798,6 +1907,65 @@ export default function PlatformFulfillmentPage() {
</Descriptions>
</Card>
<Card size="small" title="用户资料(order_site)">
{selected.customerProfile ? (
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="客户角色" span={2}>
{selected.customerProfile.roleName || '未填写'}
</Descriptions.Item>
<Descriptions.Item label="登录方式">
{CUSTOMER_PLATFORM_LABELS[selected.customerProfile.platform] || selected.customerProfile.platform || '-'}
</Descriptions.Item>
<Descriptions.Item label="系统">
{CUSTOMER_SYSTEM_LABELS[selected.customerProfile.system] || selected.customerProfile.system || '-'}
</Descriptions.Item>
<Descriptions.Item label="平台当前角色">
{selected.customerProfile.platformRoleName || '未识别'}
</Descriptions.Item>
<Descriptions.Item label="平台渠道">
{selected.customerProfile.platformChannel || '-'}
</Descriptions.Item>
<Descriptions.Item label="绑定比对" span={2}>
<Space wrap size={6}>
<Tag color={customerMatchTone(selected.customerProfile)}>
{selected.customerProfile.message}
</Tag>
{selected.customerProfile.updatedAt ? (
<Text type="secondary">更新 {formatTime(selected.customerProfile.updatedAt)}</Text>
) : null}
</Space>
</Descriptions.Item>
</Descriptions>
{selected.customerProfile.homeImages.length ? (
<Image.PreviewGroup
items={selected.customerProfile.homeImages.map((item) => item.url)}
>
<Space wrap size={8}>
{selected.customerProfile.homeImages.map((item, index) => (
<Image
key={`${item.objectKey || item.url}-${index}`}
src={item.thumbnailUrl || item.url}
width={96}
height={96}
style={{ objectFit: 'cover', borderRadius: 6 }}
alt={`游戏主页截图 ${index + 1}`}
/>
))}
</Space>
</Image.PreviewGroup>
) : (
<Text type="secondary">没有游戏主页截图</Text>
)}
</Space>
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description="客户尚未同步资料和游戏主页截图"
/>
)}
</Card>
<Card size="small" title="账号实时状态">
{selected.account ? (
<Descriptions bordered size="small" column={2}>