# ruff: noqa: F401 """斗鱼外部单协作台账服务。 核心边界(和虎牙外部 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 datetime import UTC, datetime, timedelta from typing import Any from unicodedata import normalize as unicode_normalize from loguru import logger from sqlalchemy import and_, 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_events_service import ( CATEGORY_OPS, EVENT_COLLAB_SYNCED, EVENT_LEASE_ACQUIRED, emit, ) from .account_exchange_sync_service import sync_exchange_records from .account_query_filters import ACTIVE_COLLAB_STATUSES from .account_sync_runner import WORK_STOREHOME_SYNC from .account_work_queue import enqueue_account_work from .audit_service import record_account_action, record_audit from .business_events import record_account_query from .collab_common import ( count_archived, order_visibility_expr, ) 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_collab_catalog import ( _resolve_gift, create_gift, delete_gift, get_gift, list_gift_names, list_gifts, refresh_activity_goods, serialized_goods, update_gift, ) from .douyu_collab_common import ( ACCOUNT_RECOMMEND_DEFAULT_SCAN_LIMIT, ACCOUNT_REPLACE_ROLES, ACTIVITY_METRIC_RECORD_LIMIT, ACTIVITY_RECORD_FETCH_LIMIT, ACTIVITY_RECORD_MAX_PAGES, ACTIVITY_RECORD_SETTLE_SECONDS, ACTIVITY_RECORD_TIME_SKEW_SECONDS, ARCHIVABLE_STATUSES, CK_EXPORT_ACTION, CK_EXPORT_BATCH_MAX, CK_INVALID, CK_LABELS, CK_UNVERIFIED, CK_VALID, COLLAB_LEASE_STATUSES, LEASE_PURPOSE_DOUYU_COLLAB, MAX_IMAGES, ORDER_STATUS_LABELS, ORDER_STATUSES, PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES, POINTS_GROUP_STATUSES, POINTS_THRESHOLD_DEFAULT, SOURCE_TYPE_PLATFORM_FULFILLMENT, STAGE_INDEX, STATUS_DONE, STATUS_FAILED, STATUS_FLOW, STATUS_INCOMPLETE, STATUS_POINTS_ERROR, STATUS_RECHARGED, STATUS_ROLE_ERROR, STATUS_SCRIPTED, STATUS_TIMESTAMP_FIELDS, STATUS_TO_RECHARGE, STATUS_VOID, SUCCESS_PURCHASE_FIELDS, USERNAME_EXPORT_BATCH_MAX, VERDICT_FAILED, VERDICT_SUCCESS, VERDICT_UNKNOWN, CollabError, _assert_account_replace_permission, _assert_account_replaceable, _assert_mutable, _assert_success_account_change_allowed, _assert_version, _client_for_account, _first_value, _json_safe, _mark_order_succeeded, _missing_for_recharge, _now, _text, _to_int, account_by_id, account_by_username, accounts_by_id, normalize_images, normalize_threshold, resolve_config, serialize_live_goods, users_by_id, ) from .douyu_collab_exports import export_cks, export_usernames from .douyu_collab_leases import ( _ensure_order_account_lease, _release_order_account_lease, _sync_order_lease, retain_lease_for_active_collab, ) from .douyu_collab_query import ( _apply_order_filters, _base_order_query, _metric_views, account_clusters, get_order, list_orders, order_metrics, order_timeline, serialize_metric, serialize_one, serialize_order, summary, ) from .douyu_collab_shops import ( _normalize_shop_aliases, _shop_match_values, create_shop, delete_shop, ensure_shops_registered, get_shop, list_shops, resolve_shop_name, update_shop, ) from .douyu_collab_sync import ( sync_platform_fulfillment_order, sync_platform_fulfillment_orders, ) from .douyu_goods_service import ( serialize_live_goods as _serialize_live_goods, ) from .douyu_goods_service import ( serialized_snapshots, upsert_goods_snapshot, ) from .file_service import build_file_url from .platform_fulfillment.account_selector import ( CapabilityAccount, acquire_account_lease, active_lease_for_account, capability_candidate_accounts, live_candidate_accounts, release_lease, ) 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 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) # 保留参数兼容旧调用;实时校验统一放到“使用此账号”的 set_account()。 del client_factory 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), 100, ), ) now = _now() candidates_by_id: dict[int, Account | CapabilityAccount] = {} 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 if not candidates_by_id: refresh_seeds = live_candidate_accounts( db, limit=effective_scan_limit, required_points=required, commodity_id=cid, prefer_unbound=True, empty_only=not include_rebindable, ) for account in refresh_seeds: enqueue_account_work( db, account_id=int(account.id), work_type=WORK_STOREHOME_SYNC, priority=20, due_at=now, reason=f"外部协作单推荐缺少商品能力: {cid}", payload={"commodity_id": cid, "order_id": int(order.id)}, ) if refresh_seeds: db.commit() else: for account in live_candidate_accounts( db, limit=effective_scan_limit, required_points=required, commodity_id="", 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") and account.ck_check_status == "valid" ] 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] output: list[dict[str, Any]] = [] result_limit = max(1, min(int(limit), 10)) for account in candidates: role_status = str(account.role_bind_status or ROLE_UNKNOWN) if role_status == ROLE_UNBOUND: match_type = "empty" match_label = "未绑定" elif role_status == ROLE_BOUND: if not include_rebindable: continue match_type = "rebind" match_label = "可换绑" else: continue elite_opened = account.elite_opened is True live_points = _to_int(account.points) 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})") output.append( { "account_id": int(account.id), # 后续“使用此账号”按内部 username 反查,不能用展示昵称。 "account_username": str(account.username or ""), "account_uid": str(account.uid or ""), "account_nickname": str( account.nickname or account.username or "" ), "ck_status": CK_VALID, "role_status": role_status, "bind_game_role": str(account.game_name or ""), "role_change_available_at": account.role_change_available_at, "points": live_points, "elite_opened": elite_opened, "match_type": match_type, "match_type_label": match_label, "ready": ready, "reasons": reasons, } ) if len(output) >= result_limit: break 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 ( f"本地暂无 {cid} 的新鲜商品能力,已加入后台刷新队列" if cid 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": len(candidates), "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 _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) shop_original_name = _text(shop, max_length=128) shop_name = resolve_shop_name(db, shop_original_name) 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=shop_name[:64], shop_original_name=shop_original_name, 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 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" ) elif field == "shop": new = _text(payload[field], max_length=128) 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 "shop" in pending: order.shop_original_name = str(pending["shop"] or "") order.shop = resolve_shop_name(db, order.shop_original_name)[:64] 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 _normalize_exchange_name(value: Any) -> str: return "".join(unicode_normalize("NFKC", _text(value)).casefold().split()) def _exchange_record_time(record: Mapping[str, Any]) -> datetime | None: raw = ( record.get("time") or record.get("exchangeTime") or record.get("exchange_time") or record.get("createTime") or record.get("create_time") ) if raw is None or raw == "": return None text = str(raw).strip() try: timestamp = float(text) except (TypeError, ValueError): try: parsed = datetime.fromisoformat(text) except ValueError: return None return ( parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC) ) if timestamp > 10_000_000_000: timestamp /= 1000 try: return datetime.fromtimestamp(timestamp, UTC) except (OverflowError, OSError, ValueError): return None def _matching_exchange_records( records: Sequence[Mapping[str, Any]], order: DouyuExternalOrder, ) -> list[dict[str, Any]]: """按商品 ID、精确名称和上脚本时间匹配,避免历史记录串单。""" expected_cid = _text(order.commodity_id) expected_name = _normalize_exchange_name(order.gift_name) not_before = order.scripted_at if isinstance(not_before, datetime): not_before = not_before - timedelta(seconds=ACTIVITY_RECORD_TIME_SKEW_SECONDS) matched: list[dict[str, Any]] = [] for record in records: if not isinstance(record, Mapping): continue record_cid = _text( record.get("commodityId") or record.get("commodity_id") or record.get("goodsId") ) if expected_cid and record_cid: identity_matched = record_cid == expected_cid else: record_name = _normalize_exchange_name( record.get("commodityName") or record.get("commodity_name") or record.get("goodsName") ) identity_matched = bool( expected_name and record_name and record_name == expected_name ) if not identity_matched: continue record_time = _exchange_record_time(record) if not_before is not None and (record_time is None or record_time < not_before): continue matched.append(dict(record)) 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 _load_exchange_records_for_orders( db: Session, orders: Sequence[DouyuExternalOrder], *, client: Any | None = None, ) -> list[dict[str, Any]]: if not orders: return [] order = orders[0] 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) result = sync_exchange_records( db, account, active_client, config_mapping(config), source="douyu_collab.activity", scopes=("elite",), limit=ACTIVITY_RECORD_FETCH_LIMIT, max_pages=ACTIVITY_RECORD_MAX_PAGES, ) return [ dict(record) for record in (result.get("records") or {}).get("elite", []) if isinstance(record, dict) ] def query_activity( db: Session, current: User, order: DouyuExternalOrder, *, client: Any | None = None, records: Sequence[Mapping[str, Any]] | None = None, record_query_error: str = "", source: str = "manual", include_records: bool = True, commit: bool = True, ) -> dict[str, Any]: """查兑换记录并判定;``include_records=False`` 时只刷新鱼翅和积分。""" 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") errors: list[str] = [] probe: dict[str, Any] = {} loaded_records: list[dict[str, Any]] = [] if include_records: if records is None: try: loaded_records = _load_exchange_records_for_orders( db, [order], client=client ) except Exception as exc: # noqa: BLE001 errors.append(f"兑换记录: {exc}") else: loaded_records = [dict(record) for record in records] if record_query_error: errors.append(f"兑换记录: {record_query_error}") manual_score = _to_int(order.points_balance) fish = _to_int(order.fish_fin_balance) required_total = _to_int(order.points_required_total) surplus = _to_int(order.points_surplus) points_reason = _text(order.points_check_reason) points_message = _text(order.points_check_message) threshold = normalize_threshold(order.points_threshold) else: 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()) 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 points_reason = "" if surplus is not None: if surplus < 0: points_reason = "shortage" elif surplus > threshold: points_reason = "excess" else: points_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 = points_reason order.points_check_message = points_message matched = 0 matched_records: list[dict[str, Any]] = [] now = _now() 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_records = _matching_exchange_records(loaded_records, order) matched = len(matched_records) if matched: verdict = VERDICT_SUCCESS message = f"兑换记录命中「{order.gift_name}」{matched} 条" elif order.status != STATUS_SCRIPTED: verdict = VERDICT_UNKNOWN message = "订单当前状态不再由兑换记录自动判定" elif order.scripted_at is None: verdict = VERDICT_UNKNOWN message = "订单尚未记录上脚本时间,暂不自动判定" elif now < order.scripted_at + timedelta( seconds=ACTIVITY_RECORD_SETTLE_SECONDS ): verdict = VERDICT_UNKNOWN message = f"兑换记录暂未命中「{order.gift_name}」,仍在结算等待期" else: verdict = VERDICT_FAILED message = f"兑换记录里没有「{order.gift_name}」" if not include_records: order.points_check_detail = { "fish_fin_balance": fish, "points_balance": manual_score, "required_total": required_total, "surplus": surplus, "threshold": threshold, "errors": errors, "exchange_records": 0, "locked_orders": 0, } 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(loaded_records), records_matched=matched, verdict=verdict, message=message, source=_text(source, max_length=16) or "manual", raw=_json_safe( { "verdict": verdict, "scope": "activity" if include_records else "balances", "probe": probe, "records_count": len(loaded_records), "records": loaded_records[:ACTIVITY_METRIC_RECORD_LIMIT], "matched": matched_records[:5], "record_query_error": record_query_error, } ), 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(loaded_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, ) 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(loaded_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": points_reason, "points_message": points_message, "fish_fin_balance": fish, "points_balance": manual_score, "required_total": required_total, "surplus": surplus, "errors": errors, } def query_activity_batch( db: Session, current: User, orders: Sequence[DouyuExternalOrder], *, source: str = "batch", ) -> list[dict[str, Any]]: """按账号复用兑换记录请求,再逐单用商品与时间窗口判定。""" orders_by_account: dict[tuple[str, int | str], list[DouyuExternalOrder]] = {} for order in orders: account_key: tuple[str, int | str] if order.account_id: account_key = ("id", int(order.account_id)) else: account_key = ("username", _text(order.account_username).casefold()) orders_by_account.setdefault(account_key, []).append(order) records_by_account: dict[ tuple[str, int | str], tuple[list[dict[str, Any]], str] ] = {} for account_key, account_orders in orders_by_account.items(): try: records_by_account[account_key] = ( _load_exchange_records_for_orders(db, account_orders), "", ) except Exception as exc: # noqa: BLE001 - 账号级错误复用到同账号订单 records_by_account[account_key] = ([], str(exc)) results: list[dict[str, Any]] = [] for order in orders: if order.account_id: account_key = ("id", int(order.account_id)) else: account_key = ("username", _text(order.account_username).casefold()) records, record_error = records_by_account[account_key] try: result = query_activity( db, current, order, records=records, record_query_error=record_error, source=source, ) results.append( { "id": int(order.id), "success": True, "verdict": result["verdict"], "message": result["message"], } ) except Exception as exc: # noqa: BLE001 - 批量逐单隔离 db.rollback() results.append({"id": int(order.id), "success": False, "message": str(exc)}) return results 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}