feat(douyu): 增加协作单礼包字典与权限控制

This commit is contained in:
yml2213
2026-11-06 15:09:50 +08:00
parent 578e259eea
commit 973042288f
12 changed files with 987 additions and 45 deletions
@@ -0,0 +1,52 @@
"""斗鱼外部单协作的礼包字典。
接口暂时不返回礼包信息,新建协作单时需要手填标准礼包名和所需积分。
这里把「名称 + 积分」做成可维护字典:管理员维护,客服只能选择;
以后接口恢复返回商品时,两边的选项会一起出现在下拉里。
订单里仍存礼包名字(`douyu_external_orders.gift_name`),不是 id。
改名会级联更新历史订单上的礼包名,但改积分**不回填**历史订单,
避免影响已经形成的积分核账结果。
"""
from __future__ import annotations
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "20261106_0066"
down_revision: str | None = "20261106_0065"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
TABLE = "douyu_collab_gifts"
def upgrade() -> None:
bind = op.get_bind()
if TABLE in set(sa.inspect(bind).get_table_names()):
return
op.create_table(
TABLE,
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
sa.Column("name", sa.String(length=128), nullable=False),
sa.Column("points", sa.Integer(), nullable=False, server_default="0"),
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
sa.Column("is_active", sa.Boolean(), nullable=False, server_default="1"),
sa.Column("remark", sa.String(length=255), nullable=False, server_default=""),
sa.Column("created_by", sa.Integer(), nullable=True),
sa.Column("updated_by", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
)
op.create_index(f"ix_{TABLE}_name", TABLE, ["name"], unique=True)
op.create_index(f"ix_{TABLE}_is_active", TABLE, ["is_active"])
def downgrade() -> None:
bind = op.get_bind()
if TABLE in set(sa.inspect(bind).get_table_names()):
# MySQL 删表会连索引一起删。
op.drop_table(TABLE)
+29
View File
@@ -567,6 +567,35 @@ class DouyuCollabShop(Base):
)
class DouyuCollabGift(Base):
"""斗鱼外部单协作的礼包字典(管理员维护名称与所需积分)。"""
__tablename__ = "douyu_collab_gifts"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(
String(128), unique=True, nullable=False, index=True
)
points: Mapped[int] = mapped_column(
Integer, default=0, server_default="0", nullable=False
)
sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
is_active: Mapped[bool] = mapped_column(
Boolean, default=True, server_default="1", index=True
)
remark: Mapped[str] = mapped_column(String(255), default="", server_default="")
created_by: Mapped[int | None] = mapped_column(
ForeignKey("users.id"), nullable=True
)
updated_by: Mapped[int | None] = mapped_column(
ForeignKey("users.id"), nullable=True
)
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
updated_at: Mapped[datetime] = mapped_column(
UTCDateTime, default=_utcnow, onupdate=_utcnow
)
class DouyuExternalOrder(Base):
"""斗鱼外部单协作台账(一行 = 一单 = 一个内部斗鱼账号)。
+76
View File
@@ -29,6 +29,9 @@ from ..schemas import (
DouyuCollabArchiveRequest,
DouyuCollabCkExportOut,
DouyuCollabCkExportRequest,
DouyuCollabGiftCreate,
DouyuCollabGiftOut,
DouyuCollabGiftUpdate,
DouyuCollabGoodsOut,
DouyuCollabImagesRequest,
DouyuCollabMetricOut,
@@ -75,6 +78,21 @@ def _shop_out(shop) -> dict:
}
def _gift_out(gift) -> dict:
return {
"id": int(gift.id),
"name": gift.name,
"points": int(gift.points or 0),
"sort_order": int(gift.sort_order or 0),
"is_active": bool(gift.is_active),
"remark": gift.remark or "",
"created_by": gift.created_by,
"updated_by": gift.updated_by,
"created_at": gift.created_at,
"updated_at": gift.updated_at,
}
def _publish_change(current: User, *, scope: str, action: str) -> None:
collab_events.publish(scope=scope, action=action, actor_id=int(current.id))
@@ -693,3 +711,61 @@ def delete_collab_shop(
raise _http_error(exc) from exc
_publish_change(current, scope="shops", action="shop.delete")
return {**result, "id": shop_id}
@router.get("/collab-gifts", response_model=list[DouyuCollabGiftOut])
def list_collab_gifts(
db: Session = Depends(get_db),
_current: User = Depends(require_permission("douyu:collab:view")),
):
return [_gift_out(gift) for gift in collab.list_gifts(db)]
@router.post("/collab-gifts", response_model=DouyuCollabGiftOut)
def create_collab_gift(
req: DouyuCollabGiftCreate,
db: Session = Depends(get_db),
current: User = Depends(require_permission("douyu:collab:manage")),
):
try:
gift = collab.create_gift(
db,
current,
name=req.name,
points=req.points,
remark=req.remark,
)
except collab.CollabError as exc:
raise _http_error(exc) from exc
_publish_change(current, scope="gifts", action="gift.create")
return _gift_out(gift)
@router.put("/collab-gifts/{gift_id}", response_model=DouyuCollabGiftOut)
def update_collab_gift(
gift_id: int,
req: DouyuCollabGiftUpdate,
db: Session = Depends(get_db),
current: User = Depends(require_permission("douyu:collab:manage")),
):
try:
gift = collab.get_gift(db, gift_id)
collab.update_gift(db, current, gift, req.model_dump(exclude_unset=True))
except collab.CollabError as exc:
raise _http_error(exc) from exc
_publish_change(current, scope="gifts", action="gift.update")
return _gift_out(gift)
@router.delete("/collab-gifts/{gift_id}")
def delete_collab_gift(
gift_id: int,
db: Session = Depends(get_db),
current: User = Depends(require_permission("douyu:collab:manage")),
):
try:
result = collab.delete_gift(db, current, collab.get_gift(db, gift_id))
except collab.CollabError as exc:
raise _http_error(exc) from exc
_publish_change(current, scope="gifts", action="gift.delete")
return {**result, "id": gift_id}
+27
View File
@@ -1768,6 +1768,33 @@ class DouyuCollabShopOut(BaseModel):
updated_at: datetime | None = None
class DouyuCollabGiftCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=128)
points: int = Field(..., ge=0)
remark: str = Field("", max_length=255)
class DouyuCollabGiftUpdate(BaseModel):
name: str | None = Field(None, min_length=1, max_length=128)
points: int | None = Field(None, ge=0)
sort_order: int | None = None
is_active: bool | None = None
remark: str | None = Field(None, max_length=255)
class DouyuCollabGiftOut(BaseModel):
id: int
name: str
points: int = 0
sort_order: int = 0
is_active: bool = True
remark: str = ""
created_by: int | None = None
updated_by: int | None = None
created_at: datetime | None = None
updated_at: datetime | None = None
class DouyuCollabGoodsOut(BaseModel):
commodity_id: str = ""
name: str = ""
+165 -4
View File
@@ -25,6 +25,7 @@ from core.douyu import DouyuActivityClient
from ..models import (
Account,
AuditLog,
DouyuCollabGift,
DouyuCollabShop,
DouyuConfig,
DouyuExternalOrder,
@@ -474,6 +475,18 @@ def _resolve_gift(
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:
# 接口暂时不返回商品时,管理员配置的礼包名称和积分仍然可用。
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
@@ -548,6 +561,7 @@ def create_order(
raise CollabError("订单号已存在", status_code=409, code="order_no_exists")
images = normalize_images(home_images)
explicit_points = _to_int(required_points)
name, cid, points = _resolve_gift(
db,
gift_name=gift_name,
@@ -591,18 +605,23 @@ def create_order(
with_goods=True,
)
apply_probe_snapshot(order, account, probe)
if points is None and name:
if explicit_points is None and name:
live = next(
(
item
for item in (probe.get("goods") or [])
if str(item.get("commodityName") or "") == name
if str(item.get("name") or item.get("commodityName") or "")
== name
),
None,
)
if live is not None:
points = _to_int(live.get("score"))
order.required_points = points
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:
# 草稿不联网探针,但既然用户名已存在,先把内部账号关联上,
# 后续补资料时不用再靠“用户名变化”触发解析。
@@ -1400,6 +1419,148 @@ def delete_shop(db: Session, current: User, shop: DouyuCollabShop) -> dict[str,
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)