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:
민헌andClaude Fable 5 committed 2026-07-06 11:17:01 +09:00
1 parent ffa7dda493
commit a2c299aa14
46 files changed
+775 -628

No files matched your search

@@ -7,16 +7,16 @@
값 조정(격주 배치)·표본 판정은 이식 대상이 아니다(schedules/anchoring 서비스 담당).
상수·계산식을 고칠 일이 생기면 원본 모듈과 반드시 함께 고친다(단독 수정 금지).
"""
from common.anchoring.base_table import get_base_rate_permille, load_base_table
from common.anchoring.base_table import get_base_anchoring_value, load_base_table
from common.anchoring.constants import SAMPLEABLE_SUPPLIER_TYPES
from common.anchoring.reader import fetch_current_rates
from common.anchoring.service import calc_anchor_price, calc_bracket_index
from common.anchoring.reader import fetch_current_values
from common.anchoring.service import calc_anchoring_price, calc_price_range_index
__all__ = [
"SAMPLEABLE_SUPPLIER_TYPES",
"calc_anchor_price",
"calc_bracket_index",
"fetch_current_rates",
"get_base_rate_permille",
"calc_anchoring_price",
"calc_price_range_index",
"fetch_current_values",
"get_base_anchoring_value",
"load_base_table",
]
@@ -7,11 +7,11 @@ DB 에 저장하지 않으며 런타임에 절대 수정하지 않는다. 검증
import json
from pathlib import Path
from common.anchoring.constants import BRACKET_COUNT, UPPER_BOUNDS
from common.anchoring.constants import PRICE_RANGE_COUNT, UPPER_BOUNDS
_RESOURCE = Path(__file__).parent / "resources" / "anchoring_base.json"
_rates: list[int] | None = None # bracket_index → 시작값(‰)
_rates: list[int] | None = None # price_range_index → 시작값(‰)
class BaseTableError(RuntimeError):
@@ -23,8 +23,8 @@ def _validate(rows: list) -> list[int]:
규약: 46행 · idx 1..46 연속 · upper_bound == 사다리(UPPER_BOUNDS) · 값 0.01~0.20.
"""
if not isinstance(rows, list) or len(rows) != BRACKET_COUNT:
raise BaseTableError(f"정적 테이블 행 수 불일치: {len(rows) if isinstance(rows, list) else type(rows)} != {BRACKET_COUNT}")
if not isinstance(rows, list) or len(rows) != PRICE_RANGE_COUNT:
raise BaseTableError(f"정적 테이블 행 수 불일치: {len(rows) if isinstance(rows, list) else type(rows)} != {PRICE_RANGE_COUNT}")
rates: list[int] = []
for i, row in enumerate(rows):
idx = row.get("idx")
@@ -52,8 +52,8 @@ def load_base_table() -> None:
_rates = _validate(rows)
def get_base_rate_permille(bracket_index: int) -> int:
def get_base_anchoring_value(price_range_index: int) -> int:
"""구간 인덱스 → 시작 앵커링 값(‰)."""
if _rates is None:
load_base_table()
return _rates[bracket_index]
return _rates[price_range_index]
@@ -6,8 +6,8 @@
"""
# ── 앵커링 값(정수 천분율 ‰) ──────────────────────────────
ANCHOR_RATE_MIN = 10 # 하한 1%
ANCHOR_RATE_MAX = 200 # 상한 20%
ANCHORING_VALUE_MIN = 10 # 하한 1%
ANCHORING_VALUE_MAX = 200 # 상한 20%
# 시작값은 상수가 아니라 정적 테이블(base_table)에서 로드 — 0.01/10 하드코딩 금지
# ── 가격구간 (자릿수 계단식 사다리 — 폭 = 구간 상한의 10% = 선행 자릿수 밴드) ──
@@ -25,8 +25,8 @@ def _build_upper_bounds() -> tuple:
UPPER_BOUNDS = _build_upper_bounds() # 46개 — 구간 = [이전 upper_bound, upper_bound) 좌폐우개
BRACKET_COUNT = len(UPPER_BOUNDS) # 46
BRACKET_INDEX_MAX = BRACKET_COUNT - 1 # 45
PRICE_RANGE_COUNT = len(UPPER_BOUNDS) # 46
PRICE_RANGE_INDEX_MAX = PRICE_RANGE_COUNT - 1 # 45
# 칸을 구성할 수 있는 협력사 유형 코드 — common.enums.SupplierType 의 유통(1)/제조(2)/총판(3).
# 이 외(NONE=0/NULL)는 칸 해석 불가 → 정적 테이블 시작값 사용(배치 집계에서도 자동 제외).
+18 -18
View File
@@ -2,7 +2,7 @@
원본 reader(schedules/anchoring)는 Redis 캐시를 먼저 보지만, 이식판은 DB 직조회 한 문장만 쓴다
(2026-07-03 단순화 결정 — 조회가 견적 생성 시에만 일어나 캐시가 불필요, Redis 의존 제거).
칸별 최신 조정 rate 는 모듈 소유 뷰 `anchoring.current_rates` 가 제공하고,
칸별 최신 조정 rate 는 모듈 소유 뷰 `anchoring.current_values` 가 제공하고,
조정 이력이 없는 칸은 결과에 없으므로 호출측이 정적 테이블 시작값으로 폴백한다.
견적 생성이 앵커 조회 때문에 실패해서는 안 된다(인수인계.md §1 규칙 6) — anchoring 스키마
@@ -11,22 +11,22 @@
from sqlalchemy import column, select, table
from sqlalchemy.ext.asyncio import AsyncSession
from common.anchoring.constants import ANCHOR_RATE_MAX, ANCHOR_RATE_MIN, SAMPLEABLE_SUPPLIER_TYPES
from common.anchoring.constants import ANCHORING_VALUE_MAX, ANCHORING_VALUE_MIN, SAMPLEABLE_SUPPLIER_TYPES
from common.logger import LOG
# 모듈 소유 DDL(schedules/anchoring/schema.sql)의 조회용 뷰 — negodata 는 ORM 모델 없이 읽기만 한다.
_current_rates = table(
"current_rates",
_current_values = table(
"current_values",
column("company_id"),
column("price_bracket_index"),
column("anchor_rate_permille"),
column("price_range_index"),
column("anchoring_value"),
column("supplier_type"),
schema="anchoring",
)
async def fetch_current_rates(db: AsyncSession, company_ids: list, supplier_type: int) -> dict:
"""칸별 현재 앵커링 값 일괄 조회. {(company_id, bracket_index): rate‰} 반환.
async def fetch_current_values(db: AsyncSession, company_ids: list, supplier_type: int) -> dict:
"""칸별 현재 앵커링 값 일괄 조회. {(company_id, price_range_index): rate‰} 반환.
supplier_type 은 견적 단위로 하나뿐이라 키에 넣지 않는다.
조정 이력이 없는 칸은 결과에 없다(호출측 정적 폴백). 조회 실패 시 빈 dict."""
@@ -34,22 +34,22 @@ async def fetch_current_rates(db: AsyncSession, company_ids: list, supplier_type
return {}
try:
stmt = select(
_current_rates.c.company_id,
_current_rates.c.price_bracket_index,
_current_rates.c.anchor_rate_permille,
_current_values.c.company_id,
_current_values.c.price_range_index,
_current_values.c.anchoring_value,
).where(
_current_rates.c.company_id.in_(company_ids),
_current_rates.c.supplier_type == supplier_type,
_current_values.c.company_id.in_(company_ids),
_current_values.c.supplier_type == supplier_type,
)
rows = (await db.execute(stmt)).all()
except Exception as ex:
LOG.w(f"[앵커링] current_rates 조회 실패 — 전량 정적 테이블 폴백: {ex}")
LOG.w(f"[앵커링] current_values 조회 실패 — 전량 정적 테이블 폴백: {ex}")
return {}
out = {}
for company_id, bracket_index, rate in rows:
if not ANCHOR_RATE_MIN <= rate <= ANCHOR_RATE_MAX: # 범위 밖 값은 오염 방어 — 버리고 정적 폴백
LOG.w(f"[앵커링] rate 범위 밖 — 무시(정적 폴백): company={company_id} bracket={bracket_index} rate={rate}")
for company_id, price_range_index, rate in rows:
if not ANCHORING_VALUE_MIN <= rate <= ANCHORING_VALUE_MAX: # 범위 밖 값은 오염 방어 — 버리고 정적 폴백
LOG.w(f"[앵커링] rate 범위 밖 — 무시(정적 폴백): company={company_id} bracket={price_range_index} rate={rate}")
continue
out[(company_id, bracket_index)] = rate
out[(company_id, price_range_index)] = rate
return out
+5 -5
View File
@@ -5,17 +5,17 @@
"""
from bisect import bisect_right
from common.anchoring.constants import BRACKET_INDEX_MAX, UPPER_BOUNDS
from common.anchoring.constants import PRICE_RANGE_INDEX_MAX, UPPER_BOUNDS
def calc_bracket_index(target_price: int) -> int:
def calc_price_range_index(target_price: int) -> int:
"""목표가 → 가격구간 인덱스(0-기반). 자릿수 계단식 사다리.
좌폐우개 [이전 ub, ub): 가격이 upper_bound 와 정확히 같으면 다음 칸.
1억 이상은 마지막 인덱스로 클램프. 정적 테이블 idx = 반환값 + 1"""
return min(bisect_right(UPPER_BOUNDS, target_price), BRACKET_INDEX_MAX)
return min(bisect_right(UPPER_BOUNDS, target_price), PRICE_RANGE_INDEX_MAX)
def calc_anchor_price(target_price: int, rate_permille: int) -> int:
def calc_anchoring_price(target_price: int, anchoring_value: int) -> int:
"""앵커링가 = 목표가 × (1 − A), 1원 단위 내림. (정수 연산만 — float 곱셈 재도입 금지)"""
return target_price * (1000 - rate_permille) // 1000
return target_price * (1000 - anchoring_value) // 1000
@@ -245,8 +245,8 @@ class sessions(MainTableMixin, MAIN_BASE):
qt_round = Column(Integer, nullable=False) # 견적 라운드 스냅샷
qt_type = Column(SmallInteger, nullable=False) # QuotationType 스냅샷
target_price = Column(BigInteger, nullable=False) # 목표가(원)
target_anchoring_price = Column(BigInteger, nullable=True) # 앵커링가(원) — 생성 시 박제, 이후 수정 금지(앵커링 배치 판정 기준)
anchor_rate_permille = Column(SmallInteger, nullable=True) # 제안 당시 앵커링 값(천분율‰) 박제 — 위와 동일 규칙. 나머지 앵커링 컬럼(last_offered_price 등)은 backend/배치 소유라 매핑 안 함
anchoring_price = Column(BigInteger, nullable=True) # 앵커링가(원) — 생성 시 박제, 이후 수정 금지(앵커링 배치 판정 기준)
anchoring_value = Column(SmallInteger, nullable=True) # 제안 당시 앵커링 값(정수 ‰) 박제 — 위와 동일 규칙. 주의: quotation_settings.anchoring_value(구 float 비율)와 무관. 나머지 앵커링 컬럼(last_offer_price 등)은 backend/배치 소유라 매핑 안 함
status = Column(SmallInteger, nullable=False) # SessionStatus 코드
bid_price = Column(BigInteger, nullable=True) # 입찰가(원)
bid_at = Column(DateTime(timezone=True), nullable=True) # 입찰 시각
+2 -2
View File
@@ -619,13 +619,13 @@ 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, target_anchoring_price). 삭제 제외.
"""[마감 판정] 견적의 모든 세션 → (status, supplier_id, bid_price, name, target_price, anchoring_price). 삭제 제외.
공급사가 지워졌어도 세션 집계엔 포함되도록 outerjoin(이때 name 은 None).
target/anchoring 은 마감 가격게이트 입력(견적당 상품 1개라 세션 공통값)."""
try:
query = (
select(sessions.status, sessions.supplier_id, sessions.bid_price, suppliers.name,
sessions.target_price, sessions.target_anchoring_price)
sessions.target_price, sessions.anchoring_price)
.outerjoin(suppliers, suppliers.supplier_id == sessions.supplier_id)
.where(sessions.quotation_id == qt_id, sessions.deleted == False) # noqa: E712
)
@@ -94,7 +94,7 @@ class SessionData(WebPacketProtocol):
qt_round: int
qt_type: QuotationType
target_price: int
target_anchoring_price: Optional[int] = None # 앵커링가(원). 목표가×(1−앵커링율)
anchoring_price: Optional[int] = None # 앵커링가(원). 목표가×(1000−anchoring_value)//1000
status: SessionStatus
bid_price: Optional[int] = None
bid_at: Optional[datetime] = None
@@ -203,4 +203,4 @@ class Res_TargetBreakdown(Res_WebPacketProtocol):
candidates: list[TargetCandidate] = []
chosen_basis: Optional[str] = None
target_price: int = 0
target_anchoring_price: Optional[int] = None
anchoring_price: Optional[int] = None
@@ -114,7 +114,7 @@ VALUES
INSERT INTO negotiation.sessions
(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type,
target_price, status, bid_price, bid_at, end_time,
reject_reason, reject_price, reject_delivery_type, target_anchoring_price, email_sent_at,
reject_reason, reject_price, reject_delivery_type, anchoring_price, email_sent_at,
created_at, updated_at, deleted)
VALUES
-- ① 낙찰(절감): S1 372,000(낙찰) / S2 389,000 / S3 395,000
+21 -21
View File
@@ -7,10 +7,10 @@ from fastapi import Depends
from common.anchoring import (
SAMPLEABLE_SUPPLIER_TYPES,
calc_anchor_price,
calc_bracket_index,
fetch_current_rates,
get_base_rate_permille,
calc_anchoring_price,
calc_price_range_index,
fetch_current_values,
get_base_anchoring_value,
)
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
@@ -191,7 +191,7 @@ class QuotationService:
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
res.target_anchoring_price = sess.target_anchoring_price
res.anchoring_price = sess.anchoring_price
return res
async def list_quotations(self, company_id, owner, search, status, type_, start_from, start_to, pg: PageParams) -> Res_QuotationList:
@@ -406,8 +406,8 @@ class QuotationService:
rates = rates if _err == ErrorType.SUCCESS else {}
fee = self.INTERNET_AVERAGE_FEE # 인터넷가 차감 수수료율(상수)
margin = rates.get("margin") or 0.0 # 판매가 차감 목표마진율
# 앵커링가는 quotation_settings.anchoring_value 를 더 이상 쓰지 않는다(앵커링 v1.2) —
# 칸(회사×협력사유형×가격구간)별 조정 rate 로 계산한다. 아래 세션 생성부 ②.
# 앵커링가는 quotation_settings.anchoring_value(구 float 비율)를 더 이상 쓰지 않는다(앵커링 v1.2) —
# 칸(회사×협력사유형×가격구간)별 조정 anchoring_value(정수 ‰)로 계산한다. 아래 세션 생성부 ②.
# 선택 협상카드가 있으면 새 버전을 만들어 카드들을 묶고, quotation.version_id 로 연결한다.
# (quotation↔card 는 version → version_nego_cards/version_wild_cards 로 연결.)
@@ -478,32 +478,32 @@ class QuotationService:
res.result.SetResult(ErrorType.QUOTATION_TARGET_PRICE_UNAVAILABLE)
return res
# ② 앵커가 산출 — 칸(items.company_id × quotations.supplier_type × 목표가 구간) rate 조회 후
# ② 앵커가 산출 — 칸(items.company_id × quotations.supplier_type × 목표가 구간) anchoring_value 조회 후
# 정수 연산으로 박제(앵커링 v1.2, 인수인계.md §1.3). 유형 미지정/조정 이력 없음/조회 실패는
# 정적 테이블 시작값 폴백 — rate 조회 때문에 견적 생성이 실패하지 않는다(규칙 6).
# 정적 테이블 시작값 폴백 — 값 조회 때문에 견적 생성이 실패하지 않는다(규칙 6).
_err, item_companies = await DB_SESSION_MNG.execute_lambda(
quotations.DBType(),
DBWRType.DB_READ.value,
lambda s: self.quotation_crud.get_item_companies(s, item_ids),
)
item_companies = item_companies if _err == ErrorType.SUCCESS else {}
rate_map = {}
value_map = {}
if supplier_type in SAMPLEABLE_SUPPLIER_TYPES and item_companies:
rate_map = await DB_SESSION_MNG.execute_lambda(
value_map = await DB_SESSION_MNG.execute_lambda(
quotations.DBType(),
DBWRType.DB_READ.value,
lambda s: fetch_current_rates(s, list(set(item_companies.values())), supplier_type),
lambda s: fetch_current_values(s, list(set(item_companies.values())), supplier_type),
)
session_objs = []
for iid in item_ids:
tp = target_prices[iid]
bracket = calc_bracket_index(tp)
price_range = calc_price_range_index(tp)
company = item_companies.get(iid)
rate = rate_map.get((company, bracket)) if company is not None else None
if rate is None:
rate = get_base_rate_permille(bracket)
ap = calc_anchor_price(tp, rate) # 목표가×(1000−rate)//1000 — float 곱셈 금지(1원 내림 정확성)
value = value_map.get((company, price_range)) if company is not None else None
if value is None:
value = get_base_anchoring_value(price_range)
ap = calc_anchoring_price(tp, value) # 목표가×(1000−value)//1000 — float 곱셈 금지(1원 내림 정확성)
for sid in supplier_ids:
session_objs.append(
sessions(
@@ -515,8 +515,8 @@ class QuotationService:
qt_round=quotation.round,
qt_type=quotation.type,
target_price=tp,
target_anchoring_price=ap, # 박제 — 이후 수정 금지(협상 판정·앵커링 학습 기준값)
anchor_rate_permille=rate,
anchoring_price=ap, # 박제 — 이후 수정 금지(협상 판정·앵커링 학습 기준값)
anchoring_value=value,
status=SessionStatus.CREATED.value,
end_time=quotation.end_time,
)
@@ -648,7 +648,7 @@ class QuotationService:
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)
anchor = next((r.anchoring_price for r in rows if r.anchoring_price is not None), None)
# 재생성 총 이력(체인, 사유 무관). regen_limit = 체인 전체 재생성 총 한도.
regen_used = await self._chain_regen_count(original.number, original.round)
@@ -856,7 +856,7 @@ class QuotationService:
qt_round=r.qt_round,
qt_type=r.qt_type,
target_price=r.target_price,
target_anchoring_price=r.target_anchoring_price,
anchoring_price=r.anchoring_price,
status=r.status,
bid_price=r.bid_price,
bid_at=r.bid_at,
@@ -1,29 +1,29 @@
"""앵커링 v1.2 — 견적 생성 시 칸(회사×협력사유형×가격구간) rate 로 앵커가를 박제하는지 검증.
"""앵커링 v1.2 — 견적 생성 시 칸(회사×협력사유형×가격구간) anchoring_value 로 앵커가를 박제하는지 검증.
이식 명세: schedules/anchoring/docs/인수인계.md §1.
- 앵커가 = 목표가 × (1000 − rate) // 1000 (정수 연산), anchor_rate_permille 동시 박제
- 앵커가 = 목표가 × (1000 − anchoring_value) // 1000 (정수 연산), anchoring_value 동시 박제
- 조정 이력 없음 / 유형 미지정 / anchoring 스키마 미적용 → 정적 테이블 시작값(10‰) 폴백,
견적 생성은 실패하지 않는다(규칙 6)
- 재생성 라운드는 목표가만 상속하고 앵커는 생성 시점 rate 로 재계산(규칙 1 — 상속 폐지)
- 재생성 라운드는 목표가만 상속하고 앵커는 생성 시점 anchoring_value 로 재계산(규칙 1 — 상속 폐지)
"""
import uuid
from datetime import datetime
from sqlalchemy import text
from common.anchoring import calc_bracket_index
from common.anchoring import calc_price_range_index
from common.enums import QuotationType
from crud.quotation_crud import QuotationCRUD
from router.v1.quotation.protocol import Req_CreateQuotation
from services.quotation_service import QuotationService
FUTURE = datetime(2999, 1, 1) # 마감시각 미래 — 생성 직후 크론에 안 잡히게
BASE_RATE = 10 # 정적 테이블 시작값(‰) — anchoring_base.json 전 구간 0.01
BASE_VALUE = 10 # 정적 테이블 시작값(‰) — anchoring_base.json 전 구간 0.01
async def test_create_without_anchoring_schema_falls_back_to_base_rate(db_engine, company_id):
async def test_create_without_anchoring_schema_falls_back_to_base_value(db_engine, company_id):
"""검증: anchoring 스키마가 아예 없는 DB 에서 supplier_type=1(유통) 견적 생성.
기대결과: 조회 실패에도 생성 성공 + 앵커가=목표가×990‰(시작값), rate=10 박제."""
기대결과: 조회 실패에도 생성 성공 + 앵커가=목표가×990‰(시작값), anchoring_value=10 박제."""
await _drop_anchoring(db_engine)
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
@@ -32,10 +32,10 @@ async def test_create_without_anchoring_schema_falls_back_to_base_rate(db_engine
assert res.result.success is True
tp = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE)) # 92,200
rows = await _session_anchor_rows(db_engine, res.qt_id)
assert rows == {item: (tp, tp * (1000 - BASE_RATE) // 1000, BASE_RATE)}
assert rows == {item: (tp, tp * (1000 - BASE_VALUE) // 1000, BASE_VALUE)}
async def test_create_uses_latest_adjusted_rate_per_cell(db_engine, company_id):
async def test_create_uses_latest_adjusted_value_per_cell(db_engine, company_id):
"""검증: 한 상품의 칸에만 조정 이력(50‰)을 넣고 상품 2개(다른 가격구간)로 견적 생성.
기대결과: 이력 칸 상품은 50‰, 무이력 칸 상품은 시작값 10‰ 로 각각 박제(칸 단위 조회)."""
await _reset_anchoring(db_engine)
@@ -43,29 +43,29 @@ async def test_create_uses_latest_adjusted_rate_per_cell(db_engine, company_id):
item_miss = await _seed_item(db_engine, company_id, internet_lowest=5_000) # tp 4,610 — 다른 구간
tp_hit = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE))
tp_miss = int(5_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE))
await _seed_adjustment(db_engine, company_id, supplier_type=1, bracket=calc_bracket_index(tp_hit), rate_after=50)
await _seed_adjustment(db_engine, company_id, supplier_type=1, price_range=calc_price_range_index(tp_hit), value_after=50)
res = await _create(item_ids=[item_hit, item_miss], supplier_type=1)
assert res.result.success is True
rows = await _session_anchor_rows(db_engine, res.qt_id)
assert rows[item_hit] == (tp_hit, tp_hit * 950 // 1000, 50)
assert rows[item_miss] == (tp_miss, tp_miss * 990 // 1000, BASE_RATE)
assert rows[item_miss] == (tp_miss, tp_miss * 990 // 1000, BASE_VALUE)
async def test_supplier_type_unset_uses_base_rate(db_engine, company_id):
async def test_supplier_type_unset_uses_base_value(db_engine, company_id):
"""검증: supplier_type 미지정(None) 견적 생성 — 칸(회사×유형×구간) 구성 불가.
기대결과: 같은 회사·구간에 조정 이력이 있어도 쓰지 않고 시작값 10‰ 박제."""
await _reset_anchoring(db_engine)
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
tp = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE))
await _seed_adjustment(db_engine, company_id, supplier_type=1, bracket=calc_bracket_index(tp), rate_after=50)
await _seed_adjustment(db_engine, company_id, supplier_type=1, price_range=calc_price_range_index(tp), value_after=50)
res = await _create(item_ids=[item], supplier_type=None)
assert res.result.success is True
rows = await _session_anchor_rows(db_engine, res.qt_id)
assert rows == {item: (tp, tp * 990 // 1000, BASE_RATE)}
assert rows == {item: (tp, tp * 990 // 1000, BASE_VALUE)}
async def test_regenerate_inherits_target_but_recomputes_anchor(db_engine, company_id):
@@ -79,28 +79,28 @@ async def test_regenerate_inherits_target_but_recomputes_anchor(db_engine, compa
assert res1.result.success is True
tp = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE))
rows1 = await _session_anchor_rows(db_engine, res1.qt_id)
assert rows1 == {item: (tp, tp * 990 // 1000, BASE_RATE)} # 1라운드는 시작값
assert rows1 == {item: (tp, tp * 990 // 1000, BASE_VALUE)} # 1라운드는 시작값
await _seed_adjustment(db_engine, company_id, supplier_type=1, bracket=calc_bracket_index(tp), rate_after=50)
await _seed_adjustment(db_engine, company_id, supplier_type=1, price_range=calc_price_range_index(tp), value_after=50)
res2 = await _service().regenerate_next_round(res1.qt_id, [supplier])
assert res2.result.success is True
rows2 = await _session_anchor_rows(db_engine, res2.qt_id)
assert rows2 == {item: (tp, tp * 950 // 1000, 50)} # 목표가 상속 + 앵커만 현재 rate
assert rows2 == {item: (tp, tp * 950 // 1000, 50)} # 목표가 상속 + 앵커만 현재 anchoring_value
def test_bracket_index_golden_vectors():
"""검증: 이식된 calc_bracket_index 경계 골든 벡터(자릿수 사다리, 좌폐우개).
배치의 박제 정합 감시는 rate↔앵커가 자기일관만 보므로 브래킷 이식 오류를 못 잡는다 —
def test_price_range_index_golden_vectors():
"""검증: 이식된 calc_price_range_index 경계 골든 벡터(자릿수 사다리, 좌폐우개).
배치의 박제 정합 감시는 값↔앵커가 자기일관만 보므로 브래킷 이식 오류를 못 잡는다 —
이 벡터가 원본(schedules/anchoring)과 어긋나면 이식 오류다(값 변경 금지)."""
assert calc_bracket_index(0) == 0 # 최하단 통일 칸 [0, 1,000)
assert calc_bracket_index(999) == 0
assert calc_bracket_index(1_000) == 1 # 경계 = 다음 칸(좌폐우개)
assert calc_bracket_index(9_999) == 9
assert calc_bracket_index(10_000) == 10 # 자릿수 전환 경계
assert calc_bracket_index(99_999_999) == 45
assert calc_bracket_index(100_000_000) == 45 # 1억 이상은 마지막 칸 클램프
assert calc_bracket_index(10**12) == 45
assert calc_price_range_index(0) == 0 # 최하단 통일 칸 [0, 1,000)
assert calc_price_range_index(999) == 0
assert calc_price_range_index(1_000) == 1 # 경계 = 다음 칸(좌폐우개)
assert calc_price_range_index(9_999) == 9
assert calc_price_range_index(10_000) == 10 # 자릿수 전환 경계
assert calc_price_range_index(99_999_999) == 45
assert calc_price_range_index(100_000_000) == 45 # 1억 이상은 마지막 칸 클램프
assert calc_price_range_index(10**12) == 45
# ===== 헬퍼 =====
@@ -140,16 +140,16 @@ async def _seed_item(engine, company_id, *, internet_lowest):
async def _session_anchor_rows(engine, qt_id):
"""생성된 견적의 item_id -> (target_price, target_anchoring_price, anchor_rate_permille)."""
"""생성된 견적의 item_id -> (target_price, anchoring_price, anchoring_value)."""
async with engine.begin() as conn:
rows = (await conn.execute(
text("SELECT item_id, target_price, target_anchoring_price, anchor_rate_permille "
text("SELECT item_id, target_price, anchoring_price, anchoring_value "
"FROM sessions WHERE quotation_id = :qt"),
{"qt": qt_id},
)).all()
out = {}
for item_id, tp, ap, rate in rows:
assert out.setdefault(item_id, (tp, ap, rate)) == (tp, ap, rate) # 같은 상품 세션끼리 동일 박제
for item_id, tp, ap, value in rows:
assert out.setdefault(item_id, (tp, ap, value)) == (tp, ap, value) # 같은 상품 세션끼리 동일 박제
return out
@@ -162,25 +162,25 @@ async def _drop_anchoring(engine):
# negodata 는 이 스키마를 만들지 않는다(모듈이 소유) — 테스트 재현용으로만 여기 둔다.
_ANCHORING_DDL = (
"CREATE SCHEMA IF NOT EXISTS anchoring",
"""CREATE TABLE IF NOT EXISTS anchoring.rate_adjustments (
id BIGSERIAL PRIMARY KEY,
company_id uuid NOT NULL,
supplier_type SMALLINT NOT NULL,
price_bracket_index INTEGER NOT NULL,
nego_count INTEGER NOT NULL,
success_count INTEGER NOT NULL,
anchor_rate_before SMALLINT NOT NULL,
anchor_rate_after SMALLINT NOT NULL,
consumed_session_ids JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
"""CREATE TABLE IF NOT EXISTS anchoring.adjustments (
adjustment_id BIGSERIAL PRIMARY KEY,
company_id uuid NOT NULL,
supplier_type SMALLINT NOT NULL,
price_range_index INTEGER NOT NULL,
sample_count INTEGER NOT NULL,
success_count INTEGER NOT NULL,
anchoring_value_before SMALLINT NOT NULL,
anchoring_value_after SMALLINT NOT NULL,
used_session_ids JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
)""",
"""CREATE OR REPLACE VIEW anchoring.current_rates AS
SELECT DISTINCT ON (company_id, supplier_type, price_bracket_index)
company_id, supplier_type, price_bracket_index,
anchor_rate_after AS anchor_rate_permille,
id AS last_adjustment_id, created_at AS last_adjusted_at
FROM anchoring.rate_adjustments
ORDER BY company_id, supplier_type, price_bracket_index, id DESC""",
"""CREATE OR REPLACE VIEW anchoring.current_values AS
SELECT DISTINCT ON (company_id, supplier_type, price_range_index)
company_id, supplier_type, price_range_index,
anchoring_value_after AS anchoring_value,
adjustment_id AS last_adjustment_id, created_at AS last_adjusted_at
FROM anchoring.adjustments
ORDER BY company_id, supplier_type, price_range_index, adjustment_id DESC""",
)
@@ -192,15 +192,15 @@ async def _reset_anchoring(engine):
await conn.execute(text(ddl))
async def _seed_adjustment(engine, company_id, *, supplier_type, bracket, rate_after):
async def _seed_adjustment(engine, company_id, *, supplier_type, price_range, value_after):
"""칸에 조정 이력 1행 삽입(배치가 쌓는 행의 최소 재현)."""
async with engine.begin() as conn:
await conn.execute(
text(
"INSERT INTO anchoring.rate_adjustments "
"(company_id, supplier_type, price_bracket_index, nego_count, success_count, "
" anchor_rate_before, anchor_rate_after, consumed_session_ids) "
"VALUES (:cid, :stype, :bracket, 10, 8, 10, :after, '[]'::jsonb)"
"INSERT INTO anchoring.adjustments "
"(company_id, supplier_type, price_range_index, sample_count, success_count, "
" anchoring_value_before, anchoring_value_after, used_session_ids) "
"VALUES (:cid, :stype, :price_range, 10, 8, 10, :after, '[]'::jsonb)"
),
{"cid": uuid.UUID(company_id), "stype": supplier_type, "bracket": bracket, "after": rate_after},
{"cid": uuid.UUID(company_id), "stype": supplier_type, "price_range": price_range, "after": value_after},
)
@@ -324,7 +324,7 @@ export * from './resTargetBreakdownMdPrice';
export * from './resTargetBreakdownMsg';
export * from './resTargetBreakdownPurchase';
export * from './resTargetBreakdownSelling';
export * from './resTargetBreakdownTargetAnchoringPrice';
export * from './resTargetBreakdownAnchoringPrice';
export * from './sessionData';
export * from './sessionDataBidAt';
export * from './sessionDataBidPrice';
@@ -332,7 +332,7 @@ export * from './sessionDataEmailSentAt';
export * from './sessionDataRejectDeliveryType';
export * from './sessionDataRejectPrice';
export * from './sessionDataRejectReason';
export * from './sessionDataTargetAnchoringPrice';
export * from './sessionDataAnchoringPrice';
export * from './sessionStatus';
export * from './supplierData';
export * from './supplierDataCode';
@@ -12,7 +12,7 @@ import type { ResTargetBreakdownPurchase } from './resTargetBreakdownPurchase';
import type { ResTargetBreakdownSelling } from './resTargetBreakdownSelling';
import type { TargetCandidate } from './targetCandidate';
import type { ResTargetBreakdownChosenBasis } from './resTargetBreakdownChosenBasis';
import type { ResTargetBreakdownTargetAnchoringPrice } from './resTargetBreakdownTargetAnchoringPrice';
import type { ResTargetBreakdownAnchoringPrice } from './resTargetBreakdownAnchoringPrice';
export interface ResTargetBreakdown {
result?: ErrorInfo;
@@ -29,5 +29,5 @@ export interface ResTargetBreakdown {
candidates?: TargetCandidate[];
chosen_basis?: ResTargetBreakdownChosenBasis;
target_price?: number;
target_anchoring_price?: ResTargetBreakdownTargetAnchoringPrice;
anchoring_price?: ResTargetBreakdownAnchoringPrice;
}
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
export type ResTargetBreakdownTargetAnchoringPrice = number | null;
export type ResTargetBreakdownAnchoringPrice = number | null;
@@ -5,7 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type { QuotationType } from './quotationType';
import type { SessionDataTargetAnchoringPrice } from './sessionDataTargetAnchoringPrice';
import type { SessionDataAnchoringPrice } from './sessionDataAnchoringPrice';
import type { SessionStatus } from './sessionStatus';
import type { SessionDataBidPrice } from './sessionDataBidPrice';
import type { SessionDataBidAt } from './sessionDataBidAt';
@@ -23,7 +23,7 @@ export interface SessionData {
qt_round: number;
qt_type: QuotationType;
target_price: number;
target_anchoring_price?: SessionDataTargetAnchoringPrice;
anchoring_price?: SessionDataAnchoringPrice;
status: SessionStatus;
bid_price?: SessionDataBidPrice;
bid_at?: SessionDataBidAt;
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
export type SessionDataTargetAnchoringPrice = number | null;
export type SessionDataAnchoringPrice = number | null;
@@ -103,7 +103,7 @@ export function DrawerHeaderCards({
<span className="font-sans font-bold text-foreground">{won(repSession?.target_price)}</span>
)}
</InfoField>
<InfoField label="앵커링가" value={won(repSession?.target_anchoring_price)} valueClassName="font-sans" />
<InfoField label="앵커링가" value={won(repSession?.anchoring_price)} valueClassName="font-sans" />
<InfoField label="견적상태" labelClassName="opacity-90 font-bold mb-1">
<QuotationStatusBadge status={quotation.status} />
</InfoField>
@@ -181,12 +181,12 @@ export function SessionsStatusTab({
<StatusPill tone={sessionStatusTone(sess.status)}>{sessionStatusLabel(sess.status)}</StatusPill>
</TableCell>
<TableCell className="p-3 text-right text-muted-foreground">
{sess.target_anchoring_price > 0 ? (
{sess.anchoring_price > 0 ? (
<>
₩{sess.target_anchoring_price.toLocaleString()}
₩{sess.anchoring_price.toLocaleString()}
{sess.target_price > 0 && (
<span className="ml-0.5 text-[10px] opacity-70">
({((1 - sess.target_anchoring_price / sess.target_price) * 100).toFixed(1)}%)
({((1 - sess.anchoring_price / sess.target_price) * 100).toFixed(1)}%)
</span>
)}
</>
@@ -131,7 +131,7 @@ export function TargetPriceModal({
<Typography as="p" variant="small" className="text-[11px] text-muted-foreground">공급 업체 유형: {supplierTypeLabel}</Typography>
<Typography as="p" variant="small" className="text-[11px] text-muted-foreground">앵커링 값: {bd.anchoring_value}</Typography>
<Typography as="p" variant="small" className="text-[11px] font-bold text-foreground">
앵커링가: {won(bd.target_anchoring_price)} <span className="font-normal text-[10px] text-muted-foreground">= 목표가×(1−{bd.anchoring_value})</span>
앵커링가: {won(bd.anchoring_price)} <span className="font-normal text-[10px] text-muted-foreground">= 목표가×(1−{bd.anchoring_value})</span>
</Typography>
</div>
</>
@@ -218,7 +218,7 @@ export type SessionView = {
item_name: string;
status: number;
target_price: number;
target_anchoring_price: number;
anchoring_price: number;
bid_price: number | null;
bid_at: string;
reject_reason: string | null;
@@ -359,7 +359,7 @@ export function mapServerSessionView(sd: SessionData, partners: Partner[], produ
item_name: product?.name || '-',
status: sd.status,
target_price: sd.target_price ?? 0,
target_anchoring_price: sd.target_anchoring_price ?? 0,
anchoring_price: sd.anchoring_price ?? 0,
bid_price: sd.bid_price ?? null,
bid_at: sd.bid_at ? fmtDateTime(sd.bid_at) : '-',
reject_reason: sd.reject_reason ?? null,