Compare commits

..
Author SHA1 Message Date
haewonkamandClaude Opus 5 84090433ab [docs] landing: 히어로 CTA 문구 변경 결정 기록 추가
경영진 보고용 문안을 코드 옆에 남긴다. 최초 지시안(협상 예시 보기 · 직접 체험)을
검토 과정에서 수정한 사유와, 최종안(협상 예시 체험 · 실제 데모 받기)이 지시 의도를
어떻게 유지했는지를 기록한다. 이후 CTA 문구 결정 시 참조할 원칙도 남긴다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-10 17:09:07 +09:00
haewonkamandClaude Opus 5 77d96cd4a4 [fix] landing: 히어로 CTA 문구 — 클릭 후 일어나는 일에 맞춘다
여기서 직접 체험  →  협상 예시 체험
  데모 요청        →  실제 데모 받기

두 버튼은 성격이 전혀 다른데 문구가 그걸 구분하지 못했다.
1차는 페이지 안에서 바로 조작하는 인터랙티브 데모고, 2차는 이름·이메일을 받는
리드 폼이다. 클릭 직후 경험이 다르므로 문구도 갈라야 한다.

협상 예시 체험
  고정 데이터 시뮬레이션이라 "예시"를 밝힌다. 다만 "보기"로 낮추지는 않았다 —
  도착 섹션이 "직접 경험해 보세요" 이고 역할 카드가 "공급사로 해보기" 라,
  버튼만 구경하는 말이면 클릭 전 기대와 도착 후 요구가 어긋난다.

실제 데모 받기
  누르면 폼이 뜨고 데모는 이메일로 온다. "직접 체험" 이라 쓰면 눌렀을 때 바로
  만질 줄 알았다가 입력을 요구받아 낚인 느낌이 된다. "받기" 는 이메일로 온다는
  사실이 드러나서 폼이 뜨는 게 자연스럽다.

모달 제목도 "데모 요청" → "실제 데모 받기" 로 맞췄다. 버튼이 "받기" 인데 열린 창이
"요청" 이면 전환 순간에 다른 화면처럼 읽힌다.

제출 버튼은 "데모 신청" 그대로 둔다. 같은 원칙을 적용하면 그 클릭으로 실제 일어나는
일은 신청 접수이지 데모 수령이 아니다(수령은 이메일로 나중에).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 09:47:07 +09:00
haewonkamandClaude Opus 5 d3e33b10f4 [feat] landing: 최종 CTA 결과 화면을 영상에서 컴포넌트로 — 브랜드 팔레트·중립 화자
negotiation_annotated_3d.mp4(677K)를 NegotiationReplay 컴포넌트로 대체했다.
영상이라 두 가지를 못 고쳤고, 둘 다 픽셀에 구워진 것이 원인이었다.

화자
  "아이마켓 구매 MD" 가 박혀 있었다. POC 고객사 이름이라 다른 MRO 회사에 영업할 때
  쓸 수 없다. 이제 "구매 담당자" 로, 회사명 없이 역할만 쓴다 — 상수라 언제든 바꾼다.

색
  실측하면 말풍선 #5A68CD, 목표가 라벨 #B96175, 와일드카드 배지 #DB840B 로 셋 다
  토큰에 없는 색이었고, 정작 브랜드의 핵심 대비 장치인 민트(#0FFFD6, 상대편 색)는
  한 번도 쓰이지 않았다. 이제 토큰만 쓴다 — 우리 쪽 파랑, 상대편 민트.
  진행 막대도 파랑에서 민트로 차오르며 양쪽이 만나는 지점을 그린다.

부수 효과
  - 다크 무대에 네이티브로 그리니 밝은 영상이 구멍처럼 뜨던 문제가 사라졌다.
    카드로 감싸고 그림자로 띄우던 처리가 더는 필요 없다.
  - 677K + 포스터 85K → 0. 어느 해상도에서도 선명하다(영상은 840x1260 고정이었다).
  - role="img" + aria-label 로 스크린리더가 결론을 읽는다. 영상은 못 읽었다.

숫자는 지어내지 않고 DEMO_ITEMS[0] 을 그대로 쓴다. 위쪽 인터랙티브 데모와 같은
품목·같은 가격이라 둘을 다 본 사람에게 앞뒤가 맞는다.

구현 메모
  - 화면 밖에서는 타이머를 멈춘다(IntersectionObserver). 페이지 최하단이라
    대부분의 시간 동안 보이지 않는데 계속 도는 건 배터리를 쓰는 일이다.
  - prefers-reduced-motion 이면 최종 상태를 정지 표시한다.
  - 낙찰 카드 자리를 h-[74px] 로 항상 확보하고 내용만 켜고 끈다. 나타날 때 아래가
    밀리면 페이지가 주기적으로 흔들린다. 대신 금액은 whitespace-nowrap — 고정 높이라
    한 줄이라도 접히면 잘린다(실제로 "1,080,000" 뒤 "원" 이 접혔다).

검증: 1280x900 카드 319x74 · 375x812 285x74, 슬롯 초과·가로 넘침 없음.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 13:15:46 +09:00
haewonkamandClaude Opus 5 3214e4f782 [feat] landing: 가이드 2번 탭 mp4 연결 · 최종 CTA 에 결과 화면 배치
① 이용 가이드 2번 탭 (협력사별 1:1 협상)
video 필드가 빠져 있어 이 탭만 1.7MB GIF(390x780)를 내려받고 있었다. 같은 내용의
mp4 가 저장소에 있는데 참조만 없었다 — 786K, 540x1080 으로 더 가볍고 더 크다.
GifSlot 이 video 를 우선 재생하므로 한 줄로 끝난다.

원본 캡쳐가 좌우로 잘려 문장이 중간에 끊기는 문제는 남아 있다(540x1080 원본 파일
자체에 잘린 채로 들어 있어 CSS 로 못 고친다). 재촬영이 필요하고 주석에 남겼다.

③ 최종 CTA — negotiation_annotated_3d.mp4
이용 가이드에는 넣지 않았다. 그 섹션은 "실제 화면으로 보여드립니다" 라고 약속하는데
이 영상은 재구성 목업이다(실제 UI 는 "아이마켓코리아 (구매 MD)", 영상은 "아이마켓 구매 MD").
1·3번 탭이 실제 캡쳐인데 2번만 목업이면 register 도 어긋난다.
전환을 요청하는 자리에는 그 약속이 없으므로 마케팅 컴포짓이 맞는 자리다.

- 영상 배경이 밝은 회색(#EEF4F5)이라 무대 위에 그냥 놓으면 구멍처럼 뜬다.
  모서리를 깎고 그림자를 깔아 "떠 있는 물체"로 만들면 밝기 차이가 의도로 읽힌다.
- 폰 프레임이 영상에 내장돼 있어 PhoneFrame 으로 감싸지 않는다. 감싸면 이중 프레임이다.
- 2단이 되면서 width md(max-w-4xl) → lg(max-w-5xl), 제목은 lg 부터 한 단계 축소.
  4xl 안에 세로 목업과 카피를 밀어넣으면 양쪽 다 좁아진다.
- preload="none" — 페이지 최하단이라 첫 로드에 677K 를 미리 받을 이유가 없다.

검증: 1280x900 2단 정상, 375x812 카피→영상 중앙 적층·가로 넘침 없음.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 11:56:59 +09:00
haewonkamandClaude Opus 5 e809129ae9 [feat] landing: 리드 수신 Google Apps Script 추가 (Slack 대체)
사내에서 Slack 을 쓰지 않아 수신처를 Google 로 잡는다. Apps Script 웹 앱이 POST 를
받아 스프레드시트에 적재한다 — 별도 서비스 가입 없이 이미 있는 Google 계정으로 끝나고,
영업이 시트를 그대로 열어 본다.

api/lead.ts 는 고치지 않았다. 이미 LEAD_WEBHOOK_URL 로 JSON 을 POST 하고, Slack 용
text 와 원본 필드를 함께 실어 보내도록 만들어 둬서 수신처만 바꾸면 된다.

스크립트는 docs/ 에 둔다. landing/api/ 안에 두면 Vercel 이 /api 규약에 따라 이 .js 를
서버리스 함수로 빌드하려 들고, Apps Script 전역(SpreadsheetApp 등)을 쓰므로 배포가 깨진다.

스크립트가 처리하는 것
- 헤더 자동 생성·확장. 나중에 필드가 늘어도 스크립트를 다시 안 고쳐도 된다.
- LockService 로 동시 제출이 같은 행에 겹쳐 쓰는 것을 막는다.
- Slack 전용 요약(text)은 시트에서 제외 — 같은 내용이 개별 필드에 이미 있다.
- doGet 은 배포 직후 생존 확인용.

설치 절차는 파일 상단 주석에 있다. 배포 후 Vercel 환경변수 LEAD_WEBHOOK_URL 설정 +
재배포가 필요하다 — 환경변수는 배포 시점에 주입된다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 11:34:01 +09:00
haewonkamandClaude Opus 5 631a501c5c [chore] landing: 렌더되지 않던 ROI 시뮬레이터 제거
roi-simulator.tsx 는 어디에서도 import 되지 않아 화면에 나오지 않았다.
누락이 아니라 의도적으로 내린 것이다 — 9ccf42c("카피 정직화")에서 <ROISimulator /> 를
빼고 그 자리에 <Comparison />, <Faq /> 를 넣었다.

되살리지 않는 이유는 파일 자체에 있다. 카피는 "아직 실제 도입 실증 사례가 없는
신규 카테고리"라고 스스로 인정하면서 절감액을 제시하고, 계산은 근거 없는 추산이다
(협력사당 6.5시간). 브랜드 보이스 가드레일 통과 기준 3번 — 주장·수치에 출처가 붙어야
하고 출처 없는 주장은 FAIL — 과 정면으로 부딪힌다. 다시 붙이려면 근거부터 확보해야 한다.

range-slider.tsx 도 함께 지운다. 사용처가 roi-simulator 하나뿐이라 같이 죽는다.

되살릴 일이 생기면 git 이력에 그대로 남아 있다.

남은 고아 두 개는 이번 작업과 무관한 기존 항목이라 두었다:
  components/ui/price-sparkline.tsx
  components/ui/slate-renderer.tsx

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 11:30:03 +09:00
haewonkamandClaude Opus 5 ab77900dac [feat] landing: 본문 브랜드 표기를 네고시움으로 한글화
한글 문장 안에 영문 브랜드명이 섞이면 읽는 흐름이 끊긴다. 본문 카피만 바꾸고,
성격이 다른 자리는 남겼다.

바꾼 곳 (한글 문장 안)
  reinforcement · final-cta · footer 소개문 · how-it-works-demo · comparison 토글 · roi-simulator

남긴 곳과 이유
  logo.tsx alt="NEGOTIUM"    로고는 영문 워드마크 이미지다. alt 만 한글로 바꾸면
                             보이는 것과 읽히는 것이 어긋난다.
  footer © negotium Co., Ltd. 법인 표기. 등기된 이름이라 임의로 한글화할 수 없다.
  console.negotium.ai        실제 도메인.
  og:site_name               브랜드 정식 핸들.
  코드 주석                   내부 문서.

메타 타이틀은 "네고시움(negotium)" 으로 둘 다 담았다. 영문을 빼면 negotium 으로
검색해 들어오던 유입이 끊긴다 — 검색 질의는 사용자가 정하지 우리가 못 정한다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 11:19:30 +09:00
haewonkamandClaude Opus 5 09d24f5022 [fix] landing: 구매자 모드 응수에 목표가 반영 · 무대 선택색 · 플레이 화면 유리 패널
구매 담당자 모드
공급사 모드와 같은 문제가 있었다. simulateBuyerRun 의 에이전트 첫 수가 marketLow 만
읊어서, 목표가를 얼마로 잡든 같은 문장이 나왔다 — 위임한 기준이 반영되는지 확인할
길이 없었다. 이제 목표가를 받았다고 명시하고, 시장 최저가 대비 위치에 따라 태도를
달리한다(근거부터 깔겠다 / 무리 없이 접근하겠다).
여는 말(협력사 정가 제시)은 아직 목표가를 모르는 시점이라 상수로 둔다.

무대 위 드래그 선택색
루트의 selection:text-primary 는 라이트 본문 기준이다. 그 값(#0101F3)을 무대(#070E24)
위에 얹으면 명암비 2.0:1 — app.css 의 --color-primary-on-stage 주석이 경고하는 바로 그
상황이다. 무대 섹션에서 텍스트를 드래그하면 글자가 사라졌다.
.stage-bg / [data-stage-hero] 안에서는 무대용 액센트로 갈아끼운다.

플레이 화면 유리 패널
컨트롤과 대화 로그가 섹션 배경 위에 그냥 얹혀 있어 무대와 같은 색이라 경계가 없었고,
조작 가능한 영역인지 읽히지 않았다. 재질은 무대 위 2차 CTA 와 같게 맞췄다 — 화면 안에
재질이 두 종류면 따로 논다. 테두리는 white/12 로 얕게: 면이지 조작 요소가 아니라
버튼만큼 세우면 카드가 버튼처럼 보인다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 11:17:16 +09:00
haewonkamandClaude Opus 5 4536a48e40 [fix] landing: 제시가를 바꿔도 에이전트 응수가 그대로이던 문제
공급사 모드에서 슬라이더를 움직여도 첫 응수의 문장과 숫자가 똑같았다.

원인은 두 겹이다.
- 근거 문장이 offer 를 참조하지 않았다. cardsUsed === 0 분기가 marketLow 만 읊었다.
- CONCESSION[0] = 0 이라 부르는 값(ask)도 앵커로 고정이다.
둘이 겹쳐서, 얼마를 제시하든 화면이 전혀 반응하지 않는 것처럼 보였다.

값 고수는 유지한다 — 앵커를 지키는 게 이 에이전트의 성격이고, 제품이 파는 신뢰가
거기서 나온다. 대신 무엇에 대한 응수인지는 매번 달라지게 했다.

  정가 이상   정가 그대로는 검토가 어렵습니다 + 시장 최저가 제시
  최저가 위   제시가가 최저가보다 얼마 높은지 구체 수치로
  최저가 이하 최저가 선까지 내려온 것을 인정 + 기준까지 남은 격차

입력란 숫자에 콤마 누락도 같이 고쳤다. 화면의 다른 금액은 전부 won() 인데 여기만
1018800 으로 나와 같은 값으로 안 읽혔다. 확정 시 콤마를 넣고 파싱할 때 벗긴다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 11:10:50 +09:00
haewonkamandClaude Opus 5 ea1249429a [feat] landing: 무대 위 2차 CTA 에 유리 재질 — 데모 요청·상담 신청
두 버튼 모두 무대에서 stageGhost 를 쓰므로 변형 하나로 해결된다.

구성은 넷 — 옅은 흰 채움, 뒤를 흐리는 backdrop-blur(12px), 위쪽 1px 안쪽 하이라이트
(유리 모서리에 빛이 걸리는 부분), 아래로 깔리는 부드러운 그림자. 채도를 살짝 올리면
뒤가 흐려지며 빠지는 색기가 돌아온다(saturate 1.5).

테두리는 white/40 에서 더 내리지 않았다. /30 이면 무대 광원부(#16205A) 대비가
2.60:1 로 떨어져 WCAG 1.4.11(UI 경계 3:1)에 미달한다 — 유리 느낌 때문에 버튼이
안 보이던 원래 문제(대비 1.09:1)로 되돌아간다. 투명감은 채움과 blur 로 내고 테두리는 지킨다.

hover 는 흰색 반전이 아니라 채움을 밝힌다. 유리는 뒤가 비치는 게 정체성이라
불투명하게 뒤집으면 그 순간 유리가 아니게 된다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 11:00:46 +09:00
haewonkamandClaude Opus 5 d2f1a8f6f4 [fix] landing: 히어로 배경이 탁하고 흐리던 문제 — 스크림 축소 + 재인코딩
탁함: 스크림이 원인이었다. stage-deep(#03060F) 을 90/60/95 알파로 전면에 깔아
가장 옅은 지점에서도 영상이 40% 만 남았다. 그 값은 헤드라인 둘째 줄이 회색(/60)이던
시절 그 글자를 살리려고 넣은 것인데, 헤드라인이 흰색이 된 뒤로는 근거가 없어졌다.
게다가 중앙이 가장 옅어서 — 정작 글자가 있는 자리 — 보호 목적으로도 방향이 틀렸다.

흐림: 1280x720 crf 30 은 전면 배경으로 무르다. 1600x900 crf 24 로 재인코딩.
업스케일 1.19배 → 0.96배(다운스케일)로 바뀌어 선명도가 올라간다. 631K → 1.7M.

스크림을 걷었더니 이번엔 리드 문단(17px)이 밝은 입자 위에서 안 읽혔다. 헤드라인은
흰색 74px 이라 버티지만 본문은 못 버틴다. 전면을 덮으면 영상이 탁하고, 다 걷으면
본문이 안 읽힌다 — 둘 다 만족하려면 덮는 범위를 글자가 있는 자리로 좁혀야 한다.

  세로 그라데이션  50 / 투명 / 45   헤더 nav 와 하단 전환만 보호
  중앙 방사형      85 → 55 → 투명   카피 뒤만 국소적으로

색은 color-mix 로 --color-stage-deep 를 참조한다. 하드코딩하면 토큰이 둘이 된다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 10:57:49 +09:00
haewonkamandClaude Opus 5 be039dd92b [feat] landing: 협상 데모에 에이전트 추천가·직접 입력 추가, 히어로 헤드라인 흰색 통일
데모 — 추천하고, 사용자가 고친다
슬라이더 하나뿐이라 정확한 값을 넣을 수 없었고, 에이전트가 추천하는 자리도 없었다.
"에이전트가 제안하면 사람이 확정한다"가 제품의 관계인데 UI 가 그걸 보여주지 못했다.

- 에이전트 추천가 + 근거 + 원클릭 적용. 값은 지어내지 않고 시뮬레이터가 실제로 쓰는
  수치에서 가져온다 — 구매자는 anchor(reachable = target >= anchor 인 최저선),
  공급사는 marketLow(에이전트가 응수할 때 인용하는 값). 지어낸 숫자를 추천이라 부르면
  사용자가 그대로 넣었을 때 결과가 설명되지 않는다.
- 직접 입력란 추가. 실제 구매 담당자는 "얼마까지"라는 숫자를 이미 들고 온다.
  타이핑 중에는 clamp 하지 않고 blur/Enter 에서 확정한다 — 입력 즉시 범위로 당기면
  "1" 을 치는 순간 튕겨서 손가락과 싸운다.
- 슬라이더·직접입력·추천적용이 commitOffer 한 곳을 거친다. 경로가 셋이면 값이 셋 된다.
- 에이전트 응수 후 offer 만 갱신하고 입력란은 두던 버그 수정. 슬라이더와 숫자가 어긋났다.
- 잠금 조건(role === buyer && turns.length > 0)을 inputLocked 로 묶었다.

히어로 헤드라인
"동시에 협상합니다." 를 흰색으로. 예전 캔버스는 하단 밴드에만 입자가 있어 헤드라인
뒤가 거의 단색이었고 그때는 투명도 60% 도 읽혔다. 배경이 영상으로 바뀌며 밝은 요소가
글자 뒤로 지나가 대비가 무너졌다 — 배경이 움직이는 위에서는 가독성이 조판 장치보다
우선한다. 2톤은 배경이 정적인 최종 CTA 에 남아 있다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 10:52:29 +09:00
haewonkamandClaude Opus 5 2888ff2c28 [feat] landing: 리드 수집 서버리스 함수 + 상담 신청 폼 실전송 연결
랜딩은 ssr:false 정적 빌드라 서버 라우트가 없다. Vercel /api 디렉터리 함수로 받는다.
클라이언트가 같은 오리진(/api/lead)으로 쏘므로 엔드포인트 환경변수도 CORS 도 없다.

api/lead.ts — 리드를 잃지 않는 것이 유일한 책임
  1) 먼저 구조화 로그를 남긴다. 웹훅이 죽어도 Vercel 로그에 리드가 남는다.
  2) LEAD_WEBHOOK_URL 이 있으면 전달(Slack Incoming Webhook·Zapier·자체 API 모두 POST).
     Slack 용 text 와 원본 필드를 함께 실어 수신처를 바꿔도 이 파일을 안 고친다.
  3) 웹훅 실패해도 200 — 1) 에서 리드를 확보했으니 방문자에게 재입력을 시킬 이유가 없다.
     대신 실패는 로그에 크게 남긴다.
  봇 함정(website) 값이 차 있으면 조용히 200. 400 을 주면 어떤 필드가 함정인지 알려주는 셈이다.

contact.tsx — 가짜 성공 제거
  기존엔 setTimeout 1.2초 뒤 성공 화면만 띄우고 아무 데도 보내지 않았다. 화면은
  "접수되었습니다"인데 영업이 받을 리드는 없었다. 이제 같은 함수로 보내고 서버가
  리드를 확보했을 때만 성공을 띄운다. 실패 시 role="alert" 로 안내.

vercel.json — SPA 리라이트가 /api 를 삼키지 않도록 제외.
  "/(.*)" 그대로 두면 /api/lead 요청이 index.html 로 갔다.

데모 요청 모달 카피
  "이름과 이메일만 남겨주시면, 담당자가 일정을 잡아 연락드립니다"
  → "성함과 이메일만 남겨주시면, 사용해보실 수 있는 Demo를 보내드립니다!"
  성공 화면도 같은 약속으로 맞췄다. 폼은 데모를 보낸다는데 성공 화면이 일정을
  잡는다고 하면 방문자가 무엇을 기다려야 하는지 모른다. 라벨도 성함으로 통일.

⚠️ LEAD_WEBHOOK_URL 미설정 시 리드는 Vercel 로그에만 남는다. 로그는 최후의 그물이지
   CRM 이 아니다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 10:48:06 +09:00
haewonkamandClaude Opus 5 c53eeefcf6 [feat] landing: 데모 요청 리드 캡처 + 히어로·데모 카피 교체
카피
- 데모 섹션 헤드라인: "직접 협상해 보세요 / 에이전트는 정해진 기준을 벗어나지 않습니다"
  → "사용할수록 진화하는 에이전틱 협상, / 직접 경험해 보세요!"
  예전 카피는 FAQ 2번("에이전트가 우리 기준을 벗어나 합의해 버리면요?")을 헤드라인으로
  끌어올린 것이었다. 아직 생기지도 않은 반론에 가장 비싼 한 줄을 쓰고 있었고,
  부정문이라 "안 하는 일"을 약속했다 — 체험을 권하는 자리에 맞지 않는다.
  방어는 FAQ 에 그대로 남아 있다.
- 히어로 1차 CTA: "직접 협상해 보기" → "여기서 직접 체험"
- 히어로 2차 CTA: "도입 문의" → "데모 요청". 기존엔 #contact-section 으로 가서
  GNB "상담 신청" 과 목적지가 같았다 — 버튼만 둘이고 경로는 하나였다.

리드 캡처
- DemoRequestModal 신규. 이름·이메일 두 칸만 받는다. 필드가 늘수록 이탈이 늘고,
  영업 첫 연락에 필요한 최소가 그 둘이다. 나머지는 통화에서 채운다.
- 모달로 띄우는 이유: 히어로에서 관심이 생긴 자리에서 받아야 한다. 스크롤로
  내려보내면 그 사이에 식는다. 고관여 폼(상담 신청)은 그대로 두고 그 앞단을 만든 것.
- 접근성: Esc 닫기, Tab 을 모달 안에 가둠, 열릴 때 첫 필드 포커스·닫힐 때 복원,
  aria-modal/labelledby, 배경 스크롤 잠금, prefers-reduced-motion 대응.

전송 경로 — 성공을 위조하지 않는다
contact.tsx 는 1.2초 뒤 성공 화면만 띄우고 아무 데도 보내지 않는다("백엔드 미연결").
리드 제너레이션에서 그 방식은 최악이다. 화면은 접수됐다고 하는데 영업이 받을 리드는
없고, 아무도 그 사실을 모른다. 그래서 lib/lead.ts 는 VITE_LEAD_ENDPOINT 가 없으면
not-configured 를 돌려주고, 모달은 그걸 실패로 처리해 상담 신청 경로를 안내한다.

⚠️ VITE_LEAD_ENDPOINT 를 설정하기 전까지 데모 요청은 저장되지 않는다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 10:40:28 +09:00
haewonkamandClaude Opus 5 f214fccc49 [feat] landing: 히어로 배경을 캔버스에서 루프 영상으로 교체
배경이 설명을 지던 구조를 걷어냈다. 예전 캔버스는 negotium 파이프라인을 직접
그렸지만(입자 240개·6단계 서사·무리 라벨), 이제 배경은 배경으로만 쓴다.
설명은 카피와 아래 섹션이 맡는다.

영상: hero_veo31 0~5초를 크로스페이드 루프로. 그냥 자르면 끝에서 처음으로 튀어서
끝 0.8초를 앞 0.8초와 겹쳐 이음새를 없앴다(결과 4.25초, 첫↔끝 프레임 RMS 18.6/255).
1280x720 h264 631K + 포스터 58K. webm 은 뺐다 — VP9 이 1.0M 으로 h264 보다 커서
둘을 다 실을 이유가 없다.

- CLUSTER_ANCHORS 라벨 제거. 좌표 소스가 사라진 라벨은 화면비마다 어긋나기만 하고
  아무것도 설명하지 못한다.
- DataFlowPhase 를 orbit-ring 으로 이관 후 data-flow-canvas.tsx(500줄) 삭제.
  단계 이름을 실제로 쓰는 건 강화학습 섹션의 순환 링뿐이다.
- 영상은 가로 화면에서만 튼다. 16:9 를 세로에 object-cover 로 깔면 가로가 62% 잘리고
  남은 38% 가 1.7배로 확대된다(848x1220 실측) — 입자가 거대한 보케로 뭉개져 배경이
  아니라 노이즈가 된다. 세로에서는 무대 그라데이션만 남긴다. 모바일 대역폭도 아낀다.
- prefers-reduced-motion 도 같은 경로로 영상을 감춘다. 포스터가 뒤를 받친다.
- 스크림은 색 하나(stage-deep)로 알파만 움직인다. 중간 stop 에서 색을 바꿨더니
  그 지점이 가로선으로 읽혔다.
- 밴드 개념이 사라져 히어로 레이아웃을 카피 중앙 정렬로 되돌렸다. 직전 커밋의
  --band-top 기준 높이 계산은 더 이상 필요 없다.

검증: 1440x860 크롭 7%, 375x812 영상 숨김·제목 헤더 여유 152px, 콘솔 에러 없음.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 10:24:21 +09:00
haewonkamandClaude Opus 5 63717f5eb9 [fix] landing: 무대 위 2차 CTA 가 버튼으로 안 읽힘 — stageGhost 대비 확보
GNB "상담 신청" 이 기본 상태에서 버튼으로 인식되지 않았다. 채움이 없고
테두리는 사실상 안 보여서, 남는 건 흰 글자와 화살표뿐 — 옆 nav 링크와
구분될 근거가 없었다.

테두리를 stage-line(#1E2A52)으로 잡은 게 원인이다. 그 색은 무대 바닥(#070E24)
위 카드용인데, 헤더는 방사형 그라데이션의 광원부(#16205A)에 앉는다. 같은 색
가족이라 하필 헤더 자리에서만 선이 배경에 묻힌다.

  수정 전  테두리 대비 1.09:1  (배경과 사실상 동일)
  수정 후  테두리 대비 3.56:1  (WCAG 1.4.11 UI 경계 3:1 통과)

무대색 토큰 대신 흰색 알파로 잡았다 — 무대 어디에 놓여도 같이 성립한다.
옅은 채움(white/10)도 함께 준다. "누를 수 있는 것"은 테두리보다 면이 더
강하게 전달한다.

히어로 "도입 문의" 도 같은 변형이라 함께 해결된다. 1차 CTA(파란 채움)와의
위계는 그대로다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 09:28:23 +09:00
haewonkamandClaude Opus 5 7f15bc10d1 [fix] landing: 히어로 카피와 입자 밴드 겹침 — 경계를 구조로 강제
버튼 행이 입자 밴드를 파고들었다. 1280x720 에서 34px, 무리 라벨과는 7px.
1440x900 에서만 여유가 있어(45px) 안 보이던 문제다.

원인은 두 값이 서로 다른 기준으로 움직인 것:
  카피 상단 여백  19vh        화면 비율
  카피 높이       351px       고정
  밴드 시작       0.63×높이   화면 비율
카피만 px 고정이라 화면이 짧아지면 밴드가 카피를 덮는다.
0.19H + 351 > 0.63H  →  H < 798px 이면 전부 겹친다.
1280x720, 1366x768 같은 흔한 노트북 높이가 여기 들어간다.

pt-[19vh] 는 위치만 잡을 뿐 경계를 강제하지 못한다. 그래서:
- 카피 영역 높이를 밴드 시작선에 묶었다. 뷰포트와 무관하게 구조적으로 못 겹친다.
- BAND_TOP 을 export 해 캔버스와 카피가 같은 값을 쓴다. 라벨 좌표가 이미 쓰던 방식이다.
- 높이·밴드를 한 식에서 뽑는다. 따로 두면 어긋난다 — 밴드를 63vh 로 두고 높이만
  키웠더니 짧은 화면에서 변수가 실제 밴드보다 위를 가리켰다.
- min-h 바닥 780px. 밴드 위 공간에 헤더(104)+카피(351)+여유(24)=479px 가 들어가려면
  높이 760px 이 하한이라, 정렬만으로는 짧은 화면을 못 구한다. 살짝 스크롤될 뿐이다.
- pt-[104px] 를 md 이상에서도 유지. 빼면 가운데 정렬이 카피를 fixed 헤더 밑으로 민다.

검증(실측, 음수 = 밴드 밖):
  1280x620   +20 → -30,  헤더 여유 +12,  라벨 75px
  1280x720   +34 → -30,  헤더 여유 +12,  라벨 75px
  1440x900   -45 → -68,  헤더 여유 +50,  라벨 122px
  375x812          -57,  헤더 여유 +6

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 09:22:54 +09:00
haewonkamandClaude Opus 5 d3bcc61609 [chore] landing: Vercel 배포 설정 추가
랜딩은 ssr:false + prerender 인 SSG 라 정적 산출물만 서빙하면 된다.
프레임워크 자동 감지에 맡기면 React Router 를 SSR 로 잡을 수 있어
framework:null 로 명시하고, outputDirectory 를 build/client 로 고정한다.
SPA 리라이트는 Dockerfile.prod 의 nginx try_files 와 동등하게 맞췄다.

.vercel 은 gitignore. 프로젝트·조직 ID 가 들어가는 로컬 링크 파일이다.

배포 메모:
- 저장소가 Gitea 라 Vercel Git 연동(푸시 시 자동 배포)은 안 된다. CLI 수동 배포.
- 새 프로젝트의 첫 배포는 --prod 없이도 production 으로 승격되니,
  preview 를 원하면 --target=preview 를 명시할 것.
- preview 배포는 Vercel 이 x-robots-tag: noindex 를 자동으로 붙인다.
  색인 차단 목적으로 public/robots.txt 를 건드리지 말 것 — 출시 때 되돌리는 걸 잊는다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-05 16:36:40 +09:00
haewonkamandClaude Opus 5 55e3ab02aa [fix] landing: 섹션 세로 리듬 통일 — 간격을 SectionHeading 이 소유
디자인 시스템이 색·활자만 소유하고 간격은 각 섹션 파일에 흩어져 있어,
같은 관계에 값이 여러 개 생겼다. 스크롤할 때 섹션마다 호흡이 달라지던 원인.

  eyebrow → title      12/20px      → 16px
  title → description  16/20/32px   → 20px (display 티어 32px)
  머리 → 본문          48~96px 5종  → 56px / 80px(md)
  컨트롤 → 본문        56/64px      → 48px
  리드 → CTA           56/48px      → 48px

- SectionHeading 이 리듬을 소유하고 HEADING_GAP·CONTROL_GAP·CTA_GAP·
  DISPLAY_LEAD_GAP 를 노출. 섹션 파일에서 mb-24 같은 값을 직접 쓰지 않는다.
- negotiation-demo·final-cta 가 Section/SectionHeading 을 우회해 머리를 직접
  조판하고 있었다 — 아이브로우 간격이 이 둘만 20px 이던 원인. 프리미티브로 환원.
- SectionHeading 이 eyebrow 없이도 빈 span 을 렌더해 유령 여백이 생기던 버그 수정.
- descriptionClassName 의 text-[17px] 중복 선언 제거. lead 변형이 이미 갖고 있는
  모바일 축소 단계(text-[16px] sm:text-[17px])를 지우고 있었다.
- reinforcement: text-balance 가 쉼표를 넘어 끊던 헤드라인을 <br /> 로 명시.

reinforcement 만 gap="none" 인데, 머리가 그리드 셀 안이라 마진이 상쇄되지 않아
items-center 정렬을 밀기 때문. 간격은 그리드 래퍼가 진다.

검증: tsc --noEmit 통과, 프로덕션 빌드 통과. DOM 실측으로 375/868/1440px
전 구간에서 머리→본문·eyebrow→title·컨트롤→본문 값 일치 확인.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-05 16:22:24 +09:00
haewonkamandClaude Opus 5 bae0da42d2 [fix] landing: 히어로 세로 리듬 확보 — 간격 확대·헤드라인 74px
답답함의 원인은 가로 비율이 아니라 세로 간격이었다. 헤드라인 80px 에 대해
헤드라인↔서브 28px, 서브↔CTA 40px 는 너무 촘촘했다.

- 간격 확대: mt-7 → mt-11(44px), mt-10 → mt-14(56px).
- 헤드라인 80 → 74px. 글자 실폭이 뷰포트의 40% (레퍼런스 statworx 는 48%).
- 측정 주의사항을 주석에 남김: h1 은 블록이라 getBoundingClientRect 로 재면
  컨테이너 폭(848px)이 나온다. Range 로 텍스트 노드를 재야 실제 글자 폭이다.
  이걸 헷갈려 한 번 과교정(66px, 36%)했다가 되돌렸다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 18:43:16 +09:00
haewonkamandClaude Opus 5 15369a016d [fix] landing: 히어로 여백 확보 — 순환 링을 강화학습 섹션으로 이동
히어로에 헤드라인·서브·CTA 2개·군집 밴드·순환 링이 다 들어가 세로 예산이 포화라
위를 벌리면 아래가 터지는 상태였다. 링을 옮겨 자리를 만든다.

- 순환 링을 강화학습 섹션으로. "협상할수록 좋아진다"를 말하는 자리라
  루프가 의미상 속하는 곳이기도 하다. 텍스트 좌 / 링 우 2단 배치.
- OrbitRing 에 자체 시계 모드 추가 — progressRef·phase 를 안 주면 스스로 돈다.
  덕분에 히어로 캔버스와 무관한 섹션에서도 단독으로 쓸 수 있다.
- 히어로 상단 여백 14vh → 19vh, 밴드를 하단 전체(0.63/0.30)로 확장.
- 군집 라벨 y 계산 버그 수정. 밴드 지역 좌표(0.5)를 화면 좌표로 착각해
  밴드를 옮길 때마다 라벨이 엉뚱한 곳으로 갔다. 이제 행 수·행간에서
  격자 상단을 실제로 계산해 투영한다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 18:34:42 +09:00
haewonkamandClaude Opus 5 5917942fe3 [fix] landing: 모바일 대응 — 글리프 배율·밴드 리맵·헤더 겹침
- 글리프 크기를 화면 폭에서 파생. 격자 간격은 dx × width 로 폭에 비례하는데
  글리프가 CSS px 고정이라 375px 에서 셀(7.7px)보다 커져(22px) 서로 겹쳐 덩어리가 됐다.
- 좁은 화면(<640px)에서는 밴드를 링 뒤로 내리고 군집 라벨을 접는다.
  모바일은 CTA 가 세로로 쌓여 세로 예산이 부족하고, 375px 에서 3군집을 나란히 두면
  군집당 100px 남짓이라 어차피 판독이 안 된다. 의미는 순환 링이 담는다.
- 히어로 상단 여백을 vh 대신 모바일 고정값으로. 헤더는 고정 높이라
  pt-[7vh](모바일 57px)로는 헤더(약 70px)를 피할 수 없어 헤드라인이 겹쳤다.
- 데스크톱 상단 여백 복원(14vh)과 밴드 재배치(0.575/0.155), 링 290px.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 18:27:02 +09:00
haewonkamandClaude Opus 5 87b896fc2f [fix] landing: 히어로 구도 좌측 쏠림 · 순환 링 정원화 · Playfair self-host
- 군집 좌표를 투영 후 위치에서 역산하도록 변경.
  sx = 0.5 + (x−0.5)·k 라 깊이마다 당겨지는 양이 다르고, 가장 깊은 협력사가
  중앙으로 제일 많이 끌려와 구도가 왼쪽으로 쏠렸다. 이제 화면 19/50/81% 에
  대칭으로 놓인다 — 라벨도 같은 값을 써서 어긋나지 않는다.
- 순환 링을 원근 타원에서 정원으로 교체(orbit-ring). 점선 궤도만 회전하고
  마디·라벨은 고정이다. 눕힌 타원은 깊이는 생기지만 "닫힌 루프"의 완결감이 없다.
- 학습 단계 입자 궤도 제거. 화면을 가로지르는 큰 선이 순환 링과 의미가 겹치고
  시선을 뺏었다. 순환은 링이 맡고 입자는 안쪽으로 흡수만 한다.
- Playfair Display self-host(latin 서브셋 39KB). 구글 폰트 CDN 제거 —
  서드파티 요청이 LCP 를 흔들고 방문자 IP 가 외부로 나간다.
- 히어로 CTA "협상 시연 보기" → "직접 협상해 보기".
  데모는 실제로 동작한다(앵커 이하 낙찰 · 카드 소모 역제안 · 소진 시 개찰 확인).
  수동태 문구는 인터랙티브 기능을 영상처럼 보이게 해 전환을 깎는다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 17:16:28 +09:00
haewonkamandClaude Opus 5 6785c8a6f4 [feat] landing: 랜딩 v2 — 다크 무대 히어로·인터랙티브 협상 데모·디자인 토큰 재정립
레퍼런스(statworx·jitter·infinith) 실측값으로 디자인 시스템을 다시 잡고,
스크롤 재생형 콘솔을 사용자가 직접 협상하는 데모로 교체했다.

디자인 토큰
- 타이포: 굵기·크기·자간을 함께 조정(섹션 제목 44→64px/600→800/자간 -0.042em).
  한글 행간은 1.07 — 라틴 기준 0.95 를 쓰면 네모틀이 꽉 차 줄이 닿는다.
- 모서리: 12가지로 흩어져 있던 값을 card 8px / control 4px / full 셋으로 수렴.
  20~32px 짜리 뭉툭한 카드가 제네릭 SaaS 의 가장 강한 신호였다.
- 다크 무대 토큰 신설(stage/on-stage/counter) + 배경 그라데이션.
- primary-on-stage(#7C8CFF) 추가 — #0101F3 은 무대 배경 대비 2.0:1 로
  WCAG 최소(4.5:1)의 절반도 안 돼 다크 위에서 읽히지 않았다.
- 영문 디스플레이 서체 Playfair Display self-host(latin 서브셋 39KB).

히어로
- 배경 캔버스가 실제 파이프라인을 그린다: 수집→분류→대조→산정→협상→학습.
  분류 단계는 거래 품목(시트)·사용자·협력사로 갈라지고 라벨이 붙는다.
- z 좌표 + 원근 투영. 군집마다 z 평면을 하나씩 줘 격자는 온전한 채 깊이만 생긴다.
- 순환 링(정원, 점선 궤도 회전). 진행도는 ref 로 공유해 60fps 리렌더를 피한다.
- 카피에 진입 애니메이션을 걸지 않는다 — LCP 요소라 opacity:0 으로 시작하면
  하이드레이션 전까지 첫 화면이 빈다.

협상 데모 (신규)
- 역할 선택(공급사/구매 담당자) → 품목·단가 제시 → 턴 협상 → 낙찰/개찰 → 상담 신청.
- 판정 규칙은 실제 엔진과 동일: 앵커링가 이하 낙찰, 협상 카드 3장, 소진 시 개찰.
- 로직은 lib/negotiation-sim.ts 순수 함수로 분리 — 나중에 agent 서비스 연동 시
  컴포넌트를 건드리지 않는다.

카피 감사
- "봇" 21곳 → "에이전트"(로봇 아이콘 3개 포함). 대리인은 조달 실무의 정당한 역할이다.
- "악역은 봇이", "단가를 깎는 악역" 제거 — 협력사를 적으로 규정하는 프레임은
  같은 페이지 FAQ(공급사 만족도 82%)와 모순이고, 동반성장 평가를 받는
  대기업 구매팀 결재 라인에 올릴 수 없다.
- 번역투 최상급(초정밀·압도적·완벽히·최적의)과 데모 대화문 전면 재작성.

버그 수정
- 헤더가 흰 배경 위에 흰 글자 버튼을 그리던 문제. onStage 를 스크롤 수치로 계산해
  하이드레이션 전 스크롤 복원 시 초기값이 굳었다 → IntersectionObserver 로 교체.
- 버튼 transition-all → transition-colors (variant 교체 시 배경 플리커).
- 폼 입력 14px → 16px. iOS 사파리는 16px 미만 입력에 포커스하면 화면을 확대해
  모바일 폼 이탈을 만든다.

정리
- 대체된 히어로 3종·기존 협상 콘솔 삭제(약 760줄).
- 라벨 아이콘·알약 배지·blur(120px) 글로우 블롭 제거.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 17:08:37 +09:00
minaChoi 3c3f60c7d4 [chore] 루트 업로드 샘플 CSV 4종 제거(upload-samples/ 와 중복) 2026-07-31 10:26:44 +09:00
minaChoi bd0f39f131 [feat] negodata·agent: 목표가 네고 적용/미적용 산정근거·와일드카드 1% 10원 반올림·표 xl 전환·QA 체크리스트 2026-07-31 10:22:51 +09:00
minaChoi 775984fe48 [fix] negosium: 협상카드 카운터가 10원 단위 반올림 — 앵커·목표가와 표기 통일 2026-07-30 15:20:01 +09:00
minaChoi 5520e3c2b6 [feat] negodata: 견적 삭제(개발자 전용)·연결 데이터 캐스케이드 soft-delete
- 견적관리 체크박스 선택 + 툴바 '선택 삭제'(상품·협력사 패턴), 상세 시트 단건 '삭제'
- 백엔드 soft_delete 를 연결 협상 세션·대화까지 한 트랜잭션 캐스케이드
- 체크박스·선택삭제·상세삭제 모두 개발자(role 3)에게만 노출
2026-07-30 13:20:42 +09:00
minaChoi 2a004734d8 [feat] negodata·negosium: 엑셀 데이터 내보내기·견적상세 협상카드 연동·드로어 뒤로가기
- 엑셀 데이터 내보내기(상품·협력사·협상카드): 현재 검색/페이지 필터를 무시하고 전체를 페이지 순회로 받아(fetchAllForExport, 무언 절삭 방지) 양식과 동일 헤더로 CSV 내보내기(downloadXxxData) + '데이터 다운로드' 메뉴·todayStamp 파일명 → 내려받아 수정 후 재업로드(라운드트립)
- 견적상세 ChatTab: 사용 협상카드 매칭을 chat_id→card_id(카드 PK)로 교정, 카드 사용 메시지 본문 script 중복 제거(카드 박스에만 노출), 카드칩→/cards?detail= 상세 링크, 카드 멘트 실가격 마스킹(target_price 변수 미주입+maskPrices)
- 견적상세 협상카드 탭: 번호·스크립트 미리보기 컬럼 추가(cardScriptPreview 평문 추출)·카드명 상세 링크
- 상세 드로어: 백드롭 좌상단 '뒤로'(navigate(-1)) 버튼 추가(데스크톱), 공용 Sheet·견적상세 동일 적용
- 협상요약(negosium): 배송 리드타임 라벨을 회사설정(labels.lead_time) 연동 → '표준납기' 표기
2026-07-30 11:03:51 +09:00
minaChoi 35d38e0818 [feat] negosium: 협상 리스트 마감기준 정렬 컨트롤
- SortControl(기본순/마감임박순/여유순) 추가, StatusTabs 우측에 배치
- store setDeadline 배선 — 선택값을 서버 정렬(deadlineToOrder)로 전달
2026-07-30 08:31:16 +09:00
minaChoi 82cca894fc [fix] negosium: 'MD → 구매담당자' 표기 통일
- 챗 봇/안내 라벨(ChatMessage·MDInformation·index.css 메뉴 제목)
- negodata 목표가 산정 문구(pricing) · 온보딩 FAQ/용어(OnboardingGuideModal)
- 견적생성 메모 라벨을 '협력사 안내 메모'로 명확화(협상방에서 협력사에게 보여줄 내용)
2026-07-30 08:31:16 +09:00
minaChoi 9716528ce7 [feat] negosium: 협상 챗 헤더 정리 — 상품명 대표 + 견적번호
- 헤더 대표값을 협상 중인 상품명으로(여러 협상건 중 '이 건' 식별), 펄스 점·'가격 협상 채널' 문구 제거
- 견적번호(qt_number)를 백엔드 chat init → 프론트로 배선해 헤더 칩으로 노출(좁은 모바일은 숨김)
- 모바일 상품 드로어 상단에 구매사 로고+견적번호(BuyerBrandStrip) — 데스크톱 사이드바 로고의 모바일 대체
2026-07-30 08:31:16 +09:00
minaChoi 9dca78dc72 [feat] negosium: 협상완료 부가정보 수취·표시·잠금 + VAT 표기 통일
- 완료 요약 카드(투찰/협상 결과)에 부가정보·의견을 항상 구조로 표시, 미입력 필드는 '-'
- 협상 리스트 부가정보를 완전 읽기전용으로 잠금 — 입력은 완료 챗 마무리에서만
- 어드민 협상상세(현황·챗 탭)에 협력사 의견(custom.opinion) 노출
- 협상 화면 VAT 표기를 회사설정(vat_yn) 기준으로 통일 — hidden이면 라벨 생략
2026-07-30 08:31:16 +09:00
minaChoi 671904c762 Merge commit '30f134836b59843d84b60fa8c0923bd81afefb41' into feature/negodata 2026-07-29 09:57:05 +09:00
minaChoi 6f32b466b9 Merge branch 'design/frontend' into feature/negodata 2026-07-29 09:56:59 +09:00
minaChoi fe9adcaa26 [fix] negosium/front: 포털 모바일 safe-area 여백 정리 — 헤더 노치(safe-t+min-h)·목록 좌우/하단(safe-x/safe-b)·모달 가장자리 여백(p-4), 채팅 스크롤바 트랙 상단 64px 여백 제거 2026-07-29 09:56:11 +09:00
minaChoi f554202c58 [fix] anchoring: 앵커링가 1원 단위 내림 → 10원 단위 반올림 (자동 제안가 정돈, IMK #11 케이스) 2026-07-29 09:51:26 +09:00
minaChoi a56589c6d9 [feat] negosium/협상: 협상 종료폼 통일·의견 수취 — rejectRSP/CM를 단일 RejectForm(사유·희망가·의견)으로 통합해 액션바 렌더, 타결 부가정보에 의견 추가(custom.opinion), 결렬 제출값 파싱해 reject_reason/reject_price 컬럼 저장, 상품상세 필드 라벨 회사설정 연동·협상 단가 VAT별도 표기 2026-07-29 09:51:21 +09:00
minaChoi b33ae05cd6 [feat] negodata: 견적 목표가·앵커 반올림 + 통계 협상카드 효과 — 목표가=매입가×(1−네고율) 자동입력·산정후보를 낙찰기준탭으로 이동·목표가상한 상시표시 제거, 후보가/앵커 생성가 10원 단위 반올림(신규 세션, schedules 앵커와 동일 공식), 산정모달은 구매담당자 제시가 있어도 후보 전부 노출·MD입력가→구매담당자 제시가, 신규상품 등록에 공급사칸 추가, 상품상세/견적생성 라벨 회사설정 연동, 통계 협상카드 효과(유형별 사용빈도+사용직후 평균 제시가 하락)·와일드카드 1%인하 집계, mono 폰트 폴백 2026-07-29 09:51:03 +09:00
minheon 30f134836b [fix/feat] 인터넷 최저가(LPS) — 로딩 무한 버그 수정 · 몰별 최저가 노출 · 탐색/상세 UI 재설계 (#10) 2026-07-28 08:25:14 +00:00
민헌andClaude Opus 5 8fa77af866 [chore] lps: 배포 설정 문서화 + 죽은 env 제거 + 알림 문구 정정
배포서버 쿠팡 크롤 조사(2026-07-28)에서 드러난 '설정한 줄 알았는데 아니었던' 것들 정리.
크롤 동작 자체를 바꾸는 변경은 없다.

- Dockerfile.worker: ENV LPS_CHROME_EXECUTABLE 제거.
  읽는 코드가 없는데 값이 박혀 있어 "컨테이너 Chrome 경로가 설정돼 있다"는 오해를 만들었다.
  경로의 유일한 소스는 [WorkerConfig].chrome_executable 이다(설정 시 --no-sandbox 동반).

- config.local.toml.example: profile_dir 경고 추가.
  컨테이너에서 ".profiles" 로 두면 /app/.profiles(컨테이너 레이어)에 쌓여 재생성마다 쿠키가
  날아가고, compose 가 마운트한 lps-profiles 볼륨은 붙어만 있고 아무 일도 하지 않는다.
  로컬·배포서버 양쪽에서 실측(/profiles 는 7/9·7/16 잔재, /app/.profiles 에 9MB 최신).

- config.prod.toml.example 신규: 배포서버 설정 템플릿.
  로컬과 다른 값만 ★ 표시. 헤더에 로드 경로의 함정을 명시했다 —
  docker-compose.prod.yml 이 이 파일을 config.local.toml 자리에 마운트하므로
  APP_ENV=local 인데도 내용은 prod 설정이다(파일명만 보면 오해한다).

- worker_main.py: budget_leak 알림이 "ip_request_budget 하향 검토"를 단정하던 것을 수정.
  차단이 ip_req#1 에 몰리면 새 IP 첫 요청부터 막히는 것이라 예산과 무관하다.
  bot_detection.ip_request_no 분포를 보고 처방을 고르도록 문구를 바꿨다.

⚠️ Dockerfile.worker 가 바뀌었으므로 배포 시 lps-worker 재빌드 필요.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 16:39:14 +09:00
민헌andClaude Opus 5 89652fac1f [refactor] negodata/front: 인터넷 최저가 상세 시트 재설계 — 실구매가 중심 + 근거 검증
협상 근거로 쓰는 화면이라 "얼마에 살 수 있고, 그게 어디서 나온 값인가"를
한 번에 검증할 수 있게 정보 구조를 다시 짰다.

구조: 결론 → 판단 → 근거
  - 히어로: 합계(상품가+배송비) 32px + 단가 대비 판정을 한 블록에.
    면은 브랜드보다 채도를 낮춘 --accent 표면, 값만 브랜드 컬러(화면에 단 하나).
  - 판매처 비교표: 상품가/배송비/합계를 몰별로. 상품가 최저와 실구매가 최저가
    다를 수 있어 둘 다 표시. 결과 없는 몰도 '미발견' 행으로 남겨 빈손임을 드러낸다.
  - 검색어(찾은 상품명) + 복사 버튼 → 판매처에서 다시 찾아볼 때 붙여넣기용.
  - 가격 추이: 상품가 단일 기준. 합계 기준은 배송비를 아는 회차에만 값이 생겨
    (네이버는 배송비 미제공 — 실측 39/39) 기준을 바꾸면 값의 의미와 표본 수가
    동시에 변한다. 기준선(상품 단가) 추가 — 이 선 위면 사는 게 손해.
  - 수집 이력: 미발견도 노출(전체의 30%가 not_found 인데 그동안 숨겨져 있었다).

데이터 정직성
  - 배송비 미상(전체 69%)을 0원으로 뭉개지 않는다 — 무료배송으로 읽히면 안 된다.
    모르면 히어로 라벨이 '합계' → '상품가'로 바뀌고 그 사실을 문구로 밝힌다.
  - 화면 주인공(합계)과 목표가 산정에 쓰이는 값(상품가)이 다르므로 각주로 명시.
  - 금액 옆 배송 주석은 '+3,500'(연산으로 오해) → '배송비 포함(3,500원)'.

접근성·일관성
  - 대비 전수 계산: --accent 면 위에서 muted-fg(4.16)·amber-700(4.28)이 AA 미달이라
    accent-foreground(9.85)·800 계열(6.0~6.5)로 교체. 히어로는 큰 글씨 기준 통과.
  - rose(파괴적 뉘앙스) 제거 → 브랜드 인디고 한 톤. 장식 아이콘 전부 제거.
  - 타이포 7단계를 상수 T 로 고정(임의 크기 금지).
  - 차트 점 3종 모양을 DOT 상수로 추출해 차트와 범례가 공유 — 범례는 차트 밖이라
    --color-price 가 해석되지 않아 색이 어긋났다. 전역 토큰으로 통일.
  - Y축 눈금 1·2·5×10ⁿ, 기준 변경 시 애니메이션 끔, 커스텀 X축 tick 제거
    (recharts 의 가장자리 앵커 보정을 건너뛰어 점과 라벨이 어긋났다).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 16:06:27 +09:00
민헌andClaude Opus 5 5e24741395 [refactor] negodata/front: 최저가 탐색 모달 B2B 재설계 + 완료 판정 버그 수정
완료 판정 버그(로딩이 안 멈추던 원인 중 하나)
  폴링이 crawl_end_time 을 문자열로 비교했다. 서버는 마이크로초 6자리(.755705Z),
  JS toISOString() 은 밀리초 3자리(.755Z)라 자릿수가 달라 사전순이 시간순과 어긋난다
  ('.' < 'Z'). 게다가 클라이언트 시각을 서버 타임스탬프의 기준점으로 써서
  브라우저 시계가 조금만 앞서도 어떤 결과도 기준을 넘지 못했다.
  → 요청 직전 서버가 준 최신 수집 시각을 상품별 기준선으로 읽고 epoch ms 로 비교.

UI 재설계 (소비자 앱풍 → B2B 실무 툴)
  - 상태 3분리: confirm | searching | done. 검색 중에 완료 결론을 섞지 않는다
  - 표가 주인공: [선택 | 상품 | 기존 최저가 | 네이버 | 쿠팡 | 결과], 컴팩트 행, tabular-nums
  - 결과 열은 상태어(탐색 성공 / 변동 없음 / 탐색 실패 / 탐색 중)
  - 진행 카드: 표시등 + mm:ss 경과 + 진행바 + N/M, 셀 단위 스켈레톤으로 진행 위치 표시
  - radius 8/6/4, shadow 최소화, CTA 우측 정렬(풀와이드 금지), 강조는 indigo-800 한 톤
  - 완료 후 자동으로 닫지 않는다(결과 확인). 선택 해제는 닫을 때로 미룸

선택 재검색
  체크박스로 대상을 고르고, 검색이 끝나면 갱신되지 않은 행만 자동 선택된다
  (이미 갱신된 상품에 크롤 비용을 다시 쓰지 않도록). 재검색은 force=true 로 나가
  네거티브 캐시를 우회한다.

접근성 (스킬 기준 + 대비 실측)
  - 보조 텍스트 muted-foreground 4.88:1, indigo-800 9.93:1 (기존 1.92:1 FAIL 해소)
  - 상태는 색 단독이 아니라 텍스트/굵기/sr-only 병행
  - role=status aria-live, 탈출구 3중(X·ESC·오버레이), 버튼 높이 통일

api/generated 는 orval 재생성분. resTargetBreakdown 변경은 이전 백엔드 수정과의
스펙 동기화(이번 작업과 무관하지만 재생성으로 함께 정리됨).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 11:56:00 +09:00
민헌andClaude Opus 5 0cefe315c4 [feat] negodata/backend: 몰별 최저가(by_mall) 노출 + 강제 재검색(force) 연동
몰별 성공/실패 표시
  lps_db.price_history 에는 몰별 정보가 다 있는데(naver_lowest·coupang_lowest·by_mall),
  동기화가 final_source(이긴 몰) 하나만 남기고 나머지를 버려서 API 로는
  "네이버는 어땠는지"를 알 수 없었다. 실제로 네이버는 빈손이고 쿠팡만 성공하는
  케이스가 기본값처럼 나오는 중이라 화면에 드러낼 필요가 있다.
  → price_history.by_mall(JSONB)을 partner.item_internet_lowest_prices 로 그대로
    미러링한다(열린 스키마 — 오픈마켓 폴백이 늘어도 스키마 변경 불필요).
  - crud: 읽기 계약에 by_mall 추가 + SELECT 포함
  - model: item_internet_lowest_prices.by_mall
  - service: 언팩·저장
  - protocol: LowestPriceEntry.by_mall
  - init.sql: 테이블 정의 + 하단 보정 ALTER(기존 DB 반영용)

강제 재검색
  POST /v1/item/{id}/lowest-price?force=true → LPS 네거티브 캐시 우회.
  사용자가 '다시 검색'을 누른 경우에만 true.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 11:55:38 +09:00
민헌andClaude Opus 5 ba9d34fd31 [fix] lps: 네거티브 캐시 히트 시 이력 누락 수정 + force 재검색 지원
1) 캐시 히트가 price_history 를 남기지 않던 문제
   not_found 는 24시간 네거티브 캐시에 들어가는데, 캐시에 걸린 조기 반환 경로만
   _record_history 를 호출하지 않았다(다른 모든 경로는 호출).
   그 결과 잡은 완료인데 price_history 에 새 행이 없어, 이를 폴링하는 소비자
   (negodata 최저가 모달)가 결과를 영영 못 받고 로딩만 돌았다.
   → 캐시 히트도 '이 잡의 결과'이므로 이력을 남긴다.

2) force 플래그
   negodata 는 이제 수동 트리거 전용인데 is_negative() 가 job_type 을 보지 않아
   사람이 직접 누른 재검색까지 캐시가 가로막았다. 게다가 캐시 키가 product_code 라
   상품명·모델을 고쳐 재시도해도 동일하게 막힌다.
   → SearchItem.force=true 면 NegativeCache.drop() 으로 기록을 지우고 실제 검색.
   기본 요청은 캐시를 그대로 써서 비용 절감 효과는 유지.

실측: 캐시에 막혀 not_found 만 반복하던 상품이 force 재검색에서 2라운드 만에 found(8,500원).
⚠️ protocol.py 변경은 lps-api 와 lps-worker 를 함께 재빌드해야 반영된다
   (API 만 옛 스키마면 pydantic 이 force 를 조용히 버린다 — 실측으로 확인).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 11:55:23 +09:00
minaChoi 6534d53696 [docs] readme: 업데이트 + 플로우차트 추가 2026-07-28 09:32:40 +09:00
민헌andClaude Opus 5 ca1291708f [fix] lps-worker: compose 에 platform=linux/amd64 명시 (arm64 맥에서 이미지 빌드 실패 해소)
google-chrome-stable(Linux)은 amd64 전용이라 워커 이미지는 본질적으로 amd64다.
arm64 맥에서 platform 없이 빌드하면 arm64 로 시도하다 Chrome 의존성
(libasound2·libxfixes3 등)에서 exit 100 으로 실패하고, 그 결과 예전에 빌드된
구 chromium 이미지로 뜨면서 LPS_CHROME_EXECUTABLE(/opt/google/chrome/chrome)
경로가 없어 쿠팡 웜업이 매번 실패했다.

platform 명시 후 Rosetta 에뮬로 실제 Chrome 150 이 뜨고 쿠팡 Akamai 챌린지를
시도 1회에 통과함을 확인. prod(amd64 서버)에서는 no-op.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 09:16:19 +09:00
minaChoi a5fa44ee25 [refactor] negodata/backend: QuotationService 파사드 분할 — services/quotation/(pricing·build·closing·queries·invites), 시그니처·임포트 경로 외 동작 무변경 2026-07-27 16:15:19 +09:00
minaChoi 7b612824be [refactor] negodata: 목표가 산정 정리 — purchase_only 죽은코드 제거(백+프론트)·산정 재료 로더 공용화·자동재생성 잔재 주석 정정 2026-07-27 16:07:21 +09:00
minaChoi bacf6271df [chore] 작업분 일괄: logs.sh 컨테이너 메뉴화 · dbeaver 초기화 SQL · landing 운영 compose · negodata/front eslint 도입 · 업로드 샘플 CSV 2026-07-24 18:45:46 +09:00
minaChoi 9fb4a52c56 [fix] negosium/front: 협상 챗 에러 말풍선 토스트(하단 짤림 수정) + 가격/할인율 입력 자동 포커스 2026-07-24 18:39:49 +09:00
minaChoi f9d37e08f4 [fix] lps: 워커 이미지 chromium→google-chrome-stable 교체 (쿠팡 Akamai 지문 차단 회피) 2026-07-24 17:12:20 +09:00
minaChoi b539e073cb Merge commit 'dc8c288f' — lps-admin 신설·LPS 운영기능(ip_session/alerts/admin API)·최저가 출처링크 반영 2026-07-24 15:30:36 +09:00
HyeongBaeYang 36afcd68a6 Merge branch 'fix/nego-card-scripts-cleanup' — 협상카드 스크립트 개정·미사용 카드 정리(시드+alter) 2026-07-24 15:17:22 +09:00
HyeongBaeYangandClaude Opus 4.8 a55975e62a [fix] negosium 시드: 협상카드 스크립트 개정 + 미사용 카드 정리
출처: '260716_AIO2O 수정 및 요청사항_v2_memo check.xlsx' > '협상카드 수정' 시트(D열).
- 스크립트 개정: NGC-003(장기 관계 강조)·NGC-004(명분 제공)·NGC-007(예산 상한 안내)·NGC-008(시장가 근거 제시)
- 미사용('IMK 거래 특성과 관련성 부족') 카드 삭제: NGC-006(총비용 가치 설명)·NGC-009(조건부 가격 조정)
- init-data.sql(신규/초기화 설치 정본)에서 006·009 INSERT 제거 + 4개 멘트 갱신
- 동일 최종본을 기존 DB 보정용 alter(postgres-init/alters/2026-07-24-nego-card-scripts.sql)로도 제공(멱등)

검증: 시드 nego_cards VALUES 를 temp 테이블에 강제 평가 → 9행·전부 유효 jsonb. seed=alter=로컬 DB 일치.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 15:17:13 +09:00
minaChoi e9be649e1f [chore] logs.sh: 운영 로그 조회 스크립트 2026-07-24 14:58:57 +09:00
minaChoi 624a8846b0 [chore] landing: prod Dockerfile(SSG 빌드→nginx) 추가 2026-07-24 14:52:16 +09:00
minaChoi d580e4d5ea Merge branch 'feature/negodata'
# Conflicts:
#	landing/app/routes/home.tsx
2026-07-24 14:22:31 +09:00
minaChoi 5318ff3263 [chore] landing: 홈 문구 정비 (mobile.mov 제외·ignore) 2026-07-24 14:18:52 +09:00
minaChoi 51d07bb779 [feat] negodata: 재협상 소유권 게이팅·처리담당자·상세 링크·재생성 타이틀·알림 토스트(읽음API)·재협상요청 표기·커스텀필드 select 2026-07-24 14:18:52 +09:00
minaChoi d7c4e86f30 [feat] 공급사 포털: 협상완료 부가정보(select·종료 동의폼)·상태 라벨 통일·예아니오 Enter=예·목록 결과열·재협상 요청/철회 API·테스트 2026-07-24 14:18:52 +09:00
HyeongBaeYang 562dafa5ca Merge branch 'fix/nego-bid-price-card-limit' — 협상 투찰가 표시≠타결가·카드 사용 횟수 미강제 수정 2026-07-24 11:41:43 +09:00
HyeongBaeYangandClaude Opus 4.8 3eec80d989 [fix] agent: 협상 투찰가 표시≠타결가 버그 + 카드 사용 횟수 미강제 수정
1) 표시가≠투찰가 (배포 서버 협상 결과 오류)
- 카운터 제시 중 멘트의 절충/중간 변수(middle_price·target_mid_price)가 vars_for 재계산으로
  compute_counter 의 target 클램프·prev_customer 갱신과 어긋나, 화면엔 1,740,000 인데 실제로는
  1,700,000 으로 타결되던 문제 → vars_for 에서 세 변수(counter/middle/target_mid)를 pending 으로 고정
- WC-03 최후통첩 멘트가 제시 금액을 안 보여줘 수락 시 화면에 없던 target 으로 타결되던 문제 →
  멘트에 {target_price} 명시(seed init-data.sql). 운영 DB 는 별도 UPDATE 필요

2) 카드 사용 횟수 3회 초과
- quotation_settings.card_count(협상카드 사용 횟수 상한, 기본 3)가 어디서도 강제되지 않던 죽은 설정 →
  에이전트가 sessions.qt_setting_id 로 card_count 를 조회해 협상카드 재생 수를 min(선택수, card_count)로 캡
  (session.action_space_size 는 소진 판정 전용 — Q-table 은 카탈로그 전체로 별도 고정)

- 회귀 테스트: 표시가==타결가(test_card_tactics·test_p7_chat), card_count 로드(test_context_loader). 전체 153 pass

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 11:41:33 +09:00
HyeongBaeYang 2541a391b7 Merge branch 'feat/chat-bugfix' — 협상카드 변수 치환 누락 수정 + 상품 업로드 협력사 목록 422 수정 2026-07-24 10:37:30 +09:00
HyeongBaeYangandClaude Opus 4.8 ce551090b3 [fix] agent·negodata: 협상카드 변수 치환 누락 수정 + 상품 업로드 협력사 목록 422 수정
- agent: 인터넷 최저가(items.internet_lowest_price)를 협상 파이프라인에 연결
  (nego_context_crud 조회 → context loader → session.context → chat_engine.vars_for).
  값 있을 때만 {internet_lowest_price}/internet_min_price 치환, 미수집(0)이면 원형 유지(허위 시장가 방지)
- negodata: 카드 에디터 변수 카탈로그에 '인터넷 최저가' 추가
- negodata: 견적 생성 카드 선택 게이팅 — 조건전략 미작성({customer_condition} 잔존)·
  최저가 미수집 상품의 {internet_lowest_price} 인용 카드는 선택 불가(상품 변경 시 자동 해제 포함)
- negodata: 상품 엑셀 업로드의 협력사 목록 size 1000→100
  (PageParams le=100 초과 시 422 → 목록 비어 전 행 '미등록 협력사' 오탐)
- seed: WC-01 의 데이터 소스 없는 {customer_reference} 제거 → 고정 문구로 대체

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 10:36:24 +09:00
minaChoi 4f9789c08a [feat] 공급사 포털·landing: 채팅 남은시간·헤더 정비, 데모 미디어(mp4/gif) 교체
- 공급사 포털: 채팅 말풍선·남은시간 표기·헤더바·채팅 화면 정비
- landing: how-it-works 데모를 GIF 재생으로 되돌리고 히어로·디바이스 목업 조정, negotiation_annotated_3d 미디어 갱신
2026-07-23 15:43:23 +09:00
minaChoi cfee6e89d0 [feat] negodata: 권한 3단계(개발자 신설)·개발자 메뉴 그룹·디자인 시스템 페이지
- UserRole 1=일반 2=최고관리자 3=개발자(내부 운영). 개발자 계정은 회원 목록·총계에서 제외해 고객사에 노출하지 않음
- 계정 생성 시 권한 선택(일반/최고관리자) 추가, 개발자는 앱에서 부여 불가(DB 시드 전용)
- 사이드바 '개발자' 그룹 신설 — 회사 설정·디자인 시스템을 개발자에게만 노출
- /dev/design 디자인 시스템 페이지: 색 토큰·타이포·버튼·배지·입력·반경, 목록 화면 구조, 반응형 기준, URL 상태 규칙, 회사 커스터마이징 훅
- 공급사 재협상 요청(#15) 플로우 문서 — sessions.custom 기반(DDL 0)
2026-07-23 15:41:36 +09:00
minaChoi db07a60cfa [fix] negosium·negodata·landing: 채팅 진입·부가정보 저장 오류 수정, 모바일 여백·스크롤·노치 대응
- 채팅 링크로 바로 진입하면 세션이 협상생성(1)에 머물러 오프닝 메시지가 seed 되지 않던 문제:
  chat init/messages 에서 participate 와 동일하게 협상중(2)으로 전이(마감 견적·마감시간 초과는 제외)
- 부가정보 저장이 1301 로 실패하던 문제: '협상완료' 요약은 chat_end=false 라 세션이 아직 협상중이므로,
  마지막 말풍선이 summaryRSP/CM 이면 협상중 세션도 저장 허용
- 채팅 언마운트 시 messages 캐시도 제거 — staleTime:Infinity 라 빈 목록이 남아 재진입해도 빈 화면이던 문제
- 채팅 스크롤을 컨테이너 기준 scrollTo 로 변경(rAF 후 실행) — 요약·폼이 뒤늦게 레이아웃되면 중간에 멈추던 문제
- 모바일 채팅 상단 여백 제거(pt-[64px] 는 우측 협상절차 카드가 있는 lg 이상만)
- 노치 대응: viewport-fit=cover + safe-t/b/x 유틸 신설, 헤더·하단 액션 덱·드로어·랜딩 헤더에 적용, h-screen→100dvh
2026-07-23 12:50:40 +09:00
minaChoi 0f10b6a70f [feat] negodata·공급사포털: 상품 필드 숨김 설정·용어 카탈로그 확장·로그인 전 브랜딩·모바일 대응
- 회사 설정 hidden_fields 신설: 상품 목록·등록폼·엑셀 양식에서 감추고 목표가 후보에서도 제외
- 용어 카탈로그 9→37개(상품·협력사·견적 그룹), 목록·폼·엑셀 헤더 배선
- 엑셀 '최저한도' → '인터넷 최저가' 표기 정정(구양식 헤더는 alias 유지), 공급사 컬럼 검증 유지
- 목표가 산정내역에 적용 모드·숨김 필드 반영, 목표가 상한 라벨에 산식(상품단가×2) 표기
- 공급사 포털: 초청 링크 session_id 로 로그인 전 회사 브랜딩 조회(무인증 엔드포인트), 기본 브랜드 negotium 워드마크, negotium·AI O2O 크레딧 표기
- 목록 테이블 뷰포트 기준 전환·툴바 줄바꿈·협상현황 카드뷰로 모바일/태블릿 대응
- 이용안내 FAQ 탭 추가, 이용안내·회사설정 탭 URL 쿼리 동기화 및 빠른이동 등록
2026-07-23 11:29:35 +09:00
minaChoi 4927c9184e Merge branch 'feature/negodata' of https://gitea.o2o.kr/Negosium/o2o-negosium into feature/negodata 2026-07-22 17:28:10 +09:00
minaChoi 03322d6ca3 [feat] negodata: 카드 성공률 순위·상품 엑셀 TO-BE 싱크·회사설정 JSON 입출력·목록 포털형 UI
- 협상카드 성공률(사용 세션 대비 타결) 집계 추가, 견적 생성 카드선택 순위 정렬·통계 TOP5
- 상품 엑셀: 품목코드·모델명 라벨화, 리드타임 suffix 제거, 공급사 컬럼 신설(등록 후 supplier_items 매핑)
- 설정 화면 JSON 불러오기/내보내기(빈 값은 미갱신), IMK 설정 JSON 보관
- 설정·회원 페이지 새로고침 forbidden 수정(자식 loader 가 initAuth 대기)
- 협력사·견적 목록도 포털형 카드(툴바+테이블 결합)로 통일
2026-07-22 17:27:23 +09:00
minaChoi fa9113da55 Merge commit 'f8f8f70f54980eb5d1b60a4ff4aaa67215bd1497' 2026-07-22 17:26:52 +09:00
minaChoi 7c4b66aba5 [feat] negodata: 카드 성공률 순위·상품 엑셀 TO-BE 싱크·회사설정 JSON 입출력·목록 포털형 UI
- 협상카드 성공률(사용 세션 대비 타결) 집계 추가, 견적 생성 카드선택 순위 정렬·통계 TOP5
- 상품 엑셀: 품목코드·모델명 라벨화, 리드타임 suffix 제거, 공급사 컬럼 신설(등록 후 supplier_items 매핑)
- 설정 화면 JSON 불러오기/내보내기(빈 값은 미갱신), IMK 설정 JSON 보관
- 설정·회원 페이지 새로고침 forbidden 수정(자식 loader 가 initAuth 대기)
- 협력사·견적 목록도 포털형 카드(툴바+테이블 결합)로 통일
2026-07-22 17:24:58 +09:00
minaChoi f8f8f70f54 [style] negodata/front: 상품·카드 목록 포털형 카드(툴바+테이블 한 카드로 결합) 2026-07-22 17:23:48 +09:00
minaChoi bcb87de35e [feat] backend: 선택 와일드카드 card_id 저장 — wild 스텝이면 wild_cards 조회·card_type=2(nego는 card_type=1, step 으로 구분) 2026-07-22 16:10:22 +09:00
minaChoi 0242ecff09 [feat] negodata: 초청 메일 헤더에 회사 브랜딩(settings.branding.email_header) 배선 2026-07-22 15:54:05 +09:00
minaChoi bb576af346 [feat] negodata/front: 협상완료 부가정보 협상현황 모달·아이콘 툴팁(base-ui)·헤더 회사명 모바일 전용 2026-07-22 15:54:05 +09:00
minaChoi e67e713270 Merge branch 'feature/negodata' into feature/landing 2026-07-22 15:24:56 +09:00
minaChoi 08c1e66582 [feat] landing: negotiation 데모에 mp4/poster 추가(gif→비디오 재생) 2026-07-22 15:24:08 +09:00
minaChoi 5d0fbbcf6a [feat] 공급사 포털·backend: 협상완료 부가정보 입력(#5)·포털 브랜딩/로고·구분삭제(#19)·카드메타 nego 저장 2026-07-22 15:20:24 +09:00
minaChoi 88edcfed63 [feat] negodata: 회사 커스터마이징(설정·라벨·커스텀필드·엑셀·상품공급사#20·분류카테고리#17)·일괄삭제·로그export·구분·카드 전체선택·부가정보 표시 2026-07-22 15:20:24 +09:00
minaChoi 1e4726f4cc [feat] 스키마: company.settings·items/suppliers/sessions.custom·nego_cards 컬럼 추가(모델·init.sql) 2026-07-22 15:19:41 +09:00
minaChoi e8d2acaade [feat] negodata: 통계 인상억제율(재협상)·월별 차트 — 직전 라운드 투찰가 대비 인하율 파생 집계 2026-07-22 15:19:14 +09:00
minaChoi a9db0f7a1b Merge branch 'design/frontend' into feature/landing 2026-07-22 08:57:08 +09:00
minaChoi 3e5f8c6cd4 [feat] landing: 콘솔형 히어로·price-sparkline·데모 미디어(mp4/jpg) 세트 추가, phone 데모(how-it-works) 수정 2026-07-22 08:52:40 +09:00
minaChoi e7a51b1b75 [feat] negosium/front: 협상방 마감 정비 — 우측 패널 납작 섹션·모바일 협상절차 스텝바·이용가이드 모달 토스화·중복 이용가이드 제거·폰트 정리·마감시간 tabular-nums 2026-07-22 08:29:58 +09:00
minaChoi e9427543c8 [feat] landing: 히어로/데모 리뉴얼 — 콘솔형 히어로·price-sparkline 추가, 데모 미디어(mp4/jpg) 세트 추가, ROI 시뮬레이터·negotiation-console·버튼·홈 라우트 수정 2026-07-22 08:29:54 +09:00
minaChoi 6ffdb9a389 [feat] landing: 비교 토글 자동재개·헤더 nav 4개 정리·모바일 가운데 정렬·Phone Demo 히어로 디폴트, FAQ 연동답변·중개대행·역경매·와일드카드 등 논란 문구 정리 2026-07-21 13:49:27 +09:00
minaChoi 9ccf42cf6b [feat] landing: 카피 정직화(가이드 3탭·강화학습·이점)·실단가 반영, 비교 토글·FAQ 섹션 신설, 협상 콘솔 목표가 스파크라인·절감 델타 추가, 헤더 플리커·히어로 줄바꿈 수정 2026-07-21 10:47:45 +09:00
minaChoi e93820a51b Merge branch 'design/frontend' into feature/landing 2026-07-21 08:48:07 +09:00
minaChoi dd3609173e [feat] landing: 협상 데모 GIF 모바일 UI로 교체 (채팅 밀당→타결, 상단40/하단28 세이프에어리어, 9:18) 2026-07-21 08:45:29 +09:00
minaChoi 2386cb8867 [feat] negosium/front: 아이마켓 보고서 기준 토스풍 UI 리뉴얼 — 로그인·포털 목록(KPI·모바일 카드)·협상방 3단(말풍선·타임라인·결과/성공률 카드)·모바일 드로어, 목록 서버 페이징 유지·검색 비움 2026-07-20 17:27:11 +09:00
minaChoi b6852ec6aa [feat] landing: 협상 데모 GIF 모바일 UI로 교체 (채팅 밀당→타결, 상단40/하단28 세이프에어리어, 9:18) 2026-07-20 17:26:50 +09:00
minaChoi 03c22f9474 [feat] landing: 솔루션 랜딩페이지 신규 — 히어로·데모·ROI 시뮬레이터 섹션, docker 서비스(:3100) 추가 2026-07-20 09:09:09 +09:00
minaChoi 25e13d7b01 [feat] negodata/front: 디자인 리뉴얼 1차 — 인디고 콘솔 토큰·⌘K 크롬·대시보드/로그인/알림함 개편, 툴바 통일, 시트 스크롤 수정 2026-07-16 16:24:40 +09:00
민헌andClaude Opus 4.8 dc8c288f68 feat(lps): docker-compose 에 lps-admin 추가 + 환경설정 config.local.toml 단일화
- lps-admin 컨테이너화: Vite 정적 빌드 → nginx, /v1·/healthz·/readyz 를
  lps-api:9600 으로 동일출처 프록시(빌드 타임 API URL 주입 불필요)
- lps-api/worker: APP_ENV=local 고정 + DB_HOST override(도메인 backend·negodata·agent
  와 동일 패턴), config.<env>.toml 마운트 방식 폐기
- server_configs 에 DB 접속 env override(_apply_db_env_override) 복원
- config.dev/prod.toml.example 제거 — 환경 구분 없이 config.local.toml 하나
  (prod 서버도 그 서버의 config.local.toml + docker compose up -d)
- run_docker.sh 환경 선택 제거·lps-admin 포함, README·operations 문서 갱신

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 11:54:32 +09:00
민헌andClaude Opus 4.8 d111610555 feat(lps-admin): 관리자 페이지 디자인 개선 및 컴포넌트 통일
- 공용 프리미티브(ui.tsx): PageHeader·Segmented·Button·SearchForm·Legend·
  ScrollBox·ScrollTable·Modal + Card(fill/compact) 옵션
- 차트 공용 설정(lib/chart.ts): 축·그리드·툴팁 스타일 단일화
- 뷰포트 채우기 레이아웃 + content 영역 스크롤(Layout), 버튼 커서 복구
- 표: 헤더 밴드·행 좌우 패딩·고정/채움/auto 높이·sticky 헤더, 배지 줄바꿈 방지
- 작업 큐: 풀폭 표 + 행별 상세/JSON 모달(복사)
- 상품·가격: 가로 배치, Y축 0 기준, 시점 클릭→몰별 비교, 커스텀 툴팁·
  그라데이션 area, 몰별 컴팩트 표(소스 뱃지)
- 크롤 상태: 도넛 중앙 총계·라운드 세그먼트, 막대 그라데이션, 툴팁 통일
- 테스트 검색: 결과 통일(모달·표·소스 뱃지), 진행상태 좌측 이동, 초기화 전
  재검색 차단, 퍼널 가독성(감소량), 배송(로켓배송) 표기, 한 화면 컴팩트
- 사이드바: API 상태 상단 뱃지, 테스트 메뉴 배경색으로 구분

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 08:48:43 +09:00
minaChoi 3d515055fb [feat] negodata/front: 온보딩 이모지→아이콘 교체, step0 레이아웃·애니메이션 등 개편 2026-07-15 16:39:58 +09:00
민헌andClaude Fable 5 e6005b4f94 feat(lps-admin): 테스트 검색을 앰버로 구분 — '실제 비용 드는 액션' 신호
테스트 검색은 다른 페이지(읽기전용 모니터링)와 달리 실제 크롤·프록시
비용이 발생하는 실행 액션이라 시각적으로 구분(협의).

- 네비 '테스트 검색': 앰버 점 마커 + 앰버 텍스트/활성색, 위에 구분선으로
  모니터링 페이지들과 분리(설정과 함께 실행/유틸 그룹).
- 테스트 페이지 '검색 실행' 버튼: primary(indigo) → warn-700(#a36a00).
  흰 텍스트 대비 4.55:1 로 AA 통과(실측). 상태색은 장식이 아니라
  '비용 주의' 의미로만 사용(디자인 규칙 준수).
- whitespace-nowrap 로 라벨 줄바꿈 방지. 모바일 hscroll 0 유지.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 11:44:59 +09:00
민헌andClaude Fable 5 479cb862b1 feat(lps-admin): 상품·가격 — '몰별 최저가'+'검증 링크' 를 몰별 가격 비교로 통합
두 카드가 사실 같은 데이터(by_mall)를 다르게 그린 것이라 하나로 합침.
상위 N개(3/5/10/전체 선택)를 순위·쇼핑몰·상품명·가격·최저가 대비 델타·
링크 한 줄로 보여주고 가격 비교 막대를 얹어 한눈에 비교 가능.

- MallEntry 타입 필드명 버그 수정(mall/url → mall_name/detail_url/name)
  — 기존 몰별 최저가 차트에 몰 이름이 안 보이던 원인. 이제 표시됨.
- 상위 N 은 프리셋 칩(by_mall 이 몰별 dedup 소집합이라 자유입력보다 적합).
- '검색어'는 항목별로 없어 각 몰의 상품명(title)으로 대체 — 같은 상품
  검증 역할.
- 모바일 가로 스크롤 해소: 상단 네비 overflow-x-auto 가 페이지를 늘리던
  것(루트 w-full 누락)과 master-detail 그리드 자식 min-w-0 누락 동반 수정.
- 실기동 검증: G마켓 56,880/플랜88 59,900 렌더·칩 토글·데스크톱/모바일
  hscroll 0·콘솔 에러 0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 10:57:07 +09:00
민헌andClaude Fable 5 a306ad4cf3 docs(lps-admin): README 에 테스트 검색 페이지 추가
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 09:14:14 +09:00
민헌andClaude Fable 5 c126d56631 feat(lps-admin): 테스트 검색 페이지 — 임의 상품을 실제 파이프라인에 흘려 점검
셀렉터·프록시·AI 매칭 회귀를 UI 에서 즉석 점검. API 는 lean(브라우저
없음)이라 크롤은 워커에만 있으므로, 기존 POST /v1/lps/search 로 잡을
넣고 GET /jobs/{id} 를 2초 폴링해 결과를 시각화(신규 백엔드 0).

- 폼(상품명 필수+모델/규격/제조사/현재가) → 제출 → 진행 스텝퍼
  (대기→크롤·판정중→완료, 1초 티커 경과시간) → 결과.
- 결과: 판정(최저가·소스), 파이프라인 퍼널(수집→필터→이상치→AI→top-N
  단계별 잔존 수), 소스별 수집(+실패 시 error 표시), 검색 원가
  (AI/프록시 분해·전송량), 매칭 상품 표, 원본 JSON.
- product_code=TEST-<시각> 자동 — 프로덕션과 필터 구분(negodata 는
  UUID 만 매핑, 연동 무영향). 자격증명은 서버에만, 결과엔 집계 사용량만.
- 워커 미실행 시 8초 후 '워커 확인' 힌트, DEAD 시 오류 표시.
- 작업 큐에 '테스트만'(TEST- 접두) 필터 칩 추가.
- 실기동 검증: 맥심 커피 검색 → 퍼널 80→2·쿠팡 9.5s·원가 /bin/zsh.002 렌더,
  콘솔 에러 0, 모바일 hscroll 0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 09:13:54 +09:00
민헌andClaude Fable 5 3c8d0af2e4 chore: .gitignore 에 .gstack/ 추가 (gstack 로컬 상태 디렉터리)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 22:59:14 +09:00
민헌andClaude Fable 5 74fce19be9 style(design): FINDING-009 — 비용 빈 상태에 다음 행동 안내 추가
'없습니다'로 끝나던 빈 상태에 '워커를 켜고 검색을 돌리면 채워집니다'
안내를 붙여 사용자가 다음 행동을 알 수 있게.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 22:58:51 +09:00
민헌andClaude Fable 5 1006ad11ea style(design): FINDING-012 — 접근성 통일: 검색 라벨·행 키보드 선택·이모지 숨김 [subagent]
Settings 는 label 연결이 모범인데 Jobs/Products 검색 인풋만 접근
가능한 이름이 없었고, Products 목록(button)과 달리 Jobs 행(tr onClick)
은 키보드로 선택 불가였다. aria-label 2곳, tr tabIndex+Enter/Space
핸들러+focus-visible, 장식 이모지(⚠✓🎉) aria-hidden 처리.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 22:58:51 +09:00
민헌andClaude Fable 5 645a0362b0 style(design): FINDING-011 — 타이포 스케일 정수 6단으로 통일 (본문 14px) [subagent]
작은 앱에 0.5px 간격 10종(10.5~22)이 혼재 — 12 vs 12.5 는 위계를
만들지 못하고 half-pixel 은 zoom/서브픽셀에서 반올림이 갈린다.
{11,12,13,14,17,22} 정수 6단으로 정규화(순서 보존 매핑), 본문
13.5→14px(FINDING-004). 빌드·렌더 검증.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 22:58:14 +09:00
민헌andClaude Fable 5 29e54ad838 style(design): FINDING-007 — 고정 150px 파이의 ResponsiveContainer 제거
recharts 가 '고정 폭·높이엔 ResponsiveContainer 불필요' 경고를 콘솔에
반복 출력(페이지당 4회). PieChart 직접 렌더로 전환.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 22:54:46 +09:00
민헌andClaude Fable 5 10ea8ddd45 style(design): FINDING-010 — Crawl.tsx 하드코딩 hex 를 @theme 토큰으로 단일화 [subagent]
Crawl 이 dead-600/ink-400/cost-ai 와 동일한 값을 raw hex 로 재복제해
토큰 변경 시 어긋나는 이중 정의 상태였다. 종료사유 팔레트를 상태
토큰(ok/run/warn/dead)+신규 neutral-300/400 으로 치환, ReferenceLine·
막대·폴백 hex 전부 var() 참조로. src 내 raw hex 0 확인.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 22:53:58 +09:00
민헌andClaude Fable 5 433b973505 style(design): FINDING-003 — ink-400/500 캡션 대비 WCAG AA 통과로 다크닝
ink-400(#9aa1ac)이 11~13px 소형 텍스트(타일 부제·테이블 헤더·각주)에
쓰이는데 대비 2.54:1 로 AA(4.5:1) 미달. ink-400→#6d7480(4.59:1),
ink-500→#5d6470(5.81:1)으로 2단 위계 유지한 채 통과. 실측 재검증.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 22:52:37 +09:00
민헌andClaude Fable 5 a750c1098a style(design): FINDING-001 — 모바일(<md) 사이드바를 상단 네비로 전환
375px에서 사이드바가 196px을 고정 점유해 콘텐츠가 낱글자로 세로
분해되고 /jobs 에 가로 스크롤(484px)이 생겼다. <md 에서 상단 바
+가로 스크롤 네비(터치 44px, FINDING-006)로 전환, 로고 그라디언트
hex 를 primary-400 토큰으로 승격. 검증: dashboard/jobs 375px
hscroll=false, 스크린샷 확인.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 22:51:53 +09:00
민헌andClaude Fable 5 5e286d7949 chore(lps-admin): package-lock name 동기화 — 폴더명 변경 후속
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 22:39:49 +09:00
민헌andClaude Fable 5 992a3246a8 chore(lps-admin): 폴더명 lps-temp-fe → lps-admin
임시 FE 가 정식 관리자 콘솔이 되어 이름을 용도에 맞게 변경.
루트 병렬 유지(lps/ 는 파이썬 백엔드 루트라 중첩 시 비대칭 +
Docker 빌드 컨텍스트 오염). package.json name 동기화.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 22:07:30 +09:00
민헌andClaude Fable 5 6eb71eb035 feat(lps-temp-fe): React 관리자 페이지 — 대시보드·작업큐·상품가격·크롤·비용
임시 단일 HTML 콘솔을 걷어내고 5페이지 관리자 앱으로 교체(협의:
모니터링+필수 액션, negodata 계열 경량 스택 — Vite+React+TS+Tailwind
+recharts+react-query+react-router).

- 대시보드: /ops 5초 폴링 스탯 타일 8종 + 임계 배너(서버 AlertConfig
  기본값 미러) + 세션 내 누적 큐 추이.
- 작업 큐: 상태 탭·상품 검색·페이지네이션·상세 패널(결과/원가/오류),
  DEAD 재큐 버튼.
- 상품·가격: 가격 추이 3선 + 몰별 최저가 바 + 검증 링크 + 수동 재검색.
  시리즈 색 엔터티 고정 — 네이버 #008a43 은 쿠팡 적색과의 적록색약
  분리(ΔE 14.5)·3:1 대비를 검증해 톤다운한 값.
- 크롤 상태: 종료사유 도넛(의미 기반 상태색)·세션당 요청 수 분포
  +차단 시작 기준선(예산 튜닝 뷰)·차단 추이/이력·세션 테이블.
- 비용: 시간별 원가 스택(AI vs 프록시)·건당 평균·평균 소요(축이 달라
  별도 차트 — 이중축 금지).
- 설정: API 주소·guard 키(localStorage → X-API-Key 자동 첨부).
  서버 설정 변경 UI 없음(toml 단일 소스 원칙).
- dev 는 vite 프록시(:9600)로 CORS 불필요. 5페이지 실렌더 스크린샷 검증.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 21:59:15 +09:00
민헌andClaude Fable 5 61b438d8d0 feat(lps): 관리자 FE 용 API 6종 — 잡 목록/재큐·상품 목록·IP세션/차단/비용 통계
React 관리자 페이지(협의: 모니터링+필수 액션)의 데이터 소스.

- GET /v1/lps/jobs: 최신순 목록+총건수, status/q(상품코드·명) 필터.
  결과에 outcome·최저가·검색원가·오류를 평탄화해 목록에서 바로 보이게.
- POST /v1/lps/jobs/{id}/requeue: DEAD 재큐(attempts 리셋+pg_notify 워커
  깨움). 활성 중복(dedupe)이면 DB_ALREADY_SAME_KEY 로 거절.
- GET /v1/lps/products: 상품별 최신 스냅샷+누적 검색 수(최근 검색순).
- GET /v1/lps/stats/ip-sessions: 종료사유 분포·요청수 히스토그램·차단
  세션 최소 요청수(예산 튜닝 기준선)·최근 세션 50.
- GET /v1/lps/stats/bot: 시간대별 차단 + 최근 감지 목록.
- GET /v1/lps/stats/cost: 시간별 원가(AI/프록시 분해)+평균 소요.
- AdminService/admin_protocol/admin 라우터 신설, guard 일괄 적용.
  설정 변경 UI 는 두지 않음 — toml 단일 소스 원칙.
- 테스트 9건 추가, 전체 154 passed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 21:42:38 +09:00
민헌andClaude Fable 5 8fb54be830 feat(lps): local/dev/prod 환경별 실행 체계 — 환경 toml 2종 + 대화형 run_docker.sh
다른 개발자가 어느 환경이든 같은 방식으로 띄울 수 있게 한다.
환경 = APP_ENV 가 고르는 config.<env>.toml 하나(구조 동일, 값만 다름).

- config.docker.toml → config.dev.toml 개명, config.prod.toml.example 신설
  (prod 성격 반영: api_keys 필수 표기·debug 로그 금지·웹훅 권장).
- compose 의 lps 서비스 APP_ENV/마운트를 ${APP_ENV:-dev} 로 파라미터화,
  API 포트를 ${LPS_API_BIND:-0.0.0.0} 바인드로 노출 제어.
- run_docker.sh(대화형) 신설: 환경 선택 → 설정 파일 검증(없으면 example
  복사 제안) → 기동/재시작/중지/로그. prod 는 guard 키 비면 경고 후
  확인받고, LPS_API_BIND=127.0.0.1 자동 설정(외부는 리버스프록시 경유).
- 운영 가이드에 환경 개요 표, README 빠른 시작에 Docker 실행 추가.
- 검증: 스크립트 문법·compose(dev/prod) 파싱·APP_ENV=dev 로딩·145 passed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 21:22:53 +09:00
민헌andClaude Fable 5 c81df5bd88 refactor(lps): 설정을 TOML 단일 소스로 통합 — env/.env 이중 관리 제거
설정이 .env(compose 주입)·config.toml·코드 곳곳의 os.environ 직독 3계층에
흩어져 관리가 어려웠다. TOML 하나로 통합한다(협의 결정).

- 신설 [WorkerConfig](동시성·폴백·프로필·데드라인·유예·Chrome·하트비트),
  [AlertConfig](웹훅·쿨다운·임계 10종). [WebServerConfig].api_keys(guard),
  [DecodoConfig].ip_request_budget/port_cooldown_sec 추가 — 흩어져 있던
  LPS_* env 20여 개를 섹션으로 흡수.
- server_configs 의 env override 계층(DB_*·시크릿·NAVER_KEYS 등) 삭제.
  남는 env 는 APP_ENV(부트스트랩)·PROCESS_COUNT/WORKER_CONCURRENCY(실행
  스크립트 대화형 입력 전용)·LPS_LIVE(테스트 옵트인)뿐.
- Docker: env 주입 → config.docker.toml 마운트 + APP_ENV=docker.
  이미지 무시크릿 유지, 마운트 누락 시 FileNotFoundError 즉시 실패.
  .env.example 삭제, config.docker.toml.example 신설.
- negodata 호출부: guard 키를 env 직독에서 [WebServerConfig].lps_api_key
  (+기존 관례대로 env override)로 이동.
- 실행 스크립트: 프로필·폴백·예산 프롬프트 제거(toml 소스 안내),
  동시성/프로세스 수만 임시 override 로 유지.
- docs 7종·example toml 의 env 표기를 toml 키로 일괄 갱신.
- 전체 145 passed + APP_ENV=docker 로딩·API 기동 스모크 확인.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 21:11:31 +09:00
민헌andClaude Fable 5 993301be8b docs(lps): README·docs 최신화 — IP 선제 회전·알림 10룰·guard·ip_session 반영
이번 기능 3종+알림 확장 이후 문서와 코드의 어긋남을 정리한다.

- README: 주요 기능 표에 선제 회전(예산 3회)·임계 알림·API guard 추가,
  차단 대응 설명을 '막히기 전 교체' 순서로 재서술, 폴더 구조에
  alerts/ip_session 반영, 데이터베이스 문서 링크를 5종으로 수정.
- api.md: /v1/lps/ops 운영 스냅샷 섹션 신설(필드 주석 포함),
  /readyz 문서화, HTTP 401(guard) 상태 코드 추가.
- architecture.md: 구성요소 표에 관측·알림/API guard 행 추가.
- database.md: 제목 '테이블 5종'으로 수정.
- operations.md: 테스트 수 96→145, 로그 읽는 법에 예산 선제 회전·
  포트 쿨다운 로그 2행 추가.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 20:46:59 +09:00
민헌andClaude Fable 5 ca7f057e41 feat(lps): 알림 룰 4종 추가 — 데드라인·검색원가·포트 고갈·예산 누수
협의로 선정한 조기 신호 4종을 AlertManager 에 추가한다.

- deadline: 최근 1h JobDeadlineExceeded 수 ≥ LPS_ALERT_DEADLINE_1H(5).
  재시도로 살아나면 dead 룰엔 안 잡히는 크롤 행 반복 신호를 별도 집계.
- cost: 최근 1h 완료 잡 검색원가 합 ≥ LPS_ALERT_COST_1H_USD(1.0).
  비용의 87%가 프록시 대역폭 — 리소스차단 풀림·재시도 루프의 조용한
  비용 폭주를 감시. job.result 의 metrics.cost.total_usd JSONB 합산.
- proxy_ports_low: 가용 포트 비율 ≤ LPS_ALERT_PORTS_LOW_PCT(30%).
  쿨다운 격리 누적 — blocks_1h(80건)보다 먼저 우는 대규모 차단 조기
  신호. 워커별 프록시 중 가장 소진된 것 기준(min).
- budget_leak: 최근 6h end_reason=block 세션 ≥ LPS_ALERT_BLOCK_SESSIONS_6H(1).
  요청 예산(3회)을 지켰는데도 차단됨 = 예산 하향 검토 신호.
- deadline_1h·cost_1h_usd 는 queue.ops() 에 편입 → /v1/lps/ops 로도 노출.
  포트·세션 지표는 워커 웹훅 스냅샷에 포함(프록시 상태는 워커에만 있음).
- 테스트 4건 추가(ops 집계 2·포트 스냅샷 2), 전체 145 passed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 17:29:08 +09:00
민헌andClaude Fable 5 e7d2c87fbe feat(lps): API guard — LPS_API_KEY 설정 시에만 /v1 에 X-API-Key 검증
외부에서 API 를 함부로 호출(비용 발생 enqueue 등)하지 못하도록 정적 키
guard 를 추가한다. '키의 존재'가 토글 — 개발(local/dev)은 env 를 비워
개방 모드(기동 시 WARN), prod 만 키를 주입한다(협의 결정).

- router/v1/validator/auth.py: X-API-Key 의존성 — secrets.compare_digest
  상수시간 비교, 콤마 구분 복수 키(무중단 키 교체), 매 요청 env 조회
  (재기동 없이 테스트 가능). /v1 라우터 전체에 적용.
- /healthz·/readyz 는 라우터 밖이라 항상 개방(LB 프로브).
- negodata lps_sync_service: LPS_API_KEY env 있으면 헤더 자동 첨부(한 곳).
- compose(lps-api·negodata-backend) LPS_API_KEY 패스스루 + .env.example.
- prod 체크리스트(operations.md): 키 주입 + lps-api 포트 비공개 + 기동
  로그 'API guard ON' 확인. api.md 인증 섹션 추가.
- 라이브 스모크: 무헤더/오키 401 · 정키 2종 200 · healthz 200 확인.
- 테스트 6건 추가, 전체 141 passed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 16:45:31 +09:00
민헌andClaude Fable 5 8b9e81777c feat(lps): 알림 확장 — AlertManager 쿨다운·회복, DB풀 포화·소스별 장기실패 룰
기존 ops-monitor 는 임계 초과가 지속되면 30초마다 같은 웹훅을 반복 발송했고
(쿨다운 없음), 해소 여부도 알 수 없었다. 감시 항목도 큐 지표 4종뿐이었다.

- common/alerts.py AlertManager 신설: 룰 키별 상태 관리 — 발화 1회 +
  쿨다운(LPS_ALERT_COOLDOWN_MIN, 기본 30분)마다 리마인드, 해소 시 회복
  알림 1회. sender/clock 주입으로 네트워크·대기 없이 단위 테스트.
- 워커 ops-monitor 를 AlertManager 로 이관(기존 4룰 유지) + 신규 2룰:
  db_pool(풀 포화율 ≥ LPS_ALERT_POOL_PCT 90%) ·
  source_fail:<src>(최근 30분 시도 ≥ LPS_ALERT_SOURCE_FAIL_30M(5) & 성공 0
  — 쿼터 소진·셀렉터 드리프트·전면 차단 신호).
- DBSessionManager.pool_status(): 전 엔진 합산 checked_out/capacity/pct.
- SearchAdapter 에 시간 윈도우 성공/실패 카운터(recent_stats) — 누적
  카운터로는 '최근 30분 성공 0건'을 볼 수 없어 추가. 쿠팡(브라우저)·
  네이버(API) 성공/실패 지점에 배선.
- API 자체 풀 모니터: lifespan 백그라운드 태스크(run_pool_monitor) —
  대량 폴링으로 풀을 고갈시키는 주범이 API 자신일 수 있다.
  /v1/lps/ops 에 pool_checked_out/pool_capacity/pool_pct 노출(스모크 확인).
- 테스트 9건 추가(발화·쿨다운·회복·룰 독립·윈도우 카운터·풀 현황), 전체 135 passed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 16:42:12 +09:00
민헌andClaude Fable 5 3c5286aeec feat(lps): IP 선제 로테이션 — 요청 예산·포트 쿨다운·ip_session 관측
쿠팡 크롤 IP 를 '막힐 때까지' 쓰던 방식을 '막히기 전에 교체'로 전환한다.

- 요청 예산(LPS_IP_REQUEST_BUDGET, 기본 3): IP당 요청 수가 예산에 닿으면
  차단 전에 선제 회전. 실측상 5회 부근 차단 이력이 있어 보수적으로 3회.
  선제 교체된 포트는 평판이 깨끗해 로테이션 복귀 시 재사용된다.
- 포트 쿨다운(LPS_PORT_COOLDOWN_SEC, 기본 max(sticky,30분)): 차단 감지·
  전송오류 포트는 격리하고 _port() 가 건너뛴다. 전 포트 쿨다운이면 만료
  임박 포트 사용(가용성 우선). 포트 수는 config 범위에서 동적 산출.
- 차단 재시도 소진 시에도 회전 예약 — 불탄 포트로 다음 검색을 하지 않음.
- ip_session 테이블 신설: 세션마다 요청 수·성공/차단·종료 사유(budget/
  block/proxy_error/window/idle/shutdown)를 기록. bot_detection 과 달리
  무사 종료도 남아 예산 상한 튜닝의 원천 데이터가 된다(쿼리 database.md).
  models.py·migrations·init.sql(lps_db 섹션) 동행 갱신, dev DB 적용 완료.
- 테스트 17건 추가(쿨다운·예산 판정·세션 기록·CRUD), 전체 126 passed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 16:35:44 +09:00
민헌 f97e407f7c Merge branch 'main' into feature/negodata-lps 2026-07-13 13:55:36 +09:00
minaChoi 21f90ed84a [fix] negodata/front: 윈도우 브라우저 폰트 미적용 수정 — format woff2-variations 를 표준 woff2 로 교체 2026-07-13 08:47:09 +09:00
HyeongBaeYang ac487268d8 postgres-init lps db 추가. 2026-07-10 17:19:24 +09:00
민헌andClaude Fable 5 9ef9bfbca3 feat(negodata/front): 최저가 상세보기 버튼 노출 + 상세 시트 가독성 정리
- 상품 테이블 인터넷 최저가 셀: 값 옆에 차트 아이콘 버튼 상시 노출
  (기존 hover 밑줄만으론 클릭 가능성이 안 보임) — 값 없는 상품도
  버튼으로 진입해 빈 상태 안내를 받는다
- 상세 시트 재구성: 견적 상세 드로어와 같은 SectionCard 문법으로 통일
  · 헤드라인 카드: 상품명 → 대표가(26px rose) + 단가 대비 칩
    (절감=emerald·역전=amber, Trending 아이콘) + 단가·마지막 수집 캡션
  · 최저가 출처: 섹션 타이틀 우측 사이트 배지, 링크는 outline 버튼화
  · 가격 추이: 수집 횟수 캡션, 2회 미만이면 안내 문구(빈 영역 방지)
  · 수집 이력: 배지 폭 고정(w-14)으로 컬럼 정렬, 링크 없는 행 자리 유지

검증: 헤드리스 렌더 확인(테이블 셀·시트 v2 스크린샷), tsc 통과

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 17:18:09 +09:00
민헌andClaude Fable 5 4a20194dc8 feat(negodata): 인터넷 최저가 출처·링크·가격 추이 UI — 검증 가능한 협상 근거
인터넷 최저가는 견적 목표가·협상 카드(NGC-008 시장가 근거)의 근거값
— "어디서 찾았는지"를 클릭 한 번으로 검증할 수 있어야 한다.

- 스키마: iilp 에 lp_name(찾은 상품명)·lp_url(판매 페이지 링크) 추가
  (alters/2026-07-10-iilp-source-link.sql, init.sql 멱등 반영·dev 적용)
- 동기화: price_history 의 final_source 에 맞는 naver/coupang name·url
  을 함께 반영(기존 행은 NULL 공존)
- API: LowestPriceEntry 에 lp_name/lp_url + orval 재생성
- UI: 상품 테이블 인터넷 최저가 셀 클릭 → 상세 시트
  · 대표가(rose) + 상품 단가 대비 차액(절감=emerald/역전=amber)
  · 출처 카드: 사이트 배지·찾은 상품명·판매 페이지 새탭 링크
  · 가격 추이 라인 그래프(성공 수집 2건부터, recharts+ChartContainer
    라이트/다크 쌍 — 통계 차트와 동일 문법)
  · 최근 수집 이력 리스트(미발견 amber, 행별 외부링크)

검증: 실데이터 e2e(A4 재수집 → lp_name/lp_url 반영 확인) +
헤드리스 브라우저 렌더 확인(시트·그래프·툴팁·링크), tsc·build 통과

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 17:10:00 +09:00
민헌 1cce752b47 Merge branch 'feature/negodata-lps' — negodata↔LPS 인터넷 최저가 연동(수동 트리거 전용) 2026-07-10 16:49:49 +09:00
민헌andClaude Fable 5 5ddf5f6249 refactor(negodata): LPS 자동 요청 배치 제거 — 검색은 수동 트리거 전용
협의 결정(2026-07-10): 크롤 비용이 사용자 행동에만 비례하도록,
갱신 오래된 상품을 자동으로 검색 요청하던 잡(매일 04:00, 상한 500건,
일 ~$2)을 제거한다. 검색 진입점은 상품 화면의 수동 트리거
(POST /v1/item/{id}/lowest-price) 하나만 남는다.

- request_lps_searches 잡·request_stale_searches 서비스·stale_items
  CRUD·배치 상수(REFRESH_HOURS 등) 제거
- 수집 잡(sync_lps_results, 5분)은 유지 — 크롤을 일으키지 않는
  반영 백스톱(모달 조기 종료·폴링 초과분 자동 반영, 비용 0)

검증: 스케줄러 등록 잡 3개(견적마감 2 + LPS 수집 1) 확인, 수집 잡 실행 정상

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 16:47:39 +09:00
민헌andClaude Fable 5 3171311746 feat(negodata/front): PriceUpdateModal 데모 → LPS 실연동
- 가짜 setTimeout 애니메이션 제거 — 상품별 POST lowest-price(큐 접수,
  duplicated 는 결과 대기 합류) 후 GET 5초 폴링(서버가 조회 시 lps_db
  증분 동기화를 겸하므로 폴링이 곧 수집)
- 요청 시각 이후 crawl_end_time 이력만 이번 결과로 인정, 완료/미발견
  로그 구분(emerald/amber), 5분 대기초과분은 주기 동기화 자동반영 안내
- 종료 시 /v1/item/list invalidate → 테이블 인터넷 최저가 컬럼 갱신
- 닫기 = 폴링만 중단(서버 검색은 계속됨을 UI 에 명시)
- orval 재생성: lowest-price 응답 타입화(LowestPriceEntry·lowest_price)

검증: tsc 통과, vite build 통과 (API 흐름 자체는 ③ e2e 로 검증됨)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 16:32:38 +09:00
민헌andClaude Fable 5 28b4a9e797 feat(negodata): lowest-price 스텁 API 실구현 — 즉시 트리거 + 온디맨드 동기화 조회
- POST /v1/item/{id}/lowest-price: 상품 1건 LPS 즉시 검색요청(manual
  우선순위). queued/duplicated/unavailable 상태 반환, 실패는
  ErrorType.LPS_UNAVAILABLE(2000 블록 신설)
- GET /v1/item/{id}/lowest-price: 대표 최저가 + 최근 수집 이력(최신순,
  LowestPriceEntry 타입화). 조회 전 lps_db 증분 동기화 1회 수행 —
  5분 크론을 기다리지 않는 실시간 폴링 UX(멱등·저비용)
- 동시성 방어 2겹: 프로세스 내 asyncio.Lock(크론·온디맨드 직렬화) +
  uq_iilp_item_crawl_time 유니크 인덱스(alters/2026-07-10, init.sql
  멱등 반영·dev DB 적용) — 경합 진 쪽 tx 실패 후 다음 tick 흡수
- LpsSyncService 무인자 생성자(FastAPI Depends 호환)
- compose: negodata-backend 에 LPS_DB_HOST·LPS_BASE_URL env(미설정 시
  연동 비활성으로 조용히 동작)

검증(도커 컨테이너 e2e): 인증→POST queued→LPS 크롤→GET 온디맨드
동기화로 이력 즉시 노출(not_found 정책: 대표값 미변경 확인),
company 스코프 차단(타사 상품 ITEM_NOT_FOUND) 확인

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 16:17:05 +09:00
minaChoi c0e6987c3c [fix] negodata/front: 통계 카테고리별 절감 차트 -> 손해(음수)는 안보이게, 대시보드에서 일반관리자도 회사 통계 보이게 수정 2026-07-10 15:58:13 +09:00
민헌andClaude Fable 5 523661e3d2 feat(negodata): LPS 최저가 동기화 배치 — 요청(API)·수집(lps_db)·반영(items)
설계(2026-07-10 결정): 요청은 LPS API(dedupe·워커알림 보존), 결과는
lps_db.price_history 직접 읽기(읽기전용 엔진). product_code=item_id
로 결과가 자동 매핑된다.

- 잡③ request_lps_searches(매일 04:00 KST): 24h 이상 미수집 상품을
  최대 500건 enqueue(job_type=batch, 100건/콜 청크) — 비용 발생 잡
- 잡④ sync_lps_results(5분): 워터마크(max crawl_end_time) 증분 수집
  → item_internet_lowest_prices append(성공/실패 모두) + 성공분 최신값
  items.internet_lowest_price 박제(+yn). 한 트랜잭션(부분반영 방지)
- 스캔 바닥 3일 — 비uuid·미존재 상품 행이 워터마크를 못 올려도
  재스캔 범위 유한
- ⚠️ 시각은 aware UTC 통일 — naive 를 timestamptz 파라미터로 넘기면
  PG 세션 타임존(KST) 해석으로 9시간 어긋남(중복 수집 실측 버그 수정)
- LowestPriceWebsite 코드 enum(naver=1 coupang=2 …), iilp ORM 모델,
  lps_base_url config(+LPS_BASE_URL env)

검증: 실상품 1건 e2e(요청→크롤 found 15,000원→이력+박제 반영),
멱등성(재실행 빈 카운터), 비uuid 12건 스킵, 대상선정 쿼리 500건 상한

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 15:38:57 +09:00
HyeongBaeYangandClaude Fable 5 b41f7c67f1 [feat] negodata: 카드 에디터 조건 전략 변수 + 미리보기 변수 라벨 치환
① 카드 목록 스크립트 미리보기에서 {변수} 토큰을 한글 라벨 칩으로 렌더
   (renderCardScriptPreview) — 원시 토큰({prev_partner_price} 등) 노출 제거.
② "조건 전략"(customer_condition) 특수 변수 추가:
   - 툴바 '+ 조건 전략' → 본문에 위치 칩 삽입, 본문 아래 별도 Slate 입력창 노출
   - 조건 내용은 변수 노드에 중첩 보관(edit_script 배열 유지·하위호환) + 저장 시
     script 의 해당 위치에 주입 → agent 는 완성된 문구를 그대로 읽음(무변경)
   - 서브 에디터는 조건 전략 버튼 숨김(중첩 방지), 빈 조건 저장 차단

DB·백엔드·agent 변경 없음(edit_script 타입 unknown, 조건 노드 내 중첩).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 15:18:11 +09:00
민헌andClaude Fable 5 9e9de52200 feat(negodata): lps_db 읽기전용 연결 기반 — DBType.LPS + 조건부 엔진 등록
LPS(인터넷 최저가 검색) 연동 1단계. price_history 동기화 배치가 쓸
읽기전용 접속을 기존 확장점(DBType enum + 세션매니저 맵)에 등록한다.

- DBType.LPS=2, LpsDBConfig(read_* 만 — write 엔진 미등록으로 앱 차원
  읽기전용 강제, write 요청 시 KeyError)
- config name 비면 미등록(구버전 toml·LPS 없는 환경에서도 부팅 가능),
  배치는 is_registered() 로 사전 확인
- env override: LPS_DB_HOST/PORT/USER/PASSWORD/NAME (도커용)
- 검증: 엔진 등록·읽기 세션·write 가드 KeyError·lps_db.price_history
  실조회 확인

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 15:11:18 +09:00
HyeongBaeYang 26d9fa3c4b Merge branch 'feat/chat-update' — 협상 고도화(LLM 표현/이해층·카드 전술·변수 카탈로그) 2026-07-10 13:39:19 +09:00
민헌 18f6466a8b Merge branch 'feature/lps' — 인터넷 최저가 검색(LPS) 시스템 2026-07-10 13:30:48 +09:00
민헌andClaude Fable 5 d4cee1caf7 feat(lps): API 스케일 파라미터를 .env 로 노출 — PROCESS_COUNT·커넥션 예산
주석 상태였던 PROCESS_COUNT/DB_CONNECTION_BUDGET 를 활성화하되 서버별
값은 .env(LPS_API_PROCESS_COUNT, LPS_DB_CONNECTION_BUDGET)로 조정.
기본 1/40 — API 는 단일 프로세스로도 ~1,100 RPS(실측)라 평시 충분,
부하 대비 시에만 상향. 풀 자동 산정이 예산 초과를 방지.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 12:02:17 +09:00
민헌andClaude Fable 5 a267326bf7 fix(lps): Docker 이미지 무시크릿화 + 배포 견고화 — 리뷰 발견사항 일괄 적용
시크릿 유출 차단(핵심):
- config.local.toml(OpenAI·DECODO·네이버 키)이 COPY . . 로 이미지에
  구워지던 문제 — .dockerignore 제외 + 빌드 시 example(플레이스홀더)
  복사로 대체. 실값은 compose env 주입(리포 루트 .env, 템플릿 .env.example)
- DECODO_PORT_START/END/SESSION_MINUTES env override 추가 — 포트가
  toml(플레이스홀더 0)에만 있으면 자격증명을 넣어도 프록시가 조용히
  꺼지는 구멍 봉합

배포 견고화:
- API Dockerfile 에 HEALTHCHECK(/healthz) 추가
- autoheal 컨테이너 추가 — compose restart 는 unhealthy 를 재시작하지
  않으므로 라벨(autoheal=true) 기반 자동 재시작 담당
- 이미지 python 3.12→3.14 정렬(로컬 개발·테스트 환경과 일치)
- API 이미지 경량화: requirements-api.txt 분리(크롤 의존성 제거, 330MB)

검증: 양 이미지 빌드 성공, 이미지 내 시크릿·.profiles 부재 확인,
무시크릿 API 이미지 스모크(healthz/readyz/HEALTHCHECK healthy) 통과

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 11:53:47 +09:00
민헌andClaude Fable 5 c075dfbcfb fix(lps): .dockerignore 에 .profiles/ 추가 — Chrome 세션 이미지 유출 차단
COPY . . 가 로컬 Chrome 프로필(쿠키·cf_clearance, 149MB)을 API·워커
이미지에 굽고 있었다. 컨테이너는 빈 프로필에서 웜업으로 쿠키를 만들고
volume(/profiles)에 영속하는 설계라 이미지에 있을 이유가 없다.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 11:45:19 +09:00
민헌andClaude Fable 5 4381649658 docs(lps): 워커·브라우저 1:1 근거와 워커 수 상한 산정법 문서화
- 6-2: 브라우저가 아니라 신원(프로필+sticky IP)이 희소 자원인 이유,
  비율이 어긋날 때의 손해(유휴 낭비 vs 락 직렬화), 신원당 처리량 캡
- 6-3: 워커 상한 = min(RAM캡, 포트캡÷3, 실측 정체점) — 하드캡 계산식과
  계단식 실측 시 멈춤 신호 5가지(처리량 정체·blocks_1h·메모리·
  단일코어 포화·p95)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 11:32:12 +09:00
민헌andClaude Fable 5 463416c3a2 fix(lps): 워커 행(hang) 3중 방어 — 잡 데드라인·웜업 타임아웃·정리 루프 격리
부하테스트(N=10) 실측: 쿠팡 브라우저 재기동 경로 행으로 워커 2/3가
12~15분 정지(쿠팡 검색 1콜 880s), heartbeat 가 lease 를 계속 갱신해
reaper 회수 불가 + stuck_running=0 으로 관측 사각. 이에 대한 방어:

- P1 잡 데드라인: runner._process 에 wait_for(기본 300s, env
  LPS_JOB_DEADLINE_SEC) — 초과 시 취소·fail → 백오프 재큐/DEAD
- 웜업 시도당 60s 타임아웃 — 웜업이 어댑터 락을 쥔 채 행하면
  그 워커의 실 검색이 전부 락 대기로 동반 정지(실측 케이스)
- P2 browser reaper: close_if_idle 에 60s 타임아웃 — 한 어댑터
  close 행이 정리 루프 전체를 멈추는 것 방지(실측 케이스)
- P3 stuck_running: lease 만료 OR 실행 10분 초과(run_started_at)
  — 행 상태에서도 지표·알림에 잡히게

테스트 5건 추가(데드라인 DEAD/재큐, stuck 지표, reaper 격리)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 11:27:03 +09:00
민헌andClaude Fable 5 fbd2cec1da test(lps): 부하테스트 상품셋 100종 카탈로그 분리 — 실제 입력 분포 재현
- loadtest/catalog.json 신설(실존 상품 100종): 규격만 54 · 모델포함 26 ·
  이름만 20 · 기준가 포함 7 (price→가격밴드 필터 경로 포함)
- loadtest.py 는 인라인 6종 대신 카탈로그 로드, 실행 시 구성 요약 출력

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 10:50:28 +09:00
민헌andClaude Fable 5 5e485e9b6e feat(lps): 오픈마켓 폴백 기본 비활성(LPS_FALLBACKS 토글) — 협의 결정 B안 적용
2026-07-10 협의: 검색은 네이버+쿠팡만. G마켓·옥션·11번가 폴백은 최종 최저가
기여 0회에 검색당 최대 15s·프록시 비용 ~87%를 차지해 로직에서 제외.
주석처리 대신 env 토글로 코드·테스트는 살려둔다(부패 방지·env 한 줄 재가동).

- worker_main: LPS_FALLBACKS(기본 빈값=OFF)로만 폴백 어댑터 생성, 잘못된 값 경고,
  기동 로그에 폴백 상태 표기. 핸들러는 빈 폴백을 원래 정상 처리라 로직 변경 없음
- run_local_worker.sh: 폴백 여부 대화형 질문 추가(기본 비활성)
- compose: LPS_FALLBACKS 주석 env(재가동용)
- decision-openmarket-crawler.md: 결정(B)·근거·재가동 절차(라이브 스모크 선행) 확정 기록
- README·architecture·operations: 기본 비활성 반영

검증: 전체 테스트 106 passed(폴백 로직 테스트는 fake 주입이라 계속 유효),
워커 실기동 로그 '오픈마켓 폴백: OFF' 확인

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 10:14:39 +09:00
minaChoi 7f1c0be2b3 [feat] negodata: 협력사 채팅 계정(supplier_users) 관리 — 발급·비번 재설정·활성상태
- 백엔드: supplier_users/supplier_user_tokens ORM 매핑, /v1/supplier/{id}/account 4종(조회·발급·재설정·상태), 회사 스코프 게이팅, 재설정·비활성 시 토큰 삭제로 기존 로그인 즉시 무효화
- 비밀번호: 발급=서버 자동생성(1회 반환), 재설정=커스텀 지정 가능(미지정 시 자동생성)
- 프론트: 협력사 상세 SupplierAccountManager 섹션 + 목록 '채팅 계정' 컬럼, orval 재생성(SupplierType 은 enumLabels 로컬 상수로 이동)
- 테스트: test_supplier_account.py 9건, 전체 스위트 green
2026-07-10 10:14:00 +09:00
민헌andClaude Fable 5 89fe2c9805 feat(lps): 실시간 관측 대시보드 추가 — 큐 추이·코어별 CPU·프로세스 그룹 사용률
loadtest/monitor.py (:9700, 단일 파일·외부 인프라 없음) + run_monitor.sh(대화형).
e2e 부하(N=100 loadtest.py) 중 "프로세스가 잘 진행되는지, 코어가 전부 도는지,
병목이 어느 층인지"를 브라우저에서 2초 간격으로 본다:

- 큐 추이: /v1/lps/ops 폴링 — PENDING/RUNNING/DONE/DEAD 라인 + 처리량(개/분) 타일
- 프로세스 그룹 CPU: worker/api/chrome/postgres — 병목 층 판독
  (chrome 은 워커 자손만 집계해 사용자 브라우저와 분리, uvicorn spawn 자식은 부모로 api 귀속)
- 코어별 사용률 막대: 멀티코어 활용 확인
- 현재 스냅샷 표 + 호버 툴팁 + 라인 끝 직접 라벨(dataviz 팔레트 검증 통과, 다크 서피스)
- psutil 의존성 추가(로컬 관측 전용)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:50:14 +09:00
민헌andClaude Fable 5 64d5063041 feat(lps): 서버 실행 스크립트에 멀티코어 대화형 선택 추가
일반 실행(1) 선택 시 PROCESS_COUNT 를 물어보고(기본 1, CPU 코어 수 표기),
2 이상이면 DB_CONNECTION_BUDGET 도 물어본다(기본 96 — 전용 PG 벤치값).
워커 스크립트(run_local_worker.sh)의 동시성 질문과 같은 대화형 패턴.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:09:55 +09:00
민헌andClaude Fable 5 47c64eaf8b fix(lps): 워커 graceful shutdown — 신호 핸들러·잡 마무리 유예·정리 격리
- SIGINT/SIGTERM 핸들러 등록: cancel 대신 stop 이벤트 set → 새 잡 클레임 중단,
  하던 잡은 마무리 후 자연 종료(트레이스백 없이 exit 0). 신호 재수신 시 강제 종료
- 종료 유예 LPS_SHUTDOWN_GRACE_SEC(기본 60s) 초과 시 강제 취소(잡은 lease 만료 후 재큐)
- 워커/리퍼가 예외로 죽으면 기존처럼 전파하되, finally에서 남은 태스크 취소·완주 대기 후 정리
- 리스너·어댑터 정리를 항목별 try/except로 격리 — 하나 실패해도 나머지 Chrome 정리
- 웜업(bg) 태스크는 종료 신호 즉시 취소해 어댑터 락 해제
- compose lps-worker에 stop_grace_period: 75s (기본 10s면 드레인 전 SIGKILL)
- 운영 가이드에 워커 종료 절차 문서화

검증: SIGTERM/SIGINT 실기동 테스트 — graceful 로그 후 exit 0, 기존 테스트 26개 통과

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:03:57 +09:00
민헌andClaude Fable 5 ddb6f6bd2f fix(lps): 워커 로그 노이즈 2건 제거 — 리퍼 네이버 스킵 + 폴백 데드라인 cancel 제거
- browser-reaper가 close_if_idle 없는 어댑터(네이버 httpx)를 건너뛰도록 getattr 가드
  → 30초마다 반복되던 ERROR 로그 제거
- 폴백 데드라인을 wait_for(cancel) → asyncio.wait(버림)으로 변경
  → in-flight page.goto 취소 시 patchright 내부 future가 남기는
    'Future exception was never retrieved' 노이즈 제거, 페이지 어중간 상태 방지
  → 버려진 태스크는 강한 참조 집합(_abandoned_fallbacks)에 보관(GC 중도 파괴 방지),
    종료 시 콜백이 예외 회수 후 집합에서 제거
- 데드라인 테스트에 잔여 태스크 배수(drain) 검증 추가

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 08:50:12 +09:00
민헌andClaude Opus 4.8 08a9c52088 docs(lps): 아키텍처에 API 멀티코어 스케일·커넥션 풀 자동산정(6-1) 추가
process_count 를 늘릴 때 풀 오버서브스크립션→커넥션 고갈 함정과
connection_budget 기반 자동 역산 해법을 문서화.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 08:35:48 +09:00
민헌andClaude Opus 4.8 0e30354ba5 feat(lps): 로컬 워커·부하테스트(GUI) 실행 스크립트 추가 (대화형)
기존 run_local_server.sh 스타일에 맞춘 대화형 .sh 두 개.

- run_local_worker.sh: 동시성(WORKER_CONCURRENCY)·Chrome 프로필(LPS_PROFILE_DIR)
  선택 후 워커 기동. 실행 중 워커 감지 시 교체 여부 확인. venv/config 자동 보장.
- run_loadtest_gui.sh: Locust 웹 UI(:8089) 기동. 워커 실행 중이면 경고(크롤 비용),
  API 미기동 시 PROCESS_COUNT 받아 백그라운드 기동(종료 시 함께 정리). 부하생성기 --processes.
- .gitignore(lps): .profiles/(Chrome 쿠키·cf_clearance 세션) 커밋 방지
- README·operations: 새 스크립트 안내로 갱신

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 08:33:11 +09:00
민헌andClaude Opus 4.8 9c2432c818 feat(lps): process_count 기반 커넥션 풀 자동 산정 — 멀티코어 풀 오버서브스크립션 방지
connection_budget(기본 40)을 두고, 기동 시 process_count 에 맞춰
pool_size/max_overflow 를 역산: (pool+overflow)×2엔진×process_count ≤ budget.
워커를 늘려도 config 가 스스로 예산을 지켜 커넥션 고갈→요청 실패를 예방.

- config_models: MainDBConfig.connection_budget 추가
- server_configs: _autosize_pool(process_count 확정 후 산정) + _apply_pool_env_override
  (우선순위 = 명시 DB_POOL_SIZE > 자동 산정 > toml pool)
- web_main: 기동 로그에 실효 풀/총커넥션/예산 출력
- env: DB_CONNECTION_BUDGET override, docker-compose 에 knob 노출
- tests: test_pool_autosize 10케이스(예산 준수·분할비·비활성·infeasible 바닥)
- docs: operations 2-1 멀티코어/풀 섹션 + loadtest README 자동산정 표

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 23:59:05 +09:00
민헌andClaude Fable 5 a63793daf0 test(lps): Locust API 부하 테스트 + 멀티코어 벤치 (풀 병목 발견·증명)
API(enqueue/조회, asyncpg I/O 바운드) 부하 테스트로 멀티코어 활용·한계 측정.

- loadtest/locustfile.py: enqueue(고유코드 write)+조회 가중 부하.
- loadtest/bench_multicore.sh: PROCESS_COUNT 1→N 자동 비교(--processes 로 부하생성기도 멀티프로세스).
- server_configs: PROCESS_COUNT / DB_POOL_SIZE / DB_MAX_OVERFLOW env override(코드·toml 수정 없이 튜닝).
- loadtest/README.md: 발견 문서화.

발견(11코어·1500users): 기본 풀(10/20)로 워커 늘리면 실패 폭증(1w=0 → 4w=10336) —
(pool+overflow)×2엔진×workers=240 > PG max_connections=100 커넥션 고갈(SQLAlchemy pool checkout 실패).
증명: 풀 8/4(96<100)로 PC=4 재실행 → RPS 1336→2705(2배), 실패 0. 코드는 멀티코어 활용 가능,
막는 건 풀 오버서브스크립션. 규칙: (pool+overflow)×2×process_count ≤ max_connections.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:45:25 +09:00
민헌andClaude Fable 5 eba78dbbb9 docs(lps): README 최신화 — Dockerfile.worker·문서목록(배포/관측/크롤러논의)
폴더구조에 Dockerfile.worker, 문서 표에 Docker배포·관측·decision-openmarket-crawler 반영.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:32:52 +09:00
민헌andClaude Fable 5 97e566f844 docs(lps): 운영 가이드 — 관측(readyz/ops/알림)·라이브 스모크·Docker 배포
P4/P5 반영: /readyz·/v1/lps/ops·워커 하트비트·임계 알림 env, LPS_LIVE 라이브 스모크,
docker compose 배포(헤드풀 Chromium+Xvfb·시크릿 env·프로필 볼륨·HEALTHCHECK).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:27:02 +09:00
민헌andClaude Fable 5 eb1ff8fee1 test(lps): P5 브라우저 경로 스모크 — search 오케스트레이션 + 라이브 드리프트 감지
가장 취약·복잡한 경로(회전·재시도·차단감지)의 자동 테스트 공백을 메운다.

- mock 하니스(_MockPage/_MockCtx/_MockProxy)로 search() 를 결정론 테스트(브라우저 없이):
  정상 반환 / 차단→IP회전→복구 / 프록시전송오류→회전→복구 / 비프록시오류→실패(무회전) /
  차단 소진→blocked 실패. 5종.
- 라이브 스모크(각 어댑터 실제 사이트 검색→파싱): 셀렉터·안티봇 드리프트 감지. IP 의존·느려서
  기본 skip, LPS_LIVE=1 로 명시 실행(수동/야간). 네이버 스모크 통과 확인.

전체 96 passed, 5 skipped.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:25:42 +09:00
민헌andClaude Fable 5 d6dd47e652 feat(lps): P4 관측·알림·워커 헬스 — readyz/ops + 하트비트/HEALTHCHECK + 임계 알림
프로덕션 운영 가시성. 행/좀비 워커 감지 + 큐/차단 지표 노출 + 임계 알림.

- API: /readyz(DB 도달성=readiness, 실패 503; /healthz=liveness와 구분).
  /v1/lps/ops(플랫 JSON): 큐 카운트 + oldest_pending_sec(큐지연) + dead_1h + stuck_running + blocks_1h.
- crud: JobQueue.ops()/ping(), BotDetectionLog.recent_count().
- worker: run_ops_monitor — 하트비트 파일 주기 갱신(Docker HEALTHCHECK 가 신선도로 행 워커 감지)
  + 임계(DEAD/차단/큐지연/stuck) 초과 시 WARN 로그 + (LPS_ALERT_WEBHOOK 있으면) Slack 호환 웹훅.
- Dockerfile.worker: HEALTHCHECK(하트비트 <120s). 임계·웹훅은 env(LPS_ALERT_*).
- 테스트: readyz/ops 2종.

검증: 컨테이너 healthy 판정, 하트비트 갱신, ops 스냅샷 정상. 91 tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:21:43 +09:00
민헌andClaude Fable 5 3a8d669970 feat(lps): P2 시크릿 env 주입 + Chrome 프로필 영속 볼륨
프로덕션에서 시크릿을 이미지에 굽지 않고 env 로 주입, 재시작 시 챌린지 쿠키 유지.

- server_configs: 시크릿 env override 추가(house 의 DB override 패턴 확장) —
  OPENAI_API_KEY/MODEL, DECODO_HOST/USERNAME/PASSWORD/COST_PER_GB, NAVER_KEYS="id:sec,...".
  로컬은 env 미설정 → config.local.toml 그대로.
- worker_main: Chrome 프로필 경로를 LPS_PROFILE_DIR(기본 /tmp)로 env 화 → 영속 볼륨 마운트 가능.
- docker-compose: lps-worker 에 lps-profiles 볼륨(/profiles) + 시크릿 env 주입 주석 예시.
- config.example: 프로덕션 env 주입 목록 문서화.

검증: env override 동작(OpenAI/DECODO/Naver), 프로필이 /profiles 볼륨에 Cookies 포함 저장(cf_clearance 유지). 89 tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:04:37 +09:00
민헌andClaude Fable 5 94d4e54d5e feat(lps): P1 컨테이너화 — 워커 이미지(Chromium+Xvfb) + compose
프로덕션 배포 토대. headless Chrome 은 Akamai/Cloudflare Turnstile 에 탐지됨(실측 실패)
→ 컨테이너에선 Xvfb(가상 디스플레이)로 headful Chromium 을 실행한다.

- Dockerfile.worker: chromium+xvfb+xauth+한글폰트. Xvfb 를 백그라운드로 띄우고 python 을
  exec 승계(로그가 docker logs 로 나옴; xvfb-run 은 stdout 을 삼킴). root=--no-sandbox 필수.
- Dockerfile: API 전용(lean, 브라우저 불필요)임을 명시.
- docker-compose: lps-api(:9600) + lps-worker(shm 1g, DB=host.docker.internal) 서비스 추가.
- browser_base: 브라우저 실행 대상 env 화(LPS_CHROME_EXECUTABLE/CHANNEL). 컨테이너=시스템
  chromium(+no-sandbox/disable-dev-shm-usage), 로컬=실제 Chrome(channel=chrome).

검증(컨테이너): DB연결·프리플라이트·쿠팡(Akamai)·gmarket(Turnstile) 웜업 통과 →
end-to-end 검색 DONE(8몰: 네이버·쿠팡·G마켓·옥션·11번가, 비용 $0.016). docker logs 로 로그 확인.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 22:56:56 +09:00
민헌andClaude Fable 5 e2cd2570e3 docs(lps): 오픈마켓 크롤러 유지 여부 논의 문서
팀 논의용 의사결정 메모 — 크롤러가 비용·복잡성 ~80%인데 ROI 미증명.
현황 데이터(비용 87% DECODO·최저가 이긴 적 0·플래키), 핵심 질문(by_mall 소비처),
옵션 4종(A.TTL캐시 / B.게이트 / C.gmarket드롭 / D.현행), curl_cffi 불가 근거.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 21:51:21 +09:00
민헌andClaude Fable 5 10eb67e8c6 docs(lps): 문서 최신화 — 오픈마켓 폴백·Turnstile·비용계측·동시성·프록시복원력
이번 라운드 변경을 README/아키텍처/운영 가이드에 반영.
- README: 기능표(오픈마켓 폴백·원가계측·다중병렬), 워크플로우 4-1 폴백 단계, 폴더구조
- architecture: 안티봇 대응(쿠팡 Akamai / ESM Cloudflare Turnstile 웜업·동적차단),
  검색 원가 계측(CDP 실측·컴포넌트별 비용), 다중 상품 병렬, 유휴 브라우저 정리
- operations: 로그 항목(프리플라이트·웜업·IP회전·데드라인·유휴정리), 문제해결(407·Turnstile·
  Chrome 정리·느림/비쌈), 배포유의, 원가/몰별 DB 쿼리

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 21:18:12 +09:00
민헌andClaude Fable 5 77a36c43d4 fix(lps): gmarket 웜업 신뢰성 — 나쁜 IP 시 회전 재시도
웜업이 인터랙티브 Turnstile(IP 평판 나쁨)로 실패하면 다른 IP 로 회전해 최대 3회 재시도.
gmarket 커버리지 플래키함 완화(100 IP 풀에서 좋은 IP 를 찾을 확률↑).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 21:06:29 +09:00
민헌andClaude Fable 5 0cd817a61d fix(lps): 대역폭 비용 정확화 — CDP 실제 전송 바이트로 계측
지금까지 last_bytes=page.content()(렌더된 DOM 크기)라 실제 네트워크 전송량이 아니었다
— 리소스 차단 효과가 안 보이고 ESM DOM(~5MB) 과대계상 → DECODO 비용이 부정확했다.

- browser_base: CDP 세션(new_cdp_session) 부착, Network.loadingFinished 의 encodedDataLength
  누적 → last_bytes=실제 전송 바이트. 컨텍스트당 1회 부착, 검색마다 리셋. 미지원 시 DOM 폴백.
- 실측(gmarket): 콜드(차단해제) 3.44MB → 웜(차단활성) 1.07MB(~3x↓) — 동적 차단 효과가 이제 숫자로 보임.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 20:27:11 +09:00
민헌andClaude Fable 5 8a594b667d perf(lps): Step2/3 — Turnstile 웜업·동적 차단 + 유휴 브라우저 정리
G마켓/옥션 Cloudflare Turnstile 을 실제로 통과시키고, 쌓이는 브라우저를 정리한다.

Turnstile 규명(실측): patchright 가 콜드 ~12초에 자동 통과, 통과 후 cf_clearance 쿠키로
이후 요청은 ~5초(웜). 단 **리소스를 조금이라도 차단하면 Turnstile 지문검사에 걸려 실패**
(이미지만 막아도 실패). 하지만 **cf_clearance 확보 후엔 차단해도 재챌린지 없음**.
- 동적 차단: _block_active + _blocking_now() 훅. ESM 은 cf_clearance 있을 때만 차단
  (콜드=허용→Turnstile 통과, 웜=이미지/미디어/폰트 차단→대역폭↓). ready_timeout 25s.
  best-effort Turnstile 체크박스 클릭(인터랙티브/나쁜IP 대비).
- 웜업: 기동 시 gmarket/auction/coupang 를 1회 풀어 쿠키 선점(백그라운드) → 실 작업은 웜.
- 유휴 브라우저 정리: _last_used + close_if_idle + run_browser_reaper(유휴 120s) — 메모리 회수.
  쿠키는 user_data_dir 에 남아 재기동해도 (같은 IP면) 웜 유지.
- 테스트: 유휴 정리 2종.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 20:20:58 +09:00
minaChoi a80dac20ed [fix] postgres-init: init.sql 병합 충돌 해소 — last_accessed_at DEFAULT now()
stash 충돌 마커 제거. company.users·supplier.supplier_users 에 DEFAULT now() 추가(신규 DB)
+ 말미 보정 ALTER(기존 DB). ORM server_default 의존이라 없으면 유저 생성 시 NOT NULL 위반.

Little-Helped: Stupid Claude
2026-07-09 17:04:40 +09:00
minaChoi 1b9ca062f3 [feat] negodata: 협상카드 회사 스코프·공용 읽기전용 + 견적 목표가 산정내역 수정
협상카드
- 목록/조회를 등록자 개인 → 회사(company.users 조인) 단위로 확장: 같은 회사 유저 카드 + 공용(user_id NULL)
- 공용 카드는 기본 제공 자산 → 수정·삭제 불가(OWNER 포함), is_shared=True API 등록 거부
- 개인 카드 변경은 본인∪최고관리자만, 프론트 버튼 disable+툴팁
- 공개범위 셀렉터·엑셀 공개범위 컬럼·CardTable 전체 배지 제거(항상 개인 등록)
- test_card.py 5케이스 재작성

견적 목표가 산정내역
- get_setting_rates: 단일 컬럼 select 결과를 이중 인덱싱해 항상 예외 → 마진율이 늘 0으로 적용되던 버그 수정
- get_target_breakdown: 채택 후보 판정을 '현재 최소값' → '저장 목표가와 값 일치'로 변경(산정 후 상품가 변동에도 초록 체크 유지)
- 견적상세 협상카드 탭 세션ID 컬럼 제거

견적생성 모달
- 목표가 미리보기·마감기한 기본값(+1h)·미래 검증, combobox 팝오버 scrollIntoView, maskPrices 비율(%) 마스킹

Little-Helped: Stupid Claude
2026-07-09 17:04:40 +09:00
민헌andClaude Fable 5 4b8dee8583 perf(lps): Step1 — 폴백 데드라인 + fail-fast로 검색 지연 상한
G마켓 챌린지가 안 풀린 채 25~70초를 먹던 문제에 상한을 씌운다. 폴백은 '있으면 좋은'
보강이라 데드라인으로 잘라도 안전(그 몰만 스킵).

- handler: 각 폴백 크롤에 fallback_deadline_sec(기본 15s) wait_for. 초과 시 스킵.
  _timed_search 예외를 BaseException 로(CancelledError 계측 포함).
- 폴백 어댑터 max_block_retries=0(챌린지 대기 2배 방지), ESM ready_timeout 22→12s, st11 20→15s.
- 테스트: 느린 폴백 데드라인 스킵 1종.

실측(동시성2·4상품): 상품당 p50 84.6s→34.2s(~2.5x), 벽시계 181s→65s(~2.8x),
처리량 1.3→3.7 상품/분, 1000건 $7.12→$5.06(~29%↓, 실패 챌린지 대역폭 절감).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 17:01:09 +09:00
민헌andClaude Fable 5 ba67275cd8 docs(lps): 운영 가이드 — WORKER_CONCURRENCY 병렬 실행 + loadtest.py 안내
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 16:28:51 +09:00
민헌andClaude Fable 5 ad26e6ce6f feat(lps): 다중 상품 병렬 검색(워커별 브라우저 세트) + 부하테스트 스크립트
WORKER_CONCURRENCY 를 늘려도 공유 브라우저 lock 때문에 직렬화되던 문제를 고쳐 진짜 병렬 검색.

- worker_main: _build_worker(i) 로 워커마다 자립 세트(브라우저 어댑터·AI·핸들러) 생성.
  프로필 분리(user_data_dir_w{i}, ProcessSingleton 충돌 회피) + 워커별 다른 프록시 포트
  (proxy.seed_offset 로 100포트를 균등 분할=다른 IP). naver/judge/keyword 도 워커별(공유상태 경합 제거).
  프리플라이트는 대표 프록시로 게이트 1회 확인.
- proxy.seed_offset(k): 워커 시작 포트 분산.
- loadtest.py: N개 상품 제출→폴링→처리량·지연(p50/p95)·AI/DECODO/총비용 집계.
  실측(동시성2, 4상품): 순차합 323s→벽시계 181s(~1.8x), 상품당 $0.0071, 1000건 ~$7.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 16:28:08 +09:00
민헌andClaude Fable 5 bf19d4a8fd perf(lps): 폴백 크롤 병렬화 + 오픈마켓 대역폭 절감
한 검색의 소요·DECODO 비용을 크게 낮춘다(실측: 110s→52s, proxy 8MB→2MB, 총비용 70%↓).

- 폴백 병렬화: _enrich_with_fallback 의 순차 for-loop → gather 동시 크롤. 각 몰 어댑터는
  별 브라우저 인스턴스라 병렬 안전. 소요=합→최댓값. AI usage 계측 동시성 불변식 주석 명시
  (judge.last_usage 세팅~읽기 사이 await 없음 → asyncio 협조 스케줄링상 안전).
- 대역폭: blocked_resource_types 를 어댑터별 설정화. 오픈마켓은 이미지/미디어/폰트만 차단
  (CSS/JS 유지 — 챌린지/렌더 보호). 격리 실험으로 차단 유무가 ESM 챌린지 성패에 무관함 확인
  (실패 원인은 IP평판/headless). st11 라이브 0.11MB 검증.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 16:11:32 +09:00
minaChoi 0d62440ee1 [feat] negodata/front: 온보딩 페이지 추가 + 이용안내 모달 재작성 2026-07-09 16:08:54 +09:00
민헌andClaude Fable 5 a80109cdcf chore(lps): FE 원가 타일 AI/DECODO 비용 분해 + config example cost_per_gb
- 임시 FE: 총 비용 타일에 AI·DECODO 분해, 크롤 트래픽에 프록시 경유 바이트(과금분)
- config.local.toml.example: DecodoConfig.cost_per_gb 안내

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 15:34:57 +09:00
민헌andClaude Fable 5 c955a8f367 feat(lps): 프록시 전송오류 IP회전 + 시작 프리플라이트 + DECODO/컴포넌트별 비용
프록시(DECODO) 포트/IP 사망(407/ERR_TUNNEL/ERR_HTTP_RESPONSE_CODE_FAILURE)이
봇차단과 구분 없이 예외로 튕겨 같은 죽은 포트로 재시도만 하다 DEAD 되던 문제를 고친다.

- browser_base: is_proxy_error(순수함수) + search 루프에서 프록시 전송오류 시 IP 회전 재시도
  (max_proxy_retries=2). 봇감지 회전과 통합. uses_proxy 프로퍼티.
- 쿠팡 어댑터를 BrowserSearchAdapter 로 통합 — 중복 machinery 제거, 회전 로직 한 곳에서 공유
  (detect_block 순수함수는 유지, 테스트 호환).
- proxy.healthcheck(): 시작 프리플라이트 — 살아있는 포트 선점 + egress IP 로그(빠른 실패·가시성).
  worker_main 기동 시 호출.
- 비용: DecodoConfig.cost_per_gb 추가. metrics 에 proxy_bytes(네이버 직접 제외) + 컴포넌트별
  cost{ai_usd, proxy_usd, total_usd}. FE 원가 타일에 AI/DECODO 분해·프록시 바이트.
- 테스트: is_proxy_error 8종 + 비용 분해 1종.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 15:33:37 +09:00
민헌andClaude Fable 5 9c478e80fd chore(lps): 임시 FE — 검색 원가 4타일(소요/AI비용/토큰/크롤 트래픽)
작업 카드에 result.metrics 렌더: 소요시간(+소스별), AI 비용$·호출수, AI 토큰(in/out),
크롤 트래픽(html bytes·fetch수·크롤 몰).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 15:17:42 +09:00
민헌andClaude Fable 5 69f6641c27 feat(lps): 검색 1건 원가 계측 — AI 토큰·비용 + 시간 + 크롤 트래픽
검색이 소모하는 리소스/비용/시간을 잡 단위로 집계해 result.metrics 로 적재(API/FE 노출).
지금까진 타임스탬프만 있고 실제 비용 동인(AI 토큰·대역폭)은 버려지고 있었다.

- services/metrics.SearchMetrics: duration_ms + ai(calls/tokens/est_cost_usd, gpt-4o-mini 단가)
  + crawl(fetches/html_bytes/malls_crawled) + source_ms
- AI 클라이언트: resp.usage 를 last_usage 로 노출(그동안 폐기하던 토큰)
- 어댑터: last_bytes(처리 HTML 바이트) 노출 — naver/coupang/browser_base 공통
- handler: 각 fetch 타이밍+바이트, AI 호출 토큰을 metrics 로 누적 → 결과에 스냅샷
- FE: 작업 카드에 원가 4타일(소요/AI비용/토큰/크롤 트래픽)
- 테스트 2종. ⚠️ html_bytes 는 대역폭 근사(오픈마켓 리소스 미차단분 제외=하한), CDP 정확화는 백로그

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 15:14:35 +09:00
민헌andClaude Fable 5 61b9e6ae82 docs(lps): 오픈마켓 폴백 크롤 반영 — 아키텍처·README
파이프라인 ⑤-1 폴백 단계(네이버 미커버 몰만 크롤), 구성요소 표에 오픈마켓 폴백,
폴더 구조에 esm/st11 추가.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:54:00 +09:00
민헌andClaude Fable 5 7e5814b0e5 chore(lps): 임시 FE — 오픈마켓 크롤 소스 표기(색상·크롤 뱃지·몰별 색)
by_mall/top 에 등장하는 gmarket·auction·st11 을 소스 색상 태그(+‘크롤’ 뱃지)로 표기.
몰별 최저가 막대도 소스별 색. 폴백으로 크롤된 몰임을 UI에서 구분.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:47:31 +09:00
민헌andClaude Fable 5 f9714c3f06 feat(lps): 오픈마켓 폴백 오케스트레이션 + 몰 dedup
사용자 규칙 '네이버로 그 몰 값 확보 성공→그 값, 실패(몰 없음)→실사이트 크롤' 구현.

- handler: found 라운드 뒤 _enrich_with_fallback — 네이버 매칭이 커버 못 한 타깃 몰만
  (canonical_mall 로 판정) 크롤 어댑터로 검색→같은상품 판정→병합. 크롤 실패는 격리(무시).
  fallback_crawl STAGE 기록.
- summarize_by_mall: 키를 (source,mall)→몰명(canonical)으로 — 네이버노출 vs 직접크롤 같은 몰
  중복을 최저가 1건으로 병합(dedup).
- card_parser: MALL_BY_SOURCE + canonical_mall() 추가.
- worker_main: gmarket/auction/st11 폴백 어댑터 등록(lazy 기동, 리소스차단 OFF).
- 테스트: 커버몰 크롤생략·미커버 크롤·실패격리·몰 dedup 4종.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:45:39 +09:00
민헌andClaude Fable 5 e365e5c6e0 feat(lps): G마켓·옥션·11번가 크롤 어댑터 + 브라우저 어댑터 베이스
네이버 폴백용 오픈마켓 크롤러 3종. 4중 복제를 피해 BrowserSearchAdapter 베이스로
브라우저 수명·프록시 회전·차단감지+IP회전 재시도·감지기록을 공유하고, 사이트 차이는
훅(_search_url/_parse/ready_selector/block_markers)으로 분리.

- browser_base: patchright 공통 machinery(쿠팡 machinery 일반화)
- card_parser: 오픈마켓 공용 카드 파서(CardConfig 주입) + util(extract_price/clean_name/shipping)
- esm: G마켓·옥션(eBay 백엔드 공유, site 파라미터 1개로 커버, '잠시만' 챌린지 대기)
- st11: 11번가 PC(공식API 판매자계정 필요라 불가). 지연로딩 → scroll_steps, '.c-card-item' 토큰
- 학습 반영: 오픈마켓은 리소스차단 OFF(렌더/챌린지 깨짐), 스턱 챌린지='잠시만' 잔존 시 차단 간주→IP회전
- 파서 결정론 테스트 7종(실렌더 카드 3개씩 경량 fixture). 라이브 검증: 신선 IP로 3사 모두 파싱 성공

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:41:05 +09:00
민헌andClaude Fable 5 3a2c6e43d4 feat(lps): price_history 몰별 최저가 스냅샷(by_mall JSONB)
몰이 열린 집합이라 와이드 컬럼(gmarket_*, st11_* …) 대신 JSONB 한 컬럼으로 담는다
— 몰 추가 시 마이그레이션 0. naver/coupang/final 3선 컬럼은 그래프 하위호환 유지.

- models: price_history.by_mall JSONB 추가
- crud: record/list 에 by_mall 왕복(json.dumps + CAST jsonb)
- handler: _price_snapshot 에 summarize_by_mall 적재, final 은 소스무관 전체 최저로
- protocol/service: history API 응답에 by_mall 노출
- migrations/2026-07-09: 기존 dev DB 동기화용 ALTER(추적 파일)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:15:58 +09:00
민헌andClaude Fable 5 2eccf4de50 chore: 로컬 리서치 노트(Temp.md·new.md) gitignore 처리
크롤링 라이브러리/안티스크래핑 조사 노트로 로컬 참고용. 향후 크롤러 작업에
관련되므로 삭제하지 않고 추적만 제외해 git status 를 정리한다.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:03:08 +09:00
민헌andClaude Fable 5 7806b35723 chore(lps): 임시 검색 콘솔 FE(lps-temp-fe) — API/그래프/몰별·배송 확인용
API 통신 확인용 단일 파일 프론트(외부 CDN 0, SVG 차트 자체 구현).
검색 요청 → 잡 폴링(파이프라인 퍼널·소스별 건수) → 최저가 히어로/상품표,
최저가 이력 3선 그래프(네이버·쿠팡·최종), 몰별 최저가 막대, 배송 뱃지,
헤더 헬스·큐 상태 실시간. CORS 매칭 위해 :5173 서빙(serve.sh, 대화형).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 13:59:56 +09:00
민헌andClaude Fable 5 8460a5d833 fix(lps): 쿠팡 차단 감지 다종화 — Edge Deny·권한제한·짧은HTML 폴백
기존엔 Akamai JS 챌린지 마커만 감지해, Edge Access Denied(errors.edgesuite.net)와
'사용권한이 제한된' 권한제한 페이지가 blocked=False 로 오판됐다. 그 결과 IP 회전·
bot_detection 기록이 누락되고 같은 IP 로 재시도만 반복하다 DEAD 로 빠졌다.

- 마커 3계열로 확장(Akamai / Edge Deny / 권한제한)
- 짧은 HTML 폴백(_MIN_RESULT_HTML): 0건인데 <10KB 면 미지의 차단으로 간주
  (정상 '검색결과 없음'은 전체 chrome 포함이라 큼)
- 감지를 순수 함수 detect_block(html, product_count) 로 분리 — 단위 테스트 6종

검증: 신라면 '사용권한이 제한된'(3383B) 감지 → IP 회전 → 새 IP 59건 복구.
파서 배송 분류 테스트도 함께 추가(shared fixture).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 13:59:43 +09:00
민헌andClaude Fable 5 61bc719e28 feat(lps): 배송비 유형 분류 — 쿠팡 배송신호 파싱 + 네이버 배송비제외 명시
NormalizedProduct 에 shipping_type(rocket|rocket_merchant|free|paid|None) 추가.
쿠팡 파서: 로켓 뱃지(img src)로 유형, '무료배송'/'배송비 X원' 텍스트로 금액 판별
(상품명 '무료배송' 오탐은 이름 제거 후 매칭). 네이버 lprice 는 배송비 제외
상품가라 배송 필드 None — 카탈로그 '배송비포함 최저가'와 다른 이유를 docs/api.md 에 명시.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 13:59:28 +09:00
민헌andClaude Fable 5 313d882df4 feat(lps): 네이버 몰별 최저가 분해(by_mall) — 오픈마켓 가시화
네이버 오픈API 결과엔 G마켓·옥션·11번가 등이 이미 mallName 으로 들어오는데
최저가 1건만 쓰고 몰 정보를 버리고 있었다. summarize_by_mall() 로 매칭 후보를
(소스, 판매몰)별 최저가로 축약해 result.by_mall(가격 오름차순)에 노출한다.
추가 요청 0건으로 오픈마켓 몰별 최저가를 확보 — 별도 크롤러 불필요.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 13:59:15 +09:00
민헌andClaude Opus 4.8 4863425ca5 refactor(lps): job_type 명칭 정리 — 출처 기반(레거시 negowiz 제거)
레거시 용어(negowiz)와 모호한 이름(new/single)을 출처 기반으로 변경.
우선순위 1~4는 유지, 기본값 single→manual.

- new_product(1) / manual(2, 기본) / partner(3) / batch(4)
- lps_service 우선순위 맵 + protocol 기본값/설명 + docs/api.md 표 + 테스트 갱신
- 전체 54/54

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 11:33:46 +09:00
민헌andClaude Opus 4.8 8bf34ea346 docs(lps): 프로젝트 문서화 — README + docs/(아키텍처·DB·API·운영)
비개발자/기획자/개발자 누구나 이해하도록 일목요연하게 정리. 길이 분산 위해 분할.

- README.md: 3줄 요약 + 워크플로우 다이어그램 + 주요기능 + 빠른시작 + 문서 목차
- docs/architecture.md: 구성요소·처리 파이프라인·재시도/프록시/봇감지/이력 원리
- docs/database.md: 테이블 4종(job/price_history/search_negative/bot_detection) + 코드값
- docs/api.md: 엔드포인트 요청/응답 예시(curl/Postman), 상태·코드 요약
- docs/operations.md: 실행·로그·DB조회·테스트·문제해결·배포유의

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 11:27:39 +09:00
민헌andClaude Opus 4.8 5906acc48a feat(lps): 최저가 이력(price_history) — 트리거 기반 시계열 그래프
같은 상품 반복 검색 시 최저가를 스냅샷으로 적재 → 네이버/쿠팡/최종 3개 선 그래프.
배치 아님(조회된 상품만, 실제 검색 시각에 기록) — 트래픽/리소스 절약.

- price_history 테이블: product_code·triggered_at(X축)·naver/coupang/final 최저가+상세·outcome
- crud/price_history: record() + list_by_product(시각 오름차순)
- handler: AI 매칭 후 소스별 min + 전체 min 스냅샷 기록(_price_snapshot).
  found/not_found 기록, 네거티브 캐시 히트·기술실패는 미기록
- API: GET /v1/lps/products/{product_code}/history → 그래프 데이터(시각 오름차순)
- tests: 스냅샷 계산/기록·조회/핸들러 기록규칙/API → 전체 54/54

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 11:13:28 +09:00
민헌andClaude Opus 4.8 bca8032b79 feat(lps): 봇 감지 시 IP 회전+재시도 + 감지 이력 기록
쿠팡이 봇으로 감지(Akamai 차단 페이지)하면, 같은 IP로 재시도하던 것을
'브라우저 끄고 새 IP로 켜서 재시도'로 전환. 감지 패턴도 축적한다.

- DecodoProxy.rotate(): 시간창 무관 즉시 다음 포트(=새 IP). current_port 노출
- coupang/adapter: 0건+차단마커 감지 시 → 감지기록 → proxy.rotate()+강제재기동 →
  인라인 재시도(max_block_retries=1). IP당 요청수(ip_request_no) 추적, 재기동 시 리셋
- bot_detection 테이블 + crud: source/query/ip_request_no/proxy_port/elapsed_sec/marker/
  headless/html_len 기록 → 'IP당 몇 요청 만에 감지되나' 분석 가능
- worker_main: on_detect=BotDetectionLog.record 주입
- 로그: [coupang][BOT-DETECTED] ip_req#N port=... elapsed=...s marker=...
- tests: proxy rotate 즉시회전 + 감지기록 CRUD → 전체 47/47

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 11:04:07 +09:00
민헌andClaude Opus 4.8 7911ba1745 refactor(lps): 환경설정 TOML 단일화 — .env 제거, 시크릿도 config.local.toml 로 통합
설정이 .env(시크릿)+toml(설정)로 갈려 있던 것을 config.local.toml 하나로 통합.
DB 비번이 이미 toml 에 있어 분리 기준이 임의적이었고, backend(하우스 패턴)도
toml 단일이라 일관성 확보. 환경별로 바뀌는 값(DB_HOST 등)만 env override 유지.

- config_models: NaverConfig(keys 로테이션)·OpenAIConfig·DecodoConfig 추가
- server_configs: 3개 로드, load_dotenv 제거(python-dotenv 의존성도 제거)
- proxy/naver/similarity/keyword/worker_main: os.environ → config 객체 참조
- config.local.toml.example: [NaverConfig]/[OpenAIConfig]/[DecodoConfig] 섹션
- .env/.env.example 삭제, README/주석 갱신 (배포는 toml 마운트 or env override)
- tests: DecodoConfig 기반으로 갱신 → 전체 44/44

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 10:06:00 +09:00
민헌andClaude Opus 4.8 2481c79e3f feat(lps): DECODO 포트기반 sticky + 대역폭 최적화(리소스 차단)
대시보드 실측 반영 — Decodo residential 은 포트 기반 sticky(gate:10001..N,
고정 user/pass, 각 포트=sticky 세션). IP 회전 = 포트 순환.

- proxy.DecodoProxy: 시간창 기반 포트 선택(창 안 동일 IP, 창 지나면 다음 포트=새 IP).
  _UNSET sentinel 로 '미지정(env)' vs '명시적 빈값' 구분(테스트 결정성)
- coupang/adapter: 이미지/미디어/폰트/CSS 차단(block_resources) — per-GB 대역폭 대폭 절감,
  Akamai(JS)·상품파싱엔 무영향. 라이브 검증: 차단 ON 에도 Akamai 통과+파싱 정상
- .env.example: DECODO_HOST/USERNAME/PASSWORD/PORT_START/PORT_END/SESSION_MINUTES
- tests: 포트범위/시간창 안정성/활성조건 5건 → 전체 44/44

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 09:48:54 +09:00
민헌andClaude Opus 4.8 4de85d43ed feat(lps): DECODO residential 프록시 — 쿠팡 sticky 세션 + 주기적 IP 회전
datacenter IP + Akamai 대응. 매 요청 IP 변경은 쿠키-IP 불일치로 재챌린지를
유발하므로, sticky 세션(일정 시간 같은 IP) + 주기적 회전 방식 사용.

- search/proxy.DecodoProxy: username 에 -session-<시간창id>-sessionduration-<분> 부착
  → 창 안에선 같은 IP, 창이 지나면 새 IP. 자격증명은 .env(DECODO_*), 4개 다 있어야 활성
- coupang/adapter: proxy 주입 + 세션창 경과 시 브라우저 재기동(IP 회전). 무프록시면 직접 연결
- worker_main: 쿠팡에만 DecodoProxy 경유(네이버는 공식 API라 미적용)
- .env.example: DECODO_HOST/PORT/USERNAME/PASSWORD/SESSION_MINUTES 슬롯
- tests: 활성조건·sticky username·server형식·세션창 회전 4건 → 전체 43/43

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 09:40:26 +09:00
민헌andClaude Opus 4.8 d54dee4f24 feat(lps): 재시도/못찾음 완결 로직 — 재정제 루프 + not_found + 네거티브 캐시
'못 찾음'을 유한하게 종료. 두 재시도 축을 분리(기술=큐 attempts/백오프,
검색어=refine 라운드). not_found 는 정상 종료(DONE)지 dead-letter 아님.

- ai/keyword: LLM 검색어 생성(정밀/광역) — 원본 0매칭 시에만 지연 호출(비용 절약)
- handler: 한정 재정제 루프(원본→정밀→광역, max_rounds=3) + 명시적 outcome(found/not_found)
  · 0매칭+소스정상 → 다음 라운드, 0매칭+기술실패 → raise(큐 재시도)
  · 라운드 소진 → not_found + 네거티브 캐시 기록
- negative_cache: search_negative 테이블 + TTL(24h) upsert — 같은 상품 재요청 재검색 차단
- worker_main: OPENAI 있으면 judge+keyword_gen ON, neg_cache 상시
- tests: 재정제/not_found/캐시히트/기술실패/캐시CRUD 11건 → 전체 39/39
- 라이브: 없는상품 3라운드→not_found(30s), 재요청 캐시히트(0.00s)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 09:12:47 +09:00
민헌andClaude Opus 4.8 b0a86b9720 feat(lps): AI 유사도 판정 — '같은 상품' 매칭으로 액세서리 오염 해결
파이프라인의 비워둔 슬롯(이상치 뒤·top-N 앞)에 OpenAI 유사도 판정을 결합.
"스탠리 텀블러" 검색 시 빨대마개·커버 등 호환 액세서리가 최저가로 올라오던
문제를 해결한다(기계적 최저가 → 같은 상품 최저가).

- ai/similarity: SimilarityJudge(OpenAI structured output). 액세서리/부품/다른규격 불일치 판별
- pipeline/core: apply_filters + rank_result 로 분리(AI 를 그 사이에 끼움), run_price_pipeline 동작 불변
- handler: judge 주입 시 ai_match STAGE 추가(필터 후 후보만 판정 → 토큰 절약), 미주입 시 생략
- worker_main: OPENAI_API_KEY 있으면 판정 ON
- requirements: openai / tests: fake judge 필터링 검증 → 전체 32/32
- 라이브: '스탠리 퀜처 887ml' → ai_match(60→15) → 실제 텀블러 top-6(액세서리 제거)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 08:44:57 +09:00
민헌andClaude Opus 4.8 9557c1b1af feat(lps): 네이버 어댑터 + 다중 소스 병합 검색
네이버 쇼핑 오픈API 어댑터(크롤링 불필요) + 핸들러를 다중 소스로 확장.
쿠팡(브라우저)+네이버(API)를 동시 검색·병합해 교차 최저가를 뽑는다.

- search/naver/adapter: httpx + 오픈API + 키 로테이션(429/403 순환), .env 키 로드
- search/naver/transform: 순수 변환(태그/엔티티 정리, lprice). 가격비교(catalog) lprice 는
  '여러 판매자 중 최저가'라 최저가 솔루션엔 핵심 → 유지
- handler: asyncio.gather 동시 검색 + 소스별 실패 격리(일부 죽어도 결과) + 전체 실패 시 잡 실패
- worker_main: adapters={coupang, naver}
- tests: 네이버 변환 + 병합/실패격리/전체실패 4건 → 전체 31/31
- 라이브: 쿠팡30+네이버30 병합 top-N 최저가(소스 라벨 포함)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 08:38:15 +09:00
민헌andClaude Opus 4.8 7491bbecd9 chore(lps): .env 에서 Azure OpenAI 제거 — OpenAI 단일 방식
Azure OpenAI 는 사용하지 않기로 하여 슬롯 제거. AI 는 OPENAI_API_KEY 로 통일.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 17:31:16 +09:00
민헌andClaude Opus 4.8 c4b8692f3a chore(lps): 시크릿용 .env 도입 — API 키(NAVER/OpenAI/Azure) 주입 경로
키는 코드/커밋이 아닌 환경변수로 주입한다(감사: 시크릿 하드코딩 금지).
config.local.toml=비-시크릿 설정, .env=시크릿으로 분리.

- .env.example(템플릿, 커밋) + .env(로컬, 미추적)로 키 슬롯 제공
  · NAVER_CLIENT_ID/SECRET(+로테이션 _2..), OPENAI_API_KEY, AZURE_OPENAI_*
- server_configs 가 기동 시 lps/.env 를 load_dotenv 로 환경변수 주입
- requirements: python-dotenv 추가
- README: .env 셋업 단계 안내

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 17:14:34 +09:00
민헌andClaude Opus 4.8 fb72ab625f feat(lps): 코어 파이프라인 — mall 필터·IQR 이상치·top-N 최저가
검색 결과를 실제 최저가로 정제하는 파이프라인을 핸들러에 결합한다.
검색→필터→이상치→정렬→top-N. AI 유사도 판정 슬롯은 비워둠(키 대기).

- pipeline/filters: keep_only_mall·filter_out_malls·filter_by_price_band(요청 현재가 기준 targeted 컷)
- pipeline/outliers: IQR 기반 이상치 제거(z-score 대신 — 분포 가정 없음, stdlib만)
- pipeline/core: STAGE in/out 관측 로깅 + top-N 최저가(레퍼런스 pipeline_log 계승)
- handler: 검색→run_price_pipeline 결합, 요청 price 를 밴드 기준으로 사용
- tests: 정렬/IQR(극단 저·고가 제거)/밴드/mall/빈입력/STAGE/실 fixture 7건 → 전체 27/27
- 라이브 확인: 스탠리 텀블러 40건→top-5 최저가, STAGE 카운트 노출

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 17:06:15 +09:00
민헌andClaude Opus 4.8 abcb58ba05 feat(lps): 워커 루프 + LISTEN/NOTIFY — 큐 소비 파이프라인 가동
큐를 실제로 돌린다: 적재 → 워커 claim → 핸들러 실행 → 결과 저장 → DONE.
API(적재)와 워커(소비)를 분리 프로세스로(코드베이스 공유, 독립 스케일).

- worker/notify: 전용 asyncpg LISTEN 리스너. enqueue 에서 pg_notify → 유휴 워커 즉시 기상(폴링 제거)
- worker/runner: Worker(claim→처리, 처리중 heartbeat 로 lease 갱신, complete/fail) + run_reaper
- worker/handlers: job_type 별 핸들러(주입식). SEARCH=소스 어댑터 검색→정규화 결과
- worker_main: API 분리 워커 진입점(브라우저 무거워 기본 동시성 1)
- job_crud.enqueue: 삽입 시 pg_notify (중복 스킵 시엔 미발생)
- tests: drain→DONE·실패→재시도→dead·reaper 회수 후 재처리·NOTIFY 기상 4건 (전체 20/20)
- 라이브 E2E 확인: 적재→워커가 실제 쿠팡 검색(8건)→DONE

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 16:58:58 +09:00
민헌andClaude Opus 4.8 bebb6a71e6 feat(lps): 검색 API 라우터 — 요청 적재(enqueue) + 상태/큐 통계 조회
커머스 검색요청 계약을 프레임워크(protocol+service+RemoveNoneResponse)로 재구성.
실제 검색은 워커가 큐에서 꺼내 수행하도록 API 는 적재까지만 담당(비동기 분리).

- POST /v1/lps/search: 상품 리스트 → 상품별 SEARCH 잡 적재, product_code 로 활성 중복 방지, job_type→우선순위 매핑
- GET /v1/lps/jobs/{job_id}: 잡 상태/시도/결과 조회
- GET /v1/lps/queue/stats: 상태별 카운트(모니터링)
- protocol/lps_service 추가, job_crud.get() 단건조회, enums LPS_JOB_NOT_FOUND
- tests: 적재/중복/상태/미존재/통계 5건 (ASGI 클라이언트 + 실 lps_db) → 전체 16/16

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 16:49:28 +09:00
민헌andClaude Opus 4.8 da9bd7750c feat(lps): 작업 큐 엔진 — PostgreSQL 원자적 claim + lease + dead-letter
레퍼런스의 DB-큐 반면교사를 전부 뒤집는 큐 엔진을 구축한다.
 - 원자적 claim: FOR UPDATE SKIP LOCKED 서브쿼리 + 같은 UPDATE + RETURNING
   → 워커 다수여도 이중 할당 원천 불가(fetch/claim 미분리)
 - 모든 전이는 조건부 CAS(status/worker_id 가드) + RETURNING
 - 복구는 timeout 추측이 아닌 lease 만료 소유권 기반(reaper 회수)
 - 재시도 지수백오프 + max_attempts + dead-letter 를 큐에 내장(스크립트 난립 제거)
 - dedupe_key 부분 유니크로 활성 중복 차단, counts()로 관측(수동 psql 대체)

- enums: JobStatus(PENDING/RUNNING/DONE/DEAD)·JobType(SEARCH/OUTBOX)
- models: job 테이블(무FK·SMALLINT코드·TIMESTAMPTZ, claim/lease/dedupe 인덱스)
- crud/job_crud: JobQueue(enqueue/claim/complete/fail/renew_lease/reap/counts)
- tests: 동시 8워커 이중할당0·lease회수·재시도→dead·소유권가드 등 8건(실 lps_db)

부수: 포트 9400→9600 (negodata 9400 충돌 회피)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 16:37:32 +09:00
민헌andClaude Opus 4.8 e27b73c018 feat(lps): 쿠팡 검색 어댑터 — Akamai 우회(Patchright) + 정규화 파서
소스 어댑터 패턴으로 크롤링을 시작한다. 쿠팡은 Akamai Bot Manager 의
JS 행동 챌린지라 curl_cffi 단독 불가 → Patchright(스텔스 Playwright) +
실제 Chrome(channel=chrome)으로 챌린지를 통과하고 selectolax 로 파싱한다.

- contract: SearchAdapter(ABC)·NormalizedProduct·AdapterHealth·AdapterError
- coupang: adapter(브라우저 재사용, 챌린지 1회)·parser(순수)·selectors(외부화, webpack 해시 prefix 매칭)
- 공용: rate_limiter(2~8s 랜덤)·proxy(무프록시 off 인터페이스)·util.parse_price
- 가격 파싱: 단위가격 '(1개당 44,400원)'의 앞 '1' 오인 방지 — '원' 앞 숫자 앵커링
- deps: curl_cffi·selectolax·patchright(nodriver 는 py3.14 버그로 대체)
- tests: 파서 회귀(소형 fixture) — 라이브 2회 검색 + 파서 3/3 통과

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 15:59:48 +09:00
민헌andClaude Opus 4.8 11a7be7154 feat(lps): 인터넷 최저가 검색 솔루션 프레임워크 골격 추가
backend 와 동일한 프레임워크로 lps/ 폴더를 신설한다. 구체적인 도메인
로직(크롤링/오픈API/최저가 산정)은 미정이라 골격만 구성한다.

- FastAPI 부트스트랩(web_main/router) + lifespan·CORS·gzip·로그 미들웨어 + /healthz
- TOML 설정 로더(APP_ENV) + pydantic config + DB env override
- DB 세션 매니저(논리 DB × R/W, service→람다 위임) — 엔진 lazy 라 DB 없이도 부팅
- 공통 응답 규약(gmodel) + ErrorType/DBType/DBWRType
- router→services→crud 계층 컨벤션(services/crud 는 빈 폴더로 자리만)
- 포트 9400(backend 9300·agent 9500 회피), Dockerfile/run_local_server.sh/README
- tests/test_health.py 스모크(healthz, DB 없이 통과)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 15:18:27 +09:00
609 changed files with 43999 additions and 4466 deletions

No files matched your search

+7
View File
@@ -24,3 +24,10 @@ CLAUDE.md
# OS
.DS_Store
# 로컬 리서치 노트(크롤링 라이브러리·안티스크래핑 조사) — 추적 안 함, 로컬 참고용
/Temp.md
/new.md
/mobile.mov
.gstack/
+165 -25
View File
@@ -1,63 +1,198 @@
# O2O Negosium
동일 구조의 두 서비스(**negosium**, **negodata**)가 **하나의 PostgreSQL 인스턴스**를 공유한다.
AI 협상 솔루션. 여러 백엔드·프론트·배치가 **하나의 PostgreSQL 인스턴스**를 공유하고,
전부 `docker compose` 하나로 뜬다. (인터넷 최저가 검색 LPS 만 별도 DB `lps_db` 사용.)
## 서비스 소개
구매기업(바이어)이 협력사(공급사)와 벌이는 **가격 협상을 AI 봇이 대신 수행**하는 B2B 협상 자동화 솔루션이다.
바이어가 상품·목표가·기간만 정해 견적을 열면, 각 협력사와의 1:1 협상은 강화학습 기반 에이전트가
**협상 카드로 밀당**하며 진행하고, 마감 시각에 최저 투찰가를 기준으로 자동 **낙찰/개찰**을 판정한다.
크게 세 축 + 부속으로 나뉜다.
| 축 | 구성요소 | 역할 |
|---|---|---|
| **바이어 측** | negodata (backend + front) | 어드민. 상품·협력사 관리, 견적 생성, 마감·낙찰 관리 |
| **공급사 측** | negosium (backend + frontend) | 협력사 포털. 초청받은 협상 챗에 참여해 가격 제시 |
| **협상 엔진** | agent | 실제 AI 협상 봇. 앵커링가·협상 카드로 자동 협상 (강화학습) |
| 부속 | lps · anchoring · landing | 인터넷 최저가(목표가 재료) · 앵커값 자동 조정 배치 · 솔루션 소개 랜딩 |
## 구성
```
o2o-negosium/
├── docker-compose.yml # 두 backend (DB 는 외부)
├── postgres-init/ # DB·테이블 셋업 SQL (대상 DB 에 1회 적용)
├── backend/ # negosium 백엔드 (포트 9300)
├── negodata/backend/ # negodata 백엔드 (포트 9400)
├── agent/ front/ # (예정)
└── negodata/front/ # (예정)
├── docker-compose.yml # 전체 서비스 (DB 는 compose 밖, config 로 외부 연결)
├── postgres-init/ # DB·스키마·시드 SQL (대상 DB 에 1회 적용)
│
├── backend/ # negosium 백엔드 — 공급사/협상 API (:9300)
├── frontend/ # negosium 공급사 프론트 (:3300, 프로덕션 빌드 정적 서빙)
├── agent/ # 협상 에이전트 — RL(learning 스키마) (:9500)
│
├── negodata/backend/ # negodata 백엔드 — 바이어/어드민 API (:9400)
├── negodata/front/ # negodata 어드민 프론트 (Vite, :3000)
│
├── landing/ # 솔루션 랜딩페이지 (react-router SSG, :3100)
│
├── lps/ # 인터넷 최저가 검색: lps-api(:9600) + lps-worker(크롤)
├── lps-admin/ # LPS 관리자 UI (nginx → lps-api 프록시, :3400)
│
└── schedules/anchoring/ # 앵커링 값 자동 조정 배치 (포트 없음, 상주 스케줄러 + Redis)
```
두 백엔드는 같은 코드 골격(MVC · 람다 DB · Depends 주입 · JWT 로그인)을 쓴다.
아키텍처/패턴 상세는 각 서버 README 참고: [backend](backend/README.md) · [negodata/backend](negodata/backend/README.md)
negosium·negodata·agent 백엔드는 같은 코드 골격(MVC · 람다 DB · Depends 주입 · JWT 로그인)을 쓴다.
아키텍처/패턴 상세는 각 서브 README 참고:
- 백엔드: [backend](backend/README.md) · [negodata/backend](negodata/backend/README.md) · [agent](agent/README.md) · [lps](lps/README.md)
- 프론트: [frontend](frontend/README.md) · [negodata/front](negodata/front/README.md)
- 배치: [schedules/anchoring](schedules/anchoring/README.md) · 관리자 UI: [lps-admin](lps-admin/README.md)
### 서비스 / 포트
| 서비스 | 주소 | 역할 | DB |
|---|---|---|---|
| negosium-backend | http://localhost:9300/docs | 공급사·협상 API | negosium_db |
| negosium-front | http://localhost:3300 | 공급사 프론트 | — |
| agent | http://localhost:9500/docs | 협상 에이전트(RL) | negosium_db (learning) |
| negodata-backend | http://localhost:9400/docs | 바이어·어드민 API | negosium_db |
| negodata-front | http://localhost:3000 | 어드민 프론트 | — |
| landing | http://localhost:3100 | 솔루션 랜딩 | — |
| lps-api | http://localhost:9600/docs | 최저가 검색 접수/조회 | lps_db |
| lps-worker | 포트 없음 | 크롤 워커(헤드풀 Chromium) | lps_db |
| lps-admin | http://localhost:3400 | LPS 관리자 UI | — |
| anchoring | 포트 없음 | 앵커링 조정 배치(격주 토 00:00 KST) | negosium_db (anchoring) |
| anchoring-redis | 127.0.0.1:6380 | anchoring 조회 캐시 | — |
| autoheal | — | unhealthy 컨테이너 자동 재시작 | — |
### DB 는 compose 밖 (config 로 연결)
DB 는 docker-compose 에서 관리하지 않는다. 각 backend 는 `config.<APP_ENV>.toml` 의 접속 정보대로
**외부 PostgreSQL**(호스트 로컬 postgres, 또는 따로 떠 있는 docker postgres)에 연결한다.
한 PostgreSQL 안에 서비스별 database 를 둔다.
한 PostgreSQL 인스턴스 안에 **단일 `negosium_db`** 를 두고 도메인별 **schema** 로 묶는다.
LPS 만 별도 database(`lps_db`) 를 쓴다.
```
PostgreSQL (외부, 5432)
├── negosium_db ← negosium-backend
└── negodata_db ← negodata-backend
├── negosium_db ← negosium-backend · negodata-backend · agent · anchoring 공유
│ ├── company / supplier / partner : 회사·유저·협력사·상품
│ ├── card / quotation / negotiation: 협상 카드·견적·협상 세션
│ ├── learning : RL 자산 (agent 소유)
│ └── anchoring : 앵커링 조정 (schedules/anchoring 소유)
└── lps_db ← lps-api · lps-worker
```
- 컨테이너(docker env)에서 호스트 DB 접근: `host.docker.internal:5432` (`config.docker.toml`)
- 컨테이너(docker env)에서 호스트 DB 접근: `host.docker.internal:5432` (compose 가 `DB_HOST` 로 override)
- 로컬 실행/테스트(local·test env): `127.0.0.1:5432` (`config.local/test.toml`)
- 계정/database 명은 config 에 맞춘다 (기본 `postgres` / `password`).
| 서비스 | 서버 | docs | database |
|---|---|---|---|
| negosium-backend | http://localhost:9300 | /docs | negosium_db |
| negodata-backend | http://localhost:9400 | /docs | negodata_db |
## 핵심 플로우
### 1. 견적 라이프사이클 (전체 개요)
바이어가 견적을 열고 → 협력사가 협상에 참여 → 마감 시각에 판정되는 큰 흐름.
견적 유형은 두 축(재/신규 × 협상 1:1 / 견적 1:N)으로 4종.
```mermaid
flowchart TD
A["바이어: 상품·협력사·기간 선택<br/>견적 유형 4종 + 낙찰 기준(mid/over_action) 설정"] --> B["목표가·앵커링가 산정<br/>(MD제시가 → 인터넷최저가/매입가/판매가)"]
B --> C["협력사 초청 (이메일)"]
C --> D{"견적 유형"}
D -->|"협상 1:1 (재협상·신규협상)"| E["AI 봇 밀당 협상<br/>(협상 카드 사용)"]
D -->|"견적 1:N (재견적·신규견적)"| F["정형 흐름<br/>(배송형태·추가할인 확인)"]
E --> G["세션별 투찰가 확정<br/>(협상완료) 또는 실패"]
F --> G
G --> H{"마감 트리거<br/>①마감시각 ②전세션종결 ③수동"}
H --> I["마감 판정<br/>(최저 투찰가 기준)"]
I --> J["낙찰 (승자 1)"]
I --> K["개찰 (낙찰자 미정)"]
```
### 2. 1:1 협상 봇 판정 (agent)
협력사가 가격을 제시할 때마다 봇이 **앵커링가** 기준으로 판정한다.
재제안은 카드를 한 장씩 쓰며 **최대 3번**, 카드 소진·3번 초과에도 앵커 밑으로 못 내리면 실패(투찰 없음).
```mermaid
flowchart TD
P["협력사 가격 제시"] --> Q{"제시가 vs 앵커링가"}
Q -->|"≤ 앵커링가"| R["협상완료 — 투찰 확정"]
Q -->|"앵커 ~ 앵커×1.02"| S["와일드카드: 1% 인하 요청<br/>(세션당 1회)"]
Q -->|"앵커×1.02 초과"| T["협상 카드로 재제안"]
S --> U{"재제안 횟수 ≤ 3?<br/>카드 남음?"}
T --> U
U -->|"예"| P
U -->|"아니오 (소진·3번 초과)"| V["협상 실패 — 낙찰 후보 아님"]
```
### 3. 마감 판정
마감 시 **협상완료 세션의 최저 투찰가**를 본다. 공통 전제: 완료 세션이 없거나(전원 미응찰·협상거부)
동가 최저가 2곳 이상이면 유형과 무관하게 **개찰**. 그 외 단독 최저가일 때만 낙찰 후보가 되며,
이후 판정이 유형별로 갈린다.
#### 3-1. 견적 1:N — 단독 최저면 무조건 낙찰
가격 구간을 보지 않는다. 생성 시 `mid/over_action`이 낙찰(AWARD)로 강제되기 때문.
```mermaid
flowchart TD
M1["마감: 협상완료 세션 최저 투찰가"] --> N1{"완료 세션 있나?"}
N1 -->|"없음 (전원 미응찰·협상거부)"| O1["개찰"]
N1 -->|"동가 최저 2곳+"| O1
N1 -->|"단독 최저"| X1["낙찰 (가격 구간 무관, 무조건)"]
```
#### 3-2. 협상 1:1 — 가격 구간별, 생성 때 정한 값 적용
앵커링가 이하는 무조건 낙찰. 그 위 구간은 **견적 생성 때 미리 정해둔 값**(`mid_action`/`over_action`,
1=낙찰·2=개찰)을 마감 시 그대로 적용한다. 두 필드는 적용 구간만 다를 뿐 동작은 동일.
```mermaid
flowchart TD
M2["마감: 협상완료 세션 최저 투찰가"] --> N2{"완료 세션 있나?"}
N2 -->|"없음 (전원 미응찰·협상거부)"| O2["개찰"]
N2 -->|"동가 최저 2곳+"| O2
N2 -->|"단독 최저"| W2{"투찰가 위치"}
W2 -->|"≤ 앵커링가"| X2["낙찰"]
W2 -->|"앵커 ~ 목표가"| Y2["생성 시 정한 mid_action 적용<br/>(1=낙찰 / 2=개찰)"]
W2 -->|"목표가 초과"| Z2["생성 시 정한 over_action 적용<br/>(1=낙찰 / 2=개찰)"]
```
> 개찰 = 낙찰자 미정 마감(결렬 아님). 개찰 후 수동 처리로 **직접 낙찰 확정**(`/v1/quotation/award`)
> 또는 **재견적 재생성**(`/v1/quotation/regenerate`)이 있다.
> 비즈니스 로직 정본은 [negodata/docs/business-logic.md](negodata/docs/business-logic.md).
## 빠른 시작
```bash
# 1) DB 준비 (최초 1회) — 사용할 PostgreSQL 에 스키마 + 시드 적용
psql -h 127.0.0.1 -p 5432 -U postgres -f postgres-init/00-init.sql # 스키마 전체 (negosium_db + 도메인·learning·anchoring schema)
psql -h 127.0.0.1 -p 5432 -U postgres -f postgres-init/temp-data.sql # 임시 데이터 시드 (admin / admin1234)
# 스키마 DDL (구 01~05 통합, 전부 IF NOT EXISTS 라 재실행 안전)
psql -h 127.0.0.1 -p 5432 -U postgres -d negosium_db -f postgres-init/init-data/init.sql
# 로컬/개발 시드 (admin / admin1234, 회사·유저·협상 카드)
psql -h 127.0.0.1 -p 5432 -U postgres -d negosium_db -f postgres-init/init-data/init-data.sql
# 2) 백엔드 기동
docker compose up -d # 두 backend (DB 는 config 대로 외부 연결)
docker compose logs -f
# (DBeaver 로 처음부터 새로 깔 때는 postgres-init/dbeaver/ 의 0~5 순서 스크립트를 쓴다:
# 0 drop&create → 1 스키마 → 2 시드 → 3 lps_db → 4 카드 리셋 → 5 o2o OWNER 유저)
# 2) 전체 기동
docker compose up -d
docker compose logs -f # 컨테이너별 로그는 ./logs.sh 메뉴로도 확인
docker compose down
```
> 스키마 변경 보정은 `postgres-init/alters/` 의 날짜별 SQL 을 대상 DB 에 수동 적용한다
> (postgres-init 은 DB 최초 생성 때만 자동 실행되므로, 기존 DB 엔 alter 를 직접 돌려야 새 컬럼이 반영된다).
## 테스트
```bash
# config.test.toml 의 PostgreSQL(기본 127.0.0.1:5432) 이 떠 있어야 한다
cd backend # 또는 negodata/backend
cd backend # 또는 negodata/backend, agent, lps ...
pip install pytest pytest-asyncio httpx
python -m pytest
```
- httpx `ASGITransport` 로 네트워크 없이 앱을 직접 호출하는 e2e (각 5개).
- httpx `ASGITransport` 로 네트워크 없이 앱을 직접 호출하는 e2e.
- `DB_SESSION_MNG` 싱글톤의 커넥션 풀이 첫 이벤트 루프에 묶이므로, 모든 테스트가 단일 session 루프를 공유한다(`pytest.ini`).
- ⚠️ 테스트는 `APP_ENV=test` 로 격리한다(테스트 DB). dev DB(`negosium_db`)에 대고 돌리면 데이터가 날아간다.
## 성능 / 벤치마크
@@ -99,4 +234,9 @@ python -m locust -f loadtest/locustfile.py --host http://localhost:9300 --headle
```
## 기술 스택
FastAPI · SQLAlchemy(async) · asyncpg · PostgreSQL 16 · python-jose(JWT) · bcrypt · uvicorn · Docker Compose
- **백엔드**: FastAPI · SQLAlchemy(async) · asyncpg · PostgreSQL 16 · python-jose(JWT) · bcrypt · uvicorn
- **프론트**: React · react-router v7 · Vite · TanStack Query (negosium-front 는 프로덕션 빌드 정적 서빙)
- **에이전트**: 강화학습(Q-learning, learning 스키마) · OpenAI
- **LPS**: 헤드풀 Chromium + Patchright(스텔스 Playwright 포크, 크롤) · autoheal
- **배치**: Redis(anchoring 캐시) · 상주 스케줄러
- **공통**: Docker Compose
+1 -1
View File
@@ -114,7 +114,7 @@ def compute_counter(spec: TacticSpec, context: Dict[str, Any]) -> Optional[int]:
if counter <= 0:
return None
counter = min(counter, target) # 목표가 초과 제시 금지 (가드레일)
counter_i = int(round(counter))
counter_i = int(counter / 10 + 0.5) * 10 # 10원 단위 반올림 — 앵커가·목표가 산정과 표기 통일(IMK 요청)
if counter_i >= price:
return None # 제시가가 이미 카운터 이하 → 카운터 무의미
return counter_i
@@ -23,10 +23,18 @@ _SESSIONS = table(
"sessions",
column("session_id"), column("quotation_id"), column("item_id"), column("supplier_id"),
column("qt_type"), column("target_price"), column("anchoring_price"),
column("qt_setting_id"),
column("deleted"),
schema="negotiation",
)
_ITEMS = table("items", column("item_id"), column("name"), column("price"), column("deleted"), schema="partner")
# 견적 설정 — card_count(협상 내 협상카드 사용 횟수 상한) 조회용.
_QUOTATION_SETTINGS = table(
"quotation_settings",
column("qt_setting_id"), column("card_count"), column("deleted"),
schema="quotation",
)
_ITEMS = table("items", column("item_id"), column("name"), column("price"),
column("internet_lowest_price"), column("deleted"), schema="partner")
_SUPPLIERS = table("suppliers", column("supplier_id"), column("name"), column("total_revenue"), column("deleted"), schema="partner")
_QUOTATIONS = table(
"quotations",
@@ -72,6 +80,18 @@ class INegoContextCRUD(ABC):
"""품목 기준가(items.price). 없으면 0."""
pass
@abstractmethod
async def get_card_count(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[int]]:
"""협상카드 사용 횟수 상한(quotation_settings.card_count) — 세션의 qt_setting_id 로 조인.
설정이 없으면 None(호출부가 상한 미적용). 이 값이 협상 중 실제로 플레이 가능한 협상카드 수를 캡한다."""
pass
@abstractmethod
async def get_item_lowest_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
"""상품 인터넷 최저가(items.internet_lowest_price — LPS 수집 대표값). 미수집이면 0.
카드 스크립트 {internet_lowest_price} 치환용(NGC-008 등 시장가 인용 카드)."""
pass
@abstractmethod
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
"""협력사 총매출액(suppliers.total_revenue — KTC 미러). 없으면 0.0."""
@@ -141,6 +161,44 @@ class NegoContextCRUD(INegoContextCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def get_card_count(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[int]]:
try:
query = (
select(_QUOTATION_SETTINGS.c.card_count)
.select_from(
_SESSIONS.join(
_QUOTATION_SETTINGS,
_QUOTATION_SETTINGS.c.qt_setting_id == _SESSIONS.c.qt_setting_id,
)
)
.where(_SESSIONS.c.session_id == session_id,
_SESSIONS.c.deleted == False, # noqa: E712
_QUOTATION_SETTINGS.c.deleted == False) # noqa: E712
.limit(1)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_card_count failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows or rows[0] is None:
return err_type, None
return ErrorType.SUCCESS, int(rows[0])
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def get_item_lowest_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
try:
query = (
select(_ITEMS.c.internet_lowest_price)
.where(_ITEMS.c.item_id == item_id, _ITEMS.c.deleted == False) # noqa: E712
.limit(1)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_item_lowest_price failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
return err_type, 0
return ErrorType.SUCCESS, int(rows[0])
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
try:
query = (
+16 -2
View File
@@ -211,7 +211,7 @@ class ChatEngine:
# 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
# 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
ctx["wildcard_used"] = True
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가 (멘트 변수)
ctx["offer_1pct"] = int(price * 0.99 / 10 + 0.5) * 10 # 1% 인하가 (멘트 변수) — 10원 반올림(앵커·카운터와 통일)
ctx["pending_counter_price"] = ctx["offer_1pct"] # 수락 시 이 가격으로 타결
return "wild_card_1pct"
# 1.02 초과 ~ entry(1.05) 구간: 견적에서 선택한 와일드카드의 전술로 카운터 제시.
@@ -247,6 +247,12 @@ class ChatEngine:
out["product_name"] = str(ctx["product_name"])
if "offer_1pct" in ctx:
out["offer_1pct"] = int(ctx["offer_1pct"])
# 인터넷 최저가: LPS 대표값(items.internet_lowest_price). 카드는 {internet_lowest_price},
# 라벨 매핑(variable_mapping.json)은 internet_min_price 를 쓰므로 target/anchor 처럼 양쪽 이름 모두 채운다.
# 미수집(0/없음)이면 키를 만들지 않는다 — 원형 유지 → 허위 시장가 인용 방지(NGC-008 은 값 있을 때만 유효).
ilp = ctx.get("internet_lowest_price") or 0
if ilp > 0:
out["internet_lowest_price"] = out["internet_min_price"] = int(ilp)
# 전술 카운터 변수(카드 시드 멘트의 가격 변수) — tactics.compute_counter 산식과 동일 정의.
anchor = ctx.get("anchor_price") or 0
target = ctx.get("target_price") or 0
@@ -260,7 +266,15 @@ class ChatEngine:
if prev_customer and "input_price" in ctx:
out["middle_price"] = int(round((prev_customer + ctx["input_price"]) / 2))
if ctx.get("pending_counter_price"):
out["counter_price"] = int(ctx["pending_counter_price"])
# 카운터 제시 중: 멘트에 보이는 제시가와 수락 시 타결가(pending)를 반드시 일치시킨다.
# 절충/중간 변수(middle_price·target_mid_price)는 vars_for 재계산 값이 compute_counter 의
# target 클램프·prev_customer 갱신과 어긋나, 멘트엔 1,740,000 이 보이는데 실제로는
# 1,700,000 으로 타결되던 버그(표시가≠투찰가)가 있었다. pending 은 이 시점 유일한 '제안가'이므로
# 세 변수 모두 pending 으로 고정한다(카운터 제시 턴에만 적용 — 비-카운터 렌더는 원 계산값 유지).
pending_i = int(ctx["pending_counter_price"])
out["counter_price"] = pending_i
out["middle_price"] = pending_i
out["target_mid_price"] = pending_i
# 인하율 = (기존 공급가(상품단가) - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
# 제시가가 기존가보다 높으면(인상 제시) 음수가 나오는데, "-1.3% 인하된 금액" 같은
# 모순 표현이 되므로 discount_rate 는 0 미만 금지하고, 인상/동일/인하를 구분한
@@ -39,6 +39,7 @@ class NegotiationDbContext:
target_price: int # 목표 매입가(원) — sessions.target_price
anchor_price: int # 앵커링가 — sessions.anchoring_price(생성 시 박제). 없으면 target(무할인 폴백)
item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0
internet_lowest_price: int # 인터넷 최저가(items.internet_lowest_price, LPS 대표값) — 카드 {internet_lowest_price} 치환용. 미수집이면 0
partner_name: Optional[str] # 협력사명(suppliers.name) — 카드 {partner_name} 치환용. 없으면 None
product_name: Optional[str] # 상품명(items.name) — 카드 {product_name} 치환용. 없으면 None
partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE
@@ -46,6 +47,7 @@ class NegotiationDbContext:
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type. 미지정 시 None
selected_nego_card_numbers: list[str] # 견적 생성 시 선택된 일반 협상카드 번호(card.nego_cards.number)
selected_wild_card_numbers: list[str] # 견적 생성 시 선택된 와일드카드 번호(card.wild_cards.number)
card_count: Optional[int] # 협상카드 사용 횟수 상한(quotation_settings.card_count). None=상한 미적용
class NegotiationContextLoader:
@@ -86,6 +88,9 @@ class NegotiationContextLoader:
# 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시).
_, item_price = await self.crud.get_item_price(s, item_id)
# 인터넷 최저가(LPS 수집 대표값) — 없으면 0(시장가 인용 카드는 값 있을 때만 치환).
_, internet_lowest_price = await self.crud.get_item_lowest_price(s, item_id)
# 카드 스크립트 치환용 이름 — 협력사명/상품명. 없으면 None(호출부 기본값 폴백).
_, partner_name = await self.crud.get_supplier_name(s, supplier_id)
_, product_name = await self.crud.get_item_name(s, item_id)
@@ -103,11 +108,15 @@ class NegotiationContextLoader:
_, selected_cards = await self.crud.get_quotation_card_numbers(s, quotation_id)
selected_nego_cards, selected_wild_cards = selected_cards
# 협상카드 사용 횟수 상한(견적 설정). 없으면 None → 상한 미적용(선택 카드 수로만 캡).
_, card_count = await self.crud.get_card_count(s, sid)
return NegotiationDbContext(
rq_type="재협상" if int(qt_type) in _ONE_TO_ONE_QT_TYPES else "재견적",
target_price=target,
anchor_price=anchor,
item_price=item_price,
internet_lowest_price=internet_lowest_price,
partner_name=partner_name,
product_name=product_name,
partner_type=PartnerType.from_count(supplier_count),
@@ -115,6 +124,7 @@ class NegotiationContextLoader:
distribution_code=_SUPPLIER_TYPE_TO_CODE.get(supplier_type) if supplier_type else None,
selected_nego_card_numbers=selected_nego_cards,
selected_wild_card_numbers=selected_wild_cards,
card_count=card_count,
)
try:
+8 -1
View File
@@ -82,8 +82,12 @@ class ChatService:
selected_wild_cards = db_ctx.selected_wild_card_numbers if db_ctx else []
# 운영 DB 세션은 견적 version_id 에 묶인 카드만 사용한다. 직접 호출/데모(DB context 없음)는
# 기존 테넌트 기본 action mapping 으로 폴백해 로컬 테스트와 콘솔 데모를 유지한다.
# 협상카드 사용 횟수 상한(quotation_settings.card_count)으로 실제 플레이 가능한 카드 수를 캡한다 —
# session.action_space_size 는 카드 소진 판정(cards_total) 전용이라 여기서 줄여도 Q-table 은
# engine.action_space_size(카탈로그 전체)로 별도 고정된다. card_count 미설정(None)이면 선택 수 그대로.
card_cap = db_ctx.card_count if (db_ctx and db_ctx.card_count and db_ctx.card_count > 0) else None
action_space_size = (
min(len(selected_nego_cards), engine.action_space_size)
min(len(selected_nego_cards), engine.action_space_size, *( [card_cap] if card_cap else [] ))
if db_ctx is not None
else engine.action_space_size
)
@@ -110,6 +114,9 @@ class ChatService:
"round": 0,
# 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용.
"item_price": db_ctx.item_price if db_ctx else 0,
# 인터넷 최저가(items.internet_lowest_price, LPS 대표값) — 카드 {internet_lowest_price} 치환용.
# 미수집(0)이면 vars_for 가 키를 만들지 않아 원형 유지(허위 시장가 표기 방지).
"internet_lowest_price": db_ctx.internet_lowest_price if db_ctx else 0,
# 견적 생성 시 선택한 카드. 일반카드는 action_id 0..N-1 에 그대로 매핑한다.
# 1% 인하는 기본 와일드카드로 항상 열고, 재원부족 등 선택형 와일드카드는
# 선택된 와일드카드가 있을 때만 허용한다.
+17 -9
View File
@@ -47,8 +47,8 @@ def test_counter_formulas_and_clamp():
assert compute_counter(tactic_for("WC-05"), ctx) == 10000
# 갑 직전 포지션이 있으면 그 기준: (9800+11000)/2 = 10400 → 역시 클램프 10000
assert compute_counter(tactic_for("WC-05"), dict(ctx, prev_customer_price=9800)) == 10000
# 클램프 미발동 구간: (9900+10050)/2 = 9975 ≤ target
assert compute_counter(tactic_for("WC-05"), dict(ctx, input_price=10050)) == 9975
# 클램프 미발동 구간: (9900+10050)/2 = 9975 ≤ target → 10원 단위 반올림 9980
assert compute_counter(tactic_for("WC-05"), dict(ctx, input_price=10050)) == 9980
def test_counter_meaningless_degrades_to_hold():
@@ -169,13 +169,21 @@ def test_price_confirm_script_renders_raise_correctly():
# ---- vars_for 전술 변수 치환 ---------------------------------------------------
def test_vars_for_supplies_tactic_variables():
eng = _engine()
s = _session(input_price=10300, prev_customer_price=10000, pending_counter_price=10100)
v = eng.vars_for(s)
assert v["prev_partner_price"] == 10300
assert v["prev_customer_price"] == 10000
assert v["target_mid_price"] == 10050 # (10000+10100)/2
assert v["middle_price"] == 10150 # (10000+10300)/2
assert v["counter_price"] == 10100
# 카운터 미제시(정보성): 절충/중간 변수는 원 계산값.
s0 = _session(input_price=10300, prev_customer_price=10000) # anchor=10000, target=10100 (기본)
v0 = eng.vars_for(s0)
assert v0["prev_partner_price"] == 10300
assert v0["prev_customer_price"] == 10000
assert v0["target_mid_price"] == 10050 # (anchor 10000 + target 10100)/2
assert v0["middle_price"] == 10150 # (prev_customer 10000 + input 10300)/2
# 카운터 제시 중: 표시 제시가(middle/target_mid/counter) == 타결가(pending) 로 고정.
# 회귀(표시가≠투찰가): 예전엔 middle_price 가 재계산값 10150 을 표시하면서 10100 으로 타결됐다.
s1 = _session(input_price=10300, prev_customer_price=10000, pending_counter_price=10100)
v1 = eng.vars_for(s1)
assert v1["counter_price"] == 10100
assert v1["middle_price"] == 10100 # 재계산 10150 이 아니라 pending
assert v1["target_mid_price"] == 10100
# ---- ⑤⑥ E2E (실 DB — 견적 선택 카드 + 서비스 레이어) ---------------------------
+8
View File
@@ -192,6 +192,12 @@ async def test_loader_with_crud_double(db_engine):
async def get_item_price(self, cdb, item_id):
return ErrorType.SUCCESS, 7000
async def get_item_lowest_price(self, cdb, item_id):
return ErrorType.SUCCESS, 6300 # 인터넷 최저가(items.internet_lowest_price)
async def get_card_count(self, cdb, session_id):
return ErrorType.SUCCESS, 3 # 협상카드 사용 횟수 상한(quotation_settings.card_count)
async def get_supplier_total_revenue(self, cdb, supplier_id):
return ErrorType.SUCCESS, 12_000_000.0
@@ -219,6 +225,8 @@ async def test_loader_with_crud_double(db_engine):
assert ctx.target_price == 50000
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
assert ctx.item_price == 7000
assert ctx.internet_lowest_price == 6300 # 인터넷 최저가 로드 확인
assert ctx.card_count == 3 # 협상카드 사용 횟수 상한 로드 확인
assert ctx.partner_name == "테스트협력사"
assert ctx.product_name == "테스트상품"
assert ctx.revenue_amount == 12_000_000.0
+25
View File
@@ -162,6 +162,31 @@ def test_card_id_fixed_mapping_and_selection_mask():
assert ChatService._selection_mask(eng, session) is None
def test_counter_display_price_equals_settlement():
"""회귀(표시가≠투찰가): 카운터 제시 중 멘트에 보이는 절충/중간 변수
(middle_price·target_mid_price)는 수락 시 타결가(pending_counter_price)와 정확히 일치해야 한다.
버그: WC-05(중간값 절충)에서 compute_counter 는 target 클램프·prev_customer 갱신으로 1,700,000 을
pending 으로 적재하는데, vars_for 가 {middle_price} 를 재계산해 1,740,000 으로 표시 → 화면엔
1,740,000 인데 실제로는 1,700,000 으로 투찰되던 문제. pending 으로 고정해 표시가==타결가."""
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
repo = ScriptRepository(cfg, _TENANTS_DIR)
engine = ChatEngine(repo, rq_type="재협상")
session = ChatSession(
session_id="00000000-0000-0000-0000-000000000009",
tenant_id="imarketkorea", company_id="imarketkorea", action_space_size=0,
context={
"anchor_price": 2000000, "target_price": 1700000, "input_price": 1780000,
"prev_customer_price": 1700000, # 종결 전술이 counter 로 덮어쓴 상태
"pending_counter_price": 1700000, # compute_counter 의 target 클램프 결과(실제 타결가)
},
)
v = engine.vars_for(session)
assert v["counter_price"] == 1700000
assert v["middle_price"] == 1700000 # 재계산값 1,740,000 이 아니라 pending
assert v["target_mid_price"] == 1700000
def test_default_1pct_wildcard_still_runs_without_selected_wildcard():
"""1% 인하는 기본 제공 카드라 DB 견적에서 와일드카드를 선택하지 않아도 발동한다."""
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
+67
View File
@@ -58,6 +58,21 @@ class suppliers(MAIN_BASE):
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
class companies(MAIN_BASE):
# company.companies (고객사). 공급사 포털 브랜딩(settings.branding) 조회 전용 미러.
@staticmethod
def DBType():
return DBType.PARTNER.value
__tablename__ = "companies"
__table_args__ = {"schema": "company"}
company_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")) # 회사 식별자(PK)
name = Column(String(100), nullable=False) # 회사명
settings = Column(JSONB, nullable=True) # 회사별 커스터마이징(branding/labels 등, negodata 소유)
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
class items(MAIN_BASE):
# partner.items (상품).
@staticmethod
@@ -123,6 +138,7 @@ class sessions(MAIN_BASE):
reject_reason = Column(String(255), nullable=True) # 거절 사유
reject_price = Column(BigInteger, nullable=True) # 거절 시 제시가(원)
reject_delivery_type = Column(SmallInteger, nullable=True) # 거절 시 배송 유형 (코드)
custom = Column(JSONB, nullable=True) # 협상완료 부가정보 값 {key: value} (정의는 companies.settings.session_fields)
created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC)
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')"), onupdate=text("(now() AT TIME ZONE 'utc')")) # 수정 시각(UTC, UPDATE 시 자동 갱신)
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
@@ -157,6 +173,7 @@ class quotations(MAIN_BASE):
preferred_sp_yn = Column(Boolean, nullable=True) # 선호 공급사 지정 여부
preferred_sp_id = Column(UUID(as_uuid=True), nullable=True) # 선호 공급사(partner.suppliers.supplier_id)
preferred_sp_name = Column(String(20), nullable=True) # 선호 공급사명(스냅샷)
close_reason = Column(SmallInteger, nullable=True) # 마감 사유(CloseReason). 재협상 요청 자격 판정에 읽는다
equal_bid_yn = Column(Boolean, nullable=True) # 동일가 입찰 발생 여부
equal_bid_data = Column(JSONB, nullable=True) # 동일가 입찰 상세(JSON)
created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC)
@@ -164,6 +181,28 @@ class quotations(MAIN_BASE):
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
class notifications(MAIN_BASE):
# company.notifications (담당자 인박스). 포털은 재협상 요청 알림을 만들기 위해서만 쓴다(조회는 negodata).
# company 스키마 전용 DBType 이 없어 USER 커넥션을 재사용한다(물리 DB 동일).
@staticmethod
def DBType():
return DBType.USER.value
__tablename__ = "notifications"
__table_args__ = {"schema": "company"}
notification_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
user_id = Column(UUID(as_uuid=True), nullable=False) # 수신자(company.users.user_id) = 견적 작성자
type = Column(SmallInteger, nullable=False) # NotificationType
ref_qt_id = Column(UUID(as_uuid=True), nullable=True)
ref_session_id = Column(UUID(as_uuid=True), nullable=True)
data = Column(JSONB, nullable=True) # 렌더 스냅샷(공급사명·사유·희망가 등)
read_at = Column(DateTime(timezone=True), nullable=True)
created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')"))
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')"), onupdate=text("(now() AT TIME ZONE 'utc')"))
deleted = Column(Boolean, nullable=False, server_default=text("false"))
class quotation_settings(MAIN_BASE):
# quotation.quotation_settings (견적 설정). 견적 설정 스냅샷 — anchoring_value 는 구(舊) 앵커 산출용으로 채팅 경로에서는 더 이상 사용하지 않음(앵커는 sessions.anchoring_price 박제값).
@staticmethod
@@ -183,6 +222,34 @@ class quotation_settings(MAIN_BASE):
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
class nego_cards(MAIN_BASE):
# card.nego_cards (협상카드). backend 는 번호→UUID 변환(chats.card_id 저장)만 위해 최소 컬럼 미러.
@staticmethod
def DBType():
return DBType.NEGOTIATION.value # 같은 negosium_db — chats 와 동일 세션풀로 조회
__tablename__ = "nego_cards"
__table_args__ = {"schema": "card"}
nego_card_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
number = Column(String(10), nullable=True) # 카드 번호(agent turn.card_id 와 매칭)
deleted = Column(Boolean, nullable=False, server_default=text("false"))
class wild_cards(MAIN_BASE):
# card.wild_cards (와일드카드). backend 는 번호→UUID 변환(chats.card_id 저장)만 위해 최소 컬럼 미러.
@staticmethod
def DBType():
return DBType.NEGOTIATION.value # 같은 negosium_db
__tablename__ = "wild_cards"
__table_args__ = {"schema": "card"}
wild_card_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
number = Column(String(10), nullable=True)
deleted = Column(Boolean, nullable=False, server_default=text("false"))
class chats(MAIN_BASE):
# negotiation.chats (협상 채팅 메시지 로그). session 1 : N chats. (session_id, seq) 유니크.
@staticmethod
+35
View File
@@ -130,6 +130,41 @@ class QuotationStatus(Enum):
CLOSED = 3 # 견적마감
class CloseReason(Enum):
"""견적 마감 사유. quotation.quotations.close_reason
낙찰(AWARDED) 외 OPEN_* 는 낙찰자 미정으로 마감된 '결렬' 건 — 공급사 재협상 요청 대상."""
AWARDED = 1 # 낙찰
OPEN_PRICE = 5 # 개찰: 낙찰 기준 미달
OPEN_EQUAL = 6 # 개찰: 동가
OPEN_NOSHOW = 7 # 개찰: 전원 미응찰
OPEN_REJECT = 8 # 개찰: 협상거부 존재
# 재협상 요청 가능한 마감 사유(낙찰 건은 제외).
RENEGOTIABLE_CLOSE_REASONS = (
CloseReason.OPEN_PRICE.value,
CloseReason.OPEN_EQUAL.value,
CloseReason.OPEN_NOSHOW.value,
CloseReason.OPEN_REJECT.value,
)
class RenegotiationStatus(Enum):
"""sessions.custom.renegotiation.status — 공급사 재협상 요청 상태(IMK #15)."""
PENDING = 1 # 접수, 담당자 심사 대기
APPROVED = 2 # 승인 — 다음 라운드 생성됨
REJECTED = 3 # 반려
CANCELED = 4 # 공급사 철회
class NotificationType(Enum):
"""company.notifications.type — negodata 담당자 인박스. 포털에서 만드는 건 재협상 요청뿐."""
RENEGO_REQUESTED = 5
class ChatSender(Enum):
"""채팅 발신자 코드. negotiation.chats.sender """
+33 -1
View File
@@ -6,7 +6,7 @@ from sqlalchemy import asc, desc, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import chats, items, sessions
from common.database.model.models import chats, items, sessions, nego_cards, wild_cards
from common.enums import ErrorType, SessionStatus
from common.logger import LOG
@@ -47,6 +47,14 @@ class IChatCRUD(ABC):
async def update_last_offer_price(self, cdb: AsyncSession, session_id, price: int) -> ErrorType:
pass
@abstractmethod
async def get_nego_card_id_by_number(self, cdb: AsyncSession, number: str):
pass
@abstractmethod
async def get_wild_card_id_by_number(self, cdb: AsyncSession, number: str):
pass
class ChatCRUD(IChatCRUD):
async def list_by_session(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, list]:
@@ -112,6 +120,30 @@ class ChatCRUD(IChatCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def get_nego_card_id_by_number(self, cdb: AsyncSession, number: str):
# 협상카드 번호(agent turn.card_id) → nego_card_id(UUID). 없으면 None. 카드 사용 로그(chats.card_id) 저장용.
try:
query = select(nego_cards.nego_card_id).where(nego_cards.number == number, nego_cards.deleted == False).limit(1) # noqa: E712
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_nego_card_id_by_number({number}) failed.")
if err_type != ErrorType.SUCCESS or not row_list:
return None
return row_list[0]
except Exception as ex:
LOG.e_no_callstack(ex)
return None
async def get_wild_card_id_by_number(self, cdb: AsyncSession, number: str):
# 와일드카드 번호(agent turn.card_id, wild_card_dynamic) → wild_card_id(UUID). 없으면 None.
try:
query = select(wild_cards.wild_card_id).where(wild_cards.number == number, wild_cards.deleted == False).limit(1) # noqa: E712
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_wild_card_id_by_number({number}) failed.")
if err_type != ErrorType.SUCCESS or not row_list:
return None
return row_list[0]
except Exception as ex:
LOG.e_no_callstack(ex)
return None
async def finalize_session(
self, cdb: AsyncSession, session_id, status: int,
bid_price: Optional[int] = None, reject_reason: Optional[str] = None, reject_price: Optional[int] = None,
+98 -9
View File
@@ -1,12 +1,13 @@
from abc import ABC, abstractmethod
from typing import Tuple
from sqlalchemy import case, func, nulls_last, select, update
from sqlalchemy import case, cast, func, nulls_last, or_, select, text, update
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import items, quotations, sessions
from common.enums import ErrorType, SessionStatus
from common.enums import CloseReason, ErrorType, QuotationStatus, RENEGOTIABLE_CLOSE_REASONS, SessionStatus
from common.logger import LOG
@@ -14,11 +15,11 @@ from common.logger import LOG
# 마감일(qt_end_time)은 견적(quotation.end_time)이 진실값이다(session.end_time 은 협상 종료 시점 기록용).
class ISessionCRUD(ABC):
@abstractmethod
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]:
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
pass
@abstractmethod
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type) -> Tuple[ErrorType, int]:
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, keyword=None, result=None) -> Tuple[ErrorType, int]:
pass
@abstractmethod
@@ -41,20 +42,63 @@ class ISessionCRUD(ABC):
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
pass
@abstractmethod
async def update_session_custom(self, cdb: AsyncSession, session_id, supplier_id, custom: dict) -> ErrorType:
pass
@abstractmethod
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
# 같은 견적번호(체인)의 최대 차수. 이미 다음 라운드가 있으면 재협상 요청은 의미가 없다.
try:
query = select(func.max(quotations.round)).where(quotations.number == number, quotations.deleted == False) # noqa: E712
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
if err_type != ErrorType.SUCCESS:
return err_type, 0
top = rows[0][0] if rows and rows[0] else None
return ErrorType.SUCCESS, int(top or 0)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def merge_session_custom(self, cdb: AsyncSession, session_id, supplier_id, patch: dict) -> ErrorType:
pass
@abstractmethod
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
pass
class SessionCRUD(ISessionCRUD):
@staticmethod
def __filters(supplier_id, status, qt_type):
def __filters(supplier_id, status, qt_type, keyword=None, result=None):
conds = [sessions.supplier_id == supplier_id, sessions.deleted == False] # noqa: E712
if status is not None:
conds.append(sessions.status == status)
if qt_type is not None:
conds.append(sessions.qt_type == qt_type)
# 검색: 견적번호·상품명·상품코드 부분일치(대소문자 무시). items 는 목록/카운트 둘 다 조인돼 있다.
# ILIKE 와일드카드(%,_)는 escape 해 사용자 입력이 패턴으로 새지 않게 한다.
if keyword and keyword.strip():
kw = keyword.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
like = f"%{kw}%"
conds.append(or_(sessions.qt_number.ilike(like), items.name.ilike(like), items.code.ilike(like)))
# 결과(SessionResult) 필터 — _to_result 파생 규칙을 SQL WHERE 로 그대로 복제(집계·필터 일치용).
# 1=낙찰 2=미낙찰 3=결렬(개찰). 전부 견적 마감(CLOSED) 이 전제.
if result in (1, 2, 3):
conds.append(quotations.status == QuotationStatus.CLOSED.value)
if result == 1:
conds.append(quotations.close_reason == CloseReason.AWARDED.value)
conds.append(quotations.preferred_sp_id == sessions.supplier_id)
elif result == 2:
conds.append(quotations.close_reason == CloseReason.AWARDED.value)
conds.append(or_(quotations.preferred_sp_id.is_(None), quotations.preferred_sp_id != sessions.supplier_id))
else:
conds.append(quotations.close_reason.in_(RENEGOTIABLE_CLOSE_REASONS))
return conds
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]:
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
try:
conds = self.__filters(supplier_id, status, qt_type)
conds = self.__filters(supplier_id, status, qt_type, keyword, result)
# 정렬 규칙:
# - order 를 명시(asc/desc)하면 그룹 구분 없이 전체를 마감 기준 한 줄로 정렬(전체 정렬).
@@ -86,6 +130,12 @@ class SessionCRUD(ISessionCRUD):
items.name,
items.model_name,
items.manufacturer,
sessions.custom,
quotations.status, # 재협상 요청 자격 판정용(마감 여부)
quotations.close_reason, # 개찰(결렬) 사유
quotations.round,
quotations.preferred_sp_id, # 낙찰자(공급사) — 나와 같으면 낙찰, 다르면 미낙찰
sessions.supplier_id, # 이 세션 소유 공급사(=조회자). 낙찰자와 대조
)
.join(items, items.item_id == sessions.item_id)
.join(quotations, quotations.qt_id == sessions.quotation_id)
@@ -102,9 +152,9 @@ class SessionCRUD(ISessionCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, []
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type) -> Tuple[ErrorType, int]:
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, keyword=None, result=None) -> Tuple[ErrorType, int]:
try:
conds = self.__filters(supplier_id, status, qt_type)
conds = self.__filters(supplier_id, status, qt_type, keyword, result)
query = (
select(func.count())
.select_from(sessions)
@@ -173,3 +223,42 @@ class SessionCRUD(ISessionCRUD):
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
# 같은 견적번호(체인)의 최대 차수. 이미 다음 라운드가 있으면 재협상 요청은 의미가 없다.
try:
query = select(func.max(quotations.round)).where(quotations.number == number, quotations.deleted == False) # noqa: E712
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
if err_type != ErrorType.SUCCESS:
return err_type, 0
top = rows[0][0] if rows and rows[0] else None
return ErrorType.SUCCESS, int(top or 0)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def merge_session_custom(self, cdb: AsyncSession, session_id, supplier_id, patch: dict) -> ErrorType:
# sessions.custom 부분 갱신(기존 키 보존). 부가정보와 재협상 요청이 같은 컬럼을 쓰므로 덮어쓰면 안 된다.
try:
query = (
update(sessions)
.where(sessions.session_id == session_id, sessions.supplier_id == supplier_id)
.values(custom=func.coalesce(sessions.custom, cast(text("'{}'"), JSONB)).op("||")(cast(patch, JSONB)))
)
return await DB_SESSION_MNG.add(cdb, query)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
async def update_session_custom(self, cdb: AsyncSession, session_id, supplier_id, custom: dict) -> ErrorType:
# 협상완료 부가정보(sessions.custom) 저장. 본인 공급사 세션만(supplier_id 가드).
try:
query = (
update(sessions)
.where(sessions.session_id == session_id, sessions.supplier_id == supplier_id)
.values(custom=custom)
)
return await DB_SESSION_MNG.add(cdb, query)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
+46 -1
View File
@@ -5,7 +5,7 @@ from sqlalchemy import delete, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import supplier_user_tokens, supplier_users, suppliers
from common.database.model.models import supplier_user_tokens, supplier_users, suppliers, companies, sessions
from common.enums import ErrorType, TokenType
from common.logger import LOG
from common.utils.gtime import GTime
@@ -28,6 +28,14 @@ class IUserCRUD(ABC):
async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, str]:
pass
@abstractmethod
async def get_company_settings(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, dict]:
pass
@abstractmethod
async def get_branding_by_session(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, dict]:
pass
@abstractmethod
async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType:
pass
@@ -117,6 +125,43 @@ class UserCRUD(IUserCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def get_company_settings(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, dict]:
"""공급사 소속 회사 설정(companies.settings) 전체. 브랜딩·협상완료 필드 등이 들어있다. 미설정이면 빈 dict."""
try:
query = (
select(companies.settings)
.join(suppliers, suppliers.company_id == companies.company_id)
.where(suppliers.supplier_id == supplier_id, suppliers.deleted == False, companies.deleted == False) # noqa: E712
.limit(1)
)
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_company_settings(supplier_id:{supplier_id}) failed.")
if err_type != ErrorType.SUCCESS:
return err_type, {}
settings = row_list[0] if row_list else None
return ErrorType.SUCCESS, settings or {}
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, {}
async def get_branding_by_session(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, dict]:
"""세션이 속한 회사의 브랜딩(companies.settings.branding). 로그인 전 화면이 쓰므로 branding 만 꺼낸다."""
try:
query = (
select(companies.settings)
.join(suppliers, suppliers.company_id == companies.company_id)
.join(sessions, sessions.supplier_id == suppliers.supplier_id)
.where(sessions.session_id == session_id, sessions.deleted == False, companies.deleted == False) # noqa: E712
.limit(1)
)
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_branding_by_session(session_id:{session_id}) failed.")
if err_type != ErrorType.SUCCESS:
return err_type, {}
settings = (row_list[0] if row_list else None) or {}
return ErrorType.SUCCESS, settings.get("branding") or {}
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, {}
async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType:
try:
query = (
+15 -1
View File
@@ -1,4 +1,4 @@
from fastapi import APIRouter, Depends, Request
from fastapi import APIRouter, Depends, Path, Request
from fastapi.security import HTTPAuthorizationCredentials
from common.models.gmodel import UserInfo
@@ -20,6 +20,7 @@ from .protocol import (
Res_Me,
Res_PopupStatus,
Res_RefreshToken,
Res_SessionBranding,
)
# 라우터(MVC 의 컨트롤러). 요청 검증 -> service 호출 -> RemoveNoneResponse 반환만 담당.
@@ -106,3 +107,16 @@ async def hide_popup(
service: AuthService = Depends(),
):
return RemoveNoneResponse(await service.hide_popup(user_info, credentials.credentials, req.popup_type))
@router.get(
path="/session-branding/{session_id}",
response_model=Res_SessionBranding,
summary="세션 브랜딩(무인증)",
description="초청 링크로 진입한 로그인 전 화면에서 회사 서비스명·로고·색상만 조회한다. 인증 없이 열려 있으므로 브랜딩 외 정보는 내리지 않는다.",
)
async def session_branding(
session_id: str = Path(..., description="협상 세션 uuid (초청 링크의 session_id)"),
service: AuthService = Depends(),
):
return RemoveNoneResponse(await service.session_branding(session_id))
+8
View File
@@ -48,6 +48,8 @@ class Res_Me(Res_WebPacketProtocol):
supplier_id: str = Field("", description="소속 공급사 uuid")
supplier_name: str = Field("", description="공급사명")
role: int = Field(0, description="권한 코드 1=user, 2=manager (UserRole)")
branding: dict = Field(default_factory=dict, description="소속 회사 브랜딩(companies.settings.branding). 서비스명/로고/색")
session_fields: list = Field(default_factory=list, description="협상완료 부가정보 필드 정의(companies.settings.session_fields). 공급사가 타결 후 입력")
class Res_Logout(Res_WebPacketProtocol):
@@ -64,3 +66,9 @@ class Req_HidePopup(AuthProtocol):
class Res_HidePopup(Res_WebPacketProtocol):
pass
class Res_SessionBranding(Res_WebPacketProtocol):
service_name: str = Field("", description="회사 서비스명(companies.settings.branding.service_name). 미설정 시 빈 값")
logo_url: str = Field("", description="회사 로고 URL")
primary_color: str = Field("", description="브랜드 색상(hex)")
+3
View File
@@ -63,6 +63,7 @@ class Res_ChatInit(Res_WebPacketProtocol):
session_id: str = Field("", description="협상 세션 uuid")
session_status: int = Field(0, description="세션 상태 코드 (SessionStatus: 1=생성 2=진행중 3=완료 4=미참여 5=거부)")
quotation_id: str = Field("", description="소속 견적 uuid")
qt_number: str = Field("", description="견적번호(EST-...)")
quotation_end_time: str = Field("", description="견적 마감 시각 (ISO 8601, 타이머용)")
quotation_memo: str = Field("", description="견적 메모")
item_id: str = Field("", description="상품 uuid")
@@ -77,6 +78,8 @@ class Res_ChatInit(Res_WebPacketProtocol):
item_min_order_quantity: str = Field("", description="최소 주문 수량")
item_vat_yn: Optional[bool] = Field(None, description="VAT 포함 여부(미설정 시 null)")
item_delivery_fee_yn: Optional[bool] = Field(None, description="배송비 포함 여부(미설정 시 null)")
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 기존 입력값(sessions.custom). 재진입 시 폼 프리필용")
labels: dict = Field(default_factory=dict, description="회사 커스텀 라벨(companies.settings.labels). 상품 상세 필드명(예: lead_time) 치환용. 없으면 프론트 기본값")
# 대화 히스토리(재진입 복원)
+25
View File
@@ -1,3 +1,5 @@
from typing import Optional
from pydantic import Field
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
@@ -14,6 +16,11 @@ class ListItem(WebPacketProtocol):
item_name: str = Field("", description="상품명")
model_name: str = Field("", description="모델명")
maker_name: str = Field("", description="제조사")
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 값(sessions.custom). 미입력이면 빈 dict")
renegotiable: bool = Field(False, description="재협상 요청 가능 여부 — 낙찰 없이 마감(개찰)된 마지막 차수이고 대기 중 요청이 없을 때만 True")
renegotiation_status: int = Field(0, description="현재 재협상 요청 상태(RenegotiationStatus). 요청 이력이 없으면 0")
renegotiation_memo: str = Field("", description="담당자 심사 메모(반려 사유). 없으면 빈 문자열")
result: int = Field(0, description="공급사 관점 협상 결과(SessionResult): 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰, 재협상 대상)")
class Res_SessionList(Res_WebPacketProtocol):
@@ -33,3 +40,21 @@ class Req_Reject(WebPacketProtocol):
class Res_Reject(Res_WebPacketProtocol):
session_id: str = Field("", description="거부 처리된 세션 uuid")
class Req_ExtraInfo(WebPacketProtocol):
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 값 {key: value} (회사 정의 session_fields 대로)")
class Res_ExtraInfo(Res_WebPacketProtocol):
session_id: str = Field("", description="부가정보 저장된 세션 uuid")
class Req_Renegotiation(WebPacketProtocol):
reason: str = Field("", max_length=255, description="재협상 요청 사유(프리셋 라벨 또는 직접 입력)")
desired_price: Optional[int] = Field(None, description="희망 공급가(원). 담당자 판단 근거로만 쓰인다")
class Res_Renegotiation(Res_WebPacketProtocol):
session_id: str = Field("", description="요청이 기록된 세션 uuid")
status: int = Field(0, description="요청 상태(RenegotiationStatus): 1=심사중 2=승인 3=반려 4=철회")
+64 -2
View File
@@ -6,7 +6,16 @@ from fastapi.security import HTTPAuthorizationCredentials
from common.models.gmodel import UserInfo
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, security
from services.negotiation_service import NegotiationService
from .protocol import Req_Reject, Res_Participate, Res_Reject, Res_SessionList
from .protocol import (
Req_ExtraInfo,
Req_Reject,
Req_Renegotiation,
Res_ExtraInfo,
Res_Participate,
Res_Reject,
Res_Renegotiation,
Res_SessionList,
)
router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={404: {"description": "Not found"}})
@@ -26,9 +35,11 @@ async def list_sessions(
order: Optional[str] = Query(None, description="마감일 전체 정렬: asc(임박순)/desc(여유순). 미지정 시 기본 그룹 정렬('할 일' 우선 → 종료는 하단·최근순). 지정하면 그룹 없이 전체를 마감 기준으로 정렬."),
page: int = Query(1, ge=1, description="페이지 (1부터)"),
page_size: int = Query(20, ge=1, le=100, description="페이지당 건수 (1~100)"),
keyword: Optional[str] = Query(None, description="검색어 — 견적번호·상품명·상품코드 부분일치(대소문자 무시)"),
result: Optional[int] = Query(None, description="결과 필터(SessionResult): 1=낙찰 2=미낙찰 3=결렬(개찰). 미지정 시 전체"),
):
return RemoveNoneResponse(
await service.list_sessions(user_info, credentials.credentials, status, qt_type, order, page, page_size)
await service.list_sessions(user_info, credentials.credentials, status, qt_type, order, page, page_size, keyword, result)
)
@@ -61,3 +72,54 @@ async def reject(
service: NegotiationService = Depends(),
):
return RemoveNoneResponse(await service.reject(user_info, credentials.credentials, session_id, req.reject_reason))
@router.post(
path="/sessions/{session_id}/extra-info",
response_model=Res_ExtraInfo,
summary="협상완료 부가정보 저장",
description="협상 타결(완료) 세션에 부가정보(표준납기/MOQ/발주배수/배송유형 등, 회사 정의 session_fields)를 저장한다. 본인 공급사의 완료 세션만 허용.",
)
async def save_extra_info(
session_id: str = Path(description="대상 협상 세션 uuid"),
req: Req_ExtraInfo = ...,
user_info: UserInfo = Depends(IsValidAccessToken),
credentials: HTTPAuthorizationCredentials = Depends(security),
service: NegotiationService = Depends(),
):
return RemoveNoneResponse(await service.save_extra_info(user_info, credentials.credentials, session_id, req))
@router.post(
path="/session/{session_id}/renegotiation",
response_model=Res_Renegotiation,
summary="재협상 요청",
description="낙찰 없이 마감된(개찰) 건에 대해 공급사가 재협상을 요청한다. 담당자 승인 시 다음 라운드가 생성된다. 본인 공급사의 마지막 라운드 세션만 허용.",
)
async def request_renegotiation(
req: Req_Renegotiation,
session_id: str = Path(..., description="협상 세션 uuid"),
user_info: UserInfo = Depends(IsValidAccessToken),
credentials: HTTPAuthorizationCredentials = Depends(security),
service: NegotiationService = Depends(),
):
return RemoveNoneResponse(
await service.request_renegotiation(user_info, credentials.credentials, session_id, req)
)
@router.delete(
path="/session/{session_id}/renegotiation",
response_model=Res_Renegotiation,
summary="재협상 요청 철회",
description="심사 대기(PENDING) 중인 본인 요청을 철회한다.",
)
async def cancel_renegotiation(
session_id: str = Path(..., description="협상 세션 uuid"),
user_info: UserInfo = Depends(IsValidAccessToken),
credentials: HTTPAuthorizationCredentials = Depends(security),
service: NegotiationService = Depends(),
):
return RemoveNoneResponse(
await service.cancel_renegotiation(user_info, credentials.credentials, session_id)
)
+29
View File
@@ -18,6 +18,7 @@ from router.v1.auth.protocol import (
Res_Me,
Res_PopupStatus,
Res_RefreshToken,
Res_SessionBranding,
)
from router.v1.validator.dependencies import CreateAccessToken, CreateRefreshToken, GetHashedPW, VerifyPW
@@ -250,6 +251,34 @@ class AuthService:
res.supplier_id = info.supplier_id
res.supplier_name = info.supplier_name
res.role = info.role
# 소속 회사 설정(companies.settings) — 로고/서비스명(branding) + 협상완료 부가필드(session_fields). 실패해도 기본값.
_e, settings = await DB_SESSION_MNG.execute_lambda(
suppliers.DBType(),
DBWRType.DB_READ.value,
lambda s: self.user_crud.get_company_settings(s, uuid.UUID(info.supplier_id)),
)
settings = settings or {}
res.branding = settings.get("branding") or {}
res.session_fields = settings.get("session_fields") or []
return res
async def session_branding(self, session_id: str) -> Res_SessionBranding:
"""로그인 전(초청 링크 진입) 화면용 브랜딩. 인증 없이 session_id 로만 조회하며 브랜딩 외 정보는 내리지 않는다."""
res = Res_SessionBranding()
try:
sid = uuid.UUID(session_id)
except ValueError:
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
return res
_e, branding = await DB_SESSION_MNG.execute_lambda(
suppliers.DBType(),
DBWRType.DB_READ.value,
lambda s: self.user_crud.get_branding_by_session(s, sid),
)
branding = branding or {}
res.service_name = branding.get("service_name") or ""
res.logo_url = branding.get("logo_url") or ""
res.primary_color = branding.get("primary_color") or ""
return res
async def popup_status(self, user_info: UserInfo, access_token: str) -> Res_PopupStatus:
+108 -3
View File
@@ -24,6 +24,7 @@ from common.logger import LOG
from common.models.gmodel import UserInfo
from crud.chat_crud import ChatCRUD, IChatCRUD
from crud.session_crud import ISessionCRUD, SessionCRUD
from crud.user_crud import IUserCRUD, UserCRUD
from router.v1.chat.protocol import ChatMessage, ChatSummary, Res_ChatInit, Res_ChatMessages, Res_ChatSend
from services.agent_client import AgentChatContext, IAgentClient, get_agent_client
from services.auth_service import AuthService
@@ -44,11 +45,13 @@ class ChatService:
auth: AuthService = Depends(AuthService),
session_crud: ISessionCRUD = Depends(SessionCRUD),
chat_crud: IChatCRUD = Depends(ChatCRUD),
user_crud: IUserCRUD = Depends(UserCRUD),
agent: IAgentClient = Depends(get_agent_client),
):
self.auth = auth
self.session_crud = session_crud
self.chat_crud = chat_crud
self.user_crud = user_crud
self.agent = agent
# ---- 순수 헬퍼/매퍼 (self 불필요, 상단 집약) ----
@@ -59,6 +62,27 @@ class ChatService:
digits = "".join(ch for ch in text if ch.isdigit())
return int(digits) if digits else None
@staticmethod
def _parse_reject(text: Optional[str]) -> dict:
"""통일 결렬 폼 제출 문자열 파싱 → {offer_price, reason, opinion}.
형식: '공급희망가격-{원}, 합의불가사유-{사유}, 의견-{의견}' (사유는 '기타-{내용}' 가능).
의견은 자유서술이라 콤마 포함 가능 → 맨 뒤 '의견-' 기준으로 먼저 떼어낸다."""
s = text or ""
opinion = None
if ", 의견-" in s:
s, opinion = s.split(", 의견-", 1)
reason = None
if ", 합의불가사유-" in s:
price_part, reason = s.split(", 합의불가사유-", 1)
else:
price_part = s
price_digits = "".join(ch for ch in price_part.replace("공급희망가격-", "") if ch.isdigit())
return {
"offer_price": int(price_digits) if price_digits else None,
"reason": reason or None,
"opinion": (opinion.strip() or None) if opinion is not None else None,
}
@staticmethod
def _in_price_range(price: int, target_price: Optional[int]) -> bool:
if not target_price:
@@ -103,13 +127,18 @@ class ChatService:
)
@staticmethod
def _build_bot_chat(sess, seq: int, turn, bot_chat_type: Optional[str] = None, summary: Optional[dict] = None) -> chats:
def _build_bot_chat(sess, seq: int, turn, bot_chat_type: Optional[str] = None, summary: Optional[dict] = None, card_uuid=None, card_type=None) -> chats:
# bot_chat_type/summary 도 meta 에 영속화 → 히스토리 복원 시 폼 재현. indicator_value 는 전용 컬럼에도 적재.
# nego_card_uuid: turn.card_id(번호)를 UUID 로 변환한 값(nego 카드). 있으면 chats.card_id/card_type/card_used_yn 컬럼에 적재
# → negodata 가 이 컬럼으로 카드 사용/효과를 조인한다. (wild 카드는 agent 가 card_id 미제공 — 별도 작업)
return chats(
chat_id=uuid.uuid4(), session_id=sess.session_id, seq=seq,
sender=ChatSender.BOT.value,
target_price=int(sess.target_price or 0),
indicator_value=turn.indicator_value,
card_id=card_uuid,
card_type=card_type if card_uuid else None, # CardType: 1=nego, 2=wild
card_used_yn=True if card_uuid else None,
meta={
"script": turn.script, "step": turn.step, "client_step": turn.client_step,
"input_mode": turn.input_mode, "input_options": turn.input_options,
@@ -204,9 +233,12 @@ class ChatService:
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
return res
await self._ensure_in_progress(sess, quote)
res.session_id = str(sess.session_id)
res.session_status = sess.status
res.quotation_id = str(sess.quotation_id)
res.qt_number = sess.qt_number or ""
res.quotation_end_time = quote.end_time.isoformat(timespec="seconds") if quote.end_time else ""
res.quotation_memo = quote.memo or ""
res.item_id = str(item.item_id)
@@ -221,8 +253,48 @@ class ChatService:
res.item_min_order_quantity = item.moq or ""
res.item_vat_yn = item.vat_yn
res.item_delivery_fee_yn = item.delivery_fee_yn
res.custom = sess.custom or {}
# 회사 커스텀 라벨(companies.settings.labels) — 상품 상세 필드명 치환용(예: lead_time→표준납기). 실패해도 빈 dict 폴백.
_e, settings = await DB_SESSION_MNG.execute_lambda(
suppliers.DBType(), DBWRType.DB_READ.value,
lambda s: self.user_crud.get_company_settings(s, sess.supplier_id),
)
res.labels = (settings.get("labels") or {}) if _e == ErrorType.SUCCESS and settings else {}
# 회사가 VAT(vat_yn)를 관리하지 않으면(hidden_fields) 협상 화면 VAT 표기를 숨긴다(값 null → 프론트 라벨 생략).
_hidden = (settings.get("hidden_fields") or []) if _e == ErrorType.SUCCESS and settings else []
if "vat_yn" in _hidden:
res.item_vat_yn = None
return res
async def _ensure_in_progress(self, sess, quote) -> None:
"""협상생성(1) 세션을 채팅 진입만으로 협상중(2)으로 전이한다(participate 와 동일 전이).
negodata 안내 메일/링크는 목록의 참여 버튼을 거치지 않고 chat 으로 바로 들어오는데,
오프닝 메시지는 협상중일 때만 seed 되므로 전이가 없으면 빈 채팅으로 멈춘다.
마감된 견적은 진입해도 대화가 불가하므로 전이하지 않는다."""
if sess.status != SessionStatus.CREATED.value:
return
if quote is None or quote.status == QuotationStatus.CLOSED.value:
return
end = quote.end_time
if end is not None and end.tzinfo is None:
end = end.replace(tzinfo=timezone.utc)
if end is not None and end < datetime.now(timezone.utc):
return
err_type = await DB_SESSION_MNG.execute_lambda_run(
[sessions.DBType()],
[
lambda s: self.session_crud.update_session_status(s, sess.session_id, SessionStatus.IN_PROGRESS.value),
lambda s: self.session_crud.update_quotation_status(s, sess.quotation_id, QuotationStatus.IN_PROGRESS.value),
],
)
if err_type != ErrorType.SUCCESS:
return
sess.status = SessionStatus.IN_PROGRESS.value
# ---- messages -------------------------------------------------------
async def messages(self, user_info: UserInfo, access_token: str, session_id_str: str) -> Res_ChatMessages:
res = Res_ChatMessages()
@@ -239,6 +311,15 @@ class ChatService:
res.result.SetResult(err_type)
return res
# 협상생성 상태로 바로 진입한 경우(메일 링크) 여기서도 전이한다 —
# init 과 병렬로 호출돼 init 의 전이를 못 본 채 읽었을 수 있다.
if not rows and sess.status == SessionStatus.CREATED.value:
_, quote = await DB_SESSION_MNG.execute_lambda(
quotations.DBType(), DBWRType.DB_READ.value,
lambda s: self.session_crud.get_quotation_by_id(s, sess.quotation_id),
)
await self._ensure_in_progress(sess, quote)
# 비어 있고 협상중이면 agent 오프닝 한 턴을 seed (재진입 시 인사 메시지 보존)
if not rows and sess.status == SessionStatus.IN_PROGRESS.value:
opening = await self._seed_opening(sess)
@@ -371,8 +452,27 @@ class ChatService:
# 유저 미입력 가격 타결 케이스 — 마지막 유저 제시가와 다를 수 있다).
summary = await self._build_summary(sess, quote, item, final_price, turn.settled_price or last_price)
# 카드 번호(turn.card_id) → UUID 변환. step 으로 nego/wild 갈라 각 테이블 조회(번호가 겹칠 수 있어 종류로 구분).
# 카드 사용 로그(chats.card_id/type/used)를 negodata 조인용으로 남긴다. (1% 인하 시스템 카드는 agent 가 card_id 미제공)
card_uuid = None
card_type = None
if turn.card_id:
is_wild = bool(turn.step and turn.step.startswith("wild"))
if is_wild:
card_uuid = await DB_SESSION_MNG.execute_lambda(
chats.DBType(), DBWRType.DB_READ.value,
lambda s: self.chat_crud.get_wild_card_id_by_number(s, str(turn.card_id)),
)
card_type = 2
else:
card_uuid = await DB_SESSION_MNG.execute_lambda(
chats.DBType(), DBWRType.DB_READ.value,
lambda s: self.chat_crud.get_nego_card_id_by_number(s, str(turn.card_id)),
)
card_type = 1
# 봇 메시지 + 종료 시 확정(성공=DONE+입찰가 / 실패=REJECTED+거부사유·제시가). 한 트랜잭션.
bot_msg = self._build_bot_chat(sess, seq=max_seq + 2, turn=turn, bot_chat_type=bot_chat_type, summary=summary)
bot_msg = self._build_bot_chat(sess, seq=max_seq + 2, turn=turn, bot_chat_type=bot_chat_type, summary=summary, card_uuid=card_uuid, card_type=card_type)
funcs = [lambda s: self.chat_crud.insert_message(s, bot_msg)]
# 가격 입력 턴 → 마지막 제시가를 봇 메시지 저장과 같은 트랜잭션으로 갱신.
# 앵커링 표본 판정의 "가격 흔적"(가격을 써낸 협상만 집계 — 중간 이탈해도 실패로 측정 가능).
@@ -392,10 +492,15 @@ class ChatService:
funcs.append(lambda s: self.chat_crud.finalize_session(s, sess.session_id, new_status, bid_price=bid))
else:
new_status = SessionStatus.REJECTED.value
parsed = self._parse_reject(user_input)
funcs.append(lambda s: self.chat_crud.finalize_session(
s, sess.session_id, new_status,
reject_reason=(user_input or None), reject_price=price,
reject_reason=parsed["reason"], reject_price=parsed["offer_price"],
))
if parsed["opinion"]:
funcs.append(lambda s, op=parsed["opinion"]: self.session_crud.merge_session_custom(
s, sess.session_id, sess.supplier_id, {"opinion": op},
))
err_type = await DB_SESSION_MNG.execute_lambda_run([chats.DBType()], funcs)
if err_type != ErrorType.SUCCESS:
+289 -20
View File
@@ -4,11 +4,31 @@ from datetime import datetime, timezone
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import sessions
from common.enums import DBWRType, ErrorType, QuotationStatus, SessionStatus
from common.database.model.models import chats, notifications, sessions
from common.enums import (
CloseReason,
DBWRType,
ErrorType,
NotificationType,
QuotationStatus,
RENEGOTIABLE_CLOSE_REASONS,
RenegotiationStatus,
SessionStatus,
)
from common.logger import LOG
from common.models.gmodel import UserInfo
from crud.chat_crud import ChatCRUD, IChatCRUD
from crud.session_crud import ISessionCRUD, SessionCRUD
from router.v1.negotiation.protocol import ListItem, Res_Participate, Res_Reject, Res_SessionList
from router.v1.negotiation.protocol import (
ListItem,
Req_ExtraInfo,
Req_Renegotiation,
Res_ExtraInfo,
Res_Participate,
Res_Reject,
Res_Renegotiation,
Res_SessionList,
)
from services.auth_service import AuthService
@@ -18,11 +38,20 @@ class NegotiationService:
- 목록은 로그인 유저의 supplier_id 로만 조회한다.
"""
def __init__(self, auth: AuthService = Depends(AuthService), session_crud: ISessionCRUD = Depends(SessionCRUD)):
# 부가정보 입력 폼을 띄우는 요약 말풍선 종류. 이 말풍선이 나온 뒤면 협상은 타결된 것으로 본다.
_SUMMARY_BOT_TYPES = ("summaryRSP", "summaryCM")
def __init__(
self,
auth: AuthService = Depends(AuthService),
session_crud: ISessionCRUD = Depends(SessionCRUD),
chat_crud: IChatCRUD = Depends(ChatCRUD),
):
self.auth = auth
self.session_crud = session_crud
self.chat_crud = chat_crud
async def list_sessions(self, user_info: UserInfo, access_token: str, status, qt_type, order: str, page: int, page_size: int) -> Res_SessionList:
async def list_sessions(self, user_info: UserInfo, access_token: str, status, qt_type, order: str, page: int, page_size: int, keyword: str = None, result: int = None) -> Res_SessionList:
res = Res_SessionList()
# 1) 인증 (활성 + 저장된 access 토큰 대조)
@@ -38,7 +67,7 @@ class NegotiationService:
err_type, rows = await DB_SESSION_MNG.execute_lambda(
sessions.DBType(),
DBWRType.DB_READ.value,
lambda s: self.session_crud.list_by_supplier(s, supplier_id, status, qt_type, order, offset, page_size),
lambda s: self.session_crud.list_by_supplier(s, supplier_id, status, qt_type, order, offset, page_size, keyword, result),
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
@@ -48,31 +77,271 @@ class NegotiationService:
err_type, total = await DB_SESSION_MNG.execute_lambda(
sessions.DBType(),
DBWRType.DB_READ.value,
lambda s: self.session_crud.count_by_supplier(s, supplier_id, status, qt_type),
lambda s: self.session_crud.count_by_supplier(s, supplier_id, status, qt_type, keyword, result),
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
res.items = [
ListItem(
session_id=str(r[0]),
session_status=r[1],
qt_type=r[2],
qt_number=r[3],
qt_end_time=r[4].isoformat(timespec="seconds") if r[4] else "",
item_code=r[5] or "",
item_name=r[6] or "",
model_name=r[7] or "",
maker_name=r[8] or "",
# 같은 견적번호(체인)의 최대 차수 — 이미 다음 라운드가 있으면 재협상 요청 대상이 아니다.
max_rounds: dict = {}
for number in {r[3] for r in rows if r[3]}:
_e, mx = await DB_SESSION_MNG.execute_lambda(
sessions.DBType(), DBWRType.DB_READ.value,
lambda s, n=number: self.session_crud.chain_max_round(s, n),
)
for r in rows
]
max_rounds[number] = mx or 0
res.items = [self._to_list_item(r, max_rounds) for r in rows]
res.total = total
res.page = page
res.page_size = page_size
return res
async def save_extra_info(self, user_info: UserInfo, access_token: str, session_id_str: str, req: Req_ExtraInfo) -> Res_ExtraInfo:
"""협상완료(타결) 부가정보 저장. 견적 마감 여부와 무관하게, 본인 공급사의 '협상완료' 세션에만 허용.
_load_actionable_session 은 견적마감·마감시간을 막으므로(타결 후엔 마감됐을 수 있음) 쓰지 않고 직접 검증한다.
"""
res = Res_ExtraInfo()
# 1) 인증
err_type, info = await self.auth.authenticate(user_info, access_token)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
try:
session_id = uuid.UUID(session_id_str)
except (ValueError, TypeError):
res.result.SetResult(ErrorType.NEGO_NOT_FOUND)
return res
# 2) 세션 조회 + 소유 검증
err_type, sess = await DB_SESSION_MNG.execute_lambda(
sessions.DBType(), DBWRType.DB_READ.value,
lambda s: self.session_crud.get_session_by_id(s, session_id),
)
if err_type != ErrorType.SUCCESS or sess is None:
res.result.SetResult(ErrorType.NEGO_NOT_FOUND)
return res
if str(sess.supplier_id) != info.supplier_id:
res.result.SetResult(ErrorType.NEGO_FORBIDDEN)
return res
# 3) 협상완료(타결) 세션만 부가정보 입력 허용.
# 단 '협상완료' 요약 말풍선은 chat_end=false 라 세션이 아직 협상중(2)이다
# (동의 → '협상종료' 턴에서야 완료로 전이). 폼은 요약 시점에 뜨므로 그 구간도 허용한다.
if sess.status != SessionStatus.DONE.value:
if sess.status != SessionStatus.IN_PROGRESS.value or not await self._is_after_summary(sess.session_id):
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
return res
# 4) 저장(supplier_id 가드 crud)
err_type = await DB_SESSION_MNG.execute_lambda_run(
[sessions.DBType()],
[lambda s: self.session_crud.update_session_custom(s, session_id, uuid.UUID(info.supplier_id), req.custom or {})],
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
res.session_id = str(session_id)
return res
@staticmethod
def _to_list_item(r, max_rounds: dict) -> ListItem:
"""세션 행 → 목록 아이템. 재협상 요청 가능 여부는 서버가 판정해 내려준다(프론트가 규칙을 몰라도 되게)."""
custom = r[9] or {}
renego = custom.get("renegotiation") or {}
status = renego.get("status") or 0
is_last_round = (r[12] or 0) >= max_rounds.get(r[3], 0)
renegotiable = (
r[10] == QuotationStatus.CLOSED.value
and r[11] in RENEGOTIABLE_CLOSE_REASONS
and is_last_round
and status
not in (
RenegotiationStatus.PENDING.value,
RenegotiationStatus.APPROVED.value,
RenegotiationStatus.REJECTED.value,
)
)
return ListItem(
session_id=str(r[0]),
session_status=r[1],
qt_type=r[2],
qt_number=r[3],
qt_end_time=r[4].isoformat(timespec="seconds") if r[4] else "",
item_code=r[5] or "",
item_name=r[6] or "",
model_name=r[7] or "",
maker_name=r[8] or "",
custom=custom,
renegotiable=renegotiable,
renegotiation_status=status,
renegotiation_memo=renego.get("memo") or "",
result=NegotiationService._to_result(r[10], r[11], r[13], r[14]),
)
@staticmethod
def _to_result(qt_status, close_reason, winner_id, my_id) -> int:
"""공급사 관점 협상 결과(SessionResult). 견적 마감 전이면 0(미정).
낙찰 건은 낙찰자가 나면 1(낙찰)·아니면 2(미낙찰), 개찰(OPEN_*) 마감은 3(결렬=재협상 대상)."""
if qt_status != QuotationStatus.CLOSED.value:
return 0
if close_reason == CloseReason.AWARDED.value:
return 1 if winner_id is not None and str(winner_id) == str(my_id) else 2
if close_reason in RENEGOTIABLE_CLOSE_REASONS:
return 3
return 0
async def request_renegotiation(
self, user_info: UserInfo, access_token: str, session_id_str: str, req: Req_Renegotiation
) -> Res_Renegotiation:
"""결렬(개찰) 마감 건에 대해 공급사가 재협상을 요청한다(IMK #15).
전용 테이블 없이 sessions.custom.renegotiation 에 기록하고, 견적 작성자에게 알림을 남긴다."""
res = Res_Renegotiation()
err_type, info, sess, quote = await self._load_renegotiable(user_info, access_token, session_id_str)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
# 심사 대기·승인·반려 건은 재요청을 막는다(전용 테이블이 없어 유니크 대신 여기서 검증).
# 반려는 담당자가 이미 판단한 결과라 같은 건으로 다시 올릴 수 없다. 철회(CANCELED)만 재요청 허용.
current = (sess.custom or {}).get("renegotiation") or {}
if current.get("status") in (
RenegotiationStatus.PENDING.value,
RenegotiationStatus.APPROVED.value,
RenegotiationStatus.REJECTED.value,
):
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
return res
payload = {
"status": RenegotiationStatus.PENDING.value,
"reason": (req.reason or "").strip(),
"desired_price": req.desired_price,
"requested_at": datetime.now(timezone.utc).isoformat(),
}
err_type = await DB_SESSION_MNG.execute_lambda_run(
[sessions.DBType()],
[lambda s: self.session_crud.merge_session_custom(
s, sess.session_id, uuid.UUID(info.supplier_id), {"renegotiation": payload}
)],
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
await self._notify_renegotiation(quote, sess, info, payload)
res.session_id = str(sess.session_id)
res.status = RenegotiationStatus.PENDING.value
return res
async def cancel_renegotiation(self, user_info: UserInfo, access_token: str, session_id_str: str) -> Res_Renegotiation:
"""공급사가 자기 요청을 철회한다. 심사 대기(PENDING) 중에만 가능."""
res = Res_Renegotiation()
err_type, info, sess, _quote = await self._load_renegotiable(user_info, access_token, session_id_str)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
current = (sess.custom or {}).get("renegotiation") or {}
if current.get("status") != RenegotiationStatus.PENDING.value:
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
return res
patch = {**current, "status": RenegotiationStatus.CANCELED.value}
err_type = await DB_SESSION_MNG.execute_lambda_run(
[sessions.DBType()],
[lambda s: self.session_crud.merge_session_custom(
s, sess.session_id, uuid.UUID(info.supplier_id), {"renegotiation": patch}
)],
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
res.session_id = str(sess.session_id)
res.status = RenegotiationStatus.CANCELED.value
return res
async def _load_renegotiable(self, user_info: UserInfo, access_token: str, session_id_str: str):
"""재협상 요청 자격 검증 — 인증 → 본인 세션 → 결렬(개찰) 마감 → 마지막 라운드.
성공 시 (SUCCESS, info, sess, quote)."""
err_type, info = await self.auth.authenticate(user_info, access_token)
if err_type != ErrorType.SUCCESS:
return err_type, None, None, None
try:
session_id = uuid.UUID(session_id_str)
except (ValueError, TypeError):
return ErrorType.NEGO_NOT_FOUND, None, None, None
err_type, sess = await DB_SESSION_MNG.execute_lambda(
sessions.DBType(), DBWRType.DB_READ.value,
lambda s: self.session_crud.get_session_by_id(s, session_id),
)
if err_type != ErrorType.SUCCESS or sess is None:
return ErrorType.NEGO_NOT_FOUND, None, None, None
if str(sess.supplier_id) != info.supplier_id:
return ErrorType.NEGO_FORBIDDEN, None, None, None
err_type, quote = await DB_SESSION_MNG.execute_lambda(
sessions.DBType(), DBWRType.DB_READ.value,
lambda s: self.session_crud.get_quotation_by_id(s, sess.quotation_id),
)
if err_type != ErrorType.SUCCESS or quote is None:
return ErrorType.NEGO_NOT_FOUND, None, None, None
# 낙찰됐거나 아직 진행 중인 건은 요청 대상이 아니다.
if quote.status != QuotationStatus.CLOSED.value or quote.close_reason not in RENEGOTIABLE_CLOSE_REASONS:
return ErrorType.NEGO_NOT_PARTICIPABLE, None, None, None
# 이미 다음 라운드가 만들어졌으면 요청할 이유가 없다.
_e, max_round = await DB_SESSION_MNG.execute_lambda(
sessions.DBType(), DBWRType.DB_READ.value,
lambda s: self.session_crud.chain_max_round(s, quote.number),
)
if max_round and quote.round < max_round:
return ErrorType.NEGO_NOT_PARTICIPABLE, None, None, None
return ErrorType.SUCCESS, info, sess, quote
async def _notify_renegotiation(self, quote, sess, info, payload: dict) -> None:
"""견적 작성자 인박스에 재협상 요청 알림을 남긴다. 부가 효과라 실패해도 본 흐름을 막지 않는다."""
notif = notifications(
user_id=quote.user_id,
type=NotificationType.RENEGO_REQUESTED.value,
ref_qt_id=quote.qt_id,
ref_session_id=sess.session_id,
data={
"supplier_name": info.supplier_name,
"qt_number": quote.number,
"qt_round": quote.round,
"reason": payload.get("reason"),
"desired_price": payload.get("desired_price"),
},
)
err = await DB_SESSION_MNG.execute_lambda_run(
[notifications.DBType()],
[lambda s: DB_SESSION_MNG.insert(s, notif, raise_error=False)],
)
if err != ErrorType.SUCCESS:
LOG.e_no_callstack(f"[renego] 알림 기록 실패 qt={quote.qt_id} session={sess.session_id}")
async def _is_after_summary(self, session_id) -> bool:
"""마지막 말풍선이 타결 요약(summaryRSP/CM)인지 — 즉 협상이 타결된 뒤인지."""
err_type, (_, _, last_meta) = await DB_SESSION_MNG.execute_lambda(
chats.DBType(), DBWRType.DB_READ.value,
lambda s: self.chat_crud.get_last(s, session_id),
)
if err_type != ErrorType.SUCCESS or not last_meta:
return False
return last_meta.get("bot_chat_type") in self._SUMMARY_BOT_TYPES
async def _load_actionable_session(self, user_info: UserInfo, access_token: str, session_id_str: str, blocked_statuses: tuple):
"""참여/거부 공통 전처리: 인증 → 세션/견적 로드 → 소유·상태·견적마감·마감시간 검증.
성공 시 (SUCCESS, sess, quote), 실패 시 (err_type, None, None) 을 반환한다.
+123
View File
@@ -177,6 +177,56 @@ async def test_list_requires_auth(client):
assert (await client.get("/v1/negotiation/sessions")).status_code in (401, 403)
# ---- 검색(keyword) ----------------------------------------------------------
async def test_search_by_qt_number_and_item_code(client, nego_seed):
"""검증: 견적번호/상품코드가 같은 값(PYTESTNEGO-B)으로 검색.
기대결과: B 1건만, total 도 1(카운트도 같은 필터 적용)."""
token = await _login_token(client)
body = (await _list(client, token, keyword=f"{MARK}B")).json()
assert body["total"] == 1
assert [i["item_code"] for i in body["items"]] == [f"{MARK}B"]
async def test_search_by_item_name(client, nego_seed):
"""검증: 상품명 일부('상품 A')로 검색.
기대결과: A 1건만."""
token = await _login_token(client)
body = (await _list(client, token, keyword="상품 A")).json()
assert {i["item_code"] for i in body["items"]} == {f"{MARK}A"}
async def test_search_prefix_matches_all_own(client, nego_seed):
"""검증: 공통 prefix(PYTESTNEGO)로 검색.
기대결과: 본인 공급사 3건 전부(타 공급사 X 는 제외 유지)."""
token = await _login_token(client)
body = (await _list(client, token, keyword=MARK.rstrip("-"))).json()
assert body["total"] == 3
async def test_search_case_insensitive(client, nego_seed):
"""검증: 소문자로 검색(pytestnego-c).
기대결과: ILIKE 라 대소문자 무시하고 C 매칭."""
token = await _login_token(client)
body = (await _list(client, token, keyword=f"{MARK}c".lower())).json()
assert {i["item_code"] for i in body["items"]} == {f"{MARK}C"}
async def test_search_no_match_returns_empty(client, nego_seed):
"""검증: 어디에도 없는 검색어.
기대결과: 0건, total 0."""
token = await _login_token(client)
body = (await _list(client, token, keyword="존재하지않는검색어zzz")).json()
assert body["total"] == 0 and body["items"] == []
async def test_search_wildcard_is_escaped(client, nego_seed):
"""검증: ILIKE 와일드카드('%')를 그대로 검색 — 패턴으로 새면 전건 매칭될 위험.
기대결과: escape 되어 리터럴 '%' 로 취급 → 매칭 0건."""
token = await _login_token(client)
body = (await _list(client, token, keyword="%")).json()
assert body["total"] == 0
# ---- 참여 -------------------------------------------------------------------
async def test_participate_success(client, nego_seed, db_engine):
token = await _login_token(client)
@@ -294,3 +344,76 @@ async def test_reject_requires_auth(client, nego_seed):
sid = nego_seed["sids"]["B"]
r = await client.post(f"/v1/negotiation/sessions/{sid}/reject", json={"reject_reason": "사유"})
assert r.status_code in (401, 403)
# ---- 결과 필터(result) ------------------------------------------------------
# 마감(CLOSED) + 마감사유/낙찰자로 낙찰(1)·미낙찰(2)·결렬(3)을 만들고 result= 로 거른다.
# nego_seed 의 공급사/로그인을 재사용하고, MARK prefix 라 픽스처 teardown 이 함께 정리한다.
async def _seed_result_row(engine, *, supplier_id, code, close_reason, winner_id):
import uuid as _uuid
item_id, qt_id, session_id = _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4()
async with engine.begin() as conn:
await conn.execute(
text("INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) "
"VALUES (:iid, gen_random_uuid(), gen_random_uuid(), :name, :code, 'M', '제조사')"),
{"iid": item_id, "name": f"상품 {code}", "code": f"{MARK}{code}"},
)
await conn.execute(
text("INSERT INTO quotation.quotations "
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, close_reason, "
" preferred_sp_id, round, start_time, end_time) VALUES "
"(:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, 2, 3, :cr, "
" :win, 1, now() - make_interval(hours => 2), now() - make_interval(hours => 1))"),
{"qid": qt_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "cr": close_reason, "win": winner_id},
)
await conn.execute(
text("INSERT INTO negotiation.sessions "
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
" target_price, status, bid_price, end_time) VALUES "
"(:sid, :qid, :iid, :sup, :num, 1, 2, 100000, 3, 95000, now() - make_interval(hours => 1))"),
{"sid": session_id, "qid": qt_id, "iid": item_id, "sup": supplier_id, "num": f"{MARK}{code}"},
)
@pytest_asyncio.fixture
async def result_rows(nego_seed, db_engine):
"""nego_seed 공급사에 낙찰/미낙찰/결렬 각 1건을 추가한다(개찰 5=OPEN_PRICE, 1=AWARDED)."""
sup = nego_seed["supplier_id"]
await _seed_result_row(db_engine, supplier_id=sup, code="RWON", close_reason=1, winner_id=sup) # 낙찰(나)
await _seed_result_row(db_engine, supplier_id=sup, code="RLOST", close_reason=1, winner_id=uuid.uuid4()) # 미낙찰(남)
await _seed_result_row(db_engine, supplier_id=sup, code="ROPEN", close_reason=5, winner_id=None) # 결렬(개찰)
return nego_seed
async def test_result_filter_won(client, result_rows):
"""검증: result=1(낙찰)로 필터. 기대결과: 낙찰 건만, total=1."""
token = await _login_token(client)
body = (await _list(client, token, result=1)).json()
assert body["total"] == 1
assert body["items"][0]["item_code"] == f"{MARK}RWON"
assert body["items"][0]["result"] == 1
async def test_result_filter_lost(client, result_rows):
"""검증: result=2(미낙찰)로 필터. 기대결과: 미낙찰 건만."""
token = await _login_token(client)
body = (await _list(client, token, result=2)).json()
assert {i["item_code"] for i in body["items"]} == {f"{MARK}RLOST"}
assert body["items"][0]["result"] == 2
async def test_result_filter_open(client, result_rows):
"""검증: result=3(결렬)로 필터. 기대결과: 개찰 결렬 건만 + 재협상 대상(renegotiable=True)."""
token = await _login_token(client)
body = (await _list(client, token, result=3)).json()
assert {i["item_code"] for i in body["items"]} == {f"{MARK}ROPEN"}
assert body["items"][0]["result"] == 3
assert body["items"][0]["renegotiable"] is True
async def test_result_filter_composes_with_paging(client, result_rows):
"""검증: 결과 필터가 total(페이징)에 반영. 기대결과: result=1 이면 total=1(전체 목록과 별개)."""
token = await _login_token(client)
all_total = (await _list(client, token)).json()["total"]
won_total = (await _list(client, token, result=1)).json()["total"]
assert won_total == 1 and all_total > won_total
+215
View File
@@ -0,0 +1,215 @@
"""공급사 재협상 요청/철회(IMK #15) 포털 e2e — 요청 접수 + 철회.
담당자 심사(승인/반려)는 negodata 백엔드 몫이고, 여기(포털)는 공급사가
sessions.custom.renegotiation 에 요청을 남기고(PENDING) 스스로 철회(CANCELED)하는 절반을 본다:
· 개찰(OPEN_*) 마감 + 본인 마지막 라운드 세션 → 요청 기록(PENDING) + 담당자 알림
· 낙찰(AWARDED) 건 → 요청 거부
· 남의 공급사 세션 → 거부(FORBIDDEN)
· 이미 대기 중인데 재요청 → 거부(중복 방지)
· 대기 중 철회 → CANCELED, 이후 재요청 허용
dev negosium_db 를 그대로 쓰므로(APP_ENV=local) 전용 테스트 행만 시드하고 끝나면 지운다.
"""
import uuid
import bcrypt
import pytest_asyncio
from sqlalchemy import text
from common.enums import CloseReason, QuotationStatus, RenegotiationStatus, SessionStatus
TEST_LOGIN_ID = "pytest_renego_user"
TEST_PW = "pytest1234"
TEST_SUPPLIER_NAME = "파이테스트재협상공급사"
MARK = "PYTESTRENEGO-" # 시드 식별용 prefix (item code / qt number)
@pytest_asyncio.fixture
async def renego_seed(db_engine):
"""공급사 + 로그인유저 + 재협상 후보 세션들을 시드하고 (supplier_id, sids, uids) 반환.
(code, quotation.status, close_reason, 소속 공급사) — 요청 자격은 견적 마감사유·소유로 갈린다.
"""
supplier_id = uuid.uuid4()
other_supplier_id = uuid.uuid4()
pw_hash = bcrypt.hashpw(TEST_PW.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
specs = [
("OPEN", QuotationStatus.CLOSED.value, CloseReason.OPEN_PRICE.value, supplier_id), # 개찰 → 요청 가능
("AWARD", QuotationStatus.CLOSED.value, CloseReason.AWARDED.value, supplier_id), # 낙찰 → 불가
("OTHER", QuotationStatus.CLOSED.value, CloseReason.OPEN_PRICE.value, other_supplier_id), # 남의 공급사
]
sids, uids = {}, {}
async def _cleanup(conn):
await conn.execute(text(f"DELETE FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%'"))
await conn.execute(text(f"DELETE FROM company.notifications WHERE ref_qt_id IN "
f"(SELECT qt_id FROM quotation.quotations WHERE number LIKE '{MARK}%')"))
await conn.execute(text(f"DELETE FROM quotation.quotations WHERE number LIKE '{MARK}%'"))
await conn.execute(text(f"DELETE FROM partner.items WHERE code LIKE '{MARK}%'"))
await conn.execute(text("DELETE FROM supplier.supplier_users WHERE id = :id"), {"id": TEST_LOGIN_ID})
await conn.execute(text("DELETE FROM partner.suppliers WHERE name = :n"), {"n": TEST_SUPPLIER_NAME})
async with db_engine.begin() as conn:
await _cleanup(conn)
await conn.execute(
text("INSERT INTO partner.suppliers (supplier_id, company_id, user_id, name) "
"VALUES (:sid, gen_random_uuid(), gen_random_uuid(), :name)"),
{"sid": supplier_id, "name": TEST_SUPPLIER_NAME},
)
await conn.execute(
text("INSERT INTO supplier.supplier_users (supplier_id, id, password, name, last_accessed_at, status, role) "
"VALUES (:sid, :id, :pw, '협상담당자', now(), 1, 1)"),
{"sid": supplier_id, "id": TEST_LOGIN_ID, "pw": pw_hash},
)
for code, quote_st, close_reason, sup in specs:
item_id, qt_id, session_id, user_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
sids[code], uids[code] = session_id, user_id
await conn.execute(
text("INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) "
"VALUES (:iid, gen_random_uuid(), gen_random_uuid(), :name, :code, :model, '테스트제조사')"),
{"iid": item_id, "name": f"상품 {code}", "code": f"{MARK}{code}", "model": f"MODEL-{code}"},
)
await conn.execute(
text("INSERT INTO quotation.quotations "
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, close_reason, "
" round, start_time, end_time) VALUES "
"(:qid, :uid, gen_random_uuid(), gen_random_uuid(), :name, :num, 2, :st, :cr, "
" 1, now() - make_interval(hours => 2), now() - make_interval(hours => 1))"),
{"qid": qt_id, "uid": user_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "st": quote_st, "cr": close_reason},
)
await conn.execute(
text("INSERT INTO negotiation.sessions "
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
" target_price, status, bid_price, end_time) VALUES "
"(:sesid, :qid, :iid, :sup, :qtn, 1, 2, 100000, :sst, 95000, now() - make_interval(hours => 1))"),
{"sesid": session_id, "qid": qt_id, "iid": item_id, "sup": sup, "qtn": f"{MARK}{code}", "sst": SessionStatus.DONE.value},
)
yield {"supplier_id": supplier_id, "sids": sids, "uids": uids}
async with db_engine.begin() as conn:
await _cleanup(conn)
async def _login_token(client):
r = await client.post("/v1/auth/login", json={"id": TEST_LOGIN_ID, "pw": TEST_PW})
return r.json()["access_token"]
async def _request(client, token, session_id, *, reason="가격 재검토", desired_price=90000):
return await client.post(
f"/v1/negotiation/session/{session_id}/renegotiation",
headers={"Authorization": f"Bearer {token}"},
json={"reason": reason, "desired_price": desired_price},
)
async def _cancel(client, token, session_id):
return await client.delete(
f"/v1/negotiation/session/{session_id}/renegotiation",
headers={"Authorization": f"Bearer {token}"},
)
async def _renego(db_engine, session_id):
async with db_engine.begin() as conn:
row = (await conn.execute(
text("SELECT custom FROM negotiation.sessions WHERE session_id = :sid"),
{"sid": session_id},
)).scalar()
return (row or {}).get("renegotiation") or {}
async def _notif_count(db_engine, qt_number):
async with db_engine.begin() as conn:
return (await conn.execute(
text("SELECT count(*) FROM company.notifications WHERE ref_qt_id IN "
"(SELECT qt_id FROM quotation.quotations WHERE number = :num)"),
{"num": qt_number},
)).scalar()
# ---- 요청 -------------------------------------------------------------------
async def test_request_records_pending(client, renego_seed, db_engine):
"""검증: 개찰(OPEN_PRICE) 마감 + 본인 마지막 라운드 세션에 재협상 요청.
기대결과: success + PENDING 기록(사유·희망가 저장) + 담당자 알림 1건."""
token = await _login_token(client)
sid = renego_seed["sids"]["OPEN"]
body = (await _request(client, token, sid, reason="원자재 인상 반영", desired_price=88000)).json()
assert body["result"]["success"] is True
assert body["status"] == RenegotiationStatus.PENDING.value
saved = await _renego(db_engine, sid)
assert saved["status"] == RenegotiationStatus.PENDING.value
assert saved["reason"] == "원자재 인상 반영"
assert saved["desired_price"] == 88000
assert await _notif_count(db_engine, f"{MARK}OPEN") == 1
async def test_request_twice_blocked(client, renego_seed, db_engine):
"""검증: 이미 대기(PENDING) 요청이 있는 세션에 다시 요청.
기대결과: 2번째는 거부(중복 방지) + 상태는 여전히 PENDING 1건."""
token = await _login_token(client)
sid = renego_seed["sids"]["OPEN"]
first = (await _request(client, token, sid)).json()
second = (await _request(client, token, sid)).json()
assert first["result"]["success"] is True
assert second["result"]["success"] is False
assert (await _renego(db_engine, sid))["status"] == RenegotiationStatus.PENDING.value
async def test_request_blocked_on_awarded(client, renego_seed, db_engine):
"""검증: 낙찰(AWARDED)로 마감된 건에 재협상 요청.
기대결과: 거부(낙찰 건은 재협상 불가) + custom.renegotiation 미기록."""
token = await _login_token(client)
sid = renego_seed["sids"]["AWARD"]
body = (await _request(client, token, sid)).json()
assert body["result"]["success"] is False
assert await _renego(db_engine, sid) == {}
async def test_request_forbidden_other_supplier(client, renego_seed, db_engine):
"""검증: 다른 공급사 소유 세션에 재협상 요청.
기대결과: 거부 + custom.renegotiation 미기록(소유 가드)."""
token = await _login_token(client)
sid = renego_seed["sids"]["OTHER"]
body = (await _request(client, token, sid)).json()
assert body["result"]["success"] is False
assert await _renego(db_engine, sid) == {}
# ---- 철회 -------------------------------------------------------------------
async def test_cancel_sets_canceled_and_allows_rerequest(client, renego_seed, db_engine):
"""검증: 대기 중 요청을 철회한 뒤 다시 요청.
기대결과: 철회 시 CANCELED → 재요청 시 다시 PENDING(철회 건은 재요청 허용)."""
token = await _login_token(client)
sid = renego_seed["sids"]["OPEN"]
await _request(client, token, sid)
cancelled = (await _cancel(client, token, sid)).json()
assert cancelled["result"]["success"] is True
assert cancelled["status"] == RenegotiationStatus.CANCELED.value
assert (await _renego(db_engine, sid))["status"] == RenegotiationStatus.CANCELED.value
again = (await _request(client, token, sid)).json()
assert again["result"]["success"] is True
assert (await _renego(db_engine, sid))["status"] == RenegotiationStatus.PENDING.value
async def test_cancel_requires_pending(client, renego_seed, db_engine):
"""검증: 대기 요청이 없는 세션에 철회 시도.
기대결과: 거부(철회할 대기 요청 없음)."""
token = await _login_token(client)
sid = renego_seed["sids"]["OPEN"]
body = (await _cancel(client, token, sid)).json()
assert body["result"]["success"] is False
+51
View File
@@ -0,0 +1,51 @@
"""공급사 관점 협상 결과 파생(SessionResult) 단위 테스트.
목록의 result 코드는 견적 마감상태·마감사유·낙찰자로 파생한다(DDL 무변경). 공급사가 이 배지로
'내가 낙찰인지 / 결렬이라 재협상 요청 대상인지'를 구분한다. 결렬(3)만 renegotiable 과 짝을 이룬다.
"""
import uuid
from common.enums import CloseReason, QuotationStatus
from services.negotiation_service import NegotiationService
_R = NegotiationService._to_result
ME = uuid.uuid4()
OTHER = uuid.uuid4()
CLOSED = QuotationStatus.CLOSED.value
def test_result_undecided_before_close():
"""검증: 견적이 아직 마감 전(진행중)이면 결과 미정.
기대결과: 0(미정)."""
assert _R(QuotationStatus.IN_PROGRESS.value, None, None, ME) == 0
def test_result_won_when_winner_is_me():
"""검증: 낙찰(AWARDED) 마감 + 낙찰자가 나.
기대결과: 1(낙찰)."""
assert _R(CLOSED, CloseReason.AWARDED.value, ME, ME) == 1
def test_result_lost_when_winner_is_other():
"""검증: 낙찰 마감이지만 낙찰자가 남.
기대결과: 2(미낙찰)."""
assert _R(CLOSED, CloseReason.AWARDED.value, OTHER, ME) == 2
def test_result_lost_when_awarded_without_winner_id():
"""검증: 낙찰인데 낙찰자 id 가 비어 나와 대조 불가.
기대결과: 2(미낙찰) — 낙찰이라 단정 못 하면 낙찰로 오인시키지 않는다."""
assert _R(CLOSED, CloseReason.AWARDED.value, None, ME) == 2
def test_result_open_is_renegotiable():
"""검증: 개찰(OPEN_*) 4종으로 마감(낙찰자 미정=결렬).
기대결과: 전부 3(결렬) — 재협상 요청 대상."""
for cr in (CloseReason.OPEN_PRICE, CloseReason.OPEN_EQUAL, CloseReason.OPEN_NOSHOW, CloseReason.OPEN_REJECT):
assert _R(CLOSED, cr.value, None, ME) == 3, cr
def test_result_none_when_closed_without_reason():
"""검증: 마감됐지만 close_reason 이 아직 없음(경계).
기대결과: 0(미정) — 낙찰/결렬 어느 쪽도 아님."""
assert _R(CLOSED, None, None, ME) == 0
+214
View File
@@ -0,0 +1,214 @@
services:
# ── 프론트 (React/Vite → 정적 빌드 → nginx) ──────────────────────────────
negodata-front:
build:
context: ./negodata/front
dockerfile: Dockerfile.prod
container_name: negodata-front
ports:
- "${NEGODATA_FRONT_PORT:-30012}:80"
depends_on:
- negodata-backend # nginx 가 시작 시 upstream(negodata-backend) 이름을 해석해야 함
restart: unless-stopped
negosium-front:
build:
context: ./frontend
dockerfile: Dockerfile.prod
container_name: negosium-front
ports:
- "${NEGOSIUM_FRONT_PORT:-30010}:80"
depends_on:
- negosium-backend
restart: unless-stopped
# ── 솔루션 랜딩 (React Router SSG → 정적 빌드 → nginx) ───────────────────
landing:
build:
context: ./landing
dockerfile: Dockerfile.prod
container_name: negosium-landing
ports:
- "${LANDING_PORT:-30013}:80"
restart: unless-stopped
# ── 백엔드 (FastAPI, 기존 Dockerfile) ────────────────────────────────────
negodata-backend:
build: ./negodata/backend
container_name: negodata-backend
environment:
APP_ENV: prod
SCHEDULER_ENABLED: "1" # 견적 자동마감 크론(process_count=1 단일 워커라 중복 없음)
PYTHONUNBUFFERED: "1"
LPS_BASE_URL: http://lps-api:9600 # 최저가 검색요청 enqueue — 같은 compose 망의 lps-api 컨테이너(미설정 시 localhost:9600 → 연결실패)
# LPS 읽기 DB(lps_db)는 config.prod.toml 의 [LpsDBConfig](172.30.1.36/o2o_db_admin) 이 담당 → 별도 env 불필요
DB_HOST: ${DB_HOST} # toml 의 127.0.0.1 을 외부 DB 로 override
DB_PORT: ${DB_PORT:-5432}
DB_USER: ${DB_USER}
DB_PASSWORD: ${DB_PASSWORD}
DB_NAME: ${DB_NAME:-negosium_db}
volumes:
- ./negodata/backend/config/config.prod.toml:/app/config/config.prod.toml:ro
# 외부 비노출 — negodata-front 의 nginx 가 /v1 을 내부망으로 프록시.
extra_hosts:
- "host.docker.internal:host-gateway" # DB 가 이 서버 호스트면 DB_HOST=host.docker.internal
restart: unless-stopped
negosium-backend:
build: ./backend
container_name: negosium-backend
environment:
APP_ENV: prod
AGENT_BASE_URL: http://agent:9500 # 내부망으로 agent 호출
PYTHONUNBUFFERED: "1"
DB_HOST: ${DB_HOST}
DB_PORT: ${DB_PORT:-5432}
DB_USER: ${DB_USER}
DB_PASSWORD: ${DB_PASSWORD}
DB_NAME: ${DB_NAME:-negosium_db}
volumes:
- ./backend/config/config.prod.toml:/app/config/config.prod.toml:ro
# 외부 비노출 — negosium-front 의 nginx 가 /v1 을 내부망으로 프록시.
extra_hosts:
- "host.docker.internal:host-gateway"
restart: unless-stopped
# ── 협상 에이전트 (Python, 내부 전용) ────────────────────────────────────
agent:
build: ./agent
container_name: negosium-agent
environment:
APP_ENV: prod
PYTHONUNBUFFERED: "1"
DB_HOST: ${DB_HOST}
DB_PORT: ${DB_PORT:-5432}
DB_USER: ${DB_USER}
DB_PASSWORD: ${DB_PASSWORD}
DB_NAME: ${DB_NAME:-negosium_db}
volumes:
- ./agent/config/config.prod.toml:/app/config/config.prod.toml:ro
extra_hosts:
- "host.docker.internal:host-gateway"
restart: unless-stopped
# ── 앵커링 값 자동 조정 배치 (negosium_db 공유, 포트 없음 — 상주 스케줄러) ──
# 이미지는 config.{APP_ENV}.toml 을 읽는다(dev/prod 는 파일 없으면 기동 중단). DB/시크릿은
# config.prod.toml(172.30.1.36) 에서 온다 — env(DB_*/REDIS_*) 를 설정하면 파일값을 override.
anchoring:
build: ./schedules/anchoring
container_name: anchoring
environment:
APP_ENV: prod # → config.prod.toml 선택 (local 로 두면 빈 config.local 로 기동 실패)
REDIS_HOST: anchoring-redis # 전용 캐시 컨테이너 사용(config 의 redis host 를 override)
TZ: Asia/Seoul
volumes:
- ./schedules/anchoring/config.prod.toml:/app/config.prod.toml:ro # DB 접속·시크릿은 파일에서(마운트 필수)
depends_on:
- anchoring-redis
extra_hosts:
- "host.docker.internal:host-gateway"
restart: unless-stopped
logging: # 상주 배치 — 장기 운영 디스크 보호
driver: json-file
options:
max-size: "10m"
max-file: "5"
# 앵커링 조회 캐시 (anchoring 전용)
anchoring-redis:
image: redis:7-alpine
container_name: anchoring-redis
ports:
- "127.0.0.1:6380:6379" # 호스트 로컬만 개방 (무인증 Redis). 6380 = 호스트 redis(6379)와 충돌 회피
restart: unless-stopped
logging:
driver: json-file
options:
max-size: "10m"
max-file: "5"
# ── LPS (인터넷 최저가 검색) ──────────────────────────────────
# API(요청 접수) + 워커(크롤, Chromium+Xvfb).
# 이미지는 APP_ENV=local 고정 → config.local.toml 을 읽는다. prod 실값(DB 172.30.1.36 /
# o2o_db_admin / negosium_db + OpenAI·Naver·Decodo 시크릿)은 config.prod.toml 을 그 경로에
# 마운트해 주입한다(다른 prod 서비스와 동일한 파일 기반 방식). DB_* env 는 주지 않는다 —
# 주면 파일값을 빈 값/오타로 덮어써 인증 실패(예: 사용자 o2oadmin)한다.
lps-api:
build:
context: ./lps
dockerfile: Dockerfile
container_name: lps-api
environment:
APP_ENV: local # 이미지 고정값 — 변경 금지(config.prod.toml 을 직접 읽지 않음)
PYTHONUNBUFFERED: "1"
PROCESS_COUNT: ${LPS_API_PROCESS_COUNT:-1}
DB_CONNECTION_BUDGET: ${LPS_DB_CONNECTION_BUDGET:-40} # 전용 PG(max_connections≈100)면 90 근처로 상향
volumes:
- ./lps/config/config.prod.toml:/app/config/config.local.toml:ro # prod DB·시크릿 주입(APP_ENV=local 이 읽는 경로 덮어씀)
ports:
- "9600:9600"
extra_hosts:
- "host.docker.internal:host-gateway"
labels:
autoheal: "true" # HEALTHCHECK 실패 시 autoheal 이 재시작
restart: unless-stopped
logging:
driver: json-file
options: { max-size: "10m", max-file: "5" }
lps-worker:
build:
context: ./lps
dockerfile: Dockerfile.worker # Chromium + Xvfb (headless 는 안티봇에 탐지됨)
container_name: lps-worker
environment:
APP_ENV: local # 이미지 고정값 — 변경 금지
PYTHONUNBUFFERED: "1"
WORKER_CONCURRENCY: "1" # 상품 동시 검색 수(워커별 브라우저 세트, Chrome 4×N)
LPS_PROFILE_DIR: /profiles # Chrome 프로필을 영속 볼륨에 → 재시작해도 cf_clearance 유지
# DB·시크릿(OpenAI/Naver/Decodo)은 아래 config.prod.toml 마운트에서 온다. env override 는 주지 않는다.
volumes:
- ./lps/config/config.prod.toml:/app/config/config.local.toml:ro # prod DB·시크릿 주입(APP_ENV=local 이 읽는 경로 덮어씀)
- lps-profiles:/profiles # Chrome 프로필(쿠키) 영속
extra_hosts:
- "host.docker.internal:host-gateway"
shm_size: "1gb" # Chrome 는 /dev/shm 을 많이 씀 — 부족하면 탭 크래시
stop_grace_period: 75s # graceful 종료 유예 — 기본 10s 면 하던 잡 마무리 전에 SIGKILL
labels:
autoheal: "true" # 하트비트 HEALTHCHECK 실패(행/좀비) 시 autoheal 이 재시작
restart: unless-stopped
logging:
driver: json-file
options: { max-size: "10m", max-file: "5" }
# LPS 관리자 UI (정적 React → nginx). /v1·/healthz·/readyz 는 nginx 가 lps-api:9600 으로 프록시(동일 compose 망).
lps-admin:
build:
context: ./lps-admin
dockerfile: Dockerfile
container_name: lps-admin
ports:
- "${LPS_ADMIN_PORT:-30014}:80"
depends_on:
- lps-api
restart: unless-stopped
logging:
driver: json-file
options: { max-size: "10m", max-file: "5" }
# HEALTHCHECK 실패 컨테이너 자동 재시작 — autoheal 라벨 붙은 컨테이너(lps-api/lps-worker)를 감시해 재시작.
# docker.sock 마운트 = 도커 제어 권한이므로 신뢰 환경에서만 사용.
autoheal:
image: willfarrell/autoheal:latest
container_name: autoheal
environment:
AUTOHEAL_CONTAINER_LABEL: autoheal
volumes:
- /var/run/docker.sock:/var/run/docker.sock
restart: unless-stopped
logging:
driver: json-file
options: { max-size: "10m", max-file: "5" }
volumes:
lps-profiles:
+101
View File
@@ -7,8 +7,11 @@
# negosium 서버: http://localhost:9300/docs
# negosium 프론트: http://localhost:3300
# negodata 서버: http://localhost:9400/docs
# 솔루션 랜딩: http://localhost:3100
# agent 서버: http://localhost:9500/docs
# anchoring 배치: 포트 없음 — 상주 스케줄러(격주 토 00:00 KST), docker logs anchoring 으로 확인
# lps API: http://localhost:9600/docs
# lps admin: http://localhost:3400 (nginx → /v1·/healthz 는 lps-api 로 프록시)
#
# DB 준비(최초 1회): postgres-init 의 SQL 을 대상 DB 에 적용한다.
# psql -h <host> -p <port> -U <user> -f postgres-init/00-init.sql (스키마 전체: negosium_db + 도메인·learning·anchoring schema)
@@ -38,6 +41,10 @@ services:
RELOAD: "1" # uvicorn --reload 활성 → 소스 저장 시 자동 재기동(재빌드 불필요)
SCHEDULER_ENABLED: "1" # 마감 크론 활성(단일 워커라 중복 없음). 운영 다중 워커면 1개 프로세스에서만 1
PYTHONUNBUFFERED: "1" # 컨테이너 로그 실시간 출력(stdout 버퍼링 끔)
# ── LPS(인터넷 최저가) 연동 — 미설정이면 연동 비활성으로 조용히 동작 ──
LPS_DB_HOST: host.docker.internal # lps_db 읽기전용(수집 배치·조회 API)
LPS_BASE_URL: http://host.docker.internal:9600 # 검색요청 enqueue. lps-api 컨테이너 사용 시 http://lps-api:9600
# LPS API guard 키는 negodata 의 config.local.toml [WebServerConfig].lps_api_key 로 관리(개발은 빈값=개방)
volumes:
- ./negodata/backend:/app # 호스트 소스 = 컨테이너 코드. 이게 있어야 수정이 즉시 반영됨
ports:
@@ -57,6 +64,17 @@ services:
- /app/node_modules
restart: unless-stopped
# 솔루션 랜딩페이지 (react-router dev 서버. 배포는 `npm run build` 산출물 build/client 정적 서빙).
landing:
build: ./landing
container_name: negosium-landing
ports:
- "3100:3100"
volumes:
- ./landing:/app
- /app/node_modules
restart: unless-stopped
# 협상 에이전트 (negosium_db 공유, learning 스키마 사용).
agent:
build: ./agent
@@ -113,3 +131,86 @@ services:
options:
max-size: "10m"
max-file: "5"
# LPS API (인터넷 최저가 검색 — 요청 접수/조회, lean). 설정·시크릿은 config.local.toml 하나(미커밋, 마운트).
lps-api:
build:
context: ./lps
dockerfile: Dockerfile
container_name: lps-api
environment:
APP_ENV: local
DB_HOST: ${LPS_DB_HOST-host.docker.internal} # 컨테이너→호스트 DB (config.local.toml 의 127.0.0.1 override)
PYTHONUNBUFFERED: "1"
volumes:
- ./lps/config/config.local.toml:/app/config/config.local.toml:ro
ports:
- "${LPS_API_BIND:-0.0.0.0}:9600:9600" # prod 는 LPS_API_BIND=127.0.0.1 로 내부만 개방(리버스프록시 뒤)
extra_hosts:
- "host.docker.internal:host-gateway"
labels:
autoheal: "true" # HEALTHCHECK 실패 시 autoheal 이 재시작
restart: unless-stopped
logging:
driver: json-file
options: { max-size: "10m", max-file: "5" }
# LPS 워커 (크롤 — 헤드풀 Chromium+Xvfb, headless 는 안티봇에 탐지됨). config.local.toml 공유.
lps-worker:
build:
context: ./lps
dockerfile: Dockerfile.worker
# google-chrome-stable(Linux)은 amd64 전용 → 이미지 자체가 amd64. arm64 맥에선 명시 없으면
# arm64 로 빌드를 시도하다 Chrome 의존성에서 실패한다(Rosetta 로 에뮬 실행). prod(amd64)에선 무영향.
platform: linux/amd64
container_name: lps-worker
environment:
APP_ENV: local
DB_HOST: ${LPS_DB_HOST-host.docker.internal} # 컨테이너→호스트 DB (config.local.toml 의 127.0.0.1 override)
PYTHONUNBUFFERED: "1"
volumes:
- ./lps/config/config.local.toml:/app/config/config.local.toml:ro
- lps-profiles:/profiles # Chrome 프로필(쿠키) 영속
extra_hosts:
- "host.docker.internal:host-gateway"
shm_size: "1gb" # Chrome 는 /dev/shm 을 많이 씀 — 부족하면 탭 크래시
stop_grace_period: 75s # graceful 종료 유예(worker shutdown_grace_sec=60 + 여유)
labels:
autoheal: "true" # 하트비트 실패(행/좀비) 시 autoheal 재시작
restart: unless-stopped
logging:
driver: json-file
options: { max-size: "10m", max-file: "5" }
# LPS 관리자 UI (정적 React → nginx). /v1·/healthz·/readyz 는 nginx 가 lps-api:9600 으로 프록시(앱은 상대경로 호출).
lps-admin:
build:
context: ./lps-admin
dockerfile: Dockerfile
container_name: lps-admin
ports:
- "3400:80"
depends_on:
- lps-api
restart: unless-stopped
logging:
driver: json-file
options: { max-size: "10m", max-file: "5" }
# HEALTHCHECK 실패 컨테이너 자동 재시작 — compose 의 restart 는 '프로세스 종료'만 다루고
# unhealthy 는 표시만 하므로, autoheal 라벨 붙은 컨테이너(lps-api/lps-worker)를 감시해 재시작한다.
# docker.sock 마운트 = 도커 제어 권한이므로 신뢰 환경에서만 사용.
autoheal:
image: willfarrell/autoheal:latest
container_name: autoheal
environment:
AUTOHEAL_CONTAINER_LABEL: autoheal
volumes:
- /var/run/docker.sock:/var/run/docker.sock
restart: unless-stopped
logging:
driver: json-file
options: { max-size: "10m", max-file: "5" }
volumes:
lps-profiles:
+108
View File
@@ -0,0 +1,108 @@
# 협상 QA 체크리스트 (260727 요청 검증)
> 대상: **negodata 어드민**(:3000) + **negosium 공급사 포털**(:3300). 두 앱을 함께 돌려야 하는 플로우라 루트 `docs/`에 둔다.
> 형식: 케이스별 `~하면 → ~나와야 한다`. 근거는 코드 검증(2026-07-30) 기준. ⚠=현재 알려진 이슈.
> 런타임 주의: negosium front/backend는 이미지 빌드라 코드 수정은 **재빌드해야 반영**된다.
---
## 0. 요청사항 반영 현황 (코드 검증 결과, Excel 상태열 아님)
| # | 요청 | 판정 | 비고 |
|---|------|------|------|
| 2 | 견적관리 리스트+히스토리·상세 | ✅ | /quotation + `?detail=` 시트(협상현황/대화/카드, 라운드 타임라인) |
| 3 | 재협상 리스트·심사 | ✅ | /renegotiation 대기/승인/반려 |
| 4 | MD→구매담당자·판매가 미노출·위치 | ✅ | |
| 5/23 | 목표가=매입가×(1−네고율) 자동 | ✅ | 재/재견적 한정, 네고율=견적세팅 목표마진 |
| 6 | 공급가=매입가 일원화 | ⚙ 설정 | 코드 지원됨(`hideCls`). IMK `hidden_fields`에 `"price"` 추가하면 매입가만 남음 |
| 7 | 최저가 크롤 + VAT산식 | ⚠ 인프라 / 논이슈 | VAT는 설정·아이템별 처리(논이슈). 단 dev의 lps-worker 크래시+수집테이블 0행 → 수집 파이프라인 확인 필요 |
| 8 | 신규 상품 공급사 입력칸 | ✅ | |
| 9 | SG명/유통레벨 콤보·취급상품 삭제 | ❌ 미구현 | §9 참조 |
| 10 | 리드타임→표준납기 | ✅ 수정 | Summary.tsx 하드코딩 라벨 회사설정 반영으로 수정(2026-07-30) |
| 11 | 단가 VAT별도 | ✅ | 회사설정 `item_vat_yn` 동적(IMK는 vat_yn hidden) |
| 12 | 앵커 10원 반올림 | ✅ | `calc_anchoring_price` + 카드 카운터(`compute_counter`) + 와일드카드 1%(2026-07-31 수정) 모두 10원 반올림 |
| 13 | 절충안 계산식 | ✅ | `compute_counter` 점검, 버그 없음 |
| 14/17 | 결렬 희망가 입력란 통일 | ✅ | 단일 RejectForm |
| 15 | 마무리 배송 콤보/기타의견/투찰요약 | ✅ | ExtraInfoBar가 session_fields select 렌더 → 콤보 [직납/IMK배송/IMK집배송] |
| 16 | 제안가 갭·반올림 | ✅ | 갭은 정상(목표가=후보 min×수수료). 봇 제안가(카운터·와일드카드 1%)도 10원 반올림 반영(2026-07-31) |
| 18/22 | 성공률 기준·결렬 무관 | ✅ | 게이지는 참고용, 판정과 무관(§D). 타결=목표가 아래로/봇 카운터 수락, 결렬=카드3+최종제안 소진까지 목표가 위 |
| 19/25 | 종료 의견 단계 | ✅ | 타결 ExtraInfoBar(custom.opinion)+결렬 RejectForm 의견 |
| 20 | 결렬사유 상시노출·필수 | ✅ 검증 | 결렬 세션 9/9 사유 존재. §20 참조 |
| 21 | 카드 3회 초과 | ✅ 정상 | 3회=협상카드 한도. 와일드카드·최종제안은 별도로 붙는 구조라 보이는 카드가 3장을 넘을 수 있음(§21) |
| 24 | 목표가 필드 1→3.낙찰기준 이동 | ✅ | |
---
## A. 견적 생성 (어드민)
- **A1** 재/재견적에서 매입가 10,000·네고율(견적세팅 목표마진) 2% 입력 → 목표가(구매담당자 제시가) 필드에 **9,800 자동 채움**(10원 반올림)
- **A2** 목표가 직접 안 건드리고 생성 → `md_price=null`로 전송, 서버가 후보 최솟값으로 재산정
- **A3** **신규**협상/신규견적 → 매입가 후보 빠지고 인터넷최저가만 사용 → 자동 목표가가 매입가 기반이 아님(A1과 다른 게 정상)
- **A4** 1.기본정보엔 목표가 없어야 / **3.낙찰기준** 스텝에 목표가+산정후보 나와야
- **A5** 판매가 입력칸 없어야 / 라벨 "구매담당자 제시가"
## B. 앵커·제안가
- **B1** 협상 시작 → 세션 앵커가 = 목표가×(1−1%), **끝자리 0** (예 목표 7,650 → 앵커 7,570)
- **B2** 봇 재제안가 전부 **끝자리 0** — 카드 카운터(절충가·목표가 제시)와 **와일드카드 1% 인하가** 포함 (예 제시 15,555 → 1% 인하가 15,400). 1원 단위가 보이면 불량
## C. 협상 진행 (실시간 챗, 공급사 포털)
- **C1** 제시가 **≤ 앵커가** → **즉시 협상완료(투찰 확정)**, 성공률 99
- **C2** 앵커가 < 제시가 ≤ 앵커×1.02 → **와일드카드 1% 인하 요청**(세션 1회), 성공률 99~80
- **C3** 앵커×1.02 초과 → **일반 협상카드로 재제안(최대 3번)**, 성공률 표시(제시가 낮을수록↑)
- **C4** 카드 소진 또는 재제안 3번 후에도 앵커 밑 못 내림 → **협상 실패(결렬, 투찰 없음)**
- **C5** 카드 사용한도 3은 **협상카드에만** 적용. **와일드카드·최종제안은 별도로 붙어** 공급사가 보는 카드가 3장을 넘을 수 있음(정상, §21)
- **C6** 단가는 **VAT별도** 표기(IMK는 VAT 라벨 자체 숨김)
## D. 타결/결렬 판정 & 성공률 게이지
- **판정 규칙**: 유저가 **목표가 아래로 내리거나** 봇이 되받은 제시가(카운터)를 **수락하면 타결**. **카드(3장)+최종제안**까지 다 소진될 때까지 **목표가 위에서 버티면 결렬**.
- **D1** 성공률 게이지는 **참고용일 뿐 판정과 무관** — 제시가 낮을수록 게이지↑(상한 99, **100% 도달 안 함**).
- **D2** 성공률 낮아도 무조건 결렬 아님. 최종 마감(낙찰/개찰)은 별도 기준(§G).
## E. 협상 타결(완료) 마무리
- **E1** 협상완료 → **부가정보 입력 단계 등장** (표준납기·최소주문수량·발주배수·배송유형·의견)
- **E2** 배송유형 → **콤보 [직납/IMK배송/IMK집배송]**로 떠야 (자유입력·다른 라벨이면 불량)
- **E3** 의견(선택) 작성 → `custom.opinion` 저장돼야
- **E4** 입력 완료 → **투찰결과 요약 갱신 후 최종 안내**, 요약에 부가정보·의견 반영
- **E5** 어드민 상세(협상현황/요약)에서 부가정보 **표시+잠금(읽기전용)**
## F. 협상 결렬(실패)
- **F1** 결렬 → **결렬 사유 입력 단계 항상 노출 + 필수**(견적/유형 무관 동일 폼)
- **F2** 사유 프리셋(단가인상/수량/단종/품절)+기타, **기타 선택 시 사유 텍스트 필수**
- **F3** 희망가격 입력 = **단일 폼**(RSP/CM 동일)
- **F4** 의견(선택) 작성 가능
- **F5** 검증: 결렬(협상거부) 세션은 **100% 사유가 기록**돼야 (사유 없는 결렬 세션 = 불량). §20
## G. 마감 · 낙찰/개찰
- **G1** 투찰가 ≤ 앵커가 → **낙찰**
- **G2** 앵커~목표가 → 1:1은 **사용자 지정**(mid_action), 1:N은 낙찰
- **G3** 목표가 초과 → 1:1 **사용자 지정**(over_action, 관례 개찰), 1:N 낙찰
- **G4** 동가(최저 2곳+)·전원 미응찰·협상거부 → **개찰**(낙찰자 미정, 결렬 아님) / 마감사유 라벨 정확히
## H. 재협상 요청·심사 (공급사→어드민)
- **H1** 개찰 마감 + 본인 마지막 라운드 → **재협상 요청 가능**(사유+희망가), 담당자 알림 1건
- **H2** 낙찰건/남의 세션 요청 → **거부**
- **H3** 같은 세션 2회 요청 → 2번째 **거부**; 철회 후 재요청 가능
- **H4** 어드민 /renegotiation 대기 탭 접수 → **승인 시 다음 차수 견적 생성**, 반려 시 사유 필수
---
## 알려진 이슈 상세
### §9. 협력사 SG명/유통레벨 콤보·취급상품 삭제 — 미구현
요청 4가지 모두 현재 구조와 다르다:
1. **분류카테고리 → SG명**: 지금 '분류카테고리'는 **입력 필드가 아니라 취급상품에서 파생 집계**되는 읽기전용 값(`SupplierItemsManager.tsx`). 회사 라벨(labels.category)로 "SG명" 표기만 되지, 직접 고르는 필드가 아님.
2. **선택콤보(취급 SG명)**: 등록된 SG명 중 선택하는 콤보 없음.
3. **유통레벨 콤보(제조/총판/대리점/일반유통)**: 없음. 유사한 건 취급상품별 **공급유형** 콤보인데 값이 다름(유통/제조/총판/없음). '대리점'·'일반유통' 값 자체가 코드에 없음. IMK 설정의 `supplier_fields.distribution_level`은 콤보가 아니라 **텍스트** 커스텀 필드.
4. **취급상품 칸 삭제**: 삭제 안 됨(등록/수정폼·엑셀업로드에 그대로).
- 근본: IMK는 SG명·유통레벨을 **협력사 레벨 속성(콤보)**으로 두고 취급상품 목록은 없애길 원함. 현재는 반대로 **취급상품(supplier_items)에서 카테고리·공급유형을 파생**하는 모델. → 데이터 모델 전환이 필요한 작업.
### §20. 결렬 사유 상시 노출·필수 — 검증 완료
- agent의 모든 실패 경로가 단일 step `"협상실패"`(chat_end)로 수렴 → backend가 rejectRSP/CM로 무조건 매핑 → 프론트 통일 RejectForm(사유 필수). 세션 상태 분기 없음.
- 실데이터: 협상거부(status=5) 9건 **전부 reject_reason 존재**, 사유 없는 결렬 0건.
- 원 버그의 "견적마다 상이"는 *대화 중 결렬*(사유 있음) vs *미참여/마감 자동종료*(대화 자체 없음 → 사유 없음)의 구분이었을 뿐, 결렬 플로우는 일관됨.
### §21. 카드 3회 초과 — 정상 동작(버그 아님)
`card_count=3`은 **협상카드 사용 한도**다. 와일드카드와 최종제안(종결)은 이 한도와 **별개로 각각 붙는** 구조라, 공급사가 보는 카드가 3장을 넘을 수 있다.
1. **와일드카드 1장**(1% 인하/동적 카운터) — 협상카드 카운트와 별개.
2. **최종제안 1장**(중간값 절충/최후통첩) — 카드 소진 후 마지막 국면에 별도로 붙음.
→ 협상카드 3 + 와일드 1 + 최종제안 1 = 최대 5장 노출(예: EST-202607-4DB5).
- 참고(엣지): 세션에 견적세팅(card_count)이 연결 안 되면 한도가 안 걸릴 수 있으니, 설정이 항상 세션에 물리는지만 확인.
+1 -1
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/bot.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<title>AI 가격 협상 솔루션</title>
</head>
<body>
+7
View File
@@ -11,6 +11,7 @@ import type {
LogoutResponse,
MeResponse,
PopupStatusResponse,
SessionBrandingResponse,
} from './auth.type'
export const authApi = {
@@ -26,6 +27,12 @@ export const authApi = {
return res.data
},
/** GET /v1/auth/session-branding/{sessionId} — 로그인 전 화면용 브랜딩(인증 불필요) */
sessionBranding: async (sessionId: string): Promise<SessionBrandingResponse> => {
const res = await http.get<SessionBrandingResponse>(`/v1/auth/session-branding/${sessionId}`)
return res.data
},
/** GET /v1/auth/me — 현재 로그인 유저 정보 (access token 필요) */
me: async (): Promise<MeResponse> => {
const res = await http.get<MeResponse>('/v1/auth/me')
+29
View File
@@ -54,6 +54,29 @@ export interface RefreshTokenResponse {
}
// --- 내 정보 (GET /v1/auth/me) -------------------------------------------
export interface Branding {
service_name?: string
logo_url?: string
primary_color?: string
email_header?: string
}
// 로그인 전(초청 링크 진입) 브랜딩 조회 — GET /v1/auth/session-branding/{session_id}, 인증 불필요
export interface SessionBrandingResponse {
result: ApiResult
service_name: string
logo_url: string
primary_color: string
}
// 협상완료 부가정보 필드 정의(companies.settings.session_fields)
export interface SessionField {
key: string
label: string
type: 'text' | 'number' | 'boolean' | 'select'
options?: string[] // type='select' 일 때 고를 보기 목록
}
export interface MeResponse {
result: ApiResult
su_id: string
@@ -62,6 +85,8 @@ export interface MeResponse {
supplier_id: string
supplier_name: string
role: number
branding?: Branding
session_fields?: SessionField[]
}
// --- 로그아웃 -------------------------------------------------------------
@@ -94,6 +119,8 @@ export interface AuthUser {
supplierId: string
supplierName: string
role: number
branding: Branding
sessionFields: SessionField[]
}
export function toAuthUser(res: MeResponse): AuthUser {
@@ -104,5 +131,7 @@ export function toAuthUser(res: MeResponse): AuthUser {
supplierId: res.supplier_id,
supplierName: res.supplier_name,
role: res.role,
branding: res.branding ?? {},
sessionFields: res.session_fields ?? [],
}
}
+6
View File
@@ -32,6 +32,7 @@ export interface ChatInitResponse {
session_id: string
session_status: number
quotation_id: string
qt_number?: string
quotation_end_time: string
quotation_memo?: string
item_id: string
@@ -46,6 +47,8 @@ export interface ChatInitResponse {
item_min_order_quantity?: string
item_vat_yn?: boolean
item_delivery_fee_yn?: boolean
custom?: Record<string, unknown>
labels?: Record<string, string>
}
export interface ChatMessagesResponse {
@@ -88,6 +91,7 @@ export function mapInit(r: ChatInitResponse): ChatInitData {
session_status: r.session_status,
item_id: r.item_id,
quotation_id: r.quotation_id,
qt_number: r.qt_number ?? '',
item_name: r.item_name,
item_code: r.item_code ?? '',
item_image: r.item_image ?? '',
@@ -98,9 +102,11 @@ export function mapInit(r: ChatInitResponse): ChatInitData {
item_delivery_fee_yn:
r.item_delivery_fee_yn == null ? '' : r.item_delivery_fee_yn ? '배송비포함' : '배송비별도',
item_min_order_quantity: r.item_min_order_quantity ?? '',
custom: r.custom ?? {},
item_lead_time: r.item_lead_time ?? '',
item_spec: r.item_spec ?? '',
quotation_memo: r.quotation_memo ?? '',
quotation_end_time: r.quotation_end_time ?? '',
labels: r.labels ?? {},
}
}
+7 -1
View File
@@ -2,5 +2,11 @@
export { negotiationApi } from './negotiation.api'
export { negotiationKeys } from './negotiation.keys'
export { useSessionListQuery } from './negotiation.queries'
export { useParticipateMutation, useRejectMutation } from './negotiation.mutations'
export {
useCancelRenegotiationMutation,
useParticipateMutation,
useRejectMutation,
useRequestRenegotiationMutation,
useSaveExtraInfoMutation,
} from './negotiation.mutations'
export * from './negotiation.type'
@@ -1,9 +1,13 @@
// 협상 엔드포인트 호출 함수 (순수 HTTP 레이어, React 의존 없음).
import { http } from '@/apis/http'
import type {
ExtraInfoRequest,
ExtraInfoResponse,
ParticipateResponse,
RejectRequest,
RejectResponse,
RenegotiationRequest,
RenegotiationResponse,
SessionListParams,
SessionListResponse,
} from './negotiation.type'
@@ -31,4 +35,30 @@ export const negotiationApi = {
)
return res.data
},
/** POST /v1/negotiation/session/{id}/renegotiation — 결렬 건 재협상 요청 */
requestRenegotiation: async (sessionId: string, body: RenegotiationRequest): Promise<RenegotiationResponse> => {
const res = await http.post<RenegotiationResponse>(
`/v1/negotiation/session/${sessionId}/renegotiation`,
body,
)
return res.data
},
/** DELETE /v1/negotiation/session/{id}/renegotiation — 심사 대기 중인 요청 철회 */
cancelRenegotiation: async (sessionId: string): Promise<RenegotiationResponse> => {
const res = await http.delete<RenegotiationResponse>(
`/v1/negotiation/session/${sessionId}/renegotiation`,
)
return res.data
},
/** POST /v1/negotiation/sessions/{id}/extra-info — 협상완료 부가정보 저장 */
saveExtraInfo: async (sessionId: string, body: ExtraInfoRequest): Promise<ExtraInfoResponse> => {
const res = await http.post<ExtraInfoResponse>(
`/v1/negotiation/sessions/${sessionId}/extra-info`,
body,
)
return res.data
},
}
@@ -2,7 +2,7 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { negotiationApi } from './negotiation.api'
import { negotiationKeys } from './negotiation.keys'
import type { RejectRequest } from './negotiation.type'
import type { ExtraInfoRequest, RejectRequest, RenegotiationRequest } from './negotiation.type'
/**
* 협상 세션 참여: 성공 시 세션 목록 캐시를 무효화해 상태를 갱신한다.
@@ -30,3 +30,38 @@ export function useRejectMutation() {
},
})
}
/**
* 협상완료 부가정보 저장: 성공 시 세션 목록 캐시를 무효화한다.
*/
export function useSaveExtraInfoMutation() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ sessionId, request }: { sessionId: string; request: ExtraInfoRequest }) =>
negotiationApi.saveExtraInfo(sessionId, request),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() })
},
})
}
export function useRequestRenegotiationMutation() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ sessionId, request }: { sessionId: string; request: RenegotiationRequest }) =>
negotiationApi.requestRenegotiation(sessionId, request),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() })
},
})
}
export function useCancelRenegotiationMutation() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ sessionId }: { sessionId: string }) => negotiationApi.cancelRenegotiation(sessionId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() })
},
})
}
@@ -43,6 +43,8 @@ export interface SessionListParams {
order?: 'asc' | 'desc' // 생략 시 기본 그룹 정렬('할 일' 우선+임박순, 종료는 하단). 지정 시 그룹 무시하고 전체 마감순(asc=임박/desc=여유)
page?: number
page_size?: number
keyword?: string // 검색어 — 견적번호·상품명·상품코드 부분일치
result?: number // 결과 필터(SessionResult): 1=낙찰 2=미낙찰 3=결렬
}
export interface SessionListItem {
@@ -55,6 +57,41 @@ export interface SessionListItem {
item_name: string
model_name: string
maker_name: string
custom: Record<string, unknown> // 협상완료 부가정보(sessions.custom). 미입력이면 {}
renegotiable: boolean // 재협상 요청 가능 여부(서버 판정 — 개찰 마감 + 마지막 차수 + 대기 요청 없음)
renegotiation_status: number // 1=심사대기 2=승인 3=반려 4=철회, 이력 없으면 0
renegotiation_memo: string // 담당자 심사 메모(반려 사유)
result: number // 협상 결과(SessionResult): 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰)
}
/** 공급사 관점 협상 결과 (sessions 파생) */
export const SessionResult = { NONE: 0, WON: 1, LOST: 2, OPEN: 3 } as const
export const SESSION_RESULT_LABEL: Record<number, string> = {
1: '낙찰',
2: '미낙찰',
3: '결렬',
}
// 재협상 요청(IMK #15)
export interface RenegotiationRequest {
reason: string
desired_price?: number | null
}
export interface RenegotiationResponse {
result: ApiResult
session_id: string
status: number
}
export const RenegoStatus = { NONE: 0, PENDING: 1, APPROVED: 2, REJECTED: 3, CANCELED: 4 } as const
export const RENEGO_STATUS_LABEL: Record<number, string> = {
1: '재협상 심사 중',
2: '재협상 승인됨',
3: '재협상 반려됨',
4: '요청 철회됨',
}
export interface SessionListResponse {
@@ -65,6 +102,15 @@ export interface SessionListResponse {
page_size: number
}
// --- 협상완료 부가정보 (POST /v1/negotiation/sessions/{id}/extra-info) -----
export interface ExtraInfoRequest {
custom: Record<string, unknown>
}
export interface ExtraInfoResponse {
result: ApiResult
session_id: string
}
// --- 참여 (POST /v1/negotiation/sessions/{id}/participate) ----------------
export interface ParticipateResponse {
result: ApiResult
Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

+4 -4
View File
@@ -10,18 +10,18 @@ export type ButtonVariant =
export type ButtonSize = 'sm' | 'md' | 'lg'
const base =
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md font-medium select-none ' +
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl font-semibold select-none ' +
interactive +
' focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ' +
'disabled:pointer-events-none disabled:opacity-50'
const variantClass: Record<ButtonVariant, string> = {
primary: 'bg-primary text-primary-foreground',
primary: 'bg-primary text-primary-foreground shadow-sm',
secondary: 'bg-secondary text-secondary-foreground',
outline: 'border border-input bg-background',
outline: 'border border-border bg-background text-foreground',
// 투명 배경이라 brightness 무효 → bg 하이라이트
ghost: 'hover:bg-accent hover:text-accent-foreground',
destructive: 'bg-destructive text-white',
destructive: 'bg-destructive text-white shadow-sm',
}
const sizeClass: Record<ButtonSize, string> = {
+6 -6
View File
@@ -18,13 +18,13 @@ export function ErrorPage({
}: ErrorPageProps) {
return (
<div className="flex h-full w-full items-center justify-center">
<div className="flex flex-col items-center gap-6 p-12">
<div className="flex size-20 items-center justify-center rounded-full bg-destructive/10">
<AlertTriangle className="size-10 text-destructive" />
<div className="flex flex-col items-center gap-5 p-12">
<div className="flex size-16 items-center justify-center rounded-full bg-destructive/10">
<AlertTriangle className="size-8 text-destructive" />
</div>
<div className="flex flex-col items-center gap-2 text-center">
<p className="title-2 text-destructive">{message}</p>
<p className="body-1 text-neutral-70">{description}</p>
<div className="flex flex-col items-center gap-1.5 text-center">
<p className="text-lg font-bold text-neutral-90">{message}</p>
<p className="text-sm text-neutral-60">{description}</p>
</div>
{onRetry && (
<Button variant="primary" size="lg" onClick={onRetry}>
+2 -2
View File
@@ -6,9 +6,9 @@ export function Input({ type = 'text', className, ...props }: ComponentProps<'in
<input
type={type}
className={cn(
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm',
'flex h-10 w-full rounded-xl border border-input bg-background px-3.5 py-2 text-sm transition-all',
'placeholder:text-muted-foreground',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
'focus-visible:outline-none focus-visible:border-brand-600 focus-visible:ring-1 focus-visible:ring-brand-600',
'disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
+23 -10
View File
@@ -1,14 +1,14 @@
import { type ComponentProps } from 'react'
import { cn } from '@/lib'
import logoColor from '@/assets/imarketkorea-logo.png'
import logoWhite from '@/assets/imarketkorea-logo-white.png'
import logoDefault from '@/assets/negotium-logo.png'
export type LogoVariant = 'color' | 'white'
export type LogoSize = 'sm' | 'md' | 'lg'
// 기본 브랜드(회사 설정 미지정 시). 회사 로고가 오면 logoUrl 이 이 값을 덮는다.
const sources: Record<LogoVariant, string> = {
color: logoColor,
white: logoWhite,
color: logoDefault,
white: logoDefault,
}
const sizes: Record<LogoSize, { img: string; text: string; gap: string }> = {
@@ -17,33 +17,46 @@ const sizes: Record<LogoSize, { img: string; text: string; gap: string }> = {
lg: { img: 'h-10', text: 'text-2xl', gap: 'gap-2.5' },
}
// 기본 브랜드 로고는 가로로 긴 워드마크라 같은 높이로 두면 회사 심볼보다 훨씬 커 보인다(랜딩도 h-4 기준).
const wordmarkSizes: Record<LogoSize, string> = {
sm: 'h-3.5',
md: 'h-4',
lg: 'h-5',
}
export interface LogoProps extends Omit<ComponentProps<'div'>, 'children'> {
variant?: LogoVariant
size?: LogoSize
withText?: boolean
alt?: string
/** 회사 브랜딩 오버라이드(companies.settings.branding). 없으면 기본 iMarket Korea. */
serviceName?: string
logoUrl?: string
}
export function Logo({
variant = 'color',
size = 'md',
withText = true,
alt = 'iMarket Korea',
alt = 'NEGOTIUM',
serviceName,
logoUrl,
className,
...props
}: LogoProps) {
const s = sizes[size]
const name = serviceName || 'negotium'
return (
<div className={cn('flex items-center', s.gap, className)} {...props}>
<img
src={sources[variant]}
alt={withText ? '' : alt}
className={cn('w-auto select-none', s.img)}
src={logoUrl || sources[variant]}
alt={withText ? '' : (serviceName || alt)}
className={cn('w-auto select-none', logoUrl ? s.img : wordmarkSizes[size])}
/>
{withText && (
{withText && serviceName && (
<span className={cn('font-bold tracking-[-0.4px] text-foreground', s.text)}>
iMarket Korea
{name}
</span>
)}
</div>
+1 -1
View File
@@ -21,7 +21,7 @@ export function Modal({ children, onClose }: ModalProps) {
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-[rgba(0,0,0,0.40)]"
className="fixed inset-0 z-50 flex items-center justify-center bg-[rgba(0,0,0,0.40)] p-4"
onClick={handleBackdropClick}
>
{children}
@@ -1,7 +1,7 @@
import { Button, Input } from '@/components'
import { useLogin } from '@/features/auth/hooks/useLogin'
const inputClassName = 'h-12 rounded-md px-4 text-base'
const inputClassName = 'h-12 rounded-xl px-4 text-base'
export function LoginForm() {
const {
@@ -6,7 +6,10 @@ import { tokenStorage } from '@/apis'
// 토큰이 있으나 만료/폐기된 경우는 요청 시 인터셉터가 세션을 종료시킨다.
export function RequireAuth({ children }: { children: ReactNode }) {
if (!tokenStorage.hasToken()) {
return <Navigate to="/" replace />
// 초청 링크(/chat?session_id=...)로 들어온 미로그인 사용자 — session_id 를 넘겨야
// 로그인 화면이 그 회사 브랜딩으로 뜬다.
const sessionId = new URLSearchParams(window.location.search).get('session_id')
return <Navigate to={sessionId ? `/?session_id=${sessionId}` : '/'} replace />
}
return <>{children}</>
}
@@ -1,6 +1,7 @@
import { useNavigate } from 'react-router'
import { LogOut } from 'lucide-react'
import { useLogoutMutation, useMeQuery } from '@/apis'
import { Button } from '@/components'
import { cn, interactive } from '@/lib'
// 사이드바 하단: 공급사명 + 로그아웃
export function SidebarFooter() {
@@ -15,19 +16,23 @@ export function SidebarFooter() {
}
return (
<div className="flex w-full h-[60px] py-3 px-8 gap-3 items-center">
<div className="flex-1 flex items-center min-w-0 text-sm text-foreground">
<span className="truncate">{user?.supplierName ?? '-'}</span>
<div className="flex w-full shrink-0 items-center gap-2 border-t border-border px-6 py-3">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-bold text-neutral-90">{user?.supplierName ?? '-'}</p>
<p className="truncate text-xs text-neutral-60">{user?.name ?? '공급 파트너'}</p>
</div>
<Button
variant="secondary"
size="sm"
className="w-[61px] px-2 rounded-[4px] text-xs flex-shrink-0"
<button
type="button"
onClick={handleLogout}
disabled={logout.isPending}
className={cn(
'flex shrink-0 items-center gap-1.5 rounded-xl border border-border bg-white px-3 py-1.5 text-xs font-bold text-neutral-70 hover:bg-neutral-10 disabled:opacity-50',
interactive,
)}
>
<LogOut className="size-3.5" />
로그아웃
</Button>
</button>
</div>
)
}
@@ -0,0 +1,61 @@
import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router'
import { authApi } from '@/apis'
import type { Branding } from '@/apis/auth/auth.type'
// 로그인 전 화면의 회사 브랜딩을 담아 두는 곳. 로그아웃/토큰 만료와 무관하게 남겨
// 뒤로가기·재진입으로 session_id 가 없어져도 같은 회사 화면을 유지한다(회사 식별 정보만 담는다).
const BRANDING_KEY = 'negosium.preLoginBranding'
function readCached(): Branding | null {
try {
const raw = localStorage.getItem(BRANDING_KEY)
return raw ? (JSON.parse(raw) as Branding) : null
} catch {
return null // 손상된 값은 없는 것으로 본다
}
}
function writeCached(branding: Branding): void {
try {
localStorage.setItem(BRANDING_KEY, JSON.stringify(branding))
} catch {
// 저장 불가(프라이빗 모드 등)면 이번 방문에만 적용된다
}
}
// 로그인 전 화면(로그인 페이지)의 회사 브랜딩.
// 협력사는 초청 메일의 /chat?session_id=... 로 들어오므로, 그 session_id 로 인증 없이 브랜딩만 조회한다.
// session_id 가 없으면 마지막으로 확인된 회사 브랜딩을 쓰고, 그것도 없으면 기본 브랜드(Negosium).
export function usePreLoginBranding(): Branding | null {
const [searchParams] = useSearchParams()
const [branding, setBranding] = useState<Branding | null>(readCached)
const sessionId = searchParams.get('session_id') ?? ''
useEffect(() => {
if (!sessionId) return
let alive = true
void authApi
.sessionBranding(sessionId)
.then((res) => {
if (!alive || res.result?.success === false) return
const next: Branding = {
service_name: res.service_name || undefined,
logo_url: res.logo_url || undefined,
primary_color: res.primary_color || undefined,
}
if (!next.service_name && !next.logo_url) return
setBranding(next)
writeCached(next) // 다음 진입에 session_id 가 없어도 이 회사로 보이게 한다
})
.catch(() => {
// 조회 실패 시 캐시(또는 기본 브랜드)를 그대로 둔다
})
return () => {
alive = false
}
}, [sessionId])
return branding
}
+1
View File
@@ -1,3 +1,4 @@
export { LoginForm } from '@/features/auth/components/LoginForm'
export { SidebarFooter } from '@/features/auth/components/SidebarFooter'
export { RequireAuth } from '@/features/auth/components/RequireAuth'
export { usePreLoginBranding } from '@/features/auth/hooks/usePreLoginBranding'
@@ -1,5 +1,5 @@
import { useEffect, useRef, memo } from 'react'
import { cn } from '@/lib'
import { useEffect, useRef, memo, type RefObject } from 'react'
import { useMeQuery } from '@/apis'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
import type { ChatMessage as ChatMessageType } from '@/features/chat/types'
@@ -7,34 +7,47 @@ import { renderEmphasis } from '@/features/chat/lib/emphasis'
import { Indicator } from '@/features/chat/components/templates/Indicator'
import { Summary } from '@/features/chat/components/templates/Summary'
import { BidSummary } from '@/features/chat/components/templates/BidSummary'
import { RejectRSP } from '@/features/chat/components/templates/RejectRSP'
import { RejectCM } from '@/features/chat/components/templates/RejectCM'
const AI_LABEL = '아이마켓코리아 (구매담당자)'
export function ChatMessage() {
const scrollRef = useRef<HTMLDivElement | null>(null)
return (
<div className="flex-1 w-full min-h-0 pr-[16px]">
{/* pt-[64px]: 첫 메시지를 우측 협상절차 카드 상단과 맞추되, 스크롤 시 여백도 함께 밀려 올라가도록 스크롤 컨테이너 안쪽에 둔다 */}
<div className="chat-scroll h-full overflow-y-auto flex flex-col pt-[64px] pl-[140px] pr-[126px] max-[1350px]:pl-[80px] max-[1350px]:pr-[72px] max-[1180px]:pl-[48px] max-[1180px]:pr-[40px]">
<ChatList />
<div className="flex-1 w-full min-h-0">
<div
ref={scrollRef}
className="chat-scroll h-full overflow-y-auto flex flex-col pt-4 pb-6 px-4 sm:px-6 min-[1180px]:pl-[80px] min-[1180px]:pr-[72px] min-[1350px]:pl-[140px] min-[1350px]:pr-[126px]"
>
<ChatList scrollRef={scrollRef} />
</div>
</div>
)
}
function ChatList() {
const bottomRef = useRef<HTMLDivElement | null>(null)
function ChatList({ scrollRef }: { scrollRef: RefObject<HTMLDivElement | null> }) {
const isFirstRef = useRef(true)
const chats = useChatStore((s) => s.messages)
const isLoading = useChatStore((s) => s.isLoading)
// 메시지 추가/타이핑 표시 시 항상 맨 아래로 스크롤
// 메시지 추가/타이핑 표시 시 항상 맨 아래로 스크롤.
// 스크롤 컨테이너를 직접 내린다 — scrollIntoView 는 요약/부가정보 폼처럼 큰 블록이 뒤늦게
// 레이아웃되면 애니메이션 도중 목표 위치가 밀려 중간에 멈춘다.
// 진입 첫 렌더는 즉시(auto) — 히스토리를 복원하며 위에서부터 훑어 내려가는 연출을 막는다.
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
}, [chats, isLoading])
const scroller = scrollRef.current
if (!scroller) return
const behavior: ScrollBehavior = isFirstRef.current ? 'auto' : 'smooth'
isFirstRef.current = false
const id = requestAnimationFrame(() => {
scroller.scrollTo({ top: scroller.scrollHeight, behavior })
})
return () => cancelAnimationFrame(id)
}, [chats, isLoading, scrollRef])
if (!chats || chats.length === 0) {
return (
<div className="flex items-center justify-center h-full">
<p className="body-1 text-neutral-70">채팅 내역이 없습니다.</p>
<p className="text-sm text-neutral-60">채팅 내역이 없습니다.</p>
</div>
)
}
@@ -42,22 +55,22 @@ function ChatList() {
return (
<div className="flex flex-col w-full">
{chats.map((message, index) => (
<MessageItem key={message.chat_id || index} message={message} isFirst={index === 0} messages={chats} currentIndex={index} />
<MessageItem key={message.chat_id || index} message={message} messages={chats} currentIndex={index} />
))}
{isLoading && <TypingBubble />}
<div ref={bottomRef} />
</div>
)
}
// agent 응답을 기다리는 동안(협상 중) 대화 흐름에 표시하는 타이핑 인디케이터.
// agent 응답을 기다리는 동안(협상 중) 대화 흐름에 표시하는 타이핑 인디케이터(AI 말풍선 톤).
function TypingBubble() {
return (
<div className="mb-[56px] pt-[36px]" aria-label="협상 중" role="status">
<div className="inline-flex items-center gap-[6px]">
<span className="size-[8px] rounded-full bg-neutral-50 animate-bounce [animation-delay:-0.3s]" />
<span className="size-[8px] rounded-full bg-neutral-50 animate-bounce [animation-delay:-0.15s]" />
<span className="size-[8px] rounded-full bg-neutral-50 animate-bounce" />
<div className="mb-6 flex flex-col items-start gap-1.5" aria-label="협상 중" role="status">
<span className="text-xs font-bold text-neutral-80">{AI_LABEL}</span>
<div className="inline-flex items-center gap-1.5 rounded-2xl rounded-tl-none border border-[#D2E6FF] bg-brand-light/70 px-4 py-3.5 shadow-sm">
<span className="size-2 rounded-full bg-brand-500 animate-bounce [animation-delay:-0.3s]" />
<span className="size-2 rounded-full bg-brand-500 animate-bounce [animation-delay:-0.15s]" />
<span className="size-2 rounded-full bg-brand-500 animate-bounce" />
</div>
</div>
)
@@ -65,46 +78,43 @@ function TypingBubble() {
const MessageItem = memo(function MessageItem({
message,
isFirst,
messages,
currentIndex,
}: {
message: ChatMessageType
isFirst: boolean
messages: ChatMessageType[]
currentIndex: number
}) {
const isBot = message.sender === 'bot'
// 직전이 reject 폼이면 사용자 답변은 숨기고 구분선만 표시
// 직전이 reject 폼이면 사용자 답변 말풍선은 숨긴다(폼 자체가 답변을 담고 있음)
if (!isBot && currentIndex > 0) {
const prev = messages[currentIndex - 1]
if (prev?.bot_chat_type === 'rejectRSP' || prev?.bot_chat_type === 'rejectCM') {
return (
<>
<div className="text-right mb-[56px]" />
<div className="flex w-full bg-neutral-30 h-[1px] mb-[20px]" />
</>
)
return null
}
}
return <div>{isBot ? <BotMessage message={message} isFirst={isFirst} /> : <UserMessage text={message.script || ''} />}</div>
return isBot ? <BotMessage message={message} /> : <UserMessage text={message.script || ''} />
})
const BotMessage = memo(function BotMessage({ message, isFirst }: { message: ChatMessageType; isFirst?: boolean }) {
const BotMessage = memo(function BotMessage({ message }: { message: ChatMessageType }) {
// 인디케이터는 이번 방문에서 '협상중'이었던 세션에서만 표시.
// 진행 화면에서 실시간으로 완료되면 sticky 플래그로 계속 노출하고,
// 완료/거부 세션에 결과 열람 목적으로 재진입한 경우엔 값이 와도 숨긴다.
const showIndicator = useChatInitStore((s) => s.wasInProgress)
const hasScript = Boolean(message.script && message.script.trim())
return (
<div className="mb-[56px]">
<div className={cn('flex flex-col', !isFirst && 'pt-[36px]')}>
{/* 봇 스크립트의 `**굵게**` 경량 마크업 해석 (표현 규칙은 프론트 소유 — emphasis.tsx) */}
<div className="body-1-read-r">{renderEmphasis(message.script || '')}</div>
<div className="mb-5 animate-fade-in">
<div className="flex flex-col items-start gap-1.5">
<span className="text-xs font-bold text-neutral-80">{AI_LABEL}</span>
{hasScript && (
<div className="max-w-[80%] rounded-2xl rounded-tl-none border border-[#D2E6FF] bg-brand-light/70 p-4 text-sm leading-relaxed text-neutral-90 shadow-sm break-keep">
{renderEmphasis(message.script || '')}
</div>
)}
</div>
<div className="flex flex-col gap-4 w-full mt-[32px]">
<div className="flex flex-col gap-4 w-full mt-4">
{showIndicator && message.bot_chat_type === 'indicator' && message.indicator_value != null && (
<Indicator number={message.indicator_value} />
)}
@@ -114,26 +124,22 @@ const BotMessage = memo(function BotMessage({ message, isFirst }: { message: Cha
itemName={message.summary.item_name}
itemCode={message.summary.item_code}
bidPrice={message.summary.final_price}
deliveryType={message.summary.delivery_type || ''}
isVAT={message.summary.item_isVAT}
/>
)}
{message.bot_chat_type === 'rejectRSP' && <RejectRSP />}
{message.bot_chat_type === 'rejectCM' && <RejectCM />}
</div>
</div>
)
})
const UserMessage = memo(function UserMessage({ text }: { text: string }) {
const { data: user } = useMeQuery()
const label = `${user?.supplierName ?? '공급사'} (나)`
return (
<>
<div className="text-right mb-[56px]">
<div className="inline-block max-w-[87%] bg-neutral-40 text-neutral-90 text-lg leading-[150%] tracking-[-0.18px] px-[20px] py-[10px] rounded-full break-keep">
{text}
</div>
<div className="mb-5 flex flex-col items-end gap-1.5 animate-fade-in">
<span className="text-xs font-bold text-neutral-80">{label}</span>
<div className="max-w-[80%] rounded-2xl rounded-tr-none border border-border bg-white p-4 text-sm leading-relaxed text-neutral-90 shadow-sm break-keep">
{text}
</div>
<div className="flex w-full bg-neutral-30 h-[1px] mb-[20px]" />
</>
</div>
)
})
@@ -1,13 +1,19 @@
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { ChatMessage } from '@/features/chat/components/ChatMessage'
import { UserButton } from '@/features/chat/components/UserButton'
import { MobileStepBar } from '@/features/chat/components/MobileStepBar'
export function ChatSection() {
const { userButtonConfig } = useChatStore()
return (
<div className="flex flex-1 flex-col w-full h-full bg-surface rounded-bl-[8px]">
<div className="flex flex-1 flex-col w-full h-full min-h-0 bg-surface">
<MobileStepBar />
<ChatMessage />
<UserButton {...userButtonConfig} />
{/* 하단 액션 덱 */}
{/* safe-b: 홈 인디케이터에 입력 버튼이 가리지 않도록 하단 안전영역 확보 */}
<div className="shrink-0 safe-b border-t border-border bg-white shadow-[0_-4px_20px_rgba(0,0,0,0.03)]">
<UserButton {...userButtonConfig} />
</div>
</div>
)
}
@@ -0,0 +1,126 @@
import { useState } from 'react'
import { toast } from 'sonner'
import { useMeQuery, useSaveExtraInfoMutation, getApiErrorMessage } from '@/apis'
import type { SessionField } from '@/apis/auth/auth.type'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
// 타결 요약의 '동의' 단계 하단 액션바 = 부가정보 입력 + 동의를 한 자리에서.
// 다른 입력(가격·배송)과 같은 자리에서 받는다. proceedText = 동의 문구(누르면 저장 후 그 텍스트로 협상 종료).
// 필드 정의(session_fields)가 없으면 폼 없이 동의 버튼만 둔다. 저장 후에도 세션 목록에서 수정할 수 있다.
export function ExtraInfoBar({ proceedText }: { proceedText: string }) {
const sessionId = useChatStore((s) => s.sessionId)
const sendMessage = useChatStore((s) => s.sendMessage)
const { data: user } = useMeQuery()
const fields: SessionField[] = user?.sessionFields ?? []
const save = useSaveExtraInfoMutation()
const existing = useChatInitStore((s) => s.custom) // 기존 입력값(재진입 프리필)
const setInitData = useChatInitStore((s) => s.setInitData)
// 의견은 session_fields 와 무관한 공통 필드 — 타결·결렬 모두 항상 받는다. custom.opinion 에 저장.
const [opinion, setOpinion] = useState<string | null>(null)
const opinionValue = opinion ?? String(existing?.opinion ?? '')
// 사용자가 건드린 값만 state 로 두고, 나머지는 기존값/기본값에서 렌더마다 파생한다(초기화 effect 불필요).
const [overrides, setOverrides] = useState<Record<string, unknown>>({})
const values: Record<string, unknown> = {}
for (const f of fields) values[f.key] = overrides[f.key] ?? existing?.[f.key] ?? (f.type === 'boolean' ? false : '')
const proceed = () => sendMessage(proceedText)
const set = (key: string, value: unknown) => setOverrides((v) => ({ ...v, [key]: value }))
// 저장 성공 후에만 동의(협상 종료)로 넘어간다 — 저장 실패 시 화면 유지.
const handleSaveAndProceed = () => {
if (save.isPending) return
const custom: Record<string, unknown> = {}
for (const f of fields) {
const v = values[f.key]
if (f.type === 'boolean') custom[f.key] = !!v
else if (v !== '' && v != null) custom[f.key] = f.type === 'number' ? Number(v) : v
}
if (opinionValue.trim()) custom.opinion = opinionValue.trim()
if (Object.keys(custom).length === 0) { proceed(); return } // 입력 없음 → 저장 생략하고 종료
save.mutate(
{ sessionId, request: { custom } },
{
onSuccess: () => {
setInitData({ custom: { ...existing, ...custom } }) // 요약 카드가 방금 입력값을 즉시 반영하도록 store 갱신
proceed()
},
onError: (error) => toast.error(getApiErrorMessage(error, '부가정보 저장에 실패했습니다.')),
},
)
}
return (
<div className="w-full">
<p className="mb-3 text-sm font-semibold text-neutral-90">아래 정보를 입력하고 협상을 마무리해 주세요.</p>
{/* overflow-y-auto 는 overflow-x 도 auto 로 만들어(스펙상) 인풋 focus ring 을 좌우로 잘라낸다.
p-1 로 링 여백을 주고 -m-1 로 원래 정렬(버튼과 좌우폭)을 유지한다. */}
<div className="max-h-[36vh] space-y-3 overflow-y-auto p-1 -m-1">
{fields.map((f) => (
<div key={f.key} className="flex items-center gap-3">
<label className="w-28 shrink-0 text-sm font-semibold text-neutral-80">{f.label}</label>
{f.type === 'boolean' ? (
<button
type="button"
role="switch"
aria-checked={!!values[f.key]}
onClick={() => set(f.key, !values[f.key])}
className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors ${
values[f.key] ? 'bg-brand-600' : 'bg-neutral-30'
}`}
>
<span
className={`inline-block size-5 transform rounded-full bg-white shadow transition-transform ${
values[f.key] ? 'translate-x-5' : 'translate-x-0.5'
}`}
/>
</button>
) : f.type === 'select' ? (
<select
value={String(values[f.key] ?? '')}
onChange={(e) => set(f.key, e.target.value)}
className="h-10 w-full rounded-xl border border-border bg-white px-3 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600"
>
<option value="">선택</option>
{(f.options ?? []).map((o) => (
<option key={o} value={o}>{o}</option>
))}
</select>
) : (
<input
type={f.type === 'number' ? 'number' : 'text'}
value={String(values[f.key] ?? '')}
onChange={(e) => set(f.key, e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && !e.nativeEvent.isComposing && handleSaveAndProceed()}
className="h-10 w-full rounded-xl border border-border bg-white px-3 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600"
placeholder={f.label}
/>
)}
</div>
))}
{/* 의견 — 타결·결렬 공통 필드(IMK #18). custom.opinion 저장. */}
<div className="flex flex-col gap-1">
<label className="text-sm font-semibold text-neutral-80">
의견 <span className="font-normal text-neutral-50">(선택)</span>
</label>
<textarea
value={opinionValue}
onChange={(e) => setOpinion(e.target.value)}
rows={2}
maxLength={255}
placeholder="추가로 남길 의견이 있으면 작성해 주세요."
className="w-full resize-none rounded-xl border border-border bg-white px-3 py-2 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600"
/>
</div>
</div>
<button type="button" onClick={handleSaveAndProceed} disabled={save.isPending} className={`${PRIMARY} mt-3 w-full`}>
{save.isPending ? '저장 중…' : proceedText || '저장하고 마무리'}
</button>
</div>
)
}
const PRIMARY =
'h-[46px] min-w-[120px] rounded-xl bg-brand-600 px-6 text-sm font-bold text-white shadow-sm transition-all hover:bg-brand-700 active:scale-[0.98] disabled:opacity-50'
@@ -8,34 +8,33 @@ export function ItemImage() {
const [isOpen, setIsOpen] = useState(false)
return (
<div className="flex flex-col w-full items-center justify-center pt-16 pr-8 pb-8 pl-8">
<div className="px-5 pt-5 pb-3">
<button
type="button"
onClick={() => setIsOpen(true)}
aria-label="이미지 크게 보기"
className="relative cursor-pointer group"
className="group relative block aspect-square w-full overflow-hidden rounded-2xl border border-border bg-neutral-10 shadow-inner"
>
<Thumb src={item_image} />
<div className="absolute inset-0 flex items-center justify-center rounded-[16px] bg-neutral-40 opacity-0 transition-opacity duration-300 group-hover:opacity-90">
<span className="text-neutral-00 text-base font-medium">이미지 크게 보기</span>
</div>
{item_image ? (
<img
src={item_image}
alt="상품 이미지"
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
/>
) : (
<div className="flex h-full w-full items-center justify-center text-neutral-40">
<ImageIcon size={40} strokeWidth={1.5} />
</div>
)}
<span className="absolute left-2 top-2 rounded-md bg-neutral-90/65 px-2 py-0.5 text-[10px] font-bold text-white backdrop-blur-sm">
상세 품목
</span>
</button>
{isOpen && <ImageModal src={item_image} onClose={() => setIsOpen(false)} />}
</div>
)
}
function Thumb({ src }: { src: string }) {
if (src) {
return <img src={src} alt="상품 이미지" className="rounded-[16px] w-[220px] h-[220px] max-[1180px]:w-[200px] max-[1180px]:h-[200px] object-cover" />
}
return (
<div className="flex w-[220px] h-[220px] max-[1180px]:w-[200px] max-[1180px]:h-[200px] items-center justify-center rounded-[16px] bg-neutral-20 text-neutral-60">
<ImageIcon size={48} strokeWidth={1.5} />
</div>
)
}
function ImageModal({ src, onClose }: { src: string; onClose: () => void }) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
@@ -53,9 +52,9 @@ function ImageModal({ src, onClose }: { src: string; onClose: () => void }) {
>
<div className="relative" onClick={(e) => e.stopPropagation()}>
{src ? (
<img src={src} alt="상품 이미지" className="rounded-[16px] max-w-[42rem] max-h-[90vh] object-contain" />
<img src={src} alt="상품 이미지" className="max-h-[90vh] max-w-[42rem] rounded-2xl object-contain" />
) : (
<div className="flex w-[60vmin] h-[60vmin] max-w-[42rem] max-h-[90vh] items-center justify-center rounded-[16px] bg-neutral-20 text-neutral-60">
<div className="flex h-[60vmin] max-h-[90vh] w-[60vmin] max-w-[42rem] items-center justify-center rounded-2xl bg-neutral-20 text-neutral-50">
<ImageIcon size={96} strokeWidth={1.25} />
</div>
)}
@@ -63,9 +62,9 @@ function ImageModal({ src, onClose }: { src: string; onClose: () => void }) {
type="button"
onClick={onClose}
aria-label="닫기"
className="absolute top-4 right-4 flex items-center justify-center w-9 h-9 rounded-full bg-white border border-neutral-30 text-neutral-80 cursor-pointer hover:bg-neutral-10 transition-colors"
className="absolute right-3 top-3 flex size-9 items-center justify-center rounded-full border border-border bg-white text-neutral-80 transition-colors hover:bg-neutral-10"
>
<X size={20} />
<X size={18} />
</button>
</div>
</div>,
@@ -1,6 +1,5 @@
import { useState, useCallback, useRef, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { cn } from '@/lib'
import { ItemImage } from '@/features/chat/components/ItemImage'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
import { formatLeadTime } from '@/features/chat/lib/format'
@@ -39,14 +38,17 @@ function ItemInfo() {
const {
item_code,
item_price,
item_vat_yn,
item_model_name,
item_maker_name,
item_min_order_quantity,
item_lead_time,
item_spec,
item_name,
item_vat_yn,
labels,
} = useChatInitStore()
// 회사 설정 라벨(companies.settings.labels)로 필드명 치환. 미설정 시 기본 라벨.
const fieldLabel = (key: string, fallback: string) => labels?.[key] || fallback
const [tooltip, setTooltip] = useState<TooltipState | null>(null)
const hideTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -72,21 +74,21 @@ function ItemInfo() {
const formatPrice = (price: number) => price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
const isNewItem = !item_code && !item_price
const priceText = isNewItem ? '신규' : `${formatPrice(item_price)}원`
const formattedPrice = `${priceText}(${item_vat_yn || 'VAT별도'})`
// VAT 표기는 회사 설정 기준(item_vat_yn). vat_yn 미관리(hidden)면 값이 비어 라벨을 생략한다.
const formattedPrice = item_vat_yn ? `${priceText}(${item_vat_yn})` : priceText
const renderRow = (title: string, data: string, important = false) => {
const textClass = important ? 'title-3 text-neutral-90' : 'body-3 text-neutral-70'
const renderRow = (title: string, data: string) => {
const displayData = data || '-'
return (
<div className="flex items-start self-stretch gap-1 min-w-0">
<div className={cn(textClass, 'w-[100px]')}>{title}</div>
<div
className={cn(textClass, 'flex-1 min-w-0 break-words break-keep cursor-default')}
<div className="flex items-start justify-between gap-3 self-stretch border-b border-border/60 py-2 last:border-0 min-w-0">
<span className="shrink-0 text-[13px] text-neutral-60">{title}</span>
<span
className="min-w-0 flex-1 break-words break-keep text-right text-[13px] font-semibold text-neutral-90 cursor-default"
onMouseEnter={(e) => displayData !== '-' && showTooltip(e, displayData)}
onMouseLeave={hideTooltip}
>
{displayData}
</div>
</span>
</div>
)
}
@@ -94,31 +96,35 @@ function ItemInfo() {
return (
<div className="flex flex-col w-full flex-1 overflow-hidden min-h-0">
<div
className="text-center headline-3 text-neutral-90 mb-4 truncate px-8 flex-shrink-0 cursor-default"
className="mb-3 flex-shrink-0 truncate px-6 text-left text-sm font-bold text-neutral-90 cursor-default"
onMouseEnter={(e) => item_name && showTooltip(e, item_name)}
onMouseLeave={hideTooltip}
>
{item_name}
</div>
<div className="flex flex-1 items-start self-stretch mr-2 overflow-y-auto overflow-x-hidden pr-6 pl-8 min-h-0">
<div className="flex flex-col items-start self-stretch flex-1 gap-2 min-w-0">
{renderRow('상품코드', item_code, true)}
{renderRow('단가', formattedPrice, true)}
{renderRow('모델명', item_model_name, true)}
{renderRow('제조사', item_maker_name)}
{renderRow('최소주문수량', item_min_order_quantity)}
{renderRow('리드타임', formatLeadTime(item_lead_time))}
<div className="mb-2 flex-shrink-0 border-b border-border px-6 pb-2">
<span className="text-[11px] font-extrabold tracking-wider text-neutral-50">품목 정보</span>
</div>
<div className="flex items-start self-stretch gap-1 flex-[1_0]">
<div className="body-3 text-neutral-70 w-[100px]">규격</div>
<div
className="body-3 text-neutral-70 self-stretch w-0 flex-[1_0] overflow-hidden whitespace-normal break-words break-keep cursor-default"
<div className="flex flex-1 items-start self-stretch overflow-y-auto overflow-x-hidden px-6 min-h-0">
<div className="flex flex-col items-start self-stretch flex-1 gap-2 min-w-0">
{renderRow(fieldLabel('item.code', '상품코드'), item_code)}
{renderRow(fieldLabel('item.price', '단가'), formattedPrice)}
{renderRow(fieldLabel('item.model_name', '모델명'), item_model_name)}
{renderRow(fieldLabel('item.manufacturer', '제조사'), item_maker_name)}
{renderRow(fieldLabel('item.moq', '최소주문수량'), item_min_order_quantity)}
{renderRow(fieldLabel('lead_time', '리드타임'), formatLeadTime(item_lead_time))}
<div className="flex items-start justify-between gap-3 self-stretch py-2">
<span className="shrink-0 text-sm text-neutral-60">{fieldLabel('item.spec', '규격')}</span>
<span
className="min-w-0 flex-1 overflow-hidden whitespace-normal break-words break-keep text-right text-[13px] font-semibold text-neutral-90 cursor-default"
onMouseEnter={(e) => item_spec && showTooltip(e, item_spec, true)}
onMouseLeave={hideTooltip}
>
{item_spec || '-'}
</div>
</span>
</div>
</div>
</div>
@@ -0,0 +1,50 @@
import { type ReactNode, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { cn } from '@/lib'
interface MobileDrawerProps {
open: boolean
onClose: () => void
side?: 'left' | 'right'
title: string
children: ReactNode
}
// 모바일 전용 슬라이드 드로어(lg 미만). 데스크톱에선 절대 노출되지 않도록 lg:hidden 을 강제한다.
export function MobileDrawer({ open, onClose, side = 'left', title, children }: MobileDrawerProps) {
useEffect(() => {
if (!open) return
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [open, onClose])
if (!open) return null
return createPortal(
<div className="fixed inset-0 z-[60] lg:hidden">
<div className="absolute inset-0 bg-black/50 animate-fade-in" onClick={onClose} />
<div
className={cn(
'absolute top-0 bottom-0 flex w-[88%] max-w-[360px] flex-col bg-white shadow-xl',
side === 'left' ? 'left-0' : 'right-0',
)}
>
<div className="flex h-14 box-content safe-t shrink-0 items-center justify-between border-b border-border px-5">
<span className="text-base font-bold text-neutral-90">{title}</span>
<button
type="button"
onClick={onClose}
aria-label="닫기"
className="flex size-8 items-center justify-center rounded-full text-neutral-60 hover:bg-neutral-10"
>
<X className="size-4" />
</button>
</div>
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto safe-b">{children}</div>
</div>
</div>,
document.body,
)
}
@@ -0,0 +1,46 @@
import { Check } from 'lucide-react'
import { cn } from '@/lib'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { STEPS } from '@/features/chat/lib/negoSteps'
// 모바일 전용: 협상절차를 채팅 상단에 가로 스텝바로 항상 표시한다. (데스크톱은 우측 패널 사용)
export function MobileStepBar() {
const chats = useChatStore((s) => s.messages)
const currentStep = chats[chats.length - 1]?.display_step || STEPS[0].name
const idx = Math.max(
0,
STEPS.findIndex((s) => s.name === currentStep),
)
return (
<div className="shrink-0 border-b border-border bg-white px-4 py-2.5 lg:hidden">
<div className="flex items-center">
{STEPS.map((step, i) => {
const done = i < idx
const current = i === idx
return (
<div key={step.name} className={cn('flex items-center', i < STEPS.length - 1 && 'flex-1')}>
<div
className={cn(
'flex size-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold transition-colors',
done && 'bg-success text-white',
current && 'bg-brand-600 text-white ring-4 ring-brand-light',
!done && !current && 'border border-border bg-white text-neutral-50',
)}
>
{done ? <Check className="size-3" strokeWidth={3} /> : i + 1}
</div>
{i < STEPS.length - 1 && (
<div className={cn('mx-1 h-0.5 flex-1 rounded-full', i < idx ? 'bg-success' : 'bg-neutral-20')} />
)}
</div>
)
})}
</div>
<p className="mt-1.5 truncate text-[11px] font-bold text-brand-600">
{idx + 1}. {STEPS[idx].name}
<span className="ml-1 font-normal text-neutral-50">{STEPS[idx].desc}</span>
</p>
</div>
)
}
@@ -0,0 +1,187 @@
import { useState, useMemo } from 'react'
import { AlertTriangle } from 'lucide-react'
import { cn } from '@/lib'
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
import { SelectRadio, SubmitButton } from '@/features/chat/components/templates/rejectControls'
import { OtherReason } from '@/features/chat/components/templates/OtherReason'
import { findRestoreScript, restoreRejectRSP, extractPart } from '@/features/chat/lib/rejectForm'
const MAX_PRICE = 999999999999999
// 합의 불가 사유 프리셋 (rejectRSP 와 동일 목록)
const REASONS = [
{ value: '단가인상', text: "'원재료 가격 상승' 또는 '제조사 가격 인상'으로 요청한 공급가격을 맞출 수 없습니다." },
{ value: '수량', text: '주문 수량이 적어, 소량 생산 시 발생하는 제조비용으로 맞출 수 없습니다.' },
{ value: '단종', text: '현재 단종된 제품으로 물량 수급이 원활하지 않아 가격을 맞출 수 없습니다.' },
{ value: '품절', text: '해당 상품이 품절되어 납품할 수 없습니다.' },
]
// 통일된 협상 결렬 폼 — 최종 제안 단가 + 합의 불가 사유 + 의견.
// rejectRSP / rejectCM 두 유형 모두 이 폼 하나로 받는다(액션바 렌더).
export function RejectForm() {
const isLoading = useChatStore((s) => s.isLoading)
const sendMessage = useChatStore((s) => s.sendMessage)
const messages = useChatStore((s) => s.messages)
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
const isVAT = item_vat_yn === 'VAT별도'
// 직전 제출 내역에서 1회 복원 (rejectRSP/rejectCM 어느 유형이든).
const priorScript = useState(
() => findRestoreScript(messages, 'rejectRSP') ?? findRestoreScript(messages, 'rejectCM'),
)[0]
const restored = useState(() => restoreRejectRSP(priorScript))[0]
const [price, setPrice] = useState(restored.price)
const [selectedReason, setSelectedReason] = useState(restored.selectedReason)
const [reason, setReason] = useState(restored.reason)
const [opinion, setOpinion] = useState(() => extractPart(priorScript, '의견-'))
const [otherErrorMessage, setOtherErrorMessage] = useState('')
const [priceErrorMessage, setPriceErrorMessage] = useState('')
const [radioErrorMessage, setRadioErrorMessage] = useState('')
const isSubmitted = useMemo(
() => Boolean(findRestoreScript(messages, 'rejectRSP') ?? findRestoreScript(messages, 'rejectCM')),
[messages],
)
// 사유는 필수(20번), 의견은 선택(18번).
const isValid =
Boolean(price && parseInt(price) > 0) &&
Boolean(selectedReason) &&
(selectedReason !== '기타' || reason.trim() !== '')
const handlePriceChange = (value: string) => {
const numeric = value.replace(/\D/g, '')
if (numeric && parseInt(numeric) > MAX_PRICE) return
setPrice(numeric)
if (numeric) setPriceErrorMessage('')
}
const handleRadioChange = (value: string) => {
setSelectedReason(value)
setRadioErrorMessage('')
if (value !== '기타') {
setReason('')
setOtherErrorMessage('')
}
}
const koreanPrice = (() => {
if (!price) return '영'
const n = parseInt(price)
return Number.isNaN(n) || n === 0 ? '영' : numberToKorean(n)
})()
const handleSubmit = () => {
setPriceErrorMessage(!price || parseInt(price) === 0 ? '가격을 입력해주세요.' : '')
setRadioErrorMessage(!selectedReason ? '사유를 선택해주세요.' : '')
setOtherErrorMessage(selectedReason === '기타' && !reason.trim() ? '기타 사유를 입력해주세요.' : '')
if (isValid && !isLoading && !isSubmitted) {
const reasonPart =
selectedReason === '기타' ? `합의불가사유-기타-${reason.trim()}` : `합의불가사유-${selectedReason}`
const script = `공급희망가격-${price}, ${reasonPart}, 의견-${opinion.trim()}`
sendMessage(script, 'text')
}
}
const isDisabled = isLoading || isSubmitted
return (
<div className="w-full">
<div className="flex flex-col w-full gap-2">
<div className="flex w-full items-center justify-center gap-2 rounded-xl bg-[#FFF1F1] px-4 py-3 text-sm font-bold text-[#E5484D]">
<AlertTriangle className="size-5 shrink-0" />
협상 합의 불가 사유 및 최종 제안 단가 입력
</div>
<div className="max-h-[42vh] space-y-2 overflow-y-auto p-1 -m-1">
{/* 공급 희망 가격 */}
<div className="flex flex-col w-full gap-1">
<div className="flex w-full items-start gap-3">
<div className="w-[100px] shrink-0 pt-2.5 text-sm font-bold text-neutral-90">공급 희망 가격</div>
<div className="flex w-full flex-wrap items-center gap-2 pt-2">
<div className="flex items-center gap-2">
<input
type="text"
className={cn(
'h-10 max-w-[200px] rounded-xl border px-3 text-right text-sm outline-none transition-all placeholder:text-neutral-50',
isDisabled
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
)}
value={price ? parseInt(price).toLocaleString() : ''}
onChange={(e) => handlePriceChange(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && !e.nativeEvent.isComposing && handleSubmit()}
placeholder="0"
disabled={isDisabled}
/>
<div className="whitespace-nowrap text-sm text-neutral-70">원{isVAT && '(VAT 별도)'}</div>
</div>
<div className="whitespace-nowrap text-sm text-neutral-50">[{koreanPrice} 원]</div>
</div>
</div>
{priceErrorMessage && (
<div className="pl-[112px] text-xs font-medium text-negative">{priceErrorMessage}</div>
)}
</div>
{/* 합의 불가 사유 (필수) */}
<div className="flex w-full gap-3">
<div className="w-[100px] shrink-0 pt-2 text-sm font-bold text-neutral-90">합의 불가 사유</div>
<div className="flex w-full flex-col mt-2 gap-2">
{REASONS.map((r) => (
<SelectRadio
key={r.value}
text={r.text}
value={r.value}
name="rejectform"
selectedValue={selectedReason}
onChange={handleRadioChange}
errorMessage={radioErrorMessage}
disabled={isDisabled}
/>
))}
<OtherReason
inputValue={reason}
setInputValue={(v) => {
if (selectedReason !== '기타') return
setReason(v)
if (v.trim()) setOtherErrorMessage('')
}}
errorMessage={otherErrorMessage}
selectedValue={selectedReason}
onChange={handleRadioChange}
isError={!!radioErrorMessage}
disabled={isDisabled}
onSubmit={handleSubmit}
/>
</div>
</div>
{/* 의견 (선택) — 타결·결렬 공통 */}
<div className="flex w-full items-start gap-3">
<div className="w-[100px] shrink-0 pt-2 text-sm font-bold text-neutral-90">의견</div>
<textarea
value={opinion}
onChange={(e) => setOpinion(e.target.value)}
rows={2}
maxLength={255}
disabled={isDisabled}
placeholder="추가로 남길 의견이 있으면 작성해 주세요. (선택)"
className={cn(
'mt-2 w-full resize-none rounded-xl border px-3 py-2 text-sm outline-none transition-all placeholder:text-neutral-50',
isDisabled
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
)}
/>
</div>
</div>
<div className="flex w-full items-center justify-center mt-2">
<SubmitButton isValid={isValid} isLoading={isLoading} isSubmitted={isSubmitted} onSubmit={handleSubmit} />
</div>
</div>
</div>
)
}
@@ -1,8 +1,10 @@
import { useState, useEffect } from 'react'
import { Clock } from 'lucide-react'
import { cn } from '@/lib'
import { getTimeRemaining } from '@/features/chat/lib/remainingTime'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
// 헤더의 협상 잔여 시간. 1초마다 tick 을 올려 렌더 중 남은 시간을 다시 계산한다.
// 헤더의 협상 잔여 시간 칩. 1초마다 tick 을 올려 렌더 중 남은 시간을 다시 계산한다.
export function RemainingTime() {
const { quotation_end_time } = useChatInitStore()
const [, setTick] = useState(0)
@@ -13,6 +15,28 @@ export function RemainingTime() {
}, [])
const remaining = quotation_end_time ? getTimeRemaining(quotation_end_time) : '-'
const ended = remaining === '종료되었습니다.' || remaining === '-'
return <span className="title-1">협상 잔여 시간 : {remaining}</span>
return (
<span
className={cn(
// min-w-0 + truncate: 헤더가 좁아도 잘려나가지 않고 말줄임으로 접힌다.
'inline-flex min-w-0 shrink items-center gap-1.5 rounded-full px-3 py-1 text-xs font-bold tabular-nums',
ended ? 'bg-neutral-20 text-neutral-60' : 'bg-brand-light text-brand-600',
)}
>
<Clock className="size-3.5 shrink-0" />
<span className="truncate">
{ended ? (
// 종료 시엔 어느 폭에서도 긴 문장('종료되었습니다.')을 쓰지 않는다 — 헤더에서 잘리던 원인.
'마감 종료'
) : (
<>
<span className="hidden sm:inline">협상 마감 </span>
{remaining}
</>
)}
</span>
</span>
)
}
@@ -1,44 +1,57 @@
import { useEffect } from 'react'
import { useNavigate } from 'react-router'
import { List } from 'lucide-react'
import { cn } from '@/lib'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { Percent, Price } from '@/features/chat/components/userInputs'
import { ExtraInfoBar } from '@/features/chat/components/ExtraInfoBar'
import { RejectForm } from '@/features/chat/components/RejectForm'
import { GO_TO_LIST_TEXT } from '@/features/chat/lib/userButtonConfig'
import type { UserButtonConfig } from '@/features/chat/types'
// max-[1180px]: 채팅 폭이 좁아지면 버튼 패딩·최소폭 축소, 상품목록은 아이콘만 남긴다
const style = {
goToList:
'flex w-[159px] max-[1180px]:w-[48px] h-[48px] bg-neutral-40 hover:brightness-[0.97] rounded-[999px] items-center justify-center title-2 text-neutral-80 cursor-pointer gap-2 max-[1180px]:gap-0 transition-all ease-out hover:scale-[1.01]',
black:
'flex min-w-[120px] px-[32px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[48px] bg-primary hover:brightness-[0.97] rounded-[999px] items-center justify-center title-2 text-primary-foreground cursor-pointer whitespace-nowrap transition-all duration-200 ease-out hover:scale-[1.01]',
gray: 'flex min-w-[120px] px-[32px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[48px] bg-neutral-60 rounded-[999px] items-center justify-center title-2 text-neutral-00 cursor-pointer whitespace-nowrap transition-all ease-out hover:scale-[1.01]',
'flex min-w-[120px] px-[28px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[46px] bg-brand-600 hover:bg-brand-700 rounded-xl items-center justify-center text-sm font-bold text-white shadow-sm cursor-pointer whitespace-nowrap transition-all duration-200 ease-out active:scale-[0.98]',
gray: 'flex min-w-[120px] px-[28px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[46px] bg-neutral-60 hover:brightness-[0.97] rounded-xl items-center justify-center text-sm font-bold text-white cursor-pointer whitespace-nowrap transition-all ease-out active:scale-[0.98]',
white:
'flex min-w-[120px] px-[32px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[48px] bg-neutral-00 rounded-[999px] items-center justify-center title-2 text-neutral-80 border border-neutral-80 cursor-pointer whitespace-nowrap transition-all ease-out hover:scale-[1.01]',
'flex min-w-[120px] px-[28px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[46px] bg-white hover:bg-neutral-10 rounded-xl items-center justify-center text-sm font-bold text-neutral-80 border border-border cursor-pointer whitespace-nowrap transition-all ease-out active:scale-[0.98]',
}
export function UserButton({ type, text, textList, priceErrorMessage }: UserButtonConfig) {
if (type === '') return null
// 부가정보 입력은 폼이라 가운데정렬 덱이 아니라 전체폭으로 편다. text = 저장 후 보낼 동의 문구.
if (type === 'extra-info') {
return (
<div className="w-full px-6 py-4 max-[1180px]:px-4">
<ExtraInfoBar proceedText={text || ''} />
</div>
)
}
// 결렬 통일 폼 — 부가정보와 같은 자리(액션바)에서 전체폭으로.
if (type === 'reject') {
return (
<div className="w-full px-6 py-4 max-[1180px]:px-4">
<RejectForm />
</div>
)
}
// 입력 단계는 에러 말풍선이 위로 삐져나가야 해서 overflow 클리핑 제외 (버튼 덱만 가로 스크롤 허용)
const isInputStep = type === 'percent' || type === 'price'
return (
// pr-[16px]: 채팅 스크롤 영역(ChatMessage 바깥 pr-[16px])과 오른쪽 끝 정렬
<div className="flex w-full pb-[52px] pr-[16px]">
<div className="grid grid-cols-[1fr_auto_1fr] items-center w-full">
<div />
<div className="flex justify-center">
{type === 'one-black' && <OneBlack text={text || '확인'} />}
{type === 'one-gray' && <OneGray text={text || '확인'} />}
{type === 'black-white' && <BlackWhite textList={[textList?.[0] || '예', textList?.[1] || '아니오']} />}
{type === 'percent' && <Percent />}
{type === 'three-black' && (
<ThreeBlack textList={[textList?.[0] || '협력사배송', textList?.[1] || '지정택배배송', textList?.[2] || '픽업배송']} />
)}
{type === 'price' && <Price priceErrorMessage={priceErrorMessage} />}
{type === 'loading' && <LoadingDots />}
</div>
<div className="flex justify-end">
<GoToList />
</div>
<div className={cn('flex w-full justify-center px-6 py-4 max-[1180px]:px-4', !isInputStep && 'overflow-x-auto')}>
<div className="flex justify-center">
{type === 'one-black' && <OneBlack text={text || '확인'} />}
{type === 'one-gray' && <OneGray text={text || '확인'} />}
{type === 'black-white' && <BlackWhite textList={[textList?.[0] || '예', textList?.[1] || '아니오']} />}
{type === 'percent' && <Percent />}
{type === 'three-black' && (
<ThreeBlack textList={[textList?.[0] || '협력사배송', textList?.[1] || '지정택배배송', textList?.[2] || '픽업배송']} />
)}
{type === 'price' && <Price priceErrorMessage={priceErrorMessage} />}
{type === 'loading' && <LoadingDots />}
</div>
</div>
)
@@ -57,16 +70,6 @@ function LoadingDots() {
)
}
function GoToList() {
const navigate = useNavigate()
return (
<button className={style.goToList} onClick={() => navigate('/list')} aria-label="상품 목록으로 이동" title="상품 목록">
<List size={24} className="shrink-0" />
<span className="max-[1180px]:hidden">상품 목록</span>
</button>
)
}
function OneBlack({ text }: { text: string }) {
const navigate = useNavigate()
const sendMessage = useChatStore((s) => s.sendMessage)
@@ -102,6 +105,18 @@ function ThreeBlack({ textList }: { textList: [string, string, string] }) {
function BlackWhite({ textList }: { textList: [string, string] }) {
const sendMessage = useChatStore((s) => s.sendMessage)
// Enter = 첫 버튼(예). 입력창이 없는 선택 단계라 전역 Enter 를 잡아도 안전하다.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Enter' && !e.isComposing) {
e.preventDefault()
sendMessage(textList[0])
}
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [sendMessage, textList])
return (
<div className="flex gap-3">
<button className={style.black} onClick={() => sendMessage(textList[0])}>
@@ -1,28 +1,14 @@
import { useState } from 'react'
import { interactive, cn } from '@/lib'
import { ServiceGuidePopup } from '@/features/chat/components/popup/ServiceGuidePopup'
// 헬프데스크 — 이용 가이드 버튼 클릭 시 안내 팝업을 연다.
// 헬프데스크 — 연락처. (안내 팝업 진입은 상단 '유의사항 및 이용방법' 섹션으로 일원화)
export function Contact() {
const [isOpen, setIsOpen] = useState(false)
return (
<div className="flex flex-col w-full pl-[24px] pb-[24px]">
<div className="flex flex-col w-full gap-2">
<div className="title-5 text-neutral-80">헬프 데스크</div>
<button
type="button"
onClick={() => setIsOpen(true)}
className={cn('body-5 text-neutral-80 bg-neutral-40 rounded-[8px] px-[12px] py-[6px] w-fit', interactive)}
>
이용 가이드
</button>
<div className="flex flex-col gap-1">
<div className="body-5 text-neutral-60">010-0000-0000</div>
<div className="body-5 text-neutral-60">o2odev@o2o.kr</div>
</div>
<section className="w-full pt-4">
<div className="border-b border-border pb-2">
<span className="text-[11px] font-bold tracking-wide text-neutral-60">헬프데스크</span>
</div>
{isOpen && <ServiceGuidePopup onClose={() => setIsOpen(false)} />}
</div>
<div className="flex flex-col gap-1 pt-3 text-sm text-neutral-60">
<span>010-0000-0000</span>
<span>o2odev@o2o.kr</span>
</div>
</section>
)
}
@@ -1,6 +1,5 @@
import { useState } from 'react'
import { ChevronRight } from 'lucide-react'
import { interactive, cn } from '@/lib'
import { ServiceGuidePopup } from '@/features/chat/components/popup/ServiceGuidePopup'
// 유의사항 및 이용방법 — 클릭 시 안내 팝업을 연다.
@@ -12,13 +11,12 @@ export function Guide() {
<button
type="button"
onClick={() => setIsOpen(true)}
className={cn(
'flex w-full bg-white rounded-[28px] py-[20px] pl-[24px] pr-[16px] justify-between items-center text-left',
interactive,
)}
className="flex w-full items-center justify-between border-b border-border pb-2 text-left transition-colors hover:border-neutral-40"
>
<span className="menu-title text-neutral-80 break-keep">유의사항 및 이용방법</span>
<ChevronRight size={20} className="text-neutral-70" />
<span className="text-[11px] font-bold tracking-wide text-neutral-60 break-keep">
유의사항 및 이용방법
</span>
<ChevronRight size={16} className="text-neutral-50" />
</button>
{isOpen && <ServiceGuidePopup onClose={() => setIsOpen(false)} />}
</>
@@ -22,39 +22,33 @@ export function MDInformation({ isOpen, setIsOpen }: Props) {
if (memoArray.length === 0) return null
return (
<div className="flex flex-col w-full min-w-[200px]">
<div className="bg-white rounded-[28px]">
<div className={cn('flex items-center w-full h-[4.75rem] px-4 pl-6', isOpen ? 'pt-6 pb-3' : 'py-6')}>
<div className="flex items-center flex-1 justify-between">
<div className="menu-title text-neutral-80">MD 안내사항</div>
<button
type="button"
aria-expanded={isOpen}
onClick={() => setIsOpen(!isOpen)}
className="flex items-center justify-center w-10 h-10 cursor-pointer text-neutral-70"
>
<ChevronDown size={20} className={cn('transition-transform duration-300', !isOpen && 'rotate-180')} />
</button>
</div>
</div>
<section className="w-full">
<button
type="button"
aria-expanded={isOpen}
onClick={() => setIsOpen(!isOpen)}
className="flex w-full items-center justify-between border-b border-border pb-2"
>
<span className="text-[11px] font-bold tracking-wide text-neutral-60">구매담당자 안내사항</span>
<ChevronDown
size={16}
className={cn('text-neutral-50 transition-transform duration-300', !isOpen && '-rotate-90')}
/>
</button>
<div
className={cn(
'flex flex-col items-start gap-[19px] w-full px-6 overflow-hidden transition-all duration-300 ease-in-out',
isOpen ? 'max-h-[200px] pb-8 opacity-100' : 'max-h-0 pb-0 opacity-0',
)}
>
<div className={cn('flex flex-col gap-2 items-start self-stretch max-h-[200px] break-keep', isOpen ? 'overflow-y-auto' : 'overflow-hidden')}>
{isOpen && (
<div className="max-h-[220px] animate-fade-in overflow-y-auto pt-3">
<div className="flex flex-col gap-2 break-keep">
{memoArray.map((item, i) => (
<div key={i} className="flex items-start gap-2 body-3 text-neutral-70">
<span className="flex-shrink-0">•</span>
<div key={i} className="flex items-start gap-2 text-sm text-neutral-70">
<span className="shrink-0 text-neutral-50">•</span>
<div className="flex-1 whitespace-pre-wrap">{linkText(item)}</div>
</div>
))}
</div>
</div>
</div>
</div>
)}
</section>
)
}
@@ -63,7 +57,7 @@ function linkText(text: string) {
const isUrl = (s: string) => /^https?:\/\/[^\s]+$/.test(s)
const parts = text.split(urlRegex)
return (
<div className="body-3 text-neutral-70">
<div className="text-sm text-neutral-70">
{parts.map((part, i) =>
isUrl(part) ? (
<a
@@ -71,7 +65,7 @@ function linkText(text: string) {
href={part}
target="_blank"
rel="noopener noreferrer"
className="block text-info underline cursor-pointer hover:brightness-95 transition-all"
className="block text-brand-600 underline transition-all hover:brightness-95"
>
상품 사이트로 이동
</a>
@@ -1,16 +1,24 @@
import { useState } from 'react'
import { cn } from '@/lib'
import { MDInformation } from '@/features/chat/components/menu/MDInformation'
import { NegoStep } from '@/features/chat/components/menu/NegoStep'
import { Guide } from '@/features/chat/components/menu/Guide'
import { Contact } from '@/features/chat/components/menu/Contact'
export function MenuSection() {
// rail = 데스크톱 우측 고정 패널(lg+), drawer = 모바일 드로어 내부.
// 보고서식: 박스 카드가 아니라 하나의 흰 패널 안에 납작한 섹션들을 쌓는다.
export function MenuSection({ variant = 'rail' }: { variant?: 'rail' | 'drawer' }) {
const [isMDOpen, setIsMDOpen] = useState(true)
const [isStepOpen, setIsStepOpen] = useState(true)
const wrap =
variant === 'rail'
? 'hidden lg:flex flex-col w-[300px] max-[1350px]:w-[280px] max-[1180px]:w-[260px] h-full overflow-y-auto bg-white border-l border-border px-5 pt-6 pb-4'
: 'flex flex-col w-full p-5'
return (
<div className="flex flex-col w-[360px] max-[1350px]:w-[320px] max-[1180px]:w-[280px] h-full pt-[64px] pr-[24px]">
<div className="flex flex-col flex-1 gap-[28px]">
<div className={cn(wrap)}>
<div className="flex flex-1 flex-col gap-6">
<MDInformation isOpen={isMDOpen} setIsOpen={setIsMDOpen} />
<NegoStep isOpen={isStepOpen} setIsOpen={setIsStepOpen} />
<Guide />
@@ -1,52 +1,77 @@
import { ChevronDown } from 'lucide-react'
import { Check, ChevronDown } from 'lucide-react'
import { cn } from '@/lib'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { STEPS } from '@/features/chat/lib/negoSteps'
interface Props {
isOpen: boolean
setIsOpen: (isOpen: boolean) => void
}
const STEPS = ['서비스안내', '담당자확인', '협상품목안내', '가격협상', '협상종료']
export function NegoStep({ isOpen, setIsOpen }: Props) {
const chats = useChatStore((s) => s.messages)
const currentStep = chats[chats.length - 1]?.display_step || '서비스안내'
const currentIndex = Math.max(
0,
STEPS.findIndex((s) => s.name === currentStep),
)
return (
<div className="flex flex-col w-full min-w-[200px]">
<div className="bg-white rounded-[28px]">
<div className={cn('flex items-center w-full h-[4.75rem] px-4 pl-6', isOpen ? 'pt-6 pb-3' : 'py-6')}>
<div className="flex items-center flex-1 justify-between">
<div className="menu-title text-neutral-80">협상절차</div>
<button
type="button"
aria-expanded={isOpen}
onClick={() => setIsOpen(!isOpen)}
className="flex items-center justify-center w-10 h-10 cursor-pointer text-neutral-70"
>
<ChevronDown size={20} className={cn('transition-transform duration-300', !isOpen && 'rotate-180')} />
</button>
</div>
</div>
<section className="w-full">
<button
type="button"
aria-expanded={isOpen}
onClick={() => setIsOpen(!isOpen)}
className="flex w-full items-center justify-between border-b border-border pb-2"
>
<span className="text-[11px] font-bold tracking-wide text-neutral-60">협상절차</span>
<ChevronDown
size={16}
className={cn('text-neutral-50 transition-transform duration-300', !isOpen && '-rotate-90')}
/>
</button>
<div
className={cn(
'flex flex-col items-start gap-[19px] w-full px-6 overflow-hidden transition-all duration-300 ease-in-out',
isOpen ? 'max-h-[200px] pb-8 opacity-100' : 'max-h-0 pb-0 opacity-0',
)}
>
<div className="flex flex-col gap-2 items-start self-stretch break-keep">
{STEPS.map((step, i) => (
<div key={step} className="flex items-start gap-2">
<div className={cn('body-3 text-neutral-80', currentStep === step && 'font-bold')}>
{i + 1}. {step}
{isOpen && (
<div className="animate-fade-in pt-4">
<div className="relative">
{/* 세로 레일 */}
<span className="absolute left-[9px] top-3 bottom-3 w-0.5 bg-neutral-20" />
{STEPS.map((step, i) => {
const done = i < currentIndex
const current = i === currentIndex
return (
<div key={step.name} className="relative flex items-start gap-3 py-1.5">
<div
className={cn(
'z-10 mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold transition-all',
done && 'bg-success text-white',
current && 'scale-110 bg-brand-600 text-white ring-4 ring-brand-light',
!done && !current && 'border border-border bg-white text-neutral-50',
)}
>
{done ? <Check className="size-3" strokeWidth={3} /> : i + 1}
</div>
<div className="min-w-0">
<p
className={cn(
'text-xs leading-tight',
current && 'font-extrabold text-brand-600',
done && 'font-semibold text-success',
!done && !current && 'font-medium text-neutral-80',
)}
>
{step.name}
</p>
<p className={cn('mt-0.5 text-[10px] leading-snug', current ? 'text-brand-600/80' : 'text-neutral-50')}>
{step.desc}
</p>
</div>
</div>
</div>
))}
)
})}
</div>
</div>
</div>
</div>
)}
</section>
)
}
@@ -3,14 +3,13 @@ import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
// 협상 유의사항 및 서비스 이용 방법 안내 — 팝업 2종(자동 안내/메뉴 가이드)이 공유하는 본문.
// VAT/배송비 문구는 채팅 init 메타(useChatInitStore)를 읽어 상품별로 동적 표시한다.
// break-keep: 한국어 단어가 중간에서 잘려 줄바꿈되지 않도록 한다.
const textStyle = 'text-[17px] font-normal leading-[150%] tracking-[-0.34px] text-neutral-90 break-keep'
const bodyStyle = 'text-sm font-normal leading-relaxed text-neutral-70 break-keep'
function Bullet({ children }: { children: ReactNode }) {
return (
<div className="flex items-start py-[6px]">
<p className="ml-[8px] mr-[6px] flex-shrink-0">•</p>
<div className={`${textStyle} flex-1`}>{children}</div>
<div className="flex items-start gap-2.5 py-1.5">
<span className="mt-[7px] size-1.5 shrink-0 rounded-full bg-brand-600" />
<div className={`${bodyStyle} flex-1`}>{children}</div>
</div>
)
}
@@ -23,24 +22,26 @@ export function GuideContent() {
return (
<div className="flex w-full flex-col">
<div className="headline-3 mb-10 break-keep text-center text-neutral-90">
<div className="mb-5 break-keep text-center text-base font-bold text-neutral-90">
협상 유의 사항 및 서비스 이용 방법 안내
</div>
<div className="flex flex-col items-start">
<div className={`${textStyle} mb-2`}>
협상과 관련하여 다음 사항을 참고하여 견적에 참여해 주시기 바랍니다.
</div>
<div className={`${bodyStyle} mb-2`}>
협상과 관련하여 다음 사항을 참고하여 견적에 참여해 주시기 바랍니다.
</div>
<div className="flex flex-col divide-y divide-border/60 rounded-xl border border-border px-4 py-1">
<Bullet>
협상 개시는&nbsp;
<span className="font-bold">Negosium 시스템의 협상 참여 버튼을 클릭하는 순간부터 시작</span>
<span className="font-semibold text-neutral-90">
Negosium 시스템의 협상 참여 버튼을 클릭하는 순간부터 시작
</span>
됩니다.
</Bullet>
<Bullet>
부여된 협상 시간에&nbsp;
<span className="font-bold">
<span className="font-semibold text-neutral-90">
응찰하지 않는 경우, 협상 참여의사가 없는 것으로 간주하여 재견적으로 진행
</span>
될 수 있습니다.
@@ -48,25 +49,23 @@ export function GuideContent() {
<Bullet>
협상에 입력되는 모든 가격은&nbsp;
<span className="font-bold text-negative">
<span className="font-semibold text-negative">
{vat} 및 {deliveryFee}
</span>
&nbsp;기준이며,&nbsp;
<span className="font-bold">
<span className="font-semibold text-neutral-90">
할인을 요청하는 경우 기존 공급가격에 할인율이 적용된 가격으로 환산
</span>
되어 제시됩니다.
</Bullet>
<Bullet>
본 협상 결과에 대해서는 협상자와 협상대상자 간의 비밀 유지 조건으로 진행되고, 협상에서
얻어진 결과나 내용에 대해서는 당사자를 제외하고 제 3자에 공유할 수 없으며, 비밀 유지를
전제로 진행됩니다.
본 협상 결과에 대해서는 협상자와 협상대상자 간의 비밀 유지 조건으로 진행되고, 협상에서 얻어진 결과나 내용에
대해서는 당사자를 제외하고 제 3자에 공유할 수 없으며, 비밀 유지를 전제로 진행됩니다.
</Bullet>
<Bullet>
협상이 종결되면 특별한 사유 없이 취소 변경이 불가하니, 신중하게 협상에 참여해 주시기
바랍니다.
협상이 종결되면 특별한 사유 없이 취소 변경이 불가하니, 신중하게 협상에 참여해 주시기 바랍니다.
</Bullet>
<Bullet>안내된 사항 외 부분은 기존 견적 프로세스와 동일한 부분 유의 바랍니다.</Bullet>
@@ -78,13 +77,12 @@ export function GuideContent() {
// 하단 문의 안내 박스
export function GuideContactBox() {
return (
<div className="flex w-full flex-col items-center gap-2 rounded-[16px] bg-neutral-10 p-6">
<div className={`${textStyle} text-center`}>
기타 협상과정에서 궁금한 사항이나 문의하실 사항은 아래의 연락처로 상담을 부탁드립니다.
<div className="flex w-full flex-col items-center gap-1.5 rounded-xl bg-neutral-10 p-4">
<div className={`${bodyStyle} text-center`}>
기타 협상 과정에서 궁금하거나 문의하실 사항은 아래 연락처로 상담 부탁드립니다.
</div>
{/* textStyle 의 font-normal 과 같은 요소에서 충돌하지 않도록 bold 는 별도 조합으로 준다 */}
<div className="break-keep text-center text-[17px] font-bold leading-[150%] tracking-[-0.34px] text-neutral-90">
헬프데스크 010-0000-0000, 이메일: o2odev@o2o.kr
<div className="break-keep text-center text-sm font-bold text-neutral-90">
헬프데스크 010-0000-0000 · o2odev@o2o.kr
</div>
</div>
)
@@ -7,19 +7,19 @@ import { GuideContent, GuideContactBox } from './GuideContent'
export function ServiceGuidePopup({ onClose }: { onClose: () => void }) {
return (
<Modal onClose={onClose}>
<div className="flex max-h-[90vh] w-full max-w-[1000px] flex-col items-end gap-6 overflow-y-auto rounded-3xl bg-white px-12 pb-[56px] pt-8">
<div className="m-4 flex max-h-[90vh] w-full max-w-[720px] flex-col items-end gap-4 overflow-y-auto rounded-2xl border border-border bg-white px-6 pb-10 pt-6 shadow-xl animate-scale-in sm:px-12">
<button
type="button"
aria-label="닫기"
onClick={onClose}
className={cn(
'flex size-10 flex-shrink-0 items-center justify-center rounded-full bg-neutral-10',
'flex size-9 flex-shrink-0 items-center justify-center rounded-full bg-neutral-10 text-neutral-70 hover:bg-neutral-20',
interactive,
)}
>
<X size={20} className="text-neutral-80" />
<X size={20} />
</button>
<div className="flex w-full flex-col gap-6 px-[40px]">
<div className="flex w-full flex-col gap-6">
<GuideContent />
<GuideContactBox />
</div>
@@ -10,8 +10,8 @@ interface ServiceInfoPopupProps {
}
const buttonStyle = cn(
'flex h-[50px] w-[168px] items-center justify-center rounded-full',
'border border-neutral-30 bg-white title-5 text-neutral-70',
'flex h-[46px] flex-1 sm:flex-none sm:w-[168px] items-center justify-center rounded-xl',
'border border-border bg-white text-sm font-bold text-neutral-70 hover:bg-neutral-10',
interactive,
)
@@ -20,13 +20,13 @@ export function ServiceInfoPopup({ isOpen, onNeverShowAgain, onCloseToday }: Ser
if (!isOpen) return null
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-[rgba(0,0,0,0.40)] p-4">
<div className="flex max-h-[90vh] w-full max-w-[1000px] flex-col overflow-y-auto rounded-[24px] bg-white px-[80px] pb-[48px] pt-[56px]">
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 backdrop-blur-[2px]">
<div className="flex max-h-[90vh] w-full max-w-[720px] flex-col overflow-y-auto rounded-2xl border border-border bg-white px-6 pb-6 pt-8 shadow-xl animate-scale-in sm:px-12 sm:pt-10">
<div className="mb-6 flex w-full flex-col gap-5">
<GuideContent />
<GuideContactBox />
</div>
<div className="flex w-full justify-center gap-3">
<div className="flex w-full justify-center gap-2 sm:gap-3">
<button type="button" className={buttonStyle} onClick={onNeverShowAgain}>
안내 보지 않기
</button>
@@ -1,61 +1,77 @@
import { CheckCircle2 } from 'lucide-react'
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
import { useMeQuery } from '@/apis'
import type { SessionField } from '@/apis/auth/auth.type'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
interface BidSummaryProps {
itemName: string
itemCode: string
bidPrice: number
deliveryType: string
isVAT: boolean
}
// 투찰 결과 요약 카드
export function BidSummary({ itemName, itemCode, bidPrice, deliveryType, isVAT }: BidSummaryProps) {
return (
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-4">
<h1 className="headline-3 text-neutral-90">투찰 결과 요약</h1>
<BidItem title="상품명" value={itemName || '-'} />
<BidItem title="상품 코드" value={itemCode || '-'} />
<BidPrice title="투찰 가격" number={bidPrice || 0} isVAT={isVAT} />
<BidItem title="배송형태" value={deliveryType || '-'} />
</div>
)
// 부가정보 값 표시 포맷(불리언→예/아니오, 숫자→천단위, 그 외→문자열)
function formatFieldValue(type: SessionField['type'], value: unknown): string {
if (type === 'boolean') return value ? '예' : '아니오'
if (type === 'number') return Number(value).toLocaleString()
return String(value)
}
function BidItem({ title, value }: { title: string; value: string }) {
// 투찰 결과 요약 카드 (보고서식 final-summary)
// 공급사가 마무리에서 입력한 부가정보(회사설정 session_fields + 의견)가 있으면 함께 표시한다(입력완료 시 요약 갱신).
export function BidSummary({ itemName, itemCode, bidPrice }: BidSummaryProps) {
// VAT 표기는 회사 설정 기준(item_vat_yn). vat_yn 미관리(hidden)면 비어 라벨을 생략한다.
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
const custom = useChatInitStore((s) => s.custom)
const { data: user } = useMeQuery()
const fields: SessionField[] = user?.sessionFields ?? []
const priceStr = (bidPrice || 0).toLocaleString()
// 부가정보(회사설정 session_fields) — 완료 요약엔 구조를 항상 노출(미입력 값은 '-')
const extraRows = fields.map((f) => {
const v = custom?.[f.key]
const has = v !== undefined && v !== null && v !== ''
return { key: f.key, label: f.label, value: has ? formatFieldValue(f.type, v) : '-' }
})
const opinion = custom?.opinion ? String(custom.opinion) : ''
return (
<div className="flex items-start gap-2">
<Dot />
<div className="flex flex-1 whitespace-pre-wrap">
<span className="body-1-read-b">{title} :</span>
<div className="flex body-1-read-r">&nbsp;{value}</div>
<div className="w-full rounded-2xl border-2 border-brand-light bg-white p-5 shadow-md">
<div className="mb-4 flex items-center gap-2">
<CheckCircle2 className="size-5 text-success" />
<h3 className="text-sm font-bold text-neutral-90">투찰 결과 요약</h3>
</div>
</div>
)
}
function BidPrice({ number, isVAT, title }: { number: number; isVAT: boolean; title: string }) {
const numberString = number.toLocaleString()
return (
<div className="flex items-start gap-2">
<Dot />
<div className="flex flex-1">
<div className="body-1-read-b flex flex-shrink-0">{title} :</div>
<div className="flex flex-1 flex-wrap">
<span className="body-1-read-b text-negative break-keep">&nbsp;{numberString}원</span>
<span className="body-1-read-b text-neutral-90 break-keep">
&nbsp;({numberToKorean(parseInt(numberString.replace(/,/g, '')))}원)
<div className="divide-y divide-border/60 rounded-xl border border-border">
<Row label="상품명" value={itemName || '-'} />
<Row label="상품 코드" value={itemCode || '-'} mono />
<div className="flex items-start justify-between gap-3 px-4 py-3">
<span className="shrink-0 text-sm text-neutral-60">투찰 가격</span>
<span className="min-w-0 flex-1 break-keep text-right text-sm">
<span className="font-bold text-[#E5484D]">{priceStr}원</span>
<span className="text-neutral-70"> ({numberToKorean(bidPrice || 0)}원)</span>
{item_vat_yn ? <span className="text-neutral-70"> {item_vat_yn}</span> : null}
</span>
<span className="body-1-read-b text-neutral-90 break-keep">&nbsp;{isVAT ? 'VAT포함' : 'VAT별도'}</span>
</div>
{extraRows.map((r) => (
<Row key={r.key} label={r.label} value={r.value} />
))}
{/* 의견은 타결·결렬 공통 기본 필드 — 값이 없어도 항상 표시 */}
<Row label="의견" value={opinion || '-'} />
</div>
</div>
)
}
function Dot() {
function Row({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
return (
<div className="flex justify-end items-center w-[26px] h-[30px]">
<p className="body-1-read-r">•</p>
<div className="flex items-start justify-between gap-3 px-4 py-3">
<span className="shrink-0 text-sm text-neutral-60">{label}</span>
<span
className={`min-w-0 flex-1 break-keep text-right text-sm font-semibold text-neutral-90 ${mono ? 'font-mono' : ''}`}
>
{value}
</span>
</div>
)
}
@@ -1,78 +1,31 @@
import { cn } from '@/lib'
// 협상 성공률 바 (0~100%). 구간별 색: 빨강(~30) / 주황(~70) / 초록(70~)
function selectBgColor(index: number, currentStep: number): string {
let fill = '#E71C3B'
if (currentStep > 3 && currentStep <= 7) fill = '#FDB21C'
if (currentStep > 7) fill = '#16BD14'
return index <= currentStep ? fill : '#ddd'
}
function UnitBlock({ blockIndex, percent }: { blockIndex: number; percent: number }) {
const minBlockPercent = blockIndex * 10
const maxBlockPercent = (blockIndex + 1) * 10
const remindCount = percent - minBlockPercent
let nodeType: 'fill' | 'empty' | 'half' = 'empty'
if (maxBlockPercent < percent) nodeType = 'fill'
else if (minBlockPercent <= percent) nodeType = 'half'
return (
<div className="flex flex-col items-center flex-1">
<div className="flex w-full h-3">
{Array.from({ length: 10 }).map((_, i) => {
let color = selectBgColor(blockIndex, Math.floor(percent / 10))
if (nodeType === 'half' && i >= remindCount) color = '#ddd'
const subBlockPercent = blockIndex * 10 + i + 1
const isTarget = subBlockPercent === percent
const isLeftAlign = percent < 90
return (
<div key={i} className="flex-1 h-full rounded-[1px] relative" style={{ backgroundColor: color }}>
{isTarget && (
<div className="pointer-events-none absolute bottom-full -top-4 left-1/2 -translate-x-1/2 z-10">
<div className="relative w-0 h-0">
<div className="absolute -top-2 left-[calc(50%+4px)] -translate-x-1/2 w-0 h-0 border-l-[8px] border-r-[8px] border-t-[14px] border-l-transparent border-r-transparent border-t-black" />
<span
className={cn(
'absolute top-[calc(50%-2px)] -translate-y-1/2 text-[24px] leading-none font-bold tabular-nums text-black whitespace-nowrap',
isLeftAlign ? 'left-[18px]' : 'right-[10px]',
)}
>
{percent}%
</span>
</div>
</div>
)}
</div>
)
})}
</div>
</div>
)
}
// 협상 성공률 카드 (0~100%). 10칸 컬러 블록바 — 구간별 색(빨강→주황→초록)으로 채운다.
export function Indicator({ number }: { number: number }) {
const percent = Math.min(Math.max(number, 0), 100)
const filled = Math.round(percent / 10) // 0~10칸
const color = percent < 40 ? '#F04452' : percent < 70 ? '#F5A623' : '#0B8F57'
return (
<div className="flex w-full flex-col gap-3 bg-neutral-00 rounded-[28px] px-10 py-[36px]">
<h1 className="title-1 text-neutral-90">협상 성공률</h1>
<div className="flex flex-col gap-2">
{percent === 0 ? (
<div className="relative h-6">
<div className="absolute left-[20px] -translate-x-1/2 text-xl text-black font-bold">▼&nbsp;0%</div>
</div>
) : (
<div className="h-6" />
)}
<div className="flex gap-1">
{Array.from({ length: 10 }).map((_, i) => (
<UnitBlock key={i} blockIndex={i} percent={percent} />
))}
</div>
<div className="w-full rounded-2xl border border-border bg-white p-5 shadow-sm">
<div className="flex items-center justify-between">
<h3 className="text-sm font-bold text-neutral-90">협상 성공률</h3>
<span className="font-mono text-base font-extrabold" style={{ color }}>
{percent}%
</span>
</div>
<div className="mt-3 flex gap-1">
{Array.from({ length: 10 }).map((_, i) => (
<div
key={i}
className="h-3.5 flex-1 rounded-[3px] transition-colors duration-300"
style={{ backgroundColor: i < filled ? color : 'var(--neutral-20)' }}
/>
))}
</div>
<p className="mt-2 text-xs text-neutral-60">
협상이 진행될수록 성공률이 실시간으로 갱신됩니다.
</p>
</div>
)
}
@@ -10,6 +10,7 @@ export function OtherReason({
onChange,
isError,
disabled,
onSubmit,
}: {
inputValue: string
setInputValue: (value: string) => void
@@ -18,6 +19,7 @@ export function OtherReason({
onChange: (value: string) => void
isError: boolean
disabled?: boolean
onSubmit?: () => void
}) {
const isChecked = selectedValue === '기타'
const ref = useRef<HTMLTextAreaElement>(null)
@@ -39,19 +41,20 @@ export function OtherReason({
const isTextareaDisabled = disabled || !isChecked
return (
<div className="flex flex-col gap-1">
<div className="flex items-start gap-2">
<label className={cn('flex items-start gap-2 flex-shrink-0', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}>
<input
<div className="flex flex-col gap-1.5">
<div className="flex items-start gap-2.5">
<label className={cn('flex shrink-0 items-start gap-2.5', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}>
<span
className={cn(
'appearance-none w-[16px] h-[16px] mt-[10px] flex-shrink-0 rounded-full border-[1.5px]',
disabled ? 'cursor-not-allowed' : 'cursor-pointer',
isChecked
? 'border-neutral-70 bg-[radial-gradient(circle,var(--neutral-70)_40%,white_40%)]'
: isError
? 'border-negative bg-white'
: 'border-neutral-60 bg-white',
'mt-0.5 flex size-[18px] shrink-0 items-center justify-center rounded-full border-2 transition-colors',
isChecked ? 'border-brand-600' : isError ? 'border-negative' : 'border-neutral-40',
disabled && 'opacity-60',
)}
>
{isChecked && <span className="size-2.5 rounded-full bg-brand-600" />}
</span>
<input
className="sr-only"
type="radio"
name="rejectrsp"
value="기타"
@@ -59,26 +62,33 @@ export function OtherReason({
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
/>
<div className={cn('reject break-keep whitespace-nowrap mt-[4px] flex', disabled && 'text-neutral-60')}>
기타
</div>
<span className={cn('text-sm text-neutral-80', disabled && 'text-neutral-50')}>기타</span>
</label>
<textarea
ref={ref}
className={cn(
'w-full px-3 py-2 body-3 resize-none border border-neutral-40 rounded-[8px] outline-none transition-all duration-200 placeholder:text-neutral-60 focus:border-neutral-70 focus:outline-none',
isTextareaDisabled ? 'bg-neutral-10 text-neutral-60 cursor-not-allowed' : 'bg-white text-neutral-90',
'w-full resize-none rounded-xl border px-3 py-2 text-sm outline-none transition-all placeholder:text-neutral-50',
isTextareaDisabled
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
errorMessage && 'border-negative',
)}
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={(e) => {
// Enter=제출, Shift+Enter=줄바꿈. 한글 조합 중 Enter 는 무시.
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && onSubmit) {
e.preventDefault()
onSubmit()
}
}}
placeholder="제시한 가격을 수용할 수 없는 이유를 작성해주세요."
disabled={isTextareaDisabled}
rows={1}
style={{ minHeight: '35px', lineHeight: '20px' }}
style={{ minHeight: '38px', lineHeight: '20px' }}
/>
</div>
{errorMessage && <div className="body-5 text-negative pl-[65px]">{errorMessage}</div>}
{errorMessage && <div className="pl-[30px] text-xs font-medium text-negative">{errorMessage}</div>}
</div>
)
}
@@ -1,115 +0,0 @@
import { useState, useMemo } from 'react'
import { cn } from '@/lib'
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
import { findRestoreScript, extractPart } from '@/features/chat/lib/rejectForm'
import { SelectRadio, SubmitButton } from '@/features/chat/components/templates/rejectControls'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
const MAX_PRICE = 999999999999999
// 재견적 실패 시: 최종 공급 희망 가격 + 배송 형태 입력 폼
export function RejectCM() {
const isLoading = useChatStore((s) => s.isLoading)
const sendMessage = useChatStore((s) => s.sendMessage)
const messages = useChatStore((s) => s.messages)
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
const isVAT = item_vat_yn === 'VAT별도'
// 폼 값은 이전 제출 내역에서 1회만 복원 (setter 미사용 = lazy 초기화 전용)
const restored = useState(() => findRestoreScript(messages, 'rejectCM'))[0]
const [price, setPrice] = useState(() => extractPart(restored, '공급희망가격-'))
const [selectedReason, setSelectedReason] = useState(() => extractPart(restored, '배송형태-'))
const [priceErrorMessage, setPriceErrorMessage] = useState('')
const [radioErrorMessage, setRadioErrorMessage] = useState('')
// 제출 완료 여부는 messages 변화에 반응해야 함 (제출 후 갱신 반영)
const isSubmitted = useMemo(() => Boolean(findRestoreScript(messages, 'rejectCM')), [messages])
const isValid = Boolean(price && parseInt(price) > 0) && Boolean(selectedReason)
const handlePriceChange = (value: string) => {
const numeric = value.replace(/\D/g, '')
if (numeric && parseInt(numeric) > MAX_PRICE) return
setPrice(numeric)
if (numeric) setPriceErrorMessage('')
}
const koreanPrice = (() => {
if (!price) return '영'
const n = parseInt(price)
return Number.isNaN(n) || n === 0 ? '영' : numberToKorean(n)
})()
const handleSubmit = () => {
setPriceErrorMessage(!price || parseInt(price) === 0 ? '가격을 입력해주세요.' : '')
setRadioErrorMessage(!selectedReason ? '배송 형태를 선택해주세요.' : '')
if (isValid && !isLoading && !isSubmitted) {
sendMessage(`공급희망가격-${price}, 배송형태-${selectedReason}`, 'text')
}
}
const isDisabled = isLoading || isSubmitted
return (
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-2 transition-all duration-300">
<div className="flex w-full h-[48px] bg-[#CD2A2D] headline-3 text-neutral-00 rounded-[12px] items-center justify-center">
최종 공급 희망 가격 입력
</div>
<div className="reject break-keep py-2">
최종 공급 희망 가격과 배송 형태를 입력하여 주시기 바랍니다.
<br />
가격 검토를 통해 경쟁력 있는 가격일 경우 다시 협상에 참여할 기회가 주어지오니 신중한 가격 제안 부탁드립니다.
</div>
<div className="flex flex-col w-full gap-1">
<div className="flex w-full items-start gap-4">
<div className="flex reject-2 whitespace-nowrap pt-2 flex-shrink-0 w-[110px]">공급 희망 가격</div>
<div className="flex flex-wrap w-full items-center pt-2">
<div className="flex items-center gap-2">
<input
type="text"
className={cn(
'text-right max-w-[220px] h-full max-h-[35px] border p-2 body-3 placeholder:text-neutral-60 focus:border-neutral-70 rounded-[8px] outline-none border-neutral-40',
isDisabled ? 'bg-neutral-10 text-neutral-60 cursor-not-allowed' : 'bg-white text-neutral-90',
)}
value={price ? parseInt(price).toLocaleString() : ''}
onChange={(e) => handlePriceChange(e.target.value)}
placeholder="0"
disabled={isDisabled}
/>
<div className="reject whitespace-nowrap mr-2">원{isVAT && '(VAT 별도)'}</div>
</div>
<div className="reject-gray whitespace-nowrap">[{koreanPrice} 원]</div>
</div>
</div>
{priceErrorMessage && <div className="body-5 text-negative pl-[126px]">{priceErrorMessage}</div>}
</div>
<div className="flex w-full gap-4">
<div className="flex reject-2 whitespace-nowrap pt-2 flex-shrink-0 w-[110px]">배송 형태</div>
<div className="flex w-full items-center justify-between pr-20 flex-wrap">
{['협력사배송', '지정택배배송', '픽업배송'].map((opt) => (
<SelectRadio
key={opt}
text={opt === '협력사배송' ? '협력사 배송' : opt}
value={opt}
name="rejectcm"
selectedValue={selectedReason}
onChange={(v) => {
setSelectedReason(v)
setRadioErrorMessage('')
}}
errorMessage={radioErrorMessage}
disabled={isDisabled}
/>
))}
</div>
</div>
<div className="flex w-full items-center justify-center mt-4">
<SubmitButton isValid={isValid} isLoading={isLoading} isSubmitted={isSubmitted} onSubmit={handleSubmit} />
</div>
</div>
)
}
@@ -1,155 +0,0 @@
import { useState, useMemo } from 'react'
import { cn } from '@/lib'
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
import { SelectRadio, SubmitButton } from '@/features/chat/components/templates/rejectControls'
import { OtherReason } from '@/features/chat/components/templates/OtherReason'
import { findRestoreScript, restoreRejectRSP } from '@/features/chat/lib/rejectForm'
const MAX_PRICE = 999999999999999
const REASONS = [
{ value: '단가인상', text: "'원재료 가격 상승' 또는 '제조사 가격 인상'으로 요청한 공급가격을 맞출 수 없습니다." },
{ value: '수량', text: '주문 수량이 적어, 소량 생산 시 발생하는 제조비용으로 맞출 수 없습니다.' },
{ value: '단종', text: '현재 단종된 제품으로 물량 수급이 원활하지 않아 가격을 맞출 수 없습니다.' },
{ value: '품절', text: '해당 상품이 품절되어 납품할 수 없습니다.' },
]
// 협상 합의 불가 시: 최종 제안 단가 + 합의 불가 사유 입력 폼
export function RejectRSP() {
const isLoading = useChatStore((s) => s.isLoading)
const sendMessage = useChatStore((s) => s.sendMessage)
const messages = useChatStore((s) => s.messages)
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
const isVAT = item_vat_yn === 'VAT별도'
// 폼 값은 이전 제출 내역에서 1회만 복원 (setter 미사용 = lazy 초기화 전용)
const restored = useState(() => restoreRejectRSP(findRestoreScript(messages, 'rejectRSP')))[0]
const [price, setPrice] = useState(restored.price)
const [selectedReason, setSelectedReason] = useState(restored.selectedReason)
const [reason, setReason] = useState(restored.reason)
const [otherErrorMessage, setOtherErrorMessage] = useState('')
const [priceErrorMessage, setPriceErrorMessage] = useState('')
const [radioErrorMessage, setRadioErrorMessage] = useState('')
const isSubmitted = useMemo(
() => Boolean(findRestoreScript(messages, 'rejectRSP')),
[messages],
)
const isValid =
Boolean(price && parseInt(price) > 0) &&
Boolean(selectedReason) &&
(selectedReason !== '기타' || reason.trim() !== '')
const handlePriceChange = (value: string) => {
const numeric = value.replace(/\D/g, '')
if (numeric && parseInt(numeric) > MAX_PRICE) return
setPrice(numeric)
if (numeric) setPriceErrorMessage('')
}
const handleRadioChange = (value: string) => {
setSelectedReason(value)
setRadioErrorMessage('')
if (value !== '기타') {
setReason('')
setOtherErrorMessage('')
}
}
const koreanPrice = (() => {
if (!price) return '영'
const n = parseInt(price)
return Number.isNaN(n) || n === 0 ? '영' : numberToKorean(n)
})()
const handleSubmit = () => {
setPriceErrorMessage(!price || parseInt(price) === 0 ? '가격을 입력해주세요.' : '')
setRadioErrorMessage(!selectedReason ? '사유를 선택해주세요.' : '')
setOtherErrorMessage(selectedReason === '기타' && !reason.trim() ? '기타 사유를 입력해주세요.' : '')
if (isValid && !isLoading && !isSubmitted) {
const script =
selectedReason === '기타'
? `공급희망가격-${price}, 합의불가사유-기타-${reason.trim()}`
: `공급희망가격-${price}, 합의불가사유-${selectedReason}`
sendMessage(script, 'text')
}
}
const isDisabled = isLoading || isSubmitted
return (
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-2 transition-all duration-300">
<div className="flex w-full h-[48px] bg-[#CD2A2D] headline-3 text-neutral-00 rounded-[12px] items-center justify-center">
협상 합의 불가 사유 및 최종 제안 단가 입력
</div>
<div className="reject break-keep py-2">
협상이 합의에 도달하지 못하였습니다. 최종 희망하는 가격을 입력해주시기 바랍니다.
<br />
추가로 제시한 가격을 수용할 수 없는 이유를 선택하여 주시기 바라며, 목록에 없는 경우 기타 항목 선택 후 간단한 사유를
기재하여 주시기 바랍니다.
</div>
<div className="flex flex-col w-full gap-1">
<div className="flex w-full items-start gap-4">
<div className="flex reject-2 whitespace-nowrap pt-2 flex-shrink-0 w-[110px]">공급 희망 가격</div>
<div className="flex flex-wrap w-full items-center pt-2">
<div className="flex items-center gap-2">
<input
type="text"
className={cn(
'text-right max-w-[220px] h-full max-h-[35px] border p-2 body-3 placeholder:text-neutral-60 focus:border-neutral-70 rounded-[8px] outline-none border-neutral-40',
isDisabled ? 'bg-neutral-10 text-neutral-60 cursor-not-allowed' : 'bg-white text-neutral-90',
)}
value={price ? parseInt(price).toLocaleString() : ''}
onChange={(e) => handlePriceChange(e.target.value)}
placeholder="0"
disabled={isDisabled}
/>
<div className="reject whitespace-nowrap mr-2">원{isVAT && '(VAT 별도)'}</div>
</div>
<div className="reject-gray whitespace-nowrap">[{koreanPrice} 원]</div>
</div>
</div>
{priceErrorMessage && <div className="body-5 text-negative pl-[126px]">{priceErrorMessage}</div>}
</div>
<div className="flex w-full gap-4">
<div className="flex reject-2 whitespace-nowrap pt-2 pb-2 flex-shrink-0 w-[110px]">합의 불가 사유</div>
<div className="flex w-full flex-col mt-2 gap-2">
{REASONS.map((r) => (
<SelectRadio
key={r.value}
text={r.text}
value={r.value}
name="rejectrsp"
selectedValue={selectedReason}
onChange={handleRadioChange}
errorMessage={radioErrorMessage}
disabled={isDisabled}
/>
))}
<OtherReason
inputValue={reason}
setInputValue={(v) => {
if (selectedReason !== '기타') return
setReason(v)
if (v.trim()) setOtherErrorMessage('')
}}
errorMessage={otherErrorMessage}
selectedValue={selectedReason}
onChange={handleRadioChange}
isError={!!radioErrorMessage}
disabled={isDisabled}
/>
</div>
</div>
<div className="flex w-full items-center justify-center mt-6">
<SubmitButton isValid={isValid} isLoading={isLoading} isSubmitted={isSubmitted} onSubmit={handleSubmit} />
</div>
</div>
)
}
@@ -1,49 +1,93 @@
import { CheckCircle2 } from 'lucide-react'
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
import { formatLeadTime } from '@/features/chat/lib/format'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
import type { ChatSummary } from '@/features/chat/types'
// 협상 결과 요약 카드
export function Summary({ data }: { data: ChatSummary }) {
const priceStr = (data.final_price || 0).toLocaleString()
// VAT 표기는 회사 설정 기준(item_vat_yn). vat_yn 미관리(hidden)면 비어 라벨을 생략한다.
const item_vat_yn = useChatInitStore((s) => s.item_vat_yn)
// 공급사가 마무리에서 남긴 의견(있을 때만 표시)
const custom = useChatInitStore((s) => s.custom)
const opinion = custom?.opinion ? String(custom.opinion) : ''
// 납기 라벨은 회사 설정(labels.lead_time) 기준 — IMK 등은 '표준납기'. 미설정 시 기본 '배송 리드타임'.
const labels = useChatInitStore((s) => s.labels)
const leadTimeLabel = labels?.['lead_time'] || '배송 리드타임'
return (
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-4">
<h1 className="headline-3 text-neutral-90">협상 결과 요약</h1>
<div className="body-1-read-r">
협상이 완료되어 아래와 같이 결과를 요약하오니 다시 한 번 최종 확인 부탁 드립니다. 최종 확인 후 협상 결과에 대한
수정 변경은 불가함을 안내 드립니다.
<div className="w-full rounded-2xl border border-border bg-white p-5 shadow-sm">
<div className="mb-3 flex items-center gap-2">
<CheckCircle2 className="size-5 text-success" />
<h3 className="text-sm font-bold text-neutral-90">협상 결과 요약</h3>
</div>
<div className="flex flex-col">
<div className="body-1-read-r">협상 개시 시간 : {formatKoreanDateTime(data.nego_start_date)}</div>
<div className="body-1-read-r">협상 종료 시간 : {formatKoreanDateTime(data.nego_end_date)}</div>
<div className="body-1-read-r">
우선협상 대상자 : {data.supplier_name || '-'} ({data.supplier_manager_phone || '-'}){' '}
{data.supplier_manager_email || '-'}
<p className="text-sm leading-relaxed text-neutral-70 break-keep">
협상이 완료되어 아래와 같이 결과를 요약하오니 최종 확인 부탁드립니다. 최종 확인 후 협상 결과의 수정·변경은
불가함을 안내드립니다.
</p>
{/* 개요 */}
<div className="mt-4 space-y-1.5 rounded-xl bg-neutral-10 p-3.5 text-xs text-neutral-70">
<p>협상 개시: {formatKoreanDateTime(data.nego_start_date)}</p>
<p>협상 종료: {formatKoreanDateTime(data.nego_end_date)}</p>
<p>
우선협상 대상자: <span className="font-semibold text-neutral-90">{data.supplier_name || '-'}</span> (
{data.supplier_manager_phone || '-'}) {data.supplier_manager_email || '-'}
</p>
</div>
{/* 상세 내역 */}
<div className="mt-3 divide-y divide-border/60 rounded-xl border border-border">
<Row label="상품 코드" value={data.item_code || '-'} mono />
<Row label="상품명" value={data.item_name || '-'} />
<Row label="모델명" value={data.item_model || '-'} />
<Row label="제품 규격" value={data.item_spec || '-'} />
<Row label="최소 주문" value={data.item_moq || '-'} />
<Row label="배송 형태" value={data.item_delivery_type || '-'} />
<Row label={leadTimeLabel} value={formatLeadTime(data.item_lead_time) || '-'} />
<div className="flex items-start justify-between gap-3 px-4 py-3">
<span className="shrink-0 text-sm text-neutral-60">최종 협의 가격</span>
<span className="min-w-0 flex-1 break-keep text-right text-sm">
<span className="font-bold text-[#E5484D]">{priceStr}원</span>
<span className="text-neutral-70"> ({numberToKorean(data.final_price || 0)}원)</span>
{item_vat_yn ? <span className="text-neutral-70"> {item_vat_yn}</span> : null}
</span>
</div>
<div className="body-1-read-r">협상 상세 내역</div>
{/* 의견은 타결·결렬 공통 기본 필드 — 값이 없어도 항상 표시 */}
<Row label="의견" value={opinion || '-'} />
</div>
<div className="flex flex-col gap-4">
<DetailText title="상품 코드" value={data.item_code || '-'} />
<DetailText title="상품 명" value={data.item_name || '-'} />
<DetailText title="모델 명" value={data.item_model || '-'} />
<DetailText title="제품 규격" value={data.item_spec || '-'} />
<DetailText title="최소 주문" value={data.item_moq || '-'} />
<DetailText title="배송 형태" value={data.item_delivery_type || '-'} />
<DetailText title="배송 리드타임" value={formatLeadTime(data.item_lead_time) || '-'} />
<PriceText price={data.final_price} isVAT={data.item_isVAT} />
{/* 계약 / 구매담당자 */}
<div className="mt-3 space-y-1 text-xs text-neutral-70">
<p>공급 계약 기간: 협상 완료일로부터 1년 ({addOneYear(data.nego_end_date)})까지</p>
<p>
구매담당자: {data.md_name || '-'} ({data.md_phone_number || '-'}) {data.md_email || '-'}
</p>
</div>
<div className="flex flex-col">
<div className="body-1-read-r">
공급 계약 기간: 협상 완료일로부터 1년 ({addOneYear(data.nego_end_date)})까지
</div>
<div className="body-1-read-r">
담당 MD: {data.md_name || '-'} ({data.md_phone_number || '-'}) {data.md_email || '-'}
</div>
</div>
<div className="body-1-read-b">상기 내용에 이상이 없으며 최종 협상 결과에 동의하여 이를 승인합니다.</div>
<p className="mt-4 rounded-xl bg-brand-light px-4 py-3 text-sm font-bold text-brand-600 break-keep">
상기 내용에 이상이 없으며 최종 협상 결과에 동의하여 이를 승인합니다.
</p>
</div>
)
}
// ISO 시각 → 한국시(KST) 기준 부분값. 백엔드는 UTC(ISO)로 내려주므로 표시 시 KST 로 변환한다.
function Row({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
return (
<div className="flex items-start justify-between gap-3 px-4 py-3">
<span className="shrink-0 text-sm text-neutral-60">{label}</span>
<span
className={`min-w-0 flex-1 break-keep text-right text-sm font-semibold text-neutral-90 ${mono ? 'font-mono' : ''}`}
>
{value}
</span>
</div>
)
}
// ISO 시각 → KST 기준 부분값.
function kstParts(iso: string): Record<string, string> | null {
if (!iso) return null
const d = new Date(iso)
@@ -63,55 +107,16 @@ function kstParts(iso: string): Record<string, string> | null {
return out
}
// "YYYY년 MM월 dd일 HH시 MM분 SS초" (KST)
// "YYYY년 MM월 dd일 HH시 MM분" (KST)
function formatKoreanDateTime(iso: string): string {
const p = kstParts(iso)
if (!p) return '-'
return `${p.year}년 ${p.month}월 ${p.day}일 ${p.hour}시 ${p.minute}분 ${p.second}초`
return `${p.year}년 ${p.month}월 ${p.day}일 ${p.hour}시 ${p.minute}분`
}
// 협상 종료 시각 + 1년 → "YYYY년 MM월 dd일" (공급 계약 만료일)
// 협상 종료 시각 + 1년 → "YYYY년 MM월 dd일"
function addOneYear(iso: string): string {
const p = kstParts(iso)
if (!p) return '-'
return `${parseInt(p.year) + 1}년 ${p.month}월 ${p.day}일`
}
function DetailText({ title, value }: { title: string; value: string }) {
return (
<div className="flex items-start gap-2">
<Dot />
<div className="flex-1 whitespace-pre-wrap">
<span className="body-1-read-b">{title} :&nbsp;</span>
<span className="body-1-read-r">{value}</span>
</div>
</div>
)
}
function PriceText({ price, isVAT }: { price: number; isVAT: boolean }) {
const numberString = price.toLocaleString()
return (
<div className="flex items-start gap-2">
<Dot />
<div className="flex flex-1">
<div className="body-1-read-b flex flex-shrink-0">최종 협의 가격 :</div>
<div className="flex flex-1 flex-wrap">
<span className="body-1-read-b text-negative break-keep">&nbsp;{numberString}원</span>
<span className="body-1-read-b text-neutral-90 break-keep">
&nbsp;({numberToKorean(parseInt(numberString.replace(/,/g, '')))}원)
</span>
<span className="body-1-read-b text-neutral-90 break-keep">&nbsp;{isVAT ? 'VAT포함' : 'VAT별도'}</span>
</div>
</div>
</div>
)
}
function Dot() {
return (
<div className="flex justify-end items-center w-[26px] h-[30px]">
<p className="body-1-read-r">•</p>
</div>
)
}
@@ -22,17 +22,18 @@ export function SelectRadio({
}) {
const isChecked = selectedValue === value
return (
<label className={cn('flex items-center gap-2', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}>
<input
<label className={cn('flex items-start gap-2.5', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}>
<span
className={cn(
'appearance-none w-[16px] h-[16px] min-w-[16px] min-h-[16px] rounded-full border-[1.5px] whitespace-nowrap',
disabled ? 'cursor-not-allowed' : 'cursor-pointer',
isChecked
? 'border-neutral-70 bg-[radial-gradient(circle,var(--neutral-70)_40%,white_40%)]'
: errorMessage
? 'border-negative bg-white'
: 'border-neutral-60 bg-white',
'mt-0.5 flex size-[18px] shrink-0 items-center justify-center rounded-full border-2 transition-colors',
isChecked ? 'border-brand-600' : errorMessage ? 'border-negative' : 'border-neutral-40',
disabled && 'opacity-60',
)}
>
{isChecked && <span className="size-2.5 rounded-full bg-brand-600" />}
</span>
<input
className="sr-only"
type="radio"
name={name}
value={value}
@@ -40,7 +41,9 @@ export function SelectRadio({
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
/>
<div className={cn('reject break-keep', disabled && 'text-neutral-60')}>{text}</div>
<span className={cn('text-sm leading-relaxed text-neutral-80 break-keep', disabled && 'text-neutral-50')}>
{text}
</span>
</label>
)
}
@@ -59,15 +62,15 @@ export function SubmitButton({
if (isSubmitted) return null
const style = isLoading
? 'bg-neutral-40 text-neutral-80 cursor-not-allowed'
? 'bg-neutral-20 text-neutral-60 cursor-not-allowed'
: isValid
? 'bg-neutral-90 text-white cursor-pointer hover:bg-neutral-80'
: 'bg-neutral-20 text-neutral-60 cursor-not-allowed'
? 'bg-brand-600 text-white shadow-sm cursor-pointer hover:bg-brand-700 active:scale-[0.98]'
: 'bg-neutral-20 text-neutral-50 cursor-not-allowed'
return (
<button
className={cn(
'flex items-center justify-center w-[280px] h-[48px] rounded-[12px] text-base font-bold tracking-[-0.32px] transition-all duration-200',
'flex h-12 w-full max-w-[280px] items-center justify-center rounded-xl text-sm font-bold transition-all duration-200',
style,
)}
onClick={onSubmit}
@@ -1,4 +1,4 @@
import { useState, useRef, useId } from 'react'
import { useState, useRef, useId, useEffect } from 'react'
import { useChatStore } from '@/features/chat/stores/useChatStore'
// 단위(원/%) 오버레이 + 전송 버튼이 붙은 값 입력 (Percent / Price 공용)
@@ -22,9 +22,23 @@ function InputWithUnit({
ariaLabel: string
}) {
const errorId = useId()
// 입력 단계(percent/price)로 바뀌어 마운트될 때마다 바로 타이핑 가능하게
useEffect(() => {
inputRef.current?.focus()
}, [inputRef])
return (
<div className="relative flex flex-col gap-3">
<div className="relative flex items-center min-w-[480px] max-[1350px]:min-w-[420px] max-[1180px]:min-w-[320px]">
<div className="relative">
{/* 레이아웃 밖(absolute)에 띄워 에러가 떠도 input 위치가 안 변한다 */}
{error && (
<div
id={errorId}
role="alert"
className="absolute bottom-full left-1/2 -translate-x-1/2 mb-3 whitespace-nowrap rounded-full bg-white border border-border shadow-md px-4 py-1.5 text-sm font-semibold text-negative"
>
{error}
</div>
)}
<div className="relative flex items-center min-w-[220px] sm:min-w-[360px] min-[1180px]:min-w-[420px] min-[1350px]:min-w-[480px]">
<input
ref={inputRef}
type="text"
@@ -32,30 +46,25 @@ function InputWithUnit({
value={value}
onChange={onChange}
onKeyDown={(e) => e.key === 'Enter' && onSubmit()}
className="h-[50px] flex-1 bg-white border-none rounded-[999px] outline-none ring-1 ring-primary headline-3 text-negative placeholder:text-neutral-60 pl-[32px]"
className="h-[52px] flex-1 bg-neutral-10 rounded-xl outline-none border-2 border-brand-600 text-base font-bold text-neutral-90 placeholder:text-sm placeholder:font-normal placeholder:text-neutral-50 pl-4 pr-[124px]"
placeholder={placeholder}
aria-label={ariaLabel}
aria-invalid={!!error}
aria-describedby={error ? errorId : undefined}
/>
<div className="absolute left-[32px] headline-3 text-neutral-70 pointer-events-none">
<div className="absolute left-4 text-base font-bold text-neutral-70 pointer-events-none">
<span className="opacity-0">{value}</span>
{value && <span className="ml-1">{unit}</span>}
</div>
<button
type="button"
onClick={onSubmit}
className="absolute right-0 flex items-center justify-center min-w-[120px] h-[50px] px-[32px] bg-primary hover:brightness-[0.97] rounded-[999px] title-2 text-primary-foreground cursor-pointer whitespace-nowrap transition-colors duration-200"
className="absolute right-1.5 flex items-center justify-center min-w-[104px] h-[40px] px-6 bg-brand-600 hover:bg-brand-700 rounded-lg text-sm font-bold text-white shadow-sm cursor-pointer whitespace-nowrap transition-colors duration-200 active:scale-[0.98]"
aria-label="전송"
>
전송
</button>
</div>
{error && (
<div id={errorId} role="alert" className="absolute top-[62px] left-1/2 -translate-x-1/2 title-2 text-negative w-full text-center">
{error}
</div>
)}
</div>
)
}
@@ -160,6 +160,9 @@ export function useChatController(sessionId: string) {
useChatInitStore.getState().reset()
// init 은 진입 메타 캐시 — 비워 두어 재진입이 항상 최신 status 로 진입 게이트(1301)를 다시 타게 한다.
queryClient.removeQueries({ queryKey: chatKeys.init(sessionId) })
// messages 는 staleTime:Infinity 라 캐시가 남으면 재진입해도 다시 안 부른다 —
// 오프닝 생성 전(협상생성 상태)에 받은 빈 목록이 눌러앉아 채팅이 빈 화면으로 굳는다.
queryClient.removeQueries({ queryKey: chatKeys.messages(sessionId) })
}
}, [sessionId, sendMutate, navigate, queryClient])
@@ -0,0 +1,8 @@
// 협상 절차 5단계 — NegoStep(사이드) · MobileStepBar(모바일 상단)가 공유.
export const STEPS = [
{ name: '서비스안내', desc: '협상 방식과 유의사항을 확인합니다.' },
{ name: '담당자확인', desc: '협상 담당자 본인 여부를 확인합니다.' },
{ name: '협상품목안내', desc: '대상 품목과 기준 단가를 확인합니다.' },
{ name: '가격협상', desc: '공급 단가를 제안하고 조율합니다.' },
{ name: '협상종료', desc: '최종 합의 후 결과를 확인합니다.' },
]
@@ -16,7 +16,14 @@ export function deriveUserButtonConfig(
const options = last.next_input_type
if (last.chat_end) return { type: 'one-black', text: GO_TO_LIST_TEXT }
if (mode === 'confirm') return { type: 'one-black', text: options?.[0] || '' }
// 결렬 폼(rejectRSP/rejectCM)은 통일된 RejectForm 을 액션바에서 받는다(메시지 카드 아님).
if (last.bot_chat_type === 'rejectRSP' || last.bot_chat_type === 'rejectCM') return { type: 'reject' }
// 타결 요약이 뜬 뒤의 '동의' 단계 = 부가정보 입력 + 동의를 한 자리(액션바)에서 받는다.
// (요약 이후 confirm 단계에만 적용 — 재견적의 투찰확정/정보수정 같은 선택 단계는 그대로 둔다.)
const dealt = messages.some((m) => m.bot_chat_type === 'summaryRSP' || m.bot_chat_type === 'summaryCM')
if (mode === 'confirm') {
return dealt ? { type: 'extra-info', text: options?.[0] || '' } : { type: 'one-black', text: options?.[0] || '' }
}
if (mode === 'yes_no') return { type: 'black-white', textList: options || [] }
if (mode === 'percent') return { type: 'percent' }
if (mode === 'price') return { type: 'price', priceErrorMessage: priceErrorMessage || undefined }
@@ -16,6 +16,7 @@ const initialState: ChatInitData = {
session_status: 0,
item_id: '',
quotation_id: '',
qt_number: '',
item_name: '',
item_code: '',
item_image: '',
@@ -29,6 +30,8 @@ const initialState: ChatInitData = {
item_spec: '',
quotation_memo: '',
quotation_end_time: '',
custom: {},
labels: {},
}
export const useChatInitStore = create<ChatInitStore>((set) => ({
@@ -0,0 +1,16 @@
import { create } from 'zustand'
// 모바일(lg 미만) 협상 화면에서 좌/우 패널을 드로어로 여닫는 상태.
type Drawer = 'product' | 'status' | null
interface ChatUiStore {
drawer: Drawer
open: (drawer: Exclude<Drawer, null>) => void
close: () => void
}
export const useChatUiStore = create<ChatUiStore>((set) => ({
drawer: null,
open: (drawer) => set({ drawer }),
close: () => set({ drawer: null }),
}))
+5
View File
@@ -53,6 +53,8 @@ export type UserButtonType =
| 'percent'
| 'three-black'
| 'price'
| 'extra-info'
| 'reject'
| 'loading'
| ''
@@ -68,6 +70,7 @@ export type ChatInitData = {
session_status: number // SessionStatus 코드 (진입 시점 기준)
item_id: string
quotation_id: string
qt_number: string
item_name: string
item_code: string
item_image: string
@@ -81,4 +84,6 @@ export type ChatInitData = {
item_spec: string
quotation_memo: string
quotation_end_time: string
custom: Record<string, unknown> // 협상완료 부가정보 기존 입력값(프리필용)
labels: Record<string, string> // 회사 커스텀 라벨(companies.settings.labels). 상품 상세 필드명 치환용
}
@@ -1,49 +0,0 @@
import { cn, interactive } from '@/lib'
const PILL =
'flex items-center justify-center w-full max-w-[130px] h-[50px] rounded-full py-4 px-6 ' +
'text-lg font-semibold whitespace-nowrap ' +
interactive
export interface ActionSectionProps {
isParticipating: boolean
isRejecting: boolean
onParticipate: () => void
onReject: () => void
}
export function ActionSection({
isParticipating,
isRejecting,
onParticipate,
onReject,
}: ActionSectionProps) {
return (
<div className="flex w-full py-[35px] items-center justify-end gap-3">
<button
type="button"
onClick={onParticipate}
disabled={isParticipating}
className={cn(
PILL,
'bg-primary text-primary-foreground',
isParticipating && 'opacity-50 cursor-not-allowed',
)}
>
협상 참여
</button>
<button
type="button"
onClick={onReject}
disabled={isRejecting}
className={cn(
PILL,
'bg-background text-primary border border-primary',
isRejecting && 'opacity-50 cursor-not-allowed',
)}
>
거부
</button>
</div>
)
}
@@ -0,0 +1,157 @@
import { useState } from 'react'
import { X } from 'lucide-react'
import { Modal } from '@/components'
import { useMeQuery } from '@/apis'
import type { SessionField } from '@/apis/auth/auth.type'
import type { ListItem } from '../types'
export interface ExtraInfoPopupProps {
target: ListItem
onClose: () => void
/** 부가정보 저장 (custom = {key: value}) */
onSubmit: (custom: Record<string, unknown>) => void
}
// 협상완료 부가정보 입력 팝업. 필드 정의(session_fields)는 회사 설정(/me)에서 오고, 기존 입력값(target.custom)으로 프리필.
export function ExtraInfoPopup({ target, onClose, onSubmit }: ExtraInfoPopupProps) {
const { data: user } = useMeQuery()
const fields: SessionField[] = user?.sessionFields ?? []
const [values, setValues] = useState<Record<string, unknown>>(() => {
const init: Record<string, unknown> = {}
for (const f of fields) init[f.key] = target.custom?.[f.key] ?? (f.type === 'boolean' ? false : '')
return init
})
const [opinion, setOpinion] = useState<string>(() => String(target.custom?.opinion ?? ''))
// 부가정보는 협상 완료(동의) 시점에 확정 — 리스트에서는 항상 읽기전용(보기). 입력은 완료 챗에서만.
const readOnly = true
const set = (key: string, value: unknown) => setValues((v) => ({ ...v, [key]: value }))
const handleSubmit = () => {
// 빈 값은 제외하고 저장(부분 입력 허용)
const out: Record<string, unknown> = {}
for (const f of fields) {
const v = values[f.key]
if (f.type === 'boolean') out[f.key] = !!v
else if (v !== '' && v != null) out[f.key] = f.type === 'number' ? Number(v) : v
}
if (opinion.trim()) out.opinion = opinion.trim()
onSubmit(out)
onClose()
}
return (
<Modal onClose={onClose}>
<div className="w-full max-w-md overflow-hidden rounded-2xl border border-border bg-white shadow-xl animate-scale-in">
<div className="flex items-center justify-between border-b border-border p-5">
<div>
<h3 className="text-base font-bold text-neutral-90">협상완료 부가정보{readOnly ? ' (보기)' : ''}</h3>
<p className="mt-0.5 text-xs text-neutral-60">
{target.qt_number} · {target.item_name}
{readOnly ? ' · 제출 후에는 수정할 수 없습니다.' : ''}
</p>
</div>
<button
type="button"
onClick={onClose}
aria-label="닫기"
className="flex size-8 items-center justify-center rounded-full text-neutral-60 hover:bg-neutral-10"
>
<X className="size-4" />
</button>
</div>
<div className="space-y-4 p-5">
{fields.map((f) => (
<div key={f.key} className="space-y-1.5">
<label className="block text-sm font-semibold text-neutral-80">{f.label}</label>
{f.type === 'boolean' ? (
<button
type="button"
role="switch"
aria-checked={!!values[f.key]}
disabled={readOnly}
onClick={() => set(f.key, !values[f.key])}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors disabled:opacity-60 disabled:cursor-not-allowed ${
values[f.key] ? 'bg-brand-600' : 'bg-neutral-30'
}`}
>
<span
className={`inline-block size-5 transform rounded-full bg-white shadow transition-transform ${
values[f.key] ? 'translate-x-5' : 'translate-x-0.5'
}`}
/>
</button>
) : f.type === 'select' ? (
<select
value={String(values[f.key] ?? '')}
onChange={(e) => set(f.key, e.target.value)}
disabled={readOnly}
className="h-11 w-full rounded-xl border border-border bg-white px-3 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600 disabled:cursor-not-allowed disabled:bg-neutral-10 disabled:text-neutral-60"
>
<option value="">선택</option>
{(f.options ?? []).map((o) => (
<option key={o} value={o}>{o}</option>
))}
</select>
) : (
<input
type={f.type === 'number' ? 'number' : 'text'}
value={String(values[f.key] ?? '')}
onChange={(e) => set(f.key, e.target.value)}
disabled={readOnly}
className="h-11 w-full rounded-xl border border-border bg-white px-3 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600 disabled:cursor-not-allowed disabled:bg-neutral-10 disabled:text-neutral-60"
placeholder={f.label}
/>
)}
</div>
))}
<div className="space-y-1.5">
<label className="block text-sm font-semibold text-neutral-80">
의견 <span className="font-normal text-neutral-50">(선택)</span>
</label>
<textarea
value={opinion}
onChange={(e) => setOpinion(e.target.value)}
rows={2}
maxLength={255}
disabled={readOnly}
placeholder="추가로 남길 의견"
className="w-full resize-none rounded-xl border border-border bg-white px-3 py-2 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600 disabled:cursor-not-allowed disabled:bg-neutral-10 disabled:text-neutral-60"
/>
</div>
</div>
<div className="flex gap-2 border-t border-border p-5">
{readOnly ? (
<button
type="button"
onClick={onClose}
className="h-11 flex-1 rounded-xl border border-border text-sm font-bold text-neutral-70 hover:bg-neutral-10"
>
닫기
</button>
) : (
<>
<button
type="button"
onClick={onClose}
className="h-11 flex-1 rounded-xl border border-border text-sm font-bold text-neutral-70 hover:bg-neutral-10"
>
취소
</button>
<button
type="button"
onClick={handleSubmit}
className="h-11 flex-1 rounded-xl bg-brand-600 text-sm font-bold text-white hover:bg-brand-700 disabled:opacity-40"
>
저장
</button>
</>
)}
</div>
</div>
</Modal>
)
}
@@ -1,69 +0,0 @@
import { useState } from 'react'
import { ChevronDown } from 'lucide-react'
import { cn, interactive } from '@/lib'
export interface FilterGroupProps {
title: string
items: readonly string[]
selectedItem: string | null
onItemClick: (item: string) => void
defaultOpen?: boolean
}
export function FilterGroup({
title,
items,
selectedItem,
onItemClick,
defaultOpen = true,
}: FilterGroupProps) {
const [open, setOpen] = useState(defaultOpen)
return (
<div className="flex flex-col w-full">
<div className="flex justify-between items-center h-12 pl-3 pr-1">
<h3 className="text-2xl font-bold leading-[30px] text-foreground whitespace-nowrap">
{title}
</h3>
<button
type="button"
aria-expanded={open}
onClick={() => setOpen((v) => !v)}
className={cn('w-10 h-10 flex items-center justify-center text-muted-foreground', interactive)}
>
<ChevronDown
size={24}
className={cn('transition-transform duration-300', !open && 'rotate-180')}
/>
</button>
</div>
{/* grid-rows 0fr→1fr 펼침 */}
<div
className={cn(
'grid transition-[grid-template-rows,opacity] duration-300 ease-out',
open ? 'grid-rows-[1fr] opacity-100' : 'grid-rows-[0fr] opacity-0',
)}
>
<div className="overflow-hidden">
<div className="flex flex-col">
{items.map((item) => (
<button
key={item}
type="button"
onClick={() => onItemClick(item)}
className={cn(
'h-11 px-3 flex items-center rounded-lg text-left text-base text-foreground',
'whitespace-nowrap cursor-pointer transition active:scale-[0.98]',
selectedItem === item ? 'bg-secondary' : 'hover:bg-muted',
)}
>
{item}
</button>
))}
</div>
</div>
</div>
</div>
)
}
@@ -0,0 +1,92 @@
import { X } from 'lucide-react'
import { Modal } from '@/components'
import { cn, interactive } from '@/lib'
// 공급사 포털 목록 화면 이용안내. 상태(진행)·결과(마감)·재협상 3파트로 최근 추가된 용어를 설명한다.
// 헤더의 '이용안내' 버튼으로 여는 수동형 팝업. X·배경 클릭·ESC 로 닫는다.
export function GuidePopup({ onClose }: { onClose: () => void }) {
return (
<Modal onClose={onClose}>
<div className="m-4 flex max-h-[90vh] w-full max-w-[560px] flex-col overflow-y-auto rounded-2xl border border-border bg-white p-6 shadow-xl animate-scale-in sm:p-8">
<div className="mb-5 flex items-start justify-between gap-4">
<div>
<h2 className="text-lg font-extrabold text-neutral-90">이용안내</h2>
<p className="mt-1 text-[13px] text-neutral-60">협상 목록의 상태·결과·재협상을 안내합니다.</p>
</div>
<button
type="button"
aria-label="닫기"
onClick={onClose}
className={cn('flex size-9 shrink-0 items-center justify-center rounded-full bg-neutral-10 text-neutral-70 hover:bg-neutral-20', interactive)}
>
<X size={18} />
</button>
</div>
<div className="flex flex-col gap-6">
<Section title="진행 상태" desc="협상 세션이 지금 어느 단계인지 — 내가 무엇을 할지 알려줍니다.">
<Row badge="협상 대기" tone="wait" text="초청받은 협상. 입장해서 가격 협상을 시작하세요." />
<Row badge="협상 중" tone="prog" text="가격을 조율하는 중입니다. 이어서 진행하세요." />
<Row badge="협상 완료" tone="done" text="가격 제출을 마쳤습니다. 최종 결과는 견적 마감 후 아래 '결과'로 표시됩니다." />
<Row badge="협상 미참여" tone="none" text="기한 내 참여하지 않아 종료된 건입니다." />
<Row badge="협상 거절" tone="reject" text="내가 참여를 거절한 건입니다." />
</Section>
<Section title="협상 결과" desc="견적이 마감된 뒤 정해지는 낙찰 결과입니다. 마감 전에는 표시되지 않습니다.">
<Row badge="낙찰" tone="win" text="내가 낙찰되어 계약 대상이 된 건입니다." />
<Row badge="미낙찰" tone="lost" text="다른 공급사가 낙찰되어 이번 계약에서는 제외된 건입니다." />
<Row badge="결렬" tone="open" text="낙찰자 없이 마감된 건입니다. 조건이 바뀌었다면 재협상을 요청할 수 있습니다." />
</Section>
<Section title="재협상 요청" desc="결렬(낙찰자 미정 마감) 건에 한해 가능합니다.">
<p className="text-[13px] leading-relaxed text-neutral-70">
결렬 건의 <b className="font-bold text-neutral-90">재협상 요청</b> 버튼으로 사유·희망가를 담아 요청하면,
구매 담당자 검토 후 <b className="font-bold text-neutral-90">승인 시 다음 차수 협상</b>이 새로 열립니다.
요청 상태(심사 중·승인·반려)는 목록에서 확인할 수 있습니다.
</p>
</Section>
</div>
<button
type="button"
onClick={onClose}
className="mt-7 h-11 w-full rounded-xl bg-brand-600 text-sm font-bold text-white transition-colors hover:bg-brand-700"
>
확인했어요
</button>
</div>
</Modal>
)
}
function Section({ title, desc, children }: { title: string; desc: string; children: React.ReactNode }) {
return (
<section>
<h3 className="text-sm font-extrabold text-neutral-90">{title}</h3>
<p className="mb-3 mt-0.5 text-xs text-neutral-60">{desc}</p>
<div className="flex flex-col gap-2.5">{children}</div>
</section>
)
}
const TONE: Record<string, string> = {
wait: 'bg-brand-light text-brand-700',
prog: 'bg-[#FFF3E5] text-[#F5A623]',
done: 'bg-[#EAFDF3] text-success',
none: 'bg-neutral-20 text-neutral-60',
reject: 'bg-[#FFEBEB] text-[#FF4D4F]',
win: 'bg-[#EAFDF3] text-success',
lost: 'bg-neutral-20 text-neutral-60',
open: 'bg-[#FFF3E5] text-[#F5A623]',
}
function Row({ badge, tone, text }: { badge: string; tone: string; text: string }) {
return (
<div className="flex items-start gap-2.5">
<span className={cn('mt-0.5 inline-flex shrink-0 items-center rounded-full px-2.5 py-1 text-xs font-bold', TONE[tone])}>
{badge}
</span>
<p className="text-[13px] leading-relaxed text-neutral-70">{text}</p>
</div>
)
}
@@ -0,0 +1,85 @@
import type { ReactNode } from 'react'
import { cn } from '@/lib'
import { useSessionCounts, type KpiCount } from '@/features/list/hooks/useSessionCounts'
// 목업(claude artifact) 그대로: 진행(내가 할 일=상태축) / 결과(마감 후=결과축) 두 묶음.
// 모든 카드 동일 크기·높이 — 강조는 색·CTA 로만. 낙찰=초록, 결렬=amber(재협상 가능), 미낙찰=회색.
interface KpiCardsProps {
selectedStatus: string | null
selectedResult: number | null
onSelectStatus: (status: string) => void
onSelectResult: (code: number) => void
}
// key → 배지 점 색 / 숫자 색 / 카드 배경·테두리 / CTA.
const STYLE: Record<string, { dot?: string; num: string; card?: string; cta?: string; ctaText?: string }> = {
created: { num: 'text-brand-600' },
progress: { num: 'text-neutral-90' },
won: { dot: 'bg-success', num: 'text-success', card: 'border-success/40 bg-gradient-to-b from-emerald-50 to-white', cta: 'text-success', ctaText: '★ 계약 대상' },
open: { dot: 'bg-warning', num: 'text-warning', card: 'border-warning/40', cta: 'text-warning', ctaText: '▲ 재협상 요청 가능' },
lost: { dot: 'bg-neutral-50', num: 'text-neutral-70' },
}
export function KpiCards({ selectedStatus, selectedResult, onSelectStatus, onSelectResult }: KpiCardsProps) {
const { progress, result } = useSessionCounts()
const isActive = (c: KpiCount) =>
c.kind === 'status' ? selectedStatus === c.statusLabel : selectedResult === c.resultCode
const onClick = (c: KpiCount) =>
c.kind === 'status' ? onSelectStatus(c.statusLabel!) : onSelectResult(c.resultCode!)
return (
<div className="grid gap-4 lg:grid-cols-[2fr_3fr]">
<Cluster label="진행 · 내가 할 일" dot="bg-brand-600" cols="grid-cols-2">
{progress.map((c) => (
<Card key={c.key} data={c} active={isActive(c)} onClick={() => onClick(c)} />
))}
</Cluster>
<Cluster label="결과 · 마감 후" dot="bg-success" cols="grid-cols-3">
{result.map((c) => (
<Card key={c.key} data={c} active={isActive(c)} onClick={() => onClick(c)} />
))}
</Cluster>
</div>
)
}
function Cluster({ label, dot, cols, children }: { label: string; dot: string; cols: string; children: ReactNode }) {
return (
<div>
<div className="mb-2 flex items-center gap-1.5 px-0.5 text-[11px] font-extrabold uppercase tracking-wider text-neutral-60">
<span className={cn('size-1.5 rounded-full', dot)} />
{label}
</div>
<div className={cn('grid gap-2.5', cols)}>{children}</div>
</div>
)
}
function Card({ data, active, onClick }: { data: KpiCount; active: boolean; onClick: () => void }) {
const s = STYLE[data.key] ?? STYLE.created
const ctaText = s.ctaText ?? ' ' // 빈 카드도 CTA 줄 높이를 확보(nbsp) → 5개 카드 높이 완전 동일
return (
<button
type="button"
onClick={onClick}
className={cn(
'flex h-full flex-col rounded-2xl border bg-white p-4 text-left shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md active:scale-[0.99]',
s.card ?? 'border-border',
// 오프셋 링이라 카드 배경색(낙찰 초록·결렬 amber)과 무관하게 선택이 또렷하게 보인다.
active && 'ring-2 ring-brand-600 ring-offset-2 ring-offset-surface',
)}
>
<p className="mb-2 flex items-center gap-1.5 whitespace-nowrap text-xs font-bold text-neutral-70">
{s.dot && <span className={cn('size-1.5 rounded-full', s.dot)} />}
{data.label}
</p>
<p className={cn('text-2xl font-extrabold tabular-nums', s.num)}>
{data.isLoading ? '–' : data.count.toLocaleString()}
<span className="ml-0.5 text-xs font-bold text-neutral-60">건</span>
</p>
{/* CTA 는 좁은 카드(모바일 3열)에서 nowrap 이면 넘치므로 단어 단위로만 줄바꿈 */}
<p className={cn('mt-1.5 break-keep text-[11px] font-extrabold', s.cta)}>{ctaText}</p>
</button>
)
}
@@ -1,6 +1,6 @@
import { cn, interactive } from '@/lib'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { cn } from '@/lib'
import { buildPageItems } from '@/features/list/lib/pagination'
import { ArrowIcon, DotsIcon } from '@/features/list/components/paginationIcons'
interface PaginationProps {
totalPages: number
@@ -9,82 +9,41 @@ interface PaginationProps {
}
export function Pagination({ totalPages, currentPage, onPageChange }: PaginationProps) {
if (totalPages === 0) {
return <div className="w-full my-[35px] h-[50px]" />
}
if (totalPages <= 1) return null
const items = buildPageItems(currentPage, totalPages)
return (
<div className="flex w-full my-[35px]">
<div className="flex w-full h-[50px] items-center justify-center gap-3">
<NavButton
dir="prev"
enabled={currentPage > 1}
onClick={() => onPageChange(currentPage - 1)}
/>
<div className="flex items-center justify-center h-full rounded-[999px] border border-neutral-30 bg-neutral-00">
<div className="flex items-center justify-center gap-1 h-[38px]">
{items.map((item, idx) =>
item === 'dots' ? (
<DotsIcon key={`dots-${idx}`} />
) : (
<PageNumber
key={item}
page={item}
active={item === currentPage}
onClick={() => onPageChange(item)}
/>
),
<div className="flex items-center justify-center gap-1.5 py-1">
<NavButton dir="prev" enabled={currentPage > 1} onClick={() => onPageChange(currentPage - 1)} />
{items.map((item, idx) =>
item === 'dots' ? (
<span key={`dots-${idx}`} className="px-1 text-sm text-neutral-50 select-none">
…
</span>
) : (
<button
key={item}
type="button"
onClick={item === currentPage ? undefined : () => onPageChange(item)}
className={cn(
'flex size-9 items-center justify-center rounded-lg text-sm font-semibold tabular-nums transition-all',
item === currentPage
? 'bg-brand-600 text-white shadow-sm cursor-default'
: 'text-neutral-70 hover:bg-neutral-10 active:scale-[0.96]',
)}
</div>
</div>
<NavButton
dir="next"
enabled={currentPage < totalPages}
onClick={() => onPageChange(currentPage + 1)}
/>
</div>
>
{item}
</button>
),
)}
<NavButton dir="next" enabled={currentPage < totalPages} onClick={() => onPageChange(currentPage + 1)} />
</div>
)
}
function PageNumber({
page,
active,
onClick,
}: {
page: number
active: boolean
onClick: () => void
}) {
return (
<button
type="button"
onClick={active ? undefined : onClick}
className={cn(
'flex w-[50px] h-[50px] items-center justify-center shrink-0 text-[18px] tracking-[-0.36px] select-none',
active
? 'rounded-full bg-primary text-primary-foreground cursor-default'
: cn('text-neutral-80', interactive),
)}
>
{page}
</button>
)
}
function NavButton({
dir,
enabled,
onClick,
}: {
dir: 'prev' | 'next'
enabled: boolean
onClick: () => void
}) {
function NavButton({ dir, enabled, onClick }: { dir: 'prev' | 'next'; enabled: boolean; onClick: () => void }) {
const Icon = dir === 'prev' ? ChevronLeft : ChevronRight
return (
<button
type="button"
@@ -92,11 +51,11 @@ function NavButton({
disabled={!enabled}
onClick={enabled ? onClick : undefined}
className={cn(
'flex items-center justify-center w-[50px] h-[50px] rounded-full border border-neutral-30 bg-neutral-00 select-none',
enabled ? cn('text-neutral-60', interactive) : 'text-neutral-40 cursor-default',
'flex size-9 items-center justify-center rounded-lg border border-border transition-all',
enabled ? 'text-neutral-70 hover:bg-neutral-10 active:scale-[0.96]' : 'text-neutral-40 cursor-default',
)}
>
<ArrowIcon dir={dir} />
<Icon className="size-4" />
</button>
)
}
@@ -1,6 +1,7 @@
import { useState } from 'react'
import { X } from 'lucide-react'
import { Modal } from '@/components'
import { cn, interactive } from '@/lib'
import { cn } from '@/lib'
const REASONS = ['단종', '품절', '기타'] as const
@@ -36,88 +37,87 @@ export function RejectPopup({ onClose, onSubmit }: RejectPopupProps) {
return
}
if (isSubmitDisabled || !selectedReason) return
const reason = isEtcOpen ? customReason.trim() : selectedReason
onSubmit(reason)
onSubmit(isEtcOpen ? customReason.trim() : selectedReason)
onClose()
}
return (
<Modal onClose={onClose}>
<div className="flex h-[500px] w-[700px] flex-col items-center justify-between rounded-[10px] bg-background py-20 shadow-lg transition-all duration-300 ease-out">
<div className="w-full max-w-md overflow-hidden rounded-2xl border border-border bg-white shadow-xl animate-scale-in">
{/* 헤더 */}
<p className="text-center text-[26px] font-bold leading-9 tracking-[-0.52px] text-foreground">
거부 사유를 입력해주세요
</p>
{/* 사유 선택 */}
<div className={cn('flex gap-5 transition-all duration-300 ease-out', isEtcOpen ? 'mt-0' : 'mt-12')}>
{REASONS.map((reason) => (
<button
key={reason}
type="button"
onClick={() => handleReasonClick(reason)}
className={cn(
'flex h-[50px] w-[120px] items-center justify-center rounded-full px-8 title-2 text-foreground',
'bg-neutral-20 border',
interactive,
selectedReason === reason ? 'border-foreground' : 'border-transparent',
)}
>
{reason}
</button>
))}
<div className="flex 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="flex flex-col items-center">
<div
className={cn(
'flex w-[400px] overflow-hidden transition-all duration-300 ease-out',
isEtcOpen ? 'visible h-[120px] opacity-100' : 'invisible h-0 opacity-0',
)}
>
<textarea
placeholder="사유를 입력하여 주십시오"
value={customReason}
onChange={(e) => {
setCustomReason(e.target.value)
setShowError(false)
}}
className={cn(
'h-full w-full resize-none rounded-lg bg-background p-2.5 body-3 text-foreground',
'placeholder:text-muted-foreground focus:outline-none',
'transition-colors duration-200',
showError ? 'border-2 border-destructive' : 'border border-foreground',
)}
/>
{/* 본문 */}
<div className="space-y-4 p-5">
<div className="grid grid-cols-3 gap-2">
{REASONS.map((reason) => (
<button
key={reason}
type="button"
onClick={() => handleReasonClick(reason)}
className={cn(
'h-11 rounded-xl border text-sm font-bold transition-all active:scale-[0.98]',
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>
{/* 에러 메시지 (항상 공간 확보) */}
<div
className={cn(
'w-[400px] overflow-hidden transition-all duration-300 ease-out',
showError && isEtcOpen ? 'mt-2 h-[24px] opacity-100' : 'h-0 opacity-0',
)}
>
<p className="text-left body-5 text-destructive">기타 사유를 입력해주세요</p>
</div>
</div>
{/* 전송 */}
<button
type="button"
onClick={handleSubmit}
disabled={isSubmitDisabled}
className={cn(
'flex h-[50px] w-full max-w-[130px] items-center justify-center rounded-full px-8 title-2',
'bg-foreground text-background',
interactive,
isSubmitDisabled && 'cursor-not-allowed opacity-40',
{isEtcOpen && (
<div className="animate-fade-in">
<textarea
placeholder="사유를 입력하여 주십시오"
value={customReason}
onChange={(e) => {
setCustomReason(e.target.value)
setShowError(false)
}}
rows={3}
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>
)}
>
전송
</button>
</div>
{/* 푸터 */}
<div className="flex gap-2 border-t border-border p-4">
<button
type="button"
onClick={onClose}
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]"
>
취소
</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>
)
@@ -0,0 +1,54 @@
import { X } from 'lucide-react'
import { Modal } from '@/components'
import { RENEGO_STATUS_LABEL } from '@/apis/negotiation/negotiation.type'
import type { ListItem } from '../types'
export interface RenegotiationMemoPopupProps {
target: ListItem
onClose: () => void
}
// 재협상 심사 결과의 담당자 메모 열람 팝업. 목록에는 상태 배지만 두고 메모 전문은 여기서 보여준다.
export function RenegotiationMemoPopup({ target, onClose }: RenegotiationMemoPopupProps) {
return (
<Modal onClose={onClose}>
<div className="w-full max-w-md overflow-hidden rounded-2xl border border-border bg-white shadow-xl animate-scale-in">
<div className="flex items-center justify-between border-b border-border p-5">
<div>
<h3 className="text-base font-bold text-neutral-90">
{RENEGO_STATUS_LABEL[target.renegotiationStatus] ?? '재협상 심사 결과'}
</h3>
<p className="mt-0.5 text-xs text-neutral-60">
{target.qt_number} · {target.item_name}
</p>
</div>
<button
type="button"
onClick={onClose}
aria-label="닫기"
className="flex size-8 items-center justify-center rounded-full text-neutral-60 hover:bg-neutral-10"
>
<X className="size-4" />
</button>
</div>
<div className="p-5">
<p className="text-sm font-semibold text-neutral-80">담당자 메모</p>
<p className="mt-1.5 max-h-64 overflow-y-auto whitespace-pre-wrap break-keep rounded-xl bg-neutral-10 p-3 text-sm leading-relaxed text-neutral-80">
{target.renegotiationMemo}
</p>
</div>
<div className="border-t border-border p-5">
<button
type="button"
onClick={onClose}
className="w-full rounded-xl bg-brand-600 py-3 text-sm font-bold text-white shadow-sm transition-all hover:bg-brand-700 active:scale-[0.98]"
>
확인
</button>
</div>
</div>
</Modal>
)
}
@@ -0,0 +1,122 @@
import { useState } from 'react'
import { X } from 'lucide-react'
import { Modal } from '@/components'
import type { ListItem } from '../types'
export interface RenegotiationPopupProps {
target: ListItem
onClose: () => void
onSubmit: (reason: string, desiredPrice: number | null) => void
}
// 재협상 요청 팝업. 결렬(낙찰자 미정) 건에만 열리며, 담당자 승인 시 다음 차수가 생성된다.
// 사유는 자주 쓰는 것을 프리셋으로 두고, 직접 입력도 허용한다.
const PRESETS = ['가격 조건 재검토', '재고·납기 확보', '단가 정정', '수량 조건 변경'] as const
export function RenegotiationPopup({ target, onClose, onSubmit }: RenegotiationPopupProps) {
const [preset, setPreset] = useState<string>(PRESETS[0])
const [custom, setCustom] = useState('')
const [price, setPrice] = useState('')
const isDirect = preset === '직접 입력'
const reason = isDirect ? custom.trim() : preset
const canSubmit = reason.length > 0
const handleSubmit = () => {
if (!canSubmit) return
const parsed = Number(price.replace(/[^0-9]/g, ''))
onSubmit(reason, parsed > 0 ? parsed : null)
onClose()
}
return (
<Modal onClose={onClose}>
<div className="w-full max-w-md overflow-hidden rounded-2xl border border-border bg-white shadow-xl animate-scale-in">
<div className="flex items-center justify-between border-b border-border p-5">
<div>
<h3 className="text-base font-bold text-neutral-90">재협상 요청</h3>
<p className="mt-0.5 text-xs text-neutral-60">
{target.qt_number} · {target.item_name}
</p>
</div>
<button
type="button"
onClick={onClose}
aria-label="닫기"
className="flex size-8 items-center justify-center rounded-full text-neutral-60 hover:bg-neutral-10"
>
<X className="size-4" />
</button>
</div>
<div className="space-y-4 p-5">
<p className="rounded-xl bg-neutral-10 p-3 text-xs leading-relaxed text-neutral-70">
이 건은 낙찰자 없이 마감되었습니다. 요청하면 구매 담당자가 검토 후 승인 시
<b> 다시 협상할 기회</b>가 열립니다. 승인·반려 결과는 목록에서 확인할 수 있습니다.
</p>
<div className="space-y-1.5">
<label className="block text-sm font-semibold text-neutral-80">요청 사유</label>
<div className="flex flex-wrap gap-1.5">
{[...PRESETS, '직접 입력'].map((p) => (
<button
key={p}
type="button"
onClick={() => setPreset(p)}
className={`rounded-lg border px-3 py-1.5 text-xs font-bold transition-all active:scale-[0.98] ${
preset === p
? 'border-brand-600 bg-brand-50 text-brand-700'
: 'border-border text-neutral-70 hover:bg-neutral-10'
}`}
>
{p}
</button>
))}
</div>
{isDirect && (
<input
value={custom}
onChange={(e) => setCustom(e.target.value)}
maxLength={255}
placeholder="요청 사유를 입력해 주세요"
className="mt-1.5 h-11 w-full rounded-xl border border-border bg-white px-3 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600"
/>
)}
</div>
<div className="space-y-1.5">
<label className="block text-sm font-semibold text-neutral-80">
희망 공급가 <span className="font-medium text-neutral-60">(선택)</span>
</label>
<input
inputMode="numeric"
value={price}
onChange={(e) => setPrice(e.target.value)}
placeholder="예: 14,500,000"
className="h-11 w-full rounded-xl border border-border bg-white px-3 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600"
/>
<p className="text-xs text-neutral-60">담당자 검토 참고용입니다. 실제 가격은 재협상에서 다시 조율합니다.</p>
</div>
</div>
<div className="flex gap-2 border-t border-border p-5">
<button
type="button"
onClick={onClose}
className="flex-1 rounded-xl border border-border py-3 text-sm font-bold text-neutral-70 transition-all hover:bg-neutral-10 active:scale-[0.98]"
>
취소
</button>
<button
type="button"
onClick={handleSubmit}
disabled={!canSubmit}
className="flex-[2] rounded-xl bg-brand-600 py-3 text-sm font-bold text-white shadow-sm transition-all hover:bg-brand-700 active:scale-[0.98] disabled:opacity-50"
>
요청 보내기
</button>
</div>
</div>
</Modal>
)
}
@@ -0,0 +1,37 @@
import { cn } from '@/lib'
// 마감 기준 정렬. value(null=기본 그룹정렬)는 store.selectedDeadline 로 그대로 전달되고,
// adapter.deadlineToOrder 가 '남은 시간 적은 순'=asc(임박), 그 외=desc(여유) 로 매핑한다.
const SORT_OPTIONS: { label: string; value: string | null }[] = [
{ label: '기본순', value: null },
{ label: '마감임박순', value: '남은 시간 적은 순' },
{ label: '여유순', value: '남은 시간 긴 순' },
]
interface SortControlProps {
selected: string | null
onSelect: (value: string | null) => void
}
export function SortControl({ selected, onSelect }: SortControlProps) {
return (
<div className="flex items-center gap-0.5 rounded-xl border border-border bg-neutral-10 p-0.5">
{SORT_OPTIONS.map((o) => {
const active = selected === o.value
return (
<button
key={o.label}
type="button"
onClick={() => onSelect(o.value)}
className={cn(
'whitespace-nowrap rounded-[10px] px-2.5 py-[6px] text-xs font-bold transition-all active:scale-[0.98]',
active ? 'bg-white text-brand-700 shadow-sm' : 'text-neutral-60 hover:text-neutral-80',
)}
>
{o.label}
</button>
)
})}
</div>
)
}
@@ -0,0 +1,40 @@
import { cn } from '@/lib'
import { STATUS_META } from '@/features/list/lib/status'
// 전체 + 상태별 탭. 값은 원본 상태 라벨(협상생성 등), null = 전체.
const TABS: { label: string; value: string | null }[] = [
{ label: '전체', value: null },
{ label: STATUS_META.협상생성.display, value: '협상생성' },
{ label: STATUS_META.협상중.display, value: '협상중' },
{ label: STATUS_META.협상완료.display, value: '협상완료' },
{ label: STATUS_META.협상거부.display, value: '협상거부' },
{ label: STATUS_META.미참여.display, value: '미참여' },
]
interface StatusTabsProps {
selected: string | null
onSelect: (status: string | null) => void
}
export function StatusTabs({ selected, onSelect }: StatusTabsProps) {
return (
<div className="flex flex-wrap items-center gap-1">
{TABS.map((t) => {
const active = selected === t.value
return (
<button
key={t.label}
type="button"
onClick={() => onSelect(t.value)}
className={cn(
'whitespace-nowrap rounded-[10px] px-3 py-[7px] text-[13px] font-bold transition-all active:scale-[0.98]',
active ? 'bg-brand-light text-brand-700' : 'text-neutral-60 hover:text-neutral-80',
)}
>
{t.label}
</button>
)
})}
</div>
)
}
@@ -1,79 +0,0 @@
import { type ReactNode } from 'react'
import { Loader2 } from 'lucide-react'
import { cn } from '@/lib'
import type { ListItem } from '@/features/list/types'
import { COLUMNS } from '@/features/list/components/tableColumns'
interface TableSectionProps {
items: ListItem[]
selectedId?: string
isLoading?: boolean
onItemClick?: (item: ListItem) => void
}
export function TableSection({ items, selectedId, isLoading, onItemClick }: TableSectionProps) {
return (
<div className="flex flex-1 flex-col w-full min-h-0">
<div className="h-full overflow-auto rounded-[8px] bg-background">
<table className="w-full min-w-[1431px] border-separate border-spacing-0">
<thead className="sticky top-0 z-10">
<tr className="h-[53px] bg-table-header text-foreground text-lg font-semibold">
{COLUMNS.map((col) => (
<th key={col.key} className={cn(col.width, 'px-4 whitespace-nowrap', col.align)}>
{col.label}
</th>
))}
</tr>
</thead>
<tbody>
{isLoading ? (
<StateRow>
<Loader2 className="size-10 animate-spin text-muted-foreground" />
</StateRow>
) : items.length === 0 ? (
<StateRow>
<span className="text-lg text-muted-foreground">조회된 협상 내역이 없습니다.</span>
</StateRow>
) : (
items.map((item) => (
<tr
key={item.session_id}
onClick={() => onItemClick?.(item)}
className={cn(
'h-[53px] cursor-pointer text-lg text-foreground transition-colors',
item.session_id === selectedId ? 'bg-table-selected' : 'hover:bg-table-hover',
)}
>
{COLUMNS.map((col) => (
<td
key={col.key}
className={cn(
col.width,
'px-4 border-b border-border whitespace-nowrap',
col.align,
)}
>
{col.render ? col.render(item) : item[col.key] || '-'}
</td>
))}
</tr>
))
)}
</tbody>
</table>
</div>
</div>
)
}
// 로딩/빈 상태 행
function StateRow({ children }: { children: ReactNode }) {
return (
<tr>
<td colSpan={COLUMNS.length} className="h-[240px]">
<div className="flex items-center justify-center">{children}</div>
</td>
</tr>
)
}
@@ -0,0 +1,159 @@
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'
interface WorkspaceCardsProps {
items: ListItem[]
isLoading?: boolean
busyId?: string | null
onEnter: (item: ListItem) => void
onReject: (item: ListItem) => void
onExtraInfo: (item: ListItem) => void
onRenegotiate: (item: ListItem) => void
onMemo: (item: ListItem) => void
}
// 모바일(lg 미만) 협상 목록: 테이블 대신 카드 스택.
export function WorkspaceCards({ items, isLoading, busyId, onEnter, onReject, onExtraInfo, onRenegotiate, onMemo }: WorkspaceCardsProps) {
if (isLoading) {
return (
<div className="flex items-center justify-center py-16">
<Loader2 className="size-7 animate-spin text-neutral-50" />
</div>
)
}
if (items.length === 0) {
return <div className="py-16 text-center text-sm text-neutral-60">조회된 협상 내역이 없습니다.</div>
}
return (
<div className="divide-y divide-border">
{items.map((item) => (
<Card key={item.session_id} item={item} busy={busyId === item.session_id} onEnter={onEnter} onReject={onReject} onExtraInfo={onExtraInfo} onRenegotiate={onRenegotiate} onMemo={onMemo} />
))}
</div>
)
}
function Card({
item,
busy,
onEnter,
onReject,
onExtraInfo,
onRenegotiate,
onMemo,
}: {
item: ListItem
busy: boolean
onEnter: (item: ListItem) => void
onReject: (item: ListItem) => void
onExtraInfo: (item: ListItem) => void
onRenegotiate: (item: ListItem) => void
onMemo: (item: ListItem) => void
}) {
const meta = statusMeta(item.session_status)
const canEnter = !['미참여', '협상거부'].includes(item.session_status)
const canReject = ['협상생성', '협상중'].includes(item.session_status)
const isDone = item.session_status === '협상완료'
const enterLabel = isDone ? '결과 보기' : '협상 입장'
// 재협상: 요청 가능하면 버튼, 이미 요청했으면 진행 상태를 보여준다.
const renegoLabel = RENEGO_STATUS_LABEL[item.renegotiationStatus] ?? ''
return (
<div className="p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-1.5">
<span className="truncate font-mono text-[12px] font-semibold text-neutral-70">{item.qt_number || '-'}</span>
</div>
<p className="mt-1.5 truncate text-sm font-bold text-neutral-90">{item.item_name || '-'}</p>
<p className="mt-0.5 truncate text-xs text-neutral-60">
<span className="font-mono">{item.item_code || '-'}</span>
{item.model_name && <span> · {item.model_name}</span>}
</p>
</div>
<div className="flex shrink-0 items-center gap-1.5">
{RESULT_META[item.result] && (
<span className={cn('inline-flex items-center whitespace-nowrap rounded-full px-2 py-1 text-xs font-bold', RESULT_META[item.result].badge)}>
{RESULT_META[item.result].label}
</span>
)}
<span className={cn('inline-flex items-center gap-1 whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-bold', meta.badge)}>
<span className={cn('size-1.5 rounded-full', meta.dot)} />
{meta.display}
</span>
</div>
</div>
<div className="mt-2.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-neutral-60">
{item.maker_name && <span>제조사 {item.maker_name}</span>}
<span>마감 {formatKstDateTime(item.qt_end_time)}</span>
</div>
{renegoLabel &&
(item.renegotiationMemo ? (
<button
type="button"
onClick={() => onMemo(item)}
className="mt-2.5 flex w-full items-center justify-between rounded-xl bg-neutral-10 px-3 py-2 transition-all hover:bg-neutral-20 active:scale-[0.99]"
>
<span className="whitespace-nowrap text-xs font-bold text-neutral-80">{renegoLabel}</span>
<span className="flex items-center gap-1 whitespace-nowrap text-[11px] text-neutral-60">
담당자 메모
<MessageSquareText className="size-3.5 text-neutral-50" />
</span>
</button>
) : (
<div className="mt-2.5 rounded-xl bg-neutral-10 px-3 py-2">
<p className="text-xs font-bold text-neutral-80">{renegoLabel}</p>
</div>
))}
{(canEnter || canReject || isDone || item.renegotiable) && (
<div className="mt-3 flex gap-2">
{item.renegotiable && (
<button
type="button"
onClick={() => onRenegotiate(item)}
className="flex-1 rounded-lg border border-brand-600/40 py-2 text-xs font-bold text-brand-700 transition-all hover:bg-brand-50 active:scale-[0.98]"
>
재협상 요청
</button>
)}
{isDone && (
<button
type="button"
onClick={() => onExtraInfo(item)}
className="flex-1 rounded-lg border border-brand-600/40 py-2 text-xs font-bold text-brand-700 transition-all hover:bg-brand-50 active:scale-[0.98]"
>
부가정보 보기
</button>
)}
{canReject && (
<button
type="button"
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 && (
<button
type="button"
onClick={() => onEnter(item)}
disabled={busy}
className="flex flex-[2] items-center justify-center gap-1 rounded-lg bg-brand-600 py-2 text-xs font-bold text-white shadow-sm transition-all hover:bg-brand-700 active:scale-[0.98] disabled:opacity-50"
>
{busy && <Loader2 className="size-3 animate-spin" />}
{enterLabel}
</button>
)}
</div>
)}
</div>
)
}
@@ -0,0 +1,181 @@
import { type ReactNode } from 'react'
import { Loader2, MessageSquareText } from 'lucide-react'
import { cn, formatKstDateTime } from '@/lib'
import { RENEGO_STATUS_LABEL } from '@/apis/negotiation/negotiation.type'
import type { ListItem } from '@/features/list/types'
import { statusMeta, RESULT_META } from '@/features/list/lib/status'
interface WorkspaceTableProps {
items: ListItem[]
isLoading?: boolean
busyId?: string | null
onEnter: (item: ListItem) => void
onReject: (item: ListItem) => void
onExtraInfo: (item: ListItem) => void
onRenegotiate: (item: ListItem) => void
onMemo: (item: ListItem) => void
}
// th 기본 정렬은 center — 정렬은 베이스에 넣지 않고 컬럼마다 명시한다(cn 이 tailwind-merge 가 아니라 충돌 시 승자가 불명확).
const HEAD = 'px-5 py-3.5 text-[11px] font-bold uppercase tracking-wider text-neutral-60 whitespace-nowrap'
const CELL = 'px-5 py-4 align-middle text-sm text-neutral-80'
export function WorkspaceTable({ items, isLoading, busyId, onEnter, onReject, onExtraInfo, onRenegotiate, onMemo }: WorkspaceTableProps) {
return (
<div className="w-full overflow-x-auto">
<table className="w-full min-w-[900px] border-collapse">
<thead>
<tr className="border-b border-border bg-table-header">
<th className={cn(HEAD, 'text-left')}>견적번호</th>
<th className={cn(HEAD, 'text-left')}>상품</th>
<th className={cn(HEAD, 'text-left')}>제조사</th>
<th className={cn(HEAD, 'text-right')}>상태</th>
<th className={cn(HEAD, 'text-center')}>결과</th>
<th className={cn(HEAD, 'text-left')}>마감일</th>
<th className={cn(HEAD, 'text-right')}>액션</th>
</tr>
</thead>
<tbody>
{isLoading ? (
<StateRow>
<Loader2 className="size-8 animate-spin text-neutral-50" />
</StateRow>
) : items.length === 0 ? (
<StateRow>
<span className="text-sm text-neutral-60">조회된 협상 내역이 없습니다.</span>
</StateRow>
) : (
items.map((item) => (
<Row key={item.session_id} item={item} busy={busyId === item.session_id} onEnter={onEnter} onReject={onReject} onExtraInfo={onExtraInfo} onRenegotiate={onRenegotiate} onMemo={onMemo} />
))
)}
</tbody>
</table>
</div>
)
}
function Row({
item,
busy,
onEnter,
onReject,
onExtraInfo,
onRenegotiate,
onMemo,
}: {
item: ListItem
busy: boolean
onEnter: (item: ListItem) => void
onReject: (item: ListItem) => void
onExtraInfo: (item: ListItem) => void
onRenegotiate: (item: ListItem) => void
onMemo: (item: ListItem) => void
}) {
const meta = statusMeta(item.session_status)
const canEnter = !['미참여', '협상거부'].includes(item.session_status)
const canReject = ['협상생성', '협상중'].includes(item.session_status)
const isDone = item.session_status === '협상완료'
const enterLabel = isDone ? '결과 보기' : '협상 입장'
return (
<tr className="border-b border-border/60 transition-colors last:border-0 hover:bg-table-hover/70">
<td className={cn(CELL, 'font-mono text-[13px] font-semibold text-neutral-90 whitespace-nowrap')}>
{item.qt_number || '-'}
</td>
<td className={CELL}>
<p className="font-semibold text-neutral-90">{item.item_name || '-'}</p>
<p className="mt-0.5 text-xs text-neutral-60">
<span className="font-mono">{item.item_code || '-'}</span>
{item.model_name && <span> · {item.model_name}</span>}
</p>
</td>
<td className={cn(CELL, 'whitespace-nowrap text-neutral-70')}>{item.maker_name || '-'}</td>
<td className={cn(CELL, 'text-right')}>
<span className={cn('inline-flex items-center gap-1 whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-bold', meta.badge)}>
<span className={cn('size-1.5 rounded-full', meta.dot)} />
{meta.display}
</span>
</td>
<td className={cn(CELL, 'text-center')}>
{RESULT_META[item.result] ? (
<span className={cn('inline-flex items-center whitespace-nowrap rounded-full px-2 py-1 text-xs font-bold', RESULT_META[item.result].badge)}>
{RESULT_META[item.result].label}
</span>
) : (
<span className="text-xs text-neutral-40">–</span>
)}
</td>
<td className={cn(CELL, 'whitespace-nowrap text-neutral-70')}>{formatKstDateTime(item.qt_end_time)}</td>
<td className={CELL}>
<div className="flex items-center justify-end gap-2">
{/* 재협상: 요청 가능하면 버튼, 요청 이력이 있으면 상태 텍스트(담당자 메모 있으면 클릭 시 팝업) */}
{item.renegotiable ? (
<button
type="button"
onClick={() => onRenegotiate(item)}
className="rounded-lg border border-brand-600/40 px-3 py-1.5 text-xs font-bold text-brand-700 transition-all hover:bg-brand-50 active:scale-[0.98]"
>
재협상 요청
</button>
) : (
RENEGO_STATUS_LABEL[item.renegotiationStatus] &&
(item.renegotiationMemo ? (
<button
type="button"
onClick={() => onMemo(item)}
className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-lg bg-neutral-10 px-2.5 py-1.5 text-xs font-bold text-neutral-70 transition-all hover:bg-neutral-20 active:scale-[0.98]"
>
{RENEGO_STATUS_LABEL[item.renegotiationStatus]}
<MessageSquareText className="size-3.5 text-neutral-50" />
</button>
) : (
<span className="whitespace-nowrap rounded-lg bg-neutral-10 px-2.5 py-1.5 text-xs font-bold text-neutral-70">
{RENEGO_STATUS_LABEL[item.renegotiationStatus]}
</span>
))
)}
{isDone && (
<button
type="button"
onClick={() => onExtraInfo(item)}
className="rounded-lg border border-brand-600/40 px-3 py-1.5 text-xs font-bold text-brand-700 transition-all hover:bg-brand-50 active:scale-[0.98]"
>
부가정보 보기
</button>
)}
{canReject && (
<button
type="button"
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 ? (
<button
type="button"
onClick={() => onEnter(item)}
disabled={busy}
className="inline-flex items-center gap-1 rounded-lg bg-brand-600 px-3.5 py-1.5 text-xs font-bold text-white shadow-sm transition-all hover:bg-brand-700 active:scale-[0.98] disabled:opacity-50"
>
{busy && <Loader2 className="size-3 animate-spin" />}
{enterLabel}
</button>
) : null}
</div>
</td>
</tr>
)
}
function StateRow({ children }: { children: ReactNode }) {
return (
<tr>
<td colSpan={7} className="py-20">
<div className="flex items-center justify-center">{children}</div>
</td>
</tr>
)
}
@@ -1,32 +0,0 @@
// 페이지네이션 인라인 SVG (색 = currentColor)
const ARROW_PATH = {
prev: 'M26.9995 30.6532L21.3457 24.9995L26.9995 19.3457L28.0532 20.3995L23.4532 24.9995L28.0532 29.5995L26.9995 30.6532Z',
next: 'M23.0005 30.6532L28.6543 24.9995L23.0005 19.3457L21.9468 20.3995L26.5468 24.9995L21.9468 29.5995L23.0005 30.6532Z',
} as const
export function ArrowIcon({ dir }: { dir: 'prev' | 'next' }) {
return (
<svg width="50" height="50" viewBox="0 0 50 50" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d={ARROW_PATH[dir]} fill="currentColor" />
</svg>
)
}
export function DotsIcon() {
return (
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="select-none text-neutral-60"
>
<path
d="M6.23047 13.5C5.81797 13.5 5.46489 13.3531 5.17122 13.0592C4.87739 12.7656 4.73047 12.4125 4.73047 12C4.73047 11.5875 4.87739 11.2344 5.17122 10.9408C5.46489 10.6469 5.81797 10.5 6.23047 10.5C6.64297 10.5 6.99614 10.6469 7.28997 10.9408C7.58364 11.2344 7.73047 11.5875 7.73047 12C7.73047 12.4125 7.58364 12.7656 7.28997 13.0592C6.99614 13.3531 6.64297 13.5 6.23047 13.5ZM11.9997 13.5C11.5872 13.5 11.2341 13.3531 10.9405 13.0592C10.6466 12.7656 10.4997 12.4125 10.4997 12C10.4997 11.5875 10.6466 11.2344 10.9405 10.9408C11.2341 10.6469 11.5872 10.5 11.9997 10.5C12.4122 10.5 12.7653 10.6469 13.059 10.9408C13.3528 11.2344 13.4997 11.5875 13.4997 12C13.4997 12.4125 13.3528 12.7656 13.059 13.0592C12.7653 13.3531 12.4122 13.5 11.9997 13.5ZM17.769 13.5C17.3565 13.5 17.0033 13.3531 16.7095 13.0592C16.4158 12.7656 16.269 12.4125 16.269 12C16.269 11.5875 16.4158 11.2344 16.7095 10.9408C17.0033 10.6469 17.3565 10.5 17.769 10.5C18.1815 10.5 18.5346 10.6469 18.8282 10.9408C19.1221 11.2344 19.269 11.5875 19.269 12C19.269 12.4125 19.1221 12.7656 18.8282 13.0592C18.5346 13.3531 18.1815 13.5 17.769 13.5Z"
fill="currentColor"
/>
</svg>
)
}
@@ -1,45 +0,0 @@
import { type ReactNode } from 'react'
import { formatDateTime } from '@/features/list/lib/datetime'
import type { ListItem } from '@/features/list/types'
// 컬럼 설정 (렌더링은 TableSection)
export interface Column {
key: keyof ListItem
label: string
width: string
align: 'text-left' | 'text-center'
render?: (item: ListItem) => ReactNode
}
const STATUS_COLOR: Record<string, string> = {
협상생성: 'text-info font-semibold',
협상중: 'text-foreground font-semibold',
협상완료: 'text-success font-semibold',
미참여: 'text-muted-foreground font-semibold',
협상거부: 'text-destructive font-semibold',
}
export const COLUMNS: Column[] = [
{ key: 'item_code', label: '상품코드', width: 'w-[8.39%]', align: 'text-center' },
{
key: 'session_status',
label: '상태',
width: 'w-[6.57%]',
align: 'text-center',
render: (item) => (
<span className={STATUS_COLOR[item.session_status]}>{item.session_status || '-'}</span>
),
},
{ key: 'qt_number', label: '견적번호', width: 'w-[14.29%]', align: 'text-center' },
{ key: 'qt_type', label: '구분', width: 'w-[5.52%]', align: 'text-center' },
{ key: 'item_name', label: '상품명', width: 'w-[20.96%]', align: 'text-left' },
{ key: 'model_name', label: '모델명', width: 'w-[22.89%]', align: 'text-left' },
{ key: 'maker_name', label: '제조사', width: 'w-[8.67%]', align: 'text-center' },
{
key: 'qt_end_time',
label: '마감일',
width: 'w-[13.72%]',
align: 'text-center',
render: (item) => formatDateTime(item.qt_end_time),
},
]
@@ -1,106 +0,0 @@
import { useState } from 'react'
import { useNavigate } from 'react-router'
import { getApiErrorMessage, useParticipateMutation, useRejectMutation } from '@/apis'
import { toast } from '@/lib'
import { useList } from '@/features/list/hooks/useList'
import { ActionSection } from '@/features/list/components/ActionSection'
import { RejectPopup } from '@/features/list/components/RejectPopup'
import { TableSection } from '@/features/list/components/TableSection'
import { Pagination } from '@/features/list/components/Pagination'
// 상태별 거부 불가 안내
const REJECT_BLOCKED: Record<string, string> = {
미참여: '미참여 상태인 협상은 거부할 수 없습니다.',
협상거부: '협상거부 상태인 협상은 거부할 수 없습니다.',
협상완료: '협상완료 상태인 협상은 거부할 수 없습니다.',
}
export function ContentContainer() {
const navigate = useNavigate()
const {
items,
isLoading,
totalPages,
currentPage,
setCurrentPage,
selectedId,
selectedItem,
handleItemClick,
} = useList()
const participate = useParticipateMutation()
const reject = useRejectMutation()
const [isRejectOpen, setIsRejectOpen] = useState(false)
// 선택 검증: 선택된 협상이 없으면 안내 후 false
const requireSelection = (): boolean => {
if (!selectedItem) {
toast.info('상품을 선택해주세요.')
return false
}
return true
}
const handleParticipate = () => {
if (!requireSelection()) return
if (['협상거부', '미참여'].includes(selectedItem!.session_status)) {
toast.error('협상거부 또는 미참여한 협상에는 참여할 수 없습니다.')
return
}
const sessionId = selectedItem!.session_id
participate.mutate(sessionId, {
onSuccess: () => navigate(`/chat?session_id=${sessionId}`),
onError: (error) => toast.error(getApiErrorMessage(error, '협상 참여에 실패했습니다.')),
})
}
const handleReject = () => {
if (!requireSelection()) return
const blocked = REJECT_BLOCKED[selectedItem!.session_status]
if (blocked) {
toast.error(blocked)
return
}
setIsRejectOpen(true)
}
const handleRejectSubmit = (reason: string) => {
if (!selectedItem) return
reject.mutate(
{ sessionId: selectedItem.session_id, request: { reject_reason: reason } },
{
onSuccess: () => toast.warning('참여 거절이 완료되었습니다.'),
onError: (error) => toast.error(getApiErrorMessage(error, '거절 처리에 실패했습니다.')),
},
)
}
return (
// 좌우 거터(80px) 일괄 적용
<div className="flex flex-1 flex-col min-h-0 px-[80px]">
<ActionSection
isParticipating={participate.isPending}
isRejecting={reject.isPending}
onParticipate={handleParticipate}
onReject={handleReject}
/>
<TableSection
items={items}
isLoading={isLoading}
selectedId={selectedId ?? undefined}
onItemClick={handleItemClick}
/>
<Pagination
totalPages={totalPages}
currentPage={currentPage}
onPageChange={setCurrentPage}
/>
{isRejectOpen && (
<RejectPopup onClose={() => setIsRejectOpen(false)} onSubmit={handleRejectSubmit} />
)}
</div>
)
}
@@ -1,52 +0,0 @@
import { useShallow } from 'zustand/react/shallow'
import { FilterGroup } from '@/features/list/components/FilterGroup'
import { FILTER_GROUPS, type FilterKey } from '@/features/list/filterOptions'
import { useListStore } from '@/features/list/stores/useListStore'
export function FilterContainer() {
// 필터 필드만 구독 → 페이지 변경 시 리렌더 방지
const {
selectedType,
selectedStatus,
selectedDeadline,
toggleType,
toggleStatus,
toggleDeadline,
} = useListStore(
useShallow((s) => ({
selectedType: s.selectedType,
selectedStatus: s.selectedStatus,
selectedDeadline: s.selectedDeadline,
toggleType: s.toggleType,
toggleStatus: s.toggleStatus,
toggleDeadline: s.toggleDeadline,
})),
)
const selected: Record<FilterKey, string | null> = {
type: selectedType,
status: selectedStatus,
deadline: selectedDeadline,
}
const toggle: Record<FilterKey, (item: string) => void> = {
type: toggleType,
status: toggleStatus,
deadline: toggleDeadline,
}
return (
<div className="flex flex-1 pt-8 pr-2 pl-5 overflow-hidden bg-background">
<div className="flex flex-col gap-4 pr-2 w-full overflow-y-auto">
{FILTER_GROUPS.map((group) => (
<FilterGroup
key={group.key}
title={group.title}
items={group.items}
selectedItem={selected[group.key]}
onItemClick={toggle[group.key]}
/>
))}
</div>
</div>
)
}
@@ -0,0 +1,230 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router'
import { useShallow } from 'zustand/react/shallow'
import { HelpCircle, Search } from 'lucide-react'
import {
getApiErrorMessage,
useMeQuery,
useParticipateMutation,
useRejectMutation,
useRequestRenegotiationMutation,
useSaveExtraInfoMutation,
} from '@/apis'
import { cn, toast } from '@/lib'
import { useList } from '@/features/list/hooks/useList'
import { useListStore } from '@/features/list/stores/useListStore'
import { KpiCards } from '@/features/list/components/KpiCards'
import { StatusTabs } from '@/features/list/components/StatusTabs'
import { SortControl } from '@/features/list/components/SortControl'
import { WorkspaceTable } from '@/features/list/components/WorkspaceTable'
import { WorkspaceCards } from '@/features/list/components/WorkspaceCards'
import { Pagination } from '@/features/list/components/Pagination'
import { RejectPopup } from '@/features/list/components/RejectPopup'
import { ExtraInfoPopup } from '@/features/list/components/ExtraInfoPopup'
import { RenegotiationPopup } from '@/features/list/components/RenegotiationPopup'
import { RenegotiationMemoPopup } from '@/features/list/components/RenegotiationMemoPopup'
import { GuidePopup } from '@/features/list/components/GuidePopup'
import type { ListItem } from '@/features/list/types'
// 상태별 거부 불가 안내
const REJECT_BLOCKED: Record<string, string> = {
미참여: '미참여 상태인 협상은 거부할 수 없습니다.',
협상거부: '협상거부 상태인 협상은 거부할 수 없습니다.',
협상완료: '협상완료 상태인 협상은 거부할 수 없습니다.',
}
export function ListWorkspace() {
const navigate = useNavigate()
const { data: user } = useMeQuery()
// 리스트는 서버 페이징 + 서버 검색(keyword: 견적번호·상품명·상품코드 부분일치).
const { items, isLoading, totalPages, currentPage, setCurrentPage } = useList()
const participate = useParticipateMutation()
const reject = useRejectMutation()
const saveExtra = useSaveExtraInfoMutation()
const requestRenego = useRequestRenegotiationMutation()
const { selectedStatus, selectedResult, selectedDeadline, setStatus, toggleResult, setDeadline, setKeyword } =
useListStore(
useShallow((s) => ({
selectedStatus: s.selectedStatus,
selectedResult: s.selectedResult,
selectedDeadline: s.selectedDeadline,
setStatus: s.setStatus,
toggleResult: s.toggleResult,
setDeadline: s.setDeadline,
setKeyword: s.setKeyword,
})),
)
// 입력은 즉시 반영하되, 서버 요청은 300ms 디바운스(타이핑마다 호출 방지). 변경 시 store 가 페이지를 1로 되돌린다.
const [search, setSearch] = useState('')
useEffect(() => {
const id = setTimeout(() => setKeyword(search), 300)
return () => clearTimeout(id)
}, [search, setKeyword])
const [enteringId, setEnteringId] = useState<string | null>(null)
const [rejectTarget, setRejectTarget] = useState<ListItem | null>(null)
const [extraTarget, setExtraTarget] = useState<ListItem | null>(null)
const [renegoTarget, setRenegoTarget] = useState<ListItem | null>(null)
const [memoTarget, setMemoTarget] = useState<ListItem | null>(null)
const [guideOpen, setGuideOpen] = useState(false)
const handleEnter = (item: ListItem) => {
setEnteringId(item.session_id)
participate.mutate(item.session_id, {
onSuccess: () => navigate(`/chat?session_id=${item.session_id}`),
onError: (error) => {
setEnteringId(null)
toast.error(getApiErrorMessage(error, '협상 참여에 실패했습니다.'))
},
})
}
const handleReject = (item: ListItem) => {
const blocked = REJECT_BLOCKED[item.session_status]
if (blocked) {
toast.error(blocked)
return
}
setRejectTarget(item)
}
const handleRejectSubmit = (reason: string) => {
if (!rejectTarget) return
reject.mutate(
{ sessionId: rejectTarget.session_id, request: { reject_reason: reason } },
{
onSuccess: () => toast.warning('참여 거절이 완료되었습니다.'),
onError: (error) => toast.error(getApiErrorMessage(error, '거절 처리에 실패했습니다.')),
},
)
}
const handleExtraSubmit = (custom: Record<string, unknown>) => {
if (!extraTarget) return
saveExtra.mutate(
{ sessionId: extraTarget.session_id, request: { custom } },
{
onSuccess: () => toast.success('부가정보가 저장되었습니다.'),
onError: (error) => toast.error(getApiErrorMessage(error, '부가정보 저장에 실패했습니다.')),
},
)
}
const handleRenegoSubmit = (reason: string, desiredPrice: number | null) => {
if (!renegoTarget) return
requestRenego.mutate(
{ sessionId: renegoTarget.session_id, request: { reason, desired_price: desiredPrice } },
{
onSuccess: () => toast.success('재협상을 요청했습니다. 담당자 검토 후 결과가 목록에 표시됩니다.'),
onError: (error) => toast.error(getApiErrorMessage(error, '재협상 요청에 실패했습니다.')),
},
)
}
return (
<div className="space-y-5">
{/* 헤더 */}
<div className="flex flex-wrap items-baseline justify-between gap-2">
<div>
<h1 className="text-xl font-extrabold tracking-tight text-neutral-90">협상 워크스페이스</h1>
<p className="mt-0.5 text-[13px] text-neutral-60">
{user?.supplierName ? `${user.supplierName} (공급 파트너)` : '공급 파트너'} · 진행/결과를 한눈에
</p>
</div>
<div className="flex items-center gap-2.5">
<button
type="button"
onClick={() => setGuideOpen(true)}
className="inline-flex items-center gap-1.5 rounded-lg border border-border bg-white px-3 py-1.5 text-[13px] font-bold text-neutral-70 transition-colors hover:bg-neutral-10"
>
<HelpCircle className="size-4 text-neutral-50" />
이용안내
</button>
</div>
</div>
{/* KPI 콕핏 — 진행/결과 두 묶음 */}
<KpiCards
selectedStatus={selectedStatus}
selectedResult={selectedResult}
onSelectStatus={(s) => setStatus(selectedStatus === s ? null : s)}
onSelectResult={toggleResult}
/>
{/* 워크스페이스 카드 */}
<div className="overflow-hidden rounded-2xl border border-border bg-white shadow-sm">
<div className="flex flex-col gap-3 border-b border-border p-4 lg:flex-row lg:items-center lg:justify-between">
<StatusTabs selected={selectedStatus} onSelect={setStatus} />
<div className="flex w-full items-center gap-2 lg:w-auto">
<SortControl selected={selectedDeadline} onSelect={setDeadline} />
<div className="relative flex-1 lg:flex-none">
<Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-neutral-50" />
<input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="견적번호·상품 검색"
className={cn(
'h-9 w-full rounded-xl border border-border bg-white pl-8 pr-3 text-xs text-neutral-90 outline-none transition-all',
'placeholder:text-neutral-50 focus:border-brand-600 focus:ring-1 focus:ring-brand-600 lg:w-56',
)}
/>
</div>
</div>
</div>
{/* 데스크톱: 테이블 / 모바일: 카드 스택 */}
<div className="hidden lg:block">
<WorkspaceTable
items={items}
isLoading={isLoading}
busyId={participate.isPending ? enteringId : null}
onEnter={handleEnter}
onReject={handleReject}
onExtraInfo={setExtraTarget}
onRenegotiate={setRenegoTarget}
onMemo={setMemoTarget}
/>
</div>
<div className="lg:hidden">
<WorkspaceCards
items={items}
isLoading={isLoading}
busyId={participate.isPending ? enteringId : null}
onEnter={handleEnter}
onReject={handleReject}
onExtraInfo={setExtraTarget}
onRenegotiate={setRenegoTarget}
onMemo={setMemoTarget}
/>
</div>
<div className="border-t border-border px-4 py-3">
<Pagination totalPages={totalPages} currentPage={currentPage} onPageChange={setCurrentPage} />
</div>
</div>
{guideOpen && <GuidePopup onClose={() => setGuideOpen(false)} />}
{rejectTarget && (
<RejectPopup onClose={() => setRejectTarget(null)} onSubmit={handleRejectSubmit} />
)}
{extraTarget && (
<ExtraInfoPopup target={extraTarget} onClose={() => setExtraTarget(null)} onSubmit={handleExtraSubmit} />
)}
{renegoTarget && (
<RenegotiationPopup
target={renegoTarget}
onClose={() => setRenegoTarget(null)}
onSubmit={handleRenegoSubmit}
/>
)}
{memoTarget && (
<RenegotiationMemoPopup target={memoTarget} onClose={() => setMemoTarget(null)} />
)}
</div>
)
}
@@ -1,17 +0,0 @@
export type FilterKey = 'type' | 'status' | 'deadline'
export interface FilterGroupConfig {
key: FilterKey
title: string
items: readonly string[]
}
export const FILTER_GROUPS: readonly FilterGroupConfig[] = [
{ key: 'type', title: '구분', items: ['재견적', '재협상', '신규견적', '신규협상'] },
{
key: 'status',
title: '상태',
items: ['협상생성', '협상중', '협상완료', '미참여', '협상거부'],
},
{ key: 'deadline', title: '마감일', items: ['남은 시간 적은 순', '남은 시간 긴 순'] },
]
Loaded 100 of 609 files, more files were not shown because too many files have changed in this diff. Show more