[feat] negodata: 협상 학습 메뉴 신설 — 카드별 학습 성적 · 앵커링 현황/조정 이력
agent(협상카드 강화학습)와 anchoring(구간별 자동 조정)이 쌓아온 결과를 볼 수 있는 화면이 없어 DB 를 직접 열어야 확인이 됐다. 두 축은 성격이 달라 한 화면에 섞지 않고 탭으로 나눈다. 백엔드(읽기 전용 — 값의 주인은 agent·anchoring): - crud/learning_crud.py: learning·anchoring 스키마 경량 조회(negodata ORM 미매핑 테이블) - services/learning_service.py + router/v1/learning: /v1/learning/cards · /anchoring 프론트: - 사이드바 '협상 학습'(/learning) 추가, 탭 = 협상카드 | 앵커링 - 협상카드: 학습 협상·기록·타결 비율 요약 + 카드별 사용/타결/평균 점수(0 기준 좌우 막대) - 앵커링: 구간별 현재 인하폭 + 조정 이력(표본·성공률·값 변화) 검증: 로컬 실협상 3건으로 데이터 생성 후 두 탭 실화면 확인, tsc·eslint 통과.
This commit is contained in:
1 parent
37fa65707f
commit
e816bfbba4
28 files changed
+1077
-1
No files matched your search
@@ -0,0 +1,153 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Tuple
|
||||
|
||||
from sqlalchemy import and_, asc, column, desc, func, select, table
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import nego_cards, wild_cards
|
||||
from common.enums import ErrorType
|
||||
|
||||
# 학습(learning)·앵커링(anchoring) 스키마는 agent·anchoring 서비스 소유라 negodata ORM 에 없다.
|
||||
# 조회 전용이므로 필요한 컬럼만 경량 정의한다 — 이 값들의 주인은 negodata 가 아니다(쓰기 금지).
|
||||
_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"),
|
||||
schema="learning",
|
||||
)
|
||||
_ANCHORING_CURRENT = table(
|
||||
"current_values",
|
||||
column("company_id"), column("supplier_type"), column("price_range_index"),
|
||||
column("anchoring_value"), column("last_adjusted_at"),
|
||||
schema="anchoring",
|
||||
)
|
||||
_ANCHORING_HISTORY = table(
|
||||
"value_history",
|
||||
column("company_id"), column("supplier_type"), column("price_range_index"),
|
||||
column("anchoring_value_before"), column("anchoring_value_after"),
|
||||
column("sample_count"), column("success_count"), column("success_rate"), column("created_at"),
|
||||
schema="anchoring",
|
||||
)
|
||||
|
||||
|
||||
def _valid(company_id) -> list:
|
||||
"""유효 학습 기록 — 무효화 표시된 행은 뺀다(협상 취소·재생성 시 agent 가 표시)."""
|
||||
return [
|
||||
_EXPERIENCE_LOGS.c.company_id == company_id,
|
||||
_EXPERIENCE_LOGS.c.is_invalidated == False, # noqa: E712
|
||||
]
|
||||
|
||||
|
||||
class ILearningCRUD(ABC):
|
||||
@abstractmethod
|
||||
async def learning_summary(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, tuple]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def card_performance(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def card_names(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def anchoring_current(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def anchoring_history(self, cdb: AsyncSession, company_id, limit: int) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
|
||||
class LearningCRUD(ILearningCRUD):
|
||||
async def learning_summary(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, tuple]:
|
||||
"""(학습 협상 수, 기록 수, 타결 협상 수, 마지막 학습 시각)."""
|
||||
query = select(
|
||||
func.count(func.distinct(_EXPERIENCE_LOGS.c.session_id)),
|
||||
func.count(),
|
||||
func.count(func.distinct(_EXPERIENCE_LOGS.c.session_id))
|
||||
.filter(_EXPERIENCE_LOGS.c.settled_price.isnot(None)),
|
||||
func.max(_EXPERIENCE_LOGS.c.created_at),
|
||||
).where(and_(*_valid(company_id)))
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "learning_summary failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS or not rows:
|
||||
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]:
|
||||
"""카드별 (카드번호, 사용 협상 수, 사용 횟수, 평균 보상, 타결 협상 수).
|
||||
|
||||
보상(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)),
|
||||
)
|
||||
.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)
|
||||
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 가 카드번호 문자열이다.
|
||||
|
||||
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
|
||||
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 []))
|
||||
return ErrorType.SUCCESS, out
|
||||
|
||||
async def anchoring_current(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
|
||||
"""현재 앵커링 값 — (협력사유형, 가격대 구간, 값, 마지막 조정 시각). 셀 = 유형 × 가격대."""
|
||||
query = (
|
||||
select(
|
||||
_ANCHORING_CURRENT.c.supplier_type,
|
||||
_ANCHORING_CURRENT.c.price_range_index,
|
||||
_ANCHORING_CURRENT.c.anchoring_value,
|
||||
_ANCHORING_CURRENT.c.last_adjusted_at,
|
||||
)
|
||||
.where(_ANCHORING_CURRENT.c.company_id == company_id)
|
||||
.order_by(asc(_ANCHORING_CURRENT.c.supplier_type), asc(_ANCHORING_CURRENT.c.price_range_index))
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "anchoring_current failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, []
|
||||
return ErrorType.SUCCESS, list(rows or [])
|
||||
|
||||
async def anchoring_history(self, cdb: AsyncSession, company_id, limit: int) -> Tuple[ErrorType, list]:
|
||||
"""앵커링 조정 이력(최근순) — 조정마다 표본 수·성공률·값 변화가 남는다."""
|
||||
query = (
|
||||
select(
|
||||
_ANCHORING_HISTORY.c.supplier_type,
|
||||
_ANCHORING_HISTORY.c.price_range_index,
|
||||
_ANCHORING_HISTORY.c.anchoring_value_before,
|
||||
_ANCHORING_HISTORY.c.anchoring_value_after,
|
||||
_ANCHORING_HISTORY.c.sample_count,
|
||||
_ANCHORING_HISTORY.c.success_count,
|
||||
_ANCHORING_HISTORY.c.success_rate,
|
||||
_ANCHORING_HISTORY.c.created_at,
|
||||
)
|
||||
.where(_ANCHORING_HISTORY.c.company_id == company_id)
|
||||
.order_by(desc(_ANCHORING_HISTORY.c.created_at))
|
||||
.limit(limit)
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "anchoring_history failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, []
|
||||
return ErrorType.SUCCESS, list(rows or [])
|
||||
@@ -20,6 +20,7 @@ import router.v1.card.card
|
||||
import router.v1.quotation.quotation
|
||||
import router.v1.quotation_setting.quotation_setting
|
||||
import router.v1.dashboard.dashboard
|
||||
import router.v1.learning.learning
|
||||
import router.v1.statistics.statistics
|
||||
import router.v1.notification.notification
|
||||
import router.v1.renegotiation.renegotiation
|
||||
@@ -79,5 +80,6 @@ app.include_router(router.v1.quotation.quotation.router)
|
||||
app.include_router(router.v1.quotation_setting.quotation_setting.router)
|
||||
app.include_router(router.v1.dashboard.dashboard.router)
|
||||
app.include_router(router.v1.statistics.statistics.router)
|
||||
app.include_router(router.v1.learning.learning.router)
|
||||
app.include_router(router.v1.notification.notification.router)
|
||||
app.include_router(router.v1.renegotiation.renegotiation.router)
|
||||
Whitespace-only changes.
@@ -0,0 +1,19 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from common.models.gmodel import UserInfo
|
||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
|
||||
from services.learning_service import LearningService
|
||||
from .protocol import Res_AnchoringStatus, Res_LearningStatus
|
||||
|
||||
# 협상 학습 현황 — agent(협상카드 학습)·anchoring(앵커링 조정)이 쌓은 결과를 회사 스코프로 읽는다.
|
||||
router = APIRouter(prefix="/v1/learning", tags=["Learning"], responses={404: {"description": "Not found"}})
|
||||
|
||||
|
||||
@router.get(path="/cards", response_model=Res_LearningStatus, summary="협상카드 학습 현황")
|
||||
async def get_learning_status(service: LearningService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
return RemoveNoneResponse(await service.get_learning_status(user_info.company_id))
|
||||
|
||||
|
||||
@router.get(path="/anchoring", response_model=Res_AnchoringStatus, summary="앵커링 현황·조정 이력")
|
||||
async def get_anchoring_status(service: LearningService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
return RemoveNoneResponse(await service.get_anchoring_status(user_info.company_id))
|
||||
@@ -0,0 +1,59 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class LearningProtocol(WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class LearningKpi(LearningProtocol):
|
||||
learned_sessions: int = 0 # 학습에 반영된 협상 수
|
||||
records: int = 0 # 학습 기록 수(카드 선택 1회 = 1건)
|
||||
settled_sessions: int = 0 # 그중 타결된 협상 수
|
||||
settle_rate: float = 0.0 # 타결 비율
|
||||
last_learned_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class CardPerformanceRow(LearningProtocol):
|
||||
number: str # 카드번호(NGC-001 등)
|
||||
name: Optional[str] = None
|
||||
type: str = "nego" # nego | wild
|
||||
used_sessions: int = 0 # 이 카드를 쓴 협상 수
|
||||
uses: int = 0 # 총 사용 횟수
|
||||
avg_reward: float = 0.0 # 평균 보상 — agent 가 협상 결과로 매긴 성적
|
||||
settled_sessions: int = 0
|
||||
settle_rate: float = 0.0 # 이 카드를 쓴 협상의 타결 비율
|
||||
|
||||
|
||||
class AnchoringCell(LearningProtocol):
|
||||
supplier_type: int = 0
|
||||
supplier_type_label: str = "미지정"
|
||||
price_range_index: int = 0 # 목표가 기준 가격대 구간
|
||||
anchoring_value: float = 0.0 # 앵커링 인하폭(‰)
|
||||
last_adjusted_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class AnchoringHistoryRow(LearningProtocol):
|
||||
supplier_type_label: str = "미지정"
|
||||
price_range_index: int = 0
|
||||
value_before: float = 0.0
|
||||
value_after: float = 0.0
|
||||
sample_count: int = 0 # 조정 판단에 쓴 협상 표본 수
|
||||
success_count: int = 0
|
||||
success_rate: float = 0.0
|
||||
created_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class Res_LearningStatus(Res_WebPacketProtocol):
|
||||
kpi: LearningKpi = Field(default_factory=LearningKpi)
|
||||
cards: list[CardPerformanceRow] = []
|
||||
|
||||
|
||||
class Res_AnchoringStatus(Res_WebPacketProtocol):
|
||||
cells: list[AnchoringCell] = []
|
||||
history: list[AnchoringHistoryRow] = []
|
||||
adjusted_count: int = 0
|
||||
@@ -0,0 +1,100 @@
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import quotations
|
||||
from common.enums import DBWRType, ErrorType, SupplierType
|
||||
from crud.learning_crud import ILearningCRUD, LearningCRUD
|
||||
from router.v1.learning.protocol import (
|
||||
AnchoringCell,
|
||||
AnchoringHistoryRow,
|
||||
CardPerformanceRow,
|
||||
LearningKpi,
|
||||
Res_AnchoringStatus,
|
||||
Res_LearningStatus,
|
||||
)
|
||||
|
||||
HISTORY_LIMIT = 50 # 앵커링 조정 이력 표시 개수 — 한 화면에서 훑는 용도
|
||||
|
||||
_SUPPLIER_TYPE_LABEL = {
|
||||
SupplierType.NONE.value: "미지정",
|
||||
SupplierType.DISTRIBUTION.value: "유통",
|
||||
SupplierType.MANUFACTURE.value: "제조",
|
||||
SupplierType.SOLE_AGENCY.value: "총판",
|
||||
}
|
||||
|
||||
|
||||
class LearningService:
|
||||
"""협상 학습 현황 — 협상카드 학습(agent Q-learning)과 앵커링 조정 이력을 읽어 보여준다.
|
||||
|
||||
두 값 모두 negodata 가 만드는 값이 아니라 agent·anchoring 서비스가 쌓은 결과다(읽기 전용).
|
||||
"""
|
||||
|
||||
def __init__(self, crud: ILearningCRUD = Depends(LearningCRUD)):
|
||||
self.crud = crud
|
||||
|
||||
async def get_learning_status(self, company_id: str) -> Res_LearningStatus:
|
||||
res = Res_LearningStatus()
|
||||
# learning·anchoring 의 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=[])
|
||||
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:
|
||||
number = str(card_id)
|
||||
name, is_wild = name_map.get(number, (None, 0))
|
||||
res.cards.append(CardPerformanceRow(
|
||||
number=number,
|
||||
name=name,
|
||||
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,
|
||||
))
|
||||
return res
|
||||
|
||||
async def get_anchoring_status(self, company_id: str) -> Res_AnchoringStatus:
|
||||
res = Res_AnchoringStatus()
|
||||
cid = 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:
|
||||
res.cells.append(AnchoringCell(
|
||||
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),
|
||||
anchoring_value=float(value) if value is not None else 0.0,
|
||||
last_adjusted_at=adjusted_at,
|
||||
))
|
||||
|
||||
history = await self._read(lambda s: self.crud.anchoring_history(s, cid, HISTORY_LIMIT), default=[])
|
||||
for st, pri, before, after, sample, success, rate, created_at in history:
|
||||
res.history.append(AnchoringHistoryRow(
|
||||
supplier_type_label=_SUPPLIER_TYPE_LABEL.get(int(st or 0), "미지정"),
|
||||
price_range_index=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),
|
||||
success_count=int(success or 0),
|
||||
success_rate=round(float(rate), 3) if rate is not None else 0.0,
|
||||
created_at=created_at,
|
||||
))
|
||||
res.adjusted_count = len(res.history)
|
||||
return res
|
||||
|
||||
async def _read(self, fn, default):
|
||||
"""crud 한 건 실행 — 실패해도 화면은 떠야 하므로 기본값으로 떨어진다."""
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(quotations.DBType(), DBWRType.DB_READ.value, fn)
|
||||
return rows if err == ErrorType.SUCCESS else default
|
||||
Reference in new issue
Block a user