Compare commits
126
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84090433ab | ||
|
|
77d96cd4a4 | ||
|
|
d3e33b10f4 | ||
|
|
3214e4f782 | ||
|
|
e809129ae9 | ||
|
|
631a501c5c | ||
|
|
ab77900dac | ||
|
|
09d24f5022 | ||
|
|
4536a48e40 | ||
|
|
ea1249429a | ||
|
|
d2f1a8f6f4 | ||
|
|
be039dd92b | ||
|
|
2888ff2c28 | ||
|
|
c53eeefcf6 | ||
|
|
f214fccc49 | ||
|
|
63717f5eb9 | ||
|
|
7f15bc10d1 | ||
|
|
d3bcc61609 | ||
|
|
55e3ab02aa | ||
|
|
bae0da42d2 | ||
|
|
15369a016d | ||
|
|
5917942fe3 | ||
|
|
87b896fc2f | ||
|
|
6785c8a6f4 | ||
|
|
3c3f60c7d4 | ||
|
|
bd0f39f131 | ||
|
|
775984fe48 | ||
|
|
5520e3c2b6 | ||
|
|
2a004734d8 | ||
|
|
35d38e0818 | ||
|
|
82cca894fc | ||
|
|
9716528ce7 | ||
|
|
9dca78dc72 | ||
|
|
671904c762 | ||
|
|
6f32b466b9 | ||
|
|
fe9adcaa26 | ||
|
|
f554202c58 | ||
|
|
a56589c6d9 | ||
|
|
b33ae05cd6 | ||
|
|
30f134836b | ||
|
|
8fa77af866 | ||
|
|
89652fac1f | ||
|
|
5e24741395 | ||
|
|
0cefe315c4 | ||
|
|
ba9d34fd31 | ||
|
|
6534d53696 | ||
|
|
ca1291708f | ||
|
|
a5fa44ee25 | ||
|
|
7b612824be | ||
|
|
bacf6271df | ||
|
|
9fb4a52c56 | ||
|
|
f9d37e08f4 | ||
|
|
b539e073cb | ||
|
|
36afcd68a6 | ||
|
|
a55975e62a | ||
|
|
e9be649e1f | ||
|
|
624a8846b0 | ||
|
|
d580e4d5ea | ||
|
|
5318ff3263 | ||
|
|
51d07bb779 | ||
|
|
d7c4e86f30 | ||
|
|
562dafa5ca | ||
|
|
3eec80d989 | ||
|
|
2541a391b7 | ||
|
|
ce551090b3 | ||
|
|
4f9789c08a | ||
|
|
cfee6e89d0 | ||
|
|
db07a60cfa | ||
|
|
0f10b6a70f | ||
|
|
4927c9184e | ||
|
|
03322d6ca3 | ||
|
|
fa9113da55 | ||
|
|
7c4b66aba5 | ||
|
|
f8f8f70f54 | ||
|
|
bcb87de35e | ||
|
|
0242ecff09 | ||
|
|
bb576af346 | ||
|
|
e67e713270 | ||
|
|
08c1e66582 | ||
|
|
5d0fbbcf6a | ||
|
|
88edcfed63 | ||
|
|
1e4726f4cc | ||
|
|
e8d2acaade | ||
|
|
a9db0f7a1b | ||
|
|
3e5f8c6cd4 | ||
|
|
e7a51b1b75 | ||
|
|
e9427543c8 | ||
|
|
6ffdb9a389 | ||
|
|
9ccf42cf6b | ||
|
|
e93820a51b | ||
|
|
dd3609173e | ||
|
|
2386cb8867 | ||
|
|
b6852ec6aa | ||
|
|
03c22f9474 | ||
|
|
25e13d7b01 | ||
|
|
dc8c288f68 | ||
|
|
d111610555 | ||
|
|
3d515055fb | ||
|
|
e6005b4f94 | ||
|
|
479cb862b1 | ||
|
|
a306ad4cf3 | ||
|
|
c126d56631 | ||
|
|
3c8d0af2e4 | ||
|
|
74fce19be9 | ||
|
|
1006ad11ea | ||
|
|
645a0362b0 | ||
|
|
29e54ad838 | ||
|
|
10ea8ddd45 | ||
|
|
433b973505 | ||
|
|
a750c1098a | ||
|
|
5e286d7949 | ||
|
|
992a3246a8 | ||
|
|
6eb71eb035 | ||
|
|
61b438d8d0 | ||
|
|
8fb54be830 | ||
|
|
c81df5bd88 | ||
|
|
993301be8b | ||
|
|
ca7f057e41 | ||
|
|
e7d2c87fbe | ||
|
|
8b9e81777c | ||
|
|
3c5286aeec | ||
|
|
f97e407f7c | ||
|
|
21f90ed84a | ||
|
|
ac487268d8 | ||
|
|
9ef9bfbca3 | ||
|
|
4a20194dc8 |
No files matched your search
@@ -1,21 +0,0 @@
|
||||
# docker compose 용 환경변수 템플릿 — 복사해서 사용: cp .env.example .env
|
||||
# 실제 값(.env)은 커밋하지 않는다(.gitignore). 이미지에는 시크릿이 없으므로(lps 는 example
|
||||
# config 로 빌드) 아래 값이 없으면 해당 기능이 꺼진 채 뜬다(주석 참고).
|
||||
|
||||
# ── LPS DB (미설정 시 postgres/postgres) ──
|
||||
LPS_DB_USER=postgres
|
||||
LPS_DB_PASSWORD=postgres
|
||||
|
||||
# ── LPS API 스케일 (미설정 시 1 / 40 — 단일 프로세스로도 ~1,100 RPS) ──
|
||||
LPS_API_PROCESS_COUNT=1 # uvicorn 프로세스 수(=사용 코어 수). 커넥션 풀은 예산에서 자동 역산
|
||||
LPS_DB_CONNECTION_BUDGET=40 # lps API 커넥션 총예산. 공유 PG=40, 전용 PG(max_conn≈100)=90
|
||||
|
||||
# ── LPS 워커 시크릿 ──
|
||||
OPENAI_API_KEY= # 비면 AI 유사도 판정 OFF
|
||||
NAVER_KEYS= # "id1:secret1,id2:secret2" — 네이버 쇼핑 오픈API 키(여러 개면 로테이션)
|
||||
DECODO_HOST= # 예: gate.decodo.com — DECODO 4종이 비면 프록시 미사용(직접 연결)
|
||||
DECODO_USERNAME=
|
||||
DECODO_PASSWORD=
|
||||
DECODO_PORT_START=0 # 예: 10001
|
||||
DECODO_PORT_END=0 # 예: 10010
|
||||
DECODO_COST_PER_GB=0 # 요금($/GB) — 검색 원가 계측용(예: 3.0)
|
||||
+2
-2
@@ -29,5 +29,5 @@ CLAUDE.md
|
||||
/Temp.md
|
||||
/new.md
|
||||
|
||||
# 서빙 번들 교체 시 자동 생성되는 직전본 백업 (export 도구가 만듦)
|
||||
agent/artifacts/*.prev
|
||||
/mobile.mov
|
||||
.gstack/
|
||||
@@ -1,63 +1,198 @@
|
||||
# O2O Negosium
|
||||
|
||||
동일 구조의 두 서비스(**negosium**, **negodata**)가 **하나의 PostgreSQL 인스턴스**를 공유한다.
|
||||
AI 협상 솔루션. 여러 백엔드·프론트·배치가 **하나의 PostgreSQL 인스턴스**를 공유하고,
|
||||
전부 `docker compose` 하나로 뜬다. (인터넷 최저가 검색 LPS 만 별도 DB `lps_db` 사용.)
|
||||
|
||||
## 서비스 소개
|
||||
|
||||
구매기업(바이어)이 협력사(공급사)와 벌이는 **가격 협상을 AI 봇이 대신 수행**하는 B2B 협상 자동화 솔루션이다.
|
||||
바이어가 상품·목표가·기간만 정해 견적을 열면, 각 협력사와의 1:1 협상은 강화학습 기반 에이전트가
|
||||
**협상 카드로 밀당**하며 진행하고, 마감 시각에 최저 투찰가를 기준으로 자동 **낙찰/개찰**을 판정한다.
|
||||
|
||||
크게 세 축 + 부속으로 나뉜다.
|
||||
|
||||
| 축 | 구성요소 | 역할 |
|
||||
|---|---|---|
|
||||
| **바이어 측** | negodata (backend + front) | 어드민. 상품·협력사 관리, 견적 생성, 마감·낙찰 관리 |
|
||||
| **공급사 측** | negosium (backend + frontend) | 협력사 포털. 초청받은 협상 챗에 참여해 가격 제시 |
|
||||
| **협상 엔진** | agent | 실제 AI 협상 봇. 앵커링가·협상 카드로 자동 협상 (강화학습) |
|
||||
| 부속 | lps · anchoring · landing | 인터넷 최저가(목표가 재료) · 앵커값 자동 조정 배치 · 솔루션 소개 랜딩 |
|
||||
|
||||
## 구성
|
||||
|
||||
```
|
||||
o2o-negosium/
|
||||
├── docker-compose.yml # 두 backend (DB 는 외부)
|
||||
├── postgres-init/ # DB·테이블 셋업 SQL (대상 DB 에 1회 적용)
|
||||
├── backend/ # negosium 백엔드 (포트 9300)
|
||||
├── negodata/backend/ # negodata 백엔드 (포트 9400)
|
||||
├── agent/ front/ # (예정)
|
||||
└── negodata/front/ # (예정)
|
||||
├── 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)
|
||||
```
|
||||
|
||||
두 백엔드는 같은 코드 골격(MVC · 람다 DB · Depends 주입 · JWT 로그인)을 쓴다.
|
||||
아키텍처/패턴 상세는 각 서버 README 참고: [backend](backend/README.md) · [negodata/backend](negodata/backend/README.md)
|
||||
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 컨테이너 자동 재시작 | — |
|
||||
|
||||
### DB 는 compose 밖 (config 로 연결)
|
||||
|
||||
DB 는 docker-compose 에서 관리하지 않는다. 각 backend 는 `config.<APP_ENV>.toml` 의 접속 정보대로
|
||||
**외부 PostgreSQL**(호스트 로컬 postgres, 또는 따로 떠 있는 docker postgres)에 연결한다.
|
||||
한 PostgreSQL 안에 서비스별 database 를 둔다.
|
||||
|
||||
한 PostgreSQL 인스턴스 안에 **단일 `negosium_db`** 를 두고 도메인별 **schema** 로 묶는다.
|
||||
LPS 만 별도 database(`lps_db`) 를 쓴다.
|
||||
|
||||
```
|
||||
PostgreSQL (외부, 5432)
|
||||
├── negosium_db ← negosium-backend
|
||||
└── negodata_db ← negodata-backend
|
||||
├── 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
|
||||
```
|
||||
- 컨테이너(docker env)에서 호스트 DB 접근: `host.docker.internal:5432` (`config.docker.toml`)
|
||||
- 컨테이너(docker env)에서 호스트 DB 접근: `host.docker.internal:5432` (compose 가 `DB_HOST` 로 override)
|
||||
- 로컬 실행/테스트(local·test env): `127.0.0.1:5432` (`config.local/test.toml`)
|
||||
- 계정/database 명은 config 에 맞춘다 (기본 `postgres` / `password`).
|
||||
|
||||
| 서비스 | 서버 | docs | database |
|
||||
|---|---|---|---|
|
||||
| negosium-backend | http://localhost:9300 | /docs | negosium_db |
|
||||
| negodata-backend | http://localhost:9400 | /docs | negodata_db |
|
||||
## 핵심 플로우
|
||||
|
||||
### 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).
|
||||
|
||||
## 빠른 시작
|
||||
|
||||
```bash
|
||||
# 1) DB 준비 (최초 1회) — 사용할 PostgreSQL 에 스키마 + 시드 적용
|
||||
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)
|
||||
# 스키마 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
|
||||
|
||||
# 2) 백엔드 기동
|
||||
docker compose up -d # 두 backend (DB 는 config 대로 외부 연결)
|
||||
docker compose logs -f
|
||||
# (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 메뉴로도 확인
|
||||
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
|
||||
cd backend # 또는 negodata/backend, agent, lps ...
|
||||
pip install pytest pytest-asyncio httpx
|
||||
python -m pytest
|
||||
```
|
||||
- httpx `ASGITransport` 로 네트워크 없이 앱을 직접 호출하는 e2e (각 5개).
|
||||
- httpx `ASGITransport` 로 네트워크 없이 앱을 직접 호출하는 e2e.
|
||||
- `DB_SESSION_MNG` 싱글톤의 커넥션 풀이 첫 이벤트 루프에 묶이므로, 모든 테스트가 단일 session 루프를 공유한다(`pytest.ini`).
|
||||
- ⚠️ 테스트는 `APP_ENV=test` 로 격리한다(테스트 DB). dev DB(`negosium_db`)에 대고 돌리면 데이터가 날아간다.
|
||||
|
||||
## 성능 / 벤치마크
|
||||
|
||||
@@ -99,4 +234,9 @@ python -m locust -f loadtest/locustfile.py --host http://localhost:9300 --headle
|
||||
```
|
||||
|
||||
## 기술 스택
|
||||
FastAPI · SQLAlchemy(async) · asyncpg · PostgreSQL 16 · python-jose(JWT) · bcrypt · uvicorn · Docker Compose
|
||||
- **백엔드**: 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
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"rows": 25,
|
||||
"episodes": 4,
|
||||
"skipped": {
|
||||
"종료행/카드턴 없음(미완결 세션)": 8
|
||||
},
|
||||
"min_episodes": 1,
|
||||
"deployed": false,
|
||||
"ope_candidate": 0.9029104414200676,
|
||||
"ope_candidate_ess": 1.0,
|
||||
"ope_current": 0.9029104414200676,
|
||||
"ope_current_ess": 1.0,
|
||||
"result": "gate_failed"
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
# 완전 자율 협상 에이전트 — 처음 대비 변경 정리
|
||||
|
||||
> 기준: 협상카드 + 룰 엔진 시절(처음) → 완전 자율 에이전트 v3.2 + LLM 멘트 (2026-07-10 현재)
|
||||
> 롤백: `docker-compose.yml` 의 `AUTONOMY_MODE=0` 하나로 룰 엔진 즉시 복귀 (재빌드 불필요)
|
||||
|
||||
---
|
||||
|
||||
## 1. 한눈에 보기 — 무엇이 바뀌었나
|
||||
|
||||
| 영역 | 처음 (룰 + 카드) | 지금 (자율 에이전트) |
|
||||
|---|---|---|
|
||||
| **협상 판정** | 하드코딩 룰 (앵커 이하 타결 / 와일드카드 존 / 3라운드 결렬) | RL 정책이 매 턴 행동을 직접 선택 |
|
||||
| **발화 선택** | DB 협상카드(NGC-001~011)를 UCB/Q-table 로 선택 | 카드 없음 — 행동 30개 중 신경망이 선택 |
|
||||
| **역제안 금액** | 카드에 박힌 고정값 | 앵커~목표가 6단 사다리에서 정책이 선택 |
|
||||
| **와일드카드** | 사람이 등록한 카드(WC-01~05) 발동 | 최종제안·역제시 타이밍을 정책+봉투가 자율 수행 |
|
||||
| **멘트** | 고정 템플릿 | Gemini LLM 생성 + 할루시네이션 가드 (실패 시 템플릿 폴백) |
|
||||
| **입력 상태** | 가격 스냅샷 9차원 | 21차원 (마감·협력사 이력·인터넷최저가·에피소드 기억 추가) |
|
||||
| **학습** | Q-table 온라인 갱신 | 시뮬레이터 DQN 학습 → 프로브 게이트 → npz 번들 배포 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 의사결정 — 행동 공간 30개
|
||||
|
||||
```
|
||||
ACCEPT 수락 (협상완료, 제시가 타결)
|
||||
WALK 결렬 의사 → 최종제안 1회 보장 후 종료
|
||||
COUNTER 역제안: 금액 위치 6단 {-5%, 0, 25, 50, 75, 100% of (목표가-앵커가)} × 화법 4종
|
||||
PRESS 압박(설득): 화법 4종
|
||||
```
|
||||
|
||||
행동의 실체는 `Action(kind, counter_q, strategy)` — **(무엇을, 얼마에, 어떤 말투로)** 좌표 3개짜리 데이터다
|
||||
(`policies/autonomy_actions.py`, DB 아님). 에이전트는 매 턴 30개 중 조합 1개를 고르고,
|
||||
원화 환산(앵커 + q×스팬)과 문장(LLM)은 선택 이후의 실행 단계.
|
||||
|
||||
역제안 사다리 6단 (실스케일 앵커 418,966/목표 423,198 기준):
|
||||
q=−0.05→418,754 / 0→418,966(앵커) / 0.25→420,024 / 0.5→421,082 / 0.75→422,140 / 1.0→423,198(목표가).
|
||||
비율(q)이라 견적 스케일과 무관하게 같은 행동 공간이 재사용된다.
|
||||
|
||||
화법 4종은 기존 카드 전략 분류를 그대로 승계: **경쟁 압박 / 수용 공감 / 기준 고수 / 협력 파트너**.
|
||||
톤 선택도 학습 결과 — 라이브에서 초반 경쟁(1)→중반 수용(2)→교착 협력(4)으로 국면별 전환 관측.
|
||||
|
||||
설계 출처: 화법 4종·금액 범위(앵커~목표가)는 제품 승계, 수락·결렬 포함은 완전 자율 정의의 필연,
|
||||
**격자 6단만 설계 재량**(`COUNTER_GRID` 수정+재학습으로 변경 가능). 알려진 한계: 부를 수 있는
|
||||
금액이 격자 6지점뿐 — 연속 금액 미세조정은 불가(필요 시 격자 확장이 현실적).
|
||||
|
||||
- 모델: action-as-feature DQN (ScoreNet MLP — 상태 21 + 행동특징 9 → 점수 1개)
|
||||
- 서빙: **numpy 전용** (`autonomy_serving.npz`) — 컨테이너에 PyTorch 불필요
|
||||
- 현재 서빙본: **v3.5** (백업 `autonomy_v35.npz` / 반려본 v3.4 / 이전 v3.2)
|
||||
|
||||
## 3. 입력 상태 — 9차원 → 21차원
|
||||
|
||||
"완전한 에이전트에는 다 들어가야 한다" 요구로 확장:
|
||||
|
||||
| 그룹 | 차원 | 내용 | 출처 |
|
||||
|---|---|---|---|
|
||||
| 기본 | 9 | 매출액·유통코드·협력사수·수락률·제시가·앵커가·목표가·라운드 등 | 기존 스냅샷 |
|
||||
| 테넌트 | 5 | 보상 설정 특징 | reward config |
|
||||
| **에피소드 기억** | 2 | 직전 역제안 유무·위치 | ctx `autonomy_last` |
|
||||
| **마감** | 1 | 마감 잔여율 | quotations start/end_time |
|
||||
| **협력사 이력** | 3 | 과거 협상 횟수·성공률·평균 타결비율 | experience_logs ⨝ sessions |
|
||||
| **시장가** | 1 | 인터넷 최저가 갭 | items.internet_lowest_price |
|
||||
|
||||
- 소스가 없으면 중립값(0.5/0) — 학습 시뮬의 '미상' 표현과 동일
|
||||
- 상대 **발화 내용 파싱은 보류** (사용자 결정 — 프론트 입력 UI 변경 필요)
|
||||
|
||||
## 4. 행동 봉투 — 실전 테스트에서 잡은 결함의 구조적 방지
|
||||
|
||||
룰과 다름: **룰은 결과를 정하고, 봉투는 행동만 금지**한다. 나머지(타이밍·속도·금액)는 전부 정책 학습.
|
||||
|
||||
| # | 봉투 | 막는 결함 (실제 발생 사례) | 성격 |
|
||||
|---|---|---|---|
|
||||
| ① | 목표가 초과 제시가는 **수락 불가** | v3.1 이 보상 구멍을 착취해 목표가+14% 매입 | 안전 (영구) |
|
||||
| ② | 직전 역제안보다 **낮은 금액 재제시 금지** (단조 양보) | 423,198 → 420,024 제안 철회 사건 | 안전 (영구) |
|
||||
| ③ | 역제시는 **설득 ≥2회 후 해금** (`AUTONOMY_MIN_PRESS`) | 첫 턴부터 역제시 — 옛 의미론(일반카드=설득, 와일드카드만 역제시) 복원 | 예절 (해제 후보) |
|
||||
| ④ | 목표가 0.5% 이내 **마무리 국면에선 압박 금지** | 802원 차이에 "재검토 부탁" 반복하던 푼돈 흥정 | 예절 (해제 후보) |
|
||||
| ⑤ | **첫 역제안은 앵커가 이하만** (q ≤ 0) | 사다리 꼭대기 근처(422,140)에서 개시해 올라갈 계단이 없던 문제 | 예절 (해제 후보) |
|
||||
| ⑥ | 같은 금액 반복·결렬 의사 → **자율_최종제안 1회 보장, 금액은 목표가** | 확인 없이 결렬 / 직전 금액을 "최종"으로 반복해 승인 여지를 남긴 채 종료하던 문제 | 안전 (영구) |
|
||||
| ⑦ | **결렬(walk)도 해금 전 금지** — 설득 ≥2회 전에는 설득만 가능 | 설득 0회에 walk 선택 시 최종제안 보장(⑥)과 결합해 "첫 턴 목표가 통보"가 됨 (v3.4 라이브 결함) | 예절 (해제 후보) |
|
||||
|
||||
- 구현: 서빙 `policy/autonomy_store.py` 후보 마스크 + 학습 `tools/train_full_autonomy.py` `available_actions` **양쪽 동일**
|
||||
- 예절 봉투(③④⑤)는 실로그가 쌓이면 `AUTONOMY_MIN_PRESS=0` 등으로 해제 실험 가능
|
||||
|
||||
## 5. 멘트 — 템플릿 → LLM + 가드레일
|
||||
|
||||
**역할 분리(안전 설계):** 무엇을 말할지(금액/전략/수락/결렬)는 RL 이 결정, LLM 은 **표현만** 담당.
|
||||
|
||||
```
|
||||
설정: agent/config/config.local.toml [OpenAIConfig]
|
||||
모델: gemini-2.5-flash-lite (OpenAI 호환 base_url)
|
||||
· 2.5-flash → thinking 지연으로 백엔드 10초 한도 초과 ("협상 응답 지연" 토스트 원인)
|
||||
· 2.0-flash → 은퇴(404)
|
||||
시간: LLM_TIMEOUT_S=6 초과 시 템플릿 폴백 (검증 최대 응답 2.9초)
|
||||
끄기: AUTONOMY_LLM=0
|
||||
```
|
||||
|
||||
**할루시네이션 가드 (하나라도 걸리면 템플릿 폴백, 협상은 계속):**
|
||||
|
||||
| 가드 | 내용 |
|
||||
|---|---|
|
||||
| 숫자 화이트리스트 | 프롬프트로 준 금액(제시가·제안가·직전제안가·양보폭) 외 숫자 = 즉시 폐기 |
|
||||
| **목표가 비공개** | 압박 프롬프트에 목표가 미포함 + 화이트리스트에서도 제외 — 노출 사고 재발 방지 |
|
||||
| 금지어 | 보장/물량/독점/최저가/시장가/%/계약기간/법적 등 승인 안 된 전술·커밋 |
|
||||
| 문장 완결 | thinking 토큰 소진으로 잘린 문장 폐기 (max_tokens 2048) |
|
||||
| 제안가 포함 | 역제안·최종제안 멘트에 제안 금액 필수 |
|
||||
|
||||
**추가 기능:**
|
||||
- **인터넷 최저가 인용** (구 NGC-008 자율판): 수집돼 있고 제시가 > 최저가일 때만 근거 인용 허용 — 그 턴에만 '최저가' 금지어 해제, 수치는 화이트리스트 검증
|
||||
- **대화 기억**: 직전 제안 거절 사실·양보폭을 멘트에 반영("직전 제안에서 5원 상향한…") + 직전 멘트와 같은 문장구조 반복 금지 — "멘트가 다 똑같다" 해결. temperature 0.9
|
||||
|
||||
## 6. 학습 시뮬레이터 버전 이력 — 실패 2건 포함
|
||||
|
||||
| 버전 | 변경 | 결과 |
|
||||
|---|---|---|
|
||||
| v1 | 최초 학습 | 한 방 큰 컷 + 같은 숫자 반복 → "이게 협상이야??" |
|
||||
| v2 | 에피소드 기억·컷 특징·협력사 반복 짜증/이탈 | 개선되나 지형 불일치 잔존 |
|
||||
| v3 | 상태 21차원 확장 | — |
|
||||
| v3.1 | **지형 정합**: 앵커율 0.8~6% 샘플링 (실제 ~1% vs 시뮬 20%) | ⚠️ 보상 구멍 착취 — 목표가+14% 매입 학습 → 봉투 ① 신설 |
|
||||
| **v3.2** | 컷 반발·반복 짜증·**양보 상호성**(우리가 올리면 상대도 내림)·floor ≤ 첫제시가×0.98 | ✅ **현재 서빙본** (목표가 초과 타결 0/30) |
|
||||
| v3.3 | 단조·상호성 반영 재학습 | ❌ "무조건 목표가 즉시 지르기"로 퇴화 → **프로브 게이트 반려** (`full_autonomy.pt` 만 보관, 미서빙) |
|
||||
| v3.4 | 봉투 ①~⑤ 정합 + **보상 수정**(목표가 초과 타결 = 결렬 취급) 재학습 | ❌ **반려** — 초기 게이트(실스케일 단일 지형) 통과 후 라이브에서 퇴화 발견: 소액 지형에서 첫 턴 walk→목표가 통보 / walk 잠금 후엔 압박 12연발·최종제안 생략·화법 단조(전부 전략3). 게이트를 2개 지형으로 확장해 재판정 → v3.2 우위 확인, v3.2 복원 (`autonomy_v34_rejected.npz` 보관) |
|
||||
| **v3.5** | v3.4 + **관측성 마스크**: 마감 40% 미관측(0.5 고정)·15% 완전 미상 에피소드 — 서빙 중립값 상태를 시뮬 분포에 혼입 (v3.4 퇴화 원인 해소) | ✅ **현재 서빙본** — 게이트 78/78, 사다리 3단 사용, 협조 케이스 목표가 대비 -2,116원 타결. 게이트가 이 과정에서 **철회 실버그** 발견(아래) |
|
||||
|
||||
> **교훈 1 — 보상 = 유일한 스펙**: 룰을 제거하면 보상 함수의 구멍이 곧 행동이 된다 (v3.1).
|
||||
> **교훈 2 — 프로브 게이트**: 재학습은 퇴화할 수 있다. 배포 전 반드시 실스케일 제시가별 행동표(`tools/probe_serving_dqn.py`)로 비교 검증 (v3.3).
|
||||
> **교훈 3 — 지형 일반화**: 한 지형의 게이트 통과가 다른 지형을 보증하지 않는다 (v3.4 — 실스케일 통과, 소액 퇴화).
|
||||
> **교훈 4 — 시뮬은 관측까지 닮아야 한다**: 세계뿐 아니라 '무엇을 모르는지'도 서빙과 같아야 한다. 마감·이력 미상(중립값) 상태가 시뮬에 없으면 그 상태가 분포 밖이 된다 (v3.4 원인 → v3.5 해소).
|
||||
|
||||
**철회 실버그 (게이트가 발견, 2026-07-10 수정):** 단조 봉투의 기준 `autonomy_last`가 '마지막 행동'이라 counter→**press**→counter 순서에서 설득이 역제안 기억을 덮어써 봉투가 뚫렸다(9,975 제안 후 9,900 재제안). 역제안 기억을 `autonomy_last_counter`로 별도 보존하도록 수정 — 시뮬(역제안만 추적)과도 일치. v3.2는 이 패턴을 쓰지 않아 드러나지 않았을 뿐 프로덕션에 실존하던 구멍.
|
||||
|
||||
## 7. 현재 협상 흐름 (검증 완료)
|
||||
|
||||
```
|
||||
협력사 제시
|
||||
│
|
||||
▼
|
||||
설득(압박) ≥2회 ── 인터넷최저가 근거 인용 가능, 목표가 절대 비공개
|
||||
│
|
||||
▼
|
||||
역제안 해금 ── 첫 제안은 앵커가 이하로 개시 (봉투⑤)
|
||||
│
|
||||
▼
|
||||
단조 상향 사다리 ── 후퇴 금지(봉투②), 양보폭·속도는 정책이 결정
|
||||
│
|
||||
▼
|
||||
목표가 0.5% 이내 ── 압박 중단, 클로징만 (봉투④)
|
||||
│
|
||||
├─ 제시가 ≤ 목표가 → 수락 → 협상완료
|
||||
├─ 같은 금액 반복 / 결렬 의사 → 자율_최종제안 1회, 금액=목표가 (봉투⑥)
|
||||
│ ├─ 예 → 협상완료 └─ 아니오 → 협상실패
|
||||
└─ 12턴 초과(엔지니어링 캡) → 최종제안(목표가) 1회 거쳐 종료 — 캡도 봉투⑥을 우회하지 않음
|
||||
```
|
||||
|
||||
## 8. 운영 스위치 & 파이프라인
|
||||
|
||||
| 스위치 (docker-compose agent env) | 값 | 의미 |
|
||||
|---|---|---|
|
||||
| `AUTONOMY_MODE` | 1 | 자율 모드 (0 = 룰 엔진 복귀) |
|
||||
| `DQN_SERVING` | 1 | 카드 선택 DQN (0 = UCB Q-table) |
|
||||
| `AUTONOMY_LLM` | 1(기본) | LLM 멘트 (0 = 템플릿만) |
|
||||
| `AUTONOMY_MIN_PRESS` | 2(기본) | 역제시 해금에 필요한 설득 횟수 |
|
||||
| `LLM_TIMEOUT_S` | 6(기본) | LLM 시간 상한, 초과 시 템플릿 폴백 |
|
||||
|
||||
**학습→배포 파이프라인:**
|
||||
```
|
||||
tools/train_full_autonomy (시뮬 15k ep, 룰 베이스라인 비교)
|
||||
→ tools/export_autonomy_serving (artifacts/autonomy_serving.npz, .prev 자동 백업)
|
||||
→ tools/probe_serving_dqn (실스케일 행동표 — 눈으로 보는 진단)
|
||||
→ tools/test_autonomy_defects (결함 회귀 게이트 — 지형 2종×시나리오 3종 + 단위·멘트가드 검사,
|
||||
자동 합격/불합격. 단, v3.4 사례처럼 게이트 통과 ≠ 품질 보증:
|
||||
궤적 자체도 눈으로 비교할 것)
|
||||
→ docker compose build agent (npz 는 이미지에 베이크)
|
||||
```
|
||||
|
||||
**로깅:** 자율 행동도 experience_logs 에 기록 (card_id = `AUT|종류|위치|전략`, 진행 row + 종결 row). 카드 재학습(`retrain_from_logs`)은 AUT 세션 자동 제외.
|
||||
|
||||
## 9. 변경 파일 지도
|
||||
|
||||
| 파일 | 역할 |
|
||||
|---|---|
|
||||
| `negotiation/policy/autonomy_store.py` | **신규** — 자율 정책 numpy 서빙 + 봉투 ①~⑤ 마스크 |
|
||||
| `negotiation/policies/autonomy_actions.py` | **신규** — 행동 30개·특징 인코딩 (학습/서빙 공유) |
|
||||
| `negotiation/chat/service/ment_generator.py` | **신규** — LLM 멘트 생성 + 가드레일 |
|
||||
| `negotiation/chat/service/chat_engine.py` | 자율 스텝(자율_역제안/최종제안/압박_1~4) + `_autonomy_next` 봉투⑥ |
|
||||
| `services/chat_service.py` | decider 주입·행동 로깅·대화기억 ctx 관리 |
|
||||
| `negotiation/chat/infra/repository/nego_context_crud.py` | 인터넷최저가·견적기간·협력사이력 조회 |
|
||||
| `negotiation/chat/service/negotiation_context_loader.py` | 확장 컨텍스트 로드 (company_id) |
|
||||
| `tools/train_full_autonomy.py` | **신규** — 시뮬레이터(현실화 협력사 모델) + DQN 학습 |
|
||||
| `tools/export_autonomy_serving.py` / `probe_serving_dqn.py` | **신규** — 번들 내보내기 / 프로브 게이트 |
|
||||
| `tools/test_autonomy_defects.py` | **신규** — 결함 회귀 게이트: 실전에서 발견된 결함 41항목을 시나리오·단위·멘트가드 검사로 자동 재생 (서빙 실물 코드 구동, DB/LLM 불필요) |
|
||||
| `config/config.local.toml` | Gemini 접속 정보 (gitignore, 이미지에 베이크) |
|
||||
| `docker-compose.yml` | `AUTONOMY_MODE` / `DQN_SERVING` 플래그 |
|
||||
|
||||
## 10. 남은 일
|
||||
|
||||
- [x] 결함 회귀 게이트 구축 — `test_autonomy_defects.py` 41항목, v3.2 전항목 통과 확인 (2026-07-10)
|
||||
- [x] 보상 수정 — 목표가 초과 타결은 학습 보상에서 결렬 취급 (v3.1 구멍을 유인 수준에서 차단, 봉투 ①과 이중 방어)
|
||||
- [ ] ⚠️ **Gemini API 키 재발급** — 채팅에 노출된 키, 테스트 종료 후 반드시 교체 (config.local.toml + 이미지 리빌드)
|
||||
- [x] 봉투 정합 재학습 — v3.4 반려(소액 지형 퇴화) → 원인 규명(관측성 불일치) → **v3.5 관측성 마스크로 해소, 배포 완료** (2026-07-10)
|
||||
- [x] 철회 실버그 수정 — counter→press→counter 에서 단조 봉투 뚫림 → `autonomy_last_counter` 별도 보존
|
||||
- [x] 턴캡 최종제안 보장 — 캡 종료도 "끝내기 전 한 번 더"를 거침
|
||||
- [ ] 상대 발화 LLM 파싱 (보류 중 — 프론트 입력 UI 변경 필요)
|
||||
- [ ] 실로그 축적 후: 예절 봉투(③④⑤) 해제 실험 → LLM 협력사 셀프플레이 (집컴 GPU 단계)
|
||||
- [ ] (소소) negodata 프론트 "목표 마진율 1000%" 표시 버그 후보
|
||||
@@ -1,104 +0,0 @@
|
||||
"""FeatureBuyer — 카드 '내용(전략)'과 협력사 '프로필'에 반응하는 시뮬 협력사 (Phase 2·3).
|
||||
|
||||
효과를 2축으로 분리한다(성향 조건화가 의미를 가지려면 트레이드오프가 필요):
|
||||
- 양보력(concession power): 이 카드가 가격을 얼마나 끌어내리는가
|
||||
- 수락력(accept power) : 이 카드가 합의(수락) 확률을 얼마나 높이는가
|
||||
|
||||
전략별 기본 프로필(트레이드오프):
|
||||
경쟁(1): 양보력↑↑ 수락력↓ — 세게 깎지만 결렬 위험
|
||||
수용(2): 양보력↓ 수락력↑
|
||||
고수(3): 양보력·수락력 중간
|
||||
협력(4): 양보력↓ 수락력↑↑ — 잘 성사되지만 덜 깎임
|
||||
|
||||
여기에 협력사 세그먼트 적합도(AFFINITY)가 곱해진다: 전략이 그 협력사에 안 맞으면 둘 다 죽는다.
|
||||
소형·경쟁多 → 경쟁압박이 잘 먹힘 / 대형·단독 → 협력이 잘 먹힘(압박 역효과)
|
||||
|
||||
→ '가격 중시' 고객사는 경쟁 카드(많이 깎음, 결렬 감수), '성사 중시' 고객사는 협력 카드가 정답이
|
||||
되는 구조. 에이전트는 카드 특징 + 협력사 특징 + 고객사 성향으로 이를 학습해야 한다.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, Tuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
from eval_harness.buyer import BuyerResponse, Scenario
|
||||
|
||||
# strategy_type: 1=경쟁, 2=수용, 3=고수, 4=협력 (card.nego_cards)
|
||||
# 전략별 (양보력, 수락력) 기본 프로필 — 트레이드오프의 원천
|
||||
STRATEGY_PROFILE: Dict[int, Tuple[float, float]] = {
|
||||
1: (0.90, 0.25), # 경쟁: 세게 깎지만 성사 어려움
|
||||
2: (0.35, 0.70), # 수용
|
||||
3: (0.55, 0.50), # 고수: 중간
|
||||
4: (0.30, 0.90), # 협력: 잘 성사되지만 덜 깎임
|
||||
}
|
||||
|
||||
# 세그먼트별 전략 적합도 m ∈ [0,1] — 전략이 그 협력사에 얼마나 '먹히는가'
|
||||
AFFINITY: Dict[Tuple[str, str], Dict[int, float]] = {
|
||||
("small", "multi"): {1: 0.90, 2: 0.45, 3: 0.60, 4: 0.40}, # 소형·경쟁多 → 경쟁압박
|
||||
("small", "single"): {1: 0.35, 2: 0.60, 3: 0.80, 4: 0.55}, # 소형·단독 → 고수/논리
|
||||
("big", "multi"): {1: 0.65, 2: 0.50, 3: 0.70, 4: 0.60},
|
||||
("big", "single"): {1: 0.20, 2: 0.70, 3: 0.50, 4: 0.90}, # 대형·단독 → 협력 (압박 역효과)
|
||||
}
|
||||
REVENUE_BIG = 50_000_000 # state config 'high' 경계와 정합
|
||||
|
||||
|
||||
@dataclass
|
||||
class SupplierProfile:
|
||||
"""협력사 프로필 — 에피소드마다 달라지는 협상 상대. snapshot 필드와 정합."""
|
||||
|
||||
revenue_amount: float
|
||||
partner_count: int # 이 품목의 대안 협력사 수 (BATNA. 1:1 채팅이어도 다양)
|
||||
distribution_code: str
|
||||
|
||||
@property
|
||||
def segment(self) -> Tuple[str, str]:
|
||||
size = "big" if self.revenue_amount > REVENUE_BIG else "small"
|
||||
comp = "multi" if self.partner_count >= 2 else "single"
|
||||
return (size, comp)
|
||||
|
||||
|
||||
def sample_supplier(rng: np.random.Generator) -> SupplierProfile:
|
||||
"""무작위 협력사 생성 (학습 데이터 다양성)."""
|
||||
return SupplierProfile(
|
||||
revenue_amount=float(rng.choice([5_000_000, 20_000_000, 80_000_000, 200_000_000])),
|
||||
partner_count=int(rng.choice([1, 1, 2, 3])), # 단독 비중 높게
|
||||
distribution_code=str(rng.choice(["A", "B", "C"])),
|
||||
)
|
||||
|
||||
|
||||
class FeatureBuyer:
|
||||
"""전략 프로필 x 세그먼트 적합도 기반 협력사 모델. (양보력, 수락력) 2축."""
|
||||
|
||||
def __init__(self, supplier: SupplierProfile, card_strategy: Dict[str, int], seed: int = 0,
|
||||
accept_base: float = 0.08, max_turns: int = 5, jitter: float = 0.05):
|
||||
self.supplier = supplier
|
||||
self.card_strategy = card_strategy # {card_number: strategy_type}
|
||||
self.rng = np.random.default_rng(seed)
|
||||
self.accept_base = accept_base
|
||||
self.max_turns = max_turns
|
||||
self.jitter = jitter
|
||||
# 숨은 하한가(reservation): 앵커의 94~110%. 앵커보다 높으면(약 60%) 가격만으로는
|
||||
# 타결 불가 → 수락을 받아내야 함 → 수락력 낮은(경쟁) 카드에 진짜 결렬 위험이 생긴다.
|
||||
self.floor_ratio = float(self.rng.uniform(0.94, 1.10))
|
||||
|
||||
def powers(self, card_number: str) -> Tuple[float, float]:
|
||||
"""숨은 (양보력, 수락력). 전략 프로필 × 세그먼트 적합도 + 카드별 결정론적 지터."""
|
||||
strat = self.card_strategy.get(card_number, 3)
|
||||
conc_base, acc_base = STRATEGY_PROFILE.get(strat, (0.5, 0.5))
|
||||
m = AFFINITY[self.supplier.segment].get(strat, 0.5)
|
||||
scale = 0.35 + 0.85 * m # 적합도: 안 맞으면 둘 다 죽음 (0.35~1.2)
|
||||
j = (hash(card_number) % 1000 / 1000.0 - 0.5) * 2 * self.jitter
|
||||
c_pow = float(np.clip(conc_base * scale + j, 0.02, 0.98))
|
||||
a_pow = float(np.clip(acc_base * scale + j, 0.02, 0.98))
|
||||
return c_pow, a_pow
|
||||
|
||||
def respond(self, card_number: str, scenario: Scenario, turn: int, current_price: float) -> BuyerResponse:
|
||||
c_pow, a_pow = self.powers(card_number)
|
||||
floor = scenario.anchor_price * self.floor_ratio # 숨은 하한가 (앵커 이하 보장 없음)
|
||||
concession = (current_price - floor) * (0.10 + 0.55 * c_pow)
|
||||
new_price = max(floor, current_price - concession)
|
||||
p_accept = min(0.97, self.accept_base + 0.80 * a_pow + 0.05 * (turn - 1))
|
||||
accept = bool(self.rng.random() < p_accept)
|
||||
walked = (not accept) and (turn >= self.max_turns)
|
||||
return BuyerResponse(accept=accept, new_price=new_price, walked=walked)
|
||||
@@ -114,7 +114,7 @@ def compute_counter(spec: TacticSpec, context: Dict[str, Any]) -> Optional[int]:
|
||||
if counter <= 0:
|
||||
return None
|
||||
counter = min(counter, target) # 목표가 초과 제시 금지 (가드레일)
|
||||
counter_i = int(round(counter))
|
||||
counter_i = int(counter / 10 + 0.5) * 10 # 10원 단위 반올림 — 앵커가·목표가 산정과 표기 통일(IMK 요청)
|
||||
if counter_i >= price:
|
||||
return None # 제시가가 이미 카운터 이하 → 카운터 무의미
|
||||
return counter_i
|
||||
@@ -23,24 +23,24 @@ _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("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("internet_lowest_price"), column("deleted"), schema="partner")
|
||||
_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("start_time"), column("end_time"), column("deleted"),
|
||||
column("qt_id"), column("version_id"), column("supplier_type"), column("deleted"),
|
||||
schema="quotation",
|
||||
)
|
||||
# 자율 에이전트 이력 특징용 — agent 소유 learning 스키마 (done 행 = 협상 1건의 최종 결과).
|
||||
_EXP_LOGS = table(
|
||||
"experience_logs",
|
||||
column("session_id"), column("company_id"), column("done"), column("settled_price"),
|
||||
schema="learning",
|
||||
)
|
||||
_VERSION_NEGO_CARDS = table(
|
||||
"version_nego_cards",
|
||||
column("version_id"), column("nego_card_id"), column("created_at"), column("deleted"),
|
||||
@@ -80,6 +80,18 @@ class INegoContextCRUD(ABC):
|
||||
"""품목 기준가(items.price). 없으면 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 등 시장가 인용 카드)."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
|
||||
"""협력사 총매출액(suppliers.total_revenue — KTC 미러). 없으면 0.0."""
|
||||
@@ -116,22 +128,6 @@ class INegoContextCRUD(ABC):
|
||||
"""견적 version_id 에 연결된 (일반카드 번호 목록, 와일드카드 번호 목록). 없으면 빈 목록."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_item_internet_lowest(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
"""상품 인터넷최저가(items.internet_lowest_price). 미수집이면 0."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_quotation_period(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
"""견적 협상 기간 (start_time, end_time). 없으면 None."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_supplier_history(self, cdb: AsyncSession, company_id: str, supplier_id,
|
||||
exclude_session_id) -> Tuple[ErrorType, tuple]:
|
||||
"""이 협력사와의 과거 협상 이력 (횟수, 성사율, 평균 타결가/목표가). 없으면 (0, None, None)."""
|
||||
pass
|
||||
|
||||
|
||||
class NegoContextCRUD(INegoContextCRUD):
|
||||
async def get_session_row(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
@@ -165,15 +161,37 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def get_item_internet_lowest(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
"""상품의 인터넷최저가(partner.items.internet_lowest_price). 미수집이면 0."""
|
||||
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_internet_lowest failed.", raise_error=False)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_item_lowest_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])
|
||||
@@ -181,51 +199,6 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def get_quotation_period(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
"""견적 협상 기간 (start_time, end_time). 자율 에이전트의 마감 잔여율 특징용."""
|
||||
try:
|
||||
query = (
|
||||
select(_QUOTATIONS.c.start_time, _QUOTATIONS.c.end_time)
|
||||
.where(_QUOTATIONS.c.qt_id == quotation_id, _QUOTATIONS.c.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_quotation_period failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS or not rows:
|
||||
return err_type, None
|
||||
return ErrorType.SUCCESS, (rows[0][0], rows[0][1])
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def get_supplier_history(self, cdb: AsyncSession, company_id: str, supplier_id,
|
||||
exclude_session_id) -> Tuple[ErrorType, tuple]:
|
||||
"""이 협력사와의 과거 협상 이력 집계 → (횟수, 성사율, 평균 타결가/목표가).
|
||||
|
||||
소스 = learning.experience_logs 의 종료행(done=True) ⨝ negotiation.sessions
|
||||
(agent 가 직접 기록한 결과라 카드/자율 모드 무관하게 쌓인다). 이력 없으면 (0, None, None).
|
||||
"""
|
||||
try:
|
||||
query = (
|
||||
select(_EXP_LOGS.c.settled_price, _SESSIONS.c.target_price)
|
||||
.select_from(_EXP_LOGS.join(_SESSIONS, _SESSIONS.c.session_id == _EXP_LOGS.c.session_id))
|
||||
.where(_EXP_LOGS.c.done == True, # noqa: E712
|
||||
_EXP_LOGS.c.company_id == company_id,
|
||||
_SESSIONS.c.supplier_id == supplier_id,
|
||||
_EXP_LOGS.c.session_id != exclude_session_id,
|
||||
_SESSIONS.c.deleted == False) # noqa: E712
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_supplier_history failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS or not rows:
|
||||
return err_type, (0, None, None)
|
||||
n = len(rows)
|
||||
settled = [(int(sp), int(tp)) for sp, tp in rows if sp and tp]
|
||||
success = len([1 for sp, tp in rows if sp]) / n
|
||||
avg_ratio = (sum(sp / tp for sp, tp in settled) / len(settled)) if settled else None
|
||||
return ErrorType.SUCCESS, (n, success, avg_ratio)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, (0, None, None)
|
||||
|
||||
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
|
||||
try:
|
||||
query = (
|
||||
|
||||
@@ -17,50 +17,6 @@ MAX_ROUNDS = 3 # config 미주입 시 폴백 (규칙 정본은 tenant config n
|
||||
_PRICE_MODES = ("price",)
|
||||
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
||||
|
||||
# ---- 완전 자율 모드 (AUTONOMY_MODE, autonomy_store) --------------------------------
|
||||
# 가격협상 판정 룰(check_price_match/wildcard_entry/iteration_limit)과 카드 선택을
|
||||
# 정책 행동(수락/역제안/압박/결렬)으로 대체할 때 쓰는 스텝들. autonomy_decider 미주입이면 도달 불가.
|
||||
_AUTONOMY_TURN_CAP = 12 # 엔지니어링 타임아웃(무한 세션 방지) — 협상 룰이 아니다
|
||||
|
||||
_AUTONOMY_PRESS_SCRIPTS = {
|
||||
1: "동일 품목에 대해 복수 공급처의 견적이 함께 검토되고 있습니다. 현재 제시가로는 우선순위 확보가 어려운 상황입니다. 경쟁력 있는 가격으로 다시 제안해 주시겠어요?",
|
||||
2: "제안하신 조건의 취지는 충분히 이해했습니다. 저희도 최대한 맞춰보려 합니다. 조금만 더 조정해 주시면 내부 설득이 가능할 것 같습니다. 다시 제안해 주시겠어요?",
|
||||
3: "내부 산정 기준과 현재 제시가 사이에 아직 차이가 있습니다. 기준에 부합하는 수준으로 재검토하여 다시 제안해 주시기를 부탁드립니다.",
|
||||
4: "귀사를 장기적으로 함께할 파트너로 검토하고 있습니다. 이번 협상이 원만히 마무리되면 후속 거래 확대도 논의하고 싶습니다. 서로 만족할 수 있는 가격으로 다시 제안해 주시겠어요?",
|
||||
}
|
||||
|
||||
_AUTONOMY_STEPS = {
|
||||
"자율_역제안": {
|
||||
"script": "제안해 주신 **{input_price}원**, 내부 검토를 마쳤습니다. **{autonomy_offer}원**이라면 즉시 수락하고 우선협상 대상으로 확정하겠습니다. 수락하시겠습니까?",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": ["예", "아니오"],
|
||||
"next_step": {"예": "협상완료", "아니오": "가격협상_재입력"},
|
||||
"type": "text",
|
||||
"chat_end": False,
|
||||
},
|
||||
# 최종 통보(WC-03 의 자율 버전): 정책이 직전과 같은 금액을 다시 부르는 순간(단조 봉투상
|
||||
# 더 올릴 수 없음 = 탄약 소진) 발동. 거절하면 협상을 정리한다 — 어정쩡한 반복 대신 명확한 마무리.
|
||||
"자율_최종제안": {
|
||||
"script": "지금까지 협의에 성실히 임해 주셔서 감사합니다. **{autonomy_offer}원**은 저희가 제시할 수 있는 마지막 제안입니다. 수락해 주시면 즉시 우선협상 대상으로 확정되며, 어려우시다면 이번 협상은 여기서 마무리하겠습니다.",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": ["예", "아니오"],
|
||||
"next_step": {"예": "협상완료", "아니오": "협상실패"},
|
||||
"type": "text",
|
||||
"chat_end": False,
|
||||
},
|
||||
**{
|
||||
f"자율_압박_{s}": {
|
||||
"script": t,
|
||||
"next_input_mode": "price",
|
||||
"input_options": [],
|
||||
"next_step": {"default": "가격협상_확인"},
|
||||
"type": "text",
|
||||
"chat_end": False,
|
||||
}
|
||||
for s, t in _AUTONOMY_PRESS_SCRIPTS.items()
|
||||
},
|
||||
}
|
||||
|
||||
# 최종 타결/결렬 스텝. 재협상=협상완료(우선협상 타결), 재견적=결과제출(투찰확정). 둘 다 협상실패=결렬.
|
||||
# 이 스텝들은 chat_end=False(뒤에 협상종료가 옴)라, outcome 을 컨텍스트에 적재했다가
|
||||
# 실제 종료(chat_end=협상종료) 시점에 확정 보고한다 → backend 가 chat_end 에서 DONE/REJECTED 를 옳게 가른다.
|
||||
@@ -118,14 +74,11 @@ class ChatEngine:
|
||||
def __init__(self, scripts_repo: ScriptRepository, rq_type: str = "재협상"):
|
||||
self.repo = scripts_repo
|
||||
self.rq_type = rq_type
|
||||
# 자율 스텝은 병합만 해둔다(repo 캐시 오염 방지 위해 새 dict) — decider 미주입 시 도달 불가.
|
||||
self.scripts = {**scripts_repo.load_scripts(rq_type), **_AUTONOMY_STEPS}
|
||||
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
|
||||
# 완전 자율 모드: ChatService 가 AutonomyStore 정책을 주입하면 가격협상 판정 룰을 대체한다.
|
||||
self.autonomy_decider = None # Callable[[dict], autonomy_actions.Action]
|
||||
|
||||
# ---- public --------------------------------------------------------
|
||||
def start(self, session: ChatSession) -> StepView:
|
||||
@@ -151,12 +104,6 @@ class ChatEngine:
|
||||
session.context["round"] = session.context.get("round", 0) + 1
|
||||
nxt = self._default_next(node)
|
||||
elif mode in _CHOICE_MODES:
|
||||
# 자율 역제안/최종제안 수락("예") → 합의가는 에이전트 제안가다.
|
||||
# (카드/와일드카드 경로는 아래 pending_counter_price 일반 메커니즘이 처리하지만
|
||||
# 자율 스텝은 pending_counter 를 쓰지 않으므로 명시 분기 유지.)
|
||||
if session.step in ("자율_역제안", "자율_최종제안") and user_input == "예" \
|
||||
and session.context.get("autonomy_offer"):
|
||||
session.context["input_price"] = float(session.context["autonomy_offer"])
|
||||
nxt = self._choice_next(node, user_input, session)
|
||||
else:
|
||||
nxt = self._default_next(node)
|
||||
@@ -202,15 +149,7 @@ class ChatEngine:
|
||||
- anchor 살짝 초과(≤ anchor×wildcard_entry_ratio) + 와일드카드 미사용 → 와일드카드로 인하 압박.
|
||||
- 설정 카드(action_space) 모두 소진 → 협상실패.
|
||||
- 그 외 → 가격협상(카드 1장 플레이 후 재제안).
|
||||
|
||||
완전 자율 모드(autonomy_decider 주입)에서는 위 룰 전체를 정책 행동으로 대체한다.
|
||||
"""
|
||||
# 가격협상 판정 지점(check_price_match 포함 조건 리스트)에서만 자율 정책이 개입한다.
|
||||
if self.autonomy_decider is not None and any(
|
||||
c.get("condition") == "check_price_match" for c in conds):
|
||||
nxt = self._autonomy_next(session)
|
||||
if nxt is not None:
|
||||
return nxt # 정책 실패(예외) 시에만 아래 룰로 폴백
|
||||
ctx = session.context
|
||||
price = ctx.get("input_price", 0)
|
||||
anchor = ctx.get("anchor_price", 0)
|
||||
@@ -256,52 +195,6 @@ class ChatEngine:
|
||||
return c.get("next")
|
||||
return "가격협상"
|
||||
|
||||
def _autonomy_next(self, session: ChatSession) -> Optional[str]:
|
||||
"""완전 자율: 정책 행동 → 스텝. 수락/역제안 금액/압박 화법/결렬 타이밍 전부 정책이 결정.
|
||||
|
||||
유일한 강제 종료는 턴 상한(_AUTONOMY_TURN_CAP) — 무한 세션 방지용 엔지니어링 타임아웃.
|
||||
정책 호출이 실패하면 None 을 반환해 기존 룰 평가로 폴백한다(서비스 연속성).
|
||||
"""
|
||||
ctx = session.context
|
||||
if ctx.get("round", 0) > _AUTONOMY_TURN_CAP:
|
||||
# 턴 상한도 최종제안 보장(봉투 ⑥)을 우회하지 않는다 — 어떤 경로로 끝나든
|
||||
# "끝내기 전에 한 번 더"(제품 결정)를 거친다. 최종 거절 후에만 협상실패.
|
||||
if not ctx.get("autonomy_final_asked"):
|
||||
ctx["autonomy_final_asked"] = True
|
||||
ctx["autonomy_offer"] = int(ctx.get("target_price", 0))
|
||||
return "자율_최종제안"
|
||||
return "협상실패"
|
||||
try:
|
||||
act = self.autonomy_decider(ctx)
|
||||
except Exception: # 정책 오류 → 룰 폴백 (호출부에서 로깅)
|
||||
return None
|
||||
session.context["autonomy_action"] = f"{act.kind}:{act.strategy}:{act.counter_q}"
|
||||
span = max(ctx.get("target_price", 0) - ctx.get("anchor_price", 0), 1.0)
|
||||
# 탄약소진(같은 금액 재호출) 판정은 '마지막 역제안' 기준 — autonomy_last(마지막 행동)는
|
||||
# 사이에 낀 설득이 덮어써 판정이 리셋된다 (chat_service 가 counter 마다 별도 보존).
|
||||
last = ctx.get("autonomy_last_counter") or {}
|
||||
if act.kind == "accept":
|
||||
return "협상완료"
|
||||
if act.kind == "walk":
|
||||
# 결렬 전 마지막 제안 1회 보장 — "끝내기 전에 한 번 더 물어보고 종료" (제품 결정).
|
||||
# 최종제안을 이미 거쳤으면(autonomy_final_asked) 그대로 종료한다.
|
||||
if not ctx.get("autonomy_final_asked"):
|
||||
ctx["autonomy_final_asked"] = True
|
||||
# 최종제안 금액 = 목표가. 마지막 기회에 직전 역제안 금액을 반복하면 승인 범위의
|
||||
# 여지(목표가까지)를 남긴 채 결렬된다 — 최종에는 우리가 수락 가능한 최대치를 부른다.
|
||||
ctx["autonomy_offer"] = int(ctx.get("target_price", 0))
|
||||
return "자율_최종제안"
|
||||
return "협상실패"
|
||||
if act.kind == "counter":
|
||||
ctx["autonomy_offer"] = int(round(ctx.get("anchor_price", 0) + act.counter_q * span))
|
||||
# 직전과 같은 금액을 다시 부름 = 단조 봉투상 더 올릴 수 없음(탄약 소진) → 최종 통보로 전환.
|
||||
if last.get("kind") == "counter" and act.counter_q <= float(last.get("q", -9)) + 1e-9:
|
||||
ctx["autonomy_final_asked"] = True
|
||||
ctx["autonomy_offer"] = int(ctx.get("target_price", 0))
|
||||
return "자율_최종제안"
|
||||
return "자율_역제안"
|
||||
return f"자율_압박_{act.strategy or 3}"
|
||||
|
||||
def _pick_wildcard(self, session: ChatSession) -> str:
|
||||
"""앵커가에 아주 근접(≤ anchor×wildcard_1pct_ratio)한 구간에서만 1% 인하 요청(wild_card_1pct)으로
|
||||
앵커가 이하로 유도한다. 그 외 구간은 일반 가격협상(카드 플레이)으로 돌린다.
|
||||
@@ -318,7 +211,7 @@ class ChatEngine:
|
||||
# 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
|
||||
# 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
|
||||
ctx["wildcard_used"] = True
|
||||
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가 (멘트 변수)
|
||||
ctx["offer_1pct"] = int(price * 0.99 / 10 + 0.5) * 10 # 1% 인하가 (멘트 변수) — 10원 반올림(앵커·카운터와 통일)
|
||||
ctx["pending_counter_price"] = ctx["offer_1pct"] # 수락 시 이 가격으로 타결
|
||||
return "wild_card_1pct"
|
||||
# 1.02 초과 ~ entry(1.05) 구간: 견적에서 선택한 와일드카드의 전술로 카운터 제시.
|
||||
@@ -354,15 +247,12 @@ class ChatEngine:
|
||||
out["product_name"] = str(ctx["product_name"])
|
||||
if "offer_1pct" in ctx:
|
||||
out["offer_1pct"] = int(ctx["offer_1pct"])
|
||||
if "autonomy_offer" in ctx:
|
||||
out["autonomy_offer"] = int(ctx["autonomy_offer"])
|
||||
# 인터넷 최저가(NGC-008): 수집값이 컨텍스트에 없으면 앵커가로 폴백 — 원형 토큰 노출 방지.
|
||||
if ctx.get("internet_lowest_price"):
|
||||
out["internet_lowest_price"] = int(ctx["internet_lowest_price"])
|
||||
elif "anchor_price" in ctx:
|
||||
out["internet_lowest_price"] = int(ctx["anchor_price"])
|
||||
# 고객사 교환·요구 조건(NGC-009/010): 런타임 소스 미구현 — 중립 문구 폴백.
|
||||
out["customer_condition"] = ctx.get("customer_condition") or "상호 협의된 조건"
|
||||
# 인터넷 최저가: 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.compute_counter 산식과 동일 정의.
|
||||
anchor = ctx.get("anchor_price") or 0
|
||||
target = ctx.get("target_price") or 0
|
||||
@@ -376,7 +266,15 @@ class ChatEngine:
|
||||
if prev_customer and "input_price" in ctx:
|
||||
out["middle_price"] = int(round((prev_customer + ctx["input_price"]) / 2))
|
||||
if ctx.get("pending_counter_price"):
|
||||
out["counter_price"] = int(ctx["pending_counter_price"])
|
||||
# 카운터 제시 중: 멘트에 보이는 제시가와 수락 시 타결가(pending)를 반드시 일치시킨다.
|
||||
# 절충/중간 변수(middle_price·target_mid_price)는 vars_for 재계산 값이 compute_counter 의
|
||||
# target 클램프·prev_customer 갱신과 어긋나, 멘트엔 1,740,000 이 보이는데 실제로는
|
||||
# 1,700,000 으로 타결되던 버그(표시가≠투찰가)가 있었다. pending 은 이 시점 유일한 '제안가'이므로
|
||||
# 세 변수 모두 pending 으로 고정한다(카운터 제시 턴에만 적용 — 비-카운터 렌더는 원 계산값 유지).
|
||||
pending_i = int(ctx["pending_counter_price"])
|
||||
out["counter_price"] = pending_i
|
||||
out["middle_price"] = pending_i
|
||||
out["target_mid_price"] = pending_i
|
||||
# 인하율 = (기존 공급가(상품단가) - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
|
||||
# 제시가가 기존가보다 높으면(인상 제시) 음수가 나오는데, "-1.3% 인하된 금액" 같은
|
||||
# 모순 표현이 되므로 discount_rate 는 0 미만 금지하고, 인상/동일/인하를 구분한
|
||||
|
||||
@@ -1,188 +0,0 @@
|
||||
"""MentGenerator — 자율 협상 행동을 LLM 이 자연어 멘트로 표현 (v2: 행동은 RL, 문장은 LLM).
|
||||
|
||||
역할 분리(안전 설계):
|
||||
- 무엇을 말할지(수락/역제안 금액/압박 전략/결렬)는 RL 정책이 결정 — LLM 은 표현만 담당.
|
||||
- 가드레일: 역제안 멘트에 제안 금액이 정확히 포함되지 않으면 폐기, 예외/미설정 시 None
|
||||
→ 호출부(ChatService)가 기존 템플릿 멘트로 폴백한다. LLM 이 죽어도 협상은 계속된다.
|
||||
|
||||
설정: config.local.toml [OpenAIConfig] (Gemini 는 OpenAI 호환 base_url 로 접속).
|
||||
비활성화: AUTONOMY_LLM=0.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from common.logger import LOG
|
||||
from negotiation.profiling.config import LlmCredentials
|
||||
|
||||
_STRATEGY_TONE = {
|
||||
1: "경쟁 압박형 — 복수 공급처와 비교 검토 중임을 암시하며 긴장감을 준다",
|
||||
2: "수용 공감형 — 상대 제안의 취지에 공감하며 부드럽게 조정을 요청한다",
|
||||
3: "기준 고수형 — 내부 산정 기준과 목표가를 근거로 원칙을 지킨다",
|
||||
4: "협력 파트너형 — 장기 파트너십과 후속 거래 확대 가능성을 강조한다",
|
||||
}
|
||||
|
||||
_SYSTEM = """너는 대기업 구매팀의 가격 협상 챗봇이다. 주어진 '전달 의도'를 자연스러운 한국어 협상 멘트로 바꿔 쓴다.
|
||||
규칙 (위반 시 출력은 폐기된다):
|
||||
- 1~3문장, 정중하되 간결하게. 출력은 멘트 텍스트만 (따옴표·설명 없이).
|
||||
- 금액 숫자는 주어진 그대로 정확히 포함하고 단위는 '원'을 쓴다. 주어지지 않은 숫자·비율을 절대 만들지 않는다.
|
||||
- 지정된 '화법' 전략 안에서만 말한다. 그 외의 협상 전술(물량·기간 약속, 조건 교환, 거래 연계,
|
||||
독점 제안, 시장가·최저가 주장, 할인 약속 등)을 지어내지 않는다.
|
||||
- 회사의 정책·사실을 단정하지 않는다. 주어진 의도에 없는 정보는 말하지 않는다.
|
||||
- 상대는 협력사(판매자)이고 우리는 구매자다."""
|
||||
|
||||
# 생성문 금지어 — 승인되지 않은 커밋/주장 계열. 걸리면 템플릿 폴백(협상은 계속).
|
||||
_FORBIDDEN = ("보장", "물량", "독점", "무조건", "최저가", "시장 가격", "시장가", "계약 기간",
|
||||
"법적", "위약", "%")
|
||||
|
||||
|
||||
def _configured() -> bool:
|
||||
if os.getenv("AUTONOMY_LLM", "1").lower() in ("0", "false", "no"):
|
||||
return False
|
||||
try:
|
||||
return LlmCredentials.from_config().is_configured()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _digits(s) -> str:
|
||||
return re.sub(r"[^\d]", "", str(s))
|
||||
|
||||
|
||||
def _history_hints(ctx: dict) -> str:
|
||||
"""대화 기억 힌트 — 무기억 생성이 '매번 같은 멘트'를 만들던 문제의 해법.
|
||||
|
||||
① 직전 우리 제안이 거절된 사실과 이번 제안과의 관계(양보/입장유지)를 짚게 하고
|
||||
② 직전 봇 멘트를 보여주며 같은 문장 구조·표현의 반복을 금지한다."""
|
||||
hints = []
|
||||
prev = ctx.get("autonomy_prev")
|
||||
if prev and prev.get("kind") == "counter":
|
||||
anchor, target = float(ctx.get("anchor_price") or 0), float(ctx.get("target_price") or 0)
|
||||
prev_offer = int(round(anchor + float(prev.get("q", 0.0)) * max(target - anchor, 1.0)))
|
||||
cur_offer = int(ctx.get("autonomy_offer") or 0)
|
||||
if cur_offer > prev_offer:
|
||||
hints.append(f"참고: 직전 라운드에 우리가 {prev_offer:,}원을 제안했으나 거절당했고, "
|
||||
f"이번에는 {cur_offer - prev_offer:,}원 더 양보한 제안이다. 이 진전을 자연스럽게 짚어라.")
|
||||
elif cur_offer == prev_offer and cur_offer > 0:
|
||||
hints.append(f"참고: 직전에 제안한 {prev_offer:,}원을 거절당했지만 같은 금액을 유지한다. "
|
||||
f"입장이 확고함을 정중하게 전하라.")
|
||||
elif prev_offer > 0:
|
||||
hints.append(f"참고: 직전 제안({prev_offer:,}원)이 거절된 뒤의 재제안이다.")
|
||||
last_ment = ctx.get("autonomy_last_ment")
|
||||
if last_ment:
|
||||
hints.append(f'직전 봇 멘트: "{last_ment}" — 이와 같은 문장 구조·표현을 반복하지 말고 다르게 써라.')
|
||||
return " ".join(hints)
|
||||
|
||||
|
||||
def _prompt_for(step: str, ctx: dict) -> Optional[str]:
|
||||
price = int(ctx.get("input_price") or 0)
|
||||
rnd = ctx.get("round", 1)
|
||||
if step in ("자율_역제안", "자율_최종제안"):
|
||||
offer = int(ctx.get("autonomy_offer") or 0)
|
||||
if offer <= 0:
|
||||
return None
|
||||
strategy = int((ctx.get("autonomy_last") or {}).get("s") or 3)
|
||||
tone = _STRATEGY_TONE.get(strategy, _STRATEGY_TONE[3])
|
||||
final = ("이번이 우리가 제시할 수 있는 마지막 제안이며, 거절하시면 이번 협상은 종료됨을 "
|
||||
"분명하되 정중하게 밝혀라. " if step == "자율_최종제안" else "")
|
||||
return (f"상황: 협력사가 {price:,}원을 제시했다(협상 {rnd}라운드). "
|
||||
f"전달 의도: 우리는 **{offer:,}원**이면 즉시 수락하고 우선협상 대상으로 확정할 수 있다 — "
|
||||
f"이 핵심 의미는 유지하되 문장 표현은 자유롭게 새로 써라. {final}화법: {tone}. "
|
||||
f"{_history_hints(ctx)} 마지막에 수락 여부를 물어라.")
|
||||
if step.startswith("자율_압박_"):
|
||||
strategy = int(step.rsplit("_", 1)[1])
|
||||
tone = _STRATEGY_TONE.get(strategy, _STRATEGY_TONE[3])
|
||||
# 주의: 목표가는 프롬프트에 넣지 않는다 — 압박 중 목표가 노출은 우리 상한을 까는 것
|
||||
# (상대가 그 밑으로 내려올 이유가 사라진다). 숫자 커밋은 역제안/최종제안에서만.
|
||||
base = (f"상황: 협력사가 {price:,}원을 제시했다(협상 {rnd}라운드). "
|
||||
f"전달 의도: 어떤 금액도 언급하지 말고(내부 기준·목표가 숫자 금지), 제시가와 우리 기준의 "
|
||||
f"거리가 있다는 취지로 가격 재제안을 요청한다. 화법: {tone}. "
|
||||
f"{_history_hints(ctx)}")
|
||||
# 시장가 근거 (구 NGC-008 의 자율 버전): 수집된 인터넷최저가가 실재하고 제시가가 그보다
|
||||
# 높을 때만 사실 근거로 인용을 허용한다 — 미수집 품목에서 지어내는 주장은 가드가 차단.
|
||||
if _market_evidence(ctx):
|
||||
il = int(ctx["internet_lowest_price"])
|
||||
base += (f" 참고 사실(인용 허용되는 유일한 금액): 동일 품목의 인터넷 최저가가 {il:,}원으로 "
|
||||
f"확인된다. 현재 제시가가 이보다 높다는 점을 근거로 조정 여지를 정중히 짚어라.")
|
||||
return base
|
||||
return None
|
||||
|
||||
|
||||
def _market_evidence(ctx: dict) -> bool:
|
||||
"""시장가 근거 인용 가능 조건: 인터넷최저가 수집됨 + 제시가가 그보다 높음."""
|
||||
il = int(ctx.get("internet_lowest_price") or 0)
|
||||
return il > 0 and float(ctx.get("input_price") or 0) > il
|
||||
|
||||
|
||||
def _allowed_amounts(ctx: dict) -> set:
|
||||
"""멘트에 등장해도 되는 숫자 집합 — 우리가 프롬프트로 준 값들뿐. 이 밖의 금액 = 할루시네이션."""
|
||||
# 목표가는 화이트리스트에 없다 — 압박 멘트가 목표가를 새면(상한 노출) 즉시 폐기된다.
|
||||
# 역제안·최종제안의 제안가(autonomy_offer)가 목표가와 같은 경우만 그 값으로 허용된다.
|
||||
anchor, target = float(ctx.get("anchor_price") or 0), float(ctx.get("target_price") or 0)
|
||||
out = {int(ctx.get("input_price") or 0), int(ctx.get("autonomy_offer") or 0),
|
||||
int(ctx.get("round") or 0)}
|
||||
if _market_evidence(ctx):
|
||||
out.add(int(ctx["internet_lowest_price"])) # 시장가 근거 인용 시 그 수치만 허용
|
||||
prev = ctx.get("autonomy_prev")
|
||||
if prev and prev.get("kind") == "counter":
|
||||
prev_offer = int(round(anchor + float(prev.get("q", 0.0)) * max(target - anchor, 1.0)))
|
||||
out |= {prev_offer, abs(int(ctx.get("autonomy_offer") or 0) - prev_offer)}
|
||||
return {str(v) for v in out if v}
|
||||
|
||||
|
||||
def _guard(step: str, ctx: dict, text: str) -> bool:
|
||||
"""LLM 출력 검증(할루시네이션 차단) — 실패 시 템플릿 폴백.
|
||||
|
||||
① 길이/문장 완결 ② 금지어(승인 안 된 커밋·주장) ③ 숫자 화이트리스트: 멘트의 모든
|
||||
3자리+ 숫자는 우리가 준 값(제시가·제안가·목표가·직전제안가)이어야 한다 — 지어낸 금액 즉시 폐기.
|
||||
④ 역제안은 제안 금액 포함 필수."""
|
||||
if not text or len(text) < 10 or len(text) > 600:
|
||||
return False
|
||||
if not text.rstrip().endswith(("다.", "요.", "요?", "까?", "니까?", ".", "?")):
|
||||
return False # 문장 중간 잘림(thinking 토큰에 한도 소진 등) → 템플릿 폴백
|
||||
forbidden = _FORBIDDEN
|
||||
if _market_evidence(ctx):
|
||||
# 시장가 근거가 정당한 턴에는 '최저가/시장가' 언급을 허용 (수치는 아래 화이트리스트가 검증).
|
||||
forbidden = tuple(w for w in _FORBIDDEN if w not in ("최저가", "시장가", "시장 가격"))
|
||||
if any(w in text for w in forbidden):
|
||||
return False
|
||||
allowed = _allowed_amounts(ctx)
|
||||
for num in re.findall(r"\d{3,}", text.replace(",", "")):
|
||||
if num not in allowed:
|
||||
return False # 프롬프트에 없던 금액 생성 = 할루시네이션
|
||||
if step in ("자율_역제안", "자율_최종제안"):
|
||||
return _digits(ctx.get("autonomy_offer")) in _digits(text)
|
||||
return True
|
||||
|
||||
|
||||
async def generate(step: str, ctx: dict) -> Optional[str]:
|
||||
"""자율 스텝 멘트 생성. 미설정/실패/검증불통과 → None (호출부 템플릿 유지)."""
|
||||
if not _configured():
|
||||
return None
|
||||
prompt = _prompt_for(step, ctx)
|
||||
if prompt is None:
|
||||
return None
|
||||
try:
|
||||
from negotiation.profiling.infra.llm_adapter import chat_complete
|
||||
# openai SDK 는 동기 — 이벤트루프 블로킹 방지 위해 스레드로 넘긴다.
|
||||
# max_tokens 넉넉히 — Gemini 2.5 계열은 thinking 토큰이 한도에 포함돼 짧으면 본문이 잘린다.
|
||||
# 시간 상한: backend→agent 타임아웃(10s)보다 확실히 짧아야 한다 — 초과 시 템플릿 폴백으로
|
||||
# 협상은 즉시 계속된다("협상 응답 지연" 토스트 방지). LLM_TIMEOUT_S 로 조절.
|
||||
text = await asyncio.wait_for(
|
||||
asyncio.to_thread(
|
||||
chat_complete,
|
||||
[{"role": "system", "content": _SYSTEM}, {"role": "user", "content": prompt}],
|
||||
None, False, 0.9, 2048, # temperature 0.9 — 표현 다양성 (의미는 프롬프트 가드)
|
||||
),
|
||||
timeout=float(os.getenv("LLM_TIMEOUT_S", "6")),
|
||||
)
|
||||
text = (text or "").strip().strip('"')
|
||||
if _guard(step, ctx, text):
|
||||
return text
|
||||
LOG.w(f"[MentGenerator] 가드레일 불통과 → 템플릿 폴백 (step={step})")
|
||||
return None
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(f"[MentGenerator] LLM 실패 → 템플릿 폴백: {ex}")
|
||||
return None
|
||||
@@ -39,6 +39,7 @@ class NegotiationDbContext:
|
||||
target_price: int # 목표 매입가(원) — sessions.target_price
|
||||
anchor_price: int # 앵커링가 — sessions.anchoring_price(생성 시 박제). 없으면 target(무할인 폴백)
|
||||
item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0
|
||||
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
|
||||
partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE
|
||||
@@ -46,23 +47,15 @@ class NegotiationDbContext:
|
||||
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type. 미지정 시 None
|
||||
selected_nego_card_numbers: list[str] # 견적 생성 시 선택된 일반 협상카드 번호(card.nego_cards.number)
|
||||
selected_wild_card_numbers: list[str] # 견적 생성 시 선택된 와일드카드 번호(card.wild_cards.number)
|
||||
# ---- 자율 에이전트 v3 상태 특징 소스 (없으면 0/None — 특징은 중립 기본값으로 폴백) ----
|
||||
internet_lowest_price: int = 0 # items.internet_lowest_price (미수집 0)
|
||||
deadline_end_ts: Optional[float] = None # 견적 마감(epoch 초) — quotations.end_time
|
||||
deadline_total_s: Optional[float] = None # 협상 전체 기간(초) — end−start
|
||||
hist_n: int = 0 # 이 협력사와의 과거 협상 횟수
|
||||
hist_success: Optional[float] = None # 과거 성사율 (이력 없으면 None)
|
||||
hist_settle_ratio: Optional[float] = None # 과거 평균 타결가/목표가 (성사 이력 없으면 None)
|
||||
card_count: Optional[int] # 협상카드 사용 횟수 상한(quotation_settings.card_count). None=상한 미적용
|
||||
|
||||
|
||||
class NegotiationContextLoader:
|
||||
def __init__(self, crud: Optional[INegoContextCRUD] = None):
|
||||
self.crud: INegoContextCRUD = crud or NegoContextCRUD()
|
||||
|
||||
async def load(self, session_id: Optional[str],
|
||||
company_id: Optional[str] = None) -> Optional[NegotiationDbContext]:
|
||||
"""session_id 로 협상 컨텍스트 조회. 행이 없거나 조회 실패 시 None(호출부 기본값 폴백).
|
||||
company_id 는 협력사 이력 집계(experience_logs 테넌트 스코프)용 — 없으면 이력 특징 생략."""
|
||||
async def load(self, session_id: Optional[str]) -> Optional[NegotiationDbContext]:
|
||||
"""session_id 로 협상 컨텍스트 조회. 행이 없거나 조회 실패 시 None(호출부 기본값 폴백)."""
|
||||
if not session_id:
|
||||
return None
|
||||
try:
|
||||
@@ -95,6 +88,9 @@ class NegotiationContextLoader:
|
||||
# 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시).
|
||||
_, item_price = await self.crud.get_item_price(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)
|
||||
@@ -112,26 +108,15 @@ class NegotiationContextLoader:
|
||||
_, selected_cards = await self.crud.get_quotation_card_numbers(s, quotation_id)
|
||||
selected_nego_cards, selected_wild_cards = selected_cards
|
||||
|
||||
# ---- 자율 에이전트 v3 특징 소스 (조회 실패는 전부 중립 폴백 — 협상은 계속돼야 한다) ----
|
||||
_, internet_lowest = await self.crud.get_item_internet_lowest(s, item_id)
|
||||
_, period = await self.crud.get_quotation_period(s, quotation_id)
|
||||
deadline_end_ts = deadline_total_s = None
|
||||
if period and period[1] is not None:
|
||||
end_ts = period[1].timestamp()
|
||||
start_ts = period[0].timestamp() if period[0] is not None else None
|
||||
total = (end_ts - start_ts) if start_ts else None
|
||||
if total and total > 0:
|
||||
deadline_end_ts, deadline_total_s = end_ts, total
|
||||
hist_n, hist_success, hist_settle = 0, None, None
|
||||
if company_id:
|
||||
_, hist = await self.crud.get_supplier_history(s, company_id, supplier_id, sid)
|
||||
hist_n, hist_success, hist_settle = hist
|
||||
# 협상카드 사용 횟수 상한(견적 설정). 없으면 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,
|
||||
item_price=item_price,
|
||||
internet_lowest_price=internet_lowest_price,
|
||||
partner_name=partner_name,
|
||||
product_name=product_name,
|
||||
partner_type=PartnerType.from_count(supplier_count),
|
||||
@@ -139,12 +124,7 @@ class NegotiationContextLoader:
|
||||
distribution_code=_SUPPLIER_TYPE_TO_CODE.get(supplier_type) if supplier_type else None,
|
||||
selected_nego_card_numbers=selected_nego_cards,
|
||||
selected_wild_card_numbers=selected_wild_cards,
|
||||
internet_lowest_price=internet_lowest,
|
||||
deadline_end_ts=deadline_end_ts,
|
||||
deadline_total_s=deadline_total_s,
|
||||
hist_n=hist_n,
|
||||
hist_success=hist_success,
|
||||
hist_settle_ratio=hist_settle,
|
||||
card_count=card_count,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
"""완전 자율 협상 행동 공간 (numpy 전용 — 학습(tools)과 서빙(policy)이 공유).
|
||||
|
||||
카드 카탈로그 대신 행동의 '의미'만 남긴다:
|
||||
ACCEPT 현재 제시가로 타결
|
||||
WALK 협상 결렬 선언
|
||||
COUNTER(q, s) "C원이면 수락" 역제안. C = anchor + q×(target−anchor), s = 화법 전략
|
||||
PRESS(s) 설득 압박 (카드의 일반화 — 전략 1경쟁/2수용/3고수/4협력)
|
||||
|
||||
특징 벡터(ACTION_DIM=8) = 유형 one-hot(3) + 가격 위치(1) + 전략 one-hot(4).
|
||||
ScoreNet(상태 + 행동특징) → 스칼라 점수로 후보 30개를 채점해 argmax 한다.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
COUNTER_GRID = [-0.05, 0.0, 0.25, 0.5, 0.75, 1.0] # C = anchor + q×(target−anchor)
|
||||
ACTION_DIM = 3 + 1 + 4 + 1 # 유형(3) + 위치(1) + 전략(4) + 컷폭(1: 현 제시가 대비 인하 요구율)
|
||||
|
||||
# 자율 전용 추가 상태 (v3):
|
||||
# [0] 직전 역제안 존재(0/1) [1] 직전 역제안 위치 q ← 에피소드 기억(같은 숫자 반복 방지)
|
||||
# [2] 마감 잔여율(남은시간/전체, 미상 0.5) ← 견적 마감(quotations.end_time)
|
||||
# [3] 과거 협상 횟수 min(n,5)/5 [4] 과거 성사율(미상 0.5)
|
||||
# [5] 과거 평균 타결수준 norm((타결가/목표가−0.8)/0.4, 미상 0.5) ← 이 협력사와의 이력(experience_logs)
|
||||
# [6] 인터넷최저가 갭 clip((최저가−앵커)/앵커/0.1, ±1, 미상 0) ← 숨은 하한가의 관측 가능한 힌트
|
||||
# 특징은 학습 시뮬에도 동일하게 존재해야 한다(train_full_autonomy 가 대응물을 생성).
|
||||
EXTRA_STATE_DIM = 7
|
||||
|
||||
|
||||
def extra_state(last_kind: str = "", last_q: float = 0.0, deadline: float = 0.5,
|
||||
hist_n: float = 0.0, hist_success: float = 0.5, hist_settle: float = 0.5,
|
||||
internet_gap: float = 0.0) -> np.ndarray:
|
||||
has_counter = 1.0 if last_kind == "counter" else 0.0
|
||||
return np.array([
|
||||
has_counter,
|
||||
float(np.clip(last_q, -1.0, 1.0)) * has_counter,
|
||||
float(np.clip(deadline, 0.0, 1.0)),
|
||||
float(np.clip(hist_n, 0.0, 1.0)),
|
||||
float(np.clip(hist_success, 0.0, 1.0)),
|
||||
float(np.clip(hist_settle, 0.0, 1.0)),
|
||||
float(np.clip(internet_gap, -1.0, 1.0)),
|
||||
], dtype=np.float32)
|
||||
|
||||
|
||||
def settle_norm(avg_settle_ratio: float) -> float:
|
||||
"""평균 (타결가/목표가) → 0~1 정규화 (0.8→0, 1.0→0.5, 1.2→1)."""
|
||||
return float(np.clip((avg_settle_ratio - 0.8) / 0.4, 0.0, 1.0))
|
||||
|
||||
|
||||
def internet_gap_feat(internet_lowest: float, anchor: float) -> float:
|
||||
"""인터넷최저가의 앵커 대비 갭 (±10% 스케일). 최저가 없으면 0을 쓴다."""
|
||||
if not internet_lowest or anchor <= 0:
|
||||
return 0.0
|
||||
return float(np.clip((internet_lowest - anchor) / anchor / 0.1, -1.0, 1.0))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Action:
|
||||
kind: str # accept | walk | counter | press
|
||||
counter_q: float = 0.0 # counter 위치 (anchor~target 스팬 비율)
|
||||
strategy: int = 0 # press/counter 의 화법 전략 (1~4, 0=없음)
|
||||
|
||||
def feat(self, price_pos: float, cut: float = 0.0) -> np.ndarray:
|
||||
"""cut: 이 행동이 요구하는 인하폭 (현 제시가 대비, counter 만 >0) — 대형컷의 무례함을
|
||||
정책이 지각하게 한다. 갭이 크면 역제안 대신 압박이 낫다는 걸 배우는 근거 특징."""
|
||||
t = {"accept": [1, 0, 0], "walk": [0, 1, 0]}.get(self.kind, [0, 0, 1])
|
||||
pos = price_pos if self.kind == "accept" else self.counter_q
|
||||
s = np.zeros(4, dtype=np.float32)
|
||||
if self.strategy:
|
||||
s[self.strategy - 1] = 1.0
|
||||
return np.concatenate([np.array(t, dtype=np.float32),
|
||||
np.array([float(np.clip(pos, -1.0, 2.0)),
|
||||
], dtype=np.float32), s,
|
||||
np.array([float(np.clip(cut, 0.0, 1.0))], dtype=np.float32)])
|
||||
|
||||
|
||||
def candidate_actions():
|
||||
"""전 행동 후보: 수락 1 + 결렬 1 + 역제안 6×전략4 + 압박 4 = 30."""
|
||||
out = [Action("accept"), Action("walk")]
|
||||
out += [Action("counter", q, s) for q in COUNTER_GRID for s in (1, 2, 3, 4)]
|
||||
out += [Action("press", 0.0, s) for s in (1, 2, 3, 4)]
|
||||
return out
|
||||
|
||||
|
||||
ACTIONS = candidate_actions()
|
||||
@@ -1,132 +0,0 @@
|
||||
"""FeatureDQNPolicy — action-as-feature DQN (Phase 2·3).
|
||||
|
||||
고정 슬롯 Q(s)→[11개] 대신 ScoreNet(상태벡터 + 카드임베딩) → 스칼라 점수.
|
||||
결정 시 가용 카드 풀을 순회 채점해 argmax → 카드 추가/삭제/새 카드(zero-shot)에 구조 변화 없음.
|
||||
협력사 특징은 상태벡터에 포함(feature_builder) → '협력사를 입력으로' 달성.
|
||||
|
||||
가변 행동 학습: replay 에 다음 상태의 '가용 카드 임베딩들'을 함께 저장,
|
||||
target = r + γ · max_{c'∈next_avail} Q(s', c') · (1-done)
|
||||
"""
|
||||
|
||||
import math
|
||||
import random
|
||||
from collections import deque
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
class ScoreNet(nn.Module):
|
||||
"""(상태 + 카드임베딩) → 스칼라 점수."""
|
||||
|
||||
def __init__(self, state_dim: int, card_dim: int, hidden: int = 128):
|
||||
super().__init__()
|
||||
self.net = nn.Sequential(
|
||||
nn.Linear(state_dim + card_dim, hidden), nn.ReLU(),
|
||||
nn.Linear(hidden, hidden), nn.ReLU(),
|
||||
nn.Linear(hidden, 1),
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor: # x: [B, state+card]
|
||||
return self.net(x).squeeze(-1) # [B]
|
||||
|
||||
|
||||
class FeatureDQNPolicy:
|
||||
name = "feature_dqn"
|
||||
|
||||
def __init__(self, state_dim: int, card_dim: int, device: str = "cpu",
|
||||
lr: float = 1e-3, gamma: float = 0.95, hidden: int = 128,
|
||||
eps_start: float = 1.0, eps_end: float = 0.05, eps_decay: int = 6000,
|
||||
buffer_size: int = 50_000, batch_size: int = 64, target_sync: int = 500):
|
||||
self.device = device
|
||||
self.gamma = gamma
|
||||
self.batch_size = batch_size
|
||||
self.target_sync = target_sync
|
||||
self.q = ScoreNet(state_dim, card_dim, hidden).to(device)
|
||||
self.tgt = ScoreNet(state_dim, card_dim, hidden).to(device)
|
||||
self.tgt.load_state_dict(self.q.state_dict())
|
||||
self.opt = torch.optim.Adam(self.q.parameters(), lr=lr)
|
||||
self.buf: deque = deque(maxlen=buffer_size)
|
||||
self.eps_start, self.eps_end, self.eps_decay = eps_start, eps_end, eps_decay
|
||||
self.steps = 0
|
||||
self.greedy = False # 평가 모드(탐색 끔)
|
||||
|
||||
# ---- 탐색 스케줄 ----------------------------------------------------
|
||||
def eps(self) -> float:
|
||||
if self.greedy:
|
||||
return 0.0
|
||||
return self.eps_end + (self.eps_start - self.eps_end) * math.exp(-self.steps / self.eps_decay)
|
||||
|
||||
# ---- 채점/선택 -------------------------------------------------------
|
||||
def scores(self, state_feat: np.ndarray, card_embs: np.ndarray) -> np.ndarray:
|
||||
"""가용 카드 K개 일괄 채점. card_embs: [K, card_dim] → [K]."""
|
||||
k = card_embs.shape[0]
|
||||
x = np.concatenate([np.repeat(state_feat[None, :], k, axis=0), card_embs], axis=1)
|
||||
with torch.no_grad():
|
||||
return self.q(torch.tensor(x, device=self.device)).cpu().numpy()
|
||||
|
||||
def select(self, state_feat: np.ndarray, card_embs: np.ndarray) -> Tuple[int, float, float]:
|
||||
"""(선택 인덱스, propensity, 선택 점수). 인덱스는 card_embs 행 기준."""
|
||||
k = card_embs.shape[0]
|
||||
sc = self.scores(state_feat, card_embs)
|
||||
e = self.eps()
|
||||
if random.random() < e:
|
||||
i = random.randrange(k)
|
||||
prop = e / k
|
||||
else:
|
||||
i = int(sc.argmax())
|
||||
prop = (1.0 - e) + e / k
|
||||
return i, prop, float(sc[i])
|
||||
|
||||
# ---- 경험/학습 -------------------------------------------------------
|
||||
def remember(self, state_feat: np.ndarray, card_emb: np.ndarray, reward: float,
|
||||
next_state_feat: Optional[np.ndarray], next_card_embs: Optional[np.ndarray],
|
||||
done: bool):
|
||||
self.buf.append((state_feat, card_emb, reward, next_state_feat, next_card_embs, done))
|
||||
|
||||
def train_step(self) -> Optional[float]:
|
||||
if len(self.buf) < self.batch_size:
|
||||
return None
|
||||
batch = random.sample(self.buf, self.batch_size)
|
||||
|
||||
# Q(s, a_chosen)
|
||||
xs = np.stack([np.concatenate([s, c]) for s, c, *_ in batch])
|
||||
q_sa = self.q(torch.tensor(xs, device=self.device))
|
||||
|
||||
# target = r + γ·max_{c'} Q_tgt(s', c') — 가변 후보라 후보 전체를 한 번에 forward 후 세그먼트 max
|
||||
rewards = torch.tensor([b[2] for b in batch], device=self.device, dtype=torch.float32)
|
||||
dones = torch.tensor([float(b[5]) for b in batch], device=self.device)
|
||||
next_rows, owner = [], []
|
||||
for bi, (_, _, _, s2, cands, done) in enumerate(batch):
|
||||
if done or s2 is None or cands is None or len(cands) == 0:
|
||||
continue
|
||||
for c in cands:
|
||||
next_rows.append(np.concatenate([s2, c]))
|
||||
owner.append(bi)
|
||||
q_next_max = torch.zeros(self.batch_size, device=self.device)
|
||||
if next_rows:
|
||||
with torch.no_grad():
|
||||
q_all = self.tgt(torch.tensor(np.stack(next_rows), device=self.device))
|
||||
owner_t = torch.tensor(owner, device=self.device)
|
||||
q_next_max = q_next_max.index_reduce_(0, owner_t, q_all, "amax", include_self=False)
|
||||
target = rewards + self.gamma * q_next_max * (1.0 - dones)
|
||||
|
||||
loss = nn.functional.smooth_l1_loss(q_sa, target)
|
||||
self.opt.zero_grad()
|
||||
loss.backward()
|
||||
self.opt.step()
|
||||
self.steps += 1
|
||||
if self.steps % self.target_sync == 0:
|
||||
self.tgt.load_state_dict(self.q.state_dict())
|
||||
return float(loss)
|
||||
|
||||
# ---- 저장/로드 -------------------------------------------------------
|
||||
def save(self, path: str):
|
||||
torch.save(self.q.state_dict(), path)
|
||||
|
||||
def load(self, path: str):
|
||||
sd = torch.load(path, map_location=self.device)
|
||||
self.q.load_state_dict(sd)
|
||||
self.tgt.load_state_dict(sd)
|
||||
@@ -1,152 +0,0 @@
|
||||
"""AutonomyStore — 완전 자율 협상 정책 서빙 (룰 대체, numpy 전용).
|
||||
|
||||
AUTONOMY_MODE=1 이면 가격협상 판정 룰(앵커 이하 타결 / 와일드카드 존 / 라운드 상한)과
|
||||
카드 선택을 전부 이 정책의 행동 결정으로 대체한다:
|
||||
accept → 협상완료 (제시가 타결) walk → 협상실패
|
||||
counter → "C원이면 수락" 역제안 스텝 press → 전략별 압박 멘트 스텝
|
||||
|
||||
행동의 유일한 유인은 보상 함수다. 남는 제한은 두 가지뿐이며 비즈니스 룰이 아니다:
|
||||
- 역제안 후보 격자가 [anchor−5%span, target] 안 (행동 공간 정의)
|
||||
- 세션 턴 상한(엔지니어링 타임아웃, ChatEngine._AUTONOMY_TURN_CAP)
|
||||
|
||||
번들: artifacts/autonomy_serving.npz (tools/export_autonomy_serving.py).
|
||||
불가(플래그 꺼짐/번들 없음)면 None → 기존 룰 엔진 그대로 (즉시 롤백 경로).
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
from common.logger import LOG
|
||||
from negotiation.policies.autonomy_actions import (
|
||||
ACTIONS, Action, extra_state, internet_gap_feat, settle_norm)
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||
from negotiation.qtable.domain.service.feature_builder import (
|
||||
build_state_features, build_tenant_features)
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
BUNDLE_PATH = os.path.join(_HERE, "..", "..", "artifacts", "autonomy_serving.npz")
|
||||
|
||||
|
||||
class AutonomyPolicy:
|
||||
"""세션 컨텍스트 → 상태특징 → 행동(greedy). ChatEngine 에 decider 로 주입된다."""
|
||||
|
||||
name = "full_autonomy"
|
||||
|
||||
def __init__(self, z, reward_cfg):
|
||||
self._W = (z["W0"], z["b0"], z["W1"], z["b1"], z["W2"], z["b2"])
|
||||
self._state_dim = int(z["state_dim"])
|
||||
self._tenant_feat = build_tenant_features(reward_cfg)
|
||||
|
||||
@staticmethod
|
||||
def _acceptance(ctx: dict) -> float:
|
||||
base = ctx.get("item_price") or ctx.get("first_offer_price") or 0
|
||||
cur = ctx.get("input_price") or 0
|
||||
if base <= 0 or cur <= 0:
|
||||
return 0.0
|
||||
return max(0.0, (base - cur) / base)
|
||||
|
||||
def decide(self, ctx: dict) -> Action:
|
||||
"""ChatSession.context → Action. 상태 구성은 ChatService._snapshot 과 동일 규칙."""
|
||||
snap = NegotiationSnapshot(
|
||||
revenue_amount=ctx["revenue_amount"], distribution_code=ctx["distribution_code"],
|
||||
partner_count=ctx["partner_count"], acceptance_ratio=self._acceptance(ctx),
|
||||
input_price=ctx.get("input_price", ctx["anchor_price"]), anchor_price=ctx["anchor_price"],
|
||||
target_price=ctx["target_price"], round_number=ctx.get("round", 0),
|
||||
)
|
||||
# v3 추가 특징: 직전 역제안 기억 + 마감 잔여율 + 협력사 이력 + 인터넷최저가 갭.
|
||||
# 소스가 없으면 전부 중립값(0.5/0) — 학습 시뮬의 '미상' 표현과 동일해야 한다.
|
||||
# 역제안 기억은 autonomy_last_counter(역제안만 갱신) — autonomy_last(마지막 행동)를 쓰면
|
||||
# 사이에 낀 설득이 기억을 지워 단조 봉투가 뚫린다(counter→press→counter 철회 실버그).
|
||||
# 시뮬의 last_kind/last_q 도 역제안만 추적하므로 이쪽이 학습 분포와도 일치한다.
|
||||
last = ctx.get("autonomy_last_counter") or {}
|
||||
deadline = 0.5
|
||||
end_ts, total_s = ctx.get("deadline_end_ts"), ctx.get("deadline_total_s")
|
||||
if end_ts and total_s:
|
||||
import time
|
||||
deadline = float(np.clip((end_ts - time.time()) / total_s, 0.0, 1.0))
|
||||
hist_n = int(ctx.get("hist_n") or 0)
|
||||
hist_success = float(ctx["hist_success"]) if ctx.get("hist_success") is not None else 0.5
|
||||
hist_settle = (settle_norm(float(ctx["hist_settle_ratio"]))
|
||||
if ctx.get("hist_settle_ratio") is not None else 0.5)
|
||||
sf = np.concatenate([build_state_features(snap), self._tenant_feat, extra_state(
|
||||
last.get("kind", ""), float(last.get("q", 0.0)),
|
||||
deadline=deadline, hist_n=min(hist_n, 5) / 5.0,
|
||||
hist_success=hist_success if hist_n else 0.5,
|
||||
hist_settle=hist_settle,
|
||||
internet_gap=internet_gap_feat(float(ctx.get("internet_lowest_price") or 0),
|
||||
float(snap.anchor_price)),
|
||||
)])
|
||||
span = max(snap.target_price - snap.anchor_price, 1.0)
|
||||
pos = (snap.input_price - snap.anchor_price) / span
|
||||
# 행동 봉투 (학습 available_actions 와 동일해야 한다):
|
||||
# ① 목표가 초과 제시가는 '수락' 제외 — 매입 승인 범위(v3.1 착취 방지)
|
||||
# ② 직전 역제안보다 낮은 금액의 역제안 제외 — 단조 양보 원칙(제안 철회는 협상 예절 위반;
|
||||
# 올리는 '속도'는 정책 학습, 후퇴 '금지'만 구조로 보장)
|
||||
# ③ 역제시 해금 조건 — 옛 제품 의미론 복원(제품 결정 2026-07-10): 일반 카드는 설득만,
|
||||
# 역제시(숫자 제안)는 와일드카드처럼 마무리 수단. 최소 AUTONOMY_MIN_PRESS(기본 2)회
|
||||
# 설득 이후에만 역제시 후보가 열린다. 해금 후의 타이밍·금액은 정책 학습.
|
||||
# ④ 마무리 국면 — 제시가가 목표가 0.5% 이내로 붙으면 압박 제외(+역제시 잠금 해제):
|
||||
# 푼돈 차이에서 '재검토 부탁' 반복은 상대만 지치게 한다. 클로징(역제안/최종제안)하거나 끝내거나.
|
||||
min_press = int(os.getenv("AUTONOMY_MIN_PRESS", "2"))
|
||||
near_target = snap.input_price <= snap.target_price * 1.005
|
||||
counter_locked = (int(ctx.get("autonomy_press_n") or 0) < min_press) and not near_target
|
||||
last_counter_q = float(last["q"]) if last.get("kind") == "counter" else None
|
||||
if last_counter_q is not None:
|
||||
counter_locked = False # 이미 역제시를 시작했으면 잠그지 않는다(단조 봉투가 관리)
|
||||
# ⑤ 첫 역제안은 앵커가 이하(q ≤ 0)만 — 낮게 개시해 목표가까지 천천히 올라간다
|
||||
# (제품 결정: 사다리를 다 쓰는 앵커링 개시. 이후 단조 봉투가 상향을 관리).
|
||||
# ⑥ 결렬(walk)도 해금 전 금지 — 설득 0회에 walk 를 고르면 최종제안 보장(엔진)과 결합해
|
||||
# '첫 턴 목표가 통보'가 된다(v3.4 라이브 결함). 해금 전에는 설득만 가능.
|
||||
cands = [a for a in ACTIONS
|
||||
if not (a.kind == "accept" and snap.input_price > snap.target_price)
|
||||
and not (a.kind == "counter" and counter_locked)
|
||||
and not (a.kind == "walk" and counter_locked)
|
||||
and not (a.kind == "press" and near_target)
|
||||
and not (a.kind == "counter" and last_counter_q is None and a.counter_q > 1e-9)
|
||||
and not (a.kind == "counter" and last_counter_q is not None
|
||||
and a.counter_q < last_counter_q - 1e-9)]
|
||||
feats = []
|
||||
for a in cands:
|
||||
cut = 0.0
|
||||
if a.kind == "counter":
|
||||
c = snap.anchor_price + a.counter_q * span
|
||||
cut = max(0.0, (snap.input_price - c) / max(snap.input_price, 1.0))
|
||||
feats.append(a.feat(pos, cut))
|
||||
feats = np.stack(feats)
|
||||
W0, b0, W1, b1, W2, b2 = self._W
|
||||
x = np.concatenate([np.repeat(sf[None, :], feats.shape[0], axis=0), feats], axis=1)
|
||||
h = np.maximum(x @ W0.T + b0, 0.0)
|
||||
h = np.maximum(h @ W1.T + b1, 0.0)
|
||||
scores = (h @ W2.T + b2).squeeze(-1)
|
||||
return cands[int(np.argmax(scores))]
|
||||
|
||||
@staticmethod
|
||||
def counter_price(ctx: dict, act: Action) -> int:
|
||||
span = max(ctx["target_price"] - ctx["anchor_price"], 1.0)
|
||||
return int(round(ctx["anchor_price"] + act.counter_q * span))
|
||||
|
||||
|
||||
class AutonomyStore:
|
||||
_z = None
|
||||
_load_failed = False
|
||||
|
||||
@classmethod
|
||||
def enabled(cls) -> bool:
|
||||
return os.getenv("AUTONOMY_MODE", "0").lower() in ("1", "true", "yes")
|
||||
|
||||
@classmethod
|
||||
def policy_for(cls, engine) -> Optional[AutonomyPolicy]:
|
||||
"""engine: tenancy.registry.TenantEngine. 비활성/번들 없음 → None (룰 엔진 유지)."""
|
||||
if not cls.enabled() or cls._load_failed:
|
||||
return None
|
||||
if cls._z is None:
|
||||
try:
|
||||
cls._z = np.load(BUNDLE_PATH, allow_pickle=False)
|
||||
LOG.i("[Autonomy] 완전 자율 정책 번들 로드 완료 — 협상 판정 룰 대체 모드")
|
||||
except Exception as ex:
|
||||
cls._load_failed = True
|
||||
LOG.e_no_callstack(f"[Autonomy] 번들 로드 실패 → 룰 엔진 유지: {ex}")
|
||||
return None
|
||||
return AutonomyPolicy(cls._z, engine.config.reward)
|
||||
@@ -1,118 +0,0 @@
|
||||
"""DQNServingStore — action-as-feature DQN 서빙 (선택 전용, 학습 없음).
|
||||
|
||||
tools/export_dqn_serving.py 가 만든 dqn_serving.npz(ScoreNet 가중치 + 카드특징 392차원)를
|
||||
numpy 로 추론한다 — 서빙 컨테이너에 PyTorch 불필요.
|
||||
|
||||
역할 분담(계획서 H 트랙으로 가기 전 파일럿):
|
||||
- 카드 '선택'만 DQN(greedy). Q-table 학습/영속/experience_logs 로깅 경로는 기존 그대로 유지
|
||||
(Q-learning 은 오프폴리시라 DQN 이 고른 행동으로 갱신해도 유효, 로그는 DQN 오프라인 재학습 재료).
|
||||
- 폴백: 플래그 꺼짐 / 번들 없음 / 가용 카드 전부 특징 미보유(신규 카드) → None 반환,
|
||||
호출부(ChatService)가 기존 UCB Q-table 선택으로 진행한다.
|
||||
|
||||
활성화: 환경변수 DQN_SERVING=1 (docker-compose agent environment).
|
||||
신규 카드 주의: 번들에 없는 카드번호는 후보에서 제외된다 — 카드 추가 시
|
||||
tools/build_card_embeddings.py → tools/export_dqn_serving.py 재실행 후 재배포 필요.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import List, Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
from common.logger import LOG
|
||||
from negotiation.policies.base import ActionDecision, PolicyContext
|
||||
from negotiation.qtable.domain.service.feature_builder import (
|
||||
build_state_features, build_tenant_features)
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
BUNDLE_PATH = os.path.join(_HERE, "..", "..", "artifacts", "dqn_serving.npz")
|
||||
|
||||
|
||||
class _Bundle:
|
||||
def __init__(self, z):
|
||||
self.W0, self.b0 = z["W0"], z["b0"]
|
||||
self.W1, self.b1 = z["W1"], z["b1"]
|
||||
self.W2, self.b2 = z["W2"], z["b2"]
|
||||
self.state_dim = int(z["state_dim"])
|
||||
self.card_feats = {str(n): z["card_feats"][i]
|
||||
for i, n in enumerate(z["card_numbers"])}
|
||||
|
||||
def scores(self, state_feat: np.ndarray, card_feats: np.ndarray) -> np.ndarray:
|
||||
"""가용 카드 K개 일괄 채점: [K, state+card] → [K]."""
|
||||
k = card_feats.shape[0]
|
||||
x = np.concatenate([np.repeat(state_feat[None, :], k, axis=0), card_feats], axis=1)
|
||||
h = np.maximum(x @ self.W0.T + self.b0, 0.0)
|
||||
h = np.maximum(h @ self.W1.T + self.b1, 0.0)
|
||||
return (h @ self.W2.T + self.b2).squeeze(-1)
|
||||
|
||||
|
||||
class DQNServingPolicy:
|
||||
"""UCBQTablePolicy.select 와 동일한 PolicyContext → ActionDecision 계약(선택 전용)."""
|
||||
|
||||
name = "feature_dqn"
|
||||
_EPS = 0.1 # propensity 근사용 ε (UCB 정책과 동일 관례 — OPE 지지 확보용, 선택은 greedy)
|
||||
|
||||
def __init__(self, bundle: _Bundle, engine): # engine: tenancy.registry.TenantEngine
|
||||
self._bundle = bundle
|
||||
self._mapper = engine.mapper
|
||||
self._tenant_feat = build_tenant_features(engine.config.reward)
|
||||
|
||||
def _available(self, ctx: PolicyContext) -> List[int]:
|
||||
# UCBQTablePolicy._available 과 동일 규칙 (마스크 → used 제외 → 소진 시 전체 허용)
|
||||
if ctx.available_mask is not None:
|
||||
avail = [a for a in range(ctx.action_space_size) if ctx.available_mask[a]]
|
||||
else:
|
||||
used = ctx.episode.used_action_ids if ctx.episode else set()
|
||||
avail = [a for a in range(ctx.action_space_size) if a not in used]
|
||||
return avail or list(range(ctx.action_space_size))
|
||||
|
||||
def select(self, ctx: PolicyContext) -> Optional[ActionDecision]:
|
||||
"""카드특징이 있는 가용 카드가 없으면 None → 호출부가 Q-table 로 폴백."""
|
||||
candidates = [] # (action_id, card_feat)
|
||||
for a in self._available(ctx):
|
||||
num = self._mapper.get_card_id(a)
|
||||
feat = self._bundle.card_feats.get(num) if num else None
|
||||
if feat is not None:
|
||||
candidates.append((a, feat))
|
||||
if not candidates:
|
||||
return None
|
||||
state_feat = np.concatenate([build_state_features(ctx.snapshot), self._tenant_feat])
|
||||
if state_feat.shape[0] != self._bundle.state_dim:
|
||||
LOG.e_no_callstack(
|
||||
f"[DQNServing] state_dim 불일치: {state_feat.shape[0]} != {self._bundle.state_dim}")
|
||||
return None
|
||||
sc = self._bundle.scores(state_feat, np.stack([f for _, f in candidates]))
|
||||
i = int(sc.argmax())
|
||||
n = len(candidates)
|
||||
return ActionDecision(
|
||||
action_id=candidates[i][0],
|
||||
propensity=(1.0 - self._EPS) + self._EPS / n,
|
||||
q_value=float(sc[i]),
|
||||
ucb_score=float(sc[i]),
|
||||
available_actions=[a for a, _ in candidates],
|
||||
)
|
||||
|
||||
|
||||
class DQNServingStore:
|
||||
"""번들 lazy 로드 + 캐시. 비활성/부재 시 None (호출부 Q-table 폴백)."""
|
||||
|
||||
_bundle: Optional[_Bundle] = None
|
||||
_load_failed = False
|
||||
|
||||
@classmethod
|
||||
def enabled(cls) -> bool:
|
||||
return os.getenv("DQN_SERVING", "0").lower() in ("1", "true", "yes")
|
||||
|
||||
@classmethod
|
||||
def policy_for(cls, engine) -> Optional[DQNServingPolicy]:
|
||||
if not cls.enabled() or cls._load_failed:
|
||||
return None
|
||||
if cls._bundle is None:
|
||||
try:
|
||||
cls._bundle = _Bundle(np.load(BUNDLE_PATH, allow_pickle=False))
|
||||
LOG.i(f"[DQNServing] 번들 로드 완료: 카드 {len(cls._bundle.card_feats)}장")
|
||||
except Exception as ex:
|
||||
cls._load_failed = True # 요청마다 재시도하지 않음
|
||||
LOG.e_no_callstack(f"[DQNServing] 번들 로드 실패 → Q-table 폴백: {ex}")
|
||||
return None
|
||||
return DQNServingPolicy(cls._bundle, engine)
|
||||
@@ -1,44 +0,0 @@
|
||||
"""build_state_features — snapshot(raw 연속값) → 실수 벡터 (DQN/action-as-feature 용).
|
||||
|
||||
state_calculator.build_state(이산화)와 대비되는 연속 표현. 이산화(등급/162칸)를 하지 않고
|
||||
정규화된 raw 값을 그대로 벡터로 내보낸다. 협력사 특징(매출·경쟁사수·유통)이 벡터에 포함되므로
|
||||
'협력사를 입력으로'(Phase 3)가 자연스럽게 달성된다.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||
|
||||
DIST_CLASSES = ("A", "B", "C")
|
||||
STATE_FEATURE_DIM = 9 # build_state_features 벡터 길이. feature 추가 시 갱신.
|
||||
TENANT_FEATURE_DIM = 5 # build_tenant_features 벡터 길이.
|
||||
|
||||
|
||||
def build_tenant_features(reward_cfg) -> np.ndarray:
|
||||
"""고객사 '성향'을 ID 가 아니라 보상 설정값(내용)으로 벡터화 (Phase 3 고객사 조건화).
|
||||
|
||||
새 고객사도 tenant.yaml 의 reward 설정만 있으면 즉시 조건화된다 (cold-start 없음).
|
||||
"""
|
||||
return np.array([
|
||||
reward_cfg.max_weight, # 가격 중시 정도 (W↑ = 가격보상 비중↑)
|
||||
reward_cfg.success_reward / 2.0, # 성사를 얼마나 크게 치는가
|
||||
-reward_cfg.failure_penalty / 2.0, # 결렬을 얼마나 무서워하는가
|
||||
reward_cfg.penalty_lambda * 20.0, # 속도 성향 (오래 끌수록 벌점)
|
||||
reward_cfg.beta, # 앵커 초과달성 보너스 성향
|
||||
], dtype=np.float32)
|
||||
|
||||
|
||||
def build_state_features(s: NegotiationSnapshot) -> np.ndarray:
|
||||
"""정규화된 연속 상태 벡터. 등급화 없음 — 990원과 850원이 구별된다."""
|
||||
dist_onehot = [1.0 if s.distribution_code == c else 0.0 for c in DIST_CLASSES]
|
||||
anchor = max(s.anchor_price, 1.0)
|
||||
target = max(s.target_price, 1.0)
|
||||
return np.array([
|
||||
min(s.revenue_amount, 5e8) / 5e8, # 협력사 매출 (0~1)
|
||||
*dist_onehot, # 유통 A/B/C
|
||||
min(s.partner_count, 5) / 5.0, # 대안 협력사 수 (BATNA)
|
||||
float(np.clip(s.acceptance_ratio, 0.0, 1.0)), # 수용률
|
||||
float(np.clip((s.input_price - anchor) / anchor, -1.0, 2.0)), # 앵커 대비 격차 (연속!)
|
||||
float(np.clip((target - s.input_price) / target, -2.0, 1.0)), # 목표 대비 여유
|
||||
min(s.round_number, 10) / 10.0, # 라운드
|
||||
], dtype=np.float32)
|
||||
@@ -14,7 +14,6 @@ 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 compute_counter, tactic_available, tactic_for
|
||||
from negotiation.chat.service import ment_generator
|
||||
from negotiation.chat.service.chat_engine import (
|
||||
_CHOICE_MODES, _PRICE_MODES, ChatEngine, ChatSession, StepView,
|
||||
)
|
||||
@@ -25,9 +24,6 @@ from negotiation.chat.service.negotiation_context_loader import NegotiationConte
|
||||
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.policies.autonomy_actions import ACTIONS as AUTONOMY_ACTIONS
|
||||
from negotiation.policy.autonomy_store import AutonomyStore
|
||||
from negotiation.policy.dqn_store import DQNServingStore
|
||||
from negotiation.policy.model_store import QTablePolicyStore
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot, PartnerType
|
||||
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||
@@ -63,19 +59,9 @@ class ChatService:
|
||||
session = await sess_repo.get(req.session_id) if req.session_id else None
|
||||
# 새 세션 컨텍스트: 요청 페이로드 대신 DB(negotiation.sessions 등)에서 1회 조회.
|
||||
# 행이 없으면(데모/테스트 직접 호출) 기본값 폴백.
|
||||
db_ctx = None if session else await NegotiationContextLoader().load(req.session_id, engine.company_id)
|
||||
db_ctx = None if session else await NegotiationContextLoader().load(req.session_id)
|
||||
rq_type = session.rq_type if session else (db_ctx.rq_type if db_ctx else _DEFAULT_RQ_TYPE)
|
||||
chat_engine = ChatEngine(repo, rq_type=rq_type)
|
||||
# 완전 자율 모드(AUTONOMY_MODE=1 + 번들 존재): 가격협상 판정 룰·카드 선택을 정책 행동으로 대체.
|
||||
# decider 를 감싸 결정을 컨텍스트에 기록 → advance() 후 experience_logs 에 적재(_autonomy_learn).
|
||||
autonomy = AutonomyStore.policy_for(engine)
|
||||
if autonomy is not None:
|
||||
def _decide(ctx, _p=autonomy):
|
||||
act = _p.decide(ctx)
|
||||
ctx["autonomy_pending"] = {"idx": AUTONOMY_ACTIONS.index(act), "kind": act.kind,
|
||||
"q": act.counter_q, "s": act.strategy}
|
||||
return act
|
||||
chat_engine.autonomy_decider = _decide
|
||||
|
||||
# ① step desync 감지: backend 가 본 직전 봇 step(client_step)이 agent 세션 step 과 다르면 경고.
|
||||
# agent 가 자기 step 을 정답으로 보고 진행하고(응답의 step/client_step 으로 backend 가 따라옴),
|
||||
@@ -96,8 +82,12 @@ class ChatService:
|
||||
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)
|
||||
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
|
||||
)
|
||||
@@ -124,6 +114,9 @@ class ChatService:
|
||||
"round": 0,
|
||||
# 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용.
|
||||
"item_price": db_ctx.item_price if db_ctx else 0,
|
||||
# 인터넷 최저가(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% 인하는 기본 와일드카드로 항상 열고, 재원부족 등 선택형 와일드카드는
|
||||
# 선택된 와일드카드가 있을 때만 허용한다.
|
||||
@@ -131,13 +124,6 @@ class ChatService:
|
||||
"selected_nego_card_numbers": selected_nego_cards,
|
||||
"selected_wild_card_numbers": selected_wild_cards,
|
||||
"allow_selected_wildcards": True if db_ctx is None else bool(selected_wild_cards),
|
||||
# ---- 자율 에이전트 v3 특징 소스 (미상이면 키 자체를 중립값으로 — JSON 직렬화 안전) ----
|
||||
"internet_lowest_price": db_ctx.internet_lowest_price if db_ctx else 0,
|
||||
"deadline_end_ts": db_ctx.deadline_end_ts if db_ctx else None,
|
||||
"deadline_total_s": db_ctx.deadline_total_s if db_ctx else None,
|
||||
"hist_n": db_ctx.hist_n if db_ctx else 0,
|
||||
"hist_success": db_ctx.hist_success if db_ctx else None,
|
||||
"hist_settle_ratio": db_ctx.hist_settle_ratio if db_ctx else None,
|
||||
},
|
||||
)
|
||||
view = chat_engine.start(session)
|
||||
@@ -181,17 +167,6 @@ class ChatService:
|
||||
elif view.outcome is not None:
|
||||
await self._terminal_learn(engine, session, view.outcome, res)
|
||||
|
||||
# 3-b) 완전 자율 모드: 정책 결정·종료 결과를 experience_logs 에 적재 (실로그 재학습 재료).
|
||||
if autonomy is not None and view.error is None:
|
||||
await self._autonomy_learn(engine, session, view, res)
|
||||
# 자율 스텝 멘트를 LLM 으로 생성 (행동은 RL, 문장은 LLM). 실패/미설정 → 템플릿 유지.
|
||||
if view.step.startswith("자율_"):
|
||||
llm_ment = await ment_generator.generate(view.step, session.context)
|
||||
if llm_ment:
|
||||
res.script = llm_ment
|
||||
# 직전 봇 멘트 보존 — 다음 생성에서 같은 문장 구조 반복을 금지하는 힌트.
|
||||
session.context["autonomy_last_ment"] = (res.script or "")[:200]
|
||||
|
||||
if view.error:
|
||||
res.result.SetResult(ErrorType.NEGO_INVALID_STEP)
|
||||
res.msg = view.error
|
||||
@@ -312,13 +287,7 @@ class ChatService:
|
||||
available_mask=self._combined_mask(engine, session),
|
||||
prior_bonus=self._selection_prior(engine, session),
|
||||
episode=EpisodeState(used_action_ids=set(session.used_action_ids)))
|
||||
# 카드 '선택'은 DQN 서빙(활성 시), 학습/영속은 아래 Q-table 경로 그대로(오프폴리시 갱신).
|
||||
# DQN 불가(비활성/번들 없음/후보 특징 없음)면 None → 기존 UCB 선택 폴백.
|
||||
dqn = DQNServingStore.policy_for(engine)
|
||||
decision = dqn.select(ctx) if dqn is not None else None
|
||||
selector_name = dqn.name if decision is not None else policy.name
|
||||
if decision is None:
|
||||
decision = policy.select(ctx)
|
||||
decision = policy.select(ctx)
|
||||
session.used_action_ids.add(decision.action_id)
|
||||
card_id = self._card_id_for_action(engine, session, decision.action_id)
|
||||
# 전술 실행(재설계): 카드의 가격 행동 — 카운터 제시가를 계산해 세션에 적재한다.
|
||||
@@ -337,7 +306,7 @@ class ChatService:
|
||||
await self._log(repo, session, idx, decision.action_id, card_id, snap, reward, decision.propensity, done=False)
|
||||
|
||||
res.card_id = card_id
|
||||
res.policy = selector_name
|
||||
res.policy = policy.name
|
||||
res.q_value = decision.q_value
|
||||
res.updated_q = float(policy.qtable.q[idx, decision.action_id])
|
||||
res.visit_count = int(policy.qtable.visits[idx, decision.action_id])
|
||||
@@ -410,49 +379,6 @@ class ChatService:
|
||||
res.script = scripts.format_script(template, chat_engine.vars_for(session)) if template else view2.script
|
||||
res.card_id = closing_number
|
||||
|
||||
async def _autonomy_learn(self, engine: TenantEngine, session: ChatSession, view: StepView, res: Res_Chat):
|
||||
"""완전 자율 행동 로깅 — Q-table 은 건드리지 않고 experience_logs 만 적재한다.
|
||||
|
||||
action_id = autonomy_actions.ACTIONS 인덱스, card_id = "AUT|종류|위치|전략" (카드 재학습
|
||||
파이프라인이 임베딩 매칭에서 자동 제외하도록 프리픽스로 구분). 종료 시 최종 보상 행(done=True)을
|
||||
남겨 retrain 의 에피소드 재구성 규약(카드턴 N + 종료 1)과 정합을 맞춘다.
|
||||
"""
|
||||
def _card_id(d) -> str:
|
||||
return f"AUT|{d['kind']}|{d['q']:g}|{d['s']}"[:40]
|
||||
|
||||
ctx = session.context
|
||||
lrepo = LearningRepository(engine.company_id)
|
||||
pending = ctx.pop("autonomy_pending", None)
|
||||
if pending is not None:
|
||||
snap = self._snapshot(session, NegotiationOutcome.ONGOING)
|
||||
try:
|
||||
idx = state_index(snap, engine.config.state) # 로깅 호환용 이산 인덱스
|
||||
except ValueError:
|
||||
idx = 0 # 자율 모드는 이산 상태를 쓰지 않으므로 폴백해도 학습 오염 없음
|
||||
if ctx.get("autonomy_last"):
|
||||
ctx["autonomy_prev"] = ctx["autonomy_last"] # 직전 결정 보존 — 멘트 생성 힌트(양보 언급)용
|
||||
ctx["autonomy_last"] = dict(pending, state_index=idx)
|
||||
if pending.get("kind") == "counter":
|
||||
# 역제안 기억은 별도 키로 보존 — autonomy_last 는 '마지막 행동'이라 사이에 낀
|
||||
# 설득이 덮어쓴다. 단조 봉투·탄약소진 판정이 이 기억을 기준으로 해야
|
||||
# counter→press→counter 에서 제안 철회가 새지 않는다 (게이트가 잡은 실버그).
|
||||
ctx["autonomy_last_counter"] = dict(pending)
|
||||
if pending.get("kind") == "press":
|
||||
# 설득 횟수 누적 — 역제시 해금 조건(autonomy_store ③)의 카운터.
|
||||
ctx["autonomy_press_n"] = int(ctx.get("autonomy_press_n") or 0) + 1
|
||||
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
|
||||
await self._log(lrepo, session, idx, pending["idx"], _card_id(pending), snap,
|
||||
reward, (1.0 - 0.1) + 0.1 / len(AUTONOMY_ACTIONS), done=False)
|
||||
res.policy = "full_autonomy"
|
||||
last = ctx.get("autonomy_last")
|
||||
if view.outcome is not None and last is not None:
|
||||
oc = NegotiationOutcome.SUCCESS if view.outcome == "success" else NegotiationOutcome.FAILURE
|
||||
snap = self._snapshot(session, oc)
|
||||
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
|
||||
res.reward_total = reward.total
|
||||
await self._log(lrepo, session, last["state_index"], last["idx"], _card_id(last), snap,
|
||||
reward, None, done=True)
|
||||
|
||||
async def _terminal_learn(self, engine: TenantEngine, session: ChatSession, outcome: str, res: Res_Chat):
|
||||
oc = NegotiationOutcome.SUCCESS if outcome == "success" else NegotiationOutcome.FAILURE
|
||||
snap = self._snapshot(session, oc)
|
||||
|
||||
@@ -47,8 +47,8 @@ def test_counter_formulas_and_clamp():
|
||||
assert compute_counter(tactic_for("WC-05"), ctx) == 10000
|
||||
# 갑 직전 포지션이 있으면 그 기준: (9800+11000)/2 = 10400 → 역시 클램프 10000
|
||||
assert compute_counter(tactic_for("WC-05"), dict(ctx, prev_customer_price=9800)) == 10000
|
||||
# 클램프 미발동 구간: (9900+10050)/2 = 9975 ≤ target
|
||||
assert compute_counter(tactic_for("WC-05"), dict(ctx, input_price=10050)) == 9975
|
||||
# 클램프 미발동 구간: (9900+10050)/2 = 9975 ≤ target → 10원 단위 반올림 9980
|
||||
assert compute_counter(tactic_for("WC-05"), dict(ctx, input_price=10050)) == 9980
|
||||
|
||||
|
||||
def test_counter_meaningless_degrades_to_hold():
|
||||
@@ -169,13 +169,21 @@ def test_price_confirm_script_renders_raise_correctly():
|
||||
# ---- vars_for 전술 변수 치환 ---------------------------------------------------
|
||||
def test_vars_for_supplies_tactic_variables():
|
||||
eng = _engine()
|
||||
s = _session(input_price=10300, prev_customer_price=10000, pending_counter_price=10100)
|
||||
v = eng.vars_for(s)
|
||||
assert v["prev_partner_price"] == 10300
|
||||
assert v["prev_customer_price"] == 10000
|
||||
assert v["target_mid_price"] == 10050 # (10000+10100)/2
|
||||
assert v["middle_price"] == 10150 # (10000+10300)/2
|
||||
assert v["counter_price"] == 10100
|
||||
# 카운터 미제시(정보성): 절충/중간 변수는 원 계산값.
|
||||
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 — 견적 선택 카드 + 서비스 레이어) ---------------------------
|
||||
|
||||
@@ -192,6 +192,12 @@ async def test_loader_with_crud_double(db_engine):
|
||||
async def get_item_price(self, cdb, item_id):
|
||||
return ErrorType.SUCCESS, 7000
|
||||
|
||||
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_supplier_total_revenue(self, cdb, supplier_id):
|
||||
return ErrorType.SUCCESS, 12_000_000.0
|
||||
|
||||
@@ -219,6 +225,8 @@ async def test_loader_with_crud_double(db_engine):
|
||||
assert ctx.target_price == 50000
|
||||
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
|
||||
assert ctx.item_price == 7000
|
||||
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
|
||||
|
||||
@@ -162,6 +162,31 @@ def test_card_id_fixed_mapping_and_selection_mask():
|
||||
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")
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
"""카드 스크립트 → 임베딩 캐시 생성 (action-as-feature 준비, 1회 실행).
|
||||
|
||||
card.nego_cards(11장)의 name+script 를 문장 임베딩으로 변환해 artifacts/card_embeddings.npz 에 저장.
|
||||
새 카드가 추가되면 이 스크립트를 다시 돌리면 된다(그 카드만 임베딩돼 캐시에 합류).
|
||||
|
||||
실행:
|
||||
APP_ENV=local python -m tools.build_card_embeddings
|
||||
출력:
|
||||
artifacts/card_embeddings.npz (numbers, names, strategy, tone, embeddings[N,384])
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ARTIFACTS = os.path.join(_HERE, "..", "artifacts")
|
||||
OUT_PATH = os.path.join(ARTIFACTS, "card_embeddings.npz")
|
||||
|
||||
MODEL_NAME = "paraphrase-multilingual-MiniLM-L12-v2" # 384차원, 한국어 지원, 로컬/무료
|
||||
|
||||
|
||||
async def load_cards():
|
||||
"""card.nego_cards 에서 (number, name, script, strategy_type, tone) 로드."""
|
||||
import asyncpg
|
||||
conn = await asyncpg.connect(
|
||||
host="127.0.0.1", port=5432, user="postgres", password="password", database="negosium_db")
|
||||
try:
|
||||
rows = await conn.fetch(
|
||||
"SELECT number, name, script, strategy_type, tone FROM card.nego_cards "
|
||||
"WHERE deleted = FALSE ORDER BY number")
|
||||
return [(r["number"], r["name"], r["script"], r["strategy_type"], r["tone"]) for r in rows]
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
def main():
|
||||
cards = asyncio.run(load_cards())
|
||||
if not cards:
|
||||
raise SystemExit("card.nego_cards 가 비어있음 — DB 시드 확인 (docker start negosium-pg)")
|
||||
print(f"카드 {len(cards)}장 로드: {[c[0] for c in cards]}")
|
||||
|
||||
from sentence_transformers import SentenceTransformer
|
||||
model = SentenceTransformer(MODEL_NAME)
|
||||
texts = [f"{name}. {script}" for _, name, script, _, _ in cards]
|
||||
emb = model.encode(texts, normalize_embeddings=True) # [N, 384], 단위벡터
|
||||
print(f"임베딩 shape: {emb.shape}")
|
||||
|
||||
os.makedirs(ARTIFACTS, exist_ok=True)
|
||||
np.savez(
|
||||
OUT_PATH,
|
||||
numbers=np.array([c[0] for c in cards]),
|
||||
names=np.array([c[1] for c in cards]),
|
||||
strategy=np.array([c[3] for c in cards], dtype=np.int64),
|
||||
tone=np.array([c[4] for c in cards], dtype=np.int64),
|
||||
embeddings=emb.astype(np.float32),
|
||||
)
|
||||
print(f"저장: {OUT_PATH}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,251 +0,0 @@
|
||||
"""기존 Q-Table(UCB) vs action-as-feature DQN 공정 비교 — 고객사 성향 조건화 환경 (최종).
|
||||
|
||||
같은 환경(FeatureBuyer 2축 + 협력사·고객사성향 랜덤)에서 동일 에피소드로 학습·평가.
|
||||
- Q-Table: 이산 state 162칸 + 카드=슬롯. 성향(고객사) 입력 자체가 불가능 → 평균 성향에 수렴
|
||||
- DQN : 연속 상태 + 성향 벡터 + 카드 특징(임베딩+전략/톤 one-hot)
|
||||
|
||||
평가 4종:
|
||||
① 학습 카드 9장 — 평균보상(진짜 목적함수) + top3 적중(MC 정답 기준)
|
||||
② zero-shot 11장 — 안 본 카드 2장 포함
|
||||
③ 새 카드 첫 턴 사용률 — 구조적 차이
|
||||
④ 성향 극단 테스트 — 같은 협력사, 성향만 바꿨을 때 카드를 바꾸는가
|
||||
|
||||
실행: APP_ENV=local python -m tools.compare_qtable_vs_dqn
|
||||
"""
|
||||
|
||||
import random
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from eval_harness.buyer import Scenario
|
||||
from eval_harness.feature_buyer import FeatureBuyer, SupplierProfile, sample_supplier
|
||||
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
|
||||
from negotiation.policies.qtable_policy import UCBQTablePolicy
|
||||
from negotiation.policies.base import EpisodeState, PolicyContext, Transition
|
||||
from negotiation.qtable.domain.model.q_table import QTable
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome
|
||||
from negotiation.qtable.domain.service.feature_builder import (
|
||||
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features)
|
||||
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||
from negotiation.qtable.domain.service.state_calculator import state_index
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tools.train_feature_dqn import (
|
||||
ANCHOR, HOLDOUT, MAX_TURNS, TARGET, load_cards, make_snapshot, pref_config, sample_tenant_pref)
|
||||
|
||||
|
||||
# ---- 정책 어댑터 ------------------------------------------------------------------
|
||||
class DQNAdapter:
|
||||
name = "feature_dqn"
|
||||
|
||||
def __init__(self, policy, feat):
|
||||
self.p, self.feat = policy, feat
|
||||
|
||||
def _sf(self, snap, tf):
|
||||
return np.concatenate([build_state_features(snap), tf])
|
||||
|
||||
def choose(self, snap, tf, avail, greedy):
|
||||
self.p.greedy = greedy
|
||||
i, _, _ = self.p.select(self._sf(snap, tf), np.stack([self.feat[c] for c in avail]))
|
||||
return avail[i]
|
||||
|
||||
def learn(self, snap, tf, card, reward, next_snap, next_avail, done):
|
||||
sf = self._sf(snap, tf)
|
||||
if done or next_snap is None:
|
||||
self.p.remember(sf, self.feat[card], reward, None, None, True)
|
||||
else:
|
||||
self.p.remember(sf, self.feat[card], reward, self._sf(next_snap, tf),
|
||||
np.stack([self.feat[c] for c in next_avail]), False)
|
||||
self.p.train_step()
|
||||
|
||||
|
||||
class QTableAdapter:
|
||||
"""기존 UCBQTablePolicy. 성향(tf)은 구조상 받을 수 없다 — 이산 state 162칸에 그 축이 없음."""
|
||||
|
||||
name = "qtable_ucb"
|
||||
|
||||
def __init__(self, all_numbers, state_cfg, lr=0.1, gamma=0.95):
|
||||
self.numbers = list(all_numbers)
|
||||
self.a_of = {n: i for i, n in enumerate(self.numbers)}
|
||||
self.state_cfg = state_cfg
|
||||
self.qt = QTable(162, len(self.numbers), learning_rate=lr, discount_factor=gamma)
|
||||
self.pol = UCBQTablePolicy(self.qt)
|
||||
|
||||
def choose(self, snap, tf, avail, greedy):
|
||||
idx = state_index(snap, self.state_cfg)
|
||||
if greedy:
|
||||
q = self.qt.row(idx)
|
||||
return max(avail, key=lambda c: q[self.a_of[c]])
|
||||
mask = np.zeros(len(self.numbers), dtype=bool)
|
||||
for c in avail:
|
||||
mask[self.a_of[c]] = True
|
||||
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=len(self.numbers),
|
||||
episode=EpisodeState(), available_mask=mask)
|
||||
return self.numbers[self.pol.select(ctx).action_id]
|
||||
|
||||
def learn(self, snap, tf, card, reward, next_snap, next_avail, done):
|
||||
idx = state_index(snap, self.state_cfg)
|
||||
nidx = state_index(next_snap, self.state_cfg) if (next_snap is not None and not done) else None
|
||||
self.pol.update(Transition(state_index=idx, action_id=self.a_of[card], reward=reward,
|
||||
next_state_index=nidx, done=done))
|
||||
|
||||
|
||||
class RandomAdapter:
|
||||
name = "random"
|
||||
|
||||
def __init__(self, seed=0):
|
||||
self.rng = np.random.default_rng(seed)
|
||||
|
||||
def choose(self, snap, tf, avail, greedy):
|
||||
return avail[self.rng.integers(len(avail))]
|
||||
|
||||
def learn(self, *a, **k):
|
||||
pass
|
||||
|
||||
|
||||
# ---- 공용 에피소드 -----------------------------------------------------------------
|
||||
def run_episode(adapter, sup, tf, pool, strat, rc, seed, learn=True, greedy=False, forced_first=None):
|
||||
buyer = FeatureBuyer(sup, strat, seed=seed, max_turns=MAX_TURNS)
|
||||
scenario = Scenario(anchor_price=ANCHOR, target_price=TARGET, revenue_amount=sup.revenue_amount,
|
||||
distribution_code=sup.distribution_code, partner_count=sup.partner_count)
|
||||
price0 = TARGET * 1.15
|
||||
price, used, total_r, first_card = price0, set(), 0.0, None
|
||||
|
||||
for turn in range(1, MAX_TURNS + 1):
|
||||
acceptance = max(0.0, (price0 - price) / price0)
|
||||
snap = make_snapshot(sup, price, turn, acceptance)
|
||||
avail = [c for c in pool if c not in used] or list(pool)
|
||||
if turn == 1 and forced_first is not None:
|
||||
card = forced_first
|
||||
else:
|
||||
card = adapter.choose(snap, tf, avail, greedy)
|
||||
used.add(card)
|
||||
if first_card is None:
|
||||
first_card = card
|
||||
|
||||
resp = buyer.respond(card, scenario, turn, price)
|
||||
price = resp.new_price
|
||||
done = resp.accept or price <= ANCHOR or turn >= MAX_TURNS
|
||||
success = resp.accept or price <= ANCHOR
|
||||
outcome = (NegotiationOutcome.SUCCESS if success
|
||||
else NegotiationOutcome.FAILURE if done else NegotiationOutcome.ONGOING)
|
||||
# 채점은 최종 결과 시점만 (중간 턴 0 → γ 부트스트랩으로 전파).
|
||||
# 진행 중 보상을 누적하면 '질질 끄는 전략'이 부당하게 유리해지는 인공물이 생긴다.
|
||||
r = rc.calculate(make_snapshot(sup, price, turn, acceptance, outcome)).total if done else 0.0
|
||||
total_r += r
|
||||
|
||||
if learn:
|
||||
if done:
|
||||
adapter.learn(snap, tf, card, r, None, None, True)
|
||||
else:
|
||||
acc2 = max(0.0, (price0 - price) / price0)
|
||||
nsnap = make_snapshot(sup, price, turn + 1, acc2)
|
||||
navail = [c for c in pool if c not in used] or list(pool)
|
||||
adapter.learn(snap, tf, card, r, nsnap, navail, False)
|
||||
if done:
|
||||
return total_r, success, price, first_card
|
||||
return total_r, False, price, first_card
|
||||
|
||||
|
||||
# ---- MC 정답 랭킹: 이 (협력사, 성향)에서 진짜 좋은 첫 카드 top-k ---------------------
|
||||
_rand = RandomAdapter(seed=1)
|
||||
|
||||
def rank_cards_mc(sup, tf, pool, strat, rc, seed, sims=6, k=3):
|
||||
means = {}
|
||||
for c in pool:
|
||||
rs = [run_episode(_rand, sup, tf, pool, strat, rc, seed=seed + 17 * s,
|
||||
learn=False, greedy=False, forced_first=c)[0] for s in range(sims)]
|
||||
means[c] = np.mean(rs)
|
||||
return sorted(means, key=lambda c: -means[c])[:k]
|
||||
|
||||
|
||||
# ---- 학습/평가 ---------------------------------------------------------------------
|
||||
def train(adapter, pool, strat, base_reward, state_cfg, episodes, seed):
|
||||
rng = np.random.default_rng(seed)
|
||||
for ep in range(1, episodes + 1):
|
||||
sup = sample_supplier(rng)
|
||||
rcfg, tf = sample_tenant_pref(rng, base_reward)
|
||||
rc = RewardCalculator(rcfg, state_cfg)
|
||||
run_episode(adapter, sup, tf, pool, strat, rc, seed=seed * 100 + ep, learn=True)
|
||||
|
||||
|
||||
def evaluate(adapter, pool, strat, base_reward, state_cfg, n=300, seed0=777, label=""):
|
||||
from negotiation.qtable.domain.service.feature_builder import build_tenant_features
|
||||
rng = np.random.default_rng(seed0)
|
||||
rewards, succ, ratios, hits, holdout_first = [], 0, [], 0, 0
|
||||
for i in range(n):
|
||||
sup = sample_supplier(rng)
|
||||
rcfg, tf = sample_tenant_pref(rng, base_reward)
|
||||
rc = RewardCalculator(rcfg, state_cfg)
|
||||
good = rank_cards_mc(sup, tf, pool, strat, rc, seed=seed0 * 7 + i)
|
||||
r, ok, price, first = run_episode(adapter, sup, tf, pool, strat, rc,
|
||||
seed=seed0 * 1000 + i, learn=False, greedy=True)
|
||||
rewards.append(r); succ += ok; ratios.append(price / TARGET)
|
||||
hits += (first in good); holdout_first += (first in HOLDOUT)
|
||||
m, ci = float(np.mean(rewards)), float(1.96 * np.std(rewards) / np.sqrt(n))
|
||||
print(f"{label:<14} mean_rwd={m:.4f} ±{ci:.4f} success={succ/n:.3f} "
|
||||
f"settled/tgt={np.mean(ratios):.3f} top3_hit={hits/n:.3f} 새카드첫턴={holdout_first/n:.3f}")
|
||||
|
||||
|
||||
def pref_behavior_test(adapters, pool, strat, base_reward, state_cfg):
|
||||
"""④ 같은 협력사, 성향만 바꿨을 때 카드를 바꾸는가 (greedy).
|
||||
|
||||
첫 턴은 '일단 깎기'가 공통 정답이라 성향 차이가 잘 안 드러난다.
|
||||
→ 협상 중반(가격이 이미 target 근처, 3턴째) 상태를 함께 프로브: 여기서
|
||||
성사중시는 '마무리(수락 잘 되는) 카드', 가격중시는 '더 깎는 카드'가 갈려야 한다.
|
||||
"""
|
||||
from negotiation.qtable.domain.service.feature_builder import build_tenant_features
|
||||
sups = [SupplierProfile(5_000_000, 3, "A"), # 소형·경쟁多
|
||||
SupplierProfile(200_000_000, 1, "A")] # 대형·단독
|
||||
probes = [("첫턴", TARGET * 1.15, 1, 0.0),
|
||||
("중반(3턴,가격↓)", TARGET * 1.02, 3, 0.11)]
|
||||
for pr_name, price, turn, acc in probes:
|
||||
print(f"\n ── 프로브: {pr_name} (price={price:.0f}) ──")
|
||||
print(f" {'협력사':<13} {'성향':<9} " + " ".join(f"{a.name:<15}" for a in adapters))
|
||||
for sup in sups:
|
||||
row = {}
|
||||
for p, pname in [(0.05, "성사중시"), (0.95, "가격중시")]:
|
||||
rcfg = pref_config(base_reward, p)
|
||||
tf = build_tenant_features(rcfg)
|
||||
picks = []
|
||||
for a in adapters:
|
||||
snap = make_snapshot(sup, price, turn, acc)
|
||||
picks.append(a.choose(snap, tf, pool, True))
|
||||
seg = f"{sup.segment[0]}·{sup.segment[1]}"
|
||||
print(f" {seg:<13} {pname:<9} " + " ".join(f"{c}(전략{strat[c]})".ljust(15) for c in picks))
|
||||
|
||||
|
||||
def main(episodes=10000, seed=42):
|
||||
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
|
||||
numbers, feat, strat = load_cards()
|
||||
train_pool = [c for c in numbers if c not in HOLDOUT]
|
||||
tcfg = TenantConfigLoader().load("ktcommerce")
|
||||
card_dim = feat[numbers[0]].shape[0]
|
||||
print(f"환경: 2축 FeatureBuyer + 성향 랜덤 · 학습 {episodes}ep · 카드특징 {card_dim}차원 "
|
||||
f"(임베딩384+전략4+톤4) · 학습 {len(train_pool)}장 / 홀드아웃 {HOLDOUT}")
|
||||
|
||||
qt = QTableAdapter(numbers, tcfg.state)
|
||||
dqn = DQNAdapter(FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM,
|
||||
card_dim=card_dim, eps_decay=4000), feat)
|
||||
|
||||
print("\n[학습] qtable_ucb ...")
|
||||
train(qt, train_pool, strat, tcfg.reward, tcfg.state, episodes, seed)
|
||||
print("[학습] feature_dqn ...")
|
||||
train(dqn, train_pool, strat, tcfg.reward, tcfg.state, episodes, seed)
|
||||
|
||||
print("\n=== ① 학습 카드 9장 풀 ===")
|
||||
evaluate(RandomAdapter(seed), train_pool, strat, tcfg.reward, tcfg.state, label="random")
|
||||
evaluate(qt, train_pool, strat, tcfg.reward, tcfg.state, label="qtable_ucb")
|
||||
evaluate(dqn, train_pool, strat, tcfg.reward, tcfg.state, label="feature_dqn")
|
||||
|
||||
print("\n=== ② zero-shot 11장 풀 (안 본 카드 2장 포함) ===")
|
||||
evaluate(RandomAdapter(seed), numbers, strat, tcfg.reward, tcfg.state, label="random")
|
||||
evaluate(qt, numbers, strat, tcfg.reward, tcfg.state, label="qtable_ucb")
|
||||
evaluate(dqn, numbers, strat, tcfg.reward, tcfg.state, label="feature_dqn")
|
||||
|
||||
print("\n=== ④ 성향 극단 테스트 — 같은 협력사, 성향만 바꾸면 카드를 바꾸는가 (11장 풀) ===")
|
||||
pref_behavior_test([qt, dqn], numbers, strat, tcfg.reward, tcfg.state)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,42 +0,0 @@
|
||||
"""full_autonomy 체크포인트(.pt) → 서빙 번들(autonomy_serving.npz) export.
|
||||
|
||||
dqn_serving 과 동일 패턴: ScoreNet 가중치만 numpy 로 묶어 PyTorch 없이 서빙한다.
|
||||
행동 특징은 코드(autonomy_actions)가 런타임 생성하므로 번들에는 가중치만 담는다.
|
||||
|
||||
실행(호스트, torch 필요): APP_ENV=local python -m tools.export_autonomy_serving
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from negotiation.policies.autonomy_actions import ACTION_DIM, EXTRA_STATE_DIM
|
||||
from negotiation.qtable.domain.service.feature_builder import STATE_FEATURE_DIM, TENANT_FEATURE_DIM
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "full_autonomy.pt")
|
||||
OUT_PATH = os.path.join(_HERE, "..", "artifacts", "autonomy_serving.npz")
|
||||
|
||||
STATE_DIM = STATE_FEATURE_DIM + TENANT_FEATURE_DIM + EXTRA_STATE_DIM
|
||||
|
||||
|
||||
def main():
|
||||
sd = torch.load(CKPT_PATH, map_location="cpu")
|
||||
W0, b0 = sd["net.0.weight"].numpy(), sd["net.0.bias"].numpy()
|
||||
W1, b1 = sd["net.2.weight"].numpy(), sd["net.2.bias"].numpy()
|
||||
W2, b2 = sd["net.4.weight"].numpy(), sd["net.4.bias"].numpy()
|
||||
assert W0.shape[1] == STATE_DIM + ACTION_DIM, f"입력 차원 불일치: {W0.shape[1]}"
|
||||
|
||||
tmp = OUT_PATH + ".tmp"
|
||||
with open(tmp, "wb") as f:
|
||||
np.savez(f, W0=W0, b0=b0, W1=W1, b1=b1, W2=W2, b2=b2,
|
||||
state_dim=STATE_DIM, action_dim=ACTION_DIM)
|
||||
if os.path.exists(OUT_PATH):
|
||||
os.replace(OUT_PATH, OUT_PATH + ".prev")
|
||||
os.replace(tmp, OUT_PATH)
|
||||
print(f"[저장] {os.path.abspath(OUT_PATH)} (state {STATE_DIM} + action {ACTION_DIM})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,79 +0,0 @@
|
||||
"""feature_dqn 체크포인트(.pt) → 서빙 번들(dqn_serving.npz) export.
|
||||
|
||||
서빙 컨테이너에 PyTorch 를 넣지 않기 위해 ScoreNet(3층 MLP) 가중치와 카드 특징
|
||||
(임베딩384 + 전략 one-hot4 + 톤 one-hot4 = 392)을 numpy 번들 하나로 묶는다.
|
||||
추론은 negotiation.policy.dqn_store 의 numpy forward 가 수행한다.
|
||||
|
||||
실행(호스트, torch 필요): APP_ENV=local python -m tools.export_dqn_serving
|
||||
산출: agent/artifacts/dqn_serving.npz (.dockerignore 미제외 → 이미지에 포함)
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from tools.train_feature_dqn import load_cards
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "feature_dqn_ktcommerce.pt")
|
||||
OUT_PATH = os.path.join(_HERE, "..", "artifacts", "dqn_serving.npz")
|
||||
|
||||
STATE_DIM = 14 # build_state_features(9) + build_tenant_features(5)
|
||||
CARD_DIM = 392
|
||||
|
||||
|
||||
def _np_forward(x, W0, b0, W1, b1, W2, b2):
|
||||
h = np.maximum(x @ W0.T + b0, 0.0)
|
||||
h = np.maximum(h @ W1.T + b1, 0.0)
|
||||
return h @ W2.T + b2
|
||||
|
||||
|
||||
def export_bundle(sd, out_path: str) -> str:
|
||||
"""state_dict → 서빙 번들 npz (원자적 교체: .tmp 작성 후 replace). 반환: 절대경로.
|
||||
|
||||
retrain_from_logs 재학습 배포도 이 함수를 쓴다 — 검증(torch/numpy 일치)은 main() 전용.
|
||||
"""
|
||||
W0, b0 = sd["net.0.weight"].numpy(), sd["net.0.bias"].numpy()
|
||||
W1, b1 = sd["net.2.weight"].numpy(), sd["net.2.bias"].numpy()
|
||||
W2, b2 = sd["net.4.weight"].numpy(), sd["net.4.bias"].numpy()
|
||||
assert W0.shape[1] == STATE_DIM + CARD_DIM, f"입력 차원 불일치: {W0.shape[1]}"
|
||||
numbers, feat, _ = load_cards()
|
||||
card_feats = np.stack([feat[n] for n in numbers]).astype(np.float32)
|
||||
tmp = out_path + ".tmp"
|
||||
with open(tmp, "wb") as f:
|
||||
np.savez(
|
||||
f,
|
||||
W0=W0, b0=b0, W1=W1, b1=b1, W2=W2, b2=b2,
|
||||
card_numbers=np.array(numbers), card_feats=card_feats,
|
||||
state_dim=STATE_DIM, card_dim=CARD_DIM,
|
||||
)
|
||||
if os.path.exists(out_path):
|
||||
os.replace(out_path, out_path + ".prev") # 직전 번들 백업(롤백용)
|
||||
os.replace(tmp, out_path)
|
||||
return os.path.abspath(out_path)
|
||||
|
||||
|
||||
def main():
|
||||
sd = torch.load(CKPT_PATH, map_location="cpu")
|
||||
# 정합성 검증: torch forward == numpy forward
|
||||
from negotiation.policies.feature_dqn_policy import ScoreNet
|
||||
net = ScoreNet(STATE_DIM, CARD_DIM)
|
||||
net.load_state_dict(sd)
|
||||
net.eval()
|
||||
x = np.random.default_rng(0).normal(size=(8, STATE_DIM + CARD_DIM)).astype(np.float32)
|
||||
with torch.no_grad():
|
||||
ref = net(torch.tensor(x)).numpy()
|
||||
W0, b0 = sd["net.0.weight"].numpy(), sd["net.0.bias"].numpy()
|
||||
W1, b1 = sd["net.2.weight"].numpy(), sd["net.2.bias"].numpy()
|
||||
W2, b2 = sd["net.4.weight"].numpy(), sd["net.4.bias"].numpy()
|
||||
out = _np_forward(x, W0, b0, W1, b1, W2, b2).squeeze(-1)
|
||||
diff = float(np.abs(ref - out).max())
|
||||
assert diff < 1e-4, f"numpy/torch forward 불일치: {diff}"
|
||||
|
||||
path = export_bundle(sd, OUT_PATH)
|
||||
print(f"[저장] {path} forward 오차 {diff:.2e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,61 +0,0 @@
|
||||
"""probe_serving_dqn — 서빙 번들(dqn_serving.npz)의 상황별 카드 선택 프로브.
|
||||
|
||||
배포된 모델이 '상황에 맞게' 고르는지 눈으로 확인하는 진단 도구:
|
||||
협력사 세그먼트 × 고객사 성향 × 협상 국면(가격대)별 선택 카드를 표로 출력한다.
|
||||
전부 다르길 기대하는 게 아니라, 축을 바꿨을 때 선택이 '움직이는지'를 본다.
|
||||
|
||||
실행: APP_ENV=local python -m tools.probe_serving_dqn (numpy 만 필요, DB 불필요)
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||
from negotiation.qtable.domain.service.feature_builder import build_state_features, build_tenant_features
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tools.export_dqn_serving import OUT_PATH
|
||||
from tools.retrain_from_logs import np_scorer_from_bundle
|
||||
from tools.train_feature_dqn import pref_config
|
||||
|
||||
ANCHOR, TARGET = 495_000.0, 500_000.0 # BUGCHECK 견적과 동일 스케일
|
||||
|
||||
SUPPLIERS = {
|
||||
"소형·경쟁多": dict(revenue_amount=5_000_000, partner_count=3, distribution_code="A"),
|
||||
"소형·단독": dict(revenue_amount=5_000_000, partner_count=1, distribution_code="A"),
|
||||
"대형·경쟁多": dict(revenue_amount=200_000_000, partner_count=3, distribution_code="A"),
|
||||
"대형·단독": dict(revenue_amount=200_000_000, partner_count=1, distribution_code="A"),
|
||||
}
|
||||
PHASES = { # (라운드, 제시가): 첫턴 높은 가격 / 중반 목표가 근접 / 막판 앵커존 직전
|
||||
"첫턴(575k)": (1, 575_000.0),
|
||||
"중반(510k)": (2, 510_000.0),
|
||||
"막판(501k)": (3, 501_000.0),
|
||||
}
|
||||
PREFS = {"성사중시": 0.1, "가격중시": 0.9}
|
||||
|
||||
|
||||
def main():
|
||||
score = np_scorer_from_bundle(OUT_PATH)
|
||||
z = np.load(OUT_PATH, allow_pickle=False)
|
||||
numbers = [str(n) for n in z["card_numbers"]]
|
||||
feats = z["card_feats"]
|
||||
base = TenantConfigLoader().load("ktcommerce").reward
|
||||
|
||||
for phase, (turn, price) in PHASES.items():
|
||||
print(f"\n=== {phase} (앵커 {int(ANCHOR):,} / 목표 {int(TARGET):,}) ===")
|
||||
print(f"{'협력사':<12}" + "".join(f"{p:>16}" for p in PREFS))
|
||||
for sup_name, sup in SUPPLIERS.items():
|
||||
row = []
|
||||
for _, p in PREFS.items():
|
||||
tf = build_tenant_features(pref_config(base, p))
|
||||
snap = NegotiationSnapshot(
|
||||
revenue_amount=sup["revenue_amount"], distribution_code=sup["distribution_code"],
|
||||
partner_count=sup["partner_count"],
|
||||
acceptance_ratio=max(0.0, (575_000.0 - price) / 575_000.0),
|
||||
input_price=price, anchor_price=ANCHOR, target_price=TARGET, round_number=turn,
|
||||
)
|
||||
sf = np.concatenate([build_state_features(snap), tf])
|
||||
row.append(numbers[int(np.argmax(score(sf, feats)))])
|
||||
print(f"{sup_name:<12}" + "".join(f"{c:>16}" for c in row))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,238 +0,0 @@
|
||||
"""retrain_from_logs — experience_logs 실데이터로 feature_dqn 오프라인 재학습 + OPE 게이트.
|
||||
|
||||
파이프라인:
|
||||
① learning.experience_logs 로드(전 테넌트 — 범용 에이전트는 테넌트를 특징으로 조건화하므로 통합 학습)
|
||||
② 세션별 에피소드 재구성: 카드턴(done=False) N개 + 종료행(done=True) 1개.
|
||||
보상은 학습 규약(최종 결과 시점만 채점)에 맞춰 종료행 reward 만 쓰고 중간턴은 0.
|
||||
③ 현재 체크포인트에서 fine-tune (낮은 lr — 시뮬 사전학습 망각 방지)
|
||||
④ OPE(SNIPS, 궤적 IS): 후보 모델 vs 현재 서빙 번들. 후보가 못 넘으면 배포하지 않는다.
|
||||
⑤ 통과 시 dqn_serving.npz 원자적 교체(직전본 .prev 백업) → `docker compose build agent && up -d agent` 로 배포.
|
||||
|
||||
실행(호스트, torch+DB 필요):
|
||||
APP_ENV=local python -m tools.retrain_from_logs
|
||||
환경변수:
|
||||
MIN_EPISODES(기본 200) 재학습 최소 에피소드 수 — 미달 시 skip (과적합 방지)
|
||||
EPOCHS(기본 20) / LR(기본 1e-4) / FORCE_DEPLOY=1 (OPE 게이트 무시 — 테스트 전용)
|
||||
|
||||
주의: 서빙이 greedy(탐색 없음)라 로그가 선택 편향됨 — OPE 의 유효표본(ESS)이 작으면
|
||||
게이트가 보수적으로 배포를 막는다. 이는 의도된 동작이다(조용한 성능저하 방지).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from collections import defaultdict
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import ExperienceLog
|
||||
from common.enums import DBType, DBWRType
|
||||
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||
from negotiation.qtable.domain.service.feature_builder import (
|
||||
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features, build_tenant_features)
|
||||
from sqlalchemy import select
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tools.export_dqn_serving import CKPT_PATH, OUT_PATH, export_bundle
|
||||
from tools.train_feature_dqn import load_cards
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
RETRAIN_CKPT = os.path.join(_HERE, "..", "artifacts", "feature_dqn_retrained.pt")
|
||||
REPORT_PATH = os.path.join(_HERE, "..", "artifacts", "retrain_report.json")
|
||||
|
||||
MIN_EPISODES = int(os.getenv("MIN_EPISODES", "200"))
|
||||
EPOCHS = int(os.getenv("EPOCHS", "20"))
|
||||
LR = float(os.getenv("LR", "1e-4"))
|
||||
FORCE_DEPLOY = os.getenv("FORCE_DEPLOY") == "1"
|
||||
PROPENSITY_FALLBACK = 0.9 # 구로그 propensity 누락 시 (UCB/DQN 모두 greedy≈(1-ε)+ε/n)
|
||||
|
||||
|
||||
# ---- ① 로그 로드 -------------------------------------------------------------
|
||||
async def fetch_logs():
|
||||
def _q(s):
|
||||
q = (select(ExperienceLog.company_id, ExperienceLog.session_id, ExperienceLog.card_id,
|
||||
ExperienceLog.reward, ExperienceLog.done, ExperienceLog.snapshot,
|
||||
ExperienceLog.propensity, ExperienceLog.turn, ExperienceLog.id)
|
||||
.where(ExperienceLog.is_invalidated == False) # noqa: E712
|
||||
.order_by(ExperienceLog.company_id, ExperienceLog.session_id, ExperienceLog.id))
|
||||
return DB_SESSION_MNG.execute(s, q)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return rows
|
||||
|
||||
|
||||
# ---- ② 에피소드 재구성 --------------------------------------------------------
|
||||
def build_episodes(rows, known_cards: set):
|
||||
"""→ [{tenant, steps:[(snapshot, card, propensity)], terminal_reward}], 스킵 사유 카운트."""
|
||||
by_session = defaultdict(list)
|
||||
for r in rows:
|
||||
if r[1] is not None:
|
||||
by_session[(r[0], str(r[1]))].append(r)
|
||||
|
||||
episodes, skipped = [], defaultdict(int)
|
||||
for (company_id, _sid), items in by_session.items():
|
||||
selects = [r for r in items if not r[4] and r[5]] # done=False, snapshot 有
|
||||
terminals = [r for r in items if r[4] and r[3] is not None] # done=True, reward 有
|
||||
if not selects or not terminals:
|
||||
skipped["종료행/카드턴 없음(미완결 세션)"] += 1
|
||||
continue
|
||||
if any(str(r[2] or "").startswith("AUT|") for r in selects):
|
||||
skipped["완전 자율 세션(카드 재학습 대상 아님)"] += 1
|
||||
continue
|
||||
if any(r[2] not in known_cards for r in selects):
|
||||
skipped["임베딩 없는 카드(파일매핑 테넌트 등)"] += 1
|
||||
continue
|
||||
episodes.append(dict(
|
||||
tenant=company_id,
|
||||
steps=[(r[5], r[2], r[6] if r[6] else PROPENSITY_FALLBACK) for r in selects],
|
||||
terminal_reward=float(terminals[-1][3]),
|
||||
))
|
||||
return episodes, skipped
|
||||
|
||||
|
||||
def tenant_feat_for(cache: dict, loader: TenantConfigLoader, company_id: str) -> np.ndarray:
|
||||
"""테넌트 보상설정 → 성향 특징. 미온보딩/로드 실패는 _base 폴백."""
|
||||
if company_id not in cache:
|
||||
try:
|
||||
cfg = loader.load(company_id)
|
||||
except Exception:
|
||||
cfg = loader.load("_base")
|
||||
cache[company_id] = build_tenant_features(cfg.reward)
|
||||
return cache[company_id]
|
||||
|
||||
|
||||
def to_transitions(episodes, feat, tenant_feats):
|
||||
"""학습 규약(train_feature_dqn 과 동일): 중간턴 r=0, 종료턴만 terminal_reward. 다음 후보 = 전체 − 사용분."""
|
||||
all_cards = list(feat.keys())
|
||||
out = []
|
||||
for ep in episodes:
|
||||
tf = tenant_feats[ep["tenant"]]
|
||||
used = set()
|
||||
n = len(ep["steps"])
|
||||
for i, (snap_d, card, _p) in enumerate(ep["steps"]):
|
||||
sf = np.concatenate([build_state_features(NegotiationSnapshot.from_dict(snap_d)), tf])
|
||||
used.add(card)
|
||||
if i == n - 1:
|
||||
out.append((sf, feat[card], ep["terminal_reward"], None, None, True))
|
||||
else:
|
||||
s2_d = ep["steps"][i + 1][0]
|
||||
s2 = np.concatenate([build_state_features(NegotiationSnapshot.from_dict(s2_d)), tf])
|
||||
cands = [c for c in all_cards if c not in used] or all_cards
|
||||
out.append((sf, feat[card], 0.0, s2, np.stack([feat[c] for c in cands]), False))
|
||||
return out
|
||||
|
||||
|
||||
# ---- ④ OPE (SNIPS, 궤적 단위 IS) ----------------------------------------------
|
||||
def _greedy_match(score_fn, ep, feat, tf) -> float:
|
||||
"""궤적 IS 가중치: Π 1[greedy(sᵢ)=aᵢ]/pᵢ. 한 턴이라도 불일치면 0."""
|
||||
all_cards = list(feat.keys())
|
||||
w, used = 1.0, set()
|
||||
for snap_d, card, p in ep["steps"]:
|
||||
sf = np.concatenate([build_state_features(NegotiationSnapshot.from_dict(snap_d)), tf])
|
||||
cands = [c for c in all_cards if c not in used] or all_cards
|
||||
sc = score_fn(sf, np.stack([feat[c] for c in cands]))
|
||||
if cands[int(np.argmax(sc))] != card:
|
||||
return 0.0
|
||||
w /= max(p, 1e-3)
|
||||
used.add(card)
|
||||
return w
|
||||
|
||||
|
||||
def snips(score_fn, episodes, feat, tenant_feats):
|
||||
"""SNIPS 추정치 + 유효표본크기(ESS). 매치 0건이면 (None, 0)."""
|
||||
ws, rs = [], []
|
||||
for ep in episodes:
|
||||
w = _greedy_match(score_fn, ep, feat, tenant_feats[ep["tenant"]])
|
||||
ws.append(w)
|
||||
rs.append(ep["terminal_reward"])
|
||||
ws, rs = np.array(ws), np.array(rs)
|
||||
if ws.sum() <= 0:
|
||||
return None, 0.0
|
||||
est = float((ws * rs).sum() / ws.sum())
|
||||
ess = float(ws.sum() ** 2 / (ws ** 2).sum())
|
||||
return est, ess
|
||||
|
||||
|
||||
def np_scorer_from_bundle(path):
|
||||
"""현재 서빙 번들(npz) → score_fn (dqn_store 와 동일 forward)."""
|
||||
z = np.load(path, allow_pickle=False)
|
||||
W0, b0, W1, b1, W2, b2 = z["W0"], z["b0"], z["W1"], z["b1"], z["W2"], z["b2"]
|
||||
|
||||
def score(sf, card_feats):
|
||||
x = np.concatenate([np.repeat(sf[None, :], card_feats.shape[0], axis=0), card_feats], axis=1)
|
||||
h = np.maximum(x @ W0.T + b0, 0.0)
|
||||
h = np.maximum(h @ W1.T + b1, 0.0)
|
||||
return (h @ W2.T + b2).squeeze(-1)
|
||||
return score
|
||||
|
||||
|
||||
# ---- 메인 ---------------------------------------------------------------------
|
||||
async def run():
|
||||
numbers, feat, _ = load_cards()
|
||||
rows = await fetch_logs()
|
||||
episodes, skipped = build_episodes(rows, set(numbers))
|
||||
print(f"로그 {len(rows)}행 → 에피소드 {len(episodes)}개 (스킵: {dict(skipped) or '없음'})")
|
||||
|
||||
report = dict(rows=len(rows), episodes=len(episodes), skipped=dict(skipped),
|
||||
min_episodes=MIN_EPISODES, deployed=False)
|
||||
if len(episodes) < MIN_EPISODES and not FORCE_DEPLOY:
|
||||
print(f"[skip] 에피소드 {len(episodes)} < MIN_EPISODES {MIN_EPISODES} — 과적합 위험으로 재학습 안 함")
|
||||
report["result"] = "skipped_insufficient_data"
|
||||
return report
|
||||
|
||||
loader = TenantConfigLoader()
|
||||
tenant_feats = {}
|
||||
for ep in episodes:
|
||||
tenant_feat_for(tenant_feats, loader, ep["tenant"])
|
||||
|
||||
# ③ fine-tune (시뮬 사전학습 체크포인트에서 이어서, 낮은 lr)
|
||||
transitions = to_transitions(episodes, feat, tenant_feats)
|
||||
batch = min(64, max(8, len(transitions) // 4))
|
||||
policy = FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM,
|
||||
card_dim=feat[numbers[0]].shape[0], lr=LR, batch_size=batch)
|
||||
if os.path.exists(CKPT_PATH):
|
||||
policy.load(CKPT_PATH)
|
||||
print(f"[fine-tune] 시작점: {os.path.basename(CKPT_PATH)} lr={LR} batch={batch}")
|
||||
policy.buf.extend(transitions)
|
||||
steps = EPOCHS * max(1, len(transitions) // batch)
|
||||
losses = [l for _ in range(steps) if (l := policy.train_step()) is not None]
|
||||
print(f"[fine-tune] {steps} step loss {losses[0]:.4f} → {losses[-1]:.4f}" if losses else "[fine-tune] 스텝 없음")
|
||||
|
||||
# ④ OPE 게이트: 후보 vs 현재 서빙
|
||||
def cand_score(sf, cf):
|
||||
return policy.scores(sf, cf)
|
||||
cand_est, cand_ess = snips(cand_score, episodes, feat, tenant_feats)
|
||||
cur_est, cur_ess = (snips(np_scorer_from_bundle(OUT_PATH), episodes, feat, tenant_feats)
|
||||
if os.path.exists(OUT_PATH) else (None, 0.0))
|
||||
print(f"[OPE/SNIPS] 후보 {cand_est} (ESS {cand_ess:.1f}) vs 현재 {cur_est} (ESS {cur_ess:.1f})")
|
||||
report.update(ope_candidate=cand_est, ope_candidate_ess=cand_ess,
|
||||
ope_current=cur_est, ope_current_ess=cur_ess)
|
||||
|
||||
min_ess = max(3.0, 0.02 * len(episodes))
|
||||
passed = (cand_est is not None and cand_ess >= min_ess
|
||||
and (cur_est is None or cand_est >= cur_est - 0.01))
|
||||
if not passed and not FORCE_DEPLOY:
|
||||
print(f"[게이트 불통과] 배포하지 않음 (필요 ESS ≥ {min_ess:.1f}). 현재 번들 유지.")
|
||||
report["result"] = "gate_failed"
|
||||
return report
|
||||
|
||||
# ⑤ 배포: 후보 저장 + 번들 교체 (.prev 백업)
|
||||
policy.save(RETRAIN_CKPT)
|
||||
path = export_bundle(policy.q.state_dict(), OUT_PATH)
|
||||
print(f"[배포] {path} (직전본 → dqn_serving.npz.prev)")
|
||||
print(" 적용: docker compose build agent && docker compose up -d agent")
|
||||
report.update(result="deployed" if passed else "force_deployed", deployed=True,
|
||||
ckpt=os.path.abspath(RETRAIN_CKPT))
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
report = asyncio.run(run())
|
||||
with open(REPORT_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump(report, f, ensure_ascii=False, indent=2)
|
||||
print(f"[리포트] {os.path.abspath(REPORT_PATH)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,317 +0,0 @@
|
||||
"""결함 회귀 게이트 — 실전에서 발견된 협상 결함을 시나리오로 재생해 서빙 번들을 검증한다.
|
||||
|
||||
프로브(probe_serving_dqn)가 '눈으로 보는 행동 표'라면 이것은 '자동 합격/불합격'이다.
|
||||
모든 검사 항목은 과거 실제 발생했던 결함이며, 하나라도 실패하면 exit 1 — 배포 금지.
|
||||
재학습 번들은 반드시 이 게이트를 통과한 뒤에만 autonomy_serving.npz 로 교체한다.
|
||||
|
||||
검사 대상은 서빙 실물이다: AutonomyPolicy.decide(봉투 마스크 포함) + ChatEngine._autonomy_next
|
||||
(최종제안 전환) + ment_generator 가드(목표가 누설·할루시네이션). 시뮬 협력사는 스크립트라
|
||||
결정론적이고, 정책도 greedy 라 실행마다 같은 결과가 나온다. DB/LLM/도커 불필요.
|
||||
|
||||
지형은 복수로 검사한다 — v3.4 가 실스케일(423,198)에선 통과하고 드라이브 지형(10,000)에서
|
||||
'첫 턴 목표가 통보'로 퇴화했던 사고: 한 지형 통과는 다른 지형을 보증하지 않는다.
|
||||
|
||||
실행: agent 디렉터리에서 APP_ENV=local python -m tools.test_autonomy_defects [번들경로]
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
from negotiation.chat.service import ment_generator
|
||||
from negotiation.chat.service.chat_engine import ChatEngine
|
||||
from negotiation.policy import autonomy_store
|
||||
from negotiation.policy.autonomy_store import AutonomyPolicy
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
|
||||
# 검사 지형: 실제 견적(앵커율 ~1%) + 로컬 드라이브 견적(소액) — 스케일이 달라도 예절은 같아야 한다.
|
||||
GEOS = {
|
||||
"실스케일": dict(anchor=418_966, target=423_198, first=540_000, il=459_000),
|
||||
"소액": dict(anchor=9_900, target=10_000, first=11_500, il=0),
|
||||
}
|
||||
MIN_PRESS = int(os.getenv("AUTONOMY_MIN_PRESS", "2"))
|
||||
|
||||
_RESULTS = []
|
||||
|
||||
|
||||
def check(name: str, ok: bool, detail: str = ""):
|
||||
_RESULTS.append((name, ok, detail))
|
||||
print(f" {'✔' if ok else '✘ FAIL'} {name}" + (f" — {detail}" if detail and not ok else ""))
|
||||
|
||||
|
||||
# ---- 하니스: 서빙 실물 구동 (chat_service 의 ctx 관리 순서를 그대로 재현) ----------------
|
||||
def base_ctx(geo) -> dict:
|
||||
return dict(revenue_amount=50_000_000, distribution_code="A", partner_count=3,
|
||||
item_price=geo["first"], input_price=geo["first"], round=1,
|
||||
anchor_price=geo["anchor"], target_price=geo["target"],
|
||||
internet_lowest_price=geo["il"])
|
||||
|
||||
|
||||
def run_scenario(policy, supplier, geo, max_steps=30):
|
||||
"""정책 결정 → 스텝 전환 → 컨텍스트 부기(chat_service 순서) → 스크립트 협력사 반응 루프.
|
||||
|
||||
trace 원소: (step, kind, q, 당시 제시가, autonomy_offer, 결정 시점 press_n)
|
||||
"""
|
||||
eng = ChatEngine.__new__(ChatEngine) # _autonomy_next 는 decider 와 ctx 만 쓴다
|
||||
ctx = base_ctx(geo)
|
||||
|
||||
def decide(c):
|
||||
act = policy.decide(c)
|
||||
c["autonomy_pending"] = {"kind": act.kind, "q": act.counter_q, "s": act.strategy}
|
||||
return act
|
||||
|
||||
eng.autonomy_decider = decide
|
||||
sess = SimpleNamespace(context=ctx)
|
||||
trace, end = [], None
|
||||
for _ in range(max_steps):
|
||||
press_n_at = int(ctx.get("autonomy_press_n") or 0)
|
||||
step = eng._autonomy_next(sess)
|
||||
pending = ctx.pop("autonomy_pending", None)
|
||||
if pending: # chat_service 부기: pending → last(+prev), 역제안 별도 보존, press 카운터
|
||||
if ctx.get("autonomy_last"):
|
||||
ctx["autonomy_prev"] = ctx["autonomy_last"]
|
||||
ctx["autonomy_last"] = dict(pending)
|
||||
if pending["kind"] == "counter":
|
||||
ctx["autonomy_last_counter"] = dict(pending)
|
||||
if pending["kind"] == "press":
|
||||
ctx["autonomy_press_n"] = press_n_at + 1
|
||||
trace.append((step, (pending or {}).get("kind"), (pending or {}).get("q"),
|
||||
ctx["input_price"], ctx.get("autonomy_offer"), press_n_at))
|
||||
if step in ("협상완료", "협상실패"):
|
||||
end = step
|
||||
break
|
||||
if step == "자율_최종제안": # 예→그 금액 타결 / 아니오→협상실패 (엔진 스텝 정의)
|
||||
end = "협상완료" if supplier.final_yes(ctx) else "협상실패"
|
||||
break
|
||||
if step == "자율_역제안" and supplier.counter_yes(ctx):
|
||||
ctx["input_price"] = ctx["autonomy_offer"]
|
||||
end = "협상완료"
|
||||
break
|
||||
ctx["input_price"] = int(supplier.next_price(ctx))
|
||||
ctx["round"] = ctx.get("round", 1) + 1
|
||||
return trace, end, ctx
|
||||
|
||||
|
||||
def fmt(trace):
|
||||
out = []
|
||||
for step, kind, q, price, offer, _ in trace:
|
||||
s = f"{price:,}→{step}"
|
||||
if kind == "counter":
|
||||
s += f"({offer:,})"
|
||||
out.append(s)
|
||||
return " ".join(out)
|
||||
|
||||
|
||||
# ---- 스크립트 협력사 (결정론, 지형 비율로 정의) -----------------------------------------
|
||||
class Stubborn:
|
||||
"""조금씩 내리지만 하한이 목표가 위(×1.028) — 성사 불가능. 역제안·최종 전부 거절.
|
||||
|
||||
기대 궤적: 설득 ≥2회 → 앵커 이하 개시 → 단조 상향 사다리 → 최종제안(목표가) → 결렬."""
|
||||
def __init__(self, geo):
|
||||
self.floor = int(geo["target"] * 1.028)
|
||||
|
||||
def next_price(self, ctx):
|
||||
return max(self.floor, int(ctx["input_price"] * 0.96))
|
||||
|
||||
def counter_yes(self, ctx):
|
||||
return False
|
||||
|
||||
def final_yes(self, ctx):
|
||||
return False
|
||||
|
||||
|
||||
class HoverNearTarget:
|
||||
"""목표가 +0.19% 고정 — 마무리 국면. 압박이 나오면 안 되는 구간."""
|
||||
def __init__(self, geo):
|
||||
self.price = int(geo["target"] * 1.0019)
|
||||
|
||||
def next_price(self, ctx):
|
||||
return self.price
|
||||
|
||||
def counter_yes(self, ctx):
|
||||
return False
|
||||
|
||||
def final_yes(self, ctx):
|
||||
return False
|
||||
|
||||
|
||||
class Dealable:
|
||||
"""4% 씩 내려와 목표가 바로 아래까지 협조 — 성사 가능 케이스."""
|
||||
def __init__(self, geo):
|
||||
self.floor = int(geo["target"] * 0.9995)
|
||||
self.accept_from = geo["anchor"] + 0.4 * (geo["target"] - geo["anchor"])
|
||||
|
||||
def next_price(self, ctx):
|
||||
return max(self.floor, int(ctx["input_price"] * 0.96))
|
||||
|
||||
def counter_yes(self, ctx):
|
||||
return ctx["autonomy_offer"] >= self.accept_from # 목표가 부근 제안은 수락
|
||||
|
||||
def final_yes(self, ctx):
|
||||
return True
|
||||
|
||||
|
||||
# ---- 시나리오 검사 (각 항목 = 과거 실제 결함) -------------------------------------------
|
||||
def assert_defects(tag, trace, end, geo):
|
||||
anchor, target = geo["anchor"], geo["target"]
|
||||
near = target * 1.005
|
||||
# '역제안' 검사는 일반 역제안 스텝만 센다 — 같은 금액 재시도가 자율_최종제안으로 전환된 것은
|
||||
# 반복이 아니라 설계된 최종 통보(제품 결정: 같은 금액 재호출 = 탄약 소진 → 마지막으로 묻고 종료).
|
||||
counters = [(i, t) for i, t in enumerate(trace) if t[0] == "자율_역제안"]
|
||||
presses = [t for t in trace if t[1] == "press"]
|
||||
|
||||
if trace and trace[0][3] > near:
|
||||
check(f"[{tag}] 개시 턴은 설득 (결함: v3.4 첫턴 walk→목표가 통보)",
|
||||
trace[0][1] == "press", f"첫 결정이 {trace[0][1]}")
|
||||
if counters:
|
||||
i0, first = counters[0]
|
||||
check(f"[{tag}] 첫 역제안은 앵커 이하 (결함: 사다리 꼭대기 개시)",
|
||||
first[4] <= anchor, f"첫 역제안 {first[4]:,} > 앵커 {anchor:,}")
|
||||
pressed_before = sum(1 for t in trace[:i0] if t[1] == "press")
|
||||
if first[3] > near: # 마무리 국면은 해금 예외
|
||||
check(f"[{tag}] 역제시 해금 전 설득 ≥{MIN_PRESS}회 (결함: 첫턴 역제시)",
|
||||
pressed_before >= MIN_PRESS, f"설득 {pressed_before}회 만에 역제안")
|
||||
offers = [t[4] for _, t in counters]
|
||||
check(f"[{tag}] 역제안 단조 상향 (결함: 제안 철회 423,198→420,024)",
|
||||
all(b >= a for a, b in zip(offers, offers[1:])), f"철회 발생: {offers}")
|
||||
check(f"[{tag}] 역제안 ≤ 목표가", all(o <= target for o in offers), f"{offers}")
|
||||
check(f"[{tag}] 같은 금액 역제안 반복 없음 (결함: 421,082 반복)",
|
||||
all(b != a for a, b in zip(offers, offers[1:])), f"{offers}")
|
||||
check(f"[{tag}] 마무리 국면(≤목표가×1.005) 압박 없음 (결함: 802원 푼돈 흥정)",
|
||||
all(t[3] > near for t in presses), "목표가 코앞에서 압박")
|
||||
check(f"[{tag}] 목표가 초과 제시가 수락 없음 (결함: 목표가+14% 매입)",
|
||||
not any(t[1] == "accept" and t[3] > target for t in trace), "")
|
||||
finals = [t for t in trace if t[0] == "자율_최종제안"]
|
||||
for f in finals:
|
||||
check(f"[{tag}] 최종제안 금액 = 목표가 (결함: 직전 금액 재사용 60,548)",
|
||||
f[4] == target, f"최종제안 {f[4]:,} ≠ 목표가 {target:,}")
|
||||
# 결렬 의사(walk)로 끝났다면 반드시 최종제안을 거쳤어야 한다 (턴캡 종료는 예외)
|
||||
walked_direct = any(t[1] == "walk" and t[0] == "협상실패" for t in trace)
|
||||
capped = trace and trace[-1][0] == "협상실패" and trace[-1][1] is None
|
||||
check(f"[{tag}] 결렬 전 최종제안 1회 보장 (결함: 최종 의사 확인 없이 종료)",
|
||||
not walked_direct or capped or bool(finals), "walk 즉시 결렬")
|
||||
check(f"[{tag}] 종료 보장 (무한 세션 없음)", end is not None, "max_steps 내 미종료")
|
||||
|
||||
|
||||
# ---- 엔진 단위 검사 (정책 무관 — 전환 로직 자체) ----------------------------------------
|
||||
def engine_unit_tests():
|
||||
print("\n[엔진 전환 로직 단위 검사]")
|
||||
geo = GEOS["실스케일"]
|
||||
target = geo["target"]
|
||||
|
||||
def force(kind, q=0.0, s=3):
|
||||
eng = ChatEngine.__new__(ChatEngine)
|
||||
eng.autonomy_decider = lambda c: SimpleNamespace(kind=kind, counter_q=q, strategy=s)
|
||||
return eng
|
||||
|
||||
# walk → 최종제안(목표가) → 재차 walk → 협상실패
|
||||
ctx = base_ctx(geo)
|
||||
eng = force("walk")
|
||||
sess = SimpleNamespace(context=ctx)
|
||||
step1 = eng._autonomy_next(sess)
|
||||
check("walk 1회차 → 자율_최종제안 전환", step1 == "자율_최종제안", f"got {step1}")
|
||||
check("walk 전환 최종제안 금액 = 목표가", ctx.get("autonomy_offer") == target,
|
||||
f"{ctx.get('autonomy_offer')}")
|
||||
step2 = eng._autonomy_next(sess)
|
||||
check("walk 2회차(최종 거절 후) → 협상실패", step2 == "협상실패", f"got {step2}")
|
||||
|
||||
# 같은 q 역제안 반복 → 최종제안(목표가) 전환
|
||||
ctx = base_ctx(geo)
|
||||
ctx["autonomy_last"] = ctx["autonomy_last_counter"] = {"kind": "counter", "q": 0.5, "s": 3}
|
||||
sess = SimpleNamespace(context=ctx)
|
||||
step = force("counter", q=0.5)._autonomy_next(sess)
|
||||
check("같은 금액 재역제안 → 자율_최종제안 전환", step == "자율_최종제안", f"got {step}")
|
||||
check("탄약소진 최종제안 금액 = 목표가", ctx.get("autonomy_offer") == target,
|
||||
f"{ctx.get('autonomy_offer')}")
|
||||
|
||||
# 턴 상한 — 캡 종료도 최종제안 보장을 우회하지 않는다
|
||||
ctx = base_ctx(geo)
|
||||
ctx["round"] = 13
|
||||
sess = SimpleNamespace(context=ctx)
|
||||
step = force("press")._autonomy_next(sess)
|
||||
check("턴 상한 초과(최종 미실시) → 자율_최종제안", step == "자율_최종제안", f"got {step}")
|
||||
check("턴캡 최종제안 금액 = 목표가", ctx.get("autonomy_offer") == target,
|
||||
f"{ctx.get('autonomy_offer')}")
|
||||
step = force("press")._autonomy_next(sess)
|
||||
check("턴 상한 초과(최종 거절 후) → 협상실패", step == "협상실패", f"got {step}")
|
||||
|
||||
|
||||
# ---- 봉투 마스크 단위 검사 (모델 무관 — 후보 필터 자체) ----------------------------------
|
||||
def envelope_unit_tests(policy):
|
||||
print("\n[봉투 마스크 단위 검사]")
|
||||
geo = GEOS["소액"]
|
||||
ctx = base_ctx(geo) # 설득 0회, 제시가 목표가 위 → 설득만 가능해야 한다
|
||||
act = policy.decide(ctx)
|
||||
check("설득 0회 상태의 결정은 press 만 가능 (walk·counter·accept 잠금)",
|
||||
act.kind == "press", f"got {act.kind}")
|
||||
|
||||
|
||||
# ---- 멘트 가드 검사 (목표가 누설·할루시네이션 — LLM 호출 없음) ---------------------------
|
||||
def ment_guard_tests():
|
||||
print("\n[멘트 가드 검사]")
|
||||
geo = GEOS["실스케일"]
|
||||
target, anchor, il = geo["target"], geo["anchor"], geo["il"]
|
||||
ctx = base_ctx(geo)
|
||||
|
||||
prompt = ment_generator._prompt_for("자율_압박_3", ctx)
|
||||
check("압박 프롬프트에 목표가 숫자 없음 (결함: 목표가 노출 멘트)",
|
||||
str(target) not in prompt.replace(",", ""), "프롬프트가 목표가를 담고 있음")
|
||||
|
||||
leak = f"저희 내부 산정 기준은 {target:,}원입니다. 이 가격에 맞춰 재검토 부탁드립니다."
|
||||
check("목표가 포함 압박 멘트 → 폐기", not ment_generator._guard("자율_압박_3", ctx, leak), "")
|
||||
|
||||
invented = "시장 상황을 고려해 400,000원 수준으로 재검토 부탁드립니다."
|
||||
check("지어낸 금액 멘트 → 폐기 (할루시네이션)",
|
||||
not ment_generator._guard("자율_압박_3", ctx, invented), "")
|
||||
|
||||
ctx2 = dict(ctx, autonomy_offer=anchor)
|
||||
ok_ment = f"내부 검토 결과 {anchor:,}원이면 즉시 진행이 가능합니다. 수락해 주시겠습니까?"
|
||||
check("정상 역제안 멘트(제안가 포함) → 통과",
|
||||
ment_generator._guard("자율_역제안", ctx2, ok_ment), "")
|
||||
no_offer = "말씀하신 조건을 검토했고 조정이 필요합니다. 수락해 주시겠습니까?"
|
||||
check("제안가 없는 역제안 멘트 → 폐기",
|
||||
not ment_generator._guard("자율_역제안", ctx2, no_offer), "")
|
||||
|
||||
ev = f"동일 품목 인터넷 최저가가 {il:,}원으로 확인됩니다. 재검토 부탁드립니다."
|
||||
check("최저가 인용: 근거 있음(수집됨+제시가>최저가) → 허용",
|
||||
ment_generator._guard("자율_압박_1", ctx, ev), "")
|
||||
ctx3 = dict(ctx, internet_lowest_price=0)
|
||||
ev0 = "동일 품목 인터넷 최저가 대비 높은 수준입니다. 재검토 부탁드립니다."
|
||||
check("최저가 인용: 미수집 품목 → 폐기 (지어낸 시장 주장)",
|
||||
not ment_generator._guard("자율_압박_1", ctx3, ev0), "")
|
||||
|
||||
|
||||
def main():
|
||||
bundle = sys.argv[1] if len(sys.argv) > 1 else autonomy_store.BUNDLE_PATH
|
||||
z = np.load(bundle, allow_pickle=False)
|
||||
policy = AutonomyPolicy(z, TenantConfigLoader().load("ktcommerce").reward)
|
||||
print(f"번들: {os.path.abspath(bundle)} (state_dim={int(z['state_dim'])})")
|
||||
|
||||
for geo_name, geo in GEOS.items():
|
||||
print(f"\n{'─' * 60}\n지형 [{geo_name}] 앵커 {geo['anchor']:,} / 목표 {geo['target']:,} "
|
||||
f"/ 첫 제시가 {geo['first']:,}")
|
||||
for tag, sup_cls in (("완고", Stubborn), ("목표가위 고정", HoverNearTarget),
|
||||
("협조", Dealable)):
|
||||
trace, end, _ = run_scenario(policy, sup_cls(geo), geo)
|
||||
full_tag = f"{geo_name}·{tag}"
|
||||
print(f"\n[{full_tag}] {fmt(trace)} ⇒ {end}")
|
||||
assert_defects(full_tag, trace, end, geo)
|
||||
|
||||
engine_unit_tests()
|
||||
envelope_unit_tests(policy)
|
||||
ment_guard_tests()
|
||||
|
||||
fails = [(n, d) for n, ok, d in _RESULTS if not ok]
|
||||
print(f"\n{'=' * 60}\n결과: {len(_RESULTS) - len(fails)}/{len(_RESULTS)} 통과")
|
||||
if fails:
|
||||
print("실패 항목 — 이 번들은 배포 금지:")
|
||||
for n, d in fails:
|
||||
print(f" ✘ {n} {d}")
|
||||
sys.exit(1)
|
||||
print("전 항목 통과 — 배포 가능.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,148 +0,0 @@
|
||||
"""action-as-feature DQN 학습 (Phase 2·3) — 공용 환경 헬퍼 + 단독 학습 엔트리.
|
||||
|
||||
카드 특징 = 스크립트 임베딩(384) + 전략 one-hot(4) + 톤 one-hot(4) = 392차원
|
||||
상태 특징 = 연속 상태(9) + 고객사 성향(5) = 14차원 ← 협력사·고객사 조건화
|
||||
학습 환경 = FeatureBuyer(양보력/수락력 2축) + 에피소드마다 협력사·고객사성향 랜덤 샘플링
|
||||
|
||||
비교 평가는 tools.compare_qtable_vs_dqn 에서 수행한다.
|
||||
실행: APP_ENV=local python -m tools.train_feature_dqn
|
||||
"""
|
||||
|
||||
import os
|
||||
import random
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from eval_harness.buyer import Scenario
|
||||
from eval_harness.feature_buyer import FeatureBuyer, sample_supplier
|
||||
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot
|
||||
from negotiation.qtable.domain.service.feature_builder import (
|
||||
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features, build_tenant_features)
|
||||
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
EMB_PATH = os.path.join(_HERE, "..", "artifacts", "card_embeddings.npz")
|
||||
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "feature_dqn_ktcommerce.pt")
|
||||
|
||||
# zero-shot 실험용 홀드아웃 (전략 1·4 — 남은 풀에도 같은 전략 존재).
|
||||
# 서빙용 최종 학습은 전체 풀 사용: FULL_POOL=1 python -m tools.train_feature_dqn
|
||||
HOLDOUT = [] if os.getenv("FULL_POOL") == "1" else ["NGC-002", "NGC-010"]
|
||||
ANCHOR, TARGET = 8000.0, 10000.0
|
||||
MAX_TURNS = 5
|
||||
N_STRATEGY, N_TONE = 4, 4
|
||||
|
||||
|
||||
# ---- 카드 특징: 임베딩 + 전략/톤 one-hot ------------------------------------------
|
||||
def load_cards():
|
||||
z = np.load(EMB_PATH, allow_pickle=True)
|
||||
numbers = [str(n) for n in z["numbers"]]
|
||||
feat, strat = {}, {}
|
||||
for i, n in enumerate(numbers):
|
||||
s, t = int(z["strategy"][i]), int(z["tone"][i])
|
||||
s_oh = np.eye(N_STRATEGY, dtype=np.float32)[s - 1]
|
||||
t_oh = np.eye(N_TONE, dtype=np.float32)[t - 1]
|
||||
feat[n] = np.concatenate([z["embeddings"][i].astype(np.float32), s_oh, t_oh])
|
||||
strat[n] = s
|
||||
return numbers, feat, strat
|
||||
|
||||
|
||||
# ---- 고객사 성향: 보상 설정 샘플링 ---------------------------------------------------
|
||||
def sample_tenant_pref(rng: np.random.Generator, base_cfg):
|
||||
"""p ∈ [0,1]: 0=성사중시(협력 유리) ↔ 1=가격중시(경쟁 유리). 반환: (RewardConfig, tenant_feat)."""
|
||||
p = float(rng.uniform(0.0, 1.0))
|
||||
cfg = base_cfg.model_copy(update=dict(
|
||||
max_weight=0.25 + 0.60 * p, # 가격보상 비중
|
||||
min_weight=(0.25 + 0.60 * p) * 0.7,
|
||||
success_reward=1.6 - 1.2 * p, # 성사중시일수록 성공보상↑
|
||||
failure_penalty=-(1.4 - 1.1 * p), # 성사중시일수록 결렬이 아픔
|
||||
beta=0.1 + 0.4 * p,
|
||||
penalty_lambda=float(rng.uniform(0.005, 0.05)),
|
||||
))
|
||||
return cfg, build_tenant_features(cfg)
|
||||
|
||||
|
||||
def pref_config(base_cfg, p: float, lam: float = 0.02):
|
||||
"""평가용: 성향 p 를 고정해 RewardConfig 생성 (극단 테스트)."""
|
||||
return base_cfg.model_copy(update=dict(
|
||||
max_weight=0.25 + 0.60 * p, min_weight=(0.25 + 0.60 * p) * 0.7,
|
||||
success_reward=1.6 - 1.2 * p, failure_penalty=-(1.4 - 1.1 * p),
|
||||
beta=0.1 + 0.4 * p, penalty_lambda=lam,
|
||||
))
|
||||
|
||||
|
||||
def make_snapshot(sup, price: float, turn: int, acceptance: float,
|
||||
outcome=NegotiationOutcome.ONGOING) -> NegotiationSnapshot:
|
||||
return NegotiationSnapshot(
|
||||
revenue_amount=sup.revenue_amount, distribution_code=sup.distribution_code,
|
||||
partner_count=sup.partner_count, acceptance_ratio=acceptance,
|
||||
input_price=price, anchor_price=ANCHOR, target_price=TARGET,
|
||||
round_number=turn, outcome=outcome,
|
||||
)
|
||||
|
||||
|
||||
# ---- 단독 학습 엔트리 (비교는 compare_qtable_vs_dqn) --------------------------------
|
||||
def main(episodes=10000, seed=42):
|
||||
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
|
||||
numbers, feat, strat = load_cards()
|
||||
train_pool = [c for c in numbers if c not in HOLDOUT]
|
||||
card_dim = feat[numbers[0]].shape[0]
|
||||
print(f"카드 {len(numbers)}장 (학습 {len(train_pool)} / 홀드아웃 {HOLDOUT}) card_dim={card_dim}")
|
||||
|
||||
tcfg = TenantConfigLoader().load("ktcommerce")
|
||||
policy = FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM,
|
||||
card_dim=card_dim, eps_decay=4000, gamma=0.95)
|
||||
rng = np.random.default_rng(seed)
|
||||
|
||||
print(f"=== 학습 {episodes} 에피소드 (협력사·성향 랜덤, CPU) ===")
|
||||
recent = []
|
||||
for ep in range(1, episodes + 1):
|
||||
sup = sample_supplier(rng)
|
||||
rcfg, tf = sample_tenant_pref(rng, tcfg.reward)
|
||||
rc = RewardCalculator(rcfg, tcfg.state)
|
||||
buyer = FeatureBuyer(sup, strat, seed=seed * 100 + ep, max_turns=MAX_TURNS)
|
||||
scenario = Scenario(anchor_price=ANCHOR, target_price=TARGET, revenue_amount=sup.revenue_amount,
|
||||
distribution_code=sup.distribution_code, partner_count=sup.partner_count)
|
||||
price0 = TARGET * 1.15
|
||||
price, used, total_r = price0, set(), 0.0
|
||||
for turn in range(1, MAX_TURNS + 1):
|
||||
acceptance = max(0.0, (price0 - price) / price0)
|
||||
s = make_snapshot(sup, price, turn, acceptance)
|
||||
sf = np.concatenate([build_state_features(s), tf])
|
||||
avail = [c for c in train_pool if c not in used] or list(train_pool)
|
||||
embs = np.stack([feat[c] for c in avail])
|
||||
i, _, _ = policy.select(sf, embs)
|
||||
card = avail[i]; used.add(card)
|
||||
resp = buyer.respond(card, scenario, turn, price)
|
||||
price = resp.new_price
|
||||
done = resp.accept or price <= ANCHOR or turn >= MAX_TURNS
|
||||
success = resp.accept or price <= ANCHOR
|
||||
outcome = (NegotiationOutcome.SUCCESS if success
|
||||
else NegotiationOutcome.FAILURE if done else NegotiationOutcome.ONGOING)
|
||||
# 최종 결과 시점만 채점 (중간 0 → γ 부트스트랩) — compare 스크립트와 동일 규칙.
|
||||
r = rc.calculate(make_snapshot(sup, price, turn, acceptance, outcome)).total if done else 0.0
|
||||
total_r += r
|
||||
if done:
|
||||
policy.remember(sf, feat[card], r, None, None, True)
|
||||
else:
|
||||
acc2 = max(0.0, (price0 - price) / price0)
|
||||
s2 = make_snapshot(sup, price, turn + 1, acc2)
|
||||
navail = [c for c in train_pool if c not in used] or list(train_pool)
|
||||
policy.remember(sf, feat[card], r, np.concatenate([build_state_features(s2), tf]),
|
||||
np.stack([feat[c] for c in navail]), False)
|
||||
policy.train_step()
|
||||
if done:
|
||||
break
|
||||
recent.append(total_r)
|
||||
if ep % 2000 == 0:
|
||||
print(f" ep {ep:>6} eps={policy.eps():.3f} 최근2000 평균보상={np.mean(recent[-2000:]):.4f}")
|
||||
|
||||
policy.save(CKPT_PATH)
|
||||
print(f"[저장] {CKPT_PATH}")
|
||||
return policy
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,365 +0,0 @@
|
||||
"""train_full_autonomy — 행동 룰 0개, 완전 자율 협상 에이전트 (v2 시뮬 프로토타입).
|
||||
|
||||
기존 시스템의 룰(앵커 이하 강제타결 / 3라운드 강제결렬 / 와일드카드 존 / 카드 카탈로그)을
|
||||
전부 제거하고, 모든 결정을 에이전트 행동으로 이관한다:
|
||||
|
||||
행동 공간 (action-as-feature, ScoreNet 이 후보 열거 채점):
|
||||
ACCEPT 현재 제시가로 타결 ← '앵커 이하 강제타결' 룰 대체
|
||||
WALK 협상 결렬 선언 ← '3라운드 강제결렬' 룰 대체
|
||||
COUNTER(C) "C원이면 수락" 역제안 ← '와일드카드 1%' 룰 대체 (금액도 학습)
|
||||
PRESS(strategy) 설득 압박(카드의 일반화) ← 카드 카탈로그 대체 (전략만 남음)
|
||||
|
||||
룰이 사라진 자리는 보상이 채운다(유일한 스펙):
|
||||
R = W×R_price + (1−W)×R_end − λ×round (기존 RewardCalculator 그대로)
|
||||
협상이 끝나는 길: 에이전트의 ACCEPT/WALK, 협력사의 COUNTER 수락, 협력사의 인내심 소진(이탈).
|
||||
마지막 것은 시스템 룰이 아니라 상대방 특성이다.
|
||||
|
||||
베이스라인 = 현행 룰 시스템을 같은 환경에서 재현(앵커타결/1%클로징/3라운드결렬 + 압박).
|
||||
|
||||
실행: APP_ENV=local PYTHONUTF8=1 python -m tools.train_full_autonomy
|
||||
"""
|
||||
|
||||
import os
|
||||
import random
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from eval_harness.feature_buyer import AFFINITY, STRATEGY_PROFILE, SupplierProfile, sample_supplier
|
||||
from negotiation.policies.autonomy_actions import (
|
||||
ACTION_DIM, ACTIONS, COUNTER_GRID, EXTRA_STATE_DIM, Action, extra_state,
|
||||
internet_gap_feat, settle_norm as extra_settle)
|
||||
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot
|
||||
from negotiation.qtable.domain.service.feature_builder import (
|
||||
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features, build_tenant_features)
|
||||
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tools.train_feature_dqn import pref_config, sample_tenant_pref
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "full_autonomy.pt")
|
||||
|
||||
TARGET = 10000.0
|
||||
# 앵커율(v3.1): 실운영 기하 정합 — 앵커가 = 목표가×(1−a), a ∈ [0.8%, 6%] 를 에피소드마다 샘플링.
|
||||
# (기존 고정 20% 폭은 실제(≈1%)와 지형이 달라, 실서비스에서 압박/역제안 밸런스가 어긋났다.)
|
||||
ANCHOR_RATE_RANGE = (0.008, 0.06)
|
||||
# 행동 공간(Action/ACTIONS/COUNTER_GRID/ACTION_DIM)은 negotiation.policies.autonomy_actions 공유
|
||||
# — 서빙(autonomy_store, numpy 전용)과 학습이 같은 인코딩을 쓴다.
|
||||
|
||||
|
||||
# ---- 협력사 모델 (상대 반응: 역제안 수락/재제안 포함) ---------------------------------
|
||||
class AutonomousBuyer:
|
||||
"""FeatureBuyer 확장: 역제안(C)에 반응한다. 이탈은 '인내심' — 시스템 룰이 아닌 상대 특성."""
|
||||
|
||||
def __init__(self, sup: SupplierProfile, seed: int):
|
||||
self.sup = sup
|
||||
self.rng = np.random.default_rng(seed)
|
||||
# 기질 t ∈ [0,1]: 0=터프(하한 높고 안 물러섬) ↔ 1=수월. 관측 가능한 이력·최저가가
|
||||
# 이 숨은 기질과 상관되게 생성된다 → 에이전트가 이력/최저가 특징을 읽을 '이유'가 생긴다.
|
||||
# 하한은 '우리 앵커'가 아니라 협력사 사정(≈목표가 기준)으로 정해진다(v3.1) —
|
||||
# 하한 > 목표가(≈35%)면 애초에 성사 불가능한 협상이고, 그걸 빨리 알아채고 끊는 것도 실력이다.
|
||||
t = float(self.rng.uniform(0.0, 1.0))
|
||||
self.floor = TARGET * float(np.clip(1.12 - 0.24 * t + self.rng.normal(0, 0.02), 0.85, 1.18))
|
||||
self.patience = int(self.rng.integers(4, 9)) + (1 if t > 0.7 else 0)
|
||||
# 첫 제시가: 목표가의 105~150% — 실운영(기존 공급가가 목표가를 26%+ 상회) 분포를 덮는다.
|
||||
# 좁게(110~125%) 학습하면 큰 갭 상황에서 정책이 분포 밖 일반화(대형컷 역제안)를 한다.
|
||||
self.price = TARGET * float(self.rng.uniform(1.05, 1.50))
|
||||
# 하한가가 첫 제시가보다 높을 수 없다(자기 하한 밑으로 부르고 시작하는 판매자는 없음).
|
||||
# 이 보정이 없으면 on_press 의 max(floor,·)가 가격을 '역주행'시키는 비현실이 생긴다.
|
||||
self.floor = min(self.floor, self.price * 0.98)
|
||||
self._last_c: Optional[float] = None # 직전 역제안 (같은 숫자 반복 짜증 모델링)
|
||||
# ---- 관측 가능 부가정보 (v3 특징 소스 — 기질과 상관, 노이즈 있음) ----
|
||||
self.hist_n = int(self.rng.integers(0, 6)) # 과거 협상 횟수 (0=신규)
|
||||
if self.hist_n:
|
||||
self.hist_success = float(np.clip(0.25 + 0.6 * t + self.rng.normal(0, 0.10), 0.0, 1.0))
|
||||
self.hist_settle_ratio = float(np.clip(1.18 - 0.28 * t + self.rng.normal(0, 0.04), 0.80, 1.30))
|
||||
else:
|
||||
self.hist_success = self.hist_settle_ratio = None
|
||||
# 인터넷최저가: 숨은 하한가의 노이즈 관측치. 60% 확률로만 수집돼 있음(현실: 미수집 흔함).
|
||||
self.internet_lowest = (self.floor * float(self.rng.uniform(0.98, 1.08))
|
||||
if self.rng.random() < 0.6 else None)
|
||||
|
||||
def _powers(self, strategy: int) -> Tuple[float, float]:
|
||||
conc, acc = STRATEGY_PROFILE.get(strategy, (0.5, 0.5))
|
||||
m = AFFINITY[self.sup.segment].get(strategy, 0.5)
|
||||
scale = 0.35 + 0.85 * m
|
||||
return conc * scale, acc * scale
|
||||
|
||||
def on_press(self, strategy: int, turn: int) -> Tuple[bool, float]:
|
||||
"""(이탈여부, 새 제시가). 압박이 안 먹히는 세그먼트면 이탈 위험이 실재한다."""
|
||||
c_pow, a_pow = self._powers(strategy)
|
||||
walk_p = 0.04 + 0.30 * (1.0 - a_pow) * (turn / self.patience)
|
||||
if self.rng.random() < walk_p:
|
||||
return True, self.price
|
||||
concession = (self.price - self.floor) * (0.10 + 0.55 * c_pow)
|
||||
self.price = max(self.floor, self.price - concession)
|
||||
return False, self.price
|
||||
|
||||
def on_counter(self, c: float, strategy: int, turn: int) -> Tuple[str, float]:
|
||||
"""역제안 C 반응: 'accept'(C로 타결) | 'walk' | 'counter'(새 제시가).
|
||||
|
||||
현실화(v2): 현 제시가 대비 인하 요구폭(cut)이 클수록 수락률이 급감하고 이탈 위험이 커진다
|
||||
— 초기 버전에서 에이전트가 't1 원샷 로우볼'로 시뮬 허점을 착취하던 것을 막는다.
|
||||
압박으로 가격을 충분히 끌어내린 뒤 작은 컷으로 클로징해야 통하는 구조.
|
||||
"""
|
||||
_, a_pow = self._powers(strategy or 3)
|
||||
cut = max(0.0, (self.price - c) / max(self.price, 1.0)) # 인하 요구폭 (현 제시가 대비)
|
||||
prev_c = self._last_c
|
||||
repeated = prev_c is not None and abs(c - prev_c) < 1e-6 # 같은 숫자 반복
|
||||
self._last_c = c
|
||||
# 양보 상호성(v3.3): 직전 제안보다 올려 부르면(성의 있는 양보) 호의적으로 반응한다.
|
||||
# 이 신호가 있어야 '상대가 내리면 우리도 조금 올리는' tit-for-tat 이 학습으로 나온다.
|
||||
warm = 0.0
|
||||
if prev_c is not None and c > prev_c + 1e-9:
|
||||
warm = float(np.clip((c - prev_c) / max(self.price - self.floor, 1.0), 0.0, 0.35))
|
||||
if c >= self.floor:
|
||||
margin = (c - self.floor) / max(self.floor, 1.0)
|
||||
p_acc = float(np.clip(0.20 + 0.9 * margin / 0.08, 0.0, 0.95)) * (0.75 + 0.35 * a_pow)
|
||||
p_acc *= float(np.clip(1.0 - (cut - 0.05) / 0.20, 0.0, 1.0)) # 컷 5% 초과부터 반발, 25%면 수락 0
|
||||
if repeated:
|
||||
p_acc *= 0.25 # 이미 거절한 숫자를 또 내밀면 설득력 급감
|
||||
p_acc *= 1.0 + warm
|
||||
if self.rng.random() < min(p_acc, 0.97):
|
||||
return "accept", c
|
||||
# 모욕적 요구(하한 미달·과도한 원샷 컷·앵무새 반복) → 이탈 위험
|
||||
low = max(0.0, (self.floor - c) / max(self.floor, 1.0))
|
||||
p_walk = min(0.5, 2.0 * low) + 0.35 * max(0.0, cut - 0.20) / 0.20 + (0.15 if repeated else 0.0)
|
||||
if self.rng.random() < min(p_walk * (1.0 - warm), 0.7):
|
||||
return "walk", self.price
|
||||
self.price = max(self.floor, c + (self.price - c) * float(self.rng.uniform(0.30, 0.60) + warm))
|
||||
return "counter", self.price
|
||||
|
||||
|
||||
# ---- 에피소드 실행 (룰 없음 — 종료는 행동 또는 상대 특성으로만) ------------------------
|
||||
def make_snapshot(sup, price, turn, p0, anchor, outcome=NegotiationOutcome.ONGOING):
|
||||
return NegotiationSnapshot(
|
||||
revenue_amount=sup.revenue_amount, distribution_code=sup.distribution_code,
|
||||
partner_count=sup.partner_count, acceptance_ratio=max(0.0, (p0 - price) / p0),
|
||||
input_price=price, anchor_price=anchor, target_price=TARGET,
|
||||
round_number=turn, outcome=outcome)
|
||||
|
||||
|
||||
MIN_PRESS = int(os.getenv("AUTONOMY_MIN_PRESS", "2")) # 역제시 해금에 필요한 최소 설득 횟수
|
||||
|
||||
|
||||
def available_actions(price: float, last_counter_q: Optional[float] = None,
|
||||
counter_locked: bool = False) -> list:
|
||||
"""행동 봉투 (serving autonomy_store 와 동일해야 한다):
|
||||
① 목표가 초과 제시가는 '수락' 제외 — 매입 승인 범위(목표가 초과 수락 착취 방지)
|
||||
② 직전 역제안 미만 금액의 역제안 제외 — 단조 양보 원칙(제안 철회 금지;
|
||||
양보 '속도'는 정책이 배우고, 후퇴 '금지'만 구조로 보장)
|
||||
③ counter_locked: 설득 MIN_PRESS 회 전에는 역제시 잠금 — 옛 제품 의미론
|
||||
(일반 카드=설득, 역제시=와일드카드 성격의 마무리 수단) 복원
|
||||
④ 마무리 국면(제시가 ≤ 목표가×1.005): 압박 제외 — 푼돈 차이에서 재검토 요청 반복 방지
|
||||
⑤ 첫 역제안은 앵커 이하(q ≤ 0)만 — 낮게 개시해 사다리를 다 쓰며 올라간다"""
|
||||
near_target = price <= TARGET * 1.005
|
||||
return [a for a in ACTIONS
|
||||
if not (a.kind == "accept" and price > TARGET)
|
||||
and not (a.kind == "counter" and counter_locked and not near_target)
|
||||
and not (a.kind == "walk" and counter_locked and not near_target)
|
||||
and not (a.kind == "press" and near_target)
|
||||
and not (a.kind == "counter" and last_counter_q is None and a.counter_q > 1e-9)
|
||||
and not (a.kind == "counter" and last_counter_q is not None
|
||||
and a.counter_q < last_counter_q - 1e-9)]
|
||||
|
||||
|
||||
def action_feats(price: float, anchor: float, last_counter_q: Optional[float] = None,
|
||||
counter_locked: bool = False):
|
||||
"""현 제시가 기준 (가용 행동 리스트, 특징 [K, ACTION_DIM]). counter 는 컷폭 포함."""
|
||||
span = max(TARGET - anchor, 1.0)
|
||||
pos = (price - anchor) / span
|
||||
acts = available_actions(price, last_counter_q, counter_locked)
|
||||
rows = []
|
||||
for a in acts:
|
||||
cut = 0.0
|
||||
if a.kind == "counter":
|
||||
c = anchor + a.counter_q * span
|
||||
cut = max(0.0, (price - c) / max(price, 1.0))
|
||||
rows.append(a.feat(pos, cut))
|
||||
return acts, np.stack(rows)
|
||||
|
||||
|
||||
def run_episode(policy_fn, sup, rc: RewardCalculator, tf: np.ndarray, seed: int,
|
||||
learner: Optional[FeatureDQNPolicy] = None, trace: Optional[list] = None):
|
||||
"""policy_fn(state_feat, price_pos) → Action. learner 지정 시 replay 저장+학습."""
|
||||
buyer = AutonomousBuyer(sup, seed)
|
||||
p0 = buyer.price
|
||||
env_rng = np.random.default_rng(seed + 7)
|
||||
# 앵커율 샘플링(v3.1): 실운영처럼 앵커가 목표가 바로 아래(0.8~6%) — 좁은 스팬 지형에서 학습.
|
||||
anchor = TARGET * (1.0 - float(env_rng.uniform(*ANCHOR_RATE_RANGE)))
|
||||
span = max(TARGET - anchor, 1.0)
|
||||
turn, settled, walked = 0, None, False
|
||||
last_kind, last_q = "", 0.0 # 직전 역제안 기억 (같은 숫자 반복 방지의 학습 근거)
|
||||
press_n = 0 # 설득 횟수 — 역제시 해금(MIN_PRESS) 카운터
|
||||
# 견적 마감(환경 사실): 마감 도달 시 협상은 미타결 종료된다 — 룰이 아니라 세상의 시계.
|
||||
deadline_turns = int(env_rng.integers(3, 11))
|
||||
# 관측성 마스크(v3.5): 실서빙은 마감·이력·최저가가 '없는' 세션이 흔하고 로더가 중립값
|
||||
# (0.5/0)을 대입한다. 시뮬이 항상 다 아는 세계만 학습하면 그 중립 상태가 분포 밖이 된다
|
||||
# — v3.4 가 라이브 소액 지형에서 첫 턴 결렬로 퇴화한 원인 추정. 세계(마감 종료·상대 특성)는
|
||||
# 그대로 두고 관측만 가린다: 마감은 40% 미관측(0.5 고정), 15% 는 전부 미상(신규 견적의 전형).
|
||||
deadline_known = env_rng.random() < 0.6
|
||||
blind = env_rng.random() < 0.15
|
||||
if blind:
|
||||
deadline_known = False
|
||||
# 협력사 이력·최저가 특징 (에피소드 내 불변)
|
||||
known_hist = buyer.hist_n and not blind
|
||||
fixed_extra = dict(
|
||||
hist_n=min(buyer.hist_n, 5) / 5.0 if not blind else 0.0,
|
||||
hist_success=buyer.hist_success if known_hist else 0.5,
|
||||
hist_settle=extra_settle(buyer.hist_settle_ratio) if known_hist else 0.5,
|
||||
internet_gap=internet_gap_feat(buyer.internet_lowest or 0.0, anchor) if not blind else 0.0,
|
||||
)
|
||||
pending = None # (state_feat, action_feat) — 최종 결과 시점만 채점, 중간 r=0
|
||||
|
||||
while True:
|
||||
turn += 1
|
||||
price = buyer.price
|
||||
deadline_remain = (max(0.0, (deadline_turns - turn + 1) / deadline_turns)
|
||||
if deadline_known else 0.5) # 미관측 → 서빙 로더와 동일한 중립값
|
||||
sf = np.concatenate([build_state_features(make_snapshot(sup, price, turn, p0, anchor)), tf,
|
||||
extra_state(last_kind, last_q, deadline=deadline_remain, **fixed_extra)])
|
||||
lcq = last_q if last_kind == "counter" else None
|
||||
locked = lcq is None and press_n < MIN_PRESS
|
||||
act = policy_fn(sf, price, anchor, lcq, locked)
|
||||
if trace is not None:
|
||||
trace.append((turn, int(price), act))
|
||||
|
||||
if act.kind == "accept":
|
||||
settled = price
|
||||
elif act.kind == "walk":
|
||||
walked = True
|
||||
elif act.kind == "counter":
|
||||
c = anchor + act.counter_q * span
|
||||
resp, val = buyer.on_counter(c, act.strategy, turn)
|
||||
last_kind, last_q = "counter", act.counter_q # 역제안 기억 갱신
|
||||
if resp == "accept":
|
||||
settled = c
|
||||
elif resp == "walk":
|
||||
walked = True
|
||||
else: # press
|
||||
press_n += 1
|
||||
left, _ = buyer.on_press(act.strategy, turn)
|
||||
walked = walked or left
|
||||
if not settled and not walked and turn >= buyer.patience:
|
||||
walked = True # 인내심 소진(상대 특성) — 시스템 룰 아님
|
||||
if not settled and not walked and turn >= deadline_turns:
|
||||
walked = True # 견적 마감 도달(환경 사실) — 미타결 종료
|
||||
|
||||
done = settled is not None or walked
|
||||
final_price = settled if settled is not None else buyer.price
|
||||
# 성사 보너스는 목표가 이하 타결에만 — v3.1 이 '비싸게라도 성사'로 착취한 보상 구멍의
|
||||
# 원인 차단(봉투 ① 의 마스크와 이중 방어: 유인 자체를 올바르게). 초과 타결 = 결렬 취급.
|
||||
outcome = (NegotiationOutcome.SUCCESS if settled is not None and settled <= TARGET
|
||||
else NegotiationOutcome.FAILURE if done else NegotiationOutcome.ONGOING)
|
||||
r = rc.calculate(make_snapshot(sup, final_price, turn, p0, anchor, outcome)).total if done else 0.0
|
||||
|
||||
if learner is not None:
|
||||
pos = (price - anchor) / span
|
||||
cut = 0.0
|
||||
if act.kind == "counter":
|
||||
cut = max(0.0, (price - (anchor + act.counter_q * span)) / max(price, 1.0))
|
||||
af = act.feat(pos, cut)
|
||||
if pending:
|
||||
nxt_lcq = last_q if last_kind == "counter" else None
|
||||
learner.remember(*pending, 0.0, sf,
|
||||
action_feats(price, anchor, nxt_lcq,
|
||||
nxt_lcq is None and press_n < MIN_PRESS)[1], False)
|
||||
pending = (sf, af)
|
||||
if done:
|
||||
learner.remember(sf, af, r, None, None, True)
|
||||
learner.train_step()
|
||||
if done:
|
||||
return settled, turn, r
|
||||
|
||||
|
||||
# ---- 정책들 ------------------------------------------------------------------
|
||||
def dqn_policy(policy: FeatureDQNPolicy):
|
||||
def f(sf, price, anchor, last_counter_q=None, counter_locked=False):
|
||||
acts, feats = action_feats(price, anchor, last_counter_q, counter_locked)
|
||||
i, _, _ = policy.select(sf, feats)
|
||||
return acts[i]
|
||||
return f
|
||||
|
||||
|
||||
class RuleBaseline:
|
||||
"""현행 시스템 룰 재현: 앵커 이하 수락 / 존내 1% 클로징 / 3회 압박 후 결렬."""
|
||||
|
||||
def __init__(self):
|
||||
self.presses, self.closed = 0, False
|
||||
|
||||
def __call__(self, sf, price, anchor, last_counter_q=None, counter_locked=False) -> Action:
|
||||
span = max(TARGET - anchor, 1.0)
|
||||
if price <= anchor:
|
||||
return Action("accept")
|
||||
if price <= anchor * 1.02 and not self.closed:
|
||||
self.closed = True
|
||||
return Action("counter", (price * 0.99 - anchor) / span, 3)
|
||||
if self.presses < 3:
|
||||
self.presses += 1
|
||||
return Action("press", 0.0, 3)
|
||||
return Action("walk")
|
||||
|
||||
|
||||
# ---- 학습/평가 ----------------------------------------------------------------
|
||||
def evaluate(name, make_policy_fn, base_cfg, tcfg_state, episodes=3000, seed0=777):
|
||||
rc = RewardCalculator(pref_config(base_cfg, 0.5), tcfg_state)
|
||||
tf = build_tenant_features(pref_config(base_cfg, 0.5))
|
||||
rng = np.random.default_rng(seed0)
|
||||
rewards, settles, rounds = [], [], []
|
||||
for i in range(episodes):
|
||||
sup = sample_supplier(rng)
|
||||
settled, turn, r = run_episode(make_policy_fn(), sup, rc, tf, seed0 * 91 + i)
|
||||
rewards.append(r)
|
||||
rounds.append(turn)
|
||||
if settled is not None:
|
||||
settles.append(settled / TARGET)
|
||||
sr = len(settles) / episodes
|
||||
print(f"{name:<14} 보상 {np.mean(rewards):.4f} ±{np.std(rewards)/np.sqrt(episodes):.4f}"
|
||||
f" 성사율 {sr:.3f} 타결가/목표 {np.mean(settles):.3f} 평균라운드 {np.mean(rounds):.2f}")
|
||||
return dict(reward=float(np.mean(rewards)), success=sr,
|
||||
settle_ratio=float(np.mean(settles)) if settles else None, rounds=float(np.mean(rounds)))
|
||||
|
||||
|
||||
def main(episodes=15000, seed=42):
|
||||
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
|
||||
tcfg = TenantConfigLoader().load("ktcommerce")
|
||||
policy = FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM + EXTRA_STATE_DIM,
|
||||
card_dim=ACTION_DIM, eps_decay=5000, gamma=0.97)
|
||||
rng = np.random.default_rng(seed)
|
||||
|
||||
print(f"=== 완전 자율 학습 {episodes}ep (행동 {len(ACTIONS)}개, 룰 0개) ===")
|
||||
recent = []
|
||||
for ep in range(1, episodes + 1):
|
||||
sup = sample_supplier(rng)
|
||||
rcfg, tf = sample_tenant_pref(rng, tcfg.reward)
|
||||
rc = RewardCalculator(rcfg, tcfg.state)
|
||||
_, _, r = run_episode(dqn_policy(policy), sup, rc, tf, seed * 131 + ep, learner=policy)
|
||||
recent.append(r)
|
||||
if ep % 3000 == 0:
|
||||
print(f" ep {ep:>6} eps={policy.eps():.3f} 최근3000 평균보상={np.mean(recent[-3000:]):.4f}")
|
||||
policy.save(CKPT_PATH)
|
||||
|
||||
print("\n=== 평가 3000ep (중립 성향 p=0.5, 동일 협력사 분포) ===")
|
||||
policy.greedy = True
|
||||
evaluate("룰시스템(현행)", lambda: RuleBaseline(), tcfg.reward, tcfg.state)
|
||||
evaluate("완전자율 DQN", lambda: dqn_policy(policy), tcfg.reward, tcfg.state)
|
||||
|
||||
# 궤적 예시 — 에이전트가 룰 없이 뭘 하는지 눈으로
|
||||
print("\n=== 궤적 예시 (완전자율) ===")
|
||||
rc = RewardCalculator(pref_config(tcfg.reward, 0.5), tcfg.state)
|
||||
tf = build_tenant_features(pref_config(tcfg.reward, 0.5))
|
||||
rng2 = np.random.default_rng(7)
|
||||
for k in range(3):
|
||||
sup = sample_supplier(rng2)
|
||||
trace = []
|
||||
settled, turn, r = run_episode(dqn_policy(policy), sup, rc, tf, 5000 + k, trace=trace)
|
||||
seg = "·".join(sup.segment)
|
||||
print(f"[{seg}] " + " → ".join(
|
||||
f"t{t}:{p:,}원 {a.kind}{'' if a.kind in ('accept', 'walk') else f'({a.counter_q:.2f},전략{a.strategy})' if a.kind == 'counter' else f'(전략{a.strategy})'}"
|
||||
for t, p, a in trace) + f" ⇒ {'타결 ' + format(int(settled), ',') + '원' if settled else '결렬'} (r={r:.3f})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -58,6 +58,21 @@ 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
|
||||
@@ -123,6 +138,7 @@ 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")) # 소프트 삭제 여부
|
||||
@@ -157,6 +173,7 @@ class quotations(MAIN_BASE):
|
||||
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)
|
||||
@@ -164,6 +181,28 @@ 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
|
||||
@@ -183,6 +222,34 @@ 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,6 +130,41 @@ 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
|
||||
from common.database.model.models import chats, items, sessions, nego_cards, wild_cards
|
||||
from common.enums import ErrorType, SessionStatus
|
||||
from common.logger import LOG
|
||||
|
||||
@@ -47,6 +47,14 @@ 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]:
|
||||
@@ -112,6 +120,30 @@ 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,12 +1,13 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Tuple
|
||||
|
||||
from sqlalchemy import case, func, nulls_last, select, update
|
||||
from sqlalchemy import case, cast, func, nulls_last, or_, select, text, update
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import items, quotations, sessions
|
||||
from common.enums import ErrorType, SessionStatus
|
||||
from common.enums import CloseReason, ErrorType, QuotationStatus, RENEGOTIABLE_CLOSE_REASONS, SessionStatus
|
||||
from common.logger import LOG
|
||||
|
||||
|
||||
@@ -14,11 +15,11 @@ from common.logger import LOG
|
||||
# 마감일(qt_end_time)은 견적(quotation.end_time)이 진실값이다(session.end_time 은 협상 종료 시점 기록용).
|
||||
class ISessionCRUD(ABC):
|
||||
@abstractmethod
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]:
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type) -> Tuple[ErrorType, int]:
|
||||
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, keyword=None, result=None) -> Tuple[ErrorType, int]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -41,20 +42,63 @@ class ISessionCRUD(ABC):
|
||||
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def update_session_custom(self, cdb: AsyncSession, session_id, supplier_id, custom: dict) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
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
|
||||
top = rows[0][0] if rows and rows[0] 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:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
|
||||
pass
|
||||
|
||||
|
||||
class SessionCRUD(ISessionCRUD):
|
||||
@staticmethod
|
||||
def __filters(supplier_id, status, qt_type):
|
||||
def __filters(supplier_id, status, qt_type, keyword=None, result=None):
|
||||
conds = [sessions.supplier_id == supplier_id, sessions.deleted == False] # noqa: E712
|
||||
if status is not None:
|
||||
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) -> Tuple[ErrorType, list]:
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
|
||||
try:
|
||||
conds = self.__filters(supplier_id, status, qt_type)
|
||||
conds = self.__filters(supplier_id, status, qt_type, keyword, result)
|
||||
|
||||
# 정렬 규칙:
|
||||
# - order 를 명시(asc/desc)하면 그룹 구분 없이 전체를 마감 기준 한 줄로 정렬(전체 정렬).
|
||||
@@ -86,6 +130,12 @@ 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, # 이 세션 소유 공급사(=조회자). 낙찰자와 대조
|
||||
)
|
||||
.join(items, items.item_id == sessions.item_id)
|
||||
.join(quotations, quotations.qt_id == sessions.quotation_id)
|
||||
@@ -102,9 +152,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) -> Tuple[ErrorType, int]:
|
||||
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, keyword=None, result=None) -> Tuple[ErrorType, int]:
|
||||
try:
|
||||
conds = self.__filters(supplier_id, status, qt_type)
|
||||
conds = self.__filters(supplier_id, status, qt_type, keyword, result)
|
||||
query = (
|
||||
select(func.count())
|
||||
.select_from(sessions)
|
||||
@@ -173,3 +223,42 @@ class SessionCRUD(ISessionCRUD):
|
||||
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
|
||||
top = rows[0][0] if rows and rows[0] 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)
|
||||
)
|
||||
return await DB_SESSION_MNG.add(cdb, query)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
@@ -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
|
||||
from common.database.model.models import supplier_user_tokens, supplier_users, suppliers, companies, sessions
|
||||
from common.enums import ErrorType, TokenType
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
@@ -28,6 +28,14 @@ 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
|
||||
@@ -117,6 +125,43 @@ 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, Request
|
||||
from fastapi import APIRouter, Depends, Path, Request
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
|
||||
from common.models.gmodel import UserInfo
|
||||
@@ -20,6 +20,7 @@ from .protocol import (
|
||||
Res_Me,
|
||||
Res_PopupStatus,
|
||||
Res_RefreshToken,
|
||||
Res_SessionBranding,
|
||||
)
|
||||
|
||||
# 라우터(MVC 의 컨트롤러). 요청 검증 -> service 호출 -> RemoveNoneResponse 반환만 담당.
|
||||
@@ -106,3 +107,16 @@ 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,6 +48,8 @@ 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). 공급사가 타결 후 입력")
|
||||
|
||||
|
||||
class Res_Logout(Res_WebPacketProtocol):
|
||||
@@ -64,3 +66,9 @@ 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")
|
||||
primary_color: str = Field("", description="브랜드 색상(hex)")
|
||||
@@ -63,6 +63,7 @@ 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")
|
||||
@@ -77,6 +78,8 @@ 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). 재진입 시 폼 프리필용")
|
||||
labels: dict = Field(default_factory=dict, description="회사 커스텀 라벨(companies.settings.labels). 상품 상세 필드명(예: lead_time) 치환용. 없으면 프론트 기본값")
|
||||
|
||||
|
||||
# 대화 히스토리(재진입 복원)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
@@ -14,6 +16,11 @@ 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=결렬(개찰, 재협상 대상)")
|
||||
|
||||
|
||||
class Res_SessionList(Res_WebPacketProtocol):
|
||||
@@ -33,3 +40,21 @@ class Req_Reject(WebPacketProtocol):
|
||||
|
||||
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,7 +6,16 @@ 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_Reject, Res_Participate, Res_Reject, Res_SessionList
|
||||
from .protocol import (
|
||||
Req_ExtraInfo,
|
||||
Req_Reject,
|
||||
Req_Renegotiation,
|
||||
Res_ExtraInfo,
|
||||
Res_Participate,
|
||||
Res_Reject,
|
||||
Res_Renegotiation,
|
||||
Res_SessionList,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={404: {"description": "Not found"}})
|
||||
|
||||
@@ -26,9 +35,11 @@ async def list_sessions(
|
||||
order: Optional[str] = Query(None, 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)
|
||||
await service.list_sessions(user_info, credentials.credentials, status, qt_type, order, page, page_size, keyword, result)
|
||||
)
|
||||
|
||||
|
||||
@@ -61,3 +72,54 @@ async def reject(
|
||||
service: NegotiationService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.reject(user_info, credentials.credentials, session_id, req.reject_reason))
|
||||
|
||||
|
||||
@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)
|
||||
)
|
||||
@@ -18,6 +18,7 @@ from router.v1.auth.protocol import (
|
||||
Res_Me,
|
||||
Res_PopupStatus,
|
||||
Res_RefreshToken,
|
||||
Res_SessionBranding,
|
||||
)
|
||||
from router.v1.validator.dependencies import CreateAccessToken, CreateRefreshToken, GetHashedPW, VerifyPW
|
||||
|
||||
@@ -250,6 +251,34 @@ 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 []
|
||||
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.primary_color = branding.get("primary_color") or ""
|
||||
return res
|
||||
|
||||
async def popup_status(self, user_info: UserInfo, access_token: str) -> Res_PopupStatus:
|
||||
|
||||
@@ -24,6 +24,7 @@ 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
|
||||
@@ -44,11 +45,13 @@ 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 불필요, 상단 집약) ----
|
||||
@@ -59,6 +62,27 @@ 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)
|
||||
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:
|
||||
@@ -103,13 +127,18 @@ class ChatService:
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _build_bot_chat(sess, seq: int, turn, bot_chat_type: Optional[str] = None, summary: Optional[dict] = None) -> chats:
|
||||
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:
|
||||
# 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,
|
||||
@@ -204,9 +233,12 @@ class ChatService:
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
|
||||
return res
|
||||
|
||||
await self._ensure_in_progress(sess, quote)
|
||||
|
||||
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)
|
||||
@@ -221,8 +253,48 @@ 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 {}
|
||||
|
||||
# 회사 커스텀 라벨(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 {}
|
||||
|
||||
# 회사가 VAT(vat_yn)를 관리하지 않으면(hidden_fields) 협상 화면 VAT 표기를 숨긴다(값 null → 프론트 라벨 생략).
|
||||
_hidden = (settings.get("hidden_fields") or []) if _e == ErrorType.SUCCESS and settings else []
|
||||
if "vat_yn" in _hidden:
|
||||
res.item_vat_yn = None
|
||||
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()
|
||||
@@ -239,6 +311,15 @@ 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)
|
||||
@@ -371,8 +452,27 @@ class ChatService:
|
||||
# 유저 미입력 가격 타결 케이스 — 마지막 유저 제시가와 다를 수 있다).
|
||||
summary = await self._build_summary(sess, quote, item, final_price, turn.settled_price or last_price)
|
||||
|
||||
# 카드 번호(turn.card_id) → UUID 변환. step 으로 nego/wild 갈라 각 테이블 조회(번호가 겹칠 수 있어 종류로 구분).
|
||||
# 카드 사용 로그(chats.card_id/type/used)를 negodata 조인용으로 남긴다. (1% 인하 시스템 카드는 agent 가 card_id 미제공)
|
||||
card_uuid = None
|
||||
card_type = None
|
||||
if turn.card_id:
|
||||
is_wild = bool(turn.step and turn.step.startswith("wild"))
|
||||
if is_wild:
|
||||
card_uuid = await DB_SESSION_MNG.execute_lambda(
|
||||
chats.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.chat_crud.get_wild_card_id_by_number(s, str(turn.card_id)),
|
||||
)
|
||||
card_type = 2
|
||||
else:
|
||||
card_uuid = await DB_SESSION_MNG.execute_lambda(
|
||||
chats.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.chat_crud.get_nego_card_id_by_number(s, str(turn.card_id)),
|
||||
)
|
||||
card_type = 1
|
||||
|
||||
# 봇 메시지 + 종료 시 확정(성공=DONE+입찰가 / 실패=REJECTED+거부사유·제시가). 한 트랜잭션.
|
||||
bot_msg = self._build_bot_chat(sess, seq=max_seq + 2, turn=turn, bot_chat_type=bot_chat_type, summary=summary)
|
||||
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)
|
||||
funcs = [lambda s: self.chat_crud.insert_message(s, bot_msg)]
|
||||
# 가격 입력 턴 → 마지막 제시가를 봇 메시지 저장과 같은 트랜잭션으로 갱신.
|
||||
# 앵커링 표본 판정의 "가격 흔적"(가격을 써낸 협상만 집계 — 중간 이탈해도 실패로 측정 가능).
|
||||
@@ -392,10 +492,15 @@ 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=(user_input or None), reject_price=price,
|
||||
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},
|
||||
))
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run([chats.DBType()], funcs)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
|
||||
@@ -4,11 +4,31 @@ from datetime import datetime, timezone
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import sessions
|
||||
from common.enums import DBWRType, ErrorType, QuotationStatus, SessionStatus
|
||||
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.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, Res_Participate, Res_Reject, Res_SessionList
|
||||
from router.v1.negotiation.protocol import (
|
||||
ListItem,
|
||||
Req_ExtraInfo,
|
||||
Req_Renegotiation,
|
||||
Res_ExtraInfo,
|
||||
Res_Participate,
|
||||
Res_Reject,
|
||||
Res_Renegotiation,
|
||||
Res_SessionList,
|
||||
)
|
||||
from services.auth_service import AuthService
|
||||
|
||||
|
||||
@@ -18,11 +38,20 @@ class NegotiationService:
|
||||
- 목록은 로그인 유저의 supplier_id 로만 조회한다.
|
||||
"""
|
||||
|
||||
def __init__(self, auth: AuthService = Depends(AuthService), session_crud: ISessionCRUD = Depends(SessionCRUD)):
|
||||
# 부가정보 입력 폼을 띄우는 요약 말풍선 종류. 이 말풍선이 나온 뒤면 협상은 타결된 것으로 본다.
|
||||
_SUMMARY_BOT_TYPES = ("summaryRSP", "summaryCM")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
auth: AuthService = Depends(AuthService),
|
||||
session_crud: ISessionCRUD = Depends(SessionCRUD),
|
||||
chat_crud: IChatCRUD = Depends(ChatCRUD),
|
||||
):
|
||||
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) -> Res_SessionList:
|
||||
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:
|
||||
res = Res_SessionList()
|
||||
|
||||
# 1) 인증 (활성 + 저장된 access 토큰 대조)
|
||||
@@ -38,7 +67,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),
|
||||
lambda s: self.session_crud.list_by_supplier(s, supplier_id, status, qt_type, order, offset, page_size, keyword, result),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
@@ -48,31 +77,271 @@ 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),
|
||||
lambda s: self.session_crud.count_by_supplier(s, supplier_id, status, qt_type, keyword, result),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
res.items = [
|
||||
ListItem(
|
||||
session_id=str(r[0]),
|
||||
session_status=r[1],
|
||||
qt_type=r[2],
|
||||
qt_number=r[3],
|
||||
qt_end_time=r[4].isoformat(timespec="seconds") if r[4] else "",
|
||||
item_code=r[5] or "",
|
||||
item_name=r[6] or "",
|
||||
model_name=r[7] or "",
|
||||
maker_name=r[8] or "",
|
||||
# 같은 견적번호(체인)의 최대 차수 — 이미 다음 라운드가 있으면 재협상 요청 대상이 아니다.
|
||||
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),
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
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(
|
||||
session_id=str(r[0]),
|
||||
session_status=r[1],
|
||||
qt_type=r[2],
|
||||
qt_number=r[3],
|
||||
qt_end_time=r[4].isoformat(timespec="seconds") if r[4] else "",
|
||||
item_code=r[5] or "",
|
||||
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]),
|
||||
)
|
||||
|
||||
@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)
|
||||
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) 을 반환한다.
|
||||
|
||||
@@ -177,6 +177,56 @@ 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)
|
||||
@@ -294,3 +344,76 @@ 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
|
||||
@@ -0,0 +1,215 @@
|
||||
"""공급사 재협상 요청/철회(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
|
||||
@@ -0,0 +1,51 @@
|
||||
"""공급사 관점 협상 결과 파생(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
|
||||
@@ -0,0 +1,214 @@
|
||||
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:
|
||||
+44
-35
@@ -7,8 +7,11 @@
|
||||
# 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,6 +44,7 @@ services:
|
||||
# ── 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:
|
||||
@@ -60,6 +64,17 @@ 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
|
||||
@@ -68,8 +83,6 @@ services:
|
||||
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 폴백
|
||||
DQN_SERVING: "1" # 카드 선택을 feature_dqn(numpy 서빙)으로. 0 이면 기존 UCB Q-table
|
||||
AUTONOMY_MODE: "1" # 완전 자율 협상(판정 룰·카드 제거, 정책이 수락/역제안/결렬 결정). 0 이면 룰 엔진
|
||||
ports:
|
||||
- "9500:9500"
|
||||
extra_hosts:
|
||||
@@ -119,10 +132,7 @@ services:
|
||||
max-size: "10m"
|
||||
max-file: "5"
|
||||
|
||||
# ── LPS (인터넷 최저가 검색) ──────────────────────────────────
|
||||
# API(요청 접수, lean) + 워커(크롤, 헤드풀 Chromium+Xvfb). DB 는 외부(host.docker.internal).
|
||||
# 이미지엔 시크릿이 없다(example config 로 빌드) — 실값은 아래 env 로 주입.
|
||||
# 시크릿 값은 리포 루트 .env 파일에 채운다(.env.example 참고, .env 는 미커밋).
|
||||
# LPS API (인터넷 최저가 검색 — 요청 접수/조회, lean). 설정·시크릿은 config.local.toml 하나(미커밋, 마운트).
|
||||
lps-api:
|
||||
build:
|
||||
context: ./lps
|
||||
@@ -130,18 +140,12 @@ services:
|
||||
container_name: lps-api
|
||||
environment:
|
||||
APP_ENV: local
|
||||
DB_HOST: host.docker.internal # 컨테이너→호스트 DB (example toml 의 127.0.0.1 override)
|
||||
DB_USER: ${LPS_DB_USER:-postgres}
|
||||
DB_PASSWORD: ${LPS_DB_PASSWORD:-postgres}
|
||||
DB_HOST: ${LPS_DB_HOST-host.docker.internal} # 컨테이너→호스트 DB (config.local.toml 의 127.0.0.1 override)
|
||||
PYTHONUNBUFFERED: "1"
|
||||
# 멀티코어: PROCESS_COUNT(uvicorn 워커=코어수)를 올리면 커넥션 풀은 자동 산정된다.
|
||||
# (pool+overflow)×2엔진×PROCESS_COUNT ≤ DB_CONNECTION_BUDGET 를 config 가 스스로 보장.
|
||||
# 값은 .env 에서 서버별로 조정(compose 수정 불필요). API 병목은 드묾 — 기본 1이면 충분,
|
||||
# 부하테스트/대량 폴링 대비 시에만 코어 수만큼 상향(예: 4).
|
||||
PROCESS_COUNT: ${LPS_API_PROCESS_COUNT:-1}
|
||||
DB_CONNECTION_BUDGET: ${LPS_DB_CONNECTION_BUDGET:-40} # 전용 PG(max_connections≈100)면 90 근처로 상향
|
||||
volumes:
|
||||
- ./lps/config/config.local.toml:/app/config/config.local.toml:ro
|
||||
ports:
|
||||
- "9600:9600"
|
||||
- "${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:
|
||||
@@ -151,38 +155,43 @@ services:
|
||||
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 # Chromium + Xvfb (headless 는 안티봇에 탐지됨)
|
||||
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: host.docker.internal
|
||||
DB_USER: ${LPS_DB_USER:-postgres}
|
||||
DB_PASSWORD: ${LPS_DB_PASSWORD:-postgres}
|
||||
DB_HOST: ${LPS_DB_HOST-host.docker.internal} # 컨테이너→호스트 DB (config.local.toml 의 127.0.0.1 override)
|
||||
PYTHONUNBUFFERED: "1"
|
||||
WORKER_CONCURRENCY: "1" # 상품 동시 검색 수(워커별 브라우저 세트, Chrome 4×N)
|
||||
LPS_PROFILE_DIR: /profiles # Chrome 프로필을 영속 볼륨에 → 재시작해도 cf_clearance 유지(재웜업 회피)
|
||||
# LPS_FALLBACKS: "gmarket,auction,st11" # 오픈마켓 폴백(기본 OFF — 켜기 전 라이브 스모크로 셀렉터 점검)
|
||||
# LPS_JOB_DEADLINE_SEC: "300" # 잡 1건 처리 상한(행 방어) — 기본 300s
|
||||
# ── 시크릿 주입(이미지엔 없음 — 필수). 리포 루트 .env 에 값 채움(.env.example 참고) ──
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY:-} # 비면 AI 판정 OFF
|
||||
NAVER_KEYS: ${NAVER_KEYS:-} # "id1:secret1,id2:secret2" — 비면 네이버 검색 실패
|
||||
DECODO_HOST: ${DECODO_HOST:-} # DECODO 4종 비면 프록시 미사용(직접 연결)
|
||||
DECODO_USERNAME: ${DECODO_USERNAME:-}
|
||||
DECODO_PASSWORD: ${DECODO_PASSWORD:-}
|
||||
DECODO_PORT_START: ${DECODO_PORT_START:-0}
|
||||
DECODO_PORT_END: ${DECODO_PORT_END:-0}
|
||||
DECODO_COST_PER_GB: ${DECODO_COST_PER_GB:-0}
|
||||
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 종료 유예(LPS_SHUTDOWN_GRACE_SEC=60 + 정리 여유) — 기본 10s 면 하던 잡 마무리 전에 SIGKILL
|
||||
stop_grace_period: 75s # graceful 종료 유예(worker shutdown_grace_sec=60 + 여유)
|
||||
labels:
|
||||
autoheal: "true" # 하트비트 HEALTHCHECK 실패(행/좀비) 시 autoheal 이 재시작
|
||||
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
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
# 협상 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)이 연결 안 되면 한도가 안 걸릴 수 있으니, 설정이 항상 세션에 물리는지만 확인.
|
||||
+1
-1
@@ -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" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<title>AI 가격 협상 솔루션</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
LogoutResponse,
|
||||
MeResponse,
|
||||
PopupStatusResponse,
|
||||
SessionBrandingResponse,
|
||||
} from './auth.type'
|
||||
|
||||
export const authApi = {
|
||||
@@ -26,6 +27,12 @@ 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,6 +54,29 @@ export interface RefreshTokenResponse {
|
||||
}
|
||||
|
||||
// --- 내 정보 (GET /v1/auth/me) -------------------------------------------
|
||||
export interface Branding {
|
||||
service_name?: string
|
||||
logo_url?: string
|
||||
primary_color?: string
|
||||
email_header?: string
|
||||
}
|
||||
|
||||
// 로그인 전(초청 링크 진입) 브랜딩 조회 — GET /v1/auth/session-branding/{session_id}, 인증 불필요
|
||||
export interface SessionBrandingResponse {
|
||||
result: ApiResult
|
||||
service_name: string
|
||||
logo_url: string
|
||||
primary_color: 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
|
||||
@@ -62,6 +85,8 @@ export interface MeResponse {
|
||||
supplier_id: string
|
||||
supplier_name: string
|
||||
role: number
|
||||
branding?: Branding
|
||||
session_fields?: SessionField[]
|
||||
}
|
||||
|
||||
// --- 로그아웃 -------------------------------------------------------------
|
||||
@@ -94,6 +119,8 @@ export interface AuthUser {
|
||||
supplierId: string
|
||||
supplierName: string
|
||||
role: number
|
||||
branding: Branding
|
||||
sessionFields: SessionField[]
|
||||
}
|
||||
|
||||
export function toAuthUser(res: MeResponse): AuthUser {
|
||||
@@ -104,5 +131,7 @@ export function toAuthUser(res: MeResponse): AuthUser {
|
||||
supplierId: res.supplier_id,
|
||||
supplierName: res.supplier_name,
|
||||
role: res.role,
|
||||
branding: res.branding ?? {},
|
||||
sessionFields: res.session_fields ?? [],
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ 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
|
||||
@@ -46,6 +47,8 @@ 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>
|
||||
}
|
||||
|
||||
export interface ChatMessagesResponse {
|
||||
@@ -88,6 +91,7 @@ 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 ?? '',
|
||||
@@ -98,9 +102,11 @@ 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 ?? {},
|
||||
}
|
||||
}
|
||||
@@ -2,5 +2,11 @@
|
||||
export { negotiationApi } from './negotiation.api'
|
||||
export { negotiationKeys } from './negotiation.keys'
|
||||
export { useSessionListQuery } from './negotiation.queries'
|
||||
export { useParticipateMutation, useRejectMutation } from './negotiation.mutations'
|
||||
export {
|
||||
useCancelRenegotiationMutation,
|
||||
useParticipateMutation,
|
||||
useRejectMutation,
|
||||
useRequestRenegotiationMutation,
|
||||
useSaveExtraInfoMutation,
|
||||
} from './negotiation.mutations'
|
||||
export * from './negotiation.type'
|
||||
@@ -1,9 +1,13 @@
|
||||
// 협상 엔드포인트 호출 함수 (순수 HTTP 레이어, React 의존 없음).
|
||||
import { http } from '@/apis/http'
|
||||
import type {
|
||||
ExtraInfoRequest,
|
||||
ExtraInfoResponse,
|
||||
ParticipateResponse,
|
||||
RejectRequest,
|
||||
RejectResponse,
|
||||
RenegotiationRequest,
|
||||
RenegotiationResponse,
|
||||
SessionListParams,
|
||||
SessionListResponse,
|
||||
} from './negotiation.type'
|
||||
@@ -31,4 +35,30 @@ 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
|
||||
},
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { negotiationApi } from './negotiation.api'
|
||||
import { negotiationKeys } from './negotiation.keys'
|
||||
import type { RejectRequest } from './negotiation.type'
|
||||
import type { ExtraInfoRequest, RejectRequest, RenegotiationRequest } from './negotiation.type'
|
||||
|
||||
/**
|
||||
* 협상 세션 참여: 성공 시 세션 목록 캐시를 무효화해 상태를 갱신한다.
|
||||
@@ -30,3 +30,38 @@ export function useRejectMutation() {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 협상완료 부가정보 저장: 성공 시 세션 목록 캐시를 무효화한다.
|
||||
*/
|
||||
export function useSaveExtraInfoMutation() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: ({ sessionId, request }: { sessionId: string; request: ExtraInfoRequest }) =>
|
||||
negotiationApi.saveExtraInfo(sessionId, request),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useRequestRenegotiationMutation() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: ({ sessionId, request }: { sessionId: string; request: RenegotiationRequest }) =>
|
||||
negotiationApi.requestRenegotiation(sessionId, request),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useCancelRenegotiationMutation() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: ({ sessionId }: { sessionId: string }) => negotiationApi.cancelRenegotiation(sessionId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -43,6 +43,8 @@ export interface SessionListParams {
|
||||
order?: 'asc' | 'desc' // 생략 시 기본 그룹 정렬('할 일' 우선+임박순, 종료는 하단). 지정 시 그룹 무시하고 전체 마감순(asc=임박/desc=여유)
|
||||
page?: number
|
||||
page_size?: number
|
||||
keyword?: string // 검색어 — 견적번호·상품명·상품코드 부분일치
|
||||
result?: number // 결과 필터(SessionResult): 1=낙찰 2=미낙찰 3=결렬
|
||||
}
|
||||
|
||||
export interface SessionListItem {
|
||||
@@ -55,6 +57,41 @@ export interface SessionListItem {
|
||||
item_name: string
|
||||
model_name: string
|
||||
maker_name: string
|
||||
custom: Record<string, unknown> // 협상완료 부가정보(sessions.custom). 미입력이면 {}
|
||||
renegotiable: boolean // 재협상 요청 가능 여부(서버 판정 — 개찰 마감 + 마지막 차수 + 대기 요청 없음)
|
||||
renegotiation_status: number // 1=심사대기 2=승인 3=반려 4=철회, 이력 없으면 0
|
||||
renegotiation_memo: string // 담당자 심사 메모(반려 사유)
|
||||
result: number // 협상 결과(SessionResult): 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰)
|
||||
}
|
||||
|
||||
/** 공급사 관점 협상 결과 (sessions 파생) */
|
||||
export const SessionResult = { NONE: 0, WON: 1, LOST: 2, OPEN: 3 } as const
|
||||
|
||||
export const SESSION_RESULT_LABEL: Record<number, string> = {
|
||||
1: '낙찰',
|
||||
2: '미낙찰',
|
||||
3: '결렬',
|
||||
}
|
||||
|
||||
// 재협상 요청(IMK #15)
|
||||
export interface RenegotiationRequest {
|
||||
reason: string
|
||||
desired_price?: number | null
|
||||
}
|
||||
|
||||
export interface RenegotiationResponse {
|
||||
result: ApiResult
|
||||
session_id: string
|
||||
status: number
|
||||
}
|
||||
|
||||
export const RenegoStatus = { NONE: 0, PENDING: 1, APPROVED: 2, REJECTED: 3, CANCELED: 4 } as const
|
||||
|
||||
export const RENEGO_STATUS_LABEL: Record<number, string> = {
|
||||
1: '재협상 심사 중',
|
||||
2: '재협상 승인됨',
|
||||
3: '재협상 반려됨',
|
||||
4: '요청 철회됨',
|
||||
}
|
||||
|
||||
export interface SessionListResponse {
|
||||
@@ -65,6 +102,15 @@ export interface SessionListResponse {
|
||||
page_size: number
|
||||
}
|
||||
|
||||
// --- 협상완료 부가정보 (POST /v1/negotiation/sessions/{id}/extra-info) -----
|
||||
export interface ExtraInfoRequest {
|
||||
custom: Record<string, unknown>
|
||||
}
|
||||
export interface ExtraInfoResponse {
|
||||
result: ApiResult
|
||||
session_id: string
|
||||
}
|
||||
|
||||
// --- 참여 (POST /v1/negotiation/sessions/{id}/participate) ----------------
|
||||
export interface ParticipateResponse {
|
||||
result: ApiResult
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 57 KiB |
@@ -10,18 +10,18 @@ export type ButtonVariant =
|
||||
export type ButtonSize = 'sm' | 'md' | 'lg'
|
||||
|
||||
const base =
|
||||
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md font-medium select-none ' +
|
||||
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl font-semibold select-none ' +
|
||||
interactive +
|
||||
' focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ' +
|
||||
'disabled:pointer-events-none disabled:opacity-50'
|
||||
|
||||
const variantClass: Record<ButtonVariant, string> = {
|
||||
primary: 'bg-primary text-primary-foreground',
|
||||
primary: 'bg-primary text-primary-foreground shadow-sm',
|
||||
secondary: 'bg-secondary text-secondary-foreground',
|
||||
outline: 'border border-input bg-background',
|
||||
outline: 'border border-border bg-background text-foreground',
|
||||
// 투명 배경이라 brightness 무효 → bg 하이라이트
|
||||
ghost: 'hover:bg-accent hover:text-accent-foreground',
|
||||
destructive: 'bg-destructive text-white',
|
||||
destructive: 'bg-destructive text-white shadow-sm',
|
||||
}
|
||||
|
||||
const sizeClass: Record<ButtonSize, string> = {
|
||||
|
||||
@@ -18,13 +18,13 @@ export function ErrorPage({
|
||||
}: ErrorPageProps) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<div className="flex flex-col items-center gap-6 p-12">
|
||||
<div className="flex size-20 items-center justify-center rounded-full bg-destructive/10">
|
||||
<AlertTriangle className="size-10 text-destructive" />
|
||||
<div className="flex flex-col items-center gap-5 p-12">
|
||||
<div className="flex size-16 items-center justify-center rounded-full bg-destructive/10">
|
||||
<AlertTriangle className="size-8 text-destructive" />
|
||||
</div>
|
||||
<div className="flex flex-col items-center gap-2 text-center">
|
||||
<p className="title-2 text-destructive">{message}</p>
|
||||
<p className="body-1 text-neutral-70">{description}</p>
|
||||
<div className="flex flex-col items-center gap-1.5 text-center">
|
||||
<p className="text-lg font-bold text-neutral-90">{message}</p>
|
||||
<p className="text-sm text-neutral-60">{description}</p>
|
||||
</div>
|
||||
{onRetry && (
|
||||
<Button variant="primary" size="lg" onClick={onRetry}>
|
||||
|
||||
@@ -6,9 +6,9 @@ export function Input({ type = 'text', className, ...props }: ComponentProps<'in
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm',
|
||||
'flex h-10 w-full rounded-xl border border-input bg-background px-3.5 py-2 text-sm transition-all',
|
||||
'placeholder:text-muted-foreground',
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
|
||||
'focus-visible:outline-none focus-visible:border-brand-600 focus-visible:ring-1 focus-visible:ring-brand-600',
|
||||
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className,
|
||||
)}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { type ComponentProps } from 'react'
|
||||
import { cn } from '@/lib'
|
||||
import logoColor from '@/assets/imarketkorea-logo.png'
|
||||
import logoWhite from '@/assets/imarketkorea-logo-white.png'
|
||||
import logoDefault from '@/assets/negotium-logo.png'
|
||||
|
||||
export type LogoVariant = 'color' | 'white'
|
||||
export type LogoSize = 'sm' | 'md' | 'lg'
|
||||
|
||||
// 기본 브랜드(회사 설정 미지정 시). 회사 로고가 오면 logoUrl 이 이 값을 덮는다.
|
||||
const sources: Record<LogoVariant, string> = {
|
||||
color: logoColor,
|
||||
white: logoWhite,
|
||||
color: logoDefault,
|
||||
white: logoDefault,
|
||||
}
|
||||
|
||||
const sizes: Record<LogoSize, { img: string; text: string; gap: string }> = {
|
||||
@@ -17,33 +17,46 @@ const sizes: Record<LogoSize, { img: string; text: string; gap: string }> = {
|
||||
lg: { img: 'h-10', text: 'text-2xl', gap: 'gap-2.5' },
|
||||
}
|
||||
|
||||
// 기본 브랜드 로고는 가로로 긴 워드마크라 같은 높이로 두면 회사 심볼보다 훨씬 커 보인다(랜딩도 h-4 기준).
|
||||
const wordmarkSizes: Record<LogoSize, string> = {
|
||||
sm: 'h-3.5',
|
||||
md: 'h-4',
|
||||
lg: 'h-5',
|
||||
}
|
||||
|
||||
export interface LogoProps extends Omit<ComponentProps<'div'>, 'children'> {
|
||||
variant?: LogoVariant
|
||||
size?: LogoSize
|
||||
withText?: boolean
|
||||
alt?: string
|
||||
/** 회사 브랜딩 오버라이드(companies.settings.branding). 없으면 기본 iMarket Korea. */
|
||||
serviceName?: string
|
||||
logoUrl?: string
|
||||
}
|
||||
|
||||
export function Logo({
|
||||
variant = 'color',
|
||||
size = 'md',
|
||||
withText = true,
|
||||
alt = 'iMarket Korea',
|
||||
alt = 'NEGOTIUM',
|
||||
serviceName,
|
||||
logoUrl,
|
||||
className,
|
||||
...props
|
||||
}: LogoProps) {
|
||||
const s = sizes[size]
|
||||
const name = serviceName || 'negotium'
|
||||
|
||||
return (
|
||||
<div className={cn('flex items-center', s.gap, className)} {...props}>
|
||||
<img
|
||||
src={sources[variant]}
|
||||
alt={withText ? '' : alt}
|
||||
className={cn('w-auto select-none', s.img)}
|
||||
src={logoUrl || sources[variant]}
|
||||
alt={withText ? '' : (serviceName || alt)}
|
||||
className={cn('w-auto select-none', logoUrl ? s.img : wordmarkSizes[size])}
|
||||
/>
|
||||
{withText && (
|
||||
{withText && serviceName && (
|
||||
<span className={cn('font-bold tracking-[-0.4px] text-foreground', s.text)}>
|
||||
iMarket Korea
|
||||
{name}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -21,7 +21,7 @@ export function Modal({ children, onClose }: ModalProps) {
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-[rgba(0,0,0,0.40)]"
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-[rgba(0,0,0,0.40)] p-4"
|
||||
onClick={handleBackdropClick}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Button, Input } from '@/components'
|
||||
import { useLogin } from '@/features/auth/hooks/useLogin'
|
||||
|
||||
const inputClassName = 'h-12 rounded-md px-4 text-base'
|
||||
const inputClassName = 'h-12 rounded-xl px-4 text-base'
|
||||
|
||||
export function LoginForm() {
|
||||
const {
|
||||
|
||||
@@ -6,7 +6,10 @@ import { tokenStorage } from '@/apis'
|
||||
// 토큰이 있으나 만료/폐기된 경우는 요청 시 인터셉터가 세션을 종료시킨다.
|
||||
export function RequireAuth({ children }: { children: ReactNode }) {
|
||||
if (!tokenStorage.hasToken()) {
|
||||
return <Navigate to="/" replace />
|
||||
// 초청 링크(/chat?session_id=...)로 들어온 미로그인 사용자 — session_id 를 넘겨야
|
||||
// 로그인 화면이 그 회사 브랜딩으로 뜬다.
|
||||
const sessionId = new URLSearchParams(window.location.search).get('session_id')
|
||||
return <Navigate to={sessionId ? `/?session_id=${sessionId}` : '/'} replace />
|
||||
}
|
||||
return <>{children}</>
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useNavigate } from 'react-router'
|
||||
import { LogOut } from 'lucide-react'
|
||||
import { useLogoutMutation, useMeQuery } from '@/apis'
|
||||
import { Button } from '@/components'
|
||||
import { cn, interactive } from '@/lib'
|
||||
|
||||
// 사이드바 하단: 공급사명 + 로그아웃
|
||||
export function SidebarFooter() {
|
||||
@@ -15,19 +16,23 @@ export function SidebarFooter() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex w-full h-[60px] py-3 px-8 gap-3 items-center">
|
||||
<div className="flex-1 flex items-center min-w-0 text-sm text-foreground">
|
||||
<span className="truncate">{user?.supplierName ?? '-'}</span>
|
||||
<div className="flex w-full shrink-0 items-center gap-2 border-t border-border px-6 py-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-bold text-neutral-90">{user?.supplierName ?? '-'}</p>
|
||||
<p className="truncate text-xs text-neutral-60">{user?.name ?? '공급 파트너'}</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="w-[61px] px-2 rounded-[4px] text-xs flex-shrink-0"
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleLogout}
|
||||
disabled={logout.isPending}
|
||||
className={cn(
|
||||
'flex shrink-0 items-center gap-1.5 rounded-xl border border-border bg-white px-3 py-1.5 text-xs font-bold text-neutral-70 hover:bg-neutral-10 disabled:opacity-50',
|
||||
interactive,
|
||||
)}
|
||||
>
|
||||
<LogOut className="size-3.5" />
|
||||
로그아웃
|
||||
</Button>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useSearchParams } from 'react-router'
|
||||
import { authApi } from '@/apis'
|
||||
import type { Branding } from '@/apis/auth/auth.type'
|
||||
|
||||
// 로그인 전 화면의 회사 브랜딩을 담아 두는 곳. 로그아웃/토큰 만료와 무관하게 남겨
|
||||
// 뒤로가기·재진입으로 session_id 가 없어져도 같은 회사 화면을 유지한다(회사 식별 정보만 담는다).
|
||||
const BRANDING_KEY = 'negosium.preLoginBranding'
|
||||
|
||||
function readCached(): Branding | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(BRANDING_KEY)
|
||||
return raw ? (JSON.parse(raw) as Branding) : null
|
||||
} catch {
|
||||
return null // 손상된 값은 없는 것으로 본다
|
||||
}
|
||||
}
|
||||
|
||||
function writeCached(branding: Branding): void {
|
||||
try {
|
||||
localStorage.setItem(BRANDING_KEY, JSON.stringify(branding))
|
||||
} catch {
|
||||
// 저장 불가(프라이빗 모드 등)면 이번 방문에만 적용된다
|
||||
}
|
||||
}
|
||||
|
||||
// 로그인 전 화면(로그인 페이지)의 회사 브랜딩.
|
||||
// 협력사는 초청 메일의 /chat?session_id=... 로 들어오므로, 그 session_id 로 인증 없이 브랜딩만 조회한다.
|
||||
// session_id 가 없으면 마지막으로 확인된 회사 브랜딩을 쓰고, 그것도 없으면 기본 브랜드(Negosium).
|
||||
export function usePreLoginBranding(): Branding | null {
|
||||
const [searchParams] = useSearchParams()
|
||||
const [branding, setBranding] = useState<Branding | null>(readCached)
|
||||
|
||||
const sessionId = searchParams.get('session_id') ?? ''
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionId) return
|
||||
let alive = true
|
||||
void authApi
|
||||
.sessionBranding(sessionId)
|
||||
.then((res) => {
|
||||
if (!alive || res.result?.success === false) return
|
||||
const next: Branding = {
|
||||
service_name: res.service_name || undefined,
|
||||
logo_url: res.logo_url || undefined,
|
||||
primary_color: res.primary_color || undefined,
|
||||
}
|
||||
if (!next.service_name && !next.logo_url) return
|
||||
setBranding(next)
|
||||
writeCached(next) // 다음 진입에 session_id 가 없어도 이 회사로 보이게 한다
|
||||
})
|
||||
.catch(() => {
|
||||
// 조회 실패 시 캐시(또는 기본 브랜드)를 그대로 둔다
|
||||
})
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [sessionId])
|
||||
|
||||
return branding
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
export { LoginForm } from '@/features/auth/components/LoginForm'
|
||||
export { SidebarFooter } from '@/features/auth/components/SidebarFooter'
|
||||
export { RequireAuth } from '@/features/auth/components/RequireAuth'
|
||||
export { usePreLoginBranding } from '@/features/auth/hooks/usePreLoginBranding'
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, memo } from 'react'
|
||||
import { cn } from '@/lib'
|
||||
import { useEffect, useRef, memo, type RefObject } from 'react'
|
||||
import { useMeQuery } from '@/apis'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
import type { ChatMessage as ChatMessageType } from '@/features/chat/types'
|
||||
@@ -7,34 +7,47 @@ import { renderEmphasis } from '@/features/chat/lib/emphasis'
|
||||
import { Indicator } from '@/features/chat/components/templates/Indicator'
|
||||
import { Summary } from '@/features/chat/components/templates/Summary'
|
||||
import { BidSummary } from '@/features/chat/components/templates/BidSummary'
|
||||
import { RejectRSP } from '@/features/chat/components/templates/RejectRSP'
|
||||
import { RejectCM } from '@/features/chat/components/templates/RejectCM'
|
||||
|
||||
const AI_LABEL = '아이마켓코리아 (구매담당자)'
|
||||
|
||||
export function ChatMessage() {
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null)
|
||||
return (
|
||||
<div className="flex-1 w-full min-h-0 pr-[16px]">
|
||||
{/* pt-[64px]: 첫 메시지를 우측 협상절차 카드 상단과 맞추되, 스크롤 시 여백도 함께 밀려 올라가도록 스크롤 컨테이너 안쪽에 둔다 */}
|
||||
<div className="chat-scroll h-full overflow-y-auto flex flex-col pt-[64px] pl-[140px] pr-[126px] max-[1350px]:pl-[80px] max-[1350px]:pr-[72px] max-[1180px]:pl-[48px] max-[1180px]:pr-[40px]">
|
||||
<ChatList />
|
||||
<div className="flex-1 w-full min-h-0">
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="chat-scroll h-full overflow-y-auto flex flex-col pt-4 pb-6 px-4 sm:px-6 min-[1180px]:pl-[80px] min-[1180px]:pr-[72px] min-[1350px]:pl-[140px] min-[1350px]:pr-[126px]"
|
||||
>
|
||||
<ChatList scrollRef={scrollRef} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ChatList() {
|
||||
const bottomRef = useRef<HTMLDivElement | null>(null)
|
||||
function ChatList({ scrollRef }: { scrollRef: RefObject<HTMLDivElement | null> }) {
|
||||
const isFirstRef = useRef(true)
|
||||
const chats = useChatStore((s) => s.messages)
|
||||
const isLoading = useChatStore((s) => s.isLoading)
|
||||
|
||||
// 메시지 추가/타이핑 표시 시 항상 맨 아래로 스크롤
|
||||
// 메시지 추가/타이핑 표시 시 항상 맨 아래로 스크롤.
|
||||
// 스크롤 컨테이너를 직접 내린다 — scrollIntoView 는 요약/부가정보 폼처럼 큰 블록이 뒤늦게
|
||||
// 레이아웃되면 애니메이션 도중 목표 위치가 밀려 중간에 멈춘다.
|
||||
// 진입 첫 렌더는 즉시(auto) — 히스토리를 복원하며 위에서부터 훑어 내려가는 연출을 막는다.
|
||||
useEffect(() => {
|
||||
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
|
||||
}, [chats, isLoading])
|
||||
const scroller = scrollRef.current
|
||||
if (!scroller) return
|
||||
const behavior: ScrollBehavior = isFirstRef.current ? 'auto' : 'smooth'
|
||||
isFirstRef.current = false
|
||||
const id = requestAnimationFrame(() => {
|
||||
scroller.scrollTo({ top: scroller.scrollHeight, behavior })
|
||||
})
|
||||
return () => cancelAnimationFrame(id)
|
||||
}, [chats, isLoading, scrollRef])
|
||||
|
||||
if (!chats || chats.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<p className="body-1 text-neutral-70">채팅 내역이 없습니다.</p>
|
||||
<p className="text-sm text-neutral-60">채팅 내역이 없습니다.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -42,22 +55,22 @@ function ChatList() {
|
||||
return (
|
||||
<div className="flex flex-col w-full">
|
||||
{chats.map((message, index) => (
|
||||
<MessageItem key={message.chat_id || index} message={message} isFirst={index === 0} messages={chats} currentIndex={index} />
|
||||
<MessageItem key={message.chat_id || index} message={message} messages={chats} currentIndex={index} />
|
||||
))}
|
||||
{isLoading && <TypingBubble />}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// agent 응답을 기다리는 동안(협상 중) 대화 흐름에 표시하는 타이핑 인디케이터.
|
||||
// agent 응답을 기다리는 동안(협상 중) 대화 흐름에 표시하는 타이핑 인디케이터(AI 말풍선 톤).
|
||||
function TypingBubble() {
|
||||
return (
|
||||
<div className="mb-[56px] pt-[36px]" aria-label="협상 중" role="status">
|
||||
<div className="inline-flex items-center gap-[6px]">
|
||||
<span className="size-[8px] rounded-full bg-neutral-50 animate-bounce [animation-delay:-0.3s]" />
|
||||
<span className="size-[8px] rounded-full bg-neutral-50 animate-bounce [animation-delay:-0.15s]" />
|
||||
<span className="size-[8px] rounded-full bg-neutral-50 animate-bounce" />
|
||||
<div className="mb-6 flex flex-col items-start gap-1.5" aria-label="협상 중" role="status">
|
||||
<span className="text-xs font-bold text-neutral-80">{AI_LABEL}</span>
|
||||
<div className="inline-flex items-center gap-1.5 rounded-2xl rounded-tl-none border border-[#D2E6FF] bg-brand-light/70 px-4 py-3.5 shadow-sm">
|
||||
<span className="size-2 rounded-full bg-brand-500 animate-bounce [animation-delay:-0.3s]" />
|
||||
<span className="size-2 rounded-full bg-brand-500 animate-bounce [animation-delay:-0.15s]" />
|
||||
<span className="size-2 rounded-full bg-brand-500 animate-bounce" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -65,46 +78,43 @@ function TypingBubble() {
|
||||
|
||||
const MessageItem = memo(function MessageItem({
|
||||
message,
|
||||
isFirst,
|
||||
messages,
|
||||
currentIndex,
|
||||
}: {
|
||||
message: ChatMessageType
|
||||
isFirst: boolean
|
||||
messages: ChatMessageType[]
|
||||
currentIndex: number
|
||||
}) {
|
||||
const isBot = message.sender === 'bot'
|
||||
|
||||
// 직전이 reject 폼이면 사용자 답변은 숨기고 구분선만 표시
|
||||
// 직전이 reject 폼이면 사용자 답변 말풍선은 숨긴다(폼 자체가 답변을 담고 있음)
|
||||
if (!isBot && currentIndex > 0) {
|
||||
const prev = messages[currentIndex - 1]
|
||||
if (prev?.bot_chat_type === 'rejectRSP' || prev?.bot_chat_type === 'rejectCM') {
|
||||
return (
|
||||
<>
|
||||
<div className="text-right mb-[56px]" />
|
||||
<div className="flex w-full bg-neutral-30 h-[1px] mb-[20px]" />
|
||||
</>
|
||||
)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
return <div>{isBot ? <BotMessage message={message} isFirst={isFirst} /> : <UserMessage text={message.script || ''} />}</div>
|
||||
return isBot ? <BotMessage message={message} /> : <UserMessage text={message.script || ''} />
|
||||
})
|
||||
|
||||
const BotMessage = memo(function BotMessage({ message, isFirst }: { message: ChatMessageType; isFirst?: boolean }) {
|
||||
const BotMessage = memo(function BotMessage({ message }: { message: ChatMessageType }) {
|
||||
// 인디케이터는 이번 방문에서 '협상중'이었던 세션에서만 표시.
|
||||
// 진행 화면에서 실시간으로 완료되면 sticky 플래그로 계속 노출하고,
|
||||
// 완료/거부 세션에 결과 열람 목적으로 재진입한 경우엔 값이 와도 숨긴다.
|
||||
const showIndicator = useChatInitStore((s) => s.wasInProgress)
|
||||
const hasScript = Boolean(message.script && message.script.trim())
|
||||
|
||||
return (
|
||||
<div className="mb-[56px]">
|
||||
<div className={cn('flex flex-col', !isFirst && 'pt-[36px]')}>
|
||||
{/* 봇 스크립트의 `**굵게**` 경량 마크업 해석 (표현 규칙은 프론트 소유 — emphasis.tsx) */}
|
||||
<div className="body-1-read-r">{renderEmphasis(message.script || '')}</div>
|
||||
<div className="mb-5 animate-fade-in">
|
||||
<div className="flex flex-col items-start gap-1.5">
|
||||
<span className="text-xs font-bold text-neutral-80">{AI_LABEL}</span>
|
||||
{hasScript && (
|
||||
<div className="max-w-[80%] rounded-2xl rounded-tl-none border border-[#D2E6FF] bg-brand-light/70 p-4 text-sm leading-relaxed text-neutral-90 shadow-sm break-keep">
|
||||
{renderEmphasis(message.script || '')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 w-full mt-[32px]">
|
||||
<div className="flex flex-col gap-4 w-full mt-4">
|
||||
{showIndicator && message.bot_chat_type === 'indicator' && message.indicator_value != null && (
|
||||
<Indicator number={message.indicator_value} />
|
||||
)}
|
||||
@@ -114,26 +124,22 @@ const BotMessage = memo(function BotMessage({ message, isFirst }: { message: Cha
|
||||
itemName={message.summary.item_name}
|
||||
itemCode={message.summary.item_code}
|
||||
bidPrice={message.summary.final_price}
|
||||
deliveryType={message.summary.delivery_type || ''}
|
||||
isVAT={message.summary.item_isVAT}
|
||||
/>
|
||||
)}
|
||||
{message.bot_chat_type === 'rejectRSP' && <RejectRSP />}
|
||||
{message.bot_chat_type === 'rejectCM' && <RejectCM />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
const UserMessage = memo(function UserMessage({ text }: { text: string }) {
|
||||
const { data: user } = useMeQuery()
|
||||
const label = `${user?.supplierName ?? '공급사'} (나)`
|
||||
return (
|
||||
<>
|
||||
<div className="text-right mb-[56px]">
|
||||
<div className="inline-block max-w-[87%] bg-neutral-40 text-neutral-90 text-lg leading-[150%] tracking-[-0.18px] px-[20px] py-[10px] rounded-full break-keep">
|
||||
{text}
|
||||
</div>
|
||||
<div className="mb-5 flex flex-col items-end gap-1.5 animate-fade-in">
|
||||
<span className="text-xs font-bold text-neutral-80">{label}</span>
|
||||
<div className="max-w-[80%] rounded-2xl rounded-tr-none border border-border bg-white p-4 text-sm leading-relaxed text-neutral-90 shadow-sm break-keep">
|
||||
{text}
|
||||
</div>
|
||||
<div className="flex w-full bg-neutral-30 h-[1px] mb-[20px]" />
|
||||
</>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -1,13 +1,19 @@
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { ChatMessage } from '@/features/chat/components/ChatMessage'
|
||||
import { UserButton } from '@/features/chat/components/UserButton'
|
||||
import { MobileStepBar } from '@/features/chat/components/MobileStepBar'
|
||||
|
||||
export function ChatSection() {
|
||||
const { userButtonConfig } = useChatStore()
|
||||
return (
|
||||
<div className="flex flex-1 flex-col w-full h-full bg-surface rounded-bl-[8px]">
|
||||
<div className="flex flex-1 flex-col w-full h-full min-h-0 bg-surface">
|
||||
<MobileStepBar />
|
||||
<ChatMessage />
|
||||
<UserButton {...userButtonConfig} />
|
||||
{/* 하단 액션 덱 */}
|
||||
{/* safe-b: 홈 인디케이터에 입력 버튼이 가리지 않도록 하단 안전영역 확보 */}
|
||||
<div className="shrink-0 safe-b border-t border-border bg-white shadow-[0_-4px_20px_rgba(0,0,0,0.03)]">
|
||||
<UserButton {...userButtonConfig} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { useMeQuery, useSaveExtraInfoMutation, getApiErrorMessage } from '@/apis'
|
||||
import type { SessionField } from '@/apis/auth/auth.type'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
|
||||
// 타결 요약의 '동의' 단계 하단 액션바 = 부가정보 입력 + 동의를 한 자리에서.
|
||||
// 다른 입력(가격·배송)과 같은 자리에서 받는다. proceedText = 동의 문구(누르면 저장 후 그 텍스트로 협상 종료).
|
||||
// 필드 정의(session_fields)가 없으면 폼 없이 동의 버튼만 둔다. 저장 후에도 세션 목록에서 수정할 수 있다.
|
||||
export function ExtraInfoBar({ proceedText }: { proceedText: string }) {
|
||||
const sessionId = useChatStore((s) => s.sessionId)
|
||||
const sendMessage = useChatStore((s) => s.sendMessage)
|
||||
const { data: user } = useMeQuery()
|
||||
const fields: SessionField[] = user?.sessionFields ?? []
|
||||
const save = useSaveExtraInfoMutation()
|
||||
const existing = useChatInitStore((s) => s.custom) // 기존 입력값(재진입 프리필)
|
||||
const setInitData = useChatInitStore((s) => s.setInitData)
|
||||
// 의견은 session_fields 와 무관한 공통 필드 — 타결·결렬 모두 항상 받는다. custom.opinion 에 저장.
|
||||
const [opinion, setOpinion] = useState<string | null>(null)
|
||||
const opinionValue = opinion ?? String(existing?.opinion ?? '')
|
||||
|
||||
// 사용자가 건드린 값만 state 로 두고, 나머지는 기존값/기본값에서 렌더마다 파생한다(초기화 effect 불필요).
|
||||
const [overrides, setOverrides] = useState<Record<string, unknown>>({})
|
||||
const values: Record<string, unknown> = {}
|
||||
for (const f of fields) values[f.key] = overrides[f.key] ?? existing?.[f.key] ?? (f.type === 'boolean' ? false : '')
|
||||
|
||||
const proceed = () => sendMessage(proceedText)
|
||||
|
||||
const set = (key: string, value: unknown) => setOverrides((v) => ({ ...v, [key]: value }))
|
||||
|
||||
// 저장 성공 후에만 동의(협상 종료)로 넘어간다 — 저장 실패 시 화면 유지.
|
||||
const handleSaveAndProceed = () => {
|
||||
if (save.isPending) return
|
||||
const custom: Record<string, unknown> = {}
|
||||
for (const f of fields) {
|
||||
const v = values[f.key]
|
||||
if (f.type === 'boolean') custom[f.key] = !!v
|
||||
else if (v !== '' && v != null) custom[f.key] = f.type === 'number' ? Number(v) : v
|
||||
}
|
||||
if (opinionValue.trim()) custom.opinion = opinionValue.trim()
|
||||
if (Object.keys(custom).length === 0) { proceed(); return } // 입력 없음 → 저장 생략하고 종료
|
||||
save.mutate(
|
||||
{ sessionId, request: { custom } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setInitData({ custom: { ...existing, ...custom } }) // 요약 카드가 방금 입력값을 즉시 반영하도록 store 갱신
|
||||
proceed()
|
||||
},
|
||||
onError: (error) => toast.error(getApiErrorMessage(error, '부가정보 저장에 실패했습니다.')),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<p className="mb-3 text-sm font-semibold text-neutral-90">아래 정보를 입력하고 협상을 마무리해 주세요.</p>
|
||||
{/* overflow-y-auto 는 overflow-x 도 auto 로 만들어(스펙상) 인풋 focus ring 을 좌우로 잘라낸다.
|
||||
p-1 로 링 여백을 주고 -m-1 로 원래 정렬(버튼과 좌우폭)을 유지한다. */}
|
||||
<div className="max-h-[36vh] space-y-3 overflow-y-auto p-1 -m-1">
|
||||
{fields.map((f) => (
|
||||
<div key={f.key} className="flex items-center gap-3">
|
||||
<label className="w-28 shrink-0 text-sm font-semibold text-neutral-80">{f.label}</label>
|
||||
{f.type === 'boolean' ? (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={!!values[f.key]}
|
||||
onClick={() => set(f.key, !values[f.key])}
|
||||
className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors ${
|
||||
values[f.key] ? 'bg-brand-600' : 'bg-neutral-30'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block size-5 transform rounded-full bg-white shadow transition-transform ${
|
||||
values[f.key] ? 'translate-x-5' : 'translate-x-0.5'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
) : f.type === 'select' ? (
|
||||
<select
|
||||
value={String(values[f.key] ?? '')}
|
||||
onChange={(e) => set(f.key, e.target.value)}
|
||||
className="h-10 w-full rounded-xl border border-border bg-white px-3 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600"
|
||||
>
|
||||
<option value="">선택</option>
|
||||
{(f.options ?? []).map((o) => (
|
||||
<option key={o} value={o}>{o}</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
type={f.type === 'number' ? 'number' : 'text'}
|
||||
value={String(values[f.key] ?? '')}
|
||||
onChange={(e) => set(f.key, e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && !e.nativeEvent.isComposing && handleSaveAndProceed()}
|
||||
className="h-10 w-full rounded-xl border border-border bg-white px-3 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600"
|
||||
placeholder={f.label}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{/* 의견 — 타결·결렬 공통 필드(IMK #18). custom.opinion 저장. */}
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-sm font-semibold text-neutral-80">
|
||||
의견 <span className="font-normal text-neutral-50">(선택)</span>
|
||||
</label>
|
||||
<textarea
|
||||
value={opinionValue}
|
||||
onChange={(e) => setOpinion(e.target.value)}
|
||||
rows={2}
|
||||
maxLength={255}
|
||||
placeholder="추가로 남길 의견이 있으면 작성해 주세요."
|
||||
className="w-full resize-none rounded-xl border border-border bg-white px-3 py-2 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" onClick={handleSaveAndProceed} disabled={save.isPending} className={`${PRIMARY} mt-3 w-full`}>
|
||||
{save.isPending ? '저장 중…' : proceedText || '저장하고 마무리'}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const PRIMARY =
|
||||
'h-[46px] min-w-[120px] rounded-xl bg-brand-600 px-6 text-sm font-bold text-white shadow-sm transition-all hover:bg-brand-700 active:scale-[0.98] disabled:opacity-50'
|
||||
@@ -8,34 +8,33 @@ export function ItemImage() {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full items-center justify-center pt-16 pr-8 pb-8 pl-8">
|
||||
<div className="px-5 pt-5 pb-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsOpen(true)}
|
||||
aria-label="이미지 크게 보기"
|
||||
className="relative cursor-pointer group"
|
||||
className="group relative block aspect-square w-full overflow-hidden rounded-2xl border border-border bg-neutral-10 shadow-inner"
|
||||
>
|
||||
<Thumb src={item_image} />
|
||||
<div className="absolute inset-0 flex items-center justify-center rounded-[16px] bg-neutral-40 opacity-0 transition-opacity duration-300 group-hover:opacity-90">
|
||||
<span className="text-neutral-00 text-base font-medium">이미지 크게 보기</span>
|
||||
</div>
|
||||
{item_image ? (
|
||||
<img
|
||||
src={item_image}
|
||||
alt="상품 이미지"
|
||||
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center text-neutral-40">
|
||||
<ImageIcon size={40} strokeWidth={1.5} />
|
||||
</div>
|
||||
)}
|
||||
<span className="absolute left-2 top-2 rounded-md bg-neutral-90/65 px-2 py-0.5 text-[10px] font-bold text-white backdrop-blur-sm">
|
||||
상세 품목
|
||||
</span>
|
||||
</button>
|
||||
{isOpen && <ImageModal src={item_image} onClose={() => setIsOpen(false)} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Thumb({ src }: { src: string }) {
|
||||
if (src) {
|
||||
return <img src={src} alt="상품 이미지" className="rounded-[16px] w-[220px] h-[220px] max-[1180px]:w-[200px] max-[1180px]:h-[200px] object-cover" />
|
||||
}
|
||||
return (
|
||||
<div className="flex w-[220px] h-[220px] max-[1180px]:w-[200px] max-[1180px]:h-[200px] items-center justify-center rounded-[16px] bg-neutral-20 text-neutral-60">
|
||||
<ImageIcon size={48} strokeWidth={1.5} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ImageModal({ src, onClose }: { src: string; onClose: () => void }) {
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
||||
@@ -53,9 +52,9 @@ function ImageModal({ src, onClose }: { src: string; onClose: () => void }) {
|
||||
>
|
||||
<div className="relative" onClick={(e) => e.stopPropagation()}>
|
||||
{src ? (
|
||||
<img src={src} alt="상품 이미지" className="rounded-[16px] max-w-[42rem] max-h-[90vh] object-contain" />
|
||||
<img src={src} alt="상품 이미지" className="max-h-[90vh] max-w-[42rem] rounded-2xl object-contain" />
|
||||
) : (
|
||||
<div className="flex w-[60vmin] h-[60vmin] max-w-[42rem] max-h-[90vh] items-center justify-center rounded-[16px] bg-neutral-20 text-neutral-60">
|
||||
<div className="flex h-[60vmin] max-h-[90vh] w-[60vmin] max-w-[42rem] items-center justify-center rounded-2xl bg-neutral-20 text-neutral-50">
|
||||
<ImageIcon size={96} strokeWidth={1.25} />
|
||||
</div>
|
||||
)}
|
||||
@@ -63,9 +62,9 @@ function ImageModal({ src, onClose }: { src: string; onClose: () => void }) {
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="닫기"
|
||||
className="absolute top-4 right-4 flex items-center justify-center w-9 h-9 rounded-full bg-white border border-neutral-30 text-neutral-80 cursor-pointer hover:bg-neutral-10 transition-colors"
|
||||
className="absolute right-3 top-3 flex size-9 items-center justify-center rounded-full border border-border bg-white text-neutral-80 transition-colors hover:bg-neutral-10"
|
||||
>
|
||||
<X size={20} />
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</div>,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useState, useCallback, useRef, useEffect } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { cn } from '@/lib'
|
||||
import { ItemImage } from '@/features/chat/components/ItemImage'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
import { formatLeadTime } from '@/features/chat/lib/format'
|
||||
@@ -39,14 +38,17 @@ function ItemInfo() {
|
||||
const {
|
||||
item_code,
|
||||
item_price,
|
||||
item_vat_yn,
|
||||
item_model_name,
|
||||
item_maker_name,
|
||||
item_min_order_quantity,
|
||||
item_lead_time,
|
||||
item_spec,
|
||||
item_name,
|
||||
item_vat_yn,
|
||||
labels,
|
||||
} = useChatInitStore()
|
||||
// 회사 설정 라벨(companies.settings.labels)로 필드명 치환. 미설정 시 기본 라벨.
|
||||
const fieldLabel = (key: string, fallback: string) => labels?.[key] || fallback
|
||||
|
||||
const [tooltip, setTooltip] = useState<TooltipState | null>(null)
|
||||
const hideTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
@@ -72,21 +74,21 @@ function ItemInfo() {
|
||||
const formatPrice = (price: number) => price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||||
const isNewItem = !item_code && !item_price
|
||||
const priceText = isNewItem ? '신규' : `${formatPrice(item_price)}원`
|
||||
const formattedPrice = `${priceText}(${item_vat_yn || 'VAT별도'})`
|
||||
// VAT 표기는 회사 설정 기준(item_vat_yn). vat_yn 미관리(hidden)면 값이 비어 라벨을 생략한다.
|
||||
const formattedPrice = item_vat_yn ? `${priceText}(${item_vat_yn})` : priceText
|
||||
|
||||
const renderRow = (title: string, data: string, important = false) => {
|
||||
const textClass = important ? 'title-3 text-neutral-90' : 'body-3 text-neutral-70'
|
||||
const renderRow = (title: string, data: string) => {
|
||||
const displayData = data || '-'
|
||||
return (
|
||||
<div className="flex items-start self-stretch gap-1 min-w-0">
|
||||
<div className={cn(textClass, 'w-[100px]')}>{title}</div>
|
||||
<div
|
||||
className={cn(textClass, 'flex-1 min-w-0 break-words break-keep cursor-default')}
|
||||
<div className="flex items-start justify-between gap-3 self-stretch border-b border-border/60 py-2 last:border-0 min-w-0">
|
||||
<span className="shrink-0 text-[13px] text-neutral-60">{title}</span>
|
||||
<span
|
||||
className="min-w-0 flex-1 break-words break-keep text-right text-[13px] font-semibold text-neutral-90 cursor-default"
|
||||
onMouseEnter={(e) => displayData !== '-' && showTooltip(e, displayData)}
|
||||
onMouseLeave={hideTooltip}
|
||||
>
|
||||
{displayData}
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -94,31 +96,35 @@ function ItemInfo() {
|
||||
return (
|
||||
<div className="flex flex-col w-full flex-1 overflow-hidden min-h-0">
|
||||
<div
|
||||
className="text-center headline-3 text-neutral-90 mb-4 truncate px-8 flex-shrink-0 cursor-default"
|
||||
className="mb-3 flex-shrink-0 truncate px-6 text-left text-sm font-bold text-neutral-90 cursor-default"
|
||||
onMouseEnter={(e) => item_name && showTooltip(e, item_name)}
|
||||
onMouseLeave={hideTooltip}
|
||||
>
|
||||
{item_name}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 items-start self-stretch mr-2 overflow-y-auto overflow-x-hidden pr-6 pl-8 min-h-0">
|
||||
<div className="flex flex-col items-start self-stretch flex-1 gap-2 min-w-0">
|
||||
{renderRow('상품코드', item_code, true)}
|
||||
{renderRow('단가', formattedPrice, true)}
|
||||
{renderRow('모델명', item_model_name, true)}
|
||||
{renderRow('제조사', item_maker_name)}
|
||||
{renderRow('최소주문수량', item_min_order_quantity)}
|
||||
{renderRow('리드타임', formatLeadTime(item_lead_time))}
|
||||
<div className="mb-2 flex-shrink-0 border-b border-border px-6 pb-2">
|
||||
<span className="text-[11px] font-extrabold tracking-wider text-neutral-50">품목 정보</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start self-stretch gap-1 flex-[1_0]">
|
||||
<div className="body-3 text-neutral-70 w-[100px]">규격</div>
|
||||
<div
|
||||
className="body-3 text-neutral-70 self-stretch w-0 flex-[1_0] overflow-hidden whitespace-normal break-words break-keep cursor-default"
|
||||
<div className="flex flex-1 items-start self-stretch overflow-y-auto overflow-x-hidden px-6 min-h-0">
|
||||
<div className="flex flex-col items-start self-stretch flex-1 gap-2 min-w-0">
|
||||
{renderRow(fieldLabel('item.code', '상품코드'), item_code)}
|
||||
{renderRow(fieldLabel('item.price', '단가'), formattedPrice)}
|
||||
{renderRow(fieldLabel('item.model_name', '모델명'), item_model_name)}
|
||||
{renderRow(fieldLabel('item.manufacturer', '제조사'), item_maker_name)}
|
||||
{renderRow(fieldLabel('item.moq', '최소주문수량'), item_min_order_quantity)}
|
||||
{renderRow(fieldLabel('lead_time', '리드타임'), formatLeadTime(item_lead_time))}
|
||||
|
||||
<div className="flex items-start justify-between gap-3 self-stretch py-2">
|
||||
<span className="shrink-0 text-sm text-neutral-60">{fieldLabel('item.spec', '규격')}</span>
|
||||
<span
|
||||
className="min-w-0 flex-1 overflow-hidden whitespace-normal break-words break-keep text-right text-[13px] font-semibold text-neutral-90 cursor-default"
|
||||
onMouseEnter={(e) => item_spec && showTooltip(e, item_spec, true)}
|
||||
onMouseLeave={hideTooltip}
|
||||
>
|
||||
{item_spec || '-'}
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { type ReactNode, useEffect } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { X } from 'lucide-react'
|
||||
import { cn } from '@/lib'
|
||||
|
||||
interface MobileDrawerProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
side?: 'left' | 'right'
|
||||
title: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
// 모바일 전용 슬라이드 드로어(lg 미만). 데스크톱에선 절대 노출되지 않도록 lg:hidden 을 강제한다.
|
||||
export function MobileDrawer({ open, onClose, side = 'left', title, children }: MobileDrawerProps) {
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [open, onClose])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return createPortal(
|
||||
<div className="fixed inset-0 z-[60] lg:hidden">
|
||||
<div className="absolute inset-0 bg-black/50 animate-fade-in" onClick={onClose} />
|
||||
<div
|
||||
className={cn(
|
||||
'absolute top-0 bottom-0 flex w-[88%] max-w-[360px] flex-col bg-white shadow-xl',
|
||||
side === 'left' ? 'left-0' : 'right-0',
|
||||
)}
|
||||
>
|
||||
<div className="flex h-14 box-content safe-t shrink-0 items-center justify-between border-b border-border px-5">
|
||||
<span className="text-base font-bold text-neutral-90">{title}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="닫기"
|
||||
className="flex size-8 items-center justify-center rounded-full text-neutral-60 hover:bg-neutral-10"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto safe-b">{children}</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Check } from 'lucide-react'
|
||||
import { cn } from '@/lib'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { STEPS } from '@/features/chat/lib/negoSteps'
|
||||
|
||||
// 모바일 전용: 협상절차를 채팅 상단에 가로 스텝바로 항상 표시한다. (데스크톱은 우측 패널 사용)
|
||||
export function MobileStepBar() {
|
||||
const chats = useChatStore((s) => s.messages)
|
||||
const currentStep = chats[chats.length - 1]?.display_step || STEPS[0].name
|
||||
const idx = Math.max(
|
||||
0,
|
||||
STEPS.findIndex((s) => s.name === currentStep),
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="shrink-0 border-b border-border bg-white px-4 py-2.5 lg:hidden">
|
||||
<div className="flex items-center">
|
||||
{STEPS.map((step, i) => {
|
||||
const done = i < idx
|
||||
const current = i === idx
|
||||
return (
|
||||
<div key={step.name} className={cn('flex items-center', i < STEPS.length - 1 && 'flex-1')}>
|
||||
<div
|
||||
className={cn(
|
||||
'flex size-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold transition-colors',
|
||||
done && 'bg-success text-white',
|
||||
current && 'bg-brand-600 text-white ring-4 ring-brand-light',
|
||||
!done && !current && 'border border-border bg-white text-neutral-50',
|
||||
)}
|
||||
>
|
||||
{done ? <Check className="size-3" strokeWidth={3} /> : i + 1}
|
||||
</div>
|
||||
{i < STEPS.length - 1 && (
|
||||
<div className={cn('mx-1 h-0.5 flex-1 rounded-full', i < idx ? 'bg-success' : 'bg-neutral-20')} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<p className="mt-1.5 truncate text-[11px] font-bold text-brand-600">
|
||||
{idx + 1}. {STEPS[idx].name}
|
||||
<span className="ml-1 font-normal text-neutral-50">{STEPS[idx].desc}</span>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import { cn } from '@/lib'
|
||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
import { SelectRadio, SubmitButton } from '@/features/chat/components/templates/rejectControls'
|
||||
import { OtherReason } from '@/features/chat/components/templates/OtherReason'
|
||||
import { findRestoreScript, restoreRejectRSP, extractPart } from '@/features/chat/lib/rejectForm'
|
||||
|
||||
const MAX_PRICE = 999999999999999
|
||||
|
||||
// 합의 불가 사유 프리셋 (rejectRSP 와 동일 목록)
|
||||
const REASONS = [
|
||||
{ value: '단가인상', text: "'원재료 가격 상승' 또는 '제조사 가격 인상'으로 요청한 공급가격을 맞출 수 없습니다." },
|
||||
{ value: '수량', text: '주문 수량이 적어, 소량 생산 시 발생하는 제조비용으로 맞출 수 없습니다.' },
|
||||
{ value: '단종', text: '현재 단종된 제품으로 물량 수급이 원활하지 않아 가격을 맞출 수 없습니다.' },
|
||||
{ value: '품절', text: '해당 상품이 품절되어 납품할 수 없습니다.' },
|
||||
]
|
||||
|
||||
// 통일된 협상 결렬 폼 — 최종 제안 단가 + 합의 불가 사유 + 의견.
|
||||
// rejectRSP / rejectCM 두 유형 모두 이 폼 하나로 받는다(액션바 렌더).
|
||||
export function RejectForm() {
|
||||
const isLoading = useChatStore((s) => s.isLoading)
|
||||
const sendMessage = useChatStore((s) => s.sendMessage)
|
||||
const messages = useChatStore((s) => s.messages)
|
||||
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
|
||||
const isVAT = item_vat_yn === 'VAT별도'
|
||||
|
||||
// 직전 제출 내역에서 1회 복원 (rejectRSP/rejectCM 어느 유형이든).
|
||||
const priorScript = useState(
|
||||
() => findRestoreScript(messages, 'rejectRSP') ?? findRestoreScript(messages, 'rejectCM'),
|
||||
)[0]
|
||||
const restored = useState(() => restoreRejectRSP(priorScript))[0]
|
||||
const [price, setPrice] = useState(restored.price)
|
||||
const [selectedReason, setSelectedReason] = useState(restored.selectedReason)
|
||||
const [reason, setReason] = useState(restored.reason)
|
||||
const [opinion, setOpinion] = useState(() => extractPart(priorScript, '의견-'))
|
||||
const [otherErrorMessage, setOtherErrorMessage] = useState('')
|
||||
const [priceErrorMessage, setPriceErrorMessage] = useState('')
|
||||
const [radioErrorMessage, setRadioErrorMessage] = useState('')
|
||||
|
||||
const isSubmitted = useMemo(
|
||||
() => Boolean(findRestoreScript(messages, 'rejectRSP') ?? findRestoreScript(messages, 'rejectCM')),
|
||||
[messages],
|
||||
)
|
||||
// 사유는 필수(20번), 의견은 선택(18번).
|
||||
const isValid =
|
||||
Boolean(price && parseInt(price) > 0) &&
|
||||
Boolean(selectedReason) &&
|
||||
(selectedReason !== '기타' || reason.trim() !== '')
|
||||
|
||||
const handlePriceChange = (value: string) => {
|
||||
const numeric = value.replace(/\D/g, '')
|
||||
if (numeric && parseInt(numeric) > MAX_PRICE) return
|
||||
setPrice(numeric)
|
||||
if (numeric) setPriceErrorMessage('')
|
||||
}
|
||||
|
||||
const handleRadioChange = (value: string) => {
|
||||
setSelectedReason(value)
|
||||
setRadioErrorMessage('')
|
||||
if (value !== '기타') {
|
||||
setReason('')
|
||||
setOtherErrorMessage('')
|
||||
}
|
||||
}
|
||||
|
||||
const koreanPrice = (() => {
|
||||
if (!price) return '영'
|
||||
const n = parseInt(price)
|
||||
return Number.isNaN(n) || n === 0 ? '영' : numberToKorean(n)
|
||||
})()
|
||||
|
||||
const handleSubmit = () => {
|
||||
setPriceErrorMessage(!price || parseInt(price) === 0 ? '가격을 입력해주세요.' : '')
|
||||
setRadioErrorMessage(!selectedReason ? '사유를 선택해주세요.' : '')
|
||||
setOtherErrorMessage(selectedReason === '기타' && !reason.trim() ? '기타 사유를 입력해주세요.' : '')
|
||||
if (isValid && !isLoading && !isSubmitted) {
|
||||
const reasonPart =
|
||||
selectedReason === '기타' ? `합의불가사유-기타-${reason.trim()}` : `합의불가사유-${selectedReason}`
|
||||
const script = `공급희망가격-${price}, ${reasonPart}, 의견-${opinion.trim()}`
|
||||
sendMessage(script, 'text')
|
||||
}
|
||||
}
|
||||
|
||||
const isDisabled = isLoading || isSubmitted
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<div className="flex flex-col w-full gap-2">
|
||||
<div className="flex w-full items-center justify-center gap-2 rounded-xl bg-[#FFF1F1] px-4 py-3 text-sm font-bold text-[#E5484D]">
|
||||
<AlertTriangle className="size-5 shrink-0" />
|
||||
협상 합의 불가 사유 및 최종 제안 단가 입력
|
||||
</div>
|
||||
|
||||
<div className="max-h-[42vh] space-y-2 overflow-y-auto p-1 -m-1">
|
||||
{/* 공급 희망 가격 */}
|
||||
<div className="flex flex-col w-full gap-1">
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<div className="w-[100px] shrink-0 pt-2.5 text-sm font-bold text-neutral-90">공급 희망 가격</div>
|
||||
<div className="flex w-full flex-wrap items-center gap-2 pt-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
className={cn(
|
||||
'h-10 max-w-[200px] rounded-xl border px-3 text-right text-sm outline-none transition-all placeholder:text-neutral-50',
|
||||
isDisabled
|
||||
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
|
||||
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
|
||||
)}
|
||||
value={price ? parseInt(price).toLocaleString() : ''}
|
||||
onChange={(e) => handlePriceChange(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && !e.nativeEvent.isComposing && handleSubmit()}
|
||||
placeholder="0"
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<div className="whitespace-nowrap text-sm text-neutral-70">원{isVAT && '(VAT 별도)'}</div>
|
||||
</div>
|
||||
<div className="whitespace-nowrap text-sm text-neutral-50">[{koreanPrice} 원]</div>
|
||||
</div>
|
||||
</div>
|
||||
{priceErrorMessage && (
|
||||
<div className="pl-[112px] text-xs font-medium text-negative">{priceErrorMessage}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 합의 불가 사유 (필수) */}
|
||||
<div className="flex w-full gap-3">
|
||||
<div className="w-[100px] shrink-0 pt-2 text-sm font-bold text-neutral-90">합의 불가 사유</div>
|
||||
<div className="flex w-full flex-col mt-2 gap-2">
|
||||
{REASONS.map((r) => (
|
||||
<SelectRadio
|
||||
key={r.value}
|
||||
text={r.text}
|
||||
value={r.value}
|
||||
name="rejectform"
|
||||
selectedValue={selectedReason}
|
||||
onChange={handleRadioChange}
|
||||
errorMessage={radioErrorMessage}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
))}
|
||||
<OtherReason
|
||||
inputValue={reason}
|
||||
setInputValue={(v) => {
|
||||
if (selectedReason !== '기타') return
|
||||
setReason(v)
|
||||
if (v.trim()) setOtherErrorMessage('')
|
||||
}}
|
||||
errorMessage={otherErrorMessage}
|
||||
selectedValue={selectedReason}
|
||||
onChange={handleRadioChange}
|
||||
isError={!!radioErrorMessage}
|
||||
disabled={isDisabled}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 의견 (선택) — 타결·결렬 공통 */}
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<div className="w-[100px] shrink-0 pt-2 text-sm font-bold text-neutral-90">의견</div>
|
||||
<textarea
|
||||
value={opinion}
|
||||
onChange={(e) => setOpinion(e.target.value)}
|
||||
rows={2}
|
||||
maxLength={255}
|
||||
disabled={isDisabled}
|
||||
placeholder="추가로 남길 의견이 있으면 작성해 주세요. (선택)"
|
||||
className={cn(
|
||||
'mt-2 w-full resize-none rounded-xl border px-3 py-2 text-sm outline-none transition-all placeholder:text-neutral-50',
|
||||
isDisabled
|
||||
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
|
||||
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full items-center justify-center mt-2">
|
||||
<SubmitButton isValid={isValid} isLoading={isLoading} isSubmitted={isSubmitted} onSubmit={handleSubmit} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Clock } from 'lucide-react'
|
||||
import { cn } from '@/lib'
|
||||
import { getTimeRemaining } from '@/features/chat/lib/remainingTime'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
|
||||
// 헤더의 협상 잔여 시간. 1초마다 tick 을 올려 렌더 중 남은 시간을 다시 계산한다.
|
||||
// 헤더의 협상 잔여 시간 칩. 1초마다 tick 을 올려 렌더 중 남은 시간을 다시 계산한다.
|
||||
export function RemainingTime() {
|
||||
const { quotation_end_time } = useChatInitStore()
|
||||
const [, setTick] = useState(0)
|
||||
@@ -13,6 +15,28 @@ export function RemainingTime() {
|
||||
}, [])
|
||||
|
||||
const remaining = quotation_end_time ? getTimeRemaining(quotation_end_time) : '-'
|
||||
const ended = remaining === '종료되었습니다.' || remaining === '-'
|
||||
|
||||
return <span className="title-1">협상 잔여 시간 : {remaining}</span>
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
// min-w-0 + truncate: 헤더가 좁아도 잘려나가지 않고 말줄임으로 접힌다.
|
||||
'inline-flex min-w-0 shrink items-center gap-1.5 rounded-full px-3 py-1 text-xs font-bold tabular-nums',
|
||||
ended ? 'bg-neutral-20 text-neutral-60' : 'bg-brand-light text-brand-600',
|
||||
)}
|
||||
>
|
||||
<Clock className="size-3.5 shrink-0" />
|
||||
<span className="truncate">
|
||||
{ended ? (
|
||||
// 종료 시엔 어느 폭에서도 긴 문장('종료되었습니다.')을 쓰지 않는다 — 헤더에서 잘리던 원인.
|
||||
'마감 종료'
|
||||
) : (
|
||||
<>
|
||||
<span className="hidden sm:inline">협상 마감 </span>
|
||||
{remaining}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -1,44 +1,57 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { List } from 'lucide-react'
|
||||
import { cn } from '@/lib'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { Percent, Price } from '@/features/chat/components/userInputs'
|
||||
import { ExtraInfoBar } from '@/features/chat/components/ExtraInfoBar'
|
||||
import { RejectForm } from '@/features/chat/components/RejectForm'
|
||||
import { GO_TO_LIST_TEXT } from '@/features/chat/lib/userButtonConfig'
|
||||
import type { UserButtonConfig } from '@/features/chat/types'
|
||||
|
||||
// max-[1180px]: 채팅 폭이 좁아지면 버튼 패딩·최소폭 축소, 상품목록은 아이콘만 남긴다
|
||||
const style = {
|
||||
goToList:
|
||||
'flex w-[159px] max-[1180px]:w-[48px] h-[48px] bg-neutral-40 hover:brightness-[0.97] rounded-[999px] items-center justify-center title-2 text-neutral-80 cursor-pointer gap-2 max-[1180px]:gap-0 transition-all ease-out hover:scale-[1.01]',
|
||||
black:
|
||||
'flex min-w-[120px] px-[32px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[48px] bg-primary hover:brightness-[0.97] rounded-[999px] items-center justify-center title-2 text-primary-foreground cursor-pointer whitespace-nowrap transition-all duration-200 ease-out hover:scale-[1.01]',
|
||||
gray: 'flex min-w-[120px] px-[32px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[48px] bg-neutral-60 rounded-[999px] items-center justify-center title-2 text-neutral-00 cursor-pointer whitespace-nowrap transition-all ease-out hover:scale-[1.01]',
|
||||
'flex min-w-[120px] px-[28px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[46px] bg-brand-600 hover:bg-brand-700 rounded-xl items-center justify-center text-sm font-bold text-white shadow-sm cursor-pointer whitespace-nowrap transition-all duration-200 ease-out active:scale-[0.98]',
|
||||
gray: 'flex min-w-[120px] px-[28px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[46px] bg-neutral-60 hover:brightness-[0.97] rounded-xl items-center justify-center text-sm font-bold text-white cursor-pointer whitespace-nowrap transition-all ease-out active:scale-[0.98]',
|
||||
white:
|
||||
'flex min-w-[120px] px-[32px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[48px] bg-neutral-00 rounded-[999px] items-center justify-center title-2 text-neutral-80 border border-neutral-80 cursor-pointer whitespace-nowrap transition-all ease-out hover:scale-[1.01]',
|
||||
'flex min-w-[120px] px-[28px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[46px] bg-white hover:bg-neutral-10 rounded-xl items-center justify-center text-sm font-bold text-neutral-80 border border-border cursor-pointer whitespace-nowrap transition-all ease-out active:scale-[0.98]',
|
||||
}
|
||||
|
||||
export function UserButton({ type, text, textList, priceErrorMessage }: UserButtonConfig) {
|
||||
if (type === '') return null
|
||||
|
||||
// 부가정보 입력은 폼이라 가운데정렬 덱이 아니라 전체폭으로 편다. text = 저장 후 보낼 동의 문구.
|
||||
if (type === 'extra-info') {
|
||||
return (
|
||||
<div className="w-full px-6 py-4 max-[1180px]:px-4">
|
||||
<ExtraInfoBar proceedText={text || ''} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 결렬 통일 폼 — 부가정보와 같은 자리(액션바)에서 전체폭으로.
|
||||
if (type === 'reject') {
|
||||
return (
|
||||
<div className="w-full px-6 py-4 max-[1180px]:px-4">
|
||||
<RejectForm />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 입력 단계는 에러 말풍선이 위로 삐져나가야 해서 overflow 클리핑 제외 (버튼 덱만 가로 스크롤 허용)
|
||||
const isInputStep = type === 'percent' || type === 'price'
|
||||
return (
|
||||
// pr-[16px]: 채팅 스크롤 영역(ChatMessage 바깥 pr-[16px])과 오른쪽 끝 정렬
|
||||
<div className="flex w-full pb-[52px] pr-[16px]">
|
||||
<div className="grid grid-cols-[1fr_auto_1fr] items-center w-full">
|
||||
<div />
|
||||
<div className="flex justify-center">
|
||||
{type === 'one-black' && <OneBlack text={text || '확인'} />}
|
||||
{type === 'one-gray' && <OneGray text={text || '확인'} />}
|
||||
{type === 'black-white' && <BlackWhite textList={[textList?.[0] || '예', textList?.[1] || '아니오']} />}
|
||||
{type === 'percent' && <Percent />}
|
||||
{type === 'three-black' && (
|
||||
<ThreeBlack textList={[textList?.[0] || '협력사배송', textList?.[1] || '지정택배배송', textList?.[2] || '픽업배송']} />
|
||||
)}
|
||||
{type === 'price' && <Price priceErrorMessage={priceErrorMessage} />}
|
||||
{type === 'loading' && <LoadingDots />}
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<GoToList />
|
||||
</div>
|
||||
<div className={cn('flex w-full justify-center px-6 py-4 max-[1180px]:px-4', !isInputStep && 'overflow-x-auto')}>
|
||||
<div className="flex justify-center">
|
||||
{type === 'one-black' && <OneBlack text={text || '확인'} />}
|
||||
{type === 'one-gray' && <OneGray text={text || '확인'} />}
|
||||
{type === 'black-white' && <BlackWhite textList={[textList?.[0] || '예', textList?.[1] || '아니오']} />}
|
||||
{type === 'percent' && <Percent />}
|
||||
{type === 'three-black' && (
|
||||
<ThreeBlack textList={[textList?.[0] || '협력사배송', textList?.[1] || '지정택배배송', textList?.[2] || '픽업배송']} />
|
||||
)}
|
||||
{type === 'price' && <Price priceErrorMessage={priceErrorMessage} />}
|
||||
{type === 'loading' && <LoadingDots />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -57,16 +70,6 @@ function LoadingDots() {
|
||||
)
|
||||
}
|
||||
|
||||
function GoToList() {
|
||||
const navigate = useNavigate()
|
||||
return (
|
||||
<button className={style.goToList} onClick={() => navigate('/list')} aria-label="상품 목록으로 이동" title="상품 목록">
|
||||
<List size={24} className="shrink-0" />
|
||||
<span className="max-[1180px]:hidden">상품 목록</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function OneBlack({ text }: { text: string }) {
|
||||
const navigate = useNavigate()
|
||||
const sendMessage = useChatStore((s) => s.sendMessage)
|
||||
@@ -102,6 +105,18 @@ function ThreeBlack({ textList }: { textList: [string, string, string] }) {
|
||||
|
||||
function BlackWhite({ textList }: { textList: [string, string] }) {
|
||||
const sendMessage = useChatStore((s) => s.sendMessage)
|
||||
// Enter = 첫 버튼(예). 입력창이 없는 선택 단계라 전역 Enter 를 잡아도 안전하다.
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.isComposing) {
|
||||
e.preventDefault()
|
||||
sendMessage(textList[0])
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [sendMessage, textList])
|
||||
|
||||
return (
|
||||
<div className="flex gap-3">
|
||||
<button className={style.black} onClick={() => sendMessage(textList[0])}>
|
||||
|
||||
@@ -1,28 +1,14 @@
|
||||
import { useState } from 'react'
|
||||
import { interactive, cn } from '@/lib'
|
||||
import { ServiceGuidePopup } from '@/features/chat/components/popup/ServiceGuidePopup'
|
||||
|
||||
// 헬프데스크 — 이용 가이드 버튼 클릭 시 안내 팝업을 연다.
|
||||
// 헬프데스크 — 연락처. (안내 팝업 진입은 상단 '유의사항 및 이용방법' 섹션으로 일원화)
|
||||
export function Contact() {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full pl-[24px] pb-[24px]">
|
||||
<div className="flex flex-col w-full gap-2">
|
||||
<div className="title-5 text-neutral-80">헬프 데스크</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsOpen(true)}
|
||||
className={cn('body-5 text-neutral-80 bg-neutral-40 rounded-[8px] px-[12px] py-[6px] w-fit', interactive)}
|
||||
>
|
||||
이용 가이드
|
||||
</button>
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="body-5 text-neutral-60">010-0000-0000</div>
|
||||
<div className="body-5 text-neutral-60">o2odev@o2o.kr</div>
|
||||
</div>
|
||||
<section className="w-full pt-4">
|
||||
<div className="border-b border-border pb-2">
|
||||
<span className="text-[11px] font-bold tracking-wide text-neutral-60">헬프데스크</span>
|
||||
</div>
|
||||
{isOpen && <ServiceGuidePopup onClose={() => setIsOpen(false)} />}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 pt-3 text-sm text-neutral-60">
|
||||
<span>010-0000-0000</span>
|
||||
<span>o2odev@o2o.kr</span>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useState } from 'react'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import { interactive, cn } from '@/lib'
|
||||
import { ServiceGuidePopup } from '@/features/chat/components/popup/ServiceGuidePopup'
|
||||
|
||||
// 유의사항 및 이용방법 — 클릭 시 안내 팝업을 연다.
|
||||
@@ -12,13 +11,12 @@ export function Guide() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsOpen(true)}
|
||||
className={cn(
|
||||
'flex w-full bg-white rounded-[28px] py-[20px] pl-[24px] pr-[16px] justify-between items-center text-left',
|
||||
interactive,
|
||||
)}
|
||||
className="flex w-full items-center justify-between border-b border-border pb-2 text-left transition-colors hover:border-neutral-40"
|
||||
>
|
||||
<span className="menu-title text-neutral-80 break-keep">유의사항 및 이용방법</span>
|
||||
<ChevronRight size={20} className="text-neutral-70" />
|
||||
<span className="text-[11px] font-bold tracking-wide text-neutral-60 break-keep">
|
||||
유의사항 및 이용방법
|
||||
</span>
|
||||
<ChevronRight size={16} className="text-neutral-50" />
|
||||
</button>
|
||||
{isOpen && <ServiceGuidePopup onClose={() => setIsOpen(false)} />}
|
||||
</>
|
||||
|
||||
@@ -22,39 +22,33 @@ export function MDInformation({ isOpen, setIsOpen }: Props) {
|
||||
if (memoArray.length === 0) return null
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full min-w-[200px]">
|
||||
<div className="bg-white rounded-[28px]">
|
||||
<div className={cn('flex items-center w-full h-[4.75rem] px-4 pl-6', isOpen ? 'pt-6 pb-3' : 'py-6')}>
|
||||
<div className="flex items-center flex-1 justify-between">
|
||||
<div className="menu-title text-neutral-80">MD 안내사항</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={isOpen}
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="flex items-center justify-center w-10 h-10 cursor-pointer text-neutral-70"
|
||||
>
|
||||
<ChevronDown size={20} className={cn('transition-transform duration-300', !isOpen && 'rotate-180')} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<section className="w-full">
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={isOpen}
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="flex w-full items-center justify-between border-b border-border pb-2"
|
||||
>
|
||||
<span className="text-[11px] font-bold tracking-wide text-neutral-60">구매담당자 안내사항</span>
|
||||
<ChevronDown
|
||||
size={16}
|
||||
className={cn('text-neutral-50 transition-transform duration-300', !isOpen && '-rotate-90')}
|
||||
/>
|
||||
</button>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col items-start gap-[19px] w-full px-6 overflow-hidden transition-all duration-300 ease-in-out',
|
||||
isOpen ? 'max-h-[200px] pb-8 opacity-100' : 'max-h-0 pb-0 opacity-0',
|
||||
)}
|
||||
>
|
||||
<div className={cn('flex flex-col gap-2 items-start self-stretch max-h-[200px] break-keep', isOpen ? 'overflow-y-auto' : 'overflow-hidden')}>
|
||||
{isOpen && (
|
||||
<div className="max-h-[220px] animate-fade-in overflow-y-auto pt-3">
|
||||
<div className="flex flex-col gap-2 break-keep">
|
||||
{memoArray.map((item, i) => (
|
||||
<div key={i} className="flex items-start gap-2 body-3 text-neutral-70">
|
||||
<span className="flex-shrink-0">•</span>
|
||||
<div key={i} className="flex items-start gap-2 text-sm text-neutral-70">
|
||||
<span className="shrink-0 text-neutral-50">•</span>
|
||||
<div className="flex-1 whitespace-pre-wrap">{linkText(item)}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -63,7 +57,7 @@ function linkText(text: string) {
|
||||
const isUrl = (s: string) => /^https?:\/\/[^\s]+$/.test(s)
|
||||
const parts = text.split(urlRegex)
|
||||
return (
|
||||
<div className="body-3 text-neutral-70">
|
||||
<div className="text-sm text-neutral-70">
|
||||
{parts.map((part, i) =>
|
||||
isUrl(part) ? (
|
||||
<a
|
||||
@@ -71,7 +65,7 @@ function linkText(text: string) {
|
||||
href={part}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block text-info underline cursor-pointer hover:brightness-95 transition-all"
|
||||
className="block text-brand-600 underline transition-all hover:brightness-95"
|
||||
>
|
||||
상품 사이트로 이동
|
||||
</a>
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
import { useState } from 'react'
|
||||
import { cn } from '@/lib'
|
||||
import { MDInformation } from '@/features/chat/components/menu/MDInformation'
|
||||
import { NegoStep } from '@/features/chat/components/menu/NegoStep'
|
||||
import { Guide } from '@/features/chat/components/menu/Guide'
|
||||
import { Contact } from '@/features/chat/components/menu/Contact'
|
||||
|
||||
export function MenuSection() {
|
||||
// rail = 데스크톱 우측 고정 패널(lg+), drawer = 모바일 드로어 내부.
|
||||
// 보고서식: 박스 카드가 아니라 하나의 흰 패널 안에 납작한 섹션들을 쌓는다.
|
||||
export function MenuSection({ variant = 'rail' }: { variant?: 'rail' | 'drawer' }) {
|
||||
const [isMDOpen, setIsMDOpen] = useState(true)
|
||||
const [isStepOpen, setIsStepOpen] = useState(true)
|
||||
|
||||
const wrap =
|
||||
variant === 'rail'
|
||||
? 'hidden lg:flex flex-col w-[300px] max-[1350px]:w-[280px] max-[1180px]:w-[260px] h-full overflow-y-auto bg-white border-l border-border px-5 pt-6 pb-4'
|
||||
: 'flex flex-col w-full p-5'
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-[360px] max-[1350px]:w-[320px] max-[1180px]:w-[280px] h-full pt-[64px] pr-[24px]">
|
||||
<div className="flex flex-col flex-1 gap-[28px]">
|
||||
<div className={cn(wrap)}>
|
||||
<div className="flex flex-1 flex-col gap-6">
|
||||
<MDInformation isOpen={isMDOpen} setIsOpen={setIsMDOpen} />
|
||||
<NegoStep isOpen={isStepOpen} setIsOpen={setIsStepOpen} />
|
||||
<Guide />
|
||||
|
||||
@@ -1,52 +1,77 @@
|
||||
import { ChevronDown } from 'lucide-react'
|
||||
import { Check, ChevronDown } from 'lucide-react'
|
||||
import { cn } from '@/lib'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { STEPS } from '@/features/chat/lib/negoSteps'
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean
|
||||
setIsOpen: (isOpen: boolean) => void
|
||||
}
|
||||
|
||||
const STEPS = ['서비스안내', '담당자확인', '협상품목안내', '가격협상', '협상종료']
|
||||
|
||||
export function NegoStep({ isOpen, setIsOpen }: Props) {
|
||||
const chats = useChatStore((s) => s.messages)
|
||||
const currentStep = chats[chats.length - 1]?.display_step || '서비스안내'
|
||||
const currentIndex = Math.max(
|
||||
0,
|
||||
STEPS.findIndex((s) => s.name === currentStep),
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full min-w-[200px]">
|
||||
<div className="bg-white rounded-[28px]">
|
||||
<div className={cn('flex items-center w-full h-[4.75rem] px-4 pl-6', isOpen ? 'pt-6 pb-3' : 'py-6')}>
|
||||
<div className="flex items-center flex-1 justify-between">
|
||||
<div className="menu-title text-neutral-80">협상절차</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={isOpen}
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="flex items-center justify-center w-10 h-10 cursor-pointer text-neutral-70"
|
||||
>
|
||||
<ChevronDown size={20} className={cn('transition-transform duration-300', !isOpen && 'rotate-180')} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<section className="w-full">
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={isOpen}
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="flex w-full items-center justify-between border-b border-border pb-2"
|
||||
>
|
||||
<span className="text-[11px] font-bold tracking-wide text-neutral-60">협상절차</span>
|
||||
<ChevronDown
|
||||
size={16}
|
||||
className={cn('text-neutral-50 transition-transform duration-300', !isOpen && '-rotate-90')}
|
||||
/>
|
||||
</button>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col items-start gap-[19px] w-full px-6 overflow-hidden transition-all duration-300 ease-in-out',
|
||||
isOpen ? 'max-h-[200px] pb-8 opacity-100' : 'max-h-0 pb-0 opacity-0',
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-col gap-2 items-start self-stretch break-keep">
|
||||
{STEPS.map((step, i) => (
|
||||
<div key={step} className="flex items-start gap-2">
|
||||
<div className={cn('body-3 text-neutral-80', currentStep === step && 'font-bold')}>
|
||||
{i + 1}. {step}
|
||||
{isOpen && (
|
||||
<div className="animate-fade-in pt-4">
|
||||
<div className="relative">
|
||||
{/* 세로 레일 */}
|
||||
<span className="absolute left-[9px] top-3 bottom-3 w-0.5 bg-neutral-20" />
|
||||
{STEPS.map((step, i) => {
|
||||
const done = i < currentIndex
|
||||
const current = i === currentIndex
|
||||
return (
|
||||
<div key={step.name} className="relative flex items-start gap-3 py-1.5">
|
||||
<div
|
||||
className={cn(
|
||||
'z-10 mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold transition-all',
|
||||
done && 'bg-success text-white',
|
||||
current && 'scale-110 bg-brand-600 text-white ring-4 ring-brand-light',
|
||||
!done && !current && 'border border-border bg-white text-neutral-50',
|
||||
)}
|
||||
>
|
||||
{done ? <Check className="size-3" strokeWidth={3} /> : i + 1}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p
|
||||
className={cn(
|
||||
'text-xs leading-tight',
|
||||
current && 'font-extrabold text-brand-600',
|
||||
done && 'font-semibold text-success',
|
||||
!done && !current && 'font-medium text-neutral-80',
|
||||
)}
|
||||
>
|
||||
{step.name}
|
||||
</p>
|
||||
<p className={cn('mt-0.5 text-[10px] leading-snug', current ? 'text-brand-600/80' : 'text-neutral-50')}>
|
||||
{step.desc}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -3,14 +3,13 @@ import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
|
||||
// 협상 유의사항 및 서비스 이용 방법 안내 — 팝업 2종(자동 안내/메뉴 가이드)이 공유하는 본문.
|
||||
// VAT/배송비 문구는 채팅 init 메타(useChatInitStore)를 읽어 상품별로 동적 표시한다.
|
||||
// break-keep: 한국어 단어가 중간에서 잘려 줄바꿈되지 않도록 한다.
|
||||
const textStyle = 'text-[17px] font-normal leading-[150%] tracking-[-0.34px] text-neutral-90 break-keep'
|
||||
const bodyStyle = 'text-sm font-normal leading-relaxed text-neutral-70 break-keep'
|
||||
|
||||
function Bullet({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-start py-[6px]">
|
||||
<p className="ml-[8px] mr-[6px] flex-shrink-0">•</p>
|
||||
<div className={`${textStyle} flex-1`}>{children}</div>
|
||||
<div className="flex items-start gap-2.5 py-1.5">
|
||||
<span className="mt-[7px] size-1.5 shrink-0 rounded-full bg-brand-600" />
|
||||
<div className={`${bodyStyle} flex-1`}>{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -23,24 +22,26 @@ export function GuideContent() {
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col">
|
||||
<div className="headline-3 mb-10 break-keep text-center text-neutral-90">
|
||||
<div className="mb-5 break-keep text-center text-base font-bold text-neutral-90">
|
||||
협상 유의 사항 및 서비스 이용 방법 안내
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-start">
|
||||
<div className={`${textStyle} mb-2`}>
|
||||
협상과 관련하여 다음 사항을 참고하여 견적에 참여해 주시기 바랍니다.
|
||||
</div>
|
||||
<div className={`${bodyStyle} mb-2`}>
|
||||
협상과 관련하여 다음 사항을 참고하여 견적에 참여해 주시기 바랍니다.
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col divide-y divide-border/60 rounded-xl border border-border px-4 py-1">
|
||||
<Bullet>
|
||||
협상 개시는
|
||||
<span className="font-bold">Negosium 시스템의 협상 참여 버튼을 클릭하는 순간부터 시작</span>
|
||||
<span className="font-semibold text-neutral-90">
|
||||
Negosium 시스템의 협상 참여 버튼을 클릭하는 순간부터 시작
|
||||
</span>
|
||||
됩니다.
|
||||
</Bullet>
|
||||
|
||||
<Bullet>
|
||||
부여된 협상 시간에
|
||||
<span className="font-bold">
|
||||
<span className="font-semibold text-neutral-90">
|
||||
응찰하지 않는 경우, 협상 참여의사가 없는 것으로 간주하여 재견적으로 진행
|
||||
</span>
|
||||
될 수 있습니다.
|
||||
@@ -48,25 +49,23 @@ export function GuideContent() {
|
||||
|
||||
<Bullet>
|
||||
협상에 입력되는 모든 가격은
|
||||
<span className="font-bold text-negative">
|
||||
<span className="font-semibold text-negative">
|
||||
{vat} 및 {deliveryFee}
|
||||
</span>
|
||||
기준이며,
|
||||
<span className="font-bold">
|
||||
<span className="font-semibold text-neutral-90">
|
||||
할인을 요청하는 경우 기존 공급가격에 할인율이 적용된 가격으로 환산
|
||||
</span>
|
||||
되어 제시됩니다.
|
||||
</Bullet>
|
||||
|
||||
<Bullet>
|
||||
본 협상 결과에 대해서는 협상자와 협상대상자 간의 비밀 유지 조건으로 진행되고, 협상에서
|
||||
얻어진 결과나 내용에 대해서는 당사자를 제외하고 제 3자에 공유할 수 없으며, 비밀 유지를
|
||||
전제로 진행됩니다.
|
||||
본 협상 결과에 대해서는 협상자와 협상대상자 간의 비밀 유지 조건으로 진행되고, 협상에서 얻어진 결과나 내용에
|
||||
대해서는 당사자를 제외하고 제 3자에 공유할 수 없으며, 비밀 유지를 전제로 진행됩니다.
|
||||
</Bullet>
|
||||
|
||||
<Bullet>
|
||||
협상이 종결되면 특별한 사유 없이 취소 변경이 불가하니, 신중하게 협상에 참여해 주시기
|
||||
바랍니다.
|
||||
협상이 종결되면 특별한 사유 없이 취소 변경이 불가하니, 신중하게 협상에 참여해 주시기 바랍니다.
|
||||
</Bullet>
|
||||
|
||||
<Bullet>안내된 사항 외 부분은 기존 견적 프로세스와 동일한 부분 유의 바랍니다.</Bullet>
|
||||
@@ -78,13 +77,12 @@ export function GuideContent() {
|
||||
// 하단 문의 안내 박스
|
||||
export function GuideContactBox() {
|
||||
return (
|
||||
<div className="flex w-full flex-col items-center gap-2 rounded-[16px] bg-neutral-10 p-6">
|
||||
<div className={`${textStyle} text-center`}>
|
||||
기타 협상과정에서 궁금한 사항이나 문의하실 사항은 아래의 연락처로 상담을 부탁드립니다.
|
||||
<div className="flex w-full flex-col items-center gap-1.5 rounded-xl bg-neutral-10 p-4">
|
||||
<div className={`${bodyStyle} text-center`}>
|
||||
기타 협상 과정에서 궁금하거나 문의하실 사항은 아래 연락처로 상담 부탁드립니다.
|
||||
</div>
|
||||
{/* textStyle 의 font-normal 과 같은 요소에서 충돌하지 않도록 bold 는 별도 조합으로 준다 */}
|
||||
<div className="break-keep text-center text-[17px] font-bold leading-[150%] tracking-[-0.34px] text-neutral-90">
|
||||
헬프데스크 010-0000-0000, 이메일: o2odev@o2o.kr
|
||||
<div className="break-keep text-center text-sm font-bold text-neutral-90">
|
||||
헬프데스크 010-0000-0000 · o2odev@o2o.kr
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -7,19 +7,19 @@ import { GuideContent, GuideContactBox } from './GuideContent'
|
||||
export function ServiceGuidePopup({ onClose }: { onClose: () => void }) {
|
||||
return (
|
||||
<Modal onClose={onClose}>
|
||||
<div className="flex max-h-[90vh] w-full max-w-[1000px] flex-col items-end gap-6 overflow-y-auto rounded-3xl bg-white px-12 pb-[56px] pt-8">
|
||||
<div className="m-4 flex max-h-[90vh] w-full max-w-[720px] flex-col items-end gap-4 overflow-y-auto rounded-2xl border border-border bg-white px-6 pb-10 pt-6 shadow-xl animate-scale-in sm:px-12">
|
||||
<button
|
||||
type="button"
|
||||
aria-label="닫기"
|
||||
onClick={onClose}
|
||||
className={cn(
|
||||
'flex size-10 flex-shrink-0 items-center justify-center rounded-full bg-neutral-10',
|
||||
'flex size-9 flex-shrink-0 items-center justify-center rounded-full bg-neutral-10 text-neutral-70 hover:bg-neutral-20',
|
||||
interactive,
|
||||
)}
|
||||
>
|
||||
<X size={20} className="text-neutral-80" />
|
||||
<X size={20} />
|
||||
</button>
|
||||
<div className="flex w-full flex-col gap-6 px-[40px]">
|
||||
<div className="flex w-full flex-col gap-6">
|
||||
<GuideContent />
|
||||
<GuideContactBox />
|
||||
</div>
|
||||
|
||||
@@ -10,8 +10,8 @@ interface ServiceInfoPopupProps {
|
||||
}
|
||||
|
||||
const buttonStyle = cn(
|
||||
'flex h-[50px] w-[168px] items-center justify-center rounded-full',
|
||||
'border border-neutral-30 bg-white title-5 text-neutral-70',
|
||||
'flex h-[46px] flex-1 sm:flex-none sm:w-[168px] items-center justify-center rounded-xl',
|
||||
'border border-border bg-white text-sm font-bold text-neutral-70 hover:bg-neutral-10',
|
||||
interactive,
|
||||
)
|
||||
|
||||
@@ -20,13 +20,13 @@ export function ServiceInfoPopup({ isOpen, onNeverShowAgain, onCloseToday }: Ser
|
||||
if (!isOpen) return null
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-[rgba(0,0,0,0.40)] p-4">
|
||||
<div className="flex max-h-[90vh] w-full max-w-[1000px] flex-col overflow-y-auto rounded-[24px] bg-white px-[80px] pb-[48px] pt-[56px]">
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 backdrop-blur-[2px]">
|
||||
<div className="flex max-h-[90vh] w-full max-w-[720px] flex-col overflow-y-auto rounded-2xl border border-border bg-white px-6 pb-6 pt-8 shadow-xl animate-scale-in sm:px-12 sm:pt-10">
|
||||
<div className="mb-6 flex w-full flex-col gap-5">
|
||||
<GuideContent />
|
||||
<GuideContactBox />
|
||||
</div>
|
||||
<div className="flex w-full justify-center gap-3">
|
||||
<div className="flex w-full justify-center gap-2 sm:gap-3">
|
||||
<button type="button" className={buttonStyle} onClick={onNeverShowAgain}>
|
||||
안내 보지 않기
|
||||
</button>
|
||||
|
||||
@@ -1,61 +1,77 @@
|
||||
import { CheckCircle2 } from 'lucide-react'
|
||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||
import { useMeQuery } from '@/apis'
|
||||
import type { SessionField } from '@/apis/auth/auth.type'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
|
||||
interface BidSummaryProps {
|
||||
itemName: string
|
||||
itemCode: string
|
||||
bidPrice: number
|
||||
deliveryType: string
|
||||
isVAT: boolean
|
||||
}
|
||||
|
||||
// 투찰 결과 요약 카드
|
||||
export function BidSummary({ itemName, itemCode, bidPrice, deliveryType, isVAT }: BidSummaryProps) {
|
||||
return (
|
||||
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-4">
|
||||
<h1 className="headline-3 text-neutral-90">투찰 결과 요약</h1>
|
||||
<BidItem title="상품명" value={itemName || '-'} />
|
||||
<BidItem title="상품 코드" value={itemCode || '-'} />
|
||||
<BidPrice title="투찰 가격" number={bidPrice || 0} isVAT={isVAT} />
|
||||
<BidItem title="배송형태" value={deliveryType || '-'} />
|
||||
</div>
|
||||
)
|
||||
// 부가정보 값 표시 포맷(불리언→예/아니오, 숫자→천단위, 그 외→문자열)
|
||||
function formatFieldValue(type: SessionField['type'], value: unknown): string {
|
||||
if (type === 'boolean') return value ? '예' : '아니오'
|
||||
if (type === 'number') return Number(value).toLocaleString()
|
||||
return String(value)
|
||||
}
|
||||
|
||||
function BidItem({ title, value }: { title: string; value: string }) {
|
||||
// 투찰 결과 요약 카드 (보고서식 final-summary)
|
||||
// 공급사가 마무리에서 입력한 부가정보(회사설정 session_fields + 의견)가 있으면 함께 표시한다(입력완료 시 요약 갱신).
|
||||
export function BidSummary({ itemName, itemCode, bidPrice }: BidSummaryProps) {
|
||||
// VAT 표기는 회사 설정 기준(item_vat_yn). vat_yn 미관리(hidden)면 비어 라벨을 생략한다.
|
||||
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
|
||||
const custom = useChatInitStore((s) => s.custom)
|
||||
const { data: user } = useMeQuery()
|
||||
const fields: SessionField[] = user?.sessionFields ?? []
|
||||
const priceStr = (bidPrice || 0).toLocaleString()
|
||||
|
||||
// 부가정보(회사설정 session_fields) — 완료 요약엔 구조를 항상 노출(미입력 값은 '-')
|
||||
const extraRows = fields.map((f) => {
|
||||
const v = custom?.[f.key]
|
||||
const has = v !== undefined && v !== null && v !== ''
|
||||
return { key: f.key, label: f.label, value: has ? formatFieldValue(f.type, v) : '-' }
|
||||
})
|
||||
const opinion = custom?.opinion ? String(custom.opinion) : ''
|
||||
|
||||
return (
|
||||
<div className="flex items-start gap-2">
|
||||
<Dot />
|
||||
<div className="flex flex-1 whitespace-pre-wrap">
|
||||
<span className="body-1-read-b">{title} :</span>
|
||||
<div className="flex body-1-read-r"> {value}</div>
|
||||
<div className="w-full rounded-2xl border-2 border-brand-light bg-white p-5 shadow-md">
|
||||
<div className="mb-4 flex items-center gap-2">
|
||||
<CheckCircle2 className="size-5 text-success" />
|
||||
<h3 className="text-sm font-bold text-neutral-90">투찰 결과 요약</h3>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function BidPrice({ number, isVAT, title }: { number: number; isVAT: boolean; title: string }) {
|
||||
const numberString = number.toLocaleString()
|
||||
return (
|
||||
<div className="flex items-start gap-2">
|
||||
<Dot />
|
||||
<div className="flex flex-1">
|
||||
<div className="body-1-read-b flex flex-shrink-0">{title} :</div>
|
||||
<div className="flex flex-1 flex-wrap">
|
||||
<span className="body-1-read-b text-negative break-keep"> {numberString}원</span>
|
||||
<span className="body-1-read-b text-neutral-90 break-keep">
|
||||
({numberToKorean(parseInt(numberString.replace(/,/g, '')))}원)
|
||||
<div className="divide-y divide-border/60 rounded-xl border border-border">
|
||||
<Row label="상품명" value={itemName || '-'} />
|
||||
<Row label="상품 코드" value={itemCode || '-'} mono />
|
||||
<div className="flex items-start justify-between gap-3 px-4 py-3">
|
||||
<span className="shrink-0 text-sm text-neutral-60">투찰 가격</span>
|
||||
<span className="min-w-0 flex-1 break-keep text-right text-sm">
|
||||
<span className="font-bold text-[#E5484D]">{priceStr}원</span>
|
||||
<span className="text-neutral-70"> ({numberToKorean(bidPrice || 0)}원)</span>
|
||||
{item_vat_yn ? <span className="text-neutral-70"> {item_vat_yn}</span> : null}
|
||||
</span>
|
||||
<span className="body-1-read-b text-neutral-90 break-keep"> {isVAT ? 'VAT포함' : 'VAT별도'}</span>
|
||||
</div>
|
||||
{extraRows.map((r) => (
|
||||
<Row key={r.key} label={r.label} value={r.value} />
|
||||
))}
|
||||
{/* 의견은 타결·결렬 공통 기본 필드 — 값이 없어도 항상 표시 */}
|
||||
<Row label="의견" value={opinion || '-'} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Dot() {
|
||||
function Row({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
|
||||
return (
|
||||
<div className="flex justify-end items-center w-[26px] h-[30px]">
|
||||
<p className="body-1-read-r">•</p>
|
||||
<div className="flex items-start justify-between gap-3 px-4 py-3">
|
||||
<span className="shrink-0 text-sm text-neutral-60">{label}</span>
|
||||
<span
|
||||
className={`min-w-0 flex-1 break-keep text-right text-sm font-semibold text-neutral-90 ${mono ? 'font-mono' : ''}`}
|
||||
>
|
||||
{value}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,78 +1,31 @@
|
||||
import { cn } from '@/lib'
|
||||
|
||||
// 협상 성공률 바 (0~100%). 구간별 색: 빨강(~30) / 주황(~70) / 초록(70~)
|
||||
function selectBgColor(index: number, currentStep: number): string {
|
||||
let fill = '#E71C3B'
|
||||
if (currentStep > 3 && currentStep <= 7) fill = '#FDB21C'
|
||||
if (currentStep > 7) fill = '#16BD14'
|
||||
return index <= currentStep ? fill : '#ddd'
|
||||
}
|
||||
|
||||
function UnitBlock({ blockIndex, percent }: { blockIndex: number; percent: number }) {
|
||||
const minBlockPercent = blockIndex * 10
|
||||
const maxBlockPercent = (blockIndex + 1) * 10
|
||||
const remindCount = percent - minBlockPercent
|
||||
|
||||
let nodeType: 'fill' | 'empty' | 'half' = 'empty'
|
||||
if (maxBlockPercent < percent) nodeType = 'fill'
|
||||
else if (minBlockPercent <= percent) nodeType = 'half'
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center flex-1">
|
||||
<div className="flex w-full h-3">
|
||||
{Array.from({ length: 10 }).map((_, i) => {
|
||||
let color = selectBgColor(blockIndex, Math.floor(percent / 10))
|
||||
if (nodeType === 'half' && i >= remindCount) color = '#ddd'
|
||||
|
||||
const subBlockPercent = blockIndex * 10 + i + 1
|
||||
const isTarget = subBlockPercent === percent
|
||||
const isLeftAlign = percent < 90
|
||||
|
||||
return (
|
||||
<div key={i} className="flex-1 h-full rounded-[1px] relative" style={{ backgroundColor: color }}>
|
||||
{isTarget && (
|
||||
<div className="pointer-events-none absolute bottom-full -top-4 left-1/2 -translate-x-1/2 z-10">
|
||||
<div className="relative w-0 h-0">
|
||||
<div className="absolute -top-2 left-[calc(50%+4px)] -translate-x-1/2 w-0 h-0 border-l-[8px] border-r-[8px] border-t-[14px] border-l-transparent border-r-transparent border-t-black" />
|
||||
<span
|
||||
className={cn(
|
||||
'absolute top-[calc(50%-2px)] -translate-y-1/2 text-[24px] leading-none font-bold tabular-nums text-black whitespace-nowrap',
|
||||
isLeftAlign ? 'left-[18px]' : 'right-[10px]',
|
||||
)}
|
||||
>
|
||||
{percent}%
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 협상 성공률 카드 (0~100%). 10칸 컬러 블록바 — 구간별 색(빨강→주황→초록)으로 채운다.
|
||||
export function Indicator({ number }: { number: number }) {
|
||||
const percent = Math.min(Math.max(number, 0), 100)
|
||||
const filled = Math.round(percent / 10) // 0~10칸
|
||||
const color = percent < 40 ? '#F04452' : percent < 70 ? '#F5A623' : '#0B8F57'
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-3 bg-neutral-00 rounded-[28px] px-10 py-[36px]">
|
||||
<h1 className="title-1 text-neutral-90">협상 성공률</h1>
|
||||
<div className="flex flex-col gap-2">
|
||||
{percent === 0 ? (
|
||||
<div className="relative h-6">
|
||||
<div className="absolute left-[20px] -translate-x-1/2 text-xl text-black font-bold">▼ 0%</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-6" />
|
||||
)}
|
||||
<div className="flex gap-1">
|
||||
{Array.from({ length: 10 }).map((_, i) => (
|
||||
<UnitBlock key={i} blockIndex={i} percent={percent} />
|
||||
))}
|
||||
</div>
|
||||
<div className="w-full rounded-2xl border border-border bg-white p-5 shadow-sm">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-bold text-neutral-90">협상 성공률</h3>
|
||||
<span className="font-mono text-base font-extrabold" style={{ color }}>
|
||||
{percent}%
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex gap-1">
|
||||
{Array.from({ length: 10 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="h-3.5 flex-1 rounded-[3px] transition-colors duration-300"
|
||||
style={{ backgroundColor: i < filled ? color : 'var(--neutral-20)' }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="mt-2 text-xs text-neutral-60">
|
||||
협상이 진행될수록 성공률이 실시간으로 갱신됩니다.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ export function OtherReason({
|
||||
onChange,
|
||||
isError,
|
||||
disabled,
|
||||
onSubmit,
|
||||
}: {
|
||||
inputValue: string
|
||||
setInputValue: (value: string) => void
|
||||
@@ -18,6 +19,7 @@ export function OtherReason({
|
||||
onChange: (value: string) => void
|
||||
isError: boolean
|
||||
disabled?: boolean
|
||||
onSubmit?: () => void
|
||||
}) {
|
||||
const isChecked = selectedValue === '기타'
|
||||
const ref = useRef<HTMLTextAreaElement>(null)
|
||||
@@ -39,19 +41,20 @@ export function OtherReason({
|
||||
const isTextareaDisabled = disabled || !isChecked
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-start gap-2">
|
||||
<label className={cn('flex items-start gap-2 flex-shrink-0', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}>
|
||||
<input
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-start gap-2.5">
|
||||
<label className={cn('flex shrink-0 items-start gap-2.5', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}>
|
||||
<span
|
||||
className={cn(
|
||||
'appearance-none w-[16px] h-[16px] mt-[10px] flex-shrink-0 rounded-full border-[1.5px]',
|
||||
disabled ? 'cursor-not-allowed' : 'cursor-pointer',
|
||||
isChecked
|
||||
? 'border-neutral-70 bg-[radial-gradient(circle,var(--neutral-70)_40%,white_40%)]'
|
||||
: isError
|
||||
? 'border-negative bg-white'
|
||||
: 'border-neutral-60 bg-white',
|
||||
'mt-0.5 flex size-[18px] shrink-0 items-center justify-center rounded-full border-2 transition-colors',
|
||||
isChecked ? 'border-brand-600' : isError ? 'border-negative' : 'border-neutral-40',
|
||||
disabled && 'opacity-60',
|
||||
)}
|
||||
>
|
||||
{isChecked && <span className="size-2.5 rounded-full bg-brand-600" />}
|
||||
</span>
|
||||
<input
|
||||
className="sr-only"
|
||||
type="radio"
|
||||
name="rejectrsp"
|
||||
value="기타"
|
||||
@@ -59,26 +62,33 @@ export function OtherReason({
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<div className={cn('reject break-keep whitespace-nowrap mt-[4px] flex', disabled && 'text-neutral-60')}>
|
||||
기타
|
||||
</div>
|
||||
<span className={cn('text-sm text-neutral-80', disabled && 'text-neutral-50')}>기타</span>
|
||||
</label>
|
||||
<textarea
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'w-full px-3 py-2 body-3 resize-none border border-neutral-40 rounded-[8px] outline-none transition-all duration-200 placeholder:text-neutral-60 focus:border-neutral-70 focus:outline-none',
|
||||
isTextareaDisabled ? 'bg-neutral-10 text-neutral-60 cursor-not-allowed' : 'bg-white text-neutral-90',
|
||||
'w-full resize-none rounded-xl border px-3 py-2 text-sm outline-none transition-all placeholder:text-neutral-50',
|
||||
isTextareaDisabled
|
||||
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
|
||||
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
|
||||
errorMessage && 'border-negative',
|
||||
)}
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
// Enter=제출, Shift+Enter=줄바꿈. 한글 조합 중 Enter 는 무시.
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && onSubmit) {
|
||||
e.preventDefault()
|
||||
onSubmit()
|
||||
}
|
||||
}}
|
||||
placeholder="제시한 가격을 수용할 수 없는 이유를 작성해주세요."
|
||||
disabled={isTextareaDisabled}
|
||||
rows={1}
|
||||
style={{ minHeight: '35px', lineHeight: '20px' }}
|
||||
style={{ minHeight: '38px', lineHeight: '20px' }}
|
||||
/>
|
||||
</div>
|
||||
{errorMessage && <div className="body-5 text-negative pl-[65px]">{errorMessage}</div>}
|
||||
{errorMessage && <div className="pl-[30px] text-xs font-medium text-negative">{errorMessage}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { cn } from '@/lib'
|
||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||
import { findRestoreScript, extractPart } from '@/features/chat/lib/rejectForm'
|
||||
import { SelectRadio, SubmitButton } from '@/features/chat/components/templates/rejectControls'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
|
||||
const MAX_PRICE = 999999999999999
|
||||
|
||||
// 재견적 실패 시: 최종 공급 희망 가격 + 배송 형태 입력 폼
|
||||
export function RejectCM() {
|
||||
const isLoading = useChatStore((s) => s.isLoading)
|
||||
const sendMessage = useChatStore((s) => s.sendMessage)
|
||||
const messages = useChatStore((s) => s.messages)
|
||||
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
|
||||
const isVAT = item_vat_yn === 'VAT별도'
|
||||
|
||||
// 폼 값은 이전 제출 내역에서 1회만 복원 (setter 미사용 = lazy 초기화 전용)
|
||||
const restored = useState(() => findRestoreScript(messages, 'rejectCM'))[0]
|
||||
const [price, setPrice] = useState(() => extractPart(restored, '공급희망가격-'))
|
||||
const [selectedReason, setSelectedReason] = useState(() => extractPart(restored, '배송형태-'))
|
||||
const [priceErrorMessage, setPriceErrorMessage] = useState('')
|
||||
const [radioErrorMessage, setRadioErrorMessage] = useState('')
|
||||
|
||||
// 제출 완료 여부는 messages 변화에 반응해야 함 (제출 후 갱신 반영)
|
||||
const isSubmitted = useMemo(() => Boolean(findRestoreScript(messages, 'rejectCM')), [messages])
|
||||
const isValid = Boolean(price && parseInt(price) > 0) && Boolean(selectedReason)
|
||||
|
||||
const handlePriceChange = (value: string) => {
|
||||
const numeric = value.replace(/\D/g, '')
|
||||
if (numeric && parseInt(numeric) > MAX_PRICE) return
|
||||
setPrice(numeric)
|
||||
if (numeric) setPriceErrorMessage('')
|
||||
}
|
||||
|
||||
const koreanPrice = (() => {
|
||||
if (!price) return '영'
|
||||
const n = parseInt(price)
|
||||
return Number.isNaN(n) || n === 0 ? '영' : numberToKorean(n)
|
||||
})()
|
||||
|
||||
const handleSubmit = () => {
|
||||
setPriceErrorMessage(!price || parseInt(price) === 0 ? '가격을 입력해주세요.' : '')
|
||||
setRadioErrorMessage(!selectedReason ? '배송 형태를 선택해주세요.' : '')
|
||||
if (isValid && !isLoading && !isSubmitted) {
|
||||
sendMessage(`공급희망가격-${price}, 배송형태-${selectedReason}`, 'text')
|
||||
}
|
||||
}
|
||||
|
||||
const isDisabled = isLoading || isSubmitted
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-2 transition-all duration-300">
|
||||
<div className="flex w-full h-[48px] bg-[#CD2A2D] headline-3 text-neutral-00 rounded-[12px] items-center justify-center">
|
||||
최종 공급 희망 가격 입력
|
||||
</div>
|
||||
|
||||
<div className="reject break-keep py-2">
|
||||
최종 공급 희망 가격과 배송 형태를 입력하여 주시기 바랍니다.
|
||||
<br />
|
||||
가격 검토를 통해 경쟁력 있는 가격일 경우 다시 협상에 참여할 기회가 주어지오니 신중한 가격 제안 부탁드립니다.
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col w-full gap-1">
|
||||
<div className="flex w-full items-start gap-4">
|
||||
<div className="flex reject-2 whitespace-nowrap pt-2 flex-shrink-0 w-[110px]">공급 희망 가격</div>
|
||||
<div className="flex flex-wrap w-full items-center pt-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
className={cn(
|
||||
'text-right max-w-[220px] h-full max-h-[35px] border p-2 body-3 placeholder:text-neutral-60 focus:border-neutral-70 rounded-[8px] outline-none border-neutral-40',
|
||||
isDisabled ? 'bg-neutral-10 text-neutral-60 cursor-not-allowed' : 'bg-white text-neutral-90',
|
||||
)}
|
||||
value={price ? parseInt(price).toLocaleString() : ''}
|
||||
onChange={(e) => handlePriceChange(e.target.value)}
|
||||
placeholder="0"
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<div className="reject whitespace-nowrap mr-2">원{isVAT && '(VAT 별도)'}</div>
|
||||
</div>
|
||||
<div className="reject-gray whitespace-nowrap">[{koreanPrice} 원]</div>
|
||||
</div>
|
||||
</div>
|
||||
{priceErrorMessage && <div className="body-5 text-negative pl-[126px]">{priceErrorMessage}</div>}
|
||||
</div>
|
||||
|
||||
<div className="flex w-full gap-4">
|
||||
<div className="flex reject-2 whitespace-nowrap pt-2 flex-shrink-0 w-[110px]">배송 형태</div>
|
||||
<div className="flex w-full items-center justify-between pr-20 flex-wrap">
|
||||
{['협력사배송', '지정택배배송', '픽업배송'].map((opt) => (
|
||||
<SelectRadio
|
||||
key={opt}
|
||||
text={opt === '협력사배송' ? '협력사 배송' : opt}
|
||||
value={opt}
|
||||
name="rejectcm"
|
||||
selectedValue={selectedReason}
|
||||
onChange={(v) => {
|
||||
setSelectedReason(v)
|
||||
setRadioErrorMessage('')
|
||||
}}
|
||||
errorMessage={radioErrorMessage}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full items-center justify-center mt-4">
|
||||
<SubmitButton isValid={isValid} isLoading={isLoading} isSubmitted={isSubmitted} onSubmit={handleSubmit} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { cn } from '@/lib'
|
||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
import { SelectRadio, SubmitButton } from '@/features/chat/components/templates/rejectControls'
|
||||
import { OtherReason } from '@/features/chat/components/templates/OtherReason'
|
||||
import { findRestoreScript, restoreRejectRSP } from '@/features/chat/lib/rejectForm'
|
||||
|
||||
const MAX_PRICE = 999999999999999
|
||||
|
||||
const REASONS = [
|
||||
{ value: '단가인상', text: "'원재료 가격 상승' 또는 '제조사 가격 인상'으로 요청한 공급가격을 맞출 수 없습니다." },
|
||||
{ value: '수량', text: '주문 수량이 적어, 소량 생산 시 발생하는 제조비용으로 맞출 수 없습니다.' },
|
||||
{ value: '단종', text: '현재 단종된 제품으로 물량 수급이 원활하지 않아 가격을 맞출 수 없습니다.' },
|
||||
{ value: '품절', text: '해당 상품이 품절되어 납품할 수 없습니다.' },
|
||||
]
|
||||
|
||||
// 협상 합의 불가 시: 최종 제안 단가 + 합의 불가 사유 입력 폼
|
||||
export function RejectRSP() {
|
||||
const isLoading = useChatStore((s) => s.isLoading)
|
||||
const sendMessage = useChatStore((s) => s.sendMessage)
|
||||
const messages = useChatStore((s) => s.messages)
|
||||
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
|
||||
const isVAT = item_vat_yn === 'VAT별도'
|
||||
|
||||
// 폼 값은 이전 제출 내역에서 1회만 복원 (setter 미사용 = lazy 초기화 전용)
|
||||
const restored = useState(() => restoreRejectRSP(findRestoreScript(messages, 'rejectRSP')))[0]
|
||||
const [price, setPrice] = useState(restored.price)
|
||||
const [selectedReason, setSelectedReason] = useState(restored.selectedReason)
|
||||
const [reason, setReason] = useState(restored.reason)
|
||||
const [otherErrorMessage, setOtherErrorMessage] = useState('')
|
||||
const [priceErrorMessage, setPriceErrorMessage] = useState('')
|
||||
const [radioErrorMessage, setRadioErrorMessage] = useState('')
|
||||
|
||||
const isSubmitted = useMemo(
|
||||
() => Boolean(findRestoreScript(messages, 'rejectRSP')),
|
||||
[messages],
|
||||
)
|
||||
const isValid =
|
||||
Boolean(price && parseInt(price) > 0) &&
|
||||
Boolean(selectedReason) &&
|
||||
(selectedReason !== '기타' || reason.trim() !== '')
|
||||
|
||||
const handlePriceChange = (value: string) => {
|
||||
const numeric = value.replace(/\D/g, '')
|
||||
if (numeric && parseInt(numeric) > MAX_PRICE) return
|
||||
setPrice(numeric)
|
||||
if (numeric) setPriceErrorMessage('')
|
||||
}
|
||||
|
||||
const handleRadioChange = (value: string) => {
|
||||
setSelectedReason(value)
|
||||
setRadioErrorMessage('')
|
||||
if (value !== '기타') {
|
||||
setReason('')
|
||||
setOtherErrorMessage('')
|
||||
}
|
||||
}
|
||||
|
||||
const koreanPrice = (() => {
|
||||
if (!price) return '영'
|
||||
const n = parseInt(price)
|
||||
return Number.isNaN(n) || n === 0 ? '영' : numberToKorean(n)
|
||||
})()
|
||||
|
||||
const handleSubmit = () => {
|
||||
setPriceErrorMessage(!price || parseInt(price) === 0 ? '가격을 입력해주세요.' : '')
|
||||
setRadioErrorMessage(!selectedReason ? '사유를 선택해주세요.' : '')
|
||||
setOtherErrorMessage(selectedReason === '기타' && !reason.trim() ? '기타 사유를 입력해주세요.' : '')
|
||||
if (isValid && !isLoading && !isSubmitted) {
|
||||
const script =
|
||||
selectedReason === '기타'
|
||||
? `공급희망가격-${price}, 합의불가사유-기타-${reason.trim()}`
|
||||
: `공급희망가격-${price}, 합의불가사유-${selectedReason}`
|
||||
sendMessage(script, 'text')
|
||||
}
|
||||
}
|
||||
|
||||
const isDisabled = isLoading || isSubmitted
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-2 transition-all duration-300">
|
||||
<div className="flex w-full h-[48px] bg-[#CD2A2D] headline-3 text-neutral-00 rounded-[12px] items-center justify-center">
|
||||
협상 합의 불가 사유 및 최종 제안 단가 입력
|
||||
</div>
|
||||
|
||||
<div className="reject break-keep py-2">
|
||||
협상이 합의에 도달하지 못하였습니다. 최종 희망하는 가격을 입력해주시기 바랍니다.
|
||||
<br />
|
||||
추가로 제시한 가격을 수용할 수 없는 이유를 선택하여 주시기 바라며, 목록에 없는 경우 기타 항목 선택 후 간단한 사유를
|
||||
기재하여 주시기 바랍니다.
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col w-full gap-1">
|
||||
<div className="flex w-full items-start gap-4">
|
||||
<div className="flex reject-2 whitespace-nowrap pt-2 flex-shrink-0 w-[110px]">공급 희망 가격</div>
|
||||
<div className="flex flex-wrap w-full items-center pt-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
className={cn(
|
||||
'text-right max-w-[220px] h-full max-h-[35px] border p-2 body-3 placeholder:text-neutral-60 focus:border-neutral-70 rounded-[8px] outline-none border-neutral-40',
|
||||
isDisabled ? 'bg-neutral-10 text-neutral-60 cursor-not-allowed' : 'bg-white text-neutral-90',
|
||||
)}
|
||||
value={price ? parseInt(price).toLocaleString() : ''}
|
||||
onChange={(e) => handlePriceChange(e.target.value)}
|
||||
placeholder="0"
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<div className="reject whitespace-nowrap mr-2">원{isVAT && '(VAT 별도)'}</div>
|
||||
</div>
|
||||
<div className="reject-gray whitespace-nowrap">[{koreanPrice} 원]</div>
|
||||
</div>
|
||||
</div>
|
||||
{priceErrorMessage && <div className="body-5 text-negative pl-[126px]">{priceErrorMessage}</div>}
|
||||
</div>
|
||||
|
||||
<div className="flex w-full gap-4">
|
||||
<div className="flex reject-2 whitespace-nowrap pt-2 pb-2 flex-shrink-0 w-[110px]">합의 불가 사유</div>
|
||||
<div className="flex w-full flex-col mt-2 gap-2">
|
||||
{REASONS.map((r) => (
|
||||
<SelectRadio
|
||||
key={r.value}
|
||||
text={r.text}
|
||||
value={r.value}
|
||||
name="rejectrsp"
|
||||
selectedValue={selectedReason}
|
||||
onChange={handleRadioChange}
|
||||
errorMessage={radioErrorMessage}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
))}
|
||||
<OtherReason
|
||||
inputValue={reason}
|
||||
setInputValue={(v) => {
|
||||
if (selectedReason !== '기타') return
|
||||
setReason(v)
|
||||
if (v.trim()) setOtherErrorMessage('')
|
||||
}}
|
||||
errorMessage={otherErrorMessage}
|
||||
selectedValue={selectedReason}
|
||||
onChange={handleRadioChange}
|
||||
isError={!!radioErrorMessage}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full items-center justify-center mt-6">
|
||||
<SubmitButton isValid={isValid} isLoading={isLoading} isSubmitted={isSubmitted} onSubmit={handleSubmit} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,49 +1,93 @@
|
||||
import { CheckCircle2 } from 'lucide-react'
|
||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||
import { formatLeadTime } from '@/features/chat/lib/format'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
import type { ChatSummary } from '@/features/chat/types'
|
||||
|
||||
// 협상 결과 요약 카드
|
||||
export function Summary({ data }: { data: ChatSummary }) {
|
||||
const priceStr = (data.final_price || 0).toLocaleString()
|
||||
// VAT 표기는 회사 설정 기준(item_vat_yn). vat_yn 미관리(hidden)면 비어 라벨을 생략한다.
|
||||
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
|
||||
// 공급사가 마무리에서 남긴 의견(있을 때만 표시)
|
||||
const custom = useChatInitStore((s) => s.custom)
|
||||
const opinion = custom?.opinion ? String(custom.opinion) : ''
|
||||
// 납기 라벨은 회사 설정(labels.lead_time) 기준 — IMK 등은 '표준납기'. 미설정 시 기본 '배송 리드타임'.
|
||||
const labels = useChatInitStore((s) => s.labels)
|
||||
const leadTimeLabel = labels?.['lead_time'] || '배송 리드타임'
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-4">
|
||||
<h1 className="headline-3 text-neutral-90">협상 결과 요약</h1>
|
||||
<div className="body-1-read-r">
|
||||
협상이 완료되어 아래와 같이 결과를 요약하오니 다시 한 번 최종 확인 부탁 드립니다. 최종 확인 후 협상 결과에 대한
|
||||
수정 변경은 불가함을 안내 드립니다.
|
||||
<div className="w-full rounded-2xl border border-border bg-white p-5 shadow-sm">
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
<CheckCircle2 className="size-5 text-success" />
|
||||
<h3 className="text-sm font-bold text-neutral-90">협상 결과 요약</h3>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<div className="body-1-read-r">협상 개시 시간 : {formatKoreanDateTime(data.nego_start_date)}</div>
|
||||
<div className="body-1-read-r">협상 종료 시간 : {formatKoreanDateTime(data.nego_end_date)}</div>
|
||||
<div className="body-1-read-r">
|
||||
우선협상 대상자 : {data.supplier_name || '-'} ({data.supplier_manager_phone || '-'}){' '}
|
||||
{data.supplier_manager_email || '-'}
|
||||
|
||||
<p className="text-sm leading-relaxed text-neutral-70 break-keep">
|
||||
협상이 완료되어 아래와 같이 결과를 요약하오니 최종 확인 부탁드립니다. 최종 확인 후 협상 결과의 수정·변경은
|
||||
불가함을 안내드립니다.
|
||||
</p>
|
||||
|
||||
{/* 개요 */}
|
||||
<div className="mt-4 space-y-1.5 rounded-xl bg-neutral-10 p-3.5 text-xs text-neutral-70">
|
||||
<p>협상 개시: {formatKoreanDateTime(data.nego_start_date)}</p>
|
||||
<p>협상 종료: {formatKoreanDateTime(data.nego_end_date)}</p>
|
||||
<p>
|
||||
우선협상 대상자: <span className="font-semibold text-neutral-90">{data.supplier_name || '-'}</span> (
|
||||
{data.supplier_manager_phone || '-'}) {data.supplier_manager_email || '-'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 상세 내역 */}
|
||||
<div className="mt-3 divide-y divide-border/60 rounded-xl border border-border">
|
||||
<Row label="상품 코드" value={data.item_code || '-'} mono />
|
||||
<Row label="상품명" value={data.item_name || '-'} />
|
||||
<Row label="모델명" value={data.item_model || '-'} />
|
||||
<Row label="제품 규격" value={data.item_spec || '-'} />
|
||||
<Row label="최소 주문" value={data.item_moq || '-'} />
|
||||
<Row label="배송 형태" value={data.item_delivery_type || '-'} />
|
||||
<Row label={leadTimeLabel} value={formatLeadTime(data.item_lead_time) || '-'} />
|
||||
<div className="flex items-start justify-between gap-3 px-4 py-3">
|
||||
<span className="shrink-0 text-sm text-neutral-60">최종 협의 가격</span>
|
||||
<span className="min-w-0 flex-1 break-keep text-right text-sm">
|
||||
<span className="font-bold text-[#E5484D]">{priceStr}원</span>
|
||||
<span className="text-neutral-70"> ({numberToKorean(data.final_price || 0)}원)</span>
|
||||
{item_vat_yn ? <span className="text-neutral-70"> {item_vat_yn}</span> : null}
|
||||
</span>
|
||||
</div>
|
||||
<div className="body-1-read-r">협상 상세 내역</div>
|
||||
{/* 의견은 타결·결렬 공통 기본 필드 — 값이 없어도 항상 표시 */}
|
||||
<Row label="의견" value={opinion || '-'} />
|
||||
</div>
|
||||
<div className="flex flex-col gap-4">
|
||||
<DetailText title="상품 코드" value={data.item_code || '-'} />
|
||||
<DetailText title="상품 명" value={data.item_name || '-'} />
|
||||
<DetailText title="모델 명" value={data.item_model || '-'} />
|
||||
<DetailText title="제품 규격" value={data.item_spec || '-'} />
|
||||
<DetailText title="최소 주문" value={data.item_moq || '-'} />
|
||||
<DetailText title="배송 형태" value={data.item_delivery_type || '-'} />
|
||||
<DetailText title="배송 리드타임" value={formatLeadTime(data.item_lead_time) || '-'} />
|
||||
<PriceText price={data.final_price} isVAT={data.item_isVAT} />
|
||||
|
||||
{/* 계약 / 구매담당자 */}
|
||||
<div className="mt-3 space-y-1 text-xs text-neutral-70">
|
||||
<p>공급 계약 기간: 협상 완료일로부터 1년 ({addOneYear(data.nego_end_date)})까지</p>
|
||||
<p>
|
||||
구매담당자: {data.md_name || '-'} ({data.md_phone_number || '-'}) {data.md_email || '-'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<div className="body-1-read-r">
|
||||
공급 계약 기간: 협상 완료일로부터 1년 ({addOneYear(data.nego_end_date)})까지
|
||||
</div>
|
||||
<div className="body-1-read-r">
|
||||
담당 MD: {data.md_name || '-'} ({data.md_phone_number || '-'}) {data.md_email || '-'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="body-1-read-b">상기 내용에 이상이 없으며 최종 협상 결과에 동의하여 이를 승인합니다.</div>
|
||||
|
||||
<p className="mt-4 rounded-xl bg-brand-light px-4 py-3 text-sm font-bold text-brand-600 break-keep">
|
||||
상기 내용에 이상이 없으며 최종 협상 결과에 동의하여 이를 승인합니다.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ISO 시각 → 한국시(KST) 기준 부분값. 백엔드는 UTC(ISO)로 내려주므로 표시 시 KST 로 변환한다.
|
||||
function Row({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
|
||||
return (
|
||||
<div className="flex items-start justify-between gap-3 px-4 py-3">
|
||||
<span className="shrink-0 text-sm text-neutral-60">{label}</span>
|
||||
<span
|
||||
className={`min-w-0 flex-1 break-keep text-right text-sm font-semibold text-neutral-90 ${mono ? 'font-mono' : ''}`}
|
||||
>
|
||||
{value}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ISO 시각 → KST 기준 부분값.
|
||||
function kstParts(iso: string): Record<string, string> | null {
|
||||
if (!iso) return null
|
||||
const d = new Date(iso)
|
||||
@@ -63,55 +107,16 @@ function kstParts(iso: string): Record<string, string> | null {
|
||||
return out
|
||||
}
|
||||
|
||||
// "YYYY년 MM월 dd일 HH시 MM분 SS초" (KST)
|
||||
// "YYYY년 MM월 dd일 HH시 MM분" (KST)
|
||||
function formatKoreanDateTime(iso: string): string {
|
||||
const p = kstParts(iso)
|
||||
if (!p) return '-'
|
||||
return `${p.year}년 ${p.month}월 ${p.day}일 ${p.hour}시 ${p.minute}분 ${p.second}초`
|
||||
return `${p.year}년 ${p.month}월 ${p.day}일 ${p.hour}시 ${p.minute}분`
|
||||
}
|
||||
|
||||
// 협상 종료 시각 + 1년 → "YYYY년 MM월 dd일" (공급 계약 만료일)
|
||||
// 협상 종료 시각 + 1년 → "YYYY년 MM월 dd일"
|
||||
function addOneYear(iso: string): string {
|
||||
const p = kstParts(iso)
|
||||
if (!p) return '-'
|
||||
return `${parseInt(p.year) + 1}년 ${p.month}월 ${p.day}일`
|
||||
}
|
||||
|
||||
function DetailText({ title, value }: { title: string; value: string }) {
|
||||
return (
|
||||
<div className="flex items-start gap-2">
|
||||
<Dot />
|
||||
<div className="flex-1 whitespace-pre-wrap">
|
||||
<span className="body-1-read-b">{title} : </span>
|
||||
<span className="body-1-read-r">{value}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PriceText({ price, isVAT }: { price: number; isVAT: boolean }) {
|
||||
const numberString = price.toLocaleString()
|
||||
return (
|
||||
<div className="flex items-start gap-2">
|
||||
<Dot />
|
||||
<div className="flex flex-1">
|
||||
<div className="body-1-read-b flex flex-shrink-0">최종 협의 가격 :</div>
|
||||
<div className="flex flex-1 flex-wrap">
|
||||
<span className="body-1-read-b text-negative break-keep"> {numberString}원</span>
|
||||
<span className="body-1-read-b text-neutral-90 break-keep">
|
||||
({numberToKorean(parseInt(numberString.replace(/,/g, '')))}원)
|
||||
</span>
|
||||
<span className="body-1-read-b text-neutral-90 break-keep"> {isVAT ? 'VAT포함' : 'VAT별도'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Dot() {
|
||||
return (
|
||||
<div className="flex justify-end items-center w-[26px] h-[30px]">
|
||||
<p className="body-1-read-r">•</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -22,17 +22,18 @@ export function SelectRadio({
|
||||
}) {
|
||||
const isChecked = selectedValue === value
|
||||
return (
|
||||
<label className={cn('flex items-center gap-2', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}>
|
||||
<input
|
||||
<label className={cn('flex items-start gap-2.5', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}>
|
||||
<span
|
||||
className={cn(
|
||||
'appearance-none w-[16px] h-[16px] min-w-[16px] min-h-[16px] rounded-full border-[1.5px] whitespace-nowrap',
|
||||
disabled ? 'cursor-not-allowed' : 'cursor-pointer',
|
||||
isChecked
|
||||
? 'border-neutral-70 bg-[radial-gradient(circle,var(--neutral-70)_40%,white_40%)]'
|
||||
: errorMessage
|
||||
? 'border-negative bg-white'
|
||||
: 'border-neutral-60 bg-white',
|
||||
'mt-0.5 flex size-[18px] shrink-0 items-center justify-center rounded-full border-2 transition-colors',
|
||||
isChecked ? 'border-brand-600' : errorMessage ? 'border-negative' : 'border-neutral-40',
|
||||
disabled && 'opacity-60',
|
||||
)}
|
||||
>
|
||||
{isChecked && <span className="size-2.5 rounded-full bg-brand-600" />}
|
||||
</span>
|
||||
<input
|
||||
className="sr-only"
|
||||
type="radio"
|
||||
name={name}
|
||||
value={value}
|
||||
@@ -40,7 +41,9 @@ export function SelectRadio({
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<div className={cn('reject break-keep', disabled && 'text-neutral-60')}>{text}</div>
|
||||
<span className={cn('text-sm leading-relaxed text-neutral-80 break-keep', disabled && 'text-neutral-50')}>
|
||||
{text}
|
||||
</span>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
@@ -59,15 +62,15 @@ export function SubmitButton({
|
||||
if (isSubmitted) return null
|
||||
|
||||
const style = isLoading
|
||||
? 'bg-neutral-40 text-neutral-80 cursor-not-allowed'
|
||||
? 'bg-neutral-20 text-neutral-60 cursor-not-allowed'
|
||||
: isValid
|
||||
? 'bg-neutral-90 text-white cursor-pointer hover:bg-neutral-80'
|
||||
: 'bg-neutral-20 text-neutral-60 cursor-not-allowed'
|
||||
? 'bg-brand-600 text-white shadow-sm cursor-pointer hover:bg-brand-700 active:scale-[0.98]'
|
||||
: 'bg-neutral-20 text-neutral-50 cursor-not-allowed'
|
||||
|
||||
return (
|
||||
<button
|
||||
className={cn(
|
||||
'flex items-center justify-center w-[280px] h-[48px] rounded-[12px] text-base font-bold tracking-[-0.32px] transition-all duration-200',
|
||||
'flex h-12 w-full max-w-[280px] items-center justify-center rounded-xl text-sm font-bold transition-all duration-200',
|
||||
style,
|
||||
)}
|
||||
onClick={onSubmit}
|
||||
|
||||
Loaded 100 of 526 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user