nex_buddy/server/app/api/admin.py

672 lines
26 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""管理端:用户 / 设备 / 固件 / 平台设置 / 城市码表 / 星座码表 / 月度运势。"""
from __future__ import annotations
import json
import uuid
from datetime import datetime, timezone
from typing import Any
from fastapi import APIRouter, File, Form, HTTPException, Query, UploadFile
from fastapi.responses import FileResponse
from sqlalchemy import func, or_, select
from app.api.deps import CurrentAdmin, SessionDep
from app.core.config import settings
from app.models import Device, Firmware, Fortune, PlatformSetting, Region, User, ZodiacSign
from app.schemas.auth import AdminSettingIn, DeviceOut, OkOut, UserOut, user_out
from app.schemas.catalog import FortuneIn, FortuneOut, FortunePatch, RegionIn, RegionPatch, ZodiacIn, ZodiacPatch
from app.schemas.firmware import DeviceUpgradeOut, FirmwareOut, FirmwarePatch, RolloutIn, UpgradeIn
from app.services import catalog, firmware, redis_store, weather
router = APIRouter(prefix="/admin", tags=["admin"])
# 内置标准码表(GB/T 2260 三级),管理端可一键补全
SEED_PATH = settings.data_dir / "regions.json"
@router.get("/users")
async def list_users(admin: CurrentAdmin, db: SessionDep) -> dict:
users = (await db.execute(select(User).order_by(User.created_at.desc()))).scalars().all()
devices = (await db.execute(select(Device).where(Device.bound_user_id.isnot(None)))).scalars().all()
zmap = await catalog.zodiac_map(db)
by_user: dict[uuid.UUID, list[DeviceOut]] = {}
for d in devices:
by_user.setdefault(d.bound_user_id, []).append(DeviceOut.model_validate(d))
return {
"total": len(users),
"items": [
{**user_out(u, zmap).model_dump(mode="json"),
"devices": [d.model_dump(mode="json") for d in by_user.get(u.id, [])]}
for u in users
],
}
@router.post("/users/{user_id}/status", response_model=OkOut)
async def set_user_status(user_id: uuid.UUID, status: str, admin: CurrentAdmin, db: SessionDep) -> OkOut:
if status not in ("active", "disabled"):
raise HTTPException(400, "status must be active|disabled")
user = await db.get(User, user_id)
if user is None:
raise HTTPException(404, "user not found")
if user.id == admin.id and status == "disabled":
raise HTTPException(400, "cannot disable yourself")
user.status = status
await db.commit()
if status == "disabled":
# 停用即失联:吊销其 Web 会话与所有设备 token
await redis_store.revoke_sessions_of(str(user.id))
for d in (await db.execute(select(Device).where(Device.bound_user_id == user.id))).scalars():
await redis_store.revoke_device_tokens(str(d.id))
return OkOut(ok=True)
# ------------------------------------------------------------------ 设备管理
@router.delete("/devices/{device_id}", response_model=OkOut)
async def unbind_device(device_id: uuid.UUID, admin: CurrentAdmin, db: SessionDep) -> OkOut:
"""管理员解绑设备:清掉绑定关系并吊销设备 token,设备下次开机需重新配对。"""
device = await db.get(Device, device_id)
if device is None:
raise HTTPException(404, "device not found")
if device.bound_user_id is None:
raise HTTPException(400, "device not bound")
device.bound_user_id = None
device.bound_at = None
await db.commit()
await redis_store.revoke_device_tokens(str(device.id))
return OkOut(ok=True, detail="已解绑")
@router.post("/devices/{device_id}/revoke", response_model=OkOut)
async def revoke_device(device_id: uuid.UUID, admin: CurrentAdmin, db: SessionDep) -> OkOut:
"""只吊销 token 不解绑:设备下次请求即 401,需重新走配对流程。"""
device = await db.get(Device, device_id)
if device is None:
raise HTTPException(404, "device not found")
n = await redis_store.revoke_device_tokens(str(device.id))
return OkOut(ok=True, detail=f"revoked {n} token(s)")
# ------------------------------------------------------------------ 固件管理
def _fw_out(fw: Firmware, device_count: int = 0) -> dict:
return FirmwareOut.model_validate(fw).model_copy(update={"device_count": device_count}).model_dump(mode="json")
@router.get("/firmwares")
async def list_firmwares(
admin: CurrentAdmin,
db: SessionDep,
model: str | None = None,
channel: str | None = Query(default=None, pattern="^(stable|beta)$"),
) -> dict:
stmt = select(Firmware)
if model:
stmt = stmt.where(Firmware.model == model)
if channel:
stmt = stmt.where(Firmware.channel == channel)
rows = list((await db.execute(stmt.order_by(Firmware.version_code.desc()))).scalars().all())
counts = await firmware.device_counts(db)
return {
"items": [_fw_out(fw, counts.get(fw.version, 0)) for fw in rows],
"storage": firmware.env_storage_hint(),
"max_size": firmware.MAX_SIZE,
}
@router.post("/firmwares", response_model=OkOut)
async def upload_firmware(
admin: CurrentAdmin,
db: SessionDep,
file: UploadFile = File(..., description="xxx.ino.bin"),
version: str = Form(..., description="0.1.2 / 0.2.0-rc1"),
model: str = Form("JC3636K518C_I_W"),
channel: str = Form("stable"),
notes: str = Form(""),
notes_en: str = Form(""),
min_version: str = Form(""),
publish: bool = Form(False),
) -> OkOut:
"""上传固件包。
校验顺序是「便宜的先做」:版本号 → 通道 → 唯一性 → 落盘算哈希 → 镜像头。
这样传错文件时不用等 2 MB 都写完才报错(哈希必须读完,但重复版本能在最前面拦掉)。
"""
version = version.strip()
channel = (channel or "stable").strip()
if channel not in ("stable", "beta"):
raise HTTPException(400, "channel 只能是 stable / beta")
try:
code = firmware.version_code(version)
except firmware.FirmwareError as exc:
raise HTTPException(400, str(exc)) from exc
if min_version:
try:
firmware.parse_version(min_version)
except firmware.FirmwareError as exc:
raise HTTPException(400, f"最低版本:{exc}") from exc
dup = await db.scalar(
select(func.count()).select_from(Firmware).where(
Firmware.model == model, Firmware.channel == channel, Firmware.version == version
)
)
if dup:
raise HTTPException(409, f"{model} / {channel} 通道已有 {version},先删掉旧包再传")
try:
# 传 UploadFile 本身:它的 read() 是 async,save_stream 靠 await 流式读
path, size, sha = await firmware.save_stream(file, file.filename or "firmware.bin")
except firmware.FirmwareError as exc:
raise HTTPException(400, str(exc)) from exc
now = datetime.now(timezone.utc)
fw = Firmware(
model=model.strip(),
version=version,
version_code=code,
channel=channel,
size_bytes=size,
sha256=sha,
filename=path.name,
original_name=(file.filename or "")[:160],
notes=notes.strip(),
notes_en=notes_en.strip(),
min_version=min_version.strip(),
published=bool(publish),
created_by=admin.id,
published_at=now if publish else None,
)
db.add(fw)
await db.commit()
return OkOut(ok=True, detail=f"已上传 {version}({size / 1024:.0f} KB,sha256 {sha[:8]}…)")
@router.put("/firmwares/{firmware_id}", response_model=OkOut)
async def update_firmware(firmware_id: uuid.UUID, body: FirmwarePatch, admin: CurrentAdmin, db: SessionDep) -> OkOut:
fw = await db.get(Firmware, firmware_id)
if fw is None:
raise HTTPException(404, "firmware not found")
data = body.model_dump(exclude_unset=True)
if data.get("min_version"):
try:
firmware.parse_version(data["min_version"])
except firmware.FirmwareError as exc:
raise HTTPException(400, f"最低版本:{exc}") from exc
# 发布状态变化时补 published_at,方便列表按「上线时间」看
if "published" in data and data["published"] != fw.published:
fw.published_at = datetime.now(timezone.utc) if data["published"] else None
for k, v in data.items():
setattr(fw, k, v)
await db.commit()
return OkOut(ok=True)
@router.delete("/firmwares/{firmware_id}", response_model=OkOut)
async def delete_firmware(firmware_id: uuid.UUID, admin: CurrentAdmin, db: SessionDep) -> OkOut:
fw = await db.get(Firmware, firmware_id)
if fw is None:
raise HTTPException(404, "firmware not found")
# 有设备正指着这个包:要么等它升完,要么先取消下发,避免设备拿到 404
target = await db.scalar(
select(func.count()).select_from(Device).where(Device.target_firmware_id == fw.id)
) or 0
if target:
raise HTTPException(400, f"还有 {target} 台设备的目标版本指向它,先取消下发再删")
firmware.remove_file(fw)
await db.delete(fw)
await db.commit()
return OkOut(ok=True)
@router.get("/firmwares/{firmware_id}/download")
async def admin_download_firmware(firmware_id: uuid.UUID, admin: CurrentAdmin, db: SessionDep):
fw = await db.get(Firmware, firmware_id)
if fw is None:
raise HTTPException(404, "firmware not found")
path = firmware.path_of(fw)
if not path.exists():
raise HTTPException(410, "firmware file missing on server")
return FileResponse(
path,
media_type="application/octet-stream",
filename=f"knob_os-{fw.version}.bin",
headers={"X-Firmware-Sha256": fw.sha256},
)
def _device_label(user: User | None) -> str:
if user is None:
return ""
return user.nickname or user.email or user.phone or ""
@router.get("/devices/upgrades")
async def list_device_upgrades(admin: CurrentAdmin, db: SessionDep, q: str | None = None) -> dict:
"""设备升级状态列表:一屏看清「谁在什么版本、有没有推、推成功没」。"""
stmt = select(Device)
rows = list((await db.execute(stmt.order_by(Device.last_active_at.desc().nullslast()))).scalars().all())
uid_by_device = {d.bound_user_id for d in rows if d.bound_user_id}
users: dict[uuid.UUID, User] = {}
if uid_by_device:
for u in (await db.execute(select(User).where(User.id.in_(uid_by_device)))).scalars():
users[u.id] = u
items = [
DeviceUpgradeOut(
id=d.id,
chip_id=d.chip_id,
model=d.model,
fw_version=d.fw_version or "",
target_version=d.target_version or "",
upgrade_state=d.upgrade_state or "",
upgrade_error=d.upgrade_error or "",
upgrade_at=d.upgrade_at,
boot_slot=d.boot_slot or "",
fw_updated_at=d.fw_updated_at,
bound_user_id=d.bound_user_id,
user_label=_device_label(users.get(d.bound_user_id) if d.bound_user_id else None),
last_active_at=d.last_active_at,
).model_dump(mode="json")
for d in rows
]
if q:
like = q.strip().lower()
items = [
i for i in items
if like in i["chip_id"].lower() or like in (i["user_label"] or "").lower()
or like in (i["fw_version"] or "") or like in (i["target_version"] or "")
]
counts = await firmware.device_counts(db)
latest = await firmware.latest_published(db, "JC3636K518C_I_W")
pending = sum(1 for d in rows if d.target_firmware_id)
return {
"total": len(rows),
"by_version": counts,
"latest": latest.version if latest else "",
"pending": pending,
"items": items,
}
async def _assign(device: Device, fw: Firmware) -> None:
device.target_firmware_id = fw.id
device.target_version = fw.version
device.upgrade_state = "pending"
device.upgrade_error = ""
device.upgrade_at = datetime.now(timezone.utc)
@router.post("/devices/{device_id}/upgrade", response_model=OkOut)
async def push_upgrade(device_id: uuid.UUID, body: UpgradeIn, admin: CurrentAdmin, db: SessionDep) -> OkOut:
"""给单台设备点名下发。允许指定更低的版本(回滚)。"""
device = await db.get(Device, device_id)
if device is None:
raise HTTPException(404, "device not found")
fw = await db.get(Firmware, body.firmware_id)
if fw is None:
raise HTTPException(404, "firmware not found")
await _assign(device, fw)
await db.commit()
return OkOut(ok=True, detail=f"已指定 {device.chip_id} 升级到 {fw.version}(设备下次检查更新时生效)")
@router.delete("/devices/{device_id}/upgrade", response_model=OkOut)
async def cancel_upgrade(device_id: uuid.UUID, admin: CurrentAdmin, db: SessionDep) -> OkOut:
device = await db.get(Device, device_id)
if device is None:
raise HTTPException(404, "device not found")
device.target_firmware_id = None
device.target_version = ""
if device.upgrade_state in ("pending", "downloading"):
device.upgrade_state = "canceled"
await db.commit()
return OkOut(ok=True, detail="已取消下发")
@router.post("/firmwares/{firmware_id}/rollout", response_model=OkOut)
async def rollout_firmware(firmware_id: uuid.UUID, body: RolloutIn, admin: CurrentAdmin, db: SessionDep) -> OkOut:
"""批量下发。
默认只推给「版本低于该包」的设备——不然给已经在新版本上的设备再推一遍,
等于让它白下载 2 MB 然后回滚到同一版。
"""
fw = await db.get(Firmware, firmware_id)
if fw is None:
raise HTTPException(404, "firmware not found")
if not fw.published and not body.device_ids:
raise HTTPException(400, "该固件还没发布;批量下发前先发布,或指定具体设备")
stmt = select(Device)
if body.device_ids:
stmt = stmt.where(Device.id.in_(body.device_ids))
devices = list((await db.execute(stmt)).scalars().all())
hit = 0
for d in devices:
if d.model and fw.model and d.model != fw.model:
continue
if not body.device_ids and firmware.compare(d.fw_version or "", fw.version) >= 0:
continue
await _assign(d, fw)
hit += 1
await db.commit()
return OkOut(ok=True, detail=f"已指定 {hit} 台设备升级到 {fw.version}(共匹配 {len(devices)} 台,设备下次检查更新时生效)")
# ------------------------------------------------------------------ 月度运势
@router.get("/fortunes")
async def list_fortunes(
admin: CurrentAdmin,
db: SessionDep,
zodiac_code: str | None = None,
scope: str | None = Query(default=None, pattern="^(month|ym)$"),
year: int | None = Query(default=None, ge=2000, le=2100, description="按 ym 年过滤"),
) -> dict:
stmt = select(Fortune)
if zodiac_code:
stmt = stmt.where(Fortune.zodiac_code == zodiac_code)
if scope:
stmt = stmt.where(Fortune.scope == scope)
if year:
stmt = stmt.where(Fortune.period.like(f"{year}-%"))
rows = list((await db.execute(stmt)).scalars().all())
# 按黄经序排(白羊…双鱼),比按 code 字母序可读得多
zmap = await catalog.zodiac_map(db)
rows.sort(key=lambda f: (zmap.get(f.zodiac_code, {}).get("sort_order", 99), f.scope != "month", f.period))
return {"items": [FortuneOut.model_validate(r).model_dump(mode="json") for r in rows]}
@router.post("/fortunes", response_model=OkOut)
async def create_fortune(body: FortuneIn, admin: CurrentAdmin, db: SessionDep) -> OkOut:
if not await db.get(ZodiacSign, body.zodiac_code):
raise HTTPException(400, f"星座 {body.zodiac_code} 不在码表里")
_check_period(body.scope, body.period)
dup = await db.scalar(
select(func.count()).select_from(Fortune).where(
Fortune.zodiac_code == body.zodiac_code,
Fortune.scope == body.scope,
Fortune.period == body.period,
)
)
if dup:
raise HTTPException(409, "该星座该周期已有条目,走编辑")
db.add(Fortune(**body.model_dump()))
await db.commit()
return OkOut(ok=True)
@router.put("/fortunes/{fortune_id}", response_model=OkOut)
async def update_fortune(fortune_id: int, body: FortunePatch, admin: CurrentAdmin, db: SessionDep) -> OkOut:
row = await db.get(Fortune, fortune_id)
if row is None:
raise HTTPException(404, "fortune not found")
for k, v in body.model_dump(exclude_unset=True).items():
setattr(row, k, v)
await db.commit()
return OkOut(ok=True)
@router.delete("/fortunes/{fortune_id}", response_model=OkOut)
async def delete_fortune(fortune_id: int, admin: CurrentAdmin, db: SessionDep) -> OkOut:
row = await db.get(Fortune, fortune_id)
if row is None:
raise HTTPException(404, "fortune not found")
await db.delete(row)
await db.commit()
return OkOut(ok=True)
def _check_period(scope: str, period: str) -> None:
if scope == "month":
if not (len(period) == 2 and period.isdigit() and 1 <= int(period) <= 12):
raise HTTPException(400, "month 的 period 必须是两位月份,如 '11'")
else:
parts = period.split("-")
if len(parts) != 2 or not all(p.isdigit() for p in parts):
raise HTTPException(400, "ym 的 period 必须是 '2026-11' 形式")
y, m = int(parts[0]), int(parts[1])
if not (2000 <= y <= 2100 and 1 <= m <= 12):
raise HTTPException(400, "ym 超出范围")
@router.get("/settings")
async def get_settings(admin: CurrentAdmin, db: SessionDep) -> dict:
rows = (await db.execute(select(PlatformSetting))).scalars().all()
return {"items": [{"key": r.key, "value": r.value, "updated_at": r.updated_at.isoformat() if r.updated_at else None} for r in rows]}
@router.put("/settings", response_model=OkOut)
async def put_setting(body: AdminSettingIn, admin: CurrentAdmin, db: SessionDep) -> OkOut:
row = await db.get(PlatformSetting, body.key)
if row is None:
row = PlatformSetting(key=body.key, value=body.value, updated_by=admin.id)
db.add(row)
else:
row.value = body.value
row.updated_by = admin.id
await db.commit()
# 配置不入缓存,写完即生效;只需清掉可能已按旧配置取到的天气结果
if body.key.startswith("qweather"):
await redis_store.clear_weather_cache()
return OkOut(ok=True)
@router.post("/settings/weather/test")
async def test_weather(admin: CurrentAdmin, db: SessionDep, city: str | None = None) -> dict:
"""一键自检:DNS → TCP → TLS → HTTP 各跑一遍并计时。
天气取不到时,设备只有一个"暂无数据",人只能登服务器敲命令。把这几步搬到
这里,网页上点一下就知道是出网断了、证书被拦,还是 Key/Host 不匹配。
"""
return await weather.probe(db, city)
# ------------------------------------------------------------------ 城市码表
@router.get("/regions")
async def list_regions(
admin: CurrentAdmin,
db: SessionDep,
q: str | None = None,
level: int | None = None,
parent_code: str | None = None,
page: int = Query(1, ge=1),
page_size: int = Query(50, ge=1, le=500),
) -> dict:
stmt = select(Region)
count_stmt = select(func.count()).select_from(Region)
if q:
like = f"%{q.strip()}%"
cond = or_(Region.name.ilike(like), Region.code.ilike(like))
stmt = stmt.where(cond)
count_stmt = count_stmt.where(cond)
if level:
stmt = stmt.where(Region.level == level)
count_stmt = count_stmt.where(Region.level == level)
if parent_code:
stmt = stmt.where(Region.parent_code == parent_code)
count_stmt = count_stmt.where(Region.parent_code == parent_code)
total = await db.scalar(count_stmt) or 0
rows = (
await db.execute(
stmt.order_by(Region.sort_order, Region.code).offset((page - 1) * page_size).limit(page_size)
)
).scalars().all()
return {
"total": total,
"page": page,
"page_size": page_size,
"items": [
{
"code": r.code, "name": r.name, "level": r.level, "parent_code": r.parent_code,
"timezone": r.timezone, "enabled": r.enabled, "sort_order": r.sort_order,
}
for r in rows
],
}
@router.post("/regions", response_model=OkOut)
async def create_region(body: RegionIn, admin: CurrentAdmin, db: SessionDep) -> OkOut:
code = body.code.strip()
if await db.get(Region, code):
raise HTTPException(409, f"代码 {code} 已存在")
if body.parent_code and not await db.get(Region, body.parent_code):
raise HTTPException(400, "上级代码不存在")
max_sort = await db.scalar(select(func.max(Region.sort_order))) or 0
db.add(Region(**{**body.model_dump(), "code": code, "sort_order": body.sort_order or max_sort + 1}))
await db.commit()
await catalog.invalidate()
return OkOut(ok=True, detail=f"已新增 {body.name}")
@router.put("/regions/{code}", response_model=OkOut)
async def update_region(code: str, body: RegionPatch, admin: CurrentAdmin, db: SessionDep) -> OkOut:
region = await db.get(Region, code)
if region is None:
raise HTTPException(404, "region not found")
data = body.model_dump(exclude_unset=True)
if data.get("parent_code") and not await db.get(Region, data["parent_code"]):
raise HTTPException(400, "上级代码不存在")
for k, v in data.items():
setattr(region, k, v)
await db.commit()
await catalog.invalidate()
return OkOut(ok=True)
@router.delete("/regions/{code}", response_model=OkOut)
async def delete_region(code: str, admin: CurrentAdmin, db: SessionDep) -> OkOut:
region = await db.get(Region, code)
if region is None:
raise HTTPException(404, "region not found")
children = await db.scalar(select(func.count()).select_from(Region).where(Region.parent_code == code)) or 0
if children:
raise HTTPException(400, f"还有 {children} 个下级地区,先删下级或改为停用")
used = await db.scalar(
select(func.count()).select_from(User).where(
or_(User.birth_region_code == code, User.residence_region_code == code)
)
) or 0
if used:
raise HTTPException(400, f"有 {used} 位用户用到这个地区,建议改为停用(enabled=false)")
await db.delete(region)
await db.commit()
await catalog.invalidate()
return OkOut(ok=True)
@router.post("/regions/import", response_model=OkOut)
async def import_regions(
admin: CurrentAdmin,
db: SessionDep,
mode: str = Query("missing", pattern="^(missing|upsert)$"),
) -> OkOut:
"""从内置 GB/T 2260 码表补数据。missing 只补缺的,upsert 覆盖同名手改。"""
if not SEED_PATH.exists():
raise HTTPException(500, "内置码表文件缺失")
rows: list[dict[str, Any]] = json.loads(SEED_PATH.read_text("utf-8"))
existing = {r.code: r for r in (await db.execute(select(Region))).scalars().all()}
added = updated = 0
for row in rows:
cur = existing.get(row["code"])
if cur is None:
db.add(Region(**row))
added += 1
elif mode == "upsert":
cur.name = row["name"]
cur.level = row["level"]
cur.parent_code = row["parent_code"]
cur.timezone = row["timezone"]
cur.sort_order = row["sort_order"]
updated += 1
await db.commit()
await catalog.invalidate()
return OkOut(ok=True, detail=f"新增 {added} 条,更新 {updated} 条")
# ------------------------------------------------------------------ 星座码表
@router.get("/zodiacs")
async def list_zodiacs(admin: CurrentAdmin, db: SessionDep) -> dict:
rows = (
await db.execute(select(ZodiacSign).order_by(ZodiacSign.sort_order))
).scalars().all()
return {
"items": [
{
"code": z.code, "name_cn": z.name_cn, "name_en": z.name_en, "symbol": z.symbol,
"element": z.element, "start_month": z.start_month, "start_day": z.start_day,
"end_month": z.end_month, "end_day": z.end_day, "intro": z.intro,
"sort_order": z.sort_order, "enabled": z.enabled,
"date_range": f"{z.start_month:02d}-{z.start_day:02d} ~ {z.end_month:02d}-{z.end_day:02d}",
}
for z in rows
]
}
@router.post("/zodiacs", response_model=OkOut)
async def create_zodiac(body: ZodiacIn, admin: CurrentAdmin, db: SessionDep) -> OkOut:
if await db.get(ZodiacSign, body.code):
raise HTTPException(409, f"代码 {body.code} 已存在")
if await db.scalar(select(func.count()).select_from(ZodiacSign).where(ZodiacSign.sort_order == body.sort_order)):
raise HTTPException(400, f"黄经序号 {body.sort_order} 已被占用(0 白羊 … 11 双鱼)")
db.add(ZodiacSign(**body.model_dump()))
await db.commit()
await catalog.invalidate()
return OkOut(ok=True)
@router.put("/zodiacs/{code}", response_model=OkOut)
async def update_zodiac(code: str, body: ZodiacPatch, admin: CurrentAdmin, db: SessionDep) -> OkOut:
sign = await db.get(ZodiacSign, code)
if sign is None:
raise HTTPException(404, "sign not found")
data = body.model_dump(exclude_unset=True)
new_order = data.get("sort_order")
if new_order is not None and new_order != sign.sort_order:
clash = await db.scalar(
select(func.count()).select_from(ZodiacSign).where(ZodiacSign.sort_order == new_order)
)
if clash:
raise HTTPException(400, f"黄经序号 {new_order} 已被占用")
for k, v in data.items():
setattr(sign, k, v)
await db.commit()
await catalog.invalidate()
return OkOut(ok=True)
@router.delete("/zodiacs/{code}", response_model=OkOut)
async def delete_zodiac(code: str, admin: CurrentAdmin, db: SessionDep) -> OkOut:
sign = await db.get(ZodiacSign, code)
if sign is None:
raise HTTPException(404, "sign not found")
used = await db.scalar(
select(func.count()).select_from(User).where(or_(User.sun_sign == code, User.moon_sign == code))
) or 0
if used:
raise HTTPException(400, f"有 {used} 位用户的星盘用到它,建议停用而不是删除")
await db.delete(sign)
await db.commit()
await catalog.invalidate()
return OkOut(ok=True)