refactor: 收口跨平台重复业务实现

This commit is contained in:
yml
2026-11-13 20:35:38 +08:00
parent ad782e1954
commit f0abca3d58
25 changed files with 1386 additions and 724 deletions
+80 -63
View File
@@ -46,8 +46,12 @@ from ..models import (
User,
)
from .audit_service import record_audit
from .collab_common import (
apply_order_visibility,
)
from .file_service import build_file_url
from .file_storage import normalize_object_key
from .huya_activity_query import query_huya_activity
from .huya_points_center import (
fetch_points_center_catalog,
resolve_points_center_config,
@@ -134,7 +138,6 @@ STATUS_TIMESTAMP_FIELDS = {
}
# 归档(可见性)与业务状态正交:只允许归档已经抢购成功、不再需要日常操作的终态行。
ARCHIVE_SCOPES: tuple[str, ...] = ("active", "archived", "all")
ARCHIVABLE_STATUSES: tuple[str, ...] = (STATUS_DONE,)
# DB-only 的批量归档不需要像外部探针那样限 50 条。
ARCHIVE_BATCH_MAX = 5000
@@ -969,14 +972,15 @@ def _resolve_group_required_points(
group_orders: Sequence[HuyaExternalOrder],
*,
client: Any | None = None,
) -> tuple[list[str], str]:
) -> tuple[list[str], str, int, str]:
"""给组内缺少 ``required_points`` 的订单按礼包名补一次快照。
返回 ``(仍未解析的单号, 说明)``。只有真的缺数据时才打积分中心接口。
返回 ``(仍未解析的单号, 说明, 当前活动 SID, SID 来源)``。只有真的缺数据时
才打积分中心接口;同一轮后续积分查询复用这里发现的 SID。
"""
missing = [order for order in group_orders if order.required_points is None]
if not missing:
return [], ""
return [], "", 0, ""
source = next(
(
@@ -987,9 +991,12 @@ def _resolve_group_required_points(
None,
)
if source is None:
return [
order.order_no for order in missing
], "组内没有可用的 CK,无法解析礼包积分"
return (
[order.order_no for order in missing],
"组内没有可用的 CK,无法解析礼包积分",
0,
"",
)
result = fetch_points_center_catalog(
int(source.uid),
@@ -999,7 +1006,13 @@ def _resolve_group_required_points(
)
catalog, message = result.goods, result.message
if not catalog:
return [order.order_no for order in missing], message
sid = int(result.sid or resolve_gifts_sid(db))
return (
[order.order_no for order in missing],
message,
sid,
"queryAllocation" if result.sid else "config",
)
by_name = {
str(gift.get("name") or "").strip(): gift
@@ -1026,7 +1039,13 @@ def _resolve_group_required_points(
unresolved.append(order.order_no)
continue
order.required_points = int(gift["price"])
return unresolved, message
sid = int(result.sid or resolve_gifts_sid(db))
return (
unresolved,
message,
sid,
"queryAllocation" if result.sid else "config",
)
def _check_recharge_group(
@@ -1089,11 +1108,13 @@ def _check_recharge_group(
code="bind_account_changed",
)
unresolved, catalog_message = _resolve_group_required_points(
db,
current,
group_orders,
client=client,
unresolved, catalog_message, current_sid, current_sid_source = (
_resolve_group_required_points(
db,
current,
group_orders,
client=client,
)
)
if unresolved:
raise CollabError(
@@ -1113,6 +1134,8 @@ def _check_recharge_group(
client=client,
source=score_source,
commit=False,
current_sid=current_sid,
current_sid_source=current_sid_source,
)
score = result.get("score")
if not result.get("ok") or score is None:
@@ -1888,11 +1911,10 @@ def probe_ck(order: HuyaExternalOrder, *, client: Any | None = None) -> CkProbeR
def resolve_gifts_sid(db: Session) -> int:
"""当前活动 SID:**优先用工作台配置**(``huya_config.sid``),读不到再回落到默认值。
"""读取工作台配置的 SID 兜底值。
2026-10-16 真机定位:礼包接口的 SID 是「活动 ID」,会随活动轮换(9 月 2203 → 今天 2277),
对旧 SID 打过去是 ``status=200`` + 0 个商品 —— 界面上就表现为「礼包列表空白」。
工作台「虎牙配置」里改过 SID 之后,这里跟着变,不用改代码。
正常查询必须先走 :mod:`huya_activity_query`,从 ``queryAllocation`` 自动
发现当前 SID;本函数只在该接口不可用时提供兼容回退,不能再作为首选来源。
只读:配置行不存在时**不会**顺手建一行(预览是只读动作,设计文档 §2.3)。
"""
@@ -2201,6 +2223,8 @@ def query_order_activity(
client: Any | None = None,
source: str = "manual",
commit: bool = True,
current_sid: int = 0,
current_sid_source: str = "",
) -> dict:
"""查一次这个账号的**积分 / 兑换记录**,落一条生命周期快照,必要时自动改状态。
@@ -2238,31 +2262,23 @@ def query_order_activity(
if not uid or not cookie:
raise CollabError("这行还没有 CK,先贴一份再查积分/兑换记录", code="no_cookie")
sid = resolve_gifts_sid(db)
activity_client = client or _build_probe_client()
score_resp: Any = None
records_resp: Any = None
errors: list[str] = []
if want_score:
try:
score_resp = activity_client.query_user_score(
uid=int(uid),
cookie=cookie,
sid=sid,
timeout=ACTIVITY_QUERY_TIMEOUT_SECONDS,
)
except Exception as exc: # noqa: BLE001 一个接口炸了不影响另一个
errors.append(f"积分接口异常:{type(exc).__name__}: {_clip(exc)}")
if want_records:
try:
records_resp = activity_client.get_user_prize_records(
uid=int(uid),
cookie=cookie,
sid=sid,
timeout=ACTIVITY_QUERY_TIMEOUT_SECONDS,
)
except Exception as exc: # noqa: BLE001
errors.append(f"兑换记录接口异常:{type(exc).__name__}: {_clip(exc)}")
activity = query_huya_activity(
activity_client,
uid=int(uid),
cookie=cookie,
config_info=resolve_points_center_config(db),
configured_sid=resolve_gifts_sid(db),
current_sid=current_sid,
current_sid_source=current_sid_source,
want_score=want_score,
want_records=want_records,
timeout=ACTIVITY_QUERY_TIMEOUT_SECONDS,
)
sid = activity.sid
score_resp = activity.score_response
records_resp = activity.records_response
errors = activity.errors
score, gained, used, score_msg = (
_extract_score(score_resp) if want_score else (None, None, None, "")
@@ -2423,6 +2439,7 @@ def query_order_activity(
"order_no": order.order_no,
"uid": uid,
"sid": sid,
"sid_source": activity.sid_source,
"scope": scope,
"scope_label": ACTIVITY_SCOPE_LABELS.get(scope, scope),
"verdict": verdict,
@@ -2468,6 +2485,8 @@ def query_activity_batch(
)
results: list[dict] = []
current_sid = 0
current_sid_source = ""
for index, order in enumerate(rows):
if index and interval_seconds > 0:
time.sleep(interval_seconds)
@@ -2482,8 +2501,13 @@ def query_activity_batch(
client=client,
source="batch",
commit=False,
current_sid=current_sid,
current_sid_source=current_sid_source,
)
)
if not current_sid and results:
current_sid = int(results[-1].get("sid") or 0)
current_sid_source = str(results[-1].get("sid_source") or "")
except CollabError as exc:
results.append(
{
@@ -3714,12 +3738,6 @@ ORDER_SORT_KEYS: tuple[str, ...] = (
)
def normalize_archive_scope(value: str | None) -> str:
"""归档可见范围:默认只看活跃行,归档视图只返回已归档行。"""
scope = str(value or "active").strip().lower()
return scope if scope in ARCHIVE_SCOPES else "active"
def _filtered_orders_query(
db: Session,
*,
@@ -3745,13 +3763,13 @@ def _filtered_orders_query(
skin = (gift_name or "").strip()
if skin:
query = query.filter(HuyaExternalOrder.gift_name == skin)
if not include_void:
query = query.filter(HuyaExternalOrder.status != STATUS_VOID)
scope = normalize_archive_scope(archive_scope)
if scope == "active":
query = query.filter(HuyaExternalOrder.archived_at.is_(None))
elif scope == "archived":
query = query.filter(HuyaExternalOrder.archived_at.is_not(None))
query = apply_order_visibility(
query,
HuyaExternalOrder,
archive_scope=archive_scope,
include_void=include_void,
void_status=STATUS_VOID,
)
text = (keyword or "").strip()
if text:
like = f"%{text}%"
@@ -4039,14 +4057,13 @@ def summary(
db: Session, *, include_void: bool = False, archive_scope: str = "active"
) -> dict:
"""页头统计条:统计口径与当前列表的归档/作废过滤保持一致。"""
scope = normalize_archive_scope(archive_scope)
query = db.query(HuyaExternalOrder)
if not include_void:
query = query.filter(HuyaExternalOrder.status != STATUS_VOID)
if scope == "active":
query = query.filter(HuyaExternalOrder.archived_at.is_(None))
elif scope == "archived":
query = query.filter(HuyaExternalOrder.archived_at.is_not(None))
query = apply_order_visibility(
db.query(HuyaExternalOrder),
HuyaExternalOrder,
archive_scope=archive_scope,
include_void=include_void,
void_status=STATUS_VOID,
)
status_rows = (
query.with_entities(HuyaExternalOrder.status, func.count(HuyaExternalOrder.id))