[fix] negodata: 협상 학습 화면 정리 — 내부 점수 제거·카드탭 사용 현황 전환·메뉴 개발자 전용
- 관측 사실 기준으로 재구성: 내부 점수 제거, 앵커링 % 표기, 탭 URL 분리 - 카드탭을 성과 지표에서 사용 현황으로 전환, 지표 설명 말풍선·카드 상세 링크 - 사이드바 devOnly + 라우트 가드로 개발자 전용 처리
This commit is contained in:
1 parent
e1e519c20c
commit
f1e924931f
19 files changed
+310
-150
No files matched your search
@@ -14,6 +14,7 @@ _EXPERIENCE_LOGS = table(
|
||||
"experience_logs",
|
||||
column("company_id"), column("session_id"), column("card_id"), column("reward"),
|
||||
column("settled_price"), column("is_invalidated"), column("created_at"),
|
||||
column("turn"),
|
||||
schema="learning",
|
||||
)
|
||||
_ANCHORING_CURRENT = table(
|
||||
@@ -45,7 +46,7 @@ class ILearningCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def card_performance(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
|
||||
async def card_usage(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -76,41 +77,43 @@ class LearningCRUD(ILearningCRUD):
|
||||
return err_type, (0, 0, 0, None)
|
||||
return ErrorType.SUCCESS, tuple(rows[0])
|
||||
|
||||
async def card_performance(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
|
||||
"""카드별 (카드번호, 사용 협상 수, 사용 횟수, 평균 보상, 타결 협상 수).
|
||||
async def card_usage(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
|
||||
"""카드별 사용 현황 — (카드번호, 사용 협상 수, 사용 횟수, 평균 라운드, 마지막 사용).
|
||||
|
||||
보상(reward)은 agent 가 협상 결과로 매긴 성적이라 카드의 실제 효과를 비교하는 축이 된다.
|
||||
협상 결과(타결·가격)는 카드 한 장의 성과로 나눌 수 없어 다루지 않는다 — 한 협상에 여러 장이
|
||||
나가 어느 장의 몫인지 가릴 근거가 없고, 카드 배정도 국면에 따라 정해져 무작위가 아니다.
|
||||
평균 라운드 = 그 카드가 협상의 몇 번째 라운드에 나갔는지(설정한 국면과 실제가 맞는지 대조).
|
||||
"""
|
||||
query = (
|
||||
select(
|
||||
_EXPERIENCE_LOGS.c.card_id,
|
||||
func.count(func.distinct(_EXPERIENCE_LOGS.c.session_id)),
|
||||
func.count(),
|
||||
func.avg(_EXPERIENCE_LOGS.c.reward),
|
||||
func.count(func.distinct(_EXPERIENCE_LOGS.c.session_id))
|
||||
.filter(_EXPERIENCE_LOGS.c.settled_price.isnot(None)),
|
||||
func.avg(_EXPERIENCE_LOGS.c.turn),
|
||||
func.max(_EXPERIENCE_LOGS.c.created_at),
|
||||
)
|
||||
.where(and_(*_valid(company_id), _EXPERIENCE_LOGS.c.card_id.isnot(None)))
|
||||
.group_by(_EXPERIENCE_LOGS.c.card_id)
|
||||
.order_by(desc(func.count()))
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "card_performance failed.", raise_error=False)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "card_usage failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, []
|
||||
return ErrorType.SUCCESS, list(rows or [])
|
||||
|
||||
async def card_names(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
|
||||
"""카드번호 → (번호, 이름, 와일드 여부). 학습 로그의 card_id 가 카드번호 문자열이다.
|
||||
"""카드번호 → (번호, 이름, 와일드 여부, 카드 PK). 학습 로그의 card_id 가 카드번호 문자열이라
|
||||
상세 화면(/cards?detail=<PK>) 으로 보내려면 PK 를 같이 들고 와야 한다.
|
||||
|
||||
UNION 은 실행기가 SELECT 로 인정하지 않아 두 번 나눠 조회한다.
|
||||
"""
|
||||
out = []
|
||||
for model, is_wild in ((nego_cards, 0), (wild_cards, 1)):
|
||||
query = select(model.number, model.name).where(model.deleted == False) # noqa: E712
|
||||
for model, pk, is_wild in ((nego_cards, nego_cards.nego_card_id, 0), (wild_cards, wild_cards.wild_card_id, 1)):
|
||||
query = select(model.number, model.name, pk).where(model.deleted == False) # noqa: E712
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "card_names failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, []
|
||||
out.extend((number, name, is_wild) for number, name in (rows or []))
|
||||
out.extend((number, name, is_wild, card_id) for number, name, card_id in (rows or []))
|
||||
return ErrorType.SUCCESS, out
|
||||
|
||||
async def anchoring_current(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
|
||||
|
||||
@@ -13,33 +13,37 @@ class LearningProtocol(WebPacketProtocol):
|
||||
class LearningKpi(LearningProtocol):
|
||||
learned_sessions: int = 0 # 학습에 반영된 협상 수
|
||||
records: int = 0 # 학습 기록 수(카드 선택 1회 = 1건)
|
||||
settled_sessions: int = 0 # 그중 타결된 협상 수
|
||||
settle_rate: float = 0.0 # 타결 비율
|
||||
used_cards: int = 0 # 한 번이라도 나간 카드 수
|
||||
unused_cards: int = 0 # 아직 한 번도 안 나간 카드 수
|
||||
top3_share: float = 0.0 # 상위 3장이 차지하는 사용 비중 — 쏠림 정도
|
||||
last_learned_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class CardPerformanceRow(LearningProtocol):
|
||||
class CardUsageRow(LearningProtocol):
|
||||
number: str # 카드번호(NGC-001 등)
|
||||
name: Optional[str] = None
|
||||
card_id: Optional[str] = None # 카드 PK — 협상카드 상세(/cards?detail=) 링크용
|
||||
type: str = "nego" # nego | wild
|
||||
used_sessions: int = 0 # 이 카드를 쓴 협상 수
|
||||
used_sessions: int = 0 # 이 카드가 나간 협상 수
|
||||
uses: int = 0 # 총 사용 횟수
|
||||
avg_reward: float = 0.0 # 평균 보상 — agent 가 협상 결과로 매긴 성적
|
||||
settled_sessions: int = 0
|
||||
settle_rate: float = 0.0 # 이 카드를 쓴 협상의 타결 비율
|
||||
share: float = 0.0 # 전체 카드 사용 중 이 카드의 비중
|
||||
avg_turn: float = 0.0 # 평균 몇 번째 라운드에 나갔는지 — 설정한 국면과 대조용
|
||||
last_used_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class AnchoringCell(LearningProtocol):
|
||||
supplier_type: int = 0
|
||||
supplier_type_label: str = "미지정"
|
||||
price_range_index: int = 0 # 목표가 기준 가격대 구간
|
||||
anchoring_value: float = 0.0 # 앵커링 인하폭(‰)
|
||||
price_range_label: str = "" # 그 구간의 실제 금액 범위(화면 표기용)
|
||||
anchoring_value: float = 0.0 # 앵커링 인하폭(‰ — 10 = 1%)
|
||||
last_adjusted_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class AnchoringHistoryRow(LearningProtocol):
|
||||
supplier_type_label: str = "미지정"
|
||||
price_range_index: int = 0
|
||||
price_range_label: str = ""
|
||||
value_before: float = 0.0
|
||||
value_after: float = 0.0
|
||||
sample_count: int = 0 # 조정 판단에 쓴 협상 표본 수
|
||||
@@ -50,7 +54,7 @@ class AnchoringHistoryRow(LearningProtocol):
|
||||
|
||||
class Res_LearningStatus(Res_WebPacketProtocol):
|
||||
kpi: LearningKpi = Field(default_factory=LearningKpi)
|
||||
cards: list[CardPerformanceRow] = []
|
||||
cards: list[CardUsageRow] = []
|
||||
|
||||
|
||||
class Res_AnchoringStatus(Res_WebPacketProtocol):
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import quotations
|
||||
from common.anchoring.constants import UPPER_BOUNDS
|
||||
from common.enums import DBWRType, ErrorType, SupplierType
|
||||
from crud.learning_crud import ILearningCRUD, LearningCRUD
|
||||
from router.v1.learning.protocol import (
|
||||
AnchoringCell,
|
||||
AnchoringHistoryRow,
|
||||
CardPerformanceRow,
|
||||
CardUsageRow,
|
||||
LearningKpi,
|
||||
Res_AnchoringStatus,
|
||||
Res_LearningStatus,
|
||||
@@ -15,6 +18,14 @@ from router.v1.learning.protocol import (
|
||||
|
||||
HISTORY_LIMIT = 50 # 앵커링 조정 이력 표시 개수 — 한 화면에서 훑는 용도
|
||||
|
||||
def _price_range_label(index: int) -> str:
|
||||
"""가격대 인덱스 → 실제 금액 범위. 사다리는 common.anchoring 정본(UPPER_BOUNDS)만 참조한다."""
|
||||
if index < 0 or index >= len(UPPER_BOUNDS):
|
||||
return ""
|
||||
low = UPPER_BOUNDS[index - 1] if index else 0
|
||||
return f"{low:,}~{UPPER_BOUNDS[index]:,}원"
|
||||
|
||||
|
||||
_SUPPLIER_TYPE_LABEL = {
|
||||
SupplierType.NONE.value: "미지정",
|
||||
SupplierType.DISTRIBUTION.value: "유통",
|
||||
@@ -33,41 +44,51 @@ class LearningService:
|
||||
self.crud = crud
|
||||
|
||||
async def get_learning_status(self, company_id: str) -> Res_LearningStatus:
|
||||
"""카드 사용 현황 — 담아둔 카드가 실제로 나가는지, 어느 국면에 나가는지, 쏠리지는 않는지.
|
||||
|
||||
협상 성과(타결·가격)는 카드별로 나누지 않는다 — 한 협상에 여러 장이 나가 어느 장의 몫인지
|
||||
가릴 수 없고, 카드 배정도 무작위가 아니라 국면에 따라 정해지기 때문이다.
|
||||
"""
|
||||
res = Res_LearningStatus()
|
||||
# learning·anchoring 의 company_id 는 agent 가 테넌트 키를 그대로 넣는 문자열 컬럼이다(UUID 타입 아님).
|
||||
# learning 의 company_id 는 agent 가 테넌트 키를 그대로 넣는 문자열 컬럼이다(UUID 타입 아님).
|
||||
cid = str(company_id)
|
||||
|
||||
summary = await self._read(lambda s: self.crud.learning_summary(s, cid), default=(0, 0, 0, None))
|
||||
sessions, records, settled, last_at = summary
|
||||
res.kpi = LearningKpi(
|
||||
learned_sessions=int(sessions or 0),
|
||||
records=int(records or 0),
|
||||
settled_sessions=int(settled or 0),
|
||||
settle_rate=round((settled or 0) / sessions, 3) if sessions else 0.0,
|
||||
last_learned_at=last_at,
|
||||
)
|
||||
|
||||
rows = await self._read(lambda s: self.crud.card_performance(s, cid), default=[])
|
||||
sessions, records, _settled, last_at = await self._read(
|
||||
lambda s: self.crud.learning_summary(s, cid), default=(0, 0, 0, None))
|
||||
rows = await self._read(lambda s: self.crud.card_usage(s, cid), default=[])
|
||||
names = await self._read(lambda s: self.crud.card_names(s), default=[])
|
||||
name_map = {str(number): (name, is_wild) for number, name, is_wild in names if number}
|
||||
for card_id, used_sessions, uses, avg_reward, settled_sessions in rows:
|
||||
name_map = {str(number): (name, is_wild, card_pk) for number, name, is_wild, card_pk in names if number}
|
||||
|
||||
total_uses = sum(int(uses or 0) for _n, _s, uses, _t, _l in rows) or 1
|
||||
for card_id, used_sessions, uses, avg_turn, last_used in rows:
|
||||
number = str(card_id)
|
||||
name, is_wild = name_map.get(number, (None, 0))
|
||||
res.cards.append(CardPerformanceRow(
|
||||
name, is_wild, card_pk = name_map.get(number, (None, 0, None))
|
||||
res.cards.append(CardUsageRow(
|
||||
number=number,
|
||||
name=name,
|
||||
card_id=str(card_pk) if card_pk else None,
|
||||
type="wild" if is_wild else "nego",
|
||||
used_sessions=int(used_sessions or 0),
|
||||
uses=int(uses or 0),
|
||||
avg_reward=round(float(avg_reward), 3) if avg_reward is not None else 0.0,
|
||||
settled_sessions=int(settled_sessions or 0),
|
||||
settle_rate=round((settled_sessions or 0) / used_sessions, 3) if used_sessions else 0.0,
|
||||
share=round(int(uses or 0) / total_uses, 3),
|
||||
avg_turn=round(float(avg_turn), 1) if avg_turn is not None else 0.0,
|
||||
last_used_at=last_used,
|
||||
))
|
||||
|
||||
res.kpi = LearningKpi(
|
||||
learned_sessions=int(sessions or 0),
|
||||
records=int(records or 0),
|
||||
used_cards=len(res.cards),
|
||||
unused_cards=max(0, len(name_map) - len(res.cards)),
|
||||
top3_share=round(sum(c.uses for c in res.cards[:3]) / total_uses, 3),
|
||||
last_learned_at=last_at,
|
||||
)
|
||||
return res
|
||||
|
||||
async def get_anchoring_status(self, company_id: str) -> Res_AnchoringStatus:
|
||||
res = Res_AnchoringStatus()
|
||||
cid = str(company_id)
|
||||
# anchoring 스키마의 company_id 는 UUID 타입 — learning(문자열 테넌트 키)과 다르다.
|
||||
cid = uuid.UUID(str(company_id))
|
||||
|
||||
cells = await self._read(lambda s: self.crud.anchoring_current(s, cid), default=[])
|
||||
for supplier_type, price_range_index, value, adjusted_at in cells:
|
||||
@@ -75,6 +96,7 @@ class LearningService:
|
||||
supplier_type=int(supplier_type or 0),
|
||||
supplier_type_label=_SUPPLIER_TYPE_LABEL.get(int(supplier_type or 0), "미지정"),
|
||||
price_range_index=int(price_range_index or 0),
|
||||
price_range_label=_price_range_label(int(price_range_index or 0)),
|
||||
anchoring_value=float(value) if value is not None else 0.0,
|
||||
last_adjusted_at=adjusted_at,
|
||||
))
|
||||
@@ -84,6 +106,7 @@ class LearningService:
|
||||
res.history.append(AnchoringHistoryRow(
|
||||
supplier_type_label=_SUPPLIER_TYPE_LABEL.get(int(st or 0), "미지정"),
|
||||
price_range_index=int(pri or 0),
|
||||
price_range_label=_price_range_label(int(pri or 0)),
|
||||
value_before=float(before) if before is not None else 0.0,
|
||||
value_after=float(after) if after is not None else 0.0,
|
||||
sample_count=int(sample or 0),
|
||||
|
||||
Reference in new issue
Block a user