From 17ec07b63ac67783a4ea6be95c06f0c95b7780bf Mon Sep 17 00:00:00 2001 From: yml Date: Mon, 23 Nov 2026 19:14:44 +0800 Subject: [PATCH] =?UTF-8?q?refactor(collab):=20=E6=8B=86=E5=88=86=E6=96=97?= =?UTF-8?q?=E9=B1=BC=E8=99=8E=E7=89=99=E5=8D=8F=E4=BD=9C=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E4=B8=8E=E9=A1=B5=E9=9D=A2=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/backend/services/douyu_collab_catalog.py | 334 +++ web/backend/services/douyu_collab_common.py | 341 +++ web/backend/services/douyu_collab_exports.py | 190 ++ web/backend/services/douyu_collab_leases.py | 511 ++++ web/backend/services/douyu_collab_query.py | 495 ++++ web/backend/services/douyu_collab_service.py | 2386 +---------------- web/backend/services/douyu_collab_shops.py | 244 ++ web/backend/services/douyu_collab_sync.py | 368 +++ web/backend/services/huya_collab_catalog.py | 298 ++ web/backend/services/huya_collab_ck.py | 253 ++ web/backend/services/huya_collab_common.py | 349 +++ web/backend/services/huya_collab_exports.py | 99 + web/backend/services/huya_collab_query.py | 769 ++++++ web/backend/services/huya_collab_service.py | 2093 ++------------- web/backend/services/huya_collab_shops.py | 253 ++ web/frontend/src/pages/DouyuCollabPage.tsx | 447 +-- .../src/pages/DouyuCollabPageConfig.ts | 426 +++ web/frontend/src/pages/HuyaCollabPage.tsx | 350 +-- .../src/pages/HuyaCollabPageConfig.ts | 322 +++ 19 files changed, 5580 insertions(+), 4948 deletions(-) create mode 100644 web/backend/services/douyu_collab_catalog.py create mode 100644 web/backend/services/douyu_collab_common.py create mode 100644 web/backend/services/douyu_collab_exports.py create mode 100644 web/backend/services/douyu_collab_leases.py create mode 100644 web/backend/services/douyu_collab_query.py create mode 100644 web/backend/services/douyu_collab_shops.py create mode 100644 web/backend/services/douyu_collab_sync.py create mode 100644 web/backend/services/huya_collab_catalog.py create mode 100644 web/backend/services/huya_collab_ck.py create mode 100644 web/backend/services/huya_collab_common.py create mode 100644 web/backend/services/huya_collab_exports.py create mode 100644 web/backend/services/huya_collab_query.py create mode 100644 web/backend/services/huya_collab_shops.py create mode 100644 web/frontend/src/pages/DouyuCollabPageConfig.ts create mode 100644 web/frontend/src/pages/HuyaCollabPageConfig.ts diff --git a/web/backend/services/douyu_collab_catalog.py b/web/backend/services/douyu_collab_catalog.py new file mode 100644 index 0000000..3dd090f --- /dev/null +++ b/web/backend/services/douyu_collab_catalog.py @@ -0,0 +1,334 @@ +"""斗鱼外部单协作的礼包、商品解析与活动商品刷新。""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from sqlalchemy import func, or_ +from sqlalchemy.orm import Session + +from ..models import ( + Account, + DouyuCollabGift, + DouyuExternalOrder, + DouyuGoodsSnapshot, + PlatformCommodityMapping, + User, +) +from .audit_service import record_audit +from .business_events import record_account_query +from .douyu_account_probe import ( + config_mapping, + persist_probe_result, + probe_account, +) +from .douyu_collab_common import ( + CollabError, + _client_for_account, + _text, + _to_int, + account_by_id, + resolve_config, +) +from .douyu_goods_service import serialized_snapshots, upsert_goods_snapshot + + +def _resolve_gift( + db: Session, + *, + gift_name: str, + commodity_id: str, + required_points: Any, +) -> tuple[str, str, int | None]: + name = _text(gift_name, max_length=128) + cid = _text(commodity_id, max_length=64) + points = _to_int(required_points) + query = db.query(DouyuGoodsSnapshot) + row = None + if cid: + row = query.filter(DouyuGoodsSnapshot.commodity_id == cid).first() + if row is None and name: + row = query.filter(DouyuGoodsSnapshot.name == name).first() + if row is not None: + if not name: + name = _text(row.name, max_length=128) + if not cid: + cid = _text(row.commodity_id, max_length=64) + if points is None: + points = _to_int(row.score) + if points is None and name: + manual = ( + db.query(DouyuCollabGift) + .filter(DouyuCollabGift.name == name) + .first() + ) + if manual is not None: + points = int(manual.points or 0) + return name, cid, points + if not cid and name: + mapping = ( + db.query(PlatformCommodityMapping) + .filter( + PlatformCommodityMapping.target_platform == "douyu", + PlatformCommodityMapping.enabled.is_(True), + or_( + PlatformCommodityMapping.goods_name == name, + PlatformCommodityMapping.internal_sku_key == name, + ), + ) + .order_by(PlatformCommodityMapping.id.desc()) + .first() + ) + if mapping is not None: + cid = _text(mapping.commodity_id, max_length=64) + if points is None: + points = _to_int(mapping.required_points) + return name, cid, points + manual = db.query(DouyuCollabGift).filter(DouyuCollabGift.name == name).first() + if manual is not None: + return name, "", points if points is not None else int(manual.points or 0) + return name, cid, points + + +def list_gifts(db: Session, *, active_only: bool = False) -> list[DouyuCollabGift]: + query = db.query(DouyuCollabGift) + if active_only: + query = query.filter(DouyuCollabGift.is_active.is_(True)) + return query.order_by( + DouyuCollabGift.sort_order.asc(), + DouyuCollabGift.id.asc(), + ).all() + + +def get_gift(db: Session, gift_id: int) -> DouyuCollabGift: + gift = db.query(DouyuCollabGift).filter(DouyuCollabGift.id == gift_id).first() + if gift is None: + raise CollabError("礼包不存在", status_code=404, code="gift_not_found") + return gift + + +def create_gift( + db: Session, + current: User, + *, + name: str, + points: Any, + remark: str = "", +) -> DouyuCollabGift: + clean = _text(name, max_length=128) + if not clean: + raise CollabError("礼包名不能为空", code="gift_name_required") + clean_points = _to_int(points) + if clean_points is None or clean_points < 0: + raise CollabError("所需积分不能为空且不能小于 0", code="gift_points_invalid") + exists = db.query(DouyuCollabGift).filter(DouyuCollabGift.name == clean).first() + if exists: + raise CollabError("礼包已存在", status_code=409, code="gift_exists") + gift = DouyuCollabGift( + name=clean, + points=clean_points, + remark=_text(remark, max_length=255), + created_by=current.id, + updated_by=current.id, + ) + db.add(gift) + db.commit() + db.refresh(gift) + return gift + + +def update_gift( + db: Session, + current: User, + gift: DouyuCollabGift, + payload: Mapping[str, Any], +) -> DouyuCollabGift: + old_name = gift.name + old = { + "name": gift.name, + "points": gift.points, + "sort_order": gift.sort_order, + "is_active": gift.is_active, + "remark": gift.remark, + } + if "name" in payload: + name = _text(payload.get("name"), max_length=128) + if not name: + raise CollabError("礼包名不能为空", code="gift_name_required") + duplicate = ( + db.query(DouyuCollabGift.id) + .filter( + DouyuCollabGift.name == name, + DouyuCollabGift.id != gift.id, + ) + .first() + ) + if duplicate: + raise CollabError("礼包已存在", status_code=409, code="gift_exists") + gift.name = name + if "points" in payload: + points = _to_int(payload.get("points")) + if points is None or points < 0: + raise CollabError( + "所需积分不能为空且不能小于 0", + code="gift_points_invalid", + ) + gift.points = points + if "sort_order" in payload: + gift.sort_order = _to_int(payload.get("sort_order")) or 0 + if "is_active" in payload: + gift.is_active = bool(payload.get("is_active")) + if "remark" in payload: + gift.remark = _text(payload.get("remark"), max_length=255) + gift.updated_by = current.id + if gift.name != old_name: + db.query(DouyuExternalOrder).filter( + DouyuExternalOrder.gift_name == old_name + ).update( + {DouyuExternalOrder.gift_name: gift.name}, + synchronize_session=False, + ) + record_audit( + db, + current, + action="douyu:collab:gift_update", + target=f"douyu_collab_gift:{gift.id}", + detail={ + "old": old, + "new": { + "name": gift.name, + "points": gift.points, + "sort_order": gift.sort_order, + "is_active": gift.is_active, + "remark": gift.remark, + }, + }, + ) + db.commit() + db.refresh(gift) + return gift + + +def delete_gift( + db: Session, + current: User, + gift: DouyuCollabGift, +) -> dict[str, Any]: + gift_name = gift.name + gift_points = gift.points + used = ( + db.query(func.count(DouyuExternalOrder.id)) + .filter(DouyuExternalOrder.gift_name == gift_name) + .scalar() + or 0 + ) + if used: + raise CollabError( + f"还有 {used} 个协作单使用「{gift_name}」,请先停用或改名", + code="gift_in_use", + ) + record_audit( + db, + current, + action="douyu:collab:gift_delete", + target=f"douyu_collab_gift:{gift.id}", + detail={"name": gift_name, "points": gift_points}, + ) + db.delete(gift) + db.commit() + return {"success": True, "name": gift_name} + + +def list_gift_names(db: Session) -> list[str]: + rows = ( + db.query(DouyuExternalOrder.gift_name) + .filter(DouyuExternalOrder.gift_name != "") + .distinct() + .order_by(DouyuExternalOrder.gift_name.asc()) + .all() + ) + return [str(name) for (name,) in rows if name] + + +def refresh_activity_goods( + db: Session, + current: User, + *, + account_id: int | None = None, + client: Any | None = None, +) -> dict[str, Any]: + config = resolve_config(db) + account = account_by_id(db, account_id) + if account is None: + account = ( + db.query(Account) + .filter(Account.cookie.isnot(None), Account.cookie != "") + .order_by(Account.id.asc()) + .first() + ) + if account is None: + raise CollabError("没有带 CK 的斗鱼账号,无法刷新活动商品", code="no_account") + active_client = client or _client_for_account(account) + config_info = config_mapping(config) + db.expunge(account) + db.commit() + db.add(account) + try: + probe = probe_account( + account, + config_info, + client=active_client, + session_checker=None, + with_elite=False, + with_elite_role=False, + with_goods=True, + ) + goods = (probe.get("goods") or {}).get("items") or [] + if (probe.get("goods") or {}).get("status") == "error": + raise RuntimeError( + (probe.get("goods") or {}).get("error") or "商品查询失败" + ) + persist_probe_result( + db, + account, + probe, + current=current, + source="douyu_collab.goods_refresh", + record_event=False, + ) + except Exception as exc: + record_account_query( + db, + account, + query_type="goods_refresh", + title="刷新活动商品", + ok=False, + detail={"error": str(exc)[:1000]}, + actor_id=current.id, + ) + db.commit() + raise + upsert_goods_snapshot(db, goods, commit=False) + record_account_query( + db, + account, + query_type="goods_refresh", + title="刷新活动商品", + ok=True, + detail={"count": len(goods)}, + actor_id=current.id, + ) + record_audit( + db, + current, + action="douyu:collab:goods_refresh", + target=f"douyu_external_goods:{account.id}", + detail={"count": len(goods), "account_id": account.id}, + ) + db.commit() + return {"count": len(goods), "goods": serialized_goods(db)} + + +def serialized_goods(db: Session) -> list[dict[str, Any]]: + return serialized_snapshots(db) diff --git a/web/backend/services/douyu_collab_common.py b/web/backend/services/douyu_collab_common.py new file mode 100644 index 0000000..b58503a --- /dev/null +++ b/web/backend/services/douyu_collab_common.py @@ -0,0 +1,341 @@ +"""斗鱼外部单协作的共享状态、校验与轻量查询。""" + +from __future__ import annotations + +from collections.abc import Mapping +from datetime import UTC, datetime +from typing import Any + +from loguru import logger +from sqlalchemy.orm import Session + +from core.douyu import DouyuActivityClient + +from ..models import Account, DouyuConfig, DouyuExternalOrder, User +from .account_query_filters import ACTIVE_COLLAB_STATUSES +from .douyu_account_probe import activity_client +from .douyu_goods_service import serialize_live_goods as _serialize_live_goods + +STATUS_INCOMPLETE = "incomplete" +STATUS_TO_RECHARGE = "to_recharge" +STATUS_RECHARGED = "recharged" +STATUS_SCRIPTED = "scripted" +STATUS_DONE = "done" +STATUS_POINTS_ERROR = "points_error" +STATUS_ROLE_ERROR = "role_error" +STATUS_FAILED = "failed" +STATUS_VOID = "void" +LEASE_PURPOSE_DOUYU_COLLAB = "douyu_collab" +COLLAB_LEASE_STATUSES = ACTIVE_COLLAB_STATUSES + +ORDER_STATUSES: tuple[str, ...] = ( + STATUS_INCOMPLETE, + STATUS_TO_RECHARGE, + STATUS_RECHARGED, + STATUS_SCRIPTED, + STATUS_DONE, + STATUS_POINTS_ERROR, + STATUS_ROLE_ERROR, + STATUS_FAILED, + STATUS_VOID, +) + +ORDER_STATUS_LABELS = { + STATUS_INCOMPLETE: "待补资料", + STATUS_TO_RECHARGE: "待充值", + STATUS_RECHARGED: "已充值", + STATUS_SCRIPTED: "已上脚本", + STATUS_DONE: "抢购成功", + STATUS_POINTS_ERROR: "积分异常", + STATUS_ROLE_ERROR: "账号角色异常", + STATUS_FAILED: "抢购失败", + STATUS_VOID: "已作废", +} + +STATUS_FLOW: tuple[str, ...] = ( + STATUS_INCOMPLETE, + STATUS_TO_RECHARGE, + STATUS_RECHARGED, + STATUS_SCRIPTED, + STATUS_DONE, +) + +SOURCE_TYPE_PLATFORM_FULFILLMENT = "platform_fulfillment" +ACCOUNT_REPLACE_ROLES = frozenset({"super_admin", "operation"}) +ACCOUNT_RECOMMEND_DEFAULT_SCAN_LIMIT = 20 +PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES = frozenset( + { + "lock_goods", + "pay_locked_order", + "exchange_goods", + "exchange_esports_goods", + "exchange_xpd_goods", + "create_elite_qr", + "create_esports_qr", + "create_gold_qr", + "donate_elite_gift", + "donate_esports_chicken_gift", + "donate_esports_firework_gift", + } +) + +STAGE_INDEX = { + STATUS_INCOMPLETE: 0, + STATUS_TO_RECHARGE: 1, + STATUS_RECHARGED: 2, + STATUS_SCRIPTED: 3, + STATUS_DONE: 4, +} + +STATUS_TIMESTAMP_FIELDS = { + STATUS_RECHARGED: "recharged_at", + STATUS_SCRIPTED: "scripted_at", + STATUS_DONE: "done_at", +} + +SUCCESS_PURCHASE_FIELDS = frozenset( + { + "order_no", + "account_username", + "gift_name", + "commodity_id", + "required_points", + } +) + +ARCHIVABLE_STATUSES = (STATUS_DONE,) +POINTS_GROUP_STATUSES: tuple[str, ...] = ( + STATUS_TO_RECHARGE, + STATUS_RECHARGED, + STATUS_POINTS_ERROR, +) + +POINTS_THRESHOLD_DEFAULT = 100 +POINTS_THRESHOLD_MAX = 1_000_000 +ACTIVITY_RECORD_SETTLE_SECONDS = 300 +ACTIVITY_RECORD_TIME_SKEW_SECONDS = 60 +ACTIVITY_RECORD_FETCH_LIMIT = 100 +ACTIVITY_RECORD_MAX_PAGES = 5 +ACTIVITY_METRIC_RECORD_LIMIT = 50 +MAX_IMAGES = 20 +CK_EXPORT_BATCH_MAX = 50 +CK_EXPORT_ACTION = "douyu:collab:ck_export" +USERNAME_EXPORT_BATCH_MAX = 500 + +VERDICT_SUCCESS = "success" +VERDICT_FAILED = "failed" +VERDICT_UNKNOWN = "unknown" + +CK_VALID = "valid" +CK_INVALID = "invalid" +CK_UNVERIFIED = "unverified" +CK_LABELS = { + CK_VALID: "CK 正常", + CK_INVALID: "CK 异常", + CK_UNVERIFIED: "未检测", +} + + +class CollabError(RuntimeError): + def __init__(self, detail: str, *, status_code: int = 400, code: str = ""): + super().__init__(detail) + self.detail = detail + self.status_code = status_code + self.code = code + + +def _now() -> datetime: + return datetime.now(UTC) + + +def _to_int(value: Any) -> int | None: + if value is None or value == "": + return None + try: + return int(float(value)) + except (TypeError, ValueError): + return None + + +def _text(value: Any, *, max_length: int | None = None) -> str: + text = str(value or "").strip() + return text[:max_length] if max_length else text + + +def _mark_order_succeeded( + order: DouyuExternalOrder, + when: datetime | None = None, +) -> None: + """记录首次成功时间;状态回退不能清掉这条购买锁定依据。""" + if order.succeeded_at is None: + order.succeeded_at = when or _now() + + +def _missing_for_recharge(order: DouyuExternalOrder) -> list[str]: + missing: list[str] = [] + if not order.account_id or not _text(order.account_username): + missing.append("斗鱼账号") + if not order.gift_name: + missing.append("礼包") + if not order.home_images: + missing.append("主页截图") + if not order.bind_game_role: + missing.append("绑定角色(先校验账号)") + return missing + + +def _json_safe(value: Any) -> Any: + if isinstance(value, dict): + return {str(k): _json_safe(v) for k, v in value.items()} + if isinstance(value, list): + return [_json_safe(item) for item in value] + if isinstance(value, (str, int, float, bool)) or value is None: + return value + return str(value) + + +def _first_value(data: Mapping[str, Any], *keys: str) -> Any: + """取第一个存在且非 None 的字段;0 是合法值,不能用 `or` 兜。""" + for key in keys: + if key in data and data.get(key) is not None: + return data.get(key) + return None + + +def normalize_images(value: Any, *, field: str = "home_images") -> list[str]: + if value is None: + return [] + if not isinstance(value, list): + raise CollabError(f"{field} 必须是图片 key 数组", code="images_invalid") + keys: list[str] = [] + for item in value: + key = _text(item, max_length=512) + if key and key not in keys: + keys.append(key) + if len(keys) > MAX_IMAGES: + raise CollabError(f"最多 {MAX_IMAGES} 张图片", code="images_too_many") + return keys + + +def normalize_threshold(value: Any) -> int: + number = _to_int(value) + if number is None: + return POINTS_THRESHOLD_DEFAULT + if number < 0: + raise CollabError("积分阈值不能小于 0", code="points_threshold_invalid") + return min(number, POINTS_THRESHOLD_MAX) + + +def resolve_config(db: Session) -> DouyuConfig: + config = db.query(DouyuConfig).order_by(DouyuConfig.id.asc()).first() + if config is None: + config = DouyuConfig() + db.add(config) + db.flush() + return config + + +def account_by_username(db: Session, username: str) -> Account | None: + name = _text(username, max_length=128) + if not name: + return None + return ( + db.query(Account) + .filter(Account.username == name) + .order_by(Account.id.asc()) + .first() + ) + + +def account_by_id(db: Session, account_id: int | None) -> Account | None: + if not account_id: + return None + return db.query(Account).filter(Account.id == account_id).first() + + +def users_by_id(db: Session, ids: set[int]) -> dict[int, str]: + clean = {int(item) for item in ids if item} + if not clean: + return {} + return { + int(user_id): str(username) + for user_id, username in db.query(User.id, User.username) + .filter(User.id.in_(clean)) + .all() + } + + +def accounts_by_id(db: Session, ids: set[int]) -> dict[int, Account]: + clean = {int(item) for item in ids if item} + if not clean: + return {} + return { + int(account.id): account + for account in db.query(Account).filter(Account.id.in_(clean)).all() + } + + +def _client_for_account(account: Account) -> DouyuActivityClient: + cookie = str(account.cookie or "").strip() + if not cookie: + raise CollabError("该账号没有 CK", code="account_no_cookie") + return activity_client( + cookie, + logger_callback=lambda message: logger.debug( + "[douyu-collab] account={} {}", + account.id, + message, + ), + ) + + +def serialize_live_goods(goods: list[dict[str, Any]]) -> list[dict[str, Any]]: + """把 storehome 原始商品映射成前端稳定字段。""" + return _serialize_live_goods(goods) + + +def _assert_version(order: DouyuExternalOrder, expected: int | None) -> None: + if expected is not None and int(expected) != int(order.version or 0): + raise CollabError( + "这行已被别人修改,请刷新后再试", + status_code=409, + code="version_conflict", + ) + + +def _assert_mutable(order: DouyuExternalOrder) -> None: + if order.archived_at is not None: + raise CollabError("已归档的订单不能再编辑", code="order_archived") + if order.status == STATUS_VOID: + raise CollabError("已作废的订单不能再编辑", code="order_void") + + +def _assert_account_replace_permission(current: User) -> None: + """撤号和推荐属于高风险改号操作,只允许超级管理员和运营。""" + if current.role not in ACCOUNT_REPLACE_ROLES: + raise CollabError( + "仅超级管理员和运营可以解除或推荐账号", + status_code=403, + code="account_replace_forbidden", + ) + + +def _assert_account_replaceable(order: DouyuExternalOrder) -> None: + _assert_mutable(order) + if order.status == STATUS_DONE or order.done_at is not None: + raise CollabError( + "已完成订单不能更换账号,请先确认是否需要回退状态", + code="order_done_immutable", + ) + + +def _assert_success_account_change_allowed( + current: User, + order: DouyuExternalOrder, +) -> None: + if order.succeeded_at is not None and current.role != "super_admin": + raise CollabError( + "订单已有成功记录,购买账号仅允许超级管理员修改", + status_code=403, + code="purchase_lock_admin_required", + ) diff --git a/web/backend/services/douyu_collab_exports.py b/web/backend/services/douyu_collab_exports.py new file mode 100644 index 0000000..0ff0e09 --- /dev/null +++ b/web/backend/services/douyu_collab_exports.py @@ -0,0 +1,190 @@ +"""斗鱼外部单协作的账号凭据与用户名导出。""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +from sqlalchemy.orm import Session + +from ..models import DouyuExternalOrder, User +from .audit_service import record_audit +from .douyu_collab_common import ( + CK_EXPORT_ACTION, + CK_EXPORT_BATCH_MAX, + CK_LABELS, + ORDER_STATUS_LABELS, + USERNAME_EXPORT_BATCH_MAX, + CollabError, + account_by_id, + account_by_username, +) + + +def export_cks( + db: Session, + current: User, + order_ids: Sequence[int], + *, + commit: bool = True, +) -> dict[str, Any]: + """导出协作单关联内部账号的 **CK 明文**(前端写剪贴板用)。 + + 斗鱼协作单本身不存 CK,导出的始终是关联 ``accounts.cookie`` 的实时值。 + 和虎牙台账保持同一口径: + + 1. 需要独立权限点 ``douyu:collab:ck_export``; + 2. 每条成功导出都写审计,但审计里只记单号/账号/CK 状态,**不记 CK 本体**; + 3. 未绑定账号、账号没有 CK、订单已删除的行显式跳过并返回原因。 + """ + requested = list(dict.fromkeys(int(item) for item in order_ids if item)) + if not requested: + raise CollabError("请先勾选要导出的行", code="ck_export_empty") + if len(requested) > CK_EXPORT_BATCH_MAX: + raise CollabError( + f"一次最多导出 {CK_EXPORT_BATCH_MAX} 行,请分批操作", + code="ck_export_too_large", + ) + + rows = ( + db.query(DouyuExternalOrder).filter(DouyuExternalOrder.id.in_(requested)).all() + ) + by_id = {int(order.id): order for order in rows} + items: list[dict[str, Any]] = [] + skipped: list[dict[str, Any]] = [] + for order_id in requested: + order = by_id.get(order_id) + if order is None: + skipped.append( + { + "id": order_id, + "order_no": "", + "reason": "协作单不存在或已删除", + } + ) + continue + account = account_by_id(db, order.account_id) or account_by_username( + db, order.account_username + ) + ck_text = str(account.cookie or "").strip() if account else "" + if not ck_text: + reason = ( + "这单还没绑定斗鱼账号" if account is None else "关联的斗鱼账号还没有 CK" + ) + skipped.append( + { + "id": int(order.id), + "order_no": order.order_no, + "reason": reason, + } + ) + continue + + assert account is not None + ck_status = str(account.ck_check_status or "") + items.append( + { + "id": int(order.id), + "order_no": order.order_no, + "account_id": int(account.id), + "account_username": account.username or order.account_username or "", + "account_password": str(account.password or ""), + "account_nickname": account.nickname or order.account_nickname or "", + "status": order.status, + "status_label": ORDER_STATUS_LABELS.get(order.status, order.status), + "ck_status": ck_status, + "ck_status_label": CK_LABELS.get(ck_status, ""), + "ck_text": ck_text, + } + ) + record_audit( + db, + current, + action=CK_EXPORT_ACTION, + target=f"douyu_external_order:{order.id}", + detail={ + "order_no": order.order_no, + "account_username": account.username or order.account_username or "", + "ck_status": ck_status, + "batch_size": len(requested), + }, + ) + if commit: + db.commit() + return { + "total": len(requested), + "exported": len(items), + "skipped": skipped, + "items": items, + } + +def export_usernames( + db: Session, + order_ids: Sequence[int], +) -> dict[str, Any]: + """导出勾选订单关联的斗鱼用户名(去重、保持选择顺序)。 + + 用户名不是凭据,能看列表的人本来就能看到,所以这里不额外要求 CK 导出权限, + 也不写审计;没有用户名的行会显式跳过。 + """ + requested = list(dict.fromkeys(int(item) for item in order_ids if item)) + if not requested: + raise CollabError("请先勾选要导出的行", code="username_export_empty") + if len(requested) > USERNAME_EXPORT_BATCH_MAX: + raise CollabError( + f"一次最多导出 {USERNAME_EXPORT_BATCH_MAX} 行,请分批操作", + code="username_export_too_large", + ) + + rows = ( + db.query(DouyuExternalOrder).filter(DouyuExternalOrder.id.in_(requested)).all() + ) + by_id = {int(order.id): order for order in rows} + items: list[dict[str, Any]] = [] + skipped: list[dict[str, Any]] = [] + usernames: list[str] = [] + seen: set[str] = set() + for order_id in requested: + order = by_id.get(order_id) + if order is None: + skipped.append( + { + "id": order_id, + "order_no": "", + "reason": "协作单不存在或已删除", + } + ) + continue + username = str(order.account_username or "").strip() + if not username: + account = account_by_id(db, order.account_id) or account_by_username( + db, order.account_username + ) + username = str(account.username if account else "").strip() + if not username: + skipped.append( + { + "id": int(order.id), + "order_no": order.order_no, + "reason": "这单还没填斗鱼用户名", + } + ) + continue + items.append( + { + "id": int(order.id), + "order_no": order.order_no, + "account_username": username, + } + ) + if username not in seen: + seen.add(username) + usernames.append(username) + return { + "total": len(requested), + "exported": len(items), + "unique": len(usernames), + "skipped": skipped, + "items": items, + "usernames": usernames, + } diff --git a/web/backend/services/douyu_collab_leases.py b/web/backend/services/douyu_collab_leases.py new file mode 100644 index 0000000..7ff4b0e --- /dev/null +++ b/web/backend/services/douyu_collab_leases.py @@ -0,0 +1,511 @@ +"""斗鱼外部单协作的账号占用、平台租约接管与释放。""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from sqlalchemy.orm import Session + +from ..models import ( + AccountLease, + DouyuExternalOrder, + DouyuTask, + PlatformFulfillmentTask, + User, +) +from ..permissions import user_has_permission +from .account_events_service import ( + CATEGORY_OPS, + EVENT_LEASE_ACQUIRED, + emit, +) +from .audit_service import record_audit +from .douyu_collab_common import ( + COLLAB_LEASE_STATUSES, + LEASE_PURPOSE_DOUYU_COLLAB, + PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES, + SOURCE_TYPE_PLATFORM_FULFILLMENT, + CollabError, +) +from .platform_fulfillment.account_selector import ( + acquire_account_lease, + active_lease_for_account, + release_lease, +) + + +def _order_occupies_account(order: DouyuExternalOrder) -> bool: + return ( + bool(order.account_id) + and order.archived_at is None + and order.status in COLLAB_LEASE_STATUSES + ) + + +def _active_collab_order( + db: Session, + account_id: int, + *, + exclude_order_id: int | None = None, +) -> DouyuExternalOrder | None: + query = db.query(DouyuExternalOrder).filter( + DouyuExternalOrder.account_id == int(account_id), + DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES), + DouyuExternalOrder.archived_at.is_(None), + ) + if exclude_order_id is not None: + query = query.filter(DouyuExternalOrder.id != int(exclude_order_id)) + return query.order_by(DouyuExternalOrder.updated_at.desc()).first() + + +def _platform_lease_matches_source( + db: Session, + lease: AccountLease, + order: DouyuExternalOrder, +) -> bool: + if ( + lease.purpose != "platform_fulfillment" + or order.source_type != SOURCE_TYPE_PLATFORM_FULFILLMENT + or not order.source_task_id + ): + return False + task = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id == int(order.source_task_id)) + .first() + ) + return bool( + task is not None + and (task.lease_id == lease.id or lease.batch_id == f"pf:{int(task.id)}") + ) + + +def _lock_active_lease_for_account( + db: Session, + account_id: int, +) -> AccountLease | None: + return ( + db.query(AccountLease) + .filter( + AccountLease.account_id == int(account_id), + AccountLease.status == "active", + ) + .with_for_update() + .first() + ) + + +def _platform_task_for_lease( + db: Session, + lease: AccountLease, +) -> PlatformFulfillmentTask | None: + task_id = 0 + if lease.batch_id.startswith("pf:"): + try: + task_id = int(lease.batch_id.removeprefix("pf:")) + except ValueError: + task_id = 0 + query = db.query(PlatformFulfillmentTask).with_for_update() + if task_id: + task = query.filter(PlatformFulfillmentTask.id == task_id).first() + if task is not None: + return task + return query.filter(PlatformFulfillmentTask.lease_id == int(lease.id)).first() + + +def _takeover_platform_lease_for_collab( + db: Session, + current: User, + order: DouyuExternalOrder, + lease: AccountLease, +) -> AccountLease: + """外部协作显式接管平台租约,并在同一事务内把平台任务转人工。""" + if not user_has_permission(current, "platform_fulfillment:use"): + raise CollabError( + "没有接管平台履约账号的权限", + status_code=403, + code="platform_takeover_forbidden", + ) + platform_task = _platform_task_for_lease(db, lease) + if platform_task is None: + raise CollabError( + "平台履约任务不存在,请刷新后重试", + status_code=409, + code="account_lease_conflict", + ) + if platform_task.execution_status in {"completed", "cancelled"}: + raise CollabError( + f"平台履约任务 #{platform_task.id} 已结束,不能由协作单接管", + status_code=409, + code="platform_task_not_takeoverable", + ) + if ( + platform_task.account_id != lease.account_id + or platform_task.lease_id != lease.id + ): + raise CollabError( + f"平台履约任务 #{platform_task.id} 与账号租约不一致,请先核对", + status_code=409, + code="account_lease_conflict", + ) + blocking = ( + db.query(DouyuTask) + .filter( + DouyuTask.platform_task_id == int(platform_task.id), + DouyuTask.status.in_(("planned", "pending", "running")), + DouyuTask.task_type.in_(PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES), + ) + .order_by(DouyuTask.id.desc()) + .first() + ) + if blocking is not None: + raise CollabError( + f"平台履约任务 #{platform_task.id} 正在执行资金/兑换操作,请先停止任务", + status_code=409, + code="platform_task_running", + ) + + from .platform_fulfillment import service as platform_service + + platform_service.prepare_platform_task_for_collab_takeover( + db, + task=platform_task, + current=current, + collab_order_no=order.order_no, + ) + previous_task_id = int(platform_task.id) + lease.purpose = LEASE_PURPOSE_DOUYU_COLLAB + lease.batch_id = f"collab:{int(lease.account_id)}"[:64] + lease.commodity_id = "" + lease.holder_user_id = int(current.id) + lease.expires_at = None + lease.released_at = None + lease.release_reason = "" + emit( + db, + account_id=int(lease.account_id), + event_type=EVENT_LEASE_ACQUIRED, + title=f"外部协作接管平台履约账号:{order.order_no}", + category=CATEGORY_OPS, + detail={ + "lease_id": lease.id, + "order_id": order.id, + "order_no": order.order_no, + "platform_task_id": previous_task_id, + "reason": "collab_manual_takeover", + }, + source="lease", + subject_type="order", + subject_key=order.order_no, + actor_type="user", + actor_id=int(current.id), + source_ref=f"account_lease_collab_takeover:{lease.id}", + ) + _audit_lease_action( + db, + current, + order=order, + account_id=int(lease.account_id), + action="douyu:collab:lease_takeover", + lease=lease, + detail={ + "lease_id": lease.id, + "order_id": order.id, + "order_no": order.order_no, + "platform_task_id": previous_task_id, + "reason": "collab_manual_takeover", + }, + ) + return lease + + +def _audit_lease_action( + db: Session, + current: User, + *, + order: DouyuExternalOrder | None, + account_id: int, + action: str, + lease: AccountLease, + detail: Mapping[str, Any], +) -> None: + entry = record_audit( + db, + current, + action=action, + target=( + ( + f"douyu_external_order:{order.id}" + if order.id + else f"douyu_external_order_no:{order.order_no}" + ) + if order is not None + else f"account:{account_id}" + ), + detail=detail, + ) + entry.account_id = account_id + + +def _ensure_order_account_lease( + db: Session, + current: User, + order: DouyuExternalOrder, + *, + account_id: int | None = None, + force_active: bool = False, + takeover_platform_lease: bool = False, + commit: bool = False, +) -> AccountLease | None: + target_account_id = int(account_id or order.account_id or 0) + if not target_account_id: + return None + if not force_active and not _order_occupies_account(order): + return None + + lease = _lock_active_lease_for_account(db, target_account_id) + if lease is not None: + if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: + return lease + if takeover_platform_lease: + return _takeover_platform_lease_for_collab( + db, + current, + order, + lease, + ) + if _platform_lease_matches_source(db, lease, order): + return lease + platform_task = _platform_task_for_lease(db, lease) + task_label = ( + f"平台履约任务 #{platform_task.id}" + if platform_task is not None + else "平台履约任务" + ) + raise CollabError( + f"该账号当前被{task_label}占用,请确认转人工后再使用", + status_code=409, + code="account_lease_conflict", + ) + + lease = acquire_account_lease( + db, + account_id=target_account_id, + holder_user_id=int(current.id), + scope="elite", + purpose=LEASE_PURPOSE_DOUYU_COLLAB, + batch_id=f"collab:{target_account_id}", + commit=False, + ) + if lease is None: + raise CollabError( + "该账号刚被其他业务占用,请刷新后重试", + status_code=409, + code="account_lease_conflict", + ) + _audit_lease_action( + db, + current, + order=order, + account_id=target_account_id, + action="douyu:collab:lease_acquired", + lease=lease, + detail={ + "lease_id": lease.id, + "account_id": target_account_id, + "purpose": lease.purpose, + "batch_id": lease.batch_id, + }, + ) + if commit: + db.commit() + return lease + + +def _release_order_account_lease( + db: Session, + current: User, + order: DouyuExternalOrder, + *, + reason: str, + account_id: int | None = None, + commit: bool = False, +) -> bool: + target_account_id = int(account_id or order.account_id or 0) + if not target_account_id: + return False + if _active_collab_order(db, target_account_id, exclude_order_id=int(order.id)): + return False + lease = active_lease_for_account(db, target_account_id) + if lease is None or lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB: + return False + released = release_lease(db, lease, reason=reason, commit=False) + if released: + _audit_lease_action( + db, + current, + order=order, + account_id=target_account_id, + action="douyu:collab:lease_released", + lease=lease, + detail={ + "lease_id": lease.id, + "account_id": target_account_id, + "reason": reason, + }, + ) + if commit: + db.commit() + return released + + +def _sync_order_lease( + db: Session, + current: User, + order: DouyuExternalOrder, + *, + reason: str, + force_active: bool = False, + reuse_active_lease: bool = False, + commit: bool = False, +) -> AccountLease | None: + if force_active or _order_occupies_account(order): + if reuse_active_lease: + lease = _lock_active_lease_for_account(db, int(order.account_id or 0)) + if lease is not None: + if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: + return lease + if _platform_lease_matches_source(db, lease, order): + return lease + platform_task = _platform_task_for_lease(db, lease) + task_label = ( + f"平台履约任务 #{platform_task.id}" + if platform_task is not None + else "平台履约任务" + ) + raise CollabError( + f"该账号当前被{task_label}占用,请先由协作单确认接管", + status_code=409, + code="account_lease_conflict", + ) + return _ensure_order_account_lease( + db, + current, + order, + force_active=force_active, + commit=commit, + ) + _release_order_account_lease( + db, + current, + order, + reason=reason, + commit=commit, + ) + return None + + +def retain_lease_for_active_collab( + db: Session, + *, + account_id: int, + holder_user_id: int, + current: User | None = None, + lease: AccountLease | None = None, + source_task_id: int | None = None, + reason: str = "platform_release_to_collab", + commit: bool = False, +) -> AccountLease | None: + """平台释放账号时,把仍在活动的协作占用接续为统一协作租约。""" + active_lease = lease or active_lease_for_account(db, account_id) + if active_lease is not None and active_lease.status != "active": + return None + + query = db.query(DouyuExternalOrder).filter( + DouyuExternalOrder.account_id == int(account_id), + DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES), + DouyuExternalOrder.archived_at.is_(None), + ) + if source_task_id: + preferred = ( + query.filter(DouyuExternalOrder.source_task_id == int(source_task_id)) + .order_by(DouyuExternalOrder.updated_at.desc()) + .first() + ) + order = ( + preferred or query.order_by(DouyuExternalOrder.updated_at.desc()).first() + ) + else: + order = query.order_by(DouyuExternalOrder.updated_at.desc()).first() + if order is None: + return None + + holder_id = int( + holder_user_id + or (order.owner_id if order.owner_id else 0) + or (active_lease.holder_user_id if active_lease else 0) + ) + if not holder_id: + return None + + if active_lease is None: + active_lease = acquire_account_lease( + db, + account_id=int(account_id), + holder_user_id=holder_id, + scope="elite", + purpose=LEASE_PURPOSE_DOUYU_COLLAB, + batch_id=f"collab:{int(account_id)}", + commit=False, + ) + if active_lease is None: + return None + elif active_lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB: + previous_purpose = active_lease.purpose + active_lease.purpose = LEASE_PURPOSE_DOUYU_COLLAB + active_lease.batch_id = f"collab:{int(account_id)}"[:64] + active_lease.commodity_id = "" + active_lease.expires_at = None + active_lease.release_reason = "" + active_lease.holder_user_id = holder_id + emit( + db, + account_id=int(account_id), + event_type=EVENT_LEASE_ACQUIRED, + title=f"外部协作接管账号占用:{order.order_no}", + category=CATEGORY_OPS, + detail={ + "lease_id": active_lease.id, + "order_id": order.id, + "order_no": order.order_no, + "purpose": active_lease.purpose, + "previous_purpose": previous_purpose, + "reason": reason, + }, + source="lease", + subject_type="order", + subject_key=order.order_no, + actor_type="user" if current is not None else "system", + actor_id=int(current.id) if current is not None else None, + source_ref=f"account_lease_collab_takeover:{active_lease.id}", + ) + + if current is not None: + _audit_lease_action( + db, + current, + order=order, + account_id=int(account_id), + action="douyu:collab:lease_takeover", + lease=active_lease, + detail={ + "lease_id": active_lease.id, + "order_id": order.id, + "order_no": order.order_no, + "reason": reason, + }, + ) + if commit: + db.commit() + return active_lease diff --git a/web/backend/services/douyu_collab_query.py b/web/backend/services/douyu_collab_query.py new file mode 100644 index 0000000..1b378c2 --- /dev/null +++ b/web/backend/services/douyu_collab_query.py @@ -0,0 +1,495 @@ +"""斗鱼外部单协作的查询、序列化、汇总与时间线。""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from sqlalchemy import and_, func, or_ +from sqlalchemy.orm import Session + +from ..models import Account, AuditLog, DouyuExternalOrder, DouyuExternalOrderMetric +from .collab_common import count_archived, order_visibility_expr +from .douyu_collab_common import ( + CK_INVALID, + CK_UNVERIFIED, + CK_VALID, + ORDER_STATUS_LABELS, + STAGE_INDEX, + STATUS_DONE, + STATUS_FLOW, + STATUS_INCOMPLETE, + STATUS_VOID, + VERDICT_FAILED, + VERDICT_SUCCESS, + VERDICT_UNKNOWN, + CollabError, + _missing_for_recharge, + _text, + accounts_by_id, + users_by_id, +) +from .douyu_collab_shops import resolve_shop_name +from .file_service import build_file_url + + +def _metric_views( + db: Session, order_ids: list[int] +) -> tuple[dict[int, DouyuExternalOrderMetric], dict[int, DouyuExternalOrderMetric]]: + """返回最近一条快照,以及最近一条带兑换判定的快照。 + + 余额查询也会落快照,但它的 verdict 是 unknown;列表上的兑换结论应沿用 + 最近一次「查兑换记录」的结果,不能被余额刷新覆盖。 + """ + if not order_ids: + return {}, {} + rows = ( + db.query(DouyuExternalOrderMetric) + .filter(DouyuExternalOrderMetric.order_id.in_(order_ids)) + .order_by( + DouyuExternalOrderMetric.order_id.asc(), + DouyuExternalOrderMetric.id.desc(), + ) + .all() + ) + latest: dict[int, DouyuExternalOrderMetric] = {} + verdict_latest: dict[int, DouyuExternalOrderMetric] = {} + for row in rows: + order_id = int(row.order_id) + latest.setdefault(order_id, row) + if not str(row.source or "").startswith("balance"): + verdict_latest.setdefault(order_id, row) + return latest, verdict_latest + +def account_clusters( + db: Session, orders: list[DouyuExternalOrder] +) -> dict[int, dict[str, Any]]: + account_ids = {int(order.account_id) for order in orders if order.account_id} + if not account_ids: + return {} + rows = ( + db.query(DouyuExternalOrder) + .filter( + DouyuExternalOrder.account_id.in_(account_ids), + DouyuExternalOrder.archived_at.is_(None), + DouyuExternalOrder.status != STATUS_VOID, + ) + .order_by(DouyuExternalOrder.id.asc()) + .all() + ) + grouped: dict[int, list[DouyuExternalOrder]] = {} + for row in rows: + if row.account_id: + grouped.setdefault(int(row.account_id), []).append(row) + result: dict[int, dict[str, Any]] = {} + for account_id, items in grouped.items(): + if len(items) <= 1: + continue + result[account_id] = { + "total": len(items), + "orders": [ + { + "id": int(item.id), + "order_no": item.order_no, + "status": item.status, + "status_label": ORDER_STATUS_LABELS.get(item.status, item.status), + "gift_name": item.gift_name, + } + for item in items + ], + } + return result + +def _image_urls(keys: list[str], variant: str = "") -> list[str]: + return [build_file_url(key, variant) for key in keys] + +def serialize_order( + order: DouyuExternalOrder, + *, + users: Mapping[int, str] | None = None, + accounts: Mapping[int, Account] | None = None, + cluster: Mapping[str, Any] | None = None, + metric: DouyuExternalOrderMetric | None = None, + verdict_metric: DouyuExternalOrderMetric | None = None, +) -> dict[str, Any]: + users = users or {} + accounts = accounts or {} + account = accounts.get(int(order.account_id)) if order.account_id else None + images = list(order.home_images or []) + payload = { + "id": int(order.id), + "order_no": order.order_no, + "shop": order.shop or "", + "shop_original_name": order.shop_original_name or order.shop or "", + "owner_id": order.owner_id, + "owner_name": users.get(int(order.owner_id), "") if order.owner_id else "", + "source_type": order.source_type or "manual", + "source_task_id": order.source_task_id, + "source_order_id": order.source_order_id or "", + "source_order_item_id": order.source_order_item_id or "", + "source_platform_order_id": order.source_platform_order_id or "", + "last_synced_at": order.last_synced_at, + "account_id": order.account_id, + "account_username": order.account_username or "", + "account_uid": order.account_uid or "", + "account_nickname": order.account_nickname or "", + "account_exists": account is not None, + "has_cookie": bool(account and account.cookie), + "account_ck_status": (account.ck_check_status if account else "") or "", + "account_status": (account.status if account else "") 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, + "home_images": images, + "home_image_urls": _image_urls(images), + "home_image_thumb_urls": _image_urls(images, "thumb"), + "gift_name": order.gift_name or "", + "commodity_id": order.commodity_id or "", + "required_points": order.required_points, + "remark": order.remark or "", + "status": order.status or STATUS_INCOMPLETE, + "status_label": ORDER_STATUS_LABELS.get( + order.status or STATUS_INCOMPLETE, order.status or "" + ), + "next_status": ( + STATUS_FLOW[STAGE_INDEX[order.status] + 1] + if order.status in STAGE_INDEX and order.status != STATUS_DONE + else None + ), + "missing_fields": _missing_for_recharge(order), + "fish_fin_balance": order.fish_fin_balance, + "points_balance": order.points_balance, + "points_required_total": order.points_required_total, + "points_surplus": order.points_surplus, + "points_threshold": order.points_threshold, + "points_checked_at": order.points_checked_at, + "points_check_reason": order.points_check_reason or "", + "points_check_message": order.points_check_message or "", + "points_check_detail": order.points_check_detail, + "recharged_at": order.recharged_at, + "scripted_at": order.scripted_at, + "done_at": order.done_at, + "succeeded_at": order.succeeded_at, + "purchase_change_locked": order.succeeded_at is not None, + "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": ( + users.get(int(order.archived_by), "") if order.archived_by else "" + ), + "archive_reason": order.archive_reason or "", + "created_by": order.created_by, + "created_by_name": users.get(int(order.created_by), "") + if order.created_by + else "", + "updated_by": order.updated_by, + "updated_by_name": users.get(int(order.updated_by), "") + if order.updated_by + else "", + "version": int(order.version or 0), + "created_at": order.created_at, + "updated_at": order.updated_at, + "account_cluster": dict(cluster) if cluster else None, + "last_metric_at": metric.created_at if metric else None, + "last_metric_message": metric.message if metric else "", + "last_verdict": verdict_metric.verdict if verdict_metric else "", + "last_verdict_label": { + VERDICT_SUCCESS: "兑换成功", + VERDICT_FAILED: "兑换失败", + VERDICT_UNKNOWN: "无法判定", + }.get(verdict_metric.verdict, "") + if verdict_metric + else "", + "last_records_total": verdict_metric.records_total if verdict_metric else 0, + "last_records_matched": verdict_metric.records_matched if verdict_metric else 0, + } + return payload + +def _base_order_query(db: Session): + return db.query(DouyuExternalOrder) + +def _apply_order_filters( + db: Session, + query, + *, + include_void: bool = False, + archive_scope: str = "active", + status: str = "", + shop: str = "", + owner_id: int | None = None, + gift_name: str = "", + keyword: str = "", + ck_status: str = "", +): + search = _text(keyword) + exact_search_filter = None + if search: + exact_search_filter = or_( + DouyuExternalOrder.order_no == search, + DouyuExternalOrder.source_platform_order_id == search, + DouyuExternalOrder.source_order_id == search, + DouyuExternalOrder.source_order_item_id == search, + ) + pattern = f"%{search}%" + fuzzy_search_filter = or_( + DouyuExternalOrder.order_no.ilike(pattern), + DouyuExternalOrder.account_username.ilike(pattern), + DouyuExternalOrder.account_nickname.ilike(pattern), + DouyuExternalOrder.bind_game_role.ilike(pattern), + DouyuExternalOrder.shop.ilike(pattern), + DouyuExternalOrder.remark.ilike(pattern), + DouyuExternalOrder.source_order_id.ilike(pattern), + DouyuExternalOrder.source_order_item_id.ilike(pattern), + DouyuExternalOrder.source_platform_order_id.ilike(pattern), + ) + query = query.filter( + or_( + exact_search_filter, + and_( + order_visibility_expr( + DouyuExternalOrder, + archive_scope=archive_scope, + include_void=include_void, + void_status=STATUS_VOID, + ), + fuzzy_search_filter, + ), + ) + ) + else: + query = query.filter( + order_visibility_expr( + DouyuExternalOrder, + archive_scope=archive_scope, + include_void=include_void, + void_status=STATUS_VOID, + ) + ) + if _text(status): + status_filter = DouyuExternalOrder.status == _text(status) + query = query.filter( + or_(status_filter, exact_search_filter) + if exact_search_filter is not None + else status_filter + ) + if _text(shop): + query = query.filter( + DouyuExternalOrder.shop == resolve_shop_name(db, _text(shop)) + ) + if owner_id is not None: + query = query.filter(DouyuExternalOrder.owner_id == int(owner_id)) + if _text(gift_name): + query = query.filter(DouyuExternalOrder.gift_name == _text(gift_name)) + ck_scope = _text(ck_status) + if ck_scope: + query = query.outerjoin(Account, Account.id == DouyuExternalOrder.account_id) + if ck_scope == CK_VALID: + query = query.filter(Account.ck_check_status == CK_VALID) + elif ck_scope == CK_INVALID: + query = query.filter(Account.ck_check_status == CK_INVALID) + elif ck_scope == CK_UNVERIFIED: + query = query.filter( + or_( + DouyuExternalOrder.account_id.is_(None), + Account.ck_check_status.is_(None), + Account.ck_check_status.in_(("", CK_UNVERIFIED)), + ) + ) + return query + +def list_orders( + db: Session, + *, + page: int = 1, + page_size: int = 20, + include_void: bool = False, + archive_scope: str = "active", + status: str = "", + shop: str = "", + owner_id: int | None = None, + gift_name: str = "", + keyword: str = "", + ck_status: str = "", +) -> dict[str, Any]: + query = _apply_order_filters( + db, + _base_order_query(db), + include_void=include_void, + archive_scope=archive_scope, + status=status, + shop=shop, + owner_id=owner_id, + gift_name=gift_name, + keyword=keyword, + ck_status=ck_status, + ) + total = ( + query.order_by(None).with_entities(func.count(DouyuExternalOrder.id)).scalar() + or 0 + ) + orders = ( + query.order_by(DouyuExternalOrder.id.asc()) + .offset((max(1, page) - 1) * page_size) + .limit(page_size) + .all() + ) + users = users_by_id( + db, + { + int(item) + for order in orders + for item in ( + order.owner_id, + order.created_by, + order.updated_by, + order.archived_by, + ) + if item + }, + ) + accounts = accounts_by_id( + db, {int(order.account_id) for order in orders if order.account_id} + ) + clusters = account_clusters(db, orders) + metrics, verdict_metrics = _metric_views(db, [int(order.id) for order in orders]) + items = [ + serialize_order( + order, + users=users, + accounts=accounts, + cluster=clusters.get(int(order.account_id)) if order.account_id else None, + metric=metrics.get(int(order.id)), + verdict_metric=verdict_metrics.get(int(order.id)), + ) + for order in orders + ] + return {"items": items, "total": int(total), "page": page, "page_size": page_size} + +def get_order(db: Session, order_id: int) -> DouyuExternalOrder: + order = ( + db.query(DouyuExternalOrder).filter(DouyuExternalOrder.id == order_id).first() + ) + if order is None: + raise CollabError("协作单不存在", status_code=404, code="order_not_found") + return order + +def serialize_one(db: Session, order: DouyuExternalOrder) -> dict[str, Any]: + users = users_by_id( + db, + { + int(item) + for item in ( + order.owner_id, + order.created_by, + order.updated_by, + order.archived_by, + ) + if item + }, + ) + accounts = accounts_by_id( + db, {int(order.account_id)} if order.account_id else set() + ) + clusters = account_clusters(db, [order]) + metrics, verdict_metrics = _metric_views(db, [int(order.id)]) + return serialize_order( + order, + users=users, + accounts=accounts, + cluster=clusters.get(int(order.account_id)) if order.account_id else None, + metric=metrics.get(int(order.id)), + verdict_metric=verdict_metrics.get(int(order.id)), + ) + +def summary( + db: Session, *, include_void: bool = False, archive_scope: str = "active" +) -> dict[str, Any]: + query = _apply_order_filters( + db, + _base_order_query(db), + include_void=include_void, + archive_scope=archive_scope, + ) + rows = query.with_entities( + DouyuExternalOrder.status, func.count(DouyuExternalOrder.id) + ).group_by(DouyuExternalOrder.status) + by_status = {str(status): int(count) for status, count in rows.all()} + total = sum(by_status.values()) + ck_invalid = ( + query.outerjoin(Account, Account.id == DouyuExternalOrder.account_id) + .with_entities(func.count(DouyuExternalOrder.id)) + .filter(Account.ck_check_status == CK_INVALID) + .scalar() + or 0 + ) + return { + "total": total, + "by_status": by_status, + "ck_invalid": int(ck_invalid), + "archived_total": count_archived(db, DouyuExternalOrder), + "account_missing": ( + db.query(func.count(DouyuExternalOrder.id)) + .filter( + DouyuExternalOrder.account_id.is_(None), + DouyuExternalOrder.archived_at.is_(None), + ) + .scalar() + or 0 + ), + } + +def order_metrics(db: Session, order_id: int) -> list[dict[str, Any]]: + rows = ( + db.query(DouyuExternalOrderMetric) + .filter(DouyuExternalOrderMetric.order_id == order_id) + .order_by(DouyuExternalOrderMetric.id.desc()) + .all() + ) + return [serialize_metric(row) for row in rows] + +def serialize_metric(row: DouyuExternalOrderMetric) -> dict[str, Any]: + return { + "id": int(row.id), + "order_id": int(row.order_id), + "order_no": row.order_no, + "account_username": row.account_username, + "fish_fin_balance": row.fish_fin_balance, + "points_balance": row.points_balance, + "points_required_total": row.points_required_total, + "points_surplus": row.points_surplus, + "records_total": row.records_total, + "records_matched": row.records_matched, + "verdict": row.verdict, + "verdict_label": { + VERDICT_SUCCESS: "兑换成功", + VERDICT_FAILED: "兑换失败", + VERDICT_UNKNOWN: "无法判定", + }.get(row.verdict, row.verdict), + "message": row.message, + "source": row.source, + "created_at": row.created_at, + } + +def order_timeline( + db: Session, order_id: int, *, limit: int = 100 +) -> list[dict[str, Any]]: + rows = ( + db.query(AuditLog) + .filter(AuditLog.target == f"douyu_external_order:{order_id}") + .order_by(AuditLog.id.desc()) + .limit(limit) + .all() + ) + return [ + { + "id": int(row.id), + "action": row.action, + "username": row.username or "", + "detail": row.detail or "", + "success": row.success, + "created_at": row.created_at, + } + for row in rows + ] diff --git a/web/backend/services/douyu_collab_service.py b/web/backend/services/douyu_collab_service.py index 45db707..aacb3dc 100644 --- a/web/backend/services/douyu_collab_service.py +++ b/web/backend/services/douyu_collab_service.py @@ -1,3 +1,4 @@ +# ruff: noqa: F401 """斗鱼外部单协作台账服务。 核心边界(和虎牙外部 CK 台账的区别): @@ -74,6 +75,117 @@ from .douyu_account_probe import ( persist_probe_result, probe_account, ) +from .douyu_collab_catalog import ( + _resolve_gift, + create_gift, + delete_gift, + get_gift, + list_gift_names, + list_gifts, + refresh_activity_goods, + serialized_goods, + update_gift, +) +from .douyu_collab_common import ( + ACCOUNT_RECOMMEND_DEFAULT_SCAN_LIMIT, + ACCOUNT_REPLACE_ROLES, + ACTIVITY_METRIC_RECORD_LIMIT, + ACTIVITY_RECORD_FETCH_LIMIT, + ACTIVITY_RECORD_MAX_PAGES, + ACTIVITY_RECORD_SETTLE_SECONDS, + ACTIVITY_RECORD_TIME_SKEW_SECONDS, + ARCHIVABLE_STATUSES, + CK_EXPORT_ACTION, + CK_EXPORT_BATCH_MAX, + CK_INVALID, + CK_LABELS, + CK_UNVERIFIED, + CK_VALID, + COLLAB_LEASE_STATUSES, + LEASE_PURPOSE_DOUYU_COLLAB, + MAX_IMAGES, + ORDER_STATUS_LABELS, + ORDER_STATUSES, + PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES, + POINTS_GROUP_STATUSES, + POINTS_THRESHOLD_DEFAULT, + SOURCE_TYPE_PLATFORM_FULFILLMENT, + STAGE_INDEX, + STATUS_DONE, + STATUS_FAILED, + STATUS_FLOW, + STATUS_INCOMPLETE, + STATUS_POINTS_ERROR, + STATUS_RECHARGED, + STATUS_ROLE_ERROR, + STATUS_SCRIPTED, + STATUS_TIMESTAMP_FIELDS, + STATUS_TO_RECHARGE, + STATUS_VOID, + SUCCESS_PURCHASE_FIELDS, + USERNAME_EXPORT_BATCH_MAX, + VERDICT_FAILED, + VERDICT_SUCCESS, + VERDICT_UNKNOWN, + CollabError, + _assert_account_replace_permission, + _assert_account_replaceable, + _assert_mutable, + _assert_success_account_change_allowed, + _assert_version, + _client_for_account, + _first_value, + _json_safe, + _mark_order_succeeded, + _missing_for_recharge, + _now, + _text, + _to_int, + account_by_id, + account_by_username, + accounts_by_id, + normalize_images, + normalize_threshold, + resolve_config, + serialize_live_goods, + users_by_id, +) +from .douyu_collab_exports import export_cks, export_usernames +from .douyu_collab_leases import ( + _ensure_order_account_lease, + _release_order_account_lease, + _sync_order_lease, + retain_lease_for_active_collab, +) +from .douyu_collab_query import ( + _apply_order_filters, + _base_order_query, + _metric_views, + account_clusters, + get_order, + list_orders, + order_metrics, + order_timeline, + serialize_metric, + serialize_one, + serialize_order, + summary, +) +from .douyu_collab_shops import ( + _normalize_shop_aliases, + _shop_match_values, + create_shop, + delete_shop, + ensure_shops_registered, + get_shop, + list_shops, + resolve_shop_name, + update_shop, +) +from .douyu_collab_sync import ( + sync_platform_fulfillment_order, + sync_platform_fulfillment_orders, +) from .douyu_goods_service import ( serialize_live_goods as _serialize_live_goods, ) @@ -91,275 +203,6 @@ from .platform_fulfillment.account_selector import ( release_lease, ) -# --------------------------------------------------------------------------- -# 状态机 -# --------------------------------------------------------------------------- - -STATUS_INCOMPLETE = "incomplete" -STATUS_TO_RECHARGE = "to_recharge" -STATUS_RECHARGED = "recharged" -STATUS_SCRIPTED = "scripted" -STATUS_DONE = "done" -STATUS_POINTS_ERROR = "points_error" -STATUS_ROLE_ERROR = "role_error" -STATUS_FAILED = "failed" -STATUS_VOID = "void" -LEASE_PURPOSE_DOUYU_COLLAB = "douyu_collab" -COLLAB_LEASE_STATUSES = ACTIVE_COLLAB_STATUSES - -ORDER_STATUSES: tuple[str, ...] = ( - STATUS_INCOMPLETE, - STATUS_TO_RECHARGE, - STATUS_RECHARGED, - STATUS_SCRIPTED, - STATUS_DONE, - STATUS_POINTS_ERROR, - STATUS_ROLE_ERROR, - STATUS_FAILED, - STATUS_VOID, -) - -ORDER_STATUS_LABELS = { - STATUS_INCOMPLETE: "待补资料", - STATUS_TO_RECHARGE: "待充值", - STATUS_RECHARGED: "已充值", - STATUS_SCRIPTED: "已上脚本", - STATUS_DONE: "抢购成功", - STATUS_POINTS_ERROR: "积分异常", - STATUS_ROLE_ERROR: "账号角色异常", - STATUS_FAILED: "抢购失败", - STATUS_VOID: "已作废", -} - -STATUS_FLOW: tuple[str, ...] = ( - STATUS_INCOMPLETE, - STATUS_TO_RECHARGE, - STATUS_RECHARGED, - STATUS_SCRIPTED, - STATUS_DONE, -) - -SOURCE_TYPE_PLATFORM_FULFILLMENT = "platform_fulfillment" -ACCOUNT_REPLACE_ROLES = frozenset({"super_admin", "operation"}) -ACCOUNT_RECOMMEND_DEFAULT_SCAN_LIMIT = 20 -PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES = frozenset( - { - "lock_goods", - "pay_locked_order", - "exchange_goods", - "exchange_esports_goods", - "exchange_xpd_goods", - "create_elite_qr", - "create_esports_qr", - "create_gold_qr", - "donate_elite_gift", - "donate_esports_chicken_gift", - "donate_esports_firework_gift", - } -) - -STAGE_INDEX = { - STATUS_INCOMPLETE: 0, - STATUS_TO_RECHARGE: 1, - STATUS_RECHARGED: 2, - STATUS_SCRIPTED: 3, - STATUS_DONE: 4, -} - -STATUS_TIMESTAMP_FIELDS = { - STATUS_RECHARGED: "recharged_at", - STATUS_SCRIPTED: "scripted_at", - STATUS_DONE: "done_at", -} - -# 成功订单已经锁定购买事实。这些字段一旦变更,会让订单号、购买账号或 -# 兑换商品与后续核账/审计不一致,因此只允许超级管理员显式确认后修改。 -SUCCESS_PURCHASE_FIELDS = frozenset( - { - "order_no", - "account_username", - "gift_name", - "commodity_id", - "required_points", - } -) - -ARCHIVABLE_STATUSES = (STATUS_DONE,) -# 同一账号核账只统计“还没有完成兑换”的单:done/scripted 不重复占积分。 -POINTS_GROUP_STATUSES: tuple[str, ...] = ( - STATUS_TO_RECHARGE, - STATUS_RECHARGED, - STATUS_POINTS_ERROR, -) - -POINTS_THRESHOLD_DEFAULT = 100 -POINTS_THRESHOLD_MAX = 1_000_000 -ACTIVITY_RECORD_SETTLE_SECONDS = 300 -ACTIVITY_RECORD_TIME_SKEW_SECONDS = 60 -ACTIVITY_RECORD_FETCH_LIMIT = 100 -ACTIVITY_RECORD_MAX_PAGES = 5 -# 兑换记录最多翻 5 页,但指标快照只保留必要样本,避免 JSON 列按订单放大存储。 -ACTIVITY_METRIC_RECORD_LIMIT = 50 -MAX_IMAGES = 20 -CK_EXPORT_BATCH_MAX = 50 -CK_EXPORT_ACTION = "douyu:collab:ck_export" -USERNAME_EXPORT_BATCH_MAX = 500 - -VERDICT_SUCCESS = "success" -VERDICT_FAILED = "failed" -VERDICT_UNKNOWN = "unknown" - -CK_VALID = "valid" -CK_INVALID = "invalid" -CK_UNVERIFIED = "unverified" -CK_LABELS = { - CK_VALID: "CK 正常", - CK_INVALID: "CK 异常", - CK_UNVERIFIED: "未检测", -} - - -class CollabError(RuntimeError): - def __init__(self, detail: str, *, status_code: int = 400, code: str = ""): - super().__init__(detail) - self.detail = detail - self.status_code = status_code - self.code = code - - -def _now() -> datetime: - return datetime.now(UTC) - - -def _to_int(value: Any) -> int | None: - if value is None or value == "": - return None - try: - return int(float(value)) - except (TypeError, ValueError): - return None - - -def _text(value: Any, *, max_length: int | None = None) -> str: - text = str(value or "").strip() - return text[:max_length] if max_length else text - - -def _mark_order_succeeded( - order: DouyuExternalOrder, when: datetime | None = None -) -> None: - """记录首次成功时间;状态回退不能清掉这条购买锁定依据。""" - if order.succeeded_at is None: - order.succeeded_at = when or _now() - - -def _json_safe(value: Any) -> Any: - if isinstance(value, dict): - return {str(k): _json_safe(v) for k, v in value.items()} - if isinstance(value, list): - return [_json_safe(item) for item in value] - if isinstance(value, (str, int, float, bool)) or value is None: - return value - return str(value) - - -def _first_value(data: Mapping[str, Any], *keys: str) -> Any: - """取第一个存在且非 None 的字段;0 是合法值,不能用 `or` 兜。""" - for key in keys: - if key in data and data.get(key) is not None: - return data.get(key) - return None - - -def normalize_images(value: Any, *, field: str = "home_images") -> list[str]: - if value is None: - return [] - if not isinstance(value, list): - raise CollabError(f"{field} 必须是图片 key 数组", code="images_invalid") - keys: list[str] = [] - for item in value: - key = _text(item, max_length=512) - if key and key not in keys: - keys.append(key) - if len(keys) > MAX_IMAGES: - raise CollabError(f"最多 {MAX_IMAGES} 张图片", code="images_too_many") - return keys - - -def normalize_threshold(value: Any) -> int: - number = _to_int(value) - if number is None: - return POINTS_THRESHOLD_DEFAULT - if number < 0: - raise CollabError("积分阈值不能小于 0", code="points_threshold_invalid") - return min(number, POINTS_THRESHOLD_MAX) - - -def resolve_config(db: Session) -> DouyuConfig: - config = db.query(DouyuConfig).order_by(DouyuConfig.id.asc()).first() - if config is None: - config = DouyuConfig() - db.add(config) - db.flush() - return config - - -def account_by_username(db: Session, username: str) -> Account | None: - name = _text(username, max_length=128) - if not name: - return None - return ( - db.query(Account) - .filter(Account.username == name) - .order_by(Account.id.asc()) - .first() - ) - - -def account_by_id(db: Session, account_id: int | None) -> Account | None: - if not account_id: - return None - return db.query(Account).filter(Account.id == account_id).first() - - -def users_by_id(db: Session, ids: set[int]) -> dict[int, str]: - clean = {int(item) for item in ids if item} - if not clean: - return {} - return { - int(user_id): str(username) - for user_id, username in db.query(User.id, User.username) - .filter(User.id.in_(clean)) - .all() - } - - -def accounts_by_id(db: Session, ids: set[int]) -> dict[int, Account]: - clean = {int(item) for item in ids if item} - if not clean: - return {} - return { - int(account.id): account - for account in db.query(Account).filter(Account.id.in_(clean)).all() - } - - -def _client_for_account(account: Account) -> DouyuActivityClient: - cookie = str(account.cookie or "").strip() - if not cookie: - raise CollabError("该账号没有 CK", code="account_no_cookie") - return activity_client( - cookie, - logger_callback=lambda message: logger.debug( - "[douyu-collab] account={} {}", account.id, message - ), - ) - - -def serialize_live_goods(goods: list[dict[str, Any]]) -> list[dict[str, Any]]: - """把 storehome 原始商品映射成前端稳定字段。""" - return _serialize_live_goods(goods) - def _probe_with_client( account: Account, @@ -837,593 +680,6 @@ def apply_probe_snapshot( order.points_balance = points -def _assert_version(order: DouyuExternalOrder, expected: int | None) -> None: - if expected is not None and int(expected) != int(order.version or 0): - raise CollabError( - "这行已被别人修改,请刷新后再试", - status_code=409, - code="version_conflict", - ) - - -def _assert_mutable(order: DouyuExternalOrder) -> None: - if order.archived_at is not None: - raise CollabError("已归档的订单不能再编辑", code="order_archived") - if order.status == STATUS_VOID: - raise CollabError("已作废的订单不能再编辑", code="order_void") - - -def _assert_account_replace_permission(current: User) -> None: - """撤号和推荐属于高风险改号操作,只允许超级管理员和运营。""" - if current.role not in ACCOUNT_REPLACE_ROLES: - raise CollabError( - "仅超级管理员和运营可以解除或推荐账号", - status_code=403, - code="account_replace_forbidden", - ) - - -def _assert_account_replaceable(order: DouyuExternalOrder) -> None: - _assert_mutable(order) - if order.status == STATUS_DONE or order.done_at is not None: - raise CollabError( - "已完成订单不能更换账号,请先确认是否需要回退状态", - code="order_done_immutable", - ) - - -def _assert_success_account_change_allowed( - current: User, order: DouyuExternalOrder -) -> None: - if order.succeeded_at is not None and current.role != "super_admin": - raise CollabError( - "订单已有成功记录,购买账号仅允许超级管理员修改", - status_code=403, - code="purchase_lock_admin_required", - ) - - -def _order_occupies_account(order: DouyuExternalOrder) -> bool: - return ( - bool(order.account_id) - and order.archived_at is None - and order.status in COLLAB_LEASE_STATUSES - ) - - -def _active_collab_order( - db: Session, - account_id: int, - *, - exclude_order_id: int | None = None, -) -> DouyuExternalOrder | None: - query = db.query(DouyuExternalOrder).filter( - DouyuExternalOrder.account_id == int(account_id), - DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES), - DouyuExternalOrder.archived_at.is_(None), - ) - if exclude_order_id is not None: - query = query.filter(DouyuExternalOrder.id != int(exclude_order_id)) - return query.order_by(DouyuExternalOrder.updated_at.desc()).first() - - -def _platform_lease_matches_source( - db: Session, lease: AccountLease, order: DouyuExternalOrder -) -> bool: - if ( - lease.purpose != "platform_fulfillment" - or order.source_type != SOURCE_TYPE_PLATFORM_FULFILLMENT - or not order.source_task_id - ): - return False - task = ( - db.query(PlatformFulfillmentTask) - .filter(PlatformFulfillmentTask.id == int(order.source_task_id)) - .first() - ) - return bool( - task is not None - and (task.lease_id == lease.id or lease.batch_id == f"pf:{int(task.id)}") - ) - - -def _lock_active_lease_for_account( - db: Session, - account_id: int, -) -> AccountLease | None: - return ( - db.query(AccountLease) - .filter( - AccountLease.account_id == int(account_id), - AccountLease.status == "active", - ) - .with_for_update() - .first() - ) - - -def _platform_task_for_lease( - db: Session, - lease: AccountLease, -) -> PlatformFulfillmentTask | None: - task_id = 0 - if lease.batch_id.startswith("pf:"): - try: - task_id = int(lease.batch_id.removeprefix("pf:")) - except ValueError: - task_id = 0 - query = db.query(PlatformFulfillmentTask).with_for_update() - if task_id: - task = query.filter(PlatformFulfillmentTask.id == task_id).first() - if task is not None: - return task - return query.filter(PlatformFulfillmentTask.lease_id == int(lease.id)).first() - - -def _takeover_platform_lease_for_collab( - db: Session, - current: User, - order: DouyuExternalOrder, - lease: AccountLease, -) -> AccountLease: - """外部协作显式接管平台租约,并在同一事务内把平台任务转人工。""" - if not user_has_permission(current, "platform_fulfillment:use"): - raise CollabError( - "没有接管平台履约账号的权限", - status_code=403, - code="platform_takeover_forbidden", - ) - platform_task = _platform_task_for_lease(db, lease) - if platform_task is None: - raise CollabError( - "平台履约任务不存在,请刷新后重试", - status_code=409, - code="account_lease_conflict", - ) - if platform_task.execution_status in {"completed", "cancelled"}: - raise CollabError( - f"平台履约任务 #{platform_task.id} 已结束,不能由协作单接管", - status_code=409, - code="platform_task_not_takeoverable", - ) - if ( - platform_task.account_id != lease.account_id - or platform_task.lease_id != lease.id - ): - raise CollabError( - f"平台履约任务 #{platform_task.id} 与账号租约不一致,请先核对", - status_code=409, - code="account_lease_conflict", - ) - blocking = ( - db.query(DouyuTask) - .filter( - DouyuTask.platform_task_id == int(platform_task.id), - DouyuTask.status.in_(("planned", "pending", "running")), - DouyuTask.task_type.in_(PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES), - ) - .order_by(DouyuTask.id.desc()) - .first() - ) - if blocking is not None: - raise CollabError( - f"平台履约任务 #{platform_task.id} 正在执行资金/兑换操作,请先停止任务", - status_code=409, - code="platform_task_running", - ) - - from .platform_fulfillment import service as platform_service - - platform_service.prepare_platform_task_for_collab_takeover( - db, - task=platform_task, - current=current, - collab_order_no=order.order_no, - ) - previous_task_id = int(platform_task.id) - lease.purpose = LEASE_PURPOSE_DOUYU_COLLAB - lease.batch_id = f"collab:{int(lease.account_id)}"[:64] - lease.commodity_id = "" - lease.holder_user_id = int(current.id) - lease.expires_at = None - lease.released_at = None - lease.release_reason = "" - emit( - db, - account_id=int(lease.account_id), - event_type=EVENT_LEASE_ACQUIRED, - title=f"外部协作接管平台履约账号:{order.order_no}", - category=CATEGORY_OPS, - detail={ - "lease_id": lease.id, - "order_id": order.id, - "order_no": order.order_no, - "platform_task_id": previous_task_id, - "reason": "collab_manual_takeover", - }, - source="lease", - subject_type="order", - subject_key=order.order_no, - actor_type="user", - actor_id=int(current.id), - source_ref=f"account_lease_collab_takeover:{lease.id}", - ) - _audit_lease_action( - db, - current, - order=order, - account_id=int(lease.account_id), - action="douyu:collab:lease_takeover", - lease=lease, - detail={ - "lease_id": lease.id, - "order_id": order.id, - "order_no": order.order_no, - "platform_task_id": previous_task_id, - "reason": "collab_manual_takeover", - }, - ) - return lease - - -def _audit_lease_action( - db: Session, - current: User, - *, - order: DouyuExternalOrder | None, - account_id: int, - action: str, - lease: AccountLease, - detail: Mapping[str, Any], -) -> None: - entry = record_audit( - db, - current, - action=action, - target=( - ( - f"douyu_external_order:{order.id}" - if order.id - else f"douyu_external_order_no:{order.order_no}" - ) - if order is not None - else f"account:{account_id}" - ), - detail=detail, - ) - entry.account_id = account_id - - -def _ensure_order_account_lease( - db: Session, - current: User, - order: DouyuExternalOrder, - *, - account_id: int | None = None, - force_active: bool = False, - takeover_platform_lease: bool = False, - commit: bool = False, -) -> AccountLease | None: - target_account_id = int(account_id or order.account_id or 0) - if not target_account_id: - return None - if not force_active and not _order_occupies_account(order): - return None - - lease = _lock_active_lease_for_account(db, target_account_id) - if lease is not None: - if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: - return lease - if takeover_platform_lease: - return _takeover_platform_lease_for_collab( - db, - current, - order, - lease, - ) - if _platform_lease_matches_source(db, lease, order): - return lease - platform_task = _platform_task_for_lease(db, lease) - task_label = ( - f"平台履约任务 #{platform_task.id}" - if platform_task is not None - else "平台履约任务" - ) - raise CollabError( - f"该账号当前被{task_label}占用,请确认转人工后再使用", - status_code=409, - code="account_lease_conflict", - ) - - lease = acquire_account_lease( - db, - account_id=target_account_id, - holder_user_id=int(current.id), - scope="elite", - purpose=LEASE_PURPOSE_DOUYU_COLLAB, - batch_id=f"collab:{target_account_id}", - commit=False, - ) - if lease is None: - raise CollabError( - "该账号刚被其他业务占用,请刷新后重试", - status_code=409, - code="account_lease_conflict", - ) - _audit_lease_action( - db, - current, - order=order, - account_id=target_account_id, - action="douyu:collab:lease_acquired", - lease=lease, - detail={ - "lease_id": lease.id, - "account_id": target_account_id, - "purpose": lease.purpose, - "batch_id": lease.batch_id, - }, - ) - if commit: - db.commit() - return lease - - -def _release_order_account_lease( - db: Session, - current: User, - order: DouyuExternalOrder, - *, - reason: str, - account_id: int | None = None, - commit: bool = False, -) -> bool: - target_account_id = int(account_id or order.account_id or 0) - if not target_account_id: - return False - if _active_collab_order(db, target_account_id, exclude_order_id=int(order.id)): - return False - lease = active_lease_for_account(db, target_account_id) - if lease is None or lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB: - return False - released = release_lease(db, lease, reason=reason, commit=False) - if released: - _audit_lease_action( - db, - current, - order=order, - account_id=target_account_id, - action="douyu:collab:lease_released", - lease=lease, - detail={ - "lease_id": lease.id, - "account_id": target_account_id, - "reason": reason, - }, - ) - if commit: - db.commit() - return released - - -def _sync_order_lease( - db: Session, - current: User, - order: DouyuExternalOrder, - *, - reason: str, - force_active: bool = False, - reuse_active_lease: bool = False, - commit: bool = False, -) -> AccountLease | None: - if force_active or _order_occupies_account(order): - if reuse_active_lease: - # 纯状态回写只沿用协作租约或同一平台来源的租约;其他业务占用必须显式接管。 - lease = _lock_active_lease_for_account(db, int(order.account_id or 0)) - if lease is not None: - if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: - return lease - if _platform_lease_matches_source(db, lease, order): - return lease - platform_task = _platform_task_for_lease(db, lease) - task_label = ( - f"平台履约任务 #{platform_task.id}" - if platform_task is not None - else "平台履约任务" - ) - raise CollabError( - f"该账号当前被{task_label}占用,请先由协作单确认接管", - status_code=409, - code="account_lease_conflict", - ) - # 没有任何有效占用的历史异常行仍需补建协作租约,避免自动分配选中。 - return _ensure_order_account_lease( - db, - current, - order, - force_active=force_active, - commit=commit, - ) - _release_order_account_lease( - db, - current, - order, - reason=reason, - commit=commit, - ) - return None - - -def retain_lease_for_active_collab( - db: Session, - *, - account_id: int, - holder_user_id: int, - current: User | None = None, - lease: AccountLease | None = None, - source_task_id: int | None = None, - reason: str = "platform_release_to_collab", - commit: bool = False, -) -> AccountLease | None: - """平台释放账号时,把仍在活动的协作占用接续为统一协作租约。""" - active_lease = lease or active_lease_for_account(db, account_id) - if active_lease is not None and active_lease.status != "active": - return None - - query = db.query(DouyuExternalOrder).filter( - DouyuExternalOrder.account_id == int(account_id), - DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES), - DouyuExternalOrder.archived_at.is_(None), - ) - if source_task_id: - preferred = ( - query.filter(DouyuExternalOrder.source_task_id == int(source_task_id)) - .order_by(DouyuExternalOrder.updated_at.desc()) - .first() - ) - order = ( - preferred or query.order_by(DouyuExternalOrder.updated_at.desc()).first() - ) - else: - order = query.order_by(DouyuExternalOrder.updated_at.desc()).first() - if order is None: - return None - - holder_id = int( - holder_user_id - or (order.owner_id if order.owner_id else 0) - or (active_lease.holder_user_id if active_lease else 0) - ) - if not holder_id: - return None - - if active_lease is None: - active_lease = acquire_account_lease( - db, - account_id=int(account_id), - holder_user_id=holder_id, - scope="elite", - purpose=LEASE_PURPOSE_DOUYU_COLLAB, - batch_id=f"collab:{int(account_id)}", - commit=False, - ) - if active_lease is None: - return None - elif active_lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB: - previous_purpose = active_lease.purpose - active_lease.purpose = LEASE_PURPOSE_DOUYU_COLLAB - active_lease.batch_id = f"collab:{int(account_id)}"[:64] - active_lease.commodity_id = "" - active_lease.expires_at = None - active_lease.release_reason = "" - active_lease.holder_user_id = holder_id - emit( - db, - account_id=int(account_id), - event_type=EVENT_LEASE_ACQUIRED, - title=f"外部协作接管账号占用:{order.order_no}", - category=CATEGORY_OPS, - detail={ - "lease_id": active_lease.id, - "order_id": order.id, - "order_no": order.order_no, - "purpose": active_lease.purpose, - "previous_purpose": previous_purpose, - "reason": reason, - }, - source="lease", - subject_type="order", - subject_key=order.order_no, - actor_type="user" if current is not None else "system", - actor_id=int(current.id) if current is not None else None, - source_ref=f"account_lease_collab_takeover:{active_lease.id}", - ) - - if current is not None: - _audit_lease_action( - db, - current, - order=order, - account_id=int(account_id), - action="douyu:collab:lease_takeover", - lease=active_lease, - detail={ - "lease_id": active_lease.id, - "order_id": order.id, - "order_no": order.order_no, - "reason": reason, - }, - ) - if commit: - db.commit() - return active_lease - - -def _resolve_gift( - db: Session, *, gift_name: str, commodity_id: str, required_points: Any -) -> tuple[str, str, int | None]: - name = _text(gift_name, max_length=128) - cid = _text(commodity_id, max_length=64) - points = _to_int(required_points) - query = db.query(DouyuGoodsSnapshot) - row = None - if cid: - row = query.filter(DouyuGoodsSnapshot.commodity_id == cid).first() - if row is None and name: - row = query.filter(DouyuGoodsSnapshot.name == name).first() - if row is not None: - if not name: - name = _text(row.name, max_length=128) - if not cid: - cid = _text(row.commodity_id, max_length=64) - if points is None: - points = _to_int(row.score) - if points is None and name: - manual = ( - db.query(DouyuCollabGift).filter(DouyuCollabGift.name == name).first() - ) - if manual is not None: - points = int(manual.points or 0) - return name, cid, points - if not cid and name: - mapping = ( - db.query(PlatformCommodityMapping) - .filter( - PlatformCommodityMapping.target_platform == "douyu", - PlatformCommodityMapping.enabled.is_(True), - or_( - PlatformCommodityMapping.goods_name == name, - PlatformCommodityMapping.internal_sku_key == name, - ), - ) - .order_by(PlatformCommodityMapping.id.desc()) - .first() - ) - if mapping is not None: - cid = _text(mapping.commodity_id, max_length=64) - if points is None: - points = _to_int(mapping.required_points) - return name, cid, points - # 接口暂时不返回商品时,管理员配置的礼包名称和积分仍然可用。 - manual = db.query(DouyuCollabGift).filter(DouyuCollabGift.name == name).first() - if manual is not None: - return name, "", points if points is not None else int(manual.points or 0) - return name, cid, points - - -def _missing_for_recharge(order: DouyuExternalOrder) -> list[str]: - missing: list[str] = [] - if not order.account_id or not _text(order.account_username): - missing.append("斗鱼账号") - if not order.gift_name: - missing.append("礼包") - if not order.home_images: - missing.append("主页截图") - if not order.bind_game_role: - missing.append("绑定角色(先校验账号)") - return missing - - def _ready_for_recharge(order: DouyuExternalOrder) -> bool: return not _missing_for_recharge(order) @@ -1641,343 +897,6 @@ def create_order( return order -def _platform_fulfillment_gift( - db: Session, - task: PlatformFulfillmentTask, -) -> tuple[str, str, int | None]: - """解析履约任务对应的斗鱼商品,优先显式映射,再回退到商品快照。""" - mapping = ( - db.query(PlatformCommodityMapping) - .filter(PlatformCommodityMapping.id == task.commodity_mapping_id) - .first() - if task.commodity_mapping_id - else None - ) - snapshot = ( - db.query(DouyuGoodsSnapshot) - .filter(DouyuGoodsSnapshot.commodity_id == task.commodity_id) - .first() - if task.commodity_id - else None - ) - name = _text( - (mapping.goods_name if mapping else "") - or (snapshot.name if snapshot else "") - or task.sku_name, - max_length=128, - ) - commodity_id = _text( - task.commodity_id - or (mapping.commodity_id if mapping else "") - or (snapshot.commodity_id if snapshot else ""), - max_length=64, - ) - required_points = _to_int(task.required_points) - if required_points is None and mapping is not None: - required_points = _to_int(mapping.required_points) - if required_points is None and snapshot is not None: - required_points = _to_int(snapshot.score) - return name, commodity_id, required_points - - -def _platform_fulfillment_order_no(task: PlatformFulfillmentTask) -> str: - """外部协作单直接使用 order_site 的真实平台订单号。""" - order_no = _text(task.platform_order_id) - if not order_no: - raise CollabError("履约任务缺少平台订单号", code="platform_order_no_required") - if len(order_no) > 64: - raise CollabError( - "平台订单号超过协作单号长度限制", - code="platform_order_no_too_long", - ) - return order_no - - -def _apply_platform_fulfillment_binding( - db: Session, - order: DouyuExternalOrder, - task: PlatformFulfillmentTask, - *, - overwrite: bool, -) -> None: - """把履约任务已确认的本地绑定结果投影到协作单,不额外联网。""" - bind_task = ( - db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() - if task.bind_task_id - else None - ) - result = ( - bind_task.result if bind_task and isinstance(bind_task.result, dict) else None - ) - role = binding_role_from_result(result) - if not role: - return - if overwrite or not order.bind_game_role: - order.bind_game_role = _text(role, max_length=128) - channel = binding_channel(result) - if channel and (overwrite or not order.bind_game_channel): - order.bind_game_channel = _text(channel, max_length=128) - if overwrite or not order.bind_snapshot_at: - order.bind_snapshot_at = _now() - - -def _apply_platform_fulfillment_status( - order: DouyuExternalOrder, - task: PlatformFulfillmentTask, - *, - created: bool, -) -> None: - """只做不会倒退的状态映射,保留协作台里人工推进的中间状态。""" - if created: - if task.execution_status == "completed": - order.status = STATUS_DONE - order.done_at = order.done_at or task.completed_at or _now() - _mark_order_succeeded(order, order.done_at) - elif task.execution_status == "cancelled": - order.status = STATUS_VOID - order.void_reason = order.void_reason or "直播履约任务已取消" - else: - order.status = STATUS_INCOMPLETE - return - - if task.execution_status == "completed" and order.status not in ( - STATUS_DONE, - STATUS_VOID, - ): - order.status = STATUS_DONE - order.done_at = order.done_at or task.completed_at or _now() - _mark_order_succeeded(order, order.done_at) - elif task.execution_status == "cancelled" and order.status != STATUS_VOID: - order.status = STATUS_VOID - order.void_reason = order.void_reason or "直播履约任务已取消" - - -def sync_platform_fulfillment_order( - db: Session, - current: User, - task: PlatformFulfillmentTask, - *, - commit: bool = True, -) -> tuple[DouyuExternalOrder, str]: - """把一条直播履约任务幂等同步为斗鱼外部协作单。 - - 这里只复制本地已确认的数据,不调用斗鱼接口,也不覆盖协作台上人工维护的 - 负责人、余额、核账快照和备注。``source_task_id`` 是幂等键。 - """ - if task.source_system != "order_site": - raise CollabError("仅支持同步 order_site 履约任务", code="source_unsupported") - - order = ( - db.query(DouyuExternalOrder) - .filter(DouyuExternalOrder.source_task_id == task.id) - .first() - ) - order_no = _platform_fulfillment_order_no(task) - created = order is None - order_by_no = ( - db.query(DouyuExternalOrder) - .filter(DouyuExternalOrder.order_no == order_no) - .first() - ) - if order is not None and order_by_no is not None and order_by_no.id != order.id: - raise CollabError( - f"平台订单号 {order_no} 已关联其他履约任务", - code="order_no_conflict", - ) - if order is None and order_by_no is not None: - if order_by_no.source_task_id not in (None, task.id): - raise CollabError( - f"平台订单号 {order_no} 已关联其他履约任务", - code="order_no_conflict", - ) - # 手工先建过同一真实订单号时,直接接管为来源单,保留人工字段。 - order = order_by_no - created = False - - now = _now() - account = ( - db.query(Account).filter(Account.id == task.account_id).first() - if task.account_id - else None - ) - gift_name, commodity_id, required_points = _platform_fulfillment_gift(db, task) - - if order is None: - order = DouyuExternalOrder( - order_no=order_no, - source_type=SOURCE_TYPE_PLATFORM_FULFILLMENT, - source_task_id=task.id, - status=STATUS_INCOMPLETE, - points_threshold=POINTS_THRESHOLD_DEFAULT, - owner_id=current.id, - created_by=current.id, - version=0, - created_at=now, - ) - db.add(order) - - order.order_no = order_no - order.source_type = SOURCE_TYPE_PLATFORM_FULFILLMENT - order.source_task_id = int(task.id) - order.source_order_id = _text(task.source_order_id, max_length=64) - order.source_order_item_id = _text(task.source_order_item_id, max_length=64) - order.source_platform_order_id = _text(task.platform_order_id, max_length=128) - order.last_synced_at = now - order.updated_by = current.id - order.updated_at = now - shop_original_name = _text(task.shop_name or task.shop_id, max_length=128) - ensure_shops_registered(db, current, [shop_original_name]) - order.shop = resolve_shop_name(db, shop_original_name)[:64] - order.shop_original_name = shop_original_name - order.gift_name = gift_name - order.commodity_id = commodity_id - order.required_points = required_points - if account is not None and ( - created or (order.account_id is None and not order.account_username) - ): - order.account_id = int(account.id) - order.account_username = _text(account.username, max_length=128) - order.account_uid = _text(account.uid, max_length=32) - order.account_nickname = _text(account.nickname, max_length=128) - _apply_platform_fulfillment_binding( - db, - order, - task, - overwrite=created, - ) - _apply_platform_fulfillment_status(order, task, created=created) - order.version = int(order.version or 0) + 1 - db.flush() - _sync_order_lease( - db, - current, - order, - reason="douyu_collab_sync_terminal", - ) - - audit_detail = { - "taskId": int(task.id), - "orderNo": order.order_no, - "created": created, - "status": order.status, - } - linked_account = ( - db.query(Account).filter(Account.id == order.account_id).first() - if order.account_id - else None - ) - if linked_account is not None: - record_account_action( - db, - current, - account=linked_account, - action="douyu:collab:sync_from_platform_fulfillment", - event_type=EVENT_COLLAB_SYNCED, - title=f"同步外部单协作:{order.order_no}", - target=f"douyu_external_order:{order.id}", - detail=audit_detail, - ) - else: - record_audit( - db, - current, - action="douyu:collab:sync_from_platform_fulfillment", - target=f"douyu_external_order:{order.id}", - detail=audit_detail, - ) - if commit: - db.commit() - db.refresh(order) - return order, "created" if created else "updated" - - -def sync_platform_fulfillment_orders( - db: Session, - current: User, - *, - task_ids: Sequence[int], - commit: bool = True, -) -> dict[str, Any]: - """批量同步履约任务;单条失败回滚自己的 SAVEPOINT,不拖垮整批。""" - requested_ids = list(dict.fromkeys(int(item) for item in task_ids if item)) - tasks = ( - db.query(PlatformFulfillmentTask) - .filter(PlatformFulfillmentTask.id.in_(requested_ids)) - .all() - if requested_ids - else [] - ) - tasks_by_id = {int(task.id): task for task in tasks} - result = { - "requested": len(requested_ids), - "created": 0, - "updated": 0, - "skipped": 0, - "failed": 0, - "items": [], - } - - for task_id in requested_ids: - task = tasks_by_id.get(task_id) - if task is None: - result["skipped"] += 1 - result["items"].append( - { - "taskId": task_id, - "action": "skipped", - "reason": "履约任务不存在", - "collabOrderId": None, - "orderNo": "", - } - ) - continue - try: - with db.begin_nested(): - order, action = sync_platform_fulfillment_order( - db, - current, - task, - commit=False, - ) - result[action] += 1 - result["items"].append( - { - "taskId": task_id, - "action": action, - "reason": "", - "collabOrderId": int(order.id), - "orderNo": order.order_no, - } - ) - except CollabError as exc: - result["failed"] += 1 - result["items"].append( - { - "taskId": task_id, - "action": "failed", - "reason": exc.detail, - "collabOrderId": None, - "orderNo": "", - } - ) - except Exception: # noqa: BLE001 - 批量边界需隔离单条未知故障 - logger.exception("同步直播履约任务 {} 到斗鱼外部协作失败", task_id) - result["failed"] += 1 - result["items"].append( - { - "taskId": task_id, - "action": "failed", - "reason": "同步失败,请稍后重试", - "collabOrderId": None, - "orderNo": "", - } - ) - - if commit: - db.commit() - return result - - def update_order( db: Session, current: User, @@ -2991,941 +1910,30 @@ def query_activity_batch( return results -def _normalize_shop_aliases(values: Any) -> list[str]: - if not isinstance(values, (list, tuple, set)): - return [] - aliases: list[str] = [] - seen: set[str] = set() - for raw in values: - alias = _text(raw, max_length=128) - if not alias or alias in seen: - continue - seen.add(alias) - aliases.append(alias) - return aliases -def _shop_match_values(shop: DouyuCollabShop) -> list[str]: - return [str(shop.name or ""), *list(shop.aliases or [])] -def resolve_shop_name(db: Session, raw_name: str) -> str: - """按店铺管理中人工维护的别名映射规范简称;未知名称原样保留。""" - name = _text(raw_name, max_length=128) - if not name: - return "" - for shop in db.query(DouyuCollabShop).all(): - if name in _shop_match_values(shop): - return str(shop.name) - return name -def _reproject_shop_orders( - db: Session, - shop: DouyuCollabShop, - *, - previous_name: str, - previous_aliases: list[str], -) -> None: - """店铺名称或手工别名变化后,重新计算受影响订单的展示简称。""" - current_aliases = list(shop.aliases or []) - match_values = { - previous_name, - str(shop.name or ""), - *previous_aliases, - *current_aliases, - } - match_values.discard("") - if not match_values: - return - rows = ( - db.query(DouyuExternalOrder) - .filter( - or_( - DouyuExternalOrder.shop.in_(match_values), - DouyuExternalOrder.shop_original_name.in_(match_values), - ) - ) - .all() - ) - for order in rows: - original_name = order.shop_original_name or order.shop or "" - resolved = resolve_shop_name(db, original_name)[:64] - if order.shop == previous_name and original_name in (previous_name, shop.name): - resolved = str(shop.name)[:64] - order.shop = resolved -def ensure_shops_registered( - db: Session, current: User | None, names: list[str] -) -> None: - seen: set[str] = set() - for raw in names: - name = _text(raw, max_length=128) - if not name or name in seen: - continue - seen.add(name) - exists = any( - name in _shop_match_values(shop) - for shop in db.query(DouyuCollabShop).all() - ) - if exists: - continue - db.add( - DouyuCollabShop( - name=name[:64], - created_by=current.id if current else None, - updated_by=current.id if current else None, - ) - ) -def list_shops(db: Session, *, active_only: bool = False) -> list[DouyuCollabShop]: - query = db.query(DouyuCollabShop) - if active_only: - query = query.filter(DouyuCollabShop.is_active.is_(True)) - return query.order_by( - DouyuCollabShop.sort_order.asc(), DouyuCollabShop.id.asc() - ).all() -def get_shop(db: Session, shop_id: int) -> DouyuCollabShop: - shop = db.query(DouyuCollabShop).filter(DouyuCollabShop.id == shop_id).first() - if shop is None: - raise CollabError("店铺不存在", status_code=404, code="shop_not_found") - return shop -def create_shop( - db: Session, - current: User, - *, - name: str, - aliases: Any = None, - remark: str = "", -) -> DouyuCollabShop: - clean = _text(name, max_length=64) - if not clean: - raise CollabError("店铺名不能为空", code="shop_name_required") - exists = db.query(DouyuCollabShop).filter(DouyuCollabShop.name == clean).first() - if exists: - raise CollabError("店铺已存在", status_code=409, code="shop_exists") - shop = DouyuCollabShop( - name=clean, - aliases=_normalize_shop_aliases(aliases), - remark=_text(remark, max_length=255), - created_by=current.id, - updated_by=current.id, - ) - db.add(shop) - db.commit() - db.refresh(shop) - return shop -def update_shop( - db: Session, - current: User, - shop: DouyuCollabShop, - payload: Mapping[str, Any], -) -> DouyuCollabShop: - old_name = shop.name - old_aliases = list(shop.aliases or []) - old = { - "name": shop.name, - "aliases": old_aliases, - "sort_order": shop.sort_order, - "is_active": shop.is_active, - "remark": shop.remark, - } - if "name" in payload: - name = _text(payload.get("name"), max_length=64) - if not name: - raise CollabError("店铺名不能为空", code="shop_name_required") - duplicate = ( - db.query(DouyuCollabShop.id) - .filter( - DouyuCollabShop.name == name, - DouyuCollabShop.id != shop.id, - ) - .first() - ) - if duplicate: - raise CollabError("店铺已存在", status_code=409, code="shop_exists") - shop.name = name - if "aliases" in payload: - shop.aliases = _normalize_shop_aliases(payload.get("aliases")) - if "sort_order" in payload: - shop.sort_order = _to_int(payload.get("sort_order")) or 0 - if "is_active" in payload: - shop.is_active = bool(payload.get("is_active")) - if "remark" in payload: - shop.remark = _text(payload.get("remark"), max_length=255) - shop.updated_by = current.id - if ( - shop.name != old_name - or list(shop.aliases or []) != old_aliases - ): - _reproject_shop_orders( - db, - shop, - previous_name=old_name, - previous_aliases=old_aliases, - ) - record_audit( - db, - current, - action="douyu:collab:shop_update", - target=f"douyu_collab_shop:{shop.id}", - detail={ - "old": old, - "new": { - "name": shop.name, - "aliases": list(shop.aliases or []), - "sort_order": shop.sort_order, - "is_active": shop.is_active, - "remark": shop.remark, - }, - }, - ) - db.commit() - db.refresh(shop) - return shop -def delete_shop(db: Session, current: User, shop: DouyuCollabShop) -> dict[str, Any]: - shop_name = shop.name - used = ( - db.query(func.count(DouyuExternalOrder.id)) - .filter(DouyuExternalOrder.shop == shop_name) - .scalar() - or 0 - ) - if used: - raise CollabError( - f"还有 {used} 个协作单使用「{shop_name}」,请先改名或停用", - code="shop_in_use", - ) - record_audit( - db, - current, - action="douyu:collab:shop_delete", - target=f"douyu_collab_shop:{shop.id}", - detail={"name": shop_name}, - ) - db.delete(shop) - db.commit() - return {"success": True, "name": shop_name} -def list_gifts(db: Session, *, active_only: bool = False) -> list[DouyuCollabGift]: - query = db.query(DouyuCollabGift) - if active_only: - query = query.filter(DouyuCollabGift.is_active.is_(True)) - return query.order_by( - DouyuCollabGift.sort_order.asc(), DouyuCollabGift.id.asc() - ).all() -def get_gift(db: Session, gift_id: int) -> DouyuCollabGift: - gift = db.query(DouyuCollabGift).filter(DouyuCollabGift.id == gift_id).first() - if gift is None: - raise CollabError("礼包不存在", status_code=404, code="gift_not_found") - return gift -def create_gift( - db: Session, - current: User, - *, - name: str, - points: Any, - remark: str = "", -) -> DouyuCollabGift: - clean = _text(name, max_length=128) - if not clean: - raise CollabError("礼包名不能为空", code="gift_name_required") - clean_points = _to_int(points) - if clean_points is None or clean_points < 0: - raise CollabError("所需积分不能为空且不能小于 0", code="gift_points_invalid") - exists = db.query(DouyuCollabGift).filter(DouyuCollabGift.name == clean).first() - if exists: - raise CollabError("礼包已存在", status_code=409, code="gift_exists") - gift = DouyuCollabGift( - name=clean, - points=clean_points, - remark=_text(remark, max_length=255), - created_by=current.id, - updated_by=current.id, - ) - db.add(gift) - db.commit() - db.refresh(gift) - return gift - - -def update_gift( - db: Session, - current: User, - gift: DouyuCollabGift, - payload: Mapping[str, Any], -) -> DouyuCollabGift: - old_name = gift.name - old = { - "name": gift.name, - "points": gift.points, - "sort_order": gift.sort_order, - "is_active": gift.is_active, - "remark": gift.remark, - } - if "name" in payload: - name = _text(payload.get("name"), max_length=128) - if not name: - raise CollabError("礼包名不能为空", code="gift_name_required") - duplicate = ( - db.query(DouyuCollabGift.id) - .filter( - DouyuCollabGift.name == name, - DouyuCollabGift.id != gift.id, - ) - .first() - ) - if duplicate: - raise CollabError("礼包已存在", status_code=409, code="gift_exists") - gift.name = name - if "points" in payload: - points = _to_int(payload.get("points")) - if points is None or points < 0: - raise CollabError( - "所需积分不能为空且不能小于 0", code="gift_points_invalid" - ) - gift.points = points - if "sort_order" in payload: - gift.sort_order = _to_int(payload.get("sort_order")) or 0 - if "is_active" in payload: - gift.is_active = bool(payload.get("is_active")) - if "remark" in payload: - gift.remark = _text(payload.get("remark"), max_length=255) - gift.updated_by = current.id - if gift.name != old_name: - # 名称是订单里的展示/匹配口径,改名要同步历史订单; - # 积分是下单时的快照,更新字典不回填历史订单。 - db.query(DouyuExternalOrder).filter( - DouyuExternalOrder.gift_name == old_name - ).update({DouyuExternalOrder.gift_name: gift.name}, synchronize_session=False) - record_audit( - db, - current, - action="douyu:collab:gift_update", - target=f"douyu_collab_gift:{gift.id}", - detail={ - "old": old, - "new": { - "name": gift.name, - "points": gift.points, - "sort_order": gift.sort_order, - "is_active": gift.is_active, - "remark": gift.remark, - }, - }, - ) - db.commit() - db.refresh(gift) - return gift - - -def delete_gift(db: Session, current: User, gift: DouyuCollabGift) -> dict[str, Any]: - gift_name = gift.name - gift_points = gift.points - used = ( - db.query(func.count(DouyuExternalOrder.id)) - .filter(DouyuExternalOrder.gift_name == gift_name) - .scalar() - or 0 - ) - if used: - raise CollabError( - f"还有 {used} 个协作单使用「{gift_name}」,请先停用或改名", - code="gift_in_use", - ) - record_audit( - db, - current, - action="douyu:collab:gift_delete", - target=f"douyu_collab_gift:{gift.id}", - detail={"name": gift_name, "points": gift_points}, - ) - db.delete(gift) - db.commit() - return {"success": True, "name": gift_name} - - -def list_gift_names(db: Session) -> list[str]: - rows = ( - db.query(DouyuExternalOrder.gift_name) - .filter(DouyuExternalOrder.gift_name != "") - .distinct() - .order_by(DouyuExternalOrder.gift_name.asc()) - .all() - ) - return [str(name) for (name,) in rows if name] - - -def refresh_activity_goods( - db: Session, - current: User, - *, - account_id: int | None = None, - client: Any | None = None, -) -> dict[str, Any]: - config = resolve_config(db) - account = account_by_id(db, account_id) - if account is None: - account = ( - db.query(Account) - .filter(Account.cookie.isnot(None), Account.cookie != "") - .order_by(Account.id.asc()) - .first() - ) - if account is None: - raise CollabError("没有带 CK 的斗鱼账号,无法刷新活动商品", code="no_account") - active_client = client or _client_for_account(account) - config_info = config_mapping(config) - db.expunge(account) - db.commit() - db.add(account) - try: - probe = probe_account( - account, - config_info, - client=active_client, - session_checker=None, - with_elite=False, - with_elite_role=False, - with_goods=True, - ) - goods = (probe.get("goods") or {}).get("items") or [] - if (probe.get("goods") or {}).get("status") == "error": - raise RuntimeError( - (probe.get("goods") or {}).get("error") or "商品查询失败" - ) - persist_probe_result( - db, - account, - probe, - current=current, - source="douyu_collab.goods_refresh", - record_event=False, - ) - except Exception as exc: - record_account_query( - db, - account, - query_type="goods_refresh", - title="刷新活动商品", - ok=False, - detail={"error": str(exc)[:1000]}, - actor_id=current.id, - ) - db.commit() - raise - upsert_goods_snapshot(db, goods, commit=False) - record_account_query( - db, - account, - query_type="goods_refresh", - title="刷新活动商品", - ok=True, - detail={"count": len(goods)}, - actor_id=current.id, - ) - record_audit( - db, - current, - action="douyu:collab:goods_refresh", - target=f"douyu_external_goods:{account.id}", - detail={"count": len(goods), "account_id": account.id}, - ) - db.commit() - return {"count": len(goods), "goods": serialized_goods(db)} - - -def serialized_goods(db: Session) -> list[dict[str, Any]]: - return serialized_snapshots(db) - - -def _metric_views( - db: Session, order_ids: list[int] -) -> tuple[dict[int, DouyuExternalOrderMetric], dict[int, DouyuExternalOrderMetric]]: - """返回最近一条快照,以及最近一条带兑换判定的快照。 - - 余额查询也会落快照,但它的 verdict 是 unknown;列表上的兑换结论应沿用 - 最近一次「查兑换记录」的结果,不能被余额刷新覆盖。 - """ - if not order_ids: - return {}, {} - rows = ( - db.query(DouyuExternalOrderMetric) - .filter(DouyuExternalOrderMetric.order_id.in_(order_ids)) - .order_by( - DouyuExternalOrderMetric.order_id.asc(), - DouyuExternalOrderMetric.id.desc(), - ) - .all() - ) - latest: dict[int, DouyuExternalOrderMetric] = {} - verdict_latest: dict[int, DouyuExternalOrderMetric] = {} - for row in rows: - order_id = int(row.order_id) - latest.setdefault(order_id, row) - if not str(row.source or "").startswith("balance"): - verdict_latest.setdefault(order_id, row) - return latest, verdict_latest - - -def account_clusters( - db: Session, orders: list[DouyuExternalOrder] -) -> dict[int, dict[str, Any]]: - account_ids = {int(order.account_id) for order in orders if order.account_id} - if not account_ids: - return {} - rows = ( - db.query(DouyuExternalOrder) - .filter( - DouyuExternalOrder.account_id.in_(account_ids), - DouyuExternalOrder.archived_at.is_(None), - DouyuExternalOrder.status != STATUS_VOID, - ) - .order_by(DouyuExternalOrder.id.asc()) - .all() - ) - grouped: dict[int, list[DouyuExternalOrder]] = {} - for row in rows: - if row.account_id: - grouped.setdefault(int(row.account_id), []).append(row) - result: dict[int, dict[str, Any]] = {} - for account_id, items in grouped.items(): - if len(items) <= 1: - continue - result[account_id] = { - "total": len(items), - "orders": [ - { - "id": int(item.id), - "order_no": item.order_no, - "status": item.status, - "status_label": ORDER_STATUS_LABELS.get(item.status, item.status), - "gift_name": item.gift_name, - } - for item in items - ], - } - return result - - -def _image_urls(keys: list[str], variant: str = "") -> list[str]: - return [build_file_url(key, variant) for key in keys] - - -def serialize_order( - order: DouyuExternalOrder, - *, - users: Mapping[int, str] | None = None, - accounts: Mapping[int, Account] | None = None, - cluster: Mapping[str, Any] | None = None, - metric: DouyuExternalOrderMetric | None = None, - verdict_metric: DouyuExternalOrderMetric | None = None, -) -> dict[str, Any]: - users = users or {} - accounts = accounts or {} - account = accounts.get(int(order.account_id)) if order.account_id else None - images = list(order.home_images or []) - payload = { - "id": int(order.id), - "order_no": order.order_no, - "shop": order.shop or "", - "shop_original_name": order.shop_original_name or order.shop or "", - "owner_id": order.owner_id, - "owner_name": users.get(int(order.owner_id), "") if order.owner_id else "", - "source_type": order.source_type or "manual", - "source_task_id": order.source_task_id, - "source_order_id": order.source_order_id or "", - "source_order_item_id": order.source_order_item_id or "", - "source_platform_order_id": order.source_platform_order_id or "", - "last_synced_at": order.last_synced_at, - "account_id": order.account_id, - "account_username": order.account_username or "", - "account_uid": order.account_uid or "", - "account_nickname": order.account_nickname or "", - "account_exists": account is not None, - "has_cookie": bool(account and account.cookie), - "account_ck_status": (account.ck_check_status if account else "") or "", - "account_status": (account.status if account else "") 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, - "home_images": images, - "home_image_urls": _image_urls(images), - "home_image_thumb_urls": _image_urls(images, "thumb"), - "gift_name": order.gift_name or "", - "commodity_id": order.commodity_id or "", - "required_points": order.required_points, - "remark": order.remark or "", - "status": order.status or STATUS_INCOMPLETE, - "status_label": ORDER_STATUS_LABELS.get( - order.status or STATUS_INCOMPLETE, order.status or "" - ), - "next_status": ( - STATUS_FLOW[STAGE_INDEX[order.status] + 1] - if order.status in STAGE_INDEX and order.status != STATUS_DONE - else None - ), - "missing_fields": _missing_for_recharge(order), - "fish_fin_balance": order.fish_fin_balance, - "points_balance": order.points_balance, - "points_required_total": order.points_required_total, - "points_surplus": order.points_surplus, - "points_threshold": order.points_threshold, - "points_checked_at": order.points_checked_at, - "points_check_reason": order.points_check_reason or "", - "points_check_message": order.points_check_message or "", - "points_check_detail": order.points_check_detail, - "recharged_at": order.recharged_at, - "scripted_at": order.scripted_at, - "done_at": order.done_at, - "succeeded_at": order.succeeded_at, - "purchase_change_locked": order.succeeded_at is not None, - "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": ( - users.get(int(order.archived_by), "") if order.archived_by else "" - ), - "archive_reason": order.archive_reason or "", - "created_by": order.created_by, - "created_by_name": users.get(int(order.created_by), "") - if order.created_by - else "", - "updated_by": order.updated_by, - "updated_by_name": users.get(int(order.updated_by), "") - if order.updated_by - else "", - "version": int(order.version or 0), - "created_at": order.created_at, - "updated_at": order.updated_at, - "account_cluster": dict(cluster) if cluster else None, - "last_metric_at": metric.created_at if metric else None, - "last_metric_message": metric.message if metric else "", - "last_verdict": verdict_metric.verdict if verdict_metric else "", - "last_verdict_label": { - VERDICT_SUCCESS: "兑换成功", - VERDICT_FAILED: "兑换失败", - VERDICT_UNKNOWN: "无法判定", - }.get(verdict_metric.verdict, "") - if verdict_metric - else "", - "last_records_total": verdict_metric.records_total if verdict_metric else 0, - "last_records_matched": verdict_metric.records_matched if verdict_metric else 0, - } - return payload - - -def _base_order_query(db: Session): - return db.query(DouyuExternalOrder) - - -def _apply_order_filters( - db: Session, - query, - *, - include_void: bool = False, - archive_scope: str = "active", - status: str = "", - shop: str = "", - owner_id: int | None = None, - gift_name: str = "", - keyword: str = "", - ck_status: str = "", -): - search = _text(keyword) - exact_search_filter = None - if search: - exact_search_filter = or_( - DouyuExternalOrder.order_no == search, - DouyuExternalOrder.source_platform_order_id == search, - DouyuExternalOrder.source_order_id == search, - DouyuExternalOrder.source_order_item_id == search, - ) - pattern = f"%{search}%" - fuzzy_search_filter = or_( - DouyuExternalOrder.order_no.ilike(pattern), - DouyuExternalOrder.account_username.ilike(pattern), - DouyuExternalOrder.account_nickname.ilike(pattern), - DouyuExternalOrder.bind_game_role.ilike(pattern), - DouyuExternalOrder.shop.ilike(pattern), - DouyuExternalOrder.remark.ilike(pattern), - DouyuExternalOrder.source_order_id.ilike(pattern), - DouyuExternalOrder.source_order_item_id.ilike(pattern), - DouyuExternalOrder.source_platform_order_id.ilike(pattern), - ) - query = query.filter( - or_( - exact_search_filter, - and_( - order_visibility_expr( - DouyuExternalOrder, - archive_scope=archive_scope, - include_void=include_void, - void_status=STATUS_VOID, - ), - fuzzy_search_filter, - ), - ) - ) - else: - query = query.filter( - order_visibility_expr( - DouyuExternalOrder, - archive_scope=archive_scope, - include_void=include_void, - void_status=STATUS_VOID, - ) - ) - if _text(status): - status_filter = DouyuExternalOrder.status == _text(status) - query = query.filter( - or_(status_filter, exact_search_filter) - if exact_search_filter is not None - else status_filter - ) - if _text(shop): - query = query.filter( - DouyuExternalOrder.shop == resolve_shop_name(db, _text(shop)) - ) - if owner_id is not None: - query = query.filter(DouyuExternalOrder.owner_id == int(owner_id)) - if _text(gift_name): - query = query.filter(DouyuExternalOrder.gift_name == _text(gift_name)) - ck_scope = _text(ck_status) - if ck_scope: - query = query.outerjoin(Account, Account.id == DouyuExternalOrder.account_id) - if ck_scope == CK_VALID: - query = query.filter(Account.ck_check_status == CK_VALID) - elif ck_scope == CK_INVALID: - query = query.filter(Account.ck_check_status == CK_INVALID) - elif ck_scope == CK_UNVERIFIED: - query = query.filter( - or_( - DouyuExternalOrder.account_id.is_(None), - Account.ck_check_status.is_(None), - Account.ck_check_status.in_(("", CK_UNVERIFIED)), - ) - ) - return query - - -def list_orders( - db: Session, - *, - page: int = 1, - page_size: int = 20, - include_void: bool = False, - archive_scope: str = "active", - status: str = "", - shop: str = "", - owner_id: int | None = None, - gift_name: str = "", - keyword: str = "", - ck_status: str = "", -) -> dict[str, Any]: - query = _apply_order_filters( - db, - _base_order_query(db), - include_void=include_void, - archive_scope=archive_scope, - status=status, - shop=shop, - owner_id=owner_id, - gift_name=gift_name, - keyword=keyword, - ck_status=ck_status, - ) - total = ( - query.order_by(None).with_entities(func.count(DouyuExternalOrder.id)).scalar() - or 0 - ) - orders = ( - query.order_by(DouyuExternalOrder.id.asc()) - .offset((max(1, page) - 1) * page_size) - .limit(page_size) - .all() - ) - users = users_by_id( - db, - { - int(item) - for order in orders - for item in ( - order.owner_id, - order.created_by, - order.updated_by, - order.archived_by, - ) - if item - }, - ) - accounts = accounts_by_id( - db, {int(order.account_id) for order in orders if order.account_id} - ) - clusters = account_clusters(db, orders) - metrics, verdict_metrics = _metric_views(db, [int(order.id) for order in orders]) - items = [ - serialize_order( - order, - users=users, - accounts=accounts, - cluster=clusters.get(int(order.account_id)) if order.account_id else None, - metric=metrics.get(int(order.id)), - verdict_metric=verdict_metrics.get(int(order.id)), - ) - for order in orders - ] - return {"items": items, "total": int(total), "page": page, "page_size": page_size} - - -def get_order(db: Session, order_id: int) -> DouyuExternalOrder: - order = ( - db.query(DouyuExternalOrder).filter(DouyuExternalOrder.id == order_id).first() - ) - if order is None: - raise CollabError("协作单不存在", status_code=404, code="order_not_found") - return order - - -def serialize_one(db: Session, order: DouyuExternalOrder) -> dict[str, Any]: - users = users_by_id( - db, - { - int(item) - for item in ( - order.owner_id, - order.created_by, - order.updated_by, - order.archived_by, - ) - if item - }, - ) - accounts = accounts_by_id( - db, {int(order.account_id)} if order.account_id else set() - ) - clusters = account_clusters(db, [order]) - metrics, verdict_metrics = _metric_views(db, [int(order.id)]) - return serialize_order( - order, - users=users, - accounts=accounts, - cluster=clusters.get(int(order.account_id)) if order.account_id else None, - metric=metrics.get(int(order.id)), - verdict_metric=verdict_metrics.get(int(order.id)), - ) - - -def summary( - db: Session, *, include_void: bool = False, archive_scope: str = "active" -) -> dict[str, Any]: - query = _apply_order_filters( - db, - _base_order_query(db), - include_void=include_void, - archive_scope=archive_scope, - ) - rows = query.with_entities( - DouyuExternalOrder.status, func.count(DouyuExternalOrder.id) - ).group_by(DouyuExternalOrder.status) - by_status = {str(status): int(count) for status, count in rows.all()} - total = sum(by_status.values()) - ck_invalid = ( - query.outerjoin(Account, Account.id == DouyuExternalOrder.account_id) - .with_entities(func.count(DouyuExternalOrder.id)) - .filter(Account.ck_check_status == CK_INVALID) - .scalar() - or 0 - ) - return { - "total": total, - "by_status": by_status, - "ck_invalid": int(ck_invalid), - "archived_total": count_archived(db, DouyuExternalOrder), - "account_missing": ( - db.query(func.count(DouyuExternalOrder.id)) - .filter( - DouyuExternalOrder.account_id.is_(None), - DouyuExternalOrder.archived_at.is_(None), - ) - .scalar() - or 0 - ), - } - - -def order_metrics(db: Session, order_id: int) -> list[dict[str, Any]]: - rows = ( - db.query(DouyuExternalOrderMetric) - .filter(DouyuExternalOrderMetric.order_id == order_id) - .order_by(DouyuExternalOrderMetric.id.desc()) - .all() - ) - return [serialize_metric(row) for row in rows] - - -def serialize_metric(row: DouyuExternalOrderMetric) -> dict[str, Any]: - return { - "id": int(row.id), - "order_id": int(row.order_id), - "order_no": row.order_no, - "account_username": row.account_username, - "fish_fin_balance": row.fish_fin_balance, - "points_balance": row.points_balance, - "points_required_total": row.points_required_total, - "points_surplus": row.points_surplus, - "records_total": row.records_total, - "records_matched": row.records_matched, - "verdict": row.verdict, - "verdict_label": { - VERDICT_SUCCESS: "兑换成功", - VERDICT_FAILED: "兑换失败", - VERDICT_UNKNOWN: "无法判定", - }.get(row.verdict, row.verdict), - "message": row.message, - "source": row.source, - "created_at": row.created_at, - } - - -def order_timeline( - db: Session, order_id: int, *, limit: int = 100 -) -> list[dict[str, Any]]: - rows = ( - db.query(AuditLog) - .filter(AuditLog.target == f"douyu_external_order:{order_id}") - .order_by(AuditLog.id.desc()) - .limit(limit) - .all() - ) - return [ - { - "id": int(row.id), - "action": row.action, - "username": row.username or "", - "detail": row.detail or "", - "success": row.success, - "created_at": row.created_at, - } - for row in rows - ] def archive_orders( @@ -4023,173 +2031,3 @@ def delete_order( db.delete(order) db.commit() return {"success": True, "order_no": order_no} - - -def export_cks( - db: Session, - current: User, - order_ids: Sequence[int], - *, - commit: bool = True, -) -> dict[str, Any]: - """导出协作单关联内部账号的 **CK 明文**(前端写剪贴板用)。 - - 斗鱼协作单本身不存 CK,导出的始终是关联 ``accounts.cookie`` 的实时值。 - 和虎牙台账保持同一口径: - - 1. 需要独立权限点 ``douyu:collab:ck_export``; - 2. 每条成功导出都写审计,但审计里只记单号/账号/CK 状态,**不记 CK 本体**; - 3. 未绑定账号、账号没有 CK、订单已删除的行显式跳过并返回原因。 - """ - requested = list(dict.fromkeys(int(item) for item in order_ids if item)) - if not requested: - raise CollabError("请先勾选要导出的行", code="ck_export_empty") - if len(requested) > CK_EXPORT_BATCH_MAX: - raise CollabError( - f"一次最多导出 {CK_EXPORT_BATCH_MAX} 行,请分批操作", - code="ck_export_too_large", - ) - - rows = ( - db.query(DouyuExternalOrder).filter(DouyuExternalOrder.id.in_(requested)).all() - ) - by_id = {int(order.id): order for order in rows} - items: list[dict[str, Any]] = [] - skipped: list[dict[str, Any]] = [] - for order_id in requested: - order = by_id.get(order_id) - if order is None: - skipped.append( - { - "id": order_id, - "order_no": "", - "reason": "协作单不存在或已删除", - } - ) - continue - account = account_by_id(db, order.account_id) or account_by_username( - db, order.account_username - ) - ck_text = str(account.cookie or "").strip() if account else "" - if not ck_text: - reason = ( - "这单还没绑定斗鱼账号" if account is None else "关联的斗鱼账号还没有 CK" - ) - skipped.append( - { - "id": int(order.id), - "order_no": order.order_no, - "reason": reason, - } - ) - continue - - assert account is not None - ck_status = str(account.ck_check_status or "") - items.append( - { - "id": int(order.id), - "order_no": order.order_no, - "account_id": int(account.id), - "account_username": account.username or order.account_username or "", - "account_password": str(account.password or ""), - "account_nickname": account.nickname or order.account_nickname or "", - "status": order.status, - "status_label": ORDER_STATUS_LABELS.get(order.status, order.status), - "ck_status": ck_status, - "ck_status_label": CK_LABELS.get(ck_status, ""), - "ck_text": ck_text, - } - ) - record_audit( - db, - current, - action=CK_EXPORT_ACTION, - target=f"douyu_external_order:{order.id}", - detail={ - "order_no": order.order_no, - "account_username": account.username or order.account_username or "", - "ck_status": ck_status, - "batch_size": len(requested), - }, - ) - if commit: - db.commit() - return { - "total": len(requested), - "exported": len(items), - "skipped": skipped, - "items": items, - } - - -def export_usernames( - db: Session, - order_ids: Sequence[int], -) -> dict[str, Any]: - """导出勾选订单关联的斗鱼用户名(去重、保持选择顺序)。 - - 用户名不是凭据,能看列表的人本来就能看到,所以这里不额外要求 CK 导出权限, - 也不写审计;没有用户名的行会显式跳过。 - """ - requested = list(dict.fromkeys(int(item) for item in order_ids if item)) - if not requested: - raise CollabError("请先勾选要导出的行", code="username_export_empty") - if len(requested) > USERNAME_EXPORT_BATCH_MAX: - raise CollabError( - f"一次最多导出 {USERNAME_EXPORT_BATCH_MAX} 行,请分批操作", - code="username_export_too_large", - ) - - rows = ( - db.query(DouyuExternalOrder).filter(DouyuExternalOrder.id.in_(requested)).all() - ) - by_id = {int(order.id): order for order in rows} - items: list[dict[str, Any]] = [] - skipped: list[dict[str, Any]] = [] - usernames: list[str] = [] - seen: set[str] = set() - for order_id in requested: - order = by_id.get(order_id) - if order is None: - skipped.append( - { - "id": order_id, - "order_no": "", - "reason": "协作单不存在或已删除", - } - ) - continue - username = str(order.account_username or "").strip() - if not username: - account = account_by_id(db, order.account_id) or account_by_username( - db, order.account_username - ) - username = str(account.username if account else "").strip() - if not username: - skipped.append( - { - "id": int(order.id), - "order_no": order.order_no, - "reason": "这单还没填斗鱼用户名", - } - ) - continue - items.append( - { - "id": int(order.id), - "order_no": order.order_no, - "account_username": username, - } - ) - if username not in seen: - seen.add(username) - usernames.append(username) - return { - "total": len(requested), - "exported": len(items), - "unique": len(usernames), - "skipped": skipped, - "items": items, - "usernames": usernames, - } diff --git a/web/backend/services/douyu_collab_shops.py b/web/backend/services/douyu_collab_shops.py new file mode 100644 index 0000000..45312a1 --- /dev/null +++ b/web/backend/services/douyu_collab_shops.py @@ -0,0 +1,244 @@ +"""斗鱼外部单协作的店铺字典与人工别名映射。""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from sqlalchemy import func, or_ +from sqlalchemy.orm import Session + +from ..models import DouyuCollabShop, DouyuExternalOrder, User +from .audit_service import record_audit +from .douyu_collab_common import CollabError, _text, _to_int + + +def _normalize_shop_aliases(values: Any) -> list[str]: + if not isinstance(values, (list, tuple, set)): + return [] + aliases: list[str] = [] + seen: set[str] = set() + for raw in values: + alias = _text(raw, max_length=128) + if not alias or alias in seen: + continue + seen.add(alias) + aliases.append(alias) + return aliases + + +def _shop_match_values(shop: DouyuCollabShop) -> list[str]: + return [str(shop.name or ""), *list(shop.aliases or [])] + + +def resolve_shop_name(db: Session, raw_name: str) -> str: + """按店铺管理中人工维护的别名映射规范简称;未知名称原样保留。""" + name = _text(raw_name, max_length=128) + if not name: + return "" + for shop in db.query(DouyuCollabShop).all(): + if name in _shop_match_values(shop): + return str(shop.name) + return name + + +def _reproject_shop_orders( + db: Session, + shop: DouyuCollabShop, + *, + previous_name: str, + previous_aliases: list[str], +) -> None: + """店铺名称或手工别名变化后,重新计算受影响订单的展示简称。""" + current_aliases = list(shop.aliases or []) + match_values = { + previous_name, + str(shop.name or ""), + *previous_aliases, + *current_aliases, + } + match_values.discard("") + if not match_values: + return + rows = ( + db.query(DouyuExternalOrder) + .filter( + or_( + DouyuExternalOrder.shop.in_(match_values), + DouyuExternalOrder.shop_original_name.in_(match_values), + ) + ) + .all() + ) + for order in rows: + original_name = order.shop_original_name or order.shop or "" + resolved = resolve_shop_name(db, original_name)[:64] + if order.shop == previous_name and original_name in (previous_name, shop.name): + resolved = str(shop.name)[:64] + order.shop = resolved + + +def ensure_shops_registered( + db: Session, + current: User | None, + names: list[str], +) -> None: + seen: set[str] = set() + for raw in names: + name = _text(raw, max_length=128) + if not name or name in seen: + continue + seen.add(name) + exists = any( + name in _shop_match_values(shop) + for shop in db.query(DouyuCollabShop).all() + ) + if exists: + continue + db.add( + DouyuCollabShop( + name=name[:64], + created_by=current.id if current else None, + updated_by=current.id if current else None, + ) + ) + + +def list_shops(db: Session, *, active_only: bool = False) -> list[DouyuCollabShop]: + query = db.query(DouyuCollabShop) + if active_only: + query = query.filter(DouyuCollabShop.is_active.is_(True)) + return query.order_by( + DouyuCollabShop.sort_order.asc(), + DouyuCollabShop.id.asc(), + ).all() + + +def get_shop(db: Session, shop_id: int) -> DouyuCollabShop: + shop = db.query(DouyuCollabShop).filter(DouyuCollabShop.id == shop_id).first() + if shop is None: + raise CollabError("店铺不存在", status_code=404, code="shop_not_found") + return shop + + +def create_shop( + db: Session, + current: User, + *, + name: str, + aliases: Any = None, + remark: str = "", +) -> DouyuCollabShop: + clean = _text(name, max_length=64) + if not clean: + raise CollabError("店铺名不能为空", code="shop_name_required") + exists = db.query(DouyuCollabShop).filter(DouyuCollabShop.name == clean).first() + if exists: + raise CollabError("店铺已存在", status_code=409, code="shop_exists") + shop = DouyuCollabShop( + name=clean, + aliases=_normalize_shop_aliases(aliases), + remark=_text(remark, max_length=255), + created_by=current.id, + updated_by=current.id, + ) + db.add(shop) + db.commit() + db.refresh(shop) + return shop + + +def update_shop( + db: Session, + current: User, + shop: DouyuCollabShop, + payload: Mapping[str, Any], +) -> DouyuCollabShop: + old_name = shop.name + old_aliases = list(shop.aliases or []) + old = { + "name": shop.name, + "aliases": old_aliases, + "sort_order": shop.sort_order, + "is_active": shop.is_active, + "remark": shop.remark, + } + if "name" in payload: + name = _text(payload.get("name"), max_length=64) + if not name: + raise CollabError("店铺名不能为空", code="shop_name_required") + duplicate = ( + db.query(DouyuCollabShop.id) + .filter( + DouyuCollabShop.name == name, + DouyuCollabShop.id != shop.id, + ) + .first() + ) + if duplicate: + raise CollabError("店铺已存在", status_code=409, code="shop_exists") + shop.name = name + if "aliases" in payload: + shop.aliases = _normalize_shop_aliases(payload.get("aliases")) + if "sort_order" in payload: + shop.sort_order = _to_int(payload.get("sort_order")) or 0 + if "is_active" in payload: + shop.is_active = bool(payload.get("is_active")) + if "remark" in payload: + shop.remark = _text(payload.get("remark"), max_length=255) + shop.updated_by = current.id + if shop.name != old_name or list(shop.aliases or []) != old_aliases: + _reproject_shop_orders( + db, + shop, + previous_name=old_name, + previous_aliases=old_aliases, + ) + record_audit( + db, + current, + action="douyu:collab:shop_update", + target=f"douyu_collab_shop:{shop.id}", + detail={ + "old": old, + "new": { + "name": shop.name, + "aliases": list(shop.aliases or []), + "sort_order": shop.sort_order, + "is_active": shop.is_active, + "remark": shop.remark, + }, + }, + ) + db.commit() + db.refresh(shop) + return shop + + +def delete_shop( + db: Session, + current: User, + shop: DouyuCollabShop, +) -> dict[str, Any]: + shop_name = shop.name + used = ( + db.query(func.count(DouyuExternalOrder.id)) + .filter(DouyuExternalOrder.shop == shop_name) + .scalar() + or 0 + ) + if used: + raise CollabError( + f"还有 {used} 个协作单使用「{shop_name}」,请先改名或停用", + code="shop_in_use", + ) + record_audit( + db, + current, + action="douyu:collab:shop_delete", + target=f"douyu_collab_shop:{shop.id}", + detail={"name": shop_name}, + ) + db.delete(shop) + db.commit() + return {"success": True, "name": shop_name} diff --git a/web/backend/services/douyu_collab_sync.py b/web/backend/services/douyu_collab_sync.py new file mode 100644 index 0000000..93f5bae --- /dev/null +++ b/web/backend/services/douyu_collab_sync.py @@ -0,0 +1,368 @@ +"""直播账号履约任务向斗鱼外部单协作的幂等投影。""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +from loguru import logger +from sqlalchemy.orm import Session + +from ..models import ( + Account, + DouyuExternalOrder, + DouyuGoodsSnapshot, + DouyuTask, + PlatformCommodityMapping, + PlatformFulfillmentTask, + User, +) +from .account_binding import binding_channel, binding_role_from_result +from .account_events_service import EVENT_COLLAB_SYNCED +from .audit_service import record_account_action, record_audit +from .douyu_collab_common import ( + POINTS_THRESHOLD_DEFAULT, + SOURCE_TYPE_PLATFORM_FULFILLMENT, + STATUS_DONE, + STATUS_INCOMPLETE, + STATUS_VOID, + CollabError, + _mark_order_succeeded, + _now, + _text, + _to_int, +) +from .douyu_collab_leases import _sync_order_lease +from .douyu_collab_shops import ensure_shops_registered, resolve_shop_name + + +def _platform_fulfillment_gift( + db: Session, + task: PlatformFulfillmentTask, +) -> tuple[str, str, int | None]: + """解析履约任务对应的斗鱼商品,优先显式映射,再回退到商品快照。""" + mapping = ( + db.query(PlatformCommodityMapping) + .filter(PlatformCommodityMapping.id == task.commodity_mapping_id) + .first() + if task.commodity_mapping_id + else None + ) + snapshot = ( + db.query(DouyuGoodsSnapshot) + .filter(DouyuGoodsSnapshot.commodity_id == task.commodity_id) + .first() + if task.commodity_id + else None + ) + name = _text( + (mapping.goods_name if mapping else "") + or (snapshot.name if snapshot else "") + or task.sku_name, + max_length=128, + ) + commodity_id = _text( + task.commodity_id + or (mapping.commodity_id if mapping else "") + or (snapshot.commodity_id if snapshot else ""), + max_length=64, + ) + required_points = _to_int(task.required_points) + if required_points is None and mapping is not None: + required_points = _to_int(mapping.required_points) + if required_points is None and snapshot is not None: + required_points = _to_int(snapshot.score) + return name, commodity_id, required_points + + +def _platform_fulfillment_order_no(task: PlatformFulfillmentTask) -> str: + """外部协作单直接使用 order_site 的真实平台订单号。""" + order_no = _text(task.platform_order_id) + if not order_no: + raise CollabError("履约任务缺少平台订单号", code="platform_order_no_required") + if len(order_no) > 64: + raise CollabError( + "平台订单号超过协作单号长度限制", + code="platform_order_no_too_long", + ) + return order_no + + +def _apply_platform_fulfillment_binding( + db: Session, + order: DouyuExternalOrder, + task: PlatformFulfillmentTask, + *, + overwrite: bool, +) -> None: + """把履约任务已确认的本地绑定结果投影到协作单,不额外联网。""" + bind_task = ( + db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() + if task.bind_task_id + else None + ) + result = ( + bind_task.result if bind_task and isinstance(bind_task.result, dict) else None + ) + role = binding_role_from_result(result) + if not role: + return + if overwrite or not order.bind_game_role: + order.bind_game_role = _text(role, max_length=128) + channel = binding_channel(result) + if channel and (overwrite or not order.bind_game_channel): + order.bind_game_channel = _text(channel, max_length=128) + if overwrite or not order.bind_snapshot_at: + order.bind_snapshot_at = _now() + + +def _apply_platform_fulfillment_status( + order: DouyuExternalOrder, + task: PlatformFulfillmentTask, + *, + created: bool, +) -> None: + """只做不会倒退的状态映射,保留协作台里人工推进的中间状态。""" + if created: + if task.execution_status == "completed": + order.status = STATUS_DONE + order.done_at = order.done_at or task.completed_at or _now() + _mark_order_succeeded(order, order.done_at) + elif task.execution_status == "cancelled": + order.status = STATUS_VOID + order.void_reason = order.void_reason or "直播履约任务已取消" + else: + order.status = STATUS_INCOMPLETE + return + + if task.execution_status == "completed" and order.status not in ( + STATUS_DONE, + STATUS_VOID, + ): + order.status = STATUS_DONE + order.done_at = order.done_at or task.completed_at or _now() + _mark_order_succeeded(order, order.done_at) + elif task.execution_status == "cancelled" and order.status != STATUS_VOID: + order.status = STATUS_VOID + order.void_reason = order.void_reason or "直播履约任务已取消" + + +def sync_platform_fulfillment_order( + db: Session, + current: User, + task: PlatformFulfillmentTask, + *, + commit: bool = True, +) -> tuple[DouyuExternalOrder, str]: + """把一条直播履约任务幂等同步为斗鱼外部协作单。""" + if task.source_system != "order_site": + raise CollabError("仅支持同步 order_site 履约任务", code="source_unsupported") + + order = ( + db.query(DouyuExternalOrder) + .filter(DouyuExternalOrder.source_task_id == task.id) + .first() + ) + order_no = _platform_fulfillment_order_no(task) + created = order is None + order_by_no = ( + db.query(DouyuExternalOrder) + .filter(DouyuExternalOrder.order_no == order_no) + .first() + ) + if order is not None and order_by_no is not None and order_by_no.id != order.id: + raise CollabError( + f"平台订单号 {order_no} 已关联其他履约任务", + code="order_no_conflict", + ) + if order is None and order_by_no is not None: + if order_by_no.source_task_id not in (None, task.id): + raise CollabError( + f"平台订单号 {order_no} 已关联其他履约任务", + code="order_no_conflict", + ) + order = order_by_no + created = False + + now = _now() + account = ( + db.query(Account).filter(Account.id == task.account_id).first() + if task.account_id + else None + ) + gift_name, commodity_id, required_points = _platform_fulfillment_gift(db, task) + + if order is None: + order = DouyuExternalOrder( + order_no=order_no, + source_type=SOURCE_TYPE_PLATFORM_FULFILLMENT, + source_task_id=task.id, + status=STATUS_INCOMPLETE, + points_threshold=POINTS_THRESHOLD_DEFAULT, + owner_id=current.id, + created_by=current.id, + version=0, + created_at=now, + ) + db.add(order) + + order.order_no = order_no + order.source_type = SOURCE_TYPE_PLATFORM_FULFILLMENT + order.source_task_id = int(task.id) + order.source_order_id = _text(task.source_order_id, max_length=64) + order.source_order_item_id = _text(task.source_order_item_id, max_length=64) + order.source_platform_order_id = _text(task.platform_order_id, max_length=128) + order.last_synced_at = now + order.updated_by = current.id + order.updated_at = now + shop_original_name = _text(task.shop_name or task.shop_id, max_length=128) + ensure_shops_registered(db, current, [shop_original_name]) + order.shop = resolve_shop_name(db, shop_original_name)[:64] + order.shop_original_name = shop_original_name + order.gift_name = gift_name + order.commodity_id = commodity_id + order.required_points = required_points + if account is not None and ( + created or (order.account_id is None and not order.account_username) + ): + order.account_id = int(account.id) + order.account_username = _text(account.username, max_length=128) + order.account_uid = _text(account.uid, max_length=32) + order.account_nickname = _text(account.nickname, max_length=128) + _apply_platform_fulfillment_binding( + db, + order, + task, + overwrite=created, + ) + _apply_platform_fulfillment_status(order, task, created=created) + order.version = int(order.version or 0) + 1 + db.flush() + _sync_order_lease( + db, + current, + order, + reason="douyu_collab_sync_terminal", + ) + + audit_detail = { + "taskId": int(task.id), + "orderNo": order.order_no, + "created": created, + "status": order.status, + } + linked_account = ( + db.query(Account).filter(Account.id == order.account_id).first() + if order.account_id + else None + ) + if linked_account is not None: + record_account_action( + db, + current, + account=linked_account, + action="douyu:collab:sync_from_platform_fulfillment", + event_type=EVENT_COLLAB_SYNCED, + title=f"同步外部单协作:{order.order_no}", + target=f"douyu_external_order:{order.id}", + detail=audit_detail, + ) + else: + record_audit( + db, + current, + action="douyu:collab:sync_from_platform_fulfillment", + target=f"douyu_external_order:{order.id}", + detail=audit_detail, + ) + if commit: + db.commit() + db.refresh(order) + return order, "created" if created else "updated" + + +def sync_platform_fulfillment_orders( + db: Session, + current: User, + *, + task_ids: Sequence[int], + commit: bool = True, +) -> dict[str, Any]: + """批量同步履约任务;单条失败回滚自己的 SAVEPOINT,不拖垮整批。""" + requested_ids = list(dict.fromkeys(int(item) for item in task_ids if item)) + tasks = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id.in_(requested_ids)) + .all() + if requested_ids + else [] + ) + tasks_by_id = {int(task.id): task for task in tasks} + result = { + "requested": len(requested_ids), + "created": 0, + "updated": 0, + "skipped": 0, + "failed": 0, + "items": [], + } + + for task_id in requested_ids: + task = tasks_by_id.get(task_id) + if task is None: + result["skipped"] += 1 + result["items"].append( + { + "taskId": task_id, + "action": "skipped", + "reason": "履约任务不存在", + "collabOrderId": None, + "orderNo": "", + } + ) + continue + try: + with db.begin_nested(): + order, action = sync_platform_fulfillment_order( + db, + current, + task, + commit=False, + ) + result[action] += 1 + result["items"].append( + { + "taskId": task_id, + "action": action, + "reason": "", + "collabOrderId": int(order.id), + "orderNo": order.order_no, + } + ) + except CollabError as exc: + result["failed"] += 1 + result["items"].append( + { + "taskId": task_id, + "action": "failed", + "reason": exc.detail, + "collabOrderId": None, + "orderNo": "", + } + ) + except Exception: # noqa: BLE001 - 批量边界需隔离单条未知故障 + logger.exception("同步直播履约任务 {} 到斗鱼外部协作失败", task_id) + result["failed"] += 1 + result["items"].append( + { + "taskId": task_id, + "action": "failed", + "reason": "同步失败,请稍后重试", + "collabOrderId": None, + "orderNo": "", + } + ) + + if commit: + db.commit() + return result diff --git a/web/backend/services/huya_collab_catalog.py b/web/backend/services/huya_collab_catalog.py new file mode 100644 index 0000000..5213ab0 --- /dev/null +++ b/web/backend/services/huya_collab_catalog.py @@ -0,0 +1,298 @@ +"""虎牙外部单协作的礼包字典与常用礼包统计。""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from sqlalchemy import func +from sqlalchemy.orm import Session + +from ..models import HuyaCollabGiftCatalog, HuyaExternalOrder, User +from .audit_service import record_audit +from .huya_collab_common import ( + CollabError, + _clean_required_points, + _now, + clean_text, +) + +GIFT_NAME_LIMIT = 128 + + +def _gift_audit_target(gift: HuyaCollabGiftCatalog) -> str: + return f"huya_collab_gift:{gift.id}" + +def _touch_gift(gift: HuyaCollabGiftCatalog, current: User | None) -> None: + gift.updated_by = current.id if current else None + gift.updated_at = _now() + +def _clean_catalog_points(value: Any) -> int: + points = _clean_required_points(value) + if points is None: + raise CollabError("礼包所需积分不能为空", code="gift_points_invalid") + return points + +def _catalog_points_for_name(db: Session, name: str) -> int | None: + clean = str(name or "").strip() + if not clean: + return None + gift = ( + db.query(HuyaCollabGiftCatalog) + .filter(HuyaCollabGiftCatalog.name == clean) + .first() + ) + return int(gift.points or 0) if gift is not None else None + +def serialize_gift( + gift: HuyaCollabGiftCatalog, *, users: Mapping[int, str] | None = None +) -> dict: + names = users or {} + + def name_of(value: int | None) -> str: + return names.get(int(value), "") if value else "" + + return { + "id": gift.id, + "name": gift.name or "", + "points": int(gift.points or 0), + "sort_order": int(gift.sort_order or 0), + "is_active": bool(gift.is_active), + "remark": gift.remark or "", + "created_by_name": name_of(gift.created_by), + "updated_by_name": name_of(gift.updated_by), + "created_at": gift.created_at, + "updated_at": gift.updated_at, + } + +def list_gift_records(db: Session) -> list[HuyaCollabGiftCatalog]: + """全部礼包字典项(含停用;前端按 ``is_active`` 决定新建时是否可选)。""" + return ( + db.query(HuyaCollabGiftCatalog) + .order_by( + HuyaCollabGiftCatalog.sort_order.asc(), + HuyaCollabGiftCatalog.name.asc(), + ) + .all() + ) + +def get_gift(db: Session, gift_id: int) -> HuyaCollabGiftCatalog: + gift = ( + db.query(HuyaCollabGiftCatalog) + .filter(HuyaCollabGiftCatalog.id == gift_id) + .first() + ) + if gift is None: + raise CollabError( + "这个礼包不存在(可能已被别人删除)", + status_code=404, + code="gift_not_found", + ) + return gift + +def _assert_gift_name_available( + db: Session, name: str, *, exclude_id: int | None = None +) -> None: + query = db.query(HuyaCollabGiftCatalog).filter(HuyaCollabGiftCatalog.name == name) + if exclude_id is not None: + query = query.filter(HuyaCollabGiftCatalog.id != exclude_id) + other = query.first() + if other is not None: + raise CollabError( + f"礼包「{name}」已经在字典里了(第 {other.id} 行)", + status_code=409, + code="gift_name_conflict", + ) + +def create_gift( + db: Session, + current: User | None, + *, + name: Any, + points: Any, + sort_order: int = 0, + remark: Any = "", + commit: bool = True, +) -> HuyaCollabGiftCatalog: + clean_name = clean_text(name, field="gift_name", max_length=GIFT_NAME_LIMIT) + if not clean_name: + raise CollabError("礼包名不能为空", code="gift_name_required") + _assert_gift_name_available(db, clean_name) + gift = HuyaCollabGiftCatalog( + name=clean_name, + points=_clean_catalog_points(points), + sort_order=int(sort_order or 0), + is_active=True, + remark=clean_text(remark, field="gift_remark", max_length=255), + created_by=current.id if current else None, + updated_by=current.id if current else None, + ) + db.add(gift) + db.flush() + record_audit( + db, + current, + action="huya:collab:gift_create", + target=_gift_audit_target(gift), + detail={ + "name": gift.name, + "points": gift.points, + "sort_order": gift.sort_order, + }, + ) + if commit: + db.commit() + db.refresh(gift) + return gift + +def update_gift( + db: Session, + current: User | None, + gift: HuyaCollabGiftCatalog, + payload: Mapping[str, Any], + *, + commit: bool = True, +) -> dict: + """修改礼包字典,返回字段级 diff。 + + 改名会级联所有历史订单上的 ``gift_name``;积分只改字典,不回填订单里 + 已经形成的 ``required_points`` 快照。 + """ + changes: dict[str, dict[str, Any]] = {} + old_name = gift.name or "" + renamed_orders = 0 + + if "name" in payload: + new_name = clean_text( + payload["name"], field="gift_name", max_length=GIFT_NAME_LIMIT + ) + if not new_name: + raise CollabError("礼包名不能为空", code="gift_name_required") + if new_name != old_name: + _assert_gift_name_available(db, new_name, exclude_id=gift.id) + changes["name"] = {"old": old_name, "new": new_name} + gift.name = new_name + + if "points" in payload: + value = _clean_catalog_points(payload["points"]) + if value != int(gift.points or 0): + changes["points"] = {"old": int(gift.points or 0), "new": value} + gift.points = value + + if "sort_order" in payload: + value = int(payload["sort_order"] or 0) + if value != int(gift.sort_order or 0): + changes["sort_order"] = {"old": int(gift.sort_order or 0), "new": value} + gift.sort_order = value + + if "is_active" in payload: + value = bool(payload["is_active"]) + if value != bool(gift.is_active): + changes["is_active"] = {"old": bool(gift.is_active), "new": value} + gift.is_active = value + + if "remark" in payload: + value = clean_text(payload["remark"], field="gift_remark", max_length=255) + if value != (gift.remark or ""): + changes["remark"] = {"old": gift.remark or "", "new": value} + gift.remark = value + + if not changes: + return {} + + if "name" in changes: + renamed_orders = ( + db.query(HuyaExternalOrder) + .filter(HuyaExternalOrder.gift_name == old_name) + .update( + {HuyaExternalOrder.gift_name: changes["name"]["new"]}, + synchronize_session=False, + ) + ) + + _touch_gift(gift, current) + record_audit( + db, + current, + action="huya:collab:gift_update", + target=_gift_audit_target(gift), + detail={"changes": changes, "renamed_orders": renamed_orders}, + ) + if commit: + db.commit() + db.refresh(gift) + return changes + +def delete_gift( + db: Session, + current: User | None, + gift: HuyaCollabGiftCatalog, + *, + commit: bool = True, +) -> dict: + """删除未被订单引用的字典项;仍在使用时明确拒绝,避免历史名称失去标准口径。""" + gift_name = gift.name or "" + used = ( + db.query(func.count(HuyaExternalOrder.id)) + .filter(HuyaExternalOrder.gift_name == gift_name) + .scalar() + or 0 + ) + if used: + raise CollabError( + f"还有 {used} 个协作单使用「{gift_name}」,请先停用或改名", + code="gift_in_use", + ) + snapshot = { + "id": gift.id, + "name": gift_name, + "points": int(gift.points or 0), + } + record_audit( + db, + current, + action="huya:collab:gift_delete", + target=_gift_audit_target(gift), + detail=snapshot, + ) + db.delete(gift) + if commit: + db.commit() + return snapshot + +def list_gift_names(db: Session) -> list[str]: + """台账里出现过的礼包/皮肤名(去重、去空;筛选下拉用)。""" + rows = db.query(HuyaExternalOrder.gift_name).distinct().all() + return sorted( + {str(row[0]).strip() for row in rows if row[0] and str(row[0]).strip()} + ) + +def frequent_gift_names(db: Session, *, limit: int = 8) -> list[dict]: + """台账里用得最多的礼包名(新建 / 补资料时的「常用礼包」快捷按钮)。 + + 口径:**按出现次数降序,次数相同按最近一次使用(最大 id)降序**。 + 空礼包名不统计 —— 那是"还没填",不是一种礼包。 + + **这里不判断"当前活动还有没有这个礼包"**:活动换 SID 之后礼包列表会整批变 + (见设计文档 §11.4),那件事由前端拿礼包缓存去比对;服务层只回答 + "历史上哪些用得多"。 + """ + rows = ( + db.query( + HuyaExternalOrder.gift_name.label("name"), + func.count(HuyaExternalOrder.id).label("used"), + ) + .filter( + HuyaExternalOrder.gift_name.isnot(None), + HuyaExternalOrder.gift_name != "", + ) + .group_by(HuyaExternalOrder.gift_name) + .order_by( + func.count(HuyaExternalOrder.id).desc(), + func.max(HuyaExternalOrder.id).desc(), + ) + .limit(max(1, min(20, int(limit)))) + .all() + ) + # 空名在 SQL 里已经滤掉(见上面的 filter):这里只做类型收口。 + return [{"name": str(name), "used": int(used)} for name, used in rows] diff --git a/web/backend/services/huya_collab_ck.py b/web/backend/services/huya_collab_ck.py new file mode 100644 index 0000000..ebf4c7d --- /dev/null +++ b/web/backend/services/huya_collab_ck.py @@ -0,0 +1,253 @@ +"""虎牙外部单协作的 CK 解析与凭据状态写入口。""" + +from __future__ import annotations + +from typing import Any + +from sqlalchemy.orm import Session + +from ..models import HuyaExternalOrder, User +from .audit_service import record_audit +from .huya_collab_common import ( + CK_CHECKED_STATUSES, + CK_DISABLED, + CK_STATUSES, + CK_UNVERIFIED, + ORDER_STATUS_LABELS, + CollabError, + _audit_target, + _now, + _touch, + assert_order_mutable, + clean_text, + look_like_web_cookie, +) +from .huya_service import build_web_cookie_from_raw, parse_huya_cookie_line + +MANUAL_CK_STATUSES: tuple[str, ...] = (CK_UNVERIFIED, CK_DISABLED) + + +def parse_ck(text: str) -> dict: + """解析粘贴进来的 CK(复用 huya_service 的纯函数,不依赖账号表)。""" + parsed = parse_huya_cookie_line(text or "") + if not parsed: + raise CollabError( + "CK 解析失败:没识别到虎牙 uid(支持「纯 CK」或「账号----密码----CK」)", + code="ck_invalid", + ) + return parsed + +def uid_used_orders( + db: Session, + uid: str | None, + *, + exclude_id: int | None = None, + limit: int = 10, +) -> list[HuyaExternalOrder]: + """这个虎牙号名下**其它**订单(按创建时间升序)。 + + 2026-10-16 用户拍板**放开**「一个虎牙号只能挂一单」:同一个买家第二单常常继续用同一份 + CK。所以这里**不再抛 409**(旧行为见设计文档 §1 的变更记录),只用来在界面上提示 + 「这份 CK 已经挂在哪些单上」、以及在审计里留一笔复用痕迹。 + """ + text = str(uid or "").strip() + if not text: + return [] + query = ( + db.query(HuyaExternalOrder) + .filter(HuyaExternalOrder.uid == text) + .order_by(HuyaExternalOrder.created_at.asc(), HuyaExternalOrder.id.asc()) + ) + if exclude_id is not None: + query = query.filter(HuyaExternalOrder.id != exclude_id) + return query.limit(limit).all() + +def brief_order(order: HuyaExternalOrder) -> dict[str, Any]: + """一行的最小视图(列表/详情里"另一个单"那种展示用)。""" + return { + "id": int(order.id), + "order_no": order.order_no or "", + "shop": order.shop or "", + "gift_name": order.gift_name or "", + "uid": order.uid or "", + "status": order.status, + "status_label": ORDER_STATUS_LABELS.get(order.status, order.status), + "created_at": order.created_at, + } + +def uids_in_use( + db: Session, uid: str | None, *, exclude_id: int | None = None +) -> list[dict]: + """给预览用的「这个虎牙号已经在哪些单上」(没有就空列表)。""" + return [ + brief_order(order) for order in uid_used_orders(db, uid, exclude_id=exclude_id) + ] + +def _apply_ck(order: HuyaExternalOrder, cookie_text: str) -> dict: + """把一份 CK 写进行对象(不含冲突检查与审计,两层调用方共用)。""" + parsed = parse_ck(cookie_text) + cookie = str(parsed.get("cookie") or "") + order.uid = str(parsed.get("uid") or "") + order.yyuid = str(parsed.get("yyuid") or "") + order.hy_username = str(parsed.get("username") or "")[:128] + # 换 CK 后旧昵称不再可信;等下一次验证时由虎牙用户资料接口重新补全。 + order.nickname = "" + order.cookie = cookie + # 粘贴的若是 App 原始凭据(没有网页设备字段),顺手留一份 raw_cookie, + # 以后被风控标记时能直接「重建」而不必重新要 CK。 + if not look_like_web_cookie(cookie): + order.raw_cookie = cookie + order.ck_status = CK_UNVERIFIED + order.ck_checked_at = None + order.ck_check_message = "" + return { + "uid": order.uid, + "cookie_kind": "web" if look_like_web_cookie(cookie) else "raw", + } + +def set_ck( + db: Session, + current: User | None, + order: HuyaExternalOrder, + cookie_text: str, + *, + commit: bool = True, +) -> dict: + """贴入 / 换一份 CK,状态回到「未验证」。 + + 同一个虎牙号**允许**挂在多张单上(2026-10-16 用户拍板放开 uid 唯一性): + 复用到的那些单号只记一笔审计,不挡操作 —— 挡了就变成"同一个买家的第二单建不了"。 + + **不因换 CK 回退业务状态**:``ck_status`` 只代表凭据是否刚验证过。等用户点 + 「充值核账」时会强制重验 CK;如果探针读到的 ``bind_game_account`` 变了, + 整组核账会报错让人先处理,而不是把订单误判到旧账号组里。 + """ + assert_order_mutable(order) + before = str(order.cookie or "") + detail = _apply_ck(order, cookie_text) + reused = [ + item.order_no for item in uid_used_orders(db, order.uid, exclude_id=order.id) + ] + _touch(order, current) + record_audit( + db, + current, + action="huya:collab:ck", + target=_audit_target(order), + detail={ + "kind": "paste", + "uid": order.uid, + "order_no": order.order_no, + # 刻意**不**把 cookie 交给审计层:即便 record_audit 会脱敏, + # 凭据也不该多经一手(脱敏规则一改就是凭据泄漏)。 + # 只留一个「内容是否变了」的布尔,够用来追溯换没换过。 + "credential_changed": before != str(order.cookie or ""), + # 这个虎牙号还挂在哪些单上(同一份 CK 服务多单是允许的,留个痕) + "uid_reused_in": reused, + }, + ) + if commit: + db.commit() + db.refresh(order) + return detail + +def set_ck_status( + db: Session, + current: User | None, + order: HuyaExternalOrder, + status: str, + *, + message: str = "", + commit: bool = True, +) -> dict: + """改写凭据状态(本模块唯一的 ``ck_status`` 写入口)。 + + ``valid`` / ``invalid`` 视为「刚跑过探针」,会刷新 ``ck_checked_at``; + ``disabled`` 是人工停用,不动探针时间。 + """ + if status not in CK_STATUSES: + raise CollabError(f"未知 CK 状态:{status}", code="ck_status_unknown") + assert_order_mutable(order) + previous = order.ck_status + order.ck_status = status + order.ck_check_message = clean_text( + message, field="ck_check_message", max_length=256 + ) + if status in CK_CHECKED_STATUSES: + order.ck_checked_at = _now() + _touch(order, current) + record_audit( + db, + current, + action="huya:collab:ck_status", + target=_audit_target(order), + detail={ + "from": previous, + "to": status, + "message": order.ck_check_message, + "order_no": order.order_no, + }, + ) + if commit: + db.commit() + db.refresh(order) + return {"from": previous, "to": status} + +def rebuild_ck( + db: Session, current: User | None, order: HuyaExternalOrder, *, commit: bool = True +) -> dict: + """用 ``raw_cookie`` 重建网页运行 CK(复用 huya_service 的纯函数)。""" + assert_order_mutable(order) + if not str(order.raw_cookie or "").strip(): + raise CollabError( + "这行没有 App 原始凭据,无法重建网页 CK(请重新贴一份)", + code="no_raw_cookie", + ) + try: + rebuilt = build_web_cookie_from_raw( + uid=str(order.uid or ""), + yyuid=str(order.yyuid or ""), + username=str(order.hy_username or ""), + raw_cookie=str(order.raw_cookie or ""), + ) + except ValueError as exc: + raise CollabError(f"重建失败:{exc}", code="rebuild_failed") from exc + + order.cookie = rebuilt + order.ck_status = CK_UNVERIFIED + order.ck_checked_at = None + order.ck_check_message = "已从 App 原始凭据重建,待验证" + _touch(order, current) + record_audit( + db, + current, + action="huya:collab:ck", + target=_audit_target(order), + detail={ + "kind": "rebuild", + "uid": order.uid, + "order_no": order.order_no, + "credential_changed": True, + }, + ) + if commit: + db.commit() + db.refresh(order) + return {"uid": order.uid, "cookie_kind": "web"} + +def set_manual_ck_status( + db: Session, + current: User | None, + order: HuyaExternalOrder, + status: str, + *, + message: str = "", + commit: bool = True, +) -> dict: + """人工改凭据状态(只允许「已停用」/「未验证」),仍然走 :func:`set_ck_status` 落库。""" + if status not in MANUAL_CK_STATUSES: + raise CollabError( + "人工只能把 CK 标成「已停用」或「未验证」;有效/失效由探针判定", + code="ck_status_manual_only", + ) + return set_ck_status(db, current, order, status, message=message, commit=commit) diff --git a/web/backend/services/huya_collab_common.py b/web/backend/services/huya_collab_common.py new file mode 100644 index 0000000..839356e --- /dev/null +++ b/web/backend/services/huya_collab_common.py @@ -0,0 +1,349 @@ +"""虎牙外部 CK 协作台账的共享状态、字段校验与行级工具。""" + +from __future__ import annotations + +import re +from collections.abc import Sequence +from datetime import UTC, datetime +from typing import Any + +from ..models import HuyaExternalOrder, User +from .file_storage import normalize_object_key + +STATUS_INCOMPLETE = "incomplete" +STATUS_TO_RECHARGE = "to_recharge" +STATUS_RECHARGED = "recharged" +STATUS_SCRIPTED = "scripted" +STATUS_DONE = "done" +STATUS_POINTS_ERROR = "points_error" +STATUS_FAILED = "failed" +STATUS_VOID = "void" + +ORDER_STATUSES: tuple[str, ...] = ( + STATUS_INCOMPLETE, + STATUS_TO_RECHARGE, + STATUS_RECHARGED, + STATUS_SCRIPTED, + STATUS_DONE, + STATUS_POINTS_ERROR, + STATUS_FAILED, + STATUS_VOID, +) + +ORDER_STATUS_LABELS = { + STATUS_INCOMPLETE: "待补资料", + STATUS_TO_RECHARGE: "待充值", + STATUS_RECHARGED: "已充值", + STATUS_SCRIPTED: "已上脚本", + STATUS_DONE: "抢购成功", + STATUS_POINTS_ERROR: "积分异常", + STATUS_FAILED: "抢购失败", + STATUS_VOID: "已作废", + "pending": "待处理(历史)", + "bound": "已确认绑定(历史)", +} + +STATUS_FLOW: tuple[str, ...] = ( + STATUS_INCOMPLETE, + STATUS_TO_RECHARGE, + STATUS_RECHARGED, + STATUS_SCRIPTED, + STATUS_DONE, +) + +NEXT_STATUS = { + STATUS_INCOMPLETE: STATUS_TO_RECHARGE, + STATUS_TO_RECHARGE: STATUS_RECHARGED, + STATUS_RECHARGED: STATUS_SCRIPTED, + STATUS_SCRIPTED: STATUS_DONE, +} + +STAGE_INDEX = { + STATUS_INCOMPLETE: 0, + STATUS_TO_RECHARGE: 1, + STATUS_RECHARGED: 2, + STATUS_SCRIPTED: 3, + STATUS_DONE: 4, +} + +STATUS_TIMESTAMP_FIELDS = { + STATUS_RECHARGED: "recharged_at", + STATUS_SCRIPTED: "scripted_at", + STATUS_DONE: "done_at", +} + +ARCHIVABLE_STATUSES: tuple[str, ...] = (STATUS_DONE,) +ARCHIVE_BATCH_MAX = 5000 +PROBE_BATCH_MAX = 50 + +RECHARGE_POINTS_THRESHOLD_DEFAULT = 100 +RECHARGE_POINTS_THRESHOLD_MAX = 1_000_000 +RECHARGE_POINTS_CONFIRM_DELAY_SECONDS = 30 + +CK_UNVERIFIED = "unverified" +CK_VALID = "valid" +CK_INVALID = "invalid" +CK_DISABLED = "disabled" + +CK_STATUSES: tuple[str, ...] = (CK_UNVERIFIED, CK_VALID, CK_INVALID, CK_DISABLED) + +CK_STATUS_LABELS = { + CK_UNVERIFIED: "未验证", + CK_VALID: "有效", + CK_INVALID: "已失效", + CK_DISABLED: "已停用", +} + +CK_CHECKED_STATUSES = (CK_VALID, CK_INVALID) + +VERDICT_SUCCESS = "success" +VERDICT_FAILED = "failed" +VERDICT_UNKNOWN = "unknown" +VERDICT_NOT_QUERIED = "" +VERDICT_LABELS = { + VERDICT_SUCCESS: "兑换成功", + VERDICT_FAILED: "兑换失败", + VERDICT_UNKNOWN: "无法判定", + VERDICT_NOT_QUERIED: "未判定", +} + +ACTIVITY_SCOPE_BOTH = "both" +ACTIVITY_SCOPE_SCORE = "score" +ACTIVITY_SCOPE_RECORDS = "records" +ACTIVITY_SCOPES: tuple[str, ...] = ( + ACTIVITY_SCOPE_BOTH, + ACTIVITY_SCOPE_SCORE, + ACTIVITY_SCOPE_RECORDS, +) +ACTIVITY_SCOPE_LABELS = { + ACTIVITY_SCOPE_BOTH: "积分 + 兑换记录", + ACTIVITY_SCOPE_SCORE: "积分", + ACTIVITY_SCOPE_RECORDS: "兑换记录", +} + +EDITABLE_FIELDS: tuple[str, ...] = ( + "order_no", + "shop", + "owner_id", + "bind_douyu_account", + "bind_douyu_uid", + "gift_name", + "required_points", + "remark", +) + +FIELD_LIMITS = { + "order_no": 64, + "shop": 64, + "shop_remark": 255, + "bind_douyu_account": 128, + "bind_douyu_uid": 32, + "gift_name": 128, + "remark": 512, + "void_reason": 256, + "archive_reason": 256, + "force_reason": 256, +} + +FIELD_LABELS = { + "order_no": "订单编号", + "shop": "店铺", + "shop_remark": "店铺备注", + "owner_id": "负责人", + "bind_douyu_account": "绑定斗鱼号", + "bind_douyu_uid": "绑定斗鱼号 uid", + "gift_name": "礼包名", + "required_points": "礼包所需积分", + "remark": "备注", + "void_reason": "作废原因", + "force_reason": "强制恢复原因", + "archive_reason": "归档备注", +} + +IMAGE_SLOTS: tuple[str, ...] = ("bind_images", "home_images") +IMAGE_SLOT_LABELS = { + "bind_images": "绑定图", + "home_images": "主页截图", +} +MAX_IMAGES_PER_SLOT = 20 + +WEB_COOKIE_HINTS = ("guid=", "_qimei_uuid42") + + +class CollabError(RuntimeError): + """协作台账的业务错误,路由层据此转成对应 HTTP 状态码。""" + + def __init__(self, detail: str, *, status_code: int = 400, code: str = ""): + super().__init__(detail) + self.detail = detail + self.status_code = status_code + self.code = code + + +def _now() -> datetime: + return datetime.now(UTC) + + +def clean_text( + value: Any, + *, + field: str, + required: bool = False, + max_length: int | None = None, +) -> str: + """统一收口字段清洗:去空白、限长、必填校验。""" + text = str(value if value is not None else "").strip() + limit = max_length or FIELD_LIMITS.get(field, 255) + if len(text) > limit: + raise CollabError( + f"{FIELD_LABELS.get(field, field)}不能超过 {limit} 个字符", + code="field_too_long", + ) + if required and not text: + raise CollabError( + f"{FIELD_LABELS.get(field, field)}不能为空", + code="field_required", + ) + return text + + +def normalize_images(value: Any, *, field: str) -> list[str]: + """把图片字段统一成 object_key 数组。""" + if value is None: + return [] + if isinstance(value, str): + items: Sequence[Any] = [part for part in re.split(r"[,\s]+", value) if part] + elif isinstance(value, (list, tuple)): + items = list(value) + else: + raise CollabError( + f"{IMAGE_SLOT_LABELS.get(field, field)}格式不正确", + code="images_invalid", + ) + + result: list[str] = [] + for item in items: + text = str(item or "").strip() + if not text: + continue + try: + key = normalize_object_key(text) + except ValueError as exc: + raise CollabError( + f"{IMAGE_SLOT_LABELS.get(field, field)}的文件 key 不正确", + code="image_key_invalid", + ) from exc + if key not in result: + result.append(key) + + if len(result) > MAX_IMAGES_PER_SLOT: + raise CollabError( + f"{IMAGE_SLOT_LABELS.get(field, field)}最多 {MAX_IMAGES_PER_SLOT} 张", + code="images_too_many", + ) + return result + + +def images_of(order: HuyaExternalOrder, slot: str) -> list[str]: + value = getattr(order, slot, None) + return [str(item) for item in value] if isinstance(value, list) else [] + + +def look_like_web_cookie(cookie: str) -> bool: + text = cookie or "" + return any(hint in text for hint in WEB_COOKIE_HINTS) + + +def _touch(order: HuyaExternalOrder, current: User | None) -> None: + order.updated_by = current.id if current else None + order.version = int(order.version or 0) + 1 + order.updated_at = _now() + + +def _audit_target(order: HuyaExternalOrder) -> str: + return f"huya_external_order:{order.id}" + + +def assert_order_mutable(order: HuyaExternalOrder) -> None: + if order.archived_at is not None: + raise CollabError( + "这单已归档,只能查看;需要修改请先取消归档", + status_code=409, + code="order_archived", + ) + + +def assert_version(order: HuyaExternalOrder, expected_version: int | None) -> None: + if expected_version is None: + return + if int(expected_version) != int(order.version or 0): + raise CollabError( + f"这行已被 {_last_editor_name(order) or '其他人'} 改过" + f"(版本 {order.version}),请刷新后重试;直接覆盖会丢掉对方的修改", + status_code=409, + code="version_conflict", + ) + + +def _last_editor_name(order: HuyaExternalOrder) -> str: + editor = getattr(order, "updated_by_user", None) + return str(getattr(editor, "username", "") or "") + + +def normalize_points_threshold(value: Any) -> int: + if value is None or value == "": + return RECHARGE_POINTS_THRESHOLD_DEFAULT + try: + number = int(value) + except (TypeError, ValueError) as exc: + raise CollabError( + "积分阈值必须是整数", + code="points_threshold_invalid", + ) from exc + if number < 0: + raise CollabError("积分阈值不能小于 0", code="points_threshold_invalid") + return min(number, RECHARGE_POINTS_THRESHOLD_MAX) + + +def is_forward_status(from_status: str, target: str) -> bool: + if target == STATUS_VOID or target == STATUS_FAILED: + return from_status not in (STATUS_VOID, STATUS_FAILED) + if from_status in (STATUS_VOID, STATUS_FAILED): + return False + if from_status == STATUS_POINTS_ERROR: + return target in (STATUS_TO_RECHARGE, STATUS_RECHARGED) + if target == STATUS_POINTS_ERROR: + return from_status in (STATUS_TO_RECHARGE, STATUS_RECHARGED) + return STAGE_INDEX[target] >= STAGE_INDEX[from_status] + + +def _clean_required_points(value: Any) -> int | None: + if value is None or value == "": + return None + if isinstance(value, bool): + raise CollabError("礼包所需积分必须是整数", code="required_points_invalid") + try: + points = int(value) + except (TypeError, ValueError) as exc: + raise CollabError( + "礼包所需积分必须是整数", + code="required_points_invalid", + ) from exc + if points < 0: + raise CollabError( + "礼包所需积分不能小于 0", + code="required_points_invalid", + ) + return points + + +def _clean_owner_id(value: Any) -> int | None: + if value is None or value == "": + return None + try: + owner_id = int(value) + except (TypeError, ValueError) as exc: + raise CollabError("负责人必须是用户 ID", code="owner_invalid") from exc + if owner_id <= 0: + return None + return owner_id diff --git a/web/backend/services/huya_collab_exports.py b/web/backend/services/huya_collab_exports.py new file mode 100644 index 0000000..dcb5208 --- /dev/null +++ b/web/backend/services/huya_collab_exports.py @@ -0,0 +1,99 @@ +"""虎牙外部单协作的 CK 明文导出。""" + +from __future__ import annotations + +from collections.abc import Sequence + +from sqlalchemy.orm import Session + +from ..models import HuyaExternalOrder, User +from .audit_service import record_audit +from .huya_collab_common import ( + CK_STATUS_LABELS, + ORDER_STATUS_LABELS, + PROBE_BATCH_MAX, + CollabError, + _audit_target, +) + +CK_EXPORT_ACTION = "huya:collab:ck_export" + + +def export_cks( + db: Session, + current: User | None, + orders: Sequence[HuyaExternalOrder], + *, + commit: bool = True, +) -> dict: + """把勾选行的 **CK 明文**取出来(前端写剪贴板用)。 + + 这是本模块唯一一个把凭据**往外送**的读接口,所以三条约束写死在这里: + + 1. **单行复制与批量导出共用一个权限点** ``huya:collab:ck_export``, + 默认给运营和客服;权限页的自定义权限仍可覆盖; + 2. **逐行写审计**(``huya:collab:ck_export``):只记「谁在什么时候导出了哪一单」, + **绝不把 CK 本体写进审计/日志**(列表接口也照旧不返回 cookie); + 3. **没 CK 的行显式跳过并回原因**,不静默丢;也不替用户猜 —— + 作废/停用的单只要还有 CK 照样导出,界面把状态标出来让人自己判断。 + + Returns: + ``{total, exported, skipped: [{id, order_no, reason}], items: [{..., ck_text}]}`` + ——只有这个接口会返回 ``ck_text``。 + """ + rows = list(orders) + if not rows: + raise CollabError("请先勾选要导出的行", code="ck_export_empty") + if len(rows) > PROBE_BATCH_MAX: + raise CollabError( + f"一次最多导出 {PROBE_BATCH_MAX} 行,请分批操作", code="ck_export_too_large" + ) + + items: list[dict] = [] + skipped: list[dict] = [] + for order in rows: + ck_text = str(order.cookie or "").strip() + if not ck_text: + skipped.append( + { + "id": int(order.id), + "order_no": order.order_no, + "reason": "这行还没贴 CK", + } + ) + continue + items.append( + { + "id": int(order.id), + "order_no": order.order_no, + "uid": str(order.uid or ""), + "nickname": order.nickname or "", + "status": order.status, + "status_label": ORDER_STATUS_LABELS.get(order.status, order.status), + "ck_status": order.ck_status, + "ck_status_label": CK_STATUS_LABELS.get( + order.ck_status, order.ck_status + ), + "ck_text": ck_text, + } + ) + record_audit( + db, + current, + action=CK_EXPORT_ACTION, + target=_audit_target(order), + detail={ + "order_no": order.order_no, + "uid": str(order.uid or ""), + "ck_status": order.ck_status, + "batch_size": len(rows), + }, + ) + if commit: + db.commit() + return { + "total": len(rows), + "exported": len(items), + "skipped": skipped, + "items": items, + } diff --git a/web/backend/services/huya_collab_query.py b/web/backend/services/huya_collab_query.py new file mode 100644 index 0000000..5c5aabf --- /dev/null +++ b/web/backend/services/huya_collab_query.py @@ -0,0 +1,769 @@ +"""虎牙外部单协作的查询、归档、序列化与买家聚类。""" + +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 diff --git a/web/backend/services/huya_collab_service.py b/web/backend/services/huya_collab_service.py index caa0d0f..f52f4ee 100644 --- a/web/backend/services/huya_collab_service.py +++ b/web/backend/services/huya_collab_service.py @@ -1,3 +1,4 @@ +# ruff: noqa: F401 """虎牙外部 CK 协作台账的服务层(模型:``models.HuyaExternalOrder``)。 设计见 ``docs/设计-虎牙外部CK协作台账.md``。改这里之前先读文档 §2.3 与 §10.2, @@ -20,7 +21,6 @@ from __future__ import annotations import dataclasses import hashlib -import re import time from collections.abc import Mapping, Sequence from datetime import UTC, datetime, timedelta @@ -50,8 +50,114 @@ 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_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, @@ -61,345 +167,6 @@ from .huya_service import ( parse_huya_cookie_line, ) -# -------------------------------------------------------------------------- -# 业务状态机(一单卡在哪一步) -# -------------------------------------------------------------------------- - -# 「待补资料」是流程链的起点:只登记订单号 + 店铺,CK / 礼包 / 主页截图等客户资料 -# 到了再补(2026-10-17 用户需求)。资料齐全且 CK 有效后自动进入「待充值」。 -STATUS_INCOMPLETE = "incomplete" -STATUS_TO_RECHARGE = "to_recharge" -STATUS_RECHARGED = "recharged" -STATUS_SCRIPTED = "scripted" -STATUS_DONE = "done" -STATUS_POINTS_ERROR = "points_error" -STATUS_FAILED = "failed" -STATUS_VOID = "void" - -ORDER_STATUSES: tuple[str, ...] = ( - STATUS_INCOMPLETE, - STATUS_TO_RECHARGE, - STATUS_RECHARGED, - STATUS_SCRIPTED, - STATUS_DONE, - STATUS_POINTS_ERROR, - STATUS_FAILED, - STATUS_VOID, -) - -ORDER_STATUS_LABELS = { - STATUS_INCOMPLETE: "待补资料", - STATUS_TO_RECHARGE: "待充值", - STATUS_RECHARGED: "已充值", - STATUS_SCRIPTED: "已上脚本", - # 抢购跑到结果:查兑换记录能确认(自动改)也可以人工切(2026-10-16 用户把「已完成」改叫这个) - STATUS_DONE: "抢购成功", - # 充值完成但账号积分总额与礼包积分不匹配(不足或多余超过阈值) - STATUS_POINTS_ERROR: "积分异常", - # 旁路终态:抢购后查兑换记录,没查到这一单的礼包 → 判失败(人工确认后可作废或回退重试) - STATUS_FAILED: "抢购失败", - STATUS_VOID: "已作废", - # 历史标签:只用于旧审计/旧行展示,不在 ORDER_STATUSES 里,不能再作为目标状态。 - "pending": "待处理(历史)", - "bound": "已确认绑定(历史)", -} - -# 流程链(时间戳同步与「能不能向前走」都只看这条链);failed / void 是**旁路**终态, -# points_error 是可恢复的异常态,都不进主链。 -STATUS_FLOW: tuple[str, ...] = ( - STATUS_INCOMPLETE, - STATUS_TO_RECHARGE, - STATUS_RECHARGED, - STATUS_SCRIPTED, - STATUS_DONE, -) - -# 「向前一步」的下一站;done 是终点,failed / void 是旁路,points_error 由核账自动进入。 -NEXT_STATUS = { - STATUS_INCOMPLETE: STATUS_TO_RECHARGE, - STATUS_TO_RECHARGE: STATUS_RECHARGED, - STATUS_RECHARGED: STATUS_SCRIPTED, - STATUS_SCRIPTED: STATUS_DONE, -} - -# 阶段序号:用来同步时间戳(回退时要清掉后面阶段的时间戳,否则状态与时间戳互相矛盾)。 -STAGE_INDEX = { - STATUS_INCOMPLETE: 0, - STATUS_TO_RECHARGE: 1, - STATUS_RECHARGED: 2, - STATUS_SCRIPTED: 3, - STATUS_DONE: 4, -} - -STATUS_TIMESTAMP_FIELDS = { - STATUS_RECHARGED: "recharged_at", - STATUS_SCRIPTED: "scripted_at", - STATUS_DONE: "done_at", -} - -# 归档(可见性)与业务状态正交:只允许归档已经抢购成功、不再需要日常操作的终态行。 -ARCHIVABLE_STATUSES: tuple[str, ...] = (STATUS_DONE,) -# DB-only 的批量归档不需要像外部探针那样限 50 条。 -ARCHIVE_BATCH_MAX = 5000 - -# 充值核账阈值:账号积分 - 礼包积分合计 的允许结余上限(默认 100)。 -RECHARGE_POINTS_THRESHOLD_DEFAULT = 100 -RECHARGE_POINTS_THRESHOLD_MAX = 1_000_000 -# 积分到账/接口缓存可能晚于充值动作。首次算出异常后,统一等待一次再复核, -# 避免把瞬时 0 分直接落成 points_error;同批只等待一次,不按账号组累加。 -RECHARGE_POINTS_CONFIRM_DELAY_SECONDS = 30 - - -def normalize_points_threshold(value: Any) -> int: - """把前端传来的核账阈值规整成 0..MAX 的整数;空值/脏值回落默认 100。""" - if value is None or value == "": - return RECHARGE_POINTS_THRESHOLD_DEFAULT - try: - number = int(value) - except (TypeError, ValueError) as exc: - raise CollabError( - "积分阈值必须是整数", code="points_threshold_invalid" - ) from exc - if number < 0: - raise CollabError("积分阈值不能小于 0", code="points_threshold_invalid") - return min(number, RECHARGE_POINTS_THRESHOLD_MAX) - - -def is_forward_status(from_status: str, target: str) -> bool: - """这一步算不算「向前」(人工切换允许往前跳步,回退必须显式声明)。 - - - 流程链内:目标阶段序号 **≥ 当前** 就是向前(含原地重复设置,幂等); - - `void` / `failed`:任意非终态可进; - - `points_error`:只能从 `to_recharge` / `recharged` 进入,补足后可直接回 `recharged`; - - 从 `void` / `failed` 回到流程内:**必须** rollback。 - """ - if target == STATUS_VOID or target == STATUS_FAILED: - return from_status not in (STATUS_VOID, STATUS_FAILED) - if from_status in (STATUS_VOID, STATUS_FAILED): - return False - if from_status == STATUS_POINTS_ERROR: - return target in (STATUS_TO_RECHARGE, STATUS_RECHARGED) - if target == STATUS_POINTS_ERROR: - return from_status in (STATUS_TO_RECHARGE, STATUS_RECHARGED) - return STAGE_INDEX[target] >= STAGE_INDEX[from_status] - - -# -------------------------------------------------------------------------- -# CK 状态机(凭据本身) -# -------------------------------------------------------------------------- - -CK_UNVERIFIED = "unverified" -CK_VALID = "valid" -CK_INVALID = "invalid" -CK_DISABLED = "disabled" - -CK_STATUSES: tuple[str, ...] = (CK_UNVERIFIED, CK_VALID, CK_INVALID, CK_DISABLED) - -CK_STATUS_LABELS = { - CK_UNVERIFIED: "未验证", - CK_VALID: "有效", - CK_INVALID: "已失效", - CK_DISABLED: "已停用", -} - -# 只有这两种状态代表「刚跑过探针」,需要刷新 ck_checked_at。 -_CK_CHECKED_STATUSES = (CK_VALID, CK_INVALID) - -# -------------------------------------------------------------------------- -# 字段与图片槽位 -# -------------------------------------------------------------------------- - -EDITABLE_FIELDS: tuple[str, ...] = ( - "order_no", - "shop", - "owner_id", - "bind_douyu_account", - "bind_douyu_uid", - "gift_name", - "required_points", - "remark", -) - -FIELD_LIMITS = { - "order_no": 64, - "shop": 64, - "shop_remark": 255, - "bind_douyu_account": 128, - "bind_douyu_uid": 32, - "gift_name": 128, - "remark": 512, - "void_reason": 256, - "archive_reason": 256, - "force_reason": 256, -} - -FIELD_LABELS = { - "order_no": "订单编号", - "shop": "店铺", - "shop_remark": "店铺备注", - "owner_id": "负责人", - "bind_douyu_account": "绑定斗鱼号", - "bind_douyu_uid": "绑定斗鱼号 uid", - "gift_name": "礼包名", - "required_points": "礼包所需积分", - "remark": "备注", - "void_reason": "作废原因", - "force_reason": "强制恢复原因", - "archive_reason": "归档备注", -} - -IMAGE_SLOTS: tuple[str, ...] = ("bind_images", "home_images") - -IMAGE_SLOT_LABELS = { - "bind_images": "绑定图", - "home_images": "主页截图", -} - -MAX_IMAGES_PER_SLOT = 20 - -# 网页运行 CK 才有这两类字段;没有 → 粘贴进来的其实是 App 原始凭据, -# 顺手存进 raw_cookie,以后就能用「重建」续命(不用重新找人要 CK)。 -_WEB_COOKIE_HINTS = ("guid=", "_qimei_uuid42") - - -class CollabError(RuntimeError): - """协作台账的业务错误,路由层据此转成对应 HTTP 状态码。""" - - def __init__(self, detail: str, *, status_code: int = 400, code: str = ""): - super().__init__(detail) - self.detail = detail - self.status_code = status_code - self.code = code - - -# -------------------------------------------------------------------------- -# 内部工具 -# -------------------------------------------------------------------------- - - -def _now() -> datetime: - return datetime.now(UTC) - - -def clean_text( - value: Any, *, field: str, required: bool = False, max_length: int | None = None -) -> str: - """统一收口字段清洗:去空白、限长、必填校验。 - - **不静默截断**:超长直接报错,否则用户填了 100 字备注、库里只剩 512 字节 - 之前的片段,事后没人知道被切过。 - """ - text = str(value if value is not None else "").strip() - limit = max_length or FIELD_LIMITS.get(field, 255) - if len(text) > limit: - raise CollabError( - f"{FIELD_LABELS.get(field, field)}不能超过 {limit} 个字符", - code="field_too_long", - ) - if required and not text: - raise CollabError( - f"{FIELD_LABELS.get(field, field)}不能为空", code="field_required" - ) - return text - - -def normalize_images(value: Any, *, field: str) -> list[str]: - """把图片字段统一成 object_key 数组(去空、去重、挡路径穿越、限张数)。""" - if value is None: - return [] - if isinstance(value, str): - items: Sequence[Any] = [part for part in re.split(r"[,\s]+", value) if part] - elif isinstance(value, (list, tuple)): - items = list(value) - else: - raise CollabError( - f"{IMAGE_SLOT_LABELS.get(field, field)}格式不正确", code="images_invalid" - ) - - result: list[str] = [] - for item in items: - text = str(item or "").strip() - if not text: - continue - try: - key = normalize_object_key(text) - except ValueError as exc: - raise CollabError( - f"{IMAGE_SLOT_LABELS.get(field, field)}的文件 key 不正确", - code="image_key_invalid", - ) from exc - if key not in result: - result.append(key) - - if len(result) > MAX_IMAGES_PER_SLOT: - raise CollabError( - f"{IMAGE_SLOT_LABELS.get(field, field)}最多 {MAX_IMAGES_PER_SLOT} 张", - code="images_too_many", - ) - return result - - -def images_of(order: HuyaExternalOrder, slot: str) -> list[str]: - """安全读取图片数组(JSON 列历史上可能是 None)。""" - value = getattr(order, slot, None) - return [str(item) for item in value] if isinstance(value, list) else [] - - -def look_like_web_cookie(cookie: str) -> bool: - """判断一份 CK 是否已是「网页运行态」(含 guid/_qimei_uuid42 设备字段)。""" - text = cookie or "" - return any(hint in text for hint in _WEB_COOKIE_HINTS) - - -def parse_ck(text: str) -> dict: - """解析粘贴进来的 CK(复用 huya_service 的纯函数,不依赖账号表)。""" - parsed = parse_huya_cookie_line(text or "") - if not parsed: - raise CollabError( - "CK 解析失败:没识别到虎牙 uid(支持「纯 CK」或「账号----密码----CK」)", - code="ck_invalid", - ) - return parsed - - -def _touch(order: HuyaExternalOrder, current: User | None) -> None: - """每次写入统一推进版本号与最后修改人(乐观锁靠 version,不用 updated_at)。""" - order.updated_by = current.id if current else None - order.version = int(order.version or 0) + 1 - order.updated_at = _now() - - -def _audit_target(order: HuyaExternalOrder) -> str: - return f"huya_external_order:{order.id}" - - -def assert_order_mutable(order: HuyaExternalOrder) -> None: - """归档后整行只读;要改状态/CK/备注必须先取消归档。""" - if order.archived_at is not None: - raise CollabError( - "这单已归档,只能查看;需要修改请先取消归档", - status_code=409, - code="order_archived", - ) - - -def assert_version(order: HuyaExternalOrder, expected_version: int | None) -> None: - """乐观锁:客户端提交时带的版本必须与库里一致,否则说明别人先改了。""" - if expected_version is None: - return - if int(expected_version) != int(order.version or 0): - raise CollabError( - f"这行已被 {_last_editor_name(order) or '其他人'} 改过(版本 {order.version})," - "请刷新后重试;直接覆盖会丢掉对方的修改", - status_code=409, - code="version_conflict", - ) - - -def _last_editor_name(order: HuyaExternalOrder) -> str: - editor = getattr(order, "updated_by_user", None) - return str(getattr(editor, "username", "") or "") - def _assert_order_no_available( db: Session, order_no: str, *, exclude_id: int | None = None @@ -416,76 +183,12 @@ def _assert_order_no_available( ) -def uid_used_orders( - db: Session, - uid: str | None, - *, - exclude_id: int | None = None, - limit: int = 10, -) -> list[HuyaExternalOrder]: - """这个虎牙号名下**其它**订单(按创建时间升序)。 - - 2026-10-16 用户拍板**放开**「一个虎牙号只能挂一单」:同一个买家第二单常常继续用同一份 - CK。所以这里**不再抛 409**(旧行为见设计文档 §1 的变更记录),只用来在界面上提示 - 「这份 CK 已经挂在哪些单上」、以及在审计里留一笔复用痕迹。 - """ - text = str(uid or "").strip() - if not text: - return [] - query = ( - db.query(HuyaExternalOrder) - .filter(HuyaExternalOrder.uid == text) - .order_by(HuyaExternalOrder.created_at.asc(), HuyaExternalOrder.id.asc()) - ) - if exclude_id is not None: - query = query.filter(HuyaExternalOrder.id != exclude_id) - return query.limit(limit).all() -def brief_order(order: HuyaExternalOrder) -> dict[str, Any]: - """一行的最小视图(列表/详情里"另一个单"那种展示用)。""" - return { - "id": int(order.id), - "order_no": order.order_no or "", - "shop": order.shop or "", - "gift_name": order.gift_name or "", - "uid": order.uid or "", - "status": order.status, - "status_label": ORDER_STATUS_LABELS.get(order.status, order.status), - "created_at": order.created_at, - } -def uids_in_use( - db: Session, uid: str | None, *, exclude_id: int | None = None -) -> list[dict]: - """给预览用的「这个虎牙号已经在哪些单上」(没有就空列表)。""" - return [ - brief_order(order) for order in uid_used_orders(db, uid, exclude_id=exclude_id) - ] -def _apply_ck(order: HuyaExternalOrder, cookie_text: str) -> dict: - """把一份 CK 写进行对象(不含冲突检查与审计,两层调用方共用)。""" - parsed = parse_ck(cookie_text) - cookie = str(parsed.get("cookie") or "") - order.uid = str(parsed.get("uid") or "") - order.yyuid = str(parsed.get("yyuid") or "") - order.hy_username = str(parsed.get("username") or "")[:128] - # 换 CK 后旧昵称不再可信;等下一次验证时由虎牙用户资料接口重新补全。 - order.nickname = "" - order.cookie = cookie - # 粘贴的若是 App 原始凭据(没有网页设备字段),顺手留一份 raw_cookie, - # 以后被风控标记时能直接「重建」而不必重新要 CK。 - if not look_like_web_cookie(cookie): - order.raw_cookie = cookie - order.ck_status = CK_UNVERIFIED - order.ck_checked_at = None - order.ck_check_message = "" - return { - "uid": order.uid, - "cookie_kind": "web" if look_like_web_cookie(cookie) else "raw", - } # -------------------------------------------------------------------------- @@ -1603,159 +1306,16 @@ def check_recharge_groups( # -------------------------------------------------------------------------- -def set_ck( - db: Session, - current: User | None, - order: HuyaExternalOrder, - cookie_text: str, - *, - commit: bool = True, -) -> dict: - """贴入 / 换一份 CK,状态回到「未验证」。 - - 同一个虎牙号**允许**挂在多张单上(2026-10-16 用户拍板放开 uid 唯一性): - 复用到的那些单号只记一笔审计,不挡操作 —— 挡了就变成"同一个买家的第二单建不了"。 - - **不因换 CK 回退业务状态**:``ck_status`` 只代表凭据是否刚验证过。等用户点 - 「充值核账」时会强制重验 CK;如果探针读到的 ``bind_game_account`` 变了, - 整组核账会报错让人先处理,而不是把订单误判到旧账号组里。 - """ - assert_order_mutable(order) - before = str(order.cookie or "") - detail = _apply_ck(order, cookie_text) - reused = [ - item.order_no for item in uid_used_orders(db, order.uid, exclude_id=order.id) - ] - _touch(order, current) - record_audit( - db, - current, - action="huya:collab:ck", - target=_audit_target(order), - detail={ - "kind": "paste", - "uid": order.uid, - "order_no": order.order_no, - # 刻意**不**把 cookie 交给审计层:即便 record_audit 会脱敏, - # 凭据也不该多经一手(脱敏规则一改就是凭据泄漏)。 - # 只留一个「内容是否变了」的布尔,够用来追溯换没换过。 - "credential_changed": before != str(order.cookie or ""), - # 这个虎牙号还挂在哪些单上(同一份 CK 服务多单是允许的,留个痕) - "uid_reused_in": reused, - }, - ) - if commit: - db.commit() - db.refresh(order) - return detail -def set_ck_status( - db: Session, - current: User | None, - order: HuyaExternalOrder, - status: str, - *, - message: str = "", - commit: bool = True, -) -> dict: - """改写凭据状态(本模块唯一的 ``ck_status`` 写入口)。 - - ``valid`` / ``invalid`` 视为「刚跑过探针」,会刷新 ``ck_checked_at``; - ``disabled`` 是人工停用,不动探针时间。 - """ - if status not in CK_STATUSES: - raise CollabError(f"未知 CK 状态:{status}", code="ck_status_unknown") - assert_order_mutable(order) - previous = order.ck_status - order.ck_status = status - order.ck_check_message = clean_text( - message, field="ck_check_message", max_length=256 - ) - if status in _CK_CHECKED_STATUSES: - order.ck_checked_at = _now() - _touch(order, current) - record_audit( - db, - current, - action="huya:collab:ck_status", - target=_audit_target(order), - detail={ - "from": previous, - "to": status, - "message": order.ck_check_message, - "order_no": order.order_no, - }, - ) - if commit: - db.commit() - db.refresh(order) - return {"from": previous, "to": status} -def rebuild_ck( - db: Session, current: User | None, order: HuyaExternalOrder, *, commit: bool = True -) -> dict: - """用 ``raw_cookie`` 重建网页运行 CK(复用 huya_service 的纯函数)。""" - assert_order_mutable(order) - if not str(order.raw_cookie or "").strip(): - raise CollabError( - "这行没有 App 原始凭据,无法重建网页 CK(请重新贴一份)", - code="no_raw_cookie", - ) - try: - rebuilt = build_web_cookie_from_raw( - uid=str(order.uid or ""), - yyuid=str(order.yyuid or ""), - username=str(order.hy_username or ""), - raw_cookie=str(order.raw_cookie or ""), - ) - except ValueError as exc: - raise CollabError(f"重建失败:{exc}", code="rebuild_failed") from exc - - order.cookie = rebuilt - order.ck_status = CK_UNVERIFIED - order.ck_checked_at = None - order.ck_check_message = "已从 App 原始凭据重建,待验证" - _touch(order, current) - record_audit( - db, - current, - action="huya:collab:ck", - target=_audit_target(order), - detail={ - "kind": "rebuild", - "uid": order.uid, - "order_no": order.order_no, - "credential_changed": True, - }, - ) - if commit: - db.commit() - db.refresh(order) - return {"uid": order.uid, "cookie_kind": "web"} # 人工能改的 CK 状态:`valid` / `invalid` 只能由探针给(人工标「有效」等于绕过验证)。 MANUAL_CK_STATUSES: tuple[str, ...] = (CK_UNVERIFIED, CK_DISABLED) -def set_manual_ck_status( - db: Session, - current: User | None, - order: HuyaExternalOrder, - status: str, - *, - message: str = "", - commit: bool = True, -) -> dict: - """人工改凭据状态(只允许「已停用」/「未验证」),仍然走 :func:`set_ck_status` 落库。""" - if status not in MANUAL_CK_STATUSES: - raise CollabError( - "人工只能把 CK 标成「已停用」或「未验证」;有效/失效由探针判定", - code="ck_status_manual_only", - ) - return set_ck_status(db, current, order, status, message=message, commit=commit) def set_images( @@ -1833,8 +1393,6 @@ _probe_cache: dict[str, tuple[float, CkProbeResult]] = {} # 批量验证**串行 + 间隔**:不做定时轮询,一次也别勾太多,避免把账号送进风控名单。 PROBE_BATCH_INTERVAL_SECONDS = 1.0 -PROBE_BATCH_MAX = 50 - _CK_MESSAGE_LIMIT = 256 # ck_check_message 列宽 _PROBE_PIECE_LIMIT = 40 # 拼消息时单段文本的上限 @@ -2076,38 +1634,6 @@ def resolve_gifts_sid(db: Session) -> int: ACTIVITY_QUERY_TIMEOUT_SECONDS = 15.0 -VERDICT_SUCCESS = "success" -VERDICT_FAILED = "failed" -VERDICT_UNKNOWN = "unknown" -#: 「本次**没查**兑换记录」的判定值:**空串**。 -#: 必须与 ``unknown``(查了、但接口没通/判不了)分开 —— 列表上的判定徽标会跳过空值, -#: 否则点一次「查积分」就会把整页的徽标冲成「无法判定」,把已有结论抹掉。 -VERDICT_NOT_QUERIED = "" - -VERDICT_LABELS = { - VERDICT_SUCCESS: "兑换成功", - VERDICT_FAILED: "兑换失败", - VERDICT_UNKNOWN: "无法判定", - # 空判定 = 本次没查兑换记录(拆分查询入口后才有),与「无法判定」必须分开 - VERDICT_NOT_QUERIED: "未判定", -} - -# 「积分 / 兑换记录」的查询范围(2026-10-17 用户要求:批量按钮拆成两个)。 -# 只查一半时,**没查的那一半不写值、也不判定** —— 不许拿「没查」冒充「没有」。 -ACTIVITY_SCOPE_BOTH = "both" -ACTIVITY_SCOPE_SCORE = "score" -ACTIVITY_SCOPE_RECORDS = "records" -ACTIVITY_SCOPES: tuple[str, ...] = ( - ACTIVITY_SCOPE_BOTH, - ACTIVITY_SCOPE_SCORE, - ACTIVITY_SCOPE_RECORDS, -) -ACTIVITY_SCOPE_LABELS = { - ACTIVITY_SCOPE_BOTH: "积分 + 兑换记录", - ACTIVITY_SCOPE_SCORE: "积分", - ACTIVITY_SCOPE_RECORDS: "兑换记录", -} - # 官方兑换记录存在落库延迟:生产实测三单在查询后 20~54 秒才出现记录。 # 因此脚本开始后的观察窗口内,「没查到」只能算暂时无法判定,不能自动判失败。 ACTIVITY_RESULT_SETTLE_SECONDS = 10 * 60 @@ -2212,144 +1738,6 @@ def _extract_records(resp: Any) -> tuple[list[dict[str, Any]], str]: return list(data.get("records") or []), "" -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 {} - matched = raw.get("matched") if isinstance(raw.get("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 query_order_activity( @@ -2883,118 +2271,13 @@ def verify_ck_batch( } -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] # 导出 CK 的审计动作名(导出=把凭据带出系统,必须留痕) -CK_EXPORT_ACTION = "huya:collab:ck_export" -def export_cks( - db: Session, - current: User | None, - orders: Sequence[HuyaExternalOrder], - *, - commit: bool = True, -) -> dict: - """把勾选行的 **CK 明文**取出来(前端写剪贴板用)。 - - 这是本模块唯一一个把凭据**往外送**的读接口,所以三条约束写死在这里: - - 1. **单行复制与批量导出共用一个权限点** ``huya:collab:ck_export``, - 默认给运营和客服;权限页的自定义权限仍可覆盖; - 2. **逐行写审计**(``huya:collab:ck_export``):只记「谁在什么时候导出了哪一单」, - **绝不把 CK 本体写进审计/日志**(列表接口也照旧不返回 cookie); - 3. **没 CK 的行显式跳过并回原因**,不静默丢;也不替用户猜 —— - 作废/停用的单只要还有 CK 照样导出,界面把状态标出来让人自己判断。 - - Returns: - ``{total, exported, skipped: [{id, order_no, reason}], items: [{..., ck_text}]}`` - ——只有这个接口会返回 ``ck_text``。 - """ - rows = list(orders) - if not rows: - raise CollabError("请先勾选要导出的行", code="ck_export_empty") - if len(rows) > PROBE_BATCH_MAX: - raise CollabError( - f"一次最多导出 {PROBE_BATCH_MAX} 行,请分批操作", code="ck_export_too_large" - ) - - items: list[dict] = [] - skipped: list[dict] = [] - for order in rows: - ck_text = str(order.cookie or "").strip() - if not ck_text: - skipped.append( - { - "id": int(order.id), - "order_no": order.order_no, - "reason": "这行还没贴 CK", - } - ) - continue - items.append( - { - "id": int(order.id), - "order_no": order.order_no, - "uid": str(order.uid or ""), - "nickname": order.nickname or "", - "status": order.status, - "status_label": ORDER_STATUS_LABELS.get(order.status, order.status), - "ck_status": order.ck_status, - "ck_status_label": CK_STATUS_LABELS.get( - order.ck_status, order.ck_status - ), - "ck_text": ck_text, - } - ) - record_audit( - db, - current, - action=CK_EXPORT_ACTION, - target=_audit_target(order), - detail={ - "order_no": order.order_no, - "uid": str(order.uid or ""), - "ck_status": order.ck_status, - "batch_size": len(rows), - }, - ) - if commit: - db.commit() - return { - "total": len(rows), - "exported": len(items), - "skipped": skipped, - "items": items, - } # -------------------------------------------------------------------------- @@ -3005,544 +2288,54 @@ SHOP_NAME_LIMIT = 64 GIFT_NAME_LIMIT = 128 -def normalize_shop_name(value: Any) -> str: - """店铺名统一收口:去空白 + 限长(空串 = 不填店铺)。""" - return clean_text(value, field="shop", max_length=SHOP_NAME_LIMIT) - - -def _shop_audit_target(shop: HuyaCollabShop) -> str: - return f"huya_collab_shop:{shop.id}" - - -def _touch_shop(shop: HuyaCollabShop, current: User | None) -> None: - shop.updated_by = current.id if current else None - shop.updated_at = _now() - - -def serialize_shop( - shop: HuyaCollabShop, *, users: Mapping[int, str] | None = None -) -> dict: - names = users or {} - - def name_of(value: int | None) -> str: - return names.get(int(value), "") if value else "" - - return { - "id": shop.id, - "name": shop.name or "", - "sort_order": int(shop.sort_order or 0), - "is_active": bool(shop.is_active), - "remark": shop.remark or "", - "created_by_name": name_of(shop.created_by), - "updated_by_name": name_of(shop.updated_by), - "created_at": shop.created_at, - "updated_at": shop.updated_at, - } - - -def list_shop_records(db: Session) -> list[HuyaCollabShop]: - """全部店铺(**含停用的**:管理弹窗要能看到;新建下拉由前端按 `is_active` 过滤)。""" - return ( - db.query(HuyaCollabShop) - .order_by(HuyaCollabShop.sort_order.asc(), HuyaCollabShop.name.asc()) - .all() - ) - - -def get_shop(db: Session, shop_id: int) -> HuyaCollabShop: - shop = db.query(HuyaCollabShop).filter(HuyaCollabShop.id == shop_id).first() - if shop is None: - raise CollabError( - "这个店铺不存在(可能已被别人删除)", status_code=404, code="shop_not_found" - ) - return shop - - -def _assert_shop_name_available( - db: Session, name: str, *, exclude_id: int | None = None -) -> None: - query = db.query(HuyaCollabShop).filter(HuyaCollabShop.name == name) - if exclude_id is not None: - query = query.filter(HuyaCollabShop.id != exclude_id) - other = query.first() - if other is not None: - raise CollabError( - f"店铺「{name}」已经在字典里了(第 {other.id} 行)", - status_code=409, - code="shop_name_conflict", - ) - - -def create_shop( - db: Session, - current: User | None, - *, - name: Any, - sort_order: int = 0, - remark: Any = "", - commit: bool = True, -) -> HuyaCollabShop: - """新增一个店铺(重名 409)。""" - cleaned = normalize_shop_name(name) - if not cleaned: - raise CollabError("店铺名不能为空", code="shop_name_required") - _assert_shop_name_available(db, cleaned) - shop = HuyaCollabShop( - name=cleaned, - sort_order=int(sort_order or 0), - is_active=True, - remark=clean_text(remark, field="shop_remark", max_length=255), - created_by=current.id if current else None, - updated_by=current.id if current else None, - ) - db.add(shop) - db.flush() - record_audit( - db, - current, - action="huya:collab:shop_create", - target=_shop_audit_target(shop), - detail={"name": shop.name, "sort_order": shop.sort_order}, - ) - if commit: - db.commit() - db.refresh(shop) - return shop - - -def update_shop( - db: Session, - current: User | None, - shop: HuyaCollabShop, - payload: Mapping[str, Any], - *, - rename_orders: bool = True, - commit: bool = True, -) -> dict: - """改店铺(名字 / 排序 / 停用 / 备注),返回字段级 diff。 - - ``rename_orders=True``(默认)时,改名会**级联**把已有订单里的旧名字一起改掉, - 否则筛选会出现"改名前的老名字"这一堆孤儿值;不想要级联就显式传 False。 - """ - changes: dict[str, dict[str, Any]] = {} - old_name = shop.name or "" - renamed_orders = 0 - - if "name" in payload: - new_name = normalize_shop_name(payload["name"]) - if not new_name: - raise CollabError("店铺名不能为空", code="shop_name_required") - if new_name != old_name: - _assert_shop_name_available(db, new_name, exclude_id=shop.id) - changes["name"] = {"old": old_name, "new": new_name} - shop.name = new_name - - if "sort_order" in payload: - value = int(payload["sort_order"] or 0) - if value != int(shop.sort_order or 0): - changes["sort_order"] = {"old": int(shop.sort_order or 0), "new": value} - shop.sort_order = value - - if "is_active" in payload: - value = bool(payload["is_active"]) - if value != bool(shop.is_active): - changes["is_active"] = {"old": bool(shop.is_active), "new": value} - shop.is_active = value - - if "remark" in payload: - value = clean_text(payload["remark"], field="shop_remark", max_length=255) - if value != (shop.remark or ""): - changes["remark"] = {"old": shop.remark or "", "new": value} - shop.remark = value - - if not changes: - return {} - - if "name" in changes and rename_orders: - # 批量改名:订单里存的是名字字符串(见 models.HuyaCollabShop 的取舍说明)。 - renamed_orders = ( - db.query(HuyaExternalOrder) - .filter(HuyaExternalOrder.shop == old_name) - .update( - {HuyaExternalOrder.shop: changes["name"]["new"]}, - synchronize_session=False, - ) - ) - - _touch_shop(shop, current) - record_audit( - db, - current, - action="huya:collab:shop_update", - target=_shop_audit_target(shop), - detail={"changes": changes, "renamed_orders": renamed_orders}, - ) - if commit: - db.commit() - db.refresh(shop) - return changes - - -def delete_shop( - db: Session, current: User | None, shop: HuyaCollabShop, *, commit: bool = True -) -> dict: - """从字典里删掉(需 ``huya:collab:manage``)。 - - **不动订单**:订单里存的是名字字符串,历史单子照旧;想让以后不再用它, - 用「停用」更稳。 - """ - snapshot = {"id": shop.id, "name": shop.name or ""} - record_audit( - db, - current, - action="huya:collab:shop_delete", - target=_shop_audit_target(shop), - detail=snapshot, - ) - db.delete(shop) - if commit: - db.commit() - return snapshot - - -def ensure_shops_registered( - db: Session, current: User | None, names: Sequence[Any] -) -> list[str]: - """把订单里用到的店铺名补进字典(新建 / 编辑 / 粘贴导入共用),返回新登记的名字。 - - 这样"自定义输入一个新店铺"就能直接出现在下次的下拉里,不用先去管理弹窗加一遍。 - """ - wanted = [str(name or "").strip() for name in names] - wanted = [name for name in dict.fromkeys(wanted) if name] - if not wanted: - return [] - known = { - row[0] - for row in db.query(HuyaCollabShop.name) - .filter(HuyaCollabShop.name.in_(wanted)) - .all() - } - created: list[str] = [] - for name in wanted: - if name in known or len(name) > SHOP_NAME_LIMIT: - continue - db.add( - HuyaCollabShop( - name=name, - sort_order=0, - is_active=True, - remark="", - created_by=current.id if current else None, - updated_by=current.id if current else None, - ) - ) - created.append(name) - if created: - # 先 flush 让同一批里的重名在唯一索引上炸出来(而不是拖到 commit)。 - db.flush() - record_audit( - db, - current, - action="huya:collab:shop_create", - target="huya_collab_shops", - detail={"auto_registered": created}, - ) - return created - - -def list_shops(db: Session) -> list[str]: - """字典里的店铺名(筛选/下拉用;停用的也在,前端自己决定展示哪些)。""" - return sorted(shop.name for shop in list_shop_records(db)) - - -def _gift_audit_target(gift: HuyaCollabGiftCatalog) -> str: - return f"huya_collab_gift:{gift.id}" - - -def _touch_gift(gift: HuyaCollabGiftCatalog, current: User | None) -> None: - gift.updated_by = current.id if current else None - gift.updated_at = _now() - - -def _clean_catalog_points(value: Any) -> int: - points = _clean_required_points(value) - if points is None: - raise CollabError("礼包所需积分不能为空", code="gift_points_invalid") - return points - - -def _catalog_points_for_name(db: Session, name: str) -> int | None: - clean = str(name or "").strip() - if not clean: - return None - gift = ( - db.query(HuyaCollabGiftCatalog) - .filter(HuyaCollabGiftCatalog.name == clean) - .first() - ) - return int(gift.points or 0) if gift is not None else None - - -def serialize_gift( - gift: HuyaCollabGiftCatalog, *, users: Mapping[int, str] | None = None -) -> dict: - names = users or {} - - def name_of(value: int | None) -> str: - return names.get(int(value), "") if value else "" - - return { - "id": gift.id, - "name": gift.name or "", - "points": int(gift.points or 0), - "sort_order": int(gift.sort_order or 0), - "is_active": bool(gift.is_active), - "remark": gift.remark or "", - "created_by_name": name_of(gift.created_by), - "updated_by_name": name_of(gift.updated_by), - "created_at": gift.created_at, - "updated_at": gift.updated_at, - } - - -def list_gift_records(db: Session) -> list[HuyaCollabGiftCatalog]: - """全部礼包字典项(含停用;前端按 ``is_active`` 决定新建时是否可选)。""" - return ( - db.query(HuyaCollabGiftCatalog) - .order_by( - HuyaCollabGiftCatalog.sort_order.asc(), - HuyaCollabGiftCatalog.name.asc(), - ) - .all() - ) - - -def get_gift(db: Session, gift_id: int) -> HuyaCollabGiftCatalog: - gift = ( - db.query(HuyaCollabGiftCatalog) - .filter(HuyaCollabGiftCatalog.id == gift_id) - .first() - ) - if gift is None: - raise CollabError( - "这个礼包不存在(可能已被别人删除)", - status_code=404, - code="gift_not_found", - ) - return gift - - -def _assert_gift_name_available( - db: Session, name: str, *, exclude_id: int | None = None -) -> None: - query = db.query(HuyaCollabGiftCatalog).filter(HuyaCollabGiftCatalog.name == name) - if exclude_id is not None: - query = query.filter(HuyaCollabGiftCatalog.id != exclude_id) - other = query.first() - if other is not None: - raise CollabError( - f"礼包「{name}」已经在字典里了(第 {other.id} 行)", - status_code=409, - code="gift_name_conflict", - ) - - -def create_gift( - db: Session, - current: User | None, - *, - name: Any, - points: Any, - sort_order: int = 0, - remark: Any = "", - commit: bool = True, -) -> HuyaCollabGiftCatalog: - clean_name = clean_text(name, field="gift_name", max_length=GIFT_NAME_LIMIT) - if not clean_name: - raise CollabError("礼包名不能为空", code="gift_name_required") - _assert_gift_name_available(db, clean_name) - gift = HuyaCollabGiftCatalog( - name=clean_name, - points=_clean_catalog_points(points), - sort_order=int(sort_order or 0), - is_active=True, - remark=clean_text(remark, field="gift_remark", max_length=255), - created_by=current.id if current else None, - updated_by=current.id if current else None, - ) - db.add(gift) - db.flush() - record_audit( - db, - current, - action="huya:collab:gift_create", - target=_gift_audit_target(gift), - detail={ - "name": gift.name, - "points": gift.points, - "sort_order": gift.sort_order, - }, - ) - if commit: - db.commit() - db.refresh(gift) - return gift - - -def update_gift( - db: Session, - current: User | None, - gift: HuyaCollabGiftCatalog, - payload: Mapping[str, Any], - *, - commit: bool = True, -) -> dict: - """修改礼包字典,返回字段级 diff。 - - 改名会级联所有历史订单上的 ``gift_name``;积分只改字典,不回填订单里 - 已经形成的 ``required_points`` 快照。 - """ - changes: dict[str, dict[str, Any]] = {} - old_name = gift.name or "" - renamed_orders = 0 - - if "name" in payload: - new_name = clean_text( - payload["name"], field="gift_name", max_length=GIFT_NAME_LIMIT - ) - if not new_name: - raise CollabError("礼包名不能为空", code="gift_name_required") - if new_name != old_name: - _assert_gift_name_available(db, new_name, exclude_id=gift.id) - changes["name"] = {"old": old_name, "new": new_name} - gift.name = new_name - - if "points" in payload: - value = _clean_catalog_points(payload["points"]) - if value != int(gift.points or 0): - changes["points"] = {"old": int(gift.points or 0), "new": value} - gift.points = value - - if "sort_order" in payload: - value = int(payload["sort_order"] or 0) - if value != int(gift.sort_order or 0): - changes["sort_order"] = {"old": int(gift.sort_order or 0), "new": value} - gift.sort_order = value - - if "is_active" in payload: - value = bool(payload["is_active"]) - if value != bool(gift.is_active): - changes["is_active"] = {"old": bool(gift.is_active), "new": value} - gift.is_active = value - - if "remark" in payload: - value = clean_text(payload["remark"], field="gift_remark", max_length=255) - if value != (gift.remark or ""): - changes["remark"] = {"old": gift.remark or "", "new": value} - gift.remark = value - - if not changes: - return {} - - if "name" in changes: - renamed_orders = ( - db.query(HuyaExternalOrder) - .filter(HuyaExternalOrder.gift_name == old_name) - .update( - {HuyaExternalOrder.gift_name: changes["name"]["new"]}, - synchronize_session=False, - ) - ) - - _touch_gift(gift, current) - record_audit( - db, - current, - action="huya:collab:gift_update", - target=_gift_audit_target(gift), - detail={"changes": changes, "renamed_orders": renamed_orders}, - ) - if commit: - db.commit() - db.refresh(gift) - return changes - - -def delete_gift( - db: Session, - current: User | None, - gift: HuyaCollabGiftCatalog, - *, - commit: bool = True, -) -> dict: - """删除未被订单引用的字典项;仍在使用时明确拒绝,避免历史名称失去标准口径。""" - gift_name = gift.name or "" - used = ( - db.query(func.count(HuyaExternalOrder.id)) - .filter(HuyaExternalOrder.gift_name == gift_name) - .scalar() - or 0 - ) - if used: - raise CollabError( - f"还有 {used} 个协作单使用「{gift_name}」,请先停用或改名", - code="gift_in_use", - ) - snapshot = { - "id": gift.id, - "name": gift_name, - "points": int(gift.points or 0), - } - record_audit( - db, - current, - action="huya:collab:gift_delete", - target=_gift_audit_target(gift), - detail=snapshot, - ) - db.delete(gift) - if commit: - db.commit() - return snapshot - - -def list_gift_names(db: Session) -> list[str]: - """台账里出现过的礼包/皮肤名(去重、去空;筛选下拉用)。""" - rows = db.query(HuyaExternalOrder.gift_name).distinct().all() - return sorted( - {str(row[0]).strip() for row in rows if row[0] and str(row[0]).strip()} - ) - - -def frequent_gift_names(db: Session, *, limit: int = 8) -> list[dict]: - """台账里用得最多的礼包名(新建 / 补资料时的「常用礼包」快捷按钮)。 - - 口径:**按出现次数降序,次数相同按最近一次使用(最大 id)降序**。 - 空礼包名不统计 —— 那是"还没填",不是一种礼包。 - - **这里不判断"当前活动还有没有这个礼包"**:活动换 SID 之后礼包列表会整批变 - (见设计文档 §11.4),那件事由前端拿礼包缓存去比对;服务层只回答 - "历史上哪些用得多"。 - """ - rows = ( - db.query( - HuyaExternalOrder.gift_name.label("name"), - func.count(HuyaExternalOrder.id).label("used"), - ) - .filter( - HuyaExternalOrder.gift_name.isnot(None), - HuyaExternalOrder.gift_name != "", - ) - .group_by(HuyaExternalOrder.gift_name) - .order_by( - func.count(HuyaExternalOrder.id).desc(), - func.max(HuyaExternalOrder.id).desc(), - ) - .limit(max(1, min(20, int(limit)))) - .all() - ) - # 空名在 SQL 里已经滤掉(见上面的 filter):这里只做类型收口。 - return [{"name": str(name), "used": int(used)} for name, used in rows] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # -------------------------------------------------------------------------- @@ -3550,21 +2343,6 @@ def frequent_gift_names(db: Session, *, limit: int = 8) -> list[dict]: # -------------------------------------------------------------------------- -def _clean_required_points(value: Any) -> int | None: - """礼包所需积分:允许空;非负整数,拒绝布尔/小数/脏值。""" - if value is None or value == "": - return None - if isinstance(value, bool): - raise CollabError("礼包所需积分必须是整数", code="required_points_invalid") - try: - points = int(value) - except (TypeError, ValueError) as exc: - raise CollabError( - "礼包所需积分必须是整数", code="required_points_invalid" - ) from exc - if points < 0: - raise CollabError("礼包所需积分不能小于 0", code="required_points_invalid") - return points def create_order( @@ -3835,16 +2613,6 @@ def delete_order( return snapshot -def _clean_owner_id(value: Any) -> int | None: - if value is None or value == "": - return None - try: - owner_id = int(value) - except (TypeError, ValueError) as exc: - raise CollabError("负责人必须是用户 ID", code="owner_invalid") from exc - if owner_id <= 0: - return None - return owner_id # -------------------------------------------------------------------------- @@ -3876,501 +2644,22 @@ ORDER_SORT_KEYS: tuple[str, ...] = ( ) -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 "" - ), - } # -------------------------------------------------------------------------- @@ -4383,76 +2672,8 @@ def serialize_order( BUYER_KEY_METHOD = "bind_game_account+bind_game_role" -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 # -------------------------------------------------------------------------- @@ -4576,7 +2797,7 @@ def import_orders( seen_order_nos.add(order_no) owner_name = str(record.get("owner") or "").strip() - payload = { + payload: dict[str, Any] = { "shop": record.get("shop", ""), "bind_douyu_account": record.get("bind_douyu_account", ""), "gift_name": record.get("gift_name", ""), diff --git a/web/backend/services/huya_collab_shops.py b/web/backend/services/huya_collab_shops.py new file mode 100644 index 0000000..bda165b --- /dev/null +++ b/web/backend/services/huya_collab_shops.py @@ -0,0 +1,253 @@ +"""虎牙外部单协作的店铺字典。""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import Any + +from sqlalchemy.orm import Session + +from ..models import HuyaCollabShop, HuyaExternalOrder, User +from .audit_service import record_audit +from .huya_collab_common import CollabError, _now, clean_text + +SHOP_NAME_LIMIT = 64 + + +def normalize_shop_name(value: Any) -> str: + """店铺名统一收口:去空白 + 限长(空串 = 不填店铺)。""" + return clean_text(value, field="shop", max_length=SHOP_NAME_LIMIT) + +def _shop_audit_target(shop: HuyaCollabShop) -> str: + return f"huya_collab_shop:{shop.id}" + +def _touch_shop(shop: HuyaCollabShop, current: User | None) -> None: + shop.updated_by = current.id if current else None + shop.updated_at = _now() + +def serialize_shop( + shop: HuyaCollabShop, *, users: Mapping[int, str] | None = None +) -> dict: + names = users or {} + + def name_of(value: int | None) -> str: + return names.get(int(value), "") if value else "" + + return { + "id": shop.id, + "name": shop.name or "", + "sort_order": int(shop.sort_order or 0), + "is_active": bool(shop.is_active), + "remark": shop.remark or "", + "created_by_name": name_of(shop.created_by), + "updated_by_name": name_of(shop.updated_by), + "created_at": shop.created_at, + "updated_at": shop.updated_at, + } + +def list_shop_records(db: Session) -> list[HuyaCollabShop]: + """全部店铺(**含停用的**:管理弹窗要能看到;新建下拉由前端按 `is_active` 过滤)。""" + return ( + db.query(HuyaCollabShop) + .order_by(HuyaCollabShop.sort_order.asc(), HuyaCollabShop.name.asc()) + .all() + ) + +def get_shop(db: Session, shop_id: int) -> HuyaCollabShop: + shop = db.query(HuyaCollabShop).filter(HuyaCollabShop.id == shop_id).first() + if shop is None: + raise CollabError( + "这个店铺不存在(可能已被别人删除)", status_code=404, code="shop_not_found" + ) + return shop + +def _assert_shop_name_available( + db: Session, name: str, *, exclude_id: int | None = None +) -> None: + query = db.query(HuyaCollabShop).filter(HuyaCollabShop.name == name) + if exclude_id is not None: + query = query.filter(HuyaCollabShop.id != exclude_id) + other = query.first() + if other is not None: + raise CollabError( + f"店铺「{name}」已经在字典里了(第 {other.id} 行)", + status_code=409, + code="shop_name_conflict", + ) + +def create_shop( + db: Session, + current: User | None, + *, + name: Any, + sort_order: int = 0, + remark: Any = "", + commit: bool = True, +) -> HuyaCollabShop: + """新增一个店铺(重名 409)。""" + cleaned = normalize_shop_name(name) + if not cleaned: + raise CollabError("店铺名不能为空", code="shop_name_required") + _assert_shop_name_available(db, cleaned) + shop = HuyaCollabShop( + name=cleaned, + sort_order=int(sort_order or 0), + is_active=True, + remark=clean_text(remark, field="shop_remark", max_length=255), + created_by=current.id if current else None, + updated_by=current.id if current else None, + ) + db.add(shop) + db.flush() + record_audit( + db, + current, + action="huya:collab:shop_create", + target=_shop_audit_target(shop), + detail={"name": shop.name, "sort_order": shop.sort_order}, + ) + if commit: + db.commit() + db.refresh(shop) + return shop + +def update_shop( + db: Session, + current: User | None, + shop: HuyaCollabShop, + payload: Mapping[str, Any], + *, + rename_orders: bool = True, + commit: bool = True, +) -> dict: + """改店铺(名字 / 排序 / 停用 / 备注),返回字段级 diff。 + + ``rename_orders=True``(默认)时,改名会**级联**把已有订单里的旧名字一起改掉, + 否则筛选会出现"改名前的老名字"这一堆孤儿值;不想要级联就显式传 False。 + """ + changes: dict[str, dict[str, Any]] = {} + old_name = shop.name or "" + renamed_orders = 0 + + if "name" in payload: + new_name = normalize_shop_name(payload["name"]) + if not new_name: + raise CollabError("店铺名不能为空", code="shop_name_required") + if new_name != old_name: + _assert_shop_name_available(db, new_name, exclude_id=shop.id) + changes["name"] = {"old": old_name, "new": new_name} + shop.name = new_name + + if "sort_order" in payload: + value = int(payload["sort_order"] or 0) + if value != int(shop.sort_order or 0): + changes["sort_order"] = {"old": int(shop.sort_order or 0), "new": value} + shop.sort_order = value + + if "is_active" in payload: + value = bool(payload["is_active"]) + if value != bool(shop.is_active): + changes["is_active"] = {"old": bool(shop.is_active), "new": value} + shop.is_active = value + + if "remark" in payload: + value = clean_text(payload["remark"], field="shop_remark", max_length=255) + if value != (shop.remark or ""): + changes["remark"] = {"old": shop.remark or "", "new": value} + shop.remark = value + + if not changes: + return {} + + if "name" in changes and rename_orders: + # 批量改名:订单里存的是名字字符串(见 models.HuyaCollabShop 的取舍说明)。 + renamed_orders = ( + db.query(HuyaExternalOrder) + .filter(HuyaExternalOrder.shop == old_name) + .update( + {HuyaExternalOrder.shop: changes["name"]["new"]}, + synchronize_session=False, + ) + ) + + _touch_shop(shop, current) + record_audit( + db, + current, + action="huya:collab:shop_update", + target=_shop_audit_target(shop), + detail={"changes": changes, "renamed_orders": renamed_orders}, + ) + if commit: + db.commit() + db.refresh(shop) + return changes + +def delete_shop( + db: Session, current: User | None, shop: HuyaCollabShop, *, commit: bool = True +) -> dict: + """从字典里删掉(需 ``huya:collab:manage``)。 + + **不动订单**:订单里存的是名字字符串,历史单子照旧;想让以后不再用它, + 用「停用」更稳。 + """ + snapshot = {"id": shop.id, "name": shop.name or ""} + record_audit( + db, + current, + action="huya:collab:shop_delete", + target=_shop_audit_target(shop), + detail=snapshot, + ) + db.delete(shop) + if commit: + db.commit() + return snapshot + +def ensure_shops_registered( + db: Session, current: User | None, names: Sequence[Any] +) -> list[str]: + """把订单里用到的店铺名补进字典(新建 / 编辑 / 粘贴导入共用),返回新登记的名字。 + + 这样"自定义输入一个新店铺"就能直接出现在下次的下拉里,不用先去管理弹窗加一遍。 + """ + wanted = [str(name or "").strip() for name in names] + wanted = [name for name in dict.fromkeys(wanted) if name] + if not wanted: + return [] + known = { + row[0] + for row in db.query(HuyaCollabShop.name) + .filter(HuyaCollabShop.name.in_(wanted)) + .all() + } + created: list[str] = [] + for name in wanted: + if name in known or len(name) > SHOP_NAME_LIMIT: + continue + db.add( + HuyaCollabShop( + name=name, + sort_order=0, + is_active=True, + remark="", + created_by=current.id if current else None, + updated_by=current.id if current else None, + ) + ) + created.append(name) + if created: + # 先 flush 让同一批里的重名在唯一索引上炸出来(而不是拖到 commit)。 + db.flush() + record_audit( + db, + current, + action="huya:collab:shop_create", + target="huya_collab_shops", + detail={"auto_registered": created}, + ) + return created + +def list_shops(db: Session) -> list[str]: + """字典里的店铺名(筛选/下拉用;停用的也在,前端自己决定展示哪些)。""" + return sorted(shop.name for shop in list_shop_records(db)) diff --git a/web/frontend/src/pages/DouyuCollabPage.tsx b/web/frontend/src/pages/DouyuCollabPage.tsx index 1f2c52f..15a375c 100644 --- a/web/frontend/src/pages/DouyuCollabPage.tsx +++ b/web/frontend/src/pages/DouyuCollabPage.tsx @@ -79,430 +79,35 @@ import { useCollabRealtime, type CollabRealtimeEvent } from '../hooks/useCollabR import { message } from '../utils/antdMessage'; import { getErrorMessage } from '../utils/error'; import { copyTextToClipboard } from '../utils/clipboard'; +import { + CK_META, + COLUMN_LABELS, + COLUMN_LAYOUT_STORAGE_PREFIX, + EMPTY_FORM, + FLOW_ORDER, + REALTIME_PAUSED_STORAGE_KEY, + REALTIME_WS_PATH, + STATUS_META, + STATUS_ORDER, + cardStyle, + collabActionLabel, + collabCkLabel, + collabTimelineDetailLines, + errorCodeOf, + formatTime, + goodsOptions, + hasTextInputFocus, + normalizeColumnLayout, + pointsReasonMeta, + readColumnLayout, + readRealtimePaused, + successfulPurchaseChanges, + type ColumnPreference, + type OrderFormState, +} from './DouyuCollabPageConfig'; const { Text } = Typography; -function errorCodeOf(error: unknown): string { - return (error as { errorCode?: string } | null)?.errorCode || ''; -} - -function hasTextInputFocus(): boolean { - const active = document.activeElement; - return ( - active instanceof HTMLElement && - (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable) - ); -} - -/** 实时同步暂停开关按浏览器记住:刷新页面后仍保持暂停,直到手动恢复。 */ -const REALTIME_PAUSED_STORAGE_KEY = 'douyu.collab.realtime-paused'; -const REALTIME_WS_PATH = '/api/douyu/external-orders/ws'; -const COLUMN_LAYOUT_STORAGE_PREFIX = 'douyu.collab.columns'; - -const DEFAULT_COLUMN_LAYOUT = [ - { key: 'sequence', visible: true }, - { key: 'order_shop', visible: true }, - { key: 'owner', visible: true }, - { key: 'account', visible: true }, - { key: 'bind_role', visible: true }, - { key: 'home_images', visible: true }, - { key: 'gift', visible: true }, - { key: 'status', visible: true }, - { key: 'balances', visible: true }, - { key: 'last_query', visible: true }, - { key: 'updated', visible: true }, - { key: 'actions', visible: true }, -] as const; - -const COLUMN_LABELS: Record = { - sequence: '序号', - order_shop: '订单 / 店铺', - owner: '负责人', - account: '斗鱼账号', - bind_role: '绑定角色', - home_images: '主页截图', - gift: '礼包 / 积分', - status: '状态', - balances: '鱼翅 / 积分', - last_query: '最近查询', - updated: '最后改动', - actions: '操作', -}; - -type ColumnPreference = { key: string; visible: boolean }; - -function normalizeColumnLayout(raw: unknown): ColumnPreference[] { - const defaults = DEFAULT_COLUMN_LAYOUT.map((item) => ({ ...item })); - if (!Array.isArray(raw)) return defaults; - const known = new Set(defaults.map((item) => item.key)); - const result: ColumnPreference[] = []; - const seen = new Set(); - for (const item of raw) { - if (!item || typeof item !== 'object') continue; - const row = item as { key?: unknown; visible?: unknown }; - const key = String(row.key || ''); - if (!known.has(key) || seen.has(key)) continue; - seen.add(key); - result.push({ - key, - visible: key === 'actions' ? true : row.visible !== false, - }); - } - for (const item of defaults) { - if (!seen.has(item.key)) result.push(item); - } - return result; -} - -function readColumnLayout(userId?: number): ColumnPreference[] { - if (!userId) return normalizeColumnLayout(null); - try { - const raw = window.localStorage.getItem( - `${COLUMN_LAYOUT_STORAGE_PREFIX}:${userId}`, - ); - return normalizeColumnLayout(raw ? JSON.parse(raw) : null); - } catch { - return normalizeColumnLayout(null); - } -} - -function readRealtimePaused(): boolean { - try { - return window.localStorage.getItem(REALTIME_PAUSED_STORAGE_KEY) === '1'; - } catch { - return false; - } -} - -function cardStyle(active: boolean) { - return { - borderColor: active ? '#1677ff' : undefined, - cursor: 'pointer', - } as const; -} - -const STATUS_META: Record = { - incomplete: { label: '待补资料', color: 'default' }, - to_recharge: { label: '待充值', color: 'blue' }, - recharged: { label: '已充值', color: 'cyan' }, - scripted: { label: '已上脚本', color: 'purple' }, - done: { label: '抢购成功', color: 'green' }, - points_error: { label: '积分异常', color: 'orange' }, - role_error: { label: '账号角色异常', color: 'volcano' }, - failed: { label: '抢购失败', color: 'red' }, - void: { label: '已作废', color: 'default' }, -}; - -const STATUS_ORDER: DouyuCollabStatus[] = [ - 'incomplete', - 'to_recharge', - 'recharged', - 'scripted', - 'done', - 'points_error', - 'role_error', - 'failed', - 'void', -]; - -const FLOW_ORDER: DouyuCollabStatus[] = [ - 'incomplete', - 'to_recharge', - 'recharged', - 'scripted', - 'done', -]; - -const CK_META: Record = { - unverified: { label: '未检测', color: 'default' }, - valid: { label: 'CK 正常', color: 'green' }, - invalid: { label: 'CK 异常', color: 'red' }, - error: { label: 'CK 异常', color: 'red' }, - '': { label: '未检测', color: 'default' }, -}; - -const COLLAB_ACTION_LABELS: Record = { - 'douyu:collab:create': '新建协作单', - 'douyu:collab:update': '编辑订单资料', - 'douyu:collab:account': '更换账号', - 'douyu:collab:account_unlink': '解除账号关联', - 'douyu:collab:verify': '校验账号', - 'douyu:collab:status': '修改订单状态', - 'douyu:collab:status_auto': '自动推进订单状态', - 'douyu:collab:void': '作废订单', - 'douyu:collab:void_restore': '恢复作废订单', - 'douyu:collab:points_error': '标记积分异常', - 'douyu:collab:role_error': '标记角色异常', - 'douyu:collab:activity': '查询兑换记录', - 'douyu:collab:ck_export': '导出账号与登录凭据', - 'douyu:collab:archive': '归档订单', - 'douyu:collab:unarchive': '取消归档', - 'douyu:collab:sync_from_platform_fulfillment': '同步直播履约单', - 'douyu:collab:lease_acquired': '建立账号占用', - 'douyu:collab:lease_released': '释放账号占用', - 'douyu:collab:lease_takeover': '接管账号占用', - 'douyu:collab:goods_refresh': '刷新活动商品', - 'douyu:collab:shop_update': '修改店铺', - 'douyu:collab:shop_delete': '删除店铺', - 'douyu:collab:gift_update': '修改礼包', - 'douyu:collab:gift_delete': '删除礼包', -}; - -const COLLAB_DETAIL_LABELS: Record = { - order_no: '订单编号', - orderNo: '平台订单编号', - shop: '店铺', - owner_id: '负责人编号', - account_id: '内部账号编号', - accountId: '内部账号编号', - account_username: '斗鱼账号', - accountName: '账号名称', - account_uid: '斗鱼用户编号', - account_nickname: '账号昵称', - gift_name: '礼包', - commodity_id: '商品编号', - required_points: '所需积分', - requiredPoints: '所需积分', - home_images: '主页截图', - bind_game_role: '绑定角色', - role: '当前角色', - ck_status: '登录凭据状态', - ck: '登录凭据状态', - fish_fin_balance: '鱼翅', - points: '积分', - points_balance: '当前积分', - required_total: '同账号所需积分', - surplus: '积分结余', - message: '说明', - scope: '查询范围', - verdict: '查询判定', - records: '兑换记录', - records_matched: '命中记录', - records_total: '记录总数', - from: '原状态', - to: '新状态', - status: '状态', - rollback: '是否回退', - reason: '原因', - taskId: '履约任务编号', - created: '是否新建', - released_lease: '是否释放账号占用', - previous: '原账号信息', - lease_id: '账号占用编号', - purpose: '占用用途', - batch_id: '批次编号', - draft: '是否草稿', - exchangeStatus: '兑换资格', - softReasons: '后续处理', - eliteOpened: '精英宝典已开通', - limited: '是否达到限兑上限', - limitedCount: '限兑商品数量', -}; - -const COLLAB_DETAIL_VALUE_LABELS: Record = { - valid: '正常', - invalid: '异常', - error: '异常', - unverified: '未检测', - unknown: '无法判定', - success: '成功', - failed: '失败', - incomplete: '待补资料', - to_recharge: '待充值', - recharged: '已充值', - scripted: '已上脚本', - done: '抢购成功', - points_error: '积分异常', - role_error: '账号角色异常', - void: '已作废', - allocated: '已分配', - bound: '已绑定', - ready: '待分配', - manual_required: '已转人工', - eligible: '资格正常', - points_short: '积分不足', - not_opened: '精英宝典未开通', - activity: '兑换记录', - balances: '鱼翅与积分', - balance_manual: '人工查询鱼翅与积分', - balance_batch: '批量查询鱼翅与积分', - batch: '批量查询', - platform_fulfillment: '直播账号履约', - douyu_collab: '外部单协作', -}; - -const COLLAB_DETAIL_PREFERRED_KEYS = Object.keys(COLLAB_DETAIL_LABELS); - -function collabActionLabel(action: string): string { - return COLLAB_ACTION_LABELS[action] || '其他操作'; -} - -function collabCkLabel(status: string): string { - if (status === 'valid') return '正常'; - if (status === 'invalid' || status === 'error') return '异常'; - return '未检测'; -} - -function collabValueLabel(value: unknown): string { - if (typeof value === 'boolean') return value ? '是' : '否'; - if (value === null || value === undefined || value === '') return '-'; - if (typeof value === 'number') return String(value); - if (Array.isArray(value)) { - return value.map((item) => collabValueLabel(item)).filter((item) => item !== '-').join('、') || '-'; - } - if (typeof value === 'object') { - const row = value as Record; - if ('old' in row || 'new' in row) { - return `${collabValueLabel(row.old)} → ${collabValueLabel(row.new)}`; - } - return '-'; - } - const text = String(value); - return COLLAB_DETAIL_VALUE_LABELS[text] || collabText(text); -} - -function collabText(value: string): string { - return value - .replace(/\bCookie\b/gi, '登录凭据') - .replace(/\bCK\b/gi, '登录凭据') - .replace(/\s*act=[^,,;;\s]+/gi, '') - .trim(); -} - -function collabTimelineDetailLines(detail: string): string[] { - if (!detail) return []; - let parsed: unknown; - try { - parsed = JSON.parse(detail); - } catch { - return ['明细格式无法识别']; - } - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { - return [collabValueLabel(parsed)]; - } - const data = parsed as Record; - const lines: string[] = []; - for (const key of COLLAB_DETAIL_PREFERRED_KEYS) { - if (!(key in data)) continue; - const value = data[key]; - if (key === 'previous' && value && typeof value === 'object' && !Array.isArray(value)) { - const previous = value as Record; - const parts = [ - previous.account_username ? `账号 ${collabValueLabel(previous.account_username)}` : '', - previous.bind_game_role ? `角色 ${collabValueLabel(previous.bind_game_role)}` : '', - previous.status ? `状态 ${collabValueLabel(previous.status)}` : '', - ].filter(Boolean); - if (parts.length) lines.push(`${COLLAB_DETAIL_LABELS[key]}:${parts.join(';')}`); - continue; - } - if (key === 'ck_status' || key === 'ck') { - lines.push(`${COLLAB_DETAIL_LABELS[key]}:${collabCkLabel(String(value || ''))}`); - continue; - } - if (key === 'home_images') { - const count = Array.isArray(value) ? value.length : Number(value || 0); - lines.push(`${COLLAB_DETAIL_LABELS[key]}:${Number.isFinite(count) ? count : 0} 张`); - continue; - } - const text = collabValueLabel(value); - if (text !== '-') lines.push(`${COLLAB_DETAIL_LABELS[key]}:${text}`); - } - return lines; -} - -function formatTime(value?: string | null): string { - if (!value) return '-'; - const date = new Date(value); - return Number.isNaN(date.getTime()) ? value : date.toLocaleString(); -} - -function pointsReasonMeta(reason: string): { label: string; color: string } { - if (reason === 'shortage') return { label: '积分不足', color: 'red' }; - if (reason === 'excess') return { label: '积分超阈值', color: 'orange' }; - if (reason === 'ok') return { label: '积分正常', color: 'green' }; - return { label: '未核账', color: 'default' }; -} - -function goodsOptions(goods: DouyuCollabGoods[], accountSpecific = false) { - return goods - .filter((item) => item.commodity_id && item.name) - .map((item) => { - const time = item.is_limited ? ' · 23返场/限时' : ''; - const accountState = - accountSpecific && item.status === '1' - ? ' · 该账号已兑换' - : item.open_status === 0 - ? ' · 未开始' - : ''; - return { - value: item.commodity_id, - label: `${item.name} · ${item.score ?? '-'} 积分${time}${accountState}`, - goods: item, - disabled: accountSpecific && item.status === '1', - }; - }); -} - -interface OrderFormState { - order_no: string; - shop: string; - owner_id: number | null; - account_username: string; - gift_name: string; - commodity_id: string; - required_points: number | null; - home_images: string[]; - remark: string; -} - -const EMPTY_FORM: OrderFormState = { - order_no: '', - shop: '', - owner_id: null, - account_username: '', - gift_name: '', - commodity_id: '', - required_points: null, - home_images: [], - remark: '', -}; - -const SUCCESS_PURCHASE_FIELD_LABELS: Record = { - order_no: '订单编号', - account_username: '斗鱼用户名', - gift_name: '礼包', - commodity_id: '商品编号', - required_points: '所需积分', -}; - -interface SuccessfulPurchaseChange { - field: string; - label: string; - before: string; - after: string; -} - -function successfulPurchaseChanges( - order: DouyuCollabOrder, - form: OrderFormState, -): SuccessfulPurchaseChange[] { - const pairs: Array<[string, string | number | null, string | number | null]> = [ - ['order_no', order.order_no, form.order_no.trim()], - ['account_username', order.account_username, form.account_username.trim()], - ['gift_name', order.gift_name, form.gift_name.trim()], - ['commodity_id', order.commodity_id, form.commodity_id.trim()], - ['required_points', order.required_points, form.required_points], - ]; - return pairs - .filter(([, before, after]) => (before ?? '') !== (after ?? '')) - .map(([field, before, after]) => ({ - field, - label: SUCCESS_PURCHASE_FIELD_LABELS[field] || field, - before: before == null || before === '' ? '未填写' : String(before), - after: after == null || after === '' ? '未填写' : String(after), - })); -} - export default function DouyuCollabPage() { const navigate = useNavigate(); const [searchParams, setSearchParams] = useSearchParams(); diff --git a/web/frontend/src/pages/DouyuCollabPageConfig.ts b/web/frontend/src/pages/DouyuCollabPageConfig.ts new file mode 100644 index 0000000..9e7b030 --- /dev/null +++ b/web/frontend/src/pages/DouyuCollabPageConfig.ts @@ -0,0 +1,426 @@ +import type { + DouyuCollabGoods, + DouyuCollabOrder, + DouyuCollabStatus, +} from '../api/douyuCollab'; + +export function errorCodeOf(error: unknown): string { + return (error as { errorCode?: string } | null)?.errorCode || ''; +} + +export function hasTextInputFocus(): boolean { + const active = document.activeElement; + return ( + active instanceof HTMLElement && + (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable) + ); +} + +/** 实时同步暂停开关按浏览器记住:刷新页面后仍保持暂停,直到手动恢复。 */ +export const REALTIME_PAUSED_STORAGE_KEY = 'douyu.collab.realtime-paused'; +export const REALTIME_WS_PATH = '/api/douyu/external-orders/ws'; +export const COLUMN_LAYOUT_STORAGE_PREFIX = 'douyu.collab.columns'; + +export const DEFAULT_COLUMN_LAYOUT = [ + { key: 'sequence', visible: true }, + { key: 'order_shop', visible: true }, + { key: 'owner', visible: true }, + { key: 'account', visible: true }, + { key: 'bind_role', visible: true }, + { key: 'home_images', visible: true }, + { key: 'gift', visible: true }, + { key: 'status', visible: true }, + { key: 'balances', visible: true }, + { key: 'last_query', visible: true }, + { key: 'updated', visible: true }, + { key: 'actions', visible: true }, +] as const; + +export const COLUMN_LABELS: Record = { + sequence: '序号', + order_shop: '订单 / 店铺', + owner: '负责人', + account: '斗鱼账号', + bind_role: '绑定角色', + home_images: '主页截图', + gift: '礼包 / 积分', + status: '状态', + balances: '鱼翅 / 积分', + last_query: '最近查询', + updated: '最后改动', + actions: '操作', +}; + +export type ColumnPreference = { key: string; visible: boolean }; + +export function normalizeColumnLayout(raw: unknown): ColumnPreference[] { + const defaults = DEFAULT_COLUMN_LAYOUT.map((item) => ({ ...item })); + if (!Array.isArray(raw)) return defaults; + const known = new Set(defaults.map((item) => item.key)); + const result: ColumnPreference[] = []; + const seen = new Set(); + for (const item of raw) { + if (!item || typeof item !== 'object') continue; + const row = item as { key?: unknown; visible?: unknown }; + const key = String(row.key || ''); + if (!known.has(key) || seen.has(key)) continue; + seen.add(key); + result.push({ + key, + visible: key === 'actions' ? true : row.visible !== false, + }); + } + for (const item of defaults) { + if (!seen.has(item.key)) result.push(item); + } + return result; +} + +export function readColumnLayout(userId?: number): ColumnPreference[] { + if (!userId) return normalizeColumnLayout(null); + try { + const raw = window.localStorage.getItem( + `${COLUMN_LAYOUT_STORAGE_PREFIX}:${userId}`, + ); + return normalizeColumnLayout(raw ? JSON.parse(raw) : null); + } catch { + return normalizeColumnLayout(null); + } +} + +export function readRealtimePaused(): boolean { + try { + return window.localStorage.getItem(REALTIME_PAUSED_STORAGE_KEY) === '1'; + } catch { + return false; + } +} + +export function cardStyle(active: boolean) { + return { + borderColor: active ? '#1677ff' : undefined, + cursor: 'pointer', + } as const; +} + +export const STATUS_META: Record = { + incomplete: { label: '待补资料', color: 'default' }, + to_recharge: { label: '待充值', color: 'blue' }, + recharged: { label: '已充值', color: 'cyan' }, + scripted: { label: '已上脚本', color: 'purple' }, + done: { label: '抢购成功', color: 'green' }, + points_error: { label: '积分异常', color: 'orange' }, + role_error: { label: '账号角色异常', color: 'volcano' }, + failed: { label: '抢购失败', color: 'red' }, + void: { label: '已作废', color: 'default' }, +}; + +export const STATUS_ORDER: DouyuCollabStatus[] = [ + 'incomplete', + 'to_recharge', + 'recharged', + 'scripted', + 'done', + 'points_error', + 'role_error', + 'failed', + 'void', +]; + +export const FLOW_ORDER: DouyuCollabStatus[] = [ + 'incomplete', + 'to_recharge', + 'recharged', + 'scripted', + 'done', +]; + +export const CK_META: Record = { + unverified: { label: '未检测', color: 'default' }, + valid: { label: 'CK 正常', color: 'green' }, + invalid: { label: 'CK 异常', color: 'red' }, + error: { label: 'CK 异常', color: 'red' }, + '': { label: '未检测', color: 'default' }, +}; + +export const COLLAB_ACTION_LABELS: Record = { + 'douyu:collab:create': '新建协作单', + 'douyu:collab:update': '编辑订单资料', + 'douyu:collab:account': '更换账号', + 'douyu:collab:account_unlink': '解除账号关联', + 'douyu:collab:verify': '校验账号', + 'douyu:collab:status': '修改订单状态', + 'douyu:collab:status_auto': '自动推进订单状态', + 'douyu:collab:void': '作废订单', + 'douyu:collab:void_restore': '恢复作废订单', + 'douyu:collab:points_error': '标记积分异常', + 'douyu:collab:role_error': '标记角色异常', + 'douyu:collab:activity': '查询兑换记录', + 'douyu:collab:ck_export': '导出账号与登录凭据', + 'douyu:collab:archive': '归档订单', + 'douyu:collab:unarchive': '取消归档', + 'douyu:collab:sync_from_platform_fulfillment': '同步直播履约单', + 'douyu:collab:lease_acquired': '建立账号占用', + 'douyu:collab:lease_released': '释放账号占用', + 'douyu:collab:lease_takeover': '接管账号占用', + 'douyu:collab:goods_refresh': '刷新活动商品', + 'douyu:collab:shop_update': '修改店铺', + 'douyu:collab:shop_delete': '删除店铺', + 'douyu:collab:gift_update': '修改礼包', + 'douyu:collab:gift_delete': '删除礼包', +}; + +export const COLLAB_DETAIL_LABELS: Record = { + order_no: '订单编号', + orderNo: '平台订单编号', + shop: '店铺', + owner_id: '负责人编号', + account_id: '内部账号编号', + accountId: '内部账号编号', + account_username: '斗鱼账号', + accountName: '账号名称', + account_uid: '斗鱼用户编号', + account_nickname: '账号昵称', + gift_name: '礼包', + commodity_id: '商品编号', + required_points: '所需积分', + requiredPoints: '所需积分', + home_images: '主页截图', + bind_game_role: '绑定角色', + role: '当前角色', + ck_status: '登录凭据状态', + ck: '登录凭据状态', + fish_fin_balance: '鱼翅', + points: '积分', + points_balance: '当前积分', + required_total: '同账号所需积分', + surplus: '积分结余', + message: '说明', + scope: '查询范围', + verdict: '查询判定', + records: '兑换记录', + records_matched: '命中记录', + records_total: '记录总数', + from: '原状态', + to: '新状态', + status: '状态', + rollback: '是否回退', + reason: '原因', + taskId: '履约任务编号', + created: '是否新建', + released_lease: '是否释放账号占用', + previous: '原账号信息', + lease_id: '账号占用编号', + purpose: '占用用途', + batch_id: '批次编号', + draft: '是否草稿', + exchangeStatus: '兑换资格', + softReasons: '后续处理', + eliteOpened: '精英宝典已开通', + limited: '是否达到限兑上限', + limitedCount: '限兑商品数量', +}; + +export const COLLAB_DETAIL_VALUE_LABELS: Record = { + valid: '正常', + invalid: '异常', + error: '异常', + unverified: '未检测', + unknown: '无法判定', + success: '成功', + failed: '失败', + incomplete: '待补资料', + to_recharge: '待充值', + recharged: '已充值', + scripted: '已上脚本', + done: '抢购成功', + points_error: '积分异常', + role_error: '账号角色异常', + void: '已作废', + allocated: '已分配', + bound: '已绑定', + ready: '待分配', + manual_required: '已转人工', + eligible: '资格正常', + points_short: '积分不足', + not_opened: '精英宝典未开通', + activity: '兑换记录', + balances: '鱼翅与积分', + balance_manual: '人工查询鱼翅与积分', + balance_batch: '批量查询鱼翅与积分', + batch: '批量查询', + platform_fulfillment: '直播账号履约', + douyu_collab: '外部单协作', +}; + +export const COLLAB_DETAIL_PREFERRED_KEYS = Object.keys(COLLAB_DETAIL_LABELS); + +export function collabActionLabel(action: string): string { + return COLLAB_ACTION_LABELS[action] || '其他操作'; +} + +export function collabCkLabel(status: string): string { + if (status === 'valid') return '正常'; + if (status === 'invalid' || status === 'error') return '异常'; + return '未检测'; +} + +export function collabValueLabel(value: unknown): string { + if (typeof value === 'boolean') return value ? '是' : '否'; + if (value === null || value === undefined || value === '') return '-'; + if (typeof value === 'number') return String(value); + if (Array.isArray(value)) { + return value.map((item) => collabValueLabel(item)).filter((item) => item !== '-').join('、') || '-'; + } + if (typeof value === 'object') { + const row = value as Record; + if ('old' in row || 'new' in row) { + return `${collabValueLabel(row.old)} → ${collabValueLabel(row.new)}`; + } + return '-'; + } + const text = String(value); + return COLLAB_DETAIL_VALUE_LABELS[text] || collabText(text); +} + +export function collabText(value: string): string { + return value + .replace(/\bCookie\b/gi, '登录凭据') + .replace(/\bCK\b/gi, '登录凭据') + .replace(/\s*act=[^,,;;\s]+/gi, '') + .trim(); +} + +export function collabTimelineDetailLines(detail: string): string[] { + if (!detail) return []; + let parsed: unknown; + try { + parsed = JSON.parse(detail); + } catch { + return ['明细格式无法识别']; + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return [collabValueLabel(parsed)]; + } + const data = parsed as Record; + const lines: string[] = []; + for (const key of COLLAB_DETAIL_PREFERRED_KEYS) { + if (!(key in data)) continue; + const value = data[key]; + if (key === 'previous' && value && typeof value === 'object' && !Array.isArray(value)) { + const previous = value as Record; + const parts = [ + previous.account_username ? `账号 ${collabValueLabel(previous.account_username)}` : '', + previous.bind_game_role ? `角色 ${collabValueLabel(previous.bind_game_role)}` : '', + previous.status ? `状态 ${collabValueLabel(previous.status)}` : '', + ].filter(Boolean); + if (parts.length) lines.push(`${COLLAB_DETAIL_LABELS[key]}:${parts.join(';')}`); + continue; + } + if (key === 'ck_status' || key === 'ck') { + lines.push(`${COLLAB_DETAIL_LABELS[key]}:${collabCkLabel(String(value || ''))}`); + continue; + } + if (key === 'home_images') { + const count = Array.isArray(value) ? value.length : Number(value || 0); + lines.push(`${COLLAB_DETAIL_LABELS[key]}:${Number.isFinite(count) ? count : 0} 张`); + continue; + } + const text = collabValueLabel(value); + if (text !== '-') lines.push(`${COLLAB_DETAIL_LABELS[key]}:${text}`); + } + return lines; +} + +export function formatTime(value?: string | null): string { + if (!value) return '-'; + const date = new Date(value); + return Number.isNaN(date.getTime()) ? value : date.toLocaleString(); +} + +export function pointsReasonMeta(reason: string): { label: string; color: string } { + if (reason === 'shortage') return { label: '积分不足', color: 'red' }; + if (reason === 'excess') return { label: '积分超阈值', color: 'orange' }; + if (reason === 'ok') return { label: '积分正常', color: 'green' }; + return { label: '未核账', color: 'default' }; +} + +export function goodsOptions(goods: DouyuCollabGoods[], accountSpecific = false) { + return goods + .filter((item) => item.commodity_id && item.name) + .map((item) => { + const time = item.is_limited ? ' · 23返场/限时' : ''; + const accountState = + accountSpecific && item.status === '1' + ? ' · 该账号已兑换' + : item.open_status === 0 + ? ' · 未开始' + : ''; + return { + value: item.commodity_id, + label: `${item.name} · ${item.score ?? '-'} 积分${time}${accountState}`, + goods: item, + disabled: accountSpecific && item.status === '1', + }; + }); +} + +export interface OrderFormState { + order_no: string; + shop: string; + owner_id: number | null; + account_username: string; + gift_name: string; + commodity_id: string; + required_points: number | null; + home_images: string[]; + remark: string; +} + +export const EMPTY_FORM: OrderFormState = { + order_no: '', + shop: '', + owner_id: null, + account_username: '', + gift_name: '', + commodity_id: '', + required_points: null, + home_images: [], + remark: '', +}; + +export const SUCCESS_PURCHASE_FIELD_LABELS: Record = { + order_no: '订单编号', + account_username: '斗鱼用户名', + gift_name: '礼包', + commodity_id: '商品编号', + required_points: '所需积分', +}; + +export interface SuccessfulPurchaseChange { + field: string; + label: string; + before: string; + after: string; +} + +export function successfulPurchaseChanges( + order: DouyuCollabOrder, + form: OrderFormState, +): SuccessfulPurchaseChange[] { + const pairs: Array<[string, string | number | null, string | number | null]> = [ + ['order_no', order.order_no, form.order_no.trim()], + ['account_username', order.account_username, form.account_username.trim()], + ['gift_name', order.gift_name, form.gift_name.trim()], + ['commodity_id', order.commodity_id, form.commodity_id.trim()], + ['required_points', order.required_points, form.required_points], + ]; + return pairs + .filter(([, before, after]) => (before ?? '') !== (after ?? '')) + .map(([field, before, after]) => ({ + field, + label: SUCCESS_PURCHASE_FIELD_LABELS[field] || field, + before: before == null || before === '' ? '未填写' : String(before), + after: after == null || after === '' ? '未填写' : String(after), + })); +} diff --git a/web/frontend/src/pages/HuyaCollabPage.tsx b/web/frontend/src/pages/HuyaCollabPage.tsx index 544b4ca..42356e8 100644 --- a/web/frontend/src/pages/HuyaCollabPage.tsx +++ b/web/frontend/src/pages/HuyaCollabPage.tsx @@ -50,326 +50,42 @@ import { getErrorMessage } from '../utils/error'; import { copyTextToClipboard } from '../utils/clipboard'; import { usePermissions } from '../hooks/usePermissions'; import { useCollabRealtime, type CollabRealtimeEvent } from '../hooks/useCollabRealtime'; +import { + ACTION_LABELS, + CK_META, + COLLAB_SORT_KEYS, + FLOW_STATUS_OPTIONS, + IMPORT_PREVIEW_ROWS, + MAX_IMAGES_PER_SLOT, + RECHARGE_THRESHOLD_KEY, + REALTIME_PAUSED_STORAGE_KEY, + SLOT_META, + STATUS_META, + STATUS_ORDER_OPTIONS, + VERDICT_META, + clearCreateDraft, + clearSupplementDraft, + createDraftKey, + draftHintShown, + formatTime, + hasDraftContent, + hasTextInputFocus, + markDraftHintShown, + readCreateDraft, + readGiftCache, + readRealtimePaused, + readRechargeThreshold, + readSupplementDraft, + supplementDraftKey, + writeGiftCache, + type CollabSortKey, + type CollabSortOrder, + type SupplementDraft, + type SupplementFormValues, +} from './HuyaCollabPageConfig'; const { Text, Paragraph } = Typography; -function hasTextInputFocus(): boolean { - const active = document.activeElement; - return ( - active instanceof HTMLElement && - (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable) - ); -} - -/** 实时同步暂停开关按浏览器记住:刷新页面后仍保持暂停,直到用户手动恢复。 */ -const REALTIME_PAUSED_STORAGE_KEY = 'huya.collab.realtime-paused'; - -function readRealtimePaused(): boolean { - try { - return window.localStorage.getItem(REALTIME_PAUSED_STORAGE_KEY) === '1'; - } catch { - return false; - } -} - -const STATUS_META: Record = { - // 只登记了订单号 + 店铺,客户资料(CK / 礼包 / 主页截图)到了再补 - incomplete: { label: '待补资料', color: 'gold' }, - // 资料齐全且 CK 有效;等充值 - to_recharge: { label: '待充值', color: 'orange' }, - recharged: { label: '已充值', color: 'geekblue' }, - scripted: { label: '已上脚本', color: 'purple' }, - // 抢购成功(枚举值仍是 done):从「已上脚本」查到兑换记录 → 自动进这一步 - done: { label: '抢购成功', color: 'success' }, - // 充值完成但积分不足/超出阈值 - points_error: { label: '积分异常', color: 'volcano' }, - // 旁路终态:抢购后查兑换记录没查到这一单的礼包(枚举值仍是 failed) - failed: { label: '抢购失败', color: 'red' }, - void: { label: '已作废', color: 'error' }, -}; - -/** 判定结论的配色(生命周期时间线用):与「业务状态名」分开,这里说的是"兑换记录里查到没有" */ -const VERDICT_META: Record = { - success: { label: '兑换成功', color: 'success' }, - failed: { label: '兑换失败', color: 'error' }, - unknown: { label: '无法判定', color: 'default' }, -}; - -/** 「改状态」能选的目标(顺序 = 业务流程顺序,回退要显式勾选) - * 「待补资料」只作为新建起点,不放进「改状态」:它只能通过「回退状态」进入。 */ -const STATUS_ORDER_OPTIONS: { value: HuyaCollabStatus; label: string }[] = [ - { value: 'to_recharge', label: '待充值' }, - { value: 'recharged', label: '已充值(核账)' }, - { value: 'scripted', label: '已上脚本' }, - { value: 'done', label: '抢购成功' }, - { value: 'failed', label: '抢购失败' }, - { value: 'void', label: '已作废' }, -]; - -/** 「回退」能选的目标:流程链(含「待补资料」;要进「已作废 / 抢购失败」走「改状态」或「作废」入口) */ -const FLOW_STATUS_OPTIONS: { value: HuyaCollabStatus; label: string }[] = [ - { value: 'incomplete', label: '待补资料' }, - { value: 'to_recharge', label: '待充值' }, - { value: 'recharged', label: '已充值(核账)' }, - { value: 'scripted', label: '已上脚本' }, - { value: 'done', label: '抢购成功' }, -]; - -const CK_META: Record = { - unverified: { label: '未验证', color: 'default' }, - valid: { label: '有效', color: 'success' }, - invalid: { label: '已失效', color: 'error' }, - disabled: { label: '已停用', color: 'warning' }, -}; - -/** 表头排序字段(后端白名单):seq = 固定创建序号;点击一次正序,再点一次反序。 */ -type CollabSortKey = - | 'seq' - | 'order_no' - | 'shop' - | 'owner' - | 'bind' - | 'gift_name' - | 'status' - | 'uid' - | 'ck_status' - | 'updated_at'; -type CollabSortOrder = 'ascend' | 'descend'; -const COLLAB_SORT_KEYS: ReadonlySet = new Set([ - 'seq', - 'order_no', - 'shop', - 'owner', - 'bind', - 'gift_name', - 'status', - 'uid', - 'ck_status', - 'updated_at', -]); - -const ACTION_LABELS: Record = { - 'huya:collab:create': '新建', - 'huya:collab:update': '编辑', - 'huya:collab:status': '状态变更', - 'huya:collab:ck': 'CK 变更', - 'huya:collab:ck_status': 'CK 验证', - 'huya:collab:probe_snapshot': '绑定快照刷新', - 'huya:collab:recharge_invalidate': '核账快照失效', - 'huya:collab:image': '图片变更', - 'huya:collab:delete': '删除', -}; - -const SLOT_META: Record = { - // 绑定图不再人工上传:绑定关系由探针自动读(2026-10-16 用户拍板),只留老数据只读展示 - bind_images: { label: '历史绑定图', keysKey: 'bind_images' }, - home_images: { label: '主页截图', keysKey: 'home_images' }, -}; - -const IMPORT_PREVIEW_ROWS = 20; -// 「礼包列表」的本地缓存键:一个活动期间就那一批礼包,没必要每贴一份 CK 都去虎牙拉一次; -// v3 = 2026-11-11 起自动合并积分中心全部页签,换键避免继续用只含「精英专享」的旧缓存。 -const GIFTS_CACHE_KEY = 'huya.collab.gifts.v3'; -const RECHARGE_THRESHOLD_KEY = 'huya.collab.rechargeThreshold'; -const RECHARGE_THRESHOLD_DEFAULT = 100; - -function readRechargeThreshold(): number { - try { - const raw = window.localStorage.getItem(RECHARGE_THRESHOLD_KEY); - if (raw === null || raw === '') return RECHARGE_THRESHOLD_DEFAULT; - const value = Number(raw); - return Number.isFinite(value) && value >= 0 ? value : RECHARGE_THRESHOLD_DEFAULT; - } catch { - return RECHARGE_THRESHOLD_DEFAULT; - } -} -const MAX_IMAGES_PER_SLOT = 20; - -/** 读礼包缓存(读不到 / 解析坏 / 空列表都当没缓存) */ -function readGiftCache(): { gifts: HuyaCollabGift[]; at: number } | null { - try { - const raw = window.localStorage.getItem(GIFTS_CACHE_KEY); - if (!raw) return null; - const parsed = JSON.parse(raw) as { at?: number; gifts?: HuyaCollabGift[] }; - const gifts = Array.isArray(parsed.gifts) ? parsed.gifts : []; - if (gifts.length === 0) return null; - return { gifts, at: Number(parsed.at) || 0 }; - } catch { - return null; - } -} - -/** 写礼包缓存:写不进去(隐私模式 / 配额满)也不影响功能,静静跳过 */ -function writeGiftCache(gifts: HuyaCollabGift[]): void { - try { - window.localStorage.setItem(GIFTS_CACHE_KEY, JSON.stringify({ at: Date.now(), gifts })); - } catch { - // 忽略:缓存只是体验优化 - } -} - -// 「新建协作单」草稿:填一半关掉 / 刷新页面后再打开不能清空(2026-10-17 用户需求)。 -// 按登录用户分键,避免同一台电脑换账号后看到上一个人的 CK。 -const CREATE_DRAFT_KEY_PREFIX = 'huya.collab.createDraft'; -// 「只填订单号 + 店铺直接建单」的首次提示只弹一次(按浏览器记,不再打扰) -const CREATE_DRAFT_HINT_KEY = 'huya.collab.draftHintShown'; - -interface CreateDraft { - order_no: string; - shop: string; - ck_text: string; - gift_name: string; - required_points: number | null; - remark: string; - home_images: string[]; - saved_at: number; -} - -function createDraftKey(userId?: number | null): string { - return userId ? `${CREATE_DRAFT_KEY_PREFIX}.${userId}` : ''; -} - -/** 读草稿(读不到 / 解析坏都当没有) */ -function readCreateDraft(userId?: number | null): CreateDraft | null { - const key = createDraftKey(userId); - if (!key) return null; - try { - const raw = window.localStorage.getItem(key); - if (!raw) return null; - const parsed = JSON.parse(raw) as Partial; - const savedAt = Number(parsed.saved_at) || 0; - // 草稿只留 7 天:里面可能有一份 CK,不能无限期躺在浏览器里 - if (!savedAt || Date.now() - savedAt > 7 * 24 * 60 * 60 * 1000) { - window.localStorage.removeItem(key); - return null; - } - return { - order_no: typeof parsed.order_no === 'string' ? parsed.order_no : '', - shop: typeof parsed.shop === 'string' ? parsed.shop : '', - ck_text: typeof parsed.ck_text === 'string' ? parsed.ck_text : '', - gift_name: typeof parsed.gift_name === 'string' ? parsed.gift_name : '', - required_points: typeof parsed.required_points === 'number' ? parsed.required_points : null, - remark: typeof parsed.remark === 'string' ? parsed.remark : '', - home_images: Array.isArray(parsed.home_images) - ? parsed.home_images.filter((item): item is string => typeof item === 'string') - : [], - saved_at: Number(parsed.saved_at) || 0, - }; - } catch { - return null; - } -} - -function clearCreateDraft(userId?: number | null): void { - const key = createDraftKey(userId); - if (!key) return; - try { - window.localStorage.removeItem(key); - } catch { - // 忽略:清不掉也不影响当前表单 - } -} - -/** 「资料没填全时直接建单 → 待补资料」的首次提示是否已经展示过 */ -function draftHintShown(): boolean { - try { - return window.localStorage.getItem(CREATE_DRAFT_HINT_KEY) === '1'; - } catch { - return true; // 存不了就不要再反复弹 - } -} - -function markDraftHintShown(): void { - try { - window.localStorage.setItem(CREATE_DRAFT_HINT_KEY, '1'); - } catch { - // 忽略:提示只是体验 - } -} - -function hasDraftContent(draft: Omit): boolean { - // 礼包名不算「填过东西」:它现在默认空白、也不从草稿恢复(见下面 createForm 那段的说明), - // 否则一份「只被上次自动填了礼包」的老草稿会一直弹「已恢复上次未提交的草稿」。 - return Boolean( - draft.order_no.trim() - || draft.shop.trim() - || draft.ck_text.trim() - || draft.remark.trim() - || draft.home_images.length, - ); -} - -// 「补资料」草稿:按登录用户 + 订单 id 分开存。填一半关掉 / 刷新后, -// 再点这一行的「补资料」会原样恢复(含刚贴的 CK 和刚上传的截图 key)。 -const SUPPLEMENT_DRAFT_KEY_PREFIX = 'huya.collab.supplementDraft'; - -interface SupplementDraft { - shop: string; - ck_text: string; - gift_name: string; - required_points: number | null; - remark: string; - home_images: string[]; - saved_at: number; -} - -interface SupplementFormValues { - shop: string; - ck_text?: string; - gift_name?: string; - required_points?: number | null; - remark?: string; - home_images?: string[]; -} - -function supplementDraftKey(userId?: number | null, orderId?: number): string { - return userId && orderId ? `${SUPPLEMENT_DRAFT_KEY_PREFIX}.${userId}.${orderId}` : ''; -} - -function readSupplementDraft(userId: number | null | undefined, orderId: number): SupplementDraft | null { - const key = supplementDraftKey(userId, orderId); - if (!key) return null; - try { - const raw = window.localStorage.getItem(key); - if (!raw) return null; - const parsed = JSON.parse(raw) as Partial; - const savedAt = Number(parsed.saved_at) || 0; - if (!savedAt || Date.now() - savedAt > 7 * 24 * 60 * 60 * 1000) { - window.localStorage.removeItem(key); - return null; - } - return { - shop: typeof parsed.shop === 'string' ? parsed.shop : '', - ck_text: typeof parsed.ck_text === 'string' ? parsed.ck_text : '', - gift_name: typeof parsed.gift_name === 'string' ? parsed.gift_name : '', - required_points: typeof parsed.required_points === 'number' ? parsed.required_points : null, - remark: typeof parsed.remark === 'string' ? parsed.remark : '', - home_images: Array.isArray(parsed.home_images) - ? parsed.home_images.filter((item): item is string => typeof item === 'string') - : [], - saved_at: savedAt, - }; - } catch { - return null; - } -} - -function clearSupplementDraft(userId: number | null | undefined, orderId: number): void { - const key = supplementDraftKey(userId, orderId); - if (!key) return; - try { - window.localStorage.removeItem(key); - } catch { - // 忽略:清不掉也不影响当前表单 - } -} - -function formatTime(value: string | null | undefined): string { - if (!value) return '-'; - const time = new Date(value); - return Number.isNaN(time.getTime()) ? String(value) : time.toLocaleString(); -} - /** 点开即改、失焦提交(回车=失焦提交,Esc=放弃) */ function EditableText({ value, disabled, placeholder, onCommit, diff --git a/web/frontend/src/pages/HuyaCollabPageConfig.ts b/web/frontend/src/pages/HuyaCollabPageConfig.ts new file mode 100644 index 0000000..a566a4b --- /dev/null +++ b/web/frontend/src/pages/HuyaCollabPageConfig.ts @@ -0,0 +1,322 @@ +import type { + HuyaCollabGift, + HuyaCollabImageSlot, + HuyaCollabStatus, +} from '../api/modules'; + +export function hasTextInputFocus(): boolean { + const active = document.activeElement; + return ( + active instanceof HTMLElement && + (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable) + ); +} + +/** 实时同步暂停开关按浏览器记住:刷新页面后仍保持暂停,直到用户手动恢复。 */ +export const REALTIME_PAUSED_STORAGE_KEY = 'huya.collab.realtime-paused'; + +export function readRealtimePaused(): boolean { + try { + return window.localStorage.getItem(REALTIME_PAUSED_STORAGE_KEY) === '1'; + } catch { + return false; + } +} + +export const STATUS_META: Record = { + // 只登记了订单号 + 店铺,客户资料(CK / 礼包 / 主页截图)到了再补 + incomplete: { label: '待补资料', color: 'gold' }, + // 资料齐全且 CK 有效;等充值 + to_recharge: { label: '待充值', color: 'orange' }, + recharged: { label: '已充值', color: 'geekblue' }, + scripted: { label: '已上脚本', color: 'purple' }, + // 抢购成功(枚举值仍是 done):从「已上脚本」查到兑换记录 → 自动进这一步 + done: { label: '抢购成功', color: 'success' }, + // 充值完成但积分不足/超出阈值 + points_error: { label: '积分异常', color: 'volcano' }, + // 旁路终态:抢购后查兑换记录没查到这一单的礼包(枚举值仍是 failed) + failed: { label: '抢购失败', color: 'red' }, + void: { label: '已作废', color: 'error' }, +}; + +/** 判定结论的配色(生命周期时间线用):与「业务状态名」分开,这里说的是"兑换记录里查到没有" */ +export const VERDICT_META: Record = { + success: { label: '兑换成功', color: 'success' }, + failed: { label: '兑换失败', color: 'error' }, + unknown: { label: '无法判定', color: 'default' }, +}; + +/** 「改状态」能选的目标(顺序 = 业务流程顺序,回退要显式勾选) + * 「待补资料」只作为新建起点,不放进「改状态」:它只能通过「回退状态」进入。 */ +export const STATUS_ORDER_OPTIONS: { value: HuyaCollabStatus; label: string }[] = [ + { value: 'to_recharge', label: '待充值' }, + { value: 'recharged', label: '已充值(核账)' }, + { value: 'scripted', label: '已上脚本' }, + { value: 'done', label: '抢购成功' }, + { value: 'failed', label: '抢购失败' }, + { value: 'void', label: '已作废' }, +]; + +/** 「回退」能选的目标:流程链(含「待补资料」;要进「已作废 / 抢购失败」走「改状态」或「作废」入口) */ +export const FLOW_STATUS_OPTIONS: { value: HuyaCollabStatus; label: string }[] = [ + { value: 'incomplete', label: '待补资料' }, + { value: 'to_recharge', label: '待充值' }, + { value: 'recharged', label: '已充值(核账)' }, + { value: 'scripted', label: '已上脚本' }, + { value: 'done', label: '抢购成功' }, +]; + +export const CK_META: Record = { + unverified: { label: '未验证', color: 'default' }, + valid: { label: '有效', color: 'success' }, + invalid: { label: '已失效', color: 'error' }, + disabled: { label: '已停用', color: 'warning' }, +}; + +/** 表头排序字段(后端白名单):seq = 固定创建序号;点击一次正序,再点一次反序。 */ +export type CollabSortKey = + | 'seq' + | 'order_no' + | 'shop' + | 'owner' + | 'bind' + | 'gift_name' + | 'status' + | 'uid' + | 'ck_status' + | 'updated_at'; +export type CollabSortOrder = 'ascend' | 'descend'; +export const COLLAB_SORT_KEYS: ReadonlySet = new Set([ + 'seq', + 'order_no', + 'shop', + 'owner', + 'bind', + 'gift_name', + 'status', + 'uid', + 'ck_status', + 'updated_at', +]); + +export const ACTION_LABELS: Record = { + 'huya:collab:create': '新建', + 'huya:collab:update': '编辑', + 'huya:collab:status': '状态变更', + 'huya:collab:ck': 'CK 变更', + 'huya:collab:ck_status': 'CK 验证', + 'huya:collab:probe_snapshot': '绑定快照刷新', + 'huya:collab:recharge_invalidate': '核账快照失效', + 'huya:collab:image': '图片变更', + 'huya:collab:delete': '删除', +}; + +export const SLOT_META: Record = { + // 绑定图不再人工上传:绑定关系由探针自动读(2026-10-16 用户拍板),只留老数据只读展示 + bind_images: { label: '历史绑定图', keysKey: 'bind_images' }, + home_images: { label: '主页截图', keysKey: 'home_images' }, +}; + +export const IMPORT_PREVIEW_ROWS = 20; +// 「礼包列表」的本地缓存键:一个活动期间就那一批礼包,没必要每贴一份 CK 都去虎牙拉一次; +// v3 = 2026-11-11 起自动合并积分中心全部页签,换键避免继续用只含「精英专享」的旧缓存。 +export const GIFTS_CACHE_KEY = 'huya.collab.gifts.v3'; +export const RECHARGE_THRESHOLD_KEY = 'huya.collab.rechargeThreshold'; +export const RECHARGE_THRESHOLD_DEFAULT = 100; + +export function readRechargeThreshold(): number { + try { + const raw = window.localStorage.getItem(RECHARGE_THRESHOLD_KEY); + if (raw === null || raw === '') return RECHARGE_THRESHOLD_DEFAULT; + const value = Number(raw); + return Number.isFinite(value) && value >= 0 ? value : RECHARGE_THRESHOLD_DEFAULT; + } catch { + return RECHARGE_THRESHOLD_DEFAULT; + } +} +export const MAX_IMAGES_PER_SLOT = 20; + +/** 读礼包缓存(读不到 / 解析坏 / 空列表都当没缓存) */ +export function readGiftCache(): { gifts: HuyaCollabGift[]; at: number } | null { + try { + const raw = window.localStorage.getItem(GIFTS_CACHE_KEY); + if (!raw) return null; + const parsed = JSON.parse(raw) as { at?: number; gifts?: HuyaCollabGift[] }; + const gifts = Array.isArray(parsed.gifts) ? parsed.gifts : []; + if (gifts.length === 0) return null; + return { gifts, at: Number(parsed.at) || 0 }; + } catch { + return null; + } +} + +/** 写礼包缓存:写不进去(隐私模式 / 配额满)也不影响功能,静静跳过 */ +export function writeGiftCache(gifts: HuyaCollabGift[]): void { + try { + window.localStorage.setItem(GIFTS_CACHE_KEY, JSON.stringify({ at: Date.now(), gifts })); + } catch { + // 忽略:缓存只是体验优化 + } +} + +// 「新建协作单」草稿:填一半关掉 / 刷新页面后再打开不能清空(2026-10-17 用户需求)。 +// 按登录用户分键,避免同一台电脑换账号后看到上一个人的 CK。 +export const CREATE_DRAFT_KEY_PREFIX = 'huya.collab.createDraft'; +// 「只填订单号 + 店铺直接建单」的首次提示只弹一次(按浏览器记,不再打扰) +export const CREATE_DRAFT_HINT_KEY = 'huya.collab.draftHintShown'; + +export interface CreateDraft { + order_no: string; + shop: string; + ck_text: string; + gift_name: string; + required_points: number | null; + remark: string; + home_images: string[]; + saved_at: number; +} + +export function createDraftKey(userId?: number | null): string { + return userId ? `${CREATE_DRAFT_KEY_PREFIX}.${userId}` : ''; +} + +/** 读草稿(读不到 / 解析坏都当没有) */ +export function readCreateDraft(userId?: number | null): CreateDraft | null { + const key = createDraftKey(userId); + if (!key) return null; + try { + const raw = window.localStorage.getItem(key); + if (!raw) return null; + const parsed = JSON.parse(raw) as Partial; + const savedAt = Number(parsed.saved_at) || 0; + // 草稿只留 7 天:里面可能有一份 CK,不能无限期躺在浏览器里 + if (!savedAt || Date.now() - savedAt > 7 * 24 * 60 * 60 * 1000) { + window.localStorage.removeItem(key); + return null; + } + return { + order_no: typeof parsed.order_no === 'string' ? parsed.order_no : '', + shop: typeof parsed.shop === 'string' ? parsed.shop : '', + ck_text: typeof parsed.ck_text === 'string' ? parsed.ck_text : '', + gift_name: typeof parsed.gift_name === 'string' ? parsed.gift_name : '', + required_points: typeof parsed.required_points === 'number' ? parsed.required_points : null, + remark: typeof parsed.remark === 'string' ? parsed.remark : '', + home_images: Array.isArray(parsed.home_images) + ? parsed.home_images.filter((item): item is string => typeof item === 'string') + : [], + saved_at: Number(parsed.saved_at) || 0, + }; + } catch { + return null; + } +} + +export function clearCreateDraft(userId?: number | null): void { + const key = createDraftKey(userId); + if (!key) return; + try { + window.localStorage.removeItem(key); + } catch { + // 忽略:清不掉也不影响当前表单 + } +} + +/** 「资料没填全时直接建单 → 待补资料」的首次提示是否已经展示过 */ +export function draftHintShown(): boolean { + try { + return window.localStorage.getItem(CREATE_DRAFT_HINT_KEY) === '1'; + } catch { + return true; // 存不了就不要再反复弹 + } +} + +export function markDraftHintShown(): void { + try { + window.localStorage.setItem(CREATE_DRAFT_HINT_KEY, '1'); + } catch { + // 忽略:提示只是体验 + } +} + +export function hasDraftContent(draft: Omit): boolean { + // 礼包名不算「填过东西」:它现在默认空白、也不从草稿恢复(见下面 createForm 那段的说明), + // 否则一份「只被上次自动填了礼包」的老草稿会一直弹「已恢复上次未提交的草稿」。 + return Boolean( + draft.order_no.trim() + || draft.shop.trim() + || draft.ck_text.trim() + || draft.remark.trim() + || draft.home_images.length, + ); +} + +// 「补资料」草稿:按登录用户 + 订单 id 分开存。填一半关掉 / 刷新后, +// 再点这一行的「补资料」会原样恢复(含刚贴的 CK 和刚上传的截图 key)。 +export const SUPPLEMENT_DRAFT_KEY_PREFIX = 'huya.collab.supplementDraft'; + +export interface SupplementDraft { + shop: string; + ck_text: string; + gift_name: string; + required_points: number | null; + remark: string; + home_images: string[]; + saved_at: number; +} + +export interface SupplementFormValues { + shop: string; + ck_text?: string; + gift_name?: string; + required_points?: number | null; + remark?: string; + home_images?: string[]; +} + +export function supplementDraftKey(userId?: number | null, orderId?: number): string { + return userId && orderId ? `${SUPPLEMENT_DRAFT_KEY_PREFIX}.${userId}.${orderId}` : ''; +} + +export function readSupplementDraft(userId: number | null | undefined, orderId: number): SupplementDraft | null { + const key = supplementDraftKey(userId, orderId); + if (!key) return null; + try { + const raw = window.localStorage.getItem(key); + if (!raw) return null; + const parsed = JSON.parse(raw) as Partial; + const savedAt = Number(parsed.saved_at) || 0; + if (!savedAt || Date.now() - savedAt > 7 * 24 * 60 * 60 * 1000) { + window.localStorage.removeItem(key); + return null; + } + return { + shop: typeof parsed.shop === 'string' ? parsed.shop : '', + ck_text: typeof parsed.ck_text === 'string' ? parsed.ck_text : '', + gift_name: typeof parsed.gift_name === 'string' ? parsed.gift_name : '', + required_points: typeof parsed.required_points === 'number' ? parsed.required_points : null, + remark: typeof parsed.remark === 'string' ? parsed.remark : '', + home_images: Array.isArray(parsed.home_images) + ? parsed.home_images.filter((item): item is string => typeof item === 'string') + : [], + saved_at: savedAt, + }; + } catch { + return null; + } +} + +export function clearSupplementDraft(userId: number | null | undefined, orderId: number): void { + const key = supplementDraftKey(userId, orderId); + if (!key) return; + try { + window.localStorage.removeItem(key); + } catch { + // 忽略:清不掉也不影响当前表单 + } +} + +export function formatTime(value: string | null | undefined): string { + if (!value) return '-'; + const time = new Date(value); + return Number.isNaN(time.getTime()) ? String(value) : time.toLocaleString(); +}