Compare commits
No commits in common. "main" and "feature/backend-frontend" have entirely different histories.
main
...
feature/ba
8
.gitignore
vendored
8
.gitignore
vendored
@ -24,11 +24,3 @@ CLAUDE.md
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# 로컬 리서치 노트(크롤링 라이브러리·안티스크래핑 조사) — 추적 안 함, 로컬 참고용
|
||||
/Temp.md
|
||||
/new.md
|
||||
|
||||
/mobile.mov
|
||||
.gstack/
|
||||
.playwright-mcp/
|
||||
|
||||
BIN
0729~30_테스트.xlsx
BIN
0729~30_테스트.xlsx
Binary file not shown.
Binary file not shown.
Binary file not shown.
190
README.md
190
README.md
@ -1,198 +1,63 @@
|
||||
# O2O Negosium
|
||||
|
||||
AI 협상 솔루션. 여러 백엔드·프론트·배치가 **하나의 PostgreSQL 인스턴스**를 공유하고,
|
||||
전부 `docker compose` 하나로 뜬다. (인터넷 최저가 검색 LPS 만 별도 DB `lps_db` 사용.)
|
||||
|
||||
## 서비스 소개
|
||||
|
||||
구매기업(바이어)이 협력사(공급사)와 벌이는 **가격 협상을 AI 봇이 대신 수행**하는 B2B 협상 자동화 솔루션이다.
|
||||
바이어가 상품·목표가·기간만 정해 견적을 열면, 각 협력사와의 1:1 협상은 강화학습 기반 에이전트가
|
||||
**협상 카드로 밀당**하며 진행하고, 마감 시각에 최저 투찰가를 기준으로 자동 **낙찰/개찰**을 판정한다.
|
||||
|
||||
크게 세 축 + 부속으로 나뉜다.
|
||||
|
||||
| 축 | 구성요소 | 역할 |
|
||||
|---|---|---|
|
||||
| **바이어 측** | negodata (backend + front) | 어드민. 상품·협력사 관리, 견적 생성, 마감·낙찰 관리 |
|
||||
| **공급사 측** | negosium (backend + frontend) | 협력사 포털. 초청받은 협상 챗에 참여해 가격 제시 |
|
||||
| **협상 엔진** | agent | 실제 AI 협상 봇. 앵커링가·협상 카드로 자동 협상 (강화학습) |
|
||||
| 부속 | lps · anchoring · landing | 인터넷 최저가(목표가 재료) · 앵커값 자동 조정 배치 · 솔루션 소개 랜딩 |
|
||||
동일 구조의 두 서비스(**negosium**, **negodata**)가 **하나의 PostgreSQL 인스턴스**를 공유한다.
|
||||
|
||||
## 구성
|
||||
|
||||
```
|
||||
o2o-negosium/
|
||||
├── docker-compose.yml # 전체 서비스 (DB 는 compose 밖, config 로 외부 연결)
|
||||
├── postgres-init/ # DB·스키마·시드 SQL (대상 DB 에 1회 적용)
|
||||
│
|
||||
├── backend/ # negosium 백엔드 — 공급사/협상 API (:9300)
|
||||
├── frontend/ # negosium 공급사 프론트 (:3300, 프로덕션 빌드 정적 서빙)
|
||||
├── agent/ # 협상 에이전트 — RL(learning 스키마) (:9500)
|
||||
│
|
||||
├── negodata/backend/ # negodata 백엔드 — 바이어/어드민 API (:9400)
|
||||
├── negodata/front/ # negodata 어드민 프론트 (Vite, :3000)
|
||||
│
|
||||
├── landing/ # 솔루션 랜딩페이지 (react-router SSG, :3100)
|
||||
│
|
||||
├── lps/ # 인터넷 최저가 검색: lps-api(:9600) + lps-worker(크롤)
|
||||
├── lps-admin/ # LPS 관리자 UI (nginx → lps-api 프록시, :3400)
|
||||
│
|
||||
└── schedules/anchoring/ # 앵커링 값 자동 조정 배치 (포트 없음, 상주 스케줄러 + Redis)
|
||||
├── docker-compose.yml # 두 backend (DB 는 외부)
|
||||
├── postgres-init/ # DB·테이블 셋업 SQL (대상 DB 에 1회 적용)
|
||||
├── backend/ # negosium 백엔드 (포트 9300)
|
||||
├── negodata/backend/ # negodata 백엔드 (포트 9400)
|
||||
├── agent/ front/ # (예정)
|
||||
└── negodata/front/ # (예정)
|
||||
```
|
||||
|
||||
negosium·negodata·agent 백엔드는 같은 코드 골격(MVC · 람다 DB · Depends 주입 · JWT 로그인)을 쓴다.
|
||||
아키텍처/패턴 상세는 각 서브 README 참고:
|
||||
- 백엔드: [backend](backend/README.md) · [negodata/backend](negodata/backend/README.md) · [agent](agent/README.md) · [lps](lps/README.md)
|
||||
- 프론트: [frontend](frontend/README.md) · [negodata/front](negodata/front/README.md)
|
||||
- 배치: [schedules/anchoring](schedules/anchoring/README.md) · 관리자 UI: [lps-admin](lps-admin/README.md)
|
||||
|
||||
### 서비스 / 포트
|
||||
|
||||
| 서비스 | 주소 | 역할 | DB |
|
||||
|---|---|---|---|
|
||||
| negosium-backend | http://localhost:9300/docs | 공급사·협상 API | negosium_db |
|
||||
| negosium-front | http://localhost:3300 | 공급사 프론트 | — |
|
||||
| agent | http://localhost:9500/docs | 협상 에이전트(RL) | negosium_db (learning) |
|
||||
| negodata-backend | http://localhost:9400/docs | 바이어·어드민 API | negosium_db |
|
||||
| negodata-front | http://localhost:3000 | 어드민 프론트 | — |
|
||||
| landing | http://localhost:3100 | 솔루션 랜딩 | — |
|
||||
| lps-api | http://localhost:9600/docs | 최저가 검색 접수/조회 | lps_db |
|
||||
| lps-worker | 포트 없음 | 크롤 워커(헤드풀 Chromium) | lps_db |
|
||||
| lps-admin | http://localhost:3400 | LPS 관리자 UI | — |
|
||||
| anchoring | 포트 없음 | 앵커링 조정 배치(격주 토 00:00 KST) | negosium_db (anchoring) |
|
||||
| anchoring-redis | 127.0.0.1:6380 | anchoring 조회 캐시 | — |
|
||||
| autoheal | — | unhealthy 컨테이너 자동 재시작 | — |
|
||||
두 백엔드는 같은 코드 골격(MVC · 람다 DB · Depends 주입 · JWT 로그인)을 쓴다.
|
||||
아키텍처/패턴 상세는 각 서버 README 참고: [backend](backend/README.md) · [negodata/backend](negodata/backend/README.md)
|
||||
|
||||
### DB 는 compose 밖 (config 로 연결)
|
||||
|
||||
DB 는 docker-compose 에서 관리하지 않는다. 각 backend 는 `config.<APP_ENV>.toml` 의 접속 정보대로
|
||||
**외부 PostgreSQL**(호스트 로컬 postgres, 또는 따로 떠 있는 docker postgres)에 연결한다.
|
||||
|
||||
한 PostgreSQL 인스턴스 안에 **단일 `negosium_db`** 를 두고 도메인별 **schema** 로 묶는다.
|
||||
LPS 만 별도 database(`lps_db`) 를 쓴다.
|
||||
|
||||
한 PostgreSQL 안에 서비스별 database 를 둔다.
|
||||
```
|
||||
PostgreSQL (외부, 5432)
|
||||
├── negosium_db ← negosium-backend · negodata-backend · agent · anchoring 공유
|
||||
│ ├── company / supplier / partner : 회사·유저·협력사·상품
|
||||
│ ├── card / quotation / negotiation: 협상 카드·견적·협상 세션
|
||||
│ ├── learning : RL 자산 (agent 소유)
|
||||
│ └── anchoring : 앵커링 조정 (schedules/anchoring 소유)
|
||||
└── lps_db ← lps-api · lps-worker
|
||||
├── negosium_db ← negosium-backend
|
||||
└── negodata_db ← negodata-backend
|
||||
```
|
||||
- 컨테이너(docker env)에서 호스트 DB 접근: `host.docker.internal:5432` (compose 가 `DB_HOST` 로 override)
|
||||
- 컨테이너(docker env)에서 호스트 DB 접근: `host.docker.internal:5432` (`config.docker.toml`)
|
||||
- 로컬 실행/테스트(local·test env): `127.0.0.1:5432` (`config.local/test.toml`)
|
||||
- 계정/database 명은 config 에 맞춘다 (기본 `postgres` / `password`).
|
||||
|
||||
## 핵심 플로우
|
||||
|
||||
### 1. 견적 라이프사이클 (전체 개요)
|
||||
|
||||
바이어가 견적을 열고 → 협력사가 협상에 참여 → 마감 시각에 판정되는 큰 흐름.
|
||||
견적 유형은 두 축(재/신규 × 협상 1:1 / 견적 1:N)으로 4종.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["바이어: 상품·협력사·기간 선택<br/>견적 유형 4종 + 낙찰 기준(mid/over_action) 설정"] --> B["목표가·앵커링가 산정<br/>(MD제시가 → 인터넷최저가/매입가/판매가)"]
|
||||
B --> C["협력사 초청 (이메일)"]
|
||||
C --> D{"견적 유형"}
|
||||
D -->|"협상 1:1 (재협상·신규협상)"| E["AI 봇 밀당 협상<br/>(협상 카드 사용)"]
|
||||
D -->|"견적 1:N (재견적·신규견적)"| F["정형 흐름<br/>(배송형태·추가할인 확인)"]
|
||||
E --> G["세션별 투찰가 확정<br/>(협상완료) 또는 실패"]
|
||||
F --> G
|
||||
G --> H{"마감 트리거<br/>①마감시각 ②전세션종결 ③수동"}
|
||||
H --> I["마감 판정<br/>(최저 투찰가 기준)"]
|
||||
I --> J["낙찰 (승자 1)"]
|
||||
I --> K["개찰 (낙찰자 미정)"]
|
||||
```
|
||||
|
||||
### 2. 1:1 협상 봇 판정 (agent)
|
||||
|
||||
협력사가 가격을 제시할 때마다 봇이 **앵커링가** 기준으로 판정한다.
|
||||
재제안은 카드를 한 장씩 쓰며 **최대 3번**, 카드 소진·3번 초과에도 앵커 밑으로 못 내리면 실패(투찰 없음).
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
P["협력사 가격 제시"] --> Q{"제시가 vs 앵커링가"}
|
||||
Q -->|"≤ 앵커링가"| R["협상완료 — 투찰 확정"]
|
||||
Q -->|"앵커 ~ 앵커×1.02"| S["와일드카드: 1% 인하 요청<br/>(세션당 1회)"]
|
||||
Q -->|"앵커×1.02 초과"| T["협상 카드로 재제안"]
|
||||
S --> U{"재제안 횟수 ≤ 3?<br/>카드 남음?"}
|
||||
T --> U
|
||||
U -->|"예"| P
|
||||
U -->|"아니오 (소진·3번 초과)"| V["협상 실패 — 낙찰 후보 아님"]
|
||||
```
|
||||
|
||||
### 3. 마감 판정
|
||||
|
||||
마감 시 **협상완료 세션의 최저 투찰가**를 본다. 공통 전제: 완료 세션이 없거나(전원 미응찰·협상거부)
|
||||
동가 최저가 2곳 이상이면 유형과 무관하게 **개찰**. 그 외 단독 최저가일 때만 낙찰 후보가 되며,
|
||||
이후 판정이 유형별로 갈린다.
|
||||
|
||||
#### 3-1. 견적 1:N — 단독 최저면 무조건 낙찰
|
||||
|
||||
가격 구간을 보지 않는다. 생성 시 `mid/over_action`이 낙찰(AWARD)로 강제되기 때문.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
M1["마감: 협상완료 세션 최저 투찰가"] --> N1{"완료 세션 있나?"}
|
||||
N1 -->|"없음 (전원 미응찰·협상거부)"| O1["개찰"]
|
||||
N1 -->|"동가 최저 2곳+"| O1
|
||||
N1 -->|"단독 최저"| X1["낙찰 (가격 구간 무관, 무조건)"]
|
||||
```
|
||||
|
||||
#### 3-2. 협상 1:1 — 가격 구간별, 생성 때 정한 값 적용
|
||||
|
||||
앵커링가 이하는 무조건 낙찰. 그 위 구간은 **견적 생성 때 미리 정해둔 값**(`mid_action`/`over_action`,
|
||||
1=낙찰·2=개찰)을 마감 시 그대로 적용한다. 두 필드는 적용 구간만 다를 뿐 동작은 동일.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
M2["마감: 협상완료 세션 최저 투찰가"] --> N2{"완료 세션 있나?"}
|
||||
N2 -->|"없음 (전원 미응찰·협상거부)"| O2["개찰"]
|
||||
N2 -->|"동가 최저 2곳+"| O2
|
||||
N2 -->|"단독 최저"| W2{"투찰가 위치"}
|
||||
W2 -->|"≤ 앵커링가"| X2["낙찰"]
|
||||
W2 -->|"앵커 ~ 목표가"| Y2["생성 시 정한 mid_action 적용<br/>(1=낙찰 / 2=개찰)"]
|
||||
W2 -->|"목표가 초과"| Z2["생성 시 정한 over_action 적용<br/>(1=낙찰 / 2=개찰)"]
|
||||
```
|
||||
|
||||
> 개찰 = 낙찰자 미정 마감(결렬 아님). 개찰 후 수동 처리로 **직접 낙찰 확정**(`/v1/quotation/award`)
|
||||
> 또는 **재견적 재생성**(`/v1/quotation/regenerate`)이 있다.
|
||||
> 비즈니스 로직 정본은 [negodata/docs/business-logic.md](negodata/docs/business-logic.md).
|
||||
| 서비스 | 서버 | docs | database |
|
||||
|---|---|---|---|
|
||||
| negosium-backend | http://localhost:9300 | /docs | negosium_db |
|
||||
| negodata-backend | http://localhost:9400 | /docs | negodata_db |
|
||||
|
||||
## 빠른 시작
|
||||
|
||||
```bash
|
||||
# 1) DB 준비 (최초 1회) — 사용할 PostgreSQL 에 스키마 + 시드 적용
|
||||
# 스키마 DDL (구 01~05 통합, 전부 IF NOT EXISTS 라 재실행 안전)
|
||||
psql -h 127.0.0.1 -p 5432 -U postgres -d negosium_db -f postgres-init/init-data/init.sql
|
||||
# 로컬/개발 시드 (admin / admin1234, 회사·유저·협상 카드)
|
||||
psql -h 127.0.0.1 -p 5432 -U postgres -d negosium_db -f postgres-init/init-data/init-data.sql
|
||||
psql -h 127.0.0.1 -p 5432 -U postgres -f postgres-init/00-init.sql # 스키마 전체 (negosium_db + 도메인·learning·anchoring schema)
|
||||
psql -h 127.0.0.1 -p 5432 -U postgres -f postgres-init/temp-data.sql # 임시 데이터 시드 (admin / admin1234)
|
||||
|
||||
# (DBeaver 로 처음부터 새로 깔 때는 postgres-init/dbeaver/ 의 0~5 순서 스크립트를 쓴다:
|
||||
# 0 drop&create → 1 스키마 → 2 시드 → 3 lps_db → 4 카드 리셋 → 5 o2o OWNER 유저)
|
||||
|
||||
# 2) 전체 기동
|
||||
docker compose up -d
|
||||
docker compose logs -f # 컨테이너별 로그는 ./logs.sh 메뉴로도 확인
|
||||
# 2) 백엔드 기동
|
||||
docker compose up -d # 두 backend (DB 는 config 대로 외부 연결)
|
||||
docker compose logs -f
|
||||
docker compose down
|
||||
```
|
||||
|
||||
> 스키마 변경 보정은 `postgres-init/alters/` 의 날짜별 SQL 을 대상 DB 에 수동 적용한다
|
||||
> (postgres-init 은 DB 최초 생성 때만 자동 실행되므로, 기존 DB 엔 alter 를 직접 돌려야 새 컬럼이 반영된다).
|
||||
|
||||
## 테스트
|
||||
|
||||
```bash
|
||||
# config.test.toml 의 PostgreSQL(기본 127.0.0.1:5432) 이 떠 있어야 한다
|
||||
cd backend # 또는 negodata/backend, agent, lps ...
|
||||
cd backend # 또는 negodata/backend
|
||||
pip install pytest pytest-asyncio httpx
|
||||
python -m pytest
|
||||
```
|
||||
- httpx `ASGITransport` 로 네트워크 없이 앱을 직접 호출하는 e2e.
|
||||
- httpx `ASGITransport` 로 네트워크 없이 앱을 직접 호출하는 e2e (각 5개).
|
||||
- `DB_SESSION_MNG` 싱글톤의 커넥션 풀이 첫 이벤트 루프에 묶이므로, 모든 테스트가 단일 session 루프를 공유한다(`pytest.ini`).
|
||||
- ⚠️ 테스트는 `APP_ENV=test` 로 격리한다(테스트 DB). dev DB(`negosium_db`)에 대고 돌리면 데이터가 날아간다.
|
||||
|
||||
## 성능 / 벤치마크
|
||||
|
||||
@ -234,9 +99,4 @@ python -m locust -f loadtest/locustfile.py --host http://localhost:9300 --headle
|
||||
```
|
||||
|
||||
## 기술 스택
|
||||
- **백엔드**: FastAPI · SQLAlchemy(async) · asyncpg · PostgreSQL 16 · python-jose(JWT) · bcrypt · uvicorn
|
||||
- **프론트**: React · react-router v7 · Vite · TanStack Query (negosium-front 는 프로덕션 빌드 정적 서빙)
|
||||
- **에이전트**: 강화학습(Q-learning, learning 스키마) · OpenAI
|
||||
- **LPS**: 헤드풀 Chromium + Patchright(스텔스 Playwright 포크, 크롤) · autoheal
|
||||
- **배치**: Redis(anchoring 캐시) · 상주 스케줄러
|
||||
- **공통**: Docker Compose
|
||||
FastAPI · SQLAlchemy(async) · asyncpg · PostgreSQL 16 · python-jose(JWT) · bcrypt · uvicorn · Docker Compose
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
# Negosium Agent
|
||||
|
||||
범용 멀티테넌트 협상 솔루션 PoC. 여러 회사(imarketkorea 등)가 **각자 데이터로 분기 학습**하는
|
||||
범용 멀티테넌트 협상 솔루션 PoC. 여러 회사(ktcommerce·imarketkorea 등)가 **각자 데이터로 분기 학습**하는
|
||||
협상 카드 선택 에이전트. Q-Learning(UCB) 기반 `Chat_server`(단일 테넌트)를 참고해 신규 구축한다.
|
||||
|
||||
PoC 목표 두 가지:
|
||||
@ -99,10 +99,10 @@ APP_ENV=test python -m pytest # 테스트 (config.local.toml 사
|
||||
|
||||
**1) 의사결정 루프 데모** — 테넌트별 config 주입·상태분류·보상·DB 격리를 눈으로 확인:
|
||||
```bash
|
||||
APP_ENV=local python -m tools.console_demo --tenant imarketkorea # 기본 3턴 시나리오
|
||||
APP_ENV=local python -m tools.console_demo --tenant ktcommerce # 기본 3턴 시나리오
|
||||
APP_ENV=local python -m tools.console_demo --tenant imarketkorea # 다른 테넌트(다른 카드셋·임계값)
|
||||
APP_ENV=local python -m tools.console_demo --tenant imarketkorea --interactive # 직접 입력
|
||||
APP_ENV=local python -m tools.console_demo --tenant imarketkorea --no-db # DB 없이
|
||||
APP_ENV=local python -m tools.console_demo --tenant ktcommerce --interactive # 직접 입력
|
||||
APP_ENV=local python -m tools.console_demo --tenant ktcommerce --no-db # DB 없이
|
||||
```
|
||||
> ⚠️ 카드선택은 임시 placeholder 정책(실제 UCB Q-Table 은 H1/P5). 학습은 아직 일어나지 않는다.
|
||||
|
||||
@ -113,13 +113,13 @@ curl localhost:9500/healthz # 200
|
||||
curl localhost:9500/v1/health # {"status":"ok",...}
|
||||
curl localhost:9500/v1/foo # 400 TENANT_HEADER_MISSING (헤더 없음)
|
||||
curl localhost:9500/v1/foo -H 'X-Tenant-ID: nonexistent' # 404 TENANT_NOT_REGISTERED
|
||||
curl localhost:9500/v1/foo -H 'X-Tenant-ID: imarketkorea' # 통과(라우트 미존재라 404 Not Found)
|
||||
curl localhost:9500/v1/foo -H 'X-Tenant-ID: ktcommerce' # 통과(라우트 미존재라 404 Not Found)
|
||||
```
|
||||
|
||||
**2-1) 협상 한 라운드 (HTTP 프리뷰)** — `POST /v1/negotiation/step` (Swagger: http://localhost:9500/docs):
|
||||
```bash
|
||||
curl -s -X POST localhost:9500/v1/negotiation/step \
|
||||
-H 'X-Tenant-ID: imarketkorea' -H 'Content-Type: application/json' \
|
||||
-H 'X-Tenant-ID: ktcommerce' -H 'Content-Type: application/json' \
|
||||
-d '{"revenue_amount":20000000,"distribution_code":"A","partner_count":1,
|
||||
"acceptance_ratio":0.11,"input_price":990,"anchor_price":800,"target_price":1000,
|
||||
"round_number":3,"outcome":"success"}'
|
||||
@ -156,7 +156,7 @@ APP_ENV=local python -m tools.show_logs # learning.experience_logs 를 co
|
||||
**가격협상 턴 UCB 카드선택·학습 + 종료보상 역전파**. 브라우저 채팅 UI. (`tests/test_p7_chat.py` 5/5)
|
||||
- ✅ **H5 학습검증 하네스 (PoC 본체)**: 카드별 효과가 다른 시뮬 구매자(`eval_harness/`) → 정책 비교.
|
||||
**학습형(qtable_ucb)이 random/static 대비 평균보상 우위(95%CI 분리)·좋은카드 적중 0.9 vs 0.32** →
|
||||
"학습하면 성과가 오른다" 정량 입증. `python -m eval_harness.runner --config configs/exp_default.yaml --tenant imarketkorea`. (`tests/test_h5_*` 5/5)
|
||||
"학습하면 성과가 오른다" 정량 입증. `python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce`. (`tests/test_h5_*` 5/5)
|
||||
- ✅ **P7 14개 API**: chat / q-table(versions·switch·current) / experience-logs / reset-learning ·
|
||||
reset-all(타테넌트 무영향) / invalidate-session / **train**(오프라인 Q-learning) / verification-report /
|
||||
card-update · card-search. 전부 X-Tenant-ID 격리. (`tests/test_p7_apis.py` 5/5)
|
||||
@ -177,7 +177,7 @@ APP_ENV=local python -m tools.show_logs # learning.experience_logs 를 co
|
||||
|
||||
### PoC 본체 결과 (H5, 위 경제모델 기준 / target=10000·anchor=8000 시나리오)
|
||||
```
|
||||
python -m eval_harness.runner --config configs/exp_default.yaml --tenant imarketkorea
|
||||
python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce
|
||||
policy success settled/tgt turns mean_rwd ±95%CI good_hit
|
||||
random 0.988 0.904 2.02 1.1176 0.0206 0.350
|
||||
static 1.000 0.923 2.56 0.9995 0.0020 0.000
|
||||
|
||||
@ -55,7 +55,6 @@ class QTableVersion(_DBTypeMixin, MAIN_BASE):
|
||||
discount_factor = Column(Numeric(6, 4), nullable=False, default=0.95)
|
||||
epochs = Column(Integer, nullable=False, default=0)
|
||||
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()"))
|
||||
deleted = Column(Boolean, nullable=False, default=False)
|
||||
|
||||
|
||||
@ -40,20 +40,3 @@ def _apply_db_env_override(cfg: MainDBConfig):
|
||||
|
||||
|
||||
_apply_db_env_override(main_db_config)
|
||||
|
||||
|
||||
# LLM 키/설정 env override (DB 와 동일 패턴). 로컬은 config.local.toml [OpenAIConfig] 에 기재,
|
||||
# Docker/CI/운영은 toml 없이 env 로 주입한다(docker-compose 가 OPENAI_API_KEY passthrough).
|
||||
# env 미설정 시 no-op → toml 값 그대로.
|
||||
def _apply_llm_env_override(cfg: OpenAIConfig):
|
||||
if os.environ.get("OPENAI_API_KEY"):
|
||||
cfg.api_key = os.environ["OPENAI_API_KEY"]
|
||||
if os.environ.get("OPENAI_MODEL"):
|
||||
cfg.model = os.environ["OPENAI_MODEL"]
|
||||
if os.environ.get("OPENAI_BASE_URL"):
|
||||
cfg.base_url = os.environ["OPENAI_BASE_URL"]
|
||||
if os.environ.get("OPENAI_PROVIDER"):
|
||||
cfg.provider = os.environ["OPENAI_PROVIDER"]
|
||||
|
||||
|
||||
_apply_llm_env_override(openai_config)
|
||||
|
||||
@ -4,23 +4,10 @@ import os
|
||||
|
||||
os.environ.setdefault("APP_ENV", "local")
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_real_llm(monkeypatch):
|
||||
"""실 LLM 호출 차단 — imarketkorea 가 llm.enabled=true 라 로컬에 실키가 있으면
|
||||
챗 플로우가 자연화/NLU(과금·비결정 응답)를 시도한다. LLM 검증 테스트는
|
||||
available 을 테스트 안에서 직접 덮어써 이 가드를 우회한다."""
|
||||
from negotiation.chat.service.input_interpreter import InputInterpreter
|
||||
from negotiation.chat.service.script_naturalizer import ScriptNaturalizer
|
||||
|
||||
monkeypatch.setattr(ScriptNaturalizer, "available", staticmethod(lambda: False))
|
||||
monkeypatch.setattr(InputInterpreter, "available", staticmethod(lambda: False))
|
||||
|
||||
|
||||
@pytest_asyncio.fixture(scope="session", autouse=True)
|
||||
async def _dispose_app_engines():
|
||||
"""테스트 세션 종료 시 앱 싱글톤 엔진 정리 ('Event loop is closed' 경고 제거)."""
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@ -1,30 +0,0 @@
|
||||
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 imarketkorea
|
||||
episodes: 600 # 정책당 협상 에피소드 수 (action 11장 탐색 수렴 위해 상향)
|
||||
# 알고리즘 비교 실험 기본 설정 (H5). E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce
|
||||
episodes: 400 # 정책당 협상 에피소드 수
|
||||
seed: 42 # 재현용 (구매자 randomness 페어드)
|
||||
max_turns: 5 # 협상 라운드 상한
|
||||
n_good_cards: 3 # 시뮬 구매자: 효과 좋은 카드 수
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
"""eval_harness 러너 — 정책 비교 + 학습곡선 (H5, PoC 본체).
|
||||
|
||||
E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant imarketkorea
|
||||
E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce
|
||||
|
||||
판정: 학습형(qtable_ucb)이 random/static 대비 평균보상·성공률 우상향이면 "학습 루프 유효".
|
||||
구매자는 카드별 효과가 다른 시뮬(HeuristicBuyer) — 학습 정책만 좋은 카드를 알아내 성과가 오른다.
|
||||
@ -143,7 +143,7 @@ def _print(report: dict):
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="협상 정책 비교 하네스 (H5)")
|
||||
ap.add_argument("--config", default="configs/exp_default.yaml")
|
||||
ap.add_argument("--tenant", default="imarketkorea")
|
||||
ap.add_argument("--tenant", default="ktcommerce")
|
||||
ap.add_argument("--save", action="store_true", help="reports/ 에 JSON 저장")
|
||||
args = ap.parse_args()
|
||||
|
||||
|
||||
@ -1,52 +0,0 @@
|
||||
"""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, []
|
||||
@ -20,13 +20,6 @@ from negotiation.cards.ports.card_script_port import ICardScriptRepository
|
||||
|
||||
_NEGO_CARDS = table(
|
||||
"nego_cards",
|
||||
column("number"), column("script"), column("tone"), column("strategy_type"),
|
||||
column("created_at"), column("deleted"),
|
||||
schema="card",
|
||||
)
|
||||
|
||||
_WILD_CARDS = table(
|
||||
"wild_cards",
|
||||
column("number"), column("script"), column("created_at"), column("deleted"),
|
||||
schema="card",
|
||||
)
|
||||
@ -34,40 +27,17 @@ _WILD_CARDS = table(
|
||||
|
||||
class CardScriptDbRepository(ICardScriptRepository):
|
||||
async def get_script_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
|
||||
err, card = await self.get_card_by_number(cdb, number)
|
||||
return err, (card[0] if card else None)
|
||||
|
||||
async def get_wild_card_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
|
||||
"""card.wild_cards 멘트 조회 (WC-01~05 선택형 와일드카드/종결 전술 발동용)."""
|
||||
try:
|
||||
query = (
|
||||
select(_WILD_CARDS.c.script)
|
||||
.where(_WILD_CARDS.c.number == number, _WILD_CARDS.c.deleted == False) # noqa: E712
|
||||
.order_by(desc(_WILD_CARDS.c.created_at))
|
||||
.limit(1)
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_wild_card_script 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]) if not isinstance(rows[0], tuple) else str(rows[0][0])
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def get_card_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
try:
|
||||
query = (
|
||||
select(_NEGO_CARDS.c.script, _NEGO_CARDS.c.tone, _NEGO_CARDS.c.strategy_type)
|
||||
select(_NEGO_CARDS.c.script)
|
||||
.where(_NEGO_CARDS.c.number == number, _NEGO_CARDS.c.deleted == False) # noqa: E712
|
||||
.order_by(desc(_NEGO_CARDS.c.created_at))
|
||||
.limit(1)
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_card_script failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS or not rows or not rows[0] or not rows[0][0]:
|
||||
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
|
||||
return err_type, None
|
||||
script, tone, strategy = rows[0]
|
||||
return ErrorType.SUCCESS, (str(script), int(tone) if tone is not None else None,
|
||||
int(strategy) if strategy is not None else None)
|
||||
return ErrorType.SUCCESS, str(rows[0])
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
@ -1,240 +0,0 @@
|
||||
"""협상카드 전술 — "스크립트에 꽂힌 변수가 곧 전술" 계층.
|
||||
|
||||
카드 멘트가 제시하는 가격({target_price}·{middle_price} 등)을 파싱해 시스템 상태로 실행한다:
|
||||
카드가 제안가를 제시하면 pending_counter_price 로 적재되고, 협력사가 수락하면 그 가격으로 타결된다.
|
||||
|
||||
세 계층으로 나뉜다.
|
||||
1) 스크립트 파싱 — 이 카드가 부를 금액이 무엇인지 (parse_offer_variable)
|
||||
2) 변수 정의 — 그 금액을 지금 쓸 수 있는지 (OFFER_VARIABLES 의 계산식 + 유효조건)
|
||||
3) tactic JSONB — 문장으로 알 수 없는 운영 규칙 (min_round·closing)
|
||||
|
||||
유효 조건은 카드가 아니라 '변수'에 붙인다 — 금액이 성립하는지는 계산식의 성질이지 카드의
|
||||
성질이 아니다. 새 변수는 OFFER_VARIABLES 에 한 줄 추가하면 코드 분기 없이 끝난다.
|
||||
"""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
|
||||
# 제안가 변수 — 우리가 새로 부르는 금액. 값은 (계산식, 재료 설명).
|
||||
# 여기 없는 치환 변수({prev_partner_price}·{internet_lowest_price} 등)는 읽어주기 전용이라
|
||||
# 제안가가 되지 않는다 — 과거값·외부값을 협력사에게 "수락하라"고 내밀 수 없기 때문.
|
||||
OFFER_VARIABLES: Dict[str, Callable[[float, float, float, float], Optional[float]]] = {
|
||||
# (target, anchor, price, prev_customer) -> 제안가 | None(재료 없음)
|
||||
"target_price": lambda target, anchor, price, prev: target,
|
||||
"anchoring_price": lambda target, anchor, price, prev: anchor or None,
|
||||
# negodata 카드 에디터 칩 표기(variables.ts) — DB 시드 표기(anchoring_price)와 같은 값의 별칭.
|
||||
"anchor_price": lambda target, anchor, price, prev: anchor or None,
|
||||
"target_mid_price": lambda target, anchor, price, prev: (anchor + target) / 2 if anchor else None,
|
||||
"middle_price": lambda target, anchor, price, prev: (prev + price) / 2 if prev else None,
|
||||
}
|
||||
|
||||
_TOKEN_RE = re.compile(r"\{([a-z_]+)\}")
|
||||
|
||||
# 절충 계열 변수 — 양측 사이/우리 두 값 사이의 중간을 부르는 카드. 목표가 이상이면 미발동한다.
|
||||
_MID_VARIABLES = ("middle_price", "target_mid_price")
|
||||
|
||||
|
||||
# 세션 데이터에 따라 값이 없을 수 있는 읽기 전용 변수 → 그 값을 담는 컨텍스트 키.
|
||||
# 스크립트가 이런 변수를 인용하면 값이 있을 때만 카드가 나간다 — 없는데 나가면 협력사 채팅에
|
||||
# {internet_lowest_price} 토큰이 원형 노출된다(vars_for 가 미수집이면 키를 안 만드는 것과 짝).
|
||||
# 견적 생성 화면 게이팅(useCardGating)이 1차 방어, 여기가 2차(런타임) 방어다.
|
||||
_CONTEXT_REQUIRED_VARIABLES = {
|
||||
"internet_lowest_price": "internet_lowest_price",
|
||||
"internet_min_price": "internet_lowest_price",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CardSpec:
|
||||
"""카드 1장의 전술. 스크립트 파싱 결과 + tactic JSONB 를 합친 값.
|
||||
|
||||
offer_variable: 이 카드가 제시할 금액의 변수명. None 이면 순수 설득 카드(HOLD).
|
||||
min_round: 발동 가능 최소 라운드(협력사 가격 입력 횟수 기준).
|
||||
closing: 종결 국면 전용 — 라운드 상한·카드 소진 시의 마지막 한 방으로만 쓴다.
|
||||
requires: 스크립트가 인용한 세션-의존 변수의 컨텍스트 키 — 값이 없으면 미발동(토큰 노출 방지).
|
||||
"""
|
||||
|
||||
offer_variable: Optional[str] = None
|
||||
min_round: int = 1
|
||||
closing: bool = False
|
||||
requires: tuple = ()
|
||||
|
||||
|
||||
HOLD = CardSpec() # 스펙을 못 찾은 카드(테넌트 데모·회사 커스텀)의 폴백 — 기존 동작(설득만) 유지
|
||||
|
||||
|
||||
def settle_ceiling(context: Dict[str, Any]) -> float:
|
||||
"""이 협상에서 받아줄 수 있는 최고가 — 타결 판정선이자 카드 제안가의 상한.
|
||||
|
||||
견적 생성 시 세션에 박제한 done_ceiling_price(= 목표가 × (1 + 타결상한율)) — 목표가를 조금
|
||||
넘더라도 기존 단가보다 인하됐으면 타결시키기 위한 값. 박제가 없으면 목표가로 폴백한다.
|
||||
"""
|
||||
return float(context.get("done_ceiling_price") or context.get("target_price") or 0)
|
||||
|
||||
|
||||
def parse_offer_variable(script: Optional[str]) -> Optional[str]:
|
||||
"""스크립트가 제시하는 제안가 변수. 없으면 None(설득 카드).
|
||||
|
||||
변수가 여럿이면 마지막에 등장하는 것이 제안가다 — 카드 문장은 배경을 먼저 깔고 실제 제안을
|
||||
마지막에 하기 때문이다.
|
||||
"""
|
||||
found = [m.group(1) for m in _TOKEN_RE.finditer(script or "") if m.group(1) in OFFER_VARIABLES]
|
||||
return found[-1] if found else None
|
||||
|
||||
|
||||
def build_card_spec(script: Optional[str], tactic: Optional[dict] = None) -> CardSpec:
|
||||
"""스크립트 + tactic JSONB → CardSpec. tactic 이 비어 있으면 전부 기본값."""
|
||||
t = tactic or {}
|
||||
cited = {m.group(1) for m in _TOKEN_RE.finditer(script or "")}
|
||||
return CardSpec(
|
||||
# 파싱이 정본 카드 전부를 맞히므로 offer_variable 은 예외 카드용 override 로만 둔다.
|
||||
offer_variable=t.get("offer_variable") or parse_offer_variable(script),
|
||||
min_round=int(t.get("min_round") or 1),
|
||||
closing=bool(t.get("closing")),
|
||||
requires=tuple(sorted({_CONTEXT_REQUIRED_VARIABLES[v] for v in cited if v in _CONTEXT_REQUIRED_VARIABLES})),
|
||||
)
|
||||
|
||||
|
||||
def spec_from_context(context: Dict[str, Any], number: Optional[str]) -> CardSpec:
|
||||
"""세션 컨텍스트에 적재된 카드 스펙(card_specs)에서 꺼낸다. 없으면 HOLD 폴백.
|
||||
|
||||
스펙은 협상 시작 시 1회 적재된다(negotiation_context_loader) — 진행 중인 협상은
|
||||
카드 멘트가 도중에 바뀌어도 시작 시점 전술로 끝까지 간다.
|
||||
"""
|
||||
if not number:
|
||||
return HOLD
|
||||
raw = (context.get("card_specs") or {}).get(str(number))
|
||||
if not raw:
|
||||
return HOLD
|
||||
return CardSpec(
|
||||
offer_variable=raw.get("offer_variable"),
|
||||
min_round=int(raw.get("min_round") or 1),
|
||||
closing=bool(raw.get("closing")),
|
||||
requires=tuple(raw.get("requires") or ()),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Offer:
|
||||
"""확정된 제안 한 건 — 금액과 그 금액을 만든 재료를 함께 들고 다닌다.
|
||||
|
||||
멘트 치환이 재료를 다시 계산하지 않게 하기 위한 것 — 재계산하면 그 사이 갱신된
|
||||
prev_customer 를 읽어 문장이 자기모순이 된다.
|
||||
"""
|
||||
|
||||
price: int # 협력사에게 제시할 금액(수락 시 타결가)
|
||||
variable: str # 이 금액을 만든 멘트 변수
|
||||
prev_customer: int # 계산에 쓴 당사 직전 제안
|
||||
prev_partner: int # 계산에 쓴 협력사 제시가
|
||||
|
||||
|
||||
def record_offer(context: Dict[str, Any], offer: Offer) -> None:
|
||||
"""확정 제안을 세션에 기록한다 — 수락 판정용 금액과 멘트 치환용 재료를 한 자리에서 쓴다.
|
||||
|
||||
두 키를 항상 함께 써야 표시가와 타결가가 갈라지지 않으므로 기록 지점을 여기 하나로 묶는다.
|
||||
"""
|
||||
context["pending_counter_price"] = offer.price
|
||||
context["pending_offer"] = {
|
||||
"price": offer.price, "variable": offer.variable,
|
||||
"prev_customer": offer.prev_customer, "prev_partner": offer.prev_partner,
|
||||
}
|
||||
context["prev_customer_price"] = offer.price # 갑의 최신 포지션 — 다음 라운드 계산·역행 금지 기준
|
||||
|
||||
|
||||
def compute_offer_detail(spec: CardSpec, context: Dict[str, Any]) -> Optional[Offer]:
|
||||
"""카드가 제시할 금액 + 그 계산에 쓴 재료. 쓸 수 없는 상황이면 None."""
|
||||
price = int(float(context.get("input_price") or 0))
|
||||
prev_customer = int(float(context.get("prev_customer_price") or context.get("anchor_price") or 0))
|
||||
value = compute_offer(spec, context)
|
||||
if value is None:
|
||||
return None
|
||||
return Offer(price=value, variable=spec.offer_variable or "", prev_customer=prev_customer, prev_partner=price)
|
||||
|
||||
|
||||
def compute_offer(spec: CardSpec, context: Dict[str, Any]) -> Optional[int]:
|
||||
"""카드가 제시할 금액. 쓸 수 없는 상황이면 None → 호출부가 카드를 건너뛴다.
|
||||
|
||||
변수 공통 유효조건 (전부 만족해야 발동):
|
||||
· 값 ≤ 타결 상한가 — 받아줄 수 없는 금액은 부르지 않는다. 넘으면 깎지 않고 미발동
|
||||
· 값 < 협력사 제시가 — 이미 더 싸게 받았는데 더 비싼 값을 부를 이유가 없다
|
||||
· 값 ≥ 당사 직전 제안 — 역행 금지. 제안 시퀀스는 앵커→…→목표가로 단조 수렴해야 한다
|
||||
"""
|
||||
variable = spec.offer_variable
|
||||
if not variable:
|
||||
return None # 설득 카드 — 제시할 금액 없음
|
||||
calc = OFFER_VARIABLES.get(variable)
|
||||
if calc is None:
|
||||
return None # 미등록 변수(오타·구버전 카드)
|
||||
target = float(context.get("target_price") or 0)
|
||||
anchor = float(context.get("anchor_price") or 0)
|
||||
price = float(context.get("input_price") or 0)
|
||||
# 갑의 직전 포지션. 첫 카운터 전에는 앵커가 갑의 포지션이다.
|
||||
prev_customer = float(context.get("prev_customer_price") or anchor or 0)
|
||||
if target <= 0 or price <= 0:
|
||||
return None # 목표가·제시가 없이는 어떤 변수도 판정 불가
|
||||
|
||||
value = calc(target, anchor, price, prev_customer)
|
||||
if not value or value <= 0:
|
||||
return None # 재료 부족(앵커 미박제·직전 제안 없음)
|
||||
if value > settle_ceiling(context):
|
||||
return None # 타결 상한 초과 — 받아줄 수 없는 금액이라 지금 못 쓴다
|
||||
if variable in _MID_VARIABLES and value >= target:
|
||||
# 절충 계열은 목표가 미만일 때만 의미가 있다. 목표가 이상이면 "절반씩 나누자"면서 목표가를
|
||||
# 부르는 꼴이라 미발동 — 목표가 제시는 목표가 카드(최후통첩)가 할 일이다.
|
||||
return None
|
||||
if variable in ("target_price", "anchoring_price", "anchor_price"):
|
||||
# 원값 인용 변수 — 멘트엔 {target_price} 등 저장 원값이 그대로 나가므로, 반올림하면
|
||||
# 표시가≠타결가 미스매치가 난다(목표가 7652 멘트 → 7650 타결). 저장값 그대로 제시.
|
||||
offer = int(value)
|
||||
else:
|
||||
offer = int(value / 10 + 0.5) * 10 # 파생가(절충·중간) 10원 반올림 — 앵커·목표가 산정과 표기 통일
|
||||
if offer >= price:
|
||||
return None # 제시가가 이미 그 값 이하 → 부를 이유 없음
|
||||
if prev_customer and offer < prev_customer:
|
||||
return None # 역행 금지 — 한번 부른 금액 아래로 되돌아가지 않는다(같은 금액 재제시는 허용)
|
||||
return offer
|
||||
|
||||
|
||||
def available(spec: CardSpec, context: Dict[str, Any], *, closing_phase: bool = False) -> bool:
|
||||
"""지금 이 카드를 꺼낼 수 있는지 — 금액과 무관한 조건들.
|
||||
|
||||
· 이미 쓴 카드는 다시 안 나간다(전 카드 공통 규칙 — 협상카드/와일드카드 구분 없음)
|
||||
· 종결 전용 카드는 종결 국면에서만, 종결 국면에선 종결 전용 카드만
|
||||
· min_round 미만이면 아직 이르다
|
||||
· 스크립트가 인용한 세션-의존 변수(인터넷 최저가 등)가 결측이면 미발동 — 토큰 원형 노출 방지
|
||||
"""
|
||||
if spec.closing != closing_phase:
|
||||
return False
|
||||
if int(context.get("round") or 0) < spec.min_round:
|
||||
return False
|
||||
return all(context.get(key) for key in spec.requires)
|
||||
|
||||
|
||||
def playable(spec: CardSpec, context: Dict[str, Any], *, closing_phase: bool = False) -> bool:
|
||||
"""이 카드를 지금 실제로 플레이할 수 있는지 — available + (금액 카드는) 제안가 유효까지.
|
||||
|
||||
금액을 인용하는 카드(offer_variable 있음)는 그 금액을 못 부르는 상황이면 설득 폴백으로도
|
||||
내보내지 않는다 — 멘트에 무효한 금액(직전 제안보다 낮은 앵커, 제시가보다 높은 목표가)이
|
||||
글자로 박혀 나가 역행/모순 서사가 되기 때문. 설득 카드는 금액이 없으니 무관.
|
||||
"""
|
||||
if not available(spec, context, closing_phase=closing_phase):
|
||||
return False
|
||||
if not spec.offer_variable:
|
||||
return True
|
||||
return compute_offer(spec, context) is not None
|
||||
|
||||
|
||||
def is_played(context: Dict[str, Any], number: Optional[str]) -> bool:
|
||||
"""이 카드를 이 협상에서 이미 썼는지. 와일드 진입·종결·협상카드가 같은 이력을 본다."""
|
||||
return bool(number) and str(number) in (context.get("played_card_numbers") or [])
|
||||
|
||||
|
||||
def mark_played(context: Dict[str, Any], number: Optional[str]) -> None:
|
||||
"""카드를 실제로 내보낸 시점에 이력에 남긴다(노출되지 않은 후보는 남기지 않는다)."""
|
||||
if not number:
|
||||
return
|
||||
played = list(context.get("played_card_numbers") or [])
|
||||
if str(number) not in played:
|
||||
played.append(str(number))
|
||||
context["played_card_numbers"] = played
|
||||
@ -1,28 +0,0 @@
|
||||
"""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 로 폴백한다.
|
||||
"""
|
||||
...
|
||||
@ -21,18 +21,3 @@ class ICardScriptRepository(ABC):
|
||||
async def get_script_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
|
||||
"""카드코드(card.nego_cards.number)로 멘트(script 평문/마커)를 조회. 없으면 None."""
|
||||
...
|
||||
|
||||
async def get_card_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
"""멘트 + 메타 (script, tone, strategy_type) 조회 — LLM 표현층의 톤/전략 지시용.
|
||||
|
||||
기본 구현은 script 만 조회하고 메타는 None (파일 소스·구형 더블 호환).
|
||||
"""
|
||||
err, script = await self.get_script_by_number(cdb, number)
|
||||
return err, ((script, None, None) if script else None)
|
||||
|
||||
async def get_wild_card_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
|
||||
"""와일드카드(card.wild_cards.number) 멘트 조회 — 선택형 WC/종결 전술 발동용.
|
||||
|
||||
기본 구현은 미보유(None) — DB 어댑터만 실조회한다(더블 호환).
|
||||
"""
|
||||
return ErrorType.SUCCESS, None
|
||||
|
||||
@ -23,70 +23,12 @@ _SESSIONS = table(
|
||||
"sessions",
|
||||
column("session_id"), column("quotation_id"), column("item_id"), column("supplier_id"),
|
||||
column("qt_type"), column("target_price"), column("anchoring_price"),
|
||||
column("done_ceiling_price"), # 타결 상한가 — 견적 생성 시 박제(목표가×(1+타결상한율))
|
||||
column("qt_setting_id"),
|
||||
column("deleted"),
|
||||
schema="negotiation",
|
||||
)
|
||||
# 견적 설정 — card_count(협상 내 협상카드 사용 횟수 상한) 조회용.
|
||||
_QUOTATION_SETTINGS = table(
|
||||
"quotation_settings",
|
||||
column("qt_setting_id"), column("card_count"), column("deleted"),
|
||||
schema="quotation",
|
||||
)
|
||||
_ITEMS = table("items", column("item_id"), column("name"), column("price"), column("purchase_price"),
|
||||
column("company_id"), column("internet_lowest_price"), column("deleted"), schema="partner")
|
||||
# 고객사 설정(companies.settings) — 협상 기준가로 쓸 가격 컬럼을 여기서 정한다.
|
||||
_COMPANIES = table("companies", column("company_id"), column("settings"), column("deleted"), schema="company")
|
||||
|
||||
# 협상 기준가 후보 컬럼. 어느 컬럼을 고르든 공급사 화면 호칭은 '공급가'로 고정한다 —
|
||||
# 같은 돈을 고객사는 매입가·상품 단가 등으로 부르지만 챗은 공급사가 보는 화면이라
|
||||
# 공급사 관점 용어 하나만 쓴다. 회사 용어 사전(labels)은 관리자 화면 전용.
|
||||
_BASELINE_PRICE = "price"
|
||||
_BASELINE_PURCHASE = "purchase_price"
|
||||
_SUPPLIER_PRICE_LABEL = "공급가"
|
||||
|
||||
|
||||
def _resolve_baseline(settings: dict) -> str:
|
||||
"""회사 설정 → 협상 기준가로 쓸 items 컬럼명.
|
||||
|
||||
1순위는 관리자가 회사 설정에서 고른 값(features.nego_baseline_field).
|
||||
미설정 회사는 공급가가 기본이되, 공급가를 화면에서 감췄다면 그 회사는 공급가를 관리하지
|
||||
않는다는 뜻이므로 매입가로 폴백한다 — 설정 화면이 생기기 전에 만들어진 회사를 위한 안전망."""
|
||||
chosen = (settings.get("features") or {}).get("nego_baseline_field")
|
||||
if chosen in (_BASELINE_PRICE, _BASELINE_PURCHASE):
|
||||
return chosen
|
||||
hidden = set(settings.get("hidden_fields") or [])
|
||||
if "price" in hidden and "purchase_price" not in hidden:
|
||||
return _BASELINE_PURCHASE
|
||||
return _BASELINE_PRICE
|
||||
_SUPPLIERS = table("suppliers", column("supplier_id"), column("name"), column("total_revenue"), column("deleted"), schema="partner")
|
||||
_QUOTATIONS = table(
|
||||
"quotations",
|
||||
column("qt_id"), column("version_id"), column("supplier_type"), column("deleted"),
|
||||
schema="quotation",
|
||||
)
|
||||
_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("script"), column("tactic"), column("deleted"),
|
||||
schema="card",
|
||||
)
|
||||
_WILD_CARDS = table(
|
||||
"wild_cards",
|
||||
column("wild_card_id"), column("number"), column("script"), column("tactic"), column("deleted"),
|
||||
column("available"),
|
||||
schema="card",
|
||||
)
|
||||
_ITEMS = table("items", column("item_id"), column("price"), 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")
|
||||
# 상품↔협력사 매핑 (2026-07-07 신설): supply_type = 이 협력사가 이 상품을 공급하는 방식(SupplierType).
|
||||
_SUPPLIER_ITEMS = table(
|
||||
"supplier_items",
|
||||
@ -98,28 +40,12 @@ _SUPPLIER_ITEMS = table(
|
||||
class INegoContextCRUD(ABC):
|
||||
@abstractmethod
|
||||
async def get_session_row(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
"""세션 행 (qt_type, target_price, anchoring_price, done_ceiling_price, item_id, quotation_id, supplier_id). 없으면 None."""
|
||||
"""세션 행 (qt_type, target_price, anchoring_price, item_id, quotation_id, supplier_id). 없으면 None."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_item_baseline(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, Tuple[int, str, dict]]:
|
||||
"""협상 기준가·그 호칭·회사 용어 사전 (가격, 호칭, labels).
|
||||
|
||||
어느 컬럼을 기준가로 쓰는지는 회사 설정(features.nego_baseline_field)이 정한다.
|
||||
labels 는 companies.settings.labels 원본 — 협상 스크립트의 용어 토큰 치환에 쓴다.
|
||||
값이 없으면 (0, 호칭, {})."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_card_count(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[int]]:
|
||||
"""협상카드 사용 횟수 상한(quotation_settings.card_count) — 세션의 qt_setting_id 로 조인.
|
||||
설정이 없으면 None(호출부가 상한 미적용). 이 값이 협상 중 실제로 플레이 가능한 협상카드 수를 캡한다."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_item_lowest_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
"""상품 인터넷 최저가(items.internet_lowest_price — LPS 수집 대표값). 미수집이면 0.
|
||||
카드 스크립트 {internet_lowest_price} 치환용(NGC-008 등 시장가 인용 카드)."""
|
||||
async def get_item_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
"""품목 기준가(items.price). 없으면 0."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@ -127,22 +53,17 @@ class INegoContextCRUD(ABC):
|
||||
"""협력사 총매출액(suppliers.total_revenue — KTC 미러). 없으면 0.0."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_item_name(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, Optional[str]]:
|
||||
"""상품명(items.name). 없으면 None — 카드 스크립트 {product_name} 치환용."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, Optional[str]]:
|
||||
"""협력사명(suppliers.name). 없으면 None — 카드 스크립트 {partner_name} 치환용."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_supply_type(self, cdb: AsyncSession, supplier_id, item_id) -> Tuple[ErrorType, Optional[int]]:
|
||||
"""이 협력사가 이 상품을 공급하는 방식(supplier_items.supply_type: 0=none/1=유통/2=제조/3=총판).
|
||||
매핑이 없으면 None."""
|
||||
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
|
||||
async def count_item_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
"""상품에 연결된 협력사 수 — supplier_items 매핑 기준 distinct supplier."""
|
||||
@ -153,19 +74,12 @@ class INegoContextCRUD(ABC):
|
||||
"""상품에 연결된 협력사 수 — 협상 세션 이력 기준(supplier_items 매핑 부재 시 폴백)."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_quotation_card_numbers(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, tuple[list[tuple], list[tuple]]]:
|
||||
"""견적 version_id 에 연결된 (일반카드 행 목록, 와일드카드 행 목록). 없으면 빈 목록.
|
||||
행 = (number, script, tactic) — 스크립트 파싱 + tactic JSONB 로 카드 전술(CardSpec)을 만든다."""
|
||||
pass
|
||||
|
||||
|
||||
class NegoContextCRUD(INegoContextCRUD):
|
||||
async def get_session_row(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
try:
|
||||
query = (
|
||||
select(_SESSIONS.c.qt_type, _SESSIONS.c.target_price, _SESSIONS.c.anchoring_price,
|
||||
_SESSIONS.c.done_ceiling_price,
|
||||
_SESSIONS.c.item_id, _SESSIONS.c.quotation_id, _SESSIONS.c.supplier_id)
|
||||
.where(_SESSIONS.c.session_id == session_id, _SESSIONS.c.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
@ -178,61 +92,14 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def get_item_baseline(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, Tuple[int, str, dict]]:
|
||||
_fallback = (0, _SUPPLIER_PRICE_LABEL, {})
|
||||
async def get_item_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
try:
|
||||
# 상품 + 소속 고객사 설정 한 번에. 회사가 없어도(데이터 이상) 상품 행은 나오도록 outer join.
|
||||
query = (
|
||||
select(_ITEMS.c.price, _ITEMS.c.purchase_price, _COMPANIES.c.settings)
|
||||
.select_from(_ITEMS.outerjoin(_COMPANIES, _ITEMS.c.company_id == _COMPANIES.c.company_id))
|
||||
select(_ITEMS.c.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_baseline failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS or not rows:
|
||||
return err_type, _fallback
|
||||
# 컬럼이 2개 이상이면 execute 가 행 리스트를 준다(1개일 때만 스칼라 리스트).
|
||||
price, purchase_price, settings = rows[0]
|
||||
settings = settings if isinstance(settings, dict) else {}
|
||||
labels = settings.get("labels") or {}
|
||||
field = _resolve_baseline(settings)
|
||||
value = purchase_price if field == _BASELINE_PURCHASE else price
|
||||
return ErrorType.SUCCESS, (int(value or 0), _SUPPLIER_PRICE_LABEL, labels)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, _fallback
|
||||
|
||||
async def get_card_count(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[int]]:
|
||||
try:
|
||||
query = (
|
||||
select(_QUOTATION_SETTINGS.c.card_count)
|
||||
.select_from(
|
||||
_SESSIONS.join(
|
||||
_QUOTATION_SETTINGS,
|
||||
_QUOTATION_SETTINGS.c.qt_setting_id == _SESSIONS.c.qt_setting_id,
|
||||
)
|
||||
)
|
||||
.where(_SESSIONS.c.session_id == session_id,
|
||||
_SESSIONS.c.deleted == False, # noqa: E712
|
||||
_QUOTATION_SETTINGS.c.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_card_count 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 get_item_lowest_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
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_lowest_price failed.", raise_error=False)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_item_price 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])
|
||||
@ -255,36 +122,6 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0.0
|
||||
|
||||
async def get_item_name(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, Optional[str]]:
|
||||
try:
|
||||
query = (
|
||||
select(_ITEMS.c.name)
|
||||
.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_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 get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, Optional[str]]:
|
||||
try:
|
||||
query = (
|
||||
select(_SUPPLIERS.c.name)
|
||||
.where(_SUPPLIERS.c.supplier_id == supplier_id, _SUPPLIERS.c.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_supplier_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 get_supply_type(self, cdb: AsyncSession, supplier_id, item_id) -> Tuple[ErrorType, Optional[int]]:
|
||||
try:
|
||||
query = (
|
||||
@ -302,6 +139,21 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
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]:
|
||||
try:
|
||||
query = (
|
||||
@ -329,65 +181,3 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def get_quotation_card_numbers(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, tuple[list[tuple], list[tuple]]]:
|
||||
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, _NEGO_CARDS.c.script, _NEGO_CARDS.c.tactic)
|
||||
.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, _WILD_CARDS.c.script, _WILD_CARDS.c.tactic)
|
||||
.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
|
||||
# 협상 적용 여부(카드 설정 '적용 대기(수동)') — 꺼진 카드는 견적에 담겨 있어도 발동 금지
|
||||
_WILD_CARDS.c.available == True, # 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[0]), r[1], r[2]) for r in n_rows if r[0] is not None],
|
||||
[(str(r[0]), r[1], r[2]) for r in w_rows if r[0] is not None],
|
||||
)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, ([], [])
|
||||
|
||||
@ -10,16 +10,9 @@ import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from negotiation.cards.domain.tactics import (
|
||||
OFFER_VARIABLES, Offer, available, compute_offer_detail, is_played, mark_played, playable,
|
||||
record_offer, settle_ceiling, spec_from_context,
|
||||
)
|
||||
from negotiation.chat.service.script_repository import ScriptRepository
|
||||
|
||||
MAX_ROUNDS = 3 # config 미주입 시 폴백 (규칙 정본은 tenant config negotiation.max_counter_rounds)
|
||||
# 멘트에 찍히는 파생 가격 — 값이 다른 값에서 계산돼 나오는 것들(원값 인용 target/anchor 는 제외).
|
||||
_DERIVED_PRICE_VARIABLES = ("target_mid_price", "middle_price")
|
||||
|
||||
MAX_ROUNDS = 3
|
||||
_PRICE_MODES = ("price",)
|
||||
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
||||
|
||||
@ -29,9 +22,6 @@ _CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
||||
_SUCCESS_STEPS = ("협상완료", "결과제출")
|
||||
_FAILURE_STEPS = ("협상실패",)
|
||||
|
||||
# 카운터 제안(pending_counter_price) 수락으로 인정하는 선택 입력.
|
||||
_ACCEPT_INPUTS = ("예", "수락")
|
||||
|
||||
# 프론트는 표시용 문자열로 가격을 보낸다(예: "530,000원"). 천단위 콤마·통화기호("원")·공백 등
|
||||
# 숫자 외 문자를 제거하고 파싱한다. (콤마만 지우면 "원" 때문에 float() 가 실패해 가격 입력이
|
||||
# 영영 저장되지 않고 같은 step 에 머무는 버그가 났었다.)
|
||||
@ -49,39 +39,6 @@ def _parse_price(user_input: Any) -> Optional[float]:
|
||||
return price if price > 0 else None
|
||||
|
||||
|
||||
# 협상 스크립트가 쓰는 용어 토큰: {label_*} = 회사 용어(없으면 기본값).
|
||||
# 값은 negodata 용어 카탈로그(LABEL_CATALOG)의 base 와 같아야 화면·멘트 표기가 갈리지 않는다.
|
||||
_SCRIPT_LABELS = {
|
||||
"label_supplier": ("supplier", "협력사"),
|
||||
"label_target_price": ("target_price", "목표가"),
|
||||
"label_delivery_type": ("item.delivery_type", "배송 형태"),
|
||||
"label_delivery_type_1": ("delivery_type.1", "협력사배송"),
|
||||
"label_delivery_type_2": ("delivery_type.2", "지정택배배송"),
|
||||
"label_delivery_type_3": ("delivery_type.3", "픽업배송"),
|
||||
"label_product": ("item.name", "상품명"),
|
||||
}
|
||||
# 협상 기준가 호칭 — 공급사 화면 고정 용어. 회사 용어 사전(labels)을 타지 않는다(그건 관리자 화면 전용).
|
||||
# 실제 값은 loader 가 컨텍스트에 박제하고, DB 컨텍스트가 없는 데모/직접호출 경로만 이 폴백을 쓴다.
|
||||
_SUPPLIER_PRICE_LABEL = "공급가"
|
||||
# 조사 자동 보정: 토큰 뒤에 조사가 붙는 자리는 {label_supplier_를} 처럼 대표형을 적는다.
|
||||
# 회사가 바꾼 용어의 받침을 예측할 수 없어 스크립트에 조사를 고정할 수 없다("협력사를"/"공급업체을").
|
||||
_JOSA = {"은": ("은", "는"), "는": ("은", "는"), "이": ("이", "가"), "가": ("이", "가"),
|
||||
"을": ("을", "를"), "를": ("을", "를"), "과": ("과", "와"), "와": ("과", "와")}
|
||||
|
||||
|
||||
def _has_batchim(word: str) -> bool:
|
||||
last = word[-1] if word else ""
|
||||
return "가" <= last <= "힣" and (ord(last) - 0xAC00) % 28 != 0
|
||||
|
||||
|
||||
def _josa(word: str, form: str) -> str:
|
||||
"""단어 + 받침에 맞는 조사. form 은 대표형('를'·'는'·'가'·'와')."""
|
||||
pair = _JOSA.get(form)
|
||||
if not pair:
|
||||
return word
|
||||
return word + (pair[0] if _has_batchim(word) else pair[1])
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChatSession:
|
||||
session_id: str
|
||||
@ -115,9 +72,6 @@ class ChatEngine:
|
||||
self.rq_type = rq_type
|
||||
self.scripts = scripts_repo.load_scripts(rq_type)
|
||||
self.step_map = scripts_repo.client_step_mapping()
|
||||
# 결정 스택 규칙층(Phase 1): 와일드카드 진입 임계·라운드 상한을 테넌트 config 에서 읽는다.
|
||||
# (하드코딩 1.02/1.05/3 을 데이터화 — 고객사별로 튜닝 가능, 코드 수정 불필요)
|
||||
self.rules = scripts_repo.config.negotiation
|
||||
|
||||
# ---- public --------------------------------------------------------
|
||||
def start(self, session: ChatSession) -> StepView:
|
||||
@ -135,29 +89,21 @@ class ChatEngine:
|
||||
if price is None:
|
||||
return self._error(session, "가격을 숫자로 입력해 주세요.")
|
||||
session.context["input_price"] = price
|
||||
# 새 가격 제시 = 직전 카운터 제안 거절 확정 → 대기 중 카운터·그 재료 폐기.
|
||||
session.context.pop("pending_counter_price", None)
|
||||
session.context.pop("pending_offer", None)
|
||||
session.context["prev_partner_price"] = price
|
||||
# 협력사 첫 제시가 — 가격 수용률(첫 제시가 대비 양보율) 동적 계산의 기준값.
|
||||
session.context.setdefault("first_offer_price", price)
|
||||
session.context["round"] = session.context.get("round", 0) + 1
|
||||
nxt = self._default_next(node)
|
||||
elif mode in _CHOICE_MODES:
|
||||
# 와일드카드 1% 인하 제안을 수락("예")하면 합의가를 제안가(offer_1pct)로 확정한다.
|
||||
# (멘트에만 쓰이던 offer_1pct 가 input_price 에 반영되지 않아, 요약/입찰가가
|
||||
# 직전 제시가로 잡히던 버그 수정 — 수락 시 실제 합의가는 인하가다.)
|
||||
if session.step == "wild_card_1pct" and user_input == "예" and session.context.get("offer_1pct"):
|
||||
session.context["input_price"] = float(session.context["offer_1pct"])
|
||||
nxt = self._choice_next(node, user_input, session)
|
||||
else:
|
||||
nxt = self._default_next(node)
|
||||
|
||||
nxt = self._resolve(nxt, session)
|
||||
# 카운터 수락 일반 메커니즘: 카드/와일드카드가 제시한 카운터가(pending_counter_price)를
|
||||
# 협력사가 수락("예"/"수락")한 채 성공 스텝으로 전이하면 합의가 = 카운터가.
|
||||
# (구 offer_1pct 특수 분기의 일반화. 거절인데 성공 스텝으로 가는 경로 — 1% 거절 시
|
||||
# 원 제시가 수락 종결 — 는 카운터를 버리고 기존 input_price 로 타결한다.)
|
||||
if mode in _CHOICE_MODES and nxt in _SUCCESS_STEPS:
|
||||
pending = session.context.pop("pending_counter_price", None)
|
||||
session.context.pop("pending_offer", None)
|
||||
if pending and user_input in _ACCEPT_INPUTS:
|
||||
session.context["input_price"] = float(pending)
|
||||
return self._render(session, nxt)
|
||||
|
||||
# ---- transition ----------------------------------------------------
|
||||
@ -185,9 +131,9 @@ class ChatEngine:
|
||||
return nxt
|
||||
|
||||
def _eval_conditions(self, conds: List[dict], session: ChatSession) -> Optional[str]:
|
||||
"""KT 구매자 관점 조건 평가 (임계값은 config negotiation.* — 규칙층 데이터화).
|
||||
"""KT 구매자 관점 조건 평가.
|
||||
- 협력사 제시가 ≤ anchor → 우선협상(협상완료).
|
||||
- anchor 살짝 초과(≤ anchor×wildcard_entry_ratio) + 와일드카드 미사용 → 와일드카드로 인하 압박.
|
||||
- anchor 살짝 초과(≤ anchor*1.05) + 와일드카드 미사용 → 와일드카드로 인하 압박.
|
||||
- 설정 카드(action_space) 모두 소진 → 협상실패.
|
||||
- 그 외 → 가격협상(카드 1장 플레이 후 재제안).
|
||||
"""
|
||||
@ -200,59 +146,18 @@ class ChatEngine:
|
||||
cond = c.get("condition")
|
||||
ok = False
|
||||
if cond == "check_wildcard_entry":
|
||||
ok = (
|
||||
(not ctx.get("wildcard_used"))
|
||||
and anchor > 0
|
||||
and anchor < price
|
||||
and (
|
||||
price <= anchor * self.rules.wildcard_1pct_ratio
|
||||
or (bool(ctx.get("allow_selected_wildcards", True))
|
||||
and price <= anchor * self.rules.wildcard_entry_ratio)
|
||||
)
|
||||
)
|
||||
# 구간에 들어와도 실제로 낼 카드가 없으면(전부 종결 전용·사용됨·유효조건 미달) 이 조건은
|
||||
# 불충족으로 두고 다음 조건(우선협상·소진 판정)을 평가한다 — 여기서 매칭돼 버리면
|
||||
# 카드 소진 판정이 영영 돌지 않아, 빈 덱에서 쓴 카드를 또 꺼내는 무한 협상이 된다.
|
||||
if ok:
|
||||
probe = ChatSession(
|
||||
session_id=session.session_id, tenant_id=session.tenant_id,
|
||||
company_id=session.company_id, context=dict(ctx),
|
||||
)
|
||||
ok = self._pick_wildcard(probe) != "가격협상"
|
||||
ok = (not ctx.get("wildcard_used")) and anchor < price <= anchor * 1.05
|
||||
elif cond == "check_is_supplier_type_c":
|
||||
ok = False # 공급사 유형 미보유 (PoC 단순화)
|
||||
elif cond == "check_price_match": # = 우선협상: 제시가가 앵커가 이하
|
||||
ok = anchor > 0 and price <= anchor
|
||||
elif cond == "check_iteration_limit": # 협상 라운드 상한 또는 카드 소진 → 종결 국면
|
||||
# round 는 매 가격입력마다 증가(기존가격제시=1). 카운터제안이 상한을 넘거나 카드가
|
||||
# 소진되면 곧장 실패가 아니라 **종결 국면**으로 처리한다(실제 MD 협상 방식):
|
||||
# ① 아직 종결 전술을 안 썼으면 → 가격협상으로 보내되 force_closing 마킹
|
||||
# (ChatService 가 종결 전술 — 중간값 절충/최후통첩 — 을 강제 발동)
|
||||
# ② 종결 전술까지 소진(closing_played)이면 → 최종 제시가 ≤ target 은 타결,
|
||||
# 초과는 결렬(협상실패) — "목표가 초과 타결 금지" 가드레일과 정합.
|
||||
elif cond == "check_iteration_limit": # 협상 라운드 상한 또는 카드 소진
|
||||
# round 는 매 가격입력마다 증가(기존가격제시=1). 그 이후 카운터제안이 MAX_ROUNDS 회를
|
||||
# 넘으면 종료한다. 카드선택(RL)이 실패(state ValueError)해도 used_action_ids 가 안 늘어
|
||||
# 카드 소진 조건만으로는 종료되지 않으므로, 라운드 상한을 독립적으로 둬 무한 가격입력을 막는다.
|
||||
# (선행 chat_server 의 `iteration >= 3` 와 동일한 안전장치.)
|
||||
counter_rounds = max(0, ctx.get("round", 0) - 1)
|
||||
# 담은 협상카드 중 지금 낼 수 있는 게 하나도 없으면(사용됨·발동조건 미달 — 예:
|
||||
# 시장가 인용 카드인데 최저가 결측) 장수와 무관하게 소진으로 본다 — 안 그러면
|
||||
# 선택 마스크가 전부 막힌 채 폴백이 부적합 카드를 억지로 꺼낸다(토큰 노출).
|
||||
selected = ctx.get("selected_nego_card_numbers") or []
|
||||
none_playable = bool(selected) and not any(
|
||||
not is_played(ctx, n) and playable(spec_from_context(ctx, n), ctx)
|
||||
for n in selected
|
||||
)
|
||||
exhausted = (
|
||||
counter_rounds >= self.rules.max_counter_rounds
|
||||
or (cards_total > 0 and cards_used >= cards_total)
|
||||
or none_playable
|
||||
)
|
||||
if exhausted:
|
||||
# 타결선은 목표가가 아니라 타결 상한가(견적 생성 시 박제) — 목표가를 넘어도
|
||||
# 상한 이내면 타결한다.
|
||||
ceiling = settle_ceiling(ctx)
|
||||
if not ctx.get("closing_played"):
|
||||
ctx["force_closing"] = True
|
||||
return "가격협상"
|
||||
return "협상완료" if (ceiling > 0 and price <= ceiling) else c.get("next")
|
||||
ok = False
|
||||
ok = counter_rounds >= MAX_ROUNDS or (cards_total > 0 and cards_used >= cards_total)
|
||||
elif cond == "default":
|
||||
ok = True
|
||||
if ok:
|
||||
@ -260,45 +165,18 @@ class ChatEngine:
|
||||
return "가격협상"
|
||||
|
||||
def _pick_wildcard(self, session: ChatSession) -> str:
|
||||
"""앵커가에 아주 근접(≤ anchor×wildcard_1pct_ratio)한 구간에서만 1% 인하 요청(wild_card_1pct)으로
|
||||
앵커가 이하로 유도한다. 그 외 구간은 견적에서 선택한 와일드카드의 전술로 카운터하고,
|
||||
낼 카드가 없으면 일반 가격협상(카드 플레이)으로 돌린다.
|
||||
"""앵커가 살짝 초과 구간에서 인하 압박 카드 선택.
|
||||
- 앵커가에 아주 근접(≤ anchor*1.02): 1% 인하 요청(wild_card_1pct) → 앵커가 이하로 유도.
|
||||
- 그 외: 목표 매입가 맞춰달라(wild_card_budget).
|
||||
"""
|
||||
ctx = session.context
|
||||
price = ctx.get("input_price", 0)
|
||||
anchor = ctx.get("anchor_price", 0)
|
||||
target = ctx.get("target_price", 0)
|
||||
if anchor > 0 and price <= anchor * self.rules.wildcard_1pct_ratio:
|
||||
offer_1pct = int(price * 0.99 / 10 + 0.5) * 10 # 1% 인하가 — 10원 반올림(앵커·카운터와 통일)
|
||||
# 제안가 공통 유효조건(≤목표가 · <제시가 · 직전 당사 제안 이상=역행 금지)은 시스템 1% 카드에도
|
||||
# 동일하게 건다. 기본 앵커 밴드에선 수학적으로 항상 통과하지만 극단 데이터를 방어한다.
|
||||
prev_customer = ctx.get("prev_customer_price") or 0
|
||||
if 0 < offer_1pct < price and (target <= 0 or offer_1pct <= target) and offer_1pct >= prev_customer:
|
||||
# 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
|
||||
# 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
|
||||
ctx["wildcard_used"] = True
|
||||
ctx["offer_1pct"] = offer_1pct
|
||||
record_offer(ctx, Offer(price=offer_1pct, variable="offer_1pct",
|
||||
prev_customer=int(prev_customer or anchor), prev_partner=int(price)))
|
||||
if anchor > 0 and price <= anchor * 1.02:
|
||||
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가
|
||||
return "wild_card_1pct"
|
||||
# 1.02 초과 ~ entry(1.05) 구간: 견적에서 선택한 와일드카드의 전술로 카운터 제시.
|
||||
# (구현 전에는 이 구간이 일반 가격협상으로 회귀해 선택형 WC 가 영영 발동하지 않던 갭.)
|
||||
if anchor > 0 and price <= anchor * self.rules.wildcard_entry_ratio:
|
||||
for number in (ctx.get("selected_wild_card_numbers") or []):
|
||||
number = str(number)
|
||||
spec = spec_from_context(ctx, number)
|
||||
# 종결 전용 카드(최종 통보·중간값 절충)는 여기서 안 꺼낸다 — 종결 국면의 마지막 한 방으로 예약.
|
||||
# 이미 쓴 카드도 제외(같은 멘트 반복 방지).
|
||||
if not available(spec, ctx) or is_played(ctx, number):
|
||||
continue
|
||||
offer = compute_offer_detail(spec, ctx)
|
||||
if offer is not None:
|
||||
ctx["wildcard_used"] = True
|
||||
record_offer(ctx, offer)
|
||||
ctx["active_wild_card_number"] = number
|
||||
mark_played(ctx, number)
|
||||
return "wild_card_dynamic"
|
||||
return "가격협상"
|
||||
return "wild_card_budget"
|
||||
|
||||
# ---- render --------------------------------------------------------
|
||||
def vars_for(self, session: ChatSession) -> Dict[str, Any]:
|
||||
@ -307,109 +185,26 @@ class ChatEngine:
|
||||
out = {}
|
||||
if "input_price" in ctx:
|
||||
out["input_price"] = int(ctx["input_price"])
|
||||
# 목표가/앵커가: 엔진 내부 파일 스크립트는 {target}/{anchor}, negodata 카드 에디터는
|
||||
# {target_price}/{anchor_price}(variables.ts) 를 쓴다 — 양쪽 이름 모두 채워 치환 누락 방지.
|
||||
if "target_price" in ctx:
|
||||
out["target"] = out["target_price"] = int(ctx["target_price"])
|
||||
out["target"] = int(ctx["target_price"])
|
||||
if "anchor_price" in ctx:
|
||||
# anchoring_price = DB 시드 기본 카드/sessions 컬럼 표기, anchor_price = 카드 에디터 표기.
|
||||
out["anchor"] = out["anchor_price"] = out["anchoring_price"] = int(ctx["anchor_price"])
|
||||
# 용어 토큰 — 회사 용어 사전(labels)이 있으면 그 단어, 없으면 카탈로그 기본값.
|
||||
# 조사가 붙는 자리를 위해 {label_supplier_를} 같은 파생 키도 함께 만든다.
|
||||
labels = ctx.get("labels") or {}
|
||||
for token, (label_key, fallback) in _SCRIPT_LABELS.items():
|
||||
word = labels.get(label_key) or fallback
|
||||
out[token] = word
|
||||
for form in ("는", "가", "를", "와"):
|
||||
out[f"{token}_{form}"] = _josa(word, form)
|
||||
# 기준가 호칭은 회사 용어가 아니라 공급사 관점 고정 — loader 박제값(없으면 '공급가').
|
||||
price_word = str(ctx.get("item_price_label") or _SUPPLIER_PRICE_LABEL)
|
||||
out["label_item_price"] = price_word
|
||||
for form in ("는", "가", "를", "와"):
|
||||
out[f"label_item_price_{form}"] = _josa(price_word, form)
|
||||
# 카드 에디터 카탈로그의 협력사명/상품명(partner_name·product_name) 치환.
|
||||
if ctx.get("partner_name"):
|
||||
out["partner_name"] = str(ctx["partner_name"])
|
||||
if ctx.get("product_name"):
|
||||
out["product_name"] = str(ctx["product_name"])
|
||||
out["anchor"] = int(ctx["anchor_price"])
|
||||
if "offer_1pct" in ctx:
|
||||
out["offer_1pct"] = int(ctx["offer_1pct"])
|
||||
# 인터넷 최저가: LPS 대표값(items.internet_lowest_price). 카드는 {internet_lowest_price},
|
||||
# 라벨 매핑(variable_mapping.json)은 internet_min_price 를 쓰므로 target/anchor 처럼 양쪽 이름 모두 채운다.
|
||||
# 미수집(0/없음)이면 키를 만들지 않는다 — 원형 유지 → 허위 시장가 인용 방지(NGC-008 은 값 있을 때만 유효).
|
||||
ilp = ctx.get("internet_lowest_price") or 0
|
||||
if ilp > 0:
|
||||
out["internet_lowest_price"] = out["internet_min_price"] = int(ilp)
|
||||
# 전술 카운터 변수(카드 시드 멘트의 가격 변수) — tactics.OFFER_VARIABLES 산식과 동일 정의.
|
||||
anchor = ctx.get("anchor_price") or 0
|
||||
target = ctx.get("target_price") or 0
|
||||
# 표시 기준값 — 제안이 확정된 턴이면 그 계산에 쓴 재료(pending_offer)를 쓴다.
|
||||
# prev_customer_price 는 확정 즉시 새 제안가로 갱신되므로, 그대로 읽으면 멘트가
|
||||
# "당사 제안과 귀사 제안의 절반이 당사 제안" 같은 자기모순이 된다.
|
||||
pending_offer = ctx.get("pending_offer") or {}
|
||||
prev_customer = int(pending_offer.get("prev_customer") or ctx.get("prev_customer_price") or anchor or 0)
|
||||
partner_price = int(pending_offer.get("prev_partner") or ctx.get("prev_partner_price") or ctx.get("input_price") or 0)
|
||||
offer_price = int(pending_offer.get("price") or ctx.get("pending_counter_price") or 0)
|
||||
offer_variable = pending_offer.get("variable") or ""
|
||||
if prev_customer:
|
||||
out["prev_customer_price"] = prev_customer
|
||||
if partner_price:
|
||||
out["prev_partner_price"] = partner_price
|
||||
if offer_price:
|
||||
out["counter_price"] = offer_price
|
||||
# 파생 가격(절충가·중간가) — 제안가로 확정된 변수는 그 금액을 그대로 쓴다(멘트에 보이는 금액과
|
||||
# 수락 시 타결가는 항상 같아야 한다). 나머지는 참고 인용이므로 tactics 산식으로 채운다.
|
||||
# 산식을 여기 복사해 두면 갱신 시점 차이로 표시가와 제안가가 갈라지므로 정의를 호출만 한다.
|
||||
# 어느 변수가 제안가인지 모르는 진행 중 세션(구버전 기록)은 종전대로 전부 제안가로 고정한다.
|
||||
for name in _DERIVED_PRICE_VARIABLES:
|
||||
if offer_price and (name == offer_variable or not offer_variable):
|
||||
out[name] = offer_price
|
||||
continue
|
||||
value = OFFER_VARIABLES[name](target, anchor, partner_price, prev_customer)
|
||||
if value:
|
||||
out[name] = int(value / 10 + 0.5) * 10 # 10원 반올림 — compute_offer 와 동일
|
||||
# 인하율 = (협상 기준가 - 제시가) / 기준가 * 100. 기준가 없으면 미표시(0.0).
|
||||
# 제시가가 기준가보다 높으면(인상 제시) 음수가 나오는데, "-1.3% 인하된 금액" 같은
|
||||
# 모순 표현이 되므로 discount_rate 는 0 미만 금지하고, 인상/동일/인하를 구분한
|
||||
# 문구는 discount_phrase 로 별도 제공한다(가격협상_확인 멘트가 사용).
|
||||
# 기준가 호칭은 공급사 화면 고정 용어('공급가') — loader 가 박제한 값.
|
||||
# 인하율 = (기존 공급가 - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
|
||||
base = ctx.get("item_price") or 0
|
||||
label = ctx.get("item_price_label") or _SUPPLIER_PRICE_LABEL
|
||||
if base > 1 and "input_price" in ctx:
|
||||
rate = ((base - ctx["input_price"]) / base) * 100
|
||||
out["discount_rate"] = f"{max(0.0, rate):.1f}"
|
||||
if rate >= 0.05:
|
||||
out["discount_phrase"] = f"기존 {label} 대비 약 **{rate:.1f}%** 인하된 금액입니다. "
|
||||
elif rate <= -0.05:
|
||||
out["discount_phrase"] = (
|
||||
f"기존 {label}(**{int(base)}원**)보다 약 **{abs(rate):.1f}%** 높은 금액입니다. ")
|
||||
else:
|
||||
out["discount_phrase"] = f"기존 {_josa(label, '와')} 동일한 수준의 금액입니다. "
|
||||
out["discount_rate"] = f"{((base - ctx['input_price']) / base) * 100:.1f}"
|
||||
else:
|
||||
out["discount_rate"] = "0.0"
|
||||
out["discount_phrase"] = ""
|
||||
return out
|
||||
|
||||
def _vars(self, session: ChatSession) -> Dict[str, Any]:
|
||||
return self.vars_for(session)
|
||||
|
||||
def render_step(self, session: ChatSession, step_key: str) -> StepView:
|
||||
"""지정 스텝으로 전이·렌더 (공개) — ChatService 가 카드 카운터 제시 시
|
||||
가격협상 → 가격협상_카운터로 스텝을 전환할 때 사용한다."""
|
||||
return self._render(session, step_key)
|
||||
|
||||
def _render(self, session: ChatSession, step_key: Optional[str]) -> StepView:
|
||||
if not step_key or step_key not in self.scripts:
|
||||
return self._error(session, f"다음 단계를 찾을 수 없습니다: {step_key}")
|
||||
# 가드레일(최후 방어선): 구매자 대리는 타결 상한가를 넘겨 타결하지 않는다.
|
||||
# 상한 = 견적 생성 시 박제한 done_ceiling_price(목표가×(1+타결상한율)), 미박제면 목표가.
|
||||
# 목표가를 조금 넘어도 상한 이내면 타결이 정상이므로 여기서 뒤집지 않는다.
|
||||
# 상한까지 넘은 경우만 결렬로 강제 전환한다.
|
||||
if step_key in _SUCCESS_STEPS and self.rq_type == "재협상":
|
||||
ctx = session.context
|
||||
ceiling = settle_ceiling(ctx)
|
||||
if ceiling > 0 and ctx.get("input_price", 0) > ceiling:
|
||||
step_key = "협상실패"
|
||||
node = self.scripts[step_key]
|
||||
session.step = step_key
|
||||
chat_end = bool(node.get("chat_end"))
|
||||
@ -422,14 +217,11 @@ class ChatEngine:
|
||||
elif step_key in _FAILURE_STEPS:
|
||||
session.context["final_outcome"] = "failure"
|
||||
outcome = session.context.get("final_outcome") if chat_end else None
|
||||
# 선택지도 스크립트와 같은 변수 치환을 태운다 — 배송형태 보기가 회사 용어({label_delivery_type_1} 등)라
|
||||
# 치환을 건너뛰면 사용자에게 토큰 원문이 그대로 보인다.
|
||||
step_vars = self._vars(session)
|
||||
return StepView(
|
||||
step=step_key,
|
||||
script=self.repo.format_script(node.get("script", ""), step_vars),
|
||||
script=self.repo.format_script(node.get("script", ""), self._vars(session)),
|
||||
input_mode=node.get("next_input_mode", "null"),
|
||||
input_options=[self.repo.format_script(o, step_vars) for o in node.get("input_options", [])],
|
||||
input_options=node.get("input_options", []),
|
||||
chat_end=bool(node.get("chat_end")),
|
||||
client_step=self.step_map.get(step_key, step_key),
|
||||
needs_card_selection=(step_key == "가격협상"),
|
||||
@ -438,13 +230,9 @@ class ChatEngine:
|
||||
)
|
||||
|
||||
def _error(self, session: ChatSession, msg: str) -> StepView:
|
||||
# 에러 재렌더도 정상 렌더와 같은 변수 치환을 태운다 — 여기만 raw 로 두면
|
||||
# 가격 오입력 시 옵션 버튼에 {label_*} 토큰이 그대로 노출된다.
|
||||
node = self.scripts.get(session.step, {})
|
||||
step_vars = self._vars(session)
|
||||
return StepView(
|
||||
step=session.step, script=self.repo.format_script(node.get("script", ""), step_vars),
|
||||
input_mode=node.get("next_input_mode", "null"),
|
||||
input_options=[self.repo.format_script(o, step_vars) for o in node.get("input_options", [])],
|
||||
step=session.step, script=node.get("script", ""),
|
||||
input_mode=node.get("next_input_mode", "null"), input_options=node.get("input_options", []),
|
||||
chat_end=session.ended, client_step=self.step_map.get(session.step, session.step), error=msg,
|
||||
)
|
||||
|
||||
@ -1,149 +0,0 @@
|
||||
"""InputInterpreter — 협력사 자유 발화를 대화 단계 기대 입력으로 구조화 (Phase 3 이해층).
|
||||
|
||||
원칙: "숫자와 결정은 결정론이, 말은 LLM 이" (ScriptNaturalizer 와 동일 철학) —
|
||||
- LLM 의 역할은 ① 의도 분류(choice|price|unknown) ② 가격 '표현의 위치' 찾기까지다.
|
||||
가격 숫자 계산은 LLM 출력이 아니라 결정론 한국어 가격 파서(parse_korean_price)가 수행한다.
|
||||
- 검증: choice 는 허용 선택지 목록에 철자 그대로 있어야 하고, price_text 는 사용자 원문의
|
||||
부분 문자열이어야 한다(환각 차단). 하나라도 어긋나면 None → 호출부가 원문 그대로 폴백
|
||||
(기존 엔진의 재질문 흐름 유지 — 협상은 절대 멈추지 않는다).
|
||||
|
||||
게이트: tenant llm.enabled + 전역 자격증명(ScriptNaturalizer 와 동일). 미설정이면 무동작 —
|
||||
기존 버튼/정형 입력 경로는 그대로 두고, 자유 텍스트일 때만 해석을 시도한다.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, List, Optional
|
||||
|
||||
from common.logger import LOG
|
||||
from negotiation.profiling.config import LlmCredentials
|
||||
|
||||
# 정형 가격 입력(버튼/필드) — LLM 없이 기존 결정론 경로로 처리 가능한 형태.
|
||||
SIMPLE_PRICE_RE = re.compile(r"\s*[\d,]+(\.\d+)?\s*원?\s*")
|
||||
|
||||
# 한국어 단위 (큰 단위 → 작은 단위 순서로 등장한다고 가정: "1만 2천 500원")
|
||||
_KOREAN_UNITS = {"억": 100_000_000, "만": 10_000, "천": 1_000, "백": 100}
|
||||
_PRICE_TOKEN_RE = re.compile(r"[\d.억만천백]+")
|
||||
|
||||
|
||||
def parse_korean_price(text: str) -> Optional[float]:
|
||||
"""가격 표현 문자열 → 숫자 (결정론). "10,500원"→10500, "1만 500원"→10500, "만원"→10000,
|
||||
"1.5만"→15000, "3만2천원"→32000. 해석 불가/0 이하 → None.
|
||||
"""
|
||||
t = (text or "").replace(",", "").replace(" ", "").replace("원", "").strip()
|
||||
if not t:
|
||||
return None
|
||||
if re.fullmatch(r"\d+(\.\d+)?", t):
|
||||
v = float(t)
|
||||
return v if v > 0 else None
|
||||
if not re.fullmatch(r"[\d.억만천백]+", t):
|
||||
return None # 단위·숫자 외 문자 포함 → 해석 불가(안전 폴백)
|
||||
total, num = 0.0, ""
|
||||
for ch in t:
|
||||
if ch.isdigit() or ch == ".":
|
||||
num += ch
|
||||
else: # 단위 문자
|
||||
try:
|
||||
n = float(num) if num else 1.0 # "만원" = 1만
|
||||
except ValueError:
|
||||
return None
|
||||
total += n * _KOREAN_UNITS[ch]
|
||||
num = ""
|
||||
if num:
|
||||
try:
|
||||
total += float(num) # 잔여 숫자: "1만500" 의 500
|
||||
except ValueError:
|
||||
return None
|
||||
return total if total > 0 else None
|
||||
|
||||
|
||||
@dataclass
|
||||
class InterpretedInput:
|
||||
kind: str # "choice" | "price"
|
||||
value: str # ChatEngine.advance 에 그대로 전달할 문자열 ("예" / "10500")
|
||||
source: str # 판단 근거(선택지 원문 또는 가격 표현 원문) — 로깅/투명성용
|
||||
|
||||
|
||||
_SYSTEM = """너는 B2B 구매 협상 챗봇의 입력 해석기다. 협력사(사용자)의 자유 발화를 현재 대화 단계가 기대하는 입력으로 구조화한다.
|
||||
|
||||
규칙 (하나라도 어기면 출력은 폐기된다):
|
||||
- 출력은 JSON 하나만: {"intent": "choice"|"price"|"unknown", "choice": "<선택지 철자 그대로>"|null, "price_text": "<원문 속 가격 표현 그대로>"|null}
|
||||
- choice 는 발화의 '의미'를 선택지 중 하나에 대응시켜, 그 선택지 문자열을 철자 그대로 복사한다.
|
||||
예) 선택지 ["예","아니오"]: "네 접니다"/"맞습니다"/"진행해주세요"/"동의합니다" → "예",
|
||||
"아닌데요"/"제가 아닙니다"/"어렵습니다"/"거절하겠습니다" → "아니오"
|
||||
- 사용자가 구체적 가격을 제시/역제안하면 intent=price. price_text 는 반드시 사용자 원문에 등장한
|
||||
표현을 그대로 복사한다(예: "10,500원", "1만 500원"). 숫자를 계산하거나 변형하지 마라.
|
||||
- 발화가 어느 선택지의 의미인지 정말 판단할 수 없거나 주제와 무관할 때만 intent=unknown."""
|
||||
|
||||
|
||||
def _default_llm_call(messages: List[dict]) -> dict:
|
||||
"""기본 LLM 호출(동기) — 전역 자격증명으로 chat_json. 테스트에서 주입 대체 지점."""
|
||||
from negotiation.profiling.infra.llm_adapter import chat_json
|
||||
|
||||
return chat_json(messages, temperature=0.0, max_tokens=200)
|
||||
|
||||
|
||||
class InputInterpreter:
|
||||
def __init__(self, llm_call: Optional[Callable[[List[dict]], dict]] = None,
|
||||
timeout_seconds: float = 6.0):
|
||||
self._llm_call = llm_call or _default_llm_call
|
||||
self._timeout = timeout_seconds
|
||||
|
||||
@staticmethod
|
||||
def available() -> bool:
|
||||
"""전역 LLM 자격증명이 설정돼 있는가 (테넌트 enabled 게이트는 호출부 몫)."""
|
||||
return LlmCredentials.from_config().is_configured()
|
||||
|
||||
async def interpret(self, user_input: str, *, input_mode: str,
|
||||
input_options: Optional[List[str]] = None,
|
||||
step_script: Optional[str] = None) -> Optional[InterpretedInput]:
|
||||
"""자유 발화 → 기대 입력. 검증 불통과/실패/타임아웃 시 None(호출부 원문 폴백).
|
||||
|
||||
step_script: 직전 봇 질문(맥락) — "네 접니다" 같은 발화는 질문 없이는 의도 판단이
|
||||
애매해 unknown 이 되므로, 무엇에 대한 답인지 함께 준다.
|
||||
"""
|
||||
text = (user_input or "").strip()
|
||||
options = [str(o) for o in (input_options or [])]
|
||||
if not text:
|
||||
return None
|
||||
payload = {
|
||||
"현재 단계 기대 입력": "가격(숫자)" if input_mode == "price" else "선택지 중 하나",
|
||||
"선택지": options,
|
||||
"사용자 발화": text,
|
||||
}
|
||||
if step_script:
|
||||
payload["직전 봇 질문"] = step_script[:300]
|
||||
messages = [
|
||||
{"role": "system", "content": _SYSTEM},
|
||||
{"role": "user", "content": json.dumps(payload, ensure_ascii=False) + "\n\nJSON 으로만 답하라."},
|
||||
]
|
||||
try:
|
||||
result = await asyncio.wait_for(asyncio.to_thread(self._llm_call, messages), self._timeout)
|
||||
except Exception as ex: # 타임아웃 포함 — 원문 폴백
|
||||
LOG.w(f"[InputInterpreter] LLM 호출 실패(원문 폴백): {ex}")
|
||||
return None
|
||||
if not isinstance(result, dict):
|
||||
return None
|
||||
|
||||
intent = result.get("intent")
|
||||
if intent == "choice":
|
||||
choice = result.get("choice")
|
||||
# 결정: 선택지 목록에 철자 그대로 있어야만 채택 (LLM 이 지어낸 분기 차단).
|
||||
if isinstance(choice, str) and choice in options:
|
||||
return InterpretedInput(kind="choice", value=choice, source=choice)
|
||||
LOG.w(f"[InputInterpreter] 검증 실패: choice={choice!r} ∉ {options}")
|
||||
return None
|
||||
if intent == "price":
|
||||
span = result.get("price_text")
|
||||
# 환각 차단: 가격 표현은 사용자 원문의 부분 문자열이어야 한다.
|
||||
if not isinstance(span, str) or not span.strip() or span.strip() not in text:
|
||||
LOG.w(f"[InputInterpreter] 검증 실패: price_text={span!r} 가 원문에 없음")
|
||||
return None
|
||||
price = parse_korean_price(span.strip()) # 숫자 계산은 결정론 파서가
|
||||
if price is None:
|
||||
LOG.w(f"[InputInterpreter] 검증 실패: 가격 해석 불가 span={span!r}")
|
||||
return None
|
||||
return InterpretedInput(kind="price", value=str(int(price)), source=span.strip())
|
||||
return None # unknown → 원문 폴백(엔진 재질문)
|
||||
@ -19,7 +19,6 @@ from typing import Optional
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import DBType, DBWRType, ErrorType
|
||||
from common.logger import LOG
|
||||
from negotiation.cards.domain.tactics import build_card_spec
|
||||
from negotiation.chat.infra.repository.nego_context_crud import INegoContextCRUD, NegoContextCRUD
|
||||
from negotiation.qtable.domain.model.snapshot import PartnerType
|
||||
|
||||
@ -28,7 +27,8 @@ _ONE_TO_ONE_QT_TYPES = (1, 3)
|
||||
|
||||
# 유통 코드: SupplierType(1=distribution 유통, 2=manufacture 제조, 3=sole_agency 총판)
|
||||
# → 테넌트 code_map 키(A/B/C). 제조→A, 총판→B, 유통→C (0=none/NULL 은 미지정 → 호출부 기본값).
|
||||
# 소스: partner.supplier_items.supply_type(이 협력사×이 상품 매핑).
|
||||
# 소스 우선순위: partner.supplier_items.supply_type(이 협력사×이 상품 매핑, 2026-07-07 신설)
|
||||
# → quotations.supplier_type(재견적 1:1 견적 기록 — 매핑 부재 시 폴백).
|
||||
_SUPPLIER_TYPE_TO_CODE = {2: "A", 3: "B", 1: "C"}
|
||||
|
||||
|
||||
@ -39,22 +39,10 @@ class NegotiationDbContext:
|
||||
rq_type: str # 재협상(1:1) | 재견적(1:N) — sessions.qt_type 으로 판별
|
||||
target_price: int # 목표 매입가(원) — sessions.target_price
|
||||
anchor_price: int # 앵커링가 — sessions.anchoring_price(생성 시 박제). 없으면 target(무할인 폴백)
|
||||
done_ceiling_price: int # 타결 상한가 — sessions.done_ceiling_price(생성 시 박제). 없으면 target
|
||||
item_price: int # 협상 기준가(고객사가 관리하는 가격 — 공급가 또는 매입가) — 인하율 멘트용. 없으면 0
|
||||
item_price_label: str # 협상 멘트에서 기준가를 부르는 말(회사 용어 설정 → 없으면 카탈로그 기본값)
|
||||
labels: dict # 회사 용어 사전(companies.settings.labels) — 스크립트 {label_*} 토큰 치환용
|
||||
internet_lowest_price: int # 인터넷 최저가(items.internet_lowest_price, LPS 대표값) — 카드 {internet_lowest_price} 치환용. 미수집이면 0
|
||||
partner_name: Optional[str] # 협력사명(suppliers.name) — 카드 {partner_name} 치환용. 없으면 None
|
||||
product_name: Optional[str] # 상품명(items.name) — 카드 {product_name} 치환용. 없으면 None
|
||||
item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0
|
||||
partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE
|
||||
revenue_amount: float # 매출액(원) — suppliers.total_revenue(KTC 미러). 없으면 0
|
||||
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)
|
||||
card_count: Optional[int] # 협상카드 사용 횟수 상한(quotation_settings.card_count). None=상한 미적용
|
||||
# 카드번호 → 전술 {offer_variable, min_round, closing}. 스크립트 파싱 + tactic JSONB 로 시작 시 1회 확정 —
|
||||
# 진행 중 협상은 카드 멘트가 도중에 바뀌어도 시작 시점 전술로 끝까지 간다(세션 컨텍스트에 박제).
|
||||
card_specs: dict
|
||||
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type → quotations.supplier_type. 미지정 시 None
|
||||
|
||||
|
||||
class NegotiationContextLoader:
|
||||
@ -74,10 +62,8 @@ class NegotiationContextLoader:
|
||||
err, row = await self.crud.get_session_row(s, sid)
|
||||
if err != ErrorType.SUCCESS or row is None:
|
||||
return None
|
||||
qt_type, target_price, anchoring_price, done_ceiling_price, item_id, quotation_id, supplier_id = row
|
||||
qt_type, target_price, anchoring_price, item_id, quotation_id, supplier_id = row
|
||||
target = int(target_price or 0)
|
||||
# 타결 상한가: 견적 생성 시 박제(목표가×(1+타결상한율)). 옛 세션은 NULL → 목표가로 폴백.
|
||||
ceiling = int(done_ceiling_price or 0) or target
|
||||
|
||||
# 앵커링가: 세션 생성 시 박제된 값(anchoring_price)을 그대로 사용 — 협상 중 불변.
|
||||
# 박제가 없으면(데이터 이상) 무할인 폴백 anchor=target + WARN — 앵커링 v1.2 정책상
|
||||
@ -90,20 +76,14 @@ class NegotiationContextLoader:
|
||||
# 매출액: 협력사 총매출(KTC total_revenue 미러). 미기재 시 0 → 호출부 기본값.
|
||||
_, revenue_amount = await self.crud.get_supplier_total_revenue(s, supplier_id)
|
||||
|
||||
# 유통 코드: 이 협력사×이 상품의 공급 방식(supplier_items.supply_type).
|
||||
# 매핑이 없거나 미지정이면 None → 호출부 기본값.
|
||||
# 유통 코드: 이 협력사×이 상품의 공급 방식(supplier_items.supply_type) 우선.
|
||||
# 매핑이 없으면 견적 기록(quotations.supplier_type) 폴백. 미지정 시 None → 호출부 기본값.
|
||||
_, 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)
|
||||
|
||||
# 협상 기준가 + 그 호칭 — 어느 컬럼을 쓸지는 고객사 설정(hidden_fields)이 정한다(crud).
|
||||
# 없으면 0(인하율 멘트 미표시).
|
||||
_, (item_price, item_price_label, labels) = await self.crud.get_item_baseline(s, item_id)
|
||||
|
||||
# 인터넷 최저가(LPS 수집 대표값) — 없으면 0(시장가 인용 카드는 값 있을 때만 치환).
|
||||
_, internet_lowest_price = await self.crud.get_item_lowest_price(s, item_id)
|
||||
|
||||
# 카드 스크립트 치환용 이름 — 협력사명/상품명. 없으면 None(호출부 기본값 폴백).
|
||||
_, partner_name = await self.crud.get_supplier_name(s, supplier_id)
|
||||
_, product_name = await self.crud.get_item_name(s, item_id)
|
||||
# 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시).
|
||||
_, item_price = await self.crud.get_item_price(s, item_id)
|
||||
|
||||
# 파트너사 유형: 상품에 연결된 협력사 수 — supplier_items 매핑(등록 기준) 우선.
|
||||
# 매핑이 아직 없으면 협상 세션 이력 기준 폴백(더미보다 항상 낫다). 실패 시 SINGLE.
|
||||
@ -113,44 +93,14 @@ class NegotiationContextLoader:
|
||||
if err != ErrorType.SUCCESS:
|
||||
supplier_count = 1
|
||||
|
||||
# 견적 생성 모달에서 고른 카드셋. 값이 없으면 운영 DB 기준으로 "선택 카드 없음"이다.
|
||||
# 데모/직접호출 경로(DB context 없음)만 ChatService 에서 기존 기본 카드셋으로 폴백한다.
|
||||
_, selected_cards = await self.crud.get_quotation_card_numbers(s, quotation_id)
|
||||
nego_rows, wild_rows = selected_cards
|
||||
selected_nego_cards = [number for number, _script, _tactic in nego_rows]
|
||||
selected_wild_cards = [number for number, _script, _tactic in wild_rows]
|
||||
# 카드 전술 확정 — "스크립트에 꽂힌 변수가 곧 전술"(제안가 파싱) + tactic JSONB(min_round·closing).
|
||||
card_specs = {}
|
||||
for number, script, tactic in [*nego_rows, *wild_rows]:
|
||||
spec = build_card_spec(script, tactic if isinstance(tactic, dict) else None)
|
||||
card_specs[number] = {
|
||||
"offer_variable": spec.offer_variable,
|
||||
"min_round": spec.min_round,
|
||||
"closing": spec.closing,
|
||||
"requires": list(spec.requires), # 세션-의존 변수 결측 시 미발동(available)
|
||||
}
|
||||
|
||||
# 협상카드 사용 횟수 상한(견적 설정). 없으면 None → 상한 미적용(선택 카드 수로만 캡).
|
||||
_, card_count = await self.crud.get_card_count(s, sid)
|
||||
|
||||
return NegotiationDbContext(
|
||||
rq_type="재협상" if int(qt_type) in _ONE_TO_ONE_QT_TYPES else "재견적",
|
||||
target_price=target,
|
||||
anchor_price=anchor,
|
||||
done_ceiling_price=ceiling,
|
||||
item_price=item_price,
|
||||
item_price_label=item_price_label,
|
||||
labels=labels,
|
||||
internet_lowest_price=internet_lowest_price,
|
||||
partner_name=partner_name,
|
||||
product_name=product_name,
|
||||
partner_type=PartnerType.from_count(supplier_count),
|
||||
revenue_amount=revenue_amount,
|
||||
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,
|
||||
card_count=card_count,
|
||||
card_specs=card_specs,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@ -1,144 +0,0 @@
|
||||
"""ScriptNaturalizer — 협상 카드 멘트를 LLM 으로 상황에 맞게 자연화 (Phase 2 표현층).
|
||||
|
||||
원칙: "숫자와 결정은 결정론이, 말은 LLM 이" —
|
||||
- 입력은 **치환 전 템플릿**({input_price} 등 placeholder 유지 상태). LLM 은 숫자를 절대 만들지 않는다.
|
||||
- 상황(라운드·가격구간·수용률)은 **정성 라벨**로만 전달(수치 미노출 → 숫자 환각 원천 차단).
|
||||
- 검증 실패/타임아웃/미설정 시 None → 호출부가 원본 템플릿 폴백(협상은 절대 안 멈춤).
|
||||
|
||||
검증(ScriptVerifier 철학의 플레인 텍스트판):
|
||||
① {placeholder} 집합이 원본과 정확히 동일(누락·추가 금지)
|
||||
② 원본에 없던 숫자 등장 금지(가격 환각 차단)
|
||||
③ 비어있지 않고 길이 폭주 금지
|
||||
|
||||
게이트: tenant llm.enabled(기본 false) + 전역 LLM 자격증명(config.local.toml [OpenAIConfig]
|
||||
또는 OPENAI_API_KEY env). 호출은 스레드로 넘겨 이벤트루프 비차단 + 타임아웃.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from common.logger import LOG
|
||||
from negotiation.profiling.config import LlmCredentials
|
||||
|
||||
_PLACEHOLDER_RE = re.compile(r"\{(\w+)\}")
|
||||
_DIGITS_RE = re.compile(r"\d+")
|
||||
# 강조 마커(negodata Slate 편집 정본) — 고객사가 지정한 표시라 자연화가 보존해야 한다.
|
||||
# 색 마커 {{강조|..}} {{안내|..}} 는 여는 토큰 개수로, 굵게/밑줄은 구분자 개수(짝수=쌍)로 센다.
|
||||
_COLOR_OPEN_RE = re.compile(r"\{\{(강조|안내)\|")
|
||||
|
||||
# 카드 메타 코드 → 프롬프트 라벨 (init-data.sql CardTone/CardStrategyType 정의와 동일)
|
||||
_TONE_LABEL = {1: "강경", 2: "정중", 3: "우호", 4: "중립", 5: "단호"}
|
||||
_STRATEGY_LABEL = {1: "경쟁", 2: "수용", 3: "고수", 4: "협력", 5: "선점", 6: "종결"}
|
||||
|
||||
_SYSTEM = """너는 B2B 구매 협상 챗봇의 문장 작성기다. 주어진 협상 카드 멘트 '템플릿'을 협상 상황에 맞게 자연스럽게 다시 쓴다.
|
||||
|
||||
규칙 (하나라도 어기면 출력은 폐기된다):
|
||||
- {변수명} 치환자는 철자 그대로 유지한다. 추가/삭제/변경 금지.
|
||||
- 숫자를 직접 쓰지 마라. 가격·비율 등 모든 수치는 치환자로만 표현한다.
|
||||
- 강조 마커(**굵게** __밑줄__ {{강조|...}} {{안내|...}})는 **개수와 종류를 그대로 유지**한다.
|
||||
고객사가 지정한 강조 표시이므로 삭제·추가·종류변경 금지. 감싼 문구는 자연스럽게 바꿔도 되지만
|
||||
강조된 구절 수만큼 같은 마커로 반드시 다시 감싼다(예: **굵게** 2개면 결과도 **…** 2쌍).
|
||||
- 새로운 약속·할인 조건·법적 표현을 만들지 마라. 원 템플릿의 협상 의도(전술)는 유지한다.
|
||||
- 한국어 존댓말, 2~5문장, 채팅 말풍선에 어울리게 간결히.
|
||||
- 출력은 JSON 하나만: {"script": "다시 쓴 멘트"}"""
|
||||
|
||||
|
||||
def _default_llm_call(messages: List[dict]) -> dict:
|
||||
"""기본 LLM 호출(동기) — 전역 자격증명으로 chat_json. 테스트에서 monkeypatch 지점."""
|
||||
from negotiation.profiling.infra.llm_adapter import chat_json
|
||||
|
||||
return chat_json(messages, temperature=0.5, max_tokens=600)
|
||||
|
||||
|
||||
class ScriptNaturalizer:
|
||||
def __init__(self, llm_call: Optional[Callable[[List[dict]], dict]] = None,
|
||||
timeout_seconds: float = 8.0):
|
||||
self._llm_call = llm_call or _default_llm_call
|
||||
self._timeout = timeout_seconds
|
||||
|
||||
@staticmethod
|
||||
def available() -> bool:
|
||||
"""전역 LLM 자격증명이 설정돼 있는가 (테넌트 enabled 게이트는 호출부 몫)."""
|
||||
return LlmCredentials.from_config().is_configured()
|
||||
|
||||
async def naturalize(self, template: str, *, situation: Optional[Dict[str, Any]] = None,
|
||||
tone: Optional[int] = None, strategy: Optional[int] = None) -> Optional[str]:
|
||||
"""템플릿(치환 전)을 상황 맞춤 문장으로 재작성. 실패/검증불통과 시 None(호출부 폴백)."""
|
||||
if not template or not template.strip():
|
||||
return None
|
||||
ctx = dict(situation or {})
|
||||
if tone in _TONE_LABEL:
|
||||
ctx["톤"] = _TONE_LABEL[tone]
|
||||
if strategy in _STRATEGY_LABEL:
|
||||
ctx["전략"] = _STRATEGY_LABEL[strategy]
|
||||
messages = [
|
||||
{"role": "system", "content": _SYSTEM},
|
||||
{"role": "user", "content":
|
||||
"템플릿:\n" + template +
|
||||
"\n\n협상 상황:\n" + json.dumps(ctx, ensure_ascii=False) +
|
||||
'\n\n규칙대로 다시 써서 {"script": "..."} 로만 출력.'},
|
||||
]
|
||||
try:
|
||||
result = await asyncio.wait_for(asyncio.to_thread(self._llm_call, messages), self._timeout)
|
||||
except Exception as ex: # 타임아웃 포함 — 폴백
|
||||
LOG.w(f"[ScriptNaturalizer] LLM 호출 실패(폴백): {ex}")
|
||||
return None
|
||||
|
||||
text = result.get("script") if isinstance(result, dict) else None
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return None
|
||||
return text if self._verify(template, text) else None
|
||||
|
||||
# ---- 검증 ----------------------------------------------------------
|
||||
@staticmethod
|
||||
def _verify(template: str, rewritten: str) -> bool:
|
||||
orig = set(_PLACEHOLDER_RE.findall(template))
|
||||
new = set(_PLACEHOLDER_RE.findall(rewritten))
|
||||
if orig != new:
|
||||
LOG.w(f"[ScriptNaturalizer] 검증 실패: 치환자 불일치 (누락={orig - new}, 추가={new - orig})")
|
||||
return False
|
||||
# 원본에 없던 숫자 금지 — 가격/비율 환각 차단 (수치는 치환자로만).
|
||||
orig_digits = set(_DIGITS_RE.findall(template))
|
||||
new_digits = set(_DIGITS_RE.findall(rewritten)) - orig_digits
|
||||
if new_digits:
|
||||
LOG.w(f"[ScriptNaturalizer] 검증 실패: 새 숫자 등장 {new_digits}")
|
||||
return False
|
||||
if len(rewritten) > max(600, len(template) * 4):
|
||||
LOG.w("[ScriptNaturalizer] 검증 실패: 길이 폭주")
|
||||
return False
|
||||
# 강조 마커 보존 — 고객사가 지정한 볼드/밑줄/색을 LLM 이 떨어뜨리면 폐기(원본 폴백).
|
||||
# 굵게/밑줄: 구분자 총 개수가 같아야 짝(쌍)이 보존됨. 색: 여는 토큰 개수 동일.
|
||||
if (template.count("**") != rewritten.count("**")
|
||||
or template.count("__") != rewritten.count("__")
|
||||
or len(_COLOR_OPEN_RE.findall(template)) != len(_COLOR_OPEN_RE.findall(rewritten))):
|
||||
LOG.w("[ScriptNaturalizer] 검증 실패: 강조 마커 불일치(볼드/색 소실) → 원본 유지")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def build_situation(context: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""세션 컨텍스트 → 정성 상황 라벨 (수치 미노출 — 숫자 환각 차단의 핵심).
|
||||
|
||||
가격구간: 제시가 vs 앵커/목표 관계, 라운드: 협상 진행 단계, 인하 진행: 협상 기준가 대비.
|
||||
"""
|
||||
out: Dict[str, Any] = {}
|
||||
rnd = context.get("round") or 0
|
||||
if rnd:
|
||||
out["라운드"] = "첫 제안" if rnd <= 1 else ("초반 조율" if rnd == 2 else "막바지 조율")
|
||||
price = context.get("input_price") or 0
|
||||
anchor = context.get("anchor_price") or 0
|
||||
target = context.get("target_price") or 0
|
||||
if price and anchor and target:
|
||||
if price <= anchor:
|
||||
out["가격구간"] = "목표 범위 도달(마무리 국면)"
|
||||
elif price <= target:
|
||||
out["가격구간"] = "목표 범위 근접(조율 국면)"
|
||||
else:
|
||||
out["가격구간"] = "목표 상회(추가 인하 필요)"
|
||||
base = context.get("item_price") or 0
|
||||
if base and price:
|
||||
rate = (base - price) / base
|
||||
out["인하 진행"] = "아직 미미" if rate < 0.01 else ("일부 진행" if rate < 0.05 else "상당히 진행")
|
||||
return out
|
||||
@ -38,11 +38,6 @@ class ScriptRepository:
|
||||
# 카드 멘트 DB 소스(backoffice_db). file 모드면 미사용.
|
||||
self._card_repo: ICardScriptRepository = card_repo or CardScriptDbRepository()
|
||||
|
||||
@property
|
||||
def config(self) -> TenantConfig:
|
||||
"""테넌트 config 노출 — ChatEngine 이 협상 규칙(negotiation.*)을 읽는다."""
|
||||
return self._config
|
||||
|
||||
# ---- 경로 해석 (_base 폴백) ---------------------------------------
|
||||
def _resource_path(self, filename: str) -> Optional[str]:
|
||||
scripts_dir = self._config.resources.scripts_dir
|
||||
@ -94,47 +89,24 @@ class ScriptRepository:
|
||||
return None
|
||||
return self.format_script(text, variables)
|
||||
|
||||
async def resolve_card_template(self, action_id: int, card_id: Optional[str],
|
||||
prefer_db: bool = False) -> tuple:
|
||||
"""카드 멘트의 **치환 전 템플릿**과 메타를 해석 → (template, tone, strategy_type).
|
||||
|
||||
cards.source_type == 'backoffice_db' 면 card.nego_cards(DB, tone/strategy 포함) 우선,
|
||||
없거나 file 모드면 scripts_cards.json(파일, 메타 None) 폴백. 둘 다 없으면 (None, None, None).
|
||||
치환 전 템플릿을 그대로 주는 이유: LLM 표현층이 placeholder 를 유지한 채 재작성한 뒤
|
||||
format_script 로 치환해야 숫자를 LLM 이 절대 만지지 않기 때문.
|
||||
"""
|
||||
if (prefer_db or self._config.cards.source_type == _CARD_SOURCE_DB) and card_id:
|
||||
card = await self._fetch_card_db(card_id)
|
||||
if card:
|
||||
return card # (script, tone, strategy)
|
||||
return self.card_scripts().get(str(action_id)), None, None # 파일 폴백(메타 없음)
|
||||
|
||||
async def resolve_card_script(self, action_id: int, card_id: Optional[str],
|
||||
variables: Optional[Dict[str, Any]] = None,
|
||||
prefer_db: bool = False) -> Optional[str]:
|
||||
"""카드 멘트 해석(템플릿 + 변수 치환). DB(정본) 우선 → 파일 폴백. 마커는 불투명 텍스트."""
|
||||
template, _, _ = await self.resolve_card_template(action_id, card_id, prefer_db=prefer_db)
|
||||
if not template:
|
||||
return None
|
||||
return self.format_script(template, variables)
|
||||
variables: Optional[Dict[str, Any]] = None) -> Optional[str]:
|
||||
"""카드 멘트 해석. cards.source_type == 'backoffice_db' 면 card.nego_cards.script(DB)를
|
||||
우선 조회하고, 없거나 file 모드면 scripts_cards.json(파일) 폴백. 변수 치환 후 반환.
|
||||
|
||||
async def resolve_wild_card_template(self, number: str) -> Optional[str]:
|
||||
"""선택형 와일드카드(WC-*) 멘트 템플릿 — card.wild_cards(DB, negodata 편집 정본) 조회.
|
||||
없거나 DB 불가면 None(호출부가 스텝 기본 멘트 폴백)."""
|
||||
DB 멘트는 백오피스(negodata)가 편집한 정본이라 파일보다 우선한다. 마커(**굵게** 등)가
|
||||
섞여 있어도 agent 는 불투명 텍스트로 취급 — 표현 렌더는 프론트 소유.
|
||||
"""
|
||||
if self._config.cards.source_type == _CARD_SOURCE_DB and card_id:
|
||||
db_text = await self._fetch_card_script_db(card_id)
|
||||
if db_text:
|
||||
return self.format_script(db_text, variables)
|
||||
return self.card_script(action_id, variables) # 파일 폴백
|
||||
|
||||
async def _fetch_card_script_db(self, card_id: str) -> Optional[str]:
|
||||
async def _q(s):
|
||||
_, script = await self._card_repo.get_wild_card_by_number(s, number)
|
||||
return script
|
||||
|
||||
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"[ScriptRepository] 와일드카드 멘트 DB 조회 실패 number={number}: {ex}")
|
||||
return None
|
||||
|
||||
async def _fetch_card_db(self, card_id: str) -> Optional[tuple]:
|
||||
async def _q(s):
|
||||
_, card = await self._card_repo.get_card_by_number(s, card_id)
|
||||
return card
|
||||
_, text = await self._card_repo.get_script_by_number(s, card_id)
|
||||
return text
|
||||
|
||||
try:
|
||||
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
|
||||
@ -41,9 +41,6 @@ class PolicyContext:
|
||||
action_space_size: int
|
||||
episode: EpisodeState
|
||||
available_mask: Optional[np.ndarray] = None # None 이면 used_action_ids 로 산출
|
||||
# 의도층 prior(Phase 1): 갑이 견적에서 고른 카드 순서 등 사전 선호. 방문수로 감쇠되어
|
||||
# 콜드 스타트 선택만 편향하고 학습(Q)이 쌓이면 영향이 소멸한다 — Q-table 오염 없음.
|
||||
prior_bonus: Optional[np.ndarray] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@ -36,8 +36,7 @@ class UCBQTablePolicy(NegotiationPolicy):
|
||||
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 _ucb_scores(self, state_index: int, available: List[int],
|
||||
prior: "np.ndarray | None" = None) -> np.ndarray:
|
||||
def _ucb_scores(self, state_index: int, available: List[int]) -> np.ndarray:
|
||||
q = self.qtable.row(state_index)
|
||||
visits = self.qtable.visit_row(state_index)
|
||||
total = self.qtable.state_visits(state_index)
|
||||
@ -46,15 +45,11 @@ class UCBQTablePolicy(NegotiationPolicy):
|
||||
for a in available:
|
||||
bonus = self.c * math.sqrt(ln / (visits[a] + 1e-6))
|
||||
scores[a] = q[a] + bonus
|
||||
if prior is not None:
|
||||
# 의도층 prior — 방문수 감쇠: 콜드 스타트 동점(전부 Q=0·bonus=0)일 때만 순서를
|
||||
# 결정하고, 학습이 쌓이면 1/(1+visits) 로 사라진다.
|
||||
scores[a] += float(prior[a]) / (1.0 + visits[a])
|
||||
return scores
|
||||
|
||||
def select(self, ctx: PolicyContext) -> ActionDecision:
|
||||
available = self._available(ctx)
|
||||
scores = self._ucb_scores(ctx.state_index, available, prior=ctx.prior_bonus)
|
||||
scores = self._ucb_scores(ctx.state_index, available)
|
||||
action_id = int(np.argmax(scores))
|
||||
n = len(available)
|
||||
# ε-greedy 근사 propensity (greedy 액션)
|
||||
|
||||
@ -10,7 +10,6 @@ P5/H 트랙에서 transition_id 기반으로 정교화한다.
|
||||
import math
|
||||
from typing import Tuple
|
||||
|
||||
from common.logger import LOG
|
||||
from negotiation.policies.qtable_policy import UCBQTablePolicy
|
||||
from negotiation.qtable.domain.model.q_table import QTable
|
||||
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
||||
@ -27,42 +26,20 @@ class QTablePolicyStore:
|
||||
lr = pol_cfg.learning_rate
|
||||
gamma = pol_cfg.gamma
|
||||
|
||||
# 현재 카탈로그 스냅샷(action_id → 카드번호). 버전에 저장해 카드번호 기반 마이그레이션에 쓴다.
|
||||
card_list = [engine.mapper.get_card_id(i) for i in range(A)]
|
||||
|
||||
# cold-start 3단 (계획서 D):
|
||||
# ① 활성 버전 있으면 그대로 ② 없고 inherits_base 면 base warm-start 복제(차원 호환 시)
|
||||
# ③ 차원 불일치/base 없음 → 휴리스틱 빈 버전
|
||||
err, active = await repo.read(lambda s: repo.get_active_version(s))
|
||||
if active is not None:
|
||||
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:
|
||||
version_id = None
|
||||
if engine.config.inherits_base:
|
||||
version_id = await repo.warm_start_from_base(
|
||||
state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma,
|
||||
action_cards=card_list)
|
||||
state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma)
|
||||
if version_id is None:
|
||||
version_id = await repo.get_or_create_active_version(
|
||||
state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma,
|
||||
action_cards=card_list)
|
||||
state_space_size=S, action_space_size=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)
|
||||
|
||||
@ -155,10 +155,8 @@ class LearningRepository:
|
||||
# ---- Q-Table 영속화 (H1) -------------------------------------------
|
||||
async def get_or_create_active_version(self, *, state_space_size: int, action_space_size: int,
|
||||
learning_rate: float, discount_factor: float,
|
||||
scope: int = 2, version_name: str = "v000",
|
||||
action_cards: Optional[List[str]] = None) -> Optional[uuid.UUID]:
|
||||
"""활성 버전 version_id 반환. 없으면 v000 을 활성으로 생성. (company_id 스코프)
|
||||
action_cards: 카탈로그 스냅샷(카드번호 목록, index=action_id) — 후일 카드번호 기반 마이그레이션용."""
|
||||
scope: int = 2, version_name: str = "v000") -> Optional[uuid.UUID]:
|
||||
"""활성 버전 version_id 반환. 없으면 v000 을 활성으로 생성. (company_id 스코프)"""
|
||||
err, existing = await DB_SESSION_MNG.execute_lambda(
|
||||
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: self.get_active_version(s)
|
||||
)
|
||||
@ -172,7 +170,6 @@ class LearningRepository:
|
||||
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,
|
||||
learning_rate=learning_rate, discount_factor=discount_factor, is_active=True,
|
||||
action_cards=action_cards,
|
||||
)
|
||||
return await DB_SESSION_MNG.insert(s, obj)
|
||||
|
||||
@ -187,8 +184,7 @@ class LearningRepository:
|
||||
|
||||
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,
|
||||
version_name: str = "v000_warmstart_from_base",
|
||||
action_cards: Optional[List[str]] = None) -> Optional[uuid.UUID]:
|
||||
version_name: str = "v000_warmstart_from_base") -> Optional[uuid.UUID]:
|
||||
"""공유 베이스(_base)의 Q값/방문수를 자사로 복제해 활성 버전 생성 (cold-start ①, 계획서 D).
|
||||
|
||||
차원 불일치/베이스 없음 → None (호출자가 휴리스틱 init 폴백). visit 은 감쇠 복제(탐색 여지).
|
||||
@ -209,7 +205,7 @@ class LearningRepository:
|
||||
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,
|
||||
action_space_size=action_space_size, learning_rate=learning_rate,
|
||||
discount_factor=discount_factor, is_active=True, action_cards=action_cards,
|
||||
discount_factor=discount_factor, is_active=True,
|
||||
)
|
||||
e = await DB_SESSION_MNG.insert(s, ver)
|
||||
if e != ErrorType.SUCCESS:
|
||||
@ -231,73 +227,6 @@ class LearningRepository:
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create])
|
||||
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]]:
|
||||
"""(q_cells, visit_cells) — q_cells: (state,action,q), visit_cells: (state,action,count). 자사 스코프."""
|
||||
def _q(s):
|
||||
|
||||
@ -20,8 +20,9 @@ from config.server_configs import agent_config
|
||||
|
||||
_TENANT_HEADER = "X-Tenant-ID"
|
||||
|
||||
# 테넌트 식별이 필요 없는 경로 (헬스/문서/스키마/데모 UI + 전역 카탈로그 리로드=내부 운영).
|
||||
_WHITELIST_PREFIXES = ("/healthz", "/health", "/v1/health", "/docs", "/redoc", "/openapi.json", "/demo", "/v1/catalog-refresh-all")
|
||||
# 테넌트 식별이 필요 없는 경로 (헬스/문서/스키마/데모 UI).
|
||||
_WHITELIST_PREFIXES = ("/healthz", "/health", "/v1/health", "/docs", "/redoc", "/openapi.json", "/demo")
|
||||
|
||||
|
||||
class TenantMiddleware(BaseHTTPMiddleware):
|
||||
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 fastapi import APIRouter, Depends, Request
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
|
||||
from common.enums import EXCEPTION_TENANT_HEADER_MISSING, ErrorType
|
||||
from common.enums import ErrorType
|
||||
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
||||
from router.deps import get_tenant_engine
|
||||
from tenancy.registry import TenantEngine, tenant_registry
|
||||
from tenancy.registry import TenantEngine
|
||||
|
||||
router = APIRouter(prefix="/v1", tags=["Card"], responses={404: {"description": "Not found"}})
|
||||
|
||||
@ -41,33 +41,6 @@ async def card_update(req: CardUpdateReq, engine: TenantEngine = Depends(get_ten
|
||||
"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 조회)")
|
||||
async def card_search(card_id: Optional[str] = None, engine: TenantEngine = Depends(get_tenant_engine)):
|
||||
mapping = await _merged_mapping(engine)
|
||||
|
||||
@ -13,7 +13,7 @@ class Req_Chat(Req_WebPacketProtocol):
|
||||
협상 컨텍스트(rq_type/목표가/앵커링가/품목가/매출액/유통코드/파트너 유형)는 요청에 싣지
|
||||
않는다 — 세션 시작 시 agent 가 DB 에서 1회 조회해 확정한다(NegotiationContextLoader):
|
||||
negotiation.sessions(qt_type·target_price·anchoring_price), partner.items(price),
|
||||
partner.suppliers(total_revenue), partner.supplier_items(supply_type), 상품별 협력사 수.
|
||||
partner.suppliers(total_revenue), quotation.quotations(supplier_type), 상품별 협력사 수.
|
||||
행이 없으면(데모/테스트 직접 호출) 기본값 폴백.
|
||||
가격 수용률은 세션 내 라운드별 제시가로 매 턴 동적 계산: max(0, (기존 공급가−현재가)/기존 공급가)
|
||||
— 첫 제시가부터 기존 공급가 대비 인하가 반영되므로 첫 라운드도 실값. 기존 공급가 없으면 첫 제시가 기준.
|
||||
@ -53,9 +53,6 @@ class Res_Chat(Res_WebPacketProtocol):
|
||||
# 성공 확정 이후 턴(협상완료 요약·협상종료)에 내려주는 합의가. 와일드카드 1% 인하 수락 등
|
||||
# 유저가 직접 입력하지 않은 가격으로 타결될 수 있어, backend 요약/입찰가는 이 값을 최우선 사용한다.
|
||||
settled_price: Optional[int] = None
|
||||
# Phase 3 이해층: 자유 발화를 NLU 로 해석해 진행한 경우, 엔진에 실제 전달된 입력.
|
||||
# (예: "만원까지는 어렵고 10,500원이면 가능합니다" → "10500") 미해석/정형 입력이면 None.
|
||||
interpreted_input: Optional[str] = None
|
||||
|
||||
|
||||
class Res_ChatSession(Res_WebPacketProtocol):
|
||||
|
||||
@ -7,23 +7,14 @@ ChatEngine(동기 step 전이) + UCB Q-Table(가격협상 카드선택·학습)
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
from common.enums import DBType, ErrorType
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.logger import LOG
|
||||
from config.server_configs import agent_config
|
||||
from negotiation.cards.domain.tactics import (
|
||||
Offer, available, compute_offer_detail, is_played, mark_played, playable, record_offer, spec_from_context,
|
||||
)
|
||||
from negotiation.chat.service.chat_engine import (
|
||||
_CHOICE_MODES, _PRICE_MODES, 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.input_interpreter import SIMPLE_PRICE_RE, InputInterpreter
|
||||
from negotiation.chat.service.chat_session_repository import ChatSessionRepository
|
||||
from negotiation.chat.service.negotiation_context_loader import NegotiationContextLoader
|
||||
from negotiation.chat.service.script_naturalizer import ScriptNaturalizer, build_situation
|
||||
from negotiation.chat.service.script_repository import ScriptRepository
|
||||
from negotiation.policies.base import EpisodeState, PolicyContext, Transition
|
||||
from negotiation.policy.model_store import QTablePolicyStore
|
||||
@ -40,20 +31,10 @@ _DEFAULT_RQ_TYPE = "재협상"
|
||||
_DEFAULT_TARGET_PRICE = 10000 # KT 목표 매입가
|
||||
_DEFAULT_ANCHOR_PRICE = 9900 # 앵커링가(목표가보다 낮음). 제시가 ≤ anchor → 우선협상
|
||||
_DEFAULT_REVENUE_AMOUNT = 20_000_000 # 매출액(원) — suppliers.total_revenue 미기재 시 폴백
|
||||
_DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — supplier_items.supply_type 미지정 시 폴백
|
||||
_DEFAULT_PARTNER_NAME = "귀사" # 협력사명 — suppliers.name 미기재/데모 시 폴백(카드 {partner_name})
|
||||
_DEFAULT_PRODUCT_NAME = "본 상품" # 상품명 — items.name 미기재/데모 시 폴백(카드 {product_name})
|
||||
_DEFAULT_ITEM_PRICE_LABEL = "공급가" # 협상 기준가 호칭(공급사 화면 고정 용어) — DB 컨텍스트 없는 데모/직접호출 경로 폴백
|
||||
# (negodata 용어 카탈로그 item.price 의 base 와 같아야 표기가 갈리지 않는다)
|
||||
_DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — quotations.supplier_type 미지정 시 폴백
|
||||
|
||||
|
||||
class ChatService:
|
||||
# Phase 2 표현층 / Phase 3 이해층 — 테넌트 llm.enabled + 전역 자격증명일 때만 사용(기본 무동작).
|
||||
# 클래스 속성인 이유: FastAPI 가 ChatService 를 Depends 로 쓰므로 __init__ 파라미터를 두면
|
||||
# 쿼리 파라미터로 해석된다. 테스트는 인스턴스 속성으로 덮어 주입한다.
|
||||
_naturalizer = ScriptNaturalizer()
|
||||
_interpreter = InputInterpreter()
|
||||
|
||||
async def chat(self, engine: TenantEngine, req: Req_Chat) -> Res_Chat:
|
||||
res = Res_Chat()
|
||||
repo = ScriptRepository(engine.config, agent_config.tenants_dir)
|
||||
@ -82,26 +63,13 @@ class ChatService:
|
||||
)
|
||||
|
||||
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 으로 폴백해 로컬 테스트와 콘솔 데모를 유지한다.
|
||||
# 협상카드 사용 횟수 상한(quotation_settings.card_count)으로 실제 플레이 가능한 카드 수를 캡한다 —
|
||||
# session.action_space_size 는 카드 소진 판정(cards_total) 전용이라 여기서 줄여도 Q-table 은
|
||||
# engine.action_space_size(카탈로그 전체)로 별도 고정된다. card_count 미설정(None)이면 선택 수 그대로.
|
||||
card_cap = db_ctx.card_count if (db_ctx and db_ctx.card_count and db_ctx.card_count > 0) else None
|
||||
action_space_size = (
|
||||
min(len(selected_nego_cards), engine.action_space_size, *( [card_cap] if card_cap else [] ))
|
||||
if db_ctx is not None
|
||||
else engine.action_space_size
|
||||
)
|
||||
# session_id honoring: backend 가 보낸 session_id(= negotiation.sessions.session_id)를
|
||||
# 새 uuid 발급 없이 그대로 세션 키로 쓴다. 없으면(직접 호출/데모) 생성.
|
||||
session = ChatSession(
|
||||
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=action_space_size,
|
||||
rq_type=rq_type, action_space_size=engine.action_space_size,
|
||||
context={
|
||||
# 매출액 = suppliers.total_revenue, 유통코드 = supplier_items.supply_type 매핑 (loader).
|
||||
# 매출액 = suppliers.total_revenue, 유통코드 = quotations.supplier_type 매핑 (loader).
|
||||
# 미기재/미지정이면 기본값 폴백.
|
||||
"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,
|
||||
@ -112,40 +80,14 @@ class ChatService:
|
||||
# 목표가/앵커링가: sessions 행(생성 시 박제된 anchoring_price) → 박제 ‰ → 1% 폴백 (loader).
|
||||
"anchor_price": db_ctx.anchor_price if db_ctx else _DEFAULT_ANCHOR_PRICE,
|
||||
"target_price": db_ctx.target_price if db_ctx else _DEFAULT_TARGET_PRICE,
|
||||
# 타결 상한가(sessions.done_ceiling_price 박제) — 타결 판정선이자 카드 제안가 상한.
|
||||
# 목표가를 조금 넘어도 이 이하면 타결한다. 미박제/데모는 목표가와 같다.
|
||||
"done_ceiling_price": db_ctx.done_ceiling_price if db_ctx else _DEFAULT_TARGET_PRICE,
|
||||
# 협력사명/상품명 — 카드 스크립트 {partner_name}·{product_name} 치환용(loader). 없으면 폴백.
|
||||
"partner_name": (db_ctx.partner_name if db_ctx and db_ctx.partner_name else _DEFAULT_PARTNER_NAME),
|
||||
"product_name": (db_ctx.product_name if db_ctx and db_ctx.product_name else _DEFAULT_PRODUCT_NAME),
|
||||
"round": 0,
|
||||
# 협상 기준가(고객사가 관리하는 가격 — 공급가 또는 매입가) — 가격협상_확인 인하율 산출용.
|
||||
# 호칭은 회사 설정 라벨을 따른다("기존 {label} 대비 …" 멘트).
|
||||
# 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용.
|
||||
"item_price": db_ctx.item_price if db_ctx else 0,
|
||||
"item_price_label": db_ctx.item_price_label if db_ctx else _DEFAULT_ITEM_PRICE_LABEL,
|
||||
# 회사 용어 사전 — 스크립트의 {label_*} 토큰(협력사·목표가·배송형태 등) 치환용.
|
||||
"labels": (db_ctx.labels if db_ctx else {}),
|
||||
# 인터넷 최저가(items.internet_lowest_price, LPS 대표값) — 카드 {internet_lowest_price} 치환용.
|
||||
# 미수집(0)이면 vars_for 가 키를 만들지 않아 원형 유지(허위 시장가 표기 방지).
|
||||
"internet_lowest_price": db_ctx.internet_lowest_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,
|
||||
# 카드번호 → 전술 {offer_variable, min_round, closing}. 시작 시 1회 박제(loader) —
|
||||
# 이후 카드 멘트가 바뀌어도 이 협상은 시작 시점 전술로 끝까지 간다.
|
||||
"card_specs": (db_ctx.card_specs if db_ctx else {}),
|
||||
"allow_selected_wildcards": True if db_ctx is None else bool(selected_wild_cards),
|
||||
},
|
||||
)
|
||||
view = chat_engine.start(session)
|
||||
else:
|
||||
# Phase 3 이해층: 자유 발화(버튼/정형 입력이 아닌 텍스트)를 기대 입력으로 해석.
|
||||
# 해석 실패/미설정 시 원문 그대로 → 기존 엔진 재질문 흐름 유지.
|
||||
user_input = await self._interpret_input(engine, chat_engine, session, req.user_input, res)
|
||||
view = chat_engine.advance(session, user_input)
|
||||
view = chat_engine.advance(session, req.user_input)
|
||||
|
||||
# 2) 응답 기본 채움 (학습 블록이 가격협상 턴에서 script/indicator 를 덮어쓸 수 있어 먼저 채운다)
|
||||
res.session_id = session.session_id
|
||||
@ -162,20 +104,8 @@ class ChatService:
|
||||
if session.context.get("final_outcome") == "success" and session.context.get("input_price"):
|
||||
res.settled_price = int(session.context["input_price"])
|
||||
|
||||
# 선택형 와일드카드 턴(wild_card_dynamic): 멘트 정본은 card.wild_cards(negodata 편집).
|
||||
# DB 멘트가 있으면 스텝 기본 멘트를 대체하고, 없으면 기본 멘트(counter_price 치환)로 진행.
|
||||
if view.step == "wild_card_dynamic" and session.context.get("active_wild_card_number"):
|
||||
number = session.context["active_wild_card_number"]
|
||||
template = await repo.resolve_wild_card_template(number)
|
||||
if template:
|
||||
if engine.config.llm.enabled and ScriptNaturalizer.available():
|
||||
template = (await self._naturalizer.naturalize(
|
||||
template, situation=build_situation(session.context))) or template
|
||||
res.script = repo.format_script(template, chat_engine.vars_for(session))
|
||||
res.card_id = number
|
||||
|
||||
# 3) 학습 결합 (가격협상 카드선택 → 카드 스크립트·협상지표 / 종료 보상)
|
||||
if view.error is None and session.action_space_size > 0:
|
||||
if view.error is None and engine.action_space_size > 0:
|
||||
if view.needs_card_selection:
|
||||
await self._select_and_learn(engine, chat_engine, repo, session, res)
|
||||
elif view.outcome is not None:
|
||||
@ -206,53 +136,6 @@ class ChatService:
|
||||
res.found = True
|
||||
return res
|
||||
|
||||
# ---- Phase 3 이해층 (자유 발화 NLU) ---------------------------------
|
||||
async def _interpret_input(self, engine: TenantEngine, chat_engine: ChatEngine,
|
||||
session: ChatSession, user_input: Optional[str], res: Res_Chat) -> Optional[str]:
|
||||
"""자유 발화를 현재 step 의 기대 입력으로 해석해 엔진에 넘길 문자열을 돌려준다.
|
||||
|
||||
결정론 fast path 우선: 정형 가격([\\d,]+원?)·버튼 값 그대로면 LLM 을 부르지 않는다.
|
||||
자유 텍스트 + llm.enabled + 자격증명일 때만 InputInterpreter 호출. 해석 실패/미설정이면
|
||||
원문 그대로 반환 → 기존 엔진의 재질문/기본분기 흐름이 그대로 동작(협상 불중단).
|
||||
"""
|
||||
if user_input is None:
|
||||
return user_input
|
||||
raw = str(user_input).strip()
|
||||
if not raw:
|
||||
return user_input
|
||||
node = chat_engine.scripts.get(session.step, {})
|
||||
mode = node.get("next_input_mode", "null")
|
||||
options: list = []
|
||||
if mode in _PRICE_MODES:
|
||||
if SIMPLE_PRICE_RE.fullmatch(raw):
|
||||
return user_input # 정형 가격 — 기존 결정론 파서 경로
|
||||
elif mode in _CHOICE_MODES:
|
||||
options = self._step_options(node)
|
||||
if raw in options:
|
||||
return user_input # 버튼 값 그대로 — 결정론 경로
|
||||
else:
|
||||
return user_input # 입력을 받지 않는 스텝
|
||||
if not (engine.config.llm.enabled and InputInterpreter.available()):
|
||||
return user_input
|
||||
out = await self._interpreter.interpret(raw, input_mode=mode, input_options=options,
|
||||
step_script=node.get("script"))
|
||||
if out is None:
|
||||
return user_input
|
||||
LOG.i(f"[ChatService] NLU: {raw!r} → {out.kind}={out.value!r} (근거={out.source!r}) session={session.session_id}")
|
||||
res.interpreted_input = out.value # 투명성: backend/front 가 해석 결과를 표시할 수 있게
|
||||
return out.value
|
||||
|
||||
@staticmethod
|
||||
def _step_options(node: dict) -> list:
|
||||
"""현재 step 이 허용하는 선택지 — input_options 우선, next_step 분기 키 보강."""
|
||||
opts = [str(o) for o in (node.get("input_options") or [])]
|
||||
ns = node.get("next_step")
|
||||
if isinstance(ns, dict):
|
||||
for k in ns.keys():
|
||||
if k != "default" and str(k) not in opts:
|
||||
opts.append(str(k))
|
||||
return opts
|
||||
|
||||
# ---- 학습 ----------------------------------------------------------
|
||||
@staticmethod
|
||||
def _acceptance_ratio(context: dict) -> float:
|
||||
@ -282,11 +165,6 @@ class ChatService:
|
||||
|
||||
async def _select_and_learn(self, engine: TenantEngine, chat_engine: ChatEngine,
|
||||
scripts: ScriptRepository, session: ChatSession, res: Res_Chat):
|
||||
# 종결 국면(라운드 만료·카드 소진, 엔진 check_iteration_limit 이 마킹): 규칙층이
|
||||
# 종결 전술(중간값 절충/최후통첩)을 강제 발동한다 — RL 선택·학습 대상이 아니다.
|
||||
if session.context.pop("force_closing", False):
|
||||
await self._play_closing_tactic(engine, chat_engine, scripts, session, res)
|
||||
return
|
||||
snap = self._snapshot(session, NegotiationOutcome.ONGOING)
|
||||
try:
|
||||
idx = state_index(snap, engine.config.state)
|
||||
@ -294,34 +172,17 @@ class ChatService:
|
||||
LOG.e_no_callstack(f"[ChatService] state error: {ex}")
|
||||
return
|
||||
policy, version_id, repo = await QTablePolicyStore.load(engine)
|
||||
# action space 는 카탈로그 전체(engine.action_space_size)로 고정 — action_id↔카드 대응을
|
||||
# 견적마다 일정하게 유지해 Q-table 학습 일관성을 지킨다. 견적 선택은 축소가 아니라
|
||||
# available_mask 로 처리한다(선택 카드만 pickable, 사용분 제외 + 전술 발동조건 AND).
|
||||
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=engine.action_space_size,
|
||||
available_mask=self._combined_mask(engine, session),
|
||||
prior_bonus=self._selection_prior(engine, session),
|
||||
episode=EpisodeState(used_action_ids=set(session.used_action_ids)))
|
||||
decision = policy.select(ctx)
|
||||
session.used_action_ids.add(decision.action_id)
|
||||
card_id = self._card_id_for_action(engine, session, decision.action_id)
|
||||
# 카드번호 공용 이력 — 와일드/종결 경로와 같은 목록을 본다("한 협상 한 카드 1회" 단일 판정).
|
||||
mark_played(session.context, card_id)
|
||||
# 전술 실행: 카드가 제시할 금액(스크립트 파싱 결과)을 계산해 세션에 적재한다.
|
||||
# pending 이 있으면 이 턴은 수락/거절 스텝(가격협상_카운터)으로 전환되고,
|
||||
# 협력사가 수락하면 이 가격으로 즉시 타결된다(chat_engine 의 수락 메커니즘).
|
||||
# 유효조건(≤목표가 · <제시가) 미달이면 None → 금액 없이 설득 멘트만 나간다(HOLD 강등).
|
||||
spec = spec_from_context(session.context, card_id)
|
||||
offer = compute_offer_detail(spec, session.context) if available(spec, session.context) else None
|
||||
counter = offer.price if offer else None
|
||||
if offer is not None:
|
||||
record_offer(session.context, offer)
|
||||
card_id = engine.mapper.get_card_id(decision.action_id)
|
||||
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))
|
||||
await QTablePolicyStore.persist_cell(repo, version_id, policy, idx, decision.action_id)
|
||||
session.context["last_state"] = idx
|
||||
session.context["last_action"] = decision.action_id
|
||||
await self._log(repo, session, idx, decision.action_id, card_id, snap, reward, done=False,
|
||||
decision=decision, policy=policy)
|
||||
await self._log(repo, session, idx, decision.action_id, card_id, snap, reward, decision.propensity, done=False)
|
||||
|
||||
res.card_id = card_id
|
||||
res.policy = policy.name
|
||||
@ -334,17 +195,7 @@ class ChatService:
|
||||
# ① 선택된 카드의 스크립트를 봇 메시지(script)로 출력 ② 협상지표 게이지(indicator_value) 동봉.
|
||||
# backend/front 가 indicator/bot_chat_type 패스스루·게이지 렌더 준비 완료 → 값만 채우면 표시된다.
|
||||
# 카드 멘트: backoffice_db 모드면 card.nego_cards.script(negodata 편집 정본), 아니면 파일 폴백.
|
||||
template, tone, strategy = await scripts.resolve_card_template(
|
||||
decision.action_id, card_id,
|
||||
prefer_db=bool(session.context.get("selected_nego_card_numbers")),
|
||||
)
|
||||
# Phase 2 표현층: llm.enabled(테넌트) + 자격증명 있으면 템플릿을 상황 맞춤 자연화.
|
||||
# placeholder 유지 상태로 재작성 → 검증(치환자/숫자) → 실패·타임아웃 시 원본 폴백.
|
||||
if template and engine.config.llm.enabled and ScriptNaturalizer.available():
|
||||
naturalized = await self._naturalizer.naturalize(
|
||||
template, situation=build_situation(session.context), tone=tone, strategy=strategy)
|
||||
template = naturalized or template
|
||||
card_script = scripts.format_script(template, chat_engine.vars_for(session)) if template else None
|
||||
card_script = await scripts.resolve_card_script(decision.action_id, card_id, chat_engine.vars_for(session))
|
||||
if card_script:
|
||||
res.script = card_script
|
||||
c = session.context
|
||||
@ -354,60 +205,6 @@ class ChatService:
|
||||
res.indicator_range = ind[1]
|
||||
res.bot_chat_type = "indicator"
|
||||
|
||||
# 카운터 제시 카드면 수락/거절 스텝(가격협상_카운터)으로 전환 — 카드 멘트({target_price} 등
|
||||
# 카운터가 포함)는 그대로 두고, 입력만 [수락|다른 가격 제시] 버튼으로 바꾼다.
|
||||
if counter is not None:
|
||||
view2 = chat_engine.render_step(session, "가격협상_카운터")
|
||||
res.step, res.client_step = view2.step, view2.client_step
|
||||
res.input_mode, res.input_options = view2.input_mode, view2.input_options
|
||||
if not card_script:
|
||||
res.script = view2.script # 카드 멘트 없으면 스텝 기본 카운터 멘트
|
||||
|
||||
async def _play_closing_tactic(self, engine: TenantEngine, chat_engine: ChatEngine,
|
||||
scripts: ScriptRepository, session: ChatSession, res: Res_Chat):
|
||||
"""종결 국면 강제 전술 — 견적에서 선택한 종결 와일드카드(WC-05 중간값 절충 등) 우선,
|
||||
없으면 목표가 최후통첩. 최종 카운터를 제시하고 수락/거절 스텝으로 전환한다.
|
||||
규칙층의 강제 결정이므로 RL 선택/학습을 우회한다."""
|
||||
ctx = session.context
|
||||
ctx["closing_played"] = True
|
||||
# 선택 와일드카드 중 종결 전용 카드(closing) — 이미 쓴 카드는 건너뛰고(같은 멘트 반복 방지),
|
||||
# 제안가 유효조건(≤목표가 · <제시가) 미달 카드도 건너뛴다(예: 절충가가 목표가 초과 → 미발동).
|
||||
closing_number, closing_offer = None, None
|
||||
for n in (ctx.get("selected_wild_card_numbers") or []):
|
||||
n = str(n)
|
||||
spec = spec_from_context(ctx, n)
|
||||
if not available(spec, ctx, closing_phase=True) or is_played(ctx, n):
|
||||
continue
|
||||
offer = compute_offer_detail(spec, ctx)
|
||||
if offer is not None:
|
||||
closing_number, closing_offer = n, offer
|
||||
break
|
||||
if closing_offer is None:
|
||||
# 폴백 최후통첩: 목표가 제시 (여기 도달 = 제시가 > target 이므로 항상 유효한 카운터).
|
||||
closing_number = None
|
||||
target = int(ctx.get("target_price") or 0)
|
||||
price = int(ctx.get("input_price") or 0)
|
||||
if 0 < target < price:
|
||||
closing_offer = Offer(price=target, variable="target_price",
|
||||
prev_customer=int(ctx.get("prev_customer_price") or ctx.get("anchor_price") or 0),
|
||||
prev_partner=price)
|
||||
if closing_offer is None:
|
||||
return # 컨텍스트 이상 — 기존 가격협상 스텝 그대로(재제안 요구)
|
||||
mark_played(ctx, closing_number) # None(폴백 최후통첩)이면 no-op
|
||||
record_offer(ctx, closing_offer)
|
||||
|
||||
template = None
|
||||
if closing_number:
|
||||
template = await scripts.resolve_wild_card_template(closing_number)
|
||||
if template and engine.config.llm.enabled and ScriptNaturalizer.available():
|
||||
template = (await self._naturalizer.naturalize(
|
||||
template, situation=build_situation(ctx))) or template
|
||||
view2 = chat_engine.render_step(session, "가격협상_카운터")
|
||||
res.step, res.client_step = view2.step, view2.client_step
|
||||
res.input_mode, res.input_options = view2.input_mode, view2.input_options
|
||||
res.script = scripts.format_script(template, chat_engine.vars_for(session)) if template else view2.script
|
||||
res.card_id = closing_number
|
||||
|
||||
async def _terminal_learn(self, engine: TenantEngine, session: ChatSession, outcome: str, res: Res_Chat):
|
||||
oc = NegotiationOutcome.SUCCESS if outcome == "success" else NegotiationOutcome.FAILURE
|
||||
snap = self._snapshot(session, oc)
|
||||
@ -421,105 +218,16 @@ class ChatService:
|
||||
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 self._log(repo, session, last_state, last_action,
|
||||
self._card_id_for_action(engine, session, last_action), snap, reward, done=True)
|
||||
engine.mapper.get_card_id(last_action), snap, reward, None, done=True)
|
||||
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,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _combined_mask(cls, engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
|
||||
"""견적 선택 마스크 AND 전술 발동조건 마스크.
|
||||
|
||||
결합 결과가 전부 False 면(선택 카드가 모두 발동 불가) 선택 마스크 단독으로 폴백 —
|
||||
협상은 멈추지 않고(HOLD 설득으로라도 진행), 종결은 라운드 규칙이 처리한다.
|
||||
"""
|
||||
sel = cls._selection_mask(engine, session)
|
||||
tac = cls._tactic_mask(engine, session)
|
||||
if tac is None:
|
||||
return sel
|
||||
if sel is None:
|
||||
return tac if tac.any() else None
|
||||
both = sel & tac
|
||||
return both if both.any() else sel
|
||||
|
||||
@staticmethod
|
||||
def _tactic_mask(engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
|
||||
"""지금 플레이 가능한 action 만 True. HOLD(설득)는 발동조건만, 금액 카드는 제안가 유효까지
|
||||
본다(playable) — 무효 금액(역행·목표가 초과 등)이 멘트 글자로 나가는 것 자체를 막는다.
|
||||
전부 True 면 None(마스크 불필요)."""
|
||||
ctx = session.context
|
||||
mask = np.array(
|
||||
[playable(spec_from_context(ctx, engine.mapper.get_card_id(a)), ctx)
|
||||
for a in range(engine.action_space_size)],
|
||||
dtype=bool,
|
||||
)
|
||||
return None if mask.all() else mask
|
||||
|
||||
@staticmethod
|
||||
def _selection_prior(engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
|
||||
"""의도층 prior(Phase 1) — 견적에서 고른 카드 순서를 콜드 스타트 선호로 반영.
|
||||
|
||||
갑이 먼저 고른 카드일수록 높은 보너스(최대 0.3, 순위 선형 감소). UCB 점수에
|
||||
1/(1+visits) 감쇠로 더해지므로 학습이 쌓이면 Q 가 지배한다(오염 없음).
|
||||
선택이 2장 미만이면 순서 정보가 무의미 → None.
|
||||
"""
|
||||
selected = session.context.get("selected_nego_card_numbers") or []
|
||||
if len(selected) < 2:
|
||||
return None
|
||||
prior = np.zeros(engine.action_space_size)
|
||||
n = len(selected)
|
||||
for rank, num in enumerate(selected):
|
||||
a = engine.mapper.get_action_id(str(num))
|
||||
if a is not None and a < engine.action_space_size:
|
||||
prior[a] = 0.3 * (n - rank) / n
|
||||
return prior if prior.any() else None
|
||||
|
||||
async def _log(self, repo: LearningRepository, session, state_index, action_id, card_id, snap, reward, done,
|
||||
decision=None, policy=None):
|
||||
async def _log(self, repo: LearningRepository, session, state_index, action_id, card_id, snap, reward, propensity, done):
|
||||
data = {
|
||||
"session_id": session.session_id, "state_index": state_index, "action_id": action_id,
|
||||
"card_id": card_id, "snapshot": snap.to_dict(),
|
||||
"card_id": card_id, "snapshot": snap.to_dict(), "propensity": propensity,
|
||||
"turn": snap.round_number, "reward": reward.total, "done": done,
|
||||
"settled_price": int(snap.input_price) if snap.outcome == NegotiationOutcome.SUCCESS else None,
|
||||
}
|
||||
if decision is not None and policy is not None:
|
||||
# 선택 근거(Q값·UCB·방문수)를 그 턴 값 그대로 박제한다 — 사후에 q_values 를 읽으면 이미 갱신된 뒤라
|
||||
# "그때 왜 이 카드였나"를 복원할 수 없다. negodata 협상 학습 화면이 이 컬럼들을 읽는다.
|
||||
# 종료 로그(카드 선택 없는 done 행)는 decision 이 없어 NULL — 화면 집계(avg/max)가 무시한다.
|
||||
data.update({
|
||||
"propensity": decision.propensity,
|
||||
"available_actions": decision.available_actions,
|
||||
"q_value_at_selection": decision.q_value,
|
||||
"ucb_score_at_selection": decision.ucb_score,
|
||||
"visit_count_at_selection": int(policy.qtable.visits[state_index, action_id]),
|
||||
"total_visits_at_selection": int(policy.qtable.state_visits(state_index)),
|
||||
})
|
||||
try:
|
||||
await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [lambda s: repo.log_transition(s, data)])
|
||||
except Exception as ex:
|
||||
|
||||
@ -97,10 +97,10 @@ class NegotiationService:
|
||||
|
||||
# 7) experience_logs 기록
|
||||
if req.log:
|
||||
res.logged = await self._log(engine, session_id, idx, decision, snap, reward, policy)
|
||||
res.logged = await self._log(engine, session_id, idx, decision, snap, reward)
|
||||
return res
|
||||
|
||||
async def _log(self, engine, session_id, idx, decision, snap, reward, policy) -> bool:
|
||||
async def _log(self, engine, session_id, idx, decision, snap, reward) -> bool:
|
||||
repo = LearningRepository(engine.company_id)
|
||||
data = {
|
||||
"session_id": session_id, "state_index": idx, "action_id": decision.action_id,
|
||||
@ -108,8 +108,6 @@ class NegotiationService:
|
||||
"turn": snap.round_number, "available_actions": decision.available_actions,
|
||||
"reward": reward.total, "done": snap.outcome != NegotiationOutcome.ONGOING,
|
||||
"q_value_at_selection": decision.q_value, "ucb_score_at_selection": decision.ucb_score,
|
||||
"visit_count_at_selection": int(policy.qtable.visits[idx, decision.action_id]),
|
||||
"total_visits_at_selection": int(policy.qtable.state_visits(idx)),
|
||||
"settled_price": int(snap.input_price) if snap.outcome == NegotiationOutcome.SUCCESS else None,
|
||||
}
|
||||
try:
|
||||
|
||||
@ -1,64 +0,0 @@
|
||||
"""회사 프로필(브랜드) 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 # imarketkorea 등 데모 테넌트명 → 파일 브랜드 유지
|
||||
|
||||
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
|
||||
@ -148,11 +148,6 @@ class NegotiationConfig(BaseModel):
|
||||
anchor_rate: float = 0.01 # 목표가 대비 앵커링 인하율 (기본 1%)
|
||||
max_rounds: int = 5 # 라운드 상한(보조). 실제 종료는 '카드 소진' 기준.
|
||||
|
||||
# 결정 스택 규칙층(Phase 1) — ChatEngine 하드코딩을 테넌트별 데이터로.
|
||||
wildcard_1pct_ratio: float = 1.02 # 제시가 ≤ anchor×비율 → 1% 인하 와일드카드로 마무리 유도
|
||||
wildcard_entry_ratio: float = 1.05 # 선택 와일드카드 허용 시 와일드카드 진입 상한(anchor×비율)
|
||||
max_counter_rounds: int = 3 # 에이전트 카운터 제안 상한(초과 시 협상실패 종료)
|
||||
|
||||
def anchor_for(self, target_price: float) -> float:
|
||||
return round(target_price * (1.0 - self.anchor_rate))
|
||||
|
||||
|
||||
@ -8,34 +8,14 @@ Chat_server 는 `chat_engine = ChatEngine()` 전역 무인자 싱글톤이라
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
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 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_loader import TenantConfigLoader
|
||||
|
||||
_CARD_SOURCE_DB = "db"
|
||||
|
||||
|
||||
class TenantEngine:
|
||||
"""한 테넌트의 협상 엔진 조립체 (불변 협력자 보관).
|
||||
@ -69,13 +49,9 @@ class EngineFactory:
|
||||
|
||||
|
||||
class TenantEngineRegistry:
|
||||
def __init__(self, loader: Optional[TenantConfigLoader] = None, factory: type[EngineFactory] = EngineFactory,
|
||||
catalog_repo: Optional[ICardCatalogRepository] = None,
|
||||
company_repo: Optional[ICompanyProfileRepository] = None):
|
||||
def __init__(self, loader: Optional[TenantConfigLoader] = None, factory: type[EngineFactory] = EngineFactory):
|
||||
self._loader = loader or TenantConfigLoader()
|
||||
self._factory = factory
|
||||
self._catalog_repo = catalog_repo or CardCatalogDbRepository()
|
||||
self._company_repo = company_repo or CompanyProfileRepository()
|
||||
self._engines: Dict[str, TenantEngine] = {}
|
||||
self._locks: Dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
|
||||
|
||||
@ -93,7 +69,8 @@ class TenantEngineRegistry:
|
||||
return cached
|
||||
if not self.is_registered(tenant_id):
|
||||
raise KeyError(f"unregistered tenant: {tenant_id}")
|
||||
engine = await self._build(tenant_id)
|
||||
config = self._loader.load(tenant_id)
|
||||
engine = self._factory.build(config)
|
||||
self._engines[tenant_id] = engine
|
||||
LOG.i(f"[TenantEngineRegistry] built engine tenant_id={tenant_id} "
|
||||
f"state={engine.state_space_size} action={engine.action_space_size}")
|
||||
@ -106,55 +83,11 @@ class TenantEngineRegistry:
|
||||
self._engines.pop(tenant_id, None)
|
||||
if not self.is_registered(tenant_id):
|
||||
return None
|
||||
engine = await self._build(tenant_id)
|
||||
config = self._loader.load(tenant_id)
|
||||
engine = self._factory.build(config)
|
||||
self._engines[tenant_id] = 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]:
|
||||
return list(self._engines.keys())
|
||||
|
||||
|
||||
@ -15,7 +15,5 @@
|
||||
"가격협상_와일드": "가격협상",
|
||||
"협상완료": "협상종료",
|
||||
"협상실패": "협상종료",
|
||||
"협상종료": "협상종료",
|
||||
"가격협상_카운터": "가격협상",
|
||||
"wild_card_dynamic": "가격협상"
|
||||
"협상종료": "협상종료"
|
||||
}
|
||||
@ -1,12 +1,12 @@
|
||||
{
|
||||
"_comment": "가격협상(카드선택) 턴에 출력할 협상 카드 스크립트. action_id(0~8) → 멘트. 선행 chat_server 의 nego_card_scripts 를 대체하는 중립 기본값(CLEANROOM.md). 실제 운영 시 card.nego_cards.script 로 override(내부 소스만 변경, 흐름 동일). 변수: {target}=목표가, {input_price}=직전 제시가, {anchor}=앵커가, {discount_rate}=기존가 대비 인하율(%).",
|
||||
"_comment": "가격협상(카드선택) 턴에 출력할 협상 카드 스크립트. action_id(0~8) → 멘트. 선행 chat_server 의 nego_card_scripts 를 대체하는 중립 기본값(CLEANROOM.md). 실제 운영 시 card.nego_cards.script 로 override(내부 소스만 변경, 흐름 동일). 변수: {target}=목표 매입가, {input_price}=직전 제시가, {anchor}=앵커가, {discount_rate}=기존가 대비 인하율(%).",
|
||||
"0": "제안해 주신 **{input_price}원**, 감사합니다. 다만 동일 품목의 시장 거래가를 감안하면 추가 조정 여력이 있어 보입니다. 한 번 더 검토해 가격을 제안해 주시겠어요?",
|
||||
"1": "적극적으로 협조해 주셔서 감사합니다. 현재 제시가는 {label_target_price}(**{target}원**)와는 아직 차이가 있습니다. 조금만 더 좁혀 주시면 우선협상 대상으로 검토하겠습니다.",
|
||||
"2": "좋은 제안 감사합니다. 다른 {label_supplier}들의 제안 수준을 고려할 때, 현재 금액으로는 경쟁력이 다소 부족합니다. 재검토된 가격을 부탁드립니다.",
|
||||
"1": "적극적으로 협조해 주셔서 감사합니다. 현재 제시가는 목표 매입가(**{target}원**)와는 아직 차이가 있습니다. 조금만 더 좁혀 주시면 우선협상 대상으로 검토하겠습니다.",
|
||||
"2": "좋은 제안 감사합니다. 다른 협력사들의 제안 수준을 고려할 때, 현재 금액으로는 경쟁력이 다소 부족합니다. 재검토된 가격을 부탁드립니다.",
|
||||
"3": "협상에 성실히 임해 주셔서 감사합니다. 내부 승인 기준에 맞추려면 앵커가({anchor}원) 수준에 가까운 제안이 필요합니다. 가능하신 범위에서 다시 제안해 주세요.",
|
||||
"4": "제시해 주신 조건은 의미 있는 진전입니다. 다만 거래를 확정하려면 조금 더 협조가 필요합니다. 한 차례 더 조정해 주시겠어요?",
|
||||
"4": "제시해 주신 인하율 약 {discount_rate}%는 의미 있는 진전입니다. 다만 거래를 확정하려면 조금 더 협조가 필요합니다. 한 차례 더 조정해 주시겠어요?",
|
||||
"5": "장기적인 협력 관계를 고려해 최대한 반영하고자 합니다. 현재 제시가에서 추가로 조정해 주시면 즉시 검토를 진행하겠습니다. 다시 제안 부탁드립니다.",
|
||||
"6": "검토 결과, 현재 제시가는 우리 기준을 충족하기 직전 단계입니다. 마지막으로 한 번 더 조정된 가격을 제안해 주시면 협상을 마무리할 수 있습니다.",
|
||||
"7": "성의 있는 제안 감사합니다. 다만 물량과 납기 조건을 함께 고려하면 {input_price}원은 다소 높습니다. {label_target_price}({target}원)에 가까운 금액을 제안해 주세요.",
|
||||
"7": "성의 있는 제안 감사합니다. 다만 물량과 납기 조건을 함께 고려하면 {input_price}원은 다소 높습니다. 목표 매입가({target}원)에 가까운 금액을 제안해 주세요.",
|
||||
"8": "긍정적으로 검토되고 있습니다. 내부 결재를 위해 명분이 조금 더 필요한 상황입니다. 가능하신 선에서 한 번 더 인하된 가격을 제안해 주시겠어요?"
|
||||
}
|
||||
|
||||
@ -5,37 +5,25 @@
|
||||
"editor_script_id": "시작",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "서비스안내"
|
||||
},
|
||||
"next_step": { "default": "서비스안내" },
|
||||
"type": "null",
|
||||
"chat_end": false
|
||||
},
|
||||
"서비스안내": {
|
||||
"script": "안녕하세요. {company_name} {service_name}입니다. 본 서비스는 {company_name}와 {label_supplier} 간 물품 공급 가격 협상을 위한 것으로, 귀사가 공급 중인 품목의 새로운 가격 협상을 진행합니다. 안내 사항을 확인하신 뒤, 다음 단계로 넘어가려면 [확인]을 눌러 주세요.",
|
||||
"script": "안녕하세요. {company_name} {service_name}입니다. 본 서비스는 {company_name}와 협력사 간 물품 공급 가격 협상을 위한 것으로, 귀사가 공급 중인 품목의 새로운 가격 협상을 진행합니다. 안내 사항을 확인하신 뒤, 다음 단계로 넘어가려면 [확인]을 눌러 주세요.",
|
||||
"editor_script_id": "서비스안내",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": [
|
||||
"확인"
|
||||
],
|
||||
"next_step": {
|
||||
"default": "담당자확인"
|
||||
},
|
||||
"input_options": ["확인"],
|
||||
"next_step": { "default": "담당자확인" },
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"담당자확인": {
|
||||
"script": "본 안내는 {label_supplier} 포털에 등록된 담당자에게 발송되었습니다. 구매 협상 담당자가 맞는지 다시 한 번 확인 부탁드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택해 주세요.",
|
||||
"script": "본 안내는 협력사 포털에 등록된 담당자에게 발송되었습니다. 구매 협상 담당자가 맞는지 다시 한 번 확인 부탁드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택해 주세요.",
|
||||
"editor_script_id": "담당자확인",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"예",
|
||||
"아니오"
|
||||
],
|
||||
"next_step": {
|
||||
"예": "협상품목안내",
|
||||
"아니오": "담당자확인_아니오"
|
||||
},
|
||||
"input_options": ["예", "아니오"],
|
||||
"next_step": { "예": "협상품목안내", "아니오": "담당자확인_아니오" },
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
@ -43,19 +31,13 @@
|
||||
"script": "[아니오]를 선택하셨습니다. 담당자가 변경되어 정보를 수정하시려면 [정보변경]을, 실수로 선택하신 경우 다시 진행하려면 [돌아가기]를 선택해 주세요.",
|
||||
"editor_script_id": "담당자확인_아니오",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"돌아가기",
|
||||
"정보변경"
|
||||
],
|
||||
"next_step": {
|
||||
"돌아가기": "담당자확인",
|
||||
"정보변경": "정보변경_완료"
|
||||
},
|
||||
"input_options": ["돌아가기", "정보변경"],
|
||||
"next_step": { "돌아가기": "담당자확인", "정보변경": "정보변경_완료" },
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"정보변경_완료": {
|
||||
"script": "[정보변경]을 선택하셨습니다. {label_supplier} 관리 시스템에서 담당자 정보를 변경하신 뒤, 고객센터로 새 견적 생성을 요청해 주세요. 24시간 이내에 갱신되지 않으면 참여 의사가 없는 것으로 간주되어 해당 견적 건이 미참여로 처리될 수 있습니다.",
|
||||
"script": "[정보변경]을 선택하셨습니다. 협력사 관리 시스템에서 담당자 정보를 변경하신 뒤, 고객센터로 새 견적 생성을 요청해 주세요. 24시간 이내에 갱신되지 않으면 참여 의사가 없는 것으로 간주되어 해당 견적 건이 미참여로 처리될 수 있습니다.",
|
||||
"editor_script_id": "정보변경_완료",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
@ -67,12 +49,8 @@
|
||||
"script": "{company_name}는 귀사의 협력에 진심으로 감사드립니다. 이번 가격 협상 품목과 기본 정보를 안내드립니다. 좌측의 상품 정보를 확인해 주세요. 협상이 원만히 마무리되면 더 많은 협력 기회가 마련될 수 있습니다.",
|
||||
"editor_script_id": "협상품목안내",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": [
|
||||
"확인"
|
||||
],
|
||||
"next_step": {
|
||||
"확인": "기존가격제시"
|
||||
},
|
||||
"input_options": ["확인"],
|
||||
"next_step": { "확인": "기존가격제시" },
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
@ -81,9 +59,7 @@
|
||||
"editor_script_id": "기존가격제시",
|
||||
"next_input_mode": "price",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "가격협상_확인"
|
||||
},
|
||||
"next_step": { "default": "가격협상_확인" },
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
@ -92,42 +68,22 @@
|
||||
"editor_script_id": "가격협상_재입력",
|
||||
"next_input_mode": "price",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "가격협상_확인"
|
||||
},
|
||||
"next_step": { "default": "가격협상_확인" },
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
"가격협상_확인": {
|
||||
"script": "제시하신 가격은 **{input_price}원**입니다. {discount_phrase}이 금액으로 제안하시겠습니까? 수정하시려면 [아니오]를 선택해 주세요.",
|
||||
"script": "제시하신 가격은 **{input_price}원**으로, 기존 공급가 대비 약 **{discount_rate}%** 인하된 금액입니다. 이 금액으로 제안하시겠습니까? 수정하시려면 [아니오]를 선택해 주세요.",
|
||||
"editor_script_id": "가격협상_확인",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"예",
|
||||
"아니오"
|
||||
],
|
||||
"input_options": ["예", "아니오"],
|
||||
"next_step": {
|
||||
"예": [
|
||||
{
|
||||
"condition": "check_wildcard_entry",
|
||||
"next": "가격협상_와일드"
|
||||
},
|
||||
{
|
||||
"condition": "check_is_supplier_type_c",
|
||||
"next": "협상완료"
|
||||
},
|
||||
{
|
||||
"condition": "check_price_match",
|
||||
"next": "협상완료"
|
||||
},
|
||||
{
|
||||
"condition": "check_iteration_limit",
|
||||
"next": "협상실패"
|
||||
},
|
||||
{
|
||||
"condition": "default",
|
||||
"next": "가격협상"
|
||||
}
|
||||
{ "condition": "check_wildcard_entry", "next": "가격협상_와일드" },
|
||||
{ "condition": "check_is_supplier_type_c", "next": "협상완료" },
|
||||
{ "condition": "check_price_match", "next": "협상완료" },
|
||||
{ "condition": "check_iteration_limit", "next": "협상실패" },
|
||||
{ "condition": "default", "next": "가격협상" }
|
||||
],
|
||||
"아니오": "가격협상_재입력"
|
||||
},
|
||||
@ -138,14 +94,8 @@
|
||||
"script": "제시하신 금액은 **{input_price}원**입니다. 이 금액으로 견적을 제출하시겠습니까? 수정하시려면 [아니오]를 선택해 주세요.",
|
||||
"editor_script_id": "가격협상_확인_버짓",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"예",
|
||||
"아니오"
|
||||
],
|
||||
"next_step": {
|
||||
"예": "협상완료",
|
||||
"아니오": "가격협상_재입력"
|
||||
},
|
||||
"input_options": ["예", "아니오"],
|
||||
"next_step": { "예": "협상완료", "아니오": "가격협상_재입력" },
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
@ -154,9 +104,7 @@
|
||||
"editor_script_id": "가격협상",
|
||||
"next_input_mode": "price",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "가격협상_확인"
|
||||
},
|
||||
"next_step": { "default": "가격협상_확인" },
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
@ -164,12 +112,8 @@
|
||||
"script": "협조해 주신 덕분에 원만히 협상이 완료되었습니다. 협상 결과를 확인하신 뒤 동의해 주세요. 거래 약정에 따라 일부 조건이 조정될 수 있는 점 참고 부탁드립니다. 성실히 응해 주셔서 감사합니다.",
|
||||
"editor_script_id": "협상완료",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": [
|
||||
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."
|
||||
],
|
||||
"next_step": {
|
||||
"default": "협상종료"
|
||||
},
|
||||
"input_options": ["협상 내용을 확인했으며, 이의가 없음에 동의합니다."],
|
||||
"next_step": { "default": "협상종료" },
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
@ -178,9 +122,7 @@
|
||||
"editor_script_id": "협상실패",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "협상종료"
|
||||
},
|
||||
"next_step": { "default": "협상종료" },
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
},
|
||||
@ -192,21 +134,5 @@
|
||||
"next_step": null,
|
||||
"type": "text",
|
||||
"chat_end": true
|
||||
},
|
||||
"가격협상_카운터": {
|
||||
"script": "제시해 주신 **{input_price}원** 검토했습니다. 저희는 **{counter_price}원**을 제안드립니다. 이 가격으로 진행 가능하시면 '수락'을, 어려우시면 '다른 가격 제시'를 선택해 주세요.",
|
||||
"editor_script_id": "가격협상_카운터",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"수락",
|
||||
"다른 가격 제시"
|
||||
],
|
||||
"next_step": {
|
||||
"수락": "협상완료",
|
||||
"다른 가격 제시": "가격협상_재입력",
|
||||
"default": "가격협상_재입력"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
}
|
||||
}
|
||||
@ -10,7 +10,7 @@
|
||||
"chat_end": false
|
||||
},
|
||||
"서비스안내": {
|
||||
"script": "안녕하세요. {company_name} {service_name}입니다. 본 서비스는 {company_name}와 {label_supplier} 간 신규 물품 공급 협상을 위한 것으로, 귀사에 새로운 공급 기회를 제공하고자 합니다. 이용 방법 안내를 확인하신 뒤 [확인]을 눌러 주세요.",
|
||||
"script": "안녕하세요. {company_name} {service_name}입니다. 본 서비스는 {company_name}와 협력사 간 신규 물품 공급 협상을 위한 것으로, 귀사에 새로운 공급 기회를 제공하고자 합니다. 이용 방법 안내를 확인하신 뒤 [확인]을 눌러 주세요.",
|
||||
"editor_script_id": "서비스안내",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": ["확인"],
|
||||
@ -19,7 +19,7 @@
|
||||
"chat_end": false
|
||||
},
|
||||
"담당자확인": {
|
||||
"script": "본 안내는 {label_supplier} 포털에 등록된 담당자에게 발송되었습니다. 구매 협상 담당자가 맞는지 확인 부탁드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택해 주세요.",
|
||||
"script": "본 안내는 협력사 포털에 등록된 담당자에게 발송되었습니다. 구매 협상 담당자가 맞는지 확인 부탁드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택해 주세요.",
|
||||
"editor_script_id": "담당자확인",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": ["예", "아니오"],
|
||||
@ -37,7 +37,7 @@
|
||||
"chat_end": false
|
||||
},
|
||||
"정보변경_완료": {
|
||||
"script": "[정보변경]을 선택하셨습니다. {label_supplier} 관리 시스템에서 담당자 정보를 변경하신 뒤 고객센터로 새 견적 생성을 요청해 주세요. 24시간 이내 갱신되지 않으면 미참여로 처리될 수 있습니다.",
|
||||
"script": "[정보변경]을 선택하셨습니다. 협력사 관리 시스템에서 담당자 정보를 변경하신 뒤 고객센터로 새 견적 생성을 요청해 주세요. 24시간 이내 갱신되지 않으면 미참여로 처리될 수 있습니다.",
|
||||
"editor_script_id": "정보변경_완료",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
@ -46,7 +46,7 @@
|
||||
"chat_end": true
|
||||
},
|
||||
"협상품목안내": {
|
||||
"script": "{company_name}는 아래 상품에 대해 신규 {label_supplier_를} 선정하고 있으며, 귀사를 초대하여 견적을 요청드립니다. 제출하신 견적은 복수 업체와의 비교 평가를 통해 {label_supplier} 선정에 반영됩니다. 상품 정보를 확인해 주세요.",
|
||||
"script": "{company_name}는 아래 상품에 대해 신규 공급사를 선정하고 있으며, 귀사를 초대하여 견적을 요청드립니다. 제출하신 견적은 복수 업체와의 비교 평가를 통해 공급사 선정에 반영됩니다. 상품 정보를 확인해 주세요.",
|
||||
"editor_script_id": "협상품목안내",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": ["네, 알겠습니다."],
|
||||
@ -73,10 +73,10 @@
|
||||
"chat_end": false
|
||||
},
|
||||
"배송형태선택": {
|
||||
"script": "{label_delivery_type_를} 선택해 주세요.",
|
||||
"script": "배송 형태를 선택해 주세요.",
|
||||
"editor_script_id": "배송형태선택",
|
||||
"next_input_mode": "delivery_type",
|
||||
"input_options": ["{label_delivery_type_1}", "{label_delivery_type_2}", "{label_delivery_type_3}"],
|
||||
"input_options": ["협력사배송", "지정택배배송", "픽업배송"],
|
||||
"next_step": { "default": "가격협상_입력" },
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
|
||||
@ -5,39 +5,17 @@
|
||||
"type": "text",
|
||||
"chat_end": false,
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"예",
|
||||
"아니오"
|
||||
],
|
||||
"next_step": {
|
||||
"default": "협상완료"
|
||||
},
|
||||
"input_options": ["예", "아니오"],
|
||||
"next_step": { "default": "협상완료" },
|
||||
"editor_script_id": "wild_card_1pct"
|
||||
},
|
||||
"wild_card_budget": {
|
||||
"script": "솔직히 말씀드리면 현재 내부 예산(재원) 사정상 제안을 그대로 수용하기 어렵습니다. 당사 {label_target_price}는 **{target}원**입니다. 이 가격에 맞춰 주신다면 즉시 계약을 진행하고자 합니다. 마지막으로 한 번 더 제안 부탁드립니다.",
|
||||
"script": "솔직히 말씀드리면 현재 내부 예산(재원) 사정상 제안을 그대로 수용하기 어렵습니다. 목표 매입가는 **{target}원**입니다. 이 가격에 맞춰 주신다면 즉시 계약을 진행하고자 합니다. 마지막으로 한 번 더 제안 부탁드립니다.",
|
||||
"type": "text",
|
||||
"chat_end": false,
|
||||
"next_input_mode": "price",
|
||||
"input_options": [],
|
||||
"next_step": {
|
||||
"default": "가격협상_확인_버짓"
|
||||
},
|
||||
"next_step": { "default": "가격협상_확인_버짓" },
|
||||
"editor_script_id": "wild_card_budget"
|
||||
},
|
||||
"wild_card_dynamic": {
|
||||
"script": "저희는 **{counter_price}원**이면 즉시 진행이 가능합니다. 이 가격으로 진행 가능하시면 '수락'을, 어려우시면 '다른 가격 제시'를 선택해 주세요.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
"수락",
|
||||
"다른 가격 제시"
|
||||
],
|
||||
"next_step": {
|
||||
"수락": "협상완료",
|
||||
"다른 가격 제시": "가격협상_재입력",
|
||||
"default": "가격협상_재입력"
|
||||
},
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
}
|
||||
}
|
||||
@ -49,14 +49,9 @@ policy:
|
||||
epsilon: 1.0e-6
|
||||
|
||||
action_mapping:
|
||||
# db: action_to_card 를 card.nego_cards 카탈로그(user_id NULL, number 순)에서 동적 구성 — 정본.
|
||||
# 카드가 negodata 에서 추가/삭제되면 action space 가 자동 반영된다(config 수정 불필요).
|
||||
# 아래 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↔카드 대응을 견적마다 일정하게 유지해 학습 일관성 보장.
|
||||
type: file
|
||||
# 기본 9카드 — 자동 온보딩(신규 company_id) 테넌트가 물려받는 카드 공간(base 정책 162×9와 정합).
|
||||
# 테넌트는 자사 카탈로그(card.nego_cards/tenant_action_cards)로 override 한다.
|
||||
action_to_card:
|
||||
"0": "NGC-001"
|
||||
"1": "NGC-002"
|
||||
@ -67,8 +62,6 @@ action_mapping:
|
||||
"6": "NGC-007"
|
||||
"7": "NGC-008"
|
||||
"8": "NGC-009"
|
||||
"9": "NGC-010"
|
||||
"10": "NGC-011"
|
||||
|
||||
cards:
|
||||
# file: scripts_cards.json(파일) 사용. backoffice_db: card.nego_cards.script(negodata 편집 정본)를
|
||||
@ -78,7 +71,7 @@ cards:
|
||||
connection: {}
|
||||
|
||||
llm:
|
||||
enabled: true
|
||||
enabled: false
|
||||
|
||||
resources:
|
||||
language: ko
|
||||
|
||||
@ -23,7 +23,7 @@ reward:
|
||||
|
||||
action_mapping:
|
||||
type: file
|
||||
action_to_card: # 동일 차원(11) 유지 → warm-start 가능. 합성 데모 코드(테넌트 B).
|
||||
action_to_card: # 동일 차원(9) 유지 → warm-start 가능. 합성 데모 코드(테넌트 B).
|
||||
"0": "NGC-B001"
|
||||
"1": "NGC-B002"
|
||||
"2": "NGC-B003"
|
||||
@ -33,13 +33,9 @@ action_mapping:
|
||||
"6": "NGC-B007"
|
||||
"7": "NGC-B008"
|
||||
"8": "NGC-B009"
|
||||
"9": "NGC-B010"
|
||||
"10": "NGC-B011"
|
||||
|
||||
llm:
|
||||
enabled: true
|
||||
# api_key_ref 는 미구현(dead) — 현재 LLM 키는 전역 config.local.toml [OpenAIConfig].api_key
|
||||
# (또는 OPENAI_API_KEY env) 를 사용한다. 테넌트별 키 분리는 표현층(Phase 2) 본작업에서 구현.
|
||||
enabled: false
|
||||
api_key_ref: TENANT_B_OPENAI_API_KEY
|
||||
|
||||
resources:
|
||||
|
||||
30
agent/tenants/ktcommerce/tenant.yaml
Normal file
30
agent/tenants/ktcommerce/tenant.yaml
Normal file
@ -0,0 +1,30 @@
|
||||
# 데모 테넌트 프로파일 (합성/중립값 — CLEANROOM.md).
|
||||
# tenant_id 는 라우팅 키일 뿐이며, 아래 값은 해당 회사의 실제 운영값이 아니다.
|
||||
# 실제 운영 시 카드 카탈로그(card.nego_cards)·튜닝값은 테넌트 비공개 소스에서 주입한다.
|
||||
tenant_id: ktcommerce
|
||||
inherits_base: true
|
||||
name: "Demo Tenant A"
|
||||
company_id: null # P3 시드 시 company.companies.company_id(uuid) 로 채움
|
||||
|
||||
action_mapping:
|
||||
type: file
|
||||
action_to_card: # 우리 중립 데모 카드 코드(합성). 실제 카드 코드 아님.
|
||||
"0": "NGC-A001"
|
||||
"1": "NGC-A002"
|
||||
"2": "NGC-A003"
|
||||
"3": "NGC-A004"
|
||||
"4": "NGC-A005"
|
||||
"5": "NGC-A006"
|
||||
"6": "NGC-A007"
|
||||
"7": "NGC-A008"
|
||||
"8": "NGC-A009"
|
||||
|
||||
llm:
|
||||
enabled: false # P7 에서 테넌트별 자격증명 주입
|
||||
api_key_ref: TENANT_A_OPENAI_API_KEY
|
||||
|
||||
resources:
|
||||
language: ko
|
||||
scripts_dir: resources # 없으면 _base/resources 폴백
|
||||
company_name: "데모상사 A" # 스크립트 {company_name} 치환값 (합성)
|
||||
service_name: "Negosium"
|
||||
@ -1,157 +0,0 @@
|
||||
"""협상 퍼즈 하네스 — 랜덤 조건·랜덤 협력사 행동으로 N회 완주시키고 불변식 위반을 수집한다.
|
||||
시드 고정(재현 가능). test_ 접두사 없음 — pytest 수집 대상 아님, 수동 실행 전용:
|
||||
docker run --rm -v $PWD/agent:/work -w /work -e APP_ENV=local -e DB_HOST=host.docker.internal \
|
||||
o2o-negosium-agent sh -lc "pip install -q pytest pytest-asyncio httpx; python tests/fuzz_negotiation.py"
|
||||
|
||||
케이스마다 검사하는 불변식:
|
||||
1. 전 턴 success
|
||||
2. 같은 카드 2회 발동 금지
|
||||
3. 종결 전용(WC-03·05)은 가격협상_카운터에서만 / 비종결 와일드는 wild_card_dynamic 에서만
|
||||
4. 타결 시 타결가 ≤ 목표가
|
||||
5. 카운터/1% 수락으로 타결하면 그 멘트에 타결가 표기
|
||||
6. 멘트·버튼에 미치환 토큰({xxx}) 잔존 금지
|
||||
7. 턴 상한(60) 안에 반드시 종료
|
||||
"""
|
||||
import asyncio
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, "/work")
|
||||
|
||||
from router.v1.chat.protocol import Req_Chat # noqa: E402
|
||||
from services.chat_service import ChatService, reset_sessions # noqa: E402
|
||||
from tenancy.config_loader import TenantConfigLoader # noqa: E402
|
||||
from tenancy.registry import TenantEngineRegistry # noqa: E402
|
||||
from tests.test_card_tactics import _TENANTS_DIR, _cleanup, _seed_quote_session # noqa: E402
|
||||
|
||||
N = 100
|
||||
SEED = 20260805
|
||||
TARGET = 10_000
|
||||
NEGO_POOL = ["NGC-001", "NGC-002", "NGC-003", "NGC-004", "NGC-005",
|
||||
"NGC-007", "NGC-008", "NGC-010", "NGC-011"]
|
||||
WILD_POOL = ["WC-01", "WC-02", "WC-03", "WC-04", "WC-05"]
|
||||
CLOSING = {"WC-03", "WC-05"}
|
||||
TOKEN_RE = re.compile(r"(?<!\{)\{([a-z_0-9]+)\}(?!\})")
|
||||
|
||||
|
||||
class Supplier:
|
||||
"""랜덤 협력사 — 높은 시작가에서 점진 양보, 카운터는 확률적으로 수락/거절."""
|
||||
|
||||
def __init__(self, rng, anchor):
|
||||
self.rng = rng
|
||||
self.anchor = anchor
|
||||
self.price = TARGET * rng.uniform(1.02, 1.30)
|
||||
self.accept_p = rng.uniform(0.15, 0.5)
|
||||
|
||||
def next_price(self):
|
||||
p = int(self.price)
|
||||
# 다음 라운드를 위해 양보 — 가끔 앵커 밑까지 다이브(우선협상 유도).
|
||||
self.price *= self.rng.uniform(0.90, 0.99)
|
||||
if self.rng.random() < 0.15:
|
||||
self.price = self.anchor * self.rng.uniform(0.95, 1.04)
|
||||
return str(max(p, 100))
|
||||
|
||||
def choose(self, options):
|
||||
if "수락" in options:
|
||||
return "수락" if self.rng.random() < self.accept_p else "다른 가격 제시"
|
||||
if set(options) >= {"예", "아니오"}:
|
||||
return "예" if self.rng.random() < max(self.accept_p, 0.5) else "아니오"
|
||||
return options[0] if options else "확인"
|
||||
|
||||
|
||||
async def run_case(idx, rng):
|
||||
anchor = int(TARGET * rng.choice([0.99, 0.99, 0.97, 0.95, 1.0]))
|
||||
nego = rng.sample(NEGO_POOL, rng.randint(1, 5))
|
||||
wild = rng.sample(WILD_POOL, rng.randint(0, 5))
|
||||
sup = Supplier(rng, anchor)
|
||||
|
||||
reset_sessions()
|
||||
sid = uuid.uuid4()
|
||||
qid, ver = await _seed_quote_session(sid, nego, wild_numbers=wild, target=TARGET, anchor=anchor)
|
||||
violations, fired, settled, outcome, ended = [], [], None, None, False
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(uuid.uuid4()))
|
||||
svc = ChatService()
|
||||
ui, last_input = None, None
|
||||
for _turn in range(60):
|
||||
r = await svc.chat(eng, Req_Chat(session_id=str(sid), user_input=ui))
|
||||
if r.result.success is not True:
|
||||
violations.append(f"턴 실패 input={ui} msg={r.msg}")
|
||||
break
|
||||
script, opts = r.script or "", list(r.input_options or [])
|
||||
if TOKEN_RE.search(script):
|
||||
violations.append(f"미치환 토큰(script): {TOKEN_RE.findall(script)} @ {r.step}")
|
||||
for o in opts:
|
||||
if TOKEN_RE.search(o):
|
||||
violations.append(f"미치환 토큰(option): {o} @ {r.step}")
|
||||
if r.card_id:
|
||||
fired.append((r.step, r.card_id))
|
||||
if r.settled_price is not None:
|
||||
settled = r.settled_price
|
||||
# 카운터/1% '수락' 타결이면 마지막 카운터 멘트에 타결가가 보였어야 한다.
|
||||
if last_input in ("수락",) and str(settled) not in (last_counter or ""):
|
||||
violations.append(f"표시가≠타결가: {settled} not in counter script")
|
||||
if r.step in ("가격협상_카운터", "wild_card_dynamic", "wild_card_1pct"):
|
||||
last_counter = script
|
||||
if r.chat_end:
|
||||
outcome, ended = r.outcome, True
|
||||
break
|
||||
# 다음 입력 결정
|
||||
last_input = None
|
||||
if r.input_mode == "price":
|
||||
ui = sup.next_price()
|
||||
elif opts:
|
||||
ui = sup.choose(opts)
|
||||
last_input = ui
|
||||
else:
|
||||
ui = "확인"
|
||||
if not ended:
|
||||
violations.append("60턴 내 미종료")
|
||||
|
||||
# 카드 불변식
|
||||
ids = [c for _, c in fired]
|
||||
if len(ids) != len(set(ids)):
|
||||
violations.append(f"카드 중복: {ids}")
|
||||
for step, c in fired:
|
||||
if c in CLOSING and step != "가격협상_카운터":
|
||||
violations.append(f"종결 카드 {c} 가 {step} 에서 발동")
|
||||
if c.startswith("WC") and c not in CLOSING and step != "wild_card_dynamic":
|
||||
violations.append(f"비종결 와일드 {c} 가 {step} 에서 발동")
|
||||
if outcome == "success":
|
||||
if settled is None:
|
||||
violations.append("성공인데 settled 없음")
|
||||
elif settled > TARGET:
|
||||
violations.append(f"목표가 초과 타결: {settled}")
|
||||
finally:
|
||||
await _cleanup(sid, qid, ver)
|
||||
return {"idx": idx, "anchor": anchor, "nego": nego, "wild": wild,
|
||||
"fired": fired, "settled": settled, "outcome": outcome, "violations": violations}
|
||||
|
||||
|
||||
async def main():
|
||||
rng = random.Random(SEED)
|
||||
results, bad = [], []
|
||||
for i in range(N):
|
||||
res = await run_case(i, random.Random(rng.random()))
|
||||
results.append(res)
|
||||
if res["violations"]:
|
||||
bad.append(res)
|
||||
tag = "OK " if not res["violations"] else "BAD"
|
||||
print(f"[{tag}] #{i:02d} anchor={res['anchor']} nego={len(res['nego'])} wild={len(res['wild'])} "
|
||||
f"fired={'→'.join(c for _, c in res['fired']) or '-'} settled={res['settled']} {res['outcome']}")
|
||||
ok = sum(1 for r in results if not r["violations"])
|
||||
succ = sum(1 for r in results if r["outcome"] == "success")
|
||||
print(f"\n===== {ok}/{N} clean · 타결 {succ} / 결렬 {N - succ} =====")
|
||||
for r in bad:
|
||||
print(f"\n#{r['idx']} 위반: nego={r['nego']} wild={r['wild']} anchor={r['anchor']}")
|
||||
for v in r["violations"]:
|
||||
print(" -", v)
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
await DB_SESSION_MNG.dispose_all()
|
||||
sys.exit(0 if not bad else 1)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@ -29,7 +29,7 @@ def _reg():
|
||||
@pytest.mark.asyncio
|
||||
async def test_4_1_honors_backend_session_id(db_engine):
|
||||
reset_sessions()
|
||||
eng = await _reg().get_engine("imarketkorea")
|
||||
eng = await _reg().get_engine("ktcommerce")
|
||||
svc = ChatService()
|
||||
|
||||
# 첫 턴: backend 의 session_id 를 그대로 키로 써야 함 (새 uuid 발급 X)
|
||||
@ -53,7 +53,7 @@ async def test_4_4_company_id_auto_onboard():
|
||||
eng = await _reg().get_engine(COMPANY_ID)
|
||||
assert eng.tenant_id == COMPANY_ID
|
||||
assert eng.company_id == COMPANY_ID # 학습/세션이 이 company_id 로 격리
|
||||
assert eng.action_space_size == 9 # DB 카탈로그 9장(NGC-006·009 소프트삭제)
|
||||
assert eng.action_space_size == 9 # base 기본 카드(162×9 정합)
|
||||
assert eng.state_space_size == 162
|
||||
|
||||
|
||||
|
||||
@ -1,154 +0,0 @@
|
||||
"""협상카드 선택 E2E — 실 DB 왕복으로 "견적에서 고른 카드만 뽑히는지" 검증.
|
||||
|
||||
시나리오: 견적 생성 시 협상카드 2장(NGC-003, NGC-007)만 선택 →
|
||||
version_nego_cards 로 연결 → 협상 세션 시작 → 가격협상 턴 2회 진행.
|
||||
검증: ① 뽑힌 카드가 선택 2장 안에서만 나옴(선택 마스크) ② 세션 내 중복 없음(사용 마스크)
|
||||
③ 카탈로그(DB, NGC-001~011) 기준 action space ④ 선택 없으면 전체 카탈로그 허용(폴백).
|
||||
"""
|
||||
|
||||
import os
|
||||
import uuid as _uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import column, delete, insert, select, table
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import DBType, DBWRType, ErrorType
|
||||
from router.v1.chat.protocol import Req_Chat
|
||||
from services.chat_service import ChatService, reset_sessions
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tenancy.registry import TenantEngineRegistry
|
||||
|
||||
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||
|
||||
_T_SESSIONS = table(
|
||||
"sessions",
|
||||
column("session_id"), column("quotation_id"), column("item_id"), column("supplier_id"),
|
||||
column("qt_number"), column("qt_round"), column("qt_type"), column("target_price"),
|
||||
column("anchoring_price"), column("status"), column("end_time"),
|
||||
schema="negotiation",
|
||||
)
|
||||
_T_QUOTATIONS = table(
|
||||
"quotations",
|
||||
column("qt_id"), column("user_id"), column("qt_setting_id"), column("version_id"),
|
||||
column("name"), column("number"), column("type"), column("status"),
|
||||
column("start_time"), column("end_time"),
|
||||
schema="quotation",
|
||||
)
|
||||
_T_VNC = table(
|
||||
"version_nego_cards",
|
||||
column("vnc_id"), column("version_id"), column("nego_card_id"),
|
||||
schema="card",
|
||||
)
|
||||
_T_NEGO = table("nego_cards", column("nego_card_id"), column("number"), column("deleted"), schema="card")
|
||||
|
||||
|
||||
async def _card_uuid(number: str):
|
||||
def _q(s):
|
||||
return DB_SESSION_MNG.execute(
|
||||
s, select(_T_NEGO.c.nego_card_id).where(
|
||||
_T_NEGO.c.number == number, _T_NEGO.c.deleted == False).limit(1)) # noqa: E712
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return rows[0] if rows else None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_selected_cards_only_are_played(db_engine):
|
||||
reset_sessions()
|
||||
sid, qid, ver_id = _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4()
|
||||
iid, sup = _uuid.uuid4(), _uuid.uuid4()
|
||||
now = datetime.now(timezone.utc)
|
||||
selected = ["NGC-003", "NGC-007"]
|
||||
card_ids = {}
|
||||
for n in selected:
|
||||
card_ids[n] = await _card_uuid(n)
|
||||
assert card_ids[n] is not None, f"카탈로그에 {n} 없음(시드 확인)"
|
||||
|
||||
def _seed(s_):
|
||||
async def run(s):
|
||||
e = await DB_SESSION_MNG.add(s, insert(_T_QUOTATIONS).values(
|
||||
qt_id=qid, user_id=_uuid.uuid4(), qt_setting_id=_uuid.uuid4(), version_id=ver_id,
|
||||
name="카드선택E2E", number="QT-CARDSEL-E2E", type=1, status=2,
|
||||
start_time=now, end_time=now + timedelta(days=1)))
|
||||
if e != ErrorType.SUCCESS:
|
||||
return e
|
||||
for n in selected: # 견적 생성 시 선택한 카드 2장
|
||||
e = await DB_SESSION_MNG.add(s, insert(_T_VNC).values(
|
||||
vnc_id=_uuid.uuid4(), version_id=ver_id, nego_card_id=card_ids[n]))
|
||||
if e != ErrorType.SUCCESS:
|
||||
return e
|
||||
return await DB_SESSION_MNG.add(s, insert(_T_SESSIONS).values(
|
||||
session_id=sid, quotation_id=qid, item_id=iid, supplier_id=sup,
|
||||
qt_number="QT-CARDSEL-E2E", qt_round=1, qt_type=1,
|
||||
target_price=10000, anchoring_price=9900, status=2,
|
||||
end_time=now + timedelta(days=1)))
|
||||
return run(s_)
|
||||
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_seed])
|
||||
assert err == ErrorType.SUCCESS
|
||||
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(_uuid.uuid4())) # 자동 온보딩(_base type:db → 실 DB 카탈로그)
|
||||
assert eng.action_space_size == 9 # 카탈로그 9장(NGC-006·009 소프트삭제)
|
||||
|
||||
svc = ChatService()
|
||||
played = []
|
||||
session_id = str(sid)
|
||||
# 적응형 진행: 카드 전술 재설계 후 카운터 제시 카드(NGC-007 등)는 수락/거절 스텝
|
||||
# (가격협상_카운터)으로 전환된다 — 거절하고 새 가격을 제시하며 카드 2턴을 유도한다.
|
||||
prices = iter(["11000", "10600", "10400"])
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id))
|
||||
for _ in range(14):
|
||||
if r.step in ("가격협상", "가격협상_카운터") and r.card_id:
|
||||
played.append(r.card_id)
|
||||
if len(played) == 2:
|
||||
break
|
||||
if r.chat_end:
|
||||
break
|
||||
if r.input_mode == "price":
|
||||
ui = next(prices)
|
||||
elif r.step == "가격협상_카운터":
|
||||
ui = "다른 가격 제시"
|
||||
elif r.input_options:
|
||||
ui = "예" if "예" in r.input_options else r.input_options[0]
|
||||
else:
|
||||
ui = "확인"
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input=ui))
|
||||
|
||||
assert len(played) == 2, f"가격협상 카드 턴 2회 기대, 실제 {played}"
|
||||
# ① 선택한 카드 안에서만 뽑힘 ② 세션 내 중복 없음
|
||||
assert set(played) <= set(selected), f"선택 밖 카드 발동: {played}"
|
||||
assert len(set(played)) == 2, f"카드 중복 사용: {played}"
|
||||
finally:
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[DBType.MAIN.value],
|
||||
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SESSIONS).where(_T_SESSIONS.c.session_id == sid)),
|
||||
lambda s: DB_SESSION_MNG.add(s, delete(_T_VNC).where(_T_VNC.c.version_id == ver_id)),
|
||||
lambda s: DB_SESSION_MNG.add(s, delete(_T_QUOTATIONS).where(_T_QUOTATIONS.c.qt_id == qid))],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_selection_allows_full_catalog(db_engine):
|
||||
"""선택 카드가 없으면(직접호출/데모) 전체 카탈로그가 허용된다 — 카드가 정상적으로 뽑히는지 기본 검증."""
|
||||
reset_sessions()
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(_uuid.uuid4())) # _base type:db → DB 카탈로그
|
||||
catalog = {eng.mapper.get_card_id(a) for a in range(eng.action_space_size)}
|
||||
|
||||
svc = ChatService()
|
||||
played = []
|
||||
sid = None
|
||||
for ui in [None, "확인", "예", "확인", "11000", "예", "10600", "예", "10600", "예"]:
|
||||
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input=ui))
|
||||
sid = r.session_id
|
||||
if r.step == "가격협상" and r.card_id:
|
||||
played.append(r.card_id)
|
||||
if r.chat_end:
|
||||
break
|
||||
|
||||
assert played, "가격협상 카드 턴이 발생해야 함"
|
||||
assert set(played) <= catalog # 카탈로그(NGC-001~011) 내에서만
|
||||
assert len(played) == len(set(played)) # 세션 내 중복 없음
|
||||
@ -1,499 +0,0 @@
|
||||
"""카드 전술 검증 — "스크립트에 꽂힌 변수가 곧 전술" (파싱 + 변수별 유효조건 + tactic JSONB).
|
||||
|
||||
① 제안가 파싱(마지막 제안가 변수) + 변수별 계산식 결정론
|
||||
② 변수 공통 유효조건 — 목표가 초과·제시가 이상이면 미발동(클램프 아님 — IMK 8AB0 회귀)
|
||||
③ 카운터 수락 = 즉시 타결 / 거절 = 재입력 + pending 폐기
|
||||
④ 목표가 초과 타결 금지 가드(성공 스텝 진입 차단)
|
||||
⑤ 와일드 진입 — 종결 전용 카드 예약(중반 미발동) + 카드 이력 공유(중복 발동 차단, IMK BB9A 회귀)
|
||||
⑥ E2E: 견적 선택 카드(NGC-010 목표가 제안)의 카운터를 수락하면 settled=target
|
||||
⑦ E2E: 협력사가 target 초과를 고수하면 종결 전술(최후통첩) 후 결렬 — 고객사 이득 가드레일
|
||||
"""
|
||||
|
||||
import os
|
||||
import uuid as _uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
from negotiation.cards.domain.tactics import (
|
||||
CardSpec, HOLD, available, build_card_spec, compute_offer,
|
||||
is_played, mark_played, parse_offer_variable, playable, spec_from_context,
|
||||
)
|
||||
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession
|
||||
from negotiation.chat.service.script_repository import ScriptRepository
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
|
||||
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||
|
||||
# 엔진 단위 테스트용 카드 스펙(로더가 DB 스크립트 파싱으로 만드는 것과 같은 형태).
|
||||
_SPECS = {
|
||||
"WC-02": {"offer_variable": "target_mid_price", "min_round": 1, "closing": False},
|
||||
"WC-05": {"offer_variable": "middle_price", "min_round": 1, "closing": True},
|
||||
}
|
||||
|
||||
|
||||
def _engine() -> ChatEngine:
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||
return ChatEngine(ScriptRepository(cfg, _TENANTS_DIR), rq_type="재협상")
|
||||
|
||||
|
||||
def _session(step="가격협상_확인", **ctx_over):
|
||||
ctx = {"input_price": 10300, "anchor_price": 10000, "target_price": 10100,
|
||||
"round": 1, "allow_selected_wildcards": False, "card_specs": dict(_SPECS)}
|
||||
ctx.update(ctx_over)
|
||||
return ChatSession(session_id="00000000-0000-0000-0000-00000000e001", tenant_id="imarketkorea",
|
||||
company_id="imarketkorea", step=step, action_space_size=0, context=ctx)
|
||||
|
||||
|
||||
# ---- ① 제안가 파싱 + 계산식 ---------------------------------------------------
|
||||
def test_parse_offer_variable_last_offer_wins():
|
||||
"""제안가 변수가 여럿이면 마지막 것 — 카드 문장은 배경을 먼저, 제안을 마지막에 한다(WC-04)."""
|
||||
assert parse_offer_variable("적정가는 {anchoring_price}원이었으나 {target_price}원으로 제안") == "target_price"
|
||||
assert parse_offer_variable("{target_price}원을 제안 드립니다") == "target_price"
|
||||
# 읽어주기 변수만 있으면 설득 카드 — 제안가 없음
|
||||
assert parse_offer_variable("시장가 {internet_lowest_price}원 안팎, 제시가 {prev_partner_price}원") is None
|
||||
assert parse_offer_variable("가격 변수 없는 설득 멘트") is None
|
||||
assert parse_offer_variable(None) is None
|
||||
# WC-05 정본: 읽어주기(직전 제안·제시가) 뒤 절충가 제안
|
||||
assert parse_offer_variable("당사 제안 {prev_customer_price}원과 귀사 제안 {prev_partner_price}원을 절반씩, {middle_price}원으로") == "middle_price"
|
||||
# negodata 에디터 칩 표기(anchor_price)도 앵커가 제안으로 인식 — DB 시드 표기(anchoring_price)의 별칭
|
||||
assert parse_offer_variable("예산 한도는 {anchor_price}원입니다") == "anchor_price"
|
||||
|
||||
|
||||
def test_build_card_spec_merges_script_and_tactic():
|
||||
spec = build_card_spec("{target_price}원으로 제안", {"min_round": 2, "closing": True})
|
||||
assert spec == CardSpec(offer_variable="target_price", min_round=2, closing=True)
|
||||
# tactic 없음 → 기본값. offer_variable override 는 파싱보다 우선.
|
||||
assert build_card_spec("설득 멘트", None) == HOLD
|
||||
assert build_card_spec("멘트", {"offer_variable": "anchoring_price"}).offer_variable == "anchoring_price"
|
||||
|
||||
|
||||
def test_offer_formulas():
|
||||
ctx = {"input_price": 11000, "anchor_price": 9900, "target_price": 10000}
|
||||
offer = lambda var, c=None: compute_offer(CardSpec(offer_variable=var), c or ctx) # noqa: E731
|
||||
assert offer("target_price") == 10000
|
||||
assert offer("anchoring_price") == 9900
|
||||
assert offer("target_mid_price") == 9950 # (anchor+target)/2
|
||||
# 절충가: 갑 직전 포지션 폴백 = anchor → (8900+9500)/2 = 9200
|
||||
assert offer("middle_price", dict(ctx, input_price=9500, anchor_price=8900)) == 9200
|
||||
# 갑 직전 포지션이 있으면 그 기준: (9000+9500)/2 = 9250
|
||||
assert offer("middle_price", dict(ctx, input_price=9500, prev_customer_price=9000)) == 9250
|
||||
|
||||
|
||||
# ---- ② 변수 공통 유효조건 — 미발동(클램프 아님) --------------------------------
|
||||
def test_offer_over_target_does_not_fire_imk_8ab0():
|
||||
"""IMK 8AB0 회귀: 목표가 9,000 / 제시가 9,500 → 절충가 (8,910+9,500)/2 = 9,205 > 목표가.
|
||||
구현이 목표가로 깎아 부르면 '중간에서 만나자며 목표가를 부르는' 모순 — 클램프가 아니라 미발동이 정답."""
|
||||
ctx = {"input_price": 9500, "anchor_price": 8910, "target_price": 9000}
|
||||
assert compute_offer(CardSpec(offer_variable="middle_price"), ctx) is None
|
||||
|
||||
|
||||
def test_offer_at_or_above_input_price_does_not_fire():
|
||||
"""협력사 제시가가 이미 제안가 이하면 부를 이유가 없다 → 미발동."""
|
||||
ctx = {"input_price": 9950, "anchor_price": 9900, "target_price": 10000}
|
||||
assert compute_offer(CardSpec(offer_variable="target_price"), ctx) is None # target ≥ 제시가
|
||||
assert compute_offer(CardSpec(offer_variable="anchoring_price"), dict(ctx, input_price=9900)) is None
|
||||
|
||||
|
||||
def test_offer_without_materials_does_not_fire():
|
||||
"""재료 결측(목표가·제시가·앵커) — 어떤 변수도 미발동."""
|
||||
assert compute_offer(CardSpec(offer_variable="target_price"), {"input_price": 11000}) is None # 목표가 없음
|
||||
assert compute_offer(CardSpec(offer_variable="anchoring_price"),
|
||||
{"input_price": 11000, "target_price": 10000}) is None # 앵커 없음
|
||||
assert compute_offer(HOLD, {"input_price": 11000, "target_price": 10000}) is None # 설득 카드
|
||||
assert compute_offer(CardSpec(offer_variable="없는변수"), {"input_price": 11000, "target_price": 10000}) is None
|
||||
|
||||
|
||||
def test_available_min_round_and_closing_phase():
|
||||
spec2 = CardSpec(offer_variable="target_price", min_round=2)
|
||||
assert available(spec2, {"round": 1}) is False # min_round 미만
|
||||
assert available(spec2, {"round": 2}) is True
|
||||
closing = CardSpec(offer_variable="middle_price", closing=True)
|
||||
assert available(closing, {"round": 1}) is False # 종결 전용 — 중반 미발동(예약)
|
||||
assert available(closing, {"round": 1}, closing_phase=True) is True
|
||||
assert available(spec2, {"round": 3}, closing_phase=True) is False # 종결 국면엔 종결 카드만
|
||||
|
||||
|
||||
def test_tactic_offer_variable_overrides_parse():
|
||||
"""검증: tactic.offer_variable 명시 지정(negodata 셀렉트) — 파싱(마지막 변수) 대신 지정 변수 사용.
|
||||
기대결과: 멘트 마지막이 target_price 여도 지정한 anchoring_price 가 제안가 변수가 된다."""
|
||||
script = "적정가는 {anchoring_price}원이었으나 {target_price}원으로 제안 드립니다."
|
||||
assert build_card_spec(script).offer_variable == "target_price" # 자동: 마지막 변수
|
||||
spec = build_card_spec(script, {"offer_variable": "anchoring_price"})
|
||||
assert spec.offer_variable == "anchoring_price" # 명시 지정이 우선
|
||||
|
||||
|
||||
def test_available_requires_context_value():
|
||||
"""검증: 시장가 인용 카드(NGC-008류)의 requires 게이트 — build_card_spec 이 스크립트에서 잡아내고,
|
||||
기대결과: 컨텍스트에 인터넷 최저가가 없으면(0/결측) 미발동, 있으면 발동(퍼즈 #3·13·23·40 회귀)."""
|
||||
spec = build_card_spec("유사 거래는 {internet_lowest_price}원 안팎에서 합의되고 있습니다.")
|
||||
assert spec.requires == ("internet_lowest_price",)
|
||||
assert available(spec, {"round": 1}) is False # 결측
|
||||
assert available(spec, {"round": 1, "internet_lowest_price": 0}) is False # 미수집(0)
|
||||
assert available(spec, {"round": 1, "internet_lowest_price": 6300}) is True
|
||||
# 일반 카드는 requires 없음 — 기존 동작 그대로.
|
||||
assert build_card_spec("귀사와의 협력을 소중히 생각합니다.").requires == ()
|
||||
|
||||
|
||||
def test_offer_monotonic_no_regression():
|
||||
"""검증: 역행 금지(IMK 논의 — 절충 16,980 후 예산 상한 16,810 제시) 재현.
|
||||
기대결과: 직전 당사 제안보다 낮은 제안가 카드는 미발동(설득 폴백으로도 안 나감).
|
||||
직전 제안이 없으면 앵커 제시 허용, 같은 금액 재제시 허용, 더 높은 제안은 정상."""
|
||||
anchor_card = CardSpec(offer_variable="anchoring_price")
|
||||
ctx = {"round": 2, "target_price": 17_300, "anchor_price": 16_810, "input_price": 17_500}
|
||||
assert compute_offer(anchor_card, ctx) == 16_810 # 첫 카운터 전(포지션=앵커): 같은 금액 → 허용
|
||||
ctx["prev_customer_price"] = 16_980 # 절충 카드가 이미 16,980 을 부른 상태
|
||||
assert compute_offer(anchor_card, ctx) is None # 앵커 16,810 은 역행 → 미발동
|
||||
assert playable(anchor_card, ctx) is False # 멘트에 금액이 박히므로 설득 폴백도 금지
|
||||
assert compute_offer(CardSpec(offer_variable="target_price"), ctx) == 17_300 # 상향 제안은 정상
|
||||
|
||||
|
||||
def test_played_history_is_shared_by_number():
|
||||
ctx = {}
|
||||
assert is_played(ctx, "WC-05") is False
|
||||
mark_played(ctx, "WC-05")
|
||||
assert is_played(ctx, "WC-05") is True
|
||||
mark_played(ctx, "WC-05") # 재기록해도 1건 유지
|
||||
assert ctx["played_card_numbers"] == ["WC-05"]
|
||||
mark_played(ctx, None) # no-op(폴백 최후통첩)
|
||||
assert ctx["played_card_numbers"] == ["WC-05"]
|
||||
|
||||
|
||||
def test_spec_from_context_reads_snapshot_and_falls_back_to_hold():
|
||||
ctx = {"card_specs": dict(_SPECS)}
|
||||
assert spec_from_context(ctx, "WC-05") == CardSpec(offer_variable="middle_price", min_round=1, closing=True)
|
||||
assert spec_from_context(ctx, "NGC-B003") == HOLD # 미등록 카드(데모) 폴백
|
||||
assert spec_from_context({}, "WC-05") == HOLD # 스펙 미적재(구세션·데모) 폴백
|
||||
|
||||
|
||||
# ---- ③ 카운터 수락/거절 메커니즘 (엔진) ---------------------------------------
|
||||
def test_accept_counter_settles_at_counter_price():
|
||||
eng = _engine()
|
||||
s = _session(step="가격협상_카운터", pending_counter_price=10000)
|
||||
view = eng.advance(s, "수락")
|
||||
assert view.step == "협상완료"
|
||||
assert s.context["input_price"] == 10000 # 합의가 = 카운터가
|
||||
assert "pending_counter_price" not in s.context
|
||||
|
||||
|
||||
def test_reject_counter_reenters_price_and_discards_pending():
|
||||
eng = _engine()
|
||||
s = _session(step="가격협상_카운터", pending_counter_price=10000)
|
||||
view = eng.advance(s, "다른 가격 제시")
|
||||
assert view.step == "가격협상_재입력"
|
||||
# 새 가격 입력이 pending 을 폐기한다 — 이후 우선협상 타결이 옛 카운터로 오염되지 않음
|
||||
view = eng.advance(s, "9900")
|
||||
assert "pending_counter_price" not in s.context
|
||||
assert s.context["input_price"] == 9900
|
||||
|
||||
|
||||
def test_wildcard_1pct_decline_keeps_original_price():
|
||||
"""1% 인하 거절('아니오')도 협상완료로 가지만 합의가는 원 제시가 — pending 미적용 회귀."""
|
||||
eng = _engine()
|
||||
s = _session(step="wild_card_1pct", input_price=10000,
|
||||
offer_1pct=9900, pending_counter_price=9900)
|
||||
view = eng.advance(s, "아니오")
|
||||
assert view.step == "협상완료"
|
||||
assert s.context["input_price"] == 10000 # 거절 → 카운터 미적용
|
||||
|
||||
|
||||
# ---- ④ 목표가 초과 타결 금지 가드 --------------------------------------------
|
||||
def test_success_step_guard_rejects_over_target():
|
||||
eng = _engine()
|
||||
s = _session(input_price=10800, target_price=10000)
|
||||
view = eng.render_step(s, "협상완료")
|
||||
assert view.step == "협상실패" # 초과가 성공 진입 → 결렬 강제
|
||||
|
||||
|
||||
# ---- ⑤ 와일드 진입 — 종결 예약 + 중복 차단 (IMK BB9A 회귀) ---------------------
|
||||
def test_selected_wildcard_fires_in_entry_zone_and_records_position():
|
||||
eng = _engine()
|
||||
# 10300: 1pct 존(≤10200) 밖, entry 존(≤10500) 안 + 비종결 WC-02 선택
|
||||
s = _session(input_price=10300, allow_selected_wildcards=True,
|
||||
selected_wild_card_numbers=["WC-02"])
|
||||
view = eng.advance(s, "예")
|
||||
assert view.step == "wild_card_dynamic"
|
||||
# 제안가 = (anchor 10000 + target 10100)/2 = 10050 ≤ target — 그대로 제시(클램프 없음)
|
||||
assert s.context["pending_counter_price"] == 10050
|
||||
assert s.context["prev_customer_price"] == 10050 # 갑 포지션 기록 — "당사 제안" 멘트 정합(BB9A ③)
|
||||
assert s.context["active_wild_card_number"] == "WC-02"
|
||||
assert is_played(s.context, "WC-02") # 카드 이력 기록
|
||||
# 수락 → 그 가격으로 타결
|
||||
view = eng.advance(s, "수락")
|
||||
assert view.step == "협상완료" and s.context["input_price"] == 10050
|
||||
|
||||
|
||||
def test_closing_card_is_reserved_never_fires_mid_negotiation():
|
||||
"""종결 전용 카드(WC-05)는 entry 존이라도 중반에 안 나간다 — 종결 국면의 마지막 한 방으로 예약.
|
||||
(BB9A 중복의 절반: 중반에 당겨 쓴 카드를 종결에서 또 쓰던 경로 차단.)"""
|
||||
eng = _engine()
|
||||
s = _session(input_price=10300, allow_selected_wildcards=True,
|
||||
selected_wild_card_numbers=["WC-05"])
|
||||
view = eng.advance(s, "예")
|
||||
assert view.step == "가격협상" # 종결 카드뿐 → 일반 카드 플레이로
|
||||
assert "active_wild_card_number" not in s.context
|
||||
assert not is_played(s.context, "WC-05") # 안 나갔으니 이력도 없음
|
||||
# 종결 국면에선 발동 가능 + 이력 없음 — 서비스 종결 루프가 이 카드를 쓴다
|
||||
spec = spec_from_context(s.context, "WC-05")
|
||||
assert available(spec, s.context, closing_phase=True) is True
|
||||
|
||||
|
||||
def test_played_wildcard_is_skipped_on_reentry():
|
||||
"""이미 쓴 카드는 같은 협상에서 다시 안 나간다 — 다음 후보로 넘어간다."""
|
||||
eng = _engine()
|
||||
s = _session(input_price=10300, allow_selected_wildcards=True, wildcard_used=False,
|
||||
selected_wild_card_numbers=["WC-02"], played_card_numbers=["WC-02"])
|
||||
view = eng.advance(s, "예")
|
||||
assert view.step == "가격협상" # 유일 후보가 사용됨 → 발동 없음
|
||||
|
||||
|
||||
def test_unselected_wildcard_zone_still_falls_to_nego():
|
||||
"""와일드카드 미선택이면 entry 존이라도 일반 가격협상 — 기존 동작 보존."""
|
||||
eng = _engine()
|
||||
s = _session(input_price=10300, allow_selected_wildcards=True, selected_wild_card_numbers=[])
|
||||
view = eng.advance(s, "예")
|
||||
assert view.step == "가격협상"
|
||||
|
||||
|
||||
# ---- 인하율 표기 (회귀: 인상 제시가 "-1.3% 인하"로 표기되던 버그) -----------------
|
||||
def test_discount_never_negative_and_phrase_matches_direction():
|
||||
eng = _engine()
|
||||
# 인상 제시(기존 공급가 78000 < 제시 79000): 음수 인하율 금지 + "높은 금액" 문구
|
||||
s = _session(item_price=78000, input_price=79000)
|
||||
v = eng.vars_for(s)
|
||||
assert v["discount_rate"] == "0.0" # 마이너스 인하 표기 금지
|
||||
assert "높은 금액" in v["discount_phrase"] and "78000원" in v["discount_phrase"]
|
||||
assert "-" not in v["discount_phrase"]
|
||||
# 인하 제시: 상품단가(item_price) 기준 인하율
|
||||
v = eng.vars_for(_session(item_price=78000, input_price=77000))
|
||||
assert v["discount_rate"] == "1.3"
|
||||
assert "인하된 금액" in v["discount_phrase"]
|
||||
# 동일가
|
||||
v = eng.vars_for(_session(item_price=78000, input_price=78000))
|
||||
assert "동일한 수준" in v["discount_phrase"]
|
||||
# 기존가 미보유(신규 협상) → 문구 생략
|
||||
v = eng.vars_for(_session(item_price=0, input_price=79000))
|
||||
assert v["discount_phrase"] == "" and v["discount_rate"] == "0.0"
|
||||
|
||||
|
||||
def test_price_confirm_script_renders_raise_correctly():
|
||||
"""가격협상_확인 멘트 E2E — 인상 제시에 '인하' 표현이 나오지 않는다."""
|
||||
eng = _engine()
|
||||
s = _session(step="기존가격제시", item_price=78000, input_price=None, round=0)
|
||||
s.context.pop("input_price")
|
||||
view = eng.advance(s, "79000")
|
||||
assert view.step == "가격협상_확인"
|
||||
assert "인하" not in view.script # 인상인데 '인하' 금지
|
||||
assert "높은 금액" in view.script and "79000원" in view.script
|
||||
|
||||
|
||||
# ---- vars_for 전술 변수 치환 ---------------------------------------------------
|
||||
def test_vars_for_supplies_tactic_variables():
|
||||
eng = _engine()
|
||||
# 카운터 미제시(정보성): 절충/중간 변수는 원 계산값.
|
||||
s0 = _session(input_price=10300, prev_customer_price=10000) # anchor=10000, target=10100 (기본)
|
||||
v0 = eng.vars_for(s0)
|
||||
assert v0["prev_partner_price"] == 10300
|
||||
assert v0["prev_customer_price"] == 10000
|
||||
assert v0["target_mid_price"] == 10050 # (anchor 10000 + target 10100)/2
|
||||
assert v0["middle_price"] == 10150 # (prev_customer 10000 + input 10300)/2
|
||||
|
||||
# 카운터 제시 중: 표시 제시가(middle/target_mid/counter) == 타결가(pending) 로 고정.
|
||||
# 회귀(표시가≠투찰가): 예전엔 middle_price 가 재계산값 10150 을 표시하면서 10100 으로 타결됐다.
|
||||
s1 = _session(input_price=10300, prev_customer_price=10000, pending_counter_price=10100)
|
||||
v1 = eng.vars_for(s1)
|
||||
assert v1["counter_price"] == 10100
|
||||
assert v1["middle_price"] == 10100 # 재계산 10150 이 아니라 pending
|
||||
assert v1["target_mid_price"] == 10100
|
||||
|
||||
|
||||
# ---- ⑥⑦ E2E (실 DB — 견적 선택 카드 + 서비스 레이어) ---------------------------
|
||||
from sqlalchemy import column, delete, insert, select, table # noqa: E402
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
|
||||
from common.enums import DBType, DBWRType, ErrorType # noqa: E402
|
||||
from router.v1.chat.protocol import Req_Chat # noqa: E402
|
||||
from services.chat_service import ChatService, reset_sessions # noqa: E402
|
||||
from tenancy.registry import TenantEngineRegistry # noqa: E402
|
||||
|
||||
_T_SESSIONS = table(
|
||||
"sessions",
|
||||
column("session_id"), column("quotation_id"), column("item_id"), column("supplier_id"),
|
||||
column("qt_number"), column("qt_round"), column("qt_type"), column("target_price"),
|
||||
column("anchoring_price"), column("status"), column("end_time"),
|
||||
schema="negotiation",
|
||||
)
|
||||
_T_QUOTATIONS = table(
|
||||
"quotations",
|
||||
column("qt_id"), column("user_id"), column("qt_setting_id"), column("version_id"),
|
||||
column("name"), column("number"), column("type"), column("status"),
|
||||
column("start_time"), column("end_time"),
|
||||
schema="quotation",
|
||||
)
|
||||
_T_VNC = table("version_nego_cards", column("vnc_id"), column("version_id"), column("nego_card_id"), schema="card")
|
||||
_T_NEGO = table("nego_cards", column("nego_card_id"), column("number"), column("deleted"), schema="card")
|
||||
_T_VWC = table("version_wild_cards", column("vwc_id"), column("version_id"), column("wild_card_id"), schema="card")
|
||||
_T_WILD = table("wild_cards", column("wild_card_id"), column("number"), column("deleted"), schema="card")
|
||||
|
||||
|
||||
async def _card_uuid(number: str, *, wild=False):
|
||||
tbl, pk = (_T_WILD, _T_WILD.c.wild_card_id) if wild else (_T_NEGO, _T_NEGO.c.nego_card_id)
|
||||
|
||||
def _q(s):
|
||||
return DB_SESSION_MNG.execute(
|
||||
s, select(pk).where(tbl.c.number == number, tbl.c.deleted == False).limit(1)) # noqa: E712
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return rows[0] if rows else None
|
||||
|
||||
|
||||
async def _seed_quote_session(sid, selected_numbers, wild_numbers=(), target=10000, anchor=9900):
|
||||
qid, ver_id, iid, sup = _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4()
|
||||
now = datetime.now(timezone.utc)
|
||||
card_ids, wild_ids = {}, {}
|
||||
for n in selected_numbers:
|
||||
card_ids[n] = await _card_uuid(n)
|
||||
assert card_ids[n] is not None, f"카탈로그에 {n} 없음(시드 확인)"
|
||||
for n in wild_numbers:
|
||||
wild_ids[n] = await _card_uuid(n, wild=True)
|
||||
assert wild_ids[n] is not None, f"카탈로그에 {n} 없음(시드 확인)"
|
||||
|
||||
def _seed(s_):
|
||||
async def run(s):
|
||||
e = await DB_SESSION_MNG.add(s, insert(_T_QUOTATIONS).values(
|
||||
qt_id=qid, user_id=_uuid.uuid4(), qt_setting_id=_uuid.uuid4(), version_id=ver_id,
|
||||
name="전술E2E", number=f"QT-TACTIC-{str(sid)[:8]}", type=1, status=2,
|
||||
start_time=now, end_time=now + timedelta(days=1)))
|
||||
if e != ErrorType.SUCCESS:
|
||||
return e
|
||||
for n in selected_numbers:
|
||||
e = await DB_SESSION_MNG.add(s, insert(_T_VNC).values(
|
||||
vnc_id=_uuid.uuid4(), version_id=ver_id, nego_card_id=card_ids[n]))
|
||||
if e != ErrorType.SUCCESS:
|
||||
return e
|
||||
for n in wild_numbers:
|
||||
e = await DB_SESSION_MNG.add(s, insert(_T_VWC).values(
|
||||
vwc_id=_uuid.uuid4(), version_id=ver_id, wild_card_id=wild_ids[n]))
|
||||
if e != ErrorType.SUCCESS:
|
||||
return e
|
||||
return await DB_SESSION_MNG.add(s, insert(_T_SESSIONS).values(
|
||||
session_id=sid, quotation_id=qid, item_id=iid, supplier_id=sup,
|
||||
qt_number=f"QT-TACTIC-{str(sid)[:8]}", qt_round=1, qt_type=1,
|
||||
target_price=target, anchoring_price=anchor, status=2,
|
||||
end_time=now + timedelta(days=1)))
|
||||
return run(s_)
|
||||
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_seed])
|
||||
assert err == ErrorType.SUCCESS
|
||||
return qid, ver_id
|
||||
|
||||
|
||||
async def _cleanup(sid, qid, ver_id):
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[DBType.MAIN.value],
|
||||
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SESSIONS).where(_T_SESSIONS.c.session_id == sid)),
|
||||
lambda s: DB_SESSION_MNG.add(s, delete(_T_VNC).where(_T_VNC.c.version_id == ver_id)),
|
||||
lambda s: DB_SESSION_MNG.add(s, delete(_T_VWC).where(_T_VWC.c.version_id == ver_id)),
|
||||
lambda s: DB_SESSION_MNG.add(s, delete(_T_QUOTATIONS).where(_T_QUOTATIONS.c.qt_id == qid))],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_e2e_counter_accept_settles_at_target(db_engine):
|
||||
"""견적 선택 카드 NGC-010(향후 거래 연계 — 스크립트 {target_price} 파싱 → 목표가 제안)의
|
||||
카운터를 수락하면 합의가 = 목표가(10000) — '수락 즉시 타결' 기획 결정의 E2E 검증."""
|
||||
reset_sessions()
|
||||
sid = _uuid.uuid4()
|
||||
qid, ver_id = await _seed_quote_session(sid, ["NGC-010"])
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(_uuid.uuid4()))
|
||||
svc = ChatService()
|
||||
session_id = str(sid)
|
||||
r = None
|
||||
for ui in [None, "확인", "예", "확인", "11000", "예"]:
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input=ui))
|
||||
# 가격협상 카드 턴 → NGC-010 카운터(target) 제시 스텝
|
||||
assert r.step == "가격협상_카운터", f"카운터 스텝 기대, 실제 {r.step}"
|
||||
assert r.card_id == "NGC-010"
|
||||
assert r.input_options == ["수락", "다른 가격 제시"]
|
||||
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="수락"))
|
||||
assert r.step == "협상완료"
|
||||
assert r.settled_price == 10000 # 합의가 = 목표가 (고객사 이득)
|
||||
finally:
|
||||
await _cleanup(sid, qid, ver_id)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_e2e_over_target_ends_in_failure_after_closing(db_engine):
|
||||
"""협력사가 목표가 초과(11000)를 고수하면: 카드 소진 → 종결 전술(목표가 최후통첩) →
|
||||
그래도 거절 → 결렬(협상실패). 목표가 초과로는 절대 타결되지 않는다."""
|
||||
reset_sessions()
|
||||
sid = _uuid.uuid4()
|
||||
qid, ver_id = await _seed_quote_session(sid, ["NGC-003"]) # 설득 카드 1장 → 빠른 소진
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(_uuid.uuid4()))
|
||||
svc = ChatService()
|
||||
session_id = str(sid)
|
||||
steps, r = [], None
|
||||
# 고수 시나리오: 가격은 항상 11000, 카운터는 전부 거절
|
||||
for ui in [None, "확인", "예", "확인", "11000", "예", "11000", "예"]:
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input=ui))
|
||||
steps.append(r.step)
|
||||
# 카드(NGC-003) 소진 → 종결 국면: 목표가 최후통첩 카운터 스텝
|
||||
assert r.step == "가격협상_카운터", f"종결 카운터 기대, 실제 {steps}"
|
||||
assert "10000" in r.script # 최후통첩 = 목표가 제시
|
||||
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="다른 가격 제시"))
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="11000"))
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="예"))
|
||||
assert r.step == "협상실패" # target 초과 고수 → 결렬
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="확인"))
|
||||
assert r.chat_end and r.outcome == "failure" # backend REJECTED → 개찰 이관
|
||||
assert r.settled_price is None # 초과가 타결 없음
|
||||
finally:
|
||||
await _cleanup(sid, qid, ver_id)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_e2e_bb9a_no_duplicate_wildcard_and_real_middle(db_engine):
|
||||
"""IMK BB9A 재현 E2E — 와일드카드 2장(WC-02·WC-05) + 설득 카드 1장.
|
||||
|
||||
기대 흐름(수정 후):
|
||||
· 중반 와일드 진입 = 비종결 WC-02 (종결 전용 WC-05 는 예약 — 구현 전엔 WC-05 가 먼저 나갔다)
|
||||
· 종결 국면 = WC-05, 절충가 = (당사 직전 제안 + 협력사 제시가)/2 실계산 (구현 전엔 목표가로 클램프)
|
||||
· 같은 카드 2회 발동 없음 + 종결 발동도 card_id 기록
|
||||
"""
|
||||
reset_sessions()
|
||||
sid = _uuid.uuid4()
|
||||
qid, ver_id = await _seed_quote_session(sid, ["NGC-003"], wild_numbers=["WC-02", "WC-05"])
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(_uuid.uuid4()))
|
||||
svc = ChatService()
|
||||
session_id = str(sid)
|
||||
r = None
|
||||
# 10300: 1pct 존(≤ 9900×1.02=10098) 밖, entry 존(≤ 10395) 안 → 선택형 와일드 발동 구간
|
||||
for ui in [None, "확인", "예", "확인", "10300", "예"]:
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input=ui))
|
||||
assert r.step == "wild_card_dynamic"
|
||||
assert r.card_id == "WC-02" # 종결 전용 WC-05 가 아니라 비종결 카드
|
||||
# WC-02 제안가 = (anchor 9900 + target 10000)/2 = 9950
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="다른 가격 제시"))
|
||||
# 10010 재제시 → 설득 카드(NGC-003) 1장 소진
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="10010"))
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="예"))
|
||||
assert r.step == "가격협상" and r.card_id == "NGC-003"
|
||||
# 10005 재제시 → 카드 소진 → 종결 국면: WC-05 절충가 = (9950 + 10005)/2 = 9980 (≤ target)
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="10005"))
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="예"))
|
||||
assert r.step == "가격협상_카운터"
|
||||
assert r.card_id == "WC-05" # 종결 발동도 카드 기록(구현 전 null)
|
||||
assert "9980" in r.script # 실제 절충가 — 목표가(10000) 클램프 아님
|
||||
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="수락"))
|
||||
assert r.step == "협상완료"
|
||||
assert r.settled_price == 9980 # 표시가 = 타결가
|
||||
finally:
|
||||
await _cleanup(sid, qid, ver_id)
|
||||
@ -34,7 +34,7 @@ _T_QUOTATIONS = table(
|
||||
"quotations",
|
||||
column("qt_id"), column("user_id"), column("qt_setting_id"), column("version_id"),
|
||||
column("name"), column("number"), column("type"), column("status"),
|
||||
column("start_time"), column("end_time"),
|
||||
column("start_time"), column("end_time"), column("supplier_type"),
|
||||
schema="quotation",
|
||||
)
|
||||
_T_ITEMS = table(
|
||||
@ -80,6 +80,7 @@ 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(),
|
||||
name="로더 테스트", number="QT-LOADER-TEST", type=3, status=2,
|
||||
start_time=now, end_time=now + timedelta(days=1),
|
||||
supplier_type=2, # manufacture(제조) → 유통 코드 "A"
|
||||
))
|
||||
|
||||
def _ins_sess(s, session_id, supplier_id):
|
||||
@ -109,7 +110,7 @@ async def test_context_loaded_from_db(db_engine):
|
||||
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine("imarketkorea")
|
||||
eng = await reg.get_engine("ktcommerce")
|
||||
r = await ChatService().chat(eng, Req_Chat(session_id=str(sid)))
|
||||
assert r.session_id == str(sid) and r.step == "서비스안내"
|
||||
|
||||
@ -124,7 +125,7 @@ async def test_context_loaded_from_db(db_engine):
|
||||
assert c["distribution_code"] == "B" # supplier_items.supply_type=3(총판) → B (매핑 우선)
|
||||
assert c["partner_count"] == 2 # 매핑 기준 취급 협력사 2곳 → MULTIPLE
|
||||
|
||||
# 매핑 삭제 후 새 세션(sid2) → 유통코드는 ChatService 기본값, 파트너는 세션 이력 폴백
|
||||
# 매핑 삭제 후 새 세션(sid2) → 폴백 경로: 유통코드=quotations.supplier_type, 파트너=세션 이력
|
||||
err = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[DBType.MAIN.value],
|
||||
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SUPPLIER_ITEMS).where(_T_SUPPLIER_ITEMS.c.item_id == iid))],
|
||||
@ -132,7 +133,7 @@ async def test_context_loaded_from_db(db_engine):
|
||||
assert err == ErrorType.SUCCESS
|
||||
await ChatService().chat(eng, Req_Chat(session_id=str(sid2)))
|
||||
c2 = (await ChatSessionRepository(eng.company_id).get(str(sid2))).context
|
||||
assert c2["distribution_code"] == "A" # 매핑 없음 → ChatService 기본값
|
||||
assert c2["distribution_code"] == "A" # 폴백: quotations.supplier_type=2(제조) → A
|
||||
assert c2["partner_count"] == 2 # 폴백: 세션 이력 distinct supplier 2곳
|
||||
finally:
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
@ -164,7 +165,7 @@ async def test_null_anchoring_falls_back_to_target(db_engine):
|
||||
assert err == ErrorType.SUCCESS
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine("imarketkorea")
|
||||
eng = await reg.get_engine("ktcommerce")
|
||||
await ChatService().chat(eng, Req_Chat(session_id=str(sid)))
|
||||
saved = await ChatSessionRepository(eng.company_id).get(str(sid))
|
||||
assert saved is not None
|
||||
@ -186,31 +187,19 @@ async def test_loader_with_crud_double(db_engine):
|
||||
|
||||
class _FakeCRUD(INegoContextCRUD):
|
||||
async def get_session_row(self, cdb, session_id):
|
||||
# (qt_type, target, anchoring_price, done_ceiling_price, item_id, quotation_id, supplier_id)
|
||||
# — 재견적(2)·앵커 미박제·타결상한 52,500(목표가 +5%)
|
||||
return ErrorType.SUCCESS, (2, 50000, None, 52500, uuid.uuid4(), uuid.uuid4(), uuid.uuid4())
|
||||
# (qt_type, target, anchoring_price, item_id, quotation_id, supplier_id) — 재견적(2)·앵커 미박제
|
||||
return ErrorType.SUCCESS, (2, 50000, None, uuid.uuid4(), uuid.uuid4(), uuid.uuid4())
|
||||
|
||||
async def get_item_baseline(self, cdb, item_id):
|
||||
# 기준가를 매입가로 고른 회사 + 거래상대 호칭을 '공급업체'로 바꾼 용어 사전.
|
||||
# 호칭은 crud 가 어떤 회사든 '공급가'(공급사 화면 고정 용어)로 내려준다.
|
||||
return ErrorType.SUCCESS, (7000, "공급가", {"supplier": "공급업체"})
|
||||
|
||||
async def get_item_lowest_price(self, cdb, item_id):
|
||||
return ErrorType.SUCCESS, 6300 # 인터넷 최저가(items.internet_lowest_price)
|
||||
|
||||
async def get_card_count(self, cdb, session_id):
|
||||
return ErrorType.SUCCESS, 3 # 협상카드 사용 횟수 상한(quotation_settings.card_count)
|
||||
async def get_item_price(self, cdb, item_id):
|
||||
return ErrorType.SUCCESS, 7000
|
||||
|
||||
async def get_supplier_total_revenue(self, cdb, supplier_id):
|
||||
return ErrorType.SUCCESS, 12_000_000.0
|
||||
|
||||
async def get_item_name(self, cdb, item_id):
|
||||
return ErrorType.SUCCESS, "테스트상품"
|
||||
|
||||
async def get_supplier_name(self, cdb, supplier_id):
|
||||
return ErrorType.SUCCESS, "테스트협력사"
|
||||
|
||||
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"
|
||||
|
||||
async def count_item_suppliers(self, cdb, item_id):
|
||||
@ -219,40 +208,15 @@ async def test_loader_with_crud_double(db_engine):
|
||||
async def count_item_session_suppliers(self, cdb, item_id):
|
||||
return ErrorType.SUCCESS, 0 # 이력도 없음 → NONE
|
||||
|
||||
async def get_quotation_card_numbers(self, cdb, quotation_id):
|
||||
# 행 = (number, script, tactic) — 스크립트 파싱 + tactic JSONB 로 card_specs 를 만든다
|
||||
return ErrorType.SUCCESS, (
|
||||
[("NGC-003", "설득 멘트(가격 변수 없음)", None),
|
||||
("NGC-008", "시장가 {internet_lowest_price}원 인용(읽기 전용 변수)", None)],
|
||||
[("WC-02", "이에 당사는 {target_mid_price}원을 역으로 제안 드립니다.", None)],
|
||||
)
|
||||
|
||||
ctx = await NegotiationContextLoader(crud=_FakeCRUD()).load(str(uuid.uuid4()))
|
||||
assert ctx is not None
|
||||
assert ctx.rq_type == "재견적" # qt_type=2(1:N)
|
||||
assert ctx.target_price == 50000
|
||||
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
|
||||
assert ctx.done_ceiling_price == 52500 # 타결 상한가 박제값(목표가 +5%)
|
||||
assert ctx.item_price == 7000
|
||||
assert ctx.item_price_label == "공급가" # 기준가 호칭이 멘트까지 전달되는지
|
||||
assert ctx.labels == {"supplier": "공급업체"} # 회사 용어 사전이 스크립트 토큰용으로 실리는지
|
||||
assert ctx.internet_lowest_price == 6300 # 인터넷 최저가 로드 확인
|
||||
assert ctx.card_count == 3 # 협상카드 사용 횟수 상한 로드 확인
|
||||
assert ctx.partner_name == "테스트협력사"
|
||||
assert ctx.product_name == "테스트상품"
|
||||
assert ctx.revenue_amount == 12_000_000.0
|
||||
assert ctx.distribution_code == "B" # supply_type=3(총판) → B
|
||||
assert ctx.distribution_code == "B" # supplier_type=3(총판) → B
|
||||
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"]
|
||||
# 카드 전술 확정 — 설득 카드/읽기 전용 변수는 제안가 없음, WC-02 는 스크립트 파싱으로 중간가.
|
||||
assert ctx.card_specs["NGC-003"]["offer_variable"] is None
|
||||
assert ctx.card_specs["NGC-008"]["offer_variable"] is None # 인터넷 최저가는 읽어주기 변수 — 제안가 아님
|
||||
# 시장가 인용 카드는 최저가 결측 세션에서 미발동하도록 requires 로 표시된다(토큰 노출 방지).
|
||||
assert ctx.card_specs["NGC-008"]["requires"] == ["internet_lowest_price"]
|
||||
assert ctx.card_specs["WC-02"] == {
|
||||
"offer_variable": "target_mid_price", "min_round": 1, "closing": False, "requires": [],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@ -260,7 +224,7 @@ async def test_context_falls_back_without_db_row(db_engine):
|
||||
"""DB 에 세션 행이 없으면(데모/직접 호출) 기본 컨텍스트로 폴백한다."""
|
||||
reset_sessions()
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine("imarketkorea")
|
||||
eng = await reg.get_engine("ktcommerce")
|
||||
r = await ChatService().chat(eng, Req_Chat())
|
||||
saved = await ChatSessionRepository(eng.company_id).get(r.session_id)
|
||||
assert saved is not None
|
||||
|
||||
@ -1,145 +0,0 @@
|
||||
"""Phase 1 결정 스택 잔여분 검증 — 규칙 데이터화 + 선택카드 우선순위 prior.
|
||||
|
||||
1. 와일드카드 진입 임계(wildcard_1pct_ratio/entry_ratio)·카운터 라운드 상한(max_counter_rounds)이
|
||||
하드코딩이 아니라 테넌트 config(negotiation.*)로 주입된다.
|
||||
2. 의도층 prior: 갑이 견적에서 고른 카드 순서가 콜드 스타트 선택을 결정하고,
|
||||
학습(Q·방문수)이 쌓이면 영향이 소멸한다 — Q-table 오염 없음.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession
|
||||
from negotiation.chat.service.script_repository import ScriptRepository
|
||||
from negotiation.policies.base import EpisodeState, PolicyContext
|
||||
from negotiation.policies.qtable_policy import UCBQTablePolicy
|
||||
from negotiation.qtable.domain.model.q_table import QTable
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
|
||||
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||
|
||||
|
||||
def _engine(**rule_overrides) -> ChatEngine:
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||
for k, v in rule_overrides.items():
|
||||
setattr(cfg.negotiation, k, v)
|
||||
return ChatEngine(ScriptRepository(cfg, _TENANTS_DIR), rq_type="재협상")
|
||||
|
||||
|
||||
def _session(price, anchor=10000, rnd=1, **ctx_over):
|
||||
ctx = {"input_price": price, "anchor_price": anchor, "target_price": anchor + 100,
|
||||
"round": rnd, "allow_selected_wildcards": False}
|
||||
ctx.update(ctx_over)
|
||||
return ChatSession(session_id="00000000-0000-0000-0000-00000000d001", tenant_id="imarketkorea",
|
||||
company_id="imarketkorea", step="가격협상_확인", action_space_size=0, context=ctx)
|
||||
|
||||
|
||||
# ---- 규칙 데이터화 -----------------------------------------------------------
|
||||
def test_default_rules_loaded_from_config():
|
||||
eng = _engine()
|
||||
assert eng.rules.wildcard_1pct_ratio == 1.02
|
||||
assert eng.rules.wildcard_entry_ratio == 1.05
|
||||
assert eng.rules.max_counter_rounds == 3
|
||||
|
||||
|
||||
def test_wildcard_threshold_is_config_driven():
|
||||
# 기본(1.02): anchor 10000, 제시 10800 → 임계 밖 → 일반 가격협상
|
||||
view = _engine().advance(_session(10800), "예")
|
||||
assert view.step == "가격협상"
|
||||
# 임계를 1.10 으로 완화한 테넌트 → 같은 가격에서 1% 인하 와일드카드 발동.
|
||||
# 1%가(10800×0.99=10692)도 제안가 공통 유효조건(≤목표가)을 타므로 목표가를 그 위로 둔다 —
|
||||
# 기본 target(10100)이면 초과 제시 금지 규칙에 걸려 발동하지 않는 게 새 정답.
|
||||
view = _engine(wildcard_1pct_ratio=1.10).advance(_session(10800, target_price=11000), "예")
|
||||
assert view.step == "wild_card_1pct"
|
||||
# 목표가가 1%가 아래면(초과 제시 금지) 완화 임계라도 미발동 — 수락해도 결렬되는 모순 제안 차단.
|
||||
view = _engine(wildcard_1pct_ratio=1.10).advance(_session(10800), "예")
|
||||
assert view.step == "가격협상"
|
||||
|
||||
|
||||
def test_max_counter_rounds_is_config_driven():
|
||||
# round=3(카운터 2회 경과), 제시 11000: 기본 상한 3 → 아직 협상 지속
|
||||
view = _engine().advance(_session(11000, rnd=3), "예")
|
||||
assert view.step == "가격협상"
|
||||
# 상한 1 → 종결 국면 진입: 곧장 실패가 아니라 종결 전술 발동 지점(force_closing)으로
|
||||
s = _engine(max_counter_rounds=1), _session(11000, rnd=3)
|
||||
view = s[0].advance(s[1], "예")
|
||||
assert view.step == "가격협상" and s[1].context.get("force_closing") is True
|
||||
# 종결 전술까지 소진(closing_played) 후에도 target(10100) 초과 → 결렬
|
||||
view = _engine(max_counter_rounds=1).advance(_session(11000, rnd=3, closing_played=True), "예")
|
||||
assert view.step == "협상실패"
|
||||
# 종결 후 제시가가 target 이하로 내려오면 결렬이 아니라 타결 (새 규칙 — 구현 전엔 무조건 실패)
|
||||
view = _engine(max_counter_rounds=1).advance(
|
||||
_session(10050, rnd=3, closing_played=True, wildcard_used=True), "예")
|
||||
assert view.step == "협상완료"
|
||||
|
||||
|
||||
# ---- 선택카드 우선순위 prior ---------------------------------------------------
|
||||
def _snap():
|
||||
return NegotiationSnapshot(revenue_amount=1, distribution_code="A", partner_count=1,
|
||||
acceptance_ratio=0.1, input_price=900, anchor_price=800, target_price=1000)
|
||||
|
||||
|
||||
def _ctx(prior=None, mask=None, n=11):
|
||||
return PolicyContext(state_index=0, snapshot=_snap(), action_space_size=n,
|
||||
available_mask=mask, prior_bonus=prior, episode=EpisodeState())
|
||||
|
||||
|
||||
def test_prior_decides_cold_start_order():
|
||||
"""콜드 스타트(Q=0·방문 0)에서는 갑이 먼저 고른 카드(높은 prior)가 먼저 나간다."""
|
||||
qt = QTable(2, 11)
|
||||
prior = np.zeros(11)
|
||||
prior[7], prior[2] = 0.3, 0.15 # 선택 순서: action7 → action2
|
||||
mask = np.zeros(11, dtype=bool)
|
||||
mask[2] = mask[7] = True
|
||||
p = UCBQTablePolicy(qt, mark_visits=False)
|
||||
assert p.select(_ctx(prior=prior, mask=mask)).action_id == 7
|
||||
|
||||
|
||||
def test_prior_decays_as_learning_accumulates():
|
||||
"""학습이 쌓이면(Q·방문수) prior 는 1/(1+visits) 로 감쇠 — Q 가 지배한다."""
|
||||
qt = QTable(2, 11)
|
||||
qt.q[0, 2] = 1.0 # action2 가 학습상 우월
|
||||
qt.visits[0, 2] = 5
|
||||
qt.visits[0, 7] = 5 # 탐색 보너스 동률
|
||||
prior = np.zeros(11)
|
||||
prior[7] = 0.3 # 갑 선호는 action7
|
||||
mask = np.zeros(11, dtype=bool)
|
||||
mask[2] = mask[7] = True
|
||||
p = UCBQTablePolicy(qt, mark_visits=False)
|
||||
assert p.select(_ctx(prior=prior, mask=mask)).action_id == 2
|
||||
|
||||
|
||||
def test_no_prior_keeps_existing_behavior():
|
||||
"""prior 미주입(None) 시 기존 UCB 동작 그대로 — 회귀 없음."""
|
||||
qt = QTable(2, 4)
|
||||
qt.q[0] = np.array([1.0, 9.0, 2.0, 0.0])
|
||||
qt.visits[0] = np.array([5, 5, 5, 5])
|
||||
p = UCBQTablePolicy(qt, exploration_constant=0.1, mark_visits=False)
|
||||
assert p.select(_ctx(n=4)).action_id == 1
|
||||
|
||||
|
||||
def test_selection_prior_built_from_quotation_order():
|
||||
"""ChatService._selection_prior — 견적 선택 순서 → prior 배열 (앞선 선택일수록 큼)."""
|
||||
from services.chat_service import ChatService
|
||||
|
||||
class _Mapper:
|
||||
_m = {i: f"NGC-B{i + 1:03d}" for i in range(11)}
|
||||
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
|
||||
|
||||
session = ChatSession(session_id="00000000-0000-0000-0000-00000000d002", tenant_id="t", company_id="t",
|
||||
context={"selected_nego_card_numbers": ["NGC-B008", "NGC-B003"]})
|
||||
prior = ChatService._selection_prior(_Engine(), session)
|
||||
assert prior is not None
|
||||
assert prior[7] > prior[2] > 0 # 먼저 고른 NGC-B008(action7) 이 더 큼
|
||||
assert prior[[0, 1, 4, 10]].sum() == 0 # 미선택 카드는 0
|
||||
|
||||
# 선택이 1장이면 순서 정보가 없어 None
|
||||
session.context["selected_nego_card_numbers"] = ["NGC-B008"]
|
||||
assert ChatService._selection_prior(_Engine(), session) is None
|
||||
@ -110,7 +110,7 @@ async def test_version_and_cell_persistence(db_engine):
|
||||
@pytest.mark.asyncio
|
||||
async def test_service_step_learns_and_isolates(db_engine):
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine("imarketkorea")
|
||||
eng = await reg.get_engine("ktcommerce")
|
||||
svc = NegotiationService()
|
||||
|
||||
def req():
|
||||
@ -126,21 +126,20 @@ async def test_service_step_learns_and_isolates(db_engine):
|
||||
assert r1.learned is True and r1.policy == "qtable_ucb"
|
||||
assert r1.updated_q > 0.0 # 성공 보상으로 Q 상승
|
||||
|
||||
# DB 에서 state 전체 방문 누적 확인 (state index 는 imarketkorea config 로 동적 계산)
|
||||
# DB 에서 state 전체 방문 누적 확인 (state 58 = ktcommerce 의 이 snapshot)
|
||||
from negotiation.qtable.domain.service.state_calculator import state_index
|
||||
sidx = state_index(_snap(revenue_amount=20_000_000, acceptance_ratio=0.11, input_price=990, round_number=3), eng.config.state)
|
||||
repo_a = LearningRepository("imarketkorea")
|
||||
vid = await repo_a.get_or_create_active_version(state_space_size=162, action_space_size=9, learning_rate=0.1, discount_factor=0.95)
|
||||
_, vcells = await repo_a.load_cells(vid)
|
||||
repo_kt = LearningRepository("ktcommerce")
|
||||
vid = await repo_kt.get_or_create_active_version(state_space_size=162, action_space_size=9, learning_rate=0.1, discount_factor=0.95)
|
||||
_, vcells = await repo_kt.load_cells(vid)
|
||||
state_total = sum(c for s, a, c in vcells if s == sidx)
|
||||
assert state_total == 3 # 3회 호출 → state 누적 방문 3
|
||||
|
||||
# 테넌트 격리: 자동 온보딩 고객사(UUID)는 별도 학습/별도 state
|
||||
other = "00000000-0000-0000-0000-0000000000c1"
|
||||
eng2 = await reg.get_engine(other)
|
||||
# 테넌트 격리: imarketkorea 는 별도 학습/별도 state
|
||||
eng2 = await reg.get_engine("imarketkorea")
|
||||
ri = await svc.step(eng2, req())
|
||||
assert ri.visit_count == 1
|
||||
|
||||
err, ck = await repo_a.read(lambda s: repo_a.count_experience(s))
|
||||
err, ci = await LearningRepository(other).read(lambda s: LearningRepository(other).count_experience(s))
|
||||
err, ck = await repo_kt.read(lambda s: repo_kt.count_experience(s))
|
||||
err, ci = await LearningRepository("imarketkorea").read(lambda s: LearningRepository("imarketkorea").count_experience(s))
|
||||
assert ck == 3 and ci == 1 # experience 격리
|
||||
|
||||
@ -35,7 +35,7 @@ def test_card_effectiveness_has_good_cards():
|
||||
assert len(good) >= 3 # 효과 좋은 카드 존재 → 학습 대상 신호
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tenant", ["_base", "imarketkorea"])
|
||||
@pytest.mark.parametrize("tenant", ["ktcommerce", "imarketkorea"])
|
||||
def test_learning_beats_baseline(tenant):
|
||||
report = run("configs/exp_default.yaml", tenant)
|
||||
pols = report["policies"]
|
||||
@ -53,7 +53,7 @@ def test_learning_beats_baseline(tenant):
|
||||
|
||||
|
||||
def test_static_does_not_learn():
|
||||
report = run("configs/exp_default.yaml", "imarketkorea")
|
||||
report = run("configs/exp_default.yaml", "ktcommerce")
|
||||
static = report["policies"]["static"]
|
||||
# 정적 정책은 항상 고정 카드 → 좋은카드 적중 학습 없음(우연 일치만)
|
||||
assert static["good_card_hit_rate"] <= report["policies"]["qtable_ucb"]["good_card_hit_rate"]
|
||||
|
||||
@ -1,161 +0,0 @@
|
||||
"""Phase 3 이해층 검증 — InputInterpreter (자유 발화 NLU → 기대 입력 구조화).
|
||||
|
||||
원칙 검증: LLM 은 의도 분류·가격 표현 위치만 찾고, 숫자 계산은 결정론 파서가 한다.
|
||||
① 한국어 가격 파서 결정론 ② choice 는 선택지 목록 검증 ③ price_text 는 원문 부분문자열 검증
|
||||
④ 실패/타임아웃 → None(원문 폴백) ⑤ 챗 플로우: 자유 발화로 분기·가격 입력이 진행된다
|
||||
⑥ LLM 미설정 시 기존(정형 입력) 동작 그대로 — 회귀 없음.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from negotiation.chat.service.input_interpreter import (
|
||||
InputInterpreter, InterpretedInput, parse_korean_price,
|
||||
)
|
||||
|
||||
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||
|
||||
|
||||
# ---- 결정론 한국어 가격 파서 -------------------------------------------------
|
||||
@pytest.mark.parametrize("text,expected", [
|
||||
("10,500원", 10500),
|
||||
("10500", 10500),
|
||||
("1만 500원", 10500),
|
||||
("1만500원", 10500),
|
||||
("만원", 10000),
|
||||
("1.5만", 15000),
|
||||
("3만2천원", 32000),
|
||||
("2억", 200_000_000),
|
||||
("0", None), # 0 이하 무효
|
||||
("그건 어렵습니다", None), # 가격 아님
|
||||
("만원에 3개", None), # 잡문자 혼입 → 해석 불가(안전 폴백)
|
||||
])
|
||||
def test_parse_korean_price(text, expected):
|
||||
got = parse_korean_price(text)
|
||||
assert (got == expected) if expected is not None else (got is None)
|
||||
|
||||
|
||||
# ---- LLM 출력 검증 (환각 차단) ----------------------------------------------
|
||||
def _fake(reply: dict):
|
||||
def call(messages):
|
||||
return reply
|
||||
return call
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_choice_mapped_to_option():
|
||||
nat = InputInterpreter(llm_call=_fake({"intent": "choice", "choice": "예", "price_text": None}))
|
||||
out = await nat.interpret("네 접니다, 말씀하세요", input_mode="yes_no", input_options=["예", "아니오"])
|
||||
assert out == InterpretedInput(kind="choice", value="예", source="예")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_choice_outside_options_rejected():
|
||||
nat = InputInterpreter(llm_call=_fake({"intent": "choice", "choice": "글쎄요", "price_text": None}))
|
||||
assert await nat.interpret("음...", input_mode="yes_no", input_options=["예", "아니오"]) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_price_span_verified_and_parsed_deterministically():
|
||||
nat = InputInterpreter(llm_call=_fake({"intent": "price", "choice": None, "price_text": "1만 500원"}))
|
||||
out = await nat.interpret("저희 마진상 1만 500원까지는 맞춰드릴 수 있습니다", input_mode="price")
|
||||
assert out is not None and out.kind == "price"
|
||||
assert out.value == "10500" # 숫자는 결정론 파서 산출(LLM 계산 아님)
|
||||
assert out.source == "1만 500원"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_price_span_not_in_text_rejected():
|
||||
"""LLM 이 원문에 없는 가격 표현을 지어내면 폐기(환각 차단)."""
|
||||
nat = InputInterpreter(llm_call=_fake({"intent": "price", "choice": None, "price_text": "9,000원"}))
|
||||
assert await nat.interpret("만원이면 가능합니다", input_mode="price") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unknown_and_failures_fall_back():
|
||||
assert await InputInterpreter(llm_call=_fake({"intent": "unknown"})).interpret(
|
||||
"글쎄요 검토해 볼게요", input_mode="yes_no", input_options=["예", "아니오"]) is None
|
||||
|
||||
def boom(messages):
|
||||
raise RuntimeError("LLM down")
|
||||
assert await InputInterpreter(llm_call=boom).interpret("네", input_mode="yes_no", input_options=["예"]) is None
|
||||
|
||||
def slow(messages):
|
||||
import time
|
||||
time.sleep(0.5)
|
||||
return {"intent": "choice", "choice": "예"}
|
||||
nat = InputInterpreter(llm_call=slow, timeout_seconds=0.05)
|
||||
assert await nat.interpret("네", input_mode="yes_no", input_options=["예"]) is None
|
||||
|
||||
|
||||
# ---- 챗 플로우 E2E (fake LLM) ------------------------------------------------
|
||||
def _routing_fake(messages):
|
||||
"""단계별 fake — 기대 입력이 가격이면 price, 아니면 '예' choice 로 응답."""
|
||||
user = messages[-1]["content"]
|
||||
if "가격(숫자)" in user:
|
||||
return {"intent": "price", "choice": None, "price_text": "1만 500원"}
|
||||
return {"intent": "choice", "choice": "예", "price_text": None}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_flow_free_text_negotiation(db_engine):
|
||||
"""자유 발화만으로 담당자확인 분기 + 가격 입력이 진행된다 (버튼 없는 '진짜 대화')."""
|
||||
from router.v1.chat.protocol import Req_Chat
|
||||
from services.chat_service import ChatService, reset_sessions
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tenancy.registry import TenantEngineRegistry
|
||||
|
||||
reset_sessions()
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine("imarketkorea")
|
||||
eng.config.llm.enabled = True
|
||||
|
||||
svc = ChatService()
|
||||
svc._interpreter = InputInterpreter(llm_call=_routing_fake)
|
||||
orig = InputInterpreter.available
|
||||
InputInterpreter.available = staticmethod(lambda: True)
|
||||
try:
|
||||
sid = None
|
||||
r = await svc.chat(eng, Req_Chat(session_id=sid)) # 서비스안내
|
||||
sid = r.session_id
|
||||
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="확인")) # 담당자확인 (fast path)
|
||||
assert r.step == "담당자확인" and r.interpreted_input is None
|
||||
|
||||
# 자유 발화 → NLU 가 "예" 로 매핑 → 협상품목안내
|
||||
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="네 접니다, 말씀하세요"))
|
||||
assert r.step == "협상품목안내"
|
||||
assert r.interpreted_input == "예"
|
||||
|
||||
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="확인")) # 기존가격제시(price)
|
||||
# 자유 발화 가격 → span "1만 500원" → 결정론 파서 10500 → 가격 저장 후 확인 단계
|
||||
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="저희 마진상 1만 500원까지는 맞춰드릴 수 있습니다"))
|
||||
assert r.step == "가격협상_확인"
|
||||
assert r.interpreted_input == "10500"
|
||||
assert "10500" in r.script # 멘트 치환도 해석된 가격으로
|
||||
finally:
|
||||
InputInterpreter.available = orig
|
||||
eng.config.llm.enabled = False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_flow_without_llm_keeps_legacy_behavior(db_engine):
|
||||
"""LLM 미설정(available=False)이면 자유 발화는 원문 그대로 엔진에 전달 — 기존 동작 회귀 없음."""
|
||||
from router.v1.chat.protocol import Req_Chat
|
||||
from services.chat_service import ChatService, reset_sessions
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tenancy.registry import TenantEngineRegistry
|
||||
|
||||
reset_sessions()
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine("imarketkorea")
|
||||
|
||||
svc = ChatService()
|
||||
sid = None
|
||||
r = await svc.chat(eng, Req_Chat(session_id=sid))
|
||||
sid = r.session_id
|
||||
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="확인"))
|
||||
assert r.step == "담당자확인"
|
||||
# conftest 가드로 available=False → NLU 미동작, interpreted_input 없음
|
||||
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="네 접니다"))
|
||||
assert r.interpreted_input is None
|
||||
@ -1,190 +0,0 @@
|
||||
"""협상 불변식 시나리오 하네스 — 실서비스 스택(ChatService + 실 DB 카드)으로 13개 협상을 완주시키고,
|
||||
IMK 가 잡은 두 부류의 사고(같은 카드 반복 · 이상한 금액)가 어떤 흐름에서도 안 나는지 검사한다.
|
||||
|
||||
시나리오별 기대 이벤트(카드가 나간 턴의 step·카드·금액)를 정확히 못박고, 공통 불변식을 전 턴에 건다:
|
||||
· 카드 중복 없음 — 한 협상에서 같은 card_id 2회 발동 금지
|
||||
· 카드 자리 규칙 — 종결 전용(WC-03·05)은 가격협상_카운터에서만, 비종결 와일드는 wild_card_dynamic 에서만
|
||||
· 타결가 ≤ 목표가 — 어떤 성공 경로도 목표가 초과로 안 끝남
|
||||
· 카운터 멘트의 금액 = 수락 시 타결가 (표시가=타결가)
|
||||
"""
|
||||
|
||||
import uuid as _uuid
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from router.v1.chat.protocol import Req_Chat
|
||||
from services.chat_service import ChatService, reset_sessions
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tenancy.registry import TenantEngineRegistry
|
||||
from tests.test_card_tactics import _TENANTS_DIR, _cleanup, _seed_quote_session
|
||||
|
||||
# 종결 전용 와일드카드(DB tactic 시드와 동일) — 자리 규칙 검사용.
|
||||
_CLOSING_WILDS = {"WC-03", "WC-05"}
|
||||
_NONCLOSING_WILDS = {"WC-01", "WC-02", "WC-04"}
|
||||
# 카드가 나갈 수 있는 스텝(이벤트로 수집).
|
||||
_CARD_STEPS = {"가격협상", "wild_card_dynamic", "wild_card_1pct", "가격협상_카운터"}
|
||||
_BOILERPLATE = [None, "확인", "예", "확인"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Scenario:
|
||||
name: str
|
||||
inputs: list # 서두(안내~기존가격제시) 이후의 협력사 입력 시퀀스
|
||||
# 기대 이벤트: (step, card, offer_substring). card="NGC-*" 는 임의 협상카드(중복만 검사).
|
||||
events: list
|
||||
settled: Optional[int] # 기대 타결가(원). None=결렬
|
||||
nego: list = field(default_factory=lambda: ["NGC-001"])
|
||||
wild: list = field(default_factory=list)
|
||||
target: int = 10_000
|
||||
anchor: int = 9_900
|
||||
|
||||
|
||||
# 밴드(기본 target 10000·anchor 9900): 1% 존 ≤ 10,098 · 진입 존 ≤ 10,395.
|
||||
SCENARIOS = [
|
||||
# S01 BB9A 재현 — 중반 비종결 WC-02, 종결 WC-05 실절충가. 같은 카드 2회 없음.
|
||||
Scenario("S01_bb9a_mid_wc02_close_wc05",
|
||||
["10300", "예", "다른 가격 제시", "10010", "예", "10005", "예", "수락", "확인"],
|
||||
[("wild_card_dynamic", "WC-02", "9950"),
|
||||
("가격협상", "NGC-001", None),
|
||||
("가격협상_카운터", "WC-05", "9980")],
|
||||
settled=9980, wild=["WC-02", "WC-05"]),
|
||||
# S02 8AB0 재현 — 절충가(9,205)가 목표가(9,000) 초과 → WC-05 미발동, 목표가 최후통첩(카드 없음).
|
||||
Scenario("S02_8ab0_middle_over_target_skips",
|
||||
["9500", "예", "9500", "예", "다른 가격 제시", "9500", "예", "확인"],
|
||||
[("가격협상", "NGC-001", None),
|
||||
("가격협상_카운터", None, "9000")],
|
||||
settled=None, wild=["WC-05"], target=9_000, anchor=8_910),
|
||||
# S03 와일드 5장 전부 + 협상카드 2장 — 중반 1장(WC-01)·종결 1장(WC-03)만, 협상카드는 서로 다른 2장.
|
||||
Scenario("S03_five_wilds_full_run",
|
||||
["10300", "예", "다른 가격 제시", "10200", "예", "10150", "예", "10100", "예", "수락", "확인"],
|
||||
[("wild_card_dynamic", "WC-01", "10000"),
|
||||
("가격협상", "NGC-*", None),
|
||||
("가격협상", "NGC-*", None),
|
||||
("가격협상_카운터", "WC-03", "10000")],
|
||||
settled=10_000, nego=["NGC-001", "NGC-003"],
|
||||
wild=["WC-01", "WC-02", "WC-03", "WC-04", "WC-05"]),
|
||||
# S04 종결 전용 와일드만 담김 + 제시가가 진입 존에 머무름 — 소진 판정이 막히지 않고
|
||||
# 종결로 넘어간다(프로브 픽스 회귀: 픽스 전엔 빈 덱에서 쓴 카드를 또 꺼내는 무한 협상).
|
||||
Scenario("S04_closing_only_wild_no_deadlock",
|
||||
["10300", "예", "10250", "예", "수락", "확인"],
|
||||
[("가격협상", "NGC-001", None),
|
||||
("가격협상_카운터", None, "10000")], # WC-05 절충 10,075>목표가 → 미발동 → 최후통첩
|
||||
settled=10_000, wild=["WC-05"]),
|
||||
# S05 1% 존 — 시스템 1% 카드, 수락 시 표시 금액 그대로 타결.
|
||||
Scenario("S05_one_pct_zone_accept",
|
||||
["10050", "예", "예", "확인"],
|
||||
[("wild_card_1pct", None, "9950")],
|
||||
settled=9_950),
|
||||
# S06 앵커 이하 즉시 타결 — 카드 0장.
|
||||
Scenario("S06_priority_match_no_cards",
|
||||
["9800", "예", "확인"],
|
||||
[],
|
||||
settled=9_800),
|
||||
# S07 목표가 초과 고수 → 설득 1장 → 최후통첩 → 결렬.
|
||||
Scenario("S07_hold_high_fails",
|
||||
["11000", "예", "11000", "예", "다른 가격 제시", "11000", "예", "확인"],
|
||||
[("가격협상", "NGC-003", None),
|
||||
("가격협상_카운터", None, "10000")],
|
||||
settled=None, nego=["NGC-003"]),
|
||||
# S08 협상카드 카운터(NGC-010 목표가 제안) 수락 — 협상카드도 카운터 스텝을 쓴다.
|
||||
Scenario("S08_nego_counter_accept",
|
||||
["11000", "예", "수락", "확인"],
|
||||
[("가격협상_카운터", "NGC-010", "10000")],
|
||||
settled=10_000, nego=["NGC-010"]),
|
||||
# S09 min_round=2 — WC-04 는 1라운드 진입 존에서 안 나가고 2라운드에 나간다.
|
||||
Scenario("S09_min_round_two_defers_wc04",
|
||||
["10300", "예", "10200", "예", "수락", "확인"],
|
||||
[("가격협상", "NGC-001", None),
|
||||
("wild_card_dynamic", "WC-04", "10000")],
|
||||
settled=10_000, wild=["WC-04"]),
|
||||
# S10 종결 체인 폴백 — WC-05 무효(절충 10,175>목표) → 다음 종결 WC-03 발동.
|
||||
Scenario("S10_closing_chain_falls_to_wc03",
|
||||
["10500", "예", "10450", "예", "다른 가격 제시", "10450", "예", "확인"],
|
||||
[("가격협상", "NGC-001", None),
|
||||
("가격협상_카운터", "WC-03", "10000")],
|
||||
settled=None, wild=["WC-05", "WC-03"]),
|
||||
# S11 중반+종결 콤보 — WC-02 중반, 종결은 WC-05 무효 건너뛰고 WC-03. 전 카드 1회씩.
|
||||
Scenario("S11_mid_and_closing_combo",
|
||||
["10300", "예", "다른 가격 제시", "10400", "예", "10350", "예", "수락", "확인"],
|
||||
[("wild_card_dynamic", "WC-02", "9950"),
|
||||
("가격협상", "NGC-001", None),
|
||||
("가격협상_카운터", "WC-03", "10000")],
|
||||
settled=10_000, wild=["WC-02", "WC-05", "WC-03"]),
|
||||
# S12 라운드 상한 — 협상카드 3장 각 1회(중복 없음) 후 상한 도달 → 최후통첩 → 결렬.
|
||||
Scenario("S12_round_cap_distinct_nego_cards",
|
||||
["11000", "예", "11000", "예", "11000", "예", "11000", "예", "다른 가격 제시", "11000", "예", "확인"],
|
||||
[("가격협상", "NGC-*", None),
|
||||
("가격협상", "NGC-*", None),
|
||||
("가격협상", "NGC-*", None),
|
||||
("가격협상_카운터", None, "10000")],
|
||||
settled=None, nego=["NGC-001", "NGC-002", "NGC-003", "NGC-004", "NGC-005"]),
|
||||
# S13 재생성 아님·재료 극단 — 앵커 미박제 세션(anchor=target 폴백)에서도 초과 제시·중복 없음.
|
||||
Scenario("S13_anchor_equals_target_fallback",
|
||||
["10300", "예", "10200", "예", "수락", "확인"],
|
||||
[("가격협상", "NGC-001", None),
|
||||
("가격협상_카운터", "WC-03", "10000")], # WC-05 절충 (10000+10200)/2=10100>목표 → 스킵
|
||||
settled=10_000, wild=["WC-05", "WC-03"], anchor=10_000),
|
||||
# S14 역행 금지(IMK 논의 재현) — 절충 카드(9,950) 뒤에 예산 상한 카드(NGC-007, 앵커 9,900)가
|
||||
# 선택돼 있어도 발동하지 않는다(설득 폴백으로도 안 나감). 낼 카드가 없어져 종결(목표가 최후통첩)로.
|
||||
Scenario("S14_no_offer_regression",
|
||||
["10300", "예", "다른 가격 제시", "10200", "예", "수락", "확인"],
|
||||
[("wild_card_dynamic", "WC-02", "9950"),
|
||||
("가격협상_카운터", None, "10000")], # NGC-007 이벤트가 없어야 함(역행 차단)
|
||||
settled=10_000, nego=["NGC-007"], wild=["WC-02"]),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sc", SCENARIOS, ids=[s.name for s in SCENARIOS])
|
||||
async def test_negotiation_invariants(db_engine, sc: Scenario):
|
||||
reset_sessions()
|
||||
sid = _uuid.uuid4()
|
||||
qid, ver_id = await _seed_quote_session(sid, sc.nego, wild_numbers=sc.wild,
|
||||
target=sc.target, anchor=sc.anchor)
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(_uuid.uuid4()))
|
||||
svc = ChatService()
|
||||
trace, settled, outcome = [], None, None
|
||||
for ui in [*_BOILERPLATE, *sc.inputs]:
|
||||
r = await svc.chat(eng, Req_Chat(session_id=str(sid), user_input=ui))
|
||||
assert r.result.success is True, f"{sc.name}: 턴 실패 input={ui} msg={r.msg}"
|
||||
trace.append(r)
|
||||
if r.settled_price is not None:
|
||||
settled = r.settled_price
|
||||
if r.chat_end:
|
||||
outcome = r.outcome
|
||||
|
||||
# ── 기대 이벤트(카드/카운터 턴) 정확 일치 ──
|
||||
events = [r for r in trace if r.step in _CARD_STEPS]
|
||||
got = [(r.step, r.card_id) for r in events]
|
||||
assert len(events) == len(sc.events), f"{sc.name}: 이벤트 수 {got} ≠ 기대 {sc.events}"
|
||||
for r, (step, card, offer) in zip(events, sc.events):
|
||||
assert r.step == step, f"{sc.name}: step {r.step} ≠ {step} (전체 {got})"
|
||||
if card == "NGC-*":
|
||||
assert r.card_id and r.card_id.startswith("NGC-"), f"{sc.name}: 협상카드 기대, 실제 {r.card_id}"
|
||||
else:
|
||||
assert r.card_id == card, f"{sc.name}: card {r.card_id} ≠ {card} (전체 {got})"
|
||||
if offer is not None:
|
||||
assert offer in (r.script or ""), f"{sc.name}: 멘트에 금액 {offer} 없음 — {r.script[:80]}"
|
||||
|
||||
# ── 공통 불변식 ──
|
||||
played = [r.card_id for r in events if r.card_id]
|
||||
assert len(played) == len(set(played)), f"{sc.name}: 카드 중복 발동 {played}"
|
||||
for r in events:
|
||||
if r.card_id in _CLOSING_WILDS:
|
||||
assert r.step == "가격협상_카운터", f"{sc.name}: 종결 카드 {r.card_id}가 중반({r.step})에 발동"
|
||||
if r.card_id in _NONCLOSING_WILDS:
|
||||
assert r.step == "wild_card_dynamic", f"{sc.name}: 비종결 와일드 {r.card_id}가 {r.step}에서 발동"
|
||||
|
||||
# ── 결말 ──
|
||||
if sc.settled is None:
|
||||
assert outcome == "failure" and settled is None, f"{sc.name}: 결렬 기대, settled={settled} outcome={outcome}"
|
||||
else:
|
||||
assert outcome == "success", f"{sc.name}: 타결 기대, outcome={outcome}"
|
||||
assert settled == sc.settled, f"{sc.name}: 타결가 {settled} ≠ 기대 {sc.settled}"
|
||||
assert settled <= sc.target, f"{sc.name}: 목표가 초과 타결 {settled} > {sc.target}"
|
||||
finally:
|
||||
await _cleanup(sid, qid, ver_id)
|
||||
@ -29,12 +29,12 @@ async def test_step_requires_tenant_header(client):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_step_tenant_divergence(client):
|
||||
rk = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "_base"}, json=_BODY)
|
||||
rk = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "ktcommerce"}, json=_BODY)
|
||||
ri = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "imarketkorea"}, json=_BODY)
|
||||
assert rk.status_code == 200 and ri.status_code == 200
|
||||
dk, di = rk.json(), ri.json()
|
||||
# 같은 입력이 테넌트 config 에 따라 다른 상태/카드로 갈린다 (_base=공용 NGC-0xx, imk=NGC-Bxxx)
|
||||
assert dk["card_id"].startswith("NGC-0")
|
||||
# 같은 입력이 테넌트 config 에 따라 다른 상태/카드로 갈린다
|
||||
assert dk["card_id"].startswith("NGC-A")
|
||||
assert di["card_id"].startswith("NGC-B")
|
||||
assert dk["state_index"] != di["state_index"]
|
||||
# 응답 형태
|
||||
@ -49,7 +49,7 @@ async def test_step_tenant_divergence(client):
|
||||
@pytest.mark.asyncio
|
||||
async def test_step_invalid_distribution_code_is_domain_error(client):
|
||||
body = dict(_BODY, distribution_code="Z")
|
||||
r = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "imarketkorea"}, json=body)
|
||||
r = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "ktcommerce"}, json=body)
|
||||
assert r.status_code == 200 # HTTP 는 200, 결과코드로 에러 전달(backend 규약)
|
||||
assert r.json()["result"]["desc"] == "NEGO_INVALID_STEP"
|
||||
|
||||
@ -57,5 +57,5 @@ async def test_step_invalid_distribution_code_is_domain_error(client):
|
||||
@pytest.mark.asyncio
|
||||
async def test_step_invalid_outcome(client):
|
||||
body = dict(_BODY, outcome="maybe")
|
||||
r = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "imarketkorea"}, json=body)
|
||||
r = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "ktcommerce"}, json=body)
|
||||
assert r.json()["result"]["desc"] == "INVALID_REQUEST_DATA"
|
||||
|
||||
@ -62,5 +62,5 @@ async def test_tenant_header_required(client):
|
||||
assert r.json()["result"]["desc"] == "TENANT_HEADER_MISSING"
|
||||
|
||||
# 헤더가 있으면 미들웨어 통과 (라우트 미존재라 404).
|
||||
r = await client.get("/v1/some-protected-path", headers={"X-Tenant-ID": "imarketkorea"})
|
||||
r = await client.get("/v1/some-protected-path", headers={"X-Tenant-ID": "ktcommerce"})
|
||||
assert r.status_code == 404
|
||||
|
||||
@ -22,7 +22,7 @@ def _loader() -> TenantConfigLoader:
|
||||
|
||||
|
||||
def test_platform_neutral_defaults_load():
|
||||
cfg = _loader().load("_base")
|
||||
cfg = _loader().load("ktcommerce")
|
||||
|
||||
# 우리 플랫폼 중립 기본값 (CLEANROOM.md)
|
||||
assert cfg.state.revenue.thresholds == [10_000_000, 50_000_000]
|
||||
@ -47,12 +47,12 @@ def test_platform_neutral_defaults_load():
|
||||
|
||||
|
||||
def test_state_space_and_action_space_size():
|
||||
cfg = _loader().load("_base")
|
||||
cfg = _loader().load("ktcommerce")
|
||||
assert cfg.state.state_space_size == 162 # 3×3×3×3×2 (차원 구성은 기능적 설계)
|
||||
assert cfg.action_mapping.action_space_size == 11
|
||||
# 공용 카드 코드 (파일 폴백 스냅샷 — 정본은 DB 카탈로그)
|
||||
assert cfg.action_mapping.action_to_card["0"] == "NGC-001"
|
||||
assert cfg.action_mapping.action_to_card["8"] == "NGC-009"
|
||||
assert cfg.action_mapping.action_space_size == 9
|
||||
# 합성 데모 카드 코드 (우리 스킴)
|
||||
assert cfg.action_mapping.action_to_card["0"] == "NGC-A001"
|
||||
assert cfg.action_mapping.action_to_card["8"] == "NGC-A009"
|
||||
|
||||
|
||||
def test_base_deep_merge_unit():
|
||||
@ -77,19 +77,20 @@ def test_second_tenant_overrides_merged_on_base():
|
||||
assert cfg.policy.type == "ucb"
|
||||
# 차원은 데모 테넌트 A 와 동일(162) → base warm-start 호환(P5)
|
||||
assert cfg.state.state_space_size == 162
|
||||
assert cfg.action_mapping.action_space_size == 11
|
||||
assert cfg.action_mapping.action_space_size == 9
|
||||
assert cfg.action_mapping.action_to_card["0"] == "NGC-B001"
|
||||
|
||||
|
||||
def test_base_self_does_not_inherit():
|
||||
cfg = _loader().load("_base")
|
||||
assert cfg.tenant_id == "_base"
|
||||
# _base 는 기본 11카드(자동 온보딩 테넌트가 물려받음, base 정책 162×11 정합)
|
||||
assert cfg.action_mapping.action_space_size == 11
|
||||
# _base 는 기본 9카드(자동 온보딩 테넌트가 물려받음, base 정책 162×9 정합)
|
||||
assert cfg.action_mapping.action_space_size == 9
|
||||
|
||||
|
||||
def test_is_registered():
|
||||
loader = _loader()
|
||||
assert loader.is_registered("ktcommerce") is True
|
||||
assert loader.is_registered("imarketkorea") is True
|
||||
# 미등록 company_id(uuid 등)는 _base 자동 온보딩 대상이라 '등록됨'으로 본다. 빈 키만 미등록.
|
||||
assert loader.is_registered("00000000-0000-0000-0000-000000000001") is True
|
||||
@ -98,7 +99,7 @@ def test_is_registered():
|
||||
|
||||
def test_no_proprietary_card_codes_or_labels_in_repo():
|
||||
"""클린룸 가드: 독점 카드 코드/ verbatim 라벨이 로드된 config 에 존재하지 않는다."""
|
||||
for tid in ("_base", "imarketkorea"):
|
||||
for tid in ("_base", "ktcommerce", "imarketkorea"):
|
||||
cfg = _loader().load(tid)
|
||||
cards = " ".join(cfg.action_mapping.action_to_card.values())
|
||||
assert "NC26" not in cards # 참고 엔진의 고유 카드 코드
|
||||
|
||||
@ -46,7 +46,7 @@ def _snapshot(**over) -> NegotiationSnapshot:
|
||||
|
||||
|
||||
def test_build_state_deterministic_and_in_range():
|
||||
cfg = _cfg("_base")
|
||||
cfg = _cfg("ktcommerce")
|
||||
snap = _snapshot()
|
||||
s1 = build_state(snap, cfg.state)
|
||||
s2 = build_state(snap, cfg.state)
|
||||
@ -65,7 +65,7 @@ def test_encode_index_known_example():
|
||||
|
||||
|
||||
def test_mixed_radix_bijection_over_full_space():
|
||||
cfg = _cfg("_base")
|
||||
cfg = _cfg("ktcommerce")
|
||||
dims = state_dims(cfg.state)
|
||||
assert dims == [3, 3, 3, 3, 2]
|
||||
seen = set()
|
||||
@ -77,17 +77,17 @@ def test_mixed_radix_bijection_over_full_space():
|
||||
|
||||
|
||||
def test_config_injection_changes_classification():
|
||||
# revenue=20,000,000 원: _base(th=[10M,50M]) → mid(1), imarketkorea(th=[30M,100M]) → low(0)
|
||||
# revenue=20,000,000 원: ktcommerce(th=[10M,50M]) → mid(1), imarketkorea(th=[30M,100M]) → low(0)
|
||||
snap = _snapshot(revenue_amount=20_000_000)
|
||||
base = build_state(snap, _cfg("_base").state)
|
||||
kt = build_state(snap, _cfg("ktcommerce").state)
|
||||
imk = build_state(snap, _cfg("imarketkorea").state)
|
||||
assert base.revenue_idx == 1
|
||||
assert kt.revenue_idx == 1
|
||||
assert imk.revenue_idx == 0
|
||||
assert base != imk # 같은 입력이 테넌트 config 에 따라 다른 상태
|
||||
assert kt != imk # 같은 입력이 테넌트 config 에 따라 다른 상태
|
||||
|
||||
|
||||
def test_distribution_unknown_code_raises():
|
||||
cfg = _cfg("_base")
|
||||
cfg = _cfg("ktcommerce")
|
||||
snap = _snapshot(distribution_code="Z") # code_map 에 없음
|
||||
try:
|
||||
build_state(snap, cfg.state)
|
||||
@ -97,7 +97,7 @@ def test_distribution_unknown_code_raises():
|
||||
|
||||
|
||||
def test_price_zone_and_partner_buckets():
|
||||
cfg = _cfg("_base").state
|
||||
cfg = _cfg("ktcommerce").state
|
||||
# 제시가 ≤ 앵커가(9900) → 우선협상 구간(0)
|
||||
assert build_state(_snapshot(input_price=9800), cfg).price_zone_idx == 0
|
||||
# 제시가 > 앵커가 → 협상 지속 구간(1)
|
||||
@ -110,28 +110,28 @@ def test_price_zone_and_partner_buckets():
|
||||
|
||||
def test_reward_deterministic_and_config_driven():
|
||||
snap = _snapshot(outcome=NegotiationOutcome.FAILURE, round_number=2)
|
||||
base = _cfg("_base")
|
||||
kt = _cfg("ktcommerce")
|
||||
imk = _cfg("imarketkorea")
|
||||
base_rc = RewardCalculator(base.reward, base.state) # failure_penalty -0.5
|
||||
kt_rc = RewardCalculator(kt.reward, kt.state) # failure_penalty -0.5
|
||||
imk_rc = RewardCalculator(imk.reward, imk.state) # failure_penalty -0.7
|
||||
|
||||
r1 = base_rc.calculate(snap)
|
||||
r2 = base_rc.calculate(snap)
|
||||
r1 = kt_rc.calculate(snap)
|
||||
r2 = kt_rc.calculate(snap)
|
||||
assert r1 == r2 # 결정론
|
||||
assert r1.end_reward == -0.5 # config 반영
|
||||
assert imk_rc.calculate(snap).end_reward == -0.7
|
||||
|
||||
# 성공 라운드 보상이 실패보다 크다 (방향성)
|
||||
success = _snapshot(outcome=NegotiationOutcome.SUCCESS, round_number=0)
|
||||
assert base_rc.calculate(success).total > base_rc.calculate(_snapshot(outcome=NegotiationOutcome.FAILURE, round_number=0)).total
|
||||
assert kt_rc.calculate(success).total > kt_rc.calculate(_snapshot(outcome=NegotiationOutcome.FAILURE, round_number=0)).total
|
||||
|
||||
|
||||
def test_action_card_mapper_roundtrip_and_mask():
|
||||
cfg = _cfg("_base")
|
||||
cfg = _cfg("ktcommerce")
|
||||
mapper = ActionCardMapper(cfg.action_mapping)
|
||||
assert mapper.action_space_size == 11
|
||||
assert mapper.get_card_id(0) == "NGC-001"
|
||||
assert mapper.get_action_id("NGC-001") == 0
|
||||
assert mapper.action_space_size == 9
|
||||
assert mapper.get_card_id(0) == "NGC-A001"
|
||||
assert mapper.get_action_id("NGC-A001") == 0
|
||||
assert mapper.get_card_id(99) is None
|
||||
|
||||
# 중복방지 마스킹: 사용한 action 제외
|
||||
@ -139,7 +139,7 @@ def test_action_card_mapper_roundtrip_and_mask():
|
||||
assert mask.dtype == np.bool_
|
||||
assert mask[0] == False and mask[3] == False
|
||||
assert mask[1] == True
|
||||
assert mask.sum() == 9
|
||||
assert mask.sum() == 7
|
||||
|
||||
# reload 로 다른 테넌트 카드셋 교체
|
||||
mapper.reload(_cfg("imarketkorea").action_mapping)
|
||||
|
||||
@ -27,22 +27,22 @@ def _registry() -> TenantEngineRegistry:
|
||||
@pytest.mark.asyncio
|
||||
async def test_two_tenants_distinct_engines():
|
||||
reg = _registry()
|
||||
e1 = await reg.get_engine("_base")
|
||||
e1 = await reg.get_engine("ktcommerce")
|
||||
e2 = await reg.get_engine("imarketkorea")
|
||||
assert e1 is not e2
|
||||
assert e1.tenant_id == "_base" and e2.tenant_id == "imarketkorea"
|
||||
# 서로 다른 카드매핑 (다른 카드셋 — _base=공용 카탈로그, imk=파일 오버라이드)
|
||||
assert e1.mapper.get_card_id(0) == "NGC-001"
|
||||
assert e1.tenant_id == "ktcommerce" and e2.tenant_id == "imarketkorea"
|
||||
# 서로 다른 카드매핑 (다른 카드셋)
|
||||
assert e1.mapper.get_card_id(0) == "NGC-A001"
|
||||
assert e2.mapper.get_card_id(0) == "NGC-B001"
|
||||
# 차원
|
||||
assert e1.state_space_size == 162 and e1.action_space_size == 9 # 카탈로그 9장(NGC-006·009 소프트삭제)
|
||||
assert e1.state_space_size == 162 and e1.action_space_size == 9
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_engine_cached():
|
||||
reg = _registry()
|
||||
a = await reg.get_engine("imarketkorea")
|
||||
b = await reg.get_engine("imarketkorea")
|
||||
a = await reg.get_engine("ktcommerce")
|
||||
b = await reg.get_engine("ktcommerce")
|
||||
assert a is b # 캐시 — 동일 인스턴스
|
||||
|
||||
|
||||
@ -58,7 +58,7 @@ async def test_concurrent_first_build_once():
|
||||
return EngineFactory.build(config)
|
||||
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0), factory=CountingFactory)
|
||||
results = await asyncio.gather(*[reg.get_engine("imarketkorea") for _ in range(12)])
|
||||
results = await asyncio.gather(*[reg.get_engine("ktcommerce") for _ in range(12)])
|
||||
# 모두 같은 인스턴스 + 1회만 조립
|
||||
assert all(r is results[0] for r in results)
|
||||
assert builds["n"] == 1
|
||||
@ -69,9 +69,9 @@ async def test_unregistered_company_id_auto_onboards():
|
||||
reg = _registry()
|
||||
# 미등록 company_id(uuid)는 _base 자동 온보딩 → 엔진 생성됨(베이스 9카드, 162 state).
|
||||
eng = await reg.get_engine("00000000-0000-0000-0000-000000000001")
|
||||
assert eng.action_space_size == 9 and eng.state_space_size == 162 # DB 카탈로그 9장
|
||||
assert eng.action_space_size == 9 and eng.state_space_size == 162
|
||||
assert eng.company_id == "00000000-0000-0000-0000-000000000001"
|
||||
assert reg.is_registered("imarketkorea") is True
|
||||
assert reg.is_registered("ktcommerce") is True
|
||||
# 빈 키만 미등록 → KeyError
|
||||
with pytest.raises(KeyError):
|
||||
await reg.get_engine("")
|
||||
@ -80,9 +80,9 @@ async def test_unregistered_company_id_auto_onboards():
|
||||
@pytest.mark.asyncio
|
||||
async def test_reload_rebuilds_only_that_tenant():
|
||||
reg = _registry()
|
||||
a = await reg.get_engine("_base")
|
||||
a = await reg.get_engine("ktcommerce")
|
||||
b = await reg.get_engine("imarketkorea")
|
||||
reloaded = await reg.reload("_base")
|
||||
reloaded = await reg.reload("ktcommerce")
|
||||
assert reloaded is not a # 재조립됨
|
||||
assert await reg.get_engine("imarketkorea") is b # 타테넌트는 그대로
|
||||
|
||||
@ -97,132 +97,6 @@ def test_episode_state_is_request_scoped():
|
||||
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("imarketkorea") # 비-UUID → 조회 안 함
|
||||
assert eng.config.resources.company_name == "데모상사 B"
|
||||
|
||||
|
||||
@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
|
||||
async def test_middleware_header_missing_unregistered_registered(client):
|
||||
# 헤더 누락 → 400
|
||||
@ -236,6 +110,6 @@ async def test_middleware_header_missing_unregistered_registered(client):
|
||||
assert r.json().get("result", {}).get("desc") != "TENANT_NOT_REGISTERED"
|
||||
|
||||
# 등록 테넌트 → 미들웨어 통과
|
||||
r = await client.get("/v1/protected", headers={"X-Tenant-ID": "imarketkorea"})
|
||||
r = await client.get("/v1/protected", headers={"X-Tenant-ID": "ktcommerce"})
|
||||
assert r.status_code == 404
|
||||
assert r.json().get("result", {}).get("desc") != "TENANT_NOT_REGISTERED"
|
||||
|
||||
@ -58,8 +58,8 @@ async def test_warm_start_copies_base_with_decayed_visits(db_engine):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cold_start_creates_warmstart_version(db_engine):
|
||||
await _seed_base(A=11) # imarketkorea action_space=11 과 차원 일치해야 warm-start
|
||||
eng = await _reg().get_engine("imarketkorea") # 활성 버전 없음 → cold-start
|
||||
await _seed_base()
|
||||
eng = await _reg().get_engine("ktcommerce") # 활성 버전 없음 → cold-start
|
||||
policy, version_id, repo = await QTablePolicyStore.load(eng)
|
||||
err, ver = await repo.read(lambda s: repo.get_active_version(s))
|
||||
assert ver.version_name == "v000_warmstart_from_base"
|
||||
@ -67,57 +67,6 @@ async def test_cold_start_creates_warmstart_version(db_engine):
|
||||
assert policy.qtable.q[5, 2] == 0.9
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_dim_change_migrates_preserving_learning(db_engine):
|
||||
"""카탈로그 카드 수 변경(7→9) 시 학습 보존 마이그레이션 — 겹치는 셀 복사 + 새 카드 fresh."""
|
||||
import uuid as _uuid
|
||||
cid = str(_uuid.uuid4())
|
||||
# 이 회사 활성 버전을 A=7 로 시드 + 셀 (5,2)=0.9
|
||||
repo = LearningRepository(cid)
|
||||
vid = await repo.get_or_create_active_version(
|
||||
state_space_size=162, action_space_size=7, learning_rate=0.1, discount_factor=0.95,
|
||||
scope=2, version_name="old_v7")
|
||||
await repo.upsert_cell(vid, state_index=5, action_id=2, q_value=0.9, count=7)
|
||||
|
||||
# 엔진(_base type:db → 카탈로그 9장) 로드 → 7≠9 감지 → 마이그레이션
|
||||
eng = await _reg().get_engine(cid)
|
||||
assert eng.action_space_size == 9
|
||||
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, 8] == 0.0 # 새 카드(action 8) 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 == 9
|
||||
|
||||
|
||||
@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
|
||||
async def test_dimension_mismatch_falls_back_to_heuristic(db_engine):
|
||||
await _seed_base(S=162, A=9)
|
||||
@ -140,7 +89,7 @@ async def test_no_base_returns_none(db_engine):
|
||||
@pytest.mark.asyncio
|
||||
async def test_existing_version_not_warmstarted(db_engine):
|
||||
await _seed_base()
|
||||
eng = await _reg().get_engine("imarketkorea")
|
||||
eng = await _reg().get_engine("ktcommerce")
|
||||
# 첫 로드 → warm-start 버전 생성
|
||||
await QTablePolicyStore.load(eng)
|
||||
# 둘째 로드 → 기존 활성 버전 재사용(중복 warm-start 안 함)
|
||||
|
||||
@ -7,7 +7,7 @@ reset-learning, reset-all, q-table/{versions,switch,current}, experience-logs, t
|
||||
|
||||
import pytest
|
||||
|
||||
H = {"X-Tenant-ID": "imarketkorea"}
|
||||
H = {"X-Tenant-ID": "ktcommerce"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@ -66,26 +66,6 @@ async def test_card_update_search(client, db_engine):
|
||||
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
|
||||
async def test_invalidate_and_reset_scoped(client, db_engine):
|
||||
# 가격협상 카드선택이 일어나는 긴 경로(850→900→990)로 양 테넌트 데이터 생성
|
||||
@ -97,7 +77,7 @@ async def test_invalidate_and_reset_scoped(client, db_engine):
|
||||
sid = cr.json()["session_id"]
|
||||
if cr.json().get("chat_end"):
|
||||
break
|
||||
H2 = {"X-Tenant-ID": "00000000-0000-0000-0000-0000000000b2"} # 실고객사 모사(자동 온보딩)
|
||||
H2 = {"X-Tenant-ID": "imarketkorea"}
|
||||
sid2 = None
|
||||
for ui in convo:
|
||||
cr = await client.post("/v1/chat", headers=H2, json={"session_id": sid2, "user_input": ui})
|
||||
@ -108,7 +88,7 @@ async def test_invalidate_and_reset_scoped(client, db_engine):
|
||||
before2 = (await client.get("/v1/experience-logs", headers=H2)).json()["total"]
|
||||
assert before2 >= 1
|
||||
|
||||
# imarketkorea reset-all → 타테넌트(H2) 무영향
|
||||
# ktcommerce reset-all → imarketkorea 무영향
|
||||
assert (await client.post("/v1/reset-all", headers=H)).json()["success"]
|
||||
assert (await client.get("/v1/experience-logs", headers=H)).json()["total"] == 0
|
||||
assert (await client.get("/v1/experience-logs", headers=H2)).json()["total"] == before2
|
||||
|
||||
@ -2,8 +2,8 @@
|
||||
|
||||
1. 전체 대화: 서비스안내→담당자확인→협상품목안내→가격협상→와일드카드→협상완료→협상종료(chat_end).
|
||||
2. 가격협상 턴에서 카드 선택 + 학습(card_id, updated_q).
|
||||
3. 와일드카드 발동(wild_card_1pct) + 종료 보상(success).
|
||||
4. 브랜드 치환(데모상사 B), 클린룸(스크립트에 KT 흔적 없음).
|
||||
3. 와일드카드 발동(wild_card_budget) + 종료 보상(success).
|
||||
4. 브랜드 치환 테넌트별(데모상사 A/B), 클린룸(스크립트에 KT 흔적 없음).
|
||||
5. 경험로그 적재 + 종료 후 진행 시 에러.
|
||||
6. (HTTP) 헤더로 새 세션 시작 + 한 턴 진행.
|
||||
"""
|
||||
@ -15,8 +15,6 @@ import pytest
|
||||
|
||||
from router.v1.chat.protocol import Req_Chat
|
||||
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 tenancy.config_loader import TenantConfigLoader
|
||||
from tenancy.registry import TenantEngineRegistry
|
||||
@ -44,11 +42,10 @@ async def _run(svc, eng, turns):
|
||||
@pytest.mark.asyncio
|
||||
async def test_full_conversation_reaches_completion(db_engine):
|
||||
reset_sessions()
|
||||
eng = await _reg().get_engine("imarketkorea")
|
||||
eng = await _reg().get_engine("ktcommerce")
|
||||
svc = ChatService()
|
||||
# anchor=9900, target=10000(기본). 11000(>anchor*1.02)→가격협상(카드),
|
||||
# 10000(anchor<p≤anchor*1.02)→1% 와일드카드→수락하면 협상완료.
|
||||
turns = [None, "확인", "예", "확인", "11000", "예", "10000", "예", "예",
|
||||
# anchor=9900, target=10000(기본). 11000(>10395)→가격협상(카드), 10200(9900~10395)→와일드카드, 9800(≤anchor)→우선협상
|
||||
turns = [None, "확인", "예", "확인", "11000", "예", "10200", "예", "9800", "예",
|
||||
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."]
|
||||
out = await _run(svc, eng, turns)
|
||||
steps = [r.step for r in out]
|
||||
@ -59,22 +56,22 @@ async def test_full_conversation_reaches_completion(db_engine):
|
||||
|
||||
# 가격협상 카드선택 + 학습
|
||||
nego = [r for r in out if r.step == "가격협상"]
|
||||
assert nego and nego[0].card_id and nego[0].card_id.startswith("NGC-B")
|
||||
assert nego and nego[0].card_id and nego[0].card_id.startswith("NGC-A")
|
||||
assert nego[0].updated_q is not None
|
||||
|
||||
# 와일드카드 발동 (1% 인하)
|
||||
assert any(r.step == "wild_card_1pct" for r in out)
|
||||
# 와일드카드 발동
|
||||
assert any(r.step == "wild_card_budget" for r in out)
|
||||
|
||||
# 종료 보상(success)
|
||||
done = [r for r in out if r.outcome == "success"]
|
||||
assert done and done[0].reward_total is not None
|
||||
|
||||
# 브랜드 치환 + 클린룸
|
||||
assert "데모상사 B" in out[0].script
|
||||
assert "데모상사 A" in out[0].script
|
||||
assert not _KT.search(out[0].script)
|
||||
|
||||
# 경험로그 적재
|
||||
repo = LearningRepository("imarketkorea")
|
||||
repo = LearningRepository("ktcommerce")
|
||||
err, cnt = await repo.read(lambda s: repo.count_experience(s))
|
||||
assert cnt >= 1
|
||||
|
||||
@ -87,7 +84,7 @@ async def test_wildcard_1pct_accept_settles_at_offer_price(db_engine):
|
||||
잡히던 버그 — settled_price 가 인하가(예: 19800)로 내려와야 한다.
|
||||
"""
|
||||
reset_sessions()
|
||||
eng = await _reg().get_engine("imarketkorea")
|
||||
eng = await _reg().get_engine("ktcommerce")
|
||||
svc = ChatService()
|
||||
# anchor=9900(기본). 10000 은 anchor*1.02(10098) 이내 → wild_card_1pct 발동, offer_1pct=9900.
|
||||
out = await _run(svc, eng, [None, "확인", "예", "확인", "10000", "예", "예",
|
||||
@ -125,121 +122,10 @@ def test_acceptance_ratio_dynamic_calc():
|
||||
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-B{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="imarketkorea", company_id="imarketkorea",
|
||||
context={"selected_nego_card_numbers": ["NGC-B003", "NGC-B008"]}, action_space_size=11,
|
||||
)
|
||||
|
||||
# ① card_id 는 고정 매핑 (선택 리스트 인덱싱 아님)
|
||||
assert ChatService._card_id_for_action(eng, session, 0) == "NGC-B001"
|
||||
assert ChatService._card_id_for_action(eng, session, 2) == "NGC-B003"
|
||||
|
||||
# ② 선택은 mask 로 — NGC-B003(action 2), NGC-B008(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_counter_display_price_equals_settlement():
|
||||
"""회귀(표시가≠투찰가): 카운터 제시 중 멘트에 보이는 절충/중간 변수
|
||||
(middle_price·target_mid_price)는 수락 시 타결가(pending_counter_price)와 정확히 일치해야 한다.
|
||||
|
||||
버그: WC-05(중간값 절충)에서 compute_counter 는 target 클램프·prev_customer 갱신으로 1,700,000 을
|
||||
pending 으로 적재하는데, vars_for 가 {middle_price} 를 재계산해 1,740,000 으로 표시 → 화면엔
|
||||
1,740,000 인데 실제로는 1,700,000 으로 투찰되던 문제. pending 으로 고정해 표시가==타결가."""
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||
repo = ScriptRepository(cfg, _TENANTS_DIR)
|
||||
engine = ChatEngine(repo, rq_type="재협상")
|
||||
session = ChatSession(
|
||||
session_id="00000000-0000-0000-0000-000000000009",
|
||||
tenant_id="imarketkorea", company_id="imarketkorea", action_space_size=0,
|
||||
context={
|
||||
"anchor_price": 2000000, "target_price": 1700000, "input_price": 1780000,
|
||||
"prev_customer_price": 1700000, # 종결 전술이 counter 로 덮어쓴 상태
|
||||
"pending_counter_price": 1700000, # compute_counter 의 target 클램프 결과(실제 타결가)
|
||||
},
|
||||
)
|
||||
v = engine.vars_for(session)
|
||||
assert v["counter_price"] == 1700000
|
||||
assert v["middle_price"] == 1700000 # 재계산값 1,740,000 이 아니라 pending
|
||||
assert v["target_mid_price"] == 1700000
|
||||
|
||||
|
||||
def test_default_1pct_wildcard_still_runs_without_selected_wildcard():
|
||||
"""1% 인하는 기본 제공 카드라 DB 견적에서 와일드카드를 선택하지 않아도 발동한다."""
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||
repo = ScriptRepository(cfg, _TENANTS_DIR)
|
||||
engine = ChatEngine(repo, rq_type="재협상")
|
||||
session = ChatSession(
|
||||
session_id="00000000-0000-0000-0000-000000000002",
|
||||
tenant_id="imarketkorea",
|
||||
company_id="imarketkorea",
|
||||
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("imarketkorea")
|
||||
repo = ScriptRepository(cfg, _TENANTS_DIR)
|
||||
engine = ChatEngine(repo, rq_type="재협상")
|
||||
session = ChatSession(
|
||||
session_id="00000000-0000-0000-0000-000000000003",
|
||||
tenant_id="imarketkorea",
|
||||
company_id="imarketkorea",
|
||||
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
|
||||
async def test_priority_completes_without_wildcard(db_engine):
|
||||
reset_sessions()
|
||||
eng = await _reg().get_engine("imarketkorea")
|
||||
eng = await _reg().get_engine("ktcommerce")
|
||||
svc = ChatService()
|
||||
# 첫 제시가가 앵커가(9900) 이하 → 우선협상 → 바로 협상완료(카드/와일드카드 없이)
|
||||
out = await _run(svc, eng, [None, "확인", "예", "확인", "9800", "예",
|
||||
@ -262,7 +148,7 @@ async def test_tenant_brand_isolation(db_engine):
|
||||
@pytest.mark.asyncio
|
||||
async def test_advance_after_end_errors(db_engine):
|
||||
reset_sessions()
|
||||
eng = await _reg().get_engine("imarketkorea")
|
||||
eng = await _reg().get_engine("ktcommerce")
|
||||
svc = ChatService()
|
||||
out = await _run(svc, eng, [None, "확인", "예", "확인", "1000", "예",
|
||||
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."])
|
||||
@ -273,12 +159,12 @@ async def test_advance_after_end_errors(db_engine):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_http_chat_start(client):
|
||||
r = await client.post("/v1/chat", headers={"X-Tenant-ID": "imarketkorea"}, json={"rq_type": "재협상"})
|
||||
r = await client.post("/v1/chat", headers={"X-Tenant-ID": "ktcommerce"}, json={"rq_type": "재협상"})
|
||||
assert r.status_code == 200
|
||||
d = r.json()
|
||||
assert d["step"] == "서비스안내"
|
||||
assert d["input_options"] == ["확인"]
|
||||
assert "데모상사 B" in d["script"]
|
||||
assert "데모상사 A" in d["script"]
|
||||
# 헤더 없으면 400
|
||||
r2 = await client.post("/v1/chat", json={"rq_type": "재협상"})
|
||||
assert r2.status_code == 400
|
||||
|
||||
@ -25,7 +25,7 @@ def _eng():
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_persists_and_resumes_across_instances(db_engine):
|
||||
reg = _eng()
|
||||
eng = await reg.get_engine("imarketkorea")
|
||||
eng = await reg.get_engine("ktcommerce")
|
||||
|
||||
# 인스턴스 1: 협상 시작 + 몇 턴 진행 (컨텍스트는 DB 조회 — 행이 없으므로 기본값 폴백)
|
||||
svc1 = ChatService()
|
||||
@ -51,19 +51,19 @@ async def test_session_persists_and_resumes_across_instances(db_engine):
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_company_scoped(db_engine):
|
||||
reg = _eng()
|
||||
eng = await reg.get_engine("imarketkorea")
|
||||
eng = await reg.get_engine("ktcommerce")
|
||||
svc = ChatService()
|
||||
r = await svc.chat(eng, Req_Chat())
|
||||
sid = r.session_id
|
||||
|
||||
# 자사(imarketkorea)로는 조회됨
|
||||
# 자사(ktcommerce)로는 조회됨
|
||||
assert await ChatSessionRepository(eng.company_id).get(sid) is not None
|
||||
# 타테넌트 company_id 로는 조회 안 됨 (격리)
|
||||
assert await ChatSessionRepository("00000000-0000-0000-0000-0000000000aa").get(sid) is None
|
||||
# 타테넌트(imarketkorea) company_id 로는 조회 안 됨 (격리)
|
||||
assert await ChatSessionRepository("imarketkorea").get(sid) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_none_for_missing(db_engine):
|
||||
repo = ChatSessionRepository("imarketkorea")
|
||||
repo = ChatSessionRepository("ktcommerce")
|
||||
assert await repo.get(None) is None
|
||||
assert await repo.get("00000000-0000-0000-0000-000000000000") is None
|
||||
|
||||
@ -1,157 +0,0 @@
|
||||
"""Phase 2 표현층 검증 — ScriptNaturalizer (LLM 카드 멘트 자연화).
|
||||
|
||||
원칙 검증: LLM 은 말만 다듬고 숫자는 절대 만들지 않는다.
|
||||
① 치환자 보존 성공 경로 ② 치환자 누락/추가 → 폐기 ③ 새 숫자 → 폐기
|
||||
④ 타임아웃/예외 → 폐기(폴백) ⑤ 상황 라벨은 정성(수치 미노출)
|
||||
⑥ 챗 플로우: llm.enabled=True 면 카드 멘트가 자연화본으로, 실패 시 원본으로.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from negotiation.chat.service.script_naturalizer import ScriptNaturalizer, build_situation
|
||||
|
||||
_TEMPLATE = "제안해 주신 **{input_price}원**, 감사합니다. 한 번 더 검토해 가격을 제안해 주시겠어요?"
|
||||
|
||||
|
||||
def _fake(reply):
|
||||
"""llm_call 더블 — 고정 응답."""
|
||||
def call(messages):
|
||||
return {"script": reply}
|
||||
return call
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_naturalize_success_preserves_placeholders():
|
||||
nat = ScriptNaturalizer(llm_call=_fake(
|
||||
"긍정적으로 검토 중입니다. 다만 **{input_price}원**은 조정 여지가 있어 보입니다. 재제안 부탁드립니다."))
|
||||
out = await nat.naturalize(_TEMPLATE, situation={"라운드": "초반 조율"}, tone=2, strategy=1)
|
||||
assert out and "{input_price}" in out and out != _TEMPLATE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_naturalize_rejects_missing_placeholder():
|
||||
nat = ScriptNaturalizer(llm_call=_fake("가격 재검토 부탁드립니다.")) # 치환자 삭제됨
|
||||
assert await nat.naturalize(_TEMPLATE) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_naturalize_rejects_added_placeholder():
|
||||
nat = ScriptNaturalizer(llm_call=_fake("{input_price}원과 {secret_discount}까지 드리겠습니다."))
|
||||
assert await nat.naturalize(_TEMPLATE) is None # 원본에 없던 변수 환각
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_naturalize_rejects_new_digits():
|
||||
nat = ScriptNaturalizer(llm_call=_fake("{input_price}원에서 5% 더 인하해 주시면 즉시 계약하겠습니다."))
|
||||
assert await nat.naturalize(_TEMPLATE) is None # LLM 이 만든 숫자(5) 금지
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_naturalize_rejects_dropped_emphasis_markers():
|
||||
"""고객사가 지정한 볼드/색 마커를 LLM 이 떨어뜨리면 폐기 → 원본(스타일 보존) 폴백."""
|
||||
tmpl = "제안해 주신 **{input_price}원**, {{강조|재검토}} 부탁드립니다."
|
||||
# 볼드·색 마커를 모두 지운 재작성 → 검증 실패
|
||||
nat = ScriptNaturalizer(llm_call=_fake("제안해 주신 {input_price}원, 재검토 부탁드립니다."))
|
||||
assert await nat.naturalize(tmpl) is None
|
||||
# 마커를 그대로 유지한 재작성 → 통과
|
||||
nat = ScriptNaturalizer(llm_call=_fake("제시하신 **{input_price}원** 관련, {{강조|재검토}}를 요청드립니다."))
|
||||
out = await nat.naturalize(tmpl)
|
||||
assert out and out.count("**") == 2 and "{{강조|" in out
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_naturalize_timeout_falls_back():
|
||||
def slow(messages):
|
||||
import time
|
||||
time.sleep(0.5)
|
||||
return {"script": _TEMPLATE}
|
||||
nat = ScriptNaturalizer(llm_call=slow, timeout_seconds=0.05)
|
||||
assert await nat.naturalize(_TEMPLATE) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_naturalize_exception_falls_back():
|
||||
def boom(messages):
|
||||
raise RuntimeError("LLM down")
|
||||
nat = ScriptNaturalizer(llm_call=boom)
|
||||
assert await nat.naturalize(_TEMPLATE) is None
|
||||
|
||||
|
||||
def test_build_situation_is_qualitative_only():
|
||||
"""상황 라벨에 실제 수치가 노출되지 않는다(숫자 환각 차단의 전제)."""
|
||||
ctx = {"round": 2, "input_price": 10200, "anchor_price": 9900, "target_price": 10000, "item_price": 11000}
|
||||
s = build_situation(ctx)
|
||||
assert s["라운드"] == "초반 조율"
|
||||
assert s["가격구간"] == "목표 상회(추가 인하 필요)"
|
||||
joined = str(s)
|
||||
for n in ("10200", "9900", "10000", "11000"):
|
||||
assert n not in joined # 수치 미노출
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_flow_uses_naturalized_script_when_llm_enabled(db_engine):
|
||||
"""llm.enabled=True + 자격증명 존재 시 가격협상 카드 멘트가 자연화본(치환 완료)으로 나온다."""
|
||||
from router.v1.chat.protocol import Req_Chat
|
||||
from services.chat_service import ChatService, reset_sessions
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tenancy.registry import TenantEngineRegistry
|
||||
|
||||
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||
reset_sessions()
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine("imarketkorea")
|
||||
eng.config.llm.enabled = True # 테넌트 게이트 on
|
||||
|
||||
svc = ChatService()
|
||||
svc._naturalizer = ScriptNaturalizer(llm_call=_fake(
|
||||
"【자연화】 제시해 주신 **{input_price}원** 잘 검토했습니다. 초반 조율 단계이니 한 걸음 더 부탁드립니다."))
|
||||
# 자격증명 게이트 우회(테스트 환경에 키가 없어도 동작 검증)
|
||||
orig_available = ScriptNaturalizer.available
|
||||
ScriptNaturalizer.available = staticmethod(lambda: True)
|
||||
try:
|
||||
sid = None
|
||||
for ui in [None, "확인", "예", "확인", "11000", "예"]:
|
||||
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input=ui))
|
||||
sid = r.session_id
|
||||
assert r.step == "가격협상" and r.card_id
|
||||
assert r.script.startswith("【자연화】") # LLM 재작성본 사용
|
||||
assert "11000" in r.script # 치환은 엔진이 수행(숫자 정확)
|
||||
assert "{input_price}" not in r.script # 치환 완료
|
||||
finally:
|
||||
ScriptNaturalizer.available = orig_available
|
||||
eng.config.llm.enabled = False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_flow_falls_back_to_template_on_llm_failure(db_engine):
|
||||
"""LLM 실패 시 카드 원본 멘트로 폴백 — 협상은 절대 멈추지 않는다."""
|
||||
from router.v1.chat.protocol import Req_Chat
|
||||
from services.chat_service import ChatService, reset_sessions
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tenancy.registry import TenantEngineRegistry
|
||||
|
||||
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||
reset_sessions()
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine("imarketkorea")
|
||||
eng.config.llm.enabled = True
|
||||
|
||||
def boom(messages):
|
||||
raise RuntimeError("LLM down")
|
||||
svc = ChatService()
|
||||
svc._naturalizer = ScriptNaturalizer(llm_call=boom)
|
||||
orig_available = ScriptNaturalizer.available
|
||||
ScriptNaturalizer.available = staticmethod(lambda: True)
|
||||
try:
|
||||
sid = None
|
||||
for ui in [None, "확인", "예", "확인", "11000", "예"]:
|
||||
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input=ui))
|
||||
sid = r.session_id
|
||||
assert r.step == "가격협상" and r.card_id
|
||||
assert r.script and "11000" in r.script # 원본 템플릿 + 치환으로 정상 응답
|
||||
finally:
|
||||
ScriptNaturalizer.available = orig_available
|
||||
eng.config.llm.enabled = False
|
||||
@ -20,7 +20,7 @@ _TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__fi
|
||||
_FORBIDDEN = re.compile(r"kt\s*commerce|케이티|커머스|nego-?wiz", re.IGNORECASE)
|
||||
|
||||
|
||||
def _repo(tenant_id="imarketkorea"):
|
||||
def _repo(tenant_id="ktcommerce"):
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load(tenant_id)
|
||||
return ScriptRepository(cfg, _TENANTS_DIR)
|
||||
|
||||
@ -42,10 +42,7 @@ def test_requote_structure_preserved():
|
||||
for key in ["서비스안내", "가격제안", "배송형태선택", "가격협상_확인", "결과안내", "결과제출", "협상종료"]:
|
||||
assert key in s
|
||||
assert s["배송형태선택"]["next_input_mode"] == "delivery_type"
|
||||
# 리소스 원본은 회사 용어 토큰({label_*}) — 렌더 시 회사 라벨(없으면 기본값)로 치환된다.
|
||||
assert s["배송형태선택"]["input_options"] == [
|
||||
"{label_delivery_type_1}", "{label_delivery_type_2}", "{label_delivery_type_3}",
|
||||
]
|
||||
assert s["배송형태선택"]["input_options"] == ["협력사배송", "지정택배배송", "픽업배송"]
|
||||
|
||||
|
||||
def test_wildcard_present_and_merged():
|
||||
@ -68,9 +65,11 @@ def test_cleanroom_no_proprietary_brand_in_any_resource():
|
||||
|
||||
|
||||
def test_brand_substitution_per_tenant():
|
||||
kt = _repo("ktcommerce").get_step("서비스안내", "재협상")
|
||||
im = _repo("imarketkorea").get_step("서비스안내", "재협상")
|
||||
assert "데모상사 B" in im["script"] and "Negosium" in im["script"]
|
||||
assert "{company_name}" not in im["script"] # 치환 완료
|
||||
assert "데모상사 A" in kt["script"] and "Negosium" in kt["script"]
|
||||
assert "데모상사 B" in im["script"]
|
||||
assert "{company_name}" not in kt["script"] # 치환 완료
|
||||
|
||||
|
||||
def test_variable_substitution_and_missing_kept():
|
||||
@ -104,16 +103,12 @@ async def test_resolve_card_script_file_mode_default():
|
||||
repo = _repo()
|
||||
assert repo._config.cards.source_type == "file"
|
||||
# action 0 파일 멘트가 변수 치환되어 나온다 (DB 무접근)
|
||||
out = await repo.resolve_card_script(0, "NGC-B001", {"input_price": 9800})
|
||||
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800})
|
||||
assert out and "9800" in out
|
||||
|
||||
|
||||
from negotiation.cards.ports.card_script_port import ICardScriptRepository
|
||||
|
||||
|
||||
class _FakeCardRepo(ICardScriptRepository):
|
||||
"""ICardScriptRepository 더블 — DB 없이 카드코드→멘트 매핑만 흉내(세션 인자 무시).
|
||||
포트 상속으로 get_card_by_number 기본 구현(메타 None)을 물려받는다."""
|
||||
class _FakeCardRepo:
|
||||
"""ICardScriptRepository 더블 — DB 없이 카드코드→멘트 매핑만 흉내(세션 인자 무시)."""
|
||||
|
||||
def __init__(self, by_number: dict):
|
||||
self._by = by_number
|
||||
@ -126,9 +121,9 @@ class _FakeCardRepo(ICardScriptRepository):
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_card_script_db_mode_prefers_db(monkeypatch):
|
||||
"""source_type='backoffice_db': card.nego_cards.script(정본)를 파일보다 우선 사용 + 마커 보존."""
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce")
|
||||
cfg.cards.source_type = "backoffice_db"
|
||||
fake = _FakeCardRepo({"NGC-B001": "DB 편집 멘트 **{input_price}원** 검토 중입니다."})
|
||||
fake = _FakeCardRepo({"NGC-A001": "DB 편집 멘트 **{input_price}원** 검토 중입니다."})
|
||||
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
|
||||
|
||||
# execute_lambda 를 세션 없이 콜백만 실행하도록 대체(순수 단위검증)
|
||||
@ -137,14 +132,14 @@ async def test_resolve_card_script_db_mode_prefers_db(monkeypatch):
|
||||
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(0, "NGC-B001", {"input_price": 9800})
|
||||
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800})
|
||||
assert out == "DB 편집 멘트 **9800원** 검토 중입니다." # DB 우선 + 마커(**) 불투명 보존 + 변수 치환
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_card_script_db_mode_falls_back_to_file(monkeypatch):
|
||||
"""DB 에 해당 카드 멘트가 없으면 파일(scripts_cards.json)로 폴백."""
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce")
|
||||
cfg.cards.source_type = "backoffice_db"
|
||||
fake = _FakeCardRepo({}) # DB 미보유
|
||||
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
|
||||
@ -154,43 +149,5 @@ async def test_resolve_card_script_db_mode_falls_back_to_file(monkeypatch):
|
||||
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(0, "NGC-B001", {"input_price": 9800})
|
||||
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800})
|
||||
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("imarketkorea")
|
||||
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원**"
|
||||
|
||||
|
||||
def test_option_label_tokens_rendered():
|
||||
"""검증: 옵션에 회사 용어 토큰({label_delivery_type_*})이 있는 스텝을 정상 렌더·에러 재렌더로 출력.
|
||||
기대결과: 두 경로 모두 버튼 문자열이 기본 라벨(협력사배송 등)로 치환되고 토큰이 남지 않는다."""
|
||||
import os
|
||||
|
||||
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
|
||||
tenants = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||
cfg = TenantConfigLoader(tenants_dir=tenants, cache_ttl_seconds=0).load("_base")
|
||||
engine = ChatEngine(ScriptRepository(cfg, tenants), rq_type="재견적")
|
||||
session = ChatSession(session_id="s", tenant_id="_base", company_id="_base")
|
||||
|
||||
view = engine.render_step(session, "배송형태선택")
|
||||
assert view.input_options == ["협력사배송", "지정택배배송", "픽업배송"]
|
||||
|
||||
# 에러 재렌더(잘못된 입력 등)도 같은 치환을 타야 한다 — raw 옵션이면 토큰이 버튼에 노출된다.
|
||||
err_view = engine._error(session, "다시 선택해 주세요.")
|
||||
assert err_view.input_options == ["협력사배송", "지정택배배송", "픽업배송"]
|
||||
|
||||
@ -9,9 +9,9 @@
|
||||
|
||||
실행:
|
||||
cd agent
|
||||
APP_ENV=local python -m tools.console_demo --tenant imarketkorea # 기본 시나리오
|
||||
APP_ENV=local python -m tools.console_demo --tenant ktcommerce # 기본 시나리오
|
||||
APP_ENV=local python -m tools.console_demo --tenant imarketkorea --no-db # DB 로깅 없이
|
||||
APP_ENV=local python -m tools.console_demo --tenant imarketkorea --interactive
|
||||
APP_ENV=local python -m tools.console_demo --tenant ktcommerce --interactive
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@ -74,7 +74,7 @@ def _scenario():
|
||||
async def run(tenant_id: str, use_db: bool, interactive: bool):
|
||||
loader = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0)
|
||||
if not loader.is_registered(tenant_id):
|
||||
print(f"[!] 미등록 테넌트: {tenant_id}. 등록된 테넌트: imarketkorea, _base")
|
||||
print(f"[!] 미등록 테넌트: {tenant_id}. 등록된 테넌트: ktcommerce, imarketkorea, _base")
|
||||
return
|
||||
registry = TenantEngineRegistry(loader=loader)
|
||||
engine = await registry.get_engine(tenant_id)
|
||||
@ -172,7 +172,7 @@ def _interactive_turns():
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="협상 의사결정 루프 콘솔 데모 (P0~P4)")
|
||||
ap.add_argument("--tenant", default="imarketkorea", help="테넌트 id (imarketkorea|_base)")
|
||||
ap.add_argument("--tenant", default="ktcommerce", help="테넌트 id (ktcommerce|imarketkorea)")
|
||||
ap.add_argument("--no-db", action="store_true", help="DB 로깅 비활성화")
|
||||
ap.add_argument("--interactive", action="store_true", help="턴마다 직접 입력")
|
||||
args = ap.parse_args()
|
||||
|
||||
@ -1,65 +0,0 @@
|
||||
"""로컬 학습 리셋 — 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()
|
||||
@ -58,21 +58,6 @@ class suppliers(MAIN_BASE):
|
||||
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
|
||||
|
||||
|
||||
class companies(MAIN_BASE):
|
||||
# company.companies (고객사). 공급사 포털 브랜딩(settings.branding) 조회 전용 미러.
|
||||
@staticmethod
|
||||
def DBType():
|
||||
return DBType.PARTNER.value
|
||||
|
||||
__tablename__ = "companies"
|
||||
__table_args__ = {"schema": "company"}
|
||||
|
||||
company_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")) # 회사 식별자(PK)
|
||||
name = Column(String(100), nullable=False) # 회사명
|
||||
settings = Column(JSONB, nullable=True) # 회사별 커스터마이징(branding/labels 등, negodata 소유)
|
||||
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
|
||||
|
||||
|
||||
class items(MAIN_BASE):
|
||||
# partner.items (상품).
|
||||
@staticmethod
|
||||
@ -138,7 +123,6 @@ class sessions(MAIN_BASE):
|
||||
reject_reason = Column(String(255), nullable=True) # 거절 사유
|
||||
reject_price = Column(BigInteger, nullable=True) # 거절 시 제시가(원)
|
||||
reject_delivery_type = Column(SmallInteger, nullable=True) # 거절 시 배송 유형 (코드)
|
||||
custom = Column(JSONB, nullable=True) # 협상완료 부가정보 값 {key: value} (정의는 companies.settings.session_fields)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')"), onupdate=text("(now() AT TIME ZONE 'utc')")) # 수정 시각(UTC, UPDATE 시 자동 갱신)
|
||||
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
|
||||
@ -169,11 +153,11 @@ class quotations(MAIN_BASE):
|
||||
manager_contact_number = Column(String(20), nullable=True) # 담당자 연락처
|
||||
memo = Column(String(100), nullable=True) # 메모
|
||||
md_price = Column(BigInteger, nullable=True)
|
||||
supplier_type = Column(SmallInteger, nullable=True)
|
||||
iteration = Column(Integer, nullable=False, server_default=text("0")) # 반복 횟수
|
||||
preferred_sp_yn = Column(Boolean, nullable=True) # 선호 공급사 지정 여부
|
||||
preferred_sp_id = Column(UUID(as_uuid=True), nullable=True) # 선호 공급사(partner.suppliers.supplier_id)
|
||||
preferred_sp_name = Column(String(20), nullable=True) # 선호 공급사명(스냅샷)
|
||||
close_reason = Column(SmallInteger, nullable=True) # 마감 사유(CloseReason). 재협상 요청 자격 판정에 읽는다
|
||||
equal_bid_yn = Column(Boolean, nullable=True) # 동일가 입찰 발생 여부
|
||||
equal_bid_data = Column(JSONB, nullable=True) # 동일가 입찰 상세(JSON)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC)
|
||||
@ -181,28 +165,6 @@ class quotations(MAIN_BASE):
|
||||
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
|
||||
|
||||
|
||||
class notifications(MAIN_BASE):
|
||||
# company.notifications (담당자 인박스). 포털은 재협상 요청 알림을 만들기 위해서만 쓴다(조회는 negodata).
|
||||
# company 스키마 전용 DBType 이 없어 USER 커넥션을 재사용한다(물리 DB 동일).
|
||||
@staticmethod
|
||||
def DBType():
|
||||
return DBType.USER.value
|
||||
|
||||
__tablename__ = "notifications"
|
||||
__table_args__ = {"schema": "company"}
|
||||
|
||||
notification_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
|
||||
user_id = Column(UUID(as_uuid=True), nullable=False) # 수신자(company.users.user_id) = 견적 작성자
|
||||
type = Column(SmallInteger, nullable=False) # NotificationType
|
||||
ref_qt_id = Column(UUID(as_uuid=True), nullable=True)
|
||||
ref_session_id = Column(UUID(as_uuid=True), nullable=True)
|
||||
data = Column(JSONB, nullable=True) # 렌더 스냅샷(공급사명·사유·희망가 등)
|
||||
read_at = Column(DateTime(timezone=True), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')"))
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')"), onupdate=text("(now() AT TIME ZONE 'utc')"))
|
||||
deleted = Column(Boolean, nullable=False, server_default=text("false"))
|
||||
|
||||
|
||||
class quotation_settings(MAIN_BASE):
|
||||
# quotation.quotation_settings (견적 설정). 견적 설정 스냅샷 — anchoring_value 는 구(舊) 앵커 산출용으로 채팅 경로에서는 더 이상 사용하지 않음(앵커는 sessions.anchoring_price 박제값).
|
||||
@staticmethod
|
||||
@ -222,34 +184,6 @@ class quotation_settings(MAIN_BASE):
|
||||
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
|
||||
|
||||
|
||||
class nego_cards(MAIN_BASE):
|
||||
# card.nego_cards (협상카드). backend 는 번호→UUID 변환(chats.card_id 저장)만 위해 최소 컬럼 미러.
|
||||
@staticmethod
|
||||
def DBType():
|
||||
return DBType.NEGOTIATION.value # 같은 negosium_db — chats 와 동일 세션풀로 조회
|
||||
|
||||
__tablename__ = "nego_cards"
|
||||
__table_args__ = {"schema": "card"}
|
||||
|
||||
nego_card_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
|
||||
number = Column(String(10), nullable=True) # 카드 번호(agent turn.card_id 와 매칭)
|
||||
deleted = Column(Boolean, nullable=False, server_default=text("false"))
|
||||
|
||||
|
||||
class wild_cards(MAIN_BASE):
|
||||
# card.wild_cards (와일드카드). backend 는 번호→UUID 변환(chats.card_id 저장)만 위해 최소 컬럼 미러.
|
||||
@staticmethod
|
||||
def DBType():
|
||||
return DBType.NEGOTIATION.value # 같은 negosium_db
|
||||
|
||||
__tablename__ = "wild_cards"
|
||||
__table_args__ = {"schema": "card"}
|
||||
|
||||
wild_card_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
|
||||
number = Column(String(10), nullable=True)
|
||||
deleted = Column(Boolean, nullable=False, server_default=text("false"))
|
||||
|
||||
|
||||
class chats(MAIN_BASE):
|
||||
# negotiation.chats (협상 채팅 메시지 로그). session 1 : N chats. (session_id, seq) 유니크.
|
||||
@staticmethod
|
||||
|
||||
@ -130,41 +130,6 @@ class QuotationStatus(Enum):
|
||||
CLOSED = 3 # 견적마감
|
||||
|
||||
|
||||
class CloseReason(Enum):
|
||||
"""견적 마감 사유. quotation.quotations.close_reason
|
||||
낙찰(AWARDED) 외 OPEN_* 는 낙찰자 미정으로 마감된 '결렬' 건 — 공급사 재협상 요청 대상."""
|
||||
|
||||
AWARDED = 1 # 낙찰
|
||||
OPEN_PRICE = 5 # 개찰: 낙찰 기준 미달
|
||||
OPEN_EQUAL = 6 # 개찰: 동가
|
||||
OPEN_NOSHOW = 7 # 개찰: 전원 미응찰
|
||||
OPEN_REJECT = 8 # 개찰: 협상거부 존재
|
||||
|
||||
|
||||
# 재협상 요청 가능한 마감 사유(낙찰 건은 제외).
|
||||
RENEGOTIABLE_CLOSE_REASONS = (
|
||||
CloseReason.OPEN_PRICE.value,
|
||||
CloseReason.OPEN_EQUAL.value,
|
||||
CloseReason.OPEN_NOSHOW.value,
|
||||
CloseReason.OPEN_REJECT.value,
|
||||
)
|
||||
|
||||
|
||||
class RenegotiationStatus(Enum):
|
||||
"""sessions.custom.renegotiation.status — 공급사 재협상 요청 상태(IMK #15)."""
|
||||
|
||||
PENDING = 1 # 접수, 담당자 심사 대기
|
||||
APPROVED = 2 # 승인 — 다음 라운드 생성됨
|
||||
REJECTED = 3 # 반려
|
||||
CANCELED = 4 # 공급사 철회
|
||||
|
||||
|
||||
class NotificationType(Enum):
|
||||
"""company.notifications.type — negodata 담당자 인박스. 포털에서 만드는 건 재협상 요청뿐."""
|
||||
|
||||
RENEGO_REQUESTED = 5
|
||||
|
||||
|
||||
class ChatSender(Enum):
|
||||
"""채팅 발신자 코드. negotiation.chats.sender """
|
||||
|
||||
|
||||
@ -6,7 +6,7 @@ from sqlalchemy import asc, desc, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import chats, items, sessions, nego_cards, wild_cards
|
||||
from common.database.model.models import chats, items, sessions
|
||||
from common.enums import ErrorType, SessionStatus
|
||||
from common.logger import LOG
|
||||
|
||||
@ -47,14 +47,6 @@ class IChatCRUD(ABC):
|
||||
async def update_last_offer_price(self, cdb: AsyncSession, session_id, price: int) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_nego_card_id_by_number(self, cdb: AsyncSession, number: str):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_wild_card_id_by_number(self, cdb: AsyncSession, number: str):
|
||||
pass
|
||||
|
||||
|
||||
class ChatCRUD(IChatCRUD):
|
||||
async def list_by_session(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, list]:
|
||||
@ -120,30 +112,6 @@ class ChatCRUD(IChatCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def get_nego_card_id_by_number(self, cdb: AsyncSession, number: str):
|
||||
# 협상카드 번호(agent turn.card_id) → nego_card_id(UUID). 없으면 None. 카드 사용 로그(chats.card_id) 저장용.
|
||||
try:
|
||||
query = select(nego_cards.nego_card_id).where(nego_cards.number == number, nego_cards.deleted == False).limit(1) # noqa: E712
|
||||
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_nego_card_id_by_number({number}) failed.")
|
||||
if err_type != ErrorType.SUCCESS or not row_list:
|
||||
return None
|
||||
return row_list[0]
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return None
|
||||
|
||||
async def get_wild_card_id_by_number(self, cdb: AsyncSession, number: str):
|
||||
# 와일드카드 번호(agent turn.card_id, wild_card_dynamic) → wild_card_id(UUID). 없으면 None.
|
||||
try:
|
||||
query = select(wild_cards.wild_card_id).where(wild_cards.number == number, wild_cards.deleted == False).limit(1) # noqa: E712
|
||||
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_wild_card_id_by_number({number}) failed.")
|
||||
if err_type != ErrorType.SUCCESS or not row_list:
|
||||
return None
|
||||
return row_list[0]
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return None
|
||||
|
||||
async def finalize_session(
|
||||
self, cdb: AsyncSession, session_id, status: int,
|
||||
bid_price: Optional[int] = None, reject_reason: Optional[str] = None, reject_price: Optional[int] = None,
|
||||
|
||||
@ -1,40 +1,24 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Optional, Tuple
|
||||
from typing import Tuple
|
||||
|
||||
from sqlalchemy import and_, case, cast, func, nulls_last, or_, select, text, update
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy import asc, desc, func, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import chats, items, quotations, sessions
|
||||
from common.enums import CloseReason, ErrorType, QuotationStatus, RENEGOTIABLE_CLOSE_REASONS, SessionStatus
|
||||
from common.database.model.models import items, quotations, sessions
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
|
||||
|
||||
# 협상 세션 CRUD. 목록은 세션(negotiation) ⨝ 상품(partner) ⨝ 견적(quotation) 조인으로 만든다.
|
||||
# 마감일(qt_end_time)은 견적(quotation.end_time)이 진실값이다(session.end_time 은 협상 종료 시점 기록용).
|
||||
|
||||
|
||||
def _effective_status():
|
||||
"""표시용 세션 상태. 견적이 마감됐거나 마감시간이 지났으면 협상생성(1)은 더 참여할 수 없으므로 미참여(4)로 본다.
|
||||
|
||||
참여/채팅진입이 진입 시점에 하는 전이(negotiation_service._load_actionable_session, chat_service.init)와 같은 규칙을
|
||||
목록에서는 쓰기 없이 파생으로만 맞춘다. 마감 일괄정리 이후에 만들어진 세션도 '협상 대기'로 남지 않는다.
|
||||
"""
|
||||
ended = or_(quotations.status == QuotationStatus.CLOSED.value, quotations.end_time < func.now())
|
||||
return case(
|
||||
(and_(sessions.status == SessionStatus.CREATED.value, ended), SessionStatus.NOT_PARTICIPATED.value),
|
||||
else_=sessions.status,
|
||||
)
|
||||
|
||||
|
||||
class ISessionCRUD(ABC):
|
||||
@abstractmethod
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, keyword=None, result=None) -> Tuple[ErrorType, int]:
|
||||
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type) -> Tuple[ErrorType, int]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@ -54,80 +38,28 @@ class ISessionCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def update_session_reject(
|
||||
self, cdb: AsyncSession, session_id, status: int, reject_reason: str, reject_price: Optional[int] = None,
|
||||
) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def update_session_custom(self, cdb: AsyncSession, session_id, supplier_id, custom: dict) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def merge_session_custom(self, cdb: AsyncSession, session_id, supplier_id, patch: dict) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
|
||||
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
|
||||
pass
|
||||
|
||||
|
||||
class SessionCRUD(ISessionCRUD):
|
||||
@staticmethod
|
||||
def __filters(supplier_id, status, qt_type, keyword=None, result=None):
|
||||
def __filters(supplier_id, status, qt_type):
|
||||
conds = [sessions.supplier_id == supplier_id, sessions.deleted == False] # noqa: E712
|
||||
if status is not None:
|
||||
# 표시 상태로 필터 — 탭/KPI 카운트가 목록 배지와 어긋나지 않게 파생값을 그대로 쓴다.
|
||||
conds.append(_effective_status() == status)
|
||||
conds.append(sessions.status == status)
|
||||
if qt_type is not None:
|
||||
conds.append(sessions.qt_type == qt_type)
|
||||
# 검색: 견적번호·상품명·상품코드 부분일치(대소문자 무시). items 는 목록/카운트 둘 다 조인돼 있다.
|
||||
# ILIKE 와일드카드(%,_)는 escape 해 사용자 입력이 패턴으로 새지 않게 한다.
|
||||
if keyword and keyword.strip():
|
||||
kw = keyword.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
like = f"%{kw}%"
|
||||
conds.append(or_(sessions.qt_number.ilike(like), items.name.ilike(like), items.code.ilike(like)))
|
||||
# 결과(SessionResult) 필터 — _to_result 파생 규칙을 SQL WHERE 로 그대로 복제(집계·필터 일치용).
|
||||
# 1=낙찰 2=미낙찰 3=결렬(개찰). 전부 견적 마감(CLOSED) 이 전제.
|
||||
if result in (1, 2, 3):
|
||||
conds.append(quotations.status == QuotationStatus.CLOSED.value)
|
||||
if result == 1:
|
||||
conds.append(quotations.close_reason == CloseReason.AWARDED.value)
|
||||
conds.append(quotations.preferred_sp_id == sessions.supplier_id)
|
||||
elif result == 2:
|
||||
conds.append(quotations.close_reason == CloseReason.AWARDED.value)
|
||||
conds.append(or_(quotations.preferred_sp_id.is_(None), quotations.preferred_sp_id != sessions.supplier_id))
|
||||
else:
|
||||
conds.append(quotations.close_reason.in_(RENEGOTIABLE_CLOSE_REASONS))
|
||||
return conds
|
||||
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]:
|
||||
try:
|
||||
conds = self.__filters(supplier_id, status, qt_type, keyword, result)
|
||||
|
||||
# 정렬 규칙:
|
||||
# - 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 = _effective_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())
|
||||
|
||||
conds = self.__filters(supplier_id, status, qt_type)
|
||||
order_col = desc(quotations.end_time) if order == "desc" else asc(quotations.end_time)
|
||||
query = (
|
||||
select(
|
||||
sessions.session_id,
|
||||
_effective_status(), # 마감 후 남은 협상생성은 미참여로 내린다
|
||||
sessions.status,
|
||||
sessions.qt_type,
|
||||
sessions.qt_number,
|
||||
quotations.end_time, # qt_end_time = 견적 마감 시각
|
||||
@ -135,22 +67,11 @@ class SessionCRUD(ISessionCRUD):
|
||||
items.name,
|
||||
items.model_name,
|
||||
items.manufacturer,
|
||||
sessions.custom,
|
||||
quotations.status, # 재협상 요청 자격 판정용(마감 여부)
|
||||
quotations.close_reason, # 개찰(결렬) 사유
|
||||
quotations.round,
|
||||
quotations.preferred_sp_id, # 낙찰자(공급사) — 나와 같으면 낙찰, 다르면 미낙찰
|
||||
sessions.supplier_id, # 이 세션 소유 공급사(=조회자). 낙찰자와 대조
|
||||
# 대화 이력 유무 — 종료된 협상의 '결과 보기'(열람) 버튼을 띄울지 판단용. 열 게 없으면 프론트가 감춘다.
|
||||
select(1).where(chats.session_id == sessions.session_id, chats.deleted == False).exists(), # noqa: E712
|
||||
# 거부 건이 제출한 사유·희망가 — 목록의 '거부 내역' 열람용(의견은 custom.opinion).
|
||||
sessions.reject_reason,
|
||||
sessions.reject_price,
|
||||
)
|
||||
.join(items, items.item_id == sessions.item_id)
|
||||
.join(quotations, quotations.qt_id == sessions.quotation_id)
|
||||
.where(*conds, items.deleted == False, quotations.deleted == False) # noqa: E712
|
||||
.order_by(*order_cols)
|
||||
.order_by(order_col)
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
)
|
||||
@ -162,9 +83,9 @@ class SessionCRUD(ISessionCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, []
|
||||
|
||||
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, keyword=None, result=None) -> Tuple[ErrorType, int]:
|
||||
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type) -> Tuple[ErrorType, int]:
|
||||
try:
|
||||
conds = self.__filters(supplier_id, status, qt_type, keyword, result)
|
||||
conds = self.__filters(supplier_id, status, qt_type)
|
||||
query = (
|
||||
select(func.count())
|
||||
.select_from(sessions)
|
||||
@ -222,58 +143,12 @@ class SessionCRUD(ISessionCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def update_session_reject(
|
||||
self, cdb: AsyncSession, session_id, status: int, reject_reason: str, reject_price: Optional[int] = None,
|
||||
) -> ErrorType:
|
||||
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
|
||||
try:
|
||||
values = {"status": status, "reject_reason": reject_reason}
|
||||
# 공급 희망 가격은 선택 입력이라 안 들어올 수 있다 — 그때는 컬럼을 건드리지 않는다.
|
||||
if reject_price is not None:
|
||||
values["reject_price"] = reject_price
|
||||
query = (
|
||||
update(sessions)
|
||||
.where(sessions.session_id == session_id)
|
||||
.values(**values)
|
||||
)
|
||||
return await DB_SESSION_MNG.add(cdb, query)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
|
||||
# 같은 견적번호(체인)의 최대 차수. 이미 다음 라운드가 있으면 재협상 요청은 의미가 없다.
|
||||
try:
|
||||
query = select(func.max(quotations.round)).where(quotations.number == number, quotations.deleted == False) # noqa: E712
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, 0
|
||||
# 단일 컬럼 select 는 scalars() 로 내려와 rows 가 값 리스트다(행 튜플이 아님).
|
||||
top = rows[0] if rows else None
|
||||
return ErrorType.SUCCESS, int(top or 0)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def merge_session_custom(self, cdb: AsyncSession, session_id, supplier_id, patch: dict) -> ErrorType:
|
||||
# sessions.custom 부분 갱신(기존 키 보존). 부가정보와 재협상 요청이 같은 컬럼을 쓰므로 덮어쓰면 안 된다.
|
||||
try:
|
||||
query = (
|
||||
update(sessions)
|
||||
.where(sessions.session_id == session_id, sessions.supplier_id == supplier_id)
|
||||
.values(custom=func.coalesce(sessions.custom, cast(text("'{}'"), JSONB)).op("||")(cast(patch, JSONB)))
|
||||
)
|
||||
return await DB_SESSION_MNG.add(cdb, query)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def update_session_custom(self, cdb: AsyncSession, session_id, supplier_id, custom: dict) -> ErrorType:
|
||||
# 협상완료 부가정보(sessions.custom) 저장. 본인 공급사 세션만(supplier_id 가드).
|
||||
try:
|
||||
query = (
|
||||
update(sessions)
|
||||
.where(sessions.session_id == session_id, sessions.supplier_id == supplier_id)
|
||||
.values(custom=custom)
|
||||
.values(status=status, reject_reason=reject_reason)
|
||||
)
|
||||
return await DB_SESSION_MNG.add(cdb, query)
|
||||
except Exception as ex:
|
||||
|
||||
@ -5,7 +5,7 @@ from sqlalchemy import delete, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import supplier_user_tokens, supplier_users, suppliers, companies, sessions
|
||||
from common.database.model.models import supplier_user_tokens, supplier_users, suppliers
|
||||
from common.enums import ErrorType, TokenType
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
@ -28,14 +28,6 @@ class IUserCRUD(ABC):
|
||||
async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, str]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_company_settings(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, dict]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_branding_by_session(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, dict]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType:
|
||||
pass
|
||||
@ -125,43 +117,6 @@ class UserCRUD(IUserCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def get_company_settings(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, dict]:
|
||||
"""공급사 소속 회사 설정(companies.settings) 전체. 브랜딩·협상완료 필드 등이 들어있다. 미설정이면 빈 dict."""
|
||||
try:
|
||||
query = (
|
||||
select(companies.settings)
|
||||
.join(suppliers, suppliers.company_id == companies.company_id)
|
||||
.where(suppliers.supplier_id == supplier_id, suppliers.deleted == False, companies.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_company_settings(supplier_id:{supplier_id}) failed.")
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, {}
|
||||
settings = row_list[0] if row_list else None
|
||||
return ErrorType.SUCCESS, settings or {}
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, {}
|
||||
|
||||
async def get_branding_by_session(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, dict]:
|
||||
"""세션이 속한 회사의 브랜딩(companies.settings.branding). 로그인 전 화면이 쓰므로 branding 만 꺼낸다."""
|
||||
try:
|
||||
query = (
|
||||
select(companies.settings)
|
||||
.join(suppliers, suppliers.company_id == companies.company_id)
|
||||
.join(sessions, sessions.supplier_id == suppliers.supplier_id)
|
||||
.where(sessions.session_id == session_id, sessions.deleted == False, companies.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_branding_by_session(session_id:{session_id}) failed.")
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, {}
|
||||
settings = (row_list[0] if row_list else None) or {}
|
||||
return ErrorType.SUCCESS, settings.get("branding") or {}
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, {}
|
||||
|
||||
async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType:
|
||||
try:
|
||||
query = (
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, Depends, Path, Request
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
|
||||
from common.models.gmodel import UserInfo
|
||||
@ -20,7 +20,6 @@ from .protocol import (
|
||||
Res_Me,
|
||||
Res_PopupStatus,
|
||||
Res_RefreshToken,
|
||||
Res_SessionBranding,
|
||||
)
|
||||
|
||||
# 라우터(MVC 의 컨트롤러). 요청 검증 -> service 호출 -> RemoveNoneResponse 반환만 담당.
|
||||
@ -107,16 +106,3 @@ async def hide_popup(
|
||||
service: AuthService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.hide_popup(user_info, credentials.credentials, req.popup_type))
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/session-branding/{session_id}",
|
||||
response_model=Res_SessionBranding,
|
||||
summary="세션 브랜딩(무인증)",
|
||||
description="초청 링크로 진입한 로그인 전 화면에서 회사 서비스명·로고·색상만 조회한다. 인증 없이 열려 있으므로 브랜딩 외 정보는 내리지 않는다.",
|
||||
)
|
||||
async def session_branding(
|
||||
session_id: str = Path(..., description="협상 세션 uuid (초청 링크의 session_id)"),
|
||||
service: AuthService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.session_branding(session_id))
|
||||
|
||||
@ -48,9 +48,6 @@ class Res_Me(Res_WebPacketProtocol):
|
||||
supplier_id: str = Field("", description="소속 공급사 uuid")
|
||||
supplier_name: str = Field("", description="공급사명")
|
||||
role: int = Field(0, description="권한 코드 1=user, 2=manager (UserRole)")
|
||||
branding: dict = Field(default_factory=dict, description="소속 회사 브랜딩(companies.settings.branding). 서비스명/로고/색")
|
||||
session_fields: list = Field(default_factory=list, description="협상완료 부가정보 필드 정의(companies.settings.session_fields). 공급사가 타결 후 입력")
|
||||
guide_notices: list = Field(default_factory=list, description="협상 유의사항 항목(companies.settings.guide_notices). 빈 값이면 포털 기본 문구")
|
||||
|
||||
|
||||
class Res_Logout(Res_WebPacketProtocol):
|
||||
@ -67,9 +64,3 @@ class Req_HidePopup(AuthProtocol):
|
||||
|
||||
class Res_HidePopup(Res_WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class Res_SessionBranding(Res_WebPacketProtocol):
|
||||
service_name: str = Field("", description="회사 서비스명(companies.settings.branding.service_name). 미설정 시 빈 값")
|
||||
logo_url: str = Field("", description="회사 로고 URL")
|
||||
helpdesk: list = Field(default_factory=list, description="헬프데스크 연락처 줄 목록(companies.settings.branding.helpdesk). 한 줄 = 담당자 한 명")
|
||||
|
||||
@ -63,7 +63,6 @@ class Res_ChatInit(Res_WebPacketProtocol):
|
||||
session_id: str = Field("", description="협상 세션 uuid")
|
||||
session_status: int = Field(0, description="세션 상태 코드 (SessionStatus: 1=생성 2=진행중 3=완료 4=미참여 5=거부)")
|
||||
quotation_id: str = Field("", description="소속 견적 uuid")
|
||||
qt_number: str = Field("", description="견적번호(EST-...)")
|
||||
quotation_end_time: str = Field("", description="견적 마감 시각 (ISO 8601, 타이머용)")
|
||||
quotation_memo: str = Field("", description="견적 메모")
|
||||
item_id: str = Field("", description="상품 uuid")
|
||||
@ -78,10 +77,6 @@ class Res_ChatInit(Res_WebPacketProtocol):
|
||||
item_min_order_quantity: str = Field("", description="최소 주문 수량")
|
||||
item_vat_yn: Optional[bool] = Field(None, description="VAT 포함 여부(미설정 시 null)")
|
||||
item_delivery_fee_yn: Optional[bool] = Field(None, description="배송비 포함 여부(미설정 시 null)")
|
||||
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 기존 입력값(sessions.custom). 재진입 시 폼 프리필용")
|
||||
reject_reason: str = Field("", description="협상 거부 시 제출한 사유. 거부 건이 아니면 빈 문자열")
|
||||
reject_price: Optional[int] = Field(None, description="협상 거부 시 함께 낸 공급 희망 가격(원). 미입력이면 null")
|
||||
labels: dict = Field(default_factory=dict, description="회사 커스텀 라벨(companies.settings.labels). 상품 상세 필드명(예: lead_time) 치환용. 없으면 프론트 기본값")
|
||||
|
||||
|
||||
# 대화 히스토리(재진입 복원)
|
||||
|
||||
@ -1,5 +1,3 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
@ -16,14 +14,6 @@ class ListItem(WebPacketProtocol):
|
||||
item_name: str = Field("", description="상품명")
|
||||
model_name: str = Field("", description="모델명")
|
||||
maker_name: str = Field("", description="제조사")
|
||||
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 값(sessions.custom). 미입력이면 빈 dict")
|
||||
renegotiable: bool = Field(False, description="재협상 요청 가능 여부 — 낙찰 없이 마감(개찰)된 마지막 차수이고 대기 중 요청이 없을 때만 True")
|
||||
renegotiation_status: int = Field(0, description="현재 재협상 요청 상태(RenegotiationStatus). 요청 이력이 없으면 0")
|
||||
renegotiation_memo: str = Field("", description="담당자 심사 메모(반려 사유). 없으면 빈 문자열")
|
||||
result: int = Field(0, description="공급사 관점 협상 결과(SessionResult): 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰, 재협상 대상)")
|
||||
has_chat: bool = Field(False, description="대화 이력 존재 여부 — 종료된 협상(미참여·거부)의 '결과 보기' 노출 판단용")
|
||||
reject_reason: str = Field("", description="협상 거부 시 제출한 사유. 거부 건이 아니면 빈 문자열")
|
||||
reject_price: Optional[int] = Field(None, description="협상 거부 시 함께 낸 공급 희망 가격(원). 미입력이면 null")
|
||||
|
||||
|
||||
class Res_SessionList(Res_WebPacketProtocol):
|
||||
@ -39,27 +29,7 @@ class Res_Participate(Res_WebPacketProtocol):
|
||||
|
||||
class Req_Reject(WebPacketProtocol):
|
||||
reject_reason: str = Field("", max_length=255, description="거부 사유 (단종/품절 프리셋 라벨 또는 직접 입력)")
|
||||
reject_price: Optional[int] = Field(None, description="공급 희망 가격(원). 선택 입력 — 없으면 컬럼 미변경")
|
||||
opinion: Optional[str] = Field(None, max_length=255, description="추가 의견 — sessions.custom.opinion 에 병합")
|
||||
|
||||
|
||||
class Res_Reject(Res_WebPacketProtocol):
|
||||
session_id: str = Field("", description="거부 처리된 세션 uuid")
|
||||
|
||||
|
||||
class Req_ExtraInfo(WebPacketProtocol):
|
||||
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 값 {key: value} (회사 정의 session_fields 대로)")
|
||||
|
||||
|
||||
class Res_ExtraInfo(Res_WebPacketProtocol):
|
||||
session_id: str = Field("", description="부가정보 저장된 세션 uuid")
|
||||
|
||||
|
||||
class Req_Renegotiation(WebPacketProtocol):
|
||||
reason: str = Field("", max_length=255, description="재협상 요청 사유(프리셋 라벨 또는 직접 입력)")
|
||||
desired_price: Optional[int] = Field(None, description="희망 공급가(원). 담당자 판단 근거로만 쓰인다")
|
||||
|
||||
|
||||
class Res_Renegotiation(Res_WebPacketProtocol):
|
||||
session_id: str = Field("", description="요청이 기록된 세션 uuid")
|
||||
status: int = Field(0, description="요청 상태(RenegotiationStatus): 1=심사중 2=승인 3=반려 4=철회")
|
||||
|
||||
@ -6,16 +6,7 @@ from fastapi.security import HTTPAuthorizationCredentials
|
||||
from common.models.gmodel import UserInfo
|
||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, security
|
||||
from services.negotiation_service import NegotiationService
|
||||
from .protocol import (
|
||||
Req_ExtraInfo,
|
||||
Req_Reject,
|
||||
Req_Renegotiation,
|
||||
Res_ExtraInfo,
|
||||
Res_Participate,
|
||||
Res_Reject,
|
||||
Res_Renegotiation,
|
||||
Res_SessionList,
|
||||
)
|
||||
from .protocol import Req_Reject, Res_Participate, Res_Reject, Res_SessionList
|
||||
|
||||
router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={404: {"description": "Not found"}})
|
||||
|
||||
@ -24,7 +15,7 @@ router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={40
|
||||
path="/sessions",
|
||||
response_model=Res_SessionList,
|
||||
summary="협상 세션 목록",
|
||||
description="로그인한 공급사의 협상 세션 목록. 필터(status/qt_type, 정수 코드)·페이지네이션 지원. 기본 정렬(order 미지정)은 '할 일(협상생성·협상중) 우선 + 마감 임박순', 종료(완료·미참여·거부)는 하단·최근순. order 를 주면 그룹 없이 전체 마감순으로 정렬.",
|
||||
description="로그인한 공급사의 협상 세션 목록. 필터(status/qt_type, 정수 코드)·마감일 정렬·페이지네이션 지원.",
|
||||
)
|
||||
async def list_sessions(
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
@ -32,14 +23,12 @@ async def list_sessions(
|
||||
service: NegotiationService = Depends(),
|
||||
status: Optional[int] = Query(None, description="세션 상태 코드 (SessionStatus)"),
|
||||
qt_type: Optional[int] = Query(None, description="견적 유형 코드 (QtType: 1=재협상, 2=재견적, 3=신규협상, 4=신규견적)"),
|
||||
order: Optional[str] = Query(None, description="마감일 전체 정렬: asc(임박순)/desc(여유순). 미지정 시 기본 그룹 정렬('할 일' 우선 → 종료는 하단·최근순). 지정하면 그룹 없이 전체를 마감 기준으로 정렬."),
|
||||
order: str = Query("asc", description="마감일 정렬: asc(임박순)/desc"),
|
||||
page: int = Query(1, ge=1, description="페이지 (1부터)"),
|
||||
page_size: int = Query(20, ge=1, le=100, description="페이지당 건수 (1~100)"),
|
||||
keyword: Optional[str] = Query(None, description="검색어 — 견적번호·상품명·상품코드 부분일치(대소문자 무시)"),
|
||||
result: Optional[int] = Query(None, description="결과 필터(SessionResult): 1=낙찰 2=미낙찰 3=결렬(개찰). 미지정 시 전체"),
|
||||
):
|
||||
return RemoveNoneResponse(
|
||||
await service.list_sessions(user_info, credentials.credentials, status, qt_type, order, page, page_size, keyword, result)
|
||||
await service.list_sessions(user_info, credentials.credentials, status, qt_type, order, page, page_size)
|
||||
)
|
||||
|
||||
|
||||
@ -62,7 +51,7 @@ async def participate(
|
||||
path="/sessions/{session_id}/reject",
|
||||
response_model=Res_Reject,
|
||||
summary="협상 거부",
|
||||
description="세션 참여를 거부하거나 진행 중인 협상을 거부한다. 소유(공급사)·세션상태(완료/미참여/거부 불가)·견적마감·마감시간 검증 후 협상거부로 전이하고 사유·공급 희망 가격·의견을 저장.",
|
||||
description="세션 참여를 거부한다. 소유(공급사)·세션상태(완료/미참여/거부 불가)·견적마감·마감시간 검증 후 협상거부로 전이하고 사유를 저장.",
|
||||
)
|
||||
async def reject(
|
||||
session_id: str = Path(description="대상 협상 세션 uuid"),
|
||||
@ -71,59 +60,4 @@ async def reject(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: NegotiationService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(
|
||||
await service.reject(
|
||||
user_info, credentials.credentials, session_id, req.reject_reason, req.reject_price, req.opinion,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/sessions/{session_id}/extra-info",
|
||||
response_model=Res_ExtraInfo,
|
||||
summary="협상완료 부가정보 저장",
|
||||
description="협상 타결(완료) 세션에 부가정보(표준납기/MOQ/발주배수/배송유형 등, 회사 정의 session_fields)를 저장한다. 본인 공급사의 완료 세션만 허용.",
|
||||
)
|
||||
async def save_extra_info(
|
||||
session_id: str = Path(description="대상 협상 세션 uuid"),
|
||||
req: Req_ExtraInfo = ...,
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: NegotiationService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.save_extra_info(user_info, credentials.credentials, session_id, req))
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/session/{session_id}/renegotiation",
|
||||
response_model=Res_Renegotiation,
|
||||
summary="재협상 요청",
|
||||
description="낙찰 없이 마감된(개찰) 건에 대해 공급사가 재협상을 요청한다. 담당자 승인 시 다음 라운드가 생성된다. 본인 공급사의 마지막 라운드 세션만 허용.",
|
||||
)
|
||||
async def request_renegotiation(
|
||||
req: Req_Renegotiation,
|
||||
session_id: str = Path(..., description="협상 세션 uuid"),
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: NegotiationService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(
|
||||
await service.request_renegotiation(user_info, credentials.credentials, session_id, req)
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
path="/session/{session_id}/renegotiation",
|
||||
response_model=Res_Renegotiation,
|
||||
summary="재협상 요청 철회",
|
||||
description="심사 대기(PENDING) 중인 본인 요청을 철회한다.",
|
||||
)
|
||||
async def cancel_renegotiation(
|
||||
session_id: str = Path(..., description="협상 세션 uuid"),
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: NegotiationService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(
|
||||
await service.cancel_renegotiation(user_info, credentials.credentials, session_id)
|
||||
)
|
||||
return RemoveNoneResponse(await service.reject(user_info, credentials.credentials, session_id, req.reject_reason))
|
||||
|
||||
@ -18,7 +18,6 @@ from router.v1.auth.protocol import (
|
||||
Res_Me,
|
||||
Res_PopupStatus,
|
||||
Res_RefreshToken,
|
||||
Res_SessionBranding,
|
||||
)
|
||||
from router.v1.validator.dependencies import CreateAccessToken, CreateRefreshToken, GetHashedPW, VerifyPW
|
||||
|
||||
@ -251,35 +250,6 @@ class AuthService:
|
||||
res.supplier_id = info.supplier_id
|
||||
res.supplier_name = info.supplier_name
|
||||
res.role = info.role
|
||||
# 소속 회사 설정(companies.settings) — 로고/서비스명(branding) + 협상완료 부가필드(session_fields). 실패해도 기본값.
|
||||
_e, settings = await DB_SESSION_MNG.execute_lambda(
|
||||
suppliers.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_company_settings(s, uuid.UUID(info.supplier_id)),
|
||||
)
|
||||
settings = settings or {}
|
||||
res.branding = settings.get("branding") or {}
|
||||
res.session_fields = settings.get("session_fields") or []
|
||||
res.guide_notices = settings.get("guide_notices") or []
|
||||
return res
|
||||
|
||||
async def session_branding(self, session_id: str) -> Res_SessionBranding:
|
||||
"""로그인 전(초청 링크 진입) 화면용 브랜딩. 인증 없이 session_id 로만 조회하며 브랜딩 외 정보는 내리지 않는다."""
|
||||
res = Res_SessionBranding()
|
||||
try:
|
||||
sid = uuid.UUID(session_id)
|
||||
except ValueError:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
_e, branding = await DB_SESSION_MNG.execute_lambda(
|
||||
suppliers.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_branding_by_session(s, sid),
|
||||
)
|
||||
branding = branding or {}
|
||||
res.service_name = branding.get("service_name") or ""
|
||||
res.logo_url = branding.get("logo_url") or ""
|
||||
res.helpdesk = branding.get("helpdesk") or []
|
||||
return res
|
||||
|
||||
async def popup_status(self, user_info: UserInfo, access_token: str) -> Res_PopupStatus:
|
||||
|
||||
@ -24,7 +24,6 @@ from common.logger import LOG
|
||||
from common.models.gmodel import UserInfo
|
||||
from crud.chat_crud import ChatCRUD, IChatCRUD
|
||||
from crud.session_crud import ISessionCRUD, SessionCRUD
|
||||
from crud.user_crud import IUserCRUD, UserCRUD
|
||||
from router.v1.chat.protocol import ChatMessage, ChatSummary, Res_ChatInit, Res_ChatMessages, Res_ChatSend
|
||||
from services.agent_client import AgentChatContext, IAgentClient, get_agent_client
|
||||
from services.auth_service import AuthService
|
||||
@ -45,13 +44,11 @@ class ChatService:
|
||||
auth: AuthService = Depends(AuthService),
|
||||
session_crud: ISessionCRUD = Depends(SessionCRUD),
|
||||
chat_crud: IChatCRUD = Depends(ChatCRUD),
|
||||
user_crud: IUserCRUD = Depends(UserCRUD),
|
||||
agent: IAgentClient = Depends(get_agent_client),
|
||||
):
|
||||
self.auth = auth
|
||||
self.session_crud = session_crud
|
||||
self.chat_crud = chat_crud
|
||||
self.user_crud = user_crud
|
||||
self.agent = agent
|
||||
|
||||
# ---- 순수 헬퍼/매퍼 (self 불필요, 상단 집약) ----
|
||||
@ -62,35 +59,6 @@ class ChatService:
|
||||
digits = "".join(ch for ch in text if ch.isdigit())
|
||||
return int(digits) if digits else None
|
||||
|
||||
@staticmethod
|
||||
def _parse_reject(text: Optional[str]) -> dict:
|
||||
"""통일 결렬 폼 제출 문자열 파싱 → {offer_price, reason, opinion}.
|
||||
형식: '공급희망가격-{원}, 합의불가사유-{사유}, 의견-{의견}' (사유는 '기타-{내용}' 가능).
|
||||
의견은 자유서술이라 콤마 포함 가능 → 맨 뒤 '의견-' 기준으로 먼저 떼어낸다."""
|
||||
s = text or ""
|
||||
opinion = None
|
||||
if ", 의견-" in s:
|
||||
s, opinion = s.split(", 의견-", 1)
|
||||
# 폼이 아닌 자유 입력("협상 포기합니다" 등)은 원문이 곧 사유다. 폼 마커가 없으면 가격도 읽지 않는다
|
||||
# — 문장에 섞인 숫자를 희망가로 오인해 저장하는 것을 막는다.
|
||||
if "합의불가사유-" not in s and "공급희망가격-" not in s:
|
||||
return {
|
||||
"offer_price": None,
|
||||
"reason": s.strip()[:255] or None,
|
||||
"opinion": (opinion.strip() or None) if opinion is not None else None,
|
||||
}
|
||||
reason = None
|
||||
if ", 합의불가사유-" in s:
|
||||
price_part, reason = s.split(", 합의불가사유-", 1)
|
||||
else:
|
||||
price_part = s
|
||||
price_digits = "".join(ch for ch in price_part.replace("공급희망가격-", "") if ch.isdigit())
|
||||
return {
|
||||
"offer_price": int(price_digits) if price_digits else None,
|
||||
"reason": reason or None,
|
||||
"opinion": (opinion.strip() or None) if opinion is not None else None,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _in_price_range(price: int, target_price: Optional[int]) -> bool:
|
||||
if not target_price:
|
||||
@ -135,18 +103,13 @@ class ChatService:
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _build_bot_chat(sess, seq: int, turn, bot_chat_type: Optional[str] = None, summary: Optional[dict] = None, card_uuid=None, card_type=None) -> chats:
|
||||
def _build_bot_chat(sess, seq: int, turn, bot_chat_type: Optional[str] = None, summary: Optional[dict] = None) -> chats:
|
||||
# bot_chat_type/summary 도 meta 에 영속화 → 히스토리 복원 시 폼 재현. indicator_value 는 전용 컬럼에도 적재.
|
||||
# nego_card_uuid: turn.card_id(번호)를 UUID 로 변환한 값(nego 카드). 있으면 chats.card_id/card_type/card_used_yn 컬럼에 적재
|
||||
# → negodata 가 이 컬럼으로 카드 사용/효과를 조인한다. (wild 카드는 agent 가 card_id 미제공 — 별도 작업)
|
||||
return chats(
|
||||
chat_id=uuid.uuid4(), session_id=sess.session_id, seq=seq,
|
||||
sender=ChatSender.BOT.value,
|
||||
target_price=int(sess.target_price or 0),
|
||||
indicator_value=turn.indicator_value,
|
||||
card_id=card_uuid,
|
||||
card_type=card_type if card_uuid else None, # CardType: 1=nego, 2=wild
|
||||
card_used_yn=True if card_uuid else None,
|
||||
meta={
|
||||
"script": turn.script, "step": turn.step, "client_step": turn.client_step,
|
||||
"input_mode": turn.input_mode, "input_options": turn.input_options,
|
||||
@ -235,15 +198,15 @@ class ChatService:
|
||||
)
|
||||
sess.status = SessionStatus.NOT_PARTICIPATED.value
|
||||
|
||||
# 미참여/협상거부 세션도 '결과 보기'로 지난 대화를 열람할 수 있다(중간 이탈·거부로 끝난 건).
|
||||
# 대화 재개는 send() 가 협상중(2)만 허용하므로 여기서 막지 않아도 읽기 전용이다.
|
||||
|
||||
await self._ensure_in_progress(sess, quote)
|
||||
# 미참여/협상거부 상태는 진입(열람) 불가 (participate/reject 와 동일 규칙).
|
||||
# 위 마감 변환으로 미참여가 된 세션도 여기서 함께 막힌다.
|
||||
if sess.status in (SessionStatus.NOT_PARTICIPATED.value, SessionStatus.REJECTED.value):
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
|
||||
return res
|
||||
|
||||
res.session_id = str(sess.session_id)
|
||||
res.session_status = sess.status
|
||||
res.quotation_id = str(sess.quotation_id)
|
||||
res.qt_number = sess.qt_number or ""
|
||||
res.quotation_end_time = quote.end_time.isoformat(timespec="seconds") if quote.end_time else ""
|
||||
res.quotation_memo = quote.memo or ""
|
||||
res.item_id = str(item.item_id)
|
||||
@ -258,65 +221,8 @@ class ChatService:
|
||||
res.item_min_order_quantity = item.moq or ""
|
||||
res.item_vat_yn = item.vat_yn
|
||||
res.item_delivery_fee_yn = item.delivery_fee_yn
|
||||
res.custom = sess.custom or {}
|
||||
# 거부로 끝난 세션은 대화에 남지 않는 제출 내역(사유·희망가)을 열람용으로 함께 내린다.
|
||||
res.reject_reason = sess.reject_reason or ""
|
||||
res.reject_price = sess.reject_price
|
||||
|
||||
# 회사 커스텀 라벨(companies.settings.labels) — 상품 상세 필드명 치환용(예: lead_time→표준납기). 실패해도 빈 dict 폴백.
|
||||
_e, settings = await DB_SESSION_MNG.execute_lambda(
|
||||
suppliers.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_company_settings(s, sess.supplier_id),
|
||||
)
|
||||
res.labels = (settings.get("labels") or {}) if _e == ErrorType.SUCCESS and settings else {}
|
||||
|
||||
_hidden = (settings.get("hidden_fields") or []) if _e == ErrorType.SUCCESS and settings else []
|
||||
_features = (settings.get("features") or {}) if _e == ErrorType.SUCCESS and settings else {}
|
||||
|
||||
# VAT 표기 — 부가세 전체 통일 회사(features.vat_mode)는 상품 잔존값과 무관하게 'VAT 별도' 고정(False).
|
||||
# 상품별 관리 회사가 vat_yn 을 숨겼으면(구 방식) 표기 자체를 생략한다(값 null → 프론트 라벨 생략).
|
||||
if _features.get("vat_mode") == "unified_excluded":
|
||||
res.item_vat_yn = False
|
||||
elif "vat_yn" in _hidden:
|
||||
res.item_vat_yn = None
|
||||
|
||||
# 협상 기준가 — 회사 설정에서 고른 가격 컬럼(features.nego_baseline_field).
|
||||
# agent 의 인하율 멘트(nego_context_crud._resolve_baseline)와 같은 규칙이어야 화면과 멘트가 어긋나지 않는다.
|
||||
_baseline = _features.get("nego_baseline_field")
|
||||
if _baseline not in ("price", "purchase_price"):
|
||||
# 미설정 회사 폴백 — 공급가를 감췄으면 그 회사는 공급가를 관리하지 않는다는 뜻.
|
||||
_baseline = "purchase_price" if ("price" in _hidden and "purchase_price" not in _hidden) else "price"
|
||||
if _baseline == "purchase_price":
|
||||
res.item_price = item.purchase_price or 0
|
||||
return res
|
||||
|
||||
async def _ensure_in_progress(self, sess, quote) -> None:
|
||||
"""협상생성(1) 세션을 채팅 진입만으로 협상중(2)으로 전이한다(participate 와 동일 전이).
|
||||
|
||||
negodata 안내 메일/링크는 목록의 참여 버튼을 거치지 않고 chat 으로 바로 들어오는데,
|
||||
오프닝 메시지는 협상중일 때만 seed 되므로 전이가 없으면 빈 채팅으로 멈춘다.
|
||||
마감된 견적은 진입해도 대화가 불가하므로 전이하지 않는다."""
|
||||
if sess.status != SessionStatus.CREATED.value:
|
||||
return
|
||||
if quote is None or quote.status == QuotationStatus.CLOSED.value:
|
||||
return
|
||||
end = quote.end_time
|
||||
if end is not None and end.tzinfo is None:
|
||||
end = end.replace(tzinfo=timezone.utc)
|
||||
if end is not None and end < datetime.now(timezone.utc):
|
||||
return
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[sessions.DBType()],
|
||||
[
|
||||
lambda s: self.session_crud.update_session_status(s, sess.session_id, SessionStatus.IN_PROGRESS.value),
|
||||
lambda s: self.session_crud.update_quotation_status(s, sess.quotation_id, QuotationStatus.IN_PROGRESS.value),
|
||||
],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return
|
||||
sess.status = SessionStatus.IN_PROGRESS.value
|
||||
|
||||
# ---- messages -------------------------------------------------------
|
||||
async def messages(self, user_info: UserInfo, access_token: str, session_id_str: str) -> Res_ChatMessages:
|
||||
res = Res_ChatMessages()
|
||||
@ -333,15 +239,6 @@ class ChatService:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 협상생성 상태로 바로 진입한 경우(메일 링크) 여기서도 전이한다 —
|
||||
# init 과 병렬로 호출돼 init 의 전이를 못 본 채 읽었을 수 있다.
|
||||
if not rows and sess.status == SessionStatus.CREATED.value:
|
||||
_, quote = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.get_quotation_by_id(s, sess.quotation_id),
|
||||
)
|
||||
await self._ensure_in_progress(sess, quote)
|
||||
|
||||
# 비어 있고 협상중이면 agent 오프닝 한 턴을 seed (재진입 시 인사 메시지 보존)
|
||||
if not rows and sess.status == SessionStatus.IN_PROGRESS.value:
|
||||
opening = await self._seed_opening(sess)
|
||||
@ -474,43 +371,8 @@ class ChatService:
|
||||
# 유저 미입력 가격 타결 케이스 — 마지막 유저 제시가와 다를 수 있다).
|
||||
summary = await self._build_summary(sess, quote, item, final_price, turn.settled_price or last_price)
|
||||
|
||||
# 카드 번호(turn.card_id) → UUID 변환. 번호 정본 표기(NGC-/WC- prefix)로 종류를 가르고,
|
||||
# prefix 없는 구번호는 step 휴리스틱 폴백. 1차 조회가 비면 반대 테이블 재조회 —
|
||||
# 종결 전술의 와일드카드는 step 이 '가격협상_카운터'(wild 미시작)라 step 만으론 카드가
|
||||
# 영영 null 로 남았다(사용 카드 통계·화면 누락 원인).
|
||||
# 카드 사용 로그(chats.card_id/type/used)를 negodata 조인용으로 남긴다. (1% 인하 시스템 카드는 agent 가 card_id 미제공)
|
||||
card_uuid = None
|
||||
card_type = None
|
||||
if turn.card_id:
|
||||
number = str(turn.card_id)
|
||||
if number.startswith("WC"):
|
||||
wild_first = True
|
||||
elif number.startswith("NGC"):
|
||||
wild_first = False
|
||||
else:
|
||||
wild_first = bool(turn.step and turn.step.startswith("wild"))
|
||||
|
||||
async def _lookup(wild: bool):
|
||||
if wild:
|
||||
found = await DB_SESSION_MNG.execute_lambda(
|
||||
chats.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.chat_crud.get_wild_card_id_by_number(s, number),
|
||||
)
|
||||
return found, 2
|
||||
found = await DB_SESSION_MNG.execute_lambda(
|
||||
chats.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.chat_crud.get_nego_card_id_by_number(s, number),
|
||||
)
|
||||
return found, 1
|
||||
|
||||
card_uuid, card_type = await _lookup(wild_first)
|
||||
if card_uuid is None:
|
||||
card_uuid, card_type = await _lookup(not wild_first)
|
||||
if card_uuid is None:
|
||||
card_type = None
|
||||
|
||||
# 봇 메시지 + 종료 시 확정(성공=DONE+입찰가 / 실패=REJECTED+거부사유·제시가). 한 트랜잭션.
|
||||
bot_msg = self._build_bot_chat(sess, seq=max_seq + 2, turn=turn, bot_chat_type=bot_chat_type, summary=summary, card_uuid=card_uuid, card_type=card_type)
|
||||
bot_msg = self._build_bot_chat(sess, seq=max_seq + 2, turn=turn, bot_chat_type=bot_chat_type, summary=summary)
|
||||
funcs = [lambda s: self.chat_crud.insert_message(s, bot_msg)]
|
||||
# 가격 입력 턴 → 마지막 제시가를 봇 메시지 저장과 같은 트랜잭션으로 갱신.
|
||||
# 앵커링 표본 판정의 "가격 흔적"(가격을 써낸 협상만 집계 — 중간 이탈해도 실패로 측정 가능).
|
||||
@ -530,14 +392,9 @@ class ChatService:
|
||||
funcs.append(lambda s: self.chat_crud.finalize_session(s, sess.session_id, new_status, bid_price=bid))
|
||||
else:
|
||||
new_status = SessionStatus.REJECTED.value
|
||||
parsed = self._parse_reject(user_input)
|
||||
funcs.append(lambda s: self.chat_crud.finalize_session(
|
||||
s, sess.session_id, new_status,
|
||||
reject_reason=parsed["reason"], reject_price=parsed["offer_price"],
|
||||
))
|
||||
if parsed["opinion"]:
|
||||
funcs.append(lambda s, op=parsed["opinion"]: self.session_crud.merge_session_custom(
|
||||
s, sess.session_id, sess.supplier_id, {"opinion": op},
|
||||
reject_reason=(user_input or None), reject_price=price,
|
||||
))
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run([chats.DBType()], funcs)
|
||||
@ -648,17 +505,7 @@ class ChatService:
|
||||
# 배송형태: 재견적(CM)의 '배송형태선택' 단계에서 공급사가 고른 라벨. 재협상엔 단계가 없어 None.
|
||||
delivery_label = await self._delivery_choice(sess) if sess.qt_type == 2 else None
|
||||
# 상품 기본 배송유형(코드→라벨). 선택값이 없으면 표시에 폴백으로 쓸 수 있다.
|
||||
# 회사가 배송유형 보기를 자기 용어로 바꿨으면(settings.labels['delivery_type.N']) 그 단어를 쓴다 —
|
||||
# 협상 중 공급사가 고른 보기와 요약 표기가 갈리지 않도록.
|
||||
item_delivery_label = ""
|
||||
if item and item.delivery_type is not None:
|
||||
_e2, _settings = await DB_SESSION_MNG.execute_lambda(
|
||||
suppliers.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_company_settings(s, sess.supplier_id),
|
||||
)
|
||||
_labels = (_settings.get("labels") or {}) if _e2 == ErrorType.SUCCESS and _settings else {}
|
||||
item_delivery_label = (_labels.get(f"delivery_type.{item.delivery_type}")
|
||||
or DeliveryType.label_of(item.delivery_type))
|
||||
item_delivery_label = DeliveryType.label_of(item.delivery_type) if item and item.delivery_type is not None else ""
|
||||
|
||||
def _iso(dt):
|
||||
if dt is None:
|
||||
|
||||
@ -1,35 +1,14 @@
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import chats, notifications, sessions
|
||||
from common.enums import (
|
||||
CloseReason,
|
||||
DBWRType,
|
||||
ErrorType,
|
||||
NotificationType,
|
||||
QuotationStatus,
|
||||
RENEGOTIABLE_CLOSE_REASONS,
|
||||
RenegotiationStatus,
|
||||
SessionStatus,
|
||||
)
|
||||
from common.logger import LOG
|
||||
from common.database.model.models import sessions
|
||||
from common.enums import DBWRType, ErrorType, QuotationStatus, SessionStatus
|
||||
from common.models.gmodel import UserInfo
|
||||
from crud.chat_crud import ChatCRUD, IChatCRUD
|
||||
from crud.session_crud import ISessionCRUD, SessionCRUD
|
||||
from router.v1.negotiation.protocol import (
|
||||
ListItem,
|
||||
Req_ExtraInfo,
|
||||
Req_Renegotiation,
|
||||
Res_ExtraInfo,
|
||||
Res_Participate,
|
||||
Res_Reject,
|
||||
Res_Renegotiation,
|
||||
Res_SessionList,
|
||||
)
|
||||
from router.v1.negotiation.protocol import ListItem, Res_Participate, Res_Reject, Res_SessionList
|
||||
from services.auth_service import AuthService
|
||||
|
||||
|
||||
@ -39,20 +18,11 @@ class NegotiationService:
|
||||
- 목록은 로그인 유저의 supplier_id 로만 조회한다.
|
||||
"""
|
||||
|
||||
# 부가정보 입력 폼을 띄우는 요약 말풍선 종류. 이 말풍선이 나온 뒤면 협상은 타결된 것으로 본다.
|
||||
_SUMMARY_BOT_TYPES = ("summaryRSP", "summaryCM")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
auth: AuthService = Depends(AuthService),
|
||||
session_crud: ISessionCRUD = Depends(SessionCRUD),
|
||||
chat_crud: IChatCRUD = Depends(ChatCRUD),
|
||||
):
|
||||
def __init__(self, auth: AuthService = Depends(AuthService), session_crud: ISessionCRUD = Depends(SessionCRUD)):
|
||||
self.auth = auth
|
||||
self.session_crud = session_crud
|
||||
self.chat_crud = chat_crud
|
||||
|
||||
async def list_sessions(self, user_info: UserInfo, access_token: str, status, qt_type, order: str, page: int, page_size: int, keyword: str = None, result: int = None) -> Res_SessionList:
|
||||
async def list_sessions(self, user_info: UserInfo, access_token: str, status, qt_type, order: str, page: int, page_size: int) -> Res_SessionList:
|
||||
res = Res_SessionList()
|
||||
|
||||
# 1) 인증 (활성 + 저장된 access 토큰 대조)
|
||||
@ -68,7 +38,7 @@ class NegotiationService:
|
||||
err_type, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.list_by_supplier(s, supplier_id, status, qt_type, order, offset, page_size, keyword, result),
|
||||
lambda s: self.session_crud.list_by_supplier(s, supplier_id, status, qt_type, order, offset, page_size),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
@ -78,97 +48,14 @@ class NegotiationService:
|
||||
err_type, total = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.count_by_supplier(s, supplier_id, status, qt_type, keyword, result),
|
||||
lambda s: self.session_crud.count_by_supplier(s, supplier_id, status, qt_type),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 같은 견적번호(체인)의 최대 차수 — 이미 다음 라운드가 있으면 재협상 요청 대상이 아니다.
|
||||
max_rounds: dict = {}
|
||||
for number in {r[3] for r in rows if r[3]}:
|
||||
_e, mx = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s, n=number: self.session_crud.chain_max_round(s, n),
|
||||
)
|
||||
max_rounds[number] = mx or 0
|
||||
|
||||
res.items = [self._to_list_item(r, max_rounds) for r in rows]
|
||||
res.total = total
|
||||
res.page = page
|
||||
res.page_size = page_size
|
||||
return res
|
||||
|
||||
async def save_extra_info(self, user_info: UserInfo, access_token: str, session_id_str: str, req: Req_ExtraInfo) -> Res_ExtraInfo:
|
||||
"""협상완료(타결) 부가정보 저장. 견적 마감 여부와 무관하게, 본인 공급사의 '협상완료' 세션에만 허용.
|
||||
|
||||
_load_actionable_session 은 견적마감·마감시간을 막으므로(타결 후엔 마감됐을 수 있음) 쓰지 않고 직접 검증한다.
|
||||
"""
|
||||
res = Res_ExtraInfo()
|
||||
|
||||
# 1) 인증
|
||||
err_type, info = await self.auth.authenticate(user_info, access_token)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
try:
|
||||
session_id = uuid.UUID(session_id_str)
|
||||
except (ValueError, TypeError):
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_FOUND)
|
||||
return res
|
||||
|
||||
# 2) 세션 조회 + 소유 검증
|
||||
err_type, sess = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.get_session_by_id(s, session_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or sess is None:
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_FOUND)
|
||||
return res
|
||||
if str(sess.supplier_id) != info.supplier_id:
|
||||
res.result.SetResult(ErrorType.NEGO_FORBIDDEN)
|
||||
return res
|
||||
|
||||
# 3) 협상완료(타결) 세션만 부가정보 입력 허용.
|
||||
# 단 '협상완료' 요약 말풍선은 chat_end=false 라 세션이 아직 협상중(2)이다
|
||||
# (동의 → '협상종료' 턴에서야 완료로 전이). 폼은 요약 시점에 뜨므로 그 구간도 허용한다.
|
||||
if sess.status != SessionStatus.DONE.value:
|
||||
if sess.status != SessionStatus.IN_PROGRESS.value or not await self._is_after_summary(sess.session_id):
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
|
||||
return res
|
||||
|
||||
# 4) 저장(supplier_id 가드 crud)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[sessions.DBType()],
|
||||
[lambda s: self.session_crud.update_session_custom(s, session_id, uuid.UUID(info.supplier_id), req.custom or {})],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
res.session_id = str(session_id)
|
||||
return res
|
||||
|
||||
@staticmethod
|
||||
def _to_list_item(r, max_rounds: dict) -> ListItem:
|
||||
"""세션 행 → 목록 아이템. 재협상 요청 가능 여부는 서버가 판정해 내려준다(프론트가 규칙을 몰라도 되게)."""
|
||||
custom = r[9] or {}
|
||||
renego = custom.get("renegotiation") or {}
|
||||
status = renego.get("status") or 0
|
||||
|
||||
is_last_round = (r[12] or 0) >= max_rounds.get(r[3], 0)
|
||||
renegotiable = (
|
||||
r[10] == QuotationStatus.CLOSED.value
|
||||
and r[11] in RENEGOTIABLE_CLOSE_REASONS
|
||||
and is_last_round
|
||||
and status
|
||||
not in (
|
||||
RenegotiationStatus.PENDING.value,
|
||||
RenegotiationStatus.APPROVED.value,
|
||||
RenegotiationStatus.REJECTED.value,
|
||||
)
|
||||
)
|
||||
return ListItem(
|
||||
res.items = [
|
||||
ListItem(
|
||||
session_id=str(r[0]),
|
||||
session_status=r[1],
|
||||
qt_type=r[2],
|
||||
@ -178,174 +65,14 @@ class NegotiationService:
|
||||
item_name=r[6] or "",
|
||||
model_name=r[7] or "",
|
||||
maker_name=r[8] or "",
|
||||
custom=custom,
|
||||
renegotiable=renegotiable,
|
||||
renegotiation_status=status,
|
||||
renegotiation_memo=renego.get("memo") or "",
|
||||
result=NegotiationService._to_result(r[10], r[11], r[13], r[14]),
|
||||
has_chat=bool(r[15]),
|
||||
reject_reason=r[16] or "",
|
||||
reject_price=r[17],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _to_result(qt_status, close_reason, winner_id, my_id) -> int:
|
||||
"""공급사 관점 협상 결과(SessionResult). 견적 마감 전이면 0(미정).
|
||||
낙찰 건은 낙찰자가 나면 1(낙찰)·아니면 2(미낙찰), 개찰(OPEN_*) 마감은 3(결렬=재협상 대상)."""
|
||||
if qt_status != QuotationStatus.CLOSED.value:
|
||||
return 0
|
||||
if close_reason == CloseReason.AWARDED.value:
|
||||
return 1 if winner_id is not None and str(winner_id) == str(my_id) else 2
|
||||
if close_reason in RENEGOTIABLE_CLOSE_REASONS:
|
||||
return 3
|
||||
return 0
|
||||
|
||||
async def request_renegotiation(
|
||||
self, user_info: UserInfo, access_token: str, session_id_str: str, req: Req_Renegotiation
|
||||
) -> Res_Renegotiation:
|
||||
"""결렬(개찰) 마감 건에 대해 공급사가 재협상을 요청한다(IMK #15).
|
||||
전용 테이블 없이 sessions.custom.renegotiation 에 기록하고, 견적 작성자에게 알림을 남긴다."""
|
||||
res = Res_Renegotiation()
|
||||
|
||||
err_type, info, sess, quote = await self._load_renegotiable(user_info, access_token, session_id_str)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
for r in rows
|
||||
]
|
||||
res.total = total
|
||||
res.page = page
|
||||
res.page_size = page_size
|
||||
return res
|
||||
|
||||
# 심사 대기·승인·반려 건은 재요청을 막는다(전용 테이블이 없어 유니크 대신 여기서 검증).
|
||||
# 반려는 담당자가 이미 판단한 결과라 같은 건으로 다시 올릴 수 없다. 철회(CANCELED)만 재요청 허용.
|
||||
current = (sess.custom or {}).get("renegotiation") or {}
|
||||
if current.get("status") in (
|
||||
RenegotiationStatus.PENDING.value,
|
||||
RenegotiationStatus.APPROVED.value,
|
||||
RenegotiationStatus.REJECTED.value,
|
||||
):
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
|
||||
return res
|
||||
|
||||
payload = {
|
||||
"status": RenegotiationStatus.PENDING.value,
|
||||
"reason": (req.reason or "").strip(),
|
||||
"desired_price": req.desired_price,
|
||||
"requested_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[sessions.DBType()],
|
||||
[lambda s: self.session_crud.merge_session_custom(
|
||||
s, sess.session_id, uuid.UUID(info.supplier_id), {"renegotiation": payload}
|
||||
)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
await self._notify_renegotiation(quote, sess, info, payload)
|
||||
res.session_id = str(sess.session_id)
|
||||
res.status = RenegotiationStatus.PENDING.value
|
||||
return res
|
||||
|
||||
async def cancel_renegotiation(self, user_info: UserInfo, access_token: str, session_id_str: str) -> Res_Renegotiation:
|
||||
"""공급사가 자기 요청을 철회한다. 심사 대기(PENDING) 중에만 가능."""
|
||||
res = Res_Renegotiation()
|
||||
|
||||
err_type, info, sess, _quote = await self._load_renegotiable(user_info, access_token, session_id_str)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
current = (sess.custom or {}).get("renegotiation") or {}
|
||||
if current.get("status") != RenegotiationStatus.PENDING.value:
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
|
||||
return res
|
||||
|
||||
patch = {**current, "status": RenegotiationStatus.CANCELED.value}
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[sessions.DBType()],
|
||||
[lambda s: self.session_crud.merge_session_custom(
|
||||
s, sess.session_id, uuid.UUID(info.supplier_id), {"renegotiation": patch}
|
||||
)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
res.session_id = str(sess.session_id)
|
||||
res.status = RenegotiationStatus.CANCELED.value
|
||||
return res
|
||||
|
||||
async def _load_renegotiable(self, user_info: UserInfo, access_token: str, session_id_str: str):
|
||||
"""재협상 요청 자격 검증 — 인증 → 본인 세션 → 결렬(개찰) 마감 → 마지막 라운드.
|
||||
성공 시 (SUCCESS, info, sess, quote)."""
|
||||
err_type, info = await self.auth.authenticate(user_info, access_token)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, None, None, None
|
||||
try:
|
||||
session_id = uuid.UUID(session_id_str)
|
||||
except (ValueError, TypeError):
|
||||
return ErrorType.NEGO_NOT_FOUND, None, None, None
|
||||
|
||||
err_type, sess = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.get_session_by_id(s, session_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or sess is None:
|
||||
return ErrorType.NEGO_NOT_FOUND, None, None, None
|
||||
if str(sess.supplier_id) != info.supplier_id:
|
||||
return ErrorType.NEGO_FORBIDDEN, None, None, None
|
||||
|
||||
err_type, quote = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.get_quotation_by_id(s, sess.quotation_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or quote is None:
|
||||
return ErrorType.NEGO_NOT_FOUND, None, None, None
|
||||
|
||||
# 낙찰됐거나 아직 진행 중인 건은 요청 대상이 아니다.
|
||||
if quote.status != QuotationStatus.CLOSED.value or quote.close_reason not in RENEGOTIABLE_CLOSE_REASONS:
|
||||
return ErrorType.NEGO_NOT_PARTICIPABLE, None, None, None
|
||||
|
||||
# 이미 다음 라운드가 만들어졌으면 요청할 이유가 없다.
|
||||
_e, max_round = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.chain_max_round(s, quote.number),
|
||||
)
|
||||
if max_round and quote.round < max_round:
|
||||
return ErrorType.NEGO_NOT_PARTICIPABLE, None, None, None
|
||||
|
||||
return ErrorType.SUCCESS, info, sess, quote
|
||||
|
||||
async def _notify_renegotiation(self, quote, sess, info, payload: dict) -> None:
|
||||
"""견적 작성자 인박스에 재협상 요청 알림을 남긴다. 부가 효과라 실패해도 본 흐름을 막지 않는다."""
|
||||
notif = notifications(
|
||||
user_id=quote.user_id,
|
||||
type=NotificationType.RENEGO_REQUESTED.value,
|
||||
ref_qt_id=quote.qt_id,
|
||||
ref_session_id=sess.session_id,
|
||||
data={
|
||||
"supplier_name": info.supplier_name,
|
||||
"qt_number": quote.number,
|
||||
"qt_round": quote.round,
|
||||
"reason": payload.get("reason"),
|
||||
"desired_price": payload.get("desired_price"),
|
||||
},
|
||||
)
|
||||
err = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[notifications.DBType()],
|
||||
[lambda s: DB_SESSION_MNG.insert(s, notif, raise_error=False)],
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
LOG.e_no_callstack(f"[renego] 알림 기록 실패 qt={quote.qt_id} session={sess.session_id}")
|
||||
|
||||
async def _is_after_summary(self, session_id) -> bool:
|
||||
"""마지막 말풍선이 타결 요약(summaryRSP/CM)인지 — 즉 협상이 타결된 뒤인지."""
|
||||
err_type, (_, _, last_meta) = await DB_SESSION_MNG.execute_lambda(
|
||||
chats.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.chat_crud.get_last(s, session_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or not last_meta:
|
||||
return False
|
||||
return last_meta.get("bot_chat_type") in self._SUMMARY_BOT_TYPES
|
||||
|
||||
async def _load_actionable_session(self, user_info: UserInfo, access_token: str, session_id_str: str, blocked_statuses: tuple):
|
||||
"""참여/거부 공통 전처리: 인증 → 세션/견적 로드 → 소유·상태·견적마감·마감시간 검증.
|
||||
성공 시 (SUCCESS, sess, quote), 실패 시 (err_type, None, None) 을 반환한다.
|
||||
@ -438,10 +165,7 @@ class NegotiationService:
|
||||
res.session_id = str(sess.session_id)
|
||||
return res
|
||||
|
||||
async def reject(
|
||||
self, user_info: UserInfo, access_token: str, session_id_str: str, reject_reason: str,
|
||||
reject_price: Optional[int] = None, opinion: Optional[str] = None,
|
||||
) -> Res_Reject:
|
||||
async def reject(self, user_info: UserInfo, access_token: str, session_id_str: str, reject_reason: str) -> Res_Reject:
|
||||
res = Res_Reject()
|
||||
|
||||
# 거부 사유 필수
|
||||
@ -461,19 +185,11 @@ class NegotiationService:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 거부 처리 — 세션을 협상거부로 전이하고 사유·공급 희망 가격 저장.
|
||||
# 의견은 부가정보와 같은 custom 컬럼이라 병합(덮어쓰기 금지) — 채팅 결렬 폼과 같은 자리.
|
||||
funcs = [
|
||||
lambda s: self.session_crud.update_session_reject(
|
||||
s, sess.session_id, SessionStatus.REJECTED.value, reason, reject_price,
|
||||
# 거부 처리 — 세션을 협상거부로 전이하고 사유 저장
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[sessions.DBType()],
|
||||
[lambda s: self.session_crud.update_session_reject(s, sess.session_id, SessionStatus.REJECTED.value, reason)],
|
||||
)
|
||||
]
|
||||
note = (opinion or "").strip()[:255]
|
||||
if note:
|
||||
funcs.append(
|
||||
lambda s: self.session_crud.merge_session_custom(s, sess.session_id, sess.supplier_id, {"opinion": note})
|
||||
)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run([sessions.DBType()], funcs)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
@ -105,15 +105,10 @@ async def anchor_seed(db_engine):
|
||||
{"iid": item_id, "name": f"앵커상품 {code}", "code": f"{MARK}{code}"},
|
||||
)
|
||||
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) "
|
||||
"VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, 1, 2, now(), now() + interval '2 hours')"),
|
||||
text("INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, start_time, end_time, supplier_type) "
|
||||
"VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, 1, 2, now(), now() + interval '2 hours', 1)"),
|
||||
{"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(
|
||||
text("INSERT INTO negotiation.sessions "
|
||||
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
|
||||
|
||||
@ -220,58 +220,12 @@ async def test_chat_init_returns_meta(client, chat_seed):
|
||||
assert body["quotation_end_time"] # 타이머용 마감 시각
|
||||
|
||||
|
||||
async def test_chat_init_returns_reject_detail(client, chat_seed, db_engine):
|
||||
"""검증: 협상 거부로 끝난 세션에 재진입('결과 보기')했을 때의 init 응답.
|
||||
기대결과: 대화에 남지 않는 제출 내역(reject_reason·reject_price)이 실려 열람 카드를 그릴 수 있다."""
|
||||
token = await _login_token(client)
|
||||
sid = chat_seed["sids"]["P"]
|
||||
await client.post(
|
||||
f"/v1/negotiation/sessions/{sid}/reject",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
json={"reject_reason": "단종", "reject_price": 91000, "opinion": "후속 모델로 제안 가능합니다"},
|
||||
)
|
||||
body = (await _init(client, token, sid)).json()
|
||||
assert body["session_status"] == 5
|
||||
assert body["reject_reason"] == "단종"
|
||||
assert body["reject_price"] == 91000
|
||||
assert body["custom"]["opinion"] == "후속 모델로 제안 가능합니다"
|
||||
|
||||
|
||||
async def test_chat_init_forbidden_other_supplier(client, chat_seed):
|
||||
token = await _login_token(client)
|
||||
body = (await _init(client, token, chat_seed["sids"]["X"])).json()
|
||||
assert body["result"]["code"] == 1300 # NEGO_FORBIDDEN
|
||||
|
||||
|
||||
async def test_chat_init_vat_mode_unified_shows_excluded(client, chat_seed, db_engine):
|
||||
"""검증: 부가세 전체 통일 회사(features.vat_mode=unified_excluded)의 세션 채팅 init.
|
||||
기대결과: 상품에 vat_yn=true 잔존값이 있어도 item_vat_yn=False — 프론트가 'VAT별도'로 고정 표기."""
|
||||
import json
|
||||
|
||||
company_id = uuid.uuid4()
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text("INSERT INTO company.companies (company_id, name, status, settings) VALUES (:c, :n, 1, CAST(:s AS JSONB))"),
|
||||
{"c": company_id, "n": f"{MARK}VAT통일사", "s": json.dumps({"features": {"vat_mode": "unified_excluded"}})},
|
||||
)
|
||||
await conn.execute(
|
||||
text("UPDATE partner.suppliers SET company_id = :c WHERE supplier_id = :sid"),
|
||||
{"c": company_id, "sid": chat_seed["supplier_id"]},
|
||||
)
|
||||
await conn.execute(
|
||||
text("UPDATE partner.items SET vat_yn = true WHERE item_id = (SELECT item_id FROM negotiation.sessions WHERE session_id = :s)"),
|
||||
{"s": chat_seed["sids"]["P"]},
|
||||
)
|
||||
try:
|
||||
token = await _login_token(client)
|
||||
body = (await _init(client, token, chat_seed["sids"]["P"])).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["item_vat_yn"] is False
|
||||
finally:
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(text("DELETE FROM company.companies WHERE company_id = :c"), {"c": company_id})
|
||||
|
||||
|
||||
# ---- messages (오프닝 seed) -------------------------------------------------
|
||||
async def test_messages_seeds_opening(client, chat_seed):
|
||||
token = await _login_token(client)
|
||||
@ -397,28 +351,23 @@ async def test_send_blocked_when_prev_turn_pending(client, chat_seed, db_engine)
|
||||
|
||||
|
||||
async def test_init_marks_expired_created_as_not_participated(client, chat_seed, db_engine):
|
||||
"""검증: 마감시간이 지난 협상생성 세션으로 채팅 진입.
|
||||
기대결과: DB 상태가 미참여(4)로 정리되고, init 자체는 열람용으로 성공한다."""
|
||||
token = await _login_token(client)
|
||||
sid, qid = chat_seed["sids"]["C"], chat_seed["qids"]["C"] # 협상생성(1)
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(text("UPDATE quotation.quotations SET end_time = now() - make_interval(hours => 1) WHERE qt_id = :qid"), {"qid": qid})
|
||||
body = (await _init(client, token, sid)).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["session_status"] == 4
|
||||
assert await _session_status(db_engine, sid) == 4 # DB 도 미참여로 전이
|
||||
# 마감된 협상생성은 DB 상 미참여로 정리되고, 미참여는 진입 불가라 init 은 에러로 막는다.
|
||||
assert body["result"]["code"] == 1301 # NEGO_NOT_PARTICIPABLE
|
||||
assert await _session_status(db_engine, sid) == 4 # DB 는 미참여로 전이됨
|
||||
|
||||
|
||||
async def test_init_allows_viewing_rejected_session(client, chat_seed, db_engine):
|
||||
"""검증: 협상거부(5)로 끝난 세션에 '결과 보기'로 재진입.
|
||||
기대결과: init 성공(열람 허용) — 대화 재개는 send 가 협상중만 허용해 막는다."""
|
||||
async def test_init_blocks_rejected_session(client, chat_seed, db_engine):
|
||||
token = await _login_token(client)
|
||||
sid = chat_seed["sids"]["P"]
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(text("UPDATE negotiation.sessions SET status = 5 WHERE session_id = :sid"), {"sid": sid}) # 협상거부
|
||||
body = (await _init(client, token, sid)).json()
|
||||
assert body["result"]["success"] is True and body["session_status"] == 5
|
||||
assert (await _send(client, token, sid, "네")).json()["result"]["code"] == 1400 # CHAT_NOT_IN_PROGRESS
|
||||
assert body["result"]["code"] == 1301 # NEGO_NOT_PARTICIPABLE — 거부 세션 진입 차단
|
||||
|
||||
|
||||
# ---- 순수 헬퍼 단위 테스트 (DB 불필요, ChatService @staticmethod) ----------
|
||||
|
||||
@ -16,10 +16,45 @@ TEST_SUPPLIER_NAME = "파이테스트협상공급사"
|
||||
MARK = "PYTESTNEGO-" # 시드 식별용 prefix (item code / qt number)
|
||||
|
||||
|
||||
async def _seed_case(conn, code, sess_st, qt_type, hrs, quote_st, sup):
|
||||
"""상품·견적·세션 1세트 시드. 코드/견적번호에 MARK prefix 를 달아 cleanup 이 함께 지운다.
|
||||
hrs 는 마감(quotation.end_time)까지의 시간 — 음수면 이미 마감시간이 지난 건. 반환: (session_id, qt_id)."""
|
||||
@pytest_asyncio.fixture
|
||||
async def nego_seed(db_engine):
|
||||
"""공급사 + 유저 + 세션/견적 3건(본인) + 1건(타 공급사) 시드. 세션/견적 id 를 반환."""
|
||||
supplier_id = uuid.uuid4()
|
||||
other_supplier_id = uuid.uuid4()
|
||||
pw_hash = bcrypt.hashpw(TEST_PW.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
# (code, session.status, qt_type, 마감까지 시간(h), quotation.status, 소속 공급사)
|
||||
specs = [
|
||||
("A", 1, 2, 2, 1, supplier_id), # 협상생성 / 재견적 / +2h / 견적생성
|
||||
("B", 2, 1, 1, 2, supplier_id), # 협상중 / 재협상 / +1h / 견적진행중
|
||||
("C", 3, 2, 3, 2, supplier_id), # 협상완료 / 재견적 / +3h / 견적진행중
|
||||
("X", 1, 1, 1, 1, other_supplier_id), # 타 공급사 → 목록/참여에서 제외/차단
|
||||
]
|
||||
sids, qids = {}, {}
|
||||
|
||||
async def _cleanup(conn):
|
||||
await conn.execute(text(f"DELETE FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%'"))
|
||||
await conn.execute(text(f"DELETE FROM quotation.quotations WHERE number LIKE '{MARK}%'"))
|
||||
await conn.execute(text(f"DELETE FROM partner.items WHERE code LIKE '{MARK}%'"))
|
||||
await conn.execute(text("DELETE FROM supplier.supplier_users WHERE id = :id"), {"id": TEST_LOGIN_ID})
|
||||
await conn.execute(text("DELETE FROM partner.suppliers WHERE name = :n"), {"n": TEST_SUPPLIER_NAME})
|
||||
|
||||
async with db_engine.begin() as conn:
|
||||
await _cleanup(conn)
|
||||
await conn.execute(
|
||||
text("INSERT INTO partner.suppliers (supplier_id, company_id, user_id, name) VALUES (:sid, gen_random_uuid(), gen_random_uuid(), :name)"),
|
||||
{"sid": supplier_id, "name": TEST_SUPPLIER_NAME},
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO supplier.supplier_users (supplier_id, id, password, name, last_accessed_at, status, role) "
|
||||
"VALUES (:sid, :id, :pw, '협상담당자', now(), 1, 1)"
|
||||
),
|
||||
{"sid": supplier_id, "id": TEST_LOGIN_ID, "pw": pw_hash},
|
||||
)
|
||||
for code, sess_st, qt_type, hrs, quote_st, sup in specs:
|
||||
item_id, qt_id, session_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
|
||||
sids[code], qids[code] = session_id, qt_id
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) "
|
||||
@ -42,53 +77,6 @@ async def _seed_case(conn, code, sess_st, qt_type, hrs, quote_st, sup):
|
||||
),
|
||||
{"sesid": session_id, "qid": qt_id, "iid": item_id, "sup": sup, "qtn": f"{MARK}{code}", "qtt": qt_type, "st": sess_st},
|
||||
)
|
||||
return session_id, qt_id
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def nego_seed(db_engine):
|
||||
"""공급사 + 유저 + 세션/견적 3건(본인) + 1건(타 공급사) 시드. 세션/견적 id 를 반환."""
|
||||
supplier_id = uuid.uuid4()
|
||||
other_supplier_id = uuid.uuid4()
|
||||
pw_hash = bcrypt.hashpw(TEST_PW.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
# (code, session.status, qt_type, 마감까지 시간(h), quotation.status, 소속 공급사)
|
||||
specs = [
|
||||
("A", 1, 2, 2, 1, supplier_id), # 협상생성 / 재견적 / +2h / 견적생성
|
||||
("B", 2, 1, 1, 2, supplier_id), # 협상중 / 재협상 / +1h / 견적진행중
|
||||
("C", 3, 2, 3, 2, supplier_id), # 협상완료 / 재견적 / +3h / 견적진행중
|
||||
("X", 1, 1, 1, 1, other_supplier_id), # 타 공급사 → 목록/참여에서 제외/차단
|
||||
]
|
||||
sids, qids = {}, {}
|
||||
|
||||
async def _cleanup(conn):
|
||||
# 대화는 세션보다 먼저 지운다(세션이 사라지면 대상을 못 고른다).
|
||||
await conn.execute(text(
|
||||
f"DELETE FROM negotiation.chats WHERE session_id IN "
|
||||
f"(SELECT session_id FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%')"
|
||||
))
|
||||
await conn.execute(text(f"DELETE FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%'"))
|
||||
await conn.execute(text(f"DELETE FROM quotation.quotations WHERE number LIKE '{MARK}%'"))
|
||||
await conn.execute(text(f"DELETE FROM partner.items WHERE code LIKE '{MARK}%'"))
|
||||
await conn.execute(text("DELETE FROM supplier.supplier_users WHERE id = :id"), {"id": TEST_LOGIN_ID})
|
||||
await conn.execute(text("DELETE FROM partner.suppliers WHERE name = :n"), {"n": TEST_SUPPLIER_NAME})
|
||||
|
||||
async with db_engine.begin() as conn:
|
||||
await _cleanup(conn)
|
||||
await conn.execute(
|
||||
text("INSERT INTO partner.suppliers (supplier_id, company_id, user_id, name) VALUES (:sid, gen_random_uuid(), gen_random_uuid(), :name)"),
|
||||
{"sid": supplier_id, "name": TEST_SUPPLIER_NAME},
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO supplier.supplier_users (supplier_id, id, password, name, last_accessed_at, status, role) "
|
||||
"VALUES (:sid, :id, :pw, '협상담당자', now(), 1, 1)"
|
||||
),
|
||||
{"sid": supplier_id, "id": TEST_LOGIN_ID, "pw": pw_hash},
|
||||
)
|
||||
for spec in specs:
|
||||
code = spec[0]
|
||||
sids[code], qids[code] = await _seed_case(conn, *spec)
|
||||
|
||||
yield {"supplier_id": supplier_id, "sids": sids, "qids": qids}
|
||||
|
||||
@ -153,87 +141,18 @@ async def test_list_filter_status(client, nego_seed):
|
||||
assert body["total"] == 1 and body["items"][0]["item_code"] == f"{MARK}B"
|
||||
|
||||
|
||||
async def test_list_shows_closed_quotation_created_session_as_not_participated(client, db_engine, nego_seed):
|
||||
"""검증: 견적이 마감(3)된 뒤에도 세션이 협상생성(1)으로 남아 있는 건(마감 일괄정리 이후 생성 등).
|
||||
기대결과: 목록 상태는 미참여(4) — '협상 대기'로 새지 않고, status=1 필터에서도 빠지고 status=4 필터에 잡힌다."""
|
||||
async with db_engine.begin() as conn:
|
||||
await _seed_case(conn, "CLOSED1", 1, 2, -1, 3, nego_seed["supplier_id"])
|
||||
token = await _login_token(client)
|
||||
|
||||
listed = next(i for i in (await _list(client, token)).json()["items"] if i["item_code"] == f"{MARK}CLOSED1")
|
||||
assert listed["session_status"] == 4
|
||||
|
||||
waiting = (await _list(client, token, status=1)).json()
|
||||
assert waiting["total"] == 1 and {i["item_code"] for i in waiting["items"]} == {f"{MARK}A"}
|
||||
assert f"{MARK}CLOSED1" in {i["item_code"] for i in (await _list(client, token, status=4)).json()["items"]}
|
||||
|
||||
|
||||
async def test_list_shows_deadline_passed_created_session_as_not_participated(client, db_engine, nego_seed):
|
||||
"""검증: 견적은 아직 진행중(2)인데 마감시간(end_time)만 지난 협상생성 세션.
|
||||
기대결과: 미참여(4) — 참여/입장이 막히는 건이라 목록도 같은 상태로 보인다(DB 값은 그대로)."""
|
||||
async with db_engine.begin() as conn:
|
||||
session_id, _ = await _seed_case(conn, "OVERDUE", 1, 2, -3, 2, nego_seed["supplier_id"])
|
||||
token = await _login_token(client)
|
||||
|
||||
listed = next(i for i in (await _list(client, token)).json()["items"] if i["item_code"] == f"{MARK}OVERDUE")
|
||||
assert listed["session_status"] == 4
|
||||
assert await _session_status(db_engine, session_id) == 1 # 목록은 파생 표시만, 쓰기는 하지 않는다
|
||||
|
||||
|
||||
async def test_list_marks_stale_round_not_renegotiable(client, db_engine, nego_seed):
|
||||
"""검증: 개찰(결렬) 마감된 1차 견적에 2차가 이미 생성돼 있는 체인.
|
||||
기대결과: renegotiable False — 다음 라운드가 있으면 재협상 요청 대상이 아니다(체인 최대 차수 판정)."""
|
||||
async with db_engine.begin() as conn:
|
||||
await _seed_case(conn, "CHAIN", 3, 2, -2, 3, nego_seed["supplier_id"])
|
||||
await conn.execute(text(
|
||||
f"UPDATE quotation.quotations SET close_reason = 5 WHERE number = '{MARK}CHAIN'"))
|
||||
# 같은 견적번호의 2차 — 번호가 같아야 체인으로 묶인다.
|
||||
await conn.execute(text(
|
||||
"INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, round, start_time, end_time) "
|
||||
f"VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), '견적 CHAIN 2차', '{MARK}CHAIN', 2, 2, 2, now(), now() + make_interval(hours => 2))"))
|
||||
token = await _login_token(client)
|
||||
listed = next(i for i in (await _list(client, token)).json()["items"] if i["item_code"] == f"{MARK}CHAIN")
|
||||
assert listed["result"] == 3 and listed["renegotiable"] is False
|
||||
|
||||
|
||||
async def test_list_has_chat_flags_sessions_with_history(client, db_engine, nego_seed):
|
||||
"""검증: 대화 이력이 있는 세션과 없는 세션의 has_chat.
|
||||
기대결과: 이력 있는 건만 True — 종료 건의 '결과 보기' 노출이 이 값으로 갈린다."""
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text("INSERT INTO negotiation.chats (session_id, seq, sender, target_price) VALUES (:sid, 1, 1, 0)"),
|
||||
{"sid": nego_seed["sids"]["C"]},
|
||||
)
|
||||
token = await _login_token(client)
|
||||
by_code = {i["item_code"]: i["has_chat"] for i in (await _list(client, token)).json()["items"]}
|
||||
assert by_code[f"{MARK}C"] is True
|
||||
assert by_code[f"{MARK}A"] is False
|
||||
|
||||
|
||||
async def test_list_filter_qt_type(client, nego_seed):
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, qt_type=2)).json()
|
||||
assert {i["item_code"] for i in body["items"]} == {f"{MARK}A", f"{MARK}C"}
|
||||
|
||||
|
||||
async def test_list_default_sort_groups_actionable_first(client, nego_seed):
|
||||
# 기본 정렬(order 미지정): '할 일'(협상생성 A·협상중 B) 우선 → 마감 임박순, 종료(협상완료 C)는 하단.
|
||||
async def test_list_order_by_quotation_end_time(client, nego_seed):
|
||||
token = await _login_token(client)
|
||||
default = [i["item_code"] for i in (await _list(client, token)).json()["items"]]
|
||||
# 액션 그룹 임박순(B +1h → A +2h) 뒤에 종료(C). C 는 마감이 가장 멀어도(+3h) 최하단 고정.
|
||||
assert default == [f"{MARK}B", f"{MARK}A", f"{MARK}C"]
|
||||
|
||||
|
||||
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"]
|
||||
asc = (await _list(client, token, order="asc")).json()["items"]
|
||||
desc = (await _list(client, token, order="desc")).json()["items"]
|
||||
assert asc[0]["item_code"] == f"{MARK}B" # +1h 가 가장 임박
|
||||
assert desc[0]["item_code"] == f"{MARK}C" # +3h 가 가장 멈
|
||||
|
||||
|
||||
async def test_list_pagination(client, nego_seed):
|
||||
@ -246,56 +165,6 @@ async def test_list_requires_auth(client):
|
||||
assert (await client.get("/v1/negotiation/sessions")).status_code in (401, 403)
|
||||
|
||||
|
||||
# ---- 검색(keyword) ----------------------------------------------------------
|
||||
async def test_search_by_qt_number_and_item_code(client, nego_seed):
|
||||
"""검증: 견적번호/상품코드가 같은 값(PYTESTNEGO-B)으로 검색.
|
||||
기대결과: B 1건만, total 도 1(카운트도 같은 필터 적용)."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, keyword=f"{MARK}B")).json()
|
||||
assert body["total"] == 1
|
||||
assert [i["item_code"] for i in body["items"]] == [f"{MARK}B"]
|
||||
|
||||
|
||||
async def test_search_by_item_name(client, nego_seed):
|
||||
"""검증: 상품명 일부('상품 A')로 검색.
|
||||
기대결과: A 1건만."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, keyword="상품 A")).json()
|
||||
assert {i["item_code"] for i in body["items"]} == {f"{MARK}A"}
|
||||
|
||||
|
||||
async def test_search_prefix_matches_all_own(client, nego_seed):
|
||||
"""검증: 공통 prefix(PYTESTNEGO)로 검색.
|
||||
기대결과: 본인 공급사 3건 전부(타 공급사 X 는 제외 유지)."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, keyword=MARK.rstrip("-"))).json()
|
||||
assert body["total"] == 3
|
||||
|
||||
|
||||
async def test_search_case_insensitive(client, nego_seed):
|
||||
"""검증: 소문자로 검색(pytestnego-c).
|
||||
기대결과: ILIKE 라 대소문자 무시하고 C 매칭."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, keyword=f"{MARK}c".lower())).json()
|
||||
assert {i["item_code"] for i in body["items"]} == {f"{MARK}C"}
|
||||
|
||||
|
||||
async def test_search_no_match_returns_empty(client, nego_seed):
|
||||
"""검증: 어디에도 없는 검색어.
|
||||
기대결과: 0건, total 0."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, keyword="존재하지않는검색어zzz")).json()
|
||||
assert body["total"] == 0 and body["items"] == []
|
||||
|
||||
|
||||
async def test_search_wildcard_is_escaped(client, nego_seed):
|
||||
"""검증: ILIKE 와일드카드('%')를 그대로 검색 — 패턴으로 새면 전건 매칭될 위험.
|
||||
기대결과: escape 되어 리터럴 '%' 로 취급 → 매칭 0건."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, keyword="%")).json()
|
||||
assert body["total"] == 0
|
||||
|
||||
|
||||
# ---- 참여 -------------------------------------------------------------------
|
||||
async def test_participate_success(client, nego_seed, db_engine):
|
||||
token = await _login_token(client)
|
||||
@ -385,65 +254,6 @@ async def test_reject_success(client, nego_seed, db_engine):
|
||||
assert status == 5 and reason == "단종 상품입니다" # REJECTED + 사유 저장
|
||||
|
||||
|
||||
async def test_reject_with_price_and_opinion(client, nego_seed, db_engine):
|
||||
# 채팅 내 협상 거부 경로 — 사유 외에 공급 희망 가격과 의견까지 함께 남긴다.
|
||||
token = await _login_token(client)
|
||||
sid = nego_seed["sids"]["B"]
|
||||
r = await client.post(
|
||||
f"/v1/negotiation/sessions/{sid}/reject",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
json={"reject_reason": "품절", "reject_price": 88000, "opinion": "대체품으로 재견적 부탁드립니다"},
|
||||
)
|
||||
assert r.json()["result"]["success"] is True
|
||||
async with db_engine.begin() as conn:
|
||||
row = (await conn.execute(
|
||||
text("SELECT status, reject_reason, reject_price, custom FROM negotiation.sessions WHERE session_id = :sid"),
|
||||
{"sid": sid},
|
||||
)).first()
|
||||
assert row.status == 5 and row.reject_reason == "품절"
|
||||
assert row.reject_price == 88000
|
||||
assert row.custom["opinion"] == "대체품으로 재견적 부탁드립니다"
|
||||
|
||||
|
||||
async def test_reject_without_price_keeps_null(client, nego_seed, db_engine):
|
||||
# 목록 거부 경로 — 가격이 없으면 reject_price 를 건드리지 않는다.
|
||||
token = await _login_token(client)
|
||||
sid = nego_seed["sids"]["B"]
|
||||
r = await _reject(client, token, sid, "단종")
|
||||
assert r.json()["result"]["success"] is True
|
||||
async with db_engine.begin() as conn:
|
||||
row = (await conn.execute(
|
||||
text("SELECT reject_price, custom FROM negotiation.sessions WHERE session_id = :sid"),
|
||||
{"sid": sid},
|
||||
)).first()
|
||||
assert row.reject_price is None and row.custom is None
|
||||
|
||||
|
||||
async def test_list_returns_reject_detail(client, nego_seed):
|
||||
# 거부 제출 내역은 대화에 남지 않는다 — 목록이 사유·희망가를 실어야 '거부 내역'을 열람할 수 있다.
|
||||
token = await _login_token(client)
|
||||
sid = nego_seed["sids"]["B"]
|
||||
await client.post(
|
||||
f"/v1/negotiation/sessions/{sid}/reject",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
json={"reject_reason": "품절", "reject_price": 77000, "opinion": "재고 확보 후 연락드리겠습니다"},
|
||||
)
|
||||
items = (await _list(client, token)).json()["items"]
|
||||
row = next(i for i in items if i["session_id"] == str(sid))
|
||||
assert row["reject_reason"] == "품절"
|
||||
assert row["reject_price"] == 77000
|
||||
assert row["custom"]["opinion"] == "재고 확보 후 연락드리겠습니다"
|
||||
|
||||
|
||||
async def test_list_reject_detail_empty_for_active(client, nego_seed):
|
||||
# 거부 건이 아니면 빈 값 — 프론트가 '거부 내역' 버튼 노출을 상태로만 판단하므로 값이 새면 안 된다.
|
||||
token = await _login_token(client)
|
||||
items = (await _list(client, token)).json()["items"]
|
||||
row = next(i for i in items if i["session_id"] == str(nego_seed["sids"]["A"]))
|
||||
assert row["reject_reason"] == ""
|
||||
assert row.get("reject_price") is None
|
||||
|
||||
|
||||
async def test_reject_empty_reason(client, nego_seed):
|
||||
token = await _login_token(client)
|
||||
r = await _reject(client, token, nego_seed["sids"]["B"], " ") # 공백만 → 사유 없음
|
||||
@ -472,76 +282,3 @@ async def test_reject_requires_auth(client, nego_seed):
|
||||
sid = nego_seed["sids"]["B"]
|
||||
r = await client.post(f"/v1/negotiation/sessions/{sid}/reject", json={"reject_reason": "사유"})
|
||||
assert r.status_code in (401, 403)
|
||||
|
||||
|
||||
# ---- 결과 필터(result) ------------------------------------------------------
|
||||
# 마감(CLOSED) + 마감사유/낙찰자로 낙찰(1)·미낙찰(2)·결렬(3)을 만들고 result= 로 거른다.
|
||||
# nego_seed 의 공급사/로그인을 재사용하고, MARK prefix 라 픽스처 teardown 이 함께 정리한다.
|
||||
async def _seed_result_row(engine, *, supplier_id, code, close_reason, winner_id):
|
||||
import uuid as _uuid
|
||||
item_id, qt_id, session_id = _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4()
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text("INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) "
|
||||
"VALUES (:iid, gen_random_uuid(), gen_random_uuid(), :name, :code, 'M', '제조사')"),
|
||||
{"iid": item_id, "name": f"상품 {code}", "code": f"{MARK}{code}"},
|
||||
)
|
||||
await conn.execute(
|
||||
text("INSERT INTO quotation.quotations "
|
||||
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, close_reason, "
|
||||
" preferred_sp_id, round, start_time, end_time) VALUES "
|
||||
"(:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, 2, 3, :cr, "
|
||||
" :win, 1, now() - make_interval(hours => 2), now() - make_interval(hours => 1))"),
|
||||
{"qid": qt_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "cr": close_reason, "win": winner_id},
|
||||
)
|
||||
await conn.execute(
|
||||
text("INSERT INTO negotiation.sessions "
|
||||
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
|
||||
" target_price, status, bid_price, end_time) VALUES "
|
||||
"(:sid, :qid, :iid, :sup, :num, 1, 2, 100000, 3, 95000, now() - make_interval(hours => 1))"),
|
||||
{"sid": session_id, "qid": qt_id, "iid": item_id, "sup": supplier_id, "num": f"{MARK}{code}"},
|
||||
)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def result_rows(nego_seed, db_engine):
|
||||
"""nego_seed 공급사에 낙찰/미낙찰/결렬 각 1건을 추가한다(개찰 5=OPEN_PRICE, 1=AWARDED)."""
|
||||
sup = nego_seed["supplier_id"]
|
||||
await _seed_result_row(db_engine, supplier_id=sup, code="RWON", close_reason=1, winner_id=sup) # 낙찰(나)
|
||||
await _seed_result_row(db_engine, supplier_id=sup, code="RLOST", close_reason=1, winner_id=uuid.uuid4()) # 미낙찰(남)
|
||||
await _seed_result_row(db_engine, supplier_id=sup, code="ROPEN", close_reason=5, winner_id=None) # 결렬(개찰)
|
||||
return nego_seed
|
||||
|
||||
|
||||
async def test_result_filter_won(client, result_rows):
|
||||
"""검증: result=1(낙찰)로 필터. 기대결과: 낙찰 건만, total=1."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, result=1)).json()
|
||||
assert body["total"] == 1
|
||||
assert body["items"][0]["item_code"] == f"{MARK}RWON"
|
||||
assert body["items"][0]["result"] == 1
|
||||
|
||||
|
||||
async def test_result_filter_lost(client, result_rows):
|
||||
"""검증: result=2(미낙찰)로 필터. 기대결과: 미낙찰 건만."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, result=2)).json()
|
||||
assert {i["item_code"] for i in body["items"]} == {f"{MARK}RLOST"}
|
||||
assert body["items"][0]["result"] == 2
|
||||
|
||||
|
||||
async def test_result_filter_open(client, result_rows):
|
||||
"""검증: result=3(결렬)로 필터. 기대결과: 개찰 결렬 건만 + 재협상 대상(renegotiable=True)."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, result=3)).json()
|
||||
assert {i["item_code"] for i in body["items"]} == {f"{MARK}ROPEN"}
|
||||
assert body["items"][0]["result"] == 3
|
||||
assert body["items"][0]["renegotiable"] is True
|
||||
|
||||
|
||||
async def test_result_filter_composes_with_paging(client, result_rows):
|
||||
"""검증: 결과 필터가 total(페이징)에 반영. 기대결과: result=1 이면 total=1(전체 목록과 별개)."""
|
||||
token = await _login_token(client)
|
||||
all_total = (await _list(client, token)).json()["total"]
|
||||
won_total = (await _list(client, token, result=1)).json()["total"]
|
||||
assert won_total == 1 and all_total > won_total
|
||||
|
||||
@ -1,215 +0,0 @@
|
||||
"""공급사 재협상 요청/철회(IMK #15) 포털 e2e — 요청 접수 + 철회.
|
||||
|
||||
담당자 심사(승인/반려)는 negodata 백엔드 몫이고, 여기(포털)는 공급사가
|
||||
sessions.custom.renegotiation 에 요청을 남기고(PENDING) 스스로 철회(CANCELED)하는 절반을 본다:
|
||||
· 개찰(OPEN_*) 마감 + 본인 마지막 라운드 세션 → 요청 기록(PENDING) + 담당자 알림
|
||||
· 낙찰(AWARDED) 건 → 요청 거부
|
||||
· 남의 공급사 세션 → 거부(FORBIDDEN)
|
||||
· 이미 대기 중인데 재요청 → 거부(중복 방지)
|
||||
· 대기 중 철회 → CANCELED, 이후 재요청 허용
|
||||
|
||||
dev negosium_db 를 그대로 쓰므로(APP_ENV=local) 전용 테스트 행만 시드하고 끝나면 지운다.
|
||||
"""
|
||||
import uuid
|
||||
|
||||
import bcrypt
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.enums import CloseReason, QuotationStatus, RenegotiationStatus, SessionStatus
|
||||
|
||||
TEST_LOGIN_ID = "pytest_renego_user"
|
||||
TEST_PW = "pytest1234"
|
||||
TEST_SUPPLIER_NAME = "파이테스트재협상공급사"
|
||||
MARK = "PYTESTRENEGO-" # 시드 식별용 prefix (item code / qt number)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def renego_seed(db_engine):
|
||||
"""공급사 + 로그인유저 + 재협상 후보 세션들을 시드하고 (supplier_id, sids, uids) 반환.
|
||||
|
||||
(code, quotation.status, close_reason, 소속 공급사) — 요청 자격은 견적 마감사유·소유로 갈린다.
|
||||
"""
|
||||
supplier_id = uuid.uuid4()
|
||||
other_supplier_id = uuid.uuid4()
|
||||
pw_hash = bcrypt.hashpw(TEST_PW.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
specs = [
|
||||
("OPEN", QuotationStatus.CLOSED.value, CloseReason.OPEN_PRICE.value, supplier_id), # 개찰 → 요청 가능
|
||||
("AWARD", QuotationStatus.CLOSED.value, CloseReason.AWARDED.value, supplier_id), # 낙찰 → 불가
|
||||
("OTHER", QuotationStatus.CLOSED.value, CloseReason.OPEN_PRICE.value, other_supplier_id), # 남의 공급사
|
||||
]
|
||||
sids, uids = {}, {}
|
||||
|
||||
async def _cleanup(conn):
|
||||
await conn.execute(text(f"DELETE FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%'"))
|
||||
await conn.execute(text(f"DELETE FROM company.notifications WHERE ref_qt_id IN "
|
||||
f"(SELECT qt_id FROM quotation.quotations WHERE number LIKE '{MARK}%')"))
|
||||
await conn.execute(text(f"DELETE FROM quotation.quotations WHERE number LIKE '{MARK}%'"))
|
||||
await conn.execute(text(f"DELETE FROM partner.items WHERE code LIKE '{MARK}%'"))
|
||||
await conn.execute(text("DELETE FROM supplier.supplier_users WHERE id = :id"), {"id": TEST_LOGIN_ID})
|
||||
await conn.execute(text("DELETE FROM partner.suppliers WHERE name = :n"), {"n": TEST_SUPPLIER_NAME})
|
||||
|
||||
async with db_engine.begin() as conn:
|
||||
await _cleanup(conn)
|
||||
await conn.execute(
|
||||
text("INSERT INTO partner.suppliers (supplier_id, company_id, user_id, name) "
|
||||
"VALUES (:sid, gen_random_uuid(), gen_random_uuid(), :name)"),
|
||||
{"sid": supplier_id, "name": TEST_SUPPLIER_NAME},
|
||||
)
|
||||
await conn.execute(
|
||||
text("INSERT INTO supplier.supplier_users (supplier_id, id, password, name, last_accessed_at, status, role) "
|
||||
"VALUES (:sid, :id, :pw, '협상담당자', now(), 1, 1)"),
|
||||
{"sid": supplier_id, "id": TEST_LOGIN_ID, "pw": pw_hash},
|
||||
)
|
||||
for code, quote_st, close_reason, sup in specs:
|
||||
item_id, qt_id, session_id, user_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
|
||||
sids[code], uids[code] = session_id, user_id
|
||||
await conn.execute(
|
||||
text("INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) "
|
||||
"VALUES (:iid, gen_random_uuid(), gen_random_uuid(), :name, :code, :model, '테스트제조사')"),
|
||||
{"iid": item_id, "name": f"상품 {code}", "code": f"{MARK}{code}", "model": f"MODEL-{code}"},
|
||||
)
|
||||
await conn.execute(
|
||||
text("INSERT INTO quotation.quotations "
|
||||
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, close_reason, "
|
||||
" round, start_time, end_time) VALUES "
|
||||
"(:qid, :uid, gen_random_uuid(), gen_random_uuid(), :name, :num, 2, :st, :cr, "
|
||||
" 1, now() - make_interval(hours => 2), now() - make_interval(hours => 1))"),
|
||||
{"qid": qt_id, "uid": user_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "st": quote_st, "cr": close_reason},
|
||||
)
|
||||
await conn.execute(
|
||||
text("INSERT INTO negotiation.sessions "
|
||||
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
|
||||
" target_price, status, bid_price, end_time) VALUES "
|
||||
"(:sesid, :qid, :iid, :sup, :qtn, 1, 2, 100000, :sst, 95000, now() - make_interval(hours => 1))"),
|
||||
{"sesid": session_id, "qid": qt_id, "iid": item_id, "sup": sup, "qtn": f"{MARK}{code}", "sst": SessionStatus.DONE.value},
|
||||
)
|
||||
|
||||
yield {"supplier_id": supplier_id, "sids": sids, "uids": uids}
|
||||
|
||||
async with db_engine.begin() as conn:
|
||||
await _cleanup(conn)
|
||||
|
||||
|
||||
async def _login_token(client):
|
||||
r = await client.post("/v1/auth/login", json={"id": TEST_LOGIN_ID, "pw": TEST_PW})
|
||||
return r.json()["access_token"]
|
||||
|
||||
|
||||
async def _request(client, token, session_id, *, reason="가격 재검토", desired_price=90000):
|
||||
return await client.post(
|
||||
f"/v1/negotiation/session/{session_id}/renegotiation",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
json={"reason": reason, "desired_price": desired_price},
|
||||
)
|
||||
|
||||
|
||||
async def _cancel(client, token, session_id):
|
||||
return await client.delete(
|
||||
f"/v1/negotiation/session/{session_id}/renegotiation",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
|
||||
|
||||
async def _renego(db_engine, session_id):
|
||||
async with db_engine.begin() as conn:
|
||||
row = (await conn.execute(
|
||||
text("SELECT custom FROM negotiation.sessions WHERE session_id = :sid"),
|
||||
{"sid": session_id},
|
||||
)).scalar()
|
||||
return (row or {}).get("renegotiation") or {}
|
||||
|
||||
|
||||
async def _notif_count(db_engine, qt_number):
|
||||
async with db_engine.begin() as conn:
|
||||
return (await conn.execute(
|
||||
text("SELECT count(*) FROM company.notifications WHERE ref_qt_id IN "
|
||||
"(SELECT qt_id FROM quotation.quotations WHERE number = :num)"),
|
||||
{"num": qt_number},
|
||||
)).scalar()
|
||||
|
||||
|
||||
# ---- 요청 -------------------------------------------------------------------
|
||||
async def test_request_records_pending(client, renego_seed, db_engine):
|
||||
"""검증: 개찰(OPEN_PRICE) 마감 + 본인 마지막 라운드 세션에 재협상 요청.
|
||||
기대결과: success + PENDING 기록(사유·희망가 저장) + 담당자 알림 1건."""
|
||||
token = await _login_token(client)
|
||||
sid = renego_seed["sids"]["OPEN"]
|
||||
|
||||
body = (await _request(client, token, sid, reason="원자재 인상 반영", desired_price=88000)).json()
|
||||
|
||||
assert body["result"]["success"] is True
|
||||
assert body["status"] == RenegotiationStatus.PENDING.value
|
||||
saved = await _renego(db_engine, sid)
|
||||
assert saved["status"] == RenegotiationStatus.PENDING.value
|
||||
assert saved["reason"] == "원자재 인상 반영"
|
||||
assert saved["desired_price"] == 88000
|
||||
assert await _notif_count(db_engine, f"{MARK}OPEN") == 1
|
||||
|
||||
|
||||
async def test_request_twice_blocked(client, renego_seed, db_engine):
|
||||
"""검증: 이미 대기(PENDING) 요청이 있는 세션에 다시 요청.
|
||||
기대결과: 2번째는 거부(중복 방지) + 상태는 여전히 PENDING 1건."""
|
||||
token = await _login_token(client)
|
||||
sid = renego_seed["sids"]["OPEN"]
|
||||
|
||||
first = (await _request(client, token, sid)).json()
|
||||
second = (await _request(client, token, sid)).json()
|
||||
|
||||
assert first["result"]["success"] is True
|
||||
assert second["result"]["success"] is False
|
||||
assert (await _renego(db_engine, sid))["status"] == RenegotiationStatus.PENDING.value
|
||||
|
||||
|
||||
async def test_request_blocked_on_awarded(client, renego_seed, db_engine):
|
||||
"""검증: 낙찰(AWARDED)로 마감된 건에 재협상 요청.
|
||||
기대결과: 거부(낙찰 건은 재협상 불가) + custom.renegotiation 미기록."""
|
||||
token = await _login_token(client)
|
||||
sid = renego_seed["sids"]["AWARD"]
|
||||
|
||||
body = (await _request(client, token, sid)).json()
|
||||
|
||||
assert body["result"]["success"] is False
|
||||
assert await _renego(db_engine, sid) == {}
|
||||
|
||||
|
||||
async def test_request_forbidden_other_supplier(client, renego_seed, db_engine):
|
||||
"""검증: 다른 공급사 소유 세션에 재협상 요청.
|
||||
기대결과: 거부 + custom.renegotiation 미기록(소유 가드)."""
|
||||
token = await _login_token(client)
|
||||
sid = renego_seed["sids"]["OTHER"]
|
||||
|
||||
body = (await _request(client, token, sid)).json()
|
||||
|
||||
assert body["result"]["success"] is False
|
||||
assert await _renego(db_engine, sid) == {}
|
||||
|
||||
|
||||
# ---- 철회 -------------------------------------------------------------------
|
||||
async def test_cancel_sets_canceled_and_allows_rerequest(client, renego_seed, db_engine):
|
||||
"""검증: 대기 중 요청을 철회한 뒤 다시 요청.
|
||||
기대결과: 철회 시 CANCELED → 재요청 시 다시 PENDING(철회 건은 재요청 허용)."""
|
||||
token = await _login_token(client)
|
||||
sid = renego_seed["sids"]["OPEN"]
|
||||
|
||||
await _request(client, token, sid)
|
||||
cancelled = (await _cancel(client, token, sid)).json()
|
||||
assert cancelled["result"]["success"] is True
|
||||
assert cancelled["status"] == RenegotiationStatus.CANCELED.value
|
||||
assert (await _renego(db_engine, sid))["status"] == RenegotiationStatus.CANCELED.value
|
||||
|
||||
again = (await _request(client, token, sid)).json()
|
||||
assert again["result"]["success"] is True
|
||||
assert (await _renego(db_engine, sid))["status"] == RenegotiationStatus.PENDING.value
|
||||
|
||||
|
||||
async def test_cancel_requires_pending(client, renego_seed, db_engine):
|
||||
"""검증: 대기 요청이 없는 세션에 철회 시도.
|
||||
기대결과: 거부(철회할 대기 요청 없음)."""
|
||||
token = await _login_token(client)
|
||||
sid = renego_seed["sids"]["OPEN"]
|
||||
|
||||
body = (await _cancel(client, token, sid)).json()
|
||||
|
||||
assert body["result"]["success"] is False
|
||||
@ -1,51 +0,0 @@
|
||||
"""공급사 관점 협상 결과 파생(SessionResult) 단위 테스트.
|
||||
|
||||
목록의 result 코드는 견적 마감상태·마감사유·낙찰자로 파생한다(DDL 무변경). 공급사가 이 배지로
|
||||
'내가 낙찰인지 / 결렬이라 재협상 요청 대상인지'를 구분한다. 결렬(3)만 renegotiable 과 짝을 이룬다.
|
||||
"""
|
||||
import uuid
|
||||
|
||||
from common.enums import CloseReason, QuotationStatus
|
||||
from services.negotiation_service import NegotiationService
|
||||
|
||||
_R = NegotiationService._to_result
|
||||
ME = uuid.uuid4()
|
||||
OTHER = uuid.uuid4()
|
||||
CLOSED = QuotationStatus.CLOSED.value
|
||||
|
||||
|
||||
def test_result_undecided_before_close():
|
||||
"""검증: 견적이 아직 마감 전(진행중)이면 결과 미정.
|
||||
기대결과: 0(미정)."""
|
||||
assert _R(QuotationStatus.IN_PROGRESS.value, None, None, ME) == 0
|
||||
|
||||
|
||||
def test_result_won_when_winner_is_me():
|
||||
"""검증: 낙찰(AWARDED) 마감 + 낙찰자가 나.
|
||||
기대결과: 1(낙찰)."""
|
||||
assert _R(CLOSED, CloseReason.AWARDED.value, ME, ME) == 1
|
||||
|
||||
|
||||
def test_result_lost_when_winner_is_other():
|
||||
"""검증: 낙찰 마감이지만 낙찰자가 남.
|
||||
기대결과: 2(미낙찰)."""
|
||||
assert _R(CLOSED, CloseReason.AWARDED.value, OTHER, ME) == 2
|
||||
|
||||
|
||||
def test_result_lost_when_awarded_without_winner_id():
|
||||
"""검증: 낙찰인데 낙찰자 id 가 비어 나와 대조 불가.
|
||||
기대결과: 2(미낙찰) — 낙찰이라 단정 못 하면 낙찰로 오인시키지 않는다."""
|
||||
assert _R(CLOSED, CloseReason.AWARDED.value, None, ME) == 2
|
||||
|
||||
|
||||
def test_result_open_is_renegotiable():
|
||||
"""검증: 개찰(OPEN_*) 4종으로 마감(낙찰자 미정=결렬).
|
||||
기대결과: 전부 3(결렬) — 재협상 요청 대상."""
|
||||
for cr in (CloseReason.OPEN_PRICE, CloseReason.OPEN_EQUAL, CloseReason.OPEN_NOSHOW, CloseReason.OPEN_REJECT):
|
||||
assert _R(CLOSED, cr.value, None, ME) == 3, cr
|
||||
|
||||
|
||||
def test_result_none_when_closed_without_reason():
|
||||
"""검증: 마감됐지만 close_reason 이 아직 없음(경계).
|
||||
기대결과: 0(미정) — 낙찰/결렬 어느 쪽도 아님."""
|
||||
assert _R(CLOSED, None, None, ME) == 0
|
||||
BIN
dev-settings.png
BIN
dev-settings.png
Binary file not shown.
|
Before Width: | Height: | Size: 116 KiB |
@ -1,214 +0,0 @@
|
||||
services:
|
||||
# ── 프론트 (React/Vite → 정적 빌드 → nginx) ──────────────────────────────
|
||||
negodata-front:
|
||||
build:
|
||||
context: ./negodata/front
|
||||
dockerfile: Dockerfile.prod
|
||||
container_name: negodata-front
|
||||
ports:
|
||||
- "${NEGODATA_FRONT_PORT:-30012}:80"
|
||||
depends_on:
|
||||
- negodata-backend # nginx 가 시작 시 upstream(negodata-backend) 이름을 해석해야 함
|
||||
restart: unless-stopped
|
||||
|
||||
negosium-front:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile.prod
|
||||
container_name: negosium-front
|
||||
ports:
|
||||
- "${NEGOSIUM_FRONT_PORT:-30010}:80"
|
||||
depends_on:
|
||||
- negosium-backend
|
||||
restart: unless-stopped
|
||||
|
||||
# ── 솔루션 랜딩 (React Router SSG → 정적 빌드 → nginx) ───────────────────
|
||||
landing:
|
||||
build:
|
||||
context: ./landing
|
||||
dockerfile: Dockerfile.prod
|
||||
container_name: negosium-landing
|
||||
ports:
|
||||
- "${LANDING_PORT:-30013}:80"
|
||||
restart: unless-stopped
|
||||
|
||||
# ── 백엔드 (FastAPI, 기존 Dockerfile) ────────────────────────────────────
|
||||
negodata-backend:
|
||||
build: ./negodata/backend
|
||||
container_name: negodata-backend
|
||||
environment:
|
||||
APP_ENV: prod
|
||||
SCHEDULER_ENABLED: "1" # 견적 자동마감 크론(process_count=1 단일 워커라 중복 없음)
|
||||
PYTHONUNBUFFERED: "1"
|
||||
LPS_BASE_URL: http://lps-api:9600 # 최저가 검색요청 enqueue — 같은 compose 망의 lps-api 컨테이너(미설정 시 localhost:9600 → 연결실패)
|
||||
# LPS 읽기 DB(lps_db)는 config.prod.toml 의 [LpsDBConfig](172.30.1.36/o2o_db_admin) 이 담당 → 별도 env 불필요
|
||||
DB_HOST: ${DB_HOST} # toml 의 127.0.0.1 을 외부 DB 로 override
|
||||
DB_PORT: ${DB_PORT:-5432}
|
||||
DB_USER: ${DB_USER}
|
||||
DB_PASSWORD: ${DB_PASSWORD}
|
||||
DB_NAME: ${DB_NAME:-negosium_db}
|
||||
volumes:
|
||||
- ./negodata/backend/config/config.prod.toml:/app/config/config.prod.toml:ro
|
||||
# 외부 비노출 — negodata-front 의 nginx 가 /v1 을 내부망으로 프록시.
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway" # DB 가 이 서버 호스트면 DB_HOST=host.docker.internal
|
||||
restart: unless-stopped
|
||||
|
||||
negosium-backend:
|
||||
build: ./backend
|
||||
container_name: negosium-backend
|
||||
environment:
|
||||
APP_ENV: prod
|
||||
AGENT_BASE_URL: http://agent:9500 # 내부망으로 agent 호출
|
||||
PYTHONUNBUFFERED: "1"
|
||||
DB_HOST: ${DB_HOST}
|
||||
DB_PORT: ${DB_PORT:-5432}
|
||||
DB_USER: ${DB_USER}
|
||||
DB_PASSWORD: ${DB_PASSWORD}
|
||||
DB_NAME: ${DB_NAME:-negosium_db}
|
||||
volumes:
|
||||
- ./backend/config/config.prod.toml:/app/config/config.prod.toml:ro
|
||||
# 외부 비노출 — negosium-front 의 nginx 가 /v1 을 내부망으로 프록시.
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
restart: unless-stopped
|
||||
|
||||
# ── 협상 에이전트 (Python, 내부 전용) ────────────────────────────────────
|
||||
agent:
|
||||
build: ./agent
|
||||
container_name: negosium-agent
|
||||
environment:
|
||||
APP_ENV: prod
|
||||
PYTHONUNBUFFERED: "1"
|
||||
DB_HOST: ${DB_HOST}
|
||||
DB_PORT: ${DB_PORT:-5432}
|
||||
DB_USER: ${DB_USER}
|
||||
DB_PASSWORD: ${DB_PASSWORD}
|
||||
DB_NAME: ${DB_NAME:-negosium_db}
|
||||
volumes:
|
||||
- ./agent/config/config.prod.toml:/app/config/config.prod.toml:ro
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
restart: unless-stopped
|
||||
|
||||
# ── 앵커링 값 자동 조정 배치 (negosium_db 공유, 포트 없음 — 상주 스케줄러) ──
|
||||
# 이미지는 config.{APP_ENV}.toml 을 읽는다(dev/prod 는 파일 없으면 기동 중단). DB/시크릿은
|
||||
# config.prod.toml(172.30.1.36) 에서 온다 — env(DB_*/REDIS_*) 를 설정하면 파일값을 override.
|
||||
anchoring:
|
||||
build: ./schedules/anchoring
|
||||
container_name: anchoring
|
||||
environment:
|
||||
APP_ENV: prod # → config.prod.toml 선택 (local 로 두면 빈 config.local 로 기동 실패)
|
||||
REDIS_HOST: anchoring-redis # 전용 캐시 컨테이너 사용(config 의 redis host 를 override)
|
||||
TZ: Asia/Seoul
|
||||
volumes:
|
||||
- ./schedules/anchoring/config.prod.toml:/app/config.prod.toml:ro # DB 접속·시크릿은 파일에서(마운트 필수)
|
||||
depends_on:
|
||||
- anchoring-redis
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
restart: unless-stopped
|
||||
logging: # 상주 배치 — 장기 운영 디스크 보호
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "5"
|
||||
|
||||
# 앵커링 조회 캐시 (anchoring 전용)
|
||||
anchoring-redis:
|
||||
image: redis:7-alpine
|
||||
container_name: anchoring-redis
|
||||
ports:
|
||||
- "127.0.0.1:6380:6379" # 호스트 로컬만 개방 (무인증 Redis). 6380 = 호스트 redis(6379)와 충돌 회피
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "5"
|
||||
|
||||
# ── LPS (인터넷 최저가 검색) ──────────────────────────────────
|
||||
# API(요청 접수) + 워커(크롤, Chromium+Xvfb).
|
||||
# 이미지는 APP_ENV=local 고정 → config.local.toml 을 읽는다. prod 실값(DB 172.30.1.36 /
|
||||
# o2o_db_admin / negosium_db + OpenAI·Naver·Decodo 시크릿)은 config.prod.toml 을 그 경로에
|
||||
# 마운트해 주입한다(다른 prod 서비스와 동일한 파일 기반 방식). DB_* env 는 주지 않는다 —
|
||||
# 주면 파일값을 빈 값/오타로 덮어써 인증 실패(예: 사용자 o2oadmin)한다.
|
||||
lps-api:
|
||||
build:
|
||||
context: ./lps
|
||||
dockerfile: Dockerfile
|
||||
container_name: lps-api
|
||||
environment:
|
||||
APP_ENV: local # 이미지 고정값 — 변경 금지(config.prod.toml 을 직접 읽지 않음)
|
||||
PYTHONUNBUFFERED: "1"
|
||||
PROCESS_COUNT: ${LPS_API_PROCESS_COUNT:-1}
|
||||
DB_CONNECTION_BUDGET: ${LPS_DB_CONNECTION_BUDGET:-40} # 전용 PG(max_connections≈100)면 90 근처로 상향
|
||||
volumes:
|
||||
- ./lps/config/config.prod.toml:/app/config/config.local.toml:ro # prod DB·시크릿 주입(APP_ENV=local 이 읽는 경로 덮어씀)
|
||||
ports:
|
||||
- "9600:9600"
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
labels:
|
||||
autoheal: "true" # HEALTHCHECK 실패 시 autoheal 이 재시작
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
lps-worker:
|
||||
build:
|
||||
context: ./lps
|
||||
dockerfile: Dockerfile.worker # Chromium + Xvfb (headless 는 안티봇에 탐지됨)
|
||||
container_name: lps-worker
|
||||
environment:
|
||||
APP_ENV: local # 이미지 고정값 — 변경 금지
|
||||
PYTHONUNBUFFERED: "1"
|
||||
WORKER_CONCURRENCY: "1" # 상품 동시 검색 수(워커별 브라우저 세트, Chrome 4×N)
|
||||
LPS_PROFILE_DIR: /profiles # Chrome 프로필을 영속 볼륨에 → 재시작해도 cf_clearance 유지
|
||||
# DB·시크릿(OpenAI/Naver/Decodo)은 아래 config.prod.toml 마운트에서 온다. env override 는 주지 않는다.
|
||||
volumes:
|
||||
- ./lps/config/config.prod.toml:/app/config/config.local.toml:ro # prod DB·시크릿 주입(APP_ENV=local 이 읽는 경로 덮어씀)
|
||||
- lps-profiles:/profiles # Chrome 프로필(쿠키) 영속
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
shm_size: "1gb" # Chrome 는 /dev/shm 을 많이 씀 — 부족하면 탭 크래시
|
||||
stop_grace_period: 75s # graceful 종료 유예 — 기본 10s 면 하던 잡 마무리 전에 SIGKILL
|
||||
labels:
|
||||
autoheal: "true" # 하트비트 HEALTHCHECK 실패(행/좀비) 시 autoheal 이 재시작
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# LPS 관리자 UI (정적 React → nginx). /v1·/healthz·/readyz 는 nginx 가 lps-api:9600 으로 프록시(동일 compose 망).
|
||||
lps-admin:
|
||||
build:
|
||||
context: ./lps-admin
|
||||
dockerfile: Dockerfile
|
||||
container_name: lps-admin
|
||||
ports:
|
||||
- "${LPS_ADMIN_PORT:-30014}:80"
|
||||
depends_on:
|
||||
- lps-api
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# HEALTHCHECK 실패 컨테이너 자동 재시작 — autoheal 라벨 붙은 컨테이너(lps-api/lps-worker)를 감시해 재시작.
|
||||
# docker.sock 마운트 = 도커 제어 권한이므로 신뢰 환경에서만 사용.
|
||||
autoheal:
|
||||
image: willfarrell/autoheal:latest
|
||||
container_name: autoheal
|
||||
environment:
|
||||
AUTOHEAL_CONTAINER_LABEL: autoheal
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
volumes:
|
||||
lps-profiles:
|
||||
@ -7,11 +7,8 @@
|
||||
# negosium 서버: http://localhost:9300/docs
|
||||
# negosium 프론트: http://localhost:3300
|
||||
# negodata 서버: http://localhost:9400/docs
|
||||
# 솔루션 랜딩: http://localhost:3100
|
||||
# agent 서버: http://localhost:9500/docs
|
||||
# anchoring 배치: 포트 없음 — 상주 스케줄러(격주 토 00:00 KST), docker logs anchoring 으로 확인
|
||||
# lps API: http://localhost:9600/docs
|
||||
# lps admin: http://localhost:3400 (nginx → /v1·/healthz 는 lps-api 로 프록시)
|
||||
#
|
||||
# DB 준비(최초 1회): postgres-init 의 SQL 을 대상 DB 에 적용한다.
|
||||
# psql -h <host> -p <port> -U <user> -f postgres-init/00-init.sql (스키마 전체: negosium_db + 도메인·learning·anchoring schema)
|
||||
@ -41,10 +38,6 @@ services:
|
||||
RELOAD: "1" # uvicorn --reload 활성 → 소스 저장 시 자동 재기동(재빌드 불필요)
|
||||
SCHEDULER_ENABLED: "1" # 마감 크론 활성(단일 워커라 중복 없음). 운영 다중 워커면 1개 프로세스에서만 1
|
||||
PYTHONUNBUFFERED: "1" # 컨테이너 로그 실시간 출력(stdout 버퍼링 끔)
|
||||
# ── LPS(인터넷 최저가) 연동 — 미설정이면 연동 비활성으로 조용히 동작 ──
|
||||
LPS_DB_HOST: host.docker.internal # lps_db 읽기전용(수집 배치·조회 API)
|
||||
LPS_BASE_URL: http://host.docker.internal:9600 # 검색요청 enqueue. lps-api 컨테이너 사용 시 http://lps-api:9600
|
||||
# LPS API guard 키는 negodata 의 config.local.toml [WebServerConfig].lps_api_key 로 관리(개발은 빈값=개방)
|
||||
volumes:
|
||||
- ./negodata/backend:/app # 호스트 소스 = 컨테이너 코드. 이게 있어야 수정이 즉시 반영됨
|
||||
ports:
|
||||
@ -64,17 +57,6 @@ services:
|
||||
- /app/node_modules
|
||||
restart: unless-stopped
|
||||
|
||||
# 솔루션 랜딩페이지 (react-router dev 서버. 배포는 `npm run build` 산출물 build/client 정적 서빙).
|
||||
landing:
|
||||
build: ./landing
|
||||
container_name: negosium-landing
|
||||
ports:
|
||||
- "3100:3100"
|
||||
volumes:
|
||||
- ./landing:/app
|
||||
- /app/node_modules
|
||||
restart: unless-stopped
|
||||
|
||||
# 협상 에이전트 (negosium_db 공유, learning 스키마 사용).
|
||||
agent:
|
||||
build: ./agent
|
||||
@ -82,7 +64,6 @@ services:
|
||||
environment:
|
||||
APP_ENV: local
|
||||
DB_HOST: host.docker.internal # 컨테이너→호스트 DB (config.local.toml의 127.0.0.1 override)
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY:-} # LLM 키 passthrough (호스트 env/.env → 컨테이너). 빈 값이면 toml 폴백
|
||||
ports:
|
||||
- "9500:9500"
|
||||
extra_hosts:
|
||||
@ -131,86 +112,3 @@ services:
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "5"
|
||||
|
||||
# LPS API (인터넷 최저가 검색 — 요청 접수/조회, lean). 설정·시크릿은 config.local.toml 하나(미커밋, 마운트).
|
||||
lps-api:
|
||||
build:
|
||||
context: ./lps
|
||||
dockerfile: Dockerfile
|
||||
container_name: lps-api
|
||||
environment:
|
||||
APP_ENV: local
|
||||
DB_HOST: ${LPS_DB_HOST-host.docker.internal} # 컨테이너→호스트 DB (config.local.toml 의 127.0.0.1 override)
|
||||
PYTHONUNBUFFERED: "1"
|
||||
volumes:
|
||||
- ./lps/config/config.local.toml:/app/config/config.local.toml:ro
|
||||
ports:
|
||||
- "${LPS_API_BIND:-0.0.0.0}:9600:9600" # prod 는 LPS_API_BIND=127.0.0.1 로 내부만 개방(리버스프록시 뒤)
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
labels:
|
||||
autoheal: "true" # HEALTHCHECK 실패 시 autoheal 이 재시작
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# LPS 워커 (크롤 — 헤드풀 Chromium+Xvfb, headless 는 안티봇에 탐지됨). config.local.toml 공유.
|
||||
lps-worker:
|
||||
build:
|
||||
context: ./lps
|
||||
dockerfile: Dockerfile.worker
|
||||
# google-chrome-stable(Linux)은 amd64 전용 → 이미지 자체가 amd64. arm64 맥에선 명시 없으면
|
||||
# arm64 로 빌드를 시도하다 Chrome 의존성에서 실패한다(Rosetta 로 에뮬 실행). prod(amd64)에선 무영향.
|
||||
platform: linux/amd64
|
||||
container_name: lps-worker
|
||||
environment:
|
||||
APP_ENV: local
|
||||
DB_HOST: ${LPS_DB_HOST-host.docker.internal} # 컨테이너→호스트 DB (config.local.toml 의 127.0.0.1 override)
|
||||
PYTHONUNBUFFERED: "1"
|
||||
volumes:
|
||||
- ./lps/config/config.local.toml:/app/config/config.local.toml:ro
|
||||
- lps-profiles:/profiles # Chrome 프로필(쿠키) 영속
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
shm_size: "1gb" # Chrome 는 /dev/shm 을 많이 씀 — 부족하면 탭 크래시
|
||||
stop_grace_period: 75s # graceful 종료 유예(worker shutdown_grace_sec=60 + 여유)
|
||||
labels:
|
||||
autoheal: "true" # 하트비트 실패(행/좀비) 시 autoheal 재시작
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# LPS 관리자 UI (정적 React → nginx). /v1·/healthz·/readyz 는 nginx 가 lps-api:9600 으로 프록시(앱은 상대경로 호출).
|
||||
lps-admin:
|
||||
build:
|
||||
context: ./lps-admin
|
||||
dockerfile: Dockerfile
|
||||
container_name: lps-admin
|
||||
ports:
|
||||
- "3400:80"
|
||||
depends_on:
|
||||
- lps-api
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# HEALTHCHECK 실패 컨테이너 자동 재시작 — compose 의 restart 는 '프로세스 종료'만 다루고
|
||||
# unhealthy 는 표시만 하므로, autoheal 라벨 붙은 컨테이너(lps-api/lps-worker)를 감시해 재시작한다.
|
||||
# docker.sock 마운트 = 도커 제어 권한이므로 신뢰 환경에서만 사용.
|
||||
autoheal:
|
||||
image: willfarrell/autoheal:latest
|
||||
container_name: autoheal
|
||||
environment:
|
||||
AUTOHEAL_CONTAINER_LABEL: autoheal
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
volumes:
|
||||
lps-profiles:
|
||||
|
||||
Binary file not shown.
@ -1,157 +0,0 @@
|
||||
import AppKit
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
|
||||
let output = CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "docs/AIO2O-요청사항-반영보고서.pdf"
|
||||
let W: CGFloat = 595, H: CGFloat = 842, M: CGFloat = 42
|
||||
let navy = NSColor(calibratedRed: 0.06, green: 0.08, blue: 0.16, alpha: 1)
|
||||
let ink = NSColor(calibratedRed: 0.11, green: 0.13, blue: 0.18, alpha: 1)
|
||||
let muted = NSColor(calibratedRed: 0.39, green: 0.43, blue: 0.50, alpha: 1)
|
||||
let paper = NSColor(calibratedRed: 0.98, green: 0.985, blue: 0.995, alpha: 1)
|
||||
let line = NSColor(calibratedRed: 0.86, green: 0.88, blue: 0.92, alpha: 1)
|
||||
let purple = NSColor(calibratedRed: 0.48, green: 0.25, blue: 0.92, alpha: 1)
|
||||
let green = NSColor(calibratedRed: 0.08, green: 0.60, blue: 0.37, alpha: 1)
|
||||
let orange = NSColor(calibratedRed: 0.94, green: 0.48, blue: 0.10, alpha: 1)
|
||||
let red = NSColor(calibratedRed: 0.85, green: 0.24, blue: 0.28, alpha: 1)
|
||||
let blue = NSColor(calibratedRed: 0.13, green: 0.39, blue: 0.92, alpha: 1)
|
||||
|
||||
func pr(_ r: CGRect) -> CGRect { CGRect(x: r.minX, y: H-r.maxY, width: r.width, height: r.height) }
|
||||
func font(_ s: CGFloat, _ w: NSFont.Weight = .regular) -> NSFont {
|
||||
NSFont(name: "Apple SD Gothic Neo", size: s) ?? .systemFont(ofSize: s, weight: w)
|
||||
}
|
||||
func style(_ s: CGFloat, _ c: NSColor = ink, _ w: NSFont.Weight = .regular,
|
||||
_ a: NSTextAlignment = .left, _ spacing: CGFloat = 2.5) -> [NSAttributedString.Key:Any] {
|
||||
let p = NSMutableParagraphStyle(); p.alignment = a; p.lineSpacing = spacing; p.lineBreakMode = .byWordWrapping
|
||||
return [.font:font(s,w), .foregroundColor:c, .paragraphStyle:p]
|
||||
}
|
||||
func text(_ t:String,_ r:CGRect,_ s:CGFloat=10,_ c:NSColor=ink,_ w:NSFont.Weight = .regular,
|
||||
_ a:NSTextAlignment = .left,_ spacing:CGFloat=2.5) {
|
||||
NSAttributedString(string:t,attributes:style(s,c,w,a,spacing)).draw(with:pr(r),options:[.usesLineFragmentOrigin,.usesFontLeading])
|
||||
}
|
||||
func box(_ r:CGRect,_ fill:NSColor = .white,_ stroke:NSColor? = line,_ radius:CGFloat=10) {
|
||||
let p=NSBezierPath(roundedRect:pr(r),xRadius:radius,yRadius:radius); fill.setFill(); p.fill()
|
||||
if let stroke { stroke.setStroke(); p.lineWidth=0.8; p.stroke() }
|
||||
}
|
||||
func pill(_ t:String,_ r:CGRect,_ c:NSColor) {
|
||||
box(r,c.withAlphaComponent(0.12),nil,r.height/2)
|
||||
text(t,CGRect(x:r.minX,y:r.minY+4,width:r.width,height:r.height-7),8.2,c,.semibold,.center,1)
|
||||
}
|
||||
func begin(_ ctx:CGContext,_ page:Int,_ title:String) {
|
||||
ctx.beginPDFPage(nil); ctx.saveGState(); NSGraphicsContext.saveGraphicsState()
|
||||
NSGraphicsContext.current=NSGraphicsContext(cgContext:ctx,flipped:false)
|
||||
paper.setFill(); NSBezierPath(rect:pr(CGRect(x:0,y:0,width:W,height:H))).fill()
|
||||
text(title,CGRect(x:M,y:30,width:420,height:16),7.5,muted,.medium)
|
||||
text(String(format:"%02d",page),CGRect(x:W-M-30,y:30,width:30,height:16),8,muted,.medium,.right)
|
||||
let p=NSBezierPath(); p.move(to:CGPoint(x:M,y:31)); p.line(to:CGPoint(x:W-M,y:31))
|
||||
line.setStroke(); p.lineWidth=0.7; p.stroke()
|
||||
}
|
||||
func end(_ ctx:CGContext) {
|
||||
NSGraphicsContext.restoreGraphicsState(); ctx.restoreGState(); ctx.endPDFPage()
|
||||
}
|
||||
func heading(_ n:String,_ t:String,_ sub:String) {
|
||||
pill(n,CGRect(x:M,y:54,width:34,height:24),purple)
|
||||
text(t,CGRect(x:86,y:49,width:465,height:30),21,navy,.bold)
|
||||
text(sub,CGRect(x:M,y:87,width:W-2*M,height:31),9.5,muted,.regular,.left,3)
|
||||
}
|
||||
func statusRow(_ no:String,_ title:String,_ body:String,_ status:String,_ c:NSColor,_ y:CGFloat,_ h:CGFloat=82) {
|
||||
box(CGRect(x:M,y:y,width:W-2*M,height:h),.white,line,9)
|
||||
pill(no,CGRect(x:M+12,y:y+13,width:28,height:20),c)
|
||||
text(title,CGRect(x:M+50,y:y+12,width:338,height:19),10.5,navy,.bold)
|
||||
pill(status,CGRect(x:W-M-102,y:y+12,width:90,height:21),c)
|
||||
text(body,CGRect(x:M+50,y:y+37,width:W-2*M-64,height:h-44),8.8,ink,.regular,.left,2.4)
|
||||
}
|
||||
func metric(_ value:String,_ label:String,_ x:CGFloat,_ c:NSColor) {
|
||||
box(CGRect(x:x,y:435,width:117,height:96),c.withAlphaComponent(0.08),c.withAlphaComponent(0.3),12)
|
||||
text(value,CGRect(x:x+8,y:454,width:101,height:32),25,c,.bold,.center)
|
||||
text(label,CGRect(x:x+8,y:493,width:101,height:20),9,muted,.medium,.center)
|
||||
}
|
||||
|
||||
var media=CGRect(x:0,y:0,width:W,height:H)
|
||||
guard let consumer=CGDataConsumer(url:URL(fileURLWithPath:output) as CFURL),
|
||||
let ctx=CGContext(consumer:consumer,mediaBox:&media,nil) else { fatalError("PDF 생성 실패") }
|
||||
|
||||
// 1. cover
|
||||
begin(ctx,1,"AIO2O · 요청사항 반영 보고서")
|
||||
box(CGRect(x:0,y:0,width:W,height:H),navy,nil,0)
|
||||
pill("IMPLEMENTATION REVIEW",CGRect(x:M,y:112,width:148,height:25),NSColor(calibratedRed:0.42,green:0.78,blue:1,alpha:1))
|
||||
text("AIO2O 테스트 및 요청사항\n반영 결과 보고서",CGRect(x:M,y:166,width:510,height:112),34,.white,.bold,.left,7)
|
||||
text("260727_AIO2O 테스트 및 요청사항.xlsx 기준\n현재 저장소 구현·커밋·검증 캡처 대조",CGRect(x:M,y:310,width:510,height:60),14,NSColor(calibratedWhite:0.78,alpha:1),.regular,.left,7)
|
||||
box(CGRect(x:M,y:435,width:W-2*M,height:176),NSColor.white.withAlphaComponent(0.07),NSColor.white.withAlphaComponent(0.12),16)
|
||||
text("결론",CGRect(x:M+22,y:458,width:460,height:25),13,.white,.bold)
|
||||
text("핵심 업무 흐름은 대부분 구현되었습니다. 견적 목록·상세, 재협상 접수, 목표가 자동계산, 인터넷 최저가, 종료 의견, 결렬폼 통일, VAT 별도 표기, 10원 반올림은 코드 근거가 확인됩니다.\n\n다만 절충안/자동 제안가의 업무 적정성, SG명·유통레벨의 최종 UX, 최저가 VAT 산식은 추가 확인이 필요합니다.",CGRect(x:M+22,y:495,width:W-2*M-44,height:96),11,NSColor(calibratedWhite:0.88,alpha:1),.regular,.left,5)
|
||||
text("작성일 2026.07.31 | 기준 브랜치 feature/negodata | HEAD 775984fe",CGRect(x:M,y:758,width:W-2*M,height:18),8.5,NSColor(calibratedWhite:0.60,alpha:1))
|
||||
end(ctx)
|
||||
|
||||
// 2. summary
|
||||
begin(ctx,2,"AIO2O · 요청사항 반영 보고서")
|
||||
heading("01","종합 요약","엑셀 RAW 시트의 24개 요청을 현재 저장소 상태로 재판정했습니다. 중복 요청은 원 요청 번호를 유지했습니다.")
|
||||
metric("18","완료·반영",M,green); metric("3","부분 반영",M+130,orange); metric("3","확인 필요",M+260,red); metric("24","전체 항목",M+390,blue)
|
||||
text("판정 기준",CGRect(x:M,y:566,width:507,height:24),13,navy,.bold)
|
||||
statusRow("A","완료·반영","사용자 화면과 처리 로직이 모두 확인되거나, 동일 기능을 제공하는 구현 및 검증 캡처가 존재합니다.","18건",green,603,60)
|
||||
statusRow("B","부분 반영","핵심 기능은 있으나 요청한 명칭·선택값·산식 중 일부가 다르거나 배포/운영 확인이 남았습니다.","3건",orange,675,60)
|
||||
statusRow("C","확인 필요","코드는 존재하지만 계산 결과의 업무 적정성을 확정할 수 없거나 요청 산식이 명시적으로 확인되지 않습니다.","3건",red,747,60)
|
||||
end(ctx)
|
||||
|
||||
// 3. system 1
|
||||
begin(ctx,3,"AIO2O · 요청사항 반영 보고서")
|
||||
heading("02","기본 시스템 반영 내역","견적 생성부터 협력사·최저가·협상 화면까지의 공통 요청입니다.")
|
||||
statusRow("01","견적관리 목록·상세/히스토리","견적 목록과 상세 드로어가 있으며, 상세의 채팅 탭·협상카드 탭이 세션 데이터를 연결합니다. 견적번호별 진행/완료 상태와 상세 확인 경로가 마련됐습니다.","완료",green,132)
|
||||
statusRow("02","재협상 접수 및 관리","공급사 포털에서 결렬 건 재협상 요청·철회가 가능하고, 구매자 화면에 재협상 요청 목록·검토 시트·승인/반려 및 알림이 구현됐습니다.","완료",green,226)
|
||||
statusRow("03","MD 제시가 용어·위치·판매가","‘MD’는 ‘구매담당자’로 통일했고 제시가/산정후보를 ‘3. 낙찰기준’으로 이동했습니다. 판매가 설정은 숨김 처리되어 요청 흐름과 일치합니다.","완료",green,320)
|
||||
statusRow("04","목표가 자동 산출","매입가 × (1 − 목표 네고율)로 구매담당자 제시가를 자동 입력합니다. 예: 10,000원, 2% → 9,800원. 프론트 자동계산과 백엔드 가격 처리 근거가 있습니다.","완료",green,414)
|
||||
statusRow("05","공급사/매입가 라벨 일원화","상품 및 견적 화면의 회사별 필드 라벨 설정을 연동해 ‘공급사=매입가’ 표기 정책을 적용할 수 있게 했습니다. 실제 운영 회사 설정값 확인은 필요합니다.","부분",orange,508)
|
||||
statusRow("06","인터넷 최저가 수집","15%에서 멈추던 Worker/큐 처리 문제를 수정하고, 몰별 결과·진행 상태·이력 화면을 재설계했습니다. 다만 요청 산식 ‘(상품가+배송비)/1.1’의 최종 대표값 적용은 코드에서 확정되지 않습니다.","부분",orange,602)
|
||||
statusRow("07","신규 상품 공급사 입력","신규 상품 등록 폼에 공급사 선택기를 추가하고 상품–공급사 매핑을 저장하도록 구현했습니다.","완료",green,696)
|
||||
end(ctx)
|
||||
|
||||
// 4. system 2
|
||||
begin(ctx,4,"AIO2O · 요청사항 반영 보고서")
|
||||
heading("03","협력사·협상 화면 반영","용어 통일, 종료 단계, 가격 표기와 협상 지표를 중심으로 확인했습니다.")
|
||||
statusRow("08","협력사 SG명·유통레벨","취급상품 기반 분류와 공급유형 선택/저장은 구현되어 있습니다. 다만 요청한 SG명 콤보와 유통레벨 4종(제조·총판·대리점·일반유통), 취급상품 삭제가 그대로 완성됐는지는 추가 UX 확인이 필요합니다.","부분",orange,132)
|
||||
statusRow("09","리드타임 → 표준납기","협상 완료 부가정보와 API 설명에 ‘표준납기’가 반영되고 회사 정의 session_fields와 연결됩니다.","완료",green,226)
|
||||
statusRow("10","협상 단가 VAT 별도","협상 상품정보·요약·목록/상세의 단가 표기를 VAT 별도로 통일했습니다. 검증 캡처도 존재합니다.","완료",green,320)
|
||||
statusRow("11","협상 성공률 기준 안내","성공률은 공급사 제시가를 앵커가·목표가와 비교한 1~99 지표입니다. 100% 미달이 결렬 조건은 아니며, 실제 종료는 별도 낙찰/개찰 규칙이 결정합니다.","완료(안내)",blue,414)
|
||||
statusRow("12","협상 종료 추가 의견","타결 부가정보와 결렬 통합폼 모두 ‘기타 의견’을 받으며 sessions.custom.opinion에 저장합니다. 구매자 상세·요약에서 조회되고 완료 후 잠깁니다.","완료",green,508)
|
||||
statusRow("13","결렬 사유·희망가격 통일","기존 RejectRSP/RejectCM을 단일 RejectForm으로 교체했습니다. 결렬사유·희망가·의견을 한 흐름에서 받고 reject_reason/reject_price에 저장합니다.","완료",green,602)
|
||||
statusRow("14","카드 사용 횟수 제한","견적 설정의 card_count(기본 3)를 컨텍스트에서 읽어 실제 사용 가능한 카드 수와 종료 조건을 제한하도록 반영했습니다. 운영 시 기존 세션 회귀검증을 권장합니다.","완료",green,696)
|
||||
end(ctx)
|
||||
|
||||
// 5. case-specific
|
||||
begin(ctx,5,"AIO2O · 요청사항 반영 보고서")
|
||||
heading("04","견적번호별 이슈 반영","EST-202607-05DE·8945·C9D2 사례에서 제기된 가격/종료 흐름을 대조했습니다.")
|
||||
statusRow("15","앵커·자동 제안가 10원 반올림","앵커 생성가, 목표가 후보, 협상카드 카운터를 공통으로 10원 단위 반올림합니다. 예: 15,213원 → 15,210원. 관련 커밋과 단위 테스트가 있습니다.","완료",green,132)
|
||||
statusRow("16","절충안 계산식","협상카드 전술에는 앵커·목표가·직전 제시가를 이용한 중간값 및 목표가 상한 로직이 존재합니다. 다만 ‘절충안’의 기대 공식이 엑셀에 없어 업무적으로 맞는지 확정할 수 없습니다.","확인 필요",red,226)
|
||||
statusRow("17","05DE/C9D2 결렬 희망가격","견적 유형별로 갈리던 결렬 화면을 단일 폼으로 통합해 희망가격 입력 절차를 동일하게 만들었습니다.","완료",green,320)
|
||||
statusRow("18","8945 협상 마무리 개편","종료 후 표준납기·MOQ·발주배수·배송유형 등 회사 정의 부가정보를 선택/입력하고, 기타 의견과 함께 최종 요약에 반영합니다. 배송 선택값은 회사 설정에 따라 구성됩니다.","완료",green,414)
|
||||
statusRow("19","C9D2 자동 제안가 갭","제안가는 카드 전술과 앵커·목표가·직전 제시가의 조합으로 계산되고 10원 반올림됩니다. 17,500원→15,210원의 10.5% 갭이 정책상 적정한지는 목표/앵커 설정을 포함한 별도 검증이 필요합니다.","확인 필요",red,508)
|
||||
statusRow("20","성공/실패 후 의견 조회","협력사가 입력한 종료 의견은 공급사 요약과 구매자 견적 상세 양쪽에서 확인할 수 있고, 종료 후 읽기 전용으로 잠깁니다.","완료",green,602)
|
||||
statusRow("21","중복 요청 통합 반영","엑셀 18/22(성공률), 19/25(종료 의견), 5/23(목표가), 14/17/20(결렬폼)은 각각 하나의 공통 구현으로 해소했습니다.","완료",green,696)
|
||||
end(ctx)
|
||||
|
||||
// 6. evidence
|
||||
begin(ctx,6,"AIO2O · 요청사항 반영 보고서")
|
||||
heading("05","구현 근거","최근 커밋과 현재 코드에서 확인한 핵심 근거입니다. 커밋 단위로 기능 범위를 추적할 수 있습니다.")
|
||||
statusRow("A","b33ae05c · 견적 가격/상품/라벨","목표가 자동입력, 산정후보 위치 이동, 앵커·후보 10원 반올림, 신규 상품 공급사 입력, 회사 설정 라벨 연동.","커밋",purple,132,72)
|
||||
statusRow("B","a56589c6 · 종료폼/의견/VAT","결렬폼 통합, 희망가·사유 저장, 타결/결렬 의견 수취, 상품정보 라벨 연동, 협상 단가 VAT 별도 표기.","커밋",purple,216,72)
|
||||
statusRow("C","30f13483 · 인터넷 최저가","무한 로딩 버그 수정, Worker 설정 보강, 몰별 최저가·진행/상세 UI 및 이력 저장 개선.","커밋",purple,300,72)
|
||||
statusRow("D","9dca78dc · 완료 부가정보","완료 부가정보 수취·요약 표시·잠금, 구매자 상세 노출, VAT 표기 통일.","커밋",purple,384,72)
|
||||
statusRow("E","2a004734 · 견적 상세 연결","견적 상세의 채팅·협상카드 탭 연동과 드로어 탐색 개선.","커밋",purple,468,72)
|
||||
statusRow("F","775984fe / f554202c · 반올림","협상카드 카운터와 자동 앵커를 10원 단위 반올림으로 통일.","커밋",purple,552,72)
|
||||
statusRow("G","화면 검증 캡처","목록/상세, 종료 의견, VAT, 완료 요약, 읽기 전용 잠금 등 12개 캡처가 저장소 루트에 남아 있습니다.","캡처",blue,636,72)
|
||||
text("주의: 본 보고서는 2026-07-31 현재 로컬 저장소의 코드·커밋·캡처를 기준으로 합니다. 운영 배포 여부와 기존 데이터 마이그레이션 상태는 별도 확인 대상입니다.",CGRect(x:M,y:742,width:W-2*M,height:42),8.8,muted,.regular,.left,3)
|
||||
end(ctx)
|
||||
|
||||
// 7. actions
|
||||
begin(ctx,7,"AIO2O · 요청사항 반영 보고서")
|
||||
heading("06","남은 확인 및 권고","기능 누락이라기보다 업무 규칙·운영 설정을 확정해야 하는 항목입니다.")
|
||||
statusRow("1","최저가 VAT 대표값 확정","현재 LPS는 상품가와 배송비를 별도 수집·표시합니다. 대표 최저가를 반드시 (상품가+배송비)/1.1로 저장할지, 화면 표시만 할지 정책을 확정한 뒤 테스트를 추가해야 합니다.","우선순위 높음",red,142,98)
|
||||
statusRow("2","절충안/자동 제안가 기준 검증","05DE·C9D2의 실제 앵커가·목표가·직전 제시가를 넣어 계산 결과를 재현하고, 허용 최대 인하폭 또는 목표가 클램프 기준을 업무 담당자와 합의하는 것이 좋습니다.","우선순위 높음",red,254,98)
|
||||
statusRow("3","SG명·유통레벨 UX 확정","현행 취급상품 기반 분류/공급유형을 요청한 SG 콤보와 유통레벨 4종으로 대체할지, 데이터 모델을 유지한 채 라벨만 조정할지 결정이 필요합니다.","우선순위 중간",orange,366,98)
|
||||
statusRow("4","운영 배포·기존 세션 회귀검증","종료폼, 의견, 카드 횟수 제한은 신규 코드에 반영됐습니다. 운영 컨테이너 재빌드 후 기존 세션과 신규 세션에서 각각 1회 이상 확인해야 합니다.","배포 확인",blue,478,98)
|
||||
box(CGRect(x:M,y:612,width:W-2*M,height:118),purple.withAlphaComponent(0.08),purple.withAlphaComponent(0.28),12)
|
||||
text("권장 최종 승인 기준",CGRect(x:M+18,y:630,width:470,height:22),12,purple,.bold)
|
||||
text("① 운영 배포 버전 확인 ② 대표 견적 3건 시나리오 재실행 ③ 계산식 2건 서면 확정\n④ SG/유통레벨 화면 승인 ⑤ 완료·결렬 의견이 구매자 상세에 저장되는지 확인",CGRect(x:M+18,y:662,width:470,height:50),10,ink,.medium,.left,5)
|
||||
text("— End of report —",CGRect(x:M,y:760,width:W-2*M,height:20),8,muted,.medium,.center)
|
||||
end(ctx)
|
||||
|
||||
ctx.closePDF()
|
||||
Binary file not shown.
@ -1,790 +0,0 @@
|
||||
import AppKit
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
|
||||
let outPath = CommandLine.arguments.count > 1
|
||||
? CommandLine.arguments[1]
|
||||
: "docs/backend-advanced-concepts-ko.pdf"
|
||||
|
||||
let W: CGFloat = 595
|
||||
let H: CGFloat = 842
|
||||
let margin: CGFloat = 44
|
||||
|
||||
let navy = NSColor(calibratedRed: 0.055, green: 0.086, blue: 0.16, alpha: 1)
|
||||
let ink = NSColor(calibratedRed: 0.10, green: 0.13, blue: 0.18, alpha: 1)
|
||||
let muted = NSColor(calibratedRed: 0.37, green: 0.42, blue: 0.50, alpha: 1)
|
||||
let paper = NSColor(calibratedRed: 0.975, green: 0.98, blue: 0.99, alpha: 1)
|
||||
let line = NSColor(calibratedRed: 0.86, green: 0.88, blue: 0.92, alpha: 1)
|
||||
let blue = NSColor(calibratedRed: 0.16, green: 0.39, blue: 0.93, alpha: 1)
|
||||
let cyan = NSColor(calibratedRed: 0.10, green: 0.69, blue: 0.74, alpha: 1)
|
||||
let green = NSColor(calibratedRed: 0.10, green: 0.63, blue: 0.39, alpha: 1)
|
||||
let orange = NSColor(calibratedRed: 0.94, green: 0.47, blue: 0.12, alpha: 1)
|
||||
let red = NSColor(calibratedRed: 0.88, green: 0.25, blue: 0.28, alpha: 1)
|
||||
let purple = NSColor(calibratedRed: 0.48, green: 0.32, blue: 0.89, alpha: 1)
|
||||
|
||||
func pdfRect(_ r: CGRect) -> CGRect {
|
||||
CGRect(x: r.minX, y: H - r.maxY, width: r.width, height: r.height)
|
||||
}
|
||||
|
||||
func pdfPoint(_ p: CGPoint) -> CGPoint {
|
||||
CGPoint(x: p.x, y: H - p.y)
|
||||
}
|
||||
|
||||
func font(_ size: CGFloat, _ weight: NSFont.Weight = .regular) -> NSFont {
|
||||
NSFont(name: "Apple SD Gothic Neo", size: size)
|
||||
?? NSFont.systemFont(ofSize: size, weight: weight)
|
||||
}
|
||||
|
||||
func mono(_ size: CGFloat) -> NSFont {
|
||||
NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
|
||||
}
|
||||
|
||||
func attrs(_ size: CGFloat, color: NSColor = ink, weight: NSFont.Weight = .regular,
|
||||
align: NSTextAlignment = .left, lineSpacing: CGFloat = 3) -> [NSAttributedString.Key: Any] {
|
||||
let p = NSMutableParagraphStyle()
|
||||
p.alignment = align
|
||||
p.lineSpacing = lineSpacing
|
||||
p.lineBreakMode = .byWordWrapping
|
||||
return [.font: font(size, weight), .foregroundColor: color, .paragraphStyle: p]
|
||||
}
|
||||
|
||||
func drawText(_ text: String, _ rect: CGRect, size: CGFloat = 11, color: NSColor = ink,
|
||||
weight: NSFont.Weight = .regular, align: NSTextAlignment = .left,
|
||||
lineSpacing: CGFloat = 3) {
|
||||
NSAttributedString(string: text, attributes: attrs(size, color: color, weight: weight,
|
||||
align: align, lineSpacing: lineSpacing))
|
||||
.draw(with: pdfRect(rect), options: [.usesLineFragmentOrigin, .usesFontLeading])
|
||||
}
|
||||
|
||||
func rounded(_ rect: CGRect, radius: CGFloat = 12, fill: NSColor = .white,
|
||||
stroke: NSColor? = line, width: CGFloat = 1) {
|
||||
let p = NSBezierPath(roundedRect: pdfRect(rect), xRadius: radius, yRadius: radius)
|
||||
fill.setFill(); p.fill()
|
||||
if let stroke { stroke.setStroke(); p.lineWidth = width; p.stroke() }
|
||||
}
|
||||
|
||||
func pill(_ text: String, x: CGFloat, y: CGFloat, w: CGFloat, color: NSColor) {
|
||||
rounded(CGRect(x: x, y: y, width: w, height: 25), radius: 12.5,
|
||||
fill: color.withAlphaComponent(0.12), stroke: nil)
|
||||
drawText(text, CGRect(x: x, y: y + 5, width: w, height: 16), size: 9.5,
|
||||
color: color, weight: .semibold, align: .center)
|
||||
}
|
||||
|
||||
func arrow(_ from: CGPoint, _ to: CGPoint, color: NSColor = muted) {
|
||||
let from = pdfPoint(from), to = pdfPoint(to)
|
||||
let p = NSBezierPath(); p.move(to: from); p.line(to: to)
|
||||
color.setStroke(); p.lineWidth = 1.8; p.stroke()
|
||||
let a = atan2(to.y - from.y, to.x - from.x)
|
||||
let l: CGFloat = 7
|
||||
let h = NSBezierPath()
|
||||
h.move(to: to)
|
||||
h.line(to: CGPoint(x: to.x - l * cos(a - .pi / 6), y: to.y - l * sin(a - .pi / 6)))
|
||||
h.line(to: CGPoint(x: to.x - l * cos(a + .pi / 6), y: to.y - l * sin(a + .pi / 6)))
|
||||
h.close(); color.setFill(); h.fill()
|
||||
}
|
||||
|
||||
func node(_ title: String, _ sub: String, rect: CGRect, color: NSColor) {
|
||||
rounded(rect, radius: 10, fill: color.withAlphaComponent(0.10),
|
||||
stroke: color.withAlphaComponent(0.55), width: 1.2)
|
||||
drawText(title, CGRect(x: rect.minX + 8, y: rect.minY + 10, width: rect.width - 16, height: 18),
|
||||
size: 10.5, color: color, weight: .bold, align: .center)
|
||||
drawText(sub, CGRect(x: rect.minX + 8, y: rect.minY + 31, width: rect.width - 16, height: rect.height - 36),
|
||||
size: 8.5, color: muted, align: .center, lineSpacing: 1)
|
||||
}
|
||||
|
||||
func sectionTitle(_ number: String, _ title: String, _ subtitle: String, color: NSColor) {
|
||||
pill(number, x: margin, y: 48, w: 34, color: color)
|
||||
drawText(title, CGRect(x: 86, y: 46, width: 450, height: 30), size: 22,
|
||||
color: navy, weight: .bold)
|
||||
drawText(subtitle, CGRect(x: margin, y: 82, width: W - 2 * margin, height: 26),
|
||||
size: 10.5, color: muted)
|
||||
}
|
||||
|
||||
func footer(_ page: Int, _ label: String = "O2O Negosium · Backend Concepts") {
|
||||
let p = NSBezierPath()
|
||||
p.move(to: CGPoint(x: margin, y: H - 34)); p.line(to: CGPoint(x: W - margin, y: H - 34))
|
||||
line.setStroke(); p.lineWidth = 0.7; p.stroke()
|
||||
drawText(label, CGRect(x: margin, y: H - 28, width: 350, height: 14), size: 7.5, color: muted)
|
||||
drawText("\(page)", CGRect(x: W - margin - 35, y: H - 28, width: 35, height: 14),
|
||||
size: 8, color: muted, align: .right)
|
||||
}
|
||||
|
||||
func callout(_ title: String, _ body: String, rect: CGRect, color: NSColor) {
|
||||
rounded(rect, radius: 12, fill: color.withAlphaComponent(0.08),
|
||||
stroke: color.withAlphaComponent(0.35))
|
||||
rounded(CGRect(x: rect.minX, y: rect.minY, width: 5, height: rect.height),
|
||||
radius: 2.5, fill: color, stroke: nil)
|
||||
drawText(title, CGRect(x: rect.minX + 16, y: rect.minY + 12,
|
||||
width: rect.width - 28, height: 20),
|
||||
size: 11, color: color, weight: .bold)
|
||||
drawText(body, CGRect(x: rect.minX + 16, y: rect.minY + 37,
|
||||
width: rect.width - 28, height: rect.height - 45),
|
||||
size: 9.5, color: ink, lineSpacing: 3)
|
||||
}
|
||||
|
||||
func comparison(_ leftTitle: String, _ left: String, _ rightTitle: String, _ right: String,
|
||||
y: CGFloat, color: NSColor) {
|
||||
let gap: CGFloat = 14
|
||||
let cw = (W - 2 * margin - gap) / 2
|
||||
callout(leftTitle, left, rect: CGRect(x: margin, y: y, width: cw, height: 126), color: red)
|
||||
callout(rightTitle, right, rect: CGRect(x: margin + cw + gap, y: y, width: cw, height: 126), color: color)
|
||||
}
|
||||
|
||||
func codeBox(_ title: String, _ path: String, _ code: String, rect: CGRect, accent: NSColor) {
|
||||
rounded(rect, radius: 10, fill: navy, stroke: nil)
|
||||
drawText(title, CGRect(x: rect.minX + 14, y: rect.minY + 11,
|
||||
width: rect.width - 28, height: 17),
|
||||
size: 10, color: .white, weight: .bold)
|
||||
drawText(path, CGRect(x: rect.minX + 14, y: rect.minY + 30,
|
||||
width: rect.width - 28, height: 14),
|
||||
size: 7.5, color: accent)
|
||||
let p = NSMutableParagraphStyle(); p.lineSpacing = 2; p.lineBreakMode = .byClipping
|
||||
NSAttributedString(string: code, attributes: [.font: mono(7.8), .foregroundColor: NSColor(calibratedWhite: 0.88, alpha: 1), .paragraphStyle: p])
|
||||
.draw(with: pdfRect(CGRect(x: rect.minX + 14, y: rect.minY + 51,
|
||||
width: rect.width - 28, height: rect.height - 60)),
|
||||
options: [.usesLineFragmentOrigin])
|
||||
}
|
||||
|
||||
func beginPage(_ ctx: CGContext, page: Int, label: String = "O2O Negosium · Backend Concepts") {
|
||||
ctx.beginPDFPage(nil)
|
||||
ctx.saveGState()
|
||||
NSGraphicsContext.saveGraphicsState()
|
||||
NSGraphicsContext.current = NSGraphicsContext(cgContext: ctx, flipped: false)
|
||||
paper.setFill(); NSBezierPath(rect: pdfRect(CGRect(x: 0, y: 0, width: W, height: H))).fill()
|
||||
footer(page, label)
|
||||
}
|
||||
|
||||
func endPage(_ ctx: CGContext) {
|
||||
NSGraphicsContext.restoreGraphicsState()
|
||||
ctx.restoreGState()
|
||||
ctx.endPDFPage()
|
||||
}
|
||||
|
||||
var mediaBox = CGRect(x: 0, y: 0, width: W, height: H)
|
||||
guard let consumer = CGDataConsumer(url: URL(fileURLWithPath: outPath) as CFURL),
|
||||
let ctx = CGContext(consumer: consumer, mediaBox: &mediaBox, nil) else {
|
||||
fatalError("PDF context 생성 실패")
|
||||
}
|
||||
|
||||
// 1 — Cover
|
||||
beginPage(ctx, page: 1, label: "O2O Negosium · Backend Field Guide")
|
||||
rounded(CGRect(x: 0, y: 0, width: W, height: H), radius: 0, fill: navy, stroke: nil)
|
||||
for i in 0..<7 {
|
||||
let x = CGFloat(50 + i * 78)
|
||||
let c = [blue, cyan, green, orange, purple][i % 5]
|
||||
rounded(CGRect(x: x, y: 85 + CGFloat((i % 3) * 28), width: 48, height: 48),
|
||||
radius: 24, fill: c.withAlphaComponent(0.35), stroke: nil)
|
||||
}
|
||||
drawText("BACKEND", CGRect(x: margin, y: 190, width: 507, height: 35), size: 15,
|
||||
color: cyan, weight: .bold)
|
||||
drawText("어려운 개념 5가지,\n코드로 이해하기", CGRect(x: margin, y: 228, width: 507, height: 118),
|
||||
size: 36, color: .white, weight: .bold, lineSpacing: 7)
|
||||
drawText("분산 시스템 · 트랜잭션/동시성 · 멀티테넌시\n캐시 정합성 · 스케줄러/배치",
|
||||
CGRect(x: margin, y: 370, width: 507, height: 62), size: 15,
|
||||
color: NSColor(calibratedWhite: 0.80, alpha: 1), lineSpacing: 8)
|
||||
rounded(CGRect(x: margin, y: 485, width: 507, height: 154), radius: 18,
|
||||
fill: NSColor.white.withAlphaComponent(0.07),
|
||||
stroke: NSColor.white.withAlphaComponent(0.15))
|
||||
drawText("이 문서는 이렇게 읽어요", CGRect(x: 66, y: 510, width: 455, height: 25),
|
||||
size: 14, color: .white, weight: .bold)
|
||||
drawText("① 일상 비유로 개념 잡기\n② 실제 서비스 흐름을 그림으로 보기\n③ 프로젝트 코드에서 구현 확인하기\n④ 없을 때 생기는 문제와 비교하기",
|
||||
CGRect(x: 66, y: 548, width: 455, height: 78), size: 11.5,
|
||||
color: NSColor(calibratedWhite: 0.88, alpha: 1), lineSpacing: 6)
|
||||
drawText("Generated from the current repository · 2026-07-29",
|
||||
CGRect(x: margin, y: 758, width: 507, height: 18), size: 8.5,
|
||||
color: NSColor(calibratedWhite: 0.62, alpha: 1))
|
||||
endPage(ctx)
|
||||
|
||||
// 2 — Architecture map
|
||||
beginPage(ctx, page: 2)
|
||||
drawText("먼저, 서비스 지도를 봅시다", CGRect(x: margin, y: 48, width: 507, height: 34),
|
||||
size: 24, color: navy, weight: .bold)
|
||||
drawText("다섯 개념은 따로 노는 것이 아니라, 한 요청이 여러 서비스와 저장소를 지나면서 함께 작동합니다.",
|
||||
CGRect(x: margin, y: 88, width: 507, height: 32), size: 10.5, color: muted)
|
||||
node("사용자", "브라우저", rect: CGRect(x: 44, y: 170, width: 90, height: 62), color: purple)
|
||||
node("Backend", "채팅·공급사", rect: CGRect(x: 184, y: 145, width: 102, height: 72), color: blue)
|
||||
node("Agent", "AI 협상", rect: CGRect(x: 348, y: 145, width: 102, height: 72), color: orange)
|
||||
node("Negodata", "견적·관리", rect: CGRect(x: 184, y: 270, width: 102, height: 72), color: cyan)
|
||||
node("LPS", "최저가 Worker", rect: CGRect(x: 348, y: 270, width: 102, height: 72), color: green)
|
||||
node("PostgreSQL", "업무 원본", rect: CGRect(x: 184, y: 405, width: 130, height: 72), color: purple)
|
||||
node("Redis", "앵커링 캐시", rect: CGRect(x: 368, y: 405, width: 100, height: 72), color: red)
|
||||
arrow(CGPoint(x: 134, y: 200), CGPoint(x: 184, y: 182), color: purple)
|
||||
arrow(CGPoint(x: 286, y: 180), CGPoint(x: 348, y: 180), color: blue)
|
||||
arrow(CGPoint(x: 235, y: 217), CGPoint(x: 235, y: 270), color: cyan)
|
||||
arrow(CGPoint(x: 286, y: 304), CGPoint(x: 348, y: 304), color: green)
|
||||
arrow(CGPoint(x: 235, y: 342), CGPoint(x: 235, y: 405), color: purple)
|
||||
arrow(CGPoint(x: 399, y: 342), CGPoint(x: 415, y: 405), color: red)
|
||||
callout("① 경계가 생기면 ‘분산 시스템’", "서비스 A가 서비스 B를 네트워크로 호출하는 순간, 지연·타임아웃·부분 실패를 다뤄야 합니다.",
|
||||
rect: CGRect(x: margin, y: 525, width: 246, height: 105), color: blue)
|
||||
callout("② 여러 실행자가 만나면 ‘동시성’", "사용자 클릭과 스케줄러가 같은 견적을 동시에 마감할 수 있어, DB가 최종 심판 역할을 합니다.",
|
||||
rect: CGRect(x: 305, y: 525, width: 246, height: 105), color: orange)
|
||||
callout("③ 빠르게 읽되 원본을 지키면 ‘캐시’", "Redis와 프로세스 메모리는 복사본입니다. PostgreSQL과 설정 파일이 원본입니다.",
|
||||
rect: CGRect(x: margin, y: 650, width: 246, height: 105), color: red)
|
||||
callout("④ 회사별 경계를 지키면 ‘멀티테넌시’", "요청 헤더에서 회사 ID를 결정하고, 회사별 설정·엔진을 선택합니다.",
|
||||
rect: CGRect(x: 305, y: 650, width: 246, height: 105), color: purple)
|
||||
endPage(ctx)
|
||||
|
||||
// 3 — Distributed systems: concept first
|
||||
beginPage(ctx, page: 3)
|
||||
sectionTitle("3", "분산 시스템 — 개념부터", "여러 독립 실행 단위가 네트워크를 통해 하나의 업무를 완성하는 시스템", color: blue)
|
||||
callout("정확한 정의", "프로세스·컨테이너·서버가 각자 메모리와 실행 상태를 가지고, HTTP나 메시지로 통신하는 구조입니다. 한 서비스의 함수 호출과 달리 상대의 상태를 직접 볼 수 없고, 네트워크 응답만으로 결과를 추론해야 합니다.",
|
||||
rect: CGRect(x: margin, y: 126, width: 507, height: 92), color: blue)
|
||||
drawText("왜 어려운가: 네트워크에는 네 가지 결과가 있습니다", CGRect(x: margin, y: 244, width: 507, height: 24),
|
||||
size: 13.5, color: navy, weight: .bold)
|
||||
let distCases: [(String, String, NSColor)] = [
|
||||
("성공", "상대가 처리했고 응답도 받음", green),
|
||||
("명확한 실패", "상대가 오류 응답을 보냄", red),
|
||||
("연결 실패", "상대에게 요청이 도착하지 않음", orange),
|
||||
("애매한 타임아웃", "처리는 됐지만 응답만 늦었을 수도 있음", purple),
|
||||
]
|
||||
for (i, c) in distCases.enumerated() {
|
||||
let col = i % 2, row = i / 2
|
||||
let x = margin + CGFloat(col) * 260
|
||||
let y = CGFloat(286 + row * 86)
|
||||
callout(c.0, c.1, rect: CGRect(x: x, y: y, width: 247, height: 70), color: c.2)
|
||||
}
|
||||
drawText("대표적인 대응 수단", CGRect(x: margin, y: 475, width: 507, height: 24),
|
||||
size: 13.5, color: navy, weight: .bold)
|
||||
callout("Timeout", "얼마나 기다릴지 상한을 둡니다. 짧으면 정상 요청도 실패하고, 길면 자원이 오래 묶입니다.",
|
||||
rect: CGRect(x: margin, y: 515, width: 159, height: 92), color: blue)
|
||||
callout("Retry", "일시 실패를 다시 시도합니다. 단, 중복 처리에 안전한 작업에서만 제한적으로 사용합니다.",
|
||||
rect: CGRect(x: 218, y: 515, width: 159, height: 92), color: orange)
|
||||
callout("Idempotency", "같은 요청을 여러 번 보내도 결과가 한 번 처리한 것과 같도록 만듭니다.",
|
||||
rect: CGRect(x: 392, y: 515, width: 159, height: 92), color: purple)
|
||||
callout("Fallback", "주 서비스가 실패하면 대체 경로·기본값·이전 데이터를 사용합니다. 대체 결과가 업무적으로 허용될 때만 가능합니다.",
|
||||
rect: CGRect(x: margin, y: 630, width: 247, height: 92), color: green)
|
||||
callout("Circuit breaker", "실패가 계속되는 서비스를 잠시 호출하지 않아 연쇄 장애를 막습니다. 현재 프로젝트에는 명시적 구현이 없습니다.",
|
||||
rect: CGRect(x: 304, y: 630, width: 247, height: 92), color: red)
|
||||
endPage(ctx)
|
||||
|
||||
// 4 distributed concept
|
||||
beginPage(ctx, page: 4)
|
||||
sectionTitle("3", "분산 시스템과 장애 대응", "한 프로그램이 아니라 여러 서비스가 네트워크로 협력하는 구조", color: blue)
|
||||
callout("쉬운 비유", "한 식당 안에서 주방과 홀 직원이 말로 협업하는 것이 단일 시스템이라면, 분산 시스템은 서로 다른 건물의 팀이 전화로 협업하는 것입니다. 전화는 늦거나 끊길 수 있고, 상대가 일을 끝냈는데 답만 못 받을 수도 있습니다.",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 105), color: blue)
|
||||
drawText("프로젝트의 대표 흐름", CGRect(x: margin, y: 266, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("Backend", "사용자 채팅 요청", rect: CGRect(x: 52, y: 315, width: 110, height: 74), color: blue)
|
||||
node("HTTPX", "timeout 설정", rect: CGRect(x: 242, y: 315, width: 110, height: 74), color: cyan)
|
||||
node("Agent", "협상 턴 계산", rect: CGRect(x: 432, y: 315, width: 110, height: 74), color: orange)
|
||||
arrow(CGPoint(x: 162, y: 352), CGPoint(x: 242, y: 352), color: blue)
|
||||
arrow(CGPoint(x: 352, y: 352), CGPoint(x: 432, y: 352), color: cyan)
|
||||
drawText("성공", CGRect(x: 394, y: 414, width: 80, height: 18), size: 9, color: green, weight: .bold)
|
||||
arrow(CGPoint(x: 485, y: 389), CGPoint(x: 485, y: 458), color: green)
|
||||
node("응답 반영", "채팅 상태 저장", rect: CGRect(x: 430, y: 458, width: 112, height: 65), color: green)
|
||||
drawText("타임아웃/실패", CGRect(x: 185, y: 414, width: 105, height: 18), size: 9, color: red, weight: .bold)
|
||||
arrow(CGPoint(x: 297, y: 389), CGPoint(x: 297, y: 458), color: red)
|
||||
node("안전한 실패", "ok=false 반환", rect: CGRect(x: 241, y: 458, width: 112, height: 65), color: red)
|
||||
callout("중요한 함정: 타임아웃 ≠ 상대가 아무 일도 안 함", "Agent가 DB 상태를 이미 전진시킨 직후 응답만 늦었을 수 있습니다. 그래서 무조건 재시도하면 같은 턴을 두 번 처리할 위험이 있습니다. 코드가 timed_out을 따로 표시하는 이유입니다.",
|
||||
rect: CGRect(x: margin, y: 566, width: 507, height: 105), color: orange)
|
||||
comparison("이 장치가 없으면", "Agent가 느린 순간 Backend 요청도 끝없이 대기합니다. 무작정 재시도하면 협상 step이 두 번 전진할 수 있습니다.",
|
||||
"현재 방식", "HTTP timeout을 두고 성공/일반 실패/타임아웃을 구분합니다. 호출 경계에서 예외를 응답 객체로 변환합니다.",
|
||||
y: 695, color: blue)
|
||||
endPage(ctx)
|
||||
|
||||
// 5 distributed code
|
||||
beginPage(ctx, page: 5)
|
||||
sectionTitle("3", "분산 시스템 — 실제 코드", "서비스 경계마다 timeout, fallback, best-effort 정책이 다릅니다.", color: blue)
|
||||
codeBox("Agent 호출: 타임아웃을 별도 상태로 반환",
|
||||
"backend/services/agent_client.py · lines 81–91",
|
||||
"""
|
||||
async with httpx.AsyncClient(
|
||||
base_url=agent_config.base_url,
|
||||
timeout=agent_config.timeout_sec,
|
||||
) as cli:
|
||||
resp = await cli.post("/v1/chat", json=body, headers=headers)
|
||||
|
||||
except httpx.TimeoutException as ex:
|
||||
# Agent가 이미 처리했을 수 있어 단순 재시도는 위험
|
||||
return AgentTurn(ok=False, timed_out=True)
|
||||
except Exception:
|
||||
return AgentTurn(ok=False)
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 245), accent: cyan)
|
||||
codeBox("카탈로그 변경 알림: 핵심 업무를 막지 않는 best-effort",
|
||||
"negodata/backend/services/agent_notify.py · lines 15–26",
|
||||
"""
|
||||
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}")
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 395, width: 507, height: 160), accent: green)
|
||||
callout("어떻게 정책을 고르나요?", "결제처럼 반드시 성공해야 하는 작업은 실패를 호출자에게 알려 재처리해야 합니다. 반면 ‘캐시 무효화 알림’처럼 보조적인 작업은 실패해도 핵심 카드 변경을 성공시킬 수 있습니다. 모든 외부 호출을 똑같이 재시도하면 안 됩니다.",
|
||||
rect: CGRect(x: margin, y: 580, width: 507, height: 105), color: blue)
|
||||
drawText("기억할 단어", CGRect(x: margin, y: 712, width: 120, height: 20), size: 12,
|
||||
color: navy, weight: .bold)
|
||||
pill("timeout", x: 150, y: 707, w: 82, color: blue)
|
||||
pill("partial failure", x: 242, y: 707, w: 102, color: orange)
|
||||
pill("best-effort", x: 354, y: 707, w: 92, color: green)
|
||||
pill("idempotency", x: 456, y: 707, w: 90, color: purple)
|
||||
endPage(ctx)
|
||||
|
||||
// 6 — Transactions and concurrency: concept first
|
||||
beginPage(ctx, page: 6)
|
||||
sectionTitle("4", "트랜잭션·동시성 — 개념부터", "데이터의 일관성을 지키는 작업 단위와, 동시에 실행되는 요청을 제어하는 방법", color: orange)
|
||||
drawText("트랜잭션의 ACID", CGRect(x: margin, y: 126, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
let acid: [(String, String, NSColor)] = [
|
||||
("A · Atomicity", "전부 성공하거나 전부 취소", orange),
|
||||
("C · Consistency", "규칙을 만족하는 상태로 이동", green),
|
||||
("I · Isolation", "동시 작업의 중간 상태를 서로 숨김", purple),
|
||||
("D · Durability", "COMMIT된 결과는 장애 후에도 보존", blue),
|
||||
]
|
||||
for (i, a) in acid.enumerated() {
|
||||
let x = margin + CGFloat(i % 2) * 260
|
||||
let y = CGFloat(165 + (i / 2) * 84)
|
||||
callout(a.0, a.1, rect: CGRect(x: x, y: y, width: 247, height: 68), color: a.2)
|
||||
}
|
||||
drawText("동시성 문제는 어떻게 생기나?", CGRect(x: margin, y: 352, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("요청 A", "status=OPEN 읽음", rect: CGRect(x: 48, y: 401, width: 116, height: 64), color: blue)
|
||||
node("요청 B", "status=OPEN 읽음", rect: CGRect(x: 48, y: 500, width: 116, height: 64), color: purple)
|
||||
node("둘 다 처리", "중복 마감·중복 메일", rect: CGRect(x: 250, y: 449, width: 130, height: 70), color: red)
|
||||
arrow(CGPoint(x: 164, y: 433), CGPoint(x: 250, y: 471), color: blue)
|
||||
arrow(CGPoint(x: 164, y: 532), CGPoint(x: 250, y: 497), color: purple)
|
||||
callout("해결 ① 비관적 잠금", "SELECT ... FOR UPDATE로 먼저 행을 잠급니다. 명확하지만 잠금 대기와 deadlock을 관리해야 합니다.",
|
||||
rect: CGRect(x: 408, y: 391, width: 143, height: 92), color: orange)
|
||||
callout("해결 ② 조건부 갱신", "UPDATE ... WHERE status=OPEN 후 rowcount를 확인합니다. 상태 검사와 변경이 원자적으로 일어납니다.",
|
||||
rect: CGRect(x: 408, y: 497, width: 143, height: 92), color: green)
|
||||
callout("격리 수준과 잠금은 만능이 아님", "격리를 높이면 안전성은 커지지만 동시 처리량이 줄고 대기·교착 가능성이 커집니다. 업무 규칙에 맞는 최소 범위의 트랜잭션과 조건부 상태 전이가 실용적입니다.",
|
||||
rect: CGRect(x: margin, y: 624, width: 507, height: 92), color: orange)
|
||||
callout("COMMIT / ROLLBACK", "COMMIT은 변경 확정, ROLLBACK은 현재 트랜잭션의 미확정 변경 취소입니다. 외부 이메일 발송은 DB rollback으로 되돌릴 수 없다는 점도 중요합니다.",
|
||||
rect: CGRect(x: margin, y: 720, width: 507, height: 72), color: red)
|
||||
endPage(ctx)
|
||||
|
||||
// 7 transaction concept
|
||||
beginPage(ctx, page: 7)
|
||||
sectionTitle("4", "DB 트랜잭션과 동시성 제어", "여러 작업을 하나로 묶고, 동시에 온 요청 중 한 명만 통과시키는 기술", color: orange)
|
||||
callout("트랜잭션이란?", "은행 이체에서 ‘내 계좌 차감’과 ‘상대 계좌 증가’가 둘 다 성공하거나 둘 다 취소되어야 하듯, 관련 DB 변경을 하나의 작업 단위로 묶는 것입니다. 중간에 실패하면 rollback합니다.",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 92), color: orange)
|
||||
drawText("동시 마감 문제", CGRect(x: margin, y: 252, width: 200, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("사용자 클릭", "마감 요청 A", rect: CGRect(x: 50, y: 300, width: 110, height: 66), color: blue)
|
||||
node("스케줄러", "마감 요청 B", rect: CGRect(x: 50, y: 405, width: 110, height: 66), color: purple)
|
||||
node("조건부 UPDATE", "status != CLOSED", rect: CGRect(x: 243, y: 350, width: 120, height: 74), color: orange)
|
||||
node("PostgreSQL", "원자적으로 판정", rect: CGRect(x: 430, y: 350, width: 112, height: 74), color: green)
|
||||
arrow(CGPoint(x: 160, y: 333), CGPoint(x: 243, y: 376), color: blue)
|
||||
arrow(CGPoint(x: 160, y: 438), CGPoint(x: 243, y: 399), color: purple)
|
||||
arrow(CGPoint(x: 363, y: 387), CGPoint(x: 430, y: 387), color: orange)
|
||||
callout("승자", "영향받은 행 수(rowcount) = 1\n마감 판정 권한 획득",
|
||||
rect: CGRect(x: 76, y: 518, width: 205, height: 88), color: green)
|
||||
callout("패자/재요청", "rowcount = 0\n이미 닫혔으므로 추가 처리 중단",
|
||||
rect: CGRect(x: 314, y: 518, width: 205, height: 88), color: red)
|
||||
comparison("단순 SELECT 후 UPDATE", "두 요청이 동시에 OPEN을 읽으면 둘 다 마감·낙찰 로직을 실행할 수 있습니다. 이메일도 두 번 발송될 수 있습니다.",
|
||||
"조건부 UPDATE", "DB가 상태 검사와 변경을 한 문장으로 처리합니다. 먼저 성공한 요청만 rowcount=1을 받습니다.",
|
||||
y: 640, color: orange)
|
||||
endPage(ctx)
|
||||
|
||||
// 8 transaction code
|
||||
beginPage(ctx, page: 8)
|
||||
sectionTitle("4", "트랜잭션·동시성 — 실제 코드", "애플리케이션의 if문보다 DB의 원자적 UPDATE가 강한 최종 방어선입니다.", color: orange)
|
||||
codeBox("조건부 상태 전이: 마감 권한 선점",
|
||||
"negodata/backend/crud/quotation_crud.py · lines 482–500",
|
||||
"""
|
||||
query = (
|
||||
update(quotations)
|
||||
.where(
|
||||
quotations.qt_id == qt_id,
|
||||
quotations.status != QuotationStatus.CLOSED.value,
|
||||
quotations.deleted == False,
|
||||
)
|
||||
.values(
|
||||
status=QuotationStatus.CLOSED.value,
|
||||
updated_at=GTime.UTC(),
|
||||
)
|
||||
)
|
||||
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 235), accent: orange)
|
||||
codeBox("트랜잭션 실패 시 rollback",
|
||||
"negodata/backend/common/database/db_session_manager.py · lines 116–127",
|
||||
"""
|
||||
try:
|
||||
await db.commit()
|
||||
return ErrorType.SUCCESS
|
||||
except IntegrityError:
|
||||
await db.rollback()
|
||||
return ErrorType.DB_ALREADY_SAME_KEY
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
raise
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 390, width: 507, height: 175), accent: red)
|
||||
callout("왜 rowcount를 보나요?", "UPDATE가 에러 없이 실행됐다는 사실만으로는 내가 상태를 바꿨는지 알 수 없습니다. WHERE 조건에 맞는 행이 없으면 SQL은 정상 실행되지만 변경 행은 0개입니다. 그래서 1이면 승자, 0이면 이미 다른 요청이 처리한 것으로 판단합니다.",
|
||||
rect: CGRect(x: margin, y: 592, width: 507, height: 108), color: orange)
|
||||
callout("실무 체크", "트랜잭션은 짧게 유지하고, 외부 HTTP·이메일처럼 오래 걸리는 작업을 DB 트랜잭션 안에 오래 붙잡아 두지 않습니다.",
|
||||
rect: CGRect(x: margin, y: 720, width: 507, height: 65), color: purple)
|
||||
endPage(ctx)
|
||||
|
||||
// 9 — Multitenancy: concept first
|
||||
beginPage(ctx, page: 9)
|
||||
sectionTitle("5", "멀티테넌시 — 개념부터", "하나의 애플리케이션을 여러 고객사가 공유하면서 논리적으로 격리하는 설계", color: purple)
|
||||
callout("Tenant란?", "서비스를 사용하는 독립 고객 단위입니다. 이 프로젝트에서는 주로 ‘회사’가 tenant입니다. 같은 API와 서버를 쓰더라도 회사별 데이터, 설정, 권한, 협상 정책이 섞이면 안 됩니다.",
|
||||
rect: CGRect(x: margin, y: 126, width: 507, height: 88), color: purple)
|
||||
drawText("대표적인 데이터 격리 모델", CGRect(x: margin, y: 242, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
callout("DB 분리", "회사마다 별도 DB\n격리 강함 · 운영비 높음",
|
||||
rect: CGRect(x: margin, y: 282, width: 159, height: 88), color: blue)
|
||||
callout("Schema 분리", "한 DB 안에서 schema 분리\n중간 수준의 격리와 비용",
|
||||
rect: CGRect(x: 218, y: 282, width: 159, height: 88), color: cyan)
|
||||
callout("Row 공유", "같은 테이블 + tenant_id\n효율적 · 쿼리 누락 위험",
|
||||
rect: CGRect(x: 392, y: 282, width: 159, height: 88), color: orange)
|
||||
drawText("격리는 DB만의 문제가 아닙니다", CGRect(x: margin, y: 404, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
let tenantAxes: [(String, String)] = [
|
||||
("식별", "이 요청이 어느 회사 것인지 신뢰할 수 있게 결정"),
|
||||
("인가", "그 사용자가 해당 회사 자원에 접근 가능한지 확인"),
|
||||
("데이터", "모든 조회·수정 쿼리에 회사 범위 적용"),
|
||||
("설정", "회사별 정책·브랜딩·카드 선택"),
|
||||
("캐시", "캐시 key에 tenant를 포함해 회사 간 충돌 방지"),
|
||||
("자원", "한 회사의 과부하가 다른 회사에 미치는 영향 제한"),
|
||||
]
|
||||
for (i, t) in tenantAxes.enumerated() {
|
||||
let x = margin + CGFloat(i % 2) * 260
|
||||
let y = CGFloat(444 + (i / 2) * 74)
|
||||
rounded(CGRect(x: x, y: y, width: 247, height: 58), radius: 9,
|
||||
fill: purple.withAlphaComponent(0.06), stroke: purple.withAlphaComponent(0.25))
|
||||
drawText(t.0, CGRect(x: x + 12, y: y + 10, width: 52, height: 18), size: 10,
|
||||
color: purple, weight: .bold)
|
||||
drawText(t.1, CGRect(x: x + 66, y: y + 9, width: 168, height: 38), size: 8.5, color: ink)
|
||||
}
|
||||
callout("가장 흔한 사고", "쿼리의 WHERE tenant_id 조건 누락, 공유 캐시 key에 tenant_id 누락, 사용자가 body로 보낸 tenant_id를 그대로 신뢰하는 경우입니다. 그래서 tenant context를 요청 초기에 확정하고 자동 전달하는 구조가 중요합니다.",
|
||||
rect: CGRect(x: margin, y: 680, width: 507, height: 105), color: red)
|
||||
endPage(ctx)
|
||||
|
||||
// 10 multitenancy concept
|
||||
beginPage(ctx, page: 10)
|
||||
sectionTitle("5", "멀티테넌시", "하나의 시스템을 여러 회사가 쓰되, 설정과 데이터의 경계를 지키는 구조", color: purple)
|
||||
callout("쉬운 비유", "한 오피스 빌딩을 여러 회사가 함께 사용하지만 출입카드가 자기 회사 층만 열어주는 구조입니다. 서버는 공유하되, 요청마다 ‘어느 회사의 요청인지’를 먼저 확정해야 합니다.",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 92), color: purple)
|
||||
drawText("요청이 회사별 엔진을 찾는 과정", CGRect(x: margin, y: 252, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("HTTP 요청", "X-Tenant-ID", rect: CGRect(x: 45, y: 310, width: 100, height: 68), color: blue)
|
||||
node("Middleware", "존재·등록 검증", rect: CGRect(x: 195, y: 310, width: 105, height: 68), color: purple)
|
||||
node("request.state", "tenant_id 보관", rect: CGRect(x: 350, y: 310, width: 105, height: 68), color: cyan)
|
||||
arrow(CGPoint(x: 145, y: 344), CGPoint(x: 195, y: 344), color: blue)
|
||||
arrow(CGPoint(x: 300, y: 344), CGPoint(x: 350, y: 344), color: purple)
|
||||
node("Registry", "회사별 엔진 선택", rect: CGRect(x: 195, y: 445, width: 105, height: 68), color: orange)
|
||||
node("TenantEngine", "회사별 정책·카드", rect: CGRect(x: 350, y: 445, width: 105, height: 68), color: green)
|
||||
arrow(CGPoint(x: 402, y: 378), CGPoint(x: 275, y: 445), color: cyan)
|
||||
arrow(CGPoint(x: 300, y: 479), CGPoint(x: 350, y: 479), color: orange)
|
||||
callout("보안 핵심", "tenant_id를 요청 body에서 받으면 사용자가 다른 회사 ID를 넣어 위조할 수 있습니다. 이 프로젝트는 헤더/경로에서 결정한 값을 middleware가 request.state에 넣고, 뒤의 코드가 그것만 사용합니다.",
|
||||
rect: CGRect(x: margin, y: 558, width: 507, height: 105), color: red)
|
||||
comparison("멀티테넌시 경계가 약하면", "A회사 요청이 B회사 카드·설정·협상 엔진을 사용할 수 있습니다. 이는 단순 버그가 아니라 데이터 유출 사고입니다.",
|
||||
"현재 방식", "요청 시작점에서 tenant를 검증하고, Registry가 해당 회사의 설정과 엔진을 해석합니다.",
|
||||
y: 687, color: purple)
|
||||
endPage(ctx)
|
||||
|
||||
// 11 multitenancy code
|
||||
beginPage(ctx, page: 11)
|
||||
sectionTitle("5", "멀티테넌시 — 실제 코드", "식별 → 검증 → request.state 전달 → 회사별 엔진 선택의 4단계", color: purple)
|
||||
codeBox("Middleware: tenant를 요청 경계에서 확정",
|
||||
"agent/router/middleware/tenant_middleware.py · lines 35–69",
|
||||
"""
|
||||
tenant_id = request.headers.get("X-Tenant-ID")
|
||||
|
||||
if not tenant_id:
|
||||
return JSONResponse(status_code=400, ...)
|
||||
|
||||
if not tenant_registry.is_registered(tenant_id):
|
||||
return JSONResponse(status_code=404, ...)
|
||||
|
||||
request.state.tenant_id = tenant_id
|
||||
return await call_next(request)
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 205), accent: purple)
|
||||
codeBox("Dependency: 검증된 tenant로 엔진 조회",
|
||||
"agent/router/deps.py · lines 13–21",
|
||||
"""
|
||||
async def get_tenant_engine(request: Request) -> TenantEngine:
|
||||
tenant_id = getattr(request.state, "tenant_id", None)
|
||||
if not tenant_id:
|
||||
raise EXCEPTION_TENANT_HEADER_MISSING
|
||||
return await tenant_registry.get_engine(tenant_id)
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 360, width: 507, height: 165), accent: cyan)
|
||||
codeBox("Registry: 프로세스 메모리에서 회사별 엔진 재사용",
|
||||
"agent/tenancy/registry.py · lines 85–98",
|
||||
"""
|
||||
cached = self._engines.get(tenant_id)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
async with self._locks[tenant_id]:
|
||||
cached = self._engines.get(tenant_id)
|
||||
if cached is not None:
|
||||
return cached
|
||||
engine = await self._build(tenant_id)
|
||||
self._engines[tenant_id] = engine
|
||||
return engine
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 550, width: 507, height: 205), accent: orange)
|
||||
endPage(ctx)
|
||||
|
||||
// 12 — Cache consistency: concept first
|
||||
beginPage(ctx, page: 12)
|
||||
sectionTitle("8", "캐시 정합성 — 개념부터", "비싼 계산·DB·외부 호출의 결과를 가까운 곳에 복사해 재사용하는 기술", color: red)
|
||||
drawText("기본 용어", CGRect(x: margin, y: 126, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
let cacheTerms: [(String, String, NSColor)] = [
|
||||
("Hit", "캐시에 값이 있어 원본을 읽지 않음", green),
|
||||
("Miss", "값이 없어 원본을 읽고 캐시를 채움", blue),
|
||||
("TTL", "값이 자동 만료될 때까지의 시간", orange),
|
||||
("Stale", "원본은 바뀌었지만 캐시는 옛 값인 상태", red),
|
||||
]
|
||||
for (i, t) in cacheTerms.enumerated() {
|
||||
let x = margin + CGFloat(i % 2) * 260
|
||||
let y = CGFloat(165 + (i / 2) * 75)
|
||||
callout(t.0, t.1, rect: CGRect(x: x, y: y, width: 247, height: 60), color: t.2)
|
||||
}
|
||||
drawText("대표적인 읽기·쓰기 패턴", CGRect(x: margin, y: 338, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
callout("Cache-aside", "앱이 캐시를 먼저 조회하고 miss이면 DB를 읽어 캐시에 저장합니다. 단순하고 가장 흔하지만 무효화를 앱이 책임집니다.",
|
||||
rect: CGRect(x: margin, y: 378, width: 247, height: 92), color: blue)
|
||||
callout("Write-through", "쓰기 때 캐시와 원본을 함께 갱신합니다. 읽기는 안정적이지만 쓰기 지연과 두 저장소의 부분 실패를 다뤄야 합니다.",
|
||||
rect: CGRect(x: 304, y: 378, width: 247, height: 92), color: purple)
|
||||
callout("Write-behind", "캐시에 먼저 쓰고 DB는 나중에 반영합니다. 빠르지만 캐시 장애 시 데이터 유실 위험이 있어 업무 원본에는 신중해야 합니다.",
|
||||
rect: CGRect(x: margin, y: 486, width: 247, height: 92), color: orange)
|
||||
callout("Negative cache", "‘결과 없음’도 잠깐 저장합니다. 반복 실패 비용을 줄이지만 너무 긴 TTL은 새로 생긴 데이터를 늦게 발견하게 합니다.",
|
||||
rect: CGRect(x: 304, y: 486, width: 247, height: 92), color: green)
|
||||
drawText("캐시에서 자주 생기는 문제", CGRect(x: margin, y: 610, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
callout("Invalidation", "원본 변경 후 어떤 key를 언제 삭제·갱신할지 결정하기 어렵습니다.",
|
||||
rect: CGRect(x: margin, y: 650, width: 159, height: 82), color: red)
|
||||
callout("Stampede", "인기 key가 만료되는 순간 많은 요청이 동시에 DB로 몰립니다.",
|
||||
rect: CGRect(x: 218, y: 650, width: 159, height: 82), color: orange)
|
||||
callout("Key 설계", "tenant·버전 등이 빠지면 서로 다른 데이터가 같은 key를 공유합니다.",
|
||||
rect: CGRect(x: 392, y: 650, width: 159, height: 82), color: purple)
|
||||
endPage(ctx)
|
||||
|
||||
// 13 cache concept
|
||||
beginPage(ctx, page: 13)
|
||||
sectionTitle("8", "캐시 정합성과 무효화", "빠른 복사본이 원본과 다른 값을 갖지 않도록 관리하는 문제", color: red)
|
||||
callout("캐시는 복사본", "도서관 검색대의 메모가 캐시이고, 원본 장부가 DB라고 생각하면 쉽습니다. 메모는 빠르지만 오래된 정보일 수 있습니다. 정합성이란 메모와 장부가 의미상 같은 상태를 유지하는 것입니다.",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 95), color: red)
|
||||
drawText("앵커링 값의 저장·조회 순서", CGRect(x: margin, y: 252, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("1. DB 저장", "조정 이력 COMMIT", rect: CGRect(x: 46, y: 310, width: 118, height: 70), color: purple)
|
||||
node("2. Redis SET", "최신값 + TTL 7일", rect: CGRect(x: 238, y: 310, width: 118, height: 70), color: red)
|
||||
node("3. 다음 조회", "Redis 우선", rect: CGRect(x: 430, y: 310, width: 118, height: 70), color: blue)
|
||||
arrow(CGPoint(x: 164, y: 345), CGPoint(x: 238, y: 345), color: purple)
|
||||
arrow(CGPoint(x: 356, y: 345), CGPoint(x: 430, y: 345), color: red)
|
||||
drawText("Redis 실패", CGRect(x: 240, y: 417, width: 110, height: 18), size: 9, color: red, weight: .bold)
|
||||
arrow(CGPoint(x: 297, y: 380), CGPoint(x: 297, y: 465), color: red)
|
||||
node("DB Fallback", "업무는 계속", rect: CGRect(x: 238, y: 465, width: 118, height: 70), color: green)
|
||||
callout("stale 데이터란?", "DB에는 새 값 60이 저장됐는데 Redis SET이 실패해 캐시에 옛 값 55가 남은 상태입니다. 캐시 miss와 달리 값이 존재하므로 더 위험합니다. TTL과 주간 re-SET으로 회복합니다.",
|
||||
rect: CGRect(x: margin, y: 574, width: 507, height: 95), color: orange)
|
||||
comparison("캐시만 믿으면", "Redis 장애가 업무 장애가 되고, 오래된 값이 실제 제안가를 왜곡할 수 있습니다. Redis 유실 시 원본도 사라집니다.",
|
||||
"원본 DB + 파생 캐시", "Redis 장애 시 DB를 읽고, TTL과 reconciliation으로 오래된 복사본을 교정합니다.",
|
||||
y: 693, color: red)
|
||||
endPage(ctx)
|
||||
|
||||
// 14 cache code
|
||||
beginPage(ctx, page: 14)
|
||||
sectionTitle("8", "캐시 정합성 — 실제 코드", "Cache-aside, TTL, DB fallback, reconciliation이 한 세트로 작동합니다.", color: red)
|
||||
codeBox("Cache-aside: Redis miss → DB → Redis backfill",
|
||||
"schedules/anchoring/src/anchoring/reader.py · lines 33–42",
|
||||
"""
|
||||
cached = await get_value(company_id, supplier_type, price_range)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
value = await get_latest_adjusted_value(
|
||||
db, company_id, supplier_type, price_range
|
||||
)
|
||||
if value is None:
|
||||
value = get_base_anchoring_value(price_range)
|
||||
|
||||
await set_value(..., value, nx=True)
|
||||
return value
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 225), accent: red)
|
||||
codeBox("Redis 장애는 cache miss로 취급",
|
||||
"schedules/anchoring/src/anchoring/redis_client.py · lines 69–84",
|
||||
"""
|
||||
try:
|
||||
raw = await _client.get(anchor_key(...))
|
||||
if raw is None:
|
||||
return None
|
||||
return int(raw)
|
||||
except Exception as ex:
|
||||
_note_failure("get", anchor_key(...), ex)
|
||||
return None # 호출측이 DB fallback
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 380, width: 507, height: 180), accent: orange)
|
||||
callout("두 겹의 회복 장치", "TTL 7일은 오래된 키가 영원히 남는 것을 막습니다. 주간 reconciliation은 DB의 최신 조정값을 Redis에 다시 SET하여, DB commit 뒤 Redis 갱신에 실패했던 값도 교정합니다.",
|
||||
rect: CGRect(x: margin, y: 585, width: 507, height: 100), color: red)
|
||||
callout("현재 견적 생성 경로의 예외", "Negodata의 실제 견적 생성은 Redis를 사용하지 않고 PostgreSQL의 anchoring.current_values View를 일괄 조회합니다. Redis는 현재 anchoring 배치 내부 캐시입니다.",
|
||||
rect: CGRect(x: margin, y: 705, width: 507, height: 72), color: cyan)
|
||||
endPage(ctx)
|
||||
|
||||
// 15 — Scheduler and batch: concept first
|
||||
beginPage(ctx, page: 15)
|
||||
sectionTitle("9", "스케줄러·배치 — 개념부터", "시간 규칙으로 작업을 시작하고, 많은 데이터를 사용자 요청 밖에서 처리하는 방식", color: green)
|
||||
callout("둘의 차이", "스케줄러는 ‘언제 실행할지’를 결정합니다. 배치 Job은 ‘무엇을 어떻게 처리할지’를 구현합니다. CronTrigger가 알람시계라면 close_expired_quotations는 알람이 울렸을 때 수행할 실제 업무입니다.",
|
||||
rect: CGRect(x: margin, y: 126, width: 507, height: 92), color: green)
|
||||
drawText("Job의 생명주기", CGRect(x: margin, y: 248, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("Trigger", "실행 시각 도달", rect: CGRect(x: 45, y: 297, width: 94, height: 66), color: green)
|
||||
node("Select", "처리 대상 조회", rect: CGRect(x: 181, y: 297, width: 94, height: 66), color: blue)
|
||||
node("Process", "개별 업무 수행", rect: CGRect(x: 317, y: 297, width: 94, height: 66), color: orange)
|
||||
node("Checkpoint", "결과·진행점 기록", rect: CGRect(x: 453, y: 297, width: 94, height: 66), color: purple)
|
||||
arrow(CGPoint(x: 139, y: 330), CGPoint(x: 181, y: 330), color: green)
|
||||
arrow(CGPoint(x: 275, y: 330), CGPoint(x: 317, y: 330), color: blue)
|
||||
arrow(CGPoint(x: 411, y: 330), CGPoint(x: 453, y: 330), color: orange)
|
||||
drawText("운영에서 반드시 결정할 것", CGRect(x: margin, y: 405, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
let jobIssues: [(String, String, NSColor)] = [
|
||||
("중복 실행", "이전 Job이 안 끝났는데 다음 시각이 오면?", red),
|
||||
("Misfire", "서버가 꺼져 실행 시각을 놓쳤다면?", orange),
|
||||
("부분 실패", "100건 중 73번째가 실패하면 어디부터 재개?", purple),
|
||||
("재시도", "즉시 재시도, 다음 tick, 운영자 재처리 중 무엇?", blue),
|
||||
("멱등성", "같은 대상을 다시 처리해도 중복 효과가 없는가?", green),
|
||||
("관측성", "처리량·실패 대상·소요시간을 로그와 지표로 남기는가?", cyan),
|
||||
]
|
||||
for (i, j) in jobIssues.enumerated() {
|
||||
let x = margin + CGFloat(i % 2) * 260
|
||||
let y = CGFloat(445 + (i / 2) * 73)
|
||||
callout(j.0, j.1, rect: CGRect(x: x, y: y, width: 247, height: 58), color: j.2)
|
||||
}
|
||||
callout("스케줄러만으로 정확성은 보장되지 않음", "max_instances=1은 한 프로세스 안의 중복을 막을 뿐입니다. 서버가 여러 대면 각 서버가 Job을 실행할 수 있으므로 DB 조건부 갱신, 분산 락, 전용 Worker 같은 추가 방어가 필요합니다.",
|
||||
rect: CGRect(x: margin, y: 680, width: 507, height: 105), color: red)
|
||||
endPage(ctx)
|
||||
|
||||
// 16 scheduler concept
|
||||
beginPage(ctx, page: 16)
|
||||
sectionTitle("9", "스케줄러와 배치 안정성", "사용자 요청 없이 정해진 시간마다 반복 업무를 수행하는 백그라운드 실행", color: green)
|
||||
callout("쉬운 비유", "API가 손님이 주문할 때 움직이는 직원이라면, 스케줄러는 매 5분마다 마감 시간이 지난 주문을 확인하는 당직자입니다. 사람이 요청하지 않아도 시간이 되면 일을 시작합니다.",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 92), color: green)
|
||||
drawText("5분 tick의 세 가지 작업", CGRect(x: margin, y: 252, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("CronTrigger", "매 5분", rect: CGRect(x: 48, y: 315, width: 105, height: 68), color: green)
|
||||
node("잡 ①", "기한 지난 견적 마감", rect: CGRect(x: 225, y: 280, width: 135, height: 62), color: orange)
|
||||
node("잡 ②", "협상 완료 견적 마감", rect: CGRect(x: 225, y: 365, width: 135, height: 62), color: purple)
|
||||
node("잡 ③", "LPS 결과 증분 반영", rect: CGRect(x: 225, y: 450, width: 135, height: 62), color: cyan)
|
||||
arrow(CGPoint(x: 153, y: 349), CGPoint(x: 225, y: 311), color: green)
|
||||
arrow(CGPoint(x: 153, y: 349), CGPoint(x: 225, y: 396), color: green)
|
||||
arrow(CGPoint(x: 153, y: 349), CGPoint(x: 225, y: 481), color: green)
|
||||
node("PostgreSQL", "조건부 처리·기록", rect: CGRect(x: 430, y: 365, width: 115, height: 72), color: blue)
|
||||
arrow(CGPoint(x: 360, y: 311), CGPoint(x: 430, y: 385), color: orange)
|
||||
arrow(CGPoint(x: 360, y: 396), CGPoint(x: 430, y: 401), color: purple)
|
||||
arrow(CGPoint(x: 360, y: 481), CGPoint(x: 430, y: 420), color: cyan)
|
||||
callout("중복 실행 방지 장치", "SCHEDULER_ENABLED=1인 프로세스 하나만 잡을 등록합니다. 각 잡은 max_instances=1이고, 밀린 실행은 coalesce=True로 한 번만 실행합니다. 그래도 다중 서버 가능성을 고려해 DB의 조건부 UPDATE가 마지막 방어선입니다.",
|
||||
rect: CGRect(x: margin, y: 565, width: 507, height: 115), color: green)
|
||||
comparison("안정 장치가 없으면", "서버 Worker 수만큼 같은 잡이 실행되고, 같은 견적을 여러 번 마감하거나 알림을 중복 발송할 수 있습니다.",
|
||||
"현재 방식", "실행 프로세스 제한 + 잡 중복 제한 + DB 동시성 가드를 겹쳐 사용합니다.",
|
||||
y: 704, color: green)
|
||||
endPage(ctx)
|
||||
|
||||
// 17 scheduler code
|
||||
beginPage(ctx, page: 17)
|
||||
sectionTitle("9", "스케줄러·배치 — 실제 코드", "‘언제 실행할지’와 ‘무엇을 안전하게 처리할지’를 분리합니다.", color: green)
|
||||
codeBox("APScheduler 등록: 5분, 중복 방지, 지연 허용",
|
||||
"negodata/backend/scheduler/__init__.py · lines 37–69",
|
||||
"""
|
||||
_scheduler = AsyncIOScheduler(timezone="Asia/Seoul")
|
||||
_scheduler.add_job(
|
||||
jobs.close_expired_quotations,
|
||||
CronTrigger(minute="*/5"),
|
||||
id="close_expired_quotations",
|
||||
coalesce=True, # 밀린 실행은 1번만
|
||||
misfire_grace_time=600, # 10분 내 지연 실행 허용
|
||||
max_instances=1, # 같은 잡 동시 실행 금지
|
||||
)
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 215), accent: green)
|
||||
codeBox("Job: 대상 조회와 개별 마감 처리를 분리",
|
||||
"negodata/backend/scheduler/jobs.py · lines 39–61",
|
||||
"""
|
||||
err_type, qt_ids = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: crud.list_due_for_close(s, now),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return 0
|
||||
|
||||
results = await _close_each(service, qt_ids)
|
||||
return sum(results.values())
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 370, width: 507, height: 190), accent: cyan)
|
||||
callout("멱등성(idempotency)", "같은 잡을 두 번 실행해도 최종 결과가 한 번 실행한 것과 같도록 만드는 성질입니다. 대상 조회가 중복될 수 있어도 claim_for_close의 조건부 UPDATE가 두 번째 처리를 rowcount=0으로 막습니다.",
|
||||
rect: CGRect(x: margin, y: 585, width: 507, height: 105), color: purple)
|
||||
callout("실패한 tick은 어떻게 되나요?", "LPS 동기화는 watermark 기반 증분 처리라 실패한 회차의 데이터가 다음 5분 tick에서 다시 대상이 됩니다. 스케줄러 자체 재시도보다 데이터 설계를 통해 회복합니다.",
|
||||
rect: CGRect(x: margin, y: 710, width: 507, height: 72), color: green)
|
||||
endPage(ctx)
|
||||
|
||||
// 18 combined scenario
|
||||
beginPage(ctx, page: 18)
|
||||
drawText("다섯 기술이 한 장면에서 만나는 순간", CGRect(x: margin, y: 48, width: 507, height: 34),
|
||||
size: 23, color: navy, weight: .bold)
|
||||
drawText("예: 협상이 모두 끝난 견적을 스케줄러가 자동 마감하는 동안 담당자가 수동 마감을 클릭했다.",
|
||||
CGRect(x: margin, y: 88, width: 507, height: 30), size: 10.5, color: muted)
|
||||
let rows: [(String, String, NSColor)] = [
|
||||
("1", "멀티테넌시: 요청의 X-Tenant-ID로 어느 회사의 협상 엔진과 데이터인지 결정", purple),
|
||||
("2", "분산 시스템: Backend가 Agent를 HTTP로 호출할 때 timeout과 부분 실패를 구분", blue),
|
||||
("3", "스케줄러: 5분 tick이 동일 견적을 마감 대상으로 발견", green),
|
||||
("4", "동시성 제어: 수동 요청과 스케줄러 중 조건부 UPDATE를 먼저 성공한 쪽만 처리", orange),
|
||||
("5", "트랜잭션: 관련 상태 변경을 commit하거나, 실패하면 rollback", cyan),
|
||||
("6", "캐시 정합성: 원본 DB commit 후 파생 캐시를 갱신하고 실패 시 다음 회차에 회복", red),
|
||||
]
|
||||
for (i, item) in rows.enumerated() {
|
||||
let y = CGFloat(145 + i * 91)
|
||||
rounded(CGRect(x: margin, y: y, width: 507, height: 70), radius: 12,
|
||||
fill: item.2.withAlphaComponent(0.08), stroke: item.2.withAlphaComponent(0.30))
|
||||
rounded(CGRect(x: 58, y: y + 15, width: 40, height: 40), radius: 20,
|
||||
fill: item.2, stroke: nil)
|
||||
drawText(item.0, CGRect(x: 58, y: y + 24, width: 40, height: 20), size: 13,
|
||||
color: .white, weight: .bold, align: .center)
|
||||
drawText(item.1, CGRect(x: 116, y: y + 15, width: 415, height: 42), size: 10.2,
|
||||
color: ink, weight: .medium, lineSpacing: 3)
|
||||
if i < rows.count - 1 {
|
||||
arrow(CGPoint(x: 78, y: y + 70), CGPoint(x: 78, y: y + 90), color: item.2)
|
||||
}
|
||||
}
|
||||
callout("핵심 관점", "어려운 백엔드 기술은 ‘라이브러리 이름’보다 경계와 실패를 다루는 방법입니다. 네트워크 경계, 회사 경계, 트랜잭션 경계, 캐시의 원본 경계를 명확하게 설계하는 것이 핵심입니다.",
|
||||
rect: CGRect(x: margin, y: 708, width: 507, height: 78), color: navy)
|
||||
endPage(ctx)
|
||||
|
||||
// 19 glossary
|
||||
beginPage(ctx, page: 19)
|
||||
drawText("초보자를 위한 한 줄 사전", CGRect(x: margin, y: 48, width: 507, height: 34),
|
||||
size: 24, color: navy, weight: .bold)
|
||||
let glossary: [(String, String)] = [
|
||||
("분산 시스템", "여러 프로세스·서버가 네트워크로 협력하는 시스템"),
|
||||
("부분 실패", "전체 중 일부 서비스만 실패한 상태"),
|
||||
("Timeout", "응답을 무한히 기다리지 않고 정해진 시간에 포기하는 제한"),
|
||||
("Best-effort", "실패해도 핵심 업무는 성공시키는 보조 작업 정책"),
|
||||
("트랜잭션", "여러 DB 변경을 모두 성공 또는 모두 취소하는 작업 단위"),
|
||||
("Rollback", "실패했을 때 트랜잭션의 변경을 되돌리는 것"),
|
||||
("Race condition", "실행 순서에 따라 결과가 달라지는 동시성 문제"),
|
||||
("원자적 연산", "중간 상태가 보이지 않도록 한 번에 처리되는 연산"),
|
||||
("멀티테넌시", "한 시스템을 여러 고객사가 격리된 상태로 공유하는 구조"),
|
||||
("Cache-aside", "캐시를 먼저 보고, miss이면 원본 조회 후 캐시를 채우는 패턴"),
|
||||
("TTL", "캐시 값이 자동 만료되기까지의 시간"),
|
||||
("Stale", "원본보다 오래되어 현재와 맞지 않는 캐시 상태"),
|
||||
("Invalidation", "원본 변경 시 캐시를 삭제하거나 무효화하는 것"),
|
||||
("Reconciliation", "원본과 복사본을 비교·재적재해 다시 맞추는 작업"),
|
||||
("Scheduler", "정해진 시간 규칙에 따라 작업을 실행하는 도구"),
|
||||
("Batch", "사용자 요청과 별개로 데이터 묶음을 주기적으로 처리하는 작업"),
|
||||
("멱등성", "같은 작업을 반복해도 최종 결과가 달라지지 않는 성질"),
|
||||
]
|
||||
for (i, g) in glossary.enumerated() {
|
||||
let col = i < 9 ? 0 : 1
|
||||
let row = col == 0 ? i : i - 9
|
||||
let x = margin + CGFloat(col) * 260
|
||||
let y = CGFloat(128 + row * 69)
|
||||
drawText(g.0, CGRect(x: x, y: y, width: 230, height: 19), size: 10.5,
|
||||
color: [blue, orange, purple, red, green][i % 5], weight: .bold)
|
||||
drawText(g.1, CGRect(x: x, y: y + 23, width: 230, height: 36), size: 8.8,
|
||||
color: ink, lineSpacing: 2)
|
||||
}
|
||||
callout("추천 복습 순서", "트랜잭션·동시성 → 캐시 정합성 → 스케줄러 → 멀티테넌시 → 분산 시스템 순으로 다시 보면, 작은 DB 작업에서 전체 서비스 구조로 이해가 확장됩니다.",
|
||||
rect: CGRect(x: margin, y: 718, width: 507, height: 74), color: blue)
|
||||
endPage(ctx)
|
||||
|
||||
ctx.closePDF()
|
||||
print(outPath)
|
||||
@ -1,108 +0,0 @@
|
||||
# 협상 QA 체크리스트 (260727 요청 검증)
|
||||
|
||||
> 대상: **negodata 어드민**(:3000) + **negosium 공급사 포털**(:3300). 두 앱을 함께 돌려야 하는 플로우라 루트 `docs/`에 둔다.
|
||||
> 형식: 케이스별 `~하면 → ~나와야 한다`. 근거는 코드 검증(2026-07-30) 기준. ⚠=현재 알려진 이슈.
|
||||
> 런타임 주의: negosium front/backend는 이미지 빌드라 코드 수정은 **재빌드해야 반영**된다.
|
||||
|
||||
---
|
||||
|
||||
## 0. 요청사항 반영 현황 (코드 검증 결과, Excel 상태열 아님)
|
||||
|
||||
| # | 요청 | 판정 | 비고 |
|
||||
|---|------|------|------|
|
||||
| 2 | 견적관리 리스트+히스토리·상세 | ✅ | /quotation + `?detail=` 시트(협상현황/대화/카드, 라운드 타임라인) |
|
||||
| 3 | 재협상 리스트·심사 | ✅ | /renegotiation 대기/승인/반려 |
|
||||
| 4 | MD→구매담당자·판매가 미노출·위치 | ✅ | |
|
||||
| 5/23 | 목표가=매입가×(1−네고율) 자동 | ✅ | 재/재견적 한정, 네고율=견적세팅 목표마진 |
|
||||
| 6 | 공급가=매입가 일원화 | ⚙ 설정 | 코드 지원됨(`hideCls`). IMK `hidden_fields`에 `"price"` 추가하면 매입가만 남음 |
|
||||
| 7 | 최저가 크롤 + VAT산식 | ⚠ 인프라 / 논이슈 | VAT는 설정·아이템별 처리(논이슈). 단 dev의 lps-worker 크래시+수집테이블 0행 → 수집 파이프라인 확인 필요 |
|
||||
| 8 | 신규 상품 공급사 입력칸 | ✅ | |
|
||||
| 9 | SG명/유통레벨 콤보·취급상품 삭제 | ❌ 미구현 | §9 참조 |
|
||||
| 10 | 리드타임→표준납기 | ✅ 수정 | Summary.tsx 하드코딩 라벨 회사설정 반영으로 수정(2026-07-30) |
|
||||
| 11 | 단가 VAT별도 | ✅ | 회사설정 `item_vat_yn` 동적(IMK는 vat_yn hidden) |
|
||||
| 12 | 앵커 10원 반올림 | ✅ | `calc_anchoring_price` + 카드 카운터(`compute_counter`) + 와일드카드 1%(2026-07-31 수정) 모두 10원 반올림 |
|
||||
| 13 | 절충안 계산식 | ✅ | `compute_counter` 점검, 버그 없음 |
|
||||
| 14/17 | 결렬 희망가 입력란 통일 | ✅ | 단일 RejectForm |
|
||||
| 15 | 마무리 배송 콤보/기타의견/투찰요약 | ✅ | ExtraInfoBar가 session_fields select 렌더 → 콤보 [직납/IMK배송/IMK집배송] |
|
||||
| 16 | 제안가 갭·반올림 | ✅ | 갭은 정상(목표가=후보 min×수수료). 봇 제안가(카운터·와일드카드 1%)도 10원 반올림 반영(2026-07-31) |
|
||||
| 18/22 | 성공률 기준·결렬 무관 | ✅ | 게이지는 참고용, 판정과 무관(§D). 타결=목표가 아래로/봇 카운터 수락, 결렬=카드3+최종제안 소진까지 목표가 위 |
|
||||
| 19/25 | 종료 의견 단계 | ✅ | 타결 ExtraInfoBar(custom.opinion)+결렬 RejectForm 의견 |
|
||||
| 20 | 결렬사유 상시노출·필수 | ✅ 검증 | 결렬 세션 9/9 사유 존재. §20 참조 |
|
||||
| 21 | 카드 3회 초과 | ✅ 정상 | 3회=협상카드 한도. 와일드카드·최종제안은 별도로 붙는 구조라 보이는 카드가 3장을 넘을 수 있음(§21) |
|
||||
| 24 | 목표가 필드 1→3.낙찰기준 이동 | ✅ | |
|
||||
|
||||
---
|
||||
|
||||
## A. 견적 생성 (어드민)
|
||||
- **A1** 재/재견적에서 매입가 10,000·네고율(견적세팅 목표마진) 2% 입력 → 목표가(구매담당자 제시가) 필드에 **9,800 자동 채움**(10원 반올림)
|
||||
- **A2** 목표가 직접 안 건드리고 생성 → `md_price=null`로 전송, 서버가 후보 최솟값으로 재산정
|
||||
- **A3** **신규**협상/신규견적 → 매입가 후보 빠지고 인터넷최저가만 사용 → 자동 목표가가 매입가 기반이 아님(A1과 다른 게 정상)
|
||||
- **A4** 1.기본정보엔 목표가 없어야 / **3.낙찰기준** 스텝에 목표가+산정후보 나와야
|
||||
- **A5** 판매가 입력칸 없어야 / 라벨 "구매담당자 제시가"
|
||||
|
||||
## B. 앵커·제안가
|
||||
- **B1** 협상 시작 → 세션 앵커가 = 목표가×(1−1%), **끝자리 0** (예 목표 7,650 → 앵커 7,570)
|
||||
- **B2** 봇 재제안가 전부 **끝자리 0** — 카드 카운터(절충가·목표가 제시)와 **와일드카드 1% 인하가** 포함 (예 제시 15,555 → 1% 인하가 15,400). 1원 단위가 보이면 불량
|
||||
|
||||
## C. 협상 진행 (실시간 챗, 공급사 포털)
|
||||
- **C1** 제시가 **≤ 앵커가** → **즉시 협상완료(투찰 확정)**, 성공률 99
|
||||
- **C2** 앵커가 < 제시가 ≤ 앵커×1.02 → **와일드카드 1% 인하 요청**(세션 1회), 성공률 99~80
|
||||
- **C3** 앵커×1.02 초과 → **일반 협상카드로 재제안(최대 3번)**, 성공률 표시(제시가 낮을수록↑)
|
||||
- **C4** 카드 소진 또는 재제안 3번 후에도 앵커 밑 못 내림 → **협상 실패(결렬, 투찰 없음)**
|
||||
- **C5** 카드 사용한도 3은 **협상카드에만** 적용. **와일드카드·최종제안은 별도로 붙어** 공급사가 보는 카드가 3장을 넘을 수 있음(정상, §21)
|
||||
- **C6** 단가는 **VAT별도** 표기(IMK는 VAT 라벨 자체 숨김)
|
||||
|
||||
## D. 타결/결렬 판정 & 성공률 게이지
|
||||
- **판정 규칙**: 유저가 **목표가 아래로 내리거나** 봇이 되받은 제시가(카운터)를 **수락하면 타결**. **카드(3장)+최종제안**까지 다 소진될 때까지 **목표가 위에서 버티면 결렬**.
|
||||
- **D1** 성공률 게이지는 **참고용일 뿐 판정과 무관** — 제시가 낮을수록 게이지↑(상한 99, **100% 도달 안 함**).
|
||||
- **D2** 성공률 낮아도 무조건 결렬 아님. 최종 마감(낙찰/개찰)은 별도 기준(§G).
|
||||
|
||||
## E. 협상 타결(완료) 마무리
|
||||
- **E1** 협상완료 → **부가정보 입력 단계 등장** (표준납기·최소주문수량·발주배수·배송유형·의견)
|
||||
- **E2** 배송유형 → **콤보 [직납/IMK배송/IMK집배송]**로 떠야 (자유입력·다른 라벨이면 불량)
|
||||
- **E3** 의견(선택) 작성 → `custom.opinion` 저장돼야
|
||||
- **E4** 입력 완료 → **투찰결과 요약 갱신 후 최종 안내**, 요약에 부가정보·의견 반영
|
||||
- **E5** 어드민 상세(협상현황/요약)에서 부가정보 **표시+잠금(읽기전용)**
|
||||
|
||||
## F. 협상 결렬(실패)
|
||||
- **F1** 결렬 → **결렬 사유 입력 단계 항상 노출 + 필수**(견적/유형 무관 동일 폼)
|
||||
- **F2** 사유 프리셋(단가인상/수량/단종/품절)+기타, **기타 선택 시 사유 텍스트 필수**
|
||||
- **F3** 희망가격 입력 = **단일 폼**(RSP/CM 동일)
|
||||
- **F4** 의견(선택) 작성 가능
|
||||
- **F5** 검증: 결렬(협상거부) 세션은 **100% 사유가 기록**돼야 (사유 없는 결렬 세션 = 불량). §20
|
||||
|
||||
## G. 마감 · 낙찰/개찰
|
||||
- **G1** 투찰가 ≤ 앵커가 → **낙찰**
|
||||
- **G2** 앵커~목표가 → 1:1은 **사용자 지정**(mid_action), 1:N은 낙찰
|
||||
- **G3** 목표가 초과 → 1:1 **사용자 지정**(over_action, 관례 개찰), 1:N 낙찰
|
||||
- **G4** 동가(최저 2곳+)·전원 미응찰·협상거부 → **개찰**(낙찰자 미정, 결렬 아님) / 마감사유 라벨 정확히
|
||||
|
||||
## H. 재협상 요청·심사 (공급사→어드민)
|
||||
- **H1** 개찰 마감 + 본인 마지막 라운드 → **재협상 요청 가능**(사유+희망가), 담당자 알림 1건
|
||||
- **H2** 낙찰건/남의 세션 요청 → **거부**
|
||||
- **H3** 같은 세션 2회 요청 → 2번째 **거부**; 철회 후 재요청 가능
|
||||
- **H4** 어드민 /renegotiation 대기 탭 접수 → **승인 시 다음 차수 견적 생성**, 반려 시 사유 필수
|
||||
|
||||
---
|
||||
|
||||
## 알려진 이슈 상세
|
||||
|
||||
### §9. 협력사 SG명/유통레벨 콤보·취급상품 삭제 — 미구현
|
||||
요청 4가지 모두 현재 구조와 다르다:
|
||||
1. **분류카테고리 → SG명**: 지금 '분류카테고리'는 **입력 필드가 아니라 취급상품에서 파생 집계**되는 읽기전용 값(`SupplierItemsManager.tsx`). 회사 라벨(labels.category)로 "SG명" 표기만 되지, 직접 고르는 필드가 아님.
|
||||
2. **선택콤보(취급 SG명)**: 등록된 SG명 중 선택하는 콤보 없음.
|
||||
3. **유통레벨 콤보(제조/총판/대리점/일반유통)**: 없음. 유사한 건 취급상품별 **공급유형** 콤보인데 값이 다름(유통/제조/총판/없음). '대리점'·'일반유통' 값 자체가 코드에 없음. IMK 설정의 `supplier_fields.distribution_level`은 콤보가 아니라 **텍스트** 커스텀 필드.
|
||||
4. **취급상품 칸 삭제**: 삭제 안 됨(등록/수정폼·엑셀업로드에 그대로).
|
||||
- 근본: IMK는 SG명·유통레벨을 **협력사 레벨 속성(콤보)**으로 두고 취급상품 목록은 없애길 원함. 현재는 반대로 **취급상품(supplier_items)에서 카테고리·공급유형을 파생**하는 모델. → 데이터 모델 전환이 필요한 작업.
|
||||
|
||||
### §20. 결렬 사유 상시 노출·필수 — 검증 완료
|
||||
- agent의 모든 실패 경로가 단일 step `"협상실패"`(chat_end)로 수렴 → backend가 rejectRSP/CM로 무조건 매핑 → 프론트 통일 RejectForm(사유 필수). 세션 상태 분기 없음.
|
||||
- 실데이터: 협상거부(status=5) 9건 **전부 reject_reason 존재**, 사유 없는 결렬 0건.
|
||||
- 원 버그의 "견적마다 상이"는 *대화 중 결렬*(사유 있음) vs *미참여/마감 자동종료*(대화 자체 없음 → 사유 없음)의 구분이었을 뿐, 결렬 플로우는 일관됨.
|
||||
|
||||
### §21. 카드 3회 초과 — 정상 동작(버그 아님)
|
||||
`card_count=3`은 **협상카드 사용 한도**다. 와일드카드와 최종제안(종결)은 이 한도와 **별개로 각각 붙는** 구조라, 공급사가 보는 카드가 3장을 넘을 수 있다.
|
||||
1. **와일드카드 1장**(1% 인하/동적 카운터) — 협상카드 카운트와 별개.
|
||||
2. **최종제안 1장**(중간값 절충/최후통첩) — 카드 소진 후 마지막 국면에 별도로 붙음.
|
||||
→ 협상카드 3 + 와일드 1 + 최종제안 1 = 최대 5장 노출(예: EST-202607-4DB5).
|
||||
- 참고(엣지): 세션에 견적세팅(card_count)이 연결 안 되면 한도가 안 걸릴 수 있으니, 설정이 항상 세션에 물리는지만 확인.
|
||||
@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/png" href="/bot.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>AI 가격 협상 솔루션</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@ -11,7 +11,6 @@ import type {
|
||||
LogoutResponse,
|
||||
MeResponse,
|
||||
PopupStatusResponse,
|
||||
SessionBrandingResponse,
|
||||
} from './auth.type'
|
||||
|
||||
export const authApi = {
|
||||
@ -27,12 +26,6 @@ export const authApi = {
|
||||
return res.data
|
||||
},
|
||||
|
||||
/** GET /v1/auth/session-branding/{sessionId} — 로그인 전 화면용 브랜딩(인증 불필요) */
|
||||
sessionBranding: async (sessionId: string): Promise<SessionBrandingResponse> => {
|
||||
const res = await http.get<SessionBrandingResponse>(`/v1/auth/session-branding/${sessionId}`)
|
||||
return res.data
|
||||
},
|
||||
|
||||
/** GET /v1/auth/me — 현재 로그인 유저 정보 (access token 필요) */
|
||||
me: async (): Promise<MeResponse> => {
|
||||
const res = await http.get<MeResponse>('/v1/auth/me')
|
||||
|
||||
@ -54,28 +54,6 @@ export interface RefreshTokenResponse {
|
||||
}
|
||||
|
||||
// --- 내 정보 (GET /v1/auth/me) -------------------------------------------
|
||||
export interface Branding {
|
||||
service_name?: string
|
||||
logo_url?: string
|
||||
helpdesk?: string[] // 헬프데스크 연락처 — 한 줄 = 담당자 한 명. 비면 연락처 영역을 렌더하지 않는다
|
||||
}
|
||||
|
||||
// 로그인 전(초청 링크 진입) 브랜딩 조회 — GET /v1/auth/session-branding/{session_id}, 인증 불필요
|
||||
export interface SessionBrandingResponse {
|
||||
result: ApiResult
|
||||
service_name: string
|
||||
logo_url: string
|
||||
helpdesk?: string[]
|
||||
}
|
||||
|
||||
// 협상완료 부가정보 필드 정의(companies.settings.session_fields)
|
||||
export interface SessionField {
|
||||
key: string
|
||||
label: string
|
||||
type: 'text' | 'number' | 'boolean' | 'select'
|
||||
options?: string[] // type='select' 일 때 고를 보기 목록
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
result: ApiResult
|
||||
su_id: string
|
||||
@ -84,9 +62,6 @@ export interface MeResponse {
|
||||
supplier_id: string
|
||||
supplier_name: string
|
||||
role: number
|
||||
branding?: Branding
|
||||
session_fields?: SessionField[]
|
||||
guide_notices?: string[]
|
||||
}
|
||||
|
||||
// --- 로그아웃 -------------------------------------------------------------
|
||||
@ -119,10 +94,6 @@ export interface AuthUser {
|
||||
supplierId: string
|
||||
supplierName: string
|
||||
role: number
|
||||
branding: Branding
|
||||
sessionFields: SessionField[]
|
||||
/** 협상 유의사항 항목(회사 설정). 비면 포털 기본 문구를 쓴다 */
|
||||
guideNotices: string[]
|
||||
}
|
||||
|
||||
export function toAuthUser(res: MeResponse): AuthUser {
|
||||
@ -133,8 +104,5 @@ export function toAuthUser(res: MeResponse): AuthUser {
|
||||
supplierId: res.supplier_id,
|
||||
supplierName: res.supplier_name,
|
||||
role: res.role,
|
||||
branding: res.branding ?? {},
|
||||
sessionFields: res.session_fields ?? [],
|
||||
guideNotices: res.guide_notices ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
@ -32,7 +32,6 @@ export interface ChatInitResponse {
|
||||
session_id: string
|
||||
session_status: number
|
||||
quotation_id: string
|
||||
qt_number?: string
|
||||
quotation_end_time: string
|
||||
quotation_memo?: string
|
||||
item_id: string
|
||||
@ -47,10 +46,6 @@ export interface ChatInitResponse {
|
||||
item_min_order_quantity?: string
|
||||
item_vat_yn?: boolean
|
||||
item_delivery_fee_yn?: boolean
|
||||
custom?: Record<string, unknown>
|
||||
labels?: Record<string, string>
|
||||
reject_reason?: string
|
||||
reject_price?: number | null
|
||||
}
|
||||
|
||||
export interface ChatMessagesResponse {
|
||||
@ -93,7 +88,6 @@ export function mapInit(r: ChatInitResponse): ChatInitData {
|
||||
session_status: r.session_status,
|
||||
item_id: r.item_id,
|
||||
quotation_id: r.quotation_id,
|
||||
qt_number: r.qt_number ?? '',
|
||||
item_name: r.item_name,
|
||||
item_code: r.item_code ?? '',
|
||||
item_image: r.item_image ?? '',
|
||||
@ -104,13 +98,9 @@ export function mapInit(r: ChatInitResponse): ChatInitData {
|
||||
item_delivery_fee_yn:
|
||||
r.item_delivery_fee_yn == null ? '' : r.item_delivery_fee_yn ? '배송비포함' : '배송비별도',
|
||||
item_min_order_quantity: r.item_min_order_quantity ?? '',
|
||||
custom: r.custom ?? {},
|
||||
item_lead_time: r.item_lead_time ?? '',
|
||||
item_spec: r.item_spec ?? '',
|
||||
quotation_memo: r.quotation_memo ?? '',
|
||||
quotation_end_time: r.quotation_end_time ?? '',
|
||||
labels: r.labels ?? {},
|
||||
reject_reason: r.reject_reason ?? '',
|
||||
reject_price: r.reject_price ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,11 +2,5 @@
|
||||
export { negotiationApi } from './negotiation.api'
|
||||
export { negotiationKeys } from './negotiation.keys'
|
||||
export { useSessionListQuery } from './negotiation.queries'
|
||||
export {
|
||||
useCancelRenegotiationMutation,
|
||||
useParticipateMutation,
|
||||
useRejectMutation,
|
||||
useRequestRenegotiationMutation,
|
||||
useSaveExtraInfoMutation,
|
||||
} from './negotiation.mutations'
|
||||
export { useParticipateMutation, useRejectMutation } from './negotiation.mutations'
|
||||
export * from './negotiation.type'
|
||||
|
||||
@ -1,13 +1,9 @@
|
||||
// 협상 엔드포인트 호출 함수 (순수 HTTP 레이어, React 의존 없음).
|
||||
import { http } from '@/apis/http'
|
||||
import type {
|
||||
ExtraInfoRequest,
|
||||
ExtraInfoResponse,
|
||||
ParticipateResponse,
|
||||
RejectRequest,
|
||||
RejectResponse,
|
||||
RenegotiationRequest,
|
||||
RenegotiationResponse,
|
||||
SessionListParams,
|
||||
SessionListResponse,
|
||||
} from './negotiation.type'
|
||||
@ -35,30 +31,4 @@ export const negotiationApi = {
|
||||
)
|
||||
return res.data
|
||||
},
|
||||
|
||||
/** POST /v1/negotiation/session/{id}/renegotiation — 결렬 건 재협상 요청 */
|
||||
requestRenegotiation: async (sessionId: string, body: RenegotiationRequest): Promise<RenegotiationResponse> => {
|
||||
const res = await http.post<RenegotiationResponse>(
|
||||
`/v1/negotiation/session/${sessionId}/renegotiation`,
|
||||
body,
|
||||
)
|
||||
return res.data
|
||||
},
|
||||
|
||||
/** DELETE /v1/negotiation/session/{id}/renegotiation — 심사 대기 중인 요청 철회 */
|
||||
cancelRenegotiation: async (sessionId: string): Promise<RenegotiationResponse> => {
|
||||
const res = await http.delete<RenegotiationResponse>(
|
||||
`/v1/negotiation/session/${sessionId}/renegotiation`,
|
||||
)
|
||||
return res.data
|
||||
},
|
||||
|
||||
/** POST /v1/negotiation/sessions/{id}/extra-info — 협상완료 부가정보 저장 */
|
||||
saveExtraInfo: async (sessionId: string, body: ExtraInfoRequest): Promise<ExtraInfoResponse> => {
|
||||
const res = await http.post<ExtraInfoResponse>(
|
||||
`/v1/negotiation/sessions/${sessionId}/extra-info`,
|
||||
body,
|
||||
)
|
||||
return res.data
|
||||
},
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user