Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8aa4ea7342 | ||
|
|
b495a2d999 | ||
|
|
5c448bf954 | ||
|
|
1a02733cda | ||
|
|
aafac6e536 | ||
|
|
7dec3c4c48 | ||
|
|
9feb6f4bf4 | ||
|
|
628081986f | ||
|
|
ad74fdb743 | ||
|
|
56e9568fed | ||
|
|
8822f0ab42 | ||
|
|
292f61b56a | ||
|
|
70afd34b71 | ||
|
|
eb93e7aca2 | ||
|
|
6ec8248068 | ||
|
|
06a226f51f | ||
|
|
ee593fa5b4 | ||
|
|
9654df542f | ||
|
|
cea64cafec | ||
|
|
7a5d3ae9c8 | ||
|
|
77a881bdf8 |
@@ -413,3 +413,23 @@ alias 上的旧角色,不能把 `cjm` 的新角色写入账号库。
|
|||||||
| 2026-11-21 | 补充同名重绑、轮询退避、直接绑定识别和角色接口原始响应留档 |
|
| 2026-11-21 | 补充同名重绑、轮询退避、直接绑定识别和角色接口原始响应留档 |
|
||||||
| 2026-11-21 | 按最新 HAR 更新鱼翅余额/充值二维码/支付状态、积分 multipart、到期批次和积分流水协议 |
|
| 2026-11-21 | 按最新 HAR 更新鱼翅余额/充值二维码/支付状态、积分 multipart、到期批次和积分流水协议 |
|
||||||
| 2026-11-22 | 按成功/失败 HAR 重构绑定判定:已有 `bindAct=0` 可确认,`bindAct=1` 不误报,`-200001` 归为斗鱼账号冷却并保留旧角色 |
|
| 2026-11-22 | 按成功/失败 HAR 重构绑定判定:已有 `bindAct=0` 可确认,`bindAct=1` 不误报,`-200001` 归为斗鱼账号冷却并保留旧角色 |
|
||||||
|
|
||||||
|
## 精英宝典工作台:兑换图片与供应商直充上限
|
||||||
|
|
||||||
|
### 兑换图片默认隐藏
|
||||||
|
|
||||||
|
账号表“兑换图片”列不再默认展示历史兑换任务图片。只有**本页面本次发起过
|
||||||
|
交换任务**的账号才显示图片;刷新页面后历史图片继续保持隐藏。
|
||||||
|
|
||||||
|
前端用 `exchangeImageAccountIds` 记录本页发起的 `exchange_goods` /
|
||||||
|
`exchange_esports_goods` / `exchange_xpd_goods` 账号;列只在这些账号且最新
|
||||||
|
兑换成功时渲染图片。
|
||||||
|
|
||||||
|
### 供应商 API 直充单笔上限
|
||||||
|
|
||||||
|
`douyu_config.gold_api_max_amount`,默认 **800 鱼翅**。
|
||||||
|
|
||||||
|
- `精英宝典配置` 可修改;
|
||||||
|
- 充值金额输入框自动 clamp 到该值;
|
||||||
|
- 后端执行器在创建供应商订单前再次校验,超过上限直接失败,不会下单;
|
||||||
|
- 迁移 `20261124_0130_douyu_api_max_amount` 新增列并默认 800。
|
||||||
|
|||||||
@@ -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 等旧噪音逐条修数据;
|
||||||
|
- 新单人工队列只保留当前真实异常;
|
||||||
|
- 旧数据保留可查、可审计、可人工处理。
|
||||||
@@ -747,6 +747,83 @@ class TestDouyuCollabOrders:
|
|||||||
== 1
|
== 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):
|
def test_same_source_platform_lease_is_forced_to_collab_on_takeover(self):
|
||||||
task, lease = self._platform_task_lease()
|
task, lease = self._platform_task_lease()
|
||||||
order = collab.DouyuExternalOrder(
|
order = collab.DouyuExternalOrder(
|
||||||
|
|||||||
@@ -242,6 +242,30 @@ class TestDouyuGoldRechargeChannel:
|
|||||||
assert "pay_url" not in task_result
|
assert "pay_url" not in task_result
|
||||||
assert "sign" not in task_result["supplier_order"]
|
assert "sign" not in task_result["supplier_order"]
|
||||||
|
|
||||||
|
@patch("web.backend.services.douyu_runner_gold.FishFinRechargeClient")
|
||||||
|
def test_supplier_channel_rejects_amount_over_configured_max(self, client_class):
|
||||||
|
config = {
|
||||||
|
"gold_recharge_channel": "supplier_api",
|
||||||
|
"gold_api_product_id": "gold-product",
|
||||||
|
"gold_api_account_template_name": "斗鱼昵称",
|
||||||
|
"gold_api_max_amount": 800,
|
||||||
|
}
|
||||||
|
self.task.result = {"payload": {"amount": 801}}
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
self.runner._execute_create_gold_qr(
|
||||||
|
self.session,
|
||||||
|
self.task,
|
||||||
|
self.account,
|
||||||
|
"acf_uid=10001",
|
||||||
|
config,
|
||||||
|
)
|
||||||
|
|
||||||
|
client_class.assert_not_called()
|
||||||
|
self.session.refresh(self.task)
|
||||||
|
assert self.task.status == "failed"
|
||||||
|
assert "800" in self.task.message
|
||||||
|
|
||||||
@patch("web.backend.services.douyu_runner_gold.FishFinRechargeClient")
|
@patch("web.backend.services.douyu_runner_gold.FishFinRechargeClient")
|
||||||
def test_supplier_channel_rejects_account_without_nickname(self, client_class):
|
def test_supplier_channel_rejects_account_without_nickname(self, client_class):
|
||||||
self.account.nickname = ""
|
self.account.nickname = ""
|
||||||
@@ -355,6 +379,11 @@ class TestDouyuGoldRechargeChannel:
|
|||||||
dumped = res.model_dump()
|
dumped = res.model_dump()
|
||||||
assert dumped["gold_recharge_channel"] == "supplier_api"
|
assert dumped["gold_recharge_channel"] == "supplier_api"
|
||||||
assert dumped["peace_enabled"] is True
|
assert dumped["peace_enabled"] is True
|
||||||
|
assert dumped["gold_api_max_amount"] == 800
|
||||||
|
|
||||||
|
req_max = DouyuConfigUpdate(gold_api_max_amount=500)
|
||||||
|
res_max = update_config(req_max, db=self.session, current=admin_user)
|
||||||
|
assert res_max.model_dump()["gold_api_max_amount"] == 500
|
||||||
|
|
||||||
# 2. 切换回 wechat_qr
|
# 2. 切换回 wechat_qr
|
||||||
req2 = DouyuConfigUpdate(
|
req2 = DouyuConfigUpdate(
|
||||||
|
|||||||
@@ -45,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_0129"
|
HEAD_REVISION = "20261124_0132"
|
||||||
|
|
||||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||||
EXTRA_INDEXES = (
|
EXTRA_INDEXES = (
|
||||||
@@ -85,6 +85,12 @@ _LATER_ORM_COLUMNS = {
|
|||||||
"classification_source": "VARCHAR(24) NOT NULL DEFAULT 'unknown'",
|
"classification_source": "VARCHAR(24) NOT NULL DEFAULT 'unknown'",
|
||||||
"exchange_result_image_key": "VARCHAR(512) NOT NULL DEFAULT ''",
|
"exchange_result_image_key": "VARCHAR(512) NOT NULL DEFAULT ''",
|
||||||
"exchange_result_image_saved_at": "DATETIME NULL",
|
"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": {
|
"douyu_external_orders": {
|
||||||
"succeeded_at": "DATETIME NULL",
|
"succeeded_at": "DATETIME NULL",
|
||||||
@@ -407,6 +413,7 @@ class TestMigrationSmoke:
|
|||||||
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)
|
_add_account_platform_columns(mig_engine)
|
||||||
|
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
|
||||||
with Session(mig_engine) as session:
|
with Session(mig_engine) as session:
|
||||||
user = User(
|
user = User(
|
||||||
username="binding-sync-user",
|
username="binding-sync-user",
|
||||||
@@ -499,6 +506,7 @@ class TestMigrationSmoke:
|
|||||||
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)
|
_add_account_platform_columns(mig_engine)
|
||||||
|
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
|
||||||
with Session(mig_engine) as session:
|
with Session(mig_engine) as session:
|
||||||
user = User(
|
user = User(
|
||||||
username="false-binding-user",
|
username="false-binding-user",
|
||||||
@@ -617,6 +625,7 @@ class TestMigrationSmoke:
|
|||||||
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)
|
_add_account_platform_columns(mig_engine)
|
||||||
|
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
|
||||||
with Session(mig_engine) as session:
|
with Session(mig_engine) as session:
|
||||||
user = User(
|
user = User(
|
||||||
username="pending-link-user",
|
username="pending-link-user",
|
||||||
@@ -969,6 +978,7 @@ class TestMigrationSmoke:
|
|||||||
cfg.set_main_option("sqlalchemy.url", mig_url)
|
cfg.set_main_option("sqlalchemy.url", mig_url)
|
||||||
command.upgrade(cfg, "20261121_0106")
|
command.upgrade(cfg, "20261121_0106")
|
||||||
_add_account_platform_columns(mig_engine)
|
_add_account_platform_columns(mig_engine)
|
||||||
|
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
|
||||||
with Session(mig_engine) as session:
|
with Session(mig_engine) as session:
|
||||||
user = User(
|
user = User(
|
||||||
username="repair-0107-user",
|
username="repair-0107-user",
|
||||||
@@ -1431,6 +1441,7 @@ class TestMigrationSmoke:
|
|||||||
cfg.set_main_option("sqlalchemy.url", mig_url)
|
cfg.set_main_option("sqlalchemy.url", mig_url)
|
||||||
command.upgrade(cfg, "20261118_0089")
|
command.upgrade(cfg, "20261118_0089")
|
||||||
_add_account_platform_columns(mig_engine)
|
_add_account_platform_columns(mig_engine)
|
||||||
|
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
|
||||||
|
|
||||||
with Session(mig_engine) as session:
|
with Session(mig_engine) as session:
|
||||||
user = User(
|
user = User(
|
||||||
@@ -1572,6 +1583,7 @@ class TestMigrationSmoke:
|
|||||||
cfg.set_main_option("sqlalchemy.url", mig_url)
|
cfg.set_main_option("sqlalchemy.url", mig_url)
|
||||||
command.upgrade(cfg, "20261118_0091")
|
command.upgrade(cfg, "20261118_0091")
|
||||||
_add_account_platform_columns(mig_engine)
|
_add_account_platform_columns(mig_engine)
|
||||||
|
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
|
||||||
|
|
||||||
with Session(mig_engine) as session:
|
with Session(mig_engine) as session:
|
||||||
account = Account(
|
account = Account(
|
||||||
@@ -1712,6 +1724,7 @@ class TestMigrationSmoke:
|
|||||||
cfg.set_main_option("sqlalchemy.url", mig_url)
|
cfg.set_main_option("sqlalchemy.url", mig_url)
|
||||||
command.upgrade(cfg, "20261119_0097")
|
command.upgrade(cfg, "20261119_0097")
|
||||||
_add_account_platform_columns(mig_engine)
|
_add_account_platform_columns(mig_engine)
|
||||||
|
_add_later_orm_columns(mig_engine, ("platform_fulfillment_tasks",))
|
||||||
_add_later_orm_columns(mig_engine, ("douyu_external_orders",))
|
_add_later_orm_columns(mig_engine, ("douyu_external_orders",))
|
||||||
|
|
||||||
with Session(mig_engine) as session:
|
with Session(mig_engine) as session:
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ from web.backend.services.automation.jobs import (
|
|||||||
platform_fulfillment_lease_reaper as reaper,
|
platform_fulfillment_lease_reaper as reaper,
|
||||||
)
|
)
|
||||||
from web.backend.services.platform_fulfillment import account_selector, service, views
|
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)
|
NOW = datetime.now(UTC).replace(microsecond=0)
|
||||||
COMMODITY = "20260120QYOOB_bag10"
|
COMMODITY = "20260120QYOOB_bag10"
|
||||||
@@ -68,6 +69,19 @@ class _Base:
|
|||||||
views.invalidate_task_list_count_cache()
|
views.invalidate_task_list_count_cache()
|
||||||
self.session.close()
|
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(
|
def account(
|
||||||
self,
|
self,
|
||||||
name: str,
|
name: str,
|
||||||
@@ -181,6 +195,48 @@ class TestWorkbenchReadPath(_Base):
|
|||||||
self.session.commit()
|
self.session.commit()
|
||||||
return task
|
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):
|
def test_task_list_count_uses_short_ttl_cache_until_invalidated(self):
|
||||||
views.invalidate_task_list_count_cache()
|
views.invalidate_task_list_count_cache()
|
||||||
mapping = self.mapping()
|
mapping = self.mapping()
|
||||||
@@ -1068,6 +1124,60 @@ class TestSnapshotSync(_Base):
|
|||||||
outbox = self.session.query(IntegrationOutbox).one()
|
outbox = self.session.query(IntegrationOutbox).one()
|
||||||
assert outbox.payload_json["items"][0]["stateVersion"] == 1
|
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):
|
def test_duplicate_snapshot_keeps_allocated_task_state(self):
|
||||||
self.mapping()
|
self.mapping()
|
||||||
account = self.account("snapshot-allocated")
|
account = self.account("snapshot-allocated")
|
||||||
@@ -1140,6 +1250,30 @@ class TestSnapshotSync(_Base):
|
|||||||
assert task.state_version == 2
|
assert task.state_version == 2
|
||||||
assert task.next_allocate_at is None
|
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):
|
def test_unpaid_snapshot_does_not_enter_live_fulfillment(self):
|
||||||
self.mapping()
|
self.mapping()
|
||||||
|
|
||||||
@@ -3148,6 +3282,98 @@ class TestBindingAndCompletion(_Base):
|
|||||||
== 0
|
== 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):
|
def test_manual_confirm_rejects_role_not_currently_bound(self):
|
||||||
task = self._allocated()
|
task = self._allocated()
|
||||||
account = self.session.get(Account, task.account_id)
|
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):
|
def test_customer_start_queues_allocation_without_sync_network(self, monkeypatch):
|
||||||
task = self.task()
|
task = self.task()
|
||||||
|
self.complete_customer_profile(task)
|
||||||
calls: list[list[int]] = []
|
calls: list[list[int]] = []
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"web.backend.services.platform_fulfillment.auto_allocator.wake_auto_allocator",
|
"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):
|
def test_customer_start_creates_one_binding_task_and_links_platform(self, monkeypatch):
|
||||||
task = self._allocated()
|
task = self._allocated()
|
||||||
|
self.complete_customer_profile(task)
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
service.binding,
|
service.binding,
|
||||||
"enqueue_execution_job",
|
"enqueue_execution_job",
|
||||||
@@ -3565,6 +3793,7 @@ class TestBindingAndCompletion(_Base):
|
|||||||
|
|
||||||
def test_customer_started_binding_does_not_capture_request_loop(self, monkeypatch):
|
def test_customer_started_binding_does_not_capture_request_loop(self, monkeypatch):
|
||||||
task = self._allocated()
|
task = self._allocated()
|
||||||
|
self.complete_customer_profile(task)
|
||||||
captured: dict[str, object] = {}
|
captured: dict[str, object] = {}
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
service.binding,
|
service.binding,
|
||||||
@@ -3577,6 +3806,17 @@ class TestBindingAndCompletion(_Base):
|
|||||||
assert captured["job_type"] == "douyu_binding"
|
assert captured["job_type"] == "douyu_binding"
|
||||||
assert captured["batch_id"].startswith(f"pfbind-{task.id}-")
|
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):
|
def test_concurrent_start_binding_creates_one_task(self, monkeypatch):
|
||||||
task = self._allocated()
|
task = self._allocated()
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
|
|||||||
@@ -357,3 +357,44 @@ def test_schedule_retry_preserves_longer_capability_retry(db):
|
|||||||
|
|
||||||
db.refresh(task)
|
db.refresh(task)
|
||||||
assert task.next_allocate_at == retry_at
|
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}
|
||||||
|
|||||||
@@ -517,6 +517,18 @@
|
|||||||
"20261124_0129_account_role_change_lock.py": {
|
"20261124_0129_account_role_change_lock.py": {
|
||||||
"revision": "20261124_0129",
|
"revision": "20261124_0129",
|
||||||
"sha256": "75b97c990e0c870add48073da26a9d2ac9ffd75ba1ffe477ae97268155cab42c"
|
"sha256": "75b97c990e0c870add48073da26a9d2ac9ffd75ba1ffe477ae97268155cab42c"
|
||||||
|
},
|
||||||
|
"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,48 @@
|
|||||||
|
"""供应商 API 直充单笔上限(默认 800 鱼翅)。
|
||||||
|
|
||||||
|
配置项 `douyu_config.gold_api_max_amount`,任务执行前和前端输入框都使用它。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "20261124_0130"
|
||||||
|
down_revision: str | None = "20261124_0129"
|
||||||
|
branch_labels: str | None = None
|
||||||
|
depends_on: str | None = None
|
||||||
|
|
||||||
|
TABLE = "douyu_config"
|
||||||
|
COLUMN = "gold_api_max_amount"
|
||||||
|
|
||||||
|
|
||||||
|
def _column_exists() -> 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": COLUMN},
|
||||||
|
).scalar()
|
||||||
|
return bool(count)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
if not _column_exists():
|
||||||
|
op.add_column(
|
||||||
|
TABLE,
|
||||||
|
sa.Column(
|
||||||
|
COLUMN,
|
||||||
|
sa.Integer(),
|
||||||
|
nullable=False,
|
||||||
|
server_default="800",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
if _column_exists():
|
||||||
|
op.drop_column(TABLE, COLUMN)
|
||||||
@@ -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")
|
||||||
@@ -644,6 +644,10 @@ class DouyuConfig(Base):
|
|||||||
recharge_duplicate_confirm_minutes: Mapped[int] = mapped_column(
|
recharge_duplicate_confirm_minutes: Mapped[int] = mapped_column(
|
||||||
Integer, nullable=False, default=10, server_default="10"
|
Integer, nullable=False, default=10, server_default="10"
|
||||||
)
|
)
|
||||||
|
# 供应商 API 直充的单笔上限(鱼翅)。默认 800,防止误填过大金额。
|
||||||
|
gold_api_max_amount: Mapped[int] = mapped_column(
|
||||||
|
Integer, nullable=False, default=800, server_default="800"
|
||||||
|
)
|
||||||
gift_id: Mapped[str] = mapped_column(String(64), default="23643")
|
gift_id: Mapped[str] = mapped_column(String(64), default="23643")
|
||||||
skin_id: Mapped[str] = mapped_column(String(64), default="2942")
|
skin_id: Mapped[str] = mapped_column(String(64), default="2942")
|
||||||
updated_at: Mapped[datetime] = mapped_column(
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
@@ -2309,6 +2313,11 @@ class PlatformFulfillmentSetting(Base):
|
|||||||
nullable=False,
|
nullable=False,
|
||||||
default=_utcnow,
|
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(
|
updated_by: Mapped[int | None] = mapped_column(
|
||||||
ForeignKey("users.id", ondelete="SET NULL"),
|
ForeignKey("users.id", ondelete="SET NULL"),
|
||||||
nullable=True,
|
nullable=True,
|
||||||
@@ -2404,6 +2413,14 @@ class PlatformFulfillmentTask(Base):
|
|||||||
source_fulfillment_id: Mapped[str] = mapped_column(
|
source_fulfillment_id: Mapped[str] = mapped_column(
|
||||||
String(64), nullable=False, default="", server_default=""
|
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(
|
platform_order_id: Mapped[str] = mapped_column(
|
||||||
String(128), nullable=False, default="", server_default=""
|
String(128), nullable=False, default="", server_default=""
|
||||||
)
|
)
|
||||||
@@ -2463,6 +2480,21 @@ class PlatformFulfillmentTask(Base):
|
|||||||
classification_source: Mapped[str] = mapped_column(
|
classification_source: Mapped[str] = mapped_column(
|
||||||
String(24), nullable=False, default="unknown", server_default="unknown"
|
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(
|
account_id: Mapped[int | None] = mapped_column(
|
||||||
ForeignKey("accounts.id", ondelete="SET NULL"), nullable=True, index=True
|
ForeignKey("accounts.id", ondelete="SET NULL"), nullable=True, index=True
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -737,6 +737,7 @@ def _config_out(config: DouyuConfig) -> DouyuConfigOut:
|
|||||||
recharge_duplicate_confirm_minutes=number(
|
recharge_duplicate_confirm_minutes=number(
|
||||||
"recharge_duplicate_confirm_minutes"
|
"recharge_duplicate_confirm_minutes"
|
||||||
),
|
),
|
||||||
|
gold_api_max_amount=number("gold_api_max_amount"),
|
||||||
gift_id=text("gift_id"),
|
gift_id=text("gift_id"),
|
||||||
skin_id=text("skin_id"),
|
skin_id=text("skin_id"),
|
||||||
updated_at=config.updated_at,
|
updated_at=config.updated_at,
|
||||||
|
|||||||
@@ -80,6 +80,7 @@ def list_tasks(
|
|||||||
status: str = Query("", max_length=32),
|
status: str = Query("", max_length=32),
|
||||||
queue_bucket: str = Query("", max_length=32),
|
queue_bucket: str = Query("", max_length=32),
|
||||||
sale_mode: str = Query("", max_length=16),
|
sale_mode: str = Query("", max_length=16),
|
||||||
|
flow_version: int | None = Query(None, ge=1, le=2),
|
||||||
keyword: str = Query("", max_length=200),
|
keyword: str = Query("", max_length=200),
|
||||||
page: int = Query(1, ge=1),
|
page: int = Query(1, ge=1),
|
||||||
page_size: int = Query(20, ge=1, le=100),
|
page_size: int = Query(20, ge=1, le=100),
|
||||||
@@ -92,6 +93,7 @@ def list_tasks(
|
|||||||
status=status,
|
status=status,
|
||||||
queue_bucket=queue_bucket,
|
queue_bucket=queue_bucket,
|
||||||
sale_mode=sale_mode,
|
sale_mode=sale_mode,
|
||||||
|
flow_version=flow_version,
|
||||||
keyword=keyword,
|
keyword=keyword,
|
||||||
page=page,
|
page=page,
|
||||||
page_size=page_size,
|
page_size=page_size,
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ from ..database import get_db
|
|||||||
from ..models import IntegrationInbox
|
from ..models import IntegrationInbox
|
||||||
from ..schemas import (
|
from ..schemas import (
|
||||||
PlatformFulfillmentCustomerBindingAction,
|
PlatformFulfillmentCustomerBindingAction,
|
||||||
|
PlatformFulfillmentCustomerProfileRequest,
|
||||||
PlatformFulfillmentCustomerSessionBatchRequest,
|
PlatformFulfillmentCustomerSessionBatchRequest,
|
||||||
PlatformFulfillmentCustomerSessionRequest,
|
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(
|
@router.post(
|
||||||
"/customer-sessions/{task_id}/binding/start",
|
"/customer-sessions/{task_id}/binding/start",
|
||||||
dependencies=[Depends(require_integration_key)],
|
dependencies=[Depends(require_integration_key)],
|
||||||
|
|||||||
@@ -1537,6 +1537,7 @@ class DouyuConfigOut(BaseModel):
|
|||||||
gold_api_product_id: str = "111570"
|
gold_api_product_id: str = "111570"
|
||||||
gold_api_account_template_name: str = "斗鱼昵称"
|
gold_api_account_template_name: str = "斗鱼昵称"
|
||||||
recharge_duplicate_confirm_minutes: int = 10
|
recharge_duplicate_confirm_minutes: int = 10
|
||||||
|
gold_api_max_amount: int = 800
|
||||||
gift_id: str = "23643"
|
gift_id: str = "23643"
|
||||||
skin_id: str = "2942"
|
skin_id: str = "2942"
|
||||||
updated_at: datetime | None = None
|
updated_at: datetime | None = None
|
||||||
@@ -1569,6 +1570,7 @@ class DouyuConfigOut(BaseModel):
|
|||||||
"recharge_duplicate_confirm_minutes": (
|
"recharge_duplicate_confirm_minutes": (
|
||||||
self.recharge_duplicate_confirm_minutes
|
self.recharge_duplicate_confirm_minutes
|
||||||
),
|
),
|
||||||
|
"gold_api_max_amount": self.gold_api_max_amount,
|
||||||
"gift_id": self.gift_id,
|
"gift_id": self.gift_id,
|
||||||
"skin_id": self.skin_id,
|
"skin_id": self.skin_id,
|
||||||
"updated_at": _isoformat(self.updated_at),
|
"updated_at": _isoformat(self.updated_at),
|
||||||
@@ -1601,6 +1603,7 @@ class DouyuConfigUpdate(BaseModel):
|
|||||||
gold_api_product_id: str | None = Field(None, max_length=128)
|
gold_api_product_id: str | None = Field(None, max_length=128)
|
||||||
gold_api_account_template_name: str | None = Field(None, max_length=64)
|
gold_api_account_template_name: str | None = Field(None, max_length=64)
|
||||||
recharge_duplicate_confirm_minutes: int | None = Field(None, ge=0, le=1440)
|
recharge_duplicate_confirm_minutes: int | None = Field(None, ge=0, le=1440)
|
||||||
|
gold_api_max_amount: int | None = Field(None, ge=1, le=1_000_000)
|
||||||
gift_id: str | None = None
|
gift_id: str | None = None
|
||||||
skin_id: str | None = None
|
skin_id: str | None = None
|
||||||
|
|
||||||
@@ -1759,6 +1762,21 @@ class PlatformFulfillmentCustomerSessionRequest(BaseModel):
|
|||||||
platform_order_id: str = Field(default="", max_length=255)
|
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):
|
class PlatformFulfillmentCustomerBindingAction(BaseModel):
|
||||||
force_refresh: bool = False
|
force_refresh: bool = False
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|||||||
from datetime import UTC, datetime, timedelta
|
from datetime import UTC, datetime, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import Integer, cast, func, or_
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from ....models import Account, AccountLease, AutomationJob, PlatformFulfillmentTask
|
from ....models import Account, AccountLease, AutomationJob, PlatformFulfillmentTask
|
||||||
@@ -97,12 +98,25 @@ def run_platform_fulfillment_lease_reaper(
|
|||||||
# 分配并发/重试可能留下「batch_id 指向 task,但 task 实际用另一个账号/租约」
|
# 分配并发/重试可能留下「batch_id 指向 task,但 task 实际用另一个账号/租约」
|
||||||
# 的孤儿 active 租约。它不会自然过期(expires_at 常为 NULL),会永久占住账号,
|
# 的孤儿 active 租约。它不会自然过期(expires_at 常为 NULL),会永久占住账号,
|
||||||
# 并让协作单接管时报“任务与租约不一致”。这里按 task 的真实归属回收。
|
# 并让协作单接管时报“任务与租约不一致”。这里按 task 的真实归属回收。
|
||||||
|
# 注意:不能在过滤孤儿前先 limit active 租约。生产有 3,900+ 条 active
|
||||||
|
# pf 租约,先取前 500 条会被合法租约占满,后面的孤儿永远轮不到。
|
||||||
|
# 这里直接用 SQL 关联出「task 不存在 / task 账号或租约不一致」。
|
||||||
|
task_id_expr = cast(func.substring(AccountLease.batch_id, 4), Integer)
|
||||||
orphan_leases = (
|
orphan_leases = (
|
||||||
db.query(AccountLease)
|
db.query(AccountLease)
|
||||||
|
.outerjoin(
|
||||||
|
PlatformFulfillmentTask,
|
||||||
|
PlatformFulfillmentTask.id == task_id_expr,
|
||||||
|
)
|
||||||
.filter(
|
.filter(
|
||||||
AccountLease.purpose == "platform_fulfillment",
|
AccountLease.purpose == "platform_fulfillment",
|
||||||
AccountLease.status == "active",
|
AccountLease.status == "active",
|
||||||
AccountLease.batch_id.like("pf:%"),
|
AccountLease.batch_id.like("pf:%"),
|
||||||
|
or_(
|
||||||
|
PlatformFulfillmentTask.id.is_(None),
|
||||||
|
PlatformFulfillmentTask.account_id != AccountLease.account_id,
|
||||||
|
PlatformFulfillmentTask.lease_id != AccountLease.id,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
.order_by(AccountLease.id.asc())
|
.order_by(AccountLease.id.asc())
|
||||||
.limit(max(1, int(job.batch_size or 500)))
|
.limit(max(1, int(job.batch_size or 500)))
|
||||||
@@ -110,19 +124,6 @@ def run_platform_fulfillment_lease_reaper(
|
|||||||
)
|
)
|
||||||
orphan_released = 0
|
orphan_released = 0
|
||||||
for lease in orphan_leases:
|
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(
|
if release_lease(
|
||||||
db,
|
db,
|
||||||
lease,
|
lease,
|
||||||
|
|||||||
@@ -893,6 +893,15 @@ def create_order(
|
|||||||
return order
|
return order
|
||||||
|
|
||||||
|
|
||||||
|
PLATFORM_PROJECTED_FIELDS = {
|
||||||
|
"order_no",
|
||||||
|
"account_username",
|
||||||
|
"gift_name",
|
||||||
|
"commodity_id",
|
||||||
|
"required_points",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def update_order(
|
def update_order(
|
||||||
db: Session,
|
db: Session,
|
||||||
current: User,
|
current: User,
|
||||||
@@ -950,6 +959,24 @@ def update_order(
|
|||||||
if new != old:
|
if new != old:
|
||||||
changes[field] = {"old": old, "new": new}
|
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:
|
if order.succeeded_at is not None:
|
||||||
locked_changes = SUCCESS_PURCHASE_FIELDS.intersection(changes)
|
locked_changes = SUCCESS_PURCHASE_FIELDS.intersection(changes)
|
||||||
if locked_changes:
|
if locked_changes:
|
||||||
@@ -1074,6 +1101,17 @@ def set_account(
|
|||||||
_assert_mutable(order)
|
_assert_mutable(order)
|
||||||
_assert_success_account_change_allowed(current, order)
|
_assert_success_account_change_allowed(current, order)
|
||||||
_assert_version(order, expected_version)
|
_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)
|
account = account_by_username(db, username)
|
||||||
if account is None:
|
if account is None:
|
||||||
raise CollabError("斗鱼账号不存在", code="account_not_found")
|
raise CollabError("斗鱼账号不存在", code="account_not_found")
|
||||||
|
|||||||
@@ -575,6 +575,11 @@ class GoldMixin:
|
|||||||
amount: int,
|
amount: int,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""创建供应商鱼翅直充订单并轮询订单状态。"""
|
"""创建供应商鱼翅直充订单并轮询订单状态。"""
|
||||||
|
max_amount = int(config.get("gold_api_max_amount") or 800)
|
||||||
|
if amount > max_amount:
|
||||||
|
raise FishFinRechargeError(
|
||||||
|
f"单笔供应商直充不能超过 {max_amount} 鱼翅(当前 {amount})"
|
||||||
|
)
|
||||||
product_id = str(config.get("gold_api_product_id") or "").strip()
|
product_id = str(config.get("gold_api_product_id") or "").strip()
|
||||||
template_name = str(
|
template_name = str(
|
||||||
config.get("gold_api_account_template_name") or "斗鱼昵称"
|
config.get("gold_api_account_template_name") or "斗鱼昵称"
|
||||||
|
|||||||
@@ -134,6 +134,7 @@ DOUYU_CONFIG_DEFAULTS = {
|
|||||||
"gold_api_product_id": "111570",
|
"gold_api_product_id": "111570",
|
||||||
"gold_api_account_template_name": "斗鱼昵称",
|
"gold_api_account_template_name": "斗鱼昵称",
|
||||||
"recharge_duplicate_confirm_minutes": 10,
|
"recharge_duplicate_confirm_minutes": 10,
|
||||||
|
"gold_api_max_amount": 800,
|
||||||
"gift_id": "23643",
|
"gift_id": "23643",
|
||||||
"skin_id": "2942",
|
"skin_id": "2942",
|
||||||
# 和平小店总开关,默认关(小店当前关闭;关着时一键查询完全跳过它的请求)
|
# 和平小店总开关,默认关(小店当前关闭;关着时一键查询完全跳过它的请求)
|
||||||
|
|||||||
@@ -10,12 +10,13 @@ from datetime import UTC, datetime, timedelta
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
from sqlalchemy import or_
|
from sqlalchemy import func, or_
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from ...database import WorkerSessionLocal
|
from ...database import WorkerSessionLocal
|
||||||
from ...models import PlatformFulfillmentTask
|
from ...models import PlatformFulfillmentTask
|
||||||
from . import service
|
from . import service
|
||||||
|
from .common import FLOW_VERSION_CLEAN, _has_game_home_profile
|
||||||
|
|
||||||
DEFAULT_INTERVAL_SECONDS = 20
|
DEFAULT_INTERVAL_SECONDS = 20
|
||||||
DEFAULT_MIN_INTERVAL_SECONDS = 5
|
DEFAULT_MIN_INTERVAL_SECONDS = 5
|
||||||
@@ -138,6 +139,8 @@ def run_auto_allocation_once(
|
|||||||
due_cutoff = moment + timedelta(seconds=1)
|
due_cutoff = moment + timedelta(seconds=1)
|
||||||
query = db.query(PlatformFulfillmentTask).filter(
|
query = db.query(PlatformFulfillmentTask).filter(
|
||||||
PlatformFulfillmentTask.execution_status == "ready",
|
PlatformFulfillmentTask.execution_status == "ready",
|
||||||
|
# 存量任务只允许人工处理,自动选号只服务 Clean Cutover 之后的新单。
|
||||||
|
PlatformFulfillmentTask.flow_version == FLOW_VERSION_CLEAN,
|
||||||
PlatformFulfillmentTask.account_id.is_(None),
|
PlatformFulfillmentTask.account_id.is_(None),
|
||||||
PlatformFulfillmentTask.commodity_id != "",
|
PlatformFulfillmentTask.commodity_id != "",
|
||||||
or_(
|
or_(
|
||||||
@@ -191,6 +194,8 @@ def run_auto_allocation_once(
|
|||||||
if allocated_task is not None:
|
if allocated_task is not None:
|
||||||
allocated_task.next_allocate_at = None
|
allocated_task.next_allocate_at = None
|
||||||
db.commit()
|
db.commit()
|
||||||
|
if not _has_game_home_profile(allocated_task):
|
||||||
|
continue
|
||||||
try:
|
try:
|
||||||
service.start_binding_sync(
|
service.start_binding_sync(
|
||||||
db,
|
db,
|
||||||
@@ -277,6 +282,10 @@ def start_allocated_bindings_once(
|
|||||||
PlatformFulfillmentTask.binding_status == "not_started",
|
PlatformFulfillmentTask.binding_status == "not_started",
|
||||||
PlatformFulfillmentTask.account_id.isnot(None),
|
PlatformFulfillmentTask.account_id.isnot(None),
|
||||||
PlatformFulfillmentTask.lease_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(
|
.order_by(
|
||||||
PlatformFulfillmentTask.updated_at.asc(), PlatformFulfillmentTask.id.asc()
|
PlatformFulfillmentTask.updated_at.asc(), PlatformFulfillmentTask.id.asc()
|
||||||
@@ -289,6 +298,8 @@ def start_allocated_bindings_once(
|
|||||||
actor = service._integration_actor(db)
|
actor = service._integration_actor(db)
|
||||||
started = 0
|
started = 0
|
||||||
for task in rows:
|
for task in rows:
|
||||||
|
if not _has_game_home_profile(task):
|
||||||
|
continue
|
||||||
try:
|
try:
|
||||||
service.start_binding_sync(
|
service.start_binding_sync(
|
||||||
db,
|
db,
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ from ..douyu_account_state import DouyuLiveAccountState
|
|||||||
|
|
||||||
TARGET_PLATFORM = "douyu"
|
TARGET_PLATFORM = "douyu"
|
||||||
SCOPE_ELITE = "elite"
|
SCOPE_ELITE = "elite"
|
||||||
|
FLOW_VERSION_LEGACY = 1
|
||||||
|
FLOW_VERSION_CLEAN = 2
|
||||||
BINDING_COOLDOWN_ISSUES = frozenset({"account_role_cooldown", "customer_role_cooldown"})
|
BINDING_COOLDOWN_ISSUES = frozenset({"account_role_cooldown", "customer_role_cooldown"})
|
||||||
ACTIVE_STATUSES = {
|
ACTIVE_STATUSES = {
|
||||||
"ready",
|
"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
|
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:
|
def _order_match_started_at(db: Session) -> datetime | None:
|
||||||
row = (
|
row = (
|
||||||
db.query(PlatformFulfillmentSetting)
|
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
|
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(
|
def _apply_order_match_cutoff(
|
||||||
query,
|
query,
|
||||||
match_started_at: datetime | None,
|
match_started_at: datetime | None,
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import UTC, datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
@@ -16,12 +17,15 @@ from .binding import (
|
|||||||
refresh_binding,
|
refresh_binding,
|
||||||
start_binding,
|
start_binding,
|
||||||
)
|
)
|
||||||
|
from .common import FLOW_VERSION_CLEAN, _has_game_home_profile
|
||||||
from .order_sync import sync_order_item_ids
|
from .order_sync import sync_order_item_ids
|
||||||
from .repository import (
|
from .repository import (
|
||||||
_find_customer_task,
|
_find_customer_task,
|
||||||
_integration_actor,
|
_integration_actor,
|
||||||
_load_task,
|
_load_task,
|
||||||
|
_load_task_for_update,
|
||||||
)
|
)
|
||||||
|
from .runtime import _append_event
|
||||||
from .views import customer_binding_out
|
from .views import customer_binding_out
|
||||||
|
|
||||||
|
|
||||||
@@ -61,6 +65,57 @@ def ensure_customer_session(
|
|||||||
return customer_binding_out(db, task.id)
|
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(
|
async def customer_start_binding(
|
||||||
db: Session,
|
db: Session,
|
||||||
*,
|
*,
|
||||||
@@ -72,6 +127,8 @@ async def customer_start_binding(
|
|||||||
return customer_binding_out(db, task.id)
|
return customer_binding_out(db, task.id)
|
||||||
if task.issue_code == "mapping_missing":
|
if task.issue_code == "mapping_missing":
|
||||||
return customer_binding_out(db, task.id)
|
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:
|
if not task.account_id or not task.lease_id:
|
||||||
from .auto_allocator import wake_auto_allocator
|
from .auto_allocator import wake_auto_allocator
|
||||||
|
|||||||
@@ -21,8 +21,10 @@ from ..external_order_source import (
|
|||||||
)
|
)
|
||||||
from .common import (
|
from .common import (
|
||||||
AUTO_SYNC_INTERVAL_SECONDS,
|
AUTO_SYNC_INTERVAL_SECONDS,
|
||||||
|
FLOW_VERSION_LEGACY,
|
||||||
SCOPE_ELITE,
|
SCOPE_ELITE,
|
||||||
TARGET_PLATFORM,
|
TARGET_PLATFORM,
|
||||||
|
_flow_version_for_order,
|
||||||
_jsonable,
|
_jsonable,
|
||||||
_now,
|
_now,
|
||||||
_order_match_started_at,
|
_order_match_started_at,
|
||||||
@@ -42,6 +44,72 @@ _AUTO_SYNC_LOCK = threading.Lock()
|
|||||||
_AUTO_SYNC_LAST_ATTEMPT = float("-inf")
|
_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(
|
def _upsert_order_snapshot(
|
||||||
db: Session,
|
db: Session,
|
||||||
snapshot: dict[str, Any],
|
snapshot: dict[str, Any],
|
||||||
@@ -91,6 +159,10 @@ def _upsert_order_snapshot(
|
|||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
created = task is None
|
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:
|
if task is None:
|
||||||
task = PlatformFulfillmentTask(
|
task = PlatformFulfillmentTask(
|
||||||
source_system="order_site",
|
source_system="order_site",
|
||||||
@@ -115,6 +187,11 @@ def _upsert_order_snapshot(
|
|||||||
),
|
),
|
||||||
target_platform=TARGET_PLATFORM,
|
target_platform=TARGET_PLATFORM,
|
||||||
scope=SCOPE_ELITE,
|
scope=SCOPE_ELITE,
|
||||||
|
flow_version=_flow_version_for_order(
|
||||||
|
db,
|
||||||
|
paid_at=paid_at,
|
||||||
|
created_at=order_created_at,
|
||||||
|
),
|
||||||
created_at=_now(),
|
created_at=_now(),
|
||||||
updated_at=_now(),
|
updated_at=_now(),
|
||||||
)
|
)
|
||||||
@@ -150,11 +227,7 @@ def _upsert_order_snapshot(
|
|||||||
task.required_points,
|
task.required_points,
|
||||||
task.issue_code,
|
task.issue_code,
|
||||||
)
|
)
|
||||||
if task.execution_status in {"completed", "cancelled"}:
|
_apply_customer_profile(task, snapshot)
|
||||||
task.source_snapshot_json = _jsonable(snapshot)
|
|
||||||
return task, created, False
|
|
||||||
|
|
||||||
previous_execution_status = task.execution_status
|
|
||||||
terminal = (
|
terminal = (
|
||||||
terminal_order
|
terminal_order
|
||||||
or _snapshot_value(
|
or _snapshot_value(
|
||||||
@@ -179,6 +252,30 @@ def _upsert_order_snapshot(
|
|||||||
)
|
)
|
||||||
is False
|
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(
|
task.platform_order_id = str(
|
||||||
_snapshot_value(snapshot, "platformOrderId", "platform_order_id", default="")
|
_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_id=str(row.get("source_order_id") or ""),
|
||||||
source_order_item_id=item_id,
|
source_order_item_id=item_id,
|
||||||
source_fulfillment_id=str(row.get("source_fulfillment_id") or ""),
|
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(),
|
created_at=_now(),
|
||||||
updated_at=_now(),
|
updated_at=_now(),
|
||||||
)
|
)
|
||||||
@@ -481,6 +583,7 @@ def _sync_pending_tasks(
|
|||||||
task.target_platform = TARGET_PLATFORM
|
task.target_platform = TARGET_PLATFORM
|
||||||
task.scope = SCOPE_ELITE
|
task.scope = SCOPE_ELITE
|
||||||
task.source_snapshot_json = _jsonable(row)
|
task.source_snapshot_json = _jsonable(row)
|
||||||
|
_apply_customer_profile(task, row)
|
||||||
task.updated_at = _now()
|
task.updated_at = _now()
|
||||||
if task.account_id is None and task.execution_status in {
|
if task.account_id is None and task.execution_status in {
|
||||||
"pending_mapping",
|
"pending_mapping",
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ from .customer import (
|
|||||||
customer_refresh_bindings,
|
customer_refresh_bindings,
|
||||||
customer_start_binding,
|
customer_start_binding,
|
||||||
ensure_customer_session,
|
ensure_customer_session,
|
||||||
|
save_customer_profile,
|
||||||
)
|
)
|
||||||
from .lifecycle import (
|
from .lifecycle import (
|
||||||
cancel_task,
|
cancel_task,
|
||||||
@@ -173,6 +174,7 @@ __all__ = [
|
|||||||
"reset_task_binding",
|
"reset_task_binding",
|
||||||
"restore_cancelled_task",
|
"restore_cancelled_task",
|
||||||
"restore_mapping",
|
"restore_mapping",
|
||||||
|
"save_customer_profile",
|
||||||
"set_mapping_enabled",
|
"set_mapping_enabled",
|
||||||
"start_binding",
|
"start_binding",
|
||||||
"sync_active_task_from_account_binding",
|
"sync_active_task_from_account_binding",
|
||||||
|
|||||||
@@ -79,6 +79,7 @@ def _count_cache_key(
|
|||||||
status: str,
|
status: str,
|
||||||
queue_bucket: str,
|
queue_bucket: str,
|
||||||
sale_mode: str,
|
sale_mode: str,
|
||||||
|
flow_version: int | None,
|
||||||
keyword: str,
|
keyword: str,
|
||||||
) -> tuple[Any, ...]:
|
) -> tuple[Any, ...]:
|
||||||
return (
|
return (
|
||||||
@@ -86,6 +87,7 @@ def _count_cache_key(
|
|||||||
status,
|
status,
|
||||||
queue_bucket,
|
queue_bucket,
|
||||||
sale_mode,
|
sale_mode,
|
||||||
|
flow_version,
|
||||||
keyword.strip(),
|
keyword.strip(),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -209,13 +211,20 @@ def list_tasks(
|
|||||||
status: str = "",
|
status: str = "",
|
||||||
queue_bucket: str = "",
|
queue_bucket: str = "",
|
||||||
sale_mode: str = "",
|
sale_mode: str = "",
|
||||||
|
flow_version: int | None = None,
|
||||||
keyword: str = "",
|
keyword: str = "",
|
||||||
page: int = 1,
|
page: int = 1,
|
||||||
page_size: int = 20,
|
page_size: int = 20,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
cutoff = _order_match_started_at(db)
|
cutoff = _order_match_started_at(db)
|
||||||
query = db.query(PlatformFulfillmentTask)
|
query = db.query(PlatformFulfillmentTask)
|
||||||
|
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)
|
query = _apply_order_match_cutoff(query, cutoff)
|
||||||
|
# “全部”和“待映射”都要展示未映射任务,不能再套映射存在条件。
|
||||||
|
if queue_bucket not in {"all", "pending_mapping"}:
|
||||||
query = query.filter(
|
query = query.filter(
|
||||||
or_(
|
or_(
|
||||||
PlatformFulfillmentTask.commodity_mapping_id.isnot(None),
|
PlatformFulfillmentTask.commodity_mapping_id.isnot(None),
|
||||||
@@ -227,7 +236,7 @@ def list_tasks(
|
|||||||
query = query.filter(PlatformFulfillmentTask.sale_mode == mode_filter)
|
query = query.filter(PlatformFulfillmentTask.sale_mode == mode_filter)
|
||||||
elif sale_mode == "unknown":
|
elif sale_mode == "unknown":
|
||||||
query = query.filter(PlatformFulfillmentTask.sale_mode == "unknown")
|
query = query.filter(PlatformFulfillmentTask.sale_mode == "unknown")
|
||||||
if queue_bucket:
|
if queue_bucket and queue_bucket != "all":
|
||||||
now = datetime.now(UTC)
|
now = datetime.now(UTC)
|
||||||
if queue_bucket == classification.QUEUE_CANCELLED:
|
if queue_bucket == classification.QUEUE_CANCELLED:
|
||||||
query = query.filter(
|
query = query.filter(
|
||||||
@@ -308,6 +317,7 @@ def list_tasks(
|
|||||||
status=status,
|
status=status,
|
||||||
queue_bucket=queue_bucket,
|
queue_bucket=queue_bucket,
|
||||||
sale_mode=sale_mode,
|
sale_mode=sale_mode,
|
||||||
|
flow_version=flow_version,
|
||||||
keyword=keyword,
|
keyword=keyword,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -424,6 +434,7 @@ def _task_out(
|
|||||||
"goodsName": goods_name,
|
"goodsName": goods_name,
|
||||||
"requiredPoints": task.required_points,
|
"requiredPoints": task.required_points,
|
||||||
"saleMode": sale_mode,
|
"saleMode": sale_mode,
|
||||||
|
"flowVersion": int(task.flow_version or 1),
|
||||||
"campaignKey": task.campaign_key,
|
"campaignKey": task.campaign_key,
|
||||||
"campaignName": task.campaign_name,
|
"campaignName": task.campaign_name,
|
||||||
"offerAvailableFrom": task.offer_available_from,
|
"offerAvailableFrom": task.offer_available_from,
|
||||||
@@ -506,6 +517,7 @@ def _task_out(
|
|||||||
if include_qr and bind_task is not None
|
if include_qr and bind_task is not None
|
||||||
else None
|
else None
|
||||||
),
|
),
|
||||||
|
"customerProfile": _customer_profile_out(task, account, binding),
|
||||||
"exchangeTaskId": exchange_task_id,
|
"exchangeTaskId": exchange_task_id,
|
||||||
"exchangeResultImage": (
|
"exchangeResultImage": (
|
||||||
{
|
{
|
||||||
@@ -690,6 +702,63 @@ def _customer_binding_queue_state(
|
|||||||
return "preparing", 1000
|
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]:
|
def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||||
"""面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。"""
|
"""面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。"""
|
||||||
task = _load_task(db, task_id)
|
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 "",
|
"queueLane": bind_task.queue_lane if bind_task else "",
|
||||||
"accepted": False,
|
"accepted": False,
|
||||||
"stateVersion": int(task.state_version or 0),
|
"stateVersion": int(task.state_version or 0),
|
||||||
|
"customerProfile": _customer_profile_out(task, account, binding),
|
||||||
"completedAt": _jsonable(task.completed_at),
|
"completedAt": _jsonable(task.completed_at),
|
||||||
"updatedAt": _jsonable(task.updated_at),
|
"updatedAt": _jsonable(task.updated_at),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ export const platformFulfillmentApi = {
|
|||||||
status?: string;
|
status?: string;
|
||||||
queue_bucket?: string;
|
queue_bucket?: string;
|
||||||
sale_mode?: string;
|
sale_mode?: string;
|
||||||
|
flow_version?: number;
|
||||||
keyword?: string;
|
keyword?: string;
|
||||||
page?: number;
|
page?: number;
|
||||||
page_size?: number;
|
page_size?: number;
|
||||||
|
|||||||
@@ -950,6 +950,7 @@ export interface DouyuConfig {
|
|||||||
gold_api_product_id: string;
|
gold_api_product_id: string;
|
||||||
gold_api_account_template_name: string;
|
gold_api_account_template_name: string;
|
||||||
recharge_duplicate_confirm_minutes: number;
|
recharge_duplicate_confirm_minutes: number;
|
||||||
|
gold_api_max_amount: number;
|
||||||
gift_id: string;
|
gift_id: string;
|
||||||
skin_id: string;
|
skin_id: string;
|
||||||
updated_at: string | null;
|
updated_at: string | null;
|
||||||
@@ -2531,6 +2532,25 @@ export interface PlatformFulfillmentBindingEvidence {
|
|||||||
accountLock: PlatformFulfillmentBindingLock | null;
|
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 {
|
export interface PlatformFulfillmentTask {
|
||||||
id: number;
|
id: number;
|
||||||
sourceSystem: string;
|
sourceSystem: string;
|
||||||
@@ -2553,6 +2573,7 @@ export interface PlatformFulfillmentTask {
|
|||||||
goodsName: string;
|
goodsName: string;
|
||||||
requiredPoints: number | null;
|
requiredPoints: number | null;
|
||||||
saleMode: 'presale' | 'direct' | 'manual' | 'unknown';
|
saleMode: 'presale' | 'direct' | 'manual' | 'unknown';
|
||||||
|
flowVersion: number;
|
||||||
campaignKey: string;
|
campaignKey: string;
|
||||||
campaignName: string;
|
campaignName: string;
|
||||||
offerAvailableFrom: string | null;
|
offerAvailableFrom: string | null;
|
||||||
@@ -2581,6 +2602,7 @@ export interface PlatformFulfillmentTask {
|
|||||||
lease: { id: number; status: string; expiresAt: string | null } | null;
|
lease: { id: number; status: string; expiresAt: string | null } | null;
|
||||||
bindTask: PlatformFulfillmentBindTask | null;
|
bindTask: PlatformFulfillmentBindTask | null;
|
||||||
bindingEvidence: PlatformFulfillmentBindingEvidence | null;
|
bindingEvidence: PlatformFulfillmentBindingEvidence | null;
|
||||||
|
customerProfile: PlatformFulfillmentCustomerProfile | null;
|
||||||
exchangeTaskId: number | null;
|
exchangeTaskId: number | null;
|
||||||
exchangeResultImage: {
|
exchangeResultImage: {
|
||||||
objectKey: string;
|
objectKey: string;
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
|
|||||||
|
|
||||||
// 外部单协作:权限独立,客服没有 douyu:task 也要能进共享台账。
|
// 外部单协作:权限独立,客服没有 douyu:task 也要能进共享台账。
|
||||||
if (can('douyu:collab:view')) {
|
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')) {
|
if (can('platform_fulfillment:view')) {
|
||||||
douyuItems.push({ key: '/platform-fulfillment', label: '直播账号履约', icon: <ThunderboltOutlined /> });
|
douyuItems.push({ key: '/platform-fulfillment', label: '直播账号履约', icon: <ThunderboltOutlined /> });
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import {
|
|||||||
Timeline,
|
Timeline,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
Typography,
|
Typography,
|
||||||
|
theme,
|
||||||
type TableProps,
|
type TableProps,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import {
|
import {
|
||||||
@@ -109,6 +110,7 @@ import {
|
|||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
|
|
||||||
export default function DouyuCollabPage() {
|
export default function DouyuCollabPage() {
|
||||||
|
const { token } = theme.useToken();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [searchParams, setSearchParams] = useSearchParams();
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
const { modal } = App.useApp();
|
const { modal } = App.useApp();
|
||||||
@@ -165,6 +167,8 @@ export default function DouyuCollabPage() {
|
|||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState<DouyuCollabOrder | null>(null);
|
const [editing, setEditing] = useState<DouyuCollabOrder | null>(null);
|
||||||
const successfulPurchaseFieldsLocked = Boolean(editing?.succeeded_at && !isAdmin);
|
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 [form, setForm] = useState<OrderFormState>(EMPTY_FORM);
|
||||||
const [lookup, setLookup] = useState<DouyuCollabAccountLookup | null>(null);
|
const [lookup, setLookup] = useState<DouyuCollabAccountLookup | null>(null);
|
||||||
const lookupSeq = useRef(0);
|
const lookupSeq = useRef(0);
|
||||||
@@ -199,6 +203,9 @@ export default function DouyuCollabPage() {
|
|||||||
const [statusReason, setStatusReason] = useState('');
|
const [statusReason, setStatusReason] = useState('');
|
||||||
const [batchStatusRollback, setBatchStatusRollback] = useState(false);
|
const [batchStatusRollback, setBatchStatusRollback] = useState(false);
|
||||||
const [statusBusy, setStatusBusy] = 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 里,关闭即清空
|
// 勾选导出 CK:明文只在弹窗 state 里,关闭即清空
|
||||||
const [ckExportOpen, setCkExportOpen] = useState(false);
|
const [ckExportOpen, setCkExportOpen] = useState(false);
|
||||||
@@ -471,6 +478,34 @@ export default function DouyuCollabPage() {
|
|||||||
setCreateOpen(true);
|
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) => {
|
const openEdit = (order: DouyuCollabOrder) => {
|
||||||
setEditing(order);
|
setEditing(order);
|
||||||
setForm({
|
setForm({
|
||||||
@@ -583,18 +618,22 @@ export default function DouyuCollabPage() {
|
|||||||
) => {
|
) => {
|
||||||
if (editing) {
|
if (editing) {
|
||||||
return douyuCollabApi.updateOrder(editing.id, {
|
return douyuCollabApi.updateOrder(editing.id, {
|
||||||
order_no: form.order_no.trim(),
|
|
||||||
shop: form.shop.trim(),
|
shop: form.shop.trim(),
|
||||||
owner_id: form.owner_id,
|
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,
|
home_images: form.home_images,
|
||||||
remark: form.remark,
|
remark: form.remark,
|
||||||
expected_version: editing.version,
|
expected_version: editing.version,
|
||||||
confirm_purchase_change: confirmPurchaseChange,
|
confirm_purchase_change: confirmPurchaseChange,
|
||||||
takeover_platform_lease: takeoverPlatformLease,
|
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({
|
return douyuCollabApi.createOrder({
|
||||||
@@ -1464,12 +1503,39 @@ export default function DouyuCollabPage() {
|
|||||||
key: 'status',
|
key: 'status',
|
||||||
title: '状态',
|
title: '状态',
|
||||||
dataIndex: 'status',
|
dataIndex: 'status',
|
||||||
width: 130,
|
width: 210,
|
||||||
render: (value: DouyuCollabStatus, row) => (
|
render: (value: DouyuCollabStatus, row) => (
|
||||||
|
<Space direction="vertical" size={2} style={{ width: '100%' }}>
|
||||||
<Space size={4} wrap>
|
<Space size={4} wrap>
|
||||||
<Tag color={STATUS_META[value]?.color}>{row.status_label || STATUS_META[value]?.label || value}</Tag>
|
<Tag color={STATUS_META[value]?.color}>{row.status_label || STATUS_META[value]?.label || value}</Tag>
|
||||||
{row.is_archived && <Tag>已归档</Tag>}
|
{row.is_archived && <Tag>已归档</Tag>}
|
||||||
</Space>
|
</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>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1677,8 +1743,8 @@ export default function DouyuCollabPage() {
|
|||||||
return (
|
return (
|
||||||
<Space direction="vertical" size={12} style={{ width: '100%' }}>
|
<Space direction="vertical" size={12} style={{ width: '100%' }}>
|
||||||
<div>
|
<div>
|
||||||
<h2 style={{ margin: 0 }}>斗鱼外部单协作</h2>
|
<h2 style={{ margin: 0 }}>斗鱼预售台账</h2>
|
||||||
<Text type="secondary">订单挂内部斗鱼账号;输入用户名即可读取 CK、角色、鱼翅与手册积分</Text>
|
<Text type="secondary">预售订单在直播账号履约工作台绑定完成后同步到这里;这里记录财务、异常和人工补登记</Text>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Row gutter={[8, 8]}>
|
<Row gutter={[8, 8]}>
|
||||||
@@ -2112,6 +2178,19 @@ export default function DouyuCollabPage() {
|
|||||||
destroyOnHidden
|
destroyOnHidden
|
||||||
styles={{ body: { maxHeight: '78vh', overflowY: 'auto', paddingRight: 12 } }}
|
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 && (
|
{!editing && (
|
||||||
<Alert
|
<Alert
|
||||||
style={{ marginBottom: 12 }}
|
style={{ marginBottom: 12 }}
|
||||||
@@ -2155,8 +2234,8 @@ export default function DouyuCollabPage() {
|
|||||||
style={{ marginTop: 4 }}
|
style={{ marginTop: 4 }}
|
||||||
value={form.order_no}
|
value={form.order_no}
|
||||||
maxLength={64}
|
maxLength={64}
|
||||||
placeholder="外部订单编号"
|
placeholder="订单编号"
|
||||||
disabled={successfulPurchaseFieldsLocked}
|
disabled={successfulPurchaseFieldsLocked || platformProjectionLocked}
|
||||||
onChange={(event) => updateForm('order_no', event.target.value)}
|
onChange={(event) => updateForm('order_no', event.target.value)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -2198,12 +2277,12 @@ export default function DouyuCollabPage() {
|
|||||||
<Input
|
<Input
|
||||||
value={form.account_username}
|
value={form.account_username}
|
||||||
placeholder="输入内部斗鱼账号用户名,停止输入后自动查询"
|
placeholder="输入内部斗鱼账号用户名,停止输入后自动查询"
|
||||||
disabled={successfulPurchaseFieldsLocked}
|
disabled={successfulPurchaseFieldsLocked || platformProjectionLocked}
|
||||||
onChange={(event) => updateForm('account_username', event.target.value)}
|
onChange={(event) => updateForm('account_username', event.target.value)}
|
||||||
/>
|
/>
|
||||||
<Button
|
<Button
|
||||||
loading={lookupLoading}
|
loading={lookupLoading}
|
||||||
disabled={successfulPurchaseFieldsLocked}
|
disabled={successfulPurchaseFieldsLocked || platformProjectionLocked}
|
||||||
onClick={() => void handleLookup()}
|
onClick={() => void handleLookup()}
|
||||||
>
|
>
|
||||||
查询账号
|
查询账号
|
||||||
@@ -2227,6 +2306,7 @@ export default function DouyuCollabPage() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{editing &&
|
{editing &&
|
||||||
|
!platformProjectionLocked &&
|
||||||
canReplaceAccount &&
|
canReplaceAccount &&
|
||||||
!editing.succeeded_at &&
|
!editing.succeeded_at &&
|
||||||
editing.status !== 'done' &&
|
editing.status !== 'done' &&
|
||||||
@@ -2263,7 +2343,7 @@ export default function DouyuCollabPage() {
|
|||||||
allowClear
|
allowClear
|
||||||
value={form.gift_name}
|
value={form.gift_name}
|
||||||
options={giftNameOptions}
|
options={giftNameOptions}
|
||||||
disabled={successfulPurchaseFieldsLocked}
|
disabled={successfulPurchaseFieldsLocked || platformProjectionLocked}
|
||||||
placeholder={
|
placeholder={
|
||||||
goodsPool.length || giftRecords.length
|
goodsPool.length || giftRecords.length
|
||||||
? '输入礼包名称,或选择已有礼包'
|
? '输入礼包名称,或选择已有礼包'
|
||||||
@@ -2279,7 +2359,7 @@ export default function DouyuCollabPage() {
|
|||||||
optionFilterProp="label"
|
optionFilterProp="label"
|
||||||
value={form.gift_name || undefined}
|
value={form.gift_name || undefined}
|
||||||
options={giftNameOptions}
|
options={giftNameOptions}
|
||||||
disabled={successfulPurchaseFieldsLocked}
|
disabled={successfulPurchaseFieldsLocked || platformProjectionLocked}
|
||||||
placeholder={
|
placeholder={
|
||||||
giftNameOptions.length
|
giftNameOptions.length
|
||||||
? '选择礼包(由管理员统一维护)'
|
? '选择礼包(由管理员统一维护)'
|
||||||
@@ -2305,7 +2385,7 @@ export default function DouyuCollabPage() {
|
|||||||
min={0}
|
min={0}
|
||||||
precision={0}
|
precision={0}
|
||||||
value={form.required_points}
|
value={form.required_points}
|
||||||
disabled={!canManage || successfulPurchaseFieldsLocked}
|
disabled={!canManage || successfulPurchaseFieldsLocked || platformProjectionLocked}
|
||||||
placeholder={canManage ? '手动填写;选择礼包后自动带出' : '由管理员统一配置'}
|
placeholder={canManage ? '手动填写;选择礼包后自动带出' : '由管理员统一配置'}
|
||||||
onChange={(value) => updateForm('required_points', value ?? null)}
|
onChange={(value) => updateForm('required_points', value ?? null)}
|
||||||
/>
|
/>
|
||||||
@@ -2467,6 +2547,29 @@ export default function DouyuCollabPage() {
|
|||||||
</Space>
|
</Space>
|
||||||
</Modal>
|
</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
|
<Modal
|
||||||
title={
|
title={
|
||||||
batchStatusOpen
|
batchStatusOpen
|
||||||
@@ -2694,7 +2797,7 @@ export default function DouyuCollabPage() {
|
|||||||
open={detailOpen}
|
open={detailOpen}
|
||||||
onClose={closeDetail}
|
onClose={closeDetail}
|
||||||
width="min(1180px, 96vw)"
|
width="min(1180px, 96vw)"
|
||||||
styles={{ body: { padding: 24, background: '#f5f7fa' } }}
|
styles={{ body: { padding: 24, background: token.colorBgLayout } }}
|
||||||
extra={
|
extra={
|
||||||
detail && canEdit ? (
|
detail && canEdit ? (
|
||||||
<Space size={8} wrap>
|
<Space size={8} wrap>
|
||||||
@@ -2879,8 +2982,8 @@ export default function DouyuCollabPage() {
|
|||||||
|
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
background: '#fff',
|
background: token.colorBgContainer,
|
||||||
border: '1px solid #f0f0f0',
|
border: `1px solid ${token.colorBorderSecondary}`,
|
||||||
borderRadius: 8,
|
borderRadius: 8,
|
||||||
padding: 16,
|
padding: 16,
|
||||||
}}
|
}}
|
||||||
@@ -2915,8 +3018,8 @@ export default function DouyuCollabPage() {
|
|||||||
<Col xs={24} xl={12}>
|
<Col xs={24} xl={12}>
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
background: '#fff',
|
background: token.colorBgContainer,
|
||||||
border: '1px solid #f0f0f0',
|
border: `1px solid ${token.colorBorderSecondary}`,
|
||||||
borderRadius: 8,
|
borderRadius: 8,
|
||||||
padding: 16,
|
padding: 16,
|
||||||
minHeight: 260,
|
minHeight: 260,
|
||||||
@@ -2963,8 +3066,8 @@ export default function DouyuCollabPage() {
|
|||||||
<Col xs={24} xl={12}>
|
<Col xs={24} xl={12}>
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
background: '#fff',
|
background: token.colorBgContainer,
|
||||||
border: '1px solid #f0f0f0',
|
border: `1px solid ${token.colorBorderSecondary}`,
|
||||||
borderRadius: 8,
|
borderRadius: 8,
|
||||||
padding: 16,
|
padding: 16,
|
||||||
minHeight: 260,
|
minHeight: 260,
|
||||||
|
|||||||
@@ -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, 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 { 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';
|
||||||
@@ -18,6 +18,22 @@ import { usePermissions } from '../hooks/usePermissions';
|
|||||||
|
|
||||||
const { Text, Title } = Typography;
|
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 = [
|
const STATUS_OPTIONS = [
|
||||||
{ value: '', label: '全部' },
|
{ value: '', label: '全部' },
|
||||||
{ value: 'pending_mapping', label: '待映射' },
|
{ value: 'pending_mapping', label: '待映射' },
|
||||||
@@ -104,9 +120,23 @@ const MANUAL_REASON_LABELS: Record<string, string> = {
|
|||||||
other_manual: '其他人工',
|
other_manual: '其他人工',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const SALE_MODE_TAB_STORAGE_KEY = 'platform_fulfillment_sale_mode_tab';
|
||||||
|
|
||||||
const QUEUE_BUCKET_OPTIONS = [
|
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: 'current', label: '当前待办' },
|
||||||
{ value: 'presale_waiting', label: '预售待开放' },
|
{ value: 'presale_waiting', label: '预售待开放' },
|
||||||
|
{ value: 'pending_mapping', label: '待映射' },
|
||||||
{ value: 'ready_for_fulfillment', label: '可履约' },
|
{ value: 'ready_for_fulfillment', label: '可履约' },
|
||||||
{ value: 'needs_action', label: '需要人工' },
|
{ value: 'needs_action', label: '需要人工' },
|
||||||
{ value: 'completed', label: '已完成' },
|
{ value: 'completed', label: '已完成' },
|
||||||
@@ -330,7 +360,7 @@ function eventDescription(event: { eventType: string; detail: Record<string, unk
|
|||||||
return String(detail.reason || '已转人工处理');
|
return String(detail.reason || '已转人工处理');
|
||||||
}
|
}
|
||||||
if (event.eventType === 'released_to_manual') {
|
if (event.eventType === 'released_to_manual') {
|
||||||
return `转人工原因:${String(detail.reason || '以外部单协作人工处理为准')}`;
|
return `转人工原因:${String(detail.reason || '以订单台账人工处理为准')}`;
|
||||||
}
|
}
|
||||||
if (event.eventType === 'task_cancelled') {
|
if (event.eventType === 'task_cancelled') {
|
||||||
return `取消原因:${String(detail.reason || '人工取消')}`;
|
return `取消原因:${String(detail.reason || '人工取消')}`;
|
||||||
@@ -436,8 +466,16 @@ export default function PlatformFulfillmentPage() {
|
|||||||
const user = getUser();
|
const user = getUser();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { can } = usePermissions(user);
|
const { can } = usePermissions(user);
|
||||||
const [queueBucket, setQueueBucket] = useState('current');
|
const [queueBucket, setQueueBucket] = useState('all');
|
||||||
const [saleModeFilter, setSaleModeFilter] = useState('');
|
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 [keyword, setKeyword] = useState('');
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [pageSize, setPageSize] = useState(20);
|
const [pageSize, setPageSize] = useState(20);
|
||||||
@@ -521,13 +559,19 @@ export default function PlatformFulfillmentPage() {
|
|||||||
const queueBackedStatus = queueBucket === 'current'
|
const queueBackedStatus = queueBucket === 'current'
|
||||||
? 'unfinished'
|
? 'unfinished'
|
||||||
: (['completed', 'cancelled'].includes(queueBucket) ? queueBucket : undefined);
|
: (['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
|
? queueBucket
|
||||||
: undefined;
|
: undefined;
|
||||||
const result = await platformFulfillmentApi.listTasks({
|
const result = await platformFulfillmentApi.listTasks({
|
||||||
status: queueBackedStatus,
|
status: queueBackedStatus,
|
||||||
queue_bucket: backendBucket,
|
queue_bucket: queueBucket === 'all' ? 'all' : backendBucket,
|
||||||
sale_mode: saleModeFilter || undefined,
|
sale_mode: saleModeTab === 'legacy' ? undefined : saleModeTab,
|
||||||
|
flow_version: saleModeTab === 'legacy' ? 1 : 2,
|
||||||
keyword: keyword.trim() || undefined,
|
keyword: keyword.trim() || undefined,
|
||||||
page,
|
page,
|
||||||
page_size: pageSize,
|
page_size: pageSize,
|
||||||
@@ -539,7 +583,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
} finally {
|
} finally {
|
||||||
if (!silent) setLoading(false);
|
if (!silent) setLoading(false);
|
||||||
}
|
}
|
||||||
}, [keyword, page, pageSize, queueBucket, saleModeFilter]);
|
}, [keyword, page, pageSize, queueBucket, saleModeTab]);
|
||||||
|
|
||||||
const loadDetail = useCallback(async (taskId: number, silent = false) => {
|
const loadDetail = useCallback(async (taskId: number, silent = false) => {
|
||||||
if (!silent) setDetailLoading(true);
|
if (!silent) setDetailLoading(true);
|
||||||
@@ -687,7 +731,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
const result = await platformFulfillmentApi.syncCollab(taskIds);
|
const result = await platformFulfillmentApi.syncCollab(taskIds);
|
||||||
const syncedOrderNo =
|
const syncedOrderNo =
|
||||||
result.items.find((item) => item.action === 'created' || item.action === 'updated')?.orderNo || '';
|
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}` : ''
|
taskIds.length === 1 && syncedOrderNo ? `,订单 ${syncedOrderNo}` : ''
|
||||||
}`;
|
}`;
|
||||||
if (result.failed || result.skipped) {
|
if (result.failed || result.skipped) {
|
||||||
@@ -1280,26 +1324,19 @@ export default function PlatformFulfillmentPage() {
|
|||||||
{
|
{
|
||||||
title: '商品映射',
|
title: '商品映射',
|
||||||
key: 'mapping',
|
key: 'mapping',
|
||||||
width: 230,
|
width: 270,
|
||||||
render: (_, task) => (
|
render: (_, task) => (
|
||||||
<Space direction="vertical" size={2}>
|
<Space direction="vertical" size={3}>
|
||||||
<Text ellipsis title={task.commodityId}>
|
<Text ellipsis title={task.commodityId}>
|
||||||
{task.goodsName || task.skuName || task.internalSkuKey || '未映射'}
|
{task.goodsName || task.skuName || task.internalSkuKey || '未映射'}
|
||||||
</Text>
|
</Text>
|
||||||
<Text type="secondary">{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}</Text>
|
<Space size={6} wrap>
|
||||||
</Space>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '分类',
|
|
||||||
key: 'classification',
|
|
||||||
width: 190,
|
|
||||||
render: (_, task) => (
|
|
||||||
<Space direction="vertical" size={3}>
|
|
||||||
<Space size={4}>
|
|
||||||
<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>
|
||||||
|
<Text type="secondary">
|
||||||
|
{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}
|
||||||
|
</Text>
|
||||||
</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 || '未设置活动批次'}
|
||||||
@@ -1336,7 +1373,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '绑定',
|
title: '用户角色绑定',
|
||||||
key: 'binding',
|
key: 'binding',
|
||||||
width: 180,
|
width: 180,
|
||||||
render: (_, task) => (
|
render: (_, task) => (
|
||||||
@@ -1353,6 +1390,31 @@ export default function PlatformFulfillmentPage() {
|
|||||||
</Space>
|
</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: '状态',
|
title: '状态',
|
||||||
key: 'status',
|
key: 'status',
|
||||||
@@ -1370,7 +1432,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '外部协作',
|
title: '斗鱼预售台账',
|
||||||
key: 'collab',
|
key: 'collab',
|
||||||
width: 150,
|
width: 150,
|
||||||
render: (_, task) =>
|
render: (_, task) =>
|
||||||
@@ -1414,6 +1476,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
<Button size="small" onClick={() => setSelectedId(task.id)}>
|
<Button size="small" onClick={() => setSelectedId(task.id)}>
|
||||||
详情
|
详情
|
||||||
</Button>
|
</Button>
|
||||||
|
{saleModeTab === 'presale' ? (
|
||||||
<Button
|
<Button
|
||||||
size="small"
|
size="small"
|
||||||
type={task.collabOrder ? 'default' : 'primary'}
|
type={task.collabOrder ? 'default' : 'primary'}
|
||||||
@@ -1421,13 +1484,15 @@ export default function PlatformFulfillmentPage() {
|
|||||||
loading={rowCollabSyncingId === task.id}
|
loading={rowCollabSyncingId === task.id}
|
||||||
disabled={
|
disabled={
|
||||||
!can('platform_fulfillment:use') ||
|
!can('platform_fulfillment:use') ||
|
||||||
|
task.bindingStatus !== 'bound' ||
|
||||||
collabSyncing ||
|
collabSyncing ||
|
||||||
(rowCollabSyncingId !== null && rowCollabSyncingId !== task.id)
|
(rowCollabSyncingId !== null && rowCollabSyncingId !== task.id)
|
||||||
}
|
}
|
||||||
onClick={() => void performCollabSync([task.id], task.id)}
|
onClick={() => void performCollabSync([task.id], task.id)}
|
||||||
>
|
>
|
||||||
同步外部单协作
|
同步到斗鱼预售台账
|
||||||
</Button>
|
</Button>
|
||||||
|
) : null}
|
||||||
{task.executionStatus === 'pending_mapping' ? (
|
{task.executionStatus === 'pending_mapping' ? (
|
||||||
<Button size="small" type="primary" icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping(task)}>
|
<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 ? (
|
const actionButtons = selected ? (
|
||||||
<Space wrap>
|
<Space wrap>
|
||||||
{selected.bindTask?.qrUrl ? (
|
{selected.bindTask?.qrUrl ? (
|
||||||
@@ -1531,7 +1612,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
icon={<UserSwitchOutlined />}
|
icon={<UserSwitchOutlined />}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setManualReleaseTarget(selected);
|
setManualReleaseTarget(selected);
|
||||||
setManualReleaseReason('以外部单协作人工处理为准');
|
setManualReleaseReason('以订单台账人工处理为准');
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
释放并转人工
|
释放并转人工
|
||||||
@@ -1589,18 +1670,21 @@ export default function PlatformFulfillmentPage() {
|
|||||||
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
|
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
|
||||||
商品映射
|
商品映射
|
||||||
</Button>
|
</Button>
|
||||||
|
{saleModeTab === 'presale' ? (
|
||||||
<Button
|
<Button
|
||||||
icon={<LinkOutlined />}
|
icon={<LinkOutlined />}
|
||||||
loading={collabSyncing}
|
loading={collabSyncing}
|
||||||
disabled={
|
disabled={
|
||||||
!can('platform_fulfillment:use') ||
|
!can('platform_fulfillment:use') ||
|
||||||
selectedRowKeys.length === 0 ||
|
selectedRowKeys.length === 0 ||
|
||||||
|
!selectedCollabReady ||
|
||||||
rowCollabSyncingId !== null
|
rowCollabSyncingId !== null
|
||||||
}
|
}
|
||||||
onClick={() => void syncCollab()}
|
onClick={() => void syncCollab()}
|
||||||
>
|
>
|
||||||
同步外部单协作{selectedRowKeys.length > 0 ? `(${selectedRowKeys.length})` : ''}
|
同步到斗鱼预售台账{selectedRowKeys.length > 0 ? `(${selectedRowKeys.length})` : ''}
|
||||||
</Button>
|
</Button>
|
||||||
|
) : null}
|
||||||
<Button type="primary" loading={syncing} icon={<SyncOutlined />} onClick={() => void sync()}>
|
<Button type="primary" loading={syncing} icon={<SyncOutlined />} onClick={() => void sync()}>
|
||||||
同步待履约订单
|
同步待履约订单
|
||||||
</Button>
|
</Button>
|
||||||
@@ -1608,6 +1692,40 @@ export default function PlatformFulfillmentPage() {
|
|||||||
</Space>
|
</Space>
|
||||||
</Card>
|
</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">
|
<Card size="small">
|
||||||
<Space wrap style={{ marginBottom: 16 }}>
|
<Space wrap style={{ marginBottom: 16 }}>
|
||||||
<Input.Search
|
<Input.Search
|
||||||
@@ -1622,24 +1740,15 @@ export default function PlatformFulfillmentPage() {
|
|||||||
/>
|
/>
|
||||||
<Segmented
|
<Segmented
|
||||||
value={queueBucket}
|
value={queueBucket}
|
||||||
options={QUEUE_BUCKET_OPTIONS}
|
options={
|
||||||
|
saleModeTab === 'presale' ? PRESALE_QUEUE_BUCKET_OPTIONS : QUEUE_BUCKET_OPTIONS
|
||||||
|
}
|
||||||
onChange={(value) => {
|
onChange={(value) => {
|
||||||
setQueueBucket(String(value));
|
setQueueBucket(String(value));
|
||||||
|
setSelectedRowKeys([]);
|
||||||
setPage(1);
|
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 icon={<ReloadOutlined />} onClick={() => void loadTasks()}>
|
||||||
刷新
|
刷新
|
||||||
</Button>
|
</Button>
|
||||||
@@ -1647,7 +1756,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
<Table<PlatformFulfillmentTask>
|
<Table<PlatformFulfillmentTask>
|
||||||
rowKey="id"
|
rowKey="id"
|
||||||
loading={loading}
|
loading={loading}
|
||||||
columns={columns}
|
columns={centeredColumns}
|
||||||
dataSource={rows}
|
dataSource={rows}
|
||||||
rowSelection={{
|
rowSelection={{
|
||||||
selectedRowKeys,
|
selectedRowKeys,
|
||||||
@@ -1788,7 +1897,7 @@ export default function PlatformFulfillmentPage() {
|
|||||||
{bindingStatusLabel(selected.bindingStatus)}
|
{bindingStatusLabel(selected.bindingStatus)}
|
||||||
</Tag>
|
</Tag>
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="外部协作单" span={2}>
|
<Descriptions.Item label="斗鱼预售台账" span={2}>
|
||||||
{selected.collabOrder
|
{selected.collabOrder
|
||||||
? `${selected.collabOrder.orderNo} · ${collabStatusLabel(selected.collabOrder.status)}`
|
? `${selected.collabOrder.orderNo} · ${collabStatusLabel(selected.collabOrder.status)}`
|
||||||
: '未同步'}
|
: '未同步'}
|
||||||
@@ -1798,6 +1907,65 @@ export default function PlatformFulfillmentPage() {
|
|||||||
</Descriptions>
|
</Descriptions>
|
||||||
</Card>
|
</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="账号实时状态">
|
<Card size="small" title="账号实时状态">
|
||||||
{selected.account ? (
|
{selected.account ? (
|
||||||
<Descriptions bordered size="small" column={2}>
|
<Descriptions bordered size="small" column={2}>
|
||||||
|
|||||||
@@ -220,6 +220,8 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
const [configOpen, setConfigOpen] = useState(false);
|
const [configOpen, setConfigOpen] = useState(false);
|
||||||
const [concurrency, setConcurrency] = useState(3);
|
const [concurrency, setConcurrency] = useState(3);
|
||||||
const [goldAmount, setGoldAmount] = useState(() => savedPositiveInteger(DOUYU_GOLD_AMOUNT_STORAGE_KEY));
|
const [goldAmount, setGoldAmount] = useState(() => savedPositiveInteger(DOUYU_GOLD_AMOUNT_STORAGE_KEY));
|
||||||
|
// 历史兑换截图默认不展示;只有本页面本次实际发起过兑换的账号才显示。
|
||||||
|
const [exchangeImageAccountIds, setExchangeImageAccountIds] = useState<Set<number>>(() => new Set());
|
||||||
const [giftCount, setGiftCount] = useState(() => savedPositiveInteger(DOUYU_GIFT_COUNT_STORAGE_KEY));
|
const [giftCount, setGiftCount] = useState(() => savedPositiveInteger(DOUYU_GIFT_COUNT_STORAGE_KEY));
|
||||||
const [selectedGoodsId, setSelectedGoodsId] = useState('');
|
const [selectedGoodsId, setSelectedGoodsId] = useState('');
|
||||||
const [xpdPayType, setXpdPayType] = useState<'1' | '5'>('1');
|
const [xpdPayType, setXpdPayType] = useState<'1' | '5'>('1');
|
||||||
@@ -453,11 +455,12 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
const map = new Map<number, DouyuTaskItem>();
|
const map = new Map<number, DouyuTaskItem>();
|
||||||
for (const task of visibleTasks) {
|
for (const task of visibleTasks) {
|
||||||
if (!exchangeTaskSucceeded(task)) continue;
|
if (!exchangeTaskSucceeded(task)) continue;
|
||||||
|
if (!exchangeImageAccountIds.has(task.account_id)) continue;
|
||||||
const previous = map.get(task.account_id);
|
const previous = map.get(task.account_id);
|
||||||
if (!previous || task.id > previous.id) map.set(task.account_id, task);
|
if (!previous || task.id > previous.id) map.set(task.account_id, task);
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
}, [visibleTasks]);
|
}, [visibleTasks, exchangeImageAccountIds]);
|
||||||
|
|
||||||
const latestLockedTaskByAccount = useMemo(() => {
|
const latestLockedTaskByAccount = useMemo(() => {
|
||||||
const paidOrders = new Set(
|
const paidOrders = new Set(
|
||||||
@@ -1113,6 +1116,13 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
}
|
}
|
||||||
// 只有本页面创建的批次才允许主动弹二维码,防止其他工作台/浏览器的任务打扰当前操作。
|
// 只有本页面创建的批次才允许主动弹二维码,防止其他工作台/浏览器的任务打扰当前操作。
|
||||||
locallyStartedBatchIds.current.add(result.batch_id);
|
locallyStartedBatchIds.current.add(result.batch_id);
|
||||||
|
if (['exchange_goods', 'exchange_esports_goods', 'exchange_xpd_goods'].includes(taskType)) {
|
||||||
|
setExchangeImageAccountIds((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
for (const id of ids) next.add(id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
DOUYU_PAYMENT_TASK_TYPE_SET.has(taskType)
|
DOUYU_PAYMENT_TASK_TYPE_SET.has(taskType)
|
||||||
&& !(taskType === 'create_gold_qr' && goldRechargeChannel === 'supplier_api')
|
&& !(taskType === 'create_gold_qr' && goldRechargeChannel === 'supplier_api')
|
||||||
@@ -2423,6 +2433,10 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
const goldAmountLabel = '充值金额';
|
const goldAmountLabel = '充值金额';
|
||||||
|
const supplierMaxGoldAmount = Math.max(
|
||||||
|
1,
|
||||||
|
Number(config?.gold_api_max_amount) || 800,
|
||||||
|
);
|
||||||
const isRechargeChannelLoading = goldRechargeChannel === null;
|
const isRechargeChannelLoading = goldRechargeChannel === null;
|
||||||
const isSupplierGoldRecharge = goldRechargeChannel === 'supplier_api';
|
const isSupplierGoldRecharge = goldRechargeChannel === 'supplier_api';
|
||||||
const goldRechargeChannelLabel = isRechargeChannelLoading
|
const goldRechargeChannelLabel = isRechargeChannelLoading
|
||||||
@@ -2592,8 +2606,13 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
<InputNumber
|
<InputNumber
|
||||||
size="small"
|
size="small"
|
||||||
min={1}
|
min={1}
|
||||||
|
max={isSupplierGoldRecharge ? supplierMaxGoldAmount : undefined}
|
||||||
value={goldAmount}
|
value={goldAmount}
|
||||||
onChange={(v) => setGoldAmount(v || 1)}
|
onChange={(v) => setGoldAmount(
|
||||||
|
isSupplierGoldRecharge
|
||||||
|
? Math.min(Number(v) || 1, supplierMaxGoldAmount)
|
||||||
|
: (Number(v) || 1),
|
||||||
|
)}
|
||||||
addonBefore={goldAmountLabel}
|
addonBefore={goldAmountLabel}
|
||||||
style={{ width: '100%' }}
|
style={{ width: '100%' }}
|
||||||
/>
|
/>
|
||||||
@@ -2661,8 +2680,13 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
<InputNumber
|
<InputNumber
|
||||||
size="small"
|
size="small"
|
||||||
min={1}
|
min={1}
|
||||||
|
max={isSupplierGoldRecharge ? supplierMaxGoldAmount : undefined}
|
||||||
value={goldAmount}
|
value={goldAmount}
|
||||||
onChange={(v) => setGoldAmount(v || 1)}
|
onChange={(v) => setGoldAmount(
|
||||||
|
isSupplierGoldRecharge
|
||||||
|
? Math.min(Number(v) || 1, supplierMaxGoldAmount)
|
||||||
|
: (Number(v) || 1),
|
||||||
|
)}
|
||||||
addonBefore={goldAmountLabel}
|
addonBefore={goldAmountLabel}
|
||||||
style={{ width: '100%' }}
|
style={{ width: '100%' }}
|
||||||
/>
|
/>
|
||||||
@@ -3125,6 +3149,20 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
} : prev)}
|
} : prev)}
|
||||||
/>
|
/>
|
||||||
</Space>
|
</Space>
|
||||||
|
<Space style={{ width: '100%', justifyContent: 'space-between' }}>
|
||||||
|
<Text>最大单笔充值额度(鱼翅)</Text>
|
||||||
|
<InputNumber
|
||||||
|
min={1}
|
||||||
|
max={1000000}
|
||||||
|
precision={0}
|
||||||
|
style={{ width: 300 }}
|
||||||
|
value={configFormValues.gold_api_max_amount}
|
||||||
|
onChange={(value) => setConfigFormValues((prev) => prev ? {
|
||||||
|
...prev,
|
||||||
|
gold_api_max_amount: Number(value) || 800,
|
||||||
|
} : prev)}
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
{[
|
{[
|
||||||
{ label: '供应商商品 ID', key: 'gold_api_product_id' },
|
{ label: '供应商商品 ID', key: 'gold_api_product_id' },
|
||||||
{ label: '充值账号模板名(值为斗鱼昵称)', key: 'gold_api_account_template_name' },
|
{ label: '充值账号模板名(值为斗鱼昵称)', key: 'gold_api_account_template_name' },
|
||||||
|
|||||||
Reference in New Issue
Block a user