"""斗鱼外部单协作台账服务。 核心边界(和虎牙外部 CK 台账的区别): 1. **一行 = 一单 = 一个内部斗鱼账号**。协作单只存 ``account_id`` 和用户名快照, **不复制 CK**;所有查询实时读 ``accounts.cookie``,账号换 CK 后自动生效。 2. 鱼翅和手册积分是两笔资产:先充值鱼翅,再用鱼翅赠送精英令换积分。 查询时两笔都要返回,核账只看手册积分。 3. 同一斗鱼账号允许挂多单;积分核账按账号合并计算所有未作废订单的礼包积分。 4. 兑换是否成功只看当前账号的 ``exchangeList``。``getRecordList`` 是全站动态, 不能拿来判断某一单。 """ from __future__ import annotations from collections.abc import Callable, Mapping, Sequence from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import TimeoutError as FutureTimeoutError from datetime import UTC, datetime from typing import Any from loguru import logger from sqlalchemy import func, or_ from sqlalchemy.orm import Session from core.douyu import DouyuActivityClient from ..models import ( Account, AccountLease, AuditLog, DouyuCollabGift, DouyuCollabShop, DouyuConfig, DouyuExternalOrder, DouyuExternalOrderMetric, DouyuGoodsSnapshot, DouyuTask, PlatformCommodityMapping, PlatformFulfillmentTask, User, ) from ..permissions import user_has_permission from .account_binding import ( binding_channel, binding_role_from_result, can_change_role, role_change_available_at, ) from .account_events_service import ( CATEGORY_OPS, EVENT_COLLAB_SYNCED, EVENT_LEASE_ACQUIRED, emit, ) from .audit_service import record_account_action, record_audit from .business_events import record_account_query from .collab_common import apply_order_visibility, count_archived from .cookie_check_service import check_douyu_cookie from .douyu_account_probe import ( ROLE_BOUND, ROLE_ERROR, ROLE_PENDING, ROLE_UNBOUND, ROLE_UNKNOWN, SESSION_INVALID, SESSION_VALID, activity_client, config_mapping, persist_probe_result, probe_account, ) from .douyu_activity_query import ( query_exchange_orders, query_exchange_records, ) from .douyu_goods_service import ( serialize_live_goods as _serialize_live_goods, ) from .douyu_goods_service import ( serialized_snapshots, upsert_goods_snapshot, ) from .file_service import build_file_url from .platform_fulfillment.account_selector import ( acquire_account_lease, active_lease_for_account, capability_candidate_accounts, live_candidate_accounts, 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: tuple[str, ...] = ( STATUS_INCOMPLETE, STATUS_TO_RECHARGE, STATUS_RECHARGED, STATUS_SCRIPTED, STATUS_POINTS_ERROR, STATUS_ROLE_ERROR, STATUS_FAILED, ) 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 = 8 ACCOUNT_RECOMMEND_CONCURRENCY = 8 ACCOUNT_RECOMMEND_TIMEOUT_SECONDS = 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 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, *, manual_id: str, rid: str, act_alias: str, confirm_act_alias: str = "", legacy_act_alias: str = "", client: Any | None = None, with_goods: bool = True, ) -> dict[str, Any]: """只读探针:账号 CK → 手册积分 / 绑定角色 / 鱼翅余额 / 商品列表。""" if not str(account.cookie or "").strip(): return { "found": True, "ok": False, "ck_status": CK_UNVERIFIED, "message": "该账号还没有 CK", "errors": ["该账号还没有 CK"], } active_client = client or _client_for_account(account) caller_supplied_client = client is not None config_info = config_mapping( { "manual_id": manual_id, "rid": rid, "bind_act_alias": act_alias, "confirm_act_alias": confirm_act_alias or act_alias, "legacy_act_alias": legacy_act_alias, } ) result = probe_account( account, config_info, client=active_client, session_checker=None if caller_supplied_client else check_douyu_cookie, with_gold=True, with_goods=with_goods, use_cache=not caller_supplied_client, ) elite = result.get("elite") or {} role = (result.get("roles") or {}).get("elite") or {} identity = result.get("identity") or {} session = result.get("session") or {} gold = result.get("gold") or {} goods = result.get("goods") or {} bind_snapshot = role.get("snapshot") or {} role_status = str(role.get("status") or ROLE_UNKNOWN) error_labels = { "elite": "手册状态", "points": "积分", "limited_goods": "限兑商品", "gold": "鱼翅余额", "goods": "活动商品", } errors = [ f"{error_labels.get(key, key)}: {value}" for key, value in (result.get("errors") or {}).items() ] errors.extend(role.get("errors") or []) session_status = str(session.get("status") or "") if session_status == SESSION_VALID: ck_status = CK_VALID elif session_status == SESSION_INVALID: ck_status = CK_INVALID else: ck_status = CK_UNVERIFIED bind_role = _text(role.get("role_name"), max_length=128) bind_channel = _text(role.get("game_channel"), max_length=128) bind_account = _text(role.get("game_account"), max_length=128) ok = ( session_status == SESSION_VALID and role_status == ROLE_BOUND and bool(bind_role) ) if session_status == SESSION_INVALID: message = f"CK 已失效:{session.get('message') or '请重新登录'}" elif session_status not in {SESSION_VALID, ""}: message = f"CK 状态无法确认:{session.get('message') or '请稍后重试'}" elif role_status == ROLE_ERROR: message = "角色查询失败" + ( f":{';'.join(role.get('errors') or [])}" if role.get("errors") else "" ) elif role_status == ROLE_UNKNOWN: message = "角色状态无法确认,已保留上次有效结果" elif role_status == ROLE_PENDING: message = "已识别角色,待确认绑定" elif not bind_role: message = "CK 正常,但账号未绑定角色" else: message = ";".join(errors) if error_labels.get("gold") and gold.get("error"): message = f"{message};鱼翅余额: {gold['error']}" return { "found": True, "ok": ok, "ck_status": ck_status, "auth_status": session_status, "role_status": role_status, "message": message, "errors": errors, "account_id": int(account.id), "account_username": identity.get("username") or str(account.username or ""), "account_uid": _text(identity.get("uid"), max_length=32), "account_nickname": _text(identity.get("nickname"), max_length=128), "manual_type": elite.get("manual_type"), "manual_score": elite.get("manual_score"), "expire_time": elite.get("expire_time"), "manual_opened": bool(elite.get("opened")), "bind_status": bind_snapshot.get("bind_status"), "bind_phase": bind_snapshot.get("bind_phase"), "bind_game_account": bind_account, "bind_game_role": bind_role, "bind_game_channel": bind_channel, "fish_fin_balance": _to_int(gold.get("balance")), "goods": goods.get("serialized") or [], "goods_count": int(goods.get("count") or 0), "_probe_result": result, } def lookup_account( db: Session, username: str, *, client: Any | None = None, with_goods: bool = True, ) -> dict[str, Any]: config = resolve_config(db) account = account_by_username(db, username) if account is None: return { "found": False, "ok": False, "message": "账号不存在,请先到「账号管理」导入并登录", "account_username": _text(username, max_length=128), } manual_id = str(config.manual_id or "") rid = str(config.rid or "") act_alias = str(config.bind_act_alias or "") confirm_act_alias = str(config.confirm_act_alias or "") legacy_act_alias = str(config.legacy_act_alias or "") # 脱离 ORM 后提交,网络期间不持有连接,也不会因 commit 过期而重新查库。 db.expunge(account) db.commit() probe = _probe_with_client( account, manual_id=manual_id, rid=rid, act_alias=act_alias, confirm_act_alias=confirm_act_alias, legacy_act_alias=legacy_act_alias, client=client, with_goods=with_goods, ) orders = ( db.query(DouyuExternalOrder) .filter( DouyuExternalOrder.account_id == account.id, DouyuExternalOrder.archived_at.is_(None), DouyuExternalOrder.status != STATUS_VOID, ) .order_by(DouyuExternalOrder.id.asc()) .all() ) probe["orders_using_account"] = [ {"id": int(order.id), "order_no": order.order_no, "status": order.status} for order in orders ] probe["ck_status_label"] = CK_LABELS.get(str(probe.get("ck_status")), "") probe.pop("_probe_result", None) return probe def unlink_account( db: Session, current: User, order: DouyuExternalOrder, *, reason: str, expected_version: int | None = None, commit: bool = True, ) -> DouyuExternalOrder: """解除协作单与账号的关联,但不删除内部账号。""" _assert_account_replace_permission(current) _assert_success_account_change_allowed(current, order) _assert_account_replaceable(order) _assert_version(order, expected_version) if not order.account_id and not _text(order.account_username): raise CollabError("这单还没有关联斗鱼账号", code="account_not_linked") clean_reason = _text(reason, max_length=256) if not clean_reason: raise CollabError("请填写解除账号的原因", code="reason_required") previous = { "account_id": order.account_id, "account_username": order.account_username or "", "account_uid": order.account_uid or "", "account_nickname": order.account_nickname 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 "", "status": order.status, } released_lease = _release_order_account_lease( db, current, order, reason="douyu_collab_account_unlinked", ) order.account_id = None order.account_username = "" order.account_uid = "" order.account_nickname = "" order.bind_game_account = "" order.bind_game_role = "" order.bind_game_channel = "" order.bind_snapshot_at = None order.fish_fin_balance = None order.points_balance = None order.points_required_total = None order.points_surplus = None order.points_checked_at = None order.points_check_reason = "" order.points_check_message = "" order.points_check_detail = None order.recharged_at = None order.scripted_at = None order.done_at = None order.status = STATUS_INCOMPLETE order.updated_by = current.id order.updated_at = _now() order.version = int(order.version or 0) + 1 record_audit( db, current, action="douyu:collab:account_unlink", target=f"douyu_external_order:{order.id}", detail={ "reason": clean_reason, "previous": previous, "released_lease": bool(released_lease), "status": order.status, }, ) if commit: db.commit() db.refresh(order) return order def _recommendation_account_snapshot(account: Account) -> Account: """复制探针所需的标量字段,避免工作线程访问 SQLAlchemy Session。""" return Account( id=int(account.id), username=str(account.username or ""), password="", email="", email_password="", cookie=str(account.cookie or ""), uid=str(account.uid or ""), nickname=str(account.nickname or ""), elite_opened=account.elite_opened, points=account.points, gold_balance=account.gold_balance, points_expire_at=account.points_expire_at, ) def recommend_accounts( db: Session, current: User, order: DouyuExternalOrder, *, include_rebindable: bool = True, limit: int = 5, gift_name: str | None = None, commodity_id: str | None = None, required_points: Any = None, scan_limit: int | None = None, client_factory: Callable[[Account], Any] | None = None, ) -> dict[str, Any]: """推荐可绑定/可换绑账号;只读探测,不创建租约。""" _assert_account_replace_permission(current) _assert_account_replaceable(order) name, cid, points = _resolve_gift( db, gift_name=gift_name if gift_name is not None else order.gift_name, commodity_id=( commodity_id if commodity_id is not None else order.commodity_id ), required_points=( required_points if required_points is not None else order.required_points ), ) required = max(0, int(points or 0)) effective_scan_limit = max( 1, min( int(scan_limit or ACCOUNT_RECOMMEND_DEFAULT_SCAN_LIMIT), ACCOUNT_RECOMMEND_CONCURRENCY, ), ) candidates_by_id: dict[int, Account] = {} if cid: for account in capability_candidate_accounts( db, limit=effective_scan_limit, required_points=required, commodity_id=cid, scope="elite", ): candidates_by_id[int(account.id)] = account for account in live_candidate_accounts( db, limit=effective_scan_limit, required_points=required, commodity_id=cid, prefer_unbound=True, empty_only=not include_rebindable, ): candidates_by_id.setdefault(int(account.id), account) candidates = [ account for account in candidates_by_id.values() if (not order.account_id or int(account.id) != int(order.account_id)) and (include_rebindable or account.role_bind_status == "unbound") ] candidates.sort( key=lambda account: ( 0 if account.role_bind_status == "unbound" else 1, 0 if account.elite_opened is True else 1, 0 if (account.points or 0) >= required else 1, int(account.id), ) ) candidates = candidates[:effective_scan_limit] config = resolve_config(db) config_info = config_mapping( { "manual_id": str(config.manual_id or ""), "rid": str(config.rid or ""), "bind_act_alias": str(config.bind_act_alias or ""), "confirm_act_alias": str(config.confirm_act_alias or ""), "legacy_act_alias": str(config.legacy_act_alias or ""), } ) output: list[dict[str, Any]] = [] scanned = 0 result_limit = max(1, min(int(limit), 10)) def inspect_candidate(account: Account) -> tuple[Account, dict[str, Any]] | None: try: active_client = ( client_factory(account) if client_factory else activity_client( str(account.cookie or ""), logger_callback=lambda message: logger.debug( "[douyu-collab] recommend account={} {}", account.id, message, ), ) ) probe = probe_account( account, config_info, client=active_client, session_checker=( None if client_factory is not None else check_douyu_cookie ), with_elite=True, with_eligibility=False, with_limited_goods=bool(cid), with_gold=False, with_goods=False, with_elite_role=True, use_cache=client_factory is None, ) return account, probe except Exception as exc: # noqa: BLE001 - 单账号失败继续扫描 logger.info( "[douyu-collab] 推荐账号跳过 account_id={} error={}", account.id, exc, ) return None def accept_candidate(account: Account, probe: dict[str, Any]) -> None: session = probe.get("session") or {} if str(session.get("status") or "") != SESSION_VALID: return role = (probe.get("roles") or {}).get("elite") or {} role_status = str(role.get("status") or ROLE_UNKNOWN) bind_info = ( role.get("bind_info") if isinstance(role.get("bind_info"), dict) else None ) if role_status == ROLE_UNBOUND: match_type = "empty" match_label = "未绑定" elif role_status == ROLE_BOUND and can_change_role(bind_info): if not include_rebindable: return match_type = "rebind" match_label = "可换绑" else: return eligibility = probe.get("eligibility") or {} limited_ids = { str(item) for item in eligibility.get("limited_ids") or [] if str(item) } if cid and cid in limited_ids: return elite = probe.get("elite") or {} live_points = _to_int(eligibility.get("points")) if live_points is None: live_points = _to_int(elite.get("manual_score")) elite_opened = bool(elite.get("opened")) ready = bool( elite_opened and live_points is not None and live_points >= required ) reasons = [ "未绑定角色,可直接绑定" if match_type == "empty" else "已绑定角色,当前可换绑" ] if not elite_opened: reasons.append("精英宝典未开通") if live_points is None or live_points < required: reasons.append(f"积分不足({live_points or 0}/{required})") identity = probe.get("identity") or {} output.append( { "account_id": int(account.id), # 后续“使用此账号”会按内部 username 反查,不能用接口返回的展示昵称。 "account_username": str(account.username or ""), "account_uid": str(identity.get("uid") or account.uid or ""), "account_nickname": str( identity.get("nickname") or account.nickname or account.username or "" ), "ck_status": CK_VALID, "role_status": role_status, "bind_game_role": str(role.get("role_name") or ""), "role_change_available_at": role_change_available_at(bind_info), "points": live_points, "elite_opened": elite_opened, "match_type": match_type, "match_type_label": match_label, "ready": ready, "reasons": reasons, } ) snapshots = [_recommendation_account_snapshot(account) for account in candidates] if snapshots: executor = ThreadPoolExecutor( max_workers=min(ACCOUNT_RECOMMEND_CONCURRENCY, len(snapshots)) ) futures = { executor.submit(inspect_candidate, account): account for account in snapshots } scanned = len(futures) try: for future in as_completed( futures, timeout=ACCOUNT_RECOMMEND_TIMEOUT_SECONDS, ): result = future.result() if result is not None: accept_candidate(*result) if len(output) >= result_limit: break except FutureTimeoutError: logger.warning( "[douyu-collab] 推荐账号实时校验超时,已返回当前结果 scanned={} " "timeout={}s", scanned, ACCOUNT_RECOMMEND_TIMEOUT_SECONDS, ) finally: for future in futures: future.cancel() executor.shutdown(wait=False, cancel_futures=True) output.sort( key=lambda item: ( 0 if item["match_type"] == "empty" else 1, 0 if item["ready"] else 1, int(item["points"] or 0), int(item["account_id"]), ) ) selected = output[: max(1, min(int(limit), 10))] message = ( f"找到 {len(selected)} 个可用账号,未绑定账号优先" if selected else "当前没有找到未绑定或已过换绑冷却的可用账号" ) if not include_rebindable: message += ";当前仅搜索未绑定账号" return { "order_id": int(order.id), "gift_name": name, "commodity_id": cid, "required_points": points, "include_rebindable": bool(include_rebindable), "scanned": scanned, "candidates": selected, "message": message, } def apply_probe_snapshot( db: Session, current: User, order: DouyuExternalOrder, account: Account, probe: Mapping[str, Any], *, source: str, ) -> None: canonical = probe.get("_probe_result") if isinstance(canonical, dict): persist_probe_result( db, account, canonical, current=current, source=source, record_event=True, ) order.account_id = int(account.id) order.account_username = _text(account.username, max_length=128) or _text( probe.get("account_username"), max_length=128 ) order.account_uid = _text(probe.get("account_uid") or account.uid, max_length=32) order.account_nickname = _text( probe.get("account_nickname") or account.nickname, max_length=128 ) role_status = str(probe.get("role_status") or "") if role_status not in {ROLE_ERROR, ROLE_UNKNOWN}: order.bind_game_account = _text(probe.get("bind_game_account"), max_length=128) order.bind_game_role = _text(probe.get("bind_game_role"), max_length=128) order.bind_game_channel = _text(probe.get("bind_game_channel"), max_length=128) order.bind_snapshot_at = _now() fish = _to_int(probe.get("fish_fin_balance")) points = _to_int(probe.get("manual_score")) if fish is not None: order.fish_fin_balance = fish if points is not None: 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) def _maybe_advance_to_recharge( db: Session, current: User, order: DouyuExternalOrder, *, commit: bool = False, ) -> None: if order.status != STATUS_INCOMPLETE or not _ready_for_recharge(order): return old = order.status order.status = STATUS_TO_RECHARGE order.updated_by = current.id order.version = int(order.version or 0) + 1 record_audit( db, current, action="douyu:collab:status_auto", target=f"douyu_external_order:{order.id}", detail={"from": old, "to": order.status, "reason": "资料齐全"}, ) if commit: db.commit() def create_order( db: Session, current: User, *, order_no: str, shop: str = "", owner_id: int | None = None, account_username: str = "", gift_name: str = "", commodity_id: str = "", required_points: Any = None, home_images: Any = None, remark: str = "", draft: bool = False, require_verified: bool = True, takeover_platform_lease: bool = False, client: Any | None = None, commit: bool = True, ) -> DouyuExternalOrder: order_text = _text(order_no, max_length=64) if not order_text: raise CollabError("订单号不能为空", code="order_no_required") exists = ( db.query(DouyuExternalOrder) .filter(DouyuExternalOrder.order_no == order_text) .first() ) if exists is not None: raise CollabError("订单号已存在", status_code=409, code="order_no_exists") owner_user_id = int(owner_id) if owner_id is not None else int(current.id) owner = db.get(User, owner_user_id) if owner is None or not owner.is_active: raise CollabError( "负责人不存在或已停用", status_code=400, code="owner_invalid", ) images = normalize_images(home_images) explicit_points = _to_int(required_points) name, cid, points = _resolve_gift( db, gift_name=gift_name, commodity_id=commodity_id, required_points=required_points, ) order = DouyuExternalOrder( order_no=order_text, shop=_text(shop, max_length=64), owner_id=owner_user_id, account_username=_text(account_username, max_length=128), gift_name=name, commodity_id=cid, required_points=points, home_images=images, remark=_text(remark, max_length=512), status=STATUS_INCOMPLETE, points_threshold=POINTS_THRESHOLD_DEFAULT, created_by=current.id, updated_by=current.id, version=0, ) account: Account | None = None probe: dict[str, Any] | None = None if order.account_username: account = account_by_username(db, order.account_username) if account is None and not draft: raise CollabError( "斗鱼账号不存在,请先到账号管理导入/登录", code="account_not_found", ) if account is not None and not draft: config = resolve_config(db) manual_id = str(config.manual_id or "") rid = str(config.rid or "") act_alias = str(config.bind_act_alias or "") confirm_act_alias = str(config.confirm_act_alias or "") legacy_act_alias = str(config.legacy_act_alias or "") # order 还没有加入 Session。账号脱离 ORM 后提交,探针期间不占连接。 db.expunge(account) db.commit() db.add(account) probe = _probe_with_client( account, manual_id=manual_id, rid=rid, act_alias=act_alias, confirm_act_alias=confirm_act_alias, legacy_act_alias=legacy_act_alias, client=client, with_goods=True, ) apply_probe_snapshot( db, current, order, account, probe, source="douyu_collab.create", ) if explicit_points is None and name: live = next( ( item for item in (probe.get("goods") or []) if str(item.get("name") or item.get("commodityName") or "") == name ), None, ) if live is not None: live_cid = _text(live.get("commodity_id"), max_length=64) if live_cid: order.commodity_id = live_cid live_points = _to_int(live.get("score")) if live_points is not None: order.required_points = live_points elif account is not None: # 草稿不联网探针,但既然用户名已存在,先把内部账号关联上, # 后续补资料时不用再靠“用户名变化”触发解析。 order.account_id = int(account.id) order.account_uid = _text(account.uid, max_length=32) order.account_nickname = _text(account.nickname, max_length=128) if not draft and require_verified: missing: list[str] = [] if not order.shop: missing.append("店铺") if not order.account_username: missing.append("斗鱼账号") if not order.gift_name: missing.append("礼包") if not order.home_images: missing.append("主页截图") if missing: raise CollabError( f"下面这几项必须填:{'、'.join(missing)}", code="create_field_required", ) if account is None: raise CollabError("斗鱼账号不存在", code="account_not_found") if probe is None or not probe.get("ok") or not probe.get("bind_game_role"): message = (probe or {}).get("message") or "未读到绑定角色" raise CollabError( f"这个账号当前不能用:{message}", code="account_not_verified", ) if order.shop: ensure_shops_registered(db, current, [order.shop]) _ensure_order_account_lease( db, current, order, force_active=True, takeover_platform_lease=takeover_platform_lease, ) db.add(order) db.flush() record_audit( db, current, action="douyu:collab:create", target=f"douyu_external_order:{order.id}", detail={ "order_no": order.order_no, "shop": order.shop, "account_username": order.account_username, "account_id": order.account_id, "gift_name": order.gift_name, "required_points": order.required_points, "bind_game_role": order.bind_game_role, "home_images": len(order.home_images or []), "draft": bool(draft), }, ) _maybe_advance_to_recharge(db, current, order) if commit: db.commit() db.refresh(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 order.shop = _text(task.shop_name or task.shop_id, max_length=64) 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, order: DouyuExternalOrder, payload: Mapping[str, Any], *, expected_version: int | None = None, takeover_platform_lease: bool = False, client: Any | None = None, commit: bool = True, ) -> dict[str, Any]: _assert_mutable(order) _assert_version(order, expected_version) previous_account_id = int(order.account_id or 0) changes: dict[str, dict[str, Any]] = {} pending: dict[str, Any] = {} editable = { "order_no", "shop", "owner_id", "account_username", "gift_name", "commodity_id", "required_points", "remark", } for field in editable: if field not in payload: continue old = getattr(order, field) if field == "owner_id": new = int(payload[field]) if payload[field] is not None else None elif field == "required_points": new = _to_int(payload[field]) elif field == "order_no": new = _text(payload[field], max_length=64) if new and new != order.order_no: duplicate = ( db.query(DouyuExternalOrder.id) .filter( DouyuExternalOrder.order_no == new, DouyuExternalOrder.id != order.id, ) .first() ) if duplicate: raise CollabError( "订单号已存在", status_code=409, code="order_no_exists" ) else: new = _text(payload[field], max_length=512 if field == "remark" else 128) pending[field] = new if new != old: changes[field] = {"old": old, "new": new} if order.succeeded_at is not None: locked_changes = SUCCESS_PURCHASE_FIELDS.intersection(changes) if locked_changes: if current.role != "super_admin": raise CollabError( "订单已有成功记录,购买信息仅允许超级管理员修改", status_code=403, code="purchase_lock_admin_required", ) if payload.get("confirm_purchase_change") is not True: raise CollabError( "修改成功订单的购买信息需要二次确认", status_code=409, code="purchase_change_confirmation_required", ) for field, new in pending.items(): setattr(order, field, new) if "account_username" in payload and ( order.account_id is None or not order.bind_game_role or "account_username" in changes ): account = account_by_username(db, order.account_username) if account is None: if order.status == STATUS_INCOMPLETE: order.account_id = None order.account_uid = "" order.account_nickname = "" else: raise CollabError("斗鱼账号不存在", code="account_not_found") else: config = resolve_config(db) probe = _probe_with_client( account, manual_id=str(config.manual_id or ""), rid=str(config.rid or ""), act_alias=str(config.bind_act_alias or ""), confirm_act_alias=str(config.confirm_act_alias or ""), legacy_act_alias=str(config.legacy_act_alias or ""), client=client, with_goods=True, ) _ensure_order_account_lease( db, current, order, account_id=int(account.id), force_active=order.status in COLLAB_LEASE_STATUSES, takeover_platform_lease=takeover_platform_lease, ) apply_probe_snapshot( db, current, order, account, probe, source="douyu_collab.update", ) changes["account_id"] = { "old": previous_account_id or None, "new": int(account.id), } changes["bind_game_role"] = {"old": "", "new": order.bind_game_role} if "home_images" in payload: images = normalize_images(payload.get("home_images")) if images != (order.home_images or []): changes["home_images"] = { "old": len(order.home_images or []), "new": len(images), } order.home_images = images if order.gift_name and "commodity_id" in payload: _, cid, points = _resolve_gift( db, gift_name=order.gift_name, commodity_id=str(order.commodity_id or ""), required_points=order.required_points, ) order.commodity_id = cid if points is not None and order.required_points is None: order.required_points = points if changes: order.updated_by = current.id order.version = int(order.version or 0) + 1 record_audit( db, current, action="douyu:collab:update", target=f"douyu_external_order:{order.id}", detail=changes, ) _maybe_advance_to_recharge(db, current, order) if previous_account_id and previous_account_id != int(order.account_id or 0): _release_order_account_lease( db, current, order, reason="douyu_collab_account_changed", account_id=previous_account_id, ) if commit: db.commit() db.refresh(order) return changes def set_account( db: Session, current: User, order: DouyuExternalOrder, username: str, *, expected_version: int | None = None, takeover_platform_lease: bool = False, client: Any | None = None, commit: bool = True, ) -> dict[str, Any]: _assert_mutable(order) _assert_success_account_change_allowed(current, order) _assert_version(order, expected_version) account = account_by_username(db, username) if account is None: raise CollabError("斗鱼账号不存在", code="account_not_found") previous_account_id = int(order.account_id or 0) config = resolve_config(db) probe = _probe_with_client( account, manual_id=str(config.manual_id or ""), rid=str(config.rid or ""), act_alias=str(config.bind_act_alias or ""), confirm_act_alias=str(config.confirm_act_alias or ""), legacy_act_alias=str(config.legacy_act_alias or ""), client=client, with_goods=True, ) _ensure_order_account_lease( db, current, order, account_id=int(account.id), force_active=order.status in COLLAB_LEASE_STATUSES, takeover_platform_lease=takeover_platform_lease, ) apply_probe_snapshot( db, current, order, account, probe, source="douyu_collab.account", ) order.updated_by = current.id order.version = int(order.version or 0) + 1 record_audit( db, current, action="douyu:collab:account", target=f"douyu_external_order:{order.id}", detail={ "account_id": account.id, "account_username": account.username, "ck_status": probe.get("ck_status"), "role": probe.get("bind_game_role"), }, ) _maybe_advance_to_recharge(db, current, order) if previous_account_id and previous_account_id != int(order.account_id or 0): _release_order_account_lease( db, current, order, reason="douyu_collab_account_changed", account_id=previous_account_id, ) if commit: db.commit() db.refresh(order) return {"order": order, "probe": probe} def verify_order( db: Session, current: User, order: DouyuExternalOrder, *, client: Any | None = None, commit: bool = True, ) -> dict[str, Any]: _assert_mutable(order) account = account_by_id(db, order.account_id) or account_by_username( db, order.account_username ) if account is None: raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found") config = resolve_config(db) probe = _probe_with_client( account, manual_id=str(config.manual_id or ""), rid=str(config.rid or ""), act_alias=str(config.bind_act_alias or ""), confirm_act_alias=str(config.confirm_act_alias or ""), legacy_act_alias=str(config.legacy_act_alias or ""), client=client, with_goods=True, ) apply_probe_snapshot( db, current, order, account, probe, source="douyu_collab.verify", ) order.updated_by = current.id order.version = int(order.version or 0) + 1 record_audit( db, current, action="douyu:collab:verify", target=f"douyu_external_order:{order.id}", detail={ "account_id": account.id, "ck_status": probe.get("ck_status"), "role": probe.get("bind_game_role"), "fish_fin_balance": probe.get("fish_fin_balance"), "points": probe.get("manual_score"), "message": probe.get("message"), }, ) _maybe_advance_to_recharge(db, current, order) if commit: db.commit() db.refresh(order) return {"order": order, "probe": probe} def _status_audit_target(order: DouyuExternalOrder) -> str: return f"douyu_external_order:{order.id}" def _assert_ready_for_recharge( order: DouyuExternalOrder, *, entering_waiting: bool, allow_missing_role: bool = False, ) -> None: missing: list[str] = [] if not order.account_id or not order.account_username: missing.append("斗鱼账号") if not order.gift_name: missing.append("礼包") if not order.home_images: missing.append("主页截图") if not allow_missing_role and not order.bind_game_role: missing.append("绑定角色(先校验账号)") if missing: action = "进入待充值前" if entering_waiting else "更新充值状态前" raise CollabError( f"{action}还缺:{'、'.join(missing)}", code="recharge_precondition", ) def _restore_void_status( db: Session, current: User, order: DouyuExternalOrder, *, target: str, reason: str, commit: bool, ) -> DouyuExternalOrder: """超级管理员取消作废,并把订单转为指定状态。""" if current.role != "super_admin": raise CollabError( "仅超级管理员可取消作废", status_code=403, code="admin_required", ) if order.archived_at is not None: raise CollabError("已归档的订单不能改状态", code="order_archived") target_index = STAGE_INDEX.get(target) if target_index is not None and target_index >= STAGE_INDEX[STATUS_TO_RECHARGE]: _assert_ready_for_recharge( order, entering_waiting=target == STATUS_TO_RECHARGE, allow_missing_role=target == STATUS_RECHARGED, ) old_void_reason = order.void_reason or "" # 取消作废等于重新进入状态机:先清空旧流程时间,再按目标状态补当前时间。 for field in STATUS_TIMESTAMP_FIELDS.values(): setattr(order, field, None) if target_index is not None: for name, field in STATUS_TIMESTAMP_FIELDS.items(): if STAGE_INDEX[name] <= target_index: setattr(order, field, _now()) order.status = target if target == STATUS_DONE: _mark_order_succeeded(order) order.void_reason = "" order.updated_by = current.id order.version = int(order.version or 0) + 1 record_audit( db, current, action="douyu:collab:void_restore", target=_status_audit_target(order), detail={ "from": STATUS_VOID, "to": target, "previous_void_reason": old_void_reason, "reason": _text(reason, max_length=256), }, ) _sync_order_lease( db, current, order, reason="douyu_collab_void_restored", ) if commit: db.commit() db.refresh(order) return order def set_status( db: Session, current: User, order: DouyuExternalOrder, *, status: str, reason: str = "", rollback: bool = False, expected_version: int | None = None, commit: bool = True, ) -> DouyuExternalOrder: _assert_version(order, expected_version) target = _text(status, max_length=16) if target not in ORDER_STATUSES: raise CollabError("非法状态", code="status_invalid") if order.archived_at is not None: raise CollabError("已归档的订单不能改状态", code="order_archived") if order.status == STATUS_VOID: if target == STATUS_VOID: raise CollabError("已作废的订单不能改状态", code="order_void") return _restore_void_status( db, current, order, target=target, reason=reason, commit=commit, ) old = order.status now = _now() if target == STATUS_VOID: order.status = STATUS_VOID order.void_reason = _text(reason, max_length=256) order.updated_by = current.id order.version = int(order.version or 0) + 1 record_audit( db, current, action="douyu:collab:void", target=_status_audit_target(order), detail={"from": old, "reason": order.void_reason}, ) _sync_order_lease( db, current, order, reason="douyu_collab_void", reuse_active_lease=True, ) if commit: db.commit() db.refresh(order) return order if target == STATUS_FAILED: order.status = STATUS_FAILED order.updated_by = current.id order.version = int(order.version or 0) + 1 record_audit( db, current, action="douyu:collab:status", target=_status_audit_target(order), detail={"from": old, "to": target, "reason": _text(reason, max_length=256)}, ) _sync_order_lease( db, current, order, reason="douyu_collab_failed", reuse_active_lease=True, ) if commit: db.commit() db.refresh(order) return order if target == STATUS_POINTS_ERROR: order.status = STATUS_POINTS_ERROR order.updated_by = current.id order.version = int(order.version or 0) + 1 record_audit( db, current, action="douyu:collab:points_error", target=_status_audit_target(order), detail={"from": old, "reason": _text(reason, max_length=256)}, ) _sync_order_lease( db, current, order, reason="douyu_collab_points_error", reuse_active_lease=True, ) if commit: db.commit() db.refresh(order) return order if target == STATUS_ROLE_ERROR: order.status = STATUS_ROLE_ERROR order.updated_by = current.id order.version = int(order.version or 0) + 1 record_audit( db, current, action="douyu:collab:role_error", target=_status_audit_target(order), detail={"from": old, "reason": _text(reason, max_length=256)}, ) _sync_order_lease( db, current, order, reason="douyu_collab_role_error", reuse_active_lease=True, ) if commit: db.commit() db.refresh(order) return order if old in (STATUS_FAILED, STATUS_VOID, STATUS_ROLE_ERROR) and not rollback: raise CollabError( "从失败/角色异常/作废状态回流程必须显式回退", code="rollback_required", ) if target not in STAGE_INDEX: raise CollabError("该状态不能手工切换", code="status_not_manual") current_index = STAGE_INDEX.get(old) target_index = STAGE_INDEX.get(target) if current_index is None: current_index = -1 if target_index is None: raise CollabError("非法状态", code="status_invalid") if target_index < current_index and not rollback: raise CollabError("回退状态必须显式确认", code="rollback_required") if target_index >= STAGE_INDEX[STATUS_TO_RECHARGE]: _assert_ready_for_recharge( order, entering_waiting=target == STATUS_TO_RECHARGE, allow_missing_role=target == STATUS_RECHARGED, ) if target == STATUS_DONE: _mark_order_succeeded(order, now) if rollback: for name, field in STATUS_TIMESTAMP_FIELDS.items(): if STAGE_INDEX.get(name, -1) > target_index: setattr(order, field, None) else: for name, field in STATUS_TIMESTAMP_FIELDS.items(): if current_index < STAGE_INDEX[name] <= target_index: setattr(order, field, now) order.status = target order.updated_by = current.id order.version = int(order.version or 0) + 1 record_audit( db, current, action="douyu:collab:status", target=_status_audit_target(order), detail={ "from": old, "to": target, "rollback": bool(rollback), "reason": _text(reason, max_length=256), }, ) _sync_order_lease( db, current, order, reuse_active_lease=True, reason=( "douyu_collab_done" if target == STATUS_DONE else "douyu_collab_status_changed" ), ) if commit: db.commit() db.refresh(order) return order def _match_gift(records: list[dict[str, Any]], gift_name: str) -> int: name = _text(gift_name) if len(name) < 2: return 0 matched = 0 for record in records: record_name = _text( record.get("commodityName") or record.get("commodity_name") or "" ) if not record_name or len(record_name) < 2: continue if name in record_name or record_name in name: matched += 1 return matched def group_points_total(db: Session, order: DouyuExternalOrder) -> int: if not order.account_id: return int(order.required_points or 0) rows = ( db.query(DouyuExternalOrder) .filter( DouyuExternalOrder.account_id == order.account_id, DouyuExternalOrder.status.in_(POINTS_GROUP_STATUSES), DouyuExternalOrder.archived_at.is_(None), ) .all() ) return sum(int(item.required_points or 0) for item in rows) def query_activity( db: Session, current: User, order: DouyuExternalOrder, *, client: Any | None = None, source: str = "manual", include_records: bool = True, commit: bool = True, ) -> dict[str, Any]: """查询鱼翅、积分;``include_records`` 时同时查兑换记录并判定。""" account = account_by_id(db, order.account_id) or account_by_username( db, order.account_username ) if account is None: raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found") config = resolve_config(db) active_client = client or _client_for_account(account) probe = probe_account( account, config, client=active_client, session_checker=None, with_gold=True, with_elite_role=False, ) elite = (probe.get("elite") or {}).get("raw") or {} gold = { "gold": (probe.get("gold") or {}).get("balance"), } errors = list((probe.get("errors") or {}).values()) records: list[dict[str, Any]] = [] orders: list[dict[str, Any]] = [] if include_records: try: records = query_exchange_records( active_client, manual_id=str(config.manual_id or ""), limit=100, offset=0, ) except Exception as exc: # noqa: BLE001 errors.append(f"兑换记录: {exc}") try: orders = query_exchange_orders( active_client, manual_id=str(config.manual_id or ""), page=1, page_size=10, ) except Exception as exc: # noqa: BLE001 errors.append(f"锁单: {exc}") manual_score = _to_int(elite.get("manual_score")) fish = _to_int(gold.get("gold")) persist_probe_result( db, account, probe, current=current, source="douyu_collab.query_activity", record_event=False, ) if manual_score is not None: order.points_balance = manual_score account.points = manual_score if fish is not None: order.fish_fin_balance = fish account.gold_balance = fish account.updated_at = _now() required_total = group_points_total(db, order) surplus = ( (manual_score - required_total) if manual_score is not None and required_total > 0 else None ) order.points_required_total = required_total order.points_surplus = surplus order.points_checked_at = _now() threshold = normalize_threshold(order.points_threshold) order.points_threshold = threshold matched = 0 if not include_records: verdict = VERDICT_UNKNOWN message = ";".join(errors) if errors else "仅查询鱼翅与积分,未查询兑换记录" elif errors: verdict = VERDICT_UNKNOWN message = ";".join(errors) elif not order.gift_name: verdict = VERDICT_UNKNOWN message = "未填写礼包名,无法判定兑换结果" else: matched = _match_gift(records, order.gift_name) verdict = VERDICT_SUCCESS if matched else VERDICT_FAILED message = ( f"兑换记录命中「{order.gift_name}」{matched} 条" if matched else f"兑换记录里没有「{order.gift_name}」" ) reason = "" if surplus is not None: if surplus < 0: reason = "shortage" elif surplus > threshold: reason = "excess" else: reason = "ok" points_message = "" if required_total > 0 or manual_score is not None: points_message = ( f"积分 {manual_score if manual_score is not None else '-'} / " f"本账号未完成订单合计 {required_total},结余 " f"{surplus if surplus is not None else '-'}" ) order.points_check_reason = reason order.points_check_message = points_message order.points_check_detail = { "fish_fin_balance": fish, "points_balance": manual_score, "required_total": required_total, "surplus": surplus, "threshold": threshold, "errors": errors, "exchange_records": len(records), "locked_orders": len(orders), } metric = DouyuExternalOrderMetric( order_id=order.id, order_no=order.order_no, account_id=order.account_id, account_username=order.account_username, fish_fin_balance=fish, points_balance=manual_score, points_required_total=required_total, points_surplus=surplus, records_total=len(records), records_matched=matched, verdict=verdict, message=message, source=_text(source, max_length=16) or "manual", raw=_json_safe( { "elite": elite, "gold": gold, "records": records, "orders": orders, } ), created_by=current.id, ) db.add(metric) order.updated_by = current.id order.version = int(order.version or 0) + 1 record_audit( db, current, action="douyu:collab:activity", target=_status_audit_target(order), detail={ "scope": "activity" if include_records else "balances", "verdict": verdict, "message": message, "fish_fin_balance": fish, "points": manual_score, "required_total": required_total, "surplus": surplus, "records": len(records), }, ) # 只有查兑换记录时才做业务判定;余额查询保持只读,不动状态。 if include_records: if order.status == STATUS_SCRIPTED and verdict == VERDICT_SUCCESS: set_status( db, current, order, status=STATUS_DONE, reason=message, expected_version=None, commit=False, ) elif order.status == STATUS_SCRIPTED and verdict == VERDICT_FAILED: set_status( db, current, order, status=STATUS_FAILED, reason=message, expected_version=None, commit=False, ) elif order.status in (STATUS_RECHARGED, STATUS_SCRIPTED) and reason in ( "shortage", "excess", ): set_status( db, current, order, status=STATUS_POINTS_ERROR, reason=points_message, expected_version=None, commit=False, ) record_account_query( db, account, query_type="collab_activity", title="查询鱼翅与积分" if not include_records else "查询积分与兑换记录", ok=not bool(errors), detail={ "order_no": order.order_no, "include_records": include_records, "verdict": verdict, "records": len(records), "errors": errors[:10], }, actor_id=current.id, ) if commit: db.commit() db.refresh(order) db.refresh(metric) return { "order": order, "metric": metric, "scope": "activity" if include_records else "balances", "verdict": verdict, "message": message, "points_reason": reason, "points_message": points_message, "fish_fin_balance": fish, "points_balance": manual_score, "required_total": required_total, "surplus": surplus, "errors": errors, } 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=64) if not name or name in seen: continue seen.add(name) exists = ( db.query(DouyuCollabShop.id).filter(DouyuCollabShop.name == name).first() ) if exists: continue db.add( DouyuCollabShop( name=name, 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, 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, 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 = { "name": shop.name, "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 "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: db.query(DouyuExternalOrder).filter(DouyuExternalOrder.shop == old_name).update( {DouyuExternalOrder.shop: shop.name}, synchronize_session=False ) record_audit( db, current, action="douyu:collab:shop_update", target=f"douyu_collab_shop:{shop.id}", detail={ "old": old, "new": { "name": shop.name, "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 "", "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 = "", ): query = apply_order_visibility( query, DouyuExternalOrder, archive_scope=archive_scope, include_void=include_void, void_status=STATUS_VOID, ) if _text(status): query = query.filter(DouyuExternalOrder.status == _text(status)) if _text(shop): query = query.filter(DouyuExternalOrder.shop == _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)), ) ) search = _text(keyword) if search: pattern = f"%{search}%" query = query.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), ) ) 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( db: Session, current: User, ids: list[int], *, reason: str = "", ) -> dict[str, Any]: clean_ids = [int(item) for item in ids if int(item) > 0] if not clean_ids: return {"archived": 0} rows = ( db.query(DouyuExternalOrder).filter(DouyuExternalOrder.id.in_(clean_ids)).all() ) archived = 0 now = _now() for order in rows: if order.status not in ARCHIVABLE_STATUSES or order.archived_at is not None: continue order.archived_at = now order.archived_by = current.id order.archive_reason = _text(reason, max_length=256) order.updated_by = current.id order.version = int(order.version or 0) + 1 archived += 1 record_audit( db, current, action="douyu:collab:archive", target=_status_audit_target(order), detail={"reason": order.archive_reason}, ) _sync_order_lease( db, current, order, reason="douyu_collab_archived", ) db.commit() return {"archived": archived} def unarchive_orders(db: Session, current: User, ids: list[int]) -> dict[str, Any]: clean_ids = [int(item) for item in ids if int(item) > 0] if not clean_ids: return {"unarchived": 0} rows = ( db.query(DouyuExternalOrder).filter(DouyuExternalOrder.id.in_(clean_ids)).all() ) unarchived = 0 for order in rows: if order.archived_at is None: continue order.archived_at = None order.archived_by = None order.archive_reason = "" order.updated_by = current.id order.version = int(order.version or 0) + 1 unarchived += 1 record_audit( db, current, action="douyu:collab:unarchive", target=_status_audit_target(order), detail={}, ) _sync_order_lease( db, current, order, reason="douyu_collab_unarchived", ) db.commit() return {"unarchived": unarchived} def delete_order( db: Session, current: User, order: DouyuExternalOrder ) -> dict[str, Any]: order_no = order.order_no _release_order_account_lease( db, current, order, reason="douyu_collab_deleted", ) record_audit( db, current, action="douyu:collab:delete", target=f"douyu_external_order:{order.id}", detail={"order_no": order_no, "account": order.account_username}, ) 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, }