Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94c7a6568d | ||
|
|
51b3820cc9 | ||
|
|
d4acdd0ac5 | ||
|
|
b368a19f79 | ||
|
|
7b7f606ace | ||
|
|
f4e59a2184 | ||
|
|
18020a9e07 | ||
|
|
235863aea9 | ||
|
|
5519c6e73b | ||
|
|
c2760c804f | ||
|
|
98df5e2608 | ||
|
|
a2731d97f5 | ||
|
|
15f3d10eb6 | ||
|
|
d21e7c10b0 | ||
|
|
9ac8fe6363 | ||
|
|
c62b66e35b | ||
|
|
c32ee300e6 |
No files matched your search
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"rows": 25,
|
||||||
|
"episodes": 4,
|
||||||
|
"skipped": {
|
||||||
|
"종료행/카드턴 없음(미완결 세션)": 8
|
||||||
|
},
|
||||||
|
"min_episodes": 1,
|
||||||
|
"deployed": false,
|
||||||
|
"ope_candidate": 0.9029104414200676,
|
||||||
|
"ope_candidate_ess": 1.0,
|
||||||
|
"ope_current": 0.9029104414200676,
|
||||||
|
"ope_current_ess": 1.0,
|
||||||
|
"result": "gate_failed"
|
||||||
|
}
|
||||||
@@ -55,6 +55,7 @@ class QTableVersion(_DBTypeMixin, MAIN_BASE):
|
|||||||
discount_factor = Column(Numeric(6, 4), nullable=False, default=0.95)
|
discount_factor = Column(Numeric(6, 4), nullable=False, default=0.95)
|
||||||
epochs = Column(Integer, nullable=False, default=0)
|
epochs = Column(Integer, nullable=False, default=0)
|
||||||
is_active = Column(Boolean, nullable=False, default=False)
|
is_active = Column(Boolean, nullable=False, default=False)
|
||||||
|
action_cards = Column(JSONB, nullable=True) # 카탈로그 스냅샷: 카드번호 목록(index=action_id). 카드번호 기반 마이그레이션용.
|
||||||
created_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
created_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||||
deleted = Column(Boolean, nullable=False, default=False)
|
deleted = Column(Boolean, nullable=False, default=False)
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,203 @@
|
|||||||
|
# 완전 자율 협상 에이전트 — 처음 대비 변경 정리
|
||||||
|
|
||||||
|
> 기준: 협상카드 + 룰 엔진 시절(처음) → 완전 자율 에이전트 v3.2 + LLM 멘트 (2026-07-10 현재)
|
||||||
|
> 롤백: `docker-compose.yml` 의 `AUTONOMY_MODE=0` 하나로 룰 엔진 즉시 복귀 (재빌드 불필요)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 한눈에 보기 — 무엇이 바뀌었나
|
||||||
|
|
||||||
|
| 영역 | 처음 (룰 + 카드) | 지금 (자율 에이전트) |
|
||||||
|
|---|---|---|
|
||||||
|
| **협상 판정** | 하드코딩 룰 (앵커 이하 타결 / 와일드카드 존 / 3라운드 결렬) | RL 정책이 매 턴 행동을 직접 선택 |
|
||||||
|
| **발화 선택** | DB 협상카드(NGC-001~011)를 UCB/Q-table 로 선택 | 카드 없음 — 행동 30개 중 신경망이 선택 |
|
||||||
|
| **역제안 금액** | 카드에 박힌 고정값 | 앵커~목표가 6단 사다리에서 정책이 선택 |
|
||||||
|
| **와일드카드** | 사람이 등록한 카드(WC-01~05) 발동 | 최종제안·역제시 타이밍을 정책+봉투가 자율 수행 |
|
||||||
|
| **멘트** | 고정 템플릿 | Gemini LLM 생성 + 할루시네이션 가드 (실패 시 템플릿 폴백) |
|
||||||
|
| **입력 상태** | 가격 스냅샷 9차원 | 21차원 (마감·협력사 이력·인터넷최저가·에피소드 기억 추가) |
|
||||||
|
| **학습** | Q-table 온라인 갱신 | 시뮬레이터 DQN 학습 → 프로브 게이트 → npz 번들 배포 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 의사결정 — 행동 공간 30개
|
||||||
|
|
||||||
|
```
|
||||||
|
ACCEPT 수락 (협상완료, 제시가 타결)
|
||||||
|
WALK 결렬 의사 → 최종제안 1회 보장 후 종료
|
||||||
|
COUNTER 역제안: 금액 위치 6단 {-5%, 0, 25, 50, 75, 100% of (목표가-앵커가)} × 화법 4종
|
||||||
|
PRESS 압박(설득): 화법 4종
|
||||||
|
```
|
||||||
|
|
||||||
|
행동의 실체는 `Action(kind, counter_q, strategy)` — **(무엇을, 얼마에, 어떤 말투로)** 좌표 3개짜리 데이터다
|
||||||
|
(`policies/autonomy_actions.py`, DB 아님). 에이전트는 매 턴 30개 중 조합 1개를 고르고,
|
||||||
|
원화 환산(앵커 + q×스팬)과 문장(LLM)은 선택 이후의 실행 단계.
|
||||||
|
|
||||||
|
역제안 사다리 6단 (실스케일 앵커 418,966/목표 423,198 기준):
|
||||||
|
q=−0.05→418,754 / 0→418,966(앵커) / 0.25→420,024 / 0.5→421,082 / 0.75→422,140 / 1.0→423,198(목표가).
|
||||||
|
비율(q)이라 견적 스케일과 무관하게 같은 행동 공간이 재사용된다.
|
||||||
|
|
||||||
|
화법 4종은 기존 카드 전략 분류를 그대로 승계: **경쟁 압박 / 수용 공감 / 기준 고수 / 협력 파트너**.
|
||||||
|
톤 선택도 학습 결과 — 라이브에서 초반 경쟁(1)→중반 수용(2)→교착 협력(4)으로 국면별 전환 관측.
|
||||||
|
|
||||||
|
설계 출처: 화법 4종·금액 범위(앵커~목표가)는 제품 승계, 수락·결렬 포함은 완전 자율 정의의 필연,
|
||||||
|
**격자 6단만 설계 재량**(`COUNTER_GRID` 수정+재학습으로 변경 가능). 알려진 한계: 부를 수 있는
|
||||||
|
금액이 격자 6지점뿐 — 연속 금액 미세조정은 불가(필요 시 격자 확장이 현실적).
|
||||||
|
|
||||||
|
- 모델: action-as-feature DQN (ScoreNet MLP — 상태 21 + 행동특징 9 → 점수 1개)
|
||||||
|
- 서빙: **numpy 전용** (`autonomy_serving.npz`) — 컨테이너에 PyTorch 불필요
|
||||||
|
- 현재 서빙본: **v3.5** (백업 `autonomy_v35.npz` / 반려본 v3.4 / 이전 v3.2)
|
||||||
|
|
||||||
|
## 3. 입력 상태 — 9차원 → 21차원
|
||||||
|
|
||||||
|
"완전한 에이전트에는 다 들어가야 한다" 요구로 확장:
|
||||||
|
|
||||||
|
| 그룹 | 차원 | 내용 | 출처 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 기본 | 9 | 매출액·유통코드·협력사수·수락률·제시가·앵커가·목표가·라운드 등 | 기존 스냅샷 |
|
||||||
|
| 테넌트 | 5 | 보상 설정 특징 | reward config |
|
||||||
|
| **에피소드 기억** | 2 | 직전 역제안 유무·위치 | ctx `autonomy_last` |
|
||||||
|
| **마감** | 1 | 마감 잔여율 | quotations start/end_time |
|
||||||
|
| **협력사 이력** | 3 | 과거 협상 횟수·성공률·평균 타결비율 | experience_logs ⨝ sessions |
|
||||||
|
| **시장가** | 1 | 인터넷 최저가 갭 | items.internet_lowest_price |
|
||||||
|
|
||||||
|
- 소스가 없으면 중립값(0.5/0) — 학습 시뮬의 '미상' 표현과 동일
|
||||||
|
- 상대 **발화 내용 파싱은 보류** (사용자 결정 — 프론트 입력 UI 변경 필요)
|
||||||
|
|
||||||
|
## 4. 행동 봉투 — 실전 테스트에서 잡은 결함의 구조적 방지
|
||||||
|
|
||||||
|
룰과 다름: **룰은 결과를 정하고, 봉투는 행동만 금지**한다. 나머지(타이밍·속도·금액)는 전부 정책 학습.
|
||||||
|
|
||||||
|
| # | 봉투 | 막는 결함 (실제 발생 사례) | 성격 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| ① | 목표가 초과 제시가는 **수락 불가** | v3.1 이 보상 구멍을 착취해 목표가+14% 매입 | 안전 (영구) |
|
||||||
|
| ② | 직전 역제안보다 **낮은 금액 재제시 금지** (단조 양보) | 423,198 → 420,024 제안 철회 사건 | 안전 (영구) |
|
||||||
|
| ③ | 역제시는 **설득 ≥2회 후 해금** (`AUTONOMY_MIN_PRESS`) | 첫 턴부터 역제시 — 옛 의미론(일반카드=설득, 와일드카드만 역제시) 복원 | 예절 (해제 후보) |
|
||||||
|
| ④ | 목표가 0.5% 이내 **마무리 국면에선 압박 금지** | 802원 차이에 "재검토 부탁" 반복하던 푼돈 흥정 | 예절 (해제 후보) |
|
||||||
|
| ⑤ | **첫 역제안은 앵커가 이하만** (q ≤ 0) | 사다리 꼭대기 근처(422,140)에서 개시해 올라갈 계단이 없던 문제 | 예절 (해제 후보) |
|
||||||
|
| ⑥ | 같은 금액 반복·결렬 의사 → **자율_최종제안 1회 보장, 금액은 목표가** | 확인 없이 결렬 / 직전 금액을 "최종"으로 반복해 승인 여지를 남긴 채 종료하던 문제 | 안전 (영구) |
|
||||||
|
| ⑦ | **결렬(walk)도 해금 전 금지** — 설득 ≥2회 전에는 설득만 가능 | 설득 0회에 walk 선택 시 최종제안 보장(⑥)과 결합해 "첫 턴 목표가 통보"가 됨 (v3.4 라이브 결함) | 예절 (해제 후보) |
|
||||||
|
|
||||||
|
- 구현: 서빙 `policy/autonomy_store.py` 후보 마스크 + 학습 `tools/train_full_autonomy.py` `available_actions` **양쪽 동일**
|
||||||
|
- 예절 봉투(③④⑤)는 실로그가 쌓이면 `AUTONOMY_MIN_PRESS=0` 등으로 해제 실험 가능
|
||||||
|
|
||||||
|
## 5. 멘트 — 템플릿 → LLM + 가드레일
|
||||||
|
|
||||||
|
**역할 분리(안전 설계):** 무엇을 말할지(금액/전략/수락/결렬)는 RL 이 결정, LLM 은 **표현만** 담당.
|
||||||
|
|
||||||
|
```
|
||||||
|
설정: agent/config/config.local.toml [OpenAIConfig]
|
||||||
|
모델: gemini-2.5-flash-lite (OpenAI 호환 base_url)
|
||||||
|
· 2.5-flash → thinking 지연으로 백엔드 10초 한도 초과 ("협상 응답 지연" 토스트 원인)
|
||||||
|
· 2.0-flash → 은퇴(404)
|
||||||
|
시간: LLM_TIMEOUT_S=6 초과 시 템플릿 폴백 (검증 최대 응답 2.9초)
|
||||||
|
끄기: AUTONOMY_LLM=0
|
||||||
|
```
|
||||||
|
|
||||||
|
**할루시네이션 가드 (하나라도 걸리면 템플릿 폴백, 협상은 계속):**
|
||||||
|
|
||||||
|
| 가드 | 내용 |
|
||||||
|
|---|---|
|
||||||
|
| 숫자 화이트리스트 | 프롬프트로 준 금액(제시가·제안가·직전제안가·양보폭) 외 숫자 = 즉시 폐기 |
|
||||||
|
| **목표가 비공개** | 압박 프롬프트에 목표가 미포함 + 화이트리스트에서도 제외 — 노출 사고 재발 방지 |
|
||||||
|
| 금지어 | 보장/물량/독점/최저가/시장가/%/계약기간/법적 등 승인 안 된 전술·커밋 |
|
||||||
|
| 문장 완결 | thinking 토큰 소진으로 잘린 문장 폐기 (max_tokens 2048) |
|
||||||
|
| 제안가 포함 | 역제안·최종제안 멘트에 제안 금액 필수 |
|
||||||
|
|
||||||
|
**추가 기능:**
|
||||||
|
- **인터넷 최저가 인용** (구 NGC-008 자율판): 수집돼 있고 제시가 > 최저가일 때만 근거 인용 허용 — 그 턴에만 '최저가' 금지어 해제, 수치는 화이트리스트 검증
|
||||||
|
- **대화 기억**: 직전 제안 거절 사실·양보폭을 멘트에 반영("직전 제안에서 5원 상향한…") + 직전 멘트와 같은 문장구조 반복 금지 — "멘트가 다 똑같다" 해결. temperature 0.9
|
||||||
|
|
||||||
|
## 6. 학습 시뮬레이터 버전 이력 — 실패 2건 포함
|
||||||
|
|
||||||
|
| 버전 | 변경 | 결과 |
|
||||||
|
|---|---|---|
|
||||||
|
| v1 | 최초 학습 | 한 방 큰 컷 + 같은 숫자 반복 → "이게 협상이야??" |
|
||||||
|
| v2 | 에피소드 기억·컷 특징·협력사 반복 짜증/이탈 | 개선되나 지형 불일치 잔존 |
|
||||||
|
| v3 | 상태 21차원 확장 | — |
|
||||||
|
| v3.1 | **지형 정합**: 앵커율 0.8~6% 샘플링 (실제 ~1% vs 시뮬 20%) | ⚠️ 보상 구멍 착취 — 목표가+14% 매입 학습 → 봉투 ① 신설 |
|
||||||
|
| **v3.2** | 컷 반발·반복 짜증·**양보 상호성**(우리가 올리면 상대도 내림)·floor ≤ 첫제시가×0.98 | ✅ **현재 서빙본** (목표가 초과 타결 0/30) |
|
||||||
|
| v3.3 | 단조·상호성 반영 재학습 | ❌ "무조건 목표가 즉시 지르기"로 퇴화 → **프로브 게이트 반려** (`full_autonomy.pt` 만 보관, 미서빙) |
|
||||||
|
| v3.4 | 봉투 ①~⑤ 정합 + **보상 수정**(목표가 초과 타결 = 결렬 취급) 재학습 | ❌ **반려** — 초기 게이트(실스케일 단일 지형) 통과 후 라이브에서 퇴화 발견: 소액 지형에서 첫 턴 walk→목표가 통보 / walk 잠금 후엔 압박 12연발·최종제안 생략·화법 단조(전부 전략3). 게이트를 2개 지형으로 확장해 재판정 → v3.2 우위 확인, v3.2 복원 (`autonomy_v34_rejected.npz` 보관) |
|
||||||
|
| **v3.5** | v3.4 + **관측성 마스크**: 마감 40% 미관측(0.5 고정)·15% 완전 미상 에피소드 — 서빙 중립값 상태를 시뮬 분포에 혼입 (v3.4 퇴화 원인 해소) | ✅ **현재 서빙본** — 게이트 78/78, 사다리 3단 사용, 협조 케이스 목표가 대비 -2,116원 타결. 게이트가 이 과정에서 **철회 실버그** 발견(아래) |
|
||||||
|
|
||||||
|
> **교훈 1 — 보상 = 유일한 스펙**: 룰을 제거하면 보상 함수의 구멍이 곧 행동이 된다 (v3.1).
|
||||||
|
> **교훈 2 — 프로브 게이트**: 재학습은 퇴화할 수 있다. 배포 전 반드시 실스케일 제시가별 행동표(`tools/probe_serving_dqn.py`)로 비교 검증 (v3.3).
|
||||||
|
> **교훈 3 — 지형 일반화**: 한 지형의 게이트 통과가 다른 지형을 보증하지 않는다 (v3.4 — 실스케일 통과, 소액 퇴화).
|
||||||
|
> **교훈 4 — 시뮬은 관측까지 닮아야 한다**: 세계뿐 아니라 '무엇을 모르는지'도 서빙과 같아야 한다. 마감·이력 미상(중립값) 상태가 시뮬에 없으면 그 상태가 분포 밖이 된다 (v3.4 원인 → v3.5 해소).
|
||||||
|
|
||||||
|
**철회 실버그 (게이트가 발견, 2026-07-10 수정):** 단조 봉투의 기준 `autonomy_last`가 '마지막 행동'이라 counter→**press**→counter 순서에서 설득이 역제안 기억을 덮어써 봉투가 뚫렸다(9,975 제안 후 9,900 재제안). 역제안 기억을 `autonomy_last_counter`로 별도 보존하도록 수정 — 시뮬(역제안만 추적)과도 일치. v3.2는 이 패턴을 쓰지 않아 드러나지 않았을 뿐 프로덕션에 실존하던 구멍.
|
||||||
|
|
||||||
|
## 7. 현재 협상 흐름 (검증 완료)
|
||||||
|
|
||||||
|
```
|
||||||
|
협력사 제시
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
설득(압박) ≥2회 ── 인터넷최저가 근거 인용 가능, 목표가 절대 비공개
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
역제안 해금 ── 첫 제안은 앵커가 이하로 개시 (봉투⑤)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
단조 상향 사다리 ── 후퇴 금지(봉투②), 양보폭·속도는 정책이 결정
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
목표가 0.5% 이내 ── 압박 중단, 클로징만 (봉투④)
|
||||||
|
│
|
||||||
|
├─ 제시가 ≤ 목표가 → 수락 → 협상완료
|
||||||
|
├─ 같은 금액 반복 / 결렬 의사 → 자율_최종제안 1회, 금액=목표가 (봉투⑥)
|
||||||
|
│ ├─ 예 → 협상완료 └─ 아니오 → 협상실패
|
||||||
|
└─ 12턴 초과(엔지니어링 캡) → 최종제안(목표가) 1회 거쳐 종료 — 캡도 봉투⑥을 우회하지 않음
|
||||||
|
```
|
||||||
|
|
||||||
|
## 8. 운영 스위치 & 파이프라인
|
||||||
|
|
||||||
|
| 스위치 (docker-compose agent env) | 값 | 의미 |
|
||||||
|
|---|---|---|
|
||||||
|
| `AUTONOMY_MODE` | 1 | 자율 모드 (0 = 룰 엔진 복귀) |
|
||||||
|
| `DQN_SERVING` | 1 | 카드 선택 DQN (0 = UCB Q-table) |
|
||||||
|
| `AUTONOMY_LLM` | 1(기본) | LLM 멘트 (0 = 템플릿만) |
|
||||||
|
| `AUTONOMY_MIN_PRESS` | 2(기본) | 역제시 해금에 필요한 설득 횟수 |
|
||||||
|
| `LLM_TIMEOUT_S` | 6(기본) | LLM 시간 상한, 초과 시 템플릿 폴백 |
|
||||||
|
|
||||||
|
**학습→배포 파이프라인:**
|
||||||
|
```
|
||||||
|
tools/train_full_autonomy (시뮬 15k ep, 룰 베이스라인 비교)
|
||||||
|
→ tools/export_autonomy_serving (artifacts/autonomy_serving.npz, .prev 자동 백업)
|
||||||
|
→ tools/probe_serving_dqn (실스케일 행동표 — 눈으로 보는 진단)
|
||||||
|
→ tools/test_autonomy_defects (결함 회귀 게이트 — 지형 2종×시나리오 3종 + 단위·멘트가드 검사,
|
||||||
|
자동 합격/불합격. 단, v3.4 사례처럼 게이트 통과 ≠ 품질 보증:
|
||||||
|
궤적 자체도 눈으로 비교할 것)
|
||||||
|
→ docker compose build agent (npz 는 이미지에 베이크)
|
||||||
|
```
|
||||||
|
|
||||||
|
**로깅:** 자율 행동도 experience_logs 에 기록 (card_id = `AUT|종류|위치|전략`, 진행 row + 종결 row). 카드 재학습(`retrain_from_logs`)은 AUT 세션 자동 제외.
|
||||||
|
|
||||||
|
## 9. 변경 파일 지도
|
||||||
|
|
||||||
|
| 파일 | 역할 |
|
||||||
|
|---|---|
|
||||||
|
| `negotiation/policy/autonomy_store.py` | **신규** — 자율 정책 numpy 서빙 + 봉투 ①~⑤ 마스크 |
|
||||||
|
| `negotiation/policies/autonomy_actions.py` | **신규** — 행동 30개·특징 인코딩 (학습/서빙 공유) |
|
||||||
|
| `negotiation/chat/service/ment_generator.py` | **신규** — LLM 멘트 생성 + 가드레일 |
|
||||||
|
| `negotiation/chat/service/chat_engine.py` | 자율 스텝(자율_역제안/최종제안/압박_1~4) + `_autonomy_next` 봉투⑥ |
|
||||||
|
| `services/chat_service.py` | decider 주입·행동 로깅·대화기억 ctx 관리 |
|
||||||
|
| `negotiation/chat/infra/repository/nego_context_crud.py` | 인터넷최저가·견적기간·협력사이력 조회 |
|
||||||
|
| `negotiation/chat/service/negotiation_context_loader.py` | 확장 컨텍스트 로드 (company_id) |
|
||||||
|
| `tools/train_full_autonomy.py` | **신규** — 시뮬레이터(현실화 협력사 모델) + DQN 학습 |
|
||||||
|
| `tools/export_autonomy_serving.py` / `probe_serving_dqn.py` | **신규** — 번들 내보내기 / 프로브 게이트 |
|
||||||
|
| `tools/test_autonomy_defects.py` | **신규** — 결함 회귀 게이트: 실전에서 발견된 결함 41항목을 시나리오·단위·멘트가드 검사로 자동 재생 (서빙 실물 코드 구동, DB/LLM 불필요) |
|
||||||
|
| `config/config.local.toml` | Gemini 접속 정보 (gitignore, 이미지에 베이크) |
|
||||||
|
| `docker-compose.yml` | `AUTONOMY_MODE` / `DQN_SERVING` 플래그 |
|
||||||
|
|
||||||
|
## 10. 남은 일
|
||||||
|
|
||||||
|
- [x] 결함 회귀 게이트 구축 — `test_autonomy_defects.py` 41항목, v3.2 전항목 통과 확인 (2026-07-10)
|
||||||
|
- [x] 보상 수정 — 목표가 초과 타결은 학습 보상에서 결렬 취급 (v3.1 구멍을 유인 수준에서 차단, 봉투 ①과 이중 방어)
|
||||||
|
- [ ] ⚠️ **Gemini API 키 재발급** — 채팅에 노출된 키, 테스트 종료 후 반드시 교체 (config.local.toml + 이미지 리빌드)
|
||||||
|
- [x] 봉투 정합 재학습 — v3.4 반려(소액 지형 퇴화) → 원인 규명(관측성 불일치) → **v3.5 관측성 마스크로 해소, 배포 완료** (2026-07-10)
|
||||||
|
- [x] 철회 실버그 수정 — counter→press→counter 에서 단조 봉투 뚫림 → `autonomy_last_counter` 별도 보존
|
||||||
|
- [x] 턴캡 최종제안 보장 — 캡 종료도 "끝내기 전 한 번 더"를 거침
|
||||||
|
- [ ] 상대 발화 LLM 파싱 (보류 중 — 프론트 입력 UI 변경 필요)
|
||||||
|
- [ ] 실로그 축적 후: 예절 봉투(③④⑤) 해제 실험 → LLM 협력사 셀프플레이 (집컴 GPU 단계)
|
||||||
|
- [ ] (소소) negodata 프론트 "목표 마진율 1000%" 표시 버그 후보
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
ID,??MD,?????,?????,??? ???,????,???,???,????,????,???,???,1???,1? ?? ???,1? ????,????,2???,2? ?? ???,2? ????,????,3???,3? ?? ???,3? ????,????,4???,,,,,
|
||||||
|
1,,???,,,AT2025042400050,?????,"163,600",??,None (??),"8,180","8,099",,,,,,,,,,,,,,,,,,
|
||||||
|
2,,???,,,AT2025042200057,????,"350,000",??,Single (??),"35,000","33,600",35000,0,?? ?? ?? ??,o,34900,0.00286533,??? ?? ?? ??,o,33700,0.038575668,??? ?? ?? ??,x,33600,,,,,
|
||||||
|
3,,???,,,AT2025042300003,TV???,"6,790,000",??,Multiple (??),"48,500","46,560",50000,0,?? ?? ?? ??,x,46560,,?? ??,,,,,,,,,,,
|
||||||
|
4,,???,,,AT2025042200041,?????,"18,700,000",??,Multiple (??),"1,804,550","1,678,232",2200000,0,?? ?? ?? ??,x,2000000,0.1,?? ?? ?? ??,,1700000,0.294117647,??? ?? ?? ??,,1700000,,,,,
|
||||||
|
5,,???,,,AT2025041600034,???,"760,320",??,Multiple (??),"73,304","70,372",70000,,?? ??,,,,,,,,,,,,,,,
|
||||||
|
6,,???,,,AT2025042400010,????? ??,"780,000",??,Multiple (??),"75,642"," 72,617 ",,,,,,,,,,,,,,,,,,
|
||||||
|
7,,???,,,AT2025042400030,???,"313,000",??,Multiple (??),"31,300","29,735",50000,0,?? ?? ?? ??,,40000,0.25,?? ?? ?? ??,,30500,0.639344262,??? ?? ?? ??,,30500,,,,,
|
||||||
|
8,,???,,,AT2025042300096,?????,"706,800",??,None (??),"68,162","65,436",115800,0,?? ?? ?? ??,,70000,0.654285714,?? ?? ?? ??,,69000,0.67826087,??? ?? ?? ??,,65400,,,,,
|
||||||
|
9,,???,,,AT2025042300082,??????,"12,000",??,Multiple (??),"1,200","1,188",,,,,,,,,,,,,,,,,,
|
||||||
|
2.1,,???,ID 2 ???? ??(??>??),,AT2025042200057,????,"350,000",??,Single (??),"35,000"," 33,250 ",,,,,,,,,,,,,,,,,,
|
||||||
|
6.1,,???,ID 6 ???? ??(??>??),,AT2025042400010,????? ??,780000,??,Multiple (??),"75,642"," 71,860 ",,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,1,AT2025042400050,SOOT777,?????,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,2,AT2025042200057,JAJE89,????,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,3,AT2025042300003,VOV2,TV???,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,4,AT2025042200041,HEMEELY,?????,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,5,AT2025041600034,KMS5939,???,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,6,AT2025042400010,YTS111,????? ??,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,7,AT2025042400030,SJUN98,???,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,8,AT2025042300096,DREAMBIZ,?????,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,9,AT2025042300082,BWTCO40,??????,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,2.1,AT2025042200057,JAJE89,????,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,6.1,AT2025042400010,YTS111,????? ??,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
# 알고리즘 비교 실험 기본 설정 (H5). E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce
|
# 알고리즘 비교 실험 기본 설정 (H5). E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce
|
||||||
episodes: 400 # 정책당 협상 에피소드 수
|
episodes: 600 # 정책당 협상 에피소드 수 (action 11장 탐색 수렴 위해 상향)
|
||||||
seed: 42 # 재현용 (구매자 randomness 페어드)
|
seed: 42 # 재현용 (구매자 randomness 페어드)
|
||||||
max_turns: 5 # 협상 라운드 상한
|
max_turns: 5 # 협상 라운드 상한
|
||||||
n_good_cards: 3 # 시뮬 구매자: 효과 좋은 카드 수
|
n_good_cards: 3 # 시뮬 구매자: 효과 좋은 카드 수
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
"""FeatureBuyer — 카드 '내용(전략)'과 협력사 '프로필'에 반응하는 시뮬 협력사 (Phase 2·3).
|
||||||
|
|
||||||
|
효과를 2축으로 분리한다(성향 조건화가 의미를 가지려면 트레이드오프가 필요):
|
||||||
|
- 양보력(concession power): 이 카드가 가격을 얼마나 끌어내리는가
|
||||||
|
- 수락력(accept power) : 이 카드가 합의(수락) 확률을 얼마나 높이는가
|
||||||
|
|
||||||
|
전략별 기본 프로필(트레이드오프):
|
||||||
|
경쟁(1): 양보력↑↑ 수락력↓ — 세게 깎지만 결렬 위험
|
||||||
|
수용(2): 양보력↓ 수락력↑
|
||||||
|
고수(3): 양보력·수락력 중간
|
||||||
|
협력(4): 양보력↓ 수락력↑↑ — 잘 성사되지만 덜 깎임
|
||||||
|
|
||||||
|
여기에 협력사 세그먼트 적합도(AFFINITY)가 곱해진다: 전략이 그 협력사에 안 맞으면 둘 다 죽는다.
|
||||||
|
소형·경쟁多 → 경쟁압박이 잘 먹힘 / 대형·단독 → 협력이 잘 먹힘(압박 역효과)
|
||||||
|
|
||||||
|
→ '가격 중시' 고객사는 경쟁 카드(많이 깎음, 결렬 감수), '성사 중시' 고객사는 협력 카드가 정답이
|
||||||
|
되는 구조. 에이전트는 카드 특징 + 협력사 특징 + 고객사 성향으로 이를 학습해야 한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Dict, Tuple
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from eval_harness.buyer import BuyerResponse, Scenario
|
||||||
|
|
||||||
|
# strategy_type: 1=경쟁, 2=수용, 3=고수, 4=협력 (card.nego_cards)
|
||||||
|
# 전략별 (양보력, 수락력) 기본 프로필 — 트레이드오프의 원천
|
||||||
|
STRATEGY_PROFILE: Dict[int, Tuple[float, float]] = {
|
||||||
|
1: (0.90, 0.25), # 경쟁: 세게 깎지만 성사 어려움
|
||||||
|
2: (0.35, 0.70), # 수용
|
||||||
|
3: (0.55, 0.50), # 고수: 중간
|
||||||
|
4: (0.30, 0.90), # 협력: 잘 성사되지만 덜 깎임
|
||||||
|
}
|
||||||
|
|
||||||
|
# 세그먼트별 전략 적합도 m ∈ [0,1] — 전략이 그 협력사에 얼마나 '먹히는가'
|
||||||
|
AFFINITY: Dict[Tuple[str, str], Dict[int, float]] = {
|
||||||
|
("small", "multi"): {1: 0.90, 2: 0.45, 3: 0.60, 4: 0.40}, # 소형·경쟁多 → 경쟁압박
|
||||||
|
("small", "single"): {1: 0.35, 2: 0.60, 3: 0.80, 4: 0.55}, # 소형·단독 → 고수/논리
|
||||||
|
("big", "multi"): {1: 0.65, 2: 0.50, 3: 0.70, 4: 0.60},
|
||||||
|
("big", "single"): {1: 0.20, 2: 0.70, 3: 0.50, 4: 0.90}, # 대형·단독 → 협력 (압박 역효과)
|
||||||
|
}
|
||||||
|
REVENUE_BIG = 50_000_000 # state config 'high' 경계와 정합
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SupplierProfile:
|
||||||
|
"""협력사 프로필 — 에피소드마다 달라지는 협상 상대. snapshot 필드와 정합."""
|
||||||
|
|
||||||
|
revenue_amount: float
|
||||||
|
partner_count: int # 이 품목의 대안 협력사 수 (BATNA. 1:1 채팅이어도 다양)
|
||||||
|
distribution_code: str
|
||||||
|
|
||||||
|
@property
|
||||||
|
def segment(self) -> Tuple[str, str]:
|
||||||
|
size = "big" if self.revenue_amount > REVENUE_BIG else "small"
|
||||||
|
comp = "multi" if self.partner_count >= 2 else "single"
|
||||||
|
return (size, comp)
|
||||||
|
|
||||||
|
|
||||||
|
def sample_supplier(rng: np.random.Generator) -> SupplierProfile:
|
||||||
|
"""무작위 협력사 생성 (학습 데이터 다양성)."""
|
||||||
|
return SupplierProfile(
|
||||||
|
revenue_amount=float(rng.choice([5_000_000, 20_000_000, 80_000_000, 200_000_000])),
|
||||||
|
partner_count=int(rng.choice([1, 1, 2, 3])), # 단독 비중 높게
|
||||||
|
distribution_code=str(rng.choice(["A", "B", "C"])),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FeatureBuyer:
|
||||||
|
"""전략 프로필 x 세그먼트 적합도 기반 협력사 모델. (양보력, 수락력) 2축."""
|
||||||
|
|
||||||
|
def __init__(self, supplier: SupplierProfile, card_strategy: Dict[str, int], seed: int = 0,
|
||||||
|
accept_base: float = 0.08, max_turns: int = 5, jitter: float = 0.05):
|
||||||
|
self.supplier = supplier
|
||||||
|
self.card_strategy = card_strategy # {card_number: strategy_type}
|
||||||
|
self.rng = np.random.default_rng(seed)
|
||||||
|
self.accept_base = accept_base
|
||||||
|
self.max_turns = max_turns
|
||||||
|
self.jitter = jitter
|
||||||
|
# 숨은 하한가(reservation): 앵커의 94~110%. 앵커보다 높으면(약 60%) 가격만으로는
|
||||||
|
# 타결 불가 → 수락을 받아내야 함 → 수락력 낮은(경쟁) 카드에 진짜 결렬 위험이 생긴다.
|
||||||
|
self.floor_ratio = float(self.rng.uniform(0.94, 1.10))
|
||||||
|
|
||||||
|
def powers(self, card_number: str) -> Tuple[float, float]:
|
||||||
|
"""숨은 (양보력, 수락력). 전략 프로필 × 세그먼트 적합도 + 카드별 결정론적 지터."""
|
||||||
|
strat = self.card_strategy.get(card_number, 3)
|
||||||
|
conc_base, acc_base = STRATEGY_PROFILE.get(strat, (0.5, 0.5))
|
||||||
|
m = AFFINITY[self.supplier.segment].get(strat, 0.5)
|
||||||
|
scale = 0.35 + 0.85 * m # 적합도: 안 맞으면 둘 다 죽음 (0.35~1.2)
|
||||||
|
j = (hash(card_number) % 1000 / 1000.0 - 0.5) * 2 * self.jitter
|
||||||
|
c_pow = float(np.clip(conc_base * scale + j, 0.02, 0.98))
|
||||||
|
a_pow = float(np.clip(acc_base * scale + j, 0.02, 0.98))
|
||||||
|
return c_pow, a_pow
|
||||||
|
|
||||||
|
def respond(self, card_number: str, scenario: Scenario, turn: int, current_price: float) -> BuyerResponse:
|
||||||
|
c_pow, a_pow = self.powers(card_number)
|
||||||
|
floor = scenario.anchor_price * self.floor_ratio # 숨은 하한가 (앵커 이하 보장 없음)
|
||||||
|
concession = (current_price - floor) * (0.10 + 0.55 * c_pow)
|
||||||
|
new_price = max(floor, current_price - concession)
|
||||||
|
p_accept = min(0.97, self.accept_base + 0.80 * a_pow + 0.05 * (turn - 1))
|
||||||
|
accept = bool(self.rng.random() < p_accept)
|
||||||
|
walked = (not accept) and (turn >= self.max_turns)
|
||||||
|
return BuyerResponse(accept=accept, new_price=new_price, walked=walked)
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""CardCatalogDbRepository — card.nego_cards 에서 카탈로그(action space) read-only 조회.
|
||||||
|
|
||||||
|
정렬: number 오름차순(zero-padded NGC-001..NGC-011 이라 문자열 정렬로 안정적) → action_id.
|
||||||
|
스코프: o2o 기본 제공 카드(user_id IS NULL). 회사 전용 카탈로그는 후속(스코프 확장).
|
||||||
|
스키마 소유권: card 스키마는 backend/negodata 소유 — read-only. 경량 table()/column() 구성.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import List, Optional, Tuple
|
||||||
|
|
||||||
|
from sqlalchemy import asc, case, column, or_, select, table
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.enums import ErrorType
|
||||||
|
from common.logger import LOG
|
||||||
|
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
|
||||||
|
|
||||||
|
_NEGO_CARDS = table(
|
||||||
|
"nego_cards",
|
||||||
|
column("number"), column("user_id"), column("deleted"),
|
||||||
|
schema="card",
|
||||||
|
)
|
||||||
|
_USERS = table("users", column("user_id"), column("company_id"), column("deleted"), schema="company")
|
||||||
|
|
||||||
|
|
||||||
|
class CardCatalogDbRepository(ICardCatalogRepository):
|
||||||
|
async def get_nego_catalog(self, cdb: AsyncSession, company_id: Optional[object] = None) -> Tuple[ErrorType, List[str]]:
|
||||||
|
try:
|
||||||
|
# 스코프: 공용(user_id NULL) + (company_id 주면) 그 회사 유저가 만든 카드.
|
||||||
|
scope = _NEGO_CARDS.c.user_id.is_(None)
|
||||||
|
if company_id is not None:
|
||||||
|
company_users = (
|
||||||
|
select(_USERS.c.user_id)
|
||||||
|
.where(_USERS.c.company_id == company_id, _USERS.c.deleted == False) # noqa: E712
|
||||||
|
.scalar_subquery()
|
||||||
|
)
|
||||||
|
scope = or_(scope, _NEGO_CARDS.c.user_id.in_(company_users))
|
||||||
|
# 정렬: 공용(0) 먼저 → 회사(1) 뒤, 각 그룹 내 number 오름차순.
|
||||||
|
# 공용 카드의 action_id(0..N-1) 안정성 보장 — 회사 카드 추가는 뒤에 append.
|
||||||
|
shared_first = case((_NEGO_CARDS.c.user_id.is_(None), 0), else_=1)
|
||||||
|
query = (
|
||||||
|
select(_NEGO_CARDS.c.number)
|
||||||
|
.where(scope, _NEGO_CARDS.c.deleted == False) # noqa: E712
|
||||||
|
.order_by(shared_first, asc(_NEGO_CARDS.c.number))
|
||||||
|
)
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_nego_catalog failed.", raise_error=False)
|
||||||
|
if err_type != ErrorType.SUCCESS or not rows:
|
||||||
|
return err_type, []
|
||||||
|
return ErrorType.SUCCESS, [str(r) for r in rows if r]
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, []
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""ICardCatalogRepository — 협상카드 카탈로그(action space 정의) DB 조회 포트.
|
||||||
|
|
||||||
|
카탈로그 = Q-table 의 action 축을 정의하는 "카드 목록". negodata 가 관리하는 card.nego_cards 가
|
||||||
|
정본이며, agent 는 이를 조회해 action_id(0..N-1) ↔ 카드번호 매핑을 구성한다. tenant.yaml 의
|
||||||
|
action_to_card 하드코딩을 대체한다(config 결합 제거 — 카탈로그는 DB, config 는 튜닝만).
|
||||||
|
|
||||||
|
주의: 카탈로그 크기 = Q-table action 차원. 카드 수가 바뀌면 재차원화(버전 이벤트)가 필요하므로
|
||||||
|
카탈로그 변경은 드문 이벤트여야 한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from typing import List, Optional, Tuple
|
||||||
|
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from common.enums import ErrorType
|
||||||
|
|
||||||
|
|
||||||
|
class ICardCatalogRepository(ABC):
|
||||||
|
@abstractmethod
|
||||||
|
async def get_nego_catalog(self, cdb: AsyncSession, company_id: Optional[object] = None) -> Tuple[ErrorType, List[str]]:
|
||||||
|
"""action space 를 정의하는 일반 협상카드 번호 목록(정렬됨). action_id = 리스트 인덱스.
|
||||||
|
|
||||||
|
company_id(UUID) 주면 공용 카드(user_id NULL) + 그 회사 카드(user_id ∈ 회사 유저)를 함께,
|
||||||
|
**공용 먼저 → 회사 카드 뒤** 순으로 반환(공용 카드 action_id 안정성 보장). None 이면 공용만.
|
||||||
|
비었으면([]) 호출부가 파일 action_to_card 로 폴백한다.
|
||||||
|
"""
|
||||||
|
...
|
||||||
@@ -26,9 +26,41 @@ _SESSIONS = table(
|
|||||||
column("deleted"),
|
column("deleted"),
|
||||||
schema="negotiation",
|
schema="negotiation",
|
||||||
)
|
)
|
||||||
_ITEMS = table("items", column("item_id"), column("price"), column("deleted"), schema="partner")
|
_ITEMS = table("items", column("item_id"), column("price"), column("internet_lowest_price"),
|
||||||
|
column("deleted"), schema="partner")
|
||||||
_SUPPLIERS = table("suppliers", column("supplier_id"), column("total_revenue"), column("deleted"), schema="partner")
|
_SUPPLIERS = table("suppliers", column("supplier_id"), column("total_revenue"), column("deleted"), schema="partner")
|
||||||
_QUOTATIONS = table("quotations", column("qt_id"), column("supplier_type"), column("deleted"), schema="quotation")
|
_QUOTATIONS = table(
|
||||||
|
"quotations",
|
||||||
|
column("qt_id"), column("version_id"), column("supplier_type"),
|
||||||
|
column("start_time"), column("end_time"), column("deleted"),
|
||||||
|
schema="quotation",
|
||||||
|
)
|
||||||
|
# 자율 에이전트 이력 특징용 — agent 소유 learning 스키마 (done 행 = 협상 1건의 최종 결과).
|
||||||
|
_EXP_LOGS = table(
|
||||||
|
"experience_logs",
|
||||||
|
column("session_id"), column("company_id"), column("done"), column("settled_price"),
|
||||||
|
schema="learning",
|
||||||
|
)
|
||||||
|
_VERSION_NEGO_CARDS = table(
|
||||||
|
"version_nego_cards",
|
||||||
|
column("version_id"), column("nego_card_id"), column("created_at"), column("deleted"),
|
||||||
|
schema="card",
|
||||||
|
)
|
||||||
|
_VERSION_WILD_CARDS = table(
|
||||||
|
"version_wild_cards",
|
||||||
|
column("version_id"), column("wild_card_id"), column("created_at"), column("deleted"),
|
||||||
|
schema="card",
|
||||||
|
)
|
||||||
|
_NEGO_CARDS = table(
|
||||||
|
"nego_cards",
|
||||||
|
column("nego_card_id"), column("number"), column("deleted"),
|
||||||
|
schema="card",
|
||||||
|
)
|
||||||
|
_WILD_CARDS = table(
|
||||||
|
"wild_cards",
|
||||||
|
column("wild_card_id"), column("number"), column("deleted"),
|
||||||
|
schema="card",
|
||||||
|
)
|
||||||
# 상품↔협력사 매핑 (2026-07-07 신설): supply_type = 이 협력사가 이 상품을 공급하는 방식(SupplierType).
|
# 상품↔협력사 매핑 (2026-07-07 신설): supply_type = 이 협력사가 이 상품을 공급하는 방식(SupplierType).
|
||||||
_SUPPLIER_ITEMS = table(
|
_SUPPLIER_ITEMS = table(
|
||||||
"supplier_items",
|
"supplier_items",
|
||||||
@@ -59,11 +91,6 @@ class INegoContextCRUD(ABC):
|
|||||||
매핑이 없으면 None."""
|
매핑이 없으면 None."""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_quotation_supplier_type(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[int]]:
|
|
||||||
"""견적의 협력사 유형(quotations.supplier_type — supplier_items 매핑 부재 시 폴백). 미지정 시 None."""
|
|
||||||
pass
|
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def count_item_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
async def count_item_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||||
"""상품에 연결된 협력사 수 — supplier_items 매핑 기준 distinct supplier."""
|
"""상품에 연결된 협력사 수 — supplier_items 매핑 기준 distinct supplier."""
|
||||||
@@ -74,6 +101,27 @@ class INegoContextCRUD(ABC):
|
|||||||
"""상품에 연결된 협력사 수 — 협상 세션 이력 기준(supplier_items 매핑 부재 시 폴백)."""
|
"""상품에 연결된 협력사 수 — 협상 세션 이력 기준(supplier_items 매핑 부재 시 폴백)."""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def get_quotation_card_numbers(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, tuple[list[str], list[str]]]:
|
||||||
|
"""견적 version_id 에 연결된 (일반카드 번호 목록, 와일드카드 번호 목록). 없으면 빈 목록."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def get_item_internet_lowest(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||||
|
"""상품 인터넷최저가(items.internet_lowest_price). 미수집이면 0."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def get_quotation_period(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[tuple]]:
|
||||||
|
"""견적 협상 기간 (start_time, end_time). 없으면 None."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def get_supplier_history(self, cdb: AsyncSession, company_id: str, supplier_id,
|
||||||
|
exclude_session_id) -> Tuple[ErrorType, tuple]:
|
||||||
|
"""이 협력사와의 과거 협상 이력 (횟수, 성사율, 평균 타결가/목표가). 없으면 (0, None, None)."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class NegoContextCRUD(INegoContextCRUD):
|
class NegoContextCRUD(INegoContextCRUD):
|
||||||
async def get_session_row(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[tuple]]:
|
async def get_session_row(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[tuple]]:
|
||||||
@@ -107,6 +155,67 @@ class NegoContextCRUD(INegoContextCRUD):
|
|||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, 0
|
return ErrorType.DB_RUN_FAILED, 0
|
||||||
|
|
||||||
|
async def get_item_internet_lowest(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||||
|
"""상품의 인터넷최저가(partner.items.internet_lowest_price). 미수집이면 0."""
|
||||||
|
try:
|
||||||
|
query = (
|
||||||
|
select(_ITEMS.c.internet_lowest_price)
|
||||||
|
.where(_ITEMS.c.item_id == item_id, _ITEMS.c.deleted == False) # noqa: E712
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_item_internet_lowest failed.", raise_error=False)
|
||||||
|
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
|
||||||
|
return err_type, 0
|
||||||
|
return ErrorType.SUCCESS, int(rows[0])
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, 0
|
||||||
|
|
||||||
|
async def get_quotation_period(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[tuple]]:
|
||||||
|
"""견적 협상 기간 (start_time, end_time). 자율 에이전트의 마감 잔여율 특징용."""
|
||||||
|
try:
|
||||||
|
query = (
|
||||||
|
select(_QUOTATIONS.c.start_time, _QUOTATIONS.c.end_time)
|
||||||
|
.where(_QUOTATIONS.c.qt_id == quotation_id, _QUOTATIONS.c.deleted == False) # noqa: E712
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_quotation_period failed.", raise_error=False)
|
||||||
|
if err_type != ErrorType.SUCCESS or not rows:
|
||||||
|
return err_type, None
|
||||||
|
return ErrorType.SUCCESS, (rows[0][0], rows[0][1])
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, None
|
||||||
|
|
||||||
|
async def get_supplier_history(self, cdb: AsyncSession, company_id: str, supplier_id,
|
||||||
|
exclude_session_id) -> Tuple[ErrorType, tuple]:
|
||||||
|
"""이 협력사와의 과거 협상 이력 집계 → (횟수, 성사율, 평균 타결가/목표가).
|
||||||
|
|
||||||
|
소스 = learning.experience_logs 의 종료행(done=True) ⨝ negotiation.sessions
|
||||||
|
(agent 가 직접 기록한 결과라 카드/자율 모드 무관하게 쌓인다). 이력 없으면 (0, None, None).
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
query = (
|
||||||
|
select(_EXP_LOGS.c.settled_price, _SESSIONS.c.target_price)
|
||||||
|
.select_from(_EXP_LOGS.join(_SESSIONS, _SESSIONS.c.session_id == _EXP_LOGS.c.session_id))
|
||||||
|
.where(_EXP_LOGS.c.done == True, # noqa: E712
|
||||||
|
_EXP_LOGS.c.company_id == company_id,
|
||||||
|
_SESSIONS.c.supplier_id == supplier_id,
|
||||||
|
_EXP_LOGS.c.session_id != exclude_session_id,
|
||||||
|
_SESSIONS.c.deleted == False) # noqa: E712
|
||||||
|
)
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_supplier_history failed.", raise_error=False)
|
||||||
|
if err_type != ErrorType.SUCCESS or not rows:
|
||||||
|
return err_type, (0, None, None)
|
||||||
|
n = len(rows)
|
||||||
|
settled = [(int(sp), int(tp)) for sp, tp in rows if sp and tp]
|
||||||
|
success = len([1 for sp, tp in rows if sp]) / n
|
||||||
|
avg_ratio = (sum(sp / tp for sp, tp in settled) / len(settled)) if settled else None
|
||||||
|
return ErrorType.SUCCESS, (n, success, avg_ratio)
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, (0, None, None)
|
||||||
|
|
||||||
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
|
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
|
||||||
try:
|
try:
|
||||||
query = (
|
query = (
|
||||||
@@ -139,21 +248,6 @@ class NegoContextCRUD(INegoContextCRUD):
|
|||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, None
|
return ErrorType.DB_RUN_FAILED, None
|
||||||
|
|
||||||
async def get_quotation_supplier_type(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[int]]:
|
|
||||||
try:
|
|
||||||
query = (
|
|
||||||
select(_QUOTATIONS.c.supplier_type)
|
|
||||||
.where(_QUOTATIONS.c.qt_id == quotation_id, _QUOTATIONS.c.deleted == False) # noqa: E712
|
|
||||||
.limit(1)
|
|
||||||
)
|
|
||||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_quotation_supplier_type failed.", raise_error=False)
|
|
||||||
if err_type != ErrorType.SUCCESS or not rows or rows[0] is None:
|
|
||||||
return err_type, None
|
|
||||||
return ErrorType.SUCCESS, int(rows[0])
|
|
||||||
except Exception as ex:
|
|
||||||
LOG.e_no_callstack(ex)
|
|
||||||
return ErrorType.DB_RUN_FAILED, None
|
|
||||||
|
|
||||||
async def count_item_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
async def count_item_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||||
try:
|
try:
|
||||||
query = (
|
query = (
|
||||||
@@ -181,3 +275,63 @@ class NegoContextCRUD(INegoContextCRUD):
|
|||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, 0
|
return ErrorType.DB_RUN_FAILED, 0
|
||||||
|
|
||||||
|
async def get_quotation_card_numbers(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, tuple[list[str], list[str]]]:
|
||||||
|
try:
|
||||||
|
version_q = (
|
||||||
|
select(_QUOTATIONS.c.version_id)
|
||||||
|
.where(_QUOTATIONS.c.qt_id == quotation_id, _QUOTATIONS.c.deleted == False) # noqa: E712
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, version_q, "get_quotation_version failed.", raise_error=False)
|
||||||
|
if err_type != ErrorType.SUCCESS:
|
||||||
|
return err_type, ([], [])
|
||||||
|
if not rows or rows[0] is None:
|
||||||
|
return ErrorType.SUCCESS, ([], [])
|
||||||
|
version_id = rows[0]
|
||||||
|
|
||||||
|
nego_q = (
|
||||||
|
select(_NEGO_CARDS.c.number)
|
||||||
|
.select_from(
|
||||||
|
_VERSION_NEGO_CARDS.join(
|
||||||
|
_NEGO_CARDS,
|
||||||
|
_VERSION_NEGO_CARDS.c.nego_card_id == _NEGO_CARDS.c.nego_card_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.where(
|
||||||
|
_VERSION_NEGO_CARDS.c.version_id == version_id,
|
||||||
|
_VERSION_NEGO_CARDS.c.deleted == False, # noqa: E712
|
||||||
|
_NEGO_CARDS.c.deleted == False, # noqa: E712
|
||||||
|
)
|
||||||
|
.order_by(_VERSION_NEGO_CARDS.c.created_at)
|
||||||
|
)
|
||||||
|
n_err, n_rows = await DB_SESSION_MNG.execute(cdb, nego_q, "get_quotation_nego_cards failed.", raise_error=False)
|
||||||
|
if n_err != ErrorType.SUCCESS:
|
||||||
|
return n_err, ([], [])
|
||||||
|
|
||||||
|
wild_q = (
|
||||||
|
select(_WILD_CARDS.c.number)
|
||||||
|
.select_from(
|
||||||
|
_VERSION_WILD_CARDS.join(
|
||||||
|
_WILD_CARDS,
|
||||||
|
_VERSION_WILD_CARDS.c.wild_card_id == _WILD_CARDS.c.wild_card_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.where(
|
||||||
|
_VERSION_WILD_CARDS.c.version_id == version_id,
|
||||||
|
_VERSION_WILD_CARDS.c.deleted == False, # noqa: E712
|
||||||
|
_WILD_CARDS.c.deleted == False, # noqa: E712
|
||||||
|
)
|
||||||
|
.order_by(_VERSION_WILD_CARDS.c.created_at)
|
||||||
|
)
|
||||||
|
w_err, w_rows = await DB_SESSION_MNG.execute(cdb, wild_q, "get_quotation_wild_cards failed.", raise_error=False)
|
||||||
|
if w_err != ErrorType.SUCCESS:
|
||||||
|
return w_err, ([], [])
|
||||||
|
|
||||||
|
return ErrorType.SUCCESS, (
|
||||||
|
[str(r) for r in n_rows if r is not None],
|
||||||
|
[str(r) for r in w_rows if r is not None],
|
||||||
|
)
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, ([], [])
|
||||||
@@ -16,6 +16,50 @@ MAX_ROUNDS = 3
|
|||||||
_PRICE_MODES = ("price",)
|
_PRICE_MODES = ("price",)
|
||||||
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
||||||
|
|
||||||
|
# ---- 완전 자율 모드 (AUTONOMY_MODE, autonomy_store) --------------------------------
|
||||||
|
# 가격협상 판정 룰(check_price_match/wildcard_entry/iteration_limit)과 카드 선택을
|
||||||
|
# 정책 행동(수락/역제안/압박/결렬)으로 대체할 때 쓰는 스텝들. autonomy_decider 미주입이면 도달 불가.
|
||||||
|
_AUTONOMY_TURN_CAP = 12 # 엔지니어링 타임아웃(무한 세션 방지) — 협상 룰이 아니다
|
||||||
|
|
||||||
|
_AUTONOMY_PRESS_SCRIPTS = {
|
||||||
|
1: "동일 품목에 대해 복수 공급처의 견적이 함께 검토되고 있습니다. 현재 제시가로는 우선순위 확보가 어려운 상황입니다. 경쟁력 있는 가격으로 다시 제안해 주시겠어요?",
|
||||||
|
2: "제안하신 조건의 취지는 충분히 이해했습니다. 저희도 최대한 맞춰보려 합니다. 조금만 더 조정해 주시면 내부 설득이 가능할 것 같습니다. 다시 제안해 주시겠어요?",
|
||||||
|
3: "내부 산정 기준과 현재 제시가 사이에 아직 차이가 있습니다. 기준에 부합하는 수준으로 재검토하여 다시 제안해 주시기를 부탁드립니다.",
|
||||||
|
4: "귀사를 장기적으로 함께할 파트너로 검토하고 있습니다. 이번 협상이 원만히 마무리되면 후속 거래 확대도 논의하고 싶습니다. 서로 만족할 수 있는 가격으로 다시 제안해 주시겠어요?",
|
||||||
|
}
|
||||||
|
|
||||||
|
_AUTONOMY_STEPS = {
|
||||||
|
"자율_역제안": {
|
||||||
|
"script": "제안해 주신 **{input_price}원**, 내부 검토를 마쳤습니다. **{autonomy_offer}원**이라면 즉시 수락하고 우선협상 대상으로 확정하겠습니다. 수락하시겠습니까?",
|
||||||
|
"next_input_mode": "yes_no",
|
||||||
|
"input_options": ["예", "아니오"],
|
||||||
|
"next_step": {"예": "협상완료", "아니오": "가격협상_재입력"},
|
||||||
|
"type": "text",
|
||||||
|
"chat_end": False,
|
||||||
|
},
|
||||||
|
# 최종 통보(WC-03 의 자율 버전): 정책이 직전과 같은 금액을 다시 부르는 순간(단조 봉투상
|
||||||
|
# 더 올릴 수 없음 = 탄약 소진) 발동. 거절하면 협상을 정리한다 — 어정쩡한 반복 대신 명확한 마무리.
|
||||||
|
"자율_최종제안": {
|
||||||
|
"script": "지금까지 협의에 성실히 임해 주셔서 감사합니다. **{autonomy_offer}원**은 저희가 제시할 수 있는 마지막 제안입니다. 수락해 주시면 즉시 우선협상 대상으로 확정되며, 어려우시다면 이번 협상은 여기서 마무리하겠습니다.",
|
||||||
|
"next_input_mode": "yes_no",
|
||||||
|
"input_options": ["예", "아니오"],
|
||||||
|
"next_step": {"예": "협상완료", "아니오": "협상실패"},
|
||||||
|
"type": "text",
|
||||||
|
"chat_end": False,
|
||||||
|
},
|
||||||
|
**{
|
||||||
|
f"자율_압박_{s}": {
|
||||||
|
"script": t,
|
||||||
|
"next_input_mode": "price",
|
||||||
|
"input_options": [],
|
||||||
|
"next_step": {"default": "가격협상_확인"},
|
||||||
|
"type": "text",
|
||||||
|
"chat_end": False,
|
||||||
|
}
|
||||||
|
for s, t in _AUTONOMY_PRESS_SCRIPTS.items()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
# 최종 타결/결렬 스텝. 재협상=협상완료(우선협상 타결), 재견적=결과제출(투찰확정). 둘 다 협상실패=결렬.
|
# 최종 타결/결렬 스텝. 재협상=협상완료(우선협상 타결), 재견적=결과제출(투찰확정). 둘 다 협상실패=결렬.
|
||||||
# 이 스텝들은 chat_end=False(뒤에 협상종료가 옴)라, outcome 을 컨텍스트에 적재했다가
|
# 이 스텝들은 chat_end=False(뒤에 협상종료가 옴)라, outcome 을 컨텍스트에 적재했다가
|
||||||
# 실제 종료(chat_end=협상종료) 시점에 확정 보고한다 → backend 가 chat_end 에서 DONE/REJECTED 를 옳게 가른다.
|
# 실제 종료(chat_end=협상종료) 시점에 확정 보고한다 → backend 가 chat_end 에서 DONE/REJECTED 를 옳게 가른다.
|
||||||
@@ -70,8 +114,11 @@ class ChatEngine:
|
|||||||
def __init__(self, scripts_repo: ScriptRepository, rq_type: str = "재협상"):
|
def __init__(self, scripts_repo: ScriptRepository, rq_type: str = "재협상"):
|
||||||
self.repo = scripts_repo
|
self.repo = scripts_repo
|
||||||
self.rq_type = rq_type
|
self.rq_type = rq_type
|
||||||
self.scripts = scripts_repo.load_scripts(rq_type)
|
# 자율 스텝은 병합만 해둔다(repo 캐시 오염 방지 위해 새 dict) — decider 미주입 시 도달 불가.
|
||||||
|
self.scripts = {**scripts_repo.load_scripts(rq_type), **_AUTONOMY_STEPS}
|
||||||
self.step_map = scripts_repo.client_step_mapping()
|
self.step_map = scripts_repo.client_step_mapping()
|
||||||
|
# 완전 자율 모드: ChatService 가 AutonomyStore 정책을 주입하면 가격협상 판정 룰을 대체한다.
|
||||||
|
self.autonomy_decider = None # Callable[[dict], autonomy_actions.Action]
|
||||||
|
|
||||||
# ---- public --------------------------------------------------------
|
# ---- public --------------------------------------------------------
|
||||||
def start(self, session: ChatSession) -> StepView:
|
def start(self, session: ChatSession) -> StepView:
|
||||||
@@ -99,6 +146,10 @@ class ChatEngine:
|
|||||||
# 직전 제시가로 잡히던 버그 수정 — 수락 시 실제 합의가는 인하가다.)
|
# 직전 제시가로 잡히던 버그 수정 — 수락 시 실제 합의가는 인하가다.)
|
||||||
if session.step == "wild_card_1pct" and user_input == "예" and session.context.get("offer_1pct"):
|
if session.step == "wild_card_1pct" and user_input == "예" and session.context.get("offer_1pct"):
|
||||||
session.context["input_price"] = float(session.context["offer_1pct"])
|
session.context["input_price"] = float(session.context["offer_1pct"])
|
||||||
|
# 자율 역제안/최종제안 수락("예") → 합의가는 에이전트 제안가다 (wild_card_1pct 와 동일 원리).
|
||||||
|
if session.step in ("자율_역제안", "자율_최종제안") and user_input == "예" \
|
||||||
|
and session.context.get("autonomy_offer"):
|
||||||
|
session.context["input_price"] = float(session.context["autonomy_offer"])
|
||||||
nxt = self._choice_next(node, user_input, session)
|
nxt = self._choice_next(node, user_input, session)
|
||||||
else:
|
else:
|
||||||
nxt = self._default_next(node)
|
nxt = self._default_next(node)
|
||||||
@@ -136,7 +187,15 @@ class ChatEngine:
|
|||||||
- anchor 살짝 초과(≤ anchor*1.05) + 와일드카드 미사용 → 와일드카드로 인하 압박.
|
- anchor 살짝 초과(≤ anchor*1.05) + 와일드카드 미사용 → 와일드카드로 인하 압박.
|
||||||
- 설정 카드(action_space) 모두 소진 → 협상실패.
|
- 설정 카드(action_space) 모두 소진 → 협상실패.
|
||||||
- 그 외 → 가격협상(카드 1장 플레이 후 재제안).
|
- 그 외 → 가격협상(카드 1장 플레이 후 재제안).
|
||||||
|
|
||||||
|
완전 자율 모드(autonomy_decider 주입)에서는 위 룰 전체를 정책 행동으로 대체한다.
|
||||||
"""
|
"""
|
||||||
|
# 가격협상 판정 지점(check_price_match 포함 조건 리스트)에서만 자율 정책이 개입한다.
|
||||||
|
if self.autonomy_decider is not None and any(
|
||||||
|
c.get("condition") == "check_price_match" for c in conds):
|
||||||
|
nxt = self._autonomy_next(session)
|
||||||
|
if nxt is not None:
|
||||||
|
return nxt # 정책 실패(예외) 시에만 아래 룰로 폴백
|
||||||
ctx = session.context
|
ctx = session.context
|
||||||
price = ctx.get("input_price", 0)
|
price = ctx.get("input_price", 0)
|
||||||
anchor = ctx.get("anchor_price", 0)
|
anchor = ctx.get("anchor_price", 0)
|
||||||
@@ -146,7 +205,15 @@ class ChatEngine:
|
|||||||
cond = c.get("condition")
|
cond = c.get("condition")
|
||||||
ok = False
|
ok = False
|
||||||
if cond == "check_wildcard_entry":
|
if cond == "check_wildcard_entry":
|
||||||
ok = (not ctx.get("wildcard_used")) and anchor < price <= anchor * 1.05
|
ok = (
|
||||||
|
(not ctx.get("wildcard_used"))
|
||||||
|
and anchor > 0
|
||||||
|
and anchor < price
|
||||||
|
and (
|
||||||
|
price <= anchor * 1.02
|
||||||
|
or (bool(ctx.get("allow_selected_wildcards", True)) and price <= anchor * 1.05)
|
||||||
|
)
|
||||||
|
)
|
||||||
elif cond == "check_is_supplier_type_c":
|
elif cond == "check_is_supplier_type_c":
|
||||||
ok = False # 공급사 유형 미보유 (PoC 단순화)
|
ok = False # 공급사 유형 미보유 (PoC 단순화)
|
||||||
elif cond == "check_price_match": # = 우선협상: 제시가가 앵커가 이하
|
elif cond == "check_price_match": # = 우선협상: 제시가가 앵커가 이하
|
||||||
@@ -164,19 +231,71 @@ class ChatEngine:
|
|||||||
return c.get("next")
|
return c.get("next")
|
||||||
return "가격협상"
|
return "가격협상"
|
||||||
|
|
||||||
|
def _autonomy_next(self, session: ChatSession) -> Optional[str]:
|
||||||
|
"""완전 자율: 정책 행동 → 스텝. 수락/역제안 금액/압박 화법/결렬 타이밍 전부 정책이 결정.
|
||||||
|
|
||||||
|
유일한 강제 종료는 턴 상한(_AUTONOMY_TURN_CAP) — 무한 세션 방지용 엔지니어링 타임아웃.
|
||||||
|
정책 호출이 실패하면 None 을 반환해 기존 룰 평가로 폴백한다(서비스 연속성).
|
||||||
|
"""
|
||||||
|
ctx = session.context
|
||||||
|
if ctx.get("round", 0) > _AUTONOMY_TURN_CAP:
|
||||||
|
# 턴 상한도 최종제안 보장(봉투 ⑥)을 우회하지 않는다 — 어떤 경로로 끝나든
|
||||||
|
# "끝내기 전에 한 번 더"(제품 결정)를 거친다. 최종 거절 후에만 협상실패.
|
||||||
|
if not ctx.get("autonomy_final_asked"):
|
||||||
|
ctx["autonomy_final_asked"] = True
|
||||||
|
ctx["autonomy_offer"] = int(ctx.get("target_price", 0))
|
||||||
|
return "자율_최종제안"
|
||||||
|
return "협상실패"
|
||||||
|
try:
|
||||||
|
act = self.autonomy_decider(ctx)
|
||||||
|
except Exception: # 정책 오류 → 룰 폴백 (호출부에서 로깅)
|
||||||
|
return None
|
||||||
|
session.context["autonomy_action"] = f"{act.kind}:{act.strategy}:{act.counter_q}"
|
||||||
|
span = max(ctx.get("target_price", 0) - ctx.get("anchor_price", 0), 1.0)
|
||||||
|
# 탄약소진(같은 금액 재호출) 판정은 '마지막 역제안' 기준 — autonomy_last(마지막 행동)는
|
||||||
|
# 사이에 낀 설득이 덮어써 판정이 리셋된다 (chat_service 가 counter 마다 별도 보존).
|
||||||
|
last = ctx.get("autonomy_last_counter") or {}
|
||||||
|
if act.kind == "accept":
|
||||||
|
return "협상완료"
|
||||||
|
if act.kind == "walk":
|
||||||
|
# 결렬 전 마지막 제안 1회 보장 — "끝내기 전에 한 번 더 물어보고 종료" (제품 결정).
|
||||||
|
# 최종제안을 이미 거쳤으면(autonomy_final_asked) 그대로 종료한다.
|
||||||
|
if not ctx.get("autonomy_final_asked"):
|
||||||
|
ctx["autonomy_final_asked"] = True
|
||||||
|
# 최종제안 금액 = 목표가. 마지막 기회에 직전 역제안 금액을 반복하면 승인 범위의
|
||||||
|
# 여지(목표가까지)를 남긴 채 결렬된다 — 최종에는 우리가 수락 가능한 최대치를 부른다.
|
||||||
|
ctx["autonomy_offer"] = int(ctx.get("target_price", 0))
|
||||||
|
return "자율_최종제안"
|
||||||
|
return "협상실패"
|
||||||
|
if act.kind == "counter":
|
||||||
|
ctx["autonomy_offer"] = int(round(ctx.get("anchor_price", 0) + act.counter_q * span))
|
||||||
|
# 직전과 같은 금액을 다시 부름 = 단조 봉투상 더 올릴 수 없음(탄약 소진) → 최종 통보로 전환.
|
||||||
|
if last.get("kind") == "counter" and act.counter_q <= float(last.get("q", -9)) + 1e-9:
|
||||||
|
ctx["autonomy_final_asked"] = True
|
||||||
|
ctx["autonomy_offer"] = int(ctx.get("target_price", 0))
|
||||||
|
return "자율_최종제안"
|
||||||
|
return "자율_역제안"
|
||||||
|
return f"자율_압박_{act.strategy or 3}"
|
||||||
|
|
||||||
def _pick_wildcard(self, session: ChatSession) -> str:
|
def _pick_wildcard(self, session: ChatSession) -> str:
|
||||||
"""앵커가 살짝 초과 구간에서 인하 압박 카드 선택.
|
"""앵커가에 아주 근접(≤ anchor*1.02)한 구간에서만 1% 인하 요청(wild_card_1pct)으로
|
||||||
- 앵커가에 아주 근접(≤ anchor*1.02): 1% 인하 요청(wild_card_1pct) → 앵커가 이하로 유도.
|
앵커가 이하로 유도한다. 그 외 구간은 일반 가격협상(카드 플레이)으로 돌린다.
|
||||||
- 그 외: 목표 매입가 맞춰달라(wild_card_budget).
|
|
||||||
|
과거 여기서 반환하던 '재원부족'(wild_card_budget) 하드코딩 카드는 제거했다 —
|
||||||
|
견적에서 실제 선택한 와일드카드(중간값 절충·목표가 선제안 등)와 매핑되지 않은 채
|
||||||
|
'와일드카드를 하나라도 골랐으면' 조건만으로 발동해, 선택하지도 않은 재원부족 멘트가
|
||||||
|
노출되는 오작동이 있었다.
|
||||||
"""
|
"""
|
||||||
ctx = session.context
|
ctx = session.context
|
||||||
price = ctx.get("input_price", 0)
|
price = ctx.get("input_price", 0)
|
||||||
anchor = ctx.get("anchor_price", 0)
|
anchor = ctx.get("anchor_price", 0)
|
||||||
ctx["wildcard_used"] = True
|
|
||||||
if anchor > 0 and price <= anchor * 1.02:
|
if anchor > 0 and price <= anchor * 1.02:
|
||||||
|
# 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
|
||||||
|
# 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
|
||||||
|
ctx["wildcard_used"] = True
|
||||||
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가
|
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가
|
||||||
return "wild_card_1pct"
|
return "wild_card_1pct"
|
||||||
return "wild_card_budget"
|
return "가격협상"
|
||||||
|
|
||||||
# ---- render --------------------------------------------------------
|
# ---- render --------------------------------------------------------
|
||||||
def vars_for(self, session: ChatSession) -> Dict[str, Any]:
|
def vars_for(self, session: ChatSession) -> Dict[str, Any]:
|
||||||
@@ -187,10 +306,25 @@ class ChatEngine:
|
|||||||
out["input_price"] = int(ctx["input_price"])
|
out["input_price"] = int(ctx["input_price"])
|
||||||
if "target_price" in ctx:
|
if "target_price" in ctx:
|
||||||
out["target"] = int(ctx["target_price"])
|
out["target"] = int(ctx["target_price"])
|
||||||
|
# DB 카드 정본(negodata 편집, card.nego_cards.script)은 {target_price} 변수명을 쓴다
|
||||||
|
# — 파일 스크립트의 {target}과 별개로 둘 다 지원(미치환 토큰 노출 방지).
|
||||||
|
out["target_price"] = int(ctx["target_price"])
|
||||||
if "anchor_price" in ctx:
|
if "anchor_price" in ctx:
|
||||||
out["anchor"] = int(ctx["anchor_price"])
|
out["anchor"] = int(ctx["anchor_price"])
|
||||||
|
out["anchoring_price"] = int(ctx["anchor_price"]) # DB 카드 정본 변수명(NGC-007 등)
|
||||||
if "offer_1pct" in ctx:
|
if "offer_1pct" in ctx:
|
||||||
out["offer_1pct"] = int(ctx["offer_1pct"])
|
out["offer_1pct"] = int(ctx["offer_1pct"])
|
||||||
|
if "autonomy_offer" in ctx:
|
||||||
|
out["autonomy_offer"] = int(ctx["autonomy_offer"])
|
||||||
|
# 인터넷 최저가(NGC-008): 수집값이 컨텍스트에 없으면 앵커가로 폴백 — 원형 토큰 노출 방지.
|
||||||
|
# TODO: partner.item_internet_lowest_prices 최신 성공 수집값을 context loader 로 연결.
|
||||||
|
if ctx.get("internet_lowest_price"):
|
||||||
|
out["internet_lowest_price"] = int(ctx["internet_lowest_price"])
|
||||||
|
elif "anchor_price" in ctx:
|
||||||
|
out["internet_lowest_price"] = int(ctx["anchor_price"])
|
||||||
|
# 고객사 교환·요구 조건(NGC-009/010): 런타임 소스 미구현 — 중립 문구 폴백.
|
||||||
|
# TODO: 견적/카드 편집 단계에서 입력받아 컨텍스트로 전달.
|
||||||
|
out["customer_condition"] = ctx.get("customer_condition") or "상호 협의된 조건"
|
||||||
# 인하율 = (기존 공급가 - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
|
# 인하율 = (기존 공급가 - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
|
||||||
base = ctx.get("item_price") or 0
|
base = ctx.get("item_price") or 0
|
||||||
if base > 1 and "input_price" in ctx:
|
if base > 1 and "input_price" in ctx:
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
"""MentGenerator — 자율 협상 행동을 LLM 이 자연어 멘트로 표현 (v2: 행동은 RL, 문장은 LLM).
|
||||||
|
|
||||||
|
역할 분리(안전 설계):
|
||||||
|
- 무엇을 말할지(수락/역제안 금액/압박 전략/결렬)는 RL 정책이 결정 — LLM 은 표현만 담당.
|
||||||
|
- 가드레일: 역제안 멘트에 제안 금액이 정확히 포함되지 않으면 폐기, 예외/미설정 시 None
|
||||||
|
→ 호출부(ChatService)가 기존 템플릿 멘트로 폴백한다. LLM 이 죽어도 협상은 계속된다.
|
||||||
|
|
||||||
|
설정: config.local.toml [OpenAIConfig] (Gemini 는 OpenAI 호환 base_url 로 접속).
|
||||||
|
비활성화: AUTONOMY_LLM=0.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from common.logger import LOG
|
||||||
|
from negotiation.profiling.config import LlmCredentials
|
||||||
|
|
||||||
|
_STRATEGY_TONE = {
|
||||||
|
1: "경쟁 압박형 — 복수 공급처와 비교 검토 중임을 암시하며 긴장감을 준다",
|
||||||
|
2: "수용 공감형 — 상대 제안의 취지에 공감하며 부드럽게 조정을 요청한다",
|
||||||
|
3: "기준 고수형 — 내부 산정 기준과 목표가를 근거로 원칙을 지킨다",
|
||||||
|
4: "협력 파트너형 — 장기 파트너십과 후속 거래 확대 가능성을 강조한다",
|
||||||
|
}
|
||||||
|
|
||||||
|
_SYSTEM = """너는 대기업 구매팀의 가격 협상 챗봇이다. 주어진 '전달 의도'를 자연스러운 한국어 협상 멘트로 바꿔 쓴다.
|
||||||
|
규칙 (위반 시 출력은 폐기된다):
|
||||||
|
- 1~3문장, 정중하되 간결하게. 출력은 멘트 텍스트만 (따옴표·설명 없이).
|
||||||
|
- 금액 숫자는 주어진 그대로 정확히 포함하고 단위는 '원'을 쓴다. 주어지지 않은 숫자·비율을 절대 만들지 않는다.
|
||||||
|
- 지정된 '화법' 전략 안에서만 말한다. 그 외의 협상 전술(물량·기간 약속, 조건 교환, 거래 연계,
|
||||||
|
독점 제안, 시장가·최저가 주장, 할인 약속 등)을 지어내지 않는다.
|
||||||
|
- 회사의 정책·사실을 단정하지 않는다. 주어진 의도에 없는 정보는 말하지 않는다.
|
||||||
|
- 상대는 협력사(판매자)이고 우리는 구매자다."""
|
||||||
|
|
||||||
|
# 생성문 금지어 — 승인되지 않은 커밋/주장 계열. 걸리면 템플릿 폴백(협상은 계속).
|
||||||
|
_FORBIDDEN = ("보장", "물량", "독점", "무조건", "최저가", "시장 가격", "시장가", "계약 기간",
|
||||||
|
"법적", "위약", "%")
|
||||||
|
|
||||||
|
|
||||||
|
def _configured() -> bool:
|
||||||
|
if os.getenv("AUTONOMY_LLM", "1").lower() in ("0", "false", "no"):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return LlmCredentials.from_config().is_configured()
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _digits(s) -> str:
|
||||||
|
return re.sub(r"[^\d]", "", str(s))
|
||||||
|
|
||||||
|
|
||||||
|
def _history_hints(ctx: dict) -> str:
|
||||||
|
"""대화 기억 힌트 — 무기억 생성이 '매번 같은 멘트'를 만들던 문제의 해법.
|
||||||
|
|
||||||
|
① 직전 우리 제안이 거절된 사실과 이번 제안과의 관계(양보/입장유지)를 짚게 하고
|
||||||
|
② 직전 봇 멘트를 보여주며 같은 문장 구조·표현의 반복을 금지한다."""
|
||||||
|
hints = []
|
||||||
|
prev = ctx.get("autonomy_prev")
|
||||||
|
if prev and prev.get("kind") == "counter":
|
||||||
|
anchor, target = float(ctx.get("anchor_price") or 0), float(ctx.get("target_price") or 0)
|
||||||
|
prev_offer = int(round(anchor + float(prev.get("q", 0.0)) * max(target - anchor, 1.0)))
|
||||||
|
cur_offer = int(ctx.get("autonomy_offer") or 0)
|
||||||
|
if cur_offer > prev_offer:
|
||||||
|
hints.append(f"참고: 직전 라운드에 우리가 {prev_offer:,}원을 제안했으나 거절당했고, "
|
||||||
|
f"이번에는 {cur_offer - prev_offer:,}원 더 양보한 제안이다. 이 진전을 자연스럽게 짚어라.")
|
||||||
|
elif cur_offer == prev_offer and cur_offer > 0:
|
||||||
|
hints.append(f"참고: 직전에 제안한 {prev_offer:,}원을 거절당했지만 같은 금액을 유지한다. "
|
||||||
|
f"입장이 확고함을 정중하게 전하라.")
|
||||||
|
elif prev_offer > 0:
|
||||||
|
hints.append(f"참고: 직전 제안({prev_offer:,}원)이 거절된 뒤의 재제안이다.")
|
||||||
|
last_ment = ctx.get("autonomy_last_ment")
|
||||||
|
if last_ment:
|
||||||
|
hints.append(f'직전 봇 멘트: "{last_ment}" — 이와 같은 문장 구조·표현을 반복하지 말고 다르게 써라.')
|
||||||
|
return " ".join(hints)
|
||||||
|
|
||||||
|
|
||||||
|
def _prompt_for(step: str, ctx: dict) -> Optional[str]:
|
||||||
|
price = int(ctx.get("input_price") or 0)
|
||||||
|
rnd = ctx.get("round", 1)
|
||||||
|
if step in ("자율_역제안", "자율_최종제안"):
|
||||||
|
offer = int(ctx.get("autonomy_offer") or 0)
|
||||||
|
if offer <= 0:
|
||||||
|
return None
|
||||||
|
strategy = int((ctx.get("autonomy_last") or {}).get("s") or 3)
|
||||||
|
tone = _STRATEGY_TONE.get(strategy, _STRATEGY_TONE[3])
|
||||||
|
final = ("이번이 우리가 제시할 수 있는 마지막 제안이며, 거절하시면 이번 협상은 종료됨을 "
|
||||||
|
"분명하되 정중하게 밝혀라. " if step == "자율_최종제안" else "")
|
||||||
|
return (f"상황: 협력사가 {price:,}원을 제시했다(협상 {rnd}라운드). "
|
||||||
|
f"전달 의도: 우리는 **{offer:,}원**이면 즉시 수락하고 우선협상 대상으로 확정할 수 있다 — "
|
||||||
|
f"이 핵심 의미는 유지하되 문장 표현은 자유롭게 새로 써라. {final}화법: {tone}. "
|
||||||
|
f"{_history_hints(ctx)} 마지막에 수락 여부를 물어라.")
|
||||||
|
if step.startswith("자율_압박_"):
|
||||||
|
strategy = int(step.rsplit("_", 1)[1])
|
||||||
|
tone = _STRATEGY_TONE.get(strategy, _STRATEGY_TONE[3])
|
||||||
|
# 주의: 목표가는 프롬프트에 넣지 않는다 — 압박 중 목표가 노출은 우리 상한을 까는 것
|
||||||
|
# (상대가 그 밑으로 내려올 이유가 사라진다). 숫자 커밋은 역제안/최종제안에서만.
|
||||||
|
base = (f"상황: 협력사가 {price:,}원을 제시했다(협상 {rnd}라운드). "
|
||||||
|
f"전달 의도: 어떤 금액도 언급하지 말고(내부 기준·목표가 숫자 금지), 제시가와 우리 기준의 "
|
||||||
|
f"거리가 있다는 취지로 가격 재제안을 요청한다. 화법: {tone}. "
|
||||||
|
f"{_history_hints(ctx)}")
|
||||||
|
# 시장가 근거 (구 NGC-008 의 자율 버전): 수집된 인터넷최저가가 실재하고 제시가가 그보다
|
||||||
|
# 높을 때만 사실 근거로 인용을 허용한다 — 미수집 품목에서 지어내는 주장은 가드가 차단.
|
||||||
|
if _market_evidence(ctx):
|
||||||
|
il = int(ctx["internet_lowest_price"])
|
||||||
|
base += (f" 참고 사실(인용 허용되는 유일한 금액): 동일 품목의 인터넷 최저가가 {il:,}원으로 "
|
||||||
|
f"확인된다. 현재 제시가가 이보다 높다는 점을 근거로 조정 여지를 정중히 짚어라.")
|
||||||
|
return base
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _market_evidence(ctx: dict) -> bool:
|
||||||
|
"""시장가 근거 인용 가능 조건: 인터넷최저가 수집됨 + 제시가가 그보다 높음."""
|
||||||
|
il = int(ctx.get("internet_lowest_price") or 0)
|
||||||
|
return il > 0 and float(ctx.get("input_price") or 0) > il
|
||||||
|
|
||||||
|
|
||||||
|
def _allowed_amounts(ctx: dict) -> set:
|
||||||
|
"""멘트에 등장해도 되는 숫자 집합 — 우리가 프롬프트로 준 값들뿐. 이 밖의 금액 = 할루시네이션."""
|
||||||
|
# 목표가는 화이트리스트에 없다 — 압박 멘트가 목표가를 새면(상한 노출) 즉시 폐기된다.
|
||||||
|
# 역제안·최종제안의 제안가(autonomy_offer)가 목표가와 같은 경우만 그 값으로 허용된다.
|
||||||
|
anchor, target = float(ctx.get("anchor_price") or 0), float(ctx.get("target_price") or 0)
|
||||||
|
out = {int(ctx.get("input_price") or 0), int(ctx.get("autonomy_offer") or 0),
|
||||||
|
int(ctx.get("round") or 0)}
|
||||||
|
if _market_evidence(ctx):
|
||||||
|
out.add(int(ctx["internet_lowest_price"])) # 시장가 근거 인용 시 그 수치만 허용
|
||||||
|
prev = ctx.get("autonomy_prev")
|
||||||
|
if prev and prev.get("kind") == "counter":
|
||||||
|
prev_offer = int(round(anchor + float(prev.get("q", 0.0)) * max(target - anchor, 1.0)))
|
||||||
|
out |= {prev_offer, abs(int(ctx.get("autonomy_offer") or 0) - prev_offer)}
|
||||||
|
return {str(v) for v in out if v}
|
||||||
|
|
||||||
|
|
||||||
|
def _guard(step: str, ctx: dict, text: str) -> bool:
|
||||||
|
"""LLM 출력 검증(할루시네이션 차단) — 실패 시 템플릿 폴백.
|
||||||
|
|
||||||
|
① 길이/문장 완결 ② 금지어(승인 안 된 커밋·주장) ③ 숫자 화이트리스트: 멘트의 모든
|
||||||
|
3자리+ 숫자는 우리가 준 값(제시가·제안가·목표가·직전제안가)이어야 한다 — 지어낸 금액 즉시 폐기.
|
||||||
|
④ 역제안은 제안 금액 포함 필수."""
|
||||||
|
if not text or len(text) < 10 or len(text) > 600:
|
||||||
|
return False
|
||||||
|
if not text.rstrip().endswith(("다.", "요.", "요?", "까?", "니까?", ".", "?")):
|
||||||
|
return False # 문장 중간 잘림(thinking 토큰에 한도 소진 등) → 템플릿 폴백
|
||||||
|
forbidden = _FORBIDDEN
|
||||||
|
if _market_evidence(ctx):
|
||||||
|
# 시장가 근거가 정당한 턴에는 '최저가/시장가' 언급을 허용 (수치는 아래 화이트리스트가 검증).
|
||||||
|
forbidden = tuple(w for w in _FORBIDDEN if w not in ("최저가", "시장가", "시장 가격"))
|
||||||
|
if any(w in text for w in forbidden):
|
||||||
|
return False
|
||||||
|
allowed = _allowed_amounts(ctx)
|
||||||
|
for num in re.findall(r"\d{3,}", text.replace(",", "")):
|
||||||
|
if num not in allowed:
|
||||||
|
return False # 프롬프트에 없던 금액 생성 = 할루시네이션
|
||||||
|
if step in ("자율_역제안", "자율_최종제안"):
|
||||||
|
return _digits(ctx.get("autonomy_offer")) in _digits(text)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def generate(step: str, ctx: dict) -> Optional[str]:
|
||||||
|
"""자율 스텝 멘트 생성. 미설정/실패/검증불통과 → None (호출부 템플릿 유지)."""
|
||||||
|
if not _configured():
|
||||||
|
return None
|
||||||
|
prompt = _prompt_for(step, ctx)
|
||||||
|
if prompt is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
from negotiation.profiling.infra.llm_adapter import chat_complete
|
||||||
|
# openai SDK 는 동기 — 이벤트루프 블로킹 방지 위해 스레드로 넘긴다.
|
||||||
|
# max_tokens 넉넉히 — Gemini 2.5 계열은 thinking 토큰이 한도에 포함돼 짧으면 본문이 잘린다.
|
||||||
|
# 시간 상한: backend→agent 타임아웃(10s)보다 확실히 짧아야 한다 — 초과 시 템플릿 폴백으로
|
||||||
|
# 협상은 즉시 계속된다("협상 응답 지연" 토스트 방지). LLM_TIMEOUT_S 로 조절.
|
||||||
|
text = await asyncio.wait_for(
|
||||||
|
asyncio.to_thread(
|
||||||
|
chat_complete,
|
||||||
|
[{"role": "system", "content": _SYSTEM}, {"role": "user", "content": prompt}],
|
||||||
|
None, False, 0.9, 2048, # temperature 0.9 — 표현 다양성 (의미는 프롬프트 가드)
|
||||||
|
),
|
||||||
|
timeout=float(os.getenv("LLM_TIMEOUT_S", "6")),
|
||||||
|
)
|
||||||
|
text = (text or "").strip().strip('"')
|
||||||
|
if _guard(step, ctx, text):
|
||||||
|
return text
|
||||||
|
LOG.w(f"[MentGenerator] 가드레일 불통과 → 템플릿 폴백 (step={step})")
|
||||||
|
return None
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(f"[MentGenerator] LLM 실패 → 템플릿 폴백: {ex}")
|
||||||
|
return None
|
||||||
@@ -27,8 +27,7 @@ _ONE_TO_ONE_QT_TYPES = (1, 3)
|
|||||||
|
|
||||||
# 유통 코드: SupplierType(1=distribution 유통, 2=manufacture 제조, 3=sole_agency 총판)
|
# 유통 코드: SupplierType(1=distribution 유통, 2=manufacture 제조, 3=sole_agency 총판)
|
||||||
# → 테넌트 code_map 키(A/B/C). 제조→A, 총판→B, 유통→C (0=none/NULL 은 미지정 → 호출부 기본값).
|
# → 테넌트 code_map 키(A/B/C). 제조→A, 총판→B, 유통→C (0=none/NULL 은 미지정 → 호출부 기본값).
|
||||||
# 소스 우선순위: partner.supplier_items.supply_type(이 협력사×이 상품 매핑, 2026-07-07 신설)
|
# 소스: partner.supplier_items.supply_type(이 협력사×이 상품 매핑).
|
||||||
# → quotations.supplier_type(재견적 1:1 견적 기록 — 매핑 부재 시 폴백).
|
|
||||||
_SUPPLIER_TYPE_TO_CODE = {2: "A", 3: "B", 1: "C"}
|
_SUPPLIER_TYPE_TO_CODE = {2: "A", 3: "B", 1: "C"}
|
||||||
|
|
||||||
|
|
||||||
@@ -42,15 +41,26 @@ class NegotiationDbContext:
|
|||||||
item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0
|
item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0
|
||||||
partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE
|
partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE
|
||||||
revenue_amount: float # 매출액(원) — suppliers.total_revenue(KTC 미러). 없으면 0
|
revenue_amount: float # 매출액(원) — suppliers.total_revenue(KTC 미러). 없으면 0
|
||||||
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type → quotations.supplier_type. 미지정 시 None
|
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type. 미지정 시 None
|
||||||
|
selected_nego_card_numbers: list[str] # 견적 생성 시 선택된 일반 협상카드 번호(card.nego_cards.number)
|
||||||
|
selected_wild_card_numbers: list[str] # 견적 생성 시 선택된 와일드카드 번호(card.wild_cards.number)
|
||||||
|
# ---- 자율 에이전트 v3 상태 특징 소스 (없으면 0/None — 특징은 중립 기본값으로 폴백) ----
|
||||||
|
internet_lowest_price: int = 0 # items.internet_lowest_price (미수집 0)
|
||||||
|
deadline_end_ts: Optional[float] = None # 견적 마감(epoch 초) — quotations.end_time
|
||||||
|
deadline_total_s: Optional[float] = None # 협상 전체 기간(초) — end−start
|
||||||
|
hist_n: int = 0 # 이 협력사와의 과거 협상 횟수
|
||||||
|
hist_success: Optional[float] = None # 과거 성사율 (이력 없으면 None)
|
||||||
|
hist_settle_ratio: Optional[float] = None # 과거 평균 타결가/목표가 (성사 이력 없으면 None)
|
||||||
|
|
||||||
|
|
||||||
class NegotiationContextLoader:
|
class NegotiationContextLoader:
|
||||||
def __init__(self, crud: Optional[INegoContextCRUD] = None):
|
def __init__(self, crud: Optional[INegoContextCRUD] = None):
|
||||||
self.crud: INegoContextCRUD = crud or NegoContextCRUD()
|
self.crud: INegoContextCRUD = crud or NegoContextCRUD()
|
||||||
|
|
||||||
async def load(self, session_id: Optional[str]) -> Optional[NegotiationDbContext]:
|
async def load(self, session_id: Optional[str],
|
||||||
"""session_id 로 협상 컨텍스트 조회. 행이 없거나 조회 실패 시 None(호출부 기본값 폴백)."""
|
company_id: Optional[str] = None) -> Optional[NegotiationDbContext]:
|
||||||
|
"""session_id 로 협상 컨텍스트 조회. 행이 없거나 조회 실패 시 None(호출부 기본값 폴백).
|
||||||
|
company_id 는 협력사 이력 집계(experience_logs 테넌트 스코프)용 — 없으면 이력 특징 생략."""
|
||||||
if not session_id:
|
if not session_id:
|
||||||
return None
|
return None
|
||||||
try:
|
try:
|
||||||
@@ -76,11 +86,9 @@ class NegotiationContextLoader:
|
|||||||
# 매출액: 협력사 총매출(KTC total_revenue 미러). 미기재 시 0 → 호출부 기본값.
|
# 매출액: 협력사 총매출(KTC total_revenue 미러). 미기재 시 0 → 호출부 기본값.
|
||||||
_, revenue_amount = await self.crud.get_supplier_total_revenue(s, supplier_id)
|
_, revenue_amount = await self.crud.get_supplier_total_revenue(s, supplier_id)
|
||||||
|
|
||||||
# 유통 코드: 이 협력사×이 상품의 공급 방식(supplier_items.supply_type) 우선.
|
# 유통 코드: 이 협력사×이 상품의 공급 방식(supplier_items.supply_type).
|
||||||
# 매핑이 없으면 견적 기록(quotations.supplier_type) 폴백. 미지정 시 None → 호출부 기본값.
|
# 매핑이 없거나 미지정이면 None → 호출부 기본값.
|
||||||
_, supplier_type = await self.crud.get_supply_type(s, supplier_id, item_id)
|
_, supplier_type = await self.crud.get_supply_type(s, supplier_id, item_id)
|
||||||
if not supplier_type:
|
|
||||||
_, supplier_type = await self.crud.get_quotation_supplier_type(s, quotation_id)
|
|
||||||
|
|
||||||
# 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시).
|
# 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시).
|
||||||
_, item_price = await self.crud.get_item_price(s, item_id)
|
_, item_price = await self.crud.get_item_price(s, item_id)
|
||||||
@@ -93,6 +101,26 @@ class NegotiationContextLoader:
|
|||||||
if err != ErrorType.SUCCESS:
|
if err != ErrorType.SUCCESS:
|
||||||
supplier_count = 1
|
supplier_count = 1
|
||||||
|
|
||||||
|
# 견적 생성 모달에서 고른 카드셋. 값이 없으면 운영 DB 기준으로 "선택 카드 없음"이다.
|
||||||
|
# 데모/직접호출 경로(DB context 없음)만 ChatService 에서 기존 기본 카드셋으로 폴백한다.
|
||||||
|
_, selected_cards = await self.crud.get_quotation_card_numbers(s, quotation_id)
|
||||||
|
selected_nego_cards, selected_wild_cards = selected_cards
|
||||||
|
|
||||||
|
# ---- 자율 에이전트 v3 특징 소스 (조회 실패는 전부 중립 폴백 — 협상은 계속돼야 한다) ----
|
||||||
|
_, internet_lowest = await self.crud.get_item_internet_lowest(s, item_id)
|
||||||
|
_, period = await self.crud.get_quotation_period(s, quotation_id)
|
||||||
|
deadline_end_ts = deadline_total_s = None
|
||||||
|
if period and period[1] is not None:
|
||||||
|
end_ts = period[1].timestamp()
|
||||||
|
start_ts = period[0].timestamp() if period[0] is not None else None
|
||||||
|
total = (end_ts - start_ts) if start_ts else None
|
||||||
|
if total and total > 0:
|
||||||
|
deadline_end_ts, deadline_total_s = end_ts, total
|
||||||
|
hist_n, hist_success, hist_settle = 0, None, None
|
||||||
|
if company_id:
|
||||||
|
_, hist = await self.crud.get_supplier_history(s, company_id, supplier_id, sid)
|
||||||
|
hist_n, hist_success, hist_settle = hist
|
||||||
|
|
||||||
return NegotiationDbContext(
|
return NegotiationDbContext(
|
||||||
rq_type="재협상" if int(qt_type) in _ONE_TO_ONE_QT_TYPES else "재견적",
|
rq_type="재협상" if int(qt_type) in _ONE_TO_ONE_QT_TYPES else "재견적",
|
||||||
target_price=target,
|
target_price=target,
|
||||||
@@ -101,6 +129,14 @@ class NegotiationContextLoader:
|
|||||||
partner_type=PartnerType.from_count(supplier_count),
|
partner_type=PartnerType.from_count(supplier_count),
|
||||||
revenue_amount=revenue_amount,
|
revenue_amount=revenue_amount,
|
||||||
distribution_code=_SUPPLIER_TYPE_TO_CODE.get(supplier_type) if supplier_type else None,
|
distribution_code=_SUPPLIER_TYPE_TO_CODE.get(supplier_type) if supplier_type else None,
|
||||||
|
selected_nego_card_numbers=selected_nego_cards,
|
||||||
|
selected_wild_card_numbers=selected_wild_cards,
|
||||||
|
internet_lowest_price=internet_lowest,
|
||||||
|
deadline_end_ts=deadline_end_ts,
|
||||||
|
deadline_total_s=deadline_total_s,
|
||||||
|
hist_n=hist_n,
|
||||||
|
hist_success=hist_success,
|
||||||
|
hist_settle_ratio=hist_settle,
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -90,14 +90,15 @@ class ScriptRepository:
|
|||||||
return self.format_script(text, variables)
|
return self.format_script(text, variables)
|
||||||
|
|
||||||
async def resolve_card_script(self, action_id: int, card_id: Optional[str],
|
async def resolve_card_script(self, action_id: int, card_id: Optional[str],
|
||||||
variables: Optional[Dict[str, Any]] = None) -> Optional[str]:
|
variables: Optional[Dict[str, Any]] = None,
|
||||||
|
prefer_db: bool = False) -> Optional[str]:
|
||||||
"""카드 멘트 해석. cards.source_type == 'backoffice_db' 면 card.nego_cards.script(DB)를
|
"""카드 멘트 해석. cards.source_type == 'backoffice_db' 면 card.nego_cards.script(DB)를
|
||||||
우선 조회하고, 없거나 file 모드면 scripts_cards.json(파일) 폴백. 변수 치환 후 반환.
|
우선 조회하고, 없거나 file 모드면 scripts_cards.json(파일) 폴백. 변수 치환 후 반환.
|
||||||
|
|
||||||
DB 멘트는 백오피스(negodata)가 편집한 정본이라 파일보다 우선한다. 마커(**굵게** 등)가
|
DB 멘트는 백오피스(negodata)가 편집한 정본이라 파일보다 우선한다. 마커(**굵게** 등)가
|
||||||
섞여 있어도 agent 는 불투명 텍스트로 취급 — 표현 렌더는 프론트 소유.
|
섞여 있어도 agent 는 불투명 텍스트로 취급 — 표현 렌더는 프론트 소유.
|
||||||
"""
|
"""
|
||||||
if self._config.cards.source_type == _CARD_SOURCE_DB and card_id:
|
if (prefer_db or self._config.cards.source_type == _CARD_SOURCE_DB) and card_id:
|
||||||
db_text = await self._fetch_card_script_db(card_id)
|
db_text = await self._fetch_card_script_db(card_id)
|
||||||
if db_text:
|
if db_text:
|
||||||
return self.format_script(db_text, variables)
|
return self.format_script(db_text, variables)
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
"""완전 자율 협상 행동 공간 (numpy 전용 — 학습(tools)과 서빙(policy)이 공유).
|
||||||
|
|
||||||
|
카드 카탈로그 대신 행동의 '의미'만 남긴다:
|
||||||
|
ACCEPT 현재 제시가로 타결
|
||||||
|
WALK 협상 결렬 선언
|
||||||
|
COUNTER(q, s) "C원이면 수락" 역제안. C = anchor + q×(target−anchor), s = 화법 전략
|
||||||
|
PRESS(s) 설득 압박 (카드의 일반화 — 전략 1경쟁/2수용/3고수/4협력)
|
||||||
|
|
||||||
|
특징 벡터(ACTION_DIM=8) = 유형 one-hot(3) + 가격 위치(1) + 전략 one-hot(4).
|
||||||
|
ScoreNet(상태 + 행동특징) → 스칼라 점수로 후보 30개를 채점해 argmax 한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
COUNTER_GRID = [-0.05, 0.0, 0.25, 0.5, 0.75, 1.0] # C = anchor + q×(target−anchor)
|
||||||
|
ACTION_DIM = 3 + 1 + 4 + 1 # 유형(3) + 위치(1) + 전략(4) + 컷폭(1: 현 제시가 대비 인하 요구율)
|
||||||
|
|
||||||
|
# 자율 전용 추가 상태 (v3):
|
||||||
|
# [0] 직전 역제안 존재(0/1) [1] 직전 역제안 위치 q ← 에피소드 기억(같은 숫자 반복 방지)
|
||||||
|
# [2] 마감 잔여율(남은시간/전체, 미상 0.5) ← 견적 마감(quotations.end_time)
|
||||||
|
# [3] 과거 협상 횟수 min(n,5)/5 [4] 과거 성사율(미상 0.5)
|
||||||
|
# [5] 과거 평균 타결수준 norm((타결가/목표가−0.8)/0.4, 미상 0.5) ← 이 협력사와의 이력(experience_logs)
|
||||||
|
# [6] 인터넷최저가 갭 clip((최저가−앵커)/앵커/0.1, ±1, 미상 0) ← 숨은 하한가의 관측 가능한 힌트
|
||||||
|
# 특징은 학습 시뮬에도 동일하게 존재해야 한다(train_full_autonomy 가 대응물을 생성).
|
||||||
|
EXTRA_STATE_DIM = 7
|
||||||
|
|
||||||
|
|
||||||
|
def extra_state(last_kind: str = "", last_q: float = 0.0, deadline: float = 0.5,
|
||||||
|
hist_n: float = 0.0, hist_success: float = 0.5, hist_settle: float = 0.5,
|
||||||
|
internet_gap: float = 0.0) -> np.ndarray:
|
||||||
|
has_counter = 1.0 if last_kind == "counter" else 0.0
|
||||||
|
return np.array([
|
||||||
|
has_counter,
|
||||||
|
float(np.clip(last_q, -1.0, 1.0)) * has_counter,
|
||||||
|
float(np.clip(deadline, 0.0, 1.0)),
|
||||||
|
float(np.clip(hist_n, 0.0, 1.0)),
|
||||||
|
float(np.clip(hist_success, 0.0, 1.0)),
|
||||||
|
float(np.clip(hist_settle, 0.0, 1.0)),
|
||||||
|
float(np.clip(internet_gap, -1.0, 1.0)),
|
||||||
|
], dtype=np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
def settle_norm(avg_settle_ratio: float) -> float:
|
||||||
|
"""평균 (타결가/목표가) → 0~1 정규화 (0.8→0, 1.0→0.5, 1.2→1)."""
|
||||||
|
return float(np.clip((avg_settle_ratio - 0.8) / 0.4, 0.0, 1.0))
|
||||||
|
|
||||||
|
|
||||||
|
def internet_gap_feat(internet_lowest: float, anchor: float) -> float:
|
||||||
|
"""인터넷최저가의 앵커 대비 갭 (±10% 스케일). 최저가 없으면 0을 쓴다."""
|
||||||
|
if not internet_lowest or anchor <= 0:
|
||||||
|
return 0.0
|
||||||
|
return float(np.clip((internet_lowest - anchor) / anchor / 0.1, -1.0, 1.0))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Action:
|
||||||
|
kind: str # accept | walk | counter | press
|
||||||
|
counter_q: float = 0.0 # counter 위치 (anchor~target 스팬 비율)
|
||||||
|
strategy: int = 0 # press/counter 의 화법 전략 (1~4, 0=없음)
|
||||||
|
|
||||||
|
def feat(self, price_pos: float, cut: float = 0.0) -> np.ndarray:
|
||||||
|
"""cut: 이 행동이 요구하는 인하폭 (현 제시가 대비, counter 만 >0) — 대형컷의 무례함을
|
||||||
|
정책이 지각하게 한다. 갭이 크면 역제안 대신 압박이 낫다는 걸 배우는 근거 특징."""
|
||||||
|
t = {"accept": [1, 0, 0], "walk": [0, 1, 0]}.get(self.kind, [0, 0, 1])
|
||||||
|
pos = price_pos if self.kind == "accept" else self.counter_q
|
||||||
|
s = np.zeros(4, dtype=np.float32)
|
||||||
|
if self.strategy:
|
||||||
|
s[self.strategy - 1] = 1.0
|
||||||
|
return np.concatenate([np.array(t, dtype=np.float32),
|
||||||
|
np.array([float(np.clip(pos, -1.0, 2.0)),
|
||||||
|
], dtype=np.float32), s,
|
||||||
|
np.array([float(np.clip(cut, 0.0, 1.0))], dtype=np.float32)])
|
||||||
|
|
||||||
|
|
||||||
|
def candidate_actions():
|
||||||
|
"""전 행동 후보: 수락 1 + 결렬 1 + 역제안 6×전략4 + 압박 4 = 30."""
|
||||||
|
out = [Action("accept"), Action("walk")]
|
||||||
|
out += [Action("counter", q, s) for q in COUNTER_GRID for s in (1, 2, 3, 4)]
|
||||||
|
out += [Action("press", 0.0, s) for s in (1, 2, 3, 4)]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
ACTIONS = candidate_actions()
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
"""FeatureDQNPolicy — action-as-feature DQN (Phase 2·3).
|
||||||
|
|
||||||
|
고정 슬롯 Q(s)→[11개] 대신 ScoreNet(상태벡터 + 카드임베딩) → 스칼라 점수.
|
||||||
|
결정 시 가용 카드 풀을 순회 채점해 argmax → 카드 추가/삭제/새 카드(zero-shot)에 구조 변화 없음.
|
||||||
|
협력사 특징은 상태벡터에 포함(feature_builder) → '협력사를 입력으로' 달성.
|
||||||
|
|
||||||
|
가변 행동 학습: replay 에 다음 상태의 '가용 카드 임베딩들'을 함께 저장,
|
||||||
|
target = r + γ · max_{c'∈next_avail} Q(s', c') · (1-done)
|
||||||
|
"""
|
||||||
|
|
||||||
|
import math
|
||||||
|
import random
|
||||||
|
from collections import deque
|
||||||
|
from typing import Dict, List, Optional, Tuple
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
|
||||||
|
|
||||||
|
class ScoreNet(nn.Module):
|
||||||
|
"""(상태 + 카드임베딩) → 스칼라 점수."""
|
||||||
|
|
||||||
|
def __init__(self, state_dim: int, card_dim: int, hidden: int = 128):
|
||||||
|
super().__init__()
|
||||||
|
self.net = nn.Sequential(
|
||||||
|
nn.Linear(state_dim + card_dim, hidden), nn.ReLU(),
|
||||||
|
nn.Linear(hidden, hidden), nn.ReLU(),
|
||||||
|
nn.Linear(hidden, 1),
|
||||||
|
)
|
||||||
|
|
||||||
|
def forward(self, x: torch.Tensor) -> torch.Tensor: # x: [B, state+card]
|
||||||
|
return self.net(x).squeeze(-1) # [B]
|
||||||
|
|
||||||
|
|
||||||
|
class FeatureDQNPolicy:
|
||||||
|
name = "feature_dqn"
|
||||||
|
|
||||||
|
def __init__(self, state_dim: int, card_dim: int, device: str = "cpu",
|
||||||
|
lr: float = 1e-3, gamma: float = 0.95, hidden: int = 128,
|
||||||
|
eps_start: float = 1.0, eps_end: float = 0.05, eps_decay: int = 6000,
|
||||||
|
buffer_size: int = 50_000, batch_size: int = 64, target_sync: int = 500):
|
||||||
|
self.device = device
|
||||||
|
self.gamma = gamma
|
||||||
|
self.batch_size = batch_size
|
||||||
|
self.target_sync = target_sync
|
||||||
|
self.q = ScoreNet(state_dim, card_dim, hidden).to(device)
|
||||||
|
self.tgt = ScoreNet(state_dim, card_dim, hidden).to(device)
|
||||||
|
self.tgt.load_state_dict(self.q.state_dict())
|
||||||
|
self.opt = torch.optim.Adam(self.q.parameters(), lr=lr)
|
||||||
|
self.buf: deque = deque(maxlen=buffer_size)
|
||||||
|
self.eps_start, self.eps_end, self.eps_decay = eps_start, eps_end, eps_decay
|
||||||
|
self.steps = 0
|
||||||
|
self.greedy = False # 평가 모드(탐색 끔)
|
||||||
|
|
||||||
|
# ---- 탐색 스케줄 ----------------------------------------------------
|
||||||
|
def eps(self) -> float:
|
||||||
|
if self.greedy:
|
||||||
|
return 0.0
|
||||||
|
return self.eps_end + (self.eps_start - self.eps_end) * math.exp(-self.steps / self.eps_decay)
|
||||||
|
|
||||||
|
# ---- 채점/선택 -------------------------------------------------------
|
||||||
|
def scores(self, state_feat: np.ndarray, card_embs: np.ndarray) -> np.ndarray:
|
||||||
|
"""가용 카드 K개 일괄 채점. card_embs: [K, card_dim] → [K]."""
|
||||||
|
k = card_embs.shape[0]
|
||||||
|
x = np.concatenate([np.repeat(state_feat[None, :], k, axis=0), card_embs], axis=1)
|
||||||
|
with torch.no_grad():
|
||||||
|
return self.q(torch.tensor(x, device=self.device)).cpu().numpy()
|
||||||
|
|
||||||
|
def select(self, state_feat: np.ndarray, card_embs: np.ndarray) -> Tuple[int, float, float]:
|
||||||
|
"""(선택 인덱스, propensity, 선택 점수). 인덱스는 card_embs 행 기준."""
|
||||||
|
k = card_embs.shape[0]
|
||||||
|
sc = self.scores(state_feat, card_embs)
|
||||||
|
e = self.eps()
|
||||||
|
if random.random() < e:
|
||||||
|
i = random.randrange(k)
|
||||||
|
prop = e / k
|
||||||
|
else:
|
||||||
|
i = int(sc.argmax())
|
||||||
|
prop = (1.0 - e) + e / k
|
||||||
|
return i, prop, float(sc[i])
|
||||||
|
|
||||||
|
# ---- 경험/학습 -------------------------------------------------------
|
||||||
|
def remember(self, state_feat: np.ndarray, card_emb: np.ndarray, reward: float,
|
||||||
|
next_state_feat: Optional[np.ndarray], next_card_embs: Optional[np.ndarray],
|
||||||
|
done: bool):
|
||||||
|
self.buf.append((state_feat, card_emb, reward, next_state_feat, next_card_embs, done))
|
||||||
|
|
||||||
|
def train_step(self) -> Optional[float]:
|
||||||
|
if len(self.buf) < self.batch_size:
|
||||||
|
return None
|
||||||
|
batch = random.sample(self.buf, self.batch_size)
|
||||||
|
|
||||||
|
# Q(s, a_chosen)
|
||||||
|
xs = np.stack([np.concatenate([s, c]) for s, c, *_ in batch])
|
||||||
|
q_sa = self.q(torch.tensor(xs, device=self.device))
|
||||||
|
|
||||||
|
# target = r + γ·max_{c'} Q_tgt(s', c') — 가변 후보라 후보 전체를 한 번에 forward 후 세그먼트 max
|
||||||
|
rewards = torch.tensor([b[2] for b in batch], device=self.device, dtype=torch.float32)
|
||||||
|
dones = torch.tensor([float(b[5]) for b in batch], device=self.device)
|
||||||
|
next_rows, owner = [], []
|
||||||
|
for bi, (_, _, _, s2, cands, done) in enumerate(batch):
|
||||||
|
if done or s2 is None or cands is None or len(cands) == 0:
|
||||||
|
continue
|
||||||
|
for c in cands:
|
||||||
|
next_rows.append(np.concatenate([s2, c]))
|
||||||
|
owner.append(bi)
|
||||||
|
q_next_max = torch.zeros(self.batch_size, device=self.device)
|
||||||
|
if next_rows:
|
||||||
|
with torch.no_grad():
|
||||||
|
q_all = self.tgt(torch.tensor(np.stack(next_rows), device=self.device))
|
||||||
|
owner_t = torch.tensor(owner, device=self.device)
|
||||||
|
q_next_max = q_next_max.index_reduce_(0, owner_t, q_all, "amax", include_self=False)
|
||||||
|
target = rewards + self.gamma * q_next_max * (1.0 - dones)
|
||||||
|
|
||||||
|
loss = nn.functional.smooth_l1_loss(q_sa, target)
|
||||||
|
self.opt.zero_grad()
|
||||||
|
loss.backward()
|
||||||
|
self.opt.step()
|
||||||
|
self.steps += 1
|
||||||
|
if self.steps % self.target_sync == 0:
|
||||||
|
self.tgt.load_state_dict(self.q.state_dict())
|
||||||
|
return float(loss)
|
||||||
|
|
||||||
|
# ---- 저장/로드 -------------------------------------------------------
|
||||||
|
def save(self, path: str):
|
||||||
|
torch.save(self.q.state_dict(), path)
|
||||||
|
|
||||||
|
def load(self, path: str):
|
||||||
|
sd = torch.load(path, map_location=self.device)
|
||||||
|
self.q.load_state_dict(sd)
|
||||||
|
self.tgt.load_state_dict(sd)
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
"""AutonomyStore — 완전 자율 협상 정책 서빙 (룰 대체, numpy 전용).
|
||||||
|
|
||||||
|
AUTONOMY_MODE=1 이면 가격협상 판정 룰(앵커 이하 타결 / 와일드카드 존 / 라운드 상한)과
|
||||||
|
카드 선택을 전부 이 정책의 행동 결정으로 대체한다:
|
||||||
|
accept → 협상완료 (제시가 타결) walk → 협상실패
|
||||||
|
counter → "C원이면 수락" 역제안 스텝 press → 전략별 압박 멘트 스텝
|
||||||
|
|
||||||
|
행동의 유일한 유인은 보상 함수다. 남는 제한은 두 가지뿐이며 비즈니스 룰이 아니다:
|
||||||
|
- 역제안 후보 격자가 [anchor−5%span, target] 안 (행동 공간 정의)
|
||||||
|
- 세션 턴 상한(엔지니어링 타임아웃, ChatEngine._AUTONOMY_TURN_CAP)
|
||||||
|
|
||||||
|
번들: artifacts/autonomy_serving.npz (tools/export_autonomy_serving.py).
|
||||||
|
불가(플래그 꺼짐/번들 없음)면 None → 기존 룰 엔진 그대로 (즉시 롤백 경로).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from common.logger import LOG
|
||||||
|
from negotiation.policies.autonomy_actions import (
|
||||||
|
ACTIONS, Action, extra_state, internet_gap_feat, settle_norm)
|
||||||
|
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||||
|
from negotiation.qtable.domain.service.feature_builder import (
|
||||||
|
build_state_features, build_tenant_features)
|
||||||
|
|
||||||
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
BUNDLE_PATH = os.path.join(_HERE, "..", "..", "artifacts", "autonomy_serving.npz")
|
||||||
|
|
||||||
|
|
||||||
|
class AutonomyPolicy:
|
||||||
|
"""세션 컨텍스트 → 상태특징 → 행동(greedy). ChatEngine 에 decider 로 주입된다."""
|
||||||
|
|
||||||
|
name = "full_autonomy"
|
||||||
|
|
||||||
|
def __init__(self, z, reward_cfg):
|
||||||
|
self._W = (z["W0"], z["b0"], z["W1"], z["b1"], z["W2"], z["b2"])
|
||||||
|
self._state_dim = int(z["state_dim"])
|
||||||
|
self._tenant_feat = build_tenant_features(reward_cfg)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _acceptance(ctx: dict) -> float:
|
||||||
|
base = ctx.get("item_price") or ctx.get("first_offer_price") or 0
|
||||||
|
cur = ctx.get("input_price") or 0
|
||||||
|
if base <= 0 or cur <= 0:
|
||||||
|
return 0.0
|
||||||
|
return max(0.0, (base - cur) / base)
|
||||||
|
|
||||||
|
def decide(self, ctx: dict) -> Action:
|
||||||
|
"""ChatSession.context → Action. 상태 구성은 ChatService._snapshot 과 동일 규칙."""
|
||||||
|
snap = NegotiationSnapshot(
|
||||||
|
revenue_amount=ctx["revenue_amount"], distribution_code=ctx["distribution_code"],
|
||||||
|
partner_count=ctx["partner_count"], acceptance_ratio=self._acceptance(ctx),
|
||||||
|
input_price=ctx.get("input_price", ctx["anchor_price"]), anchor_price=ctx["anchor_price"],
|
||||||
|
target_price=ctx["target_price"], round_number=ctx.get("round", 0),
|
||||||
|
)
|
||||||
|
# v3 추가 특징: 직전 역제안 기억 + 마감 잔여율 + 협력사 이력 + 인터넷최저가 갭.
|
||||||
|
# 소스가 없으면 전부 중립값(0.5/0) — 학습 시뮬의 '미상' 표현과 동일해야 한다.
|
||||||
|
# 역제안 기억은 autonomy_last_counter(역제안만 갱신) — autonomy_last(마지막 행동)를 쓰면
|
||||||
|
# 사이에 낀 설득이 기억을 지워 단조 봉투가 뚫린다(counter→press→counter 철회 실버그).
|
||||||
|
# 시뮬의 last_kind/last_q 도 역제안만 추적하므로 이쪽이 학습 분포와도 일치한다.
|
||||||
|
last = ctx.get("autonomy_last_counter") or {}
|
||||||
|
deadline = 0.5
|
||||||
|
end_ts, total_s = ctx.get("deadline_end_ts"), ctx.get("deadline_total_s")
|
||||||
|
if end_ts and total_s:
|
||||||
|
import time
|
||||||
|
deadline = float(np.clip((end_ts - time.time()) / total_s, 0.0, 1.0))
|
||||||
|
hist_n = int(ctx.get("hist_n") or 0)
|
||||||
|
hist_success = float(ctx["hist_success"]) if ctx.get("hist_success") is not None else 0.5
|
||||||
|
hist_settle = (settle_norm(float(ctx["hist_settle_ratio"]))
|
||||||
|
if ctx.get("hist_settle_ratio") is not None else 0.5)
|
||||||
|
sf = np.concatenate([build_state_features(snap), self._tenant_feat, extra_state(
|
||||||
|
last.get("kind", ""), float(last.get("q", 0.0)),
|
||||||
|
deadline=deadline, hist_n=min(hist_n, 5) / 5.0,
|
||||||
|
hist_success=hist_success if hist_n else 0.5,
|
||||||
|
hist_settle=hist_settle,
|
||||||
|
internet_gap=internet_gap_feat(float(ctx.get("internet_lowest_price") or 0),
|
||||||
|
float(snap.anchor_price)),
|
||||||
|
)])
|
||||||
|
span = max(snap.target_price - snap.anchor_price, 1.0)
|
||||||
|
pos = (snap.input_price - snap.anchor_price) / span
|
||||||
|
# 행동 봉투 (학습 available_actions 와 동일해야 한다):
|
||||||
|
# ① 목표가 초과 제시가는 '수락' 제외 — 매입 승인 범위(v3.1 착취 방지)
|
||||||
|
# ② 직전 역제안보다 낮은 금액의 역제안 제외 — 단조 양보 원칙(제안 철회는 협상 예절 위반;
|
||||||
|
# 올리는 '속도'는 정책 학습, 후퇴 '금지'만 구조로 보장)
|
||||||
|
# ③ 역제시 해금 조건 — 옛 제품 의미론 복원(제품 결정 2026-07-10): 일반 카드는 설득만,
|
||||||
|
# 역제시(숫자 제안)는 와일드카드처럼 마무리 수단. 최소 AUTONOMY_MIN_PRESS(기본 2)회
|
||||||
|
# 설득 이후에만 역제시 후보가 열린다. 해금 후의 타이밍·금액은 정책 학습.
|
||||||
|
# ④ 마무리 국면 — 제시가가 목표가 0.5% 이내로 붙으면 압박 제외(+역제시 잠금 해제):
|
||||||
|
# 푼돈 차이에서 '재검토 부탁' 반복은 상대만 지치게 한다. 클로징(역제안/최종제안)하거나 끝내거나.
|
||||||
|
min_press = int(os.getenv("AUTONOMY_MIN_PRESS", "2"))
|
||||||
|
near_target = snap.input_price <= snap.target_price * 1.005
|
||||||
|
counter_locked = (int(ctx.get("autonomy_press_n") or 0) < min_press) and not near_target
|
||||||
|
last_counter_q = float(last["q"]) if last.get("kind") == "counter" else None
|
||||||
|
if last_counter_q is not None:
|
||||||
|
counter_locked = False # 이미 역제시를 시작했으면 잠그지 않는다(단조 봉투가 관리)
|
||||||
|
# ⑤ 첫 역제안은 앵커가 이하(q ≤ 0)만 — 낮게 개시해 목표가까지 천천히 올라간다
|
||||||
|
# (제품 결정: 사다리를 다 쓰는 앵커링 개시. 이후 단조 봉투가 상향을 관리).
|
||||||
|
# ⑥ 결렬(walk)도 해금 전 금지 — 설득 0회에 walk 를 고르면 최종제안 보장(엔진)과 결합해
|
||||||
|
# '첫 턴 목표가 통보'가 된다(v3.4 라이브 결함). 해금 전에는 설득만 가능.
|
||||||
|
cands = [a for a in ACTIONS
|
||||||
|
if not (a.kind == "accept" and snap.input_price > snap.target_price)
|
||||||
|
and not (a.kind == "counter" and counter_locked)
|
||||||
|
and not (a.kind == "walk" and counter_locked)
|
||||||
|
and not (a.kind == "press" and near_target)
|
||||||
|
and not (a.kind == "counter" and last_counter_q is None and a.counter_q > 1e-9)
|
||||||
|
and not (a.kind == "counter" and last_counter_q is not None
|
||||||
|
and a.counter_q < last_counter_q - 1e-9)]
|
||||||
|
feats = []
|
||||||
|
for a in cands:
|
||||||
|
cut = 0.0
|
||||||
|
if a.kind == "counter":
|
||||||
|
c = snap.anchor_price + a.counter_q * span
|
||||||
|
cut = max(0.0, (snap.input_price - c) / max(snap.input_price, 1.0))
|
||||||
|
feats.append(a.feat(pos, cut))
|
||||||
|
feats = np.stack(feats)
|
||||||
|
W0, b0, W1, b1, W2, b2 = self._W
|
||||||
|
x = np.concatenate([np.repeat(sf[None, :], feats.shape[0], axis=0), feats], axis=1)
|
||||||
|
h = np.maximum(x @ W0.T + b0, 0.0)
|
||||||
|
h = np.maximum(h @ W1.T + b1, 0.0)
|
||||||
|
scores = (h @ W2.T + b2).squeeze(-1)
|
||||||
|
return cands[int(np.argmax(scores))]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def counter_price(ctx: dict, act: Action) -> int:
|
||||||
|
span = max(ctx["target_price"] - ctx["anchor_price"], 1.0)
|
||||||
|
return int(round(ctx["anchor_price"] + act.counter_q * span))
|
||||||
|
|
||||||
|
|
||||||
|
class AutonomyStore:
|
||||||
|
_z = None
|
||||||
|
_load_failed = False
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def enabled(cls) -> bool:
|
||||||
|
return os.getenv("AUTONOMY_MODE", "0").lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def policy_for(cls, engine) -> Optional[AutonomyPolicy]:
|
||||||
|
"""engine: tenancy.registry.TenantEngine. 비활성/번들 없음 → None (룰 엔진 유지)."""
|
||||||
|
if not cls.enabled() or cls._load_failed:
|
||||||
|
return None
|
||||||
|
if cls._z is None:
|
||||||
|
try:
|
||||||
|
cls._z = np.load(BUNDLE_PATH, allow_pickle=False)
|
||||||
|
LOG.i("[Autonomy] 완전 자율 정책 번들 로드 완료 — 협상 판정 룰 대체 모드")
|
||||||
|
except Exception as ex:
|
||||||
|
cls._load_failed = True
|
||||||
|
LOG.e_no_callstack(f"[Autonomy] 번들 로드 실패 → 룰 엔진 유지: {ex}")
|
||||||
|
return None
|
||||||
|
return AutonomyPolicy(cls._z, engine.config.reward)
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
"""DQNServingStore — action-as-feature DQN 서빙 (선택 전용, 학습 없음).
|
||||||
|
|
||||||
|
tools/export_dqn_serving.py 가 만든 dqn_serving.npz(ScoreNet 가중치 + 카드특징 392차원)를
|
||||||
|
numpy 로 추론한다 — 서빙 컨테이너에 PyTorch 불필요.
|
||||||
|
|
||||||
|
역할 분담(계획서 H 트랙으로 가기 전 파일럿):
|
||||||
|
- 카드 '선택'만 DQN(greedy). Q-table 학습/영속/experience_logs 로깅 경로는 기존 그대로 유지
|
||||||
|
(Q-learning 은 오프폴리시라 DQN 이 고른 행동으로 갱신해도 유효, 로그는 DQN 오프라인 재학습 재료).
|
||||||
|
- 폴백: 플래그 꺼짐 / 번들 없음 / 가용 카드 전부 특징 미보유(신규 카드) → None 반환,
|
||||||
|
호출부(ChatService)가 기존 UCB Q-table 선택으로 진행한다.
|
||||||
|
|
||||||
|
활성화: 환경변수 DQN_SERVING=1 (docker-compose agent environment).
|
||||||
|
신규 카드 주의: 번들에 없는 카드번호는 후보에서 제외된다 — 카드 추가 시
|
||||||
|
tools/build_card_embeddings.py → tools/export_dqn_serving.py 재실행 후 재배포 필요.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from common.logger import LOG
|
||||||
|
from negotiation.policies.base import ActionDecision, PolicyContext
|
||||||
|
from negotiation.qtable.domain.service.feature_builder import (
|
||||||
|
build_state_features, build_tenant_features)
|
||||||
|
|
||||||
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
BUNDLE_PATH = os.path.join(_HERE, "..", "..", "artifacts", "dqn_serving.npz")
|
||||||
|
|
||||||
|
|
||||||
|
class _Bundle:
|
||||||
|
def __init__(self, z):
|
||||||
|
self.W0, self.b0 = z["W0"], z["b0"]
|
||||||
|
self.W1, self.b1 = z["W1"], z["b1"]
|
||||||
|
self.W2, self.b2 = z["W2"], z["b2"]
|
||||||
|
self.state_dim = int(z["state_dim"])
|
||||||
|
self.card_feats = {str(n): z["card_feats"][i]
|
||||||
|
for i, n in enumerate(z["card_numbers"])}
|
||||||
|
|
||||||
|
def scores(self, state_feat: np.ndarray, card_feats: np.ndarray) -> np.ndarray:
|
||||||
|
"""가용 카드 K개 일괄 채점: [K, state+card] → [K]."""
|
||||||
|
k = card_feats.shape[0]
|
||||||
|
x = np.concatenate([np.repeat(state_feat[None, :], k, axis=0), card_feats], axis=1)
|
||||||
|
h = np.maximum(x @ self.W0.T + self.b0, 0.0)
|
||||||
|
h = np.maximum(h @ self.W1.T + self.b1, 0.0)
|
||||||
|
return (h @ self.W2.T + self.b2).squeeze(-1)
|
||||||
|
|
||||||
|
|
||||||
|
class DQNServingPolicy:
|
||||||
|
"""UCBQTablePolicy.select 와 동일한 PolicyContext → ActionDecision 계약(선택 전용)."""
|
||||||
|
|
||||||
|
name = "feature_dqn"
|
||||||
|
_EPS = 0.1 # propensity 근사용 ε (UCB 정책과 동일 관례 — OPE 지지 확보용, 선택은 greedy)
|
||||||
|
|
||||||
|
def __init__(self, bundle: _Bundle, engine): # engine: tenancy.registry.TenantEngine
|
||||||
|
self._bundle = bundle
|
||||||
|
self._mapper = engine.mapper
|
||||||
|
self._tenant_feat = build_tenant_features(engine.config.reward)
|
||||||
|
|
||||||
|
def _available(self, ctx: PolicyContext) -> List[int]:
|
||||||
|
# UCBQTablePolicy._available 과 동일 규칙 (마스크 → used 제외 → 소진 시 전체 허용)
|
||||||
|
if ctx.available_mask is not None:
|
||||||
|
avail = [a for a in range(ctx.action_space_size) if ctx.available_mask[a]]
|
||||||
|
else:
|
||||||
|
used = ctx.episode.used_action_ids if ctx.episode else set()
|
||||||
|
avail = [a for a in range(ctx.action_space_size) if a not in used]
|
||||||
|
return avail or list(range(ctx.action_space_size))
|
||||||
|
|
||||||
|
def select(self, ctx: PolicyContext) -> Optional[ActionDecision]:
|
||||||
|
"""카드특징이 있는 가용 카드가 없으면 None → 호출부가 Q-table 로 폴백."""
|
||||||
|
candidates = [] # (action_id, card_feat)
|
||||||
|
for a in self._available(ctx):
|
||||||
|
num = self._mapper.get_card_id(a)
|
||||||
|
feat = self._bundle.card_feats.get(num) if num else None
|
||||||
|
if feat is not None:
|
||||||
|
candidates.append((a, feat))
|
||||||
|
if not candidates:
|
||||||
|
return None
|
||||||
|
state_feat = np.concatenate([build_state_features(ctx.snapshot), self._tenant_feat])
|
||||||
|
if state_feat.shape[0] != self._bundle.state_dim:
|
||||||
|
LOG.e_no_callstack(
|
||||||
|
f"[DQNServing] state_dim 불일치: {state_feat.shape[0]} != {self._bundle.state_dim}")
|
||||||
|
return None
|
||||||
|
sc = self._bundle.scores(state_feat, np.stack([f for _, f in candidates]))
|
||||||
|
i = int(sc.argmax())
|
||||||
|
n = len(candidates)
|
||||||
|
return ActionDecision(
|
||||||
|
action_id=candidates[i][0],
|
||||||
|
propensity=(1.0 - self._EPS) + self._EPS / n,
|
||||||
|
q_value=float(sc[i]),
|
||||||
|
ucb_score=float(sc[i]),
|
||||||
|
available_actions=[a for a, _ in candidates],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class DQNServingStore:
|
||||||
|
"""번들 lazy 로드 + 캐시. 비활성/부재 시 None (호출부 Q-table 폴백)."""
|
||||||
|
|
||||||
|
_bundle: Optional[_Bundle] = None
|
||||||
|
_load_failed = False
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def enabled(cls) -> bool:
|
||||||
|
return os.getenv("DQN_SERVING", "0").lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def policy_for(cls, engine) -> Optional[DQNServingPolicy]:
|
||||||
|
if not cls.enabled() or cls._load_failed:
|
||||||
|
return None
|
||||||
|
if cls._bundle is None:
|
||||||
|
try:
|
||||||
|
cls._bundle = _Bundle(np.load(BUNDLE_PATH, allow_pickle=False))
|
||||||
|
LOG.i(f"[DQNServing] 번들 로드 완료: 카드 {len(cls._bundle.card_feats)}장")
|
||||||
|
except Exception as ex:
|
||||||
|
cls._load_failed = True # 요청마다 재시도하지 않음
|
||||||
|
LOG.e_no_callstack(f"[DQNServing] 번들 로드 실패 → Q-table 폴백: {ex}")
|
||||||
|
return None
|
||||||
|
return DQNServingPolicy(cls._bundle, engine)
|
||||||
@@ -10,6 +10,7 @@ P5/H 트랙에서 transition_id 기반으로 정교화한다.
|
|||||||
import math
|
import math
|
||||||
from typing import Tuple
|
from typing import Tuple
|
||||||
|
|
||||||
|
from common.logger import LOG
|
||||||
from negotiation.policies.qtable_policy import UCBQTablePolicy
|
from negotiation.policies.qtable_policy import UCBQTablePolicy
|
||||||
from negotiation.qtable.domain.model.q_table import QTable
|
from negotiation.qtable.domain.model.q_table import QTable
|
||||||
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
||||||
@@ -26,20 +27,42 @@ class QTablePolicyStore:
|
|||||||
lr = pol_cfg.learning_rate
|
lr = pol_cfg.learning_rate
|
||||||
gamma = pol_cfg.gamma
|
gamma = pol_cfg.gamma
|
||||||
|
|
||||||
|
# 현재 카탈로그 스냅샷(action_id → 카드번호). 버전에 저장해 카드번호 기반 마이그레이션에 쓴다.
|
||||||
|
card_list = [engine.mapper.get_card_id(i) for i in range(A)]
|
||||||
|
|
||||||
# cold-start 3단 (계획서 D):
|
# cold-start 3단 (계획서 D):
|
||||||
# ① 활성 버전 있으면 그대로 ② 없고 inherits_base 면 base warm-start 복제(차원 호환 시)
|
# ① 활성 버전 있으면 그대로 ② 없고 inherits_base 면 base warm-start 복제(차원 호환 시)
|
||||||
# ③ 차원 불일치/base 없음 → 휴리스틱 빈 버전
|
# ③ 차원 불일치/base 없음 → 휴리스틱 빈 버전
|
||||||
err, active = await repo.read(lambda s: repo.get_active_version(s))
|
err, active = await repo.read(lambda s: repo.get_active_version(s))
|
||||||
if active is not None:
|
if active is not None:
|
||||||
version_id = active.version_id
|
dim_changed = active.action_space_size != A or active.state_space_size != S
|
||||||
|
# 동일 차원이라도 카탈로그 내용(카드 구성)이 바뀌면 마이그레이션(카드번호 리맵).
|
||||||
|
# 레거시 버전(action_cards=None)은 옛 구성을 몰라 내용변경 감지 불가 → 차원만 본다.
|
||||||
|
cards_changed = active.action_cards is not None and list(active.action_cards) != card_list
|
||||||
|
if dim_changed or cards_changed:
|
||||||
|
# 카드번호 기반 학습 보존 마이그레이션: 같은 카드의 Q값을 새 action_id 로 이동.
|
||||||
|
migrated = await repo.migrate_active_version_dim(
|
||||||
|
old_version=active, state_space_size=S, action_space_size=A,
|
||||||
|
learning_rate=lr, discount_factor=gamma, version_name=f"v_migrated_a{A}",
|
||||||
|
action_cards=card_list)
|
||||||
|
if migrated is not None:
|
||||||
|
LOG.i(f"[QTablePolicyStore] 카탈로그 변경 마이그레이션 company={engine.company_id} "
|
||||||
|
f"action {active.action_space_size}→{A} (카드번호 리맵, 학습 보존)")
|
||||||
|
version_id = migrated or active.version_id
|
||||||
|
else:
|
||||||
|
version_id = active.version_id
|
||||||
|
if active.action_cards is None: # 레거시 버전 backfill → 향후 카탈로그 변경 감지 가능
|
||||||
|
await repo.set_version_action_cards(version_id, card_list)
|
||||||
else:
|
else:
|
||||||
version_id = None
|
version_id = None
|
||||||
if engine.config.inherits_base:
|
if engine.config.inherits_base:
|
||||||
version_id = await repo.warm_start_from_base(
|
version_id = await repo.warm_start_from_base(
|
||||||
state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma)
|
state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma,
|
||||||
|
action_cards=card_list)
|
||||||
if version_id is None:
|
if version_id is None:
|
||||||
version_id = await repo.get_or_create_active_version(
|
version_id = await repo.get_or_create_active_version(
|
||||||
state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma)
|
state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma,
|
||||||
|
action_cards=card_list)
|
||||||
|
|
||||||
qtable = QTable(S, A, learning_rate=lr, discount_factor=gamma)
|
qtable = QTable(S, A, learning_rate=lr, discount_factor=gamma)
|
||||||
qrows, vrows = await repo.load_cells(version_id)
|
qrows, vrows = await repo.load_cells(version_id)
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""build_state_features — snapshot(raw 연속값) → 실수 벡터 (DQN/action-as-feature 용).
|
||||||
|
|
||||||
|
state_calculator.build_state(이산화)와 대비되는 연속 표현. 이산화(등급/162칸)를 하지 않고
|
||||||
|
정규화된 raw 값을 그대로 벡터로 내보낸다. 협력사 특징(매출·경쟁사수·유통)이 벡터에 포함되므로
|
||||||
|
'협력사를 입력으로'(Phase 3)가 자연스럽게 달성된다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||||
|
|
||||||
|
DIST_CLASSES = ("A", "B", "C")
|
||||||
|
STATE_FEATURE_DIM = 9 # build_state_features 벡터 길이. feature 추가 시 갱신.
|
||||||
|
TENANT_FEATURE_DIM = 5 # build_tenant_features 벡터 길이.
|
||||||
|
|
||||||
|
|
||||||
|
def build_tenant_features(reward_cfg) -> np.ndarray:
|
||||||
|
"""고객사 '성향'을 ID 가 아니라 보상 설정값(내용)으로 벡터화 (Phase 3 고객사 조건화).
|
||||||
|
|
||||||
|
새 고객사도 tenant.yaml 의 reward 설정만 있으면 즉시 조건화된다 (cold-start 없음).
|
||||||
|
"""
|
||||||
|
return np.array([
|
||||||
|
reward_cfg.max_weight, # 가격 중시 정도 (W↑ = 가격보상 비중↑)
|
||||||
|
reward_cfg.success_reward / 2.0, # 성사를 얼마나 크게 치는가
|
||||||
|
-reward_cfg.failure_penalty / 2.0, # 결렬을 얼마나 무서워하는가
|
||||||
|
reward_cfg.penalty_lambda * 20.0, # 속도 성향 (오래 끌수록 벌점)
|
||||||
|
reward_cfg.beta, # 앵커 초과달성 보너스 성향
|
||||||
|
], dtype=np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
def build_state_features(s: NegotiationSnapshot) -> np.ndarray:
|
||||||
|
"""정규화된 연속 상태 벡터. 등급화 없음 — 990원과 850원이 구별된다."""
|
||||||
|
dist_onehot = [1.0 if s.distribution_code == c else 0.0 for c in DIST_CLASSES]
|
||||||
|
anchor = max(s.anchor_price, 1.0)
|
||||||
|
target = max(s.target_price, 1.0)
|
||||||
|
return np.array([
|
||||||
|
min(s.revenue_amount, 5e8) / 5e8, # 협력사 매출 (0~1)
|
||||||
|
*dist_onehot, # 유통 A/B/C
|
||||||
|
min(s.partner_count, 5) / 5.0, # 대안 협력사 수 (BATNA)
|
||||||
|
float(np.clip(s.acceptance_ratio, 0.0, 1.0)), # 수용률
|
||||||
|
float(np.clip((s.input_price - anchor) / anchor, -1.0, 2.0)), # 앵커 대비 격차 (연속!)
|
||||||
|
float(np.clip((target - s.input_price) / target, -2.0, 1.0)), # 목표 대비 여유
|
||||||
|
min(s.round_number, 10) / 10.0, # 라운드
|
||||||
|
], dtype=np.float32)
|
||||||
@@ -155,8 +155,10 @@ class LearningRepository:
|
|||||||
# ---- Q-Table 영속화 (H1) -------------------------------------------
|
# ---- Q-Table 영속화 (H1) -------------------------------------------
|
||||||
async def get_or_create_active_version(self, *, state_space_size: int, action_space_size: int,
|
async def get_or_create_active_version(self, *, state_space_size: int, action_space_size: int,
|
||||||
learning_rate: float, discount_factor: float,
|
learning_rate: float, discount_factor: float,
|
||||||
scope: int = 2, version_name: str = "v000") -> Optional[uuid.UUID]:
|
scope: int = 2, version_name: str = "v000",
|
||||||
"""활성 버전 version_id 반환. 없으면 v000 을 활성으로 생성. (company_id 스코프)"""
|
action_cards: Optional[List[str]] = None) -> Optional[uuid.UUID]:
|
||||||
|
"""활성 버전 version_id 반환. 없으면 v000 을 활성으로 생성. (company_id 스코프)
|
||||||
|
action_cards: 카탈로그 스냅샷(카드번호 목록, index=action_id) — 후일 카드번호 기반 마이그레이션용."""
|
||||||
err, existing = await DB_SESSION_MNG.execute_lambda(
|
err, existing = await DB_SESSION_MNG.execute_lambda(
|
||||||
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: self.get_active_version(s)
|
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: self.get_active_version(s)
|
||||||
)
|
)
|
||||||
@@ -170,6 +172,7 @@ class LearningRepository:
|
|||||||
version_id=vid, company_id=self.company_id, version_name=version_name, scope=scope,
|
version_id=vid, company_id=self.company_id, version_name=version_name, scope=scope,
|
||||||
state_space_size=state_space_size, action_space_size=action_space_size,
|
state_space_size=state_space_size, action_space_size=action_space_size,
|
||||||
learning_rate=learning_rate, discount_factor=discount_factor, is_active=True,
|
learning_rate=learning_rate, discount_factor=discount_factor, is_active=True,
|
||||||
|
action_cards=action_cards,
|
||||||
)
|
)
|
||||||
return await DB_SESSION_MNG.insert(s, obj)
|
return await DB_SESSION_MNG.insert(s, obj)
|
||||||
|
|
||||||
@@ -184,7 +187,8 @@ class LearningRepository:
|
|||||||
|
|
||||||
async def warm_start_from_base(self, *, state_space_size: int, action_space_size: int,
|
async def warm_start_from_base(self, *, state_space_size: int, action_space_size: int,
|
||||||
learning_rate: float, discount_factor: float, visit_decay: float = 0.5,
|
learning_rate: float, discount_factor: float, visit_decay: float = 0.5,
|
||||||
version_name: str = "v000_warmstart_from_base") -> Optional[uuid.UUID]:
|
version_name: str = "v000_warmstart_from_base",
|
||||||
|
action_cards: Optional[List[str]] = None) -> Optional[uuid.UUID]:
|
||||||
"""공유 베이스(_base)의 Q값/방문수를 자사로 복제해 활성 버전 생성 (cold-start ①, 계획서 D).
|
"""공유 베이스(_base)의 Q값/방문수를 자사로 복제해 활성 버전 생성 (cold-start ①, 계획서 D).
|
||||||
|
|
||||||
차원 불일치/베이스 없음 → None (호출자가 휴리스틱 init 폴백). visit 은 감쇠 복제(탐색 여지).
|
차원 불일치/베이스 없음 → None (호출자가 휴리스틱 init 폴백). visit 은 감쇠 복제(탐색 여지).
|
||||||
@@ -205,7 +209,7 @@ class LearningRepository:
|
|||||||
version_id=vid, company_id=self.company_id, version_name=version_name, scope=2,
|
version_id=vid, company_id=self.company_id, version_name=version_name, scope=2,
|
||||||
base_version_id=base_ver.version_id, state_space_size=state_space_size,
|
base_version_id=base_ver.version_id, state_space_size=state_space_size,
|
||||||
action_space_size=action_space_size, learning_rate=learning_rate,
|
action_space_size=action_space_size, learning_rate=learning_rate,
|
||||||
discount_factor=discount_factor, is_active=True,
|
discount_factor=discount_factor, is_active=True, action_cards=action_cards,
|
||||||
)
|
)
|
||||||
e = await DB_SESSION_MNG.insert(s, ver)
|
e = await DB_SESSION_MNG.insert(s, ver)
|
||||||
if e != ErrorType.SUCCESS:
|
if e != ErrorType.SUCCESS:
|
||||||
@@ -227,6 +231,73 @@ class LearningRepository:
|
|||||||
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create])
|
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create])
|
||||||
return vid if err == ErrorType.SUCCESS else None
|
return vid if err == ErrorType.SUCCESS else None
|
||||||
|
|
||||||
|
async def migrate_active_version_dim(self, *, old_version, state_space_size: int, action_space_size: int,
|
||||||
|
learning_rate: float, discount_factor: float,
|
||||||
|
version_name: str = "v_migrated",
|
||||||
|
action_cards: Optional[List[str]] = None) -> Optional[uuid.UUID]:
|
||||||
|
"""활성 Q-table 을 새 카탈로그로 마이그레이션 (카드 추가/삭제/재정렬 시).
|
||||||
|
|
||||||
|
**카드번호 기반 리맵**: 옛 버전의 action_cards(카드번호 스냅샷)와 새 카탈로그(action_cards)를
|
||||||
|
비교해, 같은 **카드번호**의 학습값을 새 action_id 로 옮긴다 → 중간 삽입/삭제로 action_id 가
|
||||||
|
밀려도 학습이 카드에 정확히 따라간다. 새 카드는 fresh, 사라진 카드는 버려진다.
|
||||||
|
옛 버전에 action_cards 가 없으면(레거시) 위치 기반 폴백(끝 추가/삭제만 안전).
|
||||||
|
기존 활성 버전은 비활성화하고 새 버전을 활성화한다. 실패 시 None.
|
||||||
|
"""
|
||||||
|
qcells, vcells = await self.load_cells(old_version.version_id)
|
||||||
|
vid = uuid.uuid4()
|
||||||
|
unique_name = f"{version_name}_{vid.hex[:8]}" # (company_id, version_name) 유니크 충돌 방지
|
||||||
|
S, A = state_space_size, action_space_size
|
||||||
|
|
||||||
|
# 옛 action_id → 새 action_id 리맵 테이블. 카드번호로 매칭(스냅샷 있을 때).
|
||||||
|
old_cards = list(getattr(old_version, "action_cards", None) or [])
|
||||||
|
new_cards = list(action_cards or [])
|
||||||
|
if old_cards and new_cards:
|
||||||
|
new_index = {num: i for i, num in enumerate(new_cards)}
|
||||||
|
remap = {old_a: new_index[num] for old_a, num in enumerate(old_cards) if num in new_index}
|
||||||
|
else:
|
||||||
|
remap = {a: a for a in range(min(old_version.action_space_size, A))} # 위치 기반 폴백
|
||||||
|
|
||||||
|
async def _create(s: AsyncSession) -> ErrorType:
|
||||||
|
# 기존 활성 비활성화 → 새 버전 활성 삽입 (동시 2개 활성 방지).
|
||||||
|
e = await DB_SESSION_MNG.add(s, update(QTableVersion).where(
|
||||||
|
QTableVersion.company_id == self.company_id,
|
||||||
|
QTableVersion.version_id == old_version.version_id).values(is_active=False))
|
||||||
|
if e != ErrorType.SUCCESS:
|
||||||
|
return e
|
||||||
|
ver = QTableVersion(
|
||||||
|
version_id=vid, company_id=self.company_id, version_name=unique_name, scope=2,
|
||||||
|
base_version_id=old_version.version_id, state_space_size=S, action_space_size=A,
|
||||||
|
learning_rate=learning_rate, discount_factor=discount_factor, is_active=True,
|
||||||
|
action_cards=new_cards or None,
|
||||||
|
)
|
||||||
|
e = await DB_SESSION_MNG.insert(s, ver)
|
||||||
|
if e != ErrorType.SUCCESS:
|
||||||
|
return e
|
||||||
|
qobjs = [QValue(company_id=self.company_id, version_id=vid, state_index=st, action_id=remap[a], q_value=q)
|
||||||
|
for st, a, q in qcells if st < S and a in remap]
|
||||||
|
vobjs = [VisitCount(company_id=self.company_id, version_id=vid, state_index=st, action_id=remap[a], count=c)
|
||||||
|
for st, a, c in vcells if st < S and a in remap]
|
||||||
|
if qobjs:
|
||||||
|
e = await DB_SESSION_MNG.insert(s, qobjs)
|
||||||
|
if e != ErrorType.SUCCESS:
|
||||||
|
return e
|
||||||
|
if vobjs:
|
||||||
|
e = await DB_SESSION_MNG.insert(s, vobjs)
|
||||||
|
if e != ErrorType.SUCCESS:
|
||||||
|
return e
|
||||||
|
return ErrorType.SUCCESS
|
||||||
|
|
||||||
|
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create])
|
||||||
|
return vid if err == ErrorType.SUCCESS else None
|
||||||
|
|
||||||
|
async def set_version_action_cards(self, version_id, action_cards: List[str]) -> ErrorType:
|
||||||
|
"""버전의 카탈로그 스냅샷(action_cards) 백필 — 레거시 버전이 향후 카탈로그 변경을 감지하게 한다."""
|
||||||
|
async def _do(s: AsyncSession) -> ErrorType:
|
||||||
|
return await DB_SESSION_MNG.add(s, update(QTableVersion).where(
|
||||||
|
QTableVersion.company_id == self.company_id,
|
||||||
|
QTableVersion.version_id == version_id).values(action_cards=action_cards))
|
||||||
|
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_do])
|
||||||
|
|
||||||
async def load_cells(self, version_id) -> Tuple[List[tuple], List[tuple]]:
|
async def load_cells(self, version_id) -> Tuple[List[tuple], List[tuple]]:
|
||||||
"""(q_cells, visit_cells) — q_cells: (state,action,q), visit_cells: (state,action,count). 자사 스코프."""
|
"""(q_cells, visit_cells) — q_cells: (state,action,q), visit_cells: (state,action,count). 자사 스코프."""
|
||||||
def _q(s):
|
def _q(s):
|
||||||
|
|||||||
@@ -20,9 +20,8 @@ from config.server_configs import agent_config
|
|||||||
|
|
||||||
_TENANT_HEADER = "X-Tenant-ID"
|
_TENANT_HEADER = "X-Tenant-ID"
|
||||||
|
|
||||||
# 테넌트 식별이 필요 없는 경로 (헬스/문서/스키마/데모 UI).
|
# 테넌트 식별이 필요 없는 경로 (헬스/문서/스키마/데모 UI + 전역 카탈로그 리로드=내부 운영).
|
||||||
_WHITELIST_PREFIXES = ("/healthz", "/health", "/v1/health", "/docs", "/redoc", "/openapi.json", "/demo")
|
_WHITELIST_PREFIXES = ("/healthz", "/health", "/v1/health", "/docs", "/redoc", "/openapi.json", "/demo", "/v1/catalog-refresh-all")
|
||||||
|
|
||||||
|
|
||||||
class TenantMiddleware(BaseHTTPMiddleware):
|
class TenantMiddleware(BaseHTTPMiddleware):
|
||||||
async def dispatch(self, request: Request, call_next):
|
async def dispatch(self, request: Request, call_next):
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ PoC: action_id ↔ card_id 매핑을 learning.tenant_action_cards 에 둔다(con
|
|||||||
|
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends
|
from fastapi import APIRouter, Depends, Request
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from common.enums import ErrorType
|
from common.enums import EXCEPTION_TENANT_HEADER_MISSING, ErrorType
|
||||||
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
||||||
from router.deps import get_tenant_engine
|
from router.deps import get_tenant_engine
|
||||||
from tenancy.registry import TenantEngine
|
from tenancy.registry import TenantEngine, tenant_registry
|
||||||
|
|
||||||
router = APIRouter(prefix="/v1", tags=["Card"], responses={404: {"description": "Not found"}})
|
router = APIRouter(prefix="/v1", tags=["Card"], responses={404: {"description": "Not found"}})
|
||||||
|
|
||||||
@@ -41,6 +41,33 @@ async def card_update(req: CardUpdateReq, engine: TenantEngine = Depends(get_ten
|
|||||||
"action_id": req.action_id, "card_id": req.card_id, "desc": err.name}
|
"action_id": req.action_id, "card_id": req.card_id, "desc": err.name}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/catalog-refresh-all", summary="공용 카탈로그 변경 전역 반영(모든 엔진 캐시 클리어)")
|
||||||
|
async def catalog_refresh_all():
|
||||||
|
"""공용 카드(card.nego_cards user_id NULL)는 모든 테넌트의 action space 를 정의하므로,
|
||||||
|
변경 시 전역 반영이 필요하다. 캐시된 엔진을 전부 비워 다음 요청에서 최신 카탈로그로 재조립한다.
|
||||||
|
o2o 운영/negodata 공용카드 발행 훅에서 호출. 테넌트 헤더 불필요(미들웨어 화이트리스트) — 내부망 전용.
|
||||||
|
"""
|
||||||
|
cleared = tenant_registry.clear_all()
|
||||||
|
return {"success": True, "cleared_engines": cleared}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/catalog-refresh", summary="카드 카탈로그 변경 반영(엔진 재조립)")
|
||||||
|
async def catalog_refresh(request: Request):
|
||||||
|
"""negodata 가 카드 카탈로그(card.nego_cards)를 추가/삭제(발행)한 뒤 호출한다.
|
||||||
|
|
||||||
|
해당 테넌트의 캐시된 엔진을 재조립해 → ① DB 카탈로그로 action space 재구성(type:db)
|
||||||
|
→ 다음 협상 로드 시 ② 차원 변경이면 Q-table 학습 보존 마이그레이션이 걸린다.
|
||||||
|
엔진은 캐시되므로 이 호출 없이는 카탈로그 변경이 반영되지 않는다.
|
||||||
|
"""
|
||||||
|
tenant_id = getattr(request.state, "tenant_id", None)
|
||||||
|
if not tenant_id:
|
||||||
|
raise EXCEPTION_TENANT_HEADER_MISSING
|
||||||
|
engine = await tenant_registry.reload(tenant_id)
|
||||||
|
if engine is None:
|
||||||
|
return {"success": False, "desc": "unregistered tenant or reload failed", "tenant_id": tenant_id}
|
||||||
|
return {"success": True, "company_id": engine.company_id, "action_space_size": engine.action_space_size}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/card-search", summary="카드 검색(전체 매핑 또는 card_id 조회)")
|
@router.get("/card-search", summary="카드 검색(전체 매핑 또는 card_id 조회)")
|
||||||
async def card_search(card_id: Optional[str] = None, engine: TenantEngine = Depends(get_tenant_engine)):
|
async def card_search(card_id: Optional[str] = None, engine: TenantEngine = Depends(get_tenant_engine)):
|
||||||
mapping = await _merged_mapping(engine)
|
mapping = await _merged_mapping(engine)
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ class Req_Chat(Req_WebPacketProtocol):
|
|||||||
협상 컨텍스트(rq_type/목표가/앵커링가/품목가/매출액/유통코드/파트너 유형)는 요청에 싣지
|
협상 컨텍스트(rq_type/목표가/앵커링가/품목가/매출액/유통코드/파트너 유형)는 요청에 싣지
|
||||||
않는다 — 세션 시작 시 agent 가 DB 에서 1회 조회해 확정한다(NegotiationContextLoader):
|
않는다 — 세션 시작 시 agent 가 DB 에서 1회 조회해 확정한다(NegotiationContextLoader):
|
||||||
negotiation.sessions(qt_type·target_price·anchoring_price), partner.items(price),
|
negotiation.sessions(qt_type·target_price·anchoring_price), partner.items(price),
|
||||||
partner.suppliers(total_revenue), quotation.quotations(supplier_type), 상품별 협력사 수.
|
partner.suppliers(total_revenue), partner.supplier_items(supply_type), 상품별 협력사 수.
|
||||||
행이 없으면(데모/테스트 직접 호출) 기본값 폴백.
|
행이 없으면(데모/테스트 직접 호출) 기본값 폴백.
|
||||||
가격 수용률은 세션 내 라운드별 제시가로 매 턴 동적 계산: max(0, (기존 공급가−현재가)/기존 공급가)
|
가격 수용률은 세션 내 라운드별 제시가로 매 턴 동적 계산: max(0, (기존 공급가−현재가)/기존 공급가)
|
||||||
— 첫 제시가부터 기존 공급가 대비 인하가 반영되므로 첫 라운드도 실값. 기존 공급가 없으면 첫 제시가 기준.
|
— 첫 제시가부터 기존 공급가 대비 인하가 반영되므로 첫 라운드도 실값. 기존 공급가 없으면 첫 제시가 기준.
|
||||||
|
|||||||
+146
-10
@@ -7,16 +7,22 @@ ChatEngine(동기 step 전이) + UCB Q-Table(가격협상 카드선택·학습)
|
|||||||
import uuid
|
import uuid
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
from common.enums import DBType, ErrorType
|
from common.enums import DBType, ErrorType
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from config.server_configs import agent_config
|
from config.server_configs import agent_config
|
||||||
|
from negotiation.chat.service import ment_generator
|
||||||
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession, StepView
|
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession, StepView
|
||||||
from negotiation.chat.service.indicator import compute_indicator
|
from negotiation.chat.service.indicator import compute_indicator
|
||||||
from negotiation.chat.service.chat_session_repository import ChatSessionRepository
|
from negotiation.chat.service.chat_session_repository import ChatSessionRepository
|
||||||
from negotiation.chat.service.negotiation_context_loader import NegotiationContextLoader
|
from negotiation.chat.service.negotiation_context_loader import NegotiationContextLoader
|
||||||
from negotiation.chat.service.script_repository import ScriptRepository
|
from negotiation.chat.service.script_repository import ScriptRepository
|
||||||
from negotiation.policies.base import EpisodeState, PolicyContext, Transition
|
from negotiation.policies.base import EpisodeState, PolicyContext, Transition
|
||||||
|
from negotiation.policies.autonomy_actions import ACTIONS as AUTONOMY_ACTIONS
|
||||||
|
from negotiation.policy.autonomy_store import AutonomyStore
|
||||||
|
from negotiation.policy.dqn_store import DQNServingStore
|
||||||
from negotiation.policy.model_store import QTablePolicyStore
|
from negotiation.policy.model_store import QTablePolicyStore
|
||||||
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot, PartnerType
|
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot, PartnerType
|
||||||
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||||
@@ -31,7 +37,7 @@ _DEFAULT_RQ_TYPE = "재협상"
|
|||||||
_DEFAULT_TARGET_PRICE = 10000 # KT 목표 매입가
|
_DEFAULT_TARGET_PRICE = 10000 # KT 목표 매입가
|
||||||
_DEFAULT_ANCHOR_PRICE = 9900 # 앵커링가(목표가보다 낮음). 제시가 ≤ anchor → 우선협상
|
_DEFAULT_ANCHOR_PRICE = 9900 # 앵커링가(목표가보다 낮음). 제시가 ≤ anchor → 우선협상
|
||||||
_DEFAULT_REVENUE_AMOUNT = 20_000_000 # 매출액(원) — suppliers.total_revenue 미기재 시 폴백
|
_DEFAULT_REVENUE_AMOUNT = 20_000_000 # 매출액(원) — suppliers.total_revenue 미기재 시 폴백
|
||||||
_DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — quotations.supplier_type 미지정 시 폴백
|
_DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — supplier_items.supply_type 미지정 시 폴백
|
||||||
|
|
||||||
|
|
||||||
class ChatService:
|
class ChatService:
|
||||||
@@ -44,9 +50,19 @@ class ChatService:
|
|||||||
session = await sess_repo.get(req.session_id) if req.session_id else None
|
session = await sess_repo.get(req.session_id) if req.session_id else None
|
||||||
# 새 세션 컨텍스트: 요청 페이로드 대신 DB(negotiation.sessions 등)에서 1회 조회.
|
# 새 세션 컨텍스트: 요청 페이로드 대신 DB(negotiation.sessions 등)에서 1회 조회.
|
||||||
# 행이 없으면(데모/테스트 직접 호출) 기본값 폴백.
|
# 행이 없으면(데모/테스트 직접 호출) 기본값 폴백.
|
||||||
db_ctx = None if session else await NegotiationContextLoader().load(req.session_id)
|
db_ctx = None if session else await NegotiationContextLoader().load(req.session_id, engine.company_id)
|
||||||
rq_type = session.rq_type if session else (db_ctx.rq_type if db_ctx else _DEFAULT_RQ_TYPE)
|
rq_type = session.rq_type if session else (db_ctx.rq_type if db_ctx else _DEFAULT_RQ_TYPE)
|
||||||
chat_engine = ChatEngine(repo, rq_type=rq_type)
|
chat_engine = ChatEngine(repo, rq_type=rq_type)
|
||||||
|
# 완전 자율 모드(AUTONOMY_MODE=1 + 번들 존재): 가격협상 판정 룰·카드 선택을 정책 행동으로 대체.
|
||||||
|
# decider 를 감싸 결정을 컨텍스트에 기록 → advance() 후 experience_logs 에 적재(_autonomy_learn).
|
||||||
|
autonomy = AutonomyStore.policy_for(engine)
|
||||||
|
if autonomy is not None:
|
||||||
|
def _decide(ctx, _p=autonomy):
|
||||||
|
act = _p.decide(ctx)
|
||||||
|
ctx["autonomy_pending"] = {"idx": AUTONOMY_ACTIONS.index(act), "kind": act.kind,
|
||||||
|
"q": act.counter_q, "s": act.strategy}
|
||||||
|
return act
|
||||||
|
chat_engine.autonomy_decider = _decide
|
||||||
|
|
||||||
# ① step desync 감지: backend 가 본 직전 봇 step(client_step)이 agent 세션 step 과 다르면 경고.
|
# ① step desync 감지: backend 가 본 직전 봇 step(client_step)이 agent 세션 step 과 다르면 경고.
|
||||||
# agent 가 자기 step 을 정답으로 보고 진행하고(응답의 step/client_step 으로 backend 가 따라옴),
|
# agent 가 자기 step 을 정답으로 보고 진행하고(응답의 step/client_step 으로 backend 가 따라옴),
|
||||||
@@ -63,13 +79,22 @@ class ChatService:
|
|||||||
)
|
)
|
||||||
|
|
||||||
if session is None:
|
if session is None:
|
||||||
|
selected_nego_cards = db_ctx.selected_nego_card_numbers if db_ctx else []
|
||||||
|
selected_wild_cards = db_ctx.selected_wild_card_numbers if db_ctx else []
|
||||||
|
# 운영 DB 세션은 견적 version_id 에 묶인 카드만 사용한다. 직접 호출/데모(DB context 없음)는
|
||||||
|
# 기존 테넌트 기본 action mapping 으로 폴백해 로컬 테스트와 콘솔 데모를 유지한다.
|
||||||
|
action_space_size = (
|
||||||
|
min(len(selected_nego_cards), engine.action_space_size)
|
||||||
|
if db_ctx is not None
|
||||||
|
else engine.action_space_size
|
||||||
|
)
|
||||||
# session_id honoring: backend 가 보낸 session_id(= negotiation.sessions.session_id)를
|
# session_id honoring: backend 가 보낸 session_id(= negotiation.sessions.session_id)를
|
||||||
# 새 uuid 발급 없이 그대로 세션 키로 쓴다. 없으면(직접 호출/데모) 생성.
|
# 새 uuid 발급 없이 그대로 세션 키로 쓴다. 없으면(직접 호출/데모) 생성.
|
||||||
session = ChatSession(
|
session = ChatSession(
|
||||||
session_id=req.session_id or str(uuid.uuid4()), tenant_id=engine.tenant_id, company_id=engine.company_id,
|
session_id=req.session_id or str(uuid.uuid4()), tenant_id=engine.tenant_id, company_id=engine.company_id,
|
||||||
rq_type=rq_type, action_space_size=engine.action_space_size,
|
rq_type=rq_type, action_space_size=action_space_size,
|
||||||
context={
|
context={
|
||||||
# 매출액 = suppliers.total_revenue, 유통코드 = quotations.supplier_type 매핑 (loader).
|
# 매출액 = suppliers.total_revenue, 유통코드 = supplier_items.supply_type 매핑 (loader).
|
||||||
# 미기재/미지정이면 기본값 폴백.
|
# 미기재/미지정이면 기본값 폴백.
|
||||||
"revenue_amount": db_ctx.revenue_amount if db_ctx and db_ctx.revenue_amount > 0 else _DEFAULT_REVENUE_AMOUNT,
|
"revenue_amount": db_ctx.revenue_amount if db_ctx and db_ctx.revenue_amount > 0 else _DEFAULT_REVENUE_AMOUNT,
|
||||||
"distribution_code": db_ctx.distribution_code if db_ctx and db_ctx.distribution_code else _DEFAULT_DISTRIBUTION_CODE,
|
"distribution_code": db_ctx.distribution_code if db_ctx and db_ctx.distribution_code else _DEFAULT_DISTRIBUTION_CODE,
|
||||||
@@ -83,6 +108,20 @@ class ChatService:
|
|||||||
"round": 0,
|
"round": 0,
|
||||||
# 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용.
|
# 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용.
|
||||||
"item_price": db_ctx.item_price if db_ctx else 0,
|
"item_price": db_ctx.item_price if db_ctx else 0,
|
||||||
|
# 견적 생성 시 선택한 카드. 일반카드는 action_id 0..N-1 에 그대로 매핑한다.
|
||||||
|
# 1% 인하는 기본 와일드카드로 항상 열고, 재원부족 등 선택형 와일드카드는
|
||||||
|
# 선택된 와일드카드가 있을 때만 허용한다.
|
||||||
|
"db_context_loaded": db_ctx is not None,
|
||||||
|
"selected_nego_card_numbers": selected_nego_cards,
|
||||||
|
"selected_wild_card_numbers": selected_wild_cards,
|
||||||
|
"allow_selected_wildcards": True if db_ctx is None else bool(selected_wild_cards),
|
||||||
|
# ---- 자율 에이전트 v3 특징 소스 (미상이면 키 자체를 중립값으로 — JSON 직렬화 안전) ----
|
||||||
|
"internet_lowest_price": db_ctx.internet_lowest_price if db_ctx else 0,
|
||||||
|
"deadline_end_ts": db_ctx.deadline_end_ts if db_ctx else None,
|
||||||
|
"deadline_total_s": db_ctx.deadline_total_s if db_ctx else None,
|
||||||
|
"hist_n": db_ctx.hist_n if db_ctx else 0,
|
||||||
|
"hist_success": db_ctx.hist_success if db_ctx else None,
|
||||||
|
"hist_settle_ratio": db_ctx.hist_settle_ratio if db_ctx else None,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
view = chat_engine.start(session)
|
view = chat_engine.start(session)
|
||||||
@@ -105,12 +144,23 @@ class ChatService:
|
|||||||
res.settled_price = int(session.context["input_price"])
|
res.settled_price = int(session.context["input_price"])
|
||||||
|
|
||||||
# 3) 학습 결합 (가격협상 카드선택 → 카드 스크립트·협상지표 / 종료 보상)
|
# 3) 학습 결합 (가격협상 카드선택 → 카드 스크립트·협상지표 / 종료 보상)
|
||||||
if view.error is None and engine.action_space_size > 0:
|
if view.error is None and session.action_space_size > 0:
|
||||||
if view.needs_card_selection:
|
if view.needs_card_selection:
|
||||||
await self._select_and_learn(engine, chat_engine, repo, session, res)
|
await self._select_and_learn(engine, chat_engine, repo, session, res)
|
||||||
elif view.outcome is not None:
|
elif view.outcome is not None:
|
||||||
await self._terminal_learn(engine, session, view.outcome, res)
|
await self._terminal_learn(engine, session, view.outcome, res)
|
||||||
|
|
||||||
|
# 3-b) 완전 자율 모드: 정책 결정·종료 결과를 experience_logs 에 적재 (실로그 재학습 재료).
|
||||||
|
if autonomy is not None and view.error is None:
|
||||||
|
await self._autonomy_learn(engine, session, view, res)
|
||||||
|
# 자율 스텝 멘트를 LLM 으로 생성 (행동은 RL, 문장은 LLM). 실패/미설정 → 템플릿 유지.
|
||||||
|
if view.step.startswith("자율_"):
|
||||||
|
llm_ment = await ment_generator.generate(view.step, session.context)
|
||||||
|
if llm_ment:
|
||||||
|
res.script = llm_ment
|
||||||
|
# 직전 봇 멘트 보존 — 다음 생성에서 같은 문장 구조 반복을 금지하는 힌트.
|
||||||
|
session.context["autonomy_last_ment"] = (res.script or "")[:200]
|
||||||
|
|
||||||
if view.error:
|
if view.error:
|
||||||
res.result.SetResult(ErrorType.NEGO_INVALID_STEP)
|
res.result.SetResult(ErrorType.NEGO_INVALID_STEP)
|
||||||
res.msg = view.error
|
res.msg = view.error
|
||||||
@@ -172,11 +222,21 @@ class ChatService:
|
|||||||
LOG.e_no_callstack(f"[ChatService] state error: {ex}")
|
LOG.e_no_callstack(f"[ChatService] state error: {ex}")
|
||||||
return
|
return
|
||||||
policy, version_id, repo = await QTablePolicyStore.load(engine)
|
policy, version_id, repo = await QTablePolicyStore.load(engine)
|
||||||
|
# action space 는 카탈로그 전체(engine.action_space_size)로 고정 — action_id↔카드 대응을
|
||||||
|
# 견적마다 일정하게 유지해 Q-table 학습 일관성을 지킨다. 견적 선택은 축소가 아니라
|
||||||
|
# available_mask 로 처리한다(선택 카드만 pickable, 사용분 제외).
|
||||||
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=engine.action_space_size,
|
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=engine.action_space_size,
|
||||||
|
available_mask=self._selection_mask(engine, session),
|
||||||
episode=EpisodeState(used_action_ids=set(session.used_action_ids)))
|
episode=EpisodeState(used_action_ids=set(session.used_action_ids)))
|
||||||
decision = policy.select(ctx)
|
# 카드 '선택'은 DQN 서빙(활성 시), 학습/영속은 아래 Q-table 경로 그대로(오프폴리시 갱신).
|
||||||
|
# DQN 불가(비활성/번들 없음/후보 특징 없음)면 None → 기존 UCB 선택 폴백.
|
||||||
|
dqn = DQNServingStore.policy_for(engine)
|
||||||
|
decision = dqn.select(ctx) if dqn is not None else None
|
||||||
|
selector_name = dqn.name if decision is not None else policy.name
|
||||||
|
if decision is None:
|
||||||
|
decision = policy.select(ctx)
|
||||||
session.used_action_ids.add(decision.action_id)
|
session.used_action_ids.add(decision.action_id)
|
||||||
card_id = engine.mapper.get_card_id(decision.action_id)
|
card_id = self._card_id_for_action(engine, session, decision.action_id)
|
||||||
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
|
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
|
||||||
policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=reward.total, done=False))
|
policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=reward.total, done=False))
|
||||||
await QTablePolicyStore.persist_cell(repo, version_id, policy, idx, decision.action_id)
|
await QTablePolicyStore.persist_cell(repo, version_id, policy, idx, decision.action_id)
|
||||||
@@ -185,7 +245,7 @@ class ChatService:
|
|||||||
await self._log(repo, session, idx, decision.action_id, card_id, snap, reward, decision.propensity, done=False)
|
await self._log(repo, session, idx, decision.action_id, card_id, snap, reward, decision.propensity, done=False)
|
||||||
|
|
||||||
res.card_id = card_id
|
res.card_id = card_id
|
||||||
res.policy = policy.name
|
res.policy = selector_name
|
||||||
res.q_value = decision.q_value
|
res.q_value = decision.q_value
|
||||||
res.updated_q = float(policy.qtable.q[idx, decision.action_id])
|
res.updated_q = float(policy.qtable.q[idx, decision.action_id])
|
||||||
res.visit_count = int(policy.qtable.visits[idx, decision.action_id])
|
res.visit_count = int(policy.qtable.visits[idx, decision.action_id])
|
||||||
@@ -195,7 +255,12 @@ class ChatService:
|
|||||||
# ① 선택된 카드의 스크립트를 봇 메시지(script)로 출력 ② 협상지표 게이지(indicator_value) 동봉.
|
# ① 선택된 카드의 스크립트를 봇 메시지(script)로 출력 ② 협상지표 게이지(indicator_value) 동봉.
|
||||||
# backend/front 가 indicator/bot_chat_type 패스스루·게이지 렌더 준비 완료 → 값만 채우면 표시된다.
|
# backend/front 가 indicator/bot_chat_type 패스스루·게이지 렌더 준비 완료 → 값만 채우면 표시된다.
|
||||||
# 카드 멘트: backoffice_db 모드면 card.nego_cards.script(negodata 편집 정본), 아니면 파일 폴백.
|
# 카드 멘트: backoffice_db 모드면 card.nego_cards.script(negodata 편집 정본), 아니면 파일 폴백.
|
||||||
card_script = await scripts.resolve_card_script(decision.action_id, card_id, chat_engine.vars_for(session))
|
card_script = await scripts.resolve_card_script(
|
||||||
|
decision.action_id,
|
||||||
|
card_id,
|
||||||
|
chat_engine.vars_for(session),
|
||||||
|
prefer_db=bool(session.context.get("selected_nego_card_numbers")),
|
||||||
|
)
|
||||||
if card_script:
|
if card_script:
|
||||||
res.script = card_script
|
res.script = card_script
|
||||||
c = session.context
|
c = session.context
|
||||||
@@ -205,6 +270,49 @@ class ChatService:
|
|||||||
res.indicator_range = ind[1]
|
res.indicator_range = ind[1]
|
||||||
res.bot_chat_type = "indicator"
|
res.bot_chat_type = "indicator"
|
||||||
|
|
||||||
|
async def _autonomy_learn(self, engine: TenantEngine, session: ChatSession, view: StepView, res: Res_Chat):
|
||||||
|
"""완전 자율 행동 로깅 — Q-table 은 건드리지 않고 experience_logs 만 적재한다.
|
||||||
|
|
||||||
|
action_id = autonomy_actions.ACTIONS 인덱스, card_id = "AUT|종류|위치|전략" (카드 재학습
|
||||||
|
파이프라인이 임베딩 매칭에서 자동 제외하도록 프리픽스로 구분). 종료 시 최종 보상 행(done=True)을
|
||||||
|
남겨 retrain 의 에피소드 재구성 규약(카드턴 N + 종료 1)과 정합을 맞춘다.
|
||||||
|
"""
|
||||||
|
def _card_id(d) -> str:
|
||||||
|
return f"AUT|{d['kind']}|{d['q']:g}|{d['s']}"[:40]
|
||||||
|
|
||||||
|
ctx = session.context
|
||||||
|
lrepo = LearningRepository(engine.company_id)
|
||||||
|
pending = ctx.pop("autonomy_pending", None)
|
||||||
|
if pending is not None:
|
||||||
|
snap = self._snapshot(session, NegotiationOutcome.ONGOING)
|
||||||
|
try:
|
||||||
|
idx = state_index(snap, engine.config.state) # 로깅 호환용 이산 인덱스
|
||||||
|
except ValueError:
|
||||||
|
idx = 0 # 자율 모드는 이산 상태를 쓰지 않으므로 폴백해도 학습 오염 없음
|
||||||
|
if ctx.get("autonomy_last"):
|
||||||
|
ctx["autonomy_prev"] = ctx["autonomy_last"] # 직전 결정 보존 — 멘트 생성 힌트(양보 언급)용
|
||||||
|
ctx["autonomy_last"] = dict(pending, state_index=idx)
|
||||||
|
if pending.get("kind") == "counter":
|
||||||
|
# 역제안 기억은 별도 키로 보존 — autonomy_last 는 '마지막 행동'이라 사이에 낀
|
||||||
|
# 설득이 덮어쓴다. 단조 봉투·탄약소진 판정이 이 기억을 기준으로 해야
|
||||||
|
# counter→press→counter 에서 제안 철회가 새지 않는다 (게이트가 잡은 실버그).
|
||||||
|
ctx["autonomy_last_counter"] = dict(pending)
|
||||||
|
if pending.get("kind") == "press":
|
||||||
|
# 설득 횟수 누적 — 역제시 해금 조건(autonomy_store ③)의 카운터.
|
||||||
|
ctx["autonomy_press_n"] = int(ctx.get("autonomy_press_n") or 0) + 1
|
||||||
|
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
|
||||||
|
await self._log(lrepo, session, idx, pending["idx"], _card_id(pending), snap,
|
||||||
|
reward, (1.0 - 0.1) + 0.1 / len(AUTONOMY_ACTIONS), done=False)
|
||||||
|
res.policy = "full_autonomy"
|
||||||
|
last = ctx.get("autonomy_last")
|
||||||
|
if view.outcome is not None and last is not None:
|
||||||
|
oc = NegotiationOutcome.SUCCESS if view.outcome == "success" else NegotiationOutcome.FAILURE
|
||||||
|
snap = self._snapshot(session, oc)
|
||||||
|
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
|
||||||
|
res.reward_total = reward.total
|
||||||
|
await self._log(lrepo, session, last["state_index"], last["idx"], _card_id(last), snap,
|
||||||
|
reward, None, done=True)
|
||||||
|
|
||||||
async def _terminal_learn(self, engine: TenantEngine, session: ChatSession, outcome: str, res: Res_Chat):
|
async def _terminal_learn(self, engine: TenantEngine, session: ChatSession, outcome: str, res: Res_Chat):
|
||||||
oc = NegotiationOutcome.SUCCESS if outcome == "success" else NegotiationOutcome.FAILURE
|
oc = NegotiationOutcome.SUCCESS if outcome == "success" else NegotiationOutcome.FAILURE
|
||||||
snap = self._snapshot(session, oc)
|
snap = self._snapshot(session, oc)
|
||||||
@@ -218,9 +326,37 @@ class ChatService:
|
|||||||
policy.update(Transition(state_index=last_state, action_id=last_action, reward=reward.total, done=True))
|
policy.update(Transition(state_index=last_state, action_id=last_action, reward=reward.total, done=True))
|
||||||
await QTablePolicyStore.persist_cell(repo, version_id, policy, last_state, last_action)
|
await QTablePolicyStore.persist_cell(repo, version_id, policy, last_state, last_action)
|
||||||
await self._log(repo, session, last_state, last_action,
|
await self._log(repo, session, last_state, last_action,
|
||||||
engine.mapper.get_card_id(last_action), snap, reward, None, done=True)
|
self._card_id_for_action(engine, session, last_action), snap, reward, None, done=True)
|
||||||
res.updated_q = float(policy.qtable.q[last_state, last_action])
|
res.updated_q = float(policy.qtable.q[last_state, last_action])
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _card_id_for_action(engine: TenantEngine, session: ChatSession, action_id: int) -> Optional[str]:
|
||||||
|
# action_id ↔ 카드는 테넌트 매핑(action_to_card)으로 고정한다. 견적 선택은 available_mask 로
|
||||||
|
# 걸러지므로 여기서 selected 리스트를 인덱싱하지 않는다 — 인덱싱하면 견적마다 action_id 의미가
|
||||||
|
# 달라져(같은 action_id 가 다른 카드) Q-table 학습이 오염된다.
|
||||||
|
return engine.mapper.get_card_id(action_id)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _selection_mask(engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
|
||||||
|
"""견적에서 선택한 카드(selected_nego_card_numbers)만 pickable 로 하는 available_mask.
|
||||||
|
|
||||||
|
action space 전체(engine.action_space_size) 크기의 bool 배열. 선택 카드의 action_id 만 True,
|
||||||
|
이미 사용한 action 은 False. 선택이 없거나(직접호출/데모) 매핑 불가면 None → 전체 허용(폴백).
|
||||||
|
번호(card.nego_cards.number)와 action_to_card 값이 일치해야 매핑된다.
|
||||||
|
"""
|
||||||
|
selected = session.context.get("selected_nego_card_numbers") or []
|
||||||
|
if not selected:
|
||||||
|
return None
|
||||||
|
used = set(session.used_action_ids)
|
||||||
|
selected_ids = {engine.mapper.get_action_id(str(n)) for n in selected}
|
||||||
|
selected_ids.discard(None)
|
||||||
|
if not selected_ids:
|
||||||
|
return None # 매핑에 없는 번호뿐 → 폴백(전체 허용)
|
||||||
|
return np.array(
|
||||||
|
[(a in selected_ids and a not in used) for a in range(engine.action_space_size)],
|
||||||
|
dtype=bool,
|
||||||
|
)
|
||||||
|
|
||||||
async def _log(self, repo: LearningRepository, session, state_index, action_id, card_id, snap, reward, propensity, done):
|
async def _log(self, repo: LearningRepository, session, state_index, action_id, card_id, snap, reward, propensity, done):
|
||||||
data = {
|
data = {
|
||||||
"session_id": session.session_id, "state_index": state_index, "action_id": action_id,
|
"session_id": session.session_id, "state_index": state_index, "action_id": action_id,
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""회사 프로필(브랜드) DB 조회 — 자동 온보딩 고객사의 {company_name} 을 DB 에서 채운다.
|
||||||
|
|
||||||
|
스크립트의 {company_name} 은 지금까지 tenant.yaml resources.company_name(_base 기본값)에서 왔다.
|
||||||
|
자동 온보딩 고객사(전용 yaml 없음)는 전부 _base 브랜드로 나가므로, 실제 회사명(company.companies.name)을
|
||||||
|
company_id 로 조회해 엔진 조립 시 덮어쓴다. 회사 정보라 튜닝 오버레이와는 별개 관심사다.
|
||||||
|
|
||||||
|
스키마 소유권: company 스키마는 backend/negodata 소유 — read-only. 경량 table()/column() 구성.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from typing import Optional, Tuple
|
||||||
|
|
||||||
|
from sqlalchemy import column, select, table
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.enums import DBType, DBWRType, ErrorType
|
||||||
|
from common.logger import LOG
|
||||||
|
|
||||||
|
_COMPANIES = table("companies", column("company_id"), column("name"), column("deleted"), schema="company")
|
||||||
|
|
||||||
|
|
||||||
|
class ICompanyProfileRepository(ABC):
|
||||||
|
@abstractmethod
|
||||||
|
async def get_company_name(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, Optional[str]]:
|
||||||
|
"""company.companies.name by company_id. 없으면 None."""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
class CompanyProfileRepository(ICompanyProfileRepository):
|
||||||
|
async def get_company_name(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, Optional[str]]:
|
||||||
|
try:
|
||||||
|
query = (
|
||||||
|
select(_COMPANIES.c.name)
|
||||||
|
.where(_COMPANIES.c.company_id == company_id, _COMPANIES.c.deleted == False) # noqa: E712
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_company_name failed.", raise_error=False)
|
||||||
|
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
|
||||||
|
return err_type, None
|
||||||
|
return ErrorType.SUCCESS, str(rows[0])
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, None
|
||||||
|
|
||||||
|
|
||||||
|
async def resolve_company_name(repo: ICompanyProfileRepository, tenant_key: str) -> Optional[str]:
|
||||||
|
"""tenant_key(= company_id UUID)로 회사명 조회. 비-UUID(데모 테넌트)면 조회 안 함(None).
|
||||||
|
세션/트랜잭션 경계를 여기서 관리(execute_lambda)한다."""
|
||||||
|
try:
|
||||||
|
cid = uuid.UUID(tenant_key)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return None # ktcommerce 등 데모 테넌트명 → 파일 브랜드 유지
|
||||||
|
|
||||||
|
async def _q(s):
|
||||||
|
_, name = await repo.get_company_name(s, cid)
|
||||||
|
return name
|
||||||
|
|
||||||
|
try:
|
||||||
|
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(f"[company_profile] 회사명 조회 실패 company_id={tenant_key}: {ex}")
|
||||||
|
return None
|
||||||
@@ -8,14 +8,34 @@ Chat_server 는 `chat_engine = ChatEngine()` 전역 무인자 싱글톤이라
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import uuid
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from typing import Dict, Optional
|
from typing import Dict, Optional
|
||||||
|
|
||||||
|
|
||||||
|
def _as_uuid(key: Optional[str]):
|
||||||
|
"""key 가 UUID(실 고객사 company_id)면 uuid.UUID 반환, 데모 테넌트명 등이면 None."""
|
||||||
|
try:
|
||||||
|
return uuid.UUID(key)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.enums import DBType, DBWRType, ErrorType
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from negotiation.cards.action_card_mapper import ActionCardMapper
|
from negotiation.cards.action_card_mapper import ActionCardMapper
|
||||||
|
from negotiation.cards.adapters.card_catalog_db import CardCatalogDbRepository
|
||||||
|
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
|
||||||
|
from tenancy.company_profile_repo import (
|
||||||
|
CompanyProfileRepository,
|
||||||
|
ICompanyProfileRepository,
|
||||||
|
resolve_company_name,
|
||||||
|
)
|
||||||
from tenancy.config import TenantConfig
|
from tenancy.config import TenantConfig
|
||||||
from tenancy.config_loader import TenantConfigLoader
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
|
||||||
|
_CARD_SOURCE_DB = "db"
|
||||||
|
|
||||||
|
|
||||||
class TenantEngine:
|
class TenantEngine:
|
||||||
"""한 테넌트의 협상 엔진 조립체 (불변 협력자 보관).
|
"""한 테넌트의 협상 엔진 조립체 (불변 협력자 보관).
|
||||||
@@ -49,9 +69,13 @@ class EngineFactory:
|
|||||||
|
|
||||||
|
|
||||||
class TenantEngineRegistry:
|
class TenantEngineRegistry:
|
||||||
def __init__(self, loader: Optional[TenantConfigLoader] = None, factory: type[EngineFactory] = EngineFactory):
|
def __init__(self, loader: Optional[TenantConfigLoader] = None, factory: type[EngineFactory] = EngineFactory,
|
||||||
|
catalog_repo: Optional[ICardCatalogRepository] = None,
|
||||||
|
company_repo: Optional[ICompanyProfileRepository] = None):
|
||||||
self._loader = loader or TenantConfigLoader()
|
self._loader = loader or TenantConfigLoader()
|
||||||
self._factory = factory
|
self._factory = factory
|
||||||
|
self._catalog_repo = catalog_repo or CardCatalogDbRepository()
|
||||||
|
self._company_repo = company_repo or CompanyProfileRepository()
|
||||||
self._engines: Dict[str, TenantEngine] = {}
|
self._engines: Dict[str, TenantEngine] = {}
|
||||||
self._locks: Dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
|
self._locks: Dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
|
||||||
|
|
||||||
@@ -69,8 +93,7 @@ class TenantEngineRegistry:
|
|||||||
return cached
|
return cached
|
||||||
if not self.is_registered(tenant_id):
|
if not self.is_registered(tenant_id):
|
||||||
raise KeyError(f"unregistered tenant: {tenant_id}")
|
raise KeyError(f"unregistered tenant: {tenant_id}")
|
||||||
config = self._loader.load(tenant_id)
|
engine = await self._build(tenant_id)
|
||||||
engine = self._factory.build(config)
|
|
||||||
self._engines[tenant_id] = engine
|
self._engines[tenant_id] = engine
|
||||||
LOG.i(f"[TenantEngineRegistry] built engine tenant_id={tenant_id} "
|
LOG.i(f"[TenantEngineRegistry] built engine tenant_id={tenant_id} "
|
||||||
f"state={engine.state_space_size} action={engine.action_space_size}")
|
f"state={engine.state_space_size} action={engine.action_space_size}")
|
||||||
@@ -83,11 +106,55 @@ class TenantEngineRegistry:
|
|||||||
self._engines.pop(tenant_id, None)
|
self._engines.pop(tenant_id, None)
|
||||||
if not self.is_registered(tenant_id):
|
if not self.is_registered(tenant_id):
|
||||||
return None
|
return None
|
||||||
config = self._loader.load(tenant_id)
|
engine = await self._build(tenant_id)
|
||||||
engine = self._factory.build(config)
|
|
||||||
self._engines[tenant_id] = engine
|
self._engines[tenant_id] = engine
|
||||||
return engine
|
return engine
|
||||||
|
|
||||||
|
# ---- 조립 (카탈로그 DB 유래 반영) ----------------------------------
|
||||||
|
async def _build(self, tenant_id: str) -> TenantEngine:
|
||||||
|
config = self._loader.load(tenant_id)
|
||||||
|
# action_mapping.type == "db" 면 카드 카탈로그(card.nego_cards)에서 action_to_card 를 동적 구성.
|
||||||
|
# Q-table action 축을 config 파일이 아니라 negodata 카탈로그가 정의한다(결합 제거).
|
||||||
|
if config.action_mapping.type == _CARD_SOURCE_DB:
|
||||||
|
await self._apply_db_catalog(config)
|
||||||
|
# 브랜드: 자동 온보딩 고객사(company_id=UUID)면 company.companies.name 으로 {company_name} 을 덮어쓴다.
|
||||||
|
# 데모 테넌트(비-UUID)·미조회 시 파일 resources.company_name 유지.
|
||||||
|
await self._apply_company_brand(config, tenant_id)
|
||||||
|
return self._factory.build(config)
|
||||||
|
|
||||||
|
async def _apply_company_brand(self, config: TenantConfig, tenant_id: str) -> None:
|
||||||
|
name = await resolve_company_name(self._company_repo, config.company_id or tenant_id)
|
||||||
|
if name:
|
||||||
|
config.resources.company_name = name
|
||||||
|
|
||||||
|
async def _apply_db_catalog(self, config: TenantConfig) -> None:
|
||||||
|
"""DB 카탈로그로 config.action_mapping.action_to_card 를 덮어쓴다(성공 시).
|
||||||
|
공용 카드 + 회사 전용 카드(company_id UUID 인 경우)로 action space 를 구성한다.
|
||||||
|
비었거나 DB 불가면 config 의 파일 action_to_card 를 그대로 폴백 사용한다."""
|
||||||
|
cid = _as_uuid(config.company_id or config.tenant_id) # UUID(실 고객사)면 회사 카드 포함
|
||||||
|
|
||||||
|
async def _q(s):
|
||||||
|
_, numbers = await self._catalog_repo.get_nego_catalog(s, cid)
|
||||||
|
return numbers
|
||||||
|
|
||||||
|
try:
|
||||||
|
numbers = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(f"[TenantEngineRegistry] 카탈로그 조회 실패 tenant={config.tenant_id}: {ex} → 파일 폴백")
|
||||||
|
return
|
||||||
|
if not numbers:
|
||||||
|
LOG.w(f"[TenantEngineRegistry] 카탈로그 비어있음 tenant={config.tenant_id} → 파일 action_to_card 폴백")
|
||||||
|
return
|
||||||
|
config.action_mapping.action_to_card = {str(i): num for i, num in enumerate(numbers)}
|
||||||
|
|
||||||
|
def clear_all(self) -> int:
|
||||||
|
"""캐시된 엔진 전체를 비운다(공용 카탈로그 변경 등 전역 반영용). 반환: 비운 엔진 수.
|
||||||
|
다음 요청에서 각 테넌트 엔진이 최신 카탈로그/config 로 재조립된다."""
|
||||||
|
n = len(self._engines)
|
||||||
|
self._engines.clear()
|
||||||
|
self._loader.invalidate() # 인자 없이 = 전체 config 캐시 무효화
|
||||||
|
return n
|
||||||
|
|
||||||
def cached_tenants(self) -> list[str]:
|
def cached_tenants(self) -> list[str]:
|
||||||
return list(self._engines.keys())
|
return list(self._engines.keys())
|
||||||
|
|
||||||
|
|||||||
@@ -49,9 +49,14 @@ policy:
|
|||||||
epsilon: 1.0e-6
|
epsilon: 1.0e-6
|
||||||
|
|
||||||
action_mapping:
|
action_mapping:
|
||||||
type: file
|
# db: action_to_card 를 card.nego_cards 카탈로그(user_id NULL, number 순)에서 동적 구성 — 정본.
|
||||||
# 기본 9카드 — 자동 온보딩(신규 company_id) 테넌트가 물려받는 카드 공간(base 정책 162×9와 정합).
|
# 카드가 negodata 에서 추가/삭제되면 action space 가 자동 반영된다(config 수정 불필요).
|
||||||
# 테넌트는 자사 카탈로그(card.nego_cards/tenant_action_cards)로 override 한다.
|
# 아래 action_to_card 는 DB 카탈로그가 비어있을 때만 쓰는 폴백(정합용 스냅샷)이다.
|
||||||
|
# file: 아래 action_to_card 를 그대로 사용(데모/오프라인).
|
||||||
|
type: db
|
||||||
|
# [폴백] 카탈로그 11장(카드_기획문서 일반카드) 스냅샷 — action_id 0~10 ↔ NGC-001~NGC-011.
|
||||||
|
# Q-table action 차원 = 카탈로그 크기. 견적별 선택은 action space 축소가 아니라 available_mask 로 처리
|
||||||
|
# (선택 카드만 pickable) — action_id↔카드 대응을 견적마다 일정하게 유지해 학습 일관성 보장.
|
||||||
action_to_card:
|
action_to_card:
|
||||||
"0": "NGC-001"
|
"0": "NGC-001"
|
||||||
"1": "NGC-002"
|
"1": "NGC-002"
|
||||||
@@ -62,6 +67,8 @@ action_mapping:
|
|||||||
"6": "NGC-007"
|
"6": "NGC-007"
|
||||||
"7": "NGC-008"
|
"7": "NGC-008"
|
||||||
"8": "NGC-009"
|
"8": "NGC-009"
|
||||||
|
"9": "NGC-010"
|
||||||
|
"10": "NGC-011"
|
||||||
|
|
||||||
cards:
|
cards:
|
||||||
# file: scripts_cards.json(파일) 사용. backoffice_db: card.nego_cards.script(negodata 편집 정본)를
|
# file: scripts_cards.json(파일) 사용. backoffice_db: card.nego_cards.script(negodata 편집 정본)를
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ reward:
|
|||||||
|
|
||||||
action_mapping:
|
action_mapping:
|
||||||
type: file
|
type: file
|
||||||
action_to_card: # 동일 차원(9) 유지 → warm-start 가능. 합성 데모 코드(테넌트 B).
|
action_to_card: # 동일 차원(11) 유지 → warm-start 가능. 합성 데모 코드(테넌트 B).
|
||||||
"0": "NGC-B001"
|
"0": "NGC-B001"
|
||||||
"1": "NGC-B002"
|
"1": "NGC-B002"
|
||||||
"2": "NGC-B003"
|
"2": "NGC-B003"
|
||||||
@@ -33,6 +33,8 @@ action_mapping:
|
|||||||
"6": "NGC-B007"
|
"6": "NGC-B007"
|
||||||
"7": "NGC-B008"
|
"7": "NGC-B008"
|
||||||
"8": "NGC-B009"
|
"8": "NGC-B009"
|
||||||
|
"9": "NGC-B010"
|
||||||
|
"10": "NGC-B011"
|
||||||
|
|
||||||
llm:
|
llm:
|
||||||
enabled: false
|
enabled: false
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ company_id: null # P3 시드 시 company.companies.company_id(uuid)
|
|||||||
|
|
||||||
action_mapping:
|
action_mapping:
|
||||||
type: file
|
type: file
|
||||||
action_to_card: # 우리 중립 데모 카드 코드(합성). 실제 카드 코드 아님.
|
action_to_card: # 우리 중립 데모 카드 코드(합성). 실제 카드 코드 아님. 카탈로그 11장(_base 와 정합).
|
||||||
"0": "NGC-A001"
|
"0": "NGC-A001"
|
||||||
"1": "NGC-A002"
|
"1": "NGC-A002"
|
||||||
"2": "NGC-A003"
|
"2": "NGC-A003"
|
||||||
@@ -18,6 +18,8 @@ action_mapping:
|
|||||||
"6": "NGC-A007"
|
"6": "NGC-A007"
|
||||||
"7": "NGC-A008"
|
"7": "NGC-A008"
|
||||||
"8": "NGC-A009"
|
"8": "NGC-A009"
|
||||||
|
"9": "NGC-A010"
|
||||||
|
"10": "NGC-A011"
|
||||||
|
|
||||||
llm:
|
llm:
|
||||||
enabled: false # P7 에서 테넌트별 자격증명 주입
|
enabled: false # P7 에서 테넌트별 자격증명 주입
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ async def test_4_4_company_id_auto_onboard():
|
|||||||
eng = await _reg().get_engine(COMPANY_ID)
|
eng = await _reg().get_engine(COMPANY_ID)
|
||||||
assert eng.tenant_id == COMPANY_ID
|
assert eng.tenant_id == COMPANY_ID
|
||||||
assert eng.company_id == COMPANY_ID # 학습/세션이 이 company_id 로 격리
|
assert eng.company_id == COMPANY_ID # 학습/세션이 이 company_id 로 격리
|
||||||
assert eng.action_space_size == 9 # base 기본 카드(162×9 정합)
|
assert eng.action_space_size == 11 # base 기본 카드(162×11 정합)
|
||||||
assert eng.state_space_size == 162
|
assert eng.state_space_size == 162
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ _T_QUOTATIONS = table(
|
|||||||
"quotations",
|
"quotations",
|
||||||
column("qt_id"), column("user_id"), column("qt_setting_id"), column("version_id"),
|
column("qt_id"), column("user_id"), column("qt_setting_id"), column("version_id"),
|
||||||
column("name"), column("number"), column("type"), column("status"),
|
column("name"), column("number"), column("type"), column("status"),
|
||||||
column("start_time"), column("end_time"), column("supplier_type"),
|
column("start_time"), column("end_time"),
|
||||||
schema="quotation",
|
schema="quotation",
|
||||||
)
|
)
|
||||||
_T_ITEMS = table(
|
_T_ITEMS = table(
|
||||||
@@ -80,7 +80,6 @@ async def test_context_loaded_from_db(db_engine):
|
|||||||
qt_id=qid, user_id=uuid.uuid4(), qt_setting_id=uuid.uuid4(), version_id=uuid.uuid4(),
|
qt_id=qid, user_id=uuid.uuid4(), qt_setting_id=uuid.uuid4(), version_id=uuid.uuid4(),
|
||||||
name="로더 테스트", number="QT-LOADER-TEST", type=3, status=2,
|
name="로더 테스트", number="QT-LOADER-TEST", type=3, status=2,
|
||||||
start_time=now, end_time=now + timedelta(days=1),
|
start_time=now, end_time=now + timedelta(days=1),
|
||||||
supplier_type=2, # manufacture(제조) → 유통 코드 "A"
|
|
||||||
))
|
))
|
||||||
|
|
||||||
def _ins_sess(s, session_id, supplier_id):
|
def _ins_sess(s, session_id, supplier_id):
|
||||||
@@ -125,7 +124,7 @@ async def test_context_loaded_from_db(db_engine):
|
|||||||
assert c["distribution_code"] == "B" # supplier_items.supply_type=3(총판) → B (매핑 우선)
|
assert c["distribution_code"] == "B" # supplier_items.supply_type=3(총판) → B (매핑 우선)
|
||||||
assert c["partner_count"] == 2 # 매핑 기준 취급 협력사 2곳 → MULTIPLE
|
assert c["partner_count"] == 2 # 매핑 기준 취급 협력사 2곳 → MULTIPLE
|
||||||
|
|
||||||
# 매핑 삭제 후 새 세션(sid2) → 폴백 경로: 유통코드=quotations.supplier_type, 파트너=세션 이력
|
# 매핑 삭제 후 새 세션(sid2) → 유통코드는 ChatService 기본값, 파트너는 세션 이력 폴백
|
||||||
err = await DB_SESSION_MNG.execute_lambda_run(
|
err = await DB_SESSION_MNG.execute_lambda_run(
|
||||||
[DBType.MAIN.value],
|
[DBType.MAIN.value],
|
||||||
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SUPPLIER_ITEMS).where(_T_SUPPLIER_ITEMS.c.item_id == iid))],
|
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SUPPLIER_ITEMS).where(_T_SUPPLIER_ITEMS.c.item_id == iid))],
|
||||||
@@ -133,7 +132,7 @@ async def test_context_loaded_from_db(db_engine):
|
|||||||
assert err == ErrorType.SUCCESS
|
assert err == ErrorType.SUCCESS
|
||||||
await ChatService().chat(eng, Req_Chat(session_id=str(sid2)))
|
await ChatService().chat(eng, Req_Chat(session_id=str(sid2)))
|
||||||
c2 = (await ChatSessionRepository(eng.company_id).get(str(sid2))).context
|
c2 = (await ChatSessionRepository(eng.company_id).get(str(sid2))).context
|
||||||
assert c2["distribution_code"] == "A" # 폴백: quotations.supplier_type=2(제조) → A
|
assert c2["distribution_code"] == "A" # 매핑 없음 → ChatService 기본값
|
||||||
assert c2["partner_count"] == 2 # 폴백: 세션 이력 distinct supplier 2곳
|
assert c2["partner_count"] == 2 # 폴백: 세션 이력 distinct supplier 2곳
|
||||||
finally:
|
finally:
|
||||||
await DB_SESSION_MNG.execute_lambda_run(
|
await DB_SESSION_MNG.execute_lambda_run(
|
||||||
@@ -197,9 +196,6 @@ async def test_loader_with_crud_double(db_engine):
|
|||||||
return ErrorType.SUCCESS, 12_000_000.0
|
return ErrorType.SUCCESS, 12_000_000.0
|
||||||
|
|
||||||
async def get_supply_type(self, cdb, supplier_id, item_id):
|
async def get_supply_type(self, cdb, supplier_id, item_id):
|
||||||
return ErrorType.SUCCESS, None # 매핑 없음 → 견적 기록 폴백
|
|
||||||
|
|
||||||
async def get_quotation_supplier_type(self, cdb, quotation_id):
|
|
||||||
return ErrorType.SUCCESS, 3 # sole_agency(총판) → "B"
|
return ErrorType.SUCCESS, 3 # sole_agency(총판) → "B"
|
||||||
|
|
||||||
async def count_item_suppliers(self, cdb, item_id):
|
async def count_item_suppliers(self, cdb, item_id):
|
||||||
@@ -208,6 +204,9 @@ async def test_loader_with_crud_double(db_engine):
|
|||||||
async def count_item_session_suppliers(self, cdb, item_id):
|
async def count_item_session_suppliers(self, cdb, item_id):
|
||||||
return ErrorType.SUCCESS, 0 # 이력도 없음 → NONE
|
return ErrorType.SUCCESS, 0 # 이력도 없음 → NONE
|
||||||
|
|
||||||
|
async def get_quotation_card_numbers(self, cdb, quotation_id):
|
||||||
|
return ErrorType.SUCCESS, (["NGC-003", "NGC-008"], ["WC-02"]) # 견적 선택 카드
|
||||||
|
|
||||||
ctx = await NegotiationContextLoader(crud=_FakeCRUD()).load(str(uuid.uuid4()))
|
ctx = await NegotiationContextLoader(crud=_FakeCRUD()).load(str(uuid.uuid4()))
|
||||||
assert ctx is not None
|
assert ctx is not None
|
||||||
assert ctx.rq_type == "재견적" # qt_type=2(1:N)
|
assert ctx.rq_type == "재견적" # qt_type=2(1:N)
|
||||||
@@ -215,8 +214,10 @@ async def test_loader_with_crud_double(db_engine):
|
|||||||
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
|
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
|
||||||
assert ctx.item_price == 7000
|
assert ctx.item_price == 7000
|
||||||
assert ctx.revenue_amount == 12_000_000.0
|
assert ctx.revenue_amount == 12_000_000.0
|
||||||
assert ctx.distribution_code == "B" # supplier_type=3(총판) → B
|
assert ctx.distribution_code == "B" # supply_type=3(총판) → B
|
||||||
assert ctx.partner_type is PartnerType.NONE
|
assert ctx.partner_type is PartnerType.NONE
|
||||||
|
assert ctx.selected_nego_card_numbers == ["NGC-003", "NGC-008"]
|
||||||
|
assert ctx.selected_wild_card_numbers == ["WC-02"]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ def test_platform_neutral_defaults_load():
|
|||||||
def test_state_space_and_action_space_size():
|
def test_state_space_and_action_space_size():
|
||||||
cfg = _loader().load("ktcommerce")
|
cfg = _loader().load("ktcommerce")
|
||||||
assert cfg.state.state_space_size == 162 # 3×3×3×3×2 (차원 구성은 기능적 설계)
|
assert cfg.state.state_space_size == 162 # 3×3×3×3×2 (차원 구성은 기능적 설계)
|
||||||
assert cfg.action_mapping.action_space_size == 9
|
assert cfg.action_mapping.action_space_size == 11
|
||||||
# 합성 데모 카드 코드 (우리 스킴)
|
# 합성 데모 카드 코드 (우리 스킴)
|
||||||
assert cfg.action_mapping.action_to_card["0"] == "NGC-A001"
|
assert cfg.action_mapping.action_to_card["0"] == "NGC-A001"
|
||||||
assert cfg.action_mapping.action_to_card["8"] == "NGC-A009"
|
assert cfg.action_mapping.action_to_card["8"] == "NGC-A009"
|
||||||
@@ -77,15 +77,15 @@ def test_second_tenant_overrides_merged_on_base():
|
|||||||
assert cfg.policy.type == "ucb"
|
assert cfg.policy.type == "ucb"
|
||||||
# 차원은 데모 테넌트 A 와 동일(162) → base warm-start 호환(P5)
|
# 차원은 데모 테넌트 A 와 동일(162) → base warm-start 호환(P5)
|
||||||
assert cfg.state.state_space_size == 162
|
assert cfg.state.state_space_size == 162
|
||||||
assert cfg.action_mapping.action_space_size == 9
|
assert cfg.action_mapping.action_space_size == 11
|
||||||
assert cfg.action_mapping.action_to_card["0"] == "NGC-B001"
|
assert cfg.action_mapping.action_to_card["0"] == "NGC-B001"
|
||||||
|
|
||||||
|
|
||||||
def test_base_self_does_not_inherit():
|
def test_base_self_does_not_inherit():
|
||||||
cfg = _loader().load("_base")
|
cfg = _loader().load("_base")
|
||||||
assert cfg.tenant_id == "_base"
|
assert cfg.tenant_id == "_base"
|
||||||
# _base 는 기본 9카드(자동 온보딩 테넌트가 물려받음, base 정책 162×9 정합)
|
# _base 는 기본 11카드(자동 온보딩 테넌트가 물려받음, base 정책 162×11 정합)
|
||||||
assert cfg.action_mapping.action_space_size == 9
|
assert cfg.action_mapping.action_space_size == 11
|
||||||
|
|
||||||
|
|
||||||
def test_is_registered():
|
def test_is_registered():
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ def test_reward_deterministic_and_config_driven():
|
|||||||
def test_action_card_mapper_roundtrip_and_mask():
|
def test_action_card_mapper_roundtrip_and_mask():
|
||||||
cfg = _cfg("ktcommerce")
|
cfg = _cfg("ktcommerce")
|
||||||
mapper = ActionCardMapper(cfg.action_mapping)
|
mapper = ActionCardMapper(cfg.action_mapping)
|
||||||
assert mapper.action_space_size == 9
|
assert mapper.action_space_size == 11
|
||||||
assert mapper.get_card_id(0) == "NGC-A001"
|
assert mapper.get_card_id(0) == "NGC-A001"
|
||||||
assert mapper.get_action_id("NGC-A001") == 0
|
assert mapper.get_action_id("NGC-A001") == 0
|
||||||
assert mapper.get_card_id(99) is None
|
assert mapper.get_card_id(99) is None
|
||||||
@@ -139,7 +139,7 @@ def test_action_card_mapper_roundtrip_and_mask():
|
|||||||
assert mask.dtype == np.bool_
|
assert mask.dtype == np.bool_
|
||||||
assert mask[0] == False and mask[3] == False
|
assert mask[0] == False and mask[3] == False
|
||||||
assert mask[1] == True
|
assert mask[1] == True
|
||||||
assert mask.sum() == 7
|
assert mask.sum() == 9
|
||||||
|
|
||||||
# reload 로 다른 테넌트 카드셋 교체
|
# reload 로 다른 테넌트 카드셋 교체
|
||||||
mapper.reload(_cfg("imarketkorea").action_mapping)
|
mapper.reload(_cfg("imarketkorea").action_mapping)
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ async def test_two_tenants_distinct_engines():
|
|||||||
assert e1.mapper.get_card_id(0) == "NGC-A001"
|
assert e1.mapper.get_card_id(0) == "NGC-A001"
|
||||||
assert e2.mapper.get_card_id(0) == "NGC-B001"
|
assert e2.mapper.get_card_id(0) == "NGC-B001"
|
||||||
# 차원
|
# 차원
|
||||||
assert e1.state_space_size == 162 and e1.action_space_size == 9
|
assert e1.state_space_size == 162 and e1.action_space_size == 11
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
@@ -69,7 +69,7 @@ async def test_unregistered_company_id_auto_onboards():
|
|||||||
reg = _registry()
|
reg = _registry()
|
||||||
# 미등록 company_id(uuid)는 _base 자동 온보딩 → 엔진 생성됨(베이스 9카드, 162 state).
|
# 미등록 company_id(uuid)는 _base 자동 온보딩 → 엔진 생성됨(베이스 9카드, 162 state).
|
||||||
eng = await reg.get_engine("00000000-0000-0000-0000-000000000001")
|
eng = await reg.get_engine("00000000-0000-0000-0000-000000000001")
|
||||||
assert eng.action_space_size == 9 and eng.state_space_size == 162
|
assert eng.action_space_size == 11 and eng.state_space_size == 162
|
||||||
assert eng.company_id == "00000000-0000-0000-0000-000000000001"
|
assert eng.company_id == "00000000-0000-0000-0000-000000000001"
|
||||||
assert reg.is_registered("ktcommerce") is True
|
assert reg.is_registered("ktcommerce") is True
|
||||||
# 빈 키만 미등록 → KeyError
|
# 빈 키만 미등록 → KeyError
|
||||||
@@ -97,6 +97,132 @@ def test_episode_state_is_request_scoped():
|
|||||||
assert not hasattr(TenantEngine, "used_action_ids")
|
assert not hasattr(TenantEngine, "used_action_ids")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_action_space_from_db_catalog(db_engine):
|
||||||
|
"""action_mapping.type=db(_base) 면 카드 카탈로그(DB)가 action space 를 정의한다 — config 파일이 아님.
|
||||||
|
negodata 에서 카드가 추가/삭제되면 config 수정 없이 action space 가 반영됨을 의미."""
|
||||||
|
from common.enums import ErrorType
|
||||||
|
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
|
||||||
|
|
||||||
|
class _FakeCatalog(ICardCatalogRepository):
|
||||||
|
async def get_nego_catalog(self, cdb, company_id=None):
|
||||||
|
return ErrorType.SUCCESS, ["NGC-001", "NGC-002", "NGC-003"] # 3장짜리 카탈로그(파일은 11장)
|
||||||
|
|
||||||
|
reg = TenantEngineRegistry(
|
||||||
|
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
|
||||||
|
catalog_repo=_FakeCatalog(),
|
||||||
|
)
|
||||||
|
eng = await reg.get_engine("_base") # _base = type:db
|
||||||
|
assert eng.action_space_size == 3 # DB 카탈로그(3)가 정의 — 파일 폴백(11) 아님
|
||||||
|
assert eng.mapper.get_card_id(0) == "NGC-001"
|
||||||
|
assert eng.mapper.get_card_id(2) == "NGC-003"
|
||||||
|
assert eng.mapper.get_action_id("NGC-002") == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_action_space_falls_back_to_file_when_catalog_empty(db_engine):
|
||||||
|
"""카탈로그가 비면(신규/미시드 DB) 파일 action_to_card 로 폴백한다."""
|
||||||
|
from common.enums import ErrorType
|
||||||
|
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
|
||||||
|
|
||||||
|
class _EmptyCatalog(ICardCatalogRepository):
|
||||||
|
async def get_nego_catalog(self, cdb, company_id=None):
|
||||||
|
return ErrorType.SUCCESS, []
|
||||||
|
|
||||||
|
reg = TenantEngineRegistry(
|
||||||
|
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
|
||||||
|
catalog_repo=_EmptyCatalog(),
|
||||||
|
)
|
||||||
|
eng = await reg.get_engine("_base")
|
||||||
|
assert eng.action_space_size == 11 # 파일 폴백(11장 스냅샷)
|
||||||
|
assert eng.mapper.get_card_id(0) == "NGC-001"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_company_brand_from_db_for_auto_onboard(db_engine):
|
||||||
|
"""자동 온보딩 고객사(company_id=UUID)는 company.companies.name 으로 {company_name} 을 채운다."""
|
||||||
|
import uuid as _uuid
|
||||||
|
from common.enums import ErrorType
|
||||||
|
from tenancy.company_profile_repo import ICompanyProfileRepository
|
||||||
|
|
||||||
|
class _FakeCompany(ICompanyProfileRepository):
|
||||||
|
async def get_company_name(self, cdb, company_id):
|
||||||
|
return ErrorType.SUCCESS, "풀무원"
|
||||||
|
|
||||||
|
reg = TenantEngineRegistry(
|
||||||
|
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
|
||||||
|
company_repo=_FakeCompany(),
|
||||||
|
)
|
||||||
|
eng = await reg.get_engine(str(_uuid.uuid4())) # UUID → 자동 온보딩 + 브랜드 DB
|
||||||
|
assert eng.config.resources.company_name == "풀무원"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_demo_tenant_keeps_file_brand(db_engine):
|
||||||
|
"""데모 테넌트(비-UUID)는 회사명 조회 없이 파일 브랜드 유지."""
|
||||||
|
from common.enums import ErrorType
|
||||||
|
from tenancy.company_profile_repo import ICompanyProfileRepository
|
||||||
|
|
||||||
|
class _FakeCompany(ICompanyProfileRepository):
|
||||||
|
async def get_company_name(self, cdb, company_id):
|
||||||
|
return ErrorType.SUCCESS, "USED-ONLY-IF-QUERIED"
|
||||||
|
|
||||||
|
reg = TenantEngineRegistry(
|
||||||
|
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
|
||||||
|
company_repo=_FakeCompany(),
|
||||||
|
)
|
||||||
|
eng = await reg.get_engine("ktcommerce") # 비-UUID → 조회 안 함
|
||||||
|
assert eng.config.resources.company_name == "데모상사 A"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_catalog_includes_company_cards(db_engine):
|
||||||
|
"""per-company 카탈로그: 공용 카드(NGC-*) + 그 회사 유저가 만든 카드 — 공용 먼저 → 회사 뒤."""
|
||||||
|
import uuid as _uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from sqlalchemy import column, delete, insert, table
|
||||||
|
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.enums import DBType, ErrorType
|
||||||
|
from negotiation.cards.adapters.card_catalog_db import CardCatalogDbRepository
|
||||||
|
|
||||||
|
cid, uid, card_id = _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4()
|
||||||
|
_USERS = table("users", column("user_id"), column("company_id"), column("id"), column("password"),
|
||||||
|
column("last_accessed_at"), column("status"), column("role"), schema="company")
|
||||||
|
_NEGO = table("nego_cards", column("nego_card_id"), column("user_id"), column("name"),
|
||||||
|
column("number"), column("usage_type"), schema="card")
|
||||||
|
|
||||||
|
async def _seed(s):
|
||||||
|
await DB_SESSION_MNG.add(s, insert(_USERS).values(
|
||||||
|
user_id=uid, company_id=cid, id="pytest_catalog_user", password="x",
|
||||||
|
last_accessed_at=datetime.now(timezone.utc), status=1, role=1))
|
||||||
|
return await DB_SESSION_MNG.add(s, insert(_NEGO).values(
|
||||||
|
nego_card_id=card_id, user_id=uid, name="회사전용카드", number="COMP-01", usage_type=1))
|
||||||
|
|
||||||
|
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_seed])
|
||||||
|
assert err == ErrorType.SUCCESS
|
||||||
|
try:
|
||||||
|
repo = CardCatalogDbRepository()
|
||||||
|
_, nums = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
DBType.MAIN.value, 1, lambda s: repo.get_nego_catalog(s, cid))
|
||||||
|
assert "COMP-01" in nums # 회사 카드 포함
|
||||||
|
assert nums[0] == "NGC-001" # 공용이 먼저(action_id 0 안정)
|
||||||
|
assert nums[-1] == "COMP-01" # 회사 카드는 뒤에 append
|
||||||
|
assert nums.index("NGC-011") < nums.index("COMP-01") # 공용 전부 → 회사
|
||||||
|
|
||||||
|
# company_id 없으면 공용만 (회사 카드 제외)
|
||||||
|
_, shared_only = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
DBType.MAIN.value, 1, lambda s: repo.get_nego_catalog(s, None))
|
||||||
|
assert "COMP-01" not in shared_only
|
||||||
|
finally:
|
||||||
|
await DB_SESSION_MNG.execute_lambda_run(
|
||||||
|
[DBType.MAIN.value],
|
||||||
|
[lambda s: DB_SESSION_MNG.add(s, delete(_NEGO).where(_NEGO.c.nego_card_id == card_id)),
|
||||||
|
lambda s: DB_SESSION_MNG.add(s, delete(_USERS).where(_USERS.c.user_id == uid))],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_middleware_header_missing_unregistered_registered(client):
|
async def test_middleware_header_missing_unregistered_registered(client):
|
||||||
# 헤더 누락 → 400
|
# 헤더 누락 → 400
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ async def test_warm_start_copies_base_with_decayed_visits(db_engine):
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_cold_start_creates_warmstart_version(db_engine):
|
async def test_cold_start_creates_warmstart_version(db_engine):
|
||||||
await _seed_base()
|
await _seed_base(A=11) # ktcommerce action_space=11 과 차원 일치해야 warm-start
|
||||||
eng = await _reg().get_engine("ktcommerce") # 활성 버전 없음 → cold-start
|
eng = await _reg().get_engine("ktcommerce") # 활성 버전 없음 → cold-start
|
||||||
policy, version_id, repo = await QTablePolicyStore.load(eng)
|
policy, version_id, repo = await QTablePolicyStore.load(eng)
|
||||||
err, ver = await repo.read(lambda s: repo.get_active_version(s))
|
err, ver = await repo.read(lambda s: repo.get_active_version(s))
|
||||||
@@ -67,6 +67,57 @@ async def test_cold_start_creates_warmstart_version(db_engine):
|
|||||||
assert policy.qtable.q[5, 2] == 0.9
|
assert policy.qtable.q[5, 2] == 0.9
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_catalog_dim_change_migrates_preserving_learning(db_engine):
|
||||||
|
"""카탈로그 카드 수 변경(9→11) 시 학습 보존 마이그레이션 — 겹치는 셀 복사 + 새 카드 fresh."""
|
||||||
|
import uuid as _uuid
|
||||||
|
cid = str(_uuid.uuid4())
|
||||||
|
# 이 회사 활성 버전을 A=9 로 시드 + 셀 (5,2)=0.9
|
||||||
|
repo = LearningRepository(cid)
|
||||||
|
vid = await repo.get_or_create_active_version(
|
||||||
|
state_space_size=162, action_space_size=9, learning_rate=0.1, discount_factor=0.95,
|
||||||
|
scope=2, version_name="old_v9")
|
||||||
|
await repo.upsert_cell(vid, state_index=5, action_id=2, q_value=0.9, count=7)
|
||||||
|
|
||||||
|
# 엔진(_base type:db → 카탈로그 11장) 로드 → 9≠11 감지 → 마이그레이션
|
||||||
|
eng = await _reg().get_engine(cid)
|
||||||
|
assert eng.action_space_size == 11
|
||||||
|
policy, new_vid, _ = await QTablePolicyStore.load(eng)
|
||||||
|
assert str(new_vid) != str(vid) # 새 버전
|
||||||
|
assert policy.qtable.q[5, 2] == 0.9 # 기존 학습 보존
|
||||||
|
assert policy.qtable.q[5, 10] == 0.0 # 새 카드(action 10) fresh
|
||||||
|
assert policy.qtable.visits[5, 2] == 7 # 방문수도 보존
|
||||||
|
# 새 버전이 활성 · 차원 11
|
||||||
|
err, active = await repo.read(lambda s: repo.get_active_version(s))
|
||||||
|
assert str(active.version_id) == str(new_vid) and active.action_space_size == 11
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_migration_remaps_by_card_number(db_engine):
|
||||||
|
"""카드번호 기반 마이그레이션 — 중간 카드 삭제로 action_id 가 밀려도 학습이 카드를 따라간다."""
|
||||||
|
import uuid as _uuid
|
||||||
|
cid = str(_uuid.uuid4())
|
||||||
|
repo = LearningRepository(cid)
|
||||||
|
# A=3, action_cards=[NGC-001, NGC-002, NGC-003]. (5,2)=0.9 는 NGC-003 의 학습.
|
||||||
|
vid = await repo.get_or_create_active_version(
|
||||||
|
state_space_size=162, action_space_size=3, learning_rate=0.1, discount_factor=0.95,
|
||||||
|
scope=2, version_name="v_cards3", action_cards=["NGC-001", "NGC-002", "NGC-003"])
|
||||||
|
await repo.upsert_cell(vid, state_index=5, action_id=2, q_value=0.9, count=4) # NGC-003
|
||||||
|
await repo.upsert_cell(vid, state_index=5, action_id=0, q_value=0.3, count=2) # NGC-001
|
||||||
|
_, active = await repo.read(lambda s: repo.get_active_version(s))
|
||||||
|
|
||||||
|
# 새 카탈로그: 중간 NGC-002 제거 → [NGC-001, NGC-003] (A=2). NGC-003: old action 2 → new action 1.
|
||||||
|
new_vid = await repo.migrate_active_version_dim(
|
||||||
|
old_version=active, state_space_size=162, action_space_size=2,
|
||||||
|
learning_rate=0.1, discount_factor=0.95, action_cards=["NGC-001", "NGC-003"])
|
||||||
|
assert new_vid is not None
|
||||||
|
qcells, _ = await repo.load_cells(new_vid)
|
||||||
|
qmap = {(st, a): q for st, a, q in qcells}
|
||||||
|
assert qmap.get((5, 1)) == 0.9 # NGC-003 학습이 새 action_id 1 로 따라감(밀림 보정)
|
||||||
|
assert qmap.get((5, 0)) == 0.3 # NGC-001 은 그대로 action_id 0
|
||||||
|
assert (5, 2) not in qmap # 삭제된 NGC-002 자리 없음
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_dimension_mismatch_falls_back_to_heuristic(db_engine):
|
async def test_dimension_mismatch_falls_back_to_heuristic(db_engine):
|
||||||
await _seed_base(S=162, A=9)
|
await _seed_base(S=162, A=9)
|
||||||
|
|||||||
@@ -66,6 +66,26 @@ async def test_card_update_search(client, db_engine):
|
|||||||
assert any(m["card_id"] == "CUSTOM-X" for m in allm["mapping"])
|
assert any(m["card_id"] == "CUSTOM-X" for m in allm["mapping"])
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_catalog_refresh(client, db_engine):
|
||||||
|
# 카탈로그 발행 후 엔진 재조립 트리거 — 성공 + action_space 반환. 헤더 없으면 400.
|
||||||
|
r = await client.post("/v1/catalog-refresh", headers=H)
|
||||||
|
assert r.status_code == 200
|
||||||
|
body = r.json()
|
||||||
|
assert body["success"] and body["action_space_size"] >= 1
|
||||||
|
r2 = await client.post("/v1/catalog-refresh")
|
||||||
|
assert r2.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_catalog_refresh_all_no_tenant_header(client, db_engine):
|
||||||
|
# 공용 카탈로그 전역 반영 — 테넌트 헤더 없이도 200(화이트리스트) + 캐시 클리어.
|
||||||
|
await client.post("/v1/catalog-refresh", headers=H) # 엔진 하나 캐시
|
||||||
|
r = await client.post("/v1/catalog-refresh-all") # 헤더 없음
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.json()["success"] is True
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_invalidate_and_reset_scoped(client, db_engine):
|
async def test_invalidate_and_reset_scoped(client, db_engine):
|
||||||
# 가격협상 카드선택이 일어나는 긴 경로(850→900→990)로 양 테넌트 데이터 생성
|
# 가격협상 카드선택이 일어나는 긴 경로(850→900→990)로 양 테넌트 데이터 생성
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
1. 전체 대화: 서비스안내→담당자확인→협상품목안내→가격협상→와일드카드→협상완료→협상종료(chat_end).
|
1. 전체 대화: 서비스안내→담당자확인→협상품목안내→가격협상→와일드카드→협상완료→협상종료(chat_end).
|
||||||
2. 가격협상 턴에서 카드 선택 + 학습(card_id, updated_q).
|
2. 가격협상 턴에서 카드 선택 + 학습(card_id, updated_q).
|
||||||
3. 와일드카드 발동(wild_card_budget) + 종료 보상(success).
|
3. 와일드카드 발동(wild_card_1pct) + 종료 보상(success).
|
||||||
4. 브랜드 치환 테넌트별(데모상사 A/B), 클린룸(스크립트에 KT 흔적 없음).
|
4. 브랜드 치환 테넌트별(데모상사 A/B), 클린룸(스크립트에 KT 흔적 없음).
|
||||||
5. 경험로그 적재 + 종료 후 진행 시 에러.
|
5. 경험로그 적재 + 종료 후 진행 시 에러.
|
||||||
6. (HTTP) 헤더로 새 세션 시작 + 한 턴 진행.
|
6. (HTTP) 헤더로 새 세션 시작 + 한 턴 진행.
|
||||||
@@ -15,6 +15,8 @@ import pytest
|
|||||||
|
|
||||||
from router.v1.chat.protocol import Req_Chat
|
from router.v1.chat.protocol import Req_Chat
|
||||||
from services.chat_service import ChatService, reset_sessions
|
from services.chat_service import ChatService, reset_sessions
|
||||||
|
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession
|
||||||
|
from negotiation.chat.service.script_repository import ScriptRepository
|
||||||
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
||||||
from tenancy.config_loader import TenantConfigLoader
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
from tenancy.registry import TenantEngineRegistry
|
from tenancy.registry import TenantEngineRegistry
|
||||||
@@ -44,8 +46,9 @@ async def test_full_conversation_reaches_completion(db_engine):
|
|||||||
reset_sessions()
|
reset_sessions()
|
||||||
eng = await _reg().get_engine("ktcommerce")
|
eng = await _reg().get_engine("ktcommerce")
|
||||||
svc = ChatService()
|
svc = ChatService()
|
||||||
# anchor=9900, target=10000(기본). 11000(>10395)→가격협상(카드), 10200(9900~10395)→와일드카드, 9800(≤anchor)→우선협상
|
# anchor=9900, target=10000(기본). 11000(>anchor*1.02)→가격협상(카드),
|
||||||
turns = [None, "확인", "예", "확인", "11000", "예", "10200", "예", "9800", "예",
|
# 10000(anchor<p≤anchor*1.02)→1% 와일드카드→수락하면 협상완료.
|
||||||
|
turns = [None, "확인", "예", "확인", "11000", "예", "10000", "예", "예",
|
||||||
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."]
|
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."]
|
||||||
out = await _run(svc, eng, turns)
|
out = await _run(svc, eng, turns)
|
||||||
steps = [r.step for r in out]
|
steps = [r.step for r in out]
|
||||||
@@ -59,8 +62,8 @@ async def test_full_conversation_reaches_completion(db_engine):
|
|||||||
assert nego and nego[0].card_id and nego[0].card_id.startswith("NGC-A")
|
assert nego and nego[0].card_id and nego[0].card_id.startswith("NGC-A")
|
||||||
assert nego[0].updated_q is not None
|
assert nego[0].updated_q is not None
|
||||||
|
|
||||||
# 와일드카드 발동
|
# 와일드카드 발동 (1% 인하)
|
||||||
assert any(r.step == "wild_card_budget" for r in out)
|
assert any(r.step == "wild_card_1pct" for r in out)
|
||||||
|
|
||||||
# 종료 보상(success)
|
# 종료 보상(success)
|
||||||
done = [r for r in out if r.outcome == "success"]
|
done = [r for r in out if r.outcome == "success"]
|
||||||
@@ -122,6 +125,92 @@ def test_acceptance_ratio_dynamic_calc():
|
|||||||
assert calc({"input_price": 9800}) == 0.0 # 기준가 전무(과거 세션 호환)
|
assert calc({"input_price": 9800}) == 0.0 # 기준가 전무(과거 세션 호환)
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_id_fixed_mapping_and_selection_mask():
|
||||||
|
"""카드 정리 후: action_id↔카드는 테넌트 매핑으로 고정, 견적 선택은 available_mask 로 걸러진다.
|
||||||
|
(구 인덱스 방식 폐기 — selected[action_id] 인덱싱은 견적마다 action_id 의미가 달라져 Q-table 오염.)"""
|
||||||
|
class _Mapper:
|
||||||
|
_m = {i: f"NGC-A{i + 1:03d}" for i in range(11)}
|
||||||
|
def get_card_id(self, a):
|
||||||
|
return self._m.get(a)
|
||||||
|
def get_action_id(self, num):
|
||||||
|
return next((a for a, c in self._m.items() if c == num), None)
|
||||||
|
class _Engine:
|
||||||
|
mapper = _Mapper()
|
||||||
|
action_space_size = 11
|
||||||
|
eng = _Engine()
|
||||||
|
session = ChatSession(
|
||||||
|
session_id="00000000-0000-0000-0000-000000000001", tenant_id="ktcommerce", company_id="ktcommerce",
|
||||||
|
context={"selected_nego_card_numbers": ["NGC-A003", "NGC-A008"]}, action_space_size=11,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ① card_id 는 고정 매핑 (선택 리스트 인덱싱 아님)
|
||||||
|
assert ChatService._card_id_for_action(eng, session, 0) == "NGC-A001"
|
||||||
|
assert ChatService._card_id_for_action(eng, session, 2) == "NGC-A003"
|
||||||
|
|
||||||
|
# ② 선택은 mask 로 — NGC-A003(action 2), NGC-A008(action 7) 만 pickable
|
||||||
|
mask = ChatService._selection_mask(eng, session)
|
||||||
|
assert mask is not None and mask[2] and mask[7]
|
||||||
|
assert not mask[0] and not mask[5] and mask.sum() == 2
|
||||||
|
|
||||||
|
# ③ 사용한 action 은 mask 에서 제외
|
||||||
|
session.used_action_ids = {2}
|
||||||
|
mask2 = ChatService._selection_mask(eng, session)
|
||||||
|
assert not mask2[2] and mask2[7] and mask2.sum() == 1
|
||||||
|
|
||||||
|
# ④ 선택 없으면 None → 전체 허용(폴백)
|
||||||
|
session.context["selected_nego_card_numbers"] = []
|
||||||
|
assert ChatService._selection_mask(eng, session) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_1pct_wildcard_still_runs_without_selected_wildcard():
|
||||||
|
"""1% 인하는 기본 제공 카드라 DB 견적에서 와일드카드를 선택하지 않아도 발동한다."""
|
||||||
|
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce")
|
||||||
|
repo = ScriptRepository(cfg, _TENANTS_DIR)
|
||||||
|
engine = ChatEngine(repo, rq_type="재협상")
|
||||||
|
session = ChatSession(
|
||||||
|
session_id="00000000-0000-0000-0000-000000000002",
|
||||||
|
tenant_id="ktcommerce",
|
||||||
|
company_id="ktcommerce",
|
||||||
|
step="가격협상_확인",
|
||||||
|
action_space_size=0,
|
||||||
|
context={
|
||||||
|
"input_price": 10000,
|
||||||
|
"anchor_price": 9900,
|
||||||
|
"target_price": 10000,
|
||||||
|
"round": 1,
|
||||||
|
"allow_selected_wildcards": False,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
view = engine.advance(session, "예")
|
||||||
|
assert view.step == "wild_card_1pct"
|
||||||
|
|
||||||
|
|
||||||
|
def test_budget_wildcard_requires_selected_wildcard_for_db_context():
|
||||||
|
"""재원부족 구간은 DB 견적에서 와일드카드를 선택했을 때만 발동한다."""
|
||||||
|
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce")
|
||||||
|
repo = ScriptRepository(cfg, _TENANTS_DIR)
|
||||||
|
engine = ChatEngine(repo, rq_type="재협상")
|
||||||
|
session = ChatSession(
|
||||||
|
session_id="00000000-0000-0000-0000-000000000003",
|
||||||
|
tenant_id="ktcommerce",
|
||||||
|
company_id="ktcommerce",
|
||||||
|
step="가격협상_확인",
|
||||||
|
action_space_size=0,
|
||||||
|
context={
|
||||||
|
"input_price": 10200,
|
||||||
|
"anchor_price": 9900,
|
||||||
|
"target_price": 10000,
|
||||||
|
"round": 1,
|
||||||
|
"allow_selected_wildcards": False,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
view = engine.advance(session, "예")
|
||||||
|
assert view.step == "가격협상"
|
||||||
|
assert not view.step.startswith("wild_card_")
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_priority_completes_without_wildcard(db_engine):
|
async def test_priority_completes_without_wildcard(db_engine):
|
||||||
reset_sessions()
|
reset_sessions()
|
||||||
|
|||||||
@@ -151,3 +151,20 @@ async def test_resolve_card_script_db_mode_falls_back_to_file(monkeypatch):
|
|||||||
|
|
||||||
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800})
|
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800})
|
||||||
assert out and "9800" in out # 파일 폴백 멘트
|
assert out and "9800" in out # 파일 폴백 멘트
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_resolve_card_script_prefer_db_for_selected_cards(monkeypatch):
|
||||||
|
"""견적에서 선택된 백오피스 카드 번호는 file 모드여도 DB 멘트를 우선한다."""
|
||||||
|
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce")
|
||||||
|
assert cfg.cards.source_type == "file"
|
||||||
|
fake = _FakeCardRepo({"2": "선택 카드 DB 멘트 **{input_price}원**"})
|
||||||
|
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
|
||||||
|
|
||||||
|
async def _fake_lambda(_db, _wr, func):
|
||||||
|
return await func(None)
|
||||||
|
from negotiation.chat.service import script_repository as _sr
|
||||||
|
monkeypatch.setattr(_sr.DB_SESSION_MNG, "execute_lambda", _fake_lambda)
|
||||||
|
|
||||||
|
out = await repo.resolve_card_script(1, "2", {"input_price": 10200}, prefer_db=True)
|
||||||
|
assert out == "선택 카드 DB 멘트 **10200원**"
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""카드 스크립트 → 임베딩 캐시 생성 (action-as-feature 준비, 1회 실행).
|
||||||
|
|
||||||
|
card.nego_cards(11장)의 name+script 를 문장 임베딩으로 변환해 artifacts/card_embeddings.npz 에 저장.
|
||||||
|
새 카드가 추가되면 이 스크립트를 다시 돌리면 된다(그 카드만 임베딩돼 캐시에 합류).
|
||||||
|
|
||||||
|
실행:
|
||||||
|
APP_ENV=local python -m tools.build_card_embeddings
|
||||||
|
출력:
|
||||||
|
artifacts/card_embeddings.npz (numbers, names, strategy, tone, embeddings[N,384])
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
ARTIFACTS = os.path.join(_HERE, "..", "artifacts")
|
||||||
|
OUT_PATH = os.path.join(ARTIFACTS, "card_embeddings.npz")
|
||||||
|
|
||||||
|
MODEL_NAME = "paraphrase-multilingual-MiniLM-L12-v2" # 384차원, 한국어 지원, 로컬/무료
|
||||||
|
|
||||||
|
|
||||||
|
async def load_cards():
|
||||||
|
"""card.nego_cards 에서 (number, name, script, strategy_type, tone) 로드."""
|
||||||
|
import asyncpg
|
||||||
|
conn = await asyncpg.connect(
|
||||||
|
host="127.0.0.1", port=5432, user="postgres", password="password", database="negosium_db")
|
||||||
|
try:
|
||||||
|
rows = await conn.fetch(
|
||||||
|
"SELECT number, name, script, strategy_type, tone FROM card.nego_cards "
|
||||||
|
"WHERE deleted = FALSE ORDER BY number")
|
||||||
|
return [(r["number"], r["name"], r["script"], r["strategy_type"], r["tone"]) for r in rows]
|
||||||
|
finally:
|
||||||
|
await conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
cards = asyncio.run(load_cards())
|
||||||
|
if not cards:
|
||||||
|
raise SystemExit("card.nego_cards 가 비어있음 — DB 시드 확인 (docker start negosium-pg)")
|
||||||
|
print(f"카드 {len(cards)}장 로드: {[c[0] for c in cards]}")
|
||||||
|
|
||||||
|
from sentence_transformers import SentenceTransformer
|
||||||
|
model = SentenceTransformer(MODEL_NAME)
|
||||||
|
texts = [f"{name}. {script}" for _, name, script, _, _ in cards]
|
||||||
|
emb = model.encode(texts, normalize_embeddings=True) # [N, 384], 단위벡터
|
||||||
|
print(f"임베딩 shape: {emb.shape}")
|
||||||
|
|
||||||
|
os.makedirs(ARTIFACTS, exist_ok=True)
|
||||||
|
np.savez(
|
||||||
|
OUT_PATH,
|
||||||
|
numbers=np.array([c[0] for c in cards]),
|
||||||
|
names=np.array([c[1] for c in cards]),
|
||||||
|
strategy=np.array([c[3] for c in cards], dtype=np.int64),
|
||||||
|
tone=np.array([c[4] for c in cards], dtype=np.int64),
|
||||||
|
embeddings=emb.astype(np.float32),
|
||||||
|
)
|
||||||
|
print(f"저장: {OUT_PATH}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
"""기존 Q-Table(UCB) vs action-as-feature DQN 공정 비교 — 고객사 성향 조건화 환경 (최종).
|
||||||
|
|
||||||
|
같은 환경(FeatureBuyer 2축 + 협력사·고객사성향 랜덤)에서 동일 에피소드로 학습·평가.
|
||||||
|
- Q-Table: 이산 state 162칸 + 카드=슬롯. 성향(고객사) 입력 자체가 불가능 → 평균 성향에 수렴
|
||||||
|
- DQN : 연속 상태 + 성향 벡터 + 카드 특징(임베딩+전략/톤 one-hot)
|
||||||
|
|
||||||
|
평가 4종:
|
||||||
|
① 학습 카드 9장 — 평균보상(진짜 목적함수) + top3 적중(MC 정답 기준)
|
||||||
|
② zero-shot 11장 — 안 본 카드 2장 포함
|
||||||
|
③ 새 카드 첫 턴 사용률 — 구조적 차이
|
||||||
|
④ 성향 극단 테스트 — 같은 협력사, 성향만 바꿨을 때 카드를 바꾸는가
|
||||||
|
|
||||||
|
실행: APP_ENV=local python -m tools.compare_qtable_vs_dqn
|
||||||
|
"""
|
||||||
|
|
||||||
|
import random
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
|
||||||
|
from eval_harness.buyer import Scenario
|
||||||
|
from eval_harness.feature_buyer import FeatureBuyer, SupplierProfile, sample_supplier
|
||||||
|
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
|
||||||
|
from negotiation.policies.qtable_policy import UCBQTablePolicy
|
||||||
|
from negotiation.policies.base import EpisodeState, PolicyContext, Transition
|
||||||
|
from negotiation.qtable.domain.model.q_table import QTable
|
||||||
|
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome
|
||||||
|
from negotiation.qtable.domain.service.feature_builder import (
|
||||||
|
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features)
|
||||||
|
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||||
|
from negotiation.qtable.domain.service.state_calculator import state_index
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
from tools.train_feature_dqn import (
|
||||||
|
ANCHOR, HOLDOUT, MAX_TURNS, TARGET, load_cards, make_snapshot, pref_config, sample_tenant_pref)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 정책 어댑터 ------------------------------------------------------------------
|
||||||
|
class DQNAdapter:
|
||||||
|
name = "feature_dqn"
|
||||||
|
|
||||||
|
def __init__(self, policy, feat):
|
||||||
|
self.p, self.feat = policy, feat
|
||||||
|
|
||||||
|
def _sf(self, snap, tf):
|
||||||
|
return np.concatenate([build_state_features(snap), tf])
|
||||||
|
|
||||||
|
def choose(self, snap, tf, avail, greedy):
|
||||||
|
self.p.greedy = greedy
|
||||||
|
i, _, _ = self.p.select(self._sf(snap, tf), np.stack([self.feat[c] for c in avail]))
|
||||||
|
return avail[i]
|
||||||
|
|
||||||
|
def learn(self, snap, tf, card, reward, next_snap, next_avail, done):
|
||||||
|
sf = self._sf(snap, tf)
|
||||||
|
if done or next_snap is None:
|
||||||
|
self.p.remember(sf, self.feat[card], reward, None, None, True)
|
||||||
|
else:
|
||||||
|
self.p.remember(sf, self.feat[card], reward, self._sf(next_snap, tf),
|
||||||
|
np.stack([self.feat[c] for c in next_avail]), False)
|
||||||
|
self.p.train_step()
|
||||||
|
|
||||||
|
|
||||||
|
class QTableAdapter:
|
||||||
|
"""기존 UCBQTablePolicy. 성향(tf)은 구조상 받을 수 없다 — 이산 state 162칸에 그 축이 없음."""
|
||||||
|
|
||||||
|
name = "qtable_ucb"
|
||||||
|
|
||||||
|
def __init__(self, all_numbers, state_cfg, lr=0.1, gamma=0.95):
|
||||||
|
self.numbers = list(all_numbers)
|
||||||
|
self.a_of = {n: i for i, n in enumerate(self.numbers)}
|
||||||
|
self.state_cfg = state_cfg
|
||||||
|
self.qt = QTable(162, len(self.numbers), learning_rate=lr, discount_factor=gamma)
|
||||||
|
self.pol = UCBQTablePolicy(self.qt)
|
||||||
|
|
||||||
|
def choose(self, snap, tf, avail, greedy):
|
||||||
|
idx = state_index(snap, self.state_cfg)
|
||||||
|
if greedy:
|
||||||
|
q = self.qt.row(idx)
|
||||||
|
return max(avail, key=lambda c: q[self.a_of[c]])
|
||||||
|
mask = np.zeros(len(self.numbers), dtype=bool)
|
||||||
|
for c in avail:
|
||||||
|
mask[self.a_of[c]] = True
|
||||||
|
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=len(self.numbers),
|
||||||
|
episode=EpisodeState(), available_mask=mask)
|
||||||
|
return self.numbers[self.pol.select(ctx).action_id]
|
||||||
|
|
||||||
|
def learn(self, snap, tf, card, reward, next_snap, next_avail, done):
|
||||||
|
idx = state_index(snap, self.state_cfg)
|
||||||
|
nidx = state_index(next_snap, self.state_cfg) if (next_snap is not None and not done) else None
|
||||||
|
self.pol.update(Transition(state_index=idx, action_id=self.a_of[card], reward=reward,
|
||||||
|
next_state_index=nidx, done=done))
|
||||||
|
|
||||||
|
|
||||||
|
class RandomAdapter:
|
||||||
|
name = "random"
|
||||||
|
|
||||||
|
def __init__(self, seed=0):
|
||||||
|
self.rng = np.random.default_rng(seed)
|
||||||
|
|
||||||
|
def choose(self, snap, tf, avail, greedy):
|
||||||
|
return avail[self.rng.integers(len(avail))]
|
||||||
|
|
||||||
|
def learn(self, *a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 공용 에피소드 -----------------------------------------------------------------
|
||||||
|
def run_episode(adapter, sup, tf, pool, strat, rc, seed, learn=True, greedy=False, forced_first=None):
|
||||||
|
buyer = FeatureBuyer(sup, strat, seed=seed, max_turns=MAX_TURNS)
|
||||||
|
scenario = Scenario(anchor_price=ANCHOR, target_price=TARGET, revenue_amount=sup.revenue_amount,
|
||||||
|
distribution_code=sup.distribution_code, partner_count=sup.partner_count)
|
||||||
|
price0 = TARGET * 1.15
|
||||||
|
price, used, total_r, first_card = price0, set(), 0.0, None
|
||||||
|
|
||||||
|
for turn in range(1, MAX_TURNS + 1):
|
||||||
|
acceptance = max(0.0, (price0 - price) / price0)
|
||||||
|
snap = make_snapshot(sup, price, turn, acceptance)
|
||||||
|
avail = [c for c in pool if c not in used] or list(pool)
|
||||||
|
if turn == 1 and forced_first is not None:
|
||||||
|
card = forced_first
|
||||||
|
else:
|
||||||
|
card = adapter.choose(snap, tf, avail, greedy)
|
||||||
|
used.add(card)
|
||||||
|
if first_card is None:
|
||||||
|
first_card = card
|
||||||
|
|
||||||
|
resp = buyer.respond(card, scenario, turn, price)
|
||||||
|
price = resp.new_price
|
||||||
|
done = resp.accept or price <= ANCHOR or turn >= MAX_TURNS
|
||||||
|
success = resp.accept or price <= ANCHOR
|
||||||
|
outcome = (NegotiationOutcome.SUCCESS if success
|
||||||
|
else NegotiationOutcome.FAILURE if done else NegotiationOutcome.ONGOING)
|
||||||
|
# 채점은 최종 결과 시점만 (중간 턴 0 → γ 부트스트랩으로 전파).
|
||||||
|
# 진행 중 보상을 누적하면 '질질 끄는 전략'이 부당하게 유리해지는 인공물이 생긴다.
|
||||||
|
r = rc.calculate(make_snapshot(sup, price, turn, acceptance, outcome)).total if done else 0.0
|
||||||
|
total_r += r
|
||||||
|
|
||||||
|
if learn:
|
||||||
|
if done:
|
||||||
|
adapter.learn(snap, tf, card, r, None, None, True)
|
||||||
|
else:
|
||||||
|
acc2 = max(0.0, (price0 - price) / price0)
|
||||||
|
nsnap = make_snapshot(sup, price, turn + 1, acc2)
|
||||||
|
navail = [c for c in pool if c not in used] or list(pool)
|
||||||
|
adapter.learn(snap, tf, card, r, nsnap, navail, False)
|
||||||
|
if done:
|
||||||
|
return total_r, success, price, first_card
|
||||||
|
return total_r, False, price, first_card
|
||||||
|
|
||||||
|
|
||||||
|
# ---- MC 정답 랭킹: 이 (협력사, 성향)에서 진짜 좋은 첫 카드 top-k ---------------------
|
||||||
|
_rand = RandomAdapter(seed=1)
|
||||||
|
|
||||||
|
def rank_cards_mc(sup, tf, pool, strat, rc, seed, sims=6, k=3):
|
||||||
|
means = {}
|
||||||
|
for c in pool:
|
||||||
|
rs = [run_episode(_rand, sup, tf, pool, strat, rc, seed=seed + 17 * s,
|
||||||
|
learn=False, greedy=False, forced_first=c)[0] for s in range(sims)]
|
||||||
|
means[c] = np.mean(rs)
|
||||||
|
return sorted(means, key=lambda c: -means[c])[:k]
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 학습/평가 ---------------------------------------------------------------------
|
||||||
|
def train(adapter, pool, strat, base_reward, state_cfg, episodes, seed):
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
for ep in range(1, episodes + 1):
|
||||||
|
sup = sample_supplier(rng)
|
||||||
|
rcfg, tf = sample_tenant_pref(rng, base_reward)
|
||||||
|
rc = RewardCalculator(rcfg, state_cfg)
|
||||||
|
run_episode(adapter, sup, tf, pool, strat, rc, seed=seed * 100 + ep, learn=True)
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate(adapter, pool, strat, base_reward, state_cfg, n=300, seed0=777, label=""):
|
||||||
|
from negotiation.qtable.domain.service.feature_builder import build_tenant_features
|
||||||
|
rng = np.random.default_rng(seed0)
|
||||||
|
rewards, succ, ratios, hits, holdout_first = [], 0, [], 0, 0
|
||||||
|
for i in range(n):
|
||||||
|
sup = sample_supplier(rng)
|
||||||
|
rcfg, tf = sample_tenant_pref(rng, base_reward)
|
||||||
|
rc = RewardCalculator(rcfg, state_cfg)
|
||||||
|
good = rank_cards_mc(sup, tf, pool, strat, rc, seed=seed0 * 7 + i)
|
||||||
|
r, ok, price, first = run_episode(adapter, sup, tf, pool, strat, rc,
|
||||||
|
seed=seed0 * 1000 + i, learn=False, greedy=True)
|
||||||
|
rewards.append(r); succ += ok; ratios.append(price / TARGET)
|
||||||
|
hits += (first in good); holdout_first += (first in HOLDOUT)
|
||||||
|
m, ci = float(np.mean(rewards)), float(1.96 * np.std(rewards) / np.sqrt(n))
|
||||||
|
print(f"{label:<14} mean_rwd={m:.4f} ±{ci:.4f} success={succ/n:.3f} "
|
||||||
|
f"settled/tgt={np.mean(ratios):.3f} top3_hit={hits/n:.3f} 새카드첫턴={holdout_first/n:.3f}")
|
||||||
|
|
||||||
|
|
||||||
|
def pref_behavior_test(adapters, pool, strat, base_reward, state_cfg):
|
||||||
|
"""④ 같은 협력사, 성향만 바꿨을 때 카드를 바꾸는가 (greedy).
|
||||||
|
|
||||||
|
첫 턴은 '일단 깎기'가 공통 정답이라 성향 차이가 잘 안 드러난다.
|
||||||
|
→ 협상 중반(가격이 이미 target 근처, 3턴째) 상태를 함께 프로브: 여기서
|
||||||
|
성사중시는 '마무리(수락 잘 되는) 카드', 가격중시는 '더 깎는 카드'가 갈려야 한다.
|
||||||
|
"""
|
||||||
|
from negotiation.qtable.domain.service.feature_builder import build_tenant_features
|
||||||
|
sups = [SupplierProfile(5_000_000, 3, "A"), # 소형·경쟁多
|
||||||
|
SupplierProfile(200_000_000, 1, "A")] # 대형·단독
|
||||||
|
probes = [("첫턴", TARGET * 1.15, 1, 0.0),
|
||||||
|
("중반(3턴,가격↓)", TARGET * 1.02, 3, 0.11)]
|
||||||
|
for pr_name, price, turn, acc in probes:
|
||||||
|
print(f"\n ── 프로브: {pr_name} (price={price:.0f}) ──")
|
||||||
|
print(f" {'협력사':<13} {'성향':<9} " + " ".join(f"{a.name:<15}" for a in adapters))
|
||||||
|
for sup in sups:
|
||||||
|
row = {}
|
||||||
|
for p, pname in [(0.05, "성사중시"), (0.95, "가격중시")]:
|
||||||
|
rcfg = pref_config(base_reward, p)
|
||||||
|
tf = build_tenant_features(rcfg)
|
||||||
|
picks = []
|
||||||
|
for a in adapters:
|
||||||
|
snap = make_snapshot(sup, price, turn, acc)
|
||||||
|
picks.append(a.choose(snap, tf, pool, True))
|
||||||
|
seg = f"{sup.segment[0]}·{sup.segment[1]}"
|
||||||
|
print(f" {seg:<13} {pname:<9} " + " ".join(f"{c}(전략{strat[c]})".ljust(15) for c in picks))
|
||||||
|
|
||||||
|
|
||||||
|
def main(episodes=10000, seed=42):
|
||||||
|
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
|
||||||
|
numbers, feat, strat = load_cards()
|
||||||
|
train_pool = [c for c in numbers if c not in HOLDOUT]
|
||||||
|
tcfg = TenantConfigLoader().load("ktcommerce")
|
||||||
|
card_dim = feat[numbers[0]].shape[0]
|
||||||
|
print(f"환경: 2축 FeatureBuyer + 성향 랜덤 · 학습 {episodes}ep · 카드특징 {card_dim}차원 "
|
||||||
|
f"(임베딩384+전략4+톤4) · 학습 {len(train_pool)}장 / 홀드아웃 {HOLDOUT}")
|
||||||
|
|
||||||
|
qt = QTableAdapter(numbers, tcfg.state)
|
||||||
|
dqn = DQNAdapter(FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM,
|
||||||
|
card_dim=card_dim, eps_decay=4000), feat)
|
||||||
|
|
||||||
|
print("\n[학습] qtable_ucb ...")
|
||||||
|
train(qt, train_pool, strat, tcfg.reward, tcfg.state, episodes, seed)
|
||||||
|
print("[학습] feature_dqn ...")
|
||||||
|
train(dqn, train_pool, strat, tcfg.reward, tcfg.state, episodes, seed)
|
||||||
|
|
||||||
|
print("\n=== ① 학습 카드 9장 풀 ===")
|
||||||
|
evaluate(RandomAdapter(seed), train_pool, strat, tcfg.reward, tcfg.state, label="random")
|
||||||
|
evaluate(qt, train_pool, strat, tcfg.reward, tcfg.state, label="qtable_ucb")
|
||||||
|
evaluate(dqn, train_pool, strat, tcfg.reward, tcfg.state, label="feature_dqn")
|
||||||
|
|
||||||
|
print("\n=== ② zero-shot 11장 풀 (안 본 카드 2장 포함) ===")
|
||||||
|
evaluate(RandomAdapter(seed), numbers, strat, tcfg.reward, tcfg.state, label="random")
|
||||||
|
evaluate(qt, numbers, strat, tcfg.reward, tcfg.state, label="qtable_ucb")
|
||||||
|
evaluate(dqn, numbers, strat, tcfg.reward, tcfg.state, label="feature_dqn")
|
||||||
|
|
||||||
|
print("\n=== ④ 성향 극단 테스트 — 같은 협력사, 성향만 바꾸면 카드를 바꾸는가 (11장 풀) ===")
|
||||||
|
pref_behavior_test([qt, dqn], numbers, strat, tcfg.reward, tcfg.state)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""full_autonomy 체크포인트(.pt) → 서빙 번들(autonomy_serving.npz) export.
|
||||||
|
|
||||||
|
dqn_serving 과 동일 패턴: ScoreNet 가중치만 numpy 로 묶어 PyTorch 없이 서빙한다.
|
||||||
|
행동 특징은 코드(autonomy_actions)가 런타임 생성하므로 번들에는 가중치만 담는다.
|
||||||
|
|
||||||
|
실행(호스트, torch 필요): APP_ENV=local python -m tools.export_autonomy_serving
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
|
||||||
|
from negotiation.policies.autonomy_actions import ACTION_DIM, EXTRA_STATE_DIM
|
||||||
|
from negotiation.qtable.domain.service.feature_builder import STATE_FEATURE_DIM, TENANT_FEATURE_DIM
|
||||||
|
|
||||||
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "full_autonomy.pt")
|
||||||
|
OUT_PATH = os.path.join(_HERE, "..", "artifacts", "autonomy_serving.npz")
|
||||||
|
|
||||||
|
STATE_DIM = STATE_FEATURE_DIM + TENANT_FEATURE_DIM + EXTRA_STATE_DIM
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
sd = torch.load(CKPT_PATH, map_location="cpu")
|
||||||
|
W0, b0 = sd["net.0.weight"].numpy(), sd["net.0.bias"].numpy()
|
||||||
|
W1, b1 = sd["net.2.weight"].numpy(), sd["net.2.bias"].numpy()
|
||||||
|
W2, b2 = sd["net.4.weight"].numpy(), sd["net.4.bias"].numpy()
|
||||||
|
assert W0.shape[1] == STATE_DIM + ACTION_DIM, f"입력 차원 불일치: {W0.shape[1]}"
|
||||||
|
|
||||||
|
tmp = OUT_PATH + ".tmp"
|
||||||
|
with open(tmp, "wb") as f:
|
||||||
|
np.savez(f, W0=W0, b0=b0, W1=W1, b1=b1, W2=W2, b2=b2,
|
||||||
|
state_dim=STATE_DIM, action_dim=ACTION_DIM)
|
||||||
|
if os.path.exists(OUT_PATH):
|
||||||
|
os.replace(OUT_PATH, OUT_PATH + ".prev")
|
||||||
|
os.replace(tmp, OUT_PATH)
|
||||||
|
print(f"[저장] {os.path.abspath(OUT_PATH)} (state {STATE_DIM} + action {ACTION_DIM})")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"""feature_dqn 체크포인트(.pt) → 서빙 번들(dqn_serving.npz) export.
|
||||||
|
|
||||||
|
서빙 컨테이너에 PyTorch 를 넣지 않기 위해 ScoreNet(3층 MLP) 가중치와 카드 특징
|
||||||
|
(임베딩384 + 전략 one-hot4 + 톤 one-hot4 = 392)을 numpy 번들 하나로 묶는다.
|
||||||
|
추론은 negotiation.policy.dqn_store 의 numpy forward 가 수행한다.
|
||||||
|
|
||||||
|
실행(호스트, torch 필요): APP_ENV=local python -m tools.export_dqn_serving
|
||||||
|
산출: agent/artifacts/dqn_serving.npz (.dockerignore 미제외 → 이미지에 포함)
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
|
||||||
|
from tools.train_feature_dqn import load_cards
|
||||||
|
|
||||||
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "feature_dqn_ktcommerce.pt")
|
||||||
|
OUT_PATH = os.path.join(_HERE, "..", "artifacts", "dqn_serving.npz")
|
||||||
|
|
||||||
|
STATE_DIM = 14 # build_state_features(9) + build_tenant_features(5)
|
||||||
|
CARD_DIM = 392
|
||||||
|
|
||||||
|
|
||||||
|
def _np_forward(x, W0, b0, W1, b1, W2, b2):
|
||||||
|
h = np.maximum(x @ W0.T + b0, 0.0)
|
||||||
|
h = np.maximum(h @ W1.T + b1, 0.0)
|
||||||
|
return h @ W2.T + b2
|
||||||
|
|
||||||
|
|
||||||
|
def export_bundle(sd, out_path: str) -> str:
|
||||||
|
"""state_dict → 서빙 번들 npz (원자적 교체: .tmp 작성 후 replace). 반환: 절대경로.
|
||||||
|
|
||||||
|
retrain_from_logs 재학습 배포도 이 함수를 쓴다 — 검증(torch/numpy 일치)은 main() 전용.
|
||||||
|
"""
|
||||||
|
W0, b0 = sd["net.0.weight"].numpy(), sd["net.0.bias"].numpy()
|
||||||
|
W1, b1 = sd["net.2.weight"].numpy(), sd["net.2.bias"].numpy()
|
||||||
|
W2, b2 = sd["net.4.weight"].numpy(), sd["net.4.bias"].numpy()
|
||||||
|
assert W0.shape[1] == STATE_DIM + CARD_DIM, f"입력 차원 불일치: {W0.shape[1]}"
|
||||||
|
numbers, feat, _ = load_cards()
|
||||||
|
card_feats = np.stack([feat[n] for n in numbers]).astype(np.float32)
|
||||||
|
tmp = out_path + ".tmp"
|
||||||
|
with open(tmp, "wb") as f:
|
||||||
|
np.savez(
|
||||||
|
f,
|
||||||
|
W0=W0, b0=b0, W1=W1, b1=b1, W2=W2, b2=b2,
|
||||||
|
card_numbers=np.array(numbers), card_feats=card_feats,
|
||||||
|
state_dim=STATE_DIM, card_dim=CARD_DIM,
|
||||||
|
)
|
||||||
|
if os.path.exists(out_path):
|
||||||
|
os.replace(out_path, out_path + ".prev") # 직전 번들 백업(롤백용)
|
||||||
|
os.replace(tmp, out_path)
|
||||||
|
return os.path.abspath(out_path)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
sd = torch.load(CKPT_PATH, map_location="cpu")
|
||||||
|
# 정합성 검증: torch forward == numpy forward
|
||||||
|
from negotiation.policies.feature_dqn_policy import ScoreNet
|
||||||
|
net = ScoreNet(STATE_DIM, CARD_DIM)
|
||||||
|
net.load_state_dict(sd)
|
||||||
|
net.eval()
|
||||||
|
x = np.random.default_rng(0).normal(size=(8, STATE_DIM + CARD_DIM)).astype(np.float32)
|
||||||
|
with torch.no_grad():
|
||||||
|
ref = net(torch.tensor(x)).numpy()
|
||||||
|
W0, b0 = sd["net.0.weight"].numpy(), sd["net.0.bias"].numpy()
|
||||||
|
W1, b1 = sd["net.2.weight"].numpy(), sd["net.2.bias"].numpy()
|
||||||
|
W2, b2 = sd["net.4.weight"].numpy(), sd["net.4.bias"].numpy()
|
||||||
|
out = _np_forward(x, W0, b0, W1, b1, W2, b2).squeeze(-1)
|
||||||
|
diff = float(np.abs(ref - out).max())
|
||||||
|
assert diff < 1e-4, f"numpy/torch forward 불일치: {diff}"
|
||||||
|
|
||||||
|
path = export_bundle(sd, OUT_PATH)
|
||||||
|
print(f"[저장] {path} forward 오차 {diff:.2e}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""probe_serving_dqn — 서빙 번들(dqn_serving.npz)의 상황별 카드 선택 프로브.
|
||||||
|
|
||||||
|
배포된 모델이 '상황에 맞게' 고르는지 눈으로 확인하는 진단 도구:
|
||||||
|
협력사 세그먼트 × 고객사 성향 × 협상 국면(가격대)별 선택 카드를 표로 출력한다.
|
||||||
|
전부 다르길 기대하는 게 아니라, 축을 바꿨을 때 선택이 '움직이는지'를 본다.
|
||||||
|
|
||||||
|
실행: APP_ENV=local python -m tools.probe_serving_dqn (numpy 만 필요, DB 불필요)
|
||||||
|
"""
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||||
|
from negotiation.qtable.domain.service.feature_builder import build_state_features, build_tenant_features
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
from tools.export_dqn_serving import OUT_PATH
|
||||||
|
from tools.retrain_from_logs import np_scorer_from_bundle
|
||||||
|
from tools.train_feature_dqn import pref_config
|
||||||
|
|
||||||
|
ANCHOR, TARGET = 495_000.0, 500_000.0 # BUGCHECK 견적과 동일 스케일
|
||||||
|
|
||||||
|
SUPPLIERS = {
|
||||||
|
"소형·경쟁多": dict(revenue_amount=5_000_000, partner_count=3, distribution_code="A"),
|
||||||
|
"소형·단독": dict(revenue_amount=5_000_000, partner_count=1, distribution_code="A"),
|
||||||
|
"대형·경쟁多": dict(revenue_amount=200_000_000, partner_count=3, distribution_code="A"),
|
||||||
|
"대형·단독": dict(revenue_amount=200_000_000, partner_count=1, distribution_code="A"),
|
||||||
|
}
|
||||||
|
PHASES = { # (라운드, 제시가): 첫턴 높은 가격 / 중반 목표가 근접 / 막판 앵커존 직전
|
||||||
|
"첫턴(575k)": (1, 575_000.0),
|
||||||
|
"중반(510k)": (2, 510_000.0),
|
||||||
|
"막판(501k)": (3, 501_000.0),
|
||||||
|
}
|
||||||
|
PREFS = {"성사중시": 0.1, "가격중시": 0.9}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
score = np_scorer_from_bundle(OUT_PATH)
|
||||||
|
z = np.load(OUT_PATH, allow_pickle=False)
|
||||||
|
numbers = [str(n) for n in z["card_numbers"]]
|
||||||
|
feats = z["card_feats"]
|
||||||
|
base = TenantConfigLoader().load("ktcommerce").reward
|
||||||
|
|
||||||
|
for phase, (turn, price) in PHASES.items():
|
||||||
|
print(f"\n=== {phase} (앵커 {int(ANCHOR):,} / 목표 {int(TARGET):,}) ===")
|
||||||
|
print(f"{'협력사':<12}" + "".join(f"{p:>16}" for p in PREFS))
|
||||||
|
for sup_name, sup in SUPPLIERS.items():
|
||||||
|
row = []
|
||||||
|
for _, p in PREFS.items():
|
||||||
|
tf = build_tenant_features(pref_config(base, p))
|
||||||
|
snap = NegotiationSnapshot(
|
||||||
|
revenue_amount=sup["revenue_amount"], distribution_code=sup["distribution_code"],
|
||||||
|
partner_count=sup["partner_count"],
|
||||||
|
acceptance_ratio=max(0.0, (575_000.0 - price) / 575_000.0),
|
||||||
|
input_price=price, anchor_price=ANCHOR, target_price=TARGET, round_number=turn,
|
||||||
|
)
|
||||||
|
sf = np.concatenate([build_state_features(snap), tf])
|
||||||
|
row.append(numbers[int(np.argmax(score(sf, feats)))])
|
||||||
|
print(f"{sup_name:<12}" + "".join(f"{c:>16}" for c in row))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""로컬 학습 리셋 — learning 스키마를 비운다 (카드 카탈로그·협상 데이터는 보존).
|
||||||
|
|
||||||
|
카탈로그(카드) 구성을 바꾼 뒤 Q-table 을 처음부터 다시 학습시키고 싶을 때 사용한다.
|
||||||
|
learning.* (버전/Q값/방문수/경험로그/세션/카드매핑) 만 삭제 → 다음 협상부터 fresh 재학습.
|
||||||
|
card.*·negotiation.*·quotation.* 등 실제 데이터는 건드리지 않는다.
|
||||||
|
|
||||||
|
사용 (agent 디렉토리에서):
|
||||||
|
APP_ENV=local python -m tools.reset_learning # 전체 회사 학습 리셋
|
||||||
|
APP_ENV=local python -m tools.reset_learning --company <id> # 특정 회사만
|
||||||
|
APP_ENV=local python -m tools.reset_learning --yes # 확인 프롬프트 생략
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
import asyncpg
|
||||||
|
|
||||||
|
from config.server_configs import main_db_config
|
||||||
|
|
||||||
|
# 삭제 대상(learning 스키마). 전부 company_id 스코프라 --company 로 회사별 리셋 가능.
|
||||||
|
_LEARNING_TABLES = [
|
||||||
|
"q_values", "visit_counts", "experience_logs", "chat_sessions",
|
||||||
|
"tenant_action_cards", "q_table_versions",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def _reset(company_id: str | None) -> None:
|
||||||
|
cfg = main_db_config
|
||||||
|
conn = await asyncpg.connect(
|
||||||
|
host=cfg.write_host, port=cfg.write_port,
|
||||||
|
user=cfg.write_id, password=cfg.write_pw, database=cfg.name,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
total = 0
|
||||||
|
for t in _LEARNING_TABLES:
|
||||||
|
if company_id:
|
||||||
|
res = await conn.execute(f"DELETE FROM learning.{t} WHERE company_id = $1", company_id)
|
||||||
|
else:
|
||||||
|
res = await conn.execute(f"DELETE FROM learning.{t}")
|
||||||
|
n = int(res.split()[-1]) if res else 0
|
||||||
|
total += n
|
||||||
|
print(f" learning.{t}: {n} 행 삭제")
|
||||||
|
scope = f"회사 {company_id}" if company_id else "전체 회사"
|
||||||
|
print(f"== 학습 리셋 완료: 총 {total} 행 삭제 (scope={scope}) ==")
|
||||||
|
finally:
|
||||||
|
await conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
p = argparse.ArgumentParser(description="learning 스키마 리셋 (카드/협상 데이터는 보존)")
|
||||||
|
p.add_argument("--company", help="특정 company_id 만 리셋. 생략 시 전체")
|
||||||
|
p.add_argument("--yes", action="store_true", help="확인 프롬프트 생략")
|
||||||
|
args = p.parse_args()
|
||||||
|
|
||||||
|
scope = f"회사 {args.company}" if args.company else "전체 회사"
|
||||||
|
if not args.yes:
|
||||||
|
ans = input(f"[{main_db_config.name}] learning 스키마({scope})를 비웁니다. 계속? [y/N] ")
|
||||||
|
if ans.strip().lower() != "y":
|
||||||
|
print("취소됨.")
|
||||||
|
return
|
||||||
|
asyncio.run(_reset(args.company))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
"""retrain_from_logs — experience_logs 실데이터로 feature_dqn 오프라인 재학습 + OPE 게이트.
|
||||||
|
|
||||||
|
파이프라인:
|
||||||
|
① learning.experience_logs 로드(전 테넌트 — 범용 에이전트는 테넌트를 특징으로 조건화하므로 통합 학습)
|
||||||
|
② 세션별 에피소드 재구성: 카드턴(done=False) N개 + 종료행(done=True) 1개.
|
||||||
|
보상은 학습 규약(최종 결과 시점만 채점)에 맞춰 종료행 reward 만 쓰고 중간턴은 0.
|
||||||
|
③ 현재 체크포인트에서 fine-tune (낮은 lr — 시뮬 사전학습 망각 방지)
|
||||||
|
④ OPE(SNIPS, 궤적 IS): 후보 모델 vs 현재 서빙 번들. 후보가 못 넘으면 배포하지 않는다.
|
||||||
|
⑤ 통과 시 dqn_serving.npz 원자적 교체(직전본 .prev 백업) → `docker compose build agent && up -d agent` 로 배포.
|
||||||
|
|
||||||
|
실행(호스트, torch+DB 필요):
|
||||||
|
APP_ENV=local python -m tools.retrain_from_logs
|
||||||
|
환경변수:
|
||||||
|
MIN_EPISODES(기본 200) 재학습 최소 에피소드 수 — 미달 시 skip (과적합 방지)
|
||||||
|
EPOCHS(기본 20) / LR(기본 1e-4) / FORCE_DEPLOY=1 (OPE 게이트 무시 — 테스트 전용)
|
||||||
|
|
||||||
|
주의: 서빙이 greedy(탐색 없음)라 로그가 선택 편향됨 — OPE 의 유효표본(ESS)이 작으면
|
||||||
|
게이트가 보수적으로 배포를 막는다. 이는 의도된 동작이다(조용한 성능저하 방지).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.database.model.models import ExperienceLog
|
||||||
|
from common.enums import DBType, DBWRType
|
||||||
|
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
|
||||||
|
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||||
|
from negotiation.qtable.domain.service.feature_builder import (
|
||||||
|
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features, build_tenant_features)
|
||||||
|
from sqlalchemy import select
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
from tools.export_dqn_serving import CKPT_PATH, OUT_PATH, export_bundle
|
||||||
|
from tools.train_feature_dqn import load_cards
|
||||||
|
|
||||||
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
RETRAIN_CKPT = os.path.join(_HERE, "..", "artifacts", "feature_dqn_retrained.pt")
|
||||||
|
REPORT_PATH = os.path.join(_HERE, "..", "artifacts", "retrain_report.json")
|
||||||
|
|
||||||
|
MIN_EPISODES = int(os.getenv("MIN_EPISODES", "200"))
|
||||||
|
EPOCHS = int(os.getenv("EPOCHS", "20"))
|
||||||
|
LR = float(os.getenv("LR", "1e-4"))
|
||||||
|
FORCE_DEPLOY = os.getenv("FORCE_DEPLOY") == "1"
|
||||||
|
PROPENSITY_FALLBACK = 0.9 # 구로그 propensity 누락 시 (UCB/DQN 모두 greedy≈(1-ε)+ε/n)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- ① 로그 로드 -------------------------------------------------------------
|
||||||
|
async def fetch_logs():
|
||||||
|
def _q(s):
|
||||||
|
q = (select(ExperienceLog.company_id, ExperienceLog.session_id, ExperienceLog.card_id,
|
||||||
|
ExperienceLog.reward, ExperienceLog.done, ExperienceLog.snapshot,
|
||||||
|
ExperienceLog.propensity, ExperienceLog.turn, ExperienceLog.id)
|
||||||
|
.where(ExperienceLog.is_invalidated == False) # noqa: E712
|
||||||
|
.order_by(ExperienceLog.company_id, ExperienceLog.session_id, ExperienceLog.id))
|
||||||
|
return DB_SESSION_MNG.execute(s, q)
|
||||||
|
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
# ---- ② 에피소드 재구성 --------------------------------------------------------
|
||||||
|
def build_episodes(rows, known_cards: set):
|
||||||
|
"""→ [{tenant, steps:[(snapshot, card, propensity)], terminal_reward}], 스킵 사유 카운트."""
|
||||||
|
by_session = defaultdict(list)
|
||||||
|
for r in rows:
|
||||||
|
if r[1] is not None:
|
||||||
|
by_session[(r[0], str(r[1]))].append(r)
|
||||||
|
|
||||||
|
episodes, skipped = [], defaultdict(int)
|
||||||
|
for (company_id, _sid), items in by_session.items():
|
||||||
|
selects = [r for r in items if not r[4] and r[5]] # done=False, snapshot 有
|
||||||
|
terminals = [r for r in items if r[4] and r[3] is not None] # done=True, reward 有
|
||||||
|
if not selects or not terminals:
|
||||||
|
skipped["종료행/카드턴 없음(미완결 세션)"] += 1
|
||||||
|
continue
|
||||||
|
if any(str(r[2] or "").startswith("AUT|") for r in selects):
|
||||||
|
skipped["완전 자율 세션(카드 재학습 대상 아님)"] += 1
|
||||||
|
continue
|
||||||
|
if any(r[2] not in known_cards for r in selects):
|
||||||
|
skipped["임베딩 없는 카드(파일매핑 테넌트 등)"] += 1
|
||||||
|
continue
|
||||||
|
episodes.append(dict(
|
||||||
|
tenant=company_id,
|
||||||
|
steps=[(r[5], r[2], r[6] if r[6] else PROPENSITY_FALLBACK) for r in selects],
|
||||||
|
terminal_reward=float(terminals[-1][3]),
|
||||||
|
))
|
||||||
|
return episodes, skipped
|
||||||
|
|
||||||
|
|
||||||
|
def tenant_feat_for(cache: dict, loader: TenantConfigLoader, company_id: str) -> np.ndarray:
|
||||||
|
"""테넌트 보상설정 → 성향 특징. 미온보딩/로드 실패는 _base 폴백."""
|
||||||
|
if company_id not in cache:
|
||||||
|
try:
|
||||||
|
cfg = loader.load(company_id)
|
||||||
|
except Exception:
|
||||||
|
cfg = loader.load("_base")
|
||||||
|
cache[company_id] = build_tenant_features(cfg.reward)
|
||||||
|
return cache[company_id]
|
||||||
|
|
||||||
|
|
||||||
|
def to_transitions(episodes, feat, tenant_feats):
|
||||||
|
"""학습 규약(train_feature_dqn 과 동일): 중간턴 r=0, 종료턴만 terminal_reward. 다음 후보 = 전체 − 사용분."""
|
||||||
|
all_cards = list(feat.keys())
|
||||||
|
out = []
|
||||||
|
for ep in episodes:
|
||||||
|
tf = tenant_feats[ep["tenant"]]
|
||||||
|
used = set()
|
||||||
|
n = len(ep["steps"])
|
||||||
|
for i, (snap_d, card, _p) in enumerate(ep["steps"]):
|
||||||
|
sf = np.concatenate([build_state_features(NegotiationSnapshot.from_dict(snap_d)), tf])
|
||||||
|
used.add(card)
|
||||||
|
if i == n - 1:
|
||||||
|
out.append((sf, feat[card], ep["terminal_reward"], None, None, True))
|
||||||
|
else:
|
||||||
|
s2_d = ep["steps"][i + 1][0]
|
||||||
|
s2 = np.concatenate([build_state_features(NegotiationSnapshot.from_dict(s2_d)), tf])
|
||||||
|
cands = [c for c in all_cards if c not in used] or all_cards
|
||||||
|
out.append((sf, feat[card], 0.0, s2, np.stack([feat[c] for c in cands]), False))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---- ④ OPE (SNIPS, 궤적 단위 IS) ----------------------------------------------
|
||||||
|
def _greedy_match(score_fn, ep, feat, tf) -> float:
|
||||||
|
"""궤적 IS 가중치: Π 1[greedy(sᵢ)=aᵢ]/pᵢ. 한 턴이라도 불일치면 0."""
|
||||||
|
all_cards = list(feat.keys())
|
||||||
|
w, used = 1.0, set()
|
||||||
|
for snap_d, card, p in ep["steps"]:
|
||||||
|
sf = np.concatenate([build_state_features(NegotiationSnapshot.from_dict(snap_d)), tf])
|
||||||
|
cands = [c for c in all_cards if c not in used] or all_cards
|
||||||
|
sc = score_fn(sf, np.stack([feat[c] for c in cands]))
|
||||||
|
if cands[int(np.argmax(sc))] != card:
|
||||||
|
return 0.0
|
||||||
|
w /= max(p, 1e-3)
|
||||||
|
used.add(card)
|
||||||
|
return w
|
||||||
|
|
||||||
|
|
||||||
|
def snips(score_fn, episodes, feat, tenant_feats):
|
||||||
|
"""SNIPS 추정치 + 유효표본크기(ESS). 매치 0건이면 (None, 0)."""
|
||||||
|
ws, rs = [], []
|
||||||
|
for ep in episodes:
|
||||||
|
w = _greedy_match(score_fn, ep, feat, tenant_feats[ep["tenant"]])
|
||||||
|
ws.append(w)
|
||||||
|
rs.append(ep["terminal_reward"])
|
||||||
|
ws, rs = np.array(ws), np.array(rs)
|
||||||
|
if ws.sum() <= 0:
|
||||||
|
return None, 0.0
|
||||||
|
est = float((ws * rs).sum() / ws.sum())
|
||||||
|
ess = float(ws.sum() ** 2 / (ws ** 2).sum())
|
||||||
|
return est, ess
|
||||||
|
|
||||||
|
|
||||||
|
def np_scorer_from_bundle(path):
|
||||||
|
"""현재 서빙 번들(npz) → score_fn (dqn_store 와 동일 forward)."""
|
||||||
|
z = np.load(path, allow_pickle=False)
|
||||||
|
W0, b0, W1, b1, W2, b2 = z["W0"], z["b0"], z["W1"], z["b1"], z["W2"], z["b2"]
|
||||||
|
|
||||||
|
def score(sf, card_feats):
|
||||||
|
x = np.concatenate([np.repeat(sf[None, :], card_feats.shape[0], axis=0), card_feats], axis=1)
|
||||||
|
h = np.maximum(x @ W0.T + b0, 0.0)
|
||||||
|
h = np.maximum(h @ W1.T + b1, 0.0)
|
||||||
|
return (h @ W2.T + b2).squeeze(-1)
|
||||||
|
return score
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 메인 ---------------------------------------------------------------------
|
||||||
|
async def run():
|
||||||
|
numbers, feat, _ = load_cards()
|
||||||
|
rows = await fetch_logs()
|
||||||
|
episodes, skipped = build_episodes(rows, set(numbers))
|
||||||
|
print(f"로그 {len(rows)}행 → 에피소드 {len(episodes)}개 (스킵: {dict(skipped) or '없음'})")
|
||||||
|
|
||||||
|
report = dict(rows=len(rows), episodes=len(episodes), skipped=dict(skipped),
|
||||||
|
min_episodes=MIN_EPISODES, deployed=False)
|
||||||
|
if len(episodes) < MIN_EPISODES and not FORCE_DEPLOY:
|
||||||
|
print(f"[skip] 에피소드 {len(episodes)} < MIN_EPISODES {MIN_EPISODES} — 과적합 위험으로 재학습 안 함")
|
||||||
|
report["result"] = "skipped_insufficient_data"
|
||||||
|
return report
|
||||||
|
|
||||||
|
loader = TenantConfigLoader()
|
||||||
|
tenant_feats = {}
|
||||||
|
for ep in episodes:
|
||||||
|
tenant_feat_for(tenant_feats, loader, ep["tenant"])
|
||||||
|
|
||||||
|
# ③ fine-tune (시뮬 사전학습 체크포인트에서 이어서, 낮은 lr)
|
||||||
|
transitions = to_transitions(episodes, feat, tenant_feats)
|
||||||
|
batch = min(64, max(8, len(transitions) // 4))
|
||||||
|
policy = FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM,
|
||||||
|
card_dim=feat[numbers[0]].shape[0], lr=LR, batch_size=batch)
|
||||||
|
if os.path.exists(CKPT_PATH):
|
||||||
|
policy.load(CKPT_PATH)
|
||||||
|
print(f"[fine-tune] 시작점: {os.path.basename(CKPT_PATH)} lr={LR} batch={batch}")
|
||||||
|
policy.buf.extend(transitions)
|
||||||
|
steps = EPOCHS * max(1, len(transitions) // batch)
|
||||||
|
losses = [l for _ in range(steps) if (l := policy.train_step()) is not None]
|
||||||
|
print(f"[fine-tune] {steps} step loss {losses[0]:.4f} → {losses[-1]:.4f}" if losses else "[fine-tune] 스텝 없음")
|
||||||
|
|
||||||
|
# ④ OPE 게이트: 후보 vs 현재 서빙
|
||||||
|
def cand_score(sf, cf):
|
||||||
|
return policy.scores(sf, cf)
|
||||||
|
cand_est, cand_ess = snips(cand_score, episodes, feat, tenant_feats)
|
||||||
|
cur_est, cur_ess = (snips(np_scorer_from_bundle(OUT_PATH), episodes, feat, tenant_feats)
|
||||||
|
if os.path.exists(OUT_PATH) else (None, 0.0))
|
||||||
|
print(f"[OPE/SNIPS] 후보 {cand_est} (ESS {cand_ess:.1f}) vs 현재 {cur_est} (ESS {cur_ess:.1f})")
|
||||||
|
report.update(ope_candidate=cand_est, ope_candidate_ess=cand_ess,
|
||||||
|
ope_current=cur_est, ope_current_ess=cur_ess)
|
||||||
|
|
||||||
|
min_ess = max(3.0, 0.02 * len(episodes))
|
||||||
|
passed = (cand_est is not None and cand_ess >= min_ess
|
||||||
|
and (cur_est is None or cand_est >= cur_est - 0.01))
|
||||||
|
if not passed and not FORCE_DEPLOY:
|
||||||
|
print(f"[게이트 불통과] 배포하지 않음 (필요 ESS ≥ {min_ess:.1f}). 현재 번들 유지.")
|
||||||
|
report["result"] = "gate_failed"
|
||||||
|
return report
|
||||||
|
|
||||||
|
# ⑤ 배포: 후보 저장 + 번들 교체 (.prev 백업)
|
||||||
|
policy.save(RETRAIN_CKPT)
|
||||||
|
path = export_bundle(policy.q.state_dict(), OUT_PATH)
|
||||||
|
print(f"[배포] {path} (직전본 → dqn_serving.npz.prev)")
|
||||||
|
print(" 적용: docker compose build agent && docker compose up -d agent")
|
||||||
|
report.update(result="deployed" if passed else "force_deployed", deployed=True,
|
||||||
|
ckpt=os.path.abspath(RETRAIN_CKPT))
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
report = asyncio.run(run())
|
||||||
|
with open(REPORT_PATH, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(report, f, ensure_ascii=False, indent=2)
|
||||||
|
print(f"[리포트] {os.path.abspath(REPORT_PATH)}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
"""결함 회귀 게이트 — 실전에서 발견된 협상 결함을 시나리오로 재생해 서빙 번들을 검증한다.
|
||||||
|
|
||||||
|
프로브(probe_serving_dqn)가 '눈으로 보는 행동 표'라면 이것은 '자동 합격/불합격'이다.
|
||||||
|
모든 검사 항목은 과거 실제 발생했던 결함이며, 하나라도 실패하면 exit 1 — 배포 금지.
|
||||||
|
재학습 번들은 반드시 이 게이트를 통과한 뒤에만 autonomy_serving.npz 로 교체한다.
|
||||||
|
|
||||||
|
검사 대상은 서빙 실물이다: AutonomyPolicy.decide(봉투 마스크 포함) + ChatEngine._autonomy_next
|
||||||
|
(최종제안 전환) + ment_generator 가드(목표가 누설·할루시네이션). 시뮬 협력사는 스크립트라
|
||||||
|
결정론적이고, 정책도 greedy 라 실행마다 같은 결과가 나온다. DB/LLM/도커 불필요.
|
||||||
|
|
||||||
|
지형은 복수로 검사한다 — v3.4 가 실스케일(423,198)에선 통과하고 드라이브 지형(10,000)에서
|
||||||
|
'첫 턴 목표가 통보'로 퇴화했던 사고: 한 지형 통과는 다른 지형을 보증하지 않는다.
|
||||||
|
|
||||||
|
실행: agent 디렉터리에서 APP_ENV=local python -m tools.test_autonomy_defects [번들경로]
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from negotiation.chat.service import ment_generator
|
||||||
|
from negotiation.chat.service.chat_engine import ChatEngine
|
||||||
|
from negotiation.policy import autonomy_store
|
||||||
|
from negotiation.policy.autonomy_store import AutonomyPolicy
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
|
||||||
|
# 검사 지형: 실제 견적(앵커율 ~1%) + 로컬 드라이브 견적(소액) — 스케일이 달라도 예절은 같아야 한다.
|
||||||
|
GEOS = {
|
||||||
|
"실스케일": dict(anchor=418_966, target=423_198, first=540_000, il=459_000),
|
||||||
|
"소액": dict(anchor=9_900, target=10_000, first=11_500, il=0),
|
||||||
|
}
|
||||||
|
MIN_PRESS = int(os.getenv("AUTONOMY_MIN_PRESS", "2"))
|
||||||
|
|
||||||
|
_RESULTS = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name: str, ok: bool, detail: str = ""):
|
||||||
|
_RESULTS.append((name, ok, detail))
|
||||||
|
print(f" {'✔' if ok else '✘ FAIL'} {name}" + (f" — {detail}" if detail and not ok else ""))
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 하니스: 서빙 실물 구동 (chat_service 의 ctx 관리 순서를 그대로 재현) ----------------
|
||||||
|
def base_ctx(geo) -> dict:
|
||||||
|
return dict(revenue_amount=50_000_000, distribution_code="A", partner_count=3,
|
||||||
|
item_price=geo["first"], input_price=geo["first"], round=1,
|
||||||
|
anchor_price=geo["anchor"], target_price=geo["target"],
|
||||||
|
internet_lowest_price=geo["il"])
|
||||||
|
|
||||||
|
|
||||||
|
def run_scenario(policy, supplier, geo, max_steps=30):
|
||||||
|
"""정책 결정 → 스텝 전환 → 컨텍스트 부기(chat_service 순서) → 스크립트 협력사 반응 루프.
|
||||||
|
|
||||||
|
trace 원소: (step, kind, q, 당시 제시가, autonomy_offer, 결정 시점 press_n)
|
||||||
|
"""
|
||||||
|
eng = ChatEngine.__new__(ChatEngine) # _autonomy_next 는 decider 와 ctx 만 쓴다
|
||||||
|
ctx = base_ctx(geo)
|
||||||
|
|
||||||
|
def decide(c):
|
||||||
|
act = policy.decide(c)
|
||||||
|
c["autonomy_pending"] = {"kind": act.kind, "q": act.counter_q, "s": act.strategy}
|
||||||
|
return act
|
||||||
|
|
||||||
|
eng.autonomy_decider = decide
|
||||||
|
sess = SimpleNamespace(context=ctx)
|
||||||
|
trace, end = [], None
|
||||||
|
for _ in range(max_steps):
|
||||||
|
press_n_at = int(ctx.get("autonomy_press_n") or 0)
|
||||||
|
step = eng._autonomy_next(sess)
|
||||||
|
pending = ctx.pop("autonomy_pending", None)
|
||||||
|
if pending: # chat_service 부기: pending → last(+prev), 역제안 별도 보존, press 카운터
|
||||||
|
if ctx.get("autonomy_last"):
|
||||||
|
ctx["autonomy_prev"] = ctx["autonomy_last"]
|
||||||
|
ctx["autonomy_last"] = dict(pending)
|
||||||
|
if pending["kind"] == "counter":
|
||||||
|
ctx["autonomy_last_counter"] = dict(pending)
|
||||||
|
if pending["kind"] == "press":
|
||||||
|
ctx["autonomy_press_n"] = press_n_at + 1
|
||||||
|
trace.append((step, (pending or {}).get("kind"), (pending or {}).get("q"),
|
||||||
|
ctx["input_price"], ctx.get("autonomy_offer"), press_n_at))
|
||||||
|
if step in ("협상완료", "협상실패"):
|
||||||
|
end = step
|
||||||
|
break
|
||||||
|
if step == "자율_최종제안": # 예→그 금액 타결 / 아니오→협상실패 (엔진 스텝 정의)
|
||||||
|
end = "협상완료" if supplier.final_yes(ctx) else "협상실패"
|
||||||
|
break
|
||||||
|
if step == "자율_역제안" and supplier.counter_yes(ctx):
|
||||||
|
ctx["input_price"] = ctx["autonomy_offer"]
|
||||||
|
end = "협상완료"
|
||||||
|
break
|
||||||
|
ctx["input_price"] = int(supplier.next_price(ctx))
|
||||||
|
ctx["round"] = ctx.get("round", 1) + 1
|
||||||
|
return trace, end, ctx
|
||||||
|
|
||||||
|
|
||||||
|
def fmt(trace):
|
||||||
|
out = []
|
||||||
|
for step, kind, q, price, offer, _ in trace:
|
||||||
|
s = f"{price:,}→{step}"
|
||||||
|
if kind == "counter":
|
||||||
|
s += f"({offer:,})"
|
||||||
|
out.append(s)
|
||||||
|
return " ".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 스크립트 협력사 (결정론, 지형 비율로 정의) -----------------------------------------
|
||||||
|
class Stubborn:
|
||||||
|
"""조금씩 내리지만 하한이 목표가 위(×1.028) — 성사 불가능. 역제안·최종 전부 거절.
|
||||||
|
|
||||||
|
기대 궤적: 설득 ≥2회 → 앵커 이하 개시 → 단조 상향 사다리 → 최종제안(목표가) → 결렬."""
|
||||||
|
def __init__(self, geo):
|
||||||
|
self.floor = int(geo["target"] * 1.028)
|
||||||
|
|
||||||
|
def next_price(self, ctx):
|
||||||
|
return max(self.floor, int(ctx["input_price"] * 0.96))
|
||||||
|
|
||||||
|
def counter_yes(self, ctx):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def final_yes(self, ctx):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class HoverNearTarget:
|
||||||
|
"""목표가 +0.19% 고정 — 마무리 국면. 압박이 나오면 안 되는 구간."""
|
||||||
|
def __init__(self, geo):
|
||||||
|
self.price = int(geo["target"] * 1.0019)
|
||||||
|
|
||||||
|
def next_price(self, ctx):
|
||||||
|
return self.price
|
||||||
|
|
||||||
|
def counter_yes(self, ctx):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def final_yes(self, ctx):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class Dealable:
|
||||||
|
"""4% 씩 내려와 목표가 바로 아래까지 협조 — 성사 가능 케이스."""
|
||||||
|
def __init__(self, geo):
|
||||||
|
self.floor = int(geo["target"] * 0.9995)
|
||||||
|
self.accept_from = geo["anchor"] + 0.4 * (geo["target"] - geo["anchor"])
|
||||||
|
|
||||||
|
def next_price(self, ctx):
|
||||||
|
return max(self.floor, int(ctx["input_price"] * 0.96))
|
||||||
|
|
||||||
|
def counter_yes(self, ctx):
|
||||||
|
return ctx["autonomy_offer"] >= self.accept_from # 목표가 부근 제안은 수락
|
||||||
|
|
||||||
|
def final_yes(self, ctx):
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 시나리오 검사 (각 항목 = 과거 실제 결함) -------------------------------------------
|
||||||
|
def assert_defects(tag, trace, end, geo):
|
||||||
|
anchor, target = geo["anchor"], geo["target"]
|
||||||
|
near = target * 1.005
|
||||||
|
# '역제안' 검사는 일반 역제안 스텝만 센다 — 같은 금액 재시도가 자율_최종제안으로 전환된 것은
|
||||||
|
# 반복이 아니라 설계된 최종 통보(제품 결정: 같은 금액 재호출 = 탄약 소진 → 마지막으로 묻고 종료).
|
||||||
|
counters = [(i, t) for i, t in enumerate(trace) if t[0] == "자율_역제안"]
|
||||||
|
presses = [t for t in trace if t[1] == "press"]
|
||||||
|
|
||||||
|
if trace and trace[0][3] > near:
|
||||||
|
check(f"[{tag}] 개시 턴은 설득 (결함: v3.4 첫턴 walk→목표가 통보)",
|
||||||
|
trace[0][1] == "press", f"첫 결정이 {trace[0][1]}")
|
||||||
|
if counters:
|
||||||
|
i0, first = counters[0]
|
||||||
|
check(f"[{tag}] 첫 역제안은 앵커 이하 (결함: 사다리 꼭대기 개시)",
|
||||||
|
first[4] <= anchor, f"첫 역제안 {first[4]:,} > 앵커 {anchor:,}")
|
||||||
|
pressed_before = sum(1 for t in trace[:i0] if t[1] == "press")
|
||||||
|
if first[3] > near: # 마무리 국면은 해금 예외
|
||||||
|
check(f"[{tag}] 역제시 해금 전 설득 ≥{MIN_PRESS}회 (결함: 첫턴 역제시)",
|
||||||
|
pressed_before >= MIN_PRESS, f"설득 {pressed_before}회 만에 역제안")
|
||||||
|
offers = [t[4] for _, t in counters]
|
||||||
|
check(f"[{tag}] 역제안 단조 상향 (결함: 제안 철회 423,198→420,024)",
|
||||||
|
all(b >= a for a, b in zip(offers, offers[1:])), f"철회 발생: {offers}")
|
||||||
|
check(f"[{tag}] 역제안 ≤ 목표가", all(o <= target for o in offers), f"{offers}")
|
||||||
|
check(f"[{tag}] 같은 금액 역제안 반복 없음 (결함: 421,082 반복)",
|
||||||
|
all(b != a for a, b in zip(offers, offers[1:])), f"{offers}")
|
||||||
|
check(f"[{tag}] 마무리 국면(≤목표가×1.005) 압박 없음 (결함: 802원 푼돈 흥정)",
|
||||||
|
all(t[3] > near for t in presses), "목표가 코앞에서 압박")
|
||||||
|
check(f"[{tag}] 목표가 초과 제시가 수락 없음 (결함: 목표가+14% 매입)",
|
||||||
|
not any(t[1] == "accept" and t[3] > target for t in trace), "")
|
||||||
|
finals = [t for t in trace if t[0] == "자율_최종제안"]
|
||||||
|
for f in finals:
|
||||||
|
check(f"[{tag}] 최종제안 금액 = 목표가 (결함: 직전 금액 재사용 60,548)",
|
||||||
|
f[4] == target, f"최종제안 {f[4]:,} ≠ 목표가 {target:,}")
|
||||||
|
# 결렬 의사(walk)로 끝났다면 반드시 최종제안을 거쳤어야 한다 (턴캡 종료는 예외)
|
||||||
|
walked_direct = any(t[1] == "walk" and t[0] == "협상실패" for t in trace)
|
||||||
|
capped = trace and trace[-1][0] == "협상실패" and trace[-1][1] is None
|
||||||
|
check(f"[{tag}] 결렬 전 최종제안 1회 보장 (결함: 최종 의사 확인 없이 종료)",
|
||||||
|
not walked_direct or capped or bool(finals), "walk 즉시 결렬")
|
||||||
|
check(f"[{tag}] 종료 보장 (무한 세션 없음)", end is not None, "max_steps 내 미종료")
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 엔진 단위 검사 (정책 무관 — 전환 로직 자체) ----------------------------------------
|
||||||
|
def engine_unit_tests():
|
||||||
|
print("\n[엔진 전환 로직 단위 검사]")
|
||||||
|
geo = GEOS["실스케일"]
|
||||||
|
target = geo["target"]
|
||||||
|
|
||||||
|
def force(kind, q=0.0, s=3):
|
||||||
|
eng = ChatEngine.__new__(ChatEngine)
|
||||||
|
eng.autonomy_decider = lambda c: SimpleNamespace(kind=kind, counter_q=q, strategy=s)
|
||||||
|
return eng
|
||||||
|
|
||||||
|
# walk → 최종제안(목표가) → 재차 walk → 협상실패
|
||||||
|
ctx = base_ctx(geo)
|
||||||
|
eng = force("walk")
|
||||||
|
sess = SimpleNamespace(context=ctx)
|
||||||
|
step1 = eng._autonomy_next(sess)
|
||||||
|
check("walk 1회차 → 자율_최종제안 전환", step1 == "자율_최종제안", f"got {step1}")
|
||||||
|
check("walk 전환 최종제안 금액 = 목표가", ctx.get("autonomy_offer") == target,
|
||||||
|
f"{ctx.get('autonomy_offer')}")
|
||||||
|
step2 = eng._autonomy_next(sess)
|
||||||
|
check("walk 2회차(최종 거절 후) → 협상실패", step2 == "협상실패", f"got {step2}")
|
||||||
|
|
||||||
|
# 같은 q 역제안 반복 → 최종제안(목표가) 전환
|
||||||
|
ctx = base_ctx(geo)
|
||||||
|
ctx["autonomy_last"] = ctx["autonomy_last_counter"] = {"kind": "counter", "q": 0.5, "s": 3}
|
||||||
|
sess = SimpleNamespace(context=ctx)
|
||||||
|
step = force("counter", q=0.5)._autonomy_next(sess)
|
||||||
|
check("같은 금액 재역제안 → 자율_최종제안 전환", step == "자율_최종제안", f"got {step}")
|
||||||
|
check("탄약소진 최종제안 금액 = 목표가", ctx.get("autonomy_offer") == target,
|
||||||
|
f"{ctx.get('autonomy_offer')}")
|
||||||
|
|
||||||
|
# 턴 상한 — 캡 종료도 최종제안 보장을 우회하지 않는다
|
||||||
|
ctx = base_ctx(geo)
|
||||||
|
ctx["round"] = 13
|
||||||
|
sess = SimpleNamespace(context=ctx)
|
||||||
|
step = force("press")._autonomy_next(sess)
|
||||||
|
check("턴 상한 초과(최종 미실시) → 자율_최종제안", step == "자율_최종제안", f"got {step}")
|
||||||
|
check("턴캡 최종제안 금액 = 목표가", ctx.get("autonomy_offer") == target,
|
||||||
|
f"{ctx.get('autonomy_offer')}")
|
||||||
|
step = force("press")._autonomy_next(sess)
|
||||||
|
check("턴 상한 초과(최종 거절 후) → 협상실패", step == "협상실패", f"got {step}")
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 봉투 마스크 단위 검사 (모델 무관 — 후보 필터 자체) ----------------------------------
|
||||||
|
def envelope_unit_tests(policy):
|
||||||
|
print("\n[봉투 마스크 단위 검사]")
|
||||||
|
geo = GEOS["소액"]
|
||||||
|
ctx = base_ctx(geo) # 설득 0회, 제시가 목표가 위 → 설득만 가능해야 한다
|
||||||
|
act = policy.decide(ctx)
|
||||||
|
check("설득 0회 상태의 결정은 press 만 가능 (walk·counter·accept 잠금)",
|
||||||
|
act.kind == "press", f"got {act.kind}")
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 멘트 가드 검사 (목표가 누설·할루시네이션 — LLM 호출 없음) ---------------------------
|
||||||
|
def ment_guard_tests():
|
||||||
|
print("\n[멘트 가드 검사]")
|
||||||
|
geo = GEOS["실스케일"]
|
||||||
|
target, anchor, il = geo["target"], geo["anchor"], geo["il"]
|
||||||
|
ctx = base_ctx(geo)
|
||||||
|
|
||||||
|
prompt = ment_generator._prompt_for("자율_압박_3", ctx)
|
||||||
|
check("압박 프롬프트에 목표가 숫자 없음 (결함: 목표가 노출 멘트)",
|
||||||
|
str(target) not in prompt.replace(",", ""), "프롬프트가 목표가를 담고 있음")
|
||||||
|
|
||||||
|
leak = f"저희 내부 산정 기준은 {target:,}원입니다. 이 가격에 맞춰 재검토 부탁드립니다."
|
||||||
|
check("목표가 포함 압박 멘트 → 폐기", not ment_generator._guard("자율_압박_3", ctx, leak), "")
|
||||||
|
|
||||||
|
invented = "시장 상황을 고려해 400,000원 수준으로 재검토 부탁드립니다."
|
||||||
|
check("지어낸 금액 멘트 → 폐기 (할루시네이션)",
|
||||||
|
not ment_generator._guard("자율_압박_3", ctx, invented), "")
|
||||||
|
|
||||||
|
ctx2 = dict(ctx, autonomy_offer=anchor)
|
||||||
|
ok_ment = f"내부 검토 결과 {anchor:,}원이면 즉시 진행이 가능합니다. 수락해 주시겠습니까?"
|
||||||
|
check("정상 역제안 멘트(제안가 포함) → 통과",
|
||||||
|
ment_generator._guard("자율_역제안", ctx2, ok_ment), "")
|
||||||
|
no_offer = "말씀하신 조건을 검토했고 조정이 필요합니다. 수락해 주시겠습니까?"
|
||||||
|
check("제안가 없는 역제안 멘트 → 폐기",
|
||||||
|
not ment_generator._guard("자율_역제안", ctx2, no_offer), "")
|
||||||
|
|
||||||
|
ev = f"동일 품목 인터넷 최저가가 {il:,}원으로 확인됩니다. 재검토 부탁드립니다."
|
||||||
|
check("최저가 인용: 근거 있음(수집됨+제시가>최저가) → 허용",
|
||||||
|
ment_generator._guard("자율_압박_1", ctx, ev), "")
|
||||||
|
ctx3 = dict(ctx, internet_lowest_price=0)
|
||||||
|
ev0 = "동일 품목 인터넷 최저가 대비 높은 수준입니다. 재검토 부탁드립니다."
|
||||||
|
check("최저가 인용: 미수집 품목 → 폐기 (지어낸 시장 주장)",
|
||||||
|
not ment_generator._guard("자율_압박_1", ctx3, ev0), "")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
bundle = sys.argv[1] if len(sys.argv) > 1 else autonomy_store.BUNDLE_PATH
|
||||||
|
z = np.load(bundle, allow_pickle=False)
|
||||||
|
policy = AutonomyPolicy(z, TenantConfigLoader().load("ktcommerce").reward)
|
||||||
|
print(f"번들: {os.path.abspath(bundle)} (state_dim={int(z['state_dim'])})")
|
||||||
|
|
||||||
|
for geo_name, geo in GEOS.items():
|
||||||
|
print(f"\n{'─' * 60}\n지형 [{geo_name}] 앵커 {geo['anchor']:,} / 목표 {geo['target']:,} "
|
||||||
|
f"/ 첫 제시가 {geo['first']:,}")
|
||||||
|
for tag, sup_cls in (("완고", Stubborn), ("목표가위 고정", HoverNearTarget),
|
||||||
|
("협조", Dealable)):
|
||||||
|
trace, end, _ = run_scenario(policy, sup_cls(geo), geo)
|
||||||
|
full_tag = f"{geo_name}·{tag}"
|
||||||
|
print(f"\n[{full_tag}] {fmt(trace)} ⇒ {end}")
|
||||||
|
assert_defects(full_tag, trace, end, geo)
|
||||||
|
|
||||||
|
engine_unit_tests()
|
||||||
|
envelope_unit_tests(policy)
|
||||||
|
ment_guard_tests()
|
||||||
|
|
||||||
|
fails = [(n, d) for n, ok, d in _RESULTS if not ok]
|
||||||
|
print(f"\n{'=' * 60}\n결과: {len(_RESULTS) - len(fails)}/{len(_RESULTS)} 통과")
|
||||||
|
if fails:
|
||||||
|
print("실패 항목 — 이 번들은 배포 금지:")
|
||||||
|
for n, d in fails:
|
||||||
|
print(f" ✘ {n} {d}")
|
||||||
|
sys.exit(1)
|
||||||
|
print("전 항목 통과 — 배포 가능.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
"""action-as-feature DQN 학습 (Phase 2·3) — 공용 환경 헬퍼 + 단독 학습 엔트리.
|
||||||
|
|
||||||
|
카드 특징 = 스크립트 임베딩(384) + 전략 one-hot(4) + 톤 one-hot(4) = 392차원
|
||||||
|
상태 특징 = 연속 상태(9) + 고객사 성향(5) = 14차원 ← 협력사·고객사 조건화
|
||||||
|
학습 환경 = FeatureBuyer(양보력/수락력 2축) + 에피소드마다 협력사·고객사성향 랜덤 샘플링
|
||||||
|
|
||||||
|
비교 평가는 tools.compare_qtable_vs_dqn 에서 수행한다.
|
||||||
|
실행: APP_ENV=local python -m tools.train_feature_dqn
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
|
||||||
|
from eval_harness.buyer import Scenario
|
||||||
|
from eval_harness.feature_buyer import FeatureBuyer, sample_supplier
|
||||||
|
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
|
||||||
|
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot
|
||||||
|
from negotiation.qtable.domain.service.feature_builder import (
|
||||||
|
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features, build_tenant_features)
|
||||||
|
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
|
||||||
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
EMB_PATH = os.path.join(_HERE, "..", "artifacts", "card_embeddings.npz")
|
||||||
|
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "feature_dqn_ktcommerce.pt")
|
||||||
|
|
||||||
|
# zero-shot 실험용 홀드아웃 (전략 1·4 — 남은 풀에도 같은 전략 존재).
|
||||||
|
# 서빙용 최종 학습은 전체 풀 사용: FULL_POOL=1 python -m tools.train_feature_dqn
|
||||||
|
HOLDOUT = [] if os.getenv("FULL_POOL") == "1" else ["NGC-002", "NGC-010"]
|
||||||
|
ANCHOR, TARGET = 8000.0, 10000.0
|
||||||
|
MAX_TURNS = 5
|
||||||
|
N_STRATEGY, N_TONE = 4, 4
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 카드 특징: 임베딩 + 전략/톤 one-hot ------------------------------------------
|
||||||
|
def load_cards():
|
||||||
|
z = np.load(EMB_PATH, allow_pickle=True)
|
||||||
|
numbers = [str(n) for n in z["numbers"]]
|
||||||
|
feat, strat = {}, {}
|
||||||
|
for i, n in enumerate(numbers):
|
||||||
|
s, t = int(z["strategy"][i]), int(z["tone"][i])
|
||||||
|
s_oh = np.eye(N_STRATEGY, dtype=np.float32)[s - 1]
|
||||||
|
t_oh = np.eye(N_TONE, dtype=np.float32)[t - 1]
|
||||||
|
feat[n] = np.concatenate([z["embeddings"][i].astype(np.float32), s_oh, t_oh])
|
||||||
|
strat[n] = s
|
||||||
|
return numbers, feat, strat
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 고객사 성향: 보상 설정 샘플링 ---------------------------------------------------
|
||||||
|
def sample_tenant_pref(rng: np.random.Generator, base_cfg):
|
||||||
|
"""p ∈ [0,1]: 0=성사중시(협력 유리) ↔ 1=가격중시(경쟁 유리). 반환: (RewardConfig, tenant_feat)."""
|
||||||
|
p = float(rng.uniform(0.0, 1.0))
|
||||||
|
cfg = base_cfg.model_copy(update=dict(
|
||||||
|
max_weight=0.25 + 0.60 * p, # 가격보상 비중
|
||||||
|
min_weight=(0.25 + 0.60 * p) * 0.7,
|
||||||
|
success_reward=1.6 - 1.2 * p, # 성사중시일수록 성공보상↑
|
||||||
|
failure_penalty=-(1.4 - 1.1 * p), # 성사중시일수록 결렬이 아픔
|
||||||
|
beta=0.1 + 0.4 * p,
|
||||||
|
penalty_lambda=float(rng.uniform(0.005, 0.05)),
|
||||||
|
))
|
||||||
|
return cfg, build_tenant_features(cfg)
|
||||||
|
|
||||||
|
|
||||||
|
def pref_config(base_cfg, p: float, lam: float = 0.02):
|
||||||
|
"""평가용: 성향 p 를 고정해 RewardConfig 생성 (극단 테스트)."""
|
||||||
|
return base_cfg.model_copy(update=dict(
|
||||||
|
max_weight=0.25 + 0.60 * p, min_weight=(0.25 + 0.60 * p) * 0.7,
|
||||||
|
success_reward=1.6 - 1.2 * p, failure_penalty=-(1.4 - 1.1 * p),
|
||||||
|
beta=0.1 + 0.4 * p, penalty_lambda=lam,
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
def make_snapshot(sup, price: float, turn: int, acceptance: float,
|
||||||
|
outcome=NegotiationOutcome.ONGOING) -> NegotiationSnapshot:
|
||||||
|
return NegotiationSnapshot(
|
||||||
|
revenue_amount=sup.revenue_amount, distribution_code=sup.distribution_code,
|
||||||
|
partner_count=sup.partner_count, acceptance_ratio=acceptance,
|
||||||
|
input_price=price, anchor_price=ANCHOR, target_price=TARGET,
|
||||||
|
round_number=turn, outcome=outcome,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 단독 학습 엔트리 (비교는 compare_qtable_vs_dqn) --------------------------------
|
||||||
|
def main(episodes=10000, seed=42):
|
||||||
|
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
|
||||||
|
numbers, feat, strat = load_cards()
|
||||||
|
train_pool = [c for c in numbers if c not in HOLDOUT]
|
||||||
|
card_dim = feat[numbers[0]].shape[0]
|
||||||
|
print(f"카드 {len(numbers)}장 (학습 {len(train_pool)} / 홀드아웃 {HOLDOUT}) card_dim={card_dim}")
|
||||||
|
|
||||||
|
tcfg = TenantConfigLoader().load("ktcommerce")
|
||||||
|
policy = FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM,
|
||||||
|
card_dim=card_dim, eps_decay=4000, gamma=0.95)
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
|
||||||
|
print(f"=== 학습 {episodes} 에피소드 (협력사·성향 랜덤, CPU) ===")
|
||||||
|
recent = []
|
||||||
|
for ep in range(1, episodes + 1):
|
||||||
|
sup = sample_supplier(rng)
|
||||||
|
rcfg, tf = sample_tenant_pref(rng, tcfg.reward)
|
||||||
|
rc = RewardCalculator(rcfg, tcfg.state)
|
||||||
|
buyer = FeatureBuyer(sup, strat, seed=seed * 100 + ep, max_turns=MAX_TURNS)
|
||||||
|
scenario = Scenario(anchor_price=ANCHOR, target_price=TARGET, revenue_amount=sup.revenue_amount,
|
||||||
|
distribution_code=sup.distribution_code, partner_count=sup.partner_count)
|
||||||
|
price0 = TARGET * 1.15
|
||||||
|
price, used, total_r = price0, set(), 0.0
|
||||||
|
for turn in range(1, MAX_TURNS + 1):
|
||||||
|
acceptance = max(0.0, (price0 - price) / price0)
|
||||||
|
s = make_snapshot(sup, price, turn, acceptance)
|
||||||
|
sf = np.concatenate([build_state_features(s), tf])
|
||||||
|
avail = [c for c in train_pool if c not in used] or list(train_pool)
|
||||||
|
embs = np.stack([feat[c] for c in avail])
|
||||||
|
i, _, _ = policy.select(sf, embs)
|
||||||
|
card = avail[i]; used.add(card)
|
||||||
|
resp = buyer.respond(card, scenario, turn, price)
|
||||||
|
price = resp.new_price
|
||||||
|
done = resp.accept or price <= ANCHOR or turn >= MAX_TURNS
|
||||||
|
success = resp.accept or price <= ANCHOR
|
||||||
|
outcome = (NegotiationOutcome.SUCCESS if success
|
||||||
|
else NegotiationOutcome.FAILURE if done else NegotiationOutcome.ONGOING)
|
||||||
|
# 최종 결과 시점만 채점 (중간 0 → γ 부트스트랩) — compare 스크립트와 동일 규칙.
|
||||||
|
r = rc.calculate(make_snapshot(sup, price, turn, acceptance, outcome)).total if done else 0.0
|
||||||
|
total_r += r
|
||||||
|
if done:
|
||||||
|
policy.remember(sf, feat[card], r, None, None, True)
|
||||||
|
else:
|
||||||
|
acc2 = max(0.0, (price0 - price) / price0)
|
||||||
|
s2 = make_snapshot(sup, price, turn + 1, acc2)
|
||||||
|
navail = [c for c in train_pool if c not in used] or list(train_pool)
|
||||||
|
policy.remember(sf, feat[card], r, np.concatenate([build_state_features(s2), tf]),
|
||||||
|
np.stack([feat[c] for c in navail]), False)
|
||||||
|
policy.train_step()
|
||||||
|
if done:
|
||||||
|
break
|
||||||
|
recent.append(total_r)
|
||||||
|
if ep % 2000 == 0:
|
||||||
|
print(f" ep {ep:>6} eps={policy.eps():.3f} 최근2000 평균보상={np.mean(recent[-2000:]):.4f}")
|
||||||
|
|
||||||
|
policy.save(CKPT_PATH)
|
||||||
|
print(f"[저장] {CKPT_PATH}")
|
||||||
|
return policy
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
"""train_full_autonomy — 행동 룰 0개, 완전 자율 협상 에이전트 (v2 시뮬 프로토타입).
|
||||||
|
|
||||||
|
기존 시스템의 룰(앵커 이하 강제타결 / 3라운드 강제결렬 / 와일드카드 존 / 카드 카탈로그)을
|
||||||
|
전부 제거하고, 모든 결정을 에이전트 행동으로 이관한다:
|
||||||
|
|
||||||
|
행동 공간 (action-as-feature, ScoreNet 이 후보 열거 채점):
|
||||||
|
ACCEPT 현재 제시가로 타결 ← '앵커 이하 강제타결' 룰 대체
|
||||||
|
WALK 협상 결렬 선언 ← '3라운드 강제결렬' 룰 대체
|
||||||
|
COUNTER(C) "C원이면 수락" 역제안 ← '와일드카드 1%' 룰 대체 (금액도 학습)
|
||||||
|
PRESS(strategy) 설득 압박(카드의 일반화) ← 카드 카탈로그 대체 (전략만 남음)
|
||||||
|
|
||||||
|
룰이 사라진 자리는 보상이 채운다(유일한 스펙):
|
||||||
|
R = W×R_price + (1−W)×R_end − λ×round (기존 RewardCalculator 그대로)
|
||||||
|
협상이 끝나는 길: 에이전트의 ACCEPT/WALK, 협력사의 COUNTER 수락, 협력사의 인내심 소진(이탈).
|
||||||
|
마지막 것은 시스템 룰이 아니라 상대방 특성이다.
|
||||||
|
|
||||||
|
베이스라인 = 현행 룰 시스템을 같은 환경에서 재현(앵커타결/1%클로징/3라운드결렬 + 압박).
|
||||||
|
|
||||||
|
실행: APP_ENV=local PYTHONUTF8=1 python -m tools.train_full_autonomy
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
from typing import Optional, Tuple
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
|
||||||
|
from eval_harness.feature_buyer import AFFINITY, STRATEGY_PROFILE, SupplierProfile, sample_supplier
|
||||||
|
from negotiation.policies.autonomy_actions import (
|
||||||
|
ACTION_DIM, ACTIONS, COUNTER_GRID, EXTRA_STATE_DIM, Action, extra_state,
|
||||||
|
internet_gap_feat, settle_norm as extra_settle)
|
||||||
|
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
|
||||||
|
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot
|
||||||
|
from negotiation.qtable.domain.service.feature_builder import (
|
||||||
|
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features, build_tenant_features)
|
||||||
|
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
from tools.train_feature_dqn import pref_config, sample_tenant_pref
|
||||||
|
|
||||||
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "full_autonomy.pt")
|
||||||
|
|
||||||
|
TARGET = 10000.0
|
||||||
|
# 앵커율(v3.1): 실운영 기하 정합 — 앵커가 = 목표가×(1−a), a ∈ [0.8%, 6%] 를 에피소드마다 샘플링.
|
||||||
|
# (기존 고정 20% 폭은 실제(≈1%)와 지형이 달라, 실서비스에서 압박/역제안 밸런스가 어긋났다.)
|
||||||
|
ANCHOR_RATE_RANGE = (0.008, 0.06)
|
||||||
|
# 행동 공간(Action/ACTIONS/COUNTER_GRID/ACTION_DIM)은 negotiation.policies.autonomy_actions 공유
|
||||||
|
# — 서빙(autonomy_store, numpy 전용)과 학습이 같은 인코딩을 쓴다.
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 협력사 모델 (상대 반응: 역제안 수락/재제안 포함) ---------------------------------
|
||||||
|
class AutonomousBuyer:
|
||||||
|
"""FeatureBuyer 확장: 역제안(C)에 반응한다. 이탈은 '인내심' — 시스템 룰이 아닌 상대 특성."""
|
||||||
|
|
||||||
|
def __init__(self, sup: SupplierProfile, seed: int):
|
||||||
|
self.sup = sup
|
||||||
|
self.rng = np.random.default_rng(seed)
|
||||||
|
# 기질 t ∈ [0,1]: 0=터프(하한 높고 안 물러섬) ↔ 1=수월. 관측 가능한 이력·최저가가
|
||||||
|
# 이 숨은 기질과 상관되게 생성된다 → 에이전트가 이력/최저가 특징을 읽을 '이유'가 생긴다.
|
||||||
|
# 하한은 '우리 앵커'가 아니라 협력사 사정(≈목표가 기준)으로 정해진다(v3.1) —
|
||||||
|
# 하한 > 목표가(≈35%)면 애초에 성사 불가능한 협상이고, 그걸 빨리 알아채고 끊는 것도 실력이다.
|
||||||
|
t = float(self.rng.uniform(0.0, 1.0))
|
||||||
|
self.floor = TARGET * float(np.clip(1.12 - 0.24 * t + self.rng.normal(0, 0.02), 0.85, 1.18))
|
||||||
|
self.patience = int(self.rng.integers(4, 9)) + (1 if t > 0.7 else 0)
|
||||||
|
# 첫 제시가: 목표가의 105~150% — 실운영(기존 공급가가 목표가를 26%+ 상회) 분포를 덮는다.
|
||||||
|
# 좁게(110~125%) 학습하면 큰 갭 상황에서 정책이 분포 밖 일반화(대형컷 역제안)를 한다.
|
||||||
|
self.price = TARGET * float(self.rng.uniform(1.05, 1.50))
|
||||||
|
# 하한가가 첫 제시가보다 높을 수 없다(자기 하한 밑으로 부르고 시작하는 판매자는 없음).
|
||||||
|
# 이 보정이 없으면 on_press 의 max(floor,·)가 가격을 '역주행'시키는 비현실이 생긴다.
|
||||||
|
self.floor = min(self.floor, self.price * 0.98)
|
||||||
|
self._last_c: Optional[float] = None # 직전 역제안 (같은 숫자 반복 짜증 모델링)
|
||||||
|
# ---- 관측 가능 부가정보 (v3 특징 소스 — 기질과 상관, 노이즈 있음) ----
|
||||||
|
self.hist_n = int(self.rng.integers(0, 6)) # 과거 협상 횟수 (0=신규)
|
||||||
|
if self.hist_n:
|
||||||
|
self.hist_success = float(np.clip(0.25 + 0.6 * t + self.rng.normal(0, 0.10), 0.0, 1.0))
|
||||||
|
self.hist_settle_ratio = float(np.clip(1.18 - 0.28 * t + self.rng.normal(0, 0.04), 0.80, 1.30))
|
||||||
|
else:
|
||||||
|
self.hist_success = self.hist_settle_ratio = None
|
||||||
|
# 인터넷최저가: 숨은 하한가의 노이즈 관측치. 60% 확률로만 수집돼 있음(현실: 미수집 흔함).
|
||||||
|
self.internet_lowest = (self.floor * float(self.rng.uniform(0.98, 1.08))
|
||||||
|
if self.rng.random() < 0.6 else None)
|
||||||
|
|
||||||
|
def _powers(self, strategy: int) -> Tuple[float, float]:
|
||||||
|
conc, acc = STRATEGY_PROFILE.get(strategy, (0.5, 0.5))
|
||||||
|
m = AFFINITY[self.sup.segment].get(strategy, 0.5)
|
||||||
|
scale = 0.35 + 0.85 * m
|
||||||
|
return conc * scale, acc * scale
|
||||||
|
|
||||||
|
def on_press(self, strategy: int, turn: int) -> Tuple[bool, float]:
|
||||||
|
"""(이탈여부, 새 제시가). 압박이 안 먹히는 세그먼트면 이탈 위험이 실재한다."""
|
||||||
|
c_pow, a_pow = self._powers(strategy)
|
||||||
|
walk_p = 0.04 + 0.30 * (1.0 - a_pow) * (turn / self.patience)
|
||||||
|
if self.rng.random() < walk_p:
|
||||||
|
return True, self.price
|
||||||
|
concession = (self.price - self.floor) * (0.10 + 0.55 * c_pow)
|
||||||
|
self.price = max(self.floor, self.price - concession)
|
||||||
|
return False, self.price
|
||||||
|
|
||||||
|
def on_counter(self, c: float, strategy: int, turn: int) -> Tuple[str, float]:
|
||||||
|
"""역제안 C 반응: 'accept'(C로 타결) | 'walk' | 'counter'(새 제시가).
|
||||||
|
|
||||||
|
현실화(v2): 현 제시가 대비 인하 요구폭(cut)이 클수록 수락률이 급감하고 이탈 위험이 커진다
|
||||||
|
— 초기 버전에서 에이전트가 't1 원샷 로우볼'로 시뮬 허점을 착취하던 것을 막는다.
|
||||||
|
압박으로 가격을 충분히 끌어내린 뒤 작은 컷으로 클로징해야 통하는 구조.
|
||||||
|
"""
|
||||||
|
_, a_pow = self._powers(strategy or 3)
|
||||||
|
cut = max(0.0, (self.price - c) / max(self.price, 1.0)) # 인하 요구폭 (현 제시가 대비)
|
||||||
|
prev_c = self._last_c
|
||||||
|
repeated = prev_c is not None and abs(c - prev_c) < 1e-6 # 같은 숫자 반복
|
||||||
|
self._last_c = c
|
||||||
|
# 양보 상호성(v3.3): 직전 제안보다 올려 부르면(성의 있는 양보) 호의적으로 반응한다.
|
||||||
|
# 이 신호가 있어야 '상대가 내리면 우리도 조금 올리는' tit-for-tat 이 학습으로 나온다.
|
||||||
|
warm = 0.0
|
||||||
|
if prev_c is not None and c > prev_c + 1e-9:
|
||||||
|
warm = float(np.clip((c - prev_c) / max(self.price - self.floor, 1.0), 0.0, 0.35))
|
||||||
|
if c >= self.floor:
|
||||||
|
margin = (c - self.floor) / max(self.floor, 1.0)
|
||||||
|
p_acc = float(np.clip(0.20 + 0.9 * margin / 0.08, 0.0, 0.95)) * (0.75 + 0.35 * a_pow)
|
||||||
|
p_acc *= float(np.clip(1.0 - (cut - 0.05) / 0.20, 0.0, 1.0)) # 컷 5% 초과부터 반발, 25%면 수락 0
|
||||||
|
if repeated:
|
||||||
|
p_acc *= 0.25 # 이미 거절한 숫자를 또 내밀면 설득력 급감
|
||||||
|
p_acc *= 1.0 + warm
|
||||||
|
if self.rng.random() < min(p_acc, 0.97):
|
||||||
|
return "accept", c
|
||||||
|
# 모욕적 요구(하한 미달·과도한 원샷 컷·앵무새 반복) → 이탈 위험
|
||||||
|
low = max(0.0, (self.floor - c) / max(self.floor, 1.0))
|
||||||
|
p_walk = min(0.5, 2.0 * low) + 0.35 * max(0.0, cut - 0.20) / 0.20 + (0.15 if repeated else 0.0)
|
||||||
|
if self.rng.random() < min(p_walk * (1.0 - warm), 0.7):
|
||||||
|
return "walk", self.price
|
||||||
|
self.price = max(self.floor, c + (self.price - c) * float(self.rng.uniform(0.30, 0.60) + warm))
|
||||||
|
return "counter", self.price
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 에피소드 실행 (룰 없음 — 종료는 행동 또는 상대 특성으로만) ------------------------
|
||||||
|
def make_snapshot(sup, price, turn, p0, anchor, outcome=NegotiationOutcome.ONGOING):
|
||||||
|
return NegotiationSnapshot(
|
||||||
|
revenue_amount=sup.revenue_amount, distribution_code=sup.distribution_code,
|
||||||
|
partner_count=sup.partner_count, acceptance_ratio=max(0.0, (p0 - price) / p0),
|
||||||
|
input_price=price, anchor_price=anchor, target_price=TARGET,
|
||||||
|
round_number=turn, outcome=outcome)
|
||||||
|
|
||||||
|
|
||||||
|
MIN_PRESS = int(os.getenv("AUTONOMY_MIN_PRESS", "2")) # 역제시 해금에 필요한 최소 설득 횟수
|
||||||
|
|
||||||
|
|
||||||
|
def available_actions(price: float, last_counter_q: Optional[float] = None,
|
||||||
|
counter_locked: bool = False) -> list:
|
||||||
|
"""행동 봉투 (serving autonomy_store 와 동일해야 한다):
|
||||||
|
① 목표가 초과 제시가는 '수락' 제외 — 매입 승인 범위(목표가 초과 수락 착취 방지)
|
||||||
|
② 직전 역제안 미만 금액의 역제안 제외 — 단조 양보 원칙(제안 철회 금지;
|
||||||
|
양보 '속도'는 정책이 배우고, 후퇴 '금지'만 구조로 보장)
|
||||||
|
③ counter_locked: 설득 MIN_PRESS 회 전에는 역제시 잠금 — 옛 제품 의미론
|
||||||
|
(일반 카드=설득, 역제시=와일드카드 성격의 마무리 수단) 복원
|
||||||
|
④ 마무리 국면(제시가 ≤ 목표가×1.005): 압박 제외 — 푼돈 차이에서 재검토 요청 반복 방지
|
||||||
|
⑤ 첫 역제안은 앵커 이하(q ≤ 0)만 — 낮게 개시해 사다리를 다 쓰며 올라간다"""
|
||||||
|
near_target = price <= TARGET * 1.005
|
||||||
|
return [a for a in ACTIONS
|
||||||
|
if not (a.kind == "accept" and price > TARGET)
|
||||||
|
and not (a.kind == "counter" and counter_locked and not near_target)
|
||||||
|
and not (a.kind == "walk" and counter_locked and not near_target)
|
||||||
|
and not (a.kind == "press" and near_target)
|
||||||
|
and not (a.kind == "counter" and last_counter_q is None and a.counter_q > 1e-9)
|
||||||
|
and not (a.kind == "counter" and last_counter_q is not None
|
||||||
|
and a.counter_q < last_counter_q - 1e-9)]
|
||||||
|
|
||||||
|
|
||||||
|
def action_feats(price: float, anchor: float, last_counter_q: Optional[float] = None,
|
||||||
|
counter_locked: bool = False):
|
||||||
|
"""현 제시가 기준 (가용 행동 리스트, 특징 [K, ACTION_DIM]). counter 는 컷폭 포함."""
|
||||||
|
span = max(TARGET - anchor, 1.0)
|
||||||
|
pos = (price - anchor) / span
|
||||||
|
acts = available_actions(price, last_counter_q, counter_locked)
|
||||||
|
rows = []
|
||||||
|
for a in acts:
|
||||||
|
cut = 0.0
|
||||||
|
if a.kind == "counter":
|
||||||
|
c = anchor + a.counter_q * span
|
||||||
|
cut = max(0.0, (price - c) / max(price, 1.0))
|
||||||
|
rows.append(a.feat(pos, cut))
|
||||||
|
return acts, np.stack(rows)
|
||||||
|
|
||||||
|
|
||||||
|
def run_episode(policy_fn, sup, rc: RewardCalculator, tf: np.ndarray, seed: int,
|
||||||
|
learner: Optional[FeatureDQNPolicy] = None, trace: Optional[list] = None):
|
||||||
|
"""policy_fn(state_feat, price_pos) → Action. learner 지정 시 replay 저장+학습."""
|
||||||
|
buyer = AutonomousBuyer(sup, seed)
|
||||||
|
p0 = buyer.price
|
||||||
|
env_rng = np.random.default_rng(seed + 7)
|
||||||
|
# 앵커율 샘플링(v3.1): 실운영처럼 앵커가 목표가 바로 아래(0.8~6%) — 좁은 스팬 지형에서 학습.
|
||||||
|
anchor = TARGET * (1.0 - float(env_rng.uniform(*ANCHOR_RATE_RANGE)))
|
||||||
|
span = max(TARGET - anchor, 1.0)
|
||||||
|
turn, settled, walked = 0, None, False
|
||||||
|
last_kind, last_q = "", 0.0 # 직전 역제안 기억 (같은 숫자 반복 방지의 학습 근거)
|
||||||
|
press_n = 0 # 설득 횟수 — 역제시 해금(MIN_PRESS) 카운터
|
||||||
|
# 견적 마감(환경 사실): 마감 도달 시 협상은 미타결 종료된다 — 룰이 아니라 세상의 시계.
|
||||||
|
deadline_turns = int(env_rng.integers(3, 11))
|
||||||
|
# 관측성 마스크(v3.5): 실서빙은 마감·이력·최저가가 '없는' 세션이 흔하고 로더가 중립값
|
||||||
|
# (0.5/0)을 대입한다. 시뮬이 항상 다 아는 세계만 학습하면 그 중립 상태가 분포 밖이 된다
|
||||||
|
# — v3.4 가 라이브 소액 지형에서 첫 턴 결렬로 퇴화한 원인 추정. 세계(마감 종료·상대 특성)는
|
||||||
|
# 그대로 두고 관측만 가린다: 마감은 40% 미관측(0.5 고정), 15% 는 전부 미상(신규 견적의 전형).
|
||||||
|
deadline_known = env_rng.random() < 0.6
|
||||||
|
blind = env_rng.random() < 0.15
|
||||||
|
if blind:
|
||||||
|
deadline_known = False
|
||||||
|
# 협력사 이력·최저가 특징 (에피소드 내 불변)
|
||||||
|
known_hist = buyer.hist_n and not blind
|
||||||
|
fixed_extra = dict(
|
||||||
|
hist_n=min(buyer.hist_n, 5) / 5.0 if not blind else 0.0,
|
||||||
|
hist_success=buyer.hist_success if known_hist else 0.5,
|
||||||
|
hist_settle=extra_settle(buyer.hist_settle_ratio) if known_hist else 0.5,
|
||||||
|
internet_gap=internet_gap_feat(buyer.internet_lowest or 0.0, anchor) if not blind else 0.0,
|
||||||
|
)
|
||||||
|
pending = None # (state_feat, action_feat) — 최종 결과 시점만 채점, 중간 r=0
|
||||||
|
|
||||||
|
while True:
|
||||||
|
turn += 1
|
||||||
|
price = buyer.price
|
||||||
|
deadline_remain = (max(0.0, (deadline_turns - turn + 1) / deadline_turns)
|
||||||
|
if deadline_known else 0.5) # 미관측 → 서빙 로더와 동일한 중립값
|
||||||
|
sf = np.concatenate([build_state_features(make_snapshot(sup, price, turn, p0, anchor)), tf,
|
||||||
|
extra_state(last_kind, last_q, deadline=deadline_remain, **fixed_extra)])
|
||||||
|
lcq = last_q if last_kind == "counter" else None
|
||||||
|
locked = lcq is None and press_n < MIN_PRESS
|
||||||
|
act = policy_fn(sf, price, anchor, lcq, locked)
|
||||||
|
if trace is not None:
|
||||||
|
trace.append((turn, int(price), act))
|
||||||
|
|
||||||
|
if act.kind == "accept":
|
||||||
|
settled = price
|
||||||
|
elif act.kind == "walk":
|
||||||
|
walked = True
|
||||||
|
elif act.kind == "counter":
|
||||||
|
c = anchor + act.counter_q * span
|
||||||
|
resp, val = buyer.on_counter(c, act.strategy, turn)
|
||||||
|
last_kind, last_q = "counter", act.counter_q # 역제안 기억 갱신
|
||||||
|
if resp == "accept":
|
||||||
|
settled = c
|
||||||
|
elif resp == "walk":
|
||||||
|
walked = True
|
||||||
|
else: # press
|
||||||
|
press_n += 1
|
||||||
|
left, _ = buyer.on_press(act.strategy, turn)
|
||||||
|
walked = walked or left
|
||||||
|
if not settled and not walked and turn >= buyer.patience:
|
||||||
|
walked = True # 인내심 소진(상대 특성) — 시스템 룰 아님
|
||||||
|
if not settled and not walked and turn >= deadline_turns:
|
||||||
|
walked = True # 견적 마감 도달(환경 사실) — 미타결 종료
|
||||||
|
|
||||||
|
done = settled is not None or walked
|
||||||
|
final_price = settled if settled is not None else buyer.price
|
||||||
|
# 성사 보너스는 목표가 이하 타결에만 — v3.1 이 '비싸게라도 성사'로 착취한 보상 구멍의
|
||||||
|
# 원인 차단(봉투 ① 의 마스크와 이중 방어: 유인 자체를 올바르게). 초과 타결 = 결렬 취급.
|
||||||
|
outcome = (NegotiationOutcome.SUCCESS if settled is not None and settled <= TARGET
|
||||||
|
else NegotiationOutcome.FAILURE if done else NegotiationOutcome.ONGOING)
|
||||||
|
r = rc.calculate(make_snapshot(sup, final_price, turn, p0, anchor, outcome)).total if done else 0.0
|
||||||
|
|
||||||
|
if learner is not None:
|
||||||
|
pos = (price - anchor) / span
|
||||||
|
cut = 0.0
|
||||||
|
if act.kind == "counter":
|
||||||
|
cut = max(0.0, (price - (anchor + act.counter_q * span)) / max(price, 1.0))
|
||||||
|
af = act.feat(pos, cut)
|
||||||
|
if pending:
|
||||||
|
nxt_lcq = last_q if last_kind == "counter" else None
|
||||||
|
learner.remember(*pending, 0.0, sf,
|
||||||
|
action_feats(price, anchor, nxt_lcq,
|
||||||
|
nxt_lcq is None and press_n < MIN_PRESS)[1], False)
|
||||||
|
pending = (sf, af)
|
||||||
|
if done:
|
||||||
|
learner.remember(sf, af, r, None, None, True)
|
||||||
|
learner.train_step()
|
||||||
|
if done:
|
||||||
|
return settled, turn, r
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 정책들 ------------------------------------------------------------------
|
||||||
|
def dqn_policy(policy: FeatureDQNPolicy):
|
||||||
|
def f(sf, price, anchor, last_counter_q=None, counter_locked=False):
|
||||||
|
acts, feats = action_feats(price, anchor, last_counter_q, counter_locked)
|
||||||
|
i, _, _ = policy.select(sf, feats)
|
||||||
|
return acts[i]
|
||||||
|
return f
|
||||||
|
|
||||||
|
|
||||||
|
class RuleBaseline:
|
||||||
|
"""현행 시스템 룰 재현: 앵커 이하 수락 / 존내 1% 클로징 / 3회 압박 후 결렬."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.presses, self.closed = 0, False
|
||||||
|
|
||||||
|
def __call__(self, sf, price, anchor, last_counter_q=None, counter_locked=False) -> Action:
|
||||||
|
span = max(TARGET - anchor, 1.0)
|
||||||
|
if price <= anchor:
|
||||||
|
return Action("accept")
|
||||||
|
if price <= anchor * 1.02 and not self.closed:
|
||||||
|
self.closed = True
|
||||||
|
return Action("counter", (price * 0.99 - anchor) / span, 3)
|
||||||
|
if self.presses < 3:
|
||||||
|
self.presses += 1
|
||||||
|
return Action("press", 0.0, 3)
|
||||||
|
return Action("walk")
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 학습/평가 ----------------------------------------------------------------
|
||||||
|
def evaluate(name, make_policy_fn, base_cfg, tcfg_state, episodes=3000, seed0=777):
|
||||||
|
rc = RewardCalculator(pref_config(base_cfg, 0.5), tcfg_state)
|
||||||
|
tf = build_tenant_features(pref_config(base_cfg, 0.5))
|
||||||
|
rng = np.random.default_rng(seed0)
|
||||||
|
rewards, settles, rounds = [], [], []
|
||||||
|
for i in range(episodes):
|
||||||
|
sup = sample_supplier(rng)
|
||||||
|
settled, turn, r = run_episode(make_policy_fn(), sup, rc, tf, seed0 * 91 + i)
|
||||||
|
rewards.append(r)
|
||||||
|
rounds.append(turn)
|
||||||
|
if settled is not None:
|
||||||
|
settles.append(settled / TARGET)
|
||||||
|
sr = len(settles) / episodes
|
||||||
|
print(f"{name:<14} 보상 {np.mean(rewards):.4f} ±{np.std(rewards)/np.sqrt(episodes):.4f}"
|
||||||
|
f" 성사율 {sr:.3f} 타결가/목표 {np.mean(settles):.3f} 평균라운드 {np.mean(rounds):.2f}")
|
||||||
|
return dict(reward=float(np.mean(rewards)), success=sr,
|
||||||
|
settle_ratio=float(np.mean(settles)) if settles else None, rounds=float(np.mean(rounds)))
|
||||||
|
|
||||||
|
|
||||||
|
def main(episodes=15000, seed=42):
|
||||||
|
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
|
||||||
|
tcfg = TenantConfigLoader().load("ktcommerce")
|
||||||
|
policy = FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM + EXTRA_STATE_DIM,
|
||||||
|
card_dim=ACTION_DIM, eps_decay=5000, gamma=0.97)
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
|
||||||
|
print(f"=== 완전 자율 학습 {episodes}ep (행동 {len(ACTIONS)}개, 룰 0개) ===")
|
||||||
|
recent = []
|
||||||
|
for ep in range(1, episodes + 1):
|
||||||
|
sup = sample_supplier(rng)
|
||||||
|
rcfg, tf = sample_tenant_pref(rng, tcfg.reward)
|
||||||
|
rc = RewardCalculator(rcfg, tcfg.state)
|
||||||
|
_, _, r = run_episode(dqn_policy(policy), sup, rc, tf, seed * 131 + ep, learner=policy)
|
||||||
|
recent.append(r)
|
||||||
|
if ep % 3000 == 0:
|
||||||
|
print(f" ep {ep:>6} eps={policy.eps():.3f} 최근3000 평균보상={np.mean(recent[-3000:]):.4f}")
|
||||||
|
policy.save(CKPT_PATH)
|
||||||
|
|
||||||
|
print("\n=== 평가 3000ep (중립 성향 p=0.5, 동일 협력사 분포) ===")
|
||||||
|
policy.greedy = True
|
||||||
|
evaluate("룰시스템(현행)", lambda: RuleBaseline(), tcfg.reward, tcfg.state)
|
||||||
|
evaluate("완전자율 DQN", lambda: dqn_policy(policy), tcfg.reward, tcfg.state)
|
||||||
|
|
||||||
|
# 궤적 예시 — 에이전트가 룰 없이 뭘 하는지 눈으로
|
||||||
|
print("\n=== 궤적 예시 (완전자율) ===")
|
||||||
|
rc = RewardCalculator(pref_config(tcfg.reward, 0.5), tcfg.state)
|
||||||
|
tf = build_tenant_features(pref_config(tcfg.reward, 0.5))
|
||||||
|
rng2 = np.random.default_rng(7)
|
||||||
|
for k in range(3):
|
||||||
|
sup = sample_supplier(rng2)
|
||||||
|
trace = []
|
||||||
|
settled, turn, r = run_episode(dqn_policy(policy), sup, rc, tf, 5000 + k, trace=trace)
|
||||||
|
seg = "·".join(sup.segment)
|
||||||
|
print(f"[{seg}] " + " → ".join(
|
||||||
|
f"t{t}:{p:,}원 {a.kind}{'' if a.kind in ('accept', 'walk') else f'({a.counter_q:.2f},전략{a.strategy})' if a.kind == 'counter' else f'(전략{a.strategy})'}"
|
||||||
|
for t, p, a in trace) + f" ⇒ {'타결 ' + format(int(settled), ',') + '원' if settled else '결렬'} (r={r:.3f})")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -153,7 +153,6 @@ class quotations(MAIN_BASE):
|
|||||||
manager_contact_number = Column(String(20), nullable=True) # 담당자 연락처
|
manager_contact_number = Column(String(20), nullable=True) # 담당자 연락처
|
||||||
memo = Column(String(100), nullable=True) # 메모
|
memo = Column(String(100), nullable=True) # 메모
|
||||||
md_price = Column(BigInteger, nullable=True)
|
md_price = Column(BigInteger, nullable=True)
|
||||||
supplier_type = Column(SmallInteger, nullable=True)
|
|
||||||
iteration = Column(Integer, nullable=False, server_default=text("0")) # 반복 횟수
|
iteration = Column(Integer, nullable=False, server_default=text("0")) # 반복 횟수
|
||||||
preferred_sp_yn = Column(Boolean, nullable=True) # 선호 공급사 지정 여부
|
preferred_sp_yn = Column(Boolean, nullable=True) # 선호 공급사 지정 여부
|
||||||
preferred_sp_id = Column(UUID(as_uuid=True), nullable=True) # 선호 공급사(partner.suppliers.supplier_id)
|
preferred_sp_id = Column(UUID(as_uuid=True), nullable=True) # 선호 공급사(partner.suppliers.supplier_id)
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from typing import Tuple
|
from typing import Tuple
|
||||||
|
|
||||||
from sqlalchemy import asc, desc, func, select, update
|
from sqlalchemy import case, func, nulls_last, select, update
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import items, quotations, sessions
|
from common.database.model.models import items, quotations, sessions
|
||||||
from common.enums import ErrorType
|
from common.enums import ErrorType, SessionStatus
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
|
|
||||||
|
|
||||||
@@ -55,7 +55,26 @@ class SessionCRUD(ISessionCRUD):
|
|||||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]:
|
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]:
|
||||||
try:
|
try:
|
||||||
conds = self.__filters(supplier_id, status, qt_type)
|
conds = self.__filters(supplier_id, status, qt_type)
|
||||||
order_col = desc(quotations.end_time) if order == "desc" else asc(quotations.end_time)
|
|
||||||
|
# 정렬 규칙:
|
||||||
|
# - order 를 명시(asc/desc)하면 그룹 구분 없이 전체를 마감 기준 한 줄로 정렬(전체 정렬).
|
||||||
|
# - order 가 없으면(기본) UX 그룹 정렬:
|
||||||
|
# (1) '할 일'(협상생성·협상중)을 위로, 종료(완료·미참여·거부)는 아래로 그룹핑
|
||||||
|
# (2) 액션 그룹은 마감 임박순, (3) 종료 그룹은 최근 마감순(desc)
|
||||||
|
# - 어느 경우든 동일 마감은 session_id 로 tie-break → 페이지네이션 안정화.
|
||||||
|
# end_time 이 실제 NULL 인 견적은 nulls_last 로 맨 뒤로 민다.
|
||||||
|
if order in ("asc", "desc"):
|
||||||
|
flat = quotations.end_time.desc() if order == "desc" else quotations.end_time.asc()
|
||||||
|
order_cols = (nulls_last(flat), sessions.session_id.asc())
|
||||||
|
else:
|
||||||
|
# 그룹별로 정렬 방향이 달라, case 로 '자기 그룹 행만 end_time' 을 갖는 키를 만들고
|
||||||
|
# 반대 그룹은 NULL 로 눌러 간섭을 없앤다. status_rank 가 1차 키라 그룹 경계는 항상 유지.
|
||||||
|
actionable = sessions.status.in_((SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value))
|
||||||
|
status_rank = case((actionable, 0), else_=1)
|
||||||
|
action_order = case((actionable, quotations.end_time), else_=None).asc()
|
||||||
|
done_order = case((~actionable, quotations.end_time), else_=None).desc()
|
||||||
|
order_cols = (status_rank.asc(), nulls_last(action_order), nulls_last(done_order), sessions.session_id.asc())
|
||||||
|
|
||||||
query = (
|
query = (
|
||||||
select(
|
select(
|
||||||
sessions.session_id,
|
sessions.session_id,
|
||||||
@@ -71,7 +90,7 @@ class SessionCRUD(ISessionCRUD):
|
|||||||
.join(items, items.item_id == sessions.item_id)
|
.join(items, items.item_id == sessions.item_id)
|
||||||
.join(quotations, quotations.qt_id == sessions.quotation_id)
|
.join(quotations, quotations.qt_id == sessions.quotation_id)
|
||||||
.where(*conds, items.deleted == False, quotations.deleted == False) # noqa: E712
|
.where(*conds, items.deleted == False, quotations.deleted == False) # noqa: E712
|
||||||
.order_by(order_col)
|
.order_by(*order_cols)
|
||||||
.offset(offset)
|
.offset(offset)
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={40
|
|||||||
path="/sessions",
|
path="/sessions",
|
||||||
response_model=Res_SessionList,
|
response_model=Res_SessionList,
|
||||||
summary="협상 세션 목록",
|
summary="협상 세션 목록",
|
||||||
description="로그인한 공급사의 협상 세션 목록. 필터(status/qt_type, 정수 코드)·마감일 정렬·페이지네이션 지원.",
|
description="로그인한 공급사의 협상 세션 목록. 필터(status/qt_type, 정수 코드)·페이지네이션 지원. 기본 정렬(order 미지정)은 '할 일(협상생성·협상중) 우선 + 마감 임박순', 종료(완료·미참여·거부)는 하단·최근순. order 를 주면 그룹 없이 전체 마감순으로 정렬.",
|
||||||
)
|
)
|
||||||
async def list_sessions(
|
async def list_sessions(
|
||||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||||
@@ -23,7 +23,7 @@ async def list_sessions(
|
|||||||
service: NegotiationService = Depends(),
|
service: NegotiationService = Depends(),
|
||||||
status: Optional[int] = Query(None, description="세션 상태 코드 (SessionStatus)"),
|
status: Optional[int] = Query(None, description="세션 상태 코드 (SessionStatus)"),
|
||||||
qt_type: Optional[int] = Query(None, description="견적 유형 코드 (QtType: 1=재협상, 2=재견적, 3=신규협상, 4=신규견적)"),
|
qt_type: Optional[int] = Query(None, description="견적 유형 코드 (QtType: 1=재협상, 2=재견적, 3=신규협상, 4=신규견적)"),
|
||||||
order: str = Query("asc", description="마감일 정렬: asc(임박순)/desc"),
|
order: Optional[str] = Query(None, description="마감일 전체 정렬: asc(임박순)/desc(여유순). 미지정 시 기본 그룹 정렬('할 일' 우선 → 종료는 하단·최근순). 지정하면 그룹 없이 전체를 마감 기준으로 정렬."),
|
||||||
page: int = Query(1, ge=1, description="페이지 (1부터)"),
|
page: int = Query(1, ge=1, description="페이지 (1부터)"),
|
||||||
page_size: int = Query(20, ge=1, le=100, description="페이지당 건수 (1~100)"),
|
page_size: int = Query(20, ge=1, le=100, description="페이지당 건수 (1~100)"),
|
||||||
):
|
):
|
||||||
|
|||||||
@@ -105,10 +105,15 @@ async def anchor_seed(db_engine):
|
|||||||
{"iid": item_id, "name": f"앵커상품 {code}", "code": f"{MARK}{code}"},
|
{"iid": item_id, "name": f"앵커상품 {code}", "code": f"{MARK}{code}"},
|
||||||
)
|
)
|
||||||
await conn.execute(
|
await conn.execute(
|
||||||
text("INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, start_time, end_time, supplier_type) "
|
text("INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, start_time, end_time) "
|
||||||
"VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, 1, 2, now(), now() + interval '2 hours', 1)"),
|
"VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, 1, 2, now(), now() + interval '2 hours')"),
|
||||||
{"qid": qt_id, "name": f"앵커견적 {code}", "num": f"{MARK}{code}"},
|
{"qid": qt_id, "name": f"앵커견적 {code}", "num": f"{MARK}{code}"},
|
||||||
)
|
)
|
||||||
|
await conn.execute(
|
||||||
|
text("INSERT INTO partner.supplier_items (supplier_item_id, supplier_id, item_id, supply_type) "
|
||||||
|
"VALUES (gen_random_uuid(), :sid, :iid, 1)"),
|
||||||
|
{"sid": supplier_id, "iid": item_id},
|
||||||
|
)
|
||||||
await conn.execute(
|
await conn.execute(
|
||||||
text("INSERT INTO negotiation.sessions "
|
text("INSERT INTO negotiation.sessions "
|
||||||
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
|
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
|
||||||
|
|||||||
@@ -147,12 +147,24 @@ async def test_list_filter_qt_type(client, nego_seed):
|
|||||||
assert {i["item_code"] for i in body["items"]} == {f"{MARK}A", f"{MARK}C"}
|
assert {i["item_code"] for i in body["items"]} == {f"{MARK}A", f"{MARK}C"}
|
||||||
|
|
||||||
|
|
||||||
async def test_list_order_by_quotation_end_time(client, nego_seed):
|
async def test_list_default_sort_groups_actionable_first(client, nego_seed):
|
||||||
|
# 기본 정렬(order 미지정): '할 일'(협상생성 A·협상중 B) 우선 → 마감 임박순, 종료(협상완료 C)는 하단.
|
||||||
token = await _login_token(client)
|
token = await _login_token(client)
|
||||||
asc = (await _list(client, token, order="asc")).json()["items"]
|
default = [i["item_code"] for i in (await _list(client, token)).json()["items"]]
|
||||||
desc = (await _list(client, token, order="desc")).json()["items"]
|
# 액션 그룹 임박순(B +1h → A +2h) 뒤에 종료(C). C 는 마감이 가장 멀어도(+3h) 최하단 고정.
|
||||||
assert asc[0]["item_code"] == f"{MARK}B" # +1h 가 가장 임박
|
assert default == [f"{MARK}B", f"{MARK}A", f"{MARK}C"]
|
||||||
assert desc[0]["item_code"] == f"{MARK}C" # +3h 가 가장 멈
|
|
||||||
|
|
||||||
|
async def test_list_order_param_switches_to_global_sort(client, nego_seed):
|
||||||
|
# order 를 명시하면 그룹을 무시하고 전체를 마감 기준 한 줄로 정렬한다.
|
||||||
|
token = await _login_token(client)
|
||||||
|
asc = [i["item_code"] for i in (await _list(client, token, order="asc")).json()["items"]]
|
||||||
|
desc = [i["item_code"] for i in (await _list(client, token, order="desc")).json()["items"]]
|
||||||
|
|
||||||
|
# asc: 전체 마감 임박순 (B +1h → A +2h → C +3h)
|
||||||
|
assert asc == [f"{MARK}B", f"{MARK}A", f"{MARK}C"]
|
||||||
|
# desc: 전체 마감 여유순 — 종료(C)라도 마감이 가장 멀면 최상단으로 올라온다(그룹 무시 증거).
|
||||||
|
assert desc == [f"{MARK}C", f"{MARK}A", f"{MARK}B"]
|
||||||
|
|
||||||
|
|
||||||
async def test_list_pagination(client, nego_seed):
|
async def test_list_pagination(client, nego_seed):
|
||||||
|
|||||||
@@ -64,6 +64,8 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
APP_ENV: local
|
APP_ENV: local
|
||||||
DB_HOST: host.docker.internal # 컨테이너→호스트 DB (config.local.toml의 127.0.0.1 override)
|
DB_HOST: host.docker.internal # 컨테이너→호스트 DB (config.local.toml의 127.0.0.1 override)
|
||||||
|
DQN_SERVING: "1" # 카드 선택을 feature_dqn(numpy 서빙)으로. 0 이면 기존 UCB Q-table
|
||||||
|
AUTONOMY_MODE: "1" # 완전 자율 협상(판정 룰·카드 제거, 정책이 수락/역제안/결렬 결정). 0 이면 룰 엔진
|
||||||
ports:
|
ports:
|
||||||
- "9500:9500"
|
- "9500:9500"
|
||||||
extra_hosts:
|
extra_hosts:
|
||||||
|
|||||||
@@ -24,19 +24,23 @@ export const SESSION_STATUS_LABEL: Record<SessionStatus, string> = {
|
|||||||
export const QtType = {
|
export const QtType = {
|
||||||
RENEGO: 1, // 재협상(1:1)
|
RENEGO: 1, // 재협상(1:1)
|
||||||
REQUOTE: 2, // 재견적(1:N)
|
REQUOTE: 2, // 재견적(1:N)
|
||||||
|
NEW_NEGO: 3, // 신규협상(1:1)
|
||||||
|
NEW_QUOTE: 4, // 신규견적(1:N)
|
||||||
} as const
|
} as const
|
||||||
export type QtType = (typeof QtType)[keyof typeof QtType]
|
export type QtType = (typeof QtType)[keyof typeof QtType]
|
||||||
|
|
||||||
export const QT_TYPE_LABEL: Record<QtType, string> = {
|
export const QT_TYPE_LABEL: Record<QtType, string> = {
|
||||||
[QtType.RENEGO]: '재협상',
|
[QtType.RENEGO]: '재협상',
|
||||||
[QtType.REQUOTE]: '재견적',
|
[QtType.REQUOTE]: '재견적',
|
||||||
|
[QtType.NEW_NEGO]: '신규협상',
|
||||||
|
[QtType.NEW_QUOTE]: '신규견적',
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- 세션 목록 (GET /v1/negotiation/sessions) ----------------------------
|
// --- 세션 목록 (GET /v1/negotiation/sessions) ----------------------------
|
||||||
export interface SessionListParams {
|
export interface SessionListParams {
|
||||||
status?: number // SessionStatus 코드 필터
|
status?: number // SessionStatus 코드 필터
|
||||||
qt_type?: number // QtType 코드 필터
|
qt_type?: number // QtType 코드 필터
|
||||||
order?: 'asc' | 'desc' // 마감(qt_end_time) 정렬, asc=임박순
|
order?: 'asc' | 'desc' // 생략 시 기본 그룹 정렬('할 일' 우선+임박순, 종료는 하단). 지정 시 그룹 무시하고 전체 마감순(asc=임박/desc=여유)
|
||||||
page?: number
|
page?: number
|
||||||
page_size?: number
|
page_size?: number
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ export interface FilterGroupConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const FILTER_GROUPS: readonly FilterGroupConfig[] = [
|
export const FILTER_GROUPS: readonly FilterGroupConfig[] = [
|
||||||
{ key: 'type', title: '구분', items: ['재견적', '재협상'] },
|
{ key: 'type', title: '구분', items: ['재견적', '재협상', '신규견적', '신규협상'] },
|
||||||
{
|
{
|
||||||
key: 'status',
|
key: 'status',
|
||||||
title: '상태',
|
title: '상태',
|
||||||
|
|||||||
@@ -25,21 +25,23 @@ _current_values = table(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def fetch_current_values(db: AsyncSession, company_ids: list, supplier_type: int) -> dict:
|
async def fetch_current_values(db: AsyncSession, company_ids: list, supplier_types: list[int]) -> dict:
|
||||||
"""칸별 현재 앵커링 값 일괄 조회. {(company_id, price_range_index): rate‰} 반환.
|
"""칸별 현재 앵커링 값 일괄 조회. {(company_id, supplier_type, price_range_index): rate‰} 반환.
|
||||||
|
|
||||||
supplier_type 은 견적 단위로 하나뿐이라 키에 넣지 않는다.
|
supplier_type 은 세션의 (item_id, supplier_id) 매핑에서 온 supply_type 이다.
|
||||||
조정 이력이 없는 칸은 결과에 없다(호출측 정적 폴백). 조회 실패 시 빈 dict."""
|
조정 이력이 없는 칸은 결과에 없다(호출측 정적 폴백). 조회 실패 시 빈 dict."""
|
||||||
if not company_ids or supplier_type not in SAMPLEABLE_SUPPLIER_TYPES:
|
valid_types = sorted({int(t) for t in supplier_types if t in SAMPLEABLE_SUPPLIER_TYPES})
|
||||||
|
if not company_ids or not valid_types:
|
||||||
return {}
|
return {}
|
||||||
try:
|
try:
|
||||||
stmt = select(
|
stmt = select(
|
||||||
_current_values.c.company_id,
|
_current_values.c.company_id,
|
||||||
|
_current_values.c.supplier_type,
|
||||||
_current_values.c.price_range_index,
|
_current_values.c.price_range_index,
|
||||||
_current_values.c.anchoring_value,
|
_current_values.c.anchoring_value,
|
||||||
).where(
|
).where(
|
||||||
_current_values.c.company_id.in_(company_ids),
|
_current_values.c.company_id.in_(company_ids),
|
||||||
_current_values.c.supplier_type == supplier_type,
|
_current_values.c.supplier_type.in_(valid_types),
|
||||||
)
|
)
|
||||||
rows = (await db.execute(stmt)).all()
|
rows = (await db.execute(stmt)).all()
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
@@ -47,9 +49,9 @@ async def fetch_current_values(db: AsyncSession, company_ids: list, supplier_typ
|
|||||||
return {}
|
return {}
|
||||||
|
|
||||||
out = {}
|
out = {}
|
||||||
for company_id, price_range_index, rate in rows:
|
for company_id, supplier_type, price_range_index, rate in rows:
|
||||||
if not ANCHORING_VALUE_MIN <= rate <= ANCHORING_VALUE_MAX: # 범위 밖 값은 오염 방어 — 버리고 정적 폴백
|
if not ANCHORING_VALUE_MIN <= rate <= ANCHORING_VALUE_MAX: # 범위 밖 값은 오염 방어 — 버리고 정적 폴백
|
||||||
LOG.w(f"[앵커링] rate 범위 밖 — 무시(정적 폴백): company={company_id} bracket={price_range_index} rate={rate}")
|
LOG.w(f"[앵커링] rate 범위 밖 — 무시(정적 폴백): company={company_id} type={supplier_type} bracket={price_range_index} rate={rate}")
|
||||||
continue
|
continue
|
||||||
out[(company_id, price_range_index)] = rate
|
out[(company_id, supplier_type, price_range_index)] = rate
|
||||||
return out
|
return out
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from common.enums import UserRole
|
||||||
|
|
||||||
|
|
||||||
|
def is_owner_or_admin(resource_user_id, user_id, role) -> bool:
|
||||||
|
"""변경 액션 공용 소유권 판정 — 리소스 소유자(user_id 일치) 또는 최고관리자(OWNER)면 True.
|
||||||
|
|
||||||
|
프론트의 버튼 게이팅과 같은 규칙을 백엔드에서 강제하는 단일 출처.
|
||||||
|
소유자 없는 공용 리소스(예: user_id NULL 공용카드)는 이 판정 대상이 아니다(도메인별 별도 처리)."""
|
||||||
|
return str(resource_user_id) == str(user_id) or role == UserRole.OWNER.value
|
||||||
@@ -135,7 +135,7 @@ class supplier_items(MainTableMixin, MAIN_BASE):
|
|||||||
supplier_item_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
supplier_item_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
supplier_id = Column(UUID(as_uuid=True), nullable=False, index=True) # suppliers.supplier_id
|
supplier_id = Column(UUID(as_uuid=True), nullable=False, index=True) # suppliers.supplier_id
|
||||||
item_id = Column(UUID(as_uuid=True), nullable=False, index=True) # items.item_id
|
item_id = Column(UUID(as_uuid=True), nullable=False, index=True) # items.item_id
|
||||||
# SupplierType: 이 협력사가 이 상품을 공급하는 방식(0=없음/1=유통/2=제조/3=총판). quotations.supplier_type 와 값은 같으나 의미 단위가 (협력사,상품)이라 컬럼명은 supply_type.
|
# SupplierType: 이 협력사가 이 상품을 공급하는 방식(0=없음/1=유통/2=제조/3=총판).
|
||||||
supply_type = Column(SmallInteger, nullable=False, server_default=text("0"), default=0)
|
supply_type = Column(SmallInteger, nullable=False, server_default=text("0"), default=0)
|
||||||
|
|
||||||
|
|
||||||
@@ -229,8 +229,6 @@ class quotations(MainTableMixin, MAIN_BASE):
|
|||||||
manager_contact_number = Column(String(20), nullable=True)
|
manager_contact_number = Column(String(20), nullable=True)
|
||||||
memo = Column(String(100), nullable=True)
|
memo = Column(String(100), nullable=True)
|
||||||
md_price = Column(BigInteger, nullable=True)
|
md_price = Column(BigInteger, nullable=True)
|
||||||
supplier_type = Column(SmallInteger, nullable=True)
|
|
||||||
|
|
||||||
iteration = Column(Integer, nullable=False, default=0)
|
iteration = Column(Integer, nullable=False, default=0)
|
||||||
preferred_sp_yn = Column(Boolean, nullable=True)
|
preferred_sp_yn = Column(Boolean, nullable=True)
|
||||||
preferred_sp_id = Column(UUID(as_uuid=True), nullable=True)
|
preferred_sp_id = Column(UUID(as_uuid=True), nullable=True)
|
||||||
|
|||||||
@@ -237,8 +237,8 @@ class CardType(CodeEnum):
|
|||||||
|
|
||||||
|
|
||||||
class SupplierType(CodeEnum):
|
class SupplierType(CodeEnum):
|
||||||
"""quotations.supplier_type 코드값. 없음(0,미지정)/유통(1)/제조(2)/총판(3).
|
"""partner.supplier_items.supply_type 코드값. 없음(0,미지정)/유통(1)/제조(2)/총판(3).
|
||||||
없음은 프론트 폼에 '없음'으로 노출. KTC 앵커링 코드(기타=0)와 매핑 시 0↔없음 대응."""
|
없음은 상품-협력사 매핑에서 유형 미지정 상태를 뜻한다."""
|
||||||
|
|
||||||
NONE = 0 # 없음(미지정)
|
NONE = 0 # 없음(미지정)
|
||||||
DISTRIBUTION = 1 # 유통
|
DISTRIBUTION = 1 # 유통
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ class WebServerConfig(ConfigModel):
|
|||||||
is_test: bool = False
|
is_test: bool = False
|
||||||
client_url: str = ""
|
client_url: str = ""
|
||||||
nego_chat_url: str = "http://localhost:3300"
|
nego_chat_url: str = "http://localhost:3300"
|
||||||
|
agent_base_url: str = "http://localhost:9500" # 협상 agent(9500). 공용 카탈로그 변경 알림용.
|
||||||
|
|
||||||
|
|
||||||
class LogConfig(ConfigModel):
|
class LogConfig(ConfigModel):
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ from sqlalchemy import select, func, and_, or_, update
|
|||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.database.model.models import users
|
||||||
from common.enums import ErrorType
|
from common.enums import ErrorType
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from common.utils.gtime import GTime
|
from common.utils.gtime import GTime
|
||||||
@@ -32,13 +33,21 @@ class ICardCRUD(ABC):
|
|||||||
async def soft_delete(self, cdb: AsyncSession, model, pk_col, card_id) -> ErrorType:
|
async def soft_delete(self, cdb: AsyncSession, model, pk_col, card_id) -> ErrorType:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class CardCRUD(ICardCRUD):
|
class CardCRUD(ICardCRUD):
|
||||||
async def search(
|
async def search(
|
||||||
self, cdb: AsyncSession, model, user_id, search: Optional[str], skip: int, limit: int
|
self, cdb: AsyncSession, model, user_id, search: Optional[str], skip: int, limit: int
|
||||||
) -> Tuple[ErrorType, list, int]:
|
) -> Tuple[ErrorType, list, int]:
|
||||||
try:
|
try:
|
||||||
conditions = [model.deleted == False, model.user_id == user_id] # noqa: E712
|
# 내 개인 카드 + 전체(공용, user_id NULL) 카드. 남의 개인 카드는 제외.
|
||||||
|
conditions = [
|
||||||
|
model.deleted == False, # noqa: E712
|
||||||
|
or_(model.user_id == user_id, model.user_id.is_(None)),
|
||||||
|
]
|
||||||
if search:
|
if search:
|
||||||
conditions.append(
|
conditions.append(
|
||||||
or_(
|
or_(
|
||||||
@@ -102,3 +111,18 @@ class CardCRUD(ICardCRUD):
|
|||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED
|
return ErrorType.DB_RUN_FAILED
|
||||||
|
|
||||||
|
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
||||||
|
"""user_id 목록 → {user_id: name}. 카드 목록 '작성자(등록자)' 표기용(company.users 조인).
|
||||||
|
공용(user_id NULL) 카드는 호출 전에 걸러 넘긴다 → 맵에 없으면 작성자 없음."""
|
||||||
|
try:
|
||||||
|
if not user_ids:
|
||||||
|
return ErrorType.SUCCESS, {}
|
||||||
|
query = select(users.user_id, users.name).where(users.user_id.in_(user_ids))
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||||
|
if err_type != ErrorType.SUCCESS:
|
||||||
|
return err_type, {}
|
||||||
|
return ErrorType.SUCCESS, {uid: name for uid, name in rows}
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, {}
|
||||||
@@ -5,7 +5,7 @@ from sqlalchemy import select, func, and_, or_, update
|
|||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import items
|
from common.database.model.models import items, users
|
||||||
from common.enums import ErrorType
|
from common.enums import ErrorType
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from common.utils.gtime import GTime
|
from common.utils.gtime import GTime
|
||||||
@@ -45,6 +45,10 @@ class IItemCRUD(ABC):
|
|||||||
async def soft_delete(self, cdb: AsyncSession, item_id) -> ErrorType:
|
async def soft_delete(self, cdb: AsyncSession, item_id) -> ErrorType:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class ItemCRUD(IItemCRUD):
|
class ItemCRUD(IItemCRUD):
|
||||||
async def search(
|
async def search(
|
||||||
@@ -166,3 +170,17 @@ class ItemCRUD(IItemCRUD):
|
|||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED
|
return ErrorType.DB_RUN_FAILED
|
||||||
|
|
||||||
|
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
||||||
|
"""user_id 목록 → {user_id: name}. 상품 목록/상세 '등록자(작성자)' 표기용(company.users 조인)."""
|
||||||
|
try:
|
||||||
|
if not user_ids:
|
||||||
|
return ErrorType.SUCCESS, {}
|
||||||
|
query = select(users.user_id, users.name).where(users.user_id.in_(user_ids))
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||||
|
if err_type != ErrorType.SUCCESS:
|
||||||
|
return err_type, {}
|
||||||
|
return ErrorType.SUCCESS, {uid: name for uid, name in rows}
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, {}
|
||||||
@@ -8,9 +8,9 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import (
|
from common.database.model.models import (
|
||||||
quotations, sessions, chats, nego_cards, wild_cards, items, suppliers, quotation_settings,
|
quotations, sessions, chats, nego_cards, wild_cards, items, suppliers, quotation_settings,
|
||||||
version_nego_cards, version_wild_cards, users,
|
version_nego_cards, version_wild_cards, users, supplier_items,
|
||||||
)
|
)
|
||||||
from common.enums import ErrorType, QuotationStatus, SessionStatus
|
from common.enums import CloseReason, ErrorType, QuotationStatus, SessionStatus
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from common.utils.gtime import GTime
|
from common.utils.gtime import GTime
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ class IQuotationCRUD(ABC):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def get_last_supplier_type(self, cdb: AsyncSession, supplier_id, company_id=None) -> Tuple[ErrorType, Optional[tuple]]:
|
async def get_supply_types(self, cdb: AsyncSession, item_ids, supplier_ids) -> Tuple[ErrorType, dict]:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
@@ -148,6 +148,10 @@ class IQuotationCRUD(ABC):
|
|||||||
async def claim_for_close(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, int]:
|
async def claim_for_close(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, int]:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def claim_for_award(self, cdb: AsyncSession, qt_id, supplier_id, supplier_name) -> Tuple[ErrorType, int]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class QuotationCRUD(IQuotationCRUD):
|
class QuotationCRUD(IQuotationCRUD):
|
||||||
async def search(
|
async def search(
|
||||||
@@ -396,33 +400,30 @@ class QuotationCRUD(IQuotationCRUD):
|
|||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, {}
|
return ErrorType.DB_RUN_FAILED, {}
|
||||||
|
|
||||||
async def get_last_supplier_type(self, cdb: AsyncSession, supplier_id, company_id=None) -> Tuple[ErrorType, Optional[tuple]]:
|
async def get_supply_types(self, cdb: AsyncSession, item_ids, supplier_ids) -> Tuple[ErrorType, dict]:
|
||||||
"""협력사의 직전 견적 supplier_type. (supplier_type, qt_number) | None.
|
"""(item_id, supplier_id) -> supplier_items.supply_type 매핑.
|
||||||
sessions(supplier_id) ⨝ quotations 에서 supplier_type 가 있는 최신 견적 1건."""
|
|
||||||
|
매핑이 없거나 supply_type 이 0/NULL 이면 호출측이 정적 앵커링 값으로 폴백한다.
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
conds = [
|
if not item_ids or not supplier_ids:
|
||||||
sessions.supplier_id == supplier_id,
|
return ErrorType.SUCCESS, {}
|
||||||
quotations.supplier_type.isnot(None),
|
query = select(
|
||||||
quotations.deleted == False, # noqa: E712
|
supplier_items.item_id,
|
||||||
]
|
supplier_items.supplier_id,
|
||||||
if company_id is not None:
|
supplier_items.supply_type,
|
||||||
conds.append(quotations.user_id.in_(select(users.user_id).where(users.company_id == company_id)))
|
).where(
|
||||||
query = (
|
supplier_items.item_id.in_(item_ids),
|
||||||
select(quotations.supplier_type, quotations.number)
|
supplier_items.supplier_id.in_(supplier_ids),
|
||||||
.join(sessions, sessions.quotation_id == quotations.qt_id)
|
supplier_items.deleted == False, # noqa: E712
|
||||||
.where(*conds)
|
|
||||||
.order_by(quotations.created_at.desc())
|
|
||||||
.limit(1)
|
|
||||||
)
|
)
|
||||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||||
if err_type != ErrorType.SUCCESS:
|
if err_type != ErrorType.SUCCESS:
|
||||||
return err_type, None
|
return err_type, {}
|
||||||
if not rows:
|
return ErrorType.SUCCESS, {(r[0], r[1]): r[2] for r in rows}
|
||||||
return ErrorType.SUCCESS, None
|
|
||||||
return ErrorType.SUCCESS, (rows[0][0], rows[0][1])
|
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, None
|
return ErrorType.DB_RUN_FAILED, {}
|
||||||
|
|
||||||
async def get_setting_rates(self, cdb: AsyncSession, qt_setting_id) -> Tuple[ErrorType, dict]:
|
async def get_setting_rates(self, cdb: AsyncSession, qt_setting_id) -> Tuple[ErrorType, dict]:
|
||||||
"""견적 세팅의 목표 마진율: {margin}. 목표가 산정 입력(인터넷 수수료는 상수).
|
"""견적 세팅의 목표 마진율: {margin}. 목표가 산정 입력(인터넷 수수료는 상수).
|
||||||
@@ -474,6 +475,36 @@ class QuotationCRUD(IQuotationCRUD):
|
|||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, 0
|
return ErrorType.DB_RUN_FAILED, 0
|
||||||
|
|
||||||
|
async def claim_for_award(self, cdb: AsyncSession, qt_id, supplier_id, supplier_name) -> Tuple[ErrorType, int]:
|
||||||
|
"""[동시 직접낙찰 가드] 개찰(마감·낙찰자 미정, close_reason ∈ OPEN_*)인 견적만 낙찰(AWARDED)로 선점 전이.
|
||||||
|
선택 협력사를 낙찰자(preferred_sp_*)로 박고 동가 플래그는 내린다. status 는 이미 CLOSED 라 유지.
|
||||||
|
반환: (ErrorType, 적용행수). 이미 낙찰됐거나(재클릭) 개찰이 아니면 0 → 서비스가 한 번만 통과시킨다."""
|
||||||
|
try:
|
||||||
|
query = (
|
||||||
|
update(quotations)
|
||||||
|
.where(
|
||||||
|
quotations.qt_id == qt_id,
|
||||||
|
quotations.status == QuotationStatus.CLOSED.value,
|
||||||
|
quotations.close_reason.in_(
|
||||||
|
[CloseReason.OPEN_PRICE.value, CloseReason.OPEN_EQUAL.value,
|
||||||
|
CloseReason.OPEN_NOSHOW.value, CloseReason.OPEN_REJECT.value]
|
||||||
|
),
|
||||||
|
quotations.deleted == False, # noqa: E712
|
||||||
|
)
|
||||||
|
.values(
|
||||||
|
close_reason=CloseReason.AWARDED.value,
|
||||||
|
preferred_sp_yn=True,
|
||||||
|
preferred_sp_id=supplier_id,
|
||||||
|
preferred_sp_name=supplier_name,
|
||||||
|
equal_bid_yn=False,
|
||||||
|
updated_at=GTime.UTC(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, 0
|
||||||
|
|
||||||
async def update_sessions_status(self, cdb: AsyncSession, qt_id, from_statuses: list[int], to_status: int) -> ErrorType:
|
async def update_sessions_status(self, cdb: AsyncSession, qt_id, from_statuses: list[int], to_status: int) -> ErrorType:
|
||||||
# 견적에 딸린 세션 중 from_statuses 에 속한 것만 to_status 로 일괄 전이(삭제 제외). 다른 상태는 건드리지 않는다.
|
# 견적에 딸린 세션 중 from_statuses 에 속한 것만 to_status 로 일괄 전이(삭제 제외). 다른 상태는 건드리지 않는다.
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -0,0 +1,214 @@
|
|||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
|
from sqlalchemy import select, func, and_, case
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.database.model.models import quotations, sessions, items, chats, users
|
||||||
|
from common.enums import ErrorType, QuotationStatus, CloseReason, SessionStatus
|
||||||
|
from common.logger import LOG
|
||||||
|
|
||||||
|
|
||||||
|
# 통계 유니버스 = 현재 마감사유 5코드로 마감된 견적. 레거시 REGEN_*(2·3·4) 은 제외해
|
||||||
|
# KPI(낙찰률·마감수)와 유형별/결과분해의 분모를 일치시킨다(프로덕션엔 레거시 없어 전체 마감과 동일).
|
||||||
|
CURRENT_CLOSE_REASONS = [
|
||||||
|
CloseReason.AWARDED.value,
|
||||||
|
CloseReason.OPEN_PRICE.value,
|
||||||
|
CloseReason.OPEN_EQUAL.value,
|
||||||
|
CloseReason.OPEN_NOSHOW.value,
|
||||||
|
CloseReason.OPEN_REJECT.value,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
# 통계 집계 CRUD. 대시보드와 동일하게 회사 스코프(작성자 user_id→users.company_id)로 건다.
|
||||||
|
# owner(user_id) 가 주어지면 '내가 만든 견적'으로 더 좁힌다. quotations 엔 company_id 컬럼이 없어 서브쿼리로.
|
||||||
|
def _company_scope(company_id, owner) -> list:
|
||||||
|
conds = [
|
||||||
|
quotations.deleted == False, # noqa: E712
|
||||||
|
quotations.user_id.in_(select(users.user_id).where(users.company_id == company_id)),
|
||||||
|
]
|
||||||
|
if owner is not None:
|
||||||
|
conds.append(quotations.user_id == owner)
|
||||||
|
return conds
|
||||||
|
|
||||||
|
|
||||||
|
class IStatisticsCRUD(ABC):
|
||||||
|
@abstractmethod
|
||||||
|
async def winning_sessions(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def outcome_counts(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def type_counts(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def participation_counts(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def regen_avg_round(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, float]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def card_usage(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class StatisticsCRUD(IStatisticsCRUD):
|
||||||
|
async def winning_sessions(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
|
||||||
|
# 낙찰 마감 견적의 '낙찰 세션'(supplier_id=preferred_sp_id) 행 — 절감/추이/유형/카테고리/앵커도달률의 단일 원천.
|
||||||
|
# 파생: 저장 안 하고 조회 때 조인. category 는 items LEFT JOIN(자유텍스트·NULL 허용).
|
||||||
|
try:
|
||||||
|
stmt = (
|
||||||
|
select(
|
||||||
|
quotations.updated_at,
|
||||||
|
quotations.type,
|
||||||
|
items.category,
|
||||||
|
sessions.target_price,
|
||||||
|
sessions.bid_price,
|
||||||
|
sessions.anchoring_price,
|
||||||
|
)
|
||||||
|
.select_from(quotations)
|
||||||
|
.join(
|
||||||
|
sessions,
|
||||||
|
and_(
|
||||||
|
sessions.quotation_id == quotations.qt_id,
|
||||||
|
sessions.supplier_id == quotations.preferred_sp_id,
|
||||||
|
sessions.bid_price.isnot(None),
|
||||||
|
sessions.deleted == False, # noqa: E712
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.join(items, items.item_id == sessions.item_id, isouter=True)
|
||||||
|
.where(
|
||||||
|
and_(
|
||||||
|
*_company_scope(company_id, owner),
|
||||||
|
quotations.status == QuotationStatus.CLOSED.value,
|
||||||
|
quotations.close_reason == CloseReason.AWARDED.value,
|
||||||
|
quotations.updated_at >= since,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
err, rows = await DB_SESSION_MNG.execute(cdb, stmt)
|
||||||
|
return (err, list(rows) if err == ErrorType.SUCCESS else [])
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, []
|
||||||
|
|
||||||
|
async def outcome_counts(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
|
||||||
|
# 마감 결과 분해: close_reason 별 건수. 낙찰률·마감건수도 여기서 파생.
|
||||||
|
try:
|
||||||
|
stmt = (
|
||||||
|
select(quotations.close_reason, func.count())
|
||||||
|
.where(
|
||||||
|
and_(
|
||||||
|
*_company_scope(company_id, owner),
|
||||||
|
quotations.status == QuotationStatus.CLOSED.value,
|
||||||
|
quotations.close_reason.in_(CURRENT_CLOSE_REASONS),
|
||||||
|
quotations.updated_at >= since,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.group_by(quotations.close_reason)
|
||||||
|
)
|
||||||
|
err, rows = await DB_SESSION_MNG.execute(cdb, stmt)
|
||||||
|
return (err, list(rows) if err == ErrorType.SUCCESS else [])
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, []
|
||||||
|
|
||||||
|
async def type_counts(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
|
||||||
|
# 유형별(협상/경매) 마감 건수 + 낙찰 건수 → 유형별 낙찰률.
|
||||||
|
try:
|
||||||
|
awarded = func.sum(case((quotations.close_reason == CloseReason.AWARDED.value, 1), else_=0))
|
||||||
|
stmt = (
|
||||||
|
select(quotations.type, func.count(), awarded)
|
||||||
|
.where(
|
||||||
|
and_(
|
||||||
|
*_company_scope(company_id, owner),
|
||||||
|
quotations.status == QuotationStatus.CLOSED.value,
|
||||||
|
quotations.close_reason.in_(CURRENT_CLOSE_REASONS),
|
||||||
|
quotations.updated_at >= since,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.group_by(quotations.type)
|
||||||
|
)
|
||||||
|
err, rows = await DB_SESSION_MNG.execute(cdb, stmt)
|
||||||
|
return (err, list(rows) if err == ErrorType.SUCCESS else [])
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, []
|
||||||
|
|
||||||
|
async def participation_counts(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
|
||||||
|
# 협력사 참여: 회사 견적(창 내 생성)의 세션을 status 별 집계(응찰/미응찰/거부).
|
||||||
|
try:
|
||||||
|
conds = [
|
||||||
|
sessions.deleted == False, # noqa: E712
|
||||||
|
quotations.deleted == False, # noqa: E712
|
||||||
|
quotations.created_at >= since,
|
||||||
|
quotations.user_id.in_(select(users.user_id).where(users.company_id == company_id)),
|
||||||
|
]
|
||||||
|
if owner is not None:
|
||||||
|
conds.append(quotations.user_id == owner)
|
||||||
|
stmt = (
|
||||||
|
select(sessions.status, func.count())
|
||||||
|
.select_from(sessions)
|
||||||
|
.join(quotations, quotations.qt_id == sessions.quotation_id)
|
||||||
|
.where(and_(*conds))
|
||||||
|
.group_by(sessions.status)
|
||||||
|
)
|
||||||
|
err, rows = await DB_SESSION_MNG.execute(cdb, stmt)
|
||||||
|
return (err, list(rows) if err == ErrorType.SUCCESS else [])
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, []
|
||||||
|
|
||||||
|
async def regen_avg_round(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, float]:
|
||||||
|
# 평균 재견적 라운드. TODO: 체인키 없어 avg(round) 단순버전 — 체인당 최대 라운드 정의는 root_qt_id 도입 후.
|
||||||
|
try:
|
||||||
|
stmt = select(func.avg(quotations.round)).where(
|
||||||
|
and_(
|
||||||
|
*_company_scope(company_id, owner),
|
||||||
|
quotations.status == QuotationStatus.CLOSED.value,
|
||||||
|
quotations.close_reason.in_(CURRENT_CLOSE_REASONS),
|
||||||
|
quotations.updated_at >= since,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
err, rows = await DB_SESSION_MNG.execute(cdb, stmt)
|
||||||
|
if err != ErrorType.SUCCESS:
|
||||||
|
return err, 0.0
|
||||||
|
# 단일컬럼 집계는 execute 가 스칼라 리스트를 반환한다(대시보드 _count 와 동일). rows[0] 이 곧 avg 값.
|
||||||
|
val = rows[0] if rows else None
|
||||||
|
return ErrorType.SUCCESS, float(val) if val is not None else 0.0
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, 0.0
|
||||||
|
|
||||||
|
async def card_usage(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
|
||||||
|
# 카드 유형별 사용 빈도: card_used_yn=True 채팅을 card_type 별 집계(협상형 견적에서만 채팅 생성).
|
||||||
|
try:
|
||||||
|
conds = [
|
||||||
|
chats.deleted == False, # noqa: E712
|
||||||
|
chats.card_used_yn.is_(True),
|
||||||
|
quotations.deleted == False, # noqa: E712
|
||||||
|
quotations.created_at >= since,
|
||||||
|
quotations.user_id.in_(select(users.user_id).where(users.company_id == company_id)),
|
||||||
|
]
|
||||||
|
if owner is not None:
|
||||||
|
conds.append(quotations.user_id == owner)
|
||||||
|
stmt = (
|
||||||
|
select(chats.card_type, func.count())
|
||||||
|
.select_from(chats)
|
||||||
|
.join(sessions, sessions.session_id == chats.session_id)
|
||||||
|
.join(quotations, quotations.qt_id == sessions.quotation_id)
|
||||||
|
.where(and_(*conds))
|
||||||
|
.group_by(chats.card_type)
|
||||||
|
)
|
||||||
|
err, rows = await DB_SESSION_MNG.execute(cdb, stmt)
|
||||||
|
return (err, list(rows) if err == ErrorType.SUCCESS else [])
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, []
|
||||||
@@ -5,7 +5,7 @@ from sqlalchemy import select, func, and_, or_, update
|
|||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import suppliers
|
from common.database.model.models import suppliers, users
|
||||||
from common.enums import ErrorType
|
from common.enums import ErrorType
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from common.utils.gtime import GTime
|
from common.utils.gtime import GTime
|
||||||
@@ -41,6 +41,10 @@ class ISupplierCRUD(ABC):
|
|||||||
async def soft_delete(self, cdb: AsyncSession, supplier_id) -> ErrorType:
|
async def soft_delete(self, cdb: AsyncSession, supplier_id) -> ErrorType:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class SupplierCRUD(ISupplierCRUD):
|
class SupplierCRUD(ISupplierCRUD):
|
||||||
async def search(
|
async def search(
|
||||||
@@ -144,3 +148,17 @@ class SupplierCRUD(ISupplierCRUD):
|
|||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED
|
return ErrorType.DB_RUN_FAILED
|
||||||
|
|
||||||
|
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
||||||
|
"""user_id 목록 → {user_id: name}. 협력사 목록/상세 '등록자(작성자)' 표기용(company.users 조인)."""
|
||||||
|
try:
|
||||||
|
if not user_ids:
|
||||||
|
return ErrorType.SUCCESS, {}
|
||||||
|
query = select(users.user_id, users.name).where(users.user_id.in_(user_ids))
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||||
|
if err_type != ErrorType.SUCCESS:
|
||||||
|
return err_type, {}
|
||||||
|
return ErrorType.SUCCESS, {uid: name for uid, name in rows}
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, {}
|
||||||
@@ -19,6 +19,7 @@ import router.v1.card.card
|
|||||||
import router.v1.quotation.quotation
|
import router.v1.quotation.quotation
|
||||||
import router.v1.quotation_setting.quotation_setting
|
import router.v1.quotation_setting.quotation_setting
|
||||||
import router.v1.dashboard.dashboard
|
import router.v1.dashboard.dashboard
|
||||||
|
import router.v1.statistics.statistics
|
||||||
import router.v1.notification.notification
|
import router.v1.notification.notification
|
||||||
|
|
||||||
API_SERVER_START_TIME = GTime.UTCStr()
|
API_SERVER_START_TIME = GTime.UTCStr()
|
||||||
@@ -74,4 +75,5 @@ app.include_router(router.v1.card.card.router)
|
|||||||
app.include_router(router.v1.quotation.quotation.router)
|
app.include_router(router.v1.quotation.quotation.router)
|
||||||
app.include_router(router.v1.quotation_setting.quotation_setting.router)
|
app.include_router(router.v1.quotation_setting.quotation_setting.router)
|
||||||
app.include_router(router.v1.dashboard.dashboard.router)
|
app.include_router(router.v1.dashboard.dashboard.router)
|
||||||
|
app.include_router(router.v1.statistics.statistics.router)
|
||||||
app.include_router(router.v1.notification.notification.router)
|
app.include_router(router.v1.notification.notification.router)
|
||||||
@@ -14,6 +14,7 @@ class CardProtocol(WebPacketProtocol):
|
|||||||
|
|
||||||
class Req_CreateCard(CardProtocol):
|
class Req_CreateCard(CardProtocol):
|
||||||
is_wildcard: bool = False
|
is_wildcard: bool = False
|
||||||
|
is_shared: bool = False # True=전체(공용, user_id NULL 저장) / False=개인(등록 유저 소유)
|
||||||
name: Optional[str] = None
|
name: Optional[str] = None
|
||||||
number: Optional[str] = None
|
number: Optional[str] = None
|
||||||
script: Optional[str] = None
|
script: Optional[str] = None
|
||||||
@@ -42,6 +43,8 @@ class CardData(WebPacketProtocol):
|
|||||||
nego_card_id: uuid.UUID # 통합 식별자(일반=nego_card_id / 와일드=wild_card_id)
|
nego_card_id: uuid.UUID # 통합 식별자(일반=nego_card_id / 와일드=wild_card_id)
|
||||||
user_id: Optional[uuid.UUID] = None
|
user_id: Optional[uuid.UUID] = None
|
||||||
is_wildcard: bool = False
|
is_wildcard: bool = False
|
||||||
|
is_shared: bool = False # 전체(공용) 카드 여부 = user_id NULL. 목록 배지/폼 스코프 표시용
|
||||||
|
creator_name: Optional[str] = None # 작성자(등록자) 이름. user_id→company.users.name 조인. 공용 카드는 None
|
||||||
name: Optional[str] = None
|
name: Optional[str] = None
|
||||||
number: Optional[str] = None
|
number: Optional[str] = None
|
||||||
script: Optional[str] = None
|
script: Optional[str] = None
|
||||||
|
|||||||
@@ -69,12 +69,12 @@ async def get_item(item_id: UUID, service: ItemService = Depends(), user_info: U
|
|||||||
async def update_item(
|
async def update_item(
|
||||||
item_id: UUID, req: Req_UpdateItem, service: ItemService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
item_id: UUID, req: Req_UpdateItem, service: ItemService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||||
):
|
):
|
||||||
return RemoveNoneResponse(await service.update_item(user_info.company_id, str(item_id), req))
|
return RemoveNoneResponse(await service.update_item(user_info.company_id, str(item_id), req, user_info.user_id, user_info.role))
|
||||||
|
|
||||||
|
|
||||||
@router.delete(path="/delete/{item_id}", response_model=Res_DeleteItem, summary="상품 삭제")
|
@router.delete(path="/delete/{item_id}", response_model=Res_DeleteItem, summary="상품 삭제")
|
||||||
async def delete_item(item_id: UUID, service: ItemService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
async def delete_item(item_id: UUID, service: ItemService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||||
return RemoveNoneResponse(await service.delete_item(user_info.company_id, str(item_id)))
|
return RemoveNoneResponse(await service.delete_item(user_info.company_id, str(item_id), user_info.user_id, user_info.role))
|
||||||
|
|
||||||
|
|
||||||
@router.post(path="/{item_id}/lowest-price", response_model=Res_LowestPriceTrigger, summary="최저가 수집 요청(스텁)")
|
@router.post(path="/{item_id}/lowest-price", response_model=Res_LowestPriceTrigger, summary="최저가 수집 요청(스텁)")
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ class ItemData(WebPacketProtocol):
|
|||||||
item_id: uuid.UUID
|
item_id: uuid.UUID
|
||||||
company_id: uuid.UUID
|
company_id: uuid.UUID
|
||||||
user_id: uuid.UUID
|
user_id: uuid.UUID
|
||||||
|
creator_name: Optional[str] = None # 등록자(작성자) 이름. user_id→company.users.name 조인
|
||||||
name: str
|
name: str
|
||||||
code: Optional[str] = None
|
code: Optional[str] = None
|
||||||
category: Optional[str] = None
|
category: Optional[str] = None
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from typing import Any, Optional
|
|||||||
|
|
||||||
from pydantic import ConfigDict
|
from pydantic import ConfigDict
|
||||||
|
|
||||||
from common.enums import CardType, ChatSender, CloseReason, DeliveryType, PriceGateAction, QuotationStatus, QuotationType, SessionStatus, SupplierType
|
from common.enums import CardType, ChatSender, CloseReason, DeliveryType, PriceGateAction, QuotationStatus, QuotationType, SessionStatus
|
||||||
from common.models.gmodel import Res_PageProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
from common.models.gmodel import Res_PageProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||||
|
|
||||||
|
|
||||||
@@ -26,7 +26,6 @@ class Req_CreateQuotation(QuotationProtocol):
|
|||||||
manager_contact_number: Optional[str] = None
|
manager_contact_number: Optional[str] = None
|
||||||
memo: Optional[str] = None
|
memo: Optional[str] = None
|
||||||
md_price: Optional[int] = None # MD 제시가(원). 세션 목표가 산정 최우선값
|
md_price: Optional[int] = None # MD 제시가(원). 세션 목표가 산정 최우선값
|
||||||
supplier_type: Optional[int] = None # 협력사 유형(SupplierType). 재견적 1:1 → 견적에 기록
|
|
||||||
item_ids: list[uuid.UUID] = [] # 협상 대상 상품. item×supplier 조합마다 세션 1개 생성
|
item_ids: list[uuid.UUID] = [] # 협상 대상 상품. item×supplier 조합마다 세션 1개 생성
|
||||||
supplier_ids: list[uuid.UUID] = [] # 협상 초청 공급사
|
supplier_ids: list[uuid.UUID] = [] # 협상 초청 공급사
|
||||||
card_ids: list[uuid.UUID] = [] # 선택 협상카드. 버전을 만들어 묶고 quotation.version_id 로 연결
|
card_ids: list[uuid.UUID] = [] # 선택 협상카드. 버전을 만들어 묶고 quotation.version_id 로 연결
|
||||||
@@ -40,6 +39,10 @@ class Req_RegenerateQuotation(QuotationProtocol):
|
|||||||
supplier_ids: list[uuid.UUID] = [] # 다음 라운드에 부를 공급사(프론트 선택). 상품·기간·번호는 원 견적에서 이어받음
|
supplier_ids: list[uuid.UUID] = [] # 다음 라운드에 부를 공급사(프론트 선택). 상품·기간·번호는 원 견적에서 이어받음
|
||||||
|
|
||||||
|
|
||||||
|
class Req_AwardQuotation(QuotationProtocol):
|
||||||
|
winner_supplier_id: uuid.UUID # 담당자가 직접 낙찰시킬 협력사(투찰한 협상완료 세션 중 선택)
|
||||||
|
|
||||||
|
|
||||||
class QuotationData(WebPacketProtocol):
|
class QuotationData(WebPacketProtocol):
|
||||||
model_config = ConfigDict(from_attributes=True)
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
@@ -59,7 +62,6 @@ class QuotationData(WebPacketProtocol):
|
|||||||
manager_contact_number: Optional[str] = None
|
manager_contact_number: Optional[str] = None
|
||||||
memo: Optional[str] = None
|
memo: Optional[str] = None
|
||||||
md_price: Optional[int] = None
|
md_price: Optional[int] = None
|
||||||
supplier_type: Optional[SupplierType] = None
|
|
||||||
iteration: int = 0
|
iteration: int = 0
|
||||||
preferred_sp_yn: Optional[bool] = None
|
preferred_sp_yn: Optional[bool] = None
|
||||||
preferred_sp_id: Optional[uuid.UUID] = None
|
preferred_sp_id: Optional[uuid.UUID] = None
|
||||||
@@ -185,11 +187,6 @@ class Res_QuotationCards(Res_WebPacketProtocol):
|
|||||||
cards: list[QuotationCardData] = []
|
cards: list[QuotationCardData] = []
|
||||||
|
|
||||||
|
|
||||||
class Res_LastSupplierType(Res_WebPacketProtocol):
|
|
||||||
supplier_type: Optional[SupplierType] = None # 협력사 직전 견적의 유형(없으면 None)
|
|
||||||
qt_number: Optional[str] = None # 그 견적의 번호(이전 견적 값임을 표시용)
|
|
||||||
|
|
||||||
|
|
||||||
class TargetCandidate(WebPacketProtocol):
|
class TargetCandidate(WebPacketProtocol):
|
||||||
basis: str
|
basis: str
|
||||||
label: str
|
label: str
|
||||||
|
|||||||
@@ -7,11 +7,11 @@ from common.models.gmodel import PageParams, UserInfo
|
|||||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
|
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
|
||||||
from services.quotation_service import QuotationService
|
from services.quotation_service import QuotationService
|
||||||
from .protocol import (
|
from .protocol import (
|
||||||
|
Req_AwardQuotation,
|
||||||
Req_CreateQuotation,
|
Req_CreateQuotation,
|
||||||
Req_RegenerateQuotation,
|
Req_RegenerateQuotation,
|
||||||
Res_CreateQuotation,
|
Res_CreateQuotation,
|
||||||
Res_DeleteQuotation,
|
Res_DeleteQuotation,
|
||||||
Res_LastSupplierType,
|
|
||||||
Res_NotifySessions,
|
Res_NotifySessions,
|
||||||
Res_Quotation,
|
Res_Quotation,
|
||||||
Res_QuotationCards,
|
Res_QuotationCards,
|
||||||
@@ -55,14 +55,24 @@ async def create_quotation(
|
|||||||
|
|
||||||
@router.post(path="/stop/{qt_id}", response_model=Res_Quotation, summary="견적 마감")
|
@router.post(path="/stop/{qt_id}", response_model=Res_Quotation, summary="견적 마감")
|
||||||
async def stop_quotation(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
async def stop_quotation(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||||
return RemoveNoneResponse(await service.stop_quotation(str(qt_id), user_info.company_id))
|
return RemoveNoneResponse(await service.stop_quotation(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(path="/award/{qt_id}", response_model=Res_Quotation, summary="개찰 견적 직접 낙찰")
|
||||||
|
async def award_quotation(
|
||||||
|
qt_id: UUID, req: Req_AwardQuotation, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||||
|
):
|
||||||
|
# 권한(본인 견적만/OWNER 예외)은 서비스에서 판정하도록 호출자 user_id·role 을 넘긴다.
|
||||||
|
return RemoveNoneResponse(
|
||||||
|
await service.award_quotation(str(qt_id), user_info.company_id, user_info.user_id, user_info.role, req.winner_supplier_id)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post(path="/regenerate/{qt_id}", response_model=Res_CreateQuotation, summary="견적 재생성(다음 라운드)")
|
@router.post(path="/regenerate/{qt_id}", response_model=Res_CreateQuotation, summary="견적 재생성(다음 라운드)")
|
||||||
async def regenerate_quotation(
|
async def regenerate_quotation(
|
||||||
qt_id: UUID, req: Req_RegenerateQuotation, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
qt_id: UUID, req: Req_RegenerateQuotation, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||||
):
|
):
|
||||||
return RemoveNoneResponse(await service.regenerate_quotation(str(qt_id), user_info.company_id, req.supplier_ids))
|
return RemoveNoneResponse(await service.regenerate_quotation(str(qt_id), user_info.company_id, req.supplier_ids, user_info.user_id, user_info.role))
|
||||||
|
|
||||||
|
|
||||||
# ----- 견적 상세 (FK로 연결된 하위 데이터 / 일부는 모델 미존재로 스텁) -----
|
# ----- 견적 상세 (FK로 연결된 하위 데이터 / 일부는 모델 미존재로 스텁) -----
|
||||||
@@ -78,7 +88,7 @@ async def get_quotation_sessions(qt_id: UUID, service: QuotationService = Depend
|
|||||||
|
|
||||||
@router.post(path="/{qt_id}/notify", response_model=Res_NotifySessions, summary="협상 초청 메일 발송")
|
@router.post(path="/{qt_id}/notify", response_model=Res_NotifySessions, summary="협상 초청 메일 발송")
|
||||||
async def notify_quotation(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
async def notify_quotation(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||||
return RemoveNoneResponse(await service.notify_sessions(str(qt_id), user_info.company_id))
|
return RemoveNoneResponse(await service.notify_sessions(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
|
||||||
|
|
||||||
|
|
||||||
@router.get(path="/session/{session_id}/chat", response_model=Res_SessionChat, summary="채팅 상세")
|
@router.get(path="/session/{session_id}/chat", response_model=Res_SessionChat, summary="채팅 상세")
|
||||||
@@ -93,7 +103,7 @@ async def get_target_breakdown(session_id: UUID, service: QuotationService = Dep
|
|||||||
|
|
||||||
@router.post(path="/session/{session_id}/notify", response_model=Res_NotifySessions, summary="세션 초청 메일 재발송")
|
@router.post(path="/session/{session_id}/notify", response_model=Res_NotifySessions, summary="세션 초청 메일 재발송")
|
||||||
async def notify_session(session_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
async def notify_session(session_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||||
return RemoveNoneResponse(await service.notify_session(str(session_id), user_info.company_id))
|
return RemoveNoneResponse(await service.notify_session(str(session_id), user_info.company_id, user_info.user_id, user_info.role))
|
||||||
|
|
||||||
|
|
||||||
@router.get(path="/{qt_id}/result", response_model=Res_QuotationResult, summary="낙찰 결과")
|
@router.get(path="/{qt_id}/result", response_model=Res_QuotationResult, summary="낙찰 결과")
|
||||||
@@ -108,12 +118,7 @@ async def get_quotation_cards(qt_id: UUID, service: QuotationService = Depends()
|
|||||||
|
|
||||||
@router.delete(path="/delete/{qt_id}", response_model=Res_DeleteQuotation, summary="견적 삭제")
|
@router.delete(path="/delete/{qt_id}", response_model=Res_DeleteQuotation, summary="견적 삭제")
|
||||||
async def delete_quotation(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
async def delete_quotation(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||||
return RemoveNoneResponse(await service.delete_quotation(str(qt_id), user_info.company_id))
|
return RemoveNoneResponse(await service.delete_quotation(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
|
||||||
|
|
||||||
|
|
||||||
@router.get(path="/supplier/{supplier_id}/last-type", response_model=Res_LastSupplierType, summary="협력사 직전 견적 유형")
|
|
||||||
async def get_supplier_last_type(supplier_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
|
||||||
return RemoveNoneResponse(await service.get_last_supplier_type(str(supplier_id), user_info.company_id))
|
|
||||||
|
|
||||||
|
|
||||||
# ----- 단건 조회 (정적/하위 경로 뒤에 선언) -----
|
# ----- 단건 조회 (정적/하위 경로 뒤에 선언) -----
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
from pydantic import Field
|
||||||
|
|
||||||
|
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||||
|
|
||||||
|
|
||||||
|
class StatisticsProtocol(WebPacketProtocol):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class StatKpi(WebPacketProtocol):
|
||||||
|
total_savings: int = 0 # 총 절감액(목표가 대비, 낙찰세션 target−bid 합)
|
||||||
|
savings_rate: float = 0.0 # 평균 절감률 = 절감합/목표합
|
||||||
|
award_rate: float = 0.0 # 낙찰률 = 낙찰 마감 / 전체 마감
|
||||||
|
anchor_reach_rate: float = 0.0 # 평균 앵커 도달률 = (목표−투찰)/(목표−앵커)
|
||||||
|
savings_delta_mom: int = 0 # 전월 대비 절감액 증감
|
||||||
|
closed_count: int = 0 # 마감 견적 수(창)
|
||||||
|
regen_avg_round: float = 0.0 # 평균 재견적 라운드
|
||||||
|
|
||||||
|
|
||||||
|
class StatMonthPoint(WebPacketProtocol):
|
||||||
|
month: str # 'YYYY-MM'
|
||||||
|
savings: int = 0
|
||||||
|
rate: float = 0.0
|
||||||
|
|
||||||
|
|
||||||
|
class StatOutcome(WebPacketProtocol):
|
||||||
|
awarded: int = 0 # CloseReason 1
|
||||||
|
open_price: int = 0 # 5 가격 미달
|
||||||
|
open_equal: int = 0 # 6 동가
|
||||||
|
open_noshow: int = 0 # 7 미응찰
|
||||||
|
open_reject: int = 0 # 8 거부
|
||||||
|
|
||||||
|
|
||||||
|
class StatParticipation(WebPacketProtocol):
|
||||||
|
bid: int = 0 # 응찰(SessionStatus DONE)
|
||||||
|
no_participate: int = 0 # 미응찰(NOT_PARTICIPATED)
|
||||||
|
rejected: int = 0 # 거부(REJECTED)
|
||||||
|
|
||||||
|
|
||||||
|
class StatTypeRow(WebPacketProtocol):
|
||||||
|
label: str
|
||||||
|
award_rate: float = 0.0
|
||||||
|
avg_savings: int = 0
|
||||||
|
count: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
class StatCategory(WebPacketProtocol):
|
||||||
|
category: str
|
||||||
|
savings: int = 0
|
||||||
|
count: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
class StatCardUsage(WebPacketProtocol):
|
||||||
|
type: str # 'nego' | 'wild'
|
||||||
|
label: str
|
||||||
|
uses: int = 0
|
||||||
|
avg_drop: int = 0 # 사용 직후 상대 제시가 평균 하락. TODO: v1은 0(유형별 빈도만) — chats seq 델타 계산은 다음 단계.
|
||||||
|
|
||||||
|
|
||||||
|
class StatScope(WebPacketProtocol):
|
||||||
|
kpi: StatKpi = Field(default_factory=StatKpi)
|
||||||
|
trend: list[StatMonthPoint] = []
|
||||||
|
outcome: StatOutcome = Field(default_factory=StatOutcome)
|
||||||
|
participation: StatParticipation = Field(default_factory=StatParticipation)
|
||||||
|
type_split: list[StatTypeRow] = []
|
||||||
|
categories: list[StatCategory] = []
|
||||||
|
cards: list[StatCardUsage] = []
|
||||||
|
|
||||||
|
|
||||||
|
class Res_StatisticsSummary(Res_WebPacketProtocol):
|
||||||
|
company: StatScope = Field(default_factory=StatScope) # 회사 전체(company_id 스코프)
|
||||||
|
mine: StatScope = Field(default_factory=StatScope) # 내가 만든 견적(user_id 추가 스코프)
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
from common.models.gmodel import UserInfo
|
||||||
|
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
|
||||||
|
from services.statistics_service import StatisticsService
|
||||||
|
from .protocol import Res_StatisticsSummary
|
||||||
|
|
||||||
|
# 라우터(컨트롤러). 인증(Depends(IsValidAccessToken))의 UserInfo 로 company/user 스코프 집계를 한 번에 내린다.
|
||||||
|
router = APIRouter(prefix="/v1/statistics", tags=["Statistics"], responses={404: {"description": "Not found"}})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(path="/summary", response_model=Res_StatisticsSummary, summary="통계 요약(회사 전체 + 내 견적)")
|
||||||
|
async def get_statistics_summary(service: StatisticsService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||||
|
return RemoveNoneResponse(await service.get_summary(user_info.company_id, user_info.user_id))
|
||||||
@@ -35,6 +35,7 @@ class SupplierData(WebPacketProtocol):
|
|||||||
supplier_id: uuid.UUID
|
supplier_id: uuid.UUID
|
||||||
company_id: uuid.UUID
|
company_id: uuid.UUID
|
||||||
user_id: uuid.UUID
|
user_id: uuid.UUID
|
||||||
|
creator_name: Optional[str] = None # 등록자(작성자) 이름. user_id→company.users.name 조인
|
||||||
name: str
|
name: str
|
||||||
code: Optional[str] = None
|
code: Optional[str] = None
|
||||||
manager_name: Optional[str] = None
|
manager_name: Optional[str] = None
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ from uuid import UUID
|
|||||||
from fastapi import APIRouter, Depends, Query
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
|
||||||
from common.models.gmodel import PageParams, UserInfo
|
from common.models.gmodel import PageParams, UserInfo
|
||||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
|
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, RequireOwner
|
||||||
from services.supplier_service import SupplierService
|
from services.supplier_service import SupplierService
|
||||||
from .protocol import (
|
from .protocol import (
|
||||||
Req_CheckCodes,
|
Req_CheckCodes,
|
||||||
@@ -59,6 +59,7 @@ async def update_supplier(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.delete(path="/delete/{supplier_id}", response_model=Res_DeleteSupplier, summary="협력사 삭제")
|
@router.delete(path="/delete/{supplier_id}", response_model=Res_DeleteSupplier, summary="협력사 삭제 (최고관리자 전용)")
|
||||||
async def delete_supplier(supplier_id: UUID, service: SupplierService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
async def delete_supplier(supplier_id: UUID, service: SupplierService = Depends(), user_info: UserInfo = Depends(RequireOwner)):
|
||||||
|
# 협력사 명부는 회사 공유 자원 — 파괴적 삭제는 최고관리자만(RequireOwner 가 비-OWNER 를 403 차단).
|
||||||
return RemoveNoneResponse(await service.delete_supplier(user_info.company_id, str(supplier_id)))
|
return RemoveNoneResponse(await service.delete_supplier(user_info.company_id, str(supplier_id)))
|
||||||
@@ -34,7 +34,7 @@ INSERT INTO quotation.quotations
|
|||||||
(qt_id, user_id, qt_setting_id, version_id, name, number, type, round, status,
|
(qt_id, user_id, qt_setting_id, version_id, name, number, type, round, status,
|
||||||
start_time, end_time, manager_name, manager_email, manager_contact_number, memo,
|
start_time, end_time, manager_name, manager_email, manager_contact_number, memo,
|
||||||
iteration, preferred_sp_yn, preferred_sp_id, preferred_sp_name, equal_bid_yn, equal_bid_data,
|
iteration, preferred_sp_yn, preferred_sp_id, preferred_sp_name, equal_bid_yn, equal_bid_data,
|
||||||
close_reason, md_price, supplier_type, created_at, updated_at, deleted)
|
close_reason, md_price, created_at, updated_at, deleted)
|
||||||
VALUES
|
VALUES
|
||||||
-- ① 낙찰(절감): 목표 400,000 → 낙찰 372,000
|
-- ① 낙찰(절감): 목표 400,000 → 낙찰 372,000
|
||||||
('aaaa0001-0000-0000-0000-000000000001','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
('aaaa0001-0000-0000-0000-000000000001','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||||
@@ -42,14 +42,14 @@ VALUES
|
|||||||
'① 낙찰(절감) 데모','EST-DEMO-01',4,1,3,
|
'① 낙찰(절감) 데모','EST-DEMO-01',4,1,3,
|
||||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','낙찰·목표대비 절감 케이스',
|
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','낙찰·목표대비 절감 케이스',
|
||||||
1, true,'9795c2e5-3ac2-4e44-aeb5-c6c5e3053f09','(주)대한정밀', null, null,
|
1, true,'9795c2e5-3ac2-4e44-aeb5-c6c5e3053f09','(주)대한정밀', null, null,
|
||||||
1, 400000, 1, now(), now(), false),
|
1, 400000, now(), now(), false),
|
||||||
-- ② 낙찰(목표초과): 목표 350,000 → 낙찰 368,000 (over_action=낙찰)
|
-- ② 낙찰(목표초과): 목표 350,000 → 낙찰 368,000 (over_action=낙찰)
|
||||||
('aaaa0002-0000-0000-0000-000000000002','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
('aaaa0002-0000-0000-0000-000000000002','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||||
'② 낙찰(목표초과) 데모','EST-DEMO-02',4,1,3,
|
'② 낙찰(목표초과) 데모','EST-DEMO-02',4,1,3,
|
||||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','낙찰이지만 목표가 초과 케이스',
|
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','낙찰이지만 목표가 초과 케이스',
|
||||||
1, true,'69e7057a-5919-48cd-b329-13b833bff994','서울산업소재(주)', null, null,
|
1, true,'69e7057a-5919-48cd-b329-13b833bff994','서울산업소재(주)', null, null,
|
||||||
1, 350000, 1, now(), now(), false),
|
1, 350000, now(), now(), false),
|
||||||
-- ③ 동가 재입찰(REGEN_EQUAL): 두 곳 390,000 동률 → 재입찰 진행
|
-- ③ 동가 재입찰(REGEN_EQUAL): 두 곳 390,000 동률 → 재입찰 진행
|
||||||
('aaaa0003-0000-0000-0000-000000000003','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
('aaaa0003-0000-0000-0000-000000000003','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||||
@@ -57,42 +57,42 @@ VALUES
|
|||||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','동가 발생·다음 라운드 재입찰 케이스',
|
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','동가 발생·다음 라운드 재입찰 케이스',
|
||||||
1, false, null, null, true,
|
1, false, null, null, true,
|
||||||
'[{"supplier_id":"9795c2e5-3ac2-4e44-aeb5-c6c5e3053f09","supplier_name":"(주)대한정밀","bid_price":390000},{"supplier_id":"747897ec-adab-4f3e-9076-15803ddf821f","supplier_name":"글로벌테크놀로지","bid_price":390000}]'::jsonb,
|
'[{"supplier_id":"9795c2e5-3ac2-4e44-aeb5-c6c5e3053f09","supplier_name":"(주)대한정밀","bid_price":390000},{"supplier_id":"747897ec-adab-4f3e-9076-15803ddf821f","supplier_name":"글로벌테크놀로지","bid_price":390000}]'::jsonb,
|
||||||
6, 400000, 1, now(), now(), false),
|
6, 400000, now(), now(), false),
|
||||||
-- ④ 거부 유찰(FAIL_REJECT): 협상거부로 마감
|
-- ④ 거부 유찰(FAIL_REJECT): 협상거부로 마감
|
||||||
('aaaa0004-0000-0000-0000-000000000004','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
('aaaa0004-0000-0000-0000-000000000004','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||||
'④ 거부 개찰 데모','EST-DEMO-04',2,1,3,
|
'④ 거부 개찰 데모','EST-DEMO-04',2,1,3,
|
||||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','협상 거부로 유찰 케이스',
|
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','협상 거부로 유찰 케이스',
|
||||||
1, null, null, null, null, null,
|
1, null, null, null, null, null,
|
||||||
8, 400000, 1, now(), now(), false),
|
8, 400000, now(), now(), false),
|
||||||
-- ⑤ 미참여 재소집(REGEN_NOSHOW): 전원 미참여 → 다음 라운드 재소집
|
-- ⑤ 미참여 재소집(REGEN_NOSHOW): 전원 미참여 → 다음 라운드 재소집
|
||||||
('aaaa0005-0000-0000-0000-000000000005','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
('aaaa0005-0000-0000-0000-000000000005','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||||
'⑤ 미응찰 개찰 데모','EST-DEMO-05',1,1,3,
|
'⑤ 미응찰 개찰 데모','EST-DEMO-05',1,1,3,
|
||||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','전원 미참여·다음 라운드 재소집 케이스',
|
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','전원 미참여·다음 라운드 재소집 케이스',
|
||||||
1, false, null, null, false, null,
|
1, false, null, null, false, null,
|
||||||
7, 400000, 1, now(), now(), false),
|
7, 400000, now(), now(), false),
|
||||||
-- ⑥ 진행중: 일부 투찰 완료, 아직 안 닫힘 (close_reason NULL)
|
-- ⑥ 진행중: 일부 투찰 완료, 아직 안 닫힘 (close_reason NULL)
|
||||||
('aaaa0006-0000-0000-0000-000000000006','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
('aaaa0006-0000-0000-0000-000000000006','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||||
'⑥ 진행중 데모','EST-DEMO-06',4,1,2,
|
'⑥ 진행중 데모','EST-DEMO-06',4,1,2,
|
||||||
now()-interval '1 day', now()+interval '1 day','김담당','mgr@imk.kr','010-1111-1111','협상 진행중·현재 최저 투찰 케이스',
|
now()-interval '1 day', now()+interval '1 day','김담당','mgr@imk.kr','010-1111-1111','협상 진행중·현재 최저 투찰 케이스',
|
||||||
1, null, null, null, null, null,
|
1, null, null, null, null, null,
|
||||||
null, 400000, 1, now(), now(), false),
|
null, 400000, now(), now(), false),
|
||||||
-- ⑦ 가격 재협상(REGEN_PRICE): 단독 최저가 420,000 > 목표 350,000 → 재협상 진행
|
-- ⑦ 가격 재협상(REGEN_PRICE): 단독 최저가 420,000 > 목표 350,000 → 재협상 진행
|
||||||
('aaaa0007-0000-0000-0000-000000000007','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
('aaaa0007-0000-0000-0000-000000000007','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||||
'⑦ 목표초과 개찰 데모','EST-DEMO-07',4,1,3,
|
'⑦ 목표초과 개찰 데모','EST-DEMO-07',4,1,3,
|
||||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','목표 초과 → 재협상(더 깎기) 진행 케이스',
|
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','목표 초과 → 재협상(더 깎기) 진행 케이스',
|
||||||
1, false, null, null, false, null,
|
1, false, null, null, false, null,
|
||||||
5, 350000, 1, now(), now(), false),
|
5, 350000, now(), now(), false),
|
||||||
-- ⑧ 가격 유찰(FAIL_PRICE): 단독 최저가 430,000 > 목표 350,000, over_action=유찰(또는 한도소진) → 유찰
|
-- ⑧ 가격 유찰(FAIL_PRICE): 단독 최저가 430,000 > 목표 350,000, over_action=유찰(또는 한도소진) → 유찰
|
||||||
('aaaa0008-0000-0000-0000-000000000008','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
('aaaa0008-0000-0000-0000-000000000008','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||||
'⑧ 목표초과 개찰 데모(2)','EST-DEMO-08',4,1,3,
|
'⑧ 목표초과 개찰 데모(2)','EST-DEMO-08',4,1,3,
|
||||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','목표 초과 → 유찰 케이스',
|
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','목표 초과 → 유찰 케이스',
|
||||||
1, false, null, null, false, null,
|
1, false, null, null, false, null,
|
||||||
5, 350000, 1, now(), now(), false),
|
5, 350000, now(), now(), false),
|
||||||
-- ⑨ 동가 유찰(FAIL_EQUAL): 동가지만 재입찰 한도 소진/유찰 정책 → 유찰
|
-- ⑨ 동가 유찰(FAIL_EQUAL): 동가지만 재입찰 한도 소진/유찰 정책 → 유찰
|
||||||
('aaaa0009-0000-0000-0000-000000000009','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
('aaaa0009-0000-0000-0000-000000000009','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||||
@@ -100,14 +100,14 @@ VALUES
|
|||||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','동가지만 재입찰 한도 소진 → 유찰 케이스',
|
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','동가지만 재입찰 한도 소진 → 유찰 케이스',
|
||||||
1, false, null, null, true,
|
1, false, null, null, true,
|
||||||
'[{"supplier_id":"9795c2e5-3ac2-4e44-aeb5-c6c5e3053f09","supplier_name":"(주)대한정밀","bid_price":405000},{"supplier_id":"69e7057a-5919-48cd-b329-13b833bff994","supplier_name":"서울산업소재(주)","bid_price":405000}]'::jsonb,
|
'[{"supplier_id":"9795c2e5-3ac2-4e44-aeb5-c6c5e3053f09","supplier_name":"(주)대한정밀","bid_price":405000},{"supplier_id":"69e7057a-5919-48cd-b329-13b833bff994","supplier_name":"서울산업소재(주)","bid_price":405000}]'::jsonb,
|
||||||
6, 400000, 1, now(), now(), false),
|
6, 400000, now(), now(), false),
|
||||||
-- ⑩ 미참여 유찰(FAIL_NOSHOW): 전원 미참여 + 재소집 한도 소진 → 유찰
|
-- ⑩ 미참여 유찰(FAIL_NOSHOW): 전원 미참여 + 재소집 한도 소진 → 유찰
|
||||||
('aaaa0010-0000-0000-0000-000000000010','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
('aaaa0010-0000-0000-0000-000000000010','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||||
'⑩ 미응찰 개찰 데모(2)','EST-DEMO-10',1,2,3,
|
'⑩ 미응찰 개찰 데모(2)','EST-DEMO-10',1,2,3,
|
||||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','전원 미참여 + 재소집 한도 소진 → 유찰 케이스',
|
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','전원 미참여 + 재소집 한도 소진 → 유찰 케이스',
|
||||||
1, false, null, null, false, null,
|
1, false, null, null, false, null,
|
||||||
7, 400000, 1, now(), now(), false);
|
7, 400000, now(), now(), false);
|
||||||
|
|
||||||
-- ── 세션 ────────────────────────────────────────────────────────────────
|
-- ── 세션 ────────────────────────────────────────────────────────────────
|
||||||
-- 공통: item=a3d1fff5, DeliveryType 협력사배송=1
|
-- 공통: item=a3d1fff5, DeliveryType 협력사배송=1
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""협상 agent 카탈로그 변경 알림 (best-effort).
|
||||||
|
|
||||||
|
공용 협상카드(card.nego_cards, user_id NULL)는 agent 의 action space(Q-table action 축)를 정의한다.
|
||||||
|
negodata 에서 공용 카드를 추가/삭제/번호변경하면 agent 의 캐시된 엔진을 무효화해 최신 카탈로그로
|
||||||
|
재조립되게 알린다. 실패해도 카드 작업 자체는 성공으로 둔다 — agent 는 TTL/다음 재조립으로 결국 반영된다.
|
||||||
|
|
||||||
|
개인(회사) 카드나 와일드카드는 action space 를 바꾸지 않으므로 알리지 않는다(호출부에서 판정).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from common.logger import LOG
|
||||||
|
from config.server_configs import web_server_config
|
||||||
|
|
||||||
|
|
||||||
|
async def notify_catalog_changed() -> None:
|
||||||
|
if getattr(web_server_config, "is_test", False):
|
||||||
|
return # 테스트 환경에선 외부 호출 안 함
|
||||||
|
base = (getattr(web_server_config, "agent_base_url", "") or "").rstrip("/")
|
||||||
|
if not base:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=3.0) as cli:
|
||||||
|
await cli.post(f"{base}/v1/catalog-refresh-all")
|
||||||
|
except Exception as ex: # 알림 실패는 카드 작업을 막지 않는다
|
||||||
|
LOG.w(f"[agent_notify] 공용 카탈로그 변경 알림 실패(무시): {ex}")
|
||||||
@@ -7,6 +7,7 @@ from common.database.model.models import nego_cards, wild_cards
|
|||||||
from common.enums import CardStatus, DBWRType, ErrorType
|
from common.enums import CardStatus, DBWRType, ErrorType
|
||||||
from common.models.gmodel import PageParams
|
from common.models.gmodel import PageParams
|
||||||
from crud.card_crud import ICardCRUD, CardCRUD
|
from crud.card_crud import ICardCRUD, CardCRUD
|
||||||
|
from services.agent_notify import notify_catalog_changed
|
||||||
from router.v1.card.protocol import CardData, Req_CreateCard, Req_UpdateCard, Res_Card, Res_CardList, Res_DeleteCard
|
from router.v1.card.protocol import CardData, Req_CreateCard, Req_UpdateCard, Res_Card, Res_CardList, Res_DeleteCard
|
||||||
|
|
||||||
|
|
||||||
@@ -25,6 +26,7 @@ class CardService:
|
|||||||
nego_card_id=row.nego_card_id,
|
nego_card_id=row.nego_card_id,
|
||||||
user_id=row.user_id,
|
user_id=row.user_id,
|
||||||
is_wildcard=False,
|
is_wildcard=False,
|
||||||
|
is_shared=row.user_id is None,
|
||||||
name=row.name,
|
name=row.name,
|
||||||
number=row.number,
|
number=row.number,
|
||||||
script=row.script,
|
script=row.script,
|
||||||
@@ -42,6 +44,7 @@ class CardService:
|
|||||||
nego_card_id=row.wild_card_id,
|
nego_card_id=row.wild_card_id,
|
||||||
user_id=row.user_id,
|
user_id=row.user_id,
|
||||||
is_wildcard=True,
|
is_wildcard=True,
|
||||||
|
is_shared=row.user_id is None,
|
||||||
name=row.name,
|
name=row.name,
|
||||||
number=row.number,
|
number=row.number,
|
||||||
script=row.script,
|
script=row.script,
|
||||||
@@ -56,7 +59,8 @@ class CardService:
|
|||||||
|
|
||||||
# ---- 소유 카드 탐색(어느 테이블인지 모를 때) ------------------------------
|
# ---- 소유 카드 탐색(어느 테이블인지 모를 때) ------------------------------
|
||||||
async def _find_owned(self, user_uuid: uuid.UUID, card_id: uuid.UUID):
|
async def _find_owned(self, user_uuid: uuid.UUID, card_id: uuid.UUID):
|
||||||
"""card_id 를 nego_cards → wild_cards 순으로 찾고 소유권 확인.
|
"""card_id 를 nego_cards → wild_cards 순으로 찾고 접근권 확인.
|
||||||
|
전체(공용, user_id NULL) 카드는 누구나 조회·수정·삭제 가능. 개인 카드는 소유자만.
|
||||||
(ErrorType, model, pk_col, row, is_wildcard) 반환."""
|
(ErrorType, model, pk_col, row, is_wildcard) 반환."""
|
||||||
err, row = await DB_SESSION_MNG.execute_lambda(
|
err, row = await DB_SESSION_MNG.execute_lambda(
|
||||||
nego_cards.DBType(),
|
nego_cards.DBType(),
|
||||||
@@ -64,7 +68,7 @@ class CardService:
|
|||||||
lambda s: self.card_crud.get_by_id(s, nego_cards, nego_cards.nego_card_id, card_id),
|
lambda s: self.card_crud.get_by_id(s, nego_cards, nego_cards.nego_card_id, card_id),
|
||||||
)
|
)
|
||||||
if err == ErrorType.SUCCESS and row is not None:
|
if err == ErrorType.SUCCESS and row is not None:
|
||||||
if row.user_id != user_uuid:
|
if row.user_id is not None and row.user_id != user_uuid:
|
||||||
return ErrorType.CARD_NOT_FOUND, None, None, None, False
|
return ErrorType.CARD_NOT_FOUND, None, None, None, False
|
||||||
return ErrorType.SUCCESS, nego_cards, nego_cards.nego_card_id, row, False
|
return ErrorType.SUCCESS, nego_cards, nego_cards.nego_card_id, row, False
|
||||||
|
|
||||||
@@ -74,7 +78,7 @@ class CardService:
|
|||||||
lambda s: self.card_crud.get_by_id(s, wild_cards, wild_cards.wild_card_id, card_id),
|
lambda s: self.card_crud.get_by_id(s, wild_cards, wild_cards.wild_card_id, card_id),
|
||||||
)
|
)
|
||||||
if err == ErrorType.SUCCESS and row is not None:
|
if err == ErrorType.SUCCESS and row is not None:
|
||||||
if row.user_id != user_uuid:
|
if row.user_id is not None and row.user_id != user_uuid:
|
||||||
return ErrorType.CARD_NOT_FOUND, None, None, None, True
|
return ErrorType.CARD_NOT_FOUND, None, None, None, True
|
||||||
return ErrorType.SUCCESS, wild_cards, wild_cards.wild_card_id, row, True
|
return ErrorType.SUCCESS, wild_cards, wild_cards.wild_card_id, row, True
|
||||||
|
|
||||||
@@ -114,7 +118,21 @@ class CardService:
|
|||||||
|
|
||||||
merged = [self._nego_to_data(r) for r in nego_rows] + [self._wild_to_data(r) for r in wild_rows]
|
merged = [self._nego_to_data(r) for r in nego_rows] + [self._wild_to_data(r) for r in wild_rows]
|
||||||
merged.sort(key=lambda c: c.created_at or "", reverse=True)
|
merged.sort(key=lambda c: c.created_at or "", reverse=True)
|
||||||
res.cards = merged[pg.skip : pg.skip + pg.size]
|
page = merged[pg.skip : pg.skip + pg.size]
|
||||||
|
|
||||||
|
# 작성자명 배치 조인 — 페이지 카드의 작성자 id를 모아 IN 쿼리 1회로 {id:name} 맵을 만들어 매핑.
|
||||||
|
# (공용 카드는 user_id=NULL → 맵에 없어 creator_name=None). 행마다 조회하지 않으므로 부하 없음.
|
||||||
|
author_ids = list({c.user_id for c in page if c.user_id is not None})
|
||||||
|
if author_ids:
|
||||||
|
nm_err, name_map = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
nego_cards.DBType(),
|
||||||
|
DBWRType.DB_READ.value,
|
||||||
|
lambda s: self.card_crud.user_name_map(s, author_ids),
|
||||||
|
)
|
||||||
|
if nm_err == ErrorType.SUCCESS:
|
||||||
|
for c in page:
|
||||||
|
c.creator_name = name_map.get(c.user_id)
|
||||||
|
res.cards = page
|
||||||
res.total_nego = total_n
|
res.total_nego = total_n
|
||||||
res.total_wild = total_w
|
res.total_wild = total_w
|
||||||
# 선택된 탭 기준 페이지네이션 총건수(전체=합산).
|
# 선택된 탭 기준 페이지네이션 총건수(전체=합산).
|
||||||
@@ -134,6 +152,14 @@ class CardService:
|
|||||||
res.result.SetResult(err)
|
res.result.SetResult(err)
|
||||||
return res
|
return res
|
||||||
res.card = self._wild_to_data(row) if is_wild else self._nego_to_data(row)
|
res.card = self._wild_to_data(row) if is_wild else self._nego_to_data(row)
|
||||||
|
# 등록자명 — 공용(user_id NULL) 카드는 작성자 없음(None 유지).
|
||||||
|
if row.user_id is not None:
|
||||||
|
nm_err, name_map = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
nego_cards.DBType(), DBWRType.DB_READ.value,
|
||||||
|
lambda s: self.card_crud.user_name_map(s, [row.user_id]),
|
||||||
|
)
|
||||||
|
if nm_err == ErrorType.SUCCESS:
|
||||||
|
res.card.creator_name = name_map.get(row.user_id)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
# ---- 등록 ----------------------------------------------------------------
|
# ---- 등록 ----------------------------------------------------------------
|
||||||
@@ -141,9 +167,11 @@ class CardService:
|
|||||||
res = Res_Card()
|
res = Res_Card()
|
||||||
user_uuid = uuid.UUID(user_id)
|
user_uuid = uuid.UUID(user_id)
|
||||||
is_wildcard = req.is_wildcard
|
is_wildcard = req.is_wildcard
|
||||||
|
# 전체(공용) 카드는 소유자 없이 저장(user_id NULL) → 모든 유저 목록에 노출.
|
||||||
|
owner_id = None if req.is_shared else user_uuid
|
||||||
|
|
||||||
common = dict(
|
common = dict(
|
||||||
user_id=user_uuid,
|
user_id=owner_id,
|
||||||
name=req.name,
|
name=req.name,
|
||||||
number=req.number,
|
number=req.number,
|
||||||
script=req.script,
|
script=req.script,
|
||||||
@@ -169,6 +197,9 @@ class CardService:
|
|||||||
if err != ErrorType.SUCCESS:
|
if err != ErrorType.SUCCESS:
|
||||||
res.result.SetResult(err)
|
res.result.SetResult(err)
|
||||||
return res
|
return res
|
||||||
|
# 공용 일반카드는 agent action space 를 정의 → 변경 알림(전역 엔진 재조립). 개인/와일드는 미해당.
|
||||||
|
if req.is_shared and not is_wildcard:
|
||||||
|
await notify_catalog_changed()
|
||||||
# 서버 기본값(created_at 등)은 insert 후 객체에 실리지 않으므로 재조회.
|
# 서버 기본값(created_at 등)은 insert 후 객체에 실리지 않으므로 재조회.
|
||||||
return await self.get_card(user_id, str(getattr(card, pk_attr)))
|
return await self.get_card(user_id, str(getattr(card, pk_attr)))
|
||||||
|
|
||||||
@@ -183,6 +214,7 @@ class CardService:
|
|||||||
if err != ErrorType.SUCCESS:
|
if err != ErrorType.SUCCESS:
|
||||||
res.result.SetResult(err)
|
res.result.SetResult(err)
|
||||||
return res
|
return res
|
||||||
|
was_shared_nego = _row.user_id is None and not is_wild
|
||||||
|
|
||||||
# 해당 테이블에 있는 컬럼만 추린다(없는 필드는 무시). status → available(와일드 전용).
|
# 해당 테이블에 있는 컬럼만 추린다(없는 필드는 무시). status → available(와일드 전용).
|
||||||
allowed = {"name", "number", "script", "edit_script", "usage_type"}
|
allowed = {"name", "number", "script", "edit_script", "usage_type"}
|
||||||
@@ -199,6 +231,9 @@ class CardService:
|
|||||||
if err != ErrorType.SUCCESS:
|
if err != ErrorType.SUCCESS:
|
||||||
res.result.SetResult(err)
|
res.result.SetResult(err)
|
||||||
return res
|
return res
|
||||||
|
# 공용 일반카드 변경(번호/개수 등)은 action space 에 영향 → 알림.
|
||||||
|
if was_shared_nego:
|
||||||
|
await notify_catalog_changed()
|
||||||
return await self.get_card(user_id, card_id)
|
return await self.get_card(user_id, card_id)
|
||||||
|
|
||||||
# ---- 삭제(soft) ----------------------------------------------------------
|
# ---- 삭제(soft) ----------------------------------------------------------
|
||||||
@@ -211,6 +246,7 @@ class CardService:
|
|||||||
if err != ErrorType.SUCCESS:
|
if err != ErrorType.SUCCESS:
|
||||||
res.result.SetResult(err)
|
res.result.SetResult(err)
|
||||||
return res
|
return res
|
||||||
|
was_shared_nego = _row.user_id is None and not _is_wild
|
||||||
|
|
||||||
err = await DB_SESSION_MNG.execute_lambda_run(
|
err = await DB_SESSION_MNG.execute_lambda_run(
|
||||||
[model.DBType()],
|
[model.DBType()],
|
||||||
@@ -218,4 +254,8 @@ class CardService:
|
|||||||
)
|
)
|
||||||
if err != ErrorType.SUCCESS:
|
if err != ErrorType.SUCCESS:
|
||||||
res.result.SetResult(err)
|
res.result.SetResult(err)
|
||||||
|
return res
|
||||||
|
# 공용 일반카드 삭제는 카탈로그 수 변경 → 알림.
|
||||||
|
if was_shared_nego:
|
||||||
|
await notify_catalog_changed()
|
||||||
return res
|
return res
|
||||||
@@ -2,6 +2,7 @@ import uuid
|
|||||||
|
|
||||||
from fastapi import Depends, UploadFile
|
from fastapi import Depends, UploadFile
|
||||||
|
|
||||||
|
from common.authz import is_owner_or_admin
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import items
|
from common.database.model.models import items
|
||||||
from common.enums import DBWRType, ErrorType
|
from common.enums import DBWRType, ErrorType
|
||||||
@@ -56,6 +57,16 @@ class ItemService:
|
|||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
return res
|
return res
|
||||||
res.items = [ItemData.model_validate(r) for r in rows]
|
res.items = [ItemData.model_validate(r) for r in rows]
|
||||||
|
# 등록자명 배치 조인 — 페이지 상품의 user_id를 모아 IN 쿼리 1회로 {id:name} 맵을 만들어 매핑(행별 조회 아님).
|
||||||
|
author_ids = list({r.user_id for r in rows if r.user_id is not None})
|
||||||
|
if author_ids:
|
||||||
|
nm_err, name_map = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
items.DBType(), DBWRType.DB_READ.value,
|
||||||
|
lambda s: self.item_crud.user_name_map(s, author_ids),
|
||||||
|
)
|
||||||
|
if nm_err == ErrorType.SUCCESS:
|
||||||
|
for d in res.items:
|
||||||
|
d.creator_name = name_map.get(d.user_id)
|
||||||
res.total = total
|
res.total = total
|
||||||
return res
|
return res
|
||||||
|
|
||||||
@@ -81,6 +92,13 @@ class ItemService:
|
|||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
return res
|
return res
|
||||||
res.item = ItemData.model_validate(item)
|
res.item = ItemData.model_validate(item)
|
||||||
|
if item.user_id is not None:
|
||||||
|
nm_err, name_map = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
items.DBType(), DBWRType.DB_READ.value,
|
||||||
|
lambda s: self.item_crud.user_name_map(s, [item.user_id]),
|
||||||
|
)
|
||||||
|
if nm_err == ErrorType.SUCCESS:
|
||||||
|
res.item.creator_name = name_map.get(item.user_id)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
async def check_codes(self, company_id: str, codes: list) -> Res_CheckCodes:
|
async def check_codes(self, company_id: str, codes: list) -> Res_CheckCodes:
|
||||||
@@ -128,17 +146,22 @@ class ItemService:
|
|||||||
# 서버 기본값(created_at/updated_at)은 insert 후 Python 객체에 실리지 않으므로 재조회한다.
|
# 서버 기본값(created_at/updated_at)은 insert 후 Python 객체에 실리지 않으므로 재조회한다.
|
||||||
return await self.get_item(company_id, str(item.item_id))
|
return await self.get_item(company_id, str(item.item_id))
|
||||||
|
|
||||||
async def update_item(self, company_id: str, item_id: str, req: Req_UpdateItem) -> Res_Item:
|
async def update_item(self, company_id: str, item_id: str, req: Req_UpdateItem, user_id=None, role=None) -> Res_Item:
|
||||||
res = Res_Item()
|
res = Res_Item()
|
||||||
company_uuid = uuid.UUID(company_id)
|
company_uuid = uuid.UUID(company_id)
|
||||||
item_uuid = uuid.UUID(item_id)
|
item_uuid = uuid.UUID(item_id)
|
||||||
data = req.model_dump(exclude_unset=True)
|
data = req.model_dump(exclude_unset=True)
|
||||||
|
|
||||||
# 소유권 확인
|
# 회사 스코프 확인
|
||||||
err_type, _ = await self._fetch_owned(company_uuid, item_uuid)
|
err_type, item = await self._fetch_owned(company_uuid, item_uuid)
|
||||||
if err_type != ErrorType.SUCCESS:
|
if err_type != ErrorType.SUCCESS or item is None:
|
||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
return res
|
return res
|
||||||
|
# 소유자 게이팅 — 본인이 등록한 상품 또는 최고관리자만 수정(user_id 미지정=내부 호출은 스킵).
|
||||||
|
if user_id is not None and not is_owner_or_admin(item.user_id, user_id, role):
|
||||||
|
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||||
|
res.msg = "본인이 등록한 상품만 수정할 수 있습니다."
|
||||||
|
return res
|
||||||
|
|
||||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||||
[items.DBType()],
|
[items.DBType()],
|
||||||
@@ -151,15 +174,20 @@ class ItemService:
|
|||||||
# 갱신 후 재조회
|
# 갱신 후 재조회
|
||||||
return await self.get_item(company_id, item_id)
|
return await self.get_item(company_id, item_id)
|
||||||
|
|
||||||
async def delete_item(self, company_id: str, item_id: str) -> Res_DeleteItem:
|
async def delete_item(self, company_id: str, item_id: str, user_id=None, role=None) -> Res_DeleteItem:
|
||||||
res = Res_DeleteItem()
|
res = Res_DeleteItem()
|
||||||
company_uuid = uuid.UUID(company_id)
|
company_uuid = uuid.UUID(company_id)
|
||||||
item_uuid = uuid.UUID(item_id)
|
item_uuid = uuid.UUID(item_id)
|
||||||
|
|
||||||
err_type, _ = await self._fetch_owned(company_uuid, item_uuid)
|
err_type, item = await self._fetch_owned(company_uuid, item_uuid)
|
||||||
if err_type != ErrorType.SUCCESS:
|
if err_type != ErrorType.SUCCESS or item is None:
|
||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
return res
|
return res
|
||||||
|
# 소유자 게이팅 — 본인이 등록한 상품 또는 최고관리자만 삭제(user_id 미지정=내부 호출은 스킵).
|
||||||
|
if user_id is not None and not is_owner_or_admin(item.user_id, user_id, role):
|
||||||
|
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||||
|
res.msg = "본인이 등록한 상품만 삭제할 수 있습니다."
|
||||||
|
return res
|
||||||
|
|
||||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||||
[items.DBType()],
|
[items.DBType()],
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from common.anchoring import (
|
|||||||
fetch_current_values,
|
fetch_current_values,
|
||||||
get_base_anchoring_value,
|
get_base_anchoring_value,
|
||||||
)
|
)
|
||||||
|
from common.authz import is_owner_or_admin
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
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
|
from common.database.model.models import quotations, sessions, chats, versions, version_nego_cards, version_wild_cards
|
||||||
from common.enums import CloseOutcome, CloseReason, DBWRType, ErrorType, NotificationType, PriceGateAction, QuotationStatus, QuotationType, SessionStatus
|
from common.enums import CloseOutcome, CloseReason, DBWRType, ErrorType, NotificationType, PriceGateAction, QuotationStatus, QuotationType, SessionStatus
|
||||||
@@ -28,7 +29,6 @@ from router.v1.quotation.protocol import (
|
|||||||
Req_CreateQuotation,
|
Req_CreateQuotation,
|
||||||
Res_CreateQuotation,
|
Res_CreateQuotation,
|
||||||
Res_DeleteQuotation,
|
Res_DeleteQuotation,
|
||||||
Res_LastSupplierType,
|
|
||||||
Res_NotifySessions,
|
Res_NotifySessions,
|
||||||
Res_Quotation,
|
Res_Quotation,
|
||||||
Res_QuotationCards,
|
Res_QuotationCards,
|
||||||
@@ -254,22 +254,6 @@ class QuotationService:
|
|||||||
res.quotation = QuotationData.model_validate(quotation)
|
res.quotation = QuotationData.model_validate(quotation)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
async def get_last_supplier_type(self, supplier_id: str, company_id=None) -> Res_LastSupplierType:
|
|
||||||
"""협력사의 직전 견적 supplier_type(견적생성 모달 프리필용). 이력 없으면 비워서 반환."""
|
|
||||||
res = Res_LastSupplierType()
|
|
||||||
err_type, got = await DB_SESSION_MNG.execute_lambda(
|
|
||||||
quotations.DBType(),
|
|
||||||
DBWRType.DB_READ.value,
|
|
||||||
lambda s: self.quotation_crud.get_last_supplier_type(s, uuid.UUID(supplier_id), company_id),
|
|
||||||
)
|
|
||||||
if err_type != ErrorType.SUCCESS:
|
|
||||||
res.result.SetResult(err_type)
|
|
||||||
return res
|
|
||||||
if got:
|
|
||||||
res.supplier_type = got[0]
|
|
||||||
res.qt_number = got[1]
|
|
||||||
return res
|
|
||||||
|
|
||||||
async def create_quotation(self, user_id: str, req: Req_CreateQuotation) -> Res_CreateQuotation:
|
async def create_quotation(self, user_id: str, req: Req_CreateQuotation) -> Res_CreateQuotation:
|
||||||
"""[프론트] 신규 견적 생성. 요청값을 보정한 뒤 공통 빌더(_build_quotation)에 위임한다.
|
"""[프론트] 신규 견적 생성. 요청값을 보정한 뒤 공통 빌더(_build_quotation)에 위임한다.
|
||||||
생성 성공 시 작성자에게 CREATED 알림(인박스)."""
|
생성 성공 시 작성자에게 CREATED 알림(인박스)."""
|
||||||
@@ -290,7 +274,6 @@ class QuotationService:
|
|||||||
manager_contact_number=req.manager_contact_number,
|
manager_contact_number=req.manager_contact_number,
|
||||||
memo=req.memo,
|
memo=req.memo,
|
||||||
md_price=req.md_price,
|
md_price=req.md_price,
|
||||||
supplier_type=req.supplier_type,
|
|
||||||
item_ids=req.item_ids,
|
item_ids=req.item_ids,
|
||||||
supplier_ids=req.supplier_ids,
|
supplier_ids=req.supplier_ids,
|
||||||
card_ids=req.card_ids,
|
card_ids=req.card_ids,
|
||||||
@@ -369,7 +352,6 @@ class QuotationService:
|
|||||||
manager_contact_number=original.manager_contact_number,
|
manager_contact_number=original.manager_contact_number,
|
||||||
memo=original.memo,
|
memo=original.memo,
|
||||||
md_price=original.md_price,
|
md_price=original.md_price,
|
||||||
supplier_type=original.supplier_type,
|
|
||||||
item_ids=item_ids,
|
item_ids=item_ids,
|
||||||
supplier_ids=list(supplier_ids),
|
supplier_ids=list(supplier_ids),
|
||||||
card_ids=[], # 새 버전 안 만듦(원본 version_id 재사용)
|
card_ids=[], # 새 버전 안 만듦(원본 version_id 재사용)
|
||||||
@@ -382,7 +364,7 @@ class QuotationService:
|
|||||||
self, *,
|
self, *,
|
||||||
user_id: str, qt_setting_id, version_id, name: str, number: str,
|
user_id: str, qt_setting_id, version_id, name: str, number: str,
|
||||||
type_: int, status: int, round_: int, start_time, end_time,
|
type_: int, status: int, round_: int, start_time, end_time,
|
||||||
manager_name, manager_email, manager_contact_number, memo, md_price, supplier_type,
|
manager_name, manager_email, manager_contact_number, memo, md_price,
|
||||||
item_ids: list, supplier_ids: list, card_ids: list,
|
item_ids: list, supplier_ids: list, card_ids: list,
|
||||||
mid_action: Optional[int] = None, # 낙찰 기준(견적 단위). 앵커링가<투찰가≤목표가 처리(AWARD/OPEN)
|
mid_action: Optional[int] = None, # 낙찰 기준(견적 단위). 앵커링가<투찰가≤목표가 처리(AWARD/OPEN)
|
||||||
over_action: Optional[int] = None, # 목표가<투찰가 처리(1:1 협상은 항상 OPEN)
|
over_action: Optional[int] = None, # 목표가<투찰가 처리(1:1 협상은 항상 OPEN)
|
||||||
@@ -417,7 +399,7 @@ class QuotationService:
|
|||||||
fee = self.INTERNET_AVERAGE_FEE # 인터넷가 차감 수수료율(상수)
|
fee = self.INTERNET_AVERAGE_FEE # 인터넷가 차감 수수료율(상수)
|
||||||
margin = rates.get("margin") or 0.0 # 판매가 차감 목표마진율
|
margin = rates.get("margin") or 0.0 # 판매가 차감 목표마진율
|
||||||
# 앵커링가는 quotation_settings.anchoring_value(구 float 비율)를 더 이상 쓰지 않는다(앵커링 v1.2) —
|
# 앵커링가는 quotation_settings.anchoring_value(구 float 비율)를 더 이상 쓰지 않는다(앵커링 v1.2) —
|
||||||
# 칸(회사×협력사유형×가격구간)별 조정 anchoring_value(정수 ‰)로 계산한다. 아래 세션 생성부 ②.
|
# 칸(회사×상품-협력사 공급유형×가격구간)별 조정 anchoring_value(정수 ‰)로 계산한다. 아래 세션 생성부 ②.
|
||||||
|
|
||||||
# 선택 협상카드가 있으면 새 버전을 만들어 카드들을 묶고, quotation.version_id 로 연결한다.
|
# 선택 협상카드가 있으면 새 버전을 만들어 카드들을 묶고, quotation.version_id 로 연결한다.
|
||||||
# (quotation↔card 는 version → version_nego_cards/version_wild_cards 로 연결.)
|
# (quotation↔card 는 version → version_nego_cards/version_wild_cards 로 연결.)
|
||||||
@@ -464,7 +446,6 @@ class QuotationService:
|
|||||||
manager_contact_number=manager_contact_number,
|
manager_contact_number=manager_contact_number,
|
||||||
memo=memo,
|
memo=memo,
|
||||||
md_price=md_price,
|
md_price=md_price,
|
||||||
supplier_type=supplier_type,
|
|
||||||
mid_action=mid_action,
|
mid_action=mid_action,
|
||||||
over_action=over_action,
|
over_action=over_action,
|
||||||
)
|
)
|
||||||
@@ -490,8 +471,8 @@ class QuotationService:
|
|||||||
res.result.SetResult(ErrorType.QUOTATION_TARGET_PRICE_UNAVAILABLE)
|
res.result.SetResult(ErrorType.QUOTATION_TARGET_PRICE_UNAVAILABLE)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
# ② 앵커가 산출 — 칸(items.company_id × quotations.supplier_type × 목표가 구간) anchoring_value 조회 후
|
# ② 앵커가 산출 — 칸(items.company_id × supplier_items.supply_type × 목표가 구간) anchoring_value 조회 후
|
||||||
# 정수 연산으로 박제(앵커링 v1.2, 인수인계.md §1.3). 유형 미지정/조정 이력 없음/조회 실패는
|
# 정수 연산으로 박제(앵커링 v1.2, 인수인계.md §1.3). 매핑 미지정/조정 이력 없음/조회 실패는
|
||||||
# 정적 테이블 시작값 폴백 — 값 조회 때문에 견적 생성이 실패하지 않는다(규칙 6).
|
# 정적 테이블 시작값 폴백 — 값 조회 때문에 견적 생성이 실패하지 않는다(규칙 6).
|
||||||
_err, item_companies = await DB_SESSION_MNG.execute_lambda(
|
_err, item_companies = await DB_SESSION_MNG.execute_lambda(
|
||||||
quotations.DBType(),
|
quotations.DBType(),
|
||||||
@@ -499,12 +480,19 @@ class QuotationService:
|
|||||||
lambda s: self.quotation_crud.get_item_companies(s, item_ids),
|
lambda s: self.quotation_crud.get_item_companies(s, item_ids),
|
||||||
)
|
)
|
||||||
item_companies = item_companies if _err == ErrorType.SUCCESS else {}
|
item_companies = item_companies if _err == ErrorType.SUCCESS else {}
|
||||||
|
_err, supply_types = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
quotations.DBType(),
|
||||||
|
DBWRType.DB_READ.value,
|
||||||
|
lambda s: self.quotation_crud.get_supply_types(s, item_ids, supplier_ids),
|
||||||
|
)
|
||||||
|
supply_types = supply_types if _err == ErrorType.SUCCESS else {}
|
||||||
value_map = {}
|
value_map = {}
|
||||||
if supplier_type in SAMPLEABLE_SUPPLIER_TYPES and item_companies:
|
sampleable_supply_types = sorted({t for t in supply_types.values() if t in SAMPLEABLE_SUPPLIER_TYPES})
|
||||||
|
if sampleable_supply_types and item_companies:
|
||||||
value_map = await DB_SESSION_MNG.execute_lambda(
|
value_map = await DB_SESSION_MNG.execute_lambda(
|
||||||
quotations.DBType(),
|
quotations.DBType(),
|
||||||
DBWRType.DB_READ.value,
|
DBWRType.DB_READ.value,
|
||||||
lambda s: fetch_current_values(s, list(set(item_companies.values())), supplier_type),
|
lambda s: fetch_current_values(s, list(set(item_companies.values())), sampleable_supply_types),
|
||||||
)
|
)
|
||||||
|
|
||||||
session_objs = []
|
session_objs = []
|
||||||
@@ -512,11 +500,12 @@ class QuotationService:
|
|||||||
tp = target_prices[iid]
|
tp = target_prices[iid]
|
||||||
price_range = calc_price_range_index(tp)
|
price_range = calc_price_range_index(tp)
|
||||||
company = item_companies.get(iid)
|
company = item_companies.get(iid)
|
||||||
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:
|
for sid in supplier_ids:
|
||||||
|
supply_type = supply_types.get((iid, sid))
|
||||||
|
value = value_map.get((company, supply_type, 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원 내림 정확성)
|
||||||
session_objs.append(
|
session_objs.append(
|
||||||
sessions(
|
sessions(
|
||||||
session_id=uuid.uuid4(),
|
session_id=uuid.uuid4(),
|
||||||
@@ -678,7 +667,7 @@ class QuotationService:
|
|||||||
# 4) 전원 미응찰 → 개찰(미응찰).
|
# 4) 전원 미응찰 → 개찰(미응찰).
|
||||||
return await self._open(qt_uuid, original, CloseReason.OPEN_NOSHOW.value, "no_show")
|
return await self._open(qt_uuid, original, CloseReason.OPEN_NOSHOW.value, "no_show")
|
||||||
|
|
||||||
async def regenerate_quotation(self, qt_id: str, company_id, supplier_ids: list) -> Res_CreateQuotation:
|
async def regenerate_quotation(self, qt_id: str, company_id, supplier_ids: list, user_id=None, role=None) -> Res_CreateQuotation:
|
||||||
"""[프론트] 마감된 견적을 골라 수동으로 다음 라운드를 생성한다.
|
"""[프론트] 마감된 견적을 골라 수동으로 다음 라운드를 생성한다.
|
||||||
크론/수동마감의 자동 재생성과 달리 사유·체인 한도 판정 없이, 프론트가 고른 공급사로 바로 만든다.
|
크론/수동마감의 자동 재생성과 달리 사유·체인 한도 판정 없이, 프론트가 고른 공급사로 바로 만든다.
|
||||||
상품·기간·견적번호·카드버전은 원 견적에서 이어받는다(regenerate_next_round)."""
|
상품·기간·견적번호·카드버전은 원 견적에서 이어받는다(regenerate_next_round)."""
|
||||||
@@ -689,6 +678,11 @@ class QuotationService:
|
|||||||
if err_type != ErrorType.SUCCESS or original is None:
|
if err_type != ErrorType.SUCCESS or original is None:
|
||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
return res
|
return res
|
||||||
|
# 소유자 게이팅 — 본인 견적 또는 최고관리자만 재생성(user_id 미지정=내부 호출은 스킵).
|
||||||
|
if user_id is not None and not is_owner_or_admin(original.user_id, user_id, role):
|
||||||
|
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||||
|
res.msg = "본인이 생성한 견적만 재생성할 수 있습니다."
|
||||||
|
return res
|
||||||
# 마감된 견적만 재생성(진행 중인 라운드를 또 찍어 같은 번호가 동시에 살아있는 걸 막는다).
|
# 마감된 견적만 재생성(진행 중인 라운드를 또 찍어 같은 번호가 동시에 살아있는 걸 막는다).
|
||||||
if original.status != QuotationStatus.CLOSED.value:
|
if original.status != QuotationStatus.CLOSED.value:
|
||||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||||
@@ -711,29 +705,106 @@ class QuotationService:
|
|||||||
|
|
||||||
return await self.regenerate_next_round(qt_uuid, supplier_ids)
|
return await self.regenerate_next_round(qt_uuid, supplier_ids)
|
||||||
|
|
||||||
async def stop_quotation(self, qt_id: str, company_id=None) -> Res_Quotation:
|
async def stop_quotation(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_Quotation:
|
||||||
"""[프론트] 수동 견적마감. 크론과 똑같은 마감 판정(close_and_decide)을 탄다
|
"""[프론트] 수동 견적마감. 크론과 똑같은 마감 판정(close_and_decide)을 탄다
|
||||||
(단독낙찰 확정 / 동가·미참여면 다음 라운드 재생성 / 거부·한도면 그냥 마감)."""
|
(단독낙찰 확정 / 동가·미참여면 다음 라운드 재생성 / 거부·한도면 그냥 마감)."""
|
||||||
res = Res_Quotation()
|
res = Res_Quotation()
|
||||||
qt_uuid = uuid.UUID(qt_id)
|
qt_uuid = uuid.UUID(qt_id)
|
||||||
|
|
||||||
# 존재 확인(+회사 가드)
|
# 존재 확인(+회사 가드)
|
||||||
err_type, _ = await self._fetch(qt_uuid, company_id)
|
err_type, original = await self._fetch(qt_uuid, company_id)
|
||||||
if err_type != ErrorType.SUCCESS:
|
if err_type != ErrorType.SUCCESS or original is None:
|
||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
return res
|
return res
|
||||||
|
# 소유자 게이팅 — 본인 견적 또는 최고관리자만 마감(user_id 미지정=내부 호출은 스킵).
|
||||||
|
if user_id is not None and not is_owner_or_admin(original.user_id, user_id, role):
|
||||||
|
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||||
|
res.msg = "본인이 생성한 견적만 마감할 수 있습니다."
|
||||||
|
return res
|
||||||
|
|
||||||
await self.close_and_decide(qt_uuid)
|
await self.close_and_decide(qt_uuid)
|
||||||
return await self.get_quotation(qt_id, company_id)
|
return await self.get_quotation(qt_id, company_id)
|
||||||
|
|
||||||
async def delete_quotation(self, qt_id: str, company_id=None) -> Res_DeleteQuotation:
|
async def award_quotation(self, qt_id: str, company_id, user_id, role, winner_supplier_id) -> Res_Quotation:
|
||||||
|
"""[프론트] 개찰(낙찰자 미정 마감) 견적을 담당자가 직접 낙찰 처리한다.
|
||||||
|
투찰한 협상완료(DONE) 세션 중 고른 협력사를 낙찰자로 박고 close_reason 을 AWARDED 로 바꾼다(직접 낙찰).
|
||||||
|
자동 낙찰(close_and_decide)과 결과 컬럼은 같되, 알림에 manual 플래그로 '직접 낙찰'임을 남긴다.
|
||||||
|
권한: 본인이 생성한 견적만. 단 최고관리자(OWNER)는 회사 내 남의 견적도 낙찰할 수 있다."""
|
||||||
|
res = Res_Quotation()
|
||||||
|
qt_uuid = uuid.UUID(qt_id)
|
||||||
|
sp_uuid = winner_supplier_id if isinstance(winner_supplier_id, uuid.UUID) else uuid.UUID(str(winner_supplier_id))
|
||||||
|
|
||||||
|
# 존재 확인(+회사 가드) — 남의 회사 견적은 NOT_FOUND.
|
||||||
|
err_type, original = await self._fetch(qt_uuid, company_id)
|
||||||
|
if err_type != ErrorType.SUCCESS or original is None:
|
||||||
|
res.result.SetResult(err_type if err_type != ErrorType.SUCCESS else ErrorType.QUOTATION_NOT_FOUND)
|
||||||
|
return res
|
||||||
|
|
||||||
|
# 자기 견적만 직접 낙찰 — 최고관리자(OWNER)만 회사 내 남의 견적도 허용. 되돌릴 수 없는 낙찰이라 백엔드에서 강제한다.
|
||||||
|
if not is_owner_or_admin(original.user_id, user_id, role):
|
||||||
|
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||||
|
res.msg = "본인이 생성한 견적만 낙찰할 수 있습니다."
|
||||||
|
return res
|
||||||
|
|
||||||
|
# 개찰(마감·낙찰자 미정, close_reason ∈ OPEN_*)만 직접 낙찰 대상. 진행중/이미 낙찰은 거부.
|
||||||
|
if original.status != QuotationStatus.CLOSED.value or original.close_reason not in (
|
||||||
|
CloseReason.OPEN_PRICE.value, CloseReason.OPEN_EQUAL.value,
|
||||||
|
CloseReason.OPEN_NOSHOW.value, CloseReason.OPEN_REJECT.value,
|
||||||
|
):
|
||||||
|
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||||
|
res.msg = "개찰(낙찰자 미정) 상태의 견적만 직접 낙찰할 수 있습니다."
|
||||||
|
return res
|
||||||
|
|
||||||
|
# 낙찰 후보 = 투찰한 협상완료(DONE) 세션. close_and_decide 와 같은 조회(list_sessions_status,
|
||||||
|
# 공급사 삭제돼도 포함되는 outerjoin)를 써서 자동낙찰과 후보 집합을 일치시킨다.
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
sessions.DBType(),
|
||||||
|
DBWRType.DB_READ.value,
|
||||||
|
lambda s: self.quotation_crud.list_sessions_status(s, qt_uuid),
|
||||||
|
)
|
||||||
|
rows = rows if err_type == ErrorType.SUCCESS else []
|
||||||
|
winner = next(
|
||||||
|
(r for r in rows
|
||||||
|
if r.status == SessionStatus.DONE.value and r.bid_price is not None and r.supplier_id == sp_uuid),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if winner is None:
|
||||||
|
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||||
|
res.msg = "선택한 협력사는 이 견적의 낙찰 후보(투찰한 협상완료 협력사)가 아닙니다."
|
||||||
|
return res
|
||||||
|
|
||||||
|
# [동시 직접낙찰 가드] 개찰→낙찰 원자 선점. 실제로 전이한 호출자만 통과(재클릭·경합 방어).
|
||||||
|
claim_err, claimed = await DB_SESSION_MNG.execute_lambda_claim(
|
||||||
|
quotations.DBType(),
|
||||||
|
lambda s: self.quotation_crud.claim_for_award(s, qt_uuid, sp_uuid, (winner.name or "")[:20]),
|
||||||
|
)
|
||||||
|
if claim_err != ErrorType.SUCCESS or claimed == 0:
|
||||||
|
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||||
|
res.msg = "이미 낙찰 처리된 견적입니다."
|
||||||
|
return res
|
||||||
|
|
||||||
|
# 작성자 알림 — 자동낙찰과 같은 SUCCESS 코드, manual 플래그로 '직접 낙찰' 구분.
|
||||||
|
await create_notification(
|
||||||
|
original.user_id, NotificationType.SUCCESS,
|
||||||
|
{"qt_name": original.name, "qt_number": original.number,
|
||||||
|
"winner_name": winner.name, "winner_price": winner.bid_price, "manual": True},
|
||||||
|
ref_qt_id=qt_uuid,
|
||||||
|
)
|
||||||
|
return await self.get_quotation(qt_id, company_id)
|
||||||
|
|
||||||
|
async def delete_quotation(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_DeleteQuotation:
|
||||||
res = Res_DeleteQuotation()
|
res = Res_DeleteQuotation()
|
||||||
qt_uuid = uuid.UUID(qt_id)
|
qt_uuid = uuid.UUID(qt_id)
|
||||||
|
|
||||||
err_type, _ = await self._fetch(qt_uuid, company_id)
|
err_type, original = await self._fetch(qt_uuid, company_id)
|
||||||
if err_type != ErrorType.SUCCESS:
|
if err_type != ErrorType.SUCCESS or original is None:
|
||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
return res
|
return res
|
||||||
|
# 소유자 게이팅 — 본인 견적 또는 최고관리자만 삭제(user_id 미지정=내부 호출은 스킵).
|
||||||
|
if user_id is not None and not is_owner_or_admin(original.user_id, user_id, role):
|
||||||
|
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||||
|
res.msg = "본인이 생성한 견적만 삭제할 수 있습니다."
|
||||||
|
return res
|
||||||
|
|
||||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||||
[quotations.DBType()],
|
[quotations.DBType()],
|
||||||
@@ -815,15 +886,20 @@ class QuotationService:
|
|||||||
return res
|
return res
|
||||||
|
|
||||||
# ----- 협상 초청 메일 (수동 발송)
|
# ----- 협상 초청 메일 (수동 발송)
|
||||||
async def notify_sessions(self, qt_id: str, company_id=None) -> Res_NotifySessions:
|
async def notify_sessions(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_NotifySessions:
|
||||||
"""[수동 발송] 견적의 '미발송' 세션(공급사 담당자)에게 협상 초청 메일을 일괄 발송한다.
|
"""[수동 발송] 견적의 '미발송' 세션(공급사 담당자)에게 협상 초청 메일을 일괄 발송한다.
|
||||||
대상 = email_sent_at IS NULL + 담당자 이메일 보유."""
|
대상 = email_sent_at IS NULL + 담당자 이메일 보유."""
|
||||||
res = Res_NotifySessions()
|
res = Res_NotifySessions()
|
||||||
qt_uuid = uuid.UUID(qt_id)
|
qt_uuid = uuid.UUID(qt_id)
|
||||||
err_type, quotation = await self._fetch(qt_uuid, company_id)
|
err_type, quotation = await self._fetch(qt_uuid, company_id)
|
||||||
if err_type != ErrorType.SUCCESS:
|
if err_type != ErrorType.SUCCESS or quotation is None:
|
||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
return res
|
return res
|
||||||
|
# 소유자 게이팅 — 본인 견적 또는 최고관리자만 초청메일 발송(user_id 미지정=내부 호출은 스킵).
|
||||||
|
if user_id is not None and not is_owner_or_admin(quotation.user_id, user_id, role):
|
||||||
|
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||||
|
res.msg = "본인이 생성한 견적만 초청 메일을 발송할 수 있습니다."
|
||||||
|
return res
|
||||||
|
|
||||||
err_type, rows = await DB_SESSION_MNG.execute_lambda(
|
err_type, rows = await DB_SESSION_MNG.execute_lambda(
|
||||||
sessions.DBType(),
|
sessions.DBType(),
|
||||||
@@ -851,7 +927,7 @@ class QuotationService:
|
|||||||
await self._mark_emailed(sent_ids)
|
await self._mark_emailed(sent_ids)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
async def notify_session(self, session_id: str, company_id=None) -> Res_NotifySessions:
|
async def notify_session(self, session_id: str, company_id=None, user_id=None, role=None) -> Res_NotifySessions:
|
||||||
"""[수동 재발송] 단일 세션(공급사)에 초청 메일 발송(이미 보냈어도 강제 재발송)."""
|
"""[수동 재발송] 단일 세션(공급사)에 초청 메일 발송(이미 보냈어도 강제 재발송)."""
|
||||||
res = Res_NotifySessions()
|
res = Res_NotifySessions()
|
||||||
sess_uuid = uuid.UUID(session_id)
|
sess_uuid = uuid.UUID(session_id)
|
||||||
@@ -866,9 +942,14 @@ class QuotationService:
|
|||||||
sess, sp_name, email = got[0], got[1], got[2]
|
sess, sp_name, email = got[0], got[1], got[2]
|
||||||
res.total = 1
|
res.total = 1
|
||||||
err_type, quotation = await self._fetch(sess.quotation_id, company_id)
|
err_type, quotation = await self._fetch(sess.quotation_id, company_id)
|
||||||
if err_type != ErrorType.SUCCESS:
|
if err_type != ErrorType.SUCCESS or quotation is None:
|
||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
return res
|
return res
|
||||||
|
# 소유자 게이팅 — 본인 견적 또는 최고관리자만 재발송(user_id 미지정=내부 호출은 스킵).
|
||||||
|
if user_id is not None and not is_owner_or_admin(quotation.user_id, user_id, role):
|
||||||
|
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||||
|
res.msg = "본인이 생성한 견적만 초청 메일을 발송할 수 있습니다."
|
||||||
|
return res
|
||||||
if not email:
|
if not email:
|
||||||
res.skipped = 1
|
res.skipped = 1
|
||||||
return res
|
return res
|
||||||
|
|||||||
@@ -0,0 +1,193 @@
|
|||||||
|
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.enums import DBWRType, ErrorType, QuotationType, SessionStatus, CardType, CloseReason
|
||||||
|
from common.utils.gtime import GTime
|
||||||
|
from crud.statistics_crud import StatisticsCRUD, IStatisticsCRUD
|
||||||
|
from router.v1.statistics.protocol import (
|
||||||
|
Res_StatisticsSummary,
|
||||||
|
StatScope,
|
||||||
|
StatKpi,
|
||||||
|
StatMonthPoint,
|
||||||
|
StatOutcome,
|
||||||
|
StatParticipation,
|
||||||
|
StatTypeRow,
|
||||||
|
StatCategory,
|
||||||
|
StatCardUsage,
|
||||||
|
)
|
||||||
|
|
||||||
|
WINDOW_MONTHS = 6 # 최근 6개월(당월 포함) 창
|
||||||
|
|
||||||
|
|
||||||
|
class StatisticsService:
|
||||||
|
"""통계(성과 분석) 집계. 회사 전체(company)와 내 견적(mine) 두 스코프를 한 응답으로 내린다.
|
||||||
|
|
||||||
|
전부 파생(저장 안 함) — 조회 때 sessions/items/chats 조인 집계한다. 읽기 전용.
|
||||||
|
절감 원천은 '낙찰 세션'(preferred_sp_id) 이며, 여기서 총절감·추이·유형·카테고리·앵커도달률을 모두 파생한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, stat_crud: IStatisticsCRUD = Depends(StatisticsCRUD)):
|
||||||
|
self.stat_crud = stat_crud
|
||||||
|
|
||||||
|
async def get_summary(self, company_id: str, user_id: str) -> Res_StatisticsSummary:
|
||||||
|
res = Res_StatisticsSummary()
|
||||||
|
company_uuid = uuid.UUID(company_id)
|
||||||
|
user_uuid = uuid.UUID(user_id)
|
||||||
|
labels, window_start = self._window(GTime.UTC())
|
||||||
|
|
||||||
|
res.company = await self._scope(company_uuid, None, labels, window_start)
|
||||||
|
res.mine = await self._scope(company_uuid, user_uuid, labels, window_start)
|
||||||
|
return res
|
||||||
|
|
||||||
|
# ── 스코프 집계 ─────────────────────────────────────────────
|
||||||
|
async def _scope(self, company_uuid, owner_uuid, labels, since) -> StatScope:
|
||||||
|
scope = StatScope()
|
||||||
|
|
||||||
|
win_rows = await self._read(lambda s: self.stat_crud.winning_sessions(s, company_uuid, owner_uuid, since))
|
||||||
|
outcome_rows = await self._read(lambda s: self.stat_crud.outcome_counts(s, company_uuid, owner_uuid, since))
|
||||||
|
type_rows = await self._read(lambda s: self.stat_crud.type_counts(s, company_uuid, owner_uuid, since))
|
||||||
|
part_rows = await self._read(lambda s: self.stat_crud.participation_counts(s, company_uuid, owner_uuid, since))
|
||||||
|
regen = await self._read_scalar(lambda s: self.stat_crud.regen_avg_round(s, company_uuid, owner_uuid, since))
|
||||||
|
card_rows = await self._read(lambda s: self.stat_crud.card_usage(s, company_uuid, owner_uuid, since))
|
||||||
|
|
||||||
|
scope.trend = self._trend(win_rows, labels)
|
||||||
|
scope.categories = self._categories(win_rows)
|
||||||
|
scope.outcome = self._outcome(outcome_rows)
|
||||||
|
scope.participation = self._participation(part_rows)
|
||||||
|
scope.type_split = self._type_split(type_rows, win_rows)
|
||||||
|
scope.cards = self._cards(card_rows)
|
||||||
|
scope.kpi = self._kpi(win_rows, scope.trend, scope.outcome, regen)
|
||||||
|
return scope
|
||||||
|
|
||||||
|
# ── 파생 계산 ───────────────────────────────────────────────
|
||||||
|
def _kpi(self, win_rows, trend, outcome, regen) -> StatKpi:
|
||||||
|
k = StatKpi()
|
||||||
|
total_saving = sum(int(r.target_price) - int(r.bid_price) for r in win_rows)
|
||||||
|
total_target = sum(int(r.target_price) for r in win_rows)
|
||||||
|
k.total_savings = total_saving
|
||||||
|
k.savings_rate = (total_saving / total_target) if total_target else 0.0
|
||||||
|
k.anchor_reach_rate = self._anchor_reach(win_rows)
|
||||||
|
|
||||||
|
closed = outcome.awarded + outcome.open_price + outcome.open_equal + outcome.open_noshow + outcome.open_reject
|
||||||
|
k.closed_count = closed
|
||||||
|
k.award_rate = (outcome.awarded / closed) if closed else 0.0
|
||||||
|
k.regen_avg_round = round(regen, 2)
|
||||||
|
# 전월 대비: 마지막 두 달 절감액 차(창에 2개월 미만이면 0).
|
||||||
|
k.savings_delta_mom = (trend[-1].savings - trend[-2].savings) if len(trend) >= 2 else 0
|
||||||
|
return k
|
||||||
|
|
||||||
|
def _anchor_reach(self, win_rows) -> float:
|
||||||
|
# (목표−투찰)/(목표−앵커), 앵커 있고 목표>앵커인 세션만 평균.
|
||||||
|
# 세션별로 [0,100%] 클램프 후 평균 — '도달률'이라 앵커 도달=100% 상한(앵커 뚫어도 100%로).
|
||||||
|
# (앵커 gap 이 작으면 원비율이 100% 훌쩍 넘어 평균이 왜곡되므로 캡한다.)
|
||||||
|
vals = []
|
||||||
|
for r in win_rows:
|
||||||
|
if r.anchoring_price is None:
|
||||||
|
continue
|
||||||
|
target, bid, anchor = int(r.target_price), int(r.bid_price), int(r.anchoring_price)
|
||||||
|
span = target - anchor
|
||||||
|
if span > 0:
|
||||||
|
reach = (target - bid) / span
|
||||||
|
vals.append(min(1.0, max(0.0, reach)))
|
||||||
|
return (sum(vals) / len(vals)) if vals else 0.0
|
||||||
|
|
||||||
|
def _trend(self, win_rows, labels) -> list:
|
||||||
|
bucket = {m: {"savings": 0, "target": 0} for m in labels}
|
||||||
|
for r in win_rows:
|
||||||
|
m = f"{r.updated_at.year:04d}-{r.updated_at.month:02d}"
|
||||||
|
if m in bucket:
|
||||||
|
bucket[m]["savings"] += int(r.target_price) - int(r.bid_price)
|
||||||
|
bucket[m]["target"] += int(r.target_price)
|
||||||
|
out = []
|
||||||
|
for m in labels:
|
||||||
|
b = bucket[m]
|
||||||
|
rate = (b["savings"] / b["target"]) if b["target"] else 0.0
|
||||||
|
out.append(StatMonthPoint(month=m, savings=b["savings"], rate=rate))
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _categories(self, win_rows) -> list:
|
||||||
|
# TODO: items.category 자유텍스트 그룹 — 표기 흔들리면 지저분. 카테고리 정규화(코드/테이블) 후 개선.
|
||||||
|
agg: dict = {}
|
||||||
|
for r in win_rows:
|
||||||
|
key = r.category or "미분류"
|
||||||
|
a = agg.setdefault(key, {"savings": 0, "count": 0})
|
||||||
|
a["savings"] += int(r.target_price) - int(r.bid_price)
|
||||||
|
a["count"] += 1
|
||||||
|
rows = [StatCategory(category=k, savings=v["savings"], count=v["count"]) for k, v in agg.items()]
|
||||||
|
rows.sort(key=lambda x: x.savings, reverse=True)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
def _outcome(self, outcome_rows) -> StatOutcome:
|
||||||
|
by = {int(cr): int(n) for cr, n in outcome_rows if cr is not None}
|
||||||
|
return StatOutcome(
|
||||||
|
awarded=by.get(CloseReason.AWARDED.value, 0),
|
||||||
|
open_price=by.get(CloseReason.OPEN_PRICE.value, 0),
|
||||||
|
open_equal=by.get(CloseReason.OPEN_EQUAL.value, 0),
|
||||||
|
open_noshow=by.get(CloseReason.OPEN_NOSHOW.value, 0),
|
||||||
|
open_reject=by.get(CloseReason.OPEN_REJECT.value, 0),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _participation(self, part_rows) -> StatParticipation:
|
||||||
|
by = {int(st): int(n) for st, n in part_rows if st is not None}
|
||||||
|
return StatParticipation(
|
||||||
|
bid=by.get(SessionStatus.DONE.value, 0),
|
||||||
|
no_participate=by.get(SessionStatus.NOT_PARTICIPATED.value, 0),
|
||||||
|
rejected=by.get(SessionStatus.REJECTED.value, 0),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _type_split(self, type_rows, win_rows) -> list:
|
||||||
|
# 4개 코드(협상 1·3 / 견적 2·4=1:N)를 2그룹으로 묶는다. 낙찰률·건수=type_counts, 평균절감=낙찰세션.
|
||||||
|
grp = {"nego": {"count": 0, "awarded": 0}, "auction": {"count": 0, "awarded": 0}}
|
||||||
|
for t, cnt, awarded in type_rows:
|
||||||
|
g = "auction" if QuotationType.is_auction(int(t)) else "nego"
|
||||||
|
grp[g]["count"] += int(cnt or 0)
|
||||||
|
grp[g]["awarded"] += int(awarded or 0)
|
||||||
|
|
||||||
|
sav = {"nego": [], "auction": []}
|
||||||
|
for r in win_rows:
|
||||||
|
g = "auction" if QuotationType.is_auction(int(r.type)) else "nego"
|
||||||
|
sav[g].append(int(r.target_price) - int(r.bid_price))
|
||||||
|
|
||||||
|
out = []
|
||||||
|
for g, label in (("nego", "협상 (1:1)"), ("auction", "견적 (1:N)")):
|
||||||
|
cnt = grp[g]["count"]
|
||||||
|
rate = (grp[g]["awarded"] / cnt) if cnt else 0.0
|
||||||
|
avg = int(sum(sav[g]) / len(sav[g])) if sav[g] else 0
|
||||||
|
out.append(StatTypeRow(label=label, award_rate=rate, avg_savings=avg, count=cnt))
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _cards(self, card_rows) -> list:
|
||||||
|
by = {int(ct): int(n) for ct, n in card_rows if ct is not None}
|
||||||
|
return [
|
||||||
|
StatCardUsage(type="nego", label="협상카드", uses=by.get(CardType.NEGO.value, 0), avg_drop=0),
|
||||||
|
StatCardUsage(type="wild", label="와일드카드", uses=by.get(CardType.WILD.value, 0), avg_drop=0),
|
||||||
|
]
|
||||||
|
|
||||||
|
# ── 창(최근 6개월) ─────────────────────────────────────────
|
||||||
|
def _window(self, now):
|
||||||
|
yy, mm = now.year, now.month
|
||||||
|
mm -= (WINDOW_MONTHS - 1)
|
||||||
|
while mm <= 0:
|
||||||
|
mm += 12
|
||||||
|
yy -= 1
|
||||||
|
window_start = now.replace(year=yy, month=mm, day=1, hour=0, minute=0, second=0, microsecond=0)
|
||||||
|
labels, ly, lm = [], yy, mm
|
||||||
|
for _ in range(WINDOW_MONTHS):
|
||||||
|
labels.append(f"{ly:04d}-{lm:02d}")
|
||||||
|
lm += 1
|
||||||
|
if lm > 12:
|
||||||
|
lm = 1
|
||||||
|
ly += 1
|
||||||
|
return labels, window_start
|
||||||
|
|
||||||
|
# ── DB 실행 헬퍼 ───────────────────────────────────────────
|
||||||
|
async def _read(self, fn) -> list:
|
||||||
|
err, rows = await DB_SESSION_MNG.execute_lambda(quotations.DBType(), DBWRType.DB_READ.value, fn)
|
||||||
|
return rows if err == ErrorType.SUCCESS else []
|
||||||
|
|
||||||
|
async def _read_scalar(self, fn) -> float:
|
||||||
|
err, val = await DB_SESSION_MNG.execute_lambda(quotations.DBType(), DBWRType.DB_READ.value, fn)
|
||||||
|
return val if err == ErrorType.SUCCESS else 0.0
|
||||||
@@ -51,6 +51,16 @@ class SupplierService:
|
|||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
return res
|
return res
|
||||||
res.suppliers = [SupplierData.model_validate(r) for r in rows]
|
res.suppliers = [SupplierData.model_validate(r) for r in rows]
|
||||||
|
# 등록자명 배치 조인 — 페이지 협력사의 user_id를 모아 IN 쿼리 1회로 {id:name} 맵을 만들어 매핑(행별 조회 아님).
|
||||||
|
author_ids = list({r.user_id for r in rows if r.user_id is not None})
|
||||||
|
if author_ids:
|
||||||
|
nm_err, name_map = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
suppliers.DBType(), DBWRType.DB_READ.value,
|
||||||
|
lambda s: self.supplier_crud.user_name_map(s, author_ids),
|
||||||
|
)
|
||||||
|
if nm_err == ErrorType.SUCCESS:
|
||||||
|
for d in res.suppliers:
|
||||||
|
d.creator_name = name_map.get(d.user_id)
|
||||||
res.total = total
|
res.total = total
|
||||||
return res
|
return res
|
||||||
|
|
||||||
@@ -61,6 +71,13 @@ class SupplierService:
|
|||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
return res
|
return res
|
||||||
res.supplier = SupplierData.model_validate(supplier)
|
res.supplier = SupplierData.model_validate(supplier)
|
||||||
|
if supplier.user_id is not None:
|
||||||
|
nm_err, name_map = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
suppliers.DBType(), DBWRType.DB_READ.value,
|
||||||
|
lambda s: self.supplier_crud.user_name_map(s, [supplier.user_id]),
|
||||||
|
)
|
||||||
|
if nm_err == ErrorType.SUCCESS:
|
||||||
|
res.supplier.creator_name = name_map.get(supplier.user_id)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
async def check_codes(self, company_id: str, codes: list) -> Res_CheckCodes:
|
async def check_codes(self, company_id: str, codes: list) -> Res_CheckCodes:
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""card 도메인 스코프 e2e — 개인 카드는 소유자만, 전체(공용) 카드는 누구나.
|
||||||
|
스코프 규칙: user_id 있으면 개인(본인만 조회·관리) / NULL 이면 전체(모든 유저 조회·수정·삭제). 로그인은 auth_headers."""
|
||||||
|
|
||||||
|
|
||||||
|
async def _create_card(client, headers, *, number, name="카드", is_shared=False, is_wildcard=False):
|
||||||
|
r = await client.post(
|
||||||
|
"/v1/card/create",
|
||||||
|
json={
|
||||||
|
"is_wildcard": is_wildcard,
|
||||||
|
"is_shared": is_shared,
|
||||||
|
"name": name,
|
||||||
|
"number": number,
|
||||||
|
"script": "안녕하세요",
|
||||||
|
},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
body = r.json()
|
||||||
|
assert body["result"]["success"] is True, body
|
||||||
|
return body["card"]["nego_card_id"]
|
||||||
|
|
||||||
|
|
||||||
|
async def _list_numbers(client, headers):
|
||||||
|
r = await client.get("/v1/card/list", headers=headers)
|
||||||
|
return {c["number"] for c in r.json().get("cards", [])}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_personal_card_is_owner_only(client, auth_headers):
|
||||||
|
"""검증: user_id 가 박힌 개인 카드는 소유자 목록·단건조회에만 노출되고 타 유저에겐 숨는다.
|
||||||
|
기대결과: A 목록엔 있고 B 목록엔 없음, B 의 단건 조회는 success=False(CARD_NOT_FOUND)."""
|
||||||
|
ha = await auth_headers("cardA")
|
||||||
|
hb = await auth_headers("cardB")
|
||||||
|
cid = await _create_card(client, ha, number="P-1", is_shared=False)
|
||||||
|
|
||||||
|
assert "P-1" in await _list_numbers(client, ha)
|
||||||
|
assert "P-1" not in await _list_numbers(client, hb)
|
||||||
|
assert (await client.get(f"/v1/card/{cid}", headers=hb)).json()["result"]["success"] is False
|
||||||
|
|
||||||
|
|
||||||
|
async def test_shared_card_visible_to_all(client, auth_headers):
|
||||||
|
"""검증: is_shared=True 카드는 user_id NULL 로 저장돼 모든 유저 목록·단건조회에 노출된다.
|
||||||
|
기대결과: A·B 목록 모두에 존재, 비생성자 B 의 단건 조회 success=True, is_shared 플래그 True."""
|
||||||
|
ha = await auth_headers("cardSA")
|
||||||
|
hb = await auth_headers("cardSB")
|
||||||
|
cid = await _create_card(client, ha, number="S-1", is_shared=True)
|
||||||
|
|
||||||
|
assert "S-1" in await _list_numbers(client, ha)
|
||||||
|
assert "S-1" in await _list_numbers(client, hb)
|
||||||
|
got = await client.get(f"/v1/card/{cid}", headers=hb)
|
||||||
|
assert got.json()["result"]["success"] is True
|
||||||
|
assert got.json()["card"]["is_shared"] is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_shared_card_editable_and_deletable_by_anyone(client, auth_headers):
|
||||||
|
"""검증: 전체(공용) 카드는 소유자가 없어 아무 유저나 수정·삭제 가능(정책: 누구나).
|
||||||
|
기대결과: 비생성자 B 의 수정·삭제 모두 success=True, 삭제 후 목록에서 사라짐."""
|
||||||
|
ha = await auth_headers("cardEA")
|
||||||
|
hb = await auth_headers("cardEB")
|
||||||
|
cid = await _create_card(client, ha, number="S-EDIT", is_shared=True)
|
||||||
|
|
||||||
|
upd = await client.patch(f"/v1/card/update/{cid}", json={"name": "B가 수정"}, headers=hb)
|
||||||
|
assert upd.json()["result"]["success"] is True
|
||||||
|
|
||||||
|
dele = await client.delete(f"/v1/card/delete/{cid}", headers=hb)
|
||||||
|
assert dele.json()["result"]["success"] is True
|
||||||
|
assert "S-EDIT" not in await _list_numbers(client, hb)
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
"""소유자 게이팅 — 변경 액션은 '본인 소유' 또는 '최고관리자(OWNER)'만. 프론트 버튼 차단과 같은 규칙을 백엔드가 강제한다.
|
||||||
|
|
||||||
|
- item(상품): 같은 회사의 다른 일반유저는 남의 상품을 수정·삭제 못 한다(OWNER는 가능).
|
||||||
|
- quotation(견적): 남의 견적 삭제는 비소유 일반유저 차단, OWNER 허용, user_id 미지정(내부 호출)은 스킵.
|
||||||
|
공용 판정은 common.authz.is_owner_or_admin — 여기 통과하면 다른 변경 액션(마감·재생성·초청메일)도 같은 규칙을 탄다.
|
||||||
|
"""
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
from common.enums import ErrorType, QuotationStatus, QuotationType, UserRole
|
||||||
|
from crud.quotation_crud import QuotationCRUD
|
||||||
|
from services.quotation_service import QuotationService
|
||||||
|
|
||||||
|
PAST = datetime(2020, 1, 1)
|
||||||
|
|
||||||
|
|
||||||
|
# ===== item(상품) — HTTP e2e: 같은 회사, 다른 유저 =====
|
||||||
|
async def test_item_update_delete_blocked_for_non_owner(client, auth_headers):
|
||||||
|
"""검증: A가 등록한 상품을 같은 회사의 다른 일반유저 B가 수정·삭제 시도.
|
||||||
|
기대결과: 둘 다 거부(ACCOUNT_FORBIDDEN), 상품은 원값 그대로 남는다."""
|
||||||
|
ha = await auth_headers("item_owner") # 소유자
|
||||||
|
hb = await auth_headers("item_other") # 같은 회사, USER
|
||||||
|
item_id = (await client.post(
|
||||||
|
"/v1/item/create", json={"name": "상품A", "price": 1000, "code": "OWN1"}, headers=ha
|
||||||
|
)).json()["item"]["item_id"]
|
||||||
|
|
||||||
|
r_upd = await client.patch(f"/v1/item/update/{item_id}", json={"price": 9999}, headers=hb)
|
||||||
|
assert r_upd.json()["result"]["success"] is False
|
||||||
|
assert r_upd.json()["result"]["code"] == ErrorType.ACCOUNT_FORBIDDEN.value
|
||||||
|
|
||||||
|
r_del = await client.delete(f"/v1/item/delete/{item_id}", headers=hb)
|
||||||
|
assert r_del.json()["result"]["success"] is False
|
||||||
|
assert r_del.json()["result"]["code"] == ErrorType.ACCOUNT_FORBIDDEN.value
|
||||||
|
|
||||||
|
# 수정·삭제 모두 무산 — 원값으로 조회된다
|
||||||
|
assert (await client.get(f"/v1/item/{item_id}", headers=ha)).json()["item"]["price"] == 1000
|
||||||
|
|
||||||
|
|
||||||
|
async def test_item_delete_allowed_for_owner_role(client, auth_headers):
|
||||||
|
"""검증: A가 등록한 상품을 같은 회사 최고관리자(OWNER)가 삭제.
|
||||||
|
기대결과: 성공 — 소유자가 아니어도 OWNER는 허용."""
|
||||||
|
ha = await auth_headers("item_owner2")
|
||||||
|
hadmin = await auth_headers("item_admin", role=UserRole.OWNER.value)
|
||||||
|
item_id = (await client.post(
|
||||||
|
"/v1/item/create", json={"name": "상품B", "price": 500, "code": "OWN2"}, headers=ha
|
||||||
|
)).json()["item"]["item_id"]
|
||||||
|
|
||||||
|
r = await client.delete(f"/v1/item/delete/{item_id}", headers=hadmin)
|
||||||
|
assert r.json()["result"]["success"] is True
|
||||||
|
|
||||||
|
|
||||||
|
# ===== quotation(견적) — 서비스 직접: 삭제 게이팅 =====
|
||||||
|
async def test_quotation_delete_blocked_for_non_owner(db_engine):
|
||||||
|
"""검증: 남의 견적을 비소유 일반유저(USER)가 삭제 시도.
|
||||||
|
기대결과: 거부(ACCOUNT_FORBIDDEN) + soft-delete 안 됨(deleted=false)."""
|
||||||
|
owner, other = uuid.uuid4(), uuid.uuid4()
|
||||||
|
qt = await _seed_quotation(db_engine, user_id=owner, number="DEL-NONOWNER")
|
||||||
|
|
||||||
|
res = await _service().delete_quotation(str(qt), None, other, UserRole.USER.value)
|
||||||
|
|
||||||
|
assert res.result.success is False
|
||||||
|
assert res.result.code == ErrorType.ACCOUNT_FORBIDDEN.value
|
||||||
|
assert await _deleted(db_engine, qt) is False
|
||||||
|
|
||||||
|
|
||||||
|
async def test_quotation_delete_allowed_for_owner_role(db_engine):
|
||||||
|
"""검증: 남의 견적을 최고관리자(OWNER)가 삭제.
|
||||||
|
기대결과: 성공 + deleted=true."""
|
||||||
|
creator, admin = uuid.uuid4(), uuid.uuid4()
|
||||||
|
qt = await _seed_quotation(db_engine, user_id=creator, number="DEL-OWNER")
|
||||||
|
|
||||||
|
res = await _service().delete_quotation(str(qt), None, admin, UserRole.OWNER.value)
|
||||||
|
|
||||||
|
assert res.result.success is True
|
||||||
|
assert await _deleted(db_engine, qt) is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_quotation_delete_skips_gate_for_internal_call(db_engine):
|
||||||
|
"""검증: user_id 미지정(내부/스케줄러 호출)로 삭제.
|
||||||
|
기대결과: 소유권 검사 스킵 → 성공(회사 스코프만 적용)."""
|
||||||
|
creator = uuid.uuid4()
|
||||||
|
qt = await _seed_quotation(db_engine, user_id=creator, number="DEL-INTERNAL")
|
||||||
|
|
||||||
|
res = await _service().delete_quotation(str(qt), None)
|
||||||
|
|
||||||
|
assert res.result.success is True
|
||||||
|
assert await _deleted(db_engine, qt) is True
|
||||||
|
|
||||||
|
|
||||||
|
# ===== 헬퍼 =====
|
||||||
|
async def _seed_quotation(engine, *, user_id, number):
|
||||||
|
"""견적 1건 시드(삭제 게이팅 확인용 — 상태는 무관하므로 CLOSED로 고정)."""
|
||||||
|
qt_id = uuid.uuid4()
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
await conn.execute(
|
||||||
|
text(
|
||||||
|
"INSERT INTO quotations "
|
||||||
|
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, "
|
||||||
|
" round, iteration, start_time, end_time, deleted) VALUES "
|
||||||
|
"(:qt_id, :user_id, :qt_setting_id, :version_id, '견적', :number, :type, :status, "
|
||||||
|
" 1, 0, :t, :t, false)"
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"qt_id": qt_id, "user_id": user_id, "qt_setting_id": uuid.uuid4(),
|
||||||
|
"version_id": uuid.uuid4(), "number": number, "type": QuotationType.REQUOTE.value,
|
||||||
|
"status": QuotationStatus.CLOSED.value, "t": PAST,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return qt_id
|
||||||
|
|
||||||
|
|
||||||
|
async def _deleted(engine, qt_id) -> bool:
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
return (await conn.execute(
|
||||||
|
text("SELECT deleted FROM quotations WHERE qt_id = :q"), {"q": qt_id}
|
||||||
|
)).scalar_one()
|
||||||
|
|
||||||
|
|
||||||
|
def _service():
|
||||||
|
return QuotationService(QuotationCRUD())
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
"""앵커링 v1.2 — 견적 생성 시 칸(회사×협력사유형×가격구간) anchoring_value 로 앵커가를 박제하는지 검증.
|
"""앵커링 v1.2 — 견적 생성 시 칸(회사×상품-협력사 공급유형×가격구간) anchoring_value 로 앵커가를 박제하는지 검증.
|
||||||
|
|
||||||
이식 명세: schedules/anchoring/docs/인수인계.md §1.
|
이식 명세: schedules/anchoring/docs/인수인계.md §1.
|
||||||
- 앵커가 = 목표가 × (1000 − anchoring_value) // 1000 (정수 연산), anchoring_value 동시 박제
|
- 앵커가 = 목표가 × (1000 − anchoring_value) // 1000 (정수 연산), anchoring_value 동시 박제
|
||||||
- 조정 이력 없음 / 유형 미지정 / anchoring 스키마 미적용 → 정적 테이블 시작값(10‰) 폴백,
|
- 조정 이력 없음 / 매핑 유형 미지정 / anchoring 스키마 미적용 → 정적 테이블 시작값(10‰) 폴백,
|
||||||
견적 생성은 실패하지 않는다(규칙 6)
|
견적 생성은 실패하지 않는다(규칙 6)
|
||||||
- 재생성 라운드는 목표가만 상속하고 앵커는 생성 시점 anchoring_value 로 재계산(규칙 1 — 상속 폐지)
|
- 재생성 라운드는 목표가만 상속하고 앵커는 생성 시점 anchoring_value 로 재계산(규칙 1 — 상속 폐지)
|
||||||
"""
|
"""
|
||||||
@@ -22,12 +22,12 @@ BASE_VALUE = 10 # 정적 테이블 시작값(‰) — anchoring_base.json 전
|
|||||||
|
|
||||||
|
|
||||||
async def test_create_without_anchoring_schema_falls_back_to_base_value(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(유통) 견적 생성.
|
"""검증: anchoring 스키마가 아예 없는 DB 에서 supply_type=1(유통) 매핑으로 견적 생성.
|
||||||
기대결과: 조회 실패에도 생성 성공 + 앵커가=목표가×990‰(시작값), anchoring_value=10 박제."""
|
기대결과: 조회 실패에도 생성 성공 + 앵커가=목표가×990‰(시작값), anchoring_value=10 박제."""
|
||||||
await _drop_anchoring(db_engine)
|
await _drop_anchoring(db_engine)
|
||||||
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
|
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
|
||||||
|
|
||||||
res = await _create(item_ids=[item], supplier_type=1)
|
res = await _create(db_engine, item_ids=[item], supply_type=1)
|
||||||
|
|
||||||
assert res.result.success is True
|
assert res.result.success is True
|
||||||
tp = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE)) # 92,200
|
tp = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE)) # 92,200
|
||||||
@@ -45,7 +45,7 @@ async def test_create_uses_latest_adjusted_value_per_cell(db_engine, company_id)
|
|||||||
tp_miss = int(5_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, price_range=calc_price_range_index(tp_hit), value_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)
|
res = await _create(db_engine, item_ids=[item_hit, item_miss], supply_type=1)
|
||||||
|
|
||||||
assert res.result.success is True
|
assert res.result.success is True
|
||||||
rows = await _session_anchor_rows(db_engine, res.qt_id)
|
rows = await _session_anchor_rows(db_engine, res.qt_id)
|
||||||
@@ -53,15 +53,15 @@ async def test_create_uses_latest_adjusted_value_per_cell(db_engine, company_id)
|
|||||||
assert rows[item_miss] == (tp_miss, tp_miss * 990 // 1000, BASE_VALUE)
|
assert rows[item_miss] == (tp_miss, tp_miss * 990 // 1000, BASE_VALUE)
|
||||||
|
|
||||||
|
|
||||||
async def test_supplier_type_unset_uses_base_value(db_engine, company_id):
|
async def test_supply_type_unset_uses_base_value(db_engine, company_id):
|
||||||
"""검증: supplier_type 미지정(None) 견적 생성 — 칸(회사×유형×구간) 구성 불가.
|
"""검증: supply_type 미지정(None) 매핑으로 견적 생성 — 칸(회사×유형×구간) 구성 불가.
|
||||||
기대결과: 같은 회사·구간에 조정 이력이 있어도 쓰지 않고 시작값 10‰ 박제."""
|
기대결과: 같은 회사·구간에 조정 이력이 있어도 쓰지 않고 시작값 10‰ 박제."""
|
||||||
await _reset_anchoring(db_engine)
|
await _reset_anchoring(db_engine)
|
||||||
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
|
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
|
||||||
tp = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE))
|
tp = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE))
|
||||||
await _seed_adjustment(db_engine, company_id, supplier_type=1, price_range=calc_price_range_index(tp), value_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)
|
res = await _create(db_engine, item_ids=[item], supply_type=None)
|
||||||
|
|
||||||
assert res.result.success is True
|
assert res.result.success is True
|
||||||
rows = await _session_anchor_rows(db_engine, res.qt_id)
|
rows = await _session_anchor_rows(db_engine, res.qt_id)
|
||||||
@@ -75,7 +75,7 @@ async def test_regenerate_inherits_target_but_recomputes_anchor(db_engine, compa
|
|||||||
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
|
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
|
||||||
supplier = uuid.uuid4()
|
supplier = uuid.uuid4()
|
||||||
|
|
||||||
res1 = await _create(item_ids=[item], supplier_type=1, supplier_ids=[supplier])
|
res1 = await _create(db_engine, item_ids=[item], supply_type=1, supplier_ids=[supplier])
|
||||||
assert res1.result.success is True
|
assert res1.result.success is True
|
||||||
tp = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE))
|
tp = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE))
|
||||||
rows1 = await _session_anchor_rows(db_engine, res1.qt_id)
|
rows1 = await _session_anchor_rows(db_engine, res1.qt_id)
|
||||||
@@ -108,20 +108,40 @@ def _service():
|
|||||||
return QuotationService(QuotationCRUD())
|
return QuotationService(QuotationCRUD())
|
||||||
|
|
||||||
|
|
||||||
async def _create(*, item_ids, supplier_type, supplier_ids=None):
|
async def _create(engine, *, item_ids, supply_type, supplier_ids=None):
|
||||||
"""supplier_type 을 지정해 견적 1건 생성(공급사 기본 1곳)."""
|
"""supplier_items.supply_type 매핑을 시드한 뒤 견적 1건 생성(공급사 기본 1곳)."""
|
||||||
|
supplier_ids = supplier_ids or [uuid.uuid4()]
|
||||||
|
await _seed_supplier_items(engine, item_ids, supplier_ids, supply_type=supply_type)
|
||||||
req = Req_CreateQuotation(
|
req = Req_CreateQuotation(
|
||||||
qt_setting_id=uuid.uuid4(), # FK 미설정 — 세팅 없으면 율 0(앵커는 세팅과 무관해짐)
|
qt_setting_id=uuid.uuid4(), # FK 미설정 — 세팅 없으면 율 0(앵커는 세팅과 무관해짐)
|
||||||
name="앵커링검증",
|
name="앵커링검증",
|
||||||
type=QuotationType.NEW_QUOTE.value,
|
type=QuotationType.NEW_QUOTE.value,
|
||||||
end_time=FUTURE,
|
end_time=FUTURE,
|
||||||
supplier_type=supplier_type,
|
|
||||||
item_ids=list(item_ids),
|
item_ids=list(item_ids),
|
||||||
supplier_ids=supplier_ids or [uuid.uuid4()],
|
supplier_ids=supplier_ids,
|
||||||
)
|
)
|
||||||
return await _service().create_quotation(str(uuid.uuid4()), req)
|
return await _service().create_quotation(str(uuid.uuid4()), req)
|
||||||
|
|
||||||
|
|
||||||
|
async def _seed_supplier_items(engine, item_ids, supplier_ids, *, supply_type):
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
for item_id in item_ids:
|
||||||
|
for supplier_id in supplier_ids:
|
||||||
|
await conn.execute(
|
||||||
|
text(
|
||||||
|
"INSERT INTO supplier_items "
|
||||||
|
"(supplier_item_id, supplier_id, item_id, supply_type) "
|
||||||
|
"VALUES (:id, :supplier_id, :item_id, :supply_type)"
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"id": uuid.uuid4(),
|
||||||
|
"supplier_id": supplier_id,
|
||||||
|
"item_id": item_id,
|
||||||
|
"supply_type": supply_type if supply_type is not None else 0,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def _seed_item(engine, company_id, *, internet_lowest):
|
async def _seed_item(engine, company_id, *, internet_lowest):
|
||||||
"""상품 1건 시드(인터넷최저가만). NOT NULL 컬럼은 명시(ORM default 는 raw INSERT 에 안 먹음)."""
|
"""상품 1건 시드(인터넷최저가만). NOT NULL 컬럼은 명시(ORM default 는 raw INSERT 에 안 먹음)."""
|
||||||
item_id = uuid.uuid4()
|
item_id = uuid.uuid4()
|
||||||
|
|||||||
@@ -0,0 +1,206 @@
|
|||||||
|
"""개찰 견적 직접 낙찰(award_quotation) 테스트 — 담당자가 개찰(낙찰자 미정 마감) 견적의 낙찰자를 직접 지정.
|
||||||
|
|
||||||
|
직접 낙찰은 자동 낙찰(close_and_decide)과 결과 컬럼은 같되(close_reason=AWARDED, preferred_sp_*),
|
||||||
|
알림에 manual 플래그로 '직접' 낙찰임을 남긴다. 다음을 본다:
|
||||||
|
· 개찰 + 투찰(DONE) 협력사 지정 → 낙찰 확정 + 알림 SUCCESS(manual=True)
|
||||||
|
· 개찰 아님(이미 낙찰) → 거부(INVALID_REQUEST_DATA), 알림 없음
|
||||||
|
· 후보 아닌 협력사 지정 → 거부, close_reason 유지
|
||||||
|
· 낙찰 후 재지정(재클릭) → 거부(동시성 가드), 알림 1건 유지
|
||||||
|
|
||||||
|
세션의 협상 결과(협상완료/입찰가)와 개찰 상태(close_reason)는 협상/마감에서만 생기는 값이라 SQL 로 직접 넣는다.
|
||||||
|
"""
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
import pytest_asyncio
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
from common.enums import CloseReason, ErrorType, QuotationStatus, QuotationType, SessionStatus, UserRole
|
||||||
|
from crud.quotation_crud import QuotationCRUD
|
||||||
|
from services.quotation_service import QuotationService
|
||||||
|
|
||||||
|
PAST = datetime(2020, 1, 1)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest_asyncio.fixture
|
||||||
|
async def clean(db_engine):
|
||||||
|
"""conftest 는 notifications 를 비우지 않는다 → 알림 단언이 다른 테스트에 안 흔들리게 여기서 함께 비운다."""
|
||||||
|
async with db_engine.begin() as conn:
|
||||||
|
await conn.execute(text("TRUNCATE TABLE sessions, quotations, notifications RESTART IDENTITY CASCADE"))
|
||||||
|
return db_engine
|
||||||
|
|
||||||
|
|
||||||
|
async def test_award_opened_sets_winner_and_notifies(clean):
|
||||||
|
"""검증: 개찰(동가) 견적 + 투찰 협력사 2건(A=100, B=120) 중 A 를 직접 낙찰.
|
||||||
|
기대결과: close_reason→낙찰, preferred_sp=A, 동가플래그 해제 + 알림 SUCCESS(manual=True, winner_price=100)."""
|
||||||
|
engine = clean
|
||||||
|
user_id, supplier_a = uuid.uuid4(), uuid.uuid4()
|
||||||
|
qt = await _seed_opened(engine, user_id=user_id, number="A-WIN", close_reason=CloseReason.OPEN_EQUAL.value)
|
||||||
|
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, supplier_id=supplier_a)
|
||||||
|
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=120)
|
||||||
|
|
||||||
|
res = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a)
|
||||||
|
|
||||||
|
assert res.result.success is True
|
||||||
|
row = await _quotation(engine, qt)
|
||||||
|
assert row.close_reason == CloseReason.AWARDED.value
|
||||||
|
assert row.preferred_sp_yn is True
|
||||||
|
assert str(row.preferred_sp_id) == str(supplier_a)
|
||||||
|
assert row.equal_bid_yn is False
|
||||||
|
|
||||||
|
notis = await _notifications(engine, user_id)
|
||||||
|
assert len(notis) == 1
|
||||||
|
type_, data, ref = notis[0]
|
||||||
|
assert type_ == 1 # NotificationType.SUCCESS
|
||||||
|
assert data["manual"] is True
|
||||||
|
assert data["winner_price"] == 100
|
||||||
|
assert str(ref) == str(qt)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_award_rejects_when_not_opened(clean):
|
||||||
|
"""검증: 이미 낙찰된 견적(close_reason=AWARDED)에 직접 낙찰을 다시 시도.
|
||||||
|
기대결과: 거부(INVALID_REQUEST_DATA) + 새 알림 없음."""
|
||||||
|
engine = clean
|
||||||
|
user_id, supplier_a = uuid.uuid4(), uuid.uuid4()
|
||||||
|
qt = await _seed_opened(engine, user_id=user_id, number="A-DONE", close_reason=CloseReason.AWARDED.value)
|
||||||
|
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, supplier_id=supplier_a)
|
||||||
|
|
||||||
|
res = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a)
|
||||||
|
|
||||||
|
assert res.result.success is False
|
||||||
|
assert res.result.code == ErrorType.INVALID_REQUEST_DATA.value
|
||||||
|
assert len(await _notifications(engine, user_id)) == 0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_award_rejects_unknown_supplier(clean):
|
||||||
|
"""검증: 개찰 견적에, 투찰 후보가 아닌 협력사 id 를 지정.
|
||||||
|
기대결과: 거부 + close_reason 은 개찰(OPEN_PRICE) 그대로 유지, 알림 없음."""
|
||||||
|
engine = clean
|
||||||
|
user_id, bidder, stranger = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
|
||||||
|
qt = await _seed_opened(engine, user_id=user_id, number="A-STRANGER", close_reason=CloseReason.OPEN_PRICE.value)
|
||||||
|
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, supplier_id=bidder)
|
||||||
|
|
||||||
|
res = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, stranger)
|
||||||
|
|
||||||
|
assert res.result.success is False
|
||||||
|
row = await _quotation(engine, qt)
|
||||||
|
assert row.close_reason == CloseReason.OPEN_PRICE.value
|
||||||
|
assert row.preferred_sp_id is None
|
||||||
|
assert len(await _notifications(engine, user_id)) == 0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_award_is_idempotent(clean):
|
||||||
|
"""검증: 직접 낙찰 성공 후 같은 견적에 재지정(재클릭/경합).
|
||||||
|
기대결과: 2번째는 거부(이미 낙찰) + 알림은 1건만 유지(동시성 가드가 한 번만 통과)."""
|
||||||
|
engine = clean
|
||||||
|
user_id, supplier_a = uuid.uuid4(), uuid.uuid4()
|
||||||
|
qt = await _seed_opened(engine, user_id=user_id, number="A-IDEMP", close_reason=CloseReason.OPEN_REJECT.value)
|
||||||
|
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, supplier_id=supplier_a)
|
||||||
|
|
||||||
|
first = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a)
|
||||||
|
second = await _service().award_quotation(str(qt), None, user_id, UserRole.USER.value, supplier_a)
|
||||||
|
|
||||||
|
assert first.result.success is True
|
||||||
|
assert second.result.success is False
|
||||||
|
assert len(await _notifications(engine, user_id)) == 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_award_rejects_non_owner(clean):
|
||||||
|
"""검증: 남의 개찰 견적을 일반 유저(비소유·USER)가 직접 낙찰 시도.
|
||||||
|
기대결과: 거부(ACCOUNT_FORBIDDEN) + close_reason 개찰 유지 + 알림 없음."""
|
||||||
|
engine = clean
|
||||||
|
owner, other, supplier_a = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
|
||||||
|
qt = await _seed_opened(engine, user_id=owner, number="A-NONOWNER", close_reason=CloseReason.OPEN_PRICE.value)
|
||||||
|
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, supplier_id=supplier_a)
|
||||||
|
|
||||||
|
res = await _service().award_quotation(str(qt), None, other, UserRole.USER.value, supplier_a)
|
||||||
|
|
||||||
|
assert res.result.success is False
|
||||||
|
assert res.result.code == ErrorType.ACCOUNT_FORBIDDEN.value
|
||||||
|
row = await _quotation(engine, qt)
|
||||||
|
assert row.close_reason == CloseReason.OPEN_PRICE.value
|
||||||
|
assert row.preferred_sp_id is None
|
||||||
|
assert len(await _notifications(engine, owner)) == 0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_award_allows_owner_role(clean):
|
||||||
|
"""검증: 남의 개찰 견적을 최고관리자(OWNER)가 직접 낙찰.
|
||||||
|
기대결과: 낙찰 성공 + 알림은 견적 작성자(owner) 인박스에 남는다(호출자가 아니라)."""
|
||||||
|
engine = clean
|
||||||
|
creator, admin, supplier_a = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
|
||||||
|
qt = await _seed_opened(engine, user_id=creator, number="A-OWNER", close_reason=CloseReason.OPEN_EQUAL.value)
|
||||||
|
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, supplier_id=supplier_a)
|
||||||
|
|
||||||
|
res = await _service().award_quotation(str(qt), None, admin, UserRole.OWNER.value, supplier_a)
|
||||||
|
|
||||||
|
assert res.result.success is True
|
||||||
|
row = await _quotation(engine, qt)
|
||||||
|
assert row.close_reason == CloseReason.AWARDED.value
|
||||||
|
assert str(row.preferred_sp_id) == str(supplier_a)
|
||||||
|
assert len(await _notifications(engine, creator)) == 1
|
||||||
|
assert len(await _notifications(engine, admin)) == 0
|
||||||
|
|
||||||
|
|
||||||
|
# ===== 헬퍼 =====
|
||||||
|
async def _seed_opened(engine, *, user_id, number, close_reason, round_=1):
|
||||||
|
"""개찰/낙찰 상태(status=CLOSED + close_reason)로 견적 1건 시드. 낙찰자 컬럼은 비운 채 시작."""
|
||||||
|
qt_id = uuid.uuid4()
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
await conn.execute(
|
||||||
|
text(
|
||||||
|
"INSERT INTO quotations "
|
||||||
|
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, close_reason, "
|
||||||
|
" round, iteration, start_time, end_time, deleted) VALUES "
|
||||||
|
"(:qt_id, :user_id, :qt_setting_id, :version_id, '견적A', :number, :type, :status, :close_reason, "
|
||||||
|
" :round, 0, :start_time, :end_time, false)"
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"qt_id": qt_id, "user_id": user_id, "qt_setting_id": uuid.uuid4(),
|
||||||
|
"version_id": uuid.uuid4(), "number": number, "type": QuotationType.REQUOTE.value,
|
||||||
|
"status": QuotationStatus.CLOSED.value, "close_reason": close_reason,
|
||||||
|
"round": round_, "start_time": PAST, "end_time": PAST,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return qt_id
|
||||||
|
|
||||||
|
|
||||||
|
async def _add_session(engine, qt_id, *, status, bid_price=None, supplier_id=None):
|
||||||
|
"""세션 1건 시드(공급사 협상 1건). status/bid_price 로 협상완료·입찰가를 만든다."""
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
await conn.execute(
|
||||||
|
text(
|
||||||
|
"INSERT INTO sessions "
|
||||||
|
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
|
||||||
|
" target_price, status, bid_price, end_time) VALUES "
|
||||||
|
"(:session_id, :quotation_id, :item_id, :supplier_id, 'Q', 1, :qt_type, "
|
||||||
|
" 0, :status, :bid_price, :end_time)"
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"session_id": uuid.uuid4(), "quotation_id": qt_id, "item_id": uuid.uuid4(),
|
||||||
|
"supplier_id": supplier_id or uuid.uuid4(), "qt_type": QuotationType.REQUOTE.value,
|
||||||
|
"status": status, "bid_price": bid_price, "end_time": PAST,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _quotation(engine, qt_id):
|
||||||
|
"""견적 1행(마감 결과 컬럼 확인용)."""
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
return (await conn.execute(
|
||||||
|
text("SELECT close_reason, preferred_sp_yn, preferred_sp_id, equal_bid_yn "
|
||||||
|
"FROM quotations WHERE qt_id = :qt_id"),
|
||||||
|
{"qt_id": qt_id},
|
||||||
|
)).one()
|
||||||
|
|
||||||
|
|
||||||
|
async def _notifications(engine, user_id):
|
||||||
|
"""user_id(작성자) 인박스 알림 (type, data, ref_qt_id) — 생성순."""
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
return (await conn.execute(
|
||||||
|
text("SELECT type, data, ref_qt_id FROM notifications WHERE user_id = :uid ORDER BY created_at"),
|
||||||
|
{"uid": user_id},
|
||||||
|
)).all()
|
||||||
|
|
||||||
|
|
||||||
|
def _service():
|
||||||
|
return QuotationService(QuotationCRUD())
|
||||||
Generated
+377
@@ -25,6 +25,7 @@
|
|||||||
"react-dom": "^19.0.1",
|
"react-dom": "^19.0.1",
|
||||||
"react-hook-form": "^7.79.0",
|
"react-hook-form": "^7.79.0",
|
||||||
"react-router": "^7.17.0",
|
"react-router": "^7.17.0",
|
||||||
|
"recharts": "^3.8.0",
|
||||||
"shadcn": "^4.11.0",
|
"shadcn": "^4.11.0",
|
||||||
"slate": "^0.118.1",
|
"slate": "^0.118.1",
|
||||||
"slate-dom": "^0.119.0",
|
"slate-dom": "^0.119.0",
|
||||||
@@ -2431,6 +2432,42 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@reduxjs/toolkit": {
|
||||||
|
"version": "2.12.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.12.0.tgz",
|
||||||
|
"integrity": "sha512-KiT+RzZbp6mQET+Mg+h2c97+9j1sNflUxQkIHI7Yuzf6Peu+OYpmkn6nbHWmLLWj+1ZODUJFwGZ7gx3L9R9EOw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@standard-schema/spec": "^1.0.0",
|
||||||
|
"@standard-schema/utils": "^0.3.0",
|
||||||
|
"immer": "^11.0.0",
|
||||||
|
"redux": "^5.0.1",
|
||||||
|
"redux-thunk": "^3.1.0",
|
||||||
|
"reselect": "^5.1.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^16.9.0 || ^17.0.0 || ^18 || ^19",
|
||||||
|
"react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"react-redux": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@reduxjs/toolkit/node_modules/immer": {
|
||||||
|
"version": "11.1.11",
|
||||||
|
"resolved": "https://registry.npmjs.org/immer/-/immer-11.1.11.tgz",
|
||||||
|
"integrity": "sha512-qzXuyXAkPySAGYkfsAwodDPWT8Zm7/Uo5BNt4BjhMhG5WlWyZZ4wQqnWwdS8kjlQ1Cwu6gjw3A6+0gTQwlyYtw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/immer"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@rolldown/pluginutils": {
|
"node_modules/@rolldown/pluginutils": {
|
||||||
"version": "1.0.0-rc.3",
|
"version": "1.0.0-rc.3",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz",
|
||||||
@@ -2829,6 +2866,12 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@standard-schema/spec": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@standard-schema/utils": {
|
"node_modules/@standard-schema/utils": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
|
||||||
@@ -3639,6 +3682,69 @@
|
|||||||
"@types/node": "*"
|
"@types/node": "*"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/d3-array": {
|
||||||
|
"version": "3.2.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
|
||||||
|
"integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@types/d3-color": {
|
||||||
|
"version": "3.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
|
||||||
|
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@types/d3-ease": {
|
||||||
|
"version": "3.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
|
||||||
|
"integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@types/d3-interpolate": {
|
||||||
|
"version": "3.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
|
||||||
|
"integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/d3-color": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@types/d3-path": {
|
||||||
|
"version": "3.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
|
||||||
|
"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@types/d3-scale": {
|
||||||
|
"version": "4.0.9",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
|
||||||
|
"integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/d3-time": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@types/d3-shape": {
|
||||||
|
"version": "3.1.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",
|
||||||
|
"integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/d3-path": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@types/d3-time": {
|
||||||
|
"version": "3.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
|
||||||
|
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@types/d3-timer": {
|
||||||
|
"version": "3.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
|
||||||
|
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@types/es-aggregate-error": {
|
"node_modules/@types/es-aggregate-error": {
|
||||||
"version": "1.0.6",
|
"version": "1.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/@types/es-aggregate-error/-/es-aggregate-error-1.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/@types/es-aggregate-error/-/es-aggregate-error-1.0.6.tgz",
|
||||||
@@ -3808,6 +3914,12 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/use-sync-external-store": {
|
||||||
|
"version": "0.0.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
|
||||||
|
"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@types/validate-npm-package-name": {
|
"node_modules/@types/validate-npm-package-name": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/@types/validate-npm-package-name/-/validate-npm-package-name-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/@types/validate-npm-package-name/-/validate-npm-package-name-4.0.2.tgz",
|
||||||
@@ -4699,6 +4811,127 @@
|
|||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/d3-array": {
|
||||||
|
"version": "3.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
|
||||||
|
"integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"internmap": "1 - 2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/d3-color": {
|
||||||
|
"version": "3.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
|
||||||
|
"integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/d3-ease": {
|
||||||
|
"version": "3.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
|
||||||
|
"integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/d3-format": {
|
||||||
|
"version": "3.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",
|
||||||
|
"integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/d3-interpolate": {
|
||||||
|
"version": "3.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
|
||||||
|
"integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"d3-color": "1 - 3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/d3-path": {
|
||||||
|
"version": "3.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
|
||||||
|
"integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/d3-scale": {
|
||||||
|
"version": "4.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
|
||||||
|
"integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"d3-array": "2.10.0 - 3",
|
||||||
|
"d3-format": "1 - 3",
|
||||||
|
"d3-interpolate": "1.2.0 - 3",
|
||||||
|
"d3-time": "2.1.1 - 3",
|
||||||
|
"d3-time-format": "2 - 4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/d3-shape": {
|
||||||
|
"version": "3.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
|
||||||
|
"integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"d3-path": "^3.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/d3-time": {
|
||||||
|
"version": "3.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
|
||||||
|
"integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"d3-array": "2 - 3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/d3-time-format": {
|
||||||
|
"version": "4.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
|
||||||
|
"integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"d3-time": "1 - 3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/d3-timer": {
|
||||||
|
"version": "3.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
|
||||||
|
"integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/data-uri-to-buffer": {
|
"node_modules/data-uri-to-buffer": {
|
||||||
"version": "4.0.1",
|
"version": "4.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
|
||||||
@@ -4779,6 +5012,12 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/decimal.js-light": {
|
||||||
|
"version": "2.5.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",
|
||||||
|
"integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/dedent": {
|
"node_modules/dedent": {
|
||||||
"version": "1.7.2",
|
"version": "1.7.2",
|
||||||
"resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz",
|
"resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz",
|
||||||
@@ -5249,6 +5488,16 @@
|
|||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/es-toolkit": {
|
||||||
|
"version": "1.49.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.49.0.tgz",
|
||||||
|
"integrity": "sha512-G5iZ6Pc/FNRY/soKZHC+TxGDD83rHUDXxzaWhGCX44vAv/tMs56WMusnm/KMNK+luUPsgA9U28cGr4RDlSzL2g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"workspaces": [
|
||||||
|
"docs",
|
||||||
|
"benchmarks"
|
||||||
|
]
|
||||||
|
},
|
||||||
"node_modules/es6-promise": {
|
"node_modules/es6-promise": {
|
||||||
"version": "3.3.1",
|
"version": "3.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz",
|
||||||
@@ -5354,6 +5603,12 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/eventemitter3": {
|
||||||
|
"version": "5.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
|
||||||
|
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/eventsource": {
|
"node_modules/eventsource": {
|
||||||
"version": "3.0.7",
|
"version": "3.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
|
"resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
|
||||||
@@ -6319,6 +6574,15 @@
|
|||||||
"node": ">= 0.4"
|
"node": ">= 0.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/internmap": {
|
||||||
|
"version": "2.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
|
||||||
|
"integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/ip-address": {
|
"node_modules/ip-address": {
|
||||||
"version": "10.2.0",
|
"version": "10.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
|
||||||
@@ -8836,6 +9100,36 @@
|
|||||||
"react": "^16.8.0 || ^17 || ^18 || ^19"
|
"react": "^16.8.0 || ^17 || ^18 || ^19"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/react-is": {
|
||||||
|
"version": "19.2.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.7.tgz",
|
||||||
|
"integrity": "sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
|
},
|
||||||
|
"node_modules/react-redux": {
|
||||||
|
"version": "9.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.3.0.tgz",
|
||||||
|
"integrity": "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/use-sync-external-store": "^0.0.6",
|
||||||
|
"use-sync-external-store": "^1.4.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "^18.2.25 || ^19",
|
||||||
|
"react": "^18.0 || ^19",
|
||||||
|
"redux": "^5.0.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"redux": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/react-refresh": {
|
"node_modules/react-refresh": {
|
||||||
"version": "0.18.0",
|
"version": "0.18.0",
|
||||||
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",
|
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",
|
||||||
@@ -8979,6 +9273,67 @@
|
|||||||
"node": ">= 4"
|
"node": ">= 4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/recharts": {
|
||||||
|
"version": "3.8.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.8.0.tgz",
|
||||||
|
"integrity": "sha512-Z/m38DX3L73ExO4Tpc9/iZWHmHnlzWG4njQbxsF5aSjwqmHNDDIm0rdEBArkwsBvR8U6EirlEHiQNYWCVh9sGQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"workspaces": [
|
||||||
|
"www"
|
||||||
|
],
|
||||||
|
"dependencies": {
|
||||||
|
"@reduxjs/toolkit": "^1.9.0 || 2.x.x",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"decimal.js-light": "^2.5.1",
|
||||||
|
"es-toolkit": "^1.39.3",
|
||||||
|
"eventemitter3": "^5.0.1",
|
||||||
|
"immer": "^10.1.1",
|
||||||
|
"react-redux": "8.x.x || 9.x.x",
|
||||||
|
"reselect": "5.1.1",
|
||||||
|
"tiny-invariant": "^1.3.3",
|
||||||
|
"use-sync-external-store": "^1.2.2",
|
||||||
|
"victory-vendor": "^37.0.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||||
|
"react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||||
|
"react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/recharts/node_modules/immer": {
|
||||||
|
"version": "10.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz",
|
||||||
|
"integrity": "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/immer"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/recharts/node_modules/reselect": {
|
||||||
|
"version": "5.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz",
|
||||||
|
"integrity": "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/redux": {
|
||||||
|
"version": "5.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
|
||||||
|
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/redux-thunk": {
|
||||||
|
"version": "3.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",
|
||||||
|
"integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peerDependencies": {
|
||||||
|
"redux": "^5.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/reflect.getprototypeof": {
|
"node_modules/reflect.getprototypeof": {
|
||||||
"version": "1.0.10",
|
"version": "1.0.10",
|
||||||
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
|
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
|
||||||
@@ -11043,6 +11398,28 @@
|
|||||||
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc"
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/victory-vendor": {
|
||||||
|
"version": "37.3.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",
|
||||||
|
"integrity": "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==",
|
||||||
|
"license": "MIT AND ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/d3-array": "^3.0.3",
|
||||||
|
"@types/d3-ease": "^3.0.0",
|
||||||
|
"@types/d3-interpolate": "^3.0.1",
|
||||||
|
"@types/d3-scale": "^4.0.2",
|
||||||
|
"@types/d3-shape": "^3.1.0",
|
||||||
|
"@types/d3-time": "^3.0.0",
|
||||||
|
"@types/d3-timer": "^3.0.0",
|
||||||
|
"d3-array": "^3.1.6",
|
||||||
|
"d3-ease": "^3.0.1",
|
||||||
|
"d3-interpolate": "^3.0.1",
|
||||||
|
"d3-scale": "^4.0.2",
|
||||||
|
"d3-shape": "^3.1.0",
|
||||||
|
"d3-time": "^3.0.0",
|
||||||
|
"d3-timer": "^3.0.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "6.4.3",
|
"version": "6.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
|
||||||
|
|||||||
@@ -29,6 +29,7 @@
|
|||||||
"react-dom": "^19.0.1",
|
"react-dom": "^19.0.1",
|
||||||
"react-hook-form": "^7.79.0",
|
"react-hook-form": "^7.79.0",
|
||||||
"react-router": "^7.17.0",
|
"react-router": "^7.17.0",
|
||||||
|
"recharts": "^3.8.0",
|
||||||
"shadcn": "^4.11.0",
|
"shadcn": "^4.11.0",
|
||||||
"slate": "^0.118.1",
|
"slate": "^0.118.1",
|
||||||
"slate-dom": "^0.119.0",
|
"slate-dom": "^0.119.0",
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { CardDataUserId } from './cardDataUserId';
|
import type { CardDataUserId } from './cardDataUserId';
|
||||||
|
import type { CardDataCreatorName } from './cardDataCreatorName';
|
||||||
import type { CardDataName } from './cardDataName';
|
import type { CardDataName } from './cardDataName';
|
||||||
import type { CardDataNumber } from './cardDataNumber';
|
import type { CardDataNumber } from './cardDataNumber';
|
||||||
import type { CardDataScript } from './cardDataScript';
|
import type { CardDataScript } from './cardDataScript';
|
||||||
@@ -20,6 +21,8 @@ export interface CardData {
|
|||||||
nego_card_id: string;
|
nego_card_id: string;
|
||||||
user_id?: CardDataUserId;
|
user_id?: CardDataUserId;
|
||||||
is_wildcard?: boolean;
|
is_wildcard?: boolean;
|
||||||
|
is_shared?: boolean;
|
||||||
|
creator_name?: CardDataCreatorName;
|
||||||
name?: CardDataName;
|
name?: CardDataName;
|
||||||
number?: CardDataNumber;
|
number?: CardDataNumber;
|
||||||
script?: CardDataScript;
|
script?: CardDataScript;
|
||||||
|
|||||||
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user