Compare commits

..
Author SHA1 Message Date
minaChoi ac6366a898 [feat] negosium·negodata: 협상 진행 중 거부 + 결렬 건 최종 제출가로 직접 낙찰
협력사가 단종·품절을 대화 도중 알아채도 봇의 결렬 선언을 기다려야 했고,
거부로 끝난 협상은 가격을 남겨도 낙찰 후보에서 빠져 계약으로 이어지지 않았다.

negosium
- 채팅 액션바에 협상 거부 진입점 — 대화가 끝나지 않고 입력을 기다리는 동안만 노출,
  주 CTA 와 붙지 않게 넓은 화면은 우측 끝 고정·좁은 화면은 wrap
- 거부 팝업은 목록 거부 팝업과 같은 어휘·규격, 대화 중이라 공급 희망 가격·의견을 더 받는다
- /reject 에 reject_price·opinion 추가 — sessions.reject_price 저장, 의견은 custom 병합
- 화면 문구 '거절' → '거부' 통일 (버튼·배지·탭·토스트·안내 팝업)

negodata
- 개찰 견적 직접 낙찰 후보 = 가격을 써낸 세션 — 투찰한 협상완료 + 공급 희망가를 남긴 협상거부
- 계약가 파생 _award_price/awardPrice — coalesce(투찰가, 거부 시 공급 희망가)
- 통계 낙찰 세션 조인도 같은 기준 — 안 고치면 거부가로 낙찰한 건이 절감 집계에서 빠진다
- 세션 상태 탭 라벨 '거절사유/거절가격/거절배송방식' → '거부…'

자동 마감 판정(close_and_decide)은 그대로 — 자동 낙찰은 투찰가만 본다.
2026-08-11 10:34:07 +09:00
minaChoi f1e924931f [fix] negodata: 협상 학습 화면 정리 — 내부 점수 제거·카드탭 사용 현황 전환·메뉴 개발자 전용
- 관측 사실 기준으로 재구성: 내부 점수 제거, 앵커링 % 표기, 탭 URL 분리
- 카드탭을 성과 지표에서 사용 현황으로 전환, 지표 설명 말풍선·카드 상세 링크
- 사이드바 devOnly + 라우트 가드로 개발자 전용 처리
2026-08-11 08:49:15 +09:00
minaChoi e1e519c20c [fix] negosium/backend·front: 마감된 협상이 '협상 대기'로 보이던 문제 + 종료 협상 결과 보기
- 목록 상태를 파생 계산(_effective_status): 견적 마감/마감시간 경과 + 협상생성(1) → 미참여(4).
  표시·상태필터·기본정렬 그룹에 같이 적용해 탭·KPI 카운트가 배지와 어긋나지 않게 함(DB 쓰기 없음).
  마감 일괄정리 이후 생긴 세션이 '협상 대기'에 남아 눌러도 마감 에러가 나던 헛클릭 제거.
- 미참여·협상거부 세션도 채팅 init 허용 → '결과 보기'로 지난 대화 열람. 대화 재개는 send 가
  협상중만 허용해 읽기 전용. 열 게 없는 건은 목록 has_chat(대화 이력 유무)으로 버튼 자체를 감춤.
- 종료 건은 참여 API 를 타지 않고 채팅으로 직행, 채팅 액션바는 목록 복귀만 남겨 입력 잠금.
- chain_max_round 가 단일컬럼 select 결과를 행 튜플로 읽어 매 목록 호출마다 예외 → 체인 최대차수
  0 → 옛 라운드에도 재협상 요청이 뜨고 통과되던 버그 수정(+ABC 에 중복된 죽은 구현 제거).
2026-08-10 13:57:30 +09:00
minaChoi e816bfbba4 [feat] negodata: 협상 학습 메뉴 신설 — 카드별 학습 성적 · 앵커링 현황/조정 이력
agent(협상카드 강화학습)와 anchoring(구간별 자동 조정)이 쌓아온 결과를 볼 수 있는 화면이
없어 DB 를 직접 열어야 확인이 됐다. 두 축은 성격이 달라 한 화면에 섞지 않고 탭으로 나눈다.

백엔드(읽기 전용 — 값의 주인은 agent·anchoring):
- crud/learning_crud.py: learning·anchoring 스키마 경량 조회(negodata ORM 미매핑 테이블)
- services/learning_service.py + router/v1/learning: /v1/learning/cards · /anchoring

프론트:
- 사이드바 '협상 학습'(/learning) 추가, 탭 = 협상카드 | 앵커링
- 협상카드: 학습 협상·기록·타결 비율 요약 + 카드별 사용/타결/평균 점수(0 기준 좌우 막대)
- 앵커링: 구간별 현재 인하폭 + 조정 이력(표본·성공률·값 변화)

검증: 로컬 실협상 3건으로 데이터 생성 후 두 탭 실화면 확인, tsc·eslint 통과.
2026-08-10 13:24:32 +09:00
minaChoi 37fa65707f [fix] postgres-init: 카드 시드를 운영 현행에 맞춤 — 중반 카드 앵커가 인용 + 목표가 카드 종결 전용
협상 중반에 목표가를 부르면 이후 올려줄 금액이 없어져 남은 카드가 같은 값만 반복한다.
제안은 앵커가 → 중간가 → 목표가로 수렴해야 하므로 시드를 그 순서에 맞춘다.

- NGC-010 향후 거래 연계 · NGC-011 양보 가치 강조: 제시 금액 {target_price} → {anchor_price}
- tactic: WC-01 종결 전용 추가, WC-04 min_round 2 → 종결 전용, WC-05 종결 전용 + min_round 2,
  WC-02 min_round 2 추가 (WC-03 종전 유지)

init-data.sql · dbeaver/4_cards_reset_dbeaver.sql 동일 반영.
검증: 임시 DB 에 1_init + 4_cards_reset 적용 후 tactic·변수 확인.
2026-08-10 11:41:25 +09:00
minaChoi 86d50c1291 [fix] negodata/front: 윈도우 모달 한글 깨짐 — 컨테이너 font-mono 제거 + 모노 스택 한글 폴백
모달 래퍼·폼에 걸린 font-mono 가 내부 한글까지 모노 스택으로 태웠다. JetBrains Mono·Consolas 에
한글 글리프가 없어 Windows 에서 굴림으로 떨어졌다(맥은 뒤쪽 폰트가 한글을 커버해 정상으로 보임).

- 한글이 들어가는 컨테이너 15곳에서 font-mono 제거 — 숫자 정렬이 필요한 칸은 유지
- --font-mono 스택 끝에 'Noto Sans KR' 추가, index.html 에 구글폰트 링크
  (self-host Pretendard 가 못 뜰 때의 안전망 — 정상 경로는 동일 도메인 Pretendard)
2026-08-10 09:49:26 +09:00
minaChoi 436384fa36 [fix] agent: 중간값 카드가 목표가로 제시되던 문제 — 제안가 산식 일원화·절충 카드 목표가 이상 미발동·적용 대기 와일드카드 차단
원인 두 겹.
1) 절충 계열 가드가 타결 상한만 봐서, 중간가((앵커+목표)/2)처럼 구조상 목표가를 넘지 못하는
   값은 항상 통과했다. 앵커가 목표가에 붙으면 그 값이 곧 목표가라 목표가로 제시된다.
   → 파생 제안값이 목표가 이상이면 미발동(compute_offer). 목표가 카드는 영향 없음.
2) 제안가 확정 시 계산에 쓴 당사 직전가를 남기지 않고 그 자리를 제안가로 덮은 뒤, 멘트 렌더가
   갱신된 값으로 재계산해 "당사 A 와 귀사 B 의 절반은 A" 자기모순이 났다. 직전 커밋은 갱신을
   렌더 뒤로 미뤘으나 와일드카드는 렌더 지점이 더 뒤라 그대로 남아 있었다.
   → Offer/record_offer 로 금액과 재료(당사 직전가·협력사 제시가)를 함께 박제하고, vars_for 는
     재계산 대신 그 기록을 읽는다. 렌더 순서에 의존하지 않으므로 직전 커밋의 순서 조정은 제거.
   → 산식은 tactics.OFFER_VARIABLES 한 곳만 남기고 chat_engine 의 복사본 삭제.

곁들여: 카드 설정에서 '적용 대기'로 꺼둔 와일드카드가 견적에 담겨 있으면 그대로 발동하던 것을
차단(wild_cards.available 조건). 테이블 정의에 빠져 있던 컬럼도 보강.

검증: 단위/E2E 35건, 실협상 8시나리오(멘트 토큰 노출·절반 산술 정합·카드 중복·제안가 역행·
상한 초과 자동 검사) 통과.
2026-08-10 09:45:30 +09:00
minaChoi a405e00bf9 [fix] agent·negodata/front: 중간값 멘트 모순 수정(갑 포지션 갱신을 치환 뒤로·원값 인용가 반올림 제외·1% 카드 역행 금지) + 계정 전환 쿼리캐시 초기화·ChatTab 카드 렌더 정리 + font-mono 한글 폴백(Windows 한글깨짐) 2026-08-07 15:48:48 +09:00
민헌andClaude Opus 5 7dc925bcd4 docs(lps): 2026-08-07 세션 기록 — IP 로테이션 검수·네이버 UA 규명·결과 상태 정의
다음 세션이 이어받을 수 있게 남긴다.

- docs/2026-08-07-session-notes.md 신규: 세 덩어리(IP 로테이션 결함 6개, 네이버 컨테이너 차단이
  실은 UA 플랫폼 토큰이었다는 규명, '못 봤다'를 '없다'고 말하던 문제의 4단계 해결)와
  **되돌리기 전에 볼 근거**(예산을 IP 에 묶는 이유, 태우지 않는 판정, 임대 없이 크롤 금지,
  UA 는 플랫폼만 바꾸고 버전은 실값, 상태는 하나로 저장하고 표시에서 접기).
- 미해결: 쿠팡 간헐 차단 — IP 에 따라 갈리므로 환경이 아니라 평판. 쿠팡만 gate(해외 IP)를 쓰는 게
  유력한 원인이고, 네이버처럼 kr_host 로 바꾸는 검증이 중단된 상태.
- 다음 할 일 5가지(운영 마이그레이션 → 쿠팡 KR 검증 → 예산 튜닝 → AI 매칭 정확도 → admin 잡목록).
- 주의사항 5가지: **마이그레이션→코드 순서 강제**(역순이면 최저가 조회가 통째로 실패, 재현 확인),
  워커 켜고 pytest 하면 test_job_queue 3개 깨짐, JS 지문 위장은 patchright 가 막아 불가,
  로컬 negodata-front 는 node_modules 가 named volume 이라 재빌드로 의존성이 안 늘어남.
- README 문서 표에 링크 추가.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 15:02:25 +09:00
민헌 0c6c431f0a Merge branch 'feat/source-state'
'못 봤다'를 '없다'고 말하던 문제를 4단계로 해결한다. 상태를 하나로 정의·저장하고 표시 단계에서
보는 사람에 맞게 접는다 — 운영자(lps-admin)는 7상태 그대로, 실사용자(negodata)는 셋으로.

1) SourceState 7상태 — 어댑터가 이미 알던 '봤다/못 봤다' 구분을 핸들러가 버리지 않게 한다
2) price_history.sources/partial — 그 구분을 담을 자리(by_mall 은 가격 있는 몰만 담는다)
3) lps-admin — 몰별 상태·차단 마커·조치 힌트(blocked=자동회복 vs env_blocked=사람이 고쳐야)
4) negodata — '–'(확인했고 없음)와 '확인 못함'(못 봄)을 가르고, 후자는 재검색 대상으로 남긴다

⚠️ 배포 순서: 마이그레이션 2개(6_lps_2026-08_dbeaver.sql · 2026-08-07-iilp-source-state.sql)를
   **코드보다 먼저** 적용해야 한다. negodata 가 ORM 전체 엔티티를 조회하므로 컬럼이 없으면
   최저가 조회가 통째로 실패한다(재현 확인). 역순(마이그레이션 후 옛 코드)은 안전하다.

실환경 검증: 실제 크롤 결과로 네이버 no_match→'–', 쿠팡 env_blocked→'확인 못함' 확인.
잡 DEAD 0건, 네거티브 캐시 미오염, 포트 소각 8/100 에서 차단.
2026-08-07 14:46:02 +09:00
87 changed files with 2127 additions and 311 deletions

No files matched your search

+59 -16
View File
@@ -8,9 +8,8 @@
2) 변수 정의 — 그 금액을 지금 쓸 수 있는지 (OFFER_VARIABLES 의 계산식 + 유효조건)
3) tactic JSONB — 문장으로 알 수 없는 운영 규칙 (min_round·closing)
유효 조건을 카드가 아니라 '변수'에 붙이는 이유: 절충가가 목표가를 넘을 수 있는 것은
(직전제안+제시가)/2 라는 계산식의 성질이지 특정 카드의 성질이 아니다. 같은 변수를 쓰는
카드가 늘어도 규칙은 한 곳이고, 새 변수는 이 표에 한 줄 추가하면 코드 분기 없이 끝난다.
유효 조건은 카드가 아니라 '변수'에 붙인다 — 금액이 성립하는지는 계산식의 성질이지 카드의
성질이 아니다. 새 변수는 OFFER_VARIABLES 에 한 줄 추가하면 코드 분기 없이 끝난다.
"""
import re
@@ -32,6 +31,9 @@ OFFER_VARIABLES: Dict[str, Callable[[float, float, float, float], Optional[float
_TOKEN_RE = re.compile(r"\{([a-z_]+)\}")
# 절충 계열 변수 — 양측 사이/우리 두 값 사이의 중간을 부르는 카드. 목표가 이상이면 미발동한다.
_MID_VARIABLES = ("middle_price", "target_mid_price")
# 세션 데이터에 따라 값이 없을 수 있는 읽기 전용 변수 → 그 값을 담는 컨텍스트 키.
# 스크립트가 이런 변수를 인용하면 값이 있을 때만 카드가 나간다 — 없는데 나가면 협력사 채팅에
@@ -65,9 +67,8 @@ HOLD = CardSpec() # 스펙을 못 찾은 카드(테넌트 데모·회사 커스
def settle_ceiling(context: Dict[str, Any]) -> float:
"""이 협상에서 받아줄 수 있는 최고가 — 타결 판정선이자 카드 제안가의 상한.
견적 생성 시 세션에 박제한 done_ceiling_price(= 목표가 × (1 + 타결상한율)). 목표가를 조금
넘더라도 기존 단가보다 인하됐으면 타결시키기 위한 값이다(IMK: 기존 17,500 / 목표 16,980 /
최종 17,300 이 결렬되던 케이스). 박제가 없는 옛 세션·데모는 목표가로 폴백 — 종전 동작 유지.
견적 생성 시 세션에 박제한 done_ceiling_price(= 목표가 × (1 + 타결상한율)) — 목표가를 조금
넘더라도 기존 단가보다 인하됐으면 타결시키기 위한 값. 박제가 없으면 목표가로 폴백한다.
"""
return float(context.get("done_ceiling_price") or context.get("target_price") or 0)
@@ -75,9 +76,8 @@ def settle_ceiling(context: Dict[str, Any]) -> float:
def parse_offer_variable(script: Optional[str]) -> Optional[str]:
"""스크립트가 제시하는 제안가 변수. 없으면 None(설득 카드).
제안가 변수가 여럿이면 **마지막에 등장하는 것**이 제안가다 — 카드 문장은 배경을 먼저 깔고
(예: "당초 검토한 적정가는 {anchoring_price}원이었으나") 실제 제안을 마지막에 하기 때문이다
(예: "이에 {target_price}원으로 조정하여 제안 드립니다").
변수가 여럿이면 마지막에 등장하는 것이 제안가다 — 카드 문장은 배경을 먼저 깔고 실제 제안을
마지막에 하기 때문이다.
"""
found = [m.group(1) for m in _TOKEN_RE.finditer(script or "") if m.group(1) in OFFER_VARIABLES]
return found[-1] if found else None
@@ -115,16 +115,50 @@ def spec_from_context(context: Dict[str, Any], number: Optional[str]) -> CardSpe
)
@dataclass(frozen=True)
class Offer:
"""확정된 제안 한 건 — 금액과 그 금액을 만든 재료를 함께 들고 다닌다.
멘트 치환이 재료를 다시 계산하지 않게 하기 위한 것 — 재계산하면 그 사이 갱신된
prev_customer 를 읽어 문장이 자기모순이 된다.
"""
price: int # 협력사에게 제시할 금액(수락 시 타결가)
variable: str # 이 금액을 만든 멘트 변수
prev_customer: int # 계산에 쓴 당사 직전 제안
prev_partner: int # 계산에 쓴 협력사 제시가
def record_offer(context: Dict[str, Any], offer: Offer) -> None:
"""확정 제안을 세션에 기록한다 — 수락 판정용 금액과 멘트 치환용 재료를 한 자리에서 쓴다.
두 키를 항상 함께 써야 표시가와 타결가가 갈라지지 않으므로 기록 지점을 여기 하나로 묶는다.
"""
context["pending_counter_price"] = offer.price
context["pending_offer"] = {
"price": offer.price, "variable": offer.variable,
"prev_customer": offer.prev_customer, "prev_partner": offer.prev_partner,
}
context["prev_customer_price"] = offer.price # 갑의 최신 포지션 — 다음 라운드 계산·역행 금지 기준
def compute_offer_detail(spec: CardSpec, context: Dict[str, Any]) -> Optional[Offer]:
"""카드가 제시할 금액 + 그 계산에 쓴 재료. 쓸 수 없는 상황이면 None."""
price = int(float(context.get("input_price") or 0))
prev_customer = int(float(context.get("prev_customer_price") or context.get("anchor_price") or 0))
value = compute_offer(spec, context)
if value is None:
return None
return Offer(price=value, variable=spec.offer_variable or "", prev_customer=prev_customer, prev_partner=price)
def compute_offer(spec: CardSpec, context: Dict[str, Any]) -> Optional[int]:
"""카드가 제시할 금액. 쓸 수 없는 상황이면 None → 호출부가 카드를 건너뛴다.
변수 공통 유효조건 (전부 만족해야 발동):
· 값 ≤ 타결 상한가 — 구매자는 받아줄 수 없는 금액을 부르지 않는다. 넘으면 클램프가 아니라
**미발동**(깎아 부르면 "중간에서 만나자"면서 상한을 부르는 모순이 된다).
상한은 견적 생성 시 박제한 done_ceiling_price(목표가×(1+율)), 없으면 목표가.
· 값 ≤ 타결 상한가 — 받아줄 수 없는 금액은 부르지 않는다. 넘으면 깎지 않고 미발동
· 값 < 협력사 제시가 — 이미 더 싸게 받았는데 더 비싼 값을 부를 이유가 없다
· 값 ≥ 당사 직전 제안 — 역행 금지(IMK 논의). 16,980을 불러놓고 16,810(앵커)을 부르면 협상이
좁혀지지 않고 되돌아간다. 제안 시퀀스는 앵커→…→목표가로 단조 수렴해야 한다
· 값 ≥ 당사 직전 제안 — 역행 금지. 제안 시퀀스는 앵커→…→목표가로 단조 수렴해야 한다
"""
variable = spec.offer_variable
if not variable:
@@ -145,7 +179,16 @@ def compute_offer(spec: CardSpec, context: Dict[str, Any]) -> Optional[int]:
return None # 재료 부족(앵커 미박제·직전 제안 없음)
if value > settle_ceiling(context):
return None # 타결 상한 초과 — 받아줄 수 없는 금액이라 지금 못 쓴다
offer = int(value / 10 + 0.5) * 10 # 10원 단위 반올림 — 앵커가·목표가 산정과 표기 통일
if variable in _MID_VARIABLES and value >= target:
# 절충 계열은 목표가 미만일 때만 의미가 있다. 목표가 이상이면 "절반씩 나누자"면서 목표가를
# 부르는 꼴이라 미발동 — 목표가 제시는 목표가 카드(최후통첩)가 할 일이다.
return None
if variable in ("target_price", "anchoring_price", "anchor_price"):
# 원값 인용 변수 — 멘트엔 {target_price} 등 저장 원값이 그대로 나가므로, 반올림하면
# 표시가≠타결가 미스매치가 난다(목표가 7652 멘트 → 7650 타결). 저장값 그대로 제시.
offer = int(value)
else:
offer = int(value / 10 + 0.5) * 10 # 파생가(절충·중간) 10원 반올림 — 앵커·목표가 산정과 표기 통일
if offer >= price:
return None # 제시가가 이미 그 값 이하 → 부를 이유 없음
if prev_customer and offer < prev_customer:
@@ -173,7 +216,7 @@ def playable(spec: CardSpec, context: Dict[str, Any], *, closing_phase: bool = F
금액을 인용하는 카드(offer_variable 있음)는 그 금액을 못 부르는 상황이면 설득 폴백으로도
내보내지 않는다 — 멘트에 무효한 금액(직전 제안보다 낮은 앵커, 제시가보다 높은 목표가)이
글자로 박혀 나가 역행/모순 서사가 되기 때문(IMK 역행 논의). 설득 카드는 금액이 없으니 무관.
글자로 박혀 나가 역행/모순 서사가 되기 때문. 설득 카드는 금액이 없으니 무관.
"""
if not available(spec, context, closing_phase=closing_phase):
return False
@@ -84,6 +84,7 @@ _NEGO_CARDS = table(
_WILD_CARDS = table(
"wild_cards",
column("wild_card_id"), column("number"), column("script"), column("tactic"), column("deleted"),
column("available"),
schema="card",
)
# 상품↔협력사 매핑 (2026-07-07 신설): supply_type = 이 협력사가 이 상품을 공급하는 방식(SupplierType).
@@ -374,6 +375,8 @@ class NegoContextCRUD(INegoContextCRUD):
_VERSION_WILD_CARDS.c.version_id == version_id,
_VERSION_WILD_CARDS.c.deleted == False, # noqa: E712
_WILD_CARDS.c.deleted == False, # noqa: E712
# 협상 적용 여부(카드 설정 '적용 대기(수동)') — 꺼진 카드는 견적에 담겨 있어도 발동 금지
_WILD_CARDS.c.available == True, # noqa: E712
)
.order_by(_VERSION_WILD_CARDS.c.created_at)
)
+45 -37
View File
@@ -11,11 +11,15 @@ from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
from negotiation.cards.domain.tactics import (
available, compute_offer, is_played, mark_played, playable, settle_ceiling, spec_from_context,
OFFER_VARIABLES, Offer, available, compute_offer_detail, is_played, mark_played, playable,
record_offer, settle_ceiling, spec_from_context,
)
from negotiation.chat.service.script_repository import ScriptRepository
MAX_ROUNDS = 3 # config 미주입 시 폴백 (규칙 정본은 tenant config negotiation.max_counter_rounds)
# 멘트에 찍히는 파생 가격 — 값이 다른 값에서 계산돼 나오는 것들(원값 인용 target/anchor 는 제외).
_DERIVED_PRICE_VARIABLES = ("target_mid_price", "middle_price")
_PRICE_MODES = ("price",)
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
@@ -131,8 +135,9 @@ class ChatEngine:
if price is None:
return self._error(session, "가격을 숫자로 입력해 주세요.")
session.context["input_price"] = price
# 새 가격 제시 = 직전 카운터 제안 거절 확정 → 대기 중 카운터 폐기.
# 새 가격 제시 = 직전 카운터 제안 거절 확정 → 대기 중 카운터·그 재료 폐기.
session.context.pop("pending_counter_price", None)
session.context.pop("pending_offer", None)
session.context["prev_partner_price"] = price
# 협력사 첫 제시가 — 가격 수용률(첫 제시가 대비 양보율) 동적 계산의 기준값.
session.context.setdefault("first_offer_price", price)
@@ -150,6 +155,7 @@ class ChatEngine:
# 원 제시가 수락 종결 — 는 카운터를 버리고 기존 input_price 로 타결한다.)
if mode in _CHOICE_MODES and nxt in _SUCCESS_STEPS:
pending = session.context.pop("pending_counter_price", None)
session.context.pop("pending_offer", None)
if pending and user_input in _ACCEPT_INPUTS:
session.context["input_price"] = float(pending)
return self._render(session, nxt)
@@ -240,7 +246,7 @@ class ChatEngine:
)
if exhausted:
# 타결선은 목표가가 아니라 타결 상한가(견적 생성 시 박제) — 목표가를 넘어도
# 상한 이내면 타결한다(IMK: 기존 단가보다 인하됐는데 결렬되던 케이스).
# 상한 이내면 타결한다.
ceiling = settle_ceiling(ctx)
if not ctx.get("closing_played"):
ctx["force_closing"] = True
@@ -255,12 +261,8 @@ class ChatEngine:
def _pick_wildcard(self, session: ChatSession) -> str:
"""앵커가에 아주 근접(≤ anchor×wildcard_1pct_ratio)한 구간에서만 1% 인하 요청(wild_card_1pct)으로
앵커가 이하로 유도한다. 그 외 구간은 일반 가격협상(카드 플레이)으로 돌린다.
과거 여기서 반환하던 '재원부족'(wild_card_budget) 하드코딩 카드는 제거했다 —
견적에서 실제 선택한 와일드카드(중간값 절충·목표가 선제안 등)와 매핑되지 않은 채
'와일드카드를 하나라도 골랐으면' 조건만으로 발동해, 선택하지도 않은 재원부족 멘트가
노출되는 오작동이 있었다.
앵커가 이하로 유도한다. 그 외 구간은 견적에서 선택한 와일드카드의 전술로 카운터하고,
낼 카드가 없으면 일반 가격협상(카드 플레이)으로 돌린다.
"""
ctx = session.context
price = ctx.get("input_price", 0)
@@ -268,15 +270,16 @@ class ChatEngine:
target = ctx.get("target_price", 0)
if anchor > 0 and price <= anchor * self.rules.wildcard_1pct_ratio:
offer_1pct = int(price * 0.99 / 10 + 0.5) * 10 # 1% 인하가 — 10원 반올림(앵커·카운터와 통일)
# 제안가 공통 유효조건(≤목표가 · <제시가)은 시스템 1% 카드에도 동일하게 건다.
# 기본 앵커 밴드에선 수학적으로 항상 통과하지만, 앵커율 0 등 극단 데이터를 방어한다.
if 0 < offer_1pct < price and (target <= 0 or offer_1pct <= target):
# 제안가 공통 유효조건(≤목표가 · <제시가 · 직전 당사 제안 이상=역행 금지)은 시스템 1% 카드에도
# 동일하게 건다. 기본 앵커 밴드에선 수학적으로 항상 통과하지만 극단 데이터를 방어한다.
prev_customer = ctx.get("prev_customer_price") or 0
if 0 < offer_1pct < price and (target <= 0 or offer_1pct <= target) and offer_1pct >= prev_customer:
# 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
# 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
ctx["wildcard_used"] = True
ctx["offer_1pct"] = offer_1pct
ctx["pending_counter_price"] = offer_1pct # 수락 시 이 가격으로 타결
ctx["prev_customer_price"] = offer_1pct # 갑의 최신 포지션 — 이후 절충가 계산 기준
record_offer(ctx, Offer(price=offer_1pct, variable="offer_1pct",
prev_customer=int(prev_customer or anchor), prev_partner=int(price)))
return "wild_card_1pct"
# 1.02 초과 ~ entry(1.05) 구간: 견적에서 선택한 와일드카드의 전술로 카운터 제시.
# (구현 전에는 이 구간이 일반 가격협상으로 회귀해 선택형 WC 가 영영 발동하지 않던 갭.)
@@ -288,11 +291,10 @@ class ChatEngine:
# 이미 쓴 카드도 제외(같은 멘트 반복 방지).
if not available(spec, ctx) or is_played(ctx, number):
continue
offer = compute_offer(spec, ctx)
offer = compute_offer_detail(spec, ctx)
if offer is not None:
ctx["wildcard_used"] = True
ctx["pending_counter_price"] = offer
ctx["prev_customer_price"] = offer # 갑의 최신 포지션 — "당사 제안 ○원" 멘트가 실제 이력과 일치
record_offer(ctx, offer)
ctx["active_wild_card_number"] = number
mark_played(ctx, number)
return "wild_card_dynamic"
@@ -341,25 +343,31 @@ class ChatEngine:
# 전술 카운터 변수(카드 시드 멘트의 가격 변수) — tactics.OFFER_VARIABLES 산식과 동일 정의.
anchor = ctx.get("anchor_price") or 0
target = ctx.get("target_price") or 0
if "input_price" in ctx:
out["prev_partner_price"] = int(ctx.get("prev_partner_price") or ctx["input_price"])
prev_customer = ctx.get("prev_customer_price") or anchor
# 표시 기준값 — 제안이 확정된 턴이면 그 계산에 쓴 재료(pending_offer)를 쓴다.
# prev_customer_price 는 확정 즉시 새 제안가로 갱신되므로, 그대로 읽으면 멘트가
# "당사 제안과 귀사 제안의 절반이 당사 제안" 같은 자기모순이 된다.
pending_offer = ctx.get("pending_offer") or {}
prev_customer = int(pending_offer.get("prev_customer") or ctx.get("prev_customer_price") or anchor or 0)
partner_price = int(pending_offer.get("prev_partner") or ctx.get("prev_partner_price") or ctx.get("input_price") or 0)
offer_price = int(pending_offer.get("price") or ctx.get("pending_counter_price") or 0)
offer_variable = pending_offer.get("variable") or ""
if prev_customer:
out["prev_customer_price"] = int(prev_customer)
if anchor and target:
out["target_mid_price"] = int(round((anchor + target) / 2))
if prev_customer and "input_price" in ctx:
out["middle_price"] = int(round((prev_customer + ctx["input_price"]) / 2))
if ctx.get("pending_counter_price"):
# 카운터 제시 중: 멘트에 보이는 제시가와 수락 시 타결가(pending)를 반드시 일치시킨다.
# 절충/중간 변수(middle_price·target_mid_price)는 vars_for 재계산 값이 compute_offer 의
# 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
out["prev_customer_price"] = prev_customer
if partner_price:
out["prev_partner_price"] = partner_price
if offer_price:
out["counter_price"] = offer_price
# 파생 가격(절충가·중간가) — 제안가로 확정된 변수는 그 금액을 그대로 쓴다(멘트에 보이는 금액과
# 수락 시 타결가는 항상 같아야 한다). 나머지는 참고 인용이므로 tactics 산식으로 채운다.
# 산식을 여기 복사해 두면 갱신 시점 차이로 표시가와 제안가가 갈라지므로 정의를 호출만 한다.
# 어느 변수가 제안가인지 모르는 진행 중 세션(구버전 기록)은 종전대로 전부 제안가로 고정한다.
for name in _DERIVED_PRICE_VARIABLES:
if offer_price and (name == offer_variable or not offer_variable):
out[name] = offer_price
continue
value = OFFER_VARIABLES[name](target, anchor, partner_price, prev_customer)
if value:
out[name] = int(value / 10 + 0.5) * 10 # 10원 반올림 — compute_offer 와 동일
# 인하율 = (협상 기준가 - 제시가) / 기준가 * 100. 기준가 없으면 미표시(0.0).
# 제시가가 기준가보다 높으면(인상 제시) 음수가 나오는데, "-1.3% 인하된 금액" 같은
# 모순 표현이 되므로 discount_rate 는 0 미만 금지하고, 인상/동일/인하를 구분한
@@ -395,8 +403,8 @@ class ChatEngine:
return self._error(session, f"다음 단계를 찾을 수 없습니다: {step_key}")
# 가드레일(최후 방어선): 구매자 대리는 타결 상한가를 넘겨 타결하지 않는다.
# 상한 = 견적 생성 시 박제한 done_ceiling_price(목표가×(1+타결상한율)), 미박제면 목표가.
# 목표가를 조금 넘어도 상한 이내면 타결이 정상이므로(IMK: 기존 단가보다 인하됐는데
# 결렬되던 케이스) 여기서 뒤집으면 안 된다. 상한까지 넘은 경우만 결렬로 강제 전환한다.
# 목표가를 조금 넘어도 상한 이내면 타결이 정상이므로 여기서 뒤집지 않는다.
# 상한까지 넘은 경우만 결렬로 강제 전환한다.
if step_key in _SUCCESS_STEPS and self.rq_type == "재협상":
ctx = session.context
ceiling = settle_ceiling(ctx)
+18 -13
View File
@@ -13,7 +13,9 @@ from common.enums import DBType, ErrorType
from common.database.db_session_manager import DB_SESSION_MNG
from common.logger import LOG
from config.server_configs import agent_config
from negotiation.cards.domain.tactics import available, compute_offer, is_played, mark_played, playable, spec_from_context
from negotiation.cards.domain.tactics import (
Offer, available, compute_offer_detail, is_played, mark_played, playable, record_offer, spec_from_context,
)
from negotiation.chat.service.chat_engine import (
_CHOICE_MODES, _PRICE_MODES, ChatEngine, ChatSession, StepView,
)
@@ -309,10 +311,10 @@ class ChatService:
# 협력사가 수락하면 이 가격으로 즉시 타결된다(chat_engine 의 수락 메커니즘).
# 유효조건(≤목표가 · <제시가) 미달이면 None → 금액 없이 설득 멘트만 나간다(HOLD 강등).
spec = spec_from_context(session.context, card_id)
counter = compute_offer(spec, session.context) if available(spec, session.context) else None
if counter is not None:
session.context["pending_counter_price"] = counter
session.context["prev_customer_price"] = counter # 갑의 최신 포지션(절충가 계산 기준)
offer = compute_offer_detail(spec, session.context) if available(spec, session.context) else None
counter = offer.price if offer else None
if offer is not None:
record_offer(session.context, offer)
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=reward.total, done=False))
await QTablePolicyStore.persist_cell(repo, version_id, policy, idx, decision.action_id)
@@ -369,26 +371,29 @@ class ChatService:
ctx["closing_played"] = True
# 선택 와일드카드 중 종결 전용 카드(closing) — 이미 쓴 카드는 건너뛰고(같은 멘트 반복 방지),
# 제안가 유효조건(≤목표가 · <제시가) 미달 카드도 건너뛴다(예: 절충가가 목표가 초과 → 미발동).
closing_number, counter = None, None
closing_number, closing_offer = None, None
for n in (ctx.get("selected_wild_card_numbers") or []):
n = str(n)
spec = spec_from_context(ctx, n)
if not available(spec, ctx, closing_phase=True) or is_played(ctx, n):
continue
offer = compute_offer(spec, ctx)
offer = compute_offer_detail(spec, ctx)
if offer is not None:
closing_number, counter = n, offer
closing_number, closing_offer = n, offer
break
if counter is None:
if closing_offer is None:
# 폴백 최후통첩: 목표가 제시 (여기 도달 = 제시가 > target 이므로 항상 유효한 카운터).
closing_number = None
target = int(ctx.get("target_price") or 0)
counter = target if 0 < target < ctx.get("input_price", 0) else None
if counter is None:
price = int(ctx.get("input_price") or 0)
if 0 < target < price:
closing_offer = Offer(price=target, variable="target_price",
prev_customer=int(ctx.get("prev_customer_price") or ctx.get("anchor_price") or 0),
prev_partner=price)
if closing_offer is None:
return # 컨텍스트 이상 — 기존 가격협상 스텝 그대로(재제안 요구)
mark_played(ctx, closing_number) # None(폴백 최후통첩)이면 no-op
ctx["pending_counter_price"] = counter
ctx["prev_customer_price"] = counter
record_offer(ctx, closing_offer)
template = None
if closing_number:
+37 -23
View File
@@ -1,18 +1,33 @@
from abc import ABC, abstractmethod
from typing import Tuple
from typing import Optional, Tuple
from sqlalchemy import case, cast, func, nulls_last, or_, select, text, update
from sqlalchemy import and_, 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.database.model.models import chats, items, quotations, sessions
from common.enums import CloseReason, ErrorType, QuotationStatus, RENEGOTIABLE_CLOSE_REASONS, SessionStatus
from common.logger import LOG
# 협상 세션 CRUD. 목록은 세션(negotiation) ⨝ 상품(partner) ⨝ 견적(quotation) 조인으로 만든다.
# 마감일(qt_end_time)은 견적(quotation.end_time)이 진실값이다(session.end_time 은 협상 종료 시점 기록용).
def _effective_status():
"""표시용 세션 상태. 견적이 마감됐거나 마감시간이 지났으면 협상생성(1)은 더 참여할 수 없으므로 미참여(4)로 본다.
참여/채팅진입이 진입 시점에 하는 전이(negotiation_service._load_actionable_session, chat_service.init)와 같은 규칙을
목록에서는 쓰기 없이 파생으로만 맞춘다. 마감 일괄정리 이후에 만들어진 세션도 '협상 대기'로 남지 않는다.
"""
ended = or_(quotations.status == QuotationStatus.CLOSED.value, quotations.end_time < func.now())
return case(
(and_(sessions.status == SessionStatus.CREATED.value, ended), SessionStatus.NOT_PARTICIPATED.value),
else_=sessions.status,
)
class ISessionCRUD(ABC):
@abstractmethod
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
@@ -39,7 +54,9 @@ class ISessionCRUD(ABC):
pass
@abstractmethod
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
async def update_session_reject(
self, cdb: AsyncSession, session_id, status: int, reject_reason: str, reject_price: Optional[int] = None,
) -> ErrorType:
pass
@abstractmethod
@@ -47,19 +64,6 @@ class ISessionCRUD(ABC):
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
@@ -73,7 +77,8 @@ class SessionCRUD(ISessionCRUD):
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)
# 표시 상태로 필터 — 탭/KPI 카운트가 목록 배지와 어긋나지 않게 파생값을 그대로 쓴다.
conds.append(_effective_status() == status)
if qt_type is not None:
conds.append(sessions.qt_type == qt_type)
# 검색: 견적번호·상품명·상품코드 부분일치(대소문자 무시). items 는 목록/카운트 둘 다 조인돼 있다.
@@ -113,7 +118,7 @@ class SessionCRUD(ISessionCRUD):
else:
# 그룹별로 정렬 방향이 달라, case 로 '자기 그룹 행만 end_time' 을 갖는 키를 만들고
# 반대 그룹은 NULL 로 눌러 간섭을 없앤다. status_rank 가 1차 키라 그룹 경계는 항상 유지.
actionable = sessions.status.in_((SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value))
actionable = _effective_status().in_((SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value))
status_rank = case((actionable, 0), else_=1)
action_order = case((actionable, quotations.end_time), else_=None).asc()
done_order = case((~actionable, quotations.end_time), else_=None).desc()
@@ -122,7 +127,7 @@ class SessionCRUD(ISessionCRUD):
query = (
select(
sessions.session_id,
sessions.status,
_effective_status(), # 마감 후 남은 협상생성은 미참여로 내린다
sessions.qt_type,
sessions.qt_number,
quotations.end_time, # qt_end_time = 견적 마감 시각
@@ -136,6 +141,8 @@ class SessionCRUD(ISessionCRUD):
quotations.round,
quotations.preferred_sp_id, # 낙찰자(공급사) — 나와 같으면 낙찰, 다르면 미낙찰
sessions.supplier_id, # 이 세션 소유 공급사(=조회자). 낙찰자와 대조
# 대화 이력 유무 — 종료된 협상의 '결과 보기'(열람) 버튼을 띄울지 판단용. 열 게 없으면 프론트가 감춘다.
select(1).where(chats.session_id == sessions.session_id, chats.deleted == False).exists(), # noqa: E712
)
.join(items, items.item_id == sessions.item_id)
.join(quotations, quotations.qt_id == sessions.quotation_id)
@@ -212,12 +219,18 @@ class SessionCRUD(ISessionCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
async def update_session_reject(
self, cdb: AsyncSession, session_id, status: int, reject_reason: str, reject_price: Optional[int] = None,
) -> ErrorType:
try:
values = {"status": status, "reject_reason": reject_reason}
# 공급 희망 가격은 채팅 중 거부에서만 들어온다 — 목록 거부는 가격 없이 사유만 남긴다.
if reject_price is not None:
values["reject_price"] = reject_price
query = (
update(sessions)
.where(sessions.session_id == session_id)
.values(status=status, reject_reason=reject_reason)
.values(**values)
)
return await DB_SESSION_MNG.add(cdb, query)
except Exception as ex:
@@ -231,7 +244,8 @@ class SessionCRUD(ISessionCRUD):
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
# 단일 컬럼 select 는 scalars() 로 내려와 rows 가 값 리스트다(행 튜플이 아님).
top = rows[0] if rows else None
return ErrorType.SUCCESS, int(top or 0)
except Exception as ex:
LOG.e_no_callstack(ex)
@@ -21,6 +21,7 @@ class ListItem(WebPacketProtocol):
renegotiation_status: int = Field(0, description="현재 재협상 요청 상태(RenegotiationStatus). 요청 이력이 없으면 0")
renegotiation_memo: str = Field("", description="담당자 심사 메모(반려 사유). 없으면 빈 문자열")
result: int = Field(0, description="공급사 관점 협상 결과(SessionResult): 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰, 재협상 대상)")
has_chat: bool = Field(False, description="대화 이력 존재 여부 — 종료된 협상(미참여·거부)의 '결과 보기' 노출 판단용")
class Res_SessionList(Res_WebPacketProtocol):
@@ -36,6 +37,8 @@ class Res_Participate(Res_WebPacketProtocol):
class Req_Reject(WebPacketProtocol):
reject_reason: str = Field("", max_length=255, description="거부 사유 (단종/품절 프리셋 라벨 또는 직접 입력)")
reject_price: Optional[int] = Field(None, description="공급 희망 가격(원). 채팅 중 거부에서만 들어온다 — 목록 거부엔 없음")
opinion: Optional[str] = Field(None, max_length=255, description="추가 의견 — sessions.custom.opinion 에 병합")
class Res_Reject(Res_WebPacketProtocol):
+6 -2
View File
@@ -62,7 +62,7 @@ async def participate(
path="/sessions/{session_id}/reject",
response_model=Res_Reject,
summary="협상 거부",
description="세션 참여를 거부한다. 소유(공급사)·세션상태(완료/미참여/거부 불가)·견적마감·마감시간 검증 후 협상거부로 전이하고 사유를 저장.",
description="세션 참여를 거부하거나 진행 중인 협상을 거부한다. 소유(공급사)·세션상태(완료/미참여/거부 불가)·견적마감·마감시간 검증 후 협상거부로 전이하고 사유·공급 희망 가격·의견을 저장.",
)
async def reject(
session_id: str = Path(description="대상 협상 세션 uuid"),
@@ -71,7 +71,11 @@ async def reject(
credentials: HTTPAuthorizationCredentials = Depends(security),
service: NegotiationService = Depends(),
):
return RemoveNoneResponse(await service.reject(user_info, credentials.credentials, session_id, req.reject_reason))
return RemoveNoneResponse(
await service.reject(
user_info, credentials.credentials, session_id, req.reject_reason, req.reject_price, req.opinion,
)
)
@router.post(
+2 -5
View File
@@ -227,11 +227,8 @@ class ChatService:
)
sess.status = SessionStatus.NOT_PARTICIPATED.value
# 미참여/협상거부 상태는 진입(열람) 불가 (participate/reject 와 동일 규칙).
# 위 마감 변환으로 미참여가 된 세션도 여기서 함께 막힌다.
if sess.status in (SessionStatus.NOT_PARTICIPATED.value, SessionStatus.REJECTED.value):
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
return res
# 미참여/협상거부 세션도 '결과 보기'로 지난 대화를 열람할 수 있다(중간 이탈·거부로 끝난 건).
# 대화 재개는 send() 가 협상중(2)만 허용하므로 여기서 막지 않아도 읽기 전용이다.
await self._ensure_in_progress(sess, quote)
+19 -6
View File
@@ -1,5 +1,6 @@
import uuid
from datetime import datetime, timezone
from typing import Optional
from fastapi import Depends
@@ -182,6 +183,7 @@ class NegotiationService:
renegotiation_status=status,
renegotiation_memo=renego.get("memo") or "",
result=NegotiationService._to_result(r[10], r[11], r[13], r[14]),
has_chat=bool(r[15]),
)
@staticmethod
@@ -434,7 +436,10 @@ class NegotiationService:
res.session_id = str(sess.session_id)
return res
async def reject(self, user_info: UserInfo, access_token: str, session_id_str: str, reject_reason: str) -> Res_Reject:
async def reject(
self, user_info: UserInfo, access_token: str, session_id_str: str, reject_reason: str,
reject_price: Optional[int] = None, opinion: Optional[str] = None,
) -> Res_Reject:
res = Res_Reject()
# 거부 사유 필수
@@ -454,11 +459,19 @@ class NegotiationService:
res.result.SetResult(err_type)
return res
# 거부 처리 — 세션을 협상거부로 전이하고 사유 저장
err_type = await DB_SESSION_MNG.execute_lambda_run(
[sessions.DBType()],
[lambda s: self.session_crud.update_session_reject(s, sess.session_id, SessionStatus.REJECTED.value, reason)],
)
# 거부 처리 — 세션을 협상거부로 전이하고 사유·공급 희망 가격 저장.
# 의견은 부가정보와 같은 custom 컬럼이라 병합(덮어쓰기 금지) — 채팅 결렬 폼과 같은 자리.
funcs = [
lambda s: self.session_crud.update_session_reject(
s, sess.session_id, SessionStatus.REJECTED.value, reason, reject_price,
)
]
note = (opinion or "").strip()[:255]
if note:
funcs.append(
lambda s: self.session_crud.merge_session_custom(s, sess.session_id, sess.supplier_id, {"opinion": note})
)
err_type = await DB_SESSION_MNG.execute_lambda_run([sessions.DBType()], funcs)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
+10 -5
View File
@@ -380,23 +380,28 @@ async def test_send_blocked_when_prev_turn_pending(client, chat_seed, db_engine)
async def test_init_marks_expired_created_as_not_participated(client, chat_seed, db_engine):
"""검증: 마감시간이 지난 협상생성 세션으로 채팅 진입.
기대결과: DB 상태가 미참여(4)로 정리되고, init 자체는 열람용으로 성공한다."""
token = await _login_token(client)
sid, qid = chat_seed["sids"]["C"], chat_seed["qids"]["C"] # 협상생성(1)
async with db_engine.begin() as conn:
await conn.execute(text("UPDATE quotation.quotations SET end_time = now() - make_interval(hours => 1) WHERE qt_id = :qid"), {"qid": qid})
body = (await _init(client, token, sid)).json()
# 마감된 협상생성은 DB 상 미참여로 정리되고, 미참여는 진입 불가라 init 은 에러로 막는다.
assert body["result"]["code"] == 1301 # NEGO_NOT_PARTICIPABLE
assert await _session_status(db_engine, sid) == 4 # DB 는 미참여로 전이됨
assert body["result"]["success"] is True
assert body["session_status"] == 4
assert await _session_status(db_engine, sid) == 4 # DB 도 미참여로 전이
async def test_init_blocks_rejected_session(client, chat_seed, db_engine):
async def test_init_allows_viewing_rejected_session(client, chat_seed, db_engine):
"""검증: 협상거부(5)로 끝난 세션에 '결과 보기'로 재진입.
기대결과: init 성공(열람 허용) — 대화 재개는 send 가 협상중만 허용해 막는다."""
token = await _login_token(client)
sid = chat_seed["sids"]["P"]
async with db_engine.begin() as conn:
await conn.execute(text("UPDATE negotiation.sessions SET status = 5 WHERE session_id = :sid"), {"sid": sid}) # 협상거부
body = (await _init(client, token, sid)).json()
assert body["result"]["code"] == 1301 # NEGO_NOT_PARTICIPABLE — 거부 세션 진입 차단
assert body["result"]["success"] is True and body["session_status"] == 5
assert (await _send(client, token, sid, "네")).json()["result"]["code"] == 1400 # CHAT_NOT_IN_PROGRESS
# ---- 순수 헬퍼 단위 테스트 (DB 불필요, ChatService @staticmethod) ----------
+128 -25
View File
@@ -16,6 +16,35 @@ TEST_SUPPLIER_NAME = "파이테스트협상공급사"
MARK = "PYTESTNEGO-" # 시드 식별용 prefix (item code / qt number)
async def _seed_case(conn, code, sess_st, qt_type, hrs, quote_st, sup):
"""상품·견적·세션 1세트 시드. 코드/견적번호에 MARK prefix 를 달아 cleanup 이 함께 지운다.
hrs 는 마감(quotation.end_time)까지의 시간 — 음수면 이미 마감시간이 지난 건. 반환: (session_id, qt_id)."""
item_id, qt_id, session_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
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, start_time, end_time) "
"VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, :tp, :st, now(), now() + make_interval(hours => :hrs))"
),
{"qid": qt_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "tp": qt_type, "st": quote_st, "hrs": hrs},
)
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, end_time) "
"VALUES (:sesid, :qid, :iid, :sup, :qtn, 1, :qtt, 100000, :st, now())"
),
{"sesid": session_id, "qid": qt_id, "iid": item_id, "sup": sup, "qtn": f"{MARK}{code}", "qtt": qt_type, "st": sess_st},
)
return session_id, qt_id
@pytest_asyncio.fixture
async def nego_seed(db_engine):
"""공급사 + 유저 + 세션/견적 3건(본인) + 1건(타 공급사) 시드. 세션/견적 id 를 반환."""
@@ -33,6 +62,11 @@ async def nego_seed(db_engine):
sids, qids = {}, {}
async def _cleanup(conn):
# 대화는 세션보다 먼저 지운다(세션이 사라지면 대상을 못 고른다).
await conn.execute(text(
f"DELETE FROM negotiation.chats WHERE session_id IN "
f"(SELECT session_id FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%')"
))
await conn.execute(text(f"DELETE FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%'"))
await conn.execute(text(f"DELETE FROM quotation.quotations WHERE number LIKE '{MARK}%'"))
await conn.execute(text(f"DELETE FROM partner.items WHERE code LIKE '{MARK}%'"))
@@ -52,31 +86,9 @@ async def nego_seed(db_engine):
),
{"sid": supplier_id, "id": TEST_LOGIN_ID, "pw": pw_hash},
)
for code, sess_st, qt_type, hrs, quote_st, sup in specs:
item_id, qt_id, session_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
sids[code], qids[code] = session_id, qt_id
await conn.execute(
text(
"INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) "
"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, start_time, end_time) "
"VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, :tp, :st, now(), now() + make_interval(hours => :hrs))"
),
{"qid": qt_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "tp": qt_type, "st": quote_st, "hrs": hrs},
)
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, end_time) "
"VALUES (:sesid, :qid, :iid, :sup, :qtn, 1, :qtt, 100000, :st, now())"
),
{"sesid": session_id, "qid": qt_id, "iid": item_id, "sup": sup, "qtn": f"{MARK}{code}", "qtt": qt_type, "st": sess_st},
)
for spec in specs:
code = spec[0]
sids[code], qids[code] = await _seed_case(conn, *spec)
yield {"supplier_id": supplier_id, "sids": sids, "qids": qids}
@@ -141,6 +153,63 @@ async def test_list_filter_status(client, nego_seed):
assert body["total"] == 1 and body["items"][0]["item_code"] == f"{MARK}B"
async def test_list_shows_closed_quotation_created_session_as_not_participated(client, db_engine, nego_seed):
"""검증: 견적이 마감(3)된 뒤에도 세션이 협상생성(1)으로 남아 있는 건(마감 일괄정리 이후 생성 등).
기대결과: 목록 상태는 미참여(4) — '협상 대기'로 새지 않고, status=1 필터에서도 빠지고 status=4 필터에 잡힌다."""
async with db_engine.begin() as conn:
await _seed_case(conn, "CLOSED1", 1, 2, -1, 3, nego_seed["supplier_id"])
token = await _login_token(client)
listed = next(i for i in (await _list(client, token)).json()["items"] if i["item_code"] == f"{MARK}CLOSED1")
assert listed["session_status"] == 4
waiting = (await _list(client, token, status=1)).json()
assert waiting["total"] == 1 and {i["item_code"] for i in waiting["items"]} == {f"{MARK}A"}
assert f"{MARK}CLOSED1" in {i["item_code"] for i in (await _list(client, token, status=4)).json()["items"]}
async def test_list_shows_deadline_passed_created_session_as_not_participated(client, db_engine, nego_seed):
"""검증: 견적은 아직 진행중(2)인데 마감시간(end_time)만 지난 협상생성 세션.
기대결과: 미참여(4) — 참여/입장이 막히는 건이라 목록도 같은 상태로 보인다(DB 값은 그대로)."""
async with db_engine.begin() as conn:
session_id, _ = await _seed_case(conn, "OVERDUE", 1, 2, -3, 2, nego_seed["supplier_id"])
token = await _login_token(client)
listed = next(i for i in (await _list(client, token)).json()["items"] if i["item_code"] == f"{MARK}OVERDUE")
assert listed["session_status"] == 4
assert await _session_status(db_engine, session_id) == 1 # 목록은 파생 표시만, 쓰기는 하지 않는다
async def test_list_marks_stale_round_not_renegotiable(client, db_engine, nego_seed):
"""검증: 개찰(결렬) 마감된 1차 견적에 2차가 이미 생성돼 있는 체인.
기대결과: renegotiable False — 다음 라운드가 있으면 재협상 요청 대상이 아니다(체인 최대 차수 판정)."""
async with db_engine.begin() as conn:
await _seed_case(conn, "CHAIN", 3, 2, -2, 3, nego_seed["supplier_id"])
await conn.execute(text(
f"UPDATE quotation.quotations SET close_reason = 5 WHERE number = '{MARK}CHAIN'"))
# 같은 견적번호의 2차 — 번호가 같아야 체인으로 묶인다.
await conn.execute(text(
"INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, round, start_time, end_time) "
f"VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), '견적 CHAIN 2차', '{MARK}CHAIN', 2, 2, 2, now(), now() + make_interval(hours => 2))"))
token = await _login_token(client)
listed = next(i for i in (await _list(client, token)).json()["items"] if i["item_code"] == f"{MARK}CHAIN")
assert listed["result"] == 3 and listed["renegotiable"] is False
async def test_list_has_chat_flags_sessions_with_history(client, db_engine, nego_seed):
"""검증: 대화 이력이 있는 세션과 없는 세션의 has_chat.
기대결과: 이력 있는 건만 True — 종료 건의 '결과 보기' 노출이 이 값으로 갈린다."""
async with db_engine.begin() as conn:
await conn.execute(
text("INSERT INTO negotiation.chats (session_id, seq, sender, target_price) VALUES (:sid, 1, 1, 0)"),
{"sid": nego_seed["sids"]["C"]},
)
token = await _login_token(client)
by_code = {i["item_code"]: i["has_chat"] for i in (await _list(client, token)).json()["items"]}
assert by_code[f"{MARK}C"] is True
assert by_code[f"{MARK}A"] is False
async def test_list_filter_qt_type(client, nego_seed):
token = await _login_token(client)
body = (await _list(client, token, qt_type=2)).json()
@@ -316,6 +385,40 @@ async def test_reject_success(client, nego_seed, db_engine):
assert status == 5 and reason == "단종 상품입니다" # REJECTED + 사유 저장
async def test_reject_with_price_and_opinion(client, nego_seed, db_engine):
# 채팅 내 협상 거부 경로 — 사유 외에 공급 희망 가격과 의견까지 함께 남긴다.
token = await _login_token(client)
sid = nego_seed["sids"]["B"]
r = await client.post(
f"/v1/negotiation/sessions/{sid}/reject",
headers={"Authorization": f"Bearer {token}"},
json={"reject_reason": "품절", "reject_price": 88000, "opinion": "대체품으로 재견적 부탁드립니다"},
)
assert r.json()["result"]["success"] is True
async with db_engine.begin() as conn:
row = (await conn.execute(
text("SELECT status, reject_reason, reject_price, custom FROM negotiation.sessions WHERE session_id = :sid"),
{"sid": sid},
)).first()
assert row.status == 5 and row.reject_reason == "품절"
assert row.reject_price == 88000
assert row.custom["opinion"] == "대체품으로 재견적 부탁드립니다"
async def test_reject_without_price_keeps_null(client, nego_seed, db_engine):
# 목록 거부 경로 — 가격이 없으면 reject_price 를 건드리지 않는다.
token = await _login_token(client)
sid = nego_seed["sids"]["B"]
r = await _reject(client, token, sid, "단종")
assert r.json()["result"]["success"] is True
async with db_engine.begin() as conn:
row = (await conn.execute(
text("SELECT reject_price, custom FROM negotiation.sessions WHERE session_id = :sid"),
{"sid": sid},
)).first()
assert row.reject_price is None and row.custom is None
async def test_reject_empty_reason(client, nego_seed):
token = await _login_token(client)
r = await _reject(client, token, nego_seed["sids"]["B"], " ") # 공백만 → 사유 없음
@@ -62,6 +62,7 @@ export interface SessionListItem {
renegotiation_status: number // 1=심사대기 2=승인 3=반려 4=철회, 이력 없으면 0
renegotiation_memo: string // 담당자 심사 메모(반려 사유)
result: number // 협상 결과(SessionResult): 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰)
has_chat: boolean // 대화 이력 존재 여부 — 종료된 협상의 '결과 보기' 노출 판단용
}
/** 공급사 관점 협상 결과 (sessions 파생) */
@@ -118,10 +119,13 @@ export interface ParticipateResponse {
}
// --- 거부 (POST /v1/negotiation/sessions/{id}/reject) ---------------------
// 목록의 협상 거부와 채팅 중 협상 거부가 같은 엔드포인트를 쓴다.
// reject_reason: 프리셋(단종/품절) 라벨 또는 '기타' 직접 입력 텍스트.
// (백엔드 sessions.reject_reason 컬럼에 대응. 엔드포인트는 백엔드 추가 예정)
// reject_price/opinion: 채팅 중 거부에서만 채운다(목록 거부는 사유만).
export interface RejectRequest {
reject_reason: string
reject_price?: number
opinion?: string
}
export interface RejectResponse {
@@ -1,10 +1,33 @@
import { useState } from 'react'
import { SessionStatus } from '@/apis'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
import { ChatMessage } from '@/features/chat/components/ChatMessage'
import { UserButton } from '@/features/chat/components/UserButton'
import { RejectPopup } from '@/features/chat/components/popup/RejectPopup'
import { canRejectNegotiation, GO_TO_LIST_TEXT } from '@/features/chat/lib/userButtonConfig'
import { MobileStepBar } from '@/features/chat/components/MobileStepBar'
import type { UserButtonConfig } from '@/features/chat/types'
// 미참여·협상거부로 끝난 세션은 '결과 보기'(열람) 진입이라 입력을 잠근다.
// 마지막 봇 메시지가 입력을 요구하는 상태로 멈춰 있어도(중간 이탈) 서버가 전송을 막으므로 액션바는 복귀 버튼만 둔다.
const READ_ONLY_STATUSES: number[] = [SessionStatus.NOT_PARTICIPATED, SessionStatus.REJECTED]
const READ_ONLY_CONFIG: UserButtonConfig = { type: 'one-black', text: GO_TO_LIST_TEXT }
// 거부 가능한 세션 상태 — 백엔드 /reject 가 허용하는 범위(완료/미참여/거부는 불가)와 같다.
const REJECTABLE_STATUSES: number[] = [SessionStatus.CREATED, SessionStatus.IN_PROGRESS]
export function ChatSection() {
const { userButtonConfig } = useChatStore()
const { messages, userButtonConfig } = useChatStore()
const sessionStatus = useChatInitStore((s) => s.session_status)
const [isRejectOpen, setIsRejectOpen] = useState(false)
const isReadOnly = READ_ONLY_STATUSES.includes(sessionStatus)
const config = isReadOnly ? READ_ONLY_CONFIG : userButtonConfig
// 단종·품절처럼 대화로 풀 수 없는 사유는 봇의 결렬 선언을 기다릴 수 없다 — 진행 중에도 빠져나갈 길을 둔다.
const canReject =
!isReadOnly && REJECTABLE_STATUSES.includes(sessionStatus) && canRejectNegotiation(messages, userButtonConfig)
return (
<div className="flex flex-1 flex-col w-full h-full min-h-0 bg-surface">
<MobileStepBar />
@@ -12,8 +35,9 @@ export function ChatSection() {
{/* 하단 액션 덱 */}
{/* safe-b: 홈 인디케이터에 입력 버튼이 가리지 않도록 하단 안전영역 확보 */}
<div className="shrink-0 safe-b border-t border-border bg-white shadow-[0_-4px_20px_rgba(0,0,0,0.03)]">
<UserButton {...userButtonConfig} />
<UserButton {...config} onReject={canReject ? () => setIsRejectOpen(true) : undefined} />
</div>
{isRejectOpen && <RejectPopup onClose={() => setIsRejectOpen(false)} />}
</div>
)
}
@@ -17,7 +17,8 @@ const style = {
'flex min-w-[120px] px-[28px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[46px] bg-white hover:bg-neutral-10 rounded-xl items-center justify-center text-sm font-bold text-neutral-80 border border-border cursor-pointer whitespace-nowrap transition-all ease-out active:scale-[0.98]',
}
export function UserButton({ type, text, textList, priceErrorMessage }: UserButtonConfig) {
// onReject: 협상 거부 진입점. 넘어오면 버튼 덱 끝에 붙는다(입력 단계는 인풋이 넓어 좁은 화면에서 아랫줄로 wrap).
export function UserButton({ type, text, textList, priceErrorMessage, onReject }: UserButtonConfig & { onReject?: () => void }) {
if (type === '') return null
// 부가정보 입력은 폼이라 가운데정렬 덱이 아니라 전체폭으로 편다. text = 저장 후 보낼 동의 문구.
@@ -41,8 +42,13 @@ export function UserButton({ type, text, textList, priceErrorMessage }: UserButt
// 입력 단계는 에러 말풍선이 위로 삐져나가야 해서 overflow 클리핑 제외 (버튼 덱만 가로 스크롤 허용)
const isInputStep = type === 'percent' || type === 'price'
return (
<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">
<div
className={cn(
'relative flex w-full flex-wrap items-center justify-center gap-3 px-6 py-4 max-[1180px]:px-4',
!isInputStep && 'overflow-x-auto',
)}
>
<div className="flex items-center justify-center gap-3">
{type === 'one-black' && <OneBlack text={text || '확인'} />}
{type === 'one-gray' && <OneGray text={text || '확인'} />}
{type === 'black-white' && <BlackWhite textList={[textList?.[0] || '예', textList?.[1] || '아니오']} />}
@@ -53,6 +59,19 @@ export function UserButton({ type, text, textList, priceErrorMessage }: UserButt
{type === 'price' && <Price priceErrorMessage={priceErrorMessage} />}
{type === 'loading' && <LoadingDots />}
</div>
{/* 오클릭 방지: 주 CTA 와 붙이지 않는다. 넓은 화면은 우측 끝 고정(가운데 CTA 는 그대로),
좁은 화면은 인풋 폭 때문에 같은 줄이 안 나오므로 wrap 되어 아랫줄로 내려간다. */}
{onReject && (
<button
className={cn(
style.white,
'min-[1180px]:absolute min-[1180px]:right-8 min-[1180px]:top-1/2 min-[1180px]:-translate-y-1/2',
)}
onClick={onReject}
>
협상 거부
</button>
)}
</div>
)
}
@@ -0,0 +1,210 @@
import { useState } from 'react'
import { useNavigate } from 'react-router'
import { X } from 'lucide-react'
import { Modal } from '@/components'
import { getApiErrorMessage, useRejectMutation } from '@/apis'
import { cn, toast } from '@/lib'
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
const MAX_PRICE = 999999999999999
// 사유 목록은 목록 화면의 거부 팝업과 동일하게 맞춘다.
const REASONS = ['단종', '품절', '기타'] as const
// 협상 진행 중 거부 팝업 — 목록의 거부 팝업과 같은 어휘·같은 엔드포인트를 쓰고,
// 대화 중이라 이미 오간 가격이 있으므로 공급 희망 가격과 의견을 더 받는다.
export function RejectPopup({ onClose }: { onClose: () => void }) {
const navigate = useNavigate()
const reject = useRejectMutation()
const sessionId = useChatStore((s) => s.sessionId)
const itemVatYn = useChatInitStore((s) => s.item_vat_yn)
const isVAT = itemVatYn === 'VAT별도'
const [selectedReason, setSelectedReason] = useState<string | null>(null)
const [customReason, setCustomReason] = useState('')
const [price, setPrice] = useState('')
const [opinion, setOpinion] = useState('')
const [showError, setShowError] = useState(false)
const isEtcOpen = selectedReason === '기타'
const isPending = reject.isPending
const isSubmitDisabled = !selectedReason || (isEtcOpen && !customReason.trim()) || isPending
const handleReasonClick = (reason: string) => {
setShowError(false)
if (selectedReason === reason) {
setSelectedReason(null)
setCustomReason('')
} else {
setSelectedReason(reason)
if (reason !== '기타') setCustomReason('')
}
}
const handlePriceChange = (value: string) => {
const numeric = value.replace(/\D/g, '')
if (numeric && parseInt(numeric) > MAX_PRICE) return
setPrice(numeric)
}
const handleSubmit = () => {
if (isEtcOpen && !customReason.trim()) {
setShowError(true)
return
}
if (isSubmitDisabled || !selectedReason) return
reject.mutate(
{
sessionId,
request: {
reject_reason: isEtcOpen ? customReason.trim() : selectedReason,
// 선택 입력 — 빈 값이면 보내지 않아 컬럼을 건드리지 않는다.
...(price ? { reject_price: parseInt(price) } : {}),
...(opinion.trim() ? { opinion: opinion.trim() } : {}),
},
},
{
onSuccess: () => {
onClose()
toast.warning('협상 거부가 완료되었습니다.')
navigate('/list')
},
onError: (error) => toast.error(getApiErrorMessage(error, '거부 처리에 실패했습니다.')),
},
)
}
const koreanPrice = price && parseInt(price) > 0 ? `[${numberToKorean(parseInt(price))} 원]` : ''
return (
<Modal onClose={onClose}>
<div className="flex max-h-[85vh] w-full max-w-md flex-col overflow-hidden rounded-2xl border border-border bg-white shadow-xl animate-scale-in">
{/* 헤더 */}
<div className="flex shrink-0 items-center justify-between border-b border-border p-5">
<h3 className="text-base font-bold text-neutral-90">거부 사유를 입력해주세요</h3>
<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="min-h-0 flex-1 space-y-4 overflow-y-auto p-5">
<div className="grid grid-cols-3 gap-2">
{REASONS.map((reason) => (
<button
key={reason}
type="button"
onClick={() => handleReasonClick(reason)}
disabled={isPending}
className={cn(
'h-11 rounded-xl border text-sm font-bold transition-all active:scale-[0.98] disabled:opacity-50',
selectedReason === reason
? 'border-brand-600 bg-brand-light text-brand-600'
: 'border-border bg-white text-neutral-70 hover:bg-neutral-10',
)}
>
{reason}
</button>
))}
</div>
{isEtcOpen && (
<div className="animate-fade-in">
<textarea
placeholder="사유를 입력하여 주십시오"
value={customReason}
onChange={(e) => {
setCustomReason(e.target.value)
setShowError(false)
}}
rows={3}
disabled={isPending}
className={cn(
'w-full resize-none rounded-xl border bg-white p-3 text-sm text-neutral-90 outline-none transition-all',
'placeholder:text-neutral-50 focus:ring-1',
showError
? 'border-destructive focus:border-destructive focus:ring-destructive'
: 'border-border focus:border-brand-600 focus:ring-brand-600',
)}
/>
{showError && <p className="mt-1.5 text-xs font-medium text-destructive">기타 사유를 입력해주세요</p>}
</div>
)}
{/* 공급 희망 가격 (선택) — 결렬 폼과 같은 라벨·표기 */}
<div className="flex flex-col gap-1.5">
<div className="text-sm font-bold text-neutral-90">
공급 희망 가격 <span className="font-medium text-neutral-60">(선택)</span>
</div>
<div className="flex flex-wrap 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',
isPending
? '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={isPending}
/>
<span className="whitespace-nowrap text-sm text-neutral-70">원{isVAT && '(VAT 별도)'}</span>
{koreanPrice && <span className="whitespace-nowrap text-sm text-neutral-50">{koreanPrice}</span>}
</div>
</div>
{/* 의견 (선택) — 결렬 폼과 동일 */}
<div className="flex flex-col gap-1.5">
<div className="text-sm font-bold text-neutral-90">
의견 <span className="font-medium text-neutral-60">(선택)</span>
</div>
<textarea
value={opinion}
onChange={(e) => setOpinion(e.target.value)}
rows={2}
maxLength={255}
disabled={isPending}
placeholder="추가로 남길 의견이 있으면 작성해 주세요."
className={cn(
'w-full resize-none rounded-xl border px-3 py-2 text-sm outline-none transition-all placeholder:text-neutral-50',
isPending
? '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 shrink-0 gap-2 border-t border-border p-4">
<button
type="button"
onClick={onClose}
disabled={isPending}
className="h-11 flex-1 rounded-xl border border-border bg-white text-sm font-bold text-neutral-70 transition-all hover:bg-neutral-10 active:scale-[0.98] disabled:opacity-50"
>
취소
</button>
<button
type="button"
onClick={handleSubmit}
disabled={isSubmitDisabled}
className="h-11 flex-1 rounded-xl bg-brand-600 text-sm font-bold text-white shadow-sm transition-all hover:bg-brand-700 active:scale-[0.98] disabled:opacity-40"
>
거부 처리
</button>
</div>
</div>
</Modal>
)
}
@@ -24,8 +24,9 @@ const TERMINAL_CODES = new Set<number>([
ErrorCode.NEGO_NOT_FOUND,
])
// 진입 로드(init/messages) 시 '잘못된 접근'으로 볼 코드 → 권한 없음 / 없는(또는 남의) 세션 /
// 진입 불가 상태(미참여·거부). 토스트 안내 후 목록으로 복귀시킨다. (인증≠인가 — 로그아웃하지 않는다)
// 진입 로드(init/messages) 시 '잘못된 접근'으로 볼 코드 → 권한 없음 / 없는(또는 남의) 세션 / 진입 불가 상태.
// 토스트 안내 후 목록으로 복귀시킨다. (인증≠인가 — 로그아웃하지 않는다)
// 종료된 세션(완료·미참여·거부)은 열람 진입이 허용되므로 여기 걸리지 않는다 — 입력만 잠긴다(ChatSection).
const INVALID_ACCESS_CODES = new Set<number>([
ErrorCode.NEGO_FORBIDDEN,
ErrorCode.NEGO_NOT_FOUND,
@@ -115,8 +116,8 @@ export function useChatController(sessionId: string) {
if (data.message) s.appendMessage(mapMessage(data.message))
s.setIsLoading(false)
// 협상 종료 전이(완료/거부 등): 목록 캐시만 무효화해 /list 복귀 시 최신 상태를 보장한다.
// init 은 '진입 메타'라 화면에서 재조회하지 않는다 — 재조회하면 미참여/거부 진입 게이트(1301)에
// 걸려 방금 정상 종료한 사용자가 튕겨난다. 재진입 시 최신 status 는 언마운트의 removeQueries 가 보장한다.
// init 은 '진입 메타'라 화면에서 재조회하지 않는다 — 방금 종료한 화면의 입력이 열람 모드로
// 갈아치워지지 않게 한다. 재진입 시 최신 status 는 언마운트의 removeQueries 가 보장한다.
if (data.session_status !== SessionStatus.IN_PROGRESS || data.message?.chat_end) {
queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() })
}
@@ -2,6 +2,17 @@ import type { ChatMessage, UserButtonConfig } from '@/features/chat/types'
export const GO_TO_LIST_TEXT = '상품 목록으로 가기'
// 협상 거부 진입점을 숨기는 액션바 상태.
// reject=봇이 이미 결렬을 선언(그 폼이 최종가를 받는다) / extra-info=타결 후 동의 단계 / loading=응답 대기.
const NO_REJECT_TYPES = ['', 'loading', 'reject', 'extra-info']
// 채팅 안에서 협상을 거부할 수 있는 상태인지 — 대화가 끝나지 않고 협력사 입력을 기다리는 동안만.
export function canRejectNegotiation(messages: ChatMessage[], config: UserButtonConfig): boolean {
if (!messages || messages.length === 0) return false
if (messages[messages.length - 1].chat_end) return false
return !NO_REJECT_TYPES.includes(config.type)
}
// 마지막 봇 메시지의 next_input_mode 로 하단 입력 UI 구성을 결정한다.
export function deriveUserButtonConfig(
messages: ChatMessage[],
@@ -29,7 +29,7 @@ export function GuidePopup({ onClose }: { onClose: () => void }) {
<Row badge="협상 중" tone="prog" text="가격을 조율하는 중입니다. 이어서 진행하세요." />
<Row badge="협상 완료" tone="done" text="가격 제출을 마쳤습니다. 최종 결과는 견적 마감 후 아래 '결과'로 표시됩니다." />
<Row badge="협상 미참여" tone="none" text="기한 내 참여하지 않아 종료된 건입니다." />
<Row badge="협상 거절" tone="reject" text="내가 참여를 거절한 건입니다." />
<Row badge="협상 거부" tone="reject" text="내가 거부한 건입니다." />
</Section>
<Section title="협상 결과" desc="견적이 마감된 뒤 정해지는 낙찰 결과입니다. 마감 전에는 표시되지 않습니다.">
@@ -2,7 +2,7 @@ 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, RESULT_META } from '@/features/list/lib/status'
import { statusMeta, canEnterChat, isEndedStatus, RESULT_META } from '@/features/list/lib/status'
interface WorkspaceCardsProps {
items: ListItem[]
@@ -55,10 +55,11 @@ function Card({
onMemo: (item: ListItem) => void
}) {
const meta = statusMeta(item.session_status)
const canEnter = !['미참여', '협상거부'].includes(item.session_status)
const ended = isEndedStatus(item.session_status)
const canEnter = canEnterChat(item.session_status, item.hasChat)
const canReject = ['협상생성', '협상중'].includes(item.session_status)
const isDone = item.session_status === '협상완료'
const enterLabel = isDone ? '결과 보기' : '협상 입장'
const enterLabel = ended ? '결과 보기' : '협상 입장'
// 재협상: 요청 가능하면 버튼, 이미 요청했으면 진행 상태를 보여준다.
const renegoLabel = RENEGO_STATUS_LABEL[item.renegotiationStatus] ?? ''
@@ -138,7 +139,7 @@ function Card({
onClick={() => onReject(item)}
className="flex-1 rounded-lg border border-border py-2 text-xs font-bold text-neutral-70 transition-all hover:bg-neutral-10 active:scale-[0.98]"
>
거절
협상 거부
</button>
)}
{canEnter && (
@@ -3,7 +3,7 @@ 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, RESULT_META } from '@/features/list/lib/status'
import { statusMeta, canEnterChat, isEndedStatus, RESULT_META } from '@/features/list/lib/status'
interface WorkspaceTableProps {
items: ListItem[]
@@ -73,10 +73,11 @@ function Row({
onMemo: (item: ListItem) => void
}) {
const meta = statusMeta(item.session_status)
const canEnter = !['미참여', '협상거부'].includes(item.session_status)
const ended = isEndedStatus(item.session_status)
const canEnter = canEnterChat(item.session_status, item.hasChat)
const canReject = ['협상생성', '협상중'].includes(item.session_status)
const isDone = item.session_status === '협상완료'
const enterLabel = isDone ? '결과 보기' : '협상 입장'
const enterLabel = ended ? '결과 보기' : '협상 입장'
return (
<tr className="border-b border-border/60 transition-colors last:border-0 hover:bg-table-hover/70">
@@ -150,7 +151,7 @@ function Row({
onClick={() => onReject(item)}
className="rounded-lg border border-border px-3 py-1.5 text-xs font-bold text-neutral-70 transition-all hover:bg-neutral-10 active:scale-[0.98]"
>
거절
협상 거부
</button>
)}
{canEnter ? (
@@ -24,6 +24,7 @@ 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 { isEndedStatus } from '@/features/list/lib/status'
import type { ListItem } from '@/features/list/types'
// 상태별 거부 불가 안내
@@ -70,6 +71,11 @@ export function ListWorkspace() {
const [guideOpen, setGuideOpen] = useState(false)
const handleEnter = (item: ListItem) => {
// 종료 건(완료·미참여·거부)은 열람 전용 — 참여 API 는 미참여/거부를 막으므로 바로 채팅으로 보낸다.
if (isEndedStatus(item.session_status)) {
navigate(`/chat?session_id=${item.session_id}`)
return
}
setEnteringId(item.session_id)
participate.mutate(item.session_id, {
onSuccess: () => navigate(`/chat?session_id=${item.session_id}`),
@@ -94,8 +100,8 @@ export function ListWorkspace() {
reject.mutate(
{ sessionId: rejectTarget.session_id, request: { reject_reason: reason } },
{
onSuccess: () => toast.warning('참여 거절이 완료되었습니다.'),
onError: (error) => toast.error(getApiErrorMessage(error, '거절 처리에 실패했습니다.')),
onSuccess: () => toast.warning('협상 거부가 완료되었습니다.'),
onError: (error) => toast.error(getApiErrorMessage(error, '거부 처리에 실패했습니다.')),
},
)
}
@@ -42,5 +42,6 @@ export function toListItem(api: SessionListItem): ListItem {
renegotiationStatus: api.renegotiation_status ?? 0,
renegotiationMemo: api.renegotiation_memo ?? '',
result: api.result ?? 0,
hasChat: api.has_chat ?? false,
}
}
+13 -1
View File
@@ -11,13 +11,25 @@ export const STATUS_META: Record<string, StatusMeta> = {
협상중: { 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-[#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' }
}
// 종료 상태 — 대화를 이어갈 수 없고 지난 이력만 '결과 보기'로 열람한다(백엔드 send 도 협상중만 허용).
const ENDED_STATUSES = ['협상완료', '미참여', '협상거부']
export function isEndedStatus(label: string): boolean {
return ENDED_STATUSES.includes(label)
}
// 채팅 진입 가능 여부. 진행 건은 항상, 종료 건은 볼 대화가 있을 때만 — 초청만 받고 끝난 건은 열어도 빈 화면이다.
export function canEnterChat(label: string, hasChat: boolean): boolean {
return !isEndedStatus(label) || hasChat
}
// 협상 결과(SessionResult 코드) → 완료 건에 붙는 결과 배지. 0(미정)은 표시하지 않는다.
// 결렬(3)은 재협상 요청 대상이라 눈에 띄게 노랑으로 둔다.
export const RESULT_META: Record<number, { label: string; badge: string }> = {
+1
View File
@@ -13,4 +13,5 @@ export type ListItem = {
renegotiationStatus: number // 0=없음 1=심사중 2=승인 3=반려 4=철회
renegotiationMemo: string // 담당자 심사 메모(반려 사유)
result: number // 협상 결과: 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰)
hasChat: boolean // 대화 이력 존재 — 종료된 협상의 '결과 보기' 노출 조건
}
+1
View File
@@ -198,6 +198,7 @@ docker compose up -d # negosium 스택 + lps-api·lps-worker·lps
| **[데이터베이스](docs/database.md)** | 개발자/기획자 | 테이블 6종 구조와 코드값(+by_mall·ip_session·proxy_port 장부) |
| **[API 사용법](docs/api.md)** | 연동 개발자 | 엔드포인트·요청/응답·metrics 예시 |
| **[운영 가이드](docs/operations.md)** | 운영자/개발자 | 실행·병렬·관측(readyz/ops/알림)·**Docker 배포**·문제 해결 |
| **[2026-08-07 세션 기록](docs/2026-08-07-session-notes.md)** | 팀 | 직전 작업 요약 — 결정 근거·미해결(쿠팡 차단)·다음 할 일·주의사항 |
| **[크롤러 논의](docs/decision-openmarket-crawler.md)** | 팀 | 오픈마켓 크롤러 유지 여부(ROI) 의사결정 메모 |
---
+87
View File
@@ -0,0 +1,87 @@
# 2026-08-07 작업 기록 — IP 로테이션 검수 · 네이버 컨테이너 차단 규명 · 결과 상태 정의
다음 세션이 이어받을 수 있도록 **무엇이 왜 바뀌었고, 무엇이 남았는지**만 적는다.
상태 정의는 `result-states.md`, 운영 절차는 `operations.md` 가 소스다.
## 1. 무슨 일이 있었나
세 덩어리다. 앞의 둘은 "고장 났다"에서 출발했고, 셋째는 그 과정에서 드러난 설계 문제다.
**① IP 로테이션이 설계대로 안 돌고 있었다.** 검수해 보니 결함이 6개였고, 그중 하나는
`bot_detection.ip_request_no` 를 항상 `1` 로 만들어 **과거 진단 결론까지 오염**시켰다.
**② 컨테이너에서 네이버만 막혔다.** 원인은 컨테이너가 아니라 **UA 의 플랫폼 토큰**이었다.
네이버는 리눅스 데스크톱 Chrome 을 HTTP 405 로 거부한다.
**③ '못 봤다'를 '없다'고 말하고 있었다.** 차단당해 확인 못 한 몰이 화면에서 '없음(–)'과
구분되지 않았다. 상태를 정의하고 4단계로 화면까지 연결했다.
## 2. 지금 상태
| 항목 | 상태 |
|---|---|
| 네이버 | 컨테이너에서 정상(UA 보정). 검색당 40건 |
| 쿠팡 | **간헐적 차단** — 해외 IP(`gate`) 사용이 원인으로 추정(아래 4번) |
| IP 로테이션 | 예산·회전·소각이 모두 의도대로. 서킷브레이커가 풀 고갈 차단 |
| 결과 상태 | 몰별 7상태 → 운영자 화면은 그대로, 사용자 화면은 3가지로 접음 |
| 잡 | 한 소스가 막혀도 정상 종료(DEAD 아님) |
| 테스트 | lps 292 · negodata 107 passed |
| 배포 | 로컬 전체 재빌드·기동 완료. **운영은 마이그레이션 미적용**(아래 5번) |
## 3. 이번에 정한 것 (되돌리려면 근거부터 볼 것)
- **예산은 브라우저가 아니라 IP 에 묶는다.** 유휴 정리(120s)는 브라우저만 닫고 같은 IP 로
돌아오는데, 브라우저 기준으로 세면 카운터가 매번 초기화돼 **예산이 영영 발화하지 않는다**
(실측: 6회 검색이 전부 같은 포트·`ip_req#1`). 시계도 하나(`_session_started_at`)로 통일했다.
- **회전해도 소용없는 차단은 IP 를 태우지 않는다.** 서로 다른 IP 3개가 연속으로 **첫 요청부터**
막히면 IP 문제가 아니다(평판이면 몇 개는 통과하고, 과사용이면 뒤쪽에서 막힌다). 임계 없이
태우면 잡 16건에 100포트가 30분 쿨다운으로 묶인다. 성공 1회로 자동 해제된다.
- **임대 없이는 크롤하지 않는다.** 풀이 마르면 예전엔 계산식으로 포트를 골라 **남이 쥔 IP 를
같이 썼다**(실측 재현). 장부가 막으려던 바로 그 문제라, 못 잡으면 실패하는 게 맞다.
- **UA 는 플랫폼 토큰만 바꾸고 버전은 실제 값을 쓴다.** 통째로 하드코딩하면 컨테이너 Chrome 이
업데이트될 때 UA 와 엔진이 어긋나 그 불일치가 새 봇 신호가 된다. 쿠팡은 잘 통과하므로 안 건드린다.
- **상태는 하나로 정의·저장하고 표시 단계에서 접는다.** 저장을 단순화하면 운영자가 원인을 못 보고,
표시를 상세화하면 사용자가 못 읽는다. `partial` 을 컬럼으로 둔 것도 같은 이유 — 소비자가
'어떤 상태가 확인된 것인가'라는 판단 규칙까지 알면 상태 정의가 두 곳으로 흩어진다.
- **부분 실패의 `not_found` 는 네거티브 캐시에 넣지 않는다.** 못 본 몰에 있었을 수 있는데
'없음'으로 굳히면 TTL 동안 재검색이 막힌다(사용자가 '다시 검색'을 눌러도 캐시 히트).
## 4. 미해결 — 쿠팡 간헐적 차단
`사용권한이 제한된`(3.4KB)·`errors.edgesuite.net`(0.4KB) 마커로 막히는데 **IP 에 따라 갈린다**
(일부는 통과 → 서킷브레이커가 자동 해제). 즉 환경이 아니라 **IP 평판** 쪽이다.
유력한 원인: **쿠팡만 `gate`(국가 무지정 = 해외 IP)를 쓴다.** 네이버는 `kr_host`(한국 IP)로
바꾼 뒤 안정됐다. 같은 처방이 통할 가능성이 높다.
> 검증하려던 스크립트가 도구 시간 제한으로 중단됐다. 컨테이너에서 `gate` vs `kr` 통과율을
> IP 3개씩 비교하면 된다(네이버 UA 검증과 같은 방식).
⚠️ 맥 컨테이너는 amd64 를 **Rosetta 로 에뮬레이션**한다. 여기서 쿠팡이 막히는 건 실서버와
다를 수 있다 — 실서버에선 쿠팡이 60건 정상이었다. 판단은 실서버 로그로 한다.
## 5. 다음에 할 일 (우선순위)
1. **운영 DB 마이그레이션 적용** — 아직 안 됐다. 순서가 중요하다(아래 6번).
`6_lps_2026-08_dbeaver.sql`(lps_db) · `2026-08-07-iilp-source-state.sql`(negosium_db)
2. **쿠팡 KR 게이트웨이 검증** — 4번. 지금 최저가 커버리지의 최대 구멍이다.
3. **예산 튜닝** — F1 수정으로 `ip_request_no` 가 **처음으로 실제 사용량을 반영**한다.
`ip_req#1` 위주면 IP 평판, `2` 이상이면 예산 하향. **2026-08-06 이전 데이터는 쓰지 말 것.**
4. **AI 매칭 정확도 측정** — 세션 초반에 접근법만 논의하고 미착수. 정답 세트 20~30개로
"몇 % 맞나"를 재야 한다. 지금도 최저가 품질의 최대 병목이다.
5. lps-admin **잡 목록**에 몰별 상태 노출(상품 화면엔 이미 있음, 우선순위 낮음).
## 6. 작업 시 주의
- **마이그레이션 → 코드 순서를 지킬 것.** negodata 가 ORM 전체 엔티티를 조회하므로
(`lps_sync_crud.py:96`), 컬럼이 없는 DB 에 새 코드가 붙으면 **최저가 조회가 통째로 실패**한다
(재현 확인). 역순(마이그레이션 후 옛 코드)은 안전하다 — 옛 컨테이너로 실증했다.
- **워커를 켜 둔 채 pytest 하면 `test_job_queue` 3개가 깨진다.** 워커가 테스트 잡을 집어가서다.
코드 문제가 아니다 — `docker compose stop lps-worker` 후 돌리면 292 passed.
- **JS 로 브라우저 지문을 덮는 방법은 이 스택에서 통하지 않는다.** patchright 가
`add_init_script`(CDP 주입)를 무력화하고, MV3 확장도 값이 안 바뀐다. 다시 시도하기 전에
`services/search/fingerprint.py` docstring 을 볼 것.
- **로컬 dev 의 `negodata-front` 는 `node_modules` 가 named volume 이다.** 의존성이 늘면
이미지를 다시 빌드해도 반영되지 않는다 — 컨테이너 안에서 `npm install` 해야 한다(prod 은
`Dockerfile.prod` 라 해당 없음).
- 테스트가 실DB를 TRUNCATE 하는 문제는 그대로다(`price_history`·`job`·`ip_session`·`bot_detection`).
+156
View File
@@ -0,0 +1,156 @@
from abc import ABC, abstractmethod
from typing import Tuple
from sqlalchemy import and_, asc, column, desc, func, select, table
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import nego_cards, wild_cards
from common.enums import ErrorType
# 학습(learning)·앵커링(anchoring) 스키마는 agent·anchoring 서비스 소유라 negodata ORM 에 없다.
# 조회 전용이므로 필요한 컬럼만 경량 정의한다 — 이 값들의 주인은 negodata 가 아니다(쓰기 금지).
_EXPERIENCE_LOGS = table(
"experience_logs",
column("company_id"), column("session_id"), column("card_id"), column("reward"),
column("settled_price"), column("is_invalidated"), column("created_at"),
column("turn"),
schema="learning",
)
_ANCHORING_CURRENT = table(
"current_values",
column("company_id"), column("supplier_type"), column("price_range_index"),
column("anchoring_value"), column("last_adjusted_at"),
schema="anchoring",
)
_ANCHORING_HISTORY = table(
"value_history",
column("company_id"), column("supplier_type"), column("price_range_index"),
column("anchoring_value_before"), column("anchoring_value_after"),
column("sample_count"), column("success_count"), column("success_rate"), column("created_at"),
schema="anchoring",
)
def _valid(company_id) -> list:
"""유효 학습 기록 — 무효화 표시된 행은 뺀다(협상 취소·재생성 시 agent 가 표시)."""
return [
_EXPERIENCE_LOGS.c.company_id == company_id,
_EXPERIENCE_LOGS.c.is_invalidated == False, # noqa: E712
]
class ILearningCRUD(ABC):
@abstractmethod
async def learning_summary(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, tuple]:
pass
@abstractmethod
async def card_usage(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
pass
@abstractmethod
async def card_names(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
pass
@abstractmethod
async def anchoring_current(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
pass
@abstractmethod
async def anchoring_history(self, cdb: AsyncSession, company_id, limit: int) -> Tuple[ErrorType, list]:
pass
class LearningCRUD(ILearningCRUD):
async def learning_summary(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, tuple]:
"""(학습 협상 수, 기록 수, 타결 협상 수, 마지막 학습 시각)."""
query = select(
func.count(func.distinct(_EXPERIENCE_LOGS.c.session_id)),
func.count(),
func.count(func.distinct(_EXPERIENCE_LOGS.c.session_id))
.filter(_EXPERIENCE_LOGS.c.settled_price.isnot(None)),
func.max(_EXPERIENCE_LOGS.c.created_at),
).where(and_(*_valid(company_id)))
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "learning_summary failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows:
return err_type, (0, 0, 0, None)
return ErrorType.SUCCESS, tuple(rows[0])
async def card_usage(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
"""카드별 사용 현황 — (카드번호, 사용 협상 수, 사용 횟수, 평균 라운드, 마지막 사용).
협상 결과(타결·가격)는 카드 한 장의 성과로 나눌 수 없어 다루지 않는다 — 한 협상에 여러 장이
나가 어느 장의 몫인지 가릴 근거가 없고, 카드 배정도 국면에 따라 정해져 무작위가 아니다.
평균 라운드 = 그 카드가 협상의 몇 번째 라운드에 나갔는지(설정한 국면과 실제가 맞는지 대조).
"""
query = (
select(
_EXPERIENCE_LOGS.c.card_id,
func.count(func.distinct(_EXPERIENCE_LOGS.c.session_id)),
func.count(),
func.avg(_EXPERIENCE_LOGS.c.turn),
func.max(_EXPERIENCE_LOGS.c.created_at),
)
.where(and_(*_valid(company_id), _EXPERIENCE_LOGS.c.card_id.isnot(None)))
.group_by(_EXPERIENCE_LOGS.c.card_id)
.order_by(desc(func.count()))
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "card_usage failed.", raise_error=False)
if err_type != ErrorType.SUCCESS:
return err_type, []
return ErrorType.SUCCESS, list(rows or [])
async def card_names(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
"""카드번호 → (번호, 이름, 와일드 여부, 카드 PK). 학습 로그의 card_id 가 카드번호 문자열이라
상세 화면(/cards?detail=<PK>) 으로 보내려면 PK 를 같이 들고 와야 한다.
UNION 은 실행기가 SELECT 로 인정하지 않아 두 번 나눠 조회한다.
"""
out = []
for model, pk, is_wild in ((nego_cards, nego_cards.nego_card_id, 0), (wild_cards, wild_cards.wild_card_id, 1)):
query = select(model.number, model.name, pk).where(model.deleted == False) # noqa: E712
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "card_names failed.", raise_error=False)
if err_type != ErrorType.SUCCESS:
return err_type, []
out.extend((number, name, is_wild, card_id) for number, name, card_id in (rows or []))
return ErrorType.SUCCESS, out
async def anchoring_current(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
"""현재 앵커링 값 — (협력사유형, 가격대 구간, 값, 마지막 조정 시각). 셀 = 유형 × 가격대."""
query = (
select(
_ANCHORING_CURRENT.c.supplier_type,
_ANCHORING_CURRENT.c.price_range_index,
_ANCHORING_CURRENT.c.anchoring_value,
_ANCHORING_CURRENT.c.last_adjusted_at,
)
.where(_ANCHORING_CURRENT.c.company_id == company_id)
.order_by(asc(_ANCHORING_CURRENT.c.supplier_type), asc(_ANCHORING_CURRENT.c.price_range_index))
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "anchoring_current failed.", raise_error=False)
if err_type != ErrorType.SUCCESS:
return err_type, []
return ErrorType.SUCCESS, list(rows or [])
async def anchoring_history(self, cdb: AsyncSession, company_id, limit: int) -> Tuple[ErrorType, list]:
"""앵커링 조정 이력(최근순) — 조정마다 표본 수·성공률·값 변화가 남는다."""
query = (
select(
_ANCHORING_HISTORY.c.supplier_type,
_ANCHORING_HISTORY.c.price_range_index,
_ANCHORING_HISTORY.c.anchoring_value_before,
_ANCHORING_HISTORY.c.anchoring_value_after,
_ANCHORING_HISTORY.c.sample_count,
_ANCHORING_HISTORY.c.success_count,
_ANCHORING_HISTORY.c.success_rate,
_ANCHORING_HISTORY.c.created_at,
)
.where(_ANCHORING_HISTORY.c.company_id == company_id)
.order_by(desc(_ANCHORING_HISTORY.c.created_at))
.limit(limit)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "anchoring_history failed.", raise_error=False)
if err_type != ErrorType.SUCCESS:
return err_type, []
return ErrorType.SUCCESS, list(rows or [])
+4 -3
View File
@@ -703,13 +703,14 @@ class QuotationCRUD(IQuotationCRUD):
return ErrorType.DB_RUN_FAILED, 0
async def list_sessions_status(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, list]:
"""[마감 판정] 견적의 모든 세션 → (status, supplier_id, bid_price, name, target_price, anchoring_price). 삭제 제외.
"""[마감 판정] 견적의 모든 세션 → (status, supplier_id, bid_price, name, target_price, anchoring_price, reject_price). 삭제 제외.
공급사가 지워졌어도 세션 집계엔 포함되도록 outerjoin(이때 name 은 None).
target/anchoring 은 마감 가격게이트 입력(견적당 상품 1개라 세션 공통값)."""
target/anchoring 은 마감 가격게이트 입력(견적당 상품 1개라 세션 공통값).
reject_price 는 거부 협력사의 공급 희망 가격 — 자동 마감 판정엔 안 쓰고 수동 직접 낙찰 후보에서만 본다."""
try:
query = (
select(sessions.status, sessions.supplier_id, sessions.bid_price, suppliers.name,
sessions.target_price, sessions.anchoring_price)
sessions.target_price, sessions.anchoring_price, sessions.reject_price)
.outerjoin(suppliers, suppliers.supplier_id == sessions.supplier_id)
.where(sessions.quotation_id == qt_id, sessions.deleted == False) # noqa: E712
)
+5 -2
View File
@@ -76,14 +76,17 @@ class StatisticsCRUD(IStatisticsCRUD):
async def winning_sessions(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
# 낙찰 마감 견적의 '낙찰 세션'(supplier_id=preferred_sp_id) 행 — 절감/추이/유형/카테고리/앵커도달률의 단일 원천.
# 파생: 저장 안 하고 조회 때 조인. category 는 items LEFT JOIN(자유텍스트·NULL 허용).
# 계약가는 coalesce(투찰가, 거부 시 공급 희망가) — 결렬 건을 담당자가 직접 낙찰하면 bid_price 가 없어
# 절감 집계에서 통째로 빠지기 때문. 이름은 bid_price 로 유지해 statistics_service 는 그대로 쓴다.
try:
award_price = func.coalesce(sessions.bid_price, sessions.reject_price).label("bid_price")
stmt = (
select(
quotations.updated_at,
quotations.type,
items.category,
sessions.target_price,
sessions.bid_price,
award_price,
sessions.anchoring_price,
)
.select_from(quotations)
@@ -92,7 +95,7 @@ class StatisticsCRUD(IStatisticsCRUD):
and_(
sessions.quotation_id == quotations.qt_id,
sessions.supplier_id == quotations.preferred_sp_id,
sessions.bid_price.isnot(None),
or_(sessions.bid_price.isnot(None), sessions.reject_price.isnot(None)),
sessions.deleted == False, # noqa: E712
),
)
+2
View File
@@ -20,6 +20,7 @@ import router.v1.card.card
import router.v1.quotation.quotation
import router.v1.quotation_setting.quotation_setting
import router.v1.dashboard.dashboard
import router.v1.learning.learning
import router.v1.statistics.statistics
import router.v1.notification.notification
import router.v1.renegotiation.renegotiation
@@ -79,5 +80,6 @@ app.include_router(router.v1.quotation.quotation.router)
app.include_router(router.v1.quotation_setting.quotation_setting.router)
app.include_router(router.v1.dashboard.dashboard.router)
app.include_router(router.v1.statistics.statistics.router)
app.include_router(router.v1.learning.learning.router)
app.include_router(router.v1.notification.notification.router)
app.include_router(router.v1.renegotiation.renegotiation.router)
Whitespace-only changes.
@@ -0,0 +1,19 @@
from fastapi import APIRouter, Depends
from common.models.gmodel import UserInfo
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
from services.learning_service import LearningService
from .protocol import Res_AnchoringStatus, Res_LearningStatus
# 협상 학습 현황 — agent(협상카드 학습)·anchoring(앵커링 조정)이 쌓은 결과를 회사 스코프로 읽는다.
router = APIRouter(prefix="/v1/learning", tags=["Learning"], responses={404: {"description": "Not found"}})
@router.get(path="/cards", response_model=Res_LearningStatus, summary="협상카드 학습 현황")
async def get_learning_status(service: LearningService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.get_learning_status(user_info.company_id))
@router.get(path="/anchoring", response_model=Res_AnchoringStatus, summary="앵커링 현황·조정 이력")
async def get_anchoring_status(service: LearningService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.get_anchoring_status(user_info.company_id))
@@ -0,0 +1,63 @@
from datetime import datetime
from typing import Optional
from pydantic import Field
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
class LearningProtocol(WebPacketProtocol):
pass
class LearningKpi(LearningProtocol):
learned_sessions: int = 0 # 학습에 반영된 협상 수
records: int = 0 # 학습 기록 수(카드 선택 1회 = 1건)
used_cards: int = 0 # 한 번이라도 나간 카드 수
unused_cards: int = 0 # 아직 한 번도 안 나간 카드 수
top3_share: float = 0.0 # 상위 3장이 차지하는 사용 비중 — 쏠림 정도
last_learned_at: Optional[datetime] = None
class CardUsageRow(LearningProtocol):
number: str # 카드번호(NGC-001 등)
name: Optional[str] = None
card_id: Optional[str] = None # 카드 PK — 협상카드 상세(/cards?detail=) 링크용
type: str = "nego" # nego | wild
used_sessions: int = 0 # 이 카드가 나간 협상 수
uses: int = 0 # 총 사용 횟수
share: float = 0.0 # 전체 카드 사용 중 이 카드의 비중
avg_turn: float = 0.0 # 평균 몇 번째 라운드에 나갔는지 — 설정한 국면과 대조용
last_used_at: Optional[datetime] = None
class AnchoringCell(LearningProtocol):
supplier_type: int = 0
supplier_type_label: str = "미지정"
price_range_index: int = 0 # 목표가 기준 가격대 구간
price_range_label: str = "" # 그 구간의 실제 금액 범위(화면 표기용)
anchoring_value: float = 0.0 # 앵커링 인하폭(‰ — 10 = 1%)
last_adjusted_at: Optional[datetime] = None
class AnchoringHistoryRow(LearningProtocol):
supplier_type_label: str = "미지정"
price_range_index: int = 0
price_range_label: str = ""
value_before: float = 0.0
value_after: float = 0.0
sample_count: int = 0 # 조정 판단에 쓴 협상 표본 수
success_count: int = 0
success_rate: float = 0.0
created_at: Optional[datetime] = None
class Res_LearningStatus(Res_WebPacketProtocol):
kpi: LearningKpi = Field(default_factory=LearningKpi)
cards: list[CardUsageRow] = []
class Res_AnchoringStatus(Res_WebPacketProtocol):
cells: list[AnchoringCell] = []
history: list[AnchoringHistoryRow] = []
adjusted_count: int = 0
@@ -0,0 +1,123 @@
import uuid
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import quotations
from common.anchoring.constants import UPPER_BOUNDS
from common.enums import DBWRType, ErrorType, SupplierType
from crud.learning_crud import ILearningCRUD, LearningCRUD
from router.v1.learning.protocol import (
AnchoringCell,
AnchoringHistoryRow,
CardUsageRow,
LearningKpi,
Res_AnchoringStatus,
Res_LearningStatus,
)
HISTORY_LIMIT = 50 # 앵커링 조정 이력 표시 개수 — 한 화면에서 훑는 용도
def _price_range_label(index: int) -> str:
"""가격대 인덱스 → 실제 금액 범위. 사다리는 common.anchoring 정본(UPPER_BOUNDS)만 참조한다."""
if index < 0 or index >= len(UPPER_BOUNDS):
return ""
low = UPPER_BOUNDS[index - 1] if index else 0
return f"{low:,}~{UPPER_BOUNDS[index]:,}원"
_SUPPLIER_TYPE_LABEL = {
SupplierType.NONE.value: "미지정",
SupplierType.DISTRIBUTION.value: "유통",
SupplierType.MANUFACTURE.value: "제조",
SupplierType.SOLE_AGENCY.value: "총판",
}
class LearningService:
"""협상 학습 현황 — 협상카드 학습(agent Q-learning)과 앵커링 조정 이력을 읽어 보여준다.
두 값 모두 negodata 가 만드는 값이 아니라 agent·anchoring 서비스가 쌓은 결과다(읽기 전용).
"""
def __init__(self, crud: ILearningCRUD = Depends(LearningCRUD)):
self.crud = crud
async def get_learning_status(self, company_id: str) -> Res_LearningStatus:
"""카드 사용 현황 — 담아둔 카드가 실제로 나가는지, 어느 국면에 나가는지, 쏠리지는 않는지.
협상 성과(타결·가격)는 카드별로 나누지 않는다 — 한 협상에 여러 장이 나가 어느 장의 몫인지
가릴 수 없고, 카드 배정도 무작위가 아니라 국면에 따라 정해지기 때문이다.
"""
res = Res_LearningStatus()
# learning 의 company_id 는 agent 가 테넌트 키를 그대로 넣는 문자열 컬럼이다(UUID 타입 아님).
cid = str(company_id)
sessions, records, _settled, last_at = await self._read(
lambda s: self.crud.learning_summary(s, cid), default=(0, 0, 0, None))
rows = await self._read(lambda s: self.crud.card_usage(s, cid), default=[])
names = await self._read(lambda s: self.crud.card_names(s), default=[])
name_map = {str(number): (name, is_wild, card_pk) for number, name, is_wild, card_pk in names if number}
total_uses = sum(int(uses or 0) for _n, _s, uses, _t, _l in rows) or 1
for card_id, used_sessions, uses, avg_turn, last_used in rows:
number = str(card_id)
name, is_wild, card_pk = name_map.get(number, (None, 0, None))
res.cards.append(CardUsageRow(
number=number,
name=name,
card_id=str(card_pk) if card_pk else None,
type="wild" if is_wild else "nego",
used_sessions=int(used_sessions or 0),
uses=int(uses or 0),
share=round(int(uses or 0) / total_uses, 3),
avg_turn=round(float(avg_turn), 1) if avg_turn is not None else 0.0,
last_used_at=last_used,
))
res.kpi = LearningKpi(
learned_sessions=int(sessions or 0),
records=int(records or 0),
used_cards=len(res.cards),
unused_cards=max(0, len(name_map) - len(res.cards)),
top3_share=round(sum(c.uses for c in res.cards[:3]) / total_uses, 3),
last_learned_at=last_at,
)
return res
async def get_anchoring_status(self, company_id: str) -> Res_AnchoringStatus:
res = Res_AnchoringStatus()
# anchoring 스키마의 company_id 는 UUID 타입 — learning(문자열 테넌트 키)과 다르다.
cid = uuid.UUID(str(company_id))
cells = await self._read(lambda s: self.crud.anchoring_current(s, cid), default=[])
for supplier_type, price_range_index, value, adjusted_at in cells:
res.cells.append(AnchoringCell(
supplier_type=int(supplier_type or 0),
supplier_type_label=_SUPPLIER_TYPE_LABEL.get(int(supplier_type or 0), "미지정"),
price_range_index=int(price_range_index or 0),
price_range_label=_price_range_label(int(price_range_index or 0)),
anchoring_value=float(value) if value is not None else 0.0,
last_adjusted_at=adjusted_at,
))
history = await self._read(lambda s: self.crud.anchoring_history(s, cid, HISTORY_LIMIT), default=[])
for st, pri, before, after, sample, success, rate, created_at in history:
res.history.append(AnchoringHistoryRow(
supplier_type_label=_SUPPLIER_TYPE_LABEL.get(int(st or 0), "미지정"),
price_range_index=int(pri or 0),
price_range_label=_price_range_label(int(pri or 0)),
value_before=float(before) if before is not None else 0.0,
value_after=float(after) if after is not None else 0.0,
sample_count=int(sample or 0),
success_count=int(success or 0),
success_rate=round(float(rate), 3) if rate is not None else 0.0,
created_at=created_at,
))
res.adjusted_count = len(res.history)
return res
async def _read(self, fn, default):
"""crud 한 건 실행 — 실패해도 화면은 떠야 하므로 기본값으로 떨어진다."""
err, rows = await DB_SESSION_MNG.execute_lambda(quotations.DBType(), DBWRType.DB_READ.value, fn)
return rows if err == ErrorType.SUCCESS else default
+20 -10
View File
@@ -10,6 +10,17 @@ from router.v1.quotation.protocol import Res_Quotation
from services.notification import create_notification
def _award_price(row) -> Optional[int]:
"""직접 낙찰 시 계약 기준가 — 타결했으면 투찰가, 협상이 거부로 끝났으면 그때 써낸 공급 희망 가격.
둘 다 없으면(가격을 한 번도 안 낸 협력사) None → 낙찰 후보가 아니다.
자동 마감 판정(close_and_decide)은 이 함수를 쓰지 않는다 — 자동 낙찰은 투찰가만 본다."""
if row.status == SessionStatus.DONE.value and row.bid_price is not None:
return int(row.bid_price)
if row.status == SessionStatus.REJECTED.value and row.reject_price is not None:
return int(row.reject_price)
return None
class ClosingMixin:
@staticmethod
def _pick_winner(done_rows) -> tuple[Optional[dict], Optional[dict]]:
@@ -159,7 +170,9 @@ class ClosingMixin:
async def award_quotation(self, qt_id: str, company_id, user_id, role, winner_supplier_id) -> Res_Quotation:
"""[프론트] 개찰(낙찰자 미정 마감) 견적을 담당자가 직접 낙찰 처리한다.
투찰한 협상완료(DONE) 세션 중 고른 협력사를 낙찰자로 박고 close_reason 을 AWARDED 로 바꾼다(직접 낙찰).
가격을 써낸 세션 중 고른 협력사를 낙찰자로 박고 close_reason 을 AWARDED 로 바꾼다(직접 낙찰).
후보는 투찰한 협상완료(DONE) + 공급 희망 가격을 남긴 협상거부(REJECTED) — 협상이 결렬돼도
마지막에 제출한 가격으로 계약을 진행하는 운영 방침을 시스템에서 그대로 처리하기 위함이다.
자동 낙찰(close_and_decide)과 결과 컬럼은 같되, 알림에 manual 플래그로 '직접 낙찰'임을 남긴다.
권한: 본인이 생성한 견적만. 단 최고관리자(OWNER)는 회사 내 남의 견적도 낙찰할 수 있다."""
res = Res_Quotation()
@@ -187,23 +200,20 @@ class ClosingMixin:
res.msg = "개찰(낙찰자 미정) 상태의 견적만 직접 낙찰할 수 있습니다."
return res
# 낙찰 후보 = 투찰한 협상완료(DONE) 세션. close_and_decide 와 같은 조회(list_sessions_status,
# 공급사 삭제돼도 포함되는 outerjoin)를 써서 자동낙찰과 후보 집합을 일치시킨다.
# 낙찰 후보 = 가격을 써낸 세션. close_and_decide 와 같은 조회(list_sessions_status,
# 공급사 삭제돼도 포함되는 outerjoin)를 쓴다.
err_type, rows = await DB_SESSION_MNG.execute_lambda(
sessions.DBType(),
DBWRType.DB_READ.value,
lambda s: self.quotation_crud.list_sessions_status(s, qt_uuid),
)
rows = rows if err_type == ErrorType.SUCCESS else []
winner = next(
(r for r in rows
if r.status == SessionStatus.DONE.value and r.bid_price is not None and r.supplier_id == sp_uuid),
None,
)
winner = next((r for r in rows if r.supplier_id == sp_uuid and _award_price(r) is not None), None)
if winner is None:
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
res.msg = "선택한 협력사는 이 견적의 낙찰 후보(투찰한 협상완료 협력사)가 아닙니다."
res.msg = "선택한 협력사는 이 견적의 낙찰 후보(가격을 제출한 협력사)가 아닙니다."
return res
winner_price = _award_price(winner)
# [동시 직접낙찰 가드] 개찰→낙찰 원자 선점. 실제로 전이한 호출자만 통과(재클릭·경합 방어).
claim_err, claimed = await DB_SESSION_MNG.execute_lambda_claim(
@@ -219,7 +229,7 @@ class ClosingMixin:
await create_notification(
original.user_id, NotificationType.SUCCESS,
{"qt_name": original.name, "qt_number": original.number,
"winner_name": winner.name, "winner_price": winner.bid_price, "manual": True},
"winner_name": winner.name, "winner_price": winner_price, "manual": True},
ref_qt_id=qt_uuid,
)
return await self.get_quotation(qt_id, company_id)
+4
View File
@@ -3,6 +3,10 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<!-- 구글폰트 Noto Sans KR — self-host Pretendard 가 어떤 환경에서든 못 뜰 때 한글이 굴림/맑은고딕으로 떨어지지 않게 하는 안전망 -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300..900&display=swap" rel="stylesheet" />
<title>NegoData</title>
</head>
<body>
@@ -0,0 +1,217 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import {
useQuery
} from '@tanstack/react-query';
import type {
DataTag,
DefinedInitialDataOptions,
DefinedUseQueryResult,
QueryClient,
QueryFunction,
QueryKey,
UndefinedInitialDataOptions,
UseQueryOptions,
UseQueryResult
} from '@tanstack/react-query';
import type {
ResAnchoringStatus,
ResLearningStatus
} from '.././model';
import { customFetch } from '../../mutator/custom-fetch';
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
/**
* @summary 협상카드 학습 현황
*/
export const getLearningStatus = (
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
) => {
return customFetch<ResLearningStatus>(
{url: `/v1/learning/cards`, method: 'GET', signal
},
options);
}
export const getGetLearningStatusQueryKey = () => {
return [
`/v1/learning/cards`
] as const;
}
export const getGetLearningStatusQueryOptions = <TData = Awaited<ReturnType<typeof getLearningStatus>>, TError = void>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getLearningStatus>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetLearningStatusQueryKey();
const queryFn: QueryFunction<Awaited<ReturnType<typeof getLearningStatus>>> = ({ signal }) => getLearningStatus(requestOptions, signal);
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getLearningStatus>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type GetLearningStatusQueryResult = NonNullable<Awaited<ReturnType<typeof getLearningStatus>>>
export type GetLearningStatusQueryError = void
export function useGetLearningStatus<TData = Awaited<ReturnType<typeof getLearningStatus>>, TError = void>(
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getLearningStatus>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getLearningStatus>>,
TError,
Awaited<ReturnType<typeof getLearningStatus>>
> , 'initialData'
>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetLearningStatus<TData = Awaited<ReturnType<typeof getLearningStatus>>, TError = void>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getLearningStatus>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getLearningStatus>>,
TError,
Awaited<ReturnType<typeof getLearningStatus>>
> , 'initialData'
>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetLearningStatus<TData = Awaited<ReturnType<typeof getLearningStatus>>, TError = void>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getLearningStatus>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary 협상카드 학습 현황
*/
export function useGetLearningStatus<TData = Awaited<ReturnType<typeof getLearningStatus>>, TError = void>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getLearningStatus>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getGetLearningStatusQueryOptions(options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
query.queryKey = queryOptions.queryKey ;
return query;
}
/**
* @summary 앵커링 현황·조정 이력
*/
export const getAnchoringStatus = (
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
) => {
return customFetch<ResAnchoringStatus>(
{url: `/v1/learning/anchoring`, method: 'GET', signal
},
options);
}
export const getGetAnchoringStatusQueryKey = () => {
return [
`/v1/learning/anchoring`
] as const;
}
export const getGetAnchoringStatusQueryOptions = <TData = Awaited<ReturnType<typeof getAnchoringStatus>>, TError = void>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getAnchoringStatus>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetAnchoringStatusQueryKey();
const queryFn: QueryFunction<Awaited<ReturnType<typeof getAnchoringStatus>>> = ({ signal }) => getAnchoringStatus(requestOptions, signal);
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getAnchoringStatus>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type GetAnchoringStatusQueryResult = NonNullable<Awaited<ReturnType<typeof getAnchoringStatus>>>
export type GetAnchoringStatusQueryError = void
export function useGetAnchoringStatus<TData = Awaited<ReturnType<typeof getAnchoringStatus>>, TError = void>(
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getAnchoringStatus>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getAnchoringStatus>>,
TError,
Awaited<ReturnType<typeof getAnchoringStatus>>
> , 'initialData'
>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetAnchoringStatus<TData = Awaited<ReturnType<typeof getAnchoringStatus>>, TError = void>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getAnchoringStatus>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getAnchoringStatus>>,
TError,
Awaited<ReturnType<typeof getAnchoringStatus>>
> , 'initialData'
>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetAnchoringStatus<TData = Awaited<ReturnType<typeof getAnchoringStatus>>, TError = void>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getAnchoringStatus>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary 앵커링 현황·조정 이력
*/
export function useGetAnchoringStatus<TData = Awaited<ReturnType<typeof getAnchoringStatus>>, TError = void>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getAnchoringStatus>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getGetAnchoringStatusQueryOptions(options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
query.queryKey = queryOptions.queryKey ;
return query;
}
@@ -0,0 +1,16 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import type { AnchoringCellLastAdjustedAt } from './anchoringCellLastAdjustedAt';
export interface AnchoringCell {
supplier_type?: number;
supplier_type_label?: string;
price_range_index?: number;
price_range_label?: string;
anchoring_value?: number;
last_adjusted_at?: AnchoringCellLastAdjustedAt;
}
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type AnchoringCellLastAdjustedAt = string | null;
@@ -0,0 +1,19 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import type { AnchoringHistoryRowCreatedAt } from './anchoringHistoryRowCreatedAt';
export interface AnchoringHistoryRow {
supplier_type_label?: string;
price_range_index?: number;
price_range_label?: string;
value_before?: number;
value_after?: number;
sample_count?: number;
success_count?: number;
success_rate?: number;
created_at?: AnchoringHistoryRowCreatedAt;
}
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type AnchoringHistoryRowCreatedAt = string | null;
@@ -0,0 +1,21 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import type { CardUsageRowName } from './cardUsageRowName';
import type { CardUsageRowCardId } from './cardUsageRowCardId';
import type { CardUsageRowLastUsedAt } from './cardUsageRowLastUsedAt';
export interface CardUsageRow {
number: string;
name?: CardUsageRowName;
card_id?: CardUsageRowCardId;
type?: string;
used_sessions?: number;
uses?: number;
share?: number;
avg_turn?: number;
last_used_at?: CardUsageRowLastUsedAt;
}
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type CardUsageRowCardId = string | null;
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type CardUsageRowLastUsedAt = string | null;
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type CardUsageRowName = string | null;
@@ -5,6 +5,10 @@
* OpenAPI spec version: 0.1.0
*/
export * from './anchoringCell';
export * from './anchoringCellLastAdjustedAt';
export * from './anchoringHistoryRow';
export * from './anchoringHistoryRowCreatedAt';
export * from './bodyUploadItemImageV1ItemImagePost';
export * from './cardData';
export * from './cardDataCondition';
@@ -20,6 +24,10 @@ export * from './cardDataUpdatedAt';
export * from './cardDataUserId';
export * from './cardStatus';
export * from './cardType';
export * from './cardUsageRow';
export * from './cardUsageRowCardId';
export * from './cardUsageRowLastUsedAt';
export * from './cardUsageRowName';
export * from './cardUsageType';
export * from './chatMessageData';
export * from './chatMessageDataCardId';
@@ -77,6 +85,8 @@ export * from './itemDataVatYn';
export * from './itemSupplyType';
export * from './itemSupplyTypeSupplierItemId';
export * from './itemSupplyTypeSupplierName';
export * from './learningKpi';
export * from './learningKpiLastLearnedAt';
export * from './listCardsParams';
export * from './listItemsParams';
export * from './listNotificationsParams';
@@ -274,6 +284,8 @@ export * from './reqUpdateSupplierManagerName';
export * from './reqUpdateSupplierName';
export * from './reqUpdateSupplierTotalRevenue';
export * from './reqUpdateSupplyType';
export * from './resAnchoringStatus';
export * from './resAnchoringStatusMsg';
export * from './resBulkMapByNames';
export * from './resBulkMapByNamesMsg';
export * from './resCard';
@@ -327,6 +339,8 @@ export * from './resItemListMsg';
export * from './resItemMsg';
export * from './resItemSupplyTypeList';
export * from './resItemSupplyTypeListMsg';
export * from './resLearningStatus';
export * from './resLearningStatusMsg';
export * from './resLogin';
export * from './resLoginMsg';
export * from './resLowestPriceResult';
@@ -0,0 +1,16 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import type { LearningKpiLastLearnedAt } from './learningKpiLastLearnedAt';
export interface LearningKpi {
learned_sessions?: number;
records?: number;
used_cards?: number;
unused_cards?: number;
top3_share?: number;
last_learned_at?: LearningKpiLastLearnedAt;
}
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type LearningKpiLastLearnedAt = string | null;
@@ -0,0 +1,18 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import type { ErrorInfo } from './errorInfo';
import type { ResAnchoringStatusMsg } from './resAnchoringStatusMsg';
import type { AnchoringCell } from './anchoringCell';
import type { AnchoringHistoryRow } from './anchoringHistoryRow';
export interface ResAnchoringStatus {
result?: ErrorInfo;
msg?: ResAnchoringStatusMsg;
cells?: AnchoringCell[];
history?: AnchoringHistoryRow[];
adjusted_count?: number;
}
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type ResAnchoringStatusMsg = string | null;
@@ -0,0 +1,17 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import type { ErrorInfo } from './errorInfo';
import type { ResLearningStatusMsg } from './resLearningStatusMsg';
import type { LearningKpi } from './learningKpi';
import type { CardUsageRow } from './cardUsageRow';
export interface ResLearningStatus {
result?: ErrorInfo;
msg?: ResLearningStatusMsg;
kpi?: LearningKpi;
cards?: CardUsageRow[];
}
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type ResLearningStatusMsg = string | null;
+3 -14
View File
@@ -1,21 +1,10 @@
import {QueryClient, QueryClientProvider} from '@tanstack/react-query';
import {useState, type ReactNode} from 'react';
import {QueryClientProvider} from '@tanstack/react-query';
import {type ReactNode} from 'react';
import {Toaster} from 'sonner';
import {ConfirmHost} from '@/lib/confirm';
import {queryClient} from '@/lib/query-client';
export function Providers({children}: {children: ReactNode}) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: false,
},
},
}),
);
return (
<QueryClientProvider client={queryClient}>
{children}
+10
View File
@@ -5,6 +5,7 @@ import {hasSeenOnboarding} from '../features/onboarding/storage';
import AuthenticatedLayout from '@/components/layout/AuthenticatedLayout';
import LoginPage from '../pages/login';
import DashboardPage from '../pages/dashboard';
import LearningPage from '../pages/learning';
import StatisticsPage from '../pages/statistics';
import ForbiddenPage from '../pages/forbidden';
import DevDesignPage from '../pages/dev-design';
@@ -69,6 +70,15 @@ export const router = createBrowserRouter([
children: [
{path: 'dashboard', Component: DashboardPage},
{path: 'statistics', Component: StatisticsPage},
{
// 개발자 전용. 학습·앵커링 내부 동작을 드러내는 화면이라 고객사 관리자에게 열지 않는다.
path: 'learning',
loader: async () => {
await initAuth();
return hasRole('개발자') ? null : redirect('/forbidden');
},
Component: LearningPage,
},
{path: 'products', Component: ProductsPage},
{path: 'partners', Component: PartnersPage},
{path: 'quotation', Component: QuotationPage},
@@ -49,14 +49,11 @@ export function ActionBanner() {
const queryClient = useQueryClient();
const readOne = useReadOne();
const { data: notif } = useListNotifications(
{ size: 20 },
{ query: { refetchInterval: 30_000, staleTime: 10_000 } },
);
const { data: notif } = useListNotifications({ size: 20 }, { query: { refetchInterval: 30_000 } });
// 재협상 요청 토스트는 '아직 완료 안 된(대기중)' 것만 — 내가 처리 가능한(can_act) 대기 세션 집합.
const { data: renego } = useListRequests(
{ status: 1, page: 1, size: 50 },
{ query: { refetchInterval: 30_000, staleTime: 10_000 } },
{ query: { refetchInterval: 30_000 } },
);
const pendingSessions = new Set(
(renego?.requests ?? []).filter((r) => r.can_act !== false).map((r) => r.session_id),
@@ -7,6 +7,7 @@ import {showToast} from '@/lib/notify';
const PAGE_TO_PATH: Record<PageType, string> = {
DASHBOARD: '/dashboard',
STATISTICS: '/statistics',
LEARNING: '/learning',
PRODUCTS: '/products',
PARTNERS: '/partners',
QUOTATION: '/quotation',
@@ -18,6 +18,7 @@ import {
import {
LayoutDashboard,
BarChart3,
Brain,
Briefcase,
Users,
UserCog,
@@ -78,6 +79,7 @@ const menuGroups: { label?: string; items: MenuItem[] }[] = [
{
label: '개발자',
items: [
{ type: 'LEARNING', label: '협상 학습', icon: Brain, id: 'sidebar-learning', devOnly: true },
{ type: 'DEV_SETTINGS', label: '고급 설정', icon: SlidersHorizontal, id: 'sidebar-dev-settings', devOnly: true },
{ type: 'DESIGN', label: '디자인 시스템', icon: Palette, id: 'sidebar-design', devOnly: true },
],
@@ -96,6 +98,7 @@ const canSee = (item: MenuItem, role?: string): boolean => {
const pageLabelMap: Record<PageType, string> = {
DASHBOARD: '대시보드',
STATISTICS: '통계',
LEARNING: '협상 학습',
PRODUCTS: '상품관리',
PARTNERS: '협력사관리',
QUOTATION: '견적관리',
@@ -68,7 +68,7 @@ export function ProfileSheet({ open, onClose }: { open: boolean; onClose: () =>
return (
<Sheet open={open} title="내 정보 수정" onClose={onClose}>
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs font-mono">
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs">
{/* 읽기 전용: 회사 / 로그인ID / 권한 */}
<div className="rounded-md border border-border bg-muted/40 p-3 space-y-1.5">
<div className="flex justify-between">
@@ -10,6 +10,7 @@ import {useAuthStore, type AuthUser, type UserRole} from '../../stores/auth';
import {UserRole as UserRoleCode} from '../../api/generated/model';
import {USER_ROLE_LABEL} from '../../lib/enumLabels';
import {toMessage, resultMessage} from '../../lib/apiError';
import {queryClient} from '../../lib/query-client';
const ACCESS_KEY = 'negodata.accessToken';
const REFRESH_KEY = 'negodata.refreshToken';
@@ -69,6 +70,8 @@ export function initAuth(): Promise<void> {
export async function login(loginId: string, password: string): Promise<ResMe> {
const tokens = ensureOk(await loginRequest({id: loginId, password}));
// 직전 계정(다른 회사)의 캐시가 남아 브랜딩·목록이 그대로 보이는 것 방지
queryClient.clear();
localStorage.setItem(ACCESS_KEY, tokens.access_token ?? '');
localStorage.setItem(REFRESH_KEY, tokens.refresh_token ?? '');
setAccessToken(tokens.access_token ?? null);
@@ -105,4 +108,5 @@ export async function logout(): Promise<void> {
localStorage.removeItem(REFRESH_KEY);
setAccessToken(null);
useAuthStore.getState().setUser(null);
queryClient.clear();
}
@@ -160,7 +160,7 @@ export function CardExcelUploadModal({ open, onConfirm, onClose }: CardExcelUplo
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-xs">
<div className="w-full max-w-6xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up font-mono">
<div className="w-full max-w-6xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up">
{/* Modal Title */}
<div className="flex items-center justify-between pb-4 border-b border-border">
@@ -221,7 +221,7 @@ export function CardFormSheet({
return (
<Sheet open={open} title={title} onClose={onClose}>
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs font-mono">
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs">
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
{/* Card Type Selection */}
<div className="space-y-1">
@@ -0,0 +1,292 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { Link } from 'react-router';
import { Bot, CheckCircle2, HelpCircle, Layers, Ruler } from 'lucide-react';
import { Panel } from '@/features/statistics/components/Panel';
import { StatTile } from '@/features/statistics/components/StatTile';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Typography } from '@/components/ui/typography';
import { fmtDateTime } from '@/features/quotations/types';
import type { AnchoringData, LearningData } from './types';
// 협상 학습 현황. 협상카드(강화학습)와 앵커링(자동 조정)은 서로 다른 축이라 탭으로 나눠 각각 한 화면에 담는다.
// 두 값 모두 agent·anchoring 서비스가 쌓은 결과를 읽기만 한다.
export function CardLearningView({ data }: { data: LearningData }) {
return (
<div className="space-y-4">
<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
<StatTile label="학습한 협상" value={`${data.learnedSessions}건`} icon={Bot} tone="purple" />
<StatTile label="카드 사용" value={`${data.records}회`} icon={Layers} tone="blue" />
<StatTile label="써본 카드" value={`${data.usedCards}종`} icon={CheckCircle2} tone="emerald" />
<StatTile label="아직 안 쓴 카드" value={`${data.unusedCards}종`} icon={Ruler} tone="amber" />
</div>
<Panel
title="카드 사용 현황"
subtitle="담아둔 카드가 실제로 나가는지, 어느 국면에 나가는지 봅니다. 협상 결과는 여러 장이 함께 만든 것이라 카드별 성과로 나누지 않습니다."
right={
data.lastLearnedAt ? (
<Typography as="span" variant="small" className="text-[11px] text-muted-foreground">
최근 사용 {fmtDateTime(data.lastLearnedAt)}
</Typography>
) : undefined
}
>
{data.cards.length === 0 ? (
<EmptyRow text="아직 사용된 카드가 없습니다. 협상이 진행되면 여기에 쌓입니다." />
) : (
<>
{data.top3Share >= 0.8 && data.usedCards > 3 && (
<Typography as="div" variant="small" className="mb-2 text-[11px] text-amber-700 dark:text-amber-400">
상위 3장이 전체 사용의 {pct(data.top3Share)}를 차지합니다 — 나머지 카드는 조건이 맞지 않아
밀리고 있을 수 있습니다.
</Typography>
)}
<Table className="text-xs">
<TableHeader>
<TableRow>
<TableHead className="w-24">카드번호</TableHead>
<TableHead>카드이름</TableHead>
<TableHead className="w-20 text-center">종류</TableHead>
<TableHead className="w-24 text-right">사용 협상</TableHead>
<TableHead className="w-24 text-right">사용 횟수</TableHead>
<TableHead className="w-28 text-right">
<HeadWithHelp label="사용 비중" help="전체 카드 사용 횟수 중 이 카드가 차지하는 비율입니다. 한두 장에 몰려 있으면 나머지 카드가 발동 조건에 걸려 밀리고 있을 수 있습니다." />
</TableHead>
<TableHead className="w-32 text-right">
<HeadWithHelp label="평균 라운드" help="이 카드가 협상의 몇 번째 라운드에 나갔는지의 평균입니다. 값이 작으면 초반에, 크면 종결 무렵에 나간다는 뜻입니다. 종결 전용으로 설정한 카드가 초반에 나오고 있지는 않은지 확인할 때 봅니다." />
</TableHead>
<TableHead className="w-36 text-right">마지막 사용</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.cards.map((c) => (
<TableRow key={c.number}>
<TableCell className="font-mono">{c.number}</TableCell>
<TableCell className="font-medium">
{c.cardId ? (
<Link
to={`/cards?detail=${c.cardId}`}
className="underline decoration-1 underline-offset-2 hover:text-primary"
title={`${c.name} — 협상카드 상세로 이동`}
>
{c.name}
</Link>
) : (
c.name
)}
</TableCell>
<TableCell className="text-center">
<TypeBadge isWild={c.isWild} />
</TableCell>
<TableCell className="text-right">{c.usedSessions}</TableCell>
<TableCell className="text-right">{c.uses}</TableCell>
<TableCell className="text-right">{pct(c.share)}</TableCell>
<TableCell className="text-right">{c.avgTurn ? `${c.avgTurn}R` : '-'}</TableCell>
<TableCell className="text-right text-muted-foreground">
{c.lastUsedAt ? fmtDateTime(c.lastUsedAt) : '-'}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</>
)}
</Panel>
</div>
);
}
export function AnchoringStatusView({ data }: { data: AnchoringData }) {
const adjusted = data.cells.filter((c) => c.adjustedAt).length;
const avg = data.cells.length
? data.cells.reduce((sum, c) => sum + c.value, 0) / data.cells.length
: 0;
return (
<div className="space-y-4">
<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
<StatTile label="관리 중인 구간" value={`${data.cells.length}개`} icon={Layers} tone="purple" />
<StatTile label="조정된 구간" value={`${adjusted}개`} icon={CheckCircle2} tone="emerald" />
<StatTile label="평균 인하폭 (목표가 대비)" value={rate(avg)} icon={Ruler} tone="blue" />
<StatTile label="조정 이력" value={`${data.history.length}건`} icon={Bot} tone="amber" />
</div>
<div className="grid gap-4 xl:grid-cols-2">
<Panel title="현재 앵커링 값"
subtitle="협력사 유형과 가격대가 이 조합이면 이 인하폭을 적용합니다. 앵커가 = 목표가 − (목표가 × 인하폭).">
{data.cells.length === 0 ? (
<EmptyRow text="아직 설정된 구간이 없습니다. 협상이 쌓이면 구간별로 값이 만들어집니다." />
) : (
<Table className="text-xs">
<TableHeader>
<TableRow>
<TableHead className="w-24">협력사 유형</TableHead>
<TableHead>가격대</TableHead>
<TableHead className="w-24 text-right">인하폭</TableHead>
<TableHead className="text-right">마지막 조정</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.cells.map((c) => (
<TableRow key={`${c.supplierType}-${c.priceRange}`}>
<TableCell>{c.supplierType}</TableCell>
<TableCell className="font-mono">{c.priceRange}</TableCell>
<TableCell className="text-right font-mono">{rate(c.value)}</TableCell>
<TableCell className="text-right text-muted-foreground">
{c.adjustedAt ? fmtDateTime(c.adjustedAt) : '조정 전'}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</Panel>
<Panel title="조정 이력"
subtitle="구간마다 협상 10건이 모이면 평가합니다. 앵커가 이하로 합의된 비율이 높으면 인하폭을 올리고, 낮으면 내립니다.">
{data.history.length === 0 ? (
<EmptyRow text="아직 조정된 이력이 없습니다." />
) : (
<Table className="text-xs">
<TableHeader>
<TableRow>
<TableHead className="w-24">협력사 유형</TableHead>
<TableHead>가격대</TableHead>
<TableHead className="w-28 text-right">변화</TableHead>
<TableHead className="w-20 text-right">표본</TableHead>
<TableHead className="w-20 text-right">성공률</TableHead>
<TableHead className="text-right">시각</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.history.map((h, i) => (
<TableRow key={`${h.supplierType}-${h.priceRange}-${h.at ?? i}`}>
<TableCell>{h.supplierType}</TableCell>
<TableCell className="font-mono">{h.priceRange}</TableCell>
<TableCell className="text-right font-mono">
{rate(h.before)} → <span className="font-semibold">{rate(h.after)}</span>
</TableCell>
<TableCell className="text-right">{h.samples}</TableCell>
<TableCell className="text-right">{pct(h.successRate)}</TableCell>
<TableCell className="text-right text-muted-foreground">
{h.at ? fmtDateTime(h.at) : '-'}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</Panel>
</div>
</div>
);
}
// 표 헤더의 ? — 지표 정의를 눌러서 확인한다. 부제에 정의를 길게 늘어놓지 않기 위한 것이고,
// 여러 줄 설명이라 마우스를 떼면 사라지는 hover 툴팁 대신 클릭으로 여닫는다.
function HeadWithHelp({ label, help }: { label: string; help: string }) {
// pinned = 클릭으로 고정(다른 곳 누를 때까지 유지), hovered = 마우스 올린 동안만 노출.
const [pinned, setPinned] = useState(false);
const [hovered, setHovered] = useState(false);
const open = pinned || hovered;
const [pos, setPos] = useState({ top: 0, right: 0 });
const ref = useRef<HTMLSpanElement>(null);
// 표 컨테이너가 overflow-x-auto 라 말풍선을 그 안에 두면 잘리거나 가로 스크롤이 생긴다.
// body 로 띄우고 트리거 좌표에 맞춰 붙인다.
useLayoutEffect(() => {
if (!open || !ref.current) return;
const r = ref.current.getBoundingClientRect();
setPos({ top: r.bottom + 6, right: window.innerWidth - r.right });
}, [open]);
useEffect(() => {
if (!pinned) return;
const close = (e: Event) => {
if (!ref.current?.contains(e.target as Node)) setPinned(false);
};
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setPinned(false);
document.addEventListener('pointerdown', close);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('pointerdown', close);
document.removeEventListener('keydown', onKey);
};
}, [pinned]);
return (
<span
ref={ref}
className="inline-flex items-center justify-end gap-1"
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
{label}
<button
type="button"
aria-label={`${label} 설명`}
aria-expanded={open}
onFocus={() => setHovered(true)}
onBlur={() => setHovered(false)}
// pointerdown 으로 받는다 — click 은 표 행 리렌더 사이에 끼면 눌러도 안 열리는 경우가 있다.
// 전파를 끊지 않으면 방금 등록된 바깥클릭 핸들러가 같은 이벤트로 곧바로 닫는다.
onPointerDown={(e) => {
e.stopPropagation();
setPinned((v) => !v);
}}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
e.stopPropagation();
setPinned((v) => !v);
}
}}
className="text-muted-foreground hover:text-foreground cursor-pointer"
>
<HelpCircle size={12} />
</button>
{open &&
createPortal(
<div
style={{ top: pos.top, right: pos.right }}
className="fixed z-50 w-72 whitespace-normal break-keep rounded-lg border border-border bg-popover px-3 py-2 text-left text-xs font-normal leading-relaxed text-popover-foreground normal-case shadow-lg"
>
{help}
</div>,
document.body,
)}
</span>
);
}
function TypeBadge({ isWild }: { isWild: boolean }) {
return (
<span
className={`inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-semibold ${
isWild
? 'border-amber-300/45 bg-amber-50 text-amber-700 dark:bg-amber-950/20 dark:text-amber-400'
: 'border-primary/25 bg-primary/5 text-primary'
}`}
>
{isWild ? '와일드' : '협상'}
</span>
);
}
function EmptyRow({ text }: { text: string }) {
return (
<Typography as="div" variant="small" className="py-10 text-center text-xs text-muted-foreground">
{text}
</Typography>
);
}
function pct(v: number): string {
return `${(v * 100).toFixed(0)}%`;
}
// 앵커링 값은 천분율(‰)로 저장된다 — 10 = 1%. 화면은 담당자가 쓰는 단위(%)로 보여준다.
function rate(v: number): string {
return `${(v / 10).toFixed(1)}%`;
}
@@ -0,0 +1,54 @@
import { useGetAnchoringStatus, useGetLearningStatus } from '@/api/generated/learning/learning';
import type { AnchoringData, LearningData } from './types';
// 생성 API(snake_case·전부 optional) → 화면 타입 매퍼. api/generated 는 수정 금지라 여기서 흡수한다.
export function useLearningData(): { data: LearningData; isLoading: boolean } {
const { data, isLoading } = useGetLearningStatus();
const k = data?.kpi ?? {};
return {
isLoading,
data: {
learnedSessions: k.learned_sessions ?? 0,
records: k.records ?? 0,
usedCards: k.used_cards ?? 0,
unusedCards: k.unused_cards ?? 0,
top3Share: k.top3_share ?? 0,
lastLearnedAt: k.last_learned_at ?? null,
cards: (data?.cards ?? []).map((c) => ({
number: c.number,
name: c.name ?? c.number,
cardId: c.card_id ?? null,
isWild: c.type === 'wild',
usedSessions: c.used_sessions ?? 0,
uses: c.uses ?? 0,
share: c.share ?? 0,
avgTurn: c.avg_turn ?? 0,
lastUsedAt: c.last_used_at ?? null,
})),
},
};
}
export function useAnchoringData(): { data: AnchoringData; isLoading: boolean } {
const { data, isLoading } = useGetAnchoringStatus();
return {
isLoading,
data: {
cells: (data?.cells ?? []).map((c) => ({
supplierType: c.supplier_type_label ?? '미지정',
priceRange: c.price_range_label ?? '',
value: c.anchoring_value ?? 0,
adjustedAt: c.last_adjusted_at ?? null,
})),
history: (data?.history ?? []).map((h) => ({
supplierType: h.supplier_type_label ?? '미지정',
priceRange: h.price_range_label ?? '',
before: h.value_before ?? 0,
after: h.value_after ?? 0,
samples: h.sample_count ?? 0,
successRate: h.success_rate ?? 0,
at: h.created_at ?? null,
})),
},
};
}
@@ -0,0 +1,45 @@
// 협상 학습 화면 도메인 타입. api/generated(snake_case·전부 optional)를 api.ts 에서 이 형태로 흡수한다.
export type CardRow = {
number: string;
name: string;
cardId: string | null; // 협상카드 상세 링크용 PK
isWild: boolean;
usedSessions: number; // 이 카드가 나간 협상 수
uses: number; // 총 사용 횟수
share: number; // 전체 카드 사용 중 비중
avgTurn: number; // 평균 몇 번째 라운드에 나갔는지
lastUsedAt: string | null;
};
export type LearningData = {
learnedSessions: number;
records: number;
usedCards: number;
unusedCards: number;
top3Share: number; // 상위 3장 사용 비중 — 쏠림
lastLearnedAt: string | null;
cards: CardRow[];
};
export type AnchorCell = {
supplierType: string; // 유통/제조/총판/미지정
priceRange: string; // 가격대 구간(실제 금액 범위)
value: number; // 앵커링 인하폭 — 천분율 저장값(10 = 1%)
adjustedAt: string | null;
};
export type AnchorHistoryRow = {
supplierType: string;
priceRange: string;
before: number;
after: number;
samples: number; // 조정 판단에 쓴 협상 표본 수
successRate: number;
at: string | null;
};
export type AnchoringData = {
cells: AnchorCell[];
history: AnchorHistoryRow[];
};
@@ -131,7 +131,7 @@ export function MemberFormSheet({
return (
<Sheet open={open} title={mode === 'create' ? '신규 계정 생성' : '계정 정보 관리'} onClose={onClose}>
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs font-mono">
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs">
{/* 로그인 ID */}
<div className="space-y-1">
<Typography as="label" variant="label">로그인 ID</Typography>
@@ -225,7 +225,7 @@ export function ExcelUploadModal({ open, partners, onConfirm, onClose }: ExcelUp
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-xs">
<div className="w-full max-w-5xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up font-mono">
<div className="w-full max-w-5xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up">
{/* Modal Title */}
<div className="flex items-center justify-between pb-4 border-b border-border">
@@ -128,7 +128,7 @@ export function PartnerFormSheet({
title={mode === 'create' ? '신규 협력사 등록' : '협력사 정보 관리'}
onClose={onClose}
>
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs font-mono">
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs">
{/* Partner Name */}
<div className="space-y-1">
<Typography as="label" variant="label">{label('supplier.name')}</Typography>
@@ -442,7 +442,7 @@ export function ExcelUploadModal({ open, products, onConfirm, onClose }: ExcelUp
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-xs">
<div className="w-full max-w-5xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up font-mono">
<div className="w-full max-w-5xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up">
{/* Modal Title */}
<div className="flex items-center justify-between pb-4 border-b border-border">
@@ -511,7 +511,7 @@ export function ExcelUploadModal({ open, products, onConfirm, onClose }: ExcelUp
<CheckCircle2 className="text-emerald-500" size={16} />
<span>{excelFile}</span>
</div>
<span className="text-[10px] text-muted-foreground font-mono">{validated.length}개 데이터 행 검출</span>
<span className="text-[10px] text-muted-foreground">{validated.length}개 데이터 행 검출</span>
</div>
{/* Previews table and validation */}
@@ -519,7 +519,7 @@ export function ExcelUploadModal({ open, products, onConfirm, onClose }: ExcelUp
<span className="text-xs font-bold text-foreground block">정합성 검출 미리보기</span>
<div className="border border-border rounded overflow-auto max-h-72">
<Table className="text-left font-mono text-[11px] border-collapse bg-background min-w-max">
<Table className="text-left text-[11px] border-collapse bg-background min-w-max">
<TableHeader className="bg-muted text-muted-foreground text-[10px] border-b border-border">
<TableRow>
<TableHead className="p-2 font-semibold whitespace-nowrap">행</TableHead>
@@ -559,7 +559,7 @@ export function ExcelUploadModal({ open, products, onConfirm, onClose }: ExcelUp
{row.status}
</span>
</TableCell>
<TableCell className={`p-2 font-mono text-[10px] whitespace-nowrap ${row.status === '오류' ? 'text-rose-500' : 'text-emerald-600'}`}>
<TableCell className={`p-2 text-[10px] whitespace-nowrap ${row.status === '오류' ? 'text-rose-500' : 'text-emerald-600'}`}>
{row.message}
</TableCell>
{columns.map((c) => {
@@ -569,7 +569,7 @@ export function ExcelUploadModal({ open, products, onConfirm, onClose }: ExcelUp
<Input
type={c.numeric && !c.customKey ? 'number' : 'text'}
placeholder={c.header}
className={`bg-muted/20 hover:bg-muted/50 ${c.numeric ? 'w-24 text-right font-mono' : 'min-w-[110px] font-mono'}`}
className={`bg-muted/20 hover:bg-muted/50 ${c.numeric ? 'w-24 text-right font-mono' : 'min-w-[110px]'}`}
value={String(value ?? '')}
onChange={(e) => handleUpdateField(row.id, c, e.target.value)}
/>
@@ -588,7 +588,7 @@ export function ExcelUploadModal({ open, products, onConfirm, onClose }: ExcelUp
{/* Excel footer */}
<div className="flex items-center justify-between pt-4 border-t border-border mt-6 text-xs bg-muted/40 p-3 rounded">
<span className="font-mono text-muted-foreground">
<span className="text-muted-foreground">
정상 적격 수치: {validCount}개 // 오류 행 수치: {errorCount}개
</span>
<div className="flex gap-2">
@@ -113,7 +113,7 @@ export function ImageBulkUploadModal({
if (!open) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-xs">
<div className="w-full max-w-3xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up font-mono">
<div className="w-full max-w-3xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up">
{/* 헤더 */}
<div className="flex items-center justify-between pb-3 border-b border-border">
<Typography variant="h3">상품 이미지 일괄 업로드</Typography>
@@ -241,7 +241,7 @@ export function ProductFormSheet({
title={mode === 'create' ? '신규 상품 등록' : '상품 정보 수정'}
onClose={onClose}
>
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs font-mono">
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs">
{/* Product Name */}
<div className="space-y-1">
<Typography as="label" variant="label">{label('item.name')}</Typography>
@@ -290,12 +290,12 @@ export function QuotationCreateModal({
<div className="fixed inset-0 z-[60] flex items-center justify-center">
<div className="flex flex-col items-center gap-3 rounded-xl bg-card px-8 py-6 shadow-2xl border border-border">
<Loader2 className="text-primary animate-spin" size={44} strokeWidth={2.5} />
<Typography variant="small" className="font-semibold font-mono">견적 생성 중…</Typography>
<Typography variant="small" className="text-muted-foreground font-mono">견적 · 협상 세션 등록 중</Typography>
<Typography variant="small" className="font-semibold">견적 생성 중…</Typography>
<Typography variant="small" className="text-muted-foreground">견적 · 협상 세션 등록 중</Typography>
</div>
</div>
)}
<div className="w-full max-w-2xl bg-card border border-border rounded-lg shadow-2xl p-6 flex flex-col max-h-[90vh] overflow-hidden animate-scale-up font-mono">
<div className="w-full max-w-2xl bg-card border border-border rounded-lg shadow-2xl p-6 flex flex-col max-h-[90vh] overflow-hidden animate-scale-up">
{/* Header */}
<div className="shrink-0 flex items-center justify-between pb-4 border-b border-border">
@@ -429,7 +429,7 @@ export function QuotationCreateModal({
{step === 3 && (
<div className="space-y-4">
<div className="space-y-1 font-mono text-xs">
<div className="space-y-1 text-xs">
<Typography as="label" variant="label">적용할 견적 세팅 지정</Typography>
<Select value={settingId} onValueChange={(v) => setSettingId(v ?? '')}>
<SelectTrigger id="wizard-setting-select" className="w-full">
@@ -4,13 +4,11 @@ import type { SessionData } from '@/api/generated/model/sessionData';
import type { QuotationCardData } from '@/api/generated/model/quotationCardData';
import type { ChatMessageData } from '@/api/generated/model/chatMessageData';
import { ChatSender, CardType } from '@/api/generated/model';
import SlateRenderer from '@/components/SlateRenderer';
import { Typography } from '@/components/ui/typography';
import { StatusPill, sessionStatusTone } from './StatusPill';
import { type Product, type Partner, sessionStatusLabel } from '../../types';
import { useCompanySettings } from '@/features/settings/useCompanySettings';
import { renderEmphasis } from '@/lib/emphasis';
import { renderCardScriptPreview } from '@/features/cards/editor';
// 협상로그 JSON 다운로드(IMK #9). 가격·인하율은 실값 그대로 내보낸다 — 이 탭을 열 수 있는 사람이
// 이미 공개 대상(해당 견적 담당자∪최고관리자, 조회 게이팅)뿐이라 마스킹이 하던 차단 역할이 없다.
@@ -186,19 +184,12 @@ export function ChatTab({
) : (
chatMessages.map((m) =>
m.sender === ChatSender.BOT ? (
<BotBubble
key={m.chat_id}
message={m}
currentSupplierName={currentSupplierName}
currentProduct={currentProduct}
serverCards={serverCards}
/>
<BotBubble key={m.chat_id} message={m} serverCards={serverCards} />
) : (
<PartnerBubble
key={m.chat_id}
message={m}
currentSupplierName={currentSupplierName}
currentProduct={currentProduct}
serverCards={serverCards}
/>
),
@@ -211,22 +202,16 @@ export function ChatTab({
);
}
// 봇(좌측) 말풍선. 진행 단계·협상 스크립트(가격 마스킹)·사용 협상카드를 보여준다.
// 봇(좌측) 말풍선. 진행 단계·협상 스크립트·사용 협상카드를 보여준다.
// 간격은 부모(flex flex-col gap)에서 주고, 말풍선 박스는 block 으로 둬 긴 텍스트 줄바꿈이 깨지지 않게 한다.
function BotBubble({
message,
currentSupplierName,
currentProduct,
serverCards,
}: {
message: ChatMessageData;
currentSupplierName: string;
currentProduct: Product | undefined;
serverCards: QuotationCardData[];
}) {
const m = message;
// 카드 사용 메시지는 같은 멘트가 아래 카드 박스에 그대로 나오므로 본문 script 는 중복 → 카드 없을 때만 노출.
const usedCard = findUsedCard(m, serverCards);
return (
<div className="flex justify-start">
<div className="flex flex-col gap-1.5 max-w-[85%]">
@@ -241,18 +226,13 @@ function BotBubble({
{m.step}
</Typography>
)}
{m.script && !usedCard && (
{/* 본문은 실제 발화(chats.meta.script) — 카드 멘트도 변수 치환·자연화가 끝난 최종본이 여기 담긴다. */}
{m.script && (
<Typography as="p" variant="small" className="text-xs whitespace-pre-line leading-relaxed text-inherit">
{renderEmphasis(m.script)}
</Typography>
)}
<UsedCardBox
message={m}
isBot
currentSupplierName={currentSupplierName}
currentProduct={currentProduct}
serverCards={serverCards}
/>
<UsedCardBox message={m} isBot serverCards={serverCards} />
</div>
</div>
</div>
@@ -263,12 +243,10 @@ function BotBubble({
function PartnerBubble({
message,
currentSupplierName,
currentProduct,
serverCards,
}: {
message: ChatMessageData;
currentSupplierName: string;
currentProduct: Product | undefined;
serverCards: QuotationCardData[];
}) {
const m = message;
@@ -291,13 +269,7 @@ function PartnerBubble({
{m.script}
</Typography>
)}
<UsedCardBox
message={m}
isBot={false}
currentSupplierName={currentSupplierName}
currentProduct={currentProduct}
serverCards={serverCards}
/>
<UsedCardBox message={m} isBot={false} serverCards={serverCards} />
</div>
</div>
</div>
@@ -305,24 +277,20 @@ function PartnerBubble({
}
// 말풍선에 붙는 협상카드 박스(봇/협력사 공용). 카드 미사용 메시지면 아무것도 렌더하지 않는다.
// 톤(amber/primary)만 isBot 으로 가르고, 멘트/조건/메모 렌더 로직은 공유한다.
// 멘트 본문은 위 말풍선(실발화 m.script)이 담당 — 여기선 카드 메타(번호·이름·종류·와일드 조건/메모)만.
// 톤은 카드 종류(와일드=amber, 협상=primary)로 가른다.
function UsedCardBox({
message,
isBot,
currentSupplierName,
currentProduct,
serverCards,
}: {
message: ChatMessageData;
isBot: boolean;
currentSupplierName: string;
currentProduct: Product | undefined;
serverCards: QuotationCardData[];
}) {
const m = message;
const usedCard = findUsedCard(m, serverCards);
if (!usedCard) return null;
const cardNodes = Array.isArray(usedCard.edit_script) ? (usedCard.edit_script as unknown[]) : null;
const isWildCard = usedCard.type === CardType.WILD;
const cardDetailId = usedCard.nego_card_id ?? usedCard.wild_card_id ?? null; // 협상카드 상세(/cards?detail=) 링크용
@@ -330,12 +298,20 @@ function UsedCardBox({
<div
className={`rounded border p-2 ${
isBot
? 'bg-amber-50/70 border-amber-200 dark:bg-amber-950/20 dark:border-amber-900/40'
: 'bg-white/10 border-white/20'
? isWildCard
? 'bg-amber-50/70 border-amber-200 dark:bg-amber-950/20 dark:border-amber-900/40'
: 'bg-primary/5 border-primary/25 dark:bg-primary/10 dark:border-primary/30'
: isWildCard
? 'bg-amber-300/15 border-amber-200/40'
: 'bg-white/10 border-white/20'
}`}
>
{/* 헤더: 어떤 카드인지(번호·이름·종류) */}
<div className={`flex items-center gap-1 ${isBot ? 'text-amber-800 dark:text-amber-300' : 'text-primary-foreground'}`}>
<div
className={`flex items-center gap-1 ${
isBot ? (isWildCard ? 'text-amber-800 dark:text-amber-300' : 'text-primary') : 'text-primary-foreground'
}`}
>
<Sparkles size={10} />
<Typography as="span" variant="small" className="text-[10px] font-semibold text-inherit">협상카드</Typography>
{cardDetailId ? (
@@ -374,23 +350,6 @@ function UsedCardBox({
</Typography>
</div>
{/* 멘트 본문: 서식본(edit_script) 우선, 없으면 평문 script. 가격 변수는 매핑하지 않아(값 미주입) 실가격이 노출되지 않는다. */}
{cardNodes ? (
<div className="mt-1.5">
<SlateRenderer
nodes={cardNodes}
variables={{
partner_name: currentSupplierName,
product_name: currentProduct?.name ?? '',
}}
/>
</div>
) : usedCard.script ? (
<Typography as="p" variant="small" className="mt-1.5 text-xs leading-relaxed whitespace-pre-line text-foreground/85">
{renderCardScriptPreview(usedCard.script)}
</Typography>
) : null}
{/* 와일드카드 부가 정보: 사용 조건 / 메모 */}
{isWildCard && (usedCard.condition || usedCard.memo) && (
<div className="mt-1.5 pt-1.5 border-t border-amber-200/60 dark:border-amber-900/40 space-y-0.5 text-muted-foreground">
@@ -92,7 +92,7 @@ export function DrawerHeaderCards({
: [];
return (
<div className="mt-4 space-y-4 text-xs font-mono">
<div className="mt-4 space-y-4 text-xs">
{/* 결과 요약: 목표가 대비 낙찰/절감 */}
<ResultSummaryBand quotation={quotation} sessionViews={sessionViews} />
@@ -166,7 +166,7 @@ export function RegenerateModal({
return (
<div className="fixed inset-0 z-[55] flex items-center justify-center p-4 bg-black/40 backdrop-blur-xs">
<div className="w-full max-w-3xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up font-mono">
<div className="w-full max-w-3xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up">
{/* Header */}
<div className="flex items-center justify-between pb-4 border-b border-border">
<div className="flex items-center gap-2">
@@ -9,7 +9,7 @@ import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@
import { SessionStatus } from '@/api/generated/model';
import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip';
import { StatusPill, sessionStatusTone } from './StatusPill';
import { mapServerSessionView, sessionStatusLabel } from '../../types';
import { awardPrice, mapServerSessionView, sessionStatusLabel } from '../../types';
import { useCompanySettings } from '@/features/settings/useCompanySettings';
type SessionView = ReturnType<typeof mapServerSessionView>;
@@ -57,22 +57,24 @@ export function SessionsStatusTab({
const [awarding, setAwarding] = useState(false);
const unsentCount = sessionViews.filter((s) => !s.email_sent_at).length;
// 낙찰 후보 = 투찰한 협상완료(DONE) 협력사. 개찰 견적에서 이 중 하나를 담당자가 직접 낙찰한다.
const candidates = sessionViews.filter((s) => s.status === SessionStatus.DONE && s.bid_price != null);
// 낙찰 후보 = 가격을 써낸 협력사(투찰한 협상완료 + 공급 희망가를 남긴 협상거부).
// 협상이 결렬돼도 최종 제출가로 계약을 진행하므로 거부 건도 후보에 넣는다.
const candidates = sessionViews.filter((s) => awardPrice(s) != null);
const showAward = canAward && candidates.length > 0;
// 최저 투찰가 = 자동낙찰과 같은 기준 → 추천 표시(담당자가 동가/사정상 다른 곳을 골라도 됨).
const lowestBid = candidates.length ? Math.min(...candidates.map((s) => s.bid_price as number)) : null;
// 최저가 = 자동낙찰과 같은 기준 → 추천 표시(담당자가 동가/사정상 다른 곳을 골라도 됨).
const lowestBid = candidates.length ? Math.min(...candidates.map((s) => awardPrice(s) as number)) : null;
const selectedWinner = candidates.find((s) => s.supplier_id === selectedWinnerId) ?? null;
const colCount = showAward ? 13 : 12;
const handleAward = async () => {
if (!selectedWinner) return;
const name = selectedWinner.supplier_name;
const price = selectedWinner.bid_price != null ? `₩${selectedWinner.bid_price.toLocaleString()}` : '-';
const winnerPrice = awardPrice(selectedWinner);
const price = winnerPrice != null ? `₩${winnerPrice.toLocaleString()}` : '-';
if (
!(await confirm({
title: '직접 낙찰',
description: `[${name}] (투찰가 ${price})을(를) 낙찰 처리하시겠습니까? 낙찰은 되돌릴 수 없습니다.`,
description: `[${name}] (계약가 ${price})을(를) 낙찰 처리하시겠습니까? 낙찰은 되돌릴 수 없습니다.`,
confirmText: '낙찰 확정',
}))
)
@@ -179,9 +181,9 @@ export function SessionsStatusTab({
<TableHead className="p-3 font-semibold text-right">투찰가</TableHead>
<TableHead className="p-3 font-semibold">투찰시각</TableHead>
<TableHead className="p-3 font-semibold">마감시각</TableHead>
<TableHead className="p-3 font-semibold font-sans">거절사유</TableHead>
<TableHead className="p-3 font-semibold text-right">거절가격</TableHead>
<TableHead className="p-3 font-semibold font-sans">거절배송방식</TableHead>
<TableHead className="p-3 font-semibold font-sans">거부사유</TableHead>
<TableHead className="p-3 font-semibold text-right">거부가격</TableHead>
<TableHead className="p-3 font-semibold font-sans">거부배송방식</TableHead>
</TableRow>
</TableHeader>
<TableBody className="divide-y divide-border">
@@ -193,8 +195,8 @@ export function SessionsStatusTab({
</TableRow>
)}
{sessionViews.map((sess) => {
const isCandidate = sess.status === SessionStatus.DONE && sess.bid_price != null;
const isRecommended = isCandidate && sess.bid_price === lowestBid;
const isCandidate = awardPrice(sess) != null;
const isRecommended = isCandidate && awardPrice(sess) === lowestBid;
const isWinner = !!winnerSupplierId && sess.supplier_id === winnerSupplierId;
return (
<TableRow
@@ -355,8 +357,8 @@ export function SessionsStatusTab({
</Typography>
)}
{sessionViews.map((sess) => {
const isCandidate = sess.status === SessionStatus.DONE && sess.bid_price != null;
const isRecommended = isCandidate && sess.bid_price === lowestBid;
const isCandidate = awardPrice(sess) != null;
const isRecommended = isCandidate && awardPrice(sess) === lowestBid;
const isWinner = !!winnerSupplierId && sess.supplier_id === winnerSupplierId;
const rows: { label: string; value: string }[] = [
{ label: '상품', value: sess.item_name || '-' },
@@ -368,10 +370,10 @@ export function SessionsStatusTab({
{ label: '투찰시각', value: sess.bid_at || '-' },
{ label: '마감시각', value: sess.end_time || '-' },
];
// 거절 정보는 값이 있을 때만(빈 줄로 카드가 길어지지 않게).
if (sess.reject_reason) rows.push({ label: '거절사유', value: sess.reject_reason });
if (sess.reject_price) rows.push({ label: '거절가격', value: `₩${sess.reject_price.toLocaleString()}` });
if (sess.reject_delivery_type) rows.push({ label: '거절배송방식', value: sess.reject_delivery_type });
// 거부 정보는 값이 있을 때만(빈 줄로 카드가 길어지지 않게).
if (sess.reject_reason) rows.push({ label: '거부사유', value: sess.reject_reason });
if (sess.reject_price) rows.push({ label: '거부가격', value: `₩${sess.reject_price.toLocaleString()}` });
if (sess.reject_delivery_type) rows.push({ label: '거부배송방식', value: sess.reject_delivery_type });
return (
<div key={sess.session_id} className={cn('p-3', isWinner && 'bg-success/10')}>
<div className="flex items-center gap-2">
@@ -52,7 +52,7 @@ export function TargetPriceModal({
onClick={onClose}
>
<div
className="w-full max-w-md bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto font-mono text-xs animate-scale-up"
className="w-full max-w-md bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto text-xs animate-scale-up"
onClick={(e) => e.stopPropagation()}
>
{/* 헤더 */}
@@ -45,7 +45,7 @@ export function QuotationSettingsModal({
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-xs">
<div className="w-full max-w-2xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up font-mono text-xs">
<div className="w-full max-w-2xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up text-xs">
<div className="flex items-center justify-between pb-4 border-b border-border mb-4">
<div className="flex items-center gap-2">
@@ -283,15 +283,23 @@ export type QuotationResultView = {
savingsRate: number | null;
};
// 계약 기준가 — 타결했으면 투찰가, 협상이 거부로 끝났으면 그때 써낸 공급 희망 가격.
// 결렬 건도 최종 제출가로 계약을 진행하므로 낙찰 후보·결과 표기가 같은 기준을 본다.
export function awardPrice(s: SessionView): number | null {
if (s.status === SessionStatus.DONE && s.bid_price != null) return s.bid_price;
if (s.status === SessionStatus.REJECTED && s.reject_price != null) return s.reject_price;
return null;
}
export function buildQuotationResult(q: QuotationData, sessions: SessionView[]): QuotationResultView {
const winnerId = q.preferred_sp_id ?? null;
const winnerSession = winnerId ? sessions.find((s) => s.supplier_id === winnerId) ?? null : null;
// 투찰가 있는 세션들 중 최저 = 잠정 낙찰가(우선협상자 미확정 시).
const bids = sessions.map((s) => s.bid_price).filter((v): v is number => v != null);
// 가격을 써낸 세션들 중 최저 = 잠정 낙찰가(우선협상자 미확정 시).
const bids = sessions.map(awardPrice).filter((v): v is number => v != null);
const lowestBid = bids.length ? Math.min(...bids) : null;
const highestBid = bids.length ? Math.max(...bids) : null;
const winnerPrice = winnerSession?.bid_price ?? lowestBid;
const winnerPrice = (winnerSession ? awardPrice(winnerSession) : null) ?? lowestBid;
const provisional = !winnerSession;
const sessionTarget =
@@ -159,7 +159,7 @@ export function SettingsView({ tabs = SETTINGS_TABS }: { tabs?: readonly Setting
setDraft((d) => ({ ...d, labels: { ...d.labels, [key]: value } }));
return (
<div className="space-y-4 font-mono text-xs">
<div className="space-y-4 text-xs">
<Tabs value={tab} onValueChange={setTab}>
<div className="flex items-center justify-between gap-3 flex-wrap">
<TabsList>
@@ -6,7 +6,7 @@ import { LABEL_DEFAULTS, DEFAULT_VAT_MODE, type CompanySettings, type VatMode }
// 조회는 전 유저(브랜딩/라벨 렌더용), 저장은 백엔드가 OWNER 로 게이트한다.
export function useCompanySettings() {
const queryClient = useQueryClient();
const query = useGetSettings({ query: { staleTime: 5 * 60 * 1000 } });
const query = useGetSettings();
const settings: CompanySettings = (query.data?.settings as CompanySettings) ?? {};
const save = async (next: CompanySettings) => {
+16
View File
@@ -0,0 +1,16 @@
import {QueryClient} from '@tanstack/react-query';
// negodata 는 서버 응답을 캐시하지 않는다 — 화면에 뜨는 값은 항상 그 시점의 서버 값이다.
// (캐시를 두면 계정을 갈아탔을 때 앞 회사 CI·라벨·목록이 그대로 그려진다.)
// staleTime 0 = 받는 즉시 stale 로 보고 다시 읽는다, gcTime 0 = 화면에서 내려가면 바로 버린다.
// 페이지네이션 깜빡임은 각 훅의 placeholderData(keepPreviousData)가 막는다 — 캐시가 아니라 직전 렌더값이다.
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 0,
gcTime: 0,
retry: 1,
refetchOnWindowFocus: false,
},
},
});
+1 -1
View File
@@ -84,7 +84,7 @@ export default function DevDesignPage() {
<StatusPill tone="blue">진행중</StatusPill>
<StatusPill tone="emerald">완료</StatusPill>
<StatusPill tone="amber">주의</StatusPill>
<StatusPill tone="rose">거절</StatusPill>
<StatusPill tone="rose">거부</StatusPill>
</div>
</Section>
+66
View File
@@ -0,0 +1,66 @@
import { useSearchParams } from 'react-router';
import { PageContainer } from '@/components/layout/PageContainer';
import { Typography } from '@/components/ui/typography';
import { AnchoringStatusView, CardLearningView } from '@/features/learning/LearningView';
import { useAnchoringData, useLearningData } from '@/features/learning/api';
// 협상 학습. AI가 협상을 거치며 쌓은 결과를 보는 화면이다.
// 협상카드 = 어떤 카드가 잘 먹혔는지(강화학습), 앵커링 = 구간별 인하폭이 어떻게 조정됐는지.
// 두 축은 성격이 달라 탭으로 나눈다 — 각각 한 화면에서 끝나야 훑기 좋다.
type Tab = 'cards' | 'anchoring';
export default function LearningPage() {
// 탭은 쿼리(?tab=)에 둔다 — 새로고침·뒤로가기·링크 공유가 그대로 되도록.
const [params, setParams] = useSearchParams();
const tab: Tab = params.get('tab') === 'anchoring' ? 'anchoring' : 'cards';
const setTab = (next: Tab) => setParams(next === 'cards' ? {} : { tab: next }, { replace: true });
const learning = useLearningData();
const anchoring = useAnchoringData();
const isLoading = tab === 'cards' ? learning.isLoading : anchoring.isLoading;
return (
<PageContainer>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<Typography variant="h2">협상 학습</Typography>
<div className="flex gap-1 rounded-lg border border-border bg-card p-1">
<TabButton active={tab === 'cards'} onClick={() => setTab('cards')}>
협상카드
</TabButton>
<TabButton active={tab === 'anchoring'} onClick={() => setTab('anchoring')}>
앵커링
</TabButton>
</div>
</div>
{isLoading ? (
<Typography variant="muted">학습 현황을 불러오는 중…</Typography>
) : tab === 'cards' ? (
<CardLearningView data={learning.data} />
) : (
<AnchoringStatusView data={anchoring.data} />
)}
</PageContainer>
);
}
function TabButton({
active,
onClick,
children,
}: {
active: boolean;
onClick: () => void;
children: React.ReactNode;
}) {
return (
<button
type="button"
onClick={onClick}
className={`rounded-md px-3 py-1.5 text-xs font-semibold transition-colors ${
active ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:bg-muted'
}`}
>
{children}
</button>
);
}
+3 -2
View File
@@ -36,7 +36,8 @@
--color-ring: var(--ring);
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
--font-mono: "JetBrains Mono", Consolas, "Segoe UI Mono", ui-monospace, SFMono-Regular, "Menlo", monospace;
/* 모노 폰트엔 한글 글리프가 없다 — Pretendard 를 넣어야 한글이 OS 기본(Windows 굴림)으로 떨어지지 않는다 */
--font-mono: "JetBrains Mono", Consolas, "Segoe UI Mono", ui-monospace, SFMono-Regular, "Menlo", "Pretendard Variable", "Noto Sans KR", monospace;
}
:root {
@@ -124,7 +125,7 @@
@theme inline {
--font-heading: var(--font-sans);
--font-sans: 'Pretendard Variable', 'Geist Variable', system-ui, sans-serif;
--font-sans: 'Pretendard Variable', 'Geist Variable', 'Noto Sans KR', system-ui, sans-serif;
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
+1 -1
View File
@@ -45,4 +45,4 @@ export interface CardTactic {
offer_variable?: string; // 제시 가격 변수 명시 지정. 없으면 멘트 파싱(마지막 가격 변수) — 멘트에 있는 변수만 허용
}
export type PageType = 'DASHBOARD' | 'STATISTICS' | 'PRODUCTS' | 'PARTNERS' | 'QUOTATION' | 'CARDS' | 'RENEGOTIATION' | 'MEMBERS' | 'SETTINGS' | 'DEV_SETTINGS' | 'DESIGN' | 'NOTIFICATIONS';
export type PageType = 'DASHBOARD' | 'STATISTICS' | 'LEARNING' | 'PRODUCTS' | 'PARTNERS' | 'QUOTATION' | 'CARDS' | 'RENEGOTIATION' | 'MEMBERS' | 'SETTINGS' | 'DEV_SETTINGS' | 'DESIGN' | 'NOTIFICATIONS';
@@ -13,6 +13,7 @@ DELETE FROM card.wild_cards WHERE user_id IS NULL;
-- 기본가(DB 존재):
-- {target_price} 목표가격(고객사 지향가) 접미: 원(VAT별도)
-- {anchoring_price} 앵커링가격(고객사 하한) 접미: 원(VAT별도)
-- {anchor_price} 위와 같은 값(카드 에디터 칩 표기 '앵커가')
-- {internet_lowest_price} 인터넷 최저가 접미: 원(VAT별도)
-- 세션값(협상 중 직전 제시가):
-- {prev_customer_price} 고객사 직전 제시가 접미: 원
@@ -98,20 +99,20 @@ SELECT * FROM (VALUES
-- 10. 향후 거래 연계 — tone 4(중립) · strategy 4(협력)
(NULL::uuid, '향후 거래 연계', 'NGC-010',
'이번 거래의 가격을 {target_price}원(VAT별도)으로 조정하는 대신, {customer_condition}을 함께 검토해 주실 것을 제안 드립니다.
'이번 거래의 가격을 {anchor_price}원(VAT별도)으로 조정하는 대신, {customer_condition}을 함께 검토해 주실 것을 제안 드립니다.
당장의 단가 한 건만 보기보다 향후 이어질 거래까지 함께 고려한다면, 양사 모두에게 더 큰 가치를 만들 수 있습니다. 이번 합의를 장기적 관계의 출발점으로 삼아, 서로에게 이익이 되는 구조를 함께 설계하기를 바랍니다.',
'[{"type": "paragraph", "children": [{"text": "이번 거래의 가격을 "}, {"type": "variable", "name": "target_price", "label": "목표가격(고객사 지향가)", "children": [{"text": ""}], "suffix": "원(VAT별도)", "style": {"bold": true, "color": "red"}}, {"text": "으로 조정하는 대신, "}, {"type": "variable", "name": "customer_condition", "label": "고객사 교환·요구 조건", "children": [{"text": ""}], "style": {"bold": true}}, {"text": "을 함께 검토해 주실 것을 제안 드립니다."}]}, {"type": "paragraph", "children": [{"text": "당장의 단가 한 건만 보기보다 향후 이어질 거래까지 함께 고려한다면, 양사 모두에게 더 큰 가치를 만들 수 있습니다. 이번 합의를 장기적 관계의 출발점으로 삼아, 서로에게 이익이 되는 구조를 함께 설계하기를 바랍니다."}]}]'::jsonb,
'[{"type": "paragraph", "children": [{"text": "이번 거래의 가격을 "}, {"type": "variable", "name": "anchor_price", "label": "앵커가", "children": [{"text": ""}], "suffix": "원(VAT별도)", "style": {"bold": true, "color": "red"}}, {"text": "으로 조정하는 대신, "}, {"type": "variable", "name": "customer_condition", "label": "고객사 교환·요구 조건", "children": [{"text": ""}], "style": {"bold": true}}, {"text": "을 함께 검토해 주실 것을 제안 드립니다."}]}, {"type": "paragraph", "children": [{"text": "당장의 단가 한 건만 보기보다 향후 이어질 거래까지 함께 고려한다면, 양사 모두에게 더 큰 가치를 만들 수 있습니다. 이번 합의를 장기적 관계의 출발점으로 삼아, 서로에게 이익이 되는 구조를 함께 설계하기를 바랍니다."}]}]'::jsonb,
1, 4, 4),
-- 11. 양보 가치 강조 — tone 4(중립) · strategy 4(협력)
(NULL::uuid, '양보 가치 강조', 'NGC-011',
'이번 조정은 당사에 결코 작은 일이 아님을 먼저 말씀드리고 싶습니다.
{target_price}원(VAT별도)으로의 조정은 당사 수익 구조상 상당한 부담을 감수한 결정이며, 내부적으로도 쉽지 않은 승인 과정을 거쳤습니다. 이는 곧 귀사께서 그만큼 실질적인 혜택을 얻으시게 된다는 의미이기도 합니다.
{anchor_price}원(VAT별도)으로의 조정은 당사 수익 구조상 상당한 부담을 감수한 결정이며, 내부적으로도 쉽지 않은 승인 과정을 거쳤습니다. 이는 곧 귀사께서 그만큼 실질적인 혜택을 얻으시게 된다는 의미이기도 합니다.
당사가 감수한 만큼, 귀사께서도 이에 상응하는 조건으로 화답해 주시기를 정중히 요청 드립니다.',
'[{"type": "paragraph", "children": [{"text": "이번 조정은 당사에 결코 작은 일이 아님을 먼저 말씀드리고 싶습니다."}]}, {"type": "paragraph", "children": [{"type": "variable", "name": "target_price", "label": "목표가격(고객사 지향가)", "children": [{"text": ""}], "suffix": "원(VAT별도)", "style": {"bold": true, "color": "red"}}, {"text": "으로의 조정은 당사 수익 구조상 상당한 부담을 감수한 결정", "bold": true}, {"text": "이며, 내부적으로도 쉽지 않은 승인 과정을 거쳤습니다. 이는 곧 귀사께서 그만큼 실질적인 혜택을 얻으시게 된다는 의미이기도 합니다."}]}, {"type": "paragraph", "children": [{"text": "당사가 감수한 만큼, 귀사께서도 이에 상응하는 조건으로 화답해 주시기를 정중히 요청 드립니다."}]}]'::jsonb,
'[{"type": "paragraph", "children": [{"text": "이번 조정은 당사에 결코 작은 일이 아님을 먼저 말씀드리고 싶습니다."}]}, {"type": "paragraph", "children": [{"type": "variable", "name": "anchor_price", "label": "앵커가", "children": [{"text": ""}], "suffix": "원(VAT별도)", "style": {"bold": true, "color": "red"}}, {"text": "으로의 조정은 당사 수익 구조상 상당한 부담을 감수한 결정", "bold": true}, {"text": "이며, 내부적으로도 쉽지 않은 승인 과정을 거쳤습니다. 이는 곧 귀사께서 그만큼 실질적인 혜택을 얻으시게 된다는 의미이기도 합니다."}]}, {"type": "paragraph", "children": [{"text": "당사가 감수한 만큼, 귀사께서도 이에 상응하는 조건으로 화답해 주시기를 정중히 요청 드립니다."}]}]'::jsonb,
1, 4, 4)
) AS v(user_id, name, number, script, edit_script, usage_type, tone, strategy_type)
WHERE NOT EXISTS (SELECT 1 FROM card.nego_cards WHERE user_id IS NULL AND deleted = FALSE);
@@ -172,8 +173,11 @@ WHERE NOT EXISTS (SELECT 1 FROM card.wild_cards WHERE user_id IS NULL AND delete
-- 와일드카드 전술 운영 규칙(tactic) — init-data.sql 과 동일(멱등).
UPDATE card.wild_cards SET tactic = '{"closing": true}'::jsonb
WHERE number IN ('WC-03', 'WC-05') AND user_id IS NULL AND deleted = FALSE
WHERE number IN ('WC-01', 'WC-03', 'WC-04') AND user_id IS NULL AND deleted = FALSE
AND (tactic IS NULL OR tactic = '{}'::jsonb);
UPDATE card.wild_cards SET tactic = '{"closing": true, "min_round": 2}'::jsonb
WHERE number = 'WC-05' AND user_id IS NULL AND deleted = FALSE
AND (tactic IS NULL OR tactic = '{}'::jsonb);
UPDATE card.wild_cards SET tactic = '{"min_round": 2}'::jsonb
WHERE number = 'WC-04' AND user_id IS NULL AND deleted = FALSE
WHERE number = 'WC-02' AND user_id IS NULL AND deleted = FALSE
AND (tactic IS NULL OR tactic = '{}'::jsonb);
+13 -8
View File
@@ -122,20 +122,20 @@ SELECT * FROM (VALUES
-- 10. 향후 거래 연계 — tone 4(중립) · strategy 4(협력)
(NULL::uuid, '향후 거래 연계', 'NGC-010',
'이번 거래의 가격을 {target_price}원(VAT별도)으로 조정하는 대신, {customer_condition}을 함께 검토해 주실 것을 제안 드립니다.
'이번 거래의 가격을 {anchor_price}원(VAT별도)으로 조정하는 대신, {customer_condition}을 함께 검토해 주실 것을 제안 드립니다.
당장의 단가 한 건만 보기보다 향후 이어질 거래까지 함께 고려한다면, 양사 모두에게 더 큰 가치를 만들 수 있습니다. 이번 합의를 장기적 관계의 출발점으로 삼아, 서로에게 이익이 되는 구조를 함께 설계하기를 바랍니다.',
'[{"type": "paragraph", "children": [{"text": "이번 거래의 가격을 "}, {"type": "variable", "name": "target_price", "label": "목표가격(고객사 지향가)", "children": [{"text": ""}], "suffix": "원(VAT별도)", "style": {"bold": true, "color": "red"}}, {"text": "으로 조정하는 대신, "}, {"type": "variable", "name": "customer_condition", "label": "고객사 교환·요구 조건", "children": [{"text": ""}], "style": {"bold": true}}, {"text": "을 함께 검토해 주실 것을 제안 드립니다."}]}, {"type": "paragraph", "children": [{"text": "당장의 단가 한 건만 보기보다 향후 이어질 거래까지 함께 고려한다면, 양사 모두에게 더 큰 가치를 만들 수 있습니다. 이번 합의를 장기적 관계의 출발점으로 삼아, 서로에게 이익이 되는 구조를 함께 설계하기를 바랍니다."}]}]'::jsonb,
'[{"type": "paragraph", "children": [{"text": "이번 거래의 가격을 "}, {"type": "variable", "name": "anchor_price", "label": "앵커가", "children": [{"text": ""}], "suffix": "원(VAT별도)", "style": {"bold": true, "color": "red"}}, {"text": "으로 조정하는 대신, "}, {"type": "variable", "name": "customer_condition", "label": "고객사 교환·요구 조건", "children": [{"text": ""}], "style": {"bold": true}}, {"text": "을 함께 검토해 주실 것을 제안 드립니다."}]}, {"type": "paragraph", "children": [{"text": "당장의 단가 한 건만 보기보다 향후 이어질 거래까지 함께 고려한다면, 양사 모두에게 더 큰 가치를 만들 수 있습니다. 이번 합의를 장기적 관계의 출발점으로 삼아, 서로에게 이익이 되는 구조를 함께 설계하기를 바랍니다."}]}]'::jsonb,
1, 4, 4),
-- 11. 양보 가치 강조 — tone 4(중립) · strategy 4(협력)
(NULL::uuid, '양보 가치 강조', 'NGC-011',
'이번 조정은 당사에 결코 작은 일이 아님을 먼저 말씀드리고 싶습니다.
{target_price}원(VAT별도)으로의 조정은 당사 수익 구조상 상당한 부담을 감수한 결정이며, 내부적으로도 쉽지 않은 승인 과정을 거쳤습니다. 이는 곧 귀사께서 그만큼 실질적인 혜택을 얻으시게 된다는 의미이기도 합니다.
{anchor_price}원(VAT별도)으로의 조정은 당사 수익 구조상 상당한 부담을 감수한 결정이며, 내부적으로도 쉽지 않은 승인 과정을 거쳤습니다. 이는 곧 귀사께서 그만큼 실질적인 혜택을 얻으시게 된다는 의미이기도 합니다.
당사가 감수한 만큼, 귀사께서도 이에 상응하는 조건으로 화답해 주시기를 정중히 요청 드립니다.',
'[{"type": "paragraph", "children": [{"text": "이번 조정은 당사에 결코 작은 일이 아님을 먼저 말씀드리고 싶습니다."}]}, {"type": "paragraph", "children": [{"type": "variable", "name": "target_price", "label": "목표가격(고객사 지향가)", "children": [{"text": ""}], "suffix": "원(VAT별도)", "style": {"bold": true, "color": "red"}}, {"text": "으로의 조정은 당사 수익 구조상 상당한 부담을 감수한 결정", "bold": true}, {"text": "이며, 내부적으로도 쉽지 않은 승인 과정을 거쳤습니다. 이는 곧 귀사께서 그만큼 실질적인 혜택을 얻으시게 된다는 의미이기도 합니다."}]}, {"type": "paragraph", "children": [{"text": "당사가 감수한 만큼, 귀사께서도 이에 상응하는 조건으로 화답해 주시기를 정중히 요청 드립니다."}]}]'::jsonb,
'[{"type": "paragraph", "children": [{"text": "이번 조정은 당사에 결코 작은 일이 아님을 먼저 말씀드리고 싶습니다."}]}, {"type": "paragraph", "children": [{"type": "variable", "name": "anchor_price", "label": "앵커가", "children": [{"text": ""}], "suffix": "원(VAT별도)", "style": {"bold": true, "color": "red"}}, {"text": "으로의 조정은 당사 수익 구조상 상당한 부담을 감수한 결정", "bold": true}, {"text": "이며, 내부적으로도 쉽지 않은 승인 과정을 거쳤습니다. 이는 곧 귀사께서 그만큼 실질적인 혜택을 얻으시게 된다는 의미이기도 합니다."}]}, {"type": "paragraph", "children": [{"text": "당사가 감수한 만큼, 귀사께서도 이에 상응하는 조건으로 화답해 주시기를 정중히 요청 드립니다."}]}]'::jsonb,
1, 4, 4)
) AS v(user_id, name, number, script, edit_script, usage_type, tone, strategy_type)
WHERE NOT EXISTS (SELECT 1 FROM card.nego_cards WHERE user_id IS NULL AND deleted = FALSE);
@@ -196,11 +196,16 @@ WHERE NOT EXISTS (SELECT 1 FROM card.wild_cards WHERE user_id IS NULL AND delete
-- 와일드카드 전술 운영 규칙(tactic) — 제안가는 script 변수 파싱으로 결정되므로,
-- 문장으로 알 수 없는 규칙(종결 전용·최소 라운드)만 여기 시드한다. 멱등(미설정 행만 갱신).
-- WC-03 최종 통보 · WC-05 중간값 절충 = 종결 국면 전용(마지막 한 방으로 예약)
-- WC-04 단계적 인하 제안 = 2라운드부터("당초 적정가 → 한발 물러서" 서사)
-- 목표가 제시 카드(WC-01·03·04)는 종결 전용 — 협상 중반에 목표가를 부르면 이후 올려줄 금액이
-- 없어져 남은 카드가 같은 값만 반복하게 된다. 제안은 앵커가 → 중간가 → 목표가로 수렴시킨다.
-- WC-05 중간값 절충 = 종결 전용 + 2라운드부터(간격이 좁혀진 뒤라야 절충이 성립)
-- WC-02 역제안가 제시 = 2라운드부터(상대 제안을 받아본 뒤 하는 것)
UPDATE card.wild_cards SET tactic = '{"closing": true}'::jsonb
WHERE number IN ('WC-03', 'WC-05') AND user_id IS NULL AND deleted = FALSE
WHERE number IN ('WC-01', 'WC-03', 'WC-04') AND user_id IS NULL AND deleted = FALSE
AND (tactic IS NULL OR tactic = '{}'::jsonb);
UPDATE card.wild_cards SET tactic = '{"closing": true, "min_round": 2}'::jsonb
WHERE number = 'WC-05' AND user_id IS NULL AND deleted = FALSE
AND (tactic IS NULL OR tactic = '{}'::jsonb);
UPDATE card.wild_cards SET tactic = '{"min_round": 2}'::jsonb
WHERE number = 'WC-04' AND user_id IS NULL AND deleted = FALSE
WHERE number = 'WC-02' AND user_id IS NULL AND deleted = FALSE
AND (tactic IS NULL OR tactic = '{}'::jsonb);