Files
member-backend/app/repositories/organizations_repo.py

68 lines
2.2 KiB
Python

from sqlalchemy import func, or_, select
from sqlalchemy.orm import Session
from app.models.organization import Organization
class OrganizationsRepository:
def __init__(self, db: Session) -> None:
self.db = db
def list(
self,
keyword: str | None = None,
status: str | None = None,
limit: int = 50,
offset: int = 0,
) -> tuple[list[Organization], int]:
stmt = select(Organization)
count_stmt = select(func.count()).select_from(Organization)
if keyword:
pattern = f"%{keyword}%"
cond = or_(Organization.org_code.ilike(pattern), Organization.name.ilike(pattern))
stmt = stmt.where(cond)
count_stmt = count_stmt.where(cond)
if status:
stmt = stmt.where(Organization.status == status)
count_stmt = count_stmt.where(Organization.status == status)
stmt = stmt.order_by(Organization.created_at.desc()).limit(limit).offset(offset)
items = list(self.db.scalars(stmt).all())
total = int(self.db.scalar(count_stmt) or 0)
return items, total
def get_by_id(self, org_id: str) -> Organization | None:
stmt = select(Organization).where(Organization.id == org_id)
return self.db.scalar(stmt)
def get_by_code(self, org_code: str) -> Organization | None:
stmt = select(Organization).where(Organization.org_code == org_code)
return self.db.scalar(stmt)
def create(self, org_code: str, name: str, tax_id: str | None, status: str = "active") -> Organization:
org = Organization(org_code=org_code, name=name, tax_id=tax_id, status=status)
self.db.add(org)
self.db.commit()
self.db.refresh(org)
return org
def update(
self,
org: Organization,
*,
name: str | None = None,
tax_id: str | None = None,
status: str | None = None,
) -> Organization:
if name is not None:
org.name = name
if tax_id is not None:
org.tax_id = tax_id
if status is not None:
org.status = status
self.db.commit()
self.db.refresh(org)
return org