refactor(collab): 拆分斗鱼虎牙协作服务与页面配置
This commit is contained in:
@@ -0,0 +1,349 @@
|
||||
"""虎牙外部 CK 协作台账的共享状态、字段校验与行级工具。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Sequence
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from ..models import HuyaExternalOrder, User
|
||||
from .file_storage import normalize_object_key
|
||||
|
||||
STATUS_INCOMPLETE = "incomplete"
|
||||
STATUS_TO_RECHARGE = "to_recharge"
|
||||
STATUS_RECHARGED = "recharged"
|
||||
STATUS_SCRIPTED = "scripted"
|
||||
STATUS_DONE = "done"
|
||||
STATUS_POINTS_ERROR = "points_error"
|
||||
STATUS_FAILED = "failed"
|
||||
STATUS_VOID = "void"
|
||||
|
||||
ORDER_STATUSES: tuple[str, ...] = (
|
||||
STATUS_INCOMPLETE,
|
||||
STATUS_TO_RECHARGE,
|
||||
STATUS_RECHARGED,
|
||||
STATUS_SCRIPTED,
|
||||
STATUS_DONE,
|
||||
STATUS_POINTS_ERROR,
|
||||
STATUS_FAILED,
|
||||
STATUS_VOID,
|
||||
)
|
||||
|
||||
ORDER_STATUS_LABELS = {
|
||||
STATUS_INCOMPLETE: "待补资料",
|
||||
STATUS_TO_RECHARGE: "待充值",
|
||||
STATUS_RECHARGED: "已充值",
|
||||
STATUS_SCRIPTED: "已上脚本",
|
||||
STATUS_DONE: "抢购成功",
|
||||
STATUS_POINTS_ERROR: "积分异常",
|
||||
STATUS_FAILED: "抢购失败",
|
||||
STATUS_VOID: "已作废",
|
||||
"pending": "待处理(历史)",
|
||||
"bound": "已确认绑定(历史)",
|
||||
}
|
||||
|
||||
STATUS_FLOW: tuple[str, ...] = (
|
||||
STATUS_INCOMPLETE,
|
||||
STATUS_TO_RECHARGE,
|
||||
STATUS_RECHARGED,
|
||||
STATUS_SCRIPTED,
|
||||
STATUS_DONE,
|
||||
)
|
||||
|
||||
NEXT_STATUS = {
|
||||
STATUS_INCOMPLETE: STATUS_TO_RECHARGE,
|
||||
STATUS_TO_RECHARGE: STATUS_RECHARGED,
|
||||
STATUS_RECHARGED: STATUS_SCRIPTED,
|
||||
STATUS_SCRIPTED: STATUS_DONE,
|
||||
}
|
||||
|
||||
STAGE_INDEX = {
|
||||
STATUS_INCOMPLETE: 0,
|
||||
STATUS_TO_RECHARGE: 1,
|
||||
STATUS_RECHARGED: 2,
|
||||
STATUS_SCRIPTED: 3,
|
||||
STATUS_DONE: 4,
|
||||
}
|
||||
|
||||
STATUS_TIMESTAMP_FIELDS = {
|
||||
STATUS_RECHARGED: "recharged_at",
|
||||
STATUS_SCRIPTED: "scripted_at",
|
||||
STATUS_DONE: "done_at",
|
||||
}
|
||||
|
||||
ARCHIVABLE_STATUSES: tuple[str, ...] = (STATUS_DONE,)
|
||||
ARCHIVE_BATCH_MAX = 5000
|
||||
PROBE_BATCH_MAX = 50
|
||||
|
||||
RECHARGE_POINTS_THRESHOLD_DEFAULT = 100
|
||||
RECHARGE_POINTS_THRESHOLD_MAX = 1_000_000
|
||||
RECHARGE_POINTS_CONFIRM_DELAY_SECONDS = 30
|
||||
|
||||
CK_UNVERIFIED = "unverified"
|
||||
CK_VALID = "valid"
|
||||
CK_INVALID = "invalid"
|
||||
CK_DISABLED = "disabled"
|
||||
|
||||
CK_STATUSES: tuple[str, ...] = (CK_UNVERIFIED, CK_VALID, CK_INVALID, CK_DISABLED)
|
||||
|
||||
CK_STATUS_LABELS = {
|
||||
CK_UNVERIFIED: "未验证",
|
||||
CK_VALID: "有效",
|
||||
CK_INVALID: "已失效",
|
||||
CK_DISABLED: "已停用",
|
||||
}
|
||||
|
||||
CK_CHECKED_STATUSES = (CK_VALID, CK_INVALID)
|
||||
|
||||
VERDICT_SUCCESS = "success"
|
||||
VERDICT_FAILED = "failed"
|
||||
VERDICT_UNKNOWN = "unknown"
|
||||
VERDICT_NOT_QUERIED = ""
|
||||
VERDICT_LABELS = {
|
||||
VERDICT_SUCCESS: "兑换成功",
|
||||
VERDICT_FAILED: "兑换失败",
|
||||
VERDICT_UNKNOWN: "无法判定",
|
||||
VERDICT_NOT_QUERIED: "未判定",
|
||||
}
|
||||
|
||||
ACTIVITY_SCOPE_BOTH = "both"
|
||||
ACTIVITY_SCOPE_SCORE = "score"
|
||||
ACTIVITY_SCOPE_RECORDS = "records"
|
||||
ACTIVITY_SCOPES: tuple[str, ...] = (
|
||||
ACTIVITY_SCOPE_BOTH,
|
||||
ACTIVITY_SCOPE_SCORE,
|
||||
ACTIVITY_SCOPE_RECORDS,
|
||||
)
|
||||
ACTIVITY_SCOPE_LABELS = {
|
||||
ACTIVITY_SCOPE_BOTH: "积分 + 兑换记录",
|
||||
ACTIVITY_SCOPE_SCORE: "积分",
|
||||
ACTIVITY_SCOPE_RECORDS: "兑换记录",
|
||||
}
|
||||
|
||||
EDITABLE_FIELDS: tuple[str, ...] = (
|
||||
"order_no",
|
||||
"shop",
|
||||
"owner_id",
|
||||
"bind_douyu_account",
|
||||
"bind_douyu_uid",
|
||||
"gift_name",
|
||||
"required_points",
|
||||
"remark",
|
||||
)
|
||||
|
||||
FIELD_LIMITS = {
|
||||
"order_no": 64,
|
||||
"shop": 64,
|
||||
"shop_remark": 255,
|
||||
"bind_douyu_account": 128,
|
||||
"bind_douyu_uid": 32,
|
||||
"gift_name": 128,
|
||||
"remark": 512,
|
||||
"void_reason": 256,
|
||||
"archive_reason": 256,
|
||||
"force_reason": 256,
|
||||
}
|
||||
|
||||
FIELD_LABELS = {
|
||||
"order_no": "订单编号",
|
||||
"shop": "店铺",
|
||||
"shop_remark": "店铺备注",
|
||||
"owner_id": "负责人",
|
||||
"bind_douyu_account": "绑定斗鱼号",
|
||||
"bind_douyu_uid": "绑定斗鱼号 uid",
|
||||
"gift_name": "礼包名",
|
||||
"required_points": "礼包所需积分",
|
||||
"remark": "备注",
|
||||
"void_reason": "作废原因",
|
||||
"force_reason": "强制恢复原因",
|
||||
"archive_reason": "归档备注",
|
||||
}
|
||||
|
||||
IMAGE_SLOTS: tuple[str, ...] = ("bind_images", "home_images")
|
||||
IMAGE_SLOT_LABELS = {
|
||||
"bind_images": "绑定图",
|
||||
"home_images": "主页截图",
|
||||
}
|
||||
MAX_IMAGES_PER_SLOT = 20
|
||||
|
||||
WEB_COOKIE_HINTS = ("guid=", "_qimei_uuid42")
|
||||
|
||||
|
||||
class CollabError(RuntimeError):
|
||||
"""协作台账的业务错误,路由层据此转成对应 HTTP 状态码。"""
|
||||
|
||||
def __init__(self, detail: str, *, status_code: int = 400, code: str = ""):
|
||||
super().__init__(detail)
|
||||
self.detail = detail
|
||||
self.status_code = status_code
|
||||
self.code = code
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(UTC)
|
||||
|
||||
|
||||
def clean_text(
|
||||
value: Any,
|
||||
*,
|
||||
field: str,
|
||||
required: bool = False,
|
||||
max_length: int | None = None,
|
||||
) -> str:
|
||||
"""统一收口字段清洗:去空白、限长、必填校验。"""
|
||||
text = str(value if value is not None else "").strip()
|
||||
limit = max_length or FIELD_LIMITS.get(field, 255)
|
||||
if len(text) > limit:
|
||||
raise CollabError(
|
||||
f"{FIELD_LABELS.get(field, field)}不能超过 {limit} 个字符",
|
||||
code="field_too_long",
|
||||
)
|
||||
if required and not text:
|
||||
raise CollabError(
|
||||
f"{FIELD_LABELS.get(field, field)}不能为空",
|
||||
code="field_required",
|
||||
)
|
||||
return text
|
||||
|
||||
|
||||
def normalize_images(value: Any, *, field: str) -> list[str]:
|
||||
"""把图片字段统一成 object_key 数组。"""
|
||||
if value is None:
|
||||
return []
|
||||
if isinstance(value, str):
|
||||
items: Sequence[Any] = [part for part in re.split(r"[,\s]+", value) if part]
|
||||
elif isinstance(value, (list, tuple)):
|
||||
items = list(value)
|
||||
else:
|
||||
raise CollabError(
|
||||
f"{IMAGE_SLOT_LABELS.get(field, field)}格式不正确",
|
||||
code="images_invalid",
|
||||
)
|
||||
|
||||
result: list[str] = []
|
||||
for item in items:
|
||||
text = str(item or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
try:
|
||||
key = normalize_object_key(text)
|
||||
except ValueError as exc:
|
||||
raise CollabError(
|
||||
f"{IMAGE_SLOT_LABELS.get(field, field)}的文件 key 不正确",
|
||||
code="image_key_invalid",
|
||||
) from exc
|
||||
if key not in result:
|
||||
result.append(key)
|
||||
|
||||
if len(result) > MAX_IMAGES_PER_SLOT:
|
||||
raise CollabError(
|
||||
f"{IMAGE_SLOT_LABELS.get(field, field)}最多 {MAX_IMAGES_PER_SLOT} 张",
|
||||
code="images_too_many",
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def images_of(order: HuyaExternalOrder, slot: str) -> list[str]:
|
||||
value = getattr(order, slot, None)
|
||||
return [str(item) for item in value] if isinstance(value, list) else []
|
||||
|
||||
|
||||
def look_like_web_cookie(cookie: str) -> bool:
|
||||
text = cookie or ""
|
||||
return any(hint in text for hint in WEB_COOKIE_HINTS)
|
||||
|
||||
|
||||
def _touch(order: HuyaExternalOrder, current: User | None) -> None:
|
||||
order.updated_by = current.id if current else None
|
||||
order.version = int(order.version or 0) + 1
|
||||
order.updated_at = _now()
|
||||
|
||||
|
||||
def _audit_target(order: HuyaExternalOrder) -> str:
|
||||
return f"huya_external_order:{order.id}"
|
||||
|
||||
|
||||
def assert_order_mutable(order: HuyaExternalOrder) -> None:
|
||||
if order.archived_at is not None:
|
||||
raise CollabError(
|
||||
"这单已归档,只能查看;需要修改请先取消归档",
|
||||
status_code=409,
|
||||
code="order_archived",
|
||||
)
|
||||
|
||||
|
||||
def assert_version(order: HuyaExternalOrder, expected_version: int | None) -> None:
|
||||
if expected_version is None:
|
||||
return
|
||||
if int(expected_version) != int(order.version or 0):
|
||||
raise CollabError(
|
||||
f"这行已被 {_last_editor_name(order) or '其他人'} 改过"
|
||||
f"(版本 {order.version}),请刷新后重试;直接覆盖会丢掉对方的修改",
|
||||
status_code=409,
|
||||
code="version_conflict",
|
||||
)
|
||||
|
||||
|
||||
def _last_editor_name(order: HuyaExternalOrder) -> str:
|
||||
editor = getattr(order, "updated_by_user", None)
|
||||
return str(getattr(editor, "username", "") or "")
|
||||
|
||||
|
||||
def normalize_points_threshold(value: Any) -> int:
|
||||
if value is None or value == "":
|
||||
return RECHARGE_POINTS_THRESHOLD_DEFAULT
|
||||
try:
|
||||
number = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise CollabError(
|
||||
"积分阈值必须是整数",
|
||||
code="points_threshold_invalid",
|
||||
) from exc
|
||||
if number < 0:
|
||||
raise CollabError("积分阈值不能小于 0", code="points_threshold_invalid")
|
||||
return min(number, RECHARGE_POINTS_THRESHOLD_MAX)
|
||||
|
||||
|
||||
def is_forward_status(from_status: str, target: str) -> bool:
|
||||
if target == STATUS_VOID or target == STATUS_FAILED:
|
||||
return from_status not in (STATUS_VOID, STATUS_FAILED)
|
||||
if from_status in (STATUS_VOID, STATUS_FAILED):
|
||||
return False
|
||||
if from_status == STATUS_POINTS_ERROR:
|
||||
return target in (STATUS_TO_RECHARGE, STATUS_RECHARGED)
|
||||
if target == STATUS_POINTS_ERROR:
|
||||
return from_status in (STATUS_TO_RECHARGE, STATUS_RECHARGED)
|
||||
return STAGE_INDEX[target] >= STAGE_INDEX[from_status]
|
||||
|
||||
|
||||
def _clean_required_points(value: Any) -> int | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
raise CollabError("礼包所需积分必须是整数", code="required_points_invalid")
|
||||
try:
|
||||
points = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise CollabError(
|
||||
"礼包所需积分必须是整数",
|
||||
code="required_points_invalid",
|
||||
) from exc
|
||||
if points < 0:
|
||||
raise CollabError(
|
||||
"礼包所需积分不能小于 0",
|
||||
code="required_points_invalid",
|
||||
)
|
||||
return points
|
||||
|
||||
|
||||
def _clean_owner_id(value: Any) -> int | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
owner_id = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise CollabError("负责人必须是用户 ID", code="owner_invalid") from exc
|
||||
if owner_id <= 0:
|
||||
return None
|
||||
return owner_id
|
||||
Reference in New Issue
Block a user