feat(platform): 增加履约分类映射管理并锁定迁移
This commit is contained in:
@@ -18,7 +18,9 @@
|
||||
- [精英宝典 HAR 提取](虎牙/HAR提取CK与积分中心.md):HAR 中的完整 CK、积分中心和商品结构。
|
||||
- [皮肤准入映射分析](皮肤准入映射分析.md):快手皮肤订单到斗鱼商品的覆盖与映射边界。
|
||||
- [直播账号履约工作台](直播账号履约工作台.md):order_site 人工订单、斗鱼账号租约、客户扫码绑定和人工兑换。
|
||||
- [直播账号履约分类与映射规划](直播账号履约工作台分类与映射规划.md):斗鱼单平台阶段的预售/现货分类、工作队列、映射 CRUD 和分阶段 TODO。
|
||||
- [斗鱼协议总览](斗鱼/DOUYU_PROTOCOL_OVERVIEW.md):斗鱼绑定、精英宝典、兑换、支付、多 alias 判定和排障日志的统一入口。
|
||||
- [数据库迁移规范](数据库迁移规范.md):迁移文件不可变 manifest、启动校验、repair revision 和禁止 stamp 的规则。
|
||||
|
||||
## 协议与逆向证据
|
||||
|
||||
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
# 数据库迁移规范
|
||||
|
||||
更新时间:2026-11-21
|
||||
|
||||
## 硬性规则
|
||||
|
||||
1. **已经提交并可能执行过的迁移文件禁止修改**:包括改 SQL、改 `revision`、
|
||||
改 downgrade、改注释和格式化。
|
||||
2. 发现历史结构不一致时,只能新增后续 `repair` revision,不能回头改旧迁移。
|
||||
3. 禁止通过 `alembic stamp` 伪造版本;只有灾难恢复且完成备份、人工审查后才能使用。
|
||||
4. 新迁移必须在真实 MySQL 临时库执行完整 `upgrade head` 和模型一致性测试。
|
||||
5. 迁移修复不能依赖“本地已经手工执行过某条 SQL”,所有结构变化必须在 revision 中。
|
||||
|
||||
## 迁移不可变 Manifest
|
||||
|
||||
仓库维护:
|
||||
|
||||
```text
|
||||
web/backend/migrations/migration_manifest.json
|
||||
```
|
||||
|
||||
其中记录每个迁移文件的:
|
||||
|
||||
- 文件名
|
||||
- revision
|
||||
- SHA256
|
||||
|
||||
应用启动、`dev.sh` 迁移和测试都会先校验 manifest。
|
||||
|
||||
只要已登记迁移发生变化,启动会直接失败,例如:
|
||||
|
||||
```text
|
||||
迁移不可变校验失败:
|
||||
- 已发布迁移内容被修改: 20261120_0101_douyu_task_durable_schedule.py
|
||||
```
|
||||
|
||||
此时不能重新生成 manifest 了事,必须:
|
||||
|
||||
1. 还原旧迁移文件;
|
||||
2. 新增后续修复 revision;
|
||||
3. 运行测试;
|
||||
4. 再登记新迁移。
|
||||
|
||||
## 新增迁移流程
|
||||
|
||||
```bash
|
||||
uv run alembic revision -m "说明"
|
||||
```
|
||||
|
||||
编辑新迁移后:
|
||||
|
||||
```bash
|
||||
uv run pytest -q tests/test_migrations.py tests/test_migration_immutability.py
|
||||
uv run python -m web.backend.migrations.immutability --write
|
||||
uv run python -m web.backend.migrations.immutability
|
||||
```
|
||||
|
||||
`--write` 默认只接受“新增文件”;如果已有迁移的 revision 或 SHA256 发生变化,
|
||||
它也会拒绝写入。
|
||||
|
||||
只有灾难恢复才允许:
|
||||
|
||||
```bash
|
||||
uv run python -m web.backend.migrations.immutability --write --force
|
||||
```
|
||||
|
||||
使用 `--force` 必须在提交说明中写明原因,并人工审查 manifest diff。
|
||||
|
||||
## 生产核对
|
||||
|
||||
只读检查不会改变结构。常用命令:
|
||||
|
||||
```sql
|
||||
SELECT version_num FROM alembic_version;
|
||||
SHOW COLUMNS FROM douyu_tasks;
|
||||
SHOW INDEX FROM douyu_tasks;
|
||||
```
|
||||
|
||||
`SELECT`、`SHOW COLUMNS`、`information_schema` 查询都不会删除或修改列。
|
||||
如果应用报 `Unknown column`,优先检查:
|
||||
|
||||
- 当前运行镜像是否和代码提交一致;
|
||||
- `alembic_version` 是否与实际表结构一致;
|
||||
- 是否存在旧迁移被修改、手工 stamp 或未执行完的 DDL;
|
||||
- 新环境执行迁移时是否因为没有 manifest 校验而得到了另一套结构。
|
||||
|
||||
## 本次事故
|
||||
|
||||
`20261120_0101` 在首次提交后又修改过 generated column 的持久化选项。Alembic
|
||||
只记录 revision,不记录脚本内容,因此本地数据库可能已经执行过旧内容,但版本号
|
||||
仍然显示在新 revision。另一次本地库漂移表现为所有 0101 字段都在,只有
|
||||
`active_binding_key` 缺失。
|
||||
|
||||
处理方式:
|
||||
|
||||
- 新增 `20261121_0107_repair_douyu_active_binding_key.py` 幂等修复;
|
||||
- 清理重复活动二维码任务;
|
||||
- 补回列和唯一索引;
|
||||
- 从现在开始用 manifest 锁定全部 107 个迁移文件;
|
||||
- 不再允许通过修改旧迁移“顺便优化”。
|
||||
@@ -101,6 +101,30 @@
|
||||
履约详情会长期展示该凭证,支持查看大图、复制和下载;斗鱼任务日志被清理后,
|
||||
履约任务上的图片引用仍保留。
|
||||
|
||||
## 销售模式与工作队列
|
||||
|
||||
商品映射是销售模式的主要录入入口。新建或编辑斗鱼商品映射时必须选择:
|
||||
|
||||
- `预售`:客户下单时商品尚未开放;
|
||||
- `直接兑换`:商品已开放;
|
||||
- `人工`:必须人工确认的特殊单。
|
||||
|
||||
销售模式属于活动批次快照。任务应用映射时复制 `saleMode`、活动批次和开放时间;
|
||||
后续修改映射不能反向改写履约中的历史任务。预售任务到达开放时间后仍保留
|
||||
`saleMode=presale`,但开放状态变为 `available`,并自动进入“可履约”队列。
|
||||
|
||||
工作台默认显示“当前待办”,不再把已完成和已取消订单混入“全部”。一级队列包括:
|
||||
|
||||
- 当前待办
|
||||
- 预售待开放
|
||||
- 可履约
|
||||
- 需要人工
|
||||
- 已完成
|
||||
- 已取消
|
||||
|
||||
“需要人工”继续按积分不足、宝典未开通、限兑、绑定异常、账号冷却等原因细分。
|
||||
商品映射支持新建、编辑、启停、归档、恢复和删除;已被任务引用的映射只能归档。
|
||||
|
||||
## 账号租约
|
||||
|
||||
账号租约默认无限制,适合当前“分配后由运营人工处理”的流程。管理员可在
|
||||
|
||||
@@ -0,0 +1,411 @@
|
||||
# 直播账号履约工作台分类与映射规划
|
||||
|
||||
更新时间:2026-11-21
|
||||
|
||||
## 范围
|
||||
|
||||
近期只优化斗鱼单平台,不接虎牙。
|
||||
|
||||
本计划解决:
|
||||
|
||||
- 预售、直接兑换和历史任务混在一个列表;
|
||||
- `manual_required` 把积分不足、未开通宝典、限兑等问题混成一类;
|
||||
- 商品映射只有覆盖式新增,没有完整 CRUD、版本和归档;
|
||||
- 同一商品后续返场时,旧映射会被覆盖,历史语义丢失。
|
||||
|
||||
暂不实现:
|
||||
|
||||
- 虎牙履约;
|
||||
- 跨平台统一适配器;
|
||||
- 自动兑换、自动充值;
|
||||
- 物理拆分履约任务表。
|
||||
|
||||
虎牙只在“未来兼容边界”中保留,不进入本轮开发。
|
||||
|
||||
## 当前问题
|
||||
|
||||
### 1. 单表不是根因
|
||||
|
||||
`platform_fulfillment_tasks` 同时承载订单、账号租约、绑定和兑换阶段是合理的。
|
||||
任务必须共享幂等、Outbox、租约和时间线,不能按平台或销售模式拆表。
|
||||
|
||||
真正缺少的是正交分类字段:
|
||||
|
||||
- 销售模式:预售 / 直接兑换;
|
||||
- 商品开放状态:未开放 / 可兑换 / 售罄 / 已结束;
|
||||
- 履约阶段:待映射 / 待分配 / 待绑定 / 待兑换 / 待人工 / 已结束。
|
||||
|
||||
这三类信息不能用同一个 `execution_status` 表达。
|
||||
|
||||
### 2. 订单源没有明确销售模式
|
||||
|
||||
当前 `order_site` 快照只提供订单、SKU、支付和履约状态,没有稳定的
|
||||
`sale_mode` 字段。`spec_json` 虽被保留,但不能作为可靠业务字段直接解析。
|
||||
|
||||
因此首期不能让代码从商品名猜“预售/现货”:
|
||||
|
||||
- 新字段未知时显示“未分类”;
|
||||
- 管理员在创建或编辑商品映射时明确选择“预售 / 直接兑换 / 人工”;
|
||||
- 任务应用映射时把销售模式快照到任务;
|
||||
- 管理员可在报价映射或任务上人工修正;
|
||||
- 后续推动 `order_site` 在快照中增加明确 `saleMode`。
|
||||
|
||||
映射是首期销售模式的主要录入入口。人工区分必须作为新映射/返场批次的必填项,
|
||||
不能在列表里逐单临时猜测。后续 `order_site` 提供正式字段时,订单字段优先,
|
||||
映射值作为缺失时的回退,并在任务上记录 `classification_source`。
|
||||
|
||||
### 3. 斗鱼“预兑”不等于业务“预售”
|
||||
|
||||
`subscribe`、`pre_exchange`、`wait` 是斗鱼商品当前动作状态,不等于用户下单时
|
||||
购买的销售模式。业务预售应由订单/报价快照决定;斗鱼动作状态只决定当前能否兑换。
|
||||
|
||||
### 4. 现有映射没有版本
|
||||
|
||||
当前唯一约束是:
|
||||
|
||||
```text
|
||||
(target_platform, internal_sku_key)
|
||||
```
|
||||
|
||||
同一皮肤下一次返场时只能覆盖旧映射。即使暂时不接虎牙,也需要“同平台多返场
|
||||
批次”的历史记录。
|
||||
|
||||
### 5. 映射 API 和页面不完整
|
||||
|
||||
当前只有:
|
||||
|
||||
- `GET /mappings`
|
||||
- `PUT /mappings` 覆盖式新增/更新
|
||||
|
||||
缺少:
|
||||
|
||||
- 按 ID 编辑;
|
||||
- 启用/停用;
|
||||
- 归档/恢复;
|
||||
- 历史版本;
|
||||
- 关联任务预览;
|
||||
- 删除前引用检查;
|
||||
- 返场批次和开放时间。
|
||||
|
||||
## 分类模型
|
||||
|
||||
### 销售模式
|
||||
|
||||
`sale_mode`:
|
||||
|
||||
| 值 | 含义 |
|
||||
| --- | --- |
|
||||
| `presale` | 预售/返场预约,平台尚未开放兑换 |
|
||||
| `direct` | 已开售,按正常履约流程处理 |
|
||||
| `manual` | 必须人工确认的特殊单 |
|
||||
| `unknown` | 来源未提供,不能猜 |
|
||||
|
||||
销售模式由管理员在映射表单中人工选择。销售模式表示“客户购买时这一批商品是
|
||||
预售还是直接兑换”,属于历史事实;活动到期或开放后不能把任务上的
|
||||
`presale` 改写为 `direct`。
|
||||
|
||||
### 平台开放状态
|
||||
|
||||
`availability_state` 为派生状态,不落业务真值:
|
||||
|
||||
| 值 | 判定 |
|
||||
| --- | --- |
|
||||
| `waiting_release` | 当前时间早于 `available_from` |
|
||||
| `available` | 在开放区间且有库存 |
|
||||
| `sold_out` | 在活动期内但无库存 |
|
||||
| `ended` | 当前时间晚于 `available_until` |
|
||||
| `unknown` | 没有可靠的商品开放快照 |
|
||||
|
||||
### 履约队列
|
||||
|
||||
`queue_bucket` 由 API 派生:
|
||||
|
||||
| 队列 | 判定 |
|
||||
| --- | --- |
|
||||
| `pending_mapping` | 没有有效映射 |
|
||||
| `presale_waiting` | 销售模式预售,平台未开放 |
|
||||
| `ready_for_fulfillment` | 平台已开放,待选号/待绑定/待兑换 |
|
||||
| `needs_action` | 积分不足、未开通宝典、限兑、绑定异常等 |
|
||||
| `completed` | 已完成 |
|
||||
| `cancelled` | 已取消/关闭 |
|
||||
|
||||
`manual_required` 需要进一步细分为:
|
||||
|
||||
- `points_short`
|
||||
- `elite_not_opened`
|
||||
- `limit_reached`
|
||||
- `binding_failed`
|
||||
- `account_cooldown`
|
||||
- `other_manual`
|
||||
|
||||
这些细分优先从现有 `issue_code`、`exchange_status` 和绑定状态派生,不立即增加
|
||||
大量状态枚举。
|
||||
|
||||
## 数据模型
|
||||
|
||||
### PlatformCommodityMapping
|
||||
|
||||
继续作为斗鱼商品报价表,新增:
|
||||
|
||||
- `campaign_key`:返场/活动批次,如 `douyu-2026-11-return`;
|
||||
- `campaign_name`;
|
||||
- `sale_mode`;
|
||||
- `available_from`;
|
||||
- `available_until`;
|
||||
- `released_at`;
|
||||
- `goods_status`:最近刷新商品时的平台状态;
|
||||
- `version`;
|
||||
- `archived_at`;
|
||||
- `archived_by`。
|
||||
|
||||
唯一约束从:
|
||||
|
||||
```text
|
||||
(target_platform, internal_sku_key)
|
||||
```
|
||||
|
||||
调整为:
|
||||
|
||||
```text
|
||||
(target_platform, internal_sku_key, campaign_key)
|
||||
```
|
||||
|
||||
同一内部 SKU 可以保留历史返场记录,但同一批次仍只允许一条。
|
||||
|
||||
### PlatformFulfillmentTask
|
||||
|
||||
新增报价快照字段:
|
||||
|
||||
- `sale_mode`
|
||||
- `campaign_key`
|
||||
- `offer_available_from`
|
||||
- `offer_available_until`
|
||||
- `classification_source`:`order_sync / mapping / manual / unknown`
|
||||
|
||||
任务创建或映射应用时复制快照。后续修改报价不能改变历史任务。
|
||||
|
||||
映射应用规则:
|
||||
|
||||
- 新任务:从当前有效映射复制 `sale_mode` 和开放时间;
|
||||
- 已存在但 `pending_mapping` 的任务:应用映射时补快照;
|
||||
- 已进入履约中的任务:默认不因映射编辑而改变销售模式;
|
||||
- 管理员确需纠正时,走单独“修正分类”操作并写审计和任务事件。
|
||||
|
||||
### 不新增的表
|
||||
|
||||
斗鱼单平台阶段不新增 `products`、`platforms`、`offers` 三套表。先用现有
|
||||
`internal_sku_key` 和 `platform_commodity_mappings` 演进,避免过度设计。
|
||||
|
||||
虎牙接入时再评估:
|
||||
|
||||
- 抽出内部商品表;
|
||||
- 平台报价表增加平台引用;
|
||||
- 履约编排层增加平台适配器。
|
||||
|
||||
## 映射 CRUD
|
||||
|
||||
### API
|
||||
|
||||
```text
|
||||
GET /api/platform-fulfillment/mappings
|
||||
POST /api/platform-fulfillment/mappings
|
||||
PATCH /api/platform-fulfillment/mappings/{id}
|
||||
POST /api/platform-fulfillment/mappings/{id}/enable
|
||||
POST /api/platform-fulfillment/mappings/{id}/disable
|
||||
POST /api/platform-fulfillment/mappings/{id}/archive
|
||||
POST /api/platform-fulfillment/mappings/{id}/restore
|
||||
GET /api/platform-fulfillment/mappings/{id}/impact
|
||||
```
|
||||
|
||||
删除规则:
|
||||
|
||||
- 未被任务引用:允许管理员物理删除;
|
||||
- 已被任务引用:只能归档,禁止删除;
|
||||
- 所有写操作保留审计。
|
||||
|
||||
### 页面
|
||||
|
||||
映射不再只放在任务弹窗中,改为独立“商品映射”管理页或抽屉:
|
||||
|
||||
- 搜索内部 SKU、平台商品 ID、商品名;
|
||||
- 按销售模式、开放状态、启用状态、活动批次筛选;
|
||||
- 新建、编辑、启停、归档、恢复;
|
||||
- 复制上一次返场生成新批次;
|
||||
- 查看该映射影响的任务数量;
|
||||
- 展示最近刷新商品状态和开放时间。
|
||||
|
||||
新建或编辑映射时必须包含:
|
||||
|
||||
- 销售模式:预售 / 直接兑换 / 人工 / 未分类;
|
||||
- 活动批次;
|
||||
- 预售时填写“预计开放时间”;
|
||||
- 直接兑换时填写或自动读取开放区间;
|
||||
- 选择后预览会影响的待分配任务数量和销售模式。
|
||||
|
||||
任务详情里的“商品映射”只负责进入该 SKU 的映射管理,不再承担完整 CRUD。
|
||||
|
||||
## 工作台 UI
|
||||
|
||||
### 默认视图
|
||||
|
||||
默认不再显示“全部”。默认进入“当前待办”:
|
||||
|
||||
- 排除 `completed`、`cancelled`;
|
||||
- 按待映射、预售、可履约、人工异常分组;
|
||||
- 保持分页和关键词搜索。
|
||||
|
||||
### 一级分类
|
||||
|
||||
建议使用 Tabs:
|
||||
|
||||
- `当前待办`
|
||||
- `预售待开放`
|
||||
- `可履约`
|
||||
- `需要人工`
|
||||
- `已结束`
|
||||
|
||||
预售单到达开放时间后仍保留 `sale_mode=presale`,但 `availability_state` 从
|
||||
`waiting_release` 变为 `available`,并进入“可履约”工作队列。历史销售分类和
|
||||
当前可执行性必须分开保存。
|
||||
|
||||
### 二级筛选
|
||||
|
||||
- 销售模式:全部 / 预售 / 直接兑换 / 未分类
|
||||
- 履约阶段
|
||||
- 人工原因
|
||||
- 商品活动批次
|
||||
- 平台商品开放状态
|
||||
- 账号与客服
|
||||
|
||||
### 表格列
|
||||
|
||||
增加:
|
||||
|
||||
- 销售模式
|
||||
- 活动批次
|
||||
- 商品开放状态
|
||||
- 开放/结束时间
|
||||
- 人工原因
|
||||
|
||||
保留:
|
||||
|
||||
- 订单/SKU
|
||||
- 映射
|
||||
- 账号
|
||||
- 绑定
|
||||
- 兑换资格
|
||||
- 更新时间
|
||||
- 操作
|
||||
|
||||
## 实施计划
|
||||
|
||||
### Phase 0:数据审计与口径确认
|
||||
|
||||
- 盘点 `spec_json` 中可能存在的销售模式字段;
|
||||
- 与 `order_site` 确认未来是否能提供稳定 `saleMode`;
|
||||
- 确认“预售”的业务定义:下单时商品未开放,还是订单需要两阶段履约;
|
||||
- 统计现有任务中预售/现货可回填比例。
|
||||
|
||||
验收:不靠商品名猜测,未知数据明确显示“未分类”。
|
||||
|
||||
### Phase 1:模型和迁移
|
||||
|
||||
- 给映射增加批次、销售模式、开放时间、版本、归档字段;
|
||||
- 给任务增加报价快照字段;
|
||||
- 调整唯一约束;
|
||||
- 现有 19 条映射回填 `sale_mode=unknown`、活动批次 `douyu-current`;
|
||||
- 保持现有斗鱼流程不变。
|
||||
|
||||
验收:迁移可回滚,历史任务不被覆盖,现有选号和兑换流程无变化。
|
||||
|
||||
### Phase 2:映射 CRUD
|
||||
|
||||
- 增加创建、编辑、启停、归档、恢复和影响预览 API;
|
||||
- 开发独立映射管理界面;
|
||||
- 增加审计和引用保护;
|
||||
- 支持复制历史批次生成新返场映射。
|
||||
|
||||
验收:管理员不再覆盖旧映射即可完成新返场配置。
|
||||
|
||||
### Phase 3:分类查询和 UI
|
||||
|
||||
- 列表 API 增加 `queue_bucket`、`sale_mode`、`availability_state`;
|
||||
- 默认隐藏结束任务;
|
||||
- 增加一级 Tabs 和二级筛选;
|
||||
- 细分 `manual_required` 原因;
|
||||
- 保留旧 `status` 参数兼容现有调用。
|
||||
|
||||
验收:客服进入页面能直接看到当前待办,不需要从全部历史单中人工寻找。
|
||||
|
||||
### Phase 4:自动分类
|
||||
|
||||
- 商品刷新时同步开放/结束时间和库存状态;
|
||||
- 定时将预售任务从 `presale_waiting` 派生到 `ready_for_fulfillment`;
|
||||
- 仍然只更新派生展示,不把平台状态写入履约终态。
|
||||
|
||||
验收:活动开放后不需要人工重新映射,任务自动进入可履约队列。
|
||||
|
||||
## TODO
|
||||
|
||||
### P0
|
||||
|
||||
- [ ] 确认 `order_site` 是否已有预售/现货字段;
|
||||
- [ ] 确认 `spec_json` 的稳定字段清单;
|
||||
- [ ] 确定预售业务定义和人工修正权限;
|
||||
- [ ] 确定映射表单中销售模式默认值:建议默认 `unknown`,禁止静默默认成现货;
|
||||
- [ ] 确定预售开放时间的必填/可选规则;
|
||||
- [ ] 盘点当前 358 条待映射任务的 SKU;
|
||||
- [ ] 盘点 `manual_required` 1512 条的原因分布。
|
||||
|
||||
### P1
|
||||
|
||||
- [x] 增加映射 `campaign_key/campaign_name/sale_mode/available_from/available_until/version/archived_at`;
|
||||
- [x] 增加任务报价快照字段;
|
||||
- [x] 调整映射唯一约束;
|
||||
- [x] 回填现有映射和任务;
|
||||
- [x] 增加迁移和模型一致性测试。
|
||||
|
||||
### P2
|
||||
|
||||
- [x] 增加映射创建 API;
|
||||
- [x] 增加映射编辑 API;
|
||||
- [x] 增加启停、归档、恢复 API;
|
||||
- [x] 增加任务影响预览;
|
||||
- [x] 增加审计;
|
||||
- [x] 开发映射管理页面;
|
||||
- [ ] 增加“复制为下一返场批次”。
|
||||
- [x] 映射表单增加“预售 / 直接兑换 / 人工”人工选择和开放时间;
|
||||
- [ ] 保存前展示受影响的待映射任务数量。
|
||||
|
||||
### P3
|
||||
|
||||
- [x] 列表 API 增加 `queueBucket/saleMode/availabilityState`;
|
||||
- [x] 默认排除已完成和已取消;
|
||||
- [x] 增加一级 Tabs;
|
||||
- [x] 增加二级筛选;
|
||||
- [x] 细分人工处理原因;
|
||||
- [x] 调整表格列和详情抽屉;
|
||||
- [x] 增加前端类型检查、构建和接口测试。
|
||||
|
||||
### P4
|
||||
|
||||
- [ ] 商品刷新同步开放时间和库存;
|
||||
- [x] 开放时间到达后更新可履约分类;
|
||||
- [ ] 增加分类变更日志;
|
||||
- [ ] 增加管理员修正销售模式操作及审计;
|
||||
- [ ] 增加分类统计和积压告警。
|
||||
|
||||
### 虎牙 TODO
|
||||
|
||||
- [ ] 不进入近期排期;
|
||||
- [ ] 接入前抽出平台适配器;
|
||||
- [ ] 接入前评估内部商品与平台报价分表;
|
||||
- [ ] 保持当前任务表和内部 SKU 可复用。
|
||||
|
||||
## 兼容边界
|
||||
|
||||
- 所有新增 API 字段使用可选值,旧前端仍能只读旧字段;
|
||||
- `execution_status` 和 `exchange_status` 仍是履约真值;
|
||||
- `queue_bucket` 和 `availability_state` 是派生字段,可由服务端重算;
|
||||
- 历史映射不物理删除;
|
||||
- 任务必须保存映射快照,不允许展示时回查最新映射覆盖历史语义。
|
||||
@@ -0,0 +1,36 @@
|
||||
"""已发布 Alembic 迁移不可被静默修改。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from web.backend.migrations import immutability
|
||||
|
||||
|
||||
def test_committed_migration_manifest_matches_files():
|
||||
immutability.verify_manifest()
|
||||
|
||||
|
||||
def test_manifest_rejects_modified_released_migration(tmp_path: Path):
|
||||
versions = tmp_path / "versions"
|
||||
versions.mkdir()
|
||||
migration = versions / "20260101_0001_example.py"
|
||||
migration.write_text('revision = "20260101_0001"\n', encoding="utf-8")
|
||||
manifest = tmp_path / "migration_manifest.json"
|
||||
immutability.write_manifest(versions_dir=versions, manifest_path=manifest)
|
||||
|
||||
migration.write_text(
|
||||
'revision = "20260101_0001"\n# accidental released change\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
with pytest.raises(immutability.MigrationManifestError, match="内容被修改"):
|
||||
immutability.verify_manifest(
|
||||
versions_dir=versions,
|
||||
manifest_path=manifest,
|
||||
)
|
||||
|
||||
with pytest.raises(immutability.MigrationManifestError, match="拒绝更新"):
|
||||
immutability.write_manifest(versions_dir=versions, manifest_path=manifest)
|
||||
+165
-1
@@ -32,6 +32,7 @@ from web.backend.models import (
|
||||
AutomationJob,
|
||||
DouyuExternalOrder,
|
||||
HuyaExternalOrder,
|
||||
PlatformCommodityMapping,
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
WeiboAccount,
|
||||
@@ -41,7 +42,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = TESTS_DIR.parent
|
||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||
|
||||
HEAD_REVISION = "20261121_0105"
|
||||
HEAD_REVISION = "20261121_0107"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
@@ -371,6 +372,169 @@ class TestMigrationSmoke:
|
||||
with admin_engine.begin() as conn:
|
||||
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
|
||||
|
||||
def test_0106_adds_fulfillment_classification_and_backfills_mapping(self):
|
||||
creds = get_mysql_credentials()
|
||||
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
|
||||
mig_url = (
|
||||
f"mysql+pymysql://{quote_plus(creds['user'])}:"
|
||||
f"{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/"
|
||||
f"{mig_db}?charset=utf8mb4"
|
||||
)
|
||||
admin_engine = get_test_engine()
|
||||
mig_engine = create_engine(mig_url)
|
||||
original_url = database_module.DATABASE_URL
|
||||
with admin_engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
f"CREATE DATABASE `{mig_db}` "
|
||||
"CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"
|
||||
)
|
||||
)
|
||||
try:
|
||||
database_module.DATABASE_URL = mig_url
|
||||
cfg = _migration_config()
|
||||
cfg.set_main_option("sqlalchemy.url", mig_url)
|
||||
command.upgrade(cfg, "20261121_0105")
|
||||
with mig_engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO platform_commodity_mappings (
|
||||
target_platform, internal_sku_key, commodity_id,
|
||||
goods_name, required_points, scope, enabled,
|
||||
created_at, updated_at
|
||||
) VALUES (
|
||||
'douyu', '套装-分类迁移', 'bag-classification',
|
||||
'套装-分类迁移', 1280, 'elite', 1,
|
||||
UTC_TIMESTAMP(), UTC_TIMESTAMP()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
command.upgrade(cfg, "head")
|
||||
with Session(mig_engine) as session:
|
||||
row = session.query(PlatformCommodityMapping).one()
|
||||
assert row.campaign_key == "douyu-current"
|
||||
assert row.sale_mode == "unknown"
|
||||
assert row.version == 1
|
||||
assert row.archived_at is None
|
||||
|
||||
command.downgrade(cfg, "20261121_0105")
|
||||
columns = {
|
||||
item["name"]
|
||||
for item in inspect(mig_engine).get_columns(
|
||||
"platform_commodity_mappings"
|
||||
)
|
||||
}
|
||||
assert "sale_mode" not in columns
|
||||
assert "campaign_key" not in columns
|
||||
finally:
|
||||
database_module.DATABASE_URL = original_url
|
||||
mig_engine.dispose()
|
||||
with admin_engine.begin() as conn:
|
||||
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
|
||||
|
||||
def test_0107_repairs_missing_active_binding_key_and_deduplicates(self):
|
||||
creds = get_mysql_credentials()
|
||||
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
|
||||
mig_url = (
|
||||
f"mysql+pymysql://{quote_plus(creds['user'])}:"
|
||||
f"{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/"
|
||||
f"{mig_db}?charset=utf8mb4"
|
||||
)
|
||||
admin_engine = get_test_engine()
|
||||
mig_engine = create_engine(mig_url)
|
||||
original_url = database_module.DATABASE_URL
|
||||
with admin_engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
f"CREATE DATABASE `{mig_db}` "
|
||||
"CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"
|
||||
)
|
||||
)
|
||||
try:
|
||||
database_module.DATABASE_URL = mig_url
|
||||
cfg = _migration_config()
|
||||
cfg.set_main_option("sqlalchemy.url", mig_url)
|
||||
command.upgrade(cfg, "20261121_0106")
|
||||
with Session(mig_engine) as session:
|
||||
user = User(
|
||||
username="repair-0107-user",
|
||||
password_hash="hash",
|
||||
role="super_admin",
|
||||
)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
account = Account(
|
||||
username="repair-0107-account",
|
||||
password="p",
|
||||
email="repair-0107@example.com",
|
||||
email_password="ep",
|
||||
)
|
||||
session.add(account)
|
||||
session.commit()
|
||||
user_id = user.id
|
||||
account_id = account.id
|
||||
with mig_engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
"ALTER TABLE douyu_tasks "
|
||||
"DROP INDEX uq_douyu_tasks_active_binding"
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
text("ALTER TABLE douyu_tasks DROP COLUMN active_binding_key")
|
||||
)
|
||||
for _ in range(2):
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO douyu_tasks (
|
||||
batch_id, account_id, task_type, handbook_scope,
|
||||
status, message, created_by, created_at,
|
||||
platform_task_id, queue_lane, attempt_count
|
||||
) VALUES (
|
||||
'repair-0107-batch', :account_id, 'get_bind_qr',
|
||||
'elite', 'running', 'repair-test', :user_id,
|
||||
UTC_TIMESTAMP(), 555, 'binding_poll', 0
|
||||
)
|
||||
"""
|
||||
),
|
||||
{"account_id": account_id, "user_id": user_id},
|
||||
)
|
||||
|
||||
command.upgrade(cfg, "head")
|
||||
with mig_engine.connect() as conn:
|
||||
columns = {
|
||||
item["name"]
|
||||
for item in inspect(conn).get_columns("douyu_tasks")
|
||||
}
|
||||
indexes = {
|
||||
item["name"]
|
||||
for item in inspect(conn).get_indexes("douyu_tasks")
|
||||
}
|
||||
rows = conn.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT status, message, active_binding_key
|
||||
FROM douyu_tasks
|
||||
WHERE batch_id = 'repair-0107-batch'
|
||||
ORDER BY id
|
||||
"""
|
||||
)
|
||||
).mappings().all()
|
||||
assert "active_binding_key" in columns
|
||||
assert "uq_douyu_tasks_active_binding" in indexes
|
||||
assert [row["status"] for row in rows] == ["stopped", "running"]
|
||||
assert rows[0]["active_binding_key"] is None
|
||||
assert rows[1]["active_binding_key"] == "bind:555"
|
||||
finally:
|
||||
database_module.DATABASE_URL = original_url
|
||||
mig_engine.dispose()
|
||||
with admin_engine.begin() as conn:
|
||||
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
|
||||
|
||||
def test_0077_converts_super_admin_membership_to_overlay(self):
|
||||
creds = get_mysql_credentials()
|
||||
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
|
||||
|
||||
@@ -455,6 +455,95 @@ class TestSyncAndMapping(_Base):
|
||||
assert task.execution_status == "ready"
|
||||
assert task.commodity_id == COMMODITY
|
||||
assert task.required_points == 1280
|
||||
assert task.sale_mode == "unknown"
|
||||
assert task.campaign_key == "douyu-current"
|
||||
assert task.classification_source == "unknown"
|
||||
|
||||
def test_mapping_sale_mode_is_snapshotted_and_drives_presale_queue(self):
|
||||
task = self.task(mapped=False)
|
||||
self.session.add(
|
||||
DouyuGoodsSnapshot(
|
||||
commodity_id=COMMODITY,
|
||||
name=INTERNAL_SKU,
|
||||
score=1280,
|
||||
)
|
||||
)
|
||||
self.session.commit()
|
||||
available_from = NOW + timedelta(days=1)
|
||||
|
||||
mapping = service.create_mapping(
|
||||
self.session,
|
||||
internal_sku_key=INTERNAL_SKU,
|
||||
campaign_key="douyu-2026-12-return",
|
||||
campaign_name="12 月返场",
|
||||
commodity_id=COMMODITY,
|
||||
goods_name=INTERNAL_SKU,
|
||||
required_points=1280,
|
||||
sale_mode="presale",
|
||||
available_from=available_from,
|
||||
available_until=available_from + timedelta(days=7),
|
||||
released_at=None,
|
||||
enabled=True,
|
||||
current=self.admin,
|
||||
)
|
||||
|
||||
self.session.refresh(task)
|
||||
detail = service.get_task_detail(self.session, task.id)
|
||||
assert mapping["saleMode"] == "presale"
|
||||
assert mapping["availabilityState"] == "waiting_release"
|
||||
assert task.sale_mode == "presale"
|
||||
assert task.campaign_key == "douyu-2026-12-return"
|
||||
assert task.classification_source == "mapping"
|
||||
assert detail["task"]["queueBucket"] == "presale_waiting"
|
||||
assert detail["task"]["availabilityState"] == "waiting_release"
|
||||
|
||||
def test_mapping_crud_archive_and_delete_guard(self):
|
||||
task = self.task(mapped=False)
|
||||
self.session.commit()
|
||||
created = service.create_mapping(
|
||||
self.session,
|
||||
internal_sku_key=INTERNAL_SKU,
|
||||
campaign_key="douyu-2026-12-direct",
|
||||
campaign_name="12 月现货",
|
||||
commodity_id=COMMODITY,
|
||||
goods_name=INTERNAL_SKU,
|
||||
required_points=1280,
|
||||
sale_mode="direct",
|
||||
available_from=NOW,
|
||||
available_until=NOW + timedelta(days=30),
|
||||
released_at=NOW,
|
||||
enabled=True,
|
||||
current=self.admin,
|
||||
)
|
||||
updated = service.update_mapping(
|
||||
self.session,
|
||||
mapping_id=created["id"],
|
||||
internal_sku_key=INTERNAL_SKU,
|
||||
campaign_key="douyu-2026-12-direct",
|
||||
campaign_name="12 月现货修正",
|
||||
commodity_id=COMMODITY,
|
||||
goods_name="套装-兔兔白日梦(斗鱼)",
|
||||
required_points=1280,
|
||||
sale_mode="direct",
|
||||
available_from=NOW,
|
||||
available_until=NOW + timedelta(days=30),
|
||||
released_at=NOW,
|
||||
enabled=True,
|
||||
current=self.admin,
|
||||
)
|
||||
|
||||
assert updated["campaignName"] == "12 月现货修正"
|
||||
assert updated["version"] == 2
|
||||
with pytest.raises(HTTPException, match="只能归档"):
|
||||
service.delete_mapping(self.session, mapping_id=created["id"])
|
||||
archived = service.archive_mapping(
|
||||
self.session,
|
||||
mapping_id=created["id"],
|
||||
current=self.admin,
|
||||
)
|
||||
self.session.refresh(task)
|
||||
assert archived["archivedAt"] is not None
|
||||
assert task.execution_status == "pending_mapping"
|
||||
|
||||
|
||||
class TestFulfillmentCollabSync(_Base):
|
||||
|
||||
@@ -196,6 +196,11 @@ def run_migrations():
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
from .migrations.immutability import verify_manifest
|
||||
|
||||
# Alembic 不会检测旧迁移内容被改写。启动前先锁文件哈希,避免已执行迁移
|
||||
# 在全新环境产生另一套结构。
|
||||
verify_manifest()
|
||||
config = Config(str(PROJECT_ROOT / "alembic.ini"))
|
||||
config.set_main_option(
|
||||
"script_location", str(PROJECT_ROOT / "web" / "backend" / "migrations")
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
"""已发布 Alembic 迁移文件的不可变校验。
|
||||
|
||||
Alembic 只记录 revision,不记录脚本内容。修改已经执行过的迁移不会再次运行,
|
||||
但全新库会执行新内容,最终造成生产与开发/新环境结构分叉。
|
||||
|
||||
本模块用提交到仓库的 SHA256 manifest 锁定每个迁移文件。新增迁移后显式运行:
|
||||
|
||||
uv run python -m web.backend.migrations.immutability --write
|
||||
|
||||
已有迁移的任何内容变化都会让应用启动和测试直接失败。修正历史迁移只能新增
|
||||
后续 repair revision,不能改写旧文件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parent
|
||||
VERSIONS_DIR = MIGRATIONS_DIR / "versions"
|
||||
MANIFEST_PATH = MIGRATIONS_DIR / "migration_manifest.json"
|
||||
_REVISION_RE = re.compile(
|
||||
r'^revision(?::\s*str)?\s*=\s*["\']([^"\']+)["\']',
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
|
||||
class MigrationManifestError(RuntimeError):
|
||||
"""迁移文件与不可变 manifest 不一致。"""
|
||||
|
||||
|
||||
def _migration_files(versions_dir: Path = VERSIONS_DIR) -> list[Path]:
|
||||
return sorted(
|
||||
(
|
||||
path
|
||||
for path in versions_dir.glob("*.py")
|
||||
if path.is_file() and not path.name.startswith("__")
|
||||
),
|
||||
key=lambda path: path.name,
|
||||
)
|
||||
|
||||
|
||||
def _revision(path: Path) -> str:
|
||||
match = _REVISION_RE.search(path.read_text(encoding="utf-8"))
|
||||
if match is None:
|
||||
raise MigrationManifestError(f"迁移文件缺少 revision: {path.name}")
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def build_manifest(versions_dir: Path = VERSIONS_DIR) -> dict[str, Any]:
|
||||
migrations = {
|
||||
path.name: {
|
||||
"revision": _revision(path),
|
||||
"sha256": _sha256(path),
|
||||
}
|
||||
for path in _migration_files(versions_dir)
|
||||
}
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"description": "Alembic migration immutability manifest; never edit released files.",
|
||||
"migrations": migrations,
|
||||
}
|
||||
|
||||
|
||||
def write_manifest(
|
||||
*,
|
||||
versions_dir: Path = VERSIONS_DIR,
|
||||
manifest_path: Path = MANIFEST_PATH,
|
||||
force: bool = False,
|
||||
) -> None:
|
||||
current = build_manifest(versions_dir)
|
||||
if manifest_path.exists() and not force:
|
||||
expected = load_manifest(manifest_path)["migrations"]
|
||||
current_migrations = current["migrations"]
|
||||
deleted = sorted(set(expected) - set(current_migrations))
|
||||
changed = sorted(
|
||||
filename
|
||||
for filename in set(expected) & set(current_migrations)
|
||||
if expected[filename] != current_migrations[filename]
|
||||
)
|
||||
if deleted or changed:
|
||||
details = [*(f"删除: {name}" for name in deleted), *(
|
||||
f"修改: {name}" for name in changed
|
||||
)]
|
||||
raise MigrationManifestError(
|
||||
"拒绝更新已发布迁移,只有新增迁移可以写入 manifest:\n- "
|
||||
+ "\n- ".join(details)
|
||||
+ "\n如确属灾难恢复,必须显式使用 --force 并人工审查 diff。"
|
||||
)
|
||||
manifest_path.write_text(
|
||||
json.dumps(current, ensure_ascii=False, indent=2) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def load_manifest(manifest_path: Path = MANIFEST_PATH) -> dict[str, Any]:
|
||||
if not manifest_path.exists():
|
||||
raise MigrationManifestError(
|
||||
f"缺少迁移不可变 manifest: {manifest_path}。"
|
||||
" 请运行 python -m web.backend.migrations.immutability --write"
|
||||
)
|
||||
try:
|
||||
payload = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
raise MigrationManifestError(
|
||||
f"迁移 manifest 无法读取: {manifest_path}: {exc}"
|
||||
) from exc
|
||||
if not isinstance(payload, dict) or payload.get("schema_version") != 1:
|
||||
raise MigrationManifestError("迁移 manifest 格式或 schema_version 不正确")
|
||||
migrations = payload.get("migrations")
|
||||
if not isinstance(migrations, dict):
|
||||
raise MigrationManifestError("迁移 manifest 缺少 migrations 映射")
|
||||
return payload
|
||||
|
||||
|
||||
def verify_manifest(
|
||||
*,
|
||||
versions_dir: Path = VERSIONS_DIR,
|
||||
manifest_path: Path = MANIFEST_PATH,
|
||||
) -> None:
|
||||
expected = load_manifest(manifest_path)["migrations"]
|
||||
actual = build_manifest(versions_dir)["migrations"]
|
||||
errors: list[str] = []
|
||||
missing = sorted(set(expected) - set(actual))
|
||||
added = sorted(set(actual) - set(expected))
|
||||
if missing:
|
||||
errors.append(f"已锁定迁移文件被删除: {', '.join(missing)}")
|
||||
if added:
|
||||
errors.append(f"存在未登记新迁移: {', '.join(added)}")
|
||||
for filename in sorted(set(expected) & set(actual)):
|
||||
old = expected[filename]
|
||||
current = actual[filename]
|
||||
if not isinstance(old, dict):
|
||||
errors.append(f"manifest 条目格式错误: {filename}")
|
||||
continue
|
||||
if old.get("revision") != current["revision"]:
|
||||
errors.append(
|
||||
f"迁移 revision 被修改: {filename} "
|
||||
f"{old.get('revision')} -> {current['revision']}"
|
||||
)
|
||||
if old.get("sha256") != current["sha256"]:
|
||||
errors.append(f"已发布迁移内容被修改: {filename}")
|
||||
if errors:
|
||||
raise MigrationManifestError(
|
||||
"迁移不可变校验失败:\n- "
|
||||
+ "\n- ".join(errors)
|
||||
+ "\n修正历史结构必须新增 revision;"
|
||||
"只有新增迁移时才允许更新 migration_manifest.json。"
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="斗鱼迁移不可变 manifest")
|
||||
parser.add_argument(
|
||||
"--write",
|
||||
action="store_true",
|
||||
help="登记新增迁移(默认拒绝修改已存在迁移)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force",
|
||||
action="store_true",
|
||||
help="灾难恢复时强制重写已有迁移哈希;必须先人工审查",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if args.write:
|
||||
write_manifest(force=args.force)
|
||||
print(f"已写入 {MANIFEST_PATH}")
|
||||
return
|
||||
verify_manifest()
|
||||
print("迁移不可变校验通过")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,434 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"description": "Alembic migration immutability manifest; never edit released files.",
|
||||
"migrations": {
|
||||
"20260623_0001_initial_web_schema.py": {
|
||||
"revision": "20260623_0001",
|
||||
"sha256": "cd02cf4e3217e9dd47899bf2143edc9d8323820dffcb1b909e15b9d6cfed3c5d"
|
||||
},
|
||||
"20260624_0002_sensitive_columns_text.py": {
|
||||
"revision": "20260624_0002",
|
||||
"sha256": "f2ffb5bcc7fa6584e2dec3c750bb614f8d6a6027676c8532231044fa2a6eed0f"
|
||||
},
|
||||
"20260624_0003_proxy_platform.py": {
|
||||
"revision": "20260624_0003",
|
||||
"sha256": "3b4dd82907e867eb8326426631244dcad96aae6e1b06409431ac235e64cfe3d8"
|
||||
},
|
||||
"20260704_0004_huya_foundation.py": {
|
||||
"revision": "20260704_0004",
|
||||
"sha256": "325ffd2d177dcd803bbe800b8068497ca0aae9c8ae9bb387e0373f37ca8f81e4"
|
||||
},
|
||||
"20260704_0005_huya_recharge_goods.py": {
|
||||
"revision": "20260704_0005",
|
||||
"sha256": "fadfdd282163179146d08a501513f76770793fafa6f051d27a7342e98adf5152"
|
||||
},
|
||||
"20260705_0006_huya_password_accounts.py": {
|
||||
"revision": "20260705_0006",
|
||||
"sha256": "98166e52a0a01ed83acd704b54a23b5c6f5fa0f41b276d89ecce83af6c83d229"
|
||||
},
|
||||
"20260712_0007_huya_register_history.py": {
|
||||
"revision": "20260712_0007",
|
||||
"sha256": "910580e990167cd93f23d4e8a07bc0f7790ef641d25ae0fef67d8b26c9b8a8ce"
|
||||
},
|
||||
"20260724_0008_douyu_activity_tasks.py": {
|
||||
"revision": "20260724_0008",
|
||||
"sha256": "98e66ffa5a922771dbf1011c429356eaa55689b529fc4ff6713ca93cc41de278"
|
||||
},
|
||||
"20260725_0009_database_performance_indexes.py": {
|
||||
"revision": "20260725_0009",
|
||||
"sha256": "99fe5a9c73a1f52c0106f597193a82e2c86ebac8998381781aa80cc70ebea2e8"
|
||||
},
|
||||
"20260728_0010_douyu_esports_handbook.py": {
|
||||
"revision": "20260728_0010",
|
||||
"sha256": "999e2d695830eda9d57b59359870bb06c8a2ef3bcd51f90539d90cae9b45ddad"
|
||||
},
|
||||
"20260728_0011_douyu_esports_account_fields.py": {
|
||||
"revision": "20260728_0011",
|
||||
"sha256": "f8c0131c69077f874ab7fdd92bee1aeb6c3dfe118e2902948d897410a441fc0f"
|
||||
},
|
||||
"20260728_0012_douyu_esports_can_change_time.py": {
|
||||
"revision": "20260728_0012",
|
||||
"sha256": "c52302fe586e5ee45bdc8bc01e7abaa4ecf87d3c4aec46c7b7690349e12c3f21"
|
||||
},
|
||||
"20260728_0013_douyu_esports_gift_config.py": {
|
||||
"revision": "20260728_0013",
|
||||
"sha256": "6a432c0f012b2a93fc2bec936b2728045b2642b6e9560296700d5805e627ad9c"
|
||||
},
|
||||
"20260728_0014_douyu_esports_goods_snapshot.py": {
|
||||
"revision": "20260728_0014",
|
||||
"sha256": "1697204aa4e81b1d9b853efc31c2d4b56b01283c71f676b183b4e2bb835a566c"
|
||||
},
|
||||
"20260805_0015_task_status_indexes.py": {
|
||||
"revision": "20260805_0015",
|
||||
"sha256": "afeed7ab8611771710a55d3e5e9e69b65d68c99dea8c494be1071f318ca5ccaf"
|
||||
},
|
||||
"20260806_0016_douyu_peace_shop.py": {
|
||||
"revision": "20260806_0016",
|
||||
"sha256": "209e9489093a702d274c57cfd18803b00a48a8c95d5d1b14bac22ca179adb136"
|
||||
},
|
||||
"20260807_0017_douyu_xpd_fragments.py": {
|
||||
"revision": "20260807_0017",
|
||||
"sha256": "40b911f0caac903b24e76231ae299d1ee35011d4c4833e19e50fc099a566ba44"
|
||||
},
|
||||
"20260807_0018_cookie_check_fields.py": {
|
||||
"revision": "20260807_0018",
|
||||
"sha256": "3b3cfe95f6f1fb580cee39931cbd3dd55d967583f0c459c937efa15660bd29fb"
|
||||
},
|
||||
"20260808_0019_dedupe_douyu_success_cookies.py": {
|
||||
"revision": "20260808_0019",
|
||||
"sha256": "9f14024a4d35029de2fba4f18cda2c3dc447f5f145f69eaaa1be99f2674969b9"
|
||||
},
|
||||
"20260812_0020_yyb_recharge.py": {
|
||||
"revision": "20260812_0020",
|
||||
"sha256": "c369c0bf02a18843bf915a4e559f62530dc89e5c3bbf7987134a860235c11097"
|
||||
},
|
||||
"20260812_0021_yyb_qr_mediumtext.py": {
|
||||
"revision": "20260812_0021",
|
||||
"sha256": "45cbae6dd4cc1cdd6f930ced31982ddac3024b9020b0fef6371cd27466fa8693"
|
||||
},
|
||||
"20260812_0022_yyb_payment_meta.py": {
|
||||
"revision": "20260812_0022",
|
||||
"sha256": "0208ef533f0236ffd387278d5071f2516050608c24a7da918d48f52eec19044e"
|
||||
},
|
||||
"20260813_0023_soft_delete_users.py": {
|
||||
"revision": "20260813_0023",
|
||||
"sha256": "c3a7f74043c77d28bf41a86ddc1a7247747b38720d7536212e64a0b2ccb27a59"
|
||||
},
|
||||
"20260813_0024_douyu_workbench_scopes.py": {
|
||||
"revision": "20260813_0024",
|
||||
"sha256": "bd10cf3b7af6014aaeef5f5b98a1654670464b740dcb9c0368053e56b6d932e4"
|
||||
},
|
||||
"20260813_0025_douyu_workbench_empty_state.py": {
|
||||
"revision": "20260813_0025",
|
||||
"sha256": "3dbcbc3209fe5edfb144b70d6e702f11d15314600cffd7ff4c8a47a2bd3d8a96"
|
||||
},
|
||||
"20260813_0026_douyu_gold_recharge_channel.py": {
|
||||
"revision": "20260813_0026",
|
||||
"sha256": "188cb9278db9e3670aea28a85ff526fe88c6ad70a2ee6bd493733a5dc7801479"
|
||||
},
|
||||
"20260813_0027_douyu_supplier_order_id.py": {
|
||||
"revision": "20260813_0027",
|
||||
"sha256": "86bab5b4aea31bb1cd6489c5722e8797dcd61416cd02586052c7f4bcc024b2db"
|
||||
},
|
||||
"20260814_0028_douyu_nickname_recharge.py": {
|
||||
"revision": "20260814_0028",
|
||||
"sha256": "d51b7b52b69cb4e160c9e66956073ce8d807e3be764853d96614d732b6f11bc5"
|
||||
},
|
||||
"20260814_0029_audit_log_result.py": {
|
||||
"revision": "20260814_0029",
|
||||
"sha256": "a99aa0e44a7453f023760c5eef0ea33a015d8098f8821a676208c6311a0f191a"
|
||||
},
|
||||
"20260829_0030_huya_login_channel.py": {
|
||||
"revision": "20260829_0030",
|
||||
"sha256": "c42715ea438e8c5fd4b48065e9aee5a93d8425c38e8508ccd9429e8b303e751f"
|
||||
},
|
||||
"20260830_0031_mysql_task_query_indexes.py": {
|
||||
"revision": "20260830_0031",
|
||||
"sha256": "574542e230daf76d1e20f7f91a170579d5bbc206ab12449ca8e7cb3833186171"
|
||||
},
|
||||
"20260831_0032_huya_elite_workbench.py": {
|
||||
"revision": "20260831_0032",
|
||||
"sha256": "f1b7d9a9da1ff286e865f3aa3e01616c7710b6f5f235a03c06f4b9c26e673b6b"
|
||||
},
|
||||
"20260901_0033_huya_snapshot_scope.py": {
|
||||
"revision": "20260901_0033",
|
||||
"sha256": "cc6f31c6d12fe06d8ddd8c6793e3e677e1dec448f28e60f6d1265dbb49be70fd"
|
||||
},
|
||||
"20260901_0034_huya_accounts_raw_cookie.py": {
|
||||
"revision": "20260901_0034",
|
||||
"sha256": "a5ea8519e209822b9569765b9462f98fb47782a55a74eccf39828ce6c2686fb0"
|
||||
},
|
||||
"20261001_0035_login_attempt_fields.py": {
|
||||
"revision": "20261001_0035",
|
||||
"sha256": "13fe378d866a139db0f008210a735440e433804cdca59b4940a4409086ebfb51"
|
||||
},
|
||||
"20261001_0036_elite_handbook_status.py": {
|
||||
"revision": "20261001_0036",
|
||||
"sha256": "e6361fa4af24e7a0743e5a98cc153e87482e732c670008755c3694662c03ef7f"
|
||||
},
|
||||
"20261002_0037_automation_jobs.py": {
|
||||
"revision": "20261002_0037",
|
||||
"sha256": "12bb6526244f8a14908543d4dffc6eb0c14c9fe9305a46a103101c5fde2ec170"
|
||||
},
|
||||
"20261002_0038_relogin_failure_kind.py": {
|
||||
"revision": "20261002_0038",
|
||||
"sha256": "4550d39266422ced34ed1a6ca8800aeb72fb765ec814a88165faddc591409716"
|
||||
},
|
||||
"20261002_0039_external_order_cache.py": {
|
||||
"revision": "20261002_0039",
|
||||
"sha256": "884d9ba57870af91ef709ccf4ec308d48b1ea1dc5580523e02667a492edf6a9f"
|
||||
},
|
||||
"20261003_0040_douyu_tasks_account_assigned_to.py": {
|
||||
"revision": "20261003_0040",
|
||||
"sha256": "154ac7d1725b128a8f36a8cf65a38c6bc26ef59b8c33e2b8b30b7b7caebe6692"
|
||||
},
|
||||
"20261003_0041_account_events.py": {
|
||||
"revision": "20261003_0041",
|
||||
"sha256": "ac986e1000b57271994e7b85a69171553062bf39b3fcd04cba7a3b69f1f10813"
|
||||
},
|
||||
"20261003_0042_account_lifecycle.py": {
|
||||
"revision": "20261003_0042",
|
||||
"sha256": "69a8b802e7fb5f2cb2b4f5593ed6d11b52c1a91f369cf1e0529e24c43f696bd2"
|
||||
},
|
||||
"20261004_0043_drop_events_collect_job.py": {
|
||||
"revision": "20261004_0043",
|
||||
"sha256": "125381337c73a0c94a9c4bc0e03e28414566504fe055cc3c1dfd3c72afd9c8cd"
|
||||
},
|
||||
"20261004_0044_bind_status_split.py": {
|
||||
"revision": "20261004_0044",
|
||||
"sha256": "a7643c351d447c8a68c82688f8d6f20c83c6a6a7be0de5dbe3f424f63272caf8"
|
||||
},
|
||||
"20261004_0045_source_ref_nullable.py": {
|
||||
"revision": "20261004_0045",
|
||||
"sha256": "f73339b8f5251780af379d9b9e5c354b0f42af26443974c18fc754b1c2a2fd0e"
|
||||
},
|
||||
"20261004_0046_points_expire_at.py": {
|
||||
"revision": "20261004_0046",
|
||||
"sha256": "946f71c8c4c10fe90c743d63c89ce43cfa57963c101f799f11a949f555be456a"
|
||||
},
|
||||
"20261004_0047_account_overview_snapshot.py": {
|
||||
"revision": "20261004_0047",
|
||||
"sha256": "830eaae43249d32248ba5e5088294bb2e0cccdb86a1d4dce0c63b8c5e04b80ee"
|
||||
},
|
||||
"20261004_0048_high_value_owned.py": {
|
||||
"revision": "20261004_0048",
|
||||
"sha256": "2bba43e45fb9cb245ee78cd5d02e9d376245e0d21ca17aece126dc4a6bc5617e"
|
||||
},
|
||||
"20261004_0049_esports_expire_time.py": {
|
||||
"revision": "20261004_0049",
|
||||
"sha256": "ab42b086ca2736a2a84313ec43e436edfff74d5092c52467e0df56c878159c2b"
|
||||
},
|
||||
"20261004_0050_peace_enabled.py": {
|
||||
"revision": "20261004_0050",
|
||||
"sha256": "af3f84576ce8614b8de3bf6ba8331a17f156ae8d3f241cb5fa55222c1f113e41"
|
||||
},
|
||||
"20261004_0051_run_interval.py": {
|
||||
"revision": "20261004_0051",
|
||||
"sha256": "896dd9ab0c35402530eaac94565024763565a18b44aeb1fab5ac5a85caed6ca4"
|
||||
},
|
||||
"20261008_0052_relogin_failure_kind_sync.py": {
|
||||
"revision": "20261008_0052",
|
||||
"sha256": "c87154130a893798e0ef2c5787d28a9c117766612669a61f9c72cc94dee9bafb"
|
||||
},
|
||||
"20261015_0053_huya_elite_open.py": {
|
||||
"revision": "20261015_0053",
|
||||
"sha256": "559b95086e623b5026e5154bccb0be54dc34ce865f9add61b88ca5dc48359c2c"
|
||||
},
|
||||
"20261016_0054_file_assets.py": {
|
||||
"revision": "20261016_0054",
|
||||
"sha256": "e0d3dba7e899641572c72cc5ed314762bcf4bb1619aad4fbe9105e67dc25bc8d"
|
||||
},
|
||||
"20261016_0055_huya_external_orders.py": {
|
||||
"revision": "20261016_0055",
|
||||
"sha256": "2f358e18a4a5001e56dbaa6f24576b996d968eb02b953913ef49af87a33c93bc"
|
||||
},
|
||||
"20261016_0056_huya_order_bind_snapshot.py": {
|
||||
"revision": "20261016_0056",
|
||||
"sha256": "f83c46d1c10d0e871127b83b28a0da20e33d2e5a999ac34a2199a7f5f0705d45"
|
||||
},
|
||||
"20261016_0057_huya_collab_shops.py": {
|
||||
"revision": "20261016_0057",
|
||||
"sha256": "3caa37490a4c20c0a561622f12f45d1a84c7b6d0ef3b7b3c73d4d94dd74b89a0"
|
||||
},
|
||||
"20261016_0058_huya_order_uid_not_unique.py": {
|
||||
"revision": "20261016_0058",
|
||||
"sha256": "93845268bbf4edd8e409138f6a3b2cb291f1d30cecd37ea2e717a7fc385ba634"
|
||||
},
|
||||
"20261016_0059_huya_order_metrics.py": {
|
||||
"revision": "20261016_0059",
|
||||
"sha256": "2c2da487e5b522bffec45f0c367e0936735591cc53d532bf25293073d5528cea"
|
||||
},
|
||||
"20261019_0060_huya_order_archive.py": {
|
||||
"revision": "20261019_0060",
|
||||
"sha256": "b3e7780565c6ac9496d79d7cc5502050237451e4f6a6532fa4fb8a526c417943"
|
||||
},
|
||||
"20261019_0061_huya_order_recharge_points.py": {
|
||||
"revision": "20261019_0061",
|
||||
"sha256": "5d983fe1a26e5931d2957398fd9880907ac44ef4549b005b111f4dffbefa401b"
|
||||
},
|
||||
"20261020_0062_douyu_external_orders.py": {
|
||||
"revision": "20261020_0062",
|
||||
"sha256": "9325e93f2451d967ce92e1323f1bf92b56ce28c45c0422499cc3ec6f8ad9eb54"
|
||||
},
|
||||
"20261021_0063_user_phone_device_auth.py": {
|
||||
"revision": "20261021_0063",
|
||||
"sha256": "11147065b8b402019d3e2c25cf2330f7b6a90e3017d8cdb857b135dda89e6149"
|
||||
},
|
||||
"20261021_0064_repair_user_phone_device_auth.py": {
|
||||
"revision": "20261021_0064",
|
||||
"sha256": "31071ae597bfa4b1a460ae2f40a6869acd902afed6269721fb1801d16cc441ad"
|
||||
},
|
||||
"20261106_0065_account_high_value_status.py": {
|
||||
"revision": "20261106_0065",
|
||||
"sha256": "ec4f6d1939c025e3ee0afb4492c5a378749a075f4220a6938926842dbe3c538f"
|
||||
},
|
||||
"20261106_0066_douyu_collab_gifts.py": {
|
||||
"revision": "20261106_0066",
|
||||
"sha256": "0555e4f0eb4f811136c2ec6b939f25d58be78ddfeb8d4b046f8c639c6fad8903"
|
||||
},
|
||||
"20261107_0067_huya_collab_gifts.py": {
|
||||
"revision": "20261107_0067",
|
||||
"sha256": "e9e39d4b0ff1a06d9845745db53501c913bcb2925a0881343c4446a49d4348e4"
|
||||
},
|
||||
"20261107_0068_weibo_accounts.py": {
|
||||
"revision": "20261107_0068",
|
||||
"sha256": "f0059768bac782b89b8c97098a5586dc3d3d01f72a48faa6560a933cb6c257e3"
|
||||
},
|
||||
"20261107_0069_weibo_activity.py": {
|
||||
"revision": "20261107_0069",
|
||||
"sha256": "9b9cc447bf83cdb29e6d943721a7d62d47225feea681246d4d1b02e1dafadb6c"
|
||||
},
|
||||
"20261108_0070_weibo_account_lifecycle.py": {
|
||||
"revision": "20261108_0070",
|
||||
"sha256": "e49c26704da4fd2e1b271748fd62e440b07673e06cde41fca7d0722ffe2fadca"
|
||||
},
|
||||
"20261108_0071_weibo_external_orders.py": {
|
||||
"revision": "20261108_0071",
|
||||
"sha256": "fb4e6e3427b75f9b438fe1fea2d1c436908f4fd5574db2f17aff53c9e703fad6"
|
||||
},
|
||||
"20261108_0072_weibo_workbench.py": {
|
||||
"revision": "20261108_0072",
|
||||
"sha256": "716825a7619b25f2c1fd7032ed31beb2fa30f11e29bc3469c86593f8a9f06e74"
|
||||
},
|
||||
"20261108_0073_weibo_workbench_exclusive.py": {
|
||||
"revision": "20261108_0073",
|
||||
"sha256": "22b64013046d0136fbab06bd868223d363dab38cbd82494722269feb181cf52b"
|
||||
},
|
||||
"20261108_0074_weibo_account_assignee.py": {
|
||||
"revision": "20261108_0074",
|
||||
"sha256": "209c0f21064af06b6f9db3a76d1d02c6068dd14af08e4a10065d6e3cd0a027f0"
|
||||
},
|
||||
"20261109_0075_huya_bind_gid.py": {
|
||||
"revision": "20261109_0075",
|
||||
"sha256": "b0c670da39a45eccfad57c65452237178908754ea45a608380d6e6f49951e816"
|
||||
},
|
||||
"20261111_0076_huya_points_center_config.py": {
|
||||
"revision": "20261111_0076",
|
||||
"sha256": "3af9e5909c983aedc63778e57f50fcda78b13f115c1822e62d05c984a72eed75"
|
||||
},
|
||||
"20261112_0077_weibo_workbench_admin_overlay.py": {
|
||||
"revision": "20261112_0077",
|
||||
"sha256": "cd11bd58402db547f0069c94f357bef63106474e933342d6c44feb5d7dd2bf43"
|
||||
},
|
||||
"20261112_0078_huya_void_points_snapshot_cleanup.py": {
|
||||
"revision": "20261112_0078",
|
||||
"sha256": "d61d14ab8c6a566e3765f61130c7822b0f7b62e120ccceac085a85ca6ff67df8"
|
||||
},
|
||||
"20261112_0079_weibo_remove_exchange_pending.py": {
|
||||
"revision": "20261112_0079",
|
||||
"sha256": "79dbfd9c5f17090d365ff30d318783ad65f753324363524412e8b5c5fec6e580"
|
||||
},
|
||||
"20261112_0080_weibo_order_scripted_at.py": {
|
||||
"revision": "20261112_0080",
|
||||
"sha256": "e11e4c1564e1b3a7bf8414d7b410497d125776063a0346feb6a3a6dbbcf44812"
|
||||
},
|
||||
"20261113_0081_huya_exchange_proxy.py": {
|
||||
"revision": "20261113_0081",
|
||||
"sha256": "ca40c671317bd9ca915863447f75cae56f8771b448c7d9e8a034df5d3bf496f5"
|
||||
},
|
||||
"20261113_0082_weibo_recharge_records.py": {
|
||||
"revision": "20261113_0082",
|
||||
"sha256": "a2f92431bf097fbc10c0d83763b2f169ae467f80c988484a58c53d211d6723bb"
|
||||
},
|
||||
"20261117_0083_account_leases.py": {
|
||||
"revision": "20261117_0083",
|
||||
"sha256": "f2735b74b51d446196b72dec8cd580549695f3a7a678f0380d9a54b6d2f8e18a"
|
||||
},
|
||||
"20261117_0084_platform_fulfillment.py": {
|
||||
"revision": "20261117_0084",
|
||||
"sha256": "7f9dda6954bad754ea355235cfaf9928b025f9779949f9ed34d57ac39ef79157"
|
||||
},
|
||||
"20261117_0085_platform_fulfillment_lease_settings.py": {
|
||||
"revision": "20261117_0085",
|
||||
"sha256": "541fed6236a5e0fcdc51a045f71c9ed77730402cdd5ddbefe29a3478eeafa6d4"
|
||||
},
|
||||
"20261117_0086_integration_outbox.py": {
|
||||
"revision": "20261117_0086",
|
||||
"sha256": "e445db9a66c8a4934e7f557f52a684541b42ce2ca01297393964f8c5a78cf754"
|
||||
},
|
||||
"20261118_0087_platform_fulfillment_order_cutoff.py": {
|
||||
"revision": "20261118_0087",
|
||||
"sha256": "287ff117c724eff75004b35d3f8fc4bd18c4f397957467aa226934a229adebfa"
|
||||
},
|
||||
"20261118_0088_platform_fulfillment_paid_at.py": {
|
||||
"revision": "20261118_0088",
|
||||
"sha256": "eefd925bb1dba983b5f9a7dc80d007298d20d794c68c6435be41f9079beb49b5"
|
||||
},
|
||||
"20261118_0089_platform_fulfillment_immediate_allocation.py": {
|
||||
"revision": "20261118_0089",
|
||||
"sha256": "fa8a3ac6957fa0f7c6a6fc8ecdb5a3af2f70b98ef230cca2440e820fdf093275"
|
||||
},
|
||||
"20261118_0090_repair_snapshot_ready_with_account.py": {
|
||||
"revision": "20261118_0090",
|
||||
"sha256": "fb60031bf5622c89715fd9ed9d784c441a7dcacc501c1b3bca32b812c245c800"
|
||||
},
|
||||
"20261118_0091_account_commodity_states.py": {
|
||||
"revision": "20261118_0091",
|
||||
"sha256": "89e15d90a4c0922244bc96975e33c42c1d4f31ad806f95ad5e42962bf2dad89f"
|
||||
},
|
||||
"20261118_0092_backfill_exchange_subject_key.py": {
|
||||
"revision": "20261118_0092",
|
||||
"sha256": "c07c130d586924cdcddc1391feb7a70efb36f62e8e37c0742e7f43978bc5fef2"
|
||||
},
|
||||
"20261118_0093_account_commodity_time_windows.py": {
|
||||
"revision": "20261118_0093",
|
||||
"sha256": "acebbb0305673150847df113279d01d6f96bbbf685e5079c16be85db9cd8d584"
|
||||
},
|
||||
"20261118_0094_douyu_collab_fulfillment_source.py": {
|
||||
"revision": "20261118_0094",
|
||||
"sha256": "6945da1814fcb988bce2269d060c982436e10937176f8615b791fb32612cf0bc"
|
||||
},
|
||||
"20261118_0095_repair_fulfillment_collab_order_no.py": {
|
||||
"revision": "20261118_0095",
|
||||
"sha256": "e5606563a61d938dd8a7c425fe81e45920a2a7ca4e38bd8a48c073b7a0ec33ab"
|
||||
},
|
||||
"20261118_0096_douyu_task_platform_context.py": {
|
||||
"revision": "20261118_0096",
|
||||
"sha256": "7e592bae2b46f6d9017ac8bd73d5e0d711e88e38ed81d411f919e436c7f87668"
|
||||
},
|
||||
"20261119_0097_douyu_workbench_account_order.py": {
|
||||
"revision": "20261119_0097",
|
||||
"sha256": "4201e51340ef21b1e51d0b7fd13a33466d82a8933471a7d895358bbdae8ee0cb"
|
||||
},
|
||||
"20261119_0098_douyu_collab_account_leases.py": {
|
||||
"revision": "20261119_0098",
|
||||
"sha256": "a27e9f9664df49ba1f6a7a54faed123f821f19098b1b61203586b866f10749e0"
|
||||
},
|
||||
"20261119_0099_douyu_tasks_created_at_index.py": {
|
||||
"revision": "20261119_0099",
|
||||
"sha256": "7fef1a4329d80abf789beab7f4e297e1335c604bf4beee442eb9f5255e2c723a"
|
||||
},
|
||||
"20261120_0100_douyu_tasks_created_scope_index.py": {
|
||||
"revision": "20261120_0100",
|
||||
"sha256": "7ea1facb225034e93bf3c995ae1ef64bd887c925ddd9eeb7749f09ec0c07a1b7"
|
||||
},
|
||||
"20261120_0101_douyu_task_durable_schedule.py": {
|
||||
"revision": "20261120_0101",
|
||||
"sha256": "6e6865e7795e3ab403a9d8febc728a4481b7e6bd3ff8cd5a9b9ca7e087b7ef59"
|
||||
},
|
||||
"20261120_0102_query_indexes.py": {
|
||||
"revision": "20261120_0102",
|
||||
"sha256": "56beed1505d09034105c9d3208480515248885ef91a35ed6141e0758e66a2937"
|
||||
},
|
||||
"20261120_0103_douyu_collab_success_lock.py": {
|
||||
"revision": "20261120_0103",
|
||||
"sha256": "91698301c6e67e25a2a43a39f0120c79f68525a1c5c4371897a48bdd68f5cdbe"
|
||||
},
|
||||
"20261121_0104_automation_retention_huya_index.py": {
|
||||
"revision": "20261121_0104",
|
||||
"sha256": "53f76edbbf7e38b2ee13e59518be2a35760faa1357561ac914d60fd307112e1c"
|
||||
},
|
||||
"20261121_0105_platform_exchange_result_image.py": {
|
||||
"revision": "20261121_0105",
|
||||
"sha256": "c29ebff3d9264115499a4667eeb42a24c5c251cd5b6d138cb36e644746dd0c1a"
|
||||
},
|
||||
"20261121_0106_fulfillment_classification.py": {
|
||||
"revision": "20261121_0106",
|
||||
"sha256": "17a9a5be7e26397dd24e1f5c220a585a014be01d62a941f46bb2a474a1d8a7a9"
|
||||
},
|
||||
"20261121_0107_repair_douyu_active_binding_key.py": {
|
||||
"revision": "20261121_0107",
|
||||
"sha256": "29539b5fab9c6d8eaf7219b7d19376dfa6032d8b6cf02b76fc2a843c09891302"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
"""履约工作台增加销售模式、活动批次和报价快照。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "20261121_0106"
|
||||
down_revision = "20261121_0105"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
MAPPING_TABLE = "platform_commodity_mappings"
|
||||
TASK_TABLE = "platform_fulfillment_tasks"
|
||||
OLD_UNIQUE = "uq_platform_commodity_mapping_sku"
|
||||
NEW_UNIQUE = "uq_platform_commodity_mapping_campaign"
|
||||
|
||||
|
||||
def _column_exists(table: str, column: str) -> bool:
|
||||
return bool(
|
||||
op.get_bind()
|
||||
.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = :table
|
||||
AND column_name = :column
|
||||
"""
|
||||
),
|
||||
{"table": table, "column": column},
|
||||
)
|
||||
.scalar()
|
||||
)
|
||||
|
||||
|
||||
def _constraint_exists(table: str, name: str) -> bool:
|
||||
return bool(
|
||||
op.get_bind()
|
||||
.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.table_constraints
|
||||
WHERE constraint_schema = DATABASE()
|
||||
AND table_name = :table
|
||||
AND constraint_name = :name
|
||||
"""
|
||||
),
|
||||
{"table": table, "name": name},
|
||||
)
|
||||
.scalar()
|
||||
)
|
||||
|
||||
|
||||
def _index_exists(table: str, name: str) -> bool:
|
||||
return bool(
|
||||
op.get_bind()
|
||||
.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.statistics
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = :table
|
||||
AND index_name = :name
|
||||
"""
|
||||
),
|
||||
{"table": table, "name": name},
|
||||
)
|
||||
.scalar()
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
mapping_columns = (
|
||||
sa.Column(
|
||||
"campaign_key",
|
||||
sa.String(length=128),
|
||||
nullable=False,
|
||||
server_default="douyu-current",
|
||||
),
|
||||
sa.Column(
|
||||
"campaign_name",
|
||||
sa.String(length=255),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"sale_mode",
|
||||
sa.String(length=16),
|
||||
nullable=False,
|
||||
server_default="unknown",
|
||||
),
|
||||
sa.Column("available_from", sa.DateTime(), nullable=True),
|
||||
sa.Column("available_until", sa.DateTime(), nullable=True),
|
||||
sa.Column("released_at", sa.DateTime(), nullable=True),
|
||||
sa.Column(
|
||||
"goods_status",
|
||||
sa.String(length=32),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"version",
|
||||
sa.Integer(),
|
||||
nullable=False,
|
||||
server_default="1",
|
||||
),
|
||||
sa.Column("archived_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("archived_by", sa.Integer(), nullable=True),
|
||||
)
|
||||
for column in mapping_columns:
|
||||
if not _column_exists(MAPPING_TABLE, column.name):
|
||||
op.add_column(MAPPING_TABLE, column)
|
||||
if not _constraint_exists(MAPPING_TABLE, "fk_platform_mapping_archived_by"):
|
||||
op.create_foreign_key(
|
||||
"fk_platform_mapping_archived_by",
|
||||
MAPPING_TABLE,
|
||||
"users",
|
||||
["archived_by"],
|
||||
["id"],
|
||||
ondelete="SET NULL",
|
||||
)
|
||||
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE platform_commodity_mappings
|
||||
SET campaign_key = 'douyu-current'
|
||||
WHERE campaign_key IS NULL OR campaign_key = ''
|
||||
"""
|
||||
)
|
||||
)
|
||||
if _constraint_exists(MAPPING_TABLE, OLD_UNIQUE):
|
||||
op.drop_constraint(OLD_UNIQUE, MAPPING_TABLE, type_="unique")
|
||||
if not _constraint_exists(MAPPING_TABLE, NEW_UNIQUE):
|
||||
op.create_unique_constraint(
|
||||
NEW_UNIQUE,
|
||||
MAPPING_TABLE,
|
||||
["target_platform", "internal_sku_key", "campaign_key"],
|
||||
)
|
||||
if not _index_exists(MAPPING_TABLE, "ix_platform_mapping_campaign"):
|
||||
op.create_index(
|
||||
"ix_platform_mapping_campaign",
|
||||
MAPPING_TABLE,
|
||||
["target_platform", "campaign_key", "archived_at"],
|
||||
)
|
||||
|
||||
task_columns = (
|
||||
sa.Column(
|
||||
"sale_mode",
|
||||
sa.String(length=16),
|
||||
nullable=False,
|
||||
server_default="unknown",
|
||||
),
|
||||
sa.Column(
|
||||
"campaign_key",
|
||||
sa.String(length=128),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"campaign_name",
|
||||
sa.String(length=255),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column("offer_available_from", sa.DateTime(), nullable=True),
|
||||
sa.Column("offer_available_until", sa.DateTime(), nullable=True),
|
||||
sa.Column(
|
||||
"classification_source",
|
||||
sa.String(length=24),
|
||||
nullable=False,
|
||||
server_default="unknown",
|
||||
),
|
||||
)
|
||||
for column in task_columns:
|
||||
if not _column_exists(TASK_TABLE, column.name):
|
||||
op.add_column(TASK_TABLE, column)
|
||||
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE platform_fulfillment_tasks AS task
|
||||
JOIN platform_commodity_mappings AS mapping
|
||||
ON mapping.id = task.commodity_mapping_id
|
||||
SET task.sale_mode = mapping.sale_mode,
|
||||
task.campaign_key = mapping.campaign_key,
|
||||
task.campaign_name = mapping.campaign_name,
|
||||
task.offer_available_from = mapping.available_from,
|
||||
task.offer_available_until = mapping.available_until,
|
||||
task.classification_source = 'mapping'
|
||||
WHERE task.sale_mode = 'unknown'
|
||||
AND task.classification_source = 'unknown'
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if _index_exists(MAPPING_TABLE, "ix_platform_mapping_campaign"):
|
||||
op.drop_index("ix_platform_mapping_campaign", table_name=MAPPING_TABLE)
|
||||
if _constraint_exists(MAPPING_TABLE, NEW_UNIQUE):
|
||||
op.drop_constraint(NEW_UNIQUE, MAPPING_TABLE, type_="unique")
|
||||
if not _constraint_exists(MAPPING_TABLE, OLD_UNIQUE):
|
||||
op.create_unique_constraint(
|
||||
OLD_UNIQUE,
|
||||
MAPPING_TABLE,
|
||||
["target_platform", "internal_sku_key"],
|
||||
)
|
||||
if _constraint_exists(MAPPING_TABLE, "fk_platform_mapping_archived_by"):
|
||||
op.drop_constraint(
|
||||
"fk_platform_mapping_archived_by",
|
||||
MAPPING_TABLE,
|
||||
type_="foreignkey",
|
||||
)
|
||||
|
||||
for column in (
|
||||
"classification_source",
|
||||
"offer_available_until",
|
||||
"offer_available_from",
|
||||
"campaign_name",
|
||||
"campaign_key",
|
||||
"sale_mode",
|
||||
):
|
||||
if _column_exists(TASK_TABLE, column):
|
||||
op.drop_column(TASK_TABLE, column)
|
||||
for column in (
|
||||
"archived_by",
|
||||
"archived_at",
|
||||
"version",
|
||||
"goods_status",
|
||||
"released_at",
|
||||
"available_until",
|
||||
"available_from",
|
||||
"sale_mode",
|
||||
"campaign_name",
|
||||
"campaign_key",
|
||||
):
|
||||
if _column_exists(MAPPING_TABLE, column):
|
||||
op.drop_column(MAPPING_TABLE, column)
|
||||
@@ -0,0 +1,84 @@
|
||||
"""修复 douyu_tasks.active_binding_key 缺失导致的服务启动失败。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "20261121_0107"
|
||||
down_revision = "20261121_0106"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
INDEX_NAME = "uq_douyu_tasks_active_binding"
|
||||
|
||||
|
||||
def _columns() -> set[str]:
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
if not inspector.has_table("douyu_tasks"):
|
||||
return set()
|
||||
return {column["name"] for column in inspector.get_columns("douyu_tasks")}
|
||||
|
||||
|
||||
def _indexes() -> set[str]:
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
if not inspector.has_table("douyu_tasks"):
|
||||
return set()
|
||||
return {index["name"] for index in inspector.get_indexes("douyu_tasks")}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
if "active_binding_key" not in _columns():
|
||||
op.add_column(
|
||||
"douyu_tasks",
|
||||
sa.Column(
|
||||
"active_binding_key",
|
||||
sa.String(length=64),
|
||||
sa.Computed(
|
||||
"CASE WHEN task_type = 'get_bind_qr' "
|
||||
"AND platform_task_id IS NOT NULL "
|
||||
"AND status IN ('planned', 'pending', 'running') "
|
||||
"THEN CONCAT('bind:', platform_task_id) ELSE NULL END",
|
||||
persisted=False,
|
||||
),
|
||||
nullable=True,
|
||||
),
|
||||
)
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE douyu_tasks AS task
|
||||
JOIN (
|
||||
SELECT platform_task_id, MAX(id) AS keep_id
|
||||
FROM douyu_tasks
|
||||
WHERE task_type = 'get_bind_qr'
|
||||
AND platform_task_id IS NOT NULL
|
||||
AND status IN ('planned', 'pending', 'running')
|
||||
GROUP BY platform_task_id
|
||||
HAVING COUNT(*) > 1
|
||||
) AS duplicate
|
||||
ON duplicate.platform_task_id = task.platform_task_id
|
||||
SET task.status = 'stopped',
|
||||
task.message = '已被新的绑定二维码任务取代(迁移修复)',
|
||||
task.finished_at = UTC_TIMESTAMP(),
|
||||
task.next_run_at = NULL
|
||||
WHERE task.task_type = 'get_bind_qr'
|
||||
AND task.status IN ('planned', 'pending', 'running')
|
||||
AND task.id <> duplicate.keep_id
|
||||
"""
|
||||
)
|
||||
)
|
||||
if INDEX_NAME not in _indexes():
|
||||
op.create_index(
|
||||
INDEX_NAME,
|
||||
"douyu_tasks",
|
||||
["active_binding_key"],
|
||||
unique=True,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if INDEX_NAME in _indexes():
|
||||
op.drop_index(INDEX_NAME, table_name="douyu_tasks")
|
||||
if "active_binding_key" in _columns():
|
||||
op.drop_column("douyu_tasks", "active_binding_key")
|
||||
+49
-2
@@ -1934,7 +1934,7 @@ class PlatformFulfillmentSetting(Base):
|
||||
|
||||
|
||||
class PlatformCommodityMapping(Base):
|
||||
"""order_site 内部 SKU 到斗鱼商品的显式映射。"""
|
||||
"""order_site 内部 SKU 到斗鱼商品的活动批次映射。"""
|
||||
|
||||
__tablename__ = "platform_commodity_mappings"
|
||||
|
||||
@@ -1943,6 +1943,12 @@ class PlatformCommodityMapping(Base):
|
||||
String(16), nullable=False, default="douyu", server_default="douyu"
|
||||
)
|
||||
internal_sku_key: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
campaign_key: Mapped[str] = mapped_column(
|
||||
String(128), nullable=False, default="douyu-current", server_default="douyu-current"
|
||||
)
|
||||
campaign_name: Mapped[str] = mapped_column(
|
||||
String(255), nullable=False, default="", server_default=""
|
||||
)
|
||||
commodity_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
goods_name: Mapped[str] = mapped_column(
|
||||
String(255), nullable=False, default="", server_default=""
|
||||
@@ -1951,9 +1957,31 @@ class PlatformCommodityMapping(Base):
|
||||
scope: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="elite", server_default="elite"
|
||||
)
|
||||
# presale / direct / manual / unknown
|
||||
sale_mode: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="unknown", server_default="unknown"
|
||||
)
|
||||
available_from: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
available_until: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
released_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
goods_status: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default="", server_default=""
|
||||
)
|
||||
enabled: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, default=True, server_default="1"
|
||||
)
|
||||
version: Mapped[int] = mapped_column(
|
||||
Integer, nullable=False, default=1, server_default="1"
|
||||
)
|
||||
archived_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
archived_by: Mapped[int | None] = mapped_column(
|
||||
ForeignKey(
|
||||
"users.id",
|
||||
ondelete="SET NULL",
|
||||
name="fk_platform_mapping_archived_by",
|
||||
),
|
||||
nullable=True,
|
||||
)
|
||||
created_by: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("users.id"), nullable=True
|
||||
)
|
||||
@@ -1966,7 +1994,8 @@ class PlatformCommodityMapping(Base):
|
||||
UniqueConstraint(
|
||||
"target_platform",
|
||||
"internal_sku_key",
|
||||
name="uq_platform_commodity_mapping_sku",
|
||||
"campaign_key",
|
||||
name="uq_platform_commodity_mapping_campaign",
|
||||
),
|
||||
Index(
|
||||
"ix_platform_commodity_mapping_enabled",
|
||||
@@ -2031,6 +2060,24 @@ class PlatformFulfillmentTask(Base):
|
||||
String(64), nullable=False, default="", server_default=""
|
||||
)
|
||||
required_points: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
sale_mode: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="unknown", server_default="unknown"
|
||||
)
|
||||
campaign_key: Mapped[str] = mapped_column(
|
||||
String(128), nullable=False, default="", server_default=""
|
||||
)
|
||||
campaign_name: Mapped[str] = mapped_column(
|
||||
String(255), nullable=False, default="", server_default=""
|
||||
)
|
||||
offer_available_from: Mapped[datetime | None] = mapped_column(
|
||||
UTCDateTime, nullable=True
|
||||
)
|
||||
offer_available_until: Mapped[datetime | None] = mapped_column(
|
||||
UTCDateTime, nullable=True
|
||||
)
|
||||
classification_source: Mapped[str] = mapped_column(
|
||||
String(24), nullable=False, default="unknown", server_default="unknown"
|
||||
)
|
||||
account_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("accounts.id", ondelete="SET NULL"), nullable=True, index=True
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
@@ -14,6 +14,7 @@ from ..schemas import (
|
||||
PlatformFulfillmentCollabSyncRequest,
|
||||
PlatformFulfillmentCompleteRequest,
|
||||
PlatformFulfillmentMappingUpsert,
|
||||
PlatformFulfillmentMappingWrite,
|
||||
PlatformFulfillmentReasonRequest,
|
||||
PlatformFulfillmentRestoreRequest,
|
||||
PlatformFulfillmentSettingsUpdate,
|
||||
@@ -61,6 +62,8 @@ def update_settings(
|
||||
@router.get("/tasks")
|
||||
def list_tasks(
|
||||
status: str = Query("", max_length=32),
|
||||
queue_bucket: str = Query("", max_length=32),
|
||||
sale_mode: str = Query("", max_length=16),
|
||||
keyword: str = Query("", max_length=200),
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(20, ge=1, le=100),
|
||||
@@ -71,6 +74,8 @@ def list_tasks(
|
||||
return service.list_tasks(
|
||||
db,
|
||||
status=status,
|
||||
queue_bucket=queue_bucket,
|
||||
sale_mode=sale_mode,
|
||||
keyword=keyword,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
@@ -132,11 +137,42 @@ def get_task(
|
||||
@router.get("/mappings")
|
||||
def list_mappings(
|
||||
keyword: str = Query("", max_length=200),
|
||||
sale_mode: str = Query("", max_length=16),
|
||||
enabled: bool | None = Query(None),
|
||||
include_archived: bool = Query(False),
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:view")),
|
||||
) -> list[dict[str, Any]]:
|
||||
del current
|
||||
return service.list_mappings(db, keyword=keyword)
|
||||
return service.list_mappings(
|
||||
db,
|
||||
keyword=keyword,
|
||||
sale_mode=sale_mode,
|
||||
enabled=enabled,
|
||||
include_archived=include_archived,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/mappings")
|
||||
def create_mapping(
|
||||
req: PlatformFulfillmentMappingWrite,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:admin")),
|
||||
) -> dict[str, Any]:
|
||||
result = service.create_mapping(
|
||||
db,
|
||||
**req.model_dump(),
|
||||
current=current,
|
||||
)
|
||||
record_audit(
|
||||
db,
|
||||
current,
|
||||
action="platform_fulfillment:mapping:create",
|
||||
target=f"platform_commodity_mapping:{result['id']}",
|
||||
detail=result,
|
||||
)
|
||||
db.commit()
|
||||
return result
|
||||
|
||||
|
||||
@router.put("/mappings")
|
||||
@@ -153,6 +189,12 @@ def upsert_mapping(
|
||||
required_points=req.required_points,
|
||||
enabled=req.enabled,
|
||||
current=current,
|
||||
campaign_key=req.campaign_key,
|
||||
campaign_name=req.campaign_name,
|
||||
sale_mode=req.sale_mode,
|
||||
available_from=req.available_from,
|
||||
available_until=req.available_until,
|
||||
released_at=req.released_at,
|
||||
)
|
||||
record_audit(
|
||||
db,
|
||||
@@ -165,6 +207,145 @@ def upsert_mapping(
|
||||
return result
|
||||
|
||||
|
||||
@router.patch("/mappings/{mapping_id}")
|
||||
def update_mapping(
|
||||
mapping_id: int,
|
||||
req: PlatformFulfillmentMappingWrite,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:admin")),
|
||||
) -> dict[str, Any]:
|
||||
result = service.update_mapping(
|
||||
db,
|
||||
mapping_id=mapping_id,
|
||||
**req.model_dump(),
|
||||
current=current,
|
||||
)
|
||||
record_audit(
|
||||
db,
|
||||
current,
|
||||
action="platform_fulfillment:mapping:update",
|
||||
target=f"platform_commodity_mapping:{mapping_id}",
|
||||
detail=result,
|
||||
)
|
||||
db.commit()
|
||||
return result
|
||||
|
||||
|
||||
@router.delete("/mappings/{mapping_id}")
|
||||
def delete_mapping(
|
||||
mapping_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:admin")),
|
||||
) -> dict[str, Any]:
|
||||
service.delete_mapping(db, mapping_id=mapping_id)
|
||||
record_audit(
|
||||
db,
|
||||
current,
|
||||
action="platform_fulfillment:mapping:delete",
|
||||
target=f"platform_commodity_mapping:{mapping_id}",
|
||||
detail={},
|
||||
)
|
||||
db.commit()
|
||||
return {"success": True}
|
||||
|
||||
|
||||
@router.get("/mappings/{mapping_id}/impact")
|
||||
def get_mapping_impact(
|
||||
mapping_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:view")),
|
||||
) -> dict[str, Any]:
|
||||
del current
|
||||
return service.mapping_impact(db, mapping_id=mapping_id)
|
||||
|
||||
|
||||
def _mapping_state_action(
|
||||
*,
|
||||
db: Session,
|
||||
current: User,
|
||||
mapping_id: int,
|
||||
action: str,
|
||||
) -> dict[str, Any]:
|
||||
if action in {"enable", "disable"}:
|
||||
result = service.set_mapping_enabled(
|
||||
db,
|
||||
mapping_id=mapping_id,
|
||||
enabled=action == "enable",
|
||||
current=current,
|
||||
)
|
||||
elif action == "archive":
|
||||
result = service.archive_mapping(db, mapping_id=mapping_id, current=current)
|
||||
elif action == "restore":
|
||||
result = service.restore_mapping(db, mapping_id=mapping_id)
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="未知映射操作")
|
||||
record_audit(
|
||||
db,
|
||||
current,
|
||||
action=f"platform_fulfillment:mapping:{action}",
|
||||
target=f"platform_commodity_mapping:{mapping_id}",
|
||||
detail=result,
|
||||
)
|
||||
db.commit()
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/mappings/{mapping_id}/enable")
|
||||
def enable_mapping(
|
||||
mapping_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:admin")),
|
||||
) -> dict[str, Any]:
|
||||
return _mapping_state_action(
|
||||
db=db,
|
||||
current=current,
|
||||
mapping_id=mapping_id,
|
||||
action="enable",
|
||||
)
|
||||
|
||||
|
||||
@router.post("/mappings/{mapping_id}/disable")
|
||||
def disable_mapping(
|
||||
mapping_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:admin")),
|
||||
) -> dict[str, Any]:
|
||||
return _mapping_state_action(
|
||||
db=db,
|
||||
current=current,
|
||||
mapping_id=mapping_id,
|
||||
action="disable",
|
||||
)
|
||||
|
||||
|
||||
@router.post("/mappings/{mapping_id}/archive")
|
||||
def archive_mapping(
|
||||
mapping_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:admin")),
|
||||
) -> dict[str, Any]:
|
||||
return _mapping_state_action(
|
||||
db=db,
|
||||
current=current,
|
||||
mapping_id=mapping_id,
|
||||
action="archive",
|
||||
)
|
||||
|
||||
|
||||
@router.post("/mappings/{mapping_id}/restore")
|
||||
def restore_mapping(
|
||||
mapping_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:admin")),
|
||||
) -> dict[str, Any]:
|
||||
return _mapping_state_action(
|
||||
db=db,
|
||||
current=current,
|
||||
mapping_id=mapping_id,
|
||||
action="restore",
|
||||
)
|
||||
|
||||
|
||||
@router.post("/tasks/{task_id}/allocate")
|
||||
def allocate_task(
|
||||
task_id: int,
|
||||
|
||||
@@ -1580,12 +1580,25 @@ class DouyuConfigUpdate(BaseModel):
|
||||
|
||||
class PlatformFulfillmentMappingUpsert(BaseModel):
|
||||
internal_sku_key: str = Field(..., min_length=1, max_length=255)
|
||||
campaign_key: str = Field(default="douyu-current", min_length=1, max_length=128)
|
||||
campaign_name: str = Field(default="", max_length=255)
|
||||
commodity_id: str = Field(..., min_length=1, max_length=64)
|
||||
goods_name: str = Field(default="", max_length=255)
|
||||
required_points: int | None = Field(default=None, ge=0)
|
||||
sale_mode: str = Field(
|
||||
default="unknown",
|
||||
pattern="^(presale|direct|manual|unknown)$",
|
||||
)
|
||||
available_from: datetime | None = None
|
||||
available_until: datetime | None = None
|
||||
released_at: datetime | None = None
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class PlatformFulfillmentMappingWrite(PlatformFulfillmentMappingUpsert):
|
||||
pass
|
||||
|
||||
|
||||
class PlatformFulfillmentReasonRequest(BaseModel):
|
||||
reason: str = Field(default="", max_length=2000)
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""直播账号履约工作台的销售模式、开放状态和工作队列派生。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
SALE_MODES = {"presale", "direct", "manual", "unknown"}
|
||||
AVAILABILITY_WAITING_RELEASE = "waiting_release"
|
||||
AVAILABILITY_AVAILABLE = "available"
|
||||
AVAILABILITY_SOLD_OUT = "sold_out"
|
||||
AVAILABILITY_ENDED = "ended"
|
||||
AVAILABILITY_UNKNOWN = "unknown"
|
||||
|
||||
QUEUE_PENDING_MAPPING = "pending_mapping"
|
||||
QUEUE_PRESALE_WAITING = "presale_waiting"
|
||||
QUEUE_READY = "ready_for_fulfillment"
|
||||
QUEUE_NEEDS_ACTION = "needs_action"
|
||||
QUEUE_COMPLETED = "completed"
|
||||
QUEUE_CANCELLED = "cancelled"
|
||||
|
||||
QUEUE_BUCKETS = {
|
||||
QUEUE_PENDING_MAPPING,
|
||||
QUEUE_PRESALE_WAITING,
|
||||
QUEUE_READY,
|
||||
QUEUE_NEEDS_ACTION,
|
||||
QUEUE_COMPLETED,
|
||||
QUEUE_CANCELLED,
|
||||
}
|
||||
|
||||
|
||||
def normalize_sale_mode(value: Any) -> str:
|
||||
mode = str(value or "").strip().lower()
|
||||
return mode if mode in SALE_MODES else "unknown"
|
||||
|
||||
|
||||
def availability_state(
|
||||
*,
|
||||
sale_mode: str,
|
||||
available_from: datetime | None,
|
||||
available_until: datetime | None,
|
||||
goods_status: str = "",
|
||||
now: datetime | None = None,
|
||||
) -> str:
|
||||
"""按报价窗口和最近商品状态派生,不回写销售模式。"""
|
||||
moment = now or datetime.now(UTC)
|
||||
if available_from is not None and moment < _aware(available_from):
|
||||
return AVAILABILITY_WAITING_RELEASE
|
||||
if available_until is not None and moment > _aware(available_until):
|
||||
return AVAILABILITY_ENDED
|
||||
status = str(goods_status or "").strip().lower()
|
||||
if status in {"sold_out", "out_of_stock"}:
|
||||
return AVAILABILITY_SOLD_OUT
|
||||
if sale_mode == "presale":
|
||||
return (
|
||||
AVAILABILITY_AVAILABLE
|
||||
if available_from is not None
|
||||
else AVAILABILITY_WAITING_RELEASE
|
||||
)
|
||||
if sale_mode in {"direct", "manual"}:
|
||||
return AVAILABILITY_AVAILABLE
|
||||
if available_from is not None or available_until is not None:
|
||||
return AVAILABILITY_AVAILABLE
|
||||
return AVAILABILITY_UNKNOWN
|
||||
|
||||
|
||||
def manual_reason(issue_code: str, exchange_status: str) -> str:
|
||||
issue = str(issue_code or "").strip()
|
||||
exchange = str(exchange_status or "").strip()
|
||||
if issue == "points_short" or exchange == "points_short":
|
||||
return "points_short"
|
||||
if issue == "elite_not_opened" or exchange == "not_opened":
|
||||
return "elite_not_opened"
|
||||
if issue == "commodity_limit_reached" or exchange == "limited":
|
||||
return "limit_reached"
|
||||
if issue in {"binding_failed", "account_role_cooldown", "customer_role_cooldown"}:
|
||||
return "binding_failed"
|
||||
if issue in {"lease_expired", "manual_required"}:
|
||||
return "account_cooldown"
|
||||
return "other_manual"
|
||||
|
||||
|
||||
def queue_bucket(
|
||||
*,
|
||||
execution_status: str,
|
||||
sale_mode: str,
|
||||
availability: str,
|
||||
) -> str:
|
||||
status = str(execution_status or "")
|
||||
if status == "cancelled":
|
||||
return QUEUE_CANCELLED
|
||||
if status == "completed":
|
||||
return QUEUE_COMPLETED
|
||||
if status == "pending_mapping":
|
||||
return QUEUE_PENDING_MAPPING
|
||||
if sale_mode == "presale" and availability == AVAILABILITY_WAITING_RELEASE:
|
||||
return QUEUE_PRESALE_WAITING
|
||||
if status == "manual_required":
|
||||
return QUEUE_NEEDS_ACTION
|
||||
return QUEUE_READY
|
||||
|
||||
|
||||
def _aware(value: datetime) -> datetime:
|
||||
return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
|
||||
@@ -11,7 +11,7 @@ from typing import Any
|
||||
|
||||
from fastapi import HTTPException
|
||||
from loguru import logger
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -57,6 +57,7 @@ from ..external_order_source import (
|
||||
lookup_pending_manual_fulfillment,
|
||||
)
|
||||
from ..file_service import build_file_url
|
||||
from . import classification
|
||||
from .account_selector import (
|
||||
AccountCandidate,
|
||||
capability_candidate_accounts,
|
||||
@@ -120,7 +121,9 @@ def _mapping_for_sku(
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||
PlatformCommodityMapping.internal_sku_key == internal_sku_key,
|
||||
PlatformCommodityMapping.enabled.is_(True),
|
||||
PlatformCommodityMapping.archived_at.is_(None),
|
||||
)
|
||||
.order_by(PlatformCommodityMapping.updated_at.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
@@ -396,14 +399,17 @@ def _mapping_map(db: Session) -> dict[str, PlatformCommodityMapping]:
|
||||
.filter(
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||
PlatformCommodityMapping.enabled.is_(True),
|
||||
PlatformCommodityMapping.archived_at.is_(None),
|
||||
)
|
||||
.order_by(PlatformCommodityMapping.updated_at.desc())
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
str(row.internal_sku_key or "").strip(): row
|
||||
for row in rows
|
||||
if str(row.internal_sku_key or "").strip()
|
||||
}
|
||||
result: dict[str, PlatformCommodityMapping] = {}
|
||||
for row in rows:
|
||||
sku_key = str(row.internal_sku_key or "").strip()
|
||||
if sku_key and sku_key not in result:
|
||||
result[sku_key] = row
|
||||
return result
|
||||
|
||||
|
||||
def sync_order_snapshot(
|
||||
@@ -812,13 +818,33 @@ def _apply_mapping(
|
||||
update_execution_status: bool = True,
|
||||
) -> None:
|
||||
if mapping is not None:
|
||||
snapshot_classification = (
|
||||
task.execution_status == "pending_mapping"
|
||||
or task.classification_source in {"", "unknown"}
|
||||
or task.sale_mode in {"", "unknown"}
|
||||
)
|
||||
task.commodity_mapping_id = mapping.id
|
||||
task.commodity_id = mapping.commodity_id
|
||||
task.required_points = mapping.required_points
|
||||
if snapshot_classification:
|
||||
task.sale_mode = classification.normalize_sale_mode(mapping.sale_mode)
|
||||
task.campaign_key = mapping.campaign_key
|
||||
task.campaign_name = mapping.campaign_name
|
||||
task.offer_available_from = mapping.available_from
|
||||
task.offer_available_until = mapping.available_until
|
||||
task.classification_source = (
|
||||
"mapping" if task.sale_mode != "unknown" else "unknown"
|
||||
)
|
||||
else:
|
||||
task.commodity_mapping_id = None
|
||||
task.commodity_id = ""
|
||||
task.required_points = None
|
||||
task.sale_mode = "unknown"
|
||||
task.campaign_key = ""
|
||||
task.campaign_name = ""
|
||||
task.offer_available_from = None
|
||||
task.offer_available_until = None
|
||||
task.classification_source = "unknown"
|
||||
if not update_execution_status:
|
||||
return
|
||||
if mapping is None:
|
||||
@@ -995,6 +1021,8 @@ def list_tasks(
|
||||
db: Session,
|
||||
*,
|
||||
status: str = "",
|
||||
queue_bucket: str = "",
|
||||
sale_mode: str = "",
|
||||
keyword: str = "",
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
@@ -1007,6 +1035,51 @@ def list_tasks(
|
||||
PlatformFulfillmentTask.commodity_id != "",
|
||||
)
|
||||
)
|
||||
mode_filter = classification.normalize_sale_mode(sale_mode)
|
||||
if sale_mode and mode_filter != "unknown":
|
||||
query = query.filter(PlatformFulfillmentTask.sale_mode == mode_filter)
|
||||
elif sale_mode == "unknown":
|
||||
query = query.filter(PlatformFulfillmentTask.sale_mode == "unknown")
|
||||
if queue_bucket:
|
||||
now = datetime.now(UTC)
|
||||
if queue_bucket == classification.QUEUE_CANCELLED:
|
||||
query = query.filter(PlatformFulfillmentTask.execution_status == "cancelled")
|
||||
elif queue_bucket == classification.QUEUE_COMPLETED:
|
||||
query = query.filter(PlatformFulfillmentTask.execution_status == "completed")
|
||||
elif queue_bucket == classification.QUEUE_PENDING_MAPPING:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.execution_status == "pending_mapping"
|
||||
)
|
||||
elif queue_bucket == classification.QUEUE_NEEDS_ACTION:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.execution_status == "manual_required"
|
||||
)
|
||||
elif queue_bucket == classification.QUEUE_PRESALE_WAITING:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
["completed", "cancelled", "pending_mapping", "manual_required"]
|
||||
),
|
||||
PlatformFulfillmentTask.sale_mode == "presale",
|
||||
or_(
|
||||
PlatformFulfillmentTask.offer_available_from.is_(None),
|
||||
PlatformFulfillmentTask.offer_available_from > now,
|
||||
),
|
||||
)
|
||||
elif queue_bucket == classification.QUEUE_READY:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
["completed", "cancelled", "pending_mapping", "manual_required"]
|
||||
),
|
||||
or_(
|
||||
PlatformFulfillmentTask.sale_mode != "presale",
|
||||
PlatformFulfillmentTask.offer_available_from.is_(None),
|
||||
PlatformFulfillmentTask.offer_available_from <= now,
|
||||
),
|
||||
)
|
||||
else:
|
||||
query = query.filter(
|
||||
PlatformFulfillmentTask.execution_status.notin_(["completed", "cancelled"])
|
||||
)
|
||||
if status:
|
||||
if status == "unfinished":
|
||||
query = query.filter(
|
||||
@@ -1096,6 +1169,22 @@ def _task_out(
|
||||
)
|
||||
# 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。
|
||||
pending_role = pending_binding_role_from_result(bind_result)
|
||||
sale_mode = classification.normalize_sale_mode(task.sale_mode)
|
||||
availability = classification.availability_state(
|
||||
sale_mode=sale_mode,
|
||||
available_from=task.offer_available_from,
|
||||
available_until=task.offer_available_until,
|
||||
)
|
||||
queue_bucket = classification.queue_bucket(
|
||||
execution_status=task.execution_status,
|
||||
sale_mode=sale_mode,
|
||||
availability=availability,
|
||||
)
|
||||
manual_reason = (
|
||||
classification.manual_reason(task.issue_code, task.exchange_status)
|
||||
if task.execution_status == "manual_required"
|
||||
else ""
|
||||
)
|
||||
return {
|
||||
"id": task.id,
|
||||
"sourceSystem": task.source_system,
|
||||
@@ -1116,6 +1205,15 @@ def _task_out(
|
||||
"commodityMappingId": task.commodity_mapping_id,
|
||||
"commodityId": task.commodity_id,
|
||||
"requiredPoints": task.required_points,
|
||||
"saleMode": sale_mode,
|
||||
"campaignKey": task.campaign_key,
|
||||
"campaignName": task.campaign_name,
|
||||
"offerAvailableFrom": task.offer_available_from,
|
||||
"offerAvailableUntil": task.offer_available_until,
|
||||
"availabilityState": availability,
|
||||
"queueBucket": queue_bucket,
|
||||
"manualReason": manual_reason,
|
||||
"classificationSource": task.classification_source,
|
||||
"bindingStatus": task.binding_status,
|
||||
"executionStatus": task.execution_status,
|
||||
"exchangeStatus": task.exchange_status,
|
||||
@@ -1476,8 +1574,75 @@ async def customer_confirm_binding(db: Session, *, task_id: int) -> dict[str, An
|
||||
return customer_binding_out(db, task_id)
|
||||
|
||||
|
||||
def list_mappings(db: Session, *, keyword: str = "") -> list[dict[str, Any]]:
|
||||
query = db.query(PlatformCommodityMapping)
|
||||
def _mapping_impact(db: Session, row: PlatformCommodityMapping) -> int:
|
||||
query = db.query(func.count(PlatformFulfillmentTask.id)).filter(
|
||||
PlatformFulfillmentTask.internal_sku_key == row.internal_sku_key,
|
||||
PlatformFulfillmentTask.account_id.is_(None),
|
||||
PlatformFulfillmentTask.execution_status.in_(
|
||||
["pending_mapping", "ready", "manual_required"]
|
||||
),
|
||||
)
|
||||
return int(query.scalar() or 0)
|
||||
|
||||
|
||||
def _mapping_out(
|
||||
db: Session,
|
||||
row: PlatformCommodityMapping,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
mode = classification.normalize_sale_mode(row.sale_mode)
|
||||
availability = classification.availability_state(
|
||||
sale_mode=mode,
|
||||
available_from=row.available_from,
|
||||
available_until=row.available_until,
|
||||
goods_status=row.goods_status,
|
||||
now=now,
|
||||
)
|
||||
return {
|
||||
"id": row.id,
|
||||
"targetPlatform": row.target_platform,
|
||||
"internalSkuKey": row.internal_sku_key,
|
||||
"campaignKey": row.campaign_key,
|
||||
"campaignName": row.campaign_name,
|
||||
"commodityId": row.commodity_id,
|
||||
"goodsName": row.goods_name,
|
||||
"requiredPoints": row.required_points,
|
||||
"scope": row.scope,
|
||||
"saleMode": mode,
|
||||
"availableFrom": row.available_from,
|
||||
"availableUntil": row.available_until,
|
||||
"releasedAt": row.released_at,
|
||||
"goodsStatus": row.goods_status,
|
||||
"availabilityState": availability,
|
||||
"enabled": row.enabled,
|
||||
"version": row.version,
|
||||
"archivedAt": row.archived_at,
|
||||
"affectedTasks": _mapping_impact(db, row),
|
||||
"updatedAt": row.updated_at,
|
||||
}
|
||||
|
||||
|
||||
def list_mappings(
|
||||
db: Session,
|
||||
*,
|
||||
keyword: str = "",
|
||||
sale_mode: str = "",
|
||||
enabled: bool | None = None,
|
||||
include_archived: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
query = db.query(PlatformCommodityMapping).filter(
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM
|
||||
)
|
||||
if not include_archived:
|
||||
query = query.filter(PlatformCommodityMapping.archived_at.is_(None))
|
||||
if enabled is not None:
|
||||
query = query.filter(PlatformCommodityMapping.enabled.is_(enabled))
|
||||
if sale_mode:
|
||||
query = query.filter(
|
||||
PlatformCommodityMapping.sale_mode
|
||||
== classification.normalize_sale_mode(sale_mode)
|
||||
)
|
||||
text = keyword.strip()
|
||||
if text:
|
||||
pattern = f"%{text}%"
|
||||
@@ -1486,84 +1651,69 @@ def list_mappings(db: Session, *, keyword: str = "") -> list[dict[str, Any]]:
|
||||
PlatformCommodityMapping.internal_sku_key.ilike(pattern),
|
||||
PlatformCommodityMapping.commodity_id.ilike(pattern),
|
||||
PlatformCommodityMapping.goods_name.ilike(pattern),
|
||||
PlatformCommodityMapping.campaign_key.ilike(pattern),
|
||||
PlatformCommodityMapping.campaign_name.ilike(pattern),
|
||||
)
|
||||
)
|
||||
rows = query.order_by(PlatformCommodityMapping.updated_at.desc()).limit(300).all()
|
||||
return [
|
||||
{
|
||||
"id": row.id,
|
||||
"targetPlatform": row.target_platform,
|
||||
"internalSkuKey": row.internal_sku_key,
|
||||
"commodityId": row.commodity_id,
|
||||
"goodsName": row.goods_name,
|
||||
"requiredPoints": row.required_points,
|
||||
"scope": row.scope,
|
||||
"enabled": row.enabled,
|
||||
"updatedAt": row.updated_at,
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
rows = query.order_by(
|
||||
PlatformCommodityMapping.archived_at.asc(),
|
||||
PlatformCommodityMapping.enabled.desc(),
|
||||
PlatformCommodityMapping.updated_at.desc(),
|
||||
).limit(500).all()
|
||||
now = datetime.now(UTC)
|
||||
return [_mapping_out(db, row, now=now) for row in rows]
|
||||
|
||||
|
||||
def upsert_mapping(
|
||||
def _validate_mapping_window(
|
||||
available_from: datetime | None,
|
||||
available_until: datetime | None,
|
||||
) -> None:
|
||||
if (
|
||||
available_from is not None
|
||||
and available_until is not None
|
||||
and available_from >= available_until
|
||||
):
|
||||
raise HTTPException(status_code=400, detail="商品开放时间必须早于结束时间")
|
||||
|
||||
|
||||
def _disable_other_current_mappings(
|
||||
db: Session,
|
||||
*,
|
||||
internal_sku_key: str,
|
||||
commodity_id: str,
|
||||
goods_name: str,
|
||||
required_points: int | None,
|
||||
enabled: bool,
|
||||
current: User,
|
||||
) -> dict[str, Any]:
|
||||
sku_key = internal_sku_key.strip()
|
||||
commodity = commodity_id.strip()
|
||||
if not sku_key or not commodity:
|
||||
raise HTTPException(status_code=400, detail="内部 SKU 和斗鱼商品 ID 不能为空")
|
||||
goods = (
|
||||
db.query(DouyuGoodsSnapshot)
|
||||
.filter(DouyuGoodsSnapshot.commodity_id == commodity)
|
||||
.order_by(DouyuGoodsSnapshot.id.desc())
|
||||
.first()
|
||||
)
|
||||
row = (
|
||||
row: PlatformCommodityMapping,
|
||||
) -> None:
|
||||
others = (
|
||||
db.query(PlatformCommodityMapping)
|
||||
.filter(
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||
PlatformCommodityMapping.internal_sku_key == sku_key,
|
||||
PlatformCommodityMapping.id != row.id,
|
||||
PlatformCommodityMapping.target_platform == row.target_platform,
|
||||
PlatformCommodityMapping.internal_sku_key == row.internal_sku_key,
|
||||
PlatformCommodityMapping.enabled.is_(True),
|
||||
PlatformCommodityMapping.archived_at.is_(None),
|
||||
)
|
||||
.first()
|
||||
.all()
|
||||
)
|
||||
if row is None:
|
||||
row = PlatformCommodityMapping(
|
||||
target_platform=TARGET_PLATFORM,
|
||||
internal_sku_key=sku_key,
|
||||
created_by=current.id,
|
||||
created_at=_now(),
|
||||
)
|
||||
db.add(row)
|
||||
row.commodity_id = commodity
|
||||
row.goods_name = (goods_name or (goods.name if goods else "")).strip()
|
||||
row.required_points = (
|
||||
int(required_points)
|
||||
if required_points is not None
|
||||
else (int(goods.score) if goods and goods.score is not None else None)
|
||||
)
|
||||
row.scope = SCOPE_ELITE
|
||||
row.enabled = bool(enabled)
|
||||
row.updated_at = _now()
|
||||
db.flush()
|
||||
for other in others:
|
||||
other.enabled = False
|
||||
other.version = int(other.version or 1) + 1
|
||||
other.updated_at = _now()
|
||||
|
||||
|
||||
def _reapply_mapping_tasks(
|
||||
db: Session,
|
||||
*,
|
||||
row: PlatformCommodityMapping,
|
||||
current: User,
|
||||
) -> None:
|
||||
pending = db.query(PlatformFulfillmentTask).filter(
|
||||
PlatformFulfillmentTask.internal_sku_key == sku_key,
|
||||
PlatformFulfillmentTask.internal_sku_key == row.internal_sku_key,
|
||||
PlatformFulfillmentTask.account_id.is_(None),
|
||||
PlatformFulfillmentTask.execution_status.in_(
|
||||
["pending_mapping", "ready", "manual_required"]
|
||||
),
|
||||
)
|
||||
pending = _apply_order_match_cutoff(pending, _order_match_started_at(db))
|
||||
pending = pending.all()
|
||||
task_ids: list[int] = []
|
||||
for task in pending:
|
||||
for task in pending.all():
|
||||
_apply_mapping(task, row if row.enabled else None)
|
||||
task.updated_at = _now()
|
||||
task.next_allocate_at = (
|
||||
@@ -1577,18 +1727,321 @@ def upsert_mapping(
|
||||
"mapping_updated",
|
||||
actor_type="user",
|
||||
actor_id=current.id,
|
||||
detail={"commodityId": row.commodity_id, "enabled": row.enabled},
|
||||
detail={
|
||||
"mappingId": row.id,
|
||||
"commodityId": row.commodity_id,
|
||||
"saleMode": row.sale_mode,
|
||||
"campaignKey": row.campaign_key,
|
||||
"enabled": row.enabled,
|
||||
},
|
||||
)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
task_ids.append(int(task.id))
|
||||
db.commit()
|
||||
if task_ids:
|
||||
from .auto_allocator import wake_auto_allocator
|
||||
|
||||
wake_auto_allocator(task_ids)
|
||||
return next(
|
||||
item for item in list_mappings(db, keyword=sku_key) if item["id"] == row.id
|
||||
|
||||
|
||||
def _write_mapping(
|
||||
db: Session,
|
||||
row: PlatformCommodityMapping,
|
||||
*,
|
||||
internal_sku_key: str,
|
||||
campaign_key: str,
|
||||
campaign_name: str,
|
||||
commodity_id: str,
|
||||
goods_name: str,
|
||||
required_points: int | None,
|
||||
sale_mode: str,
|
||||
available_from: datetime | None,
|
||||
available_until: datetime | None,
|
||||
released_at: datetime | None,
|
||||
enabled: bool,
|
||||
current: User,
|
||||
) -> None:
|
||||
sku_key = internal_sku_key.strip()
|
||||
campaign = campaign_key.strip()
|
||||
commodity = commodity_id.strip()
|
||||
if not sku_key or not campaign or not commodity:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="内部 SKU、活动批次和斗鱼商品 ID 不能为空",
|
||||
)
|
||||
_validate_mapping_window(available_from, available_until)
|
||||
goods = (
|
||||
db.query(DouyuGoodsSnapshot)
|
||||
.filter(DouyuGoodsSnapshot.commodity_id == commodity)
|
||||
.order_by(DouyuGoodsSnapshot.id.desc())
|
||||
.first()
|
||||
)
|
||||
row.target_platform = TARGET_PLATFORM
|
||||
row.scope = SCOPE_ELITE
|
||||
row.internal_sku_key = sku_key
|
||||
row.campaign_key = campaign
|
||||
row.campaign_name = campaign_name.strip()
|
||||
row.commodity_id = commodity
|
||||
row.goods_name = (goods_name or (goods.name if goods else "")).strip()
|
||||
row.required_points = (
|
||||
int(required_points)
|
||||
if required_points is not None
|
||||
else (int(goods.score) if goods and goods.score is not None else None)
|
||||
)
|
||||
row.sale_mode = classification.normalize_sale_mode(sale_mode)
|
||||
row.available_from = available_from
|
||||
row.available_until = available_until
|
||||
row.released_at = released_at
|
||||
row.goods_status = str(goods.status if goods else "").strip()
|
||||
row.enabled = bool(enabled)
|
||||
row.updated_at = _now()
|
||||
row.version = max(1, int(row.version or 1))
|
||||
db.flush()
|
||||
if row.enabled:
|
||||
_disable_other_current_mappings(db, row=row)
|
||||
_reapply_mapping_tasks(db, row=row, current=current)
|
||||
db.commit()
|
||||
|
||||
|
||||
def create_mapping(
|
||||
db: Session,
|
||||
*,
|
||||
internal_sku_key: str,
|
||||
campaign_key: str,
|
||||
campaign_name: str,
|
||||
commodity_id: str,
|
||||
goods_name: str,
|
||||
required_points: int | None,
|
||||
sale_mode: str,
|
||||
available_from: datetime | None,
|
||||
available_until: datetime | None,
|
||||
released_at: datetime | None,
|
||||
enabled: bool,
|
||||
current: User,
|
||||
) -> dict[str, Any]:
|
||||
row = PlatformCommodityMapping(
|
||||
target_platform=TARGET_PLATFORM,
|
||||
scope=SCOPE_ELITE,
|
||||
internal_sku_key=internal_sku_key.strip(),
|
||||
campaign_key=campaign_key.strip(),
|
||||
commodity_id=commodity_id.strip(),
|
||||
created_by=current.id,
|
||||
created_at=_now(),
|
||||
updated_at=_now(),
|
||||
version=1,
|
||||
)
|
||||
duplicate = (
|
||||
db.query(PlatformCommodityMapping.id)
|
||||
.filter(
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||
PlatformCommodityMapping.internal_sku_key == internal_sku_key.strip(),
|
||||
PlatformCommodityMapping.campaign_key == campaign_key.strip(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if duplicate:
|
||||
raise HTTPException(status_code=409, detail="该 SKU 的活动批次映射已存在")
|
||||
db.add(row)
|
||||
_write_mapping(
|
||||
db,
|
||||
row,
|
||||
internal_sku_key=internal_sku_key,
|
||||
campaign_key=campaign_key,
|
||||
campaign_name=campaign_name,
|
||||
commodity_id=commodity_id,
|
||||
goods_name=goods_name,
|
||||
required_points=required_points,
|
||||
sale_mode=sale_mode,
|
||||
available_from=available_from,
|
||||
available_until=available_until,
|
||||
released_at=released_at,
|
||||
enabled=enabled,
|
||||
current=current,
|
||||
)
|
||||
return _mapping_out(db, row)
|
||||
|
||||
|
||||
def update_mapping(
|
||||
db: Session,
|
||||
*,
|
||||
mapping_id: int,
|
||||
**values: Any,
|
||||
) -> dict[str, Any]:
|
||||
row = db.get(PlatformCommodityMapping, int(mapping_id))
|
||||
if row is None or row.target_platform != TARGET_PLATFORM:
|
||||
raise HTTPException(status_code=404, detail="商品映射不存在")
|
||||
if row.archived_at is not None:
|
||||
raise HTTPException(status_code=409, detail="已归档映射不能编辑,请先恢复")
|
||||
current = values.pop("current")
|
||||
duplicate = (
|
||||
db.query(PlatformCommodityMapping.id)
|
||||
.filter(
|
||||
PlatformCommodityMapping.id != row.id,
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||
PlatformCommodityMapping.internal_sku_key
|
||||
== str(values.get("internal_sku_key") or "").strip(),
|
||||
PlatformCommodityMapping.campaign_key
|
||||
== str(values.get("campaign_key") or "").strip(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if duplicate:
|
||||
raise HTTPException(status_code=409, detail="该 SKU 的活动批次映射已存在")
|
||||
row.version = int(row.version or 1) + 1
|
||||
_write_mapping(db, row, current=current, **values)
|
||||
return _mapping_out(db, row)
|
||||
|
||||
|
||||
def set_mapping_enabled(
|
||||
db: Session,
|
||||
*,
|
||||
mapping_id: int,
|
||||
enabled: bool,
|
||||
current: User,
|
||||
) -> dict[str, Any]:
|
||||
row = db.get(PlatformCommodityMapping, int(mapping_id))
|
||||
if row is None or row.target_platform != TARGET_PLATFORM:
|
||||
raise HTTPException(status_code=404, detail="商品映射不存在")
|
||||
if row.archived_at is not None:
|
||||
raise HTTPException(status_code=409, detail="已归档映射不能启停,请先恢复")
|
||||
row.enabled = bool(enabled)
|
||||
row.version = int(row.version or 1) + 1
|
||||
row.updated_at = _now()
|
||||
db.flush()
|
||||
if enabled:
|
||||
_disable_other_current_mappings(db, row=row)
|
||||
_reapply_mapping_tasks(db, row=row, current=current)
|
||||
db.commit()
|
||||
return _mapping_out(db, row)
|
||||
|
||||
|
||||
def archive_mapping(
|
||||
db: Session,
|
||||
*,
|
||||
mapping_id: int,
|
||||
current: User,
|
||||
) -> dict[str, Any]:
|
||||
row = db.get(PlatformCommodityMapping, int(mapping_id))
|
||||
if row is None or row.target_platform != TARGET_PLATFORM:
|
||||
raise HTTPException(status_code=404, detail="商品映射不存在")
|
||||
row.enabled = False
|
||||
row.archived_at = _now()
|
||||
row.archived_by = current.id
|
||||
row.version = int(row.version or 1) + 1
|
||||
row.updated_at = _now()
|
||||
_reapply_mapping_tasks(db, row=row, current=current)
|
||||
db.commit()
|
||||
return _mapping_out(db, row)
|
||||
|
||||
|
||||
def restore_mapping(
|
||||
db: Session,
|
||||
*,
|
||||
mapping_id: int,
|
||||
) -> dict[str, Any]:
|
||||
row = db.get(PlatformCommodityMapping, int(mapping_id))
|
||||
if row is None or row.target_platform != TARGET_PLATFORM:
|
||||
raise HTTPException(status_code=404, detail="商品映射不存在")
|
||||
row.archived_at = None
|
||||
row.archived_by = None
|
||||
row.enabled = False
|
||||
row.version = int(row.version or 1) + 1
|
||||
row.updated_at = _now()
|
||||
db.commit()
|
||||
return _mapping_out(db, row)
|
||||
|
||||
|
||||
def delete_mapping(db: Session, *, mapping_id: int) -> None:
|
||||
row = db.get(PlatformCommodityMapping, int(mapping_id))
|
||||
if row is None or row.target_platform != TARGET_PLATFORM:
|
||||
raise HTTPException(status_code=404, detail="商品映射不存在")
|
||||
referenced = (
|
||||
db.query(PlatformFulfillmentTask.id)
|
||||
.filter(PlatformFulfillmentTask.commodity_mapping_id == row.id)
|
||||
.first()
|
||||
)
|
||||
if referenced:
|
||||
raise HTTPException(status_code=409, detail="映射已被任务引用,只能归档")
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
|
||||
|
||||
def mapping_impact(db: Session, *, mapping_id: int) -> dict[str, Any]:
|
||||
row = db.get(PlatformCommodityMapping, int(mapping_id))
|
||||
if row is None or row.target_platform != TARGET_PLATFORM:
|
||||
raise HTTPException(status_code=404, detail="商品映射不存在")
|
||||
rows = (
|
||||
db.query(
|
||||
PlatformFulfillmentTask.execution_status,
|
||||
PlatformFulfillmentTask.sale_mode,
|
||||
func.count(PlatformFulfillmentTask.id),
|
||||
)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.internal_sku_key == row.internal_sku_key,
|
||||
PlatformFulfillmentTask.account_id.is_(None),
|
||||
)
|
||||
.group_by(
|
||||
PlatformFulfillmentTask.execution_status,
|
||||
PlatformFulfillmentTask.sale_mode,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
"mappingId": row.id,
|
||||
"internalSkuKey": row.internal_sku_key,
|
||||
"affectedTasks": sum(int(count) for _status, _mode, count in rows),
|
||||
"groups": [
|
||||
{
|
||||
"executionStatus": status,
|
||||
"saleMode": mode,
|
||||
"count": int(count),
|
||||
}
|
||||
for status, mode, count in rows
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def upsert_mapping(
|
||||
db: Session,
|
||||
*,
|
||||
internal_sku_key: str,
|
||||
commodity_id: str,
|
||||
goods_name: str,
|
||||
required_points: int | None,
|
||||
enabled: bool,
|
||||
current: User,
|
||||
campaign_key: str = "douyu-current",
|
||||
campaign_name: str = "",
|
||||
sale_mode: str = "unknown",
|
||||
available_from: datetime | None = None,
|
||||
available_until: datetime | None = None,
|
||||
released_at: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
row = (
|
||||
db.query(PlatformCommodityMapping)
|
||||
.filter(
|
||||
PlatformCommodityMapping.target_platform == TARGET_PLATFORM,
|
||||
PlatformCommodityMapping.internal_sku_key == internal_sku_key.strip(),
|
||||
PlatformCommodityMapping.campaign_key == campaign_key.strip(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
values = {
|
||||
"internal_sku_key": internal_sku_key,
|
||||
"campaign_key": campaign_key,
|
||||
"campaign_name": campaign_name,
|
||||
"commodity_id": commodity_id,
|
||||
"goods_name": goods_name,
|
||||
"required_points": required_points,
|
||||
"sale_mode": sale_mode,
|
||||
"available_from": available_from,
|
||||
"available_until": available_until,
|
||||
"released_at": released_at,
|
||||
"enabled": enabled,
|
||||
"current": current,
|
||||
}
|
||||
if row is None:
|
||||
return create_mapping(db, **values)
|
||||
return update_mapping(db, mapping_id=row.id, **values)
|
||||
|
||||
|
||||
def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]:
|
||||
@@ -2816,13 +3269,17 @@ def release_task_to_manual(
|
||||
|
||||
__all__ = [
|
||||
"allocate_task",
|
||||
"archive_mapping",
|
||||
"cancel_task",
|
||||
"complete_manual_exchange",
|
||||
"confirm_binding",
|
||||
"create_mapping",
|
||||
"customer_refresh_bindings",
|
||||
"delete_mapping",
|
||||
"get_task_detail",
|
||||
"list_mappings",
|
||||
"list_tasks",
|
||||
"mapping_impact",
|
||||
"mark_manual_required",
|
||||
"reconcile_binding_state_outbox",
|
||||
"record_douyu_operation_result",
|
||||
@@ -2833,11 +3290,14 @@ __all__ = [
|
||||
"release_task_to_manual",
|
||||
"reset_task_binding",
|
||||
"restore_cancelled_task",
|
||||
"restore_mapping",
|
||||
"set_mapping_enabled",
|
||||
"start_binding",
|
||||
"sync_order_item_ids",
|
||||
"sync_order_snapshot",
|
||||
"sync_pending_tasks",
|
||||
"sync_pending_tasks_if_due",
|
||||
"sync_task_from_binding_runner",
|
||||
"update_mapping",
|
||||
"upsert_mapping",
|
||||
]
|
||||
|
||||
@@ -7,6 +7,20 @@ import type {
|
||||
PlatformFulfillmentSettings,
|
||||
} from './types';
|
||||
|
||||
export interface PlatformFulfillmentMappingWrite {
|
||||
internal_sku_key: string;
|
||||
campaign_key: string;
|
||||
campaign_name: string;
|
||||
commodity_id: string;
|
||||
goods_name?: string;
|
||||
required_points?: number | null;
|
||||
sale_mode: 'presale' | 'direct' | 'manual' | 'unknown';
|
||||
available_from?: string | null;
|
||||
available_until?: string | null;
|
||||
released_at?: string | null;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export const platformFulfillmentApi = {
|
||||
getSettings: () =>
|
||||
api.get<PlatformFulfillmentSettings, PlatformFulfillmentSettings>(
|
||||
@@ -25,6 +39,8 @@ export const platformFulfillmentApi = {
|
||||
),
|
||||
listTasks: (params: {
|
||||
status?: string;
|
||||
queue_bucket?: string;
|
||||
sale_mode?: string;
|
||||
keyword?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
@@ -48,22 +64,46 @@ export const platformFulfillmentApi = {
|
||||
api.get<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||
`/platform-fulfillment/tasks/${taskId}`,
|
||||
),
|
||||
listMappings: (keyword = '') =>
|
||||
listMappings: (params: {
|
||||
keyword?: string;
|
||||
sale_mode?: string;
|
||||
enabled?: boolean;
|
||||
include_archived?: boolean;
|
||||
} = {}) =>
|
||||
api.get<PlatformFulfillmentMapping[], PlatformFulfillmentMapping[]>(
|
||||
'/platform-fulfillment/mappings',
|
||||
{ params: { keyword } },
|
||||
{ params },
|
||||
),
|
||||
upsertMapping: (data: {
|
||||
internal_sku_key: string;
|
||||
commodity_id: string;
|
||||
goods_name?: string;
|
||||
required_points?: number | null;
|
||||
enabled: boolean;
|
||||
}) =>
|
||||
api.put<PlatformFulfillmentMapping, PlatformFulfillmentMapping>(
|
||||
createMapping: (data: PlatformFulfillmentMappingWrite) =>
|
||||
api.post<PlatformFulfillmentMapping, PlatformFulfillmentMapping>(
|
||||
'/platform-fulfillment/mappings',
|
||||
data,
|
||||
),
|
||||
updateMapping: (mappingId: number, data: PlatformFulfillmentMappingWrite) =>
|
||||
api.patch<PlatformFulfillmentMapping, PlatformFulfillmentMapping>(
|
||||
`/platform-fulfillment/mappings/${mappingId}`,
|
||||
data,
|
||||
),
|
||||
deleteMapping: (mappingId: number) =>
|
||||
api.delete<{ success: boolean }, { success: boolean }>(
|
||||
`/platform-fulfillment/mappings/${mappingId}`,
|
||||
),
|
||||
mappingAction: (mappingId: number, action: 'enable' | 'disable' | 'archive' | 'restore') =>
|
||||
api.post<PlatformFulfillmentMapping, PlatformFulfillmentMapping>(
|
||||
`/platform-fulfillment/mappings/${mappingId}/${action}`,
|
||||
),
|
||||
mappingImpact: (mappingId: number) =>
|
||||
api.get<{
|
||||
mappingId: number;
|
||||
internalSkuKey: string;
|
||||
affectedTasks: number;
|
||||
groups: Array<{ executionStatus: string; saleMode: string; count: number }>;
|
||||
}, {
|
||||
mappingId: number;
|
||||
internalSkuKey: string;
|
||||
affectedTasks: number;
|
||||
groups: Array<{ executionStatus: string; saleMode: string; count: number }>;
|
||||
}>(`/platform-fulfillment/mappings/${mappingId}/impact`),
|
||||
allocate: (taskId: number) =>
|
||||
api.post<PlatformFulfillmentDetail, PlatformFulfillmentDetail>(
|
||||
`/platform-fulfillment/tasks/${taskId}/allocate`,
|
||||
|
||||
@@ -2225,6 +2225,15 @@ export interface PlatformFulfillmentTask {
|
||||
commodityMappingId: number | null;
|
||||
commodityId: string;
|
||||
requiredPoints: number | null;
|
||||
saleMode: 'presale' | 'direct' | 'manual' | 'unknown';
|
||||
campaignKey: string;
|
||||
campaignName: string;
|
||||
offerAvailableFrom: string | null;
|
||||
offerAvailableUntil: string | null;
|
||||
availabilityState: 'waiting_release' | 'available' | 'sold_out' | 'ended' | 'unknown';
|
||||
queueBucket: 'pending_mapping' | 'presale_waiting' | 'ready_for_fulfillment' | 'needs_action' | 'completed' | 'cancelled';
|
||||
manualReason: string;
|
||||
classificationSource: string;
|
||||
bindingStatus: string;
|
||||
executionStatus: string;
|
||||
exchangeStatus: string;
|
||||
@@ -2273,11 +2282,22 @@ export interface PlatformFulfillmentMapping {
|
||||
id: number;
|
||||
targetPlatform: string;
|
||||
internalSkuKey: string;
|
||||
campaignKey: string;
|
||||
campaignName: string;
|
||||
commodityId: string;
|
||||
goodsName: string;
|
||||
requiredPoints: number | null;
|
||||
scope: string;
|
||||
saleMode: 'presale' | 'direct' | 'manual' | 'unknown';
|
||||
availableFrom: string | null;
|
||||
availableUntil: string | null;
|
||||
releasedAt: string | null;
|
||||
goodsStatus: string;
|
||||
availabilityState: 'waiting_release' | 'available' | 'sold_out' | 'ended' | 'unknown';
|
||||
enabled: boolean;
|
||||
version: number;
|
||||
archivedAt: string | null;
|
||||
affectedTasks: number;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,39 @@ const EXCHANGE_STATUS_LABELS: Record<string, string> = {
|
||||
manual_done: '人工兑换完成',
|
||||
};
|
||||
|
||||
const SALE_MODE_LABELS: Record<string, string> = {
|
||||
presale: '预售',
|
||||
direct: '直接兑换',
|
||||
manual: '人工',
|
||||
unknown: '未分类',
|
||||
};
|
||||
|
||||
const AVAILABILITY_LABELS: Record<string, string> = {
|
||||
waiting_release: '待开放',
|
||||
available: '可兑换',
|
||||
sold_out: '已售罄',
|
||||
ended: '已结束',
|
||||
unknown: '未知',
|
||||
};
|
||||
|
||||
const MANUAL_REASON_LABELS: Record<string, string> = {
|
||||
points_short: '积分不足',
|
||||
elite_not_opened: '宝典未开通',
|
||||
limit_reached: '已达限兑',
|
||||
binding_failed: '绑定异常',
|
||||
account_cooldown: '账号冷却',
|
||||
other_manual: '其他人工',
|
||||
};
|
||||
|
||||
const QUEUE_BUCKET_OPTIONS = [
|
||||
{ value: 'current', label: '当前待办' },
|
||||
{ value: 'presale_waiting', label: '预售待开放' },
|
||||
{ value: 'ready_for_fulfillment', label: '可履约' },
|
||||
{ value: 'needs_action', label: '需要人工' },
|
||||
{ value: 'completed', label: '已完成' },
|
||||
{ value: 'cancelled', label: '已取消' },
|
||||
];
|
||||
|
||||
const ACTOR_TYPE_LABELS: Record<string, string> = {
|
||||
system: '系统',
|
||||
user: '操作人',
|
||||
@@ -304,7 +337,8 @@ export default function PlatformFulfillmentPage() {
|
||||
const user = getUser();
|
||||
const navigate = useNavigate();
|
||||
const { can } = usePermissions(user);
|
||||
const [status, setStatus] = useState('');
|
||||
const [queueBucket, setQueueBucket] = useState('current');
|
||||
const [saleModeFilter, setSaleModeFilter] = useState('');
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
@@ -327,9 +361,18 @@ export default function PlatformFulfillmentPage() {
|
||||
const [qrOpen, setQrOpen] = useState(false);
|
||||
const [mappingOpen, setMappingOpen] = useState(false);
|
||||
const [mappingSku, setMappingSku] = useState('');
|
||||
const [mappingEditingId, setMappingEditingId] = useState<number | null>(null);
|
||||
const [mappingCampaignKey, setMappingCampaignKey] = useState('douyu-current');
|
||||
const [mappingCampaignName, setMappingCampaignName] = useState('');
|
||||
const [mappingGoodsId, setMappingGoodsId] = useState('');
|
||||
const [mappingGoodsName, setMappingGoodsName] = useState('');
|
||||
const [mappingPoints, setMappingPoints] = useState<number | null>(null);
|
||||
const [mappingEnabled, setMappingEnabled] = useState(true);
|
||||
const [mappingSaleMode, setMappingSaleMode] = useState<'presale' | 'direct' | 'manual' | 'unknown'>('unknown');
|
||||
const [mappingAvailableFrom, setMappingAvailableFrom] = useState<Dayjs | null>(null);
|
||||
const [mappingAvailableUntil, setMappingAvailableUntil] = useState<Dayjs | null>(null);
|
||||
const [mappingFilterMode, setMappingFilterMode] = useState('');
|
||||
const [mappingIncludeArchived, setMappingIncludeArchived] = useState(false);
|
||||
const [goods, setGoods] = useState<DouyuGoodsItem[]>([]);
|
||||
const [mappingGoodsLoading, setMappingGoodsLoading] = useState(false);
|
||||
const [mappings, setMappings] = useState<PlatformFulfillmentMapping[]>([]);
|
||||
@@ -354,8 +397,16 @@ export default function PlatformFulfillmentPage() {
|
||||
const loadTasks = useCallback(async (silent = false) => {
|
||||
if (!silent) setLoading(true);
|
||||
try {
|
||||
const queueBackedStatus = queueBucket === 'current'
|
||||
? 'unfinished'
|
||||
: (['completed', 'cancelled'].includes(queueBucket) ? queueBucket : undefined);
|
||||
const backendBucket = ['presale_waiting', 'ready_for_fulfillment', 'needs_action'].includes(queueBucket)
|
||||
? queueBucket
|
||||
: undefined;
|
||||
const result = await platformFulfillmentApi.listTasks({
|
||||
status: status || undefined,
|
||||
status: queueBackedStatus,
|
||||
queue_bucket: backendBucket,
|
||||
sale_mode: saleModeFilter || undefined,
|
||||
keyword: keyword.trim() || undefined,
|
||||
page,
|
||||
page_size: pageSize,
|
||||
@@ -367,7 +418,7 @@ export default function PlatformFulfillmentPage() {
|
||||
} finally {
|
||||
if (!silent) setLoading(false);
|
||||
}
|
||||
}, [keyword, page, pageSize, status]);
|
||||
}, [keyword, page, pageSize, queueBucket, saleModeFilter]);
|
||||
|
||||
const loadDetail = useCallback(async (taskId: number, silent = false) => {
|
||||
if (!silent) setDetailLoading(true);
|
||||
@@ -707,15 +758,46 @@ export default function PlatformFulfillmentPage() {
|
||||
link.click();
|
||||
};
|
||||
|
||||
const openMapping = async (task?: PlatformFulfillmentTask) => {
|
||||
const resetMappingForm = (task?: PlatformFulfillmentTask) => {
|
||||
setMappingEditingId(null);
|
||||
setMappingSku(task?.internalSkuKey || '');
|
||||
setMappingCampaignKey(task?.campaignKey || 'douyu-current');
|
||||
setMappingCampaignName(task?.campaignName || '');
|
||||
setMappingGoodsId(task?.commodityId || '');
|
||||
setMappingGoodsName('');
|
||||
setMappingPoints(task?.requiredPoints ?? null);
|
||||
setMappingEnabled(true);
|
||||
setMappingSaleMode(task?.saleMode || 'unknown');
|
||||
setMappingAvailableFrom(task?.offerAvailableFrom ? dayjs(task.offerAvailableFrom) : null);
|
||||
setMappingAvailableUntil(task?.offerAvailableUntil ? dayjs(task.offerAvailableUntil) : null);
|
||||
};
|
||||
|
||||
const loadMappingRows = async (
|
||||
keyword = mappingSku.trim(),
|
||||
mode = mappingFilterMode,
|
||||
includeArchived = mappingIncludeArchived,
|
||||
) => {
|
||||
const rows = await platformFulfillmentApi.listMappings({
|
||||
keyword,
|
||||
sale_mode: mode || undefined,
|
||||
include_archived: includeArchived,
|
||||
});
|
||||
setMappings(rows);
|
||||
};
|
||||
|
||||
const openMapping = async (task?: PlatformFulfillmentTask) => {
|
||||
resetMappingForm(task);
|
||||
setMappingOpen(true);
|
||||
setMappingGoodsLoading(true);
|
||||
try {
|
||||
const [goodsRows, mappingRows] = await Promise.all([douyuApi.listLiveGoods(), platformFulfillmentApi.listMappings(task?.internalSkuKey || '')]);
|
||||
const [goodsRows, mappingRows] = await Promise.all([
|
||||
douyuApi.listLiveGoods(),
|
||||
platformFulfillmentApi.listMappings({
|
||||
keyword: task?.internalSkuKey || '',
|
||||
sale_mode: mappingFilterMode || undefined,
|
||||
include_archived: mappingIncludeArchived,
|
||||
}),
|
||||
]);
|
||||
setGoods(goodsRows);
|
||||
setMappings(mappingRows);
|
||||
if (goodsRows.length === 0) {
|
||||
@@ -728,6 +810,65 @@ export default function PlatformFulfillmentPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const editMapping = (row: PlatformFulfillmentMapping) => {
|
||||
setMappingEditingId(row.id);
|
||||
setMappingSku(row.internalSkuKey);
|
||||
setMappingCampaignKey(row.campaignKey || 'douyu-current');
|
||||
setMappingCampaignName(row.campaignName || '');
|
||||
setMappingGoodsId(row.commodityId);
|
||||
setMappingGoodsName(row.goodsName);
|
||||
setMappingPoints(row.requiredPoints);
|
||||
setMappingEnabled(row.enabled);
|
||||
setMappingSaleMode(row.saleMode);
|
||||
setMappingAvailableFrom(row.availableFrom ? dayjs(row.availableFrom) : null);
|
||||
setMappingAvailableUntil(row.availableUntil ? dayjs(row.availableUntil) : null);
|
||||
};
|
||||
|
||||
const runMappingAction = (
|
||||
row: PlatformFulfillmentMapping,
|
||||
action: 'enable' | 'disable' | 'archive' | 'restore',
|
||||
) => {
|
||||
const label = {
|
||||
enable: '启用',
|
||||
disable: '停用',
|
||||
archive: '归档',
|
||||
restore: '恢复',
|
||||
}[action];
|
||||
Modal.confirm({
|
||||
title: `${label}映射`,
|
||||
content: `${row.internalSkuKey} / ${row.campaignKey}`,
|
||||
onOk: async () => {
|
||||
try {
|
||||
await platformFulfillmentApi.mappingAction(row.id, action);
|
||||
message.success(`映射已${label}`);
|
||||
await loadMappingRows();
|
||||
await loadTasks();
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const removeMapping = (row: PlatformFulfillmentMapping) => {
|
||||
Modal.confirm({
|
||||
title: '删除映射',
|
||||
content: row.affectedTasks > 0
|
||||
? `该映射还有 ${row.affectedTasks} 个关联任务,只能归档。`
|
||||
: '映射删除后不可恢复。',
|
||||
okButtonProps: { danger: true },
|
||||
onOk: async () => {
|
||||
try {
|
||||
await platformFulfillmentApi.deleteMapping(row.id);
|
||||
message.success('映射已删除');
|
||||
await loadMappingRows();
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const reloadMappingGoods = async () => {
|
||||
setMappingGoodsLoading(true);
|
||||
try {
|
||||
@@ -748,25 +889,41 @@ export default function PlatformFulfillmentPage() {
|
||||
const selectGoods = (commodityId: string) => {
|
||||
const item = goods.find((row) => row.commodity_id === commodityId);
|
||||
setMappingGoodsId(commodityId);
|
||||
setMappingGoodsName(item?.name || '');
|
||||
if (item?.score != null) setMappingPoints(Number(item.score));
|
||||
};
|
||||
|
||||
const saveMapping = async () => {
|
||||
if (!mappingSku.trim() || !mappingGoodsId) {
|
||||
message.warning('请填写内部 SKU 并选择斗鱼商品');
|
||||
if (!mappingSku.trim() || !mappingCampaignKey.trim() || !mappingGoodsId || !mappingSaleMode) {
|
||||
message.warning('请填写内部 SKU、活动批次、销售模式并选择斗鱼商品');
|
||||
return;
|
||||
}
|
||||
if (mappingSaleMode === 'unknown') {
|
||||
message.warning('请选择预售、直接兑换或人工销售模式');
|
||||
return;
|
||||
}
|
||||
const item = goods.find((row) => row.commodity_id === mappingGoodsId);
|
||||
try {
|
||||
await platformFulfillmentApi.upsertMapping({
|
||||
const payload = {
|
||||
internal_sku_key: mappingSku.trim(),
|
||||
campaign_key: mappingCampaignKey.trim(),
|
||||
campaign_name: mappingCampaignName.trim(),
|
||||
commodity_id: mappingGoodsId,
|
||||
goods_name: item?.name || '',
|
||||
goods_name: item?.name || mappingGoodsName,
|
||||
required_points: mappingPoints,
|
||||
sale_mode: mappingSaleMode,
|
||||
available_from: mappingAvailableFrom?.toISOString() || null,
|
||||
available_until: mappingAvailableUntil?.toISOString() || null,
|
||||
enabled: mappingEnabled,
|
||||
});
|
||||
};
|
||||
if (mappingEditingId) {
|
||||
await platformFulfillmentApi.updateMapping(mappingEditingId, payload);
|
||||
} else {
|
||||
await platformFulfillmentApi.createMapping(payload);
|
||||
}
|
||||
message.success('商品映射已保存');
|
||||
setMappings(await platformFulfillmentApi.listMappings(mappingSku.trim()));
|
||||
resetMappingForm();
|
||||
await loadMappingRows();
|
||||
await loadTasks();
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
@@ -861,6 +1018,27 @@ export default function PlatformFulfillmentPage() {
|
||||
</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'}>
|
||||
{SALE_MODE_LABELS[task.saleMode] || task.saleMode}
|
||||
</Tag>
|
||||
<Tag>{AVAILABILITY_LABELS[task.availabilityState] || task.availabilityState}</Tag>
|
||||
</Space>
|
||||
<Text type="secondary" ellipsis title={task.campaignName || task.campaignKey || '-'}>
|
||||
{task.campaignName || task.campaignKey || '未设置活动批次'}
|
||||
</Text>
|
||||
{task.offerAvailableFrom ? (
|
||||
<Text type="secondary">开放:{formatTime(task.offerAvailableFrom)}</Text>
|
||||
) : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '订单金额',
|
||||
dataIndex: 'orderAmountFen',
|
||||
@@ -900,11 +1078,16 @@ export default function PlatformFulfillmentPage() {
|
||||
{
|
||||
title: '状态',
|
||||
key: 'status',
|
||||
width: 150,
|
||||
width: 180,
|
||||
render: (_, task) => (
|
||||
<Space direction="vertical" size={4}>
|
||||
<Tag color={STATUS_COLORS[task.executionStatus] || 'default'}>{statusLabel(task.executionStatus)}</Tag>
|
||||
<Text type="secondary">兑换:{exchangeStatusLabel(task.exchangeStatus)}</Text>
|
||||
{task.manualReason ? (
|
||||
<Text type="danger">
|
||||
{MANUAL_REASON_LABELS[task.manualReason] || task.manualReason}
|
||||
</Text>
|
||||
) : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
@@ -1129,11 +1312,22 @@ export default function PlatformFulfillmentPage() {
|
||||
}}
|
||||
style={{ width: 300 }}
|
||||
/>
|
||||
<Select
|
||||
value={status}
|
||||
options={STATUS_OPTIONS}
|
||||
<Segmented
|
||||
value={queueBucket}
|
||||
options={QUEUE_BUCKET_OPTIONS}
|
||||
onChange={(value) => {
|
||||
setStatus(value);
|
||||
setQueueBucket(String(value));
|
||||
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 }}
|
||||
@@ -1151,7 +1345,7 @@ export default function PlatformFulfillmentPage() {
|
||||
selectedRowKeys,
|
||||
onChange: setSelectedRowKeys,
|
||||
}}
|
||||
scroll={{ x: 1900 }}
|
||||
scroll={{ x: 2100 }}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
@@ -1272,6 +1466,15 @@ export default function PlatformFulfillmentPage() {
|
||||
<Descriptions.Item label="斗鱼商品" span={2}>
|
||||
{selected.commodityId || '未映射'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="销售模式">
|
||||
{SALE_MODE_LABELS[selected.saleMode] || selected.saleMode}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="开放状态">
|
||||
{AVAILABILITY_LABELS[selected.availabilityState] || selected.availabilityState}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="活动批次" span={2}>
|
||||
{selected.campaignName || selected.campaignKey || '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="订单金额">{money(selected.orderAmountFen)}</Descriptions.Item>
|
||||
<Descriptions.Item label="所需积分">{selected.requiredPoints ?? '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="执行状态">{statusLabel(selected.executionStatus)}</Descriptions.Item>
|
||||
@@ -1631,9 +1834,51 @@ export default function PlatformFulfillmentPage() {
|
||||
</Space>
|
||||
</Modal>
|
||||
|
||||
<Modal open={mappingOpen} title="斗鱼商品映射" width={760} okText="保存映射" onOk={() => void saveMapping()} onCancel={() => setMappingOpen(false)}>
|
||||
<Modal
|
||||
open={mappingOpen}
|
||||
title="斗鱼商品映射管理"
|
||||
width={1120}
|
||||
okText="保存映射"
|
||||
onOk={() => void saveMapping()}
|
||||
onCancel={() => setMappingOpen(false)}
|
||||
>
|
||||
<Space direction="vertical" size={14} style={{ width: '100%' }}>
|
||||
<Input placeholder="内部 SKU,例如 套装-兔兔白日梦" value={mappingSku} onChange={(event) => setMappingSku(event.target.value)} />
|
||||
<Space wrap>
|
||||
<Select
|
||||
value={mappingFilterMode}
|
||||
options={[
|
||||
{ value: '', label: '全部销售模式' },
|
||||
...Object.entries(SALE_MODE_LABELS).map(([value, label]) => ({ value, label })),
|
||||
]}
|
||||
onChange={(value) => {
|
||||
setMappingFilterMode(value);
|
||||
void loadMappingRows(mappingSku.trim(), value).catch((error) => message.error(getErrorMessage(error)));
|
||||
}}
|
||||
style={{ width: 160 }}
|
||||
/>
|
||||
<Space>
|
||||
<Text>显示已归档</Text>
|
||||
<Switch
|
||||
checked={mappingIncludeArchived}
|
||||
onChange={(checked) => {
|
||||
setMappingIncludeArchived(checked);
|
||||
void platformFulfillmentApi.listMappings({
|
||||
keyword: mappingSku.trim(),
|
||||
sale_mode: mappingFilterMode || undefined,
|
||||
include_archived: checked,
|
||||
}).then(setMappings).catch((error) => message.error(getErrorMessage(error)));
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
<Button onClick={() => resetMappingForm()}>
|
||||
新建映射
|
||||
</Button>
|
||||
</Space>
|
||||
<Space wrap style={{ width: '100%' }}>
|
||||
<Input placeholder="内部 SKU,例如 套装-兔兔白日梦" value={mappingSku} onChange={(event) => setMappingSku(event.target.value)} style={{ width: 260 }} />
|
||||
<Input placeholder="活动批次,例如 douyu-2026-11-return" value={mappingCampaignKey} onChange={(event) => setMappingCampaignKey(event.target.value)} style={{ width: 260 }} />
|
||||
<Input placeholder="活动名称,例如 11 月返场" value={mappingCampaignName} onChange={(event) => setMappingCampaignName(event.target.value)} style={{ width: 220 }} />
|
||||
</Space>
|
||||
<Space.Compact style={{ width: '100%' }}>
|
||||
<Select
|
||||
showSearch
|
||||
@@ -1642,10 +1887,18 @@ export default function PlatformFulfillmentPage() {
|
||||
placeholder={mappingGoodsLoading ? '正在加载斗鱼活动商品…' : '选择斗鱼精英宝典商品'}
|
||||
value={mappingGoodsId || undefined}
|
||||
onChange={selectGoods}
|
||||
options={goods.map((item) => ({
|
||||
value: item.commodity_id,
|
||||
label: `${item.name || item.commodity_id} · ${item.score ?? '-'} 积分`,
|
||||
}))}
|
||||
options={[
|
||||
...goods.map((item) => ({
|
||||
value: item.commodity_id,
|
||||
label: `${item.name || item.commodity_id} · ${item.score ?? '-'} 积分`,
|
||||
})),
|
||||
...(mappingGoodsId && !goods.some((item) => item.commodity_id === mappingGoodsId)
|
||||
? [{
|
||||
value: mappingGoodsId,
|
||||
label: `${mappingGoodsName || mappingGoodsId} · 当前已缓存`,
|
||||
}]
|
||||
: []),
|
||||
]}
|
||||
notFoundContent={mappingGoodsLoading ? null : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无活动商品" />}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
@@ -1653,12 +1906,35 @@ export default function PlatformFulfillmentPage() {
|
||||
刷新商品
|
||||
</Button>
|
||||
</Space.Compact>
|
||||
<Space>
|
||||
<Space wrap>
|
||||
<Text>销售模式</Text>
|
||||
<Select
|
||||
value={mappingSaleMode}
|
||||
options={Object.entries(SALE_MODE_LABELS).map(([value, label]) => ({ value, label }))}
|
||||
onChange={setMappingSaleMode}
|
||||
style={{ width: 140 }}
|
||||
/>
|
||||
<Text>所需积分</Text>
|
||||
<InputNumber min={0} value={mappingPoints} onChange={(value) => setMappingPoints(value)} />
|
||||
<Text>启用</Text>
|
||||
<Switch checked={mappingEnabled} onChange={setMappingEnabled} />
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<Text>商品开放时间</Text>
|
||||
<DatePicker
|
||||
showTime
|
||||
value={mappingAvailableFrom}
|
||||
onChange={setMappingAvailableFrom}
|
||||
placeholder="开始时间"
|
||||
/>
|
||||
<Text>至</Text>
|
||||
<DatePicker
|
||||
showTime
|
||||
value={mappingAvailableUntil}
|
||||
onChange={setMappingAvailableUntil}
|
||||
placeholder="结束时间"
|
||||
/>
|
||||
</Space>
|
||||
<Tabs
|
||||
items={[
|
||||
{
|
||||
@@ -1671,16 +1947,79 @@ export default function PlatformFulfillmentPage() {
|
||||
pagination={false}
|
||||
dataSource={mappings}
|
||||
columns={[
|
||||
{ title: '内部 SKU', dataIndex: 'internalSkuKey' },
|
||||
{ title: '商品', dataIndex: 'goodsName' },
|
||||
{ title: '商品 ID', dataIndex: 'commodityId' },
|
||||
{ title: '积分', dataIndex: 'requiredPoints' },
|
||||
{ title: '内部 SKU', dataIndex: 'internalSkuKey', width: 150 },
|
||||
{
|
||||
title: '活动批次',
|
||||
key: 'campaign',
|
||||
width: 170,
|
||||
render: (_: unknown, row) => (
|
||||
<Space direction="vertical" size={0}>
|
||||
<Text>{row.campaignName || row.campaignKey}</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>{row.campaignKey}</Text>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{ title: '商品', dataIndex: 'goodsName', width: 150 },
|
||||
{ title: '商品 ID', dataIndex: 'commodityId', width: 180 },
|
||||
{
|
||||
title: '分类',
|
||||
key: 'saleMode',
|
||||
width: 130,
|
||||
render: (_: unknown, row) => (
|
||||
<Space direction="vertical" size={2}>
|
||||
<Tag color={row.saleMode === 'presale' ? 'gold' : row.saleMode === 'direct' ? 'green' : 'default'}>
|
||||
{SALE_MODE_LABELS[row.saleMode] || row.saleMode}
|
||||
</Tag>
|
||||
<Tag>{AVAILABILITY_LABELS[row.availabilityState] || row.availabilityState}</Tag>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{ title: '积分', dataIndex: 'requiredPoints', width: 80 },
|
||||
{ title: '影响任务', dataIndex: 'affectedTasks', width: 90 },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'enabled',
|
||||
render: (value: boolean) => <Tag color={value ? 'green' : 'default'}>{value ? '启用' : '停用'}</Tag>,
|
||||
width: 100,
|
||||
render: (value: boolean, row) => (
|
||||
<Tag color={row.archivedAt ? 'default' : value ? 'green' : 'orange'}>
|
||||
{row.archivedAt ? '已归档' : value ? '启用' : '停用'}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'actions',
|
||||
width: 310,
|
||||
render: (_: unknown, row) => (
|
||||
<Space wrap size={4}>
|
||||
<Button size="small" disabled={Boolean(row.archivedAt)} onClick={() => editMapping(row)}>
|
||||
编辑
|
||||
</Button>
|
||||
{row.archivedAt ? (
|
||||
<Button size="small" onClick={() => runMappingAction(row, 'restore')}>
|
||||
恢复
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => runMappingAction(row, row.enabled ? 'disable' : 'enable')}
|
||||
>
|
||||
{row.enabled ? '停用' : '启用'}
|
||||
</Button>
|
||||
<Button size="small" onClick={() => runMappingAction(row, 'archive')}>
|
||||
归档
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button size="small" danger onClick={() => removeMapping(row)}>
|
||||
删除
|
||||
</Button>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
scroll={{ x: 1300 }}
|
||||
/>
|
||||
),
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user