from sqlalchemy import func, or_, select from sqlalchemy.orm import Session from app.models.company import Company class CompaniesRepository: def __init__(self, db: Session) -> None: self.db = db def get_by_key(self, company_key: str) -> Company | None: stmt = select(Company).where(Company.company_key == company_key) return self.db.scalar(stmt) def get_by_id(self, company_id: str) -> Company | None: stmt = select(Company).where(Company.id == company_id) return self.db.scalar(stmt) def list(self, keyword: str | None = None, limit: int = 100, offset: int = 0) -> tuple[list[Company], int]: stmt = select(Company) count_stmt = select(func.count()).select_from(Company) if keyword: pattern = f"%{keyword}%" cond = or_(Company.company_key.ilike(pattern), Company.name.ilike(pattern)) stmt = stmt.where(cond) count_stmt = count_stmt.where(cond) stmt = stmt.order_by(Company.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, company_key: str, name: str, status: str = "active") -> Company: item = Company(company_key=company_key, name=name, status=status) self.db.add(item) self.db.commit() self.db.refresh(item) return item