from sqlalchemy import func, or_, select from sqlalchemy.orm import Session from app.models.site import Site class SitesRepository: def __init__(self, db: Session) -> None: self.db = db def get_by_key(self, site_key: str) -> Site | None: stmt = select(Site).where(Site.site_key == site_key) return self.db.scalar(stmt) def list( self, keyword: str | None = None, company_id: str | None = None, limit: int = 100, offset: int = 0, ) -> tuple[list[Site], int]: stmt = select(Site) count_stmt = select(func.count()).select_from(Site) if keyword: pattern = f"%{keyword}%" cond = or_(Site.site_key.ilike(pattern), Site.name.ilike(pattern)) stmt = stmt.where(cond) count_stmt = count_stmt.where(cond) if company_id: stmt = stmt.where(Site.company_id == company_id) count_stmt = count_stmt.where(Site.company_id == company_id) stmt = stmt.order_by(Site.created_at.desc()).limit(limit).offset(offset) return list(self.db.scalars(stmt).all()), int(self.db.scalar(count_stmt) or 0) def create(self, site_key: str, company_id: str, name: str, status: str = "active") -> Site: item = Site(site_key=site_key, company_id=company_id, name=name, status=status) self.db.add(item) self.db.commit() self.db.refresh(item) return item def update( self, item: Site, *, company_id: str | None = None, name: str | None = None, status: str | None = None, ) -> Site: if company_id is not None: item.company_id = company_id if name is not None: item.name = name if status is not None: item.status = status self.db.commit() self.db.refresh(item) return item