修复(履约与分配): 封堵工作台换绑、预售共号与分配中心越权占用
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
# 生产环境斗鱼账号重复绑定、重分配与发错排查报告(2026-11-27)
|
||||
|
||||
> 排查方式:仅对生产服务器(`121.199.24.149`)、生产日志(`/root/live-hub-py/logs/`)与生产 MySQL(`douyu_login`)执行**只读**查询与分析;未对生产环境做任何写入或状态变更。
|
||||
> 排查时间:2026-11-27 12:00 ~ 12:25(库内时间字段为 UTC,下文保留库内原始时间戳并按需要注明)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 排查问题与总体结论
|
||||
|
||||
针对反馈的问题场景:
|
||||
> “一个斗鱼号之前绑定过并发货成功,后面同一客户又下一单(新订单仍绑定该斗鱼号);在达到可换绑时间后,系统又将该账号分配给其他客户绑定,导致皮肤发错。”
|
||||
|
||||
排查生产库全量数据(`platform_fulfillment_tasks` 10,629 条、`platform_fulfillment_events` 91,974 条、`douyu_external_orders` 7,273 条、`account_leases` 11,669 条、`account_events` 638,535 条)与运行日志后,结论如下:
|
||||
|
||||
1. **自动履约系统(`platform_fulfillment_tasks`)中,因“同一客户复购仍绑旧号 -> 到期后被系统自动重分给他人 -> 发错皮肤”的案例为 `0` 例。**
|
||||
- 自动履约在分配新单时并不会自动复用客户上一单的旧斗鱼号,而是分配新号并在扫码阶段命中 7 天角色锁拦截转人工(`customer_role_bound_elsewhere` 共 181 单)。
|
||||
- 已绑定任务在完成前因租约释放/过期导致原账号被重分给其他任务的共有 72 单,但均未在原租约期间发货,且原订单均已解绑重选了其他账号。
|
||||
2. **预售台账 + 工作台人工换绑/兑换链路(`douyu_external_orders` + `douyu_tasks`)中,发现 `3` 例明确发错皮肤、`1` 例状态错位标为已完成、`1` 例失败单角色冲突未解绑,以及自动履约中 `1` 例下单角色与实际扫码角色完全不一致已发货(共 `6` 例高危/异常单,另有 `6` 例 1~2 字错别字或未发货错填)。**
|
||||
|
||||
---
|
||||
|
||||
## 2. 预售台账链路:账号未完结前被换绑他人导致发错/冲突(核心问题)
|
||||
|
||||
以下案例均为:**账号先存在一笔未完结的预售单(2026-11-07 / 11-14 创建,等待 11-26 开售),达到 7 天换绑期后,被操作员在斗鱼工作台直接发起换绑给其他客户并兑换;到 2026-11-26 批量开售兑换时,预售皮肤实际发给了新绑定的客户,且原预售单被标记为 `done`。**
|
||||
|
||||
### 2.1 已明确发错皮肤(`3` 例)
|
||||
|
||||
| `collab_id` | 订单号 | 店铺 | 归属客服 | `account_id` / 斗鱼账号 | 原订单目标角色 | 原订单商品与创建时间 | 工作台换绑过程(`douyu_tasks` & 日志) | 实际发错情况(`account_events` & 台账结果) |
|
||||
|---:|---|---|---|---|---|---|---|---|
|
||||
| **1421** | `2631101772508905` | 佳佳 | `kf_20` | `25954` / `用户3283438769` | **`明明不爱他`** | `雪国幻梦服装礼包`<br>`2026-11-07 15:37:07` | 2026-11-22 02:01:41 由 `created_by=47` 通过工作台任务 `551591` 换绑为 **`课程团队`**,02:04:45 兑换 `套装-花羊椰椰`(`551639`) | `2026-11-26 10:25:05` `official_sync` 同步到兑换 **`雪国幻梦服装礼包`**(`account_events.id=704404`),`11:03:31` 台账 `1421` 置为 `done`(`succeeded_at`),实际发给了 **`课程团队`** |
|
||||
| **1379** | `2631102091044738` | 佳佳 | `kf_20` | `25958` / `用户6495091779` | **`失去会恩熙`** | `雪国幻梦服装礼包`<br>`2026-11-07 12:52:18` | 2026-11-22 01:24:12 由 `created_by=47` 通过工作台任务 `550904` 换绑为 **`誮丶丶`**,01:26:11 兑换 `套装-魔性柴柴`(`550924`) | `2026-11-26 10:25:44` `official_sync` 同步到兑换 **`雪国幻梦服装礼包`**(`account_events.id=704377`),`11:03:30` 台账 `1379` 置为 `done`(`succeeded_at`),实际发给了 **`誮丶丶`** |
|
||||
| **1378** | `2631102163676775` | 佳佳 | `kf_20` | `25966` / `用户6661963858` | **`千寻千生`** | `雪国幻梦服装礼包`<br>`2026-11-07 12:36:16` | 2026-11-21 14:49:09 由 `created_by=47` 通过工作台任务 `547041` 换绑为 **`厌见雨`**(日志 `role_changed`),14:50:15 兑换 `套装-花羊椰椰`(`547050`);11-23 又新建 `collab_id=5201` 给 `厌见雨` 兑换 `红熊茄茄` | `2026-11-26 10:25:17` `official_sync` 同步到兑换 **`雪国幻梦服装礼包`**(`account_events.id=704263`),`11:03:30` 台账 `1378` 置为 `done`(`succeeded_at`),实际发给了 **`厌见雨`** |
|
||||
|
||||
> 根因说明:`collab:25954`、`collab:25958`、`collab:25966` 在 `2026-11-19 08:46:33` 均已有 `migration_backfill` 的活跃 `douyu_collab` 租约,仅拦住了自动履约选号,未拦住工作台人工直接发起换绑(`platform_task_id IS NULL`)。
|
||||
|
||||
### 2.2 账号已被换绑但原单仍标记 `done` / 停留在 `failed`(`2` 例)
|
||||
|
||||
| 类型 | `collab_id` | 订单号 | 店铺 / 客服 | `account_id` / 斗鱼账号 | 原订单目标角色 | 异常经过与当前状态 |
|
||||
|---|---:|---|---|---|---|---|
|
||||
| **状态错位标为 `done`** | **1983** | `2631801843194845` | 佳佳 / `kf_10` | `360` / `花凌若别离739` | **`约定呗`** | `2026-11-14 10:47:20` 创建(`雪国幻梦服装礼包`);`2026-11-21 06:02:58` 发生 `bind_ok` 换绑为 **`我亲泥`**(`collab_id=4006`,后置 `void`);`2026-11-26 11:19:37` `1983` 被标记 `done`,但 `account_events` 中无 2026-11 月该账号的 `exchange` 记录,需核对实际去向。 |
|
||||
| **失败单角色冲突** | **1319** | `2631101603363861` | 向日葵 / `kf_19` | `26261` / `用户2765408065` | **`野渡川・枪下客`** | `2026-11-07 10:07:36` 创建(`冥河战士大礼包`),当前仍为 `failed`;`2026-11-16 03:07:23` 工作台任务 `446641`(`created_by=39`)将账号换绑为 **`系梅ル`**(`collab_id=2245`),且 `2026-11-26 10:23 / 10:32` 已为 `系梅ル` 兑换 `雪国幻梦服装礼包` 与 `冥河战士大礼包`。 |
|
||||
|
||||
### 2.3 预售台账同号多单时间线补充统计
|
||||
|
||||
- `douyu_external_orders` 中共有 **378** 组「同账号 + 同 `bind_game_role`」多单记录,其中 **42** 个账号后续也出现过其他角色订单。
|
||||
- 除上述 `25954`、`25958`、`25966`、`360`、`26261` 外,其余多单案例(如 `22889`、`23130`、`23455`、`23921`、`23935`、`24090` 等)均是在原角色订单全部 `done` 并释放租约之后,才被后续订单换绑使用。
|
||||
- 另有 `collab_id=4996`(`account_id=1276` / `玉山间`,订单 `2632702005700293`,`source_task_id=5832`):`5832` 同步预售台账时记录历史快照角色 `唉琪琪sad`,随后 `5832` 绑定 `萌嘟烦恼` 并在 `2026-11-23` 正常兑换 `套装-红熊茄茄` 完成(与预售单快照字段不一致,但实际绑定和发货对象为 `萌嘟烦恼`)。
|
||||
- 另有 `collab_id=2743`、`2740`(`account_id=4150`,目标角色 `心被掏出千次`)处于 `failed` 状态且当前 `accounts.game_name` 为空。
|
||||
|
||||
---
|
||||
|
||||
## 3. 自动履约系统(`platform_fulfillment_tasks`)错误与异常统计
|
||||
|
||||
### 3.1 客户下单角色名与账号当前实际绑定角色不一致(`8` 例)
|
||||
|
||||
> 说明:在已确认绑定(`binding_status='bound'`)的履约单中,共排查出 **8** 单 `customer_role_name` 与 `accounts.game_name` 不一致(已完成 **2** 单、待发 **6** 单):
|
||||
|
||||
| 类别 | `pf_id` | 订单号 | 店铺 | `account_id` / 斗鱼账号 | 商品 | 客户填写角色 | 实际账号绑定角色 | 订单状态 |
|
||||
|---|---:|---|---|---|---|---|---|---|
|
||||
| **已完成 · 角色完全不同** | **8631** | `2632901858530670` | 西瓜游戏交易店 | `9679` / `用户0665735761` | `AUG-魔性柴柴` | **`黑小风穿飞你`** | **`佳姐爱宇哥`** | `completed` / `manual_done`<br>(11-25 10:15 绑定,10:17 兑换完成) |
|
||||
| **未发货 · 角色完全不同** | **4296** | `2632601842546999` | 佳佳游戏交易店 | `23674` / `用户4277989031` | `套装-兔兔白日梦` | **`和平精英`** | **`龸屳`** | `bound` / `eligible`(11-22 绑定,**未完成**) |
|
||||
| 已完成 · 1 字差异 | **8878** | `2632902092385128` | 小鱼儿游戏服务店 | `10201` / `用户4490945635` | `套装-花羊椰椰` | `你怎么总骗窝` | `你怎么总骗我窝` | `completed` / `manual_done` |
|
||||
| 未发货 · 符号/1字差异 | **8809** | `6931825185337671309` | 向日葵游戏交易店 | `14033` / `用户6271281097` | `冥河战士大礼包` | `念旧` | `゜念旧゚・` | `bound` / `waiting_release` |
|
||||
| 未发货 · 符号差异 | **8778** | `2632901792540919` | 小鱼儿游戏服务店 | `4056` / `用户0894954004` | `套装-花羊椰椰` | `郁刃°` | `郁刃゜` | `bound` / `waiting_release` |
|
||||
| 未发货 · 1 字差异 | **8735** | `6919948475597860138` | 向日葵游戏交易店 | `9548` / `用户0880235253` | `怪诞乔克服装礼包` | `祈愿天真无邪` | `祁愿天真无邪` | `bound` / `waiting_release` |
|
||||
| 未发货 · 1 字差异 | **8696** | `2632902167352184` | 向日葵游戏交易店 | `8906` / `用户106265215` | `冥河战士大礼包` | `云南巍山一枝花` | `云南魏山一枝花` | `bound` / `waiting_release` |
|
||||
| 未发货 · 空格差异 | **8648** | `2632902029589659` | 西瓜游戏交易店 | `8482` / `用户73016038` | `雪国幻梦服装礼包` | `云彩面包 ovo` | `云彩面包ovo` | `bound` / `waiting_release` |
|
||||
|
||||
### 3.2 绑定与租约历史异常事件汇总(`platform_fulfillment_events` & `account_leases`)
|
||||
|
||||
| 异常/保护事件类型 | 影响任务数 | 事件条数 | 处置与现状 |
|
||||
|---|---:|---:|---|
|
||||
| `binding_role_locked_elsewhere`(7 天角色锁拦截) | **181** | **199** | 系统拦下并转人工;当前仍处于 `issue_code='customer_role_bound_elsewhere'` 的共 **164** 单(涉及 **108** 个游戏角色)。 |
|
||||
| `binding_account_locked_elsewhere`(7 天账号锁拦截) | **25** | **29** | 账号 7 天内已绑过其他角色时拦下转人工。 |
|
||||
| `binding_false_confirmation_reverted`(误把历史绑定当本单确认) | **163** | **163** | 历史修复任务 `reconcile` 已回退(如 `4621`、`7328` 回退后均重新正确绑定并发货)。 |
|
||||
| `binding_reused_existing_pair`(同对复用) | **57** | **125** | 其中 **16** 单因复用角色与客户填写目标不一致被 `_revert_false_same_pair_reuse` 自动回退(`binding_false_reuse_reverted`);如 `9878` 等纠偏后正确发货。 |
|
||||
| 已绑定任务未完成前租约失效且原账号被新任务占用 | **72** | - | 含 `ttl_expired`、`manual_release`、`allocation_replaced`、`platform_fulfillment_manual`;核对结果显示这 72 单均**未**在旧租约期兑换且当前均已指向新账号,未造成错发。 |
|
||||
| 历史回填前跨系统占号(`account_allocated` 命中已有未完结 `collab` 单) | - | - | 集中发生在 `2026-11-19 08:46` `migration_backfill` 之前;11-19 之后未再出现自动选号抢占未完结预售账号并导致发错的新增案例。 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 建议人工核对清单
|
||||
|
||||
1. **立即核对并联系补救(预售台账发错风险)**:
|
||||
- `2631101772508905`(`collab_id=1421`,`account_id=25954`,原角色 `明明不爱他` -> 实际发给 `课程团队`)
|
||||
- `2631102091044738`(`collab_id=1379`,`account_id=25958`,原角色 `失去会恩熙` -> 实际发给 `誮丶丶`)
|
||||
- `2631102163676775`(`collab_id=1378`,`account_id=25966`,原角色 `千寻千生` -> 实际发给 `厌见雨`)
|
||||
- `2631801843194845`(`collab_id=1983`,`account_id=360`,原角色 `约定呗` -> 账号已绑 `我亲泥` 且无 11 月兑换流水,确认是否误标 `done`)
|
||||
2. **核对处理状态冲突单**:
|
||||
- `2631101603363861`(`collab_id=1319`,`account_id=26261`,目标 `野渡川・枪下客` 仍在 `failed`,账号已归 `系梅ル`)
|
||||
- `2632901858530670`(`pf_id=8631`,`account_id=9679`,填写 `黑小风穿飞你` vs 实绑并发货给 `佳姐爱宇哥`)
|
||||
- `2632601842546999`(`pf_id=4296`,`account_id=23674`,填写 `和平精英` vs 实绑 `龸屳`,尚未兑换)
|
||||
3. **系统侧防呆方向(供后续排期参考)**:
|
||||
- 斗鱼工作台直接发起 `get_bind_qr` / `confirm_bind` 时,如账号当前持有 `douyu_collab` 或 `platform_fulfillment` 活跃租约且未绑定对应任务,应强校验/拦截,防止人工操作绕过租约把预售号换绑给他人。
|
||||
@@ -21,8 +21,10 @@ from tests.support.db import get_test_engine, make_test_session
|
||||
from web.backend.models import (
|
||||
Account,
|
||||
AccountCommodityState,
|
||||
AccountEvent,
|
||||
AccountLease,
|
||||
DouyuExternalOrder,
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from web.backend.routers.accounts import (
|
||||
@@ -476,6 +478,107 @@ class TestAssignmentPools(_Base):
|
||||
assert exc_info.value.status_code == 400
|
||||
assert "已停用" in exc_info.value.detail
|
||||
|
||||
def test_assign_and_dispatch_block_fulfillment_and_collab_accounts(self):
|
||||
free = self.make_account("assign-guard-free")
|
||||
leased = self.make_account("assign-guard-leased")
|
||||
collab = self.make_account("assign-guard-collab")
|
||||
pf_task_acc = self.make_account("assign-guard-pf-task")
|
||||
self.session.add_all(
|
||||
[
|
||||
AccountLease(
|
||||
account_id=leased.id,
|
||||
holder_user_id=self.admin.id,
|
||||
purpose="platform_fulfillment",
|
||||
status="active",
|
||||
),
|
||||
DouyuExternalOrder(
|
||||
order_no="ASSIGN-GUARD-COLLAB-1",
|
||||
account_id=collab.id,
|
||||
account_username=collab.username,
|
||||
status="to_recharge",
|
||||
),
|
||||
PlatformFulfillmentTask(
|
||||
source_order_id="PF-ORDER-ASSIGN-GUARD-1",
|
||||
source_order_item_id="PF-ITEM-ASSIGN-GUARD-1",
|
||||
platform_order_id="PF-NO-ASSIGN-GUARD-1",
|
||||
shop_id="shop1",
|
||||
account_id=pf_task_acc.id,
|
||||
execution_status="allocated",
|
||||
binding_status="not_started",
|
||||
),
|
||||
]
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
for blocked in (leased, collab, pf_task_acc):
|
||||
with pytest.raises(HTTPException) as single_exc:
|
||||
assign_account(
|
||||
blocked.id,
|
||||
AccountAssign(assigned_to=self.support.id),
|
||||
db=self.session,
|
||||
current=self.admin,
|
||||
)
|
||||
assert single_exc.value.status_code == 409
|
||||
|
||||
with pytest.raises(HTTPException) as batch_exc:
|
||||
batch_assign_accounts(
|
||||
BatchAssign(account_ids=[blocked.id], assigned_to=self.support.id),
|
||||
db=self.session,
|
||||
current=self.admin,
|
||||
)
|
||||
assert batch_exc.value.status_code == 409
|
||||
|
||||
# 即使前端/调用方传 occupancy="" 或 "no_lease",dispatch 也必须兜底跳过被占用账号
|
||||
dispatched = dispatch_assignments(
|
||||
AssignmentDispatch(
|
||||
assigned_to=self.support.id,
|
||||
quantity=10,
|
||||
occupancy="",
|
||||
),
|
||||
db=self.session,
|
||||
current=self.admin,
|
||||
)
|
||||
assert dispatched["account_ids"] == [free.id]
|
||||
self.session.refresh(leased)
|
||||
self.session.refresh(collab)
|
||||
self.session.refresh(pf_task_acc)
|
||||
assert leased.assigned_to is None
|
||||
assert collab.assigned_to is None
|
||||
assert pf_task_acc.assigned_to is None
|
||||
|
||||
# 退回/取消分配仍允许在账号被占用后执行
|
||||
free.assigned_to = self.support.id
|
||||
self.session.commit()
|
||||
unassigned = batch_assign_accounts(
|
||||
BatchAssign(account_ids=[free.id], assigned_to=None),
|
||||
db=self.session,
|
||||
current=self.admin,
|
||||
)
|
||||
assert unassigned["count"] == 1
|
||||
|
||||
def test_bind_change_available_respects_recent_7_day_bind_ok_lock(self):
|
||||
locked = self.make_account(
|
||||
"pool-recent-bind-ok",
|
||||
role_bind_status="bound",
|
||||
role_change_available_at=self.now - timedelta(hours=1),
|
||||
ck_expected_expires_at=self.now + timedelta(days=3),
|
||||
)
|
||||
self.session.add(
|
||||
AccountEvent(
|
||||
account_id=locked.id,
|
||||
event_type="bind_ok",
|
||||
category="business",
|
||||
title="最近绑定",
|
||||
subject_type="elite_role",
|
||||
subject_key="近期角色",
|
||||
occurred_at=self.now - timedelta(days=2),
|
||||
)
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
assert self.names(bind_change_status="available") == []
|
||||
assert self.names(bind_change_status="cooldown") == [locked.username]
|
||||
|
||||
|
||||
class TestAllMatchingAssign(_Base):
|
||||
def test_assigns_every_matching_unassigned(self):
|
||||
|
||||
@@ -2474,3 +2474,169 @@ class TestDouyuCollabOrders:
|
||||
assert "/api/douyu/collab-gifts/{gift_id}" in paths
|
||||
assert "put" in paths["/api/douyu/collab-gifts/{gift_id}"]
|
||||
assert "delete" in paths["/api/douyu/collab-gifts/{gift_id}"]
|
||||
|
||||
def test_same_account_collab_orders_reject_conflicting_roles(self):
|
||||
first = collab.create_order(
|
||||
self.session,
|
||||
self.admin,
|
||||
order_no="DY-ROLE-CONFLICT-1",
|
||||
shop="店铺A",
|
||||
account_username="douyu-account-a",
|
||||
gift_name="礼包A",
|
||||
required_points=100,
|
||||
home_images=["collab/home-conflict-1.png"],
|
||||
client=FakeClient(),
|
||||
)
|
||||
assert first.bind_game_role == "角色A"
|
||||
|
||||
class RoleBClient(FakeClient):
|
||||
def bind_info(self, **_):
|
||||
return {
|
||||
"is_bound_account": True,
|
||||
"is_bound_role": True,
|
||||
"is_bound_act": True,
|
||||
"role_name": "角色B",
|
||||
"area_name": "微信",
|
||||
"plat_name": "苹果(iOS)",
|
||||
"nickname": "角色B昵称",
|
||||
}
|
||||
|
||||
with pytest.raises(collab.CollabError) as create_exc:
|
||||
collab.create_order(
|
||||
self.session,
|
||||
self.admin,
|
||||
order_no="DY-ROLE-CONFLICT-2",
|
||||
shop="店铺A",
|
||||
account_username="douyu-account-a",
|
||||
gift_name="礼包A",
|
||||
required_points=100,
|
||||
home_images=["collab/home-conflict-2.png"],
|
||||
client=RoleBClient(),
|
||||
)
|
||||
assert create_exc.value.code == "collab_role_conflict"
|
||||
assert create_exc.value.status_code == 409
|
||||
|
||||
draft = collab.create_order(
|
||||
self.session,
|
||||
self.admin,
|
||||
order_no="DY-ROLE-CONFLICT-DRAFT",
|
||||
shop="店铺A",
|
||||
gift_name="礼包A",
|
||||
required_points=100,
|
||||
draft=True,
|
||||
)
|
||||
with pytest.raises(collab.CollabError) as switch_exc:
|
||||
collab.set_account(
|
||||
self.session,
|
||||
self.admin,
|
||||
draft,
|
||||
"douyu-account-a",
|
||||
client=RoleBClient(),
|
||||
)
|
||||
assert switch_exc.value.code == "collab_role_conflict"
|
||||
|
||||
other_account = Account(
|
||||
username="douyu-account-b",
|
||||
password="password",
|
||||
email="b@example.com",
|
||||
email_password="mail-password",
|
||||
cookie="acf_uid=101; acf_nickname=testb",
|
||||
)
|
||||
self.session.add(other_account)
|
||||
self.session.commit()
|
||||
voided = collab.create_order(
|
||||
self.session,
|
||||
self.admin,
|
||||
order_no="DY-ROLE-CONFLICT-VOID",
|
||||
shop="店铺A",
|
||||
account_username="douyu-account-b",
|
||||
gift_name="礼包A",
|
||||
required_points=100,
|
||||
home_images=["collab/home-conflict-void.png"],
|
||||
client=RoleBClient(),
|
||||
)
|
||||
collab.set_status(
|
||||
self.session,
|
||||
self.admin,
|
||||
voided,
|
||||
status=collab.STATUS_VOID,
|
||||
reason="作废再测试串号恢复",
|
||||
)
|
||||
voided.account_id = self.account.id
|
||||
voided.account_username = self.account.username
|
||||
self.session.commit()
|
||||
with pytest.raises(collab.CollabError) as restore_exc:
|
||||
collab.set_status(
|
||||
self.session,
|
||||
self.admin,
|
||||
voided,
|
||||
status=collab.STATUS_INCOMPLETE,
|
||||
reason="尝试跨角色恢复",
|
||||
)
|
||||
assert restore_exc.value.code == "collab_role_conflict"
|
||||
|
||||
def test_query_activity_and_set_status_done_reject_role_mismatch(self):
|
||||
order = collab.create_order(
|
||||
self.session,
|
||||
self.admin,
|
||||
order_no="DY-ROLE-MISMATCH-DONE",
|
||||
shop="店铺A",
|
||||
account_username="douyu-account-a",
|
||||
gift_name="礼包A",
|
||||
required_points=100,
|
||||
home_images=["collab/home-role-mismatch.png"],
|
||||
client=FakeClient(),
|
||||
)
|
||||
for status in (collab.STATUS_RECHARGED, collab.STATUS_SCRIPTED):
|
||||
collab.set_status(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
status=status,
|
||||
reason="准备测试角色校验",
|
||||
)
|
||||
|
||||
self.account.game_name = "被别人绑走的角色"
|
||||
self.session.commit()
|
||||
|
||||
with pytest.raises(collab.CollabError) as manual_exc:
|
||||
collab.set_status(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
status=collab.STATUS_DONE,
|
||||
reason="误标成功",
|
||||
)
|
||||
assert manual_exc.value.code == "role_mismatch"
|
||||
assert manual_exc.value.status_code == 409
|
||||
|
||||
result = collab.query_activity(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
client=FakeClient(records=[exchange_record()]),
|
||||
)
|
||||
assert result["verdict"] == collab.VERDICT_FAILED
|
||||
assert "禁止自动标记成功" in result["message"]
|
||||
assert result["order"].status == collab.STATUS_ROLE_ERROR
|
||||
assert result["order"].done_at is None
|
||||
lease = (
|
||||
self.session.query(AccountLease)
|
||||
.filter(
|
||||
AccountLease.account_id == self.account.id,
|
||||
AccountLease.status == "active",
|
||||
)
|
||||
.one()
|
||||
)
|
||||
assert lease.purpose == collab.LEASE_PURPOSE_DOUYU_COLLAB
|
||||
|
||||
with pytest.raises(collab.CollabError) as rollback_exc:
|
||||
collab.set_status(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
status=collab.STATUS_DONE,
|
||||
rollback=True,
|
||||
reason="角色不一致时也不能强行完成",
|
||||
)
|
||||
assert rollback_exc.value.code == "role_mismatch"
|
||||
|
||||
@@ -3,7 +3,13 @@
|
||||
from unittest.mock import Mock
|
||||
|
||||
from tests.support.db import get_test_engine, make_test_session
|
||||
from web.backend.models import Account, DouyuGoodsSnapshot, DouyuTask, User
|
||||
from web.backend.models import (
|
||||
Account,
|
||||
AccountLease,
|
||||
DouyuGoodsSnapshot,
|
||||
DouyuTask,
|
||||
User,
|
||||
)
|
||||
from web.backend.services.douyu_runner import DouyuBatchRunner
|
||||
|
||||
|
||||
@@ -105,3 +111,62 @@ class TestDouyuWritePathContracts:
|
||||
assert task.result["exchange_id"] == "11098933"
|
||||
client.pay_exchange_order.assert_called_once()
|
||||
client.create_exchange_order.assert_not_called()
|
||||
|
||||
def test_runner_blocks_unlinked_bind_and_exchange_when_account_leased(self):
|
||||
self.session.add(
|
||||
AccountLease(
|
||||
account_id=self.account.id,
|
||||
holder_user_id=self.user.id,
|
||||
scope="elite",
|
||||
purpose="platform_fulfillment",
|
||||
batch_id="pf:999",
|
||||
status="active",
|
||||
)
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
qr_task = self._task("get_bind_qr", {})
|
||||
qr_runner = self._runner("get_bind_qr")
|
||||
qr_client = Mock()
|
||||
qr_runner._client = Mock(return_value=qr_client)
|
||||
qr_runner._execute_get_bind_qr(
|
||||
self.session,
|
||||
qr_task,
|
||||
self.account,
|
||||
"acf_uid=100",
|
||||
{"bind_act_alias": "20260120QYOOB"},
|
||||
)
|
||||
self.session.refresh(qr_task)
|
||||
assert qr_task.status == "failed"
|
||||
assert "平台履约" in qr_task.message
|
||||
qr_client.bind_info.assert_not_called()
|
||||
|
||||
confirm_task = self._task("confirm_bind", {})
|
||||
confirm_runner = self._runner("confirm_bind")
|
||||
confirm_client = Mock()
|
||||
confirm_runner._client = Mock(return_value=confirm_client)
|
||||
confirm_runner._execute_confirm_bind(
|
||||
self.session,
|
||||
confirm_task,
|
||||
self.account,
|
||||
"acf_uid=100",
|
||||
{"confirm_act_alias": "20260120QYOOB"},
|
||||
)
|
||||
self.session.refresh(confirm_task)
|
||||
assert confirm_task.status == "failed"
|
||||
confirm_client.confirm_bind.assert_not_called()
|
||||
|
||||
exchange_task = self._task("exchange_goods", {"commodity_id": "bag10"})
|
||||
exchange_runner = self._runner("exchange_goods")
|
||||
exchange_client = Mock()
|
||||
exchange_runner._client = Mock(return_value=exchange_client)
|
||||
exchange_runner._execute_exchange_goods(
|
||||
self.session,
|
||||
exchange_task,
|
||||
self.account,
|
||||
"acf_uid=100",
|
||||
{"manual_id": "G4KA4Qnz4LDp7", "rid": "9263298"},
|
||||
)
|
||||
self.session.refresh(exchange_task)
|
||||
assert exchange_task.status == "failed"
|
||||
exchange_client.create_exchange_order.assert_not_called()
|
||||
|
||||
@@ -6306,3 +6306,100 @@ class TestBindingAndCompletion(_Base):
|
||||
.count()
|
||||
== 1
|
||||
)
|
||||
|
||||
def test_workbench_blocks_rebind_and_goods_on_bound_or_collab_accounts(self):
|
||||
"""已绑定履约单与预售台账占用期间,禁止工作台无归属绑码/换绑,且履约期禁兑换。"""
|
||||
from web.backend.models import DouyuExternalOrder
|
||||
from web.backend.services.douyu_service import (
|
||||
DouyuLeaseConflictError,
|
||||
create_douyu_planned_tasks,
|
||||
)
|
||||
|
||||
task = self._allocated()
|
||||
task.binding_status = "bound"
|
||||
task.execution_status = "bound"
|
||||
self.session.commit()
|
||||
|
||||
for blocked_type in (
|
||||
"get_bind_qr",
|
||||
"confirm_bind",
|
||||
"lock_goods",
|
||||
"pay_locked_order",
|
||||
"exchange_goods",
|
||||
):
|
||||
with pytest.raises(DouyuLeaseConflictError):
|
||||
create_douyu_planned_tasks(
|
||||
self.session,
|
||||
[task.account_id],
|
||||
blocked_type,
|
||||
"elite",
|
||||
self.admin_id,
|
||||
enqueue_execution=False,
|
||||
)
|
||||
|
||||
# 只读查询仍允许从工作台发起
|
||||
_, query_count = create_douyu_planned_tasks(
|
||||
self.session,
|
||||
[task.account_id],
|
||||
"query_points",
|
||||
"elite",
|
||||
self.admin_id,
|
||||
enqueue_execution=False,
|
||||
)
|
||||
assert query_count == 1
|
||||
|
||||
collab_account = Account(
|
||||
username="collab-occupied-acc",
|
||||
password="pw",
|
||||
email="collab@example.com",
|
||||
email_password="epw",
|
||||
cookie="acf_uid=9090; acf_nickname=collab",
|
||||
status="active",
|
||||
)
|
||||
self.session.add(collab_account)
|
||||
self.session.flush()
|
||||
collab_lease = AccountLease(
|
||||
account_id=collab_account.id,
|
||||
holder_user_id=self.admin_id,
|
||||
scope="elite",
|
||||
purpose="douyu_collab",
|
||||
batch_id=f"collab:{collab_account.id}",
|
||||
status="active",
|
||||
)
|
||||
self.session.add(collab_lease)
|
||||
self.session.add(
|
||||
DouyuExternalOrder(
|
||||
order_no="DY-WORKBENCH-BLOCK-1",
|
||||
shop="店铺A",
|
||||
owner_id=self.admin_id,
|
||||
account_id=collab_account.id,
|
||||
account_username=collab_account.username,
|
||||
gift_name="礼包A",
|
||||
bind_game_role="原绑定角色",
|
||||
status="to_recharge",
|
||||
created_by=self.admin_id,
|
||||
)
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
for blocked_bind_type in ("get_bind_qr", "confirm_bind"):
|
||||
with pytest.raises(DouyuLeaseConflictError):
|
||||
create_douyu_planned_tasks(
|
||||
self.session,
|
||||
[collab_account.id],
|
||||
blocked_bind_type,
|
||||
"elite",
|
||||
self.admin_id,
|
||||
enqueue_execution=False,
|
||||
)
|
||||
|
||||
# 预售台账账号仍可由人工从工作台查积分或做兑换,不被绑定拦截误伤
|
||||
_, collab_query_count = create_douyu_planned_tasks(
|
||||
self.session,
|
||||
[collab_account.id],
|
||||
"query_points",
|
||||
"elite",
|
||||
self.admin_id,
|
||||
enqueue_execution=False,
|
||||
)
|
||||
assert collab_query_count == 1
|
||||
|
||||
@@ -20,6 +20,7 @@ from ..models import (
|
||||
AuditLog,
|
||||
DouyuExternalOrder,
|
||||
DouyuTask,
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from ..permissions import ROLE_LABELS, user_has_permission
|
||||
@@ -75,6 +76,8 @@ from ..services.account_query_filters import (
|
||||
ACTIVE_COLLAB_STATUSES,
|
||||
active_collab_order_exists,
|
||||
active_lease_exists,
|
||||
recent_elite_bind_lock_exists,
|
||||
role_change_ready_filter,
|
||||
)
|
||||
from ..services.account_service import parse_and_build_accounts
|
||||
from ..services.account_value import (
|
||||
@@ -184,6 +187,28 @@ def _visible_accounts_query(db: Session, current: User):
|
||||
raise HTTPException(status_code=403, detail="无权查看账号")
|
||||
|
||||
|
||||
def _active_platform_fulfillment_exists():
|
||||
return (
|
||||
select(PlatformFulfillmentTask.id)
|
||||
.where(
|
||||
PlatformFulfillmentTask.account_id == Account.id,
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
("completed", "cancelled")
|
||||
),
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
|
||||
|
||||
def _unoccupied_for_assign_filter():
|
||||
"""可分配给客服的安全兜底:无活动租约、无活跃预售单、无未结束履约任务。"""
|
||||
return and_(
|
||||
~active_lease_exists(),
|
||||
~active_collab_order_exists(),
|
||||
~_active_platform_fulfillment_exists(),
|
||||
)
|
||||
|
||||
|
||||
def _assignable_account_filter():
|
||||
"""分配池口径:当前 Cookie 必须有一次不早于它的有效 CK 检测。"""
|
||||
return and_(
|
||||
@@ -430,15 +455,15 @@ def _filter_accounts_query(
|
||||
if bind_change_value == "available":
|
||||
query = query.filter(
|
||||
Account.role_bind_status == "bound",
|
||||
or_(
|
||||
Account.role_change_available_at.is_(None),
|
||||
Account.role_change_available_at <= now,
|
||||
),
|
||||
role_change_ready_filter(now),
|
||||
)
|
||||
elif bind_change_value == "cooldown":
|
||||
query = query.filter(
|
||||
Account.role_bind_status == "bound",
|
||||
Account.role_change_available_at > now,
|
||||
or_(
|
||||
Account.role_change_available_at > now,
|
||||
recent_elite_bind_lock_exists(now),
|
||||
),
|
||||
)
|
||||
elif bind_change_value == "unbound":
|
||||
query = query.filter(Account.role_bind_status == "unbound")
|
||||
@@ -465,14 +490,15 @@ def _filter_accounts_query(
|
||||
if occupancy_value:
|
||||
has_lease = active_lease_exists()
|
||||
in_collab = active_collab_order_exists()
|
||||
in_fulfillment = _active_platform_fulfillment_exists()
|
||||
if occupancy_value == "free":
|
||||
query = query.filter(~has_lease, ~in_collab)
|
||||
query = query.filter(~has_lease, ~in_collab, ~in_fulfillment)
|
||||
elif occupancy_value == "no_lease":
|
||||
query = query.filter(~has_lease)
|
||||
query = query.filter(~has_lease, ~in_fulfillment)
|
||||
elif occupancy_value == "no_collab":
|
||||
query = query.filter(~in_collab)
|
||||
elif occupancy_value == "leased":
|
||||
query = query.filter(has_lease)
|
||||
query = query.filter(or_(has_lease, in_fulfillment))
|
||||
elif occupancy_value == "collab":
|
||||
query = query.filter(in_collab)
|
||||
|
||||
@@ -1459,6 +1485,19 @@ def assign_account(
|
||||
status_code=400,
|
||||
detail="该账号尚未通过有效 CK 检测,无法分配",
|
||||
)
|
||||
is_free = (
|
||||
db.query(Account.id)
|
||||
.filter(
|
||||
Account.id == account_id,
|
||||
_unoccupied_for_assign_filter(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not is_free:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="该账号当前被履约订单、预售台账或活动租约占用,禁止分配给客服",
|
||||
)
|
||||
|
||||
if acc.assigned_to != req.assigned_to:
|
||||
acc.assigned_to = req.assigned_to
|
||||
@@ -1527,6 +1566,33 @@ def batch_assign_accounts(
|
||||
status_code=400,
|
||||
detail=f"以下账号尚未通过有效 CK 检测,无法分配:{name_list}{suffix}",
|
||||
)
|
||||
free_ids = {
|
||||
int(account_id)
|
||||
for (account_id,) in (
|
||||
db.query(Account.id)
|
||||
.filter(
|
||||
Account.id.in_(ids),
|
||||
_unoccupied_for_assign_filter(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
}
|
||||
occupied_ids = [account_id for account_id in ids if account_id not in free_ids]
|
||||
if occupied_ids:
|
||||
names = (
|
||||
db.query(Account.username)
|
||||
.filter(Account.id.in_(occupied_ids))
|
||||
.all()
|
||||
)
|
||||
name_list = ", ".join([n[0] for n in names[:5]])
|
||||
suffix = "..." if len(occupied_ids) > 5 else ""
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=(
|
||||
f"以下账号当前被履约订单、预售台账或活动租约占用,"
|
||||
f"禁止分配给客服:{name_list}{suffix}"
|
||||
),
|
||||
)
|
||||
|
||||
# 先取出账号对象(批量时间线要逐个写事件,光有 count 不够)。
|
||||
# 「撤回」只处理当前确实有归属的账号;显式勾选里混入未分配账号时,
|
||||
@@ -1612,6 +1678,7 @@ def dispatch_assignments(
|
||||
.filter(
|
||||
Account.assigned_to.is_(None),
|
||||
_assignable_account_filter(),
|
||||
_unoccupied_for_assign_filter(),
|
||||
)
|
||||
)
|
||||
if req.strategy == "points":
|
||||
@@ -1772,6 +1839,7 @@ def assignment_options(
|
||||
]
|
||||
has_lease = active_lease_exists()
|
||||
in_collab = active_collab_order_exists()
|
||||
in_fulfillment = _active_platform_fulfillment_exists()
|
||||
|
||||
def count_with(*filters) -> int:
|
||||
return int(
|
||||
@@ -1783,10 +1851,10 @@ def assignment_options(
|
||||
|
||||
occupancy = {
|
||||
"assignable": count_with(),
|
||||
"free": count_with(~has_lease, ~in_collab),
|
||||
"no_lease": count_with(~has_lease),
|
||||
"free": count_with(~has_lease, ~in_collab, ~in_fulfillment),
|
||||
"no_lease": count_with(~has_lease, ~in_fulfillment),
|
||||
"no_collab": count_with(~in_collab),
|
||||
"leased": count_with(has_lease),
|
||||
"leased": count_with(or_(has_lease, in_fulfillment)),
|
||||
"collab": count_with(in_collab),
|
||||
}
|
||||
presets = {
|
||||
@@ -1795,12 +1863,14 @@ def assignment_options(
|
||||
Account.points <= 0,
|
||||
~has_lease,
|
||||
~in_collab,
|
||||
~in_fulfillment,
|
||||
),
|
||||
"elite_points": count_with(
|
||||
Account.elite_opened.is_(True),
|
||||
Account.points > 0,
|
||||
~has_lease,
|
||||
~in_collab,
|
||||
~in_fulfillment,
|
||||
),
|
||||
"high_value": count_with(
|
||||
or_(
|
||||
@@ -1809,6 +1879,7 @@ def assignment_options(
|
||||
),
|
||||
~has_lease,
|
||||
~in_collab,
|
||||
~in_fulfillment,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -105,6 +105,7 @@ from ..services.douyu_service import (
|
||||
DOUYU_HANDBOOK_TASK_TYPES,
|
||||
SUPPORTED_DOUYU_TASK_TYPES,
|
||||
DouyuActivePaymentError,
|
||||
DouyuLeaseConflictError,
|
||||
DouyuTaskBackpressureError,
|
||||
apply_douyu_config_defaults,
|
||||
cleanup_orphan_douyu_tasks,
|
||||
@@ -1541,7 +1542,7 @@ def _prepare_task_batch(
|
||||
recharge_channel=recharge_channel,
|
||||
recharge_amount=recharge_amount,
|
||||
)
|
||||
except DouyuActivePaymentError as exc:
|
||||
except (DouyuActivePaymentError, DouyuLeaseConflictError) as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
except DouyuTaskBackpressureError as exc:
|
||||
raise HTTPException(
|
||||
|
||||
@@ -27,7 +27,14 @@ from datetime import UTC, datetime, timedelta
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import AccountLease, DouyuTask, PlatformFulfillmentTask
|
||||
from ..models import (
|
||||
Account,
|
||||
AccountLease,
|
||||
DouyuExternalOrder,
|
||||
DouyuTask,
|
||||
PlatformFulfillmentTask,
|
||||
)
|
||||
from .account_query_filters import ACTIVE_COLLAB_STATUSES
|
||||
|
||||
#: 允许把工作台任务挂到订单上的绑定阶段。已 bound / manual_required 的订单
|
||||
#: 不再接受自动归属,避免工作台的一次手工操作改写已完成订单。
|
||||
@@ -46,30 +53,59 @@ BINDING_LINKABLE_STATUSES = frozenset(
|
||||
#: 不在此列:查询只能证明账号当前状态,不能证明某个订单的绑定已经确认。
|
||||
BINDING_TASK_TYPES = frozenset({"get_bind_qr", "confirm_bind"})
|
||||
|
||||
#: 精英工作台会改写兑换资格或消耗积分的写操作任务类型。
|
||||
WORKBENCH_GOODS_MUTATION_TYPES = frozenset(
|
||||
{"lock_goods", "pay_locked_order", "exchange_goods"}
|
||||
)
|
||||
|
||||
#: 任务创建时间与租约起点的容差。两者由不同事务写入,允许几秒偏差;
|
||||
#: 不允许跨租约归属(上一个订单的任务不能算到下一张订单上)。
|
||||
LEASE_CLOCK_TOLERANCE = timedelta(seconds=5)
|
||||
|
||||
|
||||
def active_account_lease(
|
||||
db: Session,
|
||||
account_id: int,
|
||||
*,
|
||||
purpose: str | None = None,
|
||||
) -> AccountLease | None:
|
||||
"""账号当前生效且未过期的租约;可按 ``purpose`` 过滤。"""
|
||||
query = db.query(AccountLease).filter(
|
||||
AccountLease.account_id == int(account_id),
|
||||
AccountLease.status == "active",
|
||||
or_(
|
||||
AccountLease.expires_at.is_(None),
|
||||
AccountLease.expires_at > datetime.now(UTC),
|
||||
),
|
||||
)
|
||||
if purpose is not None:
|
||||
query = query.filter(AccountLease.purpose == purpose)
|
||||
return query.order_by(AccountLease.leased_at.desc(), AccountLease.id.desc()).first()
|
||||
|
||||
|
||||
def active_fulfillment_lease(
|
||||
db: Session,
|
||||
account_id: int,
|
||||
) -> AccountLease | None:
|
||||
"""账号当前生效的履约租约;没有则返回 ``None``。"""
|
||||
return (
|
||||
db.query(AccountLease)
|
||||
.filter(
|
||||
AccountLease.account_id == int(account_id),
|
||||
AccountLease.status == "active",
|
||||
AccountLease.purpose == "platform_fulfillment",
|
||||
or_(
|
||||
AccountLease.expires_at.is_(None),
|
||||
AccountLease.expires_at > datetime.now(UTC),
|
||||
),
|
||||
)
|
||||
.order_by(AccountLease.leased_at.desc(), AccountLease.id.desc())
|
||||
.first()
|
||||
return active_account_lease(db, account_id, purpose="platform_fulfillment")
|
||||
|
||||
|
||||
def active_collab_order_for_account(
|
||||
db: Session,
|
||||
account_id: int,
|
||||
*,
|
||||
exclude_order_id: int | None = None,
|
||||
) -> DouyuExternalOrder | None:
|
||||
"""账号当前未结束、未归档的预售台账订单。"""
|
||||
query = db.query(DouyuExternalOrder).filter(
|
||||
DouyuExternalOrder.account_id == int(account_id),
|
||||
DouyuExternalOrder.status.in_(ACTIVE_COLLAB_STATUSES),
|
||||
DouyuExternalOrder.archived_at.is_(None),
|
||||
)
|
||||
if exclude_order_id is not None:
|
||||
query = query.filter(DouyuExternalOrder.id != int(exclude_order_id))
|
||||
return query.order_by(DouyuExternalOrder.updated_at.desc()).first()
|
||||
|
||||
|
||||
def active_fulfillment_binding_task_id(
|
||||
@@ -149,10 +185,100 @@ def role_names_match(left: object, right: object) -> bool:
|
||||
return bool(left_key) and left_key == right_key
|
||||
|
||||
|
||||
def _account_display_label(account: Account) -> str:
|
||||
return (
|
||||
str(account.nickname or "").strip()
|
||||
or str(account.username or "").strip()
|
||||
or str(account.uid or "").strip()
|
||||
or f"#{account.id}"
|
||||
)
|
||||
|
||||
|
||||
def workbench_task_occupation_error(
|
||||
db: Session,
|
||||
account: Account,
|
||||
*,
|
||||
task_type: str,
|
||||
handbook_scope: str,
|
||||
platform_task_id: int | None,
|
||||
allow_auto_link: bool = False,
|
||||
) -> str | None:
|
||||
"""检查工作台无归属任务是否会误改已占用账号的角色或库存。
|
||||
|
||||
仅拦截未绑定 ``platform_task_id`` 的精英宝典写操作:
|
||||
- 绑码/换绑(``get_bind_qr`` / ``confirm_bind``):若未命中可自动归属的
|
||||
待绑定履约单,禁止在任意活动租约(平台履约、预售台账等)或活跃预售单期间执行;
|
||||
- 锁单/支付/兑换:账号处于平台履约租约期间,只能由履约订单带 ``platform_task_id`` 发起。
|
||||
"""
|
||||
if handbook_scope != "elite" or platform_task_id is not None:
|
||||
return None
|
||||
label = _account_display_label(account)
|
||||
lease = active_account_lease(db, account.id)
|
||||
|
||||
if task_type in BINDING_TASK_TYPES:
|
||||
if allow_auto_link and active_fulfillment_binding_task_id(db, account.id) is not None:
|
||||
return None
|
||||
if lease is not None:
|
||||
if lease.purpose == "platform_fulfillment":
|
||||
return (
|
||||
f"账号 {label} 当前有已绑定、人工处理中或已完成的平台履约订单"
|
||||
f"(批次 {lease.batch_id or '-'}),禁止从工作台发起绑定或换绑"
|
||||
)
|
||||
if lease.purpose == "douyu_collab":
|
||||
return (
|
||||
f"账号 {label} 当前由斗鱼预售台账占用,"
|
||||
"禁止从工作台发起绑定或换绑"
|
||||
)
|
||||
return (
|
||||
f"账号 {label} 当前已被业务租约占用({lease.purpose}),"
|
||||
"禁止从工作台发起绑定或换绑"
|
||||
)
|
||||
collab = active_collab_order_for_account(db, account.id)
|
||||
if collab is not None:
|
||||
return (
|
||||
f"账号 {label} 存在未完成的斗鱼预售台账订单({collab.order_no}),"
|
||||
"禁止从工作台发起绑定或换绑"
|
||||
)
|
||||
bound_fulfillment = (
|
||||
db.query(PlatformFulfillmentTask.id)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.account_id == int(account.id),
|
||||
PlatformFulfillmentTask.scope == "elite",
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
("completed", "cancelled")
|
||||
),
|
||||
PlatformFulfillmentTask.binding_status.notin_(
|
||||
BINDING_LINKABLE_STATUSES
|
||||
),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if bound_fulfillment is not None:
|
||||
return (
|
||||
f"账号 {label} 当前有关联的已绑定或待人工处理平台履约单(#{bound_fulfillment[0]}),"
|
||||
"禁止从工作台发起绑定或换绑"
|
||||
)
|
||||
return None
|
||||
|
||||
if (
|
||||
task_type in WORKBENCH_GOODS_MUTATION_TYPES
|
||||
and lease is not None
|
||||
and lease.purpose == "platform_fulfillment"
|
||||
):
|
||||
return (
|
||||
f"账号 {label} 当前由平台履约订单占用"
|
||||
f"(批次 {lease.batch_id or '-'}),请从履约订单内发起锁单或兑换"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BINDING_LINKABLE_STATUSES",
|
||||
"BINDING_TASK_TYPES",
|
||||
"LEASE_CLOCK_TOLERANCE",
|
||||
"WORKBENCH_GOODS_MUTATION_TYPES",
|
||||
"active_account_lease",
|
||||
"active_collab_order_for_account",
|
||||
"active_fulfillment_binding_task_id",
|
||||
"active_fulfillment_lease",
|
||||
"fulfillment_lease_for_task",
|
||||
@@ -160,4 +286,5 @@ __all__ = [
|
||||
"normalize_role_name",
|
||||
"role_names_match",
|
||||
"source_created_within_lease",
|
||||
"workbench_task_occupation_error",
|
||||
]
|
||||
|
||||
@@ -8,6 +8,7 @@ from typing import Any
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import (
|
||||
Account,
|
||||
AccountLease,
|
||||
DouyuExternalOrder,
|
||||
DouyuTask,
|
||||
@@ -21,11 +22,15 @@ from .account_events_service import (
|
||||
emit,
|
||||
)
|
||||
from .audit_service import record_audit
|
||||
from .binding_ownership import role_names_match
|
||||
from .douyu_collab_common import (
|
||||
COLLAB_LEASE_STATUSES,
|
||||
LEASE_PURPOSE_DOUYU_COLLAB,
|
||||
PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES,
|
||||
SOURCE_TYPE_PLATFORM_FULFILLMENT,
|
||||
STATUS_FAILED,
|
||||
STATUS_POINTS_ERROR,
|
||||
STATUS_ROLE_ERROR,
|
||||
CollabError,
|
||||
)
|
||||
from .platform_fulfillment.account_selector import (
|
||||
@@ -43,12 +48,12 @@ def _order_occupies_account(order: DouyuExternalOrder) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _active_collab_order(
|
||||
def _active_collab_orders(
|
||||
db: Session,
|
||||
account_id: int,
|
||||
*,
|
||||
exclude_order_id: int | None = None,
|
||||
) -> DouyuExternalOrder | None:
|
||||
) -> list[DouyuExternalOrder]:
|
||||
query = db.query(DouyuExternalOrder).filter(
|
||||
DouyuExternalOrder.account_id == int(account_id),
|
||||
DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES),
|
||||
@@ -56,7 +61,88 @@ def _active_collab_order(
|
||||
)
|
||||
if exclude_order_id is not None:
|
||||
query = query.filter(DouyuExternalOrder.id != int(exclude_order_id))
|
||||
return query.order_by(DouyuExternalOrder.updated_at.desc()).first()
|
||||
return query.order_by(DouyuExternalOrder.updated_at.desc()).all()
|
||||
|
||||
|
||||
def _active_collab_order(
|
||||
db: Session,
|
||||
account_id: int,
|
||||
*,
|
||||
exclude_order_id: int | None = None,
|
||||
) -> DouyuExternalOrder | None:
|
||||
orders = _active_collab_orders(
|
||||
db,
|
||||
account_id,
|
||||
exclude_order_id=exclude_order_id,
|
||||
)
|
||||
return orders[0] if orders else None
|
||||
|
||||
|
||||
def _collab_order_expected_role(
|
||||
db: Session,
|
||||
order: DouyuExternalOrder,
|
||||
*,
|
||||
incoming_role: str = "",
|
||||
) -> str:
|
||||
explicit = str(incoming_role or order.bind_game_role or "").strip()
|
||||
if explicit:
|
||||
return explicit
|
||||
if (
|
||||
order.source_type == SOURCE_TYPE_PLATFORM_FULFILLMENT
|
||||
and order.source_task_id
|
||||
):
|
||||
task = db.get(PlatformFulfillmentTask, int(order.source_task_id))
|
||||
if task is not None and task.customer_role_name:
|
||||
return str(task.customer_role_name or "").strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _assert_collab_account_role_compatible(
|
||||
db: Session,
|
||||
order: DouyuExternalOrder,
|
||||
target_account_id: int,
|
||||
*,
|
||||
incoming_role: str = "",
|
||||
) -> None:
|
||||
"""防止不同游戏角色/客户的预售单共享同一个斗鱼账号,或复用已换绑的账号。"""
|
||||
exclude_id = int(order.id) if order.id else None
|
||||
candidate_role = _collab_order_expected_role(
|
||||
db,
|
||||
order,
|
||||
incoming_role=incoming_role,
|
||||
)
|
||||
existing_orders = _active_collab_orders(
|
||||
db,
|
||||
target_account_id,
|
||||
exclude_order_id=exclude_id,
|
||||
)
|
||||
if candidate_role:
|
||||
for existing in existing_orders:
|
||||
existing_role = _collab_order_expected_role(db, existing)
|
||||
if existing_role and not role_names_match(existing_role, candidate_role):
|
||||
raise CollabError(
|
||||
f"该账号已有进行中的预售单 {existing.order_no}"
|
||||
f"(绑定角色:{existing_role}),与当前角色({candidate_role})"
|
||||
"不一致,禁止共用同一账号",
|
||||
status_code=409,
|
||||
code="collab_role_conflict",
|
||||
)
|
||||
if (
|
||||
not str(incoming_role or "").strip()
|
||||
and str(order.bind_game_role or "").strip()
|
||||
and str(order.status or "")
|
||||
not in {STATUS_FAILED, STATUS_POINTS_ERROR, STATUS_ROLE_ERROR}
|
||||
):
|
||||
account = db.get(Account, int(target_account_id))
|
||||
current_role = str(account.game_name or "").strip() if account else ""
|
||||
order_bound_role = str(order.bind_game_role or "").strip()
|
||||
if current_role and not role_names_match(current_role, order_bound_role):
|
||||
raise CollabError(
|
||||
f"账号当前绑定角色({current_role})与预售单绑定角色"
|
||||
f"({order_bound_role})不一致,禁止继续占用该账号",
|
||||
status_code=409,
|
||||
code="collab_role_conflict",
|
||||
)
|
||||
|
||||
|
||||
def _platform_lease_matches_source(
|
||||
@@ -256,6 +342,7 @@ def _ensure_order_account_lease(
|
||||
account_id: int | None = None,
|
||||
force_active: bool = False,
|
||||
takeover_platform_lease: bool = False,
|
||||
incoming_role: str = "",
|
||||
commit: bool = False,
|
||||
) -> AccountLease | None:
|
||||
target_account_id = int(account_id or order.account_id or 0)
|
||||
@@ -264,6 +351,13 @@ def _ensure_order_account_lease(
|
||||
if not force_active and not _order_occupies_account(order):
|
||||
return None
|
||||
|
||||
_assert_collab_account_role_compatible(
|
||||
db,
|
||||
order,
|
||||
target_account_id,
|
||||
incoming_role=incoming_role,
|
||||
)
|
||||
|
||||
lease = _lock_active_lease_for_account(db, target_account_id)
|
||||
if lease is not None:
|
||||
if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB:
|
||||
@@ -368,11 +462,20 @@ def _sync_order_lease(
|
||||
reason: str,
|
||||
force_active: bool = False,
|
||||
reuse_active_lease: bool = False,
|
||||
incoming_role: str = "",
|
||||
commit: bool = False,
|
||||
) -> AccountLease | None:
|
||||
if force_active or _order_occupies_account(order):
|
||||
if reuse_active_lease:
|
||||
lease = _lock_active_lease_for_account(db, int(order.account_id or 0))
|
||||
target_account_id = int(order.account_id or 0)
|
||||
if target_account_id:
|
||||
_assert_collab_account_role_compatible(
|
||||
db,
|
||||
order,
|
||||
target_account_id,
|
||||
incoming_role=incoming_role,
|
||||
)
|
||||
lease = _lock_active_lease_for_account(db, target_account_id)
|
||||
if lease is not None:
|
||||
if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB:
|
||||
return lease
|
||||
@@ -394,6 +497,7 @@ def _sync_order_lease(
|
||||
current,
|
||||
order,
|
||||
force_active=force_active,
|
||||
incoming_role=incoming_role,
|
||||
commit=commit,
|
||||
)
|
||||
_release_order_account_lease(
|
||||
|
||||
@@ -27,6 +27,7 @@ from core.douyu import DouyuActivityClient
|
||||
|
||||
from ..models import (
|
||||
Account,
|
||||
AccountEvent,
|
||||
AccountLease,
|
||||
AuditLog,
|
||||
DouyuCollabGift,
|
||||
@@ -52,6 +53,7 @@ from .account_query_filters import ACTIVE_COLLAB_STATUSES
|
||||
from .account_sync_runner import WORK_STOREHOME_SYNC
|
||||
from .account_work_queue import enqueue_account_work
|
||||
from .audit_service import record_account_action, record_audit
|
||||
from .binding_ownership import role_names_match
|
||||
from .business_events import record_account_query
|
||||
from .collab_common import (
|
||||
count_archived,
|
||||
@@ -1030,6 +1032,7 @@ def update_order(
|
||||
account_id=int(account.id),
|
||||
force_active=order.status in COLLAB_LEASE_STATUSES,
|
||||
takeover_platform_lease=takeover_platform_lease,
|
||||
incoming_role=_text(probe.get("bind_game_role")),
|
||||
)
|
||||
apply_probe_snapshot(
|
||||
db,
|
||||
@@ -1134,6 +1137,7 @@ def set_account(
|
||||
account_id=int(account.id),
|
||||
force_active=order.status in COLLAB_LEASE_STATUSES,
|
||||
takeover_platform_lease=takeover_platform_lease,
|
||||
incoming_role=_text(probe.get("bind_game_role")),
|
||||
)
|
||||
apply_probe_snapshot(
|
||||
db,
|
||||
@@ -1232,7 +1236,68 @@ def _status_audit_target(order: DouyuExternalOrder) -> str:
|
||||
return f"douyu_external_order:{order.id}"
|
||||
|
||||
|
||||
def _collab_order_role_mismatch_reason(
|
||||
db: Session,
|
||||
order: DouyuExternalOrder,
|
||||
account: Account | None = None,
|
||||
*,
|
||||
records: Sequence[Mapping[str, Any]] = (),
|
||||
) -> str | None:
|
||||
"""校验订单目标角色与账号当前实际绑定角色、兑换记录角色是否一致。"""
|
||||
expected = _text(order.bind_game_role)
|
||||
if not expected:
|
||||
return None
|
||||
acc = account or account_by_id(db, order.account_id) or account_by_username(
|
||||
db, order.account_username
|
||||
)
|
||||
if acc is not None:
|
||||
current_role = _text(acc.game_name)
|
||||
if current_role and not role_names_match(expected, current_role):
|
||||
return (
|
||||
f"账号当前绑定角色({current_role})"
|
||||
f"与订单目标角色({expected})不一致"
|
||||
)
|
||||
if str(acc.role_bind_status or "") == "unbound":
|
||||
return f"账号当前未绑定任何游戏角色,与订单目标角色({expected})不一致"
|
||||
if isinstance(order.bind_snapshot_at, datetime):
|
||||
rebind_event = (
|
||||
db.query(AccountEvent)
|
||||
.filter(
|
||||
AccountEvent.account_id == int(acc.id),
|
||||
AccountEvent.event_type == "bind_ok",
|
||||
AccountEvent.subject_type == "elite_role",
|
||||
AccountEvent.occurred_at > order.bind_snapshot_at,
|
||||
)
|
||||
.order_by(AccountEvent.occurred_at.desc(), AccountEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
if (
|
||||
rebind_event is not None
|
||||
and _text(rebind_event.subject_key)
|
||||
and not role_names_match(expected, rebind_event.subject_key)
|
||||
):
|
||||
return (
|
||||
f"账号在快照后已换绑为({_text(rebind_event.subject_key)}),"
|
||||
f"与订单目标角色({expected})不一致"
|
||||
)
|
||||
for record in records:
|
||||
if not isinstance(record, Mapping):
|
||||
continue
|
||||
record_role = _text(
|
||||
record.get("roleName")
|
||||
or record.get("role_name")
|
||||
or record.get("bindRoleName")
|
||||
)
|
||||
if record_role and not role_names_match(expected, record_role):
|
||||
return (
|
||||
f"兑换记录角色({record_role})"
|
||||
f"与订单目标角色({expected})不一致"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _assert_ready_for_recharge(
|
||||
db: Session,
|
||||
order: DouyuExternalOrder,
|
||||
*,
|
||||
entering_waiting: bool,
|
||||
@@ -1253,6 +1318,13 @@ def _assert_ready_for_recharge(
|
||||
f"{action}还缺:{'、'.join(missing)}",
|
||||
code="recharge_precondition",
|
||||
)
|
||||
mismatch = _collab_order_role_mismatch_reason(db, order)
|
||||
if mismatch:
|
||||
raise CollabError(
|
||||
f"{mismatch},禁止推进或完成订单,请先核实角色或切换为账号角色异常",
|
||||
status_code=409,
|
||||
code="role_mismatch",
|
||||
)
|
||||
|
||||
|
||||
def _restore_void_status(
|
||||
@@ -1277,6 +1349,7 @@ def _restore_void_status(
|
||||
target_index = STAGE_INDEX.get(target)
|
||||
if target_index is not None and target_index >= STAGE_INDEX[STATUS_TO_RECHARGE]:
|
||||
_assert_ready_for_recharge(
|
||||
db,
|
||||
order,
|
||||
entering_waiting=target == STATUS_TO_RECHARGE,
|
||||
allow_missing_role=target == STATUS_RECHARGED,
|
||||
@@ -1462,6 +1535,7 @@ def set_status(
|
||||
raise CollabError("回退状态必须显式确认", code="rollback_required")
|
||||
if target_index >= STAGE_INDEX[STATUS_TO_RECHARGE]:
|
||||
_assert_ready_for_recharge(
|
||||
db,
|
||||
order,
|
||||
entering_waiting=target == STATUS_TO_RECHARGE,
|
||||
allow_missing_role=target == STATUS_RECHARGED,
|
||||
@@ -1738,6 +1812,7 @@ def query_activity(
|
||||
|
||||
matched = 0
|
||||
matched_records: list[dict[str, Any]] = []
|
||||
role_mismatch: str | None = None
|
||||
now = _now()
|
||||
if not include_records:
|
||||
verdict = VERDICT_UNKNOWN
|
||||
@@ -1752,8 +1827,18 @@ def query_activity(
|
||||
matched_records = _matching_exchange_records(loaded_records, order)
|
||||
matched = len(matched_records)
|
||||
if matched:
|
||||
verdict = VERDICT_SUCCESS
|
||||
message = f"兑换记录命中「{order.gift_name}」{matched} 条"
|
||||
role_mismatch = _collab_order_role_mismatch_reason(
|
||||
db, order, account, records=matched_records
|
||||
)
|
||||
if role_mismatch:
|
||||
verdict = VERDICT_FAILED
|
||||
message = (
|
||||
f"兑换记录命中「{order.gift_name}」{matched} 条,"
|
||||
f"但{role_mismatch},禁止自动标记成功"
|
||||
)
|
||||
else:
|
||||
verdict = VERDICT_SUCCESS
|
||||
message = f"兑换记录命中「{order.gift_name}」{matched} 条"
|
||||
elif order.status not in (STATUS_SCRIPTED, STATUS_FAILED):
|
||||
verdict = VERDICT_UNKNOWN
|
||||
message = "订单当前状态不再由兑换记录自动判定"
|
||||
@@ -1844,6 +1929,16 @@ def query_activity(
|
||||
expected_version=None,
|
||||
commit=False,
|
||||
)
|
||||
elif order.status in (STATUS_SCRIPTED, STATUS_FAILED) and role_mismatch:
|
||||
set_status(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
status=STATUS_ROLE_ERROR,
|
||||
reason=message,
|
||||
expected_version=None,
|
||||
commit=False,
|
||||
)
|
||||
elif order.status == STATUS_SCRIPTED and verdict == VERDICT_FAILED:
|
||||
set_status(
|
||||
db,
|
||||
|
||||
@@ -30,6 +30,7 @@ from .account_binding import (
|
||||
role_change_available_at,
|
||||
set_bind_status,
|
||||
)
|
||||
from .binding_ownership import role_names_match, workbench_task_occupation_error
|
||||
from .business_events import record_bind
|
||||
from .douyu_account_probe import (
|
||||
ROLE_BOUND,
|
||||
@@ -1340,6 +1341,20 @@ class BindMixin:
|
||||
"bind_candidate_decisions": candidate_decisions,
|
||||
}
|
||||
)
|
||||
if (
|
||||
snapshot["role_name"]
|
||||
and not role_names_match(baseline_role_name, snapshot["role_name"])
|
||||
):
|
||||
record_bind(
|
||||
db,
|
||||
account,
|
||||
task_id=task.id,
|
||||
scope="elite",
|
||||
role_name=snapshot["role_name"],
|
||||
act_alias=query_alias,
|
||||
rebind=bool(str(baseline_role_name or "").strip()),
|
||||
actor_id=int(task.created_by),
|
||||
)
|
||||
self._apply_bind_info_to_account(account, bind_info, BIND_BOUND)
|
||||
self._mark_task(
|
||||
db,
|
||||
@@ -1488,6 +1503,17 @@ class BindMixin:
|
||||
def _execute_get_bind_qr(
|
||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||
):
|
||||
occupation_error = workbench_task_occupation_error(
|
||||
db,
|
||||
account,
|
||||
task_type="get_bind_qr",
|
||||
handbook_scope=str(task.handbook_scope or ""),
|
||||
platform_task_id=task.platform_task_id,
|
||||
allow_auto_link=False,
|
||||
)
|
||||
if occupation_error:
|
||||
self._mark_task(db, task, "failed", occupation_error)
|
||||
return
|
||||
client = self._client(cookie)
|
||||
expected_role_name = str(
|
||||
(task.result or {}).get("expected_role_name") or ""
|
||||
@@ -1758,6 +1784,17 @@ class BindMixin:
|
||||
def _execute_confirm_bind(
|
||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||
):
|
||||
occupation_error = workbench_task_occupation_error(
|
||||
db,
|
||||
account,
|
||||
task_type="confirm_bind",
|
||||
handbook_scope=str(task.handbook_scope or ""),
|
||||
platform_task_id=task.platform_task_id,
|
||||
allow_auto_link=False,
|
||||
)
|
||||
if occupation_error:
|
||||
self._mark_task(db, task, "failed", occupation_error)
|
||||
return
|
||||
client = self._client(cookie)
|
||||
confirm_alias = self._confirm_act_alias(config)
|
||||
query_aliases = self._query_bind_act_aliases(config)
|
||||
|
||||
@@ -13,6 +13,7 @@ from core.douyu import DouyuActivityClient, DouyuActivityError
|
||||
|
||||
from ..models import Account, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, DouyuTask
|
||||
from .account_exchange_sync_service import sync_exchange_records
|
||||
from .binding_ownership import workbench_task_occupation_error
|
||||
from .business_events import record_exchange
|
||||
from .douyu_activity_query import (
|
||||
query_activity_goods,
|
||||
@@ -328,6 +329,17 @@ class GoodsMixin:
|
||||
def _execute_exchange_goods(
|
||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||
):
|
||||
occupation_error = workbench_task_occupation_error(
|
||||
db,
|
||||
account,
|
||||
task_type=str(task.task_type or "exchange_goods"),
|
||||
handbook_scope=str(task.handbook_scope or ""),
|
||||
platform_task_id=task.platform_task_id,
|
||||
allow_auto_link=False,
|
||||
)
|
||||
if occupation_error:
|
||||
self._mark_task(db, task, "failed", occupation_error)
|
||||
return
|
||||
payload = self._task_payload(task)
|
||||
commodity_id = str(
|
||||
payload.get("commodity_id") or payload.get("commodityId") or ""
|
||||
|
||||
@@ -15,7 +15,12 @@ from core.douyu.cookie_utils import cookie_value
|
||||
from ..models import Account, DouyuConfig, DouyuTask
|
||||
from . import account_query_filters as account_filters
|
||||
from .account_events_service import CATEGORY_ACTIVITY, EVENT_TASK_STARTED, emit_bulk
|
||||
from .binding_ownership import BINDING_TASK_TYPES, active_fulfillment_binding_task_id
|
||||
from .binding_ownership import (
|
||||
BINDING_TASK_TYPES,
|
||||
WORKBENCH_GOODS_MUTATION_TYPES,
|
||||
active_fulfillment_binding_task_id,
|
||||
workbench_task_occupation_error,
|
||||
)
|
||||
from .douyu_binding import resolve_douyu_binding
|
||||
|
||||
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES = account_filters.LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
|
||||
@@ -168,6 +173,10 @@ class DouyuActivePaymentError(ValueError):
|
||||
"""同一账号已有未结束的充值任务。"""
|
||||
|
||||
|
||||
class DouyuLeaseConflictError(ValueError):
|
||||
"""账号当前被履约订单或预售台账占用,禁止从工作台发起冲突操作。"""
|
||||
|
||||
|
||||
class DouyuTaskBackpressureError(ValueError):
|
||||
"""全局活跃斗鱼任务超过安全上限。"""
|
||||
|
||||
@@ -362,6 +371,22 @@ def create_douyu_planned_tasks(
|
||||
accounts = visible_douyu_task_accounts(db, account_ids)
|
||||
_ensure_active_task_budget(db, len(accounts))
|
||||
_lock_payment_accounts(db, accounts, task_type)
|
||||
if (
|
||||
platform_task_id is None
|
||||
and handbook_scope == "elite"
|
||||
and task_type in (BINDING_TASK_TYPES | WORKBENCH_GOODS_MUTATION_TYPES)
|
||||
):
|
||||
for account in accounts:
|
||||
occupation_error = workbench_task_occupation_error(
|
||||
db,
|
||||
account,
|
||||
task_type=task_type,
|
||||
handbook_scope=handbook_scope,
|
||||
platform_task_id=platform_task_id,
|
||||
allow_auto_link=True,
|
||||
)
|
||||
if occupation_error:
|
||||
raise DouyuLeaseConflictError(occupation_error)
|
||||
if (
|
||||
task_type in {"refresh_esports_goods", "refresh_xpd_goods"}
|
||||
and accounts
|
||||
|
||||
Reference in New Issue
Block a user