发布(0.4.6): 修复预售兑换记录判定与详情展示并新增工作台强制发放

This commit is contained in:
yml
2026-11-27 14:50:45 +08:00
parent 5006367217
commit e25e35994d
22 changed files with 1118 additions and 38 deletions
+2
View File
@@ -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",
+120 -1
View File
@@ -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
View File
@@ -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,
+26
View File
@@ -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] = []
+98 -1
View File
@@ -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",
]
+8 -1
View File
@@ -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)
+184 -20
View File
@@ -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:
+36 -9
View File
@@ -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
+22 -1
View File
@@ -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",