"""admin_user 表 CRUD。""" from __future__ import annotations from datetime import datetime, timezone from sqlalchemy import select from sqlalchemy.orm import Session from app.core.security import hash_password from app.models.admin import AdminUser def get_by_id(db: Session, admin_id: int) -> AdminUser | None: return db.get(AdminUser, admin_id) def get_by_username(db: Session, username: str) -> AdminUser | None: stmt = select(AdminUser).where(AdminUser.username == username) return db.execute(stmt).scalar_one_or_none() def create_admin( db: Session, *, username: str, password: str, role: str = "operator" ) -> AdminUser: admin = AdminUser( username=username, password_hash=hash_password(password), role=role, ) db.add(admin) db.commit() db.refresh(admin) return admin def update_last_login(db: Session, admin: AdminUser) -> None: admin.last_login_at = datetime.now(timezone.utc) db.commit() def list_admins(db: Session) -> list[AdminUser]: stmt = select(AdminUser).order_by(AdminUser.id) return list(db.execute(stmt).scalars().all()) def set_role(db: Session, admin: AdminUser, *, role: str) -> AdminUser: admin.role = role db.commit() db.refresh(admin) return admin def set_status(db: Session, admin: AdminUser, *, status: str) -> AdminUser: admin.status = status db.commit() db.refresh(admin) return admin def set_password(db: Session, admin: AdminUser, *, password: str) -> AdminUser: admin.password_hash = hash_password(password) db.commit() db.refresh(admin) return admin