import copy from typing import Dict, Any, List, Optional, Tuple, Type from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select, func, desc from sqlalchemy.orm.attributes import flag_modified from app.core.biz_exception import BizException from app.models.node_configuration import ( BookerEntry, SentinelEntry, StandaloneEntry, NodeConfigurationRevision, ) class NodeConfigurationService: ENTRY_MODEL_MAP: Dict[str, Type[Any]] = { "booker": BookerEntry, "sentinel": SentinelEntry, "standalone": StandaloneEntry, } @classmethod def get_model(cls, entry_type: str) -> Type[Any]: model = cls.ENTRY_MODEL_MAP.get(entry_type.lower()) if not model: raise BizException( code=40000, message=f"Invalid entry_type: '{entry_type}'. Must be one of {list(cls.ENTRY_MODEL_MAP.keys())}", http_status=400, ) return model @classmethod def _to_snapshot(cls, obj: Any) -> Dict[str, Any]: """Serialize SQLAlchemy model columns to dict snapshot""" snapshot = {} for column in obj.__table__.columns: val = getattr(obj, column.name) if hasattr(val, "isoformat"): val = val.isoformat() snapshot[column.name] = copy.deepcopy(val) return snapshot @classmethod async def _record_revision( cls, db: AsyncSession, entry_type: str, entry_id: int, version: int, action: str, snapshot: Dict[str, Any], updated_by: str, ) -> NodeConfigurationRevision: rev = NodeConfigurationRevision( entry_type=entry_type, entry_id=entry_id, version=version, action=action, snapshot=snapshot, updated_by=updated_by or "system", ) db.add(rev) await db.flush() return rev @classmethod async def list_entries( cls, db: AsyncSession, entry_type: str, page: int = 1, page_size: int = 20, identifier: Optional[str] = None, node_id: Optional[str] = None, order_id: Optional[str] = None, enable: Optional[int] = None, ) -> Tuple[int, List[Any]]: model = cls.get_model(entry_type) stmt = select(model) count_stmt = select(func.count(model.id)) if identifier: stmt = stmt.where(model.identifier.like(f"%{identifier}%")) count_stmt = count_stmt.where(model.identifier.like(f"%{identifier}%")) if node_id: stmt = stmt.where(model.node_id == node_id) count_stmt = count_stmt.where(model.node_id == node_id) if order_id and hasattr(model, "order_id"): stmt = stmt.where(model.order_id == order_id) count_stmt = count_stmt.where(model.order_id == order_id) if enable is not None and hasattr(model, "enable"): stmt = stmt.where(model.enable == enable) count_stmt = count_stmt.where(model.enable == enable) total = await db.scalar(count_stmt) or 0 offset = (page - 1) * page_size stmt = stmt.order_by(desc(model.enable), desc(model.updated_at), desc(model.id)).offset(offset).limit(page_size) result = await db.execute(stmt) items = list(result.scalars().all()) return total, items @classmethod async def get_entry( cls, db: AsyncSession, entry_type: str, entry_id: int ) -> Any: model = cls.get_model(entry_type) stmt = select(model).where(model.id == entry_id) entry = (await db.execute(stmt)).scalar_one_or_none() if not entry: raise BizException( code=40400, message=f"Configuration entry ({entry_type} ID: {entry_id}) not found", http_status=404, ) return entry @classmethod async def create_entry( cls, db: AsyncSession, entry_type: str, data: Dict[str, Any], operator: str = "system", ) -> Any: model = cls.get_model(entry_type) node_id = data.get("node_id") or "default" identifier = data.get("identifier") if not identifier: raise BizException( code=40000, message="Field 'identifier' is required", http_status=400, ) # Check duplicate (node_id, identifier) check_stmt = select(model).where( model.node_id == node_id, model.identifier == identifier ) existing = (await db.execute(check_stmt)).scalar_one_or_none() if existing: raise BizException( code=40902, message=f"Identifier '{identifier}' on node '{node_id}' already exists", http_status=409, ) # Prepare model payload entry_data = data.copy() entry_data["node_id"] = node_id entry_data["enable"] = 0 # Force disabled upon creation entry_data["updated_by"] = operator entry_data["version"] = 1 # Instantiate valid_cols = {c.name for c in model.__table__.columns} filtered_data = {k: v for k, v in entry_data.items() if k in valid_cols} entry = model(**filtered_data) db.add(entry) await db.flush() # Record revision snapshot = cls._to_snapshot(entry) await cls._record_revision( db=db, entry_type=entry_type, entry_id=entry.id, version=entry.version, action="create", snapshot=snapshot, updated_by=operator, ) await db.commit() await db.refresh(entry) return entry @classmethod async def sparse_update_entry( cls, db: AsyncSession, entry_type: str, entry_id: int, set_data: Optional[Dict[str, Any]] = None, clear_fields: Optional[List[str]] = None, base_version: Optional[int] = None, operator: str = "system", ) -> Any: entry = await cls.get_entry(db, entry_type, entry_id) set_data = set_data or {} clear_fields = clear_fields or [] # 1. Apply set_data with dot-path support for path_key, val in set_data.items(): # Strip leading 'payload.' if present clean_key = path_key[8:] if path_key.startswith("payload.") else path_key if "." in clean_key: root_field, *nested_keys = clean_key.split(".") if hasattr(entry, root_field): root_val = getattr(entry, root_field) if not isinstance(root_val, dict): root_val = {} else: root_val = copy.deepcopy(root_val) curr = root_val for nk in nested_keys[:-1]: if nk not in curr or not isinstance(curr[nk], dict): curr[nk] = {} curr = curr[nk] curr[nested_keys[-1]] = val setattr(entry, root_field, root_val) flag_modified(entry, root_field) else: if hasattr(entry, clean_key) and clean_key not in ("id", "created_at"): if isinstance(val, (dict, list)): val = copy.deepcopy(val) setattr(entry, clean_key, val) flag_modified(entry, clean_key) else: setattr(entry, clean_key, val) # 2. Apply clear_fields default_empty_map = { "proxy_pool": [], "appointment_types": [], "booker": {}, "sentinel": {}, "account": {}, "query_wait": {}, "user_preferences": {}, "plugin_config": {}, "free_config": {}, "website": "", "order_id": None, } for field in clear_fields: clean_field = field[8:] if field.startswith("payload.") else field if hasattr(entry, clean_field) and clean_field not in ("id", "created_at", "version"): default_val = default_empty_map.get(clean_field, None) setattr(entry, clean_field, default_val) if isinstance(default_val, (dict, list)): flag_modified(entry, clean_field) # Increment version and update operator entry.version = (entry.version or 0) + 1 entry.updated_by = operator await db.flush() # Record revision snapshot snapshot = cls._to_snapshot(entry) await cls._record_revision( db=db, entry_type=entry_type, entry_id=entry.id, version=entry.version, action="update", snapshot=snapshot, updated_by=operator, ) await db.commit() await db.refresh(entry) return entry @classmethod async def toggle_enable( cls, db: AsyncSession, entry_type: str, entry_id: int, enable: bool, base_version: Optional[int] = None, operator: str = "system", ) -> Any: entry = await cls.get_entry(db, entry_type, entry_id) entry.enable = 1 if enable else 0 entry.version = (entry.version or 0) + 1 entry.updated_by = operator await db.flush() snapshot = cls._to_snapshot(entry) await cls._record_revision( db=db, entry_type=entry_type, entry_id=entry.id, version=entry.version, action="enable" if enable else "disable", snapshot=snapshot, updated_by=operator, ) await db.commit() await db.refresh(entry) return entry @classmethod async def delete_entry( cls, db: AsyncSession, entry_type: str, entry_id: int, confirm_purge: bool = False, ) -> bool: model = cls.get_model(entry_type) entry = await cls.get_entry(db, entry_type, entry_id) # Deletion guard: count remaining entries for this entry_type total_count = await db.scalar(select(func.count(model.id))) or 0 if total_count <= 1 and not confirm_purge: raise BizException( code=40000, message="Deleting the last entry requires confirm_purge=true", http_status=400, ) await db.delete(entry) await db.commit() return True @classmethod async def get_revisions( cls, db: AsyncSession, entry_type: str, entry_id: int, ) -> List[NodeConfigurationRevision]: # Validate existence await cls.get_entry(db, entry_type, entry_id) stmt = ( select(NodeConfigurationRevision) .where( NodeConfigurationRevision.entry_type == entry_type, NodeConfigurationRevision.entry_id == entry_id, ) .order_by(desc(NodeConfigurationRevision.id)) ) result = await db.execute(stmt) return list(result.scalars().all()) @classmethod async def rollback_revision( cls, db: AsyncSession, entry_type: str, entry_id: int, revision_id: int, base_version: Optional[int] = None, operator: str = "system", ) -> Any: entry = await cls.get_entry(db, entry_type, entry_id) rev_stmt = select(NodeConfigurationRevision).where( NodeConfigurationRevision.id == revision_id, NodeConfigurationRevision.entry_type == entry_type, NodeConfigurationRevision.entry_id == entry_id, ) rev = (await db.execute(rev_stmt)).scalar_one_or_none() if not rev: raise BizException( code=40400, message=f"Revision {revision_id} for {entry_type} entry {entry_id} not found", http_status=404, ) snapshot = rev.snapshot or {} model = cls.get_model(entry_type) ignore_cols = {"id", "created_at", "updated_at", "version"} for col in model.__table__.columns: if col.name not in ignore_cols and col.name in snapshot: val = snapshot[col.name] if isinstance(val, (dict, list)): val = copy.deepcopy(val) setattr(entry, col.name, val) flag_modified(entry, col.name) else: setattr(entry, col.name, val) entry.version = (entry.version or 0) + 1 entry.updated_by = operator await db.flush() new_snapshot = cls._to_snapshot(entry) await cls._record_revision( db=db, entry_type=entry_type, entry_id=entry.id, version=entry.version, action="rollback", snapshot=new_snapshot, updated_by=operator, ) await db.commit() await db.refresh(entry) return entry