"""虎牙外部单协作的店铺字典。""" from __future__ import annotations from collections.abc import Mapping, Sequence from typing import Any from sqlalchemy.orm import Session from ..models import HuyaCollabShop, HuyaExternalOrder, User from .audit_service import record_audit from .huya_collab_common import CollabError, _now, clean_text SHOP_NAME_LIMIT = 64 def normalize_shop_name(value: Any) -> str: """店铺名统一收口:去空白 + 限长(空串 = 不填店铺)。""" return clean_text(value, field="shop", max_length=SHOP_NAME_LIMIT) def _shop_audit_target(shop: HuyaCollabShop) -> str: return f"huya_collab_shop:{shop.id}" def _touch_shop(shop: HuyaCollabShop, current: User | None) -> None: shop.updated_by = current.id if current else None shop.updated_at = _now() def serialize_shop( shop: HuyaCollabShop, *, users: Mapping[int, str] | None = None ) -> dict: names = users or {} def name_of(value: int | None) -> str: return names.get(int(value), "") if value else "" return { "id": shop.id, "name": shop.name or "", "sort_order": int(shop.sort_order or 0), "is_active": bool(shop.is_active), "remark": shop.remark or "", "created_by_name": name_of(shop.created_by), "updated_by_name": name_of(shop.updated_by), "created_at": shop.created_at, "updated_at": shop.updated_at, } def list_shop_records(db: Session) -> list[HuyaCollabShop]: """全部店铺(**含停用的**:管理弹窗要能看到;新建下拉由前端按 `is_active` 过滤)。""" return ( db.query(HuyaCollabShop) .order_by(HuyaCollabShop.sort_order.asc(), HuyaCollabShop.name.asc()) .all() ) def get_shop(db: Session, shop_id: int) -> HuyaCollabShop: shop = db.query(HuyaCollabShop).filter(HuyaCollabShop.id == shop_id).first() if shop is None: raise CollabError( "这个店铺不存在(可能已被别人删除)", status_code=404, code="shop_not_found" ) return shop def _assert_shop_name_available( db: Session, name: str, *, exclude_id: int | None = None ) -> None: query = db.query(HuyaCollabShop).filter(HuyaCollabShop.name == name) if exclude_id is not None: query = query.filter(HuyaCollabShop.id != exclude_id) other = query.first() if other is not None: raise CollabError( f"店铺「{name}」已经在字典里了(第 {other.id} 行)", status_code=409, code="shop_name_conflict", ) def create_shop( db: Session, current: User | None, *, name: Any, sort_order: int = 0, remark: Any = "", commit: bool = True, ) -> HuyaCollabShop: """新增一个店铺(重名 409)。""" cleaned = normalize_shop_name(name) if not cleaned: raise CollabError("店铺名不能为空", code="shop_name_required") _assert_shop_name_available(db, cleaned) shop = HuyaCollabShop( name=cleaned, sort_order=int(sort_order or 0), is_active=True, remark=clean_text(remark, field="shop_remark", max_length=255), created_by=current.id if current else None, updated_by=current.id if current else None, ) db.add(shop) db.flush() record_audit( db, current, action="huya:collab:shop_create", target=_shop_audit_target(shop), detail={"name": shop.name, "sort_order": shop.sort_order}, ) if commit: db.commit() db.refresh(shop) return shop def update_shop( db: Session, current: User | None, shop: HuyaCollabShop, payload: Mapping[str, Any], *, rename_orders: bool = True, commit: bool = True, ) -> dict: """改店铺(名字 / 排序 / 停用 / 备注),返回字段级 diff。 ``rename_orders=True``(默认)时,改名会**级联**把已有订单里的旧名字一起改掉, 否则筛选会出现"改名前的老名字"这一堆孤儿值;不想要级联就显式传 False。 """ changes: dict[str, dict[str, Any]] = {} old_name = shop.name or "" renamed_orders = 0 if "name" in payload: new_name = normalize_shop_name(payload["name"]) if not new_name: raise CollabError("店铺名不能为空", code="shop_name_required") if new_name != old_name: _assert_shop_name_available(db, new_name, exclude_id=shop.id) changes["name"] = {"old": old_name, "new": new_name} shop.name = new_name if "sort_order" in payload: value = int(payload["sort_order"] or 0) if value != int(shop.sort_order or 0): changes["sort_order"] = {"old": int(shop.sort_order or 0), "new": value} shop.sort_order = value if "is_active" in payload: value = bool(payload["is_active"]) if value != bool(shop.is_active): changes["is_active"] = {"old": bool(shop.is_active), "new": value} shop.is_active = value if "remark" in payload: value = clean_text(payload["remark"], field="shop_remark", max_length=255) if value != (shop.remark or ""): changes["remark"] = {"old": shop.remark or "", "new": value} shop.remark = value if not changes: return {} if "name" in changes and rename_orders: # 批量改名:订单里存的是名字字符串(见 models.HuyaCollabShop 的取舍说明)。 renamed_orders = ( db.query(HuyaExternalOrder) .filter(HuyaExternalOrder.shop == old_name) .update( {HuyaExternalOrder.shop: changes["name"]["new"]}, synchronize_session=False, ) ) _touch_shop(shop, current) record_audit( db, current, action="huya:collab:shop_update", target=_shop_audit_target(shop), detail={"changes": changes, "renamed_orders": renamed_orders}, ) if commit: db.commit() db.refresh(shop) return changes def delete_shop( db: Session, current: User | None, shop: HuyaCollabShop, *, commit: bool = True ) -> dict: """从字典里删掉(需 ``huya:collab:manage``)。 **不动订单**:订单里存的是名字字符串,历史单子照旧;想让以后不再用它, 用「停用」更稳。 """ snapshot = {"id": shop.id, "name": shop.name or ""} record_audit( db, current, action="huya:collab:shop_delete", target=_shop_audit_target(shop), detail=snapshot, ) db.delete(shop) if commit: db.commit() return snapshot def ensure_shops_registered( db: Session, current: User | None, names: Sequence[Any] ) -> list[str]: """把订单里用到的店铺名补进字典(新建 / 编辑 / 粘贴导入共用),返回新登记的名字。 这样"自定义输入一个新店铺"就能直接出现在下次的下拉里,不用先去管理弹窗加一遍。 """ wanted = [str(name or "").strip() for name in names] wanted = [name for name in dict.fromkeys(wanted) if name] if not wanted: return [] known = { row[0] for row in db.query(HuyaCollabShop.name) .filter(HuyaCollabShop.name.in_(wanted)) .all() } created: list[str] = [] for name in wanted: if name in known or len(name) > SHOP_NAME_LIMIT: continue db.add( HuyaCollabShop( name=name, sort_order=0, is_active=True, remark="", created_by=current.id if current else None, updated_by=current.id if current else None, ) ) created.append(name) if created: # 先 flush 让同一批里的重名在唯一索引上炸出来(而不是拖到 commit)。 db.flush() record_audit( db, current, action="huya:collab:shop_create", target="huya_collab_shops", detail={"auto_registered": created}, ) return created def list_shops(db: Session) -> list[str]: """字典里的店铺名(筛选/下拉用;停用的也在,前端自己决定展示哪些)。""" return sorted(shop.name for shop in list_shop_records(db))