Compare commits
92
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84090433ab | ||
|
|
77d96cd4a4 | ||
|
|
d3e33b10f4 | ||
|
|
3214e4f782 | ||
|
|
e809129ae9 | ||
|
|
631a501c5c | ||
|
|
ab77900dac | ||
|
|
09d24f5022 | ||
|
|
4536a48e40 | ||
|
|
ea1249429a | ||
|
|
d2f1a8f6f4 | ||
|
|
be039dd92b | ||
|
|
2888ff2c28 | ||
|
|
c53eeefcf6 | ||
|
|
f214fccc49 | ||
|
|
63717f5eb9 | ||
|
|
7f15bc10d1 | ||
|
|
d3bcc61609 | ||
|
|
55e3ab02aa | ||
|
|
bae0da42d2 | ||
|
|
15369a016d | ||
|
|
5917942fe3 | ||
|
|
87b896fc2f | ||
|
|
6785c8a6f4 | ||
|
|
3c3f60c7d4 | ||
|
|
bd0f39f131 | ||
|
|
775984fe48 | ||
|
|
5520e3c2b6 | ||
|
|
2a004734d8 | ||
|
|
35d38e0818 | ||
|
|
82cca894fc | ||
|
|
9716528ce7 | ||
|
|
9dca78dc72 | ||
|
|
671904c762 | ||
|
|
6f32b466b9 | ||
|
|
fe9adcaa26 | ||
|
|
f554202c58 | ||
|
|
a56589c6d9 | ||
|
|
b33ae05cd6 | ||
|
|
30f134836b | ||
|
|
8fa77af866 | ||
|
|
89652fac1f | ||
|
|
5e24741395 | ||
|
|
0cefe315c4 | ||
|
|
ba9d34fd31 | ||
|
|
6534d53696 | ||
|
|
ca1291708f | ||
|
|
a5fa44ee25 | ||
|
|
7b612824be | ||
|
|
bacf6271df | ||
|
|
9fb4a52c56 | ||
|
|
f9d37e08f4 | ||
|
|
b539e073cb | ||
|
|
36afcd68a6 | ||
|
|
a55975e62a | ||
|
|
e9be649e1f | ||
|
|
624a8846b0 | ||
|
|
d580e4d5ea | ||
|
|
5318ff3263 | ||
|
|
51d07bb779 | ||
|
|
d7c4e86f30 | ||
|
|
562dafa5ca | ||
|
|
3eec80d989 | ||
|
|
2541a391b7 | ||
|
|
dc8c288f68 | ||
|
|
d111610555 | ||
|
|
e6005b4f94 | ||
|
|
479cb862b1 | ||
|
|
a306ad4cf3 | ||
|
|
c126d56631 | ||
|
|
3c8d0af2e4 | ||
|
|
74fce19be9 | ||
|
|
1006ad11ea | ||
|
|
645a0362b0 | ||
|
|
29e54ad838 | ||
|
|
10ea8ddd45 | ||
|
|
433b973505 | ||
|
|
a750c1098a | ||
|
|
5e286d7949 | ||
|
|
992a3246a8 | ||
|
|
6eb71eb035 | ||
|
|
61b438d8d0 | ||
|
|
8fb54be830 | ||
|
|
c81df5bd88 | ||
|
|
993301be8b | ||
|
|
ca7f057e41 | ||
|
|
e7d2c87fbe | ||
|
|
8b9e81777c | ||
|
|
3c5286aeec | ||
|
|
f97e407f7c | ||
|
|
9ef9bfbca3 | ||
|
|
4a20194dc8 |
No files matched your search
@@ -1,21 +0,0 @@
|
||||
# docker compose 용 환경변수 템플릿 — 복사해서 사용: cp .env.example .env
|
||||
# 실제 값(.env)은 커밋하지 않는다(.gitignore). 이미지에는 시크릿이 없으므로(lps 는 example
|
||||
# config 로 빌드) 아래 값이 없으면 해당 기능이 꺼진 채 뜬다(주석 참고).
|
||||
|
||||
# ── LPS DB (미설정 시 postgres/postgres) ──
|
||||
LPS_DB_USER=postgres
|
||||
LPS_DB_PASSWORD=postgres
|
||||
|
||||
# ── LPS API 스케일 (미설정 시 1 / 40 — 단일 프로세스로도 ~1,100 RPS) ──
|
||||
LPS_API_PROCESS_COUNT=1 # uvicorn 프로세스 수(=사용 코어 수). 커넥션 풀은 예산에서 자동 역산
|
||||
LPS_DB_CONNECTION_BUDGET=40 # lps API 커넥션 총예산. 공유 PG=40, 전용 PG(max_conn≈100)=90
|
||||
|
||||
# ── LPS 워커 시크릿 ──
|
||||
OPENAI_API_KEY= # 비면 AI 유사도 판정 OFF
|
||||
NAVER_KEYS= # "id1:secret1,id2:secret2" — 네이버 쇼핑 오픈API 키(여러 개면 로테이션)
|
||||
DECODO_HOST= # 예: gate.decodo.com — DECODO 4종이 비면 프록시 미사용(직접 연결)
|
||||
DECODO_USERNAME=
|
||||
DECODO_PASSWORD=
|
||||
DECODO_PORT_START=0 # 예: 10001
|
||||
DECODO_PORT_END=0 # 예: 10010
|
||||
DECODO_COST_PER_GB=0 # 요금($/GB) — 검색 원가 계측용(예: 3.0)
|
||||
@@ -28,3 +28,6 @@ CLAUDE.md
|
||||
# 로컬 리서치 노트(크롤링 라이브러리·안티스크래핑 조사) — 추적 안 함, 로컬 참고용
|
||||
/Temp.md
|
||||
/new.md
|
||||
|
||||
/mobile.mov
|
||||
.gstack/
|
||||
@@ -1,63 +1,198 @@
|
||||
# O2O Negosium
|
||||
|
||||
동일 구조의 두 서비스(**negosium**, **negodata**)가 **하나의 PostgreSQL 인스턴스**를 공유한다.
|
||||
AI 협상 솔루션. 여러 백엔드·프론트·배치가 **하나의 PostgreSQL 인스턴스**를 공유하고,
|
||||
전부 `docker compose` 하나로 뜬다. (인터넷 최저가 검색 LPS 만 별도 DB `lps_db` 사용.)
|
||||
|
||||
## 서비스 소개
|
||||
|
||||
구매기업(바이어)이 협력사(공급사)와 벌이는 **가격 협상을 AI 봇이 대신 수행**하는 B2B 협상 자동화 솔루션이다.
|
||||
바이어가 상품·목표가·기간만 정해 견적을 열면, 각 협력사와의 1:1 협상은 강화학습 기반 에이전트가
|
||||
**협상 카드로 밀당**하며 진행하고, 마감 시각에 최저 투찰가를 기준으로 자동 **낙찰/개찰**을 판정한다.
|
||||
|
||||
크게 세 축 + 부속으로 나뉜다.
|
||||
|
||||
| 축 | 구성요소 | 역할 |
|
||||
|---|---|---|
|
||||
| **바이어 측** | negodata (backend + front) | 어드민. 상품·협력사 관리, 견적 생성, 마감·낙찰 관리 |
|
||||
| **공급사 측** | negosium (backend + frontend) | 협력사 포털. 초청받은 협상 챗에 참여해 가격 제시 |
|
||||
| **협상 엔진** | agent | 실제 AI 협상 봇. 앵커링가·협상 카드로 자동 협상 (강화학습) |
|
||||
| 부속 | lps · anchoring · landing | 인터넷 최저가(목표가 재료) · 앵커값 자동 조정 배치 · 솔루션 소개 랜딩 |
|
||||
|
||||
## 구성
|
||||
|
||||
```
|
||||
o2o-negosium/
|
||||
├── docker-compose.yml # 두 backend (DB 는 외부)
|
||||
├── postgres-init/ # DB·테이블 셋업 SQL (대상 DB 에 1회 적용)
|
||||
├── backend/ # negosium 백엔드 (포트 9300)
|
||||
├── negodata/backend/ # negodata 백엔드 (포트 9400)
|
||||
├── agent/ front/ # (예정)
|
||||
└── negodata/front/ # (예정)
|
||||
├── docker-compose.yml # 전체 서비스 (DB 는 compose 밖, config 로 외부 연결)
|
||||
├── postgres-init/ # DB·스키마·시드 SQL (대상 DB 에 1회 적용)
|
||||
│
|
||||
├── backend/ # negosium 백엔드 — 공급사/협상 API (:9300)
|
||||
├── frontend/ # negosium 공급사 프론트 (:3300, 프로덕션 빌드 정적 서빙)
|
||||
├── agent/ # 협상 에이전트 — RL(learning 스키마) (:9500)
|
||||
│
|
||||
├── negodata/backend/ # negodata 백엔드 — 바이어/어드민 API (:9400)
|
||||
├── negodata/front/ # negodata 어드민 프론트 (Vite, :3000)
|
||||
│
|
||||
├── landing/ # 솔루션 랜딩페이지 (react-router SSG, :3100)
|
||||
│
|
||||
├── lps/ # 인터넷 최저가 검색: lps-api(:9600) + lps-worker(크롤)
|
||||
├── lps-admin/ # LPS 관리자 UI (nginx → lps-api 프록시, :3400)
|
||||
│
|
||||
└── schedules/anchoring/ # 앵커링 값 자동 조정 배치 (포트 없음, 상주 스케줄러 + Redis)
|
||||
```
|
||||
|
||||
두 백엔드는 같은 코드 골격(MVC · 람다 DB · Depends 주입 · JWT 로그인)을 쓴다.
|
||||
아키텍처/패턴 상세는 각 서버 README 참고: [backend](backend/README.md) · [negodata/backend](negodata/backend/README.md)
|
||||
negosium·negodata·agent 백엔드는 같은 코드 골격(MVC · 람다 DB · Depends 주입 · JWT 로그인)을 쓴다.
|
||||
아키텍처/패턴 상세는 각 서브 README 참고:
|
||||
- 백엔드: [backend](backend/README.md) · [negodata/backend](negodata/backend/README.md) · [agent](agent/README.md) · [lps](lps/README.md)
|
||||
- 프론트: [frontend](frontend/README.md) · [negodata/front](negodata/front/README.md)
|
||||
- 배치: [schedules/anchoring](schedules/anchoring/README.md) · 관리자 UI: [lps-admin](lps-admin/README.md)
|
||||
|
||||
### 서비스 / 포트
|
||||
|
||||
| 서비스 | 주소 | 역할 | DB |
|
||||
|---|---|---|---|
|
||||
| negosium-backend | http://localhost:9300/docs | 공급사·협상 API | negosium_db |
|
||||
| negosium-front | http://localhost:3300 | 공급사 프론트 | — |
|
||||
| agent | http://localhost:9500/docs | 협상 에이전트(RL) | negosium_db (learning) |
|
||||
| negodata-backend | http://localhost:9400/docs | 바이어·어드민 API | negosium_db |
|
||||
| negodata-front | http://localhost:3000 | 어드민 프론트 | — |
|
||||
| landing | http://localhost:3100 | 솔루션 랜딩 | — |
|
||||
| lps-api | http://localhost:9600/docs | 최저가 검색 접수/조회 | lps_db |
|
||||
| lps-worker | 포트 없음 | 크롤 워커(헤드풀 Chromium) | lps_db |
|
||||
| lps-admin | http://localhost:3400 | LPS 관리자 UI | — |
|
||||
| anchoring | 포트 없음 | 앵커링 조정 배치(격주 토 00:00 KST) | negosium_db (anchoring) |
|
||||
| anchoring-redis | 127.0.0.1:6380 | anchoring 조회 캐시 | — |
|
||||
| autoheal | — | unhealthy 컨테이너 자동 재시작 | — |
|
||||
|
||||
### DB 는 compose 밖 (config 로 연결)
|
||||
|
||||
DB 는 docker-compose 에서 관리하지 않는다. 각 backend 는 `config.<APP_ENV>.toml` 의 접속 정보대로
|
||||
**외부 PostgreSQL**(호스트 로컬 postgres, 또는 따로 떠 있는 docker postgres)에 연결한다.
|
||||
한 PostgreSQL 안에 서비스별 database 를 둔다.
|
||||
|
||||
한 PostgreSQL 인스턴스 안에 **단일 `negosium_db`** 를 두고 도메인별 **schema** 로 묶는다.
|
||||
LPS 만 별도 database(`lps_db`) 를 쓴다.
|
||||
|
||||
```
|
||||
PostgreSQL (외부, 5432)
|
||||
├── negosium_db ← negosium-backend
|
||||
└── negodata_db ← negodata-backend
|
||||
├── negosium_db ← negosium-backend · negodata-backend · agent · anchoring 공유
|
||||
│ ├── company / supplier / partner : 회사·유저·협력사·상품
|
||||
│ ├── card / quotation / negotiation: 협상 카드·견적·협상 세션
|
||||
│ ├── learning : RL 자산 (agent 소유)
|
||||
│ └── anchoring : 앵커링 조정 (schedules/anchoring 소유)
|
||||
└── lps_db ← lps-api · lps-worker
|
||||
```
|
||||
- 컨테이너(docker env)에서 호스트 DB 접근: `host.docker.internal:5432` (`config.docker.toml`)
|
||||
- 컨테이너(docker env)에서 호스트 DB 접근: `host.docker.internal:5432` (compose 가 `DB_HOST` 로 override)
|
||||
- 로컬 실행/테스트(local·test env): `127.0.0.1:5432` (`config.local/test.toml`)
|
||||
- 계정/database 명은 config 에 맞춘다 (기본 `postgres` / `password`).
|
||||
|
||||
| 서비스 | 서버 | docs | database |
|
||||
|---|---|---|---|
|
||||
| negosium-backend | http://localhost:9300 | /docs | negosium_db |
|
||||
| negodata-backend | http://localhost:9400 | /docs | negodata_db |
|
||||
## 핵심 플로우
|
||||
|
||||
### 1. 견적 라이프사이클 (전체 개요)
|
||||
|
||||
바이어가 견적을 열고 → 협력사가 협상에 참여 → 마감 시각에 판정되는 큰 흐름.
|
||||
견적 유형은 두 축(재/신규 × 협상 1:1 / 견적 1:N)으로 4종.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["바이어: 상품·협력사·기간 선택<br/>견적 유형 4종 + 낙찰 기준(mid/over_action) 설정"] --> B["목표가·앵커링가 산정<br/>(MD제시가 → 인터넷최저가/매입가/판매가)"]
|
||||
B --> C["협력사 초청 (이메일)"]
|
||||
C --> D{"견적 유형"}
|
||||
D -->|"협상 1:1 (재협상·신규협상)"| E["AI 봇 밀당 협상<br/>(협상 카드 사용)"]
|
||||
D -->|"견적 1:N (재견적·신규견적)"| F["정형 흐름<br/>(배송형태·추가할인 확인)"]
|
||||
E --> G["세션별 투찰가 확정<br/>(협상완료) 또는 실패"]
|
||||
F --> G
|
||||
G --> H{"마감 트리거<br/>①마감시각 ②전세션종결 ③수동"}
|
||||
H --> I["마감 판정<br/>(최저 투찰가 기준)"]
|
||||
I --> J["낙찰 (승자 1)"]
|
||||
I --> K["개찰 (낙찰자 미정)"]
|
||||
```
|
||||
|
||||
### 2. 1:1 협상 봇 판정 (agent)
|
||||
|
||||
협력사가 가격을 제시할 때마다 봇이 **앵커링가** 기준으로 판정한다.
|
||||
재제안은 카드를 한 장씩 쓰며 **최대 3번**, 카드 소진·3번 초과에도 앵커 밑으로 못 내리면 실패(투찰 없음).
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
P["협력사 가격 제시"] --> Q{"제시가 vs 앵커링가"}
|
||||
Q -->|"≤ 앵커링가"| R["협상완료 — 투찰 확정"]
|
||||
Q -->|"앵커 ~ 앵커×1.02"| S["와일드카드: 1% 인하 요청<br/>(세션당 1회)"]
|
||||
Q -->|"앵커×1.02 초과"| T["협상 카드로 재제안"]
|
||||
S --> U{"재제안 횟수 ≤ 3?<br/>카드 남음?"}
|
||||
T --> U
|
||||
U -->|"예"| P
|
||||
U -->|"아니오 (소진·3번 초과)"| V["협상 실패 — 낙찰 후보 아님"]
|
||||
```
|
||||
|
||||
### 3. 마감 판정
|
||||
|
||||
마감 시 **협상완료 세션의 최저 투찰가**를 본다. 공통 전제: 완료 세션이 없거나(전원 미응찰·협상거부)
|
||||
동가 최저가 2곳 이상이면 유형과 무관하게 **개찰**. 그 외 단독 최저가일 때만 낙찰 후보가 되며,
|
||||
이후 판정이 유형별로 갈린다.
|
||||
|
||||
#### 3-1. 견적 1:N — 단독 최저면 무조건 낙찰
|
||||
|
||||
가격 구간을 보지 않는다. 생성 시 `mid/over_action`이 낙찰(AWARD)로 강제되기 때문.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
M1["마감: 협상완료 세션 최저 투찰가"] --> N1{"완료 세션 있나?"}
|
||||
N1 -->|"없음 (전원 미응찰·협상거부)"| O1["개찰"]
|
||||
N1 -->|"동가 최저 2곳+"| O1
|
||||
N1 -->|"단독 최저"| X1["낙찰 (가격 구간 무관, 무조건)"]
|
||||
```
|
||||
|
||||
#### 3-2. 협상 1:1 — 가격 구간별, 생성 때 정한 값 적용
|
||||
|
||||
앵커링가 이하는 무조건 낙찰. 그 위 구간은 **견적 생성 때 미리 정해둔 값**(`mid_action`/`over_action`,
|
||||
1=낙찰·2=개찰)을 마감 시 그대로 적용한다. 두 필드는 적용 구간만 다를 뿐 동작은 동일.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
M2["마감: 협상완료 세션 최저 투찰가"] --> N2{"완료 세션 있나?"}
|
||||
N2 -->|"없음 (전원 미응찰·협상거부)"| O2["개찰"]
|
||||
N2 -->|"동가 최저 2곳+"| O2
|
||||
N2 -->|"단독 최저"| W2{"투찰가 위치"}
|
||||
W2 -->|"≤ 앵커링가"| X2["낙찰"]
|
||||
W2 -->|"앵커 ~ 목표가"| Y2["생성 시 정한 mid_action 적용<br/>(1=낙찰 / 2=개찰)"]
|
||||
W2 -->|"목표가 초과"| Z2["생성 시 정한 over_action 적용<br/>(1=낙찰 / 2=개찰)"]
|
||||
```
|
||||
|
||||
> 개찰 = 낙찰자 미정 마감(결렬 아님). 개찰 후 수동 처리로 **직접 낙찰 확정**(`/v1/quotation/award`)
|
||||
> 또는 **재견적 재생성**(`/v1/quotation/regenerate`)이 있다.
|
||||
> 비즈니스 로직 정본은 [negodata/docs/business-logic.md](negodata/docs/business-logic.md).
|
||||
|
||||
## 빠른 시작
|
||||
|
||||
```bash
|
||||
# 1) DB 준비 (최초 1회) — 사용할 PostgreSQL 에 스키마 + 시드 적용
|
||||
psql -h 127.0.0.1 -p 5432 -U postgres -f postgres-init/00-init.sql # 스키마 전체 (negosium_db + 도메인·learning·anchoring schema)
|
||||
psql -h 127.0.0.1 -p 5432 -U postgres -f postgres-init/temp-data.sql # 임시 데이터 시드 (admin / admin1234)
|
||||
# 스키마 DDL (구 01~05 통합, 전부 IF NOT EXISTS 라 재실행 안전)
|
||||
psql -h 127.0.0.1 -p 5432 -U postgres -d negosium_db -f postgres-init/init-data/init.sql
|
||||
# 로컬/개발 시드 (admin / admin1234, 회사·유저·협상 카드)
|
||||
psql -h 127.0.0.1 -p 5432 -U postgres -d negosium_db -f postgres-init/init-data/init-data.sql
|
||||
|
||||
# 2) 백엔드 기동
|
||||
docker compose up -d # 두 backend (DB 는 config 대로 외부 연결)
|
||||
docker compose logs -f
|
||||
# (DBeaver 로 처음부터 새로 깔 때는 postgres-init/dbeaver/ 의 0~5 순서 스크립트를 쓴다:
|
||||
# 0 drop&create → 1 스키마 → 2 시드 → 3 lps_db → 4 카드 리셋 → 5 o2o OWNER 유저)
|
||||
|
||||
# 2) 전체 기동
|
||||
docker compose up -d
|
||||
docker compose logs -f # 컨테이너별 로그는 ./logs.sh 메뉴로도 확인
|
||||
docker compose down
|
||||
```
|
||||
|
||||
> 스키마 변경 보정은 `postgres-init/alters/` 의 날짜별 SQL 을 대상 DB 에 수동 적용한다
|
||||
> (postgres-init 은 DB 최초 생성 때만 자동 실행되므로, 기존 DB 엔 alter 를 직접 돌려야 새 컬럼이 반영된다).
|
||||
|
||||
## 테스트
|
||||
|
||||
```bash
|
||||
# config.test.toml 의 PostgreSQL(기본 127.0.0.1:5432) 이 떠 있어야 한다
|
||||
cd backend # 또는 negodata/backend
|
||||
cd backend # 또는 negodata/backend, agent, lps ...
|
||||
pip install pytest pytest-asyncio httpx
|
||||
python -m pytest
|
||||
```
|
||||
- httpx `ASGITransport` 로 네트워크 없이 앱을 직접 호출하는 e2e (각 5개).
|
||||
- httpx `ASGITransport` 로 네트워크 없이 앱을 직접 호출하는 e2e.
|
||||
- `DB_SESSION_MNG` 싱글톤의 커넥션 풀이 첫 이벤트 루프에 묶이므로, 모든 테스트가 단일 session 루프를 공유한다(`pytest.ini`).
|
||||
- ⚠️ 테스트는 `APP_ENV=test` 로 격리한다(테스트 DB). dev DB(`negosium_db`)에 대고 돌리면 데이터가 날아간다.
|
||||
|
||||
## 성능 / 벤치마크
|
||||
|
||||
@@ -99,4 +234,9 @@ python -m locust -f loadtest/locustfile.py --host http://localhost:9300 --headle
|
||||
```
|
||||
|
||||
## 기술 스택
|
||||
FastAPI · SQLAlchemy(async) · asyncpg · PostgreSQL 16 · python-jose(JWT) · bcrypt · uvicorn · Docker Compose
|
||||
- **백엔드**: FastAPI · SQLAlchemy(async) · asyncpg · PostgreSQL 16 · python-jose(JWT) · bcrypt · uvicorn
|
||||
- **프론트**: React · react-router v7 · Vite · TanStack Query (negosium-front 는 프로덕션 빌드 정적 서빙)
|
||||
- **에이전트**: 강화학습(Q-learning, learning 스키마) · OpenAI
|
||||
- **LPS**: 헤드풀 Chromium + Patchright(스텔스 Playwright 포크, 크롤) · autoheal
|
||||
- **배치**: Redis(anchoring 캐시) · 상주 스케줄러
|
||||
- **공통**: Docker Compose
|
||||
@@ -114,7 +114,7 @@ def compute_counter(spec: TacticSpec, context: Dict[str, Any]) -> Optional[int]:
|
||||
if counter <= 0:
|
||||
return None
|
||||
counter = min(counter, target) # 목표가 초과 제시 금지 (가드레일)
|
||||
counter_i = int(round(counter))
|
||||
counter_i = int(counter / 10 + 0.5) * 10 # 10원 단위 반올림 — 앵커가·목표가 산정과 표기 통일(IMK 요청)
|
||||
if counter_i >= price:
|
||||
return None # 제시가가 이미 카운터 이하 → 카운터 무의미
|
||||
return counter_i
|
||||
@@ -23,9 +23,16 @@ _SESSIONS = table(
|
||||
"sessions",
|
||||
column("session_id"), column("quotation_id"), column("item_id"), column("supplier_id"),
|
||||
column("qt_type"), column("target_price"), column("anchoring_price"),
|
||||
column("qt_setting_id"),
|
||||
column("deleted"),
|
||||
schema="negotiation",
|
||||
)
|
||||
# 견적 설정 — card_count(협상 내 협상카드 사용 횟수 상한) 조회용.
|
||||
_QUOTATION_SETTINGS = table(
|
||||
"quotation_settings",
|
||||
column("qt_setting_id"), column("card_count"), column("deleted"),
|
||||
schema="quotation",
|
||||
)
|
||||
_ITEMS = table("items", column("item_id"), column("name"), column("price"),
|
||||
column("internet_lowest_price"), column("deleted"), schema="partner")
|
||||
_SUPPLIERS = table("suppliers", column("supplier_id"), column("name"), column("total_revenue"), column("deleted"), schema="partner")
|
||||
@@ -73,6 +80,12 @@ class INegoContextCRUD(ABC):
|
||||
"""품목 기준가(items.price). 없으면 0."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_card_count(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[int]]:
|
||||
"""협상카드 사용 횟수 상한(quotation_settings.card_count) — 세션의 qt_setting_id 로 조인.
|
||||
설정이 없으면 None(호출부가 상한 미적용). 이 값이 협상 중 실제로 플레이 가능한 협상카드 수를 캡한다."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_item_lowest_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
"""상품 인터넷 최저가(items.internet_lowest_price — LPS 수집 대표값). 미수집이면 0.
|
||||
@@ -148,6 +161,29 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def get_card_count(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[int]]:
|
||||
try:
|
||||
query = (
|
||||
select(_QUOTATION_SETTINGS.c.card_count)
|
||||
.select_from(
|
||||
_SESSIONS.join(
|
||||
_QUOTATION_SETTINGS,
|
||||
_QUOTATION_SETTINGS.c.qt_setting_id == _SESSIONS.c.qt_setting_id,
|
||||
)
|
||||
)
|
||||
.where(_SESSIONS.c.session_id == session_id,
|
||||
_SESSIONS.c.deleted == False, # noqa: E712
|
||||
_QUOTATION_SETTINGS.c.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_card_count failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS or not rows or rows[0] is None:
|
||||
return err_type, None
|
||||
return ErrorType.SUCCESS, int(rows[0])
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def get_item_lowest_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
try:
|
||||
query = (
|
||||
|
||||
@@ -211,7 +211,7 @@ class ChatEngine:
|
||||
# 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
|
||||
# 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
|
||||
ctx["wildcard_used"] = True
|
||||
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가 (멘트 변수)
|
||||
ctx["offer_1pct"] = int(price * 0.99 / 10 + 0.5) * 10 # 1% 인하가 (멘트 변수) — 10원 반올림(앵커·카운터와 통일)
|
||||
ctx["pending_counter_price"] = ctx["offer_1pct"] # 수락 시 이 가격으로 타결
|
||||
return "wild_card_1pct"
|
||||
# 1.02 초과 ~ entry(1.05) 구간: 견적에서 선택한 와일드카드의 전술로 카운터 제시.
|
||||
@@ -266,7 +266,15 @@ class ChatEngine:
|
||||
if prev_customer and "input_price" in ctx:
|
||||
out["middle_price"] = int(round((prev_customer + ctx["input_price"]) / 2))
|
||||
if ctx.get("pending_counter_price"):
|
||||
out["counter_price"] = int(ctx["pending_counter_price"])
|
||||
# 카운터 제시 중: 멘트에 보이는 제시가와 수락 시 타결가(pending)를 반드시 일치시킨다.
|
||||
# 절충/중간 변수(middle_price·target_mid_price)는 vars_for 재계산 값이 compute_counter 의
|
||||
# target 클램프·prev_customer 갱신과 어긋나, 멘트엔 1,740,000 이 보이는데 실제로는
|
||||
# 1,700,000 으로 타결되던 버그(표시가≠투찰가)가 있었다. pending 은 이 시점 유일한 '제안가'이므로
|
||||
# 세 변수 모두 pending 으로 고정한다(카운터 제시 턴에만 적용 — 비-카운터 렌더는 원 계산값 유지).
|
||||
pending_i = int(ctx["pending_counter_price"])
|
||||
out["counter_price"] = pending_i
|
||||
out["middle_price"] = pending_i
|
||||
out["target_mid_price"] = pending_i
|
||||
# 인하율 = (기존 공급가(상품단가) - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
|
||||
# 제시가가 기존가보다 높으면(인상 제시) 음수가 나오는데, "-1.3% 인하된 금액" 같은
|
||||
# 모순 표현이 되므로 discount_rate 는 0 미만 금지하고, 인상/동일/인하를 구분한
|
||||
|
||||
@@ -47,6 +47,7 @@ class NegotiationDbContext:
|
||||
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type. 미지정 시 None
|
||||
selected_nego_card_numbers: list[str] # 견적 생성 시 선택된 일반 협상카드 번호(card.nego_cards.number)
|
||||
selected_wild_card_numbers: list[str] # 견적 생성 시 선택된 와일드카드 번호(card.wild_cards.number)
|
||||
card_count: Optional[int] # 협상카드 사용 횟수 상한(quotation_settings.card_count). None=상한 미적용
|
||||
|
||||
|
||||
class NegotiationContextLoader:
|
||||
@@ -107,6 +108,9 @@ class NegotiationContextLoader:
|
||||
_, selected_cards = await self.crud.get_quotation_card_numbers(s, quotation_id)
|
||||
selected_nego_cards, selected_wild_cards = selected_cards
|
||||
|
||||
# 협상카드 사용 횟수 상한(견적 설정). 없으면 None → 상한 미적용(선택 카드 수로만 캡).
|
||||
_, card_count = await self.crud.get_card_count(s, sid)
|
||||
|
||||
return NegotiationDbContext(
|
||||
rq_type="재협상" if int(qt_type) in _ONE_TO_ONE_QT_TYPES else "재견적",
|
||||
target_price=target,
|
||||
@@ -120,6 +124,7 @@ class NegotiationContextLoader:
|
||||
distribution_code=_SUPPLIER_TYPE_TO_CODE.get(supplier_type) if supplier_type else None,
|
||||
selected_nego_card_numbers=selected_nego_cards,
|
||||
selected_wild_card_numbers=selected_wild_cards,
|
||||
card_count=card_count,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -82,8 +82,12 @@ class ChatService:
|
||||
selected_wild_cards = db_ctx.selected_wild_card_numbers if db_ctx else []
|
||||
# 운영 DB 세션은 견적 version_id 에 묶인 카드만 사용한다. 직접 호출/데모(DB context 없음)는
|
||||
# 기존 테넌트 기본 action mapping 으로 폴백해 로컬 테스트와 콘솔 데모를 유지한다.
|
||||
# 협상카드 사용 횟수 상한(quotation_settings.card_count)으로 실제 플레이 가능한 카드 수를 캡한다 —
|
||||
# session.action_space_size 는 카드 소진 판정(cards_total) 전용이라 여기서 줄여도 Q-table 은
|
||||
# engine.action_space_size(카탈로그 전체)로 별도 고정된다. card_count 미설정(None)이면 선택 수 그대로.
|
||||
card_cap = db_ctx.card_count if (db_ctx and db_ctx.card_count and db_ctx.card_count > 0) else None
|
||||
action_space_size = (
|
||||
min(len(selected_nego_cards), engine.action_space_size)
|
||||
min(len(selected_nego_cards), engine.action_space_size, *( [card_cap] if card_cap else [] ))
|
||||
if db_ctx is not None
|
||||
else engine.action_space_size
|
||||
)
|
||||
|
||||
@@ -47,8 +47,8 @@ def test_counter_formulas_and_clamp():
|
||||
assert compute_counter(tactic_for("WC-05"), ctx) == 10000
|
||||
# 갑 직전 포지션이 있으면 그 기준: (9800+11000)/2 = 10400 → 역시 클램프 10000
|
||||
assert compute_counter(tactic_for("WC-05"), dict(ctx, prev_customer_price=9800)) == 10000
|
||||
# 클램프 미발동 구간: (9900+10050)/2 = 9975 ≤ target
|
||||
assert compute_counter(tactic_for("WC-05"), dict(ctx, input_price=10050)) == 9975
|
||||
# 클램프 미발동 구간: (9900+10050)/2 = 9975 ≤ target → 10원 단위 반올림 9980
|
||||
assert compute_counter(tactic_for("WC-05"), dict(ctx, input_price=10050)) == 9980
|
||||
|
||||
|
||||
def test_counter_meaningless_degrades_to_hold():
|
||||
@@ -169,13 +169,21 @@ def test_price_confirm_script_renders_raise_correctly():
|
||||
# ---- vars_for 전술 변수 치환 ---------------------------------------------------
|
||||
def test_vars_for_supplies_tactic_variables():
|
||||
eng = _engine()
|
||||
s = _session(input_price=10300, prev_customer_price=10000, pending_counter_price=10100)
|
||||
v = eng.vars_for(s)
|
||||
assert v["prev_partner_price"] == 10300
|
||||
assert v["prev_customer_price"] == 10000
|
||||
assert v["target_mid_price"] == 10050 # (10000+10100)/2
|
||||
assert v["middle_price"] == 10150 # (10000+10300)/2
|
||||
assert v["counter_price"] == 10100
|
||||
# 카운터 미제시(정보성): 절충/중간 변수는 원 계산값.
|
||||
s0 = _session(input_price=10300, prev_customer_price=10000) # anchor=10000, target=10100 (기본)
|
||||
v0 = eng.vars_for(s0)
|
||||
assert v0["prev_partner_price"] == 10300
|
||||
assert v0["prev_customer_price"] == 10000
|
||||
assert v0["target_mid_price"] == 10050 # (anchor 10000 + target 10100)/2
|
||||
assert v0["middle_price"] == 10150 # (prev_customer 10000 + input 10300)/2
|
||||
|
||||
# 카운터 제시 중: 표시 제시가(middle/target_mid/counter) == 타결가(pending) 로 고정.
|
||||
# 회귀(표시가≠투찰가): 예전엔 middle_price 가 재계산값 10150 을 표시하면서 10100 으로 타결됐다.
|
||||
s1 = _session(input_price=10300, prev_customer_price=10000, pending_counter_price=10100)
|
||||
v1 = eng.vars_for(s1)
|
||||
assert v1["counter_price"] == 10100
|
||||
assert v1["middle_price"] == 10100 # 재계산 10150 이 아니라 pending
|
||||
assert v1["target_mid_price"] == 10100
|
||||
|
||||
|
||||
# ---- ⑤⑥ E2E (실 DB — 견적 선택 카드 + 서비스 레이어) ---------------------------
|
||||
|
||||
@@ -195,6 +195,9 @@ async def test_loader_with_crud_double(db_engine):
|
||||
async def get_item_lowest_price(self, cdb, item_id):
|
||||
return ErrorType.SUCCESS, 6300 # 인터넷 최저가(items.internet_lowest_price)
|
||||
|
||||
async def get_card_count(self, cdb, session_id):
|
||||
return ErrorType.SUCCESS, 3 # 협상카드 사용 횟수 상한(quotation_settings.card_count)
|
||||
|
||||
async def get_supplier_total_revenue(self, cdb, supplier_id):
|
||||
return ErrorType.SUCCESS, 12_000_000.0
|
||||
|
||||
@@ -223,6 +226,7 @@ async def test_loader_with_crud_double(db_engine):
|
||||
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
|
||||
assert ctx.item_price == 7000
|
||||
assert ctx.internet_lowest_price == 6300 # 인터넷 최저가 로드 확인
|
||||
assert ctx.card_count == 3 # 협상카드 사용 횟수 상한 로드 확인
|
||||
assert ctx.partner_name == "테스트협력사"
|
||||
assert ctx.product_name == "테스트상품"
|
||||
assert ctx.revenue_amount == 12_000_000.0
|
||||
|
||||
@@ -162,6 +162,31 @@ def test_card_id_fixed_mapping_and_selection_mask():
|
||||
assert ChatService._selection_mask(eng, session) is None
|
||||
|
||||
|
||||
def test_counter_display_price_equals_settlement():
|
||||
"""회귀(표시가≠투찰가): 카운터 제시 중 멘트에 보이는 절충/중간 변수
|
||||
(middle_price·target_mid_price)는 수락 시 타결가(pending_counter_price)와 정확히 일치해야 한다.
|
||||
|
||||
버그: WC-05(중간값 절충)에서 compute_counter 는 target 클램프·prev_customer 갱신으로 1,700,000 을
|
||||
pending 으로 적재하는데, vars_for 가 {middle_price} 를 재계산해 1,740,000 으로 표시 → 화면엔
|
||||
1,740,000 인데 실제로는 1,700,000 으로 투찰되던 문제. pending 으로 고정해 표시가==타결가."""
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||
repo = ScriptRepository(cfg, _TENANTS_DIR)
|
||||
engine = ChatEngine(repo, rq_type="재협상")
|
||||
session = ChatSession(
|
||||
session_id="00000000-0000-0000-0000-000000000009",
|
||||
tenant_id="imarketkorea", company_id="imarketkorea", action_space_size=0,
|
||||
context={
|
||||
"anchor_price": 2000000, "target_price": 1700000, "input_price": 1780000,
|
||||
"prev_customer_price": 1700000, # 종결 전술이 counter 로 덮어쓴 상태
|
||||
"pending_counter_price": 1700000, # compute_counter 의 target 클램프 결과(실제 타결가)
|
||||
},
|
||||
)
|
||||
v = engine.vars_for(session)
|
||||
assert v["counter_price"] == 1700000
|
||||
assert v["middle_price"] == 1700000 # 재계산값 1,740,000 이 아니라 pending
|
||||
assert v["target_mid_price"] == 1700000
|
||||
|
||||
|
||||
def test_default_1pct_wildcard_still_runs_without_selected_wildcard():
|
||||
"""1% 인하는 기본 제공 카드라 DB 견적에서 와일드카드를 선택하지 않아도 발동한다."""
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||
|
||||
@@ -173,6 +173,7 @@ class quotations(MAIN_BASE):
|
||||
preferred_sp_yn = Column(Boolean, nullable=True) # 선호 공급사 지정 여부
|
||||
preferred_sp_id = Column(UUID(as_uuid=True), nullable=True) # 선호 공급사(partner.suppliers.supplier_id)
|
||||
preferred_sp_name = Column(String(20), nullable=True) # 선호 공급사명(스냅샷)
|
||||
close_reason = Column(SmallInteger, nullable=True) # 마감 사유(CloseReason). 재협상 요청 자격 판정에 읽는다
|
||||
equal_bid_yn = Column(Boolean, nullable=True) # 동일가 입찰 발생 여부
|
||||
equal_bid_data = Column(JSONB, nullable=True) # 동일가 입찰 상세(JSON)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC)
|
||||
@@ -180,6 +181,28 @@ class quotations(MAIN_BASE):
|
||||
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
|
||||
|
||||
|
||||
class notifications(MAIN_BASE):
|
||||
# company.notifications (담당자 인박스). 포털은 재협상 요청 알림을 만들기 위해서만 쓴다(조회는 negodata).
|
||||
# company 스키마 전용 DBType 이 없어 USER 커넥션을 재사용한다(물리 DB 동일).
|
||||
@staticmethod
|
||||
def DBType():
|
||||
return DBType.USER.value
|
||||
|
||||
__tablename__ = "notifications"
|
||||
__table_args__ = {"schema": "company"}
|
||||
|
||||
notification_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
|
||||
user_id = Column(UUID(as_uuid=True), nullable=False) # 수신자(company.users.user_id) = 견적 작성자
|
||||
type = Column(SmallInteger, nullable=False) # NotificationType
|
||||
ref_qt_id = Column(UUID(as_uuid=True), nullable=True)
|
||||
ref_session_id = Column(UUID(as_uuid=True), nullable=True)
|
||||
data = Column(JSONB, nullable=True) # 렌더 스냅샷(공급사명·사유·희망가 등)
|
||||
read_at = Column(DateTime(timezone=True), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')"))
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')"), onupdate=text("(now() AT TIME ZONE 'utc')"))
|
||||
deleted = Column(Boolean, nullable=False, server_default=text("false"))
|
||||
|
||||
|
||||
class quotation_settings(MAIN_BASE):
|
||||
# quotation.quotation_settings (견적 설정). 견적 설정 스냅샷 — anchoring_value 는 구(舊) 앵커 산출용으로 채팅 경로에서는 더 이상 사용하지 않음(앵커는 sessions.anchoring_price 박제값).
|
||||
@staticmethod
|
||||
|
||||
@@ -130,6 +130,41 @@ class QuotationStatus(Enum):
|
||||
CLOSED = 3 # 견적마감
|
||||
|
||||
|
||||
class CloseReason(Enum):
|
||||
"""견적 마감 사유. quotation.quotations.close_reason
|
||||
낙찰(AWARDED) 외 OPEN_* 는 낙찰자 미정으로 마감된 '결렬' 건 — 공급사 재협상 요청 대상."""
|
||||
|
||||
AWARDED = 1 # 낙찰
|
||||
OPEN_PRICE = 5 # 개찰: 낙찰 기준 미달
|
||||
OPEN_EQUAL = 6 # 개찰: 동가
|
||||
OPEN_NOSHOW = 7 # 개찰: 전원 미응찰
|
||||
OPEN_REJECT = 8 # 개찰: 협상거부 존재
|
||||
|
||||
|
||||
# 재협상 요청 가능한 마감 사유(낙찰 건은 제외).
|
||||
RENEGOTIABLE_CLOSE_REASONS = (
|
||||
CloseReason.OPEN_PRICE.value,
|
||||
CloseReason.OPEN_EQUAL.value,
|
||||
CloseReason.OPEN_NOSHOW.value,
|
||||
CloseReason.OPEN_REJECT.value,
|
||||
)
|
||||
|
||||
|
||||
class RenegotiationStatus(Enum):
|
||||
"""sessions.custom.renegotiation.status — 공급사 재협상 요청 상태(IMK #15)."""
|
||||
|
||||
PENDING = 1 # 접수, 담당자 심사 대기
|
||||
APPROVED = 2 # 승인 — 다음 라운드 생성됨
|
||||
REJECTED = 3 # 반려
|
||||
CANCELED = 4 # 공급사 철회
|
||||
|
||||
|
||||
class NotificationType(Enum):
|
||||
"""company.notifications.type — negodata 담당자 인박스. 포털에서 만드는 건 재협상 요청뿐."""
|
||||
|
||||
RENEGO_REQUESTED = 5
|
||||
|
||||
|
||||
class ChatSender(Enum):
|
||||
"""채팅 발신자 코드. negotiation.chats.sender """
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Tuple
|
||||
|
||||
from sqlalchemy import case, func, nulls_last, select, update
|
||||
from sqlalchemy import case, cast, func, nulls_last, or_, select, text, update
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import items, quotations, sessions
|
||||
from common.enums import ErrorType, SessionStatus
|
||||
from common.enums import CloseReason, ErrorType, QuotationStatus, RENEGOTIABLE_CLOSE_REASONS, SessionStatus
|
||||
from common.logger import LOG
|
||||
|
||||
|
||||
@@ -14,11 +15,11 @@ from common.logger import LOG
|
||||
# 마감일(qt_end_time)은 견적(quotation.end_time)이 진실값이다(session.end_time 은 협상 종료 시점 기록용).
|
||||
class ISessionCRUD(ABC):
|
||||
@abstractmethod
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]:
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type) -> Tuple[ErrorType, int]:
|
||||
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, keyword=None, result=None) -> Tuple[ErrorType, int]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -45,20 +46,59 @@ class ISessionCRUD(ABC):
|
||||
async def update_session_custom(self, cdb: AsyncSession, session_id, supplier_id, custom: dict) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
|
||||
# 같은 견적번호(체인)의 최대 차수. 이미 다음 라운드가 있으면 재협상 요청은 의미가 없다.
|
||||
try:
|
||||
query = select(func.max(quotations.round)).where(quotations.number == number, quotations.deleted == False) # noqa: E712
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, 0
|
||||
top = rows[0][0] if rows and rows[0] else None
|
||||
return ErrorType.SUCCESS, int(top or 0)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def merge_session_custom(self, cdb: AsyncSession, session_id, supplier_id, patch: dict) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
|
||||
pass
|
||||
|
||||
|
||||
class SessionCRUD(ISessionCRUD):
|
||||
@staticmethod
|
||||
def __filters(supplier_id, status, qt_type):
|
||||
def __filters(supplier_id, status, qt_type, keyword=None, result=None):
|
||||
conds = [sessions.supplier_id == supplier_id, sessions.deleted == False] # noqa: E712
|
||||
if status is not None:
|
||||
conds.append(sessions.status == status)
|
||||
if qt_type is not None:
|
||||
conds.append(sessions.qt_type == qt_type)
|
||||
# 검색: 견적번호·상품명·상품코드 부분일치(대소문자 무시). items 는 목록/카운트 둘 다 조인돼 있다.
|
||||
# ILIKE 와일드카드(%,_)는 escape 해 사용자 입력이 패턴으로 새지 않게 한다.
|
||||
if keyword and keyword.strip():
|
||||
kw = keyword.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
like = f"%{kw}%"
|
||||
conds.append(or_(sessions.qt_number.ilike(like), items.name.ilike(like), items.code.ilike(like)))
|
||||
# 결과(SessionResult) 필터 — _to_result 파생 규칙을 SQL WHERE 로 그대로 복제(집계·필터 일치용).
|
||||
# 1=낙찰 2=미낙찰 3=결렬(개찰). 전부 견적 마감(CLOSED) 이 전제.
|
||||
if result in (1, 2, 3):
|
||||
conds.append(quotations.status == QuotationStatus.CLOSED.value)
|
||||
if result == 1:
|
||||
conds.append(quotations.close_reason == CloseReason.AWARDED.value)
|
||||
conds.append(quotations.preferred_sp_id == sessions.supplier_id)
|
||||
elif result == 2:
|
||||
conds.append(quotations.close_reason == CloseReason.AWARDED.value)
|
||||
conds.append(or_(quotations.preferred_sp_id.is_(None), quotations.preferred_sp_id != sessions.supplier_id))
|
||||
else:
|
||||
conds.append(quotations.close_reason.in_(RENEGOTIABLE_CLOSE_REASONS))
|
||||
return conds
|
||||
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]:
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
|
||||
try:
|
||||
conds = self.__filters(supplier_id, status, qt_type)
|
||||
conds = self.__filters(supplier_id, status, qt_type, keyword, result)
|
||||
|
||||
# 정렬 규칙:
|
||||
# - order 를 명시(asc/desc)하면 그룹 구분 없이 전체를 마감 기준 한 줄로 정렬(전체 정렬).
|
||||
@@ -91,6 +131,11 @@ class SessionCRUD(ISessionCRUD):
|
||||
items.model_name,
|
||||
items.manufacturer,
|
||||
sessions.custom,
|
||||
quotations.status, # 재협상 요청 자격 판정용(마감 여부)
|
||||
quotations.close_reason, # 개찰(결렬) 사유
|
||||
quotations.round,
|
||||
quotations.preferred_sp_id, # 낙찰자(공급사) — 나와 같으면 낙찰, 다르면 미낙찰
|
||||
sessions.supplier_id, # 이 세션 소유 공급사(=조회자). 낙찰자와 대조
|
||||
)
|
||||
.join(items, items.item_id == sessions.item_id)
|
||||
.join(quotations, quotations.qt_id == sessions.quotation_id)
|
||||
@@ -107,9 +152,9 @@ class SessionCRUD(ISessionCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, []
|
||||
|
||||
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type) -> Tuple[ErrorType, int]:
|
||||
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, keyword=None, result=None) -> Tuple[ErrorType, int]:
|
||||
try:
|
||||
conds = self.__filters(supplier_id, status, qt_type)
|
||||
conds = self.__filters(supplier_id, status, qt_type, keyword, result)
|
||||
query = (
|
||||
select(func.count())
|
||||
.select_from(sessions)
|
||||
@@ -179,6 +224,32 @@ class SessionCRUD(ISessionCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
|
||||
# 같은 견적번호(체인)의 최대 차수. 이미 다음 라운드가 있으면 재협상 요청은 의미가 없다.
|
||||
try:
|
||||
query = select(func.max(quotations.round)).where(quotations.number == number, quotations.deleted == False) # noqa: E712
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, 0
|
||||
top = rows[0][0] if rows and rows[0] else None
|
||||
return ErrorType.SUCCESS, int(top or 0)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def merge_session_custom(self, cdb: AsyncSession, session_id, supplier_id, patch: dict) -> ErrorType:
|
||||
# sessions.custom 부분 갱신(기존 키 보존). 부가정보와 재협상 요청이 같은 컬럼을 쓰므로 덮어쓰면 안 된다.
|
||||
try:
|
||||
query = (
|
||||
update(sessions)
|
||||
.where(sessions.session_id == session_id, sessions.supplier_id == supplier_id)
|
||||
.values(custom=func.coalesce(sessions.custom, cast(text("'{}'"), JSONB)).op("||")(cast(patch, JSONB)))
|
||||
)
|
||||
return await DB_SESSION_MNG.add(cdb, query)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def update_session_custom(self, cdb: AsyncSession, session_id, supplier_id, custom: dict) -> ErrorType:
|
||||
# 협상완료 부가정보(sessions.custom) 저장. 본인 공급사 세션만(supplier_id 가드).
|
||||
try:
|
||||
|
||||
@@ -63,6 +63,7 @@ class Res_ChatInit(Res_WebPacketProtocol):
|
||||
session_id: str = Field("", description="협상 세션 uuid")
|
||||
session_status: int = Field(0, description="세션 상태 코드 (SessionStatus: 1=생성 2=진행중 3=완료 4=미참여 5=거부)")
|
||||
quotation_id: str = Field("", description="소속 견적 uuid")
|
||||
qt_number: str = Field("", description="견적번호(EST-...)")
|
||||
quotation_end_time: str = Field("", description="견적 마감 시각 (ISO 8601, 타이머용)")
|
||||
quotation_memo: str = Field("", description="견적 메모")
|
||||
item_id: str = Field("", description="상품 uuid")
|
||||
@@ -78,6 +79,7 @@ class Res_ChatInit(Res_WebPacketProtocol):
|
||||
item_vat_yn: Optional[bool] = Field(None, description="VAT 포함 여부(미설정 시 null)")
|
||||
item_delivery_fee_yn: Optional[bool] = Field(None, description="배송비 포함 여부(미설정 시 null)")
|
||||
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 기존 입력값(sessions.custom). 재진입 시 폼 프리필용")
|
||||
labels: dict = Field(default_factory=dict, description="회사 커스텀 라벨(companies.settings.labels). 상품 상세 필드명(예: lead_time) 치환용. 없으면 프론트 기본값")
|
||||
|
||||
|
||||
# 대화 히스토리(재진입 복원)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
@@ -15,6 +17,10 @@ class ListItem(WebPacketProtocol):
|
||||
model_name: str = Field("", description="모델명")
|
||||
maker_name: str = Field("", description="제조사")
|
||||
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 값(sessions.custom). 미입력이면 빈 dict")
|
||||
renegotiable: bool = Field(False, description="재협상 요청 가능 여부 — 낙찰 없이 마감(개찰)된 마지막 차수이고 대기 중 요청이 없을 때만 True")
|
||||
renegotiation_status: int = Field(0, description="현재 재협상 요청 상태(RenegotiationStatus). 요청 이력이 없으면 0")
|
||||
renegotiation_memo: str = Field("", description="담당자 심사 메모(반려 사유). 없으면 빈 문자열")
|
||||
result: int = Field(0, description="공급사 관점 협상 결과(SessionResult): 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰, 재협상 대상)")
|
||||
|
||||
|
||||
class Res_SessionList(Res_WebPacketProtocol):
|
||||
@@ -42,3 +48,13 @@ class Req_ExtraInfo(WebPacketProtocol):
|
||||
|
||||
class Res_ExtraInfo(Res_WebPacketProtocol):
|
||||
session_id: str = Field("", description="부가정보 저장된 세션 uuid")
|
||||
|
||||
|
||||
class Req_Renegotiation(WebPacketProtocol):
|
||||
reason: str = Field("", max_length=255, description="재협상 요청 사유(프리셋 라벨 또는 직접 입력)")
|
||||
desired_price: Optional[int] = Field(None, description="희망 공급가(원). 담당자 판단 근거로만 쓰인다")
|
||||
|
||||
|
||||
class Res_Renegotiation(Res_WebPacketProtocol):
|
||||
session_id: str = Field("", description="요청이 기록된 세션 uuid")
|
||||
status: int = Field(0, description="요청 상태(RenegotiationStatus): 1=심사중 2=승인 3=반려 4=철회")
|
||||
@@ -6,7 +6,16 @@ from fastapi.security import HTTPAuthorizationCredentials
|
||||
from common.models.gmodel import UserInfo
|
||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, security
|
||||
from services.negotiation_service import NegotiationService
|
||||
from .protocol import Req_ExtraInfo, Req_Reject, Res_ExtraInfo, Res_Participate, Res_Reject, Res_SessionList
|
||||
from .protocol import (
|
||||
Req_ExtraInfo,
|
||||
Req_Reject,
|
||||
Req_Renegotiation,
|
||||
Res_ExtraInfo,
|
||||
Res_Participate,
|
||||
Res_Reject,
|
||||
Res_Renegotiation,
|
||||
Res_SessionList,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={404: {"description": "Not found"}})
|
||||
|
||||
@@ -26,9 +35,11 @@ async def list_sessions(
|
||||
order: Optional[str] = Query(None, description="마감일 전체 정렬: asc(임박순)/desc(여유순). 미지정 시 기본 그룹 정렬('할 일' 우선 → 종료는 하단·최근순). 지정하면 그룹 없이 전체를 마감 기준으로 정렬."),
|
||||
page: int = Query(1, ge=1, description="페이지 (1부터)"),
|
||||
page_size: int = Query(20, ge=1, le=100, description="페이지당 건수 (1~100)"),
|
||||
keyword: Optional[str] = Query(None, description="검색어 — 견적번호·상품명·상품코드 부분일치(대소문자 무시)"),
|
||||
result: Optional[int] = Query(None, description="결과 필터(SessionResult): 1=낙찰 2=미낙찰 3=결렬(개찰). 미지정 시 전체"),
|
||||
):
|
||||
return RemoveNoneResponse(
|
||||
await service.list_sessions(user_info, credentials.credentials, status, qt_type, order, page, page_size)
|
||||
await service.list_sessions(user_info, credentials.credentials, status, qt_type, order, page, page_size, keyword, result)
|
||||
)
|
||||
|
||||
|
||||
@@ -77,3 +88,38 @@ async def save_extra_info(
|
||||
service: NegotiationService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.save_extra_info(user_info, credentials.credentials, session_id, req))
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/session/{session_id}/renegotiation",
|
||||
response_model=Res_Renegotiation,
|
||||
summary="재협상 요청",
|
||||
description="낙찰 없이 마감된(개찰) 건에 대해 공급사가 재협상을 요청한다. 담당자 승인 시 다음 라운드가 생성된다. 본인 공급사의 마지막 라운드 세션만 허용.",
|
||||
)
|
||||
async def request_renegotiation(
|
||||
req: Req_Renegotiation,
|
||||
session_id: str = Path(..., description="협상 세션 uuid"),
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: NegotiationService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(
|
||||
await service.request_renegotiation(user_info, credentials.credentials, session_id, req)
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
path="/session/{session_id}/renegotiation",
|
||||
response_model=Res_Renegotiation,
|
||||
summary="재협상 요청 철회",
|
||||
description="심사 대기(PENDING) 중인 본인 요청을 철회한다.",
|
||||
)
|
||||
async def cancel_renegotiation(
|
||||
session_id: str = Path(..., description="협상 세션 uuid"),
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: NegotiationService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(
|
||||
await service.cancel_renegotiation(user_info, credentials.credentials, session_id)
|
||||
)
|
||||
@@ -24,6 +24,7 @@ from common.logger import LOG
|
||||
from common.models.gmodel import UserInfo
|
||||
from crud.chat_crud import ChatCRUD, IChatCRUD
|
||||
from crud.session_crud import ISessionCRUD, SessionCRUD
|
||||
from crud.user_crud import IUserCRUD, UserCRUD
|
||||
from router.v1.chat.protocol import ChatMessage, ChatSummary, Res_ChatInit, Res_ChatMessages, Res_ChatSend
|
||||
from services.agent_client import AgentChatContext, IAgentClient, get_agent_client
|
||||
from services.auth_service import AuthService
|
||||
@@ -44,11 +45,13 @@ class ChatService:
|
||||
auth: AuthService = Depends(AuthService),
|
||||
session_crud: ISessionCRUD = Depends(SessionCRUD),
|
||||
chat_crud: IChatCRUD = Depends(ChatCRUD),
|
||||
user_crud: IUserCRUD = Depends(UserCRUD),
|
||||
agent: IAgentClient = Depends(get_agent_client),
|
||||
):
|
||||
self.auth = auth
|
||||
self.session_crud = session_crud
|
||||
self.chat_crud = chat_crud
|
||||
self.user_crud = user_crud
|
||||
self.agent = agent
|
||||
|
||||
# ---- 순수 헬퍼/매퍼 (self 불필요, 상단 집약) ----
|
||||
@@ -59,6 +62,27 @@ class ChatService:
|
||||
digits = "".join(ch for ch in text if ch.isdigit())
|
||||
return int(digits) if digits else None
|
||||
|
||||
@staticmethod
|
||||
def _parse_reject(text: Optional[str]) -> dict:
|
||||
"""통일 결렬 폼 제출 문자열 파싱 → {offer_price, reason, opinion}.
|
||||
형식: '공급희망가격-{원}, 합의불가사유-{사유}, 의견-{의견}' (사유는 '기타-{내용}' 가능).
|
||||
의견은 자유서술이라 콤마 포함 가능 → 맨 뒤 '의견-' 기준으로 먼저 떼어낸다."""
|
||||
s = text or ""
|
||||
opinion = None
|
||||
if ", 의견-" in s:
|
||||
s, opinion = s.split(", 의견-", 1)
|
||||
reason = None
|
||||
if ", 합의불가사유-" in s:
|
||||
price_part, reason = s.split(", 합의불가사유-", 1)
|
||||
else:
|
||||
price_part = s
|
||||
price_digits = "".join(ch for ch in price_part.replace("공급희망가격-", "") if ch.isdigit())
|
||||
return {
|
||||
"offer_price": int(price_digits) if price_digits else None,
|
||||
"reason": reason or None,
|
||||
"opinion": (opinion.strip() or None) if opinion is not None else None,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _in_price_range(price: int, target_price: Optional[int]) -> bool:
|
||||
if not target_price:
|
||||
@@ -214,6 +238,7 @@ class ChatService:
|
||||
res.session_id = str(sess.session_id)
|
||||
res.session_status = sess.status
|
||||
res.quotation_id = str(sess.quotation_id)
|
||||
res.qt_number = sess.qt_number or ""
|
||||
res.quotation_end_time = quote.end_time.isoformat(timespec="seconds") if quote.end_time else ""
|
||||
res.quotation_memo = quote.memo or ""
|
||||
res.item_id = str(item.item_id)
|
||||
@@ -229,6 +254,18 @@ class ChatService:
|
||||
res.item_vat_yn = item.vat_yn
|
||||
res.item_delivery_fee_yn = item.delivery_fee_yn
|
||||
res.custom = sess.custom or {}
|
||||
|
||||
# 회사 커스텀 라벨(companies.settings.labels) — 상품 상세 필드명 치환용(예: lead_time→표준납기). 실패해도 빈 dict 폴백.
|
||||
_e, settings = await DB_SESSION_MNG.execute_lambda(
|
||||
suppliers.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_company_settings(s, sess.supplier_id),
|
||||
)
|
||||
res.labels = (settings.get("labels") or {}) if _e == ErrorType.SUCCESS and settings else {}
|
||||
|
||||
# 회사가 VAT(vat_yn)를 관리하지 않으면(hidden_fields) 협상 화면 VAT 표기를 숨긴다(값 null → 프론트 라벨 생략).
|
||||
_hidden = (settings.get("hidden_fields") or []) if _e == ErrorType.SUCCESS and settings else []
|
||||
if "vat_yn" in _hidden:
|
||||
res.item_vat_yn = None
|
||||
return res
|
||||
|
||||
async def _ensure_in_progress(self, sess, quote) -> None:
|
||||
@@ -455,10 +492,15 @@ class ChatService:
|
||||
funcs.append(lambda s: self.chat_crud.finalize_session(s, sess.session_id, new_status, bid_price=bid))
|
||||
else:
|
||||
new_status = SessionStatus.REJECTED.value
|
||||
parsed = self._parse_reject(user_input)
|
||||
funcs.append(lambda s: self.chat_crud.finalize_session(
|
||||
s, sess.session_id, new_status,
|
||||
reject_reason=(user_input or None), reject_price=price,
|
||||
reject_reason=parsed["reason"], reject_price=parsed["offer_price"],
|
||||
))
|
||||
if parsed["opinion"]:
|
||||
funcs.append(lambda s, op=parsed["opinion"]: self.session_crud.merge_session_custom(
|
||||
s, sess.session_id, sess.supplier_id, {"opinion": op},
|
||||
))
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run([chats.DBType()], funcs)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
|
||||
@@ -4,12 +4,31 @@ from datetime import datetime, timezone
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import chats, sessions
|
||||
from common.enums import DBWRType, ErrorType, QuotationStatus, SessionStatus
|
||||
from common.database.model.models import chats, notifications, sessions
|
||||
from common.enums import (
|
||||
CloseReason,
|
||||
DBWRType,
|
||||
ErrorType,
|
||||
NotificationType,
|
||||
QuotationStatus,
|
||||
RENEGOTIABLE_CLOSE_REASONS,
|
||||
RenegotiationStatus,
|
||||
SessionStatus,
|
||||
)
|
||||
from common.logger import LOG
|
||||
from common.models.gmodel import UserInfo
|
||||
from crud.chat_crud import ChatCRUD, IChatCRUD
|
||||
from crud.session_crud import ISessionCRUD, SessionCRUD
|
||||
from router.v1.negotiation.protocol import ListItem, Req_ExtraInfo, Res_ExtraInfo, Res_Participate, Res_Reject, Res_SessionList
|
||||
from router.v1.negotiation.protocol import (
|
||||
ListItem,
|
||||
Req_ExtraInfo,
|
||||
Req_Renegotiation,
|
||||
Res_ExtraInfo,
|
||||
Res_Participate,
|
||||
Res_Reject,
|
||||
Res_Renegotiation,
|
||||
Res_SessionList,
|
||||
)
|
||||
from services.auth_service import AuthService
|
||||
|
||||
|
||||
@@ -32,7 +51,7 @@ class NegotiationService:
|
||||
self.session_crud = session_crud
|
||||
self.chat_crud = chat_crud
|
||||
|
||||
async def list_sessions(self, user_info: UserInfo, access_token: str, status, qt_type, order: str, page: int, page_size: int) -> Res_SessionList:
|
||||
async def list_sessions(self, user_info: UserInfo, access_token: str, status, qt_type, order: str, page: int, page_size: int, keyword: str = None, result: int = None) -> Res_SessionList:
|
||||
res = Res_SessionList()
|
||||
|
||||
# 1) 인증 (활성 + 저장된 access 토큰 대조)
|
||||
@@ -48,7 +67,7 @@ class NegotiationService:
|
||||
err_type, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.list_by_supplier(s, supplier_id, status, qt_type, order, offset, page_size),
|
||||
lambda s: self.session_crud.list_by_supplier(s, supplier_id, status, qt_type, order, offset, page_size, keyword, result),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
@@ -58,27 +77,22 @@ class NegotiationService:
|
||||
err_type, total = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.count_by_supplier(s, supplier_id, status, qt_type),
|
||||
lambda s: self.session_crud.count_by_supplier(s, supplier_id, status, qt_type, keyword, result),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
res.items = [
|
||||
ListItem(
|
||||
session_id=str(r[0]),
|
||||
session_status=r[1],
|
||||
qt_type=r[2],
|
||||
qt_number=r[3],
|
||||
qt_end_time=r[4].isoformat(timespec="seconds") if r[4] else "",
|
||||
item_code=r[5] or "",
|
||||
item_name=r[6] or "",
|
||||
model_name=r[7] or "",
|
||||
maker_name=r[8] or "",
|
||||
custom=r[9] or {},
|
||||
# 같은 견적번호(체인)의 최대 차수 — 이미 다음 라운드가 있으면 재협상 요청 대상이 아니다.
|
||||
max_rounds: dict = {}
|
||||
for number in {r[3] for r in rows if r[3]}:
|
||||
_e, mx = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s, n=number: self.session_crud.chain_max_round(s, n),
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
max_rounds[number] = mx or 0
|
||||
|
||||
res.items = [self._to_list_item(r, max_rounds) for r in rows]
|
||||
res.total = total
|
||||
res.page = page
|
||||
res.page_size = page_size
|
||||
@@ -134,6 +148,190 @@ class NegotiationService:
|
||||
res.session_id = str(session_id)
|
||||
return res
|
||||
|
||||
@staticmethod
|
||||
def _to_list_item(r, max_rounds: dict) -> ListItem:
|
||||
"""세션 행 → 목록 아이템. 재협상 요청 가능 여부는 서버가 판정해 내려준다(프론트가 규칙을 몰라도 되게)."""
|
||||
custom = r[9] or {}
|
||||
renego = custom.get("renegotiation") or {}
|
||||
status = renego.get("status") or 0
|
||||
|
||||
is_last_round = (r[12] or 0) >= max_rounds.get(r[3], 0)
|
||||
renegotiable = (
|
||||
r[10] == QuotationStatus.CLOSED.value
|
||||
and r[11] in RENEGOTIABLE_CLOSE_REASONS
|
||||
and is_last_round
|
||||
and status
|
||||
not in (
|
||||
RenegotiationStatus.PENDING.value,
|
||||
RenegotiationStatus.APPROVED.value,
|
||||
RenegotiationStatus.REJECTED.value,
|
||||
)
|
||||
)
|
||||
return ListItem(
|
||||
session_id=str(r[0]),
|
||||
session_status=r[1],
|
||||
qt_type=r[2],
|
||||
qt_number=r[3],
|
||||
qt_end_time=r[4].isoformat(timespec="seconds") if r[4] else "",
|
||||
item_code=r[5] or "",
|
||||
item_name=r[6] or "",
|
||||
model_name=r[7] or "",
|
||||
maker_name=r[8] or "",
|
||||
custom=custom,
|
||||
renegotiable=renegotiable,
|
||||
renegotiation_status=status,
|
||||
renegotiation_memo=renego.get("memo") or "",
|
||||
result=NegotiationService._to_result(r[10], r[11], r[13], r[14]),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _to_result(qt_status, close_reason, winner_id, my_id) -> int:
|
||||
"""공급사 관점 협상 결과(SessionResult). 견적 마감 전이면 0(미정).
|
||||
낙찰 건은 낙찰자가 나면 1(낙찰)·아니면 2(미낙찰), 개찰(OPEN_*) 마감은 3(결렬=재협상 대상)."""
|
||||
if qt_status != QuotationStatus.CLOSED.value:
|
||||
return 0
|
||||
if close_reason == CloseReason.AWARDED.value:
|
||||
return 1 if winner_id is not None and str(winner_id) == str(my_id) else 2
|
||||
if close_reason in RENEGOTIABLE_CLOSE_REASONS:
|
||||
return 3
|
||||
return 0
|
||||
|
||||
async def request_renegotiation(
|
||||
self, user_info: UserInfo, access_token: str, session_id_str: str, req: Req_Renegotiation
|
||||
) -> Res_Renegotiation:
|
||||
"""결렬(개찰) 마감 건에 대해 공급사가 재협상을 요청한다(IMK #15).
|
||||
전용 테이블 없이 sessions.custom.renegotiation 에 기록하고, 견적 작성자에게 알림을 남긴다."""
|
||||
res = Res_Renegotiation()
|
||||
|
||||
err_type, info, sess, quote = await self._load_renegotiable(user_info, access_token, session_id_str)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 심사 대기·승인·반려 건은 재요청을 막는다(전용 테이블이 없어 유니크 대신 여기서 검증).
|
||||
# 반려는 담당자가 이미 판단한 결과라 같은 건으로 다시 올릴 수 없다. 철회(CANCELED)만 재요청 허용.
|
||||
current = (sess.custom or {}).get("renegotiation") or {}
|
||||
if current.get("status") in (
|
||||
RenegotiationStatus.PENDING.value,
|
||||
RenegotiationStatus.APPROVED.value,
|
||||
RenegotiationStatus.REJECTED.value,
|
||||
):
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
|
||||
return res
|
||||
|
||||
payload = {
|
||||
"status": RenegotiationStatus.PENDING.value,
|
||||
"reason": (req.reason or "").strip(),
|
||||
"desired_price": req.desired_price,
|
||||
"requested_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[sessions.DBType()],
|
||||
[lambda s: self.session_crud.merge_session_custom(
|
||||
s, sess.session_id, uuid.UUID(info.supplier_id), {"renegotiation": payload}
|
||||
)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
await self._notify_renegotiation(quote, sess, info, payload)
|
||||
res.session_id = str(sess.session_id)
|
||||
res.status = RenegotiationStatus.PENDING.value
|
||||
return res
|
||||
|
||||
async def cancel_renegotiation(self, user_info: UserInfo, access_token: str, session_id_str: str) -> Res_Renegotiation:
|
||||
"""공급사가 자기 요청을 철회한다. 심사 대기(PENDING) 중에만 가능."""
|
||||
res = Res_Renegotiation()
|
||||
|
||||
err_type, info, sess, _quote = await self._load_renegotiable(user_info, access_token, session_id_str)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
current = (sess.custom or {}).get("renegotiation") or {}
|
||||
if current.get("status") != RenegotiationStatus.PENDING.value:
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
|
||||
return res
|
||||
|
||||
patch = {**current, "status": RenegotiationStatus.CANCELED.value}
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[sessions.DBType()],
|
||||
[lambda s: self.session_crud.merge_session_custom(
|
||||
s, sess.session_id, uuid.UUID(info.supplier_id), {"renegotiation": patch}
|
||||
)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
res.session_id = str(sess.session_id)
|
||||
res.status = RenegotiationStatus.CANCELED.value
|
||||
return res
|
||||
|
||||
async def _load_renegotiable(self, user_info: UserInfo, access_token: str, session_id_str: str):
|
||||
"""재협상 요청 자격 검증 — 인증 → 본인 세션 → 결렬(개찰) 마감 → 마지막 라운드.
|
||||
성공 시 (SUCCESS, info, sess, quote)."""
|
||||
err_type, info = await self.auth.authenticate(user_info, access_token)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, None, None, None
|
||||
try:
|
||||
session_id = uuid.UUID(session_id_str)
|
||||
except (ValueError, TypeError):
|
||||
return ErrorType.NEGO_NOT_FOUND, None, None, None
|
||||
|
||||
err_type, sess = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.get_session_by_id(s, session_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or sess is None:
|
||||
return ErrorType.NEGO_NOT_FOUND, None, None, None
|
||||
if str(sess.supplier_id) != info.supplier_id:
|
||||
return ErrorType.NEGO_FORBIDDEN, None, None, None
|
||||
|
||||
err_type, quote = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.get_quotation_by_id(s, sess.quotation_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or quote is None:
|
||||
return ErrorType.NEGO_NOT_FOUND, None, None, None
|
||||
|
||||
# 낙찰됐거나 아직 진행 중인 건은 요청 대상이 아니다.
|
||||
if quote.status != QuotationStatus.CLOSED.value or quote.close_reason not in RENEGOTIABLE_CLOSE_REASONS:
|
||||
return ErrorType.NEGO_NOT_PARTICIPABLE, None, None, None
|
||||
|
||||
# 이미 다음 라운드가 만들어졌으면 요청할 이유가 없다.
|
||||
_e, max_round = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.chain_max_round(s, quote.number),
|
||||
)
|
||||
if max_round and quote.round < max_round:
|
||||
return ErrorType.NEGO_NOT_PARTICIPABLE, None, None, None
|
||||
|
||||
return ErrorType.SUCCESS, info, sess, quote
|
||||
|
||||
async def _notify_renegotiation(self, quote, sess, info, payload: dict) -> None:
|
||||
"""견적 작성자 인박스에 재협상 요청 알림을 남긴다. 부가 효과라 실패해도 본 흐름을 막지 않는다."""
|
||||
notif = notifications(
|
||||
user_id=quote.user_id,
|
||||
type=NotificationType.RENEGO_REQUESTED.value,
|
||||
ref_qt_id=quote.qt_id,
|
||||
ref_session_id=sess.session_id,
|
||||
data={
|
||||
"supplier_name": info.supplier_name,
|
||||
"qt_number": quote.number,
|
||||
"qt_round": quote.round,
|
||||
"reason": payload.get("reason"),
|
||||
"desired_price": payload.get("desired_price"),
|
||||
},
|
||||
)
|
||||
err = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[notifications.DBType()],
|
||||
[lambda s: DB_SESSION_MNG.insert(s, notif, raise_error=False)],
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
LOG.e_no_callstack(f"[renego] 알림 기록 실패 qt={quote.qt_id} session={sess.session_id}")
|
||||
|
||||
async def _is_after_summary(self, session_id) -> bool:
|
||||
"""마지막 말풍선이 타결 요약(summaryRSP/CM)인지 — 즉 협상이 타결된 뒤인지."""
|
||||
err_type, (_, _, last_meta) = await DB_SESSION_MNG.execute_lambda(
|
||||
|
||||
@@ -177,6 +177,56 @@ async def test_list_requires_auth(client):
|
||||
assert (await client.get("/v1/negotiation/sessions")).status_code in (401, 403)
|
||||
|
||||
|
||||
# ---- 검색(keyword) ----------------------------------------------------------
|
||||
async def test_search_by_qt_number_and_item_code(client, nego_seed):
|
||||
"""검증: 견적번호/상품코드가 같은 값(PYTESTNEGO-B)으로 검색.
|
||||
기대결과: B 1건만, total 도 1(카운트도 같은 필터 적용)."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, keyword=f"{MARK}B")).json()
|
||||
assert body["total"] == 1
|
||||
assert [i["item_code"] for i in body["items"]] == [f"{MARK}B"]
|
||||
|
||||
|
||||
async def test_search_by_item_name(client, nego_seed):
|
||||
"""검증: 상품명 일부('상품 A')로 검색.
|
||||
기대결과: A 1건만."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, keyword="상품 A")).json()
|
||||
assert {i["item_code"] for i in body["items"]} == {f"{MARK}A"}
|
||||
|
||||
|
||||
async def test_search_prefix_matches_all_own(client, nego_seed):
|
||||
"""검증: 공통 prefix(PYTESTNEGO)로 검색.
|
||||
기대결과: 본인 공급사 3건 전부(타 공급사 X 는 제외 유지)."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, keyword=MARK.rstrip("-"))).json()
|
||||
assert body["total"] == 3
|
||||
|
||||
|
||||
async def test_search_case_insensitive(client, nego_seed):
|
||||
"""검증: 소문자로 검색(pytestnego-c).
|
||||
기대결과: ILIKE 라 대소문자 무시하고 C 매칭."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, keyword=f"{MARK}c".lower())).json()
|
||||
assert {i["item_code"] for i in body["items"]} == {f"{MARK}C"}
|
||||
|
||||
|
||||
async def test_search_no_match_returns_empty(client, nego_seed):
|
||||
"""검증: 어디에도 없는 검색어.
|
||||
기대결과: 0건, total 0."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, keyword="존재하지않는검색어zzz")).json()
|
||||
assert body["total"] == 0 and body["items"] == []
|
||||
|
||||
|
||||
async def test_search_wildcard_is_escaped(client, nego_seed):
|
||||
"""검증: ILIKE 와일드카드('%')를 그대로 검색 — 패턴으로 새면 전건 매칭될 위험.
|
||||
기대결과: escape 되어 리터럴 '%' 로 취급 → 매칭 0건."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, keyword="%")).json()
|
||||
assert body["total"] == 0
|
||||
|
||||
|
||||
# ---- 참여 -------------------------------------------------------------------
|
||||
async def test_participate_success(client, nego_seed, db_engine):
|
||||
token = await _login_token(client)
|
||||
@@ -294,3 +344,76 @@ async def test_reject_requires_auth(client, nego_seed):
|
||||
sid = nego_seed["sids"]["B"]
|
||||
r = await client.post(f"/v1/negotiation/sessions/{sid}/reject", json={"reject_reason": "사유"})
|
||||
assert r.status_code in (401, 403)
|
||||
|
||||
|
||||
# ---- 결과 필터(result) ------------------------------------------------------
|
||||
# 마감(CLOSED) + 마감사유/낙찰자로 낙찰(1)·미낙찰(2)·결렬(3)을 만들고 result= 로 거른다.
|
||||
# nego_seed 의 공급사/로그인을 재사용하고, MARK prefix 라 픽스처 teardown 이 함께 정리한다.
|
||||
async def _seed_result_row(engine, *, supplier_id, code, close_reason, winner_id):
|
||||
import uuid as _uuid
|
||||
item_id, qt_id, session_id = _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4()
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text("INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) "
|
||||
"VALUES (:iid, gen_random_uuid(), gen_random_uuid(), :name, :code, 'M', '제조사')"),
|
||||
{"iid": item_id, "name": f"상품 {code}", "code": f"{MARK}{code}"},
|
||||
)
|
||||
await conn.execute(
|
||||
text("INSERT INTO quotation.quotations "
|
||||
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, close_reason, "
|
||||
" preferred_sp_id, round, start_time, end_time) VALUES "
|
||||
"(:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, 2, 3, :cr, "
|
||||
" :win, 1, now() - make_interval(hours => 2), now() - make_interval(hours => 1))"),
|
||||
{"qid": qt_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "cr": close_reason, "win": winner_id},
|
||||
)
|
||||
await conn.execute(
|
||||
text("INSERT INTO negotiation.sessions "
|
||||
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
|
||||
" target_price, status, bid_price, end_time) VALUES "
|
||||
"(:sid, :qid, :iid, :sup, :num, 1, 2, 100000, 3, 95000, now() - make_interval(hours => 1))"),
|
||||
{"sid": session_id, "qid": qt_id, "iid": item_id, "sup": supplier_id, "num": f"{MARK}{code}"},
|
||||
)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def result_rows(nego_seed, db_engine):
|
||||
"""nego_seed 공급사에 낙찰/미낙찰/결렬 각 1건을 추가한다(개찰 5=OPEN_PRICE, 1=AWARDED)."""
|
||||
sup = nego_seed["supplier_id"]
|
||||
await _seed_result_row(db_engine, supplier_id=sup, code="RWON", close_reason=1, winner_id=sup) # 낙찰(나)
|
||||
await _seed_result_row(db_engine, supplier_id=sup, code="RLOST", close_reason=1, winner_id=uuid.uuid4()) # 미낙찰(남)
|
||||
await _seed_result_row(db_engine, supplier_id=sup, code="ROPEN", close_reason=5, winner_id=None) # 결렬(개찰)
|
||||
return nego_seed
|
||||
|
||||
|
||||
async def test_result_filter_won(client, result_rows):
|
||||
"""검증: result=1(낙찰)로 필터. 기대결과: 낙찰 건만, total=1."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, result=1)).json()
|
||||
assert body["total"] == 1
|
||||
assert body["items"][0]["item_code"] == f"{MARK}RWON"
|
||||
assert body["items"][0]["result"] == 1
|
||||
|
||||
|
||||
async def test_result_filter_lost(client, result_rows):
|
||||
"""검증: result=2(미낙찰)로 필터. 기대결과: 미낙찰 건만."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, result=2)).json()
|
||||
assert {i["item_code"] for i in body["items"]} == {f"{MARK}RLOST"}
|
||||
assert body["items"][0]["result"] == 2
|
||||
|
||||
|
||||
async def test_result_filter_open(client, result_rows):
|
||||
"""검증: result=3(결렬)로 필터. 기대결과: 개찰 결렬 건만 + 재협상 대상(renegotiable=True)."""
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, result=3)).json()
|
||||
assert {i["item_code"] for i in body["items"]} == {f"{MARK}ROPEN"}
|
||||
assert body["items"][0]["result"] == 3
|
||||
assert body["items"][0]["renegotiable"] is True
|
||||
|
||||
|
||||
async def test_result_filter_composes_with_paging(client, result_rows):
|
||||
"""검증: 결과 필터가 total(페이징)에 반영. 기대결과: result=1 이면 total=1(전체 목록과 별개)."""
|
||||
token = await _login_token(client)
|
||||
all_total = (await _list(client, token)).json()["total"]
|
||||
won_total = (await _list(client, token, result=1)).json()["total"]
|
||||
assert won_total == 1 and all_total > won_total
|
||||
@@ -0,0 +1,215 @@
|
||||
"""공급사 재협상 요청/철회(IMK #15) 포털 e2e — 요청 접수 + 철회.
|
||||
|
||||
담당자 심사(승인/반려)는 negodata 백엔드 몫이고, 여기(포털)는 공급사가
|
||||
sessions.custom.renegotiation 에 요청을 남기고(PENDING) 스스로 철회(CANCELED)하는 절반을 본다:
|
||||
· 개찰(OPEN_*) 마감 + 본인 마지막 라운드 세션 → 요청 기록(PENDING) + 담당자 알림
|
||||
· 낙찰(AWARDED) 건 → 요청 거부
|
||||
· 남의 공급사 세션 → 거부(FORBIDDEN)
|
||||
· 이미 대기 중인데 재요청 → 거부(중복 방지)
|
||||
· 대기 중 철회 → CANCELED, 이후 재요청 허용
|
||||
|
||||
dev negosium_db 를 그대로 쓰므로(APP_ENV=local) 전용 테스트 행만 시드하고 끝나면 지운다.
|
||||
"""
|
||||
import uuid
|
||||
|
||||
import bcrypt
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.enums import CloseReason, QuotationStatus, RenegotiationStatus, SessionStatus
|
||||
|
||||
TEST_LOGIN_ID = "pytest_renego_user"
|
||||
TEST_PW = "pytest1234"
|
||||
TEST_SUPPLIER_NAME = "파이테스트재협상공급사"
|
||||
MARK = "PYTESTRENEGO-" # 시드 식별용 prefix (item code / qt number)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def renego_seed(db_engine):
|
||||
"""공급사 + 로그인유저 + 재협상 후보 세션들을 시드하고 (supplier_id, sids, uids) 반환.
|
||||
|
||||
(code, quotation.status, close_reason, 소속 공급사) — 요청 자격은 견적 마감사유·소유로 갈린다.
|
||||
"""
|
||||
supplier_id = uuid.uuid4()
|
||||
other_supplier_id = uuid.uuid4()
|
||||
pw_hash = bcrypt.hashpw(TEST_PW.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
specs = [
|
||||
("OPEN", QuotationStatus.CLOSED.value, CloseReason.OPEN_PRICE.value, supplier_id), # 개찰 → 요청 가능
|
||||
("AWARD", QuotationStatus.CLOSED.value, CloseReason.AWARDED.value, supplier_id), # 낙찰 → 불가
|
||||
("OTHER", QuotationStatus.CLOSED.value, CloseReason.OPEN_PRICE.value, other_supplier_id), # 남의 공급사
|
||||
]
|
||||
sids, uids = {}, {}
|
||||
|
||||
async def _cleanup(conn):
|
||||
await conn.execute(text(f"DELETE FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%'"))
|
||||
await conn.execute(text(f"DELETE FROM company.notifications WHERE ref_qt_id IN "
|
||||
f"(SELECT qt_id FROM quotation.quotations WHERE number LIKE '{MARK}%')"))
|
||||
await conn.execute(text(f"DELETE FROM quotation.quotations WHERE number LIKE '{MARK}%'"))
|
||||
await conn.execute(text(f"DELETE FROM partner.items WHERE code LIKE '{MARK}%'"))
|
||||
await conn.execute(text("DELETE FROM supplier.supplier_users WHERE id = :id"), {"id": TEST_LOGIN_ID})
|
||||
await conn.execute(text("DELETE FROM partner.suppliers WHERE name = :n"), {"n": TEST_SUPPLIER_NAME})
|
||||
|
||||
async with db_engine.begin() as conn:
|
||||
await _cleanup(conn)
|
||||
await conn.execute(
|
||||
text("INSERT INTO partner.suppliers (supplier_id, company_id, user_id, name) "
|
||||
"VALUES (:sid, gen_random_uuid(), gen_random_uuid(), :name)"),
|
||||
{"sid": supplier_id, "name": TEST_SUPPLIER_NAME},
|
||||
)
|
||||
await conn.execute(
|
||||
text("INSERT INTO supplier.supplier_users (supplier_id, id, password, name, last_accessed_at, status, role) "
|
||||
"VALUES (:sid, :id, :pw, '협상담당자', now(), 1, 1)"),
|
||||
{"sid": supplier_id, "id": TEST_LOGIN_ID, "pw": pw_hash},
|
||||
)
|
||||
for code, quote_st, close_reason, sup in specs:
|
||||
item_id, qt_id, session_id, user_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
|
||||
sids[code], uids[code] = session_id, user_id
|
||||
await conn.execute(
|
||||
text("INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) "
|
||||
"VALUES (:iid, gen_random_uuid(), gen_random_uuid(), :name, :code, :model, '테스트제조사')"),
|
||||
{"iid": item_id, "name": f"상품 {code}", "code": f"{MARK}{code}", "model": f"MODEL-{code}"},
|
||||
)
|
||||
await conn.execute(
|
||||
text("INSERT INTO quotation.quotations "
|
||||
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, close_reason, "
|
||||
" round, start_time, end_time) VALUES "
|
||||
"(:qid, :uid, gen_random_uuid(), gen_random_uuid(), :name, :num, 2, :st, :cr, "
|
||||
" 1, now() - make_interval(hours => 2), now() - make_interval(hours => 1))"),
|
||||
{"qid": qt_id, "uid": user_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "st": quote_st, "cr": close_reason},
|
||||
)
|
||||
await conn.execute(
|
||||
text("INSERT INTO negotiation.sessions "
|
||||
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
|
||||
" target_price, status, bid_price, end_time) VALUES "
|
||||
"(:sesid, :qid, :iid, :sup, :qtn, 1, 2, 100000, :sst, 95000, now() - make_interval(hours => 1))"),
|
||||
{"sesid": session_id, "qid": qt_id, "iid": item_id, "sup": sup, "qtn": f"{MARK}{code}", "sst": SessionStatus.DONE.value},
|
||||
)
|
||||
|
||||
yield {"supplier_id": supplier_id, "sids": sids, "uids": uids}
|
||||
|
||||
async with db_engine.begin() as conn:
|
||||
await _cleanup(conn)
|
||||
|
||||
|
||||
async def _login_token(client):
|
||||
r = await client.post("/v1/auth/login", json={"id": TEST_LOGIN_ID, "pw": TEST_PW})
|
||||
return r.json()["access_token"]
|
||||
|
||||
|
||||
async def _request(client, token, session_id, *, reason="가격 재검토", desired_price=90000):
|
||||
return await client.post(
|
||||
f"/v1/negotiation/session/{session_id}/renegotiation",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
json={"reason": reason, "desired_price": desired_price},
|
||||
)
|
||||
|
||||
|
||||
async def _cancel(client, token, session_id):
|
||||
return await client.delete(
|
||||
f"/v1/negotiation/session/{session_id}/renegotiation",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
|
||||
|
||||
async def _renego(db_engine, session_id):
|
||||
async with db_engine.begin() as conn:
|
||||
row = (await conn.execute(
|
||||
text("SELECT custom FROM negotiation.sessions WHERE session_id = :sid"),
|
||||
{"sid": session_id},
|
||||
)).scalar()
|
||||
return (row or {}).get("renegotiation") or {}
|
||||
|
||||
|
||||
async def _notif_count(db_engine, qt_number):
|
||||
async with db_engine.begin() as conn:
|
||||
return (await conn.execute(
|
||||
text("SELECT count(*) FROM company.notifications WHERE ref_qt_id IN "
|
||||
"(SELECT qt_id FROM quotation.quotations WHERE number = :num)"),
|
||||
{"num": qt_number},
|
||||
)).scalar()
|
||||
|
||||
|
||||
# ---- 요청 -------------------------------------------------------------------
|
||||
async def test_request_records_pending(client, renego_seed, db_engine):
|
||||
"""검증: 개찰(OPEN_PRICE) 마감 + 본인 마지막 라운드 세션에 재협상 요청.
|
||||
기대결과: success + PENDING 기록(사유·희망가 저장) + 담당자 알림 1건."""
|
||||
token = await _login_token(client)
|
||||
sid = renego_seed["sids"]["OPEN"]
|
||||
|
||||
body = (await _request(client, token, sid, reason="원자재 인상 반영", desired_price=88000)).json()
|
||||
|
||||
assert body["result"]["success"] is True
|
||||
assert body["status"] == RenegotiationStatus.PENDING.value
|
||||
saved = await _renego(db_engine, sid)
|
||||
assert saved["status"] == RenegotiationStatus.PENDING.value
|
||||
assert saved["reason"] == "원자재 인상 반영"
|
||||
assert saved["desired_price"] == 88000
|
||||
assert await _notif_count(db_engine, f"{MARK}OPEN") == 1
|
||||
|
||||
|
||||
async def test_request_twice_blocked(client, renego_seed, db_engine):
|
||||
"""검증: 이미 대기(PENDING) 요청이 있는 세션에 다시 요청.
|
||||
기대결과: 2번째는 거부(중복 방지) + 상태는 여전히 PENDING 1건."""
|
||||
token = await _login_token(client)
|
||||
sid = renego_seed["sids"]["OPEN"]
|
||||
|
||||
first = (await _request(client, token, sid)).json()
|
||||
second = (await _request(client, token, sid)).json()
|
||||
|
||||
assert first["result"]["success"] is True
|
||||
assert second["result"]["success"] is False
|
||||
assert (await _renego(db_engine, sid))["status"] == RenegotiationStatus.PENDING.value
|
||||
|
||||
|
||||
async def test_request_blocked_on_awarded(client, renego_seed, db_engine):
|
||||
"""검증: 낙찰(AWARDED)로 마감된 건에 재협상 요청.
|
||||
기대결과: 거부(낙찰 건은 재협상 불가) + custom.renegotiation 미기록."""
|
||||
token = await _login_token(client)
|
||||
sid = renego_seed["sids"]["AWARD"]
|
||||
|
||||
body = (await _request(client, token, sid)).json()
|
||||
|
||||
assert body["result"]["success"] is False
|
||||
assert await _renego(db_engine, sid) == {}
|
||||
|
||||
|
||||
async def test_request_forbidden_other_supplier(client, renego_seed, db_engine):
|
||||
"""검증: 다른 공급사 소유 세션에 재협상 요청.
|
||||
기대결과: 거부 + custom.renegotiation 미기록(소유 가드)."""
|
||||
token = await _login_token(client)
|
||||
sid = renego_seed["sids"]["OTHER"]
|
||||
|
||||
body = (await _request(client, token, sid)).json()
|
||||
|
||||
assert body["result"]["success"] is False
|
||||
assert await _renego(db_engine, sid) == {}
|
||||
|
||||
|
||||
# ---- 철회 -------------------------------------------------------------------
|
||||
async def test_cancel_sets_canceled_and_allows_rerequest(client, renego_seed, db_engine):
|
||||
"""검증: 대기 중 요청을 철회한 뒤 다시 요청.
|
||||
기대결과: 철회 시 CANCELED → 재요청 시 다시 PENDING(철회 건은 재요청 허용)."""
|
||||
token = await _login_token(client)
|
||||
sid = renego_seed["sids"]["OPEN"]
|
||||
|
||||
await _request(client, token, sid)
|
||||
cancelled = (await _cancel(client, token, sid)).json()
|
||||
assert cancelled["result"]["success"] is True
|
||||
assert cancelled["status"] == RenegotiationStatus.CANCELED.value
|
||||
assert (await _renego(db_engine, sid))["status"] == RenegotiationStatus.CANCELED.value
|
||||
|
||||
again = (await _request(client, token, sid)).json()
|
||||
assert again["result"]["success"] is True
|
||||
assert (await _renego(db_engine, sid))["status"] == RenegotiationStatus.PENDING.value
|
||||
|
||||
|
||||
async def test_cancel_requires_pending(client, renego_seed, db_engine):
|
||||
"""검증: 대기 요청이 없는 세션에 철회 시도.
|
||||
기대결과: 거부(철회할 대기 요청 없음)."""
|
||||
token = await _login_token(client)
|
||||
sid = renego_seed["sids"]["OPEN"]
|
||||
|
||||
body = (await _cancel(client, token, sid)).json()
|
||||
|
||||
assert body["result"]["success"] is False
|
||||
@@ -0,0 +1,51 @@
|
||||
"""공급사 관점 협상 결과 파생(SessionResult) 단위 테스트.
|
||||
|
||||
목록의 result 코드는 견적 마감상태·마감사유·낙찰자로 파생한다(DDL 무변경). 공급사가 이 배지로
|
||||
'내가 낙찰인지 / 결렬이라 재협상 요청 대상인지'를 구분한다. 결렬(3)만 renegotiable 과 짝을 이룬다.
|
||||
"""
|
||||
import uuid
|
||||
|
||||
from common.enums import CloseReason, QuotationStatus
|
||||
from services.negotiation_service import NegotiationService
|
||||
|
||||
_R = NegotiationService._to_result
|
||||
ME = uuid.uuid4()
|
||||
OTHER = uuid.uuid4()
|
||||
CLOSED = QuotationStatus.CLOSED.value
|
||||
|
||||
|
||||
def test_result_undecided_before_close():
|
||||
"""검증: 견적이 아직 마감 전(진행중)이면 결과 미정.
|
||||
기대결과: 0(미정)."""
|
||||
assert _R(QuotationStatus.IN_PROGRESS.value, None, None, ME) == 0
|
||||
|
||||
|
||||
def test_result_won_when_winner_is_me():
|
||||
"""검증: 낙찰(AWARDED) 마감 + 낙찰자가 나.
|
||||
기대결과: 1(낙찰)."""
|
||||
assert _R(CLOSED, CloseReason.AWARDED.value, ME, ME) == 1
|
||||
|
||||
|
||||
def test_result_lost_when_winner_is_other():
|
||||
"""검증: 낙찰 마감이지만 낙찰자가 남.
|
||||
기대결과: 2(미낙찰)."""
|
||||
assert _R(CLOSED, CloseReason.AWARDED.value, OTHER, ME) == 2
|
||||
|
||||
|
||||
def test_result_lost_when_awarded_without_winner_id():
|
||||
"""검증: 낙찰인데 낙찰자 id 가 비어 나와 대조 불가.
|
||||
기대결과: 2(미낙찰) — 낙찰이라 단정 못 하면 낙찰로 오인시키지 않는다."""
|
||||
assert _R(CLOSED, CloseReason.AWARDED.value, None, ME) == 2
|
||||
|
||||
|
||||
def test_result_open_is_renegotiable():
|
||||
"""검증: 개찰(OPEN_*) 4종으로 마감(낙찰자 미정=결렬).
|
||||
기대결과: 전부 3(결렬) — 재협상 요청 대상."""
|
||||
for cr in (CloseReason.OPEN_PRICE, CloseReason.OPEN_EQUAL, CloseReason.OPEN_NOSHOW, CloseReason.OPEN_REJECT):
|
||||
assert _R(CLOSED, cr.value, None, ME) == 3, cr
|
||||
|
||||
|
||||
def test_result_none_when_closed_without_reason():
|
||||
"""검증: 마감됐지만 close_reason 이 아직 없음(경계).
|
||||
기대결과: 0(미정) — 낙찰/결렬 어느 쪽도 아님."""
|
||||
assert _R(CLOSED, None, None, ME) == 0
|
||||
@@ -0,0 +1,214 @@
|
||||
services:
|
||||
# ── 프론트 (React/Vite → 정적 빌드 → nginx) ──────────────────────────────
|
||||
negodata-front:
|
||||
build:
|
||||
context: ./negodata/front
|
||||
dockerfile: Dockerfile.prod
|
||||
container_name: negodata-front
|
||||
ports:
|
||||
- "${NEGODATA_FRONT_PORT:-30012}:80"
|
||||
depends_on:
|
||||
- negodata-backend # nginx 가 시작 시 upstream(negodata-backend) 이름을 해석해야 함
|
||||
restart: unless-stopped
|
||||
|
||||
negosium-front:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile.prod
|
||||
container_name: negosium-front
|
||||
ports:
|
||||
- "${NEGOSIUM_FRONT_PORT:-30010}:80"
|
||||
depends_on:
|
||||
- negosium-backend
|
||||
restart: unless-stopped
|
||||
|
||||
# ── 솔루션 랜딩 (React Router SSG → 정적 빌드 → nginx) ───────────────────
|
||||
landing:
|
||||
build:
|
||||
context: ./landing
|
||||
dockerfile: Dockerfile.prod
|
||||
container_name: negosium-landing
|
||||
ports:
|
||||
- "${LANDING_PORT:-30013}:80"
|
||||
restart: unless-stopped
|
||||
|
||||
# ── 백엔드 (FastAPI, 기존 Dockerfile) ────────────────────────────────────
|
||||
negodata-backend:
|
||||
build: ./negodata/backend
|
||||
container_name: negodata-backend
|
||||
environment:
|
||||
APP_ENV: prod
|
||||
SCHEDULER_ENABLED: "1" # 견적 자동마감 크론(process_count=1 단일 워커라 중복 없음)
|
||||
PYTHONUNBUFFERED: "1"
|
||||
LPS_BASE_URL: http://lps-api:9600 # 최저가 검색요청 enqueue — 같은 compose 망의 lps-api 컨테이너(미설정 시 localhost:9600 → 연결실패)
|
||||
# LPS 읽기 DB(lps_db)는 config.prod.toml 의 [LpsDBConfig](172.30.1.36/o2o_db_admin) 이 담당 → 별도 env 불필요
|
||||
DB_HOST: ${DB_HOST} # toml 의 127.0.0.1 을 외부 DB 로 override
|
||||
DB_PORT: ${DB_PORT:-5432}
|
||||
DB_USER: ${DB_USER}
|
||||
DB_PASSWORD: ${DB_PASSWORD}
|
||||
DB_NAME: ${DB_NAME:-negosium_db}
|
||||
volumes:
|
||||
- ./negodata/backend/config/config.prod.toml:/app/config/config.prod.toml:ro
|
||||
# 외부 비노출 — negodata-front 의 nginx 가 /v1 을 내부망으로 프록시.
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway" # DB 가 이 서버 호스트면 DB_HOST=host.docker.internal
|
||||
restart: unless-stopped
|
||||
|
||||
negosium-backend:
|
||||
build: ./backend
|
||||
container_name: negosium-backend
|
||||
environment:
|
||||
APP_ENV: prod
|
||||
AGENT_BASE_URL: http://agent:9500 # 내부망으로 agent 호출
|
||||
PYTHONUNBUFFERED: "1"
|
||||
DB_HOST: ${DB_HOST}
|
||||
DB_PORT: ${DB_PORT:-5432}
|
||||
DB_USER: ${DB_USER}
|
||||
DB_PASSWORD: ${DB_PASSWORD}
|
||||
DB_NAME: ${DB_NAME:-negosium_db}
|
||||
volumes:
|
||||
- ./backend/config/config.prod.toml:/app/config/config.prod.toml:ro
|
||||
# 외부 비노출 — negosium-front 의 nginx 가 /v1 을 내부망으로 프록시.
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
restart: unless-stopped
|
||||
|
||||
# ── 협상 에이전트 (Python, 내부 전용) ────────────────────────────────────
|
||||
agent:
|
||||
build: ./agent
|
||||
container_name: negosium-agent
|
||||
environment:
|
||||
APP_ENV: prod
|
||||
PYTHONUNBUFFERED: "1"
|
||||
DB_HOST: ${DB_HOST}
|
||||
DB_PORT: ${DB_PORT:-5432}
|
||||
DB_USER: ${DB_USER}
|
||||
DB_PASSWORD: ${DB_PASSWORD}
|
||||
DB_NAME: ${DB_NAME:-negosium_db}
|
||||
volumes:
|
||||
- ./agent/config/config.prod.toml:/app/config/config.prod.toml:ro
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
restart: unless-stopped
|
||||
|
||||
# ── 앵커링 값 자동 조정 배치 (negosium_db 공유, 포트 없음 — 상주 스케줄러) ──
|
||||
# 이미지는 config.{APP_ENV}.toml 을 읽는다(dev/prod 는 파일 없으면 기동 중단). DB/시크릿은
|
||||
# config.prod.toml(172.30.1.36) 에서 온다 — env(DB_*/REDIS_*) 를 설정하면 파일값을 override.
|
||||
anchoring:
|
||||
build: ./schedules/anchoring
|
||||
container_name: anchoring
|
||||
environment:
|
||||
APP_ENV: prod # → config.prod.toml 선택 (local 로 두면 빈 config.local 로 기동 실패)
|
||||
REDIS_HOST: anchoring-redis # 전용 캐시 컨테이너 사용(config 의 redis host 를 override)
|
||||
TZ: Asia/Seoul
|
||||
volumes:
|
||||
- ./schedules/anchoring/config.prod.toml:/app/config.prod.toml:ro # DB 접속·시크릿은 파일에서(마운트 필수)
|
||||
depends_on:
|
||||
- anchoring-redis
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
restart: unless-stopped
|
||||
logging: # 상주 배치 — 장기 운영 디스크 보호
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "5"
|
||||
|
||||
# 앵커링 조회 캐시 (anchoring 전용)
|
||||
anchoring-redis:
|
||||
image: redis:7-alpine
|
||||
container_name: anchoring-redis
|
||||
ports:
|
||||
- "127.0.0.1:6380:6379" # 호스트 로컬만 개방 (무인증 Redis). 6380 = 호스트 redis(6379)와 충돌 회피
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "5"
|
||||
|
||||
# ── LPS (인터넷 최저가 검색) ──────────────────────────────────
|
||||
# API(요청 접수) + 워커(크롤, Chromium+Xvfb).
|
||||
# 이미지는 APP_ENV=local 고정 → config.local.toml 을 읽는다. prod 실값(DB 172.30.1.36 /
|
||||
# o2o_db_admin / negosium_db + OpenAI·Naver·Decodo 시크릿)은 config.prod.toml 을 그 경로에
|
||||
# 마운트해 주입한다(다른 prod 서비스와 동일한 파일 기반 방식). DB_* env 는 주지 않는다 —
|
||||
# 주면 파일값을 빈 값/오타로 덮어써 인증 실패(예: 사용자 o2oadmin)한다.
|
||||
lps-api:
|
||||
build:
|
||||
context: ./lps
|
||||
dockerfile: Dockerfile
|
||||
container_name: lps-api
|
||||
environment:
|
||||
APP_ENV: local # 이미지 고정값 — 변경 금지(config.prod.toml 을 직접 읽지 않음)
|
||||
PYTHONUNBUFFERED: "1"
|
||||
PROCESS_COUNT: ${LPS_API_PROCESS_COUNT:-1}
|
||||
DB_CONNECTION_BUDGET: ${LPS_DB_CONNECTION_BUDGET:-40} # 전용 PG(max_connections≈100)면 90 근처로 상향
|
||||
volumes:
|
||||
- ./lps/config/config.prod.toml:/app/config/config.local.toml:ro # prod DB·시크릿 주입(APP_ENV=local 이 읽는 경로 덮어씀)
|
||||
ports:
|
||||
- "9600:9600"
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
labels:
|
||||
autoheal: "true" # HEALTHCHECK 실패 시 autoheal 이 재시작
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
lps-worker:
|
||||
build:
|
||||
context: ./lps
|
||||
dockerfile: Dockerfile.worker # Chromium + Xvfb (headless 는 안티봇에 탐지됨)
|
||||
container_name: lps-worker
|
||||
environment:
|
||||
APP_ENV: local # 이미지 고정값 — 변경 금지
|
||||
PYTHONUNBUFFERED: "1"
|
||||
WORKER_CONCURRENCY: "1" # 상품 동시 검색 수(워커별 브라우저 세트, Chrome 4×N)
|
||||
LPS_PROFILE_DIR: /profiles # Chrome 프로필을 영속 볼륨에 → 재시작해도 cf_clearance 유지
|
||||
# DB·시크릿(OpenAI/Naver/Decodo)은 아래 config.prod.toml 마운트에서 온다. env override 는 주지 않는다.
|
||||
volumes:
|
||||
- ./lps/config/config.prod.toml:/app/config/config.local.toml:ro # prod DB·시크릿 주입(APP_ENV=local 이 읽는 경로 덮어씀)
|
||||
- lps-profiles:/profiles # Chrome 프로필(쿠키) 영속
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
shm_size: "1gb" # Chrome 는 /dev/shm 을 많이 씀 — 부족하면 탭 크래시
|
||||
stop_grace_period: 75s # graceful 종료 유예 — 기본 10s 면 하던 잡 마무리 전에 SIGKILL
|
||||
labels:
|
||||
autoheal: "true" # 하트비트 HEALTHCHECK 실패(행/좀비) 시 autoheal 이 재시작
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# LPS 관리자 UI (정적 React → nginx). /v1·/healthz·/readyz 는 nginx 가 lps-api:9600 으로 프록시(동일 compose 망).
|
||||
lps-admin:
|
||||
build:
|
||||
context: ./lps-admin
|
||||
dockerfile: Dockerfile
|
||||
container_name: lps-admin
|
||||
ports:
|
||||
- "${LPS_ADMIN_PORT:-30014}:80"
|
||||
depends_on:
|
||||
- lps-api
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# HEALTHCHECK 실패 컨테이너 자동 재시작 — autoheal 라벨 붙은 컨테이너(lps-api/lps-worker)를 감시해 재시작.
|
||||
# docker.sock 마운트 = 도커 제어 권한이므로 신뢰 환경에서만 사용.
|
||||
autoheal:
|
||||
image: willfarrell/autoheal:latest
|
||||
container_name: autoheal
|
||||
environment:
|
||||
AUTOHEAL_CONTAINER_LABEL: autoheal
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
volumes:
|
||||
lps-profiles:
|
||||
+32
-33
@@ -10,6 +10,8 @@
|
||||
# 솔루션 랜딩: http://localhost:3100
|
||||
# agent 서버: http://localhost:9500/docs
|
||||
# anchoring 배치: 포트 없음 — 상주 스케줄러(격주 토 00:00 KST), docker logs anchoring 으로 확인
|
||||
# lps API: http://localhost:9600/docs
|
||||
# lps admin: http://localhost:3400 (nginx → /v1·/healthz 는 lps-api 로 프록시)
|
||||
#
|
||||
# DB 준비(최초 1회): postgres-init 의 SQL 을 대상 DB 에 적용한다.
|
||||
# psql -h <host> -p <port> -U <user> -f postgres-init/00-init.sql (스키마 전체: negosium_db + 도메인·learning·anchoring schema)
|
||||
@@ -42,6 +44,7 @@ services:
|
||||
# ── LPS(인터넷 최저가) 연동 — 미설정이면 연동 비활성으로 조용히 동작 ──
|
||||
LPS_DB_HOST: host.docker.internal # lps_db 읽기전용(수집 배치·조회 API)
|
||||
LPS_BASE_URL: http://host.docker.internal:9600 # 검색요청 enqueue. lps-api 컨테이너 사용 시 http://lps-api:9600
|
||||
# LPS API guard 키는 negodata 의 config.local.toml [WebServerConfig].lps_api_key 로 관리(개발은 빈값=개방)
|
||||
volumes:
|
||||
- ./negodata/backend:/app # 호스트 소스 = 컨테이너 코드. 이게 있어야 수정이 즉시 반영됨
|
||||
ports:
|
||||
@@ -129,10 +132,7 @@ services:
|
||||
max-size: "10m"
|
||||
max-file: "5"
|
||||
|
||||
# ── LPS (인터넷 최저가 검색) ──────────────────────────────────
|
||||
# API(요청 접수, lean) + 워커(크롤, 헤드풀 Chromium+Xvfb). DB 는 외부(host.docker.internal).
|
||||
# 이미지엔 시크릿이 없다(example config 로 빌드) — 실값은 아래 env 로 주입.
|
||||
# 시크릿 값은 리포 루트 .env 파일에 채운다(.env.example 참고, .env 는 미커밋).
|
||||
# LPS API (인터넷 최저가 검색 — 요청 접수/조회, lean). 설정·시크릿은 config.local.toml 하나(미커밋, 마운트).
|
||||
lps-api:
|
||||
build:
|
||||
context: ./lps
|
||||
@@ -140,18 +140,12 @@ services:
|
||||
container_name: lps-api
|
||||
environment:
|
||||
APP_ENV: local
|
||||
DB_HOST: host.docker.internal # 컨테이너→호스트 DB (example toml 의 127.0.0.1 override)
|
||||
DB_USER: ${LPS_DB_USER:-postgres}
|
||||
DB_PASSWORD: ${LPS_DB_PASSWORD:-postgres}
|
||||
DB_HOST: ${LPS_DB_HOST-host.docker.internal} # 컨테이너→호스트 DB (config.local.toml 의 127.0.0.1 override)
|
||||
PYTHONUNBUFFERED: "1"
|
||||
# 멀티코어: PROCESS_COUNT(uvicorn 워커=코어수)를 올리면 커넥션 풀은 자동 산정된다.
|
||||
# (pool+overflow)×2엔진×PROCESS_COUNT ≤ DB_CONNECTION_BUDGET 를 config 가 스스로 보장.
|
||||
# 값은 .env 에서 서버별로 조정(compose 수정 불필요). API 병목은 드묾 — 기본 1이면 충분,
|
||||
# 부하테스트/대량 폴링 대비 시에만 코어 수만큼 상향(예: 4).
|
||||
PROCESS_COUNT: ${LPS_API_PROCESS_COUNT:-1}
|
||||
DB_CONNECTION_BUDGET: ${LPS_DB_CONNECTION_BUDGET:-40} # 전용 PG(max_connections≈100)면 90 근처로 상향
|
||||
volumes:
|
||||
- ./lps/config/config.local.toml:/app/config/config.local.toml:ro
|
||||
ports:
|
||||
- "9600:9600"
|
||||
- "${LPS_API_BIND:-0.0.0.0}:9600:9600" # prod 는 LPS_API_BIND=127.0.0.1 로 내부만 개방(리버스프록시 뒤)
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
labels:
|
||||
@@ -161,38 +155,43 @@ services:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# LPS 워커 (크롤 — 헤드풀 Chromium+Xvfb, headless 는 안티봇에 탐지됨). config.local.toml 공유.
|
||||
lps-worker:
|
||||
build:
|
||||
context: ./lps
|
||||
dockerfile: Dockerfile.worker # Chromium + Xvfb (headless 는 안티봇에 탐지됨)
|
||||
dockerfile: Dockerfile.worker
|
||||
# google-chrome-stable(Linux)은 amd64 전용 → 이미지 자체가 amd64. arm64 맥에선 명시 없으면
|
||||
# arm64 로 빌드를 시도하다 Chrome 의존성에서 실패한다(Rosetta 로 에뮬 실행). prod(amd64)에선 무영향.
|
||||
platform: linux/amd64
|
||||
container_name: lps-worker
|
||||
environment:
|
||||
APP_ENV: local
|
||||
DB_HOST: host.docker.internal
|
||||
DB_USER: ${LPS_DB_USER:-postgres}
|
||||
DB_PASSWORD: ${LPS_DB_PASSWORD:-postgres}
|
||||
DB_HOST: ${LPS_DB_HOST-host.docker.internal} # 컨테이너→호스트 DB (config.local.toml 의 127.0.0.1 override)
|
||||
PYTHONUNBUFFERED: "1"
|
||||
WORKER_CONCURRENCY: "1" # 상품 동시 검색 수(워커별 브라우저 세트, Chrome 4×N)
|
||||
LPS_PROFILE_DIR: /profiles # Chrome 프로필을 영속 볼륨에 → 재시작해도 cf_clearance 유지(재웜업 회피)
|
||||
# LPS_FALLBACKS: "gmarket,auction,st11" # 오픈마켓 폴백(기본 OFF — 켜기 전 라이브 스모크로 셀렉터 점검)
|
||||
# LPS_JOB_DEADLINE_SEC: "300" # 잡 1건 처리 상한(행 방어) — 기본 300s
|
||||
# ── 시크릿 주입(이미지엔 없음 — 필수). 리포 루트 .env 에 값 채움(.env.example 참고) ──
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY:-} # 비면 AI 판정 OFF
|
||||
NAVER_KEYS: ${NAVER_KEYS:-} # "id1:secret1,id2:secret2" — 비면 네이버 검색 실패
|
||||
DECODO_HOST: ${DECODO_HOST:-} # DECODO 4종 비면 프록시 미사용(직접 연결)
|
||||
DECODO_USERNAME: ${DECODO_USERNAME:-}
|
||||
DECODO_PASSWORD: ${DECODO_PASSWORD:-}
|
||||
DECODO_PORT_START: ${DECODO_PORT_START:-0}
|
||||
DECODO_PORT_END: ${DECODO_PORT_END:-0}
|
||||
DECODO_COST_PER_GB: ${DECODO_COST_PER_GB:-0}
|
||||
volumes:
|
||||
- ./lps/config/config.local.toml:/app/config/config.local.toml:ro
|
||||
- lps-profiles:/profiles # Chrome 프로필(쿠키) 영속
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
shm_size: "1gb" # Chrome 는 /dev/shm 을 많이 씀 — 부족하면 탭 크래시
|
||||
stop_grace_period: 75s # graceful 종료 유예(LPS_SHUTDOWN_GRACE_SEC=60 + 정리 여유) — 기본 10s 면 하던 잡 마무리 전에 SIGKILL
|
||||
stop_grace_period: 75s # graceful 종료 유예(worker shutdown_grace_sec=60 + 여유)
|
||||
labels:
|
||||
autoheal: "true" # 하트비트 HEALTHCHECK 실패(행/좀비) 시 autoheal 이 재시작
|
||||
autoheal: "true" # 하트비트 실패(행/좀비) 시 autoheal 재시작
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# LPS 관리자 UI (정적 React → nginx). /v1·/healthz·/readyz 는 nginx 가 lps-api:9600 으로 프록시(앱은 상대경로 호출).
|
||||
lps-admin:
|
||||
build:
|
||||
context: ./lps-admin
|
||||
dockerfile: Dockerfile
|
||||
container_name: lps-admin
|
||||
ports:
|
||||
- "3400:80"
|
||||
depends_on:
|
||||
- lps-api
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
# 협상 QA 체크리스트 (260727 요청 검증)
|
||||
|
||||
> 대상: **negodata 어드민**(:3000) + **negosium 공급사 포털**(:3300). 두 앱을 함께 돌려야 하는 플로우라 루트 `docs/`에 둔다.
|
||||
> 형식: 케이스별 `~하면 → ~나와야 한다`. 근거는 코드 검증(2026-07-30) 기준. ⚠=현재 알려진 이슈.
|
||||
> 런타임 주의: negosium front/backend는 이미지 빌드라 코드 수정은 **재빌드해야 반영**된다.
|
||||
|
||||
---
|
||||
|
||||
## 0. 요청사항 반영 현황 (코드 검증 결과, Excel 상태열 아님)
|
||||
|
||||
| # | 요청 | 판정 | 비고 |
|
||||
|---|------|------|------|
|
||||
| 2 | 견적관리 리스트+히스토리·상세 | ✅ | /quotation + `?detail=` 시트(협상현황/대화/카드, 라운드 타임라인) |
|
||||
| 3 | 재협상 리스트·심사 | ✅ | /renegotiation 대기/승인/반려 |
|
||||
| 4 | MD→구매담당자·판매가 미노출·위치 | ✅ | |
|
||||
| 5/23 | 목표가=매입가×(1−네고율) 자동 | ✅ | 재/재견적 한정, 네고율=견적세팅 목표마진 |
|
||||
| 6 | 공급가=매입가 일원화 | ⚙ 설정 | 코드 지원됨(`hideCls`). IMK `hidden_fields`에 `"price"` 추가하면 매입가만 남음 |
|
||||
| 7 | 최저가 크롤 + VAT산식 | ⚠ 인프라 / 논이슈 | VAT는 설정·아이템별 처리(논이슈). 단 dev의 lps-worker 크래시+수집테이블 0행 → 수집 파이프라인 확인 필요 |
|
||||
| 8 | 신규 상품 공급사 입력칸 | ✅ | |
|
||||
| 9 | SG명/유통레벨 콤보·취급상품 삭제 | ❌ 미구현 | §9 참조 |
|
||||
| 10 | 리드타임→표준납기 | ✅ 수정 | Summary.tsx 하드코딩 라벨 회사설정 반영으로 수정(2026-07-30) |
|
||||
| 11 | 단가 VAT별도 | ✅ | 회사설정 `item_vat_yn` 동적(IMK는 vat_yn hidden) |
|
||||
| 12 | 앵커 10원 반올림 | ✅ | `calc_anchoring_price` + 카드 카운터(`compute_counter`) + 와일드카드 1%(2026-07-31 수정) 모두 10원 반올림 |
|
||||
| 13 | 절충안 계산식 | ✅ | `compute_counter` 점검, 버그 없음 |
|
||||
| 14/17 | 결렬 희망가 입력란 통일 | ✅ | 단일 RejectForm |
|
||||
| 15 | 마무리 배송 콤보/기타의견/투찰요약 | ✅ | ExtraInfoBar가 session_fields select 렌더 → 콤보 [직납/IMK배송/IMK집배송] |
|
||||
| 16 | 제안가 갭·반올림 | ✅ | 갭은 정상(목표가=후보 min×수수료). 봇 제안가(카운터·와일드카드 1%)도 10원 반올림 반영(2026-07-31) |
|
||||
| 18/22 | 성공률 기준·결렬 무관 | ✅ | 게이지는 참고용, 판정과 무관(§D). 타결=목표가 아래로/봇 카운터 수락, 결렬=카드3+최종제안 소진까지 목표가 위 |
|
||||
| 19/25 | 종료 의견 단계 | ✅ | 타결 ExtraInfoBar(custom.opinion)+결렬 RejectForm 의견 |
|
||||
| 20 | 결렬사유 상시노출·필수 | ✅ 검증 | 결렬 세션 9/9 사유 존재. §20 참조 |
|
||||
| 21 | 카드 3회 초과 | ✅ 정상 | 3회=협상카드 한도. 와일드카드·최종제안은 별도로 붙는 구조라 보이는 카드가 3장을 넘을 수 있음(§21) |
|
||||
| 24 | 목표가 필드 1→3.낙찰기준 이동 | ✅ | |
|
||||
|
||||
---
|
||||
|
||||
## A. 견적 생성 (어드민)
|
||||
- **A1** 재/재견적에서 매입가 10,000·네고율(견적세팅 목표마진) 2% 입력 → 목표가(구매담당자 제시가) 필드에 **9,800 자동 채움**(10원 반올림)
|
||||
- **A2** 목표가 직접 안 건드리고 생성 → `md_price=null`로 전송, 서버가 후보 최솟값으로 재산정
|
||||
- **A3** **신규**협상/신규견적 → 매입가 후보 빠지고 인터넷최저가만 사용 → 자동 목표가가 매입가 기반이 아님(A1과 다른 게 정상)
|
||||
- **A4** 1.기본정보엔 목표가 없어야 / **3.낙찰기준** 스텝에 목표가+산정후보 나와야
|
||||
- **A5** 판매가 입력칸 없어야 / 라벨 "구매담당자 제시가"
|
||||
|
||||
## B. 앵커·제안가
|
||||
- **B1** 협상 시작 → 세션 앵커가 = 목표가×(1−1%), **끝자리 0** (예 목표 7,650 → 앵커 7,570)
|
||||
- **B2** 봇 재제안가 전부 **끝자리 0** — 카드 카운터(절충가·목표가 제시)와 **와일드카드 1% 인하가** 포함 (예 제시 15,555 → 1% 인하가 15,400). 1원 단위가 보이면 불량
|
||||
|
||||
## C. 협상 진행 (실시간 챗, 공급사 포털)
|
||||
- **C1** 제시가 **≤ 앵커가** → **즉시 협상완료(투찰 확정)**, 성공률 99
|
||||
- **C2** 앵커가 < 제시가 ≤ 앵커×1.02 → **와일드카드 1% 인하 요청**(세션 1회), 성공률 99~80
|
||||
- **C3** 앵커×1.02 초과 → **일반 협상카드로 재제안(최대 3번)**, 성공률 표시(제시가 낮을수록↑)
|
||||
- **C4** 카드 소진 또는 재제안 3번 후에도 앵커 밑 못 내림 → **협상 실패(결렬, 투찰 없음)**
|
||||
- **C5** 카드 사용한도 3은 **협상카드에만** 적용. **와일드카드·최종제안은 별도로 붙어** 공급사가 보는 카드가 3장을 넘을 수 있음(정상, §21)
|
||||
- **C6** 단가는 **VAT별도** 표기(IMK는 VAT 라벨 자체 숨김)
|
||||
|
||||
## D. 타결/결렬 판정 & 성공률 게이지
|
||||
- **판정 규칙**: 유저가 **목표가 아래로 내리거나** 봇이 되받은 제시가(카운터)를 **수락하면 타결**. **카드(3장)+최종제안**까지 다 소진될 때까지 **목표가 위에서 버티면 결렬**.
|
||||
- **D1** 성공률 게이지는 **참고용일 뿐 판정과 무관** — 제시가 낮을수록 게이지↑(상한 99, **100% 도달 안 함**).
|
||||
- **D2** 성공률 낮아도 무조건 결렬 아님. 최종 마감(낙찰/개찰)은 별도 기준(§G).
|
||||
|
||||
## E. 협상 타결(완료) 마무리
|
||||
- **E1** 협상완료 → **부가정보 입력 단계 등장** (표준납기·최소주문수량·발주배수·배송유형·의견)
|
||||
- **E2** 배송유형 → **콤보 [직납/IMK배송/IMK집배송]**로 떠야 (자유입력·다른 라벨이면 불량)
|
||||
- **E3** 의견(선택) 작성 → `custom.opinion` 저장돼야
|
||||
- **E4** 입력 완료 → **투찰결과 요약 갱신 후 최종 안내**, 요약에 부가정보·의견 반영
|
||||
- **E5** 어드민 상세(협상현황/요약)에서 부가정보 **표시+잠금(읽기전용)**
|
||||
|
||||
## F. 협상 결렬(실패)
|
||||
- **F1** 결렬 → **결렬 사유 입력 단계 항상 노출 + 필수**(견적/유형 무관 동일 폼)
|
||||
- **F2** 사유 프리셋(단가인상/수량/단종/품절)+기타, **기타 선택 시 사유 텍스트 필수**
|
||||
- **F3** 희망가격 입력 = **단일 폼**(RSP/CM 동일)
|
||||
- **F4** 의견(선택) 작성 가능
|
||||
- **F5** 검증: 결렬(협상거부) 세션은 **100% 사유가 기록**돼야 (사유 없는 결렬 세션 = 불량). §20
|
||||
|
||||
## G. 마감 · 낙찰/개찰
|
||||
- **G1** 투찰가 ≤ 앵커가 → **낙찰**
|
||||
- **G2** 앵커~목표가 → 1:1은 **사용자 지정**(mid_action), 1:N은 낙찰
|
||||
- **G3** 목표가 초과 → 1:1 **사용자 지정**(over_action, 관례 개찰), 1:N 낙찰
|
||||
- **G4** 동가(최저 2곳+)·전원 미응찰·협상거부 → **개찰**(낙찰자 미정, 결렬 아님) / 마감사유 라벨 정확히
|
||||
|
||||
## H. 재협상 요청·심사 (공급사→어드민)
|
||||
- **H1** 개찰 마감 + 본인 마지막 라운드 → **재협상 요청 가능**(사유+희망가), 담당자 알림 1건
|
||||
- **H2** 낙찰건/남의 세션 요청 → **거부**
|
||||
- **H3** 같은 세션 2회 요청 → 2번째 **거부**; 철회 후 재요청 가능
|
||||
- **H4** 어드민 /renegotiation 대기 탭 접수 → **승인 시 다음 차수 견적 생성**, 반려 시 사유 필수
|
||||
|
||||
---
|
||||
|
||||
## 알려진 이슈 상세
|
||||
|
||||
### §9. 협력사 SG명/유통레벨 콤보·취급상품 삭제 — 미구현
|
||||
요청 4가지 모두 현재 구조와 다르다:
|
||||
1. **분류카테고리 → SG명**: 지금 '분류카테고리'는 **입력 필드가 아니라 취급상품에서 파생 집계**되는 읽기전용 값(`SupplierItemsManager.tsx`). 회사 라벨(labels.category)로 "SG명" 표기만 되지, 직접 고르는 필드가 아님.
|
||||
2. **선택콤보(취급 SG명)**: 등록된 SG명 중 선택하는 콤보 없음.
|
||||
3. **유통레벨 콤보(제조/총판/대리점/일반유통)**: 없음. 유사한 건 취급상품별 **공급유형** 콤보인데 값이 다름(유통/제조/총판/없음). '대리점'·'일반유통' 값 자체가 코드에 없음. IMK 설정의 `supplier_fields.distribution_level`은 콤보가 아니라 **텍스트** 커스텀 필드.
|
||||
4. **취급상품 칸 삭제**: 삭제 안 됨(등록/수정폼·엑셀업로드에 그대로).
|
||||
- 근본: IMK는 SG명·유통레벨을 **협력사 레벨 속성(콤보)**으로 두고 취급상품 목록은 없애길 원함. 현재는 반대로 **취급상품(supplier_items)에서 카테고리·공급유형을 파생**하는 모델. → 데이터 모델 전환이 필요한 작업.
|
||||
|
||||
### §20. 결렬 사유 상시 노출·필수 — 검증 완료
|
||||
- agent의 모든 실패 경로가 단일 step `"협상실패"`(chat_end)로 수렴 → backend가 rejectRSP/CM로 무조건 매핑 → 프론트 통일 RejectForm(사유 필수). 세션 상태 분기 없음.
|
||||
- 실데이터: 협상거부(status=5) 9건 **전부 reject_reason 존재**, 사유 없는 결렬 0건.
|
||||
- 원 버그의 "견적마다 상이"는 *대화 중 결렬*(사유 있음) vs *미참여/마감 자동종료*(대화 자체 없음 → 사유 없음)의 구분이었을 뿐, 결렬 플로우는 일관됨.
|
||||
|
||||
### §21. 카드 3회 초과 — 정상 동작(버그 아님)
|
||||
`card_count=3`은 **협상카드 사용 한도**다. 와일드카드와 최종제안(종결)은 이 한도와 **별개로 각각 붙는** 구조라, 공급사가 보는 카드가 3장을 넘을 수 있다.
|
||||
1. **와일드카드 1장**(1% 인하/동적 카운터) — 협상카드 카운트와 별개.
|
||||
2. **최종제안 1장**(중간값 절충/최후통첩) — 카드 소진 후 마지막 국면에 별도로 붙음.
|
||||
→ 협상카드 3 + 와일드 1 + 최종제안 1 = 최대 5장 노출(예: EST-202607-4DB5).
|
||||
- 참고(엣지): 세션에 견적세팅(card_count)이 연결 안 되면 한도가 안 걸릴 수 있으니, 설정이 항상 세션에 물리는지만 확인.
|
||||
@@ -73,7 +73,8 @@ export interface SessionBrandingResponse {
|
||||
export interface SessionField {
|
||||
key: string
|
||||
label: string
|
||||
type: 'text' | 'number' | 'boolean'
|
||||
type: 'text' | 'number' | 'boolean' | 'select'
|
||||
options?: string[] // type='select' 일 때 고를 보기 목록
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
|
||||
@@ -32,6 +32,7 @@ export interface ChatInitResponse {
|
||||
session_id: string
|
||||
session_status: number
|
||||
quotation_id: string
|
||||
qt_number?: string
|
||||
quotation_end_time: string
|
||||
quotation_memo?: string
|
||||
item_id: string
|
||||
@@ -47,6 +48,7 @@ export interface ChatInitResponse {
|
||||
item_vat_yn?: boolean
|
||||
item_delivery_fee_yn?: boolean
|
||||
custom?: Record<string, unknown>
|
||||
labels?: Record<string, string>
|
||||
}
|
||||
|
||||
export interface ChatMessagesResponse {
|
||||
@@ -89,6 +91,7 @@ export function mapInit(r: ChatInitResponse): ChatInitData {
|
||||
session_status: r.session_status,
|
||||
item_id: r.item_id,
|
||||
quotation_id: r.quotation_id,
|
||||
qt_number: r.qt_number ?? '',
|
||||
item_name: r.item_name,
|
||||
item_code: r.item_code ?? '',
|
||||
item_image: r.item_image ?? '',
|
||||
@@ -104,5 +107,6 @@ export function mapInit(r: ChatInitResponse): ChatInitData {
|
||||
item_spec: r.item_spec ?? '',
|
||||
quotation_memo: r.quotation_memo ?? '',
|
||||
quotation_end_time: r.quotation_end_time ?? '',
|
||||
labels: r.labels ?? {},
|
||||
}
|
||||
}
|
||||
@@ -2,5 +2,11 @@
|
||||
export { negotiationApi } from './negotiation.api'
|
||||
export { negotiationKeys } from './negotiation.keys'
|
||||
export { useSessionListQuery } from './negotiation.queries'
|
||||
export { useParticipateMutation, useRejectMutation, useSaveExtraInfoMutation } from './negotiation.mutations'
|
||||
export {
|
||||
useCancelRenegotiationMutation,
|
||||
useParticipateMutation,
|
||||
useRejectMutation,
|
||||
useRequestRenegotiationMutation,
|
||||
useSaveExtraInfoMutation,
|
||||
} from './negotiation.mutations'
|
||||
export * from './negotiation.type'
|
||||
@@ -6,6 +6,8 @@ import type {
|
||||
ParticipateResponse,
|
||||
RejectRequest,
|
||||
RejectResponse,
|
||||
RenegotiationRequest,
|
||||
RenegotiationResponse,
|
||||
SessionListParams,
|
||||
SessionListResponse,
|
||||
} from './negotiation.type'
|
||||
@@ -34,6 +36,23 @@ export const negotiationApi = {
|
||||
return res.data
|
||||
},
|
||||
|
||||
/** POST /v1/negotiation/session/{id}/renegotiation — 결렬 건 재협상 요청 */
|
||||
requestRenegotiation: async (sessionId: string, body: RenegotiationRequest): Promise<RenegotiationResponse> => {
|
||||
const res = await http.post<RenegotiationResponse>(
|
||||
`/v1/negotiation/session/${sessionId}/renegotiation`,
|
||||
body,
|
||||
)
|
||||
return res.data
|
||||
},
|
||||
|
||||
/** DELETE /v1/negotiation/session/{id}/renegotiation — 심사 대기 중인 요청 철회 */
|
||||
cancelRenegotiation: async (sessionId: string): Promise<RenegotiationResponse> => {
|
||||
const res = await http.delete<RenegotiationResponse>(
|
||||
`/v1/negotiation/session/${sessionId}/renegotiation`,
|
||||
)
|
||||
return res.data
|
||||
},
|
||||
|
||||
/** POST /v1/negotiation/sessions/{id}/extra-info — 협상완료 부가정보 저장 */
|
||||
saveExtraInfo: async (sessionId: string, body: ExtraInfoRequest): Promise<ExtraInfoResponse> => {
|
||||
const res = await http.post<ExtraInfoResponse>(
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { negotiationApi } from './negotiation.api'
|
||||
import { negotiationKeys } from './negotiation.keys'
|
||||
import type { ExtraInfoRequest, RejectRequest } from './negotiation.type'
|
||||
import type { ExtraInfoRequest, RejectRequest, RenegotiationRequest } from './negotiation.type'
|
||||
|
||||
/**
|
||||
* 협상 세션 참여: 성공 시 세션 목록 캐시를 무효화해 상태를 갱신한다.
|
||||
@@ -44,3 +44,24 @@ export function useSaveExtraInfoMutation() {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useRequestRenegotiationMutation() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: ({ sessionId, request }: { sessionId: string; request: RenegotiationRequest }) =>
|
||||
negotiationApi.requestRenegotiation(sessionId, request),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useCancelRenegotiationMutation() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: ({ sessionId }: { sessionId: string }) => negotiationApi.cancelRenegotiation(sessionId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -43,6 +43,8 @@ export interface SessionListParams {
|
||||
order?: 'asc' | 'desc' // 생략 시 기본 그룹 정렬('할 일' 우선+임박순, 종료는 하단). 지정 시 그룹 무시하고 전체 마감순(asc=임박/desc=여유)
|
||||
page?: number
|
||||
page_size?: number
|
||||
keyword?: string // 검색어 — 견적번호·상품명·상품코드 부분일치
|
||||
result?: number // 결과 필터(SessionResult): 1=낙찰 2=미낙찰 3=결렬
|
||||
}
|
||||
|
||||
export interface SessionListItem {
|
||||
@@ -56,6 +58,40 @@ export interface SessionListItem {
|
||||
model_name: string
|
||||
maker_name: string
|
||||
custom: Record<string, unknown> // 협상완료 부가정보(sessions.custom). 미입력이면 {}
|
||||
renegotiable: boolean // 재협상 요청 가능 여부(서버 판정 — 개찰 마감 + 마지막 차수 + 대기 요청 없음)
|
||||
renegotiation_status: number // 1=심사대기 2=승인 3=반려 4=철회, 이력 없으면 0
|
||||
renegotiation_memo: string // 담당자 심사 메모(반려 사유)
|
||||
result: number // 협상 결과(SessionResult): 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰)
|
||||
}
|
||||
|
||||
/** 공급사 관점 협상 결과 (sessions 파생) */
|
||||
export const SessionResult = { NONE: 0, WON: 1, LOST: 2, OPEN: 3 } as const
|
||||
|
||||
export const SESSION_RESULT_LABEL: Record<number, string> = {
|
||||
1: '낙찰',
|
||||
2: '미낙찰',
|
||||
3: '결렬',
|
||||
}
|
||||
|
||||
// 재협상 요청(IMK #15)
|
||||
export interface RenegotiationRequest {
|
||||
reason: string
|
||||
desired_price?: number | null
|
||||
}
|
||||
|
||||
export interface RenegotiationResponse {
|
||||
result: ApiResult
|
||||
session_id: string
|
||||
status: number
|
||||
}
|
||||
|
||||
export const RenegoStatus = { NONE: 0, PENDING: 1, APPROVED: 2, REJECTED: 3, CANCELED: 4 } as const
|
||||
|
||||
export const RENEGO_STATUS_LABEL: Record<number, string> = {
|
||||
1: '재협상 심사 중',
|
||||
2: '재협상 승인됨',
|
||||
3: '재협상 반려됨',
|
||||
4: '요청 철회됨',
|
||||
}
|
||||
|
||||
export interface SessionListResponse {
|
||||
|
||||
@@ -21,7 +21,7 @@ export function Modal({ children, onClose }: ModalProps) {
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-[rgba(0,0,0,0.40)]"
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-[rgba(0,0,0,0.40)] p-4"
|
||||
onClick={handleBackdropClick}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -6,23 +6,17 @@ import type { ChatMessage as ChatMessageType } from '@/features/chat/types'
|
||||
import { renderEmphasis } from '@/features/chat/lib/emphasis'
|
||||
import { Indicator } from '@/features/chat/components/templates/Indicator'
|
||||
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 { RejectRSP } from '@/features/chat/components/templates/RejectRSP'
|
||||
import { RejectCM } from '@/features/chat/components/templates/RejectCM'
|
||||
|
||||
const AI_LABEL = '아이마켓코리아 (구매 MD)'
|
||||
const AI_LABEL = '아이마켓코리아 (구매담당자)'
|
||||
|
||||
export function ChatMessage() {
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null)
|
||||
return (
|
||||
<div className="flex-1 w-full min-h-0">
|
||||
{/* lg:pt-[64px]: 첫 메시지를 우측 협상절차 카드 상단과 맞추는 값 — 그 카드가 없는 lg 미만에선
|
||||
스텝바 바로 아래 여백으로만 남아 첫 메시지가 위로 안 붙으므로 뺀다.
|
||||
스크롤 시 여백도 함께 밀려 올라가도록 스크롤 컨테이너 안쪽에 둔다 */}
|
||||
<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]"
|
||||
className="chat-scroll h-full overflow-y-auto flex flex-col pt-4 pb-6 px-4 sm:px-6 min-[1180px]:pl-[80px] min-[1180px]:pr-[72px] min-[1350px]:pl-[140px] min-[1350px]:pr-[126px]"
|
||||
>
|
||||
<ChatList scrollRef={scrollRef} />
|
||||
</div>
|
||||
@@ -48,7 +42,7 @@ function ChatList({ scrollRef }: { scrollRef: RefObject<HTMLDivElement | null> }
|
||||
scroller.scrollTo({ top: scroller.scrollHeight, behavior })
|
||||
})
|
||||
return () => cancelAnimationFrame(id)
|
||||
}, [chats, isLoading])
|
||||
}, [chats, isLoading, scrollRef])
|
||||
|
||||
if (!chats || chats.length === 0) {
|
||||
return (
|
||||
@@ -124,23 +118,14 @@ const BotMessage = memo(function BotMessage({ message }: { message: ChatMessageT
|
||||
{showIndicator && message.bot_chat_type === 'indicator' && message.indicator_value != null && (
|
||||
<Indicator number={message.indicator_value} />
|
||||
)}
|
||||
{message.bot_chat_type === 'summaryRSP' && message.summary && (
|
||||
<>
|
||||
<Summary data={message.summary} />
|
||||
<ExtraInfoForm />
|
||||
</>
|
||||
)}
|
||||
{message.bot_chat_type === 'summaryRSP' && message.summary && <Summary data={message.summary} />}
|
||||
{message.bot_chat_type === 'summaryCM' && message.summary && (
|
||||
<BidSummary
|
||||
itemName={message.summary.item_name}
|
||||
itemCode={message.summary.item_code}
|
||||
bidPrice={message.summary.final_price}
|
||||
deliveryType={message.summary.delivery_type || ''}
|
||||
isVAT={message.summary.item_isVAT}
|
||||
/>
|
||||
)}
|
||||
{message.bot_chat_type === 'rejectRSP' && <RejectRSP />}
|
||||
{message.bot_chat_type === 'rejectCM' && <RejectCM />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { useMeQuery, useSaveExtraInfoMutation, getApiErrorMessage } from '@/apis'
|
||||
import type { SessionField } from '@/apis/auth/auth.type'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
|
||||
// 타결 요약의 '동의' 단계 하단 액션바 = 부가정보 입력 + 동의를 한 자리에서.
|
||||
// 다른 입력(가격·배송)과 같은 자리에서 받는다. proceedText = 동의 문구(누르면 저장 후 그 텍스트로 협상 종료).
|
||||
// 필드 정의(session_fields)가 없으면 폼 없이 동의 버튼만 둔다. 저장 후에도 세션 목록에서 수정할 수 있다.
|
||||
export function ExtraInfoBar({ proceedText }: { proceedText: string }) {
|
||||
const sessionId = useChatStore((s) => s.sessionId)
|
||||
const sendMessage = useChatStore((s) => s.sendMessage)
|
||||
const { data: user } = useMeQuery()
|
||||
const fields: SessionField[] = user?.sessionFields ?? []
|
||||
const save = useSaveExtraInfoMutation()
|
||||
const existing = useChatInitStore((s) => s.custom) // 기존 입력값(재진입 프리필)
|
||||
const setInitData = useChatInitStore((s) => s.setInitData)
|
||||
// 의견은 session_fields 와 무관한 공통 필드 — 타결·결렬 모두 항상 받는다. custom.opinion 에 저장.
|
||||
const [opinion, setOpinion] = useState<string | null>(null)
|
||||
const opinionValue = opinion ?? String(existing?.opinion ?? '')
|
||||
|
||||
// 사용자가 건드린 값만 state 로 두고, 나머지는 기존값/기본값에서 렌더마다 파생한다(초기화 effect 불필요).
|
||||
const [overrides, setOverrides] = useState<Record<string, unknown>>({})
|
||||
const values: Record<string, unknown> = {}
|
||||
for (const f of fields) values[f.key] = overrides[f.key] ?? existing?.[f.key] ?? (f.type === 'boolean' ? false : '')
|
||||
|
||||
const proceed = () => sendMessage(proceedText)
|
||||
|
||||
const set = (key: string, value: unknown) => setOverrides((v) => ({ ...v, [key]: value }))
|
||||
|
||||
// 저장 성공 후에만 동의(협상 종료)로 넘어간다 — 저장 실패 시 화면 유지.
|
||||
const handleSaveAndProceed = () => {
|
||||
if (save.isPending) return
|
||||
const custom: Record<string, unknown> = {}
|
||||
for (const f of fields) {
|
||||
const v = values[f.key]
|
||||
if (f.type === 'boolean') custom[f.key] = !!v
|
||||
else if (v !== '' && v != null) custom[f.key] = f.type === 'number' ? Number(v) : v
|
||||
}
|
||||
if (opinionValue.trim()) custom.opinion = opinionValue.trim()
|
||||
if (Object.keys(custom).length === 0) { proceed(); return } // 입력 없음 → 저장 생략하고 종료
|
||||
save.mutate(
|
||||
{ sessionId, request: { custom } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setInitData({ custom: { ...existing, ...custom } }) // 요약 카드가 방금 입력값을 즉시 반영하도록 store 갱신
|
||||
proceed()
|
||||
},
|
||||
onError: (error) => toast.error(getApiErrorMessage(error, '부가정보 저장에 실패했습니다.')),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<p className="mb-3 text-sm font-semibold text-neutral-90">아래 정보를 입력하고 협상을 마무리해 주세요.</p>
|
||||
{/* overflow-y-auto 는 overflow-x 도 auto 로 만들어(스펙상) 인풋 focus ring 을 좌우로 잘라낸다.
|
||||
p-1 로 링 여백을 주고 -m-1 로 원래 정렬(버튼과 좌우폭)을 유지한다. */}
|
||||
<div className="max-h-[36vh] space-y-3 overflow-y-auto p-1 -m-1">
|
||||
{fields.map((f) => (
|
||||
<div key={f.key} className="flex items-center gap-3">
|
||||
<label className="w-28 shrink-0 text-sm font-semibold text-neutral-80">{f.label}</label>
|
||||
{f.type === 'boolean' ? (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={!!values[f.key]}
|
||||
onClick={() => set(f.key, !values[f.key])}
|
||||
className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors ${
|
||||
values[f.key] ? 'bg-brand-600' : 'bg-neutral-30'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block size-5 transform rounded-full bg-white shadow transition-transform ${
|
||||
values[f.key] ? 'translate-x-5' : 'translate-x-0.5'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
) : f.type === 'select' ? (
|
||||
<select
|
||||
value={String(values[f.key] ?? '')}
|
||||
onChange={(e) => set(f.key, e.target.value)}
|
||||
className="h-10 w-full rounded-xl border border-border bg-white px-3 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600"
|
||||
>
|
||||
<option value="">선택</option>
|
||||
{(f.options ?? []).map((o) => (
|
||||
<option key={o} value={o}>{o}</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
type={f.type === 'number' ? 'number' : 'text'}
|
||||
value={String(values[f.key] ?? '')}
|
||||
onChange={(e) => set(f.key, e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && !e.nativeEvent.isComposing && handleSaveAndProceed()}
|
||||
className="h-10 w-full rounded-xl border border-border bg-white px-3 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600"
|
||||
placeholder={f.label}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{/* 의견 — 타결·결렬 공통 필드(IMK #18). custom.opinion 저장. */}
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-sm font-semibold text-neutral-80">
|
||||
의견 <span className="font-normal text-neutral-50">(선택)</span>
|
||||
</label>
|
||||
<textarea
|
||||
value={opinionValue}
|
||||
onChange={(e) => setOpinion(e.target.value)}
|
||||
rows={2}
|
||||
maxLength={255}
|
||||
placeholder="추가로 남길 의견이 있으면 작성해 주세요."
|
||||
className="w-full resize-none rounded-xl border border-border bg-white px-3 py-2 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" onClick={handleSaveAndProceed} disabled={save.isPending} className={`${PRIMARY} mt-3 w-full`}>
|
||||
{save.isPending ? '저장 중…' : proceedText || '저장하고 마무리'}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const PRIMARY =
|
||||
'h-[46px] min-w-[120px] rounded-xl bg-brand-600 px-6 text-sm font-bold text-white shadow-sm transition-all hover:bg-brand-700 active:scale-[0.98] disabled:opacity-50'
|
||||
@@ -38,14 +38,17 @@ function ItemInfo() {
|
||||
const {
|
||||
item_code,
|
||||
item_price,
|
||||
item_vat_yn,
|
||||
item_model_name,
|
||||
item_maker_name,
|
||||
item_min_order_quantity,
|
||||
item_lead_time,
|
||||
item_spec,
|
||||
item_name,
|
||||
item_vat_yn,
|
||||
labels,
|
||||
} = useChatInitStore()
|
||||
// 회사 설정 라벨(companies.settings.labels)로 필드명 치환. 미설정 시 기본 라벨.
|
||||
const fieldLabel = (key: string, fallback: string) => labels?.[key] || fallback
|
||||
|
||||
const [tooltip, setTooltip] = useState<TooltipState | null>(null)
|
||||
const hideTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
@@ -71,7 +74,8 @@ function ItemInfo() {
|
||||
const formatPrice = (price: number) => price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||||
const isNewItem = !item_code && !item_price
|
||||
const priceText = isNewItem ? '신규' : `${formatPrice(item_price)}원`
|
||||
const formattedPrice = `${priceText}(${item_vat_yn || 'VAT별도'})`
|
||||
// VAT 표기는 회사 설정 기준(item_vat_yn). vat_yn 미관리(hidden)면 값이 비어 라벨을 생략한다.
|
||||
const formattedPrice = item_vat_yn ? `${priceText}(${item_vat_yn})` : priceText
|
||||
|
||||
const renderRow = (title: string, data: string) => {
|
||||
const displayData = data || '-'
|
||||
@@ -105,15 +109,15 @@ function ItemInfo() {
|
||||
|
||||
<div className="flex flex-1 items-start self-stretch overflow-y-auto overflow-x-hidden px-6 min-h-0">
|
||||
<div className="flex flex-col items-start self-stretch flex-1 gap-2 min-w-0">
|
||||
{renderRow('상품코드', item_code)}
|
||||
{renderRow('단가', formattedPrice)}
|
||||
{renderRow('모델명', item_model_name)}
|
||||
{renderRow('제조사', item_maker_name)}
|
||||
{renderRow('최소주문수량', item_min_order_quantity)}
|
||||
{renderRow('리드타임', formatLeadTime(item_lead_time))}
|
||||
{renderRow(fieldLabel('item.code', '상품코드'), item_code)}
|
||||
{renderRow(fieldLabel('item.price', '단가'), formattedPrice)}
|
||||
{renderRow(fieldLabel('item.model_name', '모델명'), item_model_name)}
|
||||
{renderRow(fieldLabel('item.manufacturer', '제조사'), item_maker_name)}
|
||||
{renderRow(fieldLabel('item.moq', '최소주문수량'), item_min_order_quantity)}
|
||||
{renderRow(fieldLabel('lead_time', '리드타임'), formatLeadTime(item_lead_time))}
|
||||
|
||||
<div className="flex items-start justify-between gap-3 self-stretch py-2">
|
||||
<span className="shrink-0 text-sm text-neutral-60">규격</span>
|
||||
<span className="shrink-0 text-sm text-neutral-60">{fieldLabel('item.spec', '규격')}</span>
|
||||
<span
|
||||
className="min-w-0 flex-1 overflow-hidden whitespace-normal break-words break-keep text-right text-[13px] font-semibold text-neutral-90 cursor-default"
|
||||
onMouseEnter={(e) => item_spec && showTooltip(e, item_spec, true)}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Check } from 'lucide-react'
|
||||
import { cn } from '@/lib'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { STEPS } from '@/features/chat/components/menu/NegoStep'
|
||||
import { STEPS } from '@/features/chat/lib/negoSteps'
|
||||
|
||||
// 모바일 전용: 협상절차를 채팅 상단에 가로 스텝바로 항상 표시한다. (데스크톱은 우측 패널 사용)
|
||||
export function MobileStepBar() {
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import { cn } from '@/lib'
|
||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
import { SelectRadio, SubmitButton } from '@/features/chat/components/templates/rejectControls'
|
||||
import { OtherReason } from '@/features/chat/components/templates/OtherReason'
|
||||
import { findRestoreScript, restoreRejectRSP, extractPart } from '@/features/chat/lib/rejectForm'
|
||||
|
||||
const MAX_PRICE = 999999999999999
|
||||
|
||||
// 합의 불가 사유 프리셋 (rejectRSP 와 동일 목록)
|
||||
const REASONS = [
|
||||
{ value: '단가인상', text: "'원재료 가격 상승' 또는 '제조사 가격 인상'으로 요청한 공급가격을 맞출 수 없습니다." },
|
||||
{ value: '수량', text: '주문 수량이 적어, 소량 생산 시 발생하는 제조비용으로 맞출 수 없습니다.' },
|
||||
{ value: '단종', text: '현재 단종된 제품으로 물량 수급이 원활하지 않아 가격을 맞출 수 없습니다.' },
|
||||
{ value: '품절', text: '해당 상품이 품절되어 납품할 수 없습니다.' },
|
||||
]
|
||||
|
||||
// 통일된 협상 결렬 폼 — 최종 제안 단가 + 합의 불가 사유 + 의견.
|
||||
// rejectRSP / rejectCM 두 유형 모두 이 폼 하나로 받는다(액션바 렌더).
|
||||
export function RejectForm() {
|
||||
const isLoading = useChatStore((s) => s.isLoading)
|
||||
const sendMessage = useChatStore((s) => s.sendMessage)
|
||||
const messages = useChatStore((s) => s.messages)
|
||||
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
|
||||
const isVAT = item_vat_yn === 'VAT별도'
|
||||
|
||||
// 직전 제출 내역에서 1회 복원 (rejectRSP/rejectCM 어느 유형이든).
|
||||
const priorScript = useState(
|
||||
() => findRestoreScript(messages, 'rejectRSP') ?? findRestoreScript(messages, 'rejectCM'),
|
||||
)[0]
|
||||
const restored = useState(() => restoreRejectRSP(priorScript))[0]
|
||||
const [price, setPrice] = useState(restored.price)
|
||||
const [selectedReason, setSelectedReason] = useState(restored.selectedReason)
|
||||
const [reason, setReason] = useState(restored.reason)
|
||||
const [opinion, setOpinion] = useState(() => extractPart(priorScript, '의견-'))
|
||||
const [otherErrorMessage, setOtherErrorMessage] = useState('')
|
||||
const [priceErrorMessage, setPriceErrorMessage] = useState('')
|
||||
const [radioErrorMessage, setRadioErrorMessage] = useState('')
|
||||
|
||||
const isSubmitted = useMemo(
|
||||
() => Boolean(findRestoreScript(messages, 'rejectRSP') ?? findRestoreScript(messages, 'rejectCM')),
|
||||
[messages],
|
||||
)
|
||||
// 사유는 필수(20번), 의견은 선택(18번).
|
||||
const isValid =
|
||||
Boolean(price && parseInt(price) > 0) &&
|
||||
Boolean(selectedReason) &&
|
||||
(selectedReason !== '기타' || reason.trim() !== '')
|
||||
|
||||
const handlePriceChange = (value: string) => {
|
||||
const numeric = value.replace(/\D/g, '')
|
||||
if (numeric && parseInt(numeric) > MAX_PRICE) return
|
||||
setPrice(numeric)
|
||||
if (numeric) setPriceErrorMessage('')
|
||||
}
|
||||
|
||||
const handleRadioChange = (value: string) => {
|
||||
setSelectedReason(value)
|
||||
setRadioErrorMessage('')
|
||||
if (value !== '기타') {
|
||||
setReason('')
|
||||
setOtherErrorMessage('')
|
||||
}
|
||||
}
|
||||
|
||||
const koreanPrice = (() => {
|
||||
if (!price) return '영'
|
||||
const n = parseInt(price)
|
||||
return Number.isNaN(n) || n === 0 ? '영' : numberToKorean(n)
|
||||
})()
|
||||
|
||||
const handleSubmit = () => {
|
||||
setPriceErrorMessage(!price || parseInt(price) === 0 ? '가격을 입력해주세요.' : '')
|
||||
setRadioErrorMessage(!selectedReason ? '사유를 선택해주세요.' : '')
|
||||
setOtherErrorMessage(selectedReason === '기타' && !reason.trim() ? '기타 사유를 입력해주세요.' : '')
|
||||
if (isValid && !isLoading && !isSubmitted) {
|
||||
const reasonPart =
|
||||
selectedReason === '기타' ? `합의불가사유-기타-${reason.trim()}` : `합의불가사유-${selectedReason}`
|
||||
const script = `공급희망가격-${price}, ${reasonPart}, 의견-${opinion.trim()}`
|
||||
sendMessage(script, 'text')
|
||||
}
|
||||
}
|
||||
|
||||
const isDisabled = isLoading || isSubmitted
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<div className="flex flex-col w-full gap-2">
|
||||
<div className="flex w-full items-center justify-center gap-2 rounded-xl bg-[#FFF1F1] px-4 py-3 text-sm font-bold text-[#E5484D]">
|
||||
<AlertTriangle className="size-5 shrink-0" />
|
||||
협상 합의 불가 사유 및 최종 제안 단가 입력
|
||||
</div>
|
||||
|
||||
<div className="max-h-[42vh] space-y-2 overflow-y-auto p-1 -m-1">
|
||||
{/* 공급 희망 가격 */}
|
||||
<div className="flex flex-col w-full gap-1">
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<div className="w-[100px] shrink-0 pt-2.5 text-sm font-bold text-neutral-90">공급 희망 가격</div>
|
||||
<div className="flex w-full flex-wrap items-center gap-2 pt-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
className={cn(
|
||||
'h-10 max-w-[200px] rounded-xl border px-3 text-right text-sm outline-none transition-all placeholder:text-neutral-50',
|
||||
isDisabled
|
||||
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
|
||||
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
|
||||
)}
|
||||
value={price ? parseInt(price).toLocaleString() : ''}
|
||||
onChange={(e) => handlePriceChange(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && !e.nativeEvent.isComposing && handleSubmit()}
|
||||
placeholder="0"
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<div className="whitespace-nowrap text-sm text-neutral-70">원{isVAT && '(VAT 별도)'}</div>
|
||||
</div>
|
||||
<div className="whitespace-nowrap text-sm text-neutral-50">[{koreanPrice} 원]</div>
|
||||
</div>
|
||||
</div>
|
||||
{priceErrorMessage && (
|
||||
<div className="pl-[112px] text-xs font-medium text-negative">{priceErrorMessage}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 합의 불가 사유 (필수) */}
|
||||
<div className="flex w-full gap-3">
|
||||
<div className="w-[100px] shrink-0 pt-2 text-sm font-bold text-neutral-90">합의 불가 사유</div>
|
||||
<div className="flex w-full flex-col mt-2 gap-2">
|
||||
{REASONS.map((r) => (
|
||||
<SelectRadio
|
||||
key={r.value}
|
||||
text={r.text}
|
||||
value={r.value}
|
||||
name="rejectform"
|
||||
selectedValue={selectedReason}
|
||||
onChange={handleRadioChange}
|
||||
errorMessage={radioErrorMessage}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
))}
|
||||
<OtherReason
|
||||
inputValue={reason}
|
||||
setInputValue={(v) => {
|
||||
if (selectedReason !== '기타') return
|
||||
setReason(v)
|
||||
if (v.trim()) setOtherErrorMessage('')
|
||||
}}
|
||||
errorMessage={otherErrorMessage}
|
||||
selectedValue={selectedReason}
|
||||
onChange={handleRadioChange}
|
||||
isError={!!radioErrorMessage}
|
||||
disabled={isDisabled}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 의견 (선택) — 타결·결렬 공통 */}
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<div className="w-[100px] shrink-0 pt-2 text-sm font-bold text-neutral-90">의견</div>
|
||||
<textarea
|
||||
value={opinion}
|
||||
onChange={(e) => setOpinion(e.target.value)}
|
||||
rows={2}
|
||||
maxLength={255}
|
||||
disabled={isDisabled}
|
||||
placeholder="추가로 남길 의견이 있으면 작성해 주세요. (선택)"
|
||||
className={cn(
|
||||
'mt-2 w-full resize-none rounded-xl border px-3 py-2 text-sm outline-none transition-all placeholder:text-neutral-50',
|
||||
isDisabled
|
||||
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
|
||||
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full items-center justify-center mt-2">
|
||||
<SubmitButton isValid={isValid} isLoading={isLoading} isSubmitted={isSubmitted} onSubmit={handleSubmit} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { cn } from '@/lib'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { Percent, Price } from '@/features/chat/components/userInputs'
|
||||
import { ExtraInfoBar } from '@/features/chat/components/ExtraInfoBar'
|
||||
import { RejectForm } from '@/features/chat/components/RejectForm'
|
||||
import { GO_TO_LIST_TEXT } from '@/features/chat/lib/userButtonConfig'
|
||||
import type { UserButtonConfig } from '@/features/chat/types'
|
||||
|
||||
@@ -17,8 +20,28 @@ const style = {
|
||||
export function UserButton({ type, text, textList, priceErrorMessage }: UserButtonConfig) {
|
||||
if (type === '') return null
|
||||
|
||||
// 부가정보 입력은 폼이라 가운데정렬 덱이 아니라 전체폭으로 편다. text = 저장 후 보낼 동의 문구.
|
||||
if (type === 'extra-info') {
|
||||
return (
|
||||
<div className="w-full px-6 py-4 max-[1180px]:px-4">
|
||||
<ExtraInfoBar proceedText={text || ''} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 결렬 통일 폼 — 부가정보와 같은 자리(액션바)에서 전체폭으로.
|
||||
if (type === 'reject') {
|
||||
return (
|
||||
<div className="w-full px-6 py-4 max-[1180px]:px-4">
|
||||
<RejectForm />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 입력 단계는 에러 말풍선이 위로 삐져나가야 해서 overflow 클리핑 제외 (버튼 덱만 가로 스크롤 허용)
|
||||
const isInputStep = type === 'percent' || type === 'price'
|
||||
return (
|
||||
<div className="flex w-full justify-center overflow-x-auto px-6 py-4 max-[1180px]:px-4">
|
||||
<div className={cn('flex w-full justify-center px-6 py-4 max-[1180px]:px-4', !isInputStep && 'overflow-x-auto')}>
|
||||
<div className="flex justify-center">
|
||||
{type === 'one-black' && <OneBlack text={text || '확인'} />}
|
||||
{type === 'one-gray' && <OneGray text={text || '확인'} />}
|
||||
@@ -82,6 +105,18 @@ function ThreeBlack({ textList }: { textList: [string, string, string] }) {
|
||||
|
||||
function BlackWhite({ textList }: { textList: [string, string] }) {
|
||||
const sendMessage = useChatStore((s) => s.sendMessage)
|
||||
// Enter = 첫 버튼(예). 입력창이 없는 선택 단계라 전역 Enter 를 잡아도 안전하다.
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.isComposing) {
|
||||
e.preventDefault()
|
||||
sendMessage(textList[0])
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [sendMessage, textList])
|
||||
|
||||
return (
|
||||
<div className="flex gap-3">
|
||||
<button className={style.black} onClick={() => sendMessage(textList[0])}>
|
||||
|
||||
@@ -29,7 +29,7 @@ export function MDInformation({ isOpen, setIsOpen }: Props) {
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="flex w-full items-center justify-between border-b border-border pb-2"
|
||||
>
|
||||
<span className="text-[11px] font-bold tracking-wide text-neutral-60">MD 안내사항</span>
|
||||
<span className="text-[11px] font-bold tracking-wide text-neutral-60">구매담당자 안내사항</span>
|
||||
<ChevronDown
|
||||
size={16}
|
||||
className={cn('text-neutral-50 transition-transform duration-300', !isOpen && '-rotate-90')}
|
||||
|
||||
@@ -1,20 +1,13 @@
|
||||
import { Check, ChevronDown } from 'lucide-react'
|
||||
import { cn } from '@/lib'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { STEPS } from '@/features/chat/lib/negoSteps'
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean
|
||||
setIsOpen: (isOpen: boolean) => void
|
||||
}
|
||||
|
||||
export const STEPS = [
|
||||
{ name: '서비스안내', desc: '협상 방식과 유의사항을 확인합니다.' },
|
||||
{ name: '담당자확인', desc: '협상 담당자 본인 여부를 확인합니다.' },
|
||||
{ name: '협상품목안내', desc: '대상 품목과 기준 단가를 확인합니다.' },
|
||||
{ name: '가격협상', desc: '공급 단가를 제안하고 조율합니다.' },
|
||||
{ name: '협상종료', desc: '최종 합의 후 결과를 확인합니다.' },
|
||||
]
|
||||
|
||||
export function NegoStep({ isOpen, setIsOpen }: Props) {
|
||||
const chats = useChatStore((s) => s.messages)
|
||||
const currentStep = chats[chats.length - 1]?.display_step || '서비스안내'
|
||||
|
||||
@@ -1,17 +1,40 @@
|
||||
import { CheckCircle2 } from 'lucide-react'
|
||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||
import { useMeQuery } from '@/apis'
|
||||
import type { SessionField } from '@/apis/auth/auth.type'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
|
||||
interface BidSummaryProps {
|
||||
itemName: string
|
||||
itemCode: string
|
||||
bidPrice: number
|
||||
deliveryType: string
|
||||
isVAT: boolean
|
||||
}
|
||||
|
||||
// 부가정보 값 표시 포맷(불리언→예/아니오, 숫자→천단위, 그 외→문자열)
|
||||
function formatFieldValue(type: SessionField['type'], value: unknown): string {
|
||||
if (type === 'boolean') return value ? '예' : '아니오'
|
||||
if (type === 'number') return Number(value).toLocaleString()
|
||||
return String(value)
|
||||
}
|
||||
|
||||
// 투찰 결과 요약 카드 (보고서식 final-summary)
|
||||
export function BidSummary({ itemName, itemCode, bidPrice, deliveryType, isVAT }: BidSummaryProps) {
|
||||
// 공급사가 마무리에서 입력한 부가정보(회사설정 session_fields + 의견)가 있으면 함께 표시한다(입력완료 시 요약 갱신).
|
||||
export function BidSummary({ itemName, itemCode, bidPrice }: BidSummaryProps) {
|
||||
// VAT 표기는 회사 설정 기준(item_vat_yn). vat_yn 미관리(hidden)면 비어 라벨을 생략한다.
|
||||
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
|
||||
const custom = useChatInitStore((s) => s.custom)
|
||||
const { data: user } = useMeQuery()
|
||||
const fields: SessionField[] = user?.sessionFields ?? []
|
||||
const priceStr = (bidPrice || 0).toLocaleString()
|
||||
|
||||
// 부가정보(회사설정 session_fields) — 완료 요약엔 구조를 항상 노출(미입력 값은 '-')
|
||||
const extraRows = fields.map((f) => {
|
||||
const v = custom?.[f.key]
|
||||
const has = v !== undefined && v !== null && v !== ''
|
||||
return { key: f.key, label: f.label, value: has ? formatFieldValue(f.type, v) : '-' }
|
||||
})
|
||||
const opinion = custom?.opinion ? String(custom.opinion) : ''
|
||||
|
||||
return (
|
||||
<div className="w-full rounded-2xl border-2 border-brand-light bg-white p-5 shadow-md">
|
||||
<div className="mb-4 flex items-center gap-2">
|
||||
@@ -27,10 +50,14 @@ export function BidSummary({ itemName, itemCode, bidPrice, deliveryType, isVAT }
|
||||
<span className="min-w-0 flex-1 break-keep text-right text-sm">
|
||||
<span className="font-bold text-[#E5484D]">{priceStr}원</span>
|
||||
<span className="text-neutral-70"> ({numberToKorean(bidPrice || 0)}원)</span>
|
||||
<span className="text-neutral-70"> {isVAT ? 'VAT포함' : 'VAT별도'}</span>
|
||||
{item_vat_yn ? <span className="text-neutral-70"> {item_vat_yn}</span> : null}
|
||||
</span>
|
||||
</div>
|
||||
<Row label="배송형태" value={deliveryType || '-'} />
|
||||
{extraRows.map((r) => (
|
||||
<Row key={r.key} label={r.label} value={r.value} />
|
||||
))}
|
||||
{/* 의견은 타결·결렬 공통 기본 필드 — 값이 없어도 항상 표시 */}
|
||||
<Row label="의견" value={opinion || '-'} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ export function OtherReason({
|
||||
onChange,
|
||||
isError,
|
||||
disabled,
|
||||
onSubmit,
|
||||
}: {
|
||||
inputValue: string
|
||||
setInputValue: (value: string) => void
|
||||
@@ -18,6 +19,7 @@ export function OtherReason({
|
||||
onChange: (value: string) => void
|
||||
isError: boolean
|
||||
disabled?: boolean
|
||||
onSubmit?: () => void
|
||||
}) {
|
||||
const isChecked = selectedValue === '기타'
|
||||
const ref = useRef<HTMLTextAreaElement>(null)
|
||||
@@ -73,6 +75,13 @@ export function OtherReason({
|
||||
)}
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
// Enter=제출, Shift+Enter=줄바꿈. 한글 조합 중 Enter 는 무시.
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && onSubmit) {
|
||||
e.preventDefault()
|
||||
onSubmit()
|
||||
}
|
||||
}}
|
||||
placeholder="제시한 가격을 수용할 수 없는 이유를 작성해주세요."
|
||||
disabled={isTextareaDisabled}
|
||||
rows={1}
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import { cn } from '@/lib'
|
||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||
import { findRestoreScript, extractPart } from '@/features/chat/lib/rejectForm'
|
||||
import { SelectRadio, SubmitButton } from '@/features/chat/components/templates/rejectControls'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
|
||||
const MAX_PRICE = 999999999999999
|
||||
|
||||
// 재견적 실패 시: 최종 공급 희망 가격 + 배송 형태 입력 폼
|
||||
export function RejectCM() {
|
||||
const isLoading = useChatStore((s) => s.isLoading)
|
||||
const sendMessage = useChatStore((s) => s.sendMessage)
|
||||
const messages = useChatStore((s) => s.messages)
|
||||
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
|
||||
const isVAT = item_vat_yn === 'VAT별도'
|
||||
|
||||
// 폼 값은 이전 제출 내역에서 1회만 복원 (setter 미사용 = lazy 초기화 전용)
|
||||
const restored = useState(() => findRestoreScript(messages, 'rejectCM'))[0]
|
||||
const [price, setPrice] = useState(() => extractPart(restored, '공급희망가격-'))
|
||||
const [selectedReason, setSelectedReason] = useState(() => extractPart(restored, '배송형태-'))
|
||||
const [priceErrorMessage, setPriceErrorMessage] = useState('')
|
||||
const [radioErrorMessage, setRadioErrorMessage] = useState('')
|
||||
|
||||
// 제출 완료 여부는 messages 변화에 반응해야 함 (제출 후 갱신 반영)
|
||||
const isSubmitted = useMemo(() => Boolean(findRestoreScript(messages, 'rejectCM')), [messages])
|
||||
const isValid = Boolean(price && parseInt(price) > 0) && Boolean(selectedReason)
|
||||
|
||||
const handlePriceChange = (value: string) => {
|
||||
const numeric = value.replace(/\D/g, '')
|
||||
if (numeric && parseInt(numeric) > MAX_PRICE) return
|
||||
setPrice(numeric)
|
||||
if (numeric) setPriceErrorMessage('')
|
||||
}
|
||||
|
||||
const koreanPrice = (() => {
|
||||
if (!price) return '영'
|
||||
const n = parseInt(price)
|
||||
return Number.isNaN(n) || n === 0 ? '영' : numberToKorean(n)
|
||||
})()
|
||||
|
||||
const handleSubmit = () => {
|
||||
setPriceErrorMessage(!price || parseInt(price) === 0 ? '가격을 입력해주세요.' : '')
|
||||
setRadioErrorMessage(!selectedReason ? '배송 형태를 선택해주세요.' : '')
|
||||
if (isValid && !isLoading && !isSubmitted) {
|
||||
sendMessage(`공급희망가격-${price}, 배송형태-${selectedReason}`, 'text')
|
||||
}
|
||||
}
|
||||
|
||||
const isDisabled = isLoading || isSubmitted
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full p-8 bg-white rounded-2xl border border-border shadow-sm gap-2 transition-all duration-300">
|
||||
<div className="flex w-full items-center justify-center gap-2 rounded-xl bg-[#FFF1F1] px-4 py-3 text-sm font-bold text-[#E5484D]">
|
||||
<AlertTriangle className="size-5 shrink-0" />
|
||||
최종 공급 희망 가격 입력
|
||||
</div>
|
||||
|
||||
<div className="py-2 text-sm leading-relaxed text-neutral-70 break-keep">
|
||||
최종 공급 희망 가격과 배송 형태를 입력하여 주시기 바랍니다.
|
||||
<br />
|
||||
가격 검토를 통해 경쟁력 있는 가격일 경우 다시 협상에 참여할 기회가 주어지오니 신중한 가격 제안 부탁드립니다.
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col w-full gap-1">
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<div className="w-[100px] shrink-0 pt-2.5 text-sm font-bold text-neutral-90">공급 희망 가격</div>
|
||||
<div className="flex w-full flex-wrap items-center gap-2 pt-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
className={cn(
|
||||
'h-10 max-w-[200px] rounded-xl border px-3 text-right text-sm outline-none transition-all placeholder:text-neutral-50',
|
||||
isDisabled
|
||||
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
|
||||
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
|
||||
)}
|
||||
value={price ? parseInt(price).toLocaleString() : ''}
|
||||
onChange={(e) => handlePriceChange(e.target.value)}
|
||||
placeholder="0"
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<div className="whitespace-nowrap text-sm text-neutral-70">원{isVAT && '(VAT 별도)'}</div>
|
||||
</div>
|
||||
<div className="whitespace-nowrap text-sm text-neutral-50">[{koreanPrice} 원]</div>
|
||||
</div>
|
||||
</div>
|
||||
{priceErrorMessage && <div className="pl-[112px] text-xs font-medium text-negative">{priceErrorMessage}</div>}
|
||||
</div>
|
||||
|
||||
<div className="flex w-full gap-3">
|
||||
<div className="w-[100px] shrink-0 pt-2 text-sm font-bold text-neutral-90">배송 형태</div>
|
||||
<div className="flex w-full flex-wrap items-center gap-x-6 gap-y-2">
|
||||
{['협력사배송', '지정택배배송', '픽업배송'].map((opt) => (
|
||||
<SelectRadio
|
||||
key={opt}
|
||||
text={opt === '협력사배송' ? '협력사 배송' : opt}
|
||||
value={opt}
|
||||
name="rejectcm"
|
||||
selectedValue={selectedReason}
|
||||
onChange={(v) => {
|
||||
setSelectedReason(v)
|
||||
setRadioErrorMessage('')
|
||||
}}
|
||||
errorMessage={radioErrorMessage}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full items-center justify-center mt-4">
|
||||
<SubmitButton isValid={isValid} isLoading={isLoading} isSubmitted={isSubmitted} onSubmit={handleSubmit} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import { cn } from '@/lib'
|
||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
import { SelectRadio, SubmitButton } from '@/features/chat/components/templates/rejectControls'
|
||||
import { OtherReason } from '@/features/chat/components/templates/OtherReason'
|
||||
import { findRestoreScript, restoreRejectRSP } from '@/features/chat/lib/rejectForm'
|
||||
|
||||
const MAX_PRICE = 999999999999999
|
||||
|
||||
const REASONS = [
|
||||
{ value: '단가인상', text: "'원재료 가격 상승' 또는 '제조사 가격 인상'으로 요청한 공급가격을 맞출 수 없습니다." },
|
||||
{ value: '수량', text: '주문 수량이 적어, 소량 생산 시 발생하는 제조비용으로 맞출 수 없습니다.' },
|
||||
{ value: '단종', text: '현재 단종된 제품으로 물량 수급이 원활하지 않아 가격을 맞출 수 없습니다.' },
|
||||
{ value: '품절', text: '해당 상품이 품절되어 납품할 수 없습니다.' },
|
||||
]
|
||||
|
||||
// 협상 합의 불가 시: 최종 제안 단가 + 합의 불가 사유 입력 폼
|
||||
export function RejectRSP() {
|
||||
const isLoading = useChatStore((s) => s.isLoading)
|
||||
const sendMessage = useChatStore((s) => s.sendMessage)
|
||||
const messages = useChatStore((s) => s.messages)
|
||||
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
|
||||
const isVAT = item_vat_yn === 'VAT별도'
|
||||
|
||||
// 폼 값은 이전 제출 내역에서 1회만 복원 (setter 미사용 = lazy 초기화 전용)
|
||||
const restored = useState(() => restoreRejectRSP(findRestoreScript(messages, 'rejectRSP')))[0]
|
||||
const [price, setPrice] = useState(restored.price)
|
||||
const [selectedReason, setSelectedReason] = useState(restored.selectedReason)
|
||||
const [reason, setReason] = useState(restored.reason)
|
||||
const [otherErrorMessage, setOtherErrorMessage] = useState('')
|
||||
const [priceErrorMessage, setPriceErrorMessage] = useState('')
|
||||
const [radioErrorMessage, setRadioErrorMessage] = useState('')
|
||||
|
||||
const isSubmitted = useMemo(
|
||||
() => Boolean(findRestoreScript(messages, 'rejectRSP')),
|
||||
[messages],
|
||||
)
|
||||
const isValid =
|
||||
Boolean(price && parseInt(price) > 0) &&
|
||||
Boolean(selectedReason) &&
|
||||
(selectedReason !== '기타' || reason.trim() !== '')
|
||||
|
||||
const handlePriceChange = (value: string) => {
|
||||
const numeric = value.replace(/\D/g, '')
|
||||
if (numeric && parseInt(numeric) > MAX_PRICE) return
|
||||
setPrice(numeric)
|
||||
if (numeric) setPriceErrorMessage('')
|
||||
}
|
||||
|
||||
const handleRadioChange = (value: string) => {
|
||||
setSelectedReason(value)
|
||||
setRadioErrorMessage('')
|
||||
if (value !== '기타') {
|
||||
setReason('')
|
||||
setOtherErrorMessage('')
|
||||
}
|
||||
}
|
||||
|
||||
const koreanPrice = (() => {
|
||||
if (!price) return '영'
|
||||
const n = parseInt(price)
|
||||
return Number.isNaN(n) || n === 0 ? '영' : numberToKorean(n)
|
||||
})()
|
||||
|
||||
const handleSubmit = () => {
|
||||
setPriceErrorMessage(!price || parseInt(price) === 0 ? '가격을 입력해주세요.' : '')
|
||||
setRadioErrorMessage(!selectedReason ? '사유를 선택해주세요.' : '')
|
||||
setOtherErrorMessage(selectedReason === '기타' && !reason.trim() ? '기타 사유를 입력해주세요.' : '')
|
||||
if (isValid && !isLoading && !isSubmitted) {
|
||||
const script =
|
||||
selectedReason === '기타'
|
||||
? `공급희망가격-${price}, 합의불가사유-기타-${reason.trim()}`
|
||||
: `공급희망가격-${price}, 합의불가사유-${selectedReason}`
|
||||
sendMessage(script, 'text')
|
||||
}
|
||||
}
|
||||
|
||||
const isDisabled = isLoading || isSubmitted
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full p-8 bg-white rounded-2xl border border-border shadow-sm gap-2 transition-all duration-300">
|
||||
<div className="flex w-full items-center justify-center gap-2 rounded-xl bg-[#FFF1F1] px-4 py-3 text-sm font-bold text-[#E5484D]">
|
||||
<AlertTriangle className="size-5 shrink-0" />
|
||||
협상 합의 불가 사유 및 최종 제안 단가 입력
|
||||
</div>
|
||||
|
||||
<div className="py-2 text-sm leading-relaxed text-neutral-70 break-keep">
|
||||
협상이 합의에 도달하지 못하였습니다. 최종 희망하는 가격을 입력해주시기 바랍니다.
|
||||
<br />
|
||||
추가로 제시한 가격을 수용할 수 없는 이유를 선택하여 주시기 바라며, 목록에 없는 경우 기타 항목 선택 후 간단한 사유를
|
||||
기재하여 주시기 바랍니다.
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col w-full gap-1">
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<div className="w-[100px] shrink-0 pt-2.5 text-sm font-bold text-neutral-90">공급 희망 가격</div>
|
||||
<div className="flex w-full flex-wrap items-center gap-2 pt-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
className={cn(
|
||||
'h-10 max-w-[200px] rounded-xl border px-3 text-right text-sm outline-none transition-all placeholder:text-neutral-50',
|
||||
isDisabled
|
||||
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
|
||||
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
|
||||
)}
|
||||
value={price ? parseInt(price).toLocaleString() : ''}
|
||||
onChange={(e) => handlePriceChange(e.target.value)}
|
||||
placeholder="0"
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<div className="whitespace-nowrap text-sm text-neutral-70">원{isVAT && '(VAT 별도)'}</div>
|
||||
</div>
|
||||
<div className="whitespace-nowrap text-sm text-neutral-50">[{koreanPrice} 원]</div>
|
||||
</div>
|
||||
</div>
|
||||
{priceErrorMessage && <div className="pl-[112px] text-xs font-medium text-negative">{priceErrorMessage}</div>}
|
||||
</div>
|
||||
|
||||
<div className="flex w-full gap-3">
|
||||
<div className="w-[100px] shrink-0 pt-2 text-sm font-bold text-neutral-90">합의 불가 사유</div>
|
||||
<div className="flex w-full flex-col mt-2 gap-2">
|
||||
{REASONS.map((r) => (
|
||||
<SelectRadio
|
||||
key={r.value}
|
||||
text={r.text}
|
||||
value={r.value}
|
||||
name="rejectrsp"
|
||||
selectedValue={selectedReason}
|
||||
onChange={handleRadioChange}
|
||||
errorMessage={radioErrorMessage}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
))}
|
||||
<OtherReason
|
||||
inputValue={reason}
|
||||
setInputValue={(v) => {
|
||||
if (selectedReason !== '기타') return
|
||||
setReason(v)
|
||||
if (v.trim()) setOtherErrorMessage('')
|
||||
}}
|
||||
errorMessage={otherErrorMessage}
|
||||
selectedValue={selectedReason}
|
||||
onChange={handleRadioChange}
|
||||
isError={!!radioErrorMessage}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full items-center justify-center mt-6">
|
||||
<SubmitButton isValid={isValid} isLoading={isLoading} isSubmitted={isSubmitted} onSubmit={handleSubmit} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,11 +1,20 @@
|
||||
import { CheckCircle2 } from 'lucide-react'
|
||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||
import { formatLeadTime } from '@/features/chat/lib/format'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
import type { ChatSummary } from '@/features/chat/types'
|
||||
|
||||
// 협상 결과 요약 카드
|
||||
export function Summary({ data }: { data: ChatSummary }) {
|
||||
const priceStr = (data.final_price || 0).toLocaleString()
|
||||
// VAT 표기는 회사 설정 기준(item_vat_yn). vat_yn 미관리(hidden)면 비어 라벨을 생략한다.
|
||||
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
|
||||
// 공급사가 마무리에서 남긴 의견(있을 때만 표시)
|
||||
const custom = useChatInitStore((s) => s.custom)
|
||||
const opinion = custom?.opinion ? String(custom.opinion) : ''
|
||||
// 납기 라벨은 회사 설정(labels.lead_time) 기준 — IMK 등은 '표준납기'. 미설정 시 기본 '배송 리드타임'.
|
||||
const labels = useChatInitStore((s) => s.labels)
|
||||
const leadTimeLabel = labels?.['lead_time'] || '배송 리드타임'
|
||||
|
||||
return (
|
||||
<div className="w-full rounded-2xl border border-border bg-white p-5 shadow-sm">
|
||||
@@ -37,22 +46,24 @@ export function Summary({ data }: { data: ChatSummary }) {
|
||||
<Row label="제품 규격" value={data.item_spec || '-'} />
|
||||
<Row label="최소 주문" value={data.item_moq || '-'} />
|
||||
<Row label="배송 형태" value={data.item_delivery_type || '-'} />
|
||||
<Row label="배송 리드타임" value={formatLeadTime(data.item_lead_time) || '-'} />
|
||||
<Row label={leadTimeLabel} value={formatLeadTime(data.item_lead_time) || '-'} />
|
||||
<div className="flex items-start justify-between gap-3 px-4 py-3">
|
||||
<span className="shrink-0 text-sm text-neutral-60">최종 협의 가격</span>
|
||||
<span className="min-w-0 flex-1 break-keep text-right text-sm">
|
||||
<span className="font-bold text-[#E5484D]">{priceStr}원</span>
|
||||
<span className="text-neutral-70"> ({numberToKorean(data.final_price || 0)}원)</span>
|
||||
<span className="text-neutral-70"> {data.item_isVAT ? 'VAT포함' : 'VAT별도'}</span>
|
||||
{item_vat_yn ? <span className="text-neutral-70"> {item_vat_yn}</span> : null}
|
||||
</span>
|
||||
</div>
|
||||
{/* 의견은 타결·결렬 공통 기본 필드 — 값이 없어도 항상 표시 */}
|
||||
<Row label="의견" value={opinion || '-'} />
|
||||
</div>
|
||||
|
||||
{/* 계약 / 담당 MD */}
|
||||
{/* 계약 / 구매담당자 */}
|
||||
<div className="mt-3 space-y-1 text-xs text-neutral-70">
|
||||
<p>공급 계약 기간: 협상 완료일로부터 1년 ({addOneYear(data.nego_end_date)})까지</p>
|
||||
<p>
|
||||
담당 MD: {data.md_name || '-'} ({data.md_phone_number || '-'}) {data.md_email || '-'}
|
||||
구매담당자: {data.md_name || '-'} ({data.md_phone_number || '-'}) {data.md_email || '-'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useRef, useId } from 'react'
|
||||
import { useState, useRef, useId, useEffect } from 'react'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
|
||||
// 단위(원/%) 오버레이 + 전송 버튼이 붙은 값 입력 (Percent / Price 공용)
|
||||
@@ -22,8 +22,22 @@ function InputWithUnit({
|
||||
ariaLabel: string
|
||||
}) {
|
||||
const errorId = useId()
|
||||
// 입력 단계(percent/price)로 바뀌어 마운트될 때마다 바로 타이핑 가능하게
|
||||
useEffect(() => {
|
||||
inputRef.current?.focus()
|
||||
}, [inputRef])
|
||||
return (
|
||||
<div className="relative flex flex-col gap-3">
|
||||
<div className="relative">
|
||||
{/* 레이아웃 밖(absolute)에 띄워 에러가 떠도 input 위치가 안 변한다 */}
|
||||
{error && (
|
||||
<div
|
||||
id={errorId}
|
||||
role="alert"
|
||||
className="absolute bottom-full left-1/2 -translate-x-1/2 mb-3 whitespace-nowrap rounded-full bg-white border border-border shadow-md px-4 py-1.5 text-sm font-semibold text-negative"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="relative flex items-center min-w-[220px] sm:min-w-[360px] min-[1180px]:min-w-[420px] min-[1350px]:min-w-[480px]">
|
||||
<input
|
||||
ref={inputRef}
|
||||
@@ -51,11 +65,6 @@ function InputWithUnit({
|
||||
전송
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<div id={errorId} role="alert" className="absolute top-[62px] left-1/2 -translate-x-1/2 text-sm font-semibold text-negative w-full text-center">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
// 협상 절차 5단계 — NegoStep(사이드) · MobileStepBar(모바일 상단)가 공유.
|
||||
export const STEPS = [
|
||||
{ name: '서비스안내', desc: '협상 방식과 유의사항을 확인합니다.' },
|
||||
{ name: '담당자확인', desc: '협상 담당자 본인 여부를 확인합니다.' },
|
||||
{ name: '협상품목안내', desc: '대상 품목과 기준 단가를 확인합니다.' },
|
||||
{ name: '가격협상', desc: '공급 단가를 제안하고 조율합니다.' },
|
||||
{ name: '협상종료', desc: '최종 합의 후 결과를 확인합니다.' },
|
||||
]
|
||||
@@ -16,7 +16,14 @@ export function deriveUserButtonConfig(
|
||||
const options = last.next_input_type
|
||||
|
||||
if (last.chat_end) return { type: 'one-black', text: GO_TO_LIST_TEXT }
|
||||
if (mode === 'confirm') return { type: 'one-black', text: options?.[0] || '' }
|
||||
// 결렬 폼(rejectRSP/rejectCM)은 통일된 RejectForm 을 액션바에서 받는다(메시지 카드 아님).
|
||||
if (last.bot_chat_type === 'rejectRSP' || last.bot_chat_type === 'rejectCM') return { type: 'reject' }
|
||||
// 타결 요약이 뜬 뒤의 '동의' 단계 = 부가정보 입력 + 동의를 한 자리(액션바)에서 받는다.
|
||||
// (요약 이후 confirm 단계에만 적용 — 재견적의 투찰확정/정보수정 같은 선택 단계는 그대로 둔다.)
|
||||
const dealt = messages.some((m) => m.bot_chat_type === 'summaryRSP' || m.bot_chat_type === 'summaryCM')
|
||||
if (mode === 'confirm') {
|
||||
return dealt ? { type: 'extra-info', text: options?.[0] || '' } : { type: 'one-black', text: options?.[0] || '' }
|
||||
}
|
||||
if (mode === 'yes_no') return { type: 'black-white', textList: options || [] }
|
||||
if (mode === 'percent') return { type: 'percent' }
|
||||
if (mode === 'price') return { type: 'price', priceErrorMessage: priceErrorMessage || undefined }
|
||||
|
||||
@@ -16,6 +16,7 @@ const initialState: ChatInitData = {
|
||||
session_status: 0,
|
||||
item_id: '',
|
||||
quotation_id: '',
|
||||
qt_number: '',
|
||||
item_name: '',
|
||||
item_code: '',
|
||||
item_image: '',
|
||||
@@ -30,6 +31,7 @@ const initialState: ChatInitData = {
|
||||
quotation_memo: '',
|
||||
quotation_end_time: '',
|
||||
custom: {},
|
||||
labels: {},
|
||||
}
|
||||
|
||||
export const useChatInitStore = create<ChatInitStore>((set) => ({
|
||||
|
||||
@@ -53,6 +53,8 @@ export type UserButtonType =
|
||||
| 'percent'
|
||||
| 'three-black'
|
||||
| 'price'
|
||||
| 'extra-info'
|
||||
| 'reject'
|
||||
| 'loading'
|
||||
| ''
|
||||
|
||||
@@ -68,6 +70,7 @@ export type ChatInitData = {
|
||||
session_status: number // SessionStatus 코드 (진입 시점 기준)
|
||||
item_id: string
|
||||
quotation_id: string
|
||||
qt_number: string
|
||||
item_name: string
|
||||
item_code: string
|
||||
item_image: string
|
||||
@@ -82,4 +85,5 @@ export type ChatInitData = {
|
||||
quotation_memo: string
|
||||
quotation_end_time: string
|
||||
custom: Record<string, unknown> // 협상완료 부가정보 기존 입력값(프리필용)
|
||||
labels: Record<string, string> // 회사 커스텀 라벨(companies.settings.labels). 상품 상세 필드명 치환용
|
||||
}
|
||||
@@ -22,6 +22,9 @@ export function ExtraInfoPopup({ target, onClose, onSubmit }: ExtraInfoPopupProp
|
||||
for (const f of fields) init[f.key] = target.custom?.[f.key] ?? (f.type === 'boolean' ? false : '')
|
||||
return init
|
||||
})
|
||||
const [opinion, setOpinion] = useState<string>(() => String(target.custom?.opinion ?? ''))
|
||||
// 부가정보는 협상 완료(동의) 시점에 확정 — 리스트에서는 항상 읽기전용(보기). 입력은 완료 챗에서만.
|
||||
const readOnly = true
|
||||
|
||||
const set = (key: string, value: unknown) => setValues((v) => ({ ...v, [key]: value }))
|
||||
|
||||
@@ -33,6 +36,7 @@ export function ExtraInfoPopup({ target, onClose, onSubmit }: ExtraInfoPopupProp
|
||||
if (f.type === 'boolean') out[f.key] = !!v
|
||||
else if (v !== '' && v != null) out[f.key] = f.type === 'number' ? Number(v) : v
|
||||
}
|
||||
if (opinion.trim()) out.opinion = opinion.trim()
|
||||
onSubmit(out)
|
||||
onClose()
|
||||
}
|
||||
@@ -42,8 +46,11 @@ export function ExtraInfoPopup({ target, onClose, onSubmit }: ExtraInfoPopupProp
|
||||
<div className="w-full max-w-md overflow-hidden rounded-2xl border border-border bg-white shadow-xl animate-scale-in">
|
||||
<div className="flex items-center justify-between border-b border-border p-5">
|
||||
<div>
|
||||
<h3 className="text-base font-bold text-neutral-90">협상완료 부가정보</h3>
|
||||
<p className="mt-0.5 text-xs text-neutral-60">{target.qt_number} · {target.item_name}</p>
|
||||
<h3 className="text-base font-bold text-neutral-90">협상완료 부가정보{readOnly ? ' (보기)' : ''}</h3>
|
||||
<p className="mt-0.5 text-xs text-neutral-60">
|
||||
{target.qt_number} · {target.item_name}
|
||||
{readOnly ? ' · 제출 후에는 수정할 수 없습니다.' : ''}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
@@ -56,10 +63,7 @@ export function ExtraInfoPopup({ target, onClose, onSubmit }: ExtraInfoPopupProp
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 p-5">
|
||||
{fields.length === 0 ? (
|
||||
<p className="py-6 text-center text-sm text-neutral-60">입력할 부가정보 항목이 없습니다.</p>
|
||||
) : (
|
||||
fields.map((f) => (
|
||||
{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' ? (
|
||||
@@ -67,8 +71,9 @@ export function ExtraInfoPopup({ target, onClose, onSubmit }: ExtraInfoPopupProp
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={!!values[f.key]}
|
||||
disabled={readOnly}
|
||||
onClick={() => set(f.key, !values[f.key])}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors disabled:opacity-60 disabled:cursor-not-allowed ${
|
||||
values[f.key] ? 'bg-brand-600' : 'bg-neutral-30'
|
||||
}`}
|
||||
>
|
||||
@@ -78,36 +83,73 @@ export function ExtraInfoPopup({ target, onClose, onSubmit }: ExtraInfoPopupProp
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
) : f.type === 'select' ? (
|
||||
<select
|
||||
value={String(values[f.key] ?? '')}
|
||||
onChange={(e) => set(f.key, e.target.value)}
|
||||
disabled={readOnly}
|
||||
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:cursor-not-allowed disabled:bg-neutral-10 disabled:text-neutral-60"
|
||||
>
|
||||
<option value="">선택</option>
|
||||
{(f.options ?? []).map((o) => (
|
||||
<option key={o} value={o}>{o}</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
type={f.type === 'number' ? 'number' : 'text'}
|
||||
value={String(values[f.key] ?? '')}
|
||||
onChange={(e) => set(f.key, e.target.value)}
|
||||
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={readOnly}
|
||||
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:cursor-not-allowed disabled:bg-neutral-10 disabled:text-neutral-60"
|
||||
placeholder={f.label}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
))}
|
||||
<div className="space-y-1.5">
|
||||
<label className="block text-sm font-semibold text-neutral-80">
|
||||
의견 <span className="font-normal text-neutral-50">(선택)</span>
|
||||
</label>
|
||||
<textarea
|
||||
value={opinion}
|
||||
onChange={(e) => setOpinion(e.target.value)}
|
||||
rows={2}
|
||||
maxLength={255}
|
||||
disabled={readOnly}
|
||||
placeholder="추가로 남길 의견"
|
||||
className="w-full resize-none rounded-xl border border-border bg-white px-3 py-2 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600 disabled:cursor-not-allowed disabled:bg-neutral-10 disabled:text-neutral-60"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 border-t border-border p-5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="h-11 flex-1 rounded-xl border border-border text-sm font-bold text-neutral-70 hover:bg-neutral-10"
|
||||
>
|
||||
취소
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSubmit}
|
||||
disabled={fields.length === 0}
|
||||
className="h-11 flex-1 rounded-xl bg-brand-600 text-sm font-bold text-white hover:bg-brand-700 disabled:opacity-40"
|
||||
>
|
||||
저장
|
||||
</button>
|
||||
{readOnly ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="h-11 flex-1 rounded-xl border border-border text-sm font-bold text-neutral-70 hover:bg-neutral-10"
|
||||
>
|
||||
닫기
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="h-11 flex-1 rounded-xl border border-border text-sm font-bold text-neutral-70 hover:bg-neutral-10"
|
||||
>
|
||||
취소
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSubmit}
|
||||
className="h-11 flex-1 rounded-xl bg-brand-600 text-sm font-bold text-white hover:bg-brand-700 disabled:opacity-40"
|
||||
>
|
||||
저장
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { X } from 'lucide-react'
|
||||
import { Modal } from '@/components'
|
||||
import { cn, interactive } from '@/lib'
|
||||
|
||||
// 공급사 포털 목록 화면 이용안내. 상태(진행)·결과(마감)·재협상 3파트로 최근 추가된 용어를 설명한다.
|
||||
// 헤더의 '이용안내' 버튼으로 여는 수동형 팝업. X·배경 클릭·ESC 로 닫는다.
|
||||
export function GuidePopup({ onClose }: { onClose: () => void }) {
|
||||
return (
|
||||
<Modal onClose={onClose}>
|
||||
<div className="m-4 flex max-h-[90vh] w-full max-w-[560px] flex-col overflow-y-auto rounded-2xl border border-border bg-white p-6 shadow-xl animate-scale-in sm:p-8">
|
||||
<div className="mb-5 flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-extrabold text-neutral-90">이용안내</h2>
|
||||
<p className="mt-1 text-[13px] text-neutral-60">협상 목록의 상태·결과·재협상을 안내합니다.</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="닫기"
|
||||
onClick={onClose}
|
||||
className={cn('flex size-9 shrink-0 items-center justify-center rounded-full bg-neutral-10 text-neutral-70 hover:bg-neutral-20', interactive)}
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-6">
|
||||
<Section title="진행 상태" desc="협상 세션이 지금 어느 단계인지 — 내가 무엇을 할지 알려줍니다.">
|
||||
<Row badge="협상 대기" tone="wait" text="초청받은 협상. 입장해서 가격 협상을 시작하세요." />
|
||||
<Row badge="협상 중" tone="prog" text="가격을 조율하는 중입니다. 이어서 진행하세요." />
|
||||
<Row badge="협상 완료" tone="done" text="가격 제출을 마쳤습니다. 최종 결과는 견적 마감 후 아래 '결과'로 표시됩니다." />
|
||||
<Row badge="협상 미참여" tone="none" text="기한 내 참여하지 않아 종료된 건입니다." />
|
||||
<Row badge="협상 거절" tone="reject" text="내가 참여를 거절한 건입니다." />
|
||||
</Section>
|
||||
|
||||
<Section title="협상 결과" desc="견적이 마감된 뒤 정해지는 낙찰 결과입니다. 마감 전에는 표시되지 않습니다.">
|
||||
<Row badge="낙찰" tone="win" text="내가 낙찰되어 계약 대상이 된 건입니다." />
|
||||
<Row badge="미낙찰" tone="lost" text="다른 공급사가 낙찰되어 이번 계약에서는 제외된 건입니다." />
|
||||
<Row badge="결렬" tone="open" text="낙찰자 없이 마감된 건입니다. 조건이 바뀌었다면 재협상을 요청할 수 있습니다." />
|
||||
</Section>
|
||||
|
||||
<Section title="재협상 요청" desc="결렬(낙찰자 미정 마감) 건에 한해 가능합니다.">
|
||||
<p className="text-[13px] leading-relaxed text-neutral-70">
|
||||
결렬 건의 <b className="font-bold text-neutral-90">재협상 요청</b> 버튼으로 사유·희망가를 담아 요청하면,
|
||||
구매 담당자 검토 후 <b className="font-bold text-neutral-90">승인 시 다음 차수 협상</b>이 새로 열립니다.
|
||||
요청 상태(심사 중·승인·반려)는 목록에서 확인할 수 있습니다.
|
||||
</p>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="mt-7 h-11 w-full rounded-xl bg-brand-600 text-sm font-bold text-white transition-colors hover:bg-brand-700"
|
||||
>
|
||||
확인했어요
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
function Section({ title, desc, children }: { title: string; desc: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<section>
|
||||
<h3 className="text-sm font-extrabold text-neutral-90">{title}</h3>
|
||||
<p className="mb-3 mt-0.5 text-xs text-neutral-60">{desc}</p>
|
||||
<div className="flex flex-col gap-2.5">{children}</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
const TONE: Record<string, string> = {
|
||||
wait: 'bg-brand-light text-brand-700',
|
||||
prog: 'bg-[#FFF3E5] text-[#F5A623]',
|
||||
done: 'bg-[#EAFDF3] text-success',
|
||||
none: 'bg-neutral-20 text-neutral-60',
|
||||
reject: 'bg-[#FFEBEB] text-[#FF4D4F]',
|
||||
win: 'bg-[#EAFDF3] text-success',
|
||||
lost: 'bg-neutral-20 text-neutral-60',
|
||||
open: 'bg-[#FFF3E5] text-[#F5A623]',
|
||||
}
|
||||
|
||||
function Row({ badge, tone, text }: { badge: string; tone: string; text: string }) {
|
||||
return (
|
||||
<div className="flex items-start gap-2.5">
|
||||
<span className={cn('mt-0.5 inline-flex shrink-0 items-center rounded-full px-2.5 py-1 text-xs font-bold', TONE[tone])}>
|
||||
{badge}
|
||||
</span>
|
||||
<p className="text-[13px] leading-relaxed text-neutral-70">{text}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,54 +1,85 @@
|
||||
import { AlertTriangle, CheckCircle2, FileText, RefreshCw } from 'lucide-react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { cn } from '@/lib'
|
||||
import { useSessionCounts, type KpiCount } from '@/features/list/hooks/useSessionCounts'
|
||||
|
||||
// key → 아이콘/색 스타일 (콕핏 카드)
|
||||
const STYLE: Record<string, { icon: typeof FileText; tile: string; iconColor: string; spin?: boolean }> = {
|
||||
created: { icon: FileText, tile: 'bg-brand-light', iconColor: 'text-brand-600' },
|
||||
progress: { icon: RefreshCw, tile: 'bg-sky-50', iconColor: 'text-sky-500', spin: true },
|
||||
done: { icon: CheckCircle2, tile: 'bg-emerald-50', iconColor: 'text-success' },
|
||||
rejected: { icon: AlertTriangle, tile: 'bg-red-50', iconColor: 'text-[#FF4D4F]' },
|
||||
}
|
||||
|
||||
// 목업(claude artifact) 그대로: 진행(내가 할 일=상태축) / 결과(마감 후=결과축) 두 묶음.
|
||||
// 모든 카드 동일 크기·높이 — 강조는 색·CTA 로만. 낙찰=초록, 결렬=amber(재협상 가능), 미낙찰=회색.
|
||||
interface KpiCardsProps {
|
||||
selectedStatus: string | null
|
||||
onSelect: (status: string) => void
|
||||
selectedResult: number | null
|
||||
onSelectStatus: (status: string) => void
|
||||
onSelectResult: (code: number) => void
|
||||
}
|
||||
|
||||
export function KpiCards({ selectedStatus, onSelect }: KpiCardsProps) {
|
||||
const counts = useSessionCounts()
|
||||
// key → 배지 점 색 / 숫자 색 / 카드 배경·테두리 / CTA.
|
||||
const STYLE: Record<string, { dot?: string; num: string; card?: string; cta?: string; ctaText?: string }> = {
|
||||
created: { num: 'text-brand-600' },
|
||||
progress: { num: 'text-neutral-90' },
|
||||
won: { dot: 'bg-success', num: 'text-success', card: 'border-success/40 bg-gradient-to-b from-emerald-50 to-white', cta: 'text-success', ctaText: '★ 계약 대상' },
|
||||
open: { dot: 'bg-warning', num: 'text-warning', card: 'border-warning/40', cta: 'text-warning', ctaText: '▲ 재협상 요청 가능' },
|
||||
lost: { dot: 'bg-neutral-50', num: 'text-neutral-70' },
|
||||
}
|
||||
|
||||
export function KpiCards({ selectedStatus, selectedResult, onSelectStatus, onSelectResult }: KpiCardsProps) {
|
||||
const { progress, result } = useSessionCounts()
|
||||
|
||||
const isActive = (c: KpiCount) =>
|
||||
c.kind === 'status' ? selectedStatus === c.statusLabel : selectedResult === c.resultCode
|
||||
const onClick = (c: KpiCount) =>
|
||||
c.kind === 'status' ? onSelectStatus(c.statusLabel!) : onSelectResult(c.resultCode!)
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-4">
|
||||
{counts.map((c) => (
|
||||
<Card key={c.key} data={c} active={selectedStatus === c.status} onClick={() => onSelect(c.status)} />
|
||||
))}
|
||||
<div className="grid gap-4 lg:grid-cols-[2fr_3fr]">
|
||||
<Cluster label="진행 · 내가 할 일" dot="bg-brand-600" cols="grid-cols-2">
|
||||
{progress.map((c) => (
|
||||
<Card key={c.key} data={c} active={isActive(c)} onClick={() => onClick(c)} />
|
||||
))}
|
||||
</Cluster>
|
||||
<Cluster label="결과 · 마감 후" dot="bg-success" cols="grid-cols-3">
|
||||
{result.map((c) => (
|
||||
<Card key={c.key} data={c} active={isActive(c)} onClick={() => onClick(c)} />
|
||||
))}
|
||||
</Cluster>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Cluster({ label, dot, cols, children }: { label: string; dot: string; cols: string; children: ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-2 flex items-center gap-1.5 px-0.5 text-[11px] font-extrabold uppercase tracking-wider text-neutral-60">
|
||||
<span className={cn('size-1.5 rounded-full', dot)} />
|
||||
{label}
|
||||
</div>
|
||||
<div className={cn('grid gap-2.5', cols)}>{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Card({ data, active, onClick }: { data: KpiCount; active: boolean; onClick: () => void }) {
|
||||
const s = STYLE[data.key]
|
||||
const Icon = s.icon
|
||||
const s = STYLE[data.key] ?? STYLE.created
|
||||
const ctaText = s.ctaText ?? ' ' // 빈 카드도 CTA 줄 높이를 확보(nbsp) → 5개 카드 높이 완전 동일
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
'flex items-center gap-3.5 rounded-2xl border bg-white p-4 text-left transition-all sm:p-5',
|
||||
'hover:shadow-md active:scale-[0.99]',
|
||||
active ? 'border-brand-600 ring-2 ring-brand-600/10 shadow-sm' : 'border-border shadow-sm',
|
||||
'flex h-full flex-col rounded-2xl border bg-white p-4 text-left shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md active:scale-[0.99]',
|
||||
s.card ?? 'border-border',
|
||||
// 오프셋 링이라 카드 배경색(낙찰 초록·결렬 amber)과 무관하게 선택이 또렷하게 보인다.
|
||||
active && 'ring-2 ring-brand-600 ring-offset-2 ring-offset-surface',
|
||||
)}
|
||||
>
|
||||
<div className={cn('flex size-10 shrink-0 items-center justify-center rounded-xl', s.tile)}>
|
||||
<Icon className={cn('size-5', s.iconColor, s.spin && 'animate-spin-slow')} />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-[11px] font-bold text-neutral-60">{data.label}</p>
|
||||
<p className="text-lg font-extrabold tabular-nums text-neutral-90">
|
||||
{data.isLoading ? '–' : data.count.toLocaleString()}
|
||||
<span className="ml-0.5 text-xs font-bold text-neutral-60">건</span>
|
||||
</p>
|
||||
</div>
|
||||
<p className="mb-2 flex items-center gap-1.5 whitespace-nowrap text-xs font-bold text-neutral-70">
|
||||
{s.dot && <span className={cn('size-1.5 rounded-full', s.dot)} />}
|
||||
{data.label}
|
||||
</p>
|
||||
<p className={cn('text-2xl font-extrabold tabular-nums', s.num)}>
|
||||
{data.isLoading ? '–' : data.count.toLocaleString()}
|
||||
<span className="ml-0.5 text-xs font-bold text-neutral-60">건</span>
|
||||
</p>
|
||||
{/* CTA 는 좁은 카드(모바일 3열)에서 nowrap 이면 넘치므로 단어 단위로만 줄바꿈 */}
|
||||
<p className={cn('mt-1.5 break-keep text-[11px] font-extrabold', s.cta)}>{ctaText}</p>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { X } from 'lucide-react'
|
||||
import { Modal } from '@/components'
|
||||
import { RENEGO_STATUS_LABEL } from '@/apis/negotiation/negotiation.type'
|
||||
import type { ListItem } from '../types'
|
||||
|
||||
export interface RenegotiationMemoPopupProps {
|
||||
target: ListItem
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
// 재협상 심사 결과의 담당자 메모 열람 팝업. 목록에는 상태 배지만 두고 메모 전문은 여기서 보여준다.
|
||||
export function RenegotiationMemoPopup({ target, onClose }: RenegotiationMemoPopupProps) {
|
||||
return (
|
||||
<Modal onClose={onClose}>
|
||||
<div className="w-full max-w-md overflow-hidden rounded-2xl border border-border bg-white shadow-xl animate-scale-in">
|
||||
<div className="flex items-center justify-between border-b border-border p-5">
|
||||
<div>
|
||||
<h3 className="text-base font-bold text-neutral-90">
|
||||
{RENEGO_STATUS_LABEL[target.renegotiationStatus] ?? '재협상 심사 결과'}
|
||||
</h3>
|
||||
<p className="mt-0.5 text-xs text-neutral-60">
|
||||
{target.qt_number} · {target.item_name}
|
||||
</p>
|
||||
</div>
|
||||
<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="p-5">
|
||||
<p className="text-sm font-semibold text-neutral-80">담당자 메모</p>
|
||||
<p className="mt-1.5 max-h-64 overflow-y-auto whitespace-pre-wrap break-keep rounded-xl bg-neutral-10 p-3 text-sm leading-relaxed text-neutral-80">
|
||||
{target.renegotiationMemo}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border p-5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="w-full rounded-xl bg-brand-600 py-3 text-sm font-bold text-white shadow-sm transition-all hover:bg-brand-700 active:scale-[0.98]"
|
||||
>
|
||||
확인
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { useState } from 'react'
|
||||
import { X } from 'lucide-react'
|
||||
import { Modal } from '@/components'
|
||||
import type { ListItem } from '../types'
|
||||
|
||||
export interface RenegotiationPopupProps {
|
||||
target: ListItem
|
||||
onClose: () => void
|
||||
onSubmit: (reason: string, desiredPrice: number | null) => void
|
||||
}
|
||||
|
||||
// 재협상 요청 팝업. 결렬(낙찰자 미정) 건에만 열리며, 담당자 승인 시 다음 차수가 생성된다.
|
||||
// 사유는 자주 쓰는 것을 프리셋으로 두고, 직접 입력도 허용한다.
|
||||
const PRESETS = ['가격 조건 재검토', '재고·납기 확보', '단가 정정', '수량 조건 변경'] as const
|
||||
|
||||
export function RenegotiationPopup({ target, onClose, onSubmit }: RenegotiationPopupProps) {
|
||||
const [preset, setPreset] = useState<string>(PRESETS[0])
|
||||
const [custom, setCustom] = useState('')
|
||||
const [price, setPrice] = useState('')
|
||||
|
||||
const isDirect = preset === '직접 입력'
|
||||
const reason = isDirect ? custom.trim() : preset
|
||||
const canSubmit = reason.length > 0
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!canSubmit) return
|
||||
const parsed = Number(price.replace(/[^0-9]/g, ''))
|
||||
onSubmit(reason, parsed > 0 ? parsed : null)
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal onClose={onClose}>
|
||||
<div className="w-full max-w-md overflow-hidden rounded-2xl border border-border bg-white shadow-xl animate-scale-in">
|
||||
<div className="flex items-center justify-between border-b border-border p-5">
|
||||
<div>
|
||||
<h3 className="text-base font-bold text-neutral-90">재협상 요청</h3>
|
||||
<p className="mt-0.5 text-xs text-neutral-60">
|
||||
{target.qt_number} · {target.item_name}
|
||||
</p>
|
||||
</div>
|
||||
<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="space-y-4 p-5">
|
||||
<p className="rounded-xl bg-neutral-10 p-3 text-xs leading-relaxed text-neutral-70">
|
||||
이 건은 낙찰자 없이 마감되었습니다. 요청하면 구매 담당자가 검토 후 승인 시
|
||||
<b> 다시 협상할 기회</b>가 열립니다. 승인·반려 결과는 목록에서 확인할 수 있습니다.
|
||||
</p>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label className="block text-sm font-semibold text-neutral-80">요청 사유</label>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{[...PRESETS, '직접 입력'].map((p) => (
|
||||
<button
|
||||
key={p}
|
||||
type="button"
|
||||
onClick={() => setPreset(p)}
|
||||
className={`rounded-lg border px-3 py-1.5 text-xs font-bold transition-all active:scale-[0.98] ${
|
||||
preset === p
|
||||
? 'border-brand-600 bg-brand-50 text-brand-700'
|
||||
: 'border-border text-neutral-70 hover:bg-neutral-10'
|
||||
}`}
|
||||
>
|
||||
{p}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{isDirect && (
|
||||
<input
|
||||
value={custom}
|
||||
onChange={(e) => setCustom(e.target.value)}
|
||||
maxLength={255}
|
||||
placeholder="요청 사유를 입력해 주세요"
|
||||
className="mt-1.5 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"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label className="block text-sm font-semibold text-neutral-80">
|
||||
희망 공급가 <span className="font-medium text-neutral-60">(선택)</span>
|
||||
</label>
|
||||
<input
|
||||
inputMode="numeric"
|
||||
value={price}
|
||||
onChange={(e) => setPrice(e.target.value)}
|
||||
placeholder="예: 14,500,000"
|
||||
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"
|
||||
/>
|
||||
<p className="text-xs text-neutral-60">담당자 검토 참고용입니다. 실제 가격은 재협상에서 다시 조율합니다.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 border-t border-border p-5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="flex-1 rounded-xl border border-border py-3 text-sm font-bold text-neutral-70 transition-all hover:bg-neutral-10 active:scale-[0.98]"
|
||||
>
|
||||
취소
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSubmit}
|
||||
disabled={!canSubmit}
|
||||
className="flex-[2] rounded-xl bg-brand-600 py-3 text-sm font-bold text-white shadow-sm transition-all hover:bg-brand-700 active:scale-[0.98] disabled:opacity-50"
|
||||
>
|
||||
요청 보내기
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { cn } from '@/lib'
|
||||
|
||||
// 마감 기준 정렬. value(null=기본 그룹정렬)는 store.selectedDeadline 로 그대로 전달되고,
|
||||
// adapter.deadlineToOrder 가 '남은 시간 적은 순'=asc(임박), 그 외=desc(여유) 로 매핑한다.
|
||||
const SORT_OPTIONS: { label: string; value: string | null }[] = [
|
||||
{ label: '기본순', value: null },
|
||||
{ label: '마감임박순', value: '남은 시간 적은 순' },
|
||||
{ label: '여유순', value: '남은 시간 긴 순' },
|
||||
]
|
||||
|
||||
interface SortControlProps {
|
||||
selected: string | null
|
||||
onSelect: (value: string | null) => void
|
||||
}
|
||||
|
||||
export function SortControl({ selected, onSelect }: SortControlProps) {
|
||||
return (
|
||||
<div className="flex items-center gap-0.5 rounded-xl border border-border bg-neutral-10 p-0.5">
|
||||
{SORT_OPTIONS.map((o) => {
|
||||
const active = selected === o.value
|
||||
return (
|
||||
<button
|
||||
key={o.label}
|
||||
type="button"
|
||||
onClick={() => onSelect(o.value)}
|
||||
className={cn(
|
||||
'whitespace-nowrap rounded-[10px] px-2.5 py-[6px] text-xs font-bold transition-all active:scale-[0.98]',
|
||||
active ? 'bg-white text-brand-700 shadow-sm' : 'text-neutral-60 hover:text-neutral-80',
|
||||
)}
|
||||
>
|
||||
{o.label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -18,7 +18,7 @@ interface StatusTabsProps {
|
||||
|
||||
export function StatusTabs({ selected, onSelect }: StatusTabsProps) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-1 rounded-xl bg-neutral-20 p-1">
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
{TABS.map((t) => {
|
||||
const active = selected === t.value
|
||||
return (
|
||||
@@ -27,8 +27,8 @@ export function StatusTabs({ selected, onSelect }: StatusTabsProps) {
|
||||
type="button"
|
||||
onClick={() => onSelect(t.value)}
|
||||
className={cn(
|
||||
'rounded-lg px-3.5 py-1.5 text-[13px] font-bold transition-all active:scale-[0.98]',
|
||||
active ? 'bg-white text-neutral-90 shadow-sm' : 'text-neutral-60 hover:text-neutral-80',
|
||||
'whitespace-nowrap rounded-[10px] px-3 py-[7px] text-[13px] font-bold transition-all active:scale-[0.98]',
|
||||
active ? 'bg-brand-light text-brand-700' : 'text-neutral-60 hover:text-neutral-80',
|
||||
)}
|
||||
>
|
||||
{t.label}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Loader2, MessageSquareText } from 'lucide-react'
|
||||
import { cn, formatKstDateTime } from '@/lib'
|
||||
import { RENEGO_STATUS_LABEL } from '@/apis/negotiation/negotiation.type'
|
||||
import type { ListItem } from '@/features/list/types'
|
||||
import { statusMeta } from '@/features/list/lib/status'
|
||||
import { statusMeta, RESULT_META } from '@/features/list/lib/status'
|
||||
|
||||
interface WorkspaceCardsProps {
|
||||
items: ListItem[]
|
||||
@@ -10,10 +11,12 @@ interface WorkspaceCardsProps {
|
||||
onEnter: (item: ListItem) => void
|
||||
onReject: (item: ListItem) => void
|
||||
onExtraInfo: (item: ListItem) => void
|
||||
onRenegotiate: (item: ListItem) => void
|
||||
onMemo: (item: ListItem) => void
|
||||
}
|
||||
|
||||
// 모바일(lg 미만) 협상 목록: 테이블 대신 카드 스택.
|
||||
export function WorkspaceCards({ items, isLoading, busyId, onEnter, onReject, onExtraInfo }: WorkspaceCardsProps) {
|
||||
export function WorkspaceCards({ items, isLoading, busyId, onEnter, onReject, onExtraInfo, onRenegotiate, onMemo }: WorkspaceCardsProps) {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
@@ -28,7 +31,7 @@ export function WorkspaceCards({ items, isLoading, busyId, onEnter, onReject, on
|
||||
return (
|
||||
<div className="divide-y divide-border">
|
||||
{items.map((item) => (
|
||||
<Card key={item.session_id} item={item} busy={busyId === item.session_id} onEnter={onEnter} onReject={onReject} onExtraInfo={onExtraInfo} />
|
||||
<Card key={item.session_id} item={item} busy={busyId === item.session_id} onEnter={onEnter} onReject={onReject} onExtraInfo={onExtraInfo} onRenegotiate={onRenegotiate} onMemo={onMemo} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
@@ -40,19 +43,24 @@ function Card({
|
||||
onEnter,
|
||||
onReject,
|
||||
onExtraInfo,
|
||||
onRenegotiate,
|
||||
onMemo,
|
||||
}: {
|
||||
item: ListItem
|
||||
busy: boolean
|
||||
onEnter: (item: ListItem) => void
|
||||
onReject: (item: ListItem) => void
|
||||
onExtraInfo: (item: ListItem) => void
|
||||
onRenegotiate: (item: ListItem) => void
|
||||
onMemo: (item: ListItem) => void
|
||||
}) {
|
||||
const meta = statusMeta(item.session_status)
|
||||
const canEnter = !['미참여', '협상거부'].includes(item.session_status)
|
||||
const canReject = ['협상생성', '협상중'].includes(item.session_status)
|
||||
const isDone = item.session_status === '협상완료'
|
||||
const enterLabel = isDone ? '결과 보기' : '협상 입장'
|
||||
const hasExtra = item.custom && Object.keys(item.custom).length > 0
|
||||
// 재협상: 요청 가능하면 버튼, 이미 요청했으면 진행 상태를 보여준다.
|
||||
const renegoLabel = RENEGO_STATUS_LABEL[item.renegotiationStatus] ?? ''
|
||||
|
||||
return (
|
||||
<div className="p-4">
|
||||
@@ -67,10 +75,17 @@ function Card({
|
||||
{item.model_name && <span> · {item.model_name}</span>}
|
||||
</p>
|
||||
</div>
|
||||
<span className={cn('inline-flex shrink-0 items-center gap-1 rounded-full px-2.5 py-1 text-xs font-bold', meta.badge)}>
|
||||
<span className={cn('size-1.5 rounded-full', meta.dot)} />
|
||||
{meta.display}
|
||||
</span>
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
{RESULT_META[item.result] && (
|
||||
<span className={cn('inline-flex items-center whitespace-nowrap rounded-full px-2 py-1 text-xs font-bold', RESULT_META[item.result].badge)}>
|
||||
{RESULT_META[item.result].label}
|
||||
</span>
|
||||
)}
|
||||
<span className={cn('inline-flex items-center gap-1 whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-bold', meta.badge)}>
|
||||
<span className={cn('size-1.5 rounded-full', meta.dot)} />
|
||||
{meta.display}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-2.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-neutral-60">
|
||||
@@ -78,15 +93,43 @@ function Card({
|
||||
<span>마감 {formatKstDateTime(item.qt_end_time)}</span>
|
||||
</div>
|
||||
|
||||
{(canEnter || canReject || isDone) && (
|
||||
{renegoLabel &&
|
||||
(item.renegotiationMemo ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onMemo(item)}
|
||||
className="mt-2.5 flex w-full items-center justify-between rounded-xl bg-neutral-10 px-3 py-2 transition-all hover:bg-neutral-20 active:scale-[0.99]"
|
||||
>
|
||||
<span className="whitespace-nowrap text-xs font-bold text-neutral-80">{renegoLabel}</span>
|
||||
<span className="flex items-center gap-1 whitespace-nowrap text-[11px] text-neutral-60">
|
||||
담당자 메모
|
||||
<MessageSquareText className="size-3.5 text-neutral-50" />
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<div className="mt-2.5 rounded-xl bg-neutral-10 px-3 py-2">
|
||||
<p className="text-xs font-bold text-neutral-80">{renegoLabel}</p>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{(canEnter || canReject || isDone || item.renegotiable) && (
|
||||
<div className="mt-3 flex gap-2">
|
||||
{item.renegotiable && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRenegotiate(item)}
|
||||
className="flex-1 rounded-lg border border-brand-600/40 py-2 text-xs font-bold text-brand-700 transition-all hover:bg-brand-50 active:scale-[0.98]"
|
||||
>
|
||||
재협상 요청
|
||||
</button>
|
||||
)}
|
||||
{isDone && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onExtraInfo(item)}
|
||||
className="flex-1 rounded-lg border border-brand-600/40 py-2 text-xs font-bold text-brand-700 transition-all hover:bg-brand-50 active:scale-[0.98]"
|
||||
>
|
||||
{hasExtra ? '부가정보 수정' : '부가정보 입력'}
|
||||
부가정보 보기
|
||||
</button>
|
||||
)}
|
||||
{canReject && (
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { type ReactNode } from 'react'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Loader2, MessageSquareText } from 'lucide-react'
|
||||
import { cn, formatKstDateTime } from '@/lib'
|
||||
import { RENEGO_STATUS_LABEL } from '@/apis/negotiation/negotiation.type'
|
||||
import type { ListItem } from '@/features/list/types'
|
||||
import { statusMeta } from '@/features/list/lib/status'
|
||||
import { statusMeta, RESULT_META } from '@/features/list/lib/status'
|
||||
|
||||
interface WorkspaceTableProps {
|
||||
items: ListItem[]
|
||||
@@ -11,22 +12,26 @@ interface WorkspaceTableProps {
|
||||
onEnter: (item: ListItem) => void
|
||||
onReject: (item: ListItem) => void
|
||||
onExtraInfo: (item: ListItem) => void
|
||||
onRenegotiate: (item: ListItem) => void
|
||||
onMemo: (item: ListItem) => void
|
||||
}
|
||||
|
||||
const HEAD = 'px-5 py-3.5 text-left text-[11px] font-bold uppercase tracking-wider text-neutral-60 whitespace-nowrap'
|
||||
// th 기본 정렬은 center — 정렬은 베이스에 넣지 않고 컬럼마다 명시한다(cn 이 tailwind-merge 가 아니라 충돌 시 승자가 불명확).
|
||||
const HEAD = 'px-5 py-3.5 text-[11px] font-bold uppercase tracking-wider text-neutral-60 whitespace-nowrap'
|
||||
const CELL = 'px-5 py-4 align-middle text-sm text-neutral-80'
|
||||
|
||||
export function WorkspaceTable({ items, isLoading, busyId, onEnter, onReject, onExtraInfo }: WorkspaceTableProps) {
|
||||
export function WorkspaceTable({ items, isLoading, busyId, onEnter, onReject, onExtraInfo, onRenegotiate, onMemo }: WorkspaceTableProps) {
|
||||
return (
|
||||
<div className="w-full overflow-x-auto">
|
||||
<table className="w-full min-w-[900px] border-collapse">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-table-header">
|
||||
<th className={HEAD}>견적번호</th>
|
||||
<th className={HEAD}>상품</th>
|
||||
<th className={HEAD}>제조사</th>
|
||||
<th className={cn(HEAD, 'text-center')}>상태</th>
|
||||
<th className={HEAD}>마감일</th>
|
||||
<th className={cn(HEAD, 'text-left')}>견적번호</th>
|
||||
<th className={cn(HEAD, 'text-left')}>상품</th>
|
||||
<th className={cn(HEAD, 'text-left')}>제조사</th>
|
||||
<th className={cn(HEAD, 'text-right')}>상태</th>
|
||||
<th className={cn(HEAD, 'text-center')}>결과</th>
|
||||
<th className={cn(HEAD, 'text-left')}>마감일</th>
|
||||
<th className={cn(HEAD, 'text-right')}>액션</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -41,7 +46,7 @@ export function WorkspaceTable({ items, isLoading, busyId, onEnter, onReject, on
|
||||
</StateRow>
|
||||
) : (
|
||||
items.map((item) => (
|
||||
<Row key={item.session_id} item={item} busy={busyId === item.session_id} onEnter={onEnter} onReject={onReject} onExtraInfo={onExtraInfo} />
|
||||
<Row key={item.session_id} item={item} busy={busyId === item.session_id} onEnter={onEnter} onReject={onReject} onExtraInfo={onExtraInfo} onRenegotiate={onRenegotiate} onMemo={onMemo} />
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
@@ -56,19 +61,22 @@ function Row({
|
||||
onEnter,
|
||||
onReject,
|
||||
onExtraInfo,
|
||||
onRenegotiate,
|
||||
onMemo,
|
||||
}: {
|
||||
item: ListItem
|
||||
busy: boolean
|
||||
onEnter: (item: ListItem) => void
|
||||
onReject: (item: ListItem) => void
|
||||
onExtraInfo: (item: ListItem) => void
|
||||
onRenegotiate: (item: ListItem) => void
|
||||
onMemo: (item: ListItem) => void
|
||||
}) {
|
||||
const meta = statusMeta(item.session_status)
|
||||
const canEnter = !['미참여', '협상거부'].includes(item.session_status)
|
||||
const canReject = ['협상생성', '협상중'].includes(item.session_status)
|
||||
const isDone = item.session_status === '협상완료'
|
||||
const enterLabel = isDone ? '결과 보기' : '협상 입장'
|
||||
const hasExtra = item.custom && Object.keys(item.custom).length > 0
|
||||
|
||||
return (
|
||||
<tr className="border-b border-border/60 transition-colors last:border-0 hover:bg-table-hover/70">
|
||||
@@ -83,22 +91,57 @@ function Row({
|
||||
</p>
|
||||
</td>
|
||||
<td className={cn(CELL, 'whitespace-nowrap text-neutral-70')}>{item.maker_name || '-'}</td>
|
||||
<td className={cn(CELL, 'text-center')}>
|
||||
<span className={cn('inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-bold', meta.badge)}>
|
||||
<td className={cn(CELL, 'text-right')}>
|
||||
<span className={cn('inline-flex items-center gap-1 whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-bold', meta.badge)}>
|
||||
<span className={cn('size-1.5 rounded-full', meta.dot)} />
|
||||
{meta.display}
|
||||
</span>
|
||||
</td>
|
||||
<td className={cn(CELL, 'text-center')}>
|
||||
{RESULT_META[item.result] ? (
|
||||
<span className={cn('inline-flex items-center whitespace-nowrap rounded-full px-2 py-1 text-xs font-bold', RESULT_META[item.result].badge)}>
|
||||
{RESULT_META[item.result].label}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs text-neutral-40">–</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={cn(CELL, 'whitespace-nowrap text-neutral-70')}>{formatKstDateTime(item.qt_end_time)}</td>
|
||||
<td className={CELL}>
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
{/* 재협상: 요청 가능하면 버튼, 요청 이력이 있으면 상태 텍스트(담당자 메모 있으면 클릭 시 팝업) */}
|
||||
{item.renegotiable ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRenegotiate(item)}
|
||||
className="rounded-lg border border-brand-600/40 px-3 py-1.5 text-xs font-bold text-brand-700 transition-all hover:bg-brand-50 active:scale-[0.98]"
|
||||
>
|
||||
재협상 요청
|
||||
</button>
|
||||
) : (
|
||||
RENEGO_STATUS_LABEL[item.renegotiationStatus] &&
|
||||
(item.renegotiationMemo ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onMemo(item)}
|
||||
className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-lg bg-neutral-10 px-2.5 py-1.5 text-xs font-bold text-neutral-70 transition-all hover:bg-neutral-20 active:scale-[0.98]"
|
||||
>
|
||||
{RENEGO_STATUS_LABEL[item.renegotiationStatus]}
|
||||
<MessageSquareText className="size-3.5 text-neutral-50" />
|
||||
</button>
|
||||
) : (
|
||||
<span className="whitespace-nowrap rounded-lg bg-neutral-10 px-2.5 py-1.5 text-xs font-bold text-neutral-70">
|
||||
{RENEGO_STATUS_LABEL[item.renegotiationStatus]}
|
||||
</span>
|
||||
))
|
||||
)}
|
||||
{isDone && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onExtraInfo(item)}
|
||||
className="rounded-lg border border-brand-600/40 px-3 py-1.5 text-xs font-bold text-brand-700 transition-all hover:bg-brand-50 active:scale-[0.98]"
|
||||
>
|
||||
{hasExtra ? '부가정보 수정' : '부가정보 입력'}
|
||||
부가정보 보기
|
||||
</button>
|
||||
)}
|
||||
{canReject && (
|
||||
@@ -120,9 +163,7 @@ function Row({
|
||||
{busy && <Loader2 className="size-3 animate-spin" />}
|
||||
{enterLabel}
|
||||
</button>
|
||||
) : (
|
||||
!canReject && <span className="text-xs text-neutral-50">–</span>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -132,7 +173,7 @@ function Row({
|
||||
function StateRow({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<tr>
|
||||
<td colSpan={6} className="py-20">
|
||||
<td colSpan={7} className="py-20">
|
||||
<div className="flex items-center justify-center">{children}</div>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -1,18 +1,29 @@
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { useShallow } from 'zustand/react/shallow'
|
||||
import { Search } from 'lucide-react'
|
||||
import { getApiErrorMessage, useMeQuery, useParticipateMutation, useRejectMutation, useSaveExtraInfoMutation } from '@/apis'
|
||||
import { HelpCircle, Search } from 'lucide-react'
|
||||
import {
|
||||
getApiErrorMessage,
|
||||
useMeQuery,
|
||||
useParticipateMutation,
|
||||
useRejectMutation,
|
||||
useRequestRenegotiationMutation,
|
||||
useSaveExtraInfoMutation,
|
||||
} from '@/apis'
|
||||
import { cn, toast } from '@/lib'
|
||||
import { useList } from '@/features/list/hooks/useList'
|
||||
import { useListStore } from '@/features/list/stores/useListStore'
|
||||
import { KpiCards } from '@/features/list/components/KpiCards'
|
||||
import { StatusTabs } from '@/features/list/components/StatusTabs'
|
||||
import { SortControl } from '@/features/list/components/SortControl'
|
||||
import { WorkspaceTable } from '@/features/list/components/WorkspaceTable'
|
||||
import { WorkspaceCards } from '@/features/list/components/WorkspaceCards'
|
||||
import { Pagination } from '@/features/list/components/Pagination'
|
||||
import { RejectPopup } from '@/features/list/components/RejectPopup'
|
||||
import { ExtraInfoPopup } from '@/features/list/components/ExtraInfoPopup'
|
||||
import { RenegotiationPopup } from '@/features/list/components/RenegotiationPopup'
|
||||
import { RenegotiationMemoPopup } from '@/features/list/components/RenegotiationMemoPopup'
|
||||
import { GuidePopup } from '@/features/list/components/GuidePopup'
|
||||
import type { ListItem } from '@/features/list/types'
|
||||
|
||||
// 상태별 거부 불가 안내
|
||||
@@ -25,23 +36,38 @@ const REJECT_BLOCKED: Record<string, string> = {
|
||||
export function ListWorkspace() {
|
||||
const navigate = useNavigate()
|
||||
const { data: user } = useMeQuery()
|
||||
// 리스트는 서버 페이징. (검색은 백엔드 미지원 → 프론트 검색은 비워 둠)
|
||||
// 리스트는 서버 페이징 + 서버 검색(keyword: 견적번호·상품명·상품코드 부분일치).
|
||||
const { items, isLoading, totalPages, currentPage, setCurrentPage } = useList()
|
||||
const participate = useParticipateMutation()
|
||||
const reject = useRejectMutation()
|
||||
const saveExtra = useSaveExtraInfoMutation()
|
||||
const requestRenego = useRequestRenegotiationMutation()
|
||||
|
||||
const { selectedStatus, setStatus } = useListStore(
|
||||
useShallow((s) => ({
|
||||
selectedStatus: s.selectedStatus,
|
||||
setStatus: s.setStatus,
|
||||
})),
|
||||
)
|
||||
const { selectedStatus, selectedResult, selectedDeadline, setStatus, toggleResult, setDeadline, setKeyword } =
|
||||
useListStore(
|
||||
useShallow((s) => ({
|
||||
selectedStatus: s.selectedStatus,
|
||||
selectedResult: s.selectedResult,
|
||||
selectedDeadline: s.selectedDeadline,
|
||||
setStatus: s.setStatus,
|
||||
toggleResult: s.toggleResult,
|
||||
setDeadline: s.setDeadline,
|
||||
setKeyword: s.setKeyword,
|
||||
})),
|
||||
)
|
||||
|
||||
// 입력은 즉시 반영하되, 서버 요청은 300ms 디바운스(타이핑마다 호출 방지). 변경 시 store 가 페이지를 1로 되돌린다.
|
||||
const [search, setSearch] = useState('')
|
||||
useEffect(() => {
|
||||
const id = setTimeout(() => setKeyword(search), 300)
|
||||
return () => clearTimeout(id)
|
||||
}, [search, setKeyword])
|
||||
const [enteringId, setEnteringId] = useState<string | null>(null)
|
||||
const [rejectTarget, setRejectTarget] = useState<ListItem | null>(null)
|
||||
const [extraTarget, setExtraTarget] = useState<ListItem | null>(null)
|
||||
const [renegoTarget, setRenegoTarget] = useState<ListItem | null>(null)
|
||||
const [memoTarget, setMemoTarget] = useState<ListItem | null>(null)
|
||||
const [guideOpen, setGuideOpen] = useState(false)
|
||||
|
||||
const handleEnter = (item: ListItem) => {
|
||||
setEnteringId(item.session_id)
|
||||
@@ -85,28 +111,53 @@ export function ListWorkspace() {
|
||||
)
|
||||
}
|
||||
|
||||
const handleRenegoSubmit = (reason: string, desiredPrice: number | null) => {
|
||||
if (!renegoTarget) return
|
||||
requestRenego.mutate(
|
||||
{ sessionId: renegoTarget.session_id, request: { reason, desired_price: desiredPrice } },
|
||||
{
|
||||
onSuccess: () => toast.success('재협상을 요청했습니다. 담당자 검토 후 결과가 목록에 표시됩니다.'),
|
||||
onError: (error) => toast.error(getApiErrorMessage(error, '재협상 요청에 실패했습니다.')),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* 환영 배너 */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 rounded-2xl border border-border bg-white px-5 py-4 shadow-[0_2px_12px_rgba(0,0,0,0.02)]">
|
||||
{/* 헤더 */}
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
||||
<div>
|
||||
<p className="text-[15px] font-bold text-neutral-90">
|
||||
{user?.supplierName ? `${user.supplierName} 담당자님, 환영합니다.` : '공급 파트너님, 환영합니다.'}
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-neutral-60">
|
||||
진행 중인 협상 건을 확인하고 가격 협상에 참여해 주세요.
|
||||
<h1 className="text-xl font-extrabold tracking-tight text-neutral-90">협상 워크스페이스</h1>
|
||||
<p className="mt-0.5 text-[13px] text-neutral-60">
|
||||
{user?.supplierName ? `${user.supplierName} (공급 파트너)` : '공급 파트너'} · 진행/결과를 한눈에
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setGuideOpen(true)}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg border border-border bg-white px-3 py-1.5 text-[13px] font-bold text-neutral-70 transition-colors hover:bg-neutral-10"
|
||||
>
|
||||
<HelpCircle className="size-4 text-neutral-50" />
|
||||
이용안내
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* KPI 콕핏 */}
|
||||
<KpiCards selectedStatus={selectedStatus} onSelect={(s) => setStatus(selectedStatus === s ? null : s)} />
|
||||
{/* KPI 콕핏 — 진행/결과 두 묶음 */}
|
||||
<KpiCards
|
||||
selectedStatus={selectedStatus}
|
||||
selectedResult={selectedResult}
|
||||
onSelectStatus={(s) => setStatus(selectedStatus === s ? null : s)}
|
||||
onSelectResult={toggleResult}
|
||||
/>
|
||||
|
||||
{/* 워크스페이스 카드 */}
|
||||
<div className="overflow-hidden rounded-2xl border border-border bg-white shadow-sm">
|
||||
<div className="flex flex-col gap-3 border-b border-border p-4 lg:flex-row lg:items-center lg:justify-between">
|
||||
<StatusTabs selected={selectedStatus} onSelect={setStatus} />
|
||||
<div className="flex w-full items-center gap-2 lg:w-auto">
|
||||
<SortControl selected={selectedDeadline} onSelect={setDeadline} />
|
||||
<div className="relative flex-1 lg:flex-none">
|
||||
<Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-neutral-50" />
|
||||
<input
|
||||
@@ -131,6 +182,8 @@ export function ListWorkspace() {
|
||||
onEnter={handleEnter}
|
||||
onReject={handleReject}
|
||||
onExtraInfo={setExtraTarget}
|
||||
onRenegotiate={setRenegoTarget}
|
||||
onMemo={setMemoTarget}
|
||||
/>
|
||||
</div>
|
||||
<div className="lg:hidden">
|
||||
@@ -141,6 +194,8 @@ export function ListWorkspace() {
|
||||
onEnter={handleEnter}
|
||||
onReject={handleReject}
|
||||
onExtraInfo={setExtraTarget}
|
||||
onRenegotiate={setRenegoTarget}
|
||||
onMemo={setMemoTarget}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -149,6 +204,8 @@ export function ListWorkspace() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{guideOpen && <GuidePopup onClose={() => setGuideOpen(false)} />}
|
||||
|
||||
{rejectTarget && (
|
||||
<RejectPopup onClose={() => setRejectTarget(null)} onSubmit={handleRejectSubmit} />
|
||||
)}
|
||||
@@ -156,6 +213,18 @@ export function ListWorkspace() {
|
||||
{extraTarget && (
|
||||
<ExtraInfoPopup target={extraTarget} onClose={() => setExtraTarget(null)} onSubmit={handleExtraSubmit} />
|
||||
)}
|
||||
|
||||
{renegoTarget && (
|
||||
<RenegotiationPopup
|
||||
target={renegoTarget}
|
||||
onClose={() => setRenegoTarget(null)}
|
||||
onSubmit={handleRenegoSubmit}
|
||||
/>
|
||||
)}
|
||||
|
||||
{memoTarget && (
|
||||
<RenegotiationMemoPopup target={memoTarget} onClose={() => setMemoTarget(null)} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -7,11 +7,13 @@ const PAGE_SIZE = 20
|
||||
|
||||
// 필터/정렬/페이지는 서버에 위임하고, 응답(정수 코드)을 화면용 라벨로 변환한다.
|
||||
export function useList() {
|
||||
const { selectedStatus, selectedDeadline, currentPage, setCurrentPage } = useListStore()
|
||||
const { selectedStatus, selectedDeadline, selectedResult, keyword, currentPage, setCurrentPage } = useListStore()
|
||||
|
||||
const query = useSessionListQuery({
|
||||
status: selectedStatus ? statusLabelToCode(selectedStatus) : undefined,
|
||||
order: selectedDeadline ? deadlineToOrder(selectedDeadline) : undefined,
|
||||
result: selectedResult ?? undefined,
|
||||
keyword: keyword.trim() || undefined,
|
||||
page: currentPage,
|
||||
page_size: PAGE_SIZE,
|
||||
})
|
||||
|
||||
@@ -1,35 +1,63 @@
|
||||
import { useQueries } from '@tanstack/react-query'
|
||||
import { negotiationApi, negotiationKeys, SessionStatus } from '@/apis'
|
||||
import { negotiationApi, negotiationKeys, SessionStatus, SessionResult } from '@/apis'
|
||||
|
||||
// KPI 콕핏에 노출할 상태별 집계. 각 상태를 page_size=1 로 조회해 total 만 읽는다(목록과 캐시 공유).
|
||||
// KPI 콕핏 집계. 진행(상태축)·결과(결과축) 두 묶음. 각 항목을 page_size=1 로 조회해 total 만 읽는다(목록과 캐시 공유).
|
||||
// 클릭 시 걸 필터가 상태냐 결과냐가 다르므로 kind 로 구분해 컨테이너가 올바른 setter 로 보낸다.
|
||||
export interface KpiCount {
|
||||
key: string
|
||||
label: string
|
||||
status: string // 클릭 시 필터에 넣을 원본 상태 라벨
|
||||
code: number
|
||||
kind: 'status' | 'result'
|
||||
statusLabel?: string // kind=status: 필터에 넣을 원본 상태 라벨
|
||||
resultCode?: number // kind=result: 필터에 넣을 SessionResult 코드
|
||||
count: number
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
const KPI = [
|
||||
{ key: 'created', label: '협상 대기', status: '협상생성', code: SessionStatus.CREATED },
|
||||
{ key: 'progress', label: '조율 진행중', status: '협상중', code: SessionStatus.IN_PROGRESS },
|
||||
{ key: 'done', label: '타결 완료', status: '협상완료', code: SessionStatus.DONE },
|
||||
{ key: 'rejected', label: '거부/반려', status: '협상거부', code: SessionStatus.REJECTED },
|
||||
// 진행 묶음(내가 할 일) — 세션 상태축.
|
||||
const PROGRESS = [
|
||||
{ key: 'created', label: '협상 대기', statusLabel: '협상생성', code: SessionStatus.CREATED },
|
||||
{ key: 'progress', label: '협상 중', statusLabel: '협상중', code: SessionStatus.IN_PROGRESS },
|
||||
] as const
|
||||
|
||||
export function useSessionCounts(): KpiCount[] {
|
||||
const results = useQueries({
|
||||
queries: KPI.map((k) => ({
|
||||
// 결과 묶음(마감 후) — 결과축. 낙찰=주강조, 결렬=재협상 가능(액션).
|
||||
const RESULT = [
|
||||
{ key: 'won', label: '낙찰', code: SessionResult.WON },
|
||||
{ key: 'open', label: '결렬', code: SessionResult.OPEN },
|
||||
{ key: 'lost', label: '미낙찰', code: SessionResult.LOST },
|
||||
] as const
|
||||
|
||||
export function useSessionCounts(): { progress: KpiCount[]; result: KpiCount[] } {
|
||||
const statusQ = useQueries({
|
||||
queries: PROGRESS.map((k) => ({
|
||||
queryKey: negotiationKeys.sessionList({ status: k.code, page: 1, page_size: 1 }),
|
||||
queryFn: () => negotiationApi.getSessions({ status: k.code, page: 1, page_size: 1 }),
|
||||
staleTime: 60 * 1000,
|
||||
})),
|
||||
})
|
||||
const resultQ = useQueries({
|
||||
queries: RESULT.map((k) => ({
|
||||
queryKey: negotiationKeys.sessionList({ result: k.code, page: 1, page_size: 1 }),
|
||||
queryFn: () => negotiationApi.getSessions({ result: k.code, page: 1, page_size: 1 }),
|
||||
staleTime: 60 * 1000,
|
||||
})),
|
||||
})
|
||||
|
||||
return KPI.map((k, i) => ({
|
||||
...k,
|
||||
count: results[i].data?.total ?? 0,
|
||||
isLoading: results[i].isLoading,
|
||||
}))
|
||||
return {
|
||||
progress: PROGRESS.map((k, i) => ({
|
||||
key: k.key,
|
||||
label: k.label,
|
||||
kind: 'status',
|
||||
statusLabel: k.statusLabel,
|
||||
count: statusQ[i].data?.total ?? 0,
|
||||
isLoading: statusQ[i].isLoading,
|
||||
})),
|
||||
result: RESULT.map((k, i) => ({
|
||||
key: k.key,
|
||||
label: k.label,
|
||||
kind: 'result',
|
||||
resultCode: k.code,
|
||||
count: resultQ[i].data?.total ?? 0,
|
||||
isLoading: resultQ[i].isLoading,
|
||||
})),
|
||||
}
|
||||
}
|
||||
@@ -38,5 +38,9 @@ export function toListItem(api: SessionListItem): ListItem {
|
||||
model_name: api.model_name,
|
||||
maker_name: api.maker_name,
|
||||
custom: api.custom ?? {},
|
||||
renegotiable: api.renegotiable ?? false,
|
||||
renegotiationStatus: api.renegotiation_status ?? 0,
|
||||
renegotiationMemo: api.renegotiation_memo ?? '',
|
||||
result: api.result ?? 0,
|
||||
}
|
||||
}
|
||||
@@ -7,13 +7,21 @@ export interface StatusMeta {
|
||||
}
|
||||
|
||||
export const STATUS_META: Record<string, StatusMeta> = {
|
||||
협상생성: { display: '대기', badge: 'bg-brand-light text-brand-600', dot: 'bg-brand-600' },
|
||||
협상중: { display: '조율중', badge: 'bg-[#FFF3E5] text-[#F5A623]', dot: 'bg-[#F5A623]' },
|
||||
협상완료: { display: '타결', badge: 'bg-[#EAFDF3] text-success', dot: 'bg-success' },
|
||||
미참여: { display: '미참여', badge: 'bg-neutral-20 text-neutral-60', dot: 'bg-neutral-60' },
|
||||
협상거부: { display: '거부', badge: 'bg-[#FFEBEB] text-[#FF4D4F]', dot: 'bg-[#FF4D4F]' },
|
||||
협상생성: { display: '협상 대기', badge: 'bg-brand-light text-brand-600', dot: 'bg-brand-600' },
|
||||
협상중: { display: '협상 중', badge: 'bg-[#FFF3E5] text-[#F5A623]', dot: 'bg-[#F5A623]' },
|
||||
협상완료: { display: '협상 완료', badge: 'bg-[#EAFDF3] text-success', dot: 'bg-success' },
|
||||
미참여: { display: '협상 미참여', badge: 'bg-neutral-20 text-neutral-60', dot: 'bg-neutral-60' },
|
||||
협상거부: { display: '협상 거절', badge: 'bg-[#FFEBEB] text-[#FF4D4F]', dot: 'bg-[#FF4D4F]' },
|
||||
}
|
||||
|
||||
export function statusMeta(label: string): StatusMeta {
|
||||
return STATUS_META[label] ?? { display: label || '-', badge: 'bg-neutral-20 text-neutral-60', dot: 'bg-neutral-60' }
|
||||
}
|
||||
|
||||
// 협상 결과(SessionResult 코드) → 완료 건에 붙는 결과 배지. 0(미정)은 표시하지 않는다.
|
||||
// 결렬(3)은 재협상 요청 대상이라 눈에 띄게 노랑으로 둔다.
|
||||
export const RESULT_META: Record<number, { label: string; badge: string }> = {
|
||||
1: { label: '낙찰', badge: 'bg-[#EAFDF3] text-success' },
|
||||
2: { label: '미낙찰', badge: 'bg-neutral-20 text-neutral-60' },
|
||||
3: { label: '결렬', badge: 'bg-[#FFF3E5] text-[#F5A623]' },
|
||||
}
|
||||
@@ -4,6 +4,8 @@ interface ListState {
|
||||
selectedType: string | null
|
||||
selectedStatus: string | null
|
||||
selectedDeadline: string | null
|
||||
selectedResult: number | null // 결과 필터(SessionResult 코드). 상태와 별개 축이라 함께 걸린다
|
||||
keyword: string
|
||||
currentPage: number
|
||||
|
||||
toggleType: (item: string) => void
|
||||
@@ -11,6 +13,9 @@ interface ListState {
|
||||
toggleStatus: (item: string) => void
|
||||
setStatus: (item: string | null) => void
|
||||
toggleDeadline: (item: string) => void
|
||||
setDeadline: (item: string | null) => void
|
||||
toggleResult: (code: number) => void
|
||||
setKeyword: (keyword: string) => void
|
||||
setCurrentPage: (page: number) => void
|
||||
resetFilters: () => void
|
||||
}
|
||||
@@ -21,17 +26,24 @@ export const useListStore = create<ListState>((set) => ({
|
||||
selectedType: null,
|
||||
selectedStatus: null,
|
||||
selectedDeadline: null,
|
||||
selectedResult: null,
|
||||
keyword: '',
|
||||
currentPage: 1,
|
||||
|
||||
toggleType: (item) =>
|
||||
set((s) => ({ selectedType: toggle(s.selectedType, item), currentPage: 1 })),
|
||||
setType: (item) => set({ selectedType: item, currentPage: 1 }),
|
||||
// 상태(진행)와 결과는 마감 전/후라 서로 배타적 — 한 축을 고르면 다른 축은 해제한다(동시 선택=거의 0건).
|
||||
toggleStatus: (item) =>
|
||||
set((s) => ({ selectedStatus: toggle(s.selectedStatus, item), currentPage: 1 })),
|
||||
setStatus: (item) => set({ selectedStatus: item, currentPage: 1 }),
|
||||
set((s) => ({ selectedStatus: toggle(s.selectedStatus, item), selectedResult: null, currentPage: 1 })),
|
||||
setStatus: (item) => set({ selectedStatus: item, selectedResult: null, currentPage: 1 }),
|
||||
toggleDeadline: (item) =>
|
||||
set((s) => ({ selectedDeadline: toggle(s.selectedDeadline, item), currentPage: 1 })),
|
||||
setDeadline: (item) => set({ selectedDeadline: item, currentPage: 1 }),
|
||||
toggleResult: (code) =>
|
||||
set((s) => ({ selectedResult: s.selectedResult === code ? null : code, selectedStatus: null, currentPage: 1 })),
|
||||
setKeyword: (keyword) => set({ keyword, currentPage: 1 }),
|
||||
setCurrentPage: (page) => set({ currentPage: page }),
|
||||
resetFilters: () =>
|
||||
set({ selectedType: null, selectedStatus: null, selectedDeadline: null, currentPage: 1 }),
|
||||
set({ selectedType: null, selectedStatus: null, selectedDeadline: null, selectedResult: null, keyword: '', currentPage: 1 }),
|
||||
}))
|
||||
@@ -9,4 +9,8 @@ export type ListItem = {
|
||||
model_name: string
|
||||
maker_name: string
|
||||
custom: Record<string, unknown> // 협상완료 부가정보(입력값). 미입력이면 {}
|
||||
renegotiable: boolean // 재협상 요청 가능(서버 판정)
|
||||
renegotiationStatus: number // 0=없음 1=심사중 2=승인 3=반려 4=철회
|
||||
renegotiationMemo: string // 담당자 심사 메모(반려 사유)
|
||||
result: number // 협상 결과: 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰)
|
||||
}
|
||||
+12
-5
@@ -160,6 +160,17 @@
|
||||
text-rendering: optimizeLegibility;
|
||||
font-synthesis: none;
|
||||
}
|
||||
|
||||
/* Tailwind v4 는 버튼 기본 커서가 default — 클릭/선택 가능한 요소는 포인터로 통일 */
|
||||
button:not(:disabled),
|
||||
[role='button']:not([aria-disabled='true']),
|
||||
input[type='checkbox']:not(:disabled),
|
||||
input[type='radio']:not(:disabled),
|
||||
select:not(:disabled),
|
||||
label[for],
|
||||
summary {
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
/* 노치/홈 인디케이터 회피 (viewport-fit=cover 와 짝). 안전영역이 0 인 기기에선 아무 영향 없다.
|
||||
@@ -188,7 +199,7 @@
|
||||
.body-1-read-r { font-size: 20px; font-weight: 400; line-height: 150%; letter-spacing: -0.4px; }
|
||||
.body-1-read-b { font-size: 20px; font-weight: 700; line-height: 150%; letter-spacing: -0.4px; }
|
||||
.caption-1 { font-size: 13px; font-weight: 400; letter-spacing: -0.26px; }
|
||||
/* 메뉴 섹션 제목 (MD안내/협상절차/이용방법) */
|
||||
/* 메뉴 섹션 제목 (구매담당자 안내/협상절차/이용방법) */
|
||||
.menu-title { font-size: 20px; font-weight: 700; line-height: 25px; letter-spacing: -0.4px; }
|
||||
/* 재견적/재협상 폼 */
|
||||
.reject { font-size: 18px; font-weight: 400; line-height: 150%; letter-spacing: -0.4px; color: var(--neutral-90); }
|
||||
@@ -210,10 +221,6 @@
|
||||
}
|
||||
|
||||
/* 채팅 영역 스크롤바 (배경과 구분되게 진하게) */
|
||||
/* 트랙 상단 64px 여백: 콘텐츠는 맨 위까지 스크롤되지만 스크롤바는 우측 협상절차 카드 상단과 같은 높이에서 시작 */
|
||||
.chat-scroll::-webkit-scrollbar-track {
|
||||
margin-top: 64px;
|
||||
}
|
||||
.chat-scroll::-webkit-scrollbar-thumb {
|
||||
background-color: var(--neutral-40);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useNavigate } from 'react-router'
|
||||
import { Bell, LogOut } from 'lucide-react'
|
||||
import { LogOut } from 'lucide-react'
|
||||
import { useLogoutMutation, useMeQuery } from '@/apis'
|
||||
import { Logo } from '@/components'
|
||||
import { cn, interactive } from '@/lib'
|
||||
@@ -14,10 +14,11 @@ export function PortalHeader() {
|
||||
logout.mutate(undefined, { onSuccess: () => navigate('/') })
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-40 flex h-16 items-center justify-between border-b border-border bg-white/90 px-4 shadow-sm backdrop-blur sm:px-6">
|
||||
<header className="sticky top-0 z-40 flex min-h-[calc(4rem+env(safe-area-inset-top))] safe-t items-center justify-between border-b border-border bg-white/90 px-4 shadow-sm backdrop-blur sm:px-6">
|
||||
<Logo size="md" serviceName={user?.branding?.service_name} logoUrl={user?.branding?.logo_url} />
|
||||
|
||||
<div className="flex items-center gap-2 sm:gap-3">
|
||||
{/* 알림함(notifications 테이블) 구현 전까지 비활성.
|
||||
<button
|
||||
type="button"
|
||||
aria-label="알림"
|
||||
@@ -29,6 +30,7 @@ export function PortalHeader() {
|
||||
<Bell className="size-5" />
|
||||
<span className="absolute right-2 top-2 size-1.5 rounded-full bg-brand-600" />
|
||||
</button>
|
||||
*/}
|
||||
|
||||
<div className="hidden min-w-0 flex-col items-end sm:flex">
|
||||
<span className="max-w-[180px] truncate text-[13px] font-bold text-neutral-90">
|
||||
|
||||
@@ -2,18 +2,22 @@ import { type ReactNode } from 'react'
|
||||
import { useNavigate, useSearchParams, Navigate } from 'react-router'
|
||||
import { ArrowLeft, Package, ClipboardList } from 'lucide-react'
|
||||
import { cn, interactive } from '@/lib'
|
||||
import { Logo } from '@/components'
|
||||
import { MainLayout, MainHeaderBar } from '@/layouts'
|
||||
import { ChatContainer, ItemSection, RemainingTime } from '@/features/chat'
|
||||
import { MobileDrawer } from '@/features/chat/components/MobileDrawer'
|
||||
import { MenuSection } from '@/features/chat/components/menu/MenuSection'
|
||||
import { useChatUiStore } from '@/features/chat/stores/useChatUiStore'
|
||||
import { SidebarFooter } from '@/features/auth'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
import { SidebarFooter, usePreLoginBranding } from '@/features/auth'
|
||||
|
||||
export function ChatPage() {
|
||||
const [searchParams] = useSearchParams()
|
||||
const sessionId = searchParams.get('session_id') ?? ''
|
||||
const drawer = useChatUiStore((s) => s.drawer)
|
||||
const close = useChatUiStore((s) => s.close)
|
||||
const qtNumber = useChatInitStore((s) => s.qt_number)
|
||||
const itemName = useChatInitStore((s) => s.item_name)
|
||||
|
||||
// session_id 없이 진입하면 목록으로 되돌린다.
|
||||
if (!sessionId) return <Navigate to="/list" replace />
|
||||
@@ -27,15 +31,21 @@ export function ChatPage() {
|
||||
<MainHeaderBar className="px-4 sm:px-6 min-[1180px]:px-8">
|
||||
{/* min-w-0: flex 기본 min-width:auto 라 자식이 안 줄어들어 헤더 밖으로 넘치던 것 방지 */}
|
||||
<div className="flex w-full min-w-0 items-center justify-between gap-2">
|
||||
<div className="flex min-w-0 shrink items-center gap-2">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<BackToListButton />
|
||||
<span className="hidden h-4 w-px bg-border lg:inline-block" />
|
||||
<span className="hidden size-2 shrink-0 rounded-full bg-brand-600 animate-pulse lg:inline-block" />
|
||||
<span className="hidden truncate text-sm font-bold text-neutral-90 lg:inline">
|
||||
실시간 구매 협상 채널
|
||||
<span className="h-4 w-px shrink-0 bg-border" />
|
||||
{/* 헤더 대표값: 협상 중인 상품명 — 여러 협상건 중 '이 건'을 식별하는 기준 */}
|
||||
<span className="min-w-0 truncate text-sm font-bold text-neutral-90">
|
||||
{itemName || '가격 협상'}
|
||||
</span>
|
||||
{/* 견적번호: 정확한 참조용 보조값. 좁은 모바일에선 숨기고 상품 드로어에서 확인 */}
|
||||
{qtNumber && (
|
||||
<span className="hidden shrink-0 rounded-md bg-neutral-10 px-2 py-0.5 font-mono text-xs font-bold tracking-tight text-neutral-70 sm:inline-block">
|
||||
{qtNumber}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex min-w-0 shrink items-center gap-1.5">
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
<PanelToggle icon={<Package className="size-4" />} label="상품" panel="product" />
|
||||
<PanelToggle icon={<ClipboardList className="size-4" />} label="현황" panel="status" />
|
||||
<RemainingTime />
|
||||
@@ -49,6 +59,8 @@ export function ChatPage() {
|
||||
|
||||
{/* 모바일 드로어 (lg 미만) */}
|
||||
<MobileDrawer open={drawer === 'product'} onClose={close} side="left" title="상품 정보">
|
||||
{/* 데스크톱 사이드바 상단(구매사 로고)이 모바일에선 숨으므로, 드로어에서 브랜드+견적번호를 노출 */}
|
||||
<BuyerBrandStrip />
|
||||
<ItemSection />
|
||||
<SidebarFooter />
|
||||
</MobileDrawer>
|
||||
@@ -72,11 +84,27 @@ function BackToListButton() {
|
||||
)}
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
<span className="hidden sm:inline">목록으로 돌아가기</span>
|
||||
<span className="hidden sm:inline">목록</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
// 모바일 상품 드로어 상단: 구매사 로고 + 서비스명 + 견적번호(데스크톱 사이드바 상단의 모바일 대체)
|
||||
function BuyerBrandStrip() {
|
||||
const branding = usePreLoginBranding()
|
||||
const qtNumber = useChatInitStore((s) => s.qt_number)
|
||||
return (
|
||||
<div className="flex shrink-0 items-center gap-2 border-b border-border px-6 py-3">
|
||||
<Logo logoUrl={branding?.logo_url} serviceName={branding?.service_name} size="sm" />
|
||||
{qtNumber && (
|
||||
<span className="ml-auto shrink-0 rounded-md bg-neutral-10 px-2 py-0.5 font-mono text-xs font-bold tracking-tight text-neutral-70">
|
||||
{qtNumber}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 헤더 우측: 상품/현황 패널 드로어 토글 (모바일 전용)
|
||||
function PanelToggle({
|
||||
icon,
|
||||
|
||||
@@ -3,13 +3,13 @@ import { ListWorkspace } from '@/features/list'
|
||||
|
||||
export function ListPage() {
|
||||
return (
|
||||
<div className="flex min-h-svh flex-col bg-surface">
|
||||
<div className="flex min-h-svh flex-col bg-surface safe-x">
|
||||
<PortalHeader />
|
||||
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6 sm:px-6">
|
||||
<ListWorkspace />
|
||||
</main>
|
||||
{/* 솔루션·제작사 표기 — 회사 브랜딩(헤더 로고)과 무관하게 고정 */}
|
||||
<footer className="border-t border-border px-4 py-4 text-center sm:px-6">
|
||||
<footer className="border-t border-border px-4 py-4 text-center sm:px-6 safe-b">
|
||||
<p className="text-[11px] font-medium text-neutral-50">
|
||||
© {new Date().getFullYear()} negotium · Made by AI O2O
|
||||
</p>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
node_modules
|
||||
build
|
||||
.react-router
|
||||
.vercel
|
||||
@@ -0,0 +1,13 @@
|
||||
# 프로덕션: SSG 빌드(ssr:false, prerender) → 정적 산출물(build/client)을 nginx 로 서빙.
|
||||
FROM node:22-slim AS build
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
COPY --from=build /app/build/client /usr/share/nginx/html
|
||||
# 프리렌더 안 된 경로도 index.html 로 폴백(SPA).
|
||||
RUN printf 'server {\n listen 80;\n root /usr/share/nginx/html;\n location / { try_files $uri $uri/ /index.html; }\n}\n' > /etc/nginx/conf.d/default.conf
|
||||
EXPOSE 80
|
||||
@@ -0,0 +1,114 @@
|
||||
import type { VercelRequest, VercelResponse } from "@vercel/node"
|
||||
|
||||
/*
|
||||
* 리드 수집 엔드포인트 (Vercel 서버리스 함수).
|
||||
*
|
||||
* 랜딩은 ssr:false 정적 빌드라 서버 라우트가 없다. 그래서 /api 디렉터리의 함수로 받는다.
|
||||
* 클라이언트는 같은 오리진으로 쏘므로 엔드포인트 환경변수도, CORS 설정도 필요 없다.
|
||||
*
|
||||
* ── 리드를 잃지 않는 것이 이 파일의 유일한 책임이다 ──────────────────────────
|
||||
* 기존 문의 폼은 1.2초 뒤 성공 화면만 띄우고 아무 데도 보내지 않았다. 화면은
|
||||
* "접수되었습니다"인데 영업이 받을 리드는 없고, 아무도 그 사실을 몰랐다.
|
||||
*
|
||||
* 그래서 순서를 이렇게 잡는다.
|
||||
* 1) 먼저 구조화된 로그를 남긴다. 웹훅이 죽어도 Vercel 로그에 리드가 남는다.
|
||||
* 2) LEAD_WEBHOOK_URL 이 있으면 그리로 전달한다(Slack Incoming Webhook·Zapier·자체 API 모두 POST 를 받는다).
|
||||
* 3) 웹훅 전달이 실패해도 200 을 준다 — 1) 에서 이미 리드를 확보했으므로 방문자에게
|
||||
* 다시 입력하라고 할 이유가 없다. 대신 실패는 로그에 크게 남긴다.
|
||||
*
|
||||
* 로그는 CRM 이 아니라 최후의 그물이다. LEAD_WEBHOOK_URL 은 반드시 설정해야 한다.
|
||||
*/
|
||||
|
||||
const MAX_FIELD = 500
|
||||
|
||||
type LeadBody = {
|
||||
source?: string
|
||||
name?: string
|
||||
email?: string
|
||||
company?: string
|
||||
phone?: string
|
||||
message?: string
|
||||
/* 봇 함정. 사람 눈에 안 보이는 필드라 값이 차 있으면 자동 제출이다. */
|
||||
website?: string
|
||||
}
|
||||
|
||||
const clean = (v: unknown) => (typeof v === "string" ? v.trim().slice(0, MAX_FIELD) : "")
|
||||
|
||||
/** 느슨한 검사. 정규식으로 이메일을 엄밀히 검증하려는 시도는 늘 진짜 주소를 막는다. */
|
||||
const emailLike = (v: string) => v.length >= 5 && v.includes("@") && !v.startsWith("@") && !v.endsWith("@") && !/\s/.test(v)
|
||||
|
||||
export default async function handler(req: VercelRequest, res: VercelResponse) {
|
||||
if (req.method !== "POST") {
|
||||
res.setHeader("Allow", "POST")
|
||||
return res.status(405).json({ ok: false, error: "method_not_allowed" })
|
||||
}
|
||||
|
||||
const body = (typeof req.body === "string" ? safeParse(req.body) : req.body) as LeadBody | null
|
||||
if (!body) return res.status(400).json({ ok: false, error: "invalid_json" })
|
||||
|
||||
// 봇은 조용히 돌려보낸다. 400 을 주면 어떤 필드가 함정인지 알려주는 셈이다.
|
||||
if (clean(body.website)) return res.status(200).json({ ok: true })
|
||||
|
||||
const lead = {
|
||||
source: clean(body.source) || "unknown",
|
||||
name: clean(body.name),
|
||||
email: clean(body.email),
|
||||
company: clean(body.company),
|
||||
phone: clean(body.phone),
|
||||
message: clean(body.message),
|
||||
submittedAt: new Date().toISOString(),
|
||||
userAgent: clean(req.headers["user-agent"]),
|
||||
}
|
||||
|
||||
if (!lead.name || !emailLike(lead.email)) {
|
||||
return res.status(400).json({ ok: false, error: "invalid_input" })
|
||||
}
|
||||
|
||||
// 1) 무슨 일이 있어도 먼저 남긴다.
|
||||
console.log("[lead]", JSON.stringify(lead))
|
||||
|
||||
// 2) 사람이 실제로 보는 곳으로 전달.
|
||||
const webhook = process.env.LEAD_WEBHOOK_URL
|
||||
if (!webhook) {
|
||||
console.warn("[lead] LEAD_WEBHOOK_URL 미설정 — 리드가 로그에만 남습니다. 웹훅을 설정하세요.")
|
||||
return res.status(200).json({ ok: true, delivered: false })
|
||||
}
|
||||
|
||||
try {
|
||||
const upstream = await fetch(webhook, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
// Slack Incoming Webhook 은 text 를 읽고, 나머지 수신처는 보통 원본 필드를 읽는다.
|
||||
// 둘 다 담아 보내면 수신처를 바꿀 때 이 파일을 고칠 일이 없다.
|
||||
body: JSON.stringify({ text: summarize(lead), ...lead }),
|
||||
})
|
||||
if (!upstream.ok) {
|
||||
console.error("[lead] 웹훅 전달 실패", upstream.status, JSON.stringify(lead))
|
||||
return res.status(200).json({ ok: true, delivered: false })
|
||||
}
|
||||
return res.status(200).json({ ok: true, delivered: true })
|
||||
} catch (e) {
|
||||
console.error("[lead] 웹훅 예외", e, JSON.stringify(lead))
|
||||
return res.status(200).json({ ok: true, delivered: false })
|
||||
}
|
||||
}
|
||||
|
||||
function safeParse(s: string) {
|
||||
try {
|
||||
return JSON.parse(s)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function summarize(l: { source: string; name: string; email: string; company: string; phone: string; message: string }) {
|
||||
const rows = [
|
||||
`*새 리드* (${l.source})`,
|
||||
`이름: ${l.name}`,
|
||||
`이메일: ${l.email}`,
|
||||
l.company && `회사: ${l.company}`,
|
||||
l.phone && `연락처: ${l.phone}`,
|
||||
l.message && `내용: ${l.message}`,
|
||||
].filter(Boolean)
|
||||
return rows.join("\n")
|
||||
}
|
||||
+90
-16
@@ -10,38 +10,112 @@
|
||||
src: url('/fonts/PretendardVariable.woff2') format('woff2');
|
||||
}
|
||||
|
||||
/* 영문 디스플레이 서체 — 이탤릭 가변(400~900), latin 서브셋.
|
||||
INFINITH 디자인 시스템과 같은 Playfair Display 를 쓴다. */
|
||||
@font-face {
|
||||
font-family: 'Playfair Display';
|
||||
font-style: italic;
|
||||
font-weight: 400 900;
|
||||
font-display: swap;
|
||||
src: url('/fonts/PlayfairDisplay-Italic.woff2') format('woff2');
|
||||
}
|
||||
|
||||
/*
|
||||
* 랜딩 디자인 토큰 (Toss 스타일 라이트 팔레트).
|
||||
* 랜딩 디자인 토큰.
|
||||
* 색은 전부 여기서만 정의하고, 컴포넌트는 토큰 클래스(text-ink, bg-primary …)만 쓴다.
|
||||
*
|
||||
* 구조는 두 겹이다.
|
||||
* - 다크 무대(stage) : 히어로·협상 데모. 협상이 벌어지는 순간에만 조명을 끈다.
|
||||
* - 라이트 본문 : 나머지 섹션. 광고 유입 전환율을 위해 밝게 유지.
|
||||
*/
|
||||
@theme {
|
||||
--font-sans: 'Pretendard Variable', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Apple SD Gothic Neo", "Malgun Gothic", sans-serif;
|
||||
--font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
|
||||
/* 영문 디스플레이 — 라벨·강조 전용. 한글 본문은 절대 이걸로 쓰지 않는다
|
||||
(Playfair 는 한글 글리프가 없어 Pretendard 로 폴백되며 톤이 깨진다). */
|
||||
--font-display: 'Playfair Display', 'Pretendard Variable', Georgia, serif;
|
||||
|
||||
/* 브랜드 */
|
||||
--color-primary: #476EFF;
|
||||
--color-primary-deep: #2F52E0; /* hover */
|
||||
--color-primary-soft: #ECF0FF; /* 연한 파랑 배경 — 봇 말풍선, 배지 */
|
||||
/* ── 브랜드 액센트 ──────────────────────────────────────────────
|
||||
여기 3줄이 브랜드 색상각의 단일 소스다. 딥틸(#005961 / #00434A / #E3F4F5)로
|
||||
되돌리려면 이 3줄만 갈아끼우면 되고, 나머지 토큰·컴포넌트는 손대지 않는다. */
|
||||
--color-primary: #0101F3; /* 일렉트릭 블루 — 라이트 배경 전용. 레퍼런스 실측값 */
|
||||
/* 다크 무대용 액센트. #0101F3 을 #070E24 위에 얹으면 명암비가 2.0:1 로,
|
||||
WCAG 최소(4.5:1)의 절반도 안 된다 — 둘 다 어두운 색이라 그렇다.
|
||||
아래 값은 무대 배경 대비 약 6:1 이다. 무대 위 파란 글자는 반드시 이걸 쓴다. */
|
||||
--color-primary-on-stage: #7C8CFF;
|
||||
--color-primary-deep: #0101C4; /* hover */
|
||||
--color-primary-soft: #EAEAFF; /* 연한 배경 — 에이전트 말풍선, 배지 */
|
||||
|
||||
/* 텍스트. ink 는 다크 섹션에선 배경색으로도 쓴다 */
|
||||
--color-ink: #191F28;
|
||||
--color-ink-soft: #4E5968; /* 보조 본문 */
|
||||
--color-ink-muted: #8B95A1; /* 캡션 */
|
||||
--color-ink-faint: #B0B8C1; /* 플레이스홀더·각주 */
|
||||
/* ── 상대편(공급사) ────────────────────────────────────────────
|
||||
협상은 두 주체가 매 턴 구분돼야 읽힌다. 민트는 블루와 색상각 70° 차이라
|
||||
구분되면서도 같은 한색 계열이라 화면이 따로 놀지 않는다.
|
||||
NEGO WIZ 로고 민트(#0FFFD6)에서 왔다. */
|
||||
--color-counter: #0FFFD6; /* 무대 위 상대측 텍스트·강조 */
|
||||
--color-counter-deep: #077A66; /* 라이트 배경 위 텍스트 (흰 바탕 대비 확보용) */
|
||||
--color-counter-surface: #0A2F35; /* 무대 위 상대측 말풍선 바닥 */
|
||||
|
||||
/* ── 다크 무대 ────────────────────────────────────────────────── */
|
||||
--color-stage: #070E24; /* 무대 바닥 (그라데이션의 중간값) */
|
||||
--color-stage-deep: #03060F; /* 무대 가장자리 — 어두워지며 공간이 뒤로 물러난다 */
|
||||
--color-stage-lift: #16205A; /* 무대 상단 광원 — 여기서 빛이 온다 */
|
||||
--color-stage-raised: #101A3D; /* 무대 위 카드·상대측 말풍선 */
|
||||
--color-stage-line: #1E2A52; /* 무대 위 테두리 */
|
||||
--color-on-stage: #FFFFFF; /* 무대 위 1차 텍스트 */
|
||||
/* 2·3차 텍스트는 중립 회색 대신 연보라 계열로 둔다. 네이비 위에 색상각이 다른
|
||||
회색을 얹으면 탁해지는데, 같은 한색 가족이면 밝게 올려도 화면이 정돈된다.
|
||||
#F5F3FF 는 ADO2 디자인 시스템의 연보라 패널 색이다. */
|
||||
--color-on-stage-soft: #F5F3FF; /* 무대 위 2차 텍스트 — 2톤 헤드라인의 약한 쪽 */
|
||||
--color-on-stage-muted: #C6C0E4; /* 무대 위 라벨·캡션 */
|
||||
|
||||
/* ── 라이트 본문 텍스트 ────────────────────────────────────────
|
||||
먹색에 브랜드 색조를 섞어둔다. 순수 회색이면 페이지가 따로 논다. */
|
||||
--color-ink: #0B1024;
|
||||
--color-ink-soft: #454E6B; /* 보조 본문 */
|
||||
--color-ink-muted: #838CAA; /* 캡션 */
|
||||
--color-ink-faint: #AAB1C7; /* 플레이스홀더·각주 */
|
||||
|
||||
/* 면·선 */
|
||||
--color-surface: #F9FAFB; /* 회색 섹션 배경 */
|
||||
--color-surface-neu: #F2F4F7; /* 뉴모피즘 히어로 전용 배경 */
|
||||
--color-fill: #F2F4F6; /* 회색 채움 — 탭 트랙, 보조 버튼 */
|
||||
--color-fill-hover: #EAECEF;
|
||||
--color-line: #F2F4F6; /* 섹션 구분선 */
|
||||
--color-line-strong: #E5E8EB; /* 카드 테두리 */
|
||||
--color-surface: #F7F8FC; /* 회색 섹션 배경 */
|
||||
--color-surface-neu: #F1F3F9; /* 보조 섹션 배경 */
|
||||
--color-fill: #F0F2F8; /* 회색 채움 — 탭 트랙, 보조 버튼 */
|
||||
--color-fill-hover: #E6E9F2;
|
||||
--color-line: #EEF0F6; /* 섹션 구분선 */
|
||||
--color-line-strong: #E0E4EE; /* 카드 테두리 */
|
||||
|
||||
--color-positive: #0B8F57; /* 낙찰·성공 강조 */
|
||||
--color-positive-soft: #E8F7EF; /* 연한 초록 배경 — 낙찰 배지 */
|
||||
|
||||
--color-accent: #8F52FF; /* 보라 강조 — 결과 탭·히어로 장식 */
|
||||
--color-accent-soft: #F4EFFF; /* 연한 보라 배경 */
|
||||
|
||||
/* ── 모서리 ────────────────────────────────────────────────────
|
||||
레퍼런스 실측은 3.5~7px 이다. 20~32px 짜리 뭉툭한 카드가 제네릭 SaaS 의
|
||||
가장 강한 신호라, 여기서는 세 값으로만 고정한다.
|
||||
card — 카드·패널·목업
|
||||
control — 탭·배지·입력 등 작은 요소
|
||||
full — 버튼·아바타 (Tailwind 기본 rounded-full 사용) */
|
||||
--radius-card: 8px;
|
||||
--radius-control: 4px;
|
||||
}
|
||||
|
||||
/* 다크 무대 배경 그라데이션.
|
||||
단색 배경은 아무리 입자에 원근을 줘도 평면으로 읽힌다. 위쪽에 광원을 두고
|
||||
가장자리로 갈수록 어두워지게 하면 화면 자체에 안팎이 생겨 깊이가 성립한다. */
|
||||
.stage-bg {
|
||||
background:
|
||||
radial-gradient(120% 78% at 50% 8%, var(--color-stage-lift) 0%, transparent 62%),
|
||||
radial-gradient(100% 100% at 50% 42%, var(--color-stage) 0%, var(--color-stage-deep) 100%);
|
||||
}
|
||||
|
||||
/* 드래그 선택 색.
|
||||
루트에 걸린 selection:text-primary 는 라이트 본문 기준이다. 그 값(#0101F3)을 다크 무대
|
||||
위에 얹으면 명암비가 2.0:1 이라 — 위 --color-primary-on-stage 주석이 경고하는 바로 그
|
||||
상황 — 무대 섹션에서 텍스트를 드래그하면 글자가 사라진다.
|
||||
무대 안에서는 무대용 액센트로 갈아끼운다. 라이트 본문은 기존 그대로. */
|
||||
.stage-bg ::selection,
|
||||
[data-stage-hero] ::selection {
|
||||
background-color: color-mix(in srgb, var(--color-primary-on-stage) 30%, transparent);
|
||||
color: var(--color-on-stage);
|
||||
}
|
||||
|
||||
html {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { AnimatePresence, motion } from "motion/react"
|
||||
import { Bot, Clock, Database, Handshake, Scale, TrendingUp, UserRound, type LucideIcon } from "lucide-react"
|
||||
import { Clock, Database, Handshake, Scale, TrendingUp, UserRound, type LucideIcon } from "lucide-react"
|
||||
|
||||
import { Section } from "@/components/ui/section"
|
||||
import { SectionHeading } from "@/components/ui/section-heading"
|
||||
import { CONTROL_GAP, SectionHeading } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { useFadeUp } from "@/lib/motion"
|
||||
|
||||
@@ -44,28 +44,31 @@ export function Comparison() {
|
||||
|
||||
return (
|
||||
<Section id="comparison">
|
||||
<motion.div {...fadeUp} className="mb-12">
|
||||
<motion.div {...fadeUp}>
|
||||
<SectionHeading
|
||||
align="center"
|
||||
eyebrow="WHY NEGOTIUM"
|
||||
eyebrow="Before & After"
|
||||
title="협상 방식을 바꾸면, 무엇이 달라질까요"
|
||||
description="기존 가격 협상의 문제는 사람이 아니라 구조입니다."
|
||||
descriptionClassName="mt-4 text-[17px] max-w-2xl"
|
||||
descriptionClassName="max-w-2xl"
|
||||
/>
|
||||
</motion.div>
|
||||
|
||||
{/* 모드 토글 — 이용 가이드 탭과 같은 세그먼트 문법 */}
|
||||
<motion.div {...toggleFadeUp} className="flex justify-center mb-14">
|
||||
<div className="p-1 bg-fill rounded-[14px] inline-flex gap-1">
|
||||
{/* 모드 토글 — 이용 가이드 탭과 같은 세그먼트 문법.
|
||||
아래 간격(CONTROL_GAP)은 머리 간격보다 좁다. 토글은 자기가 조종하는
|
||||
카드들과 한 덩어리로 읽혀야지, 제목에 붙으면 무엇을 바꾸는 스위치인지 흐려진다. */}
|
||||
<motion.div {...toggleFadeUp} className={`flex justify-center ${CONTROL_GAP}`}>
|
||||
{/* 액티브를 bg-white 로 두면 트랙(bg-fill #F0F2F8) 과 거의 같은 밝기라
|
||||
멀리서 어느 쪽이 켜졌는지 안 보인다. 채움색으로 확실히 갈라준다. */}
|
||||
<div className="p-1.5 bg-fill rounded-full inline-flex gap-1.5">
|
||||
{MODES.map((m) => (
|
||||
<button
|
||||
key={m.key}
|
||||
onClick={() => selectMode(m.key)}
|
||||
className={`px-5 py-2.5 rounded-[10px] text-xs sm:text-sm font-bold transition-all flex items-center gap-2 cursor-pointer ${
|
||||
mode === m.key ? "bg-white text-primary shadow-sm" : "text-ink-soft hover:text-ink"
|
||||
className={`px-7 py-3 rounded-full text-[15px] font-semibold transition-colors cursor-pointer ${
|
||||
mode === m.key ? "bg-primary text-white" : "text-ink-muted hover:text-ink"
|
||||
}`}
|
||||
>
|
||||
{m.key === "after" && <Bot className="w-4 h-4" />}
|
||||
<span>{m.label}</span>
|
||||
</button>
|
||||
))}
|
||||
@@ -85,7 +88,7 @@ type Mode = "before" | "after"
|
||||
|
||||
const MODES: { key: Mode; label: string }[] = [
|
||||
{ key: "before", label: "기존 방식" },
|
||||
{ key: "after", label: "negotium 도입 후" },
|
||||
{ key: "after", label: "네고시움 도입 후" },
|
||||
]
|
||||
|
||||
type CompareItem = { label: string; icon: LucideIcon; before: string; after: string }
|
||||
@@ -97,13 +100,13 @@ function CompareCard({ item, mode, index }: { item: CompareItem; mode: Mode; ind
|
||||
return (
|
||||
<motion.div
|
||||
{...fadeUp}
|
||||
className={`p-7 rounded-[28px] flex flex-col gap-5 transition-colors duration-500 ${
|
||||
className={`p-7 rounded-card flex flex-col gap-5 transition-colors duration-500 ${
|
||||
active ? "bg-primary-soft/60" : "bg-surface"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div
|
||||
className={`w-11 h-11 rounded-2xl flex items-center justify-center transition-colors duration-500 ${
|
||||
className={`w-11 h-11 rounded-card flex items-center justify-center transition-colors duration-500 ${
|
||||
active ? "bg-primary/10 text-primary" : "bg-ink-muted/10 text-ink-muted"
|
||||
}`}
|
||||
>
|
||||
@@ -156,14 +159,14 @@ const ITEMS: CompareItem[] = [
|
||||
{
|
||||
label: "사람",
|
||||
icon: UserRound,
|
||||
before: "반복 흥정과 감정 노동에 지쳐 고급 인력이 이탈합니다.",
|
||||
after: "감정 소모는 봇이 맡고, 사람은 전략 업무와 대형 거래에 집중합니다.",
|
||||
before: "반복 협상에 시간을 뺏겨 전략 업무가 계속 밀립니다.",
|
||||
after: "반복 협상은 에이전트가 맡고, 담당자는 전략 구매와 대형 건에 집중합니다.",
|
||||
},
|
||||
{
|
||||
label: "파트너 관계",
|
||||
icon: Handshake,
|
||||
before: "감정 과열과 실랑이로 장기 파트너십이 흔들립니다.",
|
||||
after: "악역은 봇이 — 압박 없는 상시 협상으로 관계가 개선됩니다.",
|
||||
before: "담당자마다 기준이 달라 협력사가 조건을 예측하기 어렵습니다.",
|
||||
after: "에이전트가 같은 기준으로 상시 응대해 조건이 일관됩니다.",
|
||||
},
|
||||
{
|
||||
label: "의사 결정",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from "react"
|
||||
import { AnimatePresence, motion } from "motion/react"
|
||||
import { Building, CheckCircle2, Loader2, Mail, Phone, Send } from "lucide-react"
|
||||
import { Check, Loader2 } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input, Textarea } from "@/components/ui/input"
|
||||
@@ -8,7 +8,7 @@ import { Section } from "@/components/ui/section"
|
||||
import { SectionHeading } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { EASE_OUT_EXPO } from "@/lib/motion"
|
||||
import type { LucideIcon } from "lucide-react"
|
||||
import { submitLead } from "@/lib/lead"
|
||||
|
||||
const EMPTY_FORM = {
|
||||
companyName: '',
|
||||
@@ -18,19 +18,33 @@ const EMPTY_FORM = {
|
||||
message: '',
|
||||
}
|
||||
|
||||
/** 도입 문의 폼. 백엔드 미연결 — 제출은 데모 처리(1.2초 후 성공 화면). */
|
||||
/*
|
||||
* 상담 신청 폼 — 고관여 경로. 저관여 리드 캡처는 데모 요청 모달이 맡는다.
|
||||
*
|
||||
* 예전에는 백엔드가 없어서 1.2초 뒤 성공 화면만 띄웠다. 화면은 "접수되었습니다"인데
|
||||
* 영업이 받을 리드는 존재하지 않았고, 아무도 그 사실을 몰랐다. 지금은 데모 요청과
|
||||
* 같은 서버리스 함수(api/lead.ts)로 보내고, 서버가 리드를 확보했을 때만 성공을 띄운다.
|
||||
*/
|
||||
export function Contact() {
|
||||
const [formData, setFormData] = useState(EMPTY_FORM)
|
||||
const [status, setStatus] = useState<'idle' | 'submitting' | 'success'>('idle')
|
||||
const [status, setStatus] = useState<'idle' | 'submitting' | 'success' | 'error'>('idle')
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!formData.companyName || !formData.contactName || !formData.email || !formData.phone) {
|
||||
return
|
||||
}
|
||||
|
||||
setStatus('submitting')
|
||||
setTimeout(() => setStatus('success'), 1200)
|
||||
const result = await submitLead({
|
||||
source: 'contact',
|
||||
name: formData.contactName,
|
||||
email: formData.email,
|
||||
company: formData.companyName,
|
||||
phone: formData.phone,
|
||||
message: formData.message,
|
||||
})
|
||||
setStatus(result.ok ? 'success' : 'error')
|
||||
}
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
@@ -41,22 +55,12 @@ export function Contact() {
|
||||
const submitting = status === 'submitting'
|
||||
|
||||
return (
|
||||
<Section
|
||||
id="contact-section"
|
||||
bordered
|
||||
decor={
|
||||
<>
|
||||
<div className="absolute top-[20%] right-[10%] w-72 h-72 bg-primary/5 blur-[100px] rounded-full pointer-events-none" />
|
||||
<div className="absolute bottom-[10%] left-[5%] w-96 h-96 bg-primary/3 blur-[120px] rounded-full pointer-events-none" />
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Section id="contact-section" bordered>
|
||||
<SectionHeading
|
||||
align="center"
|
||||
className="mb-16"
|
||||
eyebrow="GET IN TOUCH"
|
||||
title="도입 문의 및 컨택하기"
|
||||
description="사내 ERP 연동부터 우리 기업에 맞춘 흥정 시나리오 구성까지, negotium의 구매 혁신 컨설턴트가 상세히 안내해 드립니다."
|
||||
eyebrow="Get in Touch"
|
||||
title="도입 문의"
|
||||
description="품목과 협력사 규모를 알려주시면, 예상 절감 구간과 도입 절차를 정리해 드립니다."
|
||||
descriptionClassName="max-w-xl"
|
||||
/>
|
||||
|
||||
@@ -70,10 +74,10 @@ export function Contact() {
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -20 }}
|
||||
transition={{ duration: 0.5, ease: EASE_OUT_EXPO }}
|
||||
className="space-y-6"
|
||||
className="space-y-9"
|
||||
>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormField label="회사명" icon={Building} required>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-9">
|
||||
<FormField label="회사명" required>
|
||||
<Input
|
||||
type="text"
|
||||
name="companyName"
|
||||
@@ -98,8 +102,8 @@ export function Contact() {
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormField label="이메일 주소" icon={Mail} required>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-9">
|
||||
<FormField label="이메일 주소" required>
|
||||
<Input
|
||||
type="email"
|
||||
name="email"
|
||||
@@ -111,7 +115,7 @@ export function Contact() {
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="연락처" icon={Phone} required>
|
||||
<FormField label="연락처" required>
|
||||
<Input
|
||||
type="tel"
|
||||
name="phone"
|
||||
@@ -128,30 +132,34 @@ export function Contact() {
|
||||
<Textarea
|
||||
name="message"
|
||||
rows={4}
|
||||
placeholder="현재 겪고 계신 구매 조율 상의 번거로움이나, 자동화를 원하시는 구체적인 부자재 품목 정보를 남겨주시면 더욱 맞춤화된 상담이 가능합니다."
|
||||
placeholder="협상 자동화를 검토 중인 품목이나 현재 겪는 어려움을 적어주세요."
|
||||
value={formData.message}
|
||||
onChange={handleChange}
|
||||
disabled={submitting}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
{/* 대체 연락처(이메일 등)를 넣으려면 실제 영업 주소를 받아서 채워야 한다.
|
||||
임의의 주소를 공개 랜딩에 박아둘 수는 없다. */}
|
||||
{status === 'error' && (
|
||||
<p role="alert" className="text-[13px] text-ink-soft leading-[1.6] break-keep">
|
||||
지금은 접수가 어렵습니다. 잠시 후 다시 시도해 주세요.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Typography variant="caption" className="font-medium">
|
||||
* 제출 시 입력하신 정보는 문의 사항 응답 및 도입 검토 목적에 한하여 사용되며, 관련 법령에 의거하여 안전하게
|
||||
보호됩니다.
|
||||
입력하신 정보는 문의 응답과 도입 검토 목적으로만 사용됩니다.
|
||||
</Typography>
|
||||
|
||||
<div className="pt-2">
|
||||
<Button type="submit" disabled={submitting} className="w-full shadow-sm hover:shadow-md">
|
||||
<Button type="submit" disabled={submitting} size="lg" className="w-full">
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
<span>신청서 전송 중...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Send className="w-5 h-5" />
|
||||
<span>도입 문의 및 상담 신청하기</span>
|
||||
</>
|
||||
<span>상담 신청</span>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -162,15 +170,14 @@ export function Contact() {
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ duration: 0.6, ease: EASE_OUT_EXPO }}
|
||||
className="text-center py-16 px-6 bg-primary/5 rounded-[32px] text-ink break-keep"
|
||||
className="text-center py-20 px-6 border border-line-strong rounded-card text-ink break-keep"
|
||||
>
|
||||
<div className="w-16 h-16 bg-primary/10 text-primary rounded-full flex items-center justify-center mx-auto mb-6">
|
||||
<CheckCircle2 className="w-8 h-8" />
|
||||
<div className="w-12 h-12 bg-primary text-white rounded-full flex items-center justify-center mx-auto mb-6">
|
||||
<Check className="w-6 h-6" strokeWidth={2.5} />
|
||||
</div>
|
||||
<h3 className="text-2xl font-extrabold text-ink mb-3">도입 문의 신청이 접수되었습니다</h3>
|
||||
<p className="text-ink-soft font-semibold text-[15px] leading-relaxed max-w-md mx-auto mb-8">
|
||||
작성해주신 담당자 정보({formData.contactName} 님)를 통해 24시간 이내에 전담 혁신 컨설턴트가 유선 혹은 이메일로
|
||||
연락을 드리겠습니다.
|
||||
<h3 className="text-[24px] font-semibold tracking-[-0.02em] text-ink mb-3">도입 문의 신청이 접수되었습니다</h3>
|
||||
<p className="text-ink-soft text-[15px] leading-[1.6] max-w-md mx-auto mb-8">
|
||||
{formData.contactName} 님께 영업일 기준 하루 안에 연락드리겠습니다.
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -190,22 +197,14 @@ export function Contact() {
|
||||
)
|
||||
}
|
||||
|
||||
function FormField({
|
||||
label,
|
||||
icon: Icon,
|
||||
required = false,
|
||||
children,
|
||||
}: {
|
||||
label: string
|
||||
icon?: LucideIcon
|
||||
required?: boolean
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
/* 라벨 옆 작은 아이콘은 정보를 더하지 않는다 — "회사명" 옆의 빌딩 아이콘이 알려주는 건
|
||||
이미 글자가 말한 것뿐이고, 필드마다 반복되면 폼이 산만해진다. 글자만 남긴다. */
|
||||
function FormField({ label, required = false, children }: { label: string; required?: boolean; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-ink-soft flex items-center gap-1.5">
|
||||
{Icon && <Icon className="w-3.5 h-3.5 text-ink-muted" />}
|
||||
{label} {required && <span className="text-primary">*</span>}
|
||||
<div className="space-y-2.5">
|
||||
<label className="block text-[14px] font-medium text-ink">
|
||||
{label}
|
||||
{required && <span className="text-primary ml-1" aria-hidden>*</span>}
|
||||
</label>
|
||||
{children}
|
||||
</div>
|
||||
|
||||
@@ -12,13 +12,12 @@ export function CoreValues() {
|
||||
|
||||
return (
|
||||
<Section id="core-values">
|
||||
<motion.div {...fadeUp} className="mb-24">
|
||||
<motion.div {...fadeUp}>
|
||||
<SectionHeading
|
||||
align="center"
|
||||
eyebrow="BEYOND EXPECTED VALUE"
|
||||
eyebrow="Beyond Price"
|
||||
title="가격 그 이상의 이점"
|
||||
description="절감액은 시작일 뿐 — 관계, 투명성, 그리고 사람의 시간까지 지킵니다."
|
||||
descriptionClassName="mt-4 text-[17px]"
|
||||
/>
|
||||
</motion.div>
|
||||
|
||||
@@ -37,7 +36,7 @@ function ValueStrip({ value, delay }: { value: Value; delay: number }) {
|
||||
const fadeUp = useFadeUp(delay)
|
||||
|
||||
return (
|
||||
<motion.div {...fadeUp} className="bg-surface p-8 rounded-[32px] flex items-start gap-5 transition-all hover:translate-y-[-4px]">
|
||||
<motion.div {...fadeUp} className="bg-surface p-8 rounded-card flex items-start gap-5 transition-all hover:translate-y-[-4px]">
|
||||
<div className="w-10 h-10 rounded-full bg-primary/5 flex items-center justify-center text-primary shrink-0 mt-1">
|
||||
<value.icon className="w-5 h-5" />
|
||||
</div>
|
||||
@@ -56,7 +55,7 @@ const VALUES: Value[] = [
|
||||
icon: Users,
|
||||
title: "파트너사 관계 수호",
|
||||
description:
|
||||
"단가를 깎는 악역과 감정 소모는 봇이 맡습니다. 담당자는 협력사와의 신뢰와 동반 성장, 큰 틀의 파트너십에만 집중하세요.",
|
||||
"단가 조율은 에이전트가 정해진 기준으로 반복합니다. 담당자는 협력사와의 신뢰와 동반 성장에 집중할 수 있습니다.",
|
||||
},
|
||||
{
|
||||
icon: Lock,
|
||||
@@ -68,7 +67,7 @@ const VALUES: Value[] = [
|
||||
icon: Briefcase,
|
||||
title: "핵심 전략에만 집중",
|
||||
description:
|
||||
"이메일·메신저로 반복되던 흥정 수작업은 봇이 전담합니다. 인력은 공급망 위기 대처, 우량 공급처 발굴 같은 전략 업무와 대형 거래에 투입하세요.",
|
||||
"이메일·메신저로 오가던 단가 협의는 에이전트가 전담합니다. 인력은 공급망 위기 대응과 신규 공급처 발굴에 투입하세요.",
|
||||
},
|
||||
{
|
||||
icon: Clock,
|
||||
|
||||
@@ -14,13 +14,12 @@ export function Faq() {
|
||||
|
||||
return (
|
||||
<Section id="faq" width="sm">
|
||||
<motion.div {...fadeUp} className="mb-24">
|
||||
<motion.div {...fadeUp}>
|
||||
<SectionHeading
|
||||
align="center"
|
||||
eyebrow="FAQ"
|
||||
title="자주 묻는 질문"
|
||||
description="도입 검토에서 가장 많이 받는 질문들입니다."
|
||||
descriptionClassName="mt-4 text-[17px]"
|
||||
/>
|
||||
</motion.div>
|
||||
|
||||
@@ -55,7 +54,7 @@ function FaqItem({
|
||||
const fadeUp = useFadeUp(delay)
|
||||
|
||||
return (
|
||||
<motion.div {...fadeUp} className="bg-surface rounded-[28px] overflow-hidden">
|
||||
<motion.div {...fadeUp} className="bg-surface rounded-card overflow-hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
@@ -96,14 +95,14 @@ function FaqItem({
|
||||
|
||||
const FAQS: FaqEntry[] = [
|
||||
{
|
||||
question: "공급사가 봇과의 협상을 싫어하지 않을까요?",
|
||||
question: "협력사가 에이전트와의 협상을 꺼리지 않을까요?",
|
||||
answer:
|
||||
"오히려 반대입니다. 이 거래들 대부분은 지금껏 협상 테이블에 오르지도 못하던 건입니다. 봇은 24시간 원하는 시간에, 압박 없이, 늘 같은 기준으로 응대합니다. 글로벌 동종 서비스의 공급사 만족도는 82%에 이릅니다.",
|
||||
"이 건들 대부분은 지금껏 협상 테이블에 오르지도 못하던 거래입니다. 에이전트는 협력사가 편한 시간에, 늘 같은 기준으로 응대합니다. 글로벌 동종 서비스의 공급사 만족도는 82%로 보고됩니다.",
|
||||
},
|
||||
{
|
||||
question: "봇이 우리 기준을 벗어나 합의해 버리면요?",
|
||||
question: "에이전트가 우리 기준을 벗어나 합의해 버리면요?",
|
||||
answer:
|
||||
"그럴 수 없습니다. 봇은 견적을 만들 때 정한 목표가와 낙찰 기준 밖으로 나가지 않고, 최종 낙찰 규칙도 사용자가 정합니다.",
|
||||
"그럴 수 없습니다. 에이전트는 견적을 만들 때 정한 목표가와 낙찰 기준 밖으로 나가지 않고, 최종 낙찰 규칙도 사용자가 정합니다.",
|
||||
},
|
||||
{
|
||||
question: "기존 시스템과 연동되나요?",
|
||||
|
||||
@@ -2,58 +2,71 @@ import { motion } from "motion/react"
|
||||
import { ArrowRight } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { NegotiationReplay } from "@/components/ui/negotiation-replay"
|
||||
import { Section } from "@/components/ui/section"
|
||||
import { CTA_GAP, SectionHeading } from "@/components/ui/section-heading"
|
||||
import { useFadeUp } from "@/lib/motion"
|
||||
|
||||
/** 최종 CTA — 다크 몰입 섹션. */
|
||||
/**
|
||||
* 최종 CTA — 히어로와 같은 다크 무대로 페이지를 닫는다.
|
||||
*
|
||||
* 이 섹션은 원래 디자인 시스템을 우회하고 있었다: bg-ink(무대 색이 아님), font-extrabold,
|
||||
* 알약 배지, blur(120px) 글로우 블롭, 다크 배경 위 라이트 토큰(text-ink-muted).
|
||||
* 전부 토큰으로 돌렸다. 글로우 블롭은 AI 가 만든 히어로의 대표 장식이라 걷어냈다.
|
||||
*
|
||||
* 섹션 껍데기와 머리도 손으로 짜던 걸 Section/SectionHeading 으로 돌렸다.
|
||||
* 우회하는 동안 아이브로우 간격이 여기만 20px 이었다(다른 섹션은 12px).
|
||||
*
|
||||
* 전환을 요청하는 자리에 결과 화면을 같이 둔다. 이용 가이드는 "실제 화면으로 보여드립니다"
|
||||
* 라고 약속해서 재구성 목업을 넣을 수 없지만, 여기는 그 약속이 없어 마케팅 컴포짓이 맞는 자리다.
|
||||
*/
|
||||
export function FinalCTA() {
|
||||
return (
|
||||
<section className="relative bg-ink text-white py-36 md:py-48 overflow-hidden">
|
||||
{/* 다크 섹션 중앙의 은은한 파란 글로우 */}
|
||||
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[800px] h-[800px] rounded-full bg-primary/15 blur-[120px] pointer-events-none" />
|
||||
const fadeUp = useFadeUp()
|
||||
const mediaFadeUp = useFadeUp(0.12)
|
||||
|
||||
<div className="max-w-3xl mx-auto px-6 text-center relative z-10">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
whileInView={{ opacity: 1, scale: 1 }}
|
||||
viewport={{ once: true }}
|
||||
className="inline-flex items-center gap-2 px-4 py-1.5 bg-primary/10 border border-primary/20 rounded-full text-xs font-bold text-primary mb-8"
|
||||
>
|
||||
<span>START RECLAIMING YOUR BUDGET TODAY</span>
|
||||
return (
|
||||
/* 영상이 붙으면서 width 를 md(max-w-4xl) → lg(max-w-5xl) 로 넓혔다.
|
||||
세로 목업과 카피를 4xl 안에 2단으로 밀어넣으면 양쪽 다 좁아진다. */
|
||||
<Section bg="stage" width="lg">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-12 gap-12 lg:gap-16 items-center">
|
||||
<motion.div {...fadeUp} className="lg:col-span-7 text-center lg:text-left">
|
||||
<SectionHeading
|
||||
align="left"
|
||||
className="text-center lg:text-left"
|
||||
tone="stage"
|
||||
size="display"
|
||||
gap="none"
|
||||
eyebrow="Start Today"
|
||||
/* 닫는 CTA 라 히어로(74px)보다는 낮추고 섹션 제목(64px)보다는 세운다.
|
||||
2단이 되면서 한 줄이 짧아져 lg 부터 한 단계 더 줄인다. */
|
||||
titleClassName="text-[32px] sm:text-[44px] md:text-[56px] lg:text-[48px]"
|
||||
title={
|
||||
<>
|
||||
<span className="text-white">지금도 구매 예산은</span>
|
||||
<br />
|
||||
<span className="text-on-stage-soft/60">조용히 새고 있을지 모릅니다</span>
|
||||
</>
|
||||
}
|
||||
description="협상 테이블에 오르지 못하고 그냥 넘어가던 건들이 있습니다. 네고시움 에이전트가 정해진 기준 안에서 그 건들을 대신 조율합니다."
|
||||
descriptionClassName="max-w-xl text-on-stage-soft/75 mx-auto lg:mx-0"
|
||||
/>
|
||||
|
||||
<div className={`${CTA_GAP} flex justify-center lg:justify-start`}>
|
||||
<Button href="#contact-section" variant="stage" size="xl" className="group">
|
||||
<span>도입 상담 신청</span>
|
||||
<ArrowRight className="w-4 h-4 transition-transform group-hover:translate-x-0.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
<motion.h2
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.8, delay: 0.1 }}
|
||||
className="text-3xl sm:text-4xl md:text-[54px] font-extrabold tracking-tighter mb-8 text-white leading-[1.2] break-keep"
|
||||
>
|
||||
지금도 구매 예산은 <br className="sm:hidden" />
|
||||
조용히 새고 있을지 모릅니다
|
||||
</motion.h2>
|
||||
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.8, delay: 0.2 }}
|
||||
className="text-[17px] text-ink-muted max-w-xl mx-auto mb-14 leading-relaxed font-semibold break-keep"
|
||||
>
|
||||
수작업으로 진행되어 수많은 단가 타협 기회를 흘려보내던 파트너사 흥정, 규칙 준수에 압도적으로 특화된 negotium 봇에
|
||||
위임하고 재무 마진을 안전히 지키십시오.
|
||||
</motion.p>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.8, delay: 0.3 }}
|
||||
>
|
||||
<Button href="#contact-section" size="xl" className="gap-2.5 hover:-translate-y-px">
|
||||
<span>도입 및 계약 상담 신청하기</span>
|
||||
<ArrowRight className="w-5 h-5" />
|
||||
</Button>
|
||||
{/* 결과 화면. 예전엔 negotiation_annotated_3d.mp4 였는데 컴포넌트로 바꿨다 —
|
||||
영상은 화자("아이마켓 구매 MD")와 색이 픽셀에 구워져 있어 둘 다 못 고쳤다.
|
||||
다크 무대에 네이티브로 그리니 밝은 영상이 구멍처럼 뜨던 문제도 같이 사라져서,
|
||||
카드로 감싸고 그림자로 띄우던 처리가 더는 필요 없다. */}
|
||||
<motion.div {...mediaFadeUp} className="lg:col-span-5">
|
||||
<NegotiationReplay className="mx-auto max-w-[360px] lg:max-w-none" />
|
||||
</motion.div>
|
||||
</div>
|
||||
</section>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
@@ -8,7 +8,7 @@ export function Footer() {
|
||||
<div className="md:col-span-8">
|
||||
<Logo className="mb-6" />
|
||||
<Typography variant="caption" className="max-w-sm mb-6 font-medium">
|
||||
negotium은 협상 봇이 공급사와 1:1로 단가를 조율하고 낙찰까지 처리하는 B2B 구매 협상 자동화 솔루션입니다.
|
||||
네고시움은 협상 에이전트가 공급사와 1:1로 단가를 조율하고 낙찰까지 처리하는 B2B 구매 협상 자동화 솔루션입니다.
|
||||
</Typography>
|
||||
<p className="text-xs text-ink-faint font-semibold">
|
||||
© {new Date().getFullYear()} negotium Co., Ltd. All rights reserved.
|
||||
|
||||
@@ -5,36 +5,78 @@ import { Button } from "@/components/ui/button"
|
||||
import { Logo } from "@/components/ui/logo"
|
||||
|
||||
export function Header() {
|
||||
const [scrolled, setScrolled] = useState(false)
|
||||
// 두 상태는 조건이 다르다. 하나로 묶으면 다크 히어로 위에 흰 바가 떠버린다.
|
||||
// compact — 조금이라도 스크롤하면 높이를 줄인다.
|
||||
// onStage — 다크 히어로를 벗어나기 전까지. 이때는 배경을 깔지 않고 로고를 반전시킨다.
|
||||
const [compact, setCompact] = useState(false)
|
||||
const [onStage, setOnStage] = useState(true)
|
||||
|
||||
// 스크롤 시 헤더를 반투명 블러 배경으로 전환
|
||||
useEffect(() => {
|
||||
const handleScroll = () => setScrolled(window.scrollY > 40)
|
||||
const handleScroll = () => setCompact(window.scrollY > 40)
|
||||
window.addEventListener("scroll", handleScroll, { passive: true })
|
||||
handleScroll()
|
||||
return () => window.removeEventListener("scroll", handleScroll)
|
||||
}, [])
|
||||
|
||||
/* "다크 히어로 위에 있는가"는 스크롤 수치가 아니라 교차 상태다.
|
||||
scrollY 로 계산하면 하이드레이션 전에 스크롤 위치가 잡힌 경우(ScrollRestoration,
|
||||
새로고침, 뒤로가기) 초기 계산이 0 에서 끝나고 이후 스크롤 이벤트가 없으면
|
||||
영영 갱신되지 않는다 — 흰 배경 위에 흰 글자 버튼이 남는다.
|
||||
IntersectionObserver 는 관찰 시작 즉시 올바른 값을 준다. */
|
||||
useEffect(() => {
|
||||
const stage = document.querySelector("[data-stage-hero]")
|
||||
if (!stage) {
|
||||
setOnStage(false) // 다크 히어로가 없는 페이지에서는 항상 라이트
|
||||
return
|
||||
}
|
||||
// 헤더 높이(약 80px)만큼 위에서 미리 전환되도록 상단 마진을 음수로 준다.
|
||||
const io = new IntersectionObserver(([entry]) => setOnStage(entry.isIntersecting), {
|
||||
rootMargin: "-80px 0px 0px 0px",
|
||||
threshold: 0,
|
||||
})
|
||||
io.observe(stage)
|
||||
return () => io.disconnect()
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<header
|
||||
className={`fixed top-0 left-0 right-0 z-40 safe-t safe-x transition-all duration-300 ${
|
||||
scrolled ? "py-4 bg-white/80 backdrop-blur-xl border-b border-line" : "py-6 bg-transparent border-b border-transparent"
|
||||
/* 배경은 "스크롤됐을 때"만 깔되, 무대 위에서는 흰색이 아니라 무대색으로 깐다.
|
||||
투명한 채로 두면 히어로 카피가 헤더 밑으로 지나가며 nav 글자와 겹쳐 읽힌다. */
|
||||
className={`fixed top-0 left-0 right-0 z-40 safe-t safe-x transition-all duration-300 ${compact ? "py-4" : "py-6"} ${
|
||||
!compact
|
||||
? "bg-transparent border-b border-transparent"
|
||||
: onStage
|
||||
? "bg-stage/80 backdrop-blur-xl border-b border-stage-line"
|
||||
: "bg-white/80 backdrop-blur-xl border-b border-line"
|
||||
}`}
|
||||
>
|
||||
<div className="max-w-5xl mx-auto px-6 flex items-center justify-between">
|
||||
<a href="#">
|
||||
<Logo />
|
||||
<Logo className={onStage ? "brightness-0 invert" : undefined} />
|
||||
</a>
|
||||
|
||||
<nav className="hidden md:flex items-center gap-8 text-[15px] font-semibold text-ink-soft">
|
||||
<nav
|
||||
className={`hidden md:flex items-center gap-8 text-[15px] font-semibold transition-colors ${
|
||||
onStage ? "text-on-stage-soft" : "text-ink-soft"
|
||||
}`}
|
||||
>
|
||||
{NAV_LINKS.map(({ href, label }) => (
|
||||
<a key={href} href={href} className="hover:text-ink transition-colors">
|
||||
<a
|
||||
key={href}
|
||||
href={href}
|
||||
className={`transition-colors ${onStage ? "hover:text-on-stage" : "hover:text-ink"}`}
|
||||
>
|
||||
{label}
|
||||
</a>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<Button href="#contact-section" size="pill" className="gap-1.5">
|
||||
<Button
|
||||
href="#contact-section"
|
||||
variant={onStage ? "stageGhost" : "primary"}
|
||||
size={onStage ? "stageRound" : "pill"}
|
||||
className="gap-1.5"
|
||||
>
|
||||
<span>상담 신청</span>
|
||||
<ArrowUpRight className="w-4 h-4" />
|
||||
</Button>
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { motion } from "motion/react"
|
||||
import { ArrowDown, ArrowRight } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
/** 히어로 변형 — 실시간 협상 콘솔 시즐 영상을 전면에 세운 풀와이드 히어로. */
|
||||
export function HeroConsole() {
|
||||
return (
|
||||
<section className="relative min-h-screen bg-surface-neu text-ink flex flex-col justify-center pt-32 pb-20 overflow-hidden">
|
||||
<div className="mesh-bg absolute top-[-260px] left-[-160px] opacity-40 pointer-events-none" />
|
||||
|
||||
<div className="max-w-6xl mx-auto px-6 w-full relative z-10">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 28, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
transition={{ duration: 0.8, delay: 0.1 }}
|
||||
className="rounded-[28px] overflow-hidden border border-line-strong shadow-[0_30px_80px_rgba(20,25,45,0.12)] bg-white"
|
||||
>
|
||||
<video
|
||||
src="/gifs/hero_console.mp4"
|
||||
poster="/gifs/hero_console.jpg"
|
||||
autoPlay
|
||||
muted
|
||||
loop
|
||||
playsInline
|
||||
className="w-full h-auto block"
|
||||
/>
|
||||
</motion.div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.8, delay: 0.35 }}
|
||||
className="flex flex-col sm:flex-row justify-center gap-5 pt-10"
|
||||
>
|
||||
<Button
|
||||
href="#contact-section"
|
||||
className="w-full sm:w-auto group shadow-[0_8px_24px_rgba(49,130,246,0.15)] hover:scale-[1.02] active:scale-[0.98]"
|
||||
>
|
||||
<span>도입 문의 상담 받기</span>
|
||||
<ArrowRight className="w-5 h-5 transition-transform group-hover:translate-x-1" />
|
||||
</Button>
|
||||
<Button href="#how-it-works" variant="glass" className="w-full sm:w-auto gap-1.5">
|
||||
<span>작동 방식 보기</span>
|
||||
<ArrowDown className="w-4 h-4 text-ink-soft" />
|
||||
</Button>
|
||||
</motion.div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useState } from "react"
|
||||
import { ArrowRight } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { DemoRequestModal } from "@/components/ui/demo-request-modal"
|
||||
import { CTA_GAP, DISPLAY_LEAD_GAP } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
|
||||
/**
|
||||
* 다크 무대 히어로 — 배경 루프 영상.
|
||||
*
|
||||
* 예전에는 캔버스가 negotium 파이프라인을 직접 그렸고(입자 240개·6단계 서사·무리 라벨),
|
||||
* 배경이 곧 설명이었다. 지금은 배경을 배경으로만 쓴다 — 설명은 카피와 아래 섹션이 맡는다.
|
||||
* 그래서 무리 라벨(CLUSTER_ANCHORS)도 함께 걷어냈다. 좌표 소스가 사라진 라벨은
|
||||
* 화면비가 바뀔 때마다 어긋나기만 하고 아무것도 설명하지 못한다.
|
||||
*
|
||||
* 배경이 의미를 지지 않으므로 카피 가독성이 1순위다. 그래서:
|
||||
* - 영상 위에 스크림을 깐다. 예전 캔버스는 하단 밴드에만 입자가 있어 상단이 비었지만,
|
||||
* 이 영상은 화면 전체에 밝은 요소가 흩어져 흰 글자가 묻힌다.
|
||||
* - 카피는 화면 중앙 정렬. 밴드 개념이 없으니 상하로 나눌 이유도 없다.
|
||||
*/
|
||||
export function HeroDataFlow() {
|
||||
const [demoOpen, setDemoOpen] = useState(false)
|
||||
|
||||
return (
|
||||
<section
|
||||
data-stage-hero
|
||||
className="stage-bg relative min-h-screen text-on-stage flex flex-col overflow-hidden"
|
||||
>
|
||||
{/* 영상은 가로 화면에서만 튼다.
|
||||
16:9 소스를 세로 화면에 object-cover 로 깔면 가로가 62% 잘리고 남은 38% 가
|
||||
1.7배로 확대된다(848x1220 실측) — 데이터 입자가 거대한 보케로 뭉개져서
|
||||
배경이 아니라 노이즈가 된다. 캔버스는 뷰포트에 맞춰 그렸으니 없던 문제다.
|
||||
세로에서는 무대 그라데이션(stage-bg)만 남긴다. 그게 브랜드 배경이라 빈 화면이 아니다.
|
||||
prefers-reduced-motion 에서도 같은 이유로 영상을 감춘다 — 포스터가 뒤를 받친다. */}
|
||||
<div
|
||||
aria-hidden
|
||||
className="absolute inset-0 hidden landscape:block motion-reduce:hidden bg-cover bg-center"
|
||||
style={{ backgroundImage: "url(/gifs/hero_loop.jpg)" }}
|
||||
>
|
||||
<video
|
||||
className="w-full h-full object-cover"
|
||||
src="/gifs/hero_loop.mp4"
|
||||
poster="/gifs/hero_loop.jpg"
|
||||
autoPlay
|
||||
muted
|
||||
loop
|
||||
playsInline
|
||||
preload="metadata"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 카피 가독성용 스크림.
|
||||
색은 하나(stage-deep)로 두고 알파만 움직인다 — 중간 stop 에서 색이 바뀌면
|
||||
그 지점이 가로선으로 읽힌다.
|
||||
|
||||
알파는 90/60/95 였다가 낮췄다. 그 값은 헤드라인 둘째 줄이 회색(/60)이던 시절
|
||||
그 글자를 살리려고 깐 것인데, 가장 옅은 지점에서도 영상이 40% 만 남아서
|
||||
배경 전체가 탁해졌다. 헤드라인이 흰색이 된 지금은 이만큼 덮을 이유가 없다.
|
||||
구간별로 필요한 만큼만 준다 — 위는 헤더 nav(작은 회색 글자), 가운데는 흰
|
||||
헤드라인이라 가장 옅게, 아래는 다음 섹션으로 넘어가는 암전(h-32)이 따로 있다. */}
|
||||
<div
|
||||
aria-hidden
|
||||
className="absolute inset-0 pointer-events-none bg-linear-to-b from-stage-deep/50 via-transparent to-stage-deep/45"
|
||||
/>
|
||||
|
||||
{/* 카피 뒤만 국소적으로 누른다.
|
||||
전면을 균일하게 덮으면 글자는 살지만 영상이 통째로 탁해진다. 반대로 다 걷으면
|
||||
헤드라인(흰색 74px)은 버텨도 리드 문단(17px)이 밝은 입자 위에서 읽히지 않는다.
|
||||
둘 다 만족하는 유일한 방법은 덮는 범위를 글자가 있는 자리로 좁히는 것이다.
|
||||
가장자리는 영상이 그대로 보이고 가운데만 어두워진다. */}
|
||||
<div
|
||||
aria-hidden
|
||||
className="absolute inset-0 pointer-events-none"
|
||||
style={{
|
||||
background:
|
||||
"radial-gradient(58% 42% at 50% 45%," +
|
||||
" color-mix(in srgb, var(--color-stage-deep) 85%, transparent) 0%," +
|
||||
" color-mix(in srgb, var(--color-stage-deep) 55%, transparent) 45%," +
|
||||
" transparent 72%)",
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 아래 라이트 섹션과의 경계를 부드럽게 */}
|
||||
<div aria-hidden className="absolute inset-x-0 bottom-0 h-32 bg-linear-to-b from-transparent to-stage pointer-events-none" />
|
||||
|
||||
{/* pt-[104px] 는 fixed 헤더 회피용 바닥. 그 아래 남은 공간에서 수직 중앙 정렬한다. */}
|
||||
<div className="relative z-10 w-full flex-1 pt-[104px] pb-16 flex items-center">
|
||||
<div className="max-w-4xl mx-auto px-6 w-full text-center">
|
||||
{/* 히어로 카피에는 진입 애니메이션을 걸지 않는다.
|
||||
여기가 LCP 요소라 opacity:0 으로 시작하면 하이드레이션 전까지 첫 화면이 비고,
|
||||
광고 유입처럼 JS 가 느린 환경에서 그대로 손실이 된다. 모션은 배경 영상이 맡는다. */}
|
||||
{/* 여기는 2톤을 쓰지 않는다. 예전 캔버스 배경은 하단 밴드에만 입자가 있어 헤드라인
|
||||
뒤가 거의 단색이었고, 그때는 투명도 60% 로 낮춘 둘째 줄도 읽혔다. 배경이 영상으로
|
||||
바뀌면서 밝은 요소가 글자 뒤로 지나가 그 대비가 무너졌다 — 배경이 움직이는 위에서는
|
||||
가독성이 조판 장치보다 우선한다. 2톤은 최종 CTA 에 남아 있다(그쪽은 배경이 정적). */}
|
||||
<Typography variant="stageDisplay">
|
||||
<span className="text-white">협력사 전원과 1:1로,</span>
|
||||
<br />
|
||||
<span className="text-white">동시에 협상합니다.</span>
|
||||
</Typography>
|
||||
|
||||
{/* 히어로는 h1 이어야 해서 SectionHeading(h2 고정)을 못 쓴다. 대신 간격만은
|
||||
같은 상수를 물려 최종 CTA 와 리듬이 어긋나지 않게 한다. */}
|
||||
<p className={`${DISPLAY_LEAD_GAP} text-base sm:text-lg text-on-stage-soft leading-relaxed break-keep max-w-2xl mx-auto`}>
|
||||
품목·목표가·마감일만 정하면 됩니다. 협상 에이전트가 협력사마다 따로 붙어 단가를 조율하고, 마감 시각에
|
||||
최저 투찰가로 낙찰까지 판정합니다.
|
||||
</p>
|
||||
|
||||
{/* 2차 CTA 는 상담 신청(#contact-section)과 목적지가 겹쳐 사실상 같은 버튼이었다.
|
||||
데모 경로로 갈라서, 고관여 폼(상담 신청) 앞단에 저관여 리드 캡처를 둔다.
|
||||
|
||||
문구는 "클릭하면 무슨 일이 일어나는가"에 맞춘다.
|
||||
협상 예시 체험 — 페이지 안에서 바로 조작한다. 고정 데이터라 "예시"를 밝히되,
|
||||
도착 섹션이 "직접 경험해 보세요"·"해보기" 라 "보기"로 낮추면 어긋난다.
|
||||
실제 데모 받기 — 누르면 폼이 뜨고 이메일로 온다. "체험"이라 쓰면 눌렀을 때
|
||||
바로 만질 줄 알았다가 입력을 요구받아 낚인 느낌이 된다. */}
|
||||
<div className={`${CTA_GAP} flex flex-col sm:flex-row gap-3 justify-center`}>
|
||||
<Button href="#how-it-works" variant="stage" size="stageRound" className="group">
|
||||
<span>협상 예시 체험</span>
|
||||
<ArrowRight className="w-4 h-4 transition-transform group-hover:translate-x-0.5" />
|
||||
</Button>
|
||||
<Button type="button" variant="stageGhost" size="stageRound" onClick={() => setDemoOpen(true)}>
|
||||
실제 데모 받기
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DemoRequestModal open={demoOpen} onClose={() => setDemoOpen(false)} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
import { motion } from "motion/react"
|
||||
import { ArrowDown, ArrowRight } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { EASE_OUT_EXPO } from "@/lib/motion"
|
||||
|
||||
/** 기본 히어로 — 파스텔 블롭 + 그리드 + 떠다니는 와이어프레임 도형. */
|
||||
export function HeroGlassmorphic() {
|
||||
return (
|
||||
<section className="relative min-h-screen bg-surface text-ink flex flex-col justify-center pt-32 overflow-hidden">
|
||||
{/* 흐릿한 파스텔 블롭 배경 */}
|
||||
<div className="absolute top-[10%] right-[15%] w-[480px] h-[480px] bg-primary/10 rounded-full filter blur-[120px] pointer-events-none" />
|
||||
<div className="absolute bottom-[10%] left-[10%] w-[450px] h-[450px] bg-accent/10 rounded-full filter blur-[120px] pointer-events-none" />
|
||||
<div className="absolute top-[30%] left-[30%] w-[380px] h-[380px] bg-primary/10 rounded-full filter blur-[100px] pointer-events-none" />
|
||||
|
||||
{/* 저채도 그리드 패턴 오버레이 */}
|
||||
<div className="absolute inset-0 bg-[linear-gradient(rgba(0,0,0,0.01)_1px,transparent_1px),linear-gradient(90deg,rgba(0,0,0,0.01)_1px,transparent_1px)] bg-[size:40px_40px] pointer-events-none" />
|
||||
|
||||
{/* 떠다니는 와이어프레임 도형 — max-w-7xl 안에 가둠 */}
|
||||
<div className="absolute inset-0 max-w-7xl mx-auto pointer-events-none z-0">
|
||||
<motion.div
|
||||
animate={{ y: [0, -18, 0], rotate: [12, 42, 12] }}
|
||||
transition={{ duration: 8, repeat: Infinity, ease: "easeInOut" }}
|
||||
className="absolute top-[15%] left-[8vw] lg:left-[10%] w-16 h-16 sm:w-28 sm:h-28 border-2 border-primary/40 bg-white/40 shadow-[0_8px_32px_rgba(49,130,246,0.05)] rounded-[28px] pointer-events-none z-0"
|
||||
/>
|
||||
<motion.div
|
||||
animate={{ rotate: -360 }}
|
||||
transition={{ duration: 80, repeat: Infinity, ease: "linear" }}
|
||||
className="absolute bottom-[18%] left-[6vw] lg:left-[12%] w-28 h-28 sm:w-48 sm:h-48 border-2 border-dashed border-accent/30 rounded-full pointer-events-none z-0"
|
||||
/>
|
||||
<motion.div
|
||||
animate={{ x: [0, 10, 0], y: [0, 10, 0] }}
|
||||
transition={{ duration: 10, repeat: Infinity, ease: "easeInOut" }}
|
||||
className="absolute top-[30%] right-[8vw] lg:right-[12%] w-20 h-20 sm:w-36 sm:h-36 border-2 border-primary/20 rounded-[40px] pointer-events-none z-0"
|
||||
>
|
||||
<div className="w-full h-full bg-gradient-to-tr from-primary/5 to-transparent rounded-[38px]" />
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-4xl mx-auto px-6 w-full py-24 relative z-10 flex flex-col items-center text-center">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.9, delay: 0.1, ease: EASE_OUT_EXPO }}
|
||||
>
|
||||
<Typography variant="display" className="mb-8">
|
||||
구매 협상, 이제 <span className="text-primary">봇이 알아서</span> <br className="hidden sm:inline" />
|
||||
흥정부터 낙찰까지 자동으로
|
||||
</Typography>
|
||||
</motion.div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.9, delay: 0.2, ease: EASE_OUT_EXPO }}
|
||||
>
|
||||
<Typography variant="lead" className="md:text-[20px] max-w-2xl mb-12">
|
||||
협상할수록 강화학습으로 흥정 전략을 알아서 다듬어갑니다. <br className="hidden sm:inline" />
|
||||
감정 없이, 지치지 않고, 24시간 연중무휴 — 결렬 대신 성사로 이끕니다.
|
||||
</Typography>
|
||||
</motion.div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.9, delay: 0.3, ease: EASE_OUT_EXPO }}
|
||||
className="flex flex-col sm:flex-row gap-4 items-center justify-center w-full max-w-md z-20"
|
||||
>
|
||||
<Button
|
||||
href="#contact-section"
|
||||
className="w-full sm:w-auto group shadow-[0_8px_24px_rgba(49,130,246,0.15)] hover:scale-[1.02] active:scale-[0.98]"
|
||||
>
|
||||
<span>도입 문의 상담 받기</span>
|
||||
<ArrowRight className="w-5 h-5 transition-transform group-hover:translate-x-1" />
|
||||
</Button>
|
||||
<Button href="#how-it-works" variant="glass" className="w-full sm:w-auto gap-1.5">
|
||||
<span>작동 방식 보기</span>
|
||||
<ArrowDown className="w-4 h-4 text-ink-soft" />
|
||||
</Button>
|
||||
</motion.div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { motion } from "motion/react"
|
||||
import { ArrowDown, ArrowRight } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
|
||||
/** 대안 히어로 — 뉴모피즘 배경 + 실제 모바일 협상 화면(GIF) 폰 목업. */
|
||||
export function HeroNeumorphic() {
|
||||
return (
|
||||
<section className="relative min-h-screen bg-surface-neu text-ink flex flex-col justify-center pt-32 pb-20 overflow-hidden">
|
||||
{/* 우측 상단 메시 제거 — 영상 배경(#F2F4F7)과 섹션 배경을 완전 동일하게 유지해 경계선 없이 블렌딩 */}
|
||||
|
||||
<div className="max-w-5xl mx-auto px-6 w-full relative z-10 grid grid-cols-1 lg:grid-cols-12 gap-16 items-center">
|
||||
{/* 좌: 카피 + CTA */}
|
||||
<div className="lg:col-span-7 space-y-8 text-left">
|
||||
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.8, delay: 0.1 }}>
|
||||
<Typography variant="display" className="text-4xl sm:text-5xl lg:text-[54px] leading-[1.15]">
|
||||
구매 협상, <br />
|
||||
이제 <span className="text-primary">봇이 알아서</span> <br />
|
||||
흥정부터 낙찰까지 자동으로
|
||||
</Typography>
|
||||
</motion.div>
|
||||
|
||||
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.8, delay: 0.2 }}>
|
||||
<Typography variant="lead" className="max-w-xl">
|
||||
불필요한 실랑이와 감정 소모 없이, 예산 상한선 내에서 최적의 원가 절감을 달성하세요. 데이터 기반의 자율 흥정 봇이
|
||||
24시간 실시간 대리 협상을 완료합니다.
|
||||
</Typography>
|
||||
</motion.div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.8, delay: 0.3 }}
|
||||
className="flex flex-col sm:flex-row gap-5 pt-4"
|
||||
>
|
||||
<Button
|
||||
href="#contact-section"
|
||||
className="w-full sm:w-auto group shadow-[0_8px_24px_rgba(49,130,246,0.15)] hover:scale-[1.02] active:scale-[0.98]"
|
||||
>
|
||||
<span>도입 문의 상담 받기</span>
|
||||
<ArrowRight className="w-5 h-5 transition-transform group-hover:translate-x-1" />
|
||||
</Button>
|
||||
<Button href="#how-it-works" variant="glass" className="w-full sm:w-auto gap-1.5">
|
||||
<span>작동 방식 보기</span>
|
||||
<ArrowDown className="w-4 h-4 text-ink-soft" />
|
||||
</Button>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
{/* 우: 모바일 협상 채팅 + 외부 설명 UI(제안가·협상카드·낙찰 하이라이트) 합성 영상 */}
|
||||
<div className="lg:col-span-5 flex justify-center">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ duration: 0.8, delay: 0.2 }}
|
||||
className="w-full flex justify-center"
|
||||
>
|
||||
<video
|
||||
src="/gifs/negotiation_annotated_3d.mp4?v=w3"
|
||||
poster="/gifs/negotiation_annotated_3d.jpg?v=w3"
|
||||
autoPlay
|
||||
muted
|
||||
loop
|
||||
playsInline
|
||||
className="w-full max-w-[440px] h-auto"
|
||||
/>
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { useState } from "react"
|
||||
import { AnimatePresence, motion } from "motion/react"
|
||||
import { Bot, Check, Monitor, Smartphone, Sparkles, type LucideIcon } from "lucide-react"
|
||||
import { Check, Monitor, Smartphone, type LucideIcon } from "lucide-react"
|
||||
|
||||
import { BrowserFrame, PhoneFrame } from "@/components/ui/device-mockups"
|
||||
import { Section } from "@/components/ui/section"
|
||||
import { SectionHeading } from "@/components/ui/section-heading"
|
||||
import { CONTROL_GAP, SectionHeading } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
|
||||
/** 3단계 이용 가이드 — 탭 전환식 GIF 시연 (데스크톱/모바일 목업). */
|
||||
@@ -17,21 +17,20 @@ export function HowItWorksDemo() {
|
||||
<Section id="how-it-works-demo" width="lg" bordered className="overflow-hidden">
|
||||
<SectionHeading
|
||||
align="center"
|
||||
className="mb-20"
|
||||
eyebrow="SERVICE DEMONSTRATION"
|
||||
eyebrow="How it Works"
|
||||
title="견적 생성부터 낙찰까지 한눈에 보기"
|
||||
description="복잡해 보이는 구매 과정이 어떻게 자동화되는지 실제 작동 화면(GIF)을 통해 쉽고 직관적으로 확인해 보세요."
|
||||
descriptionClassName="text-[17px] max-w-2xl"
|
||||
description="견적을 열고 협상이 끝나기까지, 실제 화면으로 보여드립니다."
|
||||
descriptionClassName="max-w-2xl"
|
||||
/>
|
||||
|
||||
{/* 탭 스위치 */}
|
||||
<div className="flex justify-center mb-16">
|
||||
<div className="p-1 bg-fill rounded-[14px] inline-flex flex-wrap justify-center gap-1">
|
||||
{/* 탭 스위치 — 비교 섹션 토글과 같은 간격 규칙(본문 쪽에 묶인다) */}
|
||||
<div className={`flex justify-center ${CONTROL_GAP}`}>
|
||||
<div className="p-1 bg-fill rounded-control inline-flex flex-wrap justify-center gap-1">
|
||||
{DEMO_TABS.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
onClick={() => setActiveKey(tab.key)}
|
||||
className={`px-5 py-2.5 rounded-[10px] text-xs sm:text-sm font-bold transition-all flex items-center gap-2 cursor-pointer ${
|
||||
className={`px-5 py-2.5 rounded-control text-xs sm:text-sm font-bold transition-all flex items-center gap-2 cursor-pointer ${
|
||||
activeKey === tab.key ? "bg-white text-primary" : "text-ink-soft hover:text-ink"
|
||||
}`}
|
||||
>
|
||||
@@ -54,10 +53,9 @@ export function HowItWorksDemo() {
|
||||
transition={{ duration: 0.4 }}
|
||||
className="space-y-6"
|
||||
>
|
||||
<div className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-bold ${activeTab.badge.className}`}>
|
||||
<activeTab.badge.icon className="w-3.5 h-3.5" />
|
||||
{activeTab.badge.label}
|
||||
</div>
|
||||
{/* 알약 배경 + 아이콘을 뺀 글자만의 라벨.
|
||||
레퍼런스 라벨은 11px/600/자간 normal 에 배경도 아이콘도 없다. */}
|
||||
<div className={`text-[11px] font-semibold ${activeTab.badge.className}`}>{activeTab.badge.label}</div>
|
||||
<Typography variant="heading">{activeTab.heading}</Typography>
|
||||
{activeTab.paragraphs.map((paragraph, idx) => (
|
||||
<Typography key={idx} variant="body">
|
||||
@@ -159,7 +157,7 @@ type DemoTab = {
|
||||
key: "create" | "negotiate" | "result"
|
||||
tabIcon: LucideIcon
|
||||
tabLabel: string
|
||||
badge: { icon: LucideIcon; label: string; className: string }
|
||||
badge: { label: string; className: string }
|
||||
checkClassName: string
|
||||
heading: React.ReactNode
|
||||
paragraphs: React.ReactNode[]
|
||||
@@ -183,19 +181,19 @@ const DEMO_TABS: DemoTab[] = [
|
||||
{
|
||||
key: "create",
|
||||
tabIcon: Monitor,
|
||||
tabLabel: "1단계: AI 견적 & 가이드 수립",
|
||||
badge: { icon: Sparkles, label: "구매 관리자 콘솔 (웹)", className: "bg-primary-soft text-primary" },
|
||||
tabLabel: "1. 견적 · 기준 수립",
|
||||
badge: { label: "구매 관리자 콘솔", className: "text-primary" },
|
||||
checkClassName: "text-primary",
|
||||
heading: (
|
||||
<>
|
||||
엑셀 등록만으로 끝나는 <br />
|
||||
초정밀 가이드라인 자율 수립
|
||||
엑셀만 올리면 <br />
|
||||
목표 단가가 잡힙니다
|
||||
</>
|
||||
),
|
||||
paragraphs: [
|
||||
<>
|
||||
품목명과 시중 시장 가격을 입력하면, negotium이 <b>인터넷 최저가(LPS)</b> 데이터를 상시 반영해{" "}
|
||||
<b className="text-primary">시장 바닥값을 쥐고 시작합니다.</b>
|
||||
품목명과 시중 시장 가격을 입력하면, 네고시움이 <b>인터넷 최저가(LPS)</b> 데이터를 상시 반영해{" "}
|
||||
<b className="text-primary">시장 최저가를 기준으로 시작합니다.</b>
|
||||
</>,
|
||||
<>
|
||||
시중 최저가와 매입 이력, 목표 마진율을 종합해 — 사내 마진은 지키면서 공급사가 받아들일 수 있는{" "}
|
||||
@@ -211,7 +209,7 @@ const DEMO_TABS: DemoTab[] = [
|
||||
gifAlt: "견적 생성 가이드라인 수립 시연",
|
||||
fallback: {
|
||||
icon: Monitor,
|
||||
iconWrapClassName: "w-14 h-14 bg-primary-soft rounded-2xl text-primary",
|
||||
iconWrapClassName: "w-14 h-14 bg-primary-soft rounded-card text-primary",
|
||||
codeClassName: "bg-white text-primary",
|
||||
title: "견적 생성 시연 GIF 공간",
|
||||
hint: "실제 기동 GIF를 배치하시면 이 영역에 자동으로 재생됩니다.",
|
||||
@@ -220,8 +218,8 @@ const DEMO_TABS: DemoTab[] = [
|
||||
{
|
||||
key: "negotiate",
|
||||
tabIcon: Smartphone,
|
||||
tabLabel: "2단계: AI 자동 밀당 협상",
|
||||
badge: { icon: Bot, label: "협력사 협상 포털 (웹·모바일)", className: "bg-positive-soft border border-positive/15 text-positive" },
|
||||
tabLabel: "2. 협력사별 1:1 협상",
|
||||
badge: { label: "협력사 협상 포털", className: "text-positive" },
|
||||
checkClassName: "text-positive",
|
||||
heading: (
|
||||
<>
|
||||
@@ -234,14 +232,18 @@ const DEMO_TABS: DemoTab[] = [
|
||||
각 파트너사 담당자는 초대 메일로 <b>비대면 협상 모바일 포털</b>에 접속해, 언제든 단가를 조율합니다.
|
||||
</>,
|
||||
<>
|
||||
단순 마진 깎기가 아닙니다. 봇은 준비된 협상 카드를 상황에 맞게 꺼내, 파트너사의 자발적인 마진 타협을 부드럽게
|
||||
단순히 깎는 게 아닙니다. 에이전트는 준비된 협상 카드를 상황에 맞게 꺼내, 협력사가 받아들일 조건을
|
||||
이끌어냅니다.
|
||||
</>,
|
||||
],
|
||||
checks: ["1:1 비대면 협상 포털 제공", "불필요한 실랑이를 예방하여 파트너십 보호"],
|
||||
checks: ["협력사별 1:1 비대면 협상 포털", "같은 기준으로 응대해 관계 부담 없음"],
|
||||
mockup: "phone",
|
||||
/* mp4 를 붙이기 전까지 이 탭만 1.7MB GIF(390x780)를 내려받고 있었다. 같은 내용의
|
||||
mp4 가 저장소에 있는데 참조가 빠져 있었다 — 786K, 540x1080 으로 더 가볍고 더 크다.
|
||||
(원본 캡쳐가 좌우로 잘려 문장이 끊기는 문제는 남아 있다. 재촬영이 필요하다.) */
|
||||
gif: "/gifs/negotiation.gif",
|
||||
gifAlt: "AI 모바일 자동 협상 시연",
|
||||
video: "/gifs/negotiation.mp4",
|
||||
gifAlt: "협력사 포털 모바일 협상 화면",
|
||||
fallback: {
|
||||
icon: Smartphone,
|
||||
iconWrapClassName: "w-12 h-12 bg-positive-soft border border-positive/15 rounded-full text-positive",
|
||||
@@ -254,7 +256,7 @@ const DEMO_TABS: DemoTab[] = [
|
||||
key: "result",
|
||||
tabIcon: Monitor,
|
||||
tabLabel: "3단계: AI 협상 결과 확인",
|
||||
badge: { icon: Monitor, label: "구매 관리자 콘솔 (웹)", className: "bg-accent-soft border border-accent/15 text-accent" },
|
||||
badge: { label: "구매 관리자 콘솔", className: "text-accent" },
|
||||
checkClassName: "text-accent",
|
||||
heading: (
|
||||
<>
|
||||
@@ -280,7 +282,7 @@ const DEMO_TABS: DemoTab[] = [
|
||||
gifAlt: "협상 결과 분석 대시보드 시연",
|
||||
fallback: {
|
||||
icon: Monitor,
|
||||
iconWrapClassName: "w-14 h-14 bg-accent-soft rounded-2xl text-accent",
|
||||
iconWrapClassName: "w-14 h-14 bg-accent-soft rounded-card text-accent",
|
||||
codeClassName: "bg-white text-accent",
|
||||
title: "협상 결과 확인 시연 GIF 공간",
|
||||
hint: "결과 보고 대시보드 기동 GIF를 배치하시면 이 영역에 자동으로 재생됩니다.",
|
||||
|
||||
@@ -1,324 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { AnimatePresence, motion } from "motion/react"
|
||||
import { Bot, Handshake, ShieldCheck } from "lucide-react"
|
||||
|
||||
import { PriceSparkline } from "@/components/ui/price-sparkline"
|
||||
import { SlateRenderer } from "@/components/ui/slate-renderer"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { EASE_OUT_EXPO } from "@/lib/motion"
|
||||
import type { DialogueStep } from "@/types"
|
||||
|
||||
/** 스크롤 연동 sticky 협상 데모 — 스크롤 진행률에 따라 대화가 쌓이고 단가가 내려간다. */
|
||||
export function NegotiationConsole() {
|
||||
// -1 = 아직 섹션 진입 전(온보딩 가이드 표시)
|
||||
const [activeStep, setActiveStep] = useState(-1)
|
||||
const [animatedPrice, setAnimatedPrice] = useState(1200000)
|
||||
const sectionRef = useRef<HTMLDivElement>(null)
|
||||
const chatContainerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// 섹션 내 스크롤 진행률 → 대화 스텝 매핑
|
||||
useEffect(() => {
|
||||
const handleScroll = () => {
|
||||
if (!sectionRef.current) return
|
||||
const rect = sectionRef.current.getBoundingClientRect()
|
||||
const totalScrollable = rect.height - window.innerHeight
|
||||
if (totalScrollable <= 0) return
|
||||
|
||||
const scrolled = -rect.top
|
||||
if (scrolled < 0) {
|
||||
setActiveStep(-1)
|
||||
return
|
||||
}
|
||||
|
||||
const clampedRatio = Math.max(0, Math.min(scrolled / totalScrollable, 0.99))
|
||||
setActiveStep(Math.floor(clampedRatio * NEGOTIATION_STEPS.length))
|
||||
}
|
||||
|
||||
window.addEventListener("scroll", handleScroll, { passive: true })
|
||||
handleScroll()
|
||||
return () => window.removeEventListener("scroll", handleScroll)
|
||||
}, [])
|
||||
|
||||
// 단가 오도미터 애니메이션 (500ms ease-out)
|
||||
useEffect(() => {
|
||||
const targetPrice = activeStep === -1 ? 1200000 : NEGOTIATION_STEPS[activeStep].price
|
||||
if (animatedPrice === targetPrice) return
|
||||
|
||||
const start = animatedPrice
|
||||
const duration = 500
|
||||
const startTime = performance.now()
|
||||
|
||||
const animate = (currentTime: number) => {
|
||||
const progress = Math.min((currentTime - startTime) / duration, 1)
|
||||
const easeProgress = progress * (2 - progress)
|
||||
setAnimatedPrice(Math.round(start + (targetPrice - start) * easeProgress))
|
||||
if (progress < 1) requestAnimationFrame(animate)
|
||||
}
|
||||
|
||||
requestAnimationFrame(animate)
|
||||
}, [activeStep])
|
||||
|
||||
// 새 말풍선이 붙으면 채팅 영역을 바닥으로 스크롤
|
||||
useEffect(() => {
|
||||
chatContainerRef.current?.scrollTo({ top: chatContainerRef.current.scrollHeight, behavior: "smooth" })
|
||||
}, [activeStep])
|
||||
|
||||
return (
|
||||
<section
|
||||
id="how-it-works"
|
||||
ref={sectionRef}
|
||||
className="relative bg-surface text-ink w-full font-sans border-t border-line h-[240vh] md:h-[280vh]"
|
||||
>
|
||||
<div className="sticky top-0 h-screen flex items-center justify-center w-full overflow-hidden px-6 md:px-8">
|
||||
{/* 섹션 헤딩 — sticky 상단 고정 (모바일은 공간상 생략) */}
|
||||
<div className="absolute top-24 left-0 right-0 text-center hidden md:block">
|
||||
<Typography variant="eyebrow" className="block">
|
||||
Live Replay
|
||||
</Typography>
|
||||
<Typography variant="heading" as="h2" className="mt-1">
|
||||
봇은 물러서지 않습니다
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="max-w-4xl mx-auto grid grid-cols-1 md:grid-cols-12 gap-12 md:gap-16 items-center w-full">
|
||||
{/* 좌: 실시간 단가 패널 */}
|
||||
<div className="md:col-span-5 flex flex-col justify-center space-y-6 text-center md:text-left">
|
||||
<div>
|
||||
<span className="text-[11px] font-bold text-ink-muted uppercase tracking-wider block mb-1">실시간 협상 단가</span>
|
||||
<div className="flex items-baseline gap-1.5 justify-center md:justify-start">
|
||||
<span className="text-3xl font-bold text-primary">₩</span>
|
||||
<span className="text-4xl md:text-5xl font-black tracking-tight text-primary">
|
||||
{animatedPrice.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
{/* 시작가 대비 누적 절감 델타 — 높이 고정으로 레이아웃 점프 방지 */}
|
||||
<div className="h-6 mt-1.5">
|
||||
{animatedPrice < START_PRICE && (
|
||||
<span className="inline-flex items-baseline gap-1.5 text-positive font-bold text-sm">
|
||||
▼ {(START_PRICE - animatedPrice).toLocaleString()}원
|
||||
<span className="text-xs font-semibold">
|
||||
(−{(((START_PRICE - animatedPrice) / START_PRICE) * 100).toFixed(1)}%)
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 계단식 하락 스파크라인 + 목표가 기준선 */}
|
||||
<div>
|
||||
<PriceSparkline
|
||||
prices={NEGOTIATION_STEPS.map((step) => step.price)}
|
||||
targetPrice={TARGET_PRICE}
|
||||
progress={activeStep < 0 ? 0 : (activeStep + 1) / NEGOTIATION_STEPS.length}
|
||||
/>
|
||||
<div className="flex justify-between mt-2">
|
||||
<Typography variant="micro">시작가 {START_PRICE.toLocaleString()}</Typography>
|
||||
<Typography variant="micro" className="text-primary">
|
||||
목표가 {TARGET_PRICE.toLocaleString()}
|
||||
</Typography>
|
||||
</div>
|
||||
<Typography variant="caption" className="mt-3">
|
||||
실제 협상 화면을 재구성한 데모입니다.
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="h-10">
|
||||
<AnimatePresence mode="wait">
|
||||
{activeStep !== -1 && NEGOTIATION_STEPS[activeStep]?.badge && (
|
||||
<motion.div
|
||||
key={NEGOTIATION_STEPS[activeStep].badge}
|
||||
initial={{ scale: 0.95, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
exit={{ scale: 0.95, opacity: 0 }}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-positive-soft text-positive border border-positive/15 text-xs font-bold"
|
||||
>
|
||||
<ShieldCheck className="w-4 h-4 shrink-0" />
|
||||
{NEGOTIATION_STEPS[activeStep].badge}
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 우: 대화 말풍선 (봇 좌 / 파트너 우) */}
|
||||
<div className="md:col-span-7 flex flex-col justify-end space-y-5 h-[340px] md:h-[420px] relative overflow-hidden">
|
||||
<div className="absolute inset-0 bg-gradient-to-b from-surface via-transparent to-transparent h-12 pointer-events-none z-10" />
|
||||
|
||||
<div
|
||||
ref={chatContainerRef}
|
||||
className="flex flex-col gap-5 overflow-y-auto pr-1 scrollbar-none w-full h-full justify-center"
|
||||
>
|
||||
<AnimatePresence mode="wait" initial={false}>
|
||||
{activeStep === -1 ? (
|
||||
<motion.div
|
||||
key="onboarding-guide"
|
||||
initial={{ opacity: 0, y: 15, scale: 0.97 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: -15, scale: 0.97 }}
|
||||
transition={{ duration: 0.4 }}
|
||||
className="flex flex-col items-center justify-center text-center p-8 border border-dashed border-line-strong rounded-[28px] bg-white shadow-[0_4px_20px_rgba(0,0,0,0.01)] max-w-md mx-auto"
|
||||
>
|
||||
<div className="w-12 h-12 rounded-full bg-primary-soft flex items-center justify-center text-primary mb-4">
|
||||
<Bot className="w-6 h-6 animate-pulse" />
|
||||
</div>
|
||||
<h3 className="text-base font-bold text-ink mb-1.5">실시간 AI 협상 대화</h3>
|
||||
<p className="text-xs text-ink-soft font-semibold leading-relaxed break-keep">
|
||||
화면을 스크롤하면 실시간 단가 조율 대화가 시작됩니다.
|
||||
</p>
|
||||
<div className="mt-4 flex items-center gap-1.5 text-[11px] font-bold text-primary animate-bounce">
|
||||
<span>마우스 휠 스크롤하기</span>
|
||||
<span>↓</span>
|
||||
</div>
|
||||
</motion.div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-5 w-full mt-auto">
|
||||
{NEGOTIATION_STEPS.slice(0, activeStep + 1).map((item, idx) => {
|
||||
const isBot = item.editorNodes[0].sender === "bot"
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key={idx}
|
||||
initial={{ opacity: 0, y: 15, scale: 0.97 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: -10, scale: 0.97 }}
|
||||
transition={{ duration: 0.4, ease: EASE_OUT_EXPO }}
|
||||
className={`flex flex-col ${isBot ? "items-start" : "items-end"} w-full`}
|
||||
>
|
||||
<div className={`flex items-center gap-1.5 mb-1 text-[11px] font-bold text-ink-muted ${isBot ? "" : "flex-row-reverse"}`}>
|
||||
<span className={`flex items-center gap-1 ${isBot ? "text-primary" : "text-ink-soft"}`}>
|
||||
{isBot ? (
|
||||
<>
|
||||
<Bot className="w-3.5 h-3.5" />
|
||||
<span>NEGOTIUM BOT</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Handshake className="w-3.5 h-3.5" />
|
||||
<span>PARTNER</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`max-w-[85%] rounded-[20px] p-4 text-sm leading-relaxed font-semibold shadow-[0_2px_8px_rgba(0,0,0,0.02)] transition-all duration-300 ${
|
||||
isBot ? "bg-primary-soft text-ink rounded-tl-none" : "bg-white text-ink rounded-tr-none"
|
||||
}`}
|
||||
>
|
||||
<SlateRenderer nodes={item.editorNodes} />
|
||||
</div>
|
||||
</motion.div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// 시작가(첫 제시가)·목표가 — 좌측 패널 델타·스파크라인 기준값
|
||||
const START_PRICE = 1200000
|
||||
const TARGET_PRICE = 1080000
|
||||
|
||||
// 데모 대화 시나리오 — 1,200,000원 제시에서 1,050,000원 낙찰까지 6스텝
|
||||
const NEGOTIATION_STEPS: DialogueStep[] = [
|
||||
{
|
||||
step: 1,
|
||||
price: 1200000,
|
||||
editorNodes: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
sender: 'supplier',
|
||||
children: [
|
||||
{ text: '협력사', bold: true },
|
||||
{ text: ' : ' },
|
||||
{ text: '현재 글로벌 원재료 상승 요인으로 제안할 수 있는 최선의 단가는 1,200,000원입니다. 이 이하로는 마진 확보가 어렵습니다.' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 2,
|
||||
price: 1150000,
|
||||
editorNodes: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
sender: 'bot',
|
||||
children: [
|
||||
{ text: 'AI 흥정 봇', bold: true },
|
||||
{ text: ' : ' },
|
||||
{ text: '제시해주신 1,200,000원은 당사 타 유사 품목 이력 및 시중 원가 인덱스 데이터 대비 약 8.3% 높게 책정되어 있습니다. ', italic: true },
|
||||
{ text: '상호 호혜적 장기 계약 체결을 전제로 조율가 범위를 반영해 제안해 드립니다.', code: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 3,
|
||||
price: 1150000,
|
||||
editorNodes: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
sender: 'supplier',
|
||||
children: [
|
||||
{ text: '협력사', bold: true },
|
||||
{ text: ' : ' },
|
||||
{ text: '제조 공정상 급격한 인하는 무리가 있으나, 상생 협력 차원에서 1,150,000원까지는 즉시 조정해 드릴 용의가 있습니다.' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 4,
|
||||
price: 1080000,
|
||||
editorNodes: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
sender: 'bot',
|
||||
children: [
|
||||
{ text: 'AI 흥정 봇', bold: true },
|
||||
{ text: ' : ' },
|
||||
{ text: '적극적인 협조에 감사드립니다. 만약 연간 최소 발주 수량을 보증하고 공급망 일정을 다소 유연화해주신다면, 목표가인 1,080,000원 선까지 맞출 수 있을까요?', italic: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 5,
|
||||
price: 1050000,
|
||||
editorNodes: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
sender: 'supplier',
|
||||
children: [
|
||||
{ text: '협력사', bold: true },
|
||||
{ text: ' : ' },
|
||||
{ text: '좋습니다. 제안하신 연간 개런티 확보 및 대금 현금 결제 기한 단축을 승인해 주시는 조건으로, ' },
|
||||
{ text: '최종 조율가 1,050,000원으로 맞춰서 계약을 체결하겠습니다.', bold: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 6,
|
||||
price: 1050000,
|
||||
badge: '낙찰 성공 · 12.5% 예산 절감',
|
||||
editorNodes: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
sender: 'bot',
|
||||
children: [
|
||||
{ text: 'AI 흥정 봇', bold: true },
|
||||
{ text: ' : ' },
|
||||
{ text: '최종 합의 접수 완료 — 가이드 상한가(1,200,000원) 대비 합의 낙찰가 1,050,000원으로 최종 계약 승인 처리 완료되었습니다. ', bold: true },
|
||||
{ text: '본 흥정 마일스톤 및 단가 타결 히스토리는 사내 투명성 보증을 위해 보존 기록됩니다.', code: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
@@ -0,0 +1,466 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { motion } from "motion/react"
|
||||
import { ArrowRight, RotateCcw } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Section } from "@/components/ui/section"
|
||||
import { SectionHeading } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { EASE_OUT_EXPO } from "@/lib/motion"
|
||||
import {
|
||||
DEMO_ITEMS,
|
||||
MAX_CARDS,
|
||||
respondToOffer,
|
||||
round10,
|
||||
savings,
|
||||
simulateBuyerRun,
|
||||
won,
|
||||
type DemoItem,
|
||||
type Outcome,
|
||||
type Role,
|
||||
type Turn,
|
||||
} from "@/lib/negotiation-sim"
|
||||
|
||||
type Step = "role" | "play"
|
||||
|
||||
/**
|
||||
* 랜딩 인터랙티브 협상 데모.
|
||||
*
|
||||
* 스크롤로 재생만 되던 기존 콘솔을 대체한다. 구경이 아니라 사용자가 한쪽을 맡아
|
||||
* 실제로 값을 제시하고 판정을 받는다 — 광고로 들어온 잠재고객이 제품을 만져보는 자리다.
|
||||
*
|
||||
* 판정 규칙은 lib/negotiation-sim 에 있고 이 파일은 화면만 맡는다.
|
||||
*/
|
||||
export function NegotiationDemo() {
|
||||
const [step, setStep] = useState<Step>("role")
|
||||
const [role, setRole] = useState<Role>("seller")
|
||||
const [item, setItem] = useState<DemoItem>(DEMO_ITEMS[0])
|
||||
const [turns, setTurns] = useState<Turn[]>([])
|
||||
const [cardsUsed, setCardsUsed] = useState(0)
|
||||
const [outcome, setOutcome] = useState<Outcome>("running")
|
||||
const [offer, setOffer] = useState(DEMO_ITEMS[0].listPrice)
|
||||
/* 입력란의 원문. offer 와 따로 두는 이유는 타이핑 도중 상태다 — 숫자 하나로 묶으면
|
||||
"1" 을 치는 순간 범위 밖이라 튕겨서 사용자와 싸우게 된다. 확정은 blur/Enter 에서 한다. */
|
||||
const [offerText, setOfferText] = useState(won(DEMO_ITEMS[0].listPrice))
|
||||
const [finalPrice, setFinalPrice] = useState(DEMO_ITEMS[0].listPrice)
|
||||
|
||||
const logRef = useRef<HTMLDivElement>(null)
|
||||
const timers = useRef<number[]>([])
|
||||
|
||||
// 재생 중인 buyer 시나리오 타이머는 리셋·언마운트 때 반드시 걷어낸다.
|
||||
const clearTimers = () => {
|
||||
timers.current.forEach(clearTimeout)
|
||||
timers.current = []
|
||||
}
|
||||
useEffect(() => clearTimers, [])
|
||||
|
||||
/** 역할 선택 화면으로 완전히 되돌린다. 같은 역할로만 다시 하면 나머지 절반은
|
||||
영영 안 보게 되므로, 다시 해보기는 역할부터 고르게 하는 게 맞다. */
|
||||
const restart = () => {
|
||||
reset()
|
||||
setStep("role")
|
||||
}
|
||||
|
||||
const reset = (nextItem = item, nextRole = role) => {
|
||||
clearTimers()
|
||||
setTurns([])
|
||||
setCardsUsed(0)
|
||||
setOutcome("running")
|
||||
setFinalPrice(nextItem.listPrice)
|
||||
const start = nextRole === "seller" ? nextItem.listPrice : nextItem.marketLow
|
||||
setOffer(start)
|
||||
setOfferText(won(start))
|
||||
}
|
||||
|
||||
const pickRole = (r: Role) => {
|
||||
setRole(r)
|
||||
reset(item, r)
|
||||
setStep("play")
|
||||
}
|
||||
|
||||
const pickItem = (it: DemoItem) => {
|
||||
setItem(it)
|
||||
reset(it, role)
|
||||
}
|
||||
|
||||
// 새 말풍선이 붙으면 기록을 바닥으로 붙인다.
|
||||
useEffect(() => {
|
||||
logRef.current?.scrollTo({ top: logRef.current.scrollHeight, behavior: "smooth" })
|
||||
}, [turns])
|
||||
|
||||
/** seller — 사용자가 공급사가 되어 값을 제시하고 에이전트가 응수한다. */
|
||||
const submitOffer = () => {
|
||||
if (outcome !== "running") return
|
||||
const priced = round10(offer)
|
||||
const mine: Turn = { id: turns.length, side: "counterpart", text: `${won(priced)}원까지는 맞춰드릴 수 있습니다.`, price: priced }
|
||||
setTurns((prev) => [...prev, mine])
|
||||
|
||||
const res = respondToOffer(item, priced, cardsUsed)
|
||||
const id = window.setTimeout(() => {
|
||||
setTurns((prev) => [...prev, { id: prev.length, side: "agent", text: res.text, price: res.price }])
|
||||
setFinalPrice(res.outcome === "award" ? priced : res.price)
|
||||
setOutcome(res.outcome)
|
||||
if (res.outcome === "running") {
|
||||
setCardsUsed((c) => c + 1)
|
||||
// 에이전트가 부른 값에서 다시 시작. 입력란도 같이 갱신해야 슬라이더와 숫자가 어긋나지 않는다.
|
||||
setOffer(res.price)
|
||||
setOfferText(won(res.price))
|
||||
}
|
||||
}, 620)
|
||||
timers.current.push(id)
|
||||
}
|
||||
|
||||
/** buyer — 목표가만 정하면 에이전트가 알아서 붙는 걸 지켜본다. */
|
||||
const runBuyer = () => {
|
||||
if (turns.length > 0) return
|
||||
const target = round10(offer)
|
||||
const run = simulateBuyerRun(item, target)
|
||||
run.turns.forEach((turn, i) => {
|
||||
const id = window.setTimeout(() => {
|
||||
setTurns((prev) => [...prev, turn])
|
||||
if (turn.price) setFinalPrice(turn.price)
|
||||
if (i === run.turns.length - 1) setOutcome(run.outcome)
|
||||
}, 500 + i * 900)
|
||||
timers.current.push(id)
|
||||
})
|
||||
}
|
||||
|
||||
const done = outcome !== "running"
|
||||
const { amount, rate } = savings(item, finalPrice)
|
||||
const sliderMin = role === "seller" ? round10(item.anchor * 0.94) : round10(item.anchor * 0.94)
|
||||
const sliderMax = role === "seller" ? item.listPrice : item.marketLow
|
||||
|
||||
/* 협상이 시작된 뒤 구매자는 목표가를 못 바꾼다 — 목표가를 정하고 위임하는 게 제품의 전제다.
|
||||
공급사는 카드가 남아 있는 한 계속 제시할 수 있다. */
|
||||
const inputLocked = role === "buyer" && turns.length > 0
|
||||
|
||||
/* 추천가는 시뮬레이터가 실제로 쓰는 수치에서 가져온다. 지어낸 숫자를 추천이라 부르면
|
||||
사용자가 그대로 넣었을 때 결과가 설명되지 않는다. */
|
||||
const recommended = role === "seller" ? item.marketLow : item.anchor
|
||||
const recommendReason =
|
||||
role === "seller"
|
||||
? `같은 사양 시장 최저가 선입니다. 여기서부터 에이전트가 근거를 들고 응수합니다.`
|
||||
: `결렬 없이 도달 가능한 최저선입니다. 더 낮추면 협상이 성사되지 않습니다.`
|
||||
|
||||
/** 슬라이더·직접입력·추천적용이 모두 거쳐가는 단일 확정 경로. 범위로 당기고 10원 단위로 맞춘다. */
|
||||
const commitOffer = (raw: number) => {
|
||||
if (inputLocked) return
|
||||
const next = Number.isFinite(raw) && raw > 0 ? round10(Math.min(sliderMax, Math.max(sliderMin, raw))) : offer
|
||||
setOffer(next)
|
||||
/* 확정된 값은 콤마를 넣어 보여준다 — 화면의 다른 금액이 전부 won() 이라
|
||||
여기만 1018800 으로 나오면 같은 값으로 안 읽힌다. 타이핑 중에는 숫자만 남긴다. */
|
||||
setOfferText(won(next))
|
||||
}
|
||||
|
||||
return (
|
||||
<Section id="how-it-works" bg="stage" width="lg">
|
||||
{/* 머리는 손으로 짜지 않고 SectionHeading 을 쓴다. 예전엔 여기서 직접 조판하느라
|
||||
아이브로우 간격만 20px(다른 섹션은 12px)이었다 — 프리미티브를 우회하면
|
||||
같은 관계에 두 번째 값이 생긴다. */}
|
||||
{/* 두 문장은 의미 단위가 다르므로 줄을 명시적으로 나눈다.
|
||||
자동 줄바꿈에 맡기면 어절이 어색하게 끊긴다.
|
||||
|
||||
예전 카피는 "에이전트는 정해진 기준을 벗어나지 않습니다" 였다. FAQ 2번
|
||||
("에이전트가 우리 기준을 벗어나 합의해 버리면요?")을 헤드라인으로 끌어올린
|
||||
것이었는데, 아직 생기지도 않은 반론에 가장 비싼 한 줄을 쓰고 있었다.
|
||||
게다가 부정문이라 안 하는 일을 약속했다 — 체험을 권하는 자리에는 맞지 않는다.
|
||||
방어는 FAQ 에 그대로 남아 있으니 여기서는 능력을 말한다. */}
|
||||
<SectionHeading
|
||||
align="center"
|
||||
tone="stage"
|
||||
eyebrow="Try it Yourself"
|
||||
title={
|
||||
<>
|
||||
<span className="text-white">사용할수록 진화하는 에이전틱 협상,</span>
|
||||
<br />
|
||||
<span className="text-on-stage-soft/60">직접 경험해 보세요!</span>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* AnimatePresence mode="wait" 를 쓰지 않는다. 나가는 애니메이션이 끝나야 다음
|
||||
화면이 마운트돼서 클릭 후 0.8초가 빈다 — 역할 선택처럼 즉시 반응해야 하는
|
||||
전환에는 맞지 않는 도구다. 나가는 연출 없이 바로 갈아끼우고 짧게 들어온다. */}
|
||||
{step === "role" ? (
|
||||
<motion.div
|
||||
key="role"
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.28, ease: EASE_OUT_EXPO }}
|
||||
className="grid grid-cols-1 sm:grid-cols-2 gap-4"
|
||||
>
|
||||
<RoleCard
|
||||
title="공급사로 해보기"
|
||||
lead="직접 단가를 제시하면 에이전트가 응수합니다."
|
||||
detail="협상 카드 3장 안에서 단가가 어디까지 조율되는지 확인하실 수 있습니다."
|
||||
onClick={() => pickRole("seller")}
|
||||
/>
|
||||
<RoleCard
|
||||
title="구매 담당자로 해보기"
|
||||
lead="목표가만 정하면 에이전트가 협력사와 조율합니다."
|
||||
detail="기준을 벗어난 목표가를 설정했을 때의 처리 방식도 함께 확인하실 수 있습니다."
|
||||
onClick={() => pickRole("buyer")}
|
||||
/>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="play"
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.28, ease: EASE_OUT_EXPO }}
|
||||
/* 유리 패널로 띄운다. 컨트롤과 대화 로그가 섹션 배경 위에 그냥 얹혀 있으면
|
||||
무대와 같은 색이라 경계가 없고, 조작할 수 있는 영역인지 읽히지 않는다.
|
||||
재질은 무대 위 2차 CTA 와 같다 — 옅은 흰 채움 + backdrop-blur + 위쪽
|
||||
안쪽 하이라이트 + 아래로 깔리는 그림자. 화면 안에 재질이 두 종류면 따로 논다.
|
||||
테두리는 white/12 로 얕게 둔다. 이건 조작 요소가 아니라 면이라 버튼만큼
|
||||
세울 필요가 없고, 세우면 오히려 카드가 버튼처럼 보인다. */
|
||||
className={
|
||||
"rounded-card border border-white/12 bg-white/[0.06] " +
|
||||
"backdrop-blur-xl backdrop-saturate-150 " +
|
||||
"shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),0_24px_60px_-24px_rgba(3,6,15,0.9)] " +
|
||||
"p-6 sm:p-8 lg:p-10"
|
||||
}
|
||||
>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-12">
|
||||
{/* 좌 — 품목·컨트롤·현재가 */}
|
||||
<div className="lg:col-span-5 space-y-8">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{DEMO_ITEMS.map((it) => (
|
||||
<button
|
||||
key={it.id}
|
||||
type="button"
|
||||
onClick={() => pickItem(it)}
|
||||
className={`px-4 py-2 rounded-full text-[13px] font-semibold transition-colors ${
|
||||
it.id === item.id
|
||||
? "bg-white text-stage"
|
||||
: "bg-white/5 text-on-stage-soft/75 hover:bg-white/10 hover:text-white"
|
||||
}`}
|
||||
>
|
||||
{it.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-[13px] text-on-stage-soft/55 mb-2">{item.spec}</div>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-[24px] font-medium text-on-stage-soft/55">₩</span>
|
||||
<span className="text-[52px] md:text-[64px] font-extrabold tracking-[-0.045em] leading-none tabular-nums">
|
||||
{won(finalPrice)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-7 mt-2">
|
||||
{amount > 0 && (
|
||||
<span className="text-[15px] font-semibold text-counter">
|
||||
▼ {won(amount)}원 · {rate.toFixed(1)}%
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!done && (
|
||||
<div className="space-y-4">
|
||||
{/* 에이전트 추천가. 값을 지어내지 않고 시뮬레이터가 실제로 쓰는 수치를 쓴다 —
|
||||
구매자는 anchor(결렬 없이 닿는 최저선, reachable = target >= anchor),
|
||||
공급사는 marketLow(에이전트가 응수할 때 인용하는 값). 추천만 하고
|
||||
확정은 사용자가 한다. 그게 이 데모가 보여줘야 할 관계다. */}
|
||||
<div className="flex items-center justify-between gap-3 rounded-control border border-primary-on-stage/25 bg-primary-on-stage/10 px-4 py-3">
|
||||
<div className="min-w-0">
|
||||
<div className="text-[12px] font-semibold text-primary-on-stage mb-0.5">에이전트 추천</div>
|
||||
<div className="text-[13px] text-on-stage-soft/75 break-keep">{recommendReason}</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => commitOffer(recommended)}
|
||||
disabled={inputLocked}
|
||||
className="shrink-0 rounded-control bg-primary-on-stage/20 hover:bg-primary-on-stage/30 px-3 py-2 text-[13px] font-bold tabular-nums text-white transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
{won(recommended)}원 적용
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-baseline justify-between">
|
||||
<label htmlFor="nego-offer" className="text-[14px] font-medium text-on-stage-soft/85">
|
||||
{role === "seller" ? "제시 단가" : "목표 단가"}
|
||||
</label>
|
||||
{/* 직접 입력. 슬라이더만 두면 정확한 값을 못 넣는다 — 실제 구매 담당자는
|
||||
"얼마까지"라는 숫자를 이미 들고 온다. 타이핑 중에는 clamp 하지 않고
|
||||
blur/Enter 에서 확정한다. 입력 즉시 범위로 당기면 손가락과 싸운다. */}
|
||||
<div className="flex items-baseline gap-1">
|
||||
<input
|
||||
id="nego-offer-text"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
aria-label={role === "seller" ? "제시 단가 직접 입력" : "목표 단가 직접 입력"}
|
||||
value={offerText}
|
||||
onChange={(e) => setOfferText(e.target.value.replace(/[^\d]/g, ""))}
|
||||
onBlur={() => commitOffer(Number(offerText.replace(/[^\d]/g, "")))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault()
|
||||
commitOffer(Number(offerText.replace(/[^\d]/g, "")))
|
||||
}
|
||||
}}
|
||||
disabled={inputLocked}
|
||||
className="w-32 bg-transparent border-0 border-b-2 border-stage-line focus:border-primary-on-stage hover:border-on-stage-muted rounded-none px-0 py-1 text-right text-[18px] font-bold tabular-nums text-white outline-none transition-colors disabled:opacity-40"
|
||||
/>
|
||||
<span className="text-[15px] font-semibold text-on-stage-soft/70">원</span>
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
id="nego-offer"
|
||||
type="range"
|
||||
aria-label={role === "seller" ? "제시 단가 조절" : "목표 단가 조절"}
|
||||
min={sliderMin}
|
||||
max={sliderMax}
|
||||
step={10_000}
|
||||
value={Math.min(sliderMax, Math.max(sliderMin, offer))}
|
||||
onChange={(e) => commitOffer(Number(e.target.value))}
|
||||
disabled={inputLocked}
|
||||
className="w-full accent-primary disabled:opacity-40"
|
||||
/>
|
||||
<div className="flex justify-between text-[12px] text-on-stage-soft/45">
|
||||
<span>{won(sliderMin)}</span>
|
||||
<span>{won(sliderMax)}</span>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="stage"
|
||||
size="lg"
|
||||
className="w-full"
|
||||
onClick={role === "seller" ? submitOffer : runBuyer}
|
||||
disabled={inputLocked}
|
||||
>
|
||||
{role === "seller" ? "이 값으로 제시하기" : "협상 시작"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{role === "seller" && (
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-[13px] text-on-stage-soft/55">협상 카드</span>
|
||||
<div className="flex gap-1.5">
|
||||
{Array.from({ length: MAX_CARDS }, (_, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className={`w-7 h-1.5 rounded-full ${i < MAX_CARDS - cardsUsed ? "bg-primary-on-stage" : "bg-white/15"}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 우 — 협상 기록 */}
|
||||
<div className="lg:col-span-7">
|
||||
<div
|
||||
ref={logRef}
|
||||
className="h-[360px] md:h-[440px] overflow-y-auto scrollbar-none flex flex-col gap-4 pr-1"
|
||||
>
|
||||
{turns.length === 0 && (
|
||||
<div className="m-auto text-center text-[15px] text-on-stage-soft/45 max-w-xs break-keep">
|
||||
{role === "seller"
|
||||
? "단가를 정해 제시하면 에이전트가 근거와 함께 응수합니다."
|
||||
: "목표가를 정하고 협상을 시작하면 턴마다 재생됩니다."}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{turns.map((turn) => (
|
||||
<motion.div
|
||||
key={turn.id}
|
||||
initial={{ opacity: 0, y: 14 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.35, ease: EASE_OUT_EXPO }}
|
||||
className={`flex flex-col ${turn.side === "agent" ? "items-start" : "items-end"}`}
|
||||
>
|
||||
<span
|
||||
className={`text-[12px] font-semibold mb-1.5 ${
|
||||
turn.side === "agent" ? "text-primary-on-stage" : "text-counter"
|
||||
}`}
|
||||
>
|
||||
{turn.side === "agent" ? "협상 에이전트" : role === "seller" ? "나 (협력사)" : "협력사"}
|
||||
</span>
|
||||
<div
|
||||
className={`max-w-[88%] rounded-card px-5 py-4 text-[15px] leading-[1.6] break-keep ${
|
||||
turn.side === "agent"
|
||||
? "bg-primary text-white"
|
||||
: "bg-counter-surface text-counter border border-counter/20"
|
||||
}`}
|
||||
>
|
||||
{turn.text}
|
||||
</div>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{done && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.4, ease: EASE_OUT_EXPO }}
|
||||
className="mt-6 border-t border-stage-line pt-6"
|
||||
>
|
||||
<Typography variant="cardTitle" className="text-white mb-1.5">
|
||||
{outcome === "award"
|
||||
? `낙찰 · ${won(amount)}원 절감`
|
||||
: "개찰 — 낙찰자 미정으로 마감했습니다"}
|
||||
</Typography>
|
||||
<p className="text-[15px] text-on-stage-soft/70 leading-[1.6] break-keep mb-6">
|
||||
{outcome === "award"
|
||||
? `최초 제시가 ${won(item.listPrice)}원에서 ${rate.toFixed(1)}% 내려왔습니다. 실제 운영에서는 협력사 수만큼 이 협상이 동시에 진행됩니다.`
|
||||
: "기준을 벗어나는 값은 억지로 맞추지 않고 담당자에게 넘깁니다. 결렬이 아니라 사람이 판단할 자리를 남기는 것입니다."}
|
||||
</p>
|
||||
<div className="flex flex-col sm:flex-row gap-3">
|
||||
<Button href="#contact-section" variant="stage" size="lg" className="group">
|
||||
<span>우리 품목으로 상담받기</span>
|
||||
<ArrowRight className="w-4 h-4 transition-transform group-hover:translate-x-0.5" />
|
||||
</Button>
|
||||
<Button type="button" variant="stageGhost" size="lg" onClick={restart}>
|
||||
<RotateCcw className="w-4 h-4" />
|
||||
<span>역할 바꿔서 다시</span>
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
<p className="mt-12 text-center text-[13px] text-on-stage-soft/40">
|
||||
실제 판정 규칙(앵커링가·협상 카드 3장·개찰)을 그대로 옮긴 데모입니다. 금액은 예시입니다.
|
||||
</p>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
|
||||
function RoleCard({
|
||||
title,
|
||||
lead,
|
||||
detail,
|
||||
onClick,
|
||||
}: {
|
||||
title: string
|
||||
lead: string
|
||||
detail: string
|
||||
onClick: () => void
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="group text-left rounded-card border border-stage-line bg-white/[0.03] hover:bg-white/[0.07] hover:border-white/25 transition-colors p-8 md:p-10"
|
||||
>
|
||||
<Typography variant="heading" as="h3" className="text-white mb-3">
|
||||
{title}
|
||||
</Typography>
|
||||
<p className="text-[16px] text-on-stage-soft/85 leading-[1.6] break-keep mb-2">{lead}</p>
|
||||
<p className="text-[14px] text-on-stage-soft/55 leading-[1.6] break-keep">{detail}</p>
|
||||
<span className="mt-6 inline-flex items-center gap-1.5 text-[16px] font-semibold text-primary-on-stage">
|
||||
시작하기
|
||||
<ArrowRight className="w-4 h-4 transition-transform group-hover:translate-x-0.5" />
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -2,8 +2,9 @@ import { motion } from "motion/react"
|
||||
import { GitMerge, RefreshCw, Scale, type LucideIcon } from "lucide-react"
|
||||
|
||||
import { Section } from "@/components/ui/section"
|
||||
import { SectionHeading } from "@/components/ui/section-heading"
|
||||
import { HEADING_GAP, SectionHeading } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { OrbitRing } from "@/components/ui/orbit-ring"
|
||||
import { useFadeUp } from "@/lib/motion"
|
||||
|
||||
/** 강화학습 섹션 — 협상할수록 좋아진다는 3개 필러 카드. */
|
||||
@@ -11,22 +12,40 @@ export function Reinforcement() {
|
||||
const fadeUp = useFadeUp()
|
||||
|
||||
return (
|
||||
<Section id="reinforcement" bg="surface" bordered className="border-b border-line">
|
||||
<motion.div {...fadeUp} className="mb-20">
|
||||
<SectionHeading
|
||||
className="text-center md:text-left"
|
||||
eyebrow="REINFORCEMENT LEARNING"
|
||||
title="협상할수록, 더 좋은 조건으로"
|
||||
description={
|
||||
<>
|
||||
잘 깎는 노하우는 담당자 머릿속에만 남고, 성과는 그날의 감정과 컨디션에 흔들립니다. negotium은 진행된 모든 거래
|
||||
데이터와 파트너 거절 피드백을 <span className="font-bold text-primary">강화학습 기술</span>에 투입합니다.
|
||||
무턱대고 가격을 후려쳐 상대방의 반발만 사고 결렬로 치닫는 경직된 협상이 아니라, 파트너사가 충분히 받아들일 수
|
||||
있는 범위 내에서 최선의 마진율을 뽑아내도록 조율 페이스를 학습합니다.
|
||||
</>
|
||||
}
|
||||
descriptionClassName="mt-8 max-w-3xl"
|
||||
/>
|
||||
<Section id="reinforcement" bg="stage" width="lg">
|
||||
{/* 순환 링은 원래 히어로에 있었는데, 루프가 의미상 속하는 자리는 여기다 —
|
||||
"협상할수록 좋아진다"를 말하는 섹션이고, 히어로는 이미 세로 예산이 포화였다. */}
|
||||
{/* 머리가 그리드 셀 안에 들어가 있어서 여기만 gap="none" 이다. 그리드 아이템은
|
||||
독립 서식 문맥이라 마진이 상쇄되지 않고, 머리에 mb 를 걸면 items-center 의
|
||||
세로 정렬을 밀어버린다. 섹션 간격은 그리드 래퍼가 대신 진다. */}
|
||||
<motion.div {...fadeUp} className={`grid grid-cols-1 lg:grid-cols-12 gap-12 lg:gap-16 items-center ${HEADING_GAP}`}>
|
||||
<div className="lg:col-span-7">
|
||||
<SectionHeading
|
||||
className="text-center lg:text-left"
|
||||
gap="none"
|
||||
tone="stage"
|
||||
eyebrow="Reinforcement Learning"
|
||||
/* 쉼표에서 줄을 명시적으로 끊는다. break-keep + text-balance 에 맡기면
|
||||
두 줄 길이를 맞추려고 "협상할수록, 더 / 좋은 조건으로" 처럼 쉼표를
|
||||
넘어가서 끊어진다 — 조건절과 결과절이 한 줄에 섞여 의미가 흐려진다. */
|
||||
title={
|
||||
<>
|
||||
협상할수록,
|
||||
<br />더 좋은 조건으로
|
||||
</>
|
||||
}
|
||||
description={
|
||||
<>
|
||||
잘 깎는 요령은 담당자 머릿속에만 남고, 결과는 그날 컨디션에 흔들립니다. 네고시움은 지난 거래 기록과
|
||||
협력사가 거절한 지점을 <span className="font-semibold text-on-stage">강화학습</span>에 넣습니다. 어디까지가
|
||||
받아들여지는 선인지를 데이터로 익혀서, 결렬 없이 도달 가능한 최선을 찾아갑니다.
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="lg:col-span-5 flex justify-center">
|
||||
<OrbitRing className="w-[280px] md:w-[340px] h-auto" />
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
|
||||
@@ -44,15 +63,15 @@ function PillarCard({ pillar, delay }: { pillar: Pillar; delay: number }) {
|
||||
const fadeUp = useFadeUp(delay)
|
||||
|
||||
return (
|
||||
<motion.div {...fadeUp} className="bg-white p-8 rounded-[28px] flex flex-col justify-between h-[240px]">
|
||||
<div className="w-12 h-12 rounded-2xl bg-primary/5 text-primary flex items-center justify-center">
|
||||
<pillar.icon className="w-6 h-6" />
|
||||
<motion.div {...fadeUp} className="bg-stage-raised border border-stage-line p-8 rounded-card flex flex-col justify-between h-[240px]">
|
||||
<div className="w-11 h-11 rounded-control bg-primary/15 text-on-stage flex items-center justify-center">
|
||||
<pillar.icon className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<Typography variant="cardTitle" className="mb-2">
|
||||
<Typography variant="cardTitle" className="mb-2 text-on-stage">
|
||||
{pillar.title}
|
||||
</Typography>
|
||||
<Typography variant="caption" className="text-ink-soft">
|
||||
<Typography variant="caption" className="text-on-stage-soft">
|
||||
{pillar.description}
|
||||
</Typography>
|
||||
</div>
|
||||
@@ -68,12 +87,12 @@ const PILLARS: Pillar[] = [
|
||||
},
|
||||
{
|
||||
icon: RefreshCw,
|
||||
title: "지속적인 전략 최적화",
|
||||
description: "전략 강화 학습을 통해 기준선이 상승하고, 점진적으로 개선됩니다. 시간이 곧 협상력이 됩니다.",
|
||||
title: "쓸수록 올라가는 기준선",
|
||||
description: "협상이 쌓일수록 기준선이 올라갑니다. 운영 기간이 그대로 협상력이 됩니다.",
|
||||
},
|
||||
{
|
||||
icon: GitMerge,
|
||||
title: "낙찰 성사율 극대화",
|
||||
description: "무리하게 후려쳐 관계를 깨는 대신, 성사되는 선에서 최대한 끌어냅니다.",
|
||||
title: "결렬 없는 합의",
|
||||
description: "성사되지 않을 선까지 밀지 않습니다. 합의 가능한 범위 안에서 최선을 찾습니다.",
|
||||
},
|
||||
]
|
||||
@@ -1,158 +0,0 @@
|
||||
import { useState } from "react"
|
||||
import { ArrowRight, Clock, ShieldCheck } from "lucide-react"
|
||||
|
||||
import { RangeSlider } from "@/components/ui/range-slider"
|
||||
import { Section } from "@/components/ui/section"
|
||||
import { SectionHeading } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
|
||||
/** 도입 ROI 시뮬레이터 — 예산·협력사 수 슬라이더로 예상 절감액을 즉시 계산. */
|
||||
export function ROISimulator() {
|
||||
// 연간 총 구매 예산(억 원)
|
||||
const [budget, setBudget] = useState(50)
|
||||
// 관리 중인 협력사 수
|
||||
const [suppliers, setSuppliers] = useState(50)
|
||||
|
||||
// 보수적 절감율 2.8%~4.5% — 협력사가 많을수록 병렬 대안이 늘어 상향
|
||||
const savingRate = Math.min(0.045, 0.028 + (suppliers / 300) * 0.015)
|
||||
const estimatedSavingsValue = budget * savingRate
|
||||
|
||||
// 협력사당 왕복 흥정 수작업 절약분을 ~6.5시간으로 잡은 추산
|
||||
const savedHours = Math.round(suppliers * 6.5)
|
||||
|
||||
return (
|
||||
<Section id="benchmarks" width="lg" bordered className="border-b border-line">
|
||||
<SectionHeading
|
||||
align="center"
|
||||
className="mb-24"
|
||||
eyebrow="ROI SIMULATION"
|
||||
title={
|
||||
<>
|
||||
negotium 도입 시 <br />
|
||||
예상 절감액 확인하기
|
||||
</>
|
||||
}
|
||||
description={
|
||||
<>
|
||||
아직 실제 도입 실증 사례가 없는 신규 카테고리여도 신뢰할 수 있습니다. <br />
|
||||
연간 구매 예산과 공급사 수만 입력해 보수적인 시뮬레이션 성과를 즉시 시각화해 보세요.
|
||||
</>
|
||||
}
|
||||
descriptionClassName="mt-4 text-[17px] max-w-2xl"
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-12 gap-16 items-start">
|
||||
{/* 좌: 입력 슬라이더 */}
|
||||
<div className="lg:col-span-6 space-y-12">
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<label className="text-[16px] font-bold text-ink">연간 총 구매 예산</label>
|
||||
<span className="text-lg font-black text-primary font-mono">{formatCurrency(budget)}</span>
|
||||
</div>
|
||||
<Typography variant="caption">원자재, 부자재, 가공비, 운송비 등 협상에 연동할 총 연간 구매 규모입니다.</Typography>
|
||||
<div className="pt-2">
|
||||
<RangeSlider min={5} max={1000} step={5} value={budget} onChange={setBudget} />
|
||||
<div className="flex justify-between text-[11px] text-ink-faint font-bold pt-2">
|
||||
<span>5억 원</span>
|
||||
<span>500억 원</span>
|
||||
<span>1조 원</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<label className="text-[16px] font-bold text-ink">관리 중인 총 협력사 수</label>
|
||||
<span className="text-lg font-black text-primary font-mono">{suppliers}개사</span>
|
||||
</div>
|
||||
<Typography variant="caption">AI 봇 "밀당"이 동시에 일대일로 자동 조율할 잠재 공급사 수량입니다.</Typography>
|
||||
<div className="pt-2">
|
||||
<RangeSlider min={5} max={300} step={5} value={suppliers} onChange={setSuppliers} />
|
||||
<div className="flex justify-between text-[11px] text-ink-faint font-bold pt-2">
|
||||
<span>5개사</span>
|
||||
<span>150개사</span>
|
||||
<span>300개사</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 bg-surface p-5 rounded-2xl border border-line">
|
||||
<ShieldCheck className="w-5 h-5 text-positive flex-shrink-0 mt-0.5" />
|
||||
<Typography variant="caption" className="text-ink-soft">
|
||||
본 시뮬레이션은 글로벌 최저가 스캔(LPS) 시장 표준 및 다수 B2B 자율 협상 데이터의 보수적인 평균 수치(3.1% ~ 4.2%
|
||||
절감)를 적용하여 산정되었습니다. 실사 수준의 검증은 파일 연동을 통해 무상 지원됩니다.
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 우: 결과 지표 */}
|
||||
<div className="lg:col-span-6 lg:pl-10 space-y-12">
|
||||
<div className="space-y-3">
|
||||
<Typography variant="micro" className="text-primary block">
|
||||
ESTIMATED ANNUAL SAVINGS
|
||||
</Typography>
|
||||
<h3 className="text-sm font-semibold text-ink-muted">매년 절감 가능한 구매 원가 (보수적 추산)</h3>
|
||||
<div className="text-3xl sm:text-[44px] font-black text-primary font-mono tracking-tight leading-tight pt-1">
|
||||
{formatSavings(estimatedSavingsValue)}
|
||||
</div>
|
||||
<Typography variant="caption" className="text-ink-soft font-medium pt-1">
|
||||
사각지대에 방치되던 꼬리 거래(Tail Spend)의 상시 병렬 협상 및 인터넷 실시간 앵커가 시세 연동을 통해, 기존 수동
|
||||
흥정으로 놓치고 있던 원가 이탈을 완벽히 방어해냅니다.
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-line pt-8 space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Clock className="w-5 h-5 text-ink-muted" />
|
||||
<span className="text-xs font-bold text-ink-soft">
|
||||
연간 실무 단축 시간: <b className="text-ink font-mono text-sm ml-1">{savedHours.toLocaleString()}시간</b>
|
||||
</span>
|
||||
</div>
|
||||
<Typography variant="caption">
|
||||
메일 전송, 유선 흥정, 엑셀 취합 등에 낭비되던 소모적인 절차가 실시간 링크 전송과 AI 봇의 24시간 자율 대응으로
|
||||
완전히 생략되어 고부가가치 전략 구매 기획에 전념할 수 있습니다.
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-line pt-8 flex items-center justify-between">
|
||||
<div>
|
||||
<h4 className="text-xs font-bold text-ink">예상 도입 ROI 회수 기간</h4>
|
||||
<p className="text-[11px] text-ink-muted font-semibold mt-1">도입 즉시 마진 확보 개시</p>
|
||||
</div>
|
||||
<a
|
||||
href="#contact-section"
|
||||
className="inline-flex items-center gap-2 text-xs font-bold text-primary hover:gap-3 transition-all"
|
||||
>
|
||||
<span>무상 맞춤 검증 신청하기</span>
|
||||
<ArrowRight className="w-4 h-4" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
|
||||
/** 억 원 단위 → "50억 원" / "1조 200억 원" 표기 */
|
||||
function formatCurrency(val: number) {
|
||||
if (val >= 100) {
|
||||
const b = Math.floor(val / 100)
|
||||
const m = val % 100
|
||||
return m > 0 ? `${b}조 ${m}00억 원` : `${b}조 원`
|
||||
}
|
||||
return `${val}억 원`
|
||||
}
|
||||
|
||||
/** 억 원 단위 → "1억 5,500만 원" 표기 */
|
||||
function formatSavings(val: number) {
|
||||
const rawWon = val * 100000000
|
||||
if (rawWon >= 100000000) {
|
||||
const eonPart = Math.floor(rawWon / 100000000)
|
||||
const manPart = Math.floor((rawWon % 100000000) / 10000)
|
||||
if (manPart > 0) {
|
||||
return `${eonPart}억 ${manPart.toLocaleString()}만 원`
|
||||
}
|
||||
return `${eonPart}억 원`
|
||||
}
|
||||
return `${Math.floor(rawWon / 10000).toLocaleString()}만 원`
|
||||
}
|
||||
@@ -6,7 +6,9 @@ import { cn } from "@/lib/utils"
|
||||
// CTA 버튼 토큰. 랜딩의 CTA 는 전부 앵커 스크롤이라 href 를 주면 <a> 로 렌더한다
|
||||
// (SSG 특성상 하이드레이션 전에도 동작).
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 transition-all cursor-pointer disabled:opacity-50",
|
||||
/* transition-colors 로 좁힌다. transition-all 이면 헤더 CTA 가 무대↔라이트로 variant 를
|
||||
통째로 바꿀 때 배경이 투명에서 차오르며 플리커로 읽힌다. */
|
||||
"inline-flex items-center justify-center gap-2 transition-colors duration-200 cursor-pointer disabled:opacity-50",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
@@ -14,13 +16,40 @@ const buttonVariants = cva(
|
||||
secondary: "bg-fill hover:bg-fill-hover text-ink-soft hover:text-ink",
|
||||
// 밝은 배경 위 반투명 보조 버튼 (글라스 히어로)
|
||||
glass: "bg-white/70 hover:bg-white text-ink-soft hover:text-ink border border-white shadow-sm",
|
||||
// 다크 무대 위 1차 CTA
|
||||
stage: "bg-primary hover:bg-primary-deep text-white",
|
||||
/* 다크 무대 위 2차 CTA — 흰 알약.
|
||||
테두리를 stage-line(#1E2A52)으로 두면 안 된다. 그 색은 무대 바닥(#070E24) 위
|
||||
카드용이라, 방사형 광원부(#16205A)에 앉는 GNB 자리에서는 배경과 대비가 1.09:1 로
|
||||
사라진다. 채움도 없으면 남는 건 흰 글자뿐이라 옆 nav 링크와 구분되지 않는다.
|
||||
그래서 무대색 토큰이 아니라 흰색 알파로 잡는다 — 무대 어디에 놓여도 같이 성립한다.
|
||||
옅은 채움이 테두리보다 "누를 수 있는 것"을 더 강하게 전달하므로 둘 다 준다. */
|
||||
/* 유리(glassmorphism). 배경 영상이 비쳐 보이되 글자는 읽히는 상태를 만든다.
|
||||
구성은 넷이다 — 옅은 흰 채움, 뒤를 흐리는 backdrop-blur, 위쪽 1px 안쪽 하이라이트
|
||||
(유리 모서리에 빛이 걸리는 부분), 아래로 깔리는 부드러운 그림자(떠 있는 느낌).
|
||||
채도를 살짝 올리면(saturate) 뒤가 흐려지며 빠지는 색기가 돌아온다.
|
||||
|
||||
테두리는 white/40 에서 더 못 내린다. /30 으로 낮추면 무대 광원부(#16205A) 대비가
|
||||
2.60:1 로 떨어져 WCAG 1.4.11(UI 경계 3:1)에 미달한다 — 유리 느낌 때문에 버튼이
|
||||
안 보이던 원래 문제로 돌아간다. 투명감은 채움과 blur 로 내고 테두리는 지킨다.
|
||||
|
||||
hover 는 흰색 반전이 아니라 채움을 밝힌다. 유리는 뒤가 비치는 게 정체성이라
|
||||
불투명하게 뒤집으면 그 순간 유리가 아니게 된다. */
|
||||
stageGhost:
|
||||
"bg-white/12 hover:bg-white/25 text-white border border-white/40 hover:border-white/60 " +
|
||||
"backdrop-blur-md backdrop-saturate-150 " +
|
||||
"shadow-[inset_0_1px_0_0_rgba(255,255,255,0.30),0_8px_24px_-10px_rgba(3,6,15,0.7)]",
|
||||
},
|
||||
// radius 는 사이즈 무관 rounded-2xl(16px) 로 통일 — 알약형 금지
|
||||
/* 레퍼런스(statworx) 실측: 10.4px / 600 / 알약(radius 39px) / 패딩 12·24 / 높이 33px.
|
||||
작고 조밀한 버튼이 확신 있어 보인다 — 크고 굵은 버튼은 설득이 아니라 호소로 읽힌다.
|
||||
한글 보정: 10.4px 는 판독이 어려워 12~13px 로 올리고 높이도 터치 타깃까지 확보한다.
|
||||
(기존 주석의 "알약형 금지" 규칙은 레퍼런스 채택으로 폐기했다.) */
|
||||
size: {
|
||||
pill: "px-4.5 py-2.5 text-sm font-semibold rounded-2xl",
|
||||
md: "px-6 py-2.5 text-xs font-bold rounded-2xl",
|
||||
lg: "px-8 py-4.5 text-base font-bold rounded-2xl",
|
||||
xl: "px-10 py-5 text-base font-bold rounded-2xl",
|
||||
pill: "px-5 py-2.5 text-[12px] font-semibold rounded-full",
|
||||
md: "px-6 py-3 text-[12px] font-semibold rounded-full",
|
||||
lg: "px-7 py-3.5 text-[13px] font-semibold rounded-full",
|
||||
xl: "px-8 py-4 text-[14px] font-semibold rounded-full",
|
||||
stageRound: "px-7 py-3.5 text-[13px] font-semibold rounded-full",
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: "primary", size: "lg" },
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import { useEffect, useId, useRef, useState } from "react"
|
||||
import { AnimatePresence, motion, useReducedMotion } from "motion/react"
|
||||
import { Check, Loader2, X } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { EASE_OUT_EXPO } from "@/lib/motion"
|
||||
import { isEmailLike, submitLead } from "@/lib/lead"
|
||||
|
||||
/*
|
||||
* 데모 요청 모달 — 이름·이메일만 받는 리드 캡처.
|
||||
*
|
||||
* 상담 신청(contact.tsx)은 회사명·담당자·연락처·문의내용까지 받는 고관여 폼이다.
|
||||
* 이건 그 앞단이다. 필드가 늘수록 이탈이 늘기 때문에 두 칸에서 멈춘다 — 영업이
|
||||
* 첫 연락을 하는 데 필요한 최소가 이름과 이메일이고, 나머지는 통화에서 채운다.
|
||||
*
|
||||
* 전체 페이지로 보내지 않고 모달로 띄우는 이유도 같다. 히어로에서 관심이 생긴
|
||||
* 순간에 그 자리에서 받아야 한다. 스크롤로 내려보내면 그 사이에 식는다.
|
||||
*/
|
||||
export function DemoRequestModal({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const [name, setName] = useState("")
|
||||
const [email, setEmail] = useState("")
|
||||
const [website, setWebsite] = useState("") // 봇 함정
|
||||
const [status, setStatus] = useState<"idle" | "submitting" | "success" | "error">("idle")
|
||||
const dialogRef = useRef<HTMLDivElement>(null)
|
||||
const firstFieldRef = useRef<HTMLInputElement>(null)
|
||||
const restoreFocusTo = useRef<HTMLElement | null>(null)
|
||||
const reduce = useReducedMotion()
|
||||
const titleId = useId()
|
||||
|
||||
/* 열릴 때마다 초기화. 남겨두면 성공 화면이 다시 뜨거나 이전 에러가 붙어 나온다. */
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setStatus("idle")
|
||||
restoreFocusTo.current = document.activeElement as HTMLElement | null
|
||||
const t = setTimeout(() => firstFieldRef.current?.focus(), 60)
|
||||
return () => clearTimeout(t)
|
||||
}, [open])
|
||||
|
||||
/* 배경 스크롤 잠금. 모달 뒤에서 페이지가 움직이면 모달이 페이지의 일부처럼 읽힌다. */
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const prev = document.body.style.overflow
|
||||
document.body.style.overflow = "hidden"
|
||||
return () => {
|
||||
document.body.style.overflow = prev
|
||||
restoreFocusTo.current?.focus?.()
|
||||
}
|
||||
}, [open])
|
||||
|
||||
/* Esc 로 닫기 + Tab 을 모달 안에 가둔다. 가두지 않으면 뒤 페이지의 링크로 포커스가
|
||||
빠져나가고, 키보드·스크린리더 사용자는 자기가 어디 있는지 알 수 없게 된다. */
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
if (e.key !== "Tab") return
|
||||
const focusables = dialogRef.current?.querySelectorAll<HTMLElement>(
|
||||
'button:not([disabled]), input:not([disabled]), a[href]',
|
||||
)
|
||||
if (!focusables?.length) return
|
||||
const first = focusables[0]
|
||||
const last = focusables[focusables.length - 1]
|
||||
if (e.shiftKey && document.activeElement === first) {
|
||||
e.preventDefault()
|
||||
last.focus()
|
||||
} else if (!e.shiftKey && document.activeElement === last) {
|
||||
e.preventDefault()
|
||||
first.focus()
|
||||
}
|
||||
}
|
||||
document.addEventListener("keydown", onKeyDown)
|
||||
return () => document.removeEventListener("keydown", onKeyDown)
|
||||
}, [open, onClose])
|
||||
|
||||
const valid = name.trim().length > 0 && isEmailLike(email)
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!valid || status === "submitting") return
|
||||
setStatus("submitting")
|
||||
const result = await submitLead({ source: "demo-request", name, email, website })
|
||||
setStatus(result.ok ? "success" : "error")
|
||||
}
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-6">
|
||||
<motion.div
|
||||
className="absolute inset-0 bg-stage-deep/80 backdrop-blur-sm"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<motion.div
|
||||
ref={dialogRef}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
className="relative w-full max-w-md bg-white rounded-card p-8 sm:p-10 shadow-2xl"
|
||||
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 16, scale: 0.98 }}
|
||||
animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, scale: 1 }}
|
||||
exit={reduce ? { opacity: 0 } : { opacity: 0, y: 8, scale: 0.99 }}
|
||||
transition={{ duration: 0.28, ease: EASE_OUT_EXPO }}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="닫기"
|
||||
className="absolute top-4 right-4 p-2 text-ink-muted hover:text-ink transition-colors cursor-pointer"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
{status === "success" ? (
|
||||
<div className="text-center py-4">
|
||||
<div className="w-12 h-12 rounded-full bg-positive-soft text-positive flex items-center justify-center mx-auto mb-5">
|
||||
<Check className="w-6 h-6" />
|
||||
</div>
|
||||
<Typography variant="cardTitle" as="h2" id={titleId} className="mb-3">
|
||||
데모 신청이 접수되었습니다
|
||||
</Typography>
|
||||
{/* 폼에서 "Demo를 보내드립니다"라고 약속했으므로 성공 화면도 같은 약속을 지킨다.
|
||||
여기서 "일정을 잡아 연락드립니다"로 새면 방문자가 무엇을 기다려야 하는지 모른다. */}
|
||||
<Typography variant="small">
|
||||
입력하신 이메일로 사용해보실 수 있는 Demo를 보내드립니다.
|
||||
</Typography>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* 제목은 여는 버튼과 같은 말을 쓴다. 버튼이 "받기"인데 여기가 "요청"이면
|
||||
전환 순간에 다른 화면에 온 것처럼 읽힌다. */}
|
||||
<Typography variant="cardTitle" as="h2" id={titleId} className="mb-2">
|
||||
실제 데모 받기
|
||||
</Typography>
|
||||
<Typography variant="small" className="mb-8">
|
||||
성함과 이메일만 남겨주시면, 사용해보실 수 있는 Demo를 보내드립니다!
|
||||
</Typography>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-7">
|
||||
{/* 봇 함정. 화면에서 감추되 display:none 은 쓰지 않는다 — 일부 봇은
|
||||
숨겨진 필드를 걸러낸다. 스크린리더에는 aria-hidden + tabIndex 로 숨긴다. */}
|
||||
<div className="absolute w-px h-px -left-[9999px] overflow-hidden" aria-hidden>
|
||||
<input
|
||||
type="text"
|
||||
name="website"
|
||||
tabIndex={-1}
|
||||
autoComplete="off"
|
||||
value={website}
|
||||
onChange={(e) => setWebsite(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="lead-name" className="block text-[13px] font-semibold text-ink-soft mb-2">
|
||||
성함
|
||||
</label>
|
||||
<Input
|
||||
ref={firstFieldRef}
|
||||
id="lead-name"
|
||||
name="name"
|
||||
type="text"
|
||||
required
|
||||
autoComplete="name"
|
||||
placeholder="예: 홍길동"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
disabled={status === "submitting"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="lead-email" className="block text-[13px] font-semibold text-ink-soft mb-2">
|
||||
이메일
|
||||
</label>
|
||||
<Input
|
||||
id="lead-email"
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
autoComplete="email"
|
||||
placeholder="예: hong@company.co.kr"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={status === "submitting"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{status === "error" && (
|
||||
<p role="alert" className="text-[13px] text-ink-soft leading-[1.6] break-keep">
|
||||
지금은 접수가 어렵습니다.{" "}
|
||||
<a href="#contact-section" onClick={onClose} className="text-primary font-semibold underline">
|
||||
상담 신청
|
||||
</a>
|
||||
으로 남겨주시면 동일하게 연락드립니다.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size="lg"
|
||||
className="w-full"
|
||||
disabled={!valid || status === "submitting"}
|
||||
>
|
||||
{status === "submitting" ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
<span>접수 중</span>
|
||||
</>
|
||||
) : (
|
||||
<span>데모 신청</span>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</motion.div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
)
|
||||
}
|
||||
@@ -3,13 +3,13 @@ import type * as React from "react"
|
||||
/** 데스크톱 브라우저 목업 프레임 — 신호등 버튼 + 주소창 + 16:10 워크스페이스. */
|
||||
function BrowserFrame({ url, children }: { url: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="bg-white rounded-2xl border border-line-strong shadow-[0_12px_40px_rgba(0,0,0,0.06)] overflow-hidden w-full max-w-2xl">
|
||||
<div className="bg-white rounded-card border border-line-strong shadow-[0_12px_40px_rgba(0,0,0,0.06)] overflow-hidden w-full max-w-2xl">
|
||||
<div className="bg-fill px-4 py-3.5 flex items-center justify-between border-b border-line-strong">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="w-3 h-3 rounded-full bg-[#FF5F56] inline-block" />
|
||||
<span className="w-3 h-3 rounded-full bg-[#FFBD2E] inline-block" />
|
||||
<span className="w-3 h-3 rounded-full bg-[#27C93F] inline-block" />
|
||||
<span className="text-[11px] text-ink-muted font-mono ml-3 font-semibold bg-white px-3 py-1 rounded-md border border-line-strong truncate max-w-[180px] sm:max-w-none">
|
||||
<span className="text-[11px] text-ink-muted font-mono ml-3 font-semibold bg-white px-3 py-1 rounded-control border border-line-strong truncate max-w-[180px] sm:max-w-none">
|
||||
{url}
|
||||
</span>
|
||||
</div>
|
||||
@@ -22,9 +22,9 @@ function BrowserFrame({ url, children }: { url: string; children: React.ReactNod
|
||||
/** 모바일 폰 목업 프레임 — 노치 포함 9:18 스크린. */
|
||||
function PhoneFrame({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="relative bg-black rounded-[48px] p-3 shadow-[0_20px_50px_rgba(0,0,0,0.15)] border-4 border-line-strong w-full max-w-[290px] aspect-[9/18] overflow-hidden flex flex-col">
|
||||
<div className="relative bg-black rounded-card p-3 shadow-[0_20px_50px_rgba(0,0,0,0.15)] border-4 border-line-strong w-full max-w-[290px] aspect-[9/18] overflow-hidden flex flex-col">
|
||||
{/* 노치는 화면 '안쪽'에 작은 아일랜드로 — 베젤과 붙으면 검은 덩어리처럼 보인다 */}
|
||||
<div className="bg-white rounded-[36px] flex-1 overflow-hidden relative flex flex-col justify-center items-center">
|
||||
<div className="bg-white rounded-card flex-1 overflow-hidden relative flex flex-col justify-center items-center">
|
||||
<div className="absolute top-1 left-1/2 -translate-x-1/2 bg-black/70 h-0.5 w-3.5 rounded-full z-20" />
|
||||
{children}
|
||||
</div>
|
||||
|
||||
@@ -2,16 +2,33 @@ import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
// 문의 폼 필드 공통 스타일 — 테두리 없는 회색 채움, 포커스 시 흰 배경 + 파란 링.
|
||||
/*
|
||||
* 문의 폼 필드.
|
||||
*
|
||||
* 회색 채움 박스는 어느 템플릿에나 있다. 밑줄 필드로 바꾸면 같은 기능인데 훨씬
|
||||
* 정돈돼 보인다 — 폼이 "입력 상자 더미"가 아니라 한 장의 문서처럼 읽힌다.
|
||||
*
|
||||
* 밑줄 폼의 알려진 위험은 입력란으로 안 보이는 것(어포던스 손실)인데,
|
||||
* 라벨을 항상 위에 두고 밑줄을 2px 로 두껍게 잡아 보완했다.
|
||||
* 두께를 항상 2px 로 고정해서 포커스 때 레이아웃이 흔들리지 않는다.
|
||||
*
|
||||
* 글자 16px 은 취향이 아니라 필수다 — iOS 사파리는 16px 미만 입력에 포커스하면
|
||||
* 화면을 자동 확대해서, 광고로 들어온 모바일 사용자의 폼 이탈을 만든다.
|
||||
*/
|
||||
const fieldClass =
|
||||
"w-full px-5 py-3.5 rounded-2xl bg-surface hover:bg-fill focus:bg-white border-0 focus:ring-2 focus:ring-primary/20 text-sm font-semibold text-ink transition-all placeholder:text-ink-faint outline-none"
|
||||
"w-full bg-transparent border-0 border-b-2 border-line-strong rounded-none px-0 py-3 " +
|
||||
"text-[16px] font-normal text-ink placeholder:text-ink-faint placeholder:font-normal " +
|
||||
"outline-none transition-colors hover:border-ink-muted focus:border-primary " +
|
||||
"disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
|
||||
function Input({ className, ...props }: React.InputHTMLAttributes<HTMLInputElement>) {
|
||||
/* ComponentPropsWithRef 로 두면 ref 가 그대로 전달된다 (React 19 는 forwardRef 불필요).
|
||||
데모 요청 모달이 열릴 때 첫 필드로 포커스를 옮기려면 ref 가 필요하다. */
|
||||
function Input({ className, ...props }: React.ComponentPropsWithRef<"input">) {
|
||||
return <input className={cn(fieldClass, className)} {...props} />
|
||||
}
|
||||
|
||||
function Textarea({ className, ...props }: React.TextareaHTMLAttributes<HTMLTextAreaElement>) {
|
||||
return <textarea className={cn(fieldClass, "resize-none", className)} {...props} />
|
||||
function Textarea({ className, ...props }: React.ComponentPropsWithRef<"textarea">) {
|
||||
return <textarea className={cn(fieldClass, "resize-none leading-[1.6]", className)} {...props} />
|
||||
}
|
||||
|
||||
export { Input, Textarea }
|
||||
@@ -0,0 +1,179 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { motion, useReducedMotion } from "motion/react"
|
||||
import { Check } from "lucide-react"
|
||||
|
||||
import { DEMO_ITEMS, won } from "@/lib/negotiation-sim"
|
||||
import { EASE_OUT_EXPO } from "@/lib/motion"
|
||||
|
||||
/*
|
||||
* 협상 리플레이 — 자동 재생 결과 화면.
|
||||
*
|
||||
* 예전에는 negotiation_annotated_3d.mp4(677K)를 썼다. 영상이라 두 가지를 못 고쳤다.
|
||||
* - 화자가 "아이마켓 구매 MD" 로 픽셀에 구워져 있었다. POC 고객사 이름이라
|
||||
* 다른 MRO 회사에 영업할 때 쓸 수 없다.
|
||||
* - 색이 브랜드 팔레트 밖이었다. 실측하면 말풍선 #5A68CD, 목표가 라벨 #B96175,
|
||||
* 배지 #DB840B — 셋 다 토큰에 없는 색이고, 정작 브랜드의 핵심 대비 장치인
|
||||
* 민트(#0FFFD6, 상대편 색)는 한 번도 안 쓰였다.
|
||||
*
|
||||
* 컴포넌트로 옮기면 둘 다 뿌리에서 사라진다. 이름은 상수고 색은 토큰이라,
|
||||
* 팔레트를 바꾸면 여기도 같이 바뀐다. 에셋 677K 도 0 이 된다.
|
||||
*
|
||||
* 숫자는 지어내지 않고 DEMO_ITEMS[0] 을 그대로 쓴다 — 위쪽 인터랙티브 데모와 같은
|
||||
* 품목·같은 가격이라, 둘을 다 본 사람에게 앞뒤가 맞는다.
|
||||
*/
|
||||
|
||||
const ITEM = DEMO_ITEMS[0]
|
||||
const FINAL = ITEM.target // 1,080,000 — 데모의 목표가와 동일
|
||||
const SAVED = ITEM.listPrice - FINAL
|
||||
const RATE = (SAVED / ITEM.listPrice) * 100
|
||||
|
||||
type Line = { side: "buyer" | "supplier"; text: string; price: number }
|
||||
|
||||
/* 화자는 "구매 담당자" 로 둔다. 회사명을 넣으면 그 회사 전용 자산이 되고,
|
||||
특정 고객사 이름은 영업 대상이 바뀔 때마다 못 쓰게 된다. */
|
||||
const LINES: Line[] = [
|
||||
{ side: "supplier", text: `원자재가 올라서 이번 분기는 ${won(ITEM.listPrice)}원이 최선입니다.`, price: ITEM.listPrice },
|
||||
{ side: "buyer", text: `같은 사양 시장 최저가가 ${won(ITEM.marketLow)}원입니다. 연간 물량을 보증하면 어느 선까지 가능하신가요?`, price: ITEM.marketLow },
|
||||
{ side: "supplier", text: `공정상 한 번에 내리긴 어렵고, ${won(1_140_000)}원까지는 조정하겠습니다.`, price: 1_140_000 },
|
||||
{ side: "buyer", text: `목표가까지 얼마 남지 않았습니다. ${won(FINAL)}원이면 지금 바로 낙찰 처리하겠습니다.`, price: FINAL },
|
||||
{ side: "supplier", text: `좋습니다. ${won(FINAL)}원으로 맞추겠습니다.`, price: FINAL },
|
||||
]
|
||||
|
||||
const STEP_MS = 1600
|
||||
/** 마지막 줄 뒤 결과 카드가 머무는 시간. 짧으면 결론을 못 읽고 지나간다. */
|
||||
const HOLD_MS = 3200
|
||||
|
||||
export function NegotiationReplay({ className }: { className?: string }) {
|
||||
const reduce = useReducedMotion()
|
||||
const [shown, setShown] = useState(reduce ? LINES.length : 0)
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
const logRef = useRef<HTMLDivElement>(null)
|
||||
const [inView, setInView] = useState(false)
|
||||
|
||||
/* 화면 밖에서는 돌리지 않는다. 페이지 최하단이라 대부분의 시간 동안 보이지 않는데
|
||||
타이머만 계속 도는 건 배터리를 쓰는 일이다. */
|
||||
useEffect(() => {
|
||||
const el = rootRef.current
|
||||
if (!el) return
|
||||
const io = new IntersectionObserver(([e]) => setInView(e.isIntersecting), { threshold: 0.25 })
|
||||
io.observe(el)
|
||||
return () => io.disconnect()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (reduce || !inView) return
|
||||
const done = shown >= LINES.length
|
||||
const id = window.setTimeout(() => setShown((n) => (n >= LINES.length ? 0 : n + 1)), done ? HOLD_MS : STEP_MS)
|
||||
return () => clearTimeout(id)
|
||||
}, [shown, inView, reduce])
|
||||
|
||||
// 새 줄이 붙으면 바닥으로 붙인다.
|
||||
useEffect(() => {
|
||||
logRef.current?.scrollTo({ top: logRef.current.scrollHeight, behavior: "smooth" })
|
||||
}, [shown])
|
||||
|
||||
const current = shown > 0 ? LINES[shown - 1].price : ITEM.listPrice
|
||||
const settled = shown >= LINES.length
|
||||
/* 정가에서 목표가까지 얼마나 내려왔는지. 1 을 넘지 않게 자른다. */
|
||||
const progress = Math.min(1, (ITEM.listPrice - current) / (ITEM.listPrice - FINAL))
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
className={className}
|
||||
role="img"
|
||||
aria-label={`협상 리플레이. 최초 제시가 ${won(ITEM.listPrice)}원에서 ${won(FINAL)}원으로 낙찰되어 ${won(SAVED)}원 절감된 예시입니다.`}
|
||||
>
|
||||
<div className="rounded-card border border-stage-line bg-stage-raised/70 backdrop-blur-sm p-5 sm:p-6">
|
||||
{/* 품목 + 목표가 — 구매 담당자가 위임한 기준이 무엇인지 먼저 보여준다. */}
|
||||
<div className="flex items-start justify-between gap-3 mb-4">
|
||||
<div className="min-w-0">
|
||||
<div className="text-[14px] font-bold text-on-stage truncate">{ITEM.name}</div>
|
||||
<div className="text-[12px] text-on-stage-muted">{ITEM.spec}</div>
|
||||
</div>
|
||||
<div className="text-right shrink-0">
|
||||
<div className="text-[11px] font-semibold text-on-stage-muted">목표가</div>
|
||||
<div className="text-[14px] font-bold tabular-nums text-on-stage">{won(FINAL)}원</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 현재 제안가 + 진행 막대. 파랑에서 민트로 차오르며 양쪽이 만나는 지점을 그린다. */}
|
||||
<div className="mb-5">
|
||||
<div className="flex items-baseline justify-between mb-2">
|
||||
<span className="text-[11px] font-semibold text-on-stage-muted">현재 제안가</span>
|
||||
<span className="text-[22px] font-extrabold tabular-nums tracking-[-0.02em] text-on-stage">
|
||||
{won(current)}
|
||||
<span className="text-[14px] font-semibold text-on-stage-muted ml-0.5">원</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1.5 rounded-full bg-white/10 overflow-hidden">
|
||||
<motion.div
|
||||
className="h-full rounded-full bg-linear-to-r from-primary-on-stage to-counter"
|
||||
animate={{ width: `${progress * 100}%` }}
|
||||
transition={{ duration: 0.6, ease: EASE_OUT_EXPO }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 대화. 높이를 고정해 줄이 늘어도 레이아웃이 튀지 않는다. */}
|
||||
<div ref={logRef} className="h-[210px] overflow-hidden space-y-3 scrollbar-none">
|
||||
{LINES.slice(0, shown).map((line, i) => (
|
||||
<motion.div
|
||||
key={i}
|
||||
initial={reduce ? false : { opacity: 0, y: 8 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.3, ease: EASE_OUT_EXPO }}
|
||||
className={`flex flex-col ${line.side === "buyer" ? "items-start" : "items-end"}`}
|
||||
>
|
||||
<span
|
||||
className={`text-[11px] font-semibold mb-1 ${
|
||||
line.side === "buyer" ? "text-primary-on-stage" : "text-counter"
|
||||
}`}
|
||||
>
|
||||
{line.side === "buyer" ? "구매 담당자" : "협력사"}
|
||||
</span>
|
||||
<div
|
||||
className={`max-w-[90%] rounded-card px-3.5 py-2.5 text-[13px] leading-[1.55] break-keep ${
|
||||
line.side === "buyer"
|
||||
? "bg-primary text-white"
|
||||
: "bg-counter-surface text-counter border border-counter/20"
|
||||
}`}
|
||||
>
|
||||
{line.text}
|
||||
</div>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 낙찰 카드. 자리를 항상 차지하게 두고 내용만 켜고 끈다 — 나타날 때 아래 요소가
|
||||
밀리면 페이지 전체가 주기적으로 흔들린다. */}
|
||||
<div className="mt-4 h-[74px]">
|
||||
{settled && (
|
||||
<motion.div
|
||||
initial={reduce ? false : { opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.4, ease: EASE_OUT_EXPO }}
|
||||
className="h-full rounded-card border border-counter/25 bg-counter-surface px-3.5 py-3 flex items-center gap-2.5"
|
||||
>
|
||||
<div className="w-8 h-8 rounded-full bg-counter/15 text-counter flex items-center justify-center shrink-0">
|
||||
<Check className="w-4 h-4" />
|
||||
</div>
|
||||
{/* 금액은 줄바꿈을 막는다. 카드 높이가 74px 로 고정이라(등장할 때 아래가 밀리지
|
||||
않게 하려고) 한 줄이라도 접히면 잘린다. 좁으면 접히는 게 아니라 붙어야 한다. */}
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] font-semibold text-counter mb-0.5 whitespace-nowrap">협상 타결 → 낙찰</div>
|
||||
<div className="text-[16px] font-extrabold tabular-nums text-on-stage whitespace-nowrap">{won(FINAL)}원</div>
|
||||
</div>
|
||||
<div className="text-right shrink-0 ml-auto">
|
||||
<div className="text-[11px] font-semibold text-on-stage-muted mb-0.5 whitespace-nowrap">절감액</div>
|
||||
<div className="text-[15px] font-extrabold tabular-nums text-counter whitespace-nowrap">
|
||||
{won(SAVED)}원 <span className="text-[12px]">▼{RATE.toFixed(1)}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { useEffect, useRef, useState, type RefObject } from "react"
|
||||
|
||||
/* 파이프라인 6단계. 원래 히어로 캔버스가 소유하던 타입인데, 히어로가 영상으로 바뀌면서
|
||||
이리로 옮겼다 — 단계 이름을 실제로 쓰는 건 이제 이 링뿐이다. */
|
||||
export type DataFlowPhase = "scatter" | "cluster" | "stream" | "card" | "negotiate" | "learn"
|
||||
|
||||
/**
|
||||
* 파이프라인 순환 링 — 정원.
|
||||
*
|
||||
* 앞서 3D 로 눕힌 타원을 썼는데, 깊이는 생기지만 정원의 완결감이 사라진다.
|
||||
* negotium 의 메시지는 "닫힌 루프"라서 완결감 쪽이 맞다.
|
||||
*
|
||||
* 구조는 레퍼런스(infinith)와 같다 — 점선 원만 천천히 돌고, 마디와 글자는 고정이다.
|
||||
* 글자까지 같이 돌면 읽을 수가 없다.
|
||||
*/
|
||||
|
||||
const NODES: { key: DataFlowPhase; label: string }[] = [
|
||||
{ key: "scatter", label: "Collect" },
|
||||
{ key: "cluster", label: "Classify" },
|
||||
{ key: "stream", label: "Benchmark" },
|
||||
{ key: "card", label: "Anchor" },
|
||||
{ key: "negotiate", label: "Negotiate" },
|
||||
{ key: "learn", label: "Learn" },
|
||||
]
|
||||
|
||||
/* viewBox 는 정사각이 아니다. 라벨이 궤도 바깥 좌우로 뻗기 때문에 가로 여백이 더 필요한데,
|
||||
정사각으로 두면 "Benchmark" 같은 긴 라벨이 잘린다(SVG 는 viewBox 밖을 그냥 자른다).
|
||||
가로만 넓히면 링 크기는 유지한 채 라벨 자리를 확보할 수 있다. */
|
||||
const VB_W = 176
|
||||
const VB_H = 150
|
||||
const CX = VB_W / 2
|
||||
const CY = VB_H / 2
|
||||
const R = 46 // 궤도 반지름
|
||||
const R_LABEL = 58 // 라벨은 궤도 바깥에
|
||||
|
||||
const rad = (ratio: number) => ratio * Math.PI * 2 - Math.PI / 2 // 12시에서 시계방향
|
||||
const at = (ratio: number, radius: number) => ({
|
||||
x: CX + Math.cos(rad(ratio)) * radius,
|
||||
y: CY + Math.sin(rad(ratio)) * radius,
|
||||
})
|
||||
|
||||
const LOOP_MS = 10_500 // 히어로 캔버스와 같은 주기
|
||||
|
||||
export function OrbitRing({
|
||||
phase,
|
||||
progressRef,
|
||||
className = "",
|
||||
}: {
|
||||
/** 밖에서 단계를 주면 그걸 따르고, 없으면 자체 시계로 돈다. */
|
||||
phase?: DataFlowPhase
|
||||
/** 캔버스가 매 프레임 써 넣는 루프 진행도 0..1. 없으면 스스로 센다. */
|
||||
progressRef?: RefObject<number>
|
||||
className?: string
|
||||
}) {
|
||||
const headRef = useRef<SVGCircleElement>(null)
|
||||
const [ownIndex, setOwnIndex] = useState(0)
|
||||
|
||||
const activeIndex = phase ? Math.max(0, NODES.findIndex((n) => n.key === phase)) : ownIndex
|
||||
|
||||
/* 궤도를 도는 머리는 rAF 로 직접 갱신한다 — 60fps 로 setState 를 부르면 페이지가 매 프레임 리렌더된다.
|
||||
단계 라벨만 바뀔 때(초당 0.5회) 리렌더한다. */
|
||||
useEffect(() => {
|
||||
let raf = 0
|
||||
let last = -1
|
||||
const startedAt = performance.now()
|
||||
const tick = (now: number) => {
|
||||
const p = progressRef ? (progressRef.current ?? 0) : ((now - startedAt) % LOOP_MS) / LOOP_MS
|
||||
const { x, y } = at(p, R)
|
||||
if (headRef.current) {
|
||||
headRef.current.setAttribute("cx", String(x))
|
||||
headRef.current.setAttribute("cy", String(y))
|
||||
}
|
||||
if (!phase) {
|
||||
const i = Math.min(NODES.length - 1, Math.floor(p * NODES.length))
|
||||
if (i !== last) {
|
||||
last = i
|
||||
setOwnIndex(i)
|
||||
}
|
||||
}
|
||||
raf = requestAnimationFrame(tick)
|
||||
}
|
||||
raf = requestAnimationFrame(tick)
|
||||
return () => cancelAnimationFrame(raf)
|
||||
}, [progressRef, phase])
|
||||
|
||||
return (
|
||||
<svg viewBox={`0 0 ${VB_W} ${VB_H}`} className={className} role="img" aria-label="협상 파이프라인 순환">
|
||||
<defs>
|
||||
<linearGradient id="orbitGrad" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" stopColor="var(--color-primary-on-stage)" stopOpacity="0.9" />
|
||||
<stop offset="55%" stopColor="var(--color-on-stage-soft)" stopOpacity="0.35" />
|
||||
<stop offset="100%" stopColor="var(--color-counter)" stopOpacity="0.55" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
{/* 점선 궤도 — 이 레이어만 돈다 */}
|
||||
<g className="animate-[spin_22s_linear_infinite] motion-reduce:animate-none" style={{ transformOrigin: `${CX}px ${CY}px` }}>
|
||||
<circle cx={CX} cy={CY} r={R} fill="none" stroke="url(#orbitGrad)" strokeWidth="0.6" strokeDasharray="2.2 2.4" />
|
||||
</g>
|
||||
|
||||
{/* 바깥 보조 호 — 정지. 원이 하나면 심심하고, 둘이면 공간이 생긴다. */}
|
||||
<circle
|
||||
cx={CX}
|
||||
cy={CY}
|
||||
r={R + 9}
|
||||
fill="none"
|
||||
stroke="var(--color-on-stage-soft)"
|
||||
strokeOpacity="0.1"
|
||||
strokeWidth="0.4"
|
||||
/>
|
||||
|
||||
{/* 마디 + 라벨 — 고정 레이어 */}
|
||||
{NODES.map((n, i) => {
|
||||
const ratio = i / NODES.length
|
||||
const p = at(ratio, R)
|
||||
const l = at(ratio, R_LABEL)
|
||||
const cos = Math.cos(rad(ratio))
|
||||
const anchor = cos > 0.3 ? "start" : cos < -0.3 ? "end" : "middle"
|
||||
const active = i === activeIndex
|
||||
return (
|
||||
<g key={n.key}>
|
||||
<circle
|
||||
cx={p.x}
|
||||
cy={p.y}
|
||||
r={active ? 2.6 : 1.4}
|
||||
fill={active ? "var(--color-primary-on-stage)" : "var(--color-on-stage-soft)"}
|
||||
opacity={active ? 1 : 0.45}
|
||||
style={{ transition: "r 240ms ease-out, opacity 240ms ease-out" }}
|
||||
/>
|
||||
<text
|
||||
x={l.x}
|
||||
y={l.y + 1.6}
|
||||
textAnchor={anchor}
|
||||
fontSize="5"
|
||||
fontWeight={active ? 700 : 500}
|
||||
fill={active ? "#FFFFFF" : "var(--color-on-stage-soft)"}
|
||||
opacity={active ? 1 : 0.5}
|
||||
style={{ transition: "opacity 240ms ease-out" }}
|
||||
>
|
||||
{n.label}
|
||||
</text>
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* 궤도를 도는 머리 */}
|
||||
<circle ref={headRef} cx={CX} cy={CY - R} r="2" fill="#FFFFFF" opacity="0.95" />
|
||||
|
||||
{/* 가운데 */}
|
||||
<text x={CX} y={CY - 1} textAnchor="middle" fontSize="7" fontWeight="700" fill="#FFFFFF">
|
||||
{NODES[activeIndex].label}
|
||||
</text>
|
||||
<text
|
||||
x={CX}
|
||||
y={CY + 8.5}
|
||||
textAnchor="middle"
|
||||
fontSize="4.2"
|
||||
fontWeight="500"
|
||||
fill="var(--color-on-stage-soft)"
|
||||
opacity="0.5"
|
||||
>
|
||||
{String(activeIndex + 1).padStart(2, "0")} / {String(NODES.length).padStart(2, "0")}
|
||||
</text>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
type RangeSliderProps = {
|
||||
min: number
|
||||
max: number
|
||||
step: number
|
||||
value: number
|
||||
onChange: (value: number) => void
|
||||
}
|
||||
|
||||
/** 채워진 트랙이 값을 따라가는 파란 슬라이더 (ROI 시뮬레이터·히어로 콘솔 공용). */
|
||||
function RangeSlider({ min, max, step, value, onChange }: RangeSliderProps) {
|
||||
const filled = ((value - min) / (max - min)) * 100
|
||||
return (
|
||||
<input
|
||||
type="range"
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
value={value}
|
||||
onChange={(e) => onChange(Number(e.target.value))}
|
||||
className="w-full h-1.5 rounded-lg appearance-none cursor-pointer accent-primary transition-all"
|
||||
style={{
|
||||
background: `linear-gradient(to right, var(--color-primary) 0%, var(--color-primary) ${filled}%, var(--color-line-strong) ${filled}%, var(--color-line-strong) 100%)`,
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { RangeSlider }
|
||||
@@ -3,25 +3,102 @@ import * as React from "react"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
/*
|
||||
* 섹션 머리.
|
||||
*
|
||||
* eyebrow 는 선택이고, 기본적으로 쓰지 않는다. 작은 색 라벨을 섹션마다 반복하면
|
||||
* 레퍼런스에서는 영문 대문자라 조판 요소로 기능하지만, 한글은 대문자가 없어서
|
||||
* 그냥 "작은 글씨"가 되고 일곱 번 반복되면 벽지가 된다.
|
||||
* 위계는 라벨이 아니라 헤드라인 크기(본문의 3.5~4배)와 2톤 대비로 만든다.
|
||||
*
|
||||
* ── 세로 리듬 ────────────────────────────────────────────────────────
|
||||
* 머리 안팎의 간격은 전부 이 파일이 소유한다. 섹션 파일에서 각자 mb-12 / mb-16 /
|
||||
* mb-20 / mb-24 를 붙이던 걸 걷어낸 결과다. 같은 관계(머리 → 본문)에 값이 다섯 개
|
||||
* 있으면 스크롤할 때 섹션마다 호흡이 달라지고, 그게 "정돈이 안 됐다"는 인상의
|
||||
* 실제 원인이었다.
|
||||
*
|
||||
* 규칙은 하나다 — 간격이 위계를 만든다. 가까울수록 한 덩어리로 읽힌다.
|
||||
* 값이 흔들리면 "어디까지가 한 덩어리인가"가 섹션마다 달라져 보인다.
|
||||
*
|
||||
* eyebrow → title 16px 라벨은 제목에 붙는다
|
||||
* title → description 20 / 32px 큰 활자는 더 벌린다. 64px 제목 아래 20px 은 붙어 보인다
|
||||
* 머리 → 본문 56 / 80px 섹션 안에서 가장 큰 끊김
|
||||
*
|
||||
* 섹션 파일에서 이 관계들에 mb-· mt- 유틸리티를 직접 쓰지 않는다. 필요하면 아래 상수를
|
||||
* import 해서 쓰고, 새 값이 필요하다고 느껴지면 여기에 이름을 붙여서 추가한다.
|
||||
* 눈대중으로 한 칸씩 조정하기 시작하면 다시 지금 상태로 돌아온다.
|
||||
*/
|
||||
|
||||
/** 머리 → 본문. 머리를 직접 조판하는 섹션(무대 데모)도 이 상수를 쓴다. */
|
||||
export const HEADING_GAP = "mb-14 md:mb-20"
|
||||
/** 탭·토글 행 → 본문. 머리 간격보다 좁아서 컨트롤이 위가 아니라 본문 쪽에 묶인다. */
|
||||
export const CONTROL_GAP = "mb-12"
|
||||
/** 리드 문단 → 버튼 행 (히어로·최종 CTA). */
|
||||
export const CTA_GAP = "mt-12"
|
||||
/** display 티어 제목 → 리드 문단. 히어로는 h1 이라 SectionHeading 을 못 쓰고 이 상수를 직접 쓴다. */
|
||||
export const DISPLAY_LEAD_GAP = "mt-8"
|
||||
|
||||
/*
|
||||
* 제목 조판 티어. 티어가 바뀌면 리드 문단까지의 간격도 같이 움직인다 —
|
||||
* Typography 주석의 "크기·굵기·조임은 같이 움직인다"와 같은 이유로, 간격도 딸려간다.
|
||||
*/
|
||||
const SIZES = {
|
||||
/** 섹션 표준 h2 (34 / 64px) */
|
||||
title: { variant: "title", descriptionGap: "mt-5" },
|
||||
/** 히어로·최종 CTA 급 디스플레이 (38~74px) */
|
||||
display: { variant: "stageDisplay", descriptionGap: DISPLAY_LEAD_GAP },
|
||||
} as const
|
||||
|
||||
type SectionHeadingProps = {
|
||||
eyebrow: string
|
||||
eyebrow?: string
|
||||
title: React.ReactNode
|
||||
description?: React.ReactNode
|
||||
align?: "left" | "center"
|
||||
/** 다크 무대 섹션(bg="stage")에서는 "stage" 를 준다. Typography 변형이 먹색을 물고 있어서 필요하다. */
|
||||
tone?: "light" | "stage"
|
||||
/** 제목 조판 티어. display 는 히어로·최종 CTA 전용. */
|
||||
size?: keyof typeof SIZES
|
||||
/** 머리 아래 표준 간격을 끈다. 뒤에 컨트롤 행이 붙는 섹션에서만 쓴다. */
|
||||
gap?: "heading" | "none"
|
||||
className?: string
|
||||
/** 리드 문단 폭 제한 등 (예: "max-w-2xl") */
|
||||
/** 제목 크기 미세조정 (예: 최종 CTA 의 축소 디스플레이) */
|
||||
titleClassName?: string
|
||||
/** 리드 문단 폭 제한·색 조정 (예: "max-w-2xl"). 세로 간격은 여기서 주지 않는다. */
|
||||
descriptionClassName?: string
|
||||
}
|
||||
|
||||
function SectionHeading({ eyebrow, title, description, align = "left", className, descriptionClassName }: SectionHeadingProps) {
|
||||
function SectionHeading({
|
||||
eyebrow,
|
||||
title,
|
||||
description,
|
||||
align = "left",
|
||||
tone = "light",
|
||||
size = "title",
|
||||
gap = "heading",
|
||||
className,
|
||||
titleClassName,
|
||||
descriptionClassName,
|
||||
}: SectionHeadingProps) {
|
||||
const onStage = tone === "stage"
|
||||
const { variant, descriptionGap } = SIZES[size]
|
||||
|
||||
return (
|
||||
<div className={cn(align === "center" && "text-center", className)}>
|
||||
<Typography variant="eyebrow" className="mb-3 block">
|
||||
{eyebrow}
|
||||
<div className={cn(align === "center" && "text-center", gap === "heading" && HEADING_GAP, className)}>
|
||||
{/* eyebrow 가 없을 때 빈 span 을 렌더하면 mb + 30px 행간만큼 유령 여백이 생긴다.
|
||||
지금은 모든 섹션이 eyebrow 를 넘기지만, 하나만 빼도 그 섹션만 제목이 내려앉는다. */}
|
||||
{eyebrow && (
|
||||
<Typography variant="eyebrow" className={cn("mb-4 block", onStage && "text-primary-on-stage")}>
|
||||
{eyebrow}
|
||||
</Typography>
|
||||
)}
|
||||
<Typography variant={variant} as="h2" className={cn(onStage && "text-on-stage", titleClassName)}>
|
||||
{title}
|
||||
</Typography>
|
||||
<Typography variant="title">{title}</Typography>
|
||||
{description && (
|
||||
<Typography variant="lead" className={cn("mt-5", align === "center" && "mx-auto", descriptionClassName)}>
|
||||
<Typography
|
||||
variant="lead"
|
||||
className={cn(descriptionGap, align === "center" && "mx-auto", onStage && "text-on-stage-soft", descriptionClassName)}
|
||||
>
|
||||
{description}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
@@ -6,6 +6,8 @@ const sectionBg = {
|
||||
white: "bg-white",
|
||||
surface: "bg-surface",
|
||||
dark: "bg-ink text-white",
|
||||
/** 히어로와 같은 무대. 어두운 섹션은 이걸 쓴다 — 페이지 안에 어둠이 두 종류면 따로 논다. */
|
||||
stage: "stage-bg text-on-stage",
|
||||
}
|
||||
|
||||
const sectionWidth = {
|
||||
@@ -37,7 +39,8 @@ function Section({
|
||||
}: SectionProps) {
|
||||
return (
|
||||
<section
|
||||
className={cn("py-36 md:py-44", sectionBg[bg], bordered && "border-t border-line", decor && "relative overflow-hidden", className)}
|
||||
/* 레퍼런스 섹션 패딩은 104~139px. 176px 은 과해서 "채울 내용이 없어" 보인다. */
|
||||
className={cn("py-24 md:py-32", sectionBg[bg], bordered && "border-t border-line", decor && "relative overflow-hidden", className)}
|
||||
{...props}
|
||||
>
|
||||
{decor}
|
||||
|
||||
Loaded 100 of 324 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user