[feat] negodata: 마감 close_reason 개편 + 견적상세 단가조정 스펙트럼

- 마감사유 quotations.close_reason(SMALLINT, 8종) 신설 — 낙찰/재협상3종/유찰4종 구분, 재생성 한도 카운팅. quotation_settings 에 mid_action·over_action·regen_limit(3구간 가격정책) 추가. models.py·enums.py·01-schema.sql·crud·service·테스트 정합.
- 프론트 노출: CloseReason/PriceGateAction 라벨·배지, 목록 마감결과 컬럼, 견적세팅 모달 3구간. orval 생성모델 갱신.
- 견적상세 결과밴드: 목표가→낙찰가→절감 stat 트리오를 단가조정 흐름 스펙트럼(목표가·최저·최고 투찰가)으로 교체. lowestBid/highestBid 는 bid_price 파생(DB 컬럼 아님), 최초가 컬럼 없어 시작앵커=최고 투찰가로 대체. 라벨 방향 값순 번갈아 배치로 겹침 방지.
- 라벨 정정: "단독 낙찰"→"낙찰"(낙찰은 단수), "목표 대비"→"목표가 대비".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 4.8 committed 2026-07-03 08:37:40 +09:00
1 parent d0b6e785af
commit e23349c11e
32 files changed
+1087 -325

No files matched your search

+133 -139
View File
@@ -7,7 +7,7 @@ from fastapi import Depends
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, DBWRType, ErrorType, NotificationType, QuotationStatus, QuotationType, SessionStatus
from common.enums import CloseOutcome, CloseReason, DBWRType, ErrorType, NotificationType, PriceGateAction, QuotationStatus, QuotationType, SessionStatus
from common.logger import LOG
from common.models.gmodel import PageParams
from common.utils.gtime import GTime
@@ -268,13 +268,15 @@ class QuotationService:
return res
async def create_quotation(self, user_id: str, req: Req_CreateQuotation) -> Res_CreateQuotation:
"""[프론트] 신규 견적 생성. 요청값을 보정한 뒤 공통 빌더(_build_quotation)에 위임한다."""
return await self._build_quotation(
"""[프론트] 신규 견적 생성. 요청값을 보정한 뒤 공통 빌더(_build_quotation)에 위임한다.
생성 성공 시 작성자에게 CREATED 알림(인박스)."""
number = self._gen_number() # 견적번호는 항상 서버 생성(프론트 입력란 없음)
res = await self._build_quotation(
user_id=user_id,
qt_setting_id=req.qt_setting_id,
version_id=req.version_id or self.DEFAULT_VERSION_ID,
name=req.name,
number=self._gen_number(), # 견적번호는 항상 서버 생성(프론트 입력란 없음)
number=number,
type_=req.type,
status=req.status or QuotationStatus.CREATED.value,
round_=req.round or 1,
@@ -290,6 +292,13 @@ class QuotationService:
supplier_ids=req.supplier_ids,
card_ids=req.card_ids,
)
if res.result.success:
await create_notification(
user_id, NotificationType.CREATED,
{"qt_name": req.name, "qt_number": number},
ref_qt_id=res.qt_id,
)
return res
async def regenerate_next_round(self, original_qt_id: uuid.UUID, supplier_ids: list) -> Res_CreateQuotation:
"""[마감 후속] 결판 안 난 견적의 '다음 라운드'를 새로 만든다.
@@ -508,98 +517,71 @@ class QuotationService:
if len(tied) > 1:
equal = {"price": min_price, "suppliers": [{"supplier_id": str(sid), "name": name} for sid, _, name in tied]}
return None, equal
return {"supplier_id": tied[0][0], "name": tied[0][2]}, None
return {"supplier_id": tied[0][0], "name": tied[0][2], "bid_price": min_price}, None
async def _award_and_close(self, qt_uuid, winner) -> None:
"""단독 낙찰 확정 + 마감 + 미완료(미시작·진행중) 세션 미참여."""
data = {
"status": QuotationStatus.CLOSED.value,
"preferred_sp_yn": True,
"preferred_sp_id": winner["supplier_id"],
"preferred_sp_name": (winner["name"] or "")[:20],
"equal_bid_yn": False,
}
@staticmethod
def _gate_action(bid, target, anchor, mid_action, over_action) -> int:
"""가격게이트 판정 → PriceGateAction 코드.
bid ≤ 앵커링가 → 무조건 낙찰(AWARD)
앵커링가 < bid ≤ 목표가 → mid_action(설정)
목표가 < bid → over_action(설정)
target/bid 없으면(설정 불완전 등) AWARD 폴백(하위호환: 기존 '무조건 낙찰')."""
if bid is None or target is None:
return PriceGateAction.AWARD.value
bid = int(bid)
if anchor is not None and bid <= int(anchor):
return PriceGateAction.AWARD.value
if bid <= int(target):
return mid_action or PriceGateAction.AWARD.value
return over_action or PriceGateAction.AWARD.value
async def _close(self, qt_uuid, close_reason: int, data: dict = None) -> None:
"""마감 공통: status→CLOSED + close_reason 기록 + (있으면)추가데이터 + 미완료(미시작·진행중) 세션→미참여.
close_reason(CloseReason)이 재생성 한도 카운팅·유찰 사유 구분의 단일 근거.
preferred_sp_*/equal_bid_* 는 프론트 표시용으로 함께 채운다(사유 판별은 close_reason 이 담당)."""
payload = {"status": QuotationStatus.CLOSED.value, "close_reason": close_reason}
if data:
payload.update(data)
await DB_SESSION_MNG.execute_lambda_run(
[quotations.DBType()],
[
lambda s: self.quotation_crud.update_quotation(s, qt_uuid, data),
lambda s: self.quotation_crud.update_quotation(s, qt_uuid, payload),
lambda s: self.quotation_crud.update_sessions_status(
s, qt_uuid, [SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value], SessionStatus.NOT_PARTICIPATED.value
),
],
)
async def _just_close(self, qt_uuid) -> None:
"""그냥 마감 + 미완료 세션 미참여."""
await DB_SESSION_MNG.execute_lambda_run(
[quotations.DBType()],
[
lambda s: self.quotation_crud.update_quotation(s, qt_uuid, {"status": QuotationStatus.CLOSED.value}),
lambda s: self.quotation_crud.update_sessions_status(
s, qt_uuid, [SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value], SessionStatus.NOT_PARTICIPATED.value
),
],
)
async def _close_as_no_show(self, qt_uuid) -> None:
"""전원 미참여로 '다음 라운드 재생성' 하며 마감 + 미완료 세션 미참여.
재생성 사유(미참여)를 체인에 남기기 위해 preferred_sp_yn=False, equal_bid_yn=False 로 양성 표식한다
(단독낙찰=preferred_sp_yn True / 동가=equal_bid_yn True / 거부·한도 등 그냥 마감=둘 다 NULL 과 구분).
_chain_regen_counts 가 이 표식으로 '미참여 재생성 이력'만 정확히 센다."""
data = {
"status": QuotationStatus.CLOSED.value,
"preferred_sp_yn": False,
"equal_bid_yn": False,
}
await DB_SESSION_MNG.execute_lambda_run(
[quotations.DBType()],
[
lambda s: self.quotation_crud.update_quotation(s, qt_uuid, data),
lambda s: self.quotation_crud.update_sessions_status(
s, qt_uuid, [SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value], SessionStatus.NOT_PARTICIPATED.value
),
],
)
async def _close_as_equal(self, qt_uuid, equal) -> None:
"""동가로 마감 + 미완료 세션 미참여. equal_bid_yn/data 를 기록해 둔다
(재생성 한도 계산이 이 플래그로 동가 라운드를 식별하고, 프론트도 동가 정보를 그대로 쓴다)."""
data = {
"status": QuotationStatus.CLOSED.value,
"preferred_sp_yn": False,
"equal_bid_yn": True,
"equal_bid_data": equal,
}
await DB_SESSION_MNG.execute_lambda_run(
[quotations.DBType()],
[
lambda s: self.quotation_crud.update_quotation(s, qt_uuid, data),
lambda s: self.quotation_crud.update_sessions_status(
s, qt_uuid, [SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value], SessionStatus.NOT_PARTICIPATED.value
),
],
)
async def _regen_and_notify(self, original, qt_uuid, supplier_ids: list, reason: str, equal=None) -> CloseOutcome:
"""마감 후 다음 라운드 재생성 + 성공 시 REGENERATED 알림. 실패 시 REGEN_FAILED(원본 CLOSED 인데 체인 끊김 → 노출)."""
regen = await self.regenerate_next_round(qt_uuid, supplier_ids)
if not regen.result.success:
LOG.e_no_callstack(
f"[close] 재생성 실패({reason}) qt={qt_uuid} number={original.number} round={original.round} "
f"code={regen.result.code}({regen.result.desc})"
)
return CloseOutcome.REGEN_FAILED
payload = {"qt_name": original.name, "qt_number": original.number, "reason": reason, "next_round": original.round + 1}
if equal is not None:
payload.update({"tied_price": equal["price"], "tied_count": len(equal["suppliers"])})
await create_notification(original.user_id, NotificationType.REGENERATED, payload, ref_qt_id=regen.qt_id)
return CloseOutcome.REGENERATED
async def close_and_decide(self, qt_id) -> CloseOutcome:
"""[마감] 견적을 마감하면서 결과를 판정한다.
1) 협상완료 중 최저가 단독 → 그 공급사 낙찰 확정
2) 협상완료 중 최저가 동가 → 다음 라운드 재생성(동가 업체끼리) [체인에 동가 재생성 이력 없을 때만]
3) 협상거부 세션이 하나라도 있음 → 그냥 마감 (재생성 안 함)
4) 전원 미참여(완료·거부 0) → 다음 라운드 재생성(원 견적 공급사 전체) [체인에 미참여 재생성 이력 없을 때만]
5) 그 외 / 한도 도달 → 그냥 마감
동가를 거부보다 먼저 본다: 동률은 '협상완료'한 업체들 간 경쟁이라 무관한 다른 업체의 거부로 막지 않는다.
재생성 한도: 한 체인(같은 견적번호)에서 '미참여' 1번 + '동가' 1번(순서 무관, 같은 사유 2번은 불가).
공통: status→CLOSED, 미시작·진행중 세션→미참여."""
"""[마감] 견적을 마감하며 결과 판정. 낙찰자는 협상완료 최저가(단독/동가), 그 위에 회사 가격정책(가격게이트)으로 낙찰/재협상/유찰을 가른다.
- 단독 최저가: 가격게이트(≤앵커 무조건낙찰 / 앵커~목표 mid_action / 목표초과 over_action) → 낙찰 / 재협상(한도내) / 유찰
- 동가: 그 가격 구간 설정이 '유찰'이 아니고 한도 남으면 재입찰(tie 해소), 유찰 설정이거나 한도 소진이면 유찰
- 협상거부: 유찰
- 전원 미참여: 재소집(한도내) / 유찰
재생성 한도: regen_limit = 체인(같은 견적번호) 전체 재생성 '총' 횟수(사유 무관). 마감 사유는 close_reason 에 기록(카운팅·유찰사유 구분의 단일 근거).
공통: 원자적 status→CLOSED 선점, 미시작·진행중 세션→미참여."""
qt_uuid = qt_id if isinstance(qt_id, uuid.UUID) else uuid.UUID(str(qt_id))
err_type, original = await self._fetch(qt_uuid)
if err_type != ErrorType.SUCCESS or original is None:
return CloseOutcome.CLOSED
# [동시 마감 가드] 마감 판정 전에 원자적으로 status→CLOSED 를 선점한다.
# 두 크론 잡(close_expired / close_negotiated)이나 수동 stop_quotation 이 같은 견적을
# 동시에 닫으려 해도, 실제로 CLOSED 로 전이한 호출자만 통과하고 진 호출자는 여기서 끝난다
# → 이중 재생성·uq(number,round) 충돌 방지. (이미 닫힌 견적의 재처리도 여기서 차단)
# [동시 마감 가드] 원자적으로 status→CLOSED 선점. 실제로 전이한 호출자만 통과(이중 재생성·uq(number,round) 충돌 방지).
claim_err, claimed = await DB_SESSION_MNG.execute_lambda_claim(
quotations.DBType(),
lambda s: self.quotation_crud.claim_for_close(s, qt_uuid),
@@ -618,69 +600,86 @@ class QuotationService:
has_rejected = any(r.status == SessionStatus.REJECTED.value for r in rows)
winner, equal = self._pick_winner(done)
# 1) 단독 낙찰 → 확정
# 가격게이트 입력: 회사 정책(mid/over/limit) + 세션 목표가/앵커링가(견적당 상품 1개라 세션 공통값)
_e, rates = await DB_SESSION_MNG.execute_lambda(
quotations.DBType(),
DBWRType.DB_READ.value,
lambda s: self.quotation_crud.get_setting_rates(s, original.qt_setting_id),
)
rates = rates or {}
mid_action = rates.get("mid_action") or PriceGateAction.AWARD.value
over_action = rates.get("over_action") or PriceGateAction.AWARD.value
limit = rates.get("regen_limit")
limit = limit if limit is not None else self.MAX_REGEN_PER_CAUSE
target = next((r.target_price for r in rows if r.target_price is not None), None)
anchor = next((r.target_anchoring_price for r in rows if r.target_anchoring_price is not None), None)
# 재생성 총 이력(체인, 사유 무관). regen_limit = 체인 전체 재생성 총 한도.
regen_used = await self._chain_regen_count(original.number, original.round)
# 1) 단독 최저가 → 가격게이트로 낙찰/재협상/유찰
if winner is not None:
await self._award_and_close(qt_uuid, winner)
winner_price = min((int(bp) for _, bp, _ in done if bp is not None), default=None)
action = self._gate_action(winner["bid_price"], target, anchor, mid_action, over_action)
if action == PriceGateAction.RENEGO.value and regen_used < limit:
await self._close(qt_uuid, CloseReason.REGEN_PRICE.value, {"preferred_sp_yn": False, "equal_bid_yn": False})
return await self._regen_and_notify(original, qt_uuid, [winner["supplier_id"]], "price")
if action == PriceGateAction.AWARD.value:
await self._close(qt_uuid, CloseReason.AWARDED.value, {
"preferred_sp_yn": True, "preferred_sp_id": winner["supplier_id"],
"preferred_sp_name": (winner["name"] or "")[:20], "equal_bid_yn": False,
})
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"]},
ref_qt_id=qt_uuid,
)
return CloseOutcome.AWARDED
# FAIL 이거나, RENEGO 인데 한도 소진 → 가격 유찰
await self._close(qt_uuid, CloseReason.FAIL_PRICE.value, {"preferred_sp_yn": False, "equal_bid_yn": False})
await create_notification(
original.user_id, NotificationType.SUCCESS,
{"qt_name": original.name, "qt_number": original.number,
"winner_name": winner["name"], "winner_price": winner_price},
original.user_id, NotificationType.FAILURE,
{"qt_name": original.name, "qt_number": original.number, "reason": "price"},
ref_qt_id=qt_uuid,
)
return CloseOutcome.AWARDED
return CloseOutcome.CLOSED
# 동가/미참여 재생성은 사유별 한도(각 1번, 순서 무관) 확인 후
no_part_used, equal_used = await self._chain_regen_counts(original.number, original.round)
# 2) 동가 → 동가 업체끼리 다음 라운드 (거부보다 먼저: tie 해소 우선, 체인에 동가 이력 없을 때만)
if equal is not None and equal_used < self.MAX_REGEN_PER_CAUSE:
tied_ids = [uuid.UUID(sp["supplier_id"]) for sp in equal["suppliers"]]
await self._close_as_equal(qt_uuid, equal) # 동가 기록(equal_bid_yn) 후 마감
regen = await self.regenerate_next_round(qt_uuid, tied_ids)
if not regen.result.success:
# 원본은 이미 CLOSED 인데 다음 라운드 생성이 실패 → 체인이 끊긴 상태. 성공으로 위장하지 않고 드러낸다.
LOG.e_no_callstack(
f"[close] 동가 재생성 실패 qt={qt_uuid} number={original.number} round={original.round} "
f"code={regen.result.code}({regen.result.desc})"
)
return CloseOutcome.REGEN_FAILED
# 2) 동가 → 그 가격 구간 설정이 '유찰'이 아니고 한도 남으면 재입찰(tie 해소), 유찰 설정이거나 한도 소진이면 유찰.
# (동가는 단독 낙찰 불가 → AWARD 설정이어도 '재입찰로 tie 해소'가 자연스러워 기본은 재입찰=하위호환. 회사가 FAIL 로 두면 유찰.)
if equal is not None:
action = self._gate_action(equal["price"], target, anchor, mid_action, over_action)
if action != PriceGateAction.FAIL.value and regen_used < limit:
tied_ids = [uuid.UUID(sp["supplier_id"]) for sp in equal["suppliers"]]
await self._close(qt_uuid, CloseReason.REGEN_EQUAL.value,
{"preferred_sp_yn": False, "equal_bid_yn": True, "equal_bid_data": equal})
return await self._regen_and_notify(original, qt_uuid, tied_ids, "equal", equal=equal)
await self._close(qt_uuid, CloseReason.FAIL_EQUAL.value,
{"preferred_sp_yn": False, "equal_bid_yn": True, "equal_bid_data": equal})
await create_notification(
original.user_id, NotificationType.REGENERATED,
{"qt_name": original.name, "qt_number": original.number, "reason": "equal",
"next_round": original.round + 1, "tied_price": equal["price"], "tied_count": len(equal["suppliers"])},
ref_qt_id=regen.qt_id,
original.user_id, NotificationType.FAILURE,
{"qt_name": original.name, "qt_number": original.number, "reason": "equal"},
ref_qt_id=qt_uuid,
)
return CloseOutcome.REGENERATED
# 3) 협상거부 있음 → 마감만 (재생성 안 함)
return CloseOutcome.CLOSED
# 3) 협상거부 있음 → 유찰
if has_rejected:
await self._just_close(qt_uuid)
await self._close(qt_uuid, CloseReason.FAIL_REJECT.value)
await create_notification(
original.user_id, NotificationType.FAILURE,
{"qt_name": original.name, "qt_number": original.number, "reason": "rejected"},
ref_qt_id=qt_uuid,
)
return CloseOutcome.CLOSED
# 4) 전원 미참여 → 공급사 전체로 다음 라운드 (체인에 미참여 재생성 이력 없을 때만)
if not done and rows and no_part_used < self.MAX_REGEN_PER_CAUSE:
# 4) 전원 미참여 → 공급사 전체 재소집(한도 남을 때)
if not done and rows and regen_used < limit:
supplier_ids = list({r.supplier_id for r in rows})
await self._close_as_no_show(qt_uuid) # 미참여 재생성 표식(preferred_sp_yn=False, equal_bid_yn=False) 후 마감
regen = await self.regenerate_next_round(qt_uuid, supplier_ids)
if not regen.result.success:
# 원본은 이미 CLOSED 인데 다음 라운드 생성이 실패 → 체인이 끊긴 상태. 성공으로 위장하지 않고 드러낸다.
LOG.e_no_callstack(
f"[close] 미참여 재생성 실패 qt={qt_uuid} number={original.number} round={original.round} "
f"code={regen.result.code}({regen.result.desc})"
)
return CloseOutcome.REGEN_FAILED
await create_notification(
original.user_id, NotificationType.REGENERATED,
{"qt_name": original.name, "qt_number": original.number, "reason": "no_show", "next_round": original.round + 1},
ref_qt_id=regen.qt_id,
)
return CloseOutcome.REGENERATED
# 5) 그 외 / 한도 도달 → 마감만
await self._just_close(qt_uuid)
await self._close(qt_uuid, CloseReason.REGEN_NOSHOW.value, {"preferred_sp_yn": False, "equal_bid_yn": False})
return await self._regen_and_notify(original, qt_uuid, supplier_ids, "no_show")
# 5) 그 외 / 한도 도달 → 미참여 유찰
await self._close(qt_uuid, CloseReason.FAIL_NOSHOW.value, {"preferred_sp_yn": False, "equal_bid_yn": False})
await create_notification(
original.user_id, NotificationType.FAILURE,
{"qt_name": original.name, "qt_number": original.number, "reason": "closed"},
@@ -688,23 +687,18 @@ class QuotationService:
)
return CloseOutcome.CLOSED
async def _chain_regen_counts(self, number: str, current_round: int) -> tuple[int, int]:
"""체인(같은 견적번호) 이전 라운드들의 '재생성 사유' 횟수. 반환: (미참여 횟수, 동가 횟수).
마감 시 남긴 양성 표식으로만 센다(오집계 방지):
- 동가 재생성 → equal_bid_yn=True
- 미참여 재생성 → preferred_sp_yn=False AND equal_bid_yn=False
단독낙찰(preferred_sp_yn=True)·거부/한도 그냥 마감(둘 다 NULL)은 어느 쪽에도 세지 않는다.
(수동 regenerate_quotation 으로 단독낙찰·거부 라운드를 이어붙여도 자동 재생성 한도에 영향 없음.)"""
err_type, flags = await DB_SESSION_MNG.execute_lambda(
async def _chain_regen_count(self, number: str, current_round: int) -> int:
"""체인(같은 견적번호) 이전 라운드들의 재생성 '총' 횟수(사유 무관). regen_limit 은 체인 전체 총 한도다.
close_reason 의 REGEN_*(가격/동가/미참여) 만 센다 — 낙찰(AWARDED)·유찰(FAIL_*)·미마감(NULL)은 한도에 안 셈."""
err_type, reasons = await DB_SESSION_MNG.execute_lambda(
quotations.DBType(),
DBWRType.DB_READ.value,
lambda s: self.quotation_crud.list_chain_close_flags(s, number, current_round),
lambda s: self.quotation_crud.list_chain_close_reasons(s, number, current_round),
)
if err_type != ErrorType.SUCCESS:
return 0, 0
equal = sum(1 for _pref, eq in flags if eq is True)
no_part = sum(1 for pref, eq in flags if pref is False and eq is False)
return no_part, equal
return 0
regen = {CloseReason.REGEN_PRICE.value, CloseReason.REGEN_EQUAL.value, CloseReason.REGEN_NOSHOW.value}
return sum(1 for c in reasons if c in regen)
async def regenerate_quotation(self, qt_id: str, company_id, supplier_ids: list) -> Res_CreateQuotation:
"""[프론트] 마감된 견적을 골라 수동으로 다음 라운드를 생성한다.