260 lines
11 KiB
Python
260 lines
11 KiB
Python
from abc import ABC, abstractmethod
|
|
from typing import Tuple
|
|
|
|
from sqlalchemy import delete, select, update
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.database.model.models import supplier_user_tokens, supplier_users, suppliers, companies
|
|
from common.enums import ErrorType, TokenType
|
|
from common.logger import LOG
|
|
from common.utils.gtime import GTime
|
|
|
|
|
|
# CRUD 는 인터페이스(I*) 와 구현(*) 으로 분리한다.
|
|
# - service 는 인터페이스 타입에 의존하고 Depends 로 구현을 주입받는다 (테스트/교체 용이).
|
|
# - 모든 메서드는 (session, ...) 을 받는다. session 은 람다 호출 시 매니저가 넘겨준다.
|
|
# - 유저는 supplier_users 테이블, 공급사명은 partner.suppliers 에서 조회한다(no-FK).
|
|
class IUserCRUD(ABC):
|
|
@abstractmethod
|
|
async def get_account_by_id(self, cdb: AsyncSession, login_id: str) -> Tuple[ErrorType, supplier_users]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_account_by_su_id(self, cdb: AsyncSession, su_id) -> Tuple[ErrorType, supplier_users]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, str]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_company_settings(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, dict]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def add_account(self, cdb: AsyncSession, account: supplier_users) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def add_token(self, cdb: AsyncSession, token: supplier_user_tokens) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_token(self, cdb: AsyncSession, su_id, token_type: int) -> Tuple[ErrorType, str]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def delete_tokens_by_su_id(self, cdb: AsyncSession, su_id) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def update_access_token(self, cdb: AsyncSession, su_id, token, issued_at, expired_at) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def update_last_accessed(self, cdb: AsyncSession, su_id) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_hide_service_info(self, cdb: AsyncSession, su_id) -> Tuple[ErrorType, bool]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def set_hide_service_info(self, cdb: AsyncSession, su_id) -> ErrorType:
|
|
pass
|
|
|
|
|
|
class UserCRUD(IUserCRUD):
|
|
async def get_account_by_id(self, cdb: AsyncSession, login_id: str) -> Tuple[ErrorType, supplier_users]:
|
|
try:
|
|
query = (
|
|
select(supplier_users)
|
|
.where(supplier_users.id == login_id, supplier_users.deleted == False) # noqa: E712
|
|
.limit(1)
|
|
)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_account_by_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 get_account_by_su_id(self, cdb: AsyncSession, su_id) -> Tuple[ErrorType, supplier_users]:
|
|
try:
|
|
query = (
|
|
select(supplier_users)
|
|
.where(supplier_users.su_id == su_id, supplier_users.deleted == False) # noqa: E712
|
|
.limit(1)
|
|
)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_account_by_su_id(su_id:{su_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 get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, str]:
|
|
try:
|
|
query = (
|
|
select(suppliers.name)
|
|
.where(suppliers.supplier_id == supplier_id, suppliers.deleted == False) # noqa: E712
|
|
.limit(1)
|
|
)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_supplier_name(supplier_id:{supplier_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 get_company_settings(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, dict]:
|
|
"""공급사 소속 회사 설정(companies.settings) 전체. 브랜딩·협상완료 필드 등이 들어있다. 미설정이면 빈 dict."""
|
|
try:
|
|
query = (
|
|
select(companies.settings)
|
|
.join(suppliers, suppliers.company_id == companies.company_id)
|
|
.where(suppliers.supplier_id == supplier_id, suppliers.deleted == False, companies.deleted == False) # noqa: E712
|
|
.limit(1)
|
|
)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_company_settings(supplier_id:{supplier_id}) failed.")
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, {}
|
|
settings = row_list[0] if row_list else None
|
|
return ErrorType.SUCCESS, settings or {}
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, {}
|
|
|
|
|
|
async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType:
|
|
try:
|
|
query = (
|
|
select(supplier_users)
|
|
.where(supplier_users.id == login_id, supplier_users.deleted == False) # noqa: E712
|
|
.limit(1)
|
|
)
|
|
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_account(self, cdb: AsyncSession, account: supplier_users) -> ErrorType:
|
|
try:
|
|
return await DB_SESSION_MNG.insert(cdb, account)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def add_token(self, cdb: AsyncSession, token: supplier_user_tokens) -> ErrorType:
|
|
try:
|
|
return await DB_SESSION_MNG.insert(cdb, token)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def get_token(self, cdb: AsyncSession, su_id, token_type: int) -> Tuple[ErrorType, str]:
|
|
# 저장된 토큰(jwt 문자열)을 반환한다. stateful 검증(제시 토큰 ↔ 저장 토큰 대조)용.
|
|
try:
|
|
query = (
|
|
select(supplier_user_tokens.token["jwt"].astext)
|
|
.where(
|
|
supplier_user_tokens.su_id == su_id,
|
|
supplier_user_tokens.type == token_type,
|
|
supplier_user_tokens.deleted == False, # noqa: E712
|
|
)
|
|
.limit(1)
|
|
)
|
|
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 delete_tokens_by_su_id(self, cdb: AsyncSession, su_id) -> ErrorType:
|
|
# 단일 세션: 로그인/로그아웃 시 해당 유저의 토큰 행을 모두 제거한다(하드 삭제, 누적 방지).
|
|
try:
|
|
query = delete(supplier_user_tokens).where(supplier_user_tokens.su_id == su_id)
|
|
return await DB_SESSION_MNG.add(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def update_access_token(self, cdb: AsyncSession, su_id, token, issued_at, expired_at) -> ErrorType:
|
|
# 재발급 시 저장된 access 행만 새 토큰으로 갱신한다.
|
|
try:
|
|
query = (
|
|
update(supplier_user_tokens)
|
|
.where(
|
|
supplier_user_tokens.su_id == su_id,
|
|
supplier_user_tokens.type == TokenType.ACCESS.value,
|
|
supplier_user_tokens.deleted == False, # noqa: E712
|
|
)
|
|
.values(token=token, issued_at=issued_at, expired_at=expired_at)
|
|
)
|
|
return await DB_SESSION_MNG.add(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def update_last_accessed(self, cdb: AsyncSession, su_id) -> ErrorType:
|
|
try:
|
|
query = update(supplier_users).where(supplier_users.su_id == su_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_hide_service_info(self, cdb: AsyncSession, su_id) -> Tuple[ErrorType, bool]:
|
|
# 서비스 안내 팝업 "안내 보지 않기" 여부만 조회한다.
|
|
try:
|
|
query = (
|
|
select(supplier_users.hide_service_info)
|
|
.where(supplier_users.su_id == su_id, supplier_users.deleted == False) # noqa: E712
|
|
.limit(1)
|
|
)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_hide_service_info(su_id:{su_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 set_hide_service_info(self, cdb: AsyncSession, su_id) -> ErrorType:
|
|
# "안내 보지 않기" 는 켜기만 있다(해제 API 없음).
|
|
try:
|
|
query = (
|
|
update(supplier_users)
|
|
.where(supplier_users.su_id == su_id, supplier_users.deleted == False) # noqa: E712
|
|
.values(hide_service_info=True)
|
|
)
|
|
return await DB_SESSION_MNG.add(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|