"""虎牙外部单协作的查询、归档、序列化与买家聚类。""" from __future__ import annotations import dataclasses from collections.abc import Mapping, Sequence from typing import Any from sqlalchemy import func, or_, tuple_ from sqlalchemy.orm import Session from ..models import 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_collab_common import ( ACTIVITY_SCOPE_BOTH, ARCHIVABLE_STATUSES, ARCHIVE_BATCH_MAX, CK_INVALID, CK_STATUS_LABELS, NEXT_STATUS, ORDER_STATUS_LABELS, ORDER_STATUSES, PROBE_BATCH_MAX, STATUS_DONE, STATUS_VOID, VERDICT_LABELS, VERDICT_NOT_QUERIED, CollabError, _audit_target, _now, _touch, clean_text, images_of, ) ORDER_SORT_KEYS: tuple[str, ...] = ( "seq", "order_no", "shop", "owner", "bind", "gift_name", "status", "uid", "ck_status", "updated_at", "created_at", ) BUYER_KEY_METHOD = "bind_game_account+bind_game_role" def serialize_metric( metric: HuyaExternalOrderMetric, *, users: Mapping[int, str] | None = None ) -> dict: """一条生命周期快照的输出(时间线用)。 ``scope`` 说明这条快照当时查了哪一半 —— 前端的取舍靠它,别靠"字段是不是空"猜: 只查积分的那条积分有值、兑换记录是 0 条,不能拿 ``records_total == 0`` 当"没兑换到"。 """ names = users or {} raw = metric.raw if isinstance(metric.raw, dict) else {} raw_matched = raw.get("matched") matched = ( [item for item in raw_matched if isinstance(item, dict)] if isinstance(raw_matched, list) else [] ) return { "id": int(metric.id), "order_id": int(metric.order_id), "order_no": metric.order_no or "", "uid": metric.uid or "", "sid": metric.sid, "scope": str(raw.get("scope") or ACTIVITY_SCOPE_BOTH), "score": metric.score, "gained_score": metric.gained_score, "used_score": metric.used_score, "records_total": int(metric.records_total or 0), "records_matched": int(metric.records_matched or 0), # 空 = 本次没查兑换记录(≠「无法判定」:那个是查了但判不了) "verdict": metric.verdict or VERDICT_NOT_QUERIED, "verdict_label": VERDICT_LABELS.get(metric.verdict, metric.verdict or ""), "message": metric.message or "", "source": metric.source or "manual", "matched_preview": [ { "prize_name": str(item.get("prize_name") or ""), "score": item.get("score"), "status_label": str(item.get("status_label") or ""), "order_id": str(item.get("order_id") or ""), "exchange_time": item.get("exchange_time"), } for item in matched[:5] ], "created_by": metric.created_by, "created_by_name": names.get(int(metric.created_by or 0), ""), "created_at": metric.created_at, } def list_metrics( db: Session, order: HuyaExternalOrder, *, limit: int = 100 ) -> list[HuyaExternalOrderMetric]: """某个订单的生命周期快照(**倒序**:最近一次在前,界面直接铺时间线)。""" return ( db.query(HuyaExternalOrderMetric) .filter(HuyaExternalOrderMetric.order_id == int(order.id)) .order_by(HuyaExternalOrderMetric.id.desc()) .limit(max(1, min(500, int(limit)))) .all() ) @dataclasses.dataclass(frozen=True) class OrderMetricView: """列表「积分」列的三条线索(见 :func:`order_metric_views`)。 ``score`` / ``verdict`` 各自可能比 ``latest`` 旧:只查积分的那次不产生判定, 只查兑换记录的那次不产生积分 —— 谁都没产出的那次就不该把对方从列表上抹掉。 """ latest: HuyaExternalOrderMetric | None = None score: HuyaExternalOrderMetric | None = None verdict: HuyaExternalOrderMetric | None = None def _latest_metric_ids(db: Session, ids: Sequence[int], *filters: Any) -> list[int]: """这批行各自「最近一条」快照的主键(可选附加过滤条件)。""" if not ids: return [] newest = ( db.query(func.max(HuyaExternalOrderMetric.id).label("metric_id")) .filter(HuyaExternalOrderMetric.order_id.in_(list(ids)), *filters) .group_by(HuyaExternalOrderMetric.order_id) .subquery() ) return [row[0] for row in db.query(newest.c.metric_id).all() if row[0] is not None] def _metrics_by_id( db: Session, metric_ids: Sequence[int] ) -> dict[int, HuyaExternalOrderMetric]: if not metric_ids: return {} rows = ( db.query(HuyaExternalOrderMetric) .filter(HuyaExternalOrderMetric.id.in_(list(metric_ids))) .all() ) return {int(row.order_id): row for row in rows} def latest_metrics( db: Session, orders: Sequence[HuyaExternalOrder] ) -> dict[int, HuyaExternalOrderMetric]: """一次查出这批行各自「最近一条」快照(列表要显示最新积分,别按行发 SQL)。""" ids = [int(order.id) for order in orders] return _metrics_by_id(db, _latest_metric_ids(db, ids)) def order_metric_views( db: Session, orders: Sequence[HuyaExternalOrder] ) -> dict[int, OrderMetricView]: """列表「积分」列要显示的三条线索(整页一次算完,别按行发 SQL)。 2026-10-17 拆出「查积分 / 查兑换记录」两个入口之后,**一次查询只写一半**: 只查积分的那条 ``verdict`` 是空的、只查兑换记录的那条 ``score`` 是空的。所以: - ``latest`` —— 最近一条(列上的「最后查询时间」与结论文字); - ``score`` —— 最近一条**查过积分**的:只查兑换记录时不能让积分显示变成 ``-``; - ``verdict`` —— 最近一条**有判定结论**的(``success`` / ``failed`` / ``unknown``): 只查积分时不能把已有的判定徽标冲成「无法判定」。 注意 ``unknown``(查了但判不了)**要算结论**,否则接口抖动时会一直挂着旧徽标。 三条线索最多各发一次分组查询;都没有快照时返回空 dict。 """ ids = [int(order.id) for order in orders] if not ids: return {} latest = _metrics_by_id(db, _latest_metric_ids(db, ids)) scored = _metrics_by_id( db, _latest_metric_ids(db, ids, HuyaExternalOrderMetric.score.isnot(None)) ) judged = _metrics_by_id( db, _latest_metric_ids(db, ids, HuyaExternalOrderMetric.verdict != "") ) views: dict[int, OrderMetricView] = {} for order_id in {*latest, *scored, *judged}: views[order_id] = OrderMetricView( latest=latest.get(order_id), score=scored.get(order_id), verdict=judged.get(order_id), ) return views def list_orders_by_ids(db: Session, ids: Sequence[int]) -> list[HuyaExternalOrder]: """按 id 取行(保持勾选顺序;已被别人删掉的 id 直接忽略)。""" wanted = list(dict.fromkeys(int(value) for value in ids)) if not wanted: raise CollabError("请先选择要验证的行", code="verify_empty") if len(wanted) > PROBE_BATCH_MAX: raise CollabError( f"一次最多验证 {PROBE_BATCH_MAX} 条,请分批勾选", code="verify_batch_too_large", ) rows = db.query(HuyaExternalOrder).filter(HuyaExternalOrder.id.in_(wanted)).all() by_id = {int(row.id): row for row in rows} return [by_id[value] for value in wanted if value in by_id] def list_orders_for_archive(db: Session, ids: Sequence[int]) -> list[HuyaExternalOrder]: """按 id 取归档/取消归档目标(不受探针 50 条上限约束)。""" wanted = list(dict.fromkeys(int(value) for value in ids)) if not wanted: raise CollabError("请先选择要归档的行", code="archive_empty") if len(wanted) > ARCHIVE_BATCH_MAX: raise CollabError( f"一次最多处理 {ARCHIVE_BATCH_MAX} 行,请分批操作", code="archive_too_large", ) rows = db.query(HuyaExternalOrder).filter(HuyaExternalOrder.id.in_(wanted)).all() by_id = {int(row.id): row for row in rows} return [by_id[value] for value in wanted if value in by_id] def _filtered_orders_query( db: Session, *, shop: str = "", owner_id: int | None = None, status: str = "", ck_status: str = "", gift_name: str = "", keyword: str = "", include_void: bool = False, archive_scope: str = "active", ): """列表与「按筛选归档」共用同一套筛选,保证两边口径一致。""" query = db.query(HuyaExternalOrder) if shop: query = query.filter(HuyaExternalOrder.shop == shop) if owner_id: query = query.filter(HuyaExternalOrder.owner_id == owner_id) if status: query = query.filter(HuyaExternalOrder.status == status) if ck_status: query = query.filter(HuyaExternalOrder.ck_status == ck_status) skin = (gift_name or "").strip() if skin: query = query.filter(HuyaExternalOrder.gift_name == skin) 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}%" query = query.filter( or_( HuyaExternalOrder.order_no.like(like), HuyaExternalOrder.shop.like(like), HuyaExternalOrder.bind_douyu_account.like(like), HuyaExternalOrder.bind_game_account.like(like), HuyaExternalOrder.bind_game_role.like(like), HuyaExternalOrder.bind_game_channel.like(like), HuyaExternalOrder.uid.like(like), HuyaExternalOrder.nickname.like(like), HuyaExternalOrder.hy_username.like(like), HuyaExternalOrder.gift_name.like(like), HuyaExternalOrder.remark.like(like), ) ) return query def list_orders( db: Session, *, shop: str = "", owner_id: int | None = None, status: str = "", ck_status: str = "", gift_name: str = "", keyword: str = "", include_void: bool = False, archive_scope: str = "active", sort_by: str = "seq", sort_order: str = "asc", page: int = 1, page_size: int = 50, ) -> tuple[list[HuyaExternalOrder], int]: """共享视图:默认**不按人过滤**(负责人只是筛选维度,不是权限边界)。 默认按 ``id`` 升序(即创建顺序),新建的行永远追加在最后;表头排序走白名单, 不允许前端把任意列名拼进 SQL。归档行只有在 ``archive_scope=archived/all`` 时出现。 """ query = _filtered_orders_query( db, shop=shop, owner_id=owner_id, status=status, ck_status=ck_status, gift_name=gift_name, keyword=keyword, include_void=include_void, archive_scope=archive_scope, ) total = query.count() page = max(1, int(page or 1)) page_size = min(200, max(1, int(page_size or 50))) key = (sort_by or "seq").strip().lower() if key not in ORDER_SORT_KEYS: key = "seq" descending = (sort_order or "asc").strip().lower() == "desc" # 负责人按显示的用户名排序(不是 id),需要一次 outerjoin;其它列都直接落在订单表上。 if key == "owner": query = query.outerjoin(User, HuyaExternalOrder.owner_id == User.id) sort_column = User.username elif key == "status": # 与页头状态顺序保持一致,避免状态列按字母序排得莫名其妙。 sort_column = func.field(HuyaExternalOrder.status, *ORDER_STATUSES) elif key == "bind": sort_column = HuyaExternalOrder.bind_game_account elif key == "seq": sort_column = HuyaExternalOrder.id else: sort_column = getattr(HuyaExternalOrder, key) ordered = sort_column.desc() if descending else sort_column.asc() rows = ( query.order_by(ordered, HuyaExternalOrder.id.asc()) .offset((page - 1) * page_size) .limit(page_size) .all() ) return rows, total def archive_orders( db: Session, current: User | None, orders: Sequence[HuyaExternalOrder], *, reason: str = "", commit: bool = True, ) -> dict: """归档抢购成功的行:只改可见性字段,不影响业务状态。 已有归档的行、非「抢购成功」的行都跳过并逐条回原因;归档备注写入每行, 取消归档时清空,审计里始终保留原始备注。 """ rows = list(orders) if not rows: raise CollabError("请先选择要归档的行", code="archive_empty") if len(rows) > ARCHIVE_BATCH_MAX: raise CollabError( f"一次最多归档 {ARCHIVE_BATCH_MAX} 行,请分批操作", code="archive_too_large", ) note = clean_text(reason, field="archive_reason", max_length=256) now = _now() results: list[dict] = [] archived = 0 for order in rows: if order.archived_at is not None: results.append( { "id": int(order.id), "order_no": order.order_no, "ok": False, "message": "已经归档", } ) continue if order.status not in ARCHIVABLE_STATUSES: results.append( { "id": int(order.id), "order_no": order.order_no, "ok": False, "message": "只有「抢购成功」的单可以归档", } ) continue order.archived_at = now order.archived_by = current.id if current else None order.archive_reason = note _touch(order, current) record_audit( db, current, action="huya:collab:archive", target=_audit_target(order), detail={ "order_no": order.order_no, "status": order.status, "reason": note, }, ) archived += 1 results.append( { "id": int(order.id), "order_no": order.order_no, "ok": True, "message": "已归档", } ) if commit: db.commit() for order in rows: db.refresh(order) return { "total": len(rows), "archived": archived, "unarchived": 0, "skipped": len(rows) - archived, "results": results, } def archive_orders_by_filter( db: Session, current: User | None, *, reason: str = "", expected_count: int | None = None, shop: str = "", owner_id: int | None = None, status: str = "", ck_status: str = "", gift_name: str = "", keyword: str = "", include_void: bool = False, ) -> dict: """把当前筛选范围内的「抢购成功」活跃行一次归档。 ``expected_count`` 是前端确认弹窗里展示的数量;执行前再数一次,避免确认期间 新完成/被其他人归档导致多隐藏了行。 """ query = _filtered_orders_query( db, shop=shop, owner_id=owner_id, status=status, ck_status=ck_status, gift_name=gift_name, keyword=keyword, include_void=include_void, archive_scope="active", ).filter(HuyaExternalOrder.status == STATUS_DONE) total = query.count() if expected_count is not None and int(expected_count) != total: raise CollabError( f"匹配数量已变化(确认时 {expected_count} 条,现在 {total} 条),请刷新后重新确认", status_code=409, code="archive_count_changed", ) if total > ARCHIVE_BATCH_MAX: raise CollabError( f"一次最多归档 {ARCHIVE_BATCH_MAX} 行,请缩小筛选范围", code="archive_too_large", ) rows = query.order_by(HuyaExternalOrder.id.asc()).all() return archive_orders(db, current, rows, reason=reason) def unarchive_orders( db: Session, current: User | None, orders: Sequence[HuyaExternalOrder], *, commit: bool = True, ) -> dict: """取消归档,恢复回主台账;归档备注清空但审计保留。""" rows = list(orders) if not rows: raise CollabError("请先选择要取消归档的行", code="unarchive_empty") if len(rows) > ARCHIVE_BATCH_MAX: raise CollabError( f"一次最多取消归档 {ARCHIVE_BATCH_MAX} 行,请分批操作", code="unarchive_too_large", ) results: list[dict] = [] unarchived = 0 for order in rows: if order.archived_at is None: results.append( { "id": int(order.id), "order_no": order.order_no, "ok": False, "message": "没有归档", } ) continue previous_reason = order.archive_reason or "" order.archived_at = None order.archived_by = None order.archive_reason = "" _touch(order, current) record_audit( db, current, action="huya:collab:unarchive", target=_audit_target(order), detail={ "order_no": order.order_no, "status": order.status, "reason": previous_reason, }, ) unarchived += 1 results.append( { "id": int(order.id), "order_no": order.order_no, "ok": True, "message": "已取消归档", } ) if commit: db.commit() for order in rows: db.refresh(order) return { "total": len(rows), "archived": 0, "unarchived": unarchived, "skipped": len(rows) - unarchived, "results": results, } def summary( db: Session, *, include_void: bool = False, archive_scope: str = "active" ) -> dict: """页头统计条:统计口径与当前列表的归档/作废过滤保持一致。""" 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)) .group_by(HuyaExternalOrder.status) .all() ) by_status = {str(status): int(count) for status, count in status_rows} ck_invalid = ( query.with_entities(func.count(HuyaExternalOrder.id)) .filter(HuyaExternalOrder.ck_status == CK_INVALID) .scalar() ) archived_total = ( db.query(func.count(HuyaExternalOrder.id)) .filter(HuyaExternalOrder.archived_at.is_not(None)) .scalar() ) return { "total": sum(by_status.values()), "by_status": {code: by_status.get(code, 0) for code in ORDER_STATUSES}, "ck_invalid": int(ck_invalid or 0), "archived_total": int(archived_total or 0), } def user_names(db: Session, ids: Sequence[Any]) -> dict[int, str]: """一批用户 id → 用户名(避免每行懒加载,N+1)。""" clean = {int(value) for value in ids if value} if not clean: return {} rows = db.query(User.id, User.username).filter(User.id.in_(clean)).all() return {int(row[0]): str(row[1]) for row in rows} def users_by_id(db: Session, orders: Sequence[HuyaExternalOrder]) -> dict[int, str]: """一次性把涉及的用户名查出来,避免每行都懒加载(N+1)。""" return user_names( db, [ value for order in orders for value in ( order.owner_id, order.created_by, order.updated_by, order.archived_by, ) ], ) def serialize_order( order: HuyaExternalOrder, *, users: Mapping[int, str] | None = None, buyer_cluster: Mapping[str, Any] | None = None, last_metric: HuyaExternalOrderMetric | None = None, metric_view: OrderMetricView | None = None, ) -> dict: """把行对象转成接口输出。 图片存的是 object_key,URL 在这里现拼 —— 库里存 URL 会在换存储/改路径时 全部失效(order_site 踩过「存下来的签名链接过期后到处裂图」)。 ``buyer_cluster`` = 同一买家的其它单(见 :func:`buyer_clusters`), ``metric_view`` = 最近一次「积分 / 兑换记录」快照的三条线索(见 :func:`order_metric_views`), 都由调用方传进来(列表是一次查询算出整页的,别在这里按行查)。 ``last_metric`` 是兼容入口:只传它时三条线索都取这一条。 """ names = users or {} bind_images = images_of(order, "bind_images") home_images = images_of(order, "home_images") view = metric_view or OrderMetricView( latest=last_metric, score=last_metric, verdict=last_metric ) latest_metric = view.latest score_metric = view.score or view.latest verdict_metric = view.verdict or view.latest def urls(keys: list[str], variant: str = "") -> list[str]: return [build_file_url(key, variant) for key in keys] def name_of(value: int | None) -> str: return names.get(int(value), "") if value else "" return { "id": order.id, "order_no": order.order_no, "shop": order.shop or "", "owner_id": order.owner_id, "owner_name": name_of(order.owner_id), "uid": order.uid or "", "yyuid": order.yyuid or "", "hy_username": order.hy_username or "", "nickname": order.nickname or "", # 只暴露「有没有」,CK 本体绝不出接口。 "has_cookie": bool(order.cookie), "has_raw_cookie": bool(order.raw_cookie), "ck_status": order.ck_status, "ck_status_label": CK_STATUS_LABELS.get(order.ck_status, order.ck_status), "ck_checked_at": order.ck_checked_at, "ck_check_message": order.ck_check_message or "", "bind_douyu_account": order.bind_douyu_account or "", "bind_douyu_uid": order.bind_douyu_uid or "", # 探针读到的绑定对象(只读快照,人工不可编辑) "bind_game_account": order.bind_game_account or "", "bind_game_role": order.bind_game_role or "", "bind_game_channel": order.bind_game_channel or "", "bind_snapshot_at": order.bind_snapshot_at, "bind_images": bind_images, "home_images": home_images, "bind_image_urls": urls(bind_images), "home_image_urls": urls(home_images), "bind_image_thumb_urls": urls(bind_images, "thumb"), "home_image_thumb_urls": urls(home_images, "thumb"), "gift_name": order.gift_name or "", "required_points": order.required_points, "remark": order.remark or "", "status": order.status, "status_label": ORDER_STATUS_LABELS.get(order.status, order.status), "next_status": NEXT_STATUS.get(order.status), "bound_at": order.bound_at, "recharged_at": order.recharged_at, "scripted_at": order.scripted_at, "done_at": order.done_at, "points_checked_at": order.points_checked_at, "points_balance": order.points_balance, "points_required_total": order.points_required_total, "points_surplus": order.points_surplus, "points_threshold": order.points_threshold, "points_check_reason": order.points_check_reason or "", "points_check_message": order.points_check_message or "", "points_check_detail": order.points_check_detail, "void_reason": order.void_reason or "", "is_archived": order.archived_at is not None, "archived_at": order.archived_at, "archived_by": order.archived_by, "archived_by_name": name_of(order.archived_by), "archive_reason": order.archive_reason or "", "points": order.points, "elite_opened": order.elite_opened, "snapshot_at": order.snapshot_at, "created_by": order.created_by, "created_by_name": name_of(order.created_by), "updated_by": order.updated_by, "updated_by_name": name_of(order.updated_by), "version": int(order.version or 0), "created_at": order.created_at, "updated_at": order.updated_at, # 同一买家的其它单(软识别,只读派生;没有就是 null) "buyer_cluster": dict(buyer_cluster) if buyer_cluster else None, # 最近一次「积分 / 兑换记录」快照(生命周期时间线在详情里,列表只带这几条线索) # 积分与判定分别取「最近一条查到过它的」:拆分两个查询入口后,一次只写一半, # 不能让「只查积分」把判定徽标抹掉(反之亦然)。 "last_score": score_metric.score if score_metric else None, "last_metric_at": latest_metric.created_at if latest_metric else None, "last_metric_message": (latest_metric.message or "") if latest_metric else "", "last_verdict": (verdict_metric.verdict or "") if verdict_metric else "", "last_verdict_label": ( VERDICT_LABELS.get(verdict_metric.verdict, verdict_metric.verdict or "") if verdict_metric else "" ), "last_verdict_at": verdict_metric.created_at if verdict_metric else None, "last_verdict_message": ( (verdict_metric.message or "") if verdict_metric else "" ), } def buyer_key_of(order: HuyaExternalOrder) -> tuple[str, str] | None: """一行的买家指纹;探针还没读到「绑定账号 + 绑定角色」时返回 None(不参与归组)。""" account = str(order.bind_game_account or "").strip() role = str(order.bind_game_role or "").strip() if not account or not role: return None return (account, role) def buyer_clusters( db: Session, orders: Sequence[HuyaExternalOrder] ) -> dict[int, dict[str, Any]]: """算出这批行各自「同一买家的其它单」(不是按行发 SQL:整批一次查完)。 只有真的 ≥2 单才给结果 —— 单独一单不必在界面上标「同买家 1 单」。 返回 ``{order_id: {key, method, total, others: [...]}}``,``others`` 按创建时间升序。 """ keys: dict[tuple[str, str], None] = {} for order in orders: key = buyer_key_of(order) if key is not None: keys[key] = None if not keys: return {} pairs = list(keys) rows = ( db.query(HuyaExternalOrder) .filter( tuple_( HuyaExternalOrder.bind_game_account, HuyaExternalOrder.bind_game_role ).in_(pairs) ) .order_by(HuyaExternalOrder.created_at.asc(), HuyaExternalOrder.id.asc()) .all() ) grouped: dict[tuple[str, str], list[HuyaExternalOrder]] = {} for row in rows: key = buyer_key_of(row) if key is not None and key in keys: grouped.setdefault(key, []).append(row) clusters: dict[int, dict[str, Any]] = {} for key, siblings in grouped.items(): if len(siblings) < 2: continue for row in siblings: others = [ { "id": int(item.id), "order_no": item.order_no or "", "shop": item.shop or "", "gift_name": item.gift_name or "", "uid": item.uid or "", "status": item.status, "status_label": ORDER_STATUS_LABELS.get(item.status, item.status), "created_at": item.created_at, } for item in siblings if int(item.id) != int(row.id) ] clusters[int(row.id)] = { "key": f"{key[0]} · {key[1]}", "method": BUYER_KEY_METHOD, "total": len(siblings), "others": others, } return clusters