[feat] negodata/backend: 상품·협력사·견적 도메인 CRUD + delivery_type 코드화 + 공용 /v1/enums
- item/supplier/quotation/quotation_setting CRUD·service·router 추가 - item protocol delivery_type str→int (ERD/스키마 SMALLINT 일치) - DeliveryType enum + 한글 라벨, 공용 GET /v1/enums (도메인 코드 메타데이터) - CompanyBrief → CompanyData 로 *Data 네이밍 통일 - CORS: WebServerConfig.client_url(단일) 도입 (config_models/router) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
7e2d5e5978
commit
1f778ab975
33 files changed
+2255
-85
No files matched your search
@@ -1,12 +1,14 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import tbl_account
|
||||
from common.enums import DBWRType, ErrorType
|
||||
from common.database.model.models import users
|
||||
from common.enums import DBWRType, ErrorType, UserStatus, UserRole
|
||||
from common.logger import LOG
|
||||
from common.models.gmodel import UserInfo
|
||||
from crud.user_crud import IUserCRUD, UserCRUD
|
||||
from router.v1.auth.protocol import Res_CreateAccount, Res_Login, Res_RefreshToken
|
||||
from router.v1.auth.protocol import CompanyData, Res_CreateAccount, Res_Login, Res_Me, Res_RefreshToken
|
||||
from router.v1.validator.dependencies import (
|
||||
CreateAccessToken,
|
||||
CreateRefreshToken,
|
||||
@@ -29,59 +31,68 @@ class AuthService:
|
||||
def __init__(self, user_crud: IUserCRUD = Depends(UserCRUD)):
|
||||
self.user_crud = user_crud
|
||||
|
||||
async def attempt_login(self, id: str, pw: str, connect_ip: str) -> Res_Login:
|
||||
LOG.i(f"LOGIN : {id=}")
|
||||
@staticmethod
|
||||
def _user_info(user: users) -> UserInfo:
|
||||
# uuid → str (JWT json 직렬화 위해). 기능 라우터는 company_id 로 스코프한다.
|
||||
return UserInfo(
|
||||
user_id=str(user.user_id),
|
||||
id=user.id,
|
||||
company_id=str(user.company_id),
|
||||
)
|
||||
|
||||
async def attempt_login(self, login_id: str, password: str, connect_ip: str) -> Res_Login:
|
||||
LOG.i(f"LOGIN : id={login_id}")
|
||||
res = Res_Login()
|
||||
|
||||
# 1) 계정 조회 (Read DB)
|
||||
err_type, account = await DB_SESSION_MNG.execute_lambda(
|
||||
tbl_account.DBType(),
|
||||
err_type, user = await DB_SESSION_MNG.execute_lambda(
|
||||
users.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_account_by_id(s, id),
|
||||
lambda s: self.user_crud.get_user_by_login_id(s, login_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
# 계정 없음/조회 실패 모두 로그인 실패로 일반화
|
||||
res.result.SetResult(ErrorType.ACCOUNT_INVALID_INFO)
|
||||
return res
|
||||
account: tbl_account
|
||||
user: users
|
||||
|
||||
# 2) 비밀번호 검증
|
||||
if not await VerifyPW(pw, account.pw):
|
||||
if not await VerifyPW(password, user.password):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_INVALID_INFO)
|
||||
return res
|
||||
|
||||
# 3) 차단 여부
|
||||
if account.is_blocked:
|
||||
# 3) 상태 확인 (활성 아니면 차단)
|
||||
if user.status != UserStatus.ACTIVE.value:
|
||||
res.result.SetResult(ErrorType.ACCOUNT_BLOCKED_USER)
|
||||
return res
|
||||
|
||||
# 4) 토큰 발급
|
||||
user_info = UserInfo(uid=account.uid, id=account.id, nickname=account.nickname)
|
||||
user_info = self._user_info(user)
|
||||
res.access_token = CreateAccessToken(user_info)
|
||||
res.refresh_token = CreateRefreshToken(user_info)
|
||||
|
||||
# 5) 마지막 로그인 시간 갱신 (Write DB, 트랜잭션)
|
||||
# 5) 마지막 접속 시간 갱신 (Write DB, 트랜잭션)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[tbl_account.DBType()],
|
||||
[lambda s: self.user_crud.update_last_login(s, account.uid)],
|
||||
[users.DBType()],
|
||||
[lambda s: self.user_crud.update_last_accessed(s, user.user_id)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
res.uid = account.uid
|
||||
res.nickname = account.nickname
|
||||
return res
|
||||
|
||||
async def create_account(self, id: str, pw: str, nickname: str, connect_ip: str) -> Res_CreateAccount:
|
||||
LOG.i(f"CREATE : {id=}, {nickname=}")
|
||||
async def create_account(
|
||||
self, login_id: str, password: str, company_id: str, name: str, email: str, contact_number: str, role: int
|
||||
) -> Res_CreateAccount:
|
||||
LOG.i(f"CREATE : id={login_id}, company_id={company_id}")
|
||||
res = Res_CreateAccount()
|
||||
|
||||
# 1) 중복 ID 확인 (Read DB)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda(
|
||||
tbl_account.DBType(),
|
||||
users.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.is_account(s, id),
|
||||
lambda s: self.user_crud.is_user(s, login_id),
|
||||
)
|
||||
if err_type == ErrorType.DB_ALREADY_SAME_KEY:
|
||||
res.result.SetResult(ErrorType.ACCOUNT_ALREADY_EXIST)
|
||||
@@ -91,10 +102,18 @@ class AuthService:
|
||||
return res
|
||||
|
||||
# 2) 계정 생성 (비밀번호는 bcrypt 해시로 저장)
|
||||
account = tbl_account(id=id, pw=await GetHashedPW(pw), nickname=nickname or id)
|
||||
user = users(
|
||||
company_id=uuid.UUID(company_id),
|
||||
id=login_id,
|
||||
password=await GetHashedPW(password),
|
||||
name=name or None,
|
||||
email=email or None,
|
||||
contact_number=contact_number or None,
|
||||
role=role or UserRole.USER.value,
|
||||
)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[tbl_account.DBType()],
|
||||
[lambda s: self.user_crud.add_account(s, account)],
|
||||
[users.DBType()],
|
||||
[lambda s: self.user_crud.add_user(s, user)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
# 사전 검사와 INSERT 사이의 경쟁 조건에서 unique 위반이 나면 동일 코드로 매핑.
|
||||
@@ -104,7 +123,40 @@ class AuthService:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
res.uid = account.uid
|
||||
res.user_id = str(user.user_id)
|
||||
return res
|
||||
|
||||
async def get_me(self, user_info: UserInfo) -> Res_Me:
|
||||
res = Res_Me()
|
||||
|
||||
# 1) 유저 조회
|
||||
err_type, user = await DB_SESSION_MNG.execute_lambda(
|
||||
users.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_user_by_login_id(s, user_info.id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(ErrorType.ACCOUNT_INVALID_INFO)
|
||||
return res
|
||||
user: users
|
||||
|
||||
# 2) 소속사 조회 (없어도 치명적 아님)
|
||||
company = None
|
||||
c_err, company_row = await DB_SESSION_MNG.execute_lambda(
|
||||
users.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_company(s, user.company_id),
|
||||
)
|
||||
if c_err == ErrorType.SUCCESS and company_row is not None:
|
||||
company = CompanyData(company_id=str(company_row.company_id), name=company_row.name)
|
||||
|
||||
res.user_id = str(user.user_id)
|
||||
res.id = user.id
|
||||
res.name = user.name
|
||||
res.email = user.email
|
||||
res.contact_number = user.contact_number
|
||||
res.role = user.role
|
||||
res.company = company
|
||||
return res
|
||||
|
||||
async def refresh_token(self, refresh_token: str) -> Res_RefreshToken:
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import items
|
||||
from common.enums import DBWRType, ErrorType
|
||||
from common.logger import LOG
|
||||
from crud.item_crud import IItemCRUD, ItemCRUD
|
||||
from router.v1.item.protocol import ItemData, Res_DeleteItem, Res_Item, Res_ItemList
|
||||
|
||||
|
||||
class ItemService:
|
||||
"""상품 비즈니스 로직. company_id 로 소유권을 확인한다(멀티테넌트)."""
|
||||
|
||||
def __init__(self, item_crud: IItemCRUD = Depends(ItemCRUD)):
|
||||
self.item_crud = item_crud
|
||||
|
||||
async def _fetch_owned(self, company_uuid: uuid.UUID, item_id: uuid.UUID):
|
||||
"""item 조회 + 소유권 확인. (ErrorType, item|None) 반환."""
|
||||
err_type, item = await DB_SESSION_MNG.execute_lambda(
|
||||
items.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.item_crud.get_by_id(s, item_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or item is None:
|
||||
return ErrorType.ITEM_NOT_FOUND, None
|
||||
if item.company_id != company_uuid:
|
||||
return ErrorType.ITEM_NOT_FOUND, None
|
||||
return ErrorType.SUCCESS, item
|
||||
|
||||
async def list_items(self, company_id: str, search, category, page: int, size: int) -> Res_ItemList:
|
||||
res = Res_ItemList(page=page, size=size)
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
skip = (page - 1) * size
|
||||
|
||||
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
|
||||
items.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.item_crud.search(s, company_uuid, search, category, skip, size),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.items = [ItemData.model_validate(r) for r in rows]
|
||||
res.total = total
|
||||
return res
|
||||
|
||||
async def get_item(self, company_id: str, item_id: str) -> Res_Item:
|
||||
res = Res_Item()
|
||||
err_type, item = await self._fetch_owned(uuid.UUID(company_id), uuid.UUID(item_id))
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.item = ItemData.model_validate(item)
|
||||
return res
|
||||
|
||||
async def create_item(self, company_id: str, user_id: str, data: dict) -> Res_Item:
|
||||
res = Res_Item()
|
||||
item = items(**data, company_id=uuid.UUID(company_id), user_id=uuid.UUID(user_id))
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[items.DBType()],
|
||||
[lambda s: self.item_crud.add_item(s, item)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 서버 기본값(created_at/updated_at)은 insert 후 Python 객체에 실리지 않으므로 재조회한다.
|
||||
return await self.get_item(company_id, str(item.item_id))
|
||||
|
||||
async def update_item(self, company_id: str, item_id: str, data: dict) -> Res_Item:
|
||||
res = Res_Item()
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
item_uuid = uuid.UUID(item_id)
|
||||
|
||||
# 소유권 확인
|
||||
err_type, _ = await self._fetch_owned(company_uuid, item_uuid)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[items.DBType()],
|
||||
[lambda s: self.item_crud.update_item(s, item_uuid, data)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 갱신 후 재조회
|
||||
return await self.get_item(company_id, item_id)
|
||||
|
||||
async def delete_item(self, company_id: str, item_id: str) -> Res_DeleteItem:
|
||||
res = Res_DeleteItem()
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
item_uuid = uuid.UUID(item_id)
|
||||
|
||||
err_type, _ = await self._fetch_owned(company_uuid, item_uuid)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[items.DBType()],
|
||||
[lambda s: self.item_crud.soft_delete(s, item_uuid)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
@@ -0,0 +1,184 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import quotations
|
||||
from common.enums import DBWRType, ErrorType
|
||||
from crud.quotation_crud import IQuotationCRUD, QuotationCRUD
|
||||
from router.v1.quotation.protocol import (
|
||||
AsyncJob,
|
||||
QuotationData,
|
||||
Res_CreateQuotation,
|
||||
Res_DeleteQuotation,
|
||||
Res_Quotation,
|
||||
Res_QuotationCards,
|
||||
Res_QuotationList,
|
||||
Res_QuotationResult,
|
||||
Res_QuotationSessions,
|
||||
Res_QuotationStatus,
|
||||
Res_SessionChat,
|
||||
)
|
||||
|
||||
|
||||
class QuotationService:
|
||||
"""견적 비즈니스 로직.
|
||||
|
||||
quotations 테이블에는 company_id 가 없어 회사 스코핑은 하지 않는다(토큰 검증만).
|
||||
user_id 는 생성 시 소유자로만 기록한다(조회/변경 시 소유권 필터 없음).
|
||||
"""
|
||||
|
||||
def __init__(self, quotation_crud: IQuotationCRUD = Depends(QuotationCRUD)):
|
||||
self.quotation_crud = quotation_crud
|
||||
|
||||
async def _fetch(self, qt_id: uuid.UUID):
|
||||
"""견적 단건 조회. (ErrorType, quotation|None) 반환. (회사 스코프 없음)"""
|
||||
err_type, quotation = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.get_by_id(s, qt_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or quotation is None:
|
||||
return ErrorType.QUOTATION_NOT_FOUND, None
|
||||
return ErrorType.SUCCESS, quotation
|
||||
|
||||
async def list_quotations(self, status, type_, start_from, start_to, page: int, size: int) -> Res_QuotationList:
|
||||
res = Res_QuotationList(page=page, size=size)
|
||||
skip = (page - 1) * size
|
||||
|
||||
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.search(s, status, type_, start_from, start_to, skip, size),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.quotations = [QuotationData.model_validate(r) for r in rows]
|
||||
res.total = total
|
||||
return res
|
||||
|
||||
async def get_quotation(self, qt_id: str) -> Res_Quotation:
|
||||
res = Res_Quotation()
|
||||
err_type, quotation = await self._fetch(uuid.UUID(qt_id))
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.quotation = QuotationData.model_validate(quotation)
|
||||
return res
|
||||
|
||||
async def create_quotation(self, user_id: str, data: dict) -> Res_CreateQuotation:
|
||||
res = Res_CreateQuotation()
|
||||
quotation = quotations(**data, user_id=uuid.UUID(user_id))
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotations.DBType()],
|
||||
[lambda s: self.quotation_crud.add_quotation(s, quotation)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 서버 기본값(created_at/updated_at) 로드 위해 재조회 (응답 shape 은 Res_CreateQuotation 유지).
|
||||
f_err, fresh = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.get_by_id(s, quotation.qt_id),
|
||||
)
|
||||
res.quotation = QuotationData.model_validate(fresh if f_err == ErrorType.SUCCESS and fresh is not None else quotation)
|
||||
# 네고시움 백엔드 비동기 요청은 스텁이므로 row 만 생성한다.
|
||||
res.async_job = AsyncJob(status="submitted", message="견적 생성 작업 요청됨(스텁)")
|
||||
return res
|
||||
|
||||
async def stop_quotation(self, qt_id: str) -> Res_Quotation:
|
||||
res = Res_Quotation()
|
||||
qt_uuid = uuid.UUID(qt_id)
|
||||
|
||||
# 존재 확인
|
||||
err_type, _ = await self._fetch(qt_uuid)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 상태를 '견적마감'으로 변경(실제 DB 업데이트)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotations.DBType()],
|
||||
[lambda s: self.quotation_crud.update_quotation(s, qt_uuid, {"status": "견적마감"})],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 갱신 후 재조회
|
||||
return await self.get_quotation(qt_id)
|
||||
|
||||
async def delete_quotation(self, qt_id: str) -> Res_DeleteQuotation:
|
||||
res = Res_DeleteQuotation()
|
||||
qt_uuid = uuid.UUID(qt_id)
|
||||
|
||||
err_type, _ = await self._fetch(qt_uuid)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotations.DBType()],
|
||||
[lambda s: self.quotation_crud.soft_delete(s, qt_uuid)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
async def get_status(self, qt_id: str) -> Res_QuotationStatus:
|
||||
res = Res_QuotationStatus()
|
||||
err_type, quotation = await self._fetch(uuid.UUID(qt_id))
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.qt_id = quotation.qt_id
|
||||
res.job_status = quotation.status
|
||||
res.message = "ok"
|
||||
return res
|
||||
|
||||
async def get_result(self, qt_id: str) -> Res_QuotationResult:
|
||||
res = Res_QuotationResult()
|
||||
err_type, quotation = await self._fetch(uuid.UUID(qt_id))
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 낙찰 결과는 quotations 컬럼에서 직접 노출. results 테이블 미존재로 result_count 는 0.
|
||||
res.qt_id = quotation.qt_id
|
||||
res.winner_supplier_id = quotation.preferred_sp_id
|
||||
res.winner_supplier_name = quotation.preferred_sp_name
|
||||
res.is_equal_bid = quotation.equal_bid_yn
|
||||
res.equal_bid_data = quotation.equal_bid_data
|
||||
res.result_count = 0
|
||||
return res
|
||||
|
||||
async def list_sessions(self, qt_id: str) -> Res_QuotationSessions:
|
||||
# sessions 모델 미존재 — 존재 검증 후 빈 목록 반환(스텁).
|
||||
res = Res_QuotationSessions()
|
||||
err_type, quotation = await self._fetch(uuid.UUID(qt_id))
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.qt_id = quotation.qt_id
|
||||
res.sessions = []
|
||||
res.total = 0
|
||||
return res
|
||||
|
||||
async def list_chats(self, session_id: str) -> Res_SessionChat:
|
||||
# chats 모델 미존재 — 빈 목록 반환(스텁).
|
||||
res = Res_SessionChat()
|
||||
res.session_id = uuid.UUID(session_id)
|
||||
res.messages = []
|
||||
return res
|
||||
|
||||
async def list_cards(self, qt_id: str) -> Res_QuotationCards:
|
||||
# quotation_cards 모델 미존재 — 존재 검증 후 빈 목록 반환(스텁).
|
||||
res = Res_QuotationCards()
|
||||
err_type, quotation = await self._fetch(uuid.UUID(qt_id))
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.qt_id = quotation.qt_id
|
||||
res.cards = []
|
||||
return res
|
||||
@@ -0,0 +1,112 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import quotation_settings
|
||||
from common.enums import DBWRType, ErrorType
|
||||
from crud.quotation_setting_crud import IQuotationSettingCRUD, QuotationSettingCRUD
|
||||
from router.v1.quotation_setting.protocol import (
|
||||
QuotationSettingData,
|
||||
Res_DeleteQuotationSetting,
|
||||
Res_QuotationSetting,
|
||||
Res_QuotationSettingList,
|
||||
)
|
||||
|
||||
|
||||
class QuotationSettingService:
|
||||
"""견적 설정 비즈니스 로직. user_id 로 소유권을 확인한다(유저별 설정)."""
|
||||
|
||||
def __init__(self, qs_crud: IQuotationSettingCRUD = Depends(QuotationSettingCRUD)):
|
||||
self.qs_crud = qs_crud
|
||||
|
||||
async def _fetch_owned(self, user_uuid: uuid.UUID, qt_setting_id: uuid.UUID):
|
||||
"""설정 조회 + 소유권 확인. (ErrorType, setting|None) 반환."""
|
||||
err_type, setting = await DB_SESSION_MNG.execute_lambda(
|
||||
quotation_settings.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.qs_crud.get_by_id(s, qt_setting_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or setting is None:
|
||||
return ErrorType.QUOTATION_SETTING_NOT_FOUND, None
|
||||
if setting.user_id != user_uuid:
|
||||
return ErrorType.QUOTATION_SETTING_NOT_FOUND, None
|
||||
return ErrorType.SUCCESS, setting
|
||||
|
||||
async def list_settings(self, user_id: str) -> Res_QuotationSettingList:
|
||||
res = Res_QuotationSettingList()
|
||||
user_uuid = uuid.UUID(user_id)
|
||||
|
||||
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
|
||||
quotation_settings.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.qs_crud.list_by_user(s, user_uuid),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.settings = [QuotationSettingData.model_validate(r) for r in rows]
|
||||
res.total = total
|
||||
return res
|
||||
|
||||
async def get_setting(self, user_id: str, qt_setting_id: str) -> Res_QuotationSetting:
|
||||
res = Res_QuotationSetting()
|
||||
err_type, setting = await self._fetch_owned(uuid.UUID(user_id), uuid.UUID(qt_setting_id))
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.setting = QuotationSettingData.model_validate(setting)
|
||||
return res
|
||||
|
||||
async def create_setting(self, user_id: str, data: dict) -> Res_QuotationSetting:
|
||||
res = Res_QuotationSetting()
|
||||
setting = quotation_settings(**data, user_id=uuid.UUID(user_id))
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotation_settings.DBType()],
|
||||
[lambda s: self.qs_crud.add_setting(s, setting)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 서버 기본값(created_at/updated_at)은 insert 후 객체에 실리지 않으므로 재조회한다.
|
||||
return await self.get_setting(user_id, str(setting.qt_setting_id))
|
||||
|
||||
async def update_setting(self, user_id: str, qt_setting_id: str, data: dict) -> Res_QuotationSetting:
|
||||
res = Res_QuotationSetting()
|
||||
user_uuid = uuid.UUID(user_id)
|
||||
setting_uuid = uuid.UUID(qt_setting_id)
|
||||
|
||||
# 소유권 확인
|
||||
err_type, _ = await self._fetch_owned(user_uuid, setting_uuid)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotation_settings.DBType()],
|
||||
[lambda s: self.qs_crud.update_setting(s, setting_uuid, data)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 갱신 후 재조회
|
||||
return await self.get_setting(user_id, qt_setting_id)
|
||||
|
||||
async def delete_setting(self, user_id: str, qt_setting_id: str) -> Res_DeleteQuotationSetting:
|
||||
res = Res_DeleteQuotationSetting()
|
||||
user_uuid = uuid.UUID(user_id)
|
||||
setting_uuid = uuid.UUID(qt_setting_id)
|
||||
|
||||
err_type, _ = await self._fetch_owned(user_uuid, setting_uuid)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotation_settings.DBType()],
|
||||
[lambda s: self.qs_crud.soft_delete(s, setting_uuid)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
@@ -0,0 +1,109 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import suppliers
|
||||
from common.enums import DBWRType, ErrorType
|
||||
from common.logger import LOG
|
||||
from crud.supplier_crud import ISupplierCRUD, SupplierCRUD
|
||||
from router.v1.supplier.protocol import Res_DeleteSupplier, Res_Supplier, Res_SupplierList, SupplierData
|
||||
|
||||
|
||||
class SupplierService:
|
||||
"""협력사 비즈니스 로직. company_id 로 소유권을 확인한다(멀티테넌트)."""
|
||||
|
||||
def __init__(self, supplier_crud: ISupplierCRUD = Depends(SupplierCRUD)):
|
||||
self.supplier_crud = supplier_crud
|
||||
|
||||
async def _fetch_owned(self, company_uuid: uuid.UUID, supplier_id: uuid.UUID):
|
||||
"""supplier 조회 + 소유권 확인. (ErrorType, supplier|None) 반환."""
|
||||
err_type, supplier = await DB_SESSION_MNG.execute_lambda(
|
||||
suppliers.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.supplier_crud.get_by_id(s, supplier_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or supplier is None:
|
||||
return ErrorType.SUPPLIER_NOT_FOUND, None
|
||||
if supplier.company_id != company_uuid:
|
||||
return ErrorType.SUPPLIER_NOT_FOUND, None
|
||||
return ErrorType.SUCCESS, supplier
|
||||
|
||||
async def list_suppliers(self, company_id: str, search, page: int, size: int) -> Res_SupplierList:
|
||||
res = Res_SupplierList(page=page, size=size)
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
skip = (page - 1) * size
|
||||
|
||||
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
|
||||
suppliers.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.supplier_crud.search(s, company_uuid, search, skip, size),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.suppliers = [SupplierData.model_validate(r) for r in rows]
|
||||
res.total = total
|
||||
return res
|
||||
|
||||
async def get_supplier(self, company_id: str, supplier_id: str) -> Res_Supplier:
|
||||
res = Res_Supplier()
|
||||
err_type, supplier = await self._fetch_owned(uuid.UUID(company_id), uuid.UUID(supplier_id))
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.supplier = SupplierData.model_validate(supplier)
|
||||
return res
|
||||
|
||||
async def create_supplier(self, company_id: str, user_id: str, data: dict) -> Res_Supplier:
|
||||
res = Res_Supplier()
|
||||
supplier = suppliers(**data, company_id=uuid.UUID(company_id), user_id=uuid.UUID(user_id))
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[suppliers.DBType()],
|
||||
[lambda s: self.supplier_crud.add_supplier(s, supplier)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 서버 기본값(created_at/updated_at)은 insert 후 객체에 실리지 않으므로 재조회한다.
|
||||
return await self.get_supplier(company_id, str(supplier.supplier_id))
|
||||
|
||||
async def update_supplier(self, company_id: str, supplier_id: str, data: dict) -> Res_Supplier:
|
||||
res = Res_Supplier()
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
supplier_uuid = uuid.UUID(supplier_id)
|
||||
|
||||
# 소유권 확인
|
||||
err_type, _ = await self._fetch_owned(company_uuid, supplier_uuid)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[suppliers.DBType()],
|
||||
[lambda s: self.supplier_crud.update_supplier(s, supplier_uuid, data)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 갱신 후 재조회
|
||||
return await self.get_supplier(company_id, supplier_id)
|
||||
|
||||
async def delete_supplier(self, company_id: str, supplier_id: str) -> Res_DeleteSupplier:
|
||||
res = Res_DeleteSupplier()
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
supplier_uuid = uuid.UUID(supplier_id)
|
||||
|
||||
err_type, _ = await self._fetch_owned(company_uuid, supplier_uuid)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[suppliers.DBType()],
|
||||
[lambda s: self.supplier_crud.soft_delete(s, supplier_uuid)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
Reference in new issue
Block a user