优化(斗鱼预售台账): 统一命名并同步客户主页图

同步履约客户游戏主页截图,兼容 order_site 绝对 URL 与 objectKey;统一预售台账用户可见文案和保护标签;移除 CK 检测与重登前端页面入口。
This commit is contained in:
yml
2026-11-26 19:11:30 +08:00
parent 7a20c63464
commit 82e1944a33
44 changed files with 204 additions and 428 deletions
@@ -77,7 +77,7 @@ EVENT_TASK_STOPPED = "task_stopped" # 斗鱼账号任务停止/中断
EVENT_QUERY_COMPLETED = "query_completed" # 同步查询完成(含部分失败)
EVENT_LEASE_ACQUIRED = "lease_acquired" # 分配履约账号使用权
EVENT_LEASE_RELEASED = "lease_released" # 释放履约账号使用权
EVENT_COLLAB_SYNCED = "collab_synced" # 直播履约任务同步到外部单协作
EVENT_COLLAB_SYNCED = "collab_synced" # 直播履约任务同步到斗鱼预售台账
# 有符号金额的事件类型(用于页面「累计充值/累计消耗」):
# 充值为正、兑换为负,其余不计入金额统计。
@@ -4,7 +4,7 @@
关系动态计算:
- ``presale_bound``:仍在履约中的预售任务所分配的账号;
- ``collab_bound``:仍在进行中的斗鱼外部协作单所绑定的账号。
- ``collab_bound``:仍在进行中的斗鱼预售台账订单所绑定的账号。
配置保存在 ``ck_health.config["protection_groups"]``。这样不需要扩容账号表,
也不会污染高价值/普通的库存供给口径。目标数量用于预警缺口;只要组已启用,
@@ -49,8 +49,8 @@ GROUP_DEFINITIONS: dict[str, dict[str, Any]] = {
"auto_relogin": True,
},
"collab_bound": {
"label": "协作单绑定账号",
"description": "未归档且仍在进行中的斗鱼外部协作单所绑定账号",
"label": "预售台账绑定账号",
"description": "未归档且仍在进行中的斗鱼预售台账订单绑定账号",
"enabled": True,
"target_count": 0,
"probe_interval_minutes": DEFAULT_PROBE_INTERVAL_MINUTES,
+1 -1
View File
@@ -234,7 +234,7 @@ def register_default_jobs() -> None:
JobSpec(
key=LEASE_CK_REFRESH_KEY,
title="履约 CK 到期前刷新",
# 处理仍有效、但预测 24h 内到期的全部履约保护账号(预售 / 协作单 / 生效租约),
# 处理仍有效、但预测 24h 内到期的全部履约保护账号(预售 / 预售台账 / 生效租约),
# 提前续 CK,不参与普通失效重登的批次。
interval_seconds=600,
run_interval_seconds=600,
@@ -6,7 +6,7 @@
范围:
- 预售履约任务分配的账号、进行中的斗鱼外部协作单绑定账号;
- 预售履约任务分配的账号、进行中的斗鱼预售台账订单绑定账号;
- `account_leases.status=active` 且 purpose 为 `platform_fulfillment` / `douyu_collab`;
- `ck_check_status=valid`、有 Cookie、可自动管理、没有在途登录;
- 预测到期时间 <= now + 24h(`ck_expected_expires_at` 或 `cookie_updated_at + 7d`);
@@ -56,7 +56,7 @@ def due_lease_account_query(
db: Session,
now: datetime | None = None,
):
"""到期前 24h 的履约保护账号查询(预售 / 协作单 / 生效租约共用)。"""
"""到期前 24h 的履约保护账号查询(预售 / 预售台账 / 生效租约共用)。"""
moment = now or datetime.now(UTC)
cutoff = moment + REFRESH_BEFORE
protection = load_protection_snapshot(db)
@@ -125,7 +125,7 @@ def run_platform_fulfillment_lease_reaper(
# 分配并发/重试可能留下「batch_id 指向 task,但 task 实际用另一个账号/租约」
# 的孤儿 active 租约。它不会自然过期(expires_at 常为 NULL),会永久占住账号,
# 并让协作单接管时报“任务与租约不一致”。这里按 task 的真实归属回收。
# 并让预售单接管时报“任务与租约不一致”。这里按 task 的真实归属回收。
# 注意:不能在过滤孤儿前先 limit active 租约。生产有 3,900+ 条 active
# pf 租约,先取前 500 条会被合法租约占满,后面的孤儿永远轮不到。
# 这里直接用 SQL 关联出「task 不存在 / task 账号或租约不一致」。
@@ -174,7 +174,7 @@ def run_platform_fulfillment_lease_reaper(
task.lease_id = None
task.execution_status = "manual_required"
task.issue_code = "lease_expired_collab_handoff"
task.last_error = "平台租约已到期,账号已转外部协作人工处理"
task.last_error = "平台租约已到期,账号已转预售台账人工处理"
task.updated_at = moment
affected += 1
if released_ids:
+2 -2
View File
@@ -1,4 +1,4 @@
"""斗鱼外部单协作的礼包、商品解析与活动商品刷新。"""
"""斗鱼预售台账的礼包、商品解析与活动商品刷新。"""
from __future__ import annotations
@@ -225,7 +225,7 @@ def delete_gift(
)
if used:
raise CollabError(
f"还有 {used} 个协作单使用「{gift_name}」,请先停用或改名",
f"还有 {used} 个预售单使用「{gift_name}」,请先停用或改名",
code="gift_in_use",
)
record_audit(
+1 -1
View File
@@ -1,4 +1,4 @@
"""斗鱼外部单协作的共享状态、校验与轻量查询。"""
"""斗鱼预售台账的共享状态、校验与轻量查询。"""
from __future__ import annotations
+1 -1
View File
@@ -1,4 +1,4 @@
"""斗鱼外部单协作台账的进程内实时事件总线。
"""斗鱼预售台账的进程内实时事件总线。
写接口提交成功后只发布「台账失效」事件,前端收到后按自己的筛选静默重拉,
不在事件里携带整行数据。当前生产单 worker,进程内队列足够;多实例时再换 Redis。
+5 -5
View File
@@ -1,4 +1,4 @@
"""斗鱼外部单协作的账号凭据与用户名导出。"""
"""斗鱼预售台账的账号凭据与用户名导出。"""
from __future__ import annotations
@@ -28,9 +28,9 @@ def export_cks(
*,
commit: bool = True,
) -> dict[str, Any]:
"""导出协作单关联内部账号的 **CK 明文**(前端写剪贴板用)。
"""导出预售单关联内部账号的 **CK 明文**(前端写剪贴板用)。
斗鱼协作单本身不存 CK,导出的始终是关联 ``accounts.cookie`` 的实时值。
斗鱼预售单本身不存 CK,导出的始终是关联 ``accounts.cookie`` 的实时值。
和虎牙台账保持同一口径:
1. 需要独立权限点 ``douyu:collab:ck_export``;
@@ -59,7 +59,7 @@ def export_cks(
{
"id": order_id,
"order_no": "",
"reason": "协作单不存在或已删除",
"reason": "预售单不存在或已删除",
}
)
continue
@@ -151,7 +151,7 @@ def export_usernames(
{
"id": order_id,
"order_no": "",
"reason": "协作单不存在或已删除",
"reason": "预售单不存在或已删除",
}
)
continue
+6 -6
View File
@@ -1,4 +1,4 @@
"""斗鱼外部单协作的账号占用、平台租约接管与释放。"""
"""斗鱼预售台账的账号占用、平台租约接管与释放。"""
from __future__ import annotations
@@ -120,7 +120,7 @@ def _takeover_platform_lease_for_collab(
order: DouyuExternalOrder,
lease: AccountLease,
) -> AccountLease:
"""外部协作显式接管平台租约,并在同一事务内把平台任务转人工。"""
"""预售单显式接管平台租约,并在同一事务内把平台任务转人工。"""
if not user_has_permission(current, "platform_fulfillment:use"):
raise CollabError(
"没有接管平台履约账号的权限",
@@ -136,7 +136,7 @@ def _takeover_platform_lease_for_collab(
)
if platform_task.execution_status in {"completed", "cancelled"}:
raise CollabError(
f"平台履约任务 #{platform_task.id} 已结束,不能由协作单接管",
f"平台履约任务 #{platform_task.id} 已结束,不能由预售单接管",
status_code=409,
code="platform_task_not_takeoverable",
)
@@ -186,7 +186,7 @@ def _takeover_platform_lease_for_collab(
db,
account_id=int(lease.account_id),
event_type=EVENT_LEASE_ACQUIRED,
title=f"外部协作接管平台履约账号:{order.order_no}",
title=f"预售单接管平台履约账号:{order.order_no}",
category=CATEGORY_OPS,
detail={
"lease_id": lease.id,
@@ -385,7 +385,7 @@ def _sync_order_lease(
else "平台履约任务"
)
raise CollabError(
f"该账号当前被{task_label}占用,请先由协作单确认接管",
f"该账号当前被{task_label}占用,请先由预售单确认接管",
status_code=409,
code="account_lease_conflict",
)
@@ -473,7 +473,7 @@ def retain_lease_for_active_collab(
db,
account_id=int(account_id),
event_type=EVENT_LEASE_ACQUIRED,
title=f"外部协作接管账号占用:{order.order_no}",
title=f"预售单接管账号占用:{order.order_no}",
category=CATEGORY_OPS,
detail={
"lease_id": active_lease.id,
+2 -2
View File
@@ -1,4 +1,4 @@
"""斗鱼外部单协作的查询、序列化、汇总与时间线。"""
"""斗鱼预售台账的查询、序列化、汇总与时间线。"""
from __future__ import annotations
@@ -372,7 +372,7 @@ def get_order(db: Session, order_id: int) -> DouyuExternalOrder:
db.query(DouyuExternalOrder).filter(DouyuExternalOrder.id == order_id).first()
)
if order is None:
raise CollabError("协作单不存在", status_code=404, code="order_not_found")
raise CollabError("预售单不存在", status_code=404, code="order_not_found")
return order
def serialize_one(db: Session, order: DouyuExternalOrder) -> dict[str, Any]:
+4 -4
View File
@@ -1,9 +1,9 @@
# ruff: noqa: F401
"""斗鱼外部单协作台账服务。
"""斗鱼预售台账服务。
核心边界(和虎牙外部 CK 台账的区别):
1. **一行 = 一单 = 一个内部斗鱼账号**。协作单只存 ``account_id`` 和用户名快照,
1. **一行 = 一单 = 一个内部斗鱼账号**。预售单只存 ``account_id`` 和用户名快照,
**不复制 CK**;所有查询实时读 ``accounts.cookie``,账号换 CK 后自动生效。
2. 鱼翅和手册积分是两笔资产:先充值鱼翅,再用鱼翅赠送精英令换积分。
余额查询单独返回两笔资产,兑换记录查询不混查余额。
@@ -385,7 +385,7 @@ def unlink_account(
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)
@@ -520,7 +520,7 @@ def recommend_accounts(
work_type=WORK_STOREHOME_SYNC,
priority=20,
due_at=now,
reason=f"外部协作单推荐缺少商品能力: {cid}",
reason=f"预售台账推荐缺少商品能力: {cid}",
payload={"commodity_id": cid, "order_id": int(order.id)},
)
if refresh_seeds:
+2 -2
View File
@@ -1,4 +1,4 @@
"""斗鱼外部单协作的店铺字典与人工别名映射。"""
"""斗鱼预售台账的店铺字典与人工别名映射。"""
from __future__ import annotations
@@ -229,7 +229,7 @@ def delete_shop(
)
if used:
raise CollabError(
f"还有 {used} 个协作单使用「{shop_name}」,请先改名或停用",
f"还有 {used} 个预售单使用「{shop_name}」,请先改名或停用",
code="shop_in_use",
)
record_audit(
+43 -7
View File
@@ -1,4 +1,4 @@
"""直播账号履约任务向斗鱼外部单协作的幂等投影。"""
"""直播账号履约任务向斗鱼预售台账的幂等投影。"""
from __future__ import annotations
@@ -24,6 +24,7 @@ from .douyu_binding import (
resolve_fulfillment_binding,
)
from .douyu_collab_common import (
MAX_IMAGES,
POINTS_THRESHOLD_DEFAULT,
SOURCE_TYPE_PLATFORM_FULFILLMENT,
STATUS_DONE,
@@ -79,18 +80,50 @@ def _platform_fulfillment_gift(
def _platform_fulfillment_order_no(task: PlatformFulfillmentTask) -> str:
"""外部协作单直接使用 order_site 的真实平台订单号。"""
"""预售单直接使用 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 _platform_fulfillment_home_images(
task: PlatformFulfillmentTask,
) -> list[str]:
"""把 order_site 的客户主页截图投影成预售台账可展示的图片引用。
order_site 快照同时带 ``url`` 和 ``objectKey``。两者可能属于 order_site
自己的文件桶,因此优先保存绝对 URL,live-hub 回读时直接使用;只有没有
URL 的旧数据才退回 object key。
"""
images: list[str] = []
for item in task.customer_home_images or []:
if isinstance(item, str):
reference = item
elif isinstance(item, dict):
reference = (
item.get("url")
or item.get("thumbnailUrl")
or item.get("thumbnail_url")
or item.get("objectKey")
or item.get("object_key")
or ""
)
else:
continue
image = _text(reference, max_length=512)
if image and image not in images:
images.append(image)
if len(images) >= MAX_IMAGES:
break
return images
def _apply_platform_fulfillment_binding(
db: Session,
order: DouyuExternalOrder,
@@ -98,7 +131,7 @@ def _apply_platform_fulfillment_binding(
*,
overwrite: bool,
) -> None:
"""把履约任务已确认的本地绑定结果投影到协作单,不额外联网。"""
"""把履约任务已确认的本地绑定结果投影到预售单,不额外联网。"""
bind_task = (
db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
if task.bind_task_id
@@ -161,7 +194,7 @@ def sync_platform_fulfillment_order(
*,
commit: bool = True,
) -> tuple[DouyuExternalOrder, str]:
"""把一条直播履约任务幂等同步为斗鱼外部协作单。"""
"""把一条直播履约任务幂等同步为斗鱼预售台账订单。"""
if task.source_system != "order_site":
raise CollabError("仅支持同步 order_site 履约任务", code="source_unsupported")
@@ -198,6 +231,7 @@ def sync_platform_fulfillment_order(
else None
)
gift_name, commodity_id, required_points = _platform_fulfillment_gift(db, task)
home_images = _platform_fulfillment_home_images(task)
if order is None:
order = DouyuExternalOrder(
@@ -229,6 +263,8 @@ def sync_platform_fulfillment_order(
order.gift_name = gift_name
order.commodity_id = commodity_id
order.required_points = required_points
if home_images:
order.home_images = home_images
if account is not None and (
created or (order.account_id is None and not order.account_username)
):
@@ -270,7 +306,7 @@ def sync_platform_fulfillment_order(
account=linked_account,
action="douyu:collab:sync_from_platform_fulfillment",
event_type=EVENT_COLLAB_SYNCED,
title=f"同步外部单协作:{order.order_no}",
title=f"同步斗鱼预售台账:{order.order_no}",
target=f"douyu_external_order:{order.id}",
detail=audit_detail,
)
@@ -358,7 +394,7 @@ def sync_platform_fulfillment_orders(
}
)
except Exception: # noqa: BLE001 - 批量边界需隔离单条未知故障
logger.exception("同步直播履约任务 {} 到斗鱼外部协作失败", task_id)
logger.exception("同步直播履约任务 {} 到斗鱼预售台账失败", task_id)
result["failed"] += 1
result["items"].append(
{
+14 -3
View File
@@ -20,7 +20,7 @@ import secrets
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any
from urllib.parse import quote
from urllib.parse import quote, urlsplit
from loguru import logger
from PIL import Image, ImageOps, features
@@ -152,8 +152,19 @@ def image_variant_fallback_keys(object_key: str, variant: str) -> list[str]:
def build_file_url(object_key: str, variant: str = "") -> str:
"""文件访问地址(走后端代理,不暴露对象存储直链)。"""
url = f"/api/files/object?key={quote(normalize_object_key(object_key), safe='')}"
"""文件访问地址。
本系统上传的图片仍走 ``/api/files/object`` 代理;order_site 已在客户资料
快照里提供绝对 URL 的图片则原样返回,避免把外部地址误当成 live-hub 的
object key 再包一层查询参数。
"""
raw = str(object_key or "").strip()
parsed = urlsplit(raw)
if parsed.scheme.lower() in {"http", "https"} and parsed.netloc:
return raw
if raw.startswith("/") and not raw.startswith("//"):
return raw
url = f"/api/files/object?key={quote(normalize_object_key(raw), safe='')}"
if variant:
url = f"{url}&variant={quote(variant, safe='')}"
return url
+1 -1
View File
@@ -31,7 +31,7 @@ CATEGORY_MANUAL = "manual_login"
CATEGORY_ONBOARDING = "onboarding"
CATEGORY_RELOGIN_HIGH = "relogin_high_value"
CATEGORY_RELOGIN_ORDINARY = "relogin_ordinary"
#: 履约保护目标(预售/协作单/生效租约绑定账号)的失效重登:独立分类与配额保护,
#: 履约保护目标(预售/预售台账/生效租约绑定账号)的失效重登:独立分类与配额保护,
#: 不被全库普通重登吃干当天登录次数。
CATEGORY_RELOGIN_PROTECTED = "relogin_protected"
CATEGORY_ACCOUNT_CHECK = "account_check"
@@ -494,7 +494,7 @@ def _allocate_task_from_capability(
elif retry_reason == "account_pool_busy":
task.issue_code = "account_pool_busy"
task.last_error = (
"已有具备兑换资格的账号,但当前被租约或外部协作单占用;"
"已有具备兑换资格的账号,但当前被租约或预售台账占用;"
"后台正在继续补充可用账号"
)
else:
@@ -693,7 +693,7 @@ def restore_cancelled_task(
):
raise HTTPException(
status_code=409,
detail="关联外部协作单已在人工处理,请继续使用外部协作单",
detail="关联预售单已在人工处理,请继续使用斗鱼预售台账",
)
mapping = _mapping_for_sku(db, task.internal_sku_key)
@@ -745,12 +745,12 @@ def prepare_platform_task_for_collab_takeover(
current: User,
collab_order_no: str,
) -> None:
"""把平台履约任务转为人工,但不提交事务;由协作单接管流程原子提交。"""
"""把平台履约任务转为人工,但不提交事务;由预售单接管流程原子提交。"""
if task.execution_status in {"completed", "cancelled"}:
raise HTTPException(status_code=409, detail="已结束的履约任务不能被协作单接管")
raise HTTPException(status_code=409, detail="已结束的履约任务不能被预售单接管")
account_id = task.account_id
lease_id = task.lease_id
reason = f"外部协作单 {collab_order_no} 人工接管账号"
reason = f"预售单 {collab_order_no} 人工接管账号"
task.account_id = None
task.lease_id = None
task.bind_task_id = None
@@ -791,7 +791,7 @@ def release_task_to_manual(
task = _load_task(db, task_id)
if task.execution_status in {"completed", "cancelled"}:
raise HTTPException(status_code=409, detail="已结束任务不能转人工")
manual_reason = reason.strip()[:2000] or "以外部单协作人工处理为准"
manual_reason = reason.strip()[:2000] or "以斗鱼预售台账人工处理为准"
account_id = task.account_id
lease_id = task.lease_id
lease = (
@@ -58,7 +58,7 @@ def _retain_lease_for_active_collab(
current: User,
reason: str,
) -> AccountLease | None:
"""平台释放账号前,把仍在活动的协作单占用接续到同一租约。"""
"""平台释放账号前,把仍在活动的预售单占用接续到同一租约。"""
if lease is None or not task.account_id:
return None
from ..douyu_collab_service import retain_lease_for_active_collab
@@ -36,7 +36,7 @@ ROLE_LOCK_WINDOW = timedelta(days=7)
_BEIJING = ZoneInfo("Asia/Shanghai")
_LEASE_PURPOSE_LABELS = {
"douyu_collab": "协作单",
"douyu_collab": "预售台账",
"platform_fulfillment": "履约单",
"exchange": "兑换单",
}
@@ -142,7 +142,7 @@ def _apply_task_lease_policy(
return active_lease
if str(task.execution_status or "") in {"completed", "cancelled"}:
# 终态释放前先检查活动外部协作单。若账号仍被协作单使用,租约转换为
# 终态释放前先检查活动预售单。若账号仍被预售单使用,租约转换为
# douyu_collab 并保持无限,不能被平台 TTL 抢走。
from ..douyu_collab_service import retain_lease_for_active_collab