发布(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
+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: