Compare commits
113
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
3d515055fb | ||
|
|
21f90ed84a | ||
|
|
ac487268d8 | ||
|
|
1cce752b47 | ||
|
|
5ddf5f6249 | ||
|
|
3171311746 | ||
|
|
28b4a9e797 | ||
|
|
c0e6987c3c | ||
|
|
523661e3d2 | ||
|
|
b41f7c67f1 | ||
|
|
9e9de52200 | ||
|
|
26d9fa3c4b | ||
|
|
22500eae4c | ||
|
|
afacd74382 | ||
|
|
1682481b01 | ||
|
|
18f6466a8b | ||
|
|
d4cee1caf7 | ||
|
|
a267326bf7 | ||
|
|
c075dfbcfb | ||
|
|
4381649658 | ||
|
|
463416c3a2 | ||
|
|
fbd2cec1da | ||
|
|
5e485e9b6e | ||
|
|
7f1c0be2b3 | ||
|
|
89fe2c9805 | ||
|
|
64d5063041 | ||
|
|
47c64eaf8b | ||
|
|
ddb6f6bd2f | ||
|
|
08a9c52088 | ||
|
|
0e30354ba5 | ||
|
|
9c2432c818 | ||
|
|
a63793daf0 | ||
|
|
eba78dbbb9 | ||
|
|
97e566f844 | ||
|
|
eb1ff8fee1 | ||
|
|
d6dd47e652 | ||
|
|
3a8d669970 | ||
|
|
94d4e54d5e | ||
|
|
e2cd2570e3 | ||
|
|
10eb67e8c6 | ||
|
|
77a36c43d4 | ||
|
|
0cd817a61d | ||
|
|
8a594b667d | ||
|
|
a80dac20ed | ||
|
|
1b9ca062f3 | ||
|
|
4b8dee8583 | ||
|
|
ba67275cd8 | ||
|
|
ad26e6ce6f | ||
|
|
bf19d4a8fd | ||
|
|
0d62440ee1 | ||
|
|
a80109cdcf | ||
|
|
c955a8f367 | ||
|
|
9c478e80fd | ||
|
|
69f6641c27 | ||
|
|
61b9e6ae82 | ||
|
|
7e5814b0e5 | ||
|
|
f9714c3f06 | ||
|
|
e365e5c6e0 | ||
|
|
3a2c6e43d4 | ||
|
|
2eccf4de50 | ||
|
|
7806b35723 | ||
|
|
8460a5d833 | ||
|
|
61bc719e28 | ||
|
|
313d882df4 | ||
|
|
4863425ca5 | ||
|
|
8bf34ea346 | ||
|
|
5906acc48a | ||
|
|
bca8032b79 | ||
|
|
7911ba1745 | ||
|
|
2481c79e3f | ||
|
|
4de85d43ed | ||
|
|
d54dee4f24 | ||
|
|
b0a86b9720 | ||
|
|
9557c1b1af | ||
|
|
7491bbecd9 | ||
|
|
c4b8692f3a | ||
|
|
fb72ab625f | ||
|
|
abcb58ba05 | ||
|
|
bebb6a71e6 | ||
|
|
da9bd7750c | ||
|
|
e27b73c018 | ||
|
|
11a7be7154 |
No files matched your search
@@ -0,0 +1,21 @@
|
|||||||
|
# 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)
|
||||||
@@ -24,3 +24,7 @@ CLAUDE.md
|
|||||||
|
|
||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
|
# 로컬 리서치 노트(크롤링 라이브러리·안티스크래핑 조사) — 추적 안 함, 로컬 참고용
|
||||||
|
/Temp.md
|
||||||
|
/new.md
|
||||||
+8
-8
@@ -1,6 +1,6 @@
|
|||||||
# Negosium Agent
|
# Negosium Agent
|
||||||
|
|
||||||
범용 멀티테넌트 협상 솔루션 PoC. 여러 회사(ktcommerce·imarketkorea 등)가 **각자 데이터로 분기 학습**하는
|
범용 멀티테넌트 협상 솔루션 PoC. 여러 회사(imarketkorea 등)가 **각자 데이터로 분기 학습**하는
|
||||||
협상 카드 선택 에이전트. Q-Learning(UCB) 기반 `Chat_server`(단일 테넌트)를 참고해 신규 구축한다.
|
협상 카드 선택 에이전트. Q-Learning(UCB) 기반 `Chat_server`(단일 테넌트)를 참고해 신규 구축한다.
|
||||||
|
|
||||||
PoC 목표 두 가지:
|
PoC 목표 두 가지:
|
||||||
@@ -99,10 +99,10 @@ APP_ENV=test python -m pytest # 테스트 (config.local.toml 사
|
|||||||
|
|
||||||
**1) 의사결정 루프 데모** — 테넌트별 config 주입·상태분류·보상·DB 격리를 눈으로 확인:
|
**1) 의사결정 루프 데모** — 테넌트별 config 주입·상태분류·보상·DB 격리를 눈으로 확인:
|
||||||
```bash
|
```bash
|
||||||
APP_ENV=local python -m tools.console_demo --tenant ktcommerce # 기본 3턴 시나리오
|
APP_ENV=local python -m tools.console_demo --tenant imarketkorea # 기본 3턴 시나리오
|
||||||
APP_ENV=local python -m tools.console_demo --tenant imarketkorea # 다른 테넌트(다른 카드셋·임계값)
|
APP_ENV=local python -m tools.console_demo --tenant imarketkorea # 다른 테넌트(다른 카드셋·임계값)
|
||||||
APP_ENV=local python -m tools.console_demo --tenant ktcommerce --interactive # 직접 입력
|
APP_ENV=local python -m tools.console_demo --tenant imarketkorea --interactive # 직접 입력
|
||||||
APP_ENV=local python -m tools.console_demo --tenant ktcommerce --no-db # DB 없이
|
APP_ENV=local python -m tools.console_demo --tenant imarketkorea --no-db # DB 없이
|
||||||
```
|
```
|
||||||
> ⚠️ 카드선택은 임시 placeholder 정책(실제 UCB Q-Table 은 H1/P5). 학습은 아직 일어나지 않는다.
|
> ⚠️ 카드선택은 임시 placeholder 정책(실제 UCB Q-Table 은 H1/P5). 학습은 아직 일어나지 않는다.
|
||||||
|
|
||||||
@@ -113,13 +113,13 @@ curl localhost:9500/healthz # 200
|
|||||||
curl localhost:9500/v1/health # {"status":"ok",...}
|
curl localhost:9500/v1/health # {"status":"ok",...}
|
||||||
curl localhost:9500/v1/foo # 400 TENANT_HEADER_MISSING (헤더 없음)
|
curl localhost:9500/v1/foo # 400 TENANT_HEADER_MISSING (헤더 없음)
|
||||||
curl localhost:9500/v1/foo -H 'X-Tenant-ID: nonexistent' # 404 TENANT_NOT_REGISTERED
|
curl localhost:9500/v1/foo -H 'X-Tenant-ID: nonexistent' # 404 TENANT_NOT_REGISTERED
|
||||||
curl localhost:9500/v1/foo -H 'X-Tenant-ID: ktcommerce' # 통과(라우트 미존재라 404 Not Found)
|
curl localhost:9500/v1/foo -H 'X-Tenant-ID: imarketkorea' # 통과(라우트 미존재라 404 Not Found)
|
||||||
```
|
```
|
||||||
|
|
||||||
**2-1) 협상 한 라운드 (HTTP 프리뷰)** — `POST /v1/negotiation/step` (Swagger: http://localhost:9500/docs):
|
**2-1) 협상 한 라운드 (HTTP 프리뷰)** — `POST /v1/negotiation/step` (Swagger: http://localhost:9500/docs):
|
||||||
```bash
|
```bash
|
||||||
curl -s -X POST localhost:9500/v1/negotiation/step \
|
curl -s -X POST localhost:9500/v1/negotiation/step \
|
||||||
-H 'X-Tenant-ID: ktcommerce' -H 'Content-Type: application/json' \
|
-H 'X-Tenant-ID: imarketkorea' -H 'Content-Type: application/json' \
|
||||||
-d '{"revenue_amount":20000000,"distribution_code":"A","partner_count":1,
|
-d '{"revenue_amount":20000000,"distribution_code":"A","partner_count":1,
|
||||||
"acceptance_ratio":0.11,"input_price":990,"anchor_price":800,"target_price":1000,
|
"acceptance_ratio":0.11,"input_price":990,"anchor_price":800,"target_price":1000,
|
||||||
"round_number":3,"outcome":"success"}'
|
"round_number":3,"outcome":"success"}'
|
||||||
@@ -156,7 +156,7 @@ APP_ENV=local python -m tools.show_logs # learning.experience_logs 를 co
|
|||||||
**가격협상 턴 UCB 카드선택·학습 + 종료보상 역전파**. 브라우저 채팅 UI. (`tests/test_p7_chat.py` 5/5)
|
**가격협상 턴 UCB 카드선택·학습 + 종료보상 역전파**. 브라우저 채팅 UI. (`tests/test_p7_chat.py` 5/5)
|
||||||
- ✅ **H5 학습검증 하네스 (PoC 본체)**: 카드별 효과가 다른 시뮬 구매자(`eval_harness/`) → 정책 비교.
|
- ✅ **H5 학습검증 하네스 (PoC 본체)**: 카드별 효과가 다른 시뮬 구매자(`eval_harness/`) → 정책 비교.
|
||||||
**학습형(qtable_ucb)이 random/static 대비 평균보상 우위(95%CI 분리)·좋은카드 적중 0.9 vs 0.32** →
|
**학습형(qtable_ucb)이 random/static 대비 평균보상 우위(95%CI 분리)·좋은카드 적중 0.9 vs 0.32** →
|
||||||
"학습하면 성과가 오른다" 정량 입증. `python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce`. (`tests/test_h5_*` 5/5)
|
"학습하면 성과가 오른다" 정량 입증. `python -m eval_harness.runner --config configs/exp_default.yaml --tenant imarketkorea`. (`tests/test_h5_*` 5/5)
|
||||||
- ✅ **P7 14개 API**: chat / q-table(versions·switch·current) / experience-logs / reset-learning ·
|
- ✅ **P7 14개 API**: chat / q-table(versions·switch·current) / experience-logs / reset-learning ·
|
||||||
reset-all(타테넌트 무영향) / invalidate-session / **train**(오프라인 Q-learning) / verification-report /
|
reset-all(타테넌트 무영향) / invalidate-session / **train**(오프라인 Q-learning) / verification-report /
|
||||||
card-update · card-search. 전부 X-Tenant-ID 격리. (`tests/test_p7_apis.py` 5/5)
|
card-update · card-search. 전부 X-Tenant-ID 격리. (`tests/test_p7_apis.py` 5/5)
|
||||||
@@ -177,7 +177,7 @@ APP_ENV=local python -m tools.show_logs # learning.experience_logs 를 co
|
|||||||
|
|
||||||
### PoC 본체 결과 (H5, 위 경제모델 기준 / target=10000·anchor=8000 시나리오)
|
### PoC 본체 결과 (H5, 위 경제모델 기준 / target=10000·anchor=8000 시나리오)
|
||||||
```
|
```
|
||||||
python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce
|
python -m eval_harness.runner --config configs/exp_default.yaml --tenant imarketkorea
|
||||||
policy success settled/tgt turns mean_rwd ±95%CI good_hit
|
policy success settled/tgt turns mean_rwd ±95%CI good_hit
|
||||||
random 0.988 0.904 2.02 1.1176 0.0206 0.350
|
random 0.988 0.904 2.02 1.1176 0.0206 0.350
|
||||||
static 1.000 0.923 2.56 0.9995 0.0020 0.000
|
static 1.000 0.923 2.56 0.9995 0.0020 0.000
|
||||||
|
|||||||
@@ -40,3 +40,20 @@ def _apply_db_env_override(cfg: MainDBConfig):
|
|||||||
|
|
||||||
|
|
||||||
_apply_db_env_override(main_db_config)
|
_apply_db_env_override(main_db_config)
|
||||||
|
|
||||||
|
|
||||||
|
# LLM 키/설정 env override (DB 와 동일 패턴). 로컬은 config.local.toml [OpenAIConfig] 에 기재,
|
||||||
|
# Docker/CI/운영은 toml 없이 env 로 주입한다(docker-compose 가 OPENAI_API_KEY passthrough).
|
||||||
|
# env 미설정 시 no-op → toml 값 그대로.
|
||||||
|
def _apply_llm_env_override(cfg: OpenAIConfig):
|
||||||
|
if os.environ.get("OPENAI_API_KEY"):
|
||||||
|
cfg.api_key = os.environ["OPENAI_API_KEY"]
|
||||||
|
if os.environ.get("OPENAI_MODEL"):
|
||||||
|
cfg.model = os.environ["OPENAI_MODEL"]
|
||||||
|
if os.environ.get("OPENAI_BASE_URL"):
|
||||||
|
cfg.base_url = os.environ["OPENAI_BASE_URL"]
|
||||||
|
if os.environ.get("OPENAI_PROVIDER"):
|
||||||
|
cfg.provider = os.environ["OPENAI_PROVIDER"]
|
||||||
|
|
||||||
|
|
||||||
|
_apply_llm_env_override(openai_config)
|
||||||
@@ -4,10 +4,23 @@ import os
|
|||||||
|
|
||||||
os.environ.setdefault("APP_ENV", "local")
|
os.environ.setdefault("APP_ENV", "local")
|
||||||
|
|
||||||
|
import pytest
|
||||||
import pytest_asyncio
|
import pytest_asyncio
|
||||||
from httpx import ASGITransport, AsyncClient
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _no_real_llm(monkeypatch):
|
||||||
|
"""실 LLM 호출 차단 — imarketkorea 가 llm.enabled=true 라 로컬에 실키가 있으면
|
||||||
|
챗 플로우가 자연화/NLU(과금·비결정 응답)를 시도한다. LLM 검증 테스트는
|
||||||
|
available 을 테스트 안에서 직접 덮어써 이 가드를 우회한다."""
|
||||||
|
from negotiation.chat.service.input_interpreter import InputInterpreter
|
||||||
|
from negotiation.chat.service.script_naturalizer import ScriptNaturalizer
|
||||||
|
|
||||||
|
monkeypatch.setattr(ScriptNaturalizer, "available", staticmethod(lambda: False))
|
||||||
|
monkeypatch.setattr(InputInterpreter, "available", staticmethod(lambda: False))
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="session", autouse=True)
|
@pytest_asyncio.fixture(scope="session", autouse=True)
|
||||||
async def _dispose_app_engines():
|
async def _dispose_app_engines():
|
||||||
"""테스트 세션 종료 시 앱 싱글톤 엔진 정리 ('Event loop is closed' 경고 제거)."""
|
"""테스트 세션 종료 시 앱 싱글톤 엔진 정리 ('Event loop is closed' 경고 제거)."""
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# 알고리즘 비교 실험 기본 설정 (H5). E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce
|
# 알고리즘 비교 실험 기본 설정 (H5). E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant imarketkorea
|
||||||
episodes: 600 # 정책당 협상 에피소드 수 (action 11장 탐색 수렴 위해 상향)
|
episodes: 600 # 정책당 협상 에피소드 수 (action 11장 탐색 수렴 위해 상향)
|
||||||
seed: 42 # 재현용 (구매자 randomness 페어드)
|
seed: 42 # 재현용 (구매자 randomness 페어드)
|
||||||
max_turns: 5 # 협상 라운드 상한
|
max_turns: 5 # 협상 라운드 상한
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"""eval_harness 러너 — 정책 비교 + 학습곡선 (H5, PoC 본체).
|
"""eval_harness 러너 — 정책 비교 + 학습곡선 (H5, PoC 본체).
|
||||||
|
|
||||||
E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce
|
E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant imarketkorea
|
||||||
|
|
||||||
판정: 학습형(qtable_ucb)이 random/static 대비 평균보상·성공률 우상향이면 "학습 루프 유효".
|
판정: 학습형(qtable_ucb)이 random/static 대비 평균보상·성공률 우상향이면 "학습 루프 유효".
|
||||||
구매자는 카드별 효과가 다른 시뮬(HeuristicBuyer) — 학습 정책만 좋은 카드를 알아내 성과가 오른다.
|
구매자는 카드별 효과가 다른 시뮬(HeuristicBuyer) — 학습 정책만 좋은 카드를 알아내 성과가 오른다.
|
||||||
@@ -143,7 +143,7 @@ def _print(report: dict):
|
|||||||
def main():
|
def main():
|
||||||
ap = argparse.ArgumentParser(description="협상 정책 비교 하네스 (H5)")
|
ap = argparse.ArgumentParser(description="협상 정책 비교 하네스 (H5)")
|
||||||
ap.add_argument("--config", default="configs/exp_default.yaml")
|
ap.add_argument("--config", default="configs/exp_default.yaml")
|
||||||
ap.add_argument("--tenant", default="ktcommerce")
|
ap.add_argument("--tenant", default="imarketkorea")
|
||||||
ap.add_argument("--save", action="store_true", help="reports/ 에 JSON 저장")
|
ap.add_argument("--save", action="store_true", help="reports/ 에 JSON 저장")
|
||||||
args = ap.parse_args()
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,13 @@ from negotiation.cards.ports.card_script_port import ICardScriptRepository
|
|||||||
|
|
||||||
_NEGO_CARDS = table(
|
_NEGO_CARDS = table(
|
||||||
"nego_cards",
|
"nego_cards",
|
||||||
|
column("number"), column("script"), column("tone"), column("strategy_type"),
|
||||||
|
column("created_at"), column("deleted"),
|
||||||
|
schema="card",
|
||||||
|
)
|
||||||
|
|
||||||
|
_WILD_CARDS = table(
|
||||||
|
"wild_cards",
|
||||||
column("number"), column("script"), column("created_at"), column("deleted"),
|
column("number"), column("script"), column("created_at"), column("deleted"),
|
||||||
schema="card",
|
schema="card",
|
||||||
)
|
)
|
||||||
@@ -27,17 +34,40 @@ _NEGO_CARDS = table(
|
|||||||
|
|
||||||
class CardScriptDbRepository(ICardScriptRepository):
|
class CardScriptDbRepository(ICardScriptRepository):
|
||||||
async def get_script_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
|
async def get_script_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
|
||||||
|
err, card = await self.get_card_by_number(cdb, number)
|
||||||
|
return err, (card[0] if card else None)
|
||||||
|
|
||||||
|
async def get_wild_card_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
|
||||||
|
"""card.wild_cards 멘트 조회 (WC-01~05 선택형 와일드카드/종결 전술 발동용)."""
|
||||||
try:
|
try:
|
||||||
query = (
|
query = (
|
||||||
select(_NEGO_CARDS.c.script)
|
select(_WILD_CARDS.c.script)
|
||||||
|
.where(_WILD_CARDS.c.number == number, _WILD_CARDS.c.deleted == False) # noqa: E712
|
||||||
|
.order_by(desc(_WILD_CARDS.c.created_at))
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_wild_card_script failed.", raise_error=False)
|
||||||
|
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
|
||||||
|
return err_type, None
|
||||||
|
return ErrorType.SUCCESS, str(rows[0]) if not isinstance(rows[0], tuple) else str(rows[0][0])
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, None
|
||||||
|
|
||||||
|
async def get_card_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[tuple]]:
|
||||||
|
try:
|
||||||
|
query = (
|
||||||
|
select(_NEGO_CARDS.c.script, _NEGO_CARDS.c.tone, _NEGO_CARDS.c.strategy_type)
|
||||||
.where(_NEGO_CARDS.c.number == number, _NEGO_CARDS.c.deleted == False) # noqa: E712
|
.where(_NEGO_CARDS.c.number == number, _NEGO_CARDS.c.deleted == False) # noqa: E712
|
||||||
.order_by(desc(_NEGO_CARDS.c.created_at))
|
.order_by(desc(_NEGO_CARDS.c.created_at))
|
||||||
.limit(1)
|
.limit(1)
|
||||||
)
|
)
|
||||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_card_script failed.", raise_error=False)
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_card_script failed.", raise_error=False)
|
||||||
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
|
if err_type != ErrorType.SUCCESS or not rows or not rows[0] or not rows[0][0]:
|
||||||
return err_type, None
|
return err_type, None
|
||||||
return ErrorType.SUCCESS, str(rows[0])
|
script, tone, strategy = rows[0]
|
||||||
|
return ErrorType.SUCCESS, (str(script), int(tone) if tone is not None else None,
|
||||||
|
int(strategy) if strategy is not None else None)
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, None
|
return ErrorType.DB_RUN_FAILED, None
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
"""협상카드 전술 레지스트리 — "멘트 카드 → 전술 카드" 승격 (가격 행동 실행 계층).
|
||||||
|
|
||||||
|
카드 멘트에 이미 설계된 카운터 가격 제시({target_price}·{middle_price} 등)를 시스템 상태로
|
||||||
|
실행한다: 카드가 카운터가를 제시하면 pending_counter_price 로 적재되고, 협력사가 수락하면
|
||||||
|
그 가격으로 즉시 타결된다(기존 wild_card_1pct 의 offer_1pct 패턴을 일반화).
|
||||||
|
|
||||||
|
원칙:
|
||||||
|
- 구매자(갑) 대리이므로 카운터는 항상 min(counter, target_price) 클램프 — 목표가 초과 제시 금지.
|
||||||
|
- 협력사 제시가가 이미 카운터 이하면 카운터가 무의미 → None(HOLD 강등, 순수 설득).
|
||||||
|
- 미등록 카드번호(테넌트 데모 NGC-B*, 회사 커스텀 COMP-* 등)는 HOLD 폴백 → 기존 동작 그대로.
|
||||||
|
|
||||||
|
전술 정본은 이 코드 레지스트리다(v1). negodata 카드 편집은 멘트만 담당하고, 전술을 negodata
|
||||||
|
에서 편집할 필요가 생기면 v2 에서 card.nego_cards 컬럼로 승격해 "DB 우선, 코드 폴백"으로 바꾼다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from enum import Enum
|
||||||
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
|
||||||
|
class PriceAction(str, Enum):
|
||||||
|
HOLD = "hold" # 카운터 없음 — 재제안 요구(순수 설득, 기존 동작)
|
||||||
|
COUNTER_TARGET = "counter_target" # 목표가 제시
|
||||||
|
COUNTER_ANCHOR = "counter_anchor" # 앵커가 제시 (예산 상한 프레이밍)
|
||||||
|
COUNTER_TARGET_MID = "counter_target_mid" # (anchor+target)/2 — 시드 {target_mid_price}
|
||||||
|
COUNTER_MID = "counter_mid" # (갑 직전 포지션+협력사 제시가)/2 — 시드 {middle_price}
|
||||||
|
ONE_PCT = "one_pct" # 제시가 1% 인하 (기존 offer_1pct)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class TacticSpec:
|
||||||
|
"""카드 1장의 전술 명세.
|
||||||
|
|
||||||
|
min_round: 발동 가능 최소 라운드(협력사 가격 입력 횟수 기준).
|
||||||
|
max_price_ratio: input_price ≤ anchor×ratio 일 때만 발동 (None=무제한).
|
||||||
|
closing: 종결 국면(라운드 만료·카드 소진) 우선 전술.
|
||||||
|
"""
|
||||||
|
|
||||||
|
price_action: PriceAction = PriceAction.HOLD
|
||||||
|
min_round: int = 1
|
||||||
|
max_price_ratio: Optional[float] = None
|
||||||
|
closing: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
_DEFAULT = TacticSpec() # HOLD — 미등록 카드 폴백
|
||||||
|
|
||||||
|
# 카드번호 → 전술. 시드(init-data.sql) 멘트의 가격 변수와 1:1 정합.
|
||||||
|
# NGC-001~006: 순수 설득(경쟁 압박/승인 핑계/관계/명분/공정성/TCO) — 가격 변수 없음.
|
||||||
|
# NGC-008: {internet_lowest_price} 인용이나 데이터 소스 미보유 → v1 HOLD (소스 확보 시 승격).
|
||||||
|
_TACTICS: Dict[str, TacticSpec] = {
|
||||||
|
"NGC-007": TacticSpec(PriceAction.COUNTER_ANCHOR), # 예산 상한 안내
|
||||||
|
"NGC-009": TacticSpec(PriceAction.COUNTER_TARGET), # 조건부 가격 조정
|
||||||
|
"NGC-010": TacticSpec(PriceAction.COUNTER_TARGET), # 향후 거래 연계
|
||||||
|
"NGC-011": TacticSpec(PriceAction.COUNTER_TARGET), # 양보 가치 강조
|
||||||
|
"WC-01": TacticSpec(PriceAction.COUNTER_TARGET, min_round=1), # 목표가 선제안
|
||||||
|
"WC-02": TacticSpec(PriceAction.COUNTER_TARGET_MID), # 역제안가 제시
|
||||||
|
"WC-03": TacticSpec(PriceAction.COUNTER_TARGET, closing=True), # 최종 통보(최후통첩)
|
||||||
|
"WC-04": TacticSpec(PriceAction.COUNTER_TARGET, min_round=2), # 단계적 인하 제안
|
||||||
|
"WC-05": TacticSpec(PriceAction.COUNTER_MID, closing=True), # 중간값 절충(종결)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def tactic_for(card_number: Optional[str]) -> TacticSpec:
|
||||||
|
"""카드번호의 전술. 미등록/None 은 HOLD(기존 동작)."""
|
||||||
|
return _TACTICS.get(str(card_number), _DEFAULT) if card_number else _DEFAULT
|
||||||
|
|
||||||
|
|
||||||
|
def tactic_available(spec: TacticSpec, context: Dict[str, Any]) -> bool:
|
||||||
|
"""발동 조건 평가 — action space 마스킹용. HOLD(설득)는 언제나 가능."""
|
||||||
|
if spec.price_action is PriceAction.HOLD:
|
||||||
|
return True
|
||||||
|
rnd = int(context.get("round") or 0)
|
||||||
|
if rnd < spec.min_round:
|
||||||
|
return False
|
||||||
|
if spec.max_price_ratio is not None:
|
||||||
|
price = float(context.get("input_price") or 0)
|
||||||
|
anchor = float(context.get("anchor_price") or 0)
|
||||||
|
if anchor > 0 and price > anchor * spec.max_price_ratio:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def compute_counter(spec: TacticSpec, context: Dict[str, Any]) -> Optional[int]:
|
||||||
|
"""전술의 카운터 제시가 계산 (결정론).
|
||||||
|
|
||||||
|
- 항상 min(counter, target) 클램프 — 구매자는 목표가 초과로 제시하지 않는다.
|
||||||
|
- counter ≥ 협력사 제시가(input_price)면 카운터가 무의미(이미 더 싸게 제시받음) → None.
|
||||||
|
- 필요한 컨텍스트(target/anchor/제시가)가 없으면 None → 호출부가 HOLD 로 강등.
|
||||||
|
"""
|
||||||
|
action = spec.price_action
|
||||||
|
if action is PriceAction.HOLD:
|
||||||
|
return None
|
||||||
|
target = float(context.get("target_price") or 0)
|
||||||
|
anchor = float(context.get("anchor_price") or 0)
|
||||||
|
price = float(context.get("input_price") or 0)
|
||||||
|
if target <= 0 or price <= 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if action is PriceAction.COUNTER_TARGET:
|
||||||
|
counter = target
|
||||||
|
elif action is PriceAction.COUNTER_ANCHOR:
|
||||||
|
counter = anchor
|
||||||
|
elif action is PriceAction.COUNTER_TARGET_MID:
|
||||||
|
counter = (anchor + target) / 2 if anchor > 0 else target
|
||||||
|
elif action is PriceAction.COUNTER_MID:
|
||||||
|
# 갑의 직전 포지션(직전 카운터). 첫 카운터 전에는 앵커가 갑의 포지션이다.
|
||||||
|
prev_customer = float(context.get("prev_customer_price") or anchor or target)
|
||||||
|
counter = (prev_customer + price) / 2
|
||||||
|
elif action is PriceAction.ONE_PCT:
|
||||||
|
counter = price * 0.99
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if counter <= 0:
|
||||||
|
return None
|
||||||
|
counter = min(counter, target) # 목표가 초과 제시 금지 (가드레일)
|
||||||
|
counter_i = int(round(counter))
|
||||||
|
if counter_i >= price:
|
||||||
|
return None # 제시가가 이미 카운터 이하 → 카운터 무의미
|
||||||
|
return counter_i
|
||||||
@@ -21,3 +21,18 @@ class ICardScriptRepository(ABC):
|
|||||||
async def get_script_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
|
async def get_script_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
|
||||||
"""카드코드(card.nego_cards.number)로 멘트(script 평문/마커)를 조회. 없으면 None."""
|
"""카드코드(card.nego_cards.number)로 멘트(script 평문/마커)를 조회. 없으면 None."""
|
||||||
...
|
...
|
||||||
|
|
||||||
|
async def get_card_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[tuple]]:
|
||||||
|
"""멘트 + 메타 (script, tone, strategy_type) 조회 — LLM 표현층의 톤/전략 지시용.
|
||||||
|
|
||||||
|
기본 구현은 script 만 조회하고 메타는 None (파일 소스·구형 더블 호환).
|
||||||
|
"""
|
||||||
|
err, script = await self.get_script_by_number(cdb, number)
|
||||||
|
return err, ((script, None, None) if script else None)
|
||||||
|
|
||||||
|
async def get_wild_card_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
|
||||||
|
"""와일드카드(card.wild_cards.number) 멘트 조회 — 선택형 WC/종결 전술 발동용.
|
||||||
|
|
||||||
|
기본 구현은 미보유(None) — DB 어댑터만 실조회한다(더블 호환).
|
||||||
|
"""
|
||||||
|
return ErrorType.SUCCESS, None
|
||||||
@@ -26,8 +26,9 @@ _SESSIONS = table(
|
|||||||
column("deleted"),
|
column("deleted"),
|
||||||
schema="negotiation",
|
schema="negotiation",
|
||||||
)
|
)
|
||||||
_ITEMS = table("items", column("item_id"), column("price"), column("deleted"), schema="partner")
|
_ITEMS = table("items", column("item_id"), column("name"), column("price"),
|
||||||
_SUPPLIERS = table("suppliers", column("supplier_id"), column("total_revenue"), column("deleted"), schema="partner")
|
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 = table(
|
||||||
"quotations",
|
"quotations",
|
||||||
column("qt_id"), column("version_id"), column("supplier_type"), column("deleted"),
|
column("qt_id"), column("version_id"), column("supplier_type"), column("deleted"),
|
||||||
@@ -72,11 +73,27 @@ class INegoContextCRUD(ABC):
|
|||||||
"""품목 기준가(items.price). 없으면 0."""
|
"""품목 기준가(items.price). 없으면 0."""
|
||||||
pass
|
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
|
@abstractmethod
|
||||||
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
|
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
|
||||||
"""협력사 총매출액(suppliers.total_revenue — KTC 미러). 없으면 0.0."""
|
"""협력사 총매출액(suppliers.total_revenue — KTC 미러). 없으면 0.0."""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def get_item_name(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, Optional[str]]:
|
||||||
|
"""상품명(items.name). 없으면 None — 카드 스크립트 {product_name} 치환용."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, Optional[str]]:
|
||||||
|
"""협력사명(suppliers.name). 없으면 None — 카드 스크립트 {partner_name} 치환용."""
|
||||||
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def get_supply_type(self, cdb: AsyncSession, supplier_id, item_id) -> Tuple[ErrorType, Optional[int]]:
|
async def get_supply_type(self, cdb: AsyncSession, supplier_id, item_id) -> Tuple[ErrorType, Optional[int]]:
|
||||||
"""이 협력사가 이 상품을 공급하는 방식(supplier_items.supply_type: 0=none/1=유통/2=제조/3=총판).
|
"""이 협력사가 이 상품을 공급하는 방식(supplier_items.supply_type: 0=none/1=유통/2=제조/3=총판).
|
||||||
@@ -131,6 +148,21 @@ class NegoContextCRUD(INegoContextCRUD):
|
|||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, 0
|
return ErrorType.DB_RUN_FAILED, 0
|
||||||
|
|
||||||
|
async def get_item_lowest_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||||
|
try:
|
||||||
|
query = (
|
||||||
|
select(_ITEMS.c.internet_lowest_price)
|
||||||
|
.where(_ITEMS.c.item_id == item_id, _ITEMS.c.deleted == False) # noqa: E712
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_item_lowest_price failed.", raise_error=False)
|
||||||
|
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
|
||||||
|
return err_type, 0
|
||||||
|
return ErrorType.SUCCESS, int(rows[0])
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, 0
|
||||||
|
|
||||||
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
|
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
|
||||||
try:
|
try:
|
||||||
query = (
|
query = (
|
||||||
@@ -146,6 +178,36 @@ class NegoContextCRUD(INegoContextCRUD):
|
|||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, 0.0
|
return ErrorType.DB_RUN_FAILED, 0.0
|
||||||
|
|
||||||
|
async def get_item_name(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, Optional[str]]:
|
||||||
|
try:
|
||||||
|
query = (
|
||||||
|
select(_ITEMS.c.name)
|
||||||
|
.where(_ITEMS.c.item_id == item_id, _ITEMS.c.deleted == False) # noqa: E712
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_item_name failed.", raise_error=False)
|
||||||
|
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
|
||||||
|
return err_type, None
|
||||||
|
return ErrorType.SUCCESS, str(rows[0])
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, None
|
||||||
|
|
||||||
|
async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, Optional[str]]:
|
||||||
|
try:
|
||||||
|
query = (
|
||||||
|
select(_SUPPLIERS.c.name)
|
||||||
|
.where(_SUPPLIERS.c.supplier_id == supplier_id, _SUPPLIERS.c.deleted == False) # noqa: E712
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_supplier_name failed.", raise_error=False)
|
||||||
|
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
|
||||||
|
return err_type, None
|
||||||
|
return ErrorType.SUCCESS, str(rows[0])
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, None
|
||||||
|
|
||||||
async def get_supply_type(self, cdb: AsyncSession, supplier_id, item_id) -> Tuple[ErrorType, Optional[int]]:
|
async def get_supply_type(self, cdb: AsyncSession, supplier_id, item_id) -> Tuple[ErrorType, Optional[int]]:
|
||||||
try:
|
try:
|
||||||
query = (
|
query = (
|
||||||
|
|||||||
@@ -10,9 +10,10 @@ import re
|
|||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from negotiation.cards.domain.tactics import compute_counter, tactic_for
|
||||||
from negotiation.chat.service.script_repository import ScriptRepository
|
from negotiation.chat.service.script_repository import ScriptRepository
|
||||||
|
|
||||||
MAX_ROUNDS = 3
|
MAX_ROUNDS = 3 # config 미주입 시 폴백 (규칙 정본은 tenant config negotiation.max_counter_rounds)
|
||||||
_PRICE_MODES = ("price",)
|
_PRICE_MODES = ("price",)
|
||||||
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
||||||
|
|
||||||
@@ -22,6 +23,9 @@ _CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
|||||||
_SUCCESS_STEPS = ("협상완료", "결과제출")
|
_SUCCESS_STEPS = ("협상완료", "결과제출")
|
||||||
_FAILURE_STEPS = ("협상실패",)
|
_FAILURE_STEPS = ("협상실패",)
|
||||||
|
|
||||||
|
# 카운터 제안(pending_counter_price) 수락으로 인정하는 선택 입력.
|
||||||
|
_ACCEPT_INPUTS = ("예", "수락")
|
||||||
|
|
||||||
# 프론트는 표시용 문자열로 가격을 보낸다(예: "530,000원"). 천단위 콤마·통화기호("원")·공백 등
|
# 프론트는 표시용 문자열로 가격을 보낸다(예: "530,000원"). 천단위 콤마·통화기호("원")·공백 등
|
||||||
# 숫자 외 문자를 제거하고 파싱한다. (콤마만 지우면 "원" 때문에 float() 가 실패해 가격 입력이
|
# 숫자 외 문자를 제거하고 파싱한다. (콤마만 지우면 "원" 때문에 float() 가 실패해 가격 입력이
|
||||||
# 영영 저장되지 않고 같은 step 에 머무는 버그가 났었다.)
|
# 영영 저장되지 않고 같은 step 에 머무는 버그가 났었다.)
|
||||||
@@ -72,6 +76,9 @@ class ChatEngine:
|
|||||||
self.rq_type = rq_type
|
self.rq_type = rq_type
|
||||||
self.scripts = scripts_repo.load_scripts(rq_type)
|
self.scripts = scripts_repo.load_scripts(rq_type)
|
||||||
self.step_map = scripts_repo.client_step_mapping()
|
self.step_map = scripts_repo.client_step_mapping()
|
||||||
|
# 결정 스택 규칙층(Phase 1): 와일드카드 진입 임계·라운드 상한을 테넌트 config 에서 읽는다.
|
||||||
|
# (하드코딩 1.02/1.05/3 을 데이터화 — 고객사별로 튜닝 가능, 코드 수정 불필요)
|
||||||
|
self.rules = scripts_repo.config.negotiation
|
||||||
|
|
||||||
# ---- public --------------------------------------------------------
|
# ---- public --------------------------------------------------------
|
||||||
def start(self, session: ChatSession) -> StepView:
|
def start(self, session: ChatSession) -> StepView:
|
||||||
@@ -89,21 +96,27 @@ class ChatEngine:
|
|||||||
if price is None:
|
if price is None:
|
||||||
return self._error(session, "가격을 숫자로 입력해 주세요.")
|
return self._error(session, "가격을 숫자로 입력해 주세요.")
|
||||||
session.context["input_price"] = price
|
session.context["input_price"] = price
|
||||||
|
# 새 가격 제시 = 직전 카운터 제안 거절 확정 → 대기 중 카운터 폐기.
|
||||||
|
session.context.pop("pending_counter_price", None)
|
||||||
|
session.context["prev_partner_price"] = price
|
||||||
# 협력사 첫 제시가 — 가격 수용률(첫 제시가 대비 양보율) 동적 계산의 기준값.
|
# 협력사 첫 제시가 — 가격 수용률(첫 제시가 대비 양보율) 동적 계산의 기준값.
|
||||||
session.context.setdefault("first_offer_price", price)
|
session.context.setdefault("first_offer_price", price)
|
||||||
session.context["round"] = session.context.get("round", 0) + 1
|
session.context["round"] = session.context.get("round", 0) + 1
|
||||||
nxt = self._default_next(node)
|
nxt = self._default_next(node)
|
||||||
elif mode in _CHOICE_MODES:
|
elif mode in _CHOICE_MODES:
|
||||||
# 와일드카드 1% 인하 제안을 수락("예")하면 합의가를 제안가(offer_1pct)로 확정한다.
|
|
||||||
# (멘트에만 쓰이던 offer_1pct 가 input_price 에 반영되지 않아, 요약/입찰가가
|
|
||||||
# 직전 제시가로 잡히던 버그 수정 — 수락 시 실제 합의가는 인하가다.)
|
|
||||||
if session.step == "wild_card_1pct" and user_input == "예" and session.context.get("offer_1pct"):
|
|
||||||
session.context["input_price"] = float(session.context["offer_1pct"])
|
|
||||||
nxt = self._choice_next(node, user_input, session)
|
nxt = self._choice_next(node, user_input, session)
|
||||||
else:
|
else:
|
||||||
nxt = self._default_next(node)
|
nxt = self._default_next(node)
|
||||||
|
|
||||||
nxt = self._resolve(nxt, session)
|
nxt = self._resolve(nxt, session)
|
||||||
|
# 카운터 수락 일반 메커니즘: 카드/와일드카드가 제시한 카운터가(pending_counter_price)를
|
||||||
|
# 협력사가 수락("예"/"수락")한 채 성공 스텝으로 전이하면 합의가 = 카운터가.
|
||||||
|
# (구 offer_1pct 특수 분기의 일반화. 거절인데 성공 스텝으로 가는 경로 — 1% 거절 시
|
||||||
|
# 원 제시가 수락 종결 — 는 카운터를 버리고 기존 input_price 로 타결한다.)
|
||||||
|
if mode in _CHOICE_MODES and nxt in _SUCCESS_STEPS:
|
||||||
|
pending = session.context.pop("pending_counter_price", None)
|
||||||
|
if pending and user_input in _ACCEPT_INPUTS:
|
||||||
|
session.context["input_price"] = float(pending)
|
||||||
return self._render(session, nxt)
|
return self._render(session, nxt)
|
||||||
|
|
||||||
# ---- transition ----------------------------------------------------
|
# ---- transition ----------------------------------------------------
|
||||||
@@ -131,9 +144,9 @@ class ChatEngine:
|
|||||||
return nxt
|
return nxt
|
||||||
|
|
||||||
def _eval_conditions(self, conds: List[dict], session: ChatSession) -> Optional[str]:
|
def _eval_conditions(self, conds: List[dict], session: ChatSession) -> Optional[str]:
|
||||||
"""KT 구매자 관점 조건 평가.
|
"""KT 구매자 관점 조건 평가 (임계값은 config negotiation.* — 규칙층 데이터화).
|
||||||
- 협력사 제시가 ≤ anchor → 우선협상(협상완료).
|
- 협력사 제시가 ≤ anchor → 우선협상(협상완료).
|
||||||
- anchor 살짝 초과(≤ anchor*1.05) + 와일드카드 미사용 → 와일드카드로 인하 압박.
|
- anchor 살짝 초과(≤ anchor×wildcard_entry_ratio) + 와일드카드 미사용 → 와일드카드로 인하 압박.
|
||||||
- 설정 카드(action_space) 모두 소진 → 협상실패.
|
- 설정 카드(action_space) 모두 소진 → 협상실패.
|
||||||
- 그 외 → 가격협상(카드 1장 플레이 후 재제안).
|
- 그 외 → 가격협상(카드 1장 플레이 후 재제안).
|
||||||
"""
|
"""
|
||||||
@@ -151,21 +164,31 @@ class ChatEngine:
|
|||||||
and anchor > 0
|
and anchor > 0
|
||||||
and anchor < price
|
and anchor < price
|
||||||
and (
|
and (
|
||||||
price <= anchor * 1.02
|
price <= anchor * self.rules.wildcard_1pct_ratio
|
||||||
or (bool(ctx.get("allow_selected_wildcards", True)) and price <= anchor * 1.05)
|
or (bool(ctx.get("allow_selected_wildcards", True))
|
||||||
|
and price <= anchor * self.rules.wildcard_entry_ratio)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
elif cond == "check_is_supplier_type_c":
|
elif cond == "check_is_supplier_type_c":
|
||||||
ok = False # 공급사 유형 미보유 (PoC 단순화)
|
ok = False # 공급사 유형 미보유 (PoC 단순화)
|
||||||
elif cond == "check_price_match": # = 우선협상: 제시가가 앵커가 이하
|
elif cond == "check_price_match": # = 우선협상: 제시가가 앵커가 이하
|
||||||
ok = anchor > 0 and price <= anchor
|
ok = anchor > 0 and price <= anchor
|
||||||
elif cond == "check_iteration_limit": # 협상 라운드 상한 또는 카드 소진
|
elif cond == "check_iteration_limit": # 협상 라운드 상한 또는 카드 소진 → 종결 국면
|
||||||
# round 는 매 가격입력마다 증가(기존가격제시=1). 그 이후 카운터제안이 MAX_ROUNDS 회를
|
# round 는 매 가격입력마다 증가(기존가격제시=1). 카운터제안이 상한을 넘거나 카드가
|
||||||
# 넘으면 종료한다. 카드선택(RL)이 실패(state ValueError)해도 used_action_ids 가 안 늘어
|
# 소진되면 곧장 실패가 아니라 **종결 국면**으로 처리한다(실제 MD 협상 방식):
|
||||||
# 카드 소진 조건만으로는 종료되지 않으므로, 라운드 상한을 독립적으로 둬 무한 가격입력을 막는다.
|
# ① 아직 종결 전술을 안 썼으면 → 가격협상으로 보내되 force_closing 마킹
|
||||||
# (선행 chat_server 의 `iteration >= 3` 와 동일한 안전장치.)
|
# (ChatService 가 종결 전술 — 중간값 절충/최후통첩 — 을 강제 발동)
|
||||||
|
# ② 종결 전술까지 소진(closing_played)이면 → 최종 제시가 ≤ target 은 타결,
|
||||||
|
# 초과는 결렬(협상실패) — "목표가 초과 타결 금지" 가드레일과 정합.
|
||||||
counter_rounds = max(0, ctx.get("round", 0) - 1)
|
counter_rounds = max(0, ctx.get("round", 0) - 1)
|
||||||
ok = counter_rounds >= MAX_ROUNDS or (cards_total > 0 and cards_used >= cards_total)
|
exhausted = counter_rounds >= self.rules.max_counter_rounds or (cards_total > 0 and cards_used >= cards_total)
|
||||||
|
if exhausted:
|
||||||
|
target = ctx.get("target_price", 0)
|
||||||
|
if not ctx.get("closing_played"):
|
||||||
|
ctx["force_closing"] = True
|
||||||
|
return "가격협상"
|
||||||
|
return "협상완료" if (target > 0 and price <= target) else c.get("next")
|
||||||
|
ok = False
|
||||||
elif cond == "default":
|
elif cond == "default":
|
||||||
ok = True
|
ok = True
|
||||||
if ok:
|
if ok:
|
||||||
@@ -173,7 +196,7 @@ class ChatEngine:
|
|||||||
return "가격협상"
|
return "가격협상"
|
||||||
|
|
||||||
def _pick_wildcard(self, session: ChatSession) -> str:
|
def _pick_wildcard(self, session: ChatSession) -> str:
|
||||||
"""앵커가에 아주 근접(≤ anchor*1.02)한 구간에서만 1% 인하 요청(wild_card_1pct)으로
|
"""앵커가에 아주 근접(≤ anchor×wildcard_1pct_ratio)한 구간에서만 1% 인하 요청(wild_card_1pct)으로
|
||||||
앵커가 이하로 유도한다. 그 외 구간은 일반 가격협상(카드 플레이)으로 돌린다.
|
앵커가 이하로 유도한다. 그 외 구간은 일반 가격협상(카드 플레이)으로 돌린다.
|
||||||
|
|
||||||
과거 여기서 반환하던 '재원부족'(wild_card_budget) 하드코딩 카드는 제거했다 —
|
과거 여기서 반환하던 '재원부족'(wild_card_budget) 하드코딩 카드는 제거했다 —
|
||||||
@@ -184,12 +207,23 @@ class ChatEngine:
|
|||||||
ctx = session.context
|
ctx = session.context
|
||||||
price = ctx.get("input_price", 0)
|
price = ctx.get("input_price", 0)
|
||||||
anchor = ctx.get("anchor_price", 0)
|
anchor = ctx.get("anchor_price", 0)
|
||||||
if anchor > 0 and price <= anchor * 1.02:
|
if anchor > 0 and price <= anchor * self.rules.wildcard_1pct_ratio:
|
||||||
# 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
|
# 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
|
||||||
# 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
|
# 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
|
||||||
ctx["wildcard_used"] = True
|
ctx["wildcard_used"] = True
|
||||||
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가
|
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가 (멘트 변수)
|
||||||
|
ctx["pending_counter_price"] = ctx["offer_1pct"] # 수락 시 이 가격으로 타결
|
||||||
return "wild_card_1pct"
|
return "wild_card_1pct"
|
||||||
|
# 1.02 초과 ~ entry(1.05) 구간: 견적에서 선택한 와일드카드의 전술로 카운터 제시.
|
||||||
|
# (구현 전에는 이 구간이 일반 가격협상으로 회귀해 선택형 WC 가 영영 발동하지 않던 갭.)
|
||||||
|
if anchor > 0 and price <= anchor * self.rules.wildcard_entry_ratio:
|
||||||
|
for number in (ctx.get("selected_wild_card_numbers") or []):
|
||||||
|
counter = compute_counter(tactic_for(str(number)), ctx)
|
||||||
|
if counter is not None:
|
||||||
|
ctx["wildcard_used"] = True
|
||||||
|
ctx["pending_counter_price"] = counter
|
||||||
|
ctx["active_wild_card_number"] = str(number)
|
||||||
|
return "wild_card_dynamic"
|
||||||
return "가격협상"
|
return "가격협상"
|
||||||
|
|
||||||
# ---- render --------------------------------------------------------
|
# ---- render --------------------------------------------------------
|
||||||
@@ -199,26 +233,79 @@ class ChatEngine:
|
|||||||
out = {}
|
out = {}
|
||||||
if "input_price" in ctx:
|
if "input_price" in ctx:
|
||||||
out["input_price"] = int(ctx["input_price"])
|
out["input_price"] = int(ctx["input_price"])
|
||||||
|
# 목표가/앵커가: 엔진 내부 파일 스크립트는 {target}/{anchor}, negodata 카드 에디터는
|
||||||
|
# {target_price}/{anchor_price}(variables.ts) 를 쓴다 — 양쪽 이름 모두 채워 치환 누락 방지.
|
||||||
if "target_price" in ctx:
|
if "target_price" in ctx:
|
||||||
out["target"] = int(ctx["target_price"])
|
out["target"] = out["target_price"] = int(ctx["target_price"])
|
||||||
if "anchor_price" in ctx:
|
if "anchor_price" in ctx:
|
||||||
out["anchor"] = int(ctx["anchor_price"])
|
# anchoring_price = DB 시드 기본 카드/sessions 컬럼 표기, anchor_price = 카드 에디터 표기.
|
||||||
|
out["anchor"] = out["anchor_price"] = out["anchoring_price"] = int(ctx["anchor_price"])
|
||||||
|
# 카드 에디터 카탈로그의 협력사명/상품명(partner_name·product_name) 치환.
|
||||||
|
if ctx.get("partner_name"):
|
||||||
|
out["partner_name"] = str(ctx["partner_name"])
|
||||||
|
if ctx.get("product_name"):
|
||||||
|
out["product_name"] = str(ctx["product_name"])
|
||||||
if "offer_1pct" in ctx:
|
if "offer_1pct" in ctx:
|
||||||
out["offer_1pct"] = int(ctx["offer_1pct"])
|
out["offer_1pct"] = int(ctx["offer_1pct"])
|
||||||
# 인하율 = (기존 공급가 - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
|
# 인터넷 최저가: 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
|
||||||
|
if "input_price" in ctx:
|
||||||
|
out["prev_partner_price"] = int(ctx.get("prev_partner_price") or ctx["input_price"])
|
||||||
|
prev_customer = ctx.get("prev_customer_price") or anchor
|
||||||
|
if prev_customer:
|
||||||
|
out["prev_customer_price"] = int(prev_customer)
|
||||||
|
if anchor and target:
|
||||||
|
out["target_mid_price"] = int(round((anchor + target) / 2))
|
||||||
|
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"])
|
||||||
|
# 인하율 = (기존 공급가(상품단가) - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
|
||||||
|
# 제시가가 기존가보다 높으면(인상 제시) 음수가 나오는데, "-1.3% 인하된 금액" 같은
|
||||||
|
# 모순 표현이 되므로 discount_rate 는 0 미만 금지하고, 인상/동일/인하를 구분한
|
||||||
|
# 문구는 discount_phrase 로 별도 제공한다(가격협상_확인 멘트가 사용).
|
||||||
base = ctx.get("item_price") or 0
|
base = ctx.get("item_price") or 0
|
||||||
if base > 1 and "input_price" in ctx:
|
if base > 1 and "input_price" in ctx:
|
||||||
out["discount_rate"] = f"{((base - ctx['input_price']) / base) * 100:.1f}"
|
rate = ((base - ctx["input_price"]) / base) * 100
|
||||||
|
out["discount_rate"] = f"{max(0.0, rate):.1f}"
|
||||||
|
if rate >= 0.05:
|
||||||
|
out["discount_phrase"] = f"기존 공급가 대비 약 **{rate:.1f}%** 인하된 금액입니다. "
|
||||||
|
elif rate <= -0.05:
|
||||||
|
out["discount_phrase"] = (
|
||||||
|
f"기존 공급가(**{int(base)}원**)보다 약 **{abs(rate):.1f}%** 높은 금액입니다. ")
|
||||||
|
else:
|
||||||
|
out["discount_phrase"] = "기존 공급가와 동일한 수준의 금액입니다. "
|
||||||
else:
|
else:
|
||||||
out["discount_rate"] = "0.0"
|
out["discount_rate"] = "0.0"
|
||||||
|
out["discount_phrase"] = ""
|
||||||
return out
|
return out
|
||||||
|
|
||||||
def _vars(self, session: ChatSession) -> Dict[str, Any]:
|
def _vars(self, session: ChatSession) -> Dict[str, Any]:
|
||||||
return self.vars_for(session)
|
return self.vars_for(session)
|
||||||
|
|
||||||
|
def render_step(self, session: ChatSession, step_key: str) -> StepView:
|
||||||
|
"""지정 스텝으로 전이·렌더 (공개) — ChatService 가 카드 카운터 제시 시
|
||||||
|
가격협상 → 가격협상_카운터로 스텝을 전환할 때 사용한다."""
|
||||||
|
return self._render(session, step_key)
|
||||||
|
|
||||||
def _render(self, session: ChatSession, step_key: Optional[str]) -> StepView:
|
def _render(self, session: ChatSession, step_key: Optional[str]) -> StepView:
|
||||||
if not step_key or step_key not in self.scripts:
|
if not step_key or step_key not in self.scripts:
|
||||||
return self._error(session, f"다음 단계를 찾을 수 없습니다: {step_key}")
|
return self._error(session, f"다음 단계를 찾을 수 없습니다: {step_key}")
|
||||||
|
# 가드레일(최후 방어선): 구매자 대리는 목표가 초과로 절대 타결하지 않는다.
|
||||||
|
# 카운터 클램프·종결 규칙이 정상이면 도달하지 않지만, 스크립트 편집 실수 등으로
|
||||||
|
# 성공 스텝에 초과가로 진입하면 결렬로 강제 전환한다. (재협상 흐름 한정)
|
||||||
|
if step_key in _SUCCESS_STEPS and self.rq_type == "재협상":
|
||||||
|
ctx = session.context
|
||||||
|
target = ctx.get("target_price") or 0
|
||||||
|
if target > 0 and ctx.get("input_price", 0) > target:
|
||||||
|
step_key = "협상실패"
|
||||||
node = self.scripts[step_key]
|
node = self.scripts[step_key]
|
||||||
session.step = step_key
|
session.step = step_key
|
||||||
chat_end = bool(node.get("chat_end"))
|
chat_end = bool(node.get("chat_end"))
|
||||||
|
|||||||
@@ -0,0 +1,149 @@
|
|||||||
|
"""InputInterpreter — 협력사 자유 발화를 대화 단계 기대 입력으로 구조화 (Phase 3 이해층).
|
||||||
|
|
||||||
|
원칙: "숫자와 결정은 결정론이, 말은 LLM 이" (ScriptNaturalizer 와 동일 철학) —
|
||||||
|
- LLM 의 역할은 ① 의도 분류(choice|price|unknown) ② 가격 '표현의 위치' 찾기까지다.
|
||||||
|
가격 숫자 계산은 LLM 출력이 아니라 결정론 한국어 가격 파서(parse_korean_price)가 수행한다.
|
||||||
|
- 검증: choice 는 허용 선택지 목록에 철자 그대로 있어야 하고, price_text 는 사용자 원문의
|
||||||
|
부분 문자열이어야 한다(환각 차단). 하나라도 어긋나면 None → 호출부가 원문 그대로 폴백
|
||||||
|
(기존 엔진의 재질문 흐름 유지 — 협상은 절대 멈추지 않는다).
|
||||||
|
|
||||||
|
게이트: tenant llm.enabled + 전역 자격증명(ScriptNaturalizer 와 동일). 미설정이면 무동작 —
|
||||||
|
기존 버튼/정형 입력 경로는 그대로 두고, 자유 텍스트일 때만 해석을 시도한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Callable, List, Optional
|
||||||
|
|
||||||
|
from common.logger import LOG
|
||||||
|
from negotiation.profiling.config import LlmCredentials
|
||||||
|
|
||||||
|
# 정형 가격 입력(버튼/필드) — LLM 없이 기존 결정론 경로로 처리 가능한 형태.
|
||||||
|
SIMPLE_PRICE_RE = re.compile(r"\s*[\d,]+(\.\d+)?\s*원?\s*")
|
||||||
|
|
||||||
|
# 한국어 단위 (큰 단위 → 작은 단위 순서로 등장한다고 가정: "1만 2천 500원")
|
||||||
|
_KOREAN_UNITS = {"억": 100_000_000, "만": 10_000, "천": 1_000, "백": 100}
|
||||||
|
_PRICE_TOKEN_RE = re.compile(r"[\d.억만천백]+")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_korean_price(text: str) -> Optional[float]:
|
||||||
|
"""가격 표현 문자열 → 숫자 (결정론). "10,500원"→10500, "1만 500원"→10500, "만원"→10000,
|
||||||
|
"1.5만"→15000, "3만2천원"→32000. 해석 불가/0 이하 → None.
|
||||||
|
"""
|
||||||
|
t = (text or "").replace(",", "").replace(" ", "").replace("원", "").strip()
|
||||||
|
if not t:
|
||||||
|
return None
|
||||||
|
if re.fullmatch(r"\d+(\.\d+)?", t):
|
||||||
|
v = float(t)
|
||||||
|
return v if v > 0 else None
|
||||||
|
if not re.fullmatch(r"[\d.억만천백]+", t):
|
||||||
|
return None # 단위·숫자 외 문자 포함 → 해석 불가(안전 폴백)
|
||||||
|
total, num = 0.0, ""
|
||||||
|
for ch in t:
|
||||||
|
if ch.isdigit() or ch == ".":
|
||||||
|
num += ch
|
||||||
|
else: # 단위 문자
|
||||||
|
try:
|
||||||
|
n = float(num) if num else 1.0 # "만원" = 1만
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
total += n * _KOREAN_UNITS[ch]
|
||||||
|
num = ""
|
||||||
|
if num:
|
||||||
|
try:
|
||||||
|
total += float(num) # 잔여 숫자: "1만500" 의 500
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return total if total > 0 else None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class InterpretedInput:
|
||||||
|
kind: str # "choice" | "price"
|
||||||
|
value: str # ChatEngine.advance 에 그대로 전달할 문자열 ("예" / "10500")
|
||||||
|
source: str # 판단 근거(선택지 원문 또는 가격 표현 원문) — 로깅/투명성용
|
||||||
|
|
||||||
|
|
||||||
|
_SYSTEM = """너는 B2B 구매 협상 챗봇의 입력 해석기다. 협력사(사용자)의 자유 발화를 현재 대화 단계가 기대하는 입력으로 구조화한다.
|
||||||
|
|
||||||
|
규칙 (하나라도 어기면 출력은 폐기된다):
|
||||||
|
- 출력은 JSON 하나만: {"intent": "choice"|"price"|"unknown", "choice": "<선택지 철자 그대로>"|null, "price_text": "<원문 속 가격 표현 그대로>"|null}
|
||||||
|
- choice 는 발화의 '의미'를 선택지 중 하나에 대응시켜, 그 선택지 문자열을 철자 그대로 복사한다.
|
||||||
|
예) 선택지 ["예","아니오"]: "네 접니다"/"맞습니다"/"진행해주세요"/"동의합니다" → "예",
|
||||||
|
"아닌데요"/"제가 아닙니다"/"어렵습니다"/"거절하겠습니다" → "아니오"
|
||||||
|
- 사용자가 구체적 가격을 제시/역제안하면 intent=price. price_text 는 반드시 사용자 원문에 등장한
|
||||||
|
표현을 그대로 복사한다(예: "10,500원", "1만 500원"). 숫자를 계산하거나 변형하지 마라.
|
||||||
|
- 발화가 어느 선택지의 의미인지 정말 판단할 수 없거나 주제와 무관할 때만 intent=unknown."""
|
||||||
|
|
||||||
|
|
||||||
|
def _default_llm_call(messages: List[dict]) -> dict:
|
||||||
|
"""기본 LLM 호출(동기) — 전역 자격증명으로 chat_json. 테스트에서 주입 대체 지점."""
|
||||||
|
from negotiation.profiling.infra.llm_adapter import chat_json
|
||||||
|
|
||||||
|
return chat_json(messages, temperature=0.0, max_tokens=200)
|
||||||
|
|
||||||
|
|
||||||
|
class InputInterpreter:
|
||||||
|
def __init__(self, llm_call: Optional[Callable[[List[dict]], dict]] = None,
|
||||||
|
timeout_seconds: float = 6.0):
|
||||||
|
self._llm_call = llm_call or _default_llm_call
|
||||||
|
self._timeout = timeout_seconds
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def available() -> bool:
|
||||||
|
"""전역 LLM 자격증명이 설정돼 있는가 (테넌트 enabled 게이트는 호출부 몫)."""
|
||||||
|
return LlmCredentials.from_config().is_configured()
|
||||||
|
|
||||||
|
async def interpret(self, user_input: str, *, input_mode: str,
|
||||||
|
input_options: Optional[List[str]] = None,
|
||||||
|
step_script: Optional[str] = None) -> Optional[InterpretedInput]:
|
||||||
|
"""자유 발화 → 기대 입력. 검증 불통과/실패/타임아웃 시 None(호출부 원문 폴백).
|
||||||
|
|
||||||
|
step_script: 직전 봇 질문(맥락) — "네 접니다" 같은 발화는 질문 없이는 의도 판단이
|
||||||
|
애매해 unknown 이 되므로, 무엇에 대한 답인지 함께 준다.
|
||||||
|
"""
|
||||||
|
text = (user_input or "").strip()
|
||||||
|
options = [str(o) for o in (input_options or [])]
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
payload = {
|
||||||
|
"현재 단계 기대 입력": "가격(숫자)" if input_mode == "price" else "선택지 중 하나",
|
||||||
|
"선택지": options,
|
||||||
|
"사용자 발화": text,
|
||||||
|
}
|
||||||
|
if step_script:
|
||||||
|
payload["직전 봇 질문"] = step_script[:300]
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": _SYSTEM},
|
||||||
|
{"role": "user", "content": json.dumps(payload, ensure_ascii=False) + "\n\nJSON 으로만 답하라."},
|
||||||
|
]
|
||||||
|
try:
|
||||||
|
result = await asyncio.wait_for(asyncio.to_thread(self._llm_call, messages), self._timeout)
|
||||||
|
except Exception as ex: # 타임아웃 포함 — 원문 폴백
|
||||||
|
LOG.w(f"[InputInterpreter] LLM 호출 실패(원문 폴백): {ex}")
|
||||||
|
return None
|
||||||
|
if not isinstance(result, dict):
|
||||||
|
return None
|
||||||
|
|
||||||
|
intent = result.get("intent")
|
||||||
|
if intent == "choice":
|
||||||
|
choice = result.get("choice")
|
||||||
|
# 결정: 선택지 목록에 철자 그대로 있어야만 채택 (LLM 이 지어낸 분기 차단).
|
||||||
|
if isinstance(choice, str) and choice in options:
|
||||||
|
return InterpretedInput(kind="choice", value=choice, source=choice)
|
||||||
|
LOG.w(f"[InputInterpreter] 검증 실패: choice={choice!r} ∉ {options}")
|
||||||
|
return None
|
||||||
|
if intent == "price":
|
||||||
|
span = result.get("price_text")
|
||||||
|
# 환각 차단: 가격 표현은 사용자 원문의 부분 문자열이어야 한다.
|
||||||
|
if not isinstance(span, str) or not span.strip() or span.strip() not in text:
|
||||||
|
LOG.w(f"[InputInterpreter] 검증 실패: price_text={span!r} 가 원문에 없음")
|
||||||
|
return None
|
||||||
|
price = parse_korean_price(span.strip()) # 숫자 계산은 결정론 파서가
|
||||||
|
if price is None:
|
||||||
|
LOG.w(f"[InputInterpreter] 검증 실패: 가격 해석 불가 span={span!r}")
|
||||||
|
return None
|
||||||
|
return InterpretedInput(kind="price", value=str(int(price)), source=span.strip())
|
||||||
|
return None # unknown → 원문 폴백(엔진 재질문)
|
||||||
@@ -39,6 +39,9 @@ class NegotiationDbContext:
|
|||||||
target_price: int # 목표 매입가(원) — sessions.target_price
|
target_price: int # 목표 매입가(원) — sessions.target_price
|
||||||
anchor_price: int # 앵커링가 — sessions.anchoring_price(생성 시 박제). 없으면 target(무할인 폴백)
|
anchor_price: int # 앵커링가 — sessions.anchoring_price(생성 시 박제). 없으면 target(무할인 폴백)
|
||||||
item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0
|
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
|
partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE
|
||||||
revenue_amount: float # 매출액(원) — suppliers.total_revenue(KTC 미러). 없으면 0
|
revenue_amount: float # 매출액(원) — suppliers.total_revenue(KTC 미러). 없으면 0
|
||||||
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type. 미지정 시 None
|
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type. 미지정 시 None
|
||||||
@@ -84,6 +87,13 @@ class NegotiationContextLoader:
|
|||||||
# 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시).
|
# 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시).
|
||||||
_, item_price = await self.crud.get_item_price(s, item_id)
|
_, 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)
|
||||||
|
|
||||||
# 파트너사 유형: 상품에 연결된 협력사 수 — supplier_items 매핑(등록 기준) 우선.
|
# 파트너사 유형: 상품에 연결된 협력사 수 — supplier_items 매핑(등록 기준) 우선.
|
||||||
# 매핑이 아직 없으면 협상 세션 이력 기준 폴백(더미보다 항상 낫다). 실패 시 SINGLE.
|
# 매핑이 아직 없으면 협상 세션 이력 기준 폴백(더미보다 항상 낫다). 실패 시 SINGLE.
|
||||||
err, supplier_count = await self.crud.count_item_suppliers(s, item_id)
|
err, supplier_count = await self.crud.count_item_suppliers(s, item_id)
|
||||||
@@ -102,6 +112,9 @@ class NegotiationContextLoader:
|
|||||||
target_price=target,
|
target_price=target,
|
||||||
anchor_price=anchor,
|
anchor_price=anchor,
|
||||||
item_price=item_price,
|
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),
|
partner_type=PartnerType.from_count(supplier_count),
|
||||||
revenue_amount=revenue_amount,
|
revenue_amount=revenue_amount,
|
||||||
distribution_code=_SUPPLIER_TYPE_TO_CODE.get(supplier_type) if supplier_type else None,
|
distribution_code=_SUPPLIER_TYPE_TO_CODE.get(supplier_type) if supplier_type else None,
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
"""ScriptNaturalizer — 협상 카드 멘트를 LLM 으로 상황에 맞게 자연화 (Phase 2 표현층).
|
||||||
|
|
||||||
|
원칙: "숫자와 결정은 결정론이, 말은 LLM 이" —
|
||||||
|
- 입력은 **치환 전 템플릿**({input_price} 등 placeholder 유지 상태). LLM 은 숫자를 절대 만들지 않는다.
|
||||||
|
- 상황(라운드·가격구간·수용률)은 **정성 라벨**로만 전달(수치 미노출 → 숫자 환각 원천 차단).
|
||||||
|
- 검증 실패/타임아웃/미설정 시 None → 호출부가 원본 템플릿 폴백(협상은 절대 안 멈춤).
|
||||||
|
|
||||||
|
검증(ScriptVerifier 철학의 플레인 텍스트판):
|
||||||
|
① {placeholder} 집합이 원본과 정확히 동일(누락·추가 금지)
|
||||||
|
② 원본에 없던 숫자 등장 금지(가격 환각 차단)
|
||||||
|
③ 비어있지 않고 길이 폭주 금지
|
||||||
|
|
||||||
|
게이트: tenant llm.enabled(기본 false) + 전역 LLM 자격증명(config.local.toml [OpenAIConfig]
|
||||||
|
또는 OPENAI_API_KEY env). 호출은 스레드로 넘겨 이벤트루프 비차단 + 타임아웃.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from typing import Any, Callable, Dict, List, Optional
|
||||||
|
|
||||||
|
from common.logger import LOG
|
||||||
|
from negotiation.profiling.config import LlmCredentials
|
||||||
|
|
||||||
|
_PLACEHOLDER_RE = re.compile(r"\{(\w+)\}")
|
||||||
|
_DIGITS_RE = re.compile(r"\d+")
|
||||||
|
# 강조 마커(negodata Slate 편집 정본) — 고객사가 지정한 표시라 자연화가 보존해야 한다.
|
||||||
|
# 색 마커 {{강조|..}} {{안내|..}} 는 여는 토큰 개수로, 굵게/밑줄은 구분자 개수(짝수=쌍)로 센다.
|
||||||
|
_COLOR_OPEN_RE = re.compile(r"\{\{(강조|안내)\|")
|
||||||
|
|
||||||
|
# 카드 메타 코드 → 프롬프트 라벨 (init-data.sql CardTone/CardStrategyType 정의와 동일)
|
||||||
|
_TONE_LABEL = {1: "강경", 2: "정중", 3: "우호", 4: "중립", 5: "단호"}
|
||||||
|
_STRATEGY_LABEL = {1: "경쟁", 2: "수용", 3: "고수", 4: "협력", 5: "선점", 6: "종결"}
|
||||||
|
|
||||||
|
_SYSTEM = """너는 B2B 구매 협상 챗봇의 문장 작성기다. 주어진 협상 카드 멘트 '템플릿'을 협상 상황에 맞게 자연스럽게 다시 쓴다.
|
||||||
|
|
||||||
|
규칙 (하나라도 어기면 출력은 폐기된다):
|
||||||
|
- {변수명} 치환자는 철자 그대로 유지한다. 추가/삭제/변경 금지.
|
||||||
|
- 숫자를 직접 쓰지 마라. 가격·비율 등 모든 수치는 치환자로만 표현한다.
|
||||||
|
- 강조 마커(**굵게** __밑줄__ {{강조|...}} {{안내|...}})는 **개수와 종류를 그대로 유지**한다.
|
||||||
|
고객사가 지정한 강조 표시이므로 삭제·추가·종류변경 금지. 감싼 문구는 자연스럽게 바꿔도 되지만
|
||||||
|
강조된 구절 수만큼 같은 마커로 반드시 다시 감싼다(예: **굵게** 2개면 결과도 **…** 2쌍).
|
||||||
|
- 새로운 약속·할인 조건·법적 표현을 만들지 마라. 원 템플릿의 협상 의도(전술)는 유지한다.
|
||||||
|
- 한국어 존댓말, 2~5문장, 채팅 말풍선에 어울리게 간결히.
|
||||||
|
- 출력은 JSON 하나만: {"script": "다시 쓴 멘트"}"""
|
||||||
|
|
||||||
|
|
||||||
|
def _default_llm_call(messages: List[dict]) -> dict:
|
||||||
|
"""기본 LLM 호출(동기) — 전역 자격증명으로 chat_json. 테스트에서 monkeypatch 지점."""
|
||||||
|
from negotiation.profiling.infra.llm_adapter import chat_json
|
||||||
|
|
||||||
|
return chat_json(messages, temperature=0.5, max_tokens=600)
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptNaturalizer:
|
||||||
|
def __init__(self, llm_call: Optional[Callable[[List[dict]], dict]] = None,
|
||||||
|
timeout_seconds: float = 8.0):
|
||||||
|
self._llm_call = llm_call or _default_llm_call
|
||||||
|
self._timeout = timeout_seconds
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def available() -> bool:
|
||||||
|
"""전역 LLM 자격증명이 설정돼 있는가 (테넌트 enabled 게이트는 호출부 몫)."""
|
||||||
|
return LlmCredentials.from_config().is_configured()
|
||||||
|
|
||||||
|
async def naturalize(self, template: str, *, situation: Optional[Dict[str, Any]] = None,
|
||||||
|
tone: Optional[int] = None, strategy: Optional[int] = None) -> Optional[str]:
|
||||||
|
"""템플릿(치환 전)을 상황 맞춤 문장으로 재작성. 실패/검증불통과 시 None(호출부 폴백)."""
|
||||||
|
if not template or not template.strip():
|
||||||
|
return None
|
||||||
|
ctx = dict(situation or {})
|
||||||
|
if tone in _TONE_LABEL:
|
||||||
|
ctx["톤"] = _TONE_LABEL[tone]
|
||||||
|
if strategy in _STRATEGY_LABEL:
|
||||||
|
ctx["전략"] = _STRATEGY_LABEL[strategy]
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": _SYSTEM},
|
||||||
|
{"role": "user", "content":
|
||||||
|
"템플릿:\n" + template +
|
||||||
|
"\n\n협상 상황:\n" + json.dumps(ctx, ensure_ascii=False) +
|
||||||
|
'\n\n규칙대로 다시 써서 {"script": "..."} 로만 출력.'},
|
||||||
|
]
|
||||||
|
try:
|
||||||
|
result = await asyncio.wait_for(asyncio.to_thread(self._llm_call, messages), self._timeout)
|
||||||
|
except Exception as ex: # 타임아웃 포함 — 폴백
|
||||||
|
LOG.w(f"[ScriptNaturalizer] LLM 호출 실패(폴백): {ex}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
text = result.get("script") if isinstance(result, dict) else None
|
||||||
|
if not isinstance(text, str) or not text.strip():
|
||||||
|
return None
|
||||||
|
return text if self._verify(template, text) else None
|
||||||
|
|
||||||
|
# ---- 검증 ----------------------------------------------------------
|
||||||
|
@staticmethod
|
||||||
|
def _verify(template: str, rewritten: str) -> bool:
|
||||||
|
orig = set(_PLACEHOLDER_RE.findall(template))
|
||||||
|
new = set(_PLACEHOLDER_RE.findall(rewritten))
|
||||||
|
if orig != new:
|
||||||
|
LOG.w(f"[ScriptNaturalizer] 검증 실패: 치환자 불일치 (누락={orig - new}, 추가={new - orig})")
|
||||||
|
return False
|
||||||
|
# 원본에 없던 숫자 금지 — 가격/비율 환각 차단 (수치는 치환자로만).
|
||||||
|
orig_digits = set(_DIGITS_RE.findall(template))
|
||||||
|
new_digits = set(_DIGITS_RE.findall(rewritten)) - orig_digits
|
||||||
|
if new_digits:
|
||||||
|
LOG.w(f"[ScriptNaturalizer] 검증 실패: 새 숫자 등장 {new_digits}")
|
||||||
|
return False
|
||||||
|
if len(rewritten) > max(600, len(template) * 4):
|
||||||
|
LOG.w("[ScriptNaturalizer] 검증 실패: 길이 폭주")
|
||||||
|
return False
|
||||||
|
# 강조 마커 보존 — 고객사가 지정한 볼드/밑줄/색을 LLM 이 떨어뜨리면 폐기(원본 폴백).
|
||||||
|
# 굵게/밑줄: 구분자 총 개수가 같아야 짝(쌍)이 보존됨. 색: 여는 토큰 개수 동일.
|
||||||
|
if (template.count("**") != rewritten.count("**")
|
||||||
|
or template.count("__") != rewritten.count("__")
|
||||||
|
or len(_COLOR_OPEN_RE.findall(template)) != len(_COLOR_OPEN_RE.findall(rewritten))):
|
||||||
|
LOG.w("[ScriptNaturalizer] 검증 실패: 강조 마커 불일치(볼드/색 소실) → 원본 유지")
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def build_situation(context: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
"""세션 컨텍스트 → 정성 상황 라벨 (수치 미노출 — 숫자 환각 차단의 핵심).
|
||||||
|
|
||||||
|
가격구간: 제시가 vs 앵커/목표 관계, 라운드: 협상 진행 단계, 인하 진행: 기존 공급가 대비.
|
||||||
|
"""
|
||||||
|
out: Dict[str, Any] = {}
|
||||||
|
rnd = context.get("round") or 0
|
||||||
|
if rnd:
|
||||||
|
out["라운드"] = "첫 제안" if rnd <= 1 else ("초반 조율" if rnd == 2 else "막바지 조율")
|
||||||
|
price = context.get("input_price") or 0
|
||||||
|
anchor = context.get("anchor_price") or 0
|
||||||
|
target = context.get("target_price") or 0
|
||||||
|
if price and anchor and target:
|
||||||
|
if price <= anchor:
|
||||||
|
out["가격구간"] = "목표 범위 도달(마무리 국면)"
|
||||||
|
elif price <= target:
|
||||||
|
out["가격구간"] = "목표 범위 근접(조율 국면)"
|
||||||
|
else:
|
||||||
|
out["가격구간"] = "목표 상회(추가 인하 필요)"
|
||||||
|
base = context.get("item_price") or 0
|
||||||
|
if base and price:
|
||||||
|
rate = (base - price) / base
|
||||||
|
out["인하 진행"] = "아직 미미" if rate < 0.01 else ("일부 진행" if rate < 0.05 else "상당히 진행")
|
||||||
|
return out
|
||||||
@@ -38,6 +38,11 @@ class ScriptRepository:
|
|||||||
# 카드 멘트 DB 소스(backoffice_db). file 모드면 미사용.
|
# 카드 멘트 DB 소스(backoffice_db). file 모드면 미사용.
|
||||||
self._card_repo: ICardScriptRepository = card_repo or CardScriptDbRepository()
|
self._card_repo: ICardScriptRepository = card_repo or CardScriptDbRepository()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def config(self) -> TenantConfig:
|
||||||
|
"""테넌트 config 노출 — ChatEngine 이 협상 규칙(negotiation.*)을 읽는다."""
|
||||||
|
return self._config
|
||||||
|
|
||||||
# ---- 경로 해석 (_base 폴백) ---------------------------------------
|
# ---- 경로 해석 (_base 폴백) ---------------------------------------
|
||||||
def _resource_path(self, filename: str) -> Optional[str]:
|
def _resource_path(self, filename: str) -> Optional[str]:
|
||||||
scripts_dir = self._config.resources.scripts_dir
|
scripts_dir = self._config.resources.scripts_dir
|
||||||
@@ -89,25 +94,47 @@ class ScriptRepository:
|
|||||||
return None
|
return None
|
||||||
return self.format_script(text, variables)
|
return self.format_script(text, variables)
|
||||||
|
|
||||||
|
async def resolve_card_template(self, action_id: int, card_id: Optional[str],
|
||||||
|
prefer_db: bool = False) -> tuple:
|
||||||
|
"""카드 멘트의 **치환 전 템플릿**과 메타를 해석 → (template, tone, strategy_type).
|
||||||
|
|
||||||
|
cards.source_type == 'backoffice_db' 면 card.nego_cards(DB, tone/strategy 포함) 우선,
|
||||||
|
없거나 file 모드면 scripts_cards.json(파일, 메타 None) 폴백. 둘 다 없으면 (None, None, None).
|
||||||
|
치환 전 템플릿을 그대로 주는 이유: LLM 표현층이 placeholder 를 유지한 채 재작성한 뒤
|
||||||
|
format_script 로 치환해야 숫자를 LLM 이 절대 만지지 않기 때문.
|
||||||
|
"""
|
||||||
|
if (prefer_db or self._config.cards.source_type == _CARD_SOURCE_DB) and card_id:
|
||||||
|
card = await self._fetch_card_db(card_id)
|
||||||
|
if card:
|
||||||
|
return card # (script, tone, strategy)
|
||||||
|
return self.card_scripts().get(str(action_id)), None, None # 파일 폴백(메타 없음)
|
||||||
|
|
||||||
async def resolve_card_script(self, action_id: int, card_id: Optional[str],
|
async def resolve_card_script(self, action_id: int, card_id: Optional[str],
|
||||||
variables: Optional[Dict[str, Any]] = None,
|
variables: Optional[Dict[str, Any]] = None,
|
||||||
prefer_db: bool = False) -> Optional[str]:
|
prefer_db: bool = False) -> Optional[str]:
|
||||||
"""카드 멘트 해석. cards.source_type == 'backoffice_db' 면 card.nego_cards.script(DB)를
|
"""카드 멘트 해석(템플릿 + 변수 치환). DB(정본) 우선 → 파일 폴백. 마커는 불투명 텍스트."""
|
||||||
우선 조회하고, 없거나 file 모드면 scripts_cards.json(파일) 폴백. 변수 치환 후 반환.
|
template, _, _ = await self.resolve_card_template(action_id, card_id, prefer_db=prefer_db)
|
||||||
|
if not template:
|
||||||
|
return None
|
||||||
|
return self.format_script(template, variables)
|
||||||
|
|
||||||
DB 멘트는 백오피스(negodata)가 편집한 정본이라 파일보다 우선한다. 마커(**굵게** 등)가
|
async def resolve_wild_card_template(self, number: str) -> Optional[str]:
|
||||||
섞여 있어도 agent 는 불투명 텍스트로 취급 — 표현 렌더는 프론트 소유.
|
"""선택형 와일드카드(WC-*) 멘트 템플릿 — card.wild_cards(DB, negodata 편집 정본) 조회.
|
||||||
"""
|
없거나 DB 불가면 None(호출부가 스텝 기본 멘트 폴백)."""
|
||||||
if (prefer_db or self._config.cards.source_type == _CARD_SOURCE_DB) and card_id:
|
|
||||||
db_text = await self._fetch_card_script_db(card_id)
|
|
||||||
if db_text:
|
|
||||||
return self.format_script(db_text, variables)
|
|
||||||
return self.card_script(action_id, variables) # 파일 폴백
|
|
||||||
|
|
||||||
async def _fetch_card_script_db(self, card_id: str) -> Optional[str]:
|
|
||||||
async def _q(s):
|
async def _q(s):
|
||||||
_, text = await self._card_repo.get_script_by_number(s, card_id)
|
_, script = await self._card_repo.get_wild_card_by_number(s, number)
|
||||||
return text
|
return script
|
||||||
|
|
||||||
|
try:
|
||||||
|
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(f"[ScriptRepository] 와일드카드 멘트 DB 조회 실패 number={number}: {ex}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _fetch_card_db(self, card_id: str) -> Optional[tuple]:
|
||||||
|
async def _q(s):
|
||||||
|
_, card = await self._card_repo.get_card_by_number(s, card_id)
|
||||||
|
return card
|
||||||
|
|
||||||
try:
|
try:
|
||||||
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||||
|
|||||||
@@ -41,6 +41,9 @@ class PolicyContext:
|
|||||||
action_space_size: int
|
action_space_size: int
|
||||||
episode: EpisodeState
|
episode: EpisodeState
|
||||||
available_mask: Optional[np.ndarray] = None # None 이면 used_action_ids 로 산출
|
available_mask: Optional[np.ndarray] = None # None 이면 used_action_ids 로 산출
|
||||||
|
# 의도층 prior(Phase 1): 갑이 견적에서 고른 카드 순서 등 사전 선호. 방문수로 감쇠되어
|
||||||
|
# 콜드 스타트 선택만 편향하고 학습(Q)이 쌓이면 영향이 소멸한다 — Q-table 오염 없음.
|
||||||
|
prior_bonus: Optional[np.ndarray] = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
|
|||||||
@@ -36,7 +36,8 @@ class UCBQTablePolicy(NegotiationPolicy):
|
|||||||
avail = [a for a in range(ctx.action_space_size) if a not in used]
|
avail = [a for a in range(ctx.action_space_size) if a not in used]
|
||||||
return avail or list(range(ctx.action_space_size)) # 다 썼으면 전체 허용
|
return avail or list(range(ctx.action_space_size)) # 다 썼으면 전체 허용
|
||||||
|
|
||||||
def _ucb_scores(self, state_index: int, available: List[int]) -> np.ndarray:
|
def _ucb_scores(self, state_index: int, available: List[int],
|
||||||
|
prior: "np.ndarray | None" = None) -> np.ndarray:
|
||||||
q = self.qtable.row(state_index)
|
q = self.qtable.row(state_index)
|
||||||
visits = self.qtable.visit_row(state_index)
|
visits = self.qtable.visit_row(state_index)
|
||||||
total = self.qtable.state_visits(state_index)
|
total = self.qtable.state_visits(state_index)
|
||||||
@@ -45,11 +46,15 @@ class UCBQTablePolicy(NegotiationPolicy):
|
|||||||
for a in available:
|
for a in available:
|
||||||
bonus = self.c * math.sqrt(ln / (visits[a] + 1e-6))
|
bonus = self.c * math.sqrt(ln / (visits[a] + 1e-6))
|
||||||
scores[a] = q[a] + bonus
|
scores[a] = q[a] + bonus
|
||||||
|
if prior is not None:
|
||||||
|
# 의도층 prior — 방문수 감쇠: 콜드 스타트 동점(전부 Q=0·bonus=0)일 때만 순서를
|
||||||
|
# 결정하고, 학습이 쌓이면 1/(1+visits) 로 사라진다.
|
||||||
|
scores[a] += float(prior[a]) / (1.0 + visits[a])
|
||||||
return scores
|
return scores
|
||||||
|
|
||||||
def select(self, ctx: PolicyContext) -> ActionDecision:
|
def select(self, ctx: PolicyContext) -> ActionDecision:
|
||||||
available = self._available(ctx)
|
available = self._available(ctx)
|
||||||
scores = self._ucb_scores(ctx.state_index, available)
|
scores = self._ucb_scores(ctx.state_index, available, prior=ctx.prior_bonus)
|
||||||
action_id = int(np.argmax(scores))
|
action_id = int(np.argmax(scores))
|
||||||
n = len(available)
|
n = len(available)
|
||||||
# ε-greedy 근사 propensity (greedy 액션)
|
# ε-greedy 근사 propensity (greedy 액션)
|
||||||
|
|||||||
@@ -53,6 +53,9 @@ class Res_Chat(Res_WebPacketProtocol):
|
|||||||
# 성공 확정 이후 턴(협상완료 요약·협상종료)에 내려주는 합의가. 와일드카드 1% 인하 수락 등
|
# 성공 확정 이후 턴(협상완료 요약·협상종료)에 내려주는 합의가. 와일드카드 1% 인하 수락 등
|
||||||
# 유저가 직접 입력하지 않은 가격으로 타결될 수 있어, backend 요약/입찰가는 이 값을 최우선 사용한다.
|
# 유저가 직접 입력하지 않은 가격으로 타결될 수 있어, backend 요약/입찰가는 이 값을 최우선 사용한다.
|
||||||
settled_price: Optional[int] = None
|
settled_price: Optional[int] = None
|
||||||
|
# Phase 3 이해층: 자유 발화를 NLU 로 해석해 진행한 경우, 엔진에 실제 전달된 입력.
|
||||||
|
# (예: "만원까지는 어렵고 10,500원이면 가능합니다" → "10500") 미해석/정형 입력이면 None.
|
||||||
|
interpreted_input: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
class Res_ChatSession(Res_WebPacketProtocol):
|
class Res_ChatSession(Res_WebPacketProtocol):
|
||||||
|
|||||||
@@ -13,10 +13,15 @@ from common.enums import DBType, ErrorType
|
|||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from config.server_configs import agent_config
|
from config.server_configs import agent_config
|
||||||
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession, StepView
|
from negotiation.cards.domain.tactics import compute_counter, tactic_available, tactic_for
|
||||||
|
from negotiation.chat.service.chat_engine import (
|
||||||
|
_CHOICE_MODES, _PRICE_MODES, ChatEngine, ChatSession, StepView,
|
||||||
|
)
|
||||||
from negotiation.chat.service.indicator import compute_indicator
|
from negotiation.chat.service.indicator import compute_indicator
|
||||||
|
from negotiation.chat.service.input_interpreter import SIMPLE_PRICE_RE, InputInterpreter
|
||||||
from negotiation.chat.service.chat_session_repository import ChatSessionRepository
|
from negotiation.chat.service.chat_session_repository import ChatSessionRepository
|
||||||
from negotiation.chat.service.negotiation_context_loader import NegotiationContextLoader
|
from negotiation.chat.service.negotiation_context_loader import NegotiationContextLoader
|
||||||
|
from negotiation.chat.service.script_naturalizer import ScriptNaturalizer, build_situation
|
||||||
from negotiation.chat.service.script_repository import ScriptRepository
|
from negotiation.chat.service.script_repository import ScriptRepository
|
||||||
from negotiation.policies.base import EpisodeState, PolicyContext, Transition
|
from negotiation.policies.base import EpisodeState, PolicyContext, Transition
|
||||||
from negotiation.policy.model_store import QTablePolicyStore
|
from negotiation.policy.model_store import QTablePolicyStore
|
||||||
@@ -34,9 +39,17 @@ _DEFAULT_TARGET_PRICE = 10000 # KT 목표 매입가
|
|||||||
_DEFAULT_ANCHOR_PRICE = 9900 # 앵커링가(목표가보다 낮음). 제시가 ≤ anchor → 우선협상
|
_DEFAULT_ANCHOR_PRICE = 9900 # 앵커링가(목표가보다 낮음). 제시가 ≤ anchor → 우선협상
|
||||||
_DEFAULT_REVENUE_AMOUNT = 20_000_000 # 매출액(원) — suppliers.total_revenue 미기재 시 폴백
|
_DEFAULT_REVENUE_AMOUNT = 20_000_000 # 매출액(원) — suppliers.total_revenue 미기재 시 폴백
|
||||||
_DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — supplier_items.supply_type 미지정 시 폴백
|
_DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — supplier_items.supply_type 미지정 시 폴백
|
||||||
|
_DEFAULT_PARTNER_NAME = "귀사" # 협력사명 — suppliers.name 미기재/데모 시 폴백(카드 {partner_name})
|
||||||
|
_DEFAULT_PRODUCT_NAME = "본 상품" # 상품명 — items.name 미기재/데모 시 폴백(카드 {product_name})
|
||||||
|
|
||||||
|
|
||||||
class ChatService:
|
class ChatService:
|
||||||
|
# Phase 2 표현층 / Phase 3 이해층 — 테넌트 llm.enabled + 전역 자격증명일 때만 사용(기본 무동작).
|
||||||
|
# 클래스 속성인 이유: FastAPI 가 ChatService 를 Depends 로 쓰므로 __init__ 파라미터를 두면
|
||||||
|
# 쿼리 파라미터로 해석된다. 테스트는 인스턴스 속성으로 덮어 주입한다.
|
||||||
|
_naturalizer = ScriptNaturalizer()
|
||||||
|
_interpreter = InputInterpreter()
|
||||||
|
|
||||||
async def chat(self, engine: TenantEngine, req: Req_Chat) -> Res_Chat:
|
async def chat(self, engine: TenantEngine, req: Req_Chat) -> Res_Chat:
|
||||||
res = Res_Chat()
|
res = Res_Chat()
|
||||||
repo = ScriptRepository(engine.config, agent_config.tenants_dir)
|
repo = ScriptRepository(engine.config, agent_config.tenants_dir)
|
||||||
@@ -91,9 +104,15 @@ class ChatService:
|
|||||||
# 목표가/앵커링가: sessions 행(생성 시 박제된 anchoring_price) → 박제 ‰ → 1% 폴백 (loader).
|
# 목표가/앵커링가: sessions 행(생성 시 박제된 anchoring_price) → 박제 ‰ → 1% 폴백 (loader).
|
||||||
"anchor_price": db_ctx.anchor_price if db_ctx else _DEFAULT_ANCHOR_PRICE,
|
"anchor_price": db_ctx.anchor_price if db_ctx else _DEFAULT_ANCHOR_PRICE,
|
||||||
"target_price": db_ctx.target_price if db_ctx else _DEFAULT_TARGET_PRICE,
|
"target_price": db_ctx.target_price if db_ctx else _DEFAULT_TARGET_PRICE,
|
||||||
|
# 협력사명/상품명 — 카드 스크립트 {partner_name}·{product_name} 치환용(loader). 없으면 폴백.
|
||||||
|
"partner_name": (db_ctx.partner_name if db_ctx and db_ctx.partner_name else _DEFAULT_PARTNER_NAME),
|
||||||
|
"product_name": (db_ctx.product_name if db_ctx and db_ctx.product_name else _DEFAULT_PRODUCT_NAME),
|
||||||
"round": 0,
|
"round": 0,
|
||||||
# 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용.
|
# 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용.
|
||||||
"item_price": db_ctx.item_price if db_ctx else 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 에 그대로 매핑한다.
|
# 견적 생성 시 선택한 카드. 일반카드는 action_id 0..N-1 에 그대로 매핑한다.
|
||||||
# 1% 인하는 기본 와일드카드로 항상 열고, 재원부족 등 선택형 와일드카드는
|
# 1% 인하는 기본 와일드카드로 항상 열고, 재원부족 등 선택형 와일드카드는
|
||||||
# 선택된 와일드카드가 있을 때만 허용한다.
|
# 선택된 와일드카드가 있을 때만 허용한다.
|
||||||
@@ -105,7 +124,10 @@ class ChatService:
|
|||||||
)
|
)
|
||||||
view = chat_engine.start(session)
|
view = chat_engine.start(session)
|
||||||
else:
|
else:
|
||||||
view = chat_engine.advance(session, req.user_input)
|
# Phase 3 이해층: 자유 발화(버튼/정형 입력이 아닌 텍스트)를 기대 입력으로 해석.
|
||||||
|
# 해석 실패/미설정 시 원문 그대로 → 기존 엔진 재질문 흐름 유지.
|
||||||
|
user_input = await self._interpret_input(engine, chat_engine, session, req.user_input, res)
|
||||||
|
view = chat_engine.advance(session, user_input)
|
||||||
|
|
||||||
# 2) 응답 기본 채움 (학습 블록이 가격협상 턴에서 script/indicator 를 덮어쓸 수 있어 먼저 채운다)
|
# 2) 응답 기본 채움 (학습 블록이 가격협상 턴에서 script/indicator 를 덮어쓸 수 있어 먼저 채운다)
|
||||||
res.session_id = session.session_id
|
res.session_id = session.session_id
|
||||||
@@ -122,6 +144,18 @@ class ChatService:
|
|||||||
if session.context.get("final_outcome") == "success" and session.context.get("input_price"):
|
if session.context.get("final_outcome") == "success" and session.context.get("input_price"):
|
||||||
res.settled_price = int(session.context["input_price"])
|
res.settled_price = int(session.context["input_price"])
|
||||||
|
|
||||||
|
# 선택형 와일드카드 턴(wild_card_dynamic): 멘트 정본은 card.wild_cards(negodata 편집).
|
||||||
|
# DB 멘트가 있으면 스텝 기본 멘트를 대체하고, 없으면 기본 멘트(counter_price 치환)로 진행.
|
||||||
|
if view.step == "wild_card_dynamic" and session.context.get("active_wild_card_number"):
|
||||||
|
number = session.context["active_wild_card_number"]
|
||||||
|
template = await repo.resolve_wild_card_template(number)
|
||||||
|
if template:
|
||||||
|
if engine.config.llm.enabled and ScriptNaturalizer.available():
|
||||||
|
template = (await self._naturalizer.naturalize(
|
||||||
|
template, situation=build_situation(session.context))) or template
|
||||||
|
res.script = repo.format_script(template, chat_engine.vars_for(session))
|
||||||
|
res.card_id = number
|
||||||
|
|
||||||
# 3) 학습 결합 (가격협상 카드선택 → 카드 스크립트·협상지표 / 종료 보상)
|
# 3) 학습 결합 (가격협상 카드선택 → 카드 스크립트·협상지표 / 종료 보상)
|
||||||
if view.error is None and session.action_space_size > 0:
|
if view.error is None and session.action_space_size > 0:
|
||||||
if view.needs_card_selection:
|
if view.needs_card_selection:
|
||||||
@@ -154,6 +188,53 @@ class ChatService:
|
|||||||
res.found = True
|
res.found = True
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
# ---- Phase 3 이해층 (자유 발화 NLU) ---------------------------------
|
||||||
|
async def _interpret_input(self, engine: TenantEngine, chat_engine: ChatEngine,
|
||||||
|
session: ChatSession, user_input: Optional[str], res: Res_Chat) -> Optional[str]:
|
||||||
|
"""자유 발화를 현재 step 의 기대 입력으로 해석해 엔진에 넘길 문자열을 돌려준다.
|
||||||
|
|
||||||
|
결정론 fast path 우선: 정형 가격([\\d,]+원?)·버튼 값 그대로면 LLM 을 부르지 않는다.
|
||||||
|
자유 텍스트 + llm.enabled + 자격증명일 때만 InputInterpreter 호출. 해석 실패/미설정이면
|
||||||
|
원문 그대로 반환 → 기존 엔진의 재질문/기본분기 흐름이 그대로 동작(협상 불중단).
|
||||||
|
"""
|
||||||
|
if user_input is None:
|
||||||
|
return user_input
|
||||||
|
raw = str(user_input).strip()
|
||||||
|
if not raw:
|
||||||
|
return user_input
|
||||||
|
node = chat_engine.scripts.get(session.step, {})
|
||||||
|
mode = node.get("next_input_mode", "null")
|
||||||
|
options: list = []
|
||||||
|
if mode in _PRICE_MODES:
|
||||||
|
if SIMPLE_PRICE_RE.fullmatch(raw):
|
||||||
|
return user_input # 정형 가격 — 기존 결정론 파서 경로
|
||||||
|
elif mode in _CHOICE_MODES:
|
||||||
|
options = self._step_options(node)
|
||||||
|
if raw in options:
|
||||||
|
return user_input # 버튼 값 그대로 — 결정론 경로
|
||||||
|
else:
|
||||||
|
return user_input # 입력을 받지 않는 스텝
|
||||||
|
if not (engine.config.llm.enabled and InputInterpreter.available()):
|
||||||
|
return user_input
|
||||||
|
out = await self._interpreter.interpret(raw, input_mode=mode, input_options=options,
|
||||||
|
step_script=node.get("script"))
|
||||||
|
if out is None:
|
||||||
|
return user_input
|
||||||
|
LOG.i(f"[ChatService] NLU: {raw!r} → {out.kind}={out.value!r} (근거={out.source!r}) session={session.session_id}")
|
||||||
|
res.interpreted_input = out.value # 투명성: backend/front 가 해석 결과를 표시할 수 있게
|
||||||
|
return out.value
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _step_options(node: dict) -> list:
|
||||||
|
"""현재 step 이 허용하는 선택지 — input_options 우선, next_step 분기 키 보강."""
|
||||||
|
opts = [str(o) for o in (node.get("input_options") or [])]
|
||||||
|
ns = node.get("next_step")
|
||||||
|
if isinstance(ns, dict):
|
||||||
|
for k in ns.keys():
|
||||||
|
if k != "default" and str(k) not in opts:
|
||||||
|
opts.append(str(k))
|
||||||
|
return opts
|
||||||
|
|
||||||
# ---- 학습 ----------------------------------------------------------
|
# ---- 학습 ----------------------------------------------------------
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _acceptance_ratio(context: dict) -> float:
|
def _acceptance_ratio(context: dict) -> float:
|
||||||
@@ -183,6 +264,11 @@ class ChatService:
|
|||||||
|
|
||||||
async def _select_and_learn(self, engine: TenantEngine, chat_engine: ChatEngine,
|
async def _select_and_learn(self, engine: TenantEngine, chat_engine: ChatEngine,
|
||||||
scripts: ScriptRepository, session: ChatSession, res: Res_Chat):
|
scripts: ScriptRepository, session: ChatSession, res: Res_Chat):
|
||||||
|
# 종결 국면(라운드 만료·카드 소진, 엔진 check_iteration_limit 이 마킹): 규칙층이
|
||||||
|
# 종결 전술(중간값 절충/최후통첩)을 강제 발동한다 — RL 선택·학습 대상이 아니다.
|
||||||
|
if session.context.pop("force_closing", False):
|
||||||
|
await self._play_closing_tactic(engine, chat_engine, scripts, session, res)
|
||||||
|
return
|
||||||
snap = self._snapshot(session, NegotiationOutcome.ONGOING)
|
snap = self._snapshot(session, NegotiationOutcome.ONGOING)
|
||||||
try:
|
try:
|
||||||
idx = state_index(snap, engine.config.state)
|
idx = state_index(snap, engine.config.state)
|
||||||
@@ -192,13 +278,22 @@ class ChatService:
|
|||||||
policy, version_id, repo = await QTablePolicyStore.load(engine)
|
policy, version_id, repo = await QTablePolicyStore.load(engine)
|
||||||
# action space 는 카탈로그 전체(engine.action_space_size)로 고정 — action_id↔카드 대응을
|
# action space 는 카탈로그 전체(engine.action_space_size)로 고정 — action_id↔카드 대응을
|
||||||
# 견적마다 일정하게 유지해 Q-table 학습 일관성을 지킨다. 견적 선택은 축소가 아니라
|
# 견적마다 일정하게 유지해 Q-table 학습 일관성을 지킨다. 견적 선택은 축소가 아니라
|
||||||
# available_mask 로 처리한다(선택 카드만 pickable, 사용분 제외).
|
# available_mask 로 처리한다(선택 카드만 pickable, 사용분 제외 + 전술 발동조건 AND).
|
||||||
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=engine.action_space_size,
|
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=engine.action_space_size,
|
||||||
available_mask=self._selection_mask(engine, session),
|
available_mask=self._combined_mask(engine, session),
|
||||||
|
prior_bonus=self._selection_prior(engine, session),
|
||||||
episode=EpisodeState(used_action_ids=set(session.used_action_ids)))
|
episode=EpisodeState(used_action_ids=set(session.used_action_ids)))
|
||||||
decision = policy.select(ctx)
|
decision = policy.select(ctx)
|
||||||
session.used_action_ids.add(decision.action_id)
|
session.used_action_ids.add(decision.action_id)
|
||||||
card_id = self._card_id_for_action(engine, session, decision.action_id)
|
card_id = self._card_id_for_action(engine, session, decision.action_id)
|
||||||
|
# 전술 실행(재설계): 카드의 가격 행동 — 카운터 제시가를 계산해 세션에 적재한다.
|
||||||
|
# pending 이 있으면 이 턴은 수락/거절 스텝(가격협상_카운터)으로 전환되고,
|
||||||
|
# 협력사가 수락하면 이 가격으로 즉시 타결된다(chat_engine 의 수락 메커니즘).
|
||||||
|
spec = tactic_for(card_id)
|
||||||
|
counter = compute_counter(spec, session.context) if tactic_available(spec, session.context) else None
|
||||||
|
if counter is not None:
|
||||||
|
session.context["pending_counter_price"] = counter
|
||||||
|
session.context["prev_customer_price"] = counter # 갑의 최신 포지션(middle_price 기준)
|
||||||
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
|
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
|
||||||
policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=reward.total, done=False))
|
policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=reward.total, done=False))
|
||||||
await QTablePolicyStore.persist_cell(repo, version_id, policy, idx, decision.action_id)
|
await QTablePolicyStore.persist_cell(repo, version_id, policy, idx, decision.action_id)
|
||||||
@@ -217,12 +312,17 @@ class ChatService:
|
|||||||
# ① 선택된 카드의 스크립트를 봇 메시지(script)로 출력 ② 협상지표 게이지(indicator_value) 동봉.
|
# ① 선택된 카드의 스크립트를 봇 메시지(script)로 출력 ② 협상지표 게이지(indicator_value) 동봉.
|
||||||
# backend/front 가 indicator/bot_chat_type 패스스루·게이지 렌더 준비 완료 → 값만 채우면 표시된다.
|
# backend/front 가 indicator/bot_chat_type 패스스루·게이지 렌더 준비 완료 → 값만 채우면 표시된다.
|
||||||
# 카드 멘트: backoffice_db 모드면 card.nego_cards.script(negodata 편집 정본), 아니면 파일 폴백.
|
# 카드 멘트: backoffice_db 모드면 card.nego_cards.script(negodata 편집 정본), 아니면 파일 폴백.
|
||||||
card_script = await scripts.resolve_card_script(
|
template, tone, strategy = await scripts.resolve_card_template(
|
||||||
decision.action_id,
|
decision.action_id, card_id,
|
||||||
card_id,
|
|
||||||
chat_engine.vars_for(session),
|
|
||||||
prefer_db=bool(session.context.get("selected_nego_card_numbers")),
|
prefer_db=bool(session.context.get("selected_nego_card_numbers")),
|
||||||
)
|
)
|
||||||
|
# Phase 2 표현층: llm.enabled(테넌트) + 자격증명 있으면 템플릿을 상황 맞춤 자연화.
|
||||||
|
# placeholder 유지 상태로 재작성 → 검증(치환자/숫자) → 실패·타임아웃 시 원본 폴백.
|
||||||
|
if template and engine.config.llm.enabled and ScriptNaturalizer.available():
|
||||||
|
naturalized = await self._naturalizer.naturalize(
|
||||||
|
template, situation=build_situation(session.context), tone=tone, strategy=strategy)
|
||||||
|
template = naturalized or template
|
||||||
|
card_script = scripts.format_script(template, chat_engine.vars_for(session)) if template else None
|
||||||
if card_script:
|
if card_script:
|
||||||
res.script = card_script
|
res.script = card_script
|
||||||
c = session.context
|
c = session.context
|
||||||
@@ -232,6 +332,49 @@ class ChatService:
|
|||||||
res.indicator_range = ind[1]
|
res.indicator_range = ind[1]
|
||||||
res.bot_chat_type = "indicator"
|
res.bot_chat_type = "indicator"
|
||||||
|
|
||||||
|
# 카운터 제시 카드면 수락/거절 스텝(가격협상_카운터)으로 전환 — 카드 멘트({target_price} 등
|
||||||
|
# 카운터가 포함)는 그대로 두고, 입력만 [수락|다른 가격 제시] 버튼으로 바꾼다.
|
||||||
|
if counter is not None:
|
||||||
|
view2 = chat_engine.render_step(session, "가격협상_카운터")
|
||||||
|
res.step, res.client_step = view2.step, view2.client_step
|
||||||
|
res.input_mode, res.input_options = view2.input_mode, view2.input_options
|
||||||
|
if not card_script:
|
||||||
|
res.script = view2.script # 카드 멘트 없으면 스텝 기본 카운터 멘트
|
||||||
|
|
||||||
|
async def _play_closing_tactic(self, engine: TenantEngine, chat_engine: ChatEngine,
|
||||||
|
scripts: ScriptRepository, session: ChatSession, res: Res_Chat):
|
||||||
|
"""종결 국면 강제 전술 — 견적에서 선택한 종결 와일드카드(WC-05 중간값 절충 등) 우선,
|
||||||
|
없으면 목표가 최후통첩. 최종 카운터를 제시하고 수락/거절 스텝으로 전환한다.
|
||||||
|
규칙층의 강제 결정이므로 RL 선택/학습을 우회한다."""
|
||||||
|
ctx = session.context
|
||||||
|
ctx["closing_played"] = True
|
||||||
|
# 선택 와일드카드 중 종결 전술 (WC-05/WC-03) — 순서대로 첫 매치.
|
||||||
|
closing_number = next(
|
||||||
|
(str(n) for n in (ctx.get("selected_wild_card_numbers") or []) if tactic_for(str(n)).closing),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
counter = compute_counter(tactic_for(closing_number), ctx) if closing_number else None
|
||||||
|
if counter is None:
|
||||||
|
# 폴백 최후통첩: 목표가 제시 (여기 도달 = 제시가 > target 이므로 항상 유효한 카운터).
|
||||||
|
target = int(ctx.get("target_price") or 0)
|
||||||
|
counter = target if 0 < target < ctx.get("input_price", 0) else None
|
||||||
|
if counter is None:
|
||||||
|
return # 컨텍스트 이상 — 기존 가격협상 스텝 그대로(재제안 요구)
|
||||||
|
ctx["pending_counter_price"] = counter
|
||||||
|
ctx["prev_customer_price"] = counter
|
||||||
|
|
||||||
|
template = None
|
||||||
|
if closing_number:
|
||||||
|
template = await scripts.resolve_wild_card_template(closing_number)
|
||||||
|
if template and engine.config.llm.enabled and ScriptNaturalizer.available():
|
||||||
|
template = (await self._naturalizer.naturalize(
|
||||||
|
template, situation=build_situation(ctx))) or template
|
||||||
|
view2 = chat_engine.render_step(session, "가격협상_카운터")
|
||||||
|
res.step, res.client_step = view2.step, view2.client_step
|
||||||
|
res.input_mode, res.input_options = view2.input_mode, view2.input_options
|
||||||
|
res.script = scripts.format_script(template, chat_engine.vars_for(session)) if template else view2.script
|
||||||
|
res.card_id = closing_number
|
||||||
|
|
||||||
async def _terminal_learn(self, engine: TenantEngine, session: ChatSession, outcome: str, res: Res_Chat):
|
async def _terminal_learn(self, engine: TenantEngine, session: ChatSession, outcome: str, res: Res_Chat):
|
||||||
oc = NegotiationOutcome.SUCCESS if outcome == "success" else NegotiationOutcome.FAILURE
|
oc = NegotiationOutcome.SUCCESS if outcome == "success" else NegotiationOutcome.FAILURE
|
||||||
snap = self._snapshot(session, oc)
|
snap = self._snapshot(session, oc)
|
||||||
@@ -276,6 +419,52 @@ class ChatService:
|
|||||||
dtype=bool,
|
dtype=bool,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _combined_mask(cls, engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
|
||||||
|
"""견적 선택 마스크 AND 전술 발동조건 마스크.
|
||||||
|
|
||||||
|
결합 결과가 전부 False 면(선택 카드가 모두 발동 불가) 선택 마스크 단독으로 폴백 —
|
||||||
|
협상은 멈추지 않고(HOLD 설득으로라도 진행), 종결은 라운드 규칙이 처리한다.
|
||||||
|
"""
|
||||||
|
sel = cls._selection_mask(engine, session)
|
||||||
|
tac = cls._tactic_mask(engine, session)
|
||||||
|
if tac is None:
|
||||||
|
return sel
|
||||||
|
if sel is None:
|
||||||
|
return tac if tac.any() else None
|
||||||
|
both = sel & tac
|
||||||
|
return both if both.any() else sel
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _tactic_mask(engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
|
||||||
|
"""전술 발동조건(min_round·가격구간)을 만족하는 action 만 True. HOLD(설득)는 항상 True.
|
||||||
|
전부 True 면 None(마스크 불필요)."""
|
||||||
|
mask = np.array(
|
||||||
|
[tactic_available(tactic_for(engine.mapper.get_card_id(a)), session.context)
|
||||||
|
for a in range(engine.action_space_size)],
|
||||||
|
dtype=bool,
|
||||||
|
)
|
||||||
|
return None if mask.all() else mask
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _selection_prior(engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
|
||||||
|
"""의도층 prior(Phase 1) — 견적에서 고른 카드 순서를 콜드 스타트 선호로 반영.
|
||||||
|
|
||||||
|
갑이 먼저 고른 카드일수록 높은 보너스(최대 0.3, 순위 선형 감소). UCB 점수에
|
||||||
|
1/(1+visits) 감쇠로 더해지므로 학습이 쌓이면 Q 가 지배한다(오염 없음).
|
||||||
|
선택이 2장 미만이면 순서 정보가 무의미 → None.
|
||||||
|
"""
|
||||||
|
selected = session.context.get("selected_nego_card_numbers") or []
|
||||||
|
if len(selected) < 2:
|
||||||
|
return None
|
||||||
|
prior = np.zeros(engine.action_space_size)
|
||||||
|
n = len(selected)
|
||||||
|
for rank, num in enumerate(selected):
|
||||||
|
a = engine.mapper.get_action_id(str(num))
|
||||||
|
if a is not None and a < engine.action_space_size:
|
||||||
|
prior[a] = 0.3 * (n - rank) / n
|
||||||
|
return prior if prior.any() else None
|
||||||
|
|
||||||
async def _log(self, repo: LearningRepository, session, state_index, action_id, card_id, snap, reward, propensity, done):
|
async def _log(self, repo: LearningRepository, session, state_index, action_id, card_id, snap, reward, propensity, done):
|
||||||
data = {
|
data = {
|
||||||
"session_id": session.session_id, "state_index": state_index, "action_id": action_id,
|
"session_id": session.session_id, "state_index": state_index, "action_id": action_id,
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ async def resolve_company_name(repo: ICompanyProfileRepository, tenant_key: str)
|
|||||||
try:
|
try:
|
||||||
cid = uuid.UUID(tenant_key)
|
cid = uuid.UUID(tenant_key)
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
return None # ktcommerce 등 데모 테넌트명 → 파일 브랜드 유지
|
return None # imarketkorea 등 데모 테넌트명 → 파일 브랜드 유지
|
||||||
|
|
||||||
async def _q(s):
|
async def _q(s):
|
||||||
_, name = await repo.get_company_name(s, cid)
|
_, name = await repo.get_company_name(s, cid)
|
||||||
|
|||||||
@@ -148,6 +148,11 @@ class NegotiationConfig(BaseModel):
|
|||||||
anchor_rate: float = 0.01 # 목표가 대비 앵커링 인하율 (기본 1%)
|
anchor_rate: float = 0.01 # 목표가 대비 앵커링 인하율 (기본 1%)
|
||||||
max_rounds: int = 5 # 라운드 상한(보조). 실제 종료는 '카드 소진' 기준.
|
max_rounds: int = 5 # 라운드 상한(보조). 실제 종료는 '카드 소진' 기준.
|
||||||
|
|
||||||
|
# 결정 스택 규칙층(Phase 1) — ChatEngine 하드코딩을 테넌트별 데이터로.
|
||||||
|
wildcard_1pct_ratio: float = 1.02 # 제시가 ≤ anchor×비율 → 1% 인하 와일드카드로 마무리 유도
|
||||||
|
wildcard_entry_ratio: float = 1.05 # 선택 와일드카드 허용 시 와일드카드 진입 상한(anchor×비율)
|
||||||
|
max_counter_rounds: int = 3 # 에이전트 카운터 제안 상한(초과 시 협상실패 종료)
|
||||||
|
|
||||||
def anchor_for(self, target_price: float) -> float:
|
def anchor_for(self, target_price: float) -> float:
|
||||||
return round(target_price * (1.0 - self.anchor_rate))
|
return round(target_price * (1.0 - self.anchor_rate))
|
||||||
|
|
||||||
|
|||||||
@@ -15,5 +15,7 @@
|
|||||||
"가격협상_와일드": "가격협상",
|
"가격협상_와일드": "가격협상",
|
||||||
"협상완료": "협상종료",
|
"협상완료": "협상종료",
|
||||||
"협상실패": "협상종료",
|
"협상실패": "협상종료",
|
||||||
"협상종료": "협상종료"
|
"협상종료": "협상종료",
|
||||||
|
"가격협상_카운터": "가격협상",
|
||||||
|
"wild_card_dynamic": "가격협상"
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,9 @@
|
|||||||
"editor_script_id": "시작",
|
"editor_script_id": "시작",
|
||||||
"next_input_mode": "null",
|
"next_input_mode": "null",
|
||||||
"input_options": [],
|
"input_options": [],
|
||||||
"next_step": { "default": "서비스안내" },
|
"next_step": {
|
||||||
|
"default": "서비스안내"
|
||||||
|
},
|
||||||
"type": "null",
|
"type": "null",
|
||||||
"chat_end": false
|
"chat_end": false
|
||||||
},
|
},
|
||||||
@@ -13,8 +15,12 @@
|
|||||||
"script": "안녕하세요. {company_name} {service_name}입니다. 본 서비스는 {company_name}와 협력사 간 물품 공급 가격 협상을 위한 것으로, 귀사가 공급 중인 품목의 새로운 가격 협상을 진행합니다. 안내 사항을 확인하신 뒤, 다음 단계로 넘어가려면 [확인]을 눌러 주세요.",
|
"script": "안녕하세요. {company_name} {service_name}입니다. 본 서비스는 {company_name}와 협력사 간 물품 공급 가격 협상을 위한 것으로, 귀사가 공급 중인 품목의 새로운 가격 협상을 진행합니다. 안내 사항을 확인하신 뒤, 다음 단계로 넘어가려면 [확인]을 눌러 주세요.",
|
||||||
"editor_script_id": "서비스안내",
|
"editor_script_id": "서비스안내",
|
||||||
"next_input_mode": "confirm",
|
"next_input_mode": "confirm",
|
||||||
"input_options": ["확인"],
|
"input_options": [
|
||||||
"next_step": { "default": "담당자확인" },
|
"확인"
|
||||||
|
],
|
||||||
|
"next_step": {
|
||||||
|
"default": "담당자확인"
|
||||||
|
},
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"chat_end": false
|
"chat_end": false
|
||||||
},
|
},
|
||||||
@@ -22,8 +28,14 @@
|
|||||||
"script": "본 안내는 협력사 포털에 등록된 담당자에게 발송되었습니다. 구매 협상 담당자가 맞는지 다시 한 번 확인 부탁드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택해 주세요.",
|
"script": "본 안내는 협력사 포털에 등록된 담당자에게 발송되었습니다. 구매 협상 담당자가 맞는지 다시 한 번 확인 부탁드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택해 주세요.",
|
||||||
"editor_script_id": "담당자확인",
|
"editor_script_id": "담당자확인",
|
||||||
"next_input_mode": "yes_no",
|
"next_input_mode": "yes_no",
|
||||||
"input_options": ["예", "아니오"],
|
"input_options": [
|
||||||
"next_step": { "예": "협상품목안내", "아니오": "담당자확인_아니오" },
|
"예",
|
||||||
|
"아니오"
|
||||||
|
],
|
||||||
|
"next_step": {
|
||||||
|
"예": "협상품목안내",
|
||||||
|
"아니오": "담당자확인_아니오"
|
||||||
|
},
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"chat_end": false
|
"chat_end": false
|
||||||
},
|
},
|
||||||
@@ -31,8 +43,14 @@
|
|||||||
"script": "[아니오]를 선택하셨습니다. 담당자가 변경되어 정보를 수정하시려면 [정보변경]을, 실수로 선택하신 경우 다시 진행하려면 [돌아가기]를 선택해 주세요.",
|
"script": "[아니오]를 선택하셨습니다. 담당자가 변경되어 정보를 수정하시려면 [정보변경]을, 실수로 선택하신 경우 다시 진행하려면 [돌아가기]를 선택해 주세요.",
|
||||||
"editor_script_id": "담당자확인_아니오",
|
"editor_script_id": "담당자확인_아니오",
|
||||||
"next_input_mode": "yes_no",
|
"next_input_mode": "yes_no",
|
||||||
"input_options": ["돌아가기", "정보변경"],
|
"input_options": [
|
||||||
"next_step": { "돌아가기": "담당자확인", "정보변경": "정보변경_완료" },
|
"돌아가기",
|
||||||
|
"정보변경"
|
||||||
|
],
|
||||||
|
"next_step": {
|
||||||
|
"돌아가기": "담당자확인",
|
||||||
|
"정보변경": "정보변경_완료"
|
||||||
|
},
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"chat_end": false
|
"chat_end": false
|
||||||
},
|
},
|
||||||
@@ -49,8 +67,12 @@
|
|||||||
"script": "{company_name}는 귀사의 협력에 진심으로 감사드립니다. 이번 가격 협상 품목과 기본 정보를 안내드립니다. 좌측의 상품 정보를 확인해 주세요. 협상이 원만히 마무리되면 더 많은 협력 기회가 마련될 수 있습니다.",
|
"script": "{company_name}는 귀사의 협력에 진심으로 감사드립니다. 이번 가격 협상 품목과 기본 정보를 안내드립니다. 좌측의 상품 정보를 확인해 주세요. 협상이 원만히 마무리되면 더 많은 협력 기회가 마련될 수 있습니다.",
|
||||||
"editor_script_id": "협상품목안내",
|
"editor_script_id": "협상품목안내",
|
||||||
"next_input_mode": "confirm",
|
"next_input_mode": "confirm",
|
||||||
"input_options": ["확인"],
|
"input_options": [
|
||||||
"next_step": { "확인": "기존가격제시" },
|
"확인"
|
||||||
|
],
|
||||||
|
"next_step": {
|
||||||
|
"확인": "기존가격제시"
|
||||||
|
},
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"chat_end": false
|
"chat_end": false
|
||||||
},
|
},
|
||||||
@@ -59,7 +81,9 @@
|
|||||||
"editor_script_id": "기존가격제시",
|
"editor_script_id": "기존가격제시",
|
||||||
"next_input_mode": "price",
|
"next_input_mode": "price",
|
||||||
"input_options": [],
|
"input_options": [],
|
||||||
"next_step": { "default": "가격협상_확인" },
|
"next_step": {
|
||||||
|
"default": "가격협상_확인"
|
||||||
|
},
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"chat_end": false
|
"chat_end": false
|
||||||
},
|
},
|
||||||
@@ -68,22 +92,42 @@
|
|||||||
"editor_script_id": "가격협상_재입력",
|
"editor_script_id": "가격협상_재입력",
|
||||||
"next_input_mode": "price",
|
"next_input_mode": "price",
|
||||||
"input_options": [],
|
"input_options": [],
|
||||||
"next_step": { "default": "가격협상_확인" },
|
"next_step": {
|
||||||
|
"default": "가격협상_확인"
|
||||||
|
},
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"chat_end": false
|
"chat_end": false
|
||||||
},
|
},
|
||||||
"가격협상_확인": {
|
"가격협상_확인": {
|
||||||
"script": "제시하신 가격은 **{input_price}원**으로, 기존 공급가 대비 약 **{discount_rate}%** 인하된 금액입니다. 이 금액으로 제안하시겠습니까? 수정하시려면 [아니오]를 선택해 주세요.",
|
"script": "제시하신 가격은 **{input_price}원**입니다. {discount_phrase}이 금액으로 제안하시겠습니까? 수정하시려면 [아니오]를 선택해 주세요.",
|
||||||
"editor_script_id": "가격협상_확인",
|
"editor_script_id": "가격협상_확인",
|
||||||
"next_input_mode": "yes_no",
|
"next_input_mode": "yes_no",
|
||||||
"input_options": ["예", "아니오"],
|
"input_options": [
|
||||||
|
"예",
|
||||||
|
"아니오"
|
||||||
|
],
|
||||||
"next_step": {
|
"next_step": {
|
||||||
"예": [
|
"예": [
|
||||||
{ "condition": "check_wildcard_entry", "next": "가격협상_와일드" },
|
{
|
||||||
{ "condition": "check_is_supplier_type_c", "next": "협상완료" },
|
"condition": "check_wildcard_entry",
|
||||||
{ "condition": "check_price_match", "next": "협상완료" },
|
"next": "가격협상_와일드"
|
||||||
{ "condition": "check_iteration_limit", "next": "협상실패" },
|
},
|
||||||
{ "condition": "default", "next": "가격협상" }
|
{
|
||||||
|
"condition": "check_is_supplier_type_c",
|
||||||
|
"next": "협상완료"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"condition": "check_price_match",
|
||||||
|
"next": "협상완료"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"condition": "check_iteration_limit",
|
||||||
|
"next": "협상실패"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"condition": "default",
|
||||||
|
"next": "가격협상"
|
||||||
|
}
|
||||||
],
|
],
|
||||||
"아니오": "가격협상_재입력"
|
"아니오": "가격협상_재입력"
|
||||||
},
|
},
|
||||||
@@ -94,8 +138,14 @@
|
|||||||
"script": "제시하신 금액은 **{input_price}원**입니다. 이 금액으로 견적을 제출하시겠습니까? 수정하시려면 [아니오]를 선택해 주세요.",
|
"script": "제시하신 금액은 **{input_price}원**입니다. 이 금액으로 견적을 제출하시겠습니까? 수정하시려면 [아니오]를 선택해 주세요.",
|
||||||
"editor_script_id": "가격협상_확인_버짓",
|
"editor_script_id": "가격협상_확인_버짓",
|
||||||
"next_input_mode": "yes_no",
|
"next_input_mode": "yes_no",
|
||||||
"input_options": ["예", "아니오"],
|
"input_options": [
|
||||||
"next_step": { "예": "협상완료", "아니오": "가격협상_재입력" },
|
"예",
|
||||||
|
"아니오"
|
||||||
|
],
|
||||||
|
"next_step": {
|
||||||
|
"예": "협상완료",
|
||||||
|
"아니오": "가격협상_재입력"
|
||||||
|
},
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"chat_end": false
|
"chat_end": false
|
||||||
},
|
},
|
||||||
@@ -104,7 +154,9 @@
|
|||||||
"editor_script_id": "가격협상",
|
"editor_script_id": "가격협상",
|
||||||
"next_input_mode": "price",
|
"next_input_mode": "price",
|
||||||
"input_options": [],
|
"input_options": [],
|
||||||
"next_step": { "default": "가격협상_확인" },
|
"next_step": {
|
||||||
|
"default": "가격협상_확인"
|
||||||
|
},
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"chat_end": false
|
"chat_end": false
|
||||||
},
|
},
|
||||||
@@ -112,8 +164,12 @@
|
|||||||
"script": "협조해 주신 덕분에 원만히 협상이 완료되었습니다. 협상 결과를 확인하신 뒤 동의해 주세요. 거래 약정에 따라 일부 조건이 조정될 수 있는 점 참고 부탁드립니다. 성실히 응해 주셔서 감사합니다.",
|
"script": "협조해 주신 덕분에 원만히 협상이 완료되었습니다. 협상 결과를 확인하신 뒤 동의해 주세요. 거래 약정에 따라 일부 조건이 조정될 수 있는 점 참고 부탁드립니다. 성실히 응해 주셔서 감사합니다.",
|
||||||
"editor_script_id": "협상완료",
|
"editor_script_id": "협상완료",
|
||||||
"next_input_mode": "confirm",
|
"next_input_mode": "confirm",
|
||||||
"input_options": ["협상 내용을 확인했으며, 이의가 없음에 동의합니다."],
|
"input_options": [
|
||||||
"next_step": { "default": "협상종료" },
|
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."
|
||||||
|
],
|
||||||
|
"next_step": {
|
||||||
|
"default": "협상종료"
|
||||||
|
},
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"chat_end": false
|
"chat_end": false
|
||||||
},
|
},
|
||||||
@@ -122,7 +178,9 @@
|
|||||||
"editor_script_id": "협상실패",
|
"editor_script_id": "협상실패",
|
||||||
"next_input_mode": "null",
|
"next_input_mode": "null",
|
||||||
"input_options": [],
|
"input_options": [],
|
||||||
"next_step": { "default": "협상종료" },
|
"next_step": {
|
||||||
|
"default": "협상종료"
|
||||||
|
},
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"chat_end": false
|
"chat_end": false
|
||||||
},
|
},
|
||||||
@@ -134,5 +192,21 @@
|
|||||||
"next_step": null,
|
"next_step": null,
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"chat_end": true
|
"chat_end": true
|
||||||
|
},
|
||||||
|
"가격협상_카운터": {
|
||||||
|
"script": "제시해 주신 **{input_price}원** 검토했습니다. 저희는 **{counter_price}원**을 제안드립니다. 이 가격으로 진행 가능하시면 '수락'을, 어려우시면 '다른 가격 제시'를 선택해 주세요.",
|
||||||
|
"editor_script_id": "가격협상_카운터",
|
||||||
|
"next_input_mode": "yes_no",
|
||||||
|
"input_options": [
|
||||||
|
"수락",
|
||||||
|
"다른 가격 제시"
|
||||||
|
],
|
||||||
|
"next_step": {
|
||||||
|
"수락": "협상완료",
|
||||||
|
"다른 가격 제시": "가격협상_재입력",
|
||||||
|
"default": "가격협상_재입력"
|
||||||
|
},
|
||||||
|
"type": "text",
|
||||||
|
"chat_end": false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,8 +5,13 @@
|
|||||||
"type": "text",
|
"type": "text",
|
||||||
"chat_end": false,
|
"chat_end": false,
|
||||||
"next_input_mode": "yes_no",
|
"next_input_mode": "yes_no",
|
||||||
"input_options": ["예", "아니오"],
|
"input_options": [
|
||||||
"next_step": { "default": "협상완료" },
|
"예",
|
||||||
|
"아니오"
|
||||||
|
],
|
||||||
|
"next_step": {
|
||||||
|
"default": "협상완료"
|
||||||
|
},
|
||||||
"editor_script_id": "wild_card_1pct"
|
"editor_script_id": "wild_card_1pct"
|
||||||
},
|
},
|
||||||
"wild_card_budget": {
|
"wild_card_budget": {
|
||||||
@@ -15,7 +20,24 @@
|
|||||||
"chat_end": false,
|
"chat_end": false,
|
||||||
"next_input_mode": "price",
|
"next_input_mode": "price",
|
||||||
"input_options": [],
|
"input_options": [],
|
||||||
"next_step": { "default": "가격협상_확인_버짓" },
|
"next_step": {
|
||||||
|
"default": "가격협상_확인_버짓"
|
||||||
|
},
|
||||||
"editor_script_id": "wild_card_budget"
|
"editor_script_id": "wild_card_budget"
|
||||||
|
},
|
||||||
|
"wild_card_dynamic": {
|
||||||
|
"script": "저희는 **{counter_price}원**이면 즉시 진행이 가능합니다. 이 가격으로 진행 가능하시면 '수락'을, 어려우시면 '다른 가격 제시'를 선택해 주세요.",
|
||||||
|
"next_input_mode": "yes_no",
|
||||||
|
"input_options": [
|
||||||
|
"수락",
|
||||||
|
"다른 가격 제시"
|
||||||
|
],
|
||||||
|
"next_step": {
|
||||||
|
"수락": "협상완료",
|
||||||
|
"다른 가격 제시": "가격협상_재입력",
|
||||||
|
"default": "가격협상_재입력"
|
||||||
|
},
|
||||||
|
"type": "text",
|
||||||
|
"chat_end": false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -78,7 +78,7 @@ cards:
|
|||||||
connection: {}
|
connection: {}
|
||||||
|
|
||||||
llm:
|
llm:
|
||||||
enabled: false
|
enabled: true
|
||||||
|
|
||||||
resources:
|
resources:
|
||||||
language: ko
|
language: ko
|
||||||
|
|||||||
@@ -37,7 +37,9 @@ action_mapping:
|
|||||||
"10": "NGC-B011"
|
"10": "NGC-B011"
|
||||||
|
|
||||||
llm:
|
llm:
|
||||||
enabled: false
|
enabled: true
|
||||||
|
# api_key_ref 는 미구현(dead) — 현재 LLM 키는 전역 config.local.toml [OpenAIConfig].api_key
|
||||||
|
# (또는 OPENAI_API_KEY env) 를 사용한다. 테넌트별 키 분리는 표현층(Phase 2) 본작업에서 구현.
|
||||||
api_key_ref: TENANT_B_OPENAI_API_KEY
|
api_key_ref: TENANT_B_OPENAI_API_KEY
|
||||||
|
|
||||||
resources:
|
resources:
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
# 데모 테넌트 프로파일 (합성/중립값 — CLEANROOM.md).
|
|
||||||
# tenant_id 는 라우팅 키일 뿐이며, 아래 값은 해당 회사의 실제 운영값이 아니다.
|
|
||||||
# 실제 운영 시 카드 카탈로그(card.nego_cards)·튜닝값은 테넌트 비공개 소스에서 주입한다.
|
|
||||||
tenant_id: ktcommerce
|
|
||||||
inherits_base: true
|
|
||||||
name: "Demo Tenant A"
|
|
||||||
company_id: null # P3 시드 시 company.companies.company_id(uuid) 로 채움
|
|
||||||
|
|
||||||
action_mapping:
|
|
||||||
type: file
|
|
||||||
action_to_card: # 우리 중립 데모 카드 코드(합성). 실제 카드 코드 아님. 카탈로그 11장(_base 와 정합).
|
|
||||||
"0": "NGC-A001"
|
|
||||||
"1": "NGC-A002"
|
|
||||||
"2": "NGC-A003"
|
|
||||||
"3": "NGC-A004"
|
|
||||||
"4": "NGC-A005"
|
|
||||||
"5": "NGC-A006"
|
|
||||||
"6": "NGC-A007"
|
|
||||||
"7": "NGC-A008"
|
|
||||||
"8": "NGC-A009"
|
|
||||||
"9": "NGC-A010"
|
|
||||||
"10": "NGC-A011"
|
|
||||||
|
|
||||||
llm:
|
|
||||||
enabled: false # P7 에서 테넌트별 자격증명 주입
|
|
||||||
api_key_ref: TENANT_A_OPENAI_API_KEY
|
|
||||||
|
|
||||||
resources:
|
|
||||||
language: ko
|
|
||||||
scripts_dir: resources # 없으면 _base/resources 폴백
|
|
||||||
company_name: "데모상사 A" # 스크립트 {company_name} 치환값 (합성)
|
|
||||||
service_name: "Negosium"
|
|
||||||
@@ -29,7 +29,7 @@ def _reg():
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_4_1_honors_backend_session_id(db_engine):
|
async def test_4_1_honors_backend_session_id(db_engine):
|
||||||
reset_sessions()
|
reset_sessions()
|
||||||
eng = await _reg().get_engine("ktcommerce")
|
eng = await _reg().get_engine("imarketkorea")
|
||||||
svc = ChatService()
|
svc = ChatService()
|
||||||
|
|
||||||
# 첫 턴: backend 의 session_id 를 그대로 키로 써야 함 (새 uuid 발급 X)
|
# 첫 턴: backend 의 session_id 를 그대로 키로 써야 함 (새 uuid 발급 X)
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
"""협상카드 선택 E2E — 실 DB 왕복으로 "견적에서 고른 카드만 뽑히는지" 검증.
|
||||||
|
|
||||||
|
시나리오: 견적 생성 시 협상카드 2장(NGC-003, NGC-007)만 선택 →
|
||||||
|
version_nego_cards 로 연결 → 협상 세션 시작 → 가격협상 턴 2회 진행.
|
||||||
|
검증: ① 뽑힌 카드가 선택 2장 안에서만 나옴(선택 마스크) ② 세션 내 중복 없음(사용 마스크)
|
||||||
|
③ 카탈로그(DB, NGC-001~011) 기준 action space ④ 선택 없으면 전체 카탈로그 허용(폴백).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import uuid as _uuid
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import column, delete, insert, select, table
|
||||||
|
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.enums import DBType, DBWRType, ErrorType
|
||||||
|
from router.v1.chat.protocol import Req_Chat
|
||||||
|
from services.chat_service import ChatService, reset_sessions
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
from tenancy.registry import TenantEngineRegistry
|
||||||
|
|
||||||
|
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||||
|
|
||||||
|
_T_SESSIONS = table(
|
||||||
|
"sessions",
|
||||||
|
column("session_id"), column("quotation_id"), column("item_id"), column("supplier_id"),
|
||||||
|
column("qt_number"), column("qt_round"), column("qt_type"), column("target_price"),
|
||||||
|
column("anchoring_price"), column("status"), column("end_time"),
|
||||||
|
schema="negotiation",
|
||||||
|
)
|
||||||
|
_T_QUOTATIONS = table(
|
||||||
|
"quotations",
|
||||||
|
column("qt_id"), column("user_id"), column("qt_setting_id"), column("version_id"),
|
||||||
|
column("name"), column("number"), column("type"), column("status"),
|
||||||
|
column("start_time"), column("end_time"),
|
||||||
|
schema="quotation",
|
||||||
|
)
|
||||||
|
_T_VNC = table(
|
||||||
|
"version_nego_cards",
|
||||||
|
column("vnc_id"), column("version_id"), column("nego_card_id"),
|
||||||
|
schema="card",
|
||||||
|
)
|
||||||
|
_T_NEGO = table("nego_cards", column("nego_card_id"), column("number"), column("deleted"), schema="card")
|
||||||
|
|
||||||
|
|
||||||
|
async def _card_uuid(number: str):
|
||||||
|
def _q(s):
|
||||||
|
return DB_SESSION_MNG.execute(
|
||||||
|
s, select(_T_NEGO.c.nego_card_id).where(
|
||||||
|
_T_NEGO.c.number == number, _T_NEGO.c.deleted == False).limit(1)) # noqa: E712
|
||||||
|
_, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||||
|
return rows[0] if rows else None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_selected_cards_only_are_played(db_engine):
|
||||||
|
reset_sessions()
|
||||||
|
sid, qid, ver_id = _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4()
|
||||||
|
iid, sup = _uuid.uuid4(), _uuid.uuid4()
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
selected = ["NGC-003", "NGC-007"]
|
||||||
|
card_ids = {}
|
||||||
|
for n in selected:
|
||||||
|
card_ids[n] = await _card_uuid(n)
|
||||||
|
assert card_ids[n] is not None, f"카탈로그에 {n} 없음(시드 확인)"
|
||||||
|
|
||||||
|
def _seed(s_):
|
||||||
|
async def run(s):
|
||||||
|
e = await DB_SESSION_MNG.add(s, insert(_T_QUOTATIONS).values(
|
||||||
|
qt_id=qid, user_id=_uuid.uuid4(), qt_setting_id=_uuid.uuid4(), version_id=ver_id,
|
||||||
|
name="카드선택E2E", number="QT-CARDSEL-E2E", type=1, status=2,
|
||||||
|
start_time=now, end_time=now + timedelta(days=1)))
|
||||||
|
if e != ErrorType.SUCCESS:
|
||||||
|
return e
|
||||||
|
for n in selected: # 견적 생성 시 선택한 카드 2장
|
||||||
|
e = await DB_SESSION_MNG.add(s, insert(_T_VNC).values(
|
||||||
|
vnc_id=_uuid.uuid4(), version_id=ver_id, nego_card_id=card_ids[n]))
|
||||||
|
if e != ErrorType.SUCCESS:
|
||||||
|
return e
|
||||||
|
return await DB_SESSION_MNG.add(s, insert(_T_SESSIONS).values(
|
||||||
|
session_id=sid, quotation_id=qid, item_id=iid, supplier_id=sup,
|
||||||
|
qt_number="QT-CARDSEL-E2E", qt_round=1, qt_type=1,
|
||||||
|
target_price=10000, anchoring_price=9900, status=2,
|
||||||
|
end_time=now + timedelta(days=1)))
|
||||||
|
return run(s_)
|
||||||
|
|
||||||
|
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_seed])
|
||||||
|
assert err == ErrorType.SUCCESS
|
||||||
|
|
||||||
|
try:
|
||||||
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||||
|
eng = await reg.get_engine(str(_uuid.uuid4())) # 자동 온보딩(_base type:db → 실 DB 카탈로그)
|
||||||
|
assert eng.action_space_size == 11 # 카탈로그 11장(NGC-001~011)
|
||||||
|
|
||||||
|
svc = ChatService()
|
||||||
|
played = []
|
||||||
|
session_id = str(sid)
|
||||||
|
# 적응형 진행: 카드 전술 재설계 후 카운터 제시 카드(NGC-007 등)는 수락/거절 스텝
|
||||||
|
# (가격협상_카운터)으로 전환된다 — 거절하고 새 가격을 제시하며 카드 2턴을 유도한다.
|
||||||
|
prices = iter(["11000", "10600", "10400"])
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=session_id))
|
||||||
|
for _ in range(14):
|
||||||
|
if r.step in ("가격협상", "가격협상_카운터") and r.card_id:
|
||||||
|
played.append(r.card_id)
|
||||||
|
if len(played) == 2:
|
||||||
|
break
|
||||||
|
if r.chat_end:
|
||||||
|
break
|
||||||
|
if r.input_mode == "price":
|
||||||
|
ui = next(prices)
|
||||||
|
elif r.step == "가격협상_카운터":
|
||||||
|
ui = "다른 가격 제시"
|
||||||
|
elif r.input_options:
|
||||||
|
ui = "예" if "예" in r.input_options else r.input_options[0]
|
||||||
|
else:
|
||||||
|
ui = "확인"
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input=ui))
|
||||||
|
|
||||||
|
assert len(played) == 2, f"가격협상 카드 턴 2회 기대, 실제 {played}"
|
||||||
|
# ① 선택한 카드 안에서만 뽑힘 ② 세션 내 중복 없음
|
||||||
|
assert set(played) <= set(selected), f"선택 밖 카드 발동: {played}"
|
||||||
|
assert len(set(played)) == 2, f"카드 중복 사용: {played}"
|
||||||
|
finally:
|
||||||
|
await DB_SESSION_MNG.execute_lambda_run(
|
||||||
|
[DBType.MAIN.value],
|
||||||
|
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SESSIONS).where(_T_SESSIONS.c.session_id == sid)),
|
||||||
|
lambda s: DB_SESSION_MNG.add(s, delete(_T_VNC).where(_T_VNC.c.version_id == ver_id)),
|
||||||
|
lambda s: DB_SESSION_MNG.add(s, delete(_T_QUOTATIONS).where(_T_QUOTATIONS.c.qt_id == qid))],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_no_selection_allows_full_catalog(db_engine):
|
||||||
|
"""선택 카드가 없으면(직접호출/데모) 전체 카탈로그가 허용된다 — 카드가 정상적으로 뽑히는지 기본 검증."""
|
||||||
|
reset_sessions()
|
||||||
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||||
|
eng = await reg.get_engine(str(_uuid.uuid4())) # _base type:db → DB 카탈로그
|
||||||
|
catalog = {eng.mapper.get_card_id(a) for a in range(eng.action_space_size)}
|
||||||
|
|
||||||
|
svc = ChatService()
|
||||||
|
played = []
|
||||||
|
sid = None
|
||||||
|
for ui in [None, "확인", "예", "확인", "11000", "예", "10600", "예", "10600", "예"]:
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input=ui))
|
||||||
|
sid = r.session_id
|
||||||
|
if r.step == "가격협상" and r.card_id:
|
||||||
|
played.append(r.card_id)
|
||||||
|
if r.chat_end:
|
||||||
|
break
|
||||||
|
|
||||||
|
assert played, "가격협상 카드 턴이 발생해야 함"
|
||||||
|
assert set(played) <= catalog # 카탈로그(NGC-001~011) 내에서만
|
||||||
|
assert len(played) == len(set(played)) # 세션 내 중복 없음
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
"""카드 전술 재설계 검증 — "멘트 카드 → 전술 카드" (가격 행동 실행 계층).
|
||||||
|
|
||||||
|
① 카운터 산식 결정론 + min(counter, target) 클램프 + 무의미 카운터(HOLD 강등)
|
||||||
|
② 카운터 수락 = 즉시 타결 / 거절 = 재입력 + pending 폐기
|
||||||
|
③ 목표가 초과 타결 금지 가드(성공 스텝 진입 차단)
|
||||||
|
④ 선택형 와일드카드(WC-05 중간값 절충) 발동 — 1.02~1.05 구간 갭 해소
|
||||||
|
⑤ E2E: 견적 선택 카드(NGC-009 조건부 가격 조정)의 카운터를 수락하면 settled=target
|
||||||
|
⑥ E2E: 협력사가 target 초과를 고수하면 종결 전술(최후통첩) 후 결렬 — 고객사 이득 가드레일
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import uuid as _uuid
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from negotiation.cards.domain.tactics import (
|
||||||
|
PriceAction, TacticSpec, compute_counter, tactic_available, tactic_for,
|
||||||
|
)
|
||||||
|
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession
|
||||||
|
from negotiation.chat.service.script_repository import ScriptRepository
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
|
||||||
|
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||||
|
|
||||||
|
|
||||||
|
def _engine() -> ChatEngine:
|
||||||
|
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||||
|
return ChatEngine(ScriptRepository(cfg, _TENANTS_DIR), rq_type="재협상")
|
||||||
|
|
||||||
|
|
||||||
|
def _session(step="가격협상_확인", **ctx_over):
|
||||||
|
ctx = {"input_price": 10300, "anchor_price": 10000, "target_price": 10100,
|
||||||
|
"round": 1, "allow_selected_wildcards": False}
|
||||||
|
ctx.update(ctx_over)
|
||||||
|
return ChatSession(session_id="00000000-0000-0000-0000-00000000e001", tenant_id="imarketkorea",
|
||||||
|
company_id="imarketkorea", step=step, action_space_size=0, context=ctx)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- ① 카운터 산식 (결정론 + 가드레일 클램프) --------------------------------
|
||||||
|
def test_counter_formulas_and_clamp():
|
||||||
|
ctx = {"input_price": 11000, "anchor_price": 9900, "target_price": 10000}
|
||||||
|
assert compute_counter(tactic_for("NGC-009"), ctx) == 10000 # COUNTER_TARGET
|
||||||
|
assert compute_counter(tactic_for("NGC-007"), ctx) == 9900 # COUNTER_ANCHOR
|
||||||
|
assert compute_counter(tactic_for("WC-02"), ctx) == 9950 # (anchor+target)/2
|
||||||
|
# COUNTER_MID: 갑 직전 포지션 폴백 = anchor → (9900+11000)/2 = 10450 → target 클램프
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
def test_counter_meaningless_degrades_to_hold():
|
||||||
|
"""협력사 제시가가 이미 카운터 이하면 카운터가 무의미 → None(순수 설득 유지)."""
|
||||||
|
ctx = {"input_price": 9950, "anchor_price": 9900, "target_price": 10000}
|
||||||
|
assert compute_counter(tactic_for("NGC-009"), ctx) is None # target(10000) ≥ 제시가
|
||||||
|
assert compute_counter(TacticSpec(PriceAction.COUNTER_ANCHOR), dict(ctx, input_price=9900)) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_card_falls_back_to_hold():
|
||||||
|
"""미등록 카드번호(데모 NGC-B*, 커스텀 COMP-*)는 HOLD — 기존 동작 그대로."""
|
||||||
|
spec = tactic_for("NGC-B003")
|
||||||
|
assert spec.price_action is PriceAction.HOLD
|
||||||
|
assert compute_counter(spec, {"input_price": 11000, "target_price": 10000}) is None
|
||||||
|
assert tactic_available(spec, {}) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_tactic_availability_conditions():
|
||||||
|
assert tactic_available(tactic_for("WC-04"), {"round": 1}) is False # min_round=2
|
||||||
|
assert tactic_available(tactic_for("WC-04"), {"round": 2}) is True
|
||||||
|
|
||||||
|
|
||||||
|
# ---- ② 카운터 수락/거절 메커니즘 (엔진) ---------------------------------------
|
||||||
|
def test_accept_counter_settles_at_counter_price():
|
||||||
|
eng = _engine()
|
||||||
|
s = _session(step="가격협상_카운터", pending_counter_price=10000)
|
||||||
|
view = eng.advance(s, "수락")
|
||||||
|
assert view.step == "협상완료"
|
||||||
|
assert s.context["input_price"] == 10000 # 합의가 = 카운터가
|
||||||
|
assert "pending_counter_price" not in s.context
|
||||||
|
|
||||||
|
|
||||||
|
def test_reject_counter_reenters_price_and_discards_pending():
|
||||||
|
eng = _engine()
|
||||||
|
s = _session(step="가격협상_카운터", pending_counter_price=10000)
|
||||||
|
view = eng.advance(s, "다른 가격 제시")
|
||||||
|
assert view.step == "가격협상_재입력"
|
||||||
|
# 새 가격 입력이 pending 을 폐기한다 — 이후 우선협상 타결이 옛 카운터로 오염되지 않음
|
||||||
|
view = eng.advance(s, "9900")
|
||||||
|
assert "pending_counter_price" not in s.context
|
||||||
|
assert s.context["input_price"] == 9900
|
||||||
|
|
||||||
|
|
||||||
|
def test_wildcard_1pct_decline_keeps_original_price():
|
||||||
|
"""1% 인하 거절('아니오')도 협상완료로 가지만 합의가는 원 제시가 — pending 미적용 회귀."""
|
||||||
|
eng = _engine()
|
||||||
|
s = _session(step="wild_card_1pct", input_price=10000,
|
||||||
|
offer_1pct=9900, pending_counter_price=9900)
|
||||||
|
view = eng.advance(s, "아니오")
|
||||||
|
assert view.step == "협상완료"
|
||||||
|
assert s.context["input_price"] == 10000 # 거절 → 카운터 미적용
|
||||||
|
|
||||||
|
|
||||||
|
# ---- ③ 목표가 초과 타결 금지 가드 --------------------------------------------
|
||||||
|
def test_success_step_guard_rejects_over_target():
|
||||||
|
eng = _engine()
|
||||||
|
s = _session(input_price=10800, target_price=10000)
|
||||||
|
view = eng.render_step(s, "협상완료")
|
||||||
|
assert view.step == "협상실패" # 초과가 성공 진입 → 결렬 강제
|
||||||
|
|
||||||
|
|
||||||
|
# ---- ④ 선택형 와일드카드 발동 (1.02~1.05 구간 갭 해소) -------------------------
|
||||||
|
def test_selected_wildcard_fires_in_entry_zone():
|
||||||
|
eng = _engine()
|
||||||
|
# 10300: 1pct 존(≤10200) 밖, entry 존(≤10500) 안 + WC-05 선택
|
||||||
|
s = _session(input_price=10300, allow_selected_wildcards=True,
|
||||||
|
selected_wild_card_numbers=["WC-05"])
|
||||||
|
view = eng.advance(s, "예")
|
||||||
|
assert view.step == "wild_card_dynamic"
|
||||||
|
# 카운터 = (anchor 10000 + 10300)/2 = 10150 → target(10100) 클램프
|
||||||
|
assert s.context["pending_counter_price"] == 10100
|
||||||
|
assert s.context["active_wild_card_number"] == "WC-05"
|
||||||
|
# 수락 → 그 가격으로 타결
|
||||||
|
view = eng.advance(s, "수락")
|
||||||
|
assert view.step == "협상완료" and s.context["input_price"] == 10100
|
||||||
|
|
||||||
|
|
||||||
|
def test_unselected_wildcard_zone_still_falls_to_nego():
|
||||||
|
"""와일드카드 미선택이면 entry 존이라도 일반 가격협상 — 기존 동작 보존."""
|
||||||
|
eng = _engine()
|
||||||
|
s = _session(input_price=10300, allow_selected_wildcards=True, selected_wild_card_numbers=[])
|
||||||
|
view = eng.advance(s, "예")
|
||||||
|
assert view.step == "가격협상"
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 인하율 표기 (회귀: 인상 제시가 "-1.3% 인하"로 표기되던 버그) -----------------
|
||||||
|
def test_discount_never_negative_and_phrase_matches_direction():
|
||||||
|
eng = _engine()
|
||||||
|
# 인상 제시(기존 공급가 78000 < 제시 79000): 음수 인하율 금지 + "높은 금액" 문구
|
||||||
|
s = _session(item_price=78000, input_price=79000)
|
||||||
|
v = eng.vars_for(s)
|
||||||
|
assert v["discount_rate"] == "0.0" # 마이너스 인하 표기 금지
|
||||||
|
assert "높은 금액" in v["discount_phrase"] and "78000원" in v["discount_phrase"]
|
||||||
|
assert "-" not in v["discount_phrase"]
|
||||||
|
# 인하 제시: 상품단가(item_price) 기준 인하율
|
||||||
|
v = eng.vars_for(_session(item_price=78000, input_price=77000))
|
||||||
|
assert v["discount_rate"] == "1.3"
|
||||||
|
assert "인하된 금액" in v["discount_phrase"]
|
||||||
|
# 동일가
|
||||||
|
v = eng.vars_for(_session(item_price=78000, input_price=78000))
|
||||||
|
assert "동일한 수준" in v["discount_phrase"]
|
||||||
|
# 기존가 미보유(신규 협상) → 문구 생략
|
||||||
|
v = eng.vars_for(_session(item_price=0, input_price=79000))
|
||||||
|
assert v["discount_phrase"] == "" and v["discount_rate"] == "0.0"
|
||||||
|
|
||||||
|
|
||||||
|
def test_price_confirm_script_renders_raise_correctly():
|
||||||
|
"""가격협상_확인 멘트 E2E — 인상 제시에 '인하' 표현이 나오지 않는다."""
|
||||||
|
eng = _engine()
|
||||||
|
s = _session(step="기존가격제시", item_price=78000, input_price=None, round=0)
|
||||||
|
s.context.pop("input_price")
|
||||||
|
view = eng.advance(s, "79000")
|
||||||
|
assert view.step == "가격협상_확인"
|
||||||
|
assert "인하" not in view.script # 인상인데 '인하' 금지
|
||||||
|
assert "높은 금액" in view.script and "79000원" in view.script
|
||||||
|
|
||||||
|
|
||||||
|
# ---- vars_for 전술 변수 치환 ---------------------------------------------------
|
||||||
|
def test_vars_for_supplies_tactic_variables():
|
||||||
|
eng = _engine()
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
# ---- ⑤⑥ E2E (실 DB — 견적 선택 카드 + 서비스 레이어) ---------------------------
|
||||||
|
from sqlalchemy import column, delete, insert, select, table # noqa: E402
|
||||||
|
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
|
||||||
|
from common.enums import DBType, DBWRType, ErrorType # noqa: E402
|
||||||
|
from router.v1.chat.protocol import Req_Chat # noqa: E402
|
||||||
|
from services.chat_service import ChatService, reset_sessions # noqa: E402
|
||||||
|
from tenancy.registry import TenantEngineRegistry # noqa: E402
|
||||||
|
|
||||||
|
_T_SESSIONS = table(
|
||||||
|
"sessions",
|
||||||
|
column("session_id"), column("quotation_id"), column("item_id"), column("supplier_id"),
|
||||||
|
column("qt_number"), column("qt_round"), column("qt_type"), column("target_price"),
|
||||||
|
column("anchoring_price"), column("status"), column("end_time"),
|
||||||
|
schema="negotiation",
|
||||||
|
)
|
||||||
|
_T_QUOTATIONS = table(
|
||||||
|
"quotations",
|
||||||
|
column("qt_id"), column("user_id"), column("qt_setting_id"), column("version_id"),
|
||||||
|
column("name"), column("number"), column("type"), column("status"),
|
||||||
|
column("start_time"), column("end_time"),
|
||||||
|
schema="quotation",
|
||||||
|
)
|
||||||
|
_T_VNC = table("version_nego_cards", column("vnc_id"), column("version_id"), column("nego_card_id"), schema="card")
|
||||||
|
_T_NEGO = table("nego_cards", column("nego_card_id"), column("number"), column("deleted"), schema="card")
|
||||||
|
|
||||||
|
|
||||||
|
async def _card_uuid(number: str):
|
||||||
|
def _q(s):
|
||||||
|
return DB_SESSION_MNG.execute(
|
||||||
|
s, select(_T_NEGO.c.nego_card_id).where(
|
||||||
|
_T_NEGO.c.number == number, _T_NEGO.c.deleted == False).limit(1)) # noqa: E712
|
||||||
|
_, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||||
|
return rows[0] if rows else None
|
||||||
|
|
||||||
|
|
||||||
|
async def _seed_quote_session(sid, selected_numbers, target=10000, anchor=9900):
|
||||||
|
qid, ver_id, iid, sup = _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4()
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
card_ids = {}
|
||||||
|
for n in selected_numbers:
|
||||||
|
card_ids[n] = await _card_uuid(n)
|
||||||
|
assert card_ids[n] is not None, f"카탈로그에 {n} 없음(시드 확인)"
|
||||||
|
|
||||||
|
def _seed(s_):
|
||||||
|
async def run(s):
|
||||||
|
e = await DB_SESSION_MNG.add(s, insert(_T_QUOTATIONS).values(
|
||||||
|
qt_id=qid, user_id=_uuid.uuid4(), qt_setting_id=_uuid.uuid4(), version_id=ver_id,
|
||||||
|
name="전술E2E", number=f"QT-TACTIC-{str(sid)[:8]}", type=1, status=2,
|
||||||
|
start_time=now, end_time=now + timedelta(days=1)))
|
||||||
|
if e != ErrorType.SUCCESS:
|
||||||
|
return e
|
||||||
|
for n in selected_numbers:
|
||||||
|
e = await DB_SESSION_MNG.add(s, insert(_T_VNC).values(
|
||||||
|
vnc_id=_uuid.uuid4(), version_id=ver_id, nego_card_id=card_ids[n]))
|
||||||
|
if e != ErrorType.SUCCESS:
|
||||||
|
return e
|
||||||
|
return await DB_SESSION_MNG.add(s, insert(_T_SESSIONS).values(
|
||||||
|
session_id=sid, quotation_id=qid, item_id=iid, supplier_id=sup,
|
||||||
|
qt_number=f"QT-TACTIC-{str(sid)[:8]}", qt_round=1, qt_type=1,
|
||||||
|
target_price=target, anchoring_price=anchor, status=2,
|
||||||
|
end_time=now + timedelta(days=1)))
|
||||||
|
return run(s_)
|
||||||
|
|
||||||
|
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_seed])
|
||||||
|
assert err == ErrorType.SUCCESS
|
||||||
|
return qid, ver_id
|
||||||
|
|
||||||
|
|
||||||
|
async def _cleanup(sid, qid, ver_id):
|
||||||
|
await DB_SESSION_MNG.execute_lambda_run(
|
||||||
|
[DBType.MAIN.value],
|
||||||
|
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SESSIONS).where(_T_SESSIONS.c.session_id == sid)),
|
||||||
|
lambda s: DB_SESSION_MNG.add(s, delete(_T_VNC).where(_T_VNC.c.version_id == ver_id)),
|
||||||
|
lambda s: DB_SESSION_MNG.add(s, delete(_T_QUOTATIONS).where(_T_QUOTATIONS.c.qt_id == qid))],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_e2e_counter_accept_settles_at_target(db_engine):
|
||||||
|
"""견적 선택 카드 NGC-009(조건부 가격 조정 → COUNTER_TARGET)의 카운터를 수락하면
|
||||||
|
합의가 = 목표가(10000) — '수락 즉시 타결' 기획 결정의 E2E 검증."""
|
||||||
|
reset_sessions()
|
||||||
|
sid = _uuid.uuid4()
|
||||||
|
qid, ver_id = await _seed_quote_session(sid, ["NGC-009"])
|
||||||
|
try:
|
||||||
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||||
|
eng = await reg.get_engine(str(_uuid.uuid4()))
|
||||||
|
svc = ChatService()
|
||||||
|
session_id = str(sid)
|
||||||
|
r = None
|
||||||
|
for ui in [None, "확인", "예", "확인", "11000", "예"]:
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input=ui))
|
||||||
|
# 가격협상 카드 턴 → NGC-009 카운터(target) 제시 스텝
|
||||||
|
assert r.step == "가격협상_카운터", f"카운터 스텝 기대, 실제 {r.step}"
|
||||||
|
assert r.card_id == "NGC-009"
|
||||||
|
assert r.input_options == ["수락", "다른 가격 제시"]
|
||||||
|
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="수락"))
|
||||||
|
assert r.step == "협상완료"
|
||||||
|
assert r.settled_price == 10000 # 합의가 = 목표가 (고객사 이득)
|
||||||
|
finally:
|
||||||
|
await _cleanup(sid, qid, ver_id)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_e2e_over_target_ends_in_failure_after_closing(db_engine):
|
||||||
|
"""협력사가 목표가 초과(11000)를 고수하면: 카드 소진 → 종결 전술(목표가 최후통첩) →
|
||||||
|
그래도 거절 → 결렬(협상실패). 목표가 초과로는 절대 타결되지 않는다."""
|
||||||
|
reset_sessions()
|
||||||
|
sid = _uuid.uuid4()
|
||||||
|
qid, ver_id = await _seed_quote_session(sid, ["NGC-003"]) # HOLD 카드 1장 → 빠른 소진
|
||||||
|
try:
|
||||||
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||||
|
eng = await reg.get_engine(str(_uuid.uuid4()))
|
||||||
|
svc = ChatService()
|
||||||
|
session_id = str(sid)
|
||||||
|
steps, r = [], None
|
||||||
|
# 고수 시나리오: 가격은 항상 11000, 카운터는 전부 거절
|
||||||
|
for ui in [None, "확인", "예", "확인", "11000", "예", "11000", "예"]:
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input=ui))
|
||||||
|
steps.append(r.step)
|
||||||
|
# 카드(NGC-003) 소진 → 종결 국면: 목표가 최후통첩 카운터 스텝
|
||||||
|
assert r.step == "가격협상_카운터", f"종결 카운터 기대, 실제 {steps}"
|
||||||
|
assert "10000" in r.script # 최후통첩 = 목표가 제시
|
||||||
|
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="다른 가격 제시"))
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="11000"))
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="예"))
|
||||||
|
assert r.step == "협상실패" # target 초과 고수 → 결렬
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="확인"))
|
||||||
|
assert r.chat_end and r.outcome == "failure" # backend REJECTED → 개찰 이관
|
||||||
|
assert r.settled_price is None # 초과가 타결 없음
|
||||||
|
finally:
|
||||||
|
await _cleanup(sid, qid, ver_id)
|
||||||
@@ -109,7 +109,7 @@ async def test_context_loaded_from_db(db_engine):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||||
eng = await reg.get_engine("ktcommerce")
|
eng = await reg.get_engine("imarketkorea")
|
||||||
r = await ChatService().chat(eng, Req_Chat(session_id=str(sid)))
|
r = await ChatService().chat(eng, Req_Chat(session_id=str(sid)))
|
||||||
assert r.session_id == str(sid) and r.step == "서비스안내"
|
assert r.session_id == str(sid) and r.step == "서비스안내"
|
||||||
|
|
||||||
@@ -164,7 +164,7 @@ async def test_null_anchoring_falls_back_to_target(db_engine):
|
|||||||
assert err == ErrorType.SUCCESS
|
assert err == ErrorType.SUCCESS
|
||||||
try:
|
try:
|
||||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||||
eng = await reg.get_engine("ktcommerce")
|
eng = await reg.get_engine("imarketkorea")
|
||||||
await ChatService().chat(eng, Req_Chat(session_id=str(sid)))
|
await ChatService().chat(eng, Req_Chat(session_id=str(sid)))
|
||||||
saved = await ChatSessionRepository(eng.company_id).get(str(sid))
|
saved = await ChatSessionRepository(eng.company_id).get(str(sid))
|
||||||
assert saved is not None
|
assert saved is not None
|
||||||
@@ -192,9 +192,18 @@ async def test_loader_with_crud_double(db_engine):
|
|||||||
async def get_item_price(self, cdb, item_id):
|
async def get_item_price(self, cdb, item_id):
|
||||||
return ErrorType.SUCCESS, 7000
|
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_supplier_total_revenue(self, cdb, supplier_id):
|
async def get_supplier_total_revenue(self, cdb, supplier_id):
|
||||||
return ErrorType.SUCCESS, 12_000_000.0
|
return ErrorType.SUCCESS, 12_000_000.0
|
||||||
|
|
||||||
|
async def get_item_name(self, cdb, item_id):
|
||||||
|
return ErrorType.SUCCESS, "테스트상품"
|
||||||
|
|
||||||
|
async def get_supplier_name(self, cdb, supplier_id):
|
||||||
|
return ErrorType.SUCCESS, "테스트협력사"
|
||||||
|
|
||||||
async def get_supply_type(self, cdb, supplier_id, item_id):
|
async def get_supply_type(self, cdb, supplier_id, item_id):
|
||||||
return ErrorType.SUCCESS, 3 # sole_agency(총판) → "B"
|
return ErrorType.SUCCESS, 3 # sole_agency(총판) → "B"
|
||||||
|
|
||||||
@@ -213,6 +222,9 @@ async def test_loader_with_crud_double(db_engine):
|
|||||||
assert ctx.target_price == 50000
|
assert ctx.target_price == 50000
|
||||||
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
|
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
|
||||||
assert ctx.item_price == 7000
|
assert ctx.item_price == 7000
|
||||||
|
assert ctx.internet_lowest_price == 6300 # 인터넷 최저가 로드 확인
|
||||||
|
assert ctx.partner_name == "테스트협력사"
|
||||||
|
assert ctx.product_name == "테스트상품"
|
||||||
assert ctx.revenue_amount == 12_000_000.0
|
assert ctx.revenue_amount == 12_000_000.0
|
||||||
assert ctx.distribution_code == "B" # supply_type=3(총판) → B
|
assert ctx.distribution_code == "B" # supply_type=3(총판) → B
|
||||||
assert ctx.partner_type is PartnerType.NONE
|
assert ctx.partner_type is PartnerType.NONE
|
||||||
@@ -225,7 +237,7 @@ async def test_context_falls_back_without_db_row(db_engine):
|
|||||||
"""DB 에 세션 행이 없으면(데모/직접 호출) 기본 컨텍스트로 폴백한다."""
|
"""DB 에 세션 행이 없으면(데모/직접 호출) 기본 컨텍스트로 폴백한다."""
|
||||||
reset_sessions()
|
reset_sessions()
|
||||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||||
eng = await reg.get_engine("ktcommerce")
|
eng = await reg.get_engine("imarketkorea")
|
||||||
r = await ChatService().chat(eng, Req_Chat())
|
r = await ChatService().chat(eng, Req_Chat())
|
||||||
saved = await ChatSessionRepository(eng.company_id).get(r.session_id)
|
saved = await ChatSessionRepository(eng.company_id).get(r.session_id)
|
||||||
assert saved is not None
|
assert saved is not None
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""Phase 1 결정 스택 잔여분 검증 — 규칙 데이터화 + 선택카드 우선순위 prior.
|
||||||
|
|
||||||
|
1. 와일드카드 진입 임계(wildcard_1pct_ratio/entry_ratio)·카운터 라운드 상한(max_counter_rounds)이
|
||||||
|
하드코딩이 아니라 테넌트 config(negotiation.*)로 주입된다.
|
||||||
|
2. 의도층 prior: 갑이 견적에서 고른 카드 순서가 콜드 스타트 선택을 결정하고,
|
||||||
|
학습(Q·방문수)이 쌓이면 영향이 소멸한다 — Q-table 오염 없음.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession
|
||||||
|
from negotiation.chat.service.script_repository import ScriptRepository
|
||||||
|
from negotiation.policies.base import EpisodeState, PolicyContext
|
||||||
|
from negotiation.policies.qtable_policy import UCBQTablePolicy
|
||||||
|
from negotiation.qtable.domain.model.q_table import QTable
|
||||||
|
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
|
||||||
|
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||||
|
|
||||||
|
|
||||||
|
def _engine(**rule_overrides) -> ChatEngine:
|
||||||
|
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||||
|
for k, v in rule_overrides.items():
|
||||||
|
setattr(cfg.negotiation, k, v)
|
||||||
|
return ChatEngine(ScriptRepository(cfg, _TENANTS_DIR), rq_type="재협상")
|
||||||
|
|
||||||
|
|
||||||
|
def _session(price, anchor=10000, rnd=1, **ctx_over):
|
||||||
|
ctx = {"input_price": price, "anchor_price": anchor, "target_price": anchor + 100,
|
||||||
|
"round": rnd, "allow_selected_wildcards": False}
|
||||||
|
ctx.update(ctx_over)
|
||||||
|
return ChatSession(session_id="00000000-0000-0000-0000-00000000d001", tenant_id="imarketkorea",
|
||||||
|
company_id="imarketkorea", step="가격협상_확인", action_space_size=0, context=ctx)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 규칙 데이터화 -----------------------------------------------------------
|
||||||
|
def test_default_rules_loaded_from_config():
|
||||||
|
eng = _engine()
|
||||||
|
assert eng.rules.wildcard_1pct_ratio == 1.02
|
||||||
|
assert eng.rules.wildcard_entry_ratio == 1.05
|
||||||
|
assert eng.rules.max_counter_rounds == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_wildcard_threshold_is_config_driven():
|
||||||
|
# 기본(1.02): anchor 10000, 제시 10800 → 임계 밖 → 일반 가격협상
|
||||||
|
view = _engine().advance(_session(10800), "예")
|
||||||
|
assert view.step == "가격협상"
|
||||||
|
# 임계를 1.10 으로 완화한 테넌트 → 같은 가격에서 1% 인하 와일드카드 발동
|
||||||
|
view = _engine(wildcard_1pct_ratio=1.10).advance(_session(10800), "예")
|
||||||
|
assert view.step == "wild_card_1pct"
|
||||||
|
|
||||||
|
|
||||||
|
def test_max_counter_rounds_is_config_driven():
|
||||||
|
# round=3(카운터 2회 경과), 제시 11000: 기본 상한 3 → 아직 협상 지속
|
||||||
|
view = _engine().advance(_session(11000, rnd=3), "예")
|
||||||
|
assert view.step == "가격협상"
|
||||||
|
# 상한 1 → 종결 국면 진입: 곧장 실패가 아니라 종결 전술 발동 지점(force_closing)으로
|
||||||
|
s = _engine(max_counter_rounds=1), _session(11000, rnd=3)
|
||||||
|
view = s[0].advance(s[1], "예")
|
||||||
|
assert view.step == "가격협상" and s[1].context.get("force_closing") is True
|
||||||
|
# 종결 전술까지 소진(closing_played) 후에도 target(10100) 초과 → 결렬
|
||||||
|
view = _engine(max_counter_rounds=1).advance(_session(11000, rnd=3, closing_played=True), "예")
|
||||||
|
assert view.step == "협상실패"
|
||||||
|
# 종결 후 제시가가 target 이하로 내려오면 결렬이 아니라 타결 (새 규칙 — 구현 전엔 무조건 실패)
|
||||||
|
view = _engine(max_counter_rounds=1).advance(
|
||||||
|
_session(10050, rnd=3, closing_played=True, wildcard_used=True), "예")
|
||||||
|
assert view.step == "협상완료"
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 선택카드 우선순위 prior ---------------------------------------------------
|
||||||
|
def _snap():
|
||||||
|
return NegotiationSnapshot(revenue_amount=1, distribution_code="A", partner_count=1,
|
||||||
|
acceptance_ratio=0.1, input_price=900, anchor_price=800, target_price=1000)
|
||||||
|
|
||||||
|
|
||||||
|
def _ctx(prior=None, mask=None, n=11):
|
||||||
|
return PolicyContext(state_index=0, snapshot=_snap(), action_space_size=n,
|
||||||
|
available_mask=mask, prior_bonus=prior, episode=EpisodeState())
|
||||||
|
|
||||||
|
|
||||||
|
def test_prior_decides_cold_start_order():
|
||||||
|
"""콜드 스타트(Q=0·방문 0)에서는 갑이 먼저 고른 카드(높은 prior)가 먼저 나간다."""
|
||||||
|
qt = QTable(2, 11)
|
||||||
|
prior = np.zeros(11)
|
||||||
|
prior[7], prior[2] = 0.3, 0.15 # 선택 순서: action7 → action2
|
||||||
|
mask = np.zeros(11, dtype=bool)
|
||||||
|
mask[2] = mask[7] = True
|
||||||
|
p = UCBQTablePolicy(qt, mark_visits=False)
|
||||||
|
assert p.select(_ctx(prior=prior, mask=mask)).action_id == 7
|
||||||
|
|
||||||
|
|
||||||
|
def test_prior_decays_as_learning_accumulates():
|
||||||
|
"""학습이 쌓이면(Q·방문수) prior 는 1/(1+visits) 로 감쇠 — Q 가 지배한다."""
|
||||||
|
qt = QTable(2, 11)
|
||||||
|
qt.q[0, 2] = 1.0 # action2 가 학습상 우월
|
||||||
|
qt.visits[0, 2] = 5
|
||||||
|
qt.visits[0, 7] = 5 # 탐색 보너스 동률
|
||||||
|
prior = np.zeros(11)
|
||||||
|
prior[7] = 0.3 # 갑 선호는 action7
|
||||||
|
mask = np.zeros(11, dtype=bool)
|
||||||
|
mask[2] = mask[7] = True
|
||||||
|
p = UCBQTablePolicy(qt, mark_visits=False)
|
||||||
|
assert p.select(_ctx(prior=prior, mask=mask)).action_id == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_prior_keeps_existing_behavior():
|
||||||
|
"""prior 미주입(None) 시 기존 UCB 동작 그대로 — 회귀 없음."""
|
||||||
|
qt = QTable(2, 4)
|
||||||
|
qt.q[0] = np.array([1.0, 9.0, 2.0, 0.0])
|
||||||
|
qt.visits[0] = np.array([5, 5, 5, 5])
|
||||||
|
p = UCBQTablePolicy(qt, exploration_constant=0.1, mark_visits=False)
|
||||||
|
assert p.select(_ctx(n=4)).action_id == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_selection_prior_built_from_quotation_order():
|
||||||
|
"""ChatService._selection_prior — 견적 선택 순서 → prior 배열 (앞선 선택일수록 큼)."""
|
||||||
|
from services.chat_service import ChatService
|
||||||
|
|
||||||
|
class _Mapper:
|
||||||
|
_m = {i: f"NGC-B{i + 1:03d}" for i in range(11)}
|
||||||
|
def get_action_id(self, num):
|
||||||
|
return next((a for a, c in self._m.items() if c == num), None)
|
||||||
|
class _Engine:
|
||||||
|
mapper = _Mapper()
|
||||||
|
action_space_size = 11
|
||||||
|
|
||||||
|
session = ChatSession(session_id="00000000-0000-0000-0000-00000000d002", tenant_id="t", company_id="t",
|
||||||
|
context={"selected_nego_card_numbers": ["NGC-B008", "NGC-B003"]})
|
||||||
|
prior = ChatService._selection_prior(_Engine(), session)
|
||||||
|
assert prior is not None
|
||||||
|
assert prior[7] > prior[2] > 0 # 먼저 고른 NGC-B008(action7) 이 더 큼
|
||||||
|
assert prior[[0, 1, 4, 10]].sum() == 0 # 미선택 카드는 0
|
||||||
|
|
||||||
|
# 선택이 1장이면 순서 정보가 없어 None
|
||||||
|
session.context["selected_nego_card_numbers"] = ["NGC-B008"]
|
||||||
|
assert ChatService._selection_prior(_Engine(), session) is None
|
||||||
@@ -110,7 +110,7 @@ async def test_version_and_cell_persistence(db_engine):
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_service_step_learns_and_isolates(db_engine):
|
async def test_service_step_learns_and_isolates(db_engine):
|
||||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||||
eng = await reg.get_engine("ktcommerce")
|
eng = await reg.get_engine("imarketkorea")
|
||||||
svc = NegotiationService()
|
svc = NegotiationService()
|
||||||
|
|
||||||
def req():
|
def req():
|
||||||
@@ -126,20 +126,21 @@ async def test_service_step_learns_and_isolates(db_engine):
|
|||||||
assert r1.learned is True and r1.policy == "qtable_ucb"
|
assert r1.learned is True and r1.policy == "qtable_ucb"
|
||||||
assert r1.updated_q > 0.0 # 성공 보상으로 Q 상승
|
assert r1.updated_q > 0.0 # 성공 보상으로 Q 상승
|
||||||
|
|
||||||
# DB 에서 state 전체 방문 누적 확인 (state 58 = ktcommerce 의 이 snapshot)
|
# DB 에서 state 전체 방문 누적 확인 (state index 는 imarketkorea config 로 동적 계산)
|
||||||
from negotiation.qtable.domain.service.state_calculator import state_index
|
from negotiation.qtable.domain.service.state_calculator import state_index
|
||||||
sidx = state_index(_snap(revenue_amount=20_000_000, acceptance_ratio=0.11, input_price=990, round_number=3), eng.config.state)
|
sidx = state_index(_snap(revenue_amount=20_000_000, acceptance_ratio=0.11, input_price=990, round_number=3), eng.config.state)
|
||||||
repo_kt = LearningRepository("ktcommerce")
|
repo_a = LearningRepository("imarketkorea")
|
||||||
vid = await repo_kt.get_or_create_active_version(state_space_size=162, action_space_size=9, learning_rate=0.1, discount_factor=0.95)
|
vid = await repo_a.get_or_create_active_version(state_space_size=162, action_space_size=9, learning_rate=0.1, discount_factor=0.95)
|
||||||
_, vcells = await repo_kt.load_cells(vid)
|
_, vcells = await repo_a.load_cells(vid)
|
||||||
state_total = sum(c for s, a, c in vcells if s == sidx)
|
state_total = sum(c for s, a, c in vcells if s == sidx)
|
||||||
assert state_total == 3 # 3회 호출 → state 누적 방문 3
|
assert state_total == 3 # 3회 호출 → state 누적 방문 3
|
||||||
|
|
||||||
# 테넌트 격리: imarketkorea 는 별도 학습/별도 state
|
# 테넌트 격리: 자동 온보딩 고객사(UUID)는 별도 학습/별도 state
|
||||||
eng2 = await reg.get_engine("imarketkorea")
|
other = "00000000-0000-0000-0000-0000000000c1"
|
||||||
|
eng2 = await reg.get_engine(other)
|
||||||
ri = await svc.step(eng2, req())
|
ri = await svc.step(eng2, req())
|
||||||
assert ri.visit_count == 1
|
assert ri.visit_count == 1
|
||||||
|
|
||||||
err, ck = await repo_kt.read(lambda s: repo_kt.count_experience(s))
|
err, ck = await repo_a.read(lambda s: repo_a.count_experience(s))
|
||||||
err, ci = await LearningRepository("imarketkorea").read(lambda s: LearningRepository("imarketkorea").count_experience(s))
|
err, ci = await LearningRepository(other).read(lambda s: LearningRepository(other).count_experience(s))
|
||||||
assert ck == 3 and ci == 1 # experience 격리
|
assert ck == 3 and ci == 1 # experience 격리
|
||||||
@@ -35,7 +35,7 @@ def test_card_effectiveness_has_good_cards():
|
|||||||
assert len(good) >= 3 # 효과 좋은 카드 존재 → 학습 대상 신호
|
assert len(good) >= 3 # 효과 좋은 카드 존재 → 학습 대상 신호
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("tenant", ["ktcommerce", "imarketkorea"])
|
@pytest.mark.parametrize("tenant", ["_base", "imarketkorea"])
|
||||||
def test_learning_beats_baseline(tenant):
|
def test_learning_beats_baseline(tenant):
|
||||||
report = run("configs/exp_default.yaml", tenant)
|
report = run("configs/exp_default.yaml", tenant)
|
||||||
pols = report["policies"]
|
pols = report["policies"]
|
||||||
@@ -53,7 +53,7 @@ def test_learning_beats_baseline(tenant):
|
|||||||
|
|
||||||
|
|
||||||
def test_static_does_not_learn():
|
def test_static_does_not_learn():
|
||||||
report = run("configs/exp_default.yaml", "ktcommerce")
|
report = run("configs/exp_default.yaml", "imarketkorea")
|
||||||
static = report["policies"]["static"]
|
static = report["policies"]["static"]
|
||||||
# 정적 정책은 항상 고정 카드 → 좋은카드 적중 학습 없음(우연 일치만)
|
# 정적 정책은 항상 고정 카드 → 좋은카드 적중 학습 없음(우연 일치만)
|
||||||
assert static["good_card_hit_rate"] <= report["policies"]["qtable_ucb"]["good_card_hit_rate"]
|
assert static["good_card_hit_rate"] <= report["policies"]["qtable_ucb"]["good_card_hit_rate"]
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
"""Phase 3 이해층 검증 — InputInterpreter (자유 발화 NLU → 기대 입력 구조화).
|
||||||
|
|
||||||
|
원칙 검증: LLM 은 의도 분류·가격 표현 위치만 찾고, 숫자 계산은 결정론 파서가 한다.
|
||||||
|
① 한국어 가격 파서 결정론 ② choice 는 선택지 목록 검증 ③ price_text 는 원문 부분문자열 검증
|
||||||
|
④ 실패/타임아웃 → None(원문 폴백) ⑤ 챗 플로우: 자유 발화로 분기·가격 입력이 진행된다
|
||||||
|
⑥ LLM 미설정 시 기존(정형 입력) 동작 그대로 — 회귀 없음.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from negotiation.chat.service.input_interpreter import (
|
||||||
|
InputInterpreter, InterpretedInput, parse_korean_price,
|
||||||
|
)
|
||||||
|
|
||||||
|
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 결정론 한국어 가격 파서 -------------------------------------------------
|
||||||
|
@pytest.mark.parametrize("text,expected", [
|
||||||
|
("10,500원", 10500),
|
||||||
|
("10500", 10500),
|
||||||
|
("1만 500원", 10500),
|
||||||
|
("1만500원", 10500),
|
||||||
|
("만원", 10000),
|
||||||
|
("1.5만", 15000),
|
||||||
|
("3만2천원", 32000),
|
||||||
|
("2억", 200_000_000),
|
||||||
|
("0", None), # 0 이하 무효
|
||||||
|
("그건 어렵습니다", None), # 가격 아님
|
||||||
|
("만원에 3개", None), # 잡문자 혼입 → 해석 불가(안전 폴백)
|
||||||
|
])
|
||||||
|
def test_parse_korean_price(text, expected):
|
||||||
|
got = parse_korean_price(text)
|
||||||
|
assert (got == expected) if expected is not None else (got is None)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- LLM 출력 검증 (환각 차단) ----------------------------------------------
|
||||||
|
def _fake(reply: dict):
|
||||||
|
def call(messages):
|
||||||
|
return reply
|
||||||
|
return call
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_choice_mapped_to_option():
|
||||||
|
nat = InputInterpreter(llm_call=_fake({"intent": "choice", "choice": "예", "price_text": None}))
|
||||||
|
out = await nat.interpret("네 접니다, 말씀하세요", input_mode="yes_no", input_options=["예", "아니오"])
|
||||||
|
assert out == InterpretedInput(kind="choice", value="예", source="예")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_choice_outside_options_rejected():
|
||||||
|
nat = InputInterpreter(llm_call=_fake({"intent": "choice", "choice": "글쎄요", "price_text": None}))
|
||||||
|
assert await nat.interpret("음...", input_mode="yes_no", input_options=["예", "아니오"]) is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_price_span_verified_and_parsed_deterministically():
|
||||||
|
nat = InputInterpreter(llm_call=_fake({"intent": "price", "choice": None, "price_text": "1만 500원"}))
|
||||||
|
out = await nat.interpret("저희 마진상 1만 500원까지는 맞춰드릴 수 있습니다", input_mode="price")
|
||||||
|
assert out is not None and out.kind == "price"
|
||||||
|
assert out.value == "10500" # 숫자는 결정론 파서 산출(LLM 계산 아님)
|
||||||
|
assert out.source == "1만 500원"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_price_span_not_in_text_rejected():
|
||||||
|
"""LLM 이 원문에 없는 가격 표현을 지어내면 폐기(환각 차단)."""
|
||||||
|
nat = InputInterpreter(llm_call=_fake({"intent": "price", "choice": None, "price_text": "9,000원"}))
|
||||||
|
assert await nat.interpret("만원이면 가능합니다", input_mode="price") is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_unknown_and_failures_fall_back():
|
||||||
|
assert await InputInterpreter(llm_call=_fake({"intent": "unknown"})).interpret(
|
||||||
|
"글쎄요 검토해 볼게요", input_mode="yes_no", input_options=["예", "아니오"]) is None
|
||||||
|
|
||||||
|
def boom(messages):
|
||||||
|
raise RuntimeError("LLM down")
|
||||||
|
assert await InputInterpreter(llm_call=boom).interpret("네", input_mode="yes_no", input_options=["예"]) is None
|
||||||
|
|
||||||
|
def slow(messages):
|
||||||
|
import time
|
||||||
|
time.sleep(0.5)
|
||||||
|
return {"intent": "choice", "choice": "예"}
|
||||||
|
nat = InputInterpreter(llm_call=slow, timeout_seconds=0.05)
|
||||||
|
assert await nat.interpret("네", input_mode="yes_no", input_options=["예"]) is None
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 챗 플로우 E2E (fake LLM) ------------------------------------------------
|
||||||
|
def _routing_fake(messages):
|
||||||
|
"""단계별 fake — 기대 입력이 가격이면 price, 아니면 '예' choice 로 응답."""
|
||||||
|
user = messages[-1]["content"]
|
||||||
|
if "가격(숫자)" in user:
|
||||||
|
return {"intent": "price", "choice": None, "price_text": "1만 500원"}
|
||||||
|
return {"intent": "choice", "choice": "예", "price_text": None}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_chat_flow_free_text_negotiation(db_engine):
|
||||||
|
"""자유 발화만으로 담당자확인 분기 + 가격 입력이 진행된다 (버튼 없는 '진짜 대화')."""
|
||||||
|
from router.v1.chat.protocol import Req_Chat
|
||||||
|
from services.chat_service import ChatService, reset_sessions
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
from tenancy.registry import TenantEngineRegistry
|
||||||
|
|
||||||
|
reset_sessions()
|
||||||
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||||
|
eng = await reg.get_engine("imarketkorea")
|
||||||
|
eng.config.llm.enabled = True
|
||||||
|
|
||||||
|
svc = ChatService()
|
||||||
|
svc._interpreter = InputInterpreter(llm_call=_routing_fake)
|
||||||
|
orig = InputInterpreter.available
|
||||||
|
InputInterpreter.available = staticmethod(lambda: True)
|
||||||
|
try:
|
||||||
|
sid = None
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=sid)) # 서비스안내
|
||||||
|
sid = r.session_id
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="확인")) # 담당자확인 (fast path)
|
||||||
|
assert r.step == "담당자확인" and r.interpreted_input is None
|
||||||
|
|
||||||
|
# 자유 발화 → NLU 가 "예" 로 매핑 → 협상품목안내
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="네 접니다, 말씀하세요"))
|
||||||
|
assert r.step == "협상품목안내"
|
||||||
|
assert r.interpreted_input == "예"
|
||||||
|
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="확인")) # 기존가격제시(price)
|
||||||
|
# 자유 발화 가격 → span "1만 500원" → 결정론 파서 10500 → 가격 저장 후 확인 단계
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="저희 마진상 1만 500원까지는 맞춰드릴 수 있습니다"))
|
||||||
|
assert r.step == "가격협상_확인"
|
||||||
|
assert r.interpreted_input == "10500"
|
||||||
|
assert "10500" in r.script # 멘트 치환도 해석된 가격으로
|
||||||
|
finally:
|
||||||
|
InputInterpreter.available = orig
|
||||||
|
eng.config.llm.enabled = False
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_chat_flow_without_llm_keeps_legacy_behavior(db_engine):
|
||||||
|
"""LLM 미설정(available=False)이면 자유 발화는 원문 그대로 엔진에 전달 — 기존 동작 회귀 없음."""
|
||||||
|
from router.v1.chat.protocol import Req_Chat
|
||||||
|
from services.chat_service import ChatService, reset_sessions
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
from tenancy.registry import TenantEngineRegistry
|
||||||
|
|
||||||
|
reset_sessions()
|
||||||
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||||
|
eng = await reg.get_engine("imarketkorea")
|
||||||
|
|
||||||
|
svc = ChatService()
|
||||||
|
sid = None
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=sid))
|
||||||
|
sid = r.session_id
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="확인"))
|
||||||
|
assert r.step == "담당자확인"
|
||||||
|
# conftest 가드로 available=False → NLU 미동작, interpreted_input 없음
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="네 접니다"))
|
||||||
|
assert r.interpreted_input is None
|
||||||
@@ -29,12 +29,12 @@ async def test_step_requires_tenant_header(client):
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_step_tenant_divergence(client):
|
async def test_step_tenant_divergence(client):
|
||||||
rk = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "ktcommerce"}, json=_BODY)
|
rk = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "_base"}, json=_BODY)
|
||||||
ri = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "imarketkorea"}, json=_BODY)
|
ri = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "imarketkorea"}, json=_BODY)
|
||||||
assert rk.status_code == 200 and ri.status_code == 200
|
assert rk.status_code == 200 and ri.status_code == 200
|
||||||
dk, di = rk.json(), ri.json()
|
dk, di = rk.json(), ri.json()
|
||||||
# 같은 입력이 테넌트 config 에 따라 다른 상태/카드로 갈린다
|
# 같은 입력이 테넌트 config 에 따라 다른 상태/카드로 갈린다 (_base=공용 NGC-0xx, imk=NGC-Bxxx)
|
||||||
assert dk["card_id"].startswith("NGC-A")
|
assert dk["card_id"].startswith("NGC-0")
|
||||||
assert di["card_id"].startswith("NGC-B")
|
assert di["card_id"].startswith("NGC-B")
|
||||||
assert dk["state_index"] != di["state_index"]
|
assert dk["state_index"] != di["state_index"]
|
||||||
# 응답 형태
|
# 응답 형태
|
||||||
@@ -49,7 +49,7 @@ async def test_step_tenant_divergence(client):
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_step_invalid_distribution_code_is_domain_error(client):
|
async def test_step_invalid_distribution_code_is_domain_error(client):
|
||||||
body = dict(_BODY, distribution_code="Z")
|
body = dict(_BODY, distribution_code="Z")
|
||||||
r = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "ktcommerce"}, json=body)
|
r = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "imarketkorea"}, json=body)
|
||||||
assert r.status_code == 200 # HTTP 는 200, 결과코드로 에러 전달(backend 규약)
|
assert r.status_code == 200 # HTTP 는 200, 결과코드로 에러 전달(backend 규약)
|
||||||
assert r.json()["result"]["desc"] == "NEGO_INVALID_STEP"
|
assert r.json()["result"]["desc"] == "NEGO_INVALID_STEP"
|
||||||
|
|
||||||
@@ -57,5 +57,5 @@ async def test_step_invalid_distribution_code_is_domain_error(client):
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_step_invalid_outcome(client):
|
async def test_step_invalid_outcome(client):
|
||||||
body = dict(_BODY, outcome="maybe")
|
body = dict(_BODY, outcome="maybe")
|
||||||
r = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "ktcommerce"}, json=body)
|
r = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "imarketkorea"}, json=body)
|
||||||
assert r.json()["result"]["desc"] == "INVALID_REQUEST_DATA"
|
assert r.json()["result"]["desc"] == "INVALID_REQUEST_DATA"
|
||||||
@@ -62,5 +62,5 @@ async def test_tenant_header_required(client):
|
|||||||
assert r.json()["result"]["desc"] == "TENANT_HEADER_MISSING"
|
assert r.json()["result"]["desc"] == "TENANT_HEADER_MISSING"
|
||||||
|
|
||||||
# 헤더가 있으면 미들웨어 통과 (라우트 미존재라 404).
|
# 헤더가 있으면 미들웨어 통과 (라우트 미존재라 404).
|
||||||
r = await client.get("/v1/some-protected-path", headers={"X-Tenant-ID": "ktcommerce"})
|
r = await client.get("/v1/some-protected-path", headers={"X-Tenant-ID": "imarketkorea"})
|
||||||
assert r.status_code == 404
|
assert r.status_code == 404
|
||||||
@@ -22,7 +22,7 @@ def _loader() -> TenantConfigLoader:
|
|||||||
|
|
||||||
|
|
||||||
def test_platform_neutral_defaults_load():
|
def test_platform_neutral_defaults_load():
|
||||||
cfg = _loader().load("ktcommerce")
|
cfg = _loader().load("_base")
|
||||||
|
|
||||||
# 우리 플랫폼 중립 기본값 (CLEANROOM.md)
|
# 우리 플랫폼 중립 기본값 (CLEANROOM.md)
|
||||||
assert cfg.state.revenue.thresholds == [10_000_000, 50_000_000]
|
assert cfg.state.revenue.thresholds == [10_000_000, 50_000_000]
|
||||||
@@ -47,12 +47,12 @@ def test_platform_neutral_defaults_load():
|
|||||||
|
|
||||||
|
|
||||||
def test_state_space_and_action_space_size():
|
def test_state_space_and_action_space_size():
|
||||||
cfg = _loader().load("ktcommerce")
|
cfg = _loader().load("_base")
|
||||||
assert cfg.state.state_space_size == 162 # 3×3×3×3×2 (차원 구성은 기능적 설계)
|
assert cfg.state.state_space_size == 162 # 3×3×3×3×2 (차원 구성은 기능적 설계)
|
||||||
assert cfg.action_mapping.action_space_size == 11
|
assert cfg.action_mapping.action_space_size == 11
|
||||||
# 합성 데모 카드 코드 (우리 스킴)
|
# 공용 카드 코드 (파일 폴백 스냅샷 — 정본은 DB 카탈로그)
|
||||||
assert cfg.action_mapping.action_to_card["0"] == "NGC-A001"
|
assert cfg.action_mapping.action_to_card["0"] == "NGC-001"
|
||||||
assert cfg.action_mapping.action_to_card["8"] == "NGC-A009"
|
assert cfg.action_mapping.action_to_card["8"] == "NGC-009"
|
||||||
|
|
||||||
|
|
||||||
def test_base_deep_merge_unit():
|
def test_base_deep_merge_unit():
|
||||||
@@ -90,7 +90,6 @@ def test_base_self_does_not_inherit():
|
|||||||
|
|
||||||
def test_is_registered():
|
def test_is_registered():
|
||||||
loader = _loader()
|
loader = _loader()
|
||||||
assert loader.is_registered("ktcommerce") is True
|
|
||||||
assert loader.is_registered("imarketkorea") is True
|
assert loader.is_registered("imarketkorea") is True
|
||||||
# 미등록 company_id(uuid 등)는 _base 자동 온보딩 대상이라 '등록됨'으로 본다. 빈 키만 미등록.
|
# 미등록 company_id(uuid 등)는 _base 자동 온보딩 대상이라 '등록됨'으로 본다. 빈 키만 미등록.
|
||||||
assert loader.is_registered("00000000-0000-0000-0000-000000000001") is True
|
assert loader.is_registered("00000000-0000-0000-0000-000000000001") is True
|
||||||
@@ -99,7 +98,7 @@ def test_is_registered():
|
|||||||
|
|
||||||
def test_no_proprietary_card_codes_or_labels_in_repo():
|
def test_no_proprietary_card_codes_or_labels_in_repo():
|
||||||
"""클린룸 가드: 독점 카드 코드/ verbatim 라벨이 로드된 config 에 존재하지 않는다."""
|
"""클린룸 가드: 독점 카드 코드/ verbatim 라벨이 로드된 config 에 존재하지 않는다."""
|
||||||
for tid in ("_base", "ktcommerce", "imarketkorea"):
|
for tid in ("_base", "imarketkorea"):
|
||||||
cfg = _loader().load(tid)
|
cfg = _loader().load(tid)
|
||||||
cards = " ".join(cfg.action_mapping.action_to_card.values())
|
cards = " ".join(cfg.action_mapping.action_to_card.values())
|
||||||
assert "NC26" not in cards # 참고 엔진의 고유 카드 코드
|
assert "NC26" not in cards # 참고 엔진의 고유 카드 코드
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ def _snapshot(**over) -> NegotiationSnapshot:
|
|||||||
|
|
||||||
|
|
||||||
def test_build_state_deterministic_and_in_range():
|
def test_build_state_deterministic_and_in_range():
|
||||||
cfg = _cfg("ktcommerce")
|
cfg = _cfg("_base")
|
||||||
snap = _snapshot()
|
snap = _snapshot()
|
||||||
s1 = build_state(snap, cfg.state)
|
s1 = build_state(snap, cfg.state)
|
||||||
s2 = build_state(snap, cfg.state)
|
s2 = build_state(snap, cfg.state)
|
||||||
@@ -65,7 +65,7 @@ def test_encode_index_known_example():
|
|||||||
|
|
||||||
|
|
||||||
def test_mixed_radix_bijection_over_full_space():
|
def test_mixed_radix_bijection_over_full_space():
|
||||||
cfg = _cfg("ktcommerce")
|
cfg = _cfg("_base")
|
||||||
dims = state_dims(cfg.state)
|
dims = state_dims(cfg.state)
|
||||||
assert dims == [3, 3, 3, 3, 2]
|
assert dims == [3, 3, 3, 3, 2]
|
||||||
seen = set()
|
seen = set()
|
||||||
@@ -77,17 +77,17 @@ def test_mixed_radix_bijection_over_full_space():
|
|||||||
|
|
||||||
|
|
||||||
def test_config_injection_changes_classification():
|
def test_config_injection_changes_classification():
|
||||||
# revenue=20,000,000 원: ktcommerce(th=[10M,50M]) → mid(1), imarketkorea(th=[30M,100M]) → low(0)
|
# revenue=20,000,000 원: _base(th=[10M,50M]) → mid(1), imarketkorea(th=[30M,100M]) → low(0)
|
||||||
snap = _snapshot(revenue_amount=20_000_000)
|
snap = _snapshot(revenue_amount=20_000_000)
|
||||||
kt = build_state(snap, _cfg("ktcommerce").state)
|
base = build_state(snap, _cfg("_base").state)
|
||||||
imk = build_state(snap, _cfg("imarketkorea").state)
|
imk = build_state(snap, _cfg("imarketkorea").state)
|
||||||
assert kt.revenue_idx == 1
|
assert base.revenue_idx == 1
|
||||||
assert imk.revenue_idx == 0
|
assert imk.revenue_idx == 0
|
||||||
assert kt != imk # 같은 입력이 테넌트 config 에 따라 다른 상태
|
assert base != imk # 같은 입력이 테넌트 config 에 따라 다른 상태
|
||||||
|
|
||||||
|
|
||||||
def test_distribution_unknown_code_raises():
|
def test_distribution_unknown_code_raises():
|
||||||
cfg = _cfg("ktcommerce")
|
cfg = _cfg("_base")
|
||||||
snap = _snapshot(distribution_code="Z") # code_map 에 없음
|
snap = _snapshot(distribution_code="Z") # code_map 에 없음
|
||||||
try:
|
try:
|
||||||
build_state(snap, cfg.state)
|
build_state(snap, cfg.state)
|
||||||
@@ -97,7 +97,7 @@ def test_distribution_unknown_code_raises():
|
|||||||
|
|
||||||
|
|
||||||
def test_price_zone_and_partner_buckets():
|
def test_price_zone_and_partner_buckets():
|
||||||
cfg = _cfg("ktcommerce").state
|
cfg = _cfg("_base").state
|
||||||
# 제시가 ≤ 앵커가(9900) → 우선협상 구간(0)
|
# 제시가 ≤ 앵커가(9900) → 우선협상 구간(0)
|
||||||
assert build_state(_snapshot(input_price=9800), cfg).price_zone_idx == 0
|
assert build_state(_snapshot(input_price=9800), cfg).price_zone_idx == 0
|
||||||
# 제시가 > 앵커가 → 협상 지속 구간(1)
|
# 제시가 > 앵커가 → 협상 지속 구간(1)
|
||||||
@@ -110,28 +110,28 @@ def test_price_zone_and_partner_buckets():
|
|||||||
|
|
||||||
def test_reward_deterministic_and_config_driven():
|
def test_reward_deterministic_and_config_driven():
|
||||||
snap = _snapshot(outcome=NegotiationOutcome.FAILURE, round_number=2)
|
snap = _snapshot(outcome=NegotiationOutcome.FAILURE, round_number=2)
|
||||||
kt = _cfg("ktcommerce")
|
base = _cfg("_base")
|
||||||
imk = _cfg("imarketkorea")
|
imk = _cfg("imarketkorea")
|
||||||
kt_rc = RewardCalculator(kt.reward, kt.state) # failure_penalty -0.5
|
base_rc = RewardCalculator(base.reward, base.state) # failure_penalty -0.5
|
||||||
imk_rc = RewardCalculator(imk.reward, imk.state) # failure_penalty -0.7
|
imk_rc = RewardCalculator(imk.reward, imk.state) # failure_penalty -0.7
|
||||||
|
|
||||||
r1 = kt_rc.calculate(snap)
|
r1 = base_rc.calculate(snap)
|
||||||
r2 = kt_rc.calculate(snap)
|
r2 = base_rc.calculate(snap)
|
||||||
assert r1 == r2 # 결정론
|
assert r1 == r2 # 결정론
|
||||||
assert r1.end_reward == -0.5 # config 반영
|
assert r1.end_reward == -0.5 # config 반영
|
||||||
assert imk_rc.calculate(snap).end_reward == -0.7
|
assert imk_rc.calculate(snap).end_reward == -0.7
|
||||||
|
|
||||||
# 성공 라운드 보상이 실패보다 크다 (방향성)
|
# 성공 라운드 보상이 실패보다 크다 (방향성)
|
||||||
success = _snapshot(outcome=NegotiationOutcome.SUCCESS, round_number=0)
|
success = _snapshot(outcome=NegotiationOutcome.SUCCESS, round_number=0)
|
||||||
assert kt_rc.calculate(success).total > kt_rc.calculate(_snapshot(outcome=NegotiationOutcome.FAILURE, round_number=0)).total
|
assert base_rc.calculate(success).total > base_rc.calculate(_snapshot(outcome=NegotiationOutcome.FAILURE, round_number=0)).total
|
||||||
|
|
||||||
|
|
||||||
def test_action_card_mapper_roundtrip_and_mask():
|
def test_action_card_mapper_roundtrip_and_mask():
|
||||||
cfg = _cfg("ktcommerce")
|
cfg = _cfg("_base")
|
||||||
mapper = ActionCardMapper(cfg.action_mapping)
|
mapper = ActionCardMapper(cfg.action_mapping)
|
||||||
assert mapper.action_space_size == 11
|
assert mapper.action_space_size == 11
|
||||||
assert mapper.get_card_id(0) == "NGC-A001"
|
assert mapper.get_card_id(0) == "NGC-001"
|
||||||
assert mapper.get_action_id("NGC-A001") == 0
|
assert mapper.get_action_id("NGC-001") == 0
|
||||||
assert mapper.get_card_id(99) is None
|
assert mapper.get_card_id(99) is None
|
||||||
|
|
||||||
# 중복방지 마스킹: 사용한 action 제외
|
# 중복방지 마스킹: 사용한 action 제외
|
||||||
|
|||||||
@@ -27,12 +27,12 @@ def _registry() -> TenantEngineRegistry:
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_two_tenants_distinct_engines():
|
async def test_two_tenants_distinct_engines():
|
||||||
reg = _registry()
|
reg = _registry()
|
||||||
e1 = await reg.get_engine("ktcommerce")
|
e1 = await reg.get_engine("_base")
|
||||||
e2 = await reg.get_engine("imarketkorea")
|
e2 = await reg.get_engine("imarketkorea")
|
||||||
assert e1 is not e2
|
assert e1 is not e2
|
||||||
assert e1.tenant_id == "ktcommerce" and e2.tenant_id == "imarketkorea"
|
assert e1.tenant_id == "_base" and e2.tenant_id == "imarketkorea"
|
||||||
# 서로 다른 카드매핑 (다른 카드셋)
|
# 서로 다른 카드매핑 (다른 카드셋 — _base=공용 카탈로그, imk=파일 오버라이드)
|
||||||
assert e1.mapper.get_card_id(0) == "NGC-A001"
|
assert e1.mapper.get_card_id(0) == "NGC-001"
|
||||||
assert e2.mapper.get_card_id(0) == "NGC-B001"
|
assert e2.mapper.get_card_id(0) == "NGC-B001"
|
||||||
# 차원
|
# 차원
|
||||||
assert e1.state_space_size == 162 and e1.action_space_size == 11
|
assert e1.state_space_size == 162 and e1.action_space_size == 11
|
||||||
@@ -41,8 +41,8 @@ async def test_two_tenants_distinct_engines():
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_engine_cached():
|
async def test_engine_cached():
|
||||||
reg = _registry()
|
reg = _registry()
|
||||||
a = await reg.get_engine("ktcommerce")
|
a = await reg.get_engine("imarketkorea")
|
||||||
b = await reg.get_engine("ktcommerce")
|
b = await reg.get_engine("imarketkorea")
|
||||||
assert a is b # 캐시 — 동일 인스턴스
|
assert a is b # 캐시 — 동일 인스턴스
|
||||||
|
|
||||||
|
|
||||||
@@ -58,7 +58,7 @@ async def test_concurrent_first_build_once():
|
|||||||
return EngineFactory.build(config)
|
return EngineFactory.build(config)
|
||||||
|
|
||||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0), factory=CountingFactory)
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0), factory=CountingFactory)
|
||||||
results = await asyncio.gather(*[reg.get_engine("ktcommerce") for _ in range(12)])
|
results = await asyncio.gather(*[reg.get_engine("imarketkorea") for _ in range(12)])
|
||||||
# 모두 같은 인스턴스 + 1회만 조립
|
# 모두 같은 인스턴스 + 1회만 조립
|
||||||
assert all(r is results[0] for r in results)
|
assert all(r is results[0] for r in results)
|
||||||
assert builds["n"] == 1
|
assert builds["n"] == 1
|
||||||
@@ -71,7 +71,7 @@ async def test_unregistered_company_id_auto_onboards():
|
|||||||
eng = await reg.get_engine("00000000-0000-0000-0000-000000000001")
|
eng = await reg.get_engine("00000000-0000-0000-0000-000000000001")
|
||||||
assert eng.action_space_size == 11 and eng.state_space_size == 162
|
assert eng.action_space_size == 11 and eng.state_space_size == 162
|
||||||
assert eng.company_id == "00000000-0000-0000-0000-000000000001"
|
assert eng.company_id == "00000000-0000-0000-0000-000000000001"
|
||||||
assert reg.is_registered("ktcommerce") is True
|
assert reg.is_registered("imarketkorea") is True
|
||||||
# 빈 키만 미등록 → KeyError
|
# 빈 키만 미등록 → KeyError
|
||||||
with pytest.raises(KeyError):
|
with pytest.raises(KeyError):
|
||||||
await reg.get_engine("")
|
await reg.get_engine("")
|
||||||
@@ -80,9 +80,9 @@ async def test_unregistered_company_id_auto_onboards():
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_reload_rebuilds_only_that_tenant():
|
async def test_reload_rebuilds_only_that_tenant():
|
||||||
reg = _registry()
|
reg = _registry()
|
||||||
a = await reg.get_engine("ktcommerce")
|
a = await reg.get_engine("_base")
|
||||||
b = await reg.get_engine("imarketkorea")
|
b = await reg.get_engine("imarketkorea")
|
||||||
reloaded = await reg.reload("ktcommerce")
|
reloaded = await reg.reload("_base")
|
||||||
assert reloaded is not a # 재조립됨
|
assert reloaded is not a # 재조립됨
|
||||||
assert await reg.get_engine("imarketkorea") is b # 타테넌트는 그대로
|
assert await reg.get_engine("imarketkorea") is b # 타테넌트는 그대로
|
||||||
|
|
||||||
@@ -171,8 +171,8 @@ async def test_demo_tenant_keeps_file_brand(db_engine):
|
|||||||
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
|
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
|
||||||
company_repo=_FakeCompany(),
|
company_repo=_FakeCompany(),
|
||||||
)
|
)
|
||||||
eng = await reg.get_engine("ktcommerce") # 비-UUID → 조회 안 함
|
eng = await reg.get_engine("imarketkorea") # 비-UUID → 조회 안 함
|
||||||
assert eng.config.resources.company_name == "데모상사 A"
|
assert eng.config.resources.company_name == "데모상사 B"
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
@@ -236,6 +236,6 @@ async def test_middleware_header_missing_unregistered_registered(client):
|
|||||||
assert r.json().get("result", {}).get("desc") != "TENANT_NOT_REGISTERED"
|
assert r.json().get("result", {}).get("desc") != "TENANT_NOT_REGISTERED"
|
||||||
|
|
||||||
# 등록 테넌트 → 미들웨어 통과
|
# 등록 테넌트 → 미들웨어 통과
|
||||||
r = await client.get("/v1/protected", headers={"X-Tenant-ID": "ktcommerce"})
|
r = await client.get("/v1/protected", headers={"X-Tenant-ID": "imarketkorea"})
|
||||||
assert r.status_code == 404
|
assert r.status_code == 404
|
||||||
assert r.json().get("result", {}).get("desc") != "TENANT_NOT_REGISTERED"
|
assert r.json().get("result", {}).get("desc") != "TENANT_NOT_REGISTERED"
|
||||||
@@ -58,8 +58,8 @@ async def test_warm_start_copies_base_with_decayed_visits(db_engine):
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_cold_start_creates_warmstart_version(db_engine):
|
async def test_cold_start_creates_warmstart_version(db_engine):
|
||||||
await _seed_base(A=11) # ktcommerce action_space=11 과 차원 일치해야 warm-start
|
await _seed_base(A=11) # imarketkorea action_space=11 과 차원 일치해야 warm-start
|
||||||
eng = await _reg().get_engine("ktcommerce") # 활성 버전 없음 → cold-start
|
eng = await _reg().get_engine("imarketkorea") # 활성 버전 없음 → cold-start
|
||||||
policy, version_id, repo = await QTablePolicyStore.load(eng)
|
policy, version_id, repo = await QTablePolicyStore.load(eng)
|
||||||
err, ver = await repo.read(lambda s: repo.get_active_version(s))
|
err, ver = await repo.read(lambda s: repo.get_active_version(s))
|
||||||
assert ver.version_name == "v000_warmstart_from_base"
|
assert ver.version_name == "v000_warmstart_from_base"
|
||||||
@@ -140,7 +140,7 @@ async def test_no_base_returns_none(db_engine):
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_existing_version_not_warmstarted(db_engine):
|
async def test_existing_version_not_warmstarted(db_engine):
|
||||||
await _seed_base()
|
await _seed_base()
|
||||||
eng = await _reg().get_engine("ktcommerce")
|
eng = await _reg().get_engine("imarketkorea")
|
||||||
# 첫 로드 → warm-start 버전 생성
|
# 첫 로드 → warm-start 버전 생성
|
||||||
await QTablePolicyStore.load(eng)
|
await QTablePolicyStore.load(eng)
|
||||||
# 둘째 로드 → 기존 활성 버전 재사용(중복 warm-start 안 함)
|
# 둘째 로드 → 기존 활성 버전 재사용(중복 warm-start 안 함)
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ reset-learning, reset-all, q-table/{versions,switch,current}, experience-logs, t
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
H = {"X-Tenant-ID": "ktcommerce"}
|
H = {"X-Tenant-ID": "imarketkorea"}
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
@@ -97,7 +97,7 @@ async def test_invalidate_and_reset_scoped(client, db_engine):
|
|||||||
sid = cr.json()["session_id"]
|
sid = cr.json()["session_id"]
|
||||||
if cr.json().get("chat_end"):
|
if cr.json().get("chat_end"):
|
||||||
break
|
break
|
||||||
H2 = {"X-Tenant-ID": "imarketkorea"}
|
H2 = {"X-Tenant-ID": "00000000-0000-0000-0000-0000000000b2"} # 실고객사 모사(자동 온보딩)
|
||||||
sid2 = None
|
sid2 = None
|
||||||
for ui in convo:
|
for ui in convo:
|
||||||
cr = await client.post("/v1/chat", headers=H2, json={"session_id": sid2, "user_input": ui})
|
cr = await client.post("/v1/chat", headers=H2, json={"session_id": sid2, "user_input": ui})
|
||||||
@@ -108,7 +108,7 @@ async def test_invalidate_and_reset_scoped(client, db_engine):
|
|||||||
before2 = (await client.get("/v1/experience-logs", headers=H2)).json()["total"]
|
before2 = (await client.get("/v1/experience-logs", headers=H2)).json()["total"]
|
||||||
assert before2 >= 1
|
assert before2 >= 1
|
||||||
|
|
||||||
# ktcommerce reset-all → imarketkorea 무영향
|
# imarketkorea reset-all → 타테넌트(H2) 무영향
|
||||||
assert (await client.post("/v1/reset-all", headers=H)).json()["success"]
|
assert (await client.post("/v1/reset-all", headers=H)).json()["success"]
|
||||||
assert (await client.get("/v1/experience-logs", headers=H)).json()["total"] == 0
|
assert (await client.get("/v1/experience-logs", headers=H)).json()["total"] == 0
|
||||||
assert (await client.get("/v1/experience-logs", headers=H2)).json()["total"] == before2
|
assert (await client.get("/v1/experience-logs", headers=H2)).json()["total"] == before2
|
||||||
+22
-22
@@ -3,7 +3,7 @@
|
|||||||
1. 전체 대화: 서비스안내→담당자확인→협상품목안내→가격협상→와일드카드→협상완료→협상종료(chat_end).
|
1. 전체 대화: 서비스안내→담당자확인→협상품목안내→가격협상→와일드카드→협상완료→협상종료(chat_end).
|
||||||
2. 가격협상 턴에서 카드 선택 + 학습(card_id, updated_q).
|
2. 가격협상 턴에서 카드 선택 + 학습(card_id, updated_q).
|
||||||
3. 와일드카드 발동(wild_card_1pct) + 종료 보상(success).
|
3. 와일드카드 발동(wild_card_1pct) + 종료 보상(success).
|
||||||
4. 브랜드 치환 테넌트별(데모상사 A/B), 클린룸(스크립트에 KT 흔적 없음).
|
4. 브랜드 치환(데모상사 B), 클린룸(스크립트에 KT 흔적 없음).
|
||||||
5. 경험로그 적재 + 종료 후 진행 시 에러.
|
5. 경험로그 적재 + 종료 후 진행 시 에러.
|
||||||
6. (HTTP) 헤더로 새 세션 시작 + 한 턴 진행.
|
6. (HTTP) 헤더로 새 세션 시작 + 한 턴 진행.
|
||||||
"""
|
"""
|
||||||
@@ -44,7 +44,7 @@ async def _run(svc, eng, turns):
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_full_conversation_reaches_completion(db_engine):
|
async def test_full_conversation_reaches_completion(db_engine):
|
||||||
reset_sessions()
|
reset_sessions()
|
||||||
eng = await _reg().get_engine("ktcommerce")
|
eng = await _reg().get_engine("imarketkorea")
|
||||||
svc = ChatService()
|
svc = ChatService()
|
||||||
# anchor=9900, target=10000(기본). 11000(>anchor*1.02)→가격협상(카드),
|
# anchor=9900, target=10000(기본). 11000(>anchor*1.02)→가격협상(카드),
|
||||||
# 10000(anchor<p≤anchor*1.02)→1% 와일드카드→수락하면 협상완료.
|
# 10000(anchor<p≤anchor*1.02)→1% 와일드카드→수락하면 협상완료.
|
||||||
@@ -59,7 +59,7 @@ async def test_full_conversation_reaches_completion(db_engine):
|
|||||||
|
|
||||||
# 가격협상 카드선택 + 학습
|
# 가격협상 카드선택 + 학습
|
||||||
nego = [r for r in out if r.step == "가격협상"]
|
nego = [r for r in out if r.step == "가격협상"]
|
||||||
assert nego and nego[0].card_id and nego[0].card_id.startswith("NGC-A")
|
assert nego and nego[0].card_id and nego[0].card_id.startswith("NGC-B")
|
||||||
assert nego[0].updated_q is not None
|
assert nego[0].updated_q is not None
|
||||||
|
|
||||||
# 와일드카드 발동 (1% 인하)
|
# 와일드카드 발동 (1% 인하)
|
||||||
@@ -70,11 +70,11 @@ async def test_full_conversation_reaches_completion(db_engine):
|
|||||||
assert done and done[0].reward_total is not None
|
assert done and done[0].reward_total is not None
|
||||||
|
|
||||||
# 브랜드 치환 + 클린룸
|
# 브랜드 치환 + 클린룸
|
||||||
assert "데모상사 A" in out[0].script
|
assert "데모상사 B" in out[0].script
|
||||||
assert not _KT.search(out[0].script)
|
assert not _KT.search(out[0].script)
|
||||||
|
|
||||||
# 경험로그 적재
|
# 경험로그 적재
|
||||||
repo = LearningRepository("ktcommerce")
|
repo = LearningRepository("imarketkorea")
|
||||||
err, cnt = await repo.read(lambda s: repo.count_experience(s))
|
err, cnt = await repo.read(lambda s: repo.count_experience(s))
|
||||||
assert cnt >= 1
|
assert cnt >= 1
|
||||||
|
|
||||||
@@ -87,7 +87,7 @@ async def test_wildcard_1pct_accept_settles_at_offer_price(db_engine):
|
|||||||
잡히던 버그 — settled_price 가 인하가(예: 19800)로 내려와야 한다.
|
잡히던 버그 — settled_price 가 인하가(예: 19800)로 내려와야 한다.
|
||||||
"""
|
"""
|
||||||
reset_sessions()
|
reset_sessions()
|
||||||
eng = await _reg().get_engine("ktcommerce")
|
eng = await _reg().get_engine("imarketkorea")
|
||||||
svc = ChatService()
|
svc = ChatService()
|
||||||
# anchor=9900(기본). 10000 은 anchor*1.02(10098) 이내 → wild_card_1pct 발동, offer_1pct=9900.
|
# anchor=9900(기본). 10000 은 anchor*1.02(10098) 이내 → wild_card_1pct 발동, offer_1pct=9900.
|
||||||
out = await _run(svc, eng, [None, "확인", "예", "확인", "10000", "예", "예",
|
out = await _run(svc, eng, [None, "확인", "예", "확인", "10000", "예", "예",
|
||||||
@@ -129,7 +129,7 @@ def test_card_id_fixed_mapping_and_selection_mask():
|
|||||||
"""카드 정리 후: action_id↔카드는 테넌트 매핑으로 고정, 견적 선택은 available_mask 로 걸러진다.
|
"""카드 정리 후: action_id↔카드는 테넌트 매핑으로 고정, 견적 선택은 available_mask 로 걸러진다.
|
||||||
(구 인덱스 방식 폐기 — selected[action_id] 인덱싱은 견적마다 action_id 의미가 달라져 Q-table 오염.)"""
|
(구 인덱스 방식 폐기 — selected[action_id] 인덱싱은 견적마다 action_id 의미가 달라져 Q-table 오염.)"""
|
||||||
class _Mapper:
|
class _Mapper:
|
||||||
_m = {i: f"NGC-A{i + 1:03d}" for i in range(11)}
|
_m = {i: f"NGC-B{i + 1:03d}" for i in range(11)}
|
||||||
def get_card_id(self, a):
|
def get_card_id(self, a):
|
||||||
return self._m.get(a)
|
return self._m.get(a)
|
||||||
def get_action_id(self, num):
|
def get_action_id(self, num):
|
||||||
@@ -139,15 +139,15 @@ def test_card_id_fixed_mapping_and_selection_mask():
|
|||||||
action_space_size = 11
|
action_space_size = 11
|
||||||
eng = _Engine()
|
eng = _Engine()
|
||||||
session = ChatSession(
|
session = ChatSession(
|
||||||
session_id="00000000-0000-0000-0000-000000000001", tenant_id="ktcommerce", company_id="ktcommerce",
|
session_id="00000000-0000-0000-0000-000000000001", tenant_id="imarketkorea", company_id="imarketkorea",
|
||||||
context={"selected_nego_card_numbers": ["NGC-A003", "NGC-A008"]}, action_space_size=11,
|
context={"selected_nego_card_numbers": ["NGC-B003", "NGC-B008"]}, action_space_size=11,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ① card_id 는 고정 매핑 (선택 리스트 인덱싱 아님)
|
# ① card_id 는 고정 매핑 (선택 리스트 인덱싱 아님)
|
||||||
assert ChatService._card_id_for_action(eng, session, 0) == "NGC-A001"
|
assert ChatService._card_id_for_action(eng, session, 0) == "NGC-B001"
|
||||||
assert ChatService._card_id_for_action(eng, session, 2) == "NGC-A003"
|
assert ChatService._card_id_for_action(eng, session, 2) == "NGC-B003"
|
||||||
|
|
||||||
# ② 선택은 mask 로 — NGC-A003(action 2), NGC-A008(action 7) 만 pickable
|
# ② 선택은 mask 로 — NGC-B003(action 2), NGC-B008(action 7) 만 pickable
|
||||||
mask = ChatService._selection_mask(eng, session)
|
mask = ChatService._selection_mask(eng, session)
|
||||||
assert mask is not None and mask[2] and mask[7]
|
assert mask is not None and mask[2] and mask[7]
|
||||||
assert not mask[0] and not mask[5] and mask.sum() == 2
|
assert not mask[0] and not mask[5] and mask.sum() == 2
|
||||||
@@ -164,13 +164,13 @@ def test_card_id_fixed_mapping_and_selection_mask():
|
|||||||
|
|
||||||
def test_default_1pct_wildcard_still_runs_without_selected_wildcard():
|
def test_default_1pct_wildcard_still_runs_without_selected_wildcard():
|
||||||
"""1% 인하는 기본 제공 카드라 DB 견적에서 와일드카드를 선택하지 않아도 발동한다."""
|
"""1% 인하는 기본 제공 카드라 DB 견적에서 와일드카드를 선택하지 않아도 발동한다."""
|
||||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce")
|
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||||
repo = ScriptRepository(cfg, _TENANTS_DIR)
|
repo = ScriptRepository(cfg, _TENANTS_DIR)
|
||||||
engine = ChatEngine(repo, rq_type="재협상")
|
engine = ChatEngine(repo, rq_type="재협상")
|
||||||
session = ChatSession(
|
session = ChatSession(
|
||||||
session_id="00000000-0000-0000-0000-000000000002",
|
session_id="00000000-0000-0000-0000-000000000002",
|
||||||
tenant_id="ktcommerce",
|
tenant_id="imarketkorea",
|
||||||
company_id="ktcommerce",
|
company_id="imarketkorea",
|
||||||
step="가격협상_확인",
|
step="가격협상_확인",
|
||||||
action_space_size=0,
|
action_space_size=0,
|
||||||
context={
|
context={
|
||||||
@@ -188,13 +188,13 @@ def test_default_1pct_wildcard_still_runs_without_selected_wildcard():
|
|||||||
|
|
||||||
def test_budget_wildcard_requires_selected_wildcard_for_db_context():
|
def test_budget_wildcard_requires_selected_wildcard_for_db_context():
|
||||||
"""재원부족 구간은 DB 견적에서 와일드카드를 선택했을 때만 발동한다."""
|
"""재원부족 구간은 DB 견적에서 와일드카드를 선택했을 때만 발동한다."""
|
||||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce")
|
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||||
repo = ScriptRepository(cfg, _TENANTS_DIR)
|
repo = ScriptRepository(cfg, _TENANTS_DIR)
|
||||||
engine = ChatEngine(repo, rq_type="재협상")
|
engine = ChatEngine(repo, rq_type="재협상")
|
||||||
session = ChatSession(
|
session = ChatSession(
|
||||||
session_id="00000000-0000-0000-0000-000000000003",
|
session_id="00000000-0000-0000-0000-000000000003",
|
||||||
tenant_id="ktcommerce",
|
tenant_id="imarketkorea",
|
||||||
company_id="ktcommerce",
|
company_id="imarketkorea",
|
||||||
step="가격협상_확인",
|
step="가격협상_확인",
|
||||||
action_space_size=0,
|
action_space_size=0,
|
||||||
context={
|
context={
|
||||||
@@ -214,7 +214,7 @@ def test_budget_wildcard_requires_selected_wildcard_for_db_context():
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_priority_completes_without_wildcard(db_engine):
|
async def test_priority_completes_without_wildcard(db_engine):
|
||||||
reset_sessions()
|
reset_sessions()
|
||||||
eng = await _reg().get_engine("ktcommerce")
|
eng = await _reg().get_engine("imarketkorea")
|
||||||
svc = ChatService()
|
svc = ChatService()
|
||||||
# 첫 제시가가 앵커가(9900) 이하 → 우선협상 → 바로 협상완료(카드/와일드카드 없이)
|
# 첫 제시가가 앵커가(9900) 이하 → 우선협상 → 바로 협상완료(카드/와일드카드 없이)
|
||||||
out = await _run(svc, eng, [None, "확인", "예", "확인", "9800", "예",
|
out = await _run(svc, eng, [None, "확인", "예", "확인", "9800", "예",
|
||||||
@@ -237,7 +237,7 @@ async def test_tenant_brand_isolation(db_engine):
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_advance_after_end_errors(db_engine):
|
async def test_advance_after_end_errors(db_engine):
|
||||||
reset_sessions()
|
reset_sessions()
|
||||||
eng = await _reg().get_engine("ktcommerce")
|
eng = await _reg().get_engine("imarketkorea")
|
||||||
svc = ChatService()
|
svc = ChatService()
|
||||||
out = await _run(svc, eng, [None, "확인", "예", "확인", "1000", "예",
|
out = await _run(svc, eng, [None, "확인", "예", "확인", "1000", "예",
|
||||||
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."])
|
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."])
|
||||||
@@ -248,12 +248,12 @@ async def test_advance_after_end_errors(db_engine):
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_http_chat_start(client):
|
async def test_http_chat_start(client):
|
||||||
r = await client.post("/v1/chat", headers={"X-Tenant-ID": "ktcommerce"}, json={"rq_type": "재협상"})
|
r = await client.post("/v1/chat", headers={"X-Tenant-ID": "imarketkorea"}, json={"rq_type": "재협상"})
|
||||||
assert r.status_code == 200
|
assert r.status_code == 200
|
||||||
d = r.json()
|
d = r.json()
|
||||||
assert d["step"] == "서비스안내"
|
assert d["step"] == "서비스안내"
|
||||||
assert d["input_options"] == ["확인"]
|
assert d["input_options"] == ["확인"]
|
||||||
assert "데모상사 A" in d["script"]
|
assert "데모상사 B" in d["script"]
|
||||||
# 헤더 없으면 400
|
# 헤더 없으면 400
|
||||||
r2 = await client.post("/v1/chat", json={"rq_type": "재협상"})
|
r2 = await client.post("/v1/chat", json={"rq_type": "재협상"})
|
||||||
assert r2.status_code == 400
|
assert r2.status_code == 400
|
||||||
@@ -25,7 +25,7 @@ def _eng():
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_session_persists_and_resumes_across_instances(db_engine):
|
async def test_session_persists_and_resumes_across_instances(db_engine):
|
||||||
reg = _eng()
|
reg = _eng()
|
||||||
eng = await reg.get_engine("ktcommerce")
|
eng = await reg.get_engine("imarketkorea")
|
||||||
|
|
||||||
# 인스턴스 1: 협상 시작 + 몇 턴 진행 (컨텍스트는 DB 조회 — 행이 없으므로 기본값 폴백)
|
# 인스턴스 1: 협상 시작 + 몇 턴 진행 (컨텍스트는 DB 조회 — 행이 없으므로 기본값 폴백)
|
||||||
svc1 = ChatService()
|
svc1 = ChatService()
|
||||||
@@ -51,19 +51,19 @@ async def test_session_persists_and_resumes_across_instances(db_engine):
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_session_company_scoped(db_engine):
|
async def test_session_company_scoped(db_engine):
|
||||||
reg = _eng()
|
reg = _eng()
|
||||||
eng = await reg.get_engine("ktcommerce")
|
eng = await reg.get_engine("imarketkorea")
|
||||||
svc = ChatService()
|
svc = ChatService()
|
||||||
r = await svc.chat(eng, Req_Chat())
|
r = await svc.chat(eng, Req_Chat())
|
||||||
sid = r.session_id
|
sid = r.session_id
|
||||||
|
|
||||||
# 자사(ktcommerce)로는 조회됨
|
# 자사(imarketkorea)로는 조회됨
|
||||||
assert await ChatSessionRepository(eng.company_id).get(sid) is not None
|
assert await ChatSessionRepository(eng.company_id).get(sid) is not None
|
||||||
# 타테넌트(imarketkorea) company_id 로는 조회 안 됨 (격리)
|
# 타테넌트 company_id 로는 조회 안 됨 (격리)
|
||||||
assert await ChatSessionRepository("imarketkorea").get(sid) is None
|
assert await ChatSessionRepository("00000000-0000-0000-0000-0000000000aa").get(sid) is None
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_get_none_for_missing(db_engine):
|
async def test_get_none_for_missing(db_engine):
|
||||||
repo = ChatSessionRepository("ktcommerce")
|
repo = ChatSessionRepository("imarketkorea")
|
||||||
assert await repo.get(None) is None
|
assert await repo.get(None) is None
|
||||||
assert await repo.get("00000000-0000-0000-0000-000000000000") is None
|
assert await repo.get("00000000-0000-0000-0000-000000000000") is None
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
"""Phase 2 표현층 검증 — ScriptNaturalizer (LLM 카드 멘트 자연화).
|
||||||
|
|
||||||
|
원칙 검증: LLM 은 말만 다듬고 숫자는 절대 만들지 않는다.
|
||||||
|
① 치환자 보존 성공 경로 ② 치환자 누락/추가 → 폐기 ③ 새 숫자 → 폐기
|
||||||
|
④ 타임아웃/예외 → 폐기(폴백) ⑤ 상황 라벨은 정성(수치 미노출)
|
||||||
|
⑥ 챗 플로우: llm.enabled=True 면 카드 멘트가 자연화본으로, 실패 시 원본으로.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from negotiation.chat.service.script_naturalizer import ScriptNaturalizer, build_situation
|
||||||
|
|
||||||
|
_TEMPLATE = "제안해 주신 **{input_price}원**, 감사합니다. 한 번 더 검토해 가격을 제안해 주시겠어요?"
|
||||||
|
|
||||||
|
|
||||||
|
def _fake(reply):
|
||||||
|
"""llm_call 더블 — 고정 응답."""
|
||||||
|
def call(messages):
|
||||||
|
return {"script": reply}
|
||||||
|
return call
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_naturalize_success_preserves_placeholders():
|
||||||
|
nat = ScriptNaturalizer(llm_call=_fake(
|
||||||
|
"긍정적으로 검토 중입니다. 다만 **{input_price}원**은 조정 여지가 있어 보입니다. 재제안 부탁드립니다."))
|
||||||
|
out = await nat.naturalize(_TEMPLATE, situation={"라운드": "초반 조율"}, tone=2, strategy=1)
|
||||||
|
assert out and "{input_price}" in out and out != _TEMPLATE
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_naturalize_rejects_missing_placeholder():
|
||||||
|
nat = ScriptNaturalizer(llm_call=_fake("가격 재검토 부탁드립니다.")) # 치환자 삭제됨
|
||||||
|
assert await nat.naturalize(_TEMPLATE) is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_naturalize_rejects_added_placeholder():
|
||||||
|
nat = ScriptNaturalizer(llm_call=_fake("{input_price}원과 {secret_discount}까지 드리겠습니다."))
|
||||||
|
assert await nat.naturalize(_TEMPLATE) is None # 원본에 없던 변수 환각
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_naturalize_rejects_new_digits():
|
||||||
|
nat = ScriptNaturalizer(llm_call=_fake("{input_price}원에서 5% 더 인하해 주시면 즉시 계약하겠습니다."))
|
||||||
|
assert await nat.naturalize(_TEMPLATE) is None # LLM 이 만든 숫자(5) 금지
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_naturalize_rejects_dropped_emphasis_markers():
|
||||||
|
"""고객사가 지정한 볼드/색 마커를 LLM 이 떨어뜨리면 폐기 → 원본(스타일 보존) 폴백."""
|
||||||
|
tmpl = "제안해 주신 **{input_price}원**, {{강조|재검토}} 부탁드립니다."
|
||||||
|
# 볼드·색 마커를 모두 지운 재작성 → 검증 실패
|
||||||
|
nat = ScriptNaturalizer(llm_call=_fake("제안해 주신 {input_price}원, 재검토 부탁드립니다."))
|
||||||
|
assert await nat.naturalize(tmpl) is None
|
||||||
|
# 마커를 그대로 유지한 재작성 → 통과
|
||||||
|
nat = ScriptNaturalizer(llm_call=_fake("제시하신 **{input_price}원** 관련, {{강조|재검토}}를 요청드립니다."))
|
||||||
|
out = await nat.naturalize(tmpl)
|
||||||
|
assert out and out.count("**") == 2 and "{{강조|" in out
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_naturalize_timeout_falls_back():
|
||||||
|
def slow(messages):
|
||||||
|
import time
|
||||||
|
time.sleep(0.5)
|
||||||
|
return {"script": _TEMPLATE}
|
||||||
|
nat = ScriptNaturalizer(llm_call=slow, timeout_seconds=0.05)
|
||||||
|
assert await nat.naturalize(_TEMPLATE) is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_naturalize_exception_falls_back():
|
||||||
|
def boom(messages):
|
||||||
|
raise RuntimeError("LLM down")
|
||||||
|
nat = ScriptNaturalizer(llm_call=boom)
|
||||||
|
assert await nat.naturalize(_TEMPLATE) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_situation_is_qualitative_only():
|
||||||
|
"""상황 라벨에 실제 수치가 노출되지 않는다(숫자 환각 차단의 전제)."""
|
||||||
|
ctx = {"round": 2, "input_price": 10200, "anchor_price": 9900, "target_price": 10000, "item_price": 11000}
|
||||||
|
s = build_situation(ctx)
|
||||||
|
assert s["라운드"] == "초반 조율"
|
||||||
|
assert s["가격구간"] == "목표 상회(추가 인하 필요)"
|
||||||
|
joined = str(s)
|
||||||
|
for n in ("10200", "9900", "10000", "11000"):
|
||||||
|
assert n not in joined # 수치 미노출
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_chat_flow_uses_naturalized_script_when_llm_enabled(db_engine):
|
||||||
|
"""llm.enabled=True + 자격증명 존재 시 가격협상 카드 멘트가 자연화본(치환 완료)으로 나온다."""
|
||||||
|
from router.v1.chat.protocol import Req_Chat
|
||||||
|
from services.chat_service import ChatService, reset_sessions
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
from tenancy.registry import TenantEngineRegistry
|
||||||
|
|
||||||
|
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||||
|
reset_sessions()
|
||||||
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||||
|
eng = await reg.get_engine("imarketkorea")
|
||||||
|
eng.config.llm.enabled = True # 테넌트 게이트 on
|
||||||
|
|
||||||
|
svc = ChatService()
|
||||||
|
svc._naturalizer = ScriptNaturalizer(llm_call=_fake(
|
||||||
|
"【자연화】 제시해 주신 **{input_price}원** 잘 검토했습니다. 초반 조율 단계이니 한 걸음 더 부탁드립니다."))
|
||||||
|
# 자격증명 게이트 우회(테스트 환경에 키가 없어도 동작 검증)
|
||||||
|
orig_available = ScriptNaturalizer.available
|
||||||
|
ScriptNaturalizer.available = staticmethod(lambda: True)
|
||||||
|
try:
|
||||||
|
sid = None
|
||||||
|
for ui in [None, "확인", "예", "확인", "11000", "예"]:
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input=ui))
|
||||||
|
sid = r.session_id
|
||||||
|
assert r.step == "가격협상" and r.card_id
|
||||||
|
assert r.script.startswith("【자연화】") # LLM 재작성본 사용
|
||||||
|
assert "11000" in r.script # 치환은 엔진이 수행(숫자 정확)
|
||||||
|
assert "{input_price}" not in r.script # 치환 완료
|
||||||
|
finally:
|
||||||
|
ScriptNaturalizer.available = orig_available
|
||||||
|
eng.config.llm.enabled = False
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_chat_flow_falls_back_to_template_on_llm_failure(db_engine):
|
||||||
|
"""LLM 실패 시 카드 원본 멘트로 폴백 — 협상은 절대 멈추지 않는다."""
|
||||||
|
from router.v1.chat.protocol import Req_Chat
|
||||||
|
from services.chat_service import ChatService, reset_sessions
|
||||||
|
from tenancy.config_loader import TenantConfigLoader
|
||||||
|
from tenancy.registry import TenantEngineRegistry
|
||||||
|
|
||||||
|
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||||
|
reset_sessions()
|
||||||
|
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||||
|
eng = await reg.get_engine("imarketkorea")
|
||||||
|
eng.config.llm.enabled = True
|
||||||
|
|
||||||
|
def boom(messages):
|
||||||
|
raise RuntimeError("LLM down")
|
||||||
|
svc = ChatService()
|
||||||
|
svc._naturalizer = ScriptNaturalizer(llm_call=boom)
|
||||||
|
orig_available = ScriptNaturalizer.available
|
||||||
|
ScriptNaturalizer.available = staticmethod(lambda: True)
|
||||||
|
try:
|
||||||
|
sid = None
|
||||||
|
for ui in [None, "확인", "예", "확인", "11000", "예"]:
|
||||||
|
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input=ui))
|
||||||
|
sid = r.session_id
|
||||||
|
assert r.step == "가격협상" and r.card_id
|
||||||
|
assert r.script and "11000" in r.script # 원본 템플릿 + 치환으로 정상 응답
|
||||||
|
finally:
|
||||||
|
ScriptNaturalizer.available = orig_available
|
||||||
|
eng.config.llm.enabled = False
|
||||||
@@ -20,7 +20,7 @@ _TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__fi
|
|||||||
_FORBIDDEN = re.compile(r"kt\s*commerce|케이티|커머스|nego-?wiz", re.IGNORECASE)
|
_FORBIDDEN = re.compile(r"kt\s*commerce|케이티|커머스|nego-?wiz", re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
def _repo(tenant_id="ktcommerce"):
|
def _repo(tenant_id="imarketkorea"):
|
||||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load(tenant_id)
|
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load(tenant_id)
|
||||||
return ScriptRepository(cfg, _TENANTS_DIR)
|
return ScriptRepository(cfg, _TENANTS_DIR)
|
||||||
|
|
||||||
@@ -65,11 +65,9 @@ def test_cleanroom_no_proprietary_brand_in_any_resource():
|
|||||||
|
|
||||||
|
|
||||||
def test_brand_substitution_per_tenant():
|
def test_brand_substitution_per_tenant():
|
||||||
kt = _repo("ktcommerce").get_step("서비스안내", "재협상")
|
|
||||||
im = _repo("imarketkorea").get_step("서비스안내", "재협상")
|
im = _repo("imarketkorea").get_step("서비스안내", "재협상")
|
||||||
assert "데모상사 A" in kt["script"] and "Negosium" in kt["script"]
|
assert "데모상사 B" in im["script"] and "Negosium" in im["script"]
|
||||||
assert "데모상사 B" in im["script"]
|
assert "{company_name}" not in im["script"] # 치환 완료
|
||||||
assert "{company_name}" not in kt["script"] # 치환 완료
|
|
||||||
|
|
||||||
|
|
||||||
def test_variable_substitution_and_missing_kept():
|
def test_variable_substitution_and_missing_kept():
|
||||||
@@ -103,12 +101,16 @@ async def test_resolve_card_script_file_mode_default():
|
|||||||
repo = _repo()
|
repo = _repo()
|
||||||
assert repo._config.cards.source_type == "file"
|
assert repo._config.cards.source_type == "file"
|
||||||
# action 0 파일 멘트가 변수 치환되어 나온다 (DB 무접근)
|
# action 0 파일 멘트가 변수 치환되어 나온다 (DB 무접근)
|
||||||
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800})
|
out = await repo.resolve_card_script(0, "NGC-B001", {"input_price": 9800})
|
||||||
assert out and "9800" in out
|
assert out and "9800" in out
|
||||||
|
|
||||||
|
|
||||||
class _FakeCardRepo:
|
from negotiation.cards.ports.card_script_port import ICardScriptRepository
|
||||||
"""ICardScriptRepository 더블 — DB 없이 카드코드→멘트 매핑만 흉내(세션 인자 무시)."""
|
|
||||||
|
|
||||||
|
class _FakeCardRepo(ICardScriptRepository):
|
||||||
|
"""ICardScriptRepository 더블 — DB 없이 카드코드→멘트 매핑만 흉내(세션 인자 무시).
|
||||||
|
포트 상속으로 get_card_by_number 기본 구현(메타 None)을 물려받는다."""
|
||||||
|
|
||||||
def __init__(self, by_number: dict):
|
def __init__(self, by_number: dict):
|
||||||
self._by = by_number
|
self._by = by_number
|
||||||
@@ -121,9 +123,9 @@ class _FakeCardRepo:
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_resolve_card_script_db_mode_prefers_db(monkeypatch):
|
async def test_resolve_card_script_db_mode_prefers_db(monkeypatch):
|
||||||
"""source_type='backoffice_db': card.nego_cards.script(정본)를 파일보다 우선 사용 + 마커 보존."""
|
"""source_type='backoffice_db': card.nego_cards.script(정본)를 파일보다 우선 사용 + 마커 보존."""
|
||||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce")
|
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||||
cfg.cards.source_type = "backoffice_db"
|
cfg.cards.source_type = "backoffice_db"
|
||||||
fake = _FakeCardRepo({"NGC-A001": "DB 편집 멘트 **{input_price}원** 검토 중입니다."})
|
fake = _FakeCardRepo({"NGC-B001": "DB 편집 멘트 **{input_price}원** 검토 중입니다."})
|
||||||
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
|
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
|
||||||
|
|
||||||
# execute_lambda 를 세션 없이 콜백만 실행하도록 대체(순수 단위검증)
|
# execute_lambda 를 세션 없이 콜백만 실행하도록 대체(순수 단위검증)
|
||||||
@@ -132,14 +134,14 @@ async def test_resolve_card_script_db_mode_prefers_db(monkeypatch):
|
|||||||
from negotiation.chat.service import script_repository as _sr
|
from negotiation.chat.service import script_repository as _sr
|
||||||
monkeypatch.setattr(_sr.DB_SESSION_MNG, "execute_lambda", _fake_lambda)
|
monkeypatch.setattr(_sr.DB_SESSION_MNG, "execute_lambda", _fake_lambda)
|
||||||
|
|
||||||
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800})
|
out = await repo.resolve_card_script(0, "NGC-B001", {"input_price": 9800})
|
||||||
assert out == "DB 편집 멘트 **9800원** 검토 중입니다." # DB 우선 + 마커(**) 불투명 보존 + 변수 치환
|
assert out == "DB 편집 멘트 **9800원** 검토 중입니다." # DB 우선 + 마커(**) 불투명 보존 + 변수 치환
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_resolve_card_script_db_mode_falls_back_to_file(monkeypatch):
|
async def test_resolve_card_script_db_mode_falls_back_to_file(monkeypatch):
|
||||||
"""DB 에 해당 카드 멘트가 없으면 파일(scripts_cards.json)로 폴백."""
|
"""DB 에 해당 카드 멘트가 없으면 파일(scripts_cards.json)로 폴백."""
|
||||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce")
|
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||||
cfg.cards.source_type = "backoffice_db"
|
cfg.cards.source_type = "backoffice_db"
|
||||||
fake = _FakeCardRepo({}) # DB 미보유
|
fake = _FakeCardRepo({}) # DB 미보유
|
||||||
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
|
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
|
||||||
@@ -149,14 +151,14 @@ async def test_resolve_card_script_db_mode_falls_back_to_file(monkeypatch):
|
|||||||
from negotiation.chat.service import script_repository as _sr
|
from negotiation.chat.service import script_repository as _sr
|
||||||
monkeypatch.setattr(_sr.DB_SESSION_MNG, "execute_lambda", _fake_lambda)
|
monkeypatch.setattr(_sr.DB_SESSION_MNG, "execute_lambda", _fake_lambda)
|
||||||
|
|
||||||
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800})
|
out = await repo.resolve_card_script(0, "NGC-B001", {"input_price": 9800})
|
||||||
assert out and "9800" in out # 파일 폴백 멘트
|
assert out and "9800" in out # 파일 폴백 멘트
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_resolve_card_script_prefer_db_for_selected_cards(monkeypatch):
|
async def test_resolve_card_script_prefer_db_for_selected_cards(monkeypatch):
|
||||||
"""견적에서 선택된 백오피스 카드 번호는 file 모드여도 DB 멘트를 우선한다."""
|
"""견적에서 선택된 백오피스 카드 번호는 file 모드여도 DB 멘트를 우선한다."""
|
||||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce")
|
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||||
assert cfg.cards.source_type == "file"
|
assert cfg.cards.source_type == "file"
|
||||||
fake = _FakeCardRepo({"2": "선택 카드 DB 멘트 **{input_price}원**"})
|
fake = _FakeCardRepo({"2": "선택 카드 DB 멘트 **{input_price}원**"})
|
||||||
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
|
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
|
||||||
|
|||||||
@@ -9,9 +9,9 @@
|
|||||||
|
|
||||||
실행:
|
실행:
|
||||||
cd agent
|
cd agent
|
||||||
APP_ENV=local python -m tools.console_demo --tenant ktcommerce # 기본 시나리오
|
APP_ENV=local python -m tools.console_demo --tenant imarketkorea # 기본 시나리오
|
||||||
APP_ENV=local python -m tools.console_demo --tenant imarketkorea --no-db # DB 로깅 없이
|
APP_ENV=local python -m tools.console_demo --tenant imarketkorea --no-db # DB 로깅 없이
|
||||||
APP_ENV=local python -m tools.console_demo --tenant ktcommerce --interactive
|
APP_ENV=local python -m tools.console_demo --tenant imarketkorea --interactive
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
@@ -74,7 +74,7 @@ def _scenario():
|
|||||||
async def run(tenant_id: str, use_db: bool, interactive: bool):
|
async def run(tenant_id: str, use_db: bool, interactive: bool):
|
||||||
loader = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0)
|
loader = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0)
|
||||||
if not loader.is_registered(tenant_id):
|
if not loader.is_registered(tenant_id):
|
||||||
print(f"[!] 미등록 테넌트: {tenant_id}. 등록된 테넌트: ktcommerce, imarketkorea, _base")
|
print(f"[!] 미등록 테넌트: {tenant_id}. 등록된 테넌트: imarketkorea, _base")
|
||||||
return
|
return
|
||||||
registry = TenantEngineRegistry(loader=loader)
|
registry = TenantEngineRegistry(loader=loader)
|
||||||
engine = await registry.get_engine(tenant_id)
|
engine = await registry.get_engine(tenant_id)
|
||||||
@@ -172,7 +172,7 @@ def _interactive_turns():
|
|||||||
|
|
||||||
def main():
|
def main():
|
||||||
ap = argparse.ArgumentParser(description="협상 의사결정 루프 콘솔 데모 (P0~P4)")
|
ap = argparse.ArgumentParser(description="협상 의사결정 루프 콘솔 데모 (P0~P4)")
|
||||||
ap.add_argument("--tenant", default="ktcommerce", help="테넌트 id (ktcommerce|imarketkorea)")
|
ap.add_argument("--tenant", default="imarketkorea", help="테넌트 id (imarketkorea|_base)")
|
||||||
ap.add_argument("--no-db", action="store_true", help="DB 로깅 비활성화")
|
ap.add_argument("--no-db", action="store_true", help="DB 로깅 비활성화")
|
||||||
ap.add_argument("--interactive", action="store_true", help="턴마다 직접 입력")
|
ap.add_argument("--interactive", action="store_true", help="턴마다 직접 입력")
|
||||||
args = ap.parse_args()
|
args = ap.parse_args()
|
||||||
|
|||||||
@@ -58,6 +58,21 @@ class suppliers(MAIN_BASE):
|
|||||||
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
|
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):
|
class items(MAIN_BASE):
|
||||||
# partner.items (상품).
|
# partner.items (상품).
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -123,6 +138,7 @@ class sessions(MAIN_BASE):
|
|||||||
reject_reason = Column(String(255), nullable=True) # 거절 사유
|
reject_reason = Column(String(255), nullable=True) # 거절 사유
|
||||||
reject_price = Column(BigInteger, nullable=True) # 거절 시 제시가(원)
|
reject_price = Column(BigInteger, nullable=True) # 거절 시 제시가(원)
|
||||||
reject_delivery_type = Column(SmallInteger, 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)
|
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 시 자동 갱신)
|
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")) # 소프트 삭제 여부
|
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
|
||||||
@@ -183,6 +199,34 @@ class quotation_settings(MAIN_BASE):
|
|||||||
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
|
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):
|
class chats(MAIN_BASE):
|
||||||
# negotiation.chats (협상 채팅 메시지 로그). session 1 : N chats. (session_id, seq) 유니크.
|
# negotiation.chats (협상 채팅 메시지 로그). session 1 : N chats. (session_id, seq) 유니크.
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from sqlalchemy import asc, desc, select, update
|
|||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import chats, items, sessions
|
from common.database.model.models import chats, items, sessions, nego_cards, wild_cards
|
||||||
from common.enums import ErrorType, SessionStatus
|
from common.enums import ErrorType, SessionStatus
|
||||||
from common.logger import LOG
|
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:
|
async def update_last_offer_price(self, cdb: AsyncSession, session_id, price: int) -> ErrorType:
|
||||||
pass
|
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):
|
class ChatCRUD(IChatCRUD):
|
||||||
async def list_by_session(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, list]:
|
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)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, None
|
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(
|
async def finalize_session(
|
||||||
self, cdb: AsyncSession, session_id, status: int,
|
self, cdb: AsyncSession, session_id, status: int,
|
||||||
bid_price: Optional[int] = None, reject_reason: Optional[str] = None, reject_price: Optional[int] = None,
|
bid_price: Optional[int] = None, reject_reason: Optional[str] = None, reject_price: Optional[int] = None,
|
||||||
|
|||||||
@@ -41,6 +41,10 @@ class ISessionCRUD(ABC):
|
|||||||
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
|
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def update_session_custom(self, cdb: AsyncSession, session_id, supplier_id, custom: dict) -> ErrorType:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class SessionCRUD(ISessionCRUD):
|
class SessionCRUD(ISessionCRUD):
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -86,6 +90,7 @@ class SessionCRUD(ISessionCRUD):
|
|||||||
items.name,
|
items.name,
|
||||||
items.model_name,
|
items.model_name,
|
||||||
items.manufacturer,
|
items.manufacturer,
|
||||||
|
sessions.custom,
|
||||||
)
|
)
|
||||||
.join(items, items.item_id == sessions.item_id)
|
.join(items, items.item_id == sessions.item_id)
|
||||||
.join(quotations, quotations.qt_id == sessions.quotation_id)
|
.join(quotations, quotations.qt_id == sessions.quotation_id)
|
||||||
@@ -173,3 +178,16 @@ class SessionCRUD(ISessionCRUD):
|
|||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED
|
return ErrorType.DB_RUN_FAILED
|
||||||
|
|
||||||
|
async def 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 sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import 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.enums import ErrorType, TokenType
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from common.utils.gtime import GTime
|
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]:
|
async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, str]:
|
||||||
pass
|
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
|
@abstractmethod
|
||||||
async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType:
|
async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType:
|
||||||
pass
|
pass
|
||||||
@@ -117,6 +125,43 @@ class UserCRUD(IUserCRUD):
|
|||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, None
|
return ErrorType.DB_RUN_FAILED, None
|
||||||
|
|
||||||
|
async def get_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:
|
async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType:
|
||||||
try:
|
try:
|
||||||
query = (
|
query = (
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from fastapi import APIRouter, Depends, Request
|
from fastapi import APIRouter, Depends, Path, Request
|
||||||
from fastapi.security import HTTPAuthorizationCredentials
|
from fastapi.security import HTTPAuthorizationCredentials
|
||||||
|
|
||||||
from common.models.gmodel import UserInfo
|
from common.models.gmodel import UserInfo
|
||||||
@@ -20,6 +20,7 @@ from .protocol import (
|
|||||||
Res_Me,
|
Res_Me,
|
||||||
Res_PopupStatus,
|
Res_PopupStatus,
|
||||||
Res_RefreshToken,
|
Res_RefreshToken,
|
||||||
|
Res_SessionBranding,
|
||||||
)
|
)
|
||||||
|
|
||||||
# 라우터(MVC 의 컨트롤러). 요청 검증 -> service 호출 -> RemoveNoneResponse 반환만 담당.
|
# 라우터(MVC 의 컨트롤러). 요청 검증 -> service 호출 -> RemoveNoneResponse 반환만 담당.
|
||||||
@@ -106,3 +107,16 @@ async def hide_popup(
|
|||||||
service: AuthService = Depends(),
|
service: AuthService = Depends(),
|
||||||
):
|
):
|
||||||
return RemoveNoneResponse(await service.hide_popup(user_info, credentials.credentials, req.popup_type))
|
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_id: str = Field("", description="소속 공급사 uuid")
|
||||||
supplier_name: str = Field("", description="공급사명")
|
supplier_name: str = Field("", description="공급사명")
|
||||||
role: int = Field(0, description="권한 코드 1=user, 2=manager (UserRole)")
|
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):
|
class Res_Logout(Res_WebPacketProtocol):
|
||||||
@@ -64,3 +66,9 @@ class Req_HidePopup(AuthProtocol):
|
|||||||
|
|
||||||
class Res_HidePopup(Res_WebPacketProtocol):
|
class Res_HidePopup(Res_WebPacketProtocol):
|
||||||
pass
|
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)")
|
||||||
@@ -77,6 +77,7 @@ class Res_ChatInit(Res_WebPacketProtocol):
|
|||||||
item_min_order_quantity: str = Field("", description="최소 주문 수량")
|
item_min_order_quantity: str = Field("", description="최소 주문 수량")
|
||||||
item_vat_yn: Optional[bool] = Field(None, description="VAT 포함 여부(미설정 시 null)")
|
item_vat_yn: Optional[bool] = Field(None, description="VAT 포함 여부(미설정 시 null)")
|
||||||
item_delivery_fee_yn: Optional[bool] = Field(None, description="배송비 포함 여부(미설정 시 null)")
|
item_delivery_fee_yn: Optional[bool] = Field(None, description="배송비 포함 여부(미설정 시 null)")
|
||||||
|
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 기존 입력값(sessions.custom). 재진입 시 폼 프리필용")
|
||||||
|
|
||||||
|
|
||||||
# 대화 히스토리(재진입 복원)
|
# 대화 히스토리(재진입 복원)
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ class ListItem(WebPacketProtocol):
|
|||||||
item_name: str = Field("", description="상품명")
|
item_name: str = Field("", description="상품명")
|
||||||
model_name: str = Field("", description="모델명")
|
model_name: str = Field("", description="모델명")
|
||||||
maker_name: str = Field("", description="제조사")
|
maker_name: str = Field("", description="제조사")
|
||||||
|
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 값(sessions.custom). 미입력이면 빈 dict")
|
||||||
|
|
||||||
|
|
||||||
class Res_SessionList(Res_WebPacketProtocol):
|
class Res_SessionList(Res_WebPacketProtocol):
|
||||||
@@ -33,3 +34,11 @@ class Req_Reject(WebPacketProtocol):
|
|||||||
|
|
||||||
class Res_Reject(Res_WebPacketProtocol):
|
class Res_Reject(Res_WebPacketProtocol):
|
||||||
session_id: str = Field("", description="거부 처리된 세션 uuid")
|
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")
|
||||||
@@ -6,7 +6,7 @@ from fastapi.security import HTTPAuthorizationCredentials
|
|||||||
from common.models.gmodel import UserInfo
|
from common.models.gmodel import UserInfo
|
||||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, security
|
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, security
|
||||||
from services.negotiation_service import NegotiationService
|
from services.negotiation_service import NegotiationService
|
||||||
from .protocol import Req_Reject, Res_Participate, Res_Reject, Res_SessionList
|
from .protocol import Req_ExtraInfo, Req_Reject, Res_ExtraInfo, Res_Participate, Res_Reject, Res_SessionList
|
||||||
|
|
||||||
router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={404: {"description": "Not found"}})
|
router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={404: {"description": "Not found"}})
|
||||||
|
|
||||||
@@ -61,3 +61,19 @@ async def reject(
|
|||||||
service: NegotiationService = Depends(),
|
service: NegotiationService = Depends(),
|
||||||
):
|
):
|
||||||
return RemoveNoneResponse(await service.reject(user_info, credentials.credentials, session_id, req.reject_reason))
|
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))
|
||||||
@@ -18,6 +18,7 @@ from router.v1.auth.protocol import (
|
|||||||
Res_Me,
|
Res_Me,
|
||||||
Res_PopupStatus,
|
Res_PopupStatus,
|
||||||
Res_RefreshToken,
|
Res_RefreshToken,
|
||||||
|
Res_SessionBranding,
|
||||||
)
|
)
|
||||||
from router.v1.validator.dependencies import CreateAccessToken, CreateRefreshToken, GetHashedPW, VerifyPW
|
from router.v1.validator.dependencies import CreateAccessToken, CreateRefreshToken, GetHashedPW, VerifyPW
|
||||||
|
|
||||||
@@ -250,6 +251,34 @@ class AuthService:
|
|||||||
res.supplier_id = info.supplier_id
|
res.supplier_id = info.supplier_id
|
||||||
res.supplier_name = info.supplier_name
|
res.supplier_name = info.supplier_name
|
||||||
res.role = info.role
|
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
|
return res
|
||||||
|
|
||||||
async def popup_status(self, user_info: UserInfo, access_token: str) -> Res_PopupStatus:
|
async def popup_status(self, user_info: UserInfo, access_token: str) -> Res_PopupStatus:
|
||||||
|
|||||||
@@ -103,13 +103,18 @@ class ChatService:
|
|||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@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 는 전용 컬럼에도 적재.
|
# 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(
|
return chats(
|
||||||
chat_id=uuid.uuid4(), session_id=sess.session_id, seq=seq,
|
chat_id=uuid.uuid4(), session_id=sess.session_id, seq=seq,
|
||||||
sender=ChatSender.BOT.value,
|
sender=ChatSender.BOT.value,
|
||||||
target_price=int(sess.target_price or 0),
|
target_price=int(sess.target_price or 0),
|
||||||
indicator_value=turn.indicator_value,
|
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={
|
meta={
|
||||||
"script": turn.script, "step": turn.step, "client_step": turn.client_step,
|
"script": turn.script, "step": turn.step, "client_step": turn.client_step,
|
||||||
"input_mode": turn.input_mode, "input_options": turn.input_options,
|
"input_mode": turn.input_mode, "input_options": turn.input_options,
|
||||||
@@ -204,6 +209,8 @@ class ChatService:
|
|||||||
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
|
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
await self._ensure_in_progress(sess, quote)
|
||||||
|
|
||||||
res.session_id = str(sess.session_id)
|
res.session_id = str(sess.session_id)
|
||||||
res.session_status = sess.status
|
res.session_status = sess.status
|
||||||
res.quotation_id = str(sess.quotation_id)
|
res.quotation_id = str(sess.quotation_id)
|
||||||
@@ -221,8 +228,36 @@ class ChatService:
|
|||||||
res.item_min_order_quantity = item.moq or ""
|
res.item_min_order_quantity = item.moq or ""
|
||||||
res.item_vat_yn = item.vat_yn
|
res.item_vat_yn = item.vat_yn
|
||||||
res.item_delivery_fee_yn = item.delivery_fee_yn
|
res.item_delivery_fee_yn = item.delivery_fee_yn
|
||||||
|
res.custom = sess.custom or {}
|
||||||
return res
|
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 -------------------------------------------------------
|
# ---- messages -------------------------------------------------------
|
||||||
async def messages(self, user_info: UserInfo, access_token: str, session_id_str: str) -> Res_ChatMessages:
|
async def messages(self, user_info: UserInfo, access_token: str, session_id_str: str) -> Res_ChatMessages:
|
||||||
res = Res_ChatMessages()
|
res = Res_ChatMessages()
|
||||||
@@ -239,6 +274,15 @@ class ChatService:
|
|||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
return res
|
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 (재진입 시 인사 메시지 보존)
|
# 비어 있고 협상중이면 agent 오프닝 한 턴을 seed (재진입 시 인사 메시지 보존)
|
||||||
if not rows and sess.status == SessionStatus.IN_PROGRESS.value:
|
if not rows and sess.status == SessionStatus.IN_PROGRESS.value:
|
||||||
opening = await self._seed_opening(sess)
|
opening = await self._seed_opening(sess)
|
||||||
@@ -371,8 +415,27 @@ class ChatService:
|
|||||||
# 유저 미입력 가격 타결 케이스 — 마지막 유저 제시가와 다를 수 있다).
|
# 유저 미입력 가격 타결 케이스 — 마지막 유저 제시가와 다를 수 있다).
|
||||||
summary = await self._build_summary(sess, quote, item, final_price, turn.settled_price or last_price)
|
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+거부사유·제시가). 한 트랜잭션.
|
# 봇 메시지 + 종료 시 확정(성공=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)]
|
funcs = [lambda s: self.chat_crud.insert_message(s, bot_msg)]
|
||||||
# 가격 입력 턴 → 마지막 제시가를 봇 메시지 저장과 같은 트랜잭션으로 갱신.
|
# 가격 입력 턴 → 마지막 제시가를 봇 메시지 저장과 같은 트랜잭션으로 갱신.
|
||||||
# 앵커링 표본 판정의 "가격 흔적"(가격을 써낸 협상만 집계 — 중간 이탈해도 실패로 측정 가능).
|
# 앵커링 표본 판정의 "가격 흔적"(가격을 써낸 협상만 집계 — 중간 이탈해도 실패로 측정 가능).
|
||||||
|
|||||||
@@ -4,11 +4,12 @@ from datetime import datetime, timezone
|
|||||||
from fastapi import Depends
|
from fastapi import Depends
|
||||||
|
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import sessions
|
from common.database.model.models import chats, sessions
|
||||||
from common.enums import DBWRType, ErrorType, QuotationStatus, SessionStatus
|
from common.enums import DBWRType, ErrorType, QuotationStatus, SessionStatus
|
||||||
from common.models.gmodel import UserInfo
|
from common.models.gmodel import UserInfo
|
||||||
|
from crud.chat_crud import ChatCRUD, IChatCRUD
|
||||||
from crud.session_crud import ISessionCRUD, SessionCRUD
|
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, Res_ExtraInfo, Res_Participate, Res_Reject, Res_SessionList
|
||||||
from services.auth_service import AuthService
|
from services.auth_service import AuthService
|
||||||
|
|
||||||
|
|
||||||
@@ -18,9 +19,18 @@ class NegotiationService:
|
|||||||
- 목록은 로그인 유저의 supplier_id 로만 조회한다.
|
- 목록은 로그인 유저의 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.auth = auth
|
||||||
self.session_crud = session_crud
|
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) -> Res_SessionList:
|
||||||
res = Res_SessionList()
|
res = Res_SessionList()
|
||||||
@@ -65,6 +75,7 @@ class NegotiationService:
|
|||||||
item_name=r[6] or "",
|
item_name=r[6] or "",
|
||||||
model_name=r[7] or "",
|
model_name=r[7] or "",
|
||||||
maker_name=r[8] or "",
|
maker_name=r[8] or "",
|
||||||
|
custom=r[9] or {},
|
||||||
)
|
)
|
||||||
for r in rows
|
for r in rows
|
||||||
]
|
]
|
||||||
@@ -73,6 +84,66 @@ class NegotiationService:
|
|||||||
res.page_size = page_size
|
res.page_size = page_size
|
||||||
return res
|
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
|
||||||
|
|
||||||
|
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):
|
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) 을 반환한다.
|
성공 시 (SUCCESS, sess, quote), 실패 시 (err_type, None, None) 을 반환한다.
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
# negosium 서버: http://localhost:9300/docs
|
# negosium 서버: http://localhost:9300/docs
|
||||||
# negosium 프론트: http://localhost:3300
|
# negosium 프론트: http://localhost:3300
|
||||||
# negodata 서버: http://localhost:9400/docs
|
# negodata 서버: http://localhost:9400/docs
|
||||||
|
# 솔루션 랜딩: http://localhost:3100
|
||||||
# agent 서버: http://localhost:9500/docs
|
# agent 서버: http://localhost:9500/docs
|
||||||
# anchoring 배치: 포트 없음 — 상주 스케줄러(격주 토 00:00 KST), docker logs anchoring 으로 확인
|
# anchoring 배치: 포트 없음 — 상주 스케줄러(격주 토 00:00 KST), docker logs anchoring 으로 확인
|
||||||
#
|
#
|
||||||
@@ -38,6 +39,9 @@ services:
|
|||||||
RELOAD: "1" # uvicorn --reload 활성 → 소스 저장 시 자동 재기동(재빌드 불필요)
|
RELOAD: "1" # uvicorn --reload 활성 → 소스 저장 시 자동 재기동(재빌드 불필요)
|
||||||
SCHEDULER_ENABLED: "1" # 마감 크론 활성(단일 워커라 중복 없음). 운영 다중 워커면 1개 프로세스에서만 1
|
SCHEDULER_ENABLED: "1" # 마감 크론 활성(단일 워커라 중복 없음). 운영 다중 워커면 1개 프로세스에서만 1
|
||||||
PYTHONUNBUFFERED: "1" # 컨테이너 로그 실시간 출력(stdout 버퍼링 끔)
|
PYTHONUNBUFFERED: "1" # 컨테이너 로그 실시간 출력(stdout 버퍼링 끔)
|
||||||
|
# ── LPS(인터넷 최저가) 연동 — 미설정이면 연동 비활성으로 조용히 동작 ──
|
||||||
|
LPS_DB_HOST: host.docker.internal # lps_db 읽기전용(수집 배치·조회 API)
|
||||||
|
LPS_BASE_URL: http://host.docker.internal:9600 # 검색요청 enqueue. lps-api 컨테이너 사용 시 http://lps-api:9600
|
||||||
volumes:
|
volumes:
|
||||||
- ./negodata/backend:/app # 호스트 소스 = 컨테이너 코드. 이게 있어야 수정이 즉시 반영됨
|
- ./negodata/backend:/app # 호스트 소스 = 컨테이너 코드. 이게 있어야 수정이 즉시 반영됨
|
||||||
ports:
|
ports:
|
||||||
@@ -57,6 +61,17 @@ services:
|
|||||||
- /app/node_modules
|
- /app/node_modules
|
||||||
restart: unless-stopped
|
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 스키마 사용).
|
# 협상 에이전트 (negosium_db 공유, learning 스키마 사용).
|
||||||
agent:
|
agent:
|
||||||
build: ./agent
|
build: ./agent
|
||||||
@@ -64,6 +79,7 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
APP_ENV: local
|
APP_ENV: local
|
||||||
DB_HOST: host.docker.internal # 컨테이너→호스트 DB (config.local.toml의 127.0.0.1 override)
|
DB_HOST: host.docker.internal # 컨테이너→호스트 DB (config.local.toml의 127.0.0.1 override)
|
||||||
|
OPENAI_API_KEY: ${OPENAI_API_KEY:-} # LLM 키 passthrough (호스트 env/.env → 컨테이너). 빈 값이면 toml 폴백
|
||||||
ports:
|
ports:
|
||||||
- "9500:9500"
|
- "9500:9500"
|
||||||
extra_hosts:
|
extra_hosts:
|
||||||
@@ -112,3 +128,90 @@ services:
|
|||||||
options:
|
options:
|
||||||
max-size: "10m"
|
max-size: "10m"
|
||||||
max-file: "5"
|
max-file: "5"
|
||||||
|
|
||||||
|
# ── LPS (인터넷 최저가 검색) ──────────────────────────────────
|
||||||
|
# API(요청 접수, lean) + 워커(크롤, 헤드풀 Chromium+Xvfb). DB 는 외부(host.docker.internal).
|
||||||
|
# 이미지엔 시크릿이 없다(example config 로 빌드) — 실값은 아래 env 로 주입.
|
||||||
|
# 시크릿 값은 리포 루트 .env 파일에 채운다(.env.example 참고, .env 는 미커밋).
|
||||||
|
lps-api:
|
||||||
|
build:
|
||||||
|
context: ./lps
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
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}
|
||||||
|
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 근처로 상향
|
||||||
|
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
|
||||||
|
DB_HOST: host.docker.internal
|
||||||
|
DB_USER: ${LPS_DB_USER:-postgres}
|
||||||
|
DB_PASSWORD: ${LPS_DB_PASSWORD:-postgres}
|
||||||
|
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-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
|
||||||
|
labels:
|
||||||
|
autoheal: "true" # 하트비트 HEALTHCHECK 실패(행/좀비) 시 autoheal 이 재시작
|
||||||
|
restart: unless-stopped
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options: { max-size: "10m", max-file: "5" }
|
||||||
|
|
||||||
|
# HEALTHCHECK 실패 컨테이너 자동 재시작 — compose 의 restart 는 '프로세스 종료'만 다루고
|
||||||
|
# unhealthy 는 표시만 하므로, autoheal 라벨 붙은 컨테이너(lps-api/lps-worker)를 감시해 재시작한다.
|
||||||
|
# docker.sock 마운트 = 도커 제어 권한이므로 신뢰 환경에서만 사용.
|
||||||
|
autoheal:
|
||||||
|
image: willfarrell/autoheal:latest
|
||||||
|
container_name: autoheal
|
||||||
|
environment:
|
||||||
|
AUTOHEAL_CONTAINER_LABEL: autoheal
|
||||||
|
volumes:
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
restart: unless-stopped
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options: { max-size: "10m", max-file: "5" }
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
lps-profiles:
|
||||||
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/png" href="/bot.png" />
|
<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>
|
<title>AI 가격 협상 솔루션</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import type {
|
|||||||
LogoutResponse,
|
LogoutResponse,
|
||||||
MeResponse,
|
MeResponse,
|
||||||
PopupStatusResponse,
|
PopupStatusResponse,
|
||||||
|
SessionBrandingResponse,
|
||||||
} from './auth.type'
|
} from './auth.type'
|
||||||
|
|
||||||
export const authApi = {
|
export const authApi = {
|
||||||
@@ -26,6 +27,12 @@ export const authApi = {
|
|||||||
return res.data
|
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 필요) */
|
/** GET /v1/auth/me — 현재 로그인 유저 정보 (access token 필요) */
|
||||||
me: async (): Promise<MeResponse> => {
|
me: async (): Promise<MeResponse> => {
|
||||||
const res = await http.get<MeResponse>('/v1/auth/me')
|
const res = await http.get<MeResponse>('/v1/auth/me')
|
||||||
|
|||||||
@@ -54,6 +54,28 @@ export interface RefreshTokenResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- 내 정보 (GET /v1/auth/me) -------------------------------------------
|
// --- 내 정보 (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'
|
||||||
|
}
|
||||||
|
|
||||||
export interface MeResponse {
|
export interface MeResponse {
|
||||||
result: ApiResult
|
result: ApiResult
|
||||||
su_id: string
|
su_id: string
|
||||||
@@ -62,6 +84,8 @@ export interface MeResponse {
|
|||||||
supplier_id: string
|
supplier_id: string
|
||||||
supplier_name: string
|
supplier_name: string
|
||||||
role: number
|
role: number
|
||||||
|
branding?: Branding
|
||||||
|
session_fields?: SessionField[]
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- 로그아웃 -------------------------------------------------------------
|
// --- 로그아웃 -------------------------------------------------------------
|
||||||
@@ -94,6 +118,8 @@ export interface AuthUser {
|
|||||||
supplierId: string
|
supplierId: string
|
||||||
supplierName: string
|
supplierName: string
|
||||||
role: number
|
role: number
|
||||||
|
branding: Branding
|
||||||
|
sessionFields: SessionField[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export function toAuthUser(res: MeResponse): AuthUser {
|
export function toAuthUser(res: MeResponse): AuthUser {
|
||||||
@@ -104,5 +130,7 @@ export function toAuthUser(res: MeResponse): AuthUser {
|
|||||||
supplierId: res.supplier_id,
|
supplierId: res.supplier_id,
|
||||||
supplierName: res.supplier_name,
|
supplierName: res.supplier_name,
|
||||||
role: res.role,
|
role: res.role,
|
||||||
|
branding: res.branding ?? {},
|
||||||
|
sessionFields: res.session_fields ?? [],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,6 +46,7 @@ export interface ChatInitResponse {
|
|||||||
item_min_order_quantity?: string
|
item_min_order_quantity?: string
|
||||||
item_vat_yn?: boolean
|
item_vat_yn?: boolean
|
||||||
item_delivery_fee_yn?: boolean
|
item_delivery_fee_yn?: boolean
|
||||||
|
custom?: Record<string, unknown>
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ChatMessagesResponse {
|
export interface ChatMessagesResponse {
|
||||||
@@ -98,6 +99,7 @@ export function mapInit(r: ChatInitResponse): ChatInitData {
|
|||||||
item_delivery_fee_yn:
|
item_delivery_fee_yn:
|
||||||
r.item_delivery_fee_yn == null ? '' : r.item_delivery_fee_yn ? '배송비포함' : '배송비별도',
|
r.item_delivery_fee_yn == null ? '' : r.item_delivery_fee_yn ? '배송비포함' : '배송비별도',
|
||||||
item_min_order_quantity: r.item_min_order_quantity ?? '',
|
item_min_order_quantity: r.item_min_order_quantity ?? '',
|
||||||
|
custom: r.custom ?? {},
|
||||||
item_lead_time: r.item_lead_time ?? '',
|
item_lead_time: r.item_lead_time ?? '',
|
||||||
item_spec: r.item_spec ?? '',
|
item_spec: r.item_spec ?? '',
|
||||||
quotation_memo: r.quotation_memo ?? '',
|
quotation_memo: r.quotation_memo ?? '',
|
||||||
|
|||||||
@@ -2,5 +2,5 @@
|
|||||||
export { negotiationApi } from './negotiation.api'
|
export { negotiationApi } from './negotiation.api'
|
||||||
export { negotiationKeys } from './negotiation.keys'
|
export { negotiationKeys } from './negotiation.keys'
|
||||||
export { useSessionListQuery } from './negotiation.queries'
|
export { useSessionListQuery } from './negotiation.queries'
|
||||||
export { useParticipateMutation, useRejectMutation } from './negotiation.mutations'
|
export { useParticipateMutation, useRejectMutation, useSaveExtraInfoMutation } from './negotiation.mutations'
|
||||||
export * from './negotiation.type'
|
export * from './negotiation.type'
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
// 협상 엔드포인트 호출 함수 (순수 HTTP 레이어, React 의존 없음).
|
// 협상 엔드포인트 호출 함수 (순수 HTTP 레이어, React 의존 없음).
|
||||||
import { http } from '@/apis/http'
|
import { http } from '@/apis/http'
|
||||||
import type {
|
import type {
|
||||||
|
ExtraInfoRequest,
|
||||||
|
ExtraInfoResponse,
|
||||||
ParticipateResponse,
|
ParticipateResponse,
|
||||||
RejectRequest,
|
RejectRequest,
|
||||||
RejectResponse,
|
RejectResponse,
|
||||||
@@ -31,4 +33,13 @@ export const negotiationApi = {
|
|||||||
)
|
)
|
||||||
return res.data
|
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 { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import { negotiationApi } from './negotiation.api'
|
import { negotiationApi } from './negotiation.api'
|
||||||
import { negotiationKeys } from './negotiation.keys'
|
import { negotiationKeys } from './negotiation.keys'
|
||||||
import type { RejectRequest } from './negotiation.type'
|
import type { ExtraInfoRequest, RejectRequest } from './negotiation.type'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 협상 세션 참여: 성공 시 세션 목록 캐시를 무효화해 상태를 갱신한다.
|
* 협상 세션 참여: 성공 시 세션 목록 캐시를 무효화해 상태를 갱신한다.
|
||||||
@@ -30,3 +30,17 @@ 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() })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -55,6 +55,7 @@ export interface SessionListItem {
|
|||||||
item_name: string
|
item_name: string
|
||||||
model_name: string
|
model_name: string
|
||||||
maker_name: string
|
maker_name: string
|
||||||
|
custom: Record<string, unknown> // 협상완료 부가정보(sessions.custom). 미입력이면 {}
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SessionListResponse {
|
export interface SessionListResponse {
|
||||||
@@ -65,6 +66,15 @@ export interface SessionListResponse {
|
|||||||
page_size: number
|
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) ----------------
|
// --- 참여 (POST /v1/negotiation/sessions/{id}/participate) ----------------
|
||||||
export interface ParticipateResponse {
|
export interface ParticipateResponse {
|
||||||
result: ApiResult
|
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'
|
export type ButtonSize = 'sm' | 'md' | 'lg'
|
||||||
|
|
||||||
const base =
|
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 +
|
interactive +
|
||||||
' focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ' +
|
' focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ' +
|
||||||
'disabled:pointer-events-none disabled:opacity-50'
|
'disabled:pointer-events-none disabled:opacity-50'
|
||||||
|
|
||||||
const variantClass: Record<ButtonVariant, string> = {
|
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',
|
secondary: 'bg-secondary text-secondary-foreground',
|
||||||
outline: 'border border-input bg-background',
|
outline: 'border border-border bg-background text-foreground',
|
||||||
// 투명 배경이라 brightness 무효 → bg 하이라이트
|
// 투명 배경이라 brightness 무효 → bg 하이라이트
|
||||||
ghost: 'hover:bg-accent hover:text-accent-foreground',
|
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> = {
|
const sizeClass: Record<ButtonSize, string> = {
|
||||||
|
|||||||
@@ -18,13 +18,13 @@ export function ErrorPage({
|
|||||||
}: ErrorPageProps) {
|
}: ErrorPageProps) {
|
||||||
return (
|
return (
|
||||||
<div className="flex h-full w-full items-center justify-center">
|
<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 flex-col items-center gap-5 p-12">
|
||||||
<div className="flex size-20 items-center justify-center rounded-full bg-destructive/10">
|
<div className="flex size-16 items-center justify-center rounded-full bg-destructive/10">
|
||||||
<AlertTriangle className="size-10 text-destructive" />
|
<AlertTriangle className="size-8 text-destructive" />
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col items-center gap-2 text-center">
|
<div className="flex flex-col items-center gap-1.5 text-center">
|
||||||
<p className="title-2 text-destructive">{message}</p>
|
<p className="text-lg font-bold text-neutral-90">{message}</p>
|
||||||
<p className="body-1 text-neutral-70">{description}</p>
|
<p className="text-sm text-neutral-60">{description}</p>
|
||||||
</div>
|
</div>
|
||||||
{onRetry && (
|
{onRetry && (
|
||||||
<Button variant="primary" size="lg" onClick={onRetry}>
|
<Button variant="primary" size="lg" onClick={onRetry}>
|
||||||
|
|||||||
@@ -6,9 +6,9 @@ export function Input({ type = 'text', className, ...props }: ComponentProps<'in
|
|||||||
<input
|
<input
|
||||||
type={type}
|
type={type}
|
||||||
className={cn(
|
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',
|
'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',
|
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import { type ComponentProps } from 'react'
|
import { type ComponentProps } from 'react'
|
||||||
import { cn } from '@/lib'
|
import { cn } from '@/lib'
|
||||||
import logoColor from '@/assets/imarketkorea-logo.png'
|
import logoDefault from '@/assets/negotium-logo.png'
|
||||||
import logoWhite from '@/assets/imarketkorea-logo-white.png'
|
|
||||||
|
|
||||||
export type LogoVariant = 'color' | 'white'
|
export type LogoVariant = 'color' | 'white'
|
||||||
export type LogoSize = 'sm' | 'md' | 'lg'
|
export type LogoSize = 'sm' | 'md' | 'lg'
|
||||||
|
|
||||||
|
// 기본 브랜드(회사 설정 미지정 시). 회사 로고가 오면 logoUrl 이 이 값을 덮는다.
|
||||||
const sources: Record<LogoVariant, string> = {
|
const sources: Record<LogoVariant, string> = {
|
||||||
color: logoColor,
|
color: logoDefault,
|
||||||
white: logoWhite,
|
white: logoDefault,
|
||||||
}
|
}
|
||||||
|
|
||||||
const sizes: Record<LogoSize, { img: string; text: string; gap: string }> = {
|
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' },
|
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'> {
|
export interface LogoProps extends Omit<ComponentProps<'div'>, 'children'> {
|
||||||
variant?: LogoVariant
|
variant?: LogoVariant
|
||||||
size?: LogoSize
|
size?: LogoSize
|
||||||
withText?: boolean
|
withText?: boolean
|
||||||
alt?: string
|
alt?: string
|
||||||
|
/** 회사 브랜딩 오버라이드(companies.settings.branding). 없으면 기본 iMarket Korea. */
|
||||||
|
serviceName?: string
|
||||||
|
logoUrl?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Logo({
|
export function Logo({
|
||||||
variant = 'color',
|
variant = 'color',
|
||||||
size = 'md',
|
size = 'md',
|
||||||
withText = true,
|
withText = true,
|
||||||
alt = 'iMarket Korea',
|
alt = 'NEGOTIUM',
|
||||||
|
serviceName,
|
||||||
|
logoUrl,
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: LogoProps) {
|
}: LogoProps) {
|
||||||
const s = sizes[size]
|
const s = sizes[size]
|
||||||
|
const name = serviceName || 'negotium'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn('flex items-center', s.gap, className)} {...props}>
|
<div className={cn('flex items-center', s.gap, className)} {...props}>
|
||||||
<img
|
<img
|
||||||
src={sources[variant]}
|
src={logoUrl || sources[variant]}
|
||||||
alt={withText ? '' : alt}
|
alt={withText ? '' : (serviceName || alt)}
|
||||||
className={cn('w-auto select-none', s.img)}
|
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)}>
|
<span className={cn('font-bold tracking-[-0.4px] text-foreground', s.text)}>
|
||||||
iMarket Korea
|
{name}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Button, Input } from '@/components'
|
import { Button, Input } from '@/components'
|
||||||
import { useLogin } from '@/features/auth/hooks/useLogin'
|
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() {
|
export function LoginForm() {
|
||||||
const {
|
const {
|
||||||
|
|||||||
@@ -6,7 +6,10 @@ import { tokenStorage } from '@/apis'
|
|||||||
// 토큰이 있으나 만료/폐기된 경우는 요청 시 인터셉터가 세션을 종료시킨다.
|
// 토큰이 있으나 만료/폐기된 경우는 요청 시 인터셉터가 세션을 종료시킨다.
|
||||||
export function RequireAuth({ children }: { children: ReactNode }) {
|
export function RequireAuth({ children }: { children: ReactNode }) {
|
||||||
if (!tokenStorage.hasToken()) {
|
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}</>
|
return <>{children}</>
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useNavigate } from 'react-router'
|
import { useNavigate } from 'react-router'
|
||||||
|
import { LogOut } from 'lucide-react'
|
||||||
import { useLogoutMutation, useMeQuery } from '@/apis'
|
import { useLogoutMutation, useMeQuery } from '@/apis'
|
||||||
import { Button } from '@/components'
|
import { cn, interactive } from '@/lib'
|
||||||
|
|
||||||
// 사이드바 하단: 공급사명 + 로그아웃
|
// 사이드바 하단: 공급사명 + 로그아웃
|
||||||
export function SidebarFooter() {
|
export function SidebarFooter() {
|
||||||
@@ -15,19 +16,23 @@ export function SidebarFooter() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex w-full h-[60px] py-3 px-8 gap-3 items-center">
|
<div className="flex w-full shrink-0 items-center gap-2 border-t border-border px-6 py-3">
|
||||||
<div className="flex-1 flex items-center min-w-0 text-sm text-foreground">
|
<div className="min-w-0 flex-1">
|
||||||
<span className="truncate">{user?.supplierName ?? '-'}</span>
|
<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>
|
</div>
|
||||||
<Button
|
<button
|
||||||
variant="secondary"
|
type="button"
|
||||||
size="sm"
|
|
||||||
className="w-[61px] px-2 rounded-[4px] text-xs flex-shrink-0"
|
|
||||||
onClick={handleLogout}
|
onClick={handleLogout}
|
||||||
disabled={logout.isPending}
|
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>
|
</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 { LoginForm } from '@/features/auth/components/LoginForm'
|
||||||
export { SidebarFooter } from '@/features/auth/components/SidebarFooter'
|
export { SidebarFooter } from '@/features/auth/components/SidebarFooter'
|
||||||
export { RequireAuth } from '@/features/auth/components/RequireAuth'
|
export { RequireAuth } from '@/features/auth/components/RequireAuth'
|
||||||
|
export { usePreLoginBranding } from '@/features/auth/hooks/usePreLoginBranding'
|
||||||
@@ -1,40 +1,59 @@
|
|||||||
import { useEffect, useRef, memo } from 'react'
|
import { useEffect, useRef, memo, type RefObject } from 'react'
|
||||||
import { cn } from '@/lib'
|
import { useMeQuery } from '@/apis'
|
||||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||||
import type { ChatMessage as ChatMessageType } from '@/features/chat/types'
|
import type { ChatMessage as ChatMessageType } from '@/features/chat/types'
|
||||||
import { renderEmphasis } from '@/features/chat/lib/emphasis'
|
import { renderEmphasis } from '@/features/chat/lib/emphasis'
|
||||||
import { Indicator } from '@/features/chat/components/templates/Indicator'
|
import { Indicator } from '@/features/chat/components/templates/Indicator'
|
||||||
import { Summary } from '@/features/chat/components/templates/Summary'
|
import { Summary } from '@/features/chat/components/templates/Summary'
|
||||||
|
import { ExtraInfoForm } from '@/features/chat/components/templates/ExtraInfoForm'
|
||||||
import { BidSummary } from '@/features/chat/components/templates/BidSummary'
|
import { BidSummary } from '@/features/chat/components/templates/BidSummary'
|
||||||
import { RejectRSP } from '@/features/chat/components/templates/RejectRSP'
|
import { RejectRSP } from '@/features/chat/components/templates/RejectRSP'
|
||||||
import { RejectCM } from '@/features/chat/components/templates/RejectCM'
|
import { RejectCM } from '@/features/chat/components/templates/RejectCM'
|
||||||
|
|
||||||
|
const AI_LABEL = '아이마켓코리아 (구매 MD)'
|
||||||
|
|
||||||
export function ChatMessage() {
|
export function ChatMessage() {
|
||||||
|
const scrollRef = useRef<HTMLDivElement | null>(null)
|
||||||
return (
|
return (
|
||||||
<div className="flex-1 w-full min-h-0 pr-[16px]">
|
<div className="flex-1 w-full min-h-0">
|
||||||
{/* pt-[64px]: 첫 메시지를 우측 협상절차 카드 상단과 맞추되, 스크롤 시 여백도 함께 밀려 올라가도록 스크롤 컨테이너 안쪽에 둔다 */}
|
{/* lg:pt-[64px]: 첫 메시지를 우측 협상절차 카드 상단과 맞추는 값 — 그 카드가 없는 lg 미만에선
|
||||||
<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
|
||||||
|
ref={scrollRef}
|
||||||
|
className="chat-scroll h-full overflow-y-auto flex flex-col pt-0 lg:pt-[64px] 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>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function ChatList() {
|
function ChatList({ scrollRef }: { scrollRef: RefObject<HTMLDivElement | null> }) {
|
||||||
const bottomRef = useRef<HTMLDivElement | null>(null)
|
const isFirstRef = useRef(true)
|
||||||
const chats = useChatStore((s) => s.messages)
|
const chats = useChatStore((s) => s.messages)
|
||||||
const isLoading = useChatStore((s) => s.isLoading)
|
const isLoading = useChatStore((s) => s.isLoading)
|
||||||
|
|
||||||
// 메시지 추가/타이핑 표시 시 항상 맨 아래로 스크롤
|
// 메시지 추가/타이핑 표시 시 항상 맨 아래로 스크롤.
|
||||||
|
// 스크롤 컨테이너를 직접 내린다 — scrollIntoView 는 요약/부가정보 폼처럼 큰 블록이 뒤늦게
|
||||||
|
// 레이아웃되면 애니메이션 도중 목표 위치가 밀려 중간에 멈춘다.
|
||||||
|
// 진입 첫 렌더는 즉시(auto) — 히스토리를 복원하며 위에서부터 훑어 내려가는 연출을 막는다.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
|
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])
|
}, [chats, isLoading])
|
||||||
|
|
||||||
if (!chats || chats.length === 0) {
|
if (!chats || chats.length === 0) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center justify-center h-full">
|
<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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -42,22 +61,22 @@ function ChatList() {
|
|||||||
return (
|
return (
|
||||||
<div className="flex flex-col w-full">
|
<div className="flex flex-col w-full">
|
||||||
{chats.map((message, index) => (
|
{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 />}
|
{isLoading && <TypingBubble />}
|
||||||
<div ref={bottomRef} />
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// agent 응답을 기다리는 동안(협상 중) 대화 흐름에 표시하는 타이핑 인디케이터.
|
// agent 응답을 기다리는 동안(협상 중) 대화 흐름에 표시하는 타이핑 인디케이터(AI 말풍선 톤).
|
||||||
function TypingBubble() {
|
function TypingBubble() {
|
||||||
return (
|
return (
|
||||||
<div className="mb-[56px] pt-[36px]" aria-label="협상 중" role="status">
|
<div className="mb-6 flex flex-col items-start gap-1.5" aria-label="협상 중" role="status">
|
||||||
<div className="inline-flex items-center gap-[6px]">
|
<span className="text-xs font-bold text-neutral-80">{AI_LABEL}</span>
|
||||||
<span className="size-[8px] rounded-full bg-neutral-50 animate-bounce [animation-delay:-0.3s]" />
|
<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-[8px] rounded-full bg-neutral-50 animate-bounce [animation-delay:-0.15s]" />
|
<span className="size-2 rounded-full bg-brand-500 animate-bounce [animation-delay:-0.3s]" />
|
||||||
<span className="size-[8px] rounded-full bg-neutral-50 animate-bounce" />
|
<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>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
@@ -65,50 +84,52 @@ function TypingBubble() {
|
|||||||
|
|
||||||
const MessageItem = memo(function MessageItem({
|
const MessageItem = memo(function MessageItem({
|
||||||
message,
|
message,
|
||||||
isFirst,
|
|
||||||
messages,
|
messages,
|
||||||
currentIndex,
|
currentIndex,
|
||||||
}: {
|
}: {
|
||||||
message: ChatMessageType
|
message: ChatMessageType
|
||||||
isFirst: boolean
|
|
||||||
messages: ChatMessageType[]
|
messages: ChatMessageType[]
|
||||||
currentIndex: number
|
currentIndex: number
|
||||||
}) {
|
}) {
|
||||||
const isBot = message.sender === 'bot'
|
const isBot = message.sender === 'bot'
|
||||||
|
|
||||||
// 직전이 reject 폼이면 사용자 답변은 숨기고 구분선만 표시
|
// 직전이 reject 폼이면 사용자 답변 말풍선은 숨긴다(폼 자체가 답변을 담고 있음)
|
||||||
if (!isBot && currentIndex > 0) {
|
if (!isBot && currentIndex > 0) {
|
||||||
const prev = messages[currentIndex - 1]
|
const prev = messages[currentIndex - 1]
|
||||||
if (prev?.bot_chat_type === 'rejectRSP' || prev?.bot_chat_type === 'rejectCM') {
|
if (prev?.bot_chat_type === 'rejectRSP' || prev?.bot_chat_type === 'rejectCM') {
|
||||||
return (
|
return null
|
||||||
<>
|
|
||||||
<div className="text-right mb-[56px]" />
|
|
||||||
<div className="flex w-full bg-neutral-30 h-[1px] mb-[20px]" />
|
|
||||||
</>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 showIndicator = useChatInitStore((s) => s.wasInProgress)
|
||||||
|
const hasScript = Boolean(message.script && message.script.trim())
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mb-[56px]">
|
<div className="mb-5 animate-fade-in">
|
||||||
<div className={cn('flex flex-col', !isFirst && 'pt-[36px]')}>
|
<div className="flex flex-col items-start gap-1.5">
|
||||||
{/* 봇 스크립트의 `**굵게**` 경량 마크업 해석 (표현 규칙은 프론트 소유 — emphasis.tsx) */}
|
<span className="text-xs font-bold text-neutral-80">{AI_LABEL}</span>
|
||||||
<div className="body-1-read-r">{renderEmphasis(message.script || '')}</div>
|
{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>
|
||||||
|
|
||||||
<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 && (
|
{showIndicator && message.bot_chat_type === 'indicator' && message.indicator_value != null && (
|
||||||
<Indicator number={message.indicator_value} />
|
<Indicator number={message.indicator_value} />
|
||||||
)}
|
)}
|
||||||
{message.bot_chat_type === 'summaryRSP' && message.summary && <Summary data={message.summary} />}
|
{message.bot_chat_type === 'summaryRSP' && message.summary && (
|
||||||
|
<>
|
||||||
|
<Summary data={message.summary} />
|
||||||
|
<ExtraInfoForm />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
{message.bot_chat_type === 'summaryCM' && message.summary && (
|
{message.bot_chat_type === 'summaryCM' && message.summary && (
|
||||||
<BidSummary
|
<BidSummary
|
||||||
itemName={message.summary.item_name}
|
itemName={message.summary.item_name}
|
||||||
@@ -126,14 +147,14 @@ const BotMessage = memo(function BotMessage({ message, isFirst }: { message: Cha
|
|||||||
})
|
})
|
||||||
|
|
||||||
const UserMessage = memo(function UserMessage({ text }: { text: string }) {
|
const UserMessage = memo(function UserMessage({ text }: { text: string }) {
|
||||||
|
const { data: user } = useMeQuery()
|
||||||
|
const label = `${user?.supplierName ?? '공급사'} (나)`
|
||||||
return (
|
return (
|
||||||
<>
|
<div className="mb-5 flex flex-col items-end gap-1.5 animate-fade-in">
|
||||||
<div className="text-right mb-[56px]">
|
<span className="text-xs font-bold text-neutral-80">{label}</span>
|
||||||
<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">
|
<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}
|
{text}
|
||||||
</div>
|
|
||||||
</div>
|
</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 { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||||
import { ChatMessage } from '@/features/chat/components/ChatMessage'
|
import { ChatMessage } from '@/features/chat/components/ChatMessage'
|
||||||
import { UserButton } from '@/features/chat/components/UserButton'
|
import { UserButton } from '@/features/chat/components/UserButton'
|
||||||
|
import { MobileStepBar } from '@/features/chat/components/MobileStepBar'
|
||||||
|
|
||||||
export function ChatSection() {
|
export function ChatSection() {
|
||||||
const { userButtonConfig } = useChatStore()
|
const { userButtonConfig } = useChatStore()
|
||||||
return (
|
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 />
|
<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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -8,34 +8,33 @@ export function ItemImage() {
|
|||||||
const [isOpen, setIsOpen] = useState(false)
|
const [isOpen, setIsOpen] = useState(false)
|
||||||
|
|
||||||
return (
|
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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setIsOpen(true)}
|
onClick={() => setIsOpen(true)}
|
||||||
aria-label="이미지 크게 보기"
|
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} />
|
{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">
|
<img
|
||||||
<span className="text-neutral-00 text-base font-medium">이미지 크게 보기</span>
|
src={item_image}
|
||||||
</div>
|
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>
|
</button>
|
||||||
{isOpen && <ImageModal src={item_image} onClose={() => setIsOpen(false)} />}
|
{isOpen && <ImageModal src={item_image} onClose={() => setIsOpen(false)} />}
|
||||||
</div>
|
</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 }) {
|
function ImageModal({ src, onClose }: { src: string; onClose: () => void }) {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
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()}>
|
<div className="relative" onClick={(e) => e.stopPropagation()}>
|
||||||
{src ? (
|
{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} />
|
<ImageIcon size={96} strokeWidth={1.25} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -63,9 +62,9 @@ function ImageModal({ src, onClose }: { src: string; onClose: () => void }) {
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
aria-label="닫기"
|
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>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</div>,
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { useState, useCallback, useRef, useEffect } from 'react'
|
import { useState, useCallback, useRef, useEffect } from 'react'
|
||||||
import { createPortal } from 'react-dom'
|
import { createPortal } from 'react-dom'
|
||||||
import { cn } from '@/lib'
|
|
||||||
import { ItemImage } from '@/features/chat/components/ItemImage'
|
import { ItemImage } from '@/features/chat/components/ItemImage'
|
||||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||||
import { formatLeadTime } from '@/features/chat/lib/format'
|
import { formatLeadTime } from '@/features/chat/lib/format'
|
||||||
@@ -74,19 +73,18 @@ function ItemInfo() {
|
|||||||
const priceText = isNewItem ? '신규' : `${formatPrice(item_price)}원`
|
const priceText = isNewItem ? '신규' : `${formatPrice(item_price)}원`
|
||||||
const formattedPrice = `${priceText}(${item_vat_yn || 'VAT별도'})`
|
const formattedPrice = `${priceText}(${item_vat_yn || 'VAT별도'})`
|
||||||
|
|
||||||
const renderRow = (title: string, data: string, important = false) => {
|
const renderRow = (title: string, data: string) => {
|
||||||
const textClass = important ? 'title-3 text-neutral-90' : 'body-3 text-neutral-70'
|
|
||||||
const displayData = data || '-'
|
const displayData = data || '-'
|
||||||
return (
|
return (
|
||||||
<div className="flex items-start self-stretch gap-1 min-w-0">
|
<div className="flex items-start justify-between gap-3 self-stretch border-b border-border/60 py-2 last:border-0 min-w-0">
|
||||||
<div className={cn(textClass, 'w-[100px]')}>{title}</div>
|
<span className="shrink-0 text-[13px] text-neutral-60">{title}</span>
|
||||||
<div
|
<span
|
||||||
className={cn(textClass, 'flex-1 min-w-0 break-words break-keep cursor-default')}
|
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)}
|
onMouseEnter={(e) => displayData !== '-' && showTooltip(e, displayData)}
|
||||||
onMouseLeave={hideTooltip}
|
onMouseLeave={hideTooltip}
|
||||||
>
|
>
|
||||||
{displayData}
|
{displayData}
|
||||||
</div>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -94,31 +92,35 @@ function ItemInfo() {
|
|||||||
return (
|
return (
|
||||||
<div className="flex flex-col w-full flex-1 overflow-hidden min-h-0">
|
<div className="flex flex-col w-full flex-1 overflow-hidden min-h-0">
|
||||||
<div
|
<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)}
|
onMouseEnter={(e) => item_name && showTooltip(e, item_name)}
|
||||||
onMouseLeave={hideTooltip}
|
onMouseLeave={hideTooltip}
|
||||||
>
|
>
|
||||||
{item_name}
|
{item_name}
|
||||||
</div>
|
</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="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 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">
|
<div className="flex flex-col items-start self-stretch flex-1 gap-2 min-w-0">
|
||||||
{renderRow('상품코드', item_code, true)}
|
{renderRow('상품코드', item_code)}
|
||||||
{renderRow('단가', formattedPrice, true)}
|
{renderRow('단가', formattedPrice)}
|
||||||
{renderRow('모델명', item_model_name, true)}
|
{renderRow('모델명', item_model_name)}
|
||||||
{renderRow('제조사', item_maker_name)}
|
{renderRow('제조사', item_maker_name)}
|
||||||
{renderRow('최소주문수량', item_min_order_quantity)}
|
{renderRow('최소주문수량', item_min_order_quantity)}
|
||||||
{renderRow('리드타임', formatLeadTime(item_lead_time))}
|
{renderRow('리드타임', formatLeadTime(item_lead_time))}
|
||||||
|
|
||||||
<div className="flex items-start self-stretch gap-1 flex-[1_0]">
|
<div className="flex items-start justify-between gap-3 self-stretch py-2">
|
||||||
<div className="body-3 text-neutral-70 w-[100px]">규격</div>
|
<span className="shrink-0 text-sm text-neutral-60">규격</span>
|
||||||
<div
|
<span
|
||||||
className="body-3 text-neutral-70 self-stretch w-0 flex-[1_0] overflow-hidden whitespace-normal break-words break-keep cursor-default"
|
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)}
|
onMouseEnter={(e) => item_spec && showTooltip(e, item_spec, true)}
|
||||||
onMouseLeave={hideTooltip}
|
onMouseLeave={hideTooltip}
|
||||||
>
|
>
|
||||||
{item_spec || '-'}
|
{item_spec || '-'}
|
||||||
</div>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</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/components/menu/NegoStep'
|
||||||
|
|
||||||
|
// 모바일 전용: 협상절차를 채팅 상단에 가로 스텝바로 항상 표시한다. (데스크톱은 우측 패널 사용)
|
||||||
|
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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
import { useState, useEffect } from 'react'
|
import { useState, useEffect } from 'react'
|
||||||
|
import { Clock } from 'lucide-react'
|
||||||
|
import { cn } from '@/lib'
|
||||||
import { getTimeRemaining } from '@/features/chat/lib/remainingTime'
|
import { getTimeRemaining } from '@/features/chat/lib/remainingTime'
|
||||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||||
|
|
||||||
// 헤더의 협상 잔여 시간. 1초마다 tick 을 올려 렌더 중 남은 시간을 다시 계산한다.
|
// 헤더의 협상 잔여 시간 칩. 1초마다 tick 을 올려 렌더 중 남은 시간을 다시 계산한다.
|
||||||
export function RemainingTime() {
|
export function RemainingTime() {
|
||||||
const { quotation_end_time } = useChatInitStore()
|
const { quotation_end_time } = useChatInitStore()
|
||||||
const [, setTick] = useState(0)
|
const [, setTick] = useState(0)
|
||||||
@@ -13,6 +15,28 @@ export function RemainingTime() {
|
|||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const remaining = quotation_end_time ? getTimeRemaining(quotation_end_time) : '-'
|
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,5 +1,4 @@
|
|||||||
import { useNavigate } from 'react-router'
|
import { useNavigate } from 'react-router'
|
||||||
import { List } from 'lucide-react'
|
|
||||||
import { cn } from '@/lib'
|
import { cn } from '@/lib'
|
||||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||||
import { Percent, Price } from '@/features/chat/components/userInputs'
|
import { Percent, Price } from '@/features/chat/components/userInputs'
|
||||||
@@ -8,37 +7,28 @@ import type { UserButtonConfig } from '@/features/chat/types'
|
|||||||
|
|
||||||
// max-[1180px]: 채팅 폭이 좁아지면 버튼 패딩·최소폭 축소, 상품목록은 아이콘만 남긴다
|
// max-[1180px]: 채팅 폭이 좁아지면 버튼 패딩·최소폭 축소, 상품목록은 아이콘만 남긴다
|
||||||
const style = {
|
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:
|
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]',
|
'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-[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]',
|
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:
|
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) {
|
export function UserButton({ type, text, textList, priceErrorMessage }: UserButtonConfig) {
|
||||||
if (type === '') return null
|
if (type === '') return null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
// pr-[16px]: 채팅 스크롤 영역(ChatMessage 바깥 pr-[16px])과 오른쪽 끝 정렬
|
<div className="flex w-full justify-center overflow-x-auto px-6 py-4 max-[1180px]:px-4">
|
||||||
<div className="flex w-full pb-[52px] pr-[16px]">
|
<div className="flex justify-center">
|
||||||
<div className="grid grid-cols-[1fr_auto_1fr] items-center w-full">
|
{type === 'one-black' && <OneBlack text={text || '확인'} />}
|
||||||
<div />
|
{type === 'one-gray' && <OneGray text={text || '확인'} />}
|
||||||
<div className="flex justify-center">
|
{type === 'black-white' && <BlackWhite textList={[textList?.[0] || '예', textList?.[1] || '아니오']} />}
|
||||||
{type === 'one-black' && <OneBlack text={text || '확인'} />}
|
{type === 'percent' && <Percent />}
|
||||||
{type === 'one-gray' && <OneGray text={text || '확인'} />}
|
{type === 'three-black' && (
|
||||||
{type === 'black-white' && <BlackWhite textList={[textList?.[0] || '예', textList?.[1] || '아니오']} />}
|
<ThreeBlack textList={[textList?.[0] || '협력사배송', textList?.[1] || '지정택배배송', textList?.[2] || '픽업배송']} />
|
||||||
{type === 'percent' && <Percent />}
|
)}
|
||||||
{type === 'three-black' && (
|
{type === 'price' && <Price priceErrorMessage={priceErrorMessage} />}
|
||||||
<ThreeBlack textList={[textList?.[0] || '협력사배송', textList?.[1] || '지정택배배송', textList?.[2] || '픽업배송']} />
|
{type === 'loading' && <LoadingDots />}
|
||||||
)}
|
|
||||||
{type === 'price' && <Price priceErrorMessage={priceErrorMessage} />}
|
|
||||||
{type === 'loading' && <LoadingDots />}
|
|
||||||
</div>
|
|
||||||
<div className="flex justify-end">
|
|
||||||
<GoToList />
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
@@ -57,16 +47,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 }) {
|
function OneBlack({ text }: { text: string }) {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const sendMessage = useChatStore((s) => s.sendMessage)
|
const sendMessage = useChatStore((s) => s.sendMessage)
|
||||||
|
|||||||
@@ -1,28 +1,14 @@
|
|||||||
import { useState } from 'react'
|
// 헬프데스크 — 연락처. (안내 팝업 진입은 상단 '유의사항 및 이용방법' 섹션으로 일원화)
|
||||||
import { interactive, cn } from '@/lib'
|
|
||||||
import { ServiceGuidePopup } from '@/features/chat/components/popup/ServiceGuidePopup'
|
|
||||||
|
|
||||||
// 헬프데스크 — 이용 가이드 버튼 클릭 시 안내 팝업을 연다.
|
|
||||||
export function Contact() {
|
export function Contact() {
|
||||||
const [isOpen, setIsOpen] = useState(false)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col w-full pl-[24px] pb-[24px]">
|
<section className="w-full pt-4">
|
||||||
<div className="flex flex-col w-full gap-2">
|
<div className="border-b border-border pb-2">
|
||||||
<div className="title-5 text-neutral-80">헬프 데스크</div>
|
<span className="text-[11px] font-bold tracking-wide text-neutral-60">헬프데스크</span>
|
||||||
<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>
|
|
||||||
</div>
|
</div>
|
||||||
{isOpen && <ServiceGuidePopup onClose={() => setIsOpen(false)} />}
|
<div className="flex flex-col gap-1 pt-3 text-sm text-neutral-60">
|
||||||
</div>
|
<span>010-0000-0000</span>
|
||||||
|
<span>o2odev@o2o.kr</span>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { ChevronRight } from 'lucide-react'
|
import { ChevronRight } from 'lucide-react'
|
||||||
import { interactive, cn } from '@/lib'
|
|
||||||
import { ServiceGuidePopup } from '@/features/chat/components/popup/ServiceGuidePopup'
|
import { ServiceGuidePopup } from '@/features/chat/components/popup/ServiceGuidePopup'
|
||||||
|
|
||||||
// 유의사항 및 이용방법 — 클릭 시 안내 팝업을 연다.
|
// 유의사항 및 이용방법 — 클릭 시 안내 팝업을 연다.
|
||||||
@@ -12,13 +11,12 @@ export function Guide() {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setIsOpen(true)}
|
onClick={() => setIsOpen(true)}
|
||||||
className={cn(
|
className="flex w-full items-center justify-between border-b border-border pb-2 text-left transition-colors hover:border-neutral-40"
|
||||||
'flex w-full bg-white rounded-[28px] py-[20px] pl-[24px] pr-[16px] justify-between items-center text-left',
|
|
||||||
interactive,
|
|
||||||
)}
|
|
||||||
>
|
>
|
||||||
<span className="menu-title text-neutral-80 break-keep">유의사항 및 이용방법</span>
|
<span className="text-[11px] font-bold tracking-wide text-neutral-60 break-keep">
|
||||||
<ChevronRight size={20} className="text-neutral-70" />
|
유의사항 및 이용방법
|
||||||
|
</span>
|
||||||
|
<ChevronRight size={16} className="text-neutral-50" />
|
||||||
</button>
|
</button>
|
||||||
{isOpen && <ServiceGuidePopup onClose={() => setIsOpen(false)} />}
|
{isOpen && <ServiceGuidePopup onClose={() => setIsOpen(false)} />}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -22,39 +22,33 @@ export function MDInformation({ isOpen, setIsOpen }: Props) {
|
|||||||
if (memoArray.length === 0) return null
|
if (memoArray.length === 0) return null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col w-full min-w-[200px]">
|
<section className="w-full">
|
||||||
<div className="bg-white rounded-[28px]">
|
<button
|
||||||
<div className={cn('flex items-center w-full h-[4.75rem] px-4 pl-6', isOpen ? 'pt-6 pb-3' : 'py-6')}>
|
type="button"
|
||||||
<div className="flex items-center flex-1 justify-between">
|
aria-expanded={isOpen}
|
||||||
<div className="menu-title text-neutral-80">MD 안내사항</div>
|
onClick={() => setIsOpen(!isOpen)}
|
||||||
<button
|
className="flex w-full items-center justify-between border-b border-border pb-2"
|
||||||
type="button"
|
>
|
||||||
aria-expanded={isOpen}
|
<span className="text-[11px] font-bold tracking-wide text-neutral-60">MD 안내사항</span>
|
||||||
onClick={() => setIsOpen(!isOpen)}
|
<ChevronDown
|
||||||
className="flex items-center justify-center w-10 h-10 cursor-pointer text-neutral-70"
|
size={16}
|
||||||
>
|
className={cn('text-neutral-50 transition-transform duration-300', !isOpen && '-rotate-90')}
|
||||||
<ChevronDown size={20} className={cn('transition-transform duration-300', !isOpen && 'rotate-180')} />
|
/>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div
|
{isOpen && (
|
||||||
className={cn(
|
<div className="max-h-[220px] animate-fade-in overflow-y-auto pt-3">
|
||||||
'flex flex-col items-start gap-[19px] w-full px-6 overflow-hidden transition-all duration-300 ease-in-out',
|
<div className="flex flex-col gap-2 break-keep">
|
||||||
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')}>
|
|
||||||
{memoArray.map((item, i) => (
|
{memoArray.map((item, i) => (
|
||||||
<div key={i} className="flex items-start gap-2 body-3 text-neutral-70">
|
<div key={i} className="flex items-start gap-2 text-sm text-neutral-70">
|
||||||
<span className="flex-shrink-0">•</span>
|
<span className="shrink-0 text-neutral-50">•</span>
|
||||||
<div className="flex-1 whitespace-pre-wrap">{linkText(item)}</div>
|
<div className="flex-1 whitespace-pre-wrap">{linkText(item)}</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
</div>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,7 +57,7 @@ function linkText(text: string) {
|
|||||||
const isUrl = (s: string) => /^https?:\/\/[^\s]+$/.test(s)
|
const isUrl = (s: string) => /^https?:\/\/[^\s]+$/.test(s)
|
||||||
const parts = text.split(urlRegex)
|
const parts = text.split(urlRegex)
|
||||||
return (
|
return (
|
||||||
<div className="body-3 text-neutral-70">
|
<div className="text-sm text-neutral-70">
|
||||||
{parts.map((part, i) =>
|
{parts.map((part, i) =>
|
||||||
isUrl(part) ? (
|
isUrl(part) ? (
|
||||||
<a
|
<a
|
||||||
@@ -71,7 +65,7 @@ function linkText(text: string) {
|
|||||||
href={part}
|
href={part}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
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>
|
</a>
|
||||||
|
|||||||
@@ -1,16 +1,24 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
|
import { cn } from '@/lib'
|
||||||
import { MDInformation } from '@/features/chat/components/menu/MDInformation'
|
import { MDInformation } from '@/features/chat/components/menu/MDInformation'
|
||||||
import { NegoStep } from '@/features/chat/components/menu/NegoStep'
|
import { NegoStep } from '@/features/chat/components/menu/NegoStep'
|
||||||
import { Guide } from '@/features/chat/components/menu/Guide'
|
import { Guide } from '@/features/chat/components/menu/Guide'
|
||||||
import { Contact } from '@/features/chat/components/menu/Contact'
|
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 [isMDOpen, setIsMDOpen] = useState(true)
|
||||||
const [isStepOpen, setIsStepOpen] = 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 (
|
return (
|
||||||
<div className="flex flex-col w-[360px] max-[1350px]:w-[320px] max-[1180px]:w-[280px] h-full pt-[64px] pr-[24px]">
|
<div className={cn(wrap)}>
|
||||||
<div className="flex flex-col flex-1 gap-[28px]">
|
<div className="flex flex-1 flex-col gap-6">
|
||||||
<MDInformation isOpen={isMDOpen} setIsOpen={setIsMDOpen} />
|
<MDInformation isOpen={isMDOpen} setIsOpen={setIsMDOpen} />
|
||||||
<NegoStep isOpen={isStepOpen} setIsOpen={setIsStepOpen} />
|
<NegoStep isOpen={isStepOpen} setIsOpen={setIsStepOpen} />
|
||||||
<Guide />
|
<Guide />
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ChevronDown } from 'lucide-react'
|
import { Check, ChevronDown } from 'lucide-react'
|
||||||
import { cn } from '@/lib'
|
import { cn } from '@/lib'
|
||||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||||
|
|
||||||
@@ -7,46 +7,78 @@ interface Props {
|
|||||||
setIsOpen: (isOpen: boolean) => void
|
setIsOpen: (isOpen: boolean) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
const STEPS = ['서비스안내', '담당자확인', '협상품목안내', '가격협상', '협상종료']
|
export const STEPS = [
|
||||||
|
{ name: '서비스안내', desc: '협상 방식과 유의사항을 확인합니다.' },
|
||||||
|
{ name: '담당자확인', desc: '협상 담당자 본인 여부를 확인합니다.' },
|
||||||
|
{ name: '협상품목안내', desc: '대상 품목과 기준 단가를 확인합니다.' },
|
||||||
|
{ name: '가격협상', desc: '공급 단가를 제안하고 조율합니다.' },
|
||||||
|
{ name: '협상종료', desc: '최종 합의 후 결과를 확인합니다.' },
|
||||||
|
]
|
||||||
|
|
||||||
export function NegoStep({ isOpen, setIsOpen }: Props) {
|
export function NegoStep({ isOpen, setIsOpen }: Props) {
|
||||||
const chats = useChatStore((s) => s.messages)
|
const chats = useChatStore((s) => s.messages)
|
||||||
const currentStep = chats[chats.length - 1]?.display_step || '서비스안내'
|
const currentStep = chats[chats.length - 1]?.display_step || '서비스안내'
|
||||||
|
const currentIndex = Math.max(
|
||||||
|
0,
|
||||||
|
STEPS.findIndex((s) => s.name === currentStep),
|
||||||
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col w-full min-w-[200px]">
|
<section className="w-full">
|
||||||
<div className="bg-white rounded-[28px]">
|
<button
|
||||||
<div className={cn('flex items-center w-full h-[4.75rem] px-4 pl-6', isOpen ? 'pt-6 pb-3' : 'py-6')}>
|
type="button"
|
||||||
<div className="flex items-center flex-1 justify-between">
|
aria-expanded={isOpen}
|
||||||
<div className="menu-title text-neutral-80">협상절차</div>
|
onClick={() => setIsOpen(!isOpen)}
|
||||||
<button
|
className="flex w-full items-center justify-between border-b border-border pb-2"
|
||||||
type="button"
|
>
|
||||||
aria-expanded={isOpen}
|
<span className="text-[11px] font-bold tracking-wide text-neutral-60">협상절차</span>
|
||||||
onClick={() => setIsOpen(!isOpen)}
|
<ChevronDown
|
||||||
className="flex items-center justify-center w-10 h-10 cursor-pointer text-neutral-70"
|
size={16}
|
||||||
>
|
className={cn('text-neutral-50 transition-transform duration-300', !isOpen && '-rotate-90')}
|
||||||
<ChevronDown size={20} className={cn('transition-transform duration-300', !isOpen && 'rotate-180')} />
|
/>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div
|
{isOpen && (
|
||||||
className={cn(
|
<div className="animate-fade-in pt-4">
|
||||||
'flex flex-col items-start gap-[19px] w-full px-6 overflow-hidden transition-all duration-300 ease-in-out',
|
<div className="relative">
|
||||||
isOpen ? 'max-h-[200px] pb-8 opacity-100' : 'max-h-0 pb-0 opacity-0',
|
{/* 세로 레일 */}
|
||||||
)}
|
<span className="absolute left-[9px] top-3 bottom-3 w-0.5 bg-neutral-20" />
|
||||||
>
|
{STEPS.map((step, i) => {
|
||||||
<div className="flex flex-col gap-2 items-start self-stretch break-keep">
|
const done = i < currentIndex
|
||||||
{STEPS.map((step, i) => (
|
const current = i === currentIndex
|
||||||
<div key={step} className="flex items-start gap-2">
|
return (
|
||||||
<div className={cn('body-3 text-neutral-80', currentStep === step && 'font-bold')}>
|
<div key={step.name} className="relative flex items-start gap-3 py-1.5">
|
||||||
{i + 1}. {step}
|
<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>
|
</div>
|
||||||
</div>
|
)}
|
||||||
</div>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -3,14 +3,13 @@ import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
|||||||
|
|
||||||
// 협상 유의사항 및 서비스 이용 방법 안내 — 팝업 2종(자동 안내/메뉴 가이드)이 공유하는 본문.
|
// 협상 유의사항 및 서비스 이용 방법 안내 — 팝업 2종(자동 안내/메뉴 가이드)이 공유하는 본문.
|
||||||
// VAT/배송비 문구는 채팅 init 메타(useChatInitStore)를 읽어 상품별로 동적 표시한다.
|
// VAT/배송비 문구는 채팅 init 메타(useChatInitStore)를 읽어 상품별로 동적 표시한다.
|
||||||
// break-keep: 한국어 단어가 중간에서 잘려 줄바꿈되지 않도록 한다.
|
const bodyStyle = 'text-sm font-normal leading-relaxed text-neutral-70 break-keep'
|
||||||
const textStyle = 'text-[17px] font-normal leading-[150%] tracking-[-0.34px] text-neutral-90 break-keep'
|
|
||||||
|
|
||||||
function Bullet({ children }: { children: ReactNode }) {
|
function Bullet({ children }: { children: ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-start py-[6px]">
|
<div className="flex items-start gap-2.5 py-1.5">
|
||||||
<p className="ml-[8px] mr-[6px] flex-shrink-0">•</p>
|
<span className="mt-[7px] size-1.5 shrink-0 rounded-full bg-brand-600" />
|
||||||
<div className={`${textStyle} flex-1`}>{children}</div>
|
<div className={`${bodyStyle} flex-1`}>{children}</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -23,24 +22,26 @@ export function GuideContent() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex w-full flex-col">
|
<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>
|
||||||
|
|
||||||
<div className="flex flex-col items-start">
|
<div className={`${bodyStyle} mb-2`}>
|
||||||
<div className={`${textStyle} mb-2`}>
|
협상과 관련하여 다음 사항을 참고하여 견적에 참여해 주시기 바랍니다.
|
||||||
협상과 관련하여 다음 사항을 참고하여 견적에 참여해 주시기 바랍니다.
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
|
<div className="flex flex-col divide-y divide-border/60 rounded-xl border border-border px-4 py-1">
|
||||||
<Bullet>
|
<Bullet>
|
||||||
협상 개시는
|
협상 개시는
|
||||||
<span className="font-bold">Negosium 시스템의 협상 참여 버튼을 클릭하는 순간부터 시작</span>
|
<span className="font-semibold text-neutral-90">
|
||||||
|
Negosium 시스템의 협상 참여 버튼을 클릭하는 순간부터 시작
|
||||||
|
</span>
|
||||||
됩니다.
|
됩니다.
|
||||||
</Bullet>
|
</Bullet>
|
||||||
|
|
||||||
<Bullet>
|
<Bullet>
|
||||||
부여된 협상 시간에
|
부여된 협상 시간에
|
||||||
<span className="font-bold">
|
<span className="font-semibold text-neutral-90">
|
||||||
응찰하지 않는 경우, 협상 참여의사가 없는 것으로 간주하여 재견적으로 진행
|
응찰하지 않는 경우, 협상 참여의사가 없는 것으로 간주하여 재견적으로 진행
|
||||||
</span>
|
</span>
|
||||||
될 수 있습니다.
|
될 수 있습니다.
|
||||||
@@ -48,25 +49,23 @@ export function GuideContent() {
|
|||||||
|
|
||||||
<Bullet>
|
<Bullet>
|
||||||
협상에 입력되는 모든 가격은
|
협상에 입력되는 모든 가격은
|
||||||
<span className="font-bold text-negative">
|
<span className="font-semibold text-negative">
|
||||||
{vat} 및 {deliveryFee}
|
{vat} 및 {deliveryFee}
|
||||||
</span>
|
</span>
|
||||||
기준이며,
|
기준이며,
|
||||||
<span className="font-bold">
|
<span className="font-semibold text-neutral-90">
|
||||||
할인을 요청하는 경우 기존 공급가격에 할인율이 적용된 가격으로 환산
|
할인을 요청하는 경우 기존 공급가격에 할인율이 적용된 가격으로 환산
|
||||||
</span>
|
</span>
|
||||||
되어 제시됩니다.
|
되어 제시됩니다.
|
||||||
</Bullet>
|
</Bullet>
|
||||||
|
|
||||||
<Bullet>
|
<Bullet>
|
||||||
본 협상 결과에 대해서는 협상자와 협상대상자 간의 비밀 유지 조건으로 진행되고, 협상에서
|
본 협상 결과에 대해서는 협상자와 협상대상자 간의 비밀 유지 조건으로 진행되고, 협상에서 얻어진 결과나 내용에
|
||||||
얻어진 결과나 내용에 대해서는 당사자를 제외하고 제 3자에 공유할 수 없으며, 비밀 유지를
|
대해서는 당사자를 제외하고 제 3자에 공유할 수 없으며, 비밀 유지를 전제로 진행됩니다.
|
||||||
전제로 진행됩니다.
|
|
||||||
</Bullet>
|
</Bullet>
|
||||||
|
|
||||||
<Bullet>
|
<Bullet>
|
||||||
협상이 종결되면 특별한 사유 없이 취소 변경이 불가하니, 신중하게 협상에 참여해 주시기
|
협상이 종결되면 특별한 사유 없이 취소 변경이 불가하니, 신중하게 협상에 참여해 주시기 바랍니다.
|
||||||
바랍니다.
|
|
||||||
</Bullet>
|
</Bullet>
|
||||||
|
|
||||||
<Bullet>안내된 사항 외 부분은 기존 견적 프로세스와 동일한 부분 유의 바랍니다.</Bullet>
|
<Bullet>안내된 사항 외 부분은 기존 견적 프로세스와 동일한 부분 유의 바랍니다.</Bullet>
|
||||||
@@ -78,13 +77,12 @@ export function GuideContent() {
|
|||||||
// 하단 문의 안내 박스
|
// 하단 문의 안내 박스
|
||||||
export function GuideContactBox() {
|
export function GuideContactBox() {
|
||||||
return (
|
return (
|
||||||
<div className="flex w-full flex-col items-center gap-2 rounded-[16px] bg-neutral-10 p-6">
|
<div className="flex w-full flex-col items-center gap-1.5 rounded-xl bg-neutral-10 p-4">
|
||||||
<div className={`${textStyle} text-center`}>
|
<div className={`${bodyStyle} text-center`}>
|
||||||
기타 협상과정에서 궁금한 사항이나 문의하실 사항은 아래의 연락처로 상담을 부탁드립니다.
|
기타 협상 과정에서 궁금하거나 문의하실 사항은 아래 연락처로 상담 부탁드립니다.
|
||||||
</div>
|
</div>
|
||||||
{/* textStyle 의 font-normal 과 같은 요소에서 충돌하지 않도록 bold 는 별도 조합으로 준다 */}
|
<div className="break-keep text-center text-sm font-bold text-neutral-90">
|
||||||
<div className="break-keep text-center text-[17px] font-bold leading-[150%] tracking-[-0.34px] text-neutral-90">
|
헬프데스크 010-0000-0000 · o2odev@o2o.kr
|
||||||
헬프데스크 010-0000-0000, 이메일: o2odev@o2o.kr
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -7,19 +7,19 @@ import { GuideContent, GuideContactBox } from './GuideContent'
|
|||||||
export function ServiceGuidePopup({ onClose }: { onClose: () => void }) {
|
export function ServiceGuidePopup({ onClose }: { onClose: () => void }) {
|
||||||
return (
|
return (
|
||||||
<Modal onClose={onClose}>
|
<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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
aria-label="닫기"
|
aria-label="닫기"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
className={cn(
|
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,
|
interactive,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<X size={20} className="text-neutral-80" />
|
<X size={20} />
|
||||||
</button>
|
</button>
|
||||||
<div className="flex w-full flex-col gap-6 px-[40px]">
|
<div className="flex w-full flex-col gap-6">
|
||||||
<GuideContent />
|
<GuideContent />
|
||||||
<GuideContactBox />
|
<GuideContactBox />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ interface ServiceInfoPopupProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const buttonStyle = cn(
|
const buttonStyle = cn(
|
||||||
'flex h-[50px] w-[168px] items-center justify-center rounded-full',
|
'flex h-[46px] flex-1 sm:flex-none sm:w-[168px] items-center justify-center rounded-xl',
|
||||||
'border border-neutral-30 bg-white title-5 text-neutral-70',
|
'border border-border bg-white text-sm font-bold text-neutral-70 hover:bg-neutral-10',
|
||||||
interactive,
|
interactive,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -20,13 +20,13 @@ export function ServiceInfoPopup({ isOpen, onNeverShowAgain, onCloseToday }: Ser
|
|||||||
if (!isOpen) return null
|
if (!isOpen) return null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-[rgba(0,0,0,0.40)] p-4">
|
<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-[1000px] flex-col overflow-y-auto rounded-[24px] bg-white px-[80px] pb-[48px] pt-[56px]">
|
<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">
|
<div className="mb-6 flex w-full flex-col gap-5">
|
||||||
<GuideContent />
|
<GuideContent />
|
||||||
<GuideContactBox />
|
<GuideContactBox />
|
||||||
</div>
|
</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 type="button" className={buttonStyle} onClick={onNeverShowAgain}>
|
||||||
안내 보지 않기
|
안내 보지 않기
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { CheckCircle2 } from 'lucide-react'
|
||||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||||
|
|
||||||
interface BidSummaryProps {
|
interface BidSummaryProps {
|
||||||
@@ -8,54 +9,42 @@ interface BidSummaryProps {
|
|||||||
isVAT: boolean
|
isVAT: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
// 투찰 결과 요약 카드
|
// 투찰 결과 요약 카드 (보고서식 final-summary)
|
||||||
export function BidSummary({ itemName, itemCode, bidPrice, deliveryType, isVAT }: BidSummaryProps) {
|
export function BidSummary({ itemName, itemCode, bidPrice, deliveryType, isVAT }: BidSummaryProps) {
|
||||||
|
const priceStr = (bidPrice || 0).toLocaleString()
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-4">
|
<div className="w-full rounded-2xl border-2 border-brand-light bg-white p-5 shadow-md">
|
||||||
<h1 className="headline-3 text-neutral-90">투찰 결과 요약</h1>
|
<div className="mb-4 flex items-center gap-2">
|
||||||
<BidItem title="상품명" value={itemName || '-'} />
|
<CheckCircle2 className="size-5 text-success" />
|
||||||
<BidItem title="상품 코드" value={itemCode || '-'} />
|
<h3 className="text-sm font-bold text-neutral-90">투찰 결과 요약</h3>
|
||||||
<BidPrice title="투찰 가격" number={bidPrice || 0} isVAT={isVAT} />
|
|
||||||
<BidItem title="배송형태" value={deliveryType || '-'} />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function BidItem({ title, value }: { title: string; value: string }) {
|
|
||||||
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>
|
</div>
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function BidPrice({ number, isVAT, title }: { number: number; isVAT: boolean; title: string }) {
|
<div className="divide-y divide-border/60 rounded-xl border border-border">
|
||||||
const numberString = number.toLocaleString()
|
<Row label="상품명" value={itemName || '-'} />
|
||||||
return (
|
<Row label="상품 코드" value={itemCode || '-'} mono />
|
||||||
<div className="flex items-start gap-2">
|
<div className="flex items-start justify-between gap-3 px-4 py-3">
|
||||||
<Dot />
|
<span className="shrink-0 text-sm text-neutral-60">투찰 가격</span>
|
||||||
<div className="flex flex-1">
|
<span className="min-w-0 flex-1 break-keep text-right text-sm">
|
||||||
<div className="body-1-read-b flex flex-shrink-0">{title} :</div>
|
<span className="font-bold text-[#E5484D]">{priceStr}원</span>
|
||||||
<div className="flex flex-1 flex-wrap">
|
<span className="text-neutral-70"> ({numberToKorean(bidPrice || 0)}원)</span>
|
||||||
<span className="body-1-read-b text-negative break-keep"> {numberString}원</span>
|
<span className="text-neutral-70"> {isVAT ? 'VAT포함' : 'VAT별도'}</span>
|
||||||
<span className="body-1-read-b text-neutral-90 break-keep">
|
|
||||||
({numberToKorean(parseInt(numberString.replace(/,/g, '')))}원)
|
|
||||||
</span>
|
</span>
|
||||||
<span className="body-1-read-b text-neutral-90 break-keep"> {isVAT ? 'VAT포함' : 'VAT별도'}</span>
|
|
||||||
</div>
|
</div>
|
||||||
|
<Row label="배송형태" value={deliveryType || '-'} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function Dot() {
|
function Row({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
|
||||||
return (
|
return (
|
||||||
<div className="flex justify-end items-center w-[26px] h-[30px]">
|
<div className="flex items-start justify-between gap-3 px-4 py-3">
|
||||||
<p className="body-1-read-r">•</p>
|
<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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { CheckCircle2 } from 'lucide-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'
|
||||||
|
|
||||||
|
// 협상 타결(Summary) 직후 부가정보 입력 폼. 필드 정의(session_fields)는 회사 설정(/me)에서 온다.
|
||||||
|
// 저장하면 sessions.custom 에 기록되고 negodata 견적상세에 표시된다. 정의가 없으면 렌더하지 않는다.
|
||||||
|
export function ExtraInfoForm() {
|
||||||
|
const sessionId = useChatStore((s) => s.sessionId)
|
||||||
|
const { data: user } = useMeQuery()
|
||||||
|
const fields: SessionField[] = user?.sessionFields ?? []
|
||||||
|
const save = useSaveExtraInfoMutation()
|
||||||
|
const existing = useChatInitStore((s) => s.custom) // 기존 입력값(재진입 프리필)
|
||||||
|
|
||||||
|
const [values, setValues] = useState<Record<string, unknown>>({})
|
||||||
|
const [inited, setInited] = useState(false)
|
||||||
|
const [saved, setSaved] = useState(false)
|
||||||
|
|
||||||
|
// fields(회사 설정)와 기존값(sessions.custom)이 준비된 첫 시점에 프리필 — 이후 사용자 편집은 보존.
|
||||||
|
useEffect(() => {
|
||||||
|
if (inited || fields.length === 0) return
|
||||||
|
const init: Record<string, unknown> = {}
|
||||||
|
for (const f of fields) init[f.key] = existing?.[f.key] ?? (f.type === 'boolean' ? false : '')
|
||||||
|
setValues(init)
|
||||||
|
setInited(true)
|
||||||
|
}, [inited, fields, existing])
|
||||||
|
|
||||||
|
if (fields.length === 0) return null
|
||||||
|
|
||||||
|
const set = (key: string, value: unknown) => setValues((v) => ({ ...v, [key]: value }))
|
||||||
|
|
||||||
|
const handleSave = () => {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
save.mutate(
|
||||||
|
{ sessionId, request: { custom } },
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
setSaved(true)
|
||||||
|
toast.success('부가정보가 저장되었습니다.')
|
||||||
|
},
|
||||||
|
onError: (error) => toast.error(getApiErrorMessage(error, '부가정보 저장에 실패했습니다.')),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<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-brand-600" />
|
||||||
|
<h3 className="text-sm font-bold text-neutral-90">부가정보 입력</h3>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm leading-relaxed text-neutral-70 break-keep">
|
||||||
|
협상이 완료되었습니다. 아래 정보를 입력해 주세요. (저장 후에도 세션 목록에서 수정할 수 있습니다.)
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="mt-4 space-y-4">
|
||||||
|
{fields.map((f) => (
|
||||||
|
<div key={f.key} className="space-y-1.5">
|
||||||
|
<label className="block 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])}
|
||||||
|
disabled={saved}
|
||||||
|
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors disabled:opacity-50 ${
|
||||||
|
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>
|
||||||
|
) : (
|
||||||
|
<input
|
||||||
|
type={f.type === 'number' ? 'number' : 'text'}
|
||||||
|
value={String(values[f.key] ?? '')}
|
||||||
|
onChange={(e) => set(f.key, e.target.value)}
|
||||||
|
disabled={saved}
|
||||||
|
className="h-11 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 disabled:bg-neutral-10"
|
||||||
|
placeholder={f.label}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={save.isPending || saved}
|
||||||
|
className="mt-4 h-11 w-full rounded-xl bg-brand-600 text-sm font-bold text-white transition-colors hover:bg-brand-700 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{saved ? '저장 완료' : save.isPending ? '저장 중…' : '부가정보 저장'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,78 +1,31 @@
|
|||||||
import { cn } from '@/lib'
|
// 협상 성공률 카드 (0~100%). 10칸 컬러 블록바 — 구간별 색(빨강→주황→초록)으로 채운다.
|
||||||
|
|
||||||
// 협상 성공률 바 (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>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function Indicator({ number }: { number: number }) {
|
export function Indicator({ number }: { number: number }) {
|
||||||
const percent = Math.min(Math.max(number, 0), 100)
|
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 (
|
return (
|
||||||
<div className="flex w-full flex-col gap-3 bg-neutral-00 rounded-[28px] px-10 py-[36px]">
|
<div className="w-full rounded-2xl border border-border bg-white p-5 shadow-sm">
|
||||||
<h1 className="title-1 text-neutral-90">협상 성공률</h1>
|
<div className="flex items-center justify-between">
|
||||||
<div className="flex flex-col gap-2">
|
<h3 className="text-sm font-bold text-neutral-90">협상 성공률</h3>
|
||||||
{percent === 0 ? (
|
<span className="font-mono text-base font-extrabold" style={{ color }}>
|
||||||
<div className="relative h-6">
|
{percent}%
|
||||||
<div className="absolute left-[20px] -translate-x-1/2 text-xl text-black font-bold">▼ 0%</div>
|
</span>
|
||||||
</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>
|
</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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -39,19 +39,20 @@ export function OtherReason({
|
|||||||
const isTextareaDisabled = disabled || !isChecked
|
const isTextareaDisabled = disabled || !isChecked
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1.5">
|
||||||
<div className="flex items-start gap-2">
|
<div className="flex items-start gap-2.5">
|
||||||
<label className={cn('flex items-start gap-2 flex-shrink-0', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}>
|
<label className={cn('flex shrink-0 items-start gap-2.5', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}>
|
||||||
<input
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
'appearance-none w-[16px] h-[16px] mt-[10px] flex-shrink-0 rounded-full border-[1.5px]',
|
'mt-0.5 flex size-[18px] shrink-0 items-center justify-center rounded-full border-2 transition-colors',
|
||||||
disabled ? 'cursor-not-allowed' : 'cursor-pointer',
|
isChecked ? 'border-brand-600' : isError ? 'border-negative' : 'border-neutral-40',
|
||||||
isChecked
|
disabled && 'opacity-60',
|
||||||
? 'border-neutral-70 bg-[radial-gradient(circle,var(--neutral-70)_40%,white_40%)]'
|
|
||||||
: isError
|
|
||||||
? 'border-negative bg-white'
|
|
||||||
: 'border-neutral-60 bg-white',
|
|
||||||
)}
|
)}
|
||||||
|
>
|
||||||
|
{isChecked && <span className="size-2.5 rounded-full bg-brand-600" />}
|
||||||
|
</span>
|
||||||
|
<input
|
||||||
|
className="sr-only"
|
||||||
type="radio"
|
type="radio"
|
||||||
name="rejectrsp"
|
name="rejectrsp"
|
||||||
value="기타"
|
value="기타"
|
||||||
@@ -59,15 +60,15 @@ export function OtherReason({
|
|||||||
onChange={(e) => onChange(e.target.value)}
|
onChange={(e) => onChange(e.target.value)}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
/>
|
/>
|
||||||
<div className={cn('reject break-keep whitespace-nowrap mt-[4px] flex', disabled && 'text-neutral-60')}>
|
<span className={cn('text-sm text-neutral-80', disabled && 'text-neutral-50')}>기타</span>
|
||||||
기타
|
|
||||||
</div>
|
|
||||||
</label>
|
</label>
|
||||||
<textarea
|
<textarea
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
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',
|
'w-full resize-none rounded-xl border px-3 py-2 text-sm outline-none transition-all placeholder:text-neutral-50',
|
||||||
isTextareaDisabled ? 'bg-neutral-10 text-neutral-60 cursor-not-allowed' : 'bg-white text-neutral-90',
|
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',
|
errorMessage && 'border-negative',
|
||||||
)}
|
)}
|
||||||
value={inputValue}
|
value={inputValue}
|
||||||
@@ -75,10 +76,10 @@ export function OtherReason({
|
|||||||
placeholder="제시한 가격을 수용할 수 없는 이유를 작성해주세요."
|
placeholder="제시한 가격을 수용할 수 없는 이유를 작성해주세요."
|
||||||
disabled={isTextareaDisabled}
|
disabled={isTextareaDisabled}
|
||||||
rows={1}
|
rows={1}
|
||||||
style={{ minHeight: '35px', lineHeight: '20px' }}
|
style={{ minHeight: '38px', lineHeight: '20px' }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useState, useMemo } from 'react'
|
import { useState, useMemo } from 'react'
|
||||||
|
import { AlertTriangle } from 'lucide-react'
|
||||||
import { cn } from '@/lib'
|
import { cn } from '@/lib'
|
||||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||||
import { findRestoreScript, extractPart } from '@/features/chat/lib/rejectForm'
|
import { findRestoreScript, extractPart } from '@/features/chat/lib/rejectForm'
|
||||||
@@ -51,44 +52,47 @@ export function RejectCM() {
|
|||||||
const isDisabled = isLoading || isSubmitted
|
const isDisabled = isLoading || isSubmitted
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-2 transition-all duration-300">
|
<div className="flex flex-col w-full p-8 bg-white rounded-2xl border border-border shadow-sm 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 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>
|
||||||
|
|
||||||
<div className="reject break-keep py-2">
|
<div className="py-2 text-sm leading-relaxed text-neutral-70 break-keep">
|
||||||
최종 공급 희망 가격과 배송 형태를 입력하여 주시기 바랍니다.
|
최종 공급 희망 가격과 배송 형태를 입력하여 주시기 바랍니다.
|
||||||
<br />
|
<br />
|
||||||
가격 검토를 통해 경쟁력 있는 가격일 경우 다시 협상에 참여할 기회가 주어지오니 신중한 가격 제안 부탁드립니다.
|
가격 검토를 통해 경쟁력 있는 가격일 경우 다시 협상에 참여할 기회가 주어지오니 신중한 가격 제안 부탁드립니다.
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col w-full gap-1">
|
<div className="flex flex-col w-full gap-1">
|
||||||
<div className="flex w-full items-start gap-4">
|
<div className="flex w-full items-start gap-3">
|
||||||
<div className="flex reject-2 whitespace-nowrap pt-2 flex-shrink-0 w-[110px]">공급 희망 가격</div>
|
<div className="w-[100px] shrink-0 pt-2.5 text-sm font-bold text-neutral-90">공급 희망 가격</div>
|
||||||
<div className="flex flex-wrap w-full items-center pt-2">
|
<div className="flex w-full flex-wrap items-center gap-2 pt-2">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
className={cn(
|
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',
|
'h-10 max-w-[200px] rounded-xl border px-3 text-right text-sm outline-none transition-all placeholder:text-neutral-50',
|
||||||
isDisabled ? 'bg-neutral-10 text-neutral-60 cursor-not-allowed' : 'bg-white text-neutral-90',
|
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() : ''}
|
value={price ? parseInt(price).toLocaleString() : ''}
|
||||||
onChange={(e) => handlePriceChange(e.target.value)}
|
onChange={(e) => handlePriceChange(e.target.value)}
|
||||||
placeholder="0"
|
placeholder="0"
|
||||||
disabled={isDisabled}
|
disabled={isDisabled}
|
||||||
/>
|
/>
|
||||||
<div className="reject whitespace-nowrap mr-2">원{isVAT && '(VAT 별도)'}</div>
|
<div className="whitespace-nowrap text-sm text-neutral-70">원{isVAT && '(VAT 별도)'}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="reject-gray whitespace-nowrap">[{koreanPrice} 원]</div>
|
<div className="whitespace-nowrap text-sm text-neutral-50">[{koreanPrice} 원]</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{priceErrorMessage && <div className="body-5 text-negative pl-[126px]">{priceErrorMessage}</div>}
|
{priceErrorMessage && <div className="pl-[112px] text-xs font-medium text-negative">{priceErrorMessage}</div>}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex w-full gap-4">
|
<div className="flex w-full gap-3">
|
||||||
<div className="flex reject-2 whitespace-nowrap pt-2 flex-shrink-0 w-[110px]">배송 형태</div>
|
<div className="w-[100px] shrink-0 pt-2 text-sm font-bold text-neutral-90">배송 형태</div>
|
||||||
<div className="flex w-full items-center justify-between pr-20 flex-wrap">
|
<div className="flex w-full flex-wrap items-center gap-x-6 gap-y-2">
|
||||||
{['협력사배송', '지정택배배송', '픽업배송'].map((opt) => (
|
{['협력사배송', '지정택배배송', '픽업배송'].map((opt) => (
|
||||||
<SelectRadio
|
<SelectRadio
|
||||||
key={opt}
|
key={opt}
|
||||||
|
|||||||
Loaded 100 of 512 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user