[feat] negosium·negodata: 협상 거부 흐름 정리 + 오프라인 계약가 낙찰 + 견적 상세 리모델링

협상 불가 사유를 내면 500 이 나고, 거부 폼은 목록·채팅이 따로 놀았으며,
제출한 내용을 다시 볼 방법이 없었다. 결렬 건은 협력사가 낸 거부가를 계약가로
간주해 낙찰시켜 절감 통계가 음수로 뒤집힐 수 있었고, 견적 상세는 판정 가격이
세 곳에 흩어져 대화 탭에선 아예 보이지 않았다.

agent
- 결렬 종료 로깅 크래시 수정 — _log 를 action_id 기반으로 되돌리고 선택 근거
  (Q·UCB·방문수)는 decision/policy 가 있을 때만 채운다. 종료 행은 카드 선택이
  없고 policy.update 뒤라 값을 넣으면 학습 화면 집계가 오염된다

negosium
- 거부 폼을 목록·채팅 공용 컴포넌트 하나로 통일(사유 3종 + 공급 희망가·의견 선택)
- 거부 사유 열람 — 목록에 '거부 사유 보기'(부가정보 보기와 같은 규격), 채팅
  재진입 시 대화 끝에 거부 내역 카드. 목록·채팅 init 응답에 reject_reason·reject_price 추가
- 자유 입력 거부("협상 포기합니다")가 사유 NULL 로 저장되던 문제 수정 — 폼 마커가
  없으면 원문을 사유로 쓰고, 문장 속 숫자를 희망가로 오인하지 않는다
- koreanNumber 를 전역 lib 으로 이동(공용 폼이 쓴다)

negodata
- 직접 낙찰에 계약가 입력 — 결렬·미응찰 건을 오프라인으로 다시 협상한 결과를
  담당자가 확정해 넣는다. 후보는 초청 협력사 전부(가격 미제출도 포함),
  계약가는 sessions.custom.offline_award 에 근거·작성자·시각과 함께 남긴다
- 통계 계약가 = 담당자 확정가 우선, 없으면 투찰가. 거부가를 계약가로 치던 파생 제거.
  KPI 에 오프라인 반영 건수 추가
- 견적 상세 리모델링 — 가격 레일(앵커링가/투찰현황 · 목표가 · 타결 상한가 · 결과가)을
  시트에 고정해 접힘·탭 전환에도 남기고, 스펙트럼에 타결 판정선과 구간색 추가.
  라벨은 폭을 실측해 두 레인으로 배치(겹침 불가). 상품·마감시각 등 전 행 동일 컬럼 제거,
  협상현황에 부가정보 노출, 1:1 은 협력사·세션상태를 결과 밴드로 올림

테스트: negosium 58 · negodata 110 통과. 프론트 빌드/린트 통과.
This commit is contained in:
minaChoi committed 2026-08-12 10:25:26 +09:00
1 parent d02ba20520
commit 6eb4dc26f8
70 files changed
+1695 -739

No files matched your search

+13 -1
View File
@@ -15,6 +15,10 @@ _EXPERIENCE_LOGS = table(
column("company_id"), column("session_id"), column("card_id"), column("reward"),
column("settled_price"), column("is_invalidated"), column("created_at"),
column("turn"),
# 선택 시점 박제값 — 카드가 왜 뽑혔는지의 근거. UCB = Q + 탐색보너스 라
# 둘의 차이가 "학습으로 뽑혔나 / 덜 써봐서 뽑혔나"를 가른다.
column("q_value_at_selection"), column("ucb_score_at_selection"),
column("visit_count_at_selection"),
schema="learning",
)
_ANCHORING_CURRENT = table(
@@ -78,11 +82,16 @@ class LearningCRUD(ILearningCRUD):
return ErrorType.SUCCESS, tuple(rows[0])
async def card_usage(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
"""카드별 사용 현황 — (카드번호, 사용 협상 수, 사용 횟수, 평균 라운드, 마지막 사용).
"""카드별 사용 현황 — (카드번호, 사용 협상 수, 사용 횟수, 평균 라운드, 마지막 사용,
평균 Q값, 평균 UCB, 누적 방문수).
협상 결과(타결·가격)는 카드 한 장의 성과로 나눌 수 없어 다루지 않는다 — 한 협상에 여러 장이
나가 어느 장의 몫인지 가릴 근거가 없고, 카드 배정도 국면에 따라 정해져 무작위가 아니다.
평균 라운드 = 그 카드가 협상의 몇 번째 라운드에 나갔는지(설정한 국면과 실제가 맞는지 대조).
Q값/방문수는 선택 시점 박제값(experience_logs)이라 q_values 테이블을 따로 안 읽는다 —
"그때 무슨 근거로 뽑혔나"가 사후 현재값보다 사용 현황에 맞는 기준이다.
방문수는 마지막 선택 시점 누적값(단조 증가라 max 가 곧 최신).
"""
query = (
select(
@@ -91,6 +100,9 @@ class LearningCRUD(ILearningCRUD):
func.count(),
func.avg(_EXPERIENCE_LOGS.c.turn),
func.max(_EXPERIENCE_LOGS.c.created_at),
func.avg(_EXPERIENCE_LOGS.c.q_value_at_selection),
func.avg(_EXPERIENCE_LOGS.c.ucb_score_at_selection),
func.max(_EXPERIENCE_LOGS.c.visit_count_at_selection),
)
.where(and_(*_valid(company_id), _EXPERIENCE_LOGS.c.card_id.isnot(None)))
.group_by(_EXPERIENCE_LOGS.c.card_id)
+27 -4
View File
@@ -2,7 +2,8 @@ from abc import ABC, abstractmethod
from datetime import datetime
from typing import Optional, Tuple
from sqlalchemy import select, func, and_, or_, update
from sqlalchemy import select, func, and_, or_, update, cast, text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
@@ -79,6 +80,10 @@ class IQuotationCRUD(ABC):
async def update_sessions_status(self, cdb: AsyncSession, qt_id, from_statuses: list[int], to_status: int) -> ErrorType:
pass
@abstractmethod
async def merge_session_custom(self, cdb: AsyncSession, session_id, patch: dict) -> ErrorType:
pass
@abstractmethod
async def soft_delete(self, cdb: AsyncSession, qt_id) -> ErrorType:
"""견적과 연결된 하위 데이터(세션·대화)를 함께 소프트 삭제."""
@@ -571,6 +576,22 @@ class QuotationCRUD(IQuotationCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
async def merge_session_custom(self, cdb: AsyncSession, session_id, patch: dict) -> ErrorType:
# sessions.custom 부분 갱신(기존 키 보존). 부가정보·의견·재협상 요청이 같은 컬럼을 쓰므로 덮어쓰면 안 된다.
try:
query = (
update(sessions)
.where(sessions.session_id == session_id)
.values(
custom=func.coalesce(sessions.custom, cast(text("'{}'"), JSONB)).op("||")(cast(patch, JSONB)),
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 soft_delete(self, cdb: AsyncSession, qt_id) -> ErrorType:
"""견적 + 연결된 하위 데이터(협상 세션·대화)를 한 트랜잭션으로 소프트 삭제한다.
대화(chats)→세션(sessions)→견적(quotations) 순서로 deleted=True. 한 스텝이라도 실패하면 execute_lambda_run 이 롤백한다."""
@@ -703,14 +724,16 @@ class QuotationCRUD(IQuotationCRUD):
return ErrorType.DB_RUN_FAILED, 0
async def list_sessions_status(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, list]:
"""[마감 판정] 견적의 모든 세션 → (status, supplier_id, bid_price, name, target_price, anchoring_price, reject_price). 삭제 제외.
"""[마감 판정] 견적의 모든 세션 → (status, supplier_id, bid_price, name, target_price, anchoring_price, reject_price, session_id). 삭제 제외.
공급사가 지워졌어도 세션 집계엔 포함되도록 outerjoin(이때 name 은 None).
target/anchoring 은 마감 가격게이트 입력(견적당 상품 1개라 세션 공통값).
reject_price 는 거부 협력사의 공급 희망 가격 — 자동 마감 판정엔 안 쓰고 수동 직접 낙찰 후보에서만 본다."""
reject_price 는 거부 협력사의 공급 희망 가격 — 자동 마감 판정엔 안 쓰고 화면 표기에만 쓴다.
session_id 는 직접 낙찰이 계약가를 그 세션 custom 에 적을 때 쓴다."""
try:
query = (
select(sessions.status, sessions.supplier_id, sessions.bid_price, suppliers.name,
sessions.target_price, sessions.anchoring_price, sessions.reject_price)
sessions.target_price, sessions.anchoring_price, sessions.reject_price,
sessions.session_id)
.outerjoin(suppliers, suppliers.supplier_id == sessions.supplier_id)
.where(sessions.quotation_id == qt_id, sessions.deleted == False) # noqa: E712
)
+8 -5
View File
@@ -1,7 +1,7 @@
from abc import ABC, abstractmethod
from typing import Tuple
from sqlalchemy import select, func, and_, or_, case
from sqlalchemy import select, func, and_, or_, case, cast, BigInteger
from sqlalchemy.orm import aliased
from sqlalchemy.ext.asyncio import AsyncSession
@@ -76,10 +76,12 @@ class StatisticsCRUD(IStatisticsCRUD):
async def winning_sessions(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
# 낙찰 마감 견적의 '낙찰 세션'(supplier_id=preferred_sp_id) 행 — 절감/추이/유형/카테고리/앵커도달률의 단일 원천.
# 파생: 저장 안 하고 조회 때 조인. category 는 items LEFT JOIN(자유텍스트·NULL 허용).
# 계약가는 coalesce(투찰가, 거부 시 공급 희망가) — 결렬 건을 담당자가 직접 낙찰하면 bid_price 가 없어
# 절감 집계에서 통째로 빠지기 때문. 이름은 bid_price 로 유지해 statistics_service 는 그대로 쓴다.
# 계약가 = 담당자가 확정한 값이 있으면 그 값, 없으면 협력사 투찰가.
# 결렬·미응찰 건을 오프라인으로 다시 협상하고 직접 낙찰하면 시스템 투찰가가 없거나 실제 계약가와
# 다르기 때문. 컬럼 이름은 bid_price 로 유지해 statistics_service 는 그대로 쓴다.
try:
award_price = func.coalesce(sessions.bid_price, sessions.reject_price).label("bid_price")
offline_price = cast(sessions.custom["offline_award"]["price"].astext, BigInteger)
award_price = func.coalesce(offline_price, sessions.bid_price).label("bid_price")
stmt = (
select(
quotations.updated_at,
@@ -88,6 +90,7 @@ class StatisticsCRUD(IStatisticsCRUD):
sessions.target_price,
award_price,
sessions.anchoring_price,
offline_price.isnot(None).label("is_offline"), # 오프라인 협상 반영 건수 표기용
)
.select_from(quotations)
.join(
@@ -95,7 +98,7 @@ class StatisticsCRUD(IStatisticsCRUD):
and_(
sessions.quotation_id == quotations.qt_id,
sessions.supplier_id == quotations.preferred_sp_id,
or_(sessions.bid_price.isnot(None), sessions.reject_price.isnot(None)),
or_(sessions.bid_price.isnot(None), offline_price.isnot(None)),
sessions.deleted == False, # noqa: E712
),
)
@@ -29,6 +29,11 @@ class CardUsageRow(LearningProtocol):
share: float = 0.0 # 전체 카드 사용 중 이 카드의 비중
avg_turn: float = 0.0 # 평균 몇 번째 라운드에 나갔는지 — 설정한 국면과 대조용
last_used_at: Optional[datetime] = None
# 선택 근거 — UCB = Q + 탐색보너스. 봇은 이 점수가 가장 높은 카드를 고른다.
avg_q: Optional[float] = None # 선택 시점 Q값 평균 — 학습이 매긴 이 카드의 값어치
avg_ucb: Optional[float] = None # 선택 시점 UCB 평균
explore_bonus: Optional[float] = None # avg_ucb - avg_q — 클수록 '아직 덜 검증돼서' 뽑힌 것
visits: int = 0 # 마지막 선택 시점 누적 방문수 — 적으면 Q값이 아직 추측
class AnchoringCell(LearningProtocol):
@@ -46,7 +46,9 @@ class Req_RegenerateQuotation(QuotationProtocol):
class Req_AwardQuotation(QuotationProtocol):
winner_supplier_id: uuid.UUID # 담당자가 직접 낙찰시킬 협력사(투찰한 협상완료 세션 중 선택)
winner_supplier_id: uuid.UUID # 담당자가 직접 낙찰시킬 협력사(견적에 초청된 협력사 중 선택)
contract_price: int # 최종 계약가(원). 오프라인 협상 결과를 담당자가 확정해 넣는다
contract_note: Optional[str] = None # 계약가 근거 메모(오프라인 협상 요약)
class QuotationData(WebPacketProtocol):
@@ -110,6 +112,7 @@ class SessionData(WebPacketProtocol):
qt_type: QuotationType
target_price: int
anchoring_price: Optional[int] = None # 앵커링가(원). 목표가×(1000−anchoring_value)//1000
done_ceiling_price: Optional[int] = None # 완료 상한가(원). 생성 시 박제 = 목표가×(1+완료상한율/1000)
status: SessionStatus
bid_price: Optional[int] = None
bid_at: Optional[datetime] = None
@@ -67,7 +67,10 @@ async def award_quotation(
):
# 권한(본인 견적만/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)
await service.award_quotation(
str(qt_id), user_info.company_id, user_info.user_id, user_info.role,
req.winner_supplier_id, req.contract_price, req.contract_note,
)
)
@@ -16,6 +16,7 @@ class StatKpi(WebPacketProtocol):
closed_count: int = 0 # 마감 견적 수(창)
regen_avg_round: float = 0.0 # 평균 재견적 라운드
markup_suppression_rate: float = 0.0 # 인상억제율(재협상: 직전 라운드 투찰가 대비 이번 투찰가 인하율, 파생)
offline_award_count: int = 0 # 낙찰 중 오프라인 협상 결과를 담당자가 반영한 건수(절감액엔 포함)
class StatMonthPoint(WebPacketProtocol):
@@ -59,8 +59,8 @@ class LearningService:
names = await self._read(lambda s: self.crud.card_names(s), default=[])
name_map = {str(number): (name, is_wild, card_pk) for number, name, is_wild, card_pk in names if number}
total_uses = sum(int(uses or 0) for _n, _s, uses, _t, _l in rows) or 1
for card_id, used_sessions, uses, avg_turn, last_used in rows:
total_uses = sum(int(r[2] or 0) for r in rows) or 1
for card_id, used_sessions, uses, avg_turn, last_used, avg_q, avg_ucb, visits in rows:
number = str(card_id)
name, is_wild, card_pk = name_map.get(number, (None, 0, None))
res.cards.append(CardUsageRow(
@@ -73,6 +73,12 @@ class LearningService:
share=round(int(uses or 0) / total_uses, 3),
avg_turn=round(float(avg_turn), 1) if avg_turn is not None else 0.0,
last_used_at=last_used,
avg_q=round(float(avg_q), 4) if avg_q is not None else None,
avg_ucb=round(float(avg_ucb), 4) if avg_ucb is not None else None,
# 탐색보너스는 두 값이 다 있을 때만 — 한쪽만 있으면 차이가 의미를 잃는다.
explore_bonus=(round(float(avg_ucb) - float(avg_q), 4)
if avg_q is not None and avg_ucb is not None else None),
visits=int(visits or 0),
))
res.kpi = LearningKpi(
+36 -20
View File
@@ -6,21 +6,12 @@ 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
from common.enums import CloseOutcome, CloseReason, DBWRType, ErrorType, NotificationType, PriceGateAction, QuotationStatus, SessionStatus
from common.logger import LOG
from common.utils.gtime import GTime
from router.v1.quotation.protocol import Res_Quotation
from services.notification import create_notification
def _award_price(row) -> Optional[int]:
"""직접 낙찰 시 계약 기준가 — 타결했으면 투찰가, 협상이 거부로 끝났으면 그때 써낸 공급 희망 가격.
둘 다 없으면(가격을 한 번도 안 낸 협력사) None → 낙찰 후보가 아니다.
자동 마감 판정(close_and_decide)은 이 함수를 쓰지 않는다 — 자동 낙찰은 투찰가만 본다."""
if row.status == SessionStatus.DONE.value and row.bid_price is not None:
return int(row.bid_price)
if row.status == SessionStatus.REJECTED.value and row.reject_price is not None:
return int(row.reject_price)
return None
class ClosingMixin:
@staticmethod
def _pick_winner(done_rows) -> tuple[Optional[dict], Optional[dict]]:
@@ -168,17 +159,25 @@ class ClosingMixin:
await self.close_and_decide(qt_uuid)
return await self.get_quotation(qt_id, company_id)
async def award_quotation(self, qt_id: str, company_id, user_id, role, winner_supplier_id) -> Res_Quotation:
async def award_quotation(
self, qt_id: str, company_id, user_id, role, winner_supplier_id,
contract_price: int, contract_note: Optional[str] = None,
) -> Res_Quotation:
"""[프론트] 개찰(낙찰자 미정 마감) 견적을 담당자가 직접 낙찰 처리한다.
가격을 써낸 세션 중 고른 협력사를 낙찰자로 박고 close_reason 을 AWARDED 로 바꾼다(직접 낙찰).
후보는 투찰한 협상완료(DONE) + 공급 희망 가격을 남긴 협상거부(REJECTED) — 협상이 결렬돼도
마지막에 제출한 가격으로 계약을 진행하는 운영 방침을 시스템에서 그대로 처리하기 위함이다.
협상이 결렬·미응찰로 끝나면 오프라인으로 다시 협상하고 그 결과를 여기서 반영한다 — 그래서
후보는 견적에 초청된 협력사 전부이고, 계약가는 담당자가 확정해 넣는다(시스템 제출가와 다를 수 있다).
계약가는 sessions.custom.offline_award 에 근거 메모·작성자·시각과 함께 남겨 통계가 이 값을 계약가로 읽는다.
자동 낙찰(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))
if not contract_price or contract_price <= 0:
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
res.msg = "계약가를 입력해야 낙찰할 수 있습니다."
return res
# 존재 확인(+회사 가드) — 남의 회사 견적은 NOT_FOUND.
err_type, original = await self._fetch(qt_uuid, company_id)
if err_type != ErrorType.SUCCESS or original is None:
@@ -200,20 +199,21 @@ class ClosingMixin:
res.msg = "개찰(낙찰자 미정) 상태의 견적만 직접 낙찰할 수 있습니다."
return res
# 낙찰 후보 = 가격을 써낸 세션. close_and_decide 와 같은 조회(list_sessions_status,
# 공급사 삭제돼도 포함되는 outerjoin)를 쓴다.
# 낙찰 후보 = 이 견적에 초청된 협력사 전부. 오프라인 협상 결과를 반영하는 자리라 시스템에
# 가격을 안 낸 협력사(전원 미응찰 견적 포함)도 고를 수 있다. 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.supplier_id == sp_uuid and _award_price(r) is not None), None)
winner = next((r for r in rows if r.supplier_id == sp_uuid), None)
if winner is None:
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
res.msg = "선택한 협력사는 이 견적의 낙찰 후보(가격을 제출한 협력사)가 아닙니다."
res.msg = "선택한 협력사는 이 견적에 초청된 협력사가 아닙니다."
return res
winner_price = _award_price(winner)
winner_price = int(contract_price)
# [동시 직접낙찰 가드] 개찰→낙찰 원자 선점. 실제로 전이한 호출자만 통과(재클릭·경합 방어).
claim_err, claimed = await DB_SESSION_MNG.execute_lambda_claim(
@@ -225,6 +225,22 @@ class ClosingMixin:
res.msg = "이미 낙찰 처리된 견적입니다."
return res
# 계약가를 낙찰 세션에 남긴다 — 통계가 이 값을 계약가로 읽고(투찰가보다 우선), 누가 언제 어떤
# 근거로 확정했는지 추적한다. custom 은 부가정보·의견과 같은 컬럼이라 병합(덮어쓰기 금지).
offline_award = {
"price": winner_price,
"note": (contract_note or "").strip()[:255],
"by": str(user_id) if user_id else "",
"at": GTime.UTC().isoformat(timespec="seconds"),
}
award_err = await DB_SESSION_MNG.execute_lambda_run(
[sessions.DBType()],
[lambda s: self.quotation_crud.merge_session_custom(s, winner.session_id, {"offline_award": offline_award})],
)
if award_err != ErrorType.SUCCESS:
# 낙찰(견적)은 이미 선점 전이됐다 — 계약가만 못 남긴 상태라 되돌리지 않고 경고로 남긴다.
LOG.w(f"[award] 계약가 기록 실패 qt_id={qt_id} session_id={winner.session_id} price={winner_price}")
# 작성자 알림 — 자동낙찰과 같은 SUCCESS 코드, manual 플래그로 '직접 낙찰' 구분.
await create_notification(
original.user_id, NotificationType.SUCCESS,
@@ -181,6 +181,7 @@ class QueriesMixin:
qt_type=r.qt_type,
target_price=r.target_price,
anchoring_price=r.anchoring_price,
done_ceiling_price=r.done_ceiling_price,
status=r.status,
bid_price=r.bid_price,
bid_at=r.bid_at,
@@ -80,6 +80,7 @@ class StatisticsService:
k.closed_count = closed
k.award_rate = (outcome.awarded / closed) if closed else 0.0
k.regen_avg_round = round(regen, 2)
k.offline_award_count = sum(1 for r in win_rows if r.is_offline)
k.markup_suppression_rate = round(markup, 4) # 인상억제율(재협상 직전 라운드 투찰가 대비, 파생)
# 전월 대비: 마지막 두 달 절감액 차(창에 2개월 미만이면 0).
k.savings_delta_mom = (trend[-1].savings - trend[-2].savings) if len(trend) >= 2 else 0
+66 -8
View File
@@ -39,7 +39,7 @@ async def test_award_opened_sets_winner_and_notifies(clean):
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)
res = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a, 100)
assert res.result.success is True
row = await _quotation(engine, qt)
@@ -65,7 +65,7 @@ async def test_award_rejects_when_not_opened(clean):
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)
res = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a, 100)
assert res.result.success is False
assert res.result.code == ErrorType.INVALID_REQUEST_DATA.value
@@ -73,14 +73,14 @@ async def test_award_rejects_when_not_opened(clean):
async def test_award_rejects_unknown_supplier(clean):
"""검증: 개찰 견적에, 투찰 후보가 아닌 협력사 id 를 지정.
"""검증: 개찰 견적에, 이 견적에 초청되지 않은(세션이 없는) 협력사 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)
res = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, stranger, 100)
assert res.result.success is False
row = await _quotation(engine, qt)
@@ -97,8 +97,8 @@ async def test_award_is_idempotent(clean):
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)
first = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a, 100)
second = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a, 100)
assert first.result.success is True
assert second.result.success is False
@@ -113,7 +113,7 @@ async def test_award_rejects_non_owner(clean):
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)
res = await _service().award_quotation(str(qt), None, other, UserRole.USER.value, supplier_a, 100)
assert res.result.success is False
assert res.result.code == ErrorType.ACCOUNT_FORBIDDEN.value
@@ -131,7 +131,7 @@ async def test_award_allows_owner_role(clean):
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)
res = await _service().award_quotation(str(qt), None, admin, UserRole.OWNER.value, supplier_a, 100)
assert res.result.success is True
row = await _quotation(engine, qt)
@@ -141,6 +141,64 @@ async def test_award_allows_owner_role(clean):
assert len(await _notifications(engine, admin)) == 0
async def test_award_records_contract_price_on_session(clean):
"""검증: 협력사 제출가(100)와 다른 계약가(88)로 직접 낙찰 — 오프라인 재협상 결과 반영.
기대결과: 낙찰 세션 custom.offline_award 에 계약가·메모가 남고, 알림 winner_price 도 계약가."""
engine = clean
user_id, supplier_a = uuid.uuid4(), uuid.uuid4()
qt = await _seed_opened(engine, user_id=user_id, number="A-OFFLINE", close_reason=CloseReason.OPEN_PRICE.value)
await _add_session(engine, qt, status=SessionStatus.REJECTED.value, bid_price=None, supplier_id=supplier_a)
res = await _service().award_quotation(
str(qt), None, user_id, UserRole.USER.value, supplier_a, 88, "오프라인 협상, 8/12 통화 합의",
)
assert res.result.success is True
async with engine.begin() as conn:
row = (await conn.execute(
text("SELECT custom FROM sessions WHERE quotation_id = :qt AND supplier_id = :sp"),
{"qt": qt, "sp": supplier_a},
)).first()
award = row.custom["offline_award"]
assert award["price"] == 88
assert award["note"] == "오프라인 협상, 8/12 통화 합의"
assert award["by"] == str(user_id)
notis = await _notifications(engine, user_id)
assert notis[0][1]["winner_price"] == 88
async def test_award_allows_supplier_without_price(clean):
"""검증: 시스템에 가격을 한 번도 안 낸(미참여) 협력사를 계약가와 함께 직접 낙찰.
기대결과: 낙찰 성공 — 전원 미응찰 견적도 오프라인 협상 결과를 반영할 수 있다."""
engine = clean
user_id, supplier_a = uuid.uuid4(), uuid.uuid4()
qt = await _seed_opened(engine, user_id=user_id, number="A-NOSHOW", close_reason=CloseReason.OPEN_NOSHOW.value)
await _add_session(engine, qt, status=SessionStatus.NOT_PARTICIPATED.value, bid_price=None, supplier_id=supplier_a)
res = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a, 77_000)
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)
async def test_award_rejects_without_contract_price(clean):
"""검증: 계약가 없이(0) 직접 낙찰 시도.
기대결과: 거부(INVALID_REQUEST_DATA) — 계약가는 절감 통계의 기준이라 필수다."""
engine = clean
user_id, supplier_a = uuid.uuid4(), uuid.uuid4()
qt = await _seed_opened(engine, user_id=user_id, number="A-NOPRICE", 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, user_id, UserRole.USER.value, supplier_a, 0)
assert res.result.success is False
assert res.result.code == ErrorType.INVALID_REQUEST_DATA.value
row = await _quotation(engine, qt)
assert row.close_reason == CloseReason.OPEN_PRICE.value
# ===== 헬퍼 =====
async def _seed_opened(engine, *, user_id, number, close_reason, round_=1):
"""개찰/낙찰 상태(status=CLOSED + close_reason)로 견적 1건 시드. 낙찰자 컬럼은 비운 채 시작."""