fix(douyu): 拆分账号资格活动窗口与库存语义

This commit is contained in:
yml
2026-11-22 20:04:49 +08:00
parent d78437c6ac
commit 1906f924bc
26 changed files with 896 additions and 174 deletions
@@ -702,3 +702,4 @@ Runner 启动前必须有预算 token;没有 token 时留在工作队列。
| 2026-11-22 | 履约租约改为状态化策略:默认无限,预售/人工独立配置,完成或取消后才设置释放时间 | | 2026-11-22 | 履约租约改为状态化策略:默认无限,预售/人工独立配置,完成或取消后才设置释放时间 |
| 2026-11-22 | 按生产并发、CK 流失和历史领取峰值提高全局供给目标,并安全升级旧默认组合 | | 2026-11-22 | 按生产并发、CK 流失和历史领取峰值提高全局供给目标,并安全升级旧默认组合 |
| 2026-11-22 | 抽取统一账号准入过滤;外部协作推荐改为纯本地能力池,兑换记录统一走本地同步投影 | | 2026-11-22 | 抽取统一账号准入过滤;外部协作推荐改为纯本地能力池,兑换记录统一走本地同步投影 |
| 2026-11-22 | 商品能力拆分账号资格、活动窗口和官方库存三轴;自动选号只读账号资格,预售允许开放前分配 |
@@ -112,12 +112,12 @@ GET /wgapi/ordnc/activity/peace/storehome
| `commodityId` | 商品唯一标识 | `account_commodity_states.commodity_id` | | `commodityId` | 商品唯一标识 | `account_commodity_states.commodity_id` |
| `commodityName` | 商品名 | `commodity_name` | | `commodityName` | 商品名 | `commodity_name` |
| `score` | 兑换所需积分 | 商品目录和资源判断 | | `score` | 兑换所需积分 | 商品目录和资源判断 |
| `status=1` | 当前账号已达该商品兑换上限 | `availability=limited`,自动选号硬排除 | | `status=1` | 当前账号已达该商品兑换上限 | `account_eligibility=limited`,自动选号硬排除 |
| `status=0` | 当前账号未达兑换上限 | 仍需继续判断库存、时间和开放状态 | | `status=0` | 当前账号有兑换资格 | `account_eligibility=eligible`,不受库存和活动时间影响 |
| `storeStatus=0` | 官方商城当前不可售 | `availability=no_stock` | | `storeStatus=0` | 官方商城展示状态关闭 | `stock_state=out_of_stock`,仅供执行提示,不参与自动选号 |
| `openStatus=0` | 活动尚未开放 | `availability=not_open` | | `openStatus=0` | 活动当前未开放 | `offer_state=before`,预售仍允许提前分配和绑定 |
| `count<=0` | 当前库存不足 | `availability=no_stock` | | `count<=0` | 官方全局库存不足 | `stock_state=out_of_stock`,仅供展示和兑换执行参考 |
| `startTime/endTime` | 商品外层开放窗口 | 与本地时间比较,投影到 `available_from/available_until` | | `startTime/endTime` | 商品开放窗口 | `offer_state=before/active/expired` 并投影到 `available_from/available_until` |
| `timeLimited` | 是否限时开放 | `time_limited` | | `timeLimited` | 是否限时开放 | `time_limited` |
| `specTimes` | 一天多场或分段开放计划 | `schedule_json` | | `specTimes` | 一天多场或分段开放计划 | `schedule_json` |
| `eliteLimited=1` | 商品要求精英手册资格 | 单独保存为门槛,不能写成账号限兑 | | `eliteLimited=1` | 商品要求精英手册资格 | 单独保存为门槛,不能写成账号限兑 |
@@ -126,21 +126,38 @@ GET /wgapi/ordnc/activity/peace/storehome
| `limitRooms` | 可用直播间列表 | 按商品目录或原始快照保留 | | `limitRooms` | 可用直播间列表 | 按商品目录或原始快照保留 |
| `preExchange.isExists=1` | 当前账号已有预兑记录 | 表示预兑状态,不等于已兑换 | | `preExchange.isExists=1` | 当前账号已有预兑记录 | 表示预兑状态,不等于已兑换 |
`count` 是商品库存,不是该账号还能兑换几次。抓包中存在 `status=1` 且 `count` 是商品全局库存,不是该账号还能兑换几次。抓包中既存在 `status=1`
`count` 仍为大量正数的情况,因此不能通过库存判断当前账号是否已限兑。 且 `count` 仍为大量正数的情况,也存在 `status=0`、`count=0`、`storeStatus=0`
但账号仍有兑换资格的情况。因此库存绝不能参与账号限兑或自动选号判断。
## 分类优先级 ## 三轴分类
`storehome` 单项归一成本地 `availability` 时必须保持以下顺序: `storehome` 单项必须拆成三个互不覆盖的维度:
1. 时间窗口未开始:`not_open`; 1. 账号资格 `account_eligibility`:
2. 时间窗口已结束:`expired`; - `status=1` → `limited`
3. `status=1`:`limited`; - `status=0` → `eligible`
4. `storeStatus=0`:`no_stock`; - 缺失 → `unknown`
5. `count<=0`:`no_stock`; 2. 活动窗口 `offer_state`:
6. `openStatus=0`:`not_open`; - 未开始或 `openStatus=0` → `before`
7. `status=0` 且以上条件均通过:`available`; - 窗口内 → `active`
8. 缺少可判定字段:`unknown`。 - 已结束 → `expired`
- 商品未返回 → `not_offered`
3. 全局库存 `stock_state`:
- `storeStatus=0` 或 `count<=0` → `out_of_stock`
- 有明确取值 → `in_stock`
- 缺失 → `unknown`
旧字段 `availability` 仍保留为“兑换执行状态”,由三轴派生,只用于界面提示和实际兑换前检查:
- 账号 `limited` → `limited`
- 活动未开始 → `not_open`
- 活动结束 → `expired`
- 活动进行中但全局库存不足 → `no_stock`
- 账号 `eligible`、活动进行中且有库存 → `available`
自动选号只允许读取 `account_eligibility=eligible`,不得读取 `stock_state`。
预售单允许 `offer_state=before` 的账号提前分配。
`eliteLimited`、`roomLimited`、`limitRoomType` 和 `preExchange` 是附加门槛或状态, `eliteLimited`、`roomLimited`、`limitRoomType` 和 `preExchange` 是附加门槛或状态,
不能在分类阶段无条件覆盖成 `limited`。 不能在分类阶段无条件覆盖成 `limited`。
@@ -314,10 +331,9 @@ raw
- `manual_id` - `manual_id`
- `rid` - `rid`
- `item_count` - `item_count`
- `limited_count` - `eligible_count` / `limited_count`
- `available_count` - `offer_before_count` / `offer_active_count`
- `not_open_count` - `stock_in_count` / `stock_out_count`
- `no_stock_count`
- `observed_at` - `observed_at`
- `source` - `source`
- `duration_ms` - `duration_ms`
@@ -333,9 +349,10 @@ raw
2. 同时需要 eligibility 和 goods 时仍只请求一次; 2. 同时需要 eligibility 和 goods 时仍只请求一次;
3. `status=1` 准确归为 `limited`; 3. `status=1` 准确归为 `limited`;
4. `status=0 + count>0 + 时间有效 + 开放有效` 归为 `available`; 4. `status=0 + count>0 + 时间有效 + 开放有效` 归为 `available`;
5. `storeStatus=0` 和 `count<=0` 归为 `no_stock`; 5. `storeStatus=0` 和 `count<=0` 只写入 `stock_state`,不参与自动选号;
6. 时间未到和已结束分别归为 `not_open/expired`; 6. 时间未到和已结束分别归为 `not_open/expired`;
7. `eliteLimited` 不会被误写成账号限兑; 7. `eliteLimited` 不会被误写成账号限兑;
8. 预售选号允许 `offer_state=before`,直接兑换单仍按活动窗口控制;
8. 完整快照成功后一次批量更新全部商品; 8. 完整快照成功后一次批量更新全部商品;
9. 商品状态未变化时不产生无意义逐行更新; 9. 商品状态未变化时不产生无意义逐行更新;
10. `storedetail` 和 `batchExchangeLimit` 不会出现在全量资格扫描调用链中。 10. `storedetail` 和 `batchExchangeLimit` 不会出现在全量资格扫描调用链中。
@@ -103,10 +103,12 @@ CK 生命周期、账号库存目标、覆盖率、查询同步契约和防重
### 账号商品能力 ### 账号商品能力
`account_commodity_states` 回答“这个账号对这个商品的官网结论是什么”: `account_commodity_states` 回答“这个账号对这个商品的官网结论是什么”,必须拆分三轴:
- `availability`:`available / limited / no_stock / not_open / expired / - `account_eligibility`:`eligible / limited / unknown`,只由账号级 `status` 决定;
not_offered / unknown`; - `offer_state`:`before / active / expired / not_offered / unknown`;
- `stock_state`:`in_stock / out_of_stock / unknown`,仅作展示和执行参考;
- `availability`:由前三个维度派生的兑换执行状态,不能作为自动选号资格;
- `raw_status`:官网原始账号级状态; - `raw_status`:官网原始账号级状态;
- `raw_json`:该商品最近一次官方原始字段; - `raw_json`:该商品最近一次官方原始字段;
- `observed_at`:最近一次观察时间; - `observed_at`:最近一次观察时间;
@@ -152,12 +154,14 @@ CK 生命周期、账号库存目标、覆盖率、查询同步契约和防重
### 官网可兑换 ### 官网可兑换
`official_available` 只由斗鱼官网判断: `official_available` 必须拆开判断:
- 官方账号级 `status=0`; - 账号资格只看官方账号级 `status=0`;
- 商品开放窗口有效; - 活动窗口单独记录为 `before / active / expired`;
- 官方库存和开放状态允许兑换; - 全局库存单独记录为 `in_stock / out_of_stock`;
- 没有明确限兑、无库存、未开放或已结束。 - 自动选号不读取库存;
- 预售允许账号资格通过后在 `before` 阶段提前分配;
- 实际兑换执行时,库存和开放状态才可能成为失败原因。
### 资源已就绪 ### 资源已就绪
@@ -241,16 +245,17 @@ AND 不违反内部兑换冷却
排序建议: 排序建议:
1. 新鲜 `available`; 1. 新鲜 `account_eligibility=eligible` 且 `offer_state=active`;
2. 过期但曾经 `available`,允许官网复核; 2. 预售单允许 `account_eligibility=eligible` 且 `offer_state=before`;
3. 从未查询或 `unknown`; 3. 过期资格允许进入后台刷新队列,但不能直接分配;
4. 已知 `limited / no_stock / not_open / expired` 默认不进入候选。 4. `account_eligibility=limited/unknown` 不进入候选;
5. `stock_state` 不参与排序或淘汰。
候选结果必须同时返回阻塞诊断,例如: 候选结果必须同时返回阻塞诊断,例如:
- 官网限兑; - 官网限兑;
- 无库存; - 活动未开放(预售不阻塞分配);
- 未开放; - 官方库存不足(仅执行提示,不阻塞分配);
- CK 失效; - CK 失效;
- 角色换绑冷却; - 角色换绑冷却;
- 有效租约; - 有效租约;
@@ -180,7 +180,7 @@ ck_observed_lifetime_seconds 不变
有效库存 = 有效库存 =
CK valid 且未超过新鲜阈值 CK valid 且未超过新鲜阈值
AND 商品状态新鲜 AND 商品状态新鲜
AND 官网 status=0 且库存/时间/开放状态允许 AND 官网账号兑换资格 status=0
AND 无有效租约 AND 无有效租约
AND 无活动外部协作单 AND 无活动外部协作单
AND 角色换绑冷却已结束 AND 角色换绑冷却已结束
@@ -192,7 +192,9 @@ ck_observed_lifetime_seconds 不变
- `resource_ready`:积分足够且宝典已开通; - `resource_ready`:积分足够且宝典已开通;
- `needs_recharge`:官网可兑换,但积分不足; - `needs_recharge`:官网可兑换,但积分不足;
- `needs_open`:官网可兑换,但宝典未开通; - `needs_open`:官网可兑换,但宝典未开通;
- `blocked`:官网限兑、无库存、未开放或冷却。 - `blocked`:账号官网限兑、资格未知或内部冷却;
- 官方全局库存、活动未开放属于执行提示,不阻断账号作为可分配供给;
- 预售可把 `offer_state=before` 且有资格的账号计入供给。
## 库存预警与补货 ## 库存预警与补货
+3 -3
View File
@@ -70,15 +70,15 @@
- 一键查询或资料刷新把官方 `storehome` 商品状态写入 `account_commodity_states`; - 一键查询或资料刷新把官方 `storehome` 商品状态写入 `account_commodity_states`;
- `storehome` 一次返回账号可见的全部商品,逐商品写状态,但每个账号只需一次列表请求; - `storehome` 一次返回账号可见的全部商品,逐商品写状态,但每个账号只需一次列表请求;
- 同时保存 `timeLimited`、`specTimes` 和起止时间,未开始/已结束与账号限兑分别处理; - 同时保存 `timeLimited`、`specTimes` 和起止时间,未开始/已结束与账号限兑分别处理;
- 可兑换、未开放等稳定能力默认缓存 6 小时,库存 15 分钟,未知状态 5 分钟; - 账号兑换资格和活动窗口默认缓存 6 小时,库存仅作展示并默认缓存 15 分钟;
否则 3 万账号池不可能在 15 分钟内刷新一遍,能力索引会长期处于过期状态; 否则 3 万账号池不可能在 15 分钟内刷新一遍,能力索引会长期处于过期状态;
- 有 pending 履约需求时,`account_capability_refresh` 作业优先刷新对应商品的过期能力; - 有 pending 履约需求时,`account_capability_refresh` 作业优先刷新对应商品的过期能力;
- 能力刷新和外部请求由 `account_sync_queue` 独立执行槽消费,不占用选号 worker; - 能力刷新和外部请求由 `account_sync_queue` 独立执行槽消费,不占用选号 worker;
- 本地能力池缺失时,选号失败只向该独立队列补入最多 20 个账号, - 本地能力池缺失时,选号失败只向该独立队列补入最多 20 个账号,
可用 `PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT` 调整; 可用 `PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT` 调整;
- 自动选号按 `next_allocate_at` 轮转,而不是永久按订单时间排在最前; - 自动选号按 `next_allocate_at` 轮转,而不是永久按订单时间排在最前;
- “未开放”任务直接排到商品开放时间,“无库存”至少退避 5 分钟, - 预售任务允许在活动开放前分配;直接兑换单的“未开放”任务排到商品开放时间;
“能力快照缺失”退避 2 分钟,避免失败任务每 45 秒占满执行槽; “账号资格快照缺失”退避 2 分钟。官方全局库存不阻止自动选号;
- 单轮默认处理 20 个本地任务,可用 `PLATFORM_FULFILLMENT_AUTO_ALLOCATE_BATCH` 调整。 - 单轮默认处理 20 个本地任务,可用 `PLATFORM_FULFILLMENT_AUTO_ALLOCATE_BATCH` 调整。
能力 TTL 可分别用 `ACCOUNT_COMMODITY_STABLE_TTL_SECONDS`、 能力 TTL 可分别用 `ACCOUNT_COMMODITY_STABLE_TTL_SECONDS`、
@@ -49,6 +49,9 @@ def _state(
platform="douyu", platform="douyu",
scope="elite", scope="elite",
commodity_id=commodity_id, commodity_id=commodity_id,
account_eligibility="eligible",
offer_state="active",
stock_state="in_stock",
availability="available", availability="available",
observed_at=NOW - timedelta(hours=2), observed_at=NOW - timedelta(hours=2),
valid_until=valid_until, valid_until=valid_until,
+51 -5
View File
@@ -34,10 +34,12 @@ def test_classify_goods_item_keeps_unknown_when_status_missing():
limited, reason, raw = service.classify_goods_item({"status": "1"}) limited, reason, raw = service.classify_goods_item({"status": "1"})
assert (limited, reason, raw) == ("limited", "该账号已达此商品兑换上限", "1") assert (limited, reason, raw) == ("limited", "该账号已达此商品兑换上限", "1")
no_stock, reason, _ = service.classify_goods_item( sold_out = service.classify_goods_item_assessment(
{"status": 0, "storeStatus": 0} {"status": 0, "storeStatus": 0, "count": 0}
) )
assert (no_stock, reason) == ("no_stock", "官方商城当前无库存") assert sold_out.account_eligibility == "eligible"
assert sold_out.stock_state == "out_of_stock"
assert sold_out.availability == "no_stock"
unknown, reason, raw = service.classify_goods_item({}) unknown, reason, raw = service.classify_goods_item({})
assert unknown == "unknown" assert unknown == "unknown"
@@ -62,13 +64,22 @@ def test_time_limited_goods_use_schedule_before_account_limit():
assert availability == "limited" assert availability == "limited"
assert "上限" in reason assert "上限" in reason
future = { future_limited = {
"status": "1", "status": "1",
"timeLimited": 1, "timeLimited": 1,
"startTime": str(int((NOW + timedelta(hours=2)).timestamp())), "startTime": str(int((NOW + timedelta(hours=2)).timestamp())),
"endTime": str(int((NOW + timedelta(hours=3)).timestamp())), "endTime": str(int((NOW + timedelta(hours=3)).timestamp())),
} }
availability, reason, _ = service.classify_goods_item(future, now=NOW) availability, reason, _ = service.classify_goods_item(future_limited, now=NOW)
assert availability == "limited"
assert "上限" in reason
future_eligible = {**future_limited, "status": "0"}
assessment = service.classify_goods_item_assessment(future_eligible, now=NOW)
availability = assessment.availability
reason = assessment.blocking_reason
assert assessment.account_eligibility == "eligible"
assert assessment.offer_state == "before"
assert availability == "not_open" assert availability == "not_open"
assert "未开始" in reason assert "未开始" in reason
@@ -83,6 +94,38 @@ def test_time_limited_goods_use_schedule_before_account_limit():
assert "已结束" in reason assert "已结束" in reason
def test_har_account_limit_is_independent_of_positive_global_stock():
rabbit = {
"commodityId": "20260120QYOOB_bag10",
"status": 1,
"storeStatus": 1,
"openStatus": 1,
"count": 76968,
}
assessment = service.classify_goods_item_assessment(rabbit, now=NOW)
assert assessment.account_eligibility == "limited"
assert assessment.stock_state == "in_stock"
assert assessment.availability == "limited"
def test_har_zero_global_stock_does_not_change_account_eligibility():
red_bear = {
"commodityId": "20260120QYOOB_bag395",
"status": 0,
"storeStatus": 0,
"openStatus": 1,
"count": 0,
}
assessment = service.classify_goods_item_assessment(red_bear, now=NOW)
assert assessment.account_eligibility == "eligible"
assert assessment.stock_state == "out_of_stock"
assert assessment.availability == "no_stock"
def test_sync_stores_time_window_and_next_boundary(db): def test_sync_stores_time_window_and_next_boundary(db):
account = _account(db, "cap-window") account = _account(db, "cap-window")
end_at = NOW + timedelta(minutes=5) end_at = NOW + timedelta(minutes=5)
@@ -163,6 +206,8 @@ def test_sync_account_goods_states_writes_capabilities_and_exchange_stats(db):
assert states["A"].last_exchange_at == NOW - timedelta(days=10) assert states["A"].last_exchange_at == NOW - timedelta(days=10)
assert states["B"].availability == "limited" assert states["B"].availability == "limited"
assert states["C"].availability == "no_stock" assert states["C"].availability == "no_stock"
assert states["C"].account_eligibility == "eligible"
assert states["C"].stock_state == "out_of_stock"
assert states["D"].availability == "unknown" assert states["D"].availability == "unknown"
assert states["A"].valid_until == NOW + timedelta( assert states["A"].valid_until == NOW + timedelta(
seconds=service.capability_ttl_seconds("available") seconds=service.capability_ttl_seconds("available")
@@ -295,6 +340,7 @@ def test_account_commodities_api_returns_summary_and_freshness(db):
account.id, account.id,
scope="", scope="",
availability="", availability="",
eligibility="",
limit=500, limit=500,
db=db, db=db,
current=user, current=user,
+4
View File
@@ -65,6 +65,9 @@ def _state(account: Account, commodity_id: str = "C") -> AccountCommodityState:
platform="douyu", platform="douyu",
scope="elite", scope="elite",
commodity_id=commodity_id, commodity_id=commodity_id,
account_eligibility="eligible",
offer_state="active",
stock_state="in_stock",
availability="available", availability="available",
observed_at=NOW, observed_at=NOW,
valid_until=NOW + timedelta(hours=1), valid_until=NOW + timedelta(hours=1),
@@ -172,6 +175,7 @@ def test_global_supply_inventory_batches_value_classes_in_two_queries(db):
db.flush() db.flush()
limited_state = _state(high_limited) limited_state = _state(high_limited)
limited_state.availability = "limited" limited_state.availability = "limited"
limited_state.account_eligibility = "limited"
db.add_all( db.add_all(
[ [
_state(high_free), _state(high_free),
+7 -1
View File
@@ -433,6 +433,9 @@ class TestDouyuCollabOrders:
platform="douyu", platform="douyu",
scope="elite", scope="elite",
commodity_id="gift-a", commodity_id="gift-a",
account_eligibility="eligible",
offer_state="active",
stock_state="in_stock",
availability="available", availability="available",
observed_at=datetime.now(UTC), observed_at=datetime.now(UTC),
valid_until=datetime.now(UTC) + timedelta(hours=1), valid_until=datetime.now(UTC) + timedelta(hours=1),
@@ -442,6 +445,9 @@ class TestDouyuCollabOrders:
platform="douyu", platform="douyu",
scope="elite", scope="elite",
commodity_id="gift-a", commodity_id="gift-a",
account_eligibility="eligible",
offer_state="active",
stock_state="in_stock",
availability="available", availability="available",
observed_at=datetime.now(UTC), observed_at=datetime.now(UTC),
valid_until=datetime.now(UTC) + timedelta(hours=1), valid_until=datetime.now(UTC) + timedelta(hours=1),
@@ -1927,7 +1933,7 @@ class TestDouyuCollabOrders:
assert goods[0]["status"] == "0" assert goods[0]["status"] == "0"
assert goods[0]["open_status"] == 0 assert goods[0]["open_status"] == 0
assert goods[0]["start_time"] == 1792749600 assert goods[0]["start_time"] == 1792749600
assert goods[0]["is_limited"] is True assert goods[0]["is_limited"] is False
def test_shop_rename_cascades_and_delete_rejects_in_use(self): def test_shop_rename_cascades_and_delete_rejects_in_use(self):
shop = collab.create_shop(self.session, self.admin, name="店铺B", remark="测试") shop = collab.create_shop(self.session, self.admin, name="店铺B", remark="测试")
+9 -1
View File
@@ -42,7 +42,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261122_0114" HEAD_REVISION = "20261122_0115"
# 迁移新增、但不声明在模型里的复合查询索引。 # 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = ( EXTRA_INDEXES = (
@@ -80,6 +80,14 @@ _LATER_ORM_COLUMNS = {
"douyu_external_orders": { "douyu_external_orders": {
"succeeded_at": "DATETIME NULL", "succeeded_at": "DATETIME NULL",
}, },
"account_commodity_states": {
"account_eligibility": "VARCHAR(16) NOT NULL DEFAULT 'unknown'",
"offer_state": "VARCHAR(16) NOT NULL DEFAULT 'unknown'",
"stock_state": "VARCHAR(16) NOT NULL DEFAULT 'unknown'",
"stock_count": "BIGINT NULL",
"store_status": "INTEGER NULL",
"open_status": "INTEGER NULL",
},
} }
+53 -1
View File
@@ -123,6 +123,13 @@ class _Base:
scope="elite", scope="elite",
commodity_id=COMMODITY, commodity_id=COMMODITY,
commodity_name=INTERNAL_SKU, commodity_name=INTERNAL_SKU,
account_eligibility=(
"limited" if availability == "limited" else "eligible"
),
offer_state="before" if availability == "not_open" else "active",
stock_state=(
"out_of_stock" if availability == "no_stock" else "in_stock"
),
availability=availability, availability=availability,
observed_at=NOW, observed_at=NOW,
valid_until=NOW + timedelta(hours=6), valid_until=NOW + timedelta(hours=6),
@@ -976,6 +983,8 @@ class TestSnapshotSync(_Base):
assert task.execution_status == "ready" assert task.execution_status == "ready"
assert task.next_allocate_at is not None assert task.next_allocate_at is not None
assert task.state_version == 1 assert task.state_version == 1
detail = service.get_task_detail(self.session, task.id)
assert detail["task"]["goodsName"] == INTERNAL_SKU
outbox = self.session.query(IntegrationOutbox).one() outbox = self.session.query(IntegrationOutbox).one()
assert outbox.payload_json["items"][0]["stateVersion"] == 1 assert outbox.payload_json["items"][0]["stateVersion"] == 1
@@ -1087,6 +1096,9 @@ class TestAccountSelection(_Base):
scope="elite", scope="elite",
commodity_id=COMMODITY, commodity_id=COMMODITY,
commodity_name=INTERNAL_SKU, commodity_name=INTERNAL_SKU,
account_eligibility="eligible",
offer_state="active",
stock_state="in_stock",
availability="available", availability="available",
observed_at=NOW, observed_at=NOW,
valid_until=NOW + timedelta(minutes=15), valid_until=NOW + timedelta(minutes=15),
@@ -1248,6 +1260,40 @@ class TestAccountSelection(_Base):
assert detail["task"]["exchangeStatus"] == "waiting_release" assert detail["task"]["exchangeStatus"] == "waiting_release"
assert detail["task"]["issueCode"] == "commodity_not_open" assert detail["task"]["issueCode"] == "commodity_not_open"
def test_presale_allocates_eligible_account_even_when_official_stock_is_zero(self):
account = self.account("presale-no-stock", capability=False)
self.session.add(
AccountCommodityState(
account_id=account.id,
platform="douyu",
scope="elite",
commodity_id=COMMODITY,
commodity_name=INTERNAL_SKU,
account_eligibility="eligible",
offer_state="before",
stock_state="out_of_stock",
availability="no_stock",
observed_at=NOW,
valid_until=NOW + timedelta(hours=1),
available_from=NOW + timedelta(days=4),
available_until=NOW + timedelta(days=10),
source="storehome_sync",
)
)
task = self.task()
task.sale_mode = "presale"
self.session.commit()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"]["id"] == account.id
assert detail["task"]["executionStatus"] == "allocated"
assert detail["task"]["exchangeStatus"] == "waiting_release"
def test_direct_sale_still_blocks_when_commodity_not_open(self): def test_direct_sale_still_blocks_when_commodity_not_open(self):
self.account("direct-future", availability="not_open") self.account("direct-future", availability="not_open")
task = self.task() task = self.task()
@@ -1273,6 +1319,9 @@ class TestAccountSelection(_Base):
scope="elite", scope="elite",
commodity_id=COMMODITY, commodity_id=COMMODITY,
commodity_name=INTERNAL_SKU, commodity_name=INTERNAL_SKU,
account_eligibility="eligible",
offer_state="before",
stock_state="in_stock",
availability="not_open", availability="not_open",
blocking_reason="限时兑换未开始", blocking_reason="限时兑换未开始",
observed_at=NOW, observed_at=NOW,
@@ -1300,7 +1349,7 @@ class TestAccountSelection(_Base):
commodity_id=COMMODITY, commodity_id=COMMODITY,
required_points=1280, required_points=1280,
now=NOW, now=NOW,
allow_not_open=True, allow_before_open=True,
) )
] == [account.id] ] == [account.id]
@@ -1335,6 +1384,9 @@ class TestAccountSelection(_Base):
scope="elite", scope="elite",
commodity_id=COMMODITY, commodity_id=COMMODITY,
commodity_name=INTERNAL_SKU, commodity_name=INTERNAL_SKU,
account_eligibility="eligible",
offer_state="active",
stock_state="in_stock",
availability="available", availability="available",
observed_at=NOW, observed_at=NOW,
valid_until=NOW + timedelta(hours=1), valid_until=NOW + timedelta(hours=1),
@@ -457,6 +457,10 @@
"20261122_0114_account_commodity_global_available_index.py": { "20261122_0114_account_commodity_global_available_index.py": {
"revision": "20261122_0114", "revision": "20261122_0114",
"sha256": "3b0da21df3a48784bf5e204d3fc95fc2e40c0edded4601869c36f1d52fe07d4b" "sha256": "3b0da21df3a48784bf5e204d3fc95fc2e40c0edded4601869c36f1d52fe07d4b"
},
"20261122_0115_account_commodity_eligibility_split.py": {
"revision": "20261122_0115",
"sha256": "a66dba263e6b2e9b10b2bd52316ef630890b470a3c2b08f8ab0a07ef0521d0fa"
} }
} }
} }
@@ -0,0 +1,184 @@
"""split account eligibility, offer window and global stock.
Revision ID: 20261122_0115
Revises: 20261122_0114
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261122_0115"
down_revision: str | None = "20261122_0114"
branch_labels: str | None = None
depends_on: str | None = None
TABLE = "account_commodity_states"
INDEX = "ix_account_commodity_eligibility"
def _columns() -> set[str]:
inspector = sa.inspect(op.get_bind())
if not inspector.has_table(TABLE):
return set()
return {str(column["name"]) for column in inspector.get_columns(TABLE)}
def _indexes() -> set[str]:
inspector = sa.inspect(op.get_bind())
if not inspector.has_table(TABLE):
return set()
return {str(index["name"]) for index in inspector.get_indexes(TABLE)}
def upgrade() -> None:
columns = _columns()
additions = (
sa.Column(
"account_eligibility",
sa.String(length=16),
nullable=False,
server_default="unknown",
),
sa.Column(
"offer_state",
sa.String(length=16),
nullable=False,
server_default="unknown",
),
sa.Column(
"stock_state",
sa.String(length=16),
nullable=False,
server_default="unknown",
),
sa.Column("stock_count", sa.BigInteger(), nullable=True),
sa.Column("store_status", sa.Integer(), nullable=True),
sa.Column("open_status", sa.Integer(), nullable=True),
)
for column in additions:
if column.name not in columns:
op.add_column(TABLE, column)
# raw_status 是已经落库的账号级 status,不依赖 JSON 函数即可立即恢复资格。
op.execute(
sa.text(
f"""
UPDATE {TABLE}
SET account_eligibility = CASE
WHEN raw_status = '0' THEN 'eligible'
WHEN raw_status = '1' THEN 'limited'
ELSE 'unknown'
END
"""
)
)
bind = op.get_bind()
if bind.dialect.name == "mysql":
op.execute(
sa.text(
f"""
UPDATE {TABLE}
SET
offer_state = CASE
WHEN availability = 'not_offered' THEN 'not_offered'
WHEN JSON_UNQUOTE(JSON_EXTRACT(
raw_json, '$.openStatus'
)) = '0' THEN 'before'
WHEN available_from IS NOT NULL
AND available_from > UTC_TIMESTAMP() THEN 'before'
WHEN available_until IS NOT NULL
AND available_until < UTC_TIMESTAMP() THEN 'expired'
WHEN availability = 'not_open' THEN 'before'
WHEN raw_json IS NULL THEN 'unknown'
ELSE 'active'
END,
stock_count = CASE
WHEN JSON_EXTRACT(raw_json, '$.count') IS NULL THEN NULL
ELSE CAST(JSON_UNQUOTE(
JSON_EXTRACT(raw_json, '$.count')
) AS SIGNED)
END,
store_status = CASE
WHEN JSON_EXTRACT(raw_json, '$.storeStatus') IS NULL THEN NULL
ELSE CAST(JSON_UNQUOTE(
JSON_EXTRACT(raw_json, '$.storeStatus')
) AS SIGNED)
END,
open_status = CASE
WHEN JSON_EXTRACT(raw_json, '$.openStatus') IS NULL THEN NULL
ELSE CAST(JSON_UNQUOTE(
JSON_EXTRACT(raw_json, '$.openStatus')
) AS SIGNED)
END,
stock_state = CASE
WHEN raw_json IS NULL THEN 'unknown'
WHEN COALESCE(
CAST(JSON_UNQUOTE(
JSON_EXTRACT(raw_json, '$.storeStatus')
) AS SIGNED),
1
) = 0 THEN 'out_of_stock'
WHEN COALESCE(
CAST(JSON_UNQUOTE(
JSON_EXTRACT(raw_json, '$.count')
) AS SIGNED),
1
) <= 0 THEN 'out_of_stock'
ELSE 'in_stock'
END
"""
)
)
else:
op.execute(
sa.text(
f"""
UPDATE {TABLE}
SET offer_state = CASE
WHEN availability = 'not_offered' THEN 'not_offered'
WHEN available_from IS NOT NULL
AND available_from > CURRENT_TIMESTAMP THEN 'before'
WHEN available_until IS NOT NULL
AND available_until < CURRENT_TIMESTAMP THEN 'expired'
WHEN availability = 'not_open' THEN 'before'
WHEN raw_json IS NULL THEN 'unknown'
ELSE 'active'
END
"""
)
)
if INDEX not in _indexes():
op.create_index(
INDEX,
TABLE,
[
"platform",
"scope",
"commodity_id",
"account_eligibility",
"offer_state",
"valid_until",
"account_id",
],
unique=False,
)
def downgrade() -> None:
if INDEX in _indexes():
op.drop_index(INDEX, table_name=TABLE)
columns = _columns()
for name in (
"open_status",
"store_status",
"stock_count",
"stock_state",
"offer_state",
"account_eligibility",
):
if name in columns:
op.drop_column(TABLE, name)
+28 -1
View File
@@ -1899,10 +1899,27 @@ class AccountCommodityState(Base):
commodity_name: Mapped[str] = mapped_column( commodity_name: Mapped[str] = mapped_column(
String(256), nullable=False, default="", server_default="" String(256), nullable=False, default="", server_default=""
) )
# available / limited / no_stock / not_open / not_offered / unknown # 展示和执行用的派生状态;自动选号不再读取本列。
# available / limited / no_stock / not_open / not_offered / expired / unknown
availability: Mapped[str] = mapped_column( availability: Mapped[str] = mapped_column(
String(16), nullable=False, default="unknown", server_default="unknown" String(16), nullable=False, default="unknown", server_default="unknown"
) )
# 账号级兑换资格,只由 storehome.status 决定。
# eligible / limited / unknown
account_eligibility: Mapped[str] = mapped_column(
String(16), nullable=False, default="unknown", server_default="unknown"
)
# 商品活动窗口:before / active / expired / not_offered / unknown
offer_state: Mapped[str] = mapped_column(
String(16), nullable=False, default="unknown", server_default="unknown"
)
# 官方全局库存,只供展示和兑换执行参考,绝不参与自动选号。
stock_state: Mapped[str] = mapped_column(
String(16), nullable=False, default="unknown", server_default="unknown"
)
stock_count: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
store_status: Mapped[int | None] = mapped_column(Integer, nullable=True)
open_status: Mapped[int | None] = mapped_column(Integer, nullable=True)
blocking_reason: Mapped[str] = mapped_column( blocking_reason: Mapped[str] = mapped_column(
String(255), nullable=False, default="", server_default="" String(255), nullable=False, default="", server_default=""
) )
@@ -1965,6 +1982,16 @@ class AccountCommodityState(Base):
"valid_until", "valid_until",
"account_id", "account_id",
), ),
Index(
"ix_account_commodity_eligibility",
"platform",
"scope",
"commodity_id",
"account_eligibility",
"offer_state",
"valid_until",
"account_id",
),
Index( Index(
"ix_account_commodity_account", "ix_account_commodity_account",
"account_id", "account_id",
+18 -2
View File
@@ -1545,6 +1545,7 @@ def account_commodities(
account_id: int, account_id: int,
scope: str = Query("", max_length=16), scope: str = Query("", max_length=16),
availability: str = Query("", max_length=16), availability: str = Query("", max_length=16),
eligibility: str = Query("", max_length=16),
limit: int = Query(500, ge=1, le=1000), limit: int = Query(500, ge=1, le=1000),
db: Session = Depends(get_db), db: Session = Depends(get_db),
current: User = Depends(get_current_user), current: User = Depends(get_current_user),
@@ -1570,13 +1571,22 @@ def account_commodities(
query = query.filter( query = query.filter(
AccountCommodityState.availability == availability_value AccountCommodityState.availability == availability_value
) )
eligibility_value = eligibility.strip()
if eligibility_value:
query = query.filter(
AccountCommodityState.account_eligibility == eligibility_value
)
rows = ( rows = (
query.order_by( query.order_by(
case( case(
(AccountCommodityState.availability == "available", 0), (AccountCommodityState.account_eligibility == "eligible", 0),
(AccountCommodityState.availability == "limited", 1), (AccountCommodityState.account_eligibility == "limited", 1),
else_=2, else_=2,
), ),
case(
(AccountCommodityState.offer_state == "active", 0),
else_=1,
),
AccountCommodityState.valid_until.desc(), AccountCommodityState.valid_until.desc(),
AccountCommodityState.commodity_id.asc(), AccountCommodityState.commodity_id.asc(),
) )
@@ -1589,6 +1599,12 @@ def account_commodities(
"commodity_id": row.commodity_id, "commodity_id": row.commodity_id,
"commodity_name": row.commodity_name, "commodity_name": row.commodity_name,
"scope": row.scope, "scope": row.scope,
"account_eligibility": row.account_eligibility,
"offer_state": row.offer_state,
"stock_state": row.stock_state,
"stock_count": row.stock_count,
"store_status": row.store_status,
"open_status": row.open_status,
"availability": row.availability, "availability": row.availability,
"blocking_reason": row.blocking_reason, "blocking_reason": row.blocking_reason,
"raw_status": row.raw_status, "raw_status": row.raw_status,
@@ -24,6 +24,20 @@ AVAILABILITY_NOT_OFFERED = "not_offered"
AVAILABILITY_EXPIRED = "expired" AVAILABILITY_EXPIRED = "expired"
AVAILABILITY_UNKNOWN = "unknown" AVAILABILITY_UNKNOWN = "unknown"
ACCOUNT_ELIGIBILITY_ELIGIBLE = "eligible"
ACCOUNT_ELIGIBILITY_LIMITED = "limited"
ACCOUNT_ELIGIBILITY_UNKNOWN = "unknown"
OFFER_STATE_BEFORE = "before"
OFFER_STATE_ACTIVE = "active"
OFFER_STATE_EXPIRED = "expired"
OFFER_STATE_NOT_OFFERED = "not_offered"
OFFER_STATE_UNKNOWN = "unknown"
STOCK_STATE_IN_STOCK = "in_stock"
STOCK_STATE_OUT_OF_STOCK = "out_of_stock"
STOCK_STATE_UNKNOWN = "unknown"
DEFAULT_CAPABILITY_TTL_SECONDS = 15 * 60 DEFAULT_CAPABILITY_TTL_SECONDS = 15 * 60
DEFAULT_STABLE_CAPABILITY_TTL_SECONDS = 6 * 60 * 60 DEFAULT_STABLE_CAPABILITY_TTL_SECONDS = 6 * 60 * 60
DEFAULT_LIMITED_CAPABILITY_TTL_SECONDS = 24 * 60 * 60 DEFAULT_LIMITED_CAPABILITY_TTL_SECONDS = 24 * 60 * 60
@@ -174,16 +188,26 @@ def goods_time_window(
) )
def classify_goods_item( @dataclass(frozen=True)
class GoodsAssessment:
account_eligibility: str
offer_state: str
stock_state: str
availability: str
blocking_reason: str
raw_status: str
stock_count: int | None
store_status: int | None
open_status: int | None
window: GoodsTimeWindow
def classify_goods_item_assessment(
item: dict[str, Any], item: dict[str, Any],
*, *,
now: datetime | None = None, now: datetime | None = None,
) -> tuple[str, str, str]: ) -> GoodsAssessment:
"""把官方 storehome 商品项归一成能力状态。 """拆分账号资格、活动窗口和全局库存,禁止三种语义互相覆盖。"""
返回 ``(availability, blocking_reason, raw_status)``。只有官方明确给出的
账号级 ``status`` 才允许写成 available / limited;缺字段一律 unknown。
"""
moment = now or datetime.now(UTC) moment = now or datetime.now(UTC)
window = goods_time_window(item, now=moment) window = goods_time_window(item, now=moment)
raw_status = str(item.get("status") if item.get("status") is not None else "") raw_status = str(item.get("status") if item.get("status") is not None else "")
@@ -200,32 +224,77 @@ def classify_goods_item(
) )
count = _to_int(item.get("count")) count = _to_int(item.get("count"))
if window.state == "before":
return (
AVAILABILITY_NOT_OPEN,
f"限时兑换未开始,开始于 {window.start.isoformat() if window.start else '未知时间'}",
raw_status,
)
if window.state == "after":
return AVAILABILITY_EXPIRED, "限时兑换已结束", raw_status
if status == 1: if status == 1:
return AVAILABILITY_LIMITED, "该账号已达此商品兑换上限", raw_status account_eligibility = ACCOUNT_ELIGIBILITY_LIMITED
if store_status == 0: elif status == 0:
return AVAILABILITY_NO_STOCK, "官方商城当前无库存", raw_status account_eligibility = ACCOUNT_ELIGIBILITY_ELIGIBLE
if count is not None and count <= 0: else:
return AVAILABILITY_NO_STOCK, "官方商城当前无库存", raw_status account_eligibility = ACCOUNT_ELIGIBILITY_UNKNOWN
if open_status == 0:
return AVAILABILITY_NOT_OPEN, "活动尚未开放兑换", raw_status if open_status == 0 or window.state == "before":
if status == 0: offer_state = OFFER_STATE_BEFORE
return AVAILABILITY_AVAILABLE, "", raw_status elif window.state == "after":
return AVAILABILITY_UNKNOWN, "官方商品列表未返回可判定的账号状态", raw_status offer_state = OFFER_STATE_EXPIRED
elif window.state == "active" or window.state == "":
offer_state = OFFER_STATE_ACTIVE
else:
offer_state = OFFER_STATE_UNKNOWN
if store_status == 0 or (count is not None and count <= 0):
stock_state = STOCK_STATE_OUT_OF_STOCK
elif store_status is not None or count is not None:
stock_state = STOCK_STATE_IN_STOCK
else:
stock_state = STOCK_STATE_UNKNOWN
if account_eligibility == ACCOUNT_ELIGIBILITY_LIMITED:
availability = AVAILABILITY_LIMITED
reason = "该账号已达此商品兑换上限"
elif account_eligibility == ACCOUNT_ELIGIBILITY_UNKNOWN:
availability = AVAILABILITY_UNKNOWN
reason = "官方商品列表未返回可判定的账号兑换资格"
elif offer_state == OFFER_STATE_BEFORE:
availability = AVAILABILITY_NOT_OPEN
reason = (
f"限时兑换未开始,开始于 {window.start.isoformat()}"
if window.start
else "活动尚未开放兑换"
)
elif offer_state == OFFER_STATE_EXPIRED:
availability = AVAILABILITY_EXPIRED
reason = "限时兑换已结束"
elif stock_state == STOCK_STATE_OUT_OF_STOCK:
availability = AVAILABILITY_NO_STOCK
reason = "官方商城当前无库存"
else:
availability = AVAILABILITY_AVAILABLE
reason = ""
return GoodsAssessment(
account_eligibility=account_eligibility,
offer_state=offer_state,
stock_state=stock_state,
availability=availability,
blocking_reason=reason,
raw_status=raw_status,
stock_count=count,
store_status=store_status,
open_status=open_status,
window=window,
)
@dataclass(frozen=True) def classify_goods_item(
class GoodsAssessment: item: dict[str, Any],
availability: str *,
blocking_reason: str now: datetime | None = None,
raw_status: str ) -> tuple[str, str, str]:
"""兼容旧调用:返回派生展示状态,不用于自动选号。"""
assessment = classify_goods_item_assessment(item, now=now)
return (
assessment.availability,
assessment.blocking_reason,
assessment.raw_status,
)
def classify_goods_items( def classify_goods_items(
@@ -243,12 +312,7 @@ def classify_goods_items(
).strip() ).strip()
if not commodity_id: if not commodity_id:
continue continue
availability, reason, raw_status = classify_goods_item(item, now=now) assessments[commodity_id] = classify_goods_item_assessment(item, now=now)
assessments[commodity_id] = GoodsAssessment(
availability=availability,
blocking_reason=reason,
raw_status=raw_status,
)
return assessments return assessments
@@ -293,6 +357,24 @@ def exchange_gate_for_availability(
return "not_available", issue_code, reason or fallback return "not_available", issue_code, reason or fallback
def allocation_availability(
account_eligibility: str,
offer_state: str,
) -> str:
"""自动选号只消费账号资格与活动窗口,明确忽略全局库存。"""
if account_eligibility == ACCOUNT_ELIGIBILITY_LIMITED:
return AVAILABILITY_LIMITED
if account_eligibility != ACCOUNT_ELIGIBILITY_ELIGIBLE:
return AVAILABILITY_UNKNOWN
if offer_state == OFFER_STATE_BEFORE:
return AVAILABILITY_NOT_OPEN
if offer_state == OFFER_STATE_EXPIRED:
return AVAILABILITY_EXPIRED
if offer_state == OFFER_STATE_NOT_OFFERED:
return AVAILABILITY_NOT_OFFERED
return AVAILABILITY_AVAILABLE
def _exchange_stats( def _exchange_stats(
db: Session, db: Session,
*, *,
@@ -416,19 +498,25 @@ def sync_account_goods_states(
db.add(state) db.add(state)
by_commodity[commodity_id] = state by_commodity[commodity_id] = state
availability, reason, raw_status = classify_goods_item(item, now=moment) assessment = classify_goods_item_assessment(item, now=moment)
window = goods_time_window(item, now=moment) window = assessment.window
ttl_valid_until = moment + timedelta( ttl_valid_until = moment + timedelta(
seconds=capability_ttl_seconds(availability) seconds=capability_ttl_seconds(assessment.availability)
) )
last_exchange_at, exchange_count = exchange_stats.get( last_exchange_at, exchange_count = exchange_stats.get(
commodity_id, commodity_id,
(None, 0), (None, 0),
) )
state.commodity_name = _commodity_name(item)[:256] state.commodity_name = _commodity_name(item)[:256]
state.availability = availability state.account_eligibility = assessment.account_eligibility
state.blocking_reason = reason[:255] state.offer_state = assessment.offer_state
state.raw_status = raw_status[:16] state.stock_state = assessment.stock_state
state.stock_count = assessment.stock_count
state.store_status = assessment.store_status
state.open_status = assessment.open_status
state.availability = assessment.availability
state.blocking_reason = assessment.blocking_reason[:255]
state.raw_status = assessment.raw_status[:16]
state.raw_json = dict(item) state.raw_json = dict(item)
state.time_limited = window.time_limited state.time_limited = window.time_limited
state.available_from = window.start state.available_from = window.start
@@ -458,6 +546,12 @@ def sync_account_goods_states(
): ):
continue continue
state.availability = AVAILABILITY_NOT_OFFERED state.availability = AVAILABILITY_NOT_OFFERED
state.account_eligibility = ACCOUNT_ELIGIBILITY_UNKNOWN
state.offer_state = OFFER_STATE_NOT_OFFERED
state.stock_state = STOCK_STATE_UNKNOWN
state.stock_count = None
state.store_status = None
state.open_status = None
state.blocking_reason = "官方商品列表本次未返回该商品" state.blocking_reason = "官方商品列表本次未返回该商品"
state.raw_json = None state.raw_json = None
state.time_limited = False state.time_limited = False
@@ -483,6 +577,12 @@ def record_account_commodity_state(
*, *,
commodity_id: str, commodity_id: str,
availability: str, availability: str,
account_eligibility: str | None = None,
offer_state: str | None = None,
stock_state: str | None = None,
stock_count: int | None = None,
store_status: int | None = None,
open_status: int | None = None,
blocking_reason: str = "", blocking_reason: str = "",
raw_status: str = "", raw_status: str = "",
observed_at: datetime | None = None, observed_at: datetime | None = None,
@@ -493,6 +593,26 @@ def record_account_commodity_state(
) -> AccountCommodityState: ) -> AccountCommodityState:
"""写入单个商品的实时检查结论,供下一轮匹配直接使用。""" """写入单个商品的实时检查结论,供下一轮匹配直接使用。"""
moment = observed_at or datetime.now(UTC) moment = observed_at or datetime.now(UTC)
if account_eligibility is None:
account_eligibility = {
AVAILABILITY_LIMITED: ACCOUNT_ELIGIBILITY_LIMITED,
AVAILABILITY_UNKNOWN: ACCOUNT_ELIGIBILITY_UNKNOWN,
AVAILABILITY_NOT_OFFERED: ACCOUNT_ELIGIBILITY_UNKNOWN,
}.get(availability, ACCOUNT_ELIGIBILITY_ELIGIBLE)
if offer_state is None:
offer_state = {
AVAILABILITY_NOT_OPEN: OFFER_STATE_BEFORE,
AVAILABILITY_EXPIRED: OFFER_STATE_EXPIRED,
AVAILABILITY_NOT_OFFERED: OFFER_STATE_NOT_OFFERED,
AVAILABILITY_AVAILABLE: OFFER_STATE_ACTIVE,
AVAILABILITY_NO_STOCK: OFFER_STATE_ACTIVE,
}.get(availability, OFFER_STATE_UNKNOWN)
if stock_state is None:
stock_state = (
STOCK_STATE_OUT_OF_STOCK
if availability == AVAILABILITY_NO_STOCK
else STOCK_STATE_UNKNOWN
)
ttl = ( ttl = (
capability_ttl_seconds(availability) capability_ttl_seconds(availability)
if valid_for_seconds is None if valid_for_seconds is None
@@ -523,6 +643,12 @@ def record_account_commodity_state(
now=moment, now=moment,
) )
last_exchange_at, exchange_count = exchange_stats.get(commodity_id, (None, 0)) last_exchange_at, exchange_count = exchange_stats.get(commodity_id, (None, 0))
state.account_eligibility = account_eligibility
state.offer_state = offer_state
state.stock_state = stock_state
state.stock_count = stock_count
state.store_status = store_status
state.open_status = open_status
state.availability = availability state.availability = availability
state.blocking_reason = blocking_reason[:255] state.blocking_reason = blocking_reason[:255]
state.raw_status = raw_status[:16] state.raw_status = raw_status[:16]
@@ -574,6 +700,7 @@ def mark_commodity_exchanged(
last_exchange_at, exchange_count = exchange_stats.get(commodity_id, (moment, 1)) last_exchange_at, exchange_count = exchange_stats.get(commodity_id, (moment, 1))
if commodity_name: if commodity_name:
state.commodity_name = commodity_name[:256] state.commodity_name = commodity_name[:256]
state.account_eligibility = ACCOUNT_ELIGIBILITY_LIMITED
state.availability = AVAILABILITY_LIMITED state.availability = AVAILABILITY_LIMITED
state.blocking_reason = "该账号已兑换过此商品,365 天内不可重复分配" state.blocking_reason = "该账号已兑换过此商品,365 天内不可重复分配"
state.observed_at = moment state.observed_at = moment
@@ -600,10 +727,12 @@ def invalidate_account_commodity_states(
db.query(AccountCommodityState) db.query(AccountCommodityState)
.filter( .filter(
AccountCommodityState.account_id == account_id, AccountCommodityState.account_id == account_id,
AccountCommodityState.availability == AVAILABILITY_AVAILABLE, AccountCommodityState.account_eligibility
== ACCOUNT_ELIGIBILITY_ELIGIBLE,
) )
.update( .update(
{ {
AccountCommodityState.account_eligibility: ACCOUNT_ELIGIBILITY_UNKNOWN,
AccountCommodityState.availability: AVAILABILITY_UNKNOWN, AccountCommodityState.availability: AVAILABILITY_UNKNOWN,
AccountCommodityState.blocking_reason: reason[:255], AccountCommodityState.blocking_reason: reason[:255],
AccountCommodityState.observed_at: moment, AccountCommodityState.observed_at: moment,
@@ -664,13 +793,51 @@ def account_capability_counts(
or 0 or 0
) )
result["fresh_available"] = int(fresh_available) result["fresh_available"] = int(fresh_available)
eligibility_rows = (
db.query(
AccountCommodityState.account_eligibility,
func.count(AccountCommodityState.id),
)
.filter(AccountCommodityState.account_id == account_id)
.group_by(AccountCommodityState.account_eligibility)
.all()
)
for eligibility, count in eligibility_rows:
result[f"eligibility_{eligibility}"] = int(count or 0)
result["fresh_eligible"] = int(
db.query(func.count(AccountCommodityState.id))
.filter(
AccountCommodityState.account_id == account_id,
AccountCommodityState.account_eligibility
== ACCOUNT_ELIGIBILITY_ELIGIBLE,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > moment,
)
.scalar()
or 0
)
result["total"] = sum( result["total"] = sum(
value for key, value in result.items() if key not in {"fresh_available", "total"} value
for key, value in result.items()
if key
not in {
"fresh_available",
"fresh_eligible",
"total",
*{f"eligibility_{item}" for item in (
ACCOUNT_ELIGIBILITY_ELIGIBLE,
ACCOUNT_ELIGIBILITY_LIMITED,
ACCOUNT_ELIGIBILITY_UNKNOWN,
)},
}
) )
return result return result
__all__ = [ __all__ = [
"ACCOUNT_ELIGIBILITY_ELIGIBLE",
"ACCOUNT_ELIGIBILITY_LIMITED",
"ACCOUNT_ELIGIBILITY_UNKNOWN",
"AVAILABILITY_AVAILABLE", "AVAILABILITY_AVAILABLE",
"AVAILABILITY_EXPIRED", "AVAILABILITY_EXPIRED",
"AVAILABILITY_LIMITED", "AVAILABILITY_LIMITED",
@@ -678,10 +845,20 @@ __all__ = [
"AVAILABILITY_NOT_OPEN", "AVAILABILITY_NOT_OPEN",
"AVAILABILITY_NO_STOCK", "AVAILABILITY_NO_STOCK",
"AVAILABILITY_UNKNOWN", "AVAILABILITY_UNKNOWN",
"OFFER_STATE_ACTIVE",
"OFFER_STATE_BEFORE",
"OFFER_STATE_EXPIRED",
"OFFER_STATE_NOT_OFFERED",
"OFFER_STATE_UNKNOWN",
"STOCK_STATE_IN_STOCK",
"STOCK_STATE_OUT_OF_STOCK",
"STOCK_STATE_UNKNOWN",
"GoodsAssessment", "GoodsAssessment",
"account_capability_counts", "account_capability_counts",
"allocation_availability",
"capability_ttl_seconds", "capability_ttl_seconds",
"classify_goods_item", "classify_goods_item",
"classify_goods_item_assessment",
"classify_goods_items", "classify_goods_items",
"exchange_gate_for_availability", "exchange_gate_for_availability",
"goods_time_window", "goods_time_window",
@@ -387,6 +387,28 @@ def account_platform_status(
} }
fresh_available = int(commodities.get(AVAILABILITY_AVAILABLE, {}).get("fresh", 0)) fresh_available = int(commodities.get(AVAILABILITY_AVAILABLE, {}).get("fresh", 0))
fresh_limited = int(commodities.get(AVAILABILITY_LIMITED, {}).get("fresh", 0)) fresh_limited = int(commodities.get(AVAILABILITY_LIMITED, {}).get("fresh", 0))
eligibility_rows = (
db.query(
AccountCommodityState.account_eligibility,
func.count(AccountCommodityState.id),
func.sum(
case(
(AccountCommodityState.valid_until > moment, 1),
else_=0,
)
),
)
.filter(AccountCommodityState.platform == "douyu")
.group_by(AccountCommodityState.account_eligibility)
.all()
)
eligibility = {
str(state): {
"total": int(total or 0),
"fresh": int(fresh or 0),
}
for state, total, fresh in eligibility_rows
}
inventories = evaluate_supply_targets(db, now=moment) inventories = evaluate_supply_targets(db, now=moment)
supply_targets: list[dict[str, Any]] = [] supply_targets: list[dict[str, Any]] = []
@@ -529,6 +551,8 @@ def account_platform_status(
"sync_domains": sync_domains, "sync_domains": sync_domains,
"commodities": { "commodities": {
"by_availability": commodities, "by_availability": commodities,
"by_account_eligibility": eligibility,
"fresh_eligible": int(eligibility.get("eligible", {}).get("fresh", 0)),
"fresh_available": fresh_available, "fresh_available": fresh_available,
"fresh_limited": fresh_limited, "fresh_limited": fresh_limited,
}, },
+13 -35
View File
@@ -14,8 +14,9 @@ from ..models import (
User, User,
) )
from .account_capability_service import ( from .account_capability_service import (
AVAILABILITY_AVAILABLE, ACCOUNT_ELIGIBILITY_ELIGIBLE,
AVAILABILITY_NOT_OPEN, OFFER_STATE_ACTIVE,
OFFER_STATE_BEFORE,
) )
from .account_lifecycle import MANUAL_STATES from .account_lifecycle import MANUAL_STATES
@@ -101,45 +102,22 @@ def fresh_ck_cutoff(now: datetime) -> datetime:
return now - timedelta(seconds=CK_FRESH_SECONDS) return now - timedelta(seconds=CK_FRESH_SECONDS)
def fresh_available_state_filter( def fresh_eligible_state_filter(
now: datetime, now: datetime,
*, *,
allow_not_open: bool = False, allow_before_open: bool = False,
): ):
allowed = ( allowed_offer_states = (
(AVAILABILITY_AVAILABLE, AVAILABILITY_NOT_OPEN) (OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)
if allow_not_open if allow_before_open
else (AVAILABILITY_AVAILABLE,) else (OFFER_STATE_ACTIVE,)
)
available_window = and_(
AccountCommodityState.availability == AVAILABILITY_AVAILABLE,
or_(
AccountCommodityState.available_from.is_(None),
AccountCommodityState.available_from <= now,
),
or_(
AccountCommodityState.available_until.is_(None),
AccountCommodityState.available_until >= now,
),
)
if not allow_not_open:
return and_(
AccountCommodityState.availability.in_(allowed),
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
available_window,
)
not_open_window = and_(
AccountCommodityState.availability == AVAILABILITY_NOT_OPEN,
or_(
AccountCommodityState.available_until.is_(None),
AccountCommodityState.available_until >= now,
),
) )
return and_( return and_(
AccountCommodityState.account_eligibility
== ACCOUNT_ELIGIBILITY_ELIGIBLE,
AccountCommodityState.offer_state.in_(allowed_offer_states),
AccountCommodityState.valid_until.isnot(None), AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now, AccountCommodityState.valid_until > now,
or_(available_window, not_open_window),
) )
@@ -152,8 +130,8 @@ __all__ = [
"assigned_to_pool_filter", "assigned_to_pool_filter",
"automatable_account_filter", "automatable_account_filter",
"cookie_present_filter", "cookie_present_filter",
"fresh_available_state_filter",
"fresh_ck_cutoff", "fresh_ck_cutoff",
"fresh_eligible_state_filter",
"pool_owner_ids", "pool_owner_ids",
"role_change_ready_filter", "role_change_ready_filter",
"valid_ck_filter", "valid_ck_filter",
@@ -22,8 +22,8 @@ from .account_query_filters import (
assigned_to_pool_filter, assigned_to_pool_filter,
automatable_account_filter, automatable_account_filter,
cookie_present_filter, cookie_present_filter,
fresh_available_state_filter,
fresh_ck_cutoff, fresh_ck_cutoff,
fresh_eligible_state_filter,
role_change_ready_filter, role_change_ready_filter,
valid_ck_filter, valid_ck_filter,
) )
@@ -128,8 +128,8 @@ def _allocatable_filter(now: datetime):
) )
def _fresh_available_filter(now: datetime): def _fresh_eligible_filter(now: datetime):
return fresh_available_state_filter(now) return fresh_eligible_state_filter(now, allow_before_open=True)
def _commodity_query( def _commodity_query(
@@ -230,7 +230,7 @@ def _global_inventory_totals(
base_filter, base_filter,
AccountCommodityState.platform == platform, AccountCommodityState.platform == platform,
AccountCommodityState.scope == scope, AccountCommodityState.scope == scope,
_fresh_available_filter(now), _fresh_eligible_filter(now),
) )
.group_by(value_class) .group_by(value_class)
.all() .all()
@@ -297,7 +297,7 @@ def evaluate_supply_target(
if target.commodity_id: if target.commodity_id:
base = _commodity_query(db, now=moment, target=target) base = _commodity_query(db, now=moment, target=target)
covered = base.count() covered = base.count()
available_query = base.filter(_fresh_available_filter(moment)) available_query = base.filter(_fresh_eligible_filter(moment))
available = available_query.count() available = available_query.count()
allocatable = available_query.filter(_allocatable_filter(moment)).count() allocatable = available_query.filter(_allocatable_filter(moment)).count()
else: else:
+2 -2
View File
@@ -62,7 +62,7 @@ def serialize_goods(raw: Mapping[str, Any]) -> dict[str, Any]:
"mark": mark, "mark": mark,
"count": _to_int(_first_value(raw, "count")), "count": _to_int(_first_value(raw, "count")),
"elite_limited": _to_int(_first_value(raw, "eliteLimited")), "elite_limited": _to_int(_first_value(raw, "eliteLimited")),
"is_limited": bool(mark) or open_status == 0, "is_limited": str(status_value or "") == "1",
"raw": _json_safe(dict(raw)), "raw": _json_safe(dict(raw)),
} }
@@ -86,7 +86,7 @@ def serialize_snapshot(row: DouyuGoodsSnapshot) -> dict[str, Any]:
"mark": mark, "mark": mark,
"count": _to_int(_first_value(raw, "count")), "count": _to_int(_first_value(raw, "count")),
"elite_limited": _to_int(_first_value(raw, "eliteLimited")), "elite_limited": _to_int(_first_value(raw, "eliteLimited")),
"is_limited": bool(mark) or open_status == 0, "is_limited": str(row.status or "") == "1",
"raw": raw, "raw": raw,
} }
@@ -19,9 +19,7 @@ from ...models import (
AccountEvent, AccountEvent,
AccountLease, AccountLease,
) )
from ..account_capability_service import ( from ..account_capability_service import OFFER_STATE_ACTIVE
AVAILABILITY_AVAILABLE,
)
from ..account_events_service import ( from ..account_events_service import (
CATEGORY_OPS, CATEGORY_OPS,
EVENT_LEASE_ACQUIRED, EVENT_LEASE_ACQUIRED,
@@ -34,7 +32,7 @@ from ..account_query_filters import (
assigned_to_pool_filter, assigned_to_pool_filter,
automatable_account_filter, automatable_account_filter,
cookie_present_filter, cookie_present_filter,
fresh_available_state_filter, fresh_eligible_state_filter,
role_change_ready_filter, role_change_ready_filter,
valid_ck_filter, valid_ck_filter,
) )
@@ -238,16 +236,16 @@ def _capability_candidate_query(
scope: str = "elite", scope: str = "elite",
limit: int = 20, limit: int = 20,
now: datetime | None = None, now: datetime | None = None,
allow_not_open: bool = False, allow_before_open: bool = False,
): ):
commodity = commodity_id.strip() commodity = commodity_id.strip()
if not commodity: if not commodity:
return None return None
moment = _now(now) moment = _now(now)
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS) since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
availability_filter = fresh_available_state_filter( eligibility_filter = fresh_eligible_state_filter(
moment, moment,
allow_not_open=allow_not_open, allow_before_open=allow_before_open,
) )
return ( return (
db.query(Account, AccountCommodityState) db.query(Account, AccountCommodityState)
@@ -259,7 +257,7 @@ def _capability_candidate_query(
AccountCommodityState.platform == "douyu", AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope, AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity, AccountCommodityState.commodity_id == commodity,
availability_filter, eligibility_filter,
or_( or_(
AccountCommodityState.last_exchange_at.is_(None), AccountCommodityState.last_exchange_at.is_(None),
AccountCommodityState.last_exchange_at < since, AccountCommodityState.last_exchange_at < since,
@@ -274,7 +272,7 @@ def _capability_candidate_query(
) )
.order_by( .order_by(
case( case(
(AccountCommodityState.availability == AVAILABILITY_AVAILABLE, 0), (AccountCommodityState.offer_state == OFFER_STATE_ACTIVE, 0),
else_=1, else_=1,
), ),
case((Account.ck_check_status == "valid", 0), else_=1), case((Account.ck_check_status == "valid", 0), else_=1),
@@ -300,7 +298,7 @@ def capability_candidate_rows(
scope: str = "elite", scope: str = "elite",
limit: int = 20, limit: int = 20,
now: datetime | None = None, now: datetime | None = None,
allow_not_open: bool = False, allow_before_open: bool = False,
) -> list[CapabilityCandidate]: ) -> list[CapabilityCandidate]:
"""读取账号与能力快照;只访问本地数据库,不触发官网请求。""" """读取账号与能力快照;只访问本地数据库,不触发官网请求。"""
query = _capability_candidate_query( query = _capability_candidate_query(
@@ -310,7 +308,7 @@ def capability_candidate_rows(
scope=scope, scope=scope,
limit=limit, limit=limit,
now=now, now=now,
allow_not_open=allow_not_open, allow_before_open=allow_before_open,
) )
if query is None: if query is None:
return [] return []
@@ -328,7 +326,7 @@ def capability_candidate_accounts(
scope: str = "elite", scope: str = "elite",
limit: int = 20, limit: int = 20,
now: datetime | None = None, now: datetime | None = None,
allow_not_open: bool = False, allow_before_open: bool = False,
) -> list[Account]: ) -> list[Account]:
"""从新鲜的商品能力索引读取候选账号,不产生外部请求。""" """从新鲜的商品能力索引读取候选账号,不产生外部请求。"""
return [ return [
@@ -340,7 +338,7 @@ def capability_candidate_accounts(
scope=scope, scope=scope,
limit=limit, limit=limit,
now=now, now=now,
allow_not_open=allow_not_open, allow_before_open=allow_before_open,
) )
] ]
@@ -37,11 +37,17 @@ from ..account_binding import (
pending_binding_role_from_result, pending_binding_role_from_result,
) )
from ..account_capability_service import ( from ..account_capability_service import (
ACCOUNT_ELIGIBILITY_LIMITED,
ACCOUNT_ELIGIBILITY_UNKNOWN,
AVAILABILITY_AVAILABLE, AVAILABILITY_AVAILABLE,
AVAILABILITY_LIMITED, AVAILABILITY_LIMITED,
AVAILABILITY_NO_STOCK,
AVAILABILITY_NOT_OFFERED, AVAILABILITY_NOT_OFFERED,
AVAILABILITY_NOT_OPEN, AVAILABILITY_NOT_OPEN,
OFFER_STATE_BEFORE,
OFFER_STATE_NOT_OFFERED,
OFFER_STATE_UNKNOWN,
STOCK_STATE_UNKNOWN,
allocation_availability,
classify_goods_items, classify_goods_items,
exchange_gate_for_availability, exchange_gate_for_availability,
record_account_commodity_state, record_account_commodity_state,
@@ -1365,6 +1371,27 @@ def _task_out(
include_qr: bool = False, include_qr: bool = False,
include_exchange_task: bool = False, include_exchange_task: bool = False,
) -> dict[str, Any]: ) -> dict[str, Any]:
mapping = (
db.query(PlatformCommodityMapping)
.filter(PlatformCommodityMapping.id == task.commodity_mapping_id)
.first()
if task.commodity_mapping_id
else None
)
goods = (
db.query(DouyuGoodsSnapshot)
.filter(DouyuGoodsSnapshot.commodity_id == task.commodity_id)
.order_by(DouyuGoodsSnapshot.id.desc())
.first()
if task.commodity_id
else None
)
goods_name = (
str(getattr(mapping, "goods_name", "") or "")
or str(getattr(goods, "name", "") or "")
or task.sku_name
or task.internal_sku_key
)
account = ( account = (
db.query(Account).filter(Account.id == task.account_id).first() db.query(Account).filter(Account.id == task.account_id).first()
if task.account_id if task.account_id
@@ -1435,6 +1462,7 @@ def _task_out(
"scope": task.scope, "scope": task.scope,
"commodityMappingId": task.commodity_mapping_id, "commodityMappingId": task.commodity_mapping_id,
"commodityId": task.commodity_id, "commodityId": task.commodity_id,
"goodsName": goods_name,
"requiredPoints": task.required_points, "requiredPoints": task.required_points,
"saleMode": sale_mode, "saleMode": sale_mode,
"campaignKey": task.campaign_key, "campaignKey": task.campaign_key,
@@ -1974,6 +2002,7 @@ def _reapply_mapping_tasks(
detail={ detail={
"mappingId": row.id, "mappingId": row.id,
"commodityId": row.commodity_id, "commodityId": row.commodity_id,
"goodsName": row.goods_name,
"saleMode": row.sale_mode, "saleMode": row.sale_mode,
"campaignKey": row.campaign_key, "campaignKey": row.campaign_key,
"enabled": row.enabled, "enabled": row.enabled,
@@ -2296,7 +2325,22 @@ def _cached_capability_state(
"""把新鲜本地能力快照转换成统一的履约状态,不访问斗鱼官网。""" """把新鲜本地能力快照转换成统一的履约状态,不访问斗鱼官网。"""
account = candidate.account account = candidate.account
state = candidate.state state = candidate.state
reason = str(state.blocking_reason or "") availability = allocation_availability(
state.account_eligibility,
state.offer_state,
)
if availability == AVAILABILITY_AVAILABLE:
reason = ""
elif availability == AVAILABILITY_LIMITED:
reason = "该账号已达此商品兑换上限"
elif availability == AVAILABILITY_NOT_OPEN:
reason = (
f"限时兑换未开始,开始于 {state.available_from.isoformat()}"
if state.available_from
else "活动尚未开放兑换"
)
else:
reason = str(state.blocking_reason or "")
return DouyuLiveAccountState( return DouyuLiveAccountState(
account_id=int(account.id), account_id=int(account.id),
account_name=account.nickname or account.username or f"#{account.id}", account_name=account.nickname or account.username or f"#{account.id}",
@@ -2307,7 +2351,7 @@ def _cached_capability_state(
points=account.points, points=account.points,
limited_ids=frozenset(), limited_ids=frozenset(),
role_change_available_at=account.role_change_available_at, role_change_available_at=account.role_change_available_at,
commodity_availability={commodity_id: state.availability}, commodity_availability={commodity_id: availability},
commodity_blocking_reasons=( commodity_blocking_reasons=(
{commodity_id: reason} if reason else {} {commodity_id: reason} if reason else {}
), ),
@@ -2321,8 +2365,23 @@ def _capability_availability_counts(
scope: str, scope: str,
now: datetime, now: datetime,
) -> dict[str, int]: ) -> dict[str, int]:
rows = ( base = db.query(AccountCommodityState).filter(
db.query(AccountCommodityState.availability, func.count(AccountCommodityState.id)) AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
)
eligibility_rows = (
base.with_entities(
AccountCommodityState.account_eligibility,
func.count(AccountCommodityState.id),
)
.group_by(AccountCommodityState.account_eligibility)
.all()
)
offer_rows = (
db.query(AccountCommodityState.offer_state, func.count(AccountCommodityState.id))
.filter( .filter(
AccountCommodityState.platform == TARGET_PLATFORM, AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope, AccountCommodityState.scope == scope,
@@ -2330,10 +2389,29 @@ def _capability_availability_counts(
AccountCommodityState.valid_until.isnot(None), AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now, AccountCommodityState.valid_until > now,
) )
.group_by(AccountCommodityState.availability) .group_by(AccountCommodityState.offer_state)
.all() .all()
) )
return {str(availability): int(count or 0) for availability, count in rows} stock_rows = (
db.query(AccountCommodityState.stock_state, func.count(AccountCommodityState.id))
.filter(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
)
.group_by(AccountCommodityState.stock_state)
.all()
)
return {
**{
f"eligibility:{key}": int(count or 0)
for key, count in eligibility_rows
},
**{f"offer:{key}": int(count or 0) for key, count in offer_rows},
**{f"stock:{key}": int(count or 0) for key, count in stock_rows},
}
def _local_allocation_retry_at( def _local_allocation_retry_at(
@@ -2356,7 +2434,7 @@ def _local_allocation_retry_at(
AccountCommodityState.platform == TARGET_PLATFORM, AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == (task.scope or SCOPE_ELITE), AccountCommodityState.scope == (task.scope or SCOPE_ELITE),
AccountCommodityState.commodity_id == task.commodity_id, AccountCommodityState.commodity_id == task.commodity_id,
AccountCommodityState.availability == AVAILABILITY_NOT_OPEN, AccountCommodityState.offer_state == OFFER_STATE_BEFORE,
AccountCommodityState.available_from.isnot(None), AccountCommodityState.available_from.isnot(None),
AccountCommodityState.available_from > now, AccountCommodityState.available_from > now,
) )
@@ -2364,11 +2442,11 @@ def _local_allocation_retry_at(
) )
if next_open_at is not None: if next_open_at is not None:
return next_open_at + timedelta(seconds=5), "commodity_not_open" return next_open_at + timedelta(seconds=5), "commodity_not_open"
if availability_counts.get(AVAILABILITY_NOT_OPEN): if availability_counts.get(f"offer:{OFFER_STATE_BEFORE}"):
return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "commodity_not_open" return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "commodity_not_open"
if availability_counts.get(AVAILABILITY_NO_STOCK):
return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "commodity_no_stock"
if availability_counts: if availability_counts:
if availability_counts.get("eligibility:eligible"):
return now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS), "lease_conflict"
return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "no_eligible_account" return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "no_eligible_account"
return now + timedelta(seconds=LOCAL_CACHE_MISS_RETRY_SECONDS), "capability_cache_miss" return now + timedelta(seconds=LOCAL_CACHE_MISS_RETRY_SECONDS), "capability_cache_miss"
@@ -2465,7 +2543,7 @@ def _allocate_task_from_capability(
commodity_id=task.commodity_id, commodity_id=task.commodity_id,
scope=task.scope or SCOPE_ELITE, scope=task.scope or SCOPE_ELITE,
now=moment, now=moment,
allow_not_open=is_presale, allow_before_open=is_presale,
) )
recent_exchange_ids: set[int] = set() recent_exchange_ids: set[int] = set()
if capability_candidates: if capability_candidates:
@@ -2577,12 +2655,9 @@ def _allocate_task_from_capability(
if retry_reason == "commodity_not_open": if retry_reason == "commodity_not_open":
task.issue_code = "commodity_not_open" task.issue_code = "commodity_not_open"
task.last_error = "该商品尚未到开放时间,已按开放时间安排重新选号" task.last_error = "该商品尚未到开放时间,已按开放时间安排重新选号"
elif retry_reason == "commodity_no_stock":
task.issue_code = "commodity_no_stock"
task.last_error = "本地能力池显示该商品当前无库存,稍后自动重试"
elif retry_reason == "capability_cache_miss": elif retry_reason == "capability_cache_miss":
task.issue_code = "capability_cache_miss" task.issue_code = "capability_cache_miss"
task.last_error = "暂无该商品的新鲜能力快照,等待后台补货刷新" task.last_error = "暂无该商品的新鲜账号兑换资格,等待后台刷新"
elif retry_reason == "lease_conflict": elif retry_reason == "lease_conflict":
task.issue_code = "account_lease_conflict" task.issue_code = "account_lease_conflict"
task.last_error = "已找到候选账号,但刚被其他任务占用" task.last_error = "已找到候选账号,但刚被其他任务占用"
@@ -3541,15 +3616,35 @@ def refresh_exchange_eligibility(
assessment = assessments.get(task.commodity_id) assessment = assessments.get(task.commodity_id)
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale" is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
if task.commodity_id in limited_ids: if task.commodity_id in limited_ids:
account_eligibility = ACCOUNT_ELIGIBILITY_LIMITED
offer_state = assessment.offer_state if assessment else OFFER_STATE_UNKNOWN
stock_state = assessment.stock_state if assessment else STOCK_STATE_UNKNOWN
availability = AVAILABILITY_LIMITED availability = AVAILABILITY_LIMITED
commodity_message = "该账号已达到此商品兑换上限" commodity_message = "该账号已达到此商品兑换上限"
elif assessments and assessment is None: elif assessments and assessment is None:
account_eligibility = ACCOUNT_ELIGIBILITY_UNKNOWN
offer_state = OFFER_STATE_NOT_OFFERED
stock_state = STOCK_STATE_UNKNOWN
availability = AVAILABILITY_NOT_OFFERED availability = AVAILABILITY_NOT_OFFERED
commodity_message = "官方商品列表本次未返回该商品,可能已下架" commodity_message = "官方商品列表本次未返回该商品,可能已下架"
elif assessment is not None and assessment.availability != AVAILABILITY_AVAILABLE: elif assessment is not None and assessment.availability != AVAILABILITY_AVAILABLE:
account_eligibility = assessment.account_eligibility
offer_state = assessment.offer_state
stock_state = assessment.stock_state
availability = assessment.availability availability = assessment.availability
commodity_message = assessment.blocking_reason commodity_message = assessment.blocking_reason
else: else:
account_eligibility = (
assessment.account_eligibility
if assessment is not None
else ACCOUNT_ELIGIBILITY_UNKNOWN
)
offer_state = (
assessment.offer_state if assessment is not None else OFFER_STATE_UNKNOWN
)
stock_state = (
assessment.stock_state if assessment is not None else STOCK_STATE_UNKNOWN
)
availability = AVAILABILITY_AVAILABLE availability = AVAILABILITY_AVAILABLE
commodity_message = "" commodity_message = ""
@@ -3579,6 +3674,12 @@ def refresh_exchange_eligibility(
account, account,
commodity_id=task.commodity_id, commodity_id=task.commodity_id,
availability=availability, availability=availability,
account_eligibility=account_eligibility,
offer_state=offer_state,
stock_state=stock_state,
stock_count=assessment.stock_count if assessment is not None else None,
store_status=assessment.store_status if assessment is not None else None,
open_status=assessment.open_status if assessment is not None else None,
blocking_reason=commodity_message, blocking_reason=commodity_message,
raw_status=( raw_status=(
assessment.raw_status assessment.raw_status
@@ -3601,6 +3702,9 @@ def refresh_exchange_eligibility(
"commodity_id": task.commodity_id, "commodity_id": task.commodity_id,
"exchange_status": task.exchange_status, "exchange_status": task.exchange_status,
"limited": task.commodity_id in limited_ids, "limited": task.commodity_id in limited_ids,
"account_eligibility": account_eligibility,
"offer_state": offer_state,
"stock_state": stock_state,
"availability": availability, "availability": availability,
"issue_code": task.issue_code, "issue_code": task.issue_code,
"points": account.points, "points": account.points,
+4 -1
View File
@@ -115,7 +115,10 @@ export const accountApi = {
exchangeRecords: (id: number) => exchangeRecords: (id: number) =>
api.get<AccountExchangeRecords, AccountExchangeRecords>(`/accounts/${id}/exchange-records`), api.get<AccountExchangeRecords, AccountExchangeRecords>(`/accounts/${id}/exchange-records`),
// 账号 × 商品当前能力索引(查询快照,带最后确认时间) // 账号 × 商品当前能力索引(查询快照,带最后确认时间)
commodities: (id: number, params?: { scope?: string; availability?: string; limit?: number }) => commodities: (
id: number,
params?: { scope?: string; availability?: string; eligibility?: string; limit?: number },
) =>
api.get<AccountCommodityStates, AccountCommodityStates>(`/accounts/${id}/commodities`, { params }), api.get<AccountCommodityStates, AccountCommodityStates>(`/accounts/${id}/commodities`, { params }),
// 时间线(倒序分页),event_type 为空表示全部 // 时间线(倒序分页),event_type 为空表示全部
events: ( events: (
+9
View File
@@ -212,6 +212,12 @@ export interface AccountCommodityState {
commodity_id: string; commodity_id: string;
commodity_name: string; commodity_name: string;
scope: string; scope: string;
account_eligibility: 'eligible' | 'limited' | 'unknown';
offer_state: 'before' | 'active' | 'expired' | 'not_offered' | 'unknown';
stock_state: 'in_stock' | 'out_of_stock' | 'unknown';
stock_count: number | null;
store_status: number | null;
open_status: number | null;
availability: AccountCommodityAvailability; availability: AccountCommodityAvailability;
blocking_reason: string; blocking_reason: string;
raw_status: string; raw_status: string;
@@ -897,6 +903,8 @@ export interface DouyuAccountPlatformStatus {
sync_domains: Record<string, Record<string, number>>; sync_domains: Record<string, Record<string, number>>;
commodities: { commodities: {
by_availability: Record<string, { total: number; fresh: number }>; by_availability: Record<string, { total: number; fresh: number }>;
by_account_eligibility: Record<string, { total: number; fresh: number }>;
fresh_eligible: number;
fresh_available: number; fresh_available: number;
fresh_limited: number; fresh_limited: number;
}; };
@@ -2444,6 +2452,7 @@ export interface PlatformFulfillmentTask {
scope: string; scope: string;
commodityMappingId: number | null; commodityMappingId: number | null;
commodityId: string; commodityId: string;
goodsName: string;
requiredPoints: number | null; requiredPoints: number | null;
saleMode: 'presale' | 'direct' | 'manual' | 'unknown'; saleMode: 'presale' | 'direct' | 'manual' | 'unknown';
campaignKey: string; campaignKey: string;
+54 -2
View File
@@ -138,6 +138,34 @@ function commodityStateTag(value: string) {
return <Tag color={state.color}>{state.label}</Tag>; return <Tag color={state.color}>{state.label}</Tag>;
} }
const ACCOUNT_ELIGIBILITY: Record<string, { label: string; color: string }> = {
eligible: { label: '账号可兑换', color: 'green' },
limited: { label: '账号已限兑', color: 'orange' },
unknown: { label: '资格待确认', color: 'default' },
};
const OFFER_STATE: Record<string, { label: string; color: string }> = {
before: { label: '活动未开始', color: 'gold' },
active: { label: '活动进行中', color: 'blue' },
expired: { label: '活动已结束', color: 'default' },
not_offered: { label: '商品未上架', color: 'default' },
unknown: { label: '时间待确认', color: 'default' },
};
const STOCK_STATE: Record<string, { label: string; color: string }> = {
in_stock: { label: '有库存', color: 'green' },
out_of_stock: { label: '官方无库存', color: 'default' },
unknown: { label: '库存未知', color: 'default' },
};
function splitStateTag(
value: string,
states: Record<string, { label: string; color: string }>,
) {
const state = states[value] ?? Object.values(states).at(-1);
return <Tag color={state?.color}>{state?.label || value}</Tag>;
}
/** 金额展示:充值为正(绿色 ¥),兑换消耗为负(红色积分)。 */ /** 金额展示:充值为正(绿色 ¥),兑换消耗为负(红色积分)。 */
function amountText(item: AccountEventItem) { function amountText(item: AccountEventItem) {
if (item.amount === null || item.amount === undefined) return null; if (item.amount === null || item.amount === undefined) return null;
@@ -352,9 +380,33 @@ export default function AccountDetailPage() {
), ),
}, },
{ {
title: '当前能力', title: '账号兑换资格',
dataIndex: 'account_eligibility',
width: 130,
render: (value: string) => splitStateTag(value, ACCOUNT_ELIGIBILITY),
},
{
title: '活动状态',
dataIndex: 'offer_state',
width: 120,
render: (value: string) => splitStateTag(value, OFFER_STATE),
},
{
title: '官方库存(仅参考)',
width: 150,
render: (_value, row) => (
<Space direction="vertical" size={0}>
{splitStateTag(row.stock_state, STOCK_STATE)}
<Text type="secondary" style={{ fontSize: 12 }}>
数量 {row.stock_count ?? '-'}
</Text>
</Space>
),
},
{
title: '兑换执行',
dataIndex: 'availability', dataIndex: 'availability',
width: 110, width: 120,
render: (value: string) => commodityStateTag(value), render: (value: string) => commodityStateTag(value),
}, },
{ {
@@ -266,7 +266,7 @@ function eventDescription(event: { eventType: string; detail: Record<string, unk
return reasons.length ? `${base};后续需要:${reasons.join('、')}` : `${base};可直接兑换`; return reasons.length ? `${base};后续需要:${reasons.join('、')}` : `${base};可直接兑换`;
} }
if (event.eventType === 'mapping_updated') { if (event.eventType === 'mapping_updated') {
return `斗鱼商品 ${String(detail.commodityId || '-')},映射${detail.enabled === false ? '已停用' : '已启用'}`; return `斗鱼商品 ${String(detail.goodsName || detail.commodityId || '-')},映射${detail.enabled === false ? '已停用' : '已启用'}`;
} }
if (event.eventType === 'exchange_eligibility_checked') { if (event.eventType === 'exchange_eligibility_checked') {
return `兑换状态:${exchangeStatusLabel(String(detail.exchangeStatus || ''))};限兑商品 ${String(detail.limitedCount ?? 0)} 个`; return `兑换状态:${exchangeStatusLabel(String(detail.exchangeStatus || ''))};限兑商品 ${String(detail.limitedCount ?? 0)} 个`;
@@ -1060,7 +1060,9 @@ export default function PlatformFulfillmentPage() {
width: 230, width: 230,
render: (_, task) => ( render: (_, task) => (
<Space direction="vertical" size={2}> <Space direction="vertical" size={2}>
<Text>{task.commodityId || '未映射'}</Text> <Text ellipsis title={task.commodityId}>
{task.goodsName || task.skuName || task.internalSkuKey || '未映射'}
</Text>
<Text type="secondary">{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}</Text> <Text type="secondary">{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}</Text>
</Space> </Space>
), ),
@@ -1518,7 +1520,7 @@ export default function PlatformFulfillmentPage() {
{selected.internalSkuKey || '-'} {selected.internalSkuKey || '-'}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="斗鱼商品" span={2}> <Descriptions.Item label="斗鱼商品" span={2}>
{selected.commodityId || '未映射'} {selected.goodsName || selected.skuName || '未映射'}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="销售模式"> <Descriptions.Item label="销售模式">
{SALE_MODE_LABELS[selected.saleMode] || selected.saleMode} {SALE_MODE_LABELS[selected.saleMode] || selected.saleMode}