Files
live-hub-py/web/backend/services/douyu_collab_catalog.py
T

335 lines
9.9 KiB
Python

"""斗鱼外部单协作的礼包、商品解析与活动商品刷新。"""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from sqlalchemy import func, or_
from sqlalchemy.orm import Session
from ..models import (
Account,
DouyuCollabGift,
DouyuExternalOrder,
DouyuGoodsSnapshot,
PlatformCommodityMapping,
User,
)
from .audit_service import record_audit
from .business_events import record_account_query
from .douyu_account_probe import (
config_mapping,
persist_probe_result,
probe_account,
)
from .douyu_collab_common import (
CollabError,
_client_for_account,
_text,
_to_int,
account_by_id,
resolve_config,
)
from .douyu_goods_service import serialized_snapshots, upsert_goods_snapshot
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 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)