refactor(anchoring): 도메인 이름 전면 개편 — adjustments·anchoring_value/price·price_range·sample 용어 통일
용어 체계: 값=anchoring_value(정수‰)·가격=anchoring_price·조정=adjustment·구간=price_range·표본=sample - DB: rate_adjustments→anchoring.adjustments (id→adjustment_id, price_bracket_index→price_range_index, nego_count→sample_count, anchor_rate_before/after→anchoring_value_before/after, consumed_session_ids→used_session_ids) - sessions: target_anchoring_price→anchoring_price, anchor_rate_permille→anchoring_value, last_offered_price→last_offer_price, anchoring_adjustment_id→used_by_adjustment_id - 뷰: rate_history/current_rates→value_history/current_values, delta_permille→value_change - 코드: calc_price_range_index·calc_anchoring_price·evaluate_samples·get_current_value· get_latest_adjusted_value·get_current_anchoring_value·fetch_current_values·get_base_anchoring_value· Adjustment(ORM)·update_last_offer_price, 상수 ANCHORING_VALUE_MIN/MAX·ADJUSTMENT_STEP· PRICE_RANGE_COUNT/INDEX_MAX, 배치 로그 키 bracket=→price_range= - API: negodata protocol 필드 target_anchoring_price→anchoring_price (front 생성 모델·컴포넌트 동반) - 기존 DB 마이그레이션 신설: schedules/anchoring/migrations/20260706_rename_anchoring.sql (멱등 DO 블록 — 테이블·컬럼·뷰·인덱스·PK 제약. 코드 배포와 동시 적용 필요) - postgres-init 01·04, 문서 6종 동기화 - 실배포 전 수정 포함: main.py argparse 화(--dry-run 단독·오타 플래그 기동 전 차단), 박제 정합식 calc_anchoring_price 재사용, clamped 지표가 실제 포화만 집계(경계값 유지 제외) 주의: sessions.anchoring_value(정수‰)와 quotation_settings.anchoring_value(구 float 비율)는 같은 이름·다른 단위 — 구 컬럼은 미변경. 검증: 모듈 20·negodata 50·backend 57 테스트 통과, front tsc·vite build 통과, 로컬 DB 마이그레이션 적용 후 배치 dry-run·상주 기동·양 서버 부팅 확인. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ffa7dda493
commit
a2c299aa14
46 files changed
+775
-628
No files matched your search
@@ -111,10 +111,10 @@ class sessions(MAIN_BASE):
|
||||
qt_round = Column(Integer, nullable=False) # 견적 라운드(스냅샷)
|
||||
qt_type = Column(SmallInteger, nullable=False) # 견적 유형: 1=재협상, 2=재견적, 3=신규협상, 4=신규견적 (QtType)
|
||||
target_price = Column(BigInteger, nullable=False) # 목표가(원)
|
||||
target_anchoring_price = Column(BigInteger, nullable=True) # 앵커링가(원) — 생성 시 박제(negodata), 사후 수정 금지
|
||||
anchor_rate_permille = Column(SmallInteger, nullable=True) # 제안 당시 앵커링 값(‰) 박제 — 사후 수정 금지
|
||||
last_offered_price = Column(BigInteger, nullable=True) # 협력사 마지막 제시가(원) — 가격 입력마다 갱신, 종료 후 불변. 앵커링 표본 판정의 "가격 흔적"
|
||||
anchoring_adjustment_id = Column(BigInteger, nullable=True) # 앵커링 배치 소비 마킹(NULL=미처리 0=제외 >0=조정 id) — schedules/anchoring 전용
|
||||
anchoring_price = Column(BigInteger, nullable=True) # 앵커링가(원) — 생성 시 박제(negodata), 사후 수정 금지
|
||||
anchoring_value = Column(SmallInteger, nullable=True) # 제안 당시 앵커링 값(‰) 박제 — 사후 수정 금지
|
||||
last_offer_price = Column(BigInteger, nullable=True) # 협력사 마지막 제시가(원) — 가격 입력마다 갱신, 종료 후 불변. 앵커링 표본 판정의 "가격 흔적"
|
||||
used_by_adjustment_id = Column(BigInteger, nullable=True) # 앵커링 배치 소비 마킹(NULL=미처리 0=제외 >0=조정 id) — schedules/anchoring 전용
|
||||
status = Column(SmallInteger, nullable=False) # 진행 상태 (SessionStatus 코드)
|
||||
bid_price = Column(BigInteger, nullable=True) # 입찰가(원)
|
||||
bid_at = Column(DateTime(timezone=True), nullable=True) # 입찰 시각
|
||||
@@ -165,7 +165,7 @@ class quotations(MAIN_BASE):
|
||||
|
||||
|
||||
class quotation_settings(MAIN_BASE):
|
||||
# quotation.quotation_settings (견적 설정). 견적 설정 스냅샷 — anchoring_value 는 구(舊) 앵커 산출용으로 채팅 경로에서는 더 이상 사용하지 않음(앵커는 sessions.target_anchoring_price 박제값).
|
||||
# quotation.quotation_settings (견적 설정). 견적 설정 스냅샷 — anchoring_value 는 구(舊) 앵커 산출용으로 채팅 경로에서는 더 이상 사용하지 않음(앵커는 sessions.anchoring_price 박제값).
|
||||
@staticmethod
|
||||
def DBType():
|
||||
return DBType.QUOTATION.value
|
||||
|
||||
@@ -44,7 +44,7 @@ class IChatCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def update_last_offered_price(self, cdb: AsyncSession, session_id, price: int) -> ErrorType:
|
||||
async def update_last_offer_price(self, cdb: AsyncSession, session_id, price: int) -> ErrorType:
|
||||
pass
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ class ChatCRUD(IChatCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def update_last_offered_price(self, cdb: AsyncSession, session_id, price: int) -> ErrorType:
|
||||
async def update_last_offer_price(self, cdb: AsyncSession, session_id, price: int) -> ErrorType:
|
||||
"""협력사 마지막 제시가 갱신 — 가격 입력 턴의 봇 메시지 저장과 같은 트랜잭션에서 호출.
|
||||
|
||||
진행 중엔 매 가격 입력마다 덮어쓰고 종료 후엔 불변. 앵커링 표본 판정에서
|
||||
@@ -147,7 +147,7 @@ class ChatCRUD(IChatCRUD):
|
||||
query = (
|
||||
update(sessions)
|
||||
.where(sessions.session_id == session_id, sessions.status == SessionStatus.IN_PROGRESS.value)
|
||||
.values(last_offered_price=price)
|
||||
.values(last_offer_price=price)
|
||||
)
|
||||
return await DB_SESSION_MNG.add(cdb, query)
|
||||
except Exception as ex:
|
||||
|
||||
@@ -43,7 +43,7 @@ class AgentChatContext:
|
||||
tenant_id: str # X-Tenant-ID = 견적(갑) 회사 company_id
|
||||
rq_type: str = "재협상" # 재협상 | 재견적
|
||||
target_price: int = 0 # 갑 목표 매입가(원)
|
||||
anchor_price: int = 0 # 앵커링가(목표가보다 낮음). 세션 생성 시 박제된 sessions.target_anchoring_price.
|
||||
anchor_price: int = 0 # 앵커링가(목표가보다 낮음). 세션 생성 시 박제된 sessions.anchoring_price.
|
||||
item_price: int = 0 # 기존 공급가(품목 기준가). agent 가격협상_확인 인하율 산출용.
|
||||
# 핸드오프 #4: agent 의 RL 상태(state) 계산 입력.
|
||||
# partner_count 는 견적당 세션 수로 산출(실데이터). 나머지 3개는 우리 스키마에 데이터 소스가 없어
|
||||
|
||||
@@ -369,7 +369,7 @@ class ChatService:
|
||||
# 가격 입력 턴 → 마지막 제시가를 봇 메시지 저장과 같은 트랜잭션으로 갱신.
|
||||
# 앵커링 표본 판정의 "가격 흔적"(가격을 써낸 협상만 집계 — 중간 이탈해도 실패로 측정 가능).
|
||||
if price is not None:
|
||||
funcs.append(lambda s: self.chat_crud.update_last_offered_price(s, sess.session_id, price))
|
||||
funcs.append(lambda s: self.chat_crud.update_last_offer_price(s, sess.session_id, price))
|
||||
new_status = sess.status
|
||||
if turn.chat_end:
|
||||
if turn.outcome == "success":
|
||||
@@ -419,7 +419,7 @@ class ChatService:
|
||||
LOG.w(f"[chat] tenant_id 해석 실패(item.company_id 없음) session_id={sess.session_id} — agent 400 위험")
|
||||
rq_type = "재협상" if sess.qt_type == 1 else "재견적"
|
||||
target_price = int(sess.target_price or 0)
|
||||
# 앵커가: 세션 생성 시 박제된 값(target_anchoring_price)을 그대로 사용 — 협상 중 불변.
|
||||
# 앵커가: 세션 생성 시 박제된 값(anchoring_price)을 그대로 사용 — 협상 중 불변.
|
||||
anchor = await self._resolve_anchor_price(sess, target_price)
|
||||
# 공급사 수: 같은 견적에 속한 세션 수(재협상=1, 재견적=N). agent partner 차원(single/multiple/none) 입력.
|
||||
partner_count = await self._count_partners(sess)
|
||||
@@ -434,7 +434,7 @@ class ChatService:
|
||||
)
|
||||
|
||||
async def _resolve_anchor_price(self, sess, target_price: int) -> int:
|
||||
"""세션에 박제된 앵커가(target_anchoring_price — negodata 가 생성 시 기록)를 그대로 사용.
|
||||
"""세션에 박제된 앵커가(anchoring_price — negodata 가 생성 시 기록)를 그대로 사용.
|
||||
|
||||
박제값 사용이 정상 경로다: 협상 진행 중 앵커링 배치 조정·재기동이 껴도 앵커가 흔들리지 않는다
|
||||
("제안 당시 값" 판정의 전제 — schedules/anchoring/docs/개발용.md §9.2). backend 는 앵커를 계산하지 않는다.
|
||||
@@ -443,8 +443,8 @@ class ChatService:
|
||||
"""
|
||||
if not target_price:
|
||||
return 0
|
||||
if sess.target_anchoring_price is not None:
|
||||
return int(sess.target_anchoring_price)
|
||||
if sess.anchoring_price is not None:
|
||||
return int(sess.anchoring_price)
|
||||
LOG.w(f"[chat] 앵커가 박제 없음 session_id={sess.session_id} — 무할인 폴백(anchor=target), 집계 제외")
|
||||
return target_price
|
||||
|
||||
|
||||
@@ -110,7 +110,7 @@ async def anchor_seed(db_engine):
|
||||
await conn.execute(
|
||||
text("INSERT INTO negotiation.sessions "
|
||||
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
|
||||
" target_price, target_anchoring_price, anchor_rate_permille, status, end_time) "
|
||||
" target_price, anchoring_price, anchoring_value, status, end_time) "
|
||||
"VALUES (:sesid, :qid, :iid, :sup, :qtn, 1, 1, :tp, :ap, :rate, 2, now() + interval '2 hours')"),
|
||||
{"sesid": session_id, "qid": qt_id, "iid": item_id, "sup": supplier_id,
|
||||
"qtn": f"{MARK}{code}", "tp": TARGET, "ap": anchor, "rate": rate},
|
||||
@@ -143,7 +143,7 @@ async def _send(client, token, sid, user_input, user_input_type=None):
|
||||
async def _anchor_columns(db_engine, session_id):
|
||||
async with db_engine.begin() as conn:
|
||||
row = (await conn.execute(text(
|
||||
"SELECT target_anchoring_price, anchor_rate_permille, last_offered_price, bid_price "
|
||||
"SELECT anchoring_price, anchoring_value, last_offer_price, bid_price "
|
||||
"FROM negotiation.sessions WHERE session_id = :sid"), {"sid": session_id})).one()
|
||||
return row
|
||||
|
||||
@@ -158,21 +158,21 @@ async def test_snapshot_consumed_and_last_offer_recorded(client, db_engine, anch
|
||||
r = await _send(client, token, sid, "네, 시작할게요") # → 가격 입력 요청 (아직 가격 흔적 없음)
|
||||
assert r.status_code == 200 and r.json()["message"]["step"] == "기존가격제시"
|
||||
row = await _anchor_columns(db_engine, sid)
|
||||
assert row.last_offered_price is None
|
||||
assert row.last_offer_price is None
|
||||
assert _fake_agent.seen_anchors[-1] == ANCHOR # backend 가 박제값을 그대로 전달
|
||||
|
||||
r = await _send(client, token, sid, "99,500", "price") # 앵커 초과 → 같은 step 반복
|
||||
assert r.json()["message"]["step"] == "기존가격제시"
|
||||
row = await _anchor_columns(db_engine, sid)
|
||||
assert row.last_offered_price == 99_500 # 가격 흔적 기록
|
||||
# 이 시점에 이탈해 일괄마감(NOT_PARTICIPATED)돼도 last_offered_price 로 실패 표본이 된다.
|
||||
assert row.last_offer_price == 99_500 # 가격 흔적 기록
|
||||
# 이 시점에 이탈해 일괄마감(NOT_PARTICIPATED)돼도 last_offer_price 로 실패 표본이 된다.
|
||||
|
||||
r = await _send(client, token, sid, "98,000", "price") # 앵커 이하 → 합의 종료
|
||||
assert r.json()["session_status"] == 3 # DONE
|
||||
row = await _anchor_columns(db_engine, sid)
|
||||
assert row.last_offered_price == 98_000 # 마지막 값으로 갱신
|
||||
assert row.last_offer_price == 98_000 # 마지막 값으로 갱신
|
||||
assert row.bid_price == 98_000
|
||||
assert (row.target_anchoring_price, row.anchor_rate_permille) == (ANCHOR, 10) # 박제 불변
|
||||
assert (row.anchoring_price, row.anchoring_value) == (ANCHOR, 10) # 박제 불변
|
||||
|
||||
|
||||
# ── 폴백 경로: 박제 NULL → 무할인(anchor=target) + 미박제 유지 ──
|
||||
@@ -188,6 +188,6 @@ async def test_null_snapshot_falls_back_to_target(client, db_engine, anchor_seed
|
||||
r = await _send(client, token, sid, "97,000", "price") # 가격 입력(폴백 앵커 이하 → 종료)
|
||||
assert r.json()["session_status"] == 3
|
||||
row = await _anchor_columns(db_engine, sid)
|
||||
assert row.target_anchoring_price is None # backend 는 박제하지 않음(앵커 없음 → 집계 제외)
|
||||
assert row.anchor_rate_permille is None
|
||||
assert row.last_offered_price == 97_000 # 가격 흔적 기록은 정상 동작
|
||||
assert row.anchoring_price is None # backend 는 박제하지 않음(앵커 없음 → 집계 제외)
|
||||
assert row.anchoring_value is None
|
||||
assert row.last_offer_price == 97_000 # 가격 흔적 기록은 정상 동작
|
||||
Reference in new issue
Block a user