175 lines
7.1 KiB
Python
175 lines
7.1 KiB
Python
from abc import ABC, abstractmethod
|
|
from typing import Optional, Tuple
|
|
|
|
from sqlalchemy import select, func, and_, or_, update
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.database.model.models import users, companies
|
|
from common.enums import ErrorType
|
|
from common.logger import LOG
|
|
from common.utils.gtime import GTime
|
|
|
|
|
|
# CRUD 는 인터페이스(I*) 와 구현(*) 으로 분리한다.
|
|
# - service 는 인터페이스 타입에 의존하고 Depends 로 구현을 주입받는다 (테스트/교체 용이).
|
|
# - 모든 메서드는 (session, ...) 을 받는다. session 은 람다 호출 시 매니저가 넘겨준다.
|
|
class IUserCRUD(ABC):
|
|
@abstractmethod
|
|
async def get_user_by_login_id(self, cdb: AsyncSession, login_id: str) -> Tuple[ErrorType, users]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def is_user(self, cdb: AsyncSession, login_id: str) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def add_user(self, cdb: AsyncSession, user: users) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def update_last_accessed(self, cdb: AsyncSession, user_id) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_company(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, companies]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def update_company_settings(self, cdb: AsyncSession, company_id, settings: dict) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def list_by_company(self, cdb: AsyncSession, company_id, search, skip, limit) -> Tuple[ErrorType, list, int]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_by_user_id(self, cdb: AsyncSession, user_id) -> Tuple[ErrorType, users]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def update_user(self, cdb: AsyncSession, user_id, data: dict) -> ErrorType:
|
|
pass
|
|
|
|
|
|
class UserCRUD(IUserCRUD):
|
|
async def get_user_by_login_id(self, cdb: AsyncSession, login_id: str) -> Tuple[ErrorType, users]:
|
|
try:
|
|
query = select(users).where(users.id == login_id, users.deleted == False).limit(1) # noqa: E712
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_user_by_login_id(ID:{login_id}) failed.")
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, None
|
|
if len(row_list) != 1:
|
|
return ErrorType.DB_INVALID_KEY, None
|
|
return ErrorType.SUCCESS, row_list[0]
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, None
|
|
|
|
async def is_user(self, cdb: AsyncSession, login_id: str) -> ErrorType:
|
|
try:
|
|
query = select(users).where(users.id == login_id, users.deleted == False).limit(1) # noqa: E712
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type
|
|
if row_list:
|
|
return ErrorType.DB_ALREADY_SAME_KEY
|
|
return ErrorType.SUCCESS
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def add_user(self, cdb: AsyncSession, user: users) -> ErrorType:
|
|
try:
|
|
return await DB_SESSION_MNG.insert(cdb, user)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def update_last_accessed(self, cdb: AsyncSession, user_id) -> ErrorType:
|
|
try:
|
|
query = update(users).where(users.user_id == user_id).values(last_accessed_at=GTime.UTC())
|
|
return await DB_SESSION_MNG.add(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def get_company(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, companies]:
|
|
try:
|
|
query = select(companies).where(companies.company_id == company_id, companies.deleted == False).limit(1) # noqa: E712
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, None
|
|
if len(row_list) != 1:
|
|
return ErrorType.DB_INVALID_KEY, None
|
|
return ErrorType.SUCCESS, row_list[0]
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, None
|
|
|
|
async def update_company_settings(self, cdb: AsyncSession, company_id, settings: dict) -> ErrorType:
|
|
try:
|
|
query = (
|
|
update(companies)
|
|
.where(companies.company_id == company_id, companies.deleted == False) # noqa: E712
|
|
.values(settings=settings, updated_at=GTime.UTC())
|
|
)
|
|
return await DB_SESSION_MNG.add(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def list_by_company(
|
|
self, cdb: AsyncSession, company_id, search: Optional[str], skip: int, limit: int
|
|
) -> Tuple[ErrorType, list, int]:
|
|
try:
|
|
conditions = [users.deleted == False, users.company_id == company_id] # noqa: E712
|
|
if search:
|
|
conditions.append(
|
|
or_(
|
|
users.id.ilike(f"%{search}%"),
|
|
users.name.ilike(f"%{search}%"),
|
|
users.email.ilike(f"%{search}%"),
|
|
)
|
|
)
|
|
where = and_(*conditions)
|
|
|
|
cnt_err, cnt_rows = await DB_SESSION_MNG.execute(cdb, select(func.count()).select_from(users).where(where))
|
|
if cnt_err != ErrorType.SUCCESS:
|
|
return cnt_err, [], 0
|
|
total = int(cnt_rows[0] or 0) if cnt_rows else 0
|
|
|
|
list_err, rows = await DB_SESSION_MNG.execute(
|
|
cdb,
|
|
select(users).where(where).order_by(users.created_at.desc()).offset(skip).limit(limit),
|
|
)
|
|
if list_err != ErrorType.SUCCESS:
|
|
return list_err, [], 0
|
|
return ErrorType.SUCCESS, list(rows), total
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, [], 0
|
|
|
|
async def get_by_user_id(self, cdb: AsyncSession, user_id) -> Tuple[ErrorType, users]:
|
|
try:
|
|
query = select(users).where(users.user_id == user_id, users.deleted == False).limit(1) # noqa: E712
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, None
|
|
if len(row_list) != 1:
|
|
return ErrorType.DB_INVALID_KEY, None
|
|
return ErrorType.SUCCESS, row_list[0]
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, None
|
|
|
|
async def update_user(self, cdb: AsyncSession, user_id, data: dict) -> ErrorType:
|
|
try:
|
|
if not data:
|
|
return ErrorType.SUCCESS
|
|
query = update(users).where(users.user_id == user_id).values(**data)
|
|
return await DB_SESSION_MNG.add(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|