Compare commits

...
Author SHA1 Message Date
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
minaChoi 3d515055fb [feat] negodata/front: 온보딩 이모지→아이콘 교체, step0 레이아웃·애니메이션 등 개편 2026-07-15 16:39:58 +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
308 changed files with 12962 additions and 2331 deletions

No files matched your search

@@ -26,7 +26,8 @@ _SESSIONS = table(
column("deleted"), column("deleted"),
schema="negotiation", schema="negotiation",
) )
_ITEMS = table("items", column("item_id"), column("name"), column("price"), column("deleted"), schema="partner") _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") _SUPPLIERS = table("suppliers", column("supplier_id"), column("name"), column("total_revenue"), column("deleted"), schema="partner")
_QUOTATIONS = table( _QUOTATIONS = table(
"quotations", "quotations",
@@ -72,6 +73,12 @@ class INegoContextCRUD(ABC):
"""품목 기준가(items.price). 없으면 0.""" """품목 기준가(items.price). 없으면 0."""
pass pass
@abstractmethod
async def get_item_lowest_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
"""상품 인터넷 최저가(items.internet_lowest_price — LPS 수집 대표값). 미수집이면 0.
카드 스크립트 {internet_lowest_price} 치환용(NGC-008 등 시장가 인용 카드)."""
pass
@abstractmethod @abstractmethod
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]: async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
"""협력사 총매출액(suppliers.total_revenue — KTC 미러). 없으면 0.0.""" """협력사 총매출액(suppliers.total_revenue — KTC 미러). 없으면 0.0."""
@@ -141,6 +148,21 @@ class NegoContextCRUD(INegoContextCRUD):
LOG.e_no_callstack(ex) LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0 return ErrorType.DB_RUN_FAILED, 0
async def get_item_lowest_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
try:
query = (
select(_ITEMS.c.internet_lowest_price)
.where(_ITEMS.c.item_id == item_id, _ITEMS.c.deleted == False) # noqa: E712
.limit(1)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_item_lowest_price failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
return err_type, 0
return ErrorType.SUCCESS, int(rows[0])
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]: async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
try: try:
query = ( query = (
@@ -247,6 +247,12 @@ class ChatEngine:
out["product_name"] = str(ctx["product_name"]) out["product_name"] = str(ctx["product_name"])
if "offer_1pct" in ctx: if "offer_1pct" in ctx:
out["offer_1pct"] = int(ctx["offer_1pct"]) out["offer_1pct"] = int(ctx["offer_1pct"])
# 인터넷 최저가: 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 산식과 동일 정의. # 전술 카운터 변수(카드 시드 멘트의 가격 변수) — tactics.compute_counter 산식과 동일 정의.
anchor = ctx.get("anchor_price") or 0 anchor = ctx.get("anchor_price") or 0
target = ctx.get("target_price") or 0 target = ctx.get("target_price") or 0
@@ -39,6 +39,7 @@ class NegotiationDbContext:
target_price: int # 목표 매입가(원) — sessions.target_price target_price: int # 목표 매입가(원) — sessions.target_price
anchor_price: int # 앵커링가 — sessions.anchoring_price(생성 시 박제). 없으면 target(무할인 폴백) anchor_price: int # 앵커링가 — sessions.anchoring_price(생성 시 박제). 없으면 target(무할인 폴백)
item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0 item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0
internet_lowest_price: int # 인터넷 최저가(items.internet_lowest_price, LPS 대표값) — 카드 {internet_lowest_price} 치환용. 미수집이면 0
partner_name: Optional[str] # 협력사명(suppliers.name) — 카드 {partner_name} 치환용. 없으면 None partner_name: Optional[str] # 협력사명(suppliers.name) — 카드 {partner_name} 치환용. 없으면 None
product_name: Optional[str] # 상품명(items.name) — 카드 {product_name} 치환용. 없으면 None product_name: Optional[str] # 상품명(items.name) — 카드 {product_name} 치환용. 없으면 None
partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE
@@ -86,6 +87,9 @@ class NegotiationContextLoader:
# 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시). # 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시).
_, item_price = await self.crud.get_item_price(s, item_id) _, item_price = await self.crud.get_item_price(s, item_id)
# 인터넷 최저가(LPS 수집 대표값) — 없으면 0(시장가 인용 카드는 값 있을 때만 치환).
_, internet_lowest_price = await self.crud.get_item_lowest_price(s, item_id)
# 카드 스크립트 치환용 이름 — 협력사명/상품명. 없으면 None(호출부 기본값 폴백). # 카드 스크립트 치환용 이름 — 협력사명/상품명. 없으면 None(호출부 기본값 폴백).
_, partner_name = await self.crud.get_supplier_name(s, supplier_id) _, partner_name = await self.crud.get_supplier_name(s, supplier_id)
_, product_name = await self.crud.get_item_name(s, item_id) _, product_name = await self.crud.get_item_name(s, item_id)
@@ -108,6 +112,7 @@ class NegotiationContextLoader:
target_price=target, target_price=target,
anchor_price=anchor, anchor_price=anchor,
item_price=item_price, item_price=item_price,
internet_lowest_price=internet_lowest_price,
partner_name=partner_name, partner_name=partner_name,
product_name=product_name, product_name=product_name,
partner_type=PartnerType.from_count(supplier_count), partner_type=PartnerType.from_count(supplier_count),
+3
View File
@@ -110,6 +110,9 @@ class ChatService:
"round": 0, "round": 0,
# 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용. # 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용.
"item_price": db_ctx.item_price if db_ctx else 0, "item_price": db_ctx.item_price if db_ctx else 0,
# 인터넷 최저가(items.internet_lowest_price, LPS 대표값) — 카드 {internet_lowest_price} 치환용.
# 미수집(0)이면 vars_for 가 키를 만들지 않아 원형 유지(허위 시장가 표기 방지).
"internet_lowest_price": db_ctx.internet_lowest_price if db_ctx else 0,
# 견적 생성 시 선택한 카드. 일반카드는 action_id 0..N-1 에 그대로 매핑한다. # 견적 생성 시 선택한 카드. 일반카드는 action_id 0..N-1 에 그대로 매핑한다.
# 1% 인하는 기본 와일드카드로 항상 열고, 재원부족 등 선택형 와일드카드는 # 1% 인하는 기본 와일드카드로 항상 열고, 재원부족 등 선택형 와일드카드는
# 선택된 와일드카드가 있을 때만 허용한다. # 선택된 와일드카드가 있을 때만 허용한다.
+4
View File
@@ -192,6 +192,9 @@ async def test_loader_with_crud_double(db_engine):
async def get_item_price(self, cdb, item_id): async def get_item_price(self, cdb, item_id):
return ErrorType.SUCCESS, 7000 return ErrorType.SUCCESS, 7000
async def get_item_lowest_price(self, cdb, item_id):
return ErrorType.SUCCESS, 6300 # 인터넷 최저가(items.internet_lowest_price)
async def get_supplier_total_revenue(self, cdb, supplier_id): async def get_supplier_total_revenue(self, cdb, supplier_id):
return ErrorType.SUCCESS, 12_000_000.0 return ErrorType.SUCCESS, 12_000_000.0
@@ -219,6 +222,7 @@ async def test_loader_with_crud_double(db_engine):
assert ctx.target_price == 50000 assert ctx.target_price == 50000
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target) assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
assert ctx.item_price == 7000 assert ctx.item_price == 7000
assert ctx.internet_lowest_price == 6300 # 인터넷 최저가 로드 확인
assert ctx.partner_name == "테스트협력사" assert ctx.partner_name == "테스트협력사"
assert ctx.product_name == "테스트상품" assert ctx.product_name == "테스트상품"
assert ctx.revenue_amount == 12_000_000.0 assert ctx.revenue_amount == 12_000_000.0
+44
View File
@@ -58,6 +58,21 @@ class suppliers(MAIN_BASE):
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부 deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
class companies(MAIN_BASE):
# company.companies (고객사). 공급사 포털 브랜딩(settings.branding) 조회 전용 미러.
@staticmethod
def DBType():
return DBType.PARTNER.value
__tablename__ = "companies"
__table_args__ = {"schema": "company"}
company_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")) # 회사 식별자(PK)
name = Column(String(100), nullable=False) # 회사명
settings = Column(JSONB, nullable=True) # 회사별 커스터마이징(branding/labels 등, negodata 소유)
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
class items(MAIN_BASE): class items(MAIN_BASE):
# partner.items (상품). # partner.items (상품).
@staticmethod @staticmethod
@@ -123,6 +138,7 @@ class sessions(MAIN_BASE):
reject_reason = Column(String(255), nullable=True) # 거절 사유 reject_reason = Column(String(255), nullable=True) # 거절 사유
reject_price = Column(BigInteger, nullable=True) # 거절 시 제시가(원) reject_price = Column(BigInteger, nullable=True) # 거절 시 제시가(원)
reject_delivery_type = Column(SmallInteger, nullable=True) # 거절 시 배송 유형 (코드) reject_delivery_type = Column(SmallInteger, nullable=True) # 거절 시 배송 유형 (코드)
custom = Column(JSONB, nullable=True) # 협상완료 부가정보 값 {key: value} (정의는 companies.settings.session_fields)
created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC) created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC)
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')"), onupdate=text("(now() AT TIME ZONE 'utc')")) # 수정 시각(UTC, UPDATE 시 자동 갱신) updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')"), onupdate=text("(now() AT TIME ZONE 'utc')")) # 수정 시각(UTC, UPDATE 시 자동 갱신)
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부 deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
@@ -183,6 +199,34 @@ class quotation_settings(MAIN_BASE):
deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부 deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부
class nego_cards(MAIN_BASE):
# card.nego_cards (협상카드). backend 는 번호→UUID 변환(chats.card_id 저장)만 위해 최소 컬럼 미러.
@staticmethod
def DBType():
return DBType.NEGOTIATION.value # 같은 negosium_db — chats 와 동일 세션풀로 조회
__tablename__ = "nego_cards"
__table_args__ = {"schema": "card"}
nego_card_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
number = Column(String(10), nullable=True) # 카드 번호(agent turn.card_id 와 매칭)
deleted = Column(Boolean, nullable=False, server_default=text("false"))
class wild_cards(MAIN_BASE):
# card.wild_cards (와일드카드). backend 는 번호→UUID 변환(chats.card_id 저장)만 위해 최소 컬럼 미러.
@staticmethod
def DBType():
return DBType.NEGOTIATION.value # 같은 negosium_db
__tablename__ = "wild_cards"
__table_args__ = {"schema": "card"}
wild_card_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
number = Column(String(10), nullable=True)
deleted = Column(Boolean, nullable=False, server_default=text("false"))
class chats(MAIN_BASE): class chats(MAIN_BASE):
# negotiation.chats (협상 채팅 메시지 로그). session 1 : N chats. (session_id, seq) 유니크. # negotiation.chats (협상 채팅 메시지 로그). session 1 : N chats. (session_id, seq) 유니크.
@staticmethod @staticmethod
+33 -1
View File
@@ -6,7 +6,7 @@ from sqlalchemy import asc, desc, select, update
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import chats, items, sessions from common.database.model.models import chats, items, sessions, nego_cards, wild_cards
from common.enums import ErrorType, SessionStatus from common.enums import ErrorType, SessionStatus
from common.logger import LOG from common.logger import LOG
@@ -47,6 +47,14 @@ class IChatCRUD(ABC):
async def update_last_offer_price(self, cdb: AsyncSession, session_id, price: int) -> ErrorType: async def update_last_offer_price(self, cdb: AsyncSession, session_id, price: int) -> ErrorType:
pass pass
@abstractmethod
async def get_nego_card_id_by_number(self, cdb: AsyncSession, number: str):
pass
@abstractmethod
async def get_wild_card_id_by_number(self, cdb: AsyncSession, number: str):
pass
class ChatCRUD(IChatCRUD): class ChatCRUD(IChatCRUD):
async def list_by_session(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, list]: async def list_by_session(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, list]:
@@ -112,6 +120,30 @@ class ChatCRUD(IChatCRUD):
LOG.e_no_callstack(ex) LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None return ErrorType.DB_RUN_FAILED, None
async def get_nego_card_id_by_number(self, cdb: AsyncSession, number: str):
# 협상카드 번호(agent turn.card_id) → nego_card_id(UUID). 없으면 None. 카드 사용 로그(chats.card_id) 저장용.
try:
query = select(nego_cards.nego_card_id).where(nego_cards.number == number, nego_cards.deleted == False).limit(1) # noqa: E712
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_nego_card_id_by_number({number}) failed.")
if err_type != ErrorType.SUCCESS or not row_list:
return None
return row_list[0]
except Exception as ex:
LOG.e_no_callstack(ex)
return None
async def get_wild_card_id_by_number(self, cdb: AsyncSession, number: str):
# 와일드카드 번호(agent turn.card_id, wild_card_dynamic) → wild_card_id(UUID). 없으면 None.
try:
query = select(wild_cards.wild_card_id).where(wild_cards.number == number, wild_cards.deleted == False).limit(1) # noqa: E712
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_wild_card_id_by_number({number}) failed.")
if err_type != ErrorType.SUCCESS or not row_list:
return None
return row_list[0]
except Exception as ex:
LOG.e_no_callstack(ex)
return None
async def finalize_session( async def finalize_session(
self, cdb: AsyncSession, session_id, status: int, self, cdb: AsyncSession, session_id, status: int,
bid_price: Optional[int] = None, reject_reason: Optional[str] = None, reject_price: Optional[int] = None, bid_price: Optional[int] = None, reject_reason: Optional[str] = None, reject_price: Optional[int] = None,
+18
View File
@@ -41,6 +41,10 @@ class ISessionCRUD(ABC):
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType: async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
pass pass
@abstractmethod
async def update_session_custom(self, cdb: AsyncSession, session_id, supplier_id, custom: dict) -> ErrorType:
pass
class SessionCRUD(ISessionCRUD): class SessionCRUD(ISessionCRUD):
@staticmethod @staticmethod
@@ -86,6 +90,7 @@ class SessionCRUD(ISessionCRUD):
items.name, items.name,
items.model_name, items.model_name,
items.manufacturer, items.manufacturer,
sessions.custom,
) )
.join(items, items.item_id == sessions.item_id) .join(items, items.item_id == sessions.item_id)
.join(quotations, quotations.qt_id == sessions.quotation_id) .join(quotations, quotations.qt_id == sessions.quotation_id)
@@ -173,3 +178,16 @@ class SessionCRUD(ISessionCRUD):
except Exception as ex: except Exception as ex:
LOG.e_no_callstack(ex) LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED return ErrorType.DB_RUN_FAILED
async def update_session_custom(self, cdb: AsyncSession, session_id, supplier_id, custom: dict) -> ErrorType:
# 협상완료 부가정보(sessions.custom) 저장. 본인 공급사 세션만(supplier_id 가드).
try:
query = (
update(sessions)
.where(sessions.session_id == session_id, sessions.supplier_id == supplier_id)
.values(custom=custom)
)
return await DB_SESSION_MNG.add(cdb, query)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
+46 -1
View File
@@ -5,7 +5,7 @@ from sqlalchemy import delete, select, update
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import supplier_user_tokens, supplier_users, suppliers from common.database.model.models import supplier_user_tokens, supplier_users, suppliers, companies, sessions
from common.enums import ErrorType, TokenType from common.enums import ErrorType, TokenType
from common.logger import LOG from common.logger import LOG
from common.utils.gtime import GTime from common.utils.gtime import GTime
@@ -28,6 +28,14 @@ class IUserCRUD(ABC):
async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, str]: async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, str]:
pass pass
@abstractmethod
async def get_company_settings(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, dict]:
pass
@abstractmethod
async def get_branding_by_session(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, dict]:
pass
@abstractmethod @abstractmethod
async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType: async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType:
pass pass
@@ -117,6 +125,43 @@ class UserCRUD(IUserCRUD):
LOG.e_no_callstack(ex) LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None return ErrorType.DB_RUN_FAILED, None
async def get_company_settings(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, dict]:
"""공급사 소속 회사 설정(companies.settings) 전체. 브랜딩·협상완료 필드 등이 들어있다. 미설정이면 빈 dict."""
try:
query = (
select(companies.settings)
.join(suppliers, suppliers.company_id == companies.company_id)
.where(suppliers.supplier_id == supplier_id, suppliers.deleted == False, companies.deleted == False) # noqa: E712
.limit(1)
)
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_company_settings(supplier_id:{supplier_id}) failed.")
if err_type != ErrorType.SUCCESS:
return err_type, {}
settings = row_list[0] if row_list else None
return ErrorType.SUCCESS, settings or {}
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, {}
async def get_branding_by_session(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, dict]:
"""세션이 속한 회사의 브랜딩(companies.settings.branding). 로그인 전 화면이 쓰므로 branding 만 꺼낸다."""
try:
query = (
select(companies.settings)
.join(suppliers, suppliers.company_id == companies.company_id)
.join(sessions, sessions.supplier_id == suppliers.supplier_id)
.where(sessions.session_id == session_id, sessions.deleted == False, companies.deleted == False) # noqa: E712
.limit(1)
)
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_branding_by_session(session_id:{session_id}) failed.")
if err_type != ErrorType.SUCCESS:
return err_type, {}
settings = (row_list[0] if row_list else None) or {}
return ErrorType.SUCCESS, settings.get("branding") or {}
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, {}
async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType: async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType:
try: try:
query = ( query = (
+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 fastapi.security import HTTPAuthorizationCredentials
from common.models.gmodel import UserInfo from common.models.gmodel import UserInfo
@@ -20,6 +20,7 @@ from .protocol import (
Res_Me, Res_Me,
Res_PopupStatus, Res_PopupStatus,
Res_RefreshToken, Res_RefreshToken,
Res_SessionBranding,
) )
# 라우터(MVC 의 컨트롤러). 요청 검증 -> service 호출 -> RemoveNoneResponse 반환만 담당. # 라우터(MVC 의 컨트롤러). 요청 검증 -> service 호출 -> RemoveNoneResponse 반환만 담당.
@@ -106,3 +107,16 @@ async def hide_popup(
service: AuthService = Depends(), service: AuthService = Depends(),
): ):
return RemoveNoneResponse(await service.hide_popup(user_info, credentials.credentials, req.popup_type)) return RemoveNoneResponse(await service.hide_popup(user_info, credentials.credentials, req.popup_type))
@router.get(
path="/session-branding/{session_id}",
response_model=Res_SessionBranding,
summary="세션 브랜딩(무인증)",
description="초청 링크로 진입한 로그인 전 화면에서 회사 서비스명·로고·색상만 조회한다. 인증 없이 열려 있으므로 브랜딩 외 정보는 내리지 않는다.",
)
async def session_branding(
session_id: str = Path(..., description="협상 세션 uuid (초청 링크의 session_id)"),
service: AuthService = Depends(),
):
return RemoveNoneResponse(await service.session_branding(session_id))
+8
View File
@@ -48,6 +48,8 @@ class Res_Me(Res_WebPacketProtocol):
supplier_id: str = Field("", description="소속 공급사 uuid") supplier_id: str = Field("", description="소속 공급사 uuid")
supplier_name: str = Field("", description="공급사명") supplier_name: str = Field("", description="공급사명")
role: int = Field(0, description="권한 코드 1=user, 2=manager (UserRole)") role: int = Field(0, description="권한 코드 1=user, 2=manager (UserRole)")
branding: dict = Field(default_factory=dict, description="소속 회사 브랜딩(companies.settings.branding). 서비스명/로고/색")
session_fields: list = Field(default_factory=list, description="협상완료 부가정보 필드 정의(companies.settings.session_fields). 공급사가 타결 후 입력")
class Res_Logout(Res_WebPacketProtocol): class Res_Logout(Res_WebPacketProtocol):
@@ -64,3 +66,9 @@ class Req_HidePopup(AuthProtocol):
class Res_HidePopup(Res_WebPacketProtocol): class Res_HidePopup(Res_WebPacketProtocol):
pass pass
class Res_SessionBranding(Res_WebPacketProtocol):
service_name: str = Field("", description="회사 서비스명(companies.settings.branding.service_name). 미설정 시 빈 값")
logo_url: str = Field("", description="회사 로고 URL")
primary_color: str = Field("", description="브랜드 색상(hex)")
+1
View File
@@ -77,6 +77,7 @@ class Res_ChatInit(Res_WebPacketProtocol):
item_min_order_quantity: str = Field("", description="최소 주문 수량") item_min_order_quantity: str = Field("", description="최소 주문 수량")
item_vat_yn: Optional[bool] = Field(None, description="VAT 포함 여부(미설정 시 null)") item_vat_yn: Optional[bool] = Field(None, description="VAT 포함 여부(미설정 시 null)")
item_delivery_fee_yn: Optional[bool] = Field(None, description="배송비 포함 여부(미설정 시 null)") item_delivery_fee_yn: Optional[bool] = Field(None, description="배송비 포함 여부(미설정 시 null)")
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 기존 입력값(sessions.custom). 재진입 시 폼 프리필용")
# 대화 히스토리(재진입 복원) # 대화 히스토리(재진입 복원)
@@ -14,6 +14,7 @@ class ListItem(WebPacketProtocol):
item_name: str = Field("", description="상품명") item_name: str = Field("", description="상품명")
model_name: str = Field("", description="모델명") model_name: str = Field("", description="모델명")
maker_name: str = Field("", description="제조사") maker_name: str = Field("", description="제조사")
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 값(sessions.custom). 미입력이면 빈 dict")
class Res_SessionList(Res_WebPacketProtocol): class Res_SessionList(Res_WebPacketProtocol):
@@ -33,3 +34,11 @@ class Req_Reject(WebPacketProtocol):
class Res_Reject(Res_WebPacketProtocol): class Res_Reject(Res_WebPacketProtocol):
session_id: str = Field("", description="거부 처리된 세션 uuid") session_id: str = Field("", description="거부 처리된 세션 uuid")
class Req_ExtraInfo(WebPacketProtocol):
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 값 {key: value} (회사 정의 session_fields 대로)")
class Res_ExtraInfo(Res_WebPacketProtocol):
session_id: str = Field("", description="부가정보 저장된 세션 uuid")
+17 -1
View File
@@ -6,7 +6,7 @@ from fastapi.security import HTTPAuthorizationCredentials
from common.models.gmodel import UserInfo from common.models.gmodel import UserInfo
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, security from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, security
from services.negotiation_service import NegotiationService from services.negotiation_service import NegotiationService
from .protocol import Req_Reject, Res_Participate, Res_Reject, Res_SessionList from .protocol import Req_ExtraInfo, Req_Reject, Res_ExtraInfo, Res_Participate, Res_Reject, Res_SessionList
router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={404: {"description": "Not found"}}) router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={404: {"description": "Not found"}})
@@ -61,3 +61,19 @@ async def reject(
service: NegotiationService = Depends(), service: NegotiationService = Depends(),
): ):
return RemoveNoneResponse(await service.reject(user_info, credentials.credentials, session_id, req.reject_reason)) return RemoveNoneResponse(await service.reject(user_info, credentials.credentials, session_id, req.reject_reason))
@router.post(
path="/sessions/{session_id}/extra-info",
response_model=Res_ExtraInfo,
summary="협상완료 부가정보 저장",
description="협상 타결(완료) 세션에 부가정보(표준납기/MOQ/발주배수/배송유형 등, 회사 정의 session_fields)를 저장한다. 본인 공급사의 완료 세션만 허용.",
)
async def save_extra_info(
session_id: str = Path(description="대상 협상 세션 uuid"),
req: Req_ExtraInfo = ...,
user_info: UserInfo = Depends(IsValidAccessToken),
credentials: HTTPAuthorizationCredentials = Depends(security),
service: NegotiationService = Depends(),
):
return RemoveNoneResponse(await service.save_extra_info(user_info, credentials.credentials, session_id, req))
+29
View File
@@ -18,6 +18,7 @@ from router.v1.auth.protocol import (
Res_Me, Res_Me,
Res_PopupStatus, Res_PopupStatus,
Res_RefreshToken, Res_RefreshToken,
Res_SessionBranding,
) )
from router.v1.validator.dependencies import CreateAccessToken, CreateRefreshToken, GetHashedPW, VerifyPW from router.v1.validator.dependencies import CreateAccessToken, CreateRefreshToken, GetHashedPW, VerifyPW
@@ -250,6 +251,34 @@ class AuthService:
res.supplier_id = info.supplier_id res.supplier_id = info.supplier_id
res.supplier_name = info.supplier_name res.supplier_name = info.supplier_name
res.role = info.role res.role = info.role
# 소속 회사 설정(companies.settings) — 로고/서비스명(branding) + 협상완료 부가필드(session_fields). 실패해도 기본값.
_e, settings = await DB_SESSION_MNG.execute_lambda(
suppliers.DBType(),
DBWRType.DB_READ.value,
lambda s: self.user_crud.get_company_settings(s, uuid.UUID(info.supplier_id)),
)
settings = settings or {}
res.branding = settings.get("branding") or {}
res.session_fields = settings.get("session_fields") or []
return res
async def session_branding(self, session_id: str) -> Res_SessionBranding:
"""로그인 전(초청 링크 진입) 화면용 브랜딩. 인증 없이 session_id 로만 조회하며 브랜딩 외 정보는 내리지 않는다."""
res = Res_SessionBranding()
try:
sid = uuid.UUID(session_id)
except ValueError:
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
return res
_e, branding = await DB_SESSION_MNG.execute_lambda(
suppliers.DBType(),
DBWRType.DB_READ.value,
lambda s: self.user_crud.get_branding_by_session(s, sid),
)
branding = branding or {}
res.service_name = branding.get("service_name") or ""
res.logo_url = branding.get("logo_url") or ""
res.primary_color = branding.get("primary_color") or ""
return res return res
async def popup_status(self, user_info: UserInfo, access_token: str) -> Res_PopupStatus: async def popup_status(self, user_info: UserInfo, access_token: str) -> Res_PopupStatus:
+65 -2
View File
@@ -103,13 +103,18 @@ class ChatService:
) )
@staticmethod @staticmethod
def _build_bot_chat(sess, seq: int, turn, bot_chat_type: Optional[str] = None, summary: Optional[dict] = None) -> chats: def _build_bot_chat(sess, seq: int, turn, bot_chat_type: Optional[str] = None, summary: Optional[dict] = None, card_uuid=None, card_type=None) -> chats:
# bot_chat_type/summary 도 meta 에 영속화 → 히스토리 복원 시 폼 재현. indicator_value 는 전용 컬럼에도 적재. # bot_chat_type/summary 도 meta 에 영속화 → 히스토리 복원 시 폼 재현. indicator_value 는 전용 컬럼에도 적재.
# nego_card_uuid: turn.card_id(번호)를 UUID 로 변환한 값(nego 카드). 있으면 chats.card_id/card_type/card_used_yn 컬럼에 적재
# → negodata 가 이 컬럼으로 카드 사용/효과를 조인한다. (wild 카드는 agent 가 card_id 미제공 — 별도 작업)
return chats( return chats(
chat_id=uuid.uuid4(), session_id=sess.session_id, seq=seq, chat_id=uuid.uuid4(), session_id=sess.session_id, seq=seq,
sender=ChatSender.BOT.value, sender=ChatSender.BOT.value,
target_price=int(sess.target_price or 0), target_price=int(sess.target_price or 0),
indicator_value=turn.indicator_value, indicator_value=turn.indicator_value,
card_id=card_uuid,
card_type=card_type if card_uuid else None, # CardType: 1=nego, 2=wild
card_used_yn=True if card_uuid else None,
meta={ meta={
"script": turn.script, "step": turn.step, "client_step": turn.client_step, "script": turn.script, "step": turn.step, "client_step": turn.client_step,
"input_mode": turn.input_mode, "input_options": turn.input_options, "input_mode": turn.input_mode, "input_options": turn.input_options,
@@ -204,6 +209,8 @@ class ChatService:
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE) res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
return res return res
await self._ensure_in_progress(sess, quote)
res.session_id = str(sess.session_id) res.session_id = str(sess.session_id)
res.session_status = sess.status res.session_status = sess.status
res.quotation_id = str(sess.quotation_id) res.quotation_id = str(sess.quotation_id)
@@ -221,8 +228,36 @@ class ChatService:
res.item_min_order_quantity = item.moq or "" res.item_min_order_quantity = item.moq or ""
res.item_vat_yn = item.vat_yn res.item_vat_yn = item.vat_yn
res.item_delivery_fee_yn = item.delivery_fee_yn res.item_delivery_fee_yn = item.delivery_fee_yn
res.custom = sess.custom or {}
return res return res
async def _ensure_in_progress(self, sess, quote) -> None:
"""협상생성(1) 세션을 채팅 진입만으로 협상중(2)으로 전이한다(participate 와 동일 전이).
negodata 안내 메일/링크는 목록의 참여 버튼을 거치지 않고 chat 으로 바로 들어오는데,
오프닝 메시지는 협상중일 때만 seed 되므로 전이가 없으면 빈 채팅으로 멈춘다.
마감된 견적은 진입해도 대화가 불가하므로 전이하지 않는다."""
if sess.status != SessionStatus.CREATED.value:
return
if quote is None or quote.status == QuotationStatus.CLOSED.value:
return
end = quote.end_time
if end is not None and end.tzinfo is None:
end = end.replace(tzinfo=timezone.utc)
if end is not None and end < datetime.now(timezone.utc):
return
err_type = await DB_SESSION_MNG.execute_lambda_run(
[sessions.DBType()],
[
lambda s: self.session_crud.update_session_status(s, sess.session_id, SessionStatus.IN_PROGRESS.value),
lambda s: self.session_crud.update_quotation_status(s, sess.quotation_id, QuotationStatus.IN_PROGRESS.value),
],
)
if err_type != ErrorType.SUCCESS:
return
sess.status = SessionStatus.IN_PROGRESS.value
# ---- messages ------------------------------------------------------- # ---- messages -------------------------------------------------------
async def messages(self, user_info: UserInfo, access_token: str, session_id_str: str) -> Res_ChatMessages: async def messages(self, user_info: UserInfo, access_token: str, session_id_str: str) -> Res_ChatMessages:
res = Res_ChatMessages() res = Res_ChatMessages()
@@ -239,6 +274,15 @@ class ChatService:
res.result.SetResult(err_type) res.result.SetResult(err_type)
return res return res
# 협상생성 상태로 바로 진입한 경우(메일 링크) 여기서도 전이한다 —
# init 과 병렬로 호출돼 init 의 전이를 못 본 채 읽었을 수 있다.
if not rows and sess.status == SessionStatus.CREATED.value:
_, quote = await DB_SESSION_MNG.execute_lambda(
quotations.DBType(), DBWRType.DB_READ.value,
lambda s: self.session_crud.get_quotation_by_id(s, sess.quotation_id),
)
await self._ensure_in_progress(sess, quote)
# 비어 있고 협상중이면 agent 오프닝 한 턴을 seed (재진입 시 인사 메시지 보존) # 비어 있고 협상중이면 agent 오프닝 한 턴을 seed (재진입 시 인사 메시지 보존)
if not rows and sess.status == SessionStatus.IN_PROGRESS.value: if not rows and sess.status == SessionStatus.IN_PROGRESS.value:
opening = await self._seed_opening(sess) opening = await self._seed_opening(sess)
@@ -371,8 +415,27 @@ class ChatService:
# 유저 미입력 가격 타결 케이스 — 마지막 유저 제시가와 다를 수 있다). # 유저 미입력 가격 타결 케이스 — 마지막 유저 제시가와 다를 수 있다).
summary = await self._build_summary(sess, quote, item, final_price, turn.settled_price or last_price) summary = await self._build_summary(sess, quote, item, final_price, turn.settled_price or last_price)
# 카드 번호(turn.card_id) → UUID 변환. step 으로 nego/wild 갈라 각 테이블 조회(번호가 겹칠 수 있어 종류로 구분).
# 카드 사용 로그(chats.card_id/type/used)를 negodata 조인용으로 남긴다. (1% 인하 시스템 카드는 agent 가 card_id 미제공)
card_uuid = None
card_type = None
if turn.card_id:
is_wild = bool(turn.step and turn.step.startswith("wild"))
if is_wild:
card_uuid = await DB_SESSION_MNG.execute_lambda(
chats.DBType(), DBWRType.DB_READ.value,
lambda s: self.chat_crud.get_wild_card_id_by_number(s, str(turn.card_id)),
)
card_type = 2
else:
card_uuid = await DB_SESSION_MNG.execute_lambda(
chats.DBType(), DBWRType.DB_READ.value,
lambda s: self.chat_crud.get_nego_card_id_by_number(s, str(turn.card_id)),
)
card_type = 1
# 봇 메시지 + 종료 시 확정(성공=DONE+입찰가 / 실패=REJECTED+거부사유·제시가). 한 트랜잭션. # 봇 메시지 + 종료 시 확정(성공=DONE+입찰가 / 실패=REJECTED+거부사유·제시가). 한 트랜잭션.
bot_msg = self._build_bot_chat(sess, seq=max_seq + 2, turn=turn, bot_chat_type=bot_chat_type, summary=summary) bot_msg = self._build_bot_chat(sess, seq=max_seq + 2, turn=turn, bot_chat_type=bot_chat_type, summary=summary, card_uuid=card_uuid, card_type=card_type)
funcs = [lambda s: self.chat_crud.insert_message(s, bot_msg)] funcs = [lambda s: self.chat_crud.insert_message(s, bot_msg)]
# 가격 입력 턴 → 마지막 제시가를 봇 메시지 저장과 같은 트랜잭션으로 갱신. # 가격 입력 턴 → 마지막 제시가를 봇 메시지 저장과 같은 트랜잭션으로 갱신.
# 앵커링 표본 판정의 "가격 흔적"(가격을 써낸 협상만 집계 — 중간 이탈해도 실패로 측정 가능). # 앵커링 표본 판정의 "가격 흔적"(가격을 써낸 협상만 집계 — 중간 이탈해도 실패로 측정 가능).
+74 -3
View File
@@ -4,11 +4,12 @@ from datetime import datetime, timezone
from fastapi import Depends from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import sessions from common.database.model.models import chats, sessions
from common.enums import DBWRType, ErrorType, QuotationStatus, SessionStatus from common.enums import DBWRType, ErrorType, QuotationStatus, SessionStatus
from common.models.gmodel import UserInfo from common.models.gmodel import UserInfo
from crud.chat_crud import ChatCRUD, IChatCRUD
from crud.session_crud import ISessionCRUD, SessionCRUD from crud.session_crud import ISessionCRUD, SessionCRUD
from router.v1.negotiation.protocol import ListItem, Res_Participate, Res_Reject, Res_SessionList from router.v1.negotiation.protocol import ListItem, Req_ExtraInfo, Res_ExtraInfo, Res_Participate, Res_Reject, Res_SessionList
from services.auth_service import AuthService from services.auth_service import AuthService
@@ -18,9 +19,18 @@ class NegotiationService:
- 목록은 로그인 유저의 supplier_id 로만 조회한다. - 목록은 로그인 유저의 supplier_id 로만 조회한다.
""" """
def __init__(self, auth: AuthService = Depends(AuthService), session_crud: ISessionCRUD = Depends(SessionCRUD)): # 부가정보 입력 폼을 띄우는 요약 말풍선 종류. 이 말풍선이 나온 뒤면 협상은 타결된 것으로 본다.
_SUMMARY_BOT_TYPES = ("summaryRSP", "summaryCM")
def __init__(
self,
auth: AuthService = Depends(AuthService),
session_crud: ISessionCRUD = Depends(SessionCRUD),
chat_crud: IChatCRUD = Depends(ChatCRUD),
):
self.auth = auth self.auth = auth
self.session_crud = session_crud self.session_crud = session_crud
self.chat_crud = chat_crud
async def list_sessions(self, user_info: UserInfo, access_token: str, status, qt_type, order: str, page: int, page_size: int) -> Res_SessionList: async def list_sessions(self, user_info: UserInfo, access_token: str, status, qt_type, order: str, page: int, page_size: int) -> Res_SessionList:
res = Res_SessionList() res = Res_SessionList()
@@ -65,6 +75,7 @@ class NegotiationService:
item_name=r[6] or "", item_name=r[6] or "",
model_name=r[7] or "", model_name=r[7] or "",
maker_name=r[8] or "", maker_name=r[8] or "",
custom=r[9] or {},
) )
for r in rows for r in rows
] ]
@@ -73,6 +84,66 @@ class NegotiationService:
res.page_size = page_size res.page_size = page_size
return res return res
async def save_extra_info(self, user_info: UserInfo, access_token: str, session_id_str: str, req: Req_ExtraInfo) -> Res_ExtraInfo:
"""협상완료(타결) 부가정보 저장. 견적 마감 여부와 무관하게, 본인 공급사의 '협상완료' 세션에만 허용.
_load_actionable_session 은 견적마감·마감시간을 막으므로(타결 후엔 마감됐을 수 있음) 쓰지 않고 직접 검증한다.
"""
res = Res_ExtraInfo()
# 1) 인증
err_type, info = await self.auth.authenticate(user_info, access_token)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
try:
session_id = uuid.UUID(session_id_str)
except (ValueError, TypeError):
res.result.SetResult(ErrorType.NEGO_NOT_FOUND)
return res
# 2) 세션 조회 + 소유 검증
err_type, sess = await DB_SESSION_MNG.execute_lambda(
sessions.DBType(), DBWRType.DB_READ.value,
lambda s: self.session_crud.get_session_by_id(s, session_id),
)
if err_type != ErrorType.SUCCESS or sess is None:
res.result.SetResult(ErrorType.NEGO_NOT_FOUND)
return res
if str(sess.supplier_id) != info.supplier_id:
res.result.SetResult(ErrorType.NEGO_FORBIDDEN)
return res
# 3) 협상완료(타결) 세션만 부가정보 입력 허용.
# 단 '협상완료' 요약 말풍선은 chat_end=false 라 세션이 아직 협상중(2)이다
# (동의 → '협상종료' 턴에서야 완료로 전이). 폼은 요약 시점에 뜨므로 그 구간도 허용한다.
if sess.status != SessionStatus.DONE.value:
if sess.status != SessionStatus.IN_PROGRESS.value or not await self._is_after_summary(sess.session_id):
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
return res
# 4) 저장(supplier_id 가드 crud)
err_type = await DB_SESSION_MNG.execute_lambda_run(
[sessions.DBType()],
[lambda s: self.session_crud.update_session_custom(s, session_id, uuid.UUID(info.supplier_id), req.custom or {})],
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
res.session_id = str(session_id)
return res
async def _is_after_summary(self, session_id) -> bool:
"""마지막 말풍선이 타결 요약(summaryRSP/CM)인지 — 즉 협상이 타결된 뒤인지."""
err_type, (_, _, last_meta) = await DB_SESSION_MNG.execute_lambda(
chats.DBType(), DBWRType.DB_READ.value,
lambda s: self.chat_crud.get_last(s, session_id),
)
if err_type != ErrorType.SUCCESS or not last_meta:
return False
return last_meta.get("bot_chat_type") in self._SUMMARY_BOT_TYPES
async def _load_actionable_session(self, user_info: UserInfo, access_token: str, session_id_str: str, blocked_statuses: tuple): async def _load_actionable_session(self, user_info: UserInfo, access_token: str, session_id_str: str, blocked_statuses: tuple):
"""참여/거부 공통 전처리: 인증 → 세션/견적 로드 → 소유·상태·견적마감·마감시간 검증. """참여/거부 공통 전처리: 인증 → 세션/견적 로드 → 소유·상태·견적마감·마감시간 검증.
성공 시 (SUCCESS, sess, quote), 실패 시 (err_type, None, None) 을 반환한다. 성공 시 (SUCCESS, sess, quote), 실패 시 (err_type, None, None) 을 반환한다.
+12
View File
@@ -7,6 +7,7 @@
# negosium 서버: http://localhost:9300/docs # negosium 서버: http://localhost:9300/docs
# negosium 프론트: http://localhost:3300 # negosium 프론트: http://localhost:3300
# negodata 서버: http://localhost:9400/docs # negodata 서버: http://localhost:9400/docs
# 솔루션 랜딩: http://localhost:3100
# agent 서버: http://localhost:9500/docs # agent 서버: http://localhost:9500/docs
# anchoring 배치: 포트 없음 — 상주 스케줄러(격주 토 00:00 KST), docker logs anchoring 으로 확인 # anchoring 배치: 포트 없음 — 상주 스케줄러(격주 토 00:00 KST), docker logs anchoring 으로 확인
# #
@@ -60,6 +61,17 @@ services:
- /app/node_modules - /app/node_modules
restart: unless-stopped restart: unless-stopped
# 솔루션 랜딩페이지 (react-router dev 서버. 배포는 `npm run build` 산출물 build/client 정적 서빙).
landing:
build: ./landing
container_name: negosium-landing
ports:
- "3100:3100"
volumes:
- ./landing:/app
- /app/node_modules
restart: unless-stopped
# 협상 에이전트 (negosium_db 공유, learning 스키마 사용). # 협상 에이전트 (negosium_db 공유, learning 스키마 사용).
agent: agent:
build: ./agent build: ./agent
+1 -1
View File
@@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/bot.png" /> <link rel="icon" type="image/png" href="/bot.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<title>AI 가격 협상 솔루션</title> <title>AI 가격 협상 솔루션</title>
</head> </head>
<body> <body>
+7
View File
@@ -11,6 +11,7 @@ import type {
LogoutResponse, LogoutResponse,
MeResponse, MeResponse,
PopupStatusResponse, PopupStatusResponse,
SessionBrandingResponse,
} from './auth.type' } from './auth.type'
export const authApi = { export const authApi = {
@@ -26,6 +27,12 @@ export const authApi = {
return res.data return res.data
}, },
/** GET /v1/auth/session-branding/{sessionId} — 로그인 전 화면용 브랜딩(인증 불필요) */
sessionBranding: async (sessionId: string): Promise<SessionBrandingResponse> => {
const res = await http.get<SessionBrandingResponse>(`/v1/auth/session-branding/${sessionId}`)
return res.data
},
/** GET /v1/auth/me — 현재 로그인 유저 정보 (access token 필요) */ /** GET /v1/auth/me — 현재 로그인 유저 정보 (access token 필요) */
me: async (): Promise<MeResponse> => { me: async (): Promise<MeResponse> => {
const res = await http.get<MeResponse>('/v1/auth/me') const res = await http.get<MeResponse>('/v1/auth/me')
+28
View File
@@ -54,6 +54,28 @@ export interface RefreshTokenResponse {
} }
// --- 내 정보 (GET /v1/auth/me) ------------------------------------------- // --- 내 정보 (GET /v1/auth/me) -------------------------------------------
export interface Branding {
service_name?: string
logo_url?: string
primary_color?: string
email_header?: string
}
// 로그인 전(초청 링크 진입) 브랜딩 조회 — GET /v1/auth/session-branding/{session_id}, 인증 불필요
export interface SessionBrandingResponse {
result: ApiResult
service_name: string
logo_url: string
primary_color: string
}
// 협상완료 부가정보 필드 정의(companies.settings.session_fields)
export interface SessionField {
key: string
label: string
type: 'text' | 'number' | 'boolean'
}
export interface MeResponse { export interface MeResponse {
result: ApiResult result: ApiResult
su_id: string su_id: string
@@ -62,6 +84,8 @@ export interface MeResponse {
supplier_id: string supplier_id: string
supplier_name: string supplier_name: string
role: number role: number
branding?: Branding
session_fields?: SessionField[]
} }
// --- 로그아웃 ------------------------------------------------------------- // --- 로그아웃 -------------------------------------------------------------
@@ -94,6 +118,8 @@ export interface AuthUser {
supplierId: string supplierId: string
supplierName: string supplierName: string
role: number role: number
branding: Branding
sessionFields: SessionField[]
} }
export function toAuthUser(res: MeResponse): AuthUser { export function toAuthUser(res: MeResponse): AuthUser {
@@ -104,5 +130,7 @@ export function toAuthUser(res: MeResponse): AuthUser {
supplierId: res.supplier_id, supplierId: res.supplier_id,
supplierName: res.supplier_name, supplierName: res.supplier_name,
role: res.role, role: res.role,
branding: res.branding ?? {},
sessionFields: res.session_fields ?? [],
} }
} }
+2
View File
@@ -46,6 +46,7 @@ export interface ChatInitResponse {
item_min_order_quantity?: string item_min_order_quantity?: string
item_vat_yn?: boolean item_vat_yn?: boolean
item_delivery_fee_yn?: boolean item_delivery_fee_yn?: boolean
custom?: Record<string, unknown>
} }
export interface ChatMessagesResponse { export interface ChatMessagesResponse {
@@ -98,6 +99,7 @@ export function mapInit(r: ChatInitResponse): ChatInitData {
item_delivery_fee_yn: item_delivery_fee_yn:
r.item_delivery_fee_yn == null ? '' : r.item_delivery_fee_yn ? '배송비포함' : '배송비별도', r.item_delivery_fee_yn == null ? '' : r.item_delivery_fee_yn ? '배송비포함' : '배송비별도',
item_min_order_quantity: r.item_min_order_quantity ?? '', item_min_order_quantity: r.item_min_order_quantity ?? '',
custom: r.custom ?? {},
item_lead_time: r.item_lead_time ?? '', item_lead_time: r.item_lead_time ?? '',
item_spec: r.item_spec ?? '', item_spec: r.item_spec ?? '',
quotation_memo: r.quotation_memo ?? '', quotation_memo: r.quotation_memo ?? '',
+1 -1
View File
@@ -2,5 +2,5 @@
export { negotiationApi } from './negotiation.api' export { negotiationApi } from './negotiation.api'
export { negotiationKeys } from './negotiation.keys' export { negotiationKeys } from './negotiation.keys'
export { useSessionListQuery } from './negotiation.queries' export { useSessionListQuery } from './negotiation.queries'
export { useParticipateMutation, useRejectMutation } from './negotiation.mutations' export { useParticipateMutation, useRejectMutation, useSaveExtraInfoMutation } from './negotiation.mutations'
export * from './negotiation.type' export * from './negotiation.type'
@@ -1,6 +1,8 @@
// 협상 엔드포인트 호출 함수 (순수 HTTP 레이어, React 의존 없음). // 협상 엔드포인트 호출 함수 (순수 HTTP 레이어, React 의존 없음).
import { http } from '@/apis/http' import { http } from '@/apis/http'
import type { import type {
ExtraInfoRequest,
ExtraInfoResponse,
ParticipateResponse, ParticipateResponse,
RejectRequest, RejectRequest,
RejectResponse, RejectResponse,
@@ -31,4 +33,13 @@ export const negotiationApi = {
) )
return res.data return res.data
}, },
/** POST /v1/negotiation/sessions/{id}/extra-info — 협상완료 부가정보 저장 */
saveExtraInfo: async (sessionId: string, body: ExtraInfoRequest): Promise<ExtraInfoResponse> => {
const res = await http.post<ExtraInfoResponse>(
`/v1/negotiation/sessions/${sessionId}/extra-info`,
body,
)
return res.data
},
} }
@@ -2,7 +2,7 @@
import { useMutation, useQueryClient } from '@tanstack/react-query' import { useMutation, useQueryClient } from '@tanstack/react-query'
import { negotiationApi } from './negotiation.api' import { negotiationApi } from './negotiation.api'
import { negotiationKeys } from './negotiation.keys' import { negotiationKeys } from './negotiation.keys'
import type { RejectRequest } from './negotiation.type' import type { ExtraInfoRequest, RejectRequest } from './negotiation.type'
/** /**
* 협상 세션 참여: 성공 시 세션 목록 캐시를 무효화해 상태를 갱신한다. * 협상 세션 참여: 성공 시 세션 목록 캐시를 무효화해 상태를 갱신한다.
@@ -30,3 +30,17 @@ export function useRejectMutation() {
}, },
}) })
} }
/**
* 협상완료 부가정보 저장: 성공 시 세션 목록 캐시를 무효화한다.
*/
export function useSaveExtraInfoMutation() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ sessionId, request }: { sessionId: string; request: ExtraInfoRequest }) =>
negotiationApi.saveExtraInfo(sessionId, request),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() })
},
})
}
@@ -55,6 +55,7 @@ export interface SessionListItem {
item_name: string item_name: string
model_name: string model_name: string
maker_name: string maker_name: string
custom: Record<string, unknown> // 협상완료 부가정보(sessions.custom). 미입력이면 {}
} }
export interface SessionListResponse { export interface SessionListResponse {
@@ -65,6 +66,15 @@ export interface SessionListResponse {
page_size: number page_size: number
} }
// --- 협상완료 부가정보 (POST /v1/negotiation/sessions/{id}/extra-info) -----
export interface ExtraInfoRequest {
custom: Record<string, unknown>
}
export interface ExtraInfoResponse {
result: ApiResult
session_id: string
}
// --- 참여 (POST /v1/negotiation/sessions/{id}/participate) ---------------- // --- 참여 (POST /v1/negotiation/sessions/{id}/participate) ----------------
export interface ParticipateResponse { export interface ParticipateResponse {
result: ApiResult result: ApiResult
Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

+4 -4
View File
@@ -10,18 +10,18 @@ export type ButtonVariant =
export type ButtonSize = 'sm' | 'md' | 'lg' export type ButtonSize = 'sm' | 'md' | 'lg'
const base = const base =
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md font-medium select-none ' + 'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl font-semibold select-none ' +
interactive + interactive +
' focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ' + ' focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ' +
'disabled:pointer-events-none disabled:opacity-50' 'disabled:pointer-events-none disabled:opacity-50'
const variantClass: Record<ButtonVariant, string> = { const variantClass: Record<ButtonVariant, string> = {
primary: 'bg-primary text-primary-foreground', primary: 'bg-primary text-primary-foreground shadow-sm',
secondary: 'bg-secondary text-secondary-foreground', secondary: 'bg-secondary text-secondary-foreground',
outline: 'border border-input bg-background', outline: 'border border-border bg-background text-foreground',
// 투명 배경이라 brightness 무효 → bg 하이라이트 // 투명 배경이라 brightness 무효 → bg 하이라이트
ghost: 'hover:bg-accent hover:text-accent-foreground', ghost: 'hover:bg-accent hover:text-accent-foreground',
destructive: 'bg-destructive text-white', destructive: 'bg-destructive text-white shadow-sm',
} }
const sizeClass: Record<ButtonSize, string> = { const sizeClass: Record<ButtonSize, string> = {
+6 -6
View File
@@ -18,13 +18,13 @@ export function ErrorPage({
}: ErrorPageProps) { }: ErrorPageProps) {
return ( return (
<div className="flex h-full w-full items-center justify-center"> <div className="flex h-full w-full items-center justify-center">
<div className="flex flex-col items-center gap-6 p-12"> <div className="flex flex-col items-center gap-5 p-12">
<div className="flex size-20 items-center justify-center rounded-full bg-destructive/10"> <div className="flex size-16 items-center justify-center rounded-full bg-destructive/10">
<AlertTriangle className="size-10 text-destructive" /> <AlertTriangle className="size-8 text-destructive" />
</div> </div>
<div className="flex flex-col items-center gap-2 text-center"> <div className="flex flex-col items-center gap-1.5 text-center">
<p className="title-2 text-destructive">{message}</p> <p className="text-lg font-bold text-neutral-90">{message}</p>
<p className="body-1 text-neutral-70">{description}</p> <p className="text-sm text-neutral-60">{description}</p>
</div> </div>
{onRetry && ( {onRetry && (
<Button variant="primary" size="lg" onClick={onRetry}> <Button variant="primary" size="lg" onClick={onRetry}>
+2 -2
View File
@@ -6,9 +6,9 @@ export function Input({ type = 'text', className, ...props }: ComponentProps<'in
<input <input
type={type} type={type}
className={cn( className={cn(
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm', 'flex h-10 w-full rounded-xl border border-input bg-background px-3.5 py-2 text-sm transition-all',
'placeholder:text-muted-foreground', 'placeholder:text-muted-foreground',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2', 'focus-visible:outline-none focus-visible:border-brand-600 focus-visible:ring-1 focus-visible:ring-brand-600',
'disabled:cursor-not-allowed disabled:opacity-50', 'disabled:cursor-not-allowed disabled:opacity-50',
className, className,
)} )}
+23 -10
View File
@@ -1,14 +1,14 @@
import { type ComponentProps } from 'react' import { type ComponentProps } from 'react'
import { cn } from '@/lib' import { cn } from '@/lib'
import logoColor from '@/assets/imarketkorea-logo.png' import logoDefault from '@/assets/negotium-logo.png'
import logoWhite from '@/assets/imarketkorea-logo-white.png'
export type LogoVariant = 'color' | 'white' export type LogoVariant = 'color' | 'white'
export type LogoSize = 'sm' | 'md' | 'lg' export type LogoSize = 'sm' | 'md' | 'lg'
// 기본 브랜드(회사 설정 미지정 시). 회사 로고가 오면 logoUrl 이 이 값을 덮는다.
const sources: Record<LogoVariant, string> = { const sources: Record<LogoVariant, string> = {
color: logoColor, color: logoDefault,
white: logoWhite, white: logoDefault,
} }
const sizes: Record<LogoSize, { img: string; text: string; gap: string }> = { const sizes: Record<LogoSize, { img: string; text: string; gap: string }> = {
@@ -17,33 +17,46 @@ const sizes: Record<LogoSize, { img: string; text: string; gap: string }> = {
lg: { img: 'h-10', text: 'text-2xl', gap: 'gap-2.5' }, lg: { img: 'h-10', text: 'text-2xl', gap: 'gap-2.5' },
} }
// 기본 브랜드 로고는 가로로 긴 워드마크라 같은 높이로 두면 회사 심볼보다 훨씬 커 보인다(랜딩도 h-4 기준).
const wordmarkSizes: Record<LogoSize, string> = {
sm: 'h-3.5',
md: 'h-4',
lg: 'h-5',
}
export interface LogoProps extends Omit<ComponentProps<'div'>, 'children'> { export interface LogoProps extends Omit<ComponentProps<'div'>, 'children'> {
variant?: LogoVariant variant?: LogoVariant
size?: LogoSize size?: LogoSize
withText?: boolean withText?: boolean
alt?: string alt?: string
/** 회사 브랜딩 오버라이드(companies.settings.branding). 없으면 기본 iMarket Korea. */
serviceName?: string
logoUrl?: string
} }
export function Logo({ export function Logo({
variant = 'color', variant = 'color',
size = 'md', size = 'md',
withText = true, withText = true,
alt = 'iMarket Korea', alt = 'NEGOTIUM',
serviceName,
logoUrl,
className, className,
...props ...props
}: LogoProps) { }: LogoProps) {
const s = sizes[size] const s = sizes[size]
const name = serviceName || 'negotium'
return ( return (
<div className={cn('flex items-center', s.gap, className)} {...props}> <div className={cn('flex items-center', s.gap, className)} {...props}>
<img <img
src={sources[variant]} src={logoUrl || sources[variant]}
alt={withText ? '' : alt} alt={withText ? '' : (serviceName || alt)}
className={cn('w-auto select-none', s.img)} className={cn('w-auto select-none', logoUrl ? s.img : wordmarkSizes[size])}
/> />
{withText && ( {withText && serviceName && (
<span className={cn('font-bold tracking-[-0.4px] text-foreground', s.text)}> <span className={cn('font-bold tracking-[-0.4px] text-foreground', s.text)}>
iMarket Korea {name}
</span> </span>
)} )}
</div> </div>
@@ -1,7 +1,7 @@
import { Button, Input } from '@/components' import { Button, Input } from '@/components'
import { useLogin } from '@/features/auth/hooks/useLogin' import { useLogin } from '@/features/auth/hooks/useLogin'
const inputClassName = 'h-12 rounded-md px-4 text-base' const inputClassName = 'h-12 rounded-xl px-4 text-base'
export function LoginForm() { export function LoginForm() {
const { const {
@@ -6,7 +6,10 @@ import { tokenStorage } from '@/apis'
// 토큰이 있으나 만료/폐기된 경우는 요청 시 인터셉터가 세션을 종료시킨다. // 토큰이 있으나 만료/폐기된 경우는 요청 시 인터셉터가 세션을 종료시킨다.
export function RequireAuth({ children }: { children: ReactNode }) { export function RequireAuth({ children }: { children: ReactNode }) {
if (!tokenStorage.hasToken()) { if (!tokenStorage.hasToken()) {
return <Navigate to="/" replace /> // 초청 링크(/chat?session_id=...)로 들어온 미로그인 사용자 — session_id 를 넘겨야
// 로그인 화면이 그 회사 브랜딩으로 뜬다.
const sessionId = new URLSearchParams(window.location.search).get('session_id')
return <Navigate to={sessionId ? `/?session_id=${sessionId}` : '/'} replace />
} }
return <>{children}</> return <>{children}</>
} }
@@ -1,6 +1,7 @@
import { useNavigate } from 'react-router' import { useNavigate } from 'react-router'
import { LogOut } from 'lucide-react'
import { useLogoutMutation, useMeQuery } from '@/apis' import { useLogoutMutation, useMeQuery } from '@/apis'
import { Button } from '@/components' import { cn, interactive } from '@/lib'
// 사이드바 하단: 공급사명 + 로그아웃 // 사이드바 하단: 공급사명 + 로그아웃
export function SidebarFooter() { export function SidebarFooter() {
@@ -15,19 +16,23 @@ export function SidebarFooter() {
} }
return ( return (
<div className="flex w-full h-[60px] py-3 px-8 gap-3 items-center"> <div className="flex w-full shrink-0 items-center gap-2 border-t border-border px-6 py-3">
<div className="flex-1 flex items-center min-w-0 text-sm text-foreground"> <div className="min-w-0 flex-1">
<span className="truncate">{user?.supplierName ?? '-'}</span> <p className="truncate text-sm font-bold text-neutral-90">{user?.supplierName ?? '-'}</p>
<p className="truncate text-xs text-neutral-60">{user?.name ?? '공급 파트너'}</p>
</div> </div>
<Button <button
variant="secondary" type="button"
size="sm"
className="w-[61px] px-2 rounded-[4px] text-xs flex-shrink-0"
onClick={handleLogout} onClick={handleLogout}
disabled={logout.isPending} disabled={logout.isPending}
className={cn(
'flex shrink-0 items-center gap-1.5 rounded-xl border border-border bg-white px-3 py-1.5 text-xs font-bold text-neutral-70 hover:bg-neutral-10 disabled:opacity-50',
interactive,
)}
> >
<LogOut className="size-3.5" />
로그아웃 로그아웃
</Button> </button>
</div> </div>
) )
} }
@@ -0,0 +1,61 @@
import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router'
import { authApi } from '@/apis'
import type { Branding } from '@/apis/auth/auth.type'
// 로그인 전 화면의 회사 브랜딩을 담아 두는 곳. 로그아웃/토큰 만료와 무관하게 남겨
// 뒤로가기·재진입으로 session_id 가 없어져도 같은 회사 화면을 유지한다(회사 식별 정보만 담는다).
const BRANDING_KEY = 'negosium.preLoginBranding'
function readCached(): Branding | null {
try {
const raw = localStorage.getItem(BRANDING_KEY)
return raw ? (JSON.parse(raw) as Branding) : null
} catch {
return null // 손상된 값은 없는 것으로 본다
}
}
function writeCached(branding: Branding): void {
try {
localStorage.setItem(BRANDING_KEY, JSON.stringify(branding))
} catch {
// 저장 불가(프라이빗 모드 등)면 이번 방문에만 적용된다
}
}
// 로그인 전 화면(로그인 페이지)의 회사 브랜딩.
// 협력사는 초청 메일의 /chat?session_id=... 로 들어오므로, 그 session_id 로 인증 없이 브랜딩만 조회한다.
// session_id 가 없으면 마지막으로 확인된 회사 브랜딩을 쓰고, 그것도 없으면 기본 브랜드(Negosium).
export function usePreLoginBranding(): Branding | null {
const [searchParams] = useSearchParams()
const [branding, setBranding] = useState<Branding | null>(readCached)
const sessionId = searchParams.get('session_id') ?? ''
useEffect(() => {
if (!sessionId) return
let alive = true
void authApi
.sessionBranding(sessionId)
.then((res) => {
if (!alive || res.result?.success === false) return
const next: Branding = {
service_name: res.service_name || undefined,
logo_url: res.logo_url || undefined,
primary_color: res.primary_color || undefined,
}
if (!next.service_name && !next.logo_url) return
setBranding(next)
writeCached(next) // 다음 진입에 session_id 가 없어도 이 회사로 보이게 한다
})
.catch(() => {
// 조회 실패 시 캐시(또는 기본 브랜드)를 그대로 둔다
})
return () => {
alive = false
}
}, [sessionId])
return branding
}
+1
View File
@@ -1,3 +1,4 @@
export { LoginForm } from '@/features/auth/components/LoginForm' export { LoginForm } from '@/features/auth/components/LoginForm'
export { SidebarFooter } from '@/features/auth/components/SidebarFooter' export { SidebarFooter } from '@/features/auth/components/SidebarFooter'
export { RequireAuth } from '@/features/auth/components/RequireAuth' export { RequireAuth } from '@/features/auth/components/RequireAuth'
export { usePreLoginBranding } from '@/features/auth/hooks/usePreLoginBranding'
@@ -1,40 +1,59 @@
import { useEffect, useRef, memo } from 'react' import { useEffect, useRef, memo, type RefObject } from 'react'
import { cn } from '@/lib' import { useMeQuery } from '@/apis'
import { useChatStore } from '@/features/chat/stores/useChatStore' import { useChatStore } from '@/features/chat/stores/useChatStore'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore' import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
import type { ChatMessage as ChatMessageType } from '@/features/chat/types' import type { ChatMessage as ChatMessageType } from '@/features/chat/types'
import { renderEmphasis } from '@/features/chat/lib/emphasis' import { renderEmphasis } from '@/features/chat/lib/emphasis'
import { Indicator } from '@/features/chat/components/templates/Indicator' import { Indicator } from '@/features/chat/components/templates/Indicator'
import { Summary } from '@/features/chat/components/templates/Summary' import { Summary } from '@/features/chat/components/templates/Summary'
import { ExtraInfoForm } from '@/features/chat/components/templates/ExtraInfoForm'
import { BidSummary } from '@/features/chat/components/templates/BidSummary' import { BidSummary } from '@/features/chat/components/templates/BidSummary'
import { RejectRSP } from '@/features/chat/components/templates/RejectRSP' import { RejectRSP } from '@/features/chat/components/templates/RejectRSP'
import { RejectCM } from '@/features/chat/components/templates/RejectCM' import { RejectCM } from '@/features/chat/components/templates/RejectCM'
const AI_LABEL = '아이마켓코리아 (구매 MD)'
export function ChatMessage() { export function ChatMessage() {
const scrollRef = useRef<HTMLDivElement | null>(null)
return ( return (
<div className="flex-1 w-full min-h-0 pr-[16px]"> <div className="flex-1 w-full min-h-0">
{/* pt-[64px]: 첫 메시지를 우측 협상절차 카드 상단과 맞추되, 스크롤 시 여백도 함께 밀려 올라가도록 스크롤 컨테이너 안쪽에 둔다 */} {/* lg:pt-[64px]: 첫 메시지를 우측 협상절차 카드 상단과 맞추는 값 — 그 카드가 없는 lg 미만에선
<div className="chat-scroll h-full overflow-y-auto flex flex-col pt-[64px] pl-[140px] pr-[126px] max-[1350px]:pl-[80px] max-[1350px]:pr-[72px] max-[1180px]:pl-[48px] max-[1180px]:pr-[40px]"> 스텝바 바로 아래 여백으로만 남아 첫 메시지가 위로 안 붙으므로 뺀다.
<ChatList /> 스크롤 시 여백도 함께 밀려 올라가도록 스크롤 컨테이너 안쪽에 둔다 */}
<div
ref={scrollRef}
className="chat-scroll h-full overflow-y-auto flex flex-col pt-0 lg:pt-[64px] pb-6 px-4 sm:px-6 min-[1180px]:pl-[80px] min-[1180px]:pr-[72px] min-[1350px]:pl-[140px] min-[1350px]:pr-[126px]"
>
<ChatList scrollRef={scrollRef} />
</div> </div>
</div> </div>
) )
} }
function ChatList() { function ChatList({ scrollRef }: { scrollRef: RefObject<HTMLDivElement | null> }) {
const bottomRef = useRef<HTMLDivElement | null>(null) const isFirstRef = useRef(true)
const chats = useChatStore((s) => s.messages) const chats = useChatStore((s) => s.messages)
const isLoading = useChatStore((s) => s.isLoading) const isLoading = useChatStore((s) => s.isLoading)
// 메시지 추가/타이핑 표시 시 항상 맨 아래로 스크롤 // 메시지 추가/타이핑 표시 시 항상 맨 아래로 스크롤.
// 스크롤 컨테이너를 직접 내린다 — scrollIntoView 는 요약/부가정보 폼처럼 큰 블록이 뒤늦게
// 레이아웃되면 애니메이션 도중 목표 위치가 밀려 중간에 멈춘다.
// 진입 첫 렌더는 즉시(auto) — 히스토리를 복원하며 위에서부터 훑어 내려가는 연출을 막는다.
useEffect(() => { useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: 'smooth' }) const scroller = scrollRef.current
if (!scroller) return
const behavior: ScrollBehavior = isFirstRef.current ? 'auto' : 'smooth'
isFirstRef.current = false
const id = requestAnimationFrame(() => {
scroller.scrollTo({ top: scroller.scrollHeight, behavior })
})
return () => cancelAnimationFrame(id)
}, [chats, isLoading]) }, [chats, isLoading])
if (!chats || chats.length === 0) { if (!chats || chats.length === 0) {
return ( return (
<div className="flex items-center justify-center h-full"> <div className="flex items-center justify-center h-full">
<p className="body-1 text-neutral-70">채팅 내역이 없습니다.</p> <p className="text-sm text-neutral-60">채팅 내역이 없습니다.</p>
</div> </div>
) )
} }
@@ -42,22 +61,22 @@ function ChatList() {
return ( return (
<div className="flex flex-col w-full"> <div className="flex flex-col w-full">
{chats.map((message, index) => ( {chats.map((message, index) => (
<MessageItem key={message.chat_id || index} message={message} isFirst={index === 0} messages={chats} currentIndex={index} /> <MessageItem key={message.chat_id || index} message={message} messages={chats} currentIndex={index} />
))} ))}
{isLoading && <TypingBubble />} {isLoading && <TypingBubble />}
<div ref={bottomRef} />
</div> </div>
) )
} }
// agent 응답을 기다리는 동안(협상 중) 대화 흐름에 표시하는 타이핑 인디케이터. // agent 응답을 기다리는 동안(협상 중) 대화 흐름에 표시하는 타이핑 인디케이터(AI 말풍선 톤).
function TypingBubble() { function TypingBubble() {
return ( return (
<div className="mb-[56px] pt-[36px]" aria-label="협상 중" role="status"> <div className="mb-6 flex flex-col items-start gap-1.5" aria-label="협상 중" role="status">
<div className="inline-flex items-center gap-[6px]"> <span className="text-xs font-bold text-neutral-80">{AI_LABEL}</span>
<span className="size-[8px] rounded-full bg-neutral-50 animate-bounce [animation-delay:-0.3s]" /> <div className="inline-flex items-center gap-1.5 rounded-2xl rounded-tl-none border border-[#D2E6FF] bg-brand-light/70 px-4 py-3.5 shadow-sm">
<span className="size-[8px] rounded-full bg-neutral-50 animate-bounce [animation-delay:-0.15s]" /> <span className="size-2 rounded-full bg-brand-500 animate-bounce [animation-delay:-0.3s]" />
<span className="size-[8px] rounded-full bg-neutral-50 animate-bounce" /> <span className="size-2 rounded-full bg-brand-500 animate-bounce [animation-delay:-0.15s]" />
<span className="size-2 rounded-full bg-brand-500 animate-bounce" />
</div> </div>
</div> </div>
) )
@@ -65,50 +84,52 @@ function TypingBubble() {
const MessageItem = memo(function MessageItem({ const MessageItem = memo(function MessageItem({
message, message,
isFirst,
messages, messages,
currentIndex, currentIndex,
}: { }: {
message: ChatMessageType message: ChatMessageType
isFirst: boolean
messages: ChatMessageType[] messages: ChatMessageType[]
currentIndex: number currentIndex: number
}) { }) {
const isBot = message.sender === 'bot' const isBot = message.sender === 'bot'
// 직전이 reject 폼이면 사용자 답변은 숨기고 구분선만 표시 // 직전이 reject 폼이면 사용자 답변 말풍선은 숨긴다(폼 자체가 답변을 담고 있음)
if (!isBot && currentIndex > 0) { if (!isBot && currentIndex > 0) {
const prev = messages[currentIndex - 1] const prev = messages[currentIndex - 1]
if (prev?.bot_chat_type === 'rejectRSP' || prev?.bot_chat_type === 'rejectCM') { if (prev?.bot_chat_type === 'rejectRSP' || prev?.bot_chat_type === 'rejectCM') {
return ( return null
<>
<div className="text-right mb-[56px]" />
<div className="flex w-full bg-neutral-30 h-[1px] mb-[20px]" />
</>
)
} }
} }
return <div>{isBot ? <BotMessage message={message} isFirst={isFirst} /> : <UserMessage text={message.script || ''} />}</div> return isBot ? <BotMessage message={message} /> : <UserMessage text={message.script || ''} />
}) })
const BotMessage = memo(function BotMessage({ message, isFirst }: { message: ChatMessageType; isFirst?: boolean }) { const BotMessage = memo(function BotMessage({ message }: { message: ChatMessageType }) {
// 인디케이터는 이번 방문에서 '협상중'이었던 세션에서만 표시. // 인디케이터는 이번 방문에서 '협상중'이었던 세션에서만 표시.
// 진행 화면에서 실시간으로 완료되면 sticky 플래그로 계속 노출하고,
// 완료/거부 세션에 결과 열람 목적으로 재진입한 경우엔 값이 와도 숨긴다.
const showIndicator = useChatInitStore((s) => s.wasInProgress) const showIndicator = useChatInitStore((s) => s.wasInProgress)
const hasScript = Boolean(message.script && message.script.trim())
return ( return (
<div className="mb-[56px]"> <div className="mb-5 animate-fade-in">
<div className={cn('flex flex-col', !isFirst && 'pt-[36px]')}> <div className="flex flex-col items-start gap-1.5">
{/* 봇 스크립트의 `**굵게**` 경량 마크업 해석 (표현 규칙은 프론트 소유 — emphasis.tsx) */} <span className="text-xs font-bold text-neutral-80">{AI_LABEL}</span>
<div className="body-1-read-r">{renderEmphasis(message.script || '')}</div> {hasScript && (
<div className="max-w-[80%] rounded-2xl rounded-tl-none border border-[#D2E6FF] bg-brand-light/70 p-4 text-sm leading-relaxed text-neutral-90 shadow-sm break-keep">
{renderEmphasis(message.script || '')}
</div>
)}
</div> </div>
<div className="flex flex-col gap-4 w-full mt-[32px]"> <div className="flex flex-col gap-4 w-full mt-4">
{showIndicator && message.bot_chat_type === 'indicator' && message.indicator_value != null && ( {showIndicator && message.bot_chat_type === 'indicator' && message.indicator_value != null && (
<Indicator number={message.indicator_value} /> <Indicator number={message.indicator_value} />
)} )}
{message.bot_chat_type === 'summaryRSP' && message.summary && <Summary data={message.summary} />} {message.bot_chat_type === 'summaryRSP' && message.summary && (
<>
<Summary data={message.summary} />
<ExtraInfoForm />
</>
)}
{message.bot_chat_type === 'summaryCM' && message.summary && ( {message.bot_chat_type === 'summaryCM' && message.summary && (
<BidSummary <BidSummary
itemName={message.summary.item_name} itemName={message.summary.item_name}
@@ -126,14 +147,14 @@ const BotMessage = memo(function BotMessage({ message, isFirst }: { message: Cha
}) })
const UserMessage = memo(function UserMessage({ text }: { text: string }) { const UserMessage = memo(function UserMessage({ text }: { text: string }) {
const { data: user } = useMeQuery()
const label = `${user?.supplierName ?? '공급사'} (나)`
return ( return (
<> <div className="mb-5 flex flex-col items-end gap-1.5 animate-fade-in">
<div className="text-right mb-[56px]"> <span className="text-xs font-bold text-neutral-80">{label}</span>
<div className="inline-block max-w-[87%] bg-neutral-40 text-neutral-90 text-lg leading-[150%] tracking-[-0.18px] px-[20px] py-[10px] rounded-full break-keep"> <div className="max-w-[80%] rounded-2xl rounded-tr-none border border-border bg-white p-4 text-sm leading-relaxed text-neutral-90 shadow-sm break-keep">
{text} {text}
</div>
</div> </div>
<div className="flex w-full bg-neutral-30 h-[1px] mb-[20px]" /> </div>
</>
) )
}) })
@@ -1,13 +1,19 @@
import { useChatStore } from '@/features/chat/stores/useChatStore' import { useChatStore } from '@/features/chat/stores/useChatStore'
import { ChatMessage } from '@/features/chat/components/ChatMessage' import { ChatMessage } from '@/features/chat/components/ChatMessage'
import { UserButton } from '@/features/chat/components/UserButton' import { UserButton } from '@/features/chat/components/UserButton'
import { MobileStepBar } from '@/features/chat/components/MobileStepBar'
export function ChatSection() { export function ChatSection() {
const { userButtonConfig } = useChatStore() const { userButtonConfig } = useChatStore()
return ( return (
<div className="flex flex-1 flex-col w-full h-full bg-surface rounded-bl-[8px]"> <div className="flex flex-1 flex-col w-full h-full min-h-0 bg-surface">
<MobileStepBar />
<ChatMessage /> <ChatMessage />
<UserButton {...userButtonConfig} /> {/* 하단 액션 덱 */}
{/* safe-b: 홈 인디케이터에 입력 버튼이 가리지 않도록 하단 안전영역 확보 */}
<div className="shrink-0 safe-b border-t border-border bg-white shadow-[0_-4px_20px_rgba(0,0,0,0.03)]">
<UserButton {...userButtonConfig} />
</div>
</div> </div>
) )
} }
@@ -8,34 +8,33 @@ export function ItemImage() {
const [isOpen, setIsOpen] = useState(false) const [isOpen, setIsOpen] = useState(false)
return ( return (
<div className="flex flex-col w-full items-center justify-center pt-16 pr-8 pb-8 pl-8"> <div className="px-5 pt-5 pb-3">
<button <button
type="button" type="button"
onClick={() => setIsOpen(true)} onClick={() => setIsOpen(true)}
aria-label="이미지 크게 보기" aria-label="이미지 크게 보기"
className="relative cursor-pointer group" className="group relative block aspect-square w-full overflow-hidden rounded-2xl border border-border bg-neutral-10 shadow-inner"
> >
<Thumb src={item_image} /> {item_image ? (
<div className="absolute inset-0 flex items-center justify-center rounded-[16px] bg-neutral-40 opacity-0 transition-opacity duration-300 group-hover:opacity-90"> <img
<span className="text-neutral-00 text-base font-medium">이미지 크게 보기</span> src={item_image}
</div> alt="상품 이미지"
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
/>
) : (
<div className="flex h-full w-full items-center justify-center text-neutral-40">
<ImageIcon size={40} strokeWidth={1.5} />
</div>
)}
<span className="absolute left-2 top-2 rounded-md bg-neutral-90/65 px-2 py-0.5 text-[10px] font-bold text-white backdrop-blur-sm">
상세 품목
</span>
</button> </button>
{isOpen && <ImageModal src={item_image} onClose={() => setIsOpen(false)} />} {isOpen && <ImageModal src={item_image} onClose={() => setIsOpen(false)} />}
</div> </div>
) )
} }
function Thumb({ src }: { src: string }) {
if (src) {
return <img src={src} alt="상품 이미지" className="rounded-[16px] w-[220px] h-[220px] max-[1180px]:w-[200px] max-[1180px]:h-[200px] object-cover" />
}
return (
<div className="flex w-[220px] h-[220px] max-[1180px]:w-[200px] max-[1180px]:h-[200px] items-center justify-center rounded-[16px] bg-neutral-20 text-neutral-60">
<ImageIcon size={48} strokeWidth={1.5} />
</div>
)
}
function ImageModal({ src, onClose }: { src: string; onClose: () => void }) { function ImageModal({ src, onClose }: { src: string; onClose: () => void }) {
useEffect(() => { useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose() const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
@@ -53,9 +52,9 @@ function ImageModal({ src, onClose }: { src: string; onClose: () => void }) {
> >
<div className="relative" onClick={(e) => e.stopPropagation()}> <div className="relative" onClick={(e) => e.stopPropagation()}>
{src ? ( {src ? (
<img src={src} alt="상품 이미지" className="rounded-[16px] max-w-[42rem] max-h-[90vh] object-contain" /> <img src={src} alt="상품 이미지" className="max-h-[90vh] max-w-[42rem] rounded-2xl object-contain" />
) : ( ) : (
<div className="flex w-[60vmin] h-[60vmin] max-w-[42rem] max-h-[90vh] items-center justify-center rounded-[16px] bg-neutral-20 text-neutral-60"> <div className="flex h-[60vmin] max-h-[90vh] w-[60vmin] max-w-[42rem] items-center justify-center rounded-2xl bg-neutral-20 text-neutral-50">
<ImageIcon size={96} strokeWidth={1.25} /> <ImageIcon size={96} strokeWidth={1.25} />
</div> </div>
)} )}
@@ -63,9 +62,9 @@ function ImageModal({ src, onClose }: { src: string; onClose: () => void }) {
type="button" type="button"
onClick={onClose} onClick={onClose}
aria-label="닫기" aria-label="닫기"
className="absolute top-4 right-4 flex items-center justify-center w-9 h-9 rounded-full bg-white border border-neutral-30 text-neutral-80 cursor-pointer hover:bg-neutral-10 transition-colors" className="absolute right-3 top-3 flex size-9 items-center justify-center rounded-full border border-border bg-white text-neutral-80 transition-colors hover:bg-neutral-10"
> >
<X size={20} /> <X size={18} />
</button> </button>
</div> </div>
</div>, </div>,
@@ -1,6 +1,5 @@
import { useState, useCallback, useRef, useEffect } from 'react' import { useState, useCallback, useRef, useEffect } from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { cn } from '@/lib'
import { ItemImage } from '@/features/chat/components/ItemImage' import { ItemImage } from '@/features/chat/components/ItemImage'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore' import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
import { formatLeadTime } from '@/features/chat/lib/format' import { formatLeadTime } from '@/features/chat/lib/format'
@@ -74,19 +73,18 @@ function ItemInfo() {
const priceText = isNewItem ? '신규' : `${formatPrice(item_price)}원` const priceText = isNewItem ? '신규' : `${formatPrice(item_price)}원`
const formattedPrice = `${priceText}(${item_vat_yn || 'VAT별도'})` const formattedPrice = `${priceText}(${item_vat_yn || 'VAT별도'})`
const renderRow = (title: string, data: string, important = false) => { const renderRow = (title: string, data: string) => {
const textClass = important ? 'title-3 text-neutral-90' : 'body-3 text-neutral-70'
const displayData = data || '-' const displayData = data || '-'
return ( return (
<div className="flex items-start self-stretch gap-1 min-w-0"> <div className="flex items-start justify-between gap-3 self-stretch border-b border-border/60 py-2 last:border-0 min-w-0">
<div className={cn(textClass, 'w-[100px]')}>{title}</div> <span className="shrink-0 text-[13px] text-neutral-60">{title}</span>
<div <span
className={cn(textClass, 'flex-1 min-w-0 break-words break-keep cursor-default')} className="min-w-0 flex-1 break-words break-keep text-right text-[13px] font-semibold text-neutral-90 cursor-default"
onMouseEnter={(e) => displayData !== '-' && showTooltip(e, displayData)} onMouseEnter={(e) => displayData !== '-' && showTooltip(e, displayData)}
onMouseLeave={hideTooltip} onMouseLeave={hideTooltip}
> >
{displayData} {displayData}
</div> </span>
</div> </div>
) )
} }
@@ -94,31 +92,35 @@ function ItemInfo() {
return ( return (
<div className="flex flex-col w-full flex-1 overflow-hidden min-h-0"> <div className="flex flex-col w-full flex-1 overflow-hidden min-h-0">
<div <div
className="text-center headline-3 text-neutral-90 mb-4 truncate px-8 flex-shrink-0 cursor-default" className="mb-3 flex-shrink-0 truncate px-6 text-left text-sm font-bold text-neutral-90 cursor-default"
onMouseEnter={(e) => item_name && showTooltip(e, item_name)} onMouseEnter={(e) => item_name && showTooltip(e, item_name)}
onMouseLeave={hideTooltip} onMouseLeave={hideTooltip}
> >
{item_name} {item_name}
</div> </div>
<div className="flex flex-1 items-start self-stretch mr-2 overflow-y-auto overflow-x-hidden pr-6 pl-8 min-h-0"> <div className="mb-2 flex-shrink-0 border-b border-border px-6 pb-2">
<span className="text-[11px] font-extrabold tracking-wider text-neutral-50">품목 정보</span>
</div>
<div className="flex flex-1 items-start self-stretch overflow-y-auto overflow-x-hidden px-6 min-h-0">
<div className="flex flex-col items-start self-stretch flex-1 gap-2 min-w-0"> <div className="flex flex-col items-start self-stretch flex-1 gap-2 min-w-0">
{renderRow('상품코드', item_code, true)} {renderRow('상품코드', item_code)}
{renderRow('단가', formattedPrice, true)} {renderRow('단가', formattedPrice)}
{renderRow('모델명', item_model_name, true)} {renderRow('모델명', item_model_name)}
{renderRow('제조사', item_maker_name)} {renderRow('제조사', item_maker_name)}
{renderRow('최소주문수량', item_min_order_quantity)} {renderRow('최소주문수량', item_min_order_quantity)}
{renderRow('리드타임', formatLeadTime(item_lead_time))} {renderRow('리드타임', formatLeadTime(item_lead_time))}
<div className="flex items-start self-stretch gap-1 flex-[1_0]"> <div className="flex items-start justify-between gap-3 self-stretch py-2">
<div className="body-3 text-neutral-70 w-[100px]">규격</div> <span className="shrink-0 text-sm text-neutral-60">규격</span>
<div <span
className="body-3 text-neutral-70 self-stretch w-0 flex-[1_0] overflow-hidden whitespace-normal break-words break-keep cursor-default" className="min-w-0 flex-1 overflow-hidden whitespace-normal break-words break-keep text-right text-[13px] font-semibold text-neutral-90 cursor-default"
onMouseEnter={(e) => item_spec && showTooltip(e, item_spec, true)} onMouseEnter={(e) => item_spec && showTooltip(e, item_spec, true)}
onMouseLeave={hideTooltip} onMouseLeave={hideTooltip}
> >
{item_spec || '-'} {item_spec || '-'}
</div> </span>
</div> </div>
</div> </div>
</div> </div>
@@ -0,0 +1,50 @@
import { type ReactNode, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { cn } from '@/lib'
interface MobileDrawerProps {
open: boolean
onClose: () => void
side?: 'left' | 'right'
title: string
children: ReactNode
}
// 모바일 전용 슬라이드 드로어(lg 미만). 데스크톱에선 절대 노출되지 않도록 lg:hidden 을 강제한다.
export function MobileDrawer({ open, onClose, side = 'left', title, children }: MobileDrawerProps) {
useEffect(() => {
if (!open) return
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [open, onClose])
if (!open) return null
return createPortal(
<div className="fixed inset-0 z-[60] lg:hidden">
<div className="absolute inset-0 bg-black/50 animate-fade-in" onClick={onClose} />
<div
className={cn(
'absolute top-0 bottom-0 flex w-[88%] max-w-[360px] flex-col bg-white shadow-xl',
side === 'left' ? 'left-0' : 'right-0',
)}
>
<div className="flex h-14 box-content safe-t shrink-0 items-center justify-between border-b border-border px-5">
<span className="text-base font-bold text-neutral-90">{title}</span>
<button
type="button"
onClick={onClose}
aria-label="닫기"
className="flex size-8 items-center justify-center rounded-full text-neutral-60 hover:bg-neutral-10"
>
<X className="size-4" />
</button>
</div>
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto safe-b">{children}</div>
</div>
</div>,
document.body,
)
}
@@ -0,0 +1,46 @@
import { Check } from 'lucide-react'
import { cn } from '@/lib'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { STEPS } from '@/features/chat/components/menu/NegoStep'
// 모바일 전용: 협상절차를 채팅 상단에 가로 스텝바로 항상 표시한다. (데스크톱은 우측 패널 사용)
export function MobileStepBar() {
const chats = useChatStore((s) => s.messages)
const currentStep = chats[chats.length - 1]?.display_step || STEPS[0].name
const idx = Math.max(
0,
STEPS.findIndex((s) => s.name === currentStep),
)
return (
<div className="shrink-0 border-b border-border bg-white px-4 py-2.5 lg:hidden">
<div className="flex items-center">
{STEPS.map((step, i) => {
const done = i < idx
const current = i === idx
return (
<div key={step.name} className={cn('flex items-center', i < STEPS.length - 1 && 'flex-1')}>
<div
className={cn(
'flex size-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold transition-colors',
done && 'bg-success text-white',
current && 'bg-brand-600 text-white ring-4 ring-brand-light',
!done && !current && 'border border-border bg-white text-neutral-50',
)}
>
{done ? <Check className="size-3" strokeWidth={3} /> : i + 1}
</div>
{i < STEPS.length - 1 && (
<div className={cn('mx-1 h-0.5 flex-1 rounded-full', i < idx ? 'bg-success' : 'bg-neutral-20')} />
)}
</div>
)
})}
</div>
<p className="mt-1.5 truncate text-[11px] font-bold text-brand-600">
{idx + 1}. {STEPS[idx].name}
<span className="ml-1 font-normal text-neutral-50">{STEPS[idx].desc}</span>
</p>
</div>
)
}
@@ -1,8 +1,10 @@
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import { Clock } from 'lucide-react'
import { cn } from '@/lib'
import { getTimeRemaining } from '@/features/chat/lib/remainingTime' import { getTimeRemaining } from '@/features/chat/lib/remainingTime'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore' import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
// 헤더의 협상 잔여 시간. 1초마다 tick 을 올려 렌더 중 남은 시간을 다시 계산한다. // 헤더의 협상 잔여 시간 칩. 1초마다 tick 을 올려 렌더 중 남은 시간을 다시 계산한다.
export function RemainingTime() { export function RemainingTime() {
const { quotation_end_time } = useChatInitStore() const { quotation_end_time } = useChatInitStore()
const [, setTick] = useState(0) const [, setTick] = useState(0)
@@ -13,6 +15,28 @@ export function RemainingTime() {
}, []) }, [])
const remaining = quotation_end_time ? getTimeRemaining(quotation_end_time) : '-' const remaining = quotation_end_time ? getTimeRemaining(quotation_end_time) : '-'
const ended = remaining === '종료되었습니다.' || remaining === '-'
return <span className="title-1">협상 잔여 시간 : {remaining}</span> return (
<span
className={cn(
// min-w-0 + truncate: 헤더가 좁아도 잘려나가지 않고 말줄임으로 접힌다.
'inline-flex min-w-0 shrink items-center gap-1.5 rounded-full px-3 py-1 text-xs font-bold tabular-nums',
ended ? 'bg-neutral-20 text-neutral-60' : 'bg-brand-light text-brand-600',
)}
>
<Clock className="size-3.5 shrink-0" />
<span className="truncate">
{ended ? (
// 종료 시엔 어느 폭에서도 긴 문장('종료되었습니다.')을 쓰지 않는다 — 헤더에서 잘리던 원인.
'마감 종료'
) : (
<>
<span className="hidden sm:inline">협상 마감 </span>
{remaining}
</>
)}
</span>
</span>
)
} }
@@ -1,5 +1,4 @@
import { useNavigate } from 'react-router' import { useNavigate } from 'react-router'
import { List } from 'lucide-react'
import { cn } from '@/lib' import { cn } from '@/lib'
import { useChatStore } from '@/features/chat/stores/useChatStore' import { useChatStore } from '@/features/chat/stores/useChatStore'
import { Percent, Price } from '@/features/chat/components/userInputs' import { Percent, Price } from '@/features/chat/components/userInputs'
@@ -8,37 +7,28 @@ import type { UserButtonConfig } from '@/features/chat/types'
// max-[1180px]: 채팅 폭이 좁아지면 버튼 패딩·최소폭 축소, 상품목록은 아이콘만 남긴다 // max-[1180px]: 채팅 폭이 좁아지면 버튼 패딩·최소폭 축소, 상품목록은 아이콘만 남긴다
const style = { const style = {
goToList:
'flex w-[159px] max-[1180px]:w-[48px] h-[48px] bg-neutral-40 hover:brightness-[0.97] rounded-[999px] items-center justify-center title-2 text-neutral-80 cursor-pointer gap-2 max-[1180px]:gap-0 transition-all ease-out hover:scale-[1.01]',
black: black:
'flex min-w-[120px] px-[32px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[48px] bg-primary hover:brightness-[0.97] rounded-[999px] items-center justify-center title-2 text-primary-foreground cursor-pointer whitespace-nowrap transition-all duration-200 ease-out hover:scale-[1.01]', 'flex min-w-[120px] px-[28px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[46px] bg-brand-600 hover:bg-brand-700 rounded-xl items-center justify-center text-sm font-bold text-white shadow-sm cursor-pointer whitespace-nowrap transition-all duration-200 ease-out active:scale-[0.98]',
gray: 'flex min-w-[120px] px-[32px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[48px] bg-neutral-60 rounded-[999px] items-center justify-center title-2 text-neutral-00 cursor-pointer whitespace-nowrap transition-all ease-out hover:scale-[1.01]', gray: 'flex min-w-[120px] px-[28px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[46px] bg-neutral-60 hover:brightness-[0.97] rounded-xl items-center justify-center text-sm font-bold text-white cursor-pointer whitespace-nowrap transition-all ease-out active:scale-[0.98]',
white: white:
'flex min-w-[120px] px-[32px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[48px] bg-neutral-00 rounded-[999px] items-center justify-center title-2 text-neutral-80 border border-neutral-80 cursor-pointer whitespace-nowrap transition-all ease-out hover:scale-[1.01]', 'flex min-w-[120px] px-[28px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[46px] bg-white hover:bg-neutral-10 rounded-xl items-center justify-center text-sm font-bold text-neutral-80 border border-border cursor-pointer whitespace-nowrap transition-all ease-out active:scale-[0.98]',
} }
export function UserButton({ type, text, textList, priceErrorMessage }: UserButtonConfig) { export function UserButton({ type, text, textList, priceErrorMessage }: UserButtonConfig) {
if (type === '') return null if (type === '') return null
return ( return (
// pr-[16px]: 채팅 스크롤 영역(ChatMessage 바깥 pr-[16px])과 오른쪽 끝 정렬 <div className="flex w-full justify-center overflow-x-auto px-6 py-4 max-[1180px]:px-4">
<div className="flex w-full pb-[52px] pr-[16px]"> <div className="flex justify-center">
<div className="grid grid-cols-[1fr_auto_1fr] items-center w-full"> {type === 'one-black' && <OneBlack text={text || '확인'} />}
<div /> {type === 'one-gray' && <OneGray text={text || '확인'} />}
<div className="flex justify-center"> {type === 'black-white' && <BlackWhite textList={[textList?.[0] || '예', textList?.[1] || '아니오']} />}
{type === 'one-black' && <OneBlack text={text || '확인'} />} {type === 'percent' && <Percent />}
{type === 'one-gray' && <OneGray text={text || '확인'} />} {type === 'three-black' && (
{type === 'black-white' && <BlackWhite textList={[textList?.[0] || '예', textList?.[1] || '아니오']} />} <ThreeBlack textList={[textList?.[0] || '협력사배송', textList?.[1] || '지정택배배송', textList?.[2] || '픽업배송']} />
{type === 'percent' && <Percent />} )}
{type === 'three-black' && ( {type === 'price' && <Price priceErrorMessage={priceErrorMessage} />}
<ThreeBlack textList={[textList?.[0] || '협력사배송', textList?.[1] || '지정택배배송', textList?.[2] || '픽업배송']} /> {type === 'loading' && <LoadingDots />}
)}
{type === 'price' && <Price priceErrorMessage={priceErrorMessage} />}
{type === 'loading' && <LoadingDots />}
</div>
<div className="flex justify-end">
<GoToList />
</div>
</div> </div>
</div> </div>
) )
@@ -57,16 +47,6 @@ function LoadingDots() {
) )
} }
function GoToList() {
const navigate = useNavigate()
return (
<button className={style.goToList} onClick={() => navigate('/list')} aria-label="상품 목록으로 이동" title="상품 목록">
<List size={24} className="shrink-0" />
<span className="max-[1180px]:hidden">상품 목록</span>
</button>
)
}
function OneBlack({ text }: { text: string }) { function OneBlack({ text }: { text: string }) {
const navigate = useNavigate() const navigate = useNavigate()
const sendMessage = useChatStore((s) => s.sendMessage) const sendMessage = useChatStore((s) => s.sendMessage)
@@ -1,28 +1,14 @@
import { useState } from 'react' // 헬프데스크 — 연락처. (안내 팝업 진입은 상단 '유의사항 및 이용방법' 섹션으로 일원화)
import { interactive, cn } from '@/lib'
import { ServiceGuidePopup } from '@/features/chat/components/popup/ServiceGuidePopup'
// 헬프데스크 — 이용 가이드 버튼 클릭 시 안내 팝업을 연다.
export function Contact() { export function Contact() {
const [isOpen, setIsOpen] = useState(false)
return ( return (
<div className="flex flex-col w-full pl-[24px] pb-[24px]"> <section className="w-full pt-4">
<div className="flex flex-col w-full gap-2"> <div className="border-b border-border pb-2">
<div className="title-5 text-neutral-80">헬프 데스크</div> <span className="text-[11px] font-bold tracking-wide text-neutral-60">헬프데스크</span>
<button
type="button"
onClick={() => setIsOpen(true)}
className={cn('body-5 text-neutral-80 bg-neutral-40 rounded-[8px] px-[12px] py-[6px] w-fit', interactive)}
>
이용 가이드
</button>
<div className="flex flex-col gap-1">
<div className="body-5 text-neutral-60">010-0000-0000</div>
<div className="body-5 text-neutral-60">o2odev@o2o.kr</div>
</div>
</div> </div>
{isOpen && <ServiceGuidePopup onClose={() => setIsOpen(false)} />} <div className="flex flex-col gap-1 pt-3 text-sm text-neutral-60">
</div> <span>010-0000-0000</span>
<span>o2odev@o2o.kr</span>
</div>
</section>
) )
} }
@@ -1,6 +1,5 @@
import { useState } from 'react' import { useState } from 'react'
import { ChevronRight } from 'lucide-react' import { ChevronRight } from 'lucide-react'
import { interactive, cn } from '@/lib'
import { ServiceGuidePopup } from '@/features/chat/components/popup/ServiceGuidePopup' import { ServiceGuidePopup } from '@/features/chat/components/popup/ServiceGuidePopup'
// 유의사항 및 이용방법 — 클릭 시 안내 팝업을 연다. // 유의사항 및 이용방법 — 클릭 시 안내 팝업을 연다.
@@ -12,13 +11,12 @@ export function Guide() {
<button <button
type="button" type="button"
onClick={() => setIsOpen(true)} onClick={() => setIsOpen(true)}
className={cn( className="flex w-full items-center justify-between border-b border-border pb-2 text-left transition-colors hover:border-neutral-40"
'flex w-full bg-white rounded-[28px] py-[20px] pl-[24px] pr-[16px] justify-between items-center text-left',
interactive,
)}
> >
<span className="menu-title text-neutral-80 break-keep">유의사항 및 이용방법</span> <span className="text-[11px] font-bold tracking-wide text-neutral-60 break-keep">
<ChevronRight size={20} className="text-neutral-70" /> 유의사항 및 이용방법
</span>
<ChevronRight size={16} className="text-neutral-50" />
</button> </button>
{isOpen && <ServiceGuidePopup onClose={() => setIsOpen(false)} />} {isOpen && <ServiceGuidePopup onClose={() => setIsOpen(false)} />}
</> </>
@@ -22,39 +22,33 @@ export function MDInformation({ isOpen, setIsOpen }: Props) {
if (memoArray.length === 0) return null if (memoArray.length === 0) return null
return ( return (
<div className="flex flex-col w-full min-w-[200px]"> <section className="w-full">
<div className="bg-white rounded-[28px]"> <button
<div className={cn('flex items-center w-full h-[4.75rem] px-4 pl-6', isOpen ? 'pt-6 pb-3' : 'py-6')}> type="button"
<div className="flex items-center flex-1 justify-between"> aria-expanded={isOpen}
<div className="menu-title text-neutral-80">MD 안내사항</div> onClick={() => setIsOpen(!isOpen)}
<button className="flex w-full items-center justify-between border-b border-border pb-2"
type="button" >
aria-expanded={isOpen} <span className="text-[11px] font-bold tracking-wide text-neutral-60">MD 안내사항</span>
onClick={() => setIsOpen(!isOpen)} <ChevronDown
className="flex items-center justify-center w-10 h-10 cursor-pointer text-neutral-70" size={16}
> className={cn('text-neutral-50 transition-transform duration-300', !isOpen && '-rotate-90')}
<ChevronDown size={20} className={cn('transition-transform duration-300', !isOpen && 'rotate-180')} /> />
</button> </button>
</div>
</div>
<div {isOpen && (
className={cn( <div className="max-h-[220px] animate-fade-in overflow-y-auto pt-3">
'flex flex-col items-start gap-[19px] w-full px-6 overflow-hidden transition-all duration-300 ease-in-out', <div className="flex flex-col gap-2 break-keep">
isOpen ? 'max-h-[200px] pb-8 opacity-100' : 'max-h-0 pb-0 opacity-0',
)}
>
<div className={cn('flex flex-col gap-2 items-start self-stretch max-h-[200px] break-keep', isOpen ? 'overflow-y-auto' : 'overflow-hidden')}>
{memoArray.map((item, i) => ( {memoArray.map((item, i) => (
<div key={i} className="flex items-start gap-2 body-3 text-neutral-70"> <div key={i} className="flex items-start gap-2 text-sm text-neutral-70">
<span className="flex-shrink-0">•</span> <span className="shrink-0 text-neutral-50">•</span>
<div className="flex-1 whitespace-pre-wrap">{linkText(item)}</div> <div className="flex-1 whitespace-pre-wrap">{linkText(item)}</div>
</div> </div>
))} ))}
</div> </div>
</div> </div>
</div> )}
</div> </section>
) )
} }
@@ -63,7 +57,7 @@ function linkText(text: string) {
const isUrl = (s: string) => /^https?:\/\/[^\s]+$/.test(s) const isUrl = (s: string) => /^https?:\/\/[^\s]+$/.test(s)
const parts = text.split(urlRegex) const parts = text.split(urlRegex)
return ( return (
<div className="body-3 text-neutral-70"> <div className="text-sm text-neutral-70">
{parts.map((part, i) => {parts.map((part, i) =>
isUrl(part) ? ( isUrl(part) ? (
<a <a
@@ -71,7 +65,7 @@ function linkText(text: string) {
href={part} href={part}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="block text-info underline cursor-pointer hover:brightness-95 transition-all" className="block text-brand-600 underline transition-all hover:brightness-95"
> >
상품 사이트로 이동 상품 사이트로 이동
</a> </a>
@@ -1,16 +1,24 @@
import { useState } from 'react' import { useState } from 'react'
import { cn } from '@/lib'
import { MDInformation } from '@/features/chat/components/menu/MDInformation' import { MDInformation } from '@/features/chat/components/menu/MDInformation'
import { NegoStep } from '@/features/chat/components/menu/NegoStep' import { NegoStep } from '@/features/chat/components/menu/NegoStep'
import { Guide } from '@/features/chat/components/menu/Guide' import { Guide } from '@/features/chat/components/menu/Guide'
import { Contact } from '@/features/chat/components/menu/Contact' import { Contact } from '@/features/chat/components/menu/Contact'
export function MenuSection() { // rail = 데스크톱 우측 고정 패널(lg+), drawer = 모바일 드로어 내부.
// 보고서식: 박스 카드가 아니라 하나의 흰 패널 안에 납작한 섹션들을 쌓는다.
export function MenuSection({ variant = 'rail' }: { variant?: 'rail' | 'drawer' }) {
const [isMDOpen, setIsMDOpen] = useState(true) const [isMDOpen, setIsMDOpen] = useState(true)
const [isStepOpen, setIsStepOpen] = useState(true) const [isStepOpen, setIsStepOpen] = useState(true)
const wrap =
variant === 'rail'
? 'hidden lg:flex flex-col w-[300px] max-[1350px]:w-[280px] max-[1180px]:w-[260px] h-full overflow-y-auto bg-white border-l border-border px-5 pt-6 pb-4'
: 'flex flex-col w-full p-5'
return ( return (
<div className="flex flex-col w-[360px] max-[1350px]:w-[320px] max-[1180px]:w-[280px] h-full pt-[64px] pr-[24px]"> <div className={cn(wrap)}>
<div className="flex flex-col flex-1 gap-[28px]"> <div className="flex flex-1 flex-col gap-6">
<MDInformation isOpen={isMDOpen} setIsOpen={setIsMDOpen} /> <MDInformation isOpen={isMDOpen} setIsOpen={setIsMDOpen} />
<NegoStep isOpen={isStepOpen} setIsOpen={setIsStepOpen} /> <NegoStep isOpen={isStepOpen} setIsOpen={setIsStepOpen} />
<Guide /> <Guide />
@@ -1,4 +1,4 @@
import { ChevronDown } from 'lucide-react' import { Check, ChevronDown } from 'lucide-react'
import { cn } from '@/lib' import { cn } from '@/lib'
import { useChatStore } from '@/features/chat/stores/useChatStore' import { useChatStore } from '@/features/chat/stores/useChatStore'
@@ -7,46 +7,78 @@ interface Props {
setIsOpen: (isOpen: boolean) => void setIsOpen: (isOpen: boolean) => void
} }
const STEPS = ['서비스안내', '담당자확인', '협상품목안내', '가격협상', '협상종료'] export const STEPS = [
{ name: '서비스안내', desc: '협상 방식과 유의사항을 확인합니다.' },
{ name: '담당자확인', desc: '협상 담당자 본인 여부를 확인합니다.' },
{ name: '협상품목안내', desc: '대상 품목과 기준 단가를 확인합니다.' },
{ name: '가격협상', desc: '공급 단가를 제안하고 조율합니다.' },
{ name: '협상종료', desc: '최종 합의 후 결과를 확인합니다.' },
]
export function NegoStep({ isOpen, setIsOpen }: Props) { export function NegoStep({ isOpen, setIsOpen }: Props) {
const chats = useChatStore((s) => s.messages) const chats = useChatStore((s) => s.messages)
const currentStep = chats[chats.length - 1]?.display_step || '서비스안내' const currentStep = chats[chats.length - 1]?.display_step || '서비스안내'
const currentIndex = Math.max(
0,
STEPS.findIndex((s) => s.name === currentStep),
)
return ( return (
<div className="flex flex-col w-full min-w-[200px]"> <section className="w-full">
<div className="bg-white rounded-[28px]"> <button
<div className={cn('flex items-center w-full h-[4.75rem] px-4 pl-6', isOpen ? 'pt-6 pb-3' : 'py-6')}> type="button"
<div className="flex items-center flex-1 justify-between"> aria-expanded={isOpen}
<div className="menu-title text-neutral-80">협상절차</div> onClick={() => setIsOpen(!isOpen)}
<button className="flex w-full items-center justify-between border-b border-border pb-2"
type="button" >
aria-expanded={isOpen} <span className="text-[11px] font-bold tracking-wide text-neutral-60">협상절차</span>
onClick={() => setIsOpen(!isOpen)} <ChevronDown
className="flex items-center justify-center w-10 h-10 cursor-pointer text-neutral-70" size={16}
> className={cn('text-neutral-50 transition-transform duration-300', !isOpen && '-rotate-90')}
<ChevronDown size={20} className={cn('transition-transform duration-300', !isOpen && 'rotate-180')} /> />
</button> </button>
</div>
</div>
<div {isOpen && (
className={cn( <div className="animate-fade-in pt-4">
'flex flex-col items-start gap-[19px] w-full px-6 overflow-hidden transition-all duration-300 ease-in-out', <div className="relative">
isOpen ? 'max-h-[200px] pb-8 opacity-100' : 'max-h-0 pb-0 opacity-0', {/* 세로 레일 */}
)} <span className="absolute left-[9px] top-3 bottom-3 w-0.5 bg-neutral-20" />
> {STEPS.map((step, i) => {
<div className="flex flex-col gap-2 items-start self-stretch break-keep"> const done = i < currentIndex
{STEPS.map((step, i) => ( const current = i === currentIndex
<div key={step} className="flex items-start gap-2"> return (
<div className={cn('body-3 text-neutral-80', currentStep === step && 'font-bold')}> <div key={step.name} className="relative flex items-start gap-3 py-1.5">
{i + 1}. {step} <div
className={cn(
'z-10 mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold transition-all',
done && 'bg-success text-white',
current && 'scale-110 bg-brand-600 text-white ring-4 ring-brand-light',
!done && !current && 'border border-border bg-white text-neutral-50',
)}
>
{done ? <Check className="size-3" strokeWidth={3} /> : i + 1}
</div>
<div className="min-w-0">
<p
className={cn(
'text-xs leading-tight',
current && 'font-extrabold text-brand-600',
done && 'font-semibold text-success',
!done && !current && 'font-medium text-neutral-80',
)}
>
{step.name}
</p>
<p className={cn('mt-0.5 text-[10px] leading-snug', current ? 'text-brand-600/80' : 'text-neutral-50')}>
{step.desc}
</p>
</div>
</div> </div>
</div> )
))} })}
</div> </div>
</div> </div>
</div> )}
</div> </section>
) )
} }
@@ -3,14 +3,13 @@ import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
// 협상 유의사항 및 서비스 이용 방법 안내 — 팝업 2종(자동 안내/메뉴 가이드)이 공유하는 본문. // 협상 유의사항 및 서비스 이용 방법 안내 — 팝업 2종(자동 안내/메뉴 가이드)이 공유하는 본문.
// VAT/배송비 문구는 채팅 init 메타(useChatInitStore)를 읽어 상품별로 동적 표시한다. // VAT/배송비 문구는 채팅 init 메타(useChatInitStore)를 읽어 상품별로 동적 표시한다.
// break-keep: 한국어 단어가 중간에서 잘려 줄바꿈되지 않도록 한다. const bodyStyle = 'text-sm font-normal leading-relaxed text-neutral-70 break-keep'
const textStyle = 'text-[17px] font-normal leading-[150%] tracking-[-0.34px] text-neutral-90 break-keep'
function Bullet({ children }: { children: ReactNode }) { function Bullet({ children }: { children: ReactNode }) {
return ( return (
<div className="flex items-start py-[6px]"> <div className="flex items-start gap-2.5 py-1.5">
<p className="ml-[8px] mr-[6px] flex-shrink-0">•</p> <span className="mt-[7px] size-1.5 shrink-0 rounded-full bg-brand-600" />
<div className={`${textStyle} flex-1`}>{children}</div> <div className={`${bodyStyle} flex-1`}>{children}</div>
</div> </div>
) )
} }
@@ -23,24 +22,26 @@ export function GuideContent() {
return ( return (
<div className="flex w-full flex-col"> <div className="flex w-full flex-col">
<div className="headline-3 mb-10 break-keep text-center text-neutral-90"> <div className="mb-5 break-keep text-center text-base font-bold text-neutral-90">
협상 유의 사항 및 서비스 이용 방법 안내 협상 유의 사항 및 서비스 이용 방법 안내
</div> </div>
<div className="flex flex-col items-start"> <div className={`${bodyStyle} mb-2`}>
<div className={`${textStyle} mb-2`}> 협상과 관련하여 다음 사항을 참고하여 견적에 참여해 주시기 바랍니다.
협상과 관련하여 다음 사항을 참고하여 견적에 참여해 주시기 바랍니다. </div>
</div>
<div className="flex flex-col divide-y divide-border/60 rounded-xl border border-border px-4 py-1">
<Bullet> <Bullet>
협상 개시는&nbsp; 협상 개시는&nbsp;
<span className="font-bold">Negosium 시스템의 협상 참여 버튼을 클릭하는 순간부터 시작</span> <span className="font-semibold text-neutral-90">
Negosium 시스템의 협상 참여 버튼을 클릭하는 순간부터 시작
</span>
됩니다. 됩니다.
</Bullet> </Bullet>
<Bullet> <Bullet>
부여된 협상 시간에&nbsp; 부여된 협상 시간에&nbsp;
<span className="font-bold"> <span className="font-semibold text-neutral-90">
응찰하지 않는 경우, 협상 참여의사가 없는 것으로 간주하여 재견적으로 진행 응찰하지 않는 경우, 협상 참여의사가 없는 것으로 간주하여 재견적으로 진행
</span> </span>
될 수 있습니다. 될 수 있습니다.
@@ -48,25 +49,23 @@ export function GuideContent() {
<Bullet> <Bullet>
협상에 입력되는 모든 가격은&nbsp; 협상에 입력되는 모든 가격은&nbsp;
<span className="font-bold text-negative"> <span className="font-semibold text-negative">
{vat} 및 {deliveryFee} {vat} 및 {deliveryFee}
</span> </span>
&nbsp;기준이며,&nbsp; &nbsp;기준이며,&nbsp;
<span className="font-bold"> <span className="font-semibold text-neutral-90">
할인을 요청하는 경우 기존 공급가격에 할인율이 적용된 가격으로 환산 할인을 요청하는 경우 기존 공급가격에 할인율이 적용된 가격으로 환산
</span> </span>
되어 제시됩니다. 되어 제시됩니다.
</Bullet> </Bullet>
<Bullet> <Bullet>
본 협상 결과에 대해서는 협상자와 협상대상자 간의 비밀 유지 조건으로 진행되고, 협상에서 본 협상 결과에 대해서는 협상자와 협상대상자 간의 비밀 유지 조건으로 진행되고, 협상에서 얻어진 결과나 내용에
얻어진 결과나 내용에 대해서는 당사자를 제외하고 제 3자에 공유할 수 없으며, 비밀 유지를 대해서는 당사자를 제외하고 제 3자에 공유할 수 없으며, 비밀 유지를 전제로 진행됩니다.
전제로 진행됩니다.
</Bullet> </Bullet>
<Bullet> <Bullet>
협상이 종결되면 특별한 사유 없이 취소 변경이 불가하니, 신중하게 협상에 참여해 주시기 협상이 종결되면 특별한 사유 없이 취소 변경이 불가하니, 신중하게 협상에 참여해 주시기 바랍니다.
바랍니다.
</Bullet> </Bullet>
<Bullet>안내된 사항 외 부분은 기존 견적 프로세스와 동일한 부분 유의 바랍니다.</Bullet> <Bullet>안내된 사항 외 부분은 기존 견적 프로세스와 동일한 부분 유의 바랍니다.</Bullet>
@@ -78,13 +77,12 @@ export function GuideContent() {
// 하단 문의 안내 박스 // 하단 문의 안내 박스
export function GuideContactBox() { export function GuideContactBox() {
return ( return (
<div className="flex w-full flex-col items-center gap-2 rounded-[16px] bg-neutral-10 p-6"> <div className="flex w-full flex-col items-center gap-1.5 rounded-xl bg-neutral-10 p-4">
<div className={`${textStyle} text-center`}> <div className={`${bodyStyle} text-center`}>
기타 협상과정에서 궁금한 사항이나 문의하실 사항은 아래의 연락처로 상담을 부탁드립니다. 기타 협상 과정에서 궁금하거나 문의하실 사항은 아래 연락처로 상담 부탁드립니다.
</div> </div>
{/* textStyle 의 font-normal 과 같은 요소에서 충돌하지 않도록 bold 는 별도 조합으로 준다 */} <div className="break-keep text-center text-sm font-bold text-neutral-90">
<div className="break-keep text-center text-[17px] font-bold leading-[150%] tracking-[-0.34px] text-neutral-90"> 헬프데스크 010-0000-0000 · o2odev@o2o.kr
헬프데스크 010-0000-0000, 이메일: o2odev@o2o.kr
</div> </div>
</div> </div>
) )
@@ -7,19 +7,19 @@ import { GuideContent, GuideContactBox } from './GuideContent'
export function ServiceGuidePopup({ onClose }: { onClose: () => void }) { export function ServiceGuidePopup({ onClose }: { onClose: () => void }) {
return ( return (
<Modal onClose={onClose}> <Modal onClose={onClose}>
<div className="flex max-h-[90vh] w-full max-w-[1000px] flex-col items-end gap-6 overflow-y-auto rounded-3xl bg-white px-12 pb-[56px] pt-8"> <div className="m-4 flex max-h-[90vh] w-full max-w-[720px] flex-col items-end gap-4 overflow-y-auto rounded-2xl border border-border bg-white px-6 pb-10 pt-6 shadow-xl animate-scale-in sm:px-12">
<button <button
type="button" type="button"
aria-label="닫기" aria-label="닫기"
onClick={onClose} onClick={onClose}
className={cn( className={cn(
'flex size-10 flex-shrink-0 items-center justify-center rounded-full bg-neutral-10', 'flex size-9 flex-shrink-0 items-center justify-center rounded-full bg-neutral-10 text-neutral-70 hover:bg-neutral-20',
interactive, interactive,
)} )}
> >
<X size={20} className="text-neutral-80" /> <X size={20} />
</button> </button>
<div className="flex w-full flex-col gap-6 px-[40px]"> <div className="flex w-full flex-col gap-6">
<GuideContent /> <GuideContent />
<GuideContactBox /> <GuideContactBox />
</div> </div>
@@ -10,8 +10,8 @@ interface ServiceInfoPopupProps {
} }
const buttonStyle = cn( const buttonStyle = cn(
'flex h-[50px] w-[168px] items-center justify-center rounded-full', 'flex h-[46px] flex-1 sm:flex-none sm:w-[168px] items-center justify-center rounded-xl',
'border border-neutral-30 bg-white title-5 text-neutral-70', 'border border-border bg-white text-sm font-bold text-neutral-70 hover:bg-neutral-10',
interactive, interactive,
) )
@@ -20,13 +20,13 @@ export function ServiceInfoPopup({ isOpen, onNeverShowAgain, onCloseToday }: Ser
if (!isOpen) return null if (!isOpen) return null
return ( return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-[rgba(0,0,0,0.40)] p-4"> <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 backdrop-blur-[2px]">
<div className="flex max-h-[90vh] w-full max-w-[1000px] flex-col overflow-y-auto rounded-[24px] bg-white px-[80px] pb-[48px] pt-[56px]"> <div className="flex max-h-[90vh] w-full max-w-[720px] flex-col overflow-y-auto rounded-2xl border border-border bg-white px-6 pb-6 pt-8 shadow-xl animate-scale-in sm:px-12 sm:pt-10">
<div className="mb-6 flex w-full flex-col gap-5"> <div className="mb-6 flex w-full flex-col gap-5">
<GuideContent /> <GuideContent />
<GuideContactBox /> <GuideContactBox />
</div> </div>
<div className="flex w-full justify-center gap-3"> <div className="flex w-full justify-center gap-2 sm:gap-3">
<button type="button" className={buttonStyle} onClick={onNeverShowAgain}> <button type="button" className={buttonStyle} onClick={onNeverShowAgain}>
안내 보지 않기 안내 보지 않기
</button> </button>
@@ -1,3 +1,4 @@
import { CheckCircle2 } from 'lucide-react'
import { numberToKorean } from '@/features/chat/lib/koreanNumber' import { numberToKorean } from '@/features/chat/lib/koreanNumber'
interface BidSummaryProps { interface BidSummaryProps {
@@ -8,54 +9,42 @@ interface BidSummaryProps {
isVAT: boolean isVAT: boolean
} }
// 투찰 결과 요약 카드 // 투찰 결과 요약 카드 (보고서식 final-summary)
export function BidSummary({ itemName, itemCode, bidPrice, deliveryType, isVAT }: BidSummaryProps) { export function BidSummary({ itemName, itemCode, bidPrice, deliveryType, isVAT }: BidSummaryProps) {
const priceStr = (bidPrice || 0).toLocaleString()
return ( return (
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-4"> <div className="w-full rounded-2xl border-2 border-brand-light bg-white p-5 shadow-md">
<h1 className="headline-3 text-neutral-90">투찰 결과 요약</h1> <div className="mb-4 flex items-center gap-2">
<BidItem title="상품명" value={itemName || '-'} /> <CheckCircle2 className="size-5 text-success" />
<BidItem title="상품 코드" value={itemCode || '-'} /> <h3 className="text-sm font-bold text-neutral-90">투찰 결과 요약</h3>
<BidPrice title="투찰 가격" number={bidPrice || 0} isVAT={isVAT} />
<BidItem title="배송형태" value={deliveryType || '-'} />
</div>
)
}
function BidItem({ title, value }: { title: string; value: string }) {
return (
<div className="flex items-start gap-2">
<Dot />
<div className="flex flex-1 whitespace-pre-wrap">
<span className="body-1-read-b">{title} :</span>
<div className="flex body-1-read-r">&nbsp;{value}</div>
</div> </div>
</div>
)
}
function BidPrice({ number, isVAT, title }: { number: number; isVAT: boolean; title: string }) { <div className="divide-y divide-border/60 rounded-xl border border-border">
const numberString = number.toLocaleString() <Row label="상품명" value={itemName || '-'} />
return ( <Row label="상품 코드" value={itemCode || '-'} mono />
<div className="flex items-start gap-2"> <div className="flex items-start justify-between gap-3 px-4 py-3">
<Dot /> <span className="shrink-0 text-sm text-neutral-60">투찰 가격</span>
<div className="flex flex-1"> <span className="min-w-0 flex-1 break-keep text-right text-sm">
<div className="body-1-read-b flex flex-shrink-0">{title} :</div> <span className="font-bold text-[#E5484D]">{priceStr}원</span>
<div className="flex flex-1 flex-wrap"> <span className="text-neutral-70"> ({numberToKorean(bidPrice || 0)}원)</span>
<span className="body-1-read-b text-negative break-keep">&nbsp;{numberString}원</span> <span className="text-neutral-70"> {isVAT ? 'VAT포함' : 'VAT별도'}</span>
<span className="body-1-read-b text-neutral-90 break-keep">
&nbsp;({numberToKorean(parseInt(numberString.replace(/,/g, '')))}원)
</span> </span>
<span className="body-1-read-b text-neutral-90 break-keep">&nbsp;{isVAT ? 'VAT포함' : 'VAT별도'}</span>
</div> </div>
<Row label="배송형태" value={deliveryType || '-'} />
</div> </div>
</div> </div>
) )
} }
function Dot() { function Row({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
return ( return (
<div className="flex justify-end items-center w-[26px] h-[30px]"> <div className="flex items-start justify-between gap-3 px-4 py-3">
<p className="body-1-read-r">•</p> <span className="shrink-0 text-sm text-neutral-60">{label}</span>
<span
className={`min-w-0 flex-1 break-keep text-right text-sm font-semibold text-neutral-90 ${mono ? 'font-mono' : ''}`}
>
{value}
</span>
</div> </div>
) )
} }
@@ -0,0 +1,109 @@
import { useEffect, useState } from 'react'
import { CheckCircle2 } from 'lucide-react'
import { toast } from 'sonner'
import { useMeQuery, useSaveExtraInfoMutation, getApiErrorMessage } from '@/apis'
import type { SessionField } from '@/apis/auth/auth.type'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
// 협상 타결(Summary) 직후 부가정보 입력 폼. 필드 정의(session_fields)는 회사 설정(/me)에서 온다.
// 저장하면 sessions.custom 에 기록되고 negodata 견적상세에 표시된다. 정의가 없으면 렌더하지 않는다.
export function ExtraInfoForm() {
const sessionId = useChatStore((s) => s.sessionId)
const { data: user } = useMeQuery()
const fields: SessionField[] = user?.sessionFields ?? []
const save = useSaveExtraInfoMutation()
const existing = useChatInitStore((s) => s.custom) // 기존 입력값(재진입 프리필)
const [values, setValues] = useState<Record<string, unknown>>({})
const [inited, setInited] = useState(false)
const [saved, setSaved] = useState(false)
// fields(회사 설정)와 기존값(sessions.custom)이 준비된 첫 시점에 프리필 — 이후 사용자 편집은 보존.
useEffect(() => {
if (inited || fields.length === 0) return
const init: Record<string, unknown> = {}
for (const f of fields) init[f.key] = existing?.[f.key] ?? (f.type === 'boolean' ? false : '')
setValues(init)
setInited(true)
}, [inited, fields, existing])
if (fields.length === 0) return null
const set = (key: string, value: unknown) => setValues((v) => ({ ...v, [key]: value }))
const handleSave = () => {
const custom: Record<string, unknown> = {}
for (const f of fields) {
const v = values[f.key]
if (f.type === 'boolean') custom[f.key] = !!v
else if (v !== '' && v != null) custom[f.key] = f.type === 'number' ? Number(v) : v
}
save.mutate(
{ sessionId, request: { custom } },
{
onSuccess: () => {
setSaved(true)
toast.success('부가정보가 저장되었습니다.')
},
onError: (error) => toast.error(getApiErrorMessage(error, '부가정보 저장에 실패했습니다.')),
},
)
}
return (
<div className="w-full rounded-2xl border border-border bg-white p-5 shadow-sm">
<div className="mb-3 flex items-center gap-2">
<CheckCircle2 className="size-5 text-brand-600" />
<h3 className="text-sm font-bold text-neutral-90">부가정보 입력</h3>
</div>
<p className="text-sm leading-relaxed text-neutral-70 break-keep">
협상이 완료되었습니다. 아래 정보를 입력해 주세요. (저장 후에도 세션 목록에서 수정할 수 있습니다.)
</p>
<div className="mt-4 space-y-4">
{fields.map((f) => (
<div key={f.key} className="space-y-1.5">
<label className="block text-sm font-semibold text-neutral-80">{f.label}</label>
{f.type === 'boolean' ? (
<button
type="button"
role="switch"
aria-checked={!!values[f.key]}
onClick={() => set(f.key, !values[f.key])}
disabled={saved}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors disabled:opacity-50 ${
values[f.key] ? 'bg-brand-600' : 'bg-neutral-30'
}`}
>
<span
className={`inline-block size-5 transform rounded-full bg-white shadow transition-transform ${
values[f.key] ? 'translate-x-5' : 'translate-x-0.5'
}`}
/>
</button>
) : (
<input
type={f.type === 'number' ? 'number' : 'text'}
value={String(values[f.key] ?? '')}
onChange={(e) => set(f.key, e.target.value)}
disabled={saved}
className="h-11 w-full rounded-xl border border-border bg-white px-3 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600 disabled:bg-neutral-10"
placeholder={f.label}
/>
)}
</div>
))}
</div>
<button
type="button"
onClick={handleSave}
disabled={save.isPending || saved}
className="mt-4 h-11 w-full rounded-xl bg-brand-600 text-sm font-bold text-white transition-colors hover:bg-brand-700 disabled:opacity-50"
>
{saved ? '저장 완료' : save.isPending ? '저장 중…' : '부가정보 저장'}
</button>
</div>
)
}
@@ -1,78 +1,31 @@
import { cn } from '@/lib' // 협상 성공률 카드 (0~100%). 10칸 컬러 블록바 — 구간별 색(빨강→주황→초록)으로 채운다.
// 협상 성공률 바 (0~100%). 구간별 색: 빨강(~30) / 주황(~70) / 초록(70~)
function selectBgColor(index: number, currentStep: number): string {
let fill = '#E71C3B'
if (currentStep > 3 && currentStep <= 7) fill = '#FDB21C'
if (currentStep > 7) fill = '#16BD14'
return index <= currentStep ? fill : '#ddd'
}
function UnitBlock({ blockIndex, percent }: { blockIndex: number; percent: number }) {
const minBlockPercent = blockIndex * 10
const maxBlockPercent = (blockIndex + 1) * 10
const remindCount = percent - minBlockPercent
let nodeType: 'fill' | 'empty' | 'half' = 'empty'
if (maxBlockPercent < percent) nodeType = 'fill'
else if (minBlockPercent <= percent) nodeType = 'half'
return (
<div className="flex flex-col items-center flex-1">
<div className="flex w-full h-3">
{Array.from({ length: 10 }).map((_, i) => {
let color = selectBgColor(blockIndex, Math.floor(percent / 10))
if (nodeType === 'half' && i >= remindCount) color = '#ddd'
const subBlockPercent = blockIndex * 10 + i + 1
const isTarget = subBlockPercent === percent
const isLeftAlign = percent < 90
return (
<div key={i} className="flex-1 h-full rounded-[1px] relative" style={{ backgroundColor: color }}>
{isTarget && (
<div className="pointer-events-none absolute bottom-full -top-4 left-1/2 -translate-x-1/2 z-10">
<div className="relative w-0 h-0">
<div className="absolute -top-2 left-[calc(50%+4px)] -translate-x-1/2 w-0 h-0 border-l-[8px] border-r-[8px] border-t-[14px] border-l-transparent border-r-transparent border-t-black" />
<span
className={cn(
'absolute top-[calc(50%-2px)] -translate-y-1/2 text-[24px] leading-none font-bold tabular-nums text-black whitespace-nowrap',
isLeftAlign ? 'left-[18px]' : 'right-[10px]',
)}
>
{percent}%
</span>
</div>
</div>
)}
</div>
)
})}
</div>
</div>
)
}
export function Indicator({ number }: { number: number }) { export function Indicator({ number }: { number: number }) {
const percent = Math.min(Math.max(number, 0), 100) const percent = Math.min(Math.max(number, 0), 100)
const filled = Math.round(percent / 10) // 0~10칸
const color = percent < 40 ? '#F04452' : percent < 70 ? '#F5A623' : '#0B8F57'
return ( return (
<div className="flex w-full flex-col gap-3 bg-neutral-00 rounded-[28px] px-10 py-[36px]"> <div className="w-full rounded-2xl border border-border bg-white p-5 shadow-sm">
<h1 className="title-1 text-neutral-90">협상 성공률</h1> <div className="flex items-center justify-between">
<div className="flex flex-col gap-2"> <h3 className="text-sm font-bold text-neutral-90">협상 성공률</h3>
{percent === 0 ? ( <span className="font-mono text-base font-extrabold" style={{ color }}>
<div className="relative h-6"> {percent}%
<div className="absolute left-[20px] -translate-x-1/2 text-xl text-black font-bold">▼&nbsp;0%</div> </span>
</div>
) : (
<div className="h-6" />
)}
<div className="flex gap-1">
{Array.from({ length: 10 }).map((_, i) => (
<UnitBlock key={i} blockIndex={i} percent={percent} />
))}
</div>
</div> </div>
<div className="mt-3 flex gap-1">
{Array.from({ length: 10 }).map((_, i) => (
<div
key={i}
className="h-3.5 flex-1 rounded-[3px] transition-colors duration-300"
style={{ backgroundColor: i < filled ? color : 'var(--neutral-20)' }}
/>
))}
</div>
<p className="mt-2 text-xs text-neutral-60">
협상이 진행될수록 성공률이 실시간으로 갱신됩니다.
</p>
</div> </div>
) )
} }
@@ -39,19 +39,20 @@ export function OtherReason({
const isTextareaDisabled = disabled || !isChecked const isTextareaDisabled = disabled || !isChecked
return ( return (
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1.5">
<div className="flex items-start gap-2"> <div className="flex items-start gap-2.5">
<label className={cn('flex items-start gap-2 flex-shrink-0', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}> <label className={cn('flex shrink-0 items-start gap-2.5', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}>
<input <span
className={cn( className={cn(
'appearance-none w-[16px] h-[16px] mt-[10px] flex-shrink-0 rounded-full border-[1.5px]', 'mt-0.5 flex size-[18px] shrink-0 items-center justify-center rounded-full border-2 transition-colors',
disabled ? 'cursor-not-allowed' : 'cursor-pointer', isChecked ? 'border-brand-600' : isError ? 'border-negative' : 'border-neutral-40',
isChecked disabled && 'opacity-60',
? 'border-neutral-70 bg-[radial-gradient(circle,var(--neutral-70)_40%,white_40%)]'
: isError
? 'border-negative bg-white'
: 'border-neutral-60 bg-white',
)} )}
>
{isChecked && <span className="size-2.5 rounded-full bg-brand-600" />}
</span>
<input
className="sr-only"
type="radio" type="radio"
name="rejectrsp" name="rejectrsp"
value="기타" value="기타"
@@ -59,15 +60,15 @@ export function OtherReason({
onChange={(e) => onChange(e.target.value)} onChange={(e) => onChange(e.target.value)}
disabled={disabled} disabled={disabled}
/> />
<div className={cn('reject break-keep whitespace-nowrap mt-[4px] flex', disabled && 'text-neutral-60')}> <span className={cn('text-sm text-neutral-80', disabled && 'text-neutral-50')}>기타</span>
기타
</div>
</label> </label>
<textarea <textarea
ref={ref} ref={ref}
className={cn( className={cn(
'w-full px-3 py-2 body-3 resize-none border border-neutral-40 rounded-[8px] outline-none transition-all duration-200 placeholder:text-neutral-60 focus:border-neutral-70 focus:outline-none', 'w-full resize-none rounded-xl border px-3 py-2 text-sm outline-none transition-all placeholder:text-neutral-50',
isTextareaDisabled ? 'bg-neutral-10 text-neutral-60 cursor-not-allowed' : 'bg-white text-neutral-90', isTextareaDisabled
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
errorMessage && 'border-negative', errorMessage && 'border-negative',
)} )}
value={inputValue} value={inputValue}
@@ -75,10 +76,10 @@ export function OtherReason({
placeholder="제시한 가격을 수용할 수 없는 이유를 작성해주세요." placeholder="제시한 가격을 수용할 수 없는 이유를 작성해주세요."
disabled={isTextareaDisabled} disabled={isTextareaDisabled}
rows={1} rows={1}
style={{ minHeight: '35px', lineHeight: '20px' }} style={{ minHeight: '38px', lineHeight: '20px' }}
/> />
</div> </div>
{errorMessage && <div className="body-5 text-negative pl-[65px]">{errorMessage}</div>} {errorMessage && <div className="pl-[30px] text-xs font-medium text-negative">{errorMessage}</div>}
</div> </div>
) )
} }
@@ -1,4 +1,5 @@
import { useState, useMemo } from 'react' import { useState, useMemo } from 'react'
import { AlertTriangle } from 'lucide-react'
import { cn } from '@/lib' import { cn } from '@/lib'
import { numberToKorean } from '@/features/chat/lib/koreanNumber' import { numberToKorean } from '@/features/chat/lib/koreanNumber'
import { findRestoreScript, extractPart } from '@/features/chat/lib/rejectForm' import { findRestoreScript, extractPart } from '@/features/chat/lib/rejectForm'
@@ -51,44 +52,47 @@ export function RejectCM() {
const isDisabled = isLoading || isSubmitted const isDisabled = isLoading || isSubmitted
return ( return (
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-2 transition-all duration-300"> <div className="flex flex-col w-full p-8 bg-white rounded-2xl border border-border shadow-sm gap-2 transition-all duration-300">
<div className="flex w-full h-[48px] bg-[#CD2A2D] headline-3 text-neutral-00 rounded-[12px] items-center justify-center"> <div className="flex w-full items-center justify-center gap-2 rounded-xl bg-[#FFF1F1] px-4 py-3 text-sm font-bold text-[#E5484D]">
<AlertTriangle className="size-5 shrink-0" />
최종 공급 희망 가격 입력 최종 공급 희망 가격 입력
</div> </div>
<div className="reject break-keep py-2"> <div className="py-2 text-sm leading-relaxed text-neutral-70 break-keep">
최종 공급 희망 가격과 배송 형태를 입력하여 주시기 바랍니다. 최종 공급 희망 가격과 배송 형태를 입력하여 주시기 바랍니다.
<br /> <br />
가격 검토를 통해 경쟁력 있는 가격일 경우 다시 협상에 참여할 기회가 주어지오니 신중한 가격 제안 부탁드립니다. 가격 검토를 통해 경쟁력 있는 가격일 경우 다시 협상에 참여할 기회가 주어지오니 신중한 가격 제안 부탁드립니다.
</div> </div>
<div className="flex flex-col w-full gap-1"> <div className="flex flex-col w-full gap-1">
<div className="flex w-full items-start gap-4"> <div className="flex w-full items-start gap-3">
<div className="flex reject-2 whitespace-nowrap pt-2 flex-shrink-0 w-[110px]">공급 희망 가격</div> <div className="w-[100px] shrink-0 pt-2.5 text-sm font-bold text-neutral-90">공급 희망 가격</div>
<div className="flex flex-wrap w-full items-center pt-2"> <div className="flex w-full flex-wrap items-center gap-2 pt-2">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<input <input
type="text" type="text"
className={cn( className={cn(
'text-right max-w-[220px] h-full max-h-[35px] border p-2 body-3 placeholder:text-neutral-60 focus:border-neutral-70 rounded-[8px] outline-none border-neutral-40', 'h-10 max-w-[200px] rounded-xl border px-3 text-right text-sm outline-none transition-all placeholder:text-neutral-50',
isDisabled ? 'bg-neutral-10 text-neutral-60 cursor-not-allowed' : 'bg-white text-neutral-90', isDisabled
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
)} )}
value={price ? parseInt(price).toLocaleString() : ''} value={price ? parseInt(price).toLocaleString() : ''}
onChange={(e) => handlePriceChange(e.target.value)} onChange={(e) => handlePriceChange(e.target.value)}
placeholder="0" placeholder="0"
disabled={isDisabled} disabled={isDisabled}
/> />
<div className="reject whitespace-nowrap mr-2">원{isVAT && '(VAT 별도)'}</div> <div className="whitespace-nowrap text-sm text-neutral-70">원{isVAT && '(VAT 별도)'}</div>
</div> </div>
<div className="reject-gray whitespace-nowrap">[{koreanPrice} 원]</div> <div className="whitespace-nowrap text-sm text-neutral-50">[{koreanPrice} 원]</div>
</div> </div>
</div> </div>
{priceErrorMessage && <div className="body-5 text-negative pl-[126px]">{priceErrorMessage}</div>} {priceErrorMessage && <div className="pl-[112px] text-xs font-medium text-negative">{priceErrorMessage}</div>}
</div> </div>
<div className="flex w-full gap-4"> <div className="flex w-full gap-3">
<div className="flex reject-2 whitespace-nowrap pt-2 flex-shrink-0 w-[110px]">배송 형태</div> <div className="w-[100px] shrink-0 pt-2 text-sm font-bold text-neutral-90">배송 형태</div>
<div className="flex w-full items-center justify-between pr-20 flex-wrap"> <div className="flex w-full flex-wrap items-center gap-x-6 gap-y-2">
{['협력사배송', '지정택배배송', '픽업배송'].map((opt) => ( {['협력사배송', '지정택배배송', '픽업배송'].map((opt) => (
<SelectRadio <SelectRadio
key={opt} key={opt}
@@ -1,4 +1,5 @@
import { useState, useMemo } from 'react' import { useState, useMemo } from 'react'
import { AlertTriangle } from 'lucide-react'
import { cn } from '@/lib' import { cn } from '@/lib'
import { numberToKorean } from '@/features/chat/lib/koreanNumber' import { numberToKorean } from '@/features/chat/lib/koreanNumber'
import { useChatStore } from '@/features/chat/stores/useChatStore' import { useChatStore } from '@/features/chat/stores/useChatStore'
@@ -80,12 +81,13 @@ export function RejectRSP() {
const isDisabled = isLoading || isSubmitted const isDisabled = isLoading || isSubmitted
return ( return (
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-2 transition-all duration-300"> <div className="flex flex-col w-full p-8 bg-white rounded-2xl border border-border shadow-sm gap-2 transition-all duration-300">
<div className="flex w-full h-[48px] bg-[#CD2A2D] headline-3 text-neutral-00 rounded-[12px] items-center justify-center"> <div className="flex w-full items-center justify-center gap-2 rounded-xl bg-[#FFF1F1] px-4 py-3 text-sm font-bold text-[#E5484D]">
<AlertTriangle className="size-5 shrink-0" />
협상 합의 불가 사유 및 최종 제안 단가 입력 협상 합의 불가 사유 및 최종 제안 단가 입력
</div> </div>
<div className="reject break-keep py-2"> <div className="py-2 text-sm leading-relaxed text-neutral-70 break-keep">
협상이 합의에 도달하지 못하였습니다. 최종 희망하는 가격을 입력해주시기 바랍니다. 협상이 합의에 도달하지 못하였습니다. 최종 희망하는 가격을 입력해주시기 바랍니다.
<br /> <br />
추가로 제시한 가격을 수용할 수 없는 이유를 선택하여 주시기 바라며, 목록에 없는 경우 기타 항목 선택 후 간단한 사유를 추가로 제시한 가격을 수용할 수 없는 이유를 선택하여 주시기 바라며, 목록에 없는 경우 기타 항목 선택 후 간단한 사유를
@@ -93,31 +95,33 @@ export function RejectRSP() {
</div> </div>
<div className="flex flex-col w-full gap-1"> <div className="flex flex-col w-full gap-1">
<div className="flex w-full items-start gap-4"> <div className="flex w-full items-start gap-3">
<div className="flex reject-2 whitespace-nowrap pt-2 flex-shrink-0 w-[110px]">공급 희망 가격</div> <div className="w-[100px] shrink-0 pt-2.5 text-sm font-bold text-neutral-90">공급 희망 가격</div>
<div className="flex flex-wrap w-full items-center pt-2"> <div className="flex w-full flex-wrap items-center gap-2 pt-2">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<input <input
type="text" type="text"
className={cn( className={cn(
'text-right max-w-[220px] h-full max-h-[35px] border p-2 body-3 placeholder:text-neutral-60 focus:border-neutral-70 rounded-[8px] outline-none border-neutral-40', 'h-10 max-w-[200px] rounded-xl border px-3 text-right text-sm outline-none transition-all placeholder:text-neutral-50',
isDisabled ? 'bg-neutral-10 text-neutral-60 cursor-not-allowed' : 'bg-white text-neutral-90', isDisabled
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
)} )}
value={price ? parseInt(price).toLocaleString() : ''} value={price ? parseInt(price).toLocaleString() : ''}
onChange={(e) => handlePriceChange(e.target.value)} onChange={(e) => handlePriceChange(e.target.value)}
placeholder="0" placeholder="0"
disabled={isDisabled} disabled={isDisabled}
/> />
<div className="reject whitespace-nowrap mr-2">원{isVAT && '(VAT 별도)'}</div> <div className="whitespace-nowrap text-sm text-neutral-70">원{isVAT && '(VAT 별도)'}</div>
</div> </div>
<div className="reject-gray whitespace-nowrap">[{koreanPrice} 원]</div> <div className="whitespace-nowrap text-sm text-neutral-50">[{koreanPrice} 원]</div>
</div> </div>
</div> </div>
{priceErrorMessage && <div className="body-5 text-negative pl-[126px]">{priceErrorMessage}</div>} {priceErrorMessage && <div className="pl-[112px] text-xs font-medium text-negative">{priceErrorMessage}</div>}
</div> </div>
<div className="flex w-full gap-4"> <div className="flex w-full gap-3">
<div className="flex reject-2 whitespace-nowrap pt-2 pb-2 flex-shrink-0 w-[110px]">합의 불가 사유</div> <div className="w-[100px] shrink-0 pt-2 text-sm font-bold text-neutral-90">합의 불가 사유</div>
<div className="flex w-full flex-col mt-2 gap-2"> <div className="flex w-full flex-col mt-2 gap-2">
{REASONS.map((r) => ( {REASONS.map((r) => (
<SelectRadio <SelectRadio
@@ -1,49 +1,82 @@
import { CheckCircle2 } from 'lucide-react'
import { numberToKorean } from '@/features/chat/lib/koreanNumber' import { numberToKorean } from '@/features/chat/lib/koreanNumber'
import { formatLeadTime } from '@/features/chat/lib/format' import { formatLeadTime } from '@/features/chat/lib/format'
import type { ChatSummary } from '@/features/chat/types' import type { ChatSummary } from '@/features/chat/types'
// 협상 결과 요약 카드 // 협상 결과 요약 카드
export function Summary({ data }: { data: ChatSummary }) { export function Summary({ data }: { data: ChatSummary }) {
const priceStr = (data.final_price || 0).toLocaleString()
return ( return (
<div className="flex flex-col w-full p-10 bg-neutral-00 rounded-[28px] gap-4"> <div className="w-full rounded-2xl border border-border bg-white p-5 shadow-sm">
<h1 className="headline-3 text-neutral-90">협상 결과 요약</h1> <div className="mb-3 flex items-center gap-2">
<div className="body-1-read-r"> <CheckCircle2 className="size-5 text-success" />
협상이 완료되어 아래와 같이 결과를 요약하오니 다시 한 번 최종 확인 부탁 드립니다. 최종 확인 후 협상 결과에 대한 <h3 className="text-sm font-bold text-neutral-90">협상 결과 요약</h3>
수정 변경은 불가함을 안내 드립니다.
</div> </div>
<div className="flex flex-col">
<div className="body-1-read-r">협상 개시 시간 : {formatKoreanDateTime(data.nego_start_date)}</div> <p className="text-sm leading-relaxed text-neutral-70 break-keep">
<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 || '-'}){' '} </p>
{data.supplier_manager_email || '-'}
{/* 개요 */}
<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="배송 리드타임" value={formatLeadTime(data.item_lead_time) || '-'} />
<div className="flex items-start justify-between gap-3 px-4 py-3">
<span className="shrink-0 text-sm text-neutral-60">최종 협의 가격</span>
<span className="min-w-0 flex-1 break-keep text-right text-sm">
<span className="font-bold text-[#E5484D]">{priceStr}원</span>
<span className="text-neutral-70"> ({numberToKorean(data.final_price || 0)}원)</span>
<span className="text-neutral-70"> {data.item_isVAT ? 'VAT포함' : 'VAT별도'}</span>
</span>
</div> </div>
<div className="body-1-read-r">협상 상세 내역</div>
</div> </div>
<div className="flex flex-col gap-4">
<DetailText title="상품 코드" value={data.item_code || '-'} /> {/* 계약 / 담당 MD */}
<DetailText title="상품 명" value={data.item_name || '-'} /> <div className="mt-3 space-y-1 text-xs text-neutral-70">
<DetailText title="모델 명" value={data.item_model || '-'} /> <p>공급 계약 기간: 협상 완료일로부터 1년 ({addOneYear(data.nego_end_date)})까지</p>
<DetailText title="제품 규격" value={data.item_spec || '-'} /> <p>
<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>
<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 || '-'} 담당 MD: {data.md_name || '-'} ({data.md_phone_number || '-'}) {data.md_email || '-'}
</div> </p>
</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> </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 { function kstParts(iso: string): Record<string, string> | null {
if (!iso) return null if (!iso) return null
const d = new Date(iso) const d = new Date(iso)
@@ -63,55 +96,16 @@ function kstParts(iso: string): Record<string, string> | null {
return out return out
} }
// "YYYY년 MM월 dd일 HH시 MM분 SS초" (KST) // "YYYY년 MM월 dd일 HH시 MM분" (KST)
function formatKoreanDateTime(iso: string): string { function formatKoreanDateTime(iso: string): string {
const p = kstParts(iso) const p = kstParts(iso)
if (!p) return '-' 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 { function addOneYear(iso: string): string {
const p = kstParts(iso) const p = kstParts(iso)
if (!p) return '-' if (!p) return '-'
return `${parseInt(p.year) + 1}년 ${p.month}월 ${p.day}일` 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 const isChecked = selectedValue === value
return ( return (
<label className={cn('flex items-center gap-2', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}> <label className={cn('flex items-start gap-2.5', disabled ? 'cursor-not-allowed' : 'cursor-pointer')}>
<input <span
className={cn( className={cn(
'appearance-none w-[16px] h-[16px] min-w-[16px] min-h-[16px] rounded-full border-[1.5px] whitespace-nowrap', 'mt-0.5 flex size-[18px] shrink-0 items-center justify-center rounded-full border-2 transition-colors',
disabled ? 'cursor-not-allowed' : 'cursor-pointer', isChecked ? 'border-brand-600' : errorMessage ? 'border-negative' : 'border-neutral-40',
isChecked disabled && 'opacity-60',
? 'border-neutral-70 bg-[radial-gradient(circle,var(--neutral-70)_40%,white_40%)]'
: errorMessage
? 'border-negative bg-white'
: 'border-neutral-60 bg-white',
)} )}
>
{isChecked && <span className="size-2.5 rounded-full bg-brand-600" />}
</span>
<input
className="sr-only"
type="radio" type="radio"
name={name} name={name}
value={value} value={value}
@@ -40,7 +41,9 @@ export function SelectRadio({
onChange={(e) => onChange(e.target.value)} onChange={(e) => onChange(e.target.value)}
disabled={disabled} 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> </label>
) )
} }
@@ -59,15 +62,15 @@ export function SubmitButton({
if (isSubmitted) return null if (isSubmitted) return null
const style = isLoading const style = isLoading
? 'bg-neutral-40 text-neutral-80 cursor-not-allowed' ? 'bg-neutral-20 text-neutral-60 cursor-not-allowed'
: isValid : isValid
? 'bg-neutral-90 text-white cursor-pointer hover:bg-neutral-80' ? 'bg-brand-600 text-white shadow-sm cursor-pointer hover:bg-brand-700 active:scale-[0.98]'
: 'bg-neutral-20 text-neutral-60 cursor-not-allowed' : 'bg-neutral-20 text-neutral-50 cursor-not-allowed'
return ( return (
<button <button
className={cn( 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, style,
)} )}
onClick={onSubmit} onClick={onSubmit}
@@ -24,7 +24,7 @@ function InputWithUnit({
const errorId = useId() const errorId = useId()
return ( return (
<div className="relative flex flex-col gap-3"> <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 flex items-center min-w-[220px] sm:min-w-[360px] min-[1180px]:min-w-[420px] min-[1350px]:min-w-[480px]">
<input <input
ref={inputRef} ref={inputRef}
type="text" type="text"
@@ -32,27 +32,27 @@ function InputWithUnit({
value={value} value={value}
onChange={onChange} onChange={onChange}
onKeyDown={(e) => e.key === 'Enter' && onSubmit()} 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} placeholder={placeholder}
aria-label={ariaLabel} aria-label={ariaLabel}
aria-invalid={!!error} aria-invalid={!!error}
aria-describedby={error ? errorId : undefined} 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> <span className="opacity-0">{value}</span>
{value && <span className="ml-1">{unit}</span>} {value && <span className="ml-1">{unit}</span>}
</div> </div>
<button <button
type="button" type="button"
onClick={onSubmit} 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="전송" aria-label="전송"
> >
전송 전송
</button> </button>
</div> </div>
{error && ( {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"> <div id={errorId} role="alert" className="absolute top-[62px] left-1/2 -translate-x-1/2 text-sm font-semibold text-negative w-full text-center">
{error} {error}
</div> </div>
)} )}
@@ -160,6 +160,9 @@ export function useChatController(sessionId: string) {
useChatInitStore.getState().reset() useChatInitStore.getState().reset()
// init 은 진입 메타 캐시 — 비워 두어 재진입이 항상 최신 status 로 진입 게이트(1301)를 다시 타게 한다. // init 은 진입 메타 캐시 — 비워 두어 재진입이 항상 최신 status 로 진입 게이트(1301)를 다시 타게 한다.
queryClient.removeQueries({ queryKey: chatKeys.init(sessionId) }) queryClient.removeQueries({ queryKey: chatKeys.init(sessionId) })
// messages 는 staleTime:Infinity 라 캐시가 남으면 재진입해도 다시 안 부른다 —
// 오프닝 생성 전(협상생성 상태)에 받은 빈 목록이 눌러앉아 채팅이 빈 화면으로 굳는다.
queryClient.removeQueries({ queryKey: chatKeys.messages(sessionId) })
} }
}, [sessionId, sendMutate, navigate, queryClient]) }, [sessionId, sendMutate, navigate, queryClient])
@@ -29,6 +29,7 @@ const initialState: ChatInitData = {
item_spec: '', item_spec: '',
quotation_memo: '', quotation_memo: '',
quotation_end_time: '', quotation_end_time: '',
custom: {},
} }
export const useChatInitStore = create<ChatInitStore>((set) => ({ 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 }),
}))
+1
View File
@@ -81,4 +81,5 @@ export type ChatInitData = {
item_spec: string item_spec: string
quotation_memo: string quotation_memo: string
quotation_end_time: string quotation_end_time: string
custom: Record<string, unknown> // 협상완료 부가정보 기존 입력값(프리필용)
} }
@@ -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,115 @@
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 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
}
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">협상완료 부가정보</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">
{fields.length === 0 ? (
<p className="py-6 text-center text-sm text-neutral-60">입력할 부가정보 항목이 없습니다.</p>
) : (
fields.map((f) => (
<div key={f.key} className="space-y-1.5">
<label className="block text-sm font-semibold text-neutral-80">{f.label}</label>
{f.type === 'boolean' ? (
<button
type="button"
role="switch"
aria-checked={!!values[f.key]}
onClick={() => set(f.key, !values[f.key])}
className={`relative inline-flex h-6 w-11 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>
) : (
<input
type={f.type === 'number' ? 'number' : 'text'}
value={String(values[f.key] ?? '')}
onChange={(e) => set(f.key, e.target.value)}
className="h-11 w-full rounded-xl border border-border bg-white px-3 text-sm outline-none focus:border-brand-600 focus:ring-1 focus:ring-brand-600"
placeholder={f.label}
/>
)}
</div>
))
)}
</div>
<div className="flex gap-2 border-t border-border p-5">
<button
type="button"
onClick={onClose}
className="h-11 flex-1 rounded-xl border border-border text-sm font-bold text-neutral-70 hover:bg-neutral-10"
>
취소
</button>
<button
type="button"
onClick={handleSubmit}
disabled={fields.length === 0}
className="h-11 flex-1 rounded-xl bg-brand-600 text-sm font-bold text-white hover:bg-brand-700 disabled:opacity-40"
>
저장
</button>
</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,54 @@
import { AlertTriangle, CheckCircle2, FileText, RefreshCw } from 'lucide-react'
import { cn } from '@/lib'
import { useSessionCounts, type KpiCount } from '@/features/list/hooks/useSessionCounts'
// key → 아이콘/색 스타일 (콕핏 카드)
const STYLE: Record<string, { icon: typeof FileText; tile: string; iconColor: string; spin?: boolean }> = {
created: { icon: FileText, tile: 'bg-brand-light', iconColor: 'text-brand-600' },
progress: { icon: RefreshCw, tile: 'bg-sky-50', iconColor: 'text-sky-500', spin: true },
done: { icon: CheckCircle2, tile: 'bg-emerald-50', iconColor: 'text-success' },
rejected: { icon: AlertTriangle, tile: 'bg-red-50', iconColor: 'text-[#FF4D4F]' },
}
interface KpiCardsProps {
selectedStatus: string | null
onSelect: (status: string) => void
}
export function KpiCards({ selectedStatus, onSelect }: KpiCardsProps) {
const counts = useSessionCounts()
return (
<div className="grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-4">
{counts.map((c) => (
<Card key={c.key} data={c} active={selectedStatus === c.status} onClick={() => onSelect(c.status)} />
))}
</div>
)
}
function Card({ data, active, onClick }: { data: KpiCount; active: boolean; onClick: () => void }) {
const s = STYLE[data.key]
const Icon = s.icon
return (
<button
type="button"
onClick={onClick}
className={cn(
'flex items-center gap-3.5 rounded-2xl border bg-white p-4 text-left transition-all sm:p-5',
'hover:shadow-md active:scale-[0.99]',
active ? 'border-brand-600 ring-2 ring-brand-600/10 shadow-sm' : 'border-border shadow-sm',
)}
>
<div className={cn('flex size-10 shrink-0 items-center justify-center rounded-xl', s.tile)}>
<Icon className={cn('size-5', s.iconColor, s.spin && 'animate-spin-slow')} />
</div>
<div className="min-w-0">
<p className="truncate text-[11px] font-bold text-neutral-60">{data.label}</p>
<p className="text-lg font-extrabold tabular-nums text-neutral-90">
{data.isLoading ? '–' : data.count.toLocaleString()}
<span className="ml-0.5 text-xs font-bold text-neutral-60">건</span>
</p>
</div>
</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 { buildPageItems } from '@/features/list/lib/pagination'
import { ArrowIcon, DotsIcon } from '@/features/list/components/paginationIcons'
interface PaginationProps { interface PaginationProps {
totalPages: number totalPages: number
@@ -9,82 +9,41 @@ interface PaginationProps {
} }
export function Pagination({ totalPages, currentPage, onPageChange }: PaginationProps) { export function Pagination({ totalPages, currentPage, onPageChange }: PaginationProps) {
if (totalPages === 0) { if (totalPages <= 1) return null
return <div className="w-full my-[35px] h-[50px]" />
}
const items = buildPageItems(currentPage, totalPages) const items = buildPageItems(currentPage, totalPages)
return ( return (
<div className="flex w-full my-[35px]"> <div className="flex items-center justify-center gap-1.5 py-1">
<div className="flex w-full h-[50px] items-center justify-center gap-3"> <NavButton dir="prev" enabled={currentPage > 1} onClick={() => onPageChange(currentPage - 1)} />
<NavButton {items.map((item, idx) =>
dir="prev" item === 'dots' ? (
enabled={currentPage > 1} <span key={`dots-${idx}`} className="px-1 text-sm text-neutral-50 select-none">
onClick={() => onPageChange(currentPage - 1)} …
/> </span>
) : (
<div className="flex items-center justify-center h-full rounded-[999px] border border-neutral-30 bg-neutral-00"> <button
<div className="flex items-center justify-center gap-1 h-[38px]"> key={item}
{items.map((item, idx) => type="button"
item === 'dots' ? ( onClick={item === currentPage ? undefined : () => onPageChange(item)}
<DotsIcon key={`dots-${idx}`} /> className={cn(
) : ( 'flex size-9 items-center justify-center rounded-lg text-sm font-semibold tabular-nums transition-all',
<PageNumber item === currentPage
key={item} ? 'bg-brand-600 text-white shadow-sm cursor-default'
page={item} : 'text-neutral-70 hover:bg-neutral-10 active:scale-[0.96]',
active={item === currentPage}
onClick={() => onPageChange(item)}
/>
),
)} )}
</div> >
</div> {item}
</button>
<NavButton ),
dir="next" )}
enabled={currentPage < totalPages} <NavButton dir="next" enabled={currentPage < totalPages} onClick={() => onPageChange(currentPage + 1)} />
onClick={() => onPageChange(currentPage + 1)}
/>
</div>
</div> </div>
) )
} }
function PageNumber({ function NavButton({ dir, enabled, onClick }: { dir: 'prev' | 'next'; enabled: boolean; onClick: () => void }) {
page, const Icon = dir === 'prev' ? ChevronLeft : ChevronRight
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
}) {
return ( return (
<button <button
type="button" type="button"
@@ -92,11 +51,11 @@ function NavButton({
disabled={!enabled} disabled={!enabled}
onClick={enabled ? onClick : undefined} onClick={enabled ? onClick : undefined}
className={cn( className={cn(
'flex items-center justify-center w-[50px] h-[50px] rounded-full border border-neutral-30 bg-neutral-00 select-none', 'flex size-9 items-center justify-center rounded-lg border border-border transition-all',
enabled ? cn('text-neutral-60', interactive) : 'text-neutral-40 cursor-default', 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> </button>
) )
} }
@@ -1,6 +1,7 @@
import { useState } from 'react' import { useState } from 'react'
import { X } from 'lucide-react'
import { Modal } from '@/components' import { Modal } from '@/components'
import { cn, interactive } from '@/lib' import { cn } from '@/lib'
const REASONS = ['단종', '품절', '기타'] as const const REASONS = ['단종', '품절', '기타'] as const
@@ -36,88 +37,87 @@ export function RejectPopup({ onClose, onSubmit }: RejectPopupProps) {
return return
} }
if (isSubmitDisabled || !selectedReason) return if (isSubmitDisabled || !selectedReason) return
onSubmit(isEtcOpen ? customReason.trim() : selectedReason)
const reason = isEtcOpen ? customReason.trim() : selectedReason
onSubmit(reason)
onClose() onClose()
} }
return ( return (
<Modal onClose={onClose}> <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"> <div className="flex items-center justify-between border-b border-border p-5">
거부 사유를 입력해주세요 <h3 className="text-base font-bold text-neutral-90">거부 사유를 입력해주세요</h3>
</p> <button
type="button"
{/* 사유 선택 */} onClick={onClose}
<div className={cn('flex gap-5 transition-all duration-300 ease-out', isEtcOpen ? 'mt-0' : 'mt-12')}> aria-label="닫기"
{REASONS.map((reason) => ( className="flex size-8 items-center justify-center rounded-full text-neutral-60 hover:bg-neutral-10"
<button >
key={reason} <X className="size-4" />
type="button" </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> </div>
{/* 기타 입력 + 에러 */} {/* 본문 */}
<div className="flex flex-col items-center"> <div className="space-y-4 p-5">
<div <div className="grid grid-cols-3 gap-2">
className={cn( {REASONS.map((reason) => (
'flex w-[400px] overflow-hidden transition-all duration-300 ease-out', <button
isEtcOpen ? 'visible h-[120px] opacity-100' : 'invisible h-0 opacity-0', key={reason}
)} type="button"
> onClick={() => handleReasonClick(reason)}
<textarea className={cn(
placeholder="사유를 입력하여 주십시오" 'h-11 rounded-xl border text-sm font-bold transition-all active:scale-[0.98]',
value={customReason} selectedReason === reason
onChange={(e) => { ? 'border-brand-600 bg-brand-light text-brand-600'
setCustomReason(e.target.value) : 'border-border bg-white text-neutral-70 hover:bg-neutral-10',
setShowError(false) )}
}} >
className={cn( {reason}
'h-full w-full resize-none rounded-lg bg-background p-2.5 body-3 text-foreground', </button>
'placeholder:text-muted-foreground focus:outline-none', ))}
'transition-colors duration-200',
showError ? 'border-2 border-destructive' : 'border border-foreground',
)}
/>
</div> </div>
{/* 에러 메시지 (항상 공간 확보) */} {isEtcOpen && (
<div <div className="animate-fade-in">
className={cn( <textarea
'w-[400px] overflow-hidden transition-all duration-300 ease-out', placeholder="사유를 입력하여 주십시오"
showError && isEtcOpen ? 'mt-2 h-[24px] opacity-100' : 'h-0 opacity-0', value={customReason}
)} onChange={(e) => {
> setCustomReason(e.target.value)
<p className="text-left body-5 text-destructive">기타 사유를 입력해주세요</p> setShowError(false)
</div> }}
</div> rows={3}
className={cn(
{/* 전송 */} 'w-full resize-none rounded-xl border bg-white p-3 text-sm text-neutral-90 outline-none transition-all',
<button 'placeholder:text-neutral-50 focus:ring-1',
type="button" showError
onClick={handleSubmit} ? 'border-destructive focus:border-destructive focus:ring-destructive'
disabled={isSubmitDisabled} : 'border-border focus:border-brand-600 focus:ring-brand-600',
className={cn( )}
'flex h-[50px] w-full max-w-[130px] items-center justify-center rounded-full px-8 title-2', />
'bg-foreground text-background', {showError && <p className="mt-1.5 text-xs font-medium text-destructive">기타 사유를 입력해주세요</p>}
interactive, </div>
isSubmitDisabled && 'cursor-not-allowed opacity-40',
)} )}
> </div>
전송
</button> {/* 푸터 */}
<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> </div>
</Modal> </Modal>
) )
@@ -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 rounded-xl bg-neutral-20 p-1">
{TABS.map((t) => {
const active = selected === t.value
return (
<button
key={t.label}
type="button"
onClick={() => onSelect(t.value)}
className={cn(
'rounded-lg px-3.5 py-1.5 text-[13px] font-bold transition-all active:scale-[0.98]',
active ? 'bg-white text-neutral-90 shadow-sm' : 'text-neutral-60 hover:text-neutral-80',
)}
>
{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,116 @@
import { Loader2 } from 'lucide-react'
import { cn, formatKstDateTime } from '@/lib'
import type { ListItem } from '@/features/list/types'
import { statusMeta } 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
}
// 모바일(lg 미만) 협상 목록: 테이블 대신 카드 스택.
export function WorkspaceCards({ items, isLoading, busyId, onEnter, onReject, onExtraInfo }: 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} />
))}
</div>
)
}
function Card({
item,
busy,
onEnter,
onReject,
onExtraInfo,
}: {
item: ListItem
busy: boolean
onEnter: (item: ListItem) => void
onReject: (item: ListItem) => void
onExtraInfo: (item: ListItem) => void
}) {
const meta = statusMeta(item.session_status)
const canEnter = !['미참여', '협상거부'].includes(item.session_status)
const canReject = ['협상생성', '협상중'].includes(item.session_status)
const isDone = item.session_status === '협상완료'
const enterLabel = isDone ? '결과 보기' : '협상 입장'
const hasExtra = item.custom && Object.keys(item.custom).length > 0
return (
<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>
<span className={cn('inline-flex shrink-0 items-center gap-1 rounded-full px-2.5 py-1 text-xs font-bold', meta.badge)}>
<span className={cn('size-1.5 rounded-full', meta.dot)} />
{meta.display}
</span>
</div>
<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>
{(canEnter || canReject || isDone) && (
<div className="mt-3 flex gap-2">
{isDone && (
<button
type="button"
onClick={() => onExtraInfo(item)}
className="flex-1 rounded-lg border border-brand-600/40 py-2 text-xs font-bold text-brand-700 transition-all hover:bg-brand-50 active:scale-[0.98]"
>
{hasExtra ? '부가정보 수정' : '부가정보 입력'}
</button>
)}
{canReject && (
<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,140 @@
import { type ReactNode } from 'react'
import { Loader2 } from 'lucide-react'
import { cn, formatKstDateTime } from '@/lib'
import type { ListItem } from '@/features/list/types'
import { statusMeta } 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
}
const HEAD = 'px-5 py-3.5 text-left text-[11px] font-bold uppercase tracking-wider text-neutral-60 whitespace-nowrap'
const CELL = 'px-5 py-4 align-middle text-sm text-neutral-80'
export function WorkspaceTable({ items, isLoading, busyId, onEnter, onReject, onExtraInfo }: WorkspaceTableProps) {
return (
<div className="w-full overflow-x-auto">
<table className="w-full min-w-[900px] border-collapse">
<thead>
<tr className="border-b border-border bg-table-header">
<th className={HEAD}>견적번호</th>
<th className={HEAD}>상품</th>
<th className={HEAD}>제조사</th>
<th className={cn(HEAD, 'text-center')}>상태</th>
<th className={HEAD}>마감일</th>
<th className={cn(HEAD, 'text-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} />
))
)}
</tbody>
</table>
</div>
)
}
function Row({
item,
busy,
onEnter,
onReject,
onExtraInfo,
}: {
item: ListItem
busy: boolean
onEnter: (item: ListItem) => void
onReject: (item: ListItem) => void
onExtraInfo: (item: ListItem) => void
}) {
const meta = statusMeta(item.session_status)
const canEnter = !['미참여', '협상거부'].includes(item.session_status)
const canReject = ['협상생성', '협상중'].includes(item.session_status)
const isDone = item.session_status === '협상완료'
const enterLabel = isDone ? '결과 보기' : '협상 입장'
const hasExtra = item.custom && Object.keys(item.custom).length > 0
return (
<tr className="border-b border-border/60 transition-colors last:border-0 hover:bg-table-hover/70">
<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-center')}>
<span className={cn('inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-bold', meta.badge)}>
<span className={cn('size-1.5 rounded-full', meta.dot)} />
{meta.display}
</span>
</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">
{isDone && (
<button
type="button"
onClick={() => onExtraInfo(item)}
className="rounded-lg border border-brand-600/40 px-3 py-1.5 text-xs font-bold text-brand-700 transition-all hover:bg-brand-50 active:scale-[0.98]"
>
{hasExtra ? '부가정보 수정' : '부가정보 입력'}
</button>
)}
{canReject && (
<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>
) : (
!canReject && <span className="text-xs text-neutral-50">–</span>
)}
</div>
</td>
</tr>
)
}
function StateRow({ children }: { children: ReactNode }) {
return (
<tr>
<td colSpan={6} 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,161 @@
import { useState } from 'react'
import { useNavigate } from 'react-router'
import { useShallow } from 'zustand/react/shallow'
import { Search } from 'lucide-react'
import { getApiErrorMessage, useMeQuery, useParticipateMutation, useRejectMutation, useSaveExtraInfoMutation } from '@/apis'
import { 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 { 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 type { ListItem } from '@/features/list/types'
// 상태별 거부 불가 안내
const REJECT_BLOCKED: Record<string, string> = {
미참여: '미참여 상태인 협상은 거부할 수 없습니다.',
협상거부: '협상거부 상태인 협상은 거부할 수 없습니다.',
협상완료: '협상완료 상태인 협상은 거부할 수 없습니다.',
}
export function ListWorkspace() {
const navigate = useNavigate()
const { data: user } = useMeQuery()
// 리스트는 서버 페이징. (검색은 백엔드 미지원 → 프론트 검색은 비워 둠)
const { items, isLoading, totalPages, currentPage, setCurrentPage } = useList()
const participate = useParticipateMutation()
const reject = useRejectMutation()
const saveExtra = useSaveExtraInfoMutation()
const { selectedStatus, setStatus } = useListStore(
useShallow((s) => ({
selectedStatus: s.selectedStatus,
setStatus: s.setStatus,
})),
)
const [search, setSearch] = useState('')
const [enteringId, setEnteringId] = useState<string | null>(null)
const [rejectTarget, setRejectTarget] = useState<ListItem | null>(null)
const [extraTarget, setExtraTarget] = useState<ListItem | null>(null)
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, '부가정보 저장에 실패했습니다.')),
},
)
}
return (
<div className="space-y-5">
{/* 환영 배너 */}
<div className="flex flex-wrap items-center justify-between gap-2 rounded-2xl border border-border bg-white px-5 py-4 shadow-[0_2px_12px_rgba(0,0,0,0.02)]">
<div>
<p className="text-[15px] font-bold text-neutral-90">
{user?.supplierName ? `${user.supplierName} 담당자님, 환영합니다.` : '공급 파트너님, 환영합니다.'}
</p>
<p className="mt-0.5 text-xs text-neutral-60">
진행 중인 협상 건을 확인하고 가격 협상에 참여해 주세요.
</p>
</div>
</div>
{/* KPI 콕핏 */}
<KpiCards selectedStatus={selectedStatus} onSelect={(s) => setStatus(selectedStatus === s ? null : s)} />
{/* 워크스페이스 카드 */}
<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">
<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}
/>
</div>
<div className="lg:hidden">
<WorkspaceCards
items={items}
isLoading={isLoading}
busyId={participate.isPending ? enteringId : null}
onEnter={handleEnter}
onReject={handleReject}
onExtraInfo={setExtraTarget}
/>
</div>
<div className="border-t border-border px-4 py-3">
<Pagination totalPages={totalPages} currentPage={currentPage} onPageChange={setCurrentPage} />
</div>
</div>
{rejectTarget && (
<RejectPopup onClose={() => setRejectTarget(null)} onSubmit={handleRejectSubmit} />
)}
{extraTarget && (
<ExtraInfoPopup target={extraTarget} onClose={() => setExtraTarget(null)} onSubmit={handleExtraSubmit} />
)}
</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: ['남은 시간 적은 순', '남은 시간 긴 순'] },
]
+5 -32
View File
@@ -1,50 +1,23 @@
import { useMemo, useState } from 'react' import { useMemo } from 'react'
import { useSessionListQuery } from '@/apis' import { useSessionListQuery } from '@/apis'
import { useListStore } from '@/features/list/stores/useListStore' import { useListStore } from '@/features/list/stores/useListStore'
import { import { deadlineToOrder, statusLabelToCode, toListItem } from '@/features/list/lib/adapter'
deadlineToOrder,
statusLabelToCode,
toListItem,
typeLabelToCode,
} from '@/features/list/lib/adapter'
import type { ListItem } from '@/features/list/types'
const PAGE_SIZE = 20 const PAGE_SIZE = 20
// 필터/정렬/페이지는 서버에 위임하고, 응답(정수 코드)을 화면용 라벨로 변환한다. // 필터/정렬/페이지는 서버에 위임하고, 응답(정수 코드)을 화면용 라벨로 변환한다.
export function useList() { export function useList() {
const { selectedType, selectedStatus, selectedDeadline, currentPage, setCurrentPage } = const { selectedStatus, selectedDeadline, currentPage, setCurrentPage } = useListStore()
useListStore()
const [selectedId, setSelectedId] = useState<string | null>(null)
const query = useSessionListQuery({ const query = useSessionListQuery({
status: selectedStatus ? statusLabelToCode(selectedStatus) : undefined, status: selectedStatus ? statusLabelToCode(selectedStatus) : undefined,
qt_type: selectedType ? typeLabelToCode(selectedType) : undefined,
order: selectedDeadline ? deadlineToOrder(selectedDeadline) : undefined, order: selectedDeadline ? deadlineToOrder(selectedDeadline) : undefined,
page: currentPage, page: currentPage,
page_size: PAGE_SIZE, page_size: PAGE_SIZE,
}) })
const items = useMemo(() => (query.data?.items ?? []).map(toListItem), [query.data]) const items = useMemo(() => (query.data?.items ?? []).map(toListItem), [query.data])
const total = query.data?.total ?? 0 const totalPages = Math.max(1, Math.ceil((query.data?.total ?? 0) / PAGE_SIZE))
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
const selectedItem = useMemo( return { items, isLoading: query.isLoading, totalPages, currentPage, setCurrentPage }
() => items.find((item) => item.session_id === selectedId) ?? null,
[items, selectedId],
)
const handleItemClick = (item: ListItem) =>
setSelectedId((prev) => (prev === item.session_id ? null : item.session_id))
return {
items,
isLoading: query.isLoading,
totalPages,
currentPage,
setCurrentPage,
selectedId,
selectedItem,
handleItemClick,
}
} }
@@ -0,0 +1,35 @@
import { useQueries } from '@tanstack/react-query'
import { negotiationApi, negotiationKeys, SessionStatus } from '@/apis'
// KPI 콕핏에 노출할 상태별 집계. 각 상태를 page_size=1 로 조회해 total 만 읽는다(목록과 캐시 공유).
export interface KpiCount {
key: string
label: string
status: string // 클릭 시 필터에 넣을 원본 상태 라벨
code: number
count: number
isLoading: boolean
}
const KPI = [
{ key: 'created', label: '협상 대기', status: '협상생성', code: SessionStatus.CREATED },
{ key: 'progress', label: '조율 진행중', status: '협상중', code: SessionStatus.IN_PROGRESS },
{ key: 'done', label: '타결 완료', status: '협상완료', code: SessionStatus.DONE },
{ key: 'rejected', label: '거부/반려', status: '협상거부', code: SessionStatus.REJECTED },
] as const
export function useSessionCounts(): KpiCount[] {
const results = useQueries({
queries: KPI.map((k) => ({
queryKey: negotiationKeys.sessionList({ status: k.code, page: 1, page_size: 1 }),
queryFn: () => negotiationApi.getSessions({ status: k.code, page: 1, page_size: 1 }),
staleTime: 60 * 1000,
})),
})
return KPI.map((k, i) => ({
...k,
count: results[i].data?.total ?? 0,
isLoading: results[i].isLoading,
}))
}
+1 -2
View File
@@ -1,3 +1,2 @@
// 공개 API (페이지에서 쓰는 것만) // 공개 API (페이지에서 쓰는 것만)
export { FilterContainer } from '@/features/list/containers/FilterContainer' export { ListWorkspace } from '@/features/list/containers/ListWorkspace'
export { ContentContainer } from '@/features/list/containers/ContentContainer'
@@ -37,5 +37,6 @@ export function toListItem(api: SessionListItem): ListItem {
item_name: api.item_name, item_name: api.item_name,
model_name: api.model_name, model_name: api.model_name,
maker_name: api.maker_name, maker_name: api.maker_name,
custom: api.custom ?? {},
} }
} }
@@ -1,6 +0,0 @@
import { formatKstDateTime } from '@/lib'
// 'YYYY-MM-DD HH:mm' (KST 고정). 백엔드 UTC 직렬화를 한국 시간으로 표시한다.
export function formatDateTime(value: string): string {
return formatKstDateTime(value)
}
+19
View File
@@ -0,0 +1,19 @@
// 세션 상태(원본 라벨) → 포털 표시 라벨 + 배지 스타일.
// 원본 라벨은 apis 의 SESSION_STATUS_LABEL(협상생성/협상중/협상완료/미참여/협상거부)과 일치한다.
export interface StatusMeta {
display: string
badge: string // 배지 배경/글자색
dot: string // 상태 점 색
}
export const STATUS_META: Record<string, StatusMeta> = {
협상생성: { display: '대기', badge: 'bg-brand-light text-brand-600', dot: 'bg-brand-600' },
협상중: { display: '조율중', badge: 'bg-[#FFF3E5] text-[#F5A623]', dot: 'bg-[#F5A623]' },
협상완료: { display: '타결', badge: 'bg-[#EAFDF3] text-success', dot: 'bg-success' },
미참여: { display: '미참여', badge: 'bg-neutral-20 text-neutral-60', dot: 'bg-neutral-60' },
협상거부: { display: '거부', badge: 'bg-[#FFEBEB] text-[#FF4D4F]', dot: 'bg-[#FF4D4F]' },
}
export function statusMeta(label: string): StatusMeta {
return STATUS_META[label] ?? { display: label || '-', badge: 'bg-neutral-20 text-neutral-60', dot: 'bg-neutral-60' }
}
@@ -7,7 +7,9 @@ interface ListState {
currentPage: number currentPage: number
toggleType: (item: string) => void toggleType: (item: string) => void
setType: (item: string | null) => void
toggleStatus: (item: string) => void toggleStatus: (item: string) => void
setStatus: (item: string | null) => void
toggleDeadline: (item: string) => void toggleDeadline: (item: string) => void
setCurrentPage: (page: number) => void setCurrentPage: (page: number) => void
resetFilters: () => void resetFilters: () => void
@@ -23,8 +25,10 @@ export const useListStore = create<ListState>((set) => ({
toggleType: (item) => toggleType: (item) =>
set((s) => ({ selectedType: toggle(s.selectedType, item), currentPage: 1 })), set((s) => ({ selectedType: toggle(s.selectedType, item), currentPage: 1 })),
setType: (item) => set({ selectedType: item, currentPage: 1 }),
toggleStatus: (item) => toggleStatus: (item) =>
set((s) => ({ selectedStatus: toggle(s.selectedStatus, item), currentPage: 1 })), set((s) => ({ selectedStatus: toggle(s.selectedStatus, item), currentPage: 1 })),
setStatus: (item) => set({ selectedStatus: item, currentPage: 1 }),
toggleDeadline: (item) => toggleDeadline: (item) =>
set((s) => ({ selectedDeadline: toggle(s.selectedDeadline, item), currentPage: 1 })), set((s) => ({ selectedDeadline: toggle(s.selectedDeadline, item), currentPage: 1 })),
setCurrentPage: (page) => set({ currentPage: page }), setCurrentPage: (page) => set({ currentPage: page }),
+1
View File
@@ -8,4 +8,5 @@ export type ListItem = {
item_name: string item_name: string
model_name: string model_name: string
maker_name: string maker_name: string
custom: Record<string, unknown> // 협상완료 부가정보(입력값). 미입력이면 {}
} }
+58 -21
View File
@@ -2,39 +2,41 @@
@import url('https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.css'); @import url('https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.css');
@import "tailwindcss"; @import "tailwindcss";
/* 디자인 토큰 (light 전용) */ /* 디자인 토큰 (light 전용) — 토스풍(Toss) 팔레트 */
:root { :root {
color-scheme: light; color-scheme: light;
--radius: 0.625rem; /* 10px 기준 */ --radius: 0.75rem; /* 12px 기준 (토스풍 라운드) */
/* 브랜드 */ /* 브랜드 (Toss blue) */
--brand-500: #5a83c1; --brand-500: #6098f5; /* ring / 보조 */
--brand-600: #254d8b; /* = --primary */ --brand-600: #3182f6; /* = --primary */
--brand-700: #1b3965; --brand-700: #1b64da; /* hover / pressed */
--brand-light: #e8f3ff; /* 연한 브랜드 배경 (선택행·AI 말풍선) */
/* Neutral */ /* Neutral (cool gray) */
--neutral-90: #151515; --neutral-90: #191f28; /* text-primary */
--neutral-80: #303030; --neutral-80: #333d4b;
--neutral-70: #606060; --neutral-70: #4e5968; /* text-secondary */
--neutral-60: #808080; --neutral-60: #8b95a1; /* text-caption */
--neutral-40: #dadbde; --neutral-50: #b0b8c1; /* placeholder */
--neutral-30: #eaebef; --neutral-40: #d1d6db;
--neutral-20: #f0f1f4; --neutral-30: #e5e8eb; /* border-card */
--neutral-10: #f7f8fa; --neutral-20: #f2f4f6; /* bg-gray */
--neutral-10: #f9fafb; /* bg-section */
--neutral-00: #ffffff; --neutral-00: #ffffff;
/* 상태 / 테이블 */ /* 상태 / 테이블 */
--negative: #e71c3b; --negative: #e71c3b;
--info: #4880ef; --info: #3182f6;
--table-header: #e3e8f1; --table-header: #f8f9fa;
--table-hover: #dbe6fc; --table-hover: #f2f4f6;
--table-selected: #b6ccf9; --table-selected: var(--brand-light);
/* 시맨틱 */ /* 시맨틱 */
--background: var(--neutral-00); --background: var(--neutral-00);
--foreground: var(--neutral-90); --foreground: var(--neutral-90);
--surface: #eef0f4; /* 중립 라이트 그레이 (콘텐츠 면, 블루기 최소) */ --surface: #f9fafb; /* 콘텐츠 면 (토스 섹션 배경) */
--card: var(--neutral-00); --card: var(--neutral-00);
--card-foreground: var(--neutral-90); --card-foreground: var(--neutral-90);
@@ -55,7 +57,7 @@
--ring: var(--brand-500); --ring: var(--brand-500);
--destructive: var(--negative); --destructive: var(--negative);
--success: #10b981; --success: #0b8f57;
--warning: #f59e0b; --warning: #f59e0b;
} }
@@ -65,12 +67,14 @@
--color-brand-500: var(--brand-500); --color-brand-500: var(--brand-500);
--color-brand-600: var(--brand-600); --color-brand-600: var(--brand-600);
--color-brand-700: var(--brand-700); --color-brand-700: var(--brand-700);
--color-brand-light: var(--brand-light);
/* Neutral */ /* Neutral */
--color-neutral-90: var(--neutral-90); --color-neutral-90: var(--neutral-90);
--color-neutral-80: var(--neutral-80); --color-neutral-80: var(--neutral-80);
--color-neutral-70: var(--neutral-70); --color-neutral-70: var(--neutral-70);
--color-neutral-60: var(--neutral-60); --color-neutral-60: var(--neutral-60);
--color-neutral-50: var(--neutral-50);
--color-neutral-40: var(--neutral-40); --color-neutral-40: var(--neutral-40);
--color-neutral-30: var(--neutral-30); --color-neutral-30: var(--neutral-30);
--color-neutral-20: var(--neutral-20); --color-neutral-20: var(--neutral-20);
@@ -120,6 +124,28 @@
--radius-2xl: calc(var(--radius) * 1.8); /* 18px */ --radius-2xl: calc(var(--radius) * 1.8); /* 18px */
--radius-3xl: calc(var(--radius) * 2.2); /* 22px */ --radius-3xl: calc(var(--radius) * 2.2); /* 22px */
--radius-4xl: calc(var(--radius) * 2.6); /* 26px */ --radius-4xl: calc(var(--radius) * 2.6); /* 26px */
/* 애니메이션 (토스풍 미세 전환) */
--animate-fade-in: fadeIn 0.2s ease-out forwards;
--animate-scale-in: scaleIn 0.2s cubic-bezier(0.16, 1, 0.3, 1) forwards;
--animate-spin-slow: spin 8s linear infinite;
--animate-pulse-slow: pulseSlow 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes scaleIn {
from { opacity: 0; transform: scale(0.98); }
to { opacity: 1; transform: scale(1); }
}
@keyframes pulseSlow {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.9; transform: scale(1.015); }
}
@keyframes spin {
to { transform: rotate(360deg); }
} }
@layer base { @layer base {
@@ -136,6 +162,17 @@
} }
} }
/* 노치/홈 인디케이터 회피 (viewport-fit=cover 와 짝). 안전영역이 0 인 기기에선 아무 영향 없다.
화면 맨 위/맨 아래에 붙는 바에만 붙인다 — 스크롤되는 본문에는 쓰지 않는다. */
@layer components {
.safe-t { padding-top: env(safe-area-inset-top); }
.safe-b { padding-bottom: env(safe-area-inset-bottom); }
.safe-x {
padding-left: env(safe-area-inset-left);
padding-right: env(safe-area-inset-right);
}
}
/* 타이포그래피 스케일 (headline / title / body / reject) */ /* 타이포그래피 스케일 (headline / title / body / reject) */
@layer components { @layer components {
.headline-3 { font-size: 24px; font-weight: 700; line-height: 30px; letter-spacing: -0.48px; } .headline-3 { font-size: 24px; font-weight: 700; line-height: 30px; letter-spacing: -0.48px; }
+4 -1
View File
@@ -1,8 +1,11 @@
import { type ReactNode } from 'react' import { type ReactNode } from 'react'
import { cn } from '@/lib' import { cn } from '@/lib'
// safe-t: 노치 기기에서 헤더가 상태바 밑으로 파고들지 않도록 안전영역만큼 키운다.
// box-content 금지 — w-full + px-* 와 겹치면 폭이 "부모100% + 좌우패딩"이 되어 오른쪽이 잘린다.
// 대신 border-box(기본) 유지하고 min-h 로 56px + 안전영역을 확보한다.
const HEADER_BASE = const HEADER_BASE =
'flex w-full h-[56px] py-[18px] items-center rounded-t-[8px] bg-primary text-primary-foreground' 'flex w-full min-h-[calc(56px+env(safe-area-inset-top))] safe-t items-center bg-white text-foreground border-b border-border'
const HEADER_ALIGN = { const HEADER_ALIGN = {
left: 'justify-start', left: 'justify-start',
+15 -10
View File
@@ -1,5 +1,6 @@
import { type ReactNode } from 'react' import { type ReactNode } from 'react'
import { Logo } from '@/components' import { Logo } from '@/components'
import { useMeQuery } from '@/apis'
import { cn } from '@/lib' import { cn } from '@/lib'
// 좌측 폭: list=반응형 비율 / chat=고정폭 단계 축소 // 좌측 폭: list=반응형 비율 / chat=고정폭 단계 축소
@@ -8,19 +9,19 @@ const SIDEBAR_WIDTH = {
'w-[20%] max-w-[320px] ' + 'w-[20%] max-w-[320px] ' +
'max-[1520px]:w-[23%] max-[1410px]:w-[25%] ' + 'max-[1520px]:w-[23%] max-[1410px]:w-[25%] ' +
'max-[1180px]:w-[27%] max-[1024px]:w-[29%] max-[960px]:w-[33%]', 'max-[1180px]:w-[27%] max-[1024px]:w-[29%] max-[960px]:w-[33%]',
chat: 'w-[350px] max-[1350px]:w-[310px] max-[1180px]:w-[280px]', chat: 'w-[300px] max-[1350px]:w-[284px] max-[1180px]:w-[260px]',
} as const } as const
const styles = { const styles = {
root: 'flex w-full min-h-screen max-h-screen bg-background', root: 'flex w-full min-h-[100dvh] max-h-[100dvh] bg-background safe-x',
scrollX: 'flex w-full min-h-screen max-h-screen overflow-x-auto overflow-y-hidden', scrollX: 'flex w-full min-h-[100dvh] max-h-[100dvh] overflow-x-auto overflow-y-hidden safe-x',
scrollXInner: 'flex w-full min-h-screen max-h-screen min-w-[1024px] bg-background', scrollXInner: 'flex w-full min-h-[100dvh] max-h-[100dvh] min-w-[1024px] bg-background',
sidebar: 'flex flex-col h-screen pt-2 bg-background', // 좌측 레일은 lg 미만에서 숨기고(드로어로 대체), main 이 전체 폭을 차지한다. 보고서식 풀블리드 + 경계선.
sidebar: 'hidden lg:flex flex-col h-[100dvh] bg-white border-r border-border',
logoHeader: logoHeader:
'flex w-full h-[56px] pl-[32px] pr-[24px] py-[8px] items-center justify-between shrink-0', 'flex w-full h-[56px] pl-[24px] pr-[16px] items-center justify-between shrink-0 border-b border-border',
main: 'flex flex-1 flex-col h-screen overflow-hidden pt-2 pr-2 pb-2 pl-0', main: 'flex flex-1 flex-col h-[100dvh] overflow-hidden',
// 다크 헤더와 합쳐져 카드 형태 content: 'flex flex-1 flex-col min-h-0 w-full overflow-hidden bg-surface',
content: 'flex flex-1 flex-col min-h-0 w-full overflow-hidden rounded-b-[8px] bg-surface',
} as const } as const
export type SidebarWidth = keyof typeof SIDEBAR_WIDTH export type SidebarWidth = keyof typeof SIDEBAR_WIDTH
@@ -43,14 +44,18 @@ export function MainLayout({
header, header,
children, children,
}: MainLayoutProps) { }: MainLayoutProps) {
const { data: user } = useMeQuery() // 회사 브랜딩(서비스명/로고) 주입
const panes = ( const panes = (
<> <>
<aside className={cn(styles.sidebar, SIDEBAR_WIDTH[sidebarWidth])}> <aside className={cn(styles.sidebar, SIDEBAR_WIDTH[sidebarWidth])}>
<div className={styles.logoHeader}> <div className={styles.logoHeader}>
<Logo size="sm" /> <Logo size="sm" serviceName={user?.branding?.service_name} logoUrl={user?.branding?.logo_url} />
{logoAction} {logoAction}
</div> </div>
{sidebar} {sidebar}
<p className="mt-auto px-4 py-3 text-[10px] font-medium text-neutral-50">
© {new Date().getFullYear()} negotium · Made by AI O2O
</p>
</aside> </aside>
<main className={styles.main}> <main className={styles.main}>
+57
View File
@@ -0,0 +1,57 @@
import { useNavigate } from 'react-router'
import { Bell, LogOut } from 'lucide-react'
import { useLogoutMutation, useMeQuery } from '@/apis'
import { Logo } from '@/components'
import { cn, interactive } from '@/lib'
// 포털 상단 네비게이션 바 (목록 화면 전용).
export function PortalHeader() {
const navigate = useNavigate()
const { data: user } = useMeQuery()
const logout = useLogoutMutation()
const handleLogout = () =>
logout.mutate(undefined, { onSuccess: () => navigate('/') })
return (
<header className="sticky top-0 z-40 flex h-16 items-center justify-between border-b border-border bg-white/90 px-4 shadow-sm backdrop-blur sm:px-6">
<Logo size="md" serviceName={user?.branding?.service_name} logoUrl={user?.branding?.logo_url} />
<div className="flex items-center gap-2 sm:gap-3">
<button
type="button"
aria-label="알림"
className={cn(
'relative flex size-9 items-center justify-center rounded-xl text-neutral-70 hover:bg-neutral-10',
interactive,
)}
>
<Bell className="size-5" />
<span className="absolute right-2 top-2 size-1.5 rounded-full bg-brand-600" />
</button>
<div className="hidden min-w-0 flex-col items-end sm:flex">
<span className="max-w-[180px] truncate text-[13px] font-bold text-neutral-90">
{user?.supplierName ?? '-'}
</span>
<span className="text-[11px] text-neutral-60">{user?.name ?? '공급 파트너'}</span>
</div>
<button
type="button"
onClick={handleLogout}
disabled={logout.isPending}
className={cn(
'flex items-center gap-1.5 rounded-xl border border-border 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" />
<span className="hidden sm:inline">로그아웃</span>
</button>
</div>
</header>
)
}
export default PortalHeader
+6 -5
View File
@@ -6,15 +6,16 @@ type ToastOptions = ExternalToast
const baseStyle = { const baseStyle = {
fontFamily: 'var(--font-sans)', fontFamily: 'var(--font-sans)',
fontSize: '18px', fontSize: '14px',
fontWeight: 600, fontWeight: 600,
letterSpacing: '-0.28px', letterSpacing: '-0.28px',
borderRadius: '8px', borderRadius: '12px',
padding: '18px 24px', padding: '12px 16px',
backgroundColor: 'var(--neutral-00)', backgroundColor: 'var(--neutral-00)',
color: 'var(--neutral-90)', color: 'var(--neutral-90)',
boxShadow: '0px 4px 12px rgba(0, 0, 0, 0.08)', boxShadow: '0px 6px 20px rgba(0, 0, 0, 0.08)',
minWidth: '440px', width: 'auto',
maxWidth: '90vw',
wordBreak: 'keep-all' as const, wordBreak: 'keep-all' as const,
overflowWrap: 'break-word' as const, overflowWrap: 'break-word' as const,
whiteSpace: 'pre-wrap' as const, whiteSpace: 'pre-wrap' as const,
+78 -18
View File
@@ -1,44 +1,104 @@
import { type ReactNode } from 'react'
import { useNavigate, useSearchParams, Navigate } from 'react-router' import { useNavigate, useSearchParams, Navigate } from 'react-router'
import { List } from 'lucide-react' import { ArrowLeft, Package, ClipboardList } from 'lucide-react'
import { cn, interactive } from '@/lib' import { cn, interactive } from '@/lib'
import { MainLayout, MainHeaderBar } from '@/layouts' import { MainLayout, MainHeaderBar } from '@/layouts'
import { ChatContainer, ItemSection, RemainingTime } from '@/features/chat' import { ChatContainer, ItemSection, RemainingTime } from '@/features/chat'
import { MobileDrawer } from '@/features/chat/components/MobileDrawer'
import { MenuSection } from '@/features/chat/components/menu/MenuSection'
import { useChatUiStore } from '@/features/chat/stores/useChatUiStore'
import { SidebarFooter } from '@/features/auth' import { SidebarFooter } from '@/features/auth'
export function ChatPage() { export function ChatPage() {
const [searchParams] = useSearchParams() const [searchParams] = useSearchParams()
const sessionId = searchParams.get('session_id') ?? '' const sessionId = searchParams.get('session_id') ?? ''
const drawer = useChatUiStore((s) => s.drawer)
const close = useChatUiStore((s) => s.close)
// session_id 없이 진입하면 목록으로 되돌린다. // session_id 없이 진입하면 목록으로 되돌린다.
if (!sessionId) return <Navigate to="/list" replace /> if (!sessionId) return <Navigate to="/list" replace />
return ( return (
<MainLayout <>
sidebarWidth="chat" <MainLayout
scrollX sidebarWidth="chat"
logoAction={<ListNavButton />} sidebar={<Sidebar />}
sidebar={<Sidebar />} header={
header={ <MainHeaderBar className="px-4 sm:px-6 min-[1180px]:px-8">
<MainHeaderBar className="px-[140px] max-[1350px]:px-[80px] max-[1180px]:px-[48px]"> {/* min-w-0: flex 기본 min-width:auto 라 자식이 안 줄어들어 헤더 밖으로 넘치던 것 방지 */}
<RemainingTime /> <div className="flex w-full min-w-0 items-center justify-between gap-2">
</MainHeaderBar> <div className="flex min-w-0 shrink items-center gap-2">
} <BackToListButton />
> <span className="hidden h-4 w-px bg-border lg:inline-block" />
<ChatContainer sessionId={sessionId} /> <span className="hidden size-2 shrink-0 rounded-full bg-brand-600 animate-pulse lg:inline-block" />
</MainLayout> <span className="hidden truncate text-sm font-bold text-neutral-90 lg:inline">
실시간 구매 협상 채널
</span>
</div>
<div className="flex min-w-0 shrink items-center gap-1.5">
<PanelToggle icon={<Package className="size-4" />} label="상품" panel="product" />
<PanelToggle icon={<ClipboardList className="size-4" />} label="현황" panel="status" />
<RemainingTime />
</div>
</div>
</MainHeaderBar>
}
>
<ChatContainer sessionId={sessionId} />
</MainLayout>
{/* 모바일 드로어 (lg 미만) */}
<MobileDrawer open={drawer === 'product'} onClose={close} side="left" title="상품 정보">
<ItemSection />
<SidebarFooter />
</MobileDrawer>
<MobileDrawer open={drawer === 'status'} onClose={close} side="right" title="협상 현황">
<MenuSection variant="drawer" />
</MobileDrawer>
</>
) )
} }
function ListNavButton() { // 헤더 좌상단: 목록으로 돌아가기 (텍스트 + ← 아이콘)
function BackToListButton() {
const navigate = useNavigate() const navigate = useNavigate()
return ( return (
<button <button
type="button" type="button"
aria-label="목록으로 이동"
onClick={() => navigate('/list')} onClick={() => navigate('/list')}
className={cn('text-foreground', interactive)} className={cn(
'flex shrink-0 items-center gap-1.5 rounded-lg px-2 py-1.5 text-sm font-bold text-neutral-70 hover:bg-neutral-10',
interactive,
)}
> >
<List size={24} /> <ArrowLeft className="size-4" />
<span className="hidden sm:inline">목록으로 돌아가기</span>
</button>
)
}
// 헤더 우측: 상품/현황 패널 드로어 토글 (모바일 전용)
function PanelToggle({
icon,
label,
panel,
}: {
icon: ReactNode
label: string
panel: 'product' | 'status'
}) {
const open = useChatUiStore((s) => s.open)
return (
<button
type="button"
onClick={() => open(panel)}
className={cn(
'flex shrink-0 items-center gap-1 rounded-lg border border-border px-2 py-1.5 text-xs font-bold text-neutral-70 hover:bg-neutral-10 lg:hidden',
interactive,
)}
>
{icon}
<span className="hidden min-[480px]:inline">{label}</span>
</button> </button>
) )
} }
+14 -23
View File
@@ -1,29 +1,20 @@
import { MainLayout, MainHeaderBar } from '@/layouts' import { PortalHeader } from '@/layouts/PortalHeader'
import { FilterContainer, ContentContainer } from '@/features/list' import { ListWorkspace } from '@/features/list'
import { SidebarFooter } from '@/features/auth'
export function ListPage() { export function ListPage() {
return ( return (
<MainLayout <div className="flex min-h-svh flex-col bg-surface">
sidebarWidth="list" <PortalHeader />
sidebar={<Sidebar />} <main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6 sm:px-6">
header={ <ListWorkspace />
<MainHeaderBar align="center" className="px-[81px]"> </main>
<span className="text-xl font-bold whitespace-nowrap">견적 선택</span> {/* 솔루션·제작사 표기 — 회사 브랜딩(헤더 로고)과 무관하게 고정 */}
</MainHeaderBar> <footer className="border-t border-border px-4 py-4 text-center sm:px-6">
} <p className="text-[11px] font-medium text-neutral-50">
> © {new Date().getFullYear()} negotium · Made by AI O2O
<ContentContainer /> </p>
</MainLayout> </footer>
) </div>
}
function Sidebar() {
return (
<>
<FilterContainer />
<SidebarFooter />
</>
) )
} }
+28 -8
View File
@@ -1,25 +1,45 @@
import { Navigate } from 'react-router' import { Navigate } from 'react-router'
import { tokenStorage } from '@/apis' import { tokenStorage } from '@/apis'
import { Logo } from '@/components' import { Logo } from '@/components'
import { LoginForm } from '@/features/auth' import { LoginForm, usePreLoginBranding } from '@/features/auth'
export function LoginPage() { export function LoginPage() {
// 초청 링크의 session_id(없으면 직전 로그인 캐시)로 회사 브랜딩을 먼저 그린다.
const branding = usePreLoginBranding()
// 이미 로그인된 상태면 목록으로 // 이미 로그인된 상태면 목록으로
if (tokenStorage.hasToken()) { if (tokenStorage.hasToken()) {
return <Navigate to="/list" replace /> return <Navigate to="/list" replace />
} }
return ( return (
<main className="flex min-h-svh w-full items-center justify-center px-6"> <main className="flex min-h-svh w-full items-center justify-center bg-surface px-6">
<div className="flex w-full max-w-100 flex-col items-center gap-10"> <div className="flex w-full max-w-sm flex-col items-center gap-6">
<header className="flex flex-col items-center justify-center gap-4"> {/* 브랜드 락업 */}
<Logo size="md" /> <div className="flex flex-col items-center gap-2">
<h1 className="text-2xl font-bold leading-[30px] tracking-[-0.48px]"> <Logo size="lg" serviceName={branding?.service_name} logoUrl={branding?.logo_url} />
<p className="text-[13px] font-medium tracking-[-0.26px] text-neutral-60">
negotium B2B 구매협상 솔루션 · 공급사 포털
</p>
</div>
{/* 로그인 카드 */}
<div className="w-full rounded-2xl border border-border bg-white p-8 shadow-sm">
<h1 className="mb-6 text-center text-xl font-bold tracking-[-0.4px] text-neutral-90">
로그인 로그인
</h1> </h1>
</header> <LoginForm />
</div>
<LoginForm /> {/* 푸터 — 문의처 + 솔루션/제작사 표기(회사 브랜딩과 무관하게 고정) */}
<div className="flex flex-col items-center gap-1">
<p className="text-xs font-medium text-neutral-60">
문의: 헬프데스크 010-0000-0000 · o2odev@o2o.kr
</p>
<p className="text-[11px] font-medium text-neutral-50">
© {new Date().getFullYear()} negotium · Made by AI O2O
</p>
</div>
</div> </div>
</main> </main>
) )
+3
View File
@@ -0,0 +1,3 @@
node_modules
build
.react-router
+15
View File
@@ -0,0 +1,15 @@
# front 와 동일 구성 — Debian slim(glibc) 로 alpine(musl)+esbuild 의 ETXTBSY 회피.
FROM node:22-slim
WORKDIR /app
# 의존성 먼저 설치 (레이어 캐시)
COPY package.json package-lock.json ./
RUN npm install
COPY . .
EXPOSE 3100
# react-router dev — --host 0.0.0.0 로 컨테이너 외부 노출 (package.json scripts.dev)
CMD ["npm", "run", "dev"]
+88
View File
@@ -0,0 +1,88 @@
@import "tailwindcss";
/* Pretendard 가변폰트 self-host (public/fonts).
format 은 표준 'woff2' 고정 — 'woff2-variations' 는 윈도우 브라우저가 무시함. */
@font-face {
font-family: 'Pretendard Variable';
font-weight: 45 920;
font-style: normal;
font-display: swap;
src: url('/fonts/PretendardVariable.woff2') format('woff2');
}
/*
* 랜딩 디자인 토큰 (Toss 스타일 라이트 팔레트).
* 색은 전부 여기서만 정의하고, 컴포넌트는 토큰 클래스(text-ink, bg-primary …)만 쓴다.
*/
@theme {
--font-sans: 'Pretendard Variable', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Apple SD Gothic Neo", "Malgun Gothic", sans-serif;
--font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
/* 브랜드 */
--color-primary: #476EFF;
--color-primary-deep: #2F52E0; /* hover */
--color-primary-soft: #ECF0FF; /* 연한 파랑 배경 — 봇 말풍선, 배지 */
/* 텍스트. ink 는 다크 섹션에선 배경색으로도 쓴다 */
--color-ink: #191F28;
--color-ink-soft: #4E5968; /* 보조 본문 */
--color-ink-muted: #8B95A1; /* 캡션 */
--color-ink-faint: #B0B8C1; /* 플레이스홀더·각주 */
/* 면·선 */
--color-surface: #F9FAFB; /* 회색 섹션 배경 */
--color-surface-neu: #F2F4F7; /* 뉴모피즘 히어로 전용 배경 */
--color-fill: #F2F4F6; /* 회색 채움 — 탭 트랙, 보조 버튼 */
--color-fill-hover: #EAECEF;
--color-line: #F2F4F6; /* 섹션 구분선 */
--color-line-strong: #E5E8EB; /* 카드 테두리 */
--color-positive: #0B8F57; /* 낙찰·성공 강조 */
--color-positive-soft: #E8F7EF; /* 연한 초록 배경 — 낙찰 배지 */
--color-accent: #8F52FF; /* 보라 강조 — 결과 탭·히어로 장식 */
--color-accent-soft: #F4EFFF; /* 연한 보라 배경 */
}
html {
scroll-behavior: smooth;
background-color: #ffffff;
color: var(--color-ink);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
margin: 0;
}
/* 스크롤은 되지만 스크롤바는 숨김 (협상 콘솔 채팅 영역) */
.scrollbar-none::-webkit-scrollbar {
display: none;
}
.scrollbar-none {
-ms-overflow-style: none;
scrollbar-width: none;
}
/* 은은한 원형 글로우 장식 (히어로 배경) */
.mesh-bg {
position: absolute;
width: 1000px;
height: 1000px;
border-radius: 50%;
background: radial-gradient(circle, rgba(49, 130, 246, 0.08) 0%, rgba(255, 255, 255, 0) 70%);
filter: blur(100px);
pointer-events: none;
}
/* 노치/홈 인디케이터 회피 (viewport-fit=cover 와 짝). 안전영역이 0 인 기기에선 아무 영향 없다.
화면 맨 위/맨 아래에 붙는 바에만 붙인다 — 스크롤되는 본문에는 쓰지 않는다. */
@layer components {
.safe-t { padding-top: env(safe-area-inset-top); }
.safe-b { padding-bottom: env(safe-area-inset-bottom); }
.safe-x {
padding-left: env(safe-area-inset-left);
padding-right: env(safe-area-inset-right);
}
}
Loaded 100 of 308 files, more files were not shown because too many files have changed in this diff. Show more