[feat] negodata: 결렬 폐지→개찰 마감 개편 + 낙찰기준 견적 단위 이관 + 세팅 컬럼 정리 (백엔드+DB)
Co-Authored-By: Claude Opus 4.8뀨 <noreply@anthropic.com>
This commit is contained in:
1 parent
1a7674b1e3
commit
38709b3098
14 files changed
+314
-415
No files matched your search
@@ -54,9 +54,6 @@ class QuotationService:
|
||||
# 기본 전략 버전(card.versions 시드). 견적 생성 시 version_id 미지정이면 이 값으로 채운다.
|
||||
DEFAULT_VERSION_ID = uuid.UUID("00000000-0000-0000-0000-000000000030")
|
||||
|
||||
# 재생성 한도: 한 체인(같은 견적번호)에서 사유(미참여/동가)별 최대 1번까지 재생성(순서 무관, 같은 사유 2번 불가).
|
||||
MAX_REGEN_PER_CAUSE = 1
|
||||
|
||||
# 재생성 라운드의 최소 협상기간(방어적 하한). 원본 협상기간이 비정상적으로 짧으면(또는 0/음수면)
|
||||
# 새 라운드가 생성 즉시 만료돼 다음 크론 tick(*/5분)에 또 마감되는 연쇄를 막는다.
|
||||
# 정상 견적(수 시간~수일)은 원본 기간을 그대로 쓰며, 이 하한은 비정상적으로 짧은 경우에만 적용된다.
|
||||
@@ -168,7 +165,6 @@ class QuotationService:
|
||||
rates = rates or {}
|
||||
fee = self.INTERNET_AVERAGE_FEE
|
||||
margin = rates.get("margin") or 0.0
|
||||
anchoring = rates.get("anchoring") or 0.0
|
||||
is_new = QuotationType.is_new(quotation.type)
|
||||
md = quotation.md_price
|
||||
|
||||
@@ -187,7 +183,6 @@ class QuotationService:
|
||||
res.selling = int(selling) if selling is not None else None
|
||||
res.fee = fee
|
||||
res.margin = margin
|
||||
res.anchoring_value = anchoring
|
||||
res.candidates = [TargetCandidate(basis=b, label=self._CANDIDATE_LABELS.get(b, b), value=int(v)) for b, v in cands]
|
||||
res.chosen_basis = None if is_inherited else chosen_basis
|
||||
res.target_price = sess.target_price
|
||||
@@ -298,6 +293,8 @@ class QuotationService:
|
||||
item_ids=req.item_ids,
|
||||
supplier_ids=req.supplier_ids,
|
||||
card_ids=req.card_ids,
|
||||
mid_action=req.mid_action,
|
||||
over_action=req.over_action,
|
||||
)
|
||||
if res.result.success:
|
||||
await create_notification(
|
||||
@@ -375,6 +372,8 @@ class QuotationService:
|
||||
item_ids=item_ids,
|
||||
supplier_ids=list(supplier_ids),
|
||||
card_ids=[], # 새 버전 안 만듦(원본 version_id 재사용)
|
||||
mid_action=original.mid_action, # 낙찰 기준 상속(타입이 REQUOTE 로 바뀌면 빌더가 AWARD 로 재정규화)
|
||||
over_action=original.over_action,
|
||||
inherited=inherited, # 직전 라운드 목표가 상속(앵커링가는 현재 rate 로 재계산)
|
||||
)
|
||||
|
||||
@@ -384,11 +383,21 @@ class QuotationService:
|
||||
type_: int, status: int, round_: int, start_time, end_time,
|
||||
manager_name, manager_email, manager_contact_number, memo, md_price, supplier_type,
|
||||
item_ids: list, supplier_ids: list, card_ids: list,
|
||||
mid_action: Optional[int] = None, # 낙찰 기준(견적 단위). 앵커링가<투찰가≤목표가 처리(AWARD/OPEN)
|
||||
over_action: Optional[int] = None, # 목표가<투찰가 처리(1:1 협상은 항상 OPEN)
|
||||
inherited: Optional[dict] = None, # 재생성 시 {item_id: target_price} 상속(KTC) — 목표가만. 앵커는 항상 재계산
|
||||
) -> Res_CreateQuotation:
|
||||
"""견적 1건 + (상품×공급사) 세션들을 한 트랜잭션으로 생성하는 공통 빌더."""
|
||||
res = Res_CreateQuotation()
|
||||
|
||||
# 낙찰 기준 정규화 — 1:N 경매는 항상 최저가 낙찰(mid=over=AWARD 강제). 1:1 협상은 요청값(미지정=AWARD).
|
||||
# create/regenerate 양 경로가 이 빌더를 타므로 불변식을 여기 한 곳에서 강제한다(재생성 시 타입 전환도 자동 재정규화).
|
||||
if QuotationType.is_auction(type_):
|
||||
mid_action = over_action = PriceGateAction.AWARD.value
|
||||
else:
|
||||
mid_action = mid_action or PriceGateAction.AWARD.value
|
||||
over_action = over_action or PriceGateAction.AWARD.value
|
||||
|
||||
# 세션 목표가 입력(상품별 인터넷최저가/매입가/판매가 + 세팅 율). 읽기 트랜잭션에서 먼저 조회.
|
||||
prices = {}
|
||||
if item_ids:
|
||||
@@ -455,6 +464,8 @@ class QuotationService:
|
||||
memo=memo,
|
||||
md_price=md_price,
|
||||
supplier_type=supplier_type,
|
||||
mid_action=mid_action,
|
||||
over_action=over_action,
|
||||
)
|
||||
|
||||
# 상품 × 공급사 조합마다 세션 1개. md/매입/판매/인터넷 후보가 하나도 없으면 목표가 산정 불가 → 생성 실패.
|
||||
@@ -557,11 +568,11 @@ class QuotationService:
|
||||
|
||||
@staticmethod
|
||||
def _gate_action(bid, target, anchor, mid_action, over_action) -> int:
|
||||
"""가격게이트 판정 → PriceGateAction 코드.
|
||||
"""가격게이트 판정 → PriceGateAction 코드(AWARD=낙찰 / OPEN=개찰).
|
||||
bid ≤ 앵커링가 → 무조건 낙찰(AWARD)
|
||||
앵커링가 < bid ≤ 목표가 → mid_action(설정)
|
||||
목표가 < bid → over_action(설정)
|
||||
target/bid 없으면(설정 불완전 등) AWARD 폴백(하위호환: 기존 '무조건 낙찰')."""
|
||||
앵커링가 < bid ≤ 목표가 → mid_action(견적 낙찰 기준)
|
||||
목표가 < bid → over_action(1:1 협상은 항상 OPEN=개찰)
|
||||
target/bid 없으면(산정 불가 등) AWARD 폴백(최저가 그대로 낙찰)."""
|
||||
if bid is None or target is None:
|
||||
return PriceGateAction.AWARD.value
|
||||
bid = int(bid)
|
||||
@@ -571,9 +582,9 @@ class QuotationService:
|
||||
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:
|
||||
async def _close(self, qt_uuid, close_reason: int, data: Optional[dict] = None) -> None:
|
||||
"""마감 공통: status→CLOSED + close_reason 기록 + (있으면)추가데이터 + 미완료(미시작·진행중) 세션→미참여.
|
||||
close_reason(CloseReason)이 재생성 한도 카운팅·유찰 사유 구분의 단일 근거.
|
||||
close_reason(CloseReason)이 낙찰/개찰 사유 구분의 단일 근거.
|
||||
preferred_sp_*/equal_bid_* 는 프론트 표시용으로 함께 채운다(사유 판별은 close_reason 이 담당)."""
|
||||
payload = {"status": QuotationStatus.CLOSED.value, "close_reason": close_reason}
|
||||
if data:
|
||||
@@ -588,28 +599,22 @@ class QuotationService:
|
||||
],
|
||||
)
|
||||
|
||||
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 _open(self, qt_uuid, original, close_reason: int, reason: str, data: Optional[dict] = None) -> CloseOutcome:
|
||||
"""개찰 마감 — 낙찰자 미정으로 CLOSED + close_reason(OPEN_*) 기록 + 작성자 알림. 자동 재협상/재생성 없음(담당자 수동 처리).
|
||||
결렬(유찰) 아님. 알림 코드는 유지하되 프론트에서 '개찰'로 표기한다."""
|
||||
await self._close(qt_uuid, close_reason, data)
|
||||
await create_notification(
|
||||
original.user_id, NotificationType.FAILURE,
|
||||
{"qt_name": original.name, "qt_number": original.number, "reason": reason},
|
||||
ref_qt_id=qt_uuid,
|
||||
)
|
||||
return CloseOutcome.OPENED
|
||||
|
||||
async def close_and_decide(self, qt_id) -> CloseOutcome:
|
||||
"""[마감] 견적을 마감하며 결과 판정. 낙찰자는 협상완료 최저가(단독/동가), 그 위에 회사 가격정책(가격게이트)으로 낙찰/재협상/유찰을 가른다.
|
||||
- 단독 최저가: 가격게이트(≤앵커 무조건낙찰 / 앵커~목표 mid_action / 목표초과 over_action) → 낙찰 / 재협상(한도내) / 유찰
|
||||
- 동가: 그 가격 구간 설정이 '유찰'이 아니고 한도 남으면 재입찰(tie 해소), 유찰 설정이거나 한도 소진이면 유찰
|
||||
- 협상거부: 유찰
|
||||
- 전원 미참여: 재소집(한도내) / 유찰
|
||||
재생성 한도: regen_limit = 체인(같은 견적번호) 전체 재생성 '총' 횟수(사유 무관). 마감 사유는 close_reason 에 기록(카운팅·유찰사유 구분의 단일 근거).
|
||||
"""[마감] 견적을 마감하며 결과 판정. 협상완료 단독 최저가가 낙찰 기준(가격게이트)을 통과할 때만 낙찰(AWARDED).
|
||||
- 단독 최저가: ≤앵커 항상 낙찰 / 앵커~목표 mid_action / 목표초과 over_action(1:1 협상은 항상 OPEN=개찰).
|
||||
- 그 외(기준 미달·동가·협상거부·전원 미응찰)는 결렬(유찰)이 아니라 개찰(OPEN_*) — 낙찰자 미정으로 마감.
|
||||
자동 재협상/재생성 없음. 다음 라운드는 담당자가 상세에서 수동 재생성(regenerate_quotation)한다.
|
||||
공통: 원자적 status→CLOSED 선점, 미시작·진행중 세션→미참여."""
|
||||
qt_uuid = qt_id if isinstance(qt_id, uuid.UUID) else uuid.UUID(str(qt_id))
|
||||
|
||||
@@ -617,7 +622,7 @@ class QuotationService:
|
||||
if err_type != ErrorType.SUCCESS or original is None:
|
||||
return CloseOutcome.CLOSED
|
||||
|
||||
# [동시 마감 가드] 원자적으로 status→CLOSED 선점. 실제로 전이한 호출자만 통과(이중 재생성·uq(number,round) 충돌 방지).
|
||||
# [동시 마감 가드] 원자적으로 status→CLOSED 선점. 실제로 전이한 호출자만 통과.
|
||||
claim_err, claimed = await DB_SESSION_MNG.execute_lambda_claim(
|
||||
quotations.DBType(),
|
||||
lambda s: self.quotation_crud.claim_for_close(s, qt_uuid),
|
||||
@@ -636,29 +641,15 @@ class QuotationService:
|
||||
has_rejected = any(r.status == SessionStatus.REJECTED.value for r in rows)
|
||||
winner, equal = self._pick_winner(done)
|
||||
|
||||
# 가격게이트 입력: 회사 정책(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
|
||||
# 가격게이트 입력: 견적 단위 낙찰 기준(mid/over, 생성 시점 박제) + 세션 목표가/앵커링가(견적당 상품 1개라 세션 공통값)
|
||||
mid_action = original.mid_action or PriceGateAction.AWARD.value
|
||||
over_action = original.over_action or PriceGateAction.AWARD.value
|
||||
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) 단독 최저가 → 가격게이트로 낙찰/재협상/유찰
|
||||
# 1) 단독 최저가가 낙찰 기준 통과 → 낙찰. 미달 → 개찰(가격).
|
||||
if winner is not 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"],
|
||||
@@ -671,70 +662,20 @@ class QuotationService:
|
||||
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.FAILURE,
|
||||
{"qt_name": original.name, "qt_number": original.number, "reason": "price"},
|
||||
ref_qt_id=qt_uuid,
|
||||
)
|
||||
return CloseOutcome.CLOSED
|
||||
# 개찰(가격) — 낙찰/동가 플래그는 NULL 로 둔다(대시보드 '개찰' 스코프가 preferred/equal 둘 다 NULL 로 집계).
|
||||
return await self._open(qt_uuid, original, CloseReason.OPEN_PRICE.value, "price")
|
||||
|
||||
# 2) 동가 → 그 가격 구간 설정이 '유찰'이 아니고 한도 남으면 재입찰(tie 해소), 유찰 설정이거나 한도 소진이면 유찰.
|
||||
# (동가는 단독 낙찰 불가 → AWARD 설정이어도 '재입찰로 tie 해소'가 자연스러워 기본은 재입찰=하위호환. 회사가 FAIL 로 두면 유찰.)
|
||||
# 2) 동가(최저가 동점) → 개찰(동가). 낙찰자 미정. equal_bid_yn 으로 표기(대시보드 '동가' 스코프).
|
||||
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.FAILURE,
|
||||
{"qt_name": original.name, "qt_number": original.number, "reason": "equal"},
|
||||
ref_qt_id=qt_uuid,
|
||||
)
|
||||
return CloseOutcome.CLOSED
|
||||
return await self._open(qt_uuid, original, CloseReason.OPEN_EQUAL.value, "equal",
|
||||
{"equal_bid_yn": True, "equal_bid_data": equal})
|
||||
|
||||
# 3) 협상거부 있음 → 유찰
|
||||
# 3) 협상거부 있음 → 개찰(거부).
|
||||
if has_rejected:
|
||||
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
|
||||
return await self._open(qt_uuid, original, CloseReason.OPEN_REJECT.value, "rejected")
|
||||
|
||||
# 4) 전원 미참여 → 공급사 전체 재소집(한도 남을 때)
|
||||
if not done and rows and regen_used < limit:
|
||||
supplier_ids = list({r.supplier_id for r in rows})
|
||||
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"},
|
||||
ref_qt_id=qt_uuid,
|
||||
)
|
||||
return CloseOutcome.CLOSED
|
||||
|
||||
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_reasons(s, number, current_round),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
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)
|
||||
# 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:
|
||||
"""[프론트] 마감된 견적을 골라 수동으로 다음 라운드를 생성한다.
|
||||
|
||||
@@ -65,11 +65,7 @@ class QuotationSettingService:
|
||||
setting = quotation_settings(
|
||||
user_id=uuid.UUID(user_id),
|
||||
target_margin_rate=req.target_margin_rate,
|
||||
anchoring_value=req.anchoring_value,
|
||||
card_count=req.card_count,
|
||||
mid_action=req.mid_action.value,
|
||||
over_action=req.over_action.value,
|
||||
regen_limit=req.regen_limit,
|
||||
)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotation_settings.DBType()],
|
||||
@@ -86,11 +82,6 @@ class QuotationSettingService:
|
||||
user_uuid = uuid.UUID(user_id)
|
||||
setting_uuid = uuid.UUID(qt_setting_id)
|
||||
data = req.model_dump(exclude_unset=True)
|
||||
# PriceGateAction enum → SMALLINT 코드값으로 변환(모델 컬럼이 int)
|
||||
for k in ("mid_action", "over_action"):
|
||||
v = data.get(k)
|
||||
if v is not None and hasattr(v, "value"):
|
||||
data[k] = v.value
|
||||
|
||||
# 소유권 확인
|
||||
err_type, _ = await self._fetch_owned(user_uuid, setting_uuid)
|
||||
|
||||
Reference in new issue
Block a user