Merge branch 'main' into feature/negodata

Helped-By: Claude Opus 4.8뀨 <noreply@anthropic.com>
This commit is contained in:
minaChoi committed 2026-07-06 16:58:04 +09:00
commit 3176ec4262
55 files changed
+915 -771

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)는 칸 해석 불가 → 정적 테이블 시작값 사용(배치 집계에서도 자동 제외).
+19 -19
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",
# 모듈 소유 DDL(postgres-init/05-anchoring-schema.sql)의 조회용 뷰 — negodata 는 ORM 모델 없이 읽기만 한다.
_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
@@ -246,8 +246,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) # 입찰 시각