[feat] negodata: 소유권 게이팅 + 견적 낙찰 + 작성자명 표시 + 전화입력 + 카드 엑셀
- 소유권 게이팅(common/authz): 변경 액션 본인∪OWNER, 협력사 삭제 OWNER 전용 - 견적 수동 낙찰(award) + 작성자명(creatorName) 표시 + 전화번호 입력 컴포넌트 + 카드 엑셀 업로드 - supplier_type 은 이번 커밋 미변경(다음 커밋에서 코드부터 정리 예정) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
c32ee300e6
commit
c62b66e35b
56 files changed
+1900
-188
No files matched your search
@@ -0,0 +1,9 @@
|
||||
from common.enums import UserRole
|
||||
|
||||
|
||||
def is_owner_or_admin(resource_user_id, user_id, role) -> bool:
|
||||
"""변경 액션 공용 소유권 판정 — 리소스 소유자(user_id 일치) 또는 최고관리자(OWNER)면 True.
|
||||
|
||||
프론트의 버튼 게이팅과 같은 규칙을 백엔드에서 강제하는 단일 출처.
|
||||
소유자 없는 공용 리소스(예: user_id NULL 공용카드)는 이 판정 대상이 아니다(도메인별 별도 처리)."""
|
||||
return str(resource_user_id) == str(user_id) or role == UserRole.OWNER.value
|
||||
@@ -5,6 +5,7 @@ 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
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
@@ -32,13 +33,21 @@ class ICardCRUD(ABC):
|
||||
async def soft_delete(self, cdb: AsyncSession, model, pk_col, card_id) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
||||
pass
|
||||
|
||||
|
||||
class CardCRUD(ICardCRUD):
|
||||
async def search(
|
||||
self, cdb: AsyncSession, model, user_id, search: Optional[str], skip: int, limit: int
|
||||
) -> Tuple[ErrorType, list, int]:
|
||||
try:
|
||||
conditions = [model.deleted == False, model.user_id == user_id] # noqa: E712
|
||||
# 내 개인 카드 + 전체(공용, user_id NULL) 카드. 남의 개인 카드는 제외.
|
||||
conditions = [
|
||||
model.deleted == False, # noqa: E712
|
||||
or_(model.user_id == user_id, model.user_id.is_(None)),
|
||||
]
|
||||
if search:
|
||||
conditions.append(
|
||||
or_(
|
||||
@@ -102,3 +111,18 @@ class CardCRUD(ICardCRUD):
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
||||
"""user_id 목록 → {user_id: name}. 카드 목록 '작성자(등록자)' 표기용(company.users 조인).
|
||||
공용(user_id NULL) 카드는 호출 전에 걸러 넘긴다 → 맵에 없으면 작성자 없음."""
|
||||
try:
|
||||
if not user_ids:
|
||||
return ErrorType.SUCCESS, {}
|
||||
query = select(users.user_id, users.name).where(users.user_id.in_(user_ids))
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, {}
|
||||
return ErrorType.SUCCESS, {uid: name for uid, name in rows}
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, {}
|
||||
@@ -5,7 +5,7 @@ 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 items
|
||||
from common.database.model.models import items, users
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
@@ -45,6 +45,10 @@ class IItemCRUD(ABC):
|
||||
async def soft_delete(self, cdb: AsyncSession, item_id) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
||||
pass
|
||||
|
||||
|
||||
class ItemCRUD(IItemCRUD):
|
||||
async def search(
|
||||
@@ -166,3 +170,17 @@ class ItemCRUD(IItemCRUD):
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
||||
"""user_id 목록 → {user_id: name}. 상품 목록/상세 '등록자(작성자)' 표기용(company.users 조인)."""
|
||||
try:
|
||||
if not user_ids:
|
||||
return ErrorType.SUCCESS, {}
|
||||
query = select(users.user_id, users.name).where(users.user_id.in_(user_ids))
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, {}
|
||||
return ErrorType.SUCCESS, {uid: name for uid, name in rows}
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, {}
|
||||
@@ -10,7 +10,7 @@ from common.database.model.models import (
|
||||
quotations, sessions, chats, nego_cards, wild_cards, items, suppliers, quotation_settings,
|
||||
version_nego_cards, version_wild_cards, users,
|
||||
)
|
||||
from common.enums import ErrorType, QuotationStatus, SessionStatus
|
||||
from common.enums import CloseReason, ErrorType, QuotationStatus, SessionStatus
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
|
||||
@@ -148,6 +148,10 @@ class IQuotationCRUD(ABC):
|
||||
async def claim_for_close(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, int]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def claim_for_award(self, cdb: AsyncSession, qt_id, supplier_id, supplier_name) -> Tuple[ErrorType, int]:
|
||||
pass
|
||||
|
||||
|
||||
class QuotationCRUD(IQuotationCRUD):
|
||||
async def search(
|
||||
@@ -474,6 +478,36 @@ class QuotationCRUD(IQuotationCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def claim_for_award(self, cdb: AsyncSession, qt_id, supplier_id, supplier_name) -> Tuple[ErrorType, int]:
|
||||
"""[동시 직접낙찰 가드] 개찰(마감·낙찰자 미정, close_reason ∈ OPEN_*)인 견적만 낙찰(AWARDED)로 선점 전이.
|
||||
선택 협력사를 낙찰자(preferred_sp_*)로 박고 동가 플래그는 내린다. status 는 이미 CLOSED 라 유지.
|
||||
반환: (ErrorType, 적용행수). 이미 낙찰됐거나(재클릭) 개찰이 아니면 0 → 서비스가 한 번만 통과시킨다."""
|
||||
try:
|
||||
query = (
|
||||
update(quotations)
|
||||
.where(
|
||||
quotations.qt_id == qt_id,
|
||||
quotations.status == QuotationStatus.CLOSED.value,
|
||||
quotations.close_reason.in_(
|
||||
[CloseReason.OPEN_PRICE.value, CloseReason.OPEN_EQUAL.value,
|
||||
CloseReason.OPEN_NOSHOW.value, CloseReason.OPEN_REJECT.value]
|
||||
),
|
||||
quotations.deleted == False, # noqa: E712
|
||||
)
|
||||
.values(
|
||||
close_reason=CloseReason.AWARDED.value,
|
||||
preferred_sp_yn=True,
|
||||
preferred_sp_id=supplier_id,
|
||||
preferred_sp_name=supplier_name,
|
||||
equal_bid_yn=False,
|
||||
updated_at=GTime.UTC(),
|
||||
)
|
||||
)
|
||||
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def update_sessions_status(self, cdb: AsyncSession, qt_id, from_statuses: list[int], to_status: int) -> ErrorType:
|
||||
# 견적에 딸린 세션 중 from_statuses 에 속한 것만 to_status 로 일괄 전이(삭제 제외). 다른 상태는 건드리지 않는다.
|
||||
try:
|
||||
|
||||
@@ -5,7 +5,7 @@ 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 suppliers
|
||||
from common.database.model.models import suppliers, users
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
@@ -41,6 +41,10 @@ class ISupplierCRUD(ABC):
|
||||
async def soft_delete(self, cdb: AsyncSession, supplier_id) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
||||
pass
|
||||
|
||||
|
||||
class SupplierCRUD(ISupplierCRUD):
|
||||
async def search(
|
||||
@@ -144,3 +148,17 @@ class SupplierCRUD(ISupplierCRUD):
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
||||
"""user_id 목록 → {user_id: name}. 협력사 목록/상세 '등록자(작성자)' 표기용(company.users 조인)."""
|
||||
try:
|
||||
if not user_ids:
|
||||
return ErrorType.SUCCESS, {}
|
||||
query = select(users.user_id, users.name).where(users.user_id.in_(user_ids))
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, {}
|
||||
return ErrorType.SUCCESS, {uid: name for uid, name in rows}
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, {}
|
||||
@@ -14,6 +14,7 @@ class CardProtocol(WebPacketProtocol):
|
||||
|
||||
class Req_CreateCard(CardProtocol):
|
||||
is_wildcard: bool = False
|
||||
is_shared: bool = False # True=전체(공용, user_id NULL 저장) / False=개인(등록 유저 소유)
|
||||
name: Optional[str] = None
|
||||
number: Optional[str] = None
|
||||
script: Optional[str] = None
|
||||
@@ -42,6 +43,8 @@ class CardData(WebPacketProtocol):
|
||||
nego_card_id: uuid.UUID # 통합 식별자(일반=nego_card_id / 와일드=wild_card_id)
|
||||
user_id: Optional[uuid.UUID] = None
|
||||
is_wildcard: bool = False
|
||||
is_shared: bool = False # 전체(공용) 카드 여부 = user_id NULL. 목록 배지/폼 스코프 표시용
|
||||
creator_name: Optional[str] = None # 작성자(등록자) 이름. user_id→company.users.name 조인. 공용 카드는 None
|
||||
name: Optional[str] = None
|
||||
number: Optional[str] = None
|
||||
script: Optional[str] = None
|
||||
|
||||
@@ -69,12 +69,12 @@ async def get_item(item_id: UUID, service: ItemService = Depends(), user_info: U
|
||||
async def update_item(
|
||||
item_id: UUID, req: Req_UpdateItem, service: ItemService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||
):
|
||||
return RemoveNoneResponse(await service.update_item(user_info.company_id, str(item_id), req))
|
||||
return RemoveNoneResponse(await service.update_item(user_info.company_id, str(item_id), req, user_info.user_id, user_info.role))
|
||||
|
||||
|
||||
@router.delete(path="/delete/{item_id}", response_model=Res_DeleteItem, summary="상품 삭제")
|
||||
async def delete_item(item_id: UUID, service: ItemService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
return RemoveNoneResponse(await service.delete_item(user_info.company_id, str(item_id)))
|
||||
return RemoveNoneResponse(await service.delete_item(user_info.company_id, str(item_id), user_info.user_id, user_info.role))
|
||||
|
||||
|
||||
@router.post(path="/{item_id}/lowest-price", response_model=Res_LowestPriceTrigger, summary="최저가 수집 요청(스텁)")
|
||||
|
||||
@@ -64,6 +64,7 @@ class ItemData(WebPacketProtocol):
|
||||
item_id: uuid.UUID
|
||||
company_id: uuid.UUID
|
||||
user_id: uuid.UUID
|
||||
creator_name: Optional[str] = None # 등록자(작성자) 이름. user_id→company.users.name 조인
|
||||
name: str
|
||||
code: Optional[str] = None
|
||||
category: Optional[str] = None
|
||||
|
||||
@@ -40,6 +40,10 @@ class Req_RegenerateQuotation(QuotationProtocol):
|
||||
supplier_ids: list[uuid.UUID] = [] # 다음 라운드에 부를 공급사(프론트 선택). 상품·기간·번호는 원 견적에서 이어받음
|
||||
|
||||
|
||||
class Req_AwardQuotation(QuotationProtocol):
|
||||
winner_supplier_id: uuid.UUID # 담당자가 직접 낙찰시킬 협력사(투찰한 협상완료 세션 중 선택)
|
||||
|
||||
|
||||
class QuotationData(WebPacketProtocol):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ from common.models.gmodel import PageParams, UserInfo
|
||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
|
||||
from services.quotation_service import QuotationService
|
||||
from .protocol import (
|
||||
Req_AwardQuotation,
|
||||
Req_CreateQuotation,
|
||||
Req_RegenerateQuotation,
|
||||
Res_CreateQuotation,
|
||||
@@ -55,14 +56,24 @@ async def create_quotation(
|
||||
|
||||
@router.post(path="/stop/{qt_id}", response_model=Res_Quotation, summary="견적 마감")
|
||||
async def stop_quotation(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
return RemoveNoneResponse(await service.stop_quotation(str(qt_id), user_info.company_id))
|
||||
return RemoveNoneResponse(await service.stop_quotation(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
|
||||
|
||||
|
||||
@router.post(path="/award/{qt_id}", response_model=Res_Quotation, summary="개찰 견적 직접 낙찰")
|
||||
async def award_quotation(
|
||||
qt_id: UUID, req: Req_AwardQuotation, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||
):
|
||||
# 권한(본인 견적만/OWNER 예외)은 서비스에서 판정하도록 호출자 user_id·role 을 넘긴다.
|
||||
return RemoveNoneResponse(
|
||||
await service.award_quotation(str(qt_id), user_info.company_id, user_info.user_id, user_info.role, req.winner_supplier_id)
|
||||
)
|
||||
|
||||
|
||||
@router.post(path="/regenerate/{qt_id}", response_model=Res_CreateQuotation, summary="견적 재생성(다음 라운드)")
|
||||
async def regenerate_quotation(
|
||||
qt_id: UUID, req: Req_RegenerateQuotation, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||
):
|
||||
return RemoveNoneResponse(await service.regenerate_quotation(str(qt_id), user_info.company_id, req.supplier_ids))
|
||||
return RemoveNoneResponse(await service.regenerate_quotation(str(qt_id), user_info.company_id, req.supplier_ids, user_info.user_id, user_info.role))
|
||||
|
||||
|
||||
# ----- 견적 상세 (FK로 연결된 하위 데이터 / 일부는 모델 미존재로 스텁) -----
|
||||
@@ -78,7 +89,7 @@ async def get_quotation_sessions(qt_id: UUID, service: QuotationService = Depend
|
||||
|
||||
@router.post(path="/{qt_id}/notify", response_model=Res_NotifySessions, summary="협상 초청 메일 발송")
|
||||
async def notify_quotation(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
return RemoveNoneResponse(await service.notify_sessions(str(qt_id), user_info.company_id))
|
||||
return RemoveNoneResponse(await service.notify_sessions(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
|
||||
|
||||
|
||||
@router.get(path="/session/{session_id}/chat", response_model=Res_SessionChat, summary="채팅 상세")
|
||||
@@ -93,7 +104,7 @@ async def get_target_breakdown(session_id: UUID, service: QuotationService = Dep
|
||||
|
||||
@router.post(path="/session/{session_id}/notify", response_model=Res_NotifySessions, summary="세션 초청 메일 재발송")
|
||||
async def notify_session(session_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
return RemoveNoneResponse(await service.notify_session(str(session_id), user_info.company_id))
|
||||
return RemoveNoneResponse(await service.notify_session(str(session_id), user_info.company_id, user_info.user_id, user_info.role))
|
||||
|
||||
|
||||
@router.get(path="/{qt_id}/result", response_model=Res_QuotationResult, summary="낙찰 결과")
|
||||
@@ -108,7 +119,7 @@ async def get_quotation_cards(qt_id: UUID, service: QuotationService = Depends()
|
||||
|
||||
@router.delete(path="/delete/{qt_id}", response_model=Res_DeleteQuotation, summary="견적 삭제")
|
||||
async def delete_quotation(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
return RemoveNoneResponse(await service.delete_quotation(str(qt_id), user_info.company_id))
|
||||
return RemoveNoneResponse(await service.delete_quotation(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
|
||||
|
||||
|
||||
@router.get(path="/supplier/{supplier_id}/last-type", response_model=Res_LastSupplierType, summary="협력사 직전 견적 유형")
|
||||
|
||||
@@ -35,6 +35,7 @@ class SupplierData(WebPacketProtocol):
|
||||
supplier_id: uuid.UUID
|
||||
company_id: uuid.UUID
|
||||
user_id: uuid.UUID
|
||||
creator_name: Optional[str] = None # 등록자(작성자) 이름. user_id→company.users.name 조인
|
||||
name: str
|
||||
code: Optional[str] = None
|
||||
manager_name: Optional[str] = None
|
||||
|
||||
@@ -3,7 +3,7 @@ from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.models.gmodel import PageParams, UserInfo
|
||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
|
||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, RequireOwner
|
||||
from services.supplier_service import SupplierService
|
||||
from .protocol import (
|
||||
Req_CheckCodes,
|
||||
@@ -59,6 +59,7 @@ async def update_supplier(
|
||||
)
|
||||
|
||||
|
||||
@router.delete(path="/delete/{supplier_id}", response_model=Res_DeleteSupplier, summary="협력사 삭제")
|
||||
async def delete_supplier(supplier_id: UUID, service: SupplierService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
@router.delete(path="/delete/{supplier_id}", response_model=Res_DeleteSupplier, summary="협력사 삭제 (최고관리자 전용)")
|
||||
async def delete_supplier(supplier_id: UUID, service: SupplierService = Depends(), user_info: UserInfo = Depends(RequireOwner)):
|
||||
# 협력사 명부는 회사 공유 자원 — 파괴적 삭제는 최고관리자만(RequireOwner 가 비-OWNER 를 403 차단).
|
||||
return RemoveNoneResponse(await service.delete_supplier(user_info.company_id, str(supplier_id)))
|
||||
@@ -25,6 +25,7 @@ class CardService:
|
||||
nego_card_id=row.nego_card_id,
|
||||
user_id=row.user_id,
|
||||
is_wildcard=False,
|
||||
is_shared=row.user_id is None,
|
||||
name=row.name,
|
||||
number=row.number,
|
||||
script=row.script,
|
||||
@@ -42,6 +43,7 @@ class CardService:
|
||||
nego_card_id=row.wild_card_id,
|
||||
user_id=row.user_id,
|
||||
is_wildcard=True,
|
||||
is_shared=row.user_id is None,
|
||||
name=row.name,
|
||||
number=row.number,
|
||||
script=row.script,
|
||||
@@ -56,7 +58,8 @@ class CardService:
|
||||
|
||||
# ---- 소유 카드 탐색(어느 테이블인지 모를 때) ------------------------------
|
||||
async def _find_owned(self, user_uuid: uuid.UUID, card_id: uuid.UUID):
|
||||
"""card_id 를 nego_cards → wild_cards 순으로 찾고 소유권 확인.
|
||||
"""card_id 를 nego_cards → wild_cards 순으로 찾고 접근권 확인.
|
||||
전체(공용, user_id NULL) 카드는 누구나 조회·수정·삭제 가능. 개인 카드는 소유자만.
|
||||
(ErrorType, model, pk_col, row, is_wildcard) 반환."""
|
||||
err, row = await DB_SESSION_MNG.execute_lambda(
|
||||
nego_cards.DBType(),
|
||||
@@ -64,7 +67,7 @@ class CardService:
|
||||
lambda s: self.card_crud.get_by_id(s, nego_cards, nego_cards.nego_card_id, card_id),
|
||||
)
|
||||
if err == ErrorType.SUCCESS and row is not None:
|
||||
if row.user_id != user_uuid:
|
||||
if row.user_id is not None and row.user_id != user_uuid:
|
||||
return ErrorType.CARD_NOT_FOUND, None, None, None, False
|
||||
return ErrorType.SUCCESS, nego_cards, nego_cards.nego_card_id, row, False
|
||||
|
||||
@@ -74,7 +77,7 @@ class CardService:
|
||||
lambda s: self.card_crud.get_by_id(s, wild_cards, wild_cards.wild_card_id, card_id),
|
||||
)
|
||||
if err == ErrorType.SUCCESS and row is not None:
|
||||
if row.user_id != user_uuid:
|
||||
if row.user_id is not None and row.user_id != user_uuid:
|
||||
return ErrorType.CARD_NOT_FOUND, None, None, None, True
|
||||
return ErrorType.SUCCESS, wild_cards, wild_cards.wild_card_id, row, True
|
||||
|
||||
@@ -114,7 +117,21 @@ class CardService:
|
||||
|
||||
merged = [self._nego_to_data(r) for r in nego_rows] + [self._wild_to_data(r) for r in wild_rows]
|
||||
merged.sort(key=lambda c: c.created_at or "", reverse=True)
|
||||
res.cards = merged[pg.skip : pg.skip + pg.size]
|
||||
page = merged[pg.skip : pg.skip + pg.size]
|
||||
|
||||
# 작성자명 배치 조인 — 페이지 카드의 작성자 id를 모아 IN 쿼리 1회로 {id:name} 맵을 만들어 매핑.
|
||||
# (공용 카드는 user_id=NULL → 맵에 없어 creator_name=None). 행마다 조회하지 않으므로 부하 없음.
|
||||
author_ids = list({c.user_id for c in page if c.user_id is not None})
|
||||
if author_ids:
|
||||
nm_err, name_map = await DB_SESSION_MNG.execute_lambda(
|
||||
nego_cards.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.card_crud.user_name_map(s, author_ids),
|
||||
)
|
||||
if nm_err == ErrorType.SUCCESS:
|
||||
for c in page:
|
||||
c.creator_name = name_map.get(c.user_id)
|
||||
res.cards = page
|
||||
res.total_nego = total_n
|
||||
res.total_wild = total_w
|
||||
# 선택된 탭 기준 페이지네이션 총건수(전체=합산).
|
||||
@@ -134,6 +151,14 @@ class CardService:
|
||||
res.result.SetResult(err)
|
||||
return res
|
||||
res.card = self._wild_to_data(row) if is_wild else self._nego_to_data(row)
|
||||
# 등록자명 — 공용(user_id NULL) 카드는 작성자 없음(None 유지).
|
||||
if row.user_id is not None:
|
||||
nm_err, name_map = await DB_SESSION_MNG.execute_lambda(
|
||||
nego_cards.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.card_crud.user_name_map(s, [row.user_id]),
|
||||
)
|
||||
if nm_err == ErrorType.SUCCESS:
|
||||
res.card.creator_name = name_map.get(row.user_id)
|
||||
return res
|
||||
|
||||
# ---- 등록 ----------------------------------------------------------------
|
||||
@@ -141,9 +166,11 @@ class CardService:
|
||||
res = Res_Card()
|
||||
user_uuid = uuid.UUID(user_id)
|
||||
is_wildcard = req.is_wildcard
|
||||
# 전체(공용) 카드는 소유자 없이 저장(user_id NULL) → 모든 유저 목록에 노출.
|
||||
owner_id = None if req.is_shared else user_uuid
|
||||
|
||||
common = dict(
|
||||
user_id=user_uuid,
|
||||
user_id=owner_id,
|
||||
name=req.name,
|
||||
number=req.number,
|
||||
script=req.script,
|
||||
|
||||
@@ -2,6 +2,7 @@ import uuid
|
||||
|
||||
from fastapi import Depends, UploadFile
|
||||
|
||||
from common.authz import is_owner_or_admin
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import items
|
||||
from common.enums import DBWRType, ErrorType
|
||||
@@ -56,6 +57,16 @@ class ItemService:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.items = [ItemData.model_validate(r) for r in rows]
|
||||
# 등록자명 배치 조인 — 페이지 상품의 user_id를 모아 IN 쿼리 1회로 {id:name} 맵을 만들어 매핑(행별 조회 아님).
|
||||
author_ids = list({r.user_id for r in rows if r.user_id is not None})
|
||||
if author_ids:
|
||||
nm_err, name_map = await DB_SESSION_MNG.execute_lambda(
|
||||
items.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.item_crud.user_name_map(s, author_ids),
|
||||
)
|
||||
if nm_err == ErrorType.SUCCESS:
|
||||
for d in res.items:
|
||||
d.creator_name = name_map.get(d.user_id)
|
||||
res.total = total
|
||||
return res
|
||||
|
||||
@@ -81,6 +92,13 @@ class ItemService:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.item = ItemData.model_validate(item)
|
||||
if item.user_id is not None:
|
||||
nm_err, name_map = await DB_SESSION_MNG.execute_lambda(
|
||||
items.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.item_crud.user_name_map(s, [item.user_id]),
|
||||
)
|
||||
if nm_err == ErrorType.SUCCESS:
|
||||
res.item.creator_name = name_map.get(item.user_id)
|
||||
return res
|
||||
|
||||
async def check_codes(self, company_id: str, codes: list) -> Res_CheckCodes:
|
||||
@@ -128,17 +146,22 @@ class ItemService:
|
||||
# 서버 기본값(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, req: Req_UpdateItem) -> Res_Item:
|
||||
async def update_item(self, company_id: str, item_id: str, req: Req_UpdateItem, user_id=None, role=None) -> Res_Item:
|
||||
res = Res_Item()
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
item_uuid = uuid.UUID(item_id)
|
||||
data = req.model_dump(exclude_unset=True)
|
||||
|
||||
# 소유권 확인
|
||||
err_type, _ = await self._fetch_owned(company_uuid, item_uuid)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
# 회사 스코프 확인
|
||||
err_type, item = await self._fetch_owned(company_uuid, item_uuid)
|
||||
if err_type != ErrorType.SUCCESS or item is None:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 소유자 게이팅 — 본인이 등록한 상품 또는 최고관리자만 수정(user_id 미지정=내부 호출은 스킵).
|
||||
if user_id is not None and not is_owner_or_admin(item.user_id, user_id, role):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||
res.msg = "본인이 등록한 상품만 수정할 수 있습니다."
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[items.DBType()],
|
||||
@@ -151,15 +174,20 @@ class ItemService:
|
||||
# 갱신 후 재조회
|
||||
return await self.get_item(company_id, item_id)
|
||||
|
||||
async def delete_item(self, company_id: str, item_id: str) -> Res_DeleteItem:
|
||||
async def delete_item(self, company_id: str, item_id: str, user_id=None, role=None) -> 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:
|
||||
err_type, item = await self._fetch_owned(company_uuid, item_uuid)
|
||||
if err_type != ErrorType.SUCCESS or item is None:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 소유자 게이팅 — 본인이 등록한 상품 또는 최고관리자만 삭제(user_id 미지정=내부 호출은 스킵).
|
||||
if user_id is not None and not is_owner_or_admin(item.user_id, user_id, role):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||
res.msg = "본인이 등록한 상품만 삭제할 수 있습니다."
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[items.DBType()],
|
||||
|
||||
@@ -12,6 +12,7 @@ from common.anchoring import (
|
||||
fetch_current_values,
|
||||
get_base_anchoring_value,
|
||||
)
|
||||
from common.authz import is_owner_or_admin
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import quotations, sessions, chats, versions, version_nego_cards, version_wild_cards
|
||||
from common.enums import CloseOutcome, CloseReason, DBWRType, ErrorType, NotificationType, PriceGateAction, QuotationStatus, QuotationType, SessionStatus
|
||||
@@ -678,7 +679,7 @@ class QuotationService:
|
||||
# 4) 전원 미응찰 → 개찰(미응찰).
|
||||
return await self._open(qt_uuid, original, CloseReason.OPEN_NOSHOW.value, "no_show")
|
||||
|
||||
async def regenerate_quotation(self, qt_id: str, company_id, supplier_ids: list) -> Res_CreateQuotation:
|
||||
async def regenerate_quotation(self, qt_id: str, company_id, supplier_ids: list, user_id=None, role=None) -> Res_CreateQuotation:
|
||||
"""[프론트] 마감된 견적을 골라 수동으로 다음 라운드를 생성한다.
|
||||
크론/수동마감의 자동 재생성과 달리 사유·체인 한도 판정 없이, 프론트가 고른 공급사로 바로 만든다.
|
||||
상품·기간·견적번호·카드버전은 원 견적에서 이어받는다(regenerate_next_round)."""
|
||||
@@ -689,6 +690,11 @@ class QuotationService:
|
||||
if err_type != ErrorType.SUCCESS or original is None:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 소유자 게이팅 — 본인 견적 또는 최고관리자만 재생성(user_id 미지정=내부 호출은 스킵).
|
||||
if user_id is not None and not is_owner_or_admin(original.user_id, user_id, role):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||
res.msg = "본인이 생성한 견적만 재생성할 수 있습니다."
|
||||
return res
|
||||
# 마감된 견적만 재생성(진행 중인 라운드를 또 찍어 같은 번호가 동시에 살아있는 걸 막는다).
|
||||
if original.status != QuotationStatus.CLOSED.value:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
@@ -711,29 +717,106 @@ class QuotationService:
|
||||
|
||||
return await self.regenerate_next_round(qt_uuid, supplier_ids)
|
||||
|
||||
async def stop_quotation(self, qt_id: str, company_id=None) -> Res_Quotation:
|
||||
async def stop_quotation(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_Quotation:
|
||||
"""[프론트] 수동 견적마감. 크론과 똑같은 마감 판정(close_and_decide)을 탄다
|
||||
(단독낙찰 확정 / 동가·미참여면 다음 라운드 재생성 / 거부·한도면 그냥 마감)."""
|
||||
res = Res_Quotation()
|
||||
qt_uuid = uuid.UUID(qt_id)
|
||||
|
||||
# 존재 확인(+회사 가드)
|
||||
err_type, _ = await self._fetch(qt_uuid, company_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
err_type, original = await self._fetch(qt_uuid, company_id)
|
||||
if err_type != ErrorType.SUCCESS or original is None:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 소유자 게이팅 — 본인 견적 또는 최고관리자만 마감(user_id 미지정=내부 호출은 스킵).
|
||||
if user_id is not None and not is_owner_or_admin(original.user_id, user_id, role):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||
res.msg = "본인이 생성한 견적만 마감할 수 있습니다."
|
||||
return res
|
||||
|
||||
await self.close_and_decide(qt_uuid)
|
||||
return await self.get_quotation(qt_id, company_id)
|
||||
|
||||
async def delete_quotation(self, qt_id: str, company_id=None) -> Res_DeleteQuotation:
|
||||
async def award_quotation(self, qt_id: str, company_id, user_id, role, winner_supplier_id) -> Res_Quotation:
|
||||
"""[프론트] 개찰(낙찰자 미정 마감) 견적을 담당자가 직접 낙찰 처리한다.
|
||||
투찰한 협상완료(DONE) 세션 중 고른 협력사를 낙찰자로 박고 close_reason 을 AWARDED 로 바꾼다(직접 낙찰).
|
||||
자동 낙찰(close_and_decide)과 결과 컬럼은 같되, 알림에 manual 플래그로 '직접 낙찰'임을 남긴다.
|
||||
권한: 본인이 생성한 견적만. 단 최고관리자(OWNER)는 회사 내 남의 견적도 낙찰할 수 있다."""
|
||||
res = Res_Quotation()
|
||||
qt_uuid = uuid.UUID(qt_id)
|
||||
sp_uuid = winner_supplier_id if isinstance(winner_supplier_id, uuid.UUID) else uuid.UUID(str(winner_supplier_id))
|
||||
|
||||
# 존재 확인(+회사 가드) — 남의 회사 견적은 NOT_FOUND.
|
||||
err_type, original = await self._fetch(qt_uuid, company_id)
|
||||
if err_type != ErrorType.SUCCESS or original is None:
|
||||
res.result.SetResult(err_type if err_type != ErrorType.SUCCESS else ErrorType.QUOTATION_NOT_FOUND)
|
||||
return res
|
||||
|
||||
# 자기 견적만 직접 낙찰 — 최고관리자(OWNER)만 회사 내 남의 견적도 허용. 되돌릴 수 없는 낙찰이라 백엔드에서 강제한다.
|
||||
if not is_owner_or_admin(original.user_id, user_id, role):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||
res.msg = "본인이 생성한 견적만 낙찰할 수 있습니다."
|
||||
return res
|
||||
|
||||
# 개찰(마감·낙찰자 미정, close_reason ∈ OPEN_*)만 직접 낙찰 대상. 진행중/이미 낙찰은 거부.
|
||||
if original.status != QuotationStatus.CLOSED.value or original.close_reason not in (
|
||||
CloseReason.OPEN_PRICE.value, CloseReason.OPEN_EQUAL.value,
|
||||
CloseReason.OPEN_NOSHOW.value, CloseReason.OPEN_REJECT.value,
|
||||
):
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
res.msg = "개찰(낙찰자 미정) 상태의 견적만 직접 낙찰할 수 있습니다."
|
||||
return res
|
||||
|
||||
# 낙찰 후보 = 투찰한 협상완료(DONE) 세션. close_and_decide 와 같은 조회(list_sessions_status,
|
||||
# 공급사 삭제돼도 포함되는 outerjoin)를 써서 자동낙찰과 후보 집합을 일치시킨다.
|
||||
err_type, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.list_sessions_status(s, qt_uuid),
|
||||
)
|
||||
rows = rows if err_type == ErrorType.SUCCESS else []
|
||||
winner = next(
|
||||
(r for r in rows
|
||||
if r.status == SessionStatus.DONE.value and r.bid_price is not None and r.supplier_id == sp_uuid),
|
||||
None,
|
||||
)
|
||||
if winner is None:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
res.msg = "선택한 협력사는 이 견적의 낙찰 후보(투찰한 협상완료 협력사)가 아닙니다."
|
||||
return res
|
||||
|
||||
# [동시 직접낙찰 가드] 개찰→낙찰 원자 선점. 실제로 전이한 호출자만 통과(재클릭·경합 방어).
|
||||
claim_err, claimed = await DB_SESSION_MNG.execute_lambda_claim(
|
||||
quotations.DBType(),
|
||||
lambda s: self.quotation_crud.claim_for_award(s, qt_uuid, sp_uuid, (winner.name or "")[:20]),
|
||||
)
|
||||
if claim_err != ErrorType.SUCCESS or claimed == 0:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
res.msg = "이미 낙찰 처리된 견적입니다."
|
||||
return res
|
||||
|
||||
# 작성자 알림 — 자동낙찰과 같은 SUCCESS 코드, manual 플래그로 '직접 낙찰' 구분.
|
||||
await create_notification(
|
||||
original.user_id, NotificationType.SUCCESS,
|
||||
{"qt_name": original.name, "qt_number": original.number,
|
||||
"winner_name": winner.name, "winner_price": winner.bid_price, "manual": True},
|
||||
ref_qt_id=qt_uuid,
|
||||
)
|
||||
return await self.get_quotation(qt_id, company_id)
|
||||
|
||||
async def delete_quotation(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_DeleteQuotation:
|
||||
res = Res_DeleteQuotation()
|
||||
qt_uuid = uuid.UUID(qt_id)
|
||||
|
||||
err_type, _ = await self._fetch(qt_uuid, company_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
err_type, original = await self._fetch(qt_uuid, company_id)
|
||||
if err_type != ErrorType.SUCCESS or original is None:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 소유자 게이팅 — 본인 견적 또는 최고관리자만 삭제(user_id 미지정=내부 호출은 스킵).
|
||||
if user_id is not None and not is_owner_or_admin(original.user_id, user_id, role):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||
res.msg = "본인이 생성한 견적만 삭제할 수 있습니다."
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotations.DBType()],
|
||||
@@ -815,15 +898,20 @@ class QuotationService:
|
||||
return res
|
||||
|
||||
# ----- 협상 초청 메일 (수동 발송)
|
||||
async def notify_sessions(self, qt_id: str, company_id=None) -> Res_NotifySessions:
|
||||
async def notify_sessions(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_NotifySessions:
|
||||
"""[수동 발송] 견적의 '미발송' 세션(공급사 담당자)에게 협상 초청 메일을 일괄 발송한다.
|
||||
대상 = email_sent_at IS NULL + 담당자 이메일 보유."""
|
||||
res = Res_NotifySessions()
|
||||
qt_uuid = uuid.UUID(qt_id)
|
||||
err_type, quotation = await self._fetch(qt_uuid, company_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
if err_type != ErrorType.SUCCESS or quotation is None:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 소유자 게이팅 — 본인 견적 또는 최고관리자만 초청메일 발송(user_id 미지정=내부 호출은 스킵).
|
||||
if user_id is not None and not is_owner_or_admin(quotation.user_id, user_id, role):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||
res.msg = "본인이 생성한 견적만 초청 메일을 발송할 수 있습니다."
|
||||
return res
|
||||
|
||||
err_type, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(),
|
||||
@@ -851,7 +939,7 @@ class QuotationService:
|
||||
await self._mark_emailed(sent_ids)
|
||||
return res
|
||||
|
||||
async def notify_session(self, session_id: str, company_id=None) -> Res_NotifySessions:
|
||||
async def notify_session(self, session_id: str, company_id=None, user_id=None, role=None) -> Res_NotifySessions:
|
||||
"""[수동 재발송] 단일 세션(공급사)에 초청 메일 발송(이미 보냈어도 강제 재발송)."""
|
||||
res = Res_NotifySessions()
|
||||
sess_uuid = uuid.UUID(session_id)
|
||||
@@ -866,9 +954,14 @@ class QuotationService:
|
||||
sess, sp_name, email = got[0], got[1], got[2]
|
||||
res.total = 1
|
||||
err_type, quotation = await self._fetch(sess.quotation_id, company_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
if err_type != ErrorType.SUCCESS or quotation is None:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 소유자 게이팅 — 본인 견적 또는 최고관리자만 재발송(user_id 미지정=내부 호출은 스킵).
|
||||
if user_id is not None and not is_owner_or_admin(quotation.user_id, user_id, role):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||
res.msg = "본인이 생성한 견적만 초청 메일을 발송할 수 있습니다."
|
||||
return res
|
||||
if not email:
|
||||
res.skipped = 1
|
||||
return res
|
||||
|
||||
@@ -51,6 +51,16 @@ class SupplierService:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.suppliers = [SupplierData.model_validate(r) for r in rows]
|
||||
# 등록자명 배치 조인 — 페이지 협력사의 user_id를 모아 IN 쿼리 1회로 {id:name} 맵을 만들어 매핑(행별 조회 아님).
|
||||
author_ids = list({r.user_id for r in rows if r.user_id is not None})
|
||||
if author_ids:
|
||||
nm_err, name_map = await DB_SESSION_MNG.execute_lambda(
|
||||
suppliers.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.supplier_crud.user_name_map(s, author_ids),
|
||||
)
|
||||
if nm_err == ErrorType.SUCCESS:
|
||||
for d in res.suppliers:
|
||||
d.creator_name = name_map.get(d.user_id)
|
||||
res.total = total
|
||||
return res
|
||||
|
||||
@@ -61,6 +71,13 @@ class SupplierService:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.supplier = SupplierData.model_validate(supplier)
|
||||
if supplier.user_id is not None:
|
||||
nm_err, name_map = await DB_SESSION_MNG.execute_lambda(
|
||||
suppliers.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.supplier_crud.user_name_map(s, [supplier.user_id]),
|
||||
)
|
||||
if nm_err == ErrorType.SUCCESS:
|
||||
res.supplier.creator_name = name_map.get(supplier.user_id)
|
||||
return res
|
||||
|
||||
async def check_codes(self, company_id: str, codes: list) -> Res_CheckCodes:
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""card 도메인 스코프 e2e — 개인 카드는 소유자만, 전체(공용) 카드는 누구나.
|
||||
스코프 규칙: user_id 있으면 개인(본인만 조회·관리) / NULL 이면 전체(모든 유저 조회·수정·삭제). 로그인은 auth_headers."""
|
||||
|
||||
|
||||
async def _create_card(client, headers, *, number, name="카드", is_shared=False, is_wildcard=False):
|
||||
r = await client.post(
|
||||
"/v1/card/create",
|
||||
json={
|
||||
"is_wildcard": is_wildcard,
|
||||
"is_shared": is_shared,
|
||||
"name": name,
|
||||
"number": number,
|
||||
"script": "안녕하세요",
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
body = r.json()
|
||||
assert body["result"]["success"] is True, body
|
||||
return body["card"]["nego_card_id"]
|
||||
|
||||
|
||||
async def _list_numbers(client, headers):
|
||||
r = await client.get("/v1/card/list", headers=headers)
|
||||
return {c["number"] for c in r.json().get("cards", [])}
|
||||
|
||||
|
||||
async def test_personal_card_is_owner_only(client, auth_headers):
|
||||
"""검증: user_id 가 박힌 개인 카드는 소유자 목록·단건조회에만 노출되고 타 유저에겐 숨는다.
|
||||
기대결과: A 목록엔 있고 B 목록엔 없음, B 의 단건 조회는 success=False(CARD_NOT_FOUND)."""
|
||||
ha = await auth_headers("cardA")
|
||||
hb = await auth_headers("cardB")
|
||||
cid = await _create_card(client, ha, number="P-1", is_shared=False)
|
||||
|
||||
assert "P-1" in await _list_numbers(client, ha)
|
||||
assert "P-1" not in await _list_numbers(client, hb)
|
||||
assert (await client.get(f"/v1/card/{cid}", headers=hb)).json()["result"]["success"] is False
|
||||
|
||||
|
||||
async def test_shared_card_visible_to_all(client, auth_headers):
|
||||
"""검증: is_shared=True 카드는 user_id NULL 로 저장돼 모든 유저 목록·단건조회에 노출된다.
|
||||
기대결과: A·B 목록 모두에 존재, 비생성자 B 의 단건 조회 success=True, is_shared 플래그 True."""
|
||||
ha = await auth_headers("cardSA")
|
||||
hb = await auth_headers("cardSB")
|
||||
cid = await _create_card(client, ha, number="S-1", is_shared=True)
|
||||
|
||||
assert "S-1" in await _list_numbers(client, ha)
|
||||
assert "S-1" in await _list_numbers(client, hb)
|
||||
got = await client.get(f"/v1/card/{cid}", headers=hb)
|
||||
assert got.json()["result"]["success"] is True
|
||||
assert got.json()["card"]["is_shared"] is True
|
||||
|
||||
|
||||
async def test_shared_card_editable_and_deletable_by_anyone(client, auth_headers):
|
||||
"""검증: 전체(공용) 카드는 소유자가 없어 아무 유저나 수정·삭제 가능(정책: 누구나).
|
||||
기대결과: 비생성자 B 의 수정·삭제 모두 success=True, 삭제 후 목록에서 사라짐."""
|
||||
ha = await auth_headers("cardEA")
|
||||
hb = await auth_headers("cardEB")
|
||||
cid = await _create_card(client, ha, number="S-EDIT", is_shared=True)
|
||||
|
||||
upd = await client.patch(f"/v1/card/update/{cid}", json={"name": "B가 수정"}, headers=hb)
|
||||
assert upd.json()["result"]["success"] is True
|
||||
|
||||
dele = await client.delete(f"/v1/card/delete/{cid}", headers=hb)
|
||||
assert dele.json()["result"]["success"] is True
|
||||
assert "S-EDIT" not in await _list_numbers(client, hb)
|
||||
@@ -0,0 +1,122 @@
|
||||
"""소유자 게이팅 — 변경 액션은 '본인 소유' 또는 '최고관리자(OWNER)'만. 프론트 버튼 차단과 같은 규칙을 백엔드가 강제한다.
|
||||
|
||||
- item(상품): 같은 회사의 다른 일반유저는 남의 상품을 수정·삭제 못 한다(OWNER는 가능).
|
||||
- quotation(견적): 남의 견적 삭제는 비소유 일반유저 차단, OWNER 허용, user_id 미지정(내부 호출)은 스킵.
|
||||
공용 판정은 common.authz.is_owner_or_admin — 여기 통과하면 다른 변경 액션(마감·재생성·초청메일)도 같은 규칙을 탄다.
|
||||
"""
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.enums import ErrorType, QuotationStatus, QuotationType, UserRole
|
||||
from crud.quotation_crud import QuotationCRUD
|
||||
from services.quotation_service import QuotationService
|
||||
|
||||
PAST = datetime(2020, 1, 1)
|
||||
|
||||
|
||||
# ===== item(상품) — HTTP e2e: 같은 회사, 다른 유저 =====
|
||||
async def test_item_update_delete_blocked_for_non_owner(client, auth_headers):
|
||||
"""검증: A가 등록한 상품을 같은 회사의 다른 일반유저 B가 수정·삭제 시도.
|
||||
기대결과: 둘 다 거부(ACCOUNT_FORBIDDEN), 상품은 원값 그대로 남는다."""
|
||||
ha = await auth_headers("item_owner") # 소유자
|
||||
hb = await auth_headers("item_other") # 같은 회사, USER
|
||||
item_id = (await client.post(
|
||||
"/v1/item/create", json={"name": "상품A", "price": 1000, "code": "OWN1"}, headers=ha
|
||||
)).json()["item"]["item_id"]
|
||||
|
||||
r_upd = await client.patch(f"/v1/item/update/{item_id}", json={"price": 9999}, headers=hb)
|
||||
assert r_upd.json()["result"]["success"] is False
|
||||
assert r_upd.json()["result"]["code"] == ErrorType.ACCOUNT_FORBIDDEN.value
|
||||
|
||||
r_del = await client.delete(f"/v1/item/delete/{item_id}", headers=hb)
|
||||
assert r_del.json()["result"]["success"] is False
|
||||
assert r_del.json()["result"]["code"] == ErrorType.ACCOUNT_FORBIDDEN.value
|
||||
|
||||
# 수정·삭제 모두 무산 — 원값으로 조회된다
|
||||
assert (await client.get(f"/v1/item/{item_id}", headers=ha)).json()["item"]["price"] == 1000
|
||||
|
||||
|
||||
async def test_item_delete_allowed_for_owner_role(client, auth_headers):
|
||||
"""검증: A가 등록한 상품을 같은 회사 최고관리자(OWNER)가 삭제.
|
||||
기대결과: 성공 — 소유자가 아니어도 OWNER는 허용."""
|
||||
ha = await auth_headers("item_owner2")
|
||||
hadmin = await auth_headers("item_admin", role=UserRole.OWNER.value)
|
||||
item_id = (await client.post(
|
||||
"/v1/item/create", json={"name": "상품B", "price": 500, "code": "OWN2"}, headers=ha
|
||||
)).json()["item"]["item_id"]
|
||||
|
||||
r = await client.delete(f"/v1/item/delete/{item_id}", headers=hadmin)
|
||||
assert r.json()["result"]["success"] is True
|
||||
|
||||
|
||||
# ===== quotation(견적) — 서비스 직접: 삭제 게이팅 =====
|
||||
async def test_quotation_delete_blocked_for_non_owner(db_engine):
|
||||
"""검증: 남의 견적을 비소유 일반유저(USER)가 삭제 시도.
|
||||
기대결과: 거부(ACCOUNT_FORBIDDEN) + soft-delete 안 됨(deleted=false)."""
|
||||
owner, other = uuid.uuid4(), uuid.uuid4()
|
||||
qt = await _seed_quotation(db_engine, user_id=owner, number="DEL-NONOWNER")
|
||||
|
||||
res = await _service().delete_quotation(str(qt), None, other, UserRole.USER.value)
|
||||
|
||||
assert res.result.success is False
|
||||
assert res.result.code == ErrorType.ACCOUNT_FORBIDDEN.value
|
||||
assert await _deleted(db_engine, qt) is False
|
||||
|
||||
|
||||
async def test_quotation_delete_allowed_for_owner_role(db_engine):
|
||||
"""검증: 남의 견적을 최고관리자(OWNER)가 삭제.
|
||||
기대결과: 성공 + deleted=true."""
|
||||
creator, admin = uuid.uuid4(), uuid.uuid4()
|
||||
qt = await _seed_quotation(db_engine, user_id=creator, number="DEL-OWNER")
|
||||
|
||||
res = await _service().delete_quotation(str(qt), None, admin, UserRole.OWNER.value)
|
||||
|
||||
assert res.result.success is True
|
||||
assert await _deleted(db_engine, qt) is True
|
||||
|
||||
|
||||
async def test_quotation_delete_skips_gate_for_internal_call(db_engine):
|
||||
"""검증: user_id 미지정(내부/스케줄러 호출)로 삭제.
|
||||
기대결과: 소유권 검사 스킵 → 성공(회사 스코프만 적용)."""
|
||||
creator = uuid.uuid4()
|
||||
qt = await _seed_quotation(db_engine, user_id=creator, number="DEL-INTERNAL")
|
||||
|
||||
res = await _service().delete_quotation(str(qt), None)
|
||||
|
||||
assert res.result.success is True
|
||||
assert await _deleted(db_engine, qt) is True
|
||||
|
||||
|
||||
# ===== 헬퍼 =====
|
||||
async def _seed_quotation(engine, *, user_id, number):
|
||||
"""견적 1건 시드(삭제 게이팅 확인용 — 상태는 무관하므로 CLOSED로 고정)."""
|
||||
qt_id = uuid.uuid4()
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO quotations "
|
||||
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, "
|
||||
" round, iteration, start_time, end_time, deleted) VALUES "
|
||||
"(:qt_id, :user_id, :qt_setting_id, :version_id, '견적', :number, :type, :status, "
|
||||
" 1, 0, :t, :t, false)"
|
||||
),
|
||||
{
|
||||
"qt_id": qt_id, "user_id": user_id, "qt_setting_id": uuid.uuid4(),
|
||||
"version_id": uuid.uuid4(), "number": number, "type": QuotationType.REQUOTE.value,
|
||||
"status": QuotationStatus.CLOSED.value, "t": PAST,
|
||||
},
|
||||
)
|
||||
return qt_id
|
||||
|
||||
|
||||
async def _deleted(engine, qt_id) -> bool:
|
||||
async with engine.begin() as conn:
|
||||
return (await conn.execute(
|
||||
text("SELECT deleted FROM quotations WHERE qt_id = :q"), {"q": qt_id}
|
||||
)).scalar_one()
|
||||
|
||||
|
||||
def _service():
|
||||
return QuotationService(QuotationCRUD())
|
||||
@@ -0,0 +1,206 @@
|
||||
"""개찰 견적 직접 낙찰(award_quotation) 테스트 — 담당자가 개찰(낙찰자 미정 마감) 견적의 낙찰자를 직접 지정.
|
||||
|
||||
직접 낙찰은 자동 낙찰(close_and_decide)과 결과 컬럼은 같되(close_reason=AWARDED, preferred_sp_*),
|
||||
알림에 manual 플래그로 '직접' 낙찰임을 남긴다. 다음을 본다:
|
||||
· 개찰 + 투찰(DONE) 협력사 지정 → 낙찰 확정 + 알림 SUCCESS(manual=True)
|
||||
· 개찰 아님(이미 낙찰) → 거부(INVALID_REQUEST_DATA), 알림 없음
|
||||
· 후보 아닌 협력사 지정 → 거부, close_reason 유지
|
||||
· 낙찰 후 재지정(재클릭) → 거부(동시성 가드), 알림 1건 유지
|
||||
|
||||
세션의 협상 결과(협상완료/입찰가)와 개찰 상태(close_reason)는 협상/마감에서만 생기는 값이라 SQL 로 직접 넣는다.
|
||||
"""
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.enums import CloseReason, ErrorType, QuotationStatus, QuotationType, SessionStatus, UserRole
|
||||
from crud.quotation_crud import QuotationCRUD
|
||||
from services.quotation_service import QuotationService
|
||||
|
||||
PAST = datetime(2020, 1, 1)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def clean(db_engine):
|
||||
"""conftest 는 notifications 를 비우지 않는다 → 알림 단언이 다른 테스트에 안 흔들리게 여기서 함께 비운다."""
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(text("TRUNCATE TABLE sessions, quotations, notifications RESTART IDENTITY CASCADE"))
|
||||
return db_engine
|
||||
|
||||
|
||||
async def test_award_opened_sets_winner_and_notifies(clean):
|
||||
"""검증: 개찰(동가) 견적 + 투찰 협력사 2건(A=100, B=120) 중 A 를 직접 낙찰.
|
||||
기대결과: close_reason→낙찰, preferred_sp=A, 동가플래그 해제 + 알림 SUCCESS(manual=True, winner_price=100)."""
|
||||
engine = clean
|
||||
user_id, supplier_a = uuid.uuid4(), uuid.uuid4()
|
||||
qt = await _seed_opened(engine, user_id=user_id, number="A-WIN", close_reason=CloseReason.OPEN_EQUAL.value)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, supplier_id=supplier_a)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=120)
|
||||
|
||||
res = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a)
|
||||
|
||||
assert res.result.success is True
|
||||
row = await _quotation(engine, qt)
|
||||
assert row.close_reason == CloseReason.AWARDED.value
|
||||
assert row.preferred_sp_yn is True
|
||||
assert str(row.preferred_sp_id) == str(supplier_a)
|
||||
assert row.equal_bid_yn is False
|
||||
|
||||
notis = await _notifications(engine, user_id)
|
||||
assert len(notis) == 1
|
||||
type_, data, ref = notis[0]
|
||||
assert type_ == 1 # NotificationType.SUCCESS
|
||||
assert data["manual"] is True
|
||||
assert data["winner_price"] == 100
|
||||
assert str(ref) == str(qt)
|
||||
|
||||
|
||||
async def test_award_rejects_when_not_opened(clean):
|
||||
"""검증: 이미 낙찰된 견적(close_reason=AWARDED)에 직접 낙찰을 다시 시도.
|
||||
기대결과: 거부(INVALID_REQUEST_DATA) + 새 알림 없음."""
|
||||
engine = clean
|
||||
user_id, supplier_a = uuid.uuid4(), uuid.uuid4()
|
||||
qt = await _seed_opened(engine, user_id=user_id, number="A-DONE", close_reason=CloseReason.AWARDED.value)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, supplier_id=supplier_a)
|
||||
|
||||
res = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a)
|
||||
|
||||
assert res.result.success is False
|
||||
assert res.result.code == ErrorType.INVALID_REQUEST_DATA.value
|
||||
assert len(await _notifications(engine, user_id)) == 0
|
||||
|
||||
|
||||
async def test_award_rejects_unknown_supplier(clean):
|
||||
"""검증: 개찰 견적에, 투찰 후보가 아닌 협력사 id 를 지정.
|
||||
기대결과: 거부 + close_reason 은 개찰(OPEN_PRICE) 그대로 유지, 알림 없음."""
|
||||
engine = clean
|
||||
user_id, bidder, stranger = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
|
||||
qt = await _seed_opened(engine, user_id=user_id, number="A-STRANGER", close_reason=CloseReason.OPEN_PRICE.value)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, supplier_id=bidder)
|
||||
|
||||
res = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, stranger)
|
||||
|
||||
assert res.result.success is False
|
||||
row = await _quotation(engine, qt)
|
||||
assert row.close_reason == CloseReason.OPEN_PRICE.value
|
||||
assert row.preferred_sp_id is None
|
||||
assert len(await _notifications(engine, user_id)) == 0
|
||||
|
||||
|
||||
async def test_award_is_idempotent(clean):
|
||||
"""검증: 직접 낙찰 성공 후 같은 견적에 재지정(재클릭/경합).
|
||||
기대결과: 2번째는 거부(이미 낙찰) + 알림은 1건만 유지(동시성 가드가 한 번만 통과)."""
|
||||
engine = clean
|
||||
user_id, supplier_a = uuid.uuid4(), uuid.uuid4()
|
||||
qt = await _seed_opened(engine, user_id=user_id, number="A-IDEMP", close_reason=CloseReason.OPEN_REJECT.value)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, supplier_id=supplier_a)
|
||||
|
||||
first = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a)
|
||||
second = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a)
|
||||
|
||||
assert first.result.success is True
|
||||
assert second.result.success is False
|
||||
assert len(await _notifications(engine, user_id)) == 1
|
||||
|
||||
|
||||
async def test_award_rejects_non_owner(clean):
|
||||
"""검증: 남의 개찰 견적을 일반 유저(비소유·USER)가 직접 낙찰 시도.
|
||||
기대결과: 거부(ACCOUNT_FORBIDDEN) + close_reason 개찰 유지 + 알림 없음."""
|
||||
engine = clean
|
||||
owner, other, supplier_a = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
|
||||
qt = await _seed_opened(engine, user_id=owner, number="A-NONOWNER", close_reason=CloseReason.OPEN_PRICE.value)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, supplier_id=supplier_a)
|
||||
|
||||
res = await _service().award_quotation(str(qt), None, other, UserRole.USER.value, supplier_a)
|
||||
|
||||
assert res.result.success is False
|
||||
assert res.result.code == ErrorType.ACCOUNT_FORBIDDEN.value
|
||||
row = await _quotation(engine, qt)
|
||||
assert row.close_reason == CloseReason.OPEN_PRICE.value
|
||||
assert row.preferred_sp_id is None
|
||||
assert len(await _notifications(engine, owner)) == 0
|
||||
|
||||
|
||||
async def test_award_allows_owner_role(clean):
|
||||
"""검증: 남의 개찰 견적을 최고관리자(OWNER)가 직접 낙찰.
|
||||
기대결과: 낙찰 성공 + 알림은 견적 작성자(owner) 인박스에 남는다(호출자가 아니라)."""
|
||||
engine = clean
|
||||
creator, admin, supplier_a = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
|
||||
qt = await _seed_opened(engine, user_id=creator, number="A-OWNER", close_reason=CloseReason.OPEN_EQUAL.value)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, supplier_id=supplier_a)
|
||||
|
||||
res = await _service().award_quotation(str(qt), None, admin, UserRole.OWNER.value, supplier_a)
|
||||
|
||||
assert res.result.success is True
|
||||
row = await _quotation(engine, qt)
|
||||
assert row.close_reason == CloseReason.AWARDED.value
|
||||
assert str(row.preferred_sp_id) == str(supplier_a)
|
||||
assert len(await _notifications(engine, creator)) == 1
|
||||
assert len(await _notifications(engine, admin)) == 0
|
||||
|
||||
|
||||
# ===== 헬퍼 =====
|
||||
async def _seed_opened(engine, *, user_id, number, close_reason, round_=1):
|
||||
"""개찰/낙찰 상태(status=CLOSED + close_reason)로 견적 1건 시드. 낙찰자 컬럼은 비운 채 시작."""
|
||||
qt_id = uuid.uuid4()
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO quotations "
|
||||
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, close_reason, "
|
||||
" round, iteration, start_time, end_time, deleted) VALUES "
|
||||
"(:qt_id, :user_id, :qt_setting_id, :version_id, '견적A', :number, :type, :status, :close_reason, "
|
||||
" :round, 0, :start_time, :end_time, false)"
|
||||
),
|
||||
{
|
||||
"qt_id": qt_id, "user_id": user_id, "qt_setting_id": uuid.uuid4(),
|
||||
"version_id": uuid.uuid4(), "number": number, "type": QuotationType.REQUOTE.value,
|
||||
"status": QuotationStatus.CLOSED.value, "close_reason": close_reason,
|
||||
"round": round_, "start_time": PAST, "end_time": PAST,
|
||||
},
|
||||
)
|
||||
return qt_id
|
||||
|
||||
|
||||
async def _add_session(engine, qt_id, *, status, bid_price=None, supplier_id=None):
|
||||
"""세션 1건 시드(공급사 협상 1건). status/bid_price 로 협상완료·입찰가를 만든다."""
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO sessions "
|
||||
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
|
||||
" target_price, status, bid_price, end_time) VALUES "
|
||||
"(:session_id, :quotation_id, :item_id, :supplier_id, 'Q', 1, :qt_type, "
|
||||
" 0, :status, :bid_price, :end_time)"
|
||||
),
|
||||
{
|
||||
"session_id": uuid.uuid4(), "quotation_id": qt_id, "item_id": uuid.uuid4(),
|
||||
"supplier_id": supplier_id or uuid.uuid4(), "qt_type": QuotationType.REQUOTE.value,
|
||||
"status": status, "bid_price": bid_price, "end_time": PAST,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def _quotation(engine, qt_id):
|
||||
"""견적 1행(마감 결과 컬럼 확인용)."""
|
||||
async with engine.begin() as conn:
|
||||
return (await conn.execute(
|
||||
text("SELECT close_reason, preferred_sp_yn, preferred_sp_id, equal_bid_yn "
|
||||
"FROM quotations WHERE qt_id = :qt_id"),
|
||||
{"qt_id": qt_id},
|
||||
)).one()
|
||||
|
||||
|
||||
async def _notifications(engine, user_id):
|
||||
"""user_id(작성자) 인박스 알림 (type, data, ref_qt_id) — 생성순."""
|
||||
async with engine.begin() as conn:
|
||||
return (await conn.execute(
|
||||
text("SELECT type, data, ref_qt_id FROM notifications WHERE user_id = :uid ORDER BY created_at"),
|
||||
{"uid": user_id},
|
||||
)).all()
|
||||
|
||||
|
||||
def _service():
|
||||
return QuotationService(QuotationCRUD())
|
||||
Reference in new issue
Block a user