# ruff: noqa: F401 """虎牙外部 CK 协作台账的服务层(模型:``models.HuyaExternalOrder``)。 设计见 ``docs/设计-虎牙外部CK协作台账.md``。改这里之前先读文档 §2.3 与 §10.2, 两条边界不是 bug: 1. **不写 ``huya_accounts``、不做外键**:CK 独立存本表; 2. **不 import 任何任务执行器**(``huya_runner*`` / ``huya_tasks``): 绑定/充值/上脚本都在别的工具里做,本表只记录结果。 S5 的探针只 import ``core.huya.http_client``(只读 RPC),同样不碰 runner。 本模块是**两套状态机的唯一写入口**(设计文档 §4.3 防漂移): - ``set_status()`` —— 业务进度 ``status`` - ``set_ck_status()`` / ``set_ck()`` / ``rebuild_ck()`` —— 凭据状态 ``ck_status`` 接口层不允许直接改这两个列,否则状态与时间戳会各自漂移。 """ from __future__ import annotations import dataclasses import hashlib import time from collections.abc import Mapping, Sequence from datetime import UTC, datetime, timedelta from typing import Any from loguru import logger from sqlalchemy import func, or_, tuple_ from sqlalchemy.orm import Session from core.huya.http_client import query_bind_game_account from ..huya_defaults import ( HUYA_DEFAULT_BIND_GID, HUYA_DEFAULT_OUTER_ACT_ID, HUYA_DEFAULT_SID, ) from ..models import ( HuyaCollabGiftCatalog, HuyaCollabShop, HuyaConfig, HuyaExternalOrder, HuyaExternalOrderMetric, User, ) from .audit_service import record_audit from .collab_common import ( apply_order_visibility, ) from .file_service import build_file_url from .huya_activity_query import query_huya_activity from .huya_collab_catalog import ( _catalog_points_for_name, create_gift, delete_gift, frequent_gift_names, get_gift, list_gift_names, list_gift_records, serialize_gift, update_gift, ) from .huya_collab_ck import ( _apply_ck, brief_order, parse_ck, rebuild_ck, set_ck, set_ck_status, set_manual_ck_status, uid_used_orders, uids_in_use, ) from .huya_collab_common import ( ACTIVITY_SCOPE_BOTH, ACTIVITY_SCOPE_LABELS, ACTIVITY_SCOPE_RECORDS, ACTIVITY_SCOPE_SCORE, ACTIVITY_SCOPES, ARCHIVABLE_STATUSES, ARCHIVE_BATCH_MAX, CK_CHECKED_STATUSES, CK_DISABLED, CK_INVALID, CK_STATUS_LABELS, CK_STATUSES, CK_UNVERIFIED, CK_VALID, EDITABLE_FIELDS, IMAGE_SLOT_LABELS, IMAGE_SLOTS, NEXT_STATUS, ORDER_STATUS_LABELS, ORDER_STATUSES, PROBE_BATCH_MAX, RECHARGE_POINTS_CONFIRM_DELAY_SECONDS, RECHARGE_POINTS_THRESHOLD_DEFAULT, STAGE_INDEX, STATUS_DONE, STATUS_FAILED, STATUS_INCOMPLETE, STATUS_POINTS_ERROR, STATUS_RECHARGED, STATUS_SCRIPTED, STATUS_TIMESTAMP_FIELDS, STATUS_TO_RECHARGE, STATUS_VOID, VERDICT_FAILED, VERDICT_LABELS, VERDICT_NOT_QUERIED, VERDICT_SUCCESS, VERDICT_UNKNOWN, CollabError, _audit_target, _clean_owner_id, _clean_required_points, _now, _touch, assert_order_mutable, assert_version, clean_text, images_of, is_forward_status, look_like_web_cookie, normalize_images, normalize_points_threshold, ) from .huya_collab_exports import export_cks from .huya_collab_query import ( OrderMetricView, archive_orders, archive_orders_by_filter, buyer_clusters, buyer_key_of, latest_metrics, list_metrics, list_orders, list_orders_by_ids, list_orders_for_archive, order_metric_views, serialize_metric, serialize_order, summary, unarchive_orders, user_names, users_by_id, ) from .huya_collab_shops import ( create_shop, delete_shop, ensure_shops_registered, get_shop, list_shop_records, list_shops, normalize_shop_name, serialize_shop, update_shop, ) from .huya_points_center import ( fetch_points_center_catalog, resolve_points_center_config, ) from .huya_service import ( build_web_cookie_from_raw, parse_huya_cookie_line, ) def _assert_order_no_available( db: Session, order_no: str, *, exclude_id: int | None = None ) -> None: query = db.query(HuyaExternalOrder).filter(HuyaExternalOrder.order_no == order_no) if exclude_id is not None: query = query.filter(HuyaExternalOrder.id != exclude_id) other = query.first() if other is not None: raise CollabError( f"订单编号 {order_no} 已被第 {other.id} 行占用", status_code=409, code="order_no_conflict", ) # -------------------------------------------------------------------------- # 业务状态机 # -------------------------------------------------------------------------- def _missing_recharge_data( order: HuyaExternalOrder, *, require_ck_valid: bool ) -> list[str]: """「待充值」所需资料;返回缺失项(空列表 = 齐全)。""" missing: list[str] = [] if not str(order.cookie or "").strip(): missing.append("外部 CK") elif require_ck_valid and order.ck_status != CK_VALID: missing.append("CK 验证有效(先贴 CK 让它自动探针读一次)") if not str(order.bind_game_account or "").strip(): missing.append("绑定账号(先贴 CK 让探针读一次)") if not str(order.bind_game_role or "").strip(): missing.append("绑定角色(先贴 CK 让探针读一次)") if not str(order.gift_name or "").strip(): missing.append("礼包名") if not images_of(order, "home_images"): missing.append("主页截图(至少 1 张)") return missing def _is_ready_for_recharge(order: HuyaExternalOrder) -> bool: return not _missing_recharge_data(order, require_ck_valid=True) def _assert_can_leave_incomplete(order: HuyaExternalOrder) -> None: """离开「待补资料」的前置校验:客户资料必须齐全。""" missing = _missing_recharge_data(order, require_ck_valid=False) if missing: raise CollabError( f"「{ORDER_STATUS_LABELS[STATUS_INCOMPLETE]}」还不能往前改,缺少:{'、'.join(missing)}", code="incomplete_precondition", ) def _assert_can_enter_to_recharge(order: HuyaExternalOrder) -> None: missing = _missing_recharge_data(order, require_ck_valid=True) if missing: raise CollabError( f"还不能进入「{ORDER_STATUS_LABELS[STATUS_TO_RECHARGE]}」,缺少:{'、'.join(missing)}", code="to_recharge_precondition", ) def _maybe_advance_to_recharge( db: Session, current: User | None, order: HuyaExternalOrder, *, commit: bool = False, ) -> bool: """资料齐全且 CK 有效时,把 ``incomplete`` 自动推进到 ``to_recharge``。""" if order.status != STATUS_INCOMPLETE or not _is_ready_for_recharge(order): return False now = _now() order.status = STATUS_TO_RECHARGE if order.bound_at is None: order.bound_at = now _sync_stage_timestamps(order, STATUS_TO_RECHARGE, now) _touch(order, current) record_audit( db, current, action="huya:collab:status_auto", target=_audit_target(order), detail={ "from": STATUS_INCOMPLETE, "to": STATUS_TO_RECHARGE, "reason": "data_complete", "order_no": order.order_no, }, ) if commit: db.commit() db.refresh(order) return True def _maybe_demote_missing_data( db: Session, current: User | None, order: HuyaExternalOrder, ) -> bool: """待充值/积分异常的单子如果关键资料被清空,退回「待补资料」。 注意:CK 失效不等于资料缺失,不触发降级;只有 CK/绑定账号/角色/礼包/截图 这些“没有就无法处理”的字段为空时才退回。 """ if order.status not in (STATUS_TO_RECHARGE, STATUS_POINTS_ERROR): return False if not _missing_recharge_data(order, require_ck_valid=False): return False from_status = order.status order.status = STATUS_INCOMPLETE order.recharged_at = None order.scripted_at = None order.done_at = None _touch(order, current) record_audit( db, current, action="huya:collab:status_auto", target=_audit_target(order), detail={ "from": from_status, "to": STATUS_INCOMPLETE, "reason": "data_missing", "order_no": order.order_no, }, ) return True def _sync_stage_timestamps( order: HuyaExternalOrder, target: str, now: datetime ) -> None: """让各阶段时间戳与目标状态保持一致。""" if target in (STATUS_VOID, STATUS_FAILED): return if target == STATUS_POINTS_ERROR: # 充值动作已经发生,只是积分不匹配;保留/补上充值时间,清掉后续阶段。 if order.recharged_at is None: order.recharged_at = now order.scripted_at = None order.done_at = None return target_index = STAGE_INDEX[target] for stage, field in STATUS_TIMESTAMP_FIELDS.items(): if STAGE_INDEX[stage] <= target_index: if getattr(order, field) is None: setattr(order, field, now) else: setattr(order, field, None) def set_status( db: Session, current: User | None, order: HuyaExternalOrder, target: str, *, reason: str = "", rollback: bool = False, force: bool = False, allow_recharge: bool = False, auto_verify_ck: bool = False, client: Any | None = None, commit: bool = True, ) -> dict: """推进/回退业务状态(本模块唯一的 ``status`` 写入口)。 ``recharged`` / ``points_error`` 只能由充值核账流程写入(``allow_recharge=True``); 普通人工状态接口不允许绕过核账。 ``auto_verify_ck=True`` 时,进入「待充值」若 CK 尚未有效,会先自动跑一次只读探针, 用户不需要再单独点「验证 CK」。 ``force=True`` 仅用于超级管理员把 ``void`` 恢复到流程内:必须填写原因, 只跳过“作废不可逆”限制,不绕过资料完整性与核账校验。 """ if target not in ORDER_STATUSES: raise CollabError(f"未知状态:{target}", code="status_unknown") if target in (STATUS_RECHARGED, STATUS_POINTS_ERROR) and not allow_recharge: raise CollabError( "「已充值 / 积分异常」必须通过充值核账流程写入", code="recharge_check_required", ) assert_order_mutable(order) if target == order.status: return {} from_status = order.status force_applied = False force_reason = "" if force: if current is None or current.role != "super_admin": raise CollabError( "只有超级管理员可以强制恢复已作废的订单", status_code=403, code="force_admin_required", ) if from_status == STATUS_VOID: force_reason = clean_text(reason, field="force_reason", required=True) force_applied = True forward = is_forward_status(from_status, target) if not forward: if force_applied: pass elif not rollback: next_status = NEXT_STATUS.get(from_status) hint = ( f"要往前的话下一步是「{ORDER_STATUS_LABELS[next_status]}」(也可以直接跳到更后面的状态)" if next_status else "这单已经走到终点" ) raise CollabError( f"不能把「{ORDER_STATUS_LABELS.get(from_status, from_status)}」改回" f"「{ORDER_STATUS_LABELS[target]}」({hint});确实要回退请显式勾选「回退」", code="status_not_forward", ) elif from_status == STATUS_VOID: raise CollabError( "已作废的单子不能改回流程内状态,请编辑或新建", code="status_from_void", ) if target == STATUS_TO_RECHARGE and auto_verify_ck and order.ck_status != CK_VALID: # 工作台改状态时自动跑一次只读探针:用户不必先手工点「验证 CK」。 probe = verify_ck(db, current, order, client=client, commit=False) if not probe.get("ok"): raise CollabError( f"CK 验证失败:{probe.get('message') or '未知原因'}", code="ck_invalid", ) if from_status == STATUS_INCOMPLETE and target not in ( STATUS_VOID, STATUS_FAILED, ): _assert_can_leave_incomplete(order) if target == STATUS_TO_RECHARGE: _assert_can_enter_to_recharge(order) now = _now() previous_void_reason = order.void_reason or "" if target == STATUS_VOID: order.void_reason = clean_text(reason, field="void_reason", required=True) else: order.void_reason = "" order.status = target if target == STATUS_TO_RECHARGE and order.bound_at is None: order.bound_at = now _sync_stage_timestamps(order, target, now) _touch(order, current) record_audit( db, current, action="huya:collab:status", target=_audit_target(order), detail={ "from": from_status, "to": target, "rollback": bool(not forward), "reason": order.void_reason, "force": force_applied, "force_reason": force_reason, "previous_void_reason": previous_void_reason if force_applied else "", "order_no": order.order_no, "allow_recharge": bool(allow_recharge), }, ) if target == STATUS_VOID or from_status == STATUS_VOID: _invalidate_recharge_group_after_void( db, current, order, changed_from=from_status, changed_to=target, ) if commit: db.commit() db.refresh(order) return {"from": from_status, "to": target} def set_status_batch( db: Session, current: User | None, orders: Sequence[HuyaExternalOrder], target: str, *, reason: str = "", rollback: bool = False, force: bool = False, auto_verify_ck: bool = False, client: Any | None = None, ) -> dict: """批量改状态:勾选多行一次切到同一个状态(部分失败不影响其它行)。 逐行用 SAVEPOINT 隔离(同 :func:`import_orders` 的做法):某一行因为前置校验没过 (例如资料不全进不了「待充值」)只记在这一条的 ``message`` 里,整体不整体失败。 ``auto_verify_ck=True`` 会透传给单行状态机,在进入「待充值」前自动补做 CK 探针。 上限与批量验证一致(``PROBE_BATCH_MAX``)—— 一次别点太多,人会看不过来。 """ rows = list(orders) if not rows: raise CollabError("请先勾选要改状态的行", code="status_batch_empty") if target in (STATUS_RECHARGED, STATUS_POINTS_ERROR): raise CollabError( "「已充值 / 积分异常」必须通过充值核账流程写入", code="recharge_check_required", ) if len(rows) > PROBE_BATCH_MAX: raise CollabError( f"一次最多改 {PROBE_BATCH_MAX} 行,请分批操作", code="status_batch_too_large", ) results: list[dict] = [] updated = 0 for order in rows: try: with db.begin_nested(): change = set_status( db, current, order, target, reason=reason, rollback=rollback, force=force, auto_verify_ck=auto_verify_ck, client=client, commit=False, ) except CollabError as exc: results.append( { "id": int(order.id), "order_no": order.order_no, "ok": False, "message": exc.detail, } ) continue if change: updated += 1 results.append( { "id": int(order.id), "order_no": order.order_no, "ok": True, "message": ( f"{ORDER_STATUS_LABELS.get(change['from'], change['from'])}" f" → {ORDER_STATUS_LABELS.get(change['to'], change['to'])}" if change else "已经是这个状态" ), } ) db.commit() for order in rows: db.refresh(order) return { "total": len(rows), "updated": updated, "failed": len(rows) - updated, "target": target, "results": results, } # -------------------------------------------------------------------------- # 充值核账(按「绑定账号 + 绑定角色」整组) # -------------------------------------------------------------------------- RECHARGE_GROUP_STATUSES: tuple[str, ...] = ( STATUS_TO_RECHARGE, STATUS_RECHARGED, STATUS_POINTS_ERROR, ) _POINTS_SNAPSHOT_FIELDS: tuple[str, ...] = ( "points_checked_at", "points_balance", "points_required_total", "points_surplus", "points_threshold", "points_check_reason", "points_check_message", "points_check_detail", ) _STALE_RECHARGE_MESSAGE = "订单组成员已作废或恢复,原积分统计已失效,请重新核账" # 探针读到的 bind_game_account 往往是「微信用户 / QQ用户」这种通用昵称, # 只按它分组会把不同买家并成一组(2026-10-19 生产 8 单被合成 48000 分)。 # 与「同一买家」软识别保持一致:账号 + 角色才是可用的买家指纹。 RechargeGroupKey = tuple[str, str] def _recharge_group_key(order: HuyaExternalOrder) -> RechargeGroupKey | None: return buyer_key_of(order) def _recharge_group_label(group_key: RechargeGroupKey) -> str: return f"{group_key[0]} / {group_key[1]}" def _preflight_recharge_binding( db: Session, current: User | None, orders: Sequence[HuyaExternalOrder], *, client: Any | None, ) -> tuple[set[int], set[int], list[dict[str, Any]]]: """核账前自动刷新绑定快照,并拦下真正发生换绑的订单。 返回 ``(verified_uids, failed_ids, failures)``。快照更新保留在本次事务里; 即使随后因换绑中止核账,也会在调用方统一提交,用户下次核账不必再手工验证。 """ by_uid: dict[str, list[HuyaExternalOrder]] = {} for order in orders: uid = str(order.uid or "").strip() if uid: by_uid.setdefault(uid, []).append(order) verified_uids: set[int] = set() failed_ids: set[int] = set() failures: list[dict[str, Any]] = [] for uid_text, rows in by_uid.items(): representative = rows[0] if not str(representative.cookie or "").strip(): continue before_by_id = { int(order.id): ( str(order.bind_game_account or ""), str(order.bind_game_role or ""), ) for order in rows } try: probe = verify_ck( db, current, representative, client=client, commit=False, ) except CollabError as exc: for order in rows: failures.append( { "id": int(order.id), "order_no": order.order_no, "message": exc.detail, } ) failed_ids.add(int(order.id)) continue if not probe.get("ok"): message = f"CK 验证失败:{probe.get('message') or '未知原因'}" for order in rows: failures.append( { "id": int(order.id), "order_no": order.order_no, "message": message, } ) failed_ids.add(int(order.id)) continue binding = probe.get("binding") or {} after_identity = ( str(binding.get("bind_game_account") or ""), str(binding.get("bind_game_role") or ""), ) changed = [ order for order in rows if before_by_id[int(order.id)] != after_identity ] if changed: before_label = " / ".join( str(part or "-") for part in before_by_id[int(changed[0].id)] ) after_label = " / ".join(str(part or "-") for part in after_identity) for order in rows: failures.append( { "id": int(order.id), "order_no": order.order_no, "message": ( "CK 已自动刷新,绑定由 " f"「{before_label}」变为「{after_label}」;" "本次未核账,请确认角色后重试" ), } ) failed_ids.add(int(order.id)) continue verified_uids.add(int(uid_text)) return verified_uids, failed_ids, failures def _recharge_group_orders( db: Session, group_key: RechargeGroupKey ) -> list[HuyaExternalOrder]: return ( db.query(HuyaExternalOrder) .filter( HuyaExternalOrder.bind_game_account == group_key[0], HuyaExternalOrder.bind_game_role == group_key[1], HuyaExternalOrder.status.in_(RECHARGE_GROUP_STATUSES), ) .order_by(HuyaExternalOrder.id.asc()) .all() ) def _clear_points_snapshot(order: HuyaExternalOrder) -> None: order.points_checked_at = None order.points_balance = None order.points_required_total = None order.points_surplus = None order.points_threshold = None order.points_check_reason = "" order.points_check_message = "" order.points_check_detail = None def _invalidate_recharge_group_after_void( db: Session, current: User | None, changed_order: HuyaExternalOrder, *, changed_from: str, changed_to: str, ) -> None: """订单作废/恢复后,让同组旧核账结果失效,避免继续展示作废前的合计。""" group_key = buyer_key_of(changed_order) if group_key is None: return rows = ( db.query(HuyaExternalOrder) .filter( HuyaExternalOrder.bind_game_account == group_key[0], HuyaExternalOrder.bind_game_role == group_key[1], or_( HuyaExternalOrder.id == changed_order.id, HuyaExternalOrder.status.in_(RECHARGE_GROUP_STATUSES), ), ) .order_by(HuyaExternalOrder.id.asc()) .all() ) now = _now() for row in rows: previous_status = row.status previous_snapshot = { field: getattr(row, field) for field in ( "points_checked_at", "points_balance", "points_required_total", "points_surplus", ) } had_snapshot = any( getattr(row, field) not in (None, "") for field in _POINTS_SNAPSHOT_FIELDS ) next_status = previous_status if ( row.id != changed_order.id and previous_status in (STATUS_RECHARGED, STATUS_POINTS_ERROR) and had_snapshot and _is_ready_for_recharge(row) ): next_status = STATUS_TO_RECHARGE row.status = next_status if row.bound_at is None: row.bound_at = now _sync_stage_timestamps(row, next_status, now) if not had_snapshot and next_status == previous_status: continue _clear_points_snapshot(row) row.points_check_reason = "stale_group" row.points_check_message = _STALE_RECHARGE_MESSAGE _touch(row, current) record_audit( db, current, action="huya:collab:recharge_invalidate", target=_audit_target(row), detail={ "source_order_no": changed_order.order_no, "source_change": f"{changed_from}->{changed_to}", "group_key": _recharge_group_label(group_key), "from_status": previous_status, "to_status": next_status, "previous": previous_snapshot, }, ) def _resolve_group_required_points( db: Session, current: User | None, group_orders: Sequence[HuyaExternalOrder], *, client: Any | None = None, ) -> 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 [], "", 0, "" source = next( ( order for order in group_orders if str(order.uid or "").strip() and str(order.cookie or "").strip() ), None, ) if source is None: return ( [order.order_no for order in missing], "组内没有可用的 CK,无法解析礼包积分", 0, "", ) result = fetch_points_center_catalog( int(source.uid), str(source.cookie), client=client or _build_probe_client(), **resolve_points_center_config(db), ) catalog, message = result.goods, result.message if not catalog: 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 for gift in catalog if gift.get("name") and gift.get("price") is not None } unresolved: list[str] = [] for order in missing: wanted = str(order.gift_name or "").strip() gift = by_name.get(wanted) if gift is None and len(wanted) >= 2: candidates = [ item for item in catalog if item.get("price") is not None and ( wanted in str(item.get("name") or "") or str(item.get("name") or "") in wanted ) ] if len(candidates) == 1: gift = candidates[0] if gift is None: unresolved.append(order.order_no) continue order.required_points = int(gift["price"]) sid = int(result.sid or resolve_gifts_sid(db)) return ( unresolved, message, sid, "queryAllocation" if result.sid else "config", ) def _check_recharge_group( db: Session, current: User | None, group_key: RechargeGroupKey, *, threshold: int, client: Any | None = None, confirm_points_error: bool = True, confirmation: Mapping[str, Any] | None = None, score_source: str = "recharge_check", verified_uids: set[int] | None = None, ) -> dict: group_label = _recharge_group_label(group_key) group_orders = _recharge_group_orders(db, group_key) if not group_orders: raise CollabError( f"绑定账号「{group_label}」下没有可核账的订单", code="recharge_group_empty", ) if any(_recharge_group_key(order) != group_key for order in group_orders): raise CollabError( "核账过程中绑定账号/角色发生变化,请刷新后重试", code="bind_account_changed", ) # 同一 uid 只验一次 CK;组内多单共用一份 CK 时不重复打接口。 representatives: dict[str, HuyaExternalOrder] = {} missing_ck: list[str] = [] for order in group_orders: uid = str(order.uid or "").strip() cookie = str(order.cookie or "").strip() if not uid or not cookie: missing_ck.append(order.order_no) continue representatives.setdefault(uid, order) if missing_ck: raise CollabError( "组内订单缺少 CK,无法核账:" + "、".join(missing_ck[:10]) + (" ..." if len(missing_ck) > 10 else ""), code="no_cookie", ) if not representatives: raise CollabError( "组内没有可用 CK,无法核账", code="no_cookie", ) for uid, order in representatives.items(): if verified_uids is not None and int(uid) in verified_uids: continue result = verify_ck(db, current, order, client=client, commit=False) if not result.get("ok"): raise CollabError( f"{order.order_no} 的 CK 验证失败:{result.get('message') or '未知原因'}", code="ck_invalid", ) if _recharge_group_key(order) != group_key: raise CollabError( "核账过程中探针读到的绑定账号/角色发生变化,请刷新后重试", code="bind_account_changed", ) unresolved, catalog_message, current_sid, current_sid_source = ( _resolve_group_required_points( db, current, group_orders, client=client, ) ) if unresolved: raise CollabError( "缺少礼包所需积分,无法核账:" + "、".join(unresolved[:10]) + (f"({catalog_message})" if catalog_message else ""), code="required_points_missing", ) uid_scores: dict[str, int] = {} for uid, order in representatives.items(): result = query_order_activity( db, current, order, scope=ACTIVITY_SCOPE_SCORE, 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: raise CollabError( f"{order.order_no} 的积分查询失败:{result.get('message') or '没有拿到积分'}", code="points_query_failed", ) uid_scores[uid] = int(score) balance = sum(uid_scores.values()) required_total = sum(int(order.required_points or 0) for order in group_orders) surplus = balance - required_total if surplus < 0: result_status = STATUS_POINTS_ERROR reason = "shortage" message = f"积分异常:账号积分 {balance},礼包合计 {required_total},还差 {-surplus} 分" elif surplus > threshold: result_status = STATUS_POINTS_ERROR reason = "excess" message = ( f"积分异常:账号积分 {balance},礼包合计 {required_total}," f"多出 {surplus} 分(阈值 {threshold})" ) else: result_status = STATUS_RECHARGED reason = "ok" message = ( f"核账通过:账号积分 {balance},礼包合计 {required_total}," f"结余 {surplus} 分(阈值 {threshold})" ) if result_status == STATUS_POINTS_ERROR and not confirm_points_error: return { "_needs_confirmation": True, "group_key": group_label, "bind_game_account": group_key[0], "bind_game_role": group_key[1], "threshold": threshold, "balance": balance, "required_total": required_total, "surplus": surplus, "reason": reason, "message": message, "order_ids": [int(order.id) for order in group_orders], } now = _now() detail = { "group_key": group_label, "bind_game_account": group_key[0], "bind_game_role": group_key[1], "threshold": threshold, "balance": balance, "required_total": required_total, "surplus": surplus, "reason": reason, "uids": [ { "uid": uid, "score": score, "order_nos": [ order.order_no for order in group_orders if str(order.uid or "").strip() == uid ], } for uid, score in uid_scores.items() ], "orders": [ { "id": int(order.id), "order_no": order.order_no, "gift_name": order.gift_name or "", "required_points": order.required_points, } for order in group_orders ], } if confirmation: detail["confirmation"] = dict(confirmation) for order in group_orders: set_status( db, current, order, result_status, allow_recharge=True, commit=False, ) order.points_checked_at = now order.points_balance = balance order.points_required_total = required_total order.points_surplus = surplus order.points_threshold = threshold order.points_check_reason = reason order.points_check_message = message[:512] order.points_check_detail = detail _touch(order, current) record_audit( db, current, action="huya:collab:recharge_check", target=_audit_target(order), detail={ "order_no": order.order_no, "group_key": group_label, "bind_game_account": group_key[0], "bind_game_role": group_key[1], "status": result_status, "balance": balance, "required_total": required_total, "surplus": surplus, "threshold": threshold, "reason": reason, "order_ids": [int(item.id) for item in group_orders], }, ) return { "group_key": group_label, "status": result_status, "status_label": ORDER_STATUS_LABELS.get(result_status, result_status), "balance": balance, "required_total": required_total, "surplus": surplus, "threshold": threshold, "reason": reason, "message": message, "order_ids": [int(order.id) for order in group_orders], "orders": [ { "id": int(order.id), "order_no": order.order_no, "status": order.status, "status_label": ORDER_STATUS_LABELS.get(order.status, order.status), } for order in group_orders ], } def _failed_recharge_group_result( group_key: RechargeGroupKey, group_orders: Sequence[HuyaExternalOrder], *, threshold: int, message: str, ) -> dict: return { "group_key": _recharge_group_label(group_key), "status": "", "status_label": "", "balance": None, "required_total": None, "surplus": None, "threshold": threshold, "reason": "error", "message": message, "order_ids": [int(order.id) for order in group_orders], "orders": [], } def check_recharge_groups( db: Session, current: User | None, orders: Sequence[HuyaExternalOrder], *, threshold: Any = RECHARGE_POINTS_THRESHOLD_DEFAULT, client: Any | None = None, confirm_delay_seconds: float = RECHARGE_POINTS_CONFIRM_DELAY_SECONDS, commit: bool = True, ) -> dict: """按「``bind_game_account`` + ``bind_game_role``」整组核账,并整组落到「已充值 / 积分异常」。 规则(2026-10-19 用户拍板,随后按生产数据修正分组键): - 分组键必须是**账号 + 角色**:探针读到的账号经常是「微信用户 / QQ用户」这种 通用昵称,只按账号会把不同买家并成一组(生产 8 单被合成 48000 分); - 只统计同组 ``to_recharge / recharged / points_error`` 的订单; - 组内不同 uid 的 CK 各查一次积分,合计为“账号积分”; - 核账前统一自动刷新绑定快照;如角色发生换绑,只保存新快照并中止,待人工确认; - ``结余 = 账号积分合计 - 礼包积分合计``; - ``结余 < 0`` 或 ``结余 > 阈值`` → 整组 ``points_error``; - 其余 → 整组 ``recharged``; - CK 失效 / 积分查询失败 / 缺少所需积分:整组保持原状态并报错,不误判成积分异常。 """ rows = list(orders) if not rows: raise CollabError("请先选择要核账的订单", code="recharge_empty") if len(rows) > PROBE_BATCH_MAX: raise CollabError( f"一次最多核账 {PROBE_BATCH_MAX} 条,请分批操作", code="recharge_too_large", ) threshold_value = normalize_points_threshold(threshold) group_keys: list[RechargeGroupKey] = [] failures: list[dict] = [] eligible_rows: list[HuyaExternalOrder] = [] for order in rows: key = _recharge_group_key(order) if key is None: _maybe_demote_missing_data(db, current, order) failures.append( { "id": int(order.id), "order_no": order.order_no, "message": "缺少绑定账号或绑定角色,已保持/退回「待补资料」", } ) continue eligible_rows.append(order) verified_uids, preflight_failed_ids, preflight_failures = ( _preflight_recharge_binding( db, current, eligible_rows, client=client, ) ) failures.extend(preflight_failures) for order in eligible_rows: if int(order.id) in preflight_failed_ids: continue key = _recharge_group_key(order) if key is None: continue if key not in group_keys: group_keys.append(key) group_results: dict[RechargeGroupKey, dict] = {} pending_confirmation: dict[RechargeGroupKey, dict] = {} for key in group_keys: try: with db.begin_nested(): group = _check_recharge_group( db, current, key, threshold=threshold_value, client=client, confirm_points_error=False, verified_uids=verified_uids, ) if group.get("_needs_confirmation"): pending_confirmation[key] = group else: group_results[key] = group except CollabError as exc: group_rows = _recharge_group_orders(db, key) group_results[key] = _failed_recharge_group_result( key, group_rows, threshold=threshold_value, message=exc.detail, ) except Exception as exc: # noqa: BLE001 单个账号组失败不影响其它组 logger.debug(f"[huya-collab] 充值核账单组失败:{type(exc).__name__}: {exc}") group_rows = _recharge_group_orders(db, key) group_results[key] = _failed_recharge_group_result( key, group_rows, threshold=threshold_value, message=f"{type(exc).__name__}: {exc}", ) delay = max(0.0, float(confirm_delay_seconds or 0)) if pending_confirmation and delay: # 已通过的组先落库,避免等待二次确认时把它们的行锁持有整整 30 秒。 if commit: db.commit() time.sleep(delay) for key, first in pending_confirmation.items(): try: with db.begin_nested(): group = _check_recharge_group( db, current, key, threshold=threshold_value, client=client, confirm_points_error=True, confirmation={ "attempts": 2, "delay_seconds": delay, "first_balance": first.get("balance"), "first_required_total": first.get("required_total"), "first_surplus": first.get("surplus"), "first_reason": first.get("reason"), }, score_source="recharge_retry", verified_uids=verified_uids, ) group_results[key] = group except CollabError as exc: group_rows = _recharge_group_orders(db, key) group_results[key] = _failed_recharge_group_result( key, group_rows, threshold=threshold_value, message=exc.detail, ) except Exception as exc: # noqa: BLE001 单个账号组二次确认失败不影响其它组 logger.debug( f"[huya-collab] 充值核账二次确认失败:{type(exc).__name__}: {exc}" ) group_rows = _recharge_group_orders(db, key) group_results[key] = _failed_recharge_group_result( key, group_rows, threshold=threshold_value, message=f"{type(exc).__name__}: {exc}", ) groups = [group_results[key] for key in group_keys if key in group_results] updated = sum( len(group.get("order_ids") or []) for group in groups if group.get("status") ) failed_ids = {int(item["id"]) for item in failures if item.get("id") is not None} for group in groups: if not group.get("status"): failed_ids.update(int(item) for item in group.get("order_ids") or []) if commit: db.commit() for order in rows: db.refresh(order) return { "total": len(rows), "updated": updated, "failed": len(failed_ids), "threshold": threshold_value, "confirmed_groups": len(pending_confirmation), "confirmation_delay_seconds": delay, "groups": groups, "failures": failures, } # -------------------------------------------------------------------------- # CK 写入口 # -------------------------------------------------------------------------- # 人工能改的 CK 状态:`valid` / `invalid` 只能由探针给(人工标「有效」等于绕过验证)。 MANUAL_CK_STATUSES: tuple[str, ...] = (CK_UNVERIFIED, CK_DISABLED) def set_images( db: Session, current: User | None, order: HuyaExternalOrder, slot: str, value: Any, *, commit: bool = True, ) -> dict: """整槽替换图片(前端上传完拿到 object_key 后一次性提交)。""" assert_order_mutable(order) if slot not in IMAGE_SLOTS: raise CollabError(f"未知图片槽位:{slot}", code="image_slot_unknown") before = images_of(order, slot) after = normalize_images(value, field=slot) if before == after: return {"slot": slot, "images": after} setattr(order, slot, after) raw_detail = { "slot": slot, "slot_label": IMAGE_SLOT_LABELS[slot], "added": [key for key in after if key not in before], "removed": [key for key in before if key not in after], "order_no": order.order_no, } # 先记录图片变更,再让自动状态迁移追加在后面(时间线顺序与因果一致)。 record_audit( db, current, action="huya:collab:image", target=_audit_target(order), detail=raw_detail, ) advanced = _maybe_advance_to_recharge(db, current, order) demoted = False if advanced else _maybe_demote_missing_data(db, current, order) if not advanced and not demoted: _touch(order, current) if commit: db.commit() db.refresh(order) return {"slot": slot, "images": after} # -------------------------------------------------------------------------- # CK 探针(S5,只读验证) # -------------------------------------------------------------------------- # 探针参数与 web/backend/huya_defaults.py 的默认活动一致(2026-11-09 真机实测)。 # 新版活动页绑定走 gid=3203、bActId=0;最终角色由通用查询的第二路 # (gid + outerActId=空)返回,这里只给出外层活动参数。 PROBE_GID = int(HUYA_DEFAULT_BIND_GID) PROBE_OUTER_ACT_ID = HUYA_DEFAULT_OUTER_ACT_ID PROBE_SCENE = "undefined" # 与 runner 绑定协议保持一致 PROBE_TIMEOUT_SECONDS = 15.0 # 探针独占的绑定快照列(每次验证**覆盖写入**,人工不编辑): # 「这单现在到底绑了哪个游戏账号、哪个角色」只认这几列。 PROBE_SNAPSHOT_FIELDS: tuple[str, ...] = ( "bind_game_account", "bind_game_role", "bind_game_channel", ) # 兑换记录等 webActUI 接口用的 SID **兜底值**:真正该用的是工作台配置里的那个 # (``huya_config.sid``,见 :func:`resolve_gifts_sid`)。 # 2026-10-16 真机定论:**SID 就是活动 ID,会随活动轮换** —— 库里 9 月的活动是 2203, # 今天是 2277。写死默认值时接口照样 ``status=200`` 但 **0 个商品**,界面上就是 # 「礼包列表空白」(换 SID 立刻回到 30 个礼包,跟 CK、UA、解析都无关)。 GIFTS_SID = int(HUYA_DEFAULT_SID) # 同一份 CK 的探针结论缓存时长("预览一次 + 提交校验一次" 只打一次接口)。 PROBE_CACHE_TTL_SECONDS = 90.0 _probe_cache: dict[str, tuple[float, CkProbeResult]] = {} # 批量验证**串行 + 间隔**:不做定时轮询,一次也别勾太多,避免把账号送进风控名单。 PROBE_BATCH_INTERVAL_SECONDS = 1.0 _CK_MESSAGE_LIMIT = 256 # ck_check_message 列宽 _PROBE_PIECE_LIMIT = 40 # 拼消息时单段文本的上限 def _clip(value: Any, limit: int = _PROBE_PIECE_LIMIT) -> str: """把探针文本裁到可读长度(``ck_check_message`` 只有 256 字符)。""" text = str(value if value is not None else "").strip() return text if len(text) <= limit else text[: limit - 3] + "..." def _probe_cache_key(uid: int, cookie: str) -> str: """探针缓存键:uid + CK 的指纹(只存哈希,不留凭据原文)。""" digest = hashlib.sha256(f"{uid}|{cookie}".encode()).hexdigest() return digest @dataclasses.dataclass(frozen=True) class CkProbeResult: """一次只读探针的结论(不落库;落库由 :func:`verify_ck` 负责)。""" ok: bool message: str snapshot: dict[str, str] = dataclasses.field(default_factory=dict) nickname: str = "" nickname_error: str = "" def _build_probe_client() -> Any: """探针客户端(HTTP cdnws 只读通道)。 只做只读 RPC:**不建 ``HuyaAccount``、不 import 任何 runner**(设计文档 §2.3)。 测试替换这个工厂就能离线跑,不真连虎牙。 """ from core.huya.http_client import HuyaHttpClient return HuyaHttpClient( logger=lambda message: logger.debug(f"[huya-collab] {message}") ) def _probe_snapshot(resp: Any) -> dict[str, str]: """探针读到的**绑定对象**:绑定在该虎牙号上的游戏账号 + 角色。 2026-10-16 真机确认:``check_user_bind_game_account`` 返回的是**游戏账号** (账号昵称 / 角色名 / 平台·区服),**不是虎牙号自己的昵称**。本函数只组装游戏 绑定快照;虎牙平台昵称由 :func:`_probe_profile_nickname` 在绑定探针通过后补读, 绝不能拿 ``gameAccount.nick`` 冒充。 这几个列由探针**独占并覆盖写入**(``bind_snapshot_at`` 记读取时间): "这单现在到底绑了哪个号、哪个角色"只有这里可信(人工填的是自由文本)。 """ account_data = getattr(resp, "accountData", None) game_account = getattr(account_data, "gameAccount", None) game_role = getattr(account_data, "gameRole", None) snapshot: dict[str, str] = dict.fromkeys(PROBE_SNAPSHOT_FIELDS, "") account_name = _clip(getattr(game_account, "nick", "")) or _clip( getattr(game_role, "roleName", "") ) if account_name: snapshot["bind_game_account"] = account_name role_name = _clip(getattr(game_role, "roleName", "")) if role_name: snapshot["bind_game_role"] = role_name channel = " · ".join( piece for piece in ( _clip(getattr(game_role, "platName", "")), _clip(getattr(game_role, "areaName", "")), ) if piece ) if channel: snapshot["bind_game_channel"] = channel return snapshot def _probe_success_message(resp: Any) -> str: """成功时的可读结论(列表上直接能看到探针读到的绑定对象)。""" account_data = getattr(resp, "accountData", None) game_account = getattr(account_data, "gameAccount", None) game_role = getattr(account_data, "gameRole", None) parts: list[str] = [] nick = _clip(getattr(game_account, "nick", "")) role_name = _clip(getattr(game_role, "roleName", "")) if nick: parts.append(f"账号 {nick}") if role_name: parts.append(f"角色 {role_name}") channel = " · ".join( piece for piece in ( _clip(getattr(game_role, "platName", "")), _clip(getattr(game_role, "areaName", "")), ) if piece ) if channel: parts.append(channel) detail = " / ".join(parts) return (f"有效:{detail}" if detail else "有效")[:_CK_MESSAGE_LIMIT] def _probe_profile_nickname(client: Any, *, uid: int, cookie: str) -> tuple[str, str]: """在绑定探针成功后补读虎牙平台昵称。 这是**展示辅助**,不参与 CK 有效性判断:``check_user_bind_game_account`` 已经确认凭据有效;用户资料接口失败时保留“CK 有效”,只把失败原因带回 UI。 不用 ``gameAccount.nick`` 顶替,两者语义不同(游戏账号 vs 虎牙平台账号)。 """ method = getattr(client, "get_user_profile_batch", None) if method is None: return "", "" try: resp = method( uid=uid, cookie=cookie, target_uids=[uid], timeout=PROBE_TIMEOUT_SECONDS, ) except Exception as exc: # noqa: BLE001 昵称失败不能影响 CK 主结论 logger.debug(f"[huya-collab] 虎牙昵称查询异常:{type(exc).__name__}: {exc}") return "", f"{type(exc).__name__}: {_clip(exc)}" if resp is None: return "", "虎牙昵称接口没有返回数据" profiles = list(getattr(resp, "profiles", None) or []) if not profiles: return "", "虎牙昵称接口没有返回用户资料" profile = next( (item for item in profiles if int(getattr(item, "uid", 0) or 0) == uid), None, ) if profile is None: return "", "虎牙昵称接口返回的 uid 不匹配" nickname = str(getattr(profile, "nick", "") or "").strip() if not nickname: return "", "虎牙昵称接口没有返回昵称" return _clip(nickname, 128), "" def probe_ck(order: HuyaExternalOrder, *, client: Any | None = None) -> CkProbeResult: """只读探针:这份 CK 还能不能过(不写库、不发敏感动作)。 判据(2026-10-16 真机对照确定,**别改成「有数据就算成功」**): 响应**非 None 且 ``status == 200``**。 实测支持这个判据:裸 cookie(无任何凭据)+ 真 uid → 返回 ``None``; 真 CK + 别人的 uid → 也返回 ``None``;只有「真 CK + 真 uid」才拿到 200 + 真实数据。 同一个 CK 在 ``PROBE_CACHE_TTL_SECONDS`` 秒内复用上次结论:新建弹窗先"预览"、 提交时再校验,不该真的打两次虎牙接口。**注入 client 时不走缓存**(测试要真结论)。 """ uid_text = str(order.uid or "").strip() cookie = str(order.cookie or "").strip() if not uid_text or not cookie: return CkProbeResult(False, "这行还没有可验证的 CK(uid 或凭据为空)") try: uid = int(uid_text) except ValueError: return CkProbeResult(False, f"CK 里的 uid 不是数字:{_clip(uid_text)}") cache_key = _probe_cache_key(uid, cookie) if client is None else "" if cache_key: cached = _probe_cache.get(cache_key) if cached and time.time() - cached[0] < PROBE_CACHE_TTL_SECONDS: return cached[1] try: probe_client = client or _build_probe_client() resp, _detail = query_bind_game_account( probe_client, uid=uid, cookie=cookie, b_act_id=0, gid=PROBE_GID, outer_act_id=PROBE_OUTER_ACT_ID, is_use_outer_act_id=0, scene=PROBE_SCENE, timeout=PROBE_TIMEOUT_SECONDS, ) except Exception as exc: # noqa: BLE001 探针异常=验证不通过,不能让接口 500 logger.debug(f"[huya-collab] CK 探针异常:{type(exc).__name__}: {exc}") return CkProbeResult(False, f"探针调用失败:{type(exc).__name__}: {_clip(exc)}") if resp is None: return CkProbeResult(False, "探针没有返回数据(凭据无效或已被风控)") status = int(getattr(resp, "status", 0) or 0) if status != 200: msg = _clip(getattr(resp, "msg", "")) suffix = f":{msg}" if msg else "" return CkProbeResult(False, f"探针返回 status={status}{suffix}") nickname, nickname_error = _probe_profile_nickname( probe_client, uid=uid, cookie=cookie ) message = _probe_success_message(resp) if nickname: message = f"{message};虎牙昵称 {nickname}"[:_CK_MESSAGE_LIMIT] elif nickname_error: message = f"{message};虎牙昵称未读到:{nickname_error}"[:_CK_MESSAGE_LIMIT] result = CkProbeResult( True, message, _probe_snapshot(resp), nickname=nickname, nickname_error=nickname_error, ) if cache_key: _probe_cache[cache_key] = (time.time(), result) return result def resolve_gifts_sid(db: Session) -> int: """读取工作台配置的 SID 兜底值。 正常查询必须先走 :mod:`huya_activity_query`,从 ``queryAllocation`` 自动 发现当前 SID;本函数只在该接口不可用时提供兼容回退,不能再作为首选来源。 只读:配置行不存在时**不会**顺手建一行(预览是只读动作,设计文档 §2.3)。 """ try: row = db.query(HuyaConfig).first() except Exception as exc: # noqa: BLE001 配置读失败不该让预览 500 logger.debug( f"[huya-collab] 读取虎牙活动 SID 失败:{type(exc).__name__}: {exc}" ) return GIFTS_SID try: value = int(str(getattr(row, "sid", "") or "").strip()) except (TypeError, ValueError): return GIFTS_SID return value or GIFTS_SID # -------------------------------------------------------------------------- # 账号全生命周期(积分 / 兑换记录:抢购之后靠它判断到底兑换成功没有) # -------------------------------------------------------------------------- ACTIVITY_QUERY_TIMEOUT_SECONDS = 15.0 # 官方兑换记录存在落库延迟:生产实测三单在查询后 20~54 秒才出现记录。 # 因此脚本开始后的观察窗口内,「没查到」只能算暂时无法判定,不能自动判失败。 ACTIVITY_RESULT_SETTLE_SECONDS = 10 * 60 # metric.raw 里最多留多少条兑换记录(避免 JSON 列被几百条记录撑爆) _METRIC_RECORD_LIMIT = 50 # 兑换记录里跟订单礼包名比对时,只取有意义的长度(太短的名字容易误匹配) _MIN_GIFT_MATCH_LENGTH = 2 def _metric_message(text: Any, limit: int = 480) -> str: piece = str(text or "").strip() return piece if len(piece) <= limit else piece[: limit - 3] + "..." def gift_matches_records( records: Sequence[Mapping[str, Any]], gift_name: str, *, not_before: datetime | None = None, ) -> list[dict[str, Any]]: """在兑换记录里找这一单的礼包(名字完全相等或互相包含都算)。 虎牙记录里的 ``prize_name`` 与活动列表里的名字基本一字不差,但偶尔带后缀/前缀, 所以用「互相包含」宽松匹配;太短的名字(<2 字)不参与,免得 "礼包" 两个字匹配一堆。 传入 ``not_before`` 时还会排除上脚本之前的旧记录,避免同一买家重复购买同款时, 把上次兑换误判成这次成功。 """ wanted = str(gift_name or "").strip() if len(wanted) < _MIN_GIFT_MATCH_LENGTH: return [] threshold = not_before if threshold is not None and threshold.tzinfo is None: threshold = threshold.replace(tzinfo=UTC) if threshold is not None: # exchange_time 只有秒精度,上脚本时间可能带微秒;同秒记录不能误排掉。 threshold = threshold.replace(microsecond=0) matched: list[dict[str, Any]] = [] for record in records: name = str(record.get("prize_name") or "").strip() if not name: continue if not (name == wanted or wanted in name or name in wanted): continue raw_exchange_time = record.get("exchange_time") if threshold is not None and raw_exchange_time not in (None, ""): try: exchange_at = datetime.fromtimestamp(float(raw_exchange_time), tz=UTC) except (TypeError, ValueError, OSError): exchange_at = None if exchange_at is not None and exchange_at < threshold: continue matched.append(dict(record)) return matched def _activity_result_settle_at(order: HuyaExternalOrder) -> datetime | None: """返回脚本后的最早自动判失败时间;没有上脚本时间时不自动判失败。""" scripted_at = order.scripted_at if scripted_at is None: return None if scripted_at.tzinfo is None: scripted_at = scripted_at.replace(tzinfo=UTC) return scripted_at + timedelta(seconds=ACTIVITY_RESULT_SETTLE_SECONDS) def _extract_score(resp: Any) -> tuple[int | None, int | None, int | None, str]: """从 ``getUserScore`` 响应里取「可用 / 累计获得 / 已消耗」+ 可读结论。""" if resp is None: return None, None, None, "积分接口没有返回数据" status = int(getattr(resp, "status", 0) or 0) if status != 200: msg = _clip(getattr(resp, "msg", "")) return ( None, None, None, f"积分接口 status={status}{(':' + msg) if msg else ''}", ) available = getattr(resp, "available_score", None) if available is None: available = getattr(resp, "score", 0) gained = int(getattr(resp, "newGainScore", 0) or 0) or int( getattr(resp, "gainScore", 0) or 0 ) used = int(getattr(resp, "newUsedScore", 0) or 0) or int( getattr(resp, "usedScore", 0) or 0 ) return int(available or 0), gained, used, "" def _extract_records(resp: Any) -> tuple[list[dict[str, Any]], str]: """从 ``getUserPrizeRecords`` 响应里取兑换记录列表 + 可读结论。""" if resp is None: return [], "兑换记录接口没有返回数据" status = int(getattr(resp, "status", 0) or 0) if status != 200: msg = _clip(getattr(resp, "msg", "")) return [], f"兑换记录接口 status={status}{(':' + msg) if msg else ''}" data = resp.to_dict() or {} return list(data.get("records") or []), "" def query_order_activity( db: Session, current: User | None, order: HuyaExternalOrder, *, scope: str = ACTIVITY_SCOPE_BOTH, client: Any | None = None, source: str = "manual", commit: bool = True, current_sid: int = 0, current_sid_source: str = "", ) -> dict: """查一次这个账号的**积分 / 兑换记录**,落一条生命周期快照,必要时自动改状态。 ``scope`` 决定这次查哪一半(2026-10-17 用户要求把批量按钮拆成两个): - ``both``(默认,保持原行为):两个接口都打,判定按兑换记录来; - ``score``:**只打积分接口**。没查兑换记录,所以 ``verdict`` 是空串 (``VERDICT_NOT_QUERIED``,不是 ``unknown``)——「没查」和「查了判不了」是两回事, 列表上的判定徽标只认有结论的,否则点一次「查积分」会把整页徽标冲成「无法判定」。 **这种查询永远不会自动改业务状态**(结论都没有,凭什么改); - ``records``:**只打兑换记录接口**。积分不写(``score`` 留空),判定与自动改状态照旧。 判定规则(2026-10-16 用户口径,仅当本次查了兑换记录时): | 情况 | verdict | 业务状态 | | --- | --- | --- | | 兑换记录里有这一单的礼包 | ``success`` | 「已上脚本」的单 → 自动「抢购成功」 | | 接口通了,但记录里没有这个礼包 | ``failed`` | 「已上脚本」的单 → 自动「抢购失败」 | | 接口没通 / 这单没填礼包名 | ``unknown`` | **不动**(数据不够,不许瞎判) | 只有 ``已上脚本`` 的单会被自动改状态 —— 抢购是上脚本之后的事,其它阶段去改属于误判; 被跳过时结论里会写清楚原因。每次调用都写一条 metric(哪怕接口失败), 「积分变化 + 兑换记录」两条线索合起来才看得清有没有真的抢到。 """ if scope not in ACTIVITY_SCOPES: raise CollabError(f"未知的查询范围:{scope}", code="activity_scope_unknown") assert_order_mutable(order) want_score = scope in (ACTIVITY_SCOPE_BOTH, ACTIVITY_SCOPE_SCORE) want_records = scope in (ACTIVITY_SCOPE_BOTH, ACTIVITY_SCOPE_RECORDS) if order.status == STATUS_VOID: raise CollabError("已作废的单子不查积分/兑换记录", code="void_order") uid = str(order.uid or "").strip() cookie = str(order.cookie or "").strip() if not uid or not cookie: raise CollabError("这行还没有 CK,先贴一份再查积分/兑换记录", code="no_cookie") activity_client = client or _build_probe_client() 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, "") ) records, records_msg = _extract_records(records_resp) if want_records else ([], "") matched = gift_matches_records( records, order.gift_name, not_before=order.scripted_at, ) now = _now() settle_at = _activity_result_settle_at(order) if not want_records: # 只查积分:兑换记录一个字节都没查 —— 不许按"记录是空的"判成「兑换失败」, # 也不许自动改状态。verdict 用空串表示「本次未判定」。 # 结论文字写**积分本身**(别写"本次只查了积分"这种每行重复的套话, # 批量查询时那会把弹窗刷成一屏废话)。 verdict = VERDICT_NOT_QUERIED if score_msg: message = score_msg elif score is not None: message = f"积分 {score}(累计获得 {gained} / 已消耗 {used})" else: message = "没取到积分,本次也不查兑换记录" elif not str(order.gift_name or "").strip(): verdict = VERDICT_UNKNOWN message = "这单没填礼包名,没法跟兑换记录比对" elif records_msg or errors: verdict = VERDICT_UNKNOWN message = ( ";".join([*errors, records_msg]).strip(";") or "兑换记录没取到,无法判定" ) elif matched: verdict = VERDICT_SUCCESS latest = matched[0] message = ( f"兑换记录里查到 {len(matched)} 条匹配「{order.gift_name}」" f"(最近一条:{latest.get('status_label') or '状态未知'}" f"{(',单号 ' + str(latest.get('order_id'))) if latest.get('order_id') else ''})" ) elif order.status == STATUS_SCRIPTED and (settle_at is None or now < settle_at): verdict = VERDICT_UNKNOWN if settle_at is None: message = ( f"兑换记录里暂未查到「{order.gift_name}」;" "这单没有上脚本时间,不能自动判定抢购失败" ) else: message = ( f"兑换记录里暂未查到「{order.gift_name}」" f"(当前共 {len(records)} 条记录);处于上脚本后的 10 分钟抢购确认窗口," "暂不自动判失败" ) else: verdict = VERDICT_FAILED message = ( f"兑换记录里没有「{order.gift_name}」" f"(当前共 {len(records)} 条记录,都没有匹配上)" ) auto_status = "" if verdict == VERDICT_SUCCESS: target = STATUS_DONE elif verdict == VERDICT_FAILED: target = STATUS_FAILED else: target = "" can_promote_success = target == STATUS_DONE and order.status in ( STATUS_SCRIPTED, STATUS_FAILED, ) can_promote_failure = target == STATUS_FAILED and order.status == STATUS_SCRIPTED if can_promote_success or can_promote_failure: set_status( db, current, order, target, rollback=order.status == STATUS_FAILED, commit=False, ) auto_status = target elif target: message = ( f"{message}(当前状态是「{ORDER_STATUS_LABELS.get(order.status, order.status)}」," "只有「已上脚本」或「抢购失败」的单才会按抢购成功结果自动纠正;" "自动判失败只作用于「已上脚本」且已过确认窗口的单)" ) raw: dict[str, Any] = { "verdict": verdict, "scope": scope, "score_available": score, "score_gained": gained, "score_used": used, "records_count": len(records), "matched": matched[:5], "result_settle_at": settle_at.isoformat() if settle_at else None, "records": records[:_METRIC_RECORD_LIMIT], } if score_resp is not None: try: raw["score_response"] = score_resp.to_dict() except Exception as exc: # noqa: BLE001 没有 to_dict 的假客户端(测试)就不存原始体 logger.debug(f"[huya-collab] 积分原始体不入库:{type(exc).__name__}: {exc}") metric = HuyaExternalOrderMetric( order_id=int(order.id), order_no=order.order_no or "", uid=uid, sid=sid, score=score, gained_score=gained, used_score=used, records_total=len(records), records_matched=len(matched), verdict=verdict, message=_metric_message( ";".join(piece for piece in (score_msg, message) if piece) ), source=source, raw=raw, created_by=current.id if current else None, ) db.add(metric) db.flush() record_audit( db, current, action="huya:collab:activity_query", target=_audit_target(order), detail={ "order_no": order.order_no, "uid": uid, "sid": sid, "source": source, "scope": scope, "score": score, "records_total": len(records), "records_matched": len(matched), "verdict": verdict, "auto_status": auto_status, }, ) if commit: db.commit() db.refresh(order) db.refresh(metric) return { # `ok` = 「这次要查的东西查到没有」:查了兑换记录就看判定,只查积分就看积分接口通没通 "ok": ( verdict not in (VERDICT_UNKNOWN, VERDICT_NOT_QUERIED) if want_records else not score_msg ), "order_id": int(order.id), "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, "verdict_label": VERDICT_LABELS.get(verdict, verdict), "score": score, "gained_score": gained, "used_score": used, "records_total": len(records), "records_matched": len(matched), "message": metric.message, "auto_status": auto_status, "auto_status_label": ORDER_STATUS_LABELS.get(auto_status, auto_status), "status": order.status, "status_label": ORDER_STATUS_LABELS.get(order.status, order.status), "metric": serialize_metric(metric), } def query_activity_batch( db: Session, current: User | None, orders: Sequence[HuyaExternalOrder], *, scope: str = ACTIVITY_SCOPE_BOTH, client: Any | None = None, interval_seconds: float = PROBE_BATCH_INTERVAL_SECONDS, ) -> dict: """勾选批量查询:**串行 + 间隔**(防风控),单条失败不影响其它。 ``scope`` 与 :func:`query_order_activity` 一致(``both`` / ``score`` / ``records``): 只查积分时不会有判定结论,所以汇总里那些行进 ``not_judged``, **不计入 unknown**(unknown 的含义是「查了但判不了」,两者不能混)。 """ if scope not in ACTIVITY_SCOPES: raise CollabError(f"未知的查询范围:{scope}", code="activity_scope_unknown") rows = list(orders) if not rows: raise CollabError("请先勾选要查询的行", code="activity_batch_empty") if len(rows) > PROBE_BATCH_MAX: raise CollabError( f"一次最多查 {PROBE_BATCH_MAX} 行,请分批查询", code="activity_batch_too_large", ) 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) try: with db.begin_nested(): results.append( query_order_activity( db, current, order, scope=scope, 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( { "ok": False, "order_id": int(order.id), "order_no": order.order_no, "scope": scope, "scope_label": ACTIVITY_SCOPE_LABELS.get(scope, scope), "verdict": VERDICT_UNKNOWN, "verdict_label": VERDICT_LABELS[VERDICT_UNKNOWN], "message": exc.detail, "auto_status": "", "status": order.status, "status_label": ORDER_STATUS_LABELS.get(order.status, order.status), } ) db.commit() for order in rows: db.refresh(order) valid = [item for item in results if item.get("verdict") == VERDICT_SUCCESS] failed = [item for item in results if item.get("verdict") == VERDICT_FAILED] unknown = [item for item in results if item.get("verdict") == VERDICT_UNKNOWN] not_judged = [ item for item in results if item.get("verdict") == VERDICT_NOT_QUERIED ] auto_changed = [item for item in results if item.get("auto_status")] return { "total": len(results), "success": len(valid), "failed": len(failed), "unknown": len(unknown), "not_judged": len(not_judged), "auto_changed": len(auto_changed), "scope": scope, "scope_label": ACTIVITY_SCOPE_LABELS.get(scope, scope), "results": results, } def preview_ck( ck_text: Any, *, with_gifts: bool = True, sid: int | None = None, points_config: Mapping[str, Any] | None = None, client: Any | None = None, ) -> dict: """**只读预览**一份待提交的 CK:解析 + 探针(+ 顺带拉积分中心礼包),一行都不写库。 新建协作单时用它给出「CK 有效 + 绑定角色」的即时反馈;提交时 :func:`create_order` 还会再校验一次(同一份 CK 命中探针缓存,不会重复打接口)。 礼包源是 ``PlayMallUI.queryAllocation``(2026-10-19 用户拍板); ``sid`` 仅为旧调用签名兼容保留,当前不再参与礼包拉取。 """ parsed = parse_ck(str(ck_text or "")) uid_text = str(parsed.get("uid") or "") cookie = str(parsed.get("cookie") or "") probe_target = HuyaExternalOrder(order_no="preview") probe_target.uid = uid_text probe_target.cookie = cookie result = probe_ck(probe_target, client=client) gifts: list[dict] = [] gifts_message = "" if with_gifts and result.ok and uid_text: catalog = fetch_points_center_catalog( int(uid_text), cookie, client=client or _build_probe_client(), **(dict(points_config) if points_config else {}), ) gifts, gifts_message = catalog.goods, catalog.message return { "ok": result.ok, "message": result.message, "uid": uid_text, "yyuid": str(parsed.get("yyuid") or ""), "hy_username": str(parsed.get("username") or ""), "nickname": result.nickname, "ck_status": CK_VALID if result.ok else CK_INVALID, "bind_game_account": result.snapshot.get("bind_game_account", ""), "bind_game_role": result.snapshot.get("bind_game_role", ""), "bind_game_channel": result.snapshot.get("bind_game_channel", ""), "has_role": bool(result.snapshot.get("bind_game_role")), "gifts": gifts, "gifts_message": gifts_message, } def verify_ck( db: Session, current: User | None, order: HuyaExternalOrder, *, client: Any | None = None, commit: bool = True, ) -> dict: """跑一次只读探针并把结论落库。 - 结论**只**通过 :func:`set_ck_status` 写(``ck_status`` 的唯一写入口,审计不会丢); - 成功时**覆盖写入**绑定快照(``bind_game_account`` / ``bind_game_role`` / ``bind_game_channel`` + ``bind_snapshot_at``):这几列是探针独占的"现在绑了谁", 覆盖前会把旧值记进 ``huya:collab:probe_snapshot`` 审计,出问题能查回来; - 人工填的那些列(含 ``bind_douyu_account``)**一律不碰**; - CK 失效**不改业务状态**(设计文档 §4.2:已绑定/已充值的单子业务上可能仍然有效)。 """ assert_order_mutable(order) if not str(order.cookie or "").strip(): raise CollabError("这行还没有 CK,先贴一份再验证", code="no_cookie") if order.status == STATUS_VOID: raise CollabError( "已作废的行不验证 CK(要重新用请先改回流程内状态)", code="void_order" ) result = probe_ck(order, client=client) binding: dict[str, str] = { field_name: str(getattr(order, field_name) or "") for field_name in PROBE_SNAPSHOT_FIELDS } nickname_before = str(order.nickname or "") if result.ok: before = dict(binding) for field_name in PROBE_SNAPSHOT_FIELDS: setattr(order, field_name, result.snapshot.get(field_name, "")) if result.nickname: order.nickname = result.nickname order.bind_snapshot_at = _now() binding = { field_name: str(getattr(order, field_name) or "") for field_name in PROBE_SNAPSHOT_FIELDS } nickname_after = str(order.nickname or "") if binding != before or nickname_after != nickname_before: # 快照变了(或第一次读到)才记一条,别每次验证都刷两行审计。 record_audit( db, current, action="huya:collab:probe_snapshot", target=_audit_target(order), detail={ "order_no": order.order_no, "before": before, "after": binding, "nickname_before": nickname_before, "nickname_after": nickname_after, }, ) target = CK_VALID if result.ok else CK_INVALID set_ck_status(db, current, order, target, message=result.message, commit=False) _maybe_advance_to_recharge(db, current, order) if commit: db.commit() db.refresh(order) return { "id": order.id, "order_no": order.order_no, "ok": result.ok, "ck_status": target, "message": result.message, "binding": binding, "nickname": str(order.nickname or ""), } def _probe_row_error(order: HuyaExternalOrder, message: str) -> dict: """批量验证里「这一行没跑成」的统一形状(状态保持原样,不谎报 invalid)。""" return { "id": order.id, "order_no": order.order_no, "ok": False, "ck_status": order.ck_status, "message": _clip(message, _CK_MESSAGE_LIMIT), "nickname": order.nickname or "", "binding": { field_name: str(getattr(order, field_name) or "") for field_name in PROBE_SNAPSHOT_FIELDS }, } def verify_ck_batch( db: Session, current: User | None, orders: Sequence[HuyaExternalOrder], *, client: Any | None = None, interval_seconds: float | None = None, commit: bool = True, ) -> dict: """批量验证:**串行 + 间隔**(人工触发,不做定时轮询),单条失败不影响其他条。 Returns: ``{total, valid, failed, results: [{id, order_no, ok, ck_status, message, binding}]}`` """ rows = list(orders) if len(rows) > PROBE_BATCH_MAX: raise CollabError( f"一次最多验证 {PROBE_BATCH_MAX} 条,请分批勾选", code="verify_batch_too_large", ) interval = ( PROBE_BATCH_INTERVAL_SECONDS if interval_seconds is None else max(0.0, float(interval_seconds)) ) results: list[dict] = [] for index, order in enumerate(rows): if index and interval: time.sleep(interval) try: # 每行一个 SAVEPOINT:某行在写库阶段炸了也只脏这一行(同 import_orders)。 with db.begin_nested(): results.append( verify_ck(db, current, order, client=client, commit=False) ) db.flush() except CollabError as exc: results.append(_probe_row_error(order, exc.detail)) except Exception as exc: # noqa: BLE001 单条失败不该带崩整批 logger.debug(f"[huya-collab] 批量验证单行失败:{type(exc).__name__}: {exc}") results.append(_probe_row_error(order, f"{type(exc).__name__}: {exc}")) if commit: db.commit() valid = sum(1 for row in results if row["ok"]) return { "total": len(results), "valid": valid, "failed": len(results) - valid, "results": results, } # 导出 CK 的审计动作名(导出=把凭据带出系统,必须留痕) # -------------------------------------------------------------------------- # 店铺字典(新建协作单时点一下选;也支持自定义输入) # -------------------------------------------------------------------------- SHOP_NAME_LIMIT = 64 GIFT_NAME_LIMIT = 128 # -------------------------------------------------------------------------- # CRUD # -------------------------------------------------------------------------- def create_order( db: Session, current: User, *, order_no: str, shop: str = "", owner_id: int | None = None, ck_text: str = "", bind_douyu_account: str = "", gift_name: str = "", required_points: Any = None, home_images: Any = None, remark: str = "", require_verified: bool = False, auto_verify_ck: bool = False, draft: bool = False, client: Any | None = None, commit: bool = True, ) -> HuyaExternalOrder: """新建一行(可同时贴 CK)。订单号唯一,重复直接报冲突。 **负责人不填就是当前登录用户**(创建人)—— 新建时不用选,谁建的单归谁; 要转给别人在列表里点一下改负责人即可(负责人不是权限边界,见设计文档 §7.1)。 ``draft=True``(**先建单后补资料**):只要求订单号,店铺也允许先空着; 状态直接进「待补资料」,CK / 礼包名 / 主页截图都可以等客户资料到了再补。 这条路径不做严格校验;但只要带了 CK,就会顺手跑一次只读探针并写入绑定快照, 探针失败也不阻止建单。 ``require_verified=True``(**人工新建表单用**,粘贴导入不传)时按"人工必填项"严格校验: **订单编号 / 店铺 / CK / 礼包名 / 主页截图**都不许空,且 CK 必须探针通、 **读到绑定角色**才让建;读不到角色直接 400 —— 这条在服务层做,前端只是体验(AGENTS §2)。 校验全部在落库**之前**完成,失败不会留下半行。 图片只收**主页截图**(``home_images``):绑定图不再人工上传 —— 绑了谁由探针自动读 (``bind_game_*``),人工截图没有意义(2026-10-16 用户拍板)。 """ order_no = clean_text(order_no, field="order_no", required=True) _assert_order_no_available(db, order_no) home_images_keys = normalize_images(home_images, field="home_images") if draft: # 草稿单不验 CK、不跑探针:先落一行占住订单号,资料到了在详情里补。 require_verified = False clean_gift_name = clean_text( gift_name, field="gift_name", max_length=GIFT_NAME_LIMIT ) clean_required_points = _clean_required_points(required_points) if clean_gift_name and clean_required_points is None: clean_required_points = _catalog_points_for_name(db, clean_gift_name) order = HuyaExternalOrder( order_no=order_no, shop=clean_text(shop, field="shop"), owner_id=_clean_owner_id(owner_id) if owner_id is not None else current.id, bind_douyu_account=clean_text(bind_douyu_account, field="bind_douyu_account"), gift_name=clean_gift_name, required_points=clean_required_points, remark=clean_text(remark, field="remark"), bind_images=[], home_images=home_images_keys, status=STATUS_INCOMPLETE, ck_status=CK_UNVERIFIED, created_by=current.id, updated_by=current.id, version=0, ) uid_reused: list[str] = [] ck_provided = bool(str(ck_text or "").strip()) if ck_provided: _apply_ck(order, ck_text) # 同一个虎牙号允许挂多单(2026-10-16 放开 uid 唯一性):只记复用痕迹,不拦 uid_reused = [item.order_no for item in uid_used_orders(db, order.uid)] if require_verified: missing: list[str] = [] if not order.shop: missing.append("店铺") if not ck_provided: missing.append("外部 CK") if not order.gift_name: missing.append("礼包名") if not order.home_images: missing.append("主页截图") if missing: raise CollabError( f"下面这几项必须填:{'、'.join(missing)}", code="create_field_required" ) # 只要带了 CK 就先探一次:严格建单失败会阻断;草稿/导入等宽松路径则保留探针 # 结果,但绝不因为外部接口失败而阻止建单。这样新行不需要再手动点一次「验证 CK」。 probe_result: CkProbeResult | None = None if ck_provided and (require_verified or auto_verify_ck): probe_result = probe_ck(order, client=client) if require_verified and probe_result is not None: role = probe_result.snapshot.get("bind_game_role", "") if not probe_result.ok or not role: raise CollabError( f"这份 CK 不能用:{probe_result.message}" + ("(探针通了但读不到绑定角色)" if probe_result.ok else ""), code="ck_not_verified", ) if probe_result is not None and probe_result.ok: for field_name in PROBE_SNAPSHOT_FIELDS: setattr(order, field_name, probe_result.snapshot.get(field_name, "")) if probe_result.nickname: order.nickname = probe_result.nickname order.bind_snapshot_at = _now() if order.shop: # 自定义输入的店铺名顺手登记进字典 → 下次下拉里就能直接点选。 ensure_shops_registered(db, current, [order.shop]) db.add(order) db.flush() # 先拿到 id,审计里要带 target # 先记「创建」这一笔,再做探针结论/自动推进:时间线按“谁导致什么”排序, # 不能出现 status_auto 排在 create 前面。 record_audit( db, current, action="huya:collab:create", target=_audit_target(order), detail={ "order_no": order.order_no, "shop": order.shop, "uid": order.uid or "", "ck_status": ( CK_VALID if probe_result is not None and probe_result.ok else order.ck_status ), "gift_name": order.gift_name, "required_points": order.required_points, "bind_game_account": order.bind_game_account or "", "bind_game_role": order.bind_game_role or "", "nickname": order.nickname or "", "home_images": len(order.home_images or []), "draft": bool(draft), # 这个虎牙号还挂在哪些单上(允许同一份 CK 服务多单,留个痕) "uid_reused_in": uid_reused, }, ) if probe_result is not None: # 结论仍然走 set_ck_status 这个唯一写入口(审计与 ck_checked_at 不会漂)。 set_ck_status( db, current, order, CK_VALID if probe_result.ok else CK_INVALID, message=probe_result.message, commit=False, ) _maybe_advance_to_recharge(db, current, order) if commit: db.commit() db.refresh(order) return order def update_order( db: Session, current: User, order: HuyaExternalOrder, payload: Mapping[str, Any], *, expected_version: int | None = None, commit: bool = True, ) -> dict: """编辑可改字段,返回**字段级 diff**(``{字段: {old, new}}``)。 乐观锁:``expected_version`` 与库里不一致 → 409,绝不静默覆盖 (这正是 Excel 协同最痛的地方)。 """ assert_order_mutable(order) assert_version(order, expected_version) changes: dict[str, dict[str, Any]] = {} for field in EDITABLE_FIELDS: if field not in payload: continue if field == "owner_id": new_value: Any = _clean_owner_id(payload[field]) elif field == "required_points": new_value = _clean_required_points(payload[field]) else: new_value = clean_text( payload[field], field=field, required=(field == "order_no"), ) old_value = getattr(order, field) if old_value == new_value: continue if field == "order_no": _assert_order_no_available(db, new_value, exclude_id=order.id) changes[field] = {"old": old_value, "new": new_value} setattr(order, field, new_value) if not changes: return {} if "shop" in changes: # 改成字典里没有的名字也允许(自定义),顺手登记,筛选下拉不会漏。 ensure_shops_registered(db, current, [changes["shop"]["new"]]) if "gift_name" in changes and "required_points" not in payload: catalog_points = _catalog_points_for_name(db, changes["gift_name"]["new"]) if catalog_points is not None and catalog_points != order.required_points: changes["required_points"] = { "old": order.required_points, "new": catalog_points, } order.required_points = catalog_points # 先记「人工改了什么」,再跑自动状态迁移:否则时间线会出现 # status_auto 排在 update 前面,像状态是被后一次操作改的。 record_audit( db, current, action="huya:collab:update", target=_audit_target(order), detail={"order_no": order.order_no, "changes": changes}, ) advanced = _maybe_advance_to_recharge(db, current, order) demoted = False if advanced else _maybe_demote_missing_data(db, current, order) if not advanced and not demoted: _touch(order, current) if commit: db.commit() db.refresh(order) return changes def delete_order( db: Session, current: User, order: HuyaExternalOrder, *, commit: bool = True ) -> dict: """物理删除(需 ``huya:collab:manage``)。 只删行,**不删对象存储里的图**:撤图不可逆,交给孤儿清理脚本按保留期处理 (设计文档 §6.4)。 """ assert_order_mutable(order) snapshot = { "order_no": order.order_no, "uid": order.uid or "", "images": images_of(order, "bind_images") + images_of(order, "home_images"), } record_audit( db, current, action="huya:collab:delete", target=_audit_target(order), detail={ "order_no": snapshot["order_no"], "uid": snapshot["uid"], "image_count": len(snapshot["images"]), }, ) db.delete(order) if commit: db.commit() return snapshot # -------------------------------------------------------------------------- # 查询 # -------------------------------------------------------------------------- def get_order(db: Session, order_id: int) -> HuyaExternalOrder: order = db.query(HuyaExternalOrder).filter(HuyaExternalOrder.id == order_id).first() if order is None: raise CollabError( "这一行不存在(可能已被别人删除)", status_code=404, code="order_not_found" ) return order ORDER_SORT_KEYS: tuple[str, ...] = ( "seq", "order_no", "shop", "owner", "bind", "gift_name", "status", "uid", "ck_status", "updated_at", "created_at", ) # -------------------------------------------------------------------------- # 同一买家的多单(软识别:只读派生,不落库、不改 uid 唯一性规则) # -------------------------------------------------------------------------- # 买家指纹 = 探针读到的「绑定账号 + 绑定角色」(同一个游戏角色 = 同一个买家)。 # **不拿 uid 当主键**:一单一份外部 CK,同一个买家买两件往往是两份不同的 CK(uid 不同), # 拿 uid 去比反而永远比不中;uid 只作为明细里的辅助信息展示。 BUYER_KEY_METHOD = "bind_game_account+bind_game_role" # -------------------------------------------------------------------------- # 批量导入(Excel 粘贴) # -------------------------------------------------------------------------- IMPORT_COLUMNS: tuple[str, ...] = ( "shop", "order_no", "owner", "bind_douyu_account", "gift_name", "remark", ) # 表头识别:中文(Excel 原表头)+ 英文别名。按位置兜底要求 6 列顺序一致。 _HEADER_ALIASES: dict[str, str] = { "店铺": "shop", "shop": "shop", "订单编号": "order_no", "订单号": "order_no", "order_no": "order_no", "orderno": "order_no", "负责人": "owner", "owner": "owner", "绑定斗鱼号": "bind_douyu_account", "绑定斗鱼": "bind_douyu_account", "斗鱼号": "bind_douyu_account", "bind_douyu_account": "bind_douyu_account", "礼包": "gift_name", "礼包名": "gift_name", "商品": "gift_name", "gift_name": "gift_name", "备注": "remark", "remark": "remark", } def parse_import_text(text: str) -> tuple[list[str], list[tuple[int, list[str]]]]: """把粘贴的文本切成 (列顺序, [(行号, 单元格)])。 支持 Excel 直接复制出来的 TSV(``\\t``),也兼容逗号/分号分隔。 第一行若能被识别成表头,则按表头映射列;否则按固定列序 ``店铺 / 订单编号 / 负责人 / 绑定斗鱼号 / 礼包 / 备注``。 """ rows: list[tuple[int, list[str]]] = [] for index, raw_line in enumerate((text or "").splitlines(), start=1): line = raw_line.rstrip("\r\n") if not line.strip(): continue if "\t" in line: cells = line.split("\t") elif ";" in line: cells = line.split(";") elif "," in line: cells = line.split(",") else: cells = [line] rows.append((index, [cell.strip() for cell in cells])) if not rows: return list(IMPORT_COLUMNS), [] first_index, first_cells = rows[0] mapped: list[str] = [] for cell in first_cells: key = _HEADER_ALIASES.get(cell.strip().lower()) or _HEADER_ALIASES.get( cell.strip() ) mapped.append(key or "") if mapped.count("order_no") == 1 and len(mapped) >= 2: logger.debug(f"协作台账导入:识别到表头(行 {first_index}){mapped}") return mapped, rows[1:] return list(IMPORT_COLUMNS), rows def import_orders( db: Session, current: User, text: str, *, owner_by_name: Mapping[str, int] | None = None, commit: bool = True, ) -> dict: """批量导入:逐行处理,**单行失败不影响其他行**(AGENTS §2),错误按行号返回。 Returns: ``{created, updated, skipped, errors: [{line, order_no, message}]}`` """ columns, rows = parse_import_text(text) owners = { str(name).strip(): int(uid) for name, uid in (owner_by_name or {}).items() } created = 0 updated = 0 skipped = 0 errors: list[dict[str, Any]] = [] seen_order_nos: set[str] = set() for line_no, cells in rows: record = { column: (cells[index] if index < len(cells) else "") for index, column in enumerate(columns) if column } order_no = str(record.get("order_no") or "").strip() if not order_no: skipped += 1 continue if order_no in seen_order_nos: # 同一批粘贴里重复出现:只处理第一条,否则后一条会把刚建的覆盖掉。 errors.append( { "line": line_no, "order_no": order_no, "message": "本次粘贴里重复出现,只处理第一条", } ) continue seen_order_nos.add(order_no) owner_name = str(record.get("owner") or "").strip() payload: dict[str, Any] = { "shop": record.get("shop", ""), "bind_douyu_account": record.get("bind_douyu_account", ""), "gift_name": record.get("gift_name", ""), "remark": record.get("remark", ""), } if owner_name: if owner_name not in owners: errors.append( { "line": line_no, "order_no": order_no, "message": f"负责人「{owner_name}」不存在或不是活跃用户", } ) continue payload["owner_id"] = owners[owner_name] outcome = "" try: # 每行套一个 SAVEPOINT:这一行炸了只回滚这一行,整批继续。 # 若直接往同一个事务里写,一次约束冲突就会把会话打成失败态, # 后面每一行都跟着报错 —— 那就成了「单行失败带崩整批」。 with db.begin_nested(): existing = ( db.query(HuyaExternalOrder) .filter(HuyaExternalOrder.order_no == order_no) .first() ) if existing is None: create_order( db, current, order_no=order_no, shop=payload.get("shop", ""), owner_id=payload.get("owner_id"), bind_douyu_account=payload.get("bind_douyu_account", ""), gift_name=payload.get("gift_name", ""), remark=payload.get("remark", ""), commit=False, ) outcome = "created" else: # 已存在按「更新」处理(设计文档 §10.2 E);导入不带 # expected_version,视为「明确要覆盖」。 changes = update_order( db, current, existing, payload, expected_version=None, commit=False, ) outcome = "updated" if changes else "skipped" # SessionLocal 是 autoflush=False:显式 flush,让后面几行的 # 重复检查能看到刚写入的这行。 db.flush() except CollabError as exc: errors.append( {"line": line_no, "order_no": order_no, "message": exc.detail} ) continue except Exception as exc: # noqa: BLE001 单行失败不该带崩整批导入 errors.append( { "line": line_no, "order_no": order_no, "message": f"{type(exc).__name__}: {exc}", } ) continue if outcome == "created": created += 1 elif outcome == "updated": updated += 1 else: skipped += 1 if commit: db.commit() return { "created": created, "updated": updated, "skipped": skipped, "errors": errors, "parsed_columns": columns, }