协作台账:新表 huya_external_orders 替代 Excel 多人协同表(设计见
docs/设计-虎牙外部CK协作台账.md),一条 CK 一行,所有人共享、改动留痕。
- 前端 pages/HuyaCollabPage.tsx + 菜单「虎牙 → 外部单协作」/huya/collab:
内联编辑(带乐观锁 version)、图片缩略图、详情抽屉(字段表单 + 两个图片槽位 +
操作时间线)、粘贴导入弹窗(带 TSV 预览)、批量/单条验证 CK、页头统计条、筛选
- 两套状态机:业务 pending→bound→recharged→scripted→done(旁路 void)、
凭据 unverified/valid/invalid/disabled;唯一写入口在 services/huya_collab_service.py,
字段级审计 + 整数 version 乐观锁(不用 updated_at:DATETIME 只到秒)
- CK 只读探针 check_user_bind_game_account(真机判据:响应非 None 且 status == 200),
成功即覆盖写绑定快照 bind_game_account/bind_game_role/bind_game_channel(迁移 0056),
失败只改凭据状态、不动业务状态;人工只能停用/恢复(POST /{id}/ck/status)
- 贴/换/重建 CK、TSV 批量导入(SAVEPOINT 单行隔离,部分失败不整体失败)、
权限 huya:collab:view/edit/manage(删除只给运营)
- 孤儿图清理脚本 scripts/cleanup_orphan_file_assets.py(默认 --dry-run)
图片上传(协作台账截图用):OSS/本地双后端 + 缩略图变体 + /api/files 代理回读,
权限 file:upload / file:view。
验证:pytest 880 passed / 6 skipped;ruff format 全绿、ruff check 仅剩既有告警;
前端 tsc -b / eslint / vite build 通过;接口端到端冒烟 29 项全绿(TestClient,探针用假客户端);
探针真机冒烟 3 例(有效 CK=True、别人 uid=False、裸 cookie=False)。
1513 lines
51 KiB
Python
1513 lines
51 KiB
Python
"""虎牙外部 CK 协作台账的服务层(模型:``models.HuyaExternalOrder``)。
|
||
|
||
设计见 ``docs/设计-虎牙外部CK协作台账.md``。改这里之前先读文档 §2.3 与 §10.2,
|
||
两条边界不是 bug:
|
||
|
||
1. **不写 ``huya_accounts``、不做外键**:CK 独立存本表;
|
||
2. **不 import 任何任务执行器**(``huya_runner*`` / ``huya_tasks``):
|
||
绑定/充值/上脚本都在别的工具里做,本表只记录结果。
|
||
S5 的探针只 import ``core.huya.http_client``(只读 RPC),同样不碰 runner。
|
||
|
||
本模块是**两套状态机的唯一写入口**(设计文档 §4.3 防漂移):
|
||
|
||
- ``set_status()`` —— 业务进度 ``status``
|
||
- ``set_ck_status()`` / ``set_ck()`` / ``rebuild_ck()`` —— 凭据状态 ``ck_status``
|
||
|
||
接口层不允许直接改这两个列,否则状态与时间戳会各自漂移。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import dataclasses
|
||
import re
|
||
import time
|
||
from collections.abc import Mapping, Sequence
|
||
from datetime import UTC, datetime
|
||
from typing import Any
|
||
|
||
from loguru import logger
|
||
from sqlalchemy import func, or_
|
||
from sqlalchemy.orm import Session
|
||
|
||
from ..huya_defaults import HUYA_DEFAULT_BIND_ACT_ID, HUYA_DEFAULT_OUTER_ACT_ID
|
||
from ..models import HuyaExternalOrder, User
|
||
from .audit_service import record_audit
|
||
from .file_service import build_file_url
|
||
from .file_storage import normalize_object_key
|
||
from .huya_service import build_web_cookie_from_raw, parse_huya_cookie_line
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 业务状态机(一单卡在哪一步)
|
||
# --------------------------------------------------------------------------
|
||
|
||
STATUS_PENDING = "pending"
|
||
STATUS_BOUND = "bound"
|
||
STATUS_RECHARGED = "recharged"
|
||
STATUS_SCRIPTED = "scripted"
|
||
STATUS_DONE = "done"
|
||
STATUS_VOID = "void"
|
||
|
||
ORDER_STATUSES: tuple[str, ...] = (
|
||
STATUS_PENDING,
|
||
STATUS_BOUND,
|
||
STATUS_RECHARGED,
|
||
STATUS_SCRIPTED,
|
||
STATUS_DONE,
|
||
STATUS_VOID,
|
||
)
|
||
|
||
ORDER_STATUS_LABELS = {
|
||
STATUS_PENDING: "待处理",
|
||
STATUS_BOUND: "已绑定",
|
||
STATUS_RECHARGED: "已充值",
|
||
STATUS_SCRIPTED: "已上脚本",
|
||
STATUS_DONE: "已完成",
|
||
STATUS_VOID: "已作废",
|
||
}
|
||
|
||
# 「向前一步」的下一站;done 是终点,void 是任意态可达的旁路,都不在这条链上。
|
||
NEXT_STATUS = {
|
||
STATUS_PENDING: STATUS_BOUND,
|
||
STATUS_BOUND: STATUS_RECHARGED,
|
||
STATUS_RECHARGED: STATUS_SCRIPTED,
|
||
STATUS_SCRIPTED: STATUS_DONE,
|
||
}
|
||
|
||
# 阶段序号:用来同步时间戳(回退时要清掉后面阶段的时间戳,否则状态与时间戳互相矛盾)。
|
||
STAGE_INDEX = {
|
||
STATUS_PENDING: 0,
|
||
STATUS_BOUND: 1,
|
||
STATUS_RECHARGED: 2,
|
||
STATUS_SCRIPTED: 3,
|
||
STATUS_DONE: 4,
|
||
}
|
||
|
||
STATUS_TIMESTAMP_FIELDS = {
|
||
STATUS_BOUND: "bound_at",
|
||
STATUS_RECHARGED: "recharged_at",
|
||
STATUS_SCRIPTED: "scripted_at",
|
||
STATUS_DONE: "done_at",
|
||
}
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 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",
|
||
"remark",
|
||
)
|
||
|
||
FIELD_LIMITS = {
|
||
"order_no": 64,
|
||
"shop": 64,
|
||
"bind_douyu_account": 128,
|
||
"bind_douyu_uid": 32,
|
||
"gift_name": 128,
|
||
"remark": 512,
|
||
"void_reason": 256,
|
||
}
|
||
|
||
FIELD_LABELS = {
|
||
"order_no": "订单编号",
|
||
"shop": "店铺",
|
||
"owner_id": "负责人",
|
||
"bind_douyu_account": "绑定斗鱼号",
|
||
"bind_douyu_uid": "绑定斗鱼号 uid",
|
||
"gift_name": "礼包名",
|
||
"remark": "备注",
|
||
"void_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_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
|
||
) -> None:
|
||
query = db.query(HuyaExternalOrder).filter(HuyaExternalOrder.order_no == order_no)
|
||
if exclude_id is not None:
|
||
query = query.filter(HuyaExternalOrder.id != exclude_id)
|
||
other = query.first()
|
||
if other is not None:
|
||
raise CollabError(
|
||
f"订单编号 {order_no} 已被第 {other.id} 行占用",
|
||
status_code=409,
|
||
code="order_no_conflict",
|
||
)
|
||
|
||
|
||
def _assert_uid_available(
|
||
db: Session, uid: str | None, *, exclude_id: int | None = None
|
||
) -> None:
|
||
"""一个虎牙号只能挂一单(已确认 1 单 = 1 CK)。"""
|
||
text = str(uid or "").strip()
|
||
if not text:
|
||
return
|
||
query = db.query(HuyaExternalOrder).filter(HuyaExternalOrder.uid == text)
|
||
if exclude_id is not None:
|
||
query = query.filter(HuyaExternalOrder.id != exclude_id)
|
||
other = query.first()
|
||
if other is not None:
|
||
raise CollabError(
|
||
f"虎牙号 {text} 已经挂在订单 {other.order_no}(第 {other.id} 行)",
|
||
status_code=409,
|
||
code="uid_conflict",
|
||
)
|
||
|
||
|
||
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]
|
||
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 _assert_can_enter_bound(order: HuyaExternalOrder) -> None:
|
||
"""进入「已绑定」的前置校验(在服务层做,前端校验只是体验)。
|
||
|
||
绑定对象有两条来源:人工填的 `bind_douyu_account`(Excel D 列),或**探针读到的
|
||
`bind_game_role`**(2026-10-16 起探针把绑定角色写进快照列)。有任意一条就算"绑上了",
|
||
否则只验证过 CK、没读过绑定角色的行会被挡在 `bound` 外面。
|
||
"""
|
||
missing: list[str] = []
|
||
if not str(order.cookie or "").strip():
|
||
missing.append("CK")
|
||
has_binding = bool(
|
||
str(order.bind_douyu_account or "").strip()
|
||
or str(order.bind_game_role or "").strip()
|
||
)
|
||
if not has_binding:
|
||
missing.append("绑定账号(人工填绑定斗鱼号,或先「验证 CK」读到绑定角色)")
|
||
if not images_of(order, "bind_images"):
|
||
missing.append("绑定图")
|
||
if missing:
|
||
raise CollabError(
|
||
f"还不能标记为「已绑定」,缺少:{'、'.join(missing)}",
|
||
code="bound_precondition",
|
||
)
|
||
|
||
|
||
def _sync_stage_timestamps(
|
||
order: HuyaExternalOrder, target: str, now: datetime
|
||
) -> None:
|
||
"""让各阶段时间戳与目标状态保持一致。
|
||
|
||
- 目标状态**之前**(含自身)缺失的时间戳补上:状态说「已上脚本」,
|
||
时间戳就不能是空的,否则前端那格显示空白、没人知道什么时候做的;
|
||
- 目标状态**之后**的时间戳清空:回退之后还留着「已上脚本时间」,
|
||
就是状态与时间戳互相矛盾。
|
||
"""
|
||
if target == STATUS_VOID:
|
||
return
|
||
target_index = STAGE_INDEX[target]
|
||
for stage, field in STATUS_TIMESTAMP_FIELDS.items():
|
||
if STAGE_INDEX[stage] <= target_index:
|
||
if getattr(order, field) is None:
|
||
setattr(order, field, now)
|
||
else:
|
||
setattr(order, field, None)
|
||
|
||
|
||
def set_status(
|
||
db: Session,
|
||
current: User | None,
|
||
order: HuyaExternalOrder,
|
||
target: str,
|
||
*,
|
||
reason: str = "",
|
||
rollback: bool = False,
|
||
commit: bool = True,
|
||
) -> dict:
|
||
"""推进/回退业务状态(本模块唯一的 ``status`` 写入口)。
|
||
|
||
Args:
|
||
target: 目标状态,必须在 ``ORDER_STATUSES`` 里。
|
||
reason: 作废原因(``target=void`` 时必填)。
|
||
rollback: 目标不是「向前一步」时,必须显式置 True 才允许改。
|
||
"""
|
||
if target not in ORDER_STATUSES:
|
||
raise CollabError(f"未知状态:{target}", code="status_unknown")
|
||
if target == order.status:
|
||
return {}
|
||
|
||
from_status = order.status
|
||
if target != STATUS_VOID and target != NEXT_STATUS.get(from_status):
|
||
if not rollback:
|
||
next_status = NEXT_STATUS.get(from_status)
|
||
hint = (
|
||
f"只能推进到「{ORDER_STATUS_LABELS[next_status]}」"
|
||
if next_status
|
||
else "这单已经走到终点,只能作废"
|
||
)
|
||
raise CollabError(
|
||
f"状态只能向前推进({hint});要回退请显式勾选「回退」",
|
||
code="status_not_forward",
|
||
)
|
||
if from_status == STATUS_VOID:
|
||
raise CollabError(
|
||
"已作废的单子不能改回流程内状态,请编辑或新建",
|
||
code="status_from_void",
|
||
)
|
||
|
||
if target == STATUS_BOUND:
|
||
_assert_can_enter_bound(order)
|
||
|
||
now = _now()
|
||
if target == STATUS_VOID:
|
||
order.void_reason = clean_text(reason, field="void_reason", required=True)
|
||
else:
|
||
# 从作废改回流程内状态时,作废原因要清掉,不然列表上会自相矛盾。
|
||
order.void_reason = ""
|
||
|
||
order.status = target
|
||
_sync_stage_timestamps(order, target, now)
|
||
_touch(order, current)
|
||
|
||
record_audit(
|
||
db,
|
||
current,
|
||
action="huya:collab:status",
|
||
target=_audit_target(order),
|
||
detail={
|
||
"from": from_status,
|
||
"to": target,
|
||
"rollback": bool(rollback and target != NEXT_STATUS.get(from_status)),
|
||
"reason": order.void_reason,
|
||
"order_no": order.order_no,
|
||
},
|
||
)
|
||
if commit:
|
||
db.commit()
|
||
db.refresh(order)
|
||
return {"from": from_status, "to": target}
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# CK 写入口
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
def set_ck(
|
||
db: Session,
|
||
current: User | None,
|
||
order: HuyaExternalOrder,
|
||
cookie_text: str,
|
||
*,
|
||
commit: bool = True,
|
||
) -> dict:
|
||
"""贴入 / 换一份 CK(uid 冲突会挡住),状态回到「未验证」。"""
|
||
before = str(order.cookie or "")
|
||
detail = _apply_ck(order, cookie_text)
|
||
_assert_uid_available(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 ""),
|
||
},
|
||
)
|
||
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")
|
||
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 的纯函数)。"""
|
||
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(
|
||
db: Session,
|
||
current: User | None,
|
||
order: HuyaExternalOrder,
|
||
slot: str,
|
||
value: Any,
|
||
*,
|
||
commit: bool = True,
|
||
) -> dict:
|
||
"""整槽替换图片(前端上传完拿到 object_key 后一次性提交)。"""
|
||
if slot not in IMAGE_SLOTS:
|
||
raise CollabError(f"未知图片槽位:{slot}", code="image_slot_unknown")
|
||
before = images_of(order, slot)
|
||
after = normalize_images(value, field=slot)
|
||
if before == after:
|
||
return {"slot": slot, "images": after}
|
||
setattr(order, slot, after)
|
||
_touch(order, current)
|
||
record_audit(
|
||
db,
|
||
current,
|
||
action="huya:collab:image",
|
||
target=_audit_target(order),
|
||
detail={
|
||
"slot": slot,
|
||
"slot_label": IMAGE_SLOT_LABELS[slot],
|
||
"added": [key for key in after if key not in before],
|
||
"removed": [key for key in before if key not in after],
|
||
"order_no": order.order_no,
|
||
},
|
||
)
|
||
if commit:
|
||
db.commit()
|
||
db.refresh(order)
|
||
return {"slot": slot, "images": after}
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# CK 探针(S5,只读验证)
|
||
# --------------------------------------------------------------------------
|
||
|
||
# 探针参数与 web/backend/huya_defaults.py 的默认活动一致(2026-10-16 真机实测)。
|
||
PROBE_BIND_ACT_ID = int(HUYA_DEFAULT_BIND_ACT_ID)
|
||
PROBE_OUTER_ACT_ID = HUYA_DEFAULT_OUTER_ACT_ID
|
||
PROBE_TIMEOUT_SECONDS = 15.0
|
||
|
||
# 探针独占的绑定快照列(每次验证**覆盖写入**,人工不编辑):
|
||
# 「这单现在到底绑了哪个游戏账号、哪个角色」只认这几列。
|
||
PROBE_SNAPSHOT_FIELDS: tuple[str, ...] = (
|
||
"bind_game_account",
|
||
"bind_game_role",
|
||
"bind_game_channel",
|
||
)
|
||
|
||
# 批量验证**串行 + 间隔**:不做定时轮询,一次也别勾太多,避免把账号送进风控名单。
|
||
PROBE_BATCH_INTERVAL_SECONDS = 1.0
|
||
PROBE_BATCH_MAX = 50
|
||
|
||
_CK_MESSAGE_LIMIT = 256 # ck_check_message 列宽
|
||
_PROBE_PIECE_LIMIT = 40 # 拼消息时单段文本的上限
|
||
|
||
|
||
def _clip(value: Any, limit: int = _PROBE_PIECE_LIMIT) -> str:
|
||
"""把探针文本裁到可读长度(``ck_check_message`` 只有 256 字符)。"""
|
||
text = str(value if value is not None else "").strip()
|
||
return text if len(text) <= limit else text[: limit - 3] + "..."
|
||
|
||
|
||
@dataclasses.dataclass(frozen=True)
|
||
class CkProbeResult:
|
||
"""一次只读探针的结论(不落库;落库由 :func:`verify_ck` 负责)。"""
|
||
|
||
ok: bool
|
||
message: str
|
||
snapshot: dict[str, str] = dataclasses.field(default_factory=dict)
|
||
|
||
|
||
def _build_probe_client() -> Any:
|
||
"""探针客户端(HTTP cdnws 只读通道)。
|
||
|
||
只做只读 RPC:**不建 ``HuyaAccount``、不 import 任何 runner**(设计文档 §2.3)。
|
||
测试替换这个工厂就能离线跑,不真连虎牙。
|
||
"""
|
||
from core.huya.http_client import HuyaHttpClient
|
||
|
||
return HuyaHttpClient(
|
||
logger=lambda message: logger.debug(f"[huya-collab] {message}")
|
||
)
|
||
|
||
|
||
def _probe_snapshot(resp: Any) -> dict[str, str]:
|
||
"""探针读到的**绑定对象**:绑定在该虎牙号上的游戏账号 + 角色。
|
||
|
||
2026-10-16 真机确认:``check_user_bind_game_account`` 返回的是**游戏账号**
|
||
(账号昵称 / 角色名 / 平台·区服),**不是虎牙号自己的昵称** —— 虎牙昵称要
|
||
`get_grow_level_user_info`,可那个接口不认凭据、当不了探针,所以 ``nickname``
|
||
一个字段都不碰(那是「虎牙号昵称」,硬写就是假数据)。
|
||
|
||
这几个列由探针**独占并覆盖写入**(``bind_snapshot_at`` 记读取时间):
|
||
"这单现在到底绑了哪个号、哪个角色"只有这里可信(人工填的是自由文本)。
|
||
"""
|
||
account_data = getattr(resp, "accountData", None)
|
||
game_account = getattr(account_data, "gameAccount", None)
|
||
game_role = getattr(account_data, "gameRole", None)
|
||
|
||
snapshot: dict[str, str] = dict.fromkeys(PROBE_SNAPSHOT_FIELDS, "")
|
||
account_name = _clip(getattr(game_account, "nick", "")) or _clip(
|
||
getattr(game_role, "roleName", "")
|
||
)
|
||
if account_name:
|
||
snapshot["bind_game_account"] = account_name
|
||
role_name = _clip(getattr(game_role, "roleName", ""))
|
||
if role_name:
|
||
snapshot["bind_game_role"] = role_name
|
||
channel = " · ".join(
|
||
piece
|
||
for piece in (
|
||
_clip(getattr(game_role, "platName", "")),
|
||
_clip(getattr(game_role, "areaName", "")),
|
||
)
|
||
if piece
|
||
)
|
||
if channel:
|
||
snapshot["bind_game_channel"] = channel
|
||
return snapshot
|
||
|
||
|
||
def _probe_success_message(resp: Any) -> str:
|
||
"""成功时的可读结论(列表上直接能看到探针读到的绑定对象)。"""
|
||
account_data = getattr(resp, "accountData", None)
|
||
game_account = getattr(account_data, "gameAccount", None)
|
||
game_role = getattr(account_data, "gameRole", None)
|
||
|
||
parts: list[str] = []
|
||
nick = _clip(getattr(game_account, "nick", ""))
|
||
role_name = _clip(getattr(game_role, "roleName", ""))
|
||
if nick:
|
||
parts.append(f"账号 {nick}")
|
||
if role_name:
|
||
parts.append(f"角色 {role_name}")
|
||
channel = " · ".join(
|
||
piece
|
||
for piece in (
|
||
_clip(getattr(game_role, "platName", "")),
|
||
_clip(getattr(game_role, "areaName", "")),
|
||
)
|
||
if piece
|
||
)
|
||
if channel:
|
||
parts.append(channel)
|
||
detail = " / ".join(parts)
|
||
return (f"有效:{detail}" if detail else "有效")[:_CK_MESSAGE_LIMIT]
|
||
|
||
|
||
def probe_ck(order: HuyaExternalOrder, *, client: Any | None = None) -> CkProbeResult:
|
||
"""只读探针:这份 CK 还能不能过(不写库、不发敏感动作)。
|
||
|
||
判据(2026-10-16 真机对照确定,**别改成「有数据就算成功」**):
|
||
响应**非 None 且 ``status == 200``**。
|
||
|
||
实测支持这个判据:裸 cookie(无任何凭据)+ 真 uid → 返回 ``None``;
|
||
真 CK + 别人的 uid → 也返回 ``None``;只有「真 CK + 真 uid」才拿到 200 + 真实数据。
|
||
"""
|
||
uid_text = str(order.uid or "").strip()
|
||
cookie = str(order.cookie or "").strip()
|
||
if not uid_text or not cookie:
|
||
return CkProbeResult(False, "这行还没有可验证的 CK(uid 或凭据为空)")
|
||
try:
|
||
uid = int(uid_text)
|
||
except ValueError:
|
||
return CkProbeResult(False, f"CK 里的 uid 不是数字:{_clip(uid_text)}")
|
||
|
||
try:
|
||
probe_client = client or _build_probe_client()
|
||
resp = probe_client.check_user_bind_game_account(
|
||
uid=uid,
|
||
cookie=cookie,
|
||
b_act_id=PROBE_BIND_ACT_ID,
|
||
is_use_outer_act_id=1,
|
||
outer_act_id=PROBE_OUTER_ACT_ID,
|
||
timeout=PROBE_TIMEOUT_SECONDS,
|
||
)
|
||
except Exception as exc: # noqa: BLE001 探针异常=验证不通过,不能让接口 500
|
||
logger.debug(f"[huya-collab] CK 探针异常:{type(exc).__name__}: {exc}")
|
||
return CkProbeResult(False, f"探针调用失败:{type(exc).__name__}: {_clip(exc)}")
|
||
|
||
if resp is None:
|
||
return CkProbeResult(False, "探针没有返回数据(凭据无效或已被风控)")
|
||
status = int(getattr(resp, "status", 0) or 0)
|
||
if status != 200:
|
||
msg = _clip(getattr(resp, "msg", ""))
|
||
suffix = f":{msg}" if msg else ""
|
||
return CkProbeResult(False, f"探针返回 status={status}{suffix}")
|
||
return CkProbeResult(True, _probe_success_message(resp), _probe_snapshot(resp))
|
||
|
||
|
||
def verify_ck(
|
||
db: Session,
|
||
current: User | None,
|
||
order: HuyaExternalOrder,
|
||
*,
|
||
client: Any | None = None,
|
||
commit: bool = True,
|
||
) -> dict:
|
||
"""跑一次只读探针并把结论落库。
|
||
|
||
- 结论**只**通过 :func:`set_ck_status` 写(``ck_status`` 的唯一写入口,审计不会丢);
|
||
- 成功时**覆盖写入**绑定快照(``bind_game_account`` / ``bind_game_role`` /
|
||
``bind_game_channel`` + ``bind_snapshot_at``):这几列是探针独占的"现在绑了谁",
|
||
覆盖前会把旧值记进 ``huya:collab:probe_snapshot`` 审计,出问题能查回来;
|
||
- 人工填的那些列(含 ``bind_douyu_account``)**一律不碰**;
|
||
- CK 失效**不改业务状态**(设计文档 §4.2:已绑定/已充值的单子业务上可能仍然有效)。
|
||
"""
|
||
if not str(order.cookie or "").strip():
|
||
raise CollabError("这行还没有 CK,先贴一份再验证", code="no_cookie")
|
||
if order.status == STATUS_VOID:
|
||
raise CollabError(
|
||
"已作废的行不验证 CK(要重新用请先改回流程内状态)", code="void_order"
|
||
)
|
||
|
||
result = probe_ck(order, client=client)
|
||
binding: dict[str, str] = {
|
||
field_name: str(getattr(order, field_name) or "")
|
||
for field_name in PROBE_SNAPSHOT_FIELDS
|
||
}
|
||
if result.ok:
|
||
before = dict(binding)
|
||
for field_name in PROBE_SNAPSHOT_FIELDS:
|
||
setattr(order, field_name, result.snapshot.get(field_name, ""))
|
||
order.bind_snapshot_at = _now()
|
||
binding = {
|
||
field_name: str(getattr(order, field_name) or "")
|
||
for field_name in PROBE_SNAPSHOT_FIELDS
|
||
}
|
||
if binding != before:
|
||
# 快照变了(或第一次读到)才记一条,别每次验证都刷两行审计。
|
||
record_audit(
|
||
db,
|
||
current,
|
||
action="huya:collab:probe_snapshot",
|
||
target=_audit_target(order),
|
||
detail={
|
||
"order_no": order.order_no,
|
||
"before": before,
|
||
"after": binding,
|
||
},
|
||
)
|
||
|
||
target = CK_VALID if result.ok else CK_INVALID
|
||
set_ck_status(db, current, order, target, message=result.message, commit=False)
|
||
if commit:
|
||
db.commit()
|
||
db.refresh(order)
|
||
return {
|
||
"id": order.id,
|
||
"order_no": order.order_no,
|
||
"ok": result.ok,
|
||
"ck_status": target,
|
||
"message": result.message,
|
||
"binding": binding,
|
||
}
|
||
|
||
|
||
def _probe_row_error(order: HuyaExternalOrder, message: str) -> dict:
|
||
"""批量验证里「这一行没跑成」的统一形状(状态保持原样,不谎报 invalid)。"""
|
||
return {
|
||
"id": order.id,
|
||
"order_no": order.order_no,
|
||
"ok": False,
|
||
"ck_status": order.ck_status,
|
||
"message": _clip(message, _CK_MESSAGE_LIMIT),
|
||
"binding": {
|
||
field_name: str(getattr(order, field_name) or "")
|
||
for field_name in PROBE_SNAPSHOT_FIELDS
|
||
},
|
||
}
|
||
|
||
|
||
def verify_ck_batch(
|
||
db: Session,
|
||
current: User | None,
|
||
orders: Sequence[HuyaExternalOrder],
|
||
*,
|
||
client: Any | None = None,
|
||
interval_seconds: float | None = None,
|
||
commit: bool = True,
|
||
) -> dict:
|
||
"""批量验证:**串行 + 间隔**(人工触发,不做定时轮询),单条失败不影响其他条。
|
||
|
||
Returns:
|
||
``{total, valid, failed, results: [{id, order_no, ok, ck_status, message, binding}]}``
|
||
"""
|
||
rows = list(orders)
|
||
if len(rows) > PROBE_BATCH_MAX:
|
||
raise CollabError(
|
||
f"一次最多验证 {PROBE_BATCH_MAX} 条,请分批勾选",
|
||
code="verify_batch_too_large",
|
||
)
|
||
interval = (
|
||
PROBE_BATCH_INTERVAL_SECONDS
|
||
if interval_seconds is None
|
||
else max(0.0, float(interval_seconds))
|
||
)
|
||
|
||
results: list[dict] = []
|
||
for index, order in enumerate(rows):
|
||
if index and interval:
|
||
time.sleep(interval)
|
||
try:
|
||
# 每行一个 SAVEPOINT:某行在写库阶段炸了也只脏这一行(同 import_orders)。
|
||
with db.begin_nested():
|
||
results.append(
|
||
verify_ck(db, current, order, client=client, commit=False)
|
||
)
|
||
db.flush()
|
||
except CollabError as exc:
|
||
results.append(_probe_row_error(order, exc.detail))
|
||
except Exception as exc: # noqa: BLE001 单条失败不该带崩整批
|
||
logger.debug(f"[huya-collab] 批量验证单行失败:{type(exc).__name__}: {exc}")
|
||
results.append(_probe_row_error(order, f"{type(exc).__name__}: {exc}"))
|
||
|
||
if commit:
|
||
db.commit()
|
||
valid = sum(1 for row in results if row["ok"])
|
||
return {
|
||
"total": len(results),
|
||
"valid": valid,
|
||
"failed": len(results) - valid,
|
||
"results": results,
|
||
}
|
||
|
||
|
||
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]
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# CRUD
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
def create_order(
|
||
db: Session,
|
||
current: User,
|
||
*,
|
||
order_no: str,
|
||
shop: str = "",
|
||
owner_id: int | None = None,
|
||
ck_text: str = "",
|
||
bind_douyu_account: str = "",
|
||
gift_name: str = "",
|
||
remark: str = "",
|
||
commit: bool = True,
|
||
) -> HuyaExternalOrder:
|
||
"""新建一行(可同时贴 CK)。订单号唯一,重复直接报冲突。"""
|
||
order_no = clean_text(order_no, field="order_no", required=True)
|
||
_assert_order_no_available(db, order_no)
|
||
|
||
order = HuyaExternalOrder(
|
||
order_no=order_no,
|
||
shop=clean_text(shop, field="shop"),
|
||
owner_id=_clean_owner_id(owner_id),
|
||
bind_douyu_account=clean_text(bind_douyu_account, field="bind_douyu_account"),
|
||
gift_name=clean_text(gift_name, field="gift_name"),
|
||
remark=clean_text(remark, field="remark"),
|
||
bind_images=[],
|
||
home_images=[],
|
||
status=STATUS_PENDING,
|
||
ck_status=CK_UNVERIFIED,
|
||
created_by=current.id,
|
||
updated_by=current.id,
|
||
version=0,
|
||
)
|
||
if str(ck_text or "").strip():
|
||
_apply_ck(order, ck_text)
|
||
_assert_uid_available(db, order.uid)
|
||
|
||
db.add(order)
|
||
db.flush() # 先拿到 id,审计里要带 target
|
||
record_audit(
|
||
db,
|
||
current,
|
||
action="huya:collab:create",
|
||
target=_audit_target(order),
|
||
detail={
|
||
"order_no": order.order_no,
|
||
"shop": order.shop,
|
||
"uid": order.uid or "",
|
||
"ck_status": order.ck_status,
|
||
},
|
||
)
|
||
if commit:
|
||
db.commit()
|
||
db.refresh(order)
|
||
return order
|
||
|
||
|
||
def update_order(
|
||
db: Session,
|
||
current: User,
|
||
order: HuyaExternalOrder,
|
||
payload: Mapping[str, Any],
|
||
*,
|
||
expected_version: int | None = None,
|
||
commit: bool = True,
|
||
) -> dict:
|
||
"""编辑可改字段,返回**字段级 diff**(``{字段: {old, new}}``)。
|
||
|
||
乐观锁:``expected_version`` 与库里不一致 → 409,绝不静默覆盖
|
||
(这正是 Excel 协同最痛的地方)。
|
||
"""
|
||
assert_version(order, expected_version)
|
||
|
||
changes: dict[str, dict[str, Any]] = {}
|
||
for field in EDITABLE_FIELDS:
|
||
if field not in payload:
|
||
continue
|
||
if field == "owner_id":
|
||
new_value: Any = _clean_owner_id(payload[field])
|
||
else:
|
||
new_value = clean_text(
|
||
payload[field],
|
||
field=field,
|
||
required=(field == "order_no"),
|
||
)
|
||
old_value = getattr(order, field)
|
||
if old_value == new_value:
|
||
continue
|
||
if field == "order_no":
|
||
_assert_order_no_available(db, new_value, exclude_id=order.id)
|
||
changes[field] = {"old": old_value, "new": new_value}
|
||
setattr(order, field, new_value)
|
||
|
||
if not changes:
|
||
return {}
|
||
|
||
_touch(order, current)
|
||
record_audit(
|
||
db,
|
||
current,
|
||
action="huya:collab:update",
|
||
target=_audit_target(order),
|
||
detail={"order_no": order.order_no, "changes": changes},
|
||
)
|
||
if commit:
|
||
db.commit()
|
||
db.refresh(order)
|
||
return changes
|
||
|
||
|
||
def delete_order(
|
||
db: Session, current: User, order: HuyaExternalOrder, *, commit: bool = True
|
||
) -> dict:
|
||
"""物理删除(需 ``huya:collab:manage``)。
|
||
|
||
只删行,**不删对象存储里的图**:撤图不可逆,交给孤儿清理脚本按保留期处理
|
||
(设计文档 §6.4)。
|
||
"""
|
||
snapshot = {
|
||
"order_no": order.order_no,
|
||
"uid": order.uid or "",
|
||
"images": images_of(order, "bind_images") + images_of(order, "home_images"),
|
||
}
|
||
record_audit(
|
||
db,
|
||
current,
|
||
action="huya:collab:delete",
|
||
target=_audit_target(order),
|
||
detail={
|
||
"order_no": snapshot["order_no"],
|
||
"uid": snapshot["uid"],
|
||
"image_count": len(snapshot["images"]),
|
||
},
|
||
)
|
||
db.delete(order)
|
||
if commit:
|
||
db.commit()
|
||
return snapshot
|
||
|
||
|
||
def _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
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 查询
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
def get_order(db: Session, order_id: int) -> HuyaExternalOrder:
|
||
order = db.query(HuyaExternalOrder).filter(HuyaExternalOrder.id == order_id).first()
|
||
if order is None:
|
||
raise CollabError(
|
||
"这一行不存在(可能已被别人删除)", status_code=404, code="order_not_found"
|
||
)
|
||
return order
|
||
|
||
|
||
def list_orders(
|
||
db: Session,
|
||
*,
|
||
shop: str = "",
|
||
owner_id: int | None = None,
|
||
status: str = "",
|
||
ck_status: str = "",
|
||
keyword: str = "",
|
||
include_void: bool = False,
|
||
page: int = 1,
|
||
page_size: int = 50,
|
||
) -> tuple[list[HuyaExternalOrder], int]:
|
||
"""共享视图:默认**不按人过滤**(负责人只是筛选维度,不是权限边界)。"""
|
||
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)
|
||
if not include_void:
|
||
query = query.filter(HuyaExternalOrder.status != STATUS_VOID)
|
||
text = (keyword or "").strip()
|
||
if text:
|
||
like = f"%{text}%"
|
||
query = query.filter(
|
||
or_(
|
||
HuyaExternalOrder.order_no.like(like),
|
||
HuyaExternalOrder.bind_douyu_account.like(like),
|
||
HuyaExternalOrder.bind_game_account.like(like),
|
||
HuyaExternalOrder.bind_game_role.like(like),
|
||
HuyaExternalOrder.uid.like(like),
|
||
HuyaExternalOrder.nickname.like(like),
|
||
HuyaExternalOrder.hy_username.like(like),
|
||
HuyaExternalOrder.gift_name.like(like),
|
||
HuyaExternalOrder.remark.like(like),
|
||
)
|
||
)
|
||
|
||
total = query.count()
|
||
page = max(1, int(page or 1))
|
||
page_size = min(200, max(1, int(page_size or 50)))
|
||
# 排序:业务状态(作废排最后)+ 最近改动在前,让「刚被谁动过」的浮上来。
|
||
stage = func.field(HuyaExternalOrder.status, *ORDER_STATUSES)
|
||
rows = (
|
||
query.order_by(stage.asc(), HuyaExternalOrder.updated_at.desc())
|
||
.offset((page - 1) * page_size)
|
||
.limit(page_size)
|
||
.all()
|
||
)
|
||
return rows, total
|
||
|
||
|
||
def summary(db: Session) -> dict:
|
||
"""页头统计条:各状态计数 + CK 失效数。"""
|
||
status_rows = (
|
||
db.query(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 = (
|
||
db.query(func.count(HuyaExternalOrder.id))
|
||
.filter(HuyaExternalOrder.ck_status == CK_INVALID)
|
||
.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),
|
||
}
|
||
|
||
|
||
def list_shops(db: Session) -> list[str]:
|
||
rows = (
|
||
db.query(HuyaExternalOrder.shop)
|
||
.filter(HuyaExternalOrder.shop != "")
|
||
.distinct()
|
||
.order_by(HuyaExternalOrder.shop)
|
||
.all()
|
||
)
|
||
return [str(row[0]) for row in rows]
|
||
|
||
|
||
def users_by_id(db: Session, orders: Sequence[HuyaExternalOrder]) -> dict[int, str]:
|
||
"""一次性把涉及的用户名查出来,避免每行都懒加载(N+1)。"""
|
||
ids = {
|
||
int(value)
|
||
for order in orders
|
||
for value in (order.owner_id, order.created_by, order.updated_by)
|
||
if value
|
||
}
|
||
if not ids:
|
||
return {}
|
||
rows = db.query(User.id, User.username).filter(User.id.in_(ids)).all()
|
||
return {int(row[0]): str(row[1]) for row in rows}
|
||
|
||
|
||
def serialize_order(
|
||
order: HuyaExternalOrder, *, users: Mapping[int, str] | None = None
|
||
) -> dict:
|
||
"""把行对象转成接口输出。
|
||
|
||
图片存的是 object_key,URL 在这里现拼 —— 库里存 URL 会在换存储/改路径时
|
||
全部失效(order_site 踩过「存下来的签名链接过期后到处裂图」)。
|
||
"""
|
||
names = users or {}
|
||
bind_images = images_of(order, "bind_images")
|
||
home_images = images_of(order, "home_images")
|
||
|
||
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 "",
|
||
"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,
|
||
"void_reason": order.void_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,
|
||
}
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 批量导入(Excel 粘贴)
|
||
# --------------------------------------------------------------------------
|
||
|
||
IMPORT_COLUMNS: tuple[str, ...] = (
|
||
"shop",
|
||
"order_no",
|
||
"owner",
|
||
"bind_douyu_account",
|
||
"gift_name",
|
||
"remark",
|
||
)
|
||
|
||
# 表头识别:中文(Excel 原表头)+ 英文别名。按位置兜底要求 6 列顺序一致。
|
||
_HEADER_ALIASES: dict[str, str] = {
|
||
"店铺": "shop",
|
||
"shop": "shop",
|
||
"订单编号": "order_no",
|
||
"订单号": "order_no",
|
||
"order_no": "order_no",
|
||
"orderno": "order_no",
|
||
"负责人": "owner",
|
||
"owner": "owner",
|
||
"绑定斗鱼号": "bind_douyu_account",
|
||
"绑定斗鱼": "bind_douyu_account",
|
||
"斗鱼号": "bind_douyu_account",
|
||
"bind_douyu_account": "bind_douyu_account",
|
||
"礼包": "gift_name",
|
||
"礼包名": "gift_name",
|
||
"商品": "gift_name",
|
||
"gift_name": "gift_name",
|
||
"备注": "remark",
|
||
"remark": "remark",
|
||
}
|
||
|
||
|
||
def parse_import_text(text: str) -> tuple[list[str], list[tuple[int, list[str]]]]:
|
||
"""把粘贴的文本切成 (列顺序, [(行号, 单元格)])。
|
||
|
||
支持 Excel 直接复制出来的 TSV(``\\t``),也兼容逗号/分号分隔。
|
||
第一行若能被识别成表头,则按表头映射列;否则按固定列序
|
||
``店铺 / 订单编号 / 负责人 / 绑定斗鱼号 / 礼包 / 备注``。
|
||
"""
|
||
rows: list[tuple[int, list[str]]] = []
|
||
for index, raw_line in enumerate((text or "").splitlines(), start=1):
|
||
line = raw_line.rstrip("\r\n")
|
||
if not line.strip():
|
||
continue
|
||
if "\t" in line:
|
||
cells = line.split("\t")
|
||
elif ";" in line:
|
||
cells = line.split(";")
|
||
elif "," in line:
|
||
cells = line.split(",")
|
||
else:
|
||
cells = [line]
|
||
rows.append((index, [cell.strip() for cell in cells]))
|
||
|
||
if not rows:
|
||
return list(IMPORT_COLUMNS), []
|
||
|
||
first_index, first_cells = rows[0]
|
||
mapped: list[str] = []
|
||
for cell in first_cells:
|
||
key = _HEADER_ALIASES.get(cell.strip().lower()) or _HEADER_ALIASES.get(
|
||
cell.strip()
|
||
)
|
||
mapped.append(key or "")
|
||
if mapped.count("order_no") == 1 and len(mapped) >= 2:
|
||
logger.debug(f"协作台账导入:识别到表头(行 {first_index}){mapped}")
|
||
return mapped, rows[1:]
|
||
return list(IMPORT_COLUMNS), rows
|
||
|
||
|
||
def import_orders(
|
||
db: Session,
|
||
current: User,
|
||
text: str,
|
||
*,
|
||
owner_by_name: Mapping[str, int] | None = None,
|
||
commit: bool = True,
|
||
) -> dict:
|
||
"""批量导入:逐行处理,**单行失败不影响其他行**(AGENTS §2),错误按行号返回。
|
||
|
||
Returns:
|
||
``{created, updated, skipped, errors: [{line, order_no, message}]}``
|
||
"""
|
||
columns, rows = parse_import_text(text)
|
||
owners = {
|
||
str(name).strip(): int(uid) for name, uid in (owner_by_name or {}).items()
|
||
}
|
||
created = 0
|
||
updated = 0
|
||
skipped = 0
|
||
errors: list[dict[str, Any]] = []
|
||
|
||
seen_order_nos: set[str] = set()
|
||
|
||
for line_no, cells in rows:
|
||
record = {
|
||
column: (cells[index] if index < len(cells) else "")
|
||
for index, column in enumerate(columns)
|
||
if column
|
||
}
|
||
order_no = str(record.get("order_no") or "").strip()
|
||
if not order_no:
|
||
skipped += 1
|
||
continue
|
||
if order_no in seen_order_nos:
|
||
# 同一批粘贴里重复出现:只处理第一条,否则后一条会把刚建的覆盖掉。
|
||
errors.append(
|
||
{
|
||
"line": line_no,
|
||
"order_no": order_no,
|
||
"message": "本次粘贴里重复出现,只处理第一条",
|
||
}
|
||
)
|
||
continue
|
||
seen_order_nos.add(order_no)
|
||
|
||
owner_name = str(record.get("owner") or "").strip()
|
||
payload = {
|
||
"shop": record.get("shop", ""),
|
||
"bind_douyu_account": record.get("bind_douyu_account", ""),
|
||
"gift_name": record.get("gift_name", ""),
|
||
"remark": record.get("remark", ""),
|
||
}
|
||
if owner_name:
|
||
if owner_name not in owners:
|
||
errors.append(
|
||
{
|
||
"line": line_no,
|
||
"order_no": order_no,
|
||
"message": f"负责人「{owner_name}」不存在或不是活跃用户",
|
||
}
|
||
)
|
||
continue
|
||
payload["owner_id"] = owners[owner_name]
|
||
|
||
outcome = ""
|
||
try:
|
||
# 每行套一个 SAVEPOINT:这一行炸了只回滚这一行,整批继续。
|
||
# 若直接往同一个事务里写,一次约束冲突就会把会话打成失败态,
|
||
# 后面每一行都跟着报错 —— 那就成了「单行失败带崩整批」。
|
||
with db.begin_nested():
|
||
existing = (
|
||
db.query(HuyaExternalOrder)
|
||
.filter(HuyaExternalOrder.order_no == order_no)
|
||
.first()
|
||
)
|
||
if existing is None:
|
||
create_order(
|
||
db,
|
||
current,
|
||
order_no=order_no,
|
||
shop=payload.get("shop", ""),
|
||
owner_id=payload.get("owner_id"),
|
||
bind_douyu_account=payload.get("bind_douyu_account", ""),
|
||
gift_name=payload.get("gift_name", ""),
|
||
remark=payload.get("remark", ""),
|
||
commit=False,
|
||
)
|
||
outcome = "created"
|
||
else:
|
||
# 已存在按「更新」处理(设计文档 §10.2 E);导入不带
|
||
# expected_version,视为「明确要覆盖」。
|
||
changes = update_order(
|
||
db,
|
||
current,
|
||
existing,
|
||
payload,
|
||
expected_version=None,
|
||
commit=False,
|
||
)
|
||
outcome = "updated" if changes else "skipped"
|
||
# SessionLocal 是 autoflush=False:显式 flush,让后面几行的
|
||
# 重复检查能看到刚写入的这行。
|
||
db.flush()
|
||
except CollabError as exc:
|
||
errors.append(
|
||
{"line": line_no, "order_no": order_no, "message": exc.detail}
|
||
)
|
||
continue
|
||
except Exception as exc: # noqa: BLE001 单行失败不该带崩整批导入
|
||
errors.append(
|
||
{
|
||
"line": line_no,
|
||
"order_no": order_no,
|
||
"message": f"{type(exc).__name__}: {exc}",
|
||
}
|
||
)
|
||
continue
|
||
|
||
if outcome == "created":
|
||
created += 1
|
||
elif outcome == "updated":
|
||
updated += 1
|
||
else:
|
||
skipped += 1
|
||
|
||
if commit:
|
||
db.commit()
|
||
return {
|
||
"created": created,
|
||
"updated": updated,
|
||
"skipped": skipped,
|
||
"errors": errors,
|
||
"parsed_columns": columns,
|
||
}
|