发布(0.4.6): 修复预售兑换记录判定与详情展示并新增工作台强制发放
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
# 直播账号运营后台
|
||||
|
||||
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.5)。
|
||||
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.6)。
|
||||
|
||||
## 能做什么
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "live-hub-py"
|
||||
version = "0.4.5"
|
||||
version = "0.4.6"
|
||||
description = "直播账号运营 Web 后台"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12,<3.13"
|
||||
|
||||
@@ -1830,7 +1830,7 @@ class TestDouyuCollabOrders:
|
||||
old_record = exchange_record(occurred_at=datetime.now(UTC) - timedelta(days=1))
|
||||
wrong_commodity = exchange_record(
|
||||
commodity_id="gift-other",
|
||||
name="礼包A",
|
||||
name="礼包B",
|
||||
)
|
||||
|
||||
result = collab.query_activity(
|
||||
@@ -2465,6 +2465,8 @@ class TestDouyuCollabOrders:
|
||||
assert "/api/douyu/external-orders/{order_id}/balances/query" in paths
|
||||
assert "/api/douyu/external-orders/activity/query" in paths
|
||||
assert "/api/douyu/external-orders/{order_id}/activity/query" in paths
|
||||
assert "/api/douyu/external-orders/{order_id}/exchange-records" in paths
|
||||
assert "/api/douyu/external-orders/{order_id}/exchange-records/query" in paths
|
||||
assert "/api/douyu/collab-shops/{shop_id}" in paths
|
||||
assert "put" in paths["/api/douyu/collab-shops/{shop_id}"]
|
||||
assert "delete" in paths["/api/douyu/collab-shops/{shop_id}"]
|
||||
@@ -2640,3 +2642,94 @@ class TestDouyuCollabOrders:
|
||||
reason="角色不一致时也不能强行完成",
|
||||
)
|
||||
assert rollback_exc.value.code == "role_mismatch"
|
||||
|
||||
def test_record_query_matches_rotated_commodity_id_by_name_and_lists_records(self):
|
||||
"""活动商品改过 ID(如 bag346 -> bag413)时,同名且同角色/时间命中仍应判成功并可在详情展示。"""
|
||||
from web.backend.models import DouyuGoodsSnapshot
|
||||
|
||||
now = datetime.now(UTC)
|
||||
self.session.add_all(
|
||||
[
|
||||
DouyuGoodsSnapshot(
|
||||
commodity_id="20260120QYOOB_bag346",
|
||||
name="冥河战士大礼包",
|
||||
score=8000,
|
||||
updated_at=now - timedelta(days=10),
|
||||
),
|
||||
DouyuGoodsSnapshot(
|
||||
commodity_id="20260120QYOOB_bag413",
|
||||
name="冥河战士大礼包",
|
||||
score=8000,
|
||||
updated_at=now - timedelta(hours=1),
|
||||
),
|
||||
]
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
# 解析礼包名应优先选用最新快照 bag413
|
||||
_, resolved_cid, resolved_points = collab._resolve_gift(
|
||||
self.session,
|
||||
gift_name="冥河战士大礼包",
|
||||
commodity_id="",
|
||||
required_points=None,
|
||||
)
|
||||
assert resolved_cid == "20260120QYOOB_bag413"
|
||||
assert resolved_points == 8000
|
||||
|
||||
# 模拟历史已保存旧 ID bag346 的订单,遇上官方返回的 bag413 兑换记录
|
||||
order = collab.create_order(
|
||||
self.session,
|
||||
self.admin,
|
||||
order_no="2631901603397968",
|
||||
shop="店铺A",
|
||||
account_username="douyu-account-a",
|
||||
gift_name="冥河战士大礼包",
|
||||
commodity_id="20260120QYOOB_bag346",
|
||||
required_points=8000,
|
||||
home_images=["collab/home-rotated-cid.png"],
|
||||
client=FakeClient(),
|
||||
)
|
||||
for status in (collab.STATUS_RECHARGED, collab.STATUS_SCRIPTED):
|
||||
collab.set_status(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
status=status,
|
||||
reason="准备测试改 ID 判定",
|
||||
)
|
||||
|
||||
wrong_role_record = {
|
||||
**exchange_record(name="冥河战士大礼包", commodity_id="20260120QYOOB_bag413"),
|
||||
"showName": "其他角色(安卓(android)-微信)",
|
||||
}
|
||||
matched_record = {
|
||||
**exchange_record(name="冥河战士大礼包", commodity_id="20260120QYOOB_bag413"),
|
||||
"showName": "角色A(苹果(iOS)-微信)",
|
||||
"score": "8000",
|
||||
}
|
||||
|
||||
detail_records = collab.list_order_exchange_records(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
refresh=True,
|
||||
client=FakeClient(records=[wrong_role_record, matched_record]),
|
||||
)
|
||||
assert detail_records["total"] == 2
|
||||
assert detail_records["matched_count"] == 1
|
||||
assert [item["match_reason"] for item in detail_records["records"]] == [
|
||||
"角色不一致",
|
||||
"命中本单",
|
||||
]
|
||||
# 详情只读查询不应改动订单状态
|
||||
assert order.status == collab.STATUS_SCRIPTED
|
||||
|
||||
# 正式自动判定应命中 rotated_cid 记录并转为 done
|
||||
result = collab.query_activity(
|
||||
self.session,
|
||||
self.admin,
|
||||
order,
|
||||
client=FakeClient(records=[matched_record]),
|
||||
)
|
||||
assert result["verdict"] == collab.VERDICT_SUCCESS
|
||||
assert result["order"].status == collab.STATUS_DONE
|
||||
|
||||
@@ -170,3 +170,74 @@ class TestDouyuWritePathContracts:
|
||||
self.session.refresh(exchange_task)
|
||||
assert exchange_task.status == "failed"
|
||||
exchange_client.create_exchange_order.assert_not_called()
|
||||
|
||||
def test_runner_force_goods_allows_matching_role_and_blocks_drift(self):
|
||||
self.account.cookie = "acf_uid=100"
|
||||
self.account.ck_check_status = "valid"
|
||||
self.account.game_name = "客户角色"
|
||||
self.account.role_bind_status = "bound"
|
||||
self.session.add(
|
||||
AccountLease(
|
||||
account_id=self.account.id,
|
||||
holder_user_id=self.user.id,
|
||||
scope="elite",
|
||||
purpose="platform_fulfillment",
|
||||
batch_id="pf:9184",
|
||||
status="active",
|
||||
)
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
lock_task = self._task(
|
||||
"lock_goods",
|
||||
{
|
||||
"commodity_id": "bag10",
|
||||
"num": 1,
|
||||
"force_occupied": True,
|
||||
"force_expected_role": "客户角色",
|
||||
},
|
||||
)
|
||||
runner = self._runner("lock_goods")
|
||||
client = Mock()
|
||||
client.create_exchange_order.return_value = {
|
||||
"order_id": "7788",
|
||||
"expire_seconds": "300",
|
||||
}
|
||||
runner._client = Mock(return_value=client)
|
||||
runner._execute_lock_goods(
|
||||
self.session,
|
||||
lock_task,
|
||||
self.account,
|
||||
"acf_uid=100",
|
||||
{"manual_id": "G4KA4Qnz4LDp7", "rid": "9263298"},
|
||||
)
|
||||
self.session.refresh(lock_task)
|
||||
assert lock_task.status == "success"
|
||||
client.create_exchange_order.assert_called_once()
|
||||
|
||||
# 若排队期间角色被改成其他角色,执行器必须拒绝
|
||||
self.account.game_name = "漂移角色"
|
||||
self.session.commit()
|
||||
drift_task = self._task(
|
||||
"lock_goods",
|
||||
{
|
||||
"commodity_id": "bag10",
|
||||
"num": 1,
|
||||
"force_occupied": True,
|
||||
"force_expected_role": "客户角色",
|
||||
},
|
||||
)
|
||||
drift_runner = self._runner("lock_goods")
|
||||
drift_client = Mock()
|
||||
drift_runner._client = Mock(return_value=drift_client)
|
||||
drift_runner._execute_lock_goods(
|
||||
self.session,
|
||||
drift_task,
|
||||
self.account,
|
||||
"acf_uid=100",
|
||||
{"manual_id": "G4KA4Qnz4LDp7", "rid": "9263298"},
|
||||
)
|
||||
self.session.refresh(drift_task)
|
||||
assert drift_task.status == "failed"
|
||||
assert "不一致" in drift_task.message
|
||||
drift_client.create_exchange_order.assert_not_called()
|
||||
|
||||
@@ -6403,3 +6403,132 @@ class TestBindingAndCompletion(_Base):
|
||||
enqueue_execution=False,
|
||||
)
|
||||
assert collab_query_count == 1
|
||||
|
||||
def test_workbench_force_exchange_requires_permission_and_matching_role(self):
|
||||
"""超管/运营可在核对账号与非空角色一致后强制锁单/兑换,并只在履约时间线留痕。"""
|
||||
from fastapi import HTTPException
|
||||
|
||||
from web.backend.models import DouyuGoodsSnapshot
|
||||
from web.backend.routers.douyu import _prepare_task_batch
|
||||
from web.backend.schemas import DouyuTaskBatchRequest
|
||||
|
||||
task = self._allocated()
|
||||
task.binding_status = "bound"
|
||||
task.execution_status = "bound"
|
||||
task.customer_role_name = "客户目标角色"
|
||||
account = self.session.get(Account, task.account_id)
|
||||
account.game_name = ""
|
||||
account.role_bind_status = "bound"
|
||||
self.session.add(
|
||||
DouyuGoodsSnapshot(
|
||||
commodity_id="bag-force-1",
|
||||
name="套装-花椰椰",
|
||||
score=988,
|
||||
raw={"name": "套装-花椰椰"},
|
||||
)
|
||||
)
|
||||
support_user = User(
|
||||
username="pf-support",
|
||||
password_hash="h",
|
||||
role="support",
|
||||
is_active=True,
|
||||
)
|
||||
op_user = User(
|
||||
username="pf-op",
|
||||
password_hash="h",
|
||||
role="operation",
|
||||
is_active=True,
|
||||
)
|
||||
self.session.add_all([support_user, op_user])
|
||||
self.session.commit()
|
||||
|
||||
req_exchange = DouyuTaskBatchRequest(
|
||||
account_ids=[account.id],
|
||||
task_type="exchange_goods",
|
||||
handbook_scope="elite",
|
||||
payload={"commodity_id": "bag-force-1"},
|
||||
)
|
||||
req_force = DouyuTaskBatchRequest(
|
||||
account_ids=[account.id],
|
||||
task_type="exchange_goods",
|
||||
handbook_scope="elite",
|
||||
payload={"commodity_id": "bag-force-1"},
|
||||
force_occupied=True,
|
||||
)
|
||||
|
||||
# 客服即使有自己名下账号并带 douyu:task,也无权在占用期间强制发放
|
||||
account.assigned_to = support_user.id
|
||||
self.session.commit()
|
||||
with pytest.raises(HTTPException) as exc_sup_409:
|
||||
_prepare_task_batch(req_exchange, self.session, support_user)
|
||||
assert exc_sup_409.value.status_code == 409
|
||||
|
||||
with pytest.raises(HTTPException) as exc_sup_403:
|
||||
_prepare_task_batch(req_force, self.session, support_user)
|
||||
assert exc_sup_403.value.status_code == 403
|
||||
account.assigned_to = None
|
||||
self.session.commit()
|
||||
|
||||
# 运营但账号尚未获取到游戏角色名 -> 严格拒绝并提示先一键获取游戏名
|
||||
with pytest.raises(HTTPException) as exc_empty_role:
|
||||
_prepare_task_batch(req_exchange, self.session, op_user)
|
||||
assert exc_empty_role.value.status_code == 409
|
||||
assert "一键获取游戏名" in exc_empty_role.value.detail
|
||||
|
||||
with pytest.raises(HTTPException) as exc_empty_force:
|
||||
_prepare_task_batch(req_force, self.session, op_user)
|
||||
assert exc_empty_force.value.status_code == 409
|
||||
assert "一键获取游戏名" in exc_empty_force.value.detail
|
||||
|
||||
# 角色与履约目标角色不一致 -> 拒绝
|
||||
account.game_name = "别的错误角色"
|
||||
self.session.commit()
|
||||
with pytest.raises(HTTPException) as exc_mismatch:
|
||||
_prepare_task_batch(req_force, self.session, op_user)
|
||||
assert exc_mismatch.value.status_code == 409
|
||||
assert "不一致" in exc_mismatch.value.detail
|
||||
|
||||
# 禁止强制绑码/换绑
|
||||
req_bind_force = DouyuTaskBatchRequest(
|
||||
account_ids=[account.id],
|
||||
task_type="get_bind_qr",
|
||||
handbook_scope="elite",
|
||||
force_occupied=True,
|
||||
)
|
||||
with pytest.raises(HTTPException) as exc_bind:
|
||||
_prepare_task_batch(req_bind_force, self.session, op_user)
|
||||
assert exc_bind.value.status_code == 400
|
||||
|
||||
# 角色一致后:首次返回 requires_force_confirmation,二次确认提交成功且保持履约状态
|
||||
account.game_name = "客户目标角色"
|
||||
self.session.commit()
|
||||
|
||||
preview = _prepare_task_batch(req_exchange, self.session, op_user)
|
||||
assert preview["requires_force_confirmation"] is True
|
||||
assert preview["occupied_accounts"][0]["account_role"] == "客户目标角色"
|
||||
assert preview["occupied_accounts"][0]["customer_role_name"] == "客户目标角色"
|
||||
|
||||
created = _prepare_task_batch(req_force, self.session, op_user)
|
||||
assert created["success"] is True
|
||||
assert created["count"] == 1
|
||||
|
||||
douyu_task = (
|
||||
self.session.query(DouyuTask)
|
||||
.filter(DouyuTask.batch_id == created["batch_id"])
|
||||
.one()
|
||||
)
|
||||
assert douyu_task.result["payload"]["force_occupied"] is True
|
||||
assert douyu_task.result["payload"]["force_expected_role"] == "客户目标角色"
|
||||
|
||||
self.session.refresh(task)
|
||||
assert task.execution_status == "bound"
|
||||
assert task.binding_status == "bound"
|
||||
|
||||
evt = (
|
||||
self.session.query(PlatformFulfillmentEvent)
|
||||
.filter_by(task_id=task.id, event_type="workbench_force_exchange")
|
||||
.one()
|
||||
)
|
||||
assert evt.detail_json["operatorUsername"] == "pf-op"
|
||||
assert evt.detail_json["accountRole"] == "客户目标角色"
|
||||
assert evt.detail_json["goodsName"] == "套装-花椰椰"
|
||||
|
||||
@@ -381,7 +381,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "live-hub-py"
|
||||
version = "0.4.5"
|
||||
version = "0.4.6"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "alembic" },
|
||||
|
||||
@@ -30,6 +30,7 @@ PERMISSIONS = {
|
||||
"cookie:export": "导出 Cookie",
|
||||
# 斗鱼活动
|
||||
"douyu:task": "斗鱼任务管理",
|
||||
"douyu:task:force": "斗鱼工作台确认角色后强制锁单/兑换",
|
||||
"douyu:config": "斗鱼配置管理",
|
||||
# 斗鱼预售台账(订单挂内部账号,导出时实时读取账号 CK)
|
||||
"douyu:collab:view": "查看斗鱼预售台账",
|
||||
@@ -114,6 +115,7 @@ ROLE_PERMISSIONS = {
|
||||
"cookie:view",
|
||||
"cookie:export",
|
||||
"douyu:task",
|
||||
"douyu:task:force",
|
||||
"douyu:config",
|
||||
"douyu:collab:view",
|
||||
"douyu:collab:edit",
|
||||
|
||||
@@ -87,6 +87,10 @@ from ..services.account_supply_service import (
|
||||
)
|
||||
from ..services.audit_service import record_audit
|
||||
from ..services.automation.scheduler import ensure_jobs
|
||||
from ..services.binding_ownership import (
|
||||
WORKBENCH_GOODS_MUTATION_TYPES,
|
||||
workbench_force_goods_inspection,
|
||||
)
|
||||
from ..services.business_events import record_recharge
|
||||
from ..services.douyu_activity_query import activity_client, query_activity_goods
|
||||
from ..services.douyu_batch_launcher import (
|
||||
@@ -114,6 +118,7 @@ from ..services.douyu_service import (
|
||||
douyu_config_value,
|
||||
douyu_task_payload,
|
||||
ensure_douyu_config,
|
||||
visible_douyu_task_accounts,
|
||||
)
|
||||
from ..services.execution_jobs import (
|
||||
JOB_DOUYU_BATCH,
|
||||
@@ -1525,6 +1530,22 @@ def _prepare_task_batch(
|
||||
)
|
||||
if guard is not None:
|
||||
return guard
|
||||
if req.force_occupied:
|
||||
if not user_has_permission(current, "douyu:task:force"):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="仅超级管理员或运营有权限在占用期间强制发放",
|
||||
)
|
||||
if (
|
||||
req.handbook_scope != "elite"
|
||||
or req.task_type not in WORKBENCH_GOODS_MUTATION_TYPES
|
||||
or req.platform_task_id is not None
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="仅精英工作台锁单、支付锁单与兑换商品支持确认角色后强制发放",
|
||||
)
|
||||
|
||||
task_payload = dict(req.payload)
|
||||
if req.recharge_confirmation_token:
|
||||
task_payload["recharge_confirmation_used"] = True
|
||||
@@ -1541,8 +1562,42 @@ def _prepare_task_batch(
|
||||
concurrency=req.concurrency,
|
||||
recharge_channel=recharge_channel,
|
||||
recharge_amount=recharge_amount,
|
||||
force_occupied=req.force_occupied,
|
||||
)
|
||||
except (DouyuActivePaymentError, DouyuLeaseConflictError) as exc:
|
||||
except DouyuLeaseConflictError as exc:
|
||||
if (
|
||||
not req.force_occupied
|
||||
and req.platform_task_id is None
|
||||
and req.handbook_scope == "elite"
|
||||
and req.task_type in WORKBENCH_GOODS_MUTATION_TYPES
|
||||
and user_has_permission(current, "douyu:task:force")
|
||||
):
|
||||
visible_accounts = visible_douyu_task_accounts(db, req.account_ids)
|
||||
inspections = [
|
||||
workbench_force_goods_inspection(db, acc)
|
||||
for acc in visible_accounts
|
||||
]
|
||||
occupied_items = [item for item in inspections if item["occupied"]]
|
||||
blocked = next(
|
||||
(item for item in occupied_items if not item["can_force"]),
|
||||
None,
|
||||
)
|
||||
if blocked is not None:
|
||||
raise HTTPException(status_code=409, detail=blocked["reason"]) from exc
|
||||
if occupied_items:
|
||||
return {
|
||||
"batch_id": "",
|
||||
"count": 0,
|
||||
"success": False,
|
||||
"requires_force_confirmation": True,
|
||||
"occupied_accounts": occupied_items,
|
||||
"message": (
|
||||
"所选账号当前由平台履约订单占用,已校验斗鱼号与绑定角色正常,"
|
||||
"请核对后确认强制发放"
|
||||
),
|
||||
}
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
except DouyuActivePaymentError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
except DouyuTaskBackpressureError as exc:
|
||||
raise HTTPException(
|
||||
@@ -1556,6 +1611,70 @@ def _prepare_task_batch(
|
||||
raise HTTPException(
|
||||
status_code=400, detail="没有可执行的斗鱼账号,请先登录获取 Cookie"
|
||||
)
|
||||
if req.force_occupied:
|
||||
commodity_id = str(
|
||||
req.payload.get("commodity_id") or req.payload.get("commodityId") or ""
|
||||
).strip()
|
||||
snapshot = (
|
||||
db.query(DouyuGoodsSnapshot)
|
||||
.filter(DouyuGoodsSnapshot.commodity_id == commodity_id)
|
||||
.first()
|
||||
if commodity_id
|
||||
else None
|
||||
)
|
||||
goods_name = str(snapshot.name or "").strip() if snapshot else ""
|
||||
forced_rows = (
|
||||
db.query(DouyuTask, Account)
|
||||
.join(Account, Account.id == DouyuTask.account_id)
|
||||
.filter(DouyuTask.batch_id == batch_id)
|
||||
.order_by(DouyuTask.id.asc())
|
||||
.all()
|
||||
)
|
||||
forced_pf_details: list[dict[str, Any]] = []
|
||||
for douyu_task, account in forced_rows:
|
||||
result_data = douyu_task.result if isinstance(douyu_task.result, dict) else {}
|
||||
raw_payload = result_data.get("payload")
|
||||
payload_meta = raw_payload if isinstance(raw_payload, dict) else {}
|
||||
pf_task_id = payload_meta.get("force_platform_task_id")
|
||||
if not payload_meta.get("force_occupied") or not pf_task_id:
|
||||
continue
|
||||
platform_fulfillment_service.record_workbench_force_exchange(
|
||||
db,
|
||||
task_id=int(pf_task_id),
|
||||
current=current,
|
||||
batch_id=batch_id,
|
||||
douyu_task_id=int(douyu_task.id),
|
||||
task_type=req.task_type,
|
||||
commodity_id=commodity_id,
|
||||
goods_name=goods_name,
|
||||
account_id=int(account.id),
|
||||
account_username=str(account.username or ""),
|
||||
account_role=str(account.game_name or ""),
|
||||
)
|
||||
forced_pf_details.append(
|
||||
{
|
||||
"douyu_task_id": int(douyu_task.id),
|
||||
"platform_task_id": int(pf_task_id),
|
||||
"account_id": int(account.id),
|
||||
"account_username": str(account.username or ""),
|
||||
"account_role": str(account.game_name or ""),
|
||||
}
|
||||
)
|
||||
if forced_pf_details:
|
||||
record_audit(
|
||||
db,
|
||||
current,
|
||||
action="douyu:workbench:force_exchange",
|
||||
target=f"douyu_batch:{batch_id}",
|
||||
detail={
|
||||
"batch_id": batch_id,
|
||||
"task_type": req.task_type,
|
||||
"commodity_id": commodity_id,
|
||||
"goods_name": goods_name,
|
||||
"accounts": forced_pf_details,
|
||||
},
|
||||
)
|
||||
db.commit()
|
||||
if req.platform_task_id:
|
||||
douyu_task_ids = [
|
||||
int(task_id)
|
||||
|
||||
@@ -35,6 +35,7 @@ from ..schemas import (
|
||||
DouyuCollabArchiveRequest,
|
||||
DouyuCollabCkExportOut,
|
||||
DouyuCollabCkExportRequest,
|
||||
DouyuCollabExchangeRecordsOut,
|
||||
DouyuCollabGiftCreate,
|
||||
DouyuCollabGiftOut,
|
||||
DouyuCollabGiftUpdate,
|
||||
@@ -721,6 +722,40 @@ def external_order_metrics(
|
||||
return collab.order_metrics(db, order_id)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/external-orders/{order_id}/exchange-records",
|
||||
response_model=DouyuCollabExchangeRecordsOut,
|
||||
)
|
||||
def get_external_order_exchange_records(
|
||||
order_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("douyu:collab:view")),
|
||||
):
|
||||
"""查看订单关联斗鱼账号已缓存的兑换记录。"""
|
||||
try:
|
||||
order = collab.get_order(db, order_id)
|
||||
return collab.list_order_exchange_records(db, current, order, refresh=False)
|
||||
except collab.CollabError as exc:
|
||||
raise _http_error(exc) from exc
|
||||
|
||||
|
||||
@router.post(
|
||||
"/external-orders/{order_id}/exchange-records/query",
|
||||
response_model=DouyuCollabExchangeRecordsOut,
|
||||
)
|
||||
def query_external_order_exchange_records(
|
||||
order_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("douyu:collab:edit")),
|
||||
):
|
||||
"""实时向斗鱼拉取兑换记录并展示明细,不自动修改订单状态。"""
|
||||
try:
|
||||
order = collab.get_order(db, order_id)
|
||||
return collab.list_order_exchange_records(db, current, order, refresh=True)
|
||||
except collab.CollabError as exc:
|
||||
raise _http_error(exc) from exc
|
||||
|
||||
|
||||
@router.delete("/external-orders/{order_id}")
|
||||
def delete_external_order(
|
||||
order_id: int,
|
||||
|
||||
@@ -1850,6 +1850,7 @@ class DouyuTaskBatchRequest(BaseModel):
|
||||
payload: dict[str, Any] = Field(default_factory=dict)
|
||||
platform_task_id: int | None = Field(None, gt=0)
|
||||
recharge_confirmation_token: str | None = Field(None, max_length=64)
|
||||
force_occupied: bool = False
|
||||
|
||||
|
||||
class DouyuWorkbenchAccountsUpdate(BaseModel):
|
||||
@@ -3093,3 +3094,28 @@ class DouyuCollabTimelineOut(BaseModel):
|
||||
detail: str = ""
|
||||
success: bool | None = None
|
||||
created_at: datetime | None = None
|
||||
|
||||
|
||||
class DouyuCollabExchangeRecordItemOut(BaseModel):
|
||||
commodity_id: str = ""
|
||||
commodity_name: str = ""
|
||||
score: int | None = None
|
||||
exchange_num: int = 1
|
||||
show_name: str = ""
|
||||
role_name: str = ""
|
||||
pic: str = ""
|
||||
occurred_at: datetime | None = None
|
||||
matched: bool = False
|
||||
match_reason: str = ""
|
||||
|
||||
|
||||
class DouyuCollabExchangeRecordsOut(BaseModel):
|
||||
order_id: int
|
||||
account_id: int | None = None
|
||||
account_username: str = ""
|
||||
refreshed: bool = False
|
||||
synced_at: datetime | None = None
|
||||
total: int = 0
|
||||
matched_count: int = 0
|
||||
error: str = ""
|
||||
records: list[DouyuCollabExchangeRecordItemOut] = []
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -194,6 +195,96 @@ def _account_display_label(account: Account) -> str:
|
||||
)
|
||||
|
||||
|
||||
def _occupying_platform_task_for_lease(
|
||||
db: Session,
|
||||
account_id: int,
|
||||
lease: AccountLease,
|
||||
) -> PlatformFulfillmentTask | None:
|
||||
task = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.filter(PlatformFulfillmentTask.lease_id == int(lease.id))
|
||||
.order_by(PlatformFulfillmentTask.id.desc())
|
||||
.first()
|
||||
)
|
||||
if task is not None:
|
||||
return task
|
||||
return (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.account_id == int(account_id),
|
||||
PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")),
|
||||
)
|
||||
.order_by(PlatformFulfillmentTask.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def workbench_force_goods_inspection(
|
||||
db: Session,
|
||||
account: Account,
|
||||
*,
|
||||
lease: AccountLease | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""评估工作台强制锁单/兑换的占用与角色安全条件。
|
||||
|
||||
只有斗鱼号凭据正常、已获取当前绑定角色(非空且非未绑定),且与履约单
|
||||
目标角色一致时才允许超管/运营二次确认后强制发放。
|
||||
"""
|
||||
active_lease = lease or active_account_lease(db, account.id)
|
||||
label = _account_display_label(account)
|
||||
if active_lease is None or active_lease.purpose != "platform_fulfillment":
|
||||
return {
|
||||
"occupied": False,
|
||||
"can_force": True,
|
||||
"reason": "",
|
||||
"account_id": int(account.id),
|
||||
"account_name": label,
|
||||
"account_role": str(account.game_name or "").strip(),
|
||||
"platform_task_id": None,
|
||||
"platform_order_id": "",
|
||||
"customer_role_name": "",
|
||||
"sku_name": "",
|
||||
"lease_batch_id": "",
|
||||
}
|
||||
|
||||
pf_task = _occupying_platform_task_for_lease(db, account.id, active_lease)
|
||||
current_role = str(account.game_name or "").strip()
|
||||
customer_role = str(pf_task.customer_role_name or "").strip() if pf_task else ""
|
||||
order_label = (
|
||||
str(pf_task.platform_order_id or pf_task.source_order_id or f"#{pf_task.id}")
|
||||
if pf_task
|
||||
else (active_lease.batch_id or "-")
|
||||
)
|
||||
|
||||
reason = ""
|
||||
if not str(account.cookie or "").strip() or str(account.ck_check_status or "") == "invalid":
|
||||
reason = f"账号 {label} 登录凭据异常,禁止强制发放"
|
||||
elif str(account.role_bind_status or "") == "unbound" or not current_role:
|
||||
reason = (
|
||||
f"账号 {label} 当前未获取到已绑定的游戏角色,"
|
||||
"请先点击「一键获取游戏名」确认角色正常后再强制发放"
|
||||
)
|
||||
elif customer_role and not role_names_match(current_role, customer_role):
|
||||
reason = (
|
||||
f"账号 {label} 当前绑定角色({current_role})与履约单 {order_label} "
|
||||
f"目标角色({customer_role})不一致,禁止强制发放"
|
||||
)
|
||||
|
||||
return {
|
||||
"occupied": True,
|
||||
"can_force": not bool(reason),
|
||||
"reason": reason,
|
||||
"account_id": int(account.id),
|
||||
"account_name": label,
|
||||
"account_role": current_role,
|
||||
"platform_task_id": int(pf_task.id) if pf_task is not None else None,
|
||||
"platform_order_id": order_label,
|
||||
"customer_role_name": customer_role,
|
||||
"sku_name": str(pf_task.sku_name or "").strip() if pf_task else "",
|
||||
"lease_batch_id": str(active_lease.batch_id or ""),
|
||||
}
|
||||
|
||||
|
||||
def workbench_task_occupation_error(
|
||||
db: Session,
|
||||
account: Account,
|
||||
@@ -202,13 +293,15 @@ def workbench_task_occupation_error(
|
||||
handbook_scope: str,
|
||||
platform_task_id: int | None,
|
||||
allow_auto_link: bool = False,
|
||||
force_occupied: bool = False,
|
||||
) -> str | None:
|
||||
"""检查工作台无归属任务是否会误改已占用账号的角色或库存。
|
||||
|
||||
仅拦截未绑定 ``platform_task_id`` 的精英宝典写操作:
|
||||
- 绑码/换绑(``get_bind_qr`` / ``confirm_bind``):若未命中可自动归属的
|
||||
待绑定履约单,禁止在任意活动租约(平台履约、预售台账等)或活跃预售单期间执行;
|
||||
- 锁单/支付/兑换:账号处于平台履约租约期间,只能由履约订单带 ``platform_task_id`` 发起。
|
||||
- 锁单/支付/兑换:账号处于平台履约租约期间,默认要求从履约订单内发起;
|
||||
超管/运营显式 ``force_occupied=True`` 时,必须通过角色非空且一致的严格校验。
|
||||
"""
|
||||
if handbook_scope != "elite" or platform_task_id is not None:
|
||||
return None
|
||||
@@ -265,6 +358,9 @@ def workbench_task_occupation_error(
|
||||
and lease is not None
|
||||
and lease.purpose == "platform_fulfillment"
|
||||
):
|
||||
if force_occupied:
|
||||
inspection = workbench_force_goods_inspection(db, account, lease=lease)
|
||||
return inspection["reason"] or None
|
||||
return (
|
||||
f"账号 {label} 当前由平台履约订单占用"
|
||||
f"(批次 {lease.batch_id or '-'}),请从履约订单内发起锁单或兑换"
|
||||
@@ -286,5 +382,6 @@ __all__ = [
|
||||
"normalize_role_name",
|
||||
"role_names_match",
|
||||
"source_created_within_lease",
|
||||
"workbench_force_goods_inspection",
|
||||
"workbench_task_occupation_error",
|
||||
]
|
||||
|
||||
@@ -49,7 +49,14 @@ def _resolve_gift(
|
||||
if cid:
|
||||
row = query.filter(DouyuGoodsSnapshot.commodity_id == cid).first()
|
||||
if row is None and name:
|
||||
row = query.filter(DouyuGoodsSnapshot.name == name).first()
|
||||
row = (
|
||||
query.filter(DouyuGoodsSnapshot.name == name)
|
||||
.order_by(
|
||||
DouyuGoodsSnapshot.updated_at.desc(),
|
||||
DouyuGoodsSnapshot.id.desc(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if row is not None:
|
||||
if not name:
|
||||
name = _text(row.name, max_length=128)
|
||||
|
||||
@@ -29,6 +29,7 @@ from ..models import (
|
||||
Account,
|
||||
AccountEvent,
|
||||
AccountLease,
|
||||
AccountSyncState,
|
||||
AuditLog,
|
||||
DouyuCollabGift,
|
||||
DouyuCollabShop,
|
||||
@@ -1620,13 +1621,62 @@ def _exchange_record_time(record: Mapping[str, Any]) -> datetime | None:
|
||||
return None
|
||||
|
||||
|
||||
def _extract_record_role(record: Mapping[str, Any]) -> str:
|
||||
explicit = _text(
|
||||
record.get("roleName")
|
||||
or record.get("role_name")
|
||||
or record.get("bindRoleName")
|
||||
)
|
||||
if explicit:
|
||||
return explicit
|
||||
show_name = _text(record.get("showName") or record.get("show_name"))
|
||||
if show_name.endswith(")") and "(" in show_name:
|
||||
prefix, suffix = show_name.rsplit("(", 1)
|
||||
if "-" in suffix and prefix.strip():
|
||||
return prefix.strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _evaluate_exchange_record(
|
||||
record: Mapping[str, Any],
|
||||
order: DouyuExternalOrder,
|
||||
*,
|
||||
not_before: datetime | None,
|
||||
) -> tuple[bool, str]:
|
||||
"""判定单条斗鱼兑换记录是否命中当前预售单,并返回原因标签。"""
|
||||
expected_cid = _text(order.commodity_id)
|
||||
expected_name = _normalize_exchange_name(order.gift_name)
|
||||
record_cid = _text(
|
||||
record.get("commodityId")
|
||||
or record.get("commodity_id")
|
||||
or record.get("goodsId")
|
||||
)
|
||||
record_name = _normalize_exchange_name(
|
||||
record.get("commodityName")
|
||||
or record.get("commodity_name")
|
||||
or record.get("goodsName")
|
||||
)
|
||||
cid_matched = bool(expected_cid and record_cid and record_cid == expected_cid)
|
||||
name_matched = bool(expected_name and record_name and record_name == expected_name)
|
||||
if not (cid_matched or name_matched):
|
||||
return False, "其他礼包"
|
||||
|
||||
rec_role = _extract_record_role(record)
|
||||
expected_role = _text(order.bind_game_role)
|
||||
if expected_role and rec_role and not role_names_match(expected_role, rec_role):
|
||||
return False, "角色不一致"
|
||||
|
||||
record_time = _exchange_record_time(record)
|
||||
if not_before is not None and (record_time is None or record_time < not_before):
|
||||
return False, "早于上脚本时间"
|
||||
return True, "命中本单"
|
||||
|
||||
|
||||
def _matching_exchange_records(
|
||||
records: Sequence[Mapping[str, Any]],
|
||||
order: DouyuExternalOrder,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按商品 ID、精确名称和上脚本时间匹配,避免历史记录串单。"""
|
||||
expected_cid = _text(order.commodity_id)
|
||||
expected_name = _normalize_exchange_name(order.gift_name)
|
||||
"""按商品 ID 或精确礼包名、角色与时间窗口匹配,避免下架换 ID 漏判或历史记录串单。"""
|
||||
not_before = order.scripted_at
|
||||
if isinstance(not_before, datetime):
|
||||
not_before = not_before - timedelta(seconds=ACTIVITY_RECORD_TIME_SKEW_SECONDS)
|
||||
@@ -1635,29 +1685,143 @@ def _matching_exchange_records(
|
||||
for record in records:
|
||||
if not isinstance(record, Mapping):
|
||||
continue
|
||||
record_cid = _text(
|
||||
ok, _ = _evaluate_exchange_record(record, order, not_before=not_before)
|
||||
if ok:
|
||||
matched.append(dict(record))
|
||||
return matched
|
||||
|
||||
|
||||
def _serialize_exchange_record_item(
|
||||
record: Mapping[str, Any],
|
||||
order: DouyuExternalOrder,
|
||||
*,
|
||||
not_before: datetime | None,
|
||||
) -> dict[str, Any]:
|
||||
record_time = _exchange_record_time(record)
|
||||
matched, match_reason = _evaluate_exchange_record(
|
||||
record,
|
||||
order,
|
||||
not_before=not_before,
|
||||
)
|
||||
return {
|
||||
"commodity_id": _text(
|
||||
record.get("commodityId")
|
||||
or record.get("commodity_id")
|
||||
or record.get("goodsId")
|
||||
),
|
||||
"commodity_name": _text(
|
||||
record.get("commodityName")
|
||||
or record.get("commodity_name")
|
||||
or record.get("goodsName")
|
||||
),
|
||||
"score": _to_int(record.get("score")),
|
||||
"exchange_num": _to_int(record.get("exchangeNum") or record.get("exchange_num"))
|
||||
or 1,
|
||||
"show_name": _text(record.get("showName") or record.get("show_name")),
|
||||
"role_name": _extract_record_role(record),
|
||||
"pic": _text(record.get("pic")),
|
||||
"occurred_at": record_time,
|
||||
"matched": matched,
|
||||
"match_reason": match_reason,
|
||||
}
|
||||
|
||||
|
||||
def list_order_exchange_records(
|
||||
db: Session,
|
||||
current: User,
|
||||
order: DouyuExternalOrder,
|
||||
*,
|
||||
refresh: bool = False,
|
||||
client: Any | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""查询或读取订单关联斗鱼账号的兑换记录,不自动修改订单状态。"""
|
||||
account = account_by_id(db, order.account_id) or account_by_username(
|
||||
db, order.account_username
|
||||
)
|
||||
if account is None:
|
||||
raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found")
|
||||
|
||||
raw_records: list[dict[str, Any]] = []
|
||||
synced_at: datetime | None = None
|
||||
error_text = ""
|
||||
|
||||
if refresh:
|
||||
try:
|
||||
raw_records = _load_exchange_records_for_orders(
|
||||
db, [order], client=client
|
||||
)
|
||||
synced_at = _now()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
error_text = str(exc)
|
||||
record_account_query(
|
||||
db,
|
||||
account,
|
||||
query_type="collab_exchange_records",
|
||||
title="详情查询兑换记录",
|
||||
ok=not bool(error_text),
|
||||
detail={
|
||||
"order_no": order.order_no,
|
||||
"records": len(raw_records),
|
||||
"error": error_text[:500],
|
||||
},
|
||||
actor_id=current.id,
|
||||
)
|
||||
if expected_cid and record_cid:
|
||||
identity_matched = record_cid == expected_cid
|
||||
else:
|
||||
record_name = _normalize_exchange_name(
|
||||
record.get("commodityName")
|
||||
or record.get("commodity_name")
|
||||
or record.get("goodsName")
|
||||
db.commit()
|
||||
|
||||
if not raw_records:
|
||||
sync_row = (
|
||||
db.query(AccountSyncState)
|
||||
.filter(
|
||||
AccountSyncState.account_id == int(account.id),
|
||||
AccountSyncState.platform == "douyu",
|
||||
AccountSyncState.domain == "exchange_records",
|
||||
)
|
||||
identity_matched = bool(
|
||||
expected_name and record_name and record_name == expected_name
|
||||
.first()
|
||||
)
|
||||
if sync_row is not None and isinstance(sync_row.raw_payload_json, Mapping):
|
||||
elite_rows = sync_row.raw_payload_json.get("elite")
|
||||
if isinstance(elite_rows, list):
|
||||
raw_records = [dict(item) for item in elite_rows if isinstance(item, Mapping)]
|
||||
if synced_at is None:
|
||||
synced_at = sync_row.updated_at
|
||||
if not raw_records:
|
||||
latest_metric = (
|
||||
db.query(DouyuExternalOrderMetric)
|
||||
.filter(
|
||||
DouyuExternalOrderMetric.order_id == int(order.id),
|
||||
~DouyuExternalOrderMetric.source.like("balance%"),
|
||||
)
|
||||
.order_by(DouyuExternalOrderMetric.id.desc())
|
||||
.first()
|
||||
)
|
||||
if not identity_matched:
|
||||
continue
|
||||
record_time = _exchange_record_time(record)
|
||||
if not_before is not None and (record_time is None or record_time < not_before):
|
||||
continue
|
||||
matched.append(dict(record))
|
||||
return matched
|
||||
if latest_metric is not None and isinstance(latest_metric.raw, Mapping):
|
||||
metric_rows = latest_metric.raw.get("records")
|
||||
if isinstance(metric_rows, list):
|
||||
raw_records = [
|
||||
dict(item) for item in metric_rows if isinstance(item, Mapping)
|
||||
]
|
||||
if synced_at is None:
|
||||
synced_at = latest_metric.created_at
|
||||
|
||||
not_before = order.scripted_at
|
||||
if isinstance(not_before, datetime):
|
||||
not_before = not_before - timedelta(seconds=ACTIVITY_RECORD_TIME_SKEW_SECONDS)
|
||||
|
||||
items = [
|
||||
_serialize_exchange_record_item(record, order, not_before=not_before)
|
||||
for record in raw_records
|
||||
]
|
||||
return {
|
||||
"order_id": int(order.id),
|
||||
"account_id": int(account.id),
|
||||
"account_username": _text(account.username),
|
||||
"refreshed": bool(refresh),
|
||||
"synced_at": synced_at,
|
||||
"total": len(items),
|
||||
"matched_count": sum(1 for item in items if item["matched"]),
|
||||
"error": error_text,
|
||||
"records": items,
|
||||
}
|
||||
|
||||
|
||||
def group_points_total(db: Session, order: DouyuExternalOrder) -> int:
|
||||
|
||||
@@ -13,7 +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 .binding_ownership import role_names_match, workbench_task_occupation_error
|
||||
from .business_events import record_exchange
|
||||
from .douyu_activity_query import (
|
||||
query_activity_goods,
|
||||
@@ -138,9 +138,39 @@ class GoodsMixin:
|
||||
},
|
||||
)
|
||||
|
||||
def _check_goods_occupation(
|
||||
self, db: Session, task: DouyuTask, account: Account
|
||||
) -> str | None:
|
||||
payload = self._task_payload(task)
|
||||
force_occupied = bool(payload.get("force_occupied"))
|
||||
expected_role = str(payload.get("force_expected_role") or "").strip()
|
||||
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,
|
||||
force_occupied=force_occupied,
|
||||
)
|
||||
if occupation_error:
|
||||
return occupation_error
|
||||
if force_occupied and expected_role:
|
||||
current_role = str(account.game_name or "").strip()
|
||||
if not current_role or not role_names_match(current_role, expected_role):
|
||||
return (
|
||||
f"账号当前绑定角色({current_role or '未获取'})"
|
||||
f"与确认时角色({expected_role})不一致,已取消强制发放"
|
||||
)
|
||||
return None
|
||||
|
||||
def _execute_lock_goods(
|
||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||
):
|
||||
occupation_error = self._check_goods_occupation(db, task, account)
|
||||
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 ""
|
||||
@@ -192,6 +222,10 @@ class GoodsMixin:
|
||||
cookie: str,
|
||||
config: dict,
|
||||
):
|
||||
occupation_error = self._check_goods_occupation(db, task, account)
|
||||
if occupation_error:
|
||||
self._mark_task(db, task, "failed", occupation_error)
|
||||
return
|
||||
payload = self._task_payload(task)
|
||||
order_id = str(payload.get("order_id") or payload.get("orderId") or "").strip()
|
||||
commodity_id = str(
|
||||
@@ -329,14 +363,7 @@ 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,
|
||||
)
|
||||
occupation_error = self._check_goods_occupation(db, task, account)
|
||||
if occupation_error:
|
||||
self._mark_task(db, task, "failed", occupation_error)
|
||||
return
|
||||
|
||||
@@ -19,6 +19,7 @@ from .binding_ownership import (
|
||||
BINDING_TASK_TYPES,
|
||||
WORKBENCH_GOODS_MUTATION_TYPES,
|
||||
active_fulfillment_binding_task_id,
|
||||
workbench_force_goods_inspection,
|
||||
workbench_task_occupation_error,
|
||||
)
|
||||
from .douyu_binding import resolve_douyu_binding
|
||||
@@ -359,6 +360,7 @@ def create_douyu_planned_tasks(
|
||||
enqueue_execution: bool = True,
|
||||
recharge_channel: str = "",
|
||||
recharge_amount: int | None = None,
|
||||
force_occupied: bool = False,
|
||||
) -> tuple[str, int]:
|
||||
"""创建斗鱼任务记录,等待后台执行器消费。"""
|
||||
if task_type not in SUPPORTED_DOUYU_TASK_TYPES:
|
||||
@@ -371,6 +373,13 @@ 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)
|
||||
allow_force_goods = (
|
||||
bool(force_occupied)
|
||||
and platform_task_id is None
|
||||
and handbook_scope == "elite"
|
||||
and task_type in WORKBENCH_GOODS_MUTATION_TYPES
|
||||
)
|
||||
forced_payloads: dict[int, dict] = {}
|
||||
if (
|
||||
platform_task_id is None
|
||||
and handbook_scope == "elite"
|
||||
@@ -384,9 +393,18 @@ def create_douyu_planned_tasks(
|
||||
handbook_scope=handbook_scope,
|
||||
platform_task_id=platform_task_id,
|
||||
allow_auto_link=True,
|
||||
force_occupied=allow_force_goods,
|
||||
)
|
||||
if occupation_error:
|
||||
raise DouyuLeaseConflictError(occupation_error)
|
||||
if allow_force_goods:
|
||||
inspection = workbench_force_goods_inspection(db, account)
|
||||
if inspection["occupied"]:
|
||||
forced_payloads[int(account.id)] = {
|
||||
"force_occupied": True,
|
||||
"force_expected_role": inspection["account_role"],
|
||||
"force_platform_task_id": inspection["platform_task_id"],
|
||||
}
|
||||
if (
|
||||
task_type in {"refresh_esports_goods", "refresh_xpd_goods"}
|
||||
and accounts
|
||||
@@ -412,6 +430,9 @@ def create_douyu_planned_tasks(
|
||||
db,
|
||||
account.id,
|
||||
)
|
||||
account_payload = dict(payload)
|
||||
if int(account.id) in forced_payloads:
|
||||
account_payload.update(forced_payloads[int(account.id)])
|
||||
task = DouyuTask(
|
||||
batch_id=batch_id,
|
||||
account_id=account.id,
|
||||
@@ -420,7 +441,7 @@ def create_douyu_planned_tasks(
|
||||
handbook_scope=handbook_scope,
|
||||
status="planned",
|
||||
message="任务已创建,等待执行",
|
||||
result={"payload": payload} if payload else None,
|
||||
result={"payload": account_payload} if account_payload else None,
|
||||
created_by=created_by,
|
||||
platform_task_id=linked_platform_task_id,
|
||||
recharge_channel=recharge_channel,
|
||||
|
||||
@@ -383,3 +383,40 @@ def record_douyu_operation_result(
|
||||
"issueCode": issue_code,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def record_workbench_force_exchange(
|
||||
db: Session,
|
||||
*,
|
||||
task_id: int,
|
||||
current: User,
|
||||
batch_id: str,
|
||||
douyu_task_id: int,
|
||||
task_type: str,
|
||||
commodity_id: str = "",
|
||||
goods_name: str = "",
|
||||
account_id: int | None = None,
|
||||
account_username: str = "",
|
||||
account_role: str = "",
|
||||
) -> None:
|
||||
"""工作台确认账号和角色一致后强制发放时,在履约时间线记一笔操作留痕(不改订单状态)。"""
|
||||
_append_event(
|
||||
db,
|
||||
int(task_id),
|
||||
"workbench_force_exchange",
|
||||
actor_type="user",
|
||||
actor_id=int(current.id),
|
||||
detail={
|
||||
"operatorId": int(current.id),
|
||||
"operatorUsername": str(current.username or ""),
|
||||
"batchId": batch_id,
|
||||
"douyuTaskId": int(douyu_task_id),
|
||||
"taskType": task_type,
|
||||
"taskLabel": SUPPORTED_DOUYU_TASK_TYPES.get(task_type, task_type),
|
||||
"commodityId": str(commodity_id or ""),
|
||||
"goodsName": str(goods_name or ""),
|
||||
"accountId": int(account_id) if account_id is not None else None,
|
||||
"accountUsername": str(account_username or ""),
|
||||
"accountRole": str(account_role or ""),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -131,6 +131,7 @@ from .runtime import ( # noqa: F401
|
||||
get_settings,
|
||||
record_douyu_operation_result,
|
||||
record_douyu_operation_started,
|
||||
record_workbench_force_exchange,
|
||||
update_settings,
|
||||
)
|
||||
from .views import ( # noqa: F401
|
||||
@@ -168,6 +169,7 @@ __all__ = [
|
||||
"reconcile_binding_state_outbox",
|
||||
"record_douyu_operation_result",
|
||||
"record_douyu_operation_started",
|
||||
"record_workbench_force_exchange",
|
||||
"refresh_active_exchange_eligibility_for_account",
|
||||
"refresh_binding",
|
||||
"refresh_exchange_eligibility",
|
||||
|
||||
@@ -301,6 +301,31 @@ export interface DouyuCollabMetric {
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
export interface DouyuCollabExchangeRecord {
|
||||
commodity_id: string;
|
||||
commodity_name: string;
|
||||
score: number | null;
|
||||
exchange_num: number;
|
||||
show_name: string;
|
||||
role_name: string;
|
||||
pic: string;
|
||||
occurred_at: string | null;
|
||||
matched: boolean;
|
||||
match_reason: string;
|
||||
}
|
||||
|
||||
export interface DouyuCollabExchangeRecordsResponse {
|
||||
order_id: number;
|
||||
account_id: number | null;
|
||||
account_username: string;
|
||||
refreshed: boolean;
|
||||
synced_at: string | null;
|
||||
total: number;
|
||||
matched_count: number;
|
||||
error: string;
|
||||
records: DouyuCollabExchangeRecord[];
|
||||
}
|
||||
|
||||
export interface DouyuCollabTimeline {
|
||||
id: number;
|
||||
action: string;
|
||||
@@ -526,6 +551,14 @@ export const douyuCollabApi = {
|
||||
api.get<DouyuCollabTimeline[], DouyuCollabTimeline[]>(`/douyu/external-orders/${id}/timeline`),
|
||||
metrics: (id: number) =>
|
||||
api.get<DouyuCollabMetric[], DouyuCollabMetric[]>(`/douyu/external-orders/${id}/metrics`),
|
||||
exchangeRecords: (id: number) =>
|
||||
api.get<DouyuCollabExchangeRecordsResponse, DouyuCollabExchangeRecordsResponse>(
|
||||
`/douyu/external-orders/${id}/exchange-records`,
|
||||
),
|
||||
queryExchangeRecords: (id: number) =>
|
||||
api.post<DouyuCollabExchangeRecordsResponse, DouyuCollabExchangeRecordsResponse>(
|
||||
`/douyu/external-orders/${id}/exchange-records/query`,
|
||||
),
|
||||
deleteOrder: (id: number) =>
|
||||
api.delete<{ success: boolean; order_no: string }, { success: boolean; order_no: string }>(
|
||||
`/douyu/external-orders/${id}`,
|
||||
|
||||
@@ -1025,6 +1025,18 @@ export interface DouyuTaskBatchRequest {
|
||||
payload?: Record<string, unknown>;
|
||||
platform_task_id?: number;
|
||||
recharge_confirmation_token?: string;
|
||||
force_occupied?: boolean;
|
||||
}
|
||||
|
||||
export interface DouyuOccupiedForceCandidate {
|
||||
account_id: number;
|
||||
account_name: string;
|
||||
account_role: string;
|
||||
platform_task_id: number | null;
|
||||
platform_order_id: string;
|
||||
customer_role_name: string;
|
||||
sku_name: string;
|
||||
lease_batch_id: string;
|
||||
}
|
||||
|
||||
export interface DouyuTaskBatchResult {
|
||||
@@ -1036,6 +1048,8 @@ export interface DouyuTaskBatchResult {
|
||||
window_minutes?: number;
|
||||
amount?: number;
|
||||
account_names?: string[];
|
||||
requires_force_confirmation?: boolean;
|
||||
occupied_accounts?: DouyuOccupiedForceCandidate[];
|
||||
message?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -65,6 +65,8 @@ import type {
|
||||
DouyuCollabAccountLookup,
|
||||
DouyuCollabAccountRecommendation,
|
||||
DouyuCollabCkExportResult,
|
||||
DouyuCollabExchangeRecord,
|
||||
DouyuCollabExchangeRecordsResponse,
|
||||
DouyuCollabGift,
|
||||
DouyuCollabGoods,
|
||||
DouyuCollabMetric,
|
||||
@@ -189,6 +191,9 @@ export default function DouyuCollabPage() {
|
||||
const [detailOpen, setDetailOpen] = useState(false);
|
||||
const [detailMetrics, setDetailMetrics] = useState<DouyuCollabMetric[]>([]);
|
||||
const [detailTimeline, setDetailTimeline] = useState<DouyuCollabTimeline[]>([]);
|
||||
const [detailExchangeRecords, setDetailExchangeRecords] =
|
||||
useState<DouyuCollabExchangeRecordsResponse | null>(null);
|
||||
const [detailRecordsLoading, setDetailRecordsLoading] = useState(false);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
const handledQueryOrderIdRef = useRef(0);
|
||||
const queryOrderId = Number(searchParams.get('orderId') || 0);
|
||||
@@ -894,14 +899,16 @@ export default function DouyuCollabPage() {
|
||||
setDetailOpen(true);
|
||||
setDetailLoading(true);
|
||||
try {
|
||||
const [metrics, timeline, latest] = await Promise.all([
|
||||
const [metrics, timeline, latest, exchangeRecords] = await Promise.all([
|
||||
douyuCollabApi.metrics(orderId),
|
||||
douyuCollabApi.timeline(orderId),
|
||||
douyuCollabApi.getOrder(orderId),
|
||||
douyuCollabApi.exchangeRecords(orderId).catch(() => null),
|
||||
]);
|
||||
setDetailMetrics(metrics);
|
||||
setDetailTimeline(timeline);
|
||||
setDetail(latest);
|
||||
setDetailExchangeRecords(exchangeRecords);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
@@ -909,6 +916,23 @@ export default function DouyuCollabPage() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const refreshDetailExchangeRecords = async (order: DouyuCollabOrder) => {
|
||||
setDetailRecordsLoading(true);
|
||||
try {
|
||||
const res = await douyuCollabApi.queryExchangeRecords(order.id);
|
||||
setDetailExchangeRecords(res);
|
||||
if (res.error) {
|
||||
message.warning(res.error);
|
||||
} else {
|
||||
message.success(`已获取最新兑换记录 ${res.total} 条(命中 ${res.matched_count} 条)`);
|
||||
}
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setDetailRecordsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!canView || !Number.isInteger(queryOrderId) || queryOrderId <= 0) return;
|
||||
if (handledQueryOrderIdRef.current === queryOrderId) return;
|
||||
@@ -3023,6 +3047,123 @@ export default function DouyuCollabPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
background: token.colorBgContainer,
|
||||
border: `1px solid ${token.colorBorderSecondary}`,
|
||||
borderRadius: 8,
|
||||
padding: 16,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Space size={8} wrap>
|
||||
<Text strong>兑换记录明细</Text>
|
||||
<Tag>共 {detailExchangeRecords?.total ?? 0} 条</Tag>
|
||||
{(detailExchangeRecords?.matched_count ?? 0) > 0 && (
|
||||
<Tag color="green">命中 {detailExchangeRecords?.matched_count} 条</Tag>
|
||||
)}
|
||||
{detailExchangeRecords?.synced_at && (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
同步于 {formatTime(detailExchangeRecords.synced_at)}
|
||||
</Text>
|
||||
)}
|
||||
</Space>
|
||||
{canEdit && detail.account_exists && (
|
||||
<Button
|
||||
size="small"
|
||||
icon={<SearchOutlined />}
|
||||
loading={detailRecordsLoading}
|
||||
onClick={() => void refreshDetailExchangeRecords(detail)}
|
||||
>
|
||||
查询最新兑换记录
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{detailExchangeRecords?.error && (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
style={{ marginTop: 10 }}
|
||||
message={detailExchangeRecords.error}
|
||||
/>
|
||||
)}
|
||||
<div style={{ marginTop: 12 }}>
|
||||
{detailRecordsLoading && !detailExchangeRecords?.records.length ? (
|
||||
<Text type="secondary">正在查询最新兑换记录…</Text>
|
||||
) : detailExchangeRecords?.records.length ? (
|
||||
<Table<DouyuCollabExchangeRecord>
|
||||
size="small"
|
||||
pagination={false}
|
||||
scroll={{ y: 240 }}
|
||||
rowKey={(rec, index) => `${rec.commodity_id}-${rec.occurred_at || index}-${index}`}
|
||||
dataSource={detailExchangeRecords.records}
|
||||
columns={[
|
||||
{
|
||||
title: '礼包名称',
|
||||
dataIndex: 'commodity_name',
|
||||
render: (_: unknown, rec) => (
|
||||
<Space direction="vertical" size={0}>
|
||||
<Text strong={rec.matched}>{rec.commodity_name || '-'}</Text>
|
||||
{rec.commodity_id && (
|
||||
<Text type="secondary" style={{ fontSize: 11 }}>
|
||||
{rec.commodity_id}
|
||||
</Text>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '兑换角色',
|
||||
dataIndex: 'show_name',
|
||||
render: (_: unknown, rec) => rec.show_name || rec.role_name || '-',
|
||||
},
|
||||
{
|
||||
title: '积分 / 数量',
|
||||
width: 110,
|
||||
render: (_: unknown, rec) => (
|
||||
<Text>
|
||||
{rec.score ?? '-'} / ×{rec.exchange_num || 1}
|
||||
</Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '兑换时间',
|
||||
dataIndex: 'occurred_at',
|
||||
width: 165,
|
||||
render: (value: string | null) => formatTime(value),
|
||||
},
|
||||
{
|
||||
title: '判定',
|
||||
dataIndex: 'matched',
|
||||
width: 125,
|
||||
render: (_: unknown, rec) =>
|
||||
rec.matched ? (
|
||||
<Tag color="green">{rec.match_reason || '命中本单'}</Tag>
|
||||
) : (
|
||||
<Tag color={rec.match_reason === '其他礼包' ? 'default' : 'orange'}>
|
||||
{rec.match_reason || '未命中'}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
) : (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
description="暂无缓存兑换记录,点击右上角「查询最新兑换记录」实时获取"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Row gutter={16}>
|
||||
<Col xs={24} xl={12}>
|
||||
<div
|
||||
|
||||
@@ -188,6 +188,7 @@ const EVENT_LABELS: Record<string, string> = {
|
||||
douyu_operation_succeeded: '斗鱼操作成功',
|
||||
douyu_operation_failed: '斗鱼操作失败',
|
||||
douyu_operation_stopped: '斗鱼操作已停止',
|
||||
workbench_force_exchange: '工作台已强制执行兑换',
|
||||
task_cancelled: '任务已取消',
|
||||
task_restored: '恢复已取消任务',
|
||||
};
|
||||
@@ -461,6 +462,14 @@ function eventDescription(event: { eventType: string; detail: Record<string, unk
|
||||
const roleText = prev && prev !== next ? `${prev} → ${next}` : next;
|
||||
return `修改客户资料:${roleText}(${plat} / ${sys})${detail.reopenedBinding ? ';已重置失败状态待重扫' : ''}`;
|
||||
}
|
||||
if (event.eventType === 'workbench_force_exchange') {
|
||||
const op = String(detail.operatorUsername || '运营/管理员');
|
||||
const item = String(detail.goodsName || detail.commodityId || '-');
|
||||
const role = String(detail.accountRole || '-');
|
||||
const acc = String(detail.accountUsername || '-');
|
||||
const label = String(detail.taskLabel || detail.taskType || '兑换商品');
|
||||
return `${op} 在总工作台强制执行「${label}」:商品 ${item},账号 ${acc}(绑定角色 ${role},批次 ${String(detail.batchId || '-')})`;
|
||||
}
|
||||
if (event.eventType === 'task_created') return '订单已进入直播账号履约工作台';
|
||||
return '履约状态已更新';
|
||||
}
|
||||
|
||||
@@ -1043,6 +1043,7 @@ export default function DouyuTasksPage({
|
||||
accountIds?: number[],
|
||||
extraPayload: Record<string, unknown> = {},
|
||||
rechargeConfirmationToken?: string,
|
||||
forceOccupied = false,
|
||||
) => {
|
||||
const ids = accountIds || selectedIds;
|
||||
if (ids.length === 0) {
|
||||
@@ -1087,7 +1088,59 @@ export default function DouyuTasksPage({
|
||||
concurrency: batchConcurrency,
|
||||
payload,
|
||||
recharge_confirmation_token: rechargeConfirmationToken,
|
||||
force_occupied: forceOccupied || undefined,
|
||||
});
|
||||
if (result.requires_force_confirmation) {
|
||||
const occupiedRows = result.occupied_accounts || [];
|
||||
Modal.confirm({
|
||||
title: '确认账号与角色后强制发放',
|
||||
width: 560,
|
||||
content: (
|
||||
<Space direction="vertical" size={8} style={{ width: '100%' }}>
|
||||
<Text>{result.message || '以下账号当前由平台履约订单占用,确认斗鱼号与角色一致后可强制发放:'}</Text>
|
||||
{occupiedRows.map((item) => (
|
||||
<div
|
||||
key={item.account_id}
|
||||
style={{
|
||||
padding: '8px 10px',
|
||||
borderRadius: 6,
|
||||
border: '1px solid #d9d9d9',
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<Text strong>{item.account_name}</Text> · 当前绑定角色:
|
||||
<Text strong>{item.account_role || '未获取'}</Text>
|
||||
</div>
|
||||
<div style={{ marginTop: 2, color: '#666' }}>
|
||||
占用订单:{item.platform_order_id || item.lease_batch_id}
|
||||
{item.sku_name ? ` · 原商品:${item.sku_name}` : ''}
|
||||
{item.customer_role_name ? ` · 订单角色:${item.customer_role_name}` : ''}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{selectedXpdGoods?.name || selectedGoodsId ? (
|
||||
<Text type="secondary">
|
||||
即将发放商品:<Text strong>{selectedXpdGoods?.name || selectedGoodsId}</Text>(履约单保持当前状态,将在履约时间线留痕)
|
||||
</Text>
|
||||
) : null}
|
||||
</Space>
|
||||
),
|
||||
okText: '确认强制发放',
|
||||
okButtonProps: { danger: true },
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
await startTask(
|
||||
taskType,
|
||||
ids,
|
||||
extraPayload,
|
||||
rechargeConfirmationToken,
|
||||
true,
|
||||
);
|
||||
},
|
||||
});
|
||||
return null;
|
||||
}
|
||||
if (result.requires_confirmation) {
|
||||
const accountText = (result.account_names || []).join('、');
|
||||
Modal.confirm({
|
||||
|
||||
Reference in New Issue
Block a user